text:
package protocol

import (
	"fmt"

	"github.com/supershabam/sarama-cg"

	"github.com/serialx/hashring"
)

// HashRing is a type of Protocol that attemps to handle additions/removals of
// nodes and partitions with the least number of changes to a previous configurations.
type HashRing struct {
	MyUserData []byte
}

// int32Slice is just so we can sort int32s.
type int32Slice []int32

func (s int32Slice) Len() int           { return len(s) }
func (s int32Slice) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] }

// Assign distributes TopicPartitions among MemberIDs
func (hr *HashRing) Assign(cand cg.Candidates) cg.Assignment {
	a := make(map[string]cg.TopicPartitions, len(cand.Members))
	ids := make([]string, 0, len(cand.Members))
	for _, member := range cand.Members {
		ids = append(ids, member.MemberID)
	}
	ring := hashring.New(ids)
	for topic, partitions := range cand.TopicPartitions {
		for _, partition := range partitions {
			key := fmt.Sprintf("%s:%d", topic, partition)
			memberID, _ := ring.GetNode(key)
			if _, ok := a[memberID]; !ok {
				a[memberID] = map[string][]int32{}
			}
			if _, ok := a[memberID][topic]; !ok {
				a[memberID][topic] = []int32{}
			}
			a[memberID][topic] = append(a[memberID][topic], partition)
		}
	}
	return a
}

// UserData is written to Kafka upon joining the group and can be accessed within
// the Assign funcion utilizing the UserData from all other members.
func (hr *HashRing) UserData() []byte {
	return hr.MyUserData
}


text:
GRANT ALL PRIVILEGES ON ninja.* TO 'ninja'@'%' IDENTIFIED BY 'ninja';
GRANT ALL PRIVILEGES ON douitsu.* TO 'douitsu'@'%' IDENTIFIED BY 'douitsu';
FLUSH PRIVILEGES;

CREATE DATABASE IF NOT EXISTS `douitsu`;

USE `douitsu`

CREATE TABLE sys_entity (
  id varchar(255) NOT NULL,
  zone varchar(255) DEFAULT NULL,
  base varchar(255) DEFAULT NULL,
  name varchar(255) DEFAULT NULL,
  fields varchar(4000) DEFAULT NULL,
  seneca varchar(255) DEFAULT NULL,
  PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE sys_settings (
  id varchar(255) NOT NULL,
  kind varchar(255) DEFAULT NULL,
  spec varchar(255) DEFAULT NULL,
  ref varchar(255) DEFAULT NULL,
  settings varchar(255) DEFAULT NULL,
  data varchar(4000) DEFAULT NULL,
  seneca varchar(255) DEFAULT NULL,
  PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE sys_user (
  id varchar(255) NOT NULL,
  nick varchar(255) DEFAULT NULL,
  name varchar(255) DEFAULT NULL,
  email varchar(255) DEFAULT NULL,
  active tinyint(1) DEFAULT NULL,
  created datetime DEFAULT NULL,
  updated datetime DEFAULT NULL,
  confirmed tinyint(1) DEFAULT NULL,
  confirmcode varchar(255) DEFAULT NULL,
  admin tinyint(1) DEFAULT NULL,
  salt varchar(255) DEFAULT NULL,
  pass varchar(255) DEFAULT NULL,
  image varchar(255) DEFAULT NULL,
  accounts varchar(4000) DEFAULT NULL,
  seneca varchar(255) DEFAULT NULL,
  PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE sys_reset (
  id varchar(255) NOT NULL,
  active tinyint(1) DEFAULT NULL,
  nick varchar(255) DEFAULT NULL,
  user varchar(255) DEFAULT NULL,
  `when` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE sys_login (
  id varchar(255) NOT NULL,
  nick varchar(255) DEFAULT NULL,
  email varchar(255) DEFAULT NULL,
  user varchar(255) DEFAULT NULL,
  active tinyint(1) DEFAULT NULL,
  auto tinyint(1) DEFAULT NULL,
  `when` datetime DEFAULT NULL,
  why varchar(255) DEFAULT NULL,
  token varchar(255) DEFAULT NULL,
  context varchar(255) DEFAULT NULL,
  ended timestamp NOT NULL,
  seneca varchar(255) DEFAULT NULL,
  PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE sys_account (
  id varchar(255) NOT NULL,
  name varchar(255) DEFAULT NULL,
  orignick varchar(255) DEFAULT NULL,
  origuser varchar(255) DEFAULT NULL,
  active tinyint(1) DEFAULT NULL,
  users varchar(4000) DEFAULT NULL,
  projects varchar(4000) DEFAULT NULL,
  seneca varchar(255) DEFAULT NULL,
  PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE application (
  id varchar(255) NOT NULL,
  account varchar(255) DEFAULT NULL,
  name varchar(255) DEFAULT NULL,
  appid varchar(255) DEFAULT NULL,
  secret varchar(255) DEFAULT NULL,
  homeurl varchar(255) DEFAULT NULL,
  callback varchar(255) DEFAULT NULL,
  `desc` varchar(255) DEFAULT NULL,
  image varchar(255) DEFAULT NULL,
  active tinyint(1) DEFAULT NULL,
  is_ninja_official tinyint(1) NOT NULL DEFAULT 0,
  client_type enum('confidential', 'public') NOT NULL DEFAULT 'confidential',
  PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE authcode (
  id varchar(255) NOT NULL,
  code varchar(255) NOT NULL,
  clientID varchar(255) NOT NULL,
  redirectURI varchar(255) NOT NULL,
  userID varchar(255) NOT NULL,
  scope varchar(255) NOT NULL DEFAULT '',
  PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE accesstoken (
  id varchar(255) NOT NULL,
  userID varchar(255) NOT NULL,
  clientID varchar(255) NOT NULL,
  clientName varchar(255) NOT NULL,
  type varchar(255) NOT NULL DEFAULT 'application',
  `mqtt_client_id` int(20) NOT NULL AUTO_INCREMENT UNIQUE,
  `node_id` varchar(64) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
  PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE accesstoken_scope (
  id varchar(255) NOT NULL,
  accesstoken varchar(255) NOT NULL,
  scope_domain varchar(255) NOT NULL,
  scope_item varchar(255) NOT NULL,
  PRIMARY KEY (id),
  UNIQUE KEY `scope_specific` (accesstoken, scope_domain, scope_item),
  FOREIGN KEY (accesstoken) REFERENCES accesstoken (id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE DATABASE IF NOT EXISTS `ninja`;
USE `ninja`;

CREATE TABLE `nodes` (
--  `mqtt_client_id` int(20) NOT NULL AUTO_INCREMENT UNIQUE,
  `user_id` varchar(64) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  `node_id` varchar(64) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  `site_id` varchar(64) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  `hardware_type` varchar(64) NOT NULL,
--  `token` varchar(64) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  `updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `mqtt_client_id` int(20) not null auto_increment,
  PRIMARY KEY (`user_id`, `node_id`),
  UNIQUE KEY `mqtt_client_id_key` (`mqtt_client_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `users` (
  `user_id` varchar(64) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  `name` varchar(128) NOT NULL,
  `email` varchar(128) NOT NULL,
  `lastAccessToken` varchar(128) NULL,
  `updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `sphere_network_key` varchar(64) NOT NULL,
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `sites` (
  `user_id` varchar(64) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  `site_id` varchar(64) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  `master_node_id` varchar(64) CHARACTER SET utf8 COLLATE utf8_bin NULL,
  `updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`user_id`, `site_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

redpajama_set_name: RedPajamaGithub


text:
package path_sum;

import org.junit.Test;

import common.TreeNode;

public class PathSum {

    public class Solution {
        public boolean hasPathSum(TreeNode root, int sum) {
            if (root == null) {
                return false;
            }
            if (root.left == null && root.right == null) {
                return sum == root.val;
            }
            return hasPathSum(root.left, sum - root.val)
                    || hasPathSum(root.right, sum - root.val);
        }
    }

    public static class UnitTest {

        @Test
        public void test() {
            new PathSum().new Solution().hasPathSum(new TreeNode(1), 1);
        }
    }
}


text:
#pragma once

#include <functional>

#include "jml/arch/demangle.h"
#include "jml/arch/exception.h"
#include "jml/utils/exc_assert.h"

#if NODEJS_ENABLED
#include "soa/js/js_call_fwd.h"
#endif // NODEJS_ENABLED

namespace boost {
namespace signals2 {
struct connection;
} // namespace signals2
} // namespace boost

namespace Json {
struct Value;
} // namespace Json

namespace Datacratic {

#if NODEJS_ENABLED
bool inJsContext();

void enterJs(void * & locker);
void exitJs(void * & locker);

struct JSLocker {
    JSLocker()
    {
        enterJs(locker);
    }

    ~JSLocker()
    {
        exitJs(locker);
    }

    void * locker;
};
#endif // NODEJS_ENABLED

/** Type of a function used to disconnect a slot from a signal. */
struct SlotDisconnector
    : public std::function<void (void)> {

    template<typename T>
    SlotDisconnector(const T & f)
        : std::function<void (void)>(f)
    {
    }

    SlotDisconnector()
    {
    }

    SlotDisconnector(const boost::signals2::connection & connection);
};

/* What do we want to do here?

   We want to be able to:
   - Pass std::function objects of different types around through the one
     interface
   - Call them as a specific type of std::function when we need to
   - Have them throw an exception if we try to call them as something that
     they're not
   - Be able to initialize them from javascript functions in such a way that
     everything will be forwarded automatically
   - Be able to make them callable from javascript
*/

/** Type of the function that does the heavy lifting.  It's a multiplexed
    function (behind the argument).

    Operations:
    0:   returns the pointer to the std::type_info block for the operator
         class.  arg1 and arg2 are unused.
    1:   free the std::function_base descendent pointed to by arg1
    3:   copy the std::function_base descendent pointed to by arg1 and
         return a pointer to the new copy
*/
typedef void * (* Operations) (int op, void * arg);

/** Default implementation of the operations on the function. */
template<typename Fn>
struct FunctionOps {
    typedef typename std::function<Fn> Function;

    static void * ops(int op, void * arg)
    {
        switch (op) {
        case 0: *(const std::type_info **)(arg) = &typeid(Fn);  break;
        case 1: delete (std::function<Fn> *)arg;  break;
        case 3: return new Function(*(std::function<Fn> *)arg);
        default:
            throw ML::Exception("invalid operation number");
        }
        return 0;
    }
};

/*****************************************************************************/
/* SLOT                                                                      */
/*****************************************************************************/

/** Encapsulates a function that can be called with a specific argument list,
    without knowing the actual argument list.

    Note that in the C++ world, the signatures under which we are calling and
    the signature of the wrapped function must match exactly (ie, no type
    coersion.

    These can be:
    - Manipulated and used without knowing the exact type signature of the
      event;
    - Made to point to a Javascript function that will be called with the
      arguments forwarded from C++;
    - Called, queried and hooked up from Javascript
*/

struct Slot {
    Slot()
        : fn(nullptr), fntype(EMPTY)
    {
    }

    Slot(Slot && other);

    Slot & operator = (Slot && other);

    void swap(Slot & other);

    Slot(const Slot & other);

    Slot & operator = (const Slot & other);

    // Initialize from a std::function where the function type and the
    // called type are identical
#if NODEJS_ENABLED
    template<typename Fn, typename F>
    static Slot fromF(const std::function<F> & fn,
                      Operations ops = FunctionOps<Fn>::ops,
                      JS::JSOperations jsops = JS::getOps(typeid(Fn)))
    {

        Slot result;
        if (!fn) return result;
        result.fntype = STD_FN;
        result.ops = ops;
        result.jsops = jsops;
        result.fn = new std::function<F>(fn);
        return result;
    }
#else // NODEJS_ENABLED
    template<typename Fn, typename F>
    static Slot fromF(const std::function<F> & fn,
                      Operations ops = FunctionOps<Fn>::ops)
    {

        Slot result;
        if (!fn) return result;
        result.fntype = STD_FN;
        result.ops = ops;
        result.fn = new std::function<F>(fn);
        return result;
    }
#endif // NODEJS_ENABLED

    // Initialize from a std::function where the function type and the
    // called type are identical
#if NODEJS_ENABLED
    template<typename Fn, typename F>
    static Slot fromF(F fn,
                      Operations ops = FunctionOps<Fn>::ops,
                      JS::JSOperations jsops = JS::getOps(typeid(Fn)))
    {
        Slot result;
        //if (!fn) return result;
        result.fntype = STD_FN;
        result.ops = ops;
        result.jsops = jsops;
        result.fn = new std::function<Fn>(fn);
        return result;
    }
#else // NODEJS_ENABLED
    template<typename Fn, typename F>
    static Slot fromF(F fn,
                      Operations ops = FunctionOps<Fn>::ops)
    {
        Slot result;
        //if (!fn)< return result;
        result.fntype = STD_FN;
        result.ops = ops;
        result.fn = new std::function<Fn>(fn);
        return result;
    }
#endif // NODEJS_ENABLED

#if NODEJS_ENABLED
    template<typename Fn>
    Slot(const std::function<Fn> & fn,
         Operations ops = FunctionOps<Fn>::ops,
         JS::JSOperations jsops = JS::getOps(typeid(Fn)))
        : fn(new std::function<Fn>(fn)), ops(ops), jsops(jsops), fntype(STD_FN)
    {
        if (!fn) {
            Slot new_me;
            swap(new_me);
        }
    }
#else // NODEJS_ENABLED
    template<typename Fn>
    Slot(const std::function<Fn> & fn,
         Operations ops = FunctionOps<Fn>::ops)
        : fn(new std::function<Fn>(fn)), ops(ops), fntype(STD_FN)
    {
        if (!fn) {
            Slot new_me;
            swap(new_me);
        }
    }
#endif // NODEJS_ENABLED

#if NODEJS_ENABLED
    /** Initialize from a Javascript function. */
    Slot(const v8::Handle<v8::Function> & fn);

    /** Initialize from a Javascript value that must be convertible to a function. */
    Slot(const v8::Handle<v8::Value> & fn);
#endif // NODEJS_ENABLED

    ~Slot();

    /** Print a string representation giving information about the slot. */
    std::string print() const;

    /** Is it empty? */
    bool isEmpty() const { return fntype == EMPTY; }

    /** Call from C++, knowing exactly what kinds of parameters there are. */
    template<typename CallAs, typename... Args>
    typename std::function<CallAs>::result_type
    call(Args... args) const
    {
#if NODEJS_ENABLED
        if (!inJsContext())
            throw ML::Exception("callback outside JS context");
#endif // NODEJS_ENABLED
        return as<CallAs>()(args...);
    }

#if NODEJS_ENABLED
    /** Call from Javascript, unpacking the parameters as we go and wrapping
        up the return value.
    */
    v8::Handle<v8::Value> call(const v8::Arguments & args) const;
    v8::Handle<v8::Value> call(const v8::Handle<v8::Object> & This,
                               int argc, v8::Handle<v8::Value> argv[]) const;

    /** Convert directly into a JS function.  NOTE: this is slow; due to
        v8 limitations we need to actually parse a JS file each time.

        If it was already a JS function, then that function is simply
        returned.
    */
    v8::Local<v8::Function> toJsFunction() const;
#endif // NODEJS_ENABLED

    /** Return the type info node of the function type.  Will return the
        typeinfo node of the v8 function if it's a JS value.
    */
    const std::type_info & type() const;

    /** Return a std function object that will synchronously call the
        given callback.
    */
#if NODEJS_ENABLED
    template<typename Fn>
    std::function<Fn> as(JS::JSOperations jsops = 0)
        const
    {
        switch (fntype) {
        case EMPTY:
            return std::function<Fn>();
            //throw ML::Exception("can't convert empty notification");
        case STD_FN:
            if (typeid(Fn) != type())
                throw ML::Exception("couldn't convert function of type "
                                    + ML::demangle(type()) + " to type "
                                    + ML::type_name<Fn>());

            ExcAssert(fn != nullptr);
            return *(std::function<Fn> *) fn;

        case JS: {
            if (!inJsContext())
                throw ML::Exception("callback outside JS context");

            if (!jsops)
                jsops = JS::getOps(typeid(Fn));

            JS::JSAsStdFn op = (JS::JSAsStdFn)jsops;

            std::function<Fn> result;
            v8::Handle<v8::Object> * This = 0;

            op(1, *jsfn, *This, &result);

            return result;
        }
        default:
            throw ML::Exception("unknown operation type");
        }
    }
#else // NODEJS_ENABLED
    template<typename Fn>
    std::function<Fn> as()
        const
    {
        switch (fntype) {
        case EMPTY:
            return std::function<Fn>();
            //throw ML::Exception("can't convert empty notification");
        case STD_FN:
            if (typeid(Fn) != type())
                throw ML::Exception("couldn't convert function of type "
                                    + ML::demangle(type()) + " to type "
                                    + ML::type_name<Fn>());

            ExcAssert(fn != nullptr);
            return *(std::function<Fn> *) fn;

        default:
            throw ML::Exception("unknown operation type");
        }
    }
#endif // NODEJS_ENABLED

    /** Implicit conversion to std::function<x> */
    template<typename Fn>
    operator std::function<Fn> () const
    {
        return as<Fn>();
    }

private:
    union {
        // std::function contents
        struct {
            void * fn;
            Operations ops;
#if NODEJS_ENABLED
            JS::JSOperations jsops;
#endif // NODEJS_ENABLED
        };

#if NODEJS_ENABLED
        // JS function contents
        struct {
            v8::Persistent<v8::Function> * jsfn;
        };
#endif // NODEJS_ENABLED
    };

    /// The kind of object that this slot refers to
    enum FnType {
        EMPTY,   ///< No function there
        STD_FN,  ///< Wrapping a std::function
        JS       ///< Wrapping a JS function
    };

    FnType fntype;  // TODO: find a way to do this without a member

    /** Free all memory associated with this */
    void free();
};

#if NODEJS_ENABLED
template<typename Fn, typename F>
Slot slot(const F & fn,
          Operations ops = FunctionOps<Fn>::ops,
          JS::JSOperations jsops = JS::getOps(typeid(Fn)))
{
    return Slot::fromF<Fn>(std::function<Fn>(fn), ops, jsops);
}
#else // NODEJS_ENABLED
template<typename Fn, typename F>
Slot slot(const F & fn,
          Operations ops = FunctionOps<Fn>::ops)
{
    return Slot::fromF<Fn>(std::function<Fn>(fn), ops);
}
#endif // NODEJS_ENABLED

template<typename Fn>
struct SlotT : public Slot {

    SlotT()
    {
    }

    SlotT(const Slot & slot)
        : Slot(slot)
    {
    }

#if NODEJS_ENABLED
    SlotT(const std::function<Fn> & fn,
         Operations ops = FunctionOps<Fn>::ops,
         JS::JSOperations jsops = JS::getOps(typeid(Fn)))
        : Slot(fn, ops, jsops)
    {
    }

    /** Initialize from a Javascript function. */
    SlotT(const v8::Handle<v8::Function> & fn)
        : Slot(fn)
    {
    }

    /** Initialize from a Javascript value that must be convertible to a
        function. */
    SlotT(const v8::Handle<v8::Value> & fn)
        : Slot(fn)
    {
    }
#else // NODEJS_ENABLED
    SlotT(const std::function<Fn> & fn,
         Operations ops = FunctionOps<Fn>::ops)
        : Slot(fn, ops)
    {
    }
#endif // NODEJS_ENABLED

    /** Print a string representation giving information about the slot. */
    std::string print() const;

    /** Call from C++, knowing exactly what kinds of parameters there are. */
    template<typename... Args>
    typename std::function<Fn>::result_type
    call(Args... args) const
    {
        return toStd()(args...);
    }

    template<typename... Args>
    typename std::function<Fn>::result_type
    operator () (Args... args) const
    {
        return call(args...);
    }

    using Slot::call;

    /** Return a std function object that will synchronously call the
        given callback.
    */
#if NODEJS_ENABLED
    std::function<Fn> toStd(JS::JSOperations jsops = 0)
        const
    {
        return Slot::as<Fn>(jsops);
    }
#else // NODEJS_ENABLED
    std::function<Fn> toStd()
        const
    {
        return Slot::as<Fn>();
    }
#endif // NODEJS_ENABLED

    /** Implicit conversion to std::function<x> */
    operator std::function<Fn> () const
    {
        return as<Fn>();
    }
};

#if NODEJS_ENABLED
namespace JS {

struct JSValue;

Slot from_js(const JSValue &, Slot * = 0);

template<typename Fn>
SlotT<Fn> from_js(const JSValue & val, SlotT<Fn> * = 0)
{
    return SlotT<Fn>(from_js(val, (Slot *)0));
}

template<typename Fn>
std::function<Fn> from_js(const JSValue & val, std::function<Fn> * = 0)
{
    return SlotT<Fn>(from_js(val, (Slot *)0)).toStd();
}

template<typename Fn>
std::function<Fn> from_js_ref(const JSValue & val, std::function<Fn> * = 0)
{
    return SlotT<Fn>(from_js(val, (Slot *)0)).toStd();
}

void to_js(JSValue & val, const Slot & slot);

template<typename Fn>
void to_js(JSValue & val, const SlotT<Fn> & slot)
{
    return to_js(val, (const Slot &)slot);
}

} // namespace JS
#endif // NODEJS_ENABLED

} // namespace Datacratic


text:
package org.apache.flink.runtime.io.network.api.reader;

import org.apache.flink.core.io.IOReadableWritable;
import org.apache.flink.runtime.io.network.partition.consumer.InputGate;

import java.io.IOException;

/**
 * Implementation of the record-oriented reader for mutable record types.
 *
 * @param <T> The type of the record that is read.
 */
public class MutableRecordReader<T extends IOReadableWritable> extends AbstractRecordReader<T> implements MutableReader<T> {

	/**
	 * Creates a new MutableRecordReader that de-serializes records from the given input gate and
	 * can spill partial records to disk, if they grow large.
	 *
	 * @param inputGate The input gate to read from.
	 * @param tmpDirectories The temp directories. USed for spilling if the reader concurrently
	 *                       reconstructs multiple large records.
	 */
	public MutableRecordReader(InputGate inputGate, String[] tmpDirectories) {
		super(inputGate, tmpDirectories);
	}

	@Override
	public boolean next(final T target) throws IOException, InterruptedException {
		return getNextRecord(target);
	}

	@Override
	public void clearBuffers() {
		super.clearBuffers();
	}
}


text:
Use IBM Bluemix services to store data from a web form in a NoSQL database

## About this application

This application builds on the basic node.js app created by Bluemix. It
uses Bootstrap to present a responsive web form that lets a user register
for a webinar. When the user clicks the *Submit* button, the node application
takes that data and sends it to the database.

This is a Cloud Foundry application that uses the NPM `cloudant` package to
interact with the database directly. There are two other versions: one creates
a Docker image from the application, and the other handles Cloudant database
access through a microservice hosted in the OpenWhisk serverless environment.

## Prerequisites

You need to have the following tools installed:

* A git client from [https://git-scm.com/downloads](https://git-scm.com/downloads)
* The latest version of node.js and npm from [https://nodejs.org](https://nodejs.org)
(npm is included when you install node)
* The Cloud Foundry command-line utility from [https://docs.cloudfoundry.org/cf-cli/](https://docs.cloudfoundry.org/cf-cli/)
* The Bluemix command-line utility from [https:clis.ng.bluemix.net](clis.ng.bluemix.net)

Once you've got everything installed, you should be able to run the `git`,
`node`, `npm`, `cf`, and `bx` commands with the `--version` option. You should
see something like this:

```
doug@dougs-mbp:~ $ git --version
git version 2.10.1 (Apple Git-78)
doug@dougs-mbp:~ $ node --version
v6.10.3
doug@dougs-mbp:~ $ npm --version
5.0.0
doug@dougs-mbp:~ $ cf --version
cf version 6.28.0+9e024bdbd.2017-06-27
doug@dougs-mbp:~ $ bx --version
bx version 0.5.5+87df0e64-2017-07-03T06:01:06+00:00
```

Don't worry about whether the version numbers match what you see here. As long
as you have a recent version of all the tools, everything should work just
fine.

## Getting started

Before you go any further, run `cf login` and `bx login`. This ensures that
you're connected to your Bluemix account as you go forward.

After cloning or forking the repo, you'll need to deploy the code to your
Bluemix account. Go to the directory with the code and edit the `manifest.yml`
file. You'll need to replace the `name:` and `host:` fields with a name that's
unique across all of Bluemix, so be creative. (_Note:_ Technically the
`name` and `host` fields don't have to be the same, but it's simpler that way.)


text:
from django.shortcuts import render

def page_not_found(request):
    '''404页面'''
    return render(request, 'errors/404.html')

def server_error(request):
    '''500页面'''
    return render(request, 'errors/500.html')


text:
using Facebook;
using Facebook.Client;
using DrumbleApp.Shared.Entities;
using DrumbleApp.Shared.ValueObjects;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace DrumbleApp.Shared.Infrastructure.Helpers
{
    public static class Facebook
    {
        public static FacebookSessionClient FacebookSessionClient = new FacebookSessionClient(DrumbleApp.Shared.Infrastructure.Constants.Constants.FacebookAppId);

        public static async Task<FacebookSession> Authenticate()
        {
            return await FacebookSessionClient.LoginAsync("user_about_me");
        }
    }
}


text:
using System.Collections.Generic;
using Orchard.Environment.Extensions.Models;
using Orchard.Security.Permissions;

namespace Orchard.Core.Navigation {
    public class Permissions : IPermissionProvider {
        public static readonly Permission ManageMenus = new Permission { Name = "ManageMenus", Description = "Manage all menus" };

        public virtual Feature Feature { get; set; }

        public IEnumerable<Permission> GetPermissions() {
            return new[] {
                ManageMenus
             };
        }

        public IEnumerable<PermissionStereotype> GetDefaultStereotypes() {
            return new[] {
                new PermissionStereotype {
                    Name = "Administrator",
                    Permissions = new[] {ManageMenus}
                }
            };
        }
    }
}


text:
@implementation UIImage (MMAdditions)

- (NSData *)mm_dataSmallerThan:(NSUInteger)dataLength {
    NSData *data = UIImageJPEGRepresentation(self, 1.0);
    while (data.length > dataLength) {
        UIImage *image = [UIImage imageWithData:data];
        data = UIImageJPEGRepresentation(image, 0.7);
    }
    return data;
}

- (NSData *)mm_dataForUpload {
    return [self mm_dataSmallerThan:1024 * 1000];
}

@end


text:
<?php

namespace Laravel\Dusk;

/**
 * This is the dotenv class.
 *
 * It's responsible for loading a `.env` file in the given directory and
 * setting the environment vars.
 */
class Dotenv
{
    /**
     * The file path.
     *
     * @var string
     */
    protected $filePath;

    /**
     * The loader instance.
     *
     * @var \Laravel\Dusk\Loader
     */
    protected $loader;

    /**
     * Create a new dotenv instance.
     *
     * @param string $path
     * @param string $file
     */
    public function __construct($path, $file = '.env')
    {
        $this->filePath = $this->getFilePath($path, $file);
        $this->loader = new Loader($this->filePath, true);
    }

    /**
     * Load environment file in given directory.
     *
     * @throws \Laravel\Dusk\Exception\InvalidFileException
     * @throws \Laravel\Dusk\Exception\InvalidPathException
     *
     * @return array
     */
    public function load()
    {
        return $this->loadData();
    }

    /**
     * Load environment file in given directory.
     *
     * @throws \Laravel\Dusk\Exception\InvalidFileException
     * @throws \Laravel\Dusk\Exception\InvalidPathException
     *
     * @return array
     */
    public function overload()
    {
        return $this->loadData(true);
    }

    /**
     * Returns the full path to the file.
     *
     * @param string $path
     * @param string $file
     *
     * @return string
     */
    protected function getFilePath($path, $file)
    {
        if (! is_string($file)) {
            $file = '.env';
        }

        return rtrim($path, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.$file;
    }

    /**
     * Actually load the data.
     *
     * @param bool $overload
     *
     * @throws \Laravel\Dusk\Exception\InvalidFileException
     * @throws \Laravel\Dusk\Exception\InvalidPathException
     *
     * @return array
     */
    protected function loadData($overload = false)
    {
        $this->loader = new Loader($this->filePath, ! $overload);

        return $this->loader->load();
    }

    /**
     * Required ensures that the specified variables exist, and returns a new validator object.
     *
     * @param string|string[] $variable
     *
     * @throws \Laravel\Dusk\Exception\ValidationException
     * @throws \Laravel\Dusk\Exception\InvalidCallbackException
     *
     * @return \Laravel\Dusk\Validator
     */
    public function required($variable)
    {
        return new Validator((array) $variable, $this->loader);
    }
}


text:
module MagLev
  module ClassLogger
    def logger
      @logger ||= ClassLogger::Logger.new(self)
    end

    def logger_name
      if respond_to? :name
        name
      else
        ''
      end
    end

    protected

    # easy way to log the return value of code
    def log_info(result = nil)
      result ||= yield
      logger.debug "#{caller_locations(1,1)[0].label}: #{result.inspect}"
      result
    end

    # easy way to log the return value of code
    def log_info(result = nil)
      result ||= yield
      logger.info "#{caller_locations(1,1)[0].label}: #{result.inspect}"
      result
    end

    class Logger
      def initialize(instance)
        @instance = instance
      end

      [:debug, :info, :warn, :error, :fatal].each do |level|
        define_method level do |*args, &block|
          log(level, *args, &block)
        end
      end

      if defined?(Rails) and Rails.respond_to?(:logger)
        def log(level, *args, &block)
          if block_given?
            Rails.logger.send level do
              format(block.call)
            end
          else
            Rails.logger.send level, format(*args)
          end
        end
      else
        def log(method, *args, &block)
          if block_given?
            puts format(block.call)
          else
            puts format(*args)
          end
        end
      end

      def id
        if @instance.respond_to? :id
          "[#{@instance.id}] - "
        end
      end

      def format(msg, *args)
        msg = "#{@instance.class.name} #{id}#{@instance.logger_name}: #{msg}"
        [msg, *args].map(&:to_s).join(' | ')
      end

      def report(type, *args)
        begin
          args = args.compact
          if respond_to?(type)
            send(type, *args)
          end

          hash = args.find {|a| a.is_a? Hash}
          args << hash = {} unless hash
          hash[:logger_name] = @instance.logger_name
          # hash[@instance.to_s] = @instance # causes stack too deep errors in some cases
          EventReporter.send(type, *args)
        rescue => ex
          MagLev.logger.warn("Failed to report error:")
          MagLev.logger.error(ex)
        end
      end
    end
  end
end


text:
enum {
	destructengine = 2,
	destructdefault = 6,
	destructwreck = 7,
	destructtree = 3,
	destructtent = 4,
	stabilizedinaxisx = 1,
	stabilizedinaxesxyz = 4,
	stabilizedinaxisy = 2,
	stabilizedinaxesboth = 3,
	destructno = 0,
	stabilizedinaxesnone = 0,
	destructman = 5,
	destructbuilding = 1
};

class CfgPatches
{
	class A3_LanguageMissions_F
	{
		author = "$STR_A3_Bohemia_Interactive";
		name = "Arma 3 Alpha - Mission Texts and Translations";
		url = "https://www.arma3.com";
		requiredAddons[] = {"A3_Data_F"};
		requiredVersion = 0.1;
		units[] = {};
		weapons[] = {};
	};
};


text:
class QMLImageProvider : public QQuickImageProvider{
public:
	QMLImageProvider(QQmlImageProviderBase::ImageType);
	~QMLImageProvider();

	//static QMLImageProvider* instance();

	virtual QImage requestImage(const QString &id, QSize *size, const QSize &requestedSize);
	virtual QPixmap requestPixmap(const QString &id, QSize *size, const QSize &requestedSize);
};

#endif


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

package org.camunda.bpm.engine.impl.dmn.cmd;

import static org.camunda.bpm.engine.impl.util.DecisionTableUtil.evaluateDecisionTable;
import static org.camunda.bpm.engine.impl.util.EnsureUtil.ensureNotNull;

import java.util.Map;

import org.camunda.bpm.dmn.engine.DmnDecisionTableResult;
import org.camunda.bpm.engine.ProcessEngineException;
import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.camunda.bpm.engine.impl.dmn.entity.repository.DecisionDefinitionEntity;
import org.camunda.bpm.engine.impl.interceptor.Command;
import org.camunda.bpm.engine.impl.interceptor.CommandContext;
import org.camunda.bpm.engine.impl.persistence.deploy.DeploymentCache;
import org.camunda.bpm.engine.impl.persistence.entity.AuthorizationManager;
import org.camunda.bpm.engine.repository.DecisionDefinition;
import org.camunda.bpm.engine.variable.VariableMap;
import org.camunda.bpm.engine.variable.Variables;

/**
 * Evaluates the decision with the given id.
 *
 * @author Philipp Ossler
 */
public class EvaluateDecisionByIdCmd implements Command<DmnDecisionTableResult> {

  protected String decisionDefinitionId;
  protected VariableMap variables;

  public EvaluateDecisionByIdCmd(String decisionDefinitionId, Map<String, Object> variables) {
    this.decisionDefinitionId = decisionDefinitionId;
    this.variables = Variables.fromMap(variables);
  }

  @Override
  public DmnDecisionTableResult execute(CommandContext commandContext) {
    ensureNotNull("decision definition id is null", "processDefinitionId", decisionDefinitionId);

    ProcessEngineConfigurationImpl processEngineConfiguration = commandContext.getProcessEngineConfiguration();
    DeploymentCache deploymentCache = processEngineConfiguration.getDeploymentCache();

    DecisionDefinitionEntity decisionDefinition = deploymentCache.findDeployedDecisionDefinitionById(decisionDefinitionId);

    // check authorization
    AuthorizationManager authorizationManager = commandContext.getAuthorizationManager();
    authorizationManager.checkEvaluateDecision(decisionDefinition.getKey());

    return doEvaluateDecision(decisionDefinition, variables);
  }

  protected DmnDecisionTableResult doEvaluateDecision(DecisionDefinition decisionDefinition, VariableMap variables) {
    try {
      return evaluateDecisionTable(decisionDefinition, variables);
    }
    catch (Exception e) {
      throw new ProcessEngineException("Exception while evaluating decision with id '"+decisionDefinitionId+"'", e);
    }
  }

}


text:
package model.admin;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;

@Entity
public class FormField {

  public static final String FIELD = "field";
  public static final String DISPLAY_NAME = "displayName";
  public static final String DEFAULT_DISPLAY_NAME = "defaultDisplayName";
  public static final String DEFAULT_VALUE = "defaultValue";

  public static final String ALLOW_CHANGE_HIDDEN = "allowChangeHidden";
  public static final String HIDDEN = "hidden";

  public static final String ALLOW_CHANGE_REQUIRED = "allowChangeRequired";
  public static final String REQUIRED = "required";

  public static final String IS_AUTO_GENERATABLE = "isAutoGeneratable";
  public static final String AUTO_GENERATE = "autoGenerate";
  public static final String IS_TIME_FIELD = "isTimeField";
  public static final String USE_CURRENT_TIME = "useCurrentTime";

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  @Column(nullable=false, updatable=false, insertable=false)
  private Long id;

  @Column(length=30)
  private String form;

  @Column(length=30)
  private String field;

  /**
   * User can override default display name with display name.
   */
  @Column(length=60)
  private String displayName;

  @Column(length=60)
  private String defaultDisplayName;

  @Column
  private Integer maxLength;

  @Lob
  private String defaultValue;

  /**
   * Fields can be hidden by setting this parameter to false.
   * We could also have a shown field instead of hidden field which would store
   * true for any field that is visible on the form. But that would not have made any difference.
   * Right now we check if the field value is not true. In this case I prefer hidden field instead
   * of shown field because by some programming mistake if we ended up storing NULL in the hidden
   * field then the field would still show up in the UI (a somewhat tolerable mistake from a user's
   * point of view) rather than not show up at all (very annoying for users).
   * Of course in the first place such an error should be allowed in the code.
   */
  private Boolean hidden;

  private Boolean isHidable;

  private Boolean isRequired;

  private Boolean canBeOptional;

  private Boolean autoGenerate;

  private Boolean isAutoGeneratable;

  private Boolean useCurrentTime;

  private Boolean isTimeField;

  public Long getId() {
    return id;
  }

  public String getForm() {
    return form;
  }

  public String getField() {
    return field;
  }

  public String getDisplayName() {
    if (displayName == null || displayName.trim().equals(""))
      return getDefaultDisplayName();
    return displayName;
  }

  public String getDefaultDisplayName() {
    return defaultDisplayName;
  }

  public String getDefaultValue() {
    return defaultValue;
  }

  public Boolean getHidden() {
    return hidden;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public void setForm(String form) {
    this.form = form;
  }

  public void setField(String field) {
    this.field = field;
  }

  public void setDisplayName(String displayName) {
    this.displayName = displayName;
  }

  public void setDefaultDisplayName(String defaultDisplayName) {
    this.defaultDisplayName = defaultDisplayName;
  }

  public void setDefaultValue(String defaultValue) {
    this.defaultValue = defaultValue;
  }

  public void setHidden(Boolean hidden) {
    this.hidden = hidden;
  }

  public void copy(FormField formField) {
    this.displayName = formField.displayName;
    this.defaultValue = formField.defaultValue;
    if (this.isHidable)
      this.hidden = formField.hidden;
    if (this.canBeOptional)
      this.isRequired = formField.isRequired;
    if (this.isAutoGeneratable)
      this.autoGenerate = formField.autoGenerate;
    if (this.isTimeField)
      this.useCurrentTime = formField.useCurrentTime;
    this.maxLength = formField.maxLength;
  }

  public Boolean getIsRequired() {
    return isRequired;
  }

  public void setIsRequired(Boolean isRequired) {
    this.isRequired = isRequired;
  }

  public Boolean getAutoGenerate() {
    return autoGenerate;
  }

  public void setAutoGenerate(Boolean autoGenerate) {
    this.autoGenerate = autoGenerate;
  }

  public Integer getMaxLength() {
    return maxLength;
  }

  public void setMaxLength(Integer maxLength) {
    this.maxLength = maxLength;
  }

  public Boolean getIsAutoGeneratable() {
    return isAutoGeneratable;
  }

  public void setIsAutoGeneratable(Boolean isAutoGeneratable) {
    this.isAutoGeneratable = isAutoGeneratable;
  }

  public Boolean getIsHidable() {
    return isHidable;
  }

  public void setIsHidable(Boolean isHidable) {
    this.isHidable = isHidable;
  }

  public Boolean getCanBeOptional() {
    return canBeOptional;
  }

  public void setCanBeOptional(Boolean canBeOptional) {
    this.canBeOptional = canBeOptional;
  }

  public Boolean getUseCurrentTime() {
    return useCurrentTime;
  }

  public void setUseCurrentTime(Boolean useCurrentTime) {
    this.useCurrentTime = useCurrentTime;
  }

  public Boolean getIsTimeField() {
    return isTimeField;
  }

  public void setIsTimeField(Boolean isTimeField) {
    this.isTimeField = isTimeField;
  }
}


text:
Komust
======

Komust is a module for [Kohana](http://github.com/kohana/), that integrates [Mustache](http://mustache.github.com) templates (using [mustache.php](http://github.com/bobthecow/mustache.php) implementation.

Examples
--------

There are 2 ways to use Komust:

Instead of extending the default Kohana Controller, extend Controller_Komust.

```php
<?php
class Controller_Welcome extends Controller_Komust {
	public function action_index()
	{
		$this->layout = 'main';
		$this->response->body($this->render('welcome/index',array('name' => 'World')));
	}
}
```

The render method in Controller_Komust, renders welcome/index with the provided data and adds the result back to the data as property/array element "content", so the rendered view can be accessed by the layout template by {{{content}}}.

Now, the only thing remaining is to create the layout and the actual view templates. Layout template (layout.mustache) could be something like:

```html+jinja
<!DOCTYPE html>
<html>
	<head>
	</head>
	<body>
		{{{content}}}
	</body>
</html>
```

And welcome/index(.mustache) could look like:
```html+jinja
<div>
	Hello {{name}}
</div>
```

That's it! Of course, in real world it is more efficient and the controller code is more readable if you use ViewModels. Let's refactor our code to do so:

```php
<?php
class Controller_Welcome extends Controller_Komust {
	public function action_index()
	{
		$this->layout = 'main';
		$this->response->body($this->render('welcome/index', View_Komust::factory('Welcome/Index')));
	}
}
```

Now, we can add the data we need to be available in our template in the View_Komust class. Let's see the class' contents:

```php
<?php
class View_Welcome_Index {
	public $name = 'World';
}
```

Our template remains the same, so no changes are needed there. That's it! The good thing about ViewModels is that you can add methods which are also available in your templates!

The second approach one may choose is to create a regular controller and render a template (without all the automagic) by using the render method of the Mustache_Engine:

```php
<?php
class Controller_Welcome extends Controller {
	public function action_index()
	{
		$mustache = Komust::factory()->engine();
		$this->response->body($mustache->render('{{message}}',array('message' => 'Hello World!')));
	}
}
```

The default factory call uses the default settings of Mustache_Engine (string loader), but you can customize that to use filesystem loader which can accomodate more complex needs. The factory method accepts a $config parameter, either an array (which holds the configuration settings) or a string, which is the config group of the komust.php config file (you can add your own configurations there). If $config is not provided, a Mustache_Engine instance with the default settings is created.


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

#if !PORTABLE
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using NUnit.Compatibility;
using ActualValueDelegate = NUnit.Framework.Constraints.ActualValueDelegate<object>;

namespace NUnit.Framework.Constraints
{
    [TestFixture, Parallelizable(ParallelScope.None)]
    public class DelayedConstraintTests : ConstraintTestBase
    {
        private const int DELAY = 100;
        private const int AFTER = 300;
        private const int POLLING = 50;
        private const int MIN = AFTER - 10;

        private static bool boolValue;
        private static List<int> list;
        private static string statusString;

        [SetUp]
        public void SetUp()
        {
            theConstraint = new DelayedConstraint(new EqualConstraint(true), 500);
            expectedDescription = "True after 500 millisecond delay";
            stringRepresentation = "<after 500 <equal True>>";

            boolValue = false;
            list = new List<int>();
            statusString = null;
            //SetValueTrueAfterDelay(300);
        }

        static object[] SuccessData = new object[] { true };
        static object[] FailureData = new object[] {
            new TestCaseData( false, "False" ),
            new TestCaseData( 0, "0" ),
            new TestCaseData( null, "null" ) };

        static ActualValueDelegate DelegateReturningValue;
        static ActualValueDelegate DelegateReturningFalse;
        static ActualValueDelegate DelegateReturningZero;

        static ActualValueDelegate<object>[] SuccessDelegates;
        static ActualValueDelegate<object>[] FailureDelegates;

        // Initialize static fields that are sensitive to order of initialization.
        // Most compilers would probably intialize these in lexical order but it
        // may not be guaranteed in all cases so we do it directly.
        static DelayedConstraintTests()
        {
            DelegateReturningValue = new ActualValueDelegate(MethodReturningValue);
            DelegateReturningFalse = new ActualValueDelegate(MethodReturningFalse);
            DelegateReturningZero = new ActualValueDelegate(MethodReturningZero);

            SuccessDelegates = new ActualValueDelegate<object>[] { DelegateReturningValue };
            FailureDelegates = new ActualValueDelegate<object>[] { DelegateReturningFalse, DelegateReturningZero };
        }

        [Test, TestCaseSource("SuccessDelegates")]
        public void SucceedsWithGoodDelegates(ActualValueDelegate<object> del)
        {
            SetValuesAfterDelay(DELAY);
            Assert.That(theConstraint.ApplyTo(del).IsSuccess);
        }

        [Test, TestCaseSource("FailureDelegates")]
        public void FailsWithBadDelegates(ActualValueDelegate<object> del)
        {
            Assert.IsFalse(theConstraint.ApplyTo(del).IsSuccess);
        }

        [Test]
        public void SimpleTest()
        {
            SetValuesAfterDelay(DELAY);
            Assert.That(DelegateReturningValue, new DelayedConstraint(new EqualConstraint(true), AFTER, POLLING));
        }

        [Test]
        public void SimpleTestUsingBoolean()
        {
            SetValuesAfterDelay(DELAY);
            Assert.That(() => boolValue, new DelayedConstraint(new EqualConstraint(true), AFTER, POLLING));
        }

        [Test]
        public void ThatOverload_ZeroDelayIsAllowed()
        {
            Assert.That(DelegateReturningZero, new DelayedConstraint(new EqualConstraint(0), 0));
        }

        [Test]
        public void ThatOverload_DoesNotAcceptNegativeDelayValues()
        {
            Assert.Throws<ArgumentException>(
                () => Assert.That(DelegateReturningZero, new DelayedConstraint(new EqualConstraint(0), -1)));
        }

        [Test]
        public void CanTestContentsOfList()
        {
            SetValuesAfterDelay(1);
            Assert.That(list, Has.Count.EqualTo(1).After(AFTER, POLLING));
        }

        [Test]
        public void CanTestContentsOfDelegateReturningList()
        {
            SetValuesAfterDelay(1);
            Assert.That(() => list, Has.Count.EqualTo(1).After(AFTER, POLLING));
        }

        [Test]
        public void CanTestInitiallyNullDelegate()
        {
            SetValuesAfterDelay(DELAY);
            Assert.That(() => statusString, Is.Not.Null.And.Length.GreaterThan(0).After(AFTER, POLLING));
        }

        [Test]
        public void ThatBlockingDelegateWhichSucceedsWithoutPolling_ReturnsAfterDelay()
        {
            var watch = new Stopwatch();
            watch.Start();

            Assert.That(() =>
            {
                Delay(DELAY);
                return true;
            }, Is.True.After(AFTER));

            watch.Stop();
            Assert.That(watch.ElapsedMilliseconds, Is.GreaterThanOrEqualTo(MIN));
        }

        [Test]
        public void ThatBlockingDelegateWhichSucceedsWithPolling_ReturnsEarly()
        {
            var watch = new Stopwatch();
            watch.Start();

            Assert.That(() =>
            {
                Delay(DELAY);
                return true;
            }, Is.True.After(AFTER, POLLING));

            watch.Stop();
            // TODO: This failed intermittently, esp. on .NET 4.0. Find another way to test or wait till we have warning errors.
            //Assert.That(watch.ElapsedMilliseconds, Is.LessThan(AFTER));
        }

        [Test]
        public void ThatBlockingDelegateWhichFailsWithoutPolling_FailsAfterDelay()
        {
            var watch = new Stopwatch();
            watch.Start();

            Assert.Throws<AssertionException>(() => Assert.That(() =>
            {
                Delay(DELAY);
                return false;
            }, Is.True.After(AFTER)));

            watch.Stop();
            Assert.That(watch.ElapsedMilliseconds, Is.GreaterThanOrEqualTo(MIN));
        }

        [Test]
        public void ThatBlockingDelegateWhichFailsWithPolling_FailsAfterDelay()
        {
            var watch = new Stopwatch();
            watch.Start();

            Assert.Throws<AssertionException>(() => Assert.That(() =>
            {
                Delay(DELAY);
                return false;
            }, Is.True.After(AFTER, POLLING)));

            watch.Stop();
            Assert.That(watch.ElapsedMilliseconds, Is.GreaterThanOrEqualTo(MIN));
        }

        [Test]
        public void ThatBlockingDelegateWhichThrowsWithoutPolling_FailsAfterDelay()
        {
            var watch = new Stopwatch();
            watch.Start();

            Assert.Throws<AssertionException>(() => Assert.That(() =>
            {
                Delay(DELAY);
                throw new InvalidOperationException();
            }, Is.True.After(AFTER)));

            watch.Stop();
            Assert.That(watch.ElapsedMilliseconds, Is.GreaterThanOrEqualTo(MIN));
        }

        [Test]
        public void ThatBlockingDelegateWhichThrowsWithPolling_FailsAfterDelay()
        {
            var watch = new Stopwatch();
            watch.Start();

            Assert.Throws<AssertionException>(() => Assert.That(() =>
            {
                Delay(DELAY);
                throw new InvalidOperationException();
            }, Is.True.After(AFTER, POLLING)));

            watch.Stop();
            Assert.That(watch.ElapsedMilliseconds, Is.GreaterThanOrEqualTo(AFTER));
        }

        private static int setValuesDelay;

        private static void MethodReturningVoid() { }

        private static object MethodReturningValue() { return boolValue; }

        private static object MethodReturningFalse() { return false; }

        private static object MethodReturningZero() { return 0; }

        private static AutoResetEvent waitEvent = new AutoResetEvent(false);

        private static void Delay(int delay)
        {
#if SILVERLIGHT
            waitEvent.WaitOne(delay);
#else
            waitEvent.WaitOne(delay, false);
#endif
        }

        private static void MethodSetsValues()
        {
            Delay(setValuesDelay);
            boolValue = true;
            list.Add(1);
            statusString = "Finished";
        }

        private void SetValuesAfterDelay(int delay)
        {
            setValuesDelay = delay;
            Thread thread = new Thread(MethodSetsValues);
            thread.Start();
        }
    }
}
#endif


text:
#include <aws/transcribestreaming/model/LanguageCode.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>

using namespace Aws::Utils;

namespace Aws
{
  namespace TranscribeStreamingService
  {
    namespace Model
    {
      namespace LanguageCodeMapper
      {

        static const int en_US_HASH = HashingUtils::HashString("en-US");
        static const int en_GB_HASH = HashingUtils::HashString("en-GB");
        static const int es_US_HASH = HashingUtils::HashString("es-US");
        static const int fr_CA_HASH = HashingUtils::HashString("fr-CA");
        static const int fr_FR_HASH = HashingUtils::HashString("fr-FR");
        static const int en_AU_HASH = HashingUtils::HashString("en-AU");
        static const int it_IT_HASH = HashingUtils::HashString("it-IT");
        static const int de_DE_HASH = HashingUtils::HashString("de-DE");
        static const int pt_BR_HASH = HashingUtils::HashString("pt-BR");
        static const int ja_JP_HASH = HashingUtils::HashString("ja-JP");
        static const int ko_KR_HASH = HashingUtils::HashString("ko-KR");

        LanguageCode GetLanguageCodeForName(const Aws::String& name)
        {
          int hashCode = HashingUtils::HashString(name.c_str());
          if (hashCode == en_US_HASH)
          {
            return LanguageCode::en_US;
          }
          else if (hashCode == en_GB_HASH)
          {
            return LanguageCode::en_GB;
          }
          else if (hashCode == es_US_HASH)
          {
            return LanguageCode::es_US;
          }
          else if (hashCode == fr_CA_HASH)
          {
            return LanguageCode::fr_CA;
          }
          else if (hashCode == fr_FR_HASH)
          {
            return LanguageCode::fr_FR;
          }
          else if (hashCode == en_AU_HASH)
          {
            return LanguageCode::en_AU;
          }
          else if (hashCode == it_IT_HASH)
          {
            return LanguageCode::it_IT;
          }
          else if (hashCode == de_DE_HASH)
          {
            return LanguageCode::de_DE;
          }
          else if (hashCode == pt_BR_HASH)
          {
            return LanguageCode::pt_BR;
          }
          else if (hashCode == ja_JP_HASH)
          {
            return LanguageCode::ja_JP;
          }
          else if (hashCode == ko_KR_HASH)
          {
            return LanguageCode::ko_KR;
          }
          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
          if(overflowContainer)
          {
            overflowContainer->StoreOverflow(hashCode, name);
            return static_cast<LanguageCode>(hashCode);
          }

          return LanguageCode::NOT_SET;
        }

        Aws::String GetNameForLanguageCode(LanguageCode enumValue)
        {
          switch(enumValue)
          {
          case LanguageCode::en_US:
            return "en-US";
          case LanguageCode::en_GB:
            return "en-GB";
          case LanguageCode::es_US:
            return "es-US";
          case LanguageCode::fr_CA:
            return "fr-CA";
          case LanguageCode::fr_FR:
            return "fr-FR";
          case LanguageCode::en_AU:
            return "en-AU";
          case LanguageCode::it_IT:
            return "it-IT";
          case LanguageCode::de_DE:
            return "de-DE";
          case LanguageCode::pt_BR:
            return "pt-BR";
          case LanguageCode::ja_JP:
            return "ja-JP";
          case LanguageCode::ko_KR:
            return "ko-KR";
          default:
            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
            if(overflowContainer)
            {
              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
            }

            return {};
          }
        }

      } // namespace LanguageCodeMapper
    } // namespace Model
  } // namespace TranscribeStreamingService
} // namespace Aws


text:
package org.sakaiproject.profile2.logic;

import java.util.List;

import org.sakaiproject.profile2.model.ProfilePrivacy;
import org.sakaiproject.profile2.model.WallItem;
import org.sakaiproject.profile2.model.WallItemComment;

/**
 * Logic interface for the Profile2 wall.
 *
 * @author d.b.robinson@lancaster.ac.uk
 */
public interface ProfileWallLogic {

	/**
	 * Notifies a user's connections of an event added to the user's wall.
	 *
	 * Note: the wall logic is currently responsible for timestamping the event,
	 * but we might want to pass the date in this API call instead.
	 *
	 * @param event the event to add.
	 * @param userUuid the ID of the user that created the event.
	 */
	public void addNewEventToWall(String event, String userUuid);

	/**
	 * Notifies a user's connections of a status update added to the user's wall.
	 *
	 * Note: the wall logic is currently responsible for timestamping the status
	 * update, but we might want to pass the date in this API call instead.
	 *
	 * @param status the status to add.
	 * @param userUuid the ID of the user whose status we're posting.
	 */
	public void addNewStatusToWall(String status, String userUuid);

	/**
	 * Adds a new wall item comment.
	 *
	 * @param wallItemComment the wall item comment to add.
	 * @return true if the add is successful and
	 *         false if the add fails.
	 */
	public boolean addNewCommentToWallItem(WallItemComment wallItemComment);

	/**
	 * Posts the specified wall item to the specified user's wall and the
	 * walls of their connections.
	 *
	 * @param userUuid the id of the user whose wall we're posting to.
	 * @param wallItem the wall item to post.
	 */
	public boolean postWallItemToWall(String userUuid, WallItem wallItem);

	/**
	 * Removes the specified wall item.
	 *
	 * @param wallItem the wall item to remove.
	 */
	public boolean removeWallItemFromWall(WallItem wallItem);

	/**
	 * Returns the wall for the specified user. The privacy record will
	 * be looked up.
	 *
	 * @param userUuid the user to query by.
	 * @return the wall for the specified user.
	 */
	public List<WallItem> getWallItemsForUser(String userUuid);

	/**
	 * Returns the wall for the specified user. Privacy settings are used
	 * to determine if the user is allowed to access the requested wall.
	 *
	 * @param userUuid the user to query by.
	 * @param privacy the privacy record for the user.
	 * @return the wall for the specified user.
	 */
	public List<WallItem> getWallItemsForUser(String userUuid, ProfilePrivacy privacy);

	/**
	 * Returns the number of available wall items for the specified user. The
	 * privacy record will be looked up.
	 *
	 * @param userUuid the user to query by.
	 * @return the number of available wall items for the specified user.
	 */
	public int getWallItemsCount(String userUuid);

	/**
	 * Returns the number of available wall items for the specified user.
	 * Privacy settings are used to determine if the user is allowed to access
	 * the requested wall items.
	 *
	 * @param userUuid the user to query by.
	 * @param privacy the privacy record for the user.
	 * @return the number of available wall items for the specified user.
	 */
	public int getWallItemsCount(String userUuid, ProfilePrivacy privacy);

}


text:
module Facts
  module Windows
    class Facterversion
      FACT_NAME = 'facterversion'

      def call_the_resolver
        fact_value = Facter::Resolvers::Facterversion.resolve(:facterversion)

        Facter::ResolvedFact.new(FACT_NAME, fact_value)
      end
    end
  end
end


text:
import base64
import hashlib
import os

from abc import ABCMeta
from abc import abstractmethod
from functools import lru_cache
from .utils import import_string

# Try to import the bcrypt library
# to be used by BCryptPasswordHasher class.
try:
    import bcrypt
except ImportError:
    bcrypt = None

class PasswordHasher(object):
    """
    Password hasher.
    """

    # The algorithm used to crypt the passwords.
    # if it is None, we will take the first password hasher from 'hashers' attribute as the default hasher.
    algorithm = None

    # Hashers supported.
    hashers = [
        'flask_password.hashers.PBKDF2PasswordHasher',
        'flask_password.hashers.BCryptPasswordHasher',
        'flask_password.hashers.MD5PasswordHasher',
        'flask_password.hashers.SHA1PasswordHasher'
    ]

    def __init__(self, app=None):
        self.__hashers = {}

        if app:
            self.init_app(app)

    def init_app(self, app):
        """Loads the configuration from Flask app."""

        self.algorithm = app.config.get('PASSWORD_ALGORITHM')
        self.hashers = app.config.get('PASSWORD_HASHERS', self.hashers)

        for hasher in self.get_hashers():
            hasher.init_app(app)

        if self.algorithm is None:
            hasher = self.get_hashers()[0]
            self.algorithm = hasher.algorithm

    def check_password(self, password, hashed_password):
        """
        Compares one plain text password against a hashed password.
        :param password: A plain text password.
        :type password: str
        :param hashed_password: An hashed password
        :type hashed_password: str
        :return: True if the password are equal; otherwise, false.
        """

        algorithm = self.get_algorithm(hashed_password)
        hasher = self.get_hasher(algorithm)
        return hasher.check_password(password, hashed_password)

    def hash_password(self, password, salt=None, algorithm=None):
        """
        Encrypt a password.
        :param password: A plain text password to be hashed.
        :type password: str
        :param salt: The salt used to encrypt the password.
        :type salt: str
        :param algorithm: The algorithm used to encrypt the password.
        :type algorithm: str
        :return: The hashed password.
        """

        if not algorithm:
            algorithm = self.algorithm

        hasher = self.get_hasher(algorithm)

        if not salt:
            salt = hasher.salt()

        return hasher.hash_password(password, salt)

    @staticmethod
    def get_algorithm(hashed_password):
        """
        Gets the algorithm from the hashed password.
        :param hashed_password: hashed password.
        :type hashed_password: str
        :return: The algorithm extract from the hashed password.
        """
        return hashed_password.split('$', 1)[0]

    def get_hasher(self, algorithm):
        """
        Gets a hasher for the specified algorithm.
        :param algorithm: The algorithm to be found.
        :return: A password hasher or exception.
        """

        hashers = self.get_hashers()

        if algorithm is None:
            return hashers[0]

        for hasher in hashers:
            if hasher.algorithm == algorithm:
                return hasher

        raise ValueError("Unknown password hashing algorithm '%s'. " % algorithm)

    @lru_cache()
    def get_hashers(self):
        """
        Gets all hashers registered.
        :return: A list of hashers.
        """
        hashers = []

        for class_name in self.hashers:
            hasher_cls = import_string(class_name)
            hasher = hasher_cls()
            hashers.append(hasher)

        return hashers

class BasePasswordHasher(metaclass=ABCMeta):
    """
    Base class for the password hashers.
    """

    # Name of algorithm used to encrypt the password.
    algorithm = None

    def init_app(self, app):
        pass

    @abstractmethod
    def check_password(self, password, hashed_password):
        """
        Compares one plain text password against a hashed password.
        :param password: A plain text password.
        :type password: str
        :param hashed_password: An hashed password
        :type hashed_password: str
        :return: True if the password are equal; otherwise, false.
        """
        pass

    @abstractmethod
    def hash_password(self, password, salt):
        """
        Encrypt a password.
        :param password: A plain text password to be hashed.
        :type password: str
        :param salt: The salt used to encrypt the password.
        :type salt: str
        :return: The hashed password.
        """
        pass

    def salt(self):
        """Generate a new salt."""
        return base64.b64encode(os.urandom(16)).decode()

class BCryptPasswordHasher(BasePasswordHasher):
    """
    BCrypt Password hashing.
    This hashing is strong and recommended.
    """

    algorithm = 'bcrypt'
    rounds = 12

    def init_app(self, app):
        """Loads the configuration from Flask app."""

        rounds = app.config.get('BCRYPT_ROUNDS')
        if rounds:
            self.rounds = rounds

    def check_password(self, password, hashed_password):
        """
        Compares one plain text password against a bcrypt hashed password.
        :param password: A plain text password.
        :type password: str
        :param hashed_password: An hashed password
        :type hashed_password: str
        :return: True if the password are equal; otherwise, false.
        """

        self.__check_bcrypt()

        algorithm, data = hashed_password.split('$', 1)

        password = password.encode()
        hashed_password = data.encode()

        return bcrypt.checkpw(password, hashed_password)

    def hash_password(self, password, salt):
        """
        Encrypt a password using bcrypt algorithm.
        :param password: A plain text password to be hashed.
        :type password: str
        :param salt: The salt used to encrypt the password.
        :type salt: str
        :return: The hashed password.
        """

        self.__check_bcrypt()

        password = password.encode()

        data = bcrypt.hashpw(password, salt)
        return "%s$%s" % (self.algorithm, data)

    def salt(self, rounds=None):
        """Generate a new salt."""

        self.__check_bcrypt()

        if not rounds:
            rounds = self.rounds
        return bcrypt.gensalt(rounds)

    @staticmethod
    def __check_bcrypt():
        """Checks whether bcrypt library has been loaded."""
        if not bcrypt:
            raise ImportError('bcrypt library is not installed. (pip install py-bcrypt)')

class PBKDF2PasswordHasher(BasePasswordHasher):
    """
    PBKDF2 Password hashing.
    This hashing is strong and recommended.
    """

    algorithm = "pbkdf2"
    iterations = 24000
    digest = hashlib.sha256

    def init_app(self, app):
        """Loads the configuration from Flask app."""

        iterations = app.config.get('PBKDF2_ITERATIONS')
        if iterations:
            self.iterations = iterations

    def check_password(self, password, hashed_password):
        """
        Compares one plain text password against a PBKDF2 hashed password.
        :param password: A plain text password.
        :type password: str
        :param hashed_password: An hashed password
        :type hashed_password: str
        :return: True if the password are equal; otherwise, false.
        """

        algorithm, iterations, salt, hash = hashed_password.split('$', 3)
        return self.hash_password(password, salt, int(iterations)) == hashed_password

    def hash_password(self, password, salt, iterations=None):
        """
        Encrypt a password using PBKDF2 algorithm.
        :param password: A plain text password to be hashed.
        :type password: str
        :param salt: The salt used to encrypt the password.
        :type salt: str
        :return: The hashed password.
        """

        if not iterations:
            iterations = self.iterations

        password_bytes = password.encode()
        salt_bytes = salt.encode()

        hash = hashlib.pbkdf2_hmac(self.digest().name, password_bytes, salt_bytes, iterations)
        hash = base64.b64encode(hash).decode('ascii').strip()
        return "%s$%s$%s$%s" % (self.algorithm, iterations, salt, hash)

class MD5PasswordHasher(BasePasswordHasher):
    """
    MD5 Password hashing.
    This hashing is too weak so it is not recommended.
    """

    algorithm = "md5"

    def check_password(self, password, hashed_password):
        """
        Compares one plain text password against a MD5 hashed password.
        :param password: A plain text password.
        :type password: str
        :param hashed_password: An hashed password
        :type hashed_password: str
        :return: True if the password are equal; otherwise, false.
        """

        algorithm, salt, hash = hashed_password.split('$', 2)
        return self.hash_password(password, salt) == hashed_password

    def hash_password(self, password, salt):
        """
        Encrypt a password using MD5 algorithm.
        :param password: A plain text password to be hashed.
        :type password: str
        :param salt: The salt used to encrypt the password.
        :type salt: str
        :return: The hashed password.
        """

        hash = hashlib.md5((salt + password).encode()).hexdigest()
        return "%s$%s$%s" % (self.algorithm, salt, hash)

class SHA1PasswordHasher(BasePasswordHasher):
    """
    SHA1 Password hashing.
    This hashing is too weak so it is not recommended.
    """

    algorithm = "sha1"

    def check_password(self, password, hashed_password):
        """
        Compares one plain text password against a SHA1 hashed password.
        :param password: A plain text password.
        :type password: str
        :param hashed_password: An hashed password
        :type hashed_password: str
        :return: True if the password are equal; otherwise, false.
        """

        algorithm, salt, hash = hashed_password.split('$', 2)
        return self.hash_password(password, salt) == hashed_password

    def hash_password(self, password, salt):
        """
        Encrypt a password using SHA1 algorithm.
        :param password: A plain text password to be hashed.
        :type password: str
        :param salt: The salt used to encrypt the password.
        :type salt: str
        :return: The hashed password.
        """

        hash = hashlib.sha1((salt + password).encode()).hexdigest()
        return "%s$%s$%s" % (self.algorithm, salt, hash)


text:
{-# LANGUAGE MultiParamTypeClasses, ForeignFunctionInterface #-}

import Java
import Control.Monad

data JIntIntArray = JIntIntArray @int[][]
  deriving Class

instance JArray JIntArray JIntIntArray where

foreign import java unsafe "@static Utils.getIntIntArray" getIntIntArray
  :: Java a JIntIntArray

main :: IO ()
main = do
  intss <- java $ do
    iiarr <- getIntIntArray
    iarrs <- iiarr <.> arrayToList
    forM iarrs $ \iarr -> iarr <.> arrayToList
  print intss
  let arr = jints intss
  java $ forM_ [0.. (length intss - 1)] $ \i -> do
    ints <- arr <.> aget i
    io $ print (fromJava ints :: [Int])

jints :: [[Int]] -> JIntIntArray
jints intss = unsafePerformJava $ do
  arr <- anew (length intss)
  forM_ (zip [0..] intss) $ \(i, ints) ->
    arr <.> aset i (toJava ints)
  return arr


text:
"use strict";
/* jslint browser: true, globalstrict: true, devel: true, debug: true */
/* globals Tundra */
// For conditions of distribution and use, see copyright notice in LICENSE

/**
 * @author Erno Kuusela
 *
 * Originally based on scene parser class from Chiru-Webclient by
 * @author Toni Dahl
 *
 */

if (Tundra === undefined)
    var Tundra = {};

Tundra.SceneParser = function(ecModel) {
    this.ecModel = ecModel;
};

Tundra.logParserDebug = true;
Tundra.parserDebug = function(msg) {
    Tundra.logParserDebug && console.log(msg);
};

Tundra.SceneParser.prototype.parseFromUrl = function(url) {
    // console.log("________________________________________" );
    var xhttp = new XMLHttpRequest();
    xhttp.overrideMimeType('text/xml');
    xhttp.open("GET", url, false);
    xhttp.send(null);
    var doc = xhttp.responseXML;
    Tundra.check(doc !== null);
    return this.parseDocXml3D(doc);
};

Tundra.SceneParser.prototype.parseFromUrlXml3D = function(url) {
    Tundra.checkDefined(url);
    // console.log("________________________________________" );
    var xhttp = new XMLHttpRequest();
    //xhttp.overrideMimeType('text/xml');
    Tundra.check(typeof(url) === "string");
    console.log("xhr start");
    xhttp.onreadystatechange = function() {
        console.log("xhr callback");
        if (xhttp.readyState == 4) {
            if (xhttp.status == 200) {
                var doc = xhttp.response;
                Tundra.check(doc !== null);
                this.parseDocXml3D(doc);
            }
        } else {
            //console.log("unhandled xhr readystate " + xhttp.readyState);
        }
    }.bind(this);

    xhttp.open("GET", url, true);
    xhttp.responseType = "document";
    xhttp.send(null);
};

Tundra.SceneParser.prototype.parseFromString = function(xmlstring) {
    var doc = new window.DOMParser().parseFromString(xmlstring, "text/xml");
    return this.parseDoc(doc);
};

Tundra.SceneParser.prototype.parseDoc = function(doc) {
    var entities = doc.getElementsByTagName("entity");
    for (var i = 0; i < entities.length; i++) {
        var entity = entities[i];

        //does not work when the TXML file has overlapping IDs - the entities just won't get created and code borks
        //id = entity.getAttribute("id");
        var id = i;

        var ECEnt = this.ecModel.createEntity(id, 'notname');
        // console.log("ECEnt: " + ECEnt);
        this.ecModel.addEntity(ECEnt);

        var components = entity.getElementsByTagName("component");

        for (var j = 0; j < components.length; j++) {
            var type = components[j].getAttribute("type");

            var attributes = components[j].getElementsByTagName("attribute");

            // debugger;

            var ECComp = this.ecModel.createComponent(type);

            for (var k = 0; k < attributes.length; k++) {
                var attribute = attributes[k];

                var name = attribute.getAttribute("name");
                var value = attribute.getAttribute("value");

                if (name.toLowerCase() === 'transform') {
                    value = value.split(',');
                    // console.log("name: " + name);
                    // console.log("value: " + value);
                }

                ECComp.updateAttribute(k, value, name);
            }

            try {
                // debugger;
                ECEnt.addComponent(ECComp, j);
                // console.log("success: " + type);
            } catch (e) {
                // console.log("fail: " + type);
                // console.log(e.fileName);
                // console.log(e.lineNumber);

            }

        }
    }

    return this.ecModel;
};

Tundra.SceneParser.prototype.createEntityWithPlaceable = function() {
    var entity = this.ecModel.scene.createEntity(0, Tundra.AttributeChange.LocalOnly);
    var placeable = entity.createComponent(0, Tundra.cComponentTypePlaceable,
                                           "", Tundra.AttributeChange.LocalOnly);
    placeable.parentRef = 0; // won't get added to three scene until this is initialized
    return entity;
};

Tundra.SceneParser.prototype.parseDocXml3D = function(doc) {
    var lightEnt = this.ecModel.scene.createEntity(0, name);
    lightEnt.createComponent(0, Tundra.cComponentTypePlaceable,
                        "", Tundra.AttributeChange.LocalOnly);
    lightEnt.createComponent(0, Tundra.cComponentTypeLight, "", Tundra.AttributeChange.LocalOnly);
    console.log("SceneParser: created placeholder light");

    var x3Nodes = doc.getElementsByTagName("xml3d");
    if (x3Nodes.length < 1) {
        console.log("xml3d node not found");
        return;
    }
    if (x3Nodes.length > 1) {
        console.log("handling only first of " + x3Nodes.length);
    }

    var groups = Tundra.getDirectChildNodesByTagName(x3Nodes[0], "group");
    console.log("handling " + groups.length + " groups");

    var transformDefs = Tundra.wtFindTransformDefs(doc);

    var setPlaceableFromGroupNode = function(placeable, groupNode) {
        Tundra.check(!!groupNode);
        var xTransform = groupNode.getAttribute("transform");
        if (!xTransform)
            return false;
        if (xTransform[0] !== "#") {
            console.log("don't know how to handle this kind of transform: " + xTransform);
            return false;
        }
        var transformId = Tundra.wtTrimLeft(xTransform, "#");
        var setter = transformDefs[transformId];
        if (!setter) {
            console.log("no transfrom def found:" + transformId);
            return false;
        }
        setter(placeable);
        console.log("placeable setter run");
        return true;
    };

    var viewsInGroups = [];
    var viewId, viewPosition, viewOrientation, xview,
       entity, ecCamera, placeable;
    for (var i = 0; i < groups.length; i++) {
        // console.log("doing group " + i);
        var group = groups[i];
        var groupId = group.getAttribute("id");

        entity = this.createEntityWithPlaceable();
        placeable = entity.componentByType("Placeable");
        Tundra.check(!!placeable);
        var gotTransform = setPlaceableFromGroupNode(placeable, group);
        if (!gotTransform)
            console.log("using default transform for group", group);

        var meshChildren = group.getElementsByTagName("mesh");
        if (meshChildren.length > 0) {
            //console.log("*** handling meshes in group " + i);
            var xmesh = meshChildren[0];
            if (meshChildren.length > 1)
                console.log("handling only first mesh of " + meshChildren.length);
            var type = xmesh.getAttribute("type");
            var src = xmesh.getAttribute("src");
            var meshName = xmesh.getAttribute("id") || groupId;
            var ecmesh = entity.createComponent(0, Tundra.cComponentTypeMesh, meshName,
                                                Tundra.AttributeChange.LocalOnly);
            ecmesh.meshRef = { ref: src };
            console.log("made mesh for id " + meshName + " entity " + entity.id);

        } else {
            //console.log("no meshes in group " + i);
        }
        var viewChildren = group.getElementsByTagName("view");

        if (viewChildren.length > 0) {
            console.log("got view in group");
            xview = viewChildren[0];
            if (viewChildren.length > 1)
                console.log("handling only first view of " + viewChildren.length);
            viewsInGroups.push(xview);
            viewId = xview.getAttribute("id");
            viewPosition = xview.getAttribute("position");
            viewOrientation = xview.getAttribute("orientation");
            if (viewPosition) {
                console.log("in-group views with position not implemented");
            } else {
                setPlaceableFromGroupNode(placeable, group);
            }
            ecCamera = entity.createComponent(0, Tundra.cComponentTypeCamera, viewId || "camera", Tundra.AttributeChange.LocalOnly);

            //console.log("in-group camera added to entity " + entity.id);
            //placeable.debug = true;
        }
    }

    var grouplessViews = Tundra.wtNodeListToArray(doc.getElementsByTagName("view"));
    for (i = grouplessViews.length; i >= 0; i--) {
        if (Tundra.wtArrayContains(viewsInGroups, grouplessViews[i]))
            Tundra.wtRemoveElementAtIndex(grouplessViews, i);
    }

    if (grouplessViews.length > 0) {
        console.log("got view outside group");
        xview = grouplessViews[0];
        if (grouplessViews.length > 1)
            console.log("handling only first view of " + grouplessViews.length);
        viewId = xview.getAttribute("id");
        viewPosition = xview.getAttribute("position");
        viewOrientation = xview.getAttribute("orientation");
        var camEntity = this.ecModel.scene.createEntity(0, Tundra.AttributeChange.LocalOnly);
        var placeable = camEntity.createComponent(0, Tundra.cComponentTypePlaceable,
                                               "", Tundra.AttributeChange.LocalOnly);
        ecCamera = camEntity.createComponent(0, Tundra.cComponentTypeCamera, viewId || "camera", Tundra.AttributeChange.LocalOnly);
        var px = placeable.transform;
        if (viewPosition) {
            //console.log("have view pos");
            Tundra.wtSplitToXyz(viewPosition, px.pos);
         }
        if (viewOrientation) {
            console.log("viewOrientation conversion " + viewOrientation);
            Tundra.wtSplitAxisAngleToEulerXyz(viewOrientation, px.rot);
            //console.log("have view orientation, x=" + px.rot.x);
        }
        ecCamera.aspectRatio = ecCamera.aspectRatio;
        placeable.debug = true;
        placeable.transform = px; // trigger signal
        placeable.parentRef = 0;
        console.log("groupless camera added to entity " + entity.id);

    }

};

Tundra.getDirectChildNodesByTagName = function(node, tagName) {
    var out = [];
    tagName = tagName.toLowerCase();
    for (var i = 0; i < node.childNodes.length; i++) {
        var cn = node.childNodes[i];
        if (cn.tagName && cn.tagName.toLowerCase() === tagName)
            out.push(cn);
    }
    return out;
}

Tundra.xyzAngleToQuaternion = function(nums) {
    /* formula from xml3d.js's rotation.js */
    Tundra.check(nums.length === 4);
    var axisVec = new THREE.Vector3(nums[0], nums[1], nums[2]);
    var axisLength = axisVec.length();
    var quatXyzw;
    if (axisLength <= 0.00001)
        quatXyzw = [0, 0, 0, 1];
    else {
        var s = Math.sin(nums[3] / 2) / axisLength;
        var w = Math.cos(nums[3] / 2);
        quatXyzw = [nums[0] * s, nums[1] * s, nums[2] * s, w];
    }
    return new THREE.Quaternion(quatXyzw[0], quatXyzw[1], quatXyzw[2], quatXyzw[3]);
};

Tundra.wtRemoveElementAtIndex = function(arr, i) {
    arr.splice(i, 1);
};

Tundra.wtNodeListToArray = function(nodeList) {
    var out = [];
    out.push.apply(out, nodeList);
    Tundra.check(out.length === nodeList.length);
    return out;
};

Tundra.wtFlattenArrays = function(arrayOfArrays) {
    var arr = [];
    return arr.concat.apply(arrayOfArrays);
};

Tundra.wtArrayContains = function(arr, elt) {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] === elt)
            return true;
    }
    return false;
};

Tundra.wtFindTransformDefs = function(root) {
    var allDefsNodes = root.getElementsByTagName("defs");
    if (allDefsNodes.length < 1) {
        console.log("can't find defs node");
        return false;
    }
    var foundTransforms = {};
    var makeSetter = function(trans, rot, scale) {
        var setter = function(placeable) {
            var px = placeable.transform;
            if (trans)
                Tundra.wtSplitToXyz(trans, px.pos);
            if (rot)
                Tundra.wtSplitAxisAngleToEulerXyz(rot, px.rot);
            if (scale)
                Tundra.wtSplitToXyz(scale, px.scale);
            placeable.transform = px; // trigger signals
            placeable.parentRef = 0;
            console.log("pos for transform= " + [px.pos.x, px.pos.y, px.pos.z]);
        };
        return setter;
    };
    var i;
    var transformNodes = [];
    for (i = 0; i < allDefsNodes.length; i++) {
        var thisDefTransforms = allDefsNodes[i].getElementsByTagName("transform")
        transformNodes = transformNodes.concat(
            Tundra.wtNodeListToArray(thisDefTransforms));
    }
    console.log("found " + transformNodes.length + " transforms accross all defs");
    for (i = 0; i < transformNodes.length; i++) {
        var transformNode = transformNodes[i];
        var trans = transformNode.getAttribute("translation"),
           rot = transformNode.getAttribute("rotation"),
           scale = transformNode.getAttribute("scale");
        var transformId = transformNode.getAttribute("id");
        if (!(trans && rot && scale)) {
            console.log("incomplete transform " + transformId + ":", trans, rot, scale);
        }
        console.log("transform: " + transformId);
        Tundra.check(!!(trans || rot || scale));
        foundTransforms[transformId] = makeSetter(trans, rot, scale);
    }
    console.log("transform finding finished");
    return foundTransforms;
};

Tundra.wtSplitToXyz = function(s, v3) {
    var nums = s.split(/\s+/).map(parseFloat);
    Tundra.check(nums.length === 3);
    v3.x = nums[0]; v3.y = nums[1]; v3.z = nums[2];
    // console.log("wtSplitToXyz: " + nums);
};
Tundra.wtSplitAxisAngleToEulerXyz = function(s, xfrmRot) {
    var nums = s.split(/\s+/).map(parseFloat);
    var euler = new THREE.Euler();
    Tundra.check(nums.length === 4);
    var q = Tundra.xyzAngleToQuaternion(nums);
    euler.setFromQuaternion(q);
    /* ec convention is degrees */
    xfrmRot.x = Tundra.wtRadToDeg(euler.x);
    xfrmRot.y = Tundra.wtRadToDeg(euler.y);
    xfrmRot.z = Tundra.wtRadToDeg(euler.z);
    //console.log("quat:", q, "euler:", euler);
};

Tundra.wtTrimLeft = function(s, trimChar) {
    while (s.length && s[0] === trimChar) {
        s = s.substring(1, s.length);
    }
    return s;
};

Tundra.wtRadToDeg = function(val) {
    return val * (180.0 / Math.PI);
};


text:
Trade in Cool Bootstrap
=================

A minimal template to get started with Jekyll and Prose.


text:
/* basename - return nondirectory portion of pathname */

/* See Makefile for compilation details. */

#include "config.h"

#if defined (HAVE_UNISTD_H)
#  include <unistd.h>
#endif

#include <stdio.h>
#include "builtins.h"
#include "shell.h"
#include "common.h"

basename_builtin (list)
     WORD_LIST *list;
{
  int slen, sufflen, off;
  char *string, *suffix, *fn;

  if (list == 0)
    {
      builtin_usage ();
      return (EX_USAGE);
    }

  if (no_options (list))
    return (EX_USAGE);

  string = list->word->word;
  suffix = (char *)NULL;
  if (list->next)
    {
      list = list->next;
      suffix = list->word->word;
    }

  if (list->next)
    {
      builtin_usage ();
      return (EX_USAGE);
    }

  slen = strlen (string);

  /* Strip trailing slashes */
  while (slen > 0 && string[slen - 1] == '/')
    slen--;

  /* (2) If string consists entirely of slash characters, string shall be
	 set to a single slash character.  In this case, skip steps (3)
	 through (5). */
  if (slen == 0)
    {
      fputs ("/\n", stdout);
      return (EXECUTION_SUCCESS);
    }

  /* (3) If there are any trailing slash characters in string, they
	 shall be removed. */
  string[slen] = '\0';

  /* (4) If there are any slash characters remaining in string, the prefix
	 of string up to an including the last slash character in string
	 shall be removed. */
  while (--slen >= 0)
    if (string[slen] == '/')
      break;

  fn = string + slen + 1;

  /* (5) If the suffix operand is present, is not identical to the
	 characters remaining in string, and is identical to a suffix
	 of the characters remaining in string, the suffix suffix
	 shall be removed from string.  Otherwise, string shall not be
	 modified by this step. */
  if (suffix)
    {
      sufflen = strlen (suffix);
      slen = strlen (fn);
      if (sufflen < slen)
        {
          off = slen - sufflen;
          if (strcmp (fn + off, suffix) == 0)
            fn[off] = '\0';
        }
    }
  printf ("%s\n", fn);
  return (EXECUTION_SUCCESS);
}

char *basename_doc[] = {
	"Return non-directory portion of pathname.",
	"",
	"The STRING is converted to a filename corresponding to the last",
	"pathname component in STRING.  If the suffix string SUFFIX is",
	"supplied, it is removed.",
	(char *)NULL
};

/* The standard structure describing a builtin command.  bash keeps an array
   of these structures. */
struct builtin basename_struct = {
	"basename",		/* builtin name */
	basename_builtin,	/* function implementing the builtin */
	BUILTIN_ENABLED,	/* initial flags for builtin */
	basename_doc,		/* array of long documentation strings. */
	"basename string [suffix]",	/* usage synopsis */
	0			/* reserved for internal use */
};


text:
'use strict';
var $ = require('../internals/export');
var DESCRIPTORS = require('../internals/descriptors');
var FORCED = require('../internals/forced-object-prototype-accessors-methods');
var toObject = require('../internals/to-object');
var toPrimitive = require('../internals/to-primitive');
var getPrototypeOf = require('../internals/object-get-prototype-of');
var getOwnPropertyDescriptor = require('../internals/object-get-own-property-descriptor').f;

// `Object.prototype.__lookupSetter__` method
// https://tc39.github.io/ecma262/#sec-object.prototype.__lookupSetter__
if (DESCRIPTORS) {
  $({ target: 'Object', proto: true, forced: FORCED }, {
    __lookupSetter__: function __lookupSetter__(P) {
      var O = toObject(this);
      var key = toPrimitive(P, true);
      var desc;
      do {
        if (desc = getOwnPropertyDescriptor(O, key)) return desc.set;
      } while (O = getPrototypeOf(O));
    }
  });
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Namespace Advanced.Algorithms.Sorting
   | Advanced Algorithms </title>
    <meta name="viewport" content="width=device-width">
    <meta name="title" content="Namespace Advanced.Algorithms.Sorting
   | Advanced Algorithms ">
    <meta name="generator" content="docfx 2.55.0.0">

    <link rel="shortcut icon" href="../favicon.ico">
    <link rel="stylesheet" href="../styles/docfx.vendor.css">
    <link rel="stylesheet" href="../styles/docfx.css">
    <link rel="stylesheet" href="../styles/main.css">
    <meta property="docfx:navrel" content="">
    <meta property="docfx:tocrel" content="toc.html">

    <meta property="docfx:rel" content="../">

              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
                Toggle navigation

              </button>

              <form class="navbar-form navbar-right" role="search" id="search">

                  <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">

              </form>

          Show / Hide Table of Contents

Namespace Advanced.Algorithms.Sorting

Classes

BubbleSort<T>

A bubble sort implementation.

BucketSort

A bucket sort implementation.

CountingSort

A counting sort implementation.

HeapSort<T>

A heap sort implementation.

InsertionSort<T>

An insertion sort implementation.

MergeSort<T>

A merge sort implementation.

QuickSort<T>

A quick sort implementation.

RadixSort

A radix sort implementation.

SelectionSort<T>

A selection sort implementation.

ShellSort<T>

A shell sort implementation.

TreeSort<T>

A tree sort implementation.

              Back to top

            Generated by DocFX


text:
layout: post
date: 2017-12-02
title: "Kisui Berlin Kisui hana Sleeveless Floor-Length Ballgown"
category: Kisui Berlin
tags: [Kisui Berlin,Kusui Berlin,Ballgown,Strapless,Floor-Length,Sleeveless]
---
### Kisui Berlin Kisui hana
Just **$399.62**
###   Sleeveless Floor-Length Ballgown

BRANDS	Kusui Berlin

Silhouette	Ballgown

Neckline	Strapless

Hemline/Train	Floor-Length

Sleeve	Sleeveless

Buy it: [https://www.readybrides.com/en/kisui-berlin/36565-kisui-hana.html](https://www.readybrides.com/en/kisui-berlin/36565-kisui-hana.html)


text:
package com.alibaba.csp.sentinel.cluster.server.command.handler;

import java.util.Set;

import com.alibaba.csp.sentinel.cluster.flow.statistic.limit.GlobalRequestLimiter;
import com.alibaba.csp.sentinel.cluster.server.config.ClusterServerConfigManager;
import com.alibaba.csp.sentinel.cluster.server.config.ServerFlowConfig;
import com.alibaba.csp.sentinel.cluster.server.config.ServerTransportConfig;
import com.alibaba.csp.sentinel.cluster.server.connection.ConnectionGroup;
import com.alibaba.csp.sentinel.cluster.server.connection.ConnectionManager;
import com.alibaba.csp.sentinel.command.CommandHandler;
import com.alibaba.csp.sentinel.command.CommandRequest;
import com.alibaba.csp.sentinel.command.CommandResponse;
import com.alibaba.csp.sentinel.command.annotation.CommandMapping;
import com.alibaba.csp.sentinel.util.AppNameUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * @author Eric Zhao
 * @since 1.4.0
 */
@CommandMapping(name = "cluster/server/info", desc = "get cluster server info")
public class FetchClusterServerInfoCommandHandler implements CommandHandler<String> {

    @Override
    public CommandResponse<String> handle(CommandRequest request) {
        JSONObject info = new JSONObject();
        JSONArray connectionGroups = new JSONArray();
        Set<String> namespaceSet = ClusterServerConfigManager.getNamespaceSet();
        for (String namespace : namespaceSet) {
            ConnectionGroup group = ConnectionManager.getOrCreateConnectionGroup(namespace);
            if (group != null) {
                connectionGroups.add(group);
            }
        }

        ServerTransportConfig transportConfig = new ServerTransportConfig()
            .setPort(ClusterServerConfigManager.getPort())
            .setIdleSeconds(ClusterServerConfigManager.getIdleSeconds());
        ServerFlowConfig flowConfig = new ServerFlowConfig()
            .setExceedCount(ClusterServerConfigManager.getExceedCount())
            .setMaxOccupyRatio(ClusterServerConfigManager.getMaxOccupyRatio())
            .setIntervalMs(ClusterServerConfigManager.getIntervalMs())
            .setSampleCount(ClusterServerConfigManager.getSampleCount())
            .setMaxAllowedQps(ClusterServerConfigManager.getMaxAllowedQps());

        JSONArray requestLimitData = buildRequestLimitData(namespaceSet);

        info.fluentPut("port", ClusterServerConfigManager.getPort())
            .fluentPut("connection", connectionGroups)
            .fluentPut("requestLimitData", requestLimitData)
            .fluentPut("transport", transportConfig)
            .fluentPut("flow", flowConfig)
            .fluentPut("namespaceSet", namespaceSet)
            .fluentPut("embedded", ClusterServerConfigManager.isEmbedded());

        // Since 1.5.0 the appName is carried so that the caller can identify the appName of the token server.
        info.put("appName", AppNameUtil.getAppName());

        return CommandResponse.ofSuccess(info.toJSONString());
    }

    private JSONArray buildRequestLimitData(Set<String> namespaceSet) {
        JSONArray array = new JSONArray();
        for (String namespace : namespaceSet) {
            array.add(new JSONObject()
                .fluentPut("namespace", namespace)
                .fluentPut("currentQps", GlobalRequestLimiter.getCurrentQps(namespace))
                .fluentPut("maxAllowedQps", GlobalRequestLimiter.getMaxAllowedQps(namespace))
            );
        }
        return array;
    }
}


text:
//
//  PhotoTweaksViewController.h
//  PhotoTweaks
//
//  Created by Tu You on 14/12/5.
//  Copyright (c) 2014年 Tu You. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "PhotoTweakView.h"

@protocol PhotoTweaksViewControllerDelegate;

/**
 The photo tweaks controller.
 */
@interface PhotoTweaksViewController : UIViewController <CropOptionsViewDelegate>

/**
 Tint color for UI elements.
 */
@property (nonatomic, strong) UIColor *tintColor;

/**
 Image to process.
 */
@property (nonatomic, strong) UIImage *image;

/**
 Flag indicating whether the image cropped will be saved to photo library automatically. Defaults to YES.
 */
@property (nonatomic, assign) BOOL autoSaveToLibray;

/**
 The optional photo tweaks controller delegate.
 */
@property (nonatomic, weak) id<PhotoTweaksViewControllerDelegate> delegate;

/**
 Creates a photo tweaks view controller with the image to process.
 */
- (instancetype)initWithImage:(UIImage *)image;

@end

/**
 The photo tweaks controller delegate
 */
@protocol PhotoTweaksViewControllerDelegate <NSObject>

@optional
/**
 Called on image cropped.
 */
- (void)finishWithCroppedImage:(UIImage *)croppedImage;

@end