text:
function tests_bag_contents_empty(){
	this.emptyBag();
	var contents = this.getContents();

	var ret = tests_assert_equals('Bag capacity', this.capacity, contents.length);
	if (!ret.ok){
		return ret;
	}

	var ret = tests_assert_equals('Bag size', 0, this.size);
	if (!ret.ok){
		return ret;
	}

	return tests_ok();
}

function tests_bag_add_apple(){
	this.addItemStack(apiNewItemStack('apple', 2));

	var contents = this.getContents();
	var ret = tests_assert_equals('Bag size', 1, this.size);
	if (!ret.ok){
		return ret;
	}

	var stack = contents[0];
	var ret = tests_assert_equals('Stack size', 2, stack.count);
	if (!ret.ok){
		return ret;
	}
	var ret = tests_assert_equals('Stack type', 'apple', stack.class_tsid);
	if (!ret.ok){
		return ret;
	}

	return tests_ok();
}

function tests_bag_add_apple_stackable(){
	this.addItemStack(apiNewItemStack('apple', 2));

	var contents = this.getContents();
	var ret = tests_assert_equals('Bag size', 1, this.size);
	if (!ret.ok){
		return ret;
	}

	var stack = contents[0];
	var ret = tests_assert_equals('Stack size', 4, stack.count);
	if (!ret.ok){
		return ret;
	}
	var ret = tests_assert_equals('Stack type', 'apple', stack.class_tsid);
	if (!ret.ok){
		return ret;
	}

	return tests_ok();
}

function tests_bag_add_apple_overflow(){
	this.addItemStack(apiNewItemStack('apple', 100));

	var contents = this.getContents();
	var ret = tests_assert_equals('Bag size', 2, this.size);
	if (!ret.ok){
		return ret;
	}

	var stack = contents[0];
	var ret = tests_assert_equals('Stack size 1', 100, stack.count);
	if (!ret.ok){
		return ret;
	}
	var ret = tests_assert_equals('Stack type 1', 'apple', stack.class_tsid);
	if (!ret.ok){
		return ret;
	}

	var stack = contents[1];
	var ret = tests_assert_equals('Stack size 2', 4, stack.count);
	if (!ret.ok){
		return ret;
	}
	var ret = tests_assert_equals('Stack type 2', 'apple', stack.class_tsid);
	if (!ret.ok){
		return ret;
	}

	return tests_ok();
}

function tests_bag_add_apple_slot(){
	this.addItemStack(apiNewItemStack('apple', 5), 10);

	var contents = this.getContents();
	var ret = tests_assert_equals('Bag size', 3, this.size);
	if (!ret.ok){
		return ret;
	}

	var stack = contents[10];
	var ret = tests_assert_equals('Stack size', 5, stack.count);
	if (!ret.ok){
		return ret;
	}
	var ret = tests_assert_equals('Stack type', 'apple', stack.class_tsid);
	if (!ret.ok){
		return ret;
	}

	return tests_ok();
}

function tests_bag_remove_item_slot(){
	var stack = this.removeItemStackSlot(10);
	stack.apiDelete();

	var contents = this.getContents();
	var ret = tests_assert_equals('Bag size', 2, this.size);
	if (!ret.ok){
		return ret;
	}

	return tests_ok();
}

function tests_bag_remove_partial_item(){
	var stack = this.removeItemStackSlot(0, 1);
	stack.apiDelete();

	var contents = this.getContents();
	var ret = tests_assert_equals('Bag size', 2, this.size);
	if (!ret.ok){
		return ret;
	}

	var stack = contents[0];
	var ret = tests_assert_equals('Stack size', 99, stack.count);
	if (!ret.ok){
		return ret;
	}

	var ret = tests_assert_equals('Stack type', 'apple', stack.class_tsid);
	if (!ret.ok){
		return ret;
	}

	return tests_ok();
}

function tests_bag_fill(){
	for (var i=this.size; i<=this.capacity; i++){
		this.addItemStack(apiNewItemStack('apple', 5), i-1);
	}

	var contents = this.getContents();
	var ret = tests_assert_equals('Bag size', this.capacity, this.size);
	if (!ret.ok){
		return ret;
	}

	return tests_ok();
}

function tests_bag_add_item_fail(){
	var remaining = this.addItemStack(apiNewItemStack('banana', 1));
	var ret = tests_assert_equals('Returned stack count', 1, remaining);
	if (!ret.ok){
		return ret;
	}

	var contents = this.getContents();
	var ret = tests_assert_equals('Bag size', this.capacity, this.size);
	if (!ret.ok){
		return ret;
	}

	return tests_ok();
}

function tests_bag_add_subbag(){
	var stack = this.removeItemStackSlot(0);
	stack.apiDelete();

	var remaining = this.addItemStack(apiNewItemStack('bag_generic', 1));
	var ret = tests_assert_equals('Returned stack count', 0, remaining);
	if (!ret.ok){
		return ret;
	}

	var contents = this.getContents();
	var stack = contents[0];
	var ret = tests_assert_equals('Stack size', 1, stack.count);
	if (!ret.ok){
		return ret;
	}
	var ret = tests_assert_equals('Stack type', 'bag_generic', stack.class_tsid);
	if (!ret.ok){
		return ret;
	}

	return tests_ok();
}

function tests_bag_add_banana_subbag(){
	var remaining = this.addItemStack(apiNewItemStack('banana', 1));
	var ret = tests_assert_equals('Returned stack count', 0, remaining);
	if (!ret.ok){
		return ret;
	}

	var contents = this.getContents();
	var ret = tests_assert_equals('Bag size', this.capacity, this.size);
	if (!ret.ok){
		return ret;
	}

	var subbag = contents[0];
	var subbag_contents = subbag.getContents();
	var ret = tests_assert_equals('Subbag size', 1, subbag.size);
	if (!ret.ok){
		return ret;
	}

	var stack = subbag_contents[0];
	var ret = tests_assert_equals('Stack size', 1, stack.count);
	if (!ret.ok){
		return ret;
	}
	var ret = tests_assert_equals('Stack type', 'banana', stack.class_tsid);
	if (!ret.ok){
		return ret;
	}

	return tests_ok();
}

function tests_bag_remove_banana_subbag(){
	log.info('Starting test: tests_bag_remove_banana_subbag');
	var contents = this.getContents();
	var subbag = contents[0];

	var stack = subbag.removeItemStackSlot(0);
	stack.apiDelete();

	var ret = tests_assert_equals('Subbag size', 0, subbag.size);
	if (!ret.ok){
		return ret;
	}

	return tests_ok();
}

function tests_bag_serguei(){
	log.info('Adding subbag');
	var remaining = this.addItemStack(apiNewItemStack('bag_generic', 1), this.capacity-1);

	var contents = this.getContents();
	var subbag = contents[this.capacity-1];

	log.info('Subbag created');
	log.info('Subbag size is: '+subbag.size);
	subbag.addItemStack(apiNewItemStack('banana', 1));
	log.info('Banana added');
	log.info('Subbag size is: '+subbag.size);
	var stack = subbag.removeItemStackSlot(0);
	stack.apiDelete();
	log.info('Banana removed');
	log.info('Subbag size is: '+subbag.size);

	var contents = subbag.getContents();
	log.info('contents: '+contents);
}

function tests_bag_add_banana_subbag_slot(){
	var contents = this.getContents();
	var ret = tests_assert_equals('Bag size', this.capacity, this.size);
	if (!ret.ok){
		return ret;
	}

	var subbag = contents[0];
	var ret = tests_assert_equals('Subbag size', 1, subbag.size);
	if (!ret.ok){
		return ret;
	}

	var remaining = subbag.addItemStack(apiNewItemStack('banana', 1), 5);
	var ret = tests_assert_equals('Returned stack count', 0, remaining);
	if (!ret.ok){
		return ret;
	}

	var subbag_contents = subbag.getContents();
	var stack = subbag_contents[5];
	var ret = tests_assert_equals('Stack size', 1, stack.count);
	if (!ret.ok){
		return ret;
	}
	var ret = tests_assert_equals('Stack type', 'banana', stack.class_tsid);
	if (!ret.ok){
		return ret;
	}

	return tests_ok();
}

function tests_bag_delete_subbag(){
	var stack = this.removeItemStackSlot(0);
	stack.apiDelete();

	var ret = tests_assert_equals('Bag size', this.capacity-1, this.size);
	if (!ret.ok){
		return ret;
	}

	return tests_ok();
}

function tests_bag_add_spicerack(){
	var remaining = this.addItemStack(apiNewItemStack('bag_spicerack', 1));
	var ret = tests_assert_equals('Returned stack count', 0, remaining);
	if (!ret.ok){
		return ret;
	}

	var contents = this.getContents();
	var stack = contents[0];
	var ret = tests_assert_equals('Stack size', 1, stack.count);
	if (!ret.ok){
		return ret;
	}
	var ret = tests_assert_equals('Stack type', 'bag_spicerack', stack.class_tsid);
	if (!ret.ok){
		return ret;
	}

	return tests_ok();
}

function tests_bag_add_banana_spicerack_auto_fail(){
	var remaining = this.addItemStack(apiNewItemStack('banana', 1));
	var ret = tests_assert_equals('Returned stack count', 1, remaining);
	if (!ret.ok){
		return ret;
	}

	var contents = this.getContents();
	var ret = tests_assert_equals('Bag size', this.capacity, this.size);
	if (!ret.ok){
		return ret;
	}

	var subbag = contents[0];
	var subbag_contents = subbag.getContents();
	var ret = tests_assert_equals('Subbag size', 0, subbag.size);
	if (!ret.ok){
		return ret;
	}

	return tests_ok();
}

function tests_bag_add_banana_spicerack_direct_fail(){
	var contents = this.getContents();
	var subbag = contents[0];
	var ret = tests_assert_equals('Subbag size', 0, subbag.size);
	if (!ret.ok){
		return ret;
	}

	var remaining = subbag.addItemStack(apiNewItemStack('banana', 1));
	var ret = tests_assert_equals('Returned stack count', 1, remaining);
	if (!ret.ok){
		return ret;
	}

	return tests_ok();
}

function tests_bag_add_cumin_spicerack_auto(){
	var remaining = this.addItemStack(apiNewItemStack('cumin', 1));
	var ret = tests_assert_equals('Returned stack count', 0, remaining);
	if (!ret.ok){
		return ret;
	}

	var contents = this.getContents();
	var ret = tests_assert_equals('Bag size', this.capacity, this.size);
	if (!ret.ok){
		return ret;
	}

	var subbag = contents[0];
	var subbag_contents = subbag.getContents();
	var ret = tests_assert_equals('Subbag size', 1, subbag.size);
	if (!ret.ok){
		return ret;
	}

	var stack = subbag_contents[0];
	var ret = tests_assert_equals('Stack size', 1, stack.count);
	if (!ret.ok){
		return ret;
	}
	var ret = tests_assert_equals('Stack type', 'cumin', stack.class_tsid);
	if (!ret.ok){
		return ret;
	}

	return tests_ok();
}

function tests_bag_remove_spicerack_item(){
	var contents = this.getContents();
	var subbag = contents[0];
	var ret = tests_assert_equals('Subbag size', 1, subbag.size);
	if (!ret.ok){
		return ret;
	}

	var subbag_contents = subbag.getContents();
	var item = subbag_contents[0];

	var stack = subbag.removeItemStack(item.path);
	stack.apiDelete();

	var ret = tests_assert_equals('Subbag size', 0, subbag.size);
	if (!ret.ok){
		return ret;
	}

	return tests_ok();
}

function tests_assert_equals(name, expects, actual){
	if (expects != actual){
		return tests_fail(name+' was '+actual+', expecting '+expects);
	}
	else{
		return tests_ok();
	}
}

function tests_ok(){
	return { 'ok' : 1 };
}

function tests_fail(msg){
	return {
		'ok' : 0,
		'error' : msg
	};
}

function tests_instance_my_location() {
	this.instances_create('test_instance', this.location.tsid);
	this.instances_enter('test_instance', this.x, this.y);
}

function tests_leave_test_instance() {
	this.instances_exit('test_instance');
}

function tests_increment_grapes_squished(){
	if (!this.grapes_squished) this.grapes_squished = 0;

	this.grapes_squished += 1;

	if (isNaN(this.grapes_squished)){
		log.error('-------------------');
		log.error(this+" grapes squished is not a number!!!");
		log.error('-------------------');
	}
	else{
		this.apiSetTimer('tests_increment_grapes_squished', 1000);
	}
}


text:
#include "syshdrs.h"
#ifdef PRAGMA_HDRSTOP
#	pragma hdrstop
#endif

int
FTPChmod(const FTPCIPtr cip, const char *const pattern, const char *const mode, const int doGlob)
{
	FTPLineList fileList;
	FTPLinePtr filePtr;
	char *file;
	int onceResult, batchResult;

	if (cip == NULL)
		return (kErrBadParameter);
	if (strcmp(cip->magic, kLibraryMagic))
		return (kErrBadMagic);

	batchResult = FTPRemoteGlob(cip, &fileList, pattern, doGlob);
	if (batchResult != kNoErr)
		return (batchResult);

	for (batchResult = kNoErr, filePtr = fileList.first;
		filePtr != NULL;
		filePtr = filePtr->next)
	{
		file = filePtr->line;
		if (file == NULL) {
			batchResult = kErrBadLineList;
			cip->errNo = kErrBadLineList;
			break;
		}
		onceResult = FTPCmd(cip, "SITE CHMOD %s %s", mode, file);
		if (onceResult < 0) {
			batchResult = onceResult;
			break;
		}
		if (onceResult != 2) {
			batchResult = kErrChmodFailed;
			cip->errNo = kErrChmodFailed;
		}
	}
	DisposeLineListContents(&fileList);
	return (batchResult);
}	/* FTPChmod */

redpajama_set_name: RedPajamaGithub


text:
<?xml version='1.0' encoding='UTF-8'?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0">
    <modelVersion>4.0.0</modelVersion>
    <groupId>scala.parsec</groupId>
    <artifactId>scalazparsec_2.9.2</artifactId>
    <packaging>jar</packaging>
    <description>Scalaz Parsec</description>
    <version>0.1.0</version>
    <name>ScalazParsec</name>
    <organization>
        <name>scala.parsec</name>
    </organization>
    <dependencies>
        <dependency>
            <groupId>org.scala-lang</groupId>
            <artifactId>scala-library</artifactId>
            <version>2.9.2</version>
        </dependency>
	<dependency>
	  <groupId>org.scalaz</groupId>
	  <artifactId>scalaz-core_2.9.2</artifactId>
	  <version>7.0.3</version>
	</dependency>

    </dependencies>

    <!-- manually included -->
    <repositories>
        <repository>
            <id>scala-tools.org</id>
            <name>Scala-tools Maven2 Repository</name>
            <url>http://scala-tools.org/repo-releases</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>scala-tools.org</id>
            <name>Scala-tools Maven2 Repository</name>
            <url>http://scala-tools.org/repo-releases</url>
        </pluginRepository>
    </pluginRepositories>
    <build>
        <plugins>
            <!-- Scala compiler plugin -->
            <plugin>
                <groupId>org.scala-tools</groupId>
                <artifactId>maven-scala-plugin</artifactId>
                <version>2.15.2</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                        <configuration>
                          <args>
                            <arg>-optimise</arg>
                          </args>
                           <includes>
                            <include>**/*.scala</include>
                          </includes>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-jar-plugin</artifactId>
              <version>2.3.1</version>
              <configuration>
                <excludes>
                  <exclude>**/*.xml</exclude>
                </excludes>
                <archive>
                  <manifest>
                  </manifest>
                </archive>
              </configuration>
            </plugin>

        </plugins>
    </build>

</project>


text:
=============================
Jorrit's Python Package
=============================
.. |pypirelease| - source |ghrelease|

|travis| |appveyor| |coveralls| |docs| |license|

..
  Versions: binary |pypirelease| - source |ghrelease|

  Builds: Linux |travis| - Windows |appveyor|

  Tests: |codecov| |coveralls|

  Docs: |docs| License: |license|

My swiss army knife for plotting and simulation in Python

Features
--------

* TODO

Installation
------------

For Linux, you can find up to date instructions in `.travis.yml` and `appveyor.yml` can be used for Windows hosts.

.. |pypirelease| image:: https://badge.fury.io/py/jopy.png
    :target: http://badge.fury.io/py/jopy

.. |ghrelease| image:: https://img.shields.io/github/release/jowr/jopy.svg
    :target: https://github.com/jowr/jopy/releases
    :alt: version tag

.. |travis| image:: https://img.shields.io/travis/jowr/jopy.svg?label=Linux
    :target: https://travis-ci.org/jowr/jopy
    :alt: Travis CI Linux builds

.. |appveyor| image:: https://img.shields.io/appveyor/ci/jowr/jopy.svg?label=Windows
    :target: https://ci.appveyor.com/project/jowr/jopy/branch/master
    :alt: AppVeyor Windows builds

.. |codecov| image:: https://codecov.io/github/jowr/jopy/coverage.svg?branch=master
    :target: https://codecov.io/github/jowr/jopy
    :alt: codecov.io

.. |coveralls| image:: https://coveralls.io/repos/jowr/jopy/badge.svg
    :target: https://coveralls.io/r/jowr/jopy
    :alt: coveralls.io

.. |docs| image:: https://readthedocs.org/projects/jopy/badge/?version=latest
    :target: https://readthedocs.org/projects/jopy/
    :alt: ReadTheDocs builds

.. |license| image:: https://img.shields.io/github/license/jowr/jopy.svg
    :target: https://github.com/jowr/jopy/blob/master/LICENSE
    :alt: license


text:
const test = require('ava');
const { eachTest, jsonify } = require('postcss-parser-tests');

const { nodeToString, parse, stringify } = require('../../lib');

eachTest((name, code, json) => {
  // Skip comments.css, because we have an extended Comment node
  if (name === 'comments.css' || name === 'atrule-no-space.css' || name === 'inside.css') {
    return;
  }

  test(`parses ${name}`, (t) => {
    const root = parse(code, { from: name });
    const parsed = jsonify(root);

    t.is(parsed, json);
  });

  if (name === 'bom.css') {
    return; // eslint-disable-line no-useless-return
  }

  test(`stringifies ${name}`, (t) => {
    const root = parse(code);
    let result = '';

    stringify(root, (i) => {
      result += i;
    });

    t.is(result, code);
  });
});

test('parses nested rules', (t) => {
  const root = parse('a { b {} }');

  t.is(root.first.first.selector, 'b');
});

test('parses at-rules inside rules', (t) => {
  const root = parse('a { @media {} }');

  t.is(root.first.first.name, 'media');
});

test('nested media query with import (#103)', (t) => {
  const less = `@media screen {
	@import "basic";
}`;
  const root = parse(less);
  const { first } = root;

  t.is(first.first.name, 'import');
  t.is(nodeToString(root), less);
});

test('detached ruleset (#86)', (t) => {
  const params = `({
  .hello {
    .test {
    }
  }

  .fred {
  }
})`;
  const less = `.test${params}`;
  const root = parse(less);
  const { first } = root;

  t.true(first.mixin);
  t.is(first.name, 'test');
  t.is(first.params, params);
  t.is(nodeToString(root), less);
});


text:
package org.apache.nifi.cluster.protocol.jaxb.message;

import org.apache.nifi.cluster.coordination.node.NodeConnectionStatus;
import org.apache.nifi.cluster.protocol.ComponentRevisionSnapshot;
import org.apache.nifi.cluster.protocol.DataFlow;
import org.apache.nifi.cluster.protocol.NodeIdentifier;

import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import java.util.List;

/**
 */
public class AdaptedConnectionResponse {

    private DataFlow dataFlow;
    private NodeIdentifier nodeIdentifier;
    private String rejectionReason;
    private int tryLaterSeconds;
    private String instanceId;
    private List<NodeConnectionStatus> nodeStatuses;
    private ComponentRevisionSnapshot componentRevisions;

    public AdaptedConnectionResponse() {
    }

    @XmlJavaTypeAdapter(DataFlowAdapter.class)
    public DataFlow getDataFlow() {
        return dataFlow;
    }

    public void setDataFlow(DataFlow dataFlow) {
        this.dataFlow = dataFlow;
    }

    @XmlJavaTypeAdapter(NodeIdentifierAdapter.class)
    public NodeIdentifier getNodeIdentifier() {
        return nodeIdentifier;
    }

    public void setNodeIdentifier(NodeIdentifier nodeIdentifier) {
        this.nodeIdentifier = nodeIdentifier;
    }

    public int getTryLaterSeconds() {
        return tryLaterSeconds;
    }

    public void setTryLaterSeconds(int tryLaterSeconds) {
        this.tryLaterSeconds = tryLaterSeconds;
    }

    public String getRejectionReason() {
        return rejectionReason;
    }

    public void setRejectionReason(final String rejectionReason) {
        this.rejectionReason = rejectionReason;
    }

    public boolean shouldTryLater() {
        return tryLaterSeconds > 0;
    }

    public void setInstanceId(String instanceId) {
        this.instanceId = instanceId;
    }

    public String getInstanceId() {
        return instanceId;
    }

    public void setNodeConnectionStatuses(List<NodeConnectionStatus> connectionStatuses) {
        this.nodeStatuses = connectionStatuses;
    }

    public List<NodeConnectionStatus> getNodeConnectionStatuses() {
        return this.nodeStatuses;
    }

    public ComponentRevisionSnapshot getComponentRevisions() {
        return componentRevisions;
    }

    public void setComponentRevisions(ComponentRevisionSnapshot componentRevisions) {
        this.componentRevisions = componentRevisions;
    }
}


text:
package main

import (
	"encoding/json"
	"errors"
	"flag"
	"fmt"
	"io"
	"net"
	"net/http"
	_ "net/http/pprof"
	"net/url"
	"os"
	"path/filepath"
	"sync"
	"sync/atomic"
	"syscall"

	"github.com/clearcontainers/proxy/api"

	"github.com/golang/glog"
)

// tokenState  tracks if an I/O token has been claimed by a shim.
type tokenState int

const (
	tokenStateAllocated tokenState = iota
	tokenStateClaimed
)

// tokenInfo keeps track of per-token data
type tokenInfo struct {
	state tokenState
	vm    *vm
}

// Main struct holding the proxy state
type proxy struct {
	// Protect concurrent accesses from separate client goroutines to this
	// structure fields
	sync.Mutex

	// proxy socket
	listener   net.Listener
	socketPath string

	// vms are hashed by their containerID
	vms map[string]*vm

	// tokenToVM maps I/O token to their per-token info
	tokenToVM map[Token]*tokenInfo

	// Output the VM console on stderr
	enableVMConsole bool

	wg sync.WaitGroup
}

type clientKind int

const (
	clientKindRuntime clientKind = 1 << iota
	clientKindShim
)

// Represents a client, either a cc-oci-runtime or cc-shim process having
// opened a socket to the proxy
type client struct {
	id    uint64
	proxy *proxy
	vm    *vm

	kind clientKind

	// token and session are populated once a client has issued a successful
	// Connectshim.
	token   Token
	session *ioSession

	conn net.Conn
}

func (c *client) info(lvl glog.Level, msg string) {
	if !glog.V(lvl) {
		return
	}
	glog.Infof("[client #%d] %s", c.id, msg)
}

func (c *client) infof(lvl glog.Level, fmt string, a ...interface{}) {
	if !glog.V(lvl) {
		return
	}
	a = append(a, 0)
	copy(a[1:], a[0:])
	a[0] = c.id
	glog.Infof("[client #%d] "+fmt, a...)
}

func (proxy *proxy) allocateTokens(vm *vm, numIOStreams int) (*api.IOResponse, error) {
	url := url.URL{
		Scheme: "unix",
		Path:   proxy.socketPath,
	}

	if numIOStreams <= 0 {
		return &api.IOResponse{
			URL: url.String(),
		}, nil
	}

	tokens := make([]string, 0, numIOStreams)

	for i := 0; i < numIOStreams; i++ {
		token, err := vm.AllocateToken()
		if err != nil {
			return nil, err
		}
		tokens = append(tokens, string(token))
		proxy.Lock()
		proxy.tokenToVM[token] = &tokenInfo{
			state: tokenStateAllocated,
			vm:    vm,
		}
		proxy.Unlock()
	}

	return &api.IOResponse{
		URL:    url.String(),
		Tokens: tokens,
	}, nil
}

func (proxy *proxy) claimToken(token Token) (*tokenInfo, error) {
	proxy.Lock()
	defer proxy.Unlock()

	info := proxy.tokenToVM[token]
	if info == nil {
		return nil, fmt.Errorf("unknown token: %s", token)
	}

	if info.state == tokenStateClaimed {
		return nil, fmt.Errorf("token already claimed: %s", token)
	}

	info.state = tokenStateClaimed

	return info, nil
}

func (proxy *proxy) releaseToken(token Token) (*tokenInfo, error) {
	proxy.Lock()
	defer proxy.Unlock()

	info := proxy.tokenToVM[token]
	if info == nil {
		return nil, fmt.Errorf("unknown token: %s", token)
	}

	return info, nil
}

// "RegisterVM"
func registerVM(data []byte, userData interface{}, response *handlerResponse) {
	client := userData.(*client)
	payload := api.RegisterVM{}

	if err := json.Unmarshal(data, &payload); err != nil {
		response.SetError(err)
		return
	}

	if payload.ContainerID == "" || payload.CtlSerial == "" || payload.IoSerial == "" {
		response.SetErrorMsg("malformed RegisterVM command")
	}

	proxy := client.proxy
	proxy.Lock()
	if _, ok := proxy.vms[payload.ContainerID]; ok {

		proxy.Unlock()
		response.SetErrorf("%s: container already registered",
			payload.ContainerID)
		return
	}

	client.infof(1,
		"RegisterVM(containerId=%s,ctlSerial=%s,ioSerial=%s,console=%s)",
		payload.ContainerID, payload.CtlSerial, payload.IoSerial,
		payload.Console)

	vm := newVM(payload.ContainerID, payload.CtlSerial, payload.IoSerial)
	proxy.vms[payload.ContainerID] = vm
	proxy.Unlock()

	if payload.Console != "" && proxy.enableVMConsole {
		vm.setConsole(payload.Console)
	}

	io, err := proxy.allocateTokens(vm, payload.NumIOStreams)
	if err != nil {
		response.SetError(err)
		return
	}
	if io != nil {
		response.AddResult("io", io)
	}

	if err := vm.Connect(); err != nil {
		proxy.Lock()
		delete(proxy.vms, payload.ContainerID)
		proxy.Unlock()
		response.SetError(err)
		return
	}

	client.vm = vm

	// We start one goroutine per-VM to monitor the qemu process
	proxy.wg.Add(1)
	go func() {
		<-vm.OnVMLost()
		vm.Close()
		proxy.wg.Done()
	}()
}

// "attach"
func attachVM(data []byte, userData interface{}, response *handlerResponse) {
	client := userData.(*client)
	proxy := client.proxy

	payload := api.AttachVM{}
	if err := json.Unmarshal(data, &payload); err != nil {
		response.SetError(err)
		return
	}

	proxy.Lock()
	vm := proxy.vms[payload.ContainerID]
	proxy.Unlock()

	if vm == nil {
		response.SetErrorf("unknown containerID: %s", payload.ContainerID)
		return
	}

	io, err := proxy.allocateTokens(vm, payload.NumIOStreams)
	if err != nil {
		response.SetError(err)
		return
	}
	if io != nil {
		response.AddResult("io", io)
	}

	client.infof(1, "AttachVM(containerId=%s)", payload.ContainerID)

	client.vm = vm
}

// "UnregisterVM"
func unregisterVM(data []byte, userData interface{}, response *handlerResponse) {
	// UnregisterVM only affects the proxy.vms map and so removes the VM
	// from the client visible API.
	// vm.Close(), which tears down the VM object, is done at the end of
	// the VM life cycle, when  we detect the qemu process is effectively
	// gone (see RegisterVM)

	client := userData.(*client)
	proxy := client.proxy

	payload := api.UnregisterVM{}
	if err := json.Unmarshal(data, &payload); err != nil {
		response.SetError(err)
		return
	}

	proxy.Lock()
	vm := proxy.vms[payload.ContainerID]
	proxy.Unlock()

	if vm == nil {
		response.SetErrorf("unknown containerID: %s", payload.ContainerID)
		return
	}

	client.info(1, "UnregisterVM()")

	proxy.Lock()
	delete(proxy.vms, vm.containerID)
	proxy.Unlock()

	client.vm = nil
}

// "hyper"
func hyper(data []byte, userData interface{}, response *handlerResponse) {
	client := userData.(*client)
	hyper := api.Hyper{}
	vm := client.vm

	if err := json.Unmarshal(data, &hyper); err != nil {
		response.SetError(err)
		return
	}

	if vm == nil {
		response.SetErrorMsg("client not attached to a vm")
		return
	}

	client.infof(1, "hyper(cmd=%s, data=%s)", hyper.HyperName, hyper.Data)

	err := vm.SendMessage(&hyper)
	response.SetError(err)
}

// "connectShim"
func connectShim(data []byte, userData interface{}, response *handlerResponse) {
	client := userData.(*client)
	proxy := client.proxy

	payload := api.ConnectShim{}
	if err := json.Unmarshal(data, &payload); err != nil {
		response.SetError(err)
		return
	}

	token := Token(payload.Token)
	info, err := proxy.claimToken(token)
	if err != nil {
		response.SetError(err)
		return
	}

	session, err := info.vm.AssociateShim(token, client.id, client.conn)
	if err != nil {
		response.SetError(err)
		return
	}

	client.kind = clientKindShim
	client.token = token
	client.session = session

	client.infof(1, "ConnectShim(token=%s)", payload.Token)
}

// "disconnectShim"
func disconnectShim(data []byte, userData interface{}, response *handlerResponse) {
	client := userData.(*client)
	proxy := client.proxy

	if client.kind != clientKindShim {
		response.SetErrorMsg("client isn't a shim")
		return
	}

	info, err := proxy.releaseToken(client.token)
	if err != nil {
		response.SetError(err)
		return
	}

	err = info.vm.FreeToken(client.token)
	if err != nil {
		response.SetError(err)
		return
	}

	client.session = nil
	client.token = ""

	client.infof(1, "DisconnectShim()")
}

// "signal"
func signal(data []byte, userData interface{}, response *handlerResponse) {
	client := userData.(*client)
	payload := api.Signal{}

	if client.kind != clientKindShim {
		response.SetErrorMsg("client isn't a shim")
		return
	}
	session := client.session

	if err := json.Unmarshal(data, &payload); err != nil {
		response.SetError(err)
		return
	}

	// Validate payload
	signal := syscall.Signal(payload.SignalNumber)
	if signal < 0 || signal >= syscall.SIGUNUSED {
		response.SetErrorf("invalid signal number %d", payload.SignalNumber)
		return
	}
	if signal == syscall.SIGWINCH && (payload.Columns == 0 || payload.Rows == 0) {
		response.SetErrorf("received SIGWINCH but terminal size is invalid (%d,%d)",
			payload.Columns, payload.Rows)
		return
	}
	if signal != syscall.SIGWINCH && (payload.Columns != 0 || payload.Rows != 0) {
		response.SetErrorf("received a terminal size (%d,%d) for signal %s",
			payload.Columns, payload.Rows, signal)
		return
	}

	client.infof(1, "Signal(%s,%d,%d)", signal, payload.Columns, payload.Rows)

	var err error
	if signal == syscall.SIGWINCH {
		err = session.SendTerminalSize(payload.Columns, payload.Rows)
	} else {
		err = session.SendSignal(signal)
	}
	if err != nil {
		response.SetError(err)
		return
	}

}

func forwardStdin(frame *api.Frame, userData interface{}) error {
	client := userData.(*client)

	if client.session == nil {
		return errors.New("stdin: client not associated with any I/O session")
	}

	return client.session.ForwardStdin(frame)
}

func newProxy() *proxy {
	return &proxy{
		vms:       make(map[string]*vm),
		tokenToVM: make(map[Token]*tokenInfo),
	}
}

// DefaultSocketPath is populated at link time with the value of:
//   ${locatestatedir}/run/cc-oci-runtime/proxy
var DefaultSocketPath string

// ArgSocketPath is populated at runtime from the option -socket-path
var ArgSocketPath = flag.String("socket-path", "", "specify path to socket file")

// getSocketPath computes the path of the proxy socket. Note that when socket
// activated, the socket path is specified in the systemd socket file but the
// same value is set in DefaultSocketPath at link time.
func getSocketPath() string {
	// Invoking "go build" without any linker option will not
	// populate DefaultSocketPath, so fallback to a reasonable
	// path. People should really use the Makefile though.
	if DefaultSocketPath == "" {
		DefaultSocketPath = "/var/run/cc-oci-runtime/proxy.sock"
	}

	socketPath := DefaultSocketPath

	if len(*ArgSocketPath) != 0 {
		socketPath = *ArgSocketPath
	}

	return socketPath
}

func (proxy *proxy) init() error {
	var l net.Listener
	var err error

	// flags
	v := flag.Lookup("v").Value.(flag.Getter).Get().(glog.Level)
	proxy.enableVMConsole = v >= 3

	// Open the proxy socket
	proxy.socketPath = getSocketPath()
	fds := listenFds()

	if len(fds) > 1 {
		return fmt.Errorf("too many activated sockets (%d)", len(fds))
	} else if len(fds) == 1 {
		fd := fds[0]
		l, err = net.FileListener(fd)
		if err != nil {
			return fmt.Errorf("couldn't listen on socket: %v", err)
		}

	} else {
		socketDir := filepath.Dir(proxy.socketPath)
		if err = os.MkdirAll(socketDir, 0750); err != nil {
			return fmt.Errorf("couldn't create socket directory: %v", err)
		}
		if err = os.Remove(proxy.socketPath); err != nil && !os.IsNotExist(err) {
			return fmt.Errorf("couldn't remove exiting socket: %v", err)
		}
		l, err = net.ListenUnix("unix", &net.UnixAddr{Name: proxy.socketPath, Net: "unix"})
		if err != nil {
			return fmt.Errorf("couldn't create AF_UNIX socket: %v", err)
		}
		if err = os.Chmod(proxy.socketPath, 0660|os.ModeSocket); err != nil {
			return fmt.Errorf("couldn't set mode on socket: %v", err)
		}

		glog.V(1).Info("listening on ", proxy.socketPath)
	}

	proxy.listener = l

	return nil
}

var nextClientID = uint64(1)

func (proxy *proxy) serveNewClient(proto *protocol, newConn net.Conn) {
	newClient := &client{
		id:    nextClientID,
		proxy: proxy,
		conn:  newConn,
	}

	atomic.AddUint64(&nextClientID, 1)

	// Unfortunately it's hard to find out information on the peer
	// at the other end of a unix socket. We use a per-client ID to
	// identify connections.
	newClient.info(1, "client connected")

	if err := proto.Serve(newConn, newClient); err != nil && err != io.EOF {
		newClient.infof(1, "error serving client: %v", err)
	}

	newConn.Close()
	newClient.info(1, "connection closed")
}

func (proxy *proxy) serve() {

	// Define the client (runtime/shim) <-> proxy protocol
	proto := newProtocol()
	proto.HandleCommand(api.CmdRegisterVM, registerVM)
	proto.HandleCommand(api.CmdAttachVM, attachVM)
	proto.HandleCommand(api.CmdUnregisterVM, unregisterVM)
	proto.HandleCommand(api.CmdHyper, hyper)
	proto.HandleCommand(api.CmdConnectShim, connectShim)
	proto.HandleCommand(api.CmdDisconnectShim, disconnectShim)
	proto.HandleCommand(api.CmdSignal, signal)
	proto.HandleStream(forwardStdin)

	glog.V(1).Info("proxy started")

	for {
		conn, err := proxy.listener.Accept()
		if err != nil {
			fmt.Fprintln(os.Stderr, "couldn't accept connection:", err)
			continue
		}

		go proxy.serveNewClient(proto, conn)
	}
}

func proxyMain() {
	proxy := newProxy()
	if err := proxy.init(); err != nil {
		fmt.Fprintln(os.Stderr, "init:", err.Error())
		os.Exit(1)
	}
	proxy.serve()

	// Wait for all the goroutines started by registerVMHandler to finish.
	//
	// Not strictly necessary as:
	//   • currently proxy.serve() cannot return,
	//   • even if it was, the process is about to exit anyway...
	//
	// That said, this wait group is used in the tests to ensure proper
	// serialisation between runs of proxyMain()(see proxy/proxy_test.go).
	proxy.wg.Wait()
}

func initLogging() {
	// We print logs on stderr by default.
	flag.Set("logtostderr", "true")

	// It can be practical to use an environment variable to trigger a verbose output
	level := os.Getenv("CC_PROXY_LOG_LEVEL")
	if level != "" {
		flag.Set("v", level)
	}
}

type profiler struct {
	enabled bool
	host    string
	port    uint
}

func (p *profiler) setup() {
	if !p.enabled {
		return
	}

	addr := fmt.Sprintf("%s:%d", p.host, p.port)
	url := "http://" + addr + "/debug/pprof"
	glog.V(1).Info("pprof enabled on " + url)

	go func() {
		http.ListenAndServe(addr, nil)
	}()
}

func main() {
	var pprof profiler

	initLogging()

	flag.BoolVar(&pprof.enabled, "pprof", false,
		"enable pprof ")
	flag.StringVar(&pprof.host, "pprof-host", "localhost",
		"host the pprof server will be bound to")
	flag.UintVar(&pprof.port, "pprof-port", 6060,
		"port the pprof server will be bound to")

	flag.Parse()
	defer glog.Flush()

	pprof.setup()
	proxyMain()
}


text:
/* globals Blaze, isSetNotNull, Template */
RocketChat.EmojiPicker = {
	width: 390,
	height: 238,
	initiated: false,
	input: null,
	source: null,
	recent: [],
	tone: null,
	opened: false,
	pickCallback: null,
	init() {
		if (this.initiated) {
			return;
		}
		this.initiated = true;

		this.recent = window.localStorage.getItem('emoji.recent') ? window.localStorage.getItem('emoji.recent').split(',') : [];
		this.tone = window.localStorage.getItem('emoji.tone') || 0;

		Blaze.render(Template.emojiPicker, document.body);

		$(document).click((event) => {
			if (!this.opened) {
				return;
			}
			if (!$(event.target).closest('.emoji-picker').length && !$(event.target).is('.emoji-picker')) {
				if (this.opened) {
					this.close();
				}
			}
		});

		$(window).resize(_.debounce(() => {
			if (!this.opened) {
				return;
			}
			this.setPosition();
		}, 300));
	},
	isOpened() {
		return this.opened;
	},
	setTone(tone) {
		this.tone = tone;
		window.localStorage.setItem('emoji.tone', tone);
	},
	getTone() {
		return this.tone;
	},
	getRecent() {
		return this.recent;
	},
	setPosition() {
		let sourcePos = $(this.source).offset();
		let left = sourcePos.left;
		let top = (sourcePos.top - this.height - 5);
		let cssProperties = {
			top: top,
			left: left
		};

		if (top < 0) {
			cssProperties.top = 10;
		}

		if (left < 35) {
			cssProperties.left = 0;
		} else {
			let windowSize = $(window).width();
			let pickerWidth = $('.emoji-picker').width();

			if (left + pickerWidth > windowSize) {
				let emojiButtonSize = $('.reaction-message.message-action').outerWidth();
				cssProperties.left = left - pickerWidth + emojiButtonSize;
			}
		}

		return $('.emoji-picker').css(cssProperties);
	},
	open(source, callback) {
		if (!this.initiated) {
			this.init();
		}
		this.pickCallback = callback;
		this.source = source;

		const containerEl = this.setPosition();
		containerEl.addClass('show');

		const emojiInput = containerEl.find('.emoji-filter input.search');
		if (emojiInput) {
			emojiInput.focus();
		}
		this.opened = true;
	},
	close() {
		$('.emoji-picker').removeClass('show');
		this.opened = false;
	},
	pickEmoji(emoji) {
		this.pickCallback(emoji);

		this.close();
		this.addRecent(emoji);
	},
	addRecent(emoji) {
		let pos = this.recent.indexOf(emoji);

		if (pos !== -1) {
			this.recent.splice(pos, 1);
		}

		this.recent.unshift(emoji);

		window.localStorage.setItem('emoji.recent', this.recent);
		RocketChat.emoji.packages.base.emojisByCategory.recent = this.recent;

		this.updateRecent();
	},
	updateRecent() {
		let total = RocketChat.emoji.packages.base.emojisByCategory.recent.length;
		let html = '';
		for (var i = 0; i < total; i++) {
			let emoji = RocketChat.emoji.packages.base.emojisByCategory.recent[i];

			if (isSetNotNull(() => RocketChat.emoji.list[`:${emoji}:`])) {
				let emojiPackage = RocketChat.emoji.list[`:${emoji}:`].emojiPackage;
				let renderedEmoji = RocketChat.emoji.packages[emojiPackage].render(`:${emoji}:`);
				html += `<li class="emoji-${emoji}" data-emoji="${emoji}">${renderedEmoji}</li>`;
			} else {
				this.recent = _.without(this.recent, emoji);
			}
		}
		$('.recent.emoji-list').empty().append(html);
	}
};


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows.Input;
using Afnor.Silverlight.Toolkit.Collections;
using Afnor.Silverlight.Toolkit.ViewServices;
using EspaceClient.BackOffice.Domaine.Criterias;
using EspaceClient.BackOffice.Domaine.Results;
using EspaceClient.BackOffice.Silverlight.Business.Depots;
using EspaceClient.BackOffice.Silverlight.Business.Interfaces;
using EspaceClient.BackOffice.Silverlight.Business.Loader;
using EspaceClient.BackOffice.Silverlight.ViewModels.Common.Modularity;
using EspaceClient.BackOffice.Silverlight.ViewModels.Helper.Resource;
using EspaceClient.BackOffice.Silverlight.ViewModels.Messages;
using EspaceClient.BackOffice.Silverlight.ViewModels.ModelBuilders.GestionContenu.Resource;
using EspaceClient.FrontOffice.Domaine;
using nRoute.Components;
using nRoute.Components.Composition;
using nRoute.Components.Messaging;
using OGDC.Silverlight.Toolkit.Services.Services;

namespace EspaceClient.BackOffice.Silverlight.ViewModels.GestionContenu.Resource.Tabs
{
    /// <summary>
    /// ViewModel de la vue <see cref="SearchView"/>
    /// </summary>
    public class SearchViewModel : TabBase
    {
        private readonly IResourceWrapper _resourceWrapper;
        private readonly IDepotRessource _depotResource;
        private readonly ILoaderReferentiel _referentiel;
        private readonly INavigatableChildWindowService _childWindowService;

        private readonly IModelBuilderDetails _builderDetails;

        protected ChannelObserver<UpdateListMessage> ObserverUpdateListMessage { get; private set; }

        private IEnumerable<TypeRessourceDto> _typeRessources;
        private ObservableCollection<RessourceResult> _searchResult;
        private SearchResourceCriteriasDto _criteres;
        private RessourceResult _selectedResource;

        private bool _isLoading;

        private ICommand _searchCommand;
        private ICommand _resetCommand;
        private ICommand _doubleClickCommand;

        [ResolveConstructor]
        public SearchViewModel(IResourceWrapper resourceWrapper, IDepotRessource depotResource, IMessenging messengingService, IApplicationContext applicationContext, ILoaderReferentiel referentiel, IModelBuilderDetails builderDetails, INavigatableChildWindowService childWindowService)
            : base(applicationContext, messengingService)
        {
            _resourceWrapper = resourceWrapper;
            _depotResource = depotResource;
            _referentiel = referentiel;
            _childWindowService = childWindowService;

            _builderDetails = builderDetails;

            InitializeCommands();

            InitializeUI();

            InitializeMessenging();
        }

        public ObservableCollection<RessourceResult> SearchResult
        {
            get
            {
                return _searchResult;
            }

            set
            {
                if (_searchResult != value)
                {
                    _searchResult = value;
                    NotifyPropertyChanged(() => SearchResult);
                }
            }
        }
        public SearchResourceCriteriasDto Criteres
        {
            get
            {
                return _criteres;
            }

            set
            {
                _criteres = value;
                NotifyPropertyChanged(() => Criteres);
            }
        }
        public RessourceResult SelectedResource
        {
            get { return _selectedResource; }
            set
            {
                if (_selectedResource != value)
                {
                    _selectedResource = value;
                    NotifyPropertyChanged(() => SelectedResource);
                }
            }
        }
        public IEnumerable<TypeRessourceDto> TypeRessources
        {
            get
            {
                return _typeRessources;
            }

            set
            {
                if (_typeRessources != value)
                {
                    _typeRessources = value;
                    NotifyPropertyChanged(() => TypeRessources);
                }
            }
        }
        public bool IsLoading
        {
            get
            {
                return _isLoading;
            }

            set
            {
                if (_isLoading != value)
                {
                    _isLoading = value;
                    NotifyPropertyChanged(() => IsLoading);
                }
            }
        }

        #region Commands

        /// <summary>
        /// Command de recherche des utilisateurs
        /// </summary>
        public ICommand SearchCommand
        {
            get { return _searchCommand; }
        }

        public ICommand DoubleClickCommand
        {
            get
            {
                return _doubleClickCommand;
            }
        }

        public ICommand ResetCommand
        {
            get { return _resetCommand; }
        }

        #endregion

        private void InitializeMessenging()
        {
            ObserverUpdateListMessage = _messengingService.CreateObserver<UpdateListMessage>(msg =>
            {
                if (msg.Type == TypeUpdateList.RechercheResource)
                {
                    if (SearchCommand.CanExecute(this))
                        SearchCommand.Execute(this);
                }
            });

            ObserverUpdateListMessage.Subscribe(ThreadOption.UIThread);
        }

        private void DisposeMessenging()
        {
            ObserverUpdateListMessage.Unsubscribe();
        }

        private void InitializeCommands()
        {
            _searchCommand = new ActionCommand(OnSearch);
            _doubleClickCommand = new ActionCommand<RessourceResult>(OnDoubleClickCommand);
            _resetCommand = new ActionCommand(OnReset);
        }

        private void InitializeUI()
        {
            OnReset();

            SearchResult = new ObservableCollection<RessourceResult>();

            IsLoading = false;

            TypeRessources = _referentiel.Referentiel.TypeRessources.WithEmptyItem(() => new TypeRessourceDto() { ID = -1, Libelle = " " });
        }

        private void OnReset()
        {
            Criteres = new SearchResourceCriteriasDto()
            {
                ResourceName = String.Empty,
                TypeResource = -1,
            };
        }

        private void OnSearch()
        {
            if (IsLoading)
                return;

            _depotResource.GetResourcesByCriterias(Criteres, r =>
            {
                foreach (var u in r)
                    SearchResult.Add(u);

                IsLoading = false;

            }, error => _messengingService.Publish(new ErrorMessage(error)));

            SearchResult.Clear();

            IsLoading = true;
        }

        private void OnDoubleClickCommand(RessourceResult selectedResource)
        {
            if (selectedResource != null)
            {
                ResourceHelper.AddResourceTab(selectedResource.ID, _applicationContext, _resourceWrapper, _childWindowService, _messengingService, _depotResource, _builderDetails);
            }
        }

        public override void OnRefreshTab<EntityType>(long id, Action<EntityType> callback)
        {
            throw new NotImplementedException();
        }

        protected override void OnRefreshTabCompleted(Action callback)
        {
            throw new NotImplementedException();
        }
    }
}


text:
package h2o.common.lang;

import h2o.apache.commons.lang.StringUtils;
import h2o.common.util.date.DateUtil;
import h2o.common.util.lang.StringUtil;

import java.time.Instant;
import java.time.LocalTime;
import java.util.Date;
import java.util.Objects;

public final class STime implements OptionalValue<String>, Comparable<STime>, java.io.Serializable {

    private static final long serialVersionUID = -1955168203520594449L;

    public static final STime NULL = new STime();

    private static final String DATE_FMT = "HH:mm:ss";

    /**
     * 时间 HH:mm:ss
     */
    private final String value;

    public STime() {
        this.value = null;
    }

    public STime(String time) {
        this(time, false);
    }

    public STime(String timeStr, boolean direct) {
        if (direct) {
            this.value = timeStr;
        } else {
            this.value = timeStr == null ? null : DateUtil.toString(toDate(timeStr, DATE_FMT), DATE_FMT);
        }
    }

    public STime(int hour, int minute, int second) {
        this(StringUtil.build(StringUtils.leftPad(Integer.toString(hour), 2, '0'), ":",
                StringUtils.leftPad(Integer.toString(minute), 2, '0'), ":",
                StringUtils.leftPad(Integer.toString(second), 2, '0')));
    }

    public STime(LocalTime localTime) {
        this.value = localTime == null ? null : StringUtil.build(
                StringUtils.leftPad(Integer.toString(localTime.getHour()), 2, '0'), ":",
                StringUtils.leftPad(Integer.toString(localTime.getMinute()), 2, '0'), ":",
                StringUtils.leftPad(Integer.toString(localTime.getSecond()), 2, '0'));
    }

    public STime(Instant instant) {
        this.value = instant == null ? null : DateUtil.toString(new Date(instant.toEpochMilli()), DATE_FMT);
    }

    public STime(Date d) {
        this.value = d == null ? null : DateUtil.toString(d, DATE_FMT);
    }

    public STime(STime stime) {
        this.value = stime.value;
    }

    private static Date toDate(String date, String fmt) {
        return SDate.toDate(date, fmt);
    }

    public static STime from(String time, String fmt) {
        return new STime(toDate(time, fmt));
    }

    @Override
    public String getValue() {
        return this.value;
    }

    public String fmt(String fmt) {

        if (DATE_FMT.equals(fmt)) {
            return this.get();
        } else {
            return DateUtil.str2Str(this.get(), DATE_FMT, fmt);
        }

    }

    public String fmt(String fmt, String def) {
        return this.isPresent() ? this.fmt(fmt) : def;
    }

    public LocalTime toLocalTime() {
        return LocalTime.of(this.getHour(), this.getMinute(), this.getSecond());
    }

    public int getHour() {
        return Integer.parseInt(StringUtils.substringBefore(this.get(), ":"));
    }

    public int getMinute() {
        return Integer.parseInt(StringUtils.substringBetween(this.get(), ":"));
    }

    public int getSecond() {
        return Integer.parseInt(StringUtils.substringAfterLast(this.get(), ":"));
    }

    @Override
    public int compareTo(STime other) {

        String l = this.orElse("");
        String r = other.orElse("");

        return l.compareTo(r);

    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        STime sTime = (STime) o;
        return Objects.equals(value, sTime.value);
    }

    @Override
    public int hashCode() {
        return Objects.hash(value);
    }

    @Override
    public String toString() {
        return this.orElse("<null>");
    }

}


text:
    {% for address in addresses %}
    {% if address.choices == "web-site"%}

    {% elif address.choices == "linkedin" %}

    {% else %}

    {% endif %}
    {% endfor %}


text:
TL;DR setup guide
-----------------
.. code-block:: bash

    $ pip install vip_hci


text:
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:minWidth="275dp"
    android:minHeight="72dp"
    android:updatePeriodMillis="0"
    android:initialLayout="@layout/process_widget"
    android:resizeMode="horizontal|vertical"
    >
</appwidget-provider>

<!--
	minWidth,minHeight : 最小的宽高
	updatePeriodMillis : 更新时间,毫秒值,最短不能小于30分钟,设置0跟30分钟一个效果
	previewImage : 预览图片,不设置默认使用应用图标
	initialLayout :widget布局文件
	configure : 可选数据,创建widget之后会启动那个activity
	resizeMode : 设置widget显示尺寸规则,主要用来设置屏幕横竖屏切换保证widget布局不会变形
	widgetCategory : 设置widget显示在什么地方 ,home_screen : 桌面    keyguard:键盘
	initialKeyguardLayout : 设置锁屏的时候显示控件的布局
 -->


text:
package me.ezjs.generator.plugins;

import me.ezjs.generator.mybatis.api.IntrospectedTable;
import me.ezjs.generator.mybatis.api.PluginAdapter;
import me.ezjs.generator.mybatis.api.dom.java.*;

import java.util.List;
import java.util.Properties;

public class ModelCustomizedPlugin extends PluginAdapter {

    @Override
    public void setProperties(Properties properties) {
        super.setProperties(properties);
    }

    public boolean validate(List<String> warnings) {
        return true;
    }

    @Override
    public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass,
                                                 IntrospectedTable introspectedTable) {
        addTableNameAnnotation(introspectedTable, topLevelClass);
        addExtendsRootObject(introspectedTable, topLevelClass);
        return true;
    }

    private void addExtendsRootObject(IntrospectedTable introspectedTable, TopLevelClass topLevelClass) {

        FullyQualifiedJavaType superClass = topLevelClass.getSuperClass();
        if (superClass == null) {
            topLevelClass.setSuperClass("RootObject");
            topLevelClass.addImportedType(new FullyQualifiedJavaType("me.ezjs.core.model.RootObject"));

            // remove id, createTime, modifyTime
        }
    }

    private void addTableNameAnnotation(IntrospectedTable introspectedTable,
                                        TopLevelClass topLevelClass) {
        StringBuilder sb = new StringBuilder();
        sb.append("@TableName(");
        sb.append("\"" + introspectedTable.getFullyQualifiedTable().getIntrospectedTableName() + "\"");
        sb.append(")");
        topLevelClass.addAnnotation(sb.toString());

        topLevelClass.addImportedType(new FullyQualifiedJavaType("me.ezjs.core.model.TableName"));

    }
}


text:
layout: page
title: Barber Enterprises Party
date: 2016-05-24
author: Harry Bowers
tags: weekly links, java
status: published
summary: Pellentesque pharetra, ex ut pulvinar convallis, est felis lacinia.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 01/25/2016
  endDate: 01/29/2016
  ctyhocn: SGUHHHX
  groupCode: BEP
published: true
---
Sed a libero pellentesque, posuere urna in, gravida nunc. Curabitur felis massa, viverra commodo dictum pulvinar, fermentum finibus ex. Aenean rutrum est in magna condimentum viverra. Ut pulvinar et sem eu volutpat. Donec commodo consectetur nisi, a tempus velit pharetra at. Curabitur sit amet feugiat ante. In est ex, vulputate nec arcu vulputate, tincidunt mattis neque. Pellentesque non arcu non neque efficitur elementum. Suspendisse blandit egestas tellus, quis pretium odio venenatis ut. Vestibulum tempor cursus semper. In ut porttitor est. Quisque eget congue tortor. Proin sodales ut mi vitae aliquet. Sed enim erat, vehicula finibus orci sit amet, placerat mollis velit. Ut finibus est nec justo vehicula accumsan. Quisque fringilla lectus sed nunc ultrices rutrum.

1 Mauris eget ante hendrerit, ultrices risus vitae, dapibus felis
1 Fusce malesuada arcu fringilla ipsum facilisis tempus.

Vivamus et erat est. Nam magna tortor, malesuada eu dictum ac, congue ut ipsum. Mauris scelerisque volutpat nulla in euismod. Sed molestie sagittis justo, id mattis enim viverra id. Praesent varius tortor diam, ac porttitor urna elementum ut. Vestibulum a velit eget lectus tristique porta. Morbi tincidunt facilisis leo, nec porta magna tincidunt ut. Quisque tortor est, viverra eget placerat quis, maximus quis enim.


text:
<?php
// src/Klookva/MyBundle/Entity/KlGroup.php
namespace Klookva\UserBundle\Entity;

use FOS\UserBundle\Model\Group as BaseGroup;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="fos_group")
 */
class KlGroup extends BaseGroup
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
     protected $id;

}


text: OCDSpec has been succeeded by [OCDSpec2](https://github.com/ericmeyer/OCDSpec2).


text:
title: "Sonic Orgasms"
date: "2016-10-14"
description: "Hill and Beez are back to run the rule over the new tracks from Avenged Sevenfold and Enter Shikari, there's a potential Download headliner discussion, chat about women's recent rise in rock, reviews on the new albums from The Dillinger Escape Plan, Venom Prison, Red Fang and Joyce Manor and our Album Club on Tool's 10,000 Days includes something that will blow your mind."
soundcloud: "287592644"
---

## News

* [Avenged Sevenfold Release New Single, "The Stage," And Music Video](http://digitalnoisemag.com/watch-avenged-sevenfold-release-new-single-the-stage-and-music-video/)
* [Enter Shikari unveil surprise new single 'Hoodwinker'](http://www.nme.com/news/music/nme-2603-1190003)
* [System of a Down Announce 2017 European Tour Dates](http://loudwire.com/system-of-a-down-2017-european-tour-dates/)
* [Next GHOST Album To Arrive In Fall Of 2017](http://www.blabbermouth.net/news/next-ghost-album-to-arrive-in-fall-of-2017/)
* [Of Mice & Men Postpone Remaining European Tour Dates](http://www.billboard.com/articles/news/7541013/of-mice-men-postpone-european-tour-dates)

## Questions

* **[Kieran Page](https://www.facebook.com/thatsnotmetalpodcast/posts/1972227496337118?comment_id=1972235323003002&comment_tracking=%7B%22tn%22%3A%22R9%22%7D)**: _I've been looking online trying to discover more all famale/female fronted bands, and all I really found were paramore copycats, do you think bands like milk teeth, marmozets, oceans of slumber and employed to serve have changed the perception of women in rock, and do you think this will lead to more unique all female/female fronted bands in the future?_
* **[Lewis Shaw](https://www.facebook.com/thatsnotmetalpodcast/posts/1972227496337118?comment_id=1972255029667698&comment_tracking=%7B%22tn%22%3A%22R9%22%7D)**: _If you could select a band to do an Unplugged set like Nirvana's or AIC's, who would you pick and what would be the setlist?_
* **[Andrew Mac Mahon](https://www.facebook.com/thatsnotmetalpodcast/posts/1972227496337118?comment_id=1972236766336191&comment_tracking=%7B%22tn%22%3A%22R9%22%7D)**: _The impact of album cover art is really lost these days due to the increase in digital sales but what do you think is the best cover art of the last few years?_

## Reviews

* [The Dillinger Escape Plan - Dissociation](https://itunes.apple.com/gb/album/dissociation/id1138306590)
* [Venom Prison - Animus](https://itunes.apple.com/gb/album/animus/id1137258218)
* [Red Fang - Only Ghosts](https://itunes.apple.com/gb/album/only-ghosts/id1131695807)
* [Joyce Manor - Cody](https://itunes.apple.com/gb/album/cody/id1140562404)

## Album Club

* [Tool - 10,000 Days](https://en.wikipedia.org/wiki/10,000_Days)


text:
package com.example.rhymedys.intelligencebj.util;

import android.content.Context;
import android.widget.Toast;

/**
 * Created by Rhymedys on 2016/9/17.
 */
public class ToastUtils {
    public static void showToast(Context context, String msg) {
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }
}


text:
<refentry xmlns="http://docbook.org/ns/docbook"
          xmlns:xlink="http://www.w3.org/1999/xlink"
          xmlns:xi="http://www.w3.org/2001/XInclude"
          xmlns:src="http://nwalsh.com/xmlns/litprog/fragment"
          xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
          version="5.0" xml:id="refentry.date.profile">
<refmeta>
<refentrytitle>refentry.date.profile</refentrytitle>
<refmiscinfo class="other" otherclass="datatype">string</refmiscinfo>
</refmeta>
<refnamediv>
<refname>refentry.date.profile</refname>
<refpurpose>Specifies profile for refentry "date" data</refpurpose>
</refnamediv>

<refsynopsisdiv>
<src:fragment xml:id="refentry.date.profile.frag">
<xsl:param name="refentry.date.profile">
  (($info[//date])[last()]/date)[1]|
  (($info[//pubdate])[last()]/pubdate)[1]
</xsl:param>
</src:fragment>
</refsynopsisdiv>

<refsection><info><title>Description</title></info>

<para>The value of <parameter>refentry.date.profile</parameter> is a
string representing an XPath expression. It is evaluated at run-time
and used only if <parameter>refentry.date.profile.enabled</parameter>
is non-zero. Otherwise, the <tag>refentry</tag> metadata-gathering
logic "hard coded" into the stylesheets is used.</para>

<para> The <literal>man(7)</literal> man page describes this content
as "the date of the last revision". In man pages, it is the content
that is usually displayed in the center footer.</para>

</refsection>
</refentry>


text:
import datetime

# converts given seconds passed since 1 Jan 1970
# back into readable time
def convertback(seconds):
    return datetime.datetime.fromtimestamp(seconds)


text:
class ClearanceMailer < ActionMailer::Base
  include Clearance::App::Models::ClearanceMailer
  include Clearance::App::Models::ClearanceFacebookMailer
end


text:
// Generated by xsd compiler for ios/objective-c
// DO NOT CHANGE!

#import <Foundation/Foundation.h>
#import "PicoClassSchema.h"
#import "PicoPropertySchema.h"
#import "PicoConstants.h"
#import "PicoBindable.h"

@class Finding_Amount;

/**

 Selling details pertaining to the respective item.

 @ingroup FindingServicePortType
*/
@interface Finding_SellingStatus : NSObject <PicoBindable> {

@private
    Finding_Amount *_currentPrice;
    Finding_Amount *_convertedCurrentPrice;
    NSNumber *_bidCount;
    NSString *_sellingState;
    NSString *_timeLeft;
    NSString *_delimiter;
    NSMutableArray *_any;

}

/**

 The current price of the item given in the currency of the site on which
 the item is listed. That is, currentPrice is returned in the original
 listing currency.

 For competitive-bid item listings, currentPrice is the current minimum
 bid price if the listing has no bids, or the current high bid if the
 listing has bids. A Buy It Now price has no effect on currentPrice.

 For Basic Fixed-Price (FixedPrice), Ad Format (AdFormat), and Classified Ad (Classified)
 listings, currentPrice is the current fixed price.

 type : class Finding_Amount
*/
@property (nonatomic, strong) Finding_Amount *currentPrice;

/**

 The listing's current price converted to the currency of the site
 specified in the find request (globalId).

 type : class Finding_Amount
*/
@property (nonatomic, strong) Finding_Amount *convertedCurrentPrice;

/**

 The number of bids that have been placed on the item.

 type : NSNumber, wrapper for primitive int
*/
@property (nonatomic, strong) NSNumber *bidCount;

/**

 Specifies the listing's status in eBay's processing workflow. If an
 item's EndTime is in the past, but there are no details about the buyer
 or high bidder (and the user is not anonymous), you can use sellingState
 information to determine whether eBay has finished processing the
 listing.

 sellingState values:

 Active

 The listing is still live. It is also possible that the auction has
 recently ended, but eBay has not completed the final processing
 (for example, the high bidder is still being determined).

 Canceled

 The listing has been canceled by either the seller or eBay.

 Ended

 The listing has ended and eBay has completed the processing of the
 sale (if any).

 EndedWithSales

 The listing has been ended with sales.

 EndedWithoutSales

 The listing has been ended without sales.

 type : NSString, wrapper for primitive string
*/
@property (nonatomic, strong) NSString *sellingState;

/**

 Time left before the listing ends. The duration is represented in the ISO
 8601 duration format (PnYnMnDTnHnMnS). For listings that have ended, the
 time left is PT0S (zero seconds). See the "duration" type for information
 about this time format.

 type : NSString, wrapper for primitive duration
*/
@property (nonatomic, strong) NSString *timeLeft;

/**
 (public property)

 type : NSString, wrapper for primitive string
*/
@property (nonatomic, strong) NSString *delimiter;

/**
 (public property)

 entry type : PicoAnyElement, wrapper for primitive anyelement
*/

@property (nonatomic, strong) NSMutableArray *any;

@end


text:
{% extends "account/base_auth.html" %}

{% load i18n %}
{% load bootstrapcss %}

{% block title %}{% trans "Login In" %}{% endblock %}

{% block sub_content %}

{% trans 'Login In' %}

        {% trans " Sign in with GitHub" %}

{% trans 'or' %}

    <form id="login_form" method="post" action="{% url 'account_login' %}">
      {% csrf_token %}

        {{ form.login | addclass:'form-control' }}
        {% if form.login.errors %}{{ form.login.errors }}{% endif %}

        {{ form.password | addclass:'form-control' }}
        {% if form.password.errors %}{{ form.password.errors }}{% endif %}

        {{ form.remember }}{% trans " Remember Me" %}
        {% if form.remember.errors %}{{ form.remember.errors }}{% endif %}

      {% if redirect_field_value %}
      <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" />
      {% endif %}
      {% if form.non_field_errors %}

        {{ form.non_field_errors }}

      {% endif %}

        <button type="submit" class="btn btn-primary btn-block">{% trans "Log In" %}</button>

{% trans "Forgot Password?" %}

    </form>

  {% blocktrans %}Don't have an account? Sign Up.{% endblocktrans %}

{% endblock %}


text:
package org.apache.amaterasu.executor.mesos.executors

import java.io.{ByteArrayInputStream, ByteArrayOutputStream, File}

import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule

import org.apache.amaterasu.common.dataobjects.{ExecData, TaskData}
import org.apache.amaterasu.common.logging.Logging

import org.apache.mesos.Protos._
import org.apache.mesos.protobuf.ByteString
import org.apache.mesos.{Executor, ExecutorDriver, MesosExecutorDriver}
import org.apache.spark.SparkContext

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.util.{Failure, Success}

import collection.JavaConverters._

/**
  * Created by roadan on 1/1/16.
  */
class ActionsExecutor extends Executor with Logging {

  var master: String = _
  var executorDriver: ExecutorDriver = _
  var sc: SparkContext = _
  var jobId: String = _
  var actionName: String = _
  //  var sparkScalaRunner: SparkScalaRunner = _
  //  var pySparkRunner: PySparkRunner = _
  var notifier: MesosNotifier = _
  var providersFactory: ProvidersFactory = _

  val mapper = new ObjectMapper()
  mapper.registerModule(DefaultScalaModule)

  override def shutdown(driver: ExecutorDriver) = {

  }

  override def killTask(driver: ExecutorDriver, taskId: TaskID) = ???

  override def disconnected(driver: ExecutorDriver) = ???

  override def reregistered(driver: ExecutorDriver, slaveInfo: SlaveInfo) = {
    this.executorDriver = driver
  }

  override def error(driver: ExecutorDriver, message: String) = {

    val status = TaskStatus.newBuilder
      .setData(ByteString.copyFromUtf8(message))
      .setState(TaskState.TASK_ERROR).build()

    driver.sendStatusUpdate(status)

  }

  override def frameworkMessage(driver: ExecutorDriver, data: Array[Byte]) = ???

  override def registered(driver: ExecutorDriver, executorInfo: ExecutorInfo, frameworkInfo: FrameworkInfo, slaveInfo: SlaveInfo): Unit = {

    this.executorDriver = driver
    val data = mapper.readValue(new ByteArrayInputStream(executorInfo.getData.toByteArray), classOf[ExecData])

    notifier = new MesosNotifier(driver)
    notifier.info(s"Executor ${executorInfo.getExecutorId.getValue} registered")
    val outStream = new ByteArrayOutputStream()
    providersFactory = ProvidersFactory(data, jobId, outStream, notifier, executorInfo.getExecutorId.getValue)

  }

  override def launchTask(driver: ExecutorDriver, taskInfo: TaskInfo): Unit = {

    notifier.info(s"launching task: ${taskInfo.getTaskId.getValue}")
    log.debug(s"launching task: $taskInfo")
    val status = TaskStatus.newBuilder
      .setTaskId(taskInfo.getTaskId)
      .setState(TaskState.TASK_STARTING).build()
    driver.sendStatusUpdate(status)
    val task = Future {

      val taskData = mapper.readValue(new ByteArrayInputStream(taskInfo.getData.toByteArray), classOf[TaskData])

      val status = TaskStatus.newBuilder
        .setTaskId(taskInfo.getTaskId)
        .setState(TaskState.TASK_RUNNING).build()
      driver.sendStatusUpdate(status)
      val runner = providersFactory.getRunner(taskData.groupId, taskData.typeId)
      runner match {
        case Some(r) => r.executeSource(taskData.src, actionName, taskData.exports.asJava)
        case None =>
          notifier.error("", s"Runner not found for group: ${taskData.groupId}, type ${taskData.typeId}. Please verify the tasks")
          None
      }

    }

    task onComplete {

      case Failure(t) =>
        println(s"launching task failed: ${t.getMessage}")
        System.exit(1)

      case Success(ts) =>

        driver.sendStatusUpdate(TaskStatus.newBuilder()
          .setTaskId(taskInfo.getTaskId)
          .setState(TaskState.TASK_FINISHED).build())
        notifier.info(s"complete task: ${taskInfo.getTaskId.getValue}")

    }

  }

}

object ActionsExecutorLauncher extends Logging {

  def main(args: Array[String]) {
    System.loadLibrary("mesos")
    log.debug("Starting a new ActionExecutor")

    val executor = new ActionsExecutor
    executor.jobId = args(0)
    executor.master = args(1)
    executor.actionName = args(2)

    val driver = new MesosExecutorDriver(executor)
    driver.run()
  }

}


text:
extern "C" {
CONCEPT_DLL_API ON_CREATE_CONTEXT  MANAGEMENT_PARAMETERS;
CONCEPT_DLL_API ON_DESTROY_CONTEXT MANAGEMENT_PARAMETERS;

CONCEPT_FUNCTION(DBOpen)
CONCEPT_FUNCTION(DBClose)
CONCEPT_FUNCTION(DBError)
CONCEPT_FUNCTION(DBErrorCode)
CONCEPT_FUNCTION(DBChanges)
CONCEPT_FUNCTION(DBLastRowID)
CONCEPT_FUNCTION(DBNewStmt)
CONCEPT_FUNCTION(DBBind)
CONCEPT_FUNCTION(DBNameBind)
CONCEPT_FUNCTION(DBTimeout)

CONCEPT_FUNCTION(DBBLOBBind)
CONCEPT_FUNCTION(DBBLOBNameBind)

CONCEPT_FUNCTION(DBFree)
CONCEPT_FUNCTION(DBColumns)
CONCEPT_FUNCTION(DBFirst)
CONCEPT_FUNCTION(DBNext)
CONCEPT_FUNCTION(DBData)
CONCEPT_FUNCTION(DBDataRead)
CONCEPT_FUNCTION(DBDataWrite)
CONCEPT_FUNCTION(DBQuery)
CONCEPT_FUNCTION(DBReset)
CONCEPT_FUNCTION(DBClearBindings)
CONCEPT_FUNCTION(DBColumnDeclType)
CONCEPT_FUNCTION(DBColumnName)
CONCEPT_FUNCTION(DBColumnType)
CONCEPT_FUNCTION(DBWrap)
CONCEPT_FUNCTION(DBParamCount)
CONCEPT_FUNCTION(DBBLOBDataBind)
CONCEPT_FUNCTION(DBBLOBNameDataBind)
}
#endif // __LIBRARY_H


text:
#import <Cocoa/Cocoa.h>
#import "GoogleExport.h"
#import <Keychain/Keychain.h>

@interface AuthenticateController : NSObject {
	NSUserDefaults *defaults;
	IBOutlet NSWindow *panel;
	IBOutlet NSTextField *errorLabel;
	IBOutlet NSTextField *usernameField;
	IBOutlet NSTextField *passwordField;
	IBOutlet NSButton *signInButton;
	IBOutlet id exportController;
	@private NSString *username;
	@private NSString *password;
	@private Keychain *myKeyChain;
	@private BOOL getDefaultPassword;
}

- (void)startKeychainSession;
- (void)fillAuthenticationFields;

- (IBAction)closeLogPanel:(id)sender;
- (IBAction)signIn:(id)sender;

@property (retain, readonly) NSWindow *panel;
@property (retain, readonly) NSString *username;
@property (retain, readonly) NSString *password;
@property BOOL getDefaultPassword;
@property (retain) NSUserDefaults *defaults;
@property (retain) NSTextField *errorLabel;
@property (retain) NSTextField *usernameField;
@property (retain) NSTextField *passwordField;
@property (retain) NSButton *signInButton;
@property (retain) id exportController;
@property (retain) Keychain *myKeyChain;
@end


text:
extern crate rusoto_mock;

use crate::generated::{
    GetQueueUrlError, GetQueueUrlRequest, MessageAttributeValue, ReceiveMessageRequest,
    SendMessageRequest, Sqs, SqsClient,
};
use std::collections::HashMap;

use self::rusoto_mock::*;
use rusoto_core::param::Params;
use rusoto_core::signature::SignedRequest;
use rusoto_core::signature::SignedRequestPayload;
use rusoto_core::{Region, RusotoError};
use serde_urlencoded;

#[tokio::test]
async fn should_serialize_map_parameters_in_request_body() {
    let mock = MockRequestDispatcher::with_status(200)
        .with_body(
            r#"<?xml version="1.0" encoding="UTF-8"?>
        <SendMessageResponse>
            <SendMessageResult>
                <MD5OfMessageBody>
                    fafb00f5732ab283681e124bf8747ed1
                </MD5OfMessageBody>
                <MD5OfMessageAttributes>
            3ae8f24a165a8cedc005670c81a27295
                </MD5OfMessageAttributes>
                <MessageId>
                    5fea7756-0ea4-451a-a703-a558b933e274
                </MessageId>
            </SendMessageResult>
            <ResponseMetadata>
                <RequestId>
                    27daac76-34dd-47df-bd01-1f6e873584a0
                </RequestId>
            </ResponseMetadata>
        </SendMessageResponse>"#,
        )
        .with_request_checker(|request: &SignedRequest| {
            println!("{:#?}", request.params);

            assert_eq!("POST", request.method);
            assert_eq!("/", request.path);
            if let Some(SignedRequestPayload::Buffer(ref buffer)) = request.payload {
                let params: Params = serde_urlencoded::from_bytes(buffer).unwrap();
                assert_eq!(
                    Some(&Some("test_attribute_name".to_owned())),
                    params.get("MessageAttribute.1.Name")
                );
                assert_eq!(
                    Some(&Some("test_attribute_value".to_owned())),
                    params.get("MessageAttribute.1.Value.StringValue")
                );
                assert_eq!(
                    Some(&Some("String".to_owned())),
                    params.get("MessageAttribute.1.Value.DataType")
                );
            } else {
                panic!("Unexpected request.payload: {:?}", request.payload);
            }
        });

    let mut message_attributes = HashMap::new();

    message_attributes.insert(
        "test_attribute_name".to_owned(),
        MessageAttributeValue {
            string_value: Some("test_attribute_value".to_owned()),
            data_type: "String".to_owned(),
            ..Default::default()
        },
    );
    let request = SendMessageRequest {
        message_body: "foo".to_owned(),
        queue_url: "bar".to_owned(),
        message_attributes: Some(message_attributes),
        ..Default::default()
    };

    let client = SqsClient::new_with(mock, MockCredentialsProvider, Region::UsEast1);
    let _result = client.send_message(request).await.unwrap();
}

#[tokio::test]
async fn should_fix_issue_323() {
    let mock = MockRequestDispatcher::with_status(200)
        .with_body(
            r#"<?xml version="1.0" encoding="UTF-8"?>
        <ReceiveMessageResponse>
            <ReceiveMessageResult>
            <Message>
                <MessageId>
                5fea7756-0ea4-451a-a703-a558b933e274
                </MessageId>
                <ReceiptHandle>
                MbZj6wDWli+JvwwJaBV+3dcjk2YW2vA3+STFFljTM8tJJg6HRG6PYSasuWXPJB+Cw
                Lj1FjgXUv1uSj1gUPAWV66FU/WeR4mq2OKpEGYWbnLmpRCJVAyeMjeU5ZBdtcQ+QE
                auMZc8ZRv37sIW2iJKq3M9MFx1YvV11A2x/KSbkJ0=
                </ReceiptHandle>
                <MD5OfBody>
                fafb00f5732ab283681e124bf8747ed1
                </MD5OfBody>
                This is a test message
                <Attribute>
                <Name>SenderId</Name>
                <Value>195004372649</Value>
                </Attribute>
            </Message>
            </ReceiveMessageResult>
            <ResponseMetadata>
            <RequestId>
                b6633655-283d-45b4-aee4-4e84e0ae6afa
            </RequestId>
            </ResponseMetadata>
        </ReceiveMessageResponse>"#,
        )
        .with_request_checker(|request: &SignedRequest| {
            assert_eq!("POST", request.method);
            assert_eq!("/", request.path);
            if let Some(SignedRequestPayload::Buffer(ref buffer)) = request.payload {
                let params: Params = serde_urlencoded::from_bytes(buffer).unwrap();
                assert_eq!(
                    params.get("Action"),
                    Some(&Some("ReceiveMessage".to_owned()))
                );
                assert_eq!(
                    params.get("MaxNumberOfMessages"),
                    Some(&Some("1".to_owned()))
                );
                assert_eq!(params.get("VisibilityTimeout"), Some(&Some("2".to_owned())));
                assert_eq!(params.get("WaitTimeSeconds"), Some(&Some("3".to_owned())));
                assert_eq!(params.get("Integer"), None);
            } else {
                panic!("Unexpected request.payload: {:?}", request.payload);
            }
        });

    let request = ReceiveMessageRequest {
        max_number_of_messages: Some(1),
        queue_url: "foo".to_owned(),
        visibility_timeout: Some(2),
        wait_time_seconds: Some(3),
        ..Default::default()
    };

    let client = SqsClient::new_with(mock, MockCredentialsProvider, Region::UsEast1);
    let _result = client.receive_message(request).await.unwrap();
}

#[tokio::test]
async fn test_parse_queue_does_not_exist_error() {
    let mock = MockRequestDispatcher::with_status(400).with_body(
        r#"<?xml version="1.0"?>
        <ErrorResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/">
            <Error>
                <Type>Sender</Type>
                AWS.SimpleQueueService.NonExistentQueue
                <Message>The specified queue does not exist for this wsdl version.</Message>
                <Detail/>
            </Error>
            <RequestId>8f8f9957-c0d9-536a-9ca6-ca7483be06ad</RequestId>
        </ErrorResponse>"#,
    );

    let request = GetQueueUrlRequest {
        queue_name: "no-such-queue".to_owned(),
        ..Default::default()
    };

    let client = SqsClient::new_with(mock, MockCredentialsProvider, Region::UsEast1);
    let result = client.get_queue_url(request).await;
    assert!(result.is_err());
    let err = result.err().unwrap();
    assert_eq!(
        RusotoError::Service(GetQueueUrlError::QueueDoesNotExist(
            "The specified queue does not exist for this wsdl version.".to_owned()
        )),
        err
    );
}

#[tokio::test]
async fn should_deserialize_map_parameters_in_response_body() {
    let mock = MockRequestDispatcher::with_status(200)
        .with_body(
            r#"<?xml version="1.0" encoding="UTF-8"?>
        <ReceiveMessageResponse>
            <ReceiveMessageResult>
            <Message>
                <MessageId>
                    5fea7756-0ea4-451a-a703-a558b933e274
                </MessageId>
                <ReceiptHandle>
                    MbZj6wDWli+JvwwJaBV+3dcjk2YW2vA3+STFFljTM8tJJg6HRG6PYSasuWXPJB+Cw
                    Lj1FjgXUv1uSj1gUPAWV66FU/WeR4mq2OKpEGYWbnLmpRCJVAyeMjeU5ZBdtcQ+QE
                    auMZc8ZRv37sIW2iJKq3M9MFx1YvV11A2x/KSbkJ0=
                </ReceiptHandle>
                <MD5OfBody>
                    fafb00f5732ab283681e124bf8747ed1
                </MD5OfBody>
                This is a test message
                <MessageAttribute>
                    <Name>test_attribute_name</Name>
                    <Value>
                        <DataType>String</DataType>
                        <StringValue>test_attribute_value</StringValue>
                    </Value>
                </MessageAttribute>
            </Message>
            </ReceiveMessageResult>
            <ResponseMetadata>
            <RequestId>
                b6633655-283d-45b4-aee4-4e84e0ae6afa
            </RequestId>
            </ResponseMetadata>
        </ReceiveMessageResponse>"#,
        );

    let request = ReceiveMessageRequest {
        queue_url: "foo".to_owned(),
        ..Default::default()
    };

    let client = SqsClient::new_with(mock, MockCredentialsProvider, Region::UsEast1);
    let result = client.receive_message(request).await;
    assert!(result.is_ok());

    let mut messages = result.unwrap().messages.unwrap();
    assert_eq!(1, messages.len());

    let message = messages.pop().unwrap();
    let mut message_attributes = HashMap::new();
    message_attributes.insert(
        "test_attribute_name".to_owned(),
        MessageAttributeValue {
            string_value: Some("test_attribute_value".to_owned()),
            data_type: "String".to_owned(),
            ..Default::default()
        },
    );

    assert_eq!(
        message_attributes,
        message.message_attributes.unwrap(),
    );
}


text:
package java.util;

public class StringTokenizer implements Enumeration {
  private final String in;
  private String delimiters;
  private final boolean includeDelimiters;
  private int position;

  public StringTokenizer(String in, String delimiters,
                         boolean includeDelimiters)
  {
    this.in = in;
    this.delimiters = delimiters;
    this.includeDelimiters = includeDelimiters;
  }

  public StringTokenizer(String in, String delimiters) {
    this(in, delimiters, false);
  }

  public StringTokenizer(String in) {
    this(in, " \t\r\n\f");
  }

  private boolean isDelimiter(char c) {
    return delimiters.indexOf(c) >= 0;
  }

  public int countTokens() {
    int count = 0;
    boolean sawNonDelimiter = false;
    for (int i = position; i < in.length(); ++i) {
      if (isDelimiter(in.charAt(i))) {
        if (sawNonDelimiter) {
          sawNonDelimiter = false;
          ++ count;
        }

        if (includeDelimiters) {
          ++ count;
        }
      } else {
        sawNonDelimiter = true;
      }
    }

    if (sawNonDelimiter) {
      ++ count;
    }

    return count;
  }

  public boolean hasMoreTokens() {
    for (int i = position; i < in.length(); ++i) {
      if (isDelimiter(in.charAt(i))) {
        if (includeDelimiters) {
          return true;
        }
      } else {
        position = i;
        return true;
      }
    }
    return false;
  }

  public String nextToken() {
    for (int i = position; i < in.length(); ++i) {
      if (isDelimiter(in.charAt(i))) {
        if (includeDelimiters) {
          return in.substring(i, i + 1);
        }
      } else {
        position = i;
        while (position < in.length() && ! isDelimiter(in.charAt(position))) {
          ++ position;
        }
        return in.substring(i, position);
      }
    }
    throw new NoSuchElementException();
  }

  public String nextToken(String delimiters) {
    this.delimiters = delimiters;
    return nextToken();
  }

  public boolean hasMoreElements() {
    return hasMoreTokens();
  }

  public Object nextElement() {
    return nextToken();
  }

}


text:
package com.emc.ecs.management.sdk.model;

import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;
import java.util.Map;

@XmlRootElement(name = "delete_bucket_tags")
public class BucketTagsParamDelete extends BucketTagsParam {

    public BucketTagsParamDelete(){
        super();
    };

    public BucketTagsParamDelete(String namespace, List<Map<String, String>> tags) {
        super(namespace, tags);
    }
}


text:
Форма загрузки Телеграммы ОАО «РЖД» о проведении переписи контейнерного парка с указанием даты переписи

        <form class="form-horizontal css-form" autocomplete="off" name="formUploadFile" id="formUploadFile" style="border: none !important;" novalidate>

                        Дата переписи
                         обязательный

                            <input type="text"
                                   name="dateCensus"
                                   style="z-index: 4;"
                                   id="dateCensus"
                                   class="form-control textSizeInput"
                                   uib-datepicker-popup="dd.MM.yyyy"
                                   popup-placement="bottom-right"
                                   ng-model="tasksDetailObj.formUploadFile.dateCensus"
                                   is-open="opened"
                                   min-date="'1090-06-22'"
                                   max-date="'2090-06-22'"
                                   placeholder="Дата переписи"
                                   ng-required="true"
                                   close-text="Закрыть"
                                   current-text="Сегодня"
                                   clear-text="Очистить"/>

                    <button type="button" style="z-index: 3; height: 32px" class="btn btn-default" ng-click="open($event)"></button>

                        Пример даты: 18.09.1989

        </form>


text:
package org.bitcoins.crypto

import scodec.bits.ByteVector

import scala.util.Try

/** Created by chris on 2/26/16.
  * Trait to implement ubiquitous factory functions across our codebase
  */
abstract class Factory[+T] {

  /** Creates a T out of a hex string. */
  def fromHex(hex: String): T = fromBytes(CryptoBytesUtil.decodeHex(hex))

  /** Deserializes the given hex string to a T
    * If the hex is not correct, [[None]] is returned
    */
  def fromHexOpt(hex: String): Option[T] = {
    fromHexT(hex).toOption
  }

  /** Deserializes the given hex string
    * if the hex is not correct, we give you a [[Failure]]
    */
  def fromHexT(hex: String): Try[T] = {
    Try(fromHex(hex))
  }

  /** Creates a T out of a hex string in little endian. */
  def fromHexLE(hex: String): T = fromBytesLE(CryptoBytesUtil.decodeHex(hex))

  /** Creates a T out of a sequence of bytes. */
  def fromBytes(bytes: ByteVector): T

  /** Deserializes the given [[ByteVector]] to a T
    * If the [[ByteVector]] is not correct, [[None]] is returned
    */
  def fromBytesOpt(bytes: ByteVector): Option[T] = {
    fromBytesT(bytes).toOption
  }

  /** Deserializes the given [[ByteVector]] string
    * if the [[ByteVector]] is not correct, we give you a [[Failure]]
    */
  def fromBytesT(bytes: ByteVector): Try[T] = {
    Try(fromBytes(bytes))
  }

  /** Creates a T out of a sequence of bytes in little endian. */
  def fromBytesLE(bytes: ByteVector): T = fromBytes(bytes.reverse)

  /** Creates a T out of a sequence of bytes. */
  def apply(bytes: ByteVector): T = fromBytes(bytes)

  /** Creates a T from a hex string. */
  def apply(hex: String): T = fromHex(hex)

  /** Allows a `def foo[C: Factory]()` construction. */
  implicit def self: Factory[T] = this
}


text:
//
//  photoLibrary.m
//  PhotoAlbum
//
//  Created by Robert on 15/3/2.
//  Copyright (c) 2015年 NationSky. All rights reserved.
//

#import "photoLibrary.h"

@interface photoLibrary()

@property (nonatomic, strong) UIViewController *vc;

@end

@implementation photoLibrary

static photoLibrary *sharedPhotoLibrary;

/**
 *  单例方法
 *
 *  @return 实例变量
 */
+ (photoLibrary *)sharephotoLibrary{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedPhotoLibrary = [[self alloc] init];
    });
    return sharedPhotoLibrary;
}

/**
 *  show actionSheet
 *
 *  @param viewController 父视图控制器
 */
- (void)getPhotoLibraryInSuperViewController:(UIViewController*)viewController{
    self.delegate = (id)viewController;
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"相机",@"相册", nil];
    [actionSheet showInView:viewController.view];

    _vc = viewController;
}
#pragma mark -
#pragma mark UIActionSheetDelegate
- (void)willPresentActionSheet:(UIActionSheet *)actionSheet{
    NSLog(@"%@",actionSheet.subviews);
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.allowsEditing = YES;
    switch (buttonIndex) {
        case 0:
            SET_PICKER_SOURCE_TYPE(imagePicker, UIImagePickerControllerSourceTypeCamera);
            break;
        case 1:
            SET_PICKER_SOURCE_TYPE(imagePicker, UIImagePickerControllerSourceTypePhotoLibrary);
            break;
        default:
            return;
    }
    [_vc presentViewController:imagePicker animated:YES completion:nil];
}
#pragma mark -
#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    // 原图
    UIImage *originalImage = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    // 编辑图
    UIImage *editedImage = [info objectForKey:@"UIImagePickerControllerEditedImage"];

    [self.delegate getPhotoSucceedOriginalImage:originalImage editedImage:editedImage];
    [picker dismissViewControllerAnimated:YES completion:nil];
}
@end


text:
package org.h2.test.rowlock;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.h2.api.ErrorCode;
import org.h2.test.TestBase;
import org.h2.util.Task;

/**
 * Row level locking tests.
 */
public class TestRowLocks extends TestBase {

    /**
     * The statements used in this test.
     */
    Statement s1, s2;

    private Connection c1, c2;

    /**
     * Run just this test.
     *
     * @param a ignored
     */
    public static void main(String... a) throws Exception {
        TestBase.createCaller().init().test();
    }

    @Override
    public void test() throws Exception {
        testSetMode();
        testCases();
        deleteDb(getTestName());
    }

    private void testSetMode() throws SQLException {
        deleteDb(getTestName());
        c1 = getConnection(getTestName());
        Statement stat = c1.createStatement();
        stat.execute("SET LOCK_MODE 2");
        ResultSet rs = stat.executeQuery("call lock_mode()");
        rs.next();
        assertEquals("2", rs.getString(1));
        c1.close();
    }

    private void testCases() throws Exception {
        deleteDb(getTestName());
        c1 = getConnection(getTestName() + ";MVCC=TRUE");
        s1 = c1.createStatement();
        s1.execute("SET LOCK_TIMEOUT 10000");
        s1.execute("CREATE TABLE TEST AS " +
                "SELECT X ID, 'Hello' NAME FROM SYSTEM_RANGE(1, 3)");
        c1.commit();
        c1.setAutoCommit(false);
        s1.execute("UPDATE TEST SET NAME='Hallo' WHERE ID=1");

        c2 = getConnection(getTestName());
        c2.setAutoCommit(false);
        s2 = c2.createStatement();

        assertEquals("Hallo", getSingleValue(s1,
                "SELECT NAME FROM TEST WHERE ID=1"));
        assertEquals("Hello", getSingleValue(s2,
                "SELECT NAME FROM TEST WHERE ID=1"));

        s2.execute("UPDATE TEST SET NAME='Hallo' WHERE ID=2");
        assertThrows(ErrorCode.LOCK_TIMEOUT_1, s2).
                executeUpdate("UPDATE TEST SET NAME='Hi' WHERE ID=1");
        c1.commit();
        c2.commit();

        assertEquals("Hallo", getSingleValue(s1,
                "SELECT NAME FROM TEST WHERE ID=1"));
        assertEquals("Hallo", getSingleValue(s2,
                "SELECT NAME FROM TEST WHERE ID=1"));

        s2.execute("UPDATE TEST SET NAME='H1' WHERE ID=1");
        Task task = new Task() {
            @Override
            public void call() throws SQLException {
                s1.execute("UPDATE TEST SET NAME='H2' WHERE ID=1");
            }
        };
        task.execute();
        Thread.sleep(100);
        c2.commit();
        task.get();
        c1.commit();
        assertEquals("H2", getSingleValue(s1,
                "SELECT NAME FROM TEST WHERE ID=1"));
        assertEquals("H2", getSingleValue(s2,
                "SELECT NAME FROM TEST WHERE ID=1"));

        c1.close();
        c2.close();
    }

    private static String getSingleValue(Statement stat, String sql)
            throws SQLException {
        ResultSet rs = stat.executeQuery(sql);
        return rs.next() ? rs.getString(1) : null;
    }

}


text:
var DisplayConfig = require('./config.display');

/**
 * Configuration options and remapping functions for the power system.
 *
 * The power system is made up of power units, which contain power supplies. Our power system is
 * configured such that each power unit handles a 3x2 portion of the display. Each power unit
 * contains 2 individual supplies, and each supply contains 1 AC input and 3 DC outputs,
 *
 * The remapping functions are used for converting between display unit column / row numbers,
 * power unit numbers, and relay numbers.
 *
 * Mod Note: You should only need to change the hardcoded numerical values here, as the rest are
 *           calculated automatically from those values.
 */
var PowerConfig = pc = module.exports = {};

/**
 * Number of unit rows powered by a single power unit
 */
PowerConfig.unitRowsPerPowerUnit = 3;

/**
 * Number of unit columns powered by a single power unit
 */
PowerConfig.unitColsPerPowerUnit = 2;

/**
 * Number of DC outputs in a single supply
 */
PowerConfig.dcOutputsPerSupply = 3;

/**
 * Number of AC inputs in a single supply
 */
PowerConfig.acInputsPerSupply = 1;

/**
 * Number of control relays in a single supply
 */
PowerConfig.controlRelaysPerSupply = 1;

/**
 * Number of units powered by a single power unit
 */
PowerConfig.unitsPerPowerUnit = pc.unitRowsPerPowerUnit * pc.unitColsPerPowerUnit;

/**
 * Number of DC outputs in a single power unit
 */
PowerConfig.dcOutputsPerUnit = pc.unitColsPerPowerUnit * pc.dcOutputsPerSupply;

/**
 * Number of AC inputs in a single power unit
 */
PowerConfig.acInputsPerUnit = pc.acInputsPerSupply * pc.unitColsPerPowerUnit;

/**
 * Number of control relays in a single power unit
 */
PowerConfig.controlRelaysPerUnit = pc.controlRelaysPerSupply * pc.unitColsPerPowerUnit;

/**
 * Total number of power units in the display
 */
PowerConfig.numPowerUnits = DisplayConfig.numUnits / pc.unitsPerPowerUnit;

/**
 * Returns the power unit number which powers the unit in a given row and column
 */
PowerConfig.unitRowColToUnitNumber = function(row, col) {
  return Math.floor(col / pc.unitColsPerPowerUnit);
}

/**
 * Returns the relay column number that belongs to a given unit column
 */
PowerConfig.unitColToRelayCol = function(col) {
  return col % pc.unitColsPerPowerUnit;
}


text:
From SimpleCV import Camera
# Initialize the camera
cam = Camera()
# Loop to continuously get images
while True:
    # Get Image from camera
    img = cam.getImage()
    # Make image black and white
    img = img.binarize()
    # Draw the text "Hello World" on image
    img.drawText("Hello World!")
    # Show the image
    img.show()