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

using EventFlow.Core;
using EventFlow.Core.RetryStrategies;
using EventFlow.Logs;
using EventFlow.PostgreSql.Connections;
using EventFlow.ReadStores;
using EventFlow.Sql.ReadModels;

namespace EventFlow.PostgreSql.ReadStores
{
    public class PostgreSqlReadModelStore<TReadModel> : SqlReadModelStore<IPostgreSqlConnection, TReadModel>, IPostgresReadModelStore<TReadModel>
        where TReadModel : class, IReadModel
    {
        public PostgreSqlReadModelStore(
            ILog log,
            IPostgreSqlConnection connection,
            IReadModelSqlGenerator readModelSqlGenerator,
            IReadModelFactory<TReadModel> readModelFactory,
            ITransientFaultHandler<IOptimisticConcurrencyRetryStrategy> transientFaultHandler)
            : base(log, connection, readModelSqlGenerator, readModelFactory, transientFaultHandler)
        {
        }
    }
}


text:
#region S# License

#endregion S# License
namespace StockSharp.Transaq.Native.Responses
{
	using System.Collections.Generic;

	internal class CandleKindsResponse : BaseResponse
	{
		public IEnumerable<CandleKind> Kinds { get; internal set; }
	}

	internal class CandleKind
	{
		public int Id { get; set; }
		public int Period { get; set; }
		public string Name { get; set; }
	}
}

redpajama_set_name: RedPajamaGithub


text:
name             'wp_setup'
maintainer       'chrisD'
maintainer_email 'chris.duong83@gmail.com'
license          'Apache 2.0'
description      'Installs/Configures wp_setup'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version          '0.1.0'


text:
<?php

namespace App\Http\Util;
/**
 * 图片工具类
 * Created by PhpStorm.
 * Author: jwu049
 * Since: 2017/7/13 11:52
 */
class ImageUtil
{
    //允许上传的图片类型
    private static $__allowed_image_types = ['jpeg', 'jpg', 'gif', 'gpeg', 'png'];

    /**
     * 获取允许上传的图片类型
     * @return array
     */
    public static function getAllowedImageTypes()
    {
        return self::$__allowed_image_types;
    }

    public static function getImageName($image_path)
    {
        if(empty($image_path)) {
            return '';
        }
        $image_info = explode('/', $image_path);
        return end($image_info);
    }

    public static function getImageExtension($image_name)
    {
        if(empty($image_name)) {
            return '';
        }
        $extension_info = explode('.', $image_name);
        return end($extension_info);
    }

}


text:
package com.datamountaineer.streamreactor.connect.cassandra.sink

import com.datamountaineer.streamreactor.connect.cassandra.CassandraConnection
import com.datamountaineer.streamreactor.connect.cassandra.config.{CassandraConfigConstants, CassandraConfigSink, CassandraSettings}
import com.datamountaineer.streamreactor.connect.errors.ErrorPolicyEnum
import com.typesafe.scalalogging.slf4j.StrictLogging
import org.apache.kafka.connect.errors.ConnectException
import org.apache.kafka.connect.sink.SinkTaskContext

import scala.util.{Failure, Success, Try}

//Factory to build
object CassandraWriter extends StrictLogging {
  def apply(connectorConfig: CassandraConfigSink, context: SinkTaskContext): CassandraJsonWriter = {

    val connection = Try(CassandraConnection(connectorConfig)) match {
      case Success(s) => s
      case Failure(f) => throw new ConnectException(s"Couldn't connect to Cassandra.", f)
    }

    val settings = CassandraSettings.configureSink(connectorConfig)
    //if error policy is retry set retry interval
    if (settings.errorPolicy.equals(ErrorPolicyEnum.RETRY)) {
      context.timeout(connectorConfig.getString(CassandraConfigConstants.ERROR_RETRY_INTERVAL).toLong)
    }

    new CassandraJsonWriter(connection, settings)
  }
}


text:
#include <cstring>
#include <cassert>
#include <boost/lexical_cast.hpp>
#include <boost/regex.hpp>
#include <string>
#include <atomic>
#include "HTTPProxy.h"
#include "util.h"
#include "Identity.h"
#include "Streaming.h"
#include "Destination.h"
#include "ClientContext.h"
#include "I2PEndian.h"
#include "I2PTunnel.h"
#include "Config.h"

namespace i2p
{
namespace proxy
{
	static const size_t http_buffer_size = 8192;
	class HTTPProxyHandler: public i2p::client::I2PServiceHandler, public std::enable_shared_from_this<HTTPProxyHandler>
	{
		private:
			enum state
			{
				GET_METHOD,
				GET_HOSTNAME,
				GET_HTTPV,
				GET_HTTPVNL, //TODO: fallback to finding HOst: header if needed
				DONE
			};

			void EnterState(state nstate);
			bool HandleData(uint8_t *http_buff, std::size_t len);
			void HandleSockRecv(const boost::system::error_code & ecode, std::size_t bytes_transfered);
			void Terminate();
			void AsyncSockRead();
			void HTTPRequestFailed(/*std::string message*/);
			void RedirectToJumpService();
			void ExtractRequest();
			bool IsI2PAddress();
			bool ValidateHTTPRequest();
			void HandleJumpServices();
			bool CreateHTTPRequest(uint8_t *http_buff, std::size_t len);
			void SentHTTPFailed(const boost::system::error_code & ecode);
			void HandleStreamRequestComplete (std::shared_ptr<i2p::stream::Stream> stream);

			uint8_t m_http_buff[http_buffer_size];
			std::shared_ptr<boost::asio::ip::tcp::socket> m_sock;
			std::string m_request; //Data left to be sent
			std::string m_url; //URL
			std::string m_method; //Method
			std::string m_version; //HTTP version
			std::string m_address; //Address
			std::string m_path; //Path
			int m_port; //Port
			state m_state;//Parsing state

		public:

			HTTPProxyHandler(HTTPProxyServer * parent, std::shared_ptr<boost::asio::ip::tcp::socket> sock) :
				I2PServiceHandler(parent), m_sock(sock)
				{ EnterState(GET_METHOD); }
			~HTTPProxyHandler() { Terminate(); }
			void Handle () { AsyncSockRead(); }
	};

	void HTTPProxyHandler::AsyncSockRead()
	{
		LogPrint(eLogDebug, "HTTPProxy: async sock read");
		if(m_sock) {
			m_sock->async_receive(boost::asio::buffer(m_http_buff, http_buffer_size),
						std::bind(&HTTPProxyHandler::HandleSockRecv, shared_from_this(),
								std::placeholders::_1, std::placeholders::_2));
		} else {
			LogPrint(eLogError, "HTTPProxy: no socket for read");
		}
	}

	void HTTPProxyHandler::Terminate() {
		if (Kill()) return;
		if (m_sock)
		{
			LogPrint(eLogDebug, "HTTPProxy: close sock");
			m_sock->close();
			m_sock = nullptr;
		}
		Done(shared_from_this());
	}

	/* All hope is lost beyond this point */
	//TODO: handle this apropriately
	void HTTPProxyHandler::HTTPRequestFailed(/*HTTPProxyHandler::errTypes error*/)
	{
		static std::string response = "HTTP/1.0 500 Internal Server Error\r\nContent-type: text/html\r\nContent-length: 0\r\n";
		boost::asio::async_write(*m_sock, boost::asio::buffer(response,response.size()),
					 std::bind(&HTTPProxyHandler::SentHTTPFailed, shared_from_this(), std::placeholders::_1));
	}

	void HTTPProxyHandler::RedirectToJumpService(/*HTTPProxyHandler::errTypes error*/)
	{
		std::stringstream response;
		std::string httpAddr; i2p::config::GetOption("http.address", httpAddr);
		uint16_t    httpPort; i2p::config::GetOption("http.port", httpPort);

		response << "HTTP/1.1 302 Found\r\nLocation: http://" << httpAddr << ":" << httpPort << "/?jumpservices=&address=" << m_address << "\r\n\r\n";
		boost::asio::async_write(*m_sock, boost::asio::buffer(response.str (),response.str ().length ()),
					 std::bind(&HTTPProxyHandler::SentHTTPFailed, shared_from_this(), std::placeholders::_1));
	}

	void HTTPProxyHandler::EnterState(HTTPProxyHandler::state nstate)
	{
		m_state = nstate;
	}

	void HTTPProxyHandler::ExtractRequest()
	{
		LogPrint(eLogDebug, "HTTPProxy: request: ", m_method, " ", m_url);
		std::string server="";
		std::string port="80";
		boost::regex rHTTP("http://(.*?)(:(\\d+))?(/.*)");
		boost::smatch m;
		std::string path;
		if(boost::regex_search(m_url, m, rHTTP, boost::match_extra))
		{
			server=m[1].str();
			if (m[2].str() != "")  port=m[3].str();
			path=m[4].str();
		}
		LogPrint(eLogDebug, "HTTPProxy: server: ", server, ", port: ", port, ", path: ", path);
		m_address = server;
		m_port = boost::lexical_cast<int>(port);
		m_path = path;
	}

	bool HTTPProxyHandler::ValidateHTTPRequest()
	{
		if ( m_version != "HTTP/1.0" && m_version != "HTTP/1.1" )
		{
			LogPrint(eLogError, "HTTPProxy: unsupported version: ", m_version);
			HTTPRequestFailed(); //TODO: send right stuff
			return false;
		}
		return true;
	}

	void HTTPProxyHandler::HandleJumpServices()
	{
		static const char * helpermark1 = "?i2paddresshelper=";
		static const char * helpermark2 = "&i2paddresshelper=";
		size_t addressHelperPos1 = m_path.rfind (helpermark1);
		size_t addressHelperPos2 = m_path.rfind (helpermark2);
		size_t addressHelperPos;
		if (addressHelperPos1 == std::string::npos)
		{
			if (addressHelperPos2 == std::string::npos)
				return; //Not a jump service
			else
				addressHelperPos = addressHelperPos2;
		}
		else
		{
			if (addressHelperPos2 == std::string::npos)
				addressHelperPos = addressHelperPos1;
			else if ( addressHelperPos1 > addressHelperPos2 )
				addressHelperPos = addressHelperPos1;
			else
				addressHelperPos = addressHelperPos2;
		}
		auto base64 = m_path.substr (addressHelperPos + strlen(helpermark1));
		base64 = i2p::util::http::urlDecode(base64); //Some of the symbols may be urlencoded
		LogPrint (eLogInfo, "HTTPProxy: jump service for ", m_address, ", inserting to address book");
		//TODO: this is very dangerous and broken. We should ask the user before doing anything see http://pastethis.i2p/raw/pn5fL4YNJL7OSWj3Sc6N/
		//TODO: we could redirect the user again to avoid dirtiness in the browser
		i2p::client::context.GetAddressBook ().InsertAddress (m_address, base64);
		m_path.erase(addressHelperPos);
	}

	bool HTTPProxyHandler::IsI2PAddress()
	{
		auto pos = m_address.rfind (".i2p");
		if (pos != std::string::npos && (pos+4) == m_address.length ())
		{
			return true;
		}
		return false;
	}

	bool HTTPProxyHandler::CreateHTTPRequest(uint8_t *http_buff, std::size_t len)
	{
		ExtractRequest(); //TODO: parse earlier
		if (!ValidateHTTPRequest()) return false;
		HandleJumpServices();

		i2p::data::IdentHash identHash;
		if (IsI2PAddress ())
		{
			if (!i2p::client::context.GetAddressBook ().GetIdentHash (m_address, identHash)){
				RedirectToJumpService();
				return false;
			}
		}

		m_request = m_method;
		m_request.push_back(' ');
		m_request += m_path;
		m_request.push_back(' ');
		m_request += m_version;
		m_request.push_back('\r');
		m_request.push_back('\n');
		m_request.append("Connection: close\r\n");
		// TODO: temporary shortcut. Must be implemented properly
		uint8_t * eol = nullptr;
		bool isEndOfHeader = false;
		while (!isEndOfHeader && len && (eol = (uint8_t *)memchr (http_buff, '\r', len)))
		{
			if (eol)
			{
				*eol = 0; eol++;
				if (strncmp ((const char *)http_buff, "Referer", 7) && strncmp ((const char *)http_buff, "Connection", 10)) // strip out referer and connection
				{
					if (!strncmp ((const char *)http_buff, "User-Agent", 10)) // replace UserAgent
						m_request.append("User-Agent: MYOB/6.66 (AN/ON)");
					else
						m_request.append ((const char *)http_buff);
					m_request.append ("\r\n");
				}
				isEndOfHeader = !http_buff[0];
				auto l = eol - http_buff;
				http_buff = eol;
				len -= l;
				if (len > 0) // \r
				{
					http_buff++;
					len--;
				}
			}
		}
		m_request.append(reinterpret_cast<const char *>(http_buff),len);
		return true;
	}

	bool HTTPProxyHandler::HandleData(uint8_t *http_buff, std::size_t len)
	{
		while (len > 0)
		{
			//TODO: fallback to finding HOst: header if needed
			switch (m_state)
			{
				case GET_METHOD:
					switch (*http_buff)
					{
						case ' ': EnterState(GET_HOSTNAME); break;
						default: m_method.push_back(*http_buff); break;
					}
				break;
				case GET_HOSTNAME:
					switch (*http_buff)
					{
						case ' ': EnterState(GET_HTTPV); break;
						default: m_url.push_back(*http_buff); break;
					}
				break;
				case GET_HTTPV:
					switch (*http_buff)
					{
						case '\r': EnterState(GET_HTTPVNL); break;
						default: m_version.push_back(*http_buff); break;
					}
				break;
				case GET_HTTPVNL:
					switch (*http_buff)
					{
						case '\n': EnterState(DONE); break;
						default:
							LogPrint(eLogError, "HTTPProxy: rejected invalid request ending with: ", ((int)*http_buff));
							HTTPRequestFailed(); //TODO: add correct code
							return false;
					}
				break;
				default:
					LogPrint(eLogError, "HTTPProxy: invalid state: ", m_state);
					HTTPRequestFailed(); //TODO: add correct code 500
					return false;
			}
			http_buff++;
			len--;
			if (m_state == DONE)
				return CreateHTTPRequest(http_buff,len);
		}
		return true;
	}

	void HTTPProxyHandler::HandleSockRecv(const boost::system::error_code & ecode, std::size_t len)
	{
		LogPrint(eLogDebug, "HTTPProxy: sock recv: ", len, " bytes");
		if(ecode)
		{
			LogPrint(eLogWarning, "HTTPProxy: sock recv got error: ", ecode);
			Terminate();
			return;
		}

		if (HandleData(m_http_buff, len))
		{
			if (m_state == DONE)
			{
				LogPrint(eLogDebug, "HTTPProxy: requested: ", m_url);
				GetOwner()->CreateStream (std::bind (&HTTPProxyHandler::HandleStreamRequestComplete,
						shared_from_this(), std::placeholders::_1), m_address, m_port);
			}
			else
				AsyncSockRead();
		}

	}

	void HTTPProxyHandler::SentHTTPFailed(const boost::system::error_code & ecode)
	{
		if (ecode)
			LogPrint (eLogError, "HTTPProxy: Closing socket after sending failure because: ", ecode.message ());
		Terminate();
	}

	void HTTPProxyHandler::HandleStreamRequestComplete (std::shared_ptr<i2p::stream::Stream> stream)
	{
		if (stream)
		{
			if (Kill()) return;
			LogPrint (eLogInfo, "HTTPProxy: New I2PTunnel connection");
			auto connection = std::make_shared<i2p::client::I2PTunnelConnection>(GetOwner(), m_sock, stream);
			GetOwner()->AddHandler (connection);
			connection->I2PConnect (reinterpret_cast<const uint8_t*>(m_request.data()), m_request.size());
			Done(shared_from_this());
		}
		else
		{
			LogPrint (eLogError, "HTTPProxy: error when creating the stream, check the previous warnings for more info");
			HTTPRequestFailed(); // TODO: Send correct error message host unreachable
		}
	}

	HTTPProxyServer::HTTPProxyServer(const std::string& address, int port, std::shared_ptr<i2p::client::ClientDestination> localDestination):
		TCPIPAcceptor(address, port, localDestination ? localDestination : i2p::client::context.GetSharedLocalDestination ())
	{
	}

	std::shared_ptr<i2p::client::I2PServiceHandler> HTTPProxyServer::CreateHandler(std::shared_ptr<boost::asio::ip::tcp::socket> socket)
	{
		return std::make_shared<HTTPProxyHandler> (this, socket);
	}

}
}


text:
package io.bxbxbai.zhuanlan.utils;

import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Message;
import android.view.InputEvent;
import android.view.KeyEvent;
import android.webkit.*;

/**
 * Created by xuebin on 15/7/8.
 */
public class ZhuanlanWebViewClient extends WebViewClient {

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        return super.shouldOverrideUrlLoading(view, url);
    }

    @Override
    public void onLoadResource(WebView view, String url) {
        super.onLoadResource(view, url);
    }

    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
        return super.shouldInterceptRequest(view, request);
    }

    @Override
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        super.onReceivedError(view, errorCode, description, failingUrl);
    }

    @Override
    public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
        super.doUpdateVisitedHistory(view, url, isReload);
    }

    @Override
    public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
        return super.shouldOverrideKeyEvent(view, event);
    }

    @Override
    public void onReceivedClientCertRequest(WebView view, ClientCertRequest request) {
        super.onReceivedClientCertRequest(view, request);
    }

    @Override
    public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
        super.onReceivedSslError(view, handler, error);
    }

    @Override
    public void onFormResubmission(WebView view, Message dontResend, Message resend) {
        super.onFormResubmission(view, dontResend, resend);
    }

    @Override
    public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
        super.onReceivedHttpAuthRequest(view, handler, host, realm);
    }

    @Override
    public void onUnhandledInputEvent(WebView view, InputEvent event) {
        super.onUnhandledInputEvent(view, event);
    }

    @Override
    public void onScaleChanged(WebView view, float oldScale, float newScale) {
        super.onScaleChanged(view, oldScale, newScale);
    }

    @Override
    public void onReceivedLoginRequest(WebView view, String realm, String account, String args) {
        super.onReceivedLoginRequest(view, realm, account, args);
    }
}


text:
function minErr(module) {
  'use strict';
  var stringify = function (arg) {
    if (typeof arg === 'function') {
      return arg.toString().replace(/ \{[\s\S]*$/, '');
    } else if (typeof arg === 'undefined') {
      return 'undefined';
    } else if (typeof arg !== 'string') {
      return JSON.stringify(arg);
    }
    return arg;
  };
  return function () {
    var code = arguments[0], prefix = '[' + (module ? module + ':' : '') + code + '] ', message, i = 1;
    message = prefix + 'http://docs.example.com' + code;
    for (; i < arguments.length; i++) {
      message = message + (i === 1 ? '?' : '&') + 'p' + (i - 1) + '=' + stringify(arguments[i]);
    }
    return new Error(message);
  };
}
(function () {
  var testMinErr = minErr('test');
  throw testMinErr('one', 'bad');
}());


text:
{% extends "common/page_base.html" %}  {# common/page_base.html extends layout.html #}
{% block css %}
	{{ super() }}

{% endblock %}

{% block content %}

IWS Feature Request panel

				<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#new_feature" id="new_feature_b">
					Add
				</button>

Feature Request

								  #
								  Title

								  Client Name
								  product Name
								  Global priority

								  Client Priority
								  Ticket URL
								  Target Date
								  Action

							{#% for fr in features %#}

								  {#{fr.id}#}

									    <input data-bind="value: title, event: { blur: $root.clearTitle }" />

									{#{fr.title}#}

								  {#{fr.description}#}

									    <select data-bind="options: $root.products, event: { blur: $root.clearProduct}, value:  product, optionsText: 'product_name'" />

								  {#{fr.description}#}

								  {#{fr.user_id}#}
								  {#{fr.priority}#}

									    <input data-bind="value: ticket_url, event: { blur: $root.clearTicketUrl }" />

								  	{#{fr.priority}#}

									    <input data-bind="value: target_date, event: { blur: $root.clearTargetDate }"
									    class="dateInput"/>

								  {#{fr.priority}#}

								  Delete

							{#% endfor %#}

<form data-bind="submit: addFeature">

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

Create new Feature

                  Title
                  <input type="text" data-bind="value: newTitle" class="form-control" id="titleText" aria-describedby="titleHelp" placeholder="Enter title">
                  Enter the title of the feature.

                  Description
                  <textarea class="form-control" data-bind="value: newDesc" id="descriptionText" rows="3"></textarea>

              {% if current_user.roles[0].name=='client' %}
              		<input type="hidden" id="current_user_id" value="{{current_user.id}}">
              		<input type="hidden" id="role_user" value="3">

              {% else %}

				  Client

				  <select class="form-control" id="cilentSelect" data-bind="options: $root.clients, value: newClient, optionsText: 'company_name'">
				  </select>

              		<input type="hidden" id="role_user" value="1">

              {% endif %}

                  Target Date
                  <input type="text" class="form-control" data-bind="value: newTargetDate" id="targetDateText"
                  aria-describedby="targetDateHelp" placeholder="Enter target Date" data-provide="datepicker">
                  Enter the target Date.

                  Ticket URL

                  	<input type="text" data-bind="value: newTicketUrl" class="form-control" id="ticketUrlText"
                  	aria-describedby="tcketUrlHelp" placeholder="Enter ticket URL" width="80%">

                  Enter the ticket URL.

				  Product

				  <select class="form-control" id="productSelect" data-bind="options: $root.products, value: newProduct, optionsText: 'product_name'">
				  </select>

        <button type="submit" class="btn btn-primary">Save</button>

</form>

  The Feature will be deleted!. Are you sure?

{% endblock %}

{% block javascript %}
    {{ super() }}

{% endblock %}


text:
require 'test_helper'

class BillTest < ActiveSupport::TestCase
  test 'new bill without validation error' do
   @regular_bill = Bill.new do |b|
      b.client_id = Client.take.id
      b.person_id = Person.take.id
      b.description = "mock"
      b.issue_date = Date.today
      b.total_amount = 123
    end
    assert @regular_bill.save
  end

  test 'new bill with validation error' do
   @bad_bill = Bill.new
   assert_not @bad_bill.save
  end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Marathwada University Journal of Science (Natural Science), B 16(9): 63 (1978)

#### Original name
Gnomoniella indica P.G. Sathe & K.M. Mogarkar

### Remarks
null


text:
<!DOCTYPE html>

    <title>Berry - Multipage Business HTML Template</title>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="description" content="Berry - Multipage Business HTML Template" />
    <meta name="keywords" content="Berry, parallax, one page, multipage, responsive, landing, html template" />
    <meta name="author" content="TidyTheme">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

    <link rel="icon" type="image/png" href="images/favicon.png">
    <link rel="apple-touch-icon" href="images/apple-touch-icon.png">
    <link rel="apple-touch-icon" sizes="72x72" href="images/apple-touch-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="114x114" href="images/apple-touch-icon-114x114.png">

    <link href="css/font-awesome.min.css" rel="stylesheet">

    <link href="icon/elegant-icons/style.css" rel="stylesheet">
    <link href="icon/etlinefont-bower-master/style.css" rel="stylesheet">

    <link href="css/animate.css" rel="stylesheet">
    <link href="css/hover.css" rel="stylesheet">

    <link href="css/prettyPhoto.css" rel="stylesheet">

    <link href="css/owl.carousel.css" rel="stylesheet">
    <link href="css/owl.theme.css" rel="stylesheet">
    <link href="css/owl.transitions.css" rel="stylesheet">

    <link rel="stylesheet" href="css/nivo-slider.css" type="text/css" />
    <link rel="stylesheet" href="css/nivo-preview.css" type="text/css" media="screen" />

    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/normalize.css" rel="stylesheet">

    <link href="css/style.css" rel="stylesheet">
    <link href="css/responsive.css" rel="stylesheet">

	<link rel="stylesheet" href="css/colors/default-color.css">

	<link rel="stylesheet" id="switcher-css" type="text/css" href="css/switcher.css" media="all" />

	<link rel="alternate stylesheet" type="text/css" href="css/colors/color_1.css" title="alternate" media="all" />
	<link rel="alternate stylesheet" type="text/css" href="css/colors/color_2.css" title="next" media="all" />
	<link rel="alternate stylesheet" type="text/css" href="css/colors/color_3.css" title="bookmark" media="all" />
	<link rel="alternate stylesheet" type="text/css" href="css/colors/color_4.css" title="colorfr" media="all" />

                <button class="navbar-toggle" data-target=".navbar-collapse" data-toggle="collapse" type="button">
                </button>

                Business Theme

				Welcome to Barry

                    Home

                            Home

                            Home Two

                            One Page

                            One Page

                            One Page

                    about

                    team

                    service

                    work

                            Work Page

                            Single Work

                    pages

                            Work Page

                            Single Work

                            Service

                            Single Blog

                    blog

                    contact

 Home  / Single Gallery

Single Gallery

Description

At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet

Project Detail

Client Market Arona

Date Jun 20, 2015

Work Type Design, Marketing

Share

Related Project

Personal, Work, Home Office

Design Workspace

Personal, Work, Home Office

Design Workspace

Personal, Work, Home Office

Design Workspace

Barry

Loren ipsum dolor consectetur adipiscing elit sed do eiusmod tempor incididunt know you labore et dolore magna aliqua consectetur adipiscing

100 Lorem Street, New York

+00 978-783-0597

duncansp @themeview.com

Latest post

                                    17 Jun

Loren ipsum dolor consectetur adipiscing elit sed do eiusmod

                                    15 Jun

Loren ipsum dolor consectetur adipiscing elit sed do eiusmod

                                    27 Jun

Loren ipsum dolor consectetur adipiscing elit sed do eiusmod

Subscribe

                                    Enter your email and we'll send you a coupon with 10% off your next order.

                                <form action="#" class="validate" id="mc-embedded-subscribe-form" method="post" name="mc-embedded-subscribe-form" novalidate="" target="_blank">

                                    <input class="email" id="mce-EMAIL" name="EMAIL" placeholder="Your Email" required="" type="text" value="">
                                    <input class="mc-embedded-subscribe" id="mc-embedded-subscribe" name="subscribe" type="submit" value="Subscribe now!">
                                </form>

2016 © Copyright BERRY. All rights Reserved.

                    Go To Top

LAYOUT STYLE

Multipurpose v1

Multipurpose v2

 Landingpage v1

 Landingpage v2

 Landingpage v3

CHOOSE YOUR COLOR

	  RESET STYLE


text:
using De.Osthus.Ambeth.Merge.Model;
using De.Osthus.Ambeth.Model;
using De.Osthus.Ambeth.Util;
using System;
using System.Runtime.Serialization;
using System.Text;

namespace De.Osthus.Ambeth.Privilege.Transfer
{
    [DataContract(Name = "PrivilegeOfService", Namespace = "http://schemas.osthus.de/Ambeth")]
    public class PrivilegeOfService : IPrivilegeOfService, IPrintable
    {
        [DataMember(IsRequired = true)]
        public IObjRef Reference { get; set; }

        [DataMember(IsRequired = true)]
        public ISecurityScope SecurityScope { get; set; }

        [DataMember(IsRequired = true)]
        public bool ReadAllowed { get; set; }

        [DataMember(IsRequired = true)]
        public bool CreateAllowed { get; set; }

        [DataMember(IsRequired = true)]
        public bool UpdateAllowed { get; set; }

        [DataMember(IsRequired = true)]
        public bool DeleteAllowed { get; set; }

        [DataMember(IsRequired = true)]
        public bool ExecuteAllowed { get; set; }

        [DataMember(IsRequired = true)]
        public String[] PropertyPrivilegeNames { get; set; }

        [DataMember(IsRequired = true)]
        public IPropertyPrivilegeOfService[] PropertyPrivileges { get; set; }

	    public override String ToString()
	    {
		    StringBuilder sb = new StringBuilder();
		    ToString(sb);
		    return sb.ToString();
	    }

	    public void ToString(StringBuilder sb)
	    {
		    sb.Append(ReadAllowed ? "+R" : "-R");
		    sb.Append(CreateAllowed ? "+C" : "-C");
		    sb.Append(UpdateAllowed ? "+U" : "-U");
		    sb.Append(DeleteAllowed ? "+D" : "-D");
		    sb.Append(ExecuteAllowed ? "+E" : "-E");
	    }
    }
}


text:
 #include "worker_info.h"

worker_info_t *worker_info_new(const worker_t *worker, pid_t child, gru_status_t *status) {
	logger_t logger = gru_logger_get();

	worker_info_t *ret = gru_alloc(sizeof(worker_info_t), status);
	gru_alloc_check(ret, NULL);

	ret->child = child;

	const char *cname = worker_name(worker, child, status);
	if (!cname) {
		kill(child, SIGKILL);
		return NULL;
	}

	logger(GRU_DEBUG, "Child %d gave the ok signal", child);
	fflush(NULL);

	worker_queue_opt_t queue_opt = worker_queue_new_opt(worker->worker_flags);

	ret->pqueue = worker_queue_new(cname, PQUEUE_READ, queue_opt, status);

	gru_dealloc_const_string(&cname);

	if (!ret->pqueue) {
		gru_status_set(status, GRU_FAILURE, "Unable to create a posix queue: %s",
					   status->message);

		kill(child, SIGKILL);
		return NULL;
	}

	ret->worker_flags = worker->worker_flags;
	ret->writer = worker->writer;

	return ret;
}

void worker_info_destroy(worker_info_t **ptr) {
	worker_info_t *wi = *ptr;

	if (!wi) {
		return;
	}

	worker_queue_destroy(&wi->pqueue);
	gru_dealloc((void **) ptr);
}


text:
package opus.gwt.management.console.client;

import opus.gwt.management.console.client.event.AddProjectEvent;
import opus.gwt.management.console.client.event.AddProjectEventHandler;
import opus.gwt.management.console.client.event.AsyncRequestEvent;
import opus.gwt.management.console.client.event.DeleteProjectEvent;
import opus.gwt.management.console.client.event.DeleteProjectEventHandler;
import opus.gwt.management.console.client.event.GetApplicationsEvent;
import opus.gwt.management.console.client.event.GetApplicationsEventHandler;
import opus.gwt.management.console.client.event.GetDjangoPackagesEvent;
import opus.gwt.management.console.client.event.GetDjangoPackagesEventHandler;
import opus.gwt.management.console.client.event.GetProjectsEvent;
import opus.gwt.management.console.client.event.GetProjectsEventHandler;
import opus.gwt.management.console.client.event.GetUserEvent;
import opus.gwt.management.console.client.event.GetUserEventHandler;
import opus.gwt.management.console.client.event.PanelTransitionEvent;

import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.Window;

public class ManagementConsoleController {

	private boolean projectsReady;
	private boolean userReady;
	private boolean djangoPackagesReady;
	private boolean applicationsReady;
	private ClientFactory clientFactory;
	private EventBus eventBus;

	public ManagementConsoleController(ClientFactory clientFactory){
		this.clientFactory = clientFactory;
		this.eventBus = clientFactory.getEventBus();
		registerHandlers();
		eventBus.fireEvent(new AsyncRequestEvent("getProjects"));
		eventBus.fireEvent(new AsyncRequestEvent("getApplications"));
		eventBus.fireEvent(new AsyncRequestEvent("getUser"));
		eventBus.fireEvent(new AsyncRequestEvent("getDjangoPackages"));
	}

	private void registerHandlers(){
		eventBus.addHandler(GetApplicationsEvent.TYPE,
			new GetApplicationsEventHandler() {
				public void onGetApplications(GetApplicationsEvent event) {
					clientFactory.setApplications(event.getApplications());
					applicationsReady = true;
					start();
				}
		});
		eventBus.addHandler(GetDjangoPackagesEvent.TYPE,
			new GetDjangoPackagesEventHandler() {
				public void onGetDjangoPackages(GetDjangoPackagesEvent event) {
					clientFactory.setDjangoPackages(event.getDjangoPackages());
					djangoPackagesReady = true;
					start();
				}
		});
		eventBus.addHandler(GetUserEvent.TYPE,
			new GetUserEventHandler() {
				public void onGetUser(GetUserEvent event) {
					clientFactory.setUser(event.getUser());
					userReady = true;
					start();
				}
		});
		eventBus.addHandler(GetProjectsEvent.TYPE,
			new GetProjectsEventHandler(){
				public void onGetProjects(GetProjectsEvent event) {
					clientFactory.setProjects(event.getProjects());
					projectsReady = true;
					start();
				}
		});
		eventBus.addHandler(AddProjectEvent.TYPE,
				new AddProjectEventHandler(){
					public void onAddProject(AddProjectEvent event) {
						clientFactory.getProjects().put(event.getProject().getName(), event.getProject());
						eventBus.fireEvent(new PanelTransitionEvent(PanelTransitionEvent.TransitionTypes.DASHBOARD, event.getProject().getName()));
					}
		});
		eventBus.addHandler(DeleteProjectEvent.TYPE,
				new DeleteProjectEventHandler(){
					public void onDeleteProject(DeleteProjectEvent event) {
						clientFactory.getProjects().remove(event.getProjectName());
						eventBus.fireEvent(new PanelTransitionEvent(PanelTransitionEvent.TransitionTypes.PROJECTS));
					}
		});
	}

	private void start(){
		if(projectsReady && applicationsReady && userReady && djangoPackagesReady){
			ManagementConsole mc = new ManagementConsole(clientFactory);
		}
	}
}


text:
package org.apache.carbondata.processing.newflow;

import java.io.Serializable;

import org.apache.carbondata.core.carbon.metadata.blocklet.compressor.CompressionCodec;
import org.apache.carbondata.core.carbon.metadata.encoder.Encoding;
import org.apache.carbondata.core.carbon.metadata.schema.table.column.CarbonColumn;

/**
 * Metadata class for each column of table.
 */
public class DataField implements Serializable {

  private CarbonColumn column;

  private CompressionCodec compressionCodec;

  public boolean hasDictionaryEncoding() {
    return column.hasEncoding(Encoding.DICTIONARY);
  }

  public CarbonColumn getColumn() {
    return column;
  }

  public void setColumn(CarbonColumn column) {
    this.column = column;
  }

  public CompressionCodec getCompressionCodec() {
    return compressionCodec;
  }

  public void setCompressionCodec(CompressionCodec compressionCodec) {
    this.compressionCodec = compressionCodec;
  }

}


text:
//
//  GHErrorHandlerUpload.m
//  GHZeusLibraries
//
//  Created by CollegePre on 16/3/2.
//  Copyright © 2016年 张冠华. All rights reserved.
//
#import <objc/runtime.h>
#import "GHErrorLog.h"
#import "GHViewModel.h"
#import "TMCache.h"
#import "NSDictionary+GHExtend.h"

// 保存设备信息Key值
NSString *const DeviceAndAppInfoKey = @"DeviceAndAppInfoKey";
// 保存error信息Key值
NSString *const ErrorDetailInfoKey = @"ErrorDetailInfoKey";
// 保存loginfo文件夹名称
NSString *const ErrorInfoFileNameKey = @"LogFile";

#define LogTxtInfosavePath [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:ErrorInfoFileNameKey]
#import "GHErrorHandlerUpload.h"

@interface GHErrorHandlerUpload()
@property (nonatomic,strong) GHViewModel  *viewModel;
@property (strong, nonatomic) NSFileManager *fileManager;
@end

@implementation GHErrorHandlerUpload

- (NSFileManager *)fileManager
{
    if (!_fileManager) {
        _fileManager = [NSFileManager defaultManager];
    }
    return _fileManager;
}

- (void)validateErrorTypeWithGHErrorHandlerReportType:(GHErrorHandlerReportType)type txtLogFeedBackURLString:(NSString *)URLString
{
    //不支持IOS7
    if ([[[UIDevice currentDevice] systemVersion]floatValue]<7.0) {
        return;
    }

    // 上传日志信息
    NSDictionary *errorinfo = [self exportErrorinfo];
    if (errorinfo) {
        [self exportTxtErrorInfo:errorinfo URLString:URLString];
    }

    // 保存设备信息
    [self saveDeviceInfo];

    if (type == GHErrorHandlerReportTypeLog) {
        return;
    }else if(type == GHErrorHandlerReportTypeLog) {
        [GHErrorLog installExceptionHandler];
        return;
    }else if(type == GHErrorHandlerReportTypeCompatibilityMode) {
        [GHErrorLog installExceptionHandler];
    }else if(type == GHErrorHandlerReportTypeSaveTXTAndUploadToServer) {
        [GHErrorLog installExceptionHandler];
    }
}

/**
 * 1
 */
- (void)exportTxtErrorInfo:(NSDictionary *)errorInfo URLString:(NSString *)URLString
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSDate *date = [NSDate date];
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = @"yyyy-MM-dd HH-mm-ss";
    NSString *dateString = [fmt stringFromDate:date];

    NSDictionary *deviceInfo = errorInfo[@"deviceInfo"];
    NSString *appName = deviceInfo[@"appName"];
    NSString *username = deviceInfo[@"username"];

    NSString *fileName =@"";
    if (username.isNoEmpty) {
        fileName = [NSString stringWithFormat:@"%@%@%@.txt",appName,username,dateString];
    }else{
        fileName = [NSString stringWithFormat:@"%@%@.txt",appName,dateString];
    }

    if (![self.fileManager fileExistsAtPath:LogTxtInfosavePath]) {
        BOOL isSuc = [self.fileManager createDirectoryAtPath:LogTxtInfosavePath withIntermediateDirectories:NO attributes:nil error:nil];
        if (isSuc) {
            NSString *txtPath = [LogTxtInfosavePath stringByAppendingPathComponent:fileName];
            BOOL isWriteSuc = [errorInfo writeToFile:txtPath atomically:YES];
            if (isWriteSuc) {
                NSLog(@"写入成功");
                [userDefaults removeObjectForKey:ErrorDetailInfoKey];

                // 上传log信息
                [self uploadLoginfoURLString:URLString errorInfo:errorInfo];
            }else{
                NSLog(@"写入失败");
            }
        }else{
            NSLog(@"创建filePath失败");
        }
    }
    else{
        NSString *txtPath = [LogTxtInfosavePath stringByAppendingPathComponent:fileName];
        BOOL isWriteSuc = [errorInfo writeToFile:txtPath atomically:YES];
        if (isWriteSuc) {
            NSLog(@"写入成功");
            // 上传log信息
            [self uploadLoginfoURLString:URLString errorInfo:errorInfo];
        }else{
            NSLog(@"写入失败");
        }
    }
}

/**
 *  2
 */
- (void)uploadLoginfoURLString:(NSString *)URLString errorInfo:(NSDictionary *)errorinfo

{
    NSArray *subPaths = [self.fileManager subpathsAtPath:LogTxtInfosavePath];
    if (subPaths.count) {
        for (NSString *subPath in subPaths) {
            if ([[subPath pathExtension] isEqualToString:@"txt"]) {
                [self uploginfoWithFileName:subPath errorInfo:errorinfo URLString:URLString];
            }
        }
    }
}

/**
 *  3
 *  URLString: http://182.92.243.56/nbsc/txtUpload.do
 */
- (void)uploginfoWithFileName:(NSString *)fileName errorInfo:(NSDictionary *)errorinfo  URLString:(NSString *)URLString
{
    NSString *filePath = [LogTxtInfosavePath stringByAppendingPathComponent:fileName];
    NSData *data = [NSData dataWithContentsOfFile:filePath];

    self.viewModel = [GHViewModel shareViewModel];

    GHUploadSessionTask * dTask_ = [GHUploadSessionTask setFileData:data
                                                           formName:@"txtFile"
                                                           fileName:filePath
                                                           mimeType:@"text/plain"
                                                          urlString:URLString delegate:self.viewModel];

    [self.viewModel uploadTask:dTask_ progress:^(NSProgress *downloadProgress)
     {
         NSLog(@"%lld",downloadProgress.completedUnitCount);
     } Block:^(GHSessionTask *session, NSError *error){
         if (!error) {
             NSLog(@"上传成功");
             [self.fileManager removeItemAtPath:filePath error:nil];
             NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
             [userDefaults removeObjectForKey:ErrorDetailInfoKey];
         }else{
             if (error.code == 1) {
                 NSLog(@"上传成功");
                 [self.fileManager removeItemAtPath:filePath error:nil];
                 NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                 [userDefaults removeObjectForKey:ErrorDetailInfoKey];

             }else {
                 NSLog(@"上传失败--%@",error);
             }
         }
     }];
}

/**
 *  3-1
 *  URLString: http://182.92.243.56/nbsc/txtUpload.do
 */
- (void)uploginfoWithFileName:(NSArray *)FileDats ForNames:(NSArray *)ForNames FileNames:(NSArray *)fileNames mimeTypes:(NSArray *)mimeTypes errorInfo:(NSDictionary *)errorinfo  URLString:(NSString *)URLString
{
    self.viewModel = [GHViewModel shareViewModel];

    GHUploadSessionTask * dTask_ = [GHUploadSessionTask  setFileDats:fileNames ForNames:ForNames FileNames:fileNames mimeTypes:mimeTypes urlString:URLString delegate:self.viewModel];

    [self.viewModel uploadTask:dTask_ progress:^(NSProgress *downloadProgress)
     {
         NSLog(@"%lld",downloadProgress.completedUnitCount);
     } Block:^(GHSessionTask *session, NSError *error)
     {
         NSLog(@"Error:%@",error);
     }];
}

/**
 *  输出错误信息
 */
- (NSDictionary *)exportErrorinfo {

    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *deviceinfo =  [userDefaults valueForKey:DeviceAndAppInfoKey];
    NSDictionary *errorinfo =  [userDefaults valueForKey:ErrorDetailInfoKey];
    if (deviceinfo.isNoEmpty && errorinfo.isNoEmpty) {
        NSDictionary *loginfo = @{@"deviceInfo":deviceinfo,@"errorInfo":errorinfo};
        return loginfo;
    }else{
        return nil;
    }
}

- (void)saveDeviceInfo
{
    /**
     *  设备类型  设备ID 设备版本号  软件版本号  app名称
     */
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    // 当前应用软件版本  比如:1.0.1
    NSString *appCurVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];

    NSString *appCurVersionNum = [infoDictionary objectForKey:@"CFBundleVersion"];
    // app名称
    NSString *app_Name = [infoDictionary objectForKey:@"CFBundleDisplayName"];

    NSString *appVersion = [NSString stringWithFormat:@"%@-%@",appCurVersion,appCurVersionNum];

    NSString *deviceId = [[UIDevice currentDevice] identifierForVendor].UUIDString;
    NSString *deviceType = [[UIDevice currentDevice] model];
    NSString *deviceVersion = [UIDevice currentDevice].systemVersion;

    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

    NSString *username = [userDefaults valueForKey:@"Account"];
    NSString *remark = [userDefaults valueForKey:@"Password"];
    NSDictionary *deviceInfo;
    if (username.isNoEmpty &&remark.isNoEmpty) {
        deviceInfo = @{@"deviceID":deviceId,@"deviceType":deviceType,@"deviceVersion":deviceVersion,@"appVersion":appVersion,@"appName":app_Name,@"username":username,@"remark":remark};
    }else{
        deviceInfo =@{@"deviceID":deviceId,@"deviceType":deviceType,@"deviceVersion":deviceVersion,@"appVersion":appVersion,@"appName":app_Name};
    }

    [userDefaults setObject:deviceInfo forKey:DeviceAndAppInfoKey];
}

@end


text:
package org.assertj.core.error;

import java.time.Duration;

/**
 * @author Filip Hrisafov
 */
public class ShouldHaveDuration extends BasicErrorMessageFactory {

  private static final String EXPECTED_PREFIX = "%n"
                                                + "Expecting Duration:%n"
                                                + "  %s%n"
                                                + "to have %s ";

  public static ShouldHaveDuration shouldHaveNanos(Duration actual, long actualNanos, long expectedNanos) {
    String metric;
    if (expectedNanos == 1 || expectedNanos == -1) {
      metric = "nano";
    } else {
      metric = "nanos";
    }
    return new ShouldHaveDuration(actual, actualNanos, expectedNanos, metric);
  }

  public static ShouldHaveDuration shouldHaveMillis(Duration actual, long actualMillis, long expectedMillis) {
    String metric;
    if (expectedMillis == 1 || expectedMillis == -1) {
      metric = "milli";
    } else {
      metric = "millis";
    }
    return new ShouldHaveDuration(actual, actualMillis, expectedMillis, metric);
  }

  public static ShouldHaveDuration shouldHaveSeconds(Duration actual, long actualSeconds, long expectedSeconds) {
    String metric;
    if (expectedSeconds == 1 || expectedSeconds == -1) {
      metric = "second";
    } else {
      metric = "seconds";
    }
    return new ShouldHaveDuration(actual, actualSeconds, expectedSeconds, metric);
  }

  public static ShouldHaveDuration shouldHaveMinutes(Duration actual, long actualMinutes, long expectedMinutes) {
    String metric;
    if (expectedMinutes == 1 || expectedMinutes == -1) {
      metric = "minute";
    } else {
      metric = "minutes";
    }
    return new ShouldHaveDuration(actual, actualMinutes, expectedMinutes, metric);
  }

  public static ShouldHaveDuration shouldHaveHours(Duration actual, long actualHours, long expectedHours) {
    String metric;
    if (expectedHours == 1 || expectedHours == -1) {
      metric = "hour";
    } else {
      metric = "hours";
    }
    return new ShouldHaveDuration(actual, actualHours, expectedHours, metric);
  }

  public static ShouldHaveDuration shouldHaveDays(Duration actual, long actualDays, long expectedDays) {
    String metric;
    if (expectedDays == 1 || expectedDays == -1) {
      metric = "day";
    } else {
      metric = "days";
    }
    return new ShouldHaveDuration(actual, actualDays, expectedDays, metric);
  }

  private ShouldHaveDuration(Duration actual, long actualSpecific, long expectedSpecific, String metric) {
    super(EXPECTED_PREFIX + metric + " but had %s", actual, expectedSpecific, actualSpecific);
  }
}


text:
<!doctype html>

	<title>Cumulate</title>
	<link rel="stylesheet" type="text/css" href="../../css/style.css">

Cumulate

Cumulate -  Cumulate as name suggests generates an increasing summary of results.It performs cumulative aggregations on input groups of data as defined by the user. It contains one input port and one output port and can be easily distinguished in the component palette.

User is provided with options to either create a custom Java class that specifies the cumulate operation or select a pre-defined standard Operation Class.

The Cumulate component can be easily distinguished in the component palette.

An enlarged version of the same is depicted when dragged on the canvas.

For further reference click on the links below:

Properties

Operation Editor

Operation Class Window

Base interface for cumulate operation class


text:
import mock
import six
import webtest
import wsme

from magnum.api.controllers.v1 import types
from magnum.common import exception
from magnum.common import utils
from magnum.tests.unit.api import base

class TestMacAddressType(base.FunctionalTest):

    def test_valid_mac_addr(self):
        test_mac = 'aa:bb:cc:11:22:33'
        with mock.patch.object(utils, 'validate_and_normalize_mac') as m_mock:
            types.MacAddressType.validate(test_mac)
            m_mock.assert_called_once_with(test_mac)

    def test_invalid_mac_addr(self):
        self.assertRaises(exception.InvalidMAC,
                          types.MacAddressType.validate, 'invalid-mac')

class TestUuidType(base.FunctionalTest):

    def test_valid_uuid(self):
        test_uuid = '1a1a1a1a-2b2b-3c3c-4d4d-5e5e5e5e5e5e'
        with mock.patch.object(utils, 'is_uuid_like') as uuid_mock:
            types.UuidType.validate(test_uuid)
            uuid_mock.assert_called_once_with(test_uuid)

    def test_invalid_uuid(self):
        self.assertRaises(exception.InvalidUUID,
                          types.UuidType.validate, 'invalid-uuid')

class MyPatchType(types.JsonPatchType):
    """Helper class for TestJsonPatchType tests."""

    @staticmethod
    def mandatory_attrs():
        return ['/mandatory']

    @staticmethod
    def internal_attrs():
        return ['/internal']

class MyRoot(wsme.WSRoot):
    """Helper class for TestJsonPatchType tests."""

    @wsme.expose([wsme.types.text], body=[MyPatchType])
    @wsme.validate([MyPatchType])
    def test(self, patch):
        return patch

class TestJsonPatchType(base.FunctionalTest):

    def setUp(self):
        super(TestJsonPatchType, self).setUp()
        self.app = webtest.TestApp(MyRoot(['restjson']).wsgiapp())

    def _patch_json(self, params, expect_errors=False):
        return self.app.patch_json(
            '/test', params=params,
            headers={'Accept': 'application/json'},
            expect_errors=expect_errors)

    def test_valid_patches(self):
        valid_patches = [{'path': '/extra/foo', 'op': 'remove'},
                         {'path': '/extra/foo', 'op': 'add', 'value': 'bar'},
                         {'path': '/foo', 'op': 'replace', 'value': 'bar'}]
        ret = self._patch_json(valid_patches, False)
        self.assertEqual(200, ret.status_int)
        self.assertEqual(sorted(valid_patches, key=lambda k: k['op']),
                         sorted(ret.json, key=lambda k: k['op']))

    def test_cannot_update_internal_attr(self):
        patch = [{'path': '/internal', 'op': 'replace', 'value': 'foo'}]
        ret = self._patch_json(patch, True)
        self.assertEqual(400, ret.status_int)

    def test_mandatory_attr(self):
        patch = [{'op': 'replace', 'path': '/mandatory', 'value': 'foo'}]
        ret = self._patch_json(patch, False)
        self.assertEqual(200, ret.status_int)
        self.assertEqual(patch, ret.json)

    def test_cannot_remove_mandatory_attr(self):
        patch = [{'op': 'remove', 'path': '/mandatory'}]
        ret = self._patch_json(patch, True)
        self.assertEqual(400, ret.status_int)

    def test_missing_required_fields_path(self):
        missing_path = [{'op': 'remove'}]
        ret = self._patch_json(missing_path, True)
        self.assertEqual(400, ret.status_int)

    def test_missing_required_fields_op(self):
        missing_op = [{'path': '/foo'}]
        ret = self._patch_json(missing_op, True)
        self.assertEqual(400, ret.status_int)

    def test_invalid_op(self):
        patch = [{'path': '/foo', 'op': 'invalid'}]
        ret = self._patch_json(patch, True)
        self.assertEqual(400, ret.status_int)

    def test_invalid_path(self):
        patch = [{'path': 'invalid-path', 'op': 'remove'}]
        ret = self._patch_json(patch, True)
        self.assertEqual(400, ret.status_int)

    def test_cannot_add_with_no_value(self):
        patch = [{'path': '/extra/foo', 'op': 'add'}]
        ret = self._patch_json(patch, True)
        self.assertEqual(400, ret.status_int)

    def test_cannot_replace_with_no_value(self):
        patch = [{'path': '/foo', 'op': 'replace'}]
        ret = self._patch_json(patch, True)
        self.assertEqual(400, ret.status_int)

class TestMultiType(base.FunctionalTest):

    def test_valid_values(self):
        vt = types.MultiType(wsme.types.text, six.integer_types)
        value = vt.validate("hello")
        self.assertEqual("hello", value)
        value = vt.validate(10)
        self.assertEqual(10, value)

        vt = types.MultiType(types.UuidType, types.NameType)
        value = vt.validate('name')
        self.assertEqual('name', value)
        uuid = "437319e3-d10f-49ec-84c8-e4abb6118c29"
        value = vt.validate(uuid)
        self.assertEqual(uuid, value)

        vt = types.MultiType(types.UuidType, six.integer_types)
        value = vt.validate(10)
        self.assertEqual(10, value)
        value = vt.validate(uuid)
        self.assertEqual(uuid, value)

    def test_invalid_values(self):
        vt = types.MultiType(wsme.types.text, six.integer_types)
        self.assertRaises(ValueError, vt.validate, 0.10)
        self.assertRaises(ValueError, vt.validate, object())

        vt = types.MultiType(types.UuidType, six.integer_types)
        self.assertRaises(ValueError, vt.validate, 'abc')
        self.assertRaises(ValueError, vt.validate, 0.10)

    def test_multitype_tostring(self):
        vt = types.MultiType(str, int)
        vts = str(vt)
        self.assertIn(str(str), vts)
        self.assertIn(str(int), vts)

class TestBooleanType(base.FunctionalTest):

    def test_valid_true_values(self):
        v = types.BooleanType()
        self.assertTrue(v.validate("true"))
        self.assertTrue(v.validate("TRUE"))
        self.assertTrue(v.validate("True"))
        self.assertTrue(v.validate("t"))
        self.assertTrue(v.validate("1"))
        self.assertTrue(v.validate("y"))
        self.assertTrue(v.validate("yes"))
        self.assertTrue(v.validate("on"))

    def test_valid_false_values(self):
        v = types.BooleanType()
        self.assertFalse(v.validate("false"))
        self.assertFalse(v.validate("FALSE"))
        self.assertFalse(v.validate("False"))
        self.assertFalse(v.validate("f"))
        self.assertFalse(v.validate("0"))
        self.assertFalse(v.validate("n"))
        self.assertFalse(v.validate("no"))
        self.assertFalse(v.validate("off"))

    def test_invalid_value(self):
        v = types.BooleanType()
        self.assertRaises(exception.Invalid, v.validate, "invalid-value")
        self.assertRaises(exception.Invalid, v.validate, "01")

class TestNameType(base.FunctionalTest):

    def test_valid_name(self):
        self.assertEqual('name', types.NameType.validate('name'))
        self.assertEqual(1234, types.NameType.validate(1234))

    def test_invalid_name(self):
        self.assertRaises(exception.InvalidName, types.NameType.validate, None)
        self.assertRaises(exception.InvalidName, types.NameType.validate, '')


text:
module.exports = function($api) {
  var ret = {};

  ret.data = {};
  ret.load = function() {
    $api.
      get('/api/popular/month').
      on('success', function(data) {
        ret.data = data.projects;
      }).
      on('error', function(data) {
        console.log('Error: ' + JSON.stringify(data));
      });
  };

  ret.load();
  return ret;
};


text:
from lia.common.LiaTestCase import LiaTestCase

from lucene import Term, IndexSearcher, TermRangeQuery

class TermRangeQueryTest(LiaTestCase):

    def testTermRangeQuery(self):

        searcher = self.getSearcher()
        query = TermRangeQuery("title2", "d", "j", True, True)

        topDocs = searcher.search(query, 100)
        self.assertEqual(3, topDocs.totalHits)
        del searcher


text:
import React from 'react';
import classNames from 'classnames';

export default class Nav extends React.Component {

    render() {
        let navClassNames = classNames(this.props.className, {
            'rm-nav-bar': true
        });
        return (
            <nav style={this.props.style} className={navClassNames}>
                {this.props.children}
            </nav>
        );
    }
}

Nav.propTypes = {
    className: React.PropTypes.string,
    style: React.PropTypes.object
};

Nav.defaultProps = {
    className: '',
    style: {}
};


text:
#include "TestSuite.h"
#include "a2ee2a.h"
#include "EBCDICTableTest.h"

EBCDICTableTest::EBCDICTableTest(TString tname) : TestCaseType(tname) {}

EBCDICTableTest::~EBCDICTableTest() {};

void EBCDICTableTest::WholeTable ()
{
	const long numChars = 256;
	unsigned char toConvert[numChars];
	unsigned char converted[numChars];
	unsigned char backConverted[numChars];

	long i;
	for (i = 0; i < numChars; i++) {
		toConvert[i] = (unsigned char) i;
	} // for

	ascii2ebcdic(converted, toConvert, numChars);
	ebcdic2ascii(backConverted, converted, numChars);

	for (i = 0; i < numChars; i++) {
		assertEqual(i, (long) backConverted[i]);
	} // for

} // WholeTable

Test *EBCDICTableTest::suite ()
/* what: return the whole suite of tests for EBCDICTableTest, add all top level
		 test functions here.
*/
{
	TestSuite *testSuite = new TestSuite;
	ADD_CASE(testSuite, EBCDICTableTest, WholeTable);

	return testSuite;
}


text:
Starfish documentation
======================

*Starfish* is a framework used for robust spectroscopic inference. While this package was designed around the need to infer stellar properties such as effective temperature :math:`T_{\rm eff}`, surface gravity :math:`\log(g)`, and metallicity :math:`[{\rm Fe}/{\rm H}]` from high resolution spectra, the framework could easily be adapted to any type of model spectra: galaxy spectra, supernovae spectra, or spectra of unresolved stellar clusters. For an introduction to the problems that *Starfish* solves, please see `our website <http://iancze.github.io/Starfish>`_. For more technical information, please see  `our paper <http://arxiv.org/abs/1412.5177>`_.

Contents:

.. toctree::
   :maxdepth: 2

   overview
   grid_tools
   spectrum
   emulator
   model
   MCMC
   scripts
   cookbook

Copyright Ian Czekala and collaborators 2013, 2014

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`


text:
require 'spec_helper_acceptance'

describe 'Identity' do
  [
    { id: 'S-1-15-2-1',
      acl_regex: %r{.*APPLICATION PACKAGE AUTHORITY\\ALL APPLICATION PACKAGES:\(OI\)\(CI\)\(F\)},
      minimum_kernel: 6.3 },
    # NOTE: 'APPLICATION PACKAGE AUTHORITY\\ALL APPLICATION PACKAGES' doesn't work due to Windows API
    { id: 'ALL APPLICATION PACKAGES',
      acl_regex: %r{.*APPLICATION PACKAGE AUTHORITY\\ALL APPLICATION PACKAGES:\(OI\)\(CI\)\(F\)},
      minimum_kernel: 6.3 },
    { id: 'S-1-15-2-2',
      acl_regex: %r{.*APPLICATION PACKAGE AUTHORITY\\ALL RESTRICTED APPLICATION PACKAGES:\(OI\)\(CI\)\(F\)},
      minimum_kernel: 10.0 },
    # NOTE: 'APPLICATION PACKAGE AUTHORITY\\ALL RESTRICTED APPLICATION PACKAGES' doesn't work due to Windows API
    { id: 'ALL RESTRICTED APPLICATION PACKAGES',
      acl_regex: %r{.*APPLICATION PACKAGE AUTHORITY\\ALL RESTRICTED APPLICATION PACKAGES:\(OI\)\(CI\)\(F\)},
      minimum_kernel: 10.0 },
  ].each do |account|
    target = "c:/#{SecureRandom.uuid}"
    verify_acl_command = "icacls #{target}"

    context 'specify APPLICATION PACKAGE AUTHORITY accounts' do
      it "Check Minimum Supported OS for #{account[:id]}" do
        # use of host_inventory returns nil with localhost
        kernelmajversion = run_shell('facter kernelmajversion').stdout.to_f

        # try next agent if user is unsupported on this Windows version
        if kernelmajversion < account[:minimum_kernel]
          warn("This test requires Windows kernel #{account[:minimum_kernel]} but this host only has #{kernelmajversion}")
          skip

          acl_manifest = <<-MANIFEST
            file { '#{target}':
              ensure => directory
            }

            acl { '#{target}':
              permissions => [
                { identity => '#{account[:id]}', rights => ['full'] },
                { identity => 'Administrators', rights => ['full'] },
              ],
            }
          MANIFEST

          it 'applies manifest' do
            apply_manifest(acl_manifest, expect_failures) do |result|
              expect(result.exit_code).to eq(2)
            end
            apply_manifest(acl_manifest, catch_changes: true)
          end

          original_acl_rights = ''
          it 'verifies ACL rights' do
            run_shell(verify_acl_command) do |result|
              original_acl_rights = result.stdout
              expect(original_acl_rights).to match(%r{#{account[:acl_regex]}})
            end
          end

          it 'applies manifest again, raises error' do
            apply_manifest(acl_manifest, expect_failures: true) do |result|
              expect(result.stderr).to match(%r{Error:})
            end
          end

          it 'verifies ACL rights again' do
            run_shell(verify_acl_command) do |result|
              expect(result.stdout).to match(%r{account[:acl_regex]})
              expect(result.stdout).to eq(original_acl_rights)
            end
          end
        end
      end
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Threading;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace StopGuessing.DataStructures
{

    /// <summary>
    /// This class will track the n most recent values observed unique itmes.  When you Add a new item to the set,
    /// and the set is already at capacity, the least-recently added item is removed.  If you re-Add
    /// an item already in the set, it will become the last to be removed (as if it were just added
    /// for the first time).
    /// </summary>
    /// <typeparam name="T"></typeparam>
    [DataContract]
    [JsonConverter(typeof(SmallCapacityConstrainedSetConverter))]
    public class SmallCapacityConstrainedSet<T> : IEquatable<SmallCapacityConstrainedSet<T>>
    {
        /// <summary>
        /// The maximum number of elements the set can hold.
        /// </summary>
        public int Capacity { get; protected set; }

        protected LinkedList<T> AsList;
        protected ReaderWriterLockSlim RwLock;

        /// <summary>
        /// Get the members of the set ordered from the most-recently added to the least-recently added.
        /// </summary>
        public IEnumerable<T> LeastRecentFirst => MostRecentFirst.Reverse();

        public bool Contains(T item)
        {
            RwLock.EnterReadLock();
            try
            {
                return AsList.Contains(item);
            }
            finally
            {
                RwLock.ExitReadLock();
            }
        }

        /// <summary>
        /// Get the members of the set ordered from the most-recently added to the least-recently added.
        /// </summary>
        public IEnumerable<T> MostRecentFirst
        {
            get
            {
                {
                    RwLock.EnterReadLock();
                    try
                    {
                        return AsList.ToArray();
                    }
                    finally
                    {
                        RwLock.ExitReadLock();
                    }
                }
            }
        }

        /// <summary>
        /// Create a set with a given capacity
        /// </summary>
        /// <param name="capacity">The maximum number of items that the set can hold.
        /// When capacity is exceeded, the oldest member of the set is removed.</param>
        public SmallCapacityConstrainedSet(int capacity)
        {
            AsList = new LinkedList<T>();
            Capacity = capacity;
            RwLock = new ReaderWriterLockSlim();
        }

        /// <summary>
        /// Add an item to the set.  If the set is already full, the oldest item in the set
        /// (the one that was added least recently) will be removed to make space for the new item.
        /// If the item is in the set, adding it will renew the recency with which it was added.
        /// </summary>
        /// <param name="item">The item to Add.</param>
        /// <returns>Returns true if the item was already a member of the set; false otherwise.</returns>
        public bool Add(T item)
        {
            RwLock.EnterWriteLock();
            try
            {
                bool itemIsAlreadyPresent = AsList.Contains(item);
                if (itemIsAlreadyPresent)
                {
                    if (!item.Equals(AsList.First))
                    {
                        // Make the item, which is already a member,
                        // the most recent
                        AsList.Remove(item);
                        AsList.AddFirst(item);
                    }
                }
                else
                {
                    if (AsList.Count >= Capacity)
                    {
                        // We need to remove the oldest item to make space for the new item
                        AsList.RemoveLast();
                    }
                    // Add the new item
                    AsList.AddFirst(item);

                }
                return itemIsAlreadyPresent;
            }
            finally
            {
                RwLock.ExitWriteLock();
            }
        }

        public bool Remove(T item)
        {
            RwLock.EnterWriteLock();
            try
            {
                return AsList.Remove(item);
            }
            finally
            {
                RwLock.ExitWriteLock();
            }
        }

        public void UnionWith(IEnumerable<T> newMembers)
        {
            foreach (T newMember in newMembers)
                Add(newMember);
        }

        public bool Equals(SmallCapacityConstrainedSet<T> other)
        {
            return other.Capacity == Capacity &&
                   other.LeastRecentFirst.SequenceEqual(LeastRecentFirst);
        }
    }

    public class SmallCapacityConstrainedSetConverter : JsonConverter
    {
        private const string CapacityName = "Capacity";
        private const string MembersName = "Members";

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            // Load JObject from stream
            JObject jObject = JObject.Load(reader);

            // Determine the specified capacity of the sequence
            int capacity = jObject[CapacityName].Value<int>();

            // Create an instance
            dynamic target = Activator.CreateInstance(objectType, capacity);

            // Create a list of values to initialize with
            Type typeArrayOfT = typeof (List<>).MakeGenericType(objectType.GenericTypeArguments);
            dynamic values = jObject[MembersName].ToObject(typeArrayOfT);
            target.UnionWith(values);

            return target;
        }

        public override void WriteJson(JsonWriter writer, Object value, JsonSerializer serializer)
        {
            dynamic set = value;
            // Start the object
            writer.WriteStartObject();
            // WriteAccountToStableStoreAsync the capacity
            writer.WritePropertyName(CapacityName);
            serializer.Serialize(writer, set.Capacity);
            // WriteAccountToStableStoreAsync the members
            writer.WritePropertyName(MembersName);
            serializer.Serialize(writer, set.LeastRecentFirst);
            // Close the object
            writer.WriteEndObject();
        }

        public override bool CanConvert(Type objectType)
        {
            bool canConvert = objectType.GetGenericTypeDefinition() == typeof(SmallCapacityConstrainedSet<>);
            //bool canConvert = StaticUtilities.IsAssignableToGenericType(objectType, typeof (SmallCapacityConstrainedSet<>));
            return canConvert;
        }
    }

}


text:
namespace Example.Tests.HandlerTests.WithComposerTests
{
    using System.Threading.Tasks;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using Miruken.Callback.Policy;

    [TestClass]
    public class TeamHandlerTests : HandlerTestScenario
    {
        [TestMethod]
        public async Task CanCreateTeam()
        {
            HandlerDescriptorFactory.Current.RegisterDescriptor<Handler.WithComposer.TeamHandler>();
            Controller.Context.AddHandlers(new Handler.WithComposer.TeamHandler());
            await AssertCanCreateTeam();
        }
    }
}


text:
var expect = require('chai').expect;
var request = require('request');
var fs = require('fs');

var Server = require('../src/server');

var port = 5000;
var url = 'http://localhost:' + port;
var server = null;

describe('#mirror-server', function() {

	beforeEach(function(done) {
		server = new Server(port);
		server.on('data', function(data) {
			//process.stdout.write(data);			// just for debugging
		});
		server.connect(function() {
			done();
		});
	});

	afterEach(function() {
		server.disconnect();
	});

	describe('GET', function() {

		it('should receive simple GET response', function(done) {
			request.get(url, function(err, response, body) {
				if (err) {
					throw err;
				}

				expect(response.statusCode).to.be.equal(200);
				expect(response.headers['content-type']).to.be.equal('application/json');
				expect(JSON.parse(body)).to.be.eql({});
				done();
			});
		});

		it('should receive GET with data', function(done) {
			request.get(url + '/?name=john&number=5', function(err, response, body) {
				if (err) {
					throw err;
				}

				expect(response.statusCode).to.be.equal(200);
				expect(response.headers['content-type']).to.be.equal('application/json');
				expect(JSON.parse(body)).to.be.eql({
					name: 'john',
					number: '5'
				});
				done();
			});
		});

		it('should send custom data', function(done) {
			request.get(url + '/?response=hello&contentType=' + encodeURIComponent('text/plain'), function(err, response, body) {
				if (err) {
					throw err;
				}

				expect(response.statusCode).to.be.equal(200);
				expect(response.headers['content-type']).to.be.equal('text/plain');
				expect(body).to.be.equal('hello');
				done();
			});
		});

		it('should change status code', function(done) {
			request.get(url + '/?statusCode=304', function(err, response) {
				if (err) {
					throw err;
				}

				expect(response.statusCode).to.be.equal(304);
				done();
			});
		});

		it('should change content type', function(done) {
			request.get(url + '/?contentType=' + encodeURIComponent('text/plain'), function(err, response) {
				if (err) {
					throw err;
				}

				expect(response.headers['content-type']).to.be.equal('text/plain');
				done();
			});
		});

	});

	describe('POST', function() {

		it('should receive simple POST response', function(done) {
			request.post({url: url, formData: {}}, function(err, response, body) {
				if (err) {
					throw err;
				}

				expect(response.statusCode).to.be.equal(200);
				expect(response.headers['content-type']).to.be.equal('application/json');
				expect(JSON.parse(body)).to.be.eql({});
				done();
			});
		});

		it('should receive GET with data', function(done) {
			var data = {
				name: 'john',
				number: '5'
			};

			request.post({url: url, formData: data}, function(err, response, body) {
				if (err) {
					throw err;
				}

				expect(response.statusCode).to.be.equal(200);
				expect(response.headers['content-type']).to.be.equal('application/json');
				expect(JSON.parse(body)).to.be.eql(data);
				done();
			});
		});

		it('should send custom data', function(done) {
			var data = {
				response: 'hello',
				contentType: 'text/plain'
			};

			request.post({url: url, formData: data}, function(err, response, body) {
				if (err) {
					throw err;
				}

				expect(response.statusCode).to.be.equal(200);
				expect(response.headers['content-type']).to.be.equal('text/plain');
				expect(body).to.be.equal('hello');
				done();
			});
		});

		it('should change status code', function(done) {
			request.post({url: url, formData: {statusCode: 304}}, function(err, response) {
				if (err) {
					throw err;
				}

				expect(response.statusCode).to.be.equal(304);
				done();
			});
		});

		it('should change content type', function(done) {
			request.post({url: url, formData: {contentType: 'text/plain'}}, function(err, response) {
				if (err) {
					throw err;
				}

				expect(response.headers['content-type']).to.be.equal('text/plain');
				done();
			});
		});

		describe('files', function() {

			it('should send files', function(done) {
				var data = {
					readme: fs.createReadStream(__dirname + '/data/readme.md'),
					install: fs.createReadStream(__dirname + '/data/install.md')
				};

				request.post({url: url, formData: data}, function(err, response) {
					if (err) {
						throw err;
					}

					expect(response.headers).to.contain.keys(['x-mirror-files']);
					expect(JSON.parse(response.headers['x-mirror-files'])).to.be.eql([
						{
							name: 'readme',
							file: 'readme.md'
						},
						{
							name: 'install',
							file: 'install.md'
						}
					]);
					done();
				});
			});

		});

	});

});


text:
#include "tensorflow/core/util/strided_slice_op.h"
#include "tensorflow/compiler/tf2xla/literal_util.h"
#include "tensorflow/compiler/tf2xla/type_util.h"
#include "tensorflow/compiler/tf2xla/xla_helpers.h"
#include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/kernels/ops_util.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/gtl/array_slice.h"
#include "tensorflow/core/platform/mem.h"

namespace tensorflow {
namespace {

class StridedSliceOp : public XlaOpKernel {
 public:
  explicit StridedSliceOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {
    OP_REQUIRES_OK(ctx, ctx->GetAttr("begin_mask", &begin_mask_));
    OP_REQUIRES_OK(ctx, ctx->GetAttr("end_mask", &end_mask_));
    OP_REQUIRES_OK(ctx, ctx->GetAttr("ellipsis_mask", &ellipsis_mask_));
    OP_REQUIRES_OK(ctx, ctx->GetAttr("new_axis_mask", &new_axis_mask_));
    OP_REQUIRES_OK(ctx, ctx->GetAttr("shrink_axis_mask", &shrink_axis_mask_));
    OP_REQUIRES_OK(ctx, ctx->GetAttr("Index", &index_type_));
  }

  void Compile(XlaOpKernelContext* ctx) override {
    const TensorShape input_shape = ctx->InputShape(0);

    TensorShape final_shape;
    gtl::InlinedVector<int64, 4> begin;
    gtl::InlinedVector<int64, 4> end;
    gtl::InlinedVector<int64, 4> strides;

    xla::Literal begin_literal, end_literal, strides_literal;
    OP_REQUIRES_OK(ctx, ctx->ConstantInput(1, &begin_literal));
    OP_REQUIRES_OK(ctx, ctx->ConstantInput(2, &end_literal));
    OP_REQUIRES_OK(ctx, ctx->ConstantInput(3, &strides_literal));

    Tensor begin_tensor, end_tensor, strides_tensor;
    OP_REQUIRES_OK(
        ctx, LiteralToHostTensor(begin_literal, index_type_, &begin_tensor));
    OP_REQUIRES_OK(ctx,
                   LiteralToHostTensor(end_literal, index_type_, &end_tensor));
    OP_REQUIRES_OK(ctx, LiteralToHostTensor(strides_literal, index_type_,
                                            &strides_tensor));

    TensorShape dummy_processing_shape;
    ShapeReadWriteFromTensorShape wrapped_final_shape(&final_shape);
    ShapeReadWriteFromTensorShape wrapped_dummy_processing_shape(
        &dummy_processing_shape);
    bool dummy = false;
    OP_REQUIRES_OK(
        ctx, ValidateStridedSliceOp(
                 &begin_tensor, &end_tensor, strides_tensor,
                 ShapeReadWriteFromTensorShape(&input_shape), begin_mask_,
                 end_mask_, ellipsis_mask_, new_axis_mask_, shrink_axis_mask_,
                 &wrapped_dummy_processing_shape, &wrapped_final_shape, &dummy,
                 &dummy, &dummy, &begin, &end, &strides));

    gtl::InlinedVector<int64, 4> dimensions_to_reverse;
    gtl::InlinedVector<int64, 4> slice_begin, slice_end;
    bool simple_strides = true;
    for (int i = 0; i < begin.size(); ++i) {
      simple_strides &= (std::abs(strides[i]) == 1);
      if (strides[i] > 0) {
        slice_begin.push_back(begin[i]);
        slice_end.push_back(end[i]);
      } else {
        // Negative stride: swap begin and end, add 1 because the interval
        // is semi-open, and mark the dimension to be reversed.
        slice_begin.push_back(end[i] + 1);
        slice_end.push_back(begin[i] + 1);
        dimensions_to_reverse.push_back(i);
      }
    }
    xla::ComputationDataHandle slice =
        ctx->builder()->Slice(ctx->Input(0), slice_begin, slice_end);
    if (!dimensions_to_reverse.empty()) {
      slice = ctx->builder()->Rev(slice, dimensions_to_reverse);
    }

    // If at least one of the strides is > 1 (or < -1) then use Slice
    // to pull out each of the strided slices, and Concat to put them
    // together again.
    if (!simple_strides) {

      // Re-adjust the begin and end now that the periphery has been
      // sliced away.
      for (int d = 0; d < strides.size(); ++d) {
        slice_end[d] -= slice_begin[d];
        slice_begin[d] = 0;
      }

      for (int d = 0; d < strides.size(); ++d) {
        int64 stride = std::abs(strides[d]);
        if (stride > 1) {
          std::vector<xla::ComputationDataHandle> to_concat;
          int64 end = slice_end[d];
          for (int64 i = 0; i < end; i += stride) {
            slice_begin[d] = i;
            slice_end[d] = i+1;
            to_concat.push_back(ctx->builder()->Slice(slice, slice_begin,
                                                      slice_end));
          }
          slice = ctx->builder()->ConcatInDim(to_concat, d);
          slice_begin[d] = 0;
          slice_end[d] = to_concat.size();
        }
      }
    }

    slice = ctx->builder()->Reshape(slice, final_shape.dim_sizes());
    ctx->SetOutput(0, slice);
  }

 private:
  int32 begin_mask_, end_mask_;
  int32 ellipsis_mask_, new_axis_mask_, shrink_axis_mask_;
  DataType index_type_;
};

REGISTER_XLA_OP(Name("StridedSlice"), StridedSliceOp);

class StridedSliceGradOp : public XlaOpKernel {
 public:
  explicit StridedSliceGradOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {
    OP_REQUIRES_OK(ctx, ctx->GetAttr("begin_mask", &begin_mask_));
    OP_REQUIRES_OK(ctx, ctx->GetAttr("end_mask", &end_mask_));
    OP_REQUIRES_OK(ctx, ctx->GetAttr("ellipsis_mask", &ellipsis_mask_));
    OP_REQUIRES_OK(ctx, ctx->GetAttr("new_axis_mask", &new_axis_mask_));
    OP_REQUIRES_OK(ctx, ctx->GetAttr("shrink_axis_mask", &shrink_axis_mask_));
    OP_REQUIRES_OK(ctx, ctx->GetAttr("Index", &index_type_));
  }

  void Compile(XlaOpKernelContext* ctx) override {
    TensorShape processing_shape, final_shape;
    gtl::InlinedVector<int64, 4> begin;
    gtl::InlinedVector<int64, 4> end;
    gtl::InlinedVector<int64, 4> strides;

    TensorShape input_shape;
    OP_REQUIRES_OK(ctx, ctx->ConstantInputAsShape(0, &input_shape));

    xla::Literal begin_literal, end_literal, strides_literal;
    OP_REQUIRES_OK(ctx, ctx->ConstantInput(1, &begin_literal));
    OP_REQUIRES_OK(ctx, ctx->ConstantInput(2, &end_literal));
    OP_REQUIRES_OK(ctx, ctx->ConstantInput(3, &strides_literal));

    Tensor begin_tensor, end_tensor, strides_tensor;
    OP_REQUIRES_OK(
        ctx, LiteralToHostTensor(begin_literal, index_type_, &begin_tensor));
    OP_REQUIRES_OK(ctx,
                   LiteralToHostTensor(end_literal, index_type_, &end_tensor));
    OP_REQUIRES_OK(ctx, LiteralToHostTensor(strides_literal, index_type_,
                                            &strides_tensor));

    bool dummy = false;
    ShapeReadWriteFromTensorShape wrapped_final_shape(&final_shape);
    ShapeReadWriteFromTensorShape wrapped_processing_shape(&processing_shape);
    OP_REQUIRES_OK(
        ctx, ValidateStridedSliceOp(
                 &begin_tensor, &end_tensor, strides_tensor,
                 ShapeReadWriteFromTensorShape(&input_shape), begin_mask_,
                 end_mask_, ellipsis_mask_, new_axis_mask_, shrink_axis_mask_,
                 &wrapped_processing_shape, &wrapped_final_shape, &dummy,
                 &dummy, &dummy, &begin, &end, &strides));

    // Check to make sure dy is consistent with the original slice
    const TensorShape dy_shape = ctx->InputShape(4);
    OP_REQUIRES(
        ctx, final_shape == dy_shape,
        errors::InvalidArgument("shape of dy was ", dy_shape.DebugString(),
                                " instead of ", final_shape.DebugString()));

    OP_REQUIRES(
        ctx, input_shape.dims() == processing_shape.dims(),
        errors::Internal(
            "input shape and processing shape must have same number of dims"));

    auto zero = XlaHelpers::Zero(ctx->builder(), ctx->expected_output_dtype(0));

    xla::ComputationDataHandle grad = ctx->Input(4);

    // Undo any new/shrink axes.
    grad = ctx->builder()->Reshape(grad, processing_shape.dim_sizes());

    // Pad the input gradients.
    gtl::InlinedVector<int64, 4> dimensions_to_reverse;
    xla::PaddingConfig padding_config;

    for (int i = 0; i < processing_shape.dims(); ++i) {
      auto* dims = padding_config.add_dimensions();
      if (strides[i] > 0) {
        dims->set_edge_padding_low(begin[i]);
        dims->set_interior_padding(strides[i] - 1);

        // Pad the upper dimension up to the expected input shape. (It's
        // not sufficient simply to use "end[i]" to compute the padding in
        // cases where the stride does not divide evenly into the interval
        // between begin[i] and end[i].)
        int64 size =
            dims->edge_padding_low() + processing_shape.dim_size(i) +
            (processing_shape.dim_size(i) - 1) * dims->interior_padding();
        dims->set_edge_padding_high(input_shape.dim_size(i) - size);
      } else {
        dimensions_to_reverse.push_back(i);
        dims->set_edge_padding_high(input_shape.dim_size(i) - begin[i] - 1);
        dims->set_interior_padding(-strides[i] - 1);

        // Pad the lower dimension up to the expected input shape.
        int64 size =
            dims->edge_padding_high() + processing_shape.dim_size(i) +
            (processing_shape.dim_size(i) - 1) * dims->interior_padding();
        dims->set_edge_padding_low(input_shape.dim_size(i) - size);
      }
    }
    if (!dimensions_to_reverse.empty()) {
      grad = ctx->builder()->Rev(grad, dimensions_to_reverse);
    }
    grad = ctx->builder()->Pad(grad, zero, padding_config);
    ctx->SetOutput(0, grad);
  }

 private:
  int32 begin_mask_, end_mask_;
  int32 ellipsis_mask_, new_axis_mask_, shrink_axis_mask_;
  DataType index_type_;
};

REGISTER_XLA_OP(Name("StridedSliceGrad"), StridedSliceGradOp);

}  // namespace
}  // namespace tensorflow


text:
'use strict';

var cpFork = require('child_process').fork;
var path = require('path');
var gulp = require('gulp');
var ulrServer = new (require('../../lib').Server)();
var serverChildProc ;

var pathToWatch =  path.join(__dirname, 'dev/**/*');

gulp.task('server', function (next) {
  function startServer() {
    serverChildProc = cpFork('./runDevServer');
    serverChildProc.on('message', function (message) {
      if ('listening' === message) {
        ulrServer.notifyReload();
        next();
      }
    });
    serverChildProc.send('start');
  }

  if (serverChildProc) {
    serverChildProc.on('message', function (message) {
      if ('closed' === message) {
        serverChildProc.kill('SIGTERM');
      }
    });
    serverChildProc.on('exit', startServer);
    serverChildProc.send('close');
  } else {
    startServer();
  }

});

gulp.task('default', ['server'], function (next) {
  ulrServer.start(function () {
    gulp.watch(pathToWatch, ['server']);
    next();
  });
});


text:
using Bridge.Test.NUnit;
using System.Runtime.CompilerServices;

namespace Bridge.ClientTest.Runtime.CompilerServices
{
    [Category(Constants.MODULE_RUNTIME)]
    [TestFixture]
    public class RuntimeHelpersTests
    {
        private class C
        {
            public override int GetHashCode()
            {
                return 0;
            }
        }

        [Test]
        public void GetHashCodeWoksForObject_SPI_1570()
        {
            // #1570
            object o1 = new object(), o2 = new object();
            Assert.AreEqual(RuntimeHelpers.GetHashCode(o1), o1.GetHashCode());
            Assert.AreEqual(o2.GetHashCode(), RuntimeHelpers.GetHashCode(o2));
        }

        //[Test]
        //public void GetHashCodeCallsGetHashCodeNonVirtually_SPI_1570()
        //{
        //    // #1570
        //    bool isOK = false;
        //    for (int i = 0; i < 3; i++)
        //    {
        //        // Since we might be unlucky and roll a 0 hash code, try 3 times.
        //        var c = new C();
        //        if (RuntimeHelpers.GetHashCode(c) != 0)
        //        {
        //            isOK = true;
        //            break;
        //        }
        //    }
        //    Assert.True(isOK, "GetHashCode should be invoked non-virtually");
        //}
    }
}


text:
import numpy as np
import itertools
import subprocess
import pysam
import gzip
import os
import pdb

MIN_MAP_QUAL = 10
MAX_VAL = 65535
MIN_READ_LEN = 1
MAX_READ_LEN = 100000

class ZipFile():
    """File class to rapidly handle some file operations on
    a gzip file. To greatly increase speed, methods in this class
    use the system's `zcat` function to read each line of the
    file, rather than the `gzip` module.

    Arguments
        filename : string
        name of the gzip file to parse.
    """

    def __init__(self, filename):

        if os.path.isfile(filename):
            pipe = subprocess.Popen(["zcat", filename], stdout=subprocess.PIPE)
            self.handle = pipe.stdout
            # remove header
            header = self.handle.next()
        else:
            raise IOError

    def _readline(self):

        for line in self.handle:
            yield line.strip().split('\t')

    def read(self, batch=None):
        """Reads in the lines of the file, either in batches
        or as a whole.

        Optional arguments
            batch : int
            read in `batch` number of lines at a time.

        """

        if batch is None:
            # read the whole file
            locations = [line for line in self._readline()]
        else:
            # read a chunk of the file
            locations = [loc for loc in itertools.islice(self._readline(), 0, batch)]

        for loc in locations:
            loc[1] = int(loc[1])
            loc[2] = int(loc[2])

        return locations

    def close(self):

        pass

class BamFile():
    """File class to handle some file operations on
    a bam file.

    Arguments
        filename : string
        name of the bam file to parse.

        protocol : string
        DNase_seq / ATAC_seq

    """

    def __init__(self, filename, protocol):

    	self._handle = pysam.Samfile(filename, "rb")
        self._protocol = protocol
        self._ref_lengths = dict([(r,l) \
            for r,l in zip(self._handle.references,self._handle.lengths)])

    def get_read_counts(self, locations, width=200):
        """Get the number of sequencing reads mapped to
        each base along a window centered at each of
        several motif instances.

        Arguments:
            locations : list
            each entry of the list is a list that specifies
            information for a motif instance

            width : int
            length of the genomic window around the motif
            instance.

        """

        counts = []

        if self._protocol=='DNase_seq':

            for location in locations:

                chrom = location[0]
                strand = location[3]
                if strand=='+':
                    center = location[1]
                else:
                    center = location[2]
                left = max([1,center-width/2])
                right = min([center+width/2, self._ref_lengths[chrom]])

                # fetch all reads overlapping this genomic location
                sam_iter = self._handle.fetch(reference=chrom, start=left, end=right)
                forward = np.zeros((width,), dtype=np.float64)
                reverse = np.zeros((width,), dtype=np.float64)

                for read in sam_iter:

                    # skip read if unmapped
                    if read.is_unmapped:
                        continue

                    # skip read, if mapping quality is low
                    if read.mapq < MIN_MAP_QUAL:
                        continue

                    start = read.pos
                    end = start + read.alen - 1

                    # skip read, if site of cleavage is outside window
                    if (read.is_reverse and end >= right) or (not read.is_reverse and start < left):
                        continue

                    if read.is_reverse:
                        reverse[end-left] += 1
                    else:
                        forward[start-left] += 1

                # flip fwd and rev strand read counts,
                # if the motif is on the opposite strand.
                if strand=='+':
                    count = [forward, reverse]
                else:
                    count = [reverse[::-1], forward[::-1]]

                count = np.hstack(count)

                # cap the read count at any location
                count[count>MAX_VAL] = MAX_VAL
                counts.append(count.astype(np.float64))

        else:

            for l,location in enumerate(locations):

                chrom = location[0]
                strand = location[3]
                if strand=='+':
                    center = location[1]
                else:
                    center = location[2]
                left = max([1,center-width/2])
                right = min([center+width/2, self._ref_lengths[chrom]])

                # fetch all reads overlapping this genomic location
                sam_iter = [read for read in self._handle.fetch(reference=chrom, start=left, end=right)]
                count = np.zeros((width,), dtype=np.float64)

                for read in sam_iter:

                    # discard anomalies
                    if not (read.is_read1 or read.is_read2):
                        continue

                    # require that (both) paired-reads are uniquely mapped
                    if read.is_unmapped or read.mate_is_unmapped:
                        continue

                    # paired reads mapped to same strand...
                    if read.is_reverse == read.mate_is_reverse:
                        continue

                    # read has poor mapping quality
                    if read.mapq < MIN_MAP_QUAL:
                        continue

                    # discard fragments that are too long or too short
                    isize = np.abs(read.isize)
                    if isize < MIN_READ_LEN or isize > MAX_READ_LEN:
                        continue

                    # pysam pos starts at 0, not 1
                    # site of adapter insertions are 9bp apart
                    # an offset of +4 / -5 gives approximate site of transposition
                    if read.is_reverse:
                        if read.pos<=read.mpos:
                            tpos = read.pos + 4
                        else:
                            tpos = read.mpos + isize - 5
                        # add read, if site of transposition is within window
                        if left<=tpos<right:
                            count[tpos-left] += 1
                    else:
                        if read.pos>=read.mpos:
                            tpos = read.mpos + isize - 5
                        else:
                            tpos = read.pos + 4
                        # add read, if site of transposition is within window
                        if left<=tpos<right:
                            count[tpos-left] += 1

                # flip read counts,
                # if the motif is on the opposite strand.
                if strand=='-':
                    count = count[::-1]

                counts.append(count)

        counts = np.array(counts).astype(np.float64)

        # cap the read count at all locations
        counts[counts>MAX_VAL] = MAX_VAL

        return counts

    def close(self):

        self._handle.close()