text:
//  * **************************************************************************
//  * Copyright (c) McCreary, Veselka, Bragg & Allen, P.C.
//  * This source code is subject to terms and conditions of the MIT License.
//  * A copy of the license can be found in the License.txt file
//  * at the root of this distribution.
//  * By using this source code in any fashion, you are agreeing to be bound by
//  * the terms of the MIT License.
//  * You must not remove this notice from this software.
//  * **************************************************************************

using System;
using System.IO;
using System.Net;
using System.Text;

namespace MvbaCore.ThirdParty
{
	public interface IWebServiceClient
	{
		Notification<string> Post(string url, string data, string contentType);
		Notification<string> Post(string url, string contentType);
		Notification<string> PostDataContract(string url, string data, string contentType);
	}

	public class WebServiceClient : IWebServiceClient
	{
		private static void AddUserCredentials(WebRequest req)
		{
			req.Credentials = CredentialCache.DefaultCredentials;
		}

		private static HttpWebRequest CreateWebRequest(string url, string contentType)
		{
			var req = (HttpWebRequest)WebRequest.Create(url);
			req.ContentType = contentType;
			return req;
		}

		private static Notification<string> GetResponse(WebRequest req)
		{
			WebResponse response;
			try
			{
				response = req.GetResponse();
			}
			catch (Exception exception)
			{
				var notification = new Notification<string>(Notification.ErrorFor("Remote threw Exception: "+exception.Message));
				notification.Add(Notification.InfoFor(exception.StackTrace));
				return notification;
			}
			var responseStream = response.GetResponseStream();
			if (responseStream == null)
			{
				return new Notification<string>(Notification.ErrorFor("received null response stream"));
			}

			using (var reader = new StreamReader(responseStream))
			{
				var s = reader.ReadToEnd();
				return new Notification<string>
				       {
					       Item = s
				       };
			}
		}

		public Notification<string> Post(string url, string content, string contentType)
		{
			var req = CreateWebRequest(url, contentType);
			req.Method = "POST";
			SendRequest(req, content);
			return GetResponse(req);
		}

		public Notification<string> Post(string url, string contentType)
		{
			var req = CreateWebRequest(url, contentType);
			req.Method = "POST";
			AddUserCredentials(req);
			req.GetRequestStream().Close();
			return GetResponse(req);
		}

		public Notification<string> PostDataContract(string url, string content, string contentType)
		{
			var req = CreateWebRequest(url, contentType);
			req.Method = "POST";
			SendRequest(req, content);
			return GetResponse(req);
		}

		private static void SendRequest(WebRequest req, string content)
		{
			AddUserCredentials(req);
			req.ContentLength = content.Length;

			using (var streamWriter = new StreamWriter(req.GetRequestStream(), Encoding.ASCII))
			{
				streamWriter.Write(content);
			}
		}
	}
}


text:
package iso20022

// Interest type is expressed as a code or a text.
type InterestType1Choice struct {

	// Specifies the type of interest.
	Code *InterestType1Code `xml:"Cd"`

	// Specifies the type of interest in uncoded form.
	Proprietary *Max35Text `xml:"Prtry"`
}

func (i *InterestType1Choice) SetCode(value string) {
	i.Code = (*InterestType1Code)(&value)
}

func (i *InterestType1Choice) SetProprietary(value string) {
	i.Proprietary = (*Max35Text)(&value)
}

redpajama_set_name: RedPajamaGithub


text:
<!-- .slide: data-state="c-slide-inter" -->

# HTML

>>>

* První, co si prohlížeč stahuje, je HTML soubor, který obsahuje informace o stránce.
* Je to textový soubor, takže ho můžete upravovat v jakémkoli textovém editoru jako je Poznámkový blok (Notepad) apod., my budeme používat Repl.it
* Oblíbené editory: VS Code, Sublime Text, Atom

---

## Značkovací jazyk

>>>
* HT**ML** => mark-up language = značkovací
* Značkovací, protože význam a strukturu dokumentu popisuje pomocí značek, anglicky tagů.

---

## Tag/značka
```html
<jmenotagu>
    Obsah tagu
</jmenotagu>
```
<!-- .element: class="c-text-xl stretch" contenteditable="true" -->

>>>
* Tag se skládá ze špičatých závorek, názvu tagu mezi nimi.
* Mluvíme o párovém tagu: první je otevírací a druhý je zavírací.
* Uzavírá se lomítkem za první špičatou závorkou.
* Mezi tagy je jeho obsah, tedy to co obaluje. To může být obyčejný text nebo další tag nebo tagy.
* Existují i nepárové tagy (těch je pár), upozorním, až se k nim dostaneme.
* Tagy vytvářejí v prostředí webové stránky tzv. **elementy/prvky**, z nichž se skládá každá stránka.

---

## Klávesnice <!-- .element: class="c-sr-only" -->

<!-- .slide: data-background="img/keyboard-cs-html.svg" -->

>>>
* Protože je pro psaní HTML potřeba některé méně časté znaky, máte na stole pomůcku pro nalezení znaků.
* Kouzelná je klávesa AltGr s kterou napíšete většinu znaků.
* Někdo může mít trochu jiné rozložení.
* Kdo má Mac to má jednodušší - platí to co je vytištěné na klávesnici.

---

## Tagy

```html
<h1>Hlavní nadpis</h1>

<p>odstavec</p>

<strong>důležitý text</strong>

```
<!-- .element: class="c-text-md stretch" contenteditable="true" -->

>>>
* jak používají web nevidomí?
* Jména tagů jsou většinou zkratky anglických slov. Např.:
 * `h` = heading
 * `p` = paragraph

---

## Základní struktura HTML

```html
<!DOCTYPE HTML>
<html>
    <head>
        <!-- vlastnosti stránky -->
    </head>
    <body>
        <!-- samotný obsah stránky -->
    </body>
</html>
```
<!-- .element: class="c-text-md stretch" contenteditable="true" -->

>>>
* HTML dokument má mít tuto strukturu.
* Úplně první je tzv. doctype. Říká prohlížeči jaký typ HTML má čekat. Není potřeba se jím nyní zabývat, jen ho tam vždy mějte.
* Všechno ostatní je uvnitř elementu `html` => je obaleno obaleno tagem `<html>`.
* V hlavičce (`<head>`) jsou definovány vlastnosti pro celou stránku. Většinou "nejsou vidět". O hlavičce později.
* V těle stránky (`<body>`) je vlastní text stránky, obrázky atd. Většinou "je vidět". Zde budeme nyní pracovat.
* Všimněte si odsazení. A dbejte na něj ve svém kódu.
* Všimněte si komentářů. Všimněte si jak tagy obalují jiné tagy.
* **Přestávka?**


text:
import logging
from argparse import ArgumentParser

from tests import (jsonMiddlewareTest,
                   middlewareTest,
                   fileMiddlewareTest,
                   loggerMiddlewareTest,
                   appMiddlewareTest,
                   dynSiteMiddlewareTest)

SEPERATOR1 = "=" * 70
SEPERATOR2 = "-" * 70

def printResult(name, res):
    def printError(flavour, errors):
        for test, err in errors:
            print("")
            print("%s: %s" % (flavour, res.getDescription(test)))
            print(SEPERATOR2)
            print("%s" % err)
    print("")
    print(SEPERATOR1)
    print("%s %d tests" % (name, res.testsRun))
    print(SEPERATOR2)
    print("Errors: %d" % len(res.errors))
    print("Failures: %d" % len(res.failures))
    if res.errors:
        printError("ERROR", res.errors)
    if res.failures:
        printError("FAIL", res.failures)
    print("")

def main():
    parser = ArgumentParser()
    parser.add_argument("-v", "--verbose",
                        dest="verbose",
                        action="store_true",
                        help="vebose log output")

    # Tests
    parser.add_argument("-m", "--middlewareTest",
                        dest="middlewareTest",
                        action="store_true",
                        help="Middleware-Test")
    parser.add_argument("-j", "--jsonMiddlewareTest",
                        dest="jsonMiddlewareTest",
                        action="store_true",
                        help="JsonMiddleware-Test")
    parser.add_argument("-f", "--fileMiddlewareTest",
                        dest="fileMiddlewareTest",
                        action="store_true",
                        help="FileMiddleware-Test")
    parser.add_argument("-a", "--appMiddlewareTest",
                        dest="appMiddlewareTest",
                        action="store_true",
                        help="AppMiddleware-Test")
    parser.add_argument("-l", "--loggerMiddlewareTest",
                        dest="loggerMiddlewareTest",
                        action="store_true",
                        help="LoggerMiddleware-Test")
    parser.add_argument("-d", "--dynSiteMiddlewareTest",
                        dest="dynSiteMiddlewareTest",
                        action="store_true",
                        help="DynSiteMiddleware-Test")

    args = parser.parse_args()

    tests = {}

    if args.middlewareTest:
        tests["Middleware-Test"] = middlewareTest

    if args.jsonMiddlewareTest:
        tests["JsonMiddleware-Test"] = jsonMiddlewareTest

    if args.fileMiddlewareTest:
        tests["FileMiddleware-Test"] = fileMiddlewareTest

    if args.appMiddlewareTest:
        tests["AppMiddleware-Test"] = appMiddlewareTest

    if args.loggerMiddlewareTest:
        tests["LoggerMiddleware-Test"] = loggerMiddlewareTest

    if args.dynSiteMiddlewareTest:
        tests["DynSiteMiddleware-Test"] = dynSiteMiddlewareTest

    if not tests:
        tests["Middleware-Test"] = middlewareTest
        tests["JsonMiddleware-Test"] = jsonMiddlewareTest
        tests["FileMiddleware-Test"] = fileMiddlewareTest
        tests["AppMiddleware-Test"] = appMiddlewareTest
        tests["LoggerMiddleware-Test"] = loggerMiddlewareTest
        tests["DynSiteMiddleware-Test"] = dynSiteMiddlewareTest

    if args.verbose:
        log = logging.getLogger()
        log.setLevel(logging.DEBUG)
        handler = logging.StreamHandler()
        formatter = logging.Formatter("%(name)s - %(levelname)s - %(message)s")
        handler.setFormatter(formatter)
        log.addHandler(handler)

    results = {}
    for name, test in tests.items():
        results[name] = test.run()

    for k, v in results.items():
        printResult(k, v)

if __name__ == "__main__":
    main()


text:
package request

import (
	"encoding/json"
	"io"
	"io/ioutil"

	"github.com/lastbackend/lastbackend/internal/pkg/errors"
)

type ClusterRequest struct{}

func (ClusterRequest) UpdateOptions() *ClusterUpdateOptions {
	return new(ClusterUpdateOptions)
}

func (c *ClusterUpdateOptions) Validate() *errors.Err {
	switch true {
	case c.Description != nil && len(*c.Description) > DefaultDescriptionLimit:
		return errors.New("cluster").BadParameter("description")
	}
	return nil
}

func (c *ClusterUpdateOptions) DecodeAndValidate(reader io.Reader) *errors.Err {

	if reader == nil {
		err := errors.New("data body can not be null")
		return errors.New("cluster").IncorrectJSON(err)
	}

	body, err := ioutil.ReadAll(reader)
	if err != nil {
		return errors.New("cluster").Unknown(err)
	}

	err = json.Unmarshal(body, c)
	if err != nil {
		return errors.New("cluster").IncorrectJSON(err)
	}

	return c.Validate()
}

func (c *ClusterUpdateOptions) ToJson() ([]byte, error) {
	return json.Marshal(c)
}

func (c *ClusterRequest) Manifest() *ClusterManifest {

	cm := new(ClusterManifest)
	cm.Namespace = make([]NamespaceManifest, 0)
	cm.Service = make([]ServiceManifest, 0)
	cm.Route = make([]RouteManifest, 0)
	cm.Task = make([]TaskManifest, 0)

	return cm
}

func (m *ClusterManifest) DecodeAndValidate(reader io.Reader) *errors.Err {

	if reader == nil {
		err := errors.New("data body can not be null")
		return errors.New("cluster").IncorrectJSON(err)
	}

	body, err := ioutil.ReadAll(reader)
	if err != nil {
		return errors.New("cluster").Unknown(err)
	}

	err = json.Unmarshal(body, m)
	if err != nil {
		return errors.New("cluster").IncorrectJSON(err)
	}

	return nil
}

func (s *ClusterManifest) ToJson() ([]byte, error) {
	return json.Marshal(s)
}


text:
<?php
/* File Headers */

namespace Elements\Bundle\ElementsSecurityBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class ElementsSecurityBundle extends Bundle
{
}


text:
/* $Id: TestIOUtils.java 1665039 2015-03-08 15:54:11Z lehmi $ */

package com.tom_roush.pdfbox.io;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import junit.framework.TestCase;

/**
 * This is a unit test for {@link IOUtils}.
 */
public class TestIOUtils extends TestCase
{

    /**
     * Tests {@link IOUtils#populateBuffer(java.io.InputStream, byte[]).
     * @throws IOException if an I/O error occursn
     */
    public void testPopulateBuffer() throws IOException
    {
        byte[] data = "Hello World!".getBytes();
        byte[] buffer = new byte[data.length];
        long count = IOUtils.populateBuffer(new ByteArrayInputStream(data), buffer);
        assertEquals(12, count);

        buffer = new byte[data.length - 2]; //Buffer too small
        InputStream in = new ByteArrayInputStream(data);
        count = IOUtils.populateBuffer(in, buffer);
        assertEquals(10, count);
        byte[] leftOver = IOUtils.toByteArray(in);
        assertEquals(2, leftOver.length);

        buffer = new byte[data.length + 2]; //Buffer too big
        in = new ByteArrayInputStream(data);
        count = IOUtils.populateBuffer(in, buffer);
        assertEquals(12, count);
        assertEquals(-1, in.read()); //EOD reached
    }

}


text:
import { Injectable } from "@angular/core";
import { Http }       from "@angular/http";
import  'rxjs/add/operator/map';

@Injectable()
export class PeopleService{
	constructor(private http: Http){}

	getPeople(){
		return this.http.get("http://192.168.1.113:4567/api/people.json")
			.map(response => response.json());
	}

}


text:
class CreateMessages < ActiveRecord::Migration
  def change
    create_table :messages do |t|
      t.integer :to_user_id
      t.integer :from_user_id
      t.text :subject
      t.text :content
      t.integer :message_status_id

      t.timestamps null: false
    end
  end
end


text:
module.exports = (client, oldMessage, newMessage) => {
  client.temp.tunnels.forEach((tunnel, index, object) => {
    var sourceChannel = client.channels.get(tunnel.source)
    var destinationChannel = client.channels.get(tunnel.destination)
    var editMessage = {}
    // Attachments
    if (newMessage.attachments) {
      editMessage.files = []
      newMessage.attachments.array().forEach(attachment => {
        editMessage.files.push(attachment.url)
      })
    }
    // Embeds
    if (newMessage.embeds) {
      editMessage.embed = newMessage.embeds[0]
    }
    tunnel.cache.forEach(element => {
      if (newMessage.id === element.fromMessage.id) {
        if (newMessage.channel.id === tunnel.source) {
          editMessage.content = newMessage.content
          element.sentMessage.edit(editMessage).catch(error => {
            sourceChannel.send(`Error editing a message: \`${error.name}: ${error.message}\``).catch(() => {
              client.log('info', `Error a message in Source channel, disconnecting from \`${destinationChannel.guild.name}/#${destinationChannel.name}\``, 'Tunnel')
              object.splice(index, 1)
            })
          })
        } else if (newMessage.channel.id === tunnel.destination) {
          editMessage.content = `__**${newMessage.author.tag}** \`(${newMessage.author.id})\`__ **[EDITED]**\n${newMessage.content}`
          element.sentMessage.edit(editMessage).catch(error => {
            sourceChannel.send(`Error editing a message: \`${error.name}: ${error.message}\``).catch(() => {
              client.log('info', `Error a message in Source channel, disconnecting from \`${destinationChannel.guild.name}/#${destinationChannel.name}\``, 'Tunnel')
              object.splice(index, 1)
            })
          })
        }
      }
    })
  })
}


text:
package org.reclipse.structure.inference.ui.matching.handlers;

import java.util.List;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.handlers.HandlerUtil;
import org.reclipse.structure.inference.annotations.ASGAnnotation;
import org.reclipse.structure.inference.ui.matching.edit.parts.pattern.MatchingPSAnnotationEditPart;
import org.reclipse.structure.inference.ui.matching.views.AbstractMatchingView;
import org.reclipse.structure.inference.ui.views.annotations.AnnotationView;
import org.reclipse.structure.specification.PSAnnotation;

public class OpenMatchedAnnotationHandler extends AbstractHandler {
	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		ISelection selection = HandlerUtil.getCurrentSelection(event);
		if (!selection.isEmpty() && selection instanceof IStructuredSelection
				&& ((IStructuredSelection) selection).size() == 1) {
			Object selected = ((IStructuredSelection) selection).getFirstElement();
			if (selected instanceof MatchingPSAnnotationEditPart) {
				PSAnnotation model = ((MatchingPSAnnotationEditPart) selected).getRealModel();
				ASGAnnotation currentAnnotation = AbstractMatchingView.getCurrent();

				List<EObject> elements = currentAnnotation.getBoundObjects().get(model.getName());
				if (elements != null && elements.size() == 1 && elements.get(0) instanceof ASGAnnotation) {
					ASGAnnotation matchedAnnotation = (ASGAnnotation) elements.get(0);

					AnnotationView view = getAnnotationView(event);
					if (view != null) {
						view.select(currentAnnotation, matchedAnnotation);
					}
				}
			}
		}

		return null;
	}

	private AnnotationView getAnnotationView(ExecutionEvent event) {
		IViewPart part = HandlerUtil.getActiveWorkbenchWindow(event).getActivePage().findView(AnnotationView.ID);
		if (part instanceof AnnotationView) {
			return (AnnotationView) part;
		}

		return null;
	}
}


text:
module Cdek

  module Respond

    extend self

    def pvz_list(body, xpath, err_xpath)

      doc = ::Nokogiri::XML::Document.parse(body)
      result = doc.search(xpath)

      if result.size > 0

        result.each do |node|
          yield(node)
        end # search

        return true

      else

        if (result = doc.search(err_xpath).first)
          return ::Cdek.get_error(result["ErrorCode"], result["Msg"])
        else
          return ::Cdek::UnknownError.new("Неизветсная ошибка")
        end

      end # if

    end # pvz_list

  end # Respond

end # Cdek


text:
@import models.sitedata.EquipmentModel
@(equipmentmodels: Seq[EquipmentModel])(implicit flash: Flash)

@main("EquipmentModel Information") {

EquipmentModel Information

    @if(!equipmentmodels.isEmpty) {

            EquipmentModel ID
            EquipmentModel Name
            EquipmentName ID
            DisplayIndex

          @for(equipmentmodel <- equipmentmodels) {

              @equipmentmodel.id
              @equipmentmodel.name
              @equipmentmodel.equipmentnameid
              @equipmentmodel.displayindex

            }

      }

  <link rel="stylesheet" media="screen" href="@routes.Assets.at("bower_components/datatables.net-dt/css/jquery.dataTables.min.css")">

  <link rel="stylesheet" media="screen" href="@routes.Assets.at("bower_components/datatables.net-colreorder-dt/css/colReorder.dataTables.min.css")">

  <link rel="stylesheet" media="screen" href="@routes.Assets.at("bower_components/datatables.net-buttons-dt/css/buttons.dataTables.min.css")">

}


text: source /usr/local/lib/rvm


text:
package com.dipity.utils;

import android.util.Log;

public class LogUtils {
	private final static boolean LOG_ENABLED = false;
	public static void d(String tag, String msg) {
		if (LOG_ENABLED)
			Log.d(tag, msg);
	}

	public static void e(String tag, String msg) {
		if (LOG_ENABLED)
			Log.e(tag, msg);
	}

	public static void e(String tag, String msg, Throwable e) {
		if (LOG_ENABLED)
			Log.e(tag, msg, e);
	}
}


text:
// Copyright 2018, 2020 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef __BLACKBOX_BLACKBOXTESTS_HPP__
#define __BLACKBOX_BLACKBOXTESTS_HPP__

#define TEST_TOPIC_NAME std::string( \
        ::testing::UnitTest::GetInstance()->current_test_info()->test_case_name() + std::string( \
            "_") + ::testing::UnitTest::GetInstance()->current_test_info()->name())

#if defined(_WIN32)
#define GET_PID _getpid
#include <process.h>
#else
#define GET_PID getpid
#include <sys/types.h>
#include <unistd.h>
#endif // if defined(_WIN32)

#include "../types/HelloWorldType.h"
#include "../types/FixedSizedType.h"
#include "../types/KeyedHelloWorldType.h"
#include "../types/StringType.h"
#include "../types/Data64kbType.h"
#include "../types/Data1mbType.h"
#include "../types/KeyedData1mbType.h"

#include <algorithm>
#include <cstddef>
#include <iostream>
#include <list>
#include <functional>

#if HAVE_SECURITY
extern void blackbox_security_init();
#endif // if HAVE_SECURITY
#if TLS_FOUND
extern void tls_init();
#endif // if TLS_FOUND

extern uint16_t global_port;
extern bool enable_datasharing;
extern bool use_pull_mode;
extern bool use_udpv4;

/****** Auxiliary print functions  ******/
template<class Type>
void default_receive_print(
        const Type&)
{
    std::cout << "Received data" << std::endl;
}

template<>
void default_receive_print(
        const HelloWorld& hello);

template<>
void default_receive_print(
        const FixedSized& hello);

template<>
void default_receive_print(
        const KeyedHelloWorld& str);

template<>
void default_receive_print(
        const String& str);

template<>
void default_receive_print(
        const Data64kb& data);

template<>
void default_receive_print(
        const Data1mb& data);

template<>
void default_receive_print(
        const KeyedData1mb& data);

template<class Type>
void default_send_print(
        const Type&)
{
    std::cout << "Sent data" << std::endl;
}

template<>
void default_send_print(
        const StringType&);

template<>
void default_send_print(
        const HelloWorld& hello);

template<>
void default_send_print(
        const FixedSized& hello);

template<>
void default_send_print(
        const KeyedHelloWorld& str);

template<>
void default_send_print(
        const String& str);

template<>
void default_send_print(
        const Data64kb& data);

template<>
void default_send_print(
        const Data1mb& data);

template<>
void default_send_print(
        const KeyedData1mb& data);

/****** Auxiliary data generators *******/
std::list<HelloWorld> default_helloworld_data_generator(
        size_t max = 0);

std::list<FixedSized> default_fixed_sized_data_generator(
        size_t max = 0);

std::list<KeyedHelloWorld> default_keyedhelloworld_data_generator(
        size_t max = 0);

std::list<String> default_large_string_data_generator(
        size_t max = 0);

std::list<Data64kb> default_data64kb_data_generator(
        size_t max = 0);

std::list<Data1mb> default_data16kb_data_generator(
        size_t max = 0);

std::list<Data1mb> default_data300kb_data_generator(
        size_t max = 0);

std::list<Data1mb> default_data300kb_mix_data_generator(
        size_t max = 0);

std::list<Data1mb> default_data96kb_data300kb_data_generator(
        size_t max = 0);

std::list<KeyedData1mb> default_keyeddata300kb_data_generator(
        size_t max = 0);

/****** Auxiliary lambda functions  ******/
extern const std::function<void(const HelloWorld&)>  default_helloworld_print;

extern const std::function<void(const FixedSized&)>  default_fixed_sized_print;

extern const std::function<void(const KeyedHelloWorld&)>  default_keyedhelloworld_print;

extern const std::function<void(const String&)>  default_string_print;

extern const std::function<void(const Data64kb&)>  default_data64kb_print;

extern const std::function<void(const Data1mb&)>  default_data300kb_print;

template<typename T>
void print_non_received_messages(
        const std::list<T>& data,
        const std::function<void(const T&)>& printer)
{
    if (data.size() != 0)
    {
        std::cout << "Samples not received: ";
        std::for_each(data.begin(), data.end(), printer);
        std::cout << std::endl;
    }
}

/***** End auxiliary lambda function *****/

#endif // __BLACKBOX_BLACKBOXTESTS_HPP__


text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.flowable.examples.bpmn.servicetask;

import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.DelegateHelper;
import org.flowable.engine.impl.delegate.ActivityBehavior;

/**
 * @author Joram Barrez
 */
public class ThrowsExceptionBehavior implements ActivityBehavior {

    @Override
    public void execute(DelegateExecution execution) {
        String var = (String) execution.getVariable("var");

        String sequenceFlowToTake = null;

        try {
            executeLogic(var);
            sequenceFlowToTake = "no-exception";
        } catch (Exception e) {
            sequenceFlowToTake = "exception";
        }

        DelegateHelper.leaveDelegate(execution, sequenceFlowToTake);
    }

    protected void executeLogic(String value) {
        if ("throw-exception".equals(value)) {
            throw new RuntimeException();
        }
    }

}


text:
./_download-pmcoa-bulk.sh

# Populate the catalog with the PMC OA articles
./_catalog-pmcoa-bulk.sh


text:
package org.slf4j.impl;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.message.Message;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.apache.logging.log4j.message.SimpleMessage;
import org.apache.logging.log4j.spi.AbstractLogger;
import org.apache.logging.log4j.spi.AbstractLoggerWrapper;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
import org.slf4j.helpers.EventDataConverter;
import org.slf4j.spi.LocationAwareLogger;

/**
 *
 */
public class SLF4JLogger implements LocationAwareLogger {

    private static final String FQCN = SLF4JLogger.class.getName();
    private static final Marker EVENT_MARKER = MarkerFactory.getMarker("EVENT");
    private final boolean eventLogger;
    private final AbstractLoggerWrapper logger;
    private final String name;
    private final EventDataConverter converter;

    public SLF4JLogger(final AbstractLogger logger, final String name) {
        this.logger = new AbstractLoggerWrapper(logger, name, null);
        this.eventLogger = "EventLogger".equals(name);
        this.name = name;
        this.converter = createConverter();
    }

    @Override
    public void trace(final String format) {
        if (logger.isTraceEnabled()) {
            logger.log(null, FQCN, Level.TRACE, new SimpleMessage(format), null);
        }
    }

    @Override
    public void trace(final String format, final Object o) {
        if (logger.isTraceEnabled()) {
            logger.log(null, FQCN, Level.TRACE, new ParameterizedMessage(format, o), null);
        }
    }

    @Override
    public void trace(final String format, final Object arg1, final Object arg2) {
        if (logger.isTraceEnabled()) {
            final ParameterizedMessage msg = new ParameterizedMessage(format, arg1, arg2);
            logger.log(null, FQCN, Level.TRACE, msg, msg.getThrowable());
        }
    }

    @Override
    public void trace(final String format, final Object... args) {
        if (logger.isTraceEnabled()) {
            final ParameterizedMessage msg = new ParameterizedMessage(format, args);
            logger.log(null, FQCN, Level.TRACE, msg, msg.getThrowable());
        }
    }

    @Override
    public void trace(final String format, final Throwable t) {
        if (logger.isTraceEnabled()) {
            logger.log(null, FQCN, Level.TRACE, new SimpleMessage(format), t);
        }
    }

    @Override
    public boolean isTraceEnabled() {
        return logger.isTraceEnabled();
    }

    @Override
    public boolean isTraceEnabled(final Marker marker) {
        return logger.isTraceEnabled((org.apache.logging.log4j.Marker) marker);
    }

    @Override
    public void trace(final Marker marker, final String s) {
        if (isTraceEnabled(marker)) {
            logger.log((org.apache.logging.log4j.Marker) marker, FQCN, Level.TRACE, new SimpleMessage(s), null);
        }
    }

    @Override
    public void trace(final Marker marker, final String s, final Object o) {
        if (isTraceEnabled(marker)) {
            logger.log((org.apache.logging.log4j.Marker) marker, FQCN, Level.TRACE,
                new ParameterizedMessage(s, o), null);
        }
    }

    @Override
    public void trace(final Marker marker, final String s, final Object o, final Object o1) {
        if (isTraceEnabled(marker)) {
            final ParameterizedMessage msg = new ParameterizedMessage(s, o, o1);
            logger.log((org.apache.logging.log4j.Marker) marker, FQCN, Level.TRACE, msg, msg.getThrowable());
        }
    }

    @Override
    public void trace(final Marker marker, final String s, final Object... objects) {
        if (isTraceEnabled(marker)) {
            final ParameterizedMessage msg = new ParameterizedMessage(s, objects);
            logger.log((org.apache.logging.log4j.Marker) marker, FQCN, Level.TRACE, msg, msg.getThrowable());
        }
    }

    @Override
    public void trace(final Marker marker, final String s, final Throwable throwable) {
        if (isTraceEnabled(marker)) {
            logger.log((org.apache.logging.log4j.Marker) marker, FQCN, Level.TRACE,
                new SimpleMessage(s), throwable);
        }
    }

    @Override
    public void debug(final String format) {
        if (logger.isDebugEnabled()) {
            logger.log(null, FQCN, Level.DEBUG, new SimpleMessage(format), null);
        }
    }

    @Override
    public void debug(final String format, final Object o) {
        if (logger.isDebugEnabled()) {
            logger.log(null, FQCN, Level.DEBUG, new ParameterizedMessage(format, o), null);
        }
    }

    @Override
    public void debug(final String format, final Object arg1, final Object arg2) {
        if (logger.isDebugEnabled()) {
            final ParameterizedMessage msg = new ParameterizedMessage(format, arg1, arg2);
            logger.log(null, FQCN, Level.DEBUG, msg, msg.getThrowable());
        }
    }

    @Override
    public void debug(final String format, final Object... args) {
        if (logger.isDebugEnabled()) {
            final ParameterizedMessage msg = new ParameterizedMessage(format, args);
            logger.log(null, FQCN, Level.DEBUG, msg, msg.getThrowable());
        }
    }

    @Override
    public void debug(final String format, final Throwable t) {
        if (logger.isDebugEnabled()) {
            logger.log(null, FQCN, Level.DEBUG, new SimpleMessage(format), t);
        }
    }

    @Override
    public boolean isDebugEnabled() {
        return logger.isDebugEnabled();
    }

    @Override
    public boolean isDebugEnabled(final Marker marker) {
        return logger.isDebugEnabled((org.apache.logging.log4j.Marker) marker);
    }

    @Override
    public void debug(final Marker marker, final String s) {
        if (isDebugEnabled(marker)) {
            logger.log((org.apache.logging.log4j.Marker) marker, FQCN, Level.DEBUG, new SimpleMessage(s), null);
        }
    }

    @Override
    public void debug(final Marker marker, final String s, final Object o) {
        if (isDebugEnabled(marker)) {
            logger.log((org.apache.logging.log4j.Marker) marker, FQCN, Level.DEBUG,
                new ParameterizedMessage(s, o), null);
        }
    }

    @Override
    public void debug(final Marker marker, final String s, final Object o, final Object o1) {
        if (isDebugEnabled(marker)) {
            final ParameterizedMessage msg = new ParameterizedMessage(s, o, o1);
            logger.log((org.apache.logging.log4j.Marker) marker, FQCN, Level.DEBUG, msg, msg.getThrowable());
        }
    }

    @Override
    public void debug(final Marker marker, final String s, final Object... objects) {
        if (isDebugEnabled(marker)) {
            final ParameterizedMessage msg = new ParameterizedMessage(s, objects);
            logger.log((org.apache.logging.log4j.Marker) marker, FQCN, Level.DEBUG, msg, msg.getThrowable());
        }
    }

    @Override
    public void debug(final Marker marker, final String s, final Throwable throwable) {
        if (isDebugEnabled(marker)) {
            logger.log((org.apache.logging.log4j.Marker) marker, FQCN, Level.DEBUG,
                new SimpleMessage(s), throwable);
        }
    }

    @Override
    public void info(final String format) {
        if (logger.isInfoEnabled()) {
            logger.log(null, FQCN, Level.INFO, new SimpleMessage(format), null);
        }
    }

    @Override
    public void info(final String format, final Object o) {
        if (logger.isInfoEnabled()) {
            logger.log(null, FQCN, Level.INFO, new ParameterizedMessage(format, o), null);
        }
    }

    @Override
    public void info(final String format, final Object arg1, final Object arg2) {
        if (logger.isInfoEnabled()) {
            final ParameterizedMessage msg = new ParameterizedMessage(format, arg1, arg2);
            logger.log(null, FQCN, Level.INFO, msg, msg.getThrowable());
        }
    }

    @Override
    public void info(final String format, final Object... args) {
        if (logger.isInfoEnabled()) {
            final ParameterizedMessage msg = new ParameterizedMessage(format, args);
            logger.log(null, FQCN, Level.INFO, msg, msg.getThrowable());
        }
    }

    @Override
    public void info(final String format, final Throwable t) {
        if (logger.isInfoEnabled()) {
            logger.log(null, FQCN, Level.INFO, new SimpleMessage(format), t);
        }
    }

    @Override
    public boolean isInfoEnabled() {
        return logger.isInfoEnabled();
    }

    @Override
    public boolean isInfoEnabled(final Marker marker) {
        return logger.isInfoEnabled((org.apache.logging.log4j.Marker) marker);
    }

    @Override
    public void info(final Marker marker, final String s) {
        if (isInfoEnabled(marker)) {
            logger.log((org.apache.logging.log4j.Marker) marker, FQCN, Level.INFO, new SimpleMessage(s), null);
        }
    }

    @Override
    public void info(final Marker marker, final String s, final Object o) {
        if (isInfoEnabled(marker)) {
            logger.log((org.apache.logging.log4j.Marker) marker, FQCN, Level.INFO,
                new ParameterizedMessage(s, o), null);
        }
    }

    @Override
    public void info(final Marker marker, final String s, final Object o, final Object o1) {
        if (isInfoEnabled(marker)) {
            final ParameterizedMessage msg = new ParameterizedMessage(s, o, o1);
            logger.log((org.apache.logging.log4j.Marker) marker, FQCN, Level.INFO, msg, msg.getThrowable());
        }
    }

    @Override
    public void info(final Marker marker, final String s, final Object... objects) {
        if (isInfoEnabled(marker)) {
            final ParameterizedMessage msg = new ParameterizedMessage(s, objects);
            logger.log((org.apache.logging.log4j.Marker) marker, FQCN, Level.INFO, msg, msg.getThrowable());
        }
    }

    @Override
    public void info(final Marker marker, final String s, final Throwable throwable) {
        if (isInfoEnabled(marker)) {
            logger.log((org.apache.logging.log4j.Marker) marker, FQCN, Level.INFO,
                new SimpleMessage(s), throwable);
        }
    }

    @Override
    public void warn(final String format) {
        if (logger.isWarnEnabled()) {
            logger.log(null, FQCN, Level.WARN, new SimpleMessage(format), null);
        }
    }

    @Override
    public void warn(final String format, final Object o) {
        if (logger.isWarnEnabled()) {
            logger.log(null, FQCN, Level.WARN, new ParameterizedMessage(format, o), null);
        }
    }

    @Override
    public void warn(final String format, final Object arg1, final Object arg2) {
        if (logger.isWarnEnabled()) {
            final ParameterizedMessage msg = new ParameterizedMessage(format, arg1, arg2);
            logger.log(null, FQCN, Level.WARN, msg, msg.getThrowable());
        }
    }

    @Override
    public void warn(final String format, final Object... args) {
        if (logger.isWarnEnabled()) {
            final ParameterizedMessage msg = new ParameterizedMessage(format, args);
            logger.log(null, FQCN, Level.WARN, msg, msg.getThrowable());
        }
    }

    @Override
    public void warn(final String format, final Throwable t) {
        if (logger.isWarnEnabled()) {
            logger.log(null, FQCN, Level.WARN, new SimpleMessage(format), t);
        }
    }

    @Override
    public boolean isWarnEnabled() {
        return logger.isWarnEnabled();
    }

    @Override
    public boolean isWarnEnabled(final Marker marker) {
        return logger.isWarnEnabled((org.apache.logging.log4j.Marker) marker);
    }

    @Override
    public void warn(final Marker marker, final String s) {
        if (isWarnEnabled(marker)) {
            logger.log((org.apache.logging.log4j.Marker) marker, FQCN, Level.WARN, new SimpleMessage(s), null);
        }
    }

    @Override
    public void warn(final Marker marker, final String s, final Object o) {
        if (isWarnEnabled(marker)) {
            logger.log((org.apache.logging.log4j.Marker) marker, FQCN, Level.WARN,
                new ParameterizedMessage(s, o), null);
        }
    }

    @Override
    public void warn(final Marker marker, final String s, final Object o, final Object o1) {
        if (isWarnEnabled(marker)) {
            final ParameterizedMessage msg = new ParameterizedMessage(s, o, o1);
            logger.log((org.apache.logging.log4j.Marker) marker, FQCN, Level.WARN, msg, msg.getThrowable());
        }
    }

    @Override
    public void warn(final Marker marker, final String s, final Object... objects) {
        if (isWarnEnabled(marker)) {
            final ParameterizedMessage msg = new ParameterizedMessage(s, objects);
            logger.log((org.apache.logging.log4j.Marker) marker, FQCN, Level.WARN, msg, msg.getThrowable());
        }
    }

    @Override
    public void warn(final Marker marker, final String s, final Throwable throwable) {
        if (isWarnEnabled(marker)) {
            logger.log((org.apache.logging.log4j.Marker) marker, FQCN, Level.WARN,
                new SimpleMessage(s), throwable);
        }
    }

    @Override
    public void error(final String format) {
        if (logger.isErrorEnabled()) {
            logger.log(null, FQCN, Level.ERROR, new SimpleMessage(format), null);
        }
    }

    @Override
    public void error(final String format, final Object o) {
        if (logger.isErrorEnabled()) {
            logger.log(null, FQCN, Level.ERROR, new ParameterizedMessage(format, o), null);
        }
    }

    @Override
    public void error(final String format, final Object arg1, final Object arg2) {
        if (logger.isErrorEnabled()) {
            final ParameterizedMessage msg = new ParameterizedMessage(format, arg1, arg2);
            logger.log(null, FQCN, Level.ERROR, msg, msg.getThrowable());
        }
    }

    @Override
    public void error(final String format, final Object... args) {
        if (logger.isErrorEnabled()) {
            final ParameterizedMessage msg = new ParameterizedMessage(format, args);
            logger.log(null, FQCN, Level.ERROR, msg, msg.getThrowable());
        }
    }

    @Override
    public void error(final String format, final Throwable t) {
        if (logger.isErrorEnabled()) {
            logger.log(null, FQCN, Level.ERROR, new SimpleMessage(format), t);
        }
    }

    @Override
    public boolean isErrorEnabled() {
        return logger.isErrorEnabled();
    }

    @Override
    public boolean isErrorEnabled(final Marker marker) {
        return logger.isErrorEnabled((org.apache.logging.log4j.Marker) marker);
    }

    @Override
    public void error(final Marker marker, final String s) {
        if (isErrorEnabled(marker)) {
            logger.log((org.apache.logging.log4j.Marker) marker, FQCN, Level.ERROR, new SimpleMessage(s), null);
        }
    }

    @Override
    public void error(final Marker marker, final String s, final Object o) {
        if (isErrorEnabled(marker)) {
            logger.log((org.apache.logging.log4j.Marker) marker, FQCN, Level.ERROR,
                new ParameterizedMessage(s, o), null);
        }
    }

    @Override
    public void error(final Marker marker, final String s, final Object o, final Object o1) {
        if (isErrorEnabled(marker)) {
            final ParameterizedMessage msg = new ParameterizedMessage(s, o, o1);
            logger.log((org.apache.logging.log4j.Marker) marker, FQCN, Level.ERROR, msg, msg.getThrowable());
        }
    }

    @Override
    public void error(final Marker marker, final String s, final Object... objects) {
        if (isErrorEnabled(marker)) {
            final ParameterizedMessage msg = new ParameterizedMessage(s, objects);
            logger.log((org.apache.logging.log4j.Marker) marker, FQCN, Level.ERROR, msg, msg.getThrowable());
        }
    }

    @Override
    public void error(final Marker marker, final String s, final Throwable throwable) {
        if (isErrorEnabled(marker)) {
            logger.log((org.apache.logging.log4j.Marker) marker, FQCN, Level.ERROR,
                new SimpleMessage(s), throwable);
        }
    }

    @Override
    public void log(final Marker marker, final String fqcn, final int i, final String s1, final Object[] objects,
                    Throwable throwable) {
        if (!logger.isEnabled(getLevel(i), (org.apache.logging.log4j.Marker) marker, s1)) {
            return;
        }
        Message msg;
        if (eventLogger && marker != null && marker.contains(EVENT_MARKER) && converter != null) {
            msg = converter.convertEvent(s1, objects, throwable);
       } else if (objects == null) {
            msg = new SimpleMessage(s1);
        } else {
            msg = new ParameterizedMessage(s1, objects, throwable);
            if (throwable != null) {
                throwable = msg.getThrowable();
            }
        }
        logger.log((org.apache.logging.log4j.Marker) marker, fqcn, getLevel(i), msg, throwable);
    }

    @Override
    public String getName() {
        return name;
    }

    private EventDataConverter createConverter() {
        try {
            Class.forName("org.slf4j.ext.EventData");
            return new EventDataConverter();
        } catch (ClassNotFoundException cnfe) {
            return null;
        }
    }

    private Level getLevel(final int i) {
        switch (i) {
            case TRACE_INT :
                return Level.TRACE;
            case DEBUG_INT :
                return Level.DEBUG;
            case INFO_INT :
                return Level.INFO;
            case WARN_INT :
                return Level.WARN;
            case ERROR_INT :
                return Level.ERROR;
        }
        return Level.ERROR;
    }
}


text:
#ifndef ALIEN_H
#define ALIEN_H

enum alien_type {
	SHIP,
	POKEMON
};

typedef struct _alien {
	int type;
	int x, y;
	int x_vel, y_vel; // velocity
	int x_acc, y_acc; // acceleration
	int r;            // radius
	int lives;        // number of lives
} alien;

alien create_alien(int type, int x, int y);

void draw_alien(alien *a);

int has_collided(alien *a, alien *b);

void update_alien(alien *a);

void draw_aliens(alien *a, int cnt);

void draw_all_aliens();

void draw_lives();

void swap_aliens(alien *a, alien *b);

int is_dead(alien *a);

/*
 * Pokemons!
 */
void check_collisions_with_pokemons();

void delete_pokemon(int id);

void clean_pokemons();

void generate_pokemon();

void generate_pokemons(int add);

#endif


text:
package jp.yokomark.lgtm.app.compose.ui.helper.options;

import jp.yokomark.lgtm.app.compose.ui.ComposeActivity;
import jp.yokomark.lgtm.misc.ui.helper.OptionsMenuHandler;

/**
 * @author yokomakukeishin
 * @version 1.0.0
 * @since 1.0.0
 */
public class HomeUpHandler implements OptionsMenuHandler<ComposeActivity> {
    @Override
    public boolean handle(ComposeActivity activity) {
        activity.finish();
        return true;
    }
}


text:
/*
	author:rogan
*/

/*
 * Android communicate with arduino over bluetooth
 */
package mars.bluetootharduino;

import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
	private BluetoothAdapter mBluetoothAdapter;
	private BluetoothSocket btSocket;
	private OutputStream outputStream;
	private static final UUID MY_UUID = UUID
			.fromString("00001101-0000-1000-8000-00805F9B34FB");
	private static String ADDRESS = ("20:13:08:28:11:59");

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

		BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(ADDRESS);

		try {
			btSocket = device
					.createInsecureRfcommSocketToServiceRecord(MY_UUID);
		} catch (Exception e) {
			e.printStackTrace();
		}

		mBluetoothAdapter.cancelDiscovery();

		try {
			btSocket.connect();
		} catch (Exception e) {

			try {
				btSocket.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}

		Button mButtonF = (Button) findViewById(R.id.buttonF);
		mButtonF.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String message;
				byte[] msgBuffer;
				try {
					outputStream = btSocket.getOutputStream();
					message = "1";
					msgBuffer = message.getBytes();
					try {
						outputStream.write(msgBuffer);
					} catch (Exception e) {
					}
				} catch (Exception e) {
				}

			}
		});

		Button mButtonB = (Button) findViewById(R.id.buttonB);
		mButtonB.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String message;
				byte[] msgBuffer;
				try {
					outputStream = btSocket.getOutputStream();
					message = "2";
					msgBuffer = message.getBytes();
					try {
						outputStream.write(msgBuffer);
					} catch (Exception e) {
					}
				} catch (Exception e) {
				}

			}
		});

		Button mButtonL = (Button) findViewById(R.id.buttonL);
		mButtonL.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String message;
				byte[] msgBuffer;
				try {
					outputStream = btSocket.getOutputStream();
					message = "3";
					msgBuffer = message.getBytes();
					try {
						outputStream.write(msgBuffer);
					} catch (Exception e) {
					}
				} catch (Exception e) {
				}

			}
		});

		Button mButtonR = (Button) findViewById(R.id.buttonR);
		mButtonR.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String message;
				byte[] msgBuffer;
				try {
					outputStream = btSocket.getOutputStream();
					message = "4";
					msgBuffer = message.getBytes();
					try {
						outputStream.write(msgBuffer);
					} catch (Exception e) {
					}
				} catch (Exception e) {
				}

			}
		});

		Button mButtonS = (Button) findViewById(R.id.buttonS);
		mButtonS.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String message;
				byte[] msgBuffer;
				try {
					outputStream = btSocket.getOutputStream();
					message = "0";
					msgBuffer = message.getBytes();
					try {
						outputStream.write(msgBuffer);
					} catch (Exception e) {
					}
				} catch (Exception e) {
				}

			}
		});
	}

}


text:
import re
import urllib

from doctype import Doctype
from doctype import FetchedEntry

class W3cDoctype(Doctype):
  _HTML_RE = re.compile(
      '(.*)	')

  '''World Wide Web Consortium documentation'''

  def __init__(self):
    Doctype.__init__(self, 'w3c', 'W3C')

  def Fetch(self, args):
    html_url = args[0]

    html_html = self._FetchUrl(html_url)

    entries = []

    for (element_file, fragment_name, element_name) in \
        W3cDoctype._HTML_RE.findall(html_html):
      assert fragment_name.lower() == element_name.lower()

      element_name = element_name.lower()

      entries.append(FetchedEntry(element_name, 'HTML', element_file))

    return entries


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.SpaServices.Webpack;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using PicPository.Data;
using PicPository.Interfaces;
using PicPository.Services;

namespace PicPository
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<RethinkDbOptions>(Configuration.GetSection("ConnectionStrings:RethinkDb"));
            services.AddSingleton<IRethinkDbConnectionFactory, RethinkDbConnectionFactory>();
            services.AddSingleton<IRethinkDbStore, RethinkDbStore>();

            services.AddMvc();

            string domain = $"https://{Configuration["Auth0:Domain"]}/";
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

            }).AddJwtBearer(options =>
            {
                options.Authority = domain;
                options.Audience = Configuration["Auth0:ApiIdentifier"];
            });

            // // Add application services.
            services.AddTransient<IEmailSender, AuthMessageSender>();
            services.AddTransient<ISmsSender, AuthMessageSender>();

            // // SendGrid email options
            services.Configure<AuthMessageSenderOptions>(Configuration.GetSection("SendGrid"));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IRethinkDbStore store)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
                {
                    HotModuleReplacement = true
                });
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            store.InitializeDatabase();

            app.UseAuthentication();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}");

                routes.MapSpaFallbackRoute(
                    name: "spa-fallback",
                    defaults: new { controller = "Home", action = "Index" });
            });
        }
    }
}


text:
<?php
/**
 * @package    Phpmig
 * @subpackage Api
 */
namespace Phpmig\Api;

use Phpmig\Migration;
use RuntimeException;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * The phpmig application for API processing
 *
 * Usage:
 * <code>
 * $container = include_once "/full/path/to/phpmig.php";
 * $output = new Symfony\Component\Console\Output\OutputInterface\BufferedOutput;
 * $phpmig = new Phpmig\Api\PhpmigApplication($container, $output);
 * $phpmig->up(); // upgrade to latest version
 * echo $output->output(); // fetch output
 * </code>
 *
 * @author      Cody Phillips
 */
class PhpmigApplication
{
    protected $container;
    protected $output;
    protected $migrations;

    public function __construct(\ArrayAccess $container, OutputInterface $output)
    {
        $this->container = $container;
        $this->output = $output;
        if (!isset($this->container['phpmig.migrator']))
            $this->container['phpmig.migrator'] = new Migration\Migrator($container['phpmig.adapter'], $this->container, $this->output);

        $migrations = array();
        if (isset($this->container['phpmig.migrations'])) {
            $migrations = $this->container['phpmig.migrations'];
            foreach ($migrations as &$migration) {
                $migration = realpath($migration);
            }
            unset($migration);
        }
        if (isset($this->container['phpmig.migrations_path'])) {
            $migrationsPath = realpath($this->container['phpmig.migrations_path']);
            $migrations = array_merge($migrations, glob($migrationsPath . DIRECTORY_SEPARATOR . '*.php'));
        }

        $this->migrations = array_unique($migrations);
    }

    /**
     * Migrate up
     *
     * @param string $version The version to migrate up to
     */
    public function up($version = null)
    {
        $adapter = ! empty($this->container['phpmig.adapter']) ? $this->container['phpmig.adapter'] : null;

        if ($adapter == null) {

            throw new RuntimeException("The container must contain a phpmig.adapter key!");
        }

        if (!$adapter->hasSchema()) {

            $this->container['phpmig.adapter']->createSchema();
        }

        foreach ($this->getMigrations($this->getVersion(), $version) as $migration) {
            $this->container['phpmig.migrator']->up($migration);
        }
    }

    /**
     * Migrate down
     *
     * @param string $version The version to migrate down to
     */
    public function down($version = 0)
    {
        if ($version === null || $version < 0)
            throw new \InvalidArgumentException("Invalid version given, expected  >= 0.");

        foreach ($this->getMigrations($this->getVersion(), $version) as $migration) {
            $this->container['phpmig.migrator']->down($migration);
        }
    }

    /**
     * Load all migrations to get $from to $to
     *
     * @param string $from The from version
     * @param string $to The to version
     * @return array An array of Phpmig\Migration\Migration objects to process
     */
    public function getMigrations($from, $to = null)
    {
        $migrations = array();

        if ($to > $from || $to === null) {
            ksort($this->migrations);
        } else {
            krsort($this->migrations);
        }

        foreach ($this->migrations as $path) {
            preg_match('/^[0-9]+/', basename($path), $matches);
            if (!array_key_exists(0, $matches)) {
                continue;
            }

            $version = $matches[0];

            // up
            if ($to > $from || $to === null) {
                if ($version > $from && ($version <= $to || $to === null)) {
                    $migrations[] = $path;
                }
            // down
            } elseif ($to < $from && $version > $to && $version <= $from) {
                $migrations[] = $path;
            }
        }

        return $this->loadMigrations($migrations);
    }

    /**
     * Loads migrations from the given set of available migration files
     *
     * @param array $migrations An array of migration files to prepare migrations for
     * @return array An array of Phpmig\Migration\Migration objects
     */
    protected function loadMigrations($migrations)
    {
        $versions = array();
        $names = array();
        foreach ($migrations as $path) {
            if (!preg_match('/^[0-9]+/', basename($path), $matches)) {
                throw new \InvalidArgumentException(sprintf('The file "%s" does not have a valid migration filename', $path));
            }

            $version = $matches[0];

            if (isset($versions[$version])) {
                throw new \InvalidArgumentException(sprintf('Duplicate migration, "%s" has the same version as "%s"', $path, $versions[$version]->getName()));
            }

            $migrationName = preg_replace('/^[0-9]+_/', '', basename($path));
            if (false !== strpos($migrationName, '.')) {
                $migrationName = substr($migrationName, 0, strpos($migrationName, '.'));
            }
            $class = $this->migrationToClassName($migrationName);

            if (isset($names[$class])) {
                throw new \InvalidArgumentException(sprintf(
                    'Migration "%s" has the same name as "%s"',
                    $path,
                    $names[$class]
                ));
            }
            $names[$class] = $path;

            require_once $path;
            if (!class_exists($class)) {
                throw new \InvalidArgumentException(sprintf(
                    'Could not find class "%s" in file "%s"',
                    $class,
                    $path
                ));
            }

            $migration = new $class($version);

            if (!($migration instanceof Migration\Migration)) {
                throw new \InvalidArgumentException(sprintf(
                    'The class "%s" in file "%s" must extend \Phpmig\Migration\Migration',
                    $class,
                    $path
                ));
            }

            $migration->setOutput($this->output); // inject output

            $versions[$version] = $migration;
        }

        return $versions;
    }

    /**
     * Transform create_table_user to CreateTableUser
     *
     * @param string $migrationName The migration name
     * @return string The CamelCase migration name
     */
    protected function migrationToClassName($migrationName)
    {
        $class = str_replace('_', ' ', $migrationName);
        $class = ucwords($class);
        return str_replace(' ', '', $class);
    }

    /**
     * Returns the current version
     *
     * @return string The current installed version
     */
    public function getVersion()
    {
        $versions = $this->container['phpmig.adapter']->fetchAll();
        sort($versions);

        if (!empty($versions)) {
            return end($versions);
        }
        return 0;
    }
}


text:
package com.cdancy.bitbucket.rest.domain.insights;

import com.google.auto.value.AutoValue;
import org.jclouds.json.SerializedNames;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;

@AutoValue
public abstract class InsightReportData {
    public enum DataType {
        BOOLEAN,
        DATE,
        DURATION,
        LINK,
        NUMBER,
        PERCENTAGE,
        TEXT
    }

    public abstract String title();

    public abstract DataType type();

    public abstract Object value();

    @SerializedNames({"title", "type", "value"})
    private static InsightReportData create(final String title,
            final DataType type,
            final Object value) {
        return new AutoValue_InsightReportData(title, type, value);
    }

    public static InsightReportData createBoolean(final String title, final boolean value) {
        return create(title, DataType.BOOLEAN, value);
    }

    public static InsightReportData createDate(final String title, final LocalDate value) {
        return createDate(title, value.atStartOfDay());
    }

    public static InsightReportData createDate(final String title, final LocalDateTime value) {
        final long epochMilli = value.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        return createDate(title, epochMilli);
    }

    public static InsightReportData createDate(final String title, final long epochMilli) {
        return create(title, DataType.DATE, epochMilli);
    }

    public static InsightReportData createDuration(final String title, final Duration duration) {
        return create(title, DataType.DURATION, duration.toMillis());
    }

    public static InsightReportData createDuration(final String title, final long millis) {
        return create(title, DataType.DURATION, millis);
    }

    public static InsightReportData createLink(final String title, final String href) {
        return createLink(title, href, href);
    }

    public static InsightReportData createLink(final String title,
            final String href,
            final String linkText) {
        final InsightReportDataLink link = InsightReportDataLink.create(linkText, href);
        return create(title, DataType.LINK, link);
    }

    public static InsightReportData createNumber(final String title, final long number) {
        return create(title, DataType.NUMBER, number);
    }

    public static InsightReportData createPercentage(final String title, final byte percentage) {
        return create(title, DataType.PERCENTAGE, percentage);
    }

    public static InsightReportData createText(final String title, final String text) {
        return create(title, DataType.TEXT, text);
    }
}


text:
rss: false
layout: article
title: "Optimize Performance Under Varying Network Conditions"
seotitle: "Optimize Performance Under Varying Network Conditions Using Chrome DevTools Network Panel"
description: "TBD description."
introduction: "TBD introduction."
article:
  written_on: 2015-04-14
  updated_on: 2015-04-14
  order: 3
authors:
  - megginkearney
priority: 0
collection: network-performance
key-takeaways:
  tldr-tbd:
    - TBD tldr.
remember:
  note-tbd:
    - TBD note.
---
{% wrap content %}

TBD. Doc: https://developer.chrome.com/devtools/docs/device-mode#network-conditions

TBD. Doc: Network panel docs: https://developer.chrome.com/devtools/docs/network#network-panel-overview

TBD. Also: https://developers.google.com/web/fundamentals/tools/test/mobilenetwork?hl=en

{% include modules/takeaway.liquid list=page.key-takeaways.tldr-tbd %}

## Fix slow page loads

If your users wait longer than 1 second for a page load,
there's a good chance they won't be coming back.
Successful page loads aren't about getting everyone on a page to load under 1 second.
You need to prioritize and display content that relates
to the primary action users want to take on that page.

Follow these steps to optimize the critical rendering path to deliver fast first page loads (see [Optimizing the Critical Rendering Path](/web/fundamentals/performance/critical-rendering-path/optimizing-critical-rendering-path)):

1. Analyze your critical path: number of resources, bytes, length. Use the Chrome DevTools Network panel to [measure resource loading times](/web/tools/profile-performance/network-performance/resource-loading).
2. Minimize number of critical resources (eliminate, defer, mark as async).
3. Optimize the order in which critical resources are downloaded.
4. Reduce the number of roundtrips to get critical bytes.

Use the [PageSpeed Insights tool](https://developers.google.com/speed/pagespeed/insights/)
to test page loads and find out what's getting in the way of the critical rendering path.
You and also find out more in [PageSpeed Rules and Recommendations](/web/fundamentals/performance/critical-rendering-path/page-speed-rules-and-recommendations).

{% include modules/remember.liquid title="Remember" list=page.remember.note-tbd %}

{% include modules/nextarticle.liquid %}

{% endwrap %}


text:
/**
 * Working with objects.
 */
gui.Object = {

	/**
	 * Object.create with default property descriptors.
	 * @see http://wiki.ecmascript.org/doku.php?id=strawman:define_properties_operator
	 * @param {object} proto
	 * @param {object} props
	 */
	create: function(proto, props) {
		var resolved = {};
		Object.keys(props).forEach(function(prop) {
			resolved[prop] = {
				value: props[prop],
				writable: true,
				enumerable: true,
				configurable: true
			};
		});
		return Object.create(proto, resolved);
	},

	/**
	 * Extend target with source properties *excluding* prototype stuff.
	 * Optional parameter 'loose' to skips properties already declared.
	 * TODO: bypass mixin?
	 * @param {object} target
	 * @param {object} source
	 * @param @optional {boolean} loose Skip properties already declared
	 * @returns {object}
	 */
	extend: function(target, source, loose) {
		var hiding = this._hiding;
		if (gui.Type.isObject(source)) {
			Object.keys(source).forEach(function(key) {
				if (!loose || !gui.Type.isDefined(target[key])) {
					var desc = Object.getOwnPropertyDescriptor(source, key);
					desc = hiding ? gui.Object._hide(desc) : desc;
					Object.defineProperty(target, key, desc);
				}
			}, this);
		} else {
			throw new TypeError("Expected object, got " + gui.Type.of(source));
		}
		return target;
	},

	/**
	 * Extend target with source properties,
	 * skipping everything already declared.
	 * @param {object} target
	 * @param {object} source
	 * @returns {object}
	 */
	extendmissing: function(target, source) {
		return this.extend(target, source, true);
	},

	/**
	 * Copy object.
	 * @returns {object}
	 */
	copy: function(source) {
		try {
			return this.extend({}, source);
		} catch (exception) {
			throw new TypeError("Could not object-copy " + gui.Type.of(source));
		}
	},

	/**
	 * Call function for each own key in object (exluding the prototype stuff)
	 * with key and value as arguments. Returns array of function call results.
	 * Function results that are `undefined` get's filtered out of this list.
	 * @param {object} object
	 * @param {function} func
	 * @param @optional {object} thisp
	 */
	each: function(object, func, thisp) {
		return Object.keys(object).map(function(key) {
			return func.call(thisp, key, object[key]);
		}).filter(function(result) {
			return result !== undefined;
		});
	},

	/**
	 * Call function for all properties in object (including prototype stuff)
	 * with key and value as arguments. Returns array of function call results.
	 * @param {object} object
	 * @param {function} func
	 * @param @optional {object} thisp
	 */
	all: function(object, func, thisp) {
		var res = [];
		for (var key in object) {
			res.push(func.call(thisp, key, object[key]));
		}
		return res.filter(function(result) {
			return result !== undefined;
		});
	},

	/**
	 * Create new object by passing all property
	 * names and values through a resolver call.
	 * Eliminate values that map to `undefined`.
	 * @param {object} source
	 * @param {function} domap
	 * @param @optional {object} thisp
	 * @returns {object}
	 */
	map: function(source, domap, thisp) {
		var result = {},
			mapping;
		this.each(source, function(key, value) {
			mapping = domap.call(thisp, key, value);
			if (mapping !== undefined) {
				result[key] = mapping;
			}
		});
		return result;
	},

	/**
	 * Lookup object for string of type "my.ns.Thing" in given context or this window.
	 * @param {String} opath Object path eg. "my.ns.Thing"
	 * @param @optional {Window} context
	 * @returns {object}
	 */
	lookup: function(opath, context) {
		var result, struct = context || self;
		if (gui.Type.isString(opath)) {
			if (!opath.includes(".")) {
				result = struct[opath];
			} else {
				var parts = opath.split(".");
				parts.every(function(part) {
					struct = struct[part];
					return gui.Type.isDefined(struct);
				});
				result = struct;
			}
		} else {
			throw new TypeError("Expected string, got " + gui.Type.of(opath));
		}
		return result;
	},

	/**
	 * Update property of object in given context based on string input.
	 * TODO: Rename "declare"
	 * @param {String} opath Object path eg. "my.ns.Thing.name"
	 * @param {object} value Property value eg. `"Johnson` or"` `[]`
	 * @param @optional {Window|object} context
	 * @returns {object}
	 */
	assert: function(opath, value, context) {
		var prop, struct = context || self;
		if (opath.includes(".")) {
			var parts = opath.split(".");
			prop = parts.pop();
			parts.forEach(function(part) {
				struct = struct[part] || (struct[part] = {});
			});
		} else {
			prop = opath;
		}
		if (struct) {
			struct[prop] = value;
		}
		return value;
	},

	/**
	 * List names of invocable methods *including* prototype stuff.
	 * @return {Array<String>}
	 */
	methods: function(object) {
		var name, value, desc, obj = object,
			result = [];
		for (name in object) {
			// make sure that we don't poke any getter type properties...
			while (!(desc = Object.getOwnPropertyDescriptor(obj, name))) {
				obj = Object.getPrototypeOf(obj);
			}
			if (typeof desc.value === 'function') {
				value = object[name];
				if (gui.Type.isMethod(value)) {
					result.push(name);
				}
			}
		}
		return result;
	},

	/**
	 * List names of invocable methods *excluding* prototype stuff.
	 * @return {Array<String>}
	 */
	ownmethods: function(object) {
		return Object.keys(object).filter(function(key) {
			return gui.Type.isMethod(object[key]);
		}).map(function(key) {
			return key;
		});
	},

	/**
	 * List names of non-method properties *including* prototype stuff.
	 * @return {Array<String>}
	 */
	nonmethods: function(object) {
		var result = [];
		for (var def in object) {
			if (!gui.Type.isFunction(object[def])) {
				result.push(def);
			}
		}
		return result;
	},

	/**
	 * Bind the "this" keyword for all public instance methods.
	 * Stuff descending from the prototype chain is ignored.
	 * TODO: does this belong here?
	 * @param {object} object
	 * @returns {object}
	 */
	bindall: function(object) {
		var methods = Array.prototype.slice.call(arguments).slice(1);
		if (!methods.length) {
			methods = gui.Object.ownmethods(object).filter(function(name) {
				return name[0] !== "_"; // exclude private methods
			});
		}
		methods.forEach(function(name) {
			object[name] = object[name].bind(object);
		});
		return object;
	},

	/**
	 * Sugar for creating non-enumerable function properties (methods).
	 * To be be used in combination with `gui.Object.extend` for effect.
	 * `mymethod : gui.Object.hidden ( function () {})'
	 * @param {function} method
	 * @return {function}
	 */
	hidden: function(method) {
		gui.Object._hiding = true;
		method.$hidden = true;
		return method;
	},

	// Private ...................................................................

	/**
	 * Hiding any methods from inspection?
	 * Otherwise economize a function call.
	 * @see {edb.Object#extend}
	 * @type {boolean}
	 */
	_hiding: false,

	/**
	 * Modify method descriptor to hide from inspection.
	 * Do note that the method may still be called upon.
	 * @param {object} desc
	 * @returns {object}
	 */
	_hide: function(desc) {
		if (desc.value && gui.Type.isFunction(desc.value)) {
			if (desc.value.$hidden && desc.configurable) {
				desc.enumerable = false;
			}
		}
		return desc;
	}
};


text:
            健康档案
            >
            随访记录


text:
<?php
$result = array();
$req = autocomplete($autocomplete_str);
while($data = mysql_fetch_array($req))
{
	array_push($result, $data[$autocomplete_str]);
}
echo json_encode($result);
?>


text:
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Windows.Input;

namespace LiveSplit.Model.Input
{
    public sealed class HotkeyHook : IDisposable
    {
        public static HotkeyHook Instance { get; set; }

        static HotkeyHook()
        {
            Instance = new HotkeyHook();
        }

        private HotkeyHook()
        {
            _window.KeyPressed += delegate(object sender, KeyPressedEventArgs args)
            {
                if (KeyPressed != null)
                {
                    KeyPressed(this, args);
                }
            };
        }

        public class KeyPressedEventArgs : EventArgs
        {
            public ModifierKeys Modifier { get; private set; }
            public Keys Key { get; private set; }

            internal KeyPressedEventArgs(ModifierKeys modifier, Keys key)
            {
                Modifier = modifier;
                Key = key;
            }
        }

        private class Window : NativeWindow, IDisposable
        {
            private static int WM_HOTKEY = 786;
            public event EventHandler<KeyPressedEventArgs> KeyPressed;
            public Window()
            {
                CreateHandle(new CreateParams());
            }
            protected override void WndProc(ref Message m)
            {
                base.WndProc(ref m);
                if (m.Msg == WM_HOTKEY)
                {
                    Keys key = (Keys)((int)m.LParam >> 16 & 65535);
                    ModifierKeys modifier = (ModifierKeys)((int)m.LParam & 65535);
                    if (KeyPressed != null)
                    {
                        KeyPressed(this, new KeyPressedEventArgs(modifier, key));
                    }
                }
            }
            public void Dispose()
            {
                DestroyHandle();
            }
        }
        private Window _window = new Window();
        private int _currentId;
        public event EventHandler<KeyPressedEventArgs> KeyPressed;
        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
        public void RegisterHotKey(ModifierKeys modifier, Keys key)
        {
            _currentId++;
            if (!RegisterHotKey(_window.Handle, _currentId, (uint)modifier, (uint)key))
            {
                throw new InvalidOperationException("Couldn't register the hot key.");
            }
        }

        public void UnregisterAllHotkeys()
        {
            for (int i = _currentId; i > 0; i--)
            {
                UnregisterHotKey(_window.Handle, i);
            }
            _currentId = 0;
        }

        public void Dispose()
        {
            UnregisterAllHotkeys();
            _window.Dispose();
        }
    }
}


text:
'use strict';

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }

function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var React = require('react');
var accept = require('attr-accept');

var Dropzone = (function (_React$Component) {
  _inherits(Dropzone, _React$Component);

  function Dropzone(props, context) {
    _classCallCheck(this, Dropzone);

    _React$Component.call(this, props, context);
    this.onClick = this.onClick.bind(this);
    this.onDragEnter = this.onDragEnter.bind(this);
    this.onDragLeave = this.onDragLeave.bind(this);
    this.onDragOver = this.onDragOver.bind(this);
    this.onDrop = this.onDrop.bind(this);

    this.state = {
      isDragActive: false
    };
  }

  Dropzone.prototype.componentDidMount = function componentDidMount() {
    this.enterCounter = 0;
  };

  Dropzone.prototype.allFilesAccepted = function allFilesAccepted(files) {
    var _this = this;

    return files.every(function (file) {
      return accept(file, _this.props.accept);
    });
  };

  Dropzone.prototype.onDragEnter = function onDragEnter(e) {
    e.preventDefault();

    // Count the dropzone and any children that are entered.
    ++this.enterCounter;

    // This is tricky. During the drag even the dataTransfer.files is null
    // But Chrome implements some drag store, which is accesible via dataTransfer.items
    var dataTransferItems = e.dataTransfer && e.dataTransfer.items ? e.dataTransfer.items : [];

    // Now we need to convert the DataTransferList to Array
    var itemsArray = Array.prototype.slice.call(dataTransferItems);
    var allFilesAccepted = this.allFilesAccepted(itemsArray);

    this.setState({
      isDragActive: allFilesAccepted,
      isDragReject: !allFilesAccepted
    });

    if (this.props.onDragEnter) {
      this.props.onDragEnter(e);
    }
  };

  Dropzone.prototype.onDragOver = function onDragOver(e) {
    e.preventDefault();
  };

  Dropzone.prototype.onDragLeave = function onDragLeave(e) {
    e.preventDefault();

    // Only deactivate once the dropzone and all children was left.
    if (--this.enterCounter > 0) {
      return;
    }

    this.setState({
      isDragActive: false,
      isDragReject: false
    });

    if (this.props.onDragLeave) {
      this.props.onDragLeave(e);
    }
  };

  Dropzone.prototype.onDrop = function onDrop(e) {
    e.preventDefault();

    // Reset the counter along with the drag on a drop.
    this.enterCounter = 0;

    this.setState({
      isDragActive: false,
      isDragReject: false
    });

    var droppedFiles = e.dataTransfer ? e.dataTransfer.files : e.target.files;
    var max = this.props.multiple ? droppedFiles.length : 1;
    var files = [];

    for (var i = 0; i < max; i++) {
      var file = droppedFiles[i];
      file.preview = window.URL.createObjectURL(file);
      files.push(file);
    }

    if (this.props.onDrop) {
      this.props.onDrop(files, e);
    }

    if (this.allFilesAccepted(files)) {
      if (this.props.onDropAccepted) {
        this.props.onDropAccepted(files, e);
      }
    } else {
      if (this.props.onDropRejected) {
        this.props.onDropRejected(files, e);
      }
    }
  };

  Dropzone.prototype.onClick = function onClick() {
    if (!this.props.disableClick) {
      this.open();
    }
  };

  Dropzone.prototype.open = function open() {
    var fileInput = this.refs.fileInput;
    fileInput.value = null;
    fileInput.click();
  };

  Dropzone.prototype.render = function render() {
    var className, style, activeStyle;

    if (this.props.className) {
      className = this.props.className;
      if (this.state.isDragActive && this.props.activeClassName) {
        className += ' ' + this.props.activeClassName;
      }
      if (this.state.isDragReject && this.props.rejectClassName) {
        className += ' ' + this.props.rejectClassName;
      }
    }

    if (this.props.style || this.props.activeStyle) {
      if (this.props.style) {
        style = this.props.style;
      }
      if (this.props.activeStyle) {
        activeStyle = this.props.activeStyle;
      }
    } else if (!className) {
      style = {
        width: 200,
        height: 200,
        borderWidth: 2,
        borderColor: '#666',
        borderStyle: 'dashed',
        borderRadius: 5
      };
      activeStyle = {
        borderStyle: 'solid',
        backgroundColor: '#eee'
      };
    }

    var appliedStyle;
    if (activeStyle && this.state.isDragActive) {
      appliedStyle = _extends({}, style, activeStyle);
    } else {
      appliedStyle = _extends({}, style);
    }

    return React.createElement(
      'div',
      {
        className: className,
        style: appliedStyle,
        onClick: this.onClick,
        onDragEnter: this.onDragEnter,
        onDragOver: this.onDragOver,
        onDragLeave: this.onDragLeave,
        onDrop: this.onDrop
      },
      this.props.children,
      React.createElement('input', {
        type: 'file',
        ref: 'fileInput',
        style: { display: 'none' },
        multiple: this.props.multiple,
        accept: this.props.accept,
        onChange: this.onDrop
      })
    );
  };

  return Dropzone;
})(React.Component);

Dropzone.defaultProps = {
  disableClick: false,
  multiple: true
};

Dropzone.propTypes = {
  onDrop: React.PropTypes.func,
  onDropAccepted: React.PropTypes.func,
  onDropRejected: React.PropTypes.func,
  onDragEnter: React.PropTypes.func,
  onDragLeave: React.PropTypes.func,

  style: React.PropTypes.object,
  activeStyle: React.PropTypes.object,
  className: React.PropTypes.string,
  activeClassName: React.PropTypes.string,
  rejectClassName: React.PropTypes.string,

  disableClick: React.PropTypes.bool,
  multiple: React.PropTypes.bool,
  accept: React.PropTypes.string
};

module.exports = Dropzone;


text:
#include <config.h>

#include <stdio.h>
#include <string.h>

#include <mosquitto_broker.h>
#include "mosquitto_plugin.h"
#include <memory_mosq.h>
#include "lib_load.h"

typedef int (*FUNC_auth_plugin_version)(void);
typedef int (*FUNC_auth_plugin_init)(void **, struct mosquitto_auth_opt *, int);
typedef int (*FUNC_auth_plugin_cleanup)(void *, struct mosquitto_auth_opt *, int);
typedef int (*FUNC_auth_plugin_security_init)(void *, struct mosquitto_auth_opt *, int, bool);
typedef int (*FUNC_auth_plugin_security_cleanup)(void *, struct mosquitto_auth_opt *, int, bool);
typedef int (*FUNC_auth_plugin_acl_check)(void *, const char *, const char *, const char *, int);
typedef int (*FUNC_auth_plugin_unpwd_check)(void *, const char *, const char *);
typedef int (*FUNC_auth_plugin_psk_key_get)(void *, const char *, const char *, char *, int);

int mosquitto_security_module_init(struct mosquitto_db *db)
{
	void *lib;
	int (*plugin_version)(void) = NULL;
	int version;
	int rc;
	if(db->config->auth_plugin){
		lib = LIB_LOAD(db->config->auth_plugin);
		if(!lib){
			_mosquitto_log_printf(NULL, MOSQ_LOG_ERR,
					"Error: Unable to load auth plugin \"%s\".", db->config->auth_plugin);
			return 1;
		}

		db->auth_plugin.lib = NULL;
		if(!(plugin_version = (FUNC_auth_plugin_version)LIB_SYM(lib, "mosquitto_auth_plugin_version"))){
			_mosquitto_log_printf(NULL, MOSQ_LOG_ERR,
					"Error: Unable to load auth plugin function mosquitto_auth_plugin_version().");
			LIB_CLOSE(lib);
			return 1;
		}
		version = plugin_version();
		if(version != MOSQ_AUTH_PLUGIN_VERSION){
			_mosquitto_log_printf(NULL, MOSQ_LOG_ERR,
					"Error: Incorrect auth plugin version (got %d, expected %d).",
					version, MOSQ_AUTH_PLUGIN_VERSION);

			LIB_CLOSE(lib);
			return 1;
		}
		if(!(db->auth_plugin.plugin_init = (FUNC_auth_plugin_init)LIB_SYM(lib, "mosquitto_auth_plugin_init"))){
			_mosquitto_log_printf(NULL, MOSQ_LOG_ERR,
					"Error: Unable to load auth plugin function mosquitto_auth_plugin_init().");
			LIB_CLOSE(lib);
			return 1;
		}
		if(!(db->auth_plugin.plugin_cleanup = (FUNC_auth_plugin_cleanup)LIB_SYM(lib, "mosquitto_auth_plugin_cleanup"))){
			_mosquitto_log_printf(NULL, MOSQ_LOG_ERR,
					"Error: Unable to load auth plugin function mosquitto_auth_plugin_cleanup().");
			LIB_CLOSE(lib);
			return 1;
		}

		if(!(db->auth_plugin.security_init = (FUNC_auth_plugin_security_init)LIB_SYM(lib, "mosquitto_auth_security_init"))){
			_mosquitto_log_printf(NULL, MOSQ_LOG_ERR,
					"Error: Unable to load auth plugin function mosquitto_auth_security_init().");
			LIB_CLOSE(lib);
			return 1;
		}

		if(!(db->auth_plugin.security_cleanup = (FUNC_auth_plugin_security_cleanup)LIB_SYM(lib, "mosquitto_auth_security_cleanup"))){
			_mosquitto_log_printf(NULL, MOSQ_LOG_ERR,
					"Error: Unable to load auth plugin function mosquitto_auth_security_cleanup().");
			LIB_CLOSE(lib);
			return 1;
		}

		if(!(db->auth_plugin.acl_check = (FUNC_auth_plugin_acl_check)LIB_SYM(lib, "mosquitto_auth_acl_check"))){
			_mosquitto_log_printf(NULL, MOSQ_LOG_ERR,
					"Error: Unable to load auth plugin function mosquitto_auth_acl_check().");
			LIB_CLOSE(lib);
			return 1;
		}

		if(!(db->auth_plugin.unpwd_check = (FUNC_auth_plugin_unpwd_check)LIB_SYM(lib, "mosquitto_auth_unpwd_check"))){
			_mosquitto_log_printf(NULL, MOSQ_LOG_ERR,
					"Error: Unable to load auth plugin function mosquitto_auth_unpwd_check().");
			LIB_CLOSE(lib);
			return 1;
		}

		if(!(db->auth_plugin.psk_key_get = (FUNC_auth_plugin_psk_key_get)LIB_SYM(lib, "mosquitto_auth_psk_key_get"))){
			_mosquitto_log_printf(NULL, MOSQ_LOG_ERR,
					"Error: Unable to load auth plugin function mosquitto_auth_psk_key_get().");
			LIB_CLOSE(lib);
			return 1;
		}

		db->auth_plugin.lib = lib;
		db->auth_plugin.user_data = NULL;
		if(db->auth_plugin.plugin_init){
			rc = db->auth_plugin.plugin_init(&db->auth_plugin.user_data, db->config->auth_options, db->config->auth_option_count);
			if(rc){
				_mosquitto_log_printf(NULL, MOSQ_LOG_ERR,
						"Error: Authentication plugin returned %d when initialising.", rc);
			}
			return rc;
		}
	}else{
		db->auth_plugin.lib = NULL;
		db->auth_plugin.plugin_init = NULL;
		db->auth_plugin.plugin_cleanup = NULL;
		db->auth_plugin.security_init = NULL;
		db->auth_plugin.security_cleanup = NULL;
		db->auth_plugin.acl_check = NULL;
		db->auth_plugin.unpwd_check = NULL;
		db->auth_plugin.psk_key_get = NULL;
	}

	return MOSQ_ERR_SUCCESS;
}

int mosquitto_security_module_cleanup(struct mosquitto_db *db)
{
	mosquitto_security_cleanup(db, false);

	if(db->auth_plugin.plugin_cleanup){
		db->auth_plugin.plugin_cleanup(db->auth_plugin.user_data, db->config->auth_options, db->config->auth_option_count);
	}

	if(db->config->auth_plugin){
		if(db->auth_plugin.lib){
			LIB_CLOSE(db->auth_plugin.lib);
		}
	}
	db->auth_plugin.lib = NULL;
	db->auth_plugin.plugin_init = NULL;
	db->auth_plugin.plugin_cleanup = NULL;
	db->auth_plugin.security_init = NULL;
	db->auth_plugin.security_cleanup = NULL;
	db->auth_plugin.acl_check = NULL;
	db->auth_plugin.unpwd_check = NULL;
	db->auth_plugin.psk_key_get = NULL;

	return MOSQ_ERR_SUCCESS;
}

int mosquitto_security_init(struct mosquitto_db *db, bool reload)
{
	if(!db->auth_plugin.lib){
		return mosquitto_security_init_default(db, reload);
	}else{
		return db->auth_plugin.security_init(db->auth_plugin.user_data, db->config->auth_options, db->config->auth_option_count, reload);
	}
}

/* Apply security settings after a reload.
 * Includes:
 * - Disconnecting anonymous users if appropriate
 * - Disconnecting users with invalid passwords
 * - Reapplying ACLs
 */
int mosquitto_security_apply(struct mosquitto_db *db)
{
	if(!db->auth_plugin.lib){
		return mosquitto_security_apply_default(db);
	}
	return MOSQ_ERR_SUCCESS;
}

int mosquitto_security_cleanup(struct mosquitto_db *db, bool reload)
{
	if(!db->auth_plugin.lib){
		return mosquitto_security_cleanup_default(db, reload);
	}else{
		return db->auth_plugin.security_cleanup(db->auth_plugin.user_data, db->config->auth_options, db->config->auth_option_count, reload);
	}
}

int mosquitto_acl_check(struct mosquitto_db *db, struct mosquitto *context, const char *topic, int access)
{
	if(!db->auth_plugin.lib){
		return mosquitto_acl_check_default(db, context, topic, access);
	}else{
#ifdef WITH_BRIDGE
		if(context->bridge){
			return db->auth_plugin.acl_check(db->auth_plugin.user_data, context->id, context->bridge->local_username, topic, access);
		}else{
#endif
			return db->auth_plugin.acl_check(db->auth_plugin.user_data, context->id, context->username, topic, access);
#ifdef WITH_BRIDGE
		}
#endif
	}
}

int mosquitto_unpwd_check(struct mosquitto_db *db, const char *username, const char *password)
{
	if(!db->auth_plugin.lib){
		return mosquitto_unpwd_check_default(db, username, password);
	}else{
		return db->auth_plugin.unpwd_check(db->auth_plugin.user_data, username, password);
	}
}

int mosquitto_psk_key_get(struct mosquitto_db *db, const char *hint, const char *identity, char *key, int max_key_len)
{
	if(!db->auth_plugin.lib){
		return mosquitto_psk_key_get_default(db, hint, identity, key, max_key_len);
	}else{
		return db->auth_plugin.psk_key_get(db->auth_plugin.user_data, hint, identity, key, max_key_len);
	}
}


text:
var expect = require("chai").expect;
var sinon = require("sinon");
var ReadlineStub = require("../../helpers/readline");

var inquirer = require("../../../lib/inquirer");
var Choices = require("../../../lib/objects/choices");
var Choice = require("../../../lib/objects/choice");

describe("Choices collection", function() {

  it("should create Choice object from array member", function() {
    var choices = new Choices([ "bar", { name: "foo" } ]);
    expect( choices.getChoice(0) ).to.be.instanceOf( Choice );
    expect( choices.getChoice(1) ).to.be.instanceOf( Choice );
  });

  it("should not process Separator object", function() {
    var sep = new inquirer.Separator();
    var choices = new Choices([ "Bar", sep ]);
    expect( choices.get(0).name ).to.equal("Bar");
    expect( choices.get(1) ).to.equal( sep );
  });

  it("should provide access to length information", function() {
    var choices = new Choices([ "Bar", new inquirer.Separator(), "foo" ]);
    expect( choices.length ).to.equal( 3 );
    expect( choices.realLength ).to.equal( 2 );

    choices.length = 1;
    expect( choices.length ).to.equal( 1 );
    expect( choices.get(1) ).to.not.exist;
    expect(function() { choices.realLength = 0; }).to.throw;
  });

  it("should allow plucking choice content", function() {
    var choices = new Choices([{ name: "n", key: "foo"}, { name: "a", key: "lab" }]);
    expect( choices.pluck("key") ).to.eql([ "foo", "lab" ]);
  });

  it("should allow filtering value with where", function() {
    var choices = new Choices([{ name: "n", key: "foo"}, { name: "a", key: "lab" }]);
    expect(choices.where({ key: "lab" })).to.eql([{ name: "a", value: "a", key: "lab" }]);
  });

  it("should façade forEach", function() {
    var raw = [ "a", "b", "c" ];
    var choices = new Choices( raw );
    choices.forEach(function( val, i ) {
      expect( val.name ).to.equal( raw[i] );
    });
  });

  it("should façade filter", function() {
    var choices = new Choices([ "a", "b", "c" ]);
    var filtered = choices.filter(function( val, i ) {
      return val.name === "a";
    });
    expect( filtered.length ).to.equal( 1 );
    expect( filtered[0].name ).to.equal("a");
  });

  it("should façade push and update the realChoices internally", function() {
    var choices = new Choices([ "a" ]);
    choices.push( "b", new inquirer.Separator() );
    expect( choices.length ).to.equal( 3 );
    expect( choices.realLength ).to.equal( 2 );
    expect( choices.getChoice(1) ).to.be.instanceOf( Choice );
    expect( choices.get(2) ).to.be.instanceOf( inquirer.Separator );
  });

});


text:
/*jshint node:true */

"use strict";

var gulp = require('gulp');
var jshint = require('gulp-jshint');
var ignore = require('gulp-ignore');
var verbose = require('./lib/gulp-verbose');
var es = require('event-stream');
//var fs = require('fs');
//var path = require('path');
//var Mocha = require('mocha');
var gulpMocha = require('./lib/gulp-mocha');
var childProcess = require('child_process');

var opts;

var setOpts = function (o) {
	opts = o;
};

var runJSHint = function (cb) {
	// TODO: junit log at log/jshint.xml
	var jshintSuccess = true; // nothing disputed it yet
	var mess = opts.verbose ? 'linting $file' : '';
	var stream = gulp.src('./**/*.js')
		.pipe(ignore({pattern:['./node_modules/**','./dist/**']}))
		.pipe(verbose(mess))
		.pipe(jshint(opts.jshint))
		.pipe(jshint.reporterSimple())
		.pipe(es.map(function (file, cb) {
			if (!file.jshint.success) {
				jshintSuccess = false;
			}
			cb(null, file);
		}));
	stream.once('end', function () {
		if (!jshintSuccess) {
			return cb('JSHint failed on one or more files');
		}
		cb();
	});
};

var runMocha = function (cb) {
	gulp.src('./test/**/*.js')
		.pipe(gulpMocha(opts.mocha, cb));
};
// TODO: how to harvest code coverage? !!!!!

var runNpmTest = function (cb) {
	var npm = (process.platform === "win32" ? "npm.cmd" : "npm");
	var s = childProcess.spawn(npm, ['test'], {stdio: 'inherit'});
	s.on('close', function (err) {
		if (err) {
			return cb('npm test errored with exit code '+err);
		}
		cb(null);
	});
};

module.exports = {
	runJSHint: runJSHint,
	runMocha: runMocha,
	runNpmTest: runNpmTest,
	setOpts: setOpts
};


text:
module Stripe2QB
  module Converters
    class ChargeToSalesReceipt < Base
      attr_reader :charge
      attr_reader :sales_receipt

      def initialize(charge, configuration)
        super(configuration)

        @charge = charge
        @sales_receipt = build_sales_receipt
      end

      def find
        @found ||= quickbooks_api.sales_receipt_service.find_by(:payment_ref_num, charge.id).first
      end

      def create!
        raise "SalesReceipt for #{charge.id} already exists: #{find.id}" if exists?

        quickbooks_api.sales_receipt_service.create(sales_receipt)
      end

      def delete!
        return false unless exists?

        result = quickbooks_api.sales_receipt_service.delete(find)
        @found = nil

        result
      end

      private

      def build_sales_receipt
        sales_receipt = Quickbooks::Model::SalesReceipt.new
        sales_receipt.customer_id = quickbooks_api.receipt_customer.id
        sales_receipt.payment_method_id = quickbooks_api.receipt_payment_method.id
        sales_receipt.deposit_to_account_id = quickbooks_api.receipt_account.id
        sales_receipt.txn_date = format_date(charge.created)
        sales_receipt.payment_ref_number = charge.id
        sales_receipt.private_note = "Imported by Stripe2QB: #{charge.id}"
        sales_receipt.auto_doc_number!

        line_item = Quickbooks::Model::Line.new
        line_item.amount = amount = format_amount(charge.amount)
        line_item.description = charge.description
        line_item.sales_item! do |detail|
          detail.quantity = 1
          detail.unit_price = amount
          detail.item_id = quickbooks_api.receipt_item.id
        end
        sales_receipt.line_items << line_item

        sales_receipt
      end
    end
  end
end


text:
<html>
<head>
<script src="../hotsausage/HotSausage.js"></script>
<script src="../hotsausage/Privacy.js"></script>
<script src="PrivacyExample1.js"></script>
</head>
<body>
</body>
</html>


text:
# BlueRand
Java True Random Number Generator (TRNG) that uses JPEG images as entropy source.

## How it works
* It uses two different input images (with the same resolution). These images are considered independent because captured in two different moments.
* It uses the [Mixing technique](https://tools.ietf.org/html/rfc4086#section-5), so the output will be unpredictable if at least one  of two images is unpredictable.
* Only some of the total amount of pixels are considered. The CSPRNG [SecureRandom](https://docs.oracle.com/javase/7/docs/api/java/security/SecureRandom.html) sets for each considered pixel how many consecutive pixels have to be discarded. In this manner the correlation between consecutive pixels is avoided. This also guarantees that if the generator is run twice two different outputs will be generated.
* Only the BLUE channel is considered. So the correlation between different channels is avoided.
* The noise that can be found inside an image is located in the least significant bits ([LSB](https://en.wikipedia.org/wiki/Least_significant_bit)). For this reason only the LSB of each input byte is used. You can choose to consider the second least significant bit too.

## Sample
Simplest use:
```java
BlueRand random = new BlueRand("sample/input/a.jpg", "sample/input/b.jpg");
try {
	ArrayList<Byte> output = random.generateRandom();
} catch (BlueRandException e) {
	e.printStackTrace();
}
```
Please check [here](sample/Sample.java) for more samples.

## Customization options
```java
BlueRand random = new BlueRand();
random.setInputImages("sample/input/a.jpg", "sample/input/b.jpg");
random.considerTwoLSB(true);
random.setOutputFile("sample/output/ab.txt");
random.setOutputImage("sample/output/ab.bmp");
random.overwriteOutputFile(true);
random.deleteInputFiles(true);
```

## Tests
An [ENT](http://www.fourmilab.ch/random/) test result:

![test-ent](test_results/ent_test.PNG)

The output random bytes as image:

![noise](sample/output/multiRuns_output.bmp)

A [RaBiGeTe MT](http://cristianopi.altervista.org/RaBiGeTe_MT/) test result:

![test-rabigete](test_results/rabigete_test.PNG)

Occurrences:

![test-occurrences](test_results/occurrences_test.PNG)

X-axis: output bytes, defined as numbers between 0 and 255.

Y-axis: number of output bytes occurrences.

## License
	Copyright 2016 Riccardo Leschiutta

	Licensed under the Apache License, Version 2.0 (the "License");
	you may not use this file except in compliance with the License.
	You may obtain a copy of the License at

		http://www.apache.org/licenses/LICENSE-2.0

	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.