text:
* Remove unused dependencies [#837](https://github.com/yesodweb/wai/pull/837)

## 3.1.5

* `Network.Wai.Middleware.RealIp`: Add a new middleware to infer the remote IP address from headers [#834](https://github.com/yesodweb/wai/pull/834)

## 3.1.4.1

* `Network.Wai.Middleware.Gzip`: Add `Vary: Accept-Encoding` header to responses [#829](https://github.com/yesodweb/wai/pull/829)

## 3.1.4

* Export `Network.Wai.Middleware.RequestLogger.JSON.requestToJSON` [#827](https://github.com/yesodweb/wai/pull/827)

## 3.1.3

* Add a `DetailedWithSettings` output format for `RequestLogger` that allows to hide requests and modify query parameters [#826](https://github.com/yesodweb/wai/pull/826)

## 3.1.2

* Remove an extraneous dot from the error message for `defaultRequestSizeLimitSettings`

## 3.1.1

* `Network.Wai.Middleware.RequestSizeLimit`: Add a new middleware to reject request bodies above a certain size. [#818](https://github.com/yesodweb/wai/pull/818/files)

## 3.1.0

* `Network.Wai.Test`: Add support for source locations to assertion primitives [#817](https://github.com/yesodweb/wai/pull/817)

## 3.0.32

* Undo previous two release, restore code from 3.0.29.2

## 3.0.31

* Undo WaiTestFailure change in previous release

## 3.0.30

* `Network.Wai.Test`: Add support for source locations to assertion primitives [#812](https://github.com/yesodweb/wai/pull/812)

## 3.0.29.2

* flush SSE headers early [#804](https://github.com/yesodweb/wai/pull/804)

## 3.0.29.1

* Fix `Network.Wai.Test.request` always sending an empty request body [#794](https://github.com/yesodweb/wai/pull/794)

## 3.0.29

* Export `Network.Wai.EventSource.eventStreamAppRaw` [#786](https://github.com/yesodweb/wai/pull/786)

## 3.0.28

* Add `Network.Wai.EventSource.eventStreamAppRaw` [#767](https://github.com/yesodweb/wai/pull/767)

## 3.0.27

* Add custom request log formatter which includes response headers [#762](https://github.com/yesodweb/wai/pull/762)

## 3.0.26.1

* When available, supply the response size to custom loggers
  [#757](https://github.com/yesodweb/wai/pull/757)

## 3.0.26

* Throw 413 for too large payload
* Throw 431 for too large headers
  [#741](https://github.com/yesodweb/wai/pull/741)

## 3.0.25

* Supporting `network` version 3.0.

## 3.0.24.3

* Drop unnecessary `lifted-base` dependency
* Drop unnecessary `stringsearch` dependency [#714](https://github.com/yesodweb/wai/pull/714)

## 3.0.24.2

* Consider quoted multipart form boundary markers [#700](https://github.com/yesodweb/wai/pull/700).
* Don't raise exceptions in `formatAsJSON` [#709](https://github.com/yesodweb/wai/pull/709)

## 3.0.24.1

* Fix a "file not found" exception in wai-extra [#705](https://github.com/yesodweb/wai/pull/706)

## 3.0.24.0

* Add timeout middleware [#702](https://github.com/yesodweb/wai/pull/702).

## 3.0.23.0

* Add rewriteRoot middleware [#697](https://github.com/yesodweb/wai/pull/697).

## 3.0.22.1

* Drop dependency on blaze-builder, requiring streaming-commons >= 0.2

## 3.0.22.0

* Support for streaming-commons 0.2
* Support for resourcet 1.2

## 3.0.21.0

* Export `Network.Wai.Parse.noLimitParseRequestBodyOptions` [#662](https://github.com/yesodweb/wai/pull/662).

## 3.0.20.2

* Revert previous change to `srequest`, which caused breakage

## 3.0.20.1

* Set `requestBodyLength` for `srequest` [#654](https://github.com/yesodweb/wai/pull/654)

## 3.0.20.0

* runSessionWith (runSession variant that gives access to ClientState) [#629](https://github.com/yesodweb/wai/pull/629)

## 3.0.19.1

* All loggers follow the autoFlush setting [#604](https://github.com/yesodweb/wai/pull/604)

## 3.0.19

* Add a new function basicAuth', which passes request to the CheckCreds argument.

## 3.0.18

* ForceSSL: preserve port number when redirecting to https. [#582](https://github.com/yesodweb/wai/pull/582)

## 3.0.17

* Gzip pre compressed [#580](https://github.com/yesodweb/wai/pull/580)

## 3.0.16.1

* Fix the way the header length is checked (for limiting the max header length)

## 3.0.16.0

* Add a new function "parseRequestBodyEx" that allows various size limits to be set.

## 3.0.15.3

* Allow wai-logger 2.3

## 3.0.15.2

* Doc improvements

## 3.0.15.1

* don't use deprecated CRT functions on Windows [#544](https://github.com/yesodweb/wai/pull/544)

## 3.0.15

* add requestSizeCheck [#525](https://github.com/yesodweb/wai/pull/525)

## 3.0.14.3

* Add missing `requestHeaderReferer` and `requestHeaderUserAgent` fields to CGI [yesod#1186](https://github.com/yesodweb/yesod/issues/1186)

## 3.0.14.2

* Case insensitive multipart request header lookup [#518](https://github.com/yesodweb/wai/pull/518)

## 3.0.14.1

* Doc update for logStdout and logStdoutDev [#515](https://github.com/yesodweb/wai/issues/515)

## 3.0.14

* Middleware to force domain names. [#506](https://github.com/yesodweb/wai/issues/506) [#507](https://github.com/yesodweb/wai/pull/507)

## 3.0.13.1

* Support wai 3.2

## 3.0.13

* Autoflush handle [#466](https://github.com/yesodweb/wai/pull/466)

## 3.0.12

* Add Network.Wai.Header.contentLength to read the Content-Length header of a response
* The gzip middleware no longer zips responses smaller than 860 bytes

## 3.0.11

* Add constructor for more detailed custom output formats for RequestLogger
* Add JSON output formatter for RequestLogger

## 3.0.10

* Adding Request Body to RequestLogger [#401](https://github.com/yesodweb/wai/pull/401)

## 3.0.9

* Network.Wai.Middleware.Routed module added

## 3.0.7

* Add appearsSecure: check if a request appears to be using SSL even in the
  presence of reverse proxies [#362](https://github.com/yesodweb/wai/pull/362)
* Add ForceSSL middleware [#363](https://github.com/yesodweb/wai/pull/363)
* Add Approot middleware

## 3.0.6.1

* Test code: only include a Cookie header if there are cookies. Without this
  patch, yesod-test cookie handling is broken.

## 3.0.6

* Add Cookie Handling to Network.Wai.Test [#356](https://github.com/yesodweb/wai/pull/356)

## 3.0.5

* add functions to extract authentication data from Authorization header [#352](add functions to extract authentication data from Authorization header #352)

## 3.0.4.6

* Access log sequence not valid [#336](https://github.com/yesodweb/wai/issues/336)

## 3.0.4.5

* Allow fast-logger 2.3

## 3.0.4.3

Test suite warning cleanup

## 3.0.4.2

Allow blaze-builder 0.4

## 3.0.4.1

Fix compilation failure on Windows [#321](https://github.com/yesodweb/wai/issues/321)

## 3.0.4

Add the `StreamFile` middleware.

## 3.0.3

Add the `AddHeaders` middleware.


text:
.spinner {
  height: 100px !important;
  position: relative !important;
  top: 50px !important;
}

.loadingMessage {
  text-align: center;
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using Newtonsoft.Json;

namespace Mastodon.API
{
    /// <summary>
    /// Account.
    /// https://github.com/tootsuite/documentation/blob/master/Using-the-API/API.md#account
    /// </summary>
    public class Account
    {
        [JsonProperty(PropertyName = "id")]
        public string Id { get; set; }
        [JsonProperty(PropertyName = "username")]
        public string Username { get; set; }
        [JsonProperty(PropertyName = "acct")]
        public string Acct { get; set; }
        [JsonProperty(PropertyName = "display_name")]
        public string DisplayName { get; set; }
        [JsonProperty(PropertyName = "locked")]
        public bool IsLocked { get; set; }
        [JsonProperty(PropertyName = "created_at")]
        public string CreatedAt { get; set; }
        [JsonProperty(PropertyName = "followers_count")]
        public int FollowersCount { get; set; }
        [JsonProperty(PropertyName = "following_count")]
        public int FollowingCount { get; set; }
        [JsonProperty(PropertyName = "statuses_count")]
        public int StatusesCount { get; set; }
        [JsonProperty(PropertyName = "note")]
        public string Note { get; set; }
        [JsonProperty(PropertyName = "url")]
        public Uri Url { get; set; }
        [JsonProperty(PropertyName = "avatar")]
        public Uri Avatar { get; set; }
        [JsonProperty(PropertyName = "avatar_static")]
        public Uri AvatarStatic { get; set; }
        [JsonProperty(PropertyName = "header")]
        public string Header { get; set; }
        [JsonProperty(PropertyName = "header_static")]
        public string HeaderStatic { get; set; }

        //
        /// <summary>
        /// Initializes for JSON.NET
        /// </summary>
        internal Account() { }

        public Account(string id, string username, string acct, string displayName, bool locked, string createdAt, int followersCount, int followingCount, int statusesCount, string note, Uri url, Uri avater, Uri avatarStatic, string header, string headerStatic)
        {
            Id = id;
            Username = username;
            Acct = acct;
            DisplayName = displayName;
            IsLocked = locked;
            CreatedAt = createdAt;
            FollowersCount = followersCount;
            FollowingCount = followingCount;
            StatusesCount = statusesCount;
            Note = note;
            Url = url;
            Avatar = avater;
            AvatarStatic = avatarStatic;
            Header = header;
            HeaderStatic = headerStatic;
        }

        public static Account Create(string id, string username, string acct, string displayName, bool locked, string createdAt, int followersCount, int followingCount, int statusesCount, string note, Uri url, Uri avater, Uri avatarStatic, string header, string headerStatic)
        {
            return new Account(id, username, acct, displayName, locked, createdAt, followersCount, followingCount, statusesCount, note, url, avater, avatarStatic, header, headerStatic);
        }

        public override string ToString()
        {
            return string.Format("[Account: Id={0}, Username={1}, Acct={2}, DisplayName={3}, isLocked={4}, CreatedAt={5}, FollowersCount={6}, FollowingCount={7}, StatusesCount={8}, Note={9}, Url={10}, Avatar={11}, AvatarStatic={12}, Header={13}, HeaderStatic={14}]", Id, Username, Acct, DisplayName, IsLocked, CreatedAt, FollowersCount, FollowingCount, StatusesCount, Note, Url, Avatar, AvatarStatic, Header, HeaderStatic);
        }

        public override bool Equals(object obj)
        {
            var o = obj as Account;
            if (o == null) return false;
            return Equals(Id, o.Id) &&
                Equals(Username, o.Username) &&
                Equals(Acct, o.Acct) &&
                Equals(DisplayName, o.DisplayName) &&
                Equals(IsLocked, o.IsLocked) &&
                Equals(CreatedAt, o.CreatedAt) &&
                Equals(FollowingCount, o.FollowingCount) &&
                Equals(FollowersCount, o.FollowersCount) &&
                Equals(StatusesCount, o.StatusesCount) &&
                Equals(Note, o.Note) &&
                Equals(Url, o.Url) &&
                Equals(Avatar, o.Avatar) &&
                Equals(AvatarStatic, o.AvatarStatic) &&
                Equals(Header, o.Header) &&
                Equals(HeaderStatic, o.HeaderStatic);
        }

        public override int GetHashCode()
        {
            return Object.GetHashCode(Id, Username, Acct, DisplayName, IsLocked, CreatedAt, FollowingCount, FollowersCount, StatusesCount, Note, Url, Avatar, AvatarStatic, Header, HeaderStatic);
        }
    }
}


text:
Importer des produits

    <form #f="ngForm" (ngSubmit)="onSubmit()"
          enctype="multipart/form-data" >

        <input type="file" id="file" accept="*/*" #fileInput
               name="fileInput"
               (change)="onFileSelected(f, $event)"
               required hidden>

                Choisir un autre fichier

                Choisir un fichier

Fichier à importer

                Nom:
                {{ toUploadFile.name}}

                Taille:
                {{ toUploadFileSizeLabel}}

                Type:
                {{ toUploadFile.type}}

                {{ uploadPercentage | number:'.0' }} %

            <button type="submit" class="boxedLink"
                    [disabled]="uploadInProgress ||toUploadFile == null ">
                Importer
            </button>

    </form>


text:
//------------------------------------------------------------------------------
// File: Status.h
//
// Desc: Header file for the Status Bar
//
// Copyright (c) Microsoft Corporation.  All rights reserved.
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// Global Variables
//------------------------------------------------------------------------------
extern TCHAR szStatusClass[];

//------------------------------------------------------------------------------
// Function Prototypes
//------------------------------------------------------------------------------
BOOL  statusInit(HANDLE hInst, HANDLE hPrev);
void  statusUpdateStatus(HWND hwnd, LPCTSTR lpsz);
int statusGetHeight(void);


text:
<?php

namespace PHPMentors\ProxyURLRewriteBundle\ProxyUrl;

use PHPMentors\DomainKata\Entity\EntityCollectionInterface;
use PHPMentors\DomainKata\Entity\EntityInterface;

class ProxyUrlCollection implements EntityCollectionInterface
{
    /**
     * @var array
     */
    private $proxyUrls = array();

    /**
     * {@inheritdoc}
     */
    public function add(EntityInterface $entity)
    {
        assert($entity instanceof ProxyUrl);

        $this->proxyUrls[$entity->getId()] = $entity;
    }

    /**
     * {@inheritdoc}
     */
    public function count()
    {
        return count($this->proxyUrls);
    }

    /**
     * {@inheritdoc}
     */
    public function getIterator()
    {
        return new \ArrayIterator($this->proxyUrls);
    }

    /**
     * {@inheritdoc}
     */
    public function get($key)
    {
        if (!array_key_exists($key, $this->proxyUrls)) {
            return null;
        }

        return $this->proxyUrls[$key];
    }

    /**
     * {@inheritdoc}
     */
    public function remove(EntityInterface $entity)
    {
        assert($entity instanceof ProxyUrl);
    }

    /**
     * {@inheritdoc}
     */
    public function toArray()
    {
        return $this->proxyUrls;
    }
}


text:
class AccountsController < ApplicationController
  skip_before_filter :verify_authenticity_token

  def show
    account = Api::Account.find(params[:app_key])
    if account
      details_log = 'Successfully retrived account'
    else
      account = error_message('Unable to retrive account')
      details_log = 'Faild to retrive account'
    end
    render json: account
    write_to_log('Elad', 'Get Account By APP_KEY', params[:app_key], details_log)
  end

  def show_account_features
    features = Api::Account.get_account_features(params[:app_key])
    if features
      details_log = 'Successfully retrived account features'
    else
      features = error_message('Unable to retrive account features')
      details_log = 'Faild to retrive account features'
    end
    render json: features
    write_to_log('Elad', 'Get Account Features', params[:app_key], details_log)
  end

  def enable_feature
    enabled_feature = Api::Account.enable_feature(params[:app_key], params[:id])
    if enabled_feature
      details_log = "Successfully enabled feature no.#{params[:id]}"
    else
      enabled_feature = error_message('Unable to enable feature')
      details_log = 'Faild to enable feature'
    end
    render json: enabled_feature
    write_to_log('Elad', 'Enable Feature', params[:app_key], details_log)
  end

  def disable_feature
    disabled_feature = Api::Account.disable_feature(params[:app_key], params[:id])
    if disabled_feature
      details_log = "Successfully disabled feature no.#{params[:id]}"
    else
      disabled_feature = error_message('Unable to disable feature')
      details_log = 'Faild to disable feature'
    end
    render json: disabled_feature
    write_to_log('Elad', 'Disable Feature', params[:app_key], details_log)
  end

end


text:
package br.com.starcode.proxytest;

public class ClasseAlvo {
    IClasse con;
}


text:
#import "CredentialsDemoFailoverStrategy.h"

@interface CredentialsDemoFailoverStrategy ()

@property (nonatomic) int64_t noConnectivityRetryPeriod;

@end

@implementation CredentialsDemoFailoverStrategy

- (FailoverDecision *)decisionOnFailoverStatus:(FailoverStatus)status {
    switch (status) {
        case FailoverStatusBootstrapServersNotAvailable:
            return [[FailoverDecision alloc] initWithFailoverAction:FailoverActionRetry
                                                        retryPeriod:self.bootstrapServersRetryPeriod
                                                           timeUnit:self.timeUnit];
        case FailoverStatusCurrentBootstrapServerNotAvailable:
            return [[FailoverDecision alloc] initWithFailoverAction:FailoverActionUseNextBootstrap
                                                        retryPeriod:self.bootstrapServersRetryPeriod
                                                           timeUnit:self.timeUnit];
        case FailoverStatusNoOperationsServersReceived:
            return [[FailoverDecision alloc] initWithFailoverAction:FailoverActionUseNextBootstrap
                                                        retryPeriod:self.bootstrapServersRetryPeriod
                                                           timeUnit:self.timeUnit];
        case FailoverStatusOperationsServersNotAvailable:
            return [[FailoverDecision alloc] initWithFailoverAction:FailoverActionRetry
                                                        retryPeriod:self.operationsServersRetryPeriod
                                                           timeUnit:self.timeUnit];
        case FailoverStatusNoConnectivity:
            return [[FailoverDecision alloc] initWithFailoverAction:FailoverActionRetry
                                                        retryPeriod:self.noConnectivityRetryPeriod
                                                           timeUnit:self.timeUnit];
        case FailoverStatusEndpointCredentialsRevoked:
        case FailoverStatusEndpointVerificationFailed:
            NSLog(@"Credentials were rejected. Client can't register on cluster");
            return [[FailoverDecision alloc] initWithFailoverAction:FailoverActionNoop];
        default:
            return [[FailoverDecision alloc] initWithFailoverAction:FailoverActionNoop];
    }
}

@end


text:
module Ruboty
  module Annoinder
    module Entity
      class Notification
        attr_accessor :id, :duration, :content, :target

        def self.get_instance(message)
          instance = self.new
          instance.duration = ValueObject::Duration.new

          head_trim_message = message.gsub(/\A\S+/, '')

          res = head_trim_message.scan(/@\S+/)
          instance.target = ValueObject::Target.new(res)

          notify_body = head_trim_message.gsub(/@\S+/, '')

          instance.content = ValueObject::Content.new(
            raw_message: message,
            notify_message: notify_body
          )

          return instance
        end

        def got_it(username)
          @target.members = @target.members - [at(username)]
          p "@target.members"
          p @target.members
        end

        def at(username)
          return username if username.match(/\A@/)
          return "@#{username}"
        end

        def to_s
          "#{id}:duration:#{duration}, content:#{content}, target:#{target}"
        end
      end
    end
  end
end


text:
namespace ExamineMd.Factories
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading;

    using ExamineMd.Models;
    using ExamineMd.Search;

    using Lucene.Net.Store;

    using Umbraco.Core;
    using Umbraco.Core.Models;
    using Umbraco.Web;
    using Umbraco.Web.Models;

    /// <summary>
    /// The virtual content factory.
    /// </summary>
    public class VirtualContentFactory
    {
        private System.Object _lock = new System.Object();

        /// <summary>
        /// The locker.
        /// </summary>
        private static readonly ReaderWriterLockSlim Locker = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);

        /// <summary>
        /// The <see cref="IMarkdownQuery"/>.
        /// </summary>
        private readonly IMarkdownQuery _query;

        /// <summary>
        /// Initializes a new instance of the <see cref="VirtualContentFactory"/> class.
        /// </summary>
        /// <param name="query">
        /// The query.
        /// </param>
        public VirtualContentFactory(IMarkdownQuery query)
        {
            Mandate.ParameterNotNull(query, "query");

            _query = query;
        }

        /// <summary>
        /// Gets the starting path from the <see cref="ExamineMd" /> content
        /// </summary>
        /// <param name="content">
        /// The content.
        /// </param>
        /// <returns>
        /// The starting path.
        /// </returns>
        public static string GetStartingPath(IPublishedContent content)
        {
            if (content.DocumentTypeAlias != "ExamineMd") return "\\";

            var startPathing = content.GetPropertyValue<string>("startingPath");
            return string.IsNullOrEmpty(startPathing) ? "\\" : startPathing.EnsureBackSlashes();
        }

        /// <summary>
        /// Builds <see cref="IVirtualMarkdownBase"/>.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <param name="url">
        /// The url.
        /// </param>
        /// <returns>
        /// The <see cref="IVirtualMarkdownBase"/>.
        /// </returns>
        public IVirtualMarkdownBase Build(IRenderModel model, string url)
        {

            url = GetStartingPath(model.Content).EnsureForwardSlashes().EnsureNotEndsWith('/') + url;
            var path = _query.Paths.GetByUrl(url);

            return Build(model, path);
        }

        /// <summary>
        /// Builds <see cref="IVirtualMarkdownBase"/>.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <param name="path">
        /// The <see cref="IMdPath"/>.
        /// </param>
        /// <returns>
        /// The <see cref="IVirtualMarkdownBase"/>.
        /// </returns>
        public IVirtualMarkdownBase Build(IRenderModel model, IMdPath path)
        {
            if (path.IsDocument)
            {
                var md = _query.Files.Get(path.Key);
                return this.BuildDocument(model, md);
            }

            return this.BuildListing(model, path);
        }

        /// <summary>
        /// Builds a <see cref="IVirtualMarkdownDocument"/>.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <param name="md">
        /// The md.
        /// </param>
        /// <returns>
        /// The <see cref="IVirtualMarkdownDocument"/>.
        /// </returns>
        public IVirtualMarkdownDocument BuildDocument(IRenderModel model, IMdFile md)
        {
            var parent = md.Path.IsRootPath() || GetStartingPath(model.Content).Contains(md.Path.Value) ?
                model.Content.Parent :
                BuildListing(model, md.Path.ParentPath());

            var document = new VirtualMarkdownDocument(model.Content, parent, md)
            {
                HeadleLine = string.IsNullOrEmpty(md.MetaData.PageTitle) ? md.Title : md.MetaData.PageTitle,
                PageTitle = string.IsNullOrEmpty(md.MetaData.PageTitle) ? md.Title : md.MetaData.PageTitle,
                MetaDescription = string.IsNullOrEmpty(md.MetaData.MetaDescription) ? string.Empty : md.MetaData.MetaDescription,
                MdPath = md.Path
            };

            return document;
        }

        /// <summary>
        /// Builds a <see cref="IVirtualMarkdownListing"/>.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <param name="path">
        /// The path.
        /// </param>
        /// <returns>
        /// The <see cref="IVirtualMarkdownListing"/>.
        /// </returns>
        public IVirtualMarkdownListing BuildListing(IRenderModel model, IMdPath path)
        {
            var parent = path.IsRootPath() || GetStartingPath(model.Content).Contains(path.Value)
                             ? model.Content.Parent
                             : this.Build(model, path.ParentPath());

            return new VirtualMarkdownListing(model.Content, parent, path, GetChildren)
                       {
                           Brief = model.Content.GetPropertyValue<string>("brief")
                       };
        }

        /// <summary>
        /// Gets a list of virtual children
        /// </summary>
        /// <param name="content">The root content</param>
        /// <param name="pathKey">
        /// The path.
        /// </param>
        /// <returns>
        /// The <see cref="IEnumerable"/>.
        /// </returns>
        internal IEnumerable<IPublishedContent> GetChildren(IPublishedContent content, string pathKey)
        {
            var contents = new List<IVirtualMarkdownBase>();

            lock (_lock)
            {
                // Directories
                var directories = _query.Paths.GetByPathKey(pathKey).Where(x => !x.IsRootPath()).ToArray();
                if (directories.Any())
                {
                    contents.AddRange(directories.Select(x => this.BuildListing(new RenderModel(content), x)));
                }

                // Files
                var files = _query.Files.GetByPathKey(pathKey).ToArray();
                if (files.Any())
                {
                    contents.AddRange(files.Select(x => this.BuildDocument(new RenderModel(content), x)));
                }
            }

            return contents;
        }
    }
}


text:
import java.util.ArrayList;
import java.util.List;

public class MiddleCode {

    private static final String METHOD = "method";
    private static final String OBJECT = "object";
    private static final String OBJECT_METHOD = "object_method";
    private static final String EVENT = "event";

    List<MiddleMethod> methods = new ArrayList<>();

    List<MiddleObject> objects = new ArrayList<>();

    List<MiddleEvent> events = new ArrayList<>();

    public MiddleCode() {
        List<String> lines = FileUtils.loadInterfaceArray();
        int id = 0;
        for (String line : lines) {
            if (line.startsWith("//")) {
                // Skips comments
                continue;
            }
            String[] keywords = line.split(" ");
            switch (keywords[0]) {
                case METHOD:
                    methods.add(new MiddleMethod(line, id++));
                    break;
                case OBJECT:
                    String newObjectName = keywords[1];
                    if (getObjectByName(newObjectName) != null) {
                        throw new RuntimeException("Object " + newObjectName + " already exists!");
                    }
                    MiddleObject newObject = new MiddleObject(newObjectName, id++);
                    newObject.addDefaultConstructor(id++);
                    objects.add(newObject);
                    break;
                case OBJECT_METHOD:
                    String objectName = keywords[1];
                    MiddleObject o = getObjectByName(objectName);
                    if (o == null) {
                        throw new RuntimeException("Cannot find object: " + objectName);
                    }
                    // Hacky here for getting the method string
                    o.addMethod(new MiddleMethod(line.substring((OBJECT_METHOD).length() + 1), id++));
                    break;
                case EVENT:
                    MiddleEvent event = new MiddleEvent(keywords[1], id++);
                    break;
            }
        }
    }

    public String toString() {
        String result = "";
        for (MiddleMethod method : methods) {
            result += "method: " + method.toString() + "\n";
        }
        for (MiddleObject o : objects) {
            result += "object: " + o.toString() + "\n";
        }
        for (MiddleEvent event : events) {
            result += "event: " + event.toString() + "\n";
        }
        return result;
    }

    private MiddleObject getObjectByName(String name) {
        name = name.trim();
        for (MiddleObject o : objects) {
            if (o.name.equals(name)) {
                return o;
            }
        }
        return null;
    }
}


text:
package com.zhigu.mapper;

import java.util.Map;

/**
 * 后台订单
 *
 * @author zhouqibing 2014年9月2日下午1:41:30
 */
public interface AdminOrderMapper {
	/**
	 * 会员订单统计
	 *
	 * @param memberID
	 * @return
	 */
	public Map<String, Object> memberOrderStatByMemberID(Integer memberID);
}


text:
#if !defined(FUSION_INCLUDE_NOT_EQUAL_TO)
#define FUSION_INCLUDE_NOT_EQUAL_TO

#include <lslboost/fusion/iterator/equal_to.hpp>
#include <lslboost/fusion/sequence/comparison/not_equal_to.hpp>

#endif


text:
@implementation ASIGListSectionControllerMethods

+ (__kindof UICollectionViewCell *)cellForItemAtIndex:(NSInteger)index sectionController:(IGListSectionController *)sectionController
{
  // Cast to id for backwards-compatibility until 3.0.0 is officially released – IGListSectionType was removed. This is safe.
  return [sectionController.collectionContext dequeueReusableCellOfClass:[_ASCollectionViewCell class] forSectionController:(id)sectionController atIndex:index];
}

+ (CGSize)sizeForItemAtIndex:(NSInteger)index
{
  ASDisplayNodeFailAssert(@"Did not expect %@ to be called.", NSStringFromSelector(_cmd));
  return CGSizeZero;
}

@end

@implementation ASIGListSupplementaryViewSourceMethods

+ (__kindof UICollectionReusableView *)viewForSupplementaryElementOfKind:(NSString *)elementKind
                                                                 atIndex:(NSInteger)index
                                                       sectionController:(IGListSectionController *)sectionController
{
  return [sectionController.collectionContext dequeueReusableSupplementaryViewOfKind:elementKind forSectionController:(id)sectionController class:[_ASCollectionReusableView class] atIndex:index];
}

+ (CGSize)sizeForSupplementaryViewOfKind:(NSString *)elementKind atIndex:(NSInteger)index
{
  ASDisplayNodeFailAssert(@"Did not expect %@ to be called.", NSStringFromSelector(_cmd));
  return CGSizeZero;
}

@end

#endif // AS_IG_LIST_KIT


text:
package org.microg.nlp.ui;

import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.AttributeSet;

import org.microg.nlp.Preferences;
import org.microg.nlp.R;
import org.microg.nlp.api.GeocoderBackend;
import org.microg.nlp.geocode.AbstractGeocodeService;

import static org.microg.nlp.api.Constants.ACTION_GEOCODER_BACKEND;

public class GeocoderBackendPreference extends AbstractBackendPreference {
    public GeocoderBackendPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
        setDialogTitle(R.string.configure_geocoder_backends);
        setTitle(R.string.configure_geocoder_backends);
    }

    @Override
    protected void onValueChanged() {
        AbstractGeocodeService.reloadGeocodeService(getContext());
    }

    @Override
    protected Intent buildBackendIntent() {
        return new Intent(ACTION_GEOCODER_BACKEND);
    }

    @Override
    protected String defaultValue() {
        return new Preferences(getContext()).getDefaultGeocoderBackends();
    }

    @Override
    protected Intent getBackendInitIntent(IBinder service) {
        GeocoderBackend backend = GeocoderBackend.Stub.asInterface(service);
        try {
            return backend.getInitIntent();
        } catch (RemoteException e) {
            return null;
        }
    }
}


text:
default: clean build

build: clean
	mkdir -p build
	node_modules/coffee-script/bin/coffee -o build/ -c src/goggles.coffee
	node_modules/browserify/bin/cmd.js build/goggles.js --standalone Goggles -o build/goggles.main.js

compress: build
	cp build/goggles.main.js goggles.js
	node_modules/.bin/uglifyjs build/goggles.main.js > goggles.min.js
	mv build/goggles.main.js build/goggles.js

test: build
	npm test

clean:
	rm -rf build

.PHONY: clean build compress test


text:
package com.nec.strudel.workload.session;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.nec.strudel.session.Interaction;

public final class FactoryUtil {

    private static final Pattern LOCAL_NAME = Pattern.compile(".*?(\\w+)\\z");

    private FactoryUtil() {
        // not instantiated
    }

    public static String getName(Interaction<?> intr) {
        Name nam = intr.getClass().getAnnotation(Name.class);
        if (nam != null) {
            return nam.value();
        }
        return convert(getLocalName(intr.getClass()));
    }

    private static String convert(String str) {
        if (str == null) {
            return null;
        }
        return str.replaceAll("([a-z])([A-Z])", "$1_$2").toUpperCase();
    }

    private static String getLocalName(Class<?> cls) {
        Matcher match = LOCAL_NAME.matcher(cls.getName());
        if (match.matches()) {
            return match.group(1);
        } else {
            return null;
        }
    }
}


text: from pyface.grid.checkbox_renderer import *


text: search_result['1396']=["topic_000000000000034C.html","tlece_CompanyStaff.UserId Property",""];


text:
namespace chrono {
namespace utils {

// -----------------------------------------------------------------------------
// WriteBodies
//
// Write to a CSV file pody position, orientation, and (optionally) linear and
// angular velocity. Optionally, only active bodies are processed.
// -----------------------------------------------------------------------------
void WriteBodies(ChSystem* system,
                 const std::string& filename,
                 bool active_only,
                 bool dump_vel,
                 const std::string& delim) {
    CSV_writer csv(delim);

    for (auto body : system->Get_bodylist()) {
        if (active_only && !body->IsActive())
            continue;
        csv << body->GetPos() << body->GetRot();
        if (dump_vel)
            csv << body->GetPos_dt() << body->GetWvel_loc();
        csv << std::endl;
    }

    csv.write_to_file(filename);
}

// -----------------------------------------------------------------------------
// WriteCheckpoint
//
// Create a CSV file with a checkpoint ...
//
// -----------------------------------------------------------------------------
bool WriteCheckpoint(ChSystem* system, const std::string& filename) {
    // Create the CSV stream.
    CSV_writer csv(" ");

    for (auto body : system->Get_bodylist()) {
        // Infer body type (0: NSC, 1:SMC)
        int btype = (body->GetContactMethod() == ChMaterialSurface::NSC) ? 0 : 1;

        // Write body type, body identifier, the body fixed flag, and the collide flag
        csv << btype << body->GetIdentifier() << body->GetBodyFixed() << body->GetCollide();

        // Write collision family information.
        csv << body->GetCollisionModel()->GetFamilyGroup() << body->GetCollisionModel()->GetFamilyMask();

        // Write body mass and inertia
        csv << body->GetMass() << body->GetInertiaXX();

        // Write body position, orientation, and their time derivatives
        csv << body->GetPos() << body->GetRot();
        csv << body->GetPos_dt() << body->GetRot_dt();

        csv << std::endl;

        // Write material information
        if (btype == 0) {
            // Write NSC material surface information
            std::shared_ptr<ChMaterialSurfaceNSC> mat = body->GetMaterialSurfaceNSC();
            csv << mat->static_friction << mat->sliding_friction << mat->rolling_friction << mat->spinning_friction;
            csv << mat->restitution << mat->cohesion << mat->dampingf;
            csv << mat->compliance << mat->complianceT << mat->complianceRoll << mat->complianceSpin;
        } else {
            // Write SMC material surface information
            std::shared_ptr<ChMaterialSurfaceSMC> mat = body->GetMaterialSurfaceSMC();
            csv << mat->young_modulus << mat->poisson_ratio;
            csv << mat->static_friction << mat->sliding_friction;
            csv << mat->restitution << mat->constant_adhesion << mat->adhesionMultDMT;
            csv << mat->kn << mat->gn << mat->kt << mat->gt;
        }

        csv << std::endl;

        // Count and write all visual assets.
        int num_visual_assets = 0;
        for (auto asset : body->GetAssets()) {
            if (std::dynamic_pointer_cast<ChVisualization>(asset))
                num_visual_assets++;
        }
        csv << num_visual_assets << std::endl;

        // Loop over each asset and, for selected visual assets only, write its data
        // on a separate line. If we encounter an unsupported type, return false.
        for (auto asset : body->GetAssets()) {
            auto visual_asset = std::dynamic_pointer_cast<ChVisualization>(asset);
            if (!visual_asset)
                continue;

            // Write relative position and rotation
            csv << visual_asset->Pos << visual_asset->Rot.Get_A_quaternion();

            // Write shape type and geometry data
            if (auto sphere = std::dynamic_pointer_cast<ChSphereShape>(visual_asset)) {
                csv << collision::SPHERE << sphere->GetSphereGeometry().rad;
            } else if (auto ellipsoid = std::dynamic_pointer_cast<ChEllipsoidShape>(visual_asset)) {
                csv << collision::ELLIPSOID << ellipsoid->GetEllipsoidGeometry().rad;
            } else if (auto box = std::dynamic_pointer_cast<ChBoxShape>(visual_asset)) {
                csv << collision::BOX << box->GetBoxGeometry().Size;
            } else if (auto capsule = std::dynamic_pointer_cast<ChCapsuleShape>(visual_asset)) {
                const geometry::ChCapsule& geom = capsule->GetCapsuleGeometry();
                csv << collision::CAPSULE << geom.rad << geom.hlen;
            } else if (auto cylinder = std::dynamic_pointer_cast<ChCylinderShape>(visual_asset)) {
                const geometry::ChCylinder& geom = cylinder->GetCylinderGeometry();
                csv << collision::CYLINDER << geom.rad << (geom.p1.y() - geom.p2.y()) / 2;
            } else if (auto cone = std::dynamic_pointer_cast<ChConeShape>(visual_asset)) {
                const geometry::ChCone& geom = cone->GetConeGeometry();
                csv << collision::CONE << geom.rad.x() << geom.rad.y();
            } else if (auto rbox = std::dynamic_pointer_cast<ChRoundedBoxShape>(visual_asset)) {
                const geometry::ChRoundedBox& geom = rbox->GetRoundedBoxGeometry();
                csv << collision::ROUNDEDBOX << geom.Size << geom.radsphere;
            } else if (auto rcyl = std::dynamic_pointer_cast<ChRoundedCylinderShape>(visual_asset)) {
                const geometry::ChRoundedCylinder& geom = rcyl->GetRoundedCylinderGeometry();
                csv << collision::ROUNDEDCYL << geom.rad << geom.hlen << geom.radsphere;
            } else {
                // Unsupported visual asset type.
                return false;
            }
            csv << std::endl;
        }
    }

    csv.write_to_file(filename);

    return true;
}

// -----------------------------------------------------------------------------
// ReadCheckpoint
//
// Read a CSV file with checkpoint data and create the bodies.
//
// -----------------------------------------------------------------------------
void ReadCheckpoint(ChSystem* system, const std::string& filename) {
    // Open input file stream
    std::ifstream ifile(filename.c_str());
    std::string line;

    while (std::getline(ifile, line)) {
        std::istringstream iss1(line);

        // Read body type, Id, flags
        int btype, bid, bfixed, bcollide;
        short family_group, family_mask;
        iss1 >> btype >> bid >> bfixed >> bcollide >> family_group >> family_mask;

        // Read body mass and inertia
        double mass;
        ChVector<> inertiaXX;
        iss1 >> mass >> inertiaXX.x() >> inertiaXX.y() >> inertiaXX.z();

        // Read body position, orientation, and their time derivatives
        ChVector<> bpos, bpos_dt;
        ChQuaternion<> brot, brot_dt;
        iss1 >> bpos.x() >> bpos.y() >> bpos.z() >> brot.e0() >> brot.e1() >> brot.e2() >> brot.e3();
        iss1 >> bpos_dt.x() >> bpos_dt.y() >> bpos_dt.z() >> brot_dt.e0() >> brot_dt.e1() >> brot_dt.e2() >> brot_dt.e3();

        // Get the next line in the file (material properties)
        std::getline(ifile, line);
        std::istringstream iss2(line);

        // Create a body of the appropriate type, read and apply material properties
        ChBody* body = system->NewBody();
        if (btype == 0) {
            std::shared_ptr<ChMaterialSurfaceNSC> mat = body->GetMaterialSurfaceNSC();
            iss2 >> mat->static_friction >> mat->sliding_friction >> mat->rolling_friction >> mat->spinning_friction;
            iss2 >> mat->restitution >> mat->cohesion >> mat->dampingf;
            iss2 >> mat->compliance >> mat->complianceT >> mat->complianceRoll >> mat->complianceSpin;
        } else {
            std::shared_ptr<ChMaterialSurfaceSMC> mat = body->GetMaterialSurfaceSMC();
            iss2 >> mat->young_modulus >> mat->poisson_ratio;
            iss2 >> mat->static_friction >> mat->sliding_friction;
            iss2 >> mat->restitution >> mat->constant_adhesion >> mat->adhesionMultDMT;
            iss2 >> mat->kn >> mat->gn >> mat->kt >> mat->gt;
        }

        // Add the body to the system.
        system->AddBody(std::shared_ptr<ChBody>(body));

        // Set body properties and state
        body->SetPos(bpos);
        body->SetRot(brot);
        body->SetPos_dt(bpos_dt);
        body->SetRot_dt(brot_dt);

        body->SetIdentifier(bid);
        body->SetBodyFixed(bfixed != 0);
        body->SetCollide(bcollide != 0);

        body->SetMass(mass);
        body->SetInertiaXX(inertiaXX);

        // Get next line in the file (number of visualization assets)
        std::getline(ifile, line);
        std::istringstream iss3(line);

        int numAssets;
        iss3 >> numAssets;

        // In a loop, read information about each asset and add geometry to the body
        body->GetCollisionModel()->ClearModel();

        for (int j = 0; j < numAssets; j++) {
            std::getline(ifile, line);
            std::istringstream iss(line);

            // Get relative position and rotation
            ChVector<> apos;
            ChQuaternion<> arot;
            iss >> apos.x() >> apos.y() >> apos.z() >> arot.e0() >> arot.e1() >> arot.e2() >> arot.e3();

            // Get visualization asset type and geometry data.
            // Create the appropriate shape (both visualization and contact).
            int atype;
            iss >> atype;

            switch (collision::ShapeType(atype)) {
                case collision::SPHERE: {
                    double radius;
                    iss >> radius;
                    AddSphereGeometry(body, radius, apos, arot);
                } break;
                case collision::ELLIPSOID: {
                    ChVector<> size;
                    iss >> size.x() >> size.y() >> size.z();
                    AddEllipsoidGeometry(body, size, apos, arot);
                } break;
                case collision::BOX: {
                    ChVector<> size;
                    iss >> size.x() >> size.y() >> size.z();
                    AddBoxGeometry(body, size, apos, arot);
                } break;
                case collision::CAPSULE: {
                    double radius, hlen;
                    iss >> radius >> hlen;
                    AddCapsuleGeometry(body, radius, hlen, apos, arot);
                } break;
                case collision::CYLINDER: {
                    double radius, hlen;
                    iss >> radius >> hlen;
                    AddCylinderGeometry(body, radius, hlen, apos, arot);
                } break;
                case collision::CONE: {
                    double radius, height;
                    iss >> radius >> height;
                    AddConeGeometry(body, radius, height, apos, arot);
                } break;
                case collision::ROUNDEDBOX: {
                    ChVector<> size;
                    double srad;
                    iss >> size.x() >> size.y() >> size.z() >> srad;
                    AddRoundedBoxGeometry(body, size, srad, apos, arot);
                } break;
                case collision::ROUNDEDCYL: {
                    double radius, hlen, srad;
                    iss >> radius >> hlen >> srad;
                    AddRoundedCylinderGeometry(body, radius, hlen, srad, apos, arot);
                } break;
                default:
                    break;
            }
        }

        // Set the collision family group and the collision family mask.
        body->GetCollisionModel()->SetFamilyGroup(family_group);
        body->GetCollisionModel()->SetFamilyMask(family_mask);

        // Complete construction of the collision model.
        body->GetCollisionModel()->BuildModel();
    }
}

// -----------------------------------------------------------------------------
// WriteShapesPovray
//
// Write CSV output file for PovRay.
// First line contains the number of visual assets and links to follow.
// A line with information about a visualization asset contains:
//    bodyId, bodyActive, x, y, z, e0, e1, e2, e3, shapeType, [shape Data]
// A line with information about a link contains:
//    linkType, [linkData]
//
// NOTE: we do not account for any transform specified for the ChGeometry of
// a visual asset (except for cylinders where that is implicit)!
// -----------------------------------------------------------------------------
enum POVRayShapeType {
    SPHERE = 0,
    ELLIPSOID = 1,
    BOX = 2,
    CYLINDER = 3,
    CONVEXHULL = 4,
    TRIANGLEMESH = 5,
    BARREL = 6,
    CAPSULE = 7,
    CONE = 8,
    ROUNDEDBOX = 9,
    ROUNDEDCYL = 10,
    ROUNDEDCONE = 11,
    BEZIER = 12
};

enum POVRayLinkType {
    REVOLUTE = 0,
    SPHERICAL = 1,
    PRISMATIC = 2,
    UNIVERSAL = 3,
    DISTANCE = 4,
    ENGINE = 5,
    SPRING = 6,
    SPRING_CB = 7
};

void WriteShapesPovray(ChSystem* system, const std::string& filename, bool body_info, const std::string& delim) {
    CSV_writer csv(delim);

    // If requested, Loop over all bodies and write out their position and
    // orientation.  Otherwise, body count is left at 0.
    int b_count = 0;

    if (body_info) {
        for (auto body : system->Get_bodylist()) {
            const ChVector<>& body_pos = body->GetFrame_REF_to_abs().GetPos();
            const ChQuaternion<>& body_rot = body->GetFrame_REF_to_abs().GetRot();

            csv << body->GetIdentifier() << body->IsActive() << body_pos << body_rot << std::endl;

            b_count++;
        }
    }

    // Loop over all bodies and over all their assets.
    int a_count = 0;
    for (auto body : system->Get_bodylist()) {
        const ChVector<>& body_pos = body->GetFrame_REF_to_abs().GetPos();
        const ChQuaternion<>& body_rot = body->GetFrame_REF_to_abs().GetRot();

        ChColor color(0.8f, 0.8f, 0.8f);

        // First loop over assets -- search for a color asset
        for (auto asset : body->GetAssets()) {
            if (auto color_asset = std::dynamic_pointer_cast<ChColorAsset>(asset))
                color = color_asset->GetColor();
        }

        // Loop over assets once again -- write information for supported types.
        for (auto asset : body->GetAssets()) {
            auto visual_asset = std::dynamic_pointer_cast<ChVisualization>(asset);
            if (!visual_asset)
                continue;

            const Vector& asset_pos = visual_asset->Pos;
            Quaternion asset_rot = visual_asset->Rot.Get_A_quaternion();

            Vector pos = body_pos + body_rot.Rotate(asset_pos);
            Quaternion rot = body_rot % asset_rot;

            bool supported = true;
            std::stringstream gss;

            if (auto sphere = std::dynamic_pointer_cast<ChSphereShape>(visual_asset)) {
                gss << SPHERE << delim << sphere->GetSphereGeometry().rad;
                a_count++;
            } else if (auto ellipsoid = std::dynamic_pointer_cast<ChEllipsoidShape>(visual_asset)) {
                const Vector& size = ellipsoid->GetEllipsoidGeometry().rad;
                gss << ELLIPSOID << delim << size.x() << delim << size.y() << delim << size.z();
                a_count++;
            } else if (auto box = std::dynamic_pointer_cast<ChBoxShape>(visual_asset)) {
                const Vector& size = box->GetBoxGeometry().Size;
                gss << BOX << delim << size.x() << delim << size.y() << delim << size.z();
                a_count++;
            } else if (auto capsule = std::dynamic_pointer_cast<ChCapsuleShape>(visual_asset)) {
                const geometry::ChCapsule& geom = capsule->GetCapsuleGeometry();
                gss << CAPSULE << delim << geom.rad << delim << geom.hlen;
                a_count++;
            } else if (auto cylinder = std::dynamic_pointer_cast<ChCylinderShape>(visual_asset)) {
                const geometry::ChCylinder& geom = cylinder->GetCylinderGeometry();
                gss << CYLINDER << delim << geom.rad << delim << geom.p1.x() << delim << geom.p1.y() << delim << geom.p1.z()
                    << delim << geom.p2.x() << delim << geom.p2.y() << delim << geom.p2.z();
                a_count++;
            } else if (auto cone = std::dynamic_pointer_cast<ChConeShape>(visual_asset)) {
                const geometry::ChCone& geom = cone->GetConeGeometry();
                gss << CONE << delim << geom.rad.x() << delim << geom.rad.y();
                a_count++;
            } else if (auto rbox = std::dynamic_pointer_cast<ChRoundedBoxShape>(visual_asset)) {
                const geometry::ChRoundedBox& geom = rbox->GetRoundedBoxGeometry();
                gss << ROUNDEDBOX << delim << geom.Size.x() << delim << geom.Size.y() << delim << geom.Size.z() << delim
                    << geom.radsphere;
                a_count++;
            } else if (auto rcyl = std::dynamic_pointer_cast<ChRoundedCylinderShape>(visual_asset)) {
                const geometry::ChRoundedCylinder& geom = rcyl->GetRoundedCylinderGeometry();
                gss << ROUNDEDCYL << delim << geom.rad << delim << geom.hlen << delim << geom.radsphere;
                a_count++;
            } else if (auto mesh = std::dynamic_pointer_cast<ChTriangleMeshShape>(visual_asset)) {
                gss << TRIANGLEMESH << delim << "\"" << mesh->GetName() << "\"";
                a_count++;
            } else if (auto line = std::dynamic_pointer_cast<ChLineShape>(visual_asset)) {
                std::shared_ptr<geometry::ChLine> geom = line->GetLineGeometry();
                if (auto bezier = std::dynamic_pointer_cast<geometry::ChLineBezier>(geom)) {
                    gss << BEZIER << delim << "\"" << line->GetName() << "\"";
                    a_count++;
                } else {
                    supported = false;
                }
            } else {
                supported = false;
            }

            if (supported) {
                csv << body->GetIdentifier() << body->IsActive() << pos << rot << color << gss.str() << std::endl;
            }
        }
    }

    // Loop over all links.  Write information on selected types of links.
    int l_count = 0;
    for (auto ilink : system->Get_linklist()) {
        if (auto link = std::dynamic_pointer_cast<ChLinkLockRevolute>(ilink)) {
            chrono::ChFrame<> frA_abs = *(link->GetMarker1()) >> *(link->GetBody1());
            chrono::ChFrame<> frB_abs = *(link->GetMarker2()) >> *(link->GetBody2());

            csv << REVOLUTE << frA_abs.GetPos() << frA_abs.GetA().Get_A_Zaxis() << std::endl;
            l_count++;
        } else if (auto link = std::dynamic_pointer_cast<ChLinkLockSpherical>(ilink)) {
            chrono::ChFrame<> frA_abs = *(link->GetMarker1()) >> *(link->GetBody1());
            chrono::ChFrame<> frB_abs = *(link->GetMarker2()) >> *(link->GetBody2());

            csv << SPHERICAL << frA_abs.GetPos() << std::endl;
            l_count++;
        }
        if (auto link = std::dynamic_pointer_cast<ChLinkLockPrismatic>(ilink)) {
            chrono::ChFrame<> frA_abs = *(link->GetMarker1()) >> *(link->GetBody1());
            chrono::ChFrame<> frB_abs = *(link->GetMarker2()) >> *(link->GetBody2());

            csv << PRISMATIC << frA_abs.GetPos() << frA_abs.GetA().Get_A_Zaxis() << std::endl;
            l_count++;
        } else if (auto link = std::dynamic_pointer_cast<ChLinkUniversal>(ilink)) {
            chrono::ChFrame<> frA_abs = link->GetFrame1Abs();
            chrono::ChFrame<> frB_abs = link->GetFrame2Abs();

            csv << UNIVERSAL << frA_abs.GetPos() << frA_abs.GetA().Get_A_Xaxis() << frB_abs.GetA().Get_A_Yaxis()
                << std::endl;
            l_count++;
        } else if (auto link = std::dynamic_pointer_cast<ChLinkSpring>(ilink)) {
            chrono::ChFrame<> frA_abs = *(link->GetMarker1()) >> *(link->GetBody1());
            chrono::ChFrame<> frB_abs = *(link->GetMarker2()) >> *(link->GetBody2());

            csv << SPRING << frA_abs.GetPos() << frB_abs.GetPos() << std::endl;
            l_count++;
        } else if (auto link = std::dynamic_pointer_cast<ChLinkSpringCB>(ilink)) {
            chrono::ChFrame<> frA_abs = *(link->GetMarker1()) >> *(link->GetBody1());
            chrono::ChFrame<> frB_abs = *(link->GetMarker2()) >> *(link->GetBody2());

            csv << SPRING_CB << frA_abs.GetPos() << frB_abs.GetPos() << std::endl;
            l_count++;
        } else if (auto link = std::dynamic_pointer_cast<ChLinkDistance>(ilink)) {
            csv << DISTANCE << link->GetEndPoint1Abs() << link->GetEndPoint2Abs() << std::endl;
            l_count++;
        } else if (auto link = std::dynamic_pointer_cast<ChLinkEngine>(ilink)) {
            chrono::ChFrame<> frA_abs = *(link->GetMarker1()) >> *(link->GetBody1());
            chrono::ChFrame<> frB_abs = *(link->GetMarker2()) >> *(link->GetBody2());

            csv << ENGINE << frA_abs.GetPos() << frA_abs.GetA().Get_A_Zaxis() << std::endl;
            l_count++;
        }
    }

    // Write the output file, including a first line with number of bodies, visual
    // assets, and links.
    std::stringstream header;
    header << b_count << delim << a_count << delim << l_count << delim << std::endl;

    csv.write_to_file(filename, header.str());
}

// -----------------------------------------------------------------------------
// WriteMeshPovray
//
// Write the triangular mesh from the specified OBJ file as a macro in a PovRay
// include file.
// -----------------------------------------------------------------------------
void WriteMeshPovray(geometry::ChTriangleMeshConnected& trimesh,
                     const std::string& mesh_name,
                     const std::string& out_dir,
                     const ChColor& col,
                     const ChVector<>& pos,
                     const ChQuaternion<>& rot,
                     bool smoothed) {
    // Transform vertices.
    for (unsigned int i = 0; i < trimesh.m_vertices.size(); i++)
        trimesh.m_vertices[i] = pos + rot.Rotate(trimesh.m_vertices[i]);

    // Transform normals
    if (smoothed) {
        for (unsigned int i = 0; i < trimesh.m_normals.size(); i++)
            trimesh.m_normals[i] = rot.Rotate(trimesh.m_normals[i]);
    }

    // Open output file.
    std::string pov_filename = out_dir + "/" + mesh_name + ".inc";
    std::ofstream ofile(pov_filename.c_str());

    ofile << "#declare " << mesh_name << "_mesh = mesh2 {" << std::endl;

    // Write vertices.
    ofile << "vertex_vectors {" << std::endl;
    ofile << trimesh.m_vertices.size();
    for (unsigned int i = 0; i < trimesh.m_vertices.size(); i++) {
        ChVector<> v = trimesh.m_vertices[i];
        ofile << ",\n<" << v.x() << ", " << v.z() << ", " << v.y() << ">";
    }
    ofile << "\n}" << std::endl;

    // Write normals.
    if (smoothed) {
        ofile << "normal_vectors {" << std::endl;
        ofile << trimesh.m_normals.size();
        for (unsigned int i = 0; i < trimesh.m_normals.size(); i++) {
            ChVector<> n = trimesh.m_normals[i];
            ofile << ",\n<" << n.x() << ", " << n.z() << ", " << n.y() << ">";
        }
        ofile << "\n}" << std::endl;
    }

    // Write face connectivity.
    ofile << "face_indices {" << std::endl;
    ofile << trimesh.m_face_v_indices.size();
    for (int i = 0; i < trimesh.m_face_v_indices.size(); i++) {
        ChVector<int> face = trimesh.m_face_v_indices[i];
        ofile << ",\n<" << face.x() << ", " << face.y() << ", " << face.z() << ">";
    }
    ofile << "\n}" << std::endl;

    ofile << "\n}" << std::endl;

    // Write the object
    ofile << "#declare " << mesh_name << " = object {" << std::endl;

    ofile << "   " << mesh_name << "_mesh" << std::endl;
    ofile << "   texture {" << std::endl;
    ofile << "      pigment {color rgb<" << col.R << ", " << col.G << ", " << col.B << ">}" << std::endl;
    ofile << "      finish  {phong 0.2  diffuse 0.6}" << std::endl;
    ofile << "    }" << std::endl;
    ofile << "}" << std::endl;

    // Close the output file.
    ofile.close();
}

void WriteMeshPovray(const std::string& obj_filename,
                     const std::string& mesh_name,
                     const std::string& out_dir,
                     const ChColor& col,
                     const ChVector<>& pos,
                     const ChQuaternion<>& rot) {
    // Read trimesh from OBJ file
    geometry::ChTriangleMeshConnected trimesh;
    trimesh.LoadWavefrontMesh(obj_filename, false, false);

    // Generate output
    WriteMeshPovray(trimesh, mesh_name, out_dir, col, pos, rot);
}

// -----------------------------------------------------------------------------
// WriteCurvePovray
//
// Write the specified Bezier curve as a macro in a PovRay include file.
// -----------------------------------------------------------------------------
void WriteCurvePovray(const ChBezierCurve& curve,
                      const std::string& curve_name,
                      const std::string& out_dir,
                      double radius,
                      const ChColor& col) {
    int nP = 20;
    double dt = 1.0 / nP;
    size_t nS = curve.getNumPoints() - 1;

    // Open output file.
    std::string pov_filename = out_dir + "/" + curve_name + ".inc";
    std::ofstream ofile(pov_filename.c_str());

    ofile << "#declare " << curve_name << " = object {" << std::endl;
    ofile << "  sphere_sweep {" << std::endl;
    ofile << "    linear_spline " << nP* nS + 1 << "," << std::endl;

    ChVector<> v = curve.eval(0, 0.0);
    ofile << "        <" << v.x() << ", " << v.z() << ", " << v.x() << "> ," << radius << std::endl;

    for (int iS = 0; iS < nS; iS++) {
        for (int iP = 1; iP <= nP; iP++) {
            v = curve.eval(iS, iP * dt);
            ofile << "        <" << v.x() << ", " << v.z() << ", " << v.y() << "> ," << radius << std::endl;
        }
    }

    ofile << "    texture {" << std::endl;
    ofile << "      pigment {color rgb<" << col.R << ", " << col.G << ", " << col.B << ">}" << std::endl;
    ofile << "      finish  {phong 0.2  diffuse 0.6}" << std::endl;
    ofile << "     }" << std::endl;

    ofile << "  }" << std::endl;
    ofile << "}" << std::endl;

    // Close the output file.
    ofile.close();
}

}  // namespace utils
}  // namespace chrono


text:
.commentContainer .content
{
    background: #fefefe;
}

.subject a
{
    color: inherit;
}


text:
from dogs.cv.utils import load, dump, delete
import numpy

def sparse_vector_dot(a, b):
    result = 0
    for vector_column, value in a.items():
        if vector_column in b:
            result += b[vector_column] * value
    return result

def l2_norm(a):
    norm = 0
    for key, value in a.items():
        norm += value ** 2
    return norm

def cos_similarity(a, b):

    if (any(a) and any(b)):
        return sparse_vector_dot(a, b) / ((l2_norm(a) * l2_norm(b)) ** (1/2))
    else:
        return 0

def tf_idf(bow, N, postings_list):

    weights = {}
    for word in bow.keys():

        tf_idf = (bow[word] / len(bow.keys()) *
                  numpy.log(N / len(postings_list[word])))
        weights[word] = tf_idf
    return weights

class Database():
    def __init__(self, database_path=None, min_score=0.1):
        self.index_created = False
        self.database_path = database_path
        self.min_score = min_score

        self.documents = {}
        self.postings_list = {}
        self.load_from_disk()

    def load_from_disk(self):
        data = load(self.database_path)
        if (data):
            self.documents = data['documents']
            self.postings_list = data['postings']

    def save_to_disk(self):
        data = {'postings': self.postings_list, 'documents': self.documents}
        dump(data, self.database_path)

    def delete_index(self, index_name=None):
        delete(self.database_path)

    def insert(self, bow, image_path=None):
        image_id = image_path
        for word in bow:
            image_ids = self.postings_list.get(word, set())
            image_ids.add(image_id)
            self.postings_list[word] = image_ids
        self.documents[image_id] = bow

    def query_simple(self, query_bow):
        candidate_ids = set()
        for word in query_bow:
            candidate_ids = candidate_ids.union(
                self.postings_list.get(word, set())
            )

        candidates = []
        for image_id in list(candidate_ids):
            candidate_bow = self.documents[image_id]
            score = cos_similarity(query_bow, candidate_bow)
            candidates.append({'image_id': image_id, 'score': score})

        candidates = sorted(
            candidates,
            key=lambda x: x['score'],
            reverse=True,
        )

        # todo: filter out scores lower than min_score

        return {
            'hits': {
                'total': len(candidates),
                'hits': candidates,
            }
        }

    def query_tf_idf(self, query_bow, **kwargs):

        query_weights = tf_idf(
            query_bow, len(self.documents), self.postings_list)

        candidate_ids = set()

        for word in query_bow:
            candidate_ids = candidate_ids.union(
                self.postings_list.get(word, set())
            )

        candidates = []
        for image_id in list(candidate_ids):
            candidate_bow = self.documents[image_id]
            candidate_weights = tf_idf(
                candidate_bow, len(self.documents), self.postings_list)
            score = cos_similarity(query_weights, candidate_weights)
            candidates.append({'_id': image_id, '_score': score})

        candidates = sorted(
            candidates,
            key=lambda x: x['_score'],
            reverse=True,
        )

        # todo: filter out scores lower than min_score
        return {
            'hits': {
                'total': len(candidates),
                'hits': candidates,
            }
        }

    def query(self, query_bow, **kwargs):
        return self.query_simple(query_bow, **kwargs)
        # return self.query_tf_idf(query_bow, **kwargs)


text:
<!doctype html>
<link rel="stylesheet" href="s.css" />

Tests for recipes/form/skin/natural

    Note: Clicks on labels adjacent to inputs does not give focus (no for="" defined)

<form>
    Input in label,label text before input <input />

     <input /> Input in label,label text after input

        Label before <input />

        <input /> Label after

    Select in label,label text before input <select></select>

     <select></select> Select in label,label text after input

        Label before <select></select>

        <select></select> Label after

    Textarea in label,label text before input <textarea></textarea>

    <textarea></textarea> Textarea in label,label text after input

        Label before <textarea></textarea>

        <textarea></textarea> Label after

    <button>Button</button>

</form>


text:
require File.expand_path('../../../spec_helper', __FILE__)

describe "SystemCallError#errno" do
  it "needs to be reviewed for spec completeness"
end

describe "Errno::EINVAL.new" do
  it "can be called with no arguments" do
    exc = Errno::EINVAL.new
    exc.should be_an_instance_of(Errno::EINVAL)
    exc.errno.should == Errno::EINVAL::Errno
    exc.message.should == "Invalid argument"
  end

  it "accepts an optional custom message" do
    exc = Errno::EINVAL.new('custom message')
    exc.should be_an_instance_of(Errno::EINVAL)
    exc.errno.should == Errno::EINVAL::Errno
    exc.message.should == "Invalid argument - custom message"
  end

  it "accepts an optional custom message and location" do
    exc = Errno::EINVAL.new('custom message', 'location')
    exc.should be_an_instance_of(Errno::EINVAL)
    exc.errno.should == Errno::EINVAL::Errno
    exc.message.should == "Invalid argument @ location - custom message"
  end
end

describe "Errno::EMFILE" do
  it "can be subclassed" do
    ExceptionSpecs::EMFILESub = Class.new(Errno::EMFILE)
    exc = ExceptionSpecs::EMFILESub.new
    exc.should be_an_instance_of(ExceptionSpecs::EMFILESub)
  end
end

describe "Errno::EAGAIN" do
  # From http://jira.codehaus.org/browse/JRUBY-4747
  it "is the same class as Errno::EWOULDBLOCK if they represent the same errno value" do
    if Errno::EAGAIN::Errno == Errno::EWOULDBLOCK::Errno
      Errno::EAGAIN.should == Errno::EWOULDBLOCK
    else
      Errno::EAGAIN.should_not == Errno::EWOULDBLOCK
    end
  end
end


text:
import datetime
import os
import sys

import lib
from jinja2 import Environment, FileSystemLoader
from lib import nullstrip, slugify

# XXX Currently runs only from the project directory.
#     I am inclined to leave it that way for now

def mktopic(title):
    "Takes a list of the words of a topic title and builds the appropriate notebook file."
    os.chdir(lib.get_project_dir())
    template_env = Environment(loader=FileSystemLoader("data/templates"))
    # -t template would be nice, but this will do for now
    src_template = template_env.get_template("base.ipynb")
    now = datetime.datetime.today()
    title = " ".join(title)
    slug = lib.slugify(title)
    nb_name = slug+".ipynb"
    dst_file = os.path.join("nbsource", nb_name)
    render_context = {"slug": slug,
                      "title": title,
                      "date": now.date(),
                      "time": now.time(),
                      "src_file": dst_file,
                      "template": src_template.filename} # we are writing a source ...
    if os.path.isfile(dst_file):
        # If the topic exists do not overwrite it XXX [unless option set].
        sys.exit("file {} already exists".format(dst_file))
    dst_nb_file = open(dst_file, "w")
    nb_content = src_template.render(render_context)
    dst_nb_file.write(nb_content)
    dst_nb_file.close()

if __name__ == "__main__":
    # possible -d option for directory?
    if len(sys.argv) < 2:
        sys.exit("Sorry, I need a topic name")
    mktopic(sys.argv[1:])


text:
@interface MessageCreate : BaseModel
@property (nonatomic, copy) NSString *meeting_id;
@property (nonatomic, copy) NSString *id;
@end


text:
require 'mkmf'
require 'rbconfig'

LIBDIR      = RbConfig::CONFIG['libdir']
INCLUDEDIR  = RbConfig::CONFIG['includedir']

HEADER_DIRS = [
  # First search /opt/local for macports
  '/opt/local/include',

  # Then search /usr/local for people that installed from source
  '/usr/local/include',

  # Check the ruby install locations
  INCLUDEDIR,

  # Finally fall back to /usr
  '/usr/include',
]

LIB_DIRS = [
  # First search /opt/local for macports
  '/opt/local/lib',

  # Then search /usr/local for people that installed from source
  '/usr/local/lib',

  # Check the ruby install locations
  LIBDIR,

  # Finally fall back to /usr
  '/usr/lib',
]

dir_config('libpostal', HEADER_DIRS, LIB_DIRS)

$CFLAGS << " -std=gnu99"
$LIBS << " -lpostal"

create_makefile('ruby_postal/cpostal/parser')


text:
import ManageCheck from './ManageCheckView'
export default ManageCheck


text:
/**
 * <copyright>
 * </copyright>
 *
 * $Id$
 */
package gov.nasa.ensemble.dictionary;

import gov.nasa.ensemble.core.jscience.TemporalOffset;
import org.eclipse.emf.ecore.EObject;

/**
 *
 * A representation of the model object 'EActivity Resource Effect'.
 *
 *
 *

 * The following features are supported:
 *

 *
{@link gov.nasa.ensemble.dictionary.Effect#getDescription Description}

 *
{@link gov.nasa.ensemble.dictionary.Effect#getName Name}

 *
{@link gov.nasa.ensemble.dictionary.Effect#getStartOffset Start Offset}

 *
{@link gov.nasa.ensemble.dictionary.Effect#getEndOffset End Offset}

 *

 *

 *
 * @see gov.nasa.ensemble.dictionary.DictionaryPackage#getEffect()
 * @model interface="true" abstract="true" superTypes="gov.nasa.ensemble.dictionary.INamedDefinition"
 * @generated
 */
public interface Effect<T extends EResourceDef> extends EObject, INamedDefinition {
	/**
	 * Returns the value of the 'Description' attribute.
	 *
	 *

	 * If the meaning of the 'Description' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Description' attribute.
	 * @see #setDescription(String)
	 * @see gov.nasa.ensemble.dictionary.DictionaryPackage#getEffect_Description()
	 * @model
	 * @generated
	 */
	String getDescription();

	/**
	 * Sets the value of the '{@link gov.nasa.ensemble.dictionary.Effect#getDescription Description}' attribute.
	 *
	 *
	 * @param value the new value of the 'Description' attribute.
	 * @see #getDescription()
	 * @generated
	 */
	void setDescription(String value);

	/**
	 * Returns the value of the 'Name' attribute.
	 *
	 *
	 * @return the value of the 'Name' attribute.
	 * @see gov.nasa.ensemble.dictionary.DictionaryPackage#getEffect_Name()
	 * @model transient="true" changeable="false" volatile="true" derived="true"
	 * @generated
	 */
	@Override
	String getName();

	/**
	 * Returns the value of the 'Start Offset' attribute.
	 * The default value is "START, 0 s".
	 *
	 *

	 * If the meaning of the 'Start Offset' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Start Offset' attribute.
	 * @see #setStartOffset(TemporalOffset)
	 * @see gov.nasa.ensemble.dictionary.DictionaryPackage#getEffect_StartOffset()
	 * @model default="START, 0 s" dataType="gov.nasa.ensemble.core.jscience.TemporalOffset"
	 * @generated
	 */
	TemporalOffset getStartOffset();

	/**
	 * Sets the value of the '{@link gov.nasa.ensemble.dictionary.Effect#getStartOffset Start Offset}' attribute.
	 *
	 *
	 * @param value the new value of the 'Start Offset' attribute.
	 * @see #getStartOffset()
	 * @generated
	 */
	void setStartOffset(TemporalOffset value);

	/**
	 * Returns the value of the 'End Offset' attribute.
	 * The default value is "END, 0 s".
	 *
	 *

	 * If the meaning of the 'End Offset' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'End Offset' attribute.
	 * @see #setEndOffset(TemporalOffset)
	 * @see gov.nasa.ensemble.dictionary.DictionaryPackage#getEffect_EndOffset()
	 * @model default="END, 0 s" dataType="gov.nasa.ensemble.core.jscience.TemporalOffset"
	 * @generated
	 */
	TemporalOffset getEndOffset();

	/**
	 * Sets the value of the '{@link gov.nasa.ensemble.dictionary.Effect#getEndOffset End Offset}' attribute.
	 *
	 *
	 * @param value the new value of the 'End Offset' attribute.
	 * @see #getEndOffset()
	 * @generated
	 */
	void setEndOffset(TemporalOffset value);

	/**
	 *
	 *
	 * @model kind="operation"
	 * @generated
	 */
	T getDefinition();

} // EActivityResourceEffect


text:
package org.pentaho.di.core.database;

import org.pentaho.di.core.Const;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.util.EnvUtil;

/**
 * Contains SAP ERP system specific information through static final members
 *
 * @author Matt
 * @since  03-07-2005
 */

public class SAPR3DatabaseMeta extends BaseDatabaseMeta implements DatabaseInterface
{
    public static final String ATTRIBUTE_SAP_LANGUAGE = "SAPLanguage";
    public static final String ATTRIBUTE_SAP_SYSTEM_NUMBER = "SAPSystemNumber";
    public static final String ATTRIBUTE_SAP_CLIENT = "SAPClient";

	public int[] getAccessTypeList()
	{
		return new int[] { DatabaseMeta.TYPE_ACCESS_PLUGIN };
	}

	public int getDefaultDatabasePort()
	{
		return -1;
	}

	/**
	 * @return Whether or not the database can use auto increment type of fields (pk)
	 */
	public boolean supportsAutoInc()
	{
		return false;
	}

	public String getDriverClass()
	{
			return null;
	}

    public String getURL(String hostname, String port, String databaseName)
    {
		return null;
	}

	/**
	 * @return true if the database supports bitmap indexes
	 */
	public boolean supportsBitmapIndex()
	{
		return false;
	}

	/**
	 * @return true if the database supports synonyms
	 */
	public boolean supportsSynonyms()
	{
		return false;
	}

	/**
	 * Generates the SQL statement to add a column to the specified table
	 * @param tablename The table to add
	 * @param v The column defined as a value
	 * @param tk the name of the technical key field
	 * @param use_autoinc whether or not this field uses auto increment
	 * @param pk the name of the primary key field
	 * @param semicolon whether or not to add a semi-colon behind the statement.
	 * @return the SQL statement to add a column to the specified table
	 */
	public String getAddColumnStatement(String tablename, ValueMetaInterface v, String tk, boolean use_autoinc, String pk, boolean semicolon)
	{
		return null;
	}

	/**
	 * Generates the SQL statement to modify a column in the specified table
	 * @param tablename The table to add
	 * @param v The column defined as a value
	 * @param tk the name of the technical key field
	 * @param use_autoinc whether or not this field uses auto increment
	 * @param pk the name of the primary key field
	 * @param semicolon whether or not to add a semi-colon behind the statement.
	 * @return the SQL statement to modify a column in the specified table
	 */
	public String getModifyColumnStatement(String tablename, ValueMetaInterface v, String tk, boolean use_autoinc, String pk, boolean semicolon)
	{
		return null;
	}

	public String getFieldDefinition(ValueMetaInterface v, String tk, String pk, boolean use_autoinc, boolean add_fieldname, boolean add_cr)
	{
	    return null;
	}

	public String [] getReservedWords()
	{
		return null;
	}

    public String[] getUsedLibraries()
    {
        return new String[] { };
    }

	public String getDatabaseFactoryName() {
		return EnvUtil.getSystemProperty(Const.KETTLE_SAP_CONNECTION_FACTORY, Const.KETTLE_SAP_CONNECTION_FACTORY_DEFAULT_NAME);
	}

	/**
	 * @return true if this is a relational database you can explore.
	 * Return false for SAP, PALO, etc.
	 */
	public boolean isExplorable() {
		return false;
	}

}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections;
using System.Collections.Generic;
using Xunit;
using SortedList_SortedListUtils;

namespace SortedListNoGenIEnum
{
    public class Driver<K, V> where K : IComparableValue
    {
        private Test m_test;

        public Driver(Test test)
        {
            m_test = test;
        }

        public void GetEnumeratorBasic(K[] keys, V[] values)
        {
            SortedList<K, V> tbl = new SortedList<K, V>(new TestSortedList<K, V>(keys, values), new ValueKeyComparer<K>());
            IEnumerable enumerable = tbl;
            IEnumerator Enum = enumerable.GetEnumerator();
            //There are no guarantees on the order of elements in the HT
            List<K> kls = new List<K>();
            for (int i = 0; i < keys.Length; i++)
                kls.Add(keys[i]);
            List<V> vls = new List<V>();
            for (int i = 0; i < keys.Length; i++)
                vls.Add(values[i]);
            for (int i = 0; i < keys.Length; i++)
            {
                m_test.Eval(Enum.MoveNext());
                Object entry = Enum.Current;

                m_test.Eval(kls.Contains(((KeyValuePair<K, V>)entry).Key));
                kls.Remove(((KeyValuePair<K, V>)entry).Key);
                m_test.Eval(vls.Contains(((KeyValuePair<K, V>)entry).Value));
                vls.Remove(((KeyValuePair<K, V>)entry).Value);
            }

            for (int i = 0; i < keys.Length; i++)
                kls.Add(keys[i]);
            for (int i = 0; i < keys.Length; i++)
                vls.Add(values[i]);
            foreach (Object entry in enumerable)
            {
                m_test.Eval(kls.Contains(((KeyValuePair<K, V>)entry).Key));
                kls.Remove(((KeyValuePair<K, V>)entry).Key);
                m_test.Eval(vls.Contains(((KeyValuePair<K, V>)entry).Value));
                vls.Remove(((KeyValuePair<K, V>)entry).Value);
            }

            kls = new List<K>();
            for (int i = 0; i < keys.Length; i++)
                kls.Add(keys[i]);
            vls = new List<V>();
            for (int i = 0; i < keys.Length; i++)
                vls.Add(values[i]);
            m_test.Eval(Enum.MoveNext() == false);
        }
        public void GetEnumeratorValidations(K[] keys, V[] values, K nkey, V nvalue)
        {
            SortedList<K, V> tbl = new SortedList<K, V>(new TestSortedList<K, V>(keys, values), new ValueKeyComparer<K>());
            IEnumerable enumerable = tbl;
            IEnumerator Enum = enumerable.GetEnumerator();
            Object entry;

            try
            {
                entry = Enum.Current;
                m_test.Eval(false);
            }
            catch (InvalidOperationException)
            {
                m_test.Eval(true);
            }
            catch (Exception)
            {
                m_test.Eval(false);
            }

            Enum.Reset();

            for (int i = 0; i < keys.Length; i++)
            {
                m_test.Eval(Enum.MoveNext());
                entry = Enum.Current;
                //			m_test.Eval(entry.Key.Equals(keys[i]) && ( ((null==(object)entry.Value)&&(null==(object)values[i])) || entry.Value.Equals(values[i])));
            }
            m_test.Eval(Enum.MoveNext() == false);

            try
            {
                entry = Enum.Current;
                m_test.Eval(false);
            }
            catch (InvalidOperationException)
            {
                m_test.Eval(true);
            }
            catch (Exception)
            {
                m_test.Eval(false);
            }

            Enum = enumerable.GetEnumerator();
            Enum.MoveNext();
            tbl.Add(nkey, nvalue);

            try
            {
                Enum.MoveNext();
                m_test.Eval(false);
            }
            catch (InvalidOperationException)
            {
                m_test.Eval(true);
            }
            catch (Exception)
            {
                m_test.Eval(false);
            }
            try
            {
                Enum.Reset();
                m_test.Eval(false);
            }
            catch (InvalidOperationException)
            {
                m_test.Eval(true);
            }
            catch (Exception)
            {
                m_test.Eval(false);
            }
        }
    }

    public class Enumerator2
    {
        [Fact]
        public static void NoGenIEnumMain()
        {
            Test test = new Test();

            Driver<RefX1<int>, ValX1<string>> IntDriver = new Driver<RefX1<int>, ValX1<string>>(test);
            RefX1<int>[] intArr = new RefX1<int>[100];
            for (int i = 0; i < 100; i++)
            {
                intArr[i] = new RefX1<int>(i);
            }

            Driver<ValX1<string>, RefX1<int>> StringDriver = new Driver<ValX1<string>, RefX1<int>>(test);
            ValX1<string>[] stringArr = new ValX1<string>[100];
            for (int i = 0; i < 100; i++)
            {
                stringArr[i] = new ValX1<string>("SomeTestString" + i.ToString());
            }

            //Ref<Val>,Val<Ref>
            IntDriver.GetEnumeratorBasic(intArr, stringArr);
            IntDriver.GetEnumeratorBasic(new RefX1<int>[0], new ValX1<string>[0]);
            IntDriver.GetEnumeratorValidations(intArr, stringArr, new RefX1<int>(1000), new ValX1<string>("1000"));
            IntDriver.GetEnumeratorValidations(new RefX1<int>[0], new ValX1<string>[0], new RefX1<int>(1000), new ValX1<string>("1000"));

            //Val<Ref>,Ref<Val>
            StringDriver.GetEnumeratorBasic(stringArr, intArr);
            StringDriver.GetEnumeratorBasic(new ValX1<string>[0], new RefX1<int>[0]);
            StringDriver.GetEnumeratorValidations(stringArr, intArr, new ValX1<string>("1000"), new RefX1<int>(1000));
            StringDriver.GetEnumeratorValidations(new ValX1<string>[0], new RefX1<int>[0], new ValX1<string>("1000"), new RefX1<int>(1000));

            Assert.True(test.result);
        }
    }
}


text:
Garage Control with Arduino
===========================

Arduino Garage Control project including sketch and tutorial.

![alt text](http://i.imgur.com/b02XVBT.jpg "The End Result")

#Demo
[Watch it in action!](https://www.youtube.com/watch?v=utPfQMeuSUI)

#Overview
The purpose of this project was to create a DIY garage control utitlity that can be remotely controlled via my iPhone.
I chose for BLE (Bluetooth Low Energy a.k.a. Bluetooth 4.0) as it - what's in a name - very energy efficient and above all, has better connectivity (range + connectiontime) then its predecessors.
We certainly didn't want to reinvent the wheel as there are quite a few tutorials on the internet showing remotely controlled garages by a smartphone.
But it's not just a test project I really want to use it on a daily basis. Therefore it must be good, real good. And that meant, useful, fast and super easy to use.
A big plus for this implementation is that it will auomatically connect once the BLE shield is in range of your smartphone, no need to press the connect button (over and over).
Most of the time it takes <1 second to be connected once you open one of the apps!

#Apps
I wrote two iOS companion apps. Note that you need to compile these yourself, the apps are not available on the App Store.
* [Carage Controller](https://github.com/piejanssens/Garage-Control-iOS) - Monitor sensors and control the garage door
* [My Garage](https://github.com/piejanssens/My-Garage-iOS) - Only function is to connect and immediately send the door switch command and close. This can be used with Siri by giving the command "Open my garage" which will just open the app and let it do it's thing.

Both apps are using a modified BLE Shield library and will keep scanning for the device until it's found and then connect. This is very useful since (in case your so lucky that your car supports this) you can drive up to your house, press the steering wheel button (or activate Siri with the home button) and say "Open my garage". As soon as you come in range of the Arduino it will open the garage!

#Requirements
The requirements describe the parts you need to create the same Arduino project as I did and is almost plug and play (that is whilst using my sketch and iOS app). It's up to you to decide what you want t$

* Automated garage that can be controlled with a relay. What's a relay?
* Power source (I used the 24V power source from the garage door itself.)
* Arduino Uno or compatible Arduino board
* [Bluetooth BLE Shield ](http://redbearlab.com/bleshield/)
* [Grove Base Shield](http://www.seeedstudio.com/depot/grove-base-shield-p-754.html)
* [Grove Relay](http://www.seeedstudio.com/depot/grove-relay-p-769.html?cPath=39_42) or other relay
* Magnetic switch: Any magnetic window switch will do, some are better (stronger) than others. I used the ones displayed in this picture which are great!
* [Grove (analog) Light Sensor](http://www.seeedstudio.com/depot/grove-light-sensor-p-746.html?cPath=25_27)
* [Grove (analog) Temperature Sensor](http://www.seeedstudio.com/depot/grove-temperature-sensor-p-774.html?cPath=25_27)
* [Grove 4pin connector cables](http://www.seeedstudio.com/depot/grove-universal-4-pin-buckled-5cm-cable-5-pcs-pack-p-925.html?cPath=98_106_57)
* A box to fit everything in
* Tools (drill, screwdriver, wires, ...)
* Optional [Power Converter e.g. 24V to 5V](http://www.seeedstudio.com/depot/cptc5-power-converter-12v24v-switch-to-5v-p-1066.html?cPath=1_4) to power the Arduino
* Optional but recommended 2.4GHz SMA antenna. Caution: you need an antenna with middle pin or adapter.
* [RedBearLab Arduino BLE Library](https://github.com/RedBearLab/BLEShield)

#How To
1. Mount the grove base shield on the BLE shield, and mount the BLE shield on the Arduino
2. Connect the light sensor connector with A3 on the base shield
3. Connect the temperature sensor connector with A2 on the base shield
4. Connect the relay with D4 on the base shield
5. Cut one grove connector cable in two.
6. Plug the connector side in D6 and wirethe black and yellow cables to either side of the magnetic switch.
7. Upload the sketch
8. Open the console and enable debugging (= send 'd') or connect with one of the companion iOS apps
9. Optional add a random authentication bytes "handshake" to both the sketch and the iOS app. These bytes are sent before switching the relay. Without this handshake the command to open the garage door will not be accepted.


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Gdns' Bull. , Singapore. Supplement 2: 61 (1991)

#### Original name
Trogia omphalinoides var. omphalinoides Corner

### Remarks
null


text:
package security

import (
	"bytes"
	"crypto/sha256"
	"fmt"
	"os"

	"github.com/pkg/errors"

	"golang.org/x/crypto/bcrypt"
	"golang.org/x/crypto/ssh/terminal"
)

// BCrypt cost should increase along with computation power.
// For estimates, see: http://security.stackexchange.com/questions/17207/recommended-of-rounds-for-bcrypt
// For now, we use the library's default cost.
const bcryptCost = bcrypt.DefaultCost

// ErrEmptyPassword indicates that an empty password was attempted to be set.
var ErrEmptyPassword = errors.New("empty passwords are not permitted")

func compareHashAndPassword(hashedPassword []byte, password string) error {
	h := sha256.New()
	return bcrypt.CompareHashAndPassword(hashedPassword, h.Sum([]byte(password)))
}

// HashPassword takes a raw password and returns a bcrypt hashed password.
func HashPassword(password string) ([]byte, error) {
	h := sha256.New()
	return bcrypt.GenerateFromPassword(h.Sum([]byte(password)), bcryptCost)
}

// PromptForPassword prompts for a password.
// This is meant to be used when using a password.
func PromptForPassword() (string, error) {
	fmt.Print("Enter password: ")
	password, err := terminal.ReadPassword(int(os.Stdin.Fd()))
	if err != nil {
		return "", err
	}
	// Make sure stdout moves on to the next line.
	fmt.Print("\n")

	return string(password), nil
}

// PromptForPasswordTwice prompts for a password twice, returning the read string if
// they match, or an error.
// This is meant to be used when setting a password.
func PromptForPasswordTwice() (string, error) {
	fmt.Print("Enter password: ")
	one, err := terminal.ReadPassword(int(os.Stdin.Fd()))
	if err != nil {
		return "", err
	}
	if len(one) == 0 {
		return "", ErrEmptyPassword
	}
	fmt.Print("\nConfirm password: ")
	two, err := terminal.ReadPassword(int(os.Stdin.Fd()))
	if err != nil {
		return "", err
	}
	// Make sure stdout moves on to the next line.
	fmt.Print("\n")
	if !bytes.Equal(one, two) {
		return "", errors.New("password mismatch")
	}

	return string(one), nil
}

// PromptForPasswordAndHash prompts for a password twice and returns the bcrypt
// hash.
func PromptForPasswordAndHash() ([]byte, error) {
	password, err := PromptForPasswordTwice()
	if err != nil {
		return nil, err
	}
	if password == "" {
		return nil, nil
	}
	return HashPassword(password)
}


text:
#include "tensorflow/compiler/jit/build_xla_ops_pass.h"

#include "tensorflow/cc/framework/ops.h"
#include "tensorflow/cc/ops/array_ops.h"
#include "tensorflow/cc/ops/resource_variable_ops.h"
#include "tensorflow/cc/ops/standard_ops.h"
#include "tensorflow/compiler/jit/defs.h"
#include "tensorflow/compiler/jit/encapsulate_subgraphs_pass.h"
#include "tensorflow/compiler/jit/node_matchers.h"
#include "tensorflow/core/common_runtime/device_factory.h"
#include "tensorflow/core/graph/algorithm.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/public/session_options.h"

namespace tensorflow {
namespace {

class BuildXlaOpsTest : public ::testing::Test {
 protected:
  void SetUp() override {
    // This is needed to register the XLA_* devices.
    CHECK(DeviceFactory::AddDevices(
              SessionOptions(), "/job:localhost/replica:0/task:0", &devices_)
              .ok());
  }

 private:
  std::vector<std::unique_ptr<Device>> devices_;
};

using ::tensorflow::testing::FindNodeByName;
using ::tensorflow::testing::matchers::Attr;
using ::tensorflow::testing::matchers::CtrlDeps;
using ::tensorflow::testing::matchers::Inputs;
using ::tensorflow::testing::matchers::NodeWith;
using ::tensorflow::testing::matchers::Op;
using ::tensorflow::testing::matchers::Out;
using ::testing::_;

Status BuildXlaOps(const Scope& s, const FunctionDefLibrary& fdef_lib,
                   std::unique_ptr<Graph>* result) {
  auto graph = absl::make_unique<Graph>(OpRegistry::Global());
  TF_RETURN_IF_ERROR(s.ToGraph(graph.get()));
  FunctionLibraryDefinition flib_def(graph->op_registry(), fdef_lib);

  // Assign all nodes to the CPU device.
  static const char* kCpuDevice = "/job:localhost/replica:0/task:0/cpu:0";
  for (Node* n : graph->nodes()) {
    if (n->requested_device().empty()) {
      n->set_assigned_device_name(kCpuDevice);
    } else {
      n->set_assigned_device_name(n->requested_device());
    }
  }

  FixupSourceAndSinkEdges(graph.get());

  SessionOptions session_options;
  GraphOptimizationPassOptions opt_options;
  opt_options.session_options = &session_options;
  opt_options.flib_def = &flib_def;
  opt_options.graph = &graph;
  BuildXlaOpsPass pass(/*enable_lazy_compilation=*/true);
  TF_RETURN_IF_ERROR(pass.Run(opt_options));
  VLOG(3) << graph->ToGraphDefDebug().DebugString();
  *result = std::move(graph);
  return Status::OK();
}

Status MakeXlaCompiledKernel(Graph* graph, const string& callee_name,
                             const string& node_name, int num_constant_args,
                             int num_resource_args, Node** result) {
  NodeDef call_node;
  call_node.set_name(node_name);
  call_node.set_op(callee_name);
  AddNodeAttr(kXlaCompiledKernelAttr, true, &call_node);
  AddNodeAttr(kXlaNumConstantArgsAttr, num_constant_args, &call_node);
  AddNodeAttr(kXlaNumResourceArgsAttr, num_resource_args, &call_node);
  Status s;
  *result = graph->AddNode(call_node, &s);
  return s;
}

Status MakeXlaCompiledKernel(Graph* graph, const string& callee_name,
                             const string& node_name, Node** result) {
  return MakeXlaCompiledKernel(graph, callee_name, node_name,
                               /*num_constant_args=*/0, /*num_resource_args=*/0,
                               result);
}

Node* MakeWrite(const Scope& scope, Output value_to_write, const string& id) {
  Output var_handle = ops::VarHandleOp(scope.WithOpName("Var_" + id), DT_FLOAT,
                                       TensorShape({}));
  ops::AssignVariableOp assign_op(scope.WithOpName("Assignee_" + id),
                                  var_handle, value_to_write);
  return assign_op.operation.node();
}

Node* MakeWrite(const Scope& scope, const string& id) {
  return MakeWrite(
      scope, ops::Const(scope.WithOpName("ValueToAssign" + id), 1.0f), id);
}

FunctionDefLibrary CreateFunctionDefLibWithConstFunction(const string& name) {
  FunctionDefLibrary fdef_lib;
  FunctionDef func = FunctionDefHelper::Create(
      /*function_name=*/name, /*in_def=*/{}, /*out_def=*/{"out: float"},
      /*attr_def*/
      {}, /*node_def=*/{FunctionDefHelper::Const("one", 1.0f)},
      /*ret_def=*/{{"out", "out:output:0"}});
  *fdef_lib.add_function() = std::move(func);
  return fdef_lib;
}

TEST_F(BuildXlaOpsTest, ControlDepsPreserved) {
  const char* kXlaDeviceName = "/job:worker/replica:0/task:0/device:XLA_CPU:0";
  Scope root = Scope::NewRootScope().WithDevice(kXlaDeviceName).ExitOnError();

  FunctionDefLibrary fdef_lib =
      CreateFunctionDefLibWithConstFunction("cluster_0");
  TF_ASSERT_OK(root.graph()->AddFunctionLibrary(fdef_lib));
  Node* call;
  TF_ASSERT_OK(MakeXlaCompiledKernel(root.graph(), "cluster_0", "C", &call));
  call->set_requested_device(kXlaDeviceName);
  Node* write_op = MakeWrite(root, "write");
  root.graph()->AddControlEdge(call, write_op);

  std::unique_ptr<Graph> graph;
  TF_ASSERT_OK(BuildXlaOps(root, fdef_lib, &graph));

  Node* write_op_new = FindNodeByName(graph.get(), write_op->name());
  ASSERT_NE(write_op_new, nullptr);
  EXPECT_THAT(write_op_new, NodeWith(CtrlDeps(NodeWith(Op("_XlaRun")))));
}

TEST_F(BuildXlaOpsTest, CleanFailureOnBogusAttr) {
  Scope root = Scope::NewRootScope().ExitOnError();

  FunctionDefLibrary fdef_lib =
      CreateFunctionDefLibWithConstFunction("cluster_0");
  TF_ASSERT_OK(root.graph()->AddFunctionLibrary(fdef_lib));

  Node* call;
  TF_ASSERT_OK(
      MakeXlaCompiledKernel(root.graph(), "cluster_0", "C", 100, 100, &call));

  Node* write_op = MakeWrite(root, "write");
  root.graph()->AddControlEdge(call, write_op);

  std::unique_ptr<Graph> graph;
  Status failure_status = BuildXlaOps(root, fdef_lib, &graph);
  ASSERT_FALSE(failure_status.ok());
  EXPECT_EQ(failure_status.code(), error::INVALID_ARGUMENT);
}

TEST_F(BuildXlaOpsTest, OnNonXlaDevice) {
  Scope root = Scope::NewRootScope().ExitOnError();

  FunctionDefLibrary fdef_lib =
      CreateFunctionDefLibWithConstFunction("cluster_0");
  TF_ASSERT_OK(root.graph()->AddFunctionLibrary(fdef_lib));

  Node* call;
  TF_ASSERT_OK(MakeXlaCompiledKernel(root.graph(), "cluster_0", "C", &call));
  TF_ASSERT_OK(root.DoShapeInference(call));

  Node* write_op = MakeWrite(root, Output(call), "write_result");

  auto xla_compile = NodeWith(Op("_XlaCompile"), Attr("must_compile", false));
  auto predicated_compilation_key =
      NodeWith(Op("Switch"), Inputs(Out(0, xla_compile), Out(1, xla_compile)));
  auto xla_run =
      NodeWith(Op("_XlaRun"), Inputs(Out(1, predicated_compilation_key)));
  auto tf_call =
      NodeWith(Op("PartitionedCall"),
               CtrlDeps(NodeWith(Op("Identity"),
                                 Inputs(Out(0, predicated_compilation_key)))));
  auto merge = NodeWith(Op("Merge"), Inputs(Out(tf_call), Out(xla_run)));
  auto assign_var = NodeWith(Op("AssignVariableOp"), Inputs(_, Out(merge)));

  std::unique_ptr<Graph> graph;
  TF_ASSERT_OK(BuildXlaOps(root, fdef_lib, &graph));

  Node* write_op_new = FindNodeByName(graph.get(), write_op->name());
  ASSERT_NE(write_op_new, nullptr);
  EXPECT_THAT(write_op_new, assign_var);
}

TEST_F(BuildXlaOpsTest, OnXlaDevice) {
  const char* kXlaDeviceName = "/job:worker/replica:0/task:0/device:XLA_CPU:0";
  Scope root = Scope::NewRootScope().WithDevice(kXlaDeviceName).ExitOnError();

  FunctionDefLibrary fdef_lib =
      CreateFunctionDefLibWithConstFunction("cluster_0");
  TF_ASSERT_OK(root.graph()->AddFunctionLibrary(fdef_lib));

  Node* call;
  TF_ASSERT_OK(MakeXlaCompiledKernel(root.graph(), "cluster_0", "C", &call));
  call->set_requested_device(kXlaDeviceName);
  TF_ASSERT_OK(root.DoShapeInference(call));

  Node* write_op = MakeWrite(root, Output(call), "write_result");

  std::unique_ptr<Graph> graph;
  TF_ASSERT_OK(BuildXlaOps(root, fdef_lib, &graph));

  auto xla_op =
      NodeWith(Op("_XlaRun"), Inputs(Out(NodeWith(Op("_XlaCompile")))));
  auto assign_var =
      NodeWith(Op("AssignVariableOp"), Inputs(Out(NodeWith()), Out(xla_op)));

  Node* write_op_new = FindNodeByName(graph.get(), write_op->name());
  ASSERT_NE(write_op_new, nullptr);
  EXPECT_THAT(write_op_new, assign_var);
}

TEST_F(BuildXlaOpsTest, NoExtraMergeForEdgeToSink) {
  Scope root = Scope::NewRootScope().ExitOnError();

  FunctionDefLibrary fdef_lib =
      CreateFunctionDefLibWithConstFunction("cluster_0");
  TF_ASSERT_OK(root.graph()->AddFunctionLibrary(fdef_lib));
  Node* call;
  TF_ASSERT_OK(MakeXlaCompiledKernel(root.graph(), "cluster_0", "C", &call));

  std::unique_ptr<Graph> graph;
  TF_ASSERT_OK(BuildXlaOps(root, fdef_lib, &graph));

  Node* sink_node = graph->sink_node();
  EXPECT_THAT(sink_node, NodeWith(CtrlDeps(NodeWith(Op("_XlaRun")),
                                           NodeWith(Op("PartitionedCall")),
                                           NodeWith(Op("NoOp")))));
}
}  // namespace
}  // namespace tensorflow


text:
import sys
sys.path.append("..")

import time

from Plurr import Plurr

p = Plurr()
x = 100000

start = time.clock()

for i in xrange(x):
  dummy = p.locale('ru')

end = time.clock()
time = end - start
print('Execution time ({0} calls): {1} sec ({2} ms per call)'.format(x, time, time * 1000 / x))