text:
<meta http-equiv="Content-Type" content="text/html\; charset=UTF-8">
<title>Yenten; cryptocurrency of the cpu, by the cpu, for the cpu</title>

円天

Yenten is a cryptocurrency of the cpu, by the cpu, for the cpu.

No ASIC. ASIC is for girls and kids.

Abstruct

Yenten is made for reducing MEGA WASTE of electricity by ASIC on the earth.

When this cryptocurrency spreads, reduction of CO2 emission would be realize by Yenten.

Algorithm: YescryptR16 (GPU was slower than CPU)

Block time: 2.0 minutes

Max Block size: 2M

Block reward of block #1: 50 YTN

Total YTN setting: 84,000,000 YTN

Calculated max YTN: about 80,000,000 YTN

SubsidyHalvingInterval: 800,000 blocks

Difficulty re-target: every block (DarkGravityWave v3-1)

Premine: none

P2P Port: 9981

RPC Port: 9982

Roadmap

2017: CPU mining, exchange, etc...

2018: CPU mining, exchange, etc...

2019: CPU mining, exchange, etc...

20XX: 1Yen < 1Yenten.

FAQ

もちろん俺らは払うで。🤜💥🤛

Q: どう払うん?

A: 円天で!💪

Of cource, we resist to ASIC...🤜💥🤛

Q: ...How???

A: By Yenten!!!💪

Download

v2.0.1

Binary   Source

Pool

You can make your pool by customizing CoiniumServ on Windows, YIIMP on Linux, etc.

search existing pools

Block Explorer

Yenten block explorer.

Exchange

CoinsMarkets

Stocks.exchange

ICQBASE(YTN/BTC)

ICQBASE(YTN/LTC)

CREX24

OpenTrade(YTN/MC)

GRAVIEX

TradeSatoshi

Bisq(P2P Exchange network)

BitcoinTalk Forum

cpuminer-opt for mining

<audio autoplay preload="auto" volume=0.2>
<source src="Splendid_reisiun.mp3">

HTML5 not supported browser

</audio>

Yenten project 2017-2018

<canvas id="c" width="256" height="320"></canvas>


text:
from django.db import models
from django.utils.translation import gettext_lazy as _
from form_designer.models import FormDefinition

from fluent_contents.models import ContentItem, ContentItemManager

class FormDesignerLink(ContentItem):
    form_definition = models.ForeignKey(
        FormDefinition, on_delete=models.PROTECT, verbose_name=_("Form")
    )

    objects = ContentItemManager()  # Avoid Django 1.10 migrations

    class Meta:
        verbose_name = _("Form link")
        verbose_name_plural = _("Form links")

    def __str__(self):
        return self.form_definition.title if self.form_definition else ""

redpajama_set_name: RedPajamaGithub


text:
=pod

=head1 NAME

RSA_sign, RSA_verify - RSA signatures

=head1 SYNOPSIS

 #include <openssl/rsa.h>

The following functions have been deprecated since OpenSSL 3.0, and can be
hidden entirely by defining B<OPENSSL_API_COMPAT> with a suitable version value,
see L<openssl_user_macros(7)>:

 int RSA_sign(int type, const unsigned char *m, unsigned int m_len,
              unsigned char *sigret, unsigned int *siglen, RSA *rsa);

 int RSA_verify(int type, const unsigned char *m, unsigned int m_len,
                unsigned char *sigbuf, unsigned int siglen, RSA *rsa);

=head1 DESCRIPTION

All of the functions described on this page are deprecated.
Applications should instead use L<EVP_PKEY_sign_init(3)>, L<EVP_PKEY_sign(3)>,
L<EVP_PKEY_verify_init(3)> and L<EVP_PKEY_verify(3)>.

RSA_sign() signs the message digest B<m> of size B<m_len> using the
private key B<rsa> using RSASSA-PKCS1-v1_5 as specified in RFC 3447. It
stores the signature in B<sigret> and the signature size in B<siglen>.
B<sigret> must point to RSA_size(B<rsa>) bytes of memory.
Note that PKCS #1 adds meta-data, placing limits on the size of the
key that can be used.
See L<RSA_private_encrypt(3)> for lower-level
operations.

B<type> denotes the message digest algorithm that was used to generate
B<m>.
If B<type> is B<NID_md5_sha1>,
an SSL signature (MD5 and SHA1 message digests with PKCS #1 padding
and no algorithm identifier) is created.

RSA_verify() verifies that the signature B<sigbuf> of size B<siglen>
matches a given message digest B<m> of size B<m_len>. B<type> denotes
the message digest algorithm that was used to generate the signature.
B<rsa> is the signer's public key.

=head1 RETURN VALUES

RSA_sign() returns 1 on success.
RSA_verify() returns 1 on successful verification.

The error codes can be obtained by L<ERR_get_error(3)>.

=head1 CONFORMING TO

SSL, PKCS #1 v2.0

=head1 SEE ALSO

L<ERR_get_error(3)>,
L<RSA_private_encrypt(3)>,
L<RSA_public_decrypt(3)>

=head1 HISTORY

All of these functions were deprecated in OpenSSL 3.0.

=head1 COPYRIGHT

Copyright 2000-2020 The OpenSSL Project Authors. All Rights Reserved.

Licensed under the Apache License 2.0 (the "License").  You may not use
this file except in compliance with the License.  You can obtain a copy
in the file LICENSE in the source distribution or at
L<https://www.openssl.org/source/license.html>.

=cut


text:
/* vi: set sw=4 ts=4: */
/* `time' utility to display resource usage of processes.
   Copyright (C) 1990, 91, 92, 93, 96 Free Software Foundation, Inc.

   Licensed under GPL version 2, see file LICENSE in this tarball for details.
*/
/* Originally written by David Keppel <pardo@cs.washington.edu>.
   Heavily modified by David MacKenzie <djm@gnu.ai.mit.edu>.
   Heavily modified for busybox by Erik Andersen <andersen@codepoet.org>
*/

#include "libbb.h"

/* Information on the resources used by a child process.  */
typedef struct {
	int waitstatus;
	struct rusage ru;
	unsigned elapsed_ms;	/* Wallclock time of process.  */
} resource_t;

/* msec = milliseconds = 1/1,000 (1*10e-3) second.
   usec = microseconds = 1/1,000,000 (1*10e-6) second.  */

#define UL unsigned long

static const char default_format[] ALIGN1 = "real\t%E\nuser\t%u\nsys\t%T";

/* The output format for the -p option .*/
static const char posix_format[] ALIGN1 = "real %e\nuser %U\nsys %S";

/* Format string for printing all statistics verbosely.
   Keep this output to 24 lines so users on terminals can see it all.*/
static const char long_format[] ALIGN1 =
	"\tCommand being timed: \"%C\"\n"
	"\tUser time (seconds): %U\n"
	"\tSystem time (seconds): %S\n"
	"\tPercent of CPU this job got: %P\n"
	"\tElapsed (wall clock) time (h:mm:ss or m:ss): %E\n"
	"\tAverage shared text size (kbytes): %X\n"
	"\tAverage unshared data size (kbytes): %D\n"
	"\tAverage stack size (kbytes): %p\n"
	"\tAverage total size (kbytes): %K\n"
	"\tMaximum resident set size (kbytes): %M\n"
	"\tAverage resident set size (kbytes): %t\n"
	"\tMajor (requiring I/O) page faults: %F\n"
	"\tMinor (reclaiming a frame) page faults: %R\n"
	"\tVoluntary context switches: %w\n"
	"\tInvoluntary context switches: %c\n"
	"\tSwaps: %W\n"
	"\tFile system inputs: %I\n"
	"\tFile system outputs: %O\n"
	"\tSocket messages sent: %s\n"
	"\tSocket messages received: %r\n"
	"\tSignals delivered: %k\n"
	"\tPage size (bytes): %Z\n"
	"\tExit status: %x";

/* Wait for and fill in data on child process PID.
   Return 0 on error, 1 if ok.  */

/* pid_t is short on BSDI, so don't try to promote it.  */
static int resuse_end(pid_t pid, resource_t * resp)
{
	int status;
	pid_t caught;

	/* Ignore signals, but don't ignore the children.  When wait3
	   returns the child process, set the time the command finished. */
	while ((caught = wait3(&status, 0, &resp->ru)) != pid) {
		if (caught == -1)
			return 0;
	}
	resp->elapsed_ms = (monotonic_us() / 1000) - resp->elapsed_ms;
	resp->waitstatus = status;
	return 1;
}

/* Print ARGV, with each entry in ARGV separated by FILLER.  */
static void printargv(char *const *argv, const char *filler)
{
	fputs(*argv, stdout);
	while (*++argv) {
		fputs(filler, stdout);
		fputs(*argv, stdout);
	}
}

/* Return the number of kilobytes corresponding to a number of pages PAGES.
   (Actually, we use it to convert pages*ticks into kilobytes*ticks.)

   Try to do arithmetic so that the risk of overflow errors is minimized.
   This is funky since the pagesize could be less than 1K.
   Note: Some machines express getrusage statistics in terms of K,
   others in terms of pages.  */

static unsigned long ptok(unsigned long pages)
{
	static unsigned long ps;
	unsigned long tmp;

	/* Initialization.  */
	if (ps == 0)
		ps = getpagesize();

	/* Conversion.  */
	if (pages > (LONG_MAX / ps)) {	/* Could overflow.  */
		tmp = pages / 1024;	/* Smaller first, */
		return tmp * ps;	/* then larger.  */
	}
	/* Could underflow.  */
	tmp = pages * ps;	/* Larger first, */
	return tmp / 1024;	/* then smaller.  */
}

/* summarize: Report on the system use of a command.

   Print the FMT argument except that `%' sequences
   have special meaning, and `\n' and `\t' are translated into
   newline and tab, respectively, and `\\' is translated into `\'.

   The character following a `%' can be:
   (* means the tcsh time builtin also recognizes it)
   % == a literal `%'
   C == command name and arguments
*  D == average unshared data size in K (ru_idrss+ru_isrss)
*  E == elapsed real (wall clock) time in [hour:]min:sec
*  F == major page faults (required physical I/O) (ru_majflt)
*  I == file system inputs (ru_inblock)
*  K == average total mem usage (ru_idrss+ru_isrss+ru_ixrss)
*  M == maximum resident set size in K (ru_maxrss)
*  O == file system outputs (ru_oublock)
*  P == percent of CPU this job got (total cpu time / elapsed time)
*  R == minor page faults (reclaims; no physical I/O involved) (ru_minflt)
*  S == system (kernel) time (seconds) (ru_stime)
*  T == system time in [hour:]min:sec
*  U == user time (seconds) (ru_utime)
*  u == user time in [hour:]min:sec
*  W == times swapped out (ru_nswap)
*  X == average amount of shared text in K (ru_ixrss)
   Z == page size
*  c == involuntary context switches (ru_nivcsw)
   e == elapsed real time in seconds
*  k == signals delivered (ru_nsignals)
   p == average unshared stack size in K (ru_isrss)
*  r == socket messages received (ru_msgrcv)
*  s == socket messages sent (ru_msgsnd)
   t == average resident set size in K (ru_idrss)
*  w == voluntary context switches (ru_nvcsw)
   x == exit status of command

   Various memory usages are found by converting from page-seconds
   to kbytes by multiplying by the page size, dividing by 1024,
   and dividing by elapsed real time.

   FMT is the format string, interpreted as described above.
   COMMAND is the command and args that are being summarized.
   RESP is resource information on the command.  */

#ifndef TICKS_PER_SEC
#define TICKS_PER_SEC 100
#endif

static void summarize(const char *fmt, char **command, resource_t * resp)
{
	unsigned vv_ms;     /* Elapsed virtual (CPU) milliseconds */
	unsigned cpu_ticks; /* Same, in "CPU ticks" */

	if (WIFSTOPPED(resp->waitstatus))
		printf("Command stopped by signal %u\n",
				WSTOPSIG(resp->waitstatus));
	else if (WIFSIGNALED(resp->waitstatus))
		printf("Command terminated by signal %u\n",
				WTERMSIG(resp->waitstatus));
	else if (WIFEXITED(resp->waitstatus) && WEXITSTATUS(resp->waitstatus))
		printf("Command exited with non-zero status %u\n",
				WEXITSTATUS(resp->waitstatus));

	vv_ms = (resp->ru.ru_utime.tv_sec + resp->ru.ru_stime.tv_sec) * 1000
	      + (resp->ru.ru_utime.tv_usec + resp->ru.ru_stime.tv_usec) / 1000;

#if (1000 / TICKS_PER_SEC) * TICKS_PER_SEC == 1000
	/* 1000 is exactly divisible by TICKS_PER_SEC */
	cpu_ticks = vv_ms / (1000 / TICKS_PER_SEC);
#else
	cpu_ticks = vv_ms * (unsigned long long)TICKS_PER_SEC / 1000;
#endif
	if (!cpu_ticks) cpu_ticks = 1; /* we divide by it, must be nonzero */

	while (*fmt) {
		/* Handle leading literal part */
		int n = strcspn(fmt, "%\\");
		if (n) {
			printf("%.*s", n, fmt);
			fmt += n;
			continue;
		}

		switch (*fmt) {
#ifdef NOT_NEEDED
		/* Handle literal char */
		/* Usually we optimize for size, but there is a limit
		 * for everything. With this we do a lot of 1-byte writes */
		default:
			bb_putchar(*fmt);
			break;
#endif

		case '%':
			switch (*++fmt) {
#ifdef NOT_NEEDED_YET
		/* Our format strings do not have these */
		/* and we do not take format str from user */
			default:
				bb_putchar('%');
				/*FALLTHROUGH*/
			case '%':
				if (!*fmt) goto ret;
				bb_putchar(*fmt);
				break;
#endif
			case 'C':	/* The command that got timed.  */
				printargv(command, " ");
				break;
			case 'D':	/* Average unshared data size.  */
				printf("%lu",
						ptok((UL) resp->ru.ru_idrss) / cpu_ticks +
						ptok((UL) resp->ru.ru_isrss) / cpu_ticks);
				break;
			case 'E': {	/* Elapsed real (wall clock) time.  */
				unsigned seconds = resp->elapsed_ms / 1000;
				if (seconds >= 3600)	/* One hour -> h:m:s.  */
					printf("%uh %um %02us",
							seconds / 3600,
							(seconds % 3600) / 60,
							seconds % 60);
				else
					printf("%um %u.%02us",	/* -> m:s.  */
							seconds / 60,
							seconds % 60,
							(unsigned)(resp->elapsed_ms / 10) % 100);
				break;
			}
			case 'F':	/* Major page faults.  */
				printf("%lu", resp->ru.ru_majflt);
				break;
			case 'I':	/* Inputs.  */
				printf("%lu", resp->ru.ru_inblock);
				break;
			case 'K':	/* Average mem usage == data+stack+text.  */
				printf("%lu",
						ptok((UL) resp->ru.ru_idrss) / cpu_ticks +
						ptok((UL) resp->ru.ru_isrss) / cpu_ticks +
						ptok((UL) resp->ru.ru_ixrss) / cpu_ticks);
				break;
			case 'M':	/* Maximum resident set size.  */
				printf("%lu", ptok((UL) resp->ru.ru_maxrss));
				break;
			case 'O':	/* Outputs.  */
				printf("%lu", resp->ru.ru_oublock);
				break;
			case 'P':	/* Percent of CPU this job got.  */
				/* % cpu is (total cpu time)/(elapsed time).  */
				if (resp->elapsed_ms > 0)
					printf("%u%%", (unsigned)(vv_ms * 100 / resp->elapsed_ms));
				else
					printf("?%%");
				break;
			case 'R':	/* Minor page faults (reclaims).  */
				printf("%lu", resp->ru.ru_minflt);
				break;
			case 'S':	/* System time.  */
				printf("%u.%02u",
						(unsigned)resp->ru.ru_stime.tv_sec,
						(unsigned)(resp->ru.ru_stime.tv_usec / 10000));
				break;
			case 'T':	/* System time.  */
				if (resp->ru.ru_stime.tv_sec >= 3600) /* One hour -> h:m:s.  */
					printf("%uh %um %02us",
							(unsigned)(resp->ru.ru_stime.tv_sec / 3600),
							(unsigned)(resp->ru.ru_stime.tv_sec % 3600) / 60,
							(unsigned)(resp->ru.ru_stime.tv_sec % 60));
				else
					printf("%um %u.%02us",	/* -> m:s.  */
							(unsigned)(resp->ru.ru_stime.tv_sec / 60),
							(unsigned)(resp->ru.ru_stime.tv_sec % 60),
							(unsigned)(resp->ru.ru_stime.tv_usec / 10000));
				break;
			case 'U':	/* User time.  */
				printf("%u.%02u",
						(unsigned)resp->ru.ru_utime.tv_sec,
						(unsigned)(resp->ru.ru_utime.tv_usec / 10000));
				break;
			case 'u':	/* User time.  */
				if (resp->ru.ru_utime.tv_sec >= 3600) /* One hour -> h:m:s.  */
					printf("%uh %um %02us",
							(unsigned)(resp->ru.ru_utime.tv_sec / 3600),
							(unsigned)(resp->ru.ru_utime.tv_sec % 3600) / 60,
							(unsigned)(resp->ru.ru_utime.tv_sec % 60));
				else
					printf("%um %u.%02us",	/* -> m:s.  */
							(unsigned)(resp->ru.ru_utime.tv_sec / 60),
							(unsigned)(resp->ru.ru_utime.tv_sec % 60),
							(unsigned)(resp->ru.ru_utime.tv_usec / 10000));
				break;
			case 'W':	/* Times swapped out.  */
				printf("%lu", resp->ru.ru_nswap);
				break;
			case 'X':	/* Average shared text size.  */
				printf("%lu", ptok((UL) resp->ru.ru_ixrss) / cpu_ticks);
				break;
			case 'Z':	/* Page size.  */
				printf("%u", getpagesize());
				break;
			case 'c':	/* Involuntary context switches.  */
				printf("%lu", resp->ru.ru_nivcsw);
				break;
			case 'e':	/* Elapsed real time in seconds.  */
				printf("%u.%02u",
						(unsigned)resp->elapsed_ms / 1000,
						(unsigned)(resp->elapsed_ms / 10) % 100);
				break;
			case 'k':	/* Signals delivered.  */
				printf("%lu", resp->ru.ru_nsignals);
				break;
			case 'p':	/* Average stack segment.  */
				printf("%lu", ptok((UL) resp->ru.ru_isrss) / cpu_ticks);
				break;
			case 'r':	/* Incoming socket messages received.  */
				printf("%lu", resp->ru.ru_msgrcv);
				break;
			case 's':	/* Outgoing socket messages sent.  */
				printf("%lu", resp->ru.ru_msgsnd);
				break;
			case 't':	/* Average resident set size.  */
				printf("%lu", ptok((UL) resp->ru.ru_idrss) / cpu_ticks);
				break;
			case 'w':	/* Voluntary context switches.  */
				printf("%lu", resp->ru.ru_nvcsw);
				break;
			case 'x':	/* Exit status.  */
				printf("%u", WEXITSTATUS(resp->waitstatus));
				break;
			}
			break;

#ifdef NOT_NEEDED_YET
		case '\\':		/* Format escape.  */
			switch (*++fmt) {
			default:
				bb_putchar('\\');
				/*FALLTHROUGH*/
			case '\\':
				if (!*fmt) goto ret;
				bb_putchar(*fmt);
				break;
			case 't':
				bb_putchar('\t');
				break;
			case 'n':
				bb_putchar('\n');
				break;
			}
			break;
#endif
		}
		++fmt;
	}
 /* ret: */
	bb_putchar('\n');
}

/* Run command CMD and return statistics on it.
   Put the statistics in *RESP.  */
static void run_command(char *const *cmd, resource_t * resp)
{
	pid_t pid;			/* Pid of child.  */
	__sighandler_t interrupt_signal, quit_signal;

	resp->elapsed_ms = monotonic_us() / 1000;
	pid = vfork();		/* Run CMD as child process.  */
	if (pid < 0)
		bb_error_msg_and_die("cannot fork");
	else if (pid == 0) {	/* If child.  */
		/* Don't cast execvp arguments; that causes errors on some systems,
		   versus merely warnings if the cast is left off.  */
		BB_EXECVP(cmd[0], cmd);
		bb_error_msg("cannot run %s", cmd[0]);
		_exit(errno == ENOENT ? 127 : 126);
	}

	/* Have signals kill the child but not self (if possible).  */
	interrupt_signal = signal(SIGINT, SIG_IGN);
	quit_signal = signal(SIGQUIT, SIG_IGN);

	if (resuse_end(pid, resp) == 0)
		bb_error_msg("error waiting for child process");

	/* Re-enable signals.  */
	signal(SIGINT, interrupt_signal);
	signal(SIGQUIT, quit_signal);
}

int time_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int time_main(int argc, char **argv)
{
	resource_t res;
	const char *output_format = default_format;
	char c;

	goto next;
	/* Parse any options  -- don't use getopt() here so we don't
	 * consume the args of our client application... */
	while (argc > 0 && argv[0][0] == '-') {
		while ((c = *++*argv)) {
			switch (c) {
			case 'v':
				output_format = long_format;
				break;
			case 'p':
				output_format = posix_format;
				break;
			default:
				bb_show_usage();
			}
		}
 next:
		argv++;
		argc--;
		if (!argc)
			bb_show_usage();
	}

	run_command(argv, &res);

	/* Cheat. printf's are shorter :) */
	/* (but see bb_putchar() body for additional wrinkle!) */
	stdout = stderr;
	dup2(2, 1); /* just in case libc does something silly :( */
	summarize(output_format, argv, &res);

	if (WIFSTOPPED(res.waitstatus))
		return WSTOPSIG(res.waitstatus);
	if (WIFSIGNALED(res.waitstatus))
		return WTERMSIG(res.waitstatus);
	if (WIFEXITED(res.waitstatus))
		return WEXITSTATUS(res.waitstatus);
	fflush_stdout_and_exit(0);
}


text:
BlueTea Push Notifications PHP Library
==========================


text:
package graft

import (
	"errors"
	"sync"
	"sync/atomic"

	"github.com/nats-io/graft/pb"
)

var mu sync.Mutex
var peers map[string]*Node

func init() {
	peers = make(map[string]*Node)
}

func mockPeerCount() int {
	mu.Lock()
	defer mu.Unlock()
	return len(peers)
}

func mockPeers() []*Node {
	mu.Lock()
	defer mu.Unlock()
	nodes := make([]*Node, 0, len(peers))
	for _, p := range peers {
		nodes = append(nodes, p)
	}
	return nodes
}

func mockRegisterPeer(n *Node) {
	mu.Lock()
	defer mu.Unlock()
	peers[n.id] = n
}

func mockUnregisterPeer(id string) {
	mu.Lock()
	defer mu.Unlock()
	delete(peers, id)
}

func mockResetPeers() {
	mu.Lock()
	defer mu.Unlock()
	peers = make(map[string]*Node)
}

// Membership designations for split network simulations.
const (
	NO_MEMBERSHIP = int32(iota)
	GRP_A
	GRP_B
)

// Handle a simulation of a split network.
func mockSplitNetwork(grp []*Node) {
	if len(grp) <= 0 {
		return
	}
	mu.Lock()
	defer mu.Unlock()
	// Reset all to other group, GrpB
	for _, p := range peers {
		rpc := p.rpc.(*MockRpcDriver)
		atomic.StoreInt32(&rpc.membership, GRP_B)
	}
	// Set passed in nodes to GrpA
	for _, p := range grp {
		rpc := p.rpc.(*MockRpcDriver)
		atomic.StoreInt32(&rpc.membership, GRP_A)
	}
}

// Restore network from a split.
func mockRestoreNetwork() {
	mu.Lock()
	defer mu.Unlock()
	for _, p := range peers {
		rpc := p.rpc.(*MockRpcDriver)
		atomic.StoreInt32(&rpc.membership, NO_MEMBERSHIP)
	}
}

type MockRpcDriver struct {
	mu   sync.Mutex
	node *Node

	// For testing
	shouldFailInit bool
	closeCalled    bool
	shouldFailComm bool
	membership     int32
}

func NewMockRpc() *MockRpcDriver {
	return &MockRpcDriver{}
}

func (rpc *MockRpcDriver) Init(n *Node) error {
	if rpc.shouldFailInit {
		return errors.New("RPC Failed to Init")
	}
	// Redo the channels to be buffered since we could be
	// sending and block the select loops.
	cSize := n.ClusterInfo().Size
	n.VoteRequests = make(chan *pb.VoteRequest, cSize)
	n.VoteResponses = make(chan *pb.VoteResponse, cSize)
	n.HeartBeats = make(chan *pb.Heartbeat, cSize)

	mockRegisterPeer(n)
	rpc.node = n
	return nil
}

func (rpc *MockRpcDriver) Close() {
	rpc.closeCalled = true
	if rpc.node != nil {
		mockUnregisterPeer(rpc.node.id)
	}
}

// Test if we can talk to a peer
func (rpc *MockRpcDriver) commAllowed(peer *Node) bool {
	// Faked nodes
	if peer == nil || peer.rpc == nil {
		return true
	}
	// Might be fake node, so allow if not a MockRpcDriver
	peerRpc, ok := peer.rpc.(*MockRpcDriver)
	if !ok {
		return true
	}

	// Check to see if we are in same group as peer
	m1 := atomic.LoadInt32(&rpc.membership)
	m2 := atomic.LoadInt32(&peerRpc.membership)
	return m1 == m2
}

func (rpc *MockRpcDriver) RequestVote(vr *pb.VoteRequest) error {
	if rpc.isCommBlocked() {
		// Silent failure
		return nil
	}
	for _, p := range mockPeers() {
		if p.id != rpc.node.id && rpc.commAllowed(p) {
			p.VoteRequests <- vr
		}
	}
	return nil
}

func (rpc *MockRpcDriver) HeartBeat(hb *pb.Heartbeat) error {
	if rpc.isCommBlocked() {
		// Silent failure
		return nil
	}

	for _, p := range mockPeers() {
		if p.id != rpc.node.id && rpc.commAllowed(p) {
			p.HeartBeats <- hb
		}
	}
	return nil
}

func (rpc *MockRpcDriver) SendVoteResponse(candidate string, vresp *pb.VoteResponse) error {
	if rpc.isCommBlocked() {
		// Silent failure
		return nil
	}

	mu.Lock()
	p := peers[candidate]
	mu.Unlock()

	if p != nil && p.isRunning() && rpc.commAllowed(p) {
		p.VoteResponses <- vresp
	}
	return nil
}

func (rpc *MockRpcDriver) isCommBlocked() bool {
	rpc.mu.Lock()
	defer rpc.mu.Unlock()
	return rpc.shouldFailComm
}


text:
require 'spec_helper'

describe 'redis' do
  context 'on Ubuntu 1404' do

    let(:facts) {
      ubuntu_1404_facts
    }

    context 'should set Ubuntu specific values' do

      context 'when $::redis_server_version fact is not present (older features not enabled)' do

        let(:facts) {
          ubuntu_1404_facts.merge({
            :redis_server_version => nil,
          })
        }

        it { should contain_file('/etc/redis/redis.conf.puppet').with('content' => /^hash-max-ziplist-entries/) }
        it { should contain_file('/etc/redis/redis.conf.puppet').without('content' => /^tcp-backlog/) }
        it { should contain_file('/etc/redis/redis.conf.puppet').without('content' => /^protected-mode/) }

      end

      context 'when $::redis_server_version fact is not present and package_ensure is a newer version(3.2.1) (older features enabled)' do

        let(:facts) {
          ubuntu_1404_facts.merge({
            :redis_server_version => nil,
          })
        }
        let (:params) { { :package_ensure => '3.2.1' } }

        it { should contain_file('/etc/redis/redis.conf.puppet').with('content' => /^hash-max-ziplist-entries/) }
        it { should contain_file('/etc/redis/redis.conf.puppet').with('content' => /^protected-mode/) }
        it { should contain_file('/etc/redis/redis.conf.puppet').with('content' => /^tcp-backlog/) }

      end

      context 'when $::redis_server_version fact is not present and package_ensure is a newer version(3:3.2.1) (older features enabled)' do

        let(:facts) {
          ubuntu_1404_facts.merge({
            :redis_server_version => nil,
          })
        }
        let (:params) { { :package_ensure => '3:3.2.1' } }

        it { should contain_file('/etc/redis/redis.conf.puppet').with('content' => /^hash-max-ziplist-entries/) }
        it { should contain_file('/etc/redis/redis.conf.puppet').with('content' => /^protected-mode/) }
        it { should contain_file('/etc/redis/redis.conf.puppet').with('content' => /^tcp-backlog/) }

      end

      context 'when $::redis_server_version fact is not present and package_ensure is a newer version(4:4.0-rc3) (older features enabled)' do

        let(:facts) {
          ubuntu_1404_facts.merge({
            :redis_server_version => nil,
          })
        }
        let (:params) { { :package_ensure => '4:4.0-rc3' } }

        it { should contain_file('/etc/redis/redis.conf.puppet').with('content' => /^hash-max-ziplist-entries/) }
        it { should contain_file('/etc/redis/redis.conf.puppet').without('content' => /^protected-mode/) }
        it { should contain_file('/etc/redis/redis.conf.puppet').with('content' => /^tcp-backlog/) }

      end
      context 'when $::redis_server_version fact is not present and package_ensure is a newer version(4.0-rc3) (older features enabled)' do

        let(:facts) {
          ubuntu_1404_facts.merge({
            :redis_server_version => nil,
          })
        }
        let (:params) { { :package_ensure => '4.0-rc3' } }

        it { should contain_file('/etc/redis/redis.conf.puppet').with('content' => /^hash-max-ziplist-entries/) }
        it { should contain_file('/etc/redis/redis.conf.puppet').without('content' => /^protected-mode/) }
        it { should contain_file('/etc/redis/redis.conf.puppet').with('content' => /^tcp-backlog/) }

      end

      context 'when $::redis_server_version fact is present but the older version (older features not enabled)' do

        let(:facts) {
          ubuntu_1404_facts.merge({
            :redis_server_version => '2.8.4',
          })
        }

        it { should contain_file('/etc/redis/redis.conf.puppet').with('content' => /^hash-max-ziplist-entries/) }
        it { should contain_file('/etc/redis/redis.conf.puppet').without('content' => /^tcp-backlog/) }
        it { should contain_file('/etc/redis/redis.conf.puppet').without('content' => /^protected-mode/) }

      end

      context 'when $::redis_server_version fact is present but a newer version (older features enabled)' do

        let(:facts) {
          ubuntu_1404_facts.merge({
            :redis_server_version => '3.2.1',
          })
        }

        it { should contain_file('/etc/redis/redis.conf.puppet').with('content' => /^hash-max-ziplist-entries/) }
        it { should contain_file('/etc/redis/redis.conf.puppet').with('content' => /^tcp-backlog/) }
        it { should contain_file('/etc/redis/redis.conf.puppet').with('content' => /^protected-mode/) }

      end
    end

  end

end


text:
namespace Snippets5.RavenDB
{
    using NServiceBus;
    using NServiceBus.Persistence;
    using NServiceBus.RavenDB;
    using NServiceBus.RavenDB.Persistence;
    using Raven.Client;
    using Raven.Client.Document;

    class RavenDBConfigure
    {
        public void StaleSagas()
        {
            //Allows to correlate sagas on non-unique properties

            #region ravendb-persistence-stale-sagas

            BusConfiguration busConfiguration = new BusConfiguration();
            busConfiguration.UsePersistence<RavenDBPersistence>()
                .AllowStaleSagaReads();

            #endregion
        }

        public void SharedSessionForSagasAndOutbox()
        {
            #region ravendb-persistence-shared-session-for-sagas

            DocumentStore myDocumentStore = new DocumentStore();
            // configure document store properties here

            BusConfiguration busConfiguration = new BusConfiguration();
            busConfiguration.UsePersistence<RavenDBPersistence>().UseSharedSession(() =>
            {
                IDocumentSession session = myDocumentStore.OpenSession();
                // customize the session properties here
                return session;
            });

            #endregion
        }

        public class MyMessage
        {
        }

        public class MyDocument
        {
        }

        #region ravendb-persistence-shared-session-for-sagas-handler

        public class MyMessageHandler : IHandleMessages<MyMessage>
        {
            ISessionProvider sessionProvider;

            public MyMessageHandler(ISessionProvider sessionProvider)
            {
                this.sessionProvider = sessionProvider;
            }

            public void Handle(MyMessage message)
            {
                MyDocument doc = new MyDocument();

                sessionProvider.Session.Store(doc);
            }
        }

        #endregion

        public void SpecificExternalDocumentStore()
        {
            #region ravendb-persistence-specific-external-store

            DocumentStore myDocumentStore = new DocumentStore();
            // configure document store properties here

            BusConfiguration busConfiguration = new BusConfiguration();
            busConfiguration.UsePersistence<RavenDBPersistence>()
                .UseDocumentStoreForSubscriptions(myDocumentStore)
                .UseDocumentStoreForSagas(myDocumentStore)
                .UseDocumentStoreForTimeouts(myDocumentStore);

            #endregion
        }

        public void SpecificDocumentStoreViaConnectionString()
        {
            //See the config file
        }

        public void ExternalDocumentStore()
        {
            #region ravendb-persistence-external-store

            DocumentStore myDocumentStore = new DocumentStore();
            // configure document store properties here

            BusConfiguration busConfiguration = new BusConfiguration();
            busConfiguration.UsePersistence<RavenDBPersistence>()
                .SetDefaultDocumentStore(myDocumentStore);

            #endregion
        }

        public void ExternalConnectionParameters()
        {
            #region ravendb-persistence-external-connection-params

            ConnectionParameters connectionParams = new ConnectionParameters();
            // configure connection params (ApiKey, DatabaseName, Url) here

            BusConfiguration busConfiguration = new BusConfiguration();
            busConfiguration.UsePersistence<RavenDBPersistence>()
                .SetDefaultDocumentStore(connectionParams);

            #endregion
        }

        public void SharedDocumentStoreViaConnectionString()
        {
            //See the config file
        }

    }
}


text:
var fs = require ('fs');
var exec    = require('child_process').exec;

var ServeMe = require("serve-me");

var dir = './www';
var cmd = '';
var cmdPrepare = '';
var host = '';
// var confFile = 'config.xml';
var confFile   = 'www/js/apppreferences-test.js'

if (process.argv[2] === 'ios') {
	dir        = './platforms/ios/www';
	// cmd = 'ios-sim launch ./platforms/ios/build/emulator/HelloCordova.app --log ./console.log --devicetypeid iPhone-6 --exit';
	cmd        = 'cordova emulate ios';
	cmdPrepare = 'cordova prepare ios';
	host       = '127.0.0.1';
} else if (process.argv[2] === 'android') {
	dir        = './platforms/android/assets/www';
	cmd        = 'cordova emulate android';
	cmdPrepare = 'cordova prepare android';
	host       = '10.0.2.2';

	if (process.argv[3]) {
		cmdPrepare += " --target=" + process.argv[3];
	}
} else if (process.argv[2] === 'windows') {
	dir        = './platforms/windows/www';
	cmd        = 'cordova emulate windows';
	cmdPrepare = 'cordova prepare windows';
	host       = '127.0.0.1';
	confFile   = 'www/js/apppreferences-test.js'
}

var serveMe = ServeMe ({
	// debug: true,
	// log: true,
	directory: dir,
	secure: false
});

function handleError (err, stdout, stderr) {
	if (err) {
		if (stdout) console.log (stdout);
		if (stderr) console.error (stderr);
		process.exit (1);
	}
}

fs.readFile (confFile, function (err, buf) {
	handleError (err, null, err);

	serveMe.start("0", function() {

		var port = serveMe.server.server.address().port;

		var configXml = buf.toString('utf-8').replace (/<content src="[^"]+/m, '<content src="http://' + host + ':' + port);

		// console.log (configXml);

		fs.writeFile (confFile, configXml, function (err) {
			handleError (err, null, err);

			console.log ('Changes applied to the', confFile);

			exec(cmdPrepare, function callback(error, stdout, stderr){
				handleError (error, stdout, stderr);

				console.log ('Prepare completed');
				exec(cmd, function callback(error, stdout, stderr){
					handleError (error, stdout, stderr);

					console.log ('Emulator running');
					setTimeout (function () {process.exit(1)}, 30000);
				});
			});
		});
	});
})

serveMe.on("http_request", function(data){
	// console.log("http request", data);
});

serveMe.get ("/test/success", function(){
	console.log ("test success");
	process.exit ();
});

serveMe.get ("/test/fail", function (req, res){
	console.log ("test failures: ", req.url);
	process.exit (1);
});


text:
package org.apache.cassandra.service;

import java.net.InetAddress;
import java.util.*;
import java.util.concurrent.*;

import org.apache.cassandra.concurrent.StageManager;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.db.filter.QueryPath;
import org.apache.cassandra.db.*;
import org.apache.cassandra.dht.IPartitioner;
import org.apache.cassandra.dht.Range;
import org.apache.cassandra.dht.Token;
import org.apache.cassandra.io.CompactionIterator.CompactedRow;
import org.apache.cassandra.io.util.DataOutputBuffer;
import org.apache.cassandra.locator.AbstractReplicationStrategy;
import org.apache.cassandra.locator.TokenMetadata;
import static org.apache.cassandra.service.AntiEntropyService.*;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.cassandra.utils.MerkleTree;

import org.apache.cassandra.CleanupHelper;
import org.apache.cassandra.Util;

import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;

public class AntiEntropyServiceTest extends CleanupHelper
{
    // table and column family to test against
    public static AntiEntropyService aes;

    public static String tablename;
    public static String cfname;
    public static ColumnFamilyStore store;
    public static InetAddress LOCAL, REMOTE;

    @BeforeClass
    public static void prepareClass() throws Exception
    {
        LOCAL = FBUtilities.getLocalAddress();
        tablename = "Keyspace4";
        StorageService.instance.initServer();
        // generate a fake endpoint for which we can spoof receiving/sending trees
        REMOTE = InetAddress.getByName("127.0.0.2");
        store = Table.open(tablename).getColumnFamilyStores().iterator().next();
        cfname = store.columnFamily_;
    }

    @Before
    public void prepare() throws Exception
    {
        aes = AntiEntropyService.instance;
        TokenMetadata tmd = StorageService.instance.getTokenMetadata();
        tmd.clearUnsafe();
        tmd.updateNormalToken(StorageService.getPartitioner().getRandomToken(), LOCAL);
        tmd.updateNormalToken(StorageService.getPartitioner().getMinimumToken(), REMOTE);
        assert tmd.isMember(REMOTE);
    }

    @Test
    public void testInstance() throws Throwable
    {
        assert null != aes;
        assert aes == AntiEntropyService.instance;
    }

    @Test
    public void testValidatorPrepare() throws Throwable
    {
        Validator validator;

        // write
        List<RowMutation> rms = new LinkedList<RowMutation>();
        RowMutation rm;
        rm = new RowMutation(tablename, "key1");
        rm.add(new QueryPath(cfname, null, "Column1".getBytes()), "asdf".getBytes(), 0);
        rms.add(rm);
        Util.writeColumnFamily(rms);

        // sample
        validator = new Validator(new CFPair(tablename, cfname));
        validator.prepare(store);

        // and confirm that the tree was split
        assertTrue(validator.tree.size() > 1);
    }

    @Test
    public void testValidatorComplete() throws Throwable
    {
        Validator validator = new Validator(new CFPair(tablename, cfname));
        validator.prepare(store);
        validator.complete();

        // confirm that the tree was validated
        Token min = validator.tree.partitioner().getMinimumToken();
        assert null != validator.tree.hash(new Range(min, min));

        // wait for queued operations to be flushed
        flushAES().get(5000, TimeUnit.MILLISECONDS);
    }

    @Test
    public void testValidatorAdd() throws Throwable
    {
        Validator validator = new Validator(new CFPair(tablename, cfname));
        IPartitioner part = validator.tree.partitioner();
        Token min = part.getMinimumToken();
        Token mid = part.midpoint(min, min);
        validator.prepare(store);

        // add a row with the minimum token
        validator.add(new CompactedRow(new DecoratedKey(min, "nonsense!"),
                                       new DataOutputBuffer()));

        // and a row after it
        validator.add(new CompactedRow(new DecoratedKey(mid, "inconceivable!"),
                                       new DataOutputBuffer()));
        validator.complete();

        // confirm that the tree was validated
        assert null != validator.tree.hash(new Range(min, min));
    }

    /**
     * Build a column family with 2 or more SSTables, and then force a major compaction
     */
    @Test
    public void testTreeStore() throws Throwable
    {
        // populate column family
        List<RowMutation> rms = new LinkedList<RowMutation>();
        RowMutation rm = new RowMutation(tablename, "key");
        rm.add(new QueryPath(cfname, null, "Column1".getBytes()), "asdf".getBytes(), 0);
        rms.add(rm);
        // with two SSTables
        Util.writeColumnFamily(rms);
        Util.writeColumnFamily(rms);

        TreePair old = aes.getRendezvousPair_TestsOnly(tablename, cfname, REMOTE);
        // force a readonly compaction, and wait for it to finish
        Validator validator = new Validator(new CFPair(tablename, cfname));
        CompactionManager.instance.submitValidation(store, validator).get(5000, TimeUnit.MILLISECONDS);

        // check that a tree was created and stored
        flushAES().get(5000, TimeUnit.MILLISECONDS);
        assert old != aes.getRendezvousPair_TestsOnly(tablename, cfname, REMOTE);
    }

    @Test
    public void testNotifyNeighbors() throws Throwable
    {
        // generate empty tree
        Validator validator = new Validator(new CFPair(tablename, cfname));
        validator.prepare(store);
        validator.complete();

        // grab reference to the tree
        MerkleTree tree = validator.tree;

        // notify ourself (should immediately be delivered into AE_STAGE)
        aes.notifyNeighbors(validator, LOCAL, Arrays.asList(LOCAL));
        flushAES().get(5, TimeUnit.SECONDS);

        // confirm that our reference is not equal to the original due
        // to (de)serialization
        assert tree != aes.getRendezvousPair_TestsOnly(tablename, cfname, REMOTE).left;
    }

    @Test
    public void testGetNeighborsPlusOne() throws Throwable
    {
        // generate rf+1 nodes, and ensure that all nodes are returned
        Set<InetAddress> expected = addTokens(1 + 1 + DatabaseDescriptor.getReplicationFactor(tablename));
        expected.remove(FBUtilities.getLocalAddress());
        assertEquals(expected, AntiEntropyService.getNeighbors(tablename));
    }

    @Test
    public void testGetNeighborsTimesTwo() throws Throwable
    {
        TokenMetadata tmd = StorageService.instance.getTokenMetadata();

        // generate rf*2 nodes, and ensure that only neighbors specified by the ARS are returned
        addTokens(1 + (2 * DatabaseDescriptor.getReplicationFactor(tablename)));
        AbstractReplicationStrategy ars = StorageService.instance.getReplicationStrategy(tablename);
        Set<InetAddress> expected = new HashSet<InetAddress>();
        for (Range replicaRange : ars.getAddressRanges(tablename).get(FBUtilities.getLocalAddress()))
        {
            expected.addAll(ars.getRangeAddresses(tmd, tablename).get(replicaRange));
        }
        expected.remove(FBUtilities.getLocalAddress());
        assertEquals(expected, AntiEntropyService.getNeighbors(tablename));
    }

    @Test
    public void testDifferencer() throws Throwable
    {
        // generate a tree
        Validator validator = new Validator(new CFPair(tablename, cfname));
        validator.prepare(store);
        validator.complete();
        MerkleTree ltree = validator.tree;

        // and a clone
        validator = new Validator(new CFPair(tablename, cfname));
        validator.prepare(store);
        validator.complete();
        MerkleTree rtree = validator.tree;

        // change a range in one of the trees
        Token min = StorageService.instance.getPartitioner().getMinimumToken();
        ltree.invalidate(min);
        MerkleTree.TreeRange changed = ltree.invalids(new Range(min, min)).next();
        changed.hash("non-empty hash!".getBytes());

        // difference the trees
        Differencer diff = new Differencer(new CFPair(tablename, cfname),
                                           LOCAL, LOCAL, ltree, rtree);
        diff.run();

        // ensure that the changed range was recorded
        assertEquals("Wrong number of differing ranges", 1, diff.differences.size());
        assertEquals("Wrong differing range", changed, diff.differences.get(0));
    }

    Set<InetAddress> addTokens(int max) throws Throwable
    {
        TokenMetadata tmd = StorageService.instance.getTokenMetadata();
        Set<InetAddress> endpoints = new HashSet<InetAddress>();
        for (int i = 1; i < max; i++)
        {
            InetAddress endpoint = InetAddress.getByName("127.0.0." + i);
            tmd.updateNormalToken(StorageService.getPartitioner().getRandomToken(), endpoint);
            endpoints.add(endpoint);
        }
        return endpoints;
    }

    Future<Object> flushAES()
    {
        return StageManager.getStage(StageManager.AE_SERVICE_STAGE).submit(new Callable<Object>()
        {
            public Boolean call()
            {
                return true;
            }
        });
    }
}


text:
package org.imsglobal.basiclti;

import java.io.IOException;
import java.net.URISyntaxException;
import javax.servlet.http.HttpServletRequest;
import net.oauth.OAuthAccessor;
import net.oauth.OAuthException;
import net.oauth.OAuthMessage;
import net.oauth.SimpleOAuthValidator;
import net.oauth.server.OAuthServlet;
import net.oauth.signature.OAuthSignatureMethod;
import org.junit.Assert;
import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Matchers;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest({OAuthServlet.class, OAuthSignatureMethod.class, SimpleOAuthValidator.class, BasicLTIUtil.class})
public class BasicLTIUtilTest {

    @Before
    public void setUp() throws Exception {
    }

    @Test
    public void testGetRealPath() {
        String fixed = BasicLTIUtil.getRealPath("http://localhost/path/blah/", "https://right.com");
        assertEquals("https://right.com/path/blah/", fixed);
        fixed = BasicLTIUtil.getRealPath("https://localhost/path/blah/", "https://right.com");
        assertEquals("https://right.com/path/blah/", fixed);
        fixed = BasicLTIUtil.getRealPath("https://localhost/path/blah/", "http://right.com");
        assertEquals("http://right.com/path/blah/", fixed);

        // Test folks sending in URL with extra stuff...
        fixed = BasicLTIUtil.getRealPath("https://localhost/path/blah/", "https://right.com/path/blah");
        assertEquals("https://right.com/path/blah/", fixed);
    }

    @Test
    public void testValidateMessageFailsWhenNoConsumerKey() throws IOException, Exception{

        HttpServletRequest requestMock = Mockito.mock(HttpServletRequest.class);
        String url = "https://example.com/lti-launch";

        PowerMockito.mockStatic(OAuthServlet.class);
        OAuthMessage messageMock = Mockito.mock(OAuthMessage.class);

        PowerMockito.when(OAuthServlet.getMessage(requestMock, url)).thenReturn(messageMock);

        Mockito.when(messageMock.getConsumerKey()).thenThrow(new IOException("io exception"));

        LtiVerificationResult result = BasicLTIUtil.validateMessage(requestMock, url, "secret");

        Assert.assertEquals(LtiError.BAD_REQUEST, result.getError());
        Assert.assertEquals(Boolean.FALSE, result.getSuccess());

    }

    @Test
    public void testValidateMessageFailWhenUriIsMalformed() throws Exception {

        HttpServletRequest requestMock = Mockito.mock(HttpServletRequest.class);
        String url = "https://example.com/lti-launch";

        PowerMockito.mockStatic(OAuthSignatureMethod.class);
        PowerMockito.when(OAuthSignatureMethod.getBaseString(Matchers.any(OAuthMessage.class))).thenThrow(new URISyntaxException("","",0));

        LtiVerificationResult result = BasicLTIUtil.validateMessage(requestMock, url, "secret");

        Assert.assertEquals(LtiError.BAD_REQUEST, result.getError());
        Assert.assertEquals(Boolean.FALSE, result.getSuccess());

    }

    @Test
    public void testValidateMessageFailOnIOException() throws Exception {

        HttpServletRequest requestMock = Mockito.mock(HttpServletRequest.class);
        String url = "https://example.com/lti-launch";

        PowerMockito.mockStatic(OAuthSignatureMethod.class);
        PowerMockito.when(OAuthSignatureMethod.getBaseString(Matchers.any(OAuthMessage.class))).thenThrow(new IOException(""));

        LtiVerificationResult result = BasicLTIUtil.validateMessage(requestMock, url, "secret");

        Assert.assertEquals(LtiError.BAD_REQUEST, result.getError());
        Assert.assertEquals(Boolean.FALSE, result.getSuccess());

    }

    @Test
    public void testValidateMessageFailOnValidateMessageIOException() throws Exception {

        SimpleOAuthValidator sov = Mockito.mock(SimpleOAuthValidator.class);
        PowerMockito.whenNew(SimpleOAuthValidator.class).withNoArguments().thenReturn(sov);
        Mockito.doThrow(new IOException("failed")).when(sov).validateMessage(Matchers.any(OAuthMessage.class), Matchers.any(OAuthAccessor.class));
        PowerMockito.mockStatic(OAuthSignatureMethod.class);
        PowerMockito.when(OAuthSignatureMethod.getBaseString(Matchers.any(OAuthMessage.class))).thenReturn("");

        LtiVerificationResult result = BasicLTIUtil.validateMessage(Mockito.mock(HttpServletRequest.class), "https://example.com/lti-launch", "secret");

        Assert.assertEquals(LtiError.BAD_REQUEST, result.getError());
        Assert.assertEquals(Boolean.FALSE, result.getSuccess());
        Assert.assertEquals(null, result.getLtiLaunchResult());
    }

    @Test
    public void testValidateMessageFailOnValidateMessageOAuthException() throws Exception {

        SimpleOAuthValidator sov = Mockito.mock(SimpleOAuthValidator.class);
        PowerMockito.whenNew(SimpleOAuthValidator.class).withNoArguments().thenReturn(sov);
        Mockito.doThrow(new OAuthException("failed")).when(sov).validateMessage(Matchers.any(OAuthMessage.class), Matchers.any(OAuthAccessor.class));
        PowerMockito.mockStatic(OAuthSignatureMethod.class);
        PowerMockito.when(OAuthSignatureMethod.getBaseString(Matchers.any(OAuthMessage.class))).thenReturn("");

        LtiVerificationResult result = BasicLTIUtil.validateMessage(Mockito.mock(HttpServletRequest.class), "https://example.com/lti-launch", "secret");

        Assert.assertEquals(LtiError.BAD_REQUEST, result.getError());
        Assert.assertEquals(Boolean.FALSE, result.getSuccess());
        Assert.assertEquals(null, result.getLtiLaunchResult());
    }

    @Test
    public void testValidateMessageFailOnValidateMessageURISyntaxException() throws Exception {

        SimpleOAuthValidator sov = Mockito.mock(SimpleOAuthValidator.class);
        PowerMockito.whenNew(SimpleOAuthValidator.class).withNoArguments().thenReturn(sov);
        Mockito.doThrow(new URISyntaxException("failed", "failed")).when(sov).validateMessage(Matchers.any(OAuthMessage.class), Matchers.any(OAuthAccessor.class));
        PowerMockito.mockStatic(OAuthSignatureMethod.class);
        PowerMockito.when(OAuthSignatureMethod.getBaseString(Matchers.any(OAuthMessage.class))).thenReturn("");

        LtiVerificationResult result = BasicLTIUtil.validateMessage(Mockito.mock(HttpServletRequest.class), "https://example.com/lti-launch", "secret");

        Assert.assertEquals(LtiError.BAD_REQUEST, result.getError());
        Assert.assertEquals(Boolean.FALSE, result.getSuccess());
        Assert.assertEquals(null, result.getLtiLaunchResult());
    }

    @Test
    public void testValidateMessagePass() throws Exception {

        SimpleOAuthValidator sov = Mockito.mock(SimpleOAuthValidator.class);
        PowerMockito.whenNew(SimpleOAuthValidator.class).withNoArguments().thenReturn(sov);
        Mockito.doNothing().when(sov).validateMessage(Matchers.any(OAuthMessage.class), Matchers.any(OAuthAccessor.class));
        PowerMockito.mockStatic(OAuthSignatureMethod.class);
        PowerMockito.when(OAuthSignatureMethod.getBaseString(Matchers.any(OAuthMessage.class))).thenReturn("");

        HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
        Mockito.when(req.getParameter("user_id")).thenReturn("pgray");
        Mockito.when(req.getParameter("roles")).thenReturn("instructor, teacher,administrator");
        Mockito.when(req.getParameter("lti_version")).thenReturn("lpv1");
        Mockito.when(req.getParameter("lti_message_type")).thenReturn("lti");
        Mockito.when(req.getParameter("resource_link_id")).thenReturn("12345");
        Mockito.when(req.getParameter("context_id")).thenReturn("9876");
        Mockito.when(req.getParameter("launch_presentation_return_url")).thenReturn("http://example.com/return");
        Mockito.when(req.getParameter("tool_consumer_instance_guid")).thenReturn("instance_id");

        LtiVerificationResult result = BasicLTIUtil.validateMessage(req, "https://example.com/lti-launch", "secret1");

        Assert.assertEquals(null, result.getError());
        Assert.assertEquals(Boolean.TRUE, result.getSuccess());
        Assert.assertNotNull(result.getLtiLaunchResult());

        Assert.assertEquals("pgray", result.getLtiLaunchResult().getUser().getId());
        Assert.assertEquals(3, result.getLtiLaunchResult().getUser().getRoles().size());
        Assert.assertTrue(result.getLtiLaunchResult().getUser().getRoles().contains("instructor"));
        Assert.assertTrue(result.getLtiLaunchResult().getUser().getRoles().contains("teacher"));
        Assert.assertTrue(result.getLtiLaunchResult().getUser().getRoles().contains("administrator"));

        Assert.assertEquals("lpv1", result.getLtiLaunchResult().getVersion());
        Assert.assertEquals("lti", result.getLtiLaunchResult().getMessageType());
        Assert.assertEquals("12345", result.getLtiLaunchResult().getResourceLinkId());
        Assert.assertEquals("9876", result.getLtiLaunchResult().getContextId());
        Assert.assertEquals("http://example.com/return", result.getLtiLaunchResult().getLaunchPresentationReturnUrl());
        Assert.assertEquals("instance_id", result.getLtiLaunchResult().getToolConsumerInstanceGuid());

    }

}


text:
package connpool

import (
	"context"
	"fmt"
	"strings"
	"sync"
	"time"

	"vitess.io/vitess/go/pools"
	"vitess.io/vitess/go/vt/dbconfigs"
	"vitess.io/vitess/go/vt/servenv"
	"vitess.io/vitess/go/vt/vterrors"

	"vitess.io/vitess/go/mysql"
	"vitess.io/vitess/go/sqltypes"
	"vitess.io/vitess/go/sync2"
	"vitess.io/vitess/go/trace"
	"vitess.io/vitess/go/vt/dbconnpool"
	"vitess.io/vitess/go/vt/log"
	"vitess.io/vitess/go/vt/sqlparser"
	"vitess.io/vitess/go/vt/vttablet/tabletserver/tabletenv"

	querypb "vitess.io/vitess/go/vt/proto/query"
	vtrpcpb "vitess.io/vitess/go/vt/proto/vtrpc"
)

// DBConn is a db connection for tabletserver.
// It performs automatic reconnects as needed.
// Its Execute function has a timeout that can kill
// its own queries and the underlying connection.
// It will also trigger a CheckMySQL whenever applicable.
type DBConn struct {
	conn         *dbconnpool.DBConnection
	info         dbconfigs.Connector
	pool         *Pool
	dbaPool      *dbconnpool.ConnectionPool
	stats        *tabletenv.Stats
	current      sync2.AtomicString
	setting      string
	resetSetting string

	// err will be set if a query is killed through a Kill.
	errmu sync.Mutex
	err   error
}

// NewDBConn creates a new DBConn. It triggers a CheckMySQL if creation fails.
func NewDBConn(ctx context.Context, cp *Pool, appParams dbconfigs.Connector) (*DBConn, error) {
	start := time.Now()
	defer cp.env.Stats().MySQLTimings.Record("Connect", start)

	c, err := dbconnpool.NewDBConnection(ctx, appParams)
	if err != nil {
		cp.env.Stats().MySQLTimings.Record("ConnectError", start)
		cp.env.CheckMySQL()
		return nil, err
	}
	return &DBConn{
		conn:    c,
		info:    appParams,
		pool:    cp,
		dbaPool: cp.dbaPool,
		stats:   cp.env.Stats(),
	}, nil
}

// NewDBConnNoPool creates a new DBConn without a pool.
func NewDBConnNoPool(ctx context.Context, params dbconfigs.Connector, dbaPool *dbconnpool.ConnectionPool, setting *pools.Setting) (*DBConn, error) {
	c, err := dbconnpool.NewDBConnection(ctx, params)
	if err != nil {
		return nil, err
	}
	dbconn := &DBConn{
		conn:    c,
		info:    params,
		dbaPool: dbaPool,
		pool:    nil,
		stats:   tabletenv.NewStats(servenv.NewExporter("Temp", "Tablet")),
	}
	if setting == nil {
		return dbconn, nil
	}
	if err = dbconn.ApplySetting(ctx, setting); err != nil {
		dbconn.Close()
		return nil, err
	}
	return dbconn, nil
}

// Err returns an error if there was a client initiated error
// like a query kill.
func (dbc *DBConn) Err() error {
	dbc.errmu.Lock()
	defer dbc.errmu.Unlock()
	return dbc.err
}

// Exec executes the specified query. If there is a connection error, it will reconnect
// and retry. A failed reconnect will trigger a CheckMySQL.
func (dbc *DBConn) Exec(ctx context.Context, query string, maxrows int, wantfields bool) (*sqltypes.Result, error) {
	span, ctx := trace.NewSpan(ctx, "DBConn.Exec")
	defer span.Finish()

	for attempt := 1; attempt <= 2; attempt++ {
		r, err := dbc.execOnce(ctx, query, maxrows, wantfields)
		switch {
		case err == nil:
			// Success.
			return r, nil
		case mysql.IsConnLostDuringQuery(err):
			// Query probably killed. Don't retry.
			return nil, err
		case !mysql.IsConnErr(err):
			// Not a connection error. Don't retry.
			return nil, err
		case attempt == 2:
			// Reached the retry limit.
			return nil, err
		}

		// Connection error. Retry if context has not expired.
		select {
		case <-ctx.Done():
			return nil, err
		default:
		}

		if reconnectErr := dbc.reconnect(ctx); reconnectErr != nil {
			dbc.pool.env.CheckMySQL()
			// Return the error of the reconnect and not the original connection error.
			return nil, reconnectErr
		}

		// Reconnect succeeded. Retry query at second attempt.
	}
	panic("unreachable")
}

func (dbc *DBConn) execOnce(ctx context.Context, query string, maxrows int, wantfields bool) (*sqltypes.Result, error) {
	dbc.current.Set(query)
	defer dbc.current.Set("")

	// Check if the context is already past its deadline before
	// trying to execute the query.
	select {
	case <-ctx.Done():
		return nil, fmt.Errorf("%v before execution started", ctx.Err())
	default:
	}

	defer dbc.stats.MySQLTimings.Record("Exec", time.Now())

	done, wg := dbc.setDeadline(ctx)
	qr, err := dbc.conn.ExecuteFetch(query, maxrows, wantfields)

	if done != nil {
		close(done)
		wg.Wait()
	}
	if dbcerr := dbc.Err(); dbcerr != nil {
		return nil, dbcerr
	}
	return qr, err
}

// ExecOnce executes the specified query, but does not retry on connection errors.
func (dbc *DBConn) ExecOnce(ctx context.Context, query string, maxrows int, wantfields bool) (*sqltypes.Result, error) {
	return dbc.execOnce(ctx, query, maxrows, wantfields)
}

// FetchNext returns the next result set.
func (dbc *DBConn) FetchNext(ctx context.Context, maxrows int, wantfields bool) (*sqltypes.Result, error) {
	// Check if the context is already past its deadline before
	// trying to fetch the next result.
	select {
	case <-ctx.Done():
		return nil, fmt.Errorf("%v before reading next result set", ctx.Err())
	default:
	}
	res, _, _, err := dbc.conn.ReadQueryResult(maxrows, wantfields)
	if err != nil {
		return nil, err
	}
	return res, err

}

// Stream executes the query and streams the results.
func (dbc *DBConn) Stream(ctx context.Context, query string, callback func(*sqltypes.Result) error, alloc func() *sqltypes.Result, streamBufferSize int, includedFields querypb.ExecuteOptions_IncludedFields) error {
	span, ctx := trace.NewSpan(ctx, "DBConn.Stream")
	trace.AnnotateSQL(span, sqlparser.Preview(query))
	defer span.Finish()

	resultSent := false
	for attempt := 1; attempt <= 2; attempt++ {
		err := dbc.streamOnce(
			ctx,
			query,
			func(r *sqltypes.Result) error {
				if !resultSent {
					resultSent = true
					r = r.StripMetadata(includedFields)
				}
				return callback(r)
			},
			alloc,
			streamBufferSize,
		)
		switch {
		case err == nil:
			// Success.
			return nil
		case mysql.IsConnLostDuringQuery(err):
			// Query probably killed. Don't retry.
			return err
		case !mysql.IsConnErr(err):
			// Not a connection error. Don't retry.
			return err
		case attempt == 2:
			// Reached the retry limit.
			return err
		case resultSent:
			// Don't retry if streaming has started.
			return err
		}

		// Connection error. Retry if context has not expired.
		select {
		case <-ctx.Done():
			return err
		default:
		}
		if reconnectErr := dbc.reconnect(ctx); reconnectErr != nil {
			dbc.pool.env.CheckMySQL()
			// Return the error of the reconnect and not the original connection error.
			return reconnectErr
		}
	}
	panic("unreachable")
}

func (dbc *DBConn) streamOnce(ctx context.Context, query string, callback func(*sqltypes.Result) error, alloc func() *sqltypes.Result, streamBufferSize int) error {
	defer dbc.stats.MySQLTimings.Record("ExecStream", time.Now())

	dbc.current.Set(query)
	defer dbc.current.Set("")

	done, wg := dbc.setDeadline(ctx)
	err := dbc.conn.ExecuteStreamFetch(query, callback, alloc, streamBufferSize)

	if done != nil {
		close(done)
		wg.Wait()
	}
	if dbcerr := dbc.Err(); dbcerr != nil {
		return dbcerr
	}
	return err
}

// StreamOnce executes the query and streams the results. But, does not retry on connection errors.
func (dbc *DBConn) StreamOnce(ctx context.Context, query string, callback func(*sqltypes.Result) error, alloc func() *sqltypes.Result, streamBufferSize int, includedFields querypb.ExecuteOptions_IncludedFields) error {
	resultSent := false
	return dbc.streamOnce(
		ctx,
		query,
		func(r *sqltypes.Result) error {
			if !resultSent {
				resultSent = true
				r = r.StripMetadata(includedFields)
			}
			return callback(r)
		},
		alloc,
		streamBufferSize,
	)
}

var (
	getModeSQL    = "select @@global.sql_mode"
	getAutocommit = "select @@autocommit"
	getAutoIsNull = "select @@sql_auto_is_null"
)

// VerifyMode is a helper method to verify mysql is running with
// sql_mode = STRICT_TRANS_TABLES or STRICT_ALL_TABLES and autocommit=ON.
func (dbc *DBConn) VerifyMode(strictTransTables bool) error {
	if strictTransTables {
		qr, err := dbc.conn.ExecuteFetch(getModeSQL, 2, false)
		if err != nil {
			return err
		}
		if len(qr.Rows) != 1 {
			return vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "incorrect rowcount received for %s: %d", getModeSQL, len(qr.Rows))
		}
		sqlMode := qr.Rows[0][0].ToString()
		if !(strings.Contains(sqlMode, "STRICT_TRANS_TABLES") || strings.Contains(sqlMode, "STRICT_ALL_TABLES")) {
			return vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "require sql_mode to be STRICT_TRANS_TABLES or STRICT_ALL_TABLES: got '%s'", qr.Rows[0][0].ToString())
		}
	}
	qr, err := dbc.conn.ExecuteFetch(getAutocommit, 2, false)
	if err != nil {
		return err
	}
	if len(qr.Rows) != 1 {
		return vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "incorrect rowcount received for %s: %d", getAutocommit, len(qr.Rows))
	}
	if !strings.Contains(qr.Rows[0][0].ToString(), "1") {
		return vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "require autocommit to be 1: got %s", qr.Rows[0][0].ToString())
	}
	qr, err = dbc.conn.ExecuteFetch(getAutoIsNull, 2, false)
	if err != nil {
		return err
	}
	if len(qr.Rows) != 1 {
		return vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "incorrect rowcount received for %s: %d", getAutoIsNull, len(qr.Rows))
	}
	if !strings.Contains(qr.Rows[0][0].ToString(), "0") {
		return vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "require sql_auto_is_null to be 0: got %s", qr.Rows[0][0].ToString())
	}
	return nil
}

// Close closes the DBConn.
func (dbc *DBConn) Close() {
	dbc.conn.Close()
}

// ApplySetting implements the pools.Resource interface.
func (dbc *DBConn) ApplySetting(ctx context.Context, setting *pools.Setting) error {
	query := setting.GetQuery()
	if _, err := dbc.execOnce(ctx, query, 1, false); err != nil {
		return err
	}
	dbc.setting = query
	dbc.resetSetting = setting.GetResetQuery()
	return nil
}

// IsSettingApplied implements the pools.Resource interface.
func (dbc *DBConn) IsSettingApplied() bool {
	return dbc.setting != ""
}

// IsSameSetting implements the pools.Resource interface.
func (dbc *DBConn) IsSameSetting(setting string) bool {
	return strings.EqualFold(setting, dbc.setting)
}

// ResetSetting implements the pools.Resource interface.
func (dbc *DBConn) ResetSetting(ctx context.Context) error {
	if _, err := dbc.execOnce(ctx, dbc.resetSetting, 1, false); err != nil {
		return err
	}
	dbc.setting = ""
	dbc.resetSetting = ""
	return nil
}

var _ pools.Resource = (*DBConn)(nil)

// IsClosed returns true if DBConn is closed.
func (dbc *DBConn) IsClosed() bool {
	return dbc.conn.IsClosed()
}

// Recycle returns the DBConn to the pool.
func (dbc *DBConn) Recycle() {
	switch {
	case dbc.pool == nil:
		dbc.Close()
	case dbc.conn.IsClosed():
		dbc.pool.Put(nil)
	default:
		dbc.pool.Put(dbc)
	}
}

// Taint unregister connection from original pool and taints the connection.
func (dbc *DBConn) Taint() {
	if dbc.pool == nil {
		return
	}
	dbc.pool.Put(nil)
	dbc.pool = nil
}

// Kill kills the currently executing query both on MySQL side
// and on the connection side. If no query is executing, it's a no-op.
// Kill will also not kill a query more than once.
func (dbc *DBConn) Kill(reason string, elapsed time.Duration) error {
	dbc.stats.KillCounters.Add("Queries", 1)
	log.Infof("Due to %s, elapsed time: %v, killing query ID %v %s", reason, elapsed, dbc.conn.ID(), dbc.CurrentForLogging())

	// Client side action. Set error and close connection.
	dbc.errmu.Lock()
	dbc.err = vterrors.Errorf(vtrpcpb.Code_CANCELED, "(errno 2013) due to %s, elapsed time: %v, killing query ID %v", reason, elapsed, dbc.conn.ID())
	dbc.errmu.Unlock()
	dbc.conn.Close()

	// Server side action. Kill the session.
	killConn, err := dbc.dbaPool.Get(context.TODO())
	if err != nil {
		log.Warningf("Failed to get conn from dba pool: %v", err)
		return err
	}
	defer killConn.Recycle()
	sql := fmt.Sprintf("kill %d", dbc.conn.ID())
	_, err = killConn.ExecuteFetch(sql, 10000, false)
	if err != nil {
		log.Errorf("Could not kill query ID %v %s: %v", dbc.conn.ID(),
			dbc.CurrentForLogging(), err)
		return err
	}
	return nil
}

// Current returns the currently executing query.
func (dbc *DBConn) Current() string {
	return dbc.current.Get()
}

// ID returns the connection id.
func (dbc *DBConn) ID() int64 {
	return dbc.conn.ID()
}

// BaseShowTables returns a query that shows tables
func (dbc *DBConn) BaseShowTables() string {
	return dbc.conn.BaseShowTables()
}

// BaseShowTablesWithSizes returns a query that shows tables and their sizes
func (dbc *DBConn) BaseShowTablesWithSizes() string {
	return dbc.conn.BaseShowTablesWithSizes()
}

func (dbc *DBConn) reconnect(ctx context.Context) error {
	dbc.conn.Close()
	// Reuse MySQLTimings from dbc.conn.
	newConn, err := dbconnpool.NewDBConnection(ctx, dbc.info)
	if err != nil {
		return err
	}
	dbc.conn = newConn
	if dbc.IsSettingApplied() {
		err = dbc.applySameSetting(ctx)
		if err != nil {
			return err
		}
	}
	dbc.errmu.Lock()
	dbc.err = nil
	dbc.errmu.Unlock()
	return nil
}

// setDeadline starts a goroutine that will kill the currently executing query
// if the deadline is exceeded. It returns a channel and a waitgroup. After the
// query is done executing, the caller is required to close the done channel
// and wait for the waitgroup to make sure that the necessary cleanup is done.
func (dbc *DBConn) setDeadline(ctx context.Context) (chan bool, *sync.WaitGroup) {
	if ctx.Done() == nil {
		return nil, nil
	}
	done := make(chan bool)
	var wg sync.WaitGroup
	wg.Add(1)
	go func() {
		defer wg.Done()
		startTime := time.Now()
		select {
		case <-ctx.Done():
			dbc.Kill(ctx.Err().Error(), time.Since(startTime))
		case <-done:
			return
		}
		elapsed := time.Since(startTime)

		// Give 2x the elapsed time and some buffer as grace period
		// for the query to get killed.
		tmr2 := time.NewTimer(2*elapsed + 5*time.Second)
		defer tmr2.Stop()
		select {
		case <-tmr2.C:
			dbc.stats.InternalErrors.Add("HungQuery", 1)
			log.Warningf("Query may be hung: %s", dbc.CurrentForLogging())
		case <-done:
			return
		}
		<-done
		log.Warningf("Hung query returned")
	}()
	return done, &wg
}

// CurrentForLogging applies transformations to the query making it suitable to log.
// It applies sanitization rules based on tablet settings and limits the max length of
// queries.
func (dbc *DBConn) CurrentForLogging() string {
	var queryToLog string
	if dbc.pool != nil && dbc.pool.env != nil && dbc.pool.env.Config() != nil && !dbc.pool.env.Config().SanitizeLogMessages {
		queryToLog = dbc.Current()
	} else {
		queryToLog, _ = sqlparser.RedactSQLQuery(dbc.Current())
	}
	return sqlparser.TruncateForLog(queryToLog)
}

func (dbc *DBConn) applySameSetting(ctx context.Context) (err error) {
	_, err = dbc.execOnce(ctx, dbc.setting, 1, false)
	return
}


text:
package org.test;

import loon.LTransition;
import loon.Screen;
import loon.canvas.LColor;
import loon.events.GameTouch;
import loon.live2d.framework.LAppLive2DManager;
import loon.live2d.framework.LAppModel;
import loon.opengl.GLEx;
import loon.utils.timer.LTimer;
import loon.utils.timer.LTimerContext;

public class Live2dTest extends Screen {

	public LTransition onTransition() {
		return LTransition.newPixelWind(LColor.white);
	}

	LTimer timer = new LTimer(200);

	@Override
	public void draw(GLEx g) {
		if (isTransitionCompleted() && isOnLoadComplete()) {
			if (model != null) {
				if (timer.action(elapsedTime)) {
					model.update();
				}
				// g.scale(0.5f, 0.5f);
				model.draw(g);
			}
		}
	}

	LAppModel model;

	@Override
	public void onLoad() {

		// haru
		// shizuku
		// wanko
		String modelSettingPath = "assets/live2d/haru/haru.model.json";

		LAppLive2DManager manager = new LAppLive2DManager();

		model = manager.loadModel(modelSettingPath);
		// model.getLive2DModel().setScale(0.2f, 0.2f);
		// model.draw();

		add(MultiScreenTest.getBackButton(this,0));
	}

	@Override
	public void alter(LTimerContext timer) {

	}

	@Override
	public void resize(int width, int height) {

	}

	@Override
	public void touchDown(GameTouch e) {
		model.onDrag(e.getX(), e.getY());
	}

	@Override
	public void touchUp(GameTouch e) {
		model.setDrag(0, 0);
	}

	@Override
	public void touchMove(GameTouch e) {

	}

	@Override
	public void touchDrag(GameTouch e) {

	}

	@Override
	public void resume() {

	}

	@Override
	public void pause() {

	}

	@Override
	public void close() {

	}

}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Acta Bot. Yunnan. 12:28, fig. 6. 1990

#### Original name
null

### Remarks
null


text:
package com.sferadev.danacast.utils;

import java.io.FileInputStream;
import java.util.Map;

import fi.iki.elonen.NanoHTTPD;

public class WebServer extends NanoHTTPD {

    String filePath;

    public WebServer(String path) {
        super(8080);
        filePath = path;
    }

    @Override
    public Response serve(String uri, Method method,
                          Map<String, String> header,
                          Map<String, String> parameters,
                          Map<String, String> files) {
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(filePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new NanoHTTPD.Response(Response.Status.OK, "video/mp4", fileInputStream);
    }
}


text:
/* THIS IS NOT AN X CONSORTIUM STANDARD OR AN X PROJECT TEAM SPECIFICATION */

#ifndef _XSHM_H_
#define _XSHM_H_

#include <X11/Xfuncproto.h>
#include <X11/extensions/shm.h>

#ifndef _XSHM_SERVER_
typedef unsigned long ShmSeg;

typedef struct {
    int	type;		    /* of event */
    unsigned long serial;   /* # of last request processed by server */
    Bool send_event;	    /* true if this came frome a SendEvent request */
    Display *display;	    /* Display the event was read from */
    Drawable drawable;	    /* drawable of request */
    int major_code;	    /* ShmReqCode */
    int minor_code;	    /* X_ShmPutImage */
    ShmSeg shmseg;	    /* the ShmSeg used in the request */
    unsigned long offset;   /* the offset into ShmSeg used in the request */
} XShmCompletionEvent;

typedef struct {
    ShmSeg shmseg;	/* resource id */
    int shmid;		/* kernel id */
    char *shmaddr;	/* address in client */
    Bool readOnly;	/* how the server should attach it */
} XShmSegmentInfo;

_XFUNCPROTOBEGIN

Bool XShmQueryExtension(
    Display*		/* dpy */
);

int XShmGetEventBase(
    Display* 		/* dpy */
);

Bool XShmQueryVersion(
    Display*		/* dpy */,
    int*		/* majorVersion */,
    int*		/* minorVersion */,
    Bool*		/* sharedPixmaps */
);

int XShmPixmapFormat(
    Display*		/* dpy */
);

Bool XShmAttach(
    Display*		/* dpy */,
    XShmSegmentInfo*	/* shminfo */
);

Bool XShmDetach(
    Display*		/* dpy */,
    XShmSegmentInfo*	/* shminfo */
);

Bool XShmPutImage(
    Display*		/* dpy */,
    Drawable		/* d */,
    GC			/* gc */,
    XImage*		/* image */,
    int			/* src_x */,
    int			/* src_y */,
    int			/* dst_x */,
    int			/* dst_y */,
    unsigned int	/* src_width */,
    unsigned int	/* src_height */,
    Bool		/* send_event */
);

Bool XShmGetImage(
    Display*		/* dpy */,
    Drawable		/* d */,
    XImage*		/* image */,
    int			/* x */,
    int			/* y */,
    unsigned long	/* plane_mask */
);

XImage *XShmCreateImage(
    Display*		/* dpy */,
    Visual*		/* visual */,
    unsigned int	/* depth */,
    int			/* format */,
    char*		/* data */,
    XShmSegmentInfo*	/* shminfo */,
    unsigned int	/* width */,
    unsigned int	/* height */
);

Pixmap XShmCreatePixmap(
    Display*		/* dpy */,
    Drawable		/* d */,
    char*		/* data */,
    XShmSegmentInfo*	/* shminfo */,
    unsigned int	/* width */,
    unsigned int	/* height */,
    unsigned int	/* depth */
);

_XFUNCPROTOEND
#endif /* _XSHM_SERVER_ */

#endif


text:
- [Instagram](https://www.instagram.com/)
- [Twitter](https://twitter.com))


text:
<!DOCTYPE html>

  {% include head.html %}

      {{ site.title }}

        Blog
        {% assign pages_list = site.pages | sort:"url" %}
          {% for node in pages_list %}
            {% if node.title != null %}
              {% if node.layout == "page" %}
                {{ node.title }}
              {% endif %}
            {% endif %}
          {% endfor %}

    {% if page.slug != 404 %}

{{ site.title }}

{{ site.tagline }}

    {% endif %}

        {{ content }}

            Copyright © 2017 Sergio Vilar


text:
class RiderYearRegistrationsController < ApplicationController
	skip_before_action :authenticate_admin!

	before_action :redirect_if_public_site_is_not_active
	before_action :validate_user_w_associated_ryr, except: [:new, :create]

	def new
		## assume never registered before - brand new ... and deal with alternative scenario once this is built
		@ryr = RiderYearRegistration.new
		options = RideYear.current.custom_ride_options
		unless options.empty?
			@options = options.map{|o| [ o.display_name, o.id ] }
		end
	end

	def create
		@ryr = RiderYearRegistration.new(user: current_user)
		if @ryr.update_attributes(ryr_params)
			redirect_to rider_year_registrations_agree_to_terms_path(rider_year_registration: @ryr)
		else
			@errors = @ryr.errors
			render :new
		end
	end

	def new_agree_to_terms
		@ryr = RiderYearRegistration.find(params[:rider_year_registration])
	end

	def create_agree_to_terms
		@ryr = RiderYearRegistration.find(params[:ryr_id])
		if @ryr.update_attributes(full_params)

			if current_user.persistent_rider_profile
				redirect_to rider_year_registrations_pay_reg_fee_path(rider_year_registration: @ryr)
			else # ie a first time rider
				redirect_to rider_year_registrations_persistent_rider_profile_path(rider_year_registration: @ryr)
			end

		else
			@errors = @ryr.errors
			render :new_agree_to_terms
		end
	end

	def new_persistent_rider_profile
		@ryr = RiderYearRegistration.find(params[:rider_year_registration])
		@prp = @ryr.user.build_persistent_rider_profile(user: @ryr.user)
	end

	def create_persistent_rider_profile
		@ryr = RiderYearRegistration.find(params[:ryr_id])
		@prp = @ryr.user.build_persistent_rider_profile(user: @ryr.user)

		if @prp.update_attributes(prp_params)
			redirect_to rider_year_registrations_mailing_address_path(rider_year_registration: @ryr)
		else
			@errors = @prp.errors
			render :new_persistent_rider_profile
		end

	end

	def new_mailing_address
		@ryr = RiderYearRegistration.find(params[:rider_year_registration])
		@ryr.mailing_addresses.build
	end

	def create_mailing_address
		@ryr = RiderYearRegistration.find(params[:ryr_id])
		m_a = @ryr.mailing_addresses.build(user: @ryr.user)

		if m_a.update_attributes(mailing_addesses_params)
			redirect_to rider_year_registrations_pay_reg_fee_path(rider_year_registration: @ryr)
		else
			@errors = m_a.errors
			render :new_mailing_address
		end
	end

	def new_pay_reg_fee
		@ryr = RiderYearRegistration.find(params[:rider_year_registration])
		@mailing_addresses = @ryr.mailing_addresses
		@custom_billing_address = MailingAddress.new
		# @registration_fee = RideYear.current_fee
	end

	def create_pay_reg_fee

		@ryr = RiderYearRegistration.find(params[:ryr_id])
		pm = PaymentMaker.new(@ryr, :registration, full_params)
		begin
			@receipt_or_errors = pm.process_payment
		rescue
			render json: {
				errors: "We're very sorry, but there was an error connecting to PayPal."
			}
			return
		end
		if @receipt_or_errors.instance_of?(Receipt)
			@rider = current_user.persistent_rider_profile
			RiderYearRegistrationsMailer.successful_registration_welcome_rider(@ryr).deliver
			render json: {
				success: 'no errors what?',
				prp_address: persistent_rider_profile_url(@rider),
				ryr: @ryr
			}
		else
			render json: @receipt_or_errors
		end
	end

	private

	def validate_user_w_associated_ryr
		id_num = params[:ryr_id] || params[:rider_year_registration]
		ryr = RiderYearRegistration.find(id_num)
		unless ryr.user == current_user
			flash[:error] = "Please log in to your own account to register."
      redirect_to new_user_session_path
    end
	end

	def full_params
    params.require(:rider_year_registration).permit(:ride_option, :goal, :agree_to_terms, :cc_type, :cc_number, :cc_expire_month, :cc_expire_year, :cc_cvv2, :custom_billing_address, :mailing_addresses, :discount_code, :custom_ride_option,
    	:mailing_addresses_attributes => [
    			:line_1, :line_2, :city, :state, :zip
    		],
    	:persistent_rider_profile_attributes => [
    			:primary_phone, :secondary_phone, :avatar, :birthdate, :bio
    		],
    	:mailing_address => [
    		:line_1, :line_2, :city, :state, :zip
    	]
    )
  end

  def mailing_addesses_params
  	full_params['mailing_addresses_attributes']['0']
  end

  def prp_params
  	full_params['persistent_rider_profile_attributes']
  end

  def ryr_params
  	{
  		ride_option: full_params[:ride_option],
  		goal: full_params[:goal],
  		discount_code: full_params[:discount_code]
  	}
  end

end


text:
<archimate:BusinessObject
    xmlns:archimate="http://www.archimatetool.com/archimate"
    name="Spring"
    id="60c079fb-ac7e-471e-915e-24fdcadc7ce8">
  <properties/>
</archimate:BusinessObject>


text:
    <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
    <title>Number Property</title>
    <xml>
    </xml>
    <link rel="stylesheet" type="text/css" href="MSDN.css" />

            log4net SDK Reference

NativeError.Number Property

 Gets the number of the native error.

        [Visual Basic]

Public ReadOnly Property Number As Integer

        [C#]

public int Number {get;}

Property Value

 The number of the native error.

Remarks

 Gets the number of the native error.

See Also

NativeError Class | log4net.Util Namespace

Copyright 2001-2006 The Apache Software Foundation.

Generated from assembly log4net [1.2.10.0]