text:
Mustachio is a pull streaming implementation of [the Mustache templating
language][mustache]. It is fully compliant with [version 1.1][v1.1.3] of [the
Mustache spec][spec].

[mustache]: https://mustache.github.io/mustache.5.html
[v1.1.3]: https://github.com/mustache/spec/tree/v1.1.3
[spec]: https://github.com/mustache/spec

[![Build Status](https://travis-ci.org/maghoff/mustachio.svg?branch=master)](https://travis-ci.org/maghoff/mustachio)

Getting started
===============

    const mustachio = require('mustachio');

    const mu = mustachio.resolver();

    mu("demo", { name: "World" }).stream().pipe(process.stdout);

And then, in a directory `templates`, create the file `demo.mustache`:

    Hello, {{name}}!

Running this program outputs:

    Hello, World!

If you want to use this together with [Express][express], see [mustachio-middleware][middleware].

[express]: http://expressjs.com/
[middleware]: https://www.npmjs.com/package/mustachio-middleware

Why Mustachio?
==============
Mustachio is streaming, whereas other templating engines usually are blocking.
Traditionally, when serving a web request, the control flow is a sequence of
three discrete steps:

 1. Input: Collect all the requisite data from the database, filesystem and any
    other sources
 2. Rendering: Pass the data (sometimes called "view") and (compiled) template
    to the templating engine to render the full response
 3. Output: Send the rendered response to the client

In this model, no output can happen before the rendering is finished, and no
rendering or output can happen before all the data has been collected. This is
often good enough! However, a streaming model offers greater flexibility, can
give better performance and it can be a better fit in an otherwise asynchronous
environment such as node.js.

In Mustachio these three steps happen interleaved, in a streaming fashion.
This means rendering can proceed as soon as the relevant data becomes
available. Consequently, Mustachio will be able to respond immediately to many
requests instead of waiting until the last bit of data trickles in. It also
means flow control works, so rendering and gathering of input data can be
suspended when the client can not keep up. This frees up resources for handling
other requests.

The [examples][examples] directory contains examples that highlight different
qualities of the streaming model:

 * [large-response][large-response] demonstrates flow control
 * [file-browser][file-browser] demonstrates rendering with data that
   asynchronously becomes available
 * [postgres-query-stream][postgres-query-stream] demonstrates rendering with
   data from a PostgreSQL database, stream reading from the database
 * [react][react] shows how to explicitly flush the render buffer before
   blocking for a large or slow operation

[examples]: https://github.com/maghoff/mustachio/tree/master/examples
[large-response]: https://github.com/maghoff/mustachio/tree/master/examples/large-response
[file-browser]: https://github.com/maghoff/mustachio/tree/master/examples/file-browser
[postgres-query-stream]: https://github.com/maghoff/mustachio/tree/master/examples/postgres-query-stream
[react]: https://github.com/maghoff/mustachio/tree/master/examples/react

API
===
    const mustachio = require('mustachio');

Using a template string
-----------------------
    const template = mustachio.string("Hello, {{name}}\n");
    const rendering = template.render({ name: "World" });

Stream render:

    rendering.stream().pipe(process.stdout);

Render to string:

    rendering.string().then(result => console.log(result));

Using templates from the file system
------------------------------------
    const resolver = mustachio.resolver();

    const rendering = resolver("template-name", { name: "World" });

This `rendering` object has `stream()` and `string()` methods just like the
`rendering` object above that we got from the template string.

The resolver uses the template ID you give in to locate a file in the file
system, under the directory `templates` in your project directory. It looks for
files with file extensions  `.mustache`, `.mu`, `.mu.html` and `.html` in that
order. The same mechanism is used to resolve partial includes.

When using the resolver, the compiled template is cached in memory and reused
when rendering the same template again. Additionally, a file system watcher is
set up to invalidate the cache whenever the template file is edited.

Customizing partials resolving
------------------------------
You can customize the base directory for templates and the file name suffixes
used for resolving partials by passing a configuration object to the resolver:

    const resolver = mustachio.resolver({
      root: path.join(__dirname, "my-templates"),
      suffixes: [ ".my.oh.my" ]
    });

To get other behaviour and even resolve partials from other sources than the
file system (such as the database, or HTTP calls), pass a custom partials
resolver object:

    const resolver = mustachio.resolver({
      partialsResolver: new CustomPartialsResolver()
    });

See [partials][partials] for details.

[partials]: https://github.com/maghoff/mustachio/tree/master/lib/partials

When using a template string, partials will by default not be resolved. To
enable partials resolving for such templates, pass a partials resolver to the
`render` function:

    template.render(data, partialsResolver);

Explicitly flushing the render buffer
-------------------------------------
As a special concern, it is possible to explicitly flush the render buffer
during rendering. Mustachio offers two ways of doing this:

 * by using the `{{_flush}}` tag in the template. Note that if your `data`
   object includes data named `_flush` it overrides the flush function
 * call `stream.flush()` in the code. It returns a `Promise`, and when this
   resolves, the render buffer has been flushed

See [the React example][react] for more about both methods.

The `data` object
-----------------
These are the types of values you can put in the `data` object: [Fundamental
types](#fundamental-types), [objects](#objects), [arrays](#arrays),
[functions](#functions), [generator functions](#generator-functions),
[promises](#promises), [text streams](#text-streams) and [object mode
streams](#object-mode-streams).

The power of Mustachio comes from combining these building blocks. It works
perfectly well to specify a function that returns a promise which resolves to
a generator that yields functions which ... etc, etc. See the
[file-browser][file-browser] example for an effective use of this.

### Fundamental types ###
    {
      "number": 5.25,
      "desc": "is a number.",
      "true-bool": true
    }

`{{number}} {{desc}} {{#true-bool}}Yes!{{/true-bool}} {{true-bool}}` ⇒ `5.25
is a number. Yes! true`

### Objects ###
    {
      "a": {
        "b": 5,
        "c": {
          "d": 6
        }
      }
    }

`{{#a}}{{b}}, {{c.d}}{{/a}}` ⇒ `5, 6`

### Arrays ###
    { "a": [1, 2, 3] }

`{{#a}}({{.}}){{/a}}` ⇒ `(1)(2)(3)`.

### Functions ###
    {
      "a": () => 5
    }

`{{a}}` ⇒ `5`

Functions get called with the containing object as the `this` argument:

    {
      "a": 5,
      "b": function () { return this.a * 2; }
    }

`{{b}}` ⇒ `10`

### Generator functions ###
Generator functions will be treated as arrays:

    {
      "a": function* () {
        yield 0;
        yield "is smaller than";
        yield 1;
      }
    }

`{{#a}}({{.}}){{/a}}` ⇒ `(0)(is smaller than)(1)`

### Promises ###
    {
      "a": new Promise((resolve, reject) => {
        // Any asynchronous operation
        require('fs').stat(__dirname, (stat, err) => {
          if (err) reject(err);
          else resolve(stat);
        });
      })
    }

`{{#a.isDirectory}}A directory!{{/a.isDirectory}}` ⇒ `A directory!`

The [file-browser example][file-browser] demonstrates use of promises as data.

### Text streams ###
A text stream can be interpolated, like a string:

    {
      "cmdline": require('fs').createReadStream('/proc/self/cmdline', 'utf8')
    }

`You ran: {{cmdline}}` ⇒ `You ran: node`

Note that streams must have an encoding set, so they output text rather than
binary data.

### Object mode streams ###
An [object mode stream][objmode] can be iterated over, like an array:

    {
      "objects": () => {
        const objects = [ 1, 2, 3 ];
        return new (require('stream')).Readable({
          objectMode: true,
          read() {
            this.push(objects.length ? objects.shift() : null);
          }
        });
      }
    }

`{{#objects}}({{.}}){{/objects}}` ⇒ `(1)(2)(3)`

[objmode]: https://nodejs.org/api/stream.html#stream_object_mode

The [postgres-query-stream example][postgres-query-stream] demonstrates use of
object mode streams.


text:
<!DOCTYPE html>

    <title>Bitcoin Wallet Extension</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" charset="UTF-8">
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/paypopup.css" rel="stylesheet">

             Success

            Not a valid address.

            <input type="text" class="form-control input-sm" id="address" autocomplete="off" placeholder="To Address">

            <input type="number" min="0" step="0.001" class="form-control input-sm" id="amount" autocomplete="off" placeholder="Amount (BTC)">

            <input type="password" class="form-control input-sm" id="password" autocomplete="off" placeholder="Password">

        <button id="button" type="button" class="btn btn-primary btn-sm">Send</button>

redpajama_set_name: RedPajamaGithub


text:
// Template Source: BaseEntity.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All Rights Reserved.  Licensed under the MIT License.  See License in the project root for license information.
// ------------------------------------------------------------------------------

package com.microsoft.graph.models;
import com.microsoft.graph.serializer.ISerializer;
import com.microsoft.graph.serializer.IJsonBackedObject;
import com.microsoft.graph.serializer.AdditionalDataManager;
import java.util.EnumSet;
import com.microsoft.graph.models.IdentitySet;

import com.google.gson.JsonObject;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;

// **NOTE** This file was generated by a tool and any changes will be overwritten.

/**
 * The class for the Planner Assignment.
 */
public class PlannerAssignment implements IJsonBackedObject {

    /** the OData type of the object as returned by the service */
    @SerializedName("@odata.type")
    @Expose
    @Nullable
    public String oDataType;

    private transient AdditionalDataManager additionalDataManager = new AdditionalDataManager(this);

    @Override
    @Nonnull
    public final AdditionalDataManager additionalDataManager() {
        return additionalDataManager;
    }

    /**
     * The Assigned By.
     * The identity of the user that performed the assignment of the task, i.e. the assignor.
     */
    @SerializedName(value = "assignedBy", alternate = {"AssignedBy"})
    @Expose
	@Nullable
    public IdentitySet assignedBy;

    /**
     * The Assigned Date Time.
     * The time at which the task was assigned. The Timestamp type represents date and time information using ISO 8601 format and is always in UTC time. For example, midnight UTC on Jan 1, 2014 is 2014-01-01T00:00:00Z
     */
    @SerializedName(value = "assignedDateTime", alternate = {"AssignedDateTime"})
    @Expose
	@Nullable
    public java.time.OffsetDateTime assignedDateTime;

    /**
     * The Order Hint.
     * Hint used to order assignees in a task. The format is defined as outlined here.
     */
    @SerializedName(value = "orderHint", alternate = {"OrderHint"})
    @Expose
	@Nullable
    public String orderHint;

    /**
     * Sets the raw JSON object
     *
     * @param serializer the serializer
     * @param json the JSON object to set this object to
     */
    public void setRawObject(@Nonnull final ISerializer serializer, @Nonnull final JsonObject json) {

    }
}


text:
package com.fasterxml.aalto.util;

import java.lang.reflect.Array;

public final class DataUtil
{
    final static char[] EMPTY_CHAR_ARRAY = new char[0];

    private DataUtil() { }

    public static char[] getEmptyCharArray() {
        return EMPTY_CHAR_ARRAY;
    }

    /*
    ////////////////////////////////////////////////////////////
    // Methods for common operations on std data structs
    ////////////////////////////////////////////////////////////
    */

    public static String[] growArrayBy(String[] arr, int more)
    {
        if (arr == null) {
            return new String[more];
        }
        String[] old = arr;
        int len = arr.length;
        arr = new String[len + more];
        System.arraycopy(old, 0, arr, 0, len);
        return arr;
    }

    public static int[] growArrayBy(int[] arr, int more)
    {
        if (arr == null) {
            return new int[more];
        }
        int[] old = arr;
        int len = arr.length;
        arr = new int[len + more];
        System.arraycopy(old, 0, arr, 0, len);
        return arr;
    }

    public static char[] growArrayBy(char[] arr, int more)
    {
        if (arr == null) {
            return new char[more];
        }
        char[] old = arr;
        int len = arr.length;
        arr = new char[len + more];
        System.arraycopy(old, 0, arr, 0, len);
        return arr;
    }

    public static Object growAnyArrayBy(Object arr, int more)
    {
        if (arr == null) {
            throw new IllegalArgumentException("Null array");
        }
        Object old = arr;
        int len = Array.getLength(arr);
        arr = Array.newInstance(arr.getClass().getComponentType(), len + more);
        System.arraycopy(old, 0, arr, 0, len);
        return arr;
    }
}


text:
#ifndef PSE_TYPES_H_
#define PSE_TYPES_H_

#include <stdlib.h>
#include <stdint.h>
#include <assert.h>
#include <string.h>
#include <stdio.h>
#include <limits.h>
#include <iostream>
#include <sstream>
#include <algorithm>

static unsigned cur_threads_used = 1;

#ifdef _OPENMP
#include <omp.h>
#endif

class J2cParRegionThreadCount {
protected:
    unsigned num_threads_used;
    unsigned m_line;
    const char *   m_file;
    unsigned m_host_min_par;
    unsigned m_phi_min_par;
public:
    J2cParRegionThreadCount(unsigned iteration_count, unsigned line, const char *file, unsigned host_min = 0, unsigned phi_min = 0) :
        m_line(line),
        m_file(file),
        m_host_min_par(host_min),
        m_phi_min_par(phi_min) {
#ifdef _OPENMP
        unsigned max = omp_get_max_threads(); // the max number of threads for this device
#else
        unsigned max = 1;
#endif

        // Don't oversubscribe too much
        if (cur_threads_used >= max) {
#ifdef DEBUGJ2C
            printf("%s %d %d %d enter max =%d thread %d\n", file, line, map, _Offload_get_device_number(), max, cur_threads_used);
#endif
            num_threads_used = 1;
        } else {
            // how many unused threads are there
            unsigned num_left = max - cur_threads_used;
            // assuming all threads are doing the same thing, take the num free and divide by how many cohorts there are to get our fair share of the rest
            unsigned our_share = (num_left / cur_threads_used) + 1;
            // never allocate more thread to this loop than the size of the loop
            num_threads_used = std::min(our_share, iteration_count);
#if 0
            if (num_threads_used < 2) {
                num_threads_used = 2;
            }
#endif
#ifdef DEBUGJ2C
            printf("%s %d %d %d enter ic = %d max = %d num_left = %d our_share = %d ntu = %d\n", file, line, max, _Offload_get_device_number(), iteration_count, max, num_left, our_share, num_threads_used);
#endif
        }

        if(num_threads_used > 1 && runInPar()) {
            // update the global
            unsigned prev = __sync_fetch_and_add(&cur_threads_used, num_threads_used);
#ifdef DEBUGJ2C
            printf("%s %d %d %d enter prev = %d new = %d\n", file, line, max, _Offload_get_device_number(), prev, prev + num_threads_used);
#endif
        }
    }

    ~J2cParRegionThreadCount(void) {
        if(num_threads_used > 1 && runInPar()) {
            unsigned prev = __sync_fetch_and_sub(&cur_threads_used, num_threads_used);
#ifdef DEBUGJ2C
            printf("%s %d %d %d exit prev = %d new = %d\n", m_file, m_line, max, _Offload_get_device_number(), prev, prev - num_threads_used);
#endif
        } else {
#ifdef DEBUGJ2C
          //  printf("%s %d %d %d exit\n", m_file, m_line, omp_get_thread_num(), _Offload_get_device_number());
#endif
        }
    }

    unsigned getUsed(void) const {
        return num_threads_used;
    }

    bool runInPar(void) const {
#ifdef __MIC__
        return num_threads_used >= m_phi_min_par;
#else
        return num_threads_used >= m_host_min_par;
#endif
    }
};

unsigned computeNumThreads(uint64_t instruction_count_estimate) {
#ifdef __MIC__
    unsigned est = instruction_count_estimate / 5500000;
#else
    unsigned est = instruction_count_estimate / 21000000;
#endif
#ifdef _OPENMP
    int max = omp_get_max_threads();
#else
    int max = 1;
#endif
    unsigned ret = est > max ? max : est == 0 ? 1 : est;
//    printf("computeNumThreads: %lld => %d\n", instruction_count_estimate, ret);
    return ret;
}

#define ALLOC alloc_if(1) free_if(0)
#define FREE  alloc_if(0) free_if(1)
#define REUSE alloc_if(0) free_if(0)

#include <sys/time.h>

#ifdef TARGET_ATTRIBUTE
TARGET_ATTRIBUTE
#endif
static double timestamp ()
{
	struct timeval tv;
	gettimeofday (&tv, 0);
	return tv.tv_sec + 1e-6*tv.tv_usec;
}

#define julia_Base__assert(x) assert(x)
#define julia_Base__StepRange(x,y,z) StepRange{x,y,z}

int64_t checked_sadd(int64_t a, int64_t b) {
    if (a > 0 && b > LLONG_MAX - a) {
        /* handle overflow */
        assert(0);
    } else if (a < 0 && b < LLONG_MIN - a) {
        /* handle underflow */
        assert(0);
    }
    return a + b;
}

#define checked_ssub(a, b) checked_sadd(a,-b)

#endif /* PSE_TYPES_H_ */


text:
<!DOCTYPE html>

		<title>BUILDING CAM - OUTWARD FACING</title>

BUILDING CAM - OUTWARD FACING

			 ** MCA-73E9... **

						Back

						Next


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Cbn.Lib.Data.Entity
{
    public interface IDbEntity: IEntity
    {
        int? UpdatedBy { get; set; }
        DateTime? UpdatedAt { get; set; }
        int? CreatedBy { get; set; }
        DateTime? CreatedAt { get; set; }
    }
}


text:
import React from 'react';
import { Hermes } from 'syntec-apollo-11';

/**
  * Função que adiciona uma mensagem.
 */
var adicionarMensagem = () => {
  Hermes.addMessage(`Mensagem ${Date.now()}`, true);
};

/**
  * Função que muda o contexto da mensagem.
 */
var mudarContexto = (context) => {
  Hermes.setContext(context);
};

class ExemploContextosEPosicao extends React.Component {

	render() {
		return (
			<div>
				<Hermes />
				<button	className='sv-button small default marged' onClick={() => {adicionarMensagem(); mudarContexto('success')}}>
                  Contexto Sucesso
                </button>
        		<button className='sv-button small default marged' onClick={() => {adicionarMensagem(); mudarContexto('info')}}>
                  Contexto Informativo
                </button>
        		<button className='sv-button small default marged' onClick={() => {adicionarMensagem(); mudarContexto('warning')}}>
                  Contexto Aviso
                </button>
        		<button className='sv-button small default marged' onClick={() => {adicionarMensagem(); mudarContexto('error')}}>
                  Contexto Erro
                </button>
        		<button className='sv-button small default marged' onClick={() => Hermes.setPosition('top')}>
                  Superior
                </button>
        		<button className='sv-button small default marged' onClick={() => Hermes.setPosition('bottom')}>
                  Inferior
                </button>
			</div>
		);
	}

}

ExemploContextosEPosicao.displayName = 'ExemploContextosEPosicao';
export default ExemploContextosEPosicao;


text:
package sarah

import (
	"context"
	"github.com/patrickmn/go-cache"
	"testing"
	"time"
)

type DummyUserContextStorage struct {
	GetFunc    func(string) (ContextualFunc, error)
	SetFunc    func(string, *UserContext) error
	DeleteFunc func(string) error
	FlushFunc  func() error
}

func (storage *DummyUserContextStorage) Get(key string) (ContextualFunc, error) {
	return storage.GetFunc(key)
}

func (storage *DummyUserContextStorage) Set(key string, userContext *UserContext) error {
	return storage.SetFunc(key, userContext)
}

func (storage *DummyUserContextStorage) Delete(key string) error {
	return storage.DeleteFunc(key)
}

func (storage *DummyUserContextStorage) Flush() error {
	return storage.FlushFunc()
}

func TestNewUserContextStorage(t *testing.T) {
	storage := NewUserContextStorage(NewCacheConfig())
	if storage == nil {
		t.Fatal("Storage is not initialized.")
	}
}

func TestDefaultUserContextStorage_Set_WithEmptyNext(t *testing.T) {
	storage := &defaultUserContextStorage{
		cache: cache.New(3*time.Minute, 10*time.Minute),
	}

	err := storage.Set("key", &UserContext{})

	if err == nil {
		t.Error("Expected error is not returned.")
	}
}

func TestDefaultUserContextStorage_CRUD(t *testing.T) {
	storage := &defaultUserContextStorage{
		cache: cache.New(3*time.Minute, 10*time.Minute),
	}

	key := "myKey"
	if empty, _ := storage.Get(key); empty != nil {
		t.Fatalf("nil should return on empty storage. %T.", empty)
	}

	_ = storage.Set(key, NewUserContext(func(ctx context.Context, input Input) (*CommandResponse, error) { return nil, nil }))
	if val, _ := storage.Get(key); val == nil {
		t.Fatal("Expected value is not stored.")
	}

	_ = storage.Delete(key)
	if empty, _ := storage.Get(key); empty != nil {
		t.Fatalf("nil should return after deletion. %#v.", empty)
	}

	_ = storage.Set(key, NewUserContext(func(ctx context.Context, input Input) (*CommandResponse, error) { return nil, nil }))
	_ = storage.Flush()
	if storage.cache.ItemCount() > 0 {
		t.Fatal("Some value is stored after flush.")
	}

	invalidKey := "invalidStoredType"
	storage.cache.Set(invalidKey, &struct{}{}, 10*time.Second)
	invalidVal, getErr := storage.Get(invalidKey)
	if getErr == nil {
		t.Error("Error must be returned for invalid stored value.")
	}
	if invalidVal != nil {
		t.Errorf("Invalid stored value shouldn't be returned: %T", invalidVal)
	}
}


text:
package org.spongepowered.api.item.inventory.type;

import org.spongepowered.api.block.entity.BlockEntity;
import org.spongepowered.api.item.inventory.Carrier;
import org.spongepowered.api.item.inventory.Inventory;

import java.util.Optional;

/**
 * An {@link Inventory} which is owned by a
 * {@link BlockEntity}. In Sponge, a BE is never seen as an Inventory itself and
 * Block Entities are instead considered to "own" their own Inventory (much like
 * equipable entities do). Underlying implementations are of course completely
 * at liberty to return the BE object directly but as far as consumers are
 * concerned the BE instance and the inventory are separate things.
 *
 *
This is intended to provide a consistent way of dealing with inventories
 * regardless of the "owner" of the inventory. Thus, any code capable of dealing
 * with a {@link Carrier} is intrinsically able to deal with a BE inventory just
 * as they would with any Entity inventory or any other type of Carrier for that
 * matter.

 *
 *
This separation of inventory logic from the BE itself also serves to
 * provide some flexibility for implementors, since it is possible that not all
 * implementations may take the view that a BE embodies its own inventory.

 *
 * @param <T> Block entity type, the specified BE must be a {@link Carrier}
 */
public interface BlockEntityInventory<T extends BlockEntity & Carrier>
        extends PersistentInventory, ViewableInventory, CarriedInventory<T> {

    /**
     * Returns the owner of this Inventory.
     *
     * @return This inventory's carrier
     */
    Optional<T> blockEntity();

}


text:
<?php
namespace Google\Service\Analytics;

class WebpropertyPermissions extends \Google\Collection
{
  public $effective;

  public function setEffective($effective)
  {
    $this->effective = $effective;
  }

  public function getEffective()
  {
    return $this->effective;
  }

}


text:
package org.apache.jackrabbit.webdav.observation;

import org.apache.jackrabbit.webdav.DavException;
import org.apache.jackrabbit.webdav.DavServletResponse;
import org.apache.jackrabbit.webdav.header.TimeoutHeader;
import org.apache.jackrabbit.webdav.header.DepthHeader;
import org.apache.jackrabbit.webdav.xml.DomUtil;
import org.apache.jackrabbit.webdav.xml.ElementIterator;
import org.apache.jackrabbit.webdav.xml.Namespace;
import org.apache.jackrabbit.webdav.xml.XmlSerializable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import java.util.ArrayList;
import java.util.List;

/**
 * SubscriptionInfo class encapsulates the subscription info
 * that forms the request body of a SUBSCRIBE request.

 * The following xml layout is defined for the subscription info:
 *

 * <!ELEMENT subscriptioninfo ( eventtype, nolocal?, filter? ) >
 * <!ELEMENT eventtype ANY >
 *
 * ANY defines any sequence of elements where at least one defines a valid
 * eventtype. Note that a single eventtype must not occur multiple times.

 * <!ELEMENT nolocal EMPTY >
 * <!ELEMENT filter ANY >
 *
 * ANY: any sequence of elements identifying a filter for event listening but
 * at least a single element.
 *

 * @see ObservationConstants#XML_SUBSCRIPTIONINFO
 */
public class SubscriptionInfo implements ObservationConstants, XmlSerializable {

    private static Logger log = LoggerFactory.getLogger(SubscriptionInfo.class);

    private final EventType[] eventTypes;
    private final Filter[] filters;
    private final boolean noLocal;
    private final boolean isDeep;
    private final long timeout;

    /**
     * Create a new SubscriptionInfo
     *
     * @param eventTypes
     * @param isDeep
     * @param timeout
     */
    public SubscriptionInfo(EventType[] eventTypes, boolean isDeep, long timeout) {
        this(eventTypes, null, false, isDeep, timeout);
    }

    /**
     * Create a new SubscriptionInfo
     *
     * @param eventTypes
     * @param filters
     * @param noLocal
     * @param isDeep
     * @param timeout
     */
    public SubscriptionInfo(EventType[] eventTypes, Filter[] filters, boolean noLocal, boolean isDeep, long timeout) {
        if (eventTypes == null || eventTypes.length == 0) {
            throw new IllegalArgumentException("'subscriptioninfo' must at least indicate a single event type.");
        }

        this.eventTypes = eventTypes;
        this.noLocal = noLocal;

        if (filters != null) {
            this.filters = filters;
        } else {
            this.filters = new Filter[0];
        }

        this.isDeep = isDeep;
        this.timeout = timeout;
    }

    /**
     * Create a new SubscriptionInfo from the given Xml element
     * and from additional information that is transported within the request
     * header:
     *

     *
{@link TimeoutHeader timeout},

     *
{@link DepthHeader isDeep}

     *

     * @param reqInfo Xml element present in the request body.
     * @param timeout as defined in the {@link org.apache.jackrabbit.webdav.DavConstants#HEADER_TIMEOUT timeout header}.
     * @param isDeep as defined in the {@link org.apache.jackrabbit.webdav.DavConstants#HEADER_DEPTH depth header}.
     * @throws IllegalArgumentException if the reqInfo element does not contain the mandatory elements.
     */
    public SubscriptionInfo(Element reqInfo, long timeout, boolean isDeep) throws DavException {
        if (!DomUtil.matches(reqInfo, XML_SUBSCRIPTIONINFO, NAMESPACE)) {
            log.warn("Element with name 'subscriptioninfo' expected");
            throw new DavException(DavServletResponse.SC_BAD_REQUEST);
        }
        Element el = DomUtil.getChildElement(reqInfo, XML_EVENTTYPE, NAMESPACE);
        if (el != null) {
            eventTypes = DefaultEventType.createFromXml(el);
            if (eventTypes.length == 0) {
                log.warn("'subscriptioninfo' must at least indicate a single, valid event type.");
                throw new DavException(DavServletResponse.SC_BAD_REQUEST);
            }
        } else {
            log.warn("'subscriptioninfo' must contain an 'eventtype' child element.");
            throw new DavException(DavServletResponse.SC_BAD_REQUEST);
        }

        List<Filter> filters = new ArrayList<Filter>();
        el = DomUtil.getChildElement(reqInfo, XML_FILTER, NAMESPACE);
        if (el != null) {
            ElementIterator it = DomUtil.getChildren(el);
            while (it.hasNext()) {
                Filter f = new Filter(it.nextElement());
                filters.add(f);
            }
        }
        this.filters = filters.toArray(new Filter[filters.size()]);

        this.noLocal = DomUtil.hasChildElement(reqInfo, XML_NOLOCAL, NAMESPACE);
        this.isDeep = isDeep;
        this.timeout = timeout;
    }

    /**
     * Return array of event type names present in the subscription info.
     *
     * @return array of String defining the names of the events this subscription
     * should listen to.
     *
     */
    public EventType[] getEventTypes() {
        return eventTypes;
    }

    /**
     * Return all filters defined for this SubscriptionInfo
     *
     * @return all filters or an empty Filter array.
     */
    public Filter[] getFilters() {
        return filters;
    }

    /**
     * Return array of filters with the specified name.
     *
     * @param localName the filter elements must provide.
     * @param namespace
     * @return array containing the text of the filter elements with the given
     * name.
     */
    public Filter[] getFilters(String localName, Namespace namespace) {
        List<Filter> l = new ArrayList<Filter>();
        for (Filter filter : filters) {
            if (filter.isMatchingFilter(localName, namespace)) {
                l.add(filter);
            }
        }
        return l.toArray(new Filter[l.size()]);
    }

    /**
     * Returns true if the {@link #XML_NOLOCAL} element is present in this
     * subscription info.
     *
     * @return if {@link #XML_NOLOCAL} element is present.
     */
    public boolean isNoLocal() {
        return noLocal;
    }

    /**
     * Returns true if the {@link org.apache.jackrabbit.webdav.DavConstants#HEADER_DEPTH
     * depths header} defined a depth other than '0'.
     *
     * @return true if this subscription info was created with isDeep
     * true.
     */
    public boolean isDeep() {
        return isDeep;
    }

    /**
     * Return the timeout as retrieved from the request.
     *
     * @return timeout.
     */
    public long getTimeOut() {
        return timeout;
    }

    /**
     * Xml representation of this SubscriptionInfo.
     *
     * @return Xml representation
     * @see org.apache.jackrabbit.webdav.xml.XmlSerializable#toXml(Document)
     * @param document
     */
    public Element toXml(Document document) {
        Element subscrInfo = DomUtil.createElement(document, XML_SUBSCRIPTIONINFO, NAMESPACE);
        Element eventType = DomUtil.addChildElement(subscrInfo, XML_EVENTTYPE, NAMESPACE);
        for (EventType et : eventTypes) {
            eventType.appendChild(et.toXml(document));
        }

        if (filters.length > 0) {
            Element filter = DomUtil.addChildElement(subscrInfo, XML_FILTER, NAMESPACE);
            for (Filter f : filters) {
                filter.appendChild(f.toXml(document));
            }
        }

        if (noLocal) {
            DomUtil.addChildElement(subscrInfo, XML_NOLOCAL, NAMESPACE);
        }
        return subscrInfo;
    }
}


text:
using namespace gl; // ToDo: multiple APIs?

namespace glbinding
{

Function<void, GLenum, GLuint, GLsizei, const GLchar *> Binding::ObjectLabel("glObjectLabel");
Function<void, const void *, GLsizei, const GLchar *> Binding::ObjectPtrLabel("glObjectPtrLabel");
Function<GLenum, GLenum, GLuint, GLenum> Binding::ObjectPurgeableAPPLE("glObjectPurgeableAPPLE");
Function<GLenum, GLenum, GLuint, GLenum> Binding::ObjectUnpurgeableAPPLE("glObjectUnpurgeableAPPLE");
Function<void, GLdouble, GLdouble, GLdouble, GLdouble, GLdouble, GLdouble> Binding::Ortho("glOrtho");
Function<void, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat> Binding::OrthofOES("glOrthofOES");
Function<void, GLfixed, GLfixed, GLfixed, GLfixed, GLfixed, GLfixed> Binding::OrthoxOES("glOrthoxOES");

} // namespace glbinding


text:
package com.kkbnart.wordis.game.animation;

import java.util.HashSet;
import java.util.Set;

import android.graphics.Canvas;

import com.kkbnart.wordis.game.GameAction;
import com.kkbnart.wordis.game.board.Board;

/**
 * Execute assigned animations.

 *
 * @author kkbnart
 */
public class AnimationExecutor {
	// Current animations to execute
	private Set<GameAnimation> animations = new HashSet<GameAnimation>();

	/**
	 * Assign new animation to {@link AnimationExecutor#animations}.

	 *
	 * @param animation New animation
	 */
	public void assignAnimation(GameAnimation animation) {
		this.animations.add(animation);
	}

	/**
	 * Execute preserved animations.

	 * Remove animations time of which is over.

	 *
	 * @param canvas	Surface view canvas
	 * @param board		Current board
	 * @return action	Game action to be taken after animation
	 */
	public GameAction execute(final Canvas canvas, final Board board) {
		// Action to be taken after animation (default None)
		GameAction action = GameAction.NONE;
		Set<GameAnimation> removeAnimations = new HashSet<GameAnimation>();
		for (GameAnimation animation : animations) {
			if (!animation.executeAnimationUpdate(canvas, board)) {
				// Update action
				action = action.compare(animation.getPostAction());
				removeAnimations.add(animation);
			}
		}
		// Remove animations
		for (GameAnimation animation : removeAnimations) {
			animations.remove(animation);
		}
		return action;
	}

	public boolean hasAnimation() {
		return !animations.isEmpty();
	}
}


text:
<?php
namespace App\Model\Table;

use App\Model\Entity\Country;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;

/**
 * Countries Model
 *
 * @property \Cake\ORM\Association\HasMany $Contacts
 */
class CountriesTable extends Table
{

    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->table('countries');
        $this->displayField('name');
        $this->primaryKey('iso');

        $this->hasMany('Contacts', [
            'foreignKey' => 'country_id'
        ]);
    }

    /**
     * Default validation rules.
     *
     * @param \Cake\Validation\Validator $validator Validator instance.
     * @return \Cake\Validation\Validator
     */
    public function validationDefault(Validator $validator)
    {
        $validator
            ->allowEmpty('id', 'create')
            ->add('id', 'unique', ['rule' => 'validateUnique', 'provider' => 'table']);

        $validator
            ->requirePresence('iso_code', 'create')
            ->notEmpty('iso_code');

        $validator
            ->requirePresence('name', 'create')
            ->notEmpty('name');

        return $validator;
    }

    public static function defaultConnectionName() {
    	return 'users';
    }
}


text:
require 'spec_helper'
require 'puppet/type/chocolateyfeature'

describe Puppet::Type.type(:chocolateyfeature) do
  let(:resource) { Puppet::Type.type(:chocolateyfeature).new(:name => "chocolateyfeature", :ensure => "enabled" ) }
  let(:provider) { Puppet::Provider.new(resource) }
  let(:catalog) { Puppet::Resource::Catalog.new }
  let (:minimum_supported_version) {'0.9.9.0'}

  before :each do
    PuppetX::Chocolatey::ChocolateyCommon.stubs(:choco_version).returns(minimum_supported_version)

    resource.provider = provider
    resource[:ensure] = 'enabled'
  end

  it "should be an instance of Puppet::Type::Chocolateyfeature" do
    resource.must be_an_instance_of Puppet::Type::Chocolateyfeature
  end

  it "parameter :name should be the name var" do
    resource.parameters[:name].isnamevar?.should be_truthy
  end

  context "parameter :name" do
    let (:param_symbol) { :name }

    it "should accept any string value" do
      resource[param_symbol] = 'value'
      resource[param_symbol] = "c:/thisstring-location/value/somefile.txt"
      resource[param_symbol] = "c:\\thisstring-location\\value\\somefile.txt"
    end
  end

  context "param :ensure" do
    it "should accept 'enabled'" do
      resource[:ensure] = 'enabled'
    end

    it "should accept enabled" do
      resource[:ensure] = :enabled
    end

    it "should accept 'disabled'" do
      resource[:ensure] = 'disabled'
    end

    it "should accept :disabled" do
      resource[:ensure] = :disabled
    end

    it "should reject any other value" do
      expect {
        resource[:ensure] = :whenever
      }.to raise_error(Puppet::Error, /Invalid value :whenever. Valid values are/)
    end
  end
end


text:
package de.taimos.dvalin.interconnect.model.maven.imports.event;

import de.taimos.dvalin.interconnect.model.event.EventDomain;
import de.taimos.dvalin.interconnect.model.event.IEvent;
import de.taimos.dvalin.interconnect.model.maven.imports.Imports;
import de.taimos.dvalin.interconnect.model.maven.model.AbstractInterconnectModel;
import de.taimos.dvalin.interconnect.model.maven.model.event.AbstractEventModel;
import de.taimos.dvalin.interconnect.model.metamodel.defs.EventDef;

/**
 * @author psigloch
 */
public class EventInterfaceImports extends BaseEventImports {

    private static final long serialVersionUID = -4856513469922204335L;

    @Override
    public void initDefaults() {
        super.initDefaults();
        this.withNullable();
        this.withNonnull();
        this.withJsonTypeInfo();
        this.withJsonIgnoreProperties();
        this.add(EventDomain.class);
    }

    @Override
    public <K extends AbstractInterconnectModel<EventDef, ? extends Imports<EventDef>>> void initFromDefinition(EventDef ivoDefinition, K model) {
        super.initFromDefinition(ivoDefinition, model);
        if (model instanceof AbstractEventModel) {
            if (model.hasParentClazz()) {
                this.add(model.getParentInterfacePath());
            } else {
                this.add(IEvent.class);
            }
        }
    }
}


text:
<?php

namespace PVLog\Json\Tests;

use PVLog\Classes\Json\Instance;
use PVLog\Classes\Json\Plant;
use PVLog\Classes\Json\Inverter;
use PVLog\Classes\Json\Strings;
use PVLog\Classes\Json\Irradiation;
use PVLog\Classes\Json\Temperature;

/**
 *
 */
class InstanceTest extends \PHPUnit_Framework_TestCase {

    protected $instance;

    /**
     *
     */
    protected function setUp() {
        $this->instance = new Instance();
        $this->instance->setPrettyJson(TRUE);
    }

    /**
     *
     */
    public function testPlainInstance() {
        $this->assertInstanceOf('PVLog\Classes\Json\Instance', $this->instance);

        $c = (new \ReflectionClass($this))->getShortName();

        $file1 = __DIR__.'/files/'.$c.'.json';
        $this->assertJsonStringEqualsJsonFile($file1, $this->instance->asJson(TRUE));
        // Test __toString()
        $this->assertJsonStringEqualsJsonFile($file1, $this->instance.'');

        $file2 = __DIR__.'/files/'.$c.'.test.json';
        $this->instance->saveJsonToFile($file2);

        $this->assertJsonFileEqualsJsonFile($file1, $file2);
        unlink($file2);

        $raw = $this->instance->getRaw();
        $this->assertContains('1.1', $raw);
    }

    /**
     *
     */
    public function testFullInstance() {
        $plant = new Plant;

        for ($i=1; $i<=2; $i++) {
            // Inverter $i
            $inverter = new Inverter;

            for ($j=1; $j<=2; $j++) {
                // Inverter $i, String $j
                $inverter->addPowerAcWatts('2000-01-01 00:00:00', 900)
                         ->addPowerAcWatts('2000-01-01 00:05:00', 900);

                $string = new Strings;
                $string->addPowerAcWatts('2000-01-01 00:00:00', 1000)
                       ->addPowerAcWatts('2000-01-01 00:05:00', 1000);

                $inverter->addString($string);
            }

            $plant->addInverter($inverter);
        }

        $this->instance->setPlant($plant);

        // check that multiple interpolate() Calls don't mess up the result,
        // interpolate() is called from asJson() by default
        $this->instance->interpolate()->interpolate();

        $this->assertJsonStringEqualsJsonFile(__DIR__.'/files/FullInstance.json', $this->instance->asJson());

        $this->instance->setPrettyJson(FALSE);
        $this->assertJsonStringEqualsJsonFile(__DIR__.'/files/FullInstance.json', $this->instance->asJson());
    }

    /**
     *
     */
    public function testCreatorProperty() {
        $value = md5(rand());
        $r = $this->instance->setCreator($value);
        $this->assertInstanceOf('PVLog\Classes\Json\Instance', $r);
        $this->assertEquals($value, $this->instance->getCreator());
    }

    /**
     *
     */
    public function testDeleteDayBeforeImportProperty() {
        $value = 1;
        $r = $this->instance->setDeleteDayBeforeImport($value);
        $this->assertInstanceOf('PVLog\Classes\Json\Instance', $r);
        $this->assertEquals($value, $this->instance->getDeleteDayBeforeImport());

        $value = 0;
        $this->instance->setDeleteDayBeforeImport($value);
        $this->assertEquals($value, $this->instance->getDeleteDayBeforeImport());
    }

    /**
     *
     */
    public function testTypeSetsProperty() {
        $r = $this->instance->setTypeMinutes();
        $this->assertInstanceOf('PVLog\Classes\Json\Instance', $r);
        $this->assertEquals('minutes', $this->instance->getType());

        $r = $this->instance->setTypeDay();
        $this->assertInstanceOf('PVLog\Classes\Json\Instance', $r);
        $this->assertEquals('day', $this->instance->getType());

        $r = $this->instance->setTypeMonth();
        $this->assertInstanceOf('PVLog\Classes\Json\Instance', $r);
        $this->assertEquals('month', $this->instance->getType());
    }

    /**
     *
     */
    public function testPlantSetterGetterProperty() {
        $r = $this->instance->setPlant(new Plant);
        $this->assertInstanceOf('PVLog\Classes\Json\Plant', $r->getPlant());
    }

    /**
     *
     */
    public function testPlantMagicProperty() {
        $this->assertNull($this->instance->plant);

        $this->instance->plant = new Plant;
        $this->assertInstanceOf('PVLog\Classes\Json\Plant', $this->instance->plant);
    }

    /**
     *
     */
    public function testSetGetIrradiation() {
        $this->assertNull($this->instance->getIrradiation());
        $this->assertNull($this->instance->irradiation);

        $irradiation = new Irradiation;
        $this->assertInstanceOf('PVLog\Classes\Json\Irradiation', $irradiation);

        $this->instance->setIrradiation($irradiation);
        $this->assertInstanceOf('PVLog\Classes\Json\Irradiation', $this->instance->getIrradiation());

        $this->instance->irradiation = $irradiation;
        $this->assertInstanceOf('PVLog\Classes\Json\Irradiation', $this->instance->irradiation);
    }

    /**
     *
     */
    public function testPlantWithoutInverters() {
        $plant = new Plant;
        $plant->addTotalWattHours('2000-01-01 00:00:00', 1);
        $this->instance->setPlant($plant);
        $this->instance->asArray();
    }

    /**
     * @expectedException InvalidArgumentException
     */
    public function testInvalidProperty() {
        $this->assertNull($this->instance->notExistingProperty);
        // throws InvalidArgumentException
        $this->instance->notExistingProperty = 0;
    }

    /**
     *
     */
    public function testSetGetTemperature() {
        $this->assertNull($this->instance->getTemperature());

        $this->instance->setTemperature(new Temperature);
        $this->assertInstanceOf('PVLog\Classes\Json\Temperature', $this->instance->getTemperature());

        $this->instance->temperature = new Temperature;
        $this->assertInstanceOf('PVLog\Classes\Json\Temperature', $this->instance->temperature);
    }

}


text:
// import { NgModule } from '@angular/core';
// import { TestBed } from '@angular/core/testing';
// import { readFirst } from '@nrwl/nx/testing';
//
// import { EffectsModule } from '@ngrx/effects';
// import { StoreModule, Store } from '@ngrx/store';
//
// import { NxModule } from '@nrwl/nx';
//
// import { DeviceEffects } from './device.effects';
// import { DeviceFacade } from './device.facade';
//
// import { deviceQuery } from './device.selectors';
// import { LoadDevice, DeviceLoaded } from './device.actions';
// import {
//   DeviceState,
//   Entity,
//   initialState,
//   deviceReducer
// } from './device.reducer';
//
// interface TestSchema {
//   device: DeviceState;
// }
//
// describe('DeviceFacade', () => {
//   let facade: DeviceFacade;
//   let store: Store<TestSchema>;
//   let createDevice;
//
//   beforeEach(() => {
//     createDevice = (id: string, name = ''): Entity => ({
//       id,
//       name: name || `name-${id}`
//     });
//   });
//
//   describe('used in NgModule', () => {
//     beforeEach(() => {
//       @NgModule({
//         imports: [
//           StoreModule.forFeature('device', deviceReducer, { initialState }),
//           EffectsModule.forFeature([DeviceEffects])
//         ],
//         providers: [DeviceFacade]
//       })
//       class CustomFeatureModule {}
//
//       @NgModule({
//         imports: [
//           NxModule.forRoot(),
//           StoreModule.forRoot({}),
//           EffectsModule.forRoot([]),
//           CustomFeatureModule
//         ]
//       })
//       class RootModule {}
//       TestBed.configureTestingModule({ imports: [RootModule] });
//
//       store = TestBed.get(Store);
//       facade = TestBed.get(DeviceFacade);
//     });
//
//     /**
//      * The initially generated facade::loadAll() returns empty array
//      */
//     it('loadAll() should return empty list with loaded == true', async done => {
//       try {
//         let list = await readFirst(facade.allDevice$);
//         let isLoaded = await readFirst(facade.loaded$);
//
//         expect(list.length).toBe(0);
//         expect(isLoaded).toBe(false);
//
//         facade.loadAll();
//
//         list = await readFirst(facade.allDevice$);
//         isLoaded = await readFirst(facade.loaded$);
//
//         expect(list.length).toBe(0);
//         expect(isLoaded).toBe(true);
//
//         done();
//       } catch (err) {
//         done.fail(err);
//       }
//     });
//
//     /**
//      * Use `DeviceLoaded` to manually submit list for state management
//      */
//     it('allDevice$ should return the loaded list; and loaded flag == true', async done => {
//       try {
//         let list = await readFirst(facade.allDevice$);
//         let isLoaded = await readFirst(facade.loaded$);
//
//         expect(list.length).toBe(0);
//         expect(isLoaded).toBe(false);
//
//         store.dispatch(
//           new DeviceLoaded([createDevice('AAA'), createDevice('BBB')])
//         );
//
//         list = await readFirst(facade.allDevice$);
//         isLoaded = await readFirst(facade.loaded$);
//
//         expect(list.length).toBe(2);
//         expect(isLoaded).toBe(true);
//
//         done();
//       } catch (err) {
//         done.fail(err);
//       }
//     });
//   });
// });


text:
package org.jboss.vfs;

import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;

/**
 * An input stream that can be used to wrap an VirtualJarInputStream (so any VFS dir)
 * and produce a byte stream following the Zip standard.
 *
 * @author John Bailey
 */
public class VirtualJarFileInputStream extends InputStream {
    // Needs to be sufficiently sized to allow local and central file headers with a single entry name
    private static final int MINIMUM_BUFFER_LENGTH = 1024;

    private final VirtualJarInputStream virtualJarInputStream;

    private State currentState = State.NOT_STARTED;

    private final List<ProcessedEntry> processedEntries = new LinkedList<ProcessedEntry>();
    private ProcessedEntry currentEntry;

    private final ByteBuffer buffer;
    private final CRC32 crc = new CRC32();

    private int currentCentralEntryIdx;
    private long centralOffset;
    private long totalRead;

    /**
     * Create with the minimum put length
     *
     * @param virtualJarInputStream The virtual jar input stream to base the stream off of
     */
    public VirtualJarFileInputStream(final VirtualJarInputStream virtualJarInputStream) {
        this(virtualJarInputStream, MINIMUM_BUFFER_LENGTH);
    }

    /**
     * Create with the a specified put size
     *
     * @param virtualJarInputStream The virtual jar input stream to base the stream off of
     * @param bufferLength          The length of put to use
     */
    public VirtualJarFileInputStream(final VirtualJarInputStream virtualJarInputStream, int bufferLength) {
        if (virtualJarInputStream == null) {
            throw VFSMessages.MESSAGES.nullArgument("virtualJarInputStream");
        }
        if (bufferLength < MINIMUM_BUFFER_LENGTH) {
            throw VFSMessages.MESSAGES.bufferMustBeLargerThan(MINIMUM_BUFFER_LENGTH);
        }

        this.virtualJarInputStream = virtualJarInputStream;

        buffer = new ByteBuffer(bufferLength);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int read() throws IOException {
        int readByte = -1;
        while (currentState != null && (readByte = currentState.read(this)) == -1) {
            currentState = currentState.getNextState(this);
        }
        totalRead++;
        return readByte;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void close() throws IOException {
        VFSUtils.safeClose(virtualJarInputStream);
        super.close();
    }

    /**
     * Close the current entry, and calculate the crc value.
     *
     * @throws IOException if any problems occur
     */
    private void closeCurrent() throws IOException {
        virtualJarInputStream.closeEntry();
        currentEntry.crc = crc.getValue();
        crc.reset();
    }

    /**
     * Buffer the content of the local file header for a single entry.
     *
     * @return true if the next local file header was buffered
     * @throws IOException if any problems occur
     */
    private boolean bufferLocalFileHeader() throws IOException {
        buffer.reset();
        JarEntry jarEntry = virtualJarInputStream.getNextJarEntry();

        if (jarEntry == null) { return false; }

        currentEntry = new ProcessedEntry(jarEntry, totalRead);
        processedEntries.add(currentEntry);

        bufferInt(ZipEntry.LOCSIG);    // Local file header signature
        bufferShort(10);               // Extraction version
        bufferShort(0);                // Flags
        bufferShort(ZipEntry.STORED);  // Compression type
        bufferInt(jarEntry.getTime()); // Entry time
        bufferInt(0);                  // CRC
        bufferInt(0);                  // Compressed size
        bufferInt(0);                  // Uncompressed size
        byte[] nameBytes = jarEntry.getName().getBytes("UTF8");
        bufferShort(nameBytes.length); // Entry name length
        bufferShort(0);                // Extra length
        buffer(nameBytes);
        return true;
    }

    /**
     * Buffer the central file header record for a single entry.
     *
     * @return true if the next central file header was buffered
     * @throws IOException if any problems occur
     */
    private boolean bufferNextCentralFileHeader() throws IOException {
        buffer.reset();

        if (currentCentralEntryIdx == processedEntries.size()) { return false; }

        ProcessedEntry entry = processedEntries.get(currentCentralEntryIdx++);

        JarEntry jarEntry = entry.jarEntry;
        bufferInt(ZipEntry.CENSIG);       // Central file header signature
        bufferShort(10);                  // Version made by
        bufferShort(10);                  // Extraction version
        bufferShort(0);                   // Flags
        bufferShort(ZipEntry.STORED);     // Compression type
        bufferInt(jarEntry.getTime());    // Entry time
        bufferInt(entry.crc);             // CRC
        bufferInt(jarEntry.getSize());    // Compressed size
        bufferInt(jarEntry.getSize());    // Uncompressed size
        byte[] nameBytes = jarEntry.getName().getBytes("UTF8");
        bufferShort(nameBytes.length);    // Entry name length
        bufferShort(0);                   // Extra field length
        bufferShort(0);                   // File comment length
        bufferShort(0);                   // Disk number start
        bufferShort(0);                   // Internal file attributes
        bufferInt(0);                     // External file attributes
        bufferInt(entry.offset);          // Relative offset of local header
        buffer(nameBytes);
        return true;
    }

    /**
     * Write the central file header records.  This is repeated
     * until all entries have been added to the central file header.
     *
     * @throws IOException if any problem occur
     */
    private void bufferCentralDirectoryEnd() throws IOException {
        buffer.reset();
        long lengthOfCentral = totalRead - centralOffset;

        int count = processedEntries.size();
        bufferInt(JarEntry.ENDSIG);      // End of central directory signature
        bufferShort(0);                  // Number of this disk
        bufferShort(0);                  // Start of central directory disk
        bufferShort(count);              // Number of processedEntries on disk
        bufferShort(count);              // Total number of processedEntries
        bufferInt(lengthOfCentral);      // Size of central directory
        bufferInt(centralOffset);        // Offset of start of central directory
        bufferShort(0);                  // Comment Length
    }

    /**
     * Buffer a 32-bit integer in little-endian
     *
     * @param i A long representation of a 32 bit int
     */
    private void bufferInt(long i) {
        buffer((byte) (i & 0xff));
        buffer((byte) ((i >>> 8) & 0xff));
        buffer((byte) ((i >>> 16) & 0xff));
        buffer((byte) ((i >>> 24) & 0xff));
    }

    /**
     * Buffer a 16-bit short in little-endian
     *
     * @param i An int representation of a 16 bit short
     */
    private void bufferShort(int i) {
        buffer((byte) (i & 0xff));
        buffer((byte) ((i >>> 8) & 0xff));
    }

    /**
     * Buffer a single byte
     *
     * @param b The byte
     */
    private void buffer(byte b) {
        if (buffer.hasCapacity()) {
            buffer.put(b);
        } else {
            throw VFSMessages.MESSAGES.bufferDoesntHaveEnoughCapacity();
        }
    }

    /**
     * Buffer a byte array
     *
     * @param bytes The bytes
     */
    private void buffer(byte[] bytes) {
        for (byte b : bytes) { buffer(b); }
    }

    private class ProcessedEntry {
        private final JarEntry jarEntry;
        private final long offset;
        private long crc;

        private ProcessedEntry(final JarEntry jarEntry, final long offset) {
            this.jarEntry = jarEntry;
            this.offset = offset;
        }
    }

    /**
     * Basic state machine that will allow the process to transition between the different process states.
     *

     * The following describes the process flow:
     * [NOT_STARTED] - Initial state
     * - Does not provide content
     * - Transitions [LOCAL_ENTRY_HEADER]
     * [LOCAL_ENTRY_HEADER] - The phase for reading the Local Directory Header
     * - Provides content of the local directory header by populating and feeding off a buffer
     * - Transitions to [ENTRY_CONTENT] if the header was written
     * - Transitions to [START_CENTRAL_DIRECTORY] if this is the last local entry header
     * [ENTRY_CONTENT] - The phase for reading the content of an entry
     * - Provides content of the entry using the VirtualJarInputStream
     * - Transitions to [LOCAL_ENTRY_HEADER]
     * [START_CENTRAL_DIRECTORY] - Phased used to transition into the central directory
     * - Does not provide content
     * - Transitions to [CENTRAL_ENTRY_HEADER]
     * [CENTRAL_ENTRY_HEADER] - The phase for reading the content of a single central directory header
     * - Provides content for the central directory header by feeding off a buffer
     * - Transitions to [CENTRAL_ENTRY_HEADER]
     * - Transitions to [CENTRAL_END] if there are no more entries
     * [CENTRAL_END] - The phase for reading the contents of the central directory end
     * - Provides content for central directory end by feeing off a buffer
     * - Transitions to NULL to terminate the processing
     */
    private enum State {
        NOT_STARTED {
            @Override
            State transition(VirtualJarFileInputStream jarFileInputStream) throws IOException {
                return LOCAL_ENTRY_HEADER;
            }
        },
        LOCAL_ENTRY_HEADER {
            boolean buffered;

            @Override
            void init(final VirtualJarFileInputStream jarFileInputStream) throws IOException {
                buffered = jarFileInputStream.bufferLocalFileHeader();
            }

            @Override
            int read(VirtualJarFileInputStream jarFileInputStream) throws IOException {
                final ByteBuffer buffer = jarFileInputStream.buffer;
                if (buffered && buffer.hasRemaining()) { return buffer.get(); }
                return -1;
            }

            @Override
            State transition(final VirtualJarFileInputStream virtualJarFileInputStream) throws IOException {
                if (buffered) { return ENTRY_CONTENT; }
                return START_CENTRAL_DIRECTORY;
            }
        },
        ENTRY_CONTENT {
            @Override
            int read(final VirtualJarFileInputStream jarFileInputStream) throws IOException {
                final VirtualJarInputStream virtualJarInputStream = jarFileInputStream.virtualJarInputStream;
                return virtualJarInputStream.read();
            }

            @Override
            State transition(final VirtualJarFileInputStream virtualJarFileInputStream) throws IOException {
                virtualJarFileInputStream.closeCurrent();
                return LOCAL_ENTRY_HEADER;
            }
        },
        START_CENTRAL_DIRECTORY {
            @Override
            void init(final VirtualJarFileInputStream jarFileInputStream) throws IOException {
                jarFileInputStream.centralOffset = jarFileInputStream.totalRead;
            }

            @Override
            State transition(final VirtualJarFileInputStream virtualJarFileInputStream) throws IOException {
                return CENTRAL_ENTRY_HEADER;
            }
        },
        CENTRAL_ENTRY_HEADER {
            boolean buffered;

            @Override
            void init(final VirtualJarFileInputStream jarFileInputStream) throws IOException {
                buffered = jarFileInputStream.bufferNextCentralFileHeader();
            }

            @Override
            int read(final VirtualJarFileInputStream jarFileInputStream) throws IOException {
                final ByteBuffer buffer = jarFileInputStream.buffer;
                if (buffered && buffer.hasRemaining()) { return buffer.get(); }
                return -1;
            }

            @Override
            State transition(final VirtualJarFileInputStream virtualJarFileInputStream) throws IOException {
                if (buffered) { return CENTRAL_ENTRY_HEADER; }
                return CENTRAL_END;
            }
        },
        CENTRAL_END {
            @Override
            void init(final VirtualJarFileInputStream jarFileInputStream) throws IOException {
                jarFileInputStream.bufferCentralDirectoryEnd();
            }

            @Override
            int read(final VirtualJarFileInputStream jarFileInputStream) throws IOException {
                final ByteBuffer buffer = jarFileInputStream.buffer;
                if (buffer.hasRemaining()) { return buffer.get(); }
                return -1;
            }

            @Override
            State transition(final VirtualJarFileInputStream virtualJarFileInputStream) throws IOException {
                return null;
            }
        };

        void init(VirtualJarFileInputStream jarFileInputStream) throws IOException {
        }

        abstract State transition(VirtualJarFileInputStream virtualJarFileInputStream) throws IOException;

        int read(VirtualJarFileInputStream jarFileInputStream) throws IOException {
            return -1;
        }

        State getNextState(VirtualJarFileInputStream jarFileInputStream) throws IOException {
            State nextState = transition(jarFileInputStream);
            if (nextState != null) { nextState.init(jarFileInputStream); }
            return nextState;
        }
    }

    private static class ByteBuffer {

        private final int bufferLength;
        private final byte[] buffer;
        private int bufferPosition;
        private int bufferDepth;

        private ByteBuffer(final int bufferLength) {
            this.buffer = new byte[bufferLength];
            this.bufferLength = bufferLength;
        }

        private boolean hasRemaining() {
            return bufferPosition < bufferDepth;
        }

        private boolean hasCapacity() {
            return bufferDepth < bufferLength;
        }

        private byte get() {
            return buffer[bufferPosition++];
        }

        private void put(byte b) {
            buffer[bufferDepth++] = b;
        }

        private void reset() {
            bufferPosition = 0;
            bufferDepth = 0;
        }
    }
}


text:
/*
 * TestNode.java
 *
 * Created on April 12, 2007, 12:54 PM
 */

package net.java.nboglpack.visualdesigner.tests;

import java.awt.Graphics;

/**
 *
 * @author  Samuel Sperling
 */
public class TestNode extends javax.swing.JPanel {

    /** Creates new form TestNode */
    public TestNode() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();

        setLayout(null);

        setBackground(new java.awt.Color(72, 83, 92));
        setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        setToolTipText("\"test\"");
        jPanel1.setBackground(new java.awt.Color(152, 161, 171));
        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel1.setText("jLabel1");
        jLabel1.setAlignmentX(0.5F);
        jLabel1.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        jLabel1.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 96, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addContainerGap(65, Short.MAX_VALUE))
        );
        add(jPanel1);
        jPanel1.setBounds(10, 45, 120, 100);

    }// </editor-fold>//GEN-END:initComponents

    public void paintComponents(Graphics g) {
        super.paintComponents(g);
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    // End of variables declaration//GEN-END:variables

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
		 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>apache-commons-tostring-sorted</groupId>
	<artifactId>apache-commons-tostring-sorted</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<dependencies>
		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<version>2.5</version>
		</dependency>
		<dependency>
			<groupId>org.testng</groupId>
			<artifactId>testng</artifactId>
			<version>6.3.1</version>
			<scope>test</scope>
		</dependency>
	</dependencies>

</project>


text:
<configuration>
  <timestamp key="byDay" datePattern="yyyy-MM-dd" />

  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>[%level] %logger{45}:%X{line} | %msg%n</pattern>
    </encoder>
  </appender>

  <appender name="FILE" class="ch.qos.logback.core.FileAppender">
    <file>target/vertx-maven-${byDay}.log</file>
    <append>false</append>
    <encoder>
      <pattern>[%level] %logger{45}:%X{line} | %msg%n</pattern>
    </encoder>
  </appender>

  <logger name="io.netty" level="ERROR" additivity="false">
    <appender-ref ref="STDOUT" />
  </logger>
  <logger name="info.freelibrary.util" level="ERROR" additivity="false">
    <appender-ref ref="STDOUT" />
  </logger>
  <logger name="io.vertx" level="OFF" additivity="false">
    <appender-ref ref="STDOUT"/>
  </logger>

  <root level="DEBUG">
    <appender-ref ref="STDOUT" />
  </root>

</configuration>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Trichophyton effractum Sabour.

### Remarks
null


text:
package edu.tamu.weaver.token.service;

import static java.util.Calendar.MINUTE;

import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.MessageDigestAlgorithms;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

@Service
public class TokenService {

    private final static Logger LOG = LoggerFactory.getLogger(TokenService.class);

    private final static String TYPE_HEADER_KEY = "typ";

    private final static String TYPE_HEADER_VALUE = "JWT";

    private final static String ENCRYPTION_ALGORITHM = "AES";

    @Value("${auth.security.jwt.secret:verysecretsecret}")
    private String secret;

    @Value("${auth.security.jwt.issuer:localhost}")
    private String issuer;

    @Value("${auth.security.jwt.duration:5}")
    private int duration;

    @Value("${shib.keys:netid,uin,lastName,firstName,email}")
    private String[] shibKeys;

    @Value("${shib.subject:netid}")
    private String shibSubject;

    @Autowired
    private Environment env;

    private Key key;

    private String jwtSecret;

    private Key jwtKey;

    @PostConstruct
    private void setup() throws NoSuchAlgorithmException {
        key = new SecretKeySpec(secret.getBytes(), ENCRYPTION_ALGORITHM);
        jwtSecret = sha512Secret(secret);
        jwtKey = Keys.hmacShaKeyFor(jwtSecret.getBytes());
    }

    public String createToken(Map<String, Object> claims) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        return createToken("aggie", claims);
    }

    public String createToken(String subject, Map<String, Object> claims) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        Calendar calendar = Calendar.getInstance();
        Date now = calendar.getTime();
        calendar.add(MINUTE, duration);
        Date expiration = calendar.getTime();
        // @formatter:off
        String jwt = Jwts.builder()
                .setClaims(claims)
                .setIssuedAt(now)
                .setIssuer(issuer)
                .setSubject(subject)
                .setExpiration(expiration)
                .setHeaderParam(TYPE_HEADER_KEY, TYPE_HEADER_VALUE)
                .signWith(jwtKey, SignatureAlgorithm.HS512)
                .compact();
        // @formatter:on
        LOG.debug("created jwt: {}", jwt);
        Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        String jwe = Base64.encodeBase64URLSafeString(cipher.doFinal(jwt.getBytes()));
        LOG.debug("encrypted jwt: {}",  jwe);
        return jwe;
    }

    public String refreshToken(String token) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
        Claims claims = parseIgnoringExpiration(token);
        Map<String, Object> claimsMap = new HashMap<String, Object>();
        claims.entrySet().forEach(claim -> {
            claimsMap.put(claim.getKey(), claim.getValue());
        });
        return createToken(claims.getSubject(), claimsMap);
    }

    public Long tokenDuration(String token) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
        Calendar calendar = Calendar.getInstance();
        Date now = calendar.getTime();
        Claims claims = parseIgnoringExpiration(token);
        Date expiration = claims.getExpiration();
        return expiration.getTime() - now.getTime();
    }

    public Claims parse(String jwe) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        LOG.debug("parsing jwe: {}", jwe);
        Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key);
        String jwt = new String(cipher.doFinal(Base64.decodeBase64(jwe)));
        LOG.debug("parsed: {}", jwt);
        Claims claims = Jwts.parserBuilder().setSigningKey(jwtKey).build().parseClaimsJws(jwt).getBody();
        LOG.debug("claims: {}", claims);
        return claims;
    }

    public Claims parseIgnoringExpiration(String token) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
        Claims claims;
        try {
            claims = parse(token);
        } catch (ExpiredJwtException e) {
            claims = e.getClaims();
        }
        return claims;
    }

    public String craftToken(Map<String, String> headers) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
        Map<String, Object> claims = new HashMap<String, Object>();
        for (String k : shibKeys) {
            claims.put(k, headers.get(env.getProperty("shib." + k, "")) != null ? headers.get(env.getProperty("shib." + k, "")) : headers.get(k));
        }
        String subject = (String) claims.get(shibSubject);
        return createToken(subject, claims);
    }

    private String sha512Secret(String input) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance(MessageDigestAlgorithms.SHA_512);
        byte[] digest = md.digest(input.getBytes());
        BigInteger no = new BigInteger(1, digest);
        String hash = no.toString(16);

        while (hash.length() < 32) {
            hash = "0" + hash;
        }

        return hash;
    }

}


text:
namespace System.ComponentModel {

    using System;

    /// <devdoc>
    /// </devdoc>
    // suppose that you have some data that can be indexed by use of string:
    // then there are two types of errors:
    // 1. an error for each piece of data that can be indexed
    // 2. an error that is valid on the entire data
    //
    public interface IDataErrorInfo {

        /// <devdoc>
        /// </devdoc>
        string this[string columnName] {
            get;
        }
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        string Error {
            get;
        }
    }
}


text:
/**
 *
 */
package net.floodlightcontroller.datacentermarketing.Scheduling;

/**
 * @author openflow
 *
 *         Queue timed allocation
 */
public class Allocation implements Comparable<Allocation> {

	public Allocation() {
		super();
	}

	long from = 0;
	long to = 0;
	float bandwidth = 0;// MByte
	ADirection direction = null;

	public String toString() {
		return "Allocation : from" + from + " to " + to + " bandwitdh "
				+ bandwidth + " direction " + direction;

	}

	public Allocation(long from, long to, float bandwidth, ADirection direction) {
		super();
		this.from = from;
		this.to = to;
		this.bandwidth = bandwidth;
		this.direction = direction;
	}

	@Override
	public int compareTo(Allocation qta) {

		return  ((Long) from).compareTo((Long) qta.from);
	}

	public boolean overlap(Allocation alloc) {
		if (from < alloc.to && to > alloc.from)
			return true;

		return false;
	}

	public long getDuration() {
		return to - from;
	}

	public boolean sameDirection(Allocation alloc) {
		return this.direction == alloc.direction;
	}

	public long getFrom() {
		return from;
	}

	public void setFrom(long from) {
		this.from = from;
	}

	public long getTo() {
		return to;
	}

	public void setTo(long to) {
		this.to = to;
	}

	public float getBandwidth() {
		return bandwidth;
	}

	public void setBandwidth(float bandwidth) {
		this.bandwidth = bandwidth;
	}

	public ADirection getDirection() {
		return direction;
	}

	public void setDirection(ADirection direction) {
		this.direction = direction;
	}

}


text:
//
//  facebook.m
//  eViihde
//
//  Created by Sami Siuruainen on 22.10.2010.
//  Copyright 2010 Sami Siuruainen. All rights reserved.
//

#import "facebook.h"

@implementation facebook

- (bool) fbLogin:(NSString *)user password:(NSString *)pass {

	return false;
}

- (void) checkToken {
	cnfController *cnf;
	cnf = [[cnfController alloc] init];

	if ( [ cnf getBoolCnf:@"disableFacebook" ] )
	{

	} else {
		//NSLog(@"len:%d", [ (NSString *) [ cnf getStringCnf:@"fb_access_token" ] length]);
		//if ( ![(NSString *) [ cnf getStringCnf:@"fb_access_token" ] length] )
		//{
			NSString *response;
			NSURLResponse *Uresponse;
			NSError *error = nil;
			NSData *data;

			NSLog(@"[ authorize @ gui_1/login ]----------------------------------------------------------------------------------------------------------------");
			NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: @"https://graph.facebook.com/oauth/authorize?type=user_agent&scope=offline_access,publish_stream,create_event&client_id=106219119443269&redirect_uri=http://www.eviihde.com/fb_callback.php&display=wap" ] cachePolicy: NSURLRequestReloadIgnoringCacheData timeoutInterval: 30];
			data = [NSURLConnection sendSynchronousRequest: request returningResponse: &Uresponse  error: &error];
			response = [NSString stringWithUTF8String: [data bytes]];
			/*
			if ([Uresponse respondsToSelector:@selector(allHeaderFields)]) {
				NSLog(@"%@", response);
				NSDictionary *dictionary = [Uresponse allHeaderFields];
				NSLog(@"%@", [dictionary description]);
			}
			*/
			if ( [[ response substringToIndex:7] compare:@"<script"] ) {
				NSLog(@"%@", response);
				[ cnf setStringCnf:@"fb_access_token" value:@"" ];
				NSRunAlertPanel(@"eViihde", @"Facebook oikeuksia ei voitu tarkistaa. Varmista asetuksista että eViihde GUI on sallittu ohjelma Facebookissa.", @"Ok", nil, nil);
			} else {
				// We are authoriced, collect code=XXX
				NSLog(@"new_token: %@", response);

				NSRange codeLocS=[ response rangeOfString:@"access_token="];
				NSString * codeString = [ response substringFromIndex: codeLocS.location + 13 ];
				NSRange codeLocE = [ codeString rangeOfString:@"&expires"];
				codeString = [ codeString substringToIndex: codeLocE.location ];
				NSLog(@"FB Access Token: %@", codeString);

				NSRange uidLocS = [ codeString rangeOfString:@"-" ];
				NSString * fbUID = [ codeString substringFromIndex: uidLocS.location + 1 ];
				NSRange uidLocE = [ fbUID rangeOfString:@"%" ];
				fbUID = [ fbUID substringToIndex:uidLocE.location ];
				NSLog(@"fbUID:%@", fbUID);
				[ cnf setStringCnf:@"fb_access_token" value:codeString ];
				[ cnf setStringCnf:@"fb_uid" value:fbUID ];
			}
		//}
	}
}

- (NSString *) setStatus:(NSString *)fbMessage {
	cnfController *cnf;
	cnf = [[cnfController alloc] init];

	//[ self checkToken ];

	NSData* requestData = [
						   [ NSString stringWithFormat:
							@"access_token=%@&message=%@",
							[ cnf getStringCnf:@"fb_access_token" ],
							fbMessage
							] dataUsingEncoding:NSUTF8StringEncoding];

	NSString* requestDataLengthString = [[NSString alloc] initWithFormat:@"%d", [requestData length]];

	NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString: @"https://graph.facebook.com/me/feed"]];
	[request setHTTPMethod:@"POST"];
	[request setHTTPBody:requestData];
	[request setValue:requestDataLengthString forHTTPHeaderField:@"Content-Length"];
	[request setTimeoutInterval:30.0];

	NSString *response;
	NSURLResponse *Uresponse;
	NSError *error = nil;
	NSData *data;

	data = [NSURLConnection sendSynchronousRequest: request returningResponse: &Uresponse  error: &error];
	response = [NSString stringWithUTF8String: [data bytes]];
	return response;
}

- (NSString *) postToFeed:(NSString *)fbMessage fbLink:(NSString *)fbLink fbPicture:(NSString *)fbPicture fbName:(NSString *)fbName fbCaption:(NSString *)fbCaption fbDescription:(NSString *)fbDescription {

	cnfController *cnf;
	cnf = [[cnfController alloc] init];

	//[ self checkToken ];

	if ( fbPicture == @"" ) {
		fbPicture = @"http://www.eviihde.com/tickets_fb.png";
	}

	NSData* requestData = [
						   [ NSString stringWithFormat:
							@"access_token=%@&message=%@&link=%@&name=%@&caption=%@&picture=%@&description=%@&privacy={\"value\": \"ALL_FRIENDS\"}",
							[ cnf getStringCnf:@"fb_access_token" ],
							fbMessage,
							fbLink,
							fbName,
							fbCaption,
							fbPicture,
							fbDescription
							] dataUsingEncoding:NSUTF8StringEncoding];

	NSString* requestDataLengthString = [[NSString alloc] initWithFormat:@"%d", [requestData length]];

	NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString: @"https://graph.facebook.com/me/feed"]];
	[request setHTTPMethod:@"POST"];
	[request setHTTPBody:requestData];
	[request setValue:requestDataLengthString forHTTPHeaderField:@"Content-Length"];
	[request setTimeoutInterval:30.0];

	NSString *response;
	NSURLResponse *Uresponse;
	NSError *error = nil;
	NSData *data;

	data = [NSURLConnection sendSynchronousRequest: request returningResponse: &Uresponse  error: &error];
	response = [NSString stringWithUTF8String: [data bytes] ];
	return response;
}

- (NSString *) postLink:(NSString *)fbLink fbPicture:(NSString *)fbPicture fbName:(NSString *)fbName fbCaption:(NSString *)fbCaption fbDescription:(NSString *)fbDescription {
	return [ self postToFeed:@"" fbLink:fbLink fbPicture:fbPicture fbName:fbName fbCaption:fbCaption fbDescription:fbDescription ];
}

- (NSString *) createEvent:(NSString *)fbEventName fbDescription:(NSString *)fbDescription fbStart_time:(NSString *)fbStart_time fbEnd_time:(NSString *)fbEnd_time fbLocation:(NSString *)fbLocation fbPrivacy:(NSString *)fbPrivacy {
	cnfController *cnf;
	cnf = [[cnfController alloc] init];

	if ( fbPrivacy == @"" ) {
		fbPrivacy = @"SECRET";
	}

	NSData* requestData = [
						   [ NSString stringWithFormat:
							@"access_token=%@&name=%@&description=%@&start_time=%@&end_time=%@&location=%@&privacy_type=%@",
							[ cnf getStringCnf:@"fb_access_token" ],
							fbEventName,
							fbDescription,
							fbStart_time,
							fbEnd_time,
							fbLocation,
							fbPrivacy
							] dataUsingEncoding:NSUTF8StringEncoding];

	NSString* requestDataLengthString = [[NSString alloc] initWithFormat:@"%d", [requestData length]];

	NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString: @"https://graph.facebook.com/me/events"]];
	[request setHTTPMethod:@"POST"];
	[request setHTTPBody:requestData];
	[request setValue:requestDataLengthString forHTTPHeaderField:@"Content-Length"];
	[request setTimeoutInterval:30.0];

	NSString *response;
	NSURLResponse *Uresponse;
	NSError *error = nil;
	NSData *data;

	data = [NSURLConnection sendSynchronousRequest: request returningResponse: &Uresponse  error: &error];
	response = [NSString stringWithUTF8String: [data bytes] ];
	return response;
}

/** TODO: SetFacebookStatus
 curl
	-F 'access_token=...' \
	-F 'message=This is my status update' \
	https://graph.facebook.com/me/feed
 **/

/** TODO: Token Error
 {
 "error": {
 "type": "OAuthException",
 "message": "Error validating access token."
 }
 }

 {
 "error": {
 "type": "OAuthException",
 "message": "An active access token must be used to query information about the current user."
 }
 }

 **/

@end


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#pragma once

#include <vespa/vespalib/stllike/string.h>
#include <memory>

namespace vespalib::eval { struct ConstantValue; }

namespace search::fef {

class Properties;
class FieldInfo;
class ITableManager;
class OnnxModel;

/**
 * Abstract view of index related information available to the
 * framework.
 **/
class IIndexEnvironment
{
public:
    typedef vespalib::string string;
    /**
     * This enum defines the different motivations the framework has
     * for configuring a feature blueprint. RANK means the feature is
     * needed for ranking calculations in normal operation. DUMP means
     * the feature is needed to perform a feature dump. VERIFY_SETUP
     * means that we are just trying to figure out if this setup is
     * valid; the feature will never actually be executed.
     **/
    enum FeatureMotivation {
        UNKNOWN = 0,
        RANK = 1,
        DUMP = 2,
        VERIFY_SETUP = 3
    };

    /**
     * Obtain the set of properties associated with this index
     * environment.
     *
     * @return properties
     **/
    virtual const Properties &getProperties() const = 0;

    /**
     * Obtain the number of fields
     *
     * @return number of fields
     **/
    virtual uint32_t getNumFields() const = 0;

    /**
     * Obtain a field by using the field enumeration. The legal range
     * for id is [0, getNumFields>. If id is out of bounds, 0 will be
     * returned.
     *
     * @return information about a single field
     **/
    virtual const FieldInfo *getField(uint32_t id) const = 0;

    /**
     * Obtain a field by using the field name. If the field is not
     * found, 0 will be returned.
     *
     * @return information about a single field
     **/
    virtual const FieldInfo *getFieldByName(const string &name) const = 0;

    /**
     * Obtain the table manager associated with this index environment.
     *
     * @return table manager
     **/
    virtual const ITableManager &getTableManager() const = 0;

    /**
     * Obtain the current motivation behind feature setup. The
     * motivation is typically that we want to set up features for
     * ranking or dumping. In some cases we are also setting things up
     * just to verify that it is possible.
     *
     * @return current feature motivation
     **/
    virtual FeatureMotivation getFeatureMotivation() const = 0;

    /**
     * Hint about the nature of the feature blueprints we are about to
     * configure. This method provides additional information that may
     * be useful when interpreting hints about future field and
     * attribute access.
     *
     * @param motivation the motivation behind the feature blueprints
     *                   the framework is about to configure.
     **/
    virtual void hintFeatureMotivation(FeatureMotivation motivation) const = 0;

    /**
     * Hint about the future access of a field. This method may be
     * used by blueprints during setup to hint the enclosing system
     * that a feature executor created by it might try to access the
     * field iterator for a specific field during execution.
     *
     * @param fieldId field id
     **/
    virtual void hintFieldAccess(uint32_t fieldId) const = 0;

    /**
     * Hint about the future access of an attribute. This method may
     * be used by blueprints during setup to hint the enclosing system
     * that a feature executor created by it might try to access a
     * specific attribute during execution.
     *
     * @param name attribute name
     **/
    virtual void hintAttributeAccess(const string &name) const = 0;

    /**
     * Returns a constant rank value with the given name or null ptr if no such value exists.
     */
    virtual std::unique_ptr<vespalib::eval::ConstantValue> getConstantValue(const vespalib::string &name) const = 0;

    /**
     * Returns the ranking expression with the given name or empty string if not found.
     **/
    virtual vespalib::string getRankingExpression(const vespalib::string &name) const = 0;

    /**
     * Get configuration for the given onnx model.
     **/
    virtual const OnnxModel *getOnnxModel(const vespalib::string &name) const = 0;

    virtual uint32_t getDistributionKey() const = 0;

    /**
     * Virtual destructor to allow safe subclassing.
     **/
    virtual ~IIndexEnvironment() {}
};

}


text:
coca-jgroups
==================

## [配置定义](src/main/java/coca/jgroups/JGroupsConst.java)[=默认值]
- co.io.selector = coca.jgroups.co.io.JGroupsChannelSelector


text:
@interface OLMutableArray () {
    NSMutableArray *_cache;
}
@end

@implementation OLMutableArray

- (instancetype)init {
    self = [super init];
    if(!self) return nil;

    _cache = [[NSMutableArray alloc] init];
    _changed = [RACSubject subject];
    _removed = [RACSubject subject];

    return self;
}

- (NSInteger)count {
    return _cache.count;
}

- (void)addObject:(id)item {
    [_cache addObject:item];
    [self signalChange:item];
}

- (id)objectAtIndex:(NSInteger)index {
    return _cache[index];
}

- (NSInteger)indexOfObject:(id)item {
    return [_cache indexOfObject:item];
}

- (void)removeObject:(id)item {
    [_cache removeObject:item];
    [self signalRemoval:item];
}

- (void)removeAll {
    [_cache removeAllObjects];
}

- (void)enumerateObjectsUsingBlock:(void (^)(id obj, NSUInteger idx, BOOL *stop))block {
    [_cache enumerateObjectsUsingBlock:block];
}

- (void)signalChange:(id)item {
    id<RACSubscriber> sub = (id<RACSubscriber>)_changed;
    [sub sendNext:item];
}

- (void)signalRemoval:(id)item {
    id<RACSubscriber> sub = (id<RACSubscriber>)_removed;
    [sub sendNext:item];
}

- (NSArray *)filter:(NSPredicate *)predicate {
    return [_cache filteredArrayUsingPredicate:predicate];
}

@end


text:
package com.yoandinkov.onthehook;

import org.apache.http.HttpStatus;

import com.yoandinkov.onthehook.crypt.JsonConverter;
import com.yoandinkov.onthehook.crypt.SHA1Converter;
import com.yoandinkov.onthehook.models.HttpResponseWrapper;
import com.yoandinkov.onthehook.models.Login;
import com.yoandinkov.onthehook.models.Response;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;

public class LoginActivity extends RequestActivity{

	private Button ButtonLogin;
	private Button ButtonRegister;
	private EditText EditTextUsername;
	private String usernameInput;
	private ProgressDialog dialog;

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

		this.setButtonLogin((Button)findViewById(R.id.loginButtonLogin));
		this.setButtonRegister((Button)findViewById(R.id.loginButtonRegister));
		this.setEditTextUsername((EditText)findViewById(R.id.loginEditTextUsername));

		this.getButtonLogin().setOnClickListener(this);
		this.getButtonRegister().setOnClickListener(this);

		String sessionKey = this.getCredentials();

		if(sessionKey != null) {
			this.startMainMenuActivity(sessionKey);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();

		String input = this.getUsernameInput();
		this.getEditTextUsername().setText(input);
	}

	@Override
	protected void onPause() {
		super.onPause();

		String input = this.getEditTextUsername().getText().toString();
		this.setUsernameInput(input);
	}

	@Override
	public void onClick(View clickedView) {
		int clickedViewId = clickedView.getId();

		switch(clickedViewId) {
		case R.id.loginButtonLogin :
			this.buttonLoginClick(clickedView);
			break;
		case R.id.loginButtonRegister :
			this.buttonRegisterClick(clickedView);
			break;
		default:
			// TODO implement
			break;
		}
	}

	private void buttonLoginClick(View currentView) {
		Login currentLogin = new Login();

		String authKey = SHA1Converter
				.encryptPassword(((EditText) findViewById(R.id.loginEditTextPassword))
						.getText().toString());
		String username = this.getEditTextUsername().getText().toString();

		currentLogin.setAuthKey(authKey);
		currentLogin.setUsername(username);

		this.logUser(currentLogin);
	}

	protected void logUser(Login login) {
		String loginAsJson = JsonConverter.toJson(login);
		String url = this.getApiUrl() + "/auth/login";

		this.setDialog(ProgressDialog.show(this, "Logging ..", ""));

		HttpPostRequester currentRequest = new HttpPostRequester();

		currentRequest.execute(url, loginAsJson);
	}

	@Override
	protected void handleResponse(HttpResponseWrapper responseWrapper) {
		Response currentResponse = responseWrapper.getResponse();

		if (currentResponse.getStatusCode() == HttpStatus.SC_OK) {
			String sessionKey = currentResponse.getBody();

			this.startMainMenuActivity(sessionKey);
		} else {
			this.dialog.hide();

			AlertDialog.Builder errorDisplay = new AlertDialog.Builder(this);

			errorDisplay.setTitle("Error")
		    .setMessage(currentResponse.getBody())
		    .setPositiveButton("OK",null);

		    errorDisplay.show();
		}
	}

	private String getCredentials() {
		String result = "";

		SharedPreferences credentials = getSharedPreferences("credentials", MODE_PRIVATE);

		result = credentials.getString("sessionKey", null);

		return result;
	}

	private void startMainMenuActivity(String sessionKey) {
		Intent startMainMenuIntention = new Intent(this, MainMenuActivity.class);

		startMainMenuIntention.putExtra("sessionKey", sessionKey);

		startActivity(startMainMenuIntention);

		finish();
	}

	// RegisterActivity redirection
	private void buttonRegisterClick(View currentView) {
		Intent startRegisterActivity = new Intent(this, RegisterActivity.class);

		startActivity(startRegisterActivity);
	}

	// Auto-generated getters/setters
	public Button getButtonLogin() {
		return ButtonLogin;
	}

	public void setButtonLogin(Button buttonLogin) {
		ButtonLogin = buttonLogin;
	}

	public Button getButtonRegister() {
		return ButtonRegister;
	}

	public void setButtonRegister(Button buttonRegister) {
		ButtonRegister = buttonRegister;
	}

	public EditText getEditTextUsername() {
		return EditTextUsername;
	}

	public void setEditTextUsername(EditText editTextUsername) {
		EditTextUsername = editTextUsername;
	}

	public String getUsernameInput() {
		return usernameInput;
	}

	public void setUsernameInput(String usernameInput) {
		this.usernameInput = usernameInput;
	}

	public ProgressDialog getDialog() {
		return dialog;
	}

	public void setDialog(ProgressDialog dialog) {
		this.dialog = dialog;
	}

}


text:
package main.java.tree;

import static org.junit.Assert.*;

import org.junit.Test;

/**
 * Created by Maksym_Mazur on 11/10/2016.
 */
public class NodeTest {
    @Test
    public void simpleTreeTest(){
        Node node = new Node(3);
        node.add(2);
        node.add(4);
        assertEquals("2 3 4 ", node.show());
    }

}


text:
"""backend URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import include
from rest_framework.authtoken import views

from posts import urls as posts_urls

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^rest-api-auth/', include('rest_framework.urls',
                                    namespace='rest_framework')),
    url(r'^api/v1/auth/', views.obtain_auth_token),

    url(r'^api/v1/', include('posts.urls', namespace='posts')),
    url(r'^api/v1/', include('categories.urls', namespace='categories')),
    url(r'^api/v1/', include('core.urls', namespace='core')),
    url(r'^api/v1/', include('profiles.urls', namespace='core')),

    url(r'', include(posts_urls)),
]  + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)


text:
//define databases
var adminDb= "admin";
var myDb= "mydb";

/*
* CHANGE USERNAME/PASSWORD
*/
db.getSiblingDB(adminDb).createUser(
  {
    user: "ENTER_ADMIN_USER",
    pwd: "ENTER_APP_PASS",
    roles: ["root"]
  }
);

//create a non-admin user with read/write access to application db
db.getSiblingDB(myDb).createUser(
    {
      user: "ENTER_USER",
      pwd: "ENTER_APP_USER",
      roles: [
         { role: "readWrite", db: myDb }
      ]
    }
);