text:
// +build linux

package e2e_node

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"sort"
	"strconv"
	"strings"
	"sync"
	"text/tabwriter"
	"time"

	cadvisorclient "github.com/google/cadvisor/client/v2"
	cadvisorapiv2 "github.com/google/cadvisor/info/v2"
	"github.com/opencontainers/runc/libcontainer/cgroups"
	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/stats"
	"k8s.io/kubernetes/pkg/labels"
	"k8s.io/kubernetes/pkg/util/procfs"
	"k8s.io/kubernetes/pkg/util/runtime"
	"k8s.io/kubernetes/pkg/util/uuid"
	"k8s.io/kubernetes/pkg/util/wait"
	"k8s.io/kubernetes/test/e2e/framework"

	. "github.com/onsi/gomega"
)

const (
	// resource monitoring
	cadvisorImageName = "google/cadvisor:latest"
	cadvisorPodName   = "cadvisor"
	cadvisorPort      = 8090
	// housekeeping interval of Cadvisor (second)
	houseKeepingInterval = 1
)

var (
	systemContainers map[string]string
)

type ResourceCollector struct {
	client  *cadvisorclient.Client
	request *cadvisorapiv2.RequestOptions

	pollingInterval time.Duration
	buffers         map[string][]*framework.ContainerResourceUsage
	lock            sync.RWMutex
	stopCh          chan struct{}
}

// NewResourceCollector creates a resource collector object which collects
// resource usage periodically from Cadvisor
func NewResourceCollector(interval time.Duration) *ResourceCollector {
	buffers := make(map[string][]*framework.ContainerResourceUsage)
	return &ResourceCollector{
		pollingInterval: interval,
		buffers:         buffers,
	}
}

// Start starts resource collector and connects to the standalone Cadvisor pod
// then repeatedly runs collectStats.
func (r *ResourceCollector) Start() {
	// Get the cgroup container names for kubelet and docker
	kubeletContainer, err := getContainerNameForProcess(kubeletProcessName, "")
	dockerContainer, err := getContainerNameForProcess(dockerProcessName, dockerPidFile)
	if err == nil {
		systemContainers = map[string]string{
			stats.SystemContainerKubelet: kubeletContainer,
			stats.SystemContainerRuntime: dockerContainer,
		}
	} else {
		framework.Failf("Failed to get docker container name in test-e2e-node resource collector.")
	}

	wait.Poll(1*time.Second, 1*time.Minute, func() (bool, error) {
		var err error
		r.client, err = cadvisorclient.NewClient(fmt.Sprintf("http://localhost:%d/", cadvisorPort))
		if err == nil {
			return true, nil
		}
		return false, err
	})

	Expect(r.client).NotTo(BeNil(), "cadvisor client not ready")

	r.request = &cadvisorapiv2.RequestOptions{IdType: "name", Count: 1, Recursive: false}
	r.stopCh = make(chan struct{})

	oldStatsMap := make(map[string]*cadvisorapiv2.ContainerStats)
	go wait.Until(func() { r.collectStats(oldStatsMap) }, r.pollingInterval, r.stopCh)
}

// Stop stops resource collector collecting stats. It does not clear the buffer
func (r *ResourceCollector) Stop() {
	close(r.stopCh)
}

// Reset clears the stats buffer of resource collector.
func (r *ResourceCollector) Reset() {
	r.lock.Lock()
	defer r.lock.Unlock()
	for _, name := range systemContainers {
		r.buffers[name] = []*framework.ContainerResourceUsage{}
	}
}

// GetCPUSummary gets CPU usage in percentile.
func (r *ResourceCollector) GetCPUSummary() framework.ContainersCPUSummary {
	result := make(framework.ContainersCPUSummary)
	for key, name := range systemContainers {
		data := r.GetBasicCPUStats(name)
		result[key] = data
	}
	return result
}

// LogLatest logs the latest resource usage.
func (r *ResourceCollector) LogLatest() {
	summary, err := r.GetLatest()
	if err != nil {
		framework.Logf("%v", err)
	}
	framework.Logf("%s", formatResourceUsageStats(summary))
}

// collectStats collects resource usage from Cadvisor.
func (r *ResourceCollector) collectStats(oldStatsMap map[string]*cadvisorapiv2.ContainerStats) {
	for _, name := range systemContainers {
		ret, err := r.client.Stats(name, r.request)
		if err != nil {
			framework.Logf("Error getting container stats, err: %v", err)
			return
		}
		cStats, ok := ret[name]
		if !ok {
			framework.Logf("Missing info/stats for container %q", name)
			return
		}

		newStats := cStats.Stats[0]

		if oldStats, ok := oldStatsMap[name]; ok && oldStats.Timestamp.Before(newStats.Timestamp) {
			if oldStats.Timestamp.Equal(newStats.Timestamp) {
				continue
			}
			r.buffers[name] = append(r.buffers[name], computeContainerResourceUsage(name, oldStats, newStats))
		}
		oldStatsMap[name] = newStats
	}
}

// computeContainerResourceUsage computes resource usage based on new data sample.
func computeContainerResourceUsage(name string, oldStats, newStats *cadvisorapiv2.ContainerStats) *framework.ContainerResourceUsage {
	return &framework.ContainerResourceUsage{
		Name:                    name,
		Timestamp:               newStats.Timestamp,
		CPUUsageInCores:         float64(newStats.Cpu.Usage.Total-oldStats.Cpu.Usage.Total) / float64(newStats.Timestamp.Sub(oldStats.Timestamp).Nanoseconds()),
		MemoryUsageInBytes:      newStats.Memory.Usage,
		MemoryWorkingSetInBytes: newStats.Memory.WorkingSet,
		MemoryRSSInBytes:        newStats.Memory.RSS,
		CPUInterval:             newStats.Timestamp.Sub(oldStats.Timestamp),
	}
}

// GetLatest gets the latest resource usage from stats buffer.
func (r *ResourceCollector) GetLatest() (framework.ResourceUsagePerContainer, error) {
	r.lock.RLock()
	defer r.lock.RUnlock()
	stats := make(framework.ResourceUsagePerContainer)
	for key, name := range systemContainers {
		contStats, ok := r.buffers[name]
		if !ok || len(contStats) == 0 {
			return nil, fmt.Errorf("No resource usage data for %s container (%s)", key, name)
		}
		stats[key] = contStats[len(contStats)-1]
	}
	return stats, nil
}

type resourceUsageByCPU []*framework.ContainerResourceUsage

func (r resourceUsageByCPU) Len() int           { return len(r) }
func (r resourceUsageByCPU) Swap(i, j int)      { r[i], r[j] = r[j], r[i] }
func (r resourceUsageByCPU) Less(i, j int) bool { return r[i].CPUUsageInCores < r[j].CPUUsageInCores }

// The percentiles to report.
var percentiles = [...]float64{0.50, 0.90, 0.95, 0.99, 1.00}

// GetBasicCPUStats returns the percentiles the cpu usage in cores for
// containerName. This method examines all data currently in the buffer.
func (r *ResourceCollector) GetBasicCPUStats(containerName string) map[float64]float64 {
	r.lock.RLock()
	defer r.lock.RUnlock()
	result := make(map[float64]float64, len(percentiles))

	// We must make a copy of array, otherwise the timeseries order is changed.
	usages := make([]*framework.ContainerResourceUsage, 0)
	for _, usage := range r.buffers[containerName] {
		usages = append(usages, usage)
	}

	sort.Sort(resourceUsageByCPU(usages))
	for _, q := range percentiles {
		index := int(float64(len(usages))*q) - 1
		if index < 0 {
			// We don't have enough data.
			result[q] = 0
			continue
		}
		result[q] = usages[index].CPUUsageInCores
	}
	return result
}

func formatResourceUsageStats(containerStats framework.ResourceUsagePerContainer) string {
	// Example output:
	//
	// Resource usage for node "e2e-test-foo-minion-abcde":
	// container        cpu(cores)  memory(MB)
	// "/"              0.363       2942.09
	// "/docker-daemon" 0.088       521.80
	// "/kubelet"       0.086       424.37
	// "/system"        0.007       119.88
	buf := &bytes.Buffer{}
	w := tabwriter.NewWriter(buf, 1, 0, 1, ' ', 0)
	fmt.Fprintf(w, "container\tcpu(cores)\tmemory_working_set(MB)\tmemory_rss(MB)\n")
	for name, s := range containerStats {
		fmt.Fprintf(w, "%q\t%.3f\t%.2f\t%.2f\n", name, s.CPUUsageInCores, float64(s.MemoryWorkingSetInBytes)/(1024*1024), float64(s.MemoryRSSInBytes)/(1024*1024))
	}
	w.Flush()
	return fmt.Sprintf("Resource usage:\n%s", buf.String())
}

func formatCPUSummary(summary framework.ContainersCPUSummary) string {
	// Example output for a node (the percentiles may differ):
	// CPU usage of containers on node "e2e-test-foo-minion-0vj7":
	// container        5th%  50th% 90th% 95th%
	// "/"              0.051 0.159 0.387 0.455
	// "/runtime        0.000 0.000 0.146 0.166
	// "/kubelet"       0.036 0.053 0.091 0.154
	// "/misc"          0.001 0.001 0.001 0.002
	var summaryStrings []string
	var header []string
	header = append(header, "container")
	for _, p := range percentiles {
		header = append(header, fmt.Sprintf("%.0fth%%", p*100))
	}

	buf := &bytes.Buffer{}
	w := tabwriter.NewWriter(buf, 1, 0, 1, ' ', 0)
	fmt.Fprintf(w, "%s\n", strings.Join(header, "\t"))

	for _, containerName := range framework.TargetContainers() {
		var s []string
		s = append(s, fmt.Sprintf("%q", containerName))
		data, ok := summary[containerName]
		for _, p := range percentiles {
			value := "N/A"
			if ok {
				value = fmt.Sprintf("%.3f", data[p])
			}
			s = append(s, value)
		}
		fmt.Fprintf(w, "%s\n", strings.Join(s, "\t"))
	}
	w.Flush()
	summaryStrings = append(summaryStrings, fmt.Sprintf("CPU usage of containers:\n%s", buf.String()))

	return strings.Join(summaryStrings, "\n")
}

// createCadvisorPod creates a standalone cadvisor pod for fine-grain resource monitoring.
func getCadvisorPod() *api.Pod {
	return &api.Pod{
		ObjectMeta: api.ObjectMeta{
			Name: cadvisorPodName,
		},
		Spec: api.PodSpec{
			// It uses a host port for the tests to collect data.
			// Currently we can not use port mapping in test-e2e-node.
			SecurityContext: &api.PodSecurityContext{
				HostNetwork: true,
			},
			Containers: []api.Container{
				{
					Image: cadvisorImageName,
					Name:  cadvisorPodName,
					Ports: []api.ContainerPort{
						{
							Name:          "http",
							HostPort:      cadvisorPort,
							ContainerPort: cadvisorPort,
							Protocol:      api.ProtocolTCP,
						},
					},
					VolumeMounts: []api.VolumeMount{
						{
							Name:      "sys",
							ReadOnly:  true,
							MountPath: "/sys",
						},
						{
							Name:      "var-run",
							ReadOnly:  false,
							MountPath: "/var/run",
						},
						{
							Name:      "docker",
							ReadOnly:  true,
							MountPath: "/var/lib/docker/",
						},
						{
							Name:      "rootfs",
							ReadOnly:  true,
							MountPath: "/rootfs",
						},
					},
					Args: []string{
						"--profiling",
						fmt.Sprintf("--housekeeping_interval=%ds", houseKeepingInterval),
						fmt.Sprintf("--port=%d", cadvisorPort),
					},
				},
			},
			Volumes: []api.Volume{
				{
					Name:         "rootfs",
					VolumeSource: api.VolumeSource{HostPath: &api.HostPathVolumeSource{Path: "/"}},
				},
				{
					Name:         "var-run",
					VolumeSource: api.VolumeSource{HostPath: &api.HostPathVolumeSource{Path: "/var/run"}},
				},
				{
					Name:         "sys",
					VolumeSource: api.VolumeSource{HostPath: &api.HostPathVolumeSource{Path: "/sys"}},
				},
				{
					Name:         "docker",
					VolumeSource: api.VolumeSource{HostPath: &api.HostPathVolumeSource{Path: "/var/lib/docker"}},
				},
			},
		},
	}
}

// deletePodsSync deletes a list of pods and block until pods disappear.
func deletePodsSync(f *framework.Framework, pods []*api.Pod) {
	var wg sync.WaitGroup
	for _, pod := range pods {
		wg.Add(1)
		go func(pod *api.Pod) {
			defer wg.Done()

			err := f.PodClient().Delete(pod.ObjectMeta.Name, api.NewDeleteOptions(30))
			Expect(err).NotTo(HaveOccurred())

			Expect(framework.WaitForPodToDisappear(f.Client, f.Namespace.Name, pod.ObjectMeta.Name, labels.Everything(),
				30*time.Second, 10*time.Minute)).NotTo(HaveOccurred())
		}(pod)
	}
	wg.Wait()
	return
}

// newTestPods creates a list of pods (specification) for test.
func newTestPods(numPods int, imageName, podType string) []*api.Pod {
	var pods []*api.Pod
	for i := 0; i < numPods; i++ {
		podName := "test-" + string(uuid.NewUUID())
		labels := map[string]string{
			"type": podType,
			"name": podName,
		}
		pods = append(pods,
			&api.Pod{
				ObjectMeta: api.ObjectMeta{
					Name:   podName,
					Labels: labels,
				},
				Spec: api.PodSpec{
					// Restart policy is always (default).
					Containers: []api.Container{
						{
							Image: imageName,
							Name:  podName,
						},
					},
				},
			})
	}
	return pods
}

// Time series of resource usage
type ResourceSeries struct {
	Timestamp            []int64           `json:"ts"`
	CPUUsageInMilliCores []int64           `json:"cpu"`
	MemoryRSSInMegaBytes []int64           `json:"memory"`
	Units                map[string]string `json:"unit"`
}

// GetResourceSeriesWithLabels gets the time series of resource usage of each container.
func (r *ResourceCollector) GetResourceTimeSeries() map[string]*ResourceSeries {
	resourceSeries := make(map[string]*ResourceSeries)
	for key, name := range systemContainers {
		newSeries := &ResourceSeries{Units: map[string]string{
			"cpu":    "mCPU",
			"memory": "MB",
		}}
		resourceSeries[key] = newSeries
		for _, usage := range r.buffers[name] {
			newSeries.Timestamp = append(newSeries.Timestamp, usage.Timestamp.UnixNano())
			newSeries.CPUUsageInMilliCores = append(newSeries.CPUUsageInMilliCores, int64(usage.CPUUsageInCores*1000))
			newSeries.MemoryRSSInMegaBytes = append(newSeries.MemoryRSSInMegaBytes, int64(float64(usage.MemoryUsageInBytes)/(1024*1024)))
		}
	}
	return resourceSeries
}

// Code for getting container name of docker, copied from pkg/kubelet/cm/container_manager_linux.go
// since they are not exposed
const (
	kubeletProcessName    = "kubelet"
	dockerProcessName     = "docker"
	dockerPidFile         = "/var/run/docker.pid"
	containerdProcessName = "docker-containerd"
	containerdPidFile     = "/run/docker/libcontainerd/docker-containerd.pid"
)

func getPidsForProcess(name, pidFile string) ([]int, error) {
	if len(pidFile) > 0 {
		if pid, err := getPidFromPidFile(pidFile); err == nil {
			return []int{pid}, nil
		} else {
			// log the error and fall back to pidof
			runtime.HandleError(err)
		}
	}
	return procfs.PidOf(name)
}

func getPidFromPidFile(pidFile string) (int, error) {
	file, err := os.Open(pidFile)
	if err != nil {
		return 0, fmt.Errorf("error opening pid file %s: %v", pidFile, err)
	}
	defer file.Close()

	data, err := ioutil.ReadAll(file)
	if err != nil {
		return 0, fmt.Errorf("error reading pid file %s: %v", pidFile, err)
	}

	pid, err := strconv.Atoi(string(data))
	if err != nil {
		return 0, fmt.Errorf("error parsing %s as a number: %v", string(data), err)
	}

	return pid, nil
}

func getContainerNameForProcess(name, pidFile string) (string, error) {
	pids, err := getPidsForProcess(name, pidFile)
	if err != nil {
		return "", fmt.Errorf("failed to detect process id for %q - %v", name, err)
	}
	if len(pids) == 0 {
		return "", nil
	}
	cont, err := getContainer(pids[0])
	if err != nil {
		return "", err
	}
	return cont, nil
}

// getContainer returns the cgroup associated with the specified pid.
// It enforces a unified hierarchy for memory and cpu cgroups.
// On systemd environments, it uses the name=systemd cgroup for the specified pid.
func getContainer(pid int) (string, error) {
	cgs, err := cgroups.ParseCgroupFile(fmt.Sprintf("/proc/%d/cgroup", pid))
	if err != nil {
		return "", err
	}

	cpu, found := cgs["cpu"]
	if !found {
		return "", cgroups.NewNotFoundError("cpu")
	}
	memory, found := cgs["memory"]
	if !found {
		return "", cgroups.NewNotFoundError("memory")
	}

	// since we use this container for accounting, we need to ensure its a unified hierarchy.
	if cpu != memory {
		return "", fmt.Errorf("cpu and memory cgroup hierarchy not unified.  cpu: %s, memory: %s", cpu, memory)
	}

	// on systemd, every pid is in a unified cgroup hierarchy (name=systemd as seen in systemd-cgls)
	// cpu and memory accounting is off by default, users may choose to enable it per unit or globally.
	// users could enable CPU and memory accounting globally via /etc/systemd/system.conf (DefaultCPUAccounting=true DefaultMemoryAccounting=true).
	// users could also enable CPU and memory accounting per unit via CPUAccounting=true and MemoryAccounting=true
	// we only warn if accounting is not enabled for CPU or memory so as to not break local development flows where kubelet is launched in a terminal.
	// for example, the cgroup for the user session will be something like /user.slice/user-X.slice/session-X.scope, but the cpu and memory
	// cgroup will be the closest ancestor where accounting is performed (most likely /) on systems that launch docker containers.
	// as a result, on those systems, you will not get cpu or memory accounting statistics for kubelet.
	// in addition, you would not get memory or cpu accounting for the runtime unless accounting was enabled on its unit (or globally).
	if systemd, found := cgs["name=systemd"]; found {
		if systemd != cpu {
			log.Printf("CPUAccounting not enabled for pid: %d", pid)
		}
		if systemd != memory {
			log.Printf("MemoryAccounting not enabled for pid: %d", pid)
		}
		return systemd, nil
	}

	return cpu, nil
}


text:
/* this file has been autogenerated by vtkNodeJsWrap */
/* editing this might proof futile */

#ifndef NATIVE_EXTENSION_VTK_VTKINTERACTIVEAREAWRAP_H
#define NATIVE_EXTENSION_VTK_VTKINTERACTIVEAREAWRAP_H

#include <nan.h>

#include <vtkSmartPointer.h>
#include <vtkInteractiveArea.h>

#include "vtkContextAreaWrap.h"
#include "../../plus/plus.h"

class VtkInteractiveAreaWrap : public VtkContextAreaWrap
{
	public:
		using Nan::ObjectWrap::Wrap;
		static void Init(v8::Local<v8::Object> exports);
		static void InitPtpl();
		static void ConstructorGetter(
			v8::Local<v8::String> property,
			const Nan::PropertyCallbackInfo<v8::Value>& info);

		VtkInteractiveAreaWrap(vtkSmartPointer<vtkInteractiveArea>);
		VtkInteractiveAreaWrap();
		~VtkInteractiveAreaWrap( );
		static Nan::Persistent<v8::FunctionTemplate> ptpl;

	private:
		static void New(const Nan::FunctionCallbackInfo<v8::Value>& info);

		static void NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void Paint(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info);

#ifdef VTK_NODE_PLUS_VTKINTERACTIVEAREAWRAP_CLASSDEF
		VTK_NODE_PLUS_VTKINTERACTIVEAREAWRAP_CLASSDEF
#endif
};

#endif

redpajama_set_name: RedPajamaGithub


text:
int tstar_ES_function(double* current_ES, int npts_phase, double coeff,double*  tmp_ES)
{

	double delta = 0.1;

	int ts_npts = npts_phase;
	double TSTAR[ts_npts];
	double conv_result[npts_phase];

	//printf("tstar for %lf begin \n", coeff);
	t_star_find_uniq(coeff, TSTAR, ts_npts, delta);
	//printf("tstar for %lf end\n\n", coeff);
	normalize_array(TSTAR,ts_npts);

	//do convolution between tstar and current_ES
	//convolution(current_ES, npts_phase, TSTAR, ts_npts, conv_result);
	convolution2(current_ES, npts_phase, TSTAR,  conv_result);
	 //int convolution2(double* array1, int npts1, double* array2, double* array_out)

	//normalize_array(conv_result,ts_npts+npts_phase);
	normalize_array(conv_result,npts_phase);
	//char conv_file[200];
	//sprintf(conv_file,"conv_file_%lf",coeff);
	//output_array1(conv_file,conv_result, ts_npts+npts_phase-1);
	//output_array1(conv_file,conv_result, npts_phase);
	//sprintf(conv_file,"current_file_%lf",coeff);
	//output_array1(conv_file,current_ES, npts_phase);

	int count;
	for(count = 0; count < npts_phase; count ++)
		tmp_ES[count] = conv_result[count];

	return 0;
}


text:
package Engine;

import static org.lwjgl.glfw.GLFWVulkan.glfwVulkanSupported;

import java.io.File;
import java.io.Serializable;
import java.util.concurrent.atomic.AtomicInteger;

import org.lwjgl.glfw.GLFW;
import org.lwjgl.glfw.GLFWErrorCallback;
import org.lwjgl.glfw.GLFWKeyCallback;
import org.lwjgl.glfw.GLFWVidMode;

import entities.Entity.RENDERCODES;
import helpers.CerealDispenser;
import helpers.KeyboardHandler;
import helpers.Logging;
import helpers.Timer;

public class GLOBALS implements Serializable {

	public enum VSYNC_SETTING {

		OFF(0), ON_DOUBLE_BUFFER(2), ON_SINGLE_BUFFER(1);
		private int value;

		private VSYNC_SETTING(int value) {
			this.value = value;
		}

		public int getValue(){
			return value;
		}
	}

	protected double SCALE= 1;
	//TODO:[BUG]Width and Height by graphics capabilities, crasshing on glfwGetVideoModes
	public boolean DEBUG = true;

	private static final long serialVersionUID = 86753091L;
	protected final int HEIGHT= (int)(480*SCALE);
	protected final boolean VULKAN_SUPPORTED = glfwVulkanSupported();
	protected final int WIDTH= (int)(640*SCALE);
	public transient long PRIMARY_MONITOR = GLFW.glfwGetPrimaryMonitor();
	public transient GLFWVidMode.Buffer availableVideoModes;

	public transient AudioEngine audioEngine;
	protected transient double delta = 0;
	protected transient GLFWErrorCallback errorCallback;
	protected transient RENDERCODES graphicsContext = RENDERCODES.INTERMEDIATE;
	protected transient GLFWKeyCallback keyboardCallback;
	public transient KeyboardHandler keyHandler;
	protected transient Timer timer = new Timer();

	protected AtomicInteger fps = new AtomicInteger(0);
	protected physicsConstants physicsVars;
	protected boolean SAVE_LOGS = false;
	protected boolean useGLIntermediateMode = false;

	protected String TITLE = "2D Engine Test!";

	protected VSYNC_SETTING use_vsync = VSYNC_SETTING.OFF;

	protected int TICK_LIMIT = 60;

	//protected String logString = "";
	// if we really need to capture this as a global its here, sorta.
	// really, just pretend that this isnt here...
	protected long WINDOW_HANDLE;

	public GLOBALS() {
		this(true);
	}

	public GLOBALS(boolean createFromFile) {
		GLOBALSfromFile(true);
	}

	public GLOBALS GLOBALSfromFile(boolean tryToDeserializeFromFile) {
		File oldGlobals = new File("./globals.gbl");
		return (GLOBALS) CerealDispenser.fromFile(oldGlobals);
	}

	public void printVars() {
		System.out.println("DEBUG: "+DEBUG);
		System.out.println("FPS_LIMIT_"+TICK_LIMIT);
		System.out.println("Timer: "+timer.toString());
		System.out.println("SCALE: "+SCALE);
		System.out.println("TITLE: "+TITLE);
		System.out.println("WIDTH: "+WIDTH);
		System.out.println("HEIGHT: "+HEIGHT);
		System.out.println("PRIMARY MONITOR: "+PRIMARY_MONITOR);
		System.out.println("AVAILABLE VIDEO MODES: ");
		//		GLFWVidMode mode;
		//		while ((mode = availableVideoModes.get())!=null) {
		//			System.out.println("\t"+mode.toString());
		//		}
		//System.out.println("ErrorCallBack: "+errorCallback.toString());
		//System.out.println("KeyCallBack: "+keyboardCallback.toString());
		System.out.println("Window Handle: "+WINDOW_HANDLE);
		System.out.println("Vulkan? "+VULKAN_SUPPORTED);
		System.out.println("Intermediate_Mode? "+useGLIntermediateMode);
		System.out.println("Save_Logs? "+SAVE_LOGS);
		System.out.println("Vsync? "+use_vsync);
		System.out.println("Graphics Context: "+graphicsContext);
		System.out.println("FPS: "+fps.get());
		physicsConstants.printVars();
		System.out.println("");
	}

	public void saveGlobals() {
		File oldGlobals = new File("./globals.gbl");
		boolean success = CerealDispenser.toFile(oldGlobals, this);
		if (!success) {
			//just let the user know that file creation was unsuccessful.
			Logging.log("File was unsuccesfully created!", DEBUG);
		}
	}

	/*
	 *Notes on exit codes!
	 * returning an int of -20 means that one of the sub threads that was running failed to stop with the program.
	 *
	 *
	 *
	 */

}


text:
package transactionentry

import (
	"net/http"

	stripe "github.com/stripe/stripe-go/v74"
	"github.com/stripe/stripe-go/v74/form"
)

// Client is used to invoke /treasury/transaction_entries APIs.
type Client struct {
	B   stripe.Backend
	Key string
}

// Get returns the details of a treasury transaction entry.
func Get(id string, params *stripe.TreasuryTransactionEntryParams) (*stripe.TreasuryTransactionEntry, error) {
	return getC().Get(id, params)
}

// Get returns the details of a treasury transaction entry.
func (c Client) Get(id string, params *stripe.TreasuryTransactionEntryParams) (*stripe.TreasuryTransactionEntry, error) {
	path := stripe.FormatURLPath("/v1/treasury/transaction_entries/%s", id)
	transactionentry := &stripe.TreasuryTransactionEntry{}
	err := c.B.Call(http.MethodGet, path, c.Key, params, transactionentry)
	return transactionentry, err
}

// List returns a list of treasury transaction entries.
func List(params *stripe.TreasuryTransactionEntryListParams) *Iter {
	return getC().List(params)
}

// List returns a list of treasury transaction entries.
func (c Client) List(listParams *stripe.TreasuryTransactionEntryListParams) *Iter {
	return &Iter{
		Iter: stripe.GetIter(listParams, func(p *stripe.Params, b *form.Values) ([]interface{}, stripe.ListContainer, error) {
			list := &stripe.TreasuryTransactionEntryList{}
			err := c.B.CallRaw(http.MethodGet, "/v1/treasury/transaction_entries", c.Key, b, p, list)

			ret := make([]interface{}, len(list.Data))
			for i, v := range list.Data {
				ret[i] = v
			}

			return ret, list, err
		}),
	}
}

// Iter is an iterator for treasury transaction entries.
type Iter struct {
	*stripe.Iter
}

// TreasuryTransactionEntry returns the treasury transaction entry which the iterator is currently pointing to.
func (i *Iter) TreasuryTransactionEntry() *stripe.TreasuryTransactionEntry {
	return i.Current().(*stripe.TreasuryTransactionEntry)
}

// TreasuryTransactionEntryList returns the current list object which the iterator is
// currently using. List objects will change as new API calls are made to
// continue pagination.
func (i *Iter) TreasuryTransactionEntryList() *stripe.TreasuryTransactionEntryList {
	return i.List().(*stripe.TreasuryTransactionEntryList)
}

func getC() Client {
	return Client{stripe.GetBackend(stripe.APIBackend), stripe.Key}
}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _taggedTemplateLiteral2 = require('babel-runtime/helpers/taggedTemplateLiteral');

var _taggedTemplateLiteral3 = _interopRequireDefault(_taggedTemplateLiteral2);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _styledComponents = require('styled-components');

var _styledComponents2 = _interopRequireDefault(_styledComponents);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var _jsxFileName = '/Users/wrariza/MEGA/apps/template-react/components/Search.js';

var _templateObject = (0, _taggedTemplateLiteral3.default)(['\n    display: flex;\n    font-weight: bold;\n    font-family: \'arial\'\n    top: 200px;\n    position: relative;\n    @media (max-width: 1024px) {\n        flex-direction: column;\n    }\n'], ['\n    display: flex;\n    font-weight: bold;\n    font-family: \'arial\'\n    top: 200px;\n    position: relative;\n    @media (max-width: 1024px) {\n        flex-direction: column;\n    }\n']),
    _templateObject2 = (0, _taggedTemplateLiteral3.default)(['\n    flex: 1; \n    margin-right: 1rem;\n    padding: 0.5 rem 1rem;\n    font-size: 1rem;\n    ', '\n    @media (max-width: 1024px){\n         margin-right: 0px;\n    }\n'], ['\n    flex: 1; \n    margin-right: 1rem;\n    padding: 0.5 rem 1rem;\n    font-size: 1rem;\n    ', '\n    @media (max-width: 1024px){\n         margin-right: 0px;\n    }\n']),
    _templateObject3 = (0, _taggedTemplateLiteral3.default)(['\n    ', '\n    backgroud-color: #ea83ee;\n    padding: 0.5rem 46px;\n    text-transform: uppercase;\n    font-weight: bold; \n    color: white;\n    box-shadow: 0 0.25rem 0.5rem 0 rgba(0, 0, 0, 0.3);\n     font-size: 1rem;\n    @media (max-width: 1024px){\n         margin-top: 1rem;\n    }\n'], ['\n    ', '\n    backgroud-color: #ea83ee;\n    padding: 0.5rem 46px;\n    text-transform: uppercase;\n    font-weight: bold; \n    color: white;\n    box-shadow: 0 0.25rem 0.5rem 0 rgba(0, 0, 0, 0.3);\n     font-size: 1rem;\n    @media (max-width: 1024px){\n         margin-top: 1rem;\n    }\n']);

var DefaultStyles = '\n    outline: 0;\n    borde: none;\n    border-radius: 4px;\n';

var Form = _styledComponents2.default.form(_templateObject);

var InputSeacher = _styledComponents2.default.input(_templateObject2, DefaultStyles);

var Button = _styledComponents2.default.button(_templateObject3, DefaultStyles);

function Searcher(props) {
    return _react2.default.createElement(Form, { onSubmit: props.onSubmit, __source: {
            fileName: _jsxFileName,
            lineNumber: 49
        }
    }, _react2.default.createElement(InputSeacher, {
        name: 'buscar',
        type: 'text',
        placeholder: 'ingrese sus palabras favoritas',
        __source: {
            fileName: _jsxFileName,
            lineNumber: 50
        }
    }), _react2.default.createElement(Button, {
        __source: {
            fileName: _jsxFileName,
            lineNumber: 55
        }
    }, 'Generar'));
}

exports.default = Searcher;


text:
import syntaxExportExtensions from "babel-plugin-syntax-export-extensions";

export default function ({ types: t }) {
  function build(node, nodes, scope) {
    const first = node.specifiers[0];
    if (!t.isExportNamespaceSpecifier(first) && !t.isExportDefaultSpecifier(first)) return;

    const specifier = node.specifiers.shift();
    const uid = scope.generateUidIdentifier(specifier.exported.name);

    let newSpecifier;
    if (t.isExportNamespaceSpecifier(specifier)) {
      newSpecifier = t.importNamespaceSpecifier(uid);
    } else {
      newSpecifier = t.importDefaultSpecifier(uid);
    }

    nodes.push(t.importDeclaration([newSpecifier], node.source));
    nodes.push(t.exportNamedDeclaration(null, [t.exportSpecifier(uid, specifier.exported)]));

    build(node, nodes, scope);
  }

  return {
    inherits: syntaxExportExtensions,

    visitor: {
      ExportNamedDeclaration(path) {
        const { node, scope } = path;
        const nodes = [];
        build(node, nodes, scope);
        if (!nodes.length) return;

        if (node.specifiers.length >= 1) {
          nodes.push(node);
        }
        path.replaceWithMultiple(nodes);
      },
    },
  };
}


text:
var host = "http://" + $("#hostName").val();
var anouncementGetUrl = host + "/Anouncement";

var getHtmlTemplate = function (title, text) {
    var template = '
' +
              '
' +
                  '
' +
                      '' + title + '' +
                      '
' +
                          text +
                      '
' +
                  '
' +
              '
' +
          '
';
    return template;
}

var getAnouncements = function () {
    var anouncements = $("#anouncements");
    anouncements.empty();
    $.get(anouncementGetUrl,
    function (data) {
        for (var i = 0; i < data.length; i++) {
            anouncements.append(getHtmlTemplate(data[i].title, data[i].text));
        }
    });
}

getAnouncements();
$("#colapseHeader").click(function() {
    getAnouncements();
});


text:
package org.apache.isis.core.metamodel.facets;

import org.apache.isis.core.metamodel.facetapi.Facet;
import org.apache.isis.core.metamodel.facetapi.FacetAbstract;
import org.apache.isis.core.metamodel.facetapi.FacetHolder;

public abstract class SingleStringValueFacetAbstract extends FacetAbstract implements SingleStringValueFacet {
    private final String value;

    public SingleStringValueFacetAbstract(final Class<? extends Facet> facetType, final FacetHolder holder, final String value) {
        this(facetType, holder, value, Derivation.NOT_DERIVED);
    }

    public SingleStringValueFacetAbstract(final Class<? extends Facet> type, final FacetHolder holder, final String value, final Derivation derivation) {
        super(type, holder, derivation);
        this.value = value;
    }

    @Override
    public String value() {
        return value;
    }

    @Override
    protected String toStringValues() {
        if (value == null) {
            return "null";
        } else {
            return "\"" + value + "\"";
        }
    }

}


text:
package runtime

import (
	"fmt"
	"runtime"
	"sync"
	"time"

	"github.com/golang/glog"
)

var (
	// ReallyCrash controls the behavior of HandleCrash and now defaults
	// true. It's still exposed so components can optionally set to false
	// to restore prior behavior.
	ReallyCrash = true
)

// PanicHandlers is a list of functions which will be invoked when a panic happens.
var PanicHandlers = []func(interface{}){logPanic}

// HandleCrash simply catches a crash and logs an error. Meant to be called via
// defer.  Additional context-specific handlers can be provided, and will be
// called in case of panic.  HandleCrash actually crashes, after calling the
// handlers and logging the panic message.
//
// TODO: remove this function. We are switching to a world where it's safe for
// apiserver to panic, since it will be restarted by kubelet. At the beginning
// of the Kubernetes project, nothing was going to restart apiserver and so
// catching panics was important. But it's actually much simpler for monitoring
// software if we just exit when an unexpected panic happens.
func HandleCrash(additionalHandlers ...func(interface{})) {
	if r := recover(); r != nil {
		for _, fn := range PanicHandlers {
			fn(r)
		}
		for _, fn := range additionalHandlers {
			fn(r)
		}
		if ReallyCrash {
			// Actually proceed to panic.
			panic(r)
		}
	}
}

// logPanic logs the caller tree when a panic occurs.
func logPanic(r interface{}) {
	callers := getCallers(r)
	if _, ok := r.(string); ok {
		glog.Errorf("Observed a panic: %s\n%v", r, callers)
	} else {
		glog.Errorf("Observed a panic: %#v (%v)\n%v", r, r, callers)
	}
}

func getCallers(r interface{}) string {
	callers := ""
	for i := 0; true; i++ {
		_, file, line, ok := runtime.Caller(i)
		if !ok {
			break
		}
		callers = callers + fmt.Sprintf("%v:%v\n", file, line)
	}

	return callers
}

// ErrorHandlers is a list of functions which will be invoked when an unreturnable
// error occurs.
// TODO(lavalamp): for testability, this and the below HandleError function
// should be packaged up into a testable and reusable object.
var ErrorHandlers = []func(error){
	logError,
	(&rudimentaryErrorBackoff{
		lastErrorTime: time.Now(),
		// 1ms was the number folks were able to stomach as a global rate limit.
		// If you need to log errors more than 1000 times a second you
		// should probably consider fixing your code instead. :)
		minPeriod: time.Millisecond,
	}).OnError,
}

// HandlerError is a method to invoke when a non-user facing piece of code cannot
// return an error and needs to indicate it has been ignored. Invoking this method
// is preferable to logging the error - the default behavior is to log but the
// errors may be sent to a remote server for analysis.
func HandleError(err error) {
	// this is sometimes called with a nil error.  We probably shouldn't fail and should do nothing instead
	if err == nil {
		return
	}

	for _, fn := range ErrorHandlers {
		fn(err)
	}
}

// logError prints an error with the call stack of the location it was reported
func logError(err error) {
	glog.ErrorDepth(2, err)
}

type rudimentaryErrorBackoff struct {
	minPeriod time.Duration // immutable
	// TODO(lavalamp): use the clock for testability. Need to move that
	// package for that to be accessible here.
	lastErrorTimeLock sync.Mutex
	lastErrorTime     time.Time
}

// OnError will block if it is called more often than the embedded period time.
// This will prevent overly tight hot error loops.
func (r *rudimentaryErrorBackoff) OnError(error) {
	r.lastErrorTimeLock.Lock()
	defer r.lastErrorTimeLock.Unlock()
	d := time.Since(r.lastErrorTime)
	if d < r.minPeriod {
		// If the time moves backwards for any reason, do nothing
		time.Sleep(r.minPeriod - d)
	}
	r.lastErrorTime = time.Now()
}

// GetCaller returns the caller of the function that calls it.
func GetCaller() string {
	var pc [1]uintptr
	runtime.Callers(3, pc[:])
	f := runtime.FuncForPC(pc[0])
	if f == nil {
		return fmt.Sprintf("Unable to find caller")
	}
	return f.Name()
}

// RecoverFromPanic replaces the specified error with an error containing the
// original error, and  the call tree when a panic occurs. This enables error
// handlers to handle errors and panics the same way.
func RecoverFromPanic(err *error) {
	if r := recover(); r != nil {
		callers := getCallers(r)

		*err = fmt.Errorf(
			"recovered from panic %q. (err=%v) Call stack:\n%v",
			r,
			*err,
			callers)
	}
}

// Must panics on non-nil errors.  Useful to handling programmer level errors.
func Must(err error) {
	if err != nil {
		panic(err)
	}
}


text:
#include <instantsearch/Analyzer.h>
#include <instantsearch/Indexer.h>
#include <instantsearch/IndexSearcher.h>
#include <instantsearch/Query.h>
#include <instantsearch/Term.h>
#include <instantsearch/Schema.h>
#include <instantsearch/Record.h>
#include <instantsearch/QueryResults.h>
#include "IntegrationTestHelper.h"

#include <cassert>
#include <iostream>
#include <cstdlib>
#include <sstream>
#include <fstream>
#include <string>
#include <vector>
#include <cstring>

using namespace std;
namespace srch2is = srch2::instantsearch;
using namespace srch2is;

void buildIndexWithDefaultStemmerAndNormalizer(string INDEX_DIR)
{

	// Create a schema
	srch2is::Schema *schema = srch2is::Schema::create(srch2is::DefaultIndex);
	schema->setPrimaryKey("record_id"); // integer, by default not searchable
	//schema->setSearchableAttribute("article_id"); // convert id to searchable text
	schema->setSearchableAttribute("article_authors", 2); // searchable text
	schema->setSearchableAttribute("article_title", 7); // searchable text

	// Create stemmer
        StemmerContainer *stem = StemmerContainer::getInstance("");

	// Create an analyzer
	srch2is::Analyzer *analyzer = srch2is::new Analyzer(stem, NULL, NULL, NULL, " ");

	// Create an index writer
	unsigned mergeEveryNSeconds = 3;
	unsigned mergeEveryMWrites = 5;
	IndexMetaData *indexMetaData1 = new IndexMetaData( new Cache(), mergeEveryNSeconds, mergeEveryMWrites, "", INDEX_DIR, "");
	Indexer *index = Indexer::create(indexMetaData1, analyzer, schema);

	// Step 2: Create records and add to the index

	// Create a record of 3 attributes
	srch2is::Record *record = new srch2is::Record(schema);
//	record->setPrimaryKey(100); // give a value for the primary key
//	record->setSearchableAttributeValue("record_location", "star-bucks");
//	record->setSearchableAttributeValue("record_description", "Star-bucks is one of the famous coffee stores in United States");
//	record->setRecordBoost(20); // set its boost value
//	indexer->addRecord(record); // add the record to the index

//	record->clear();
	// Create a record
	record->setPrimaryKey(100);
	record->setSearchableAttributeValue(0, "Wal-mart");
	record->setSearchableAttributeValue(1, "Wal-mart is the biggest star-bucks convenient store in United states provable");
	index->addRecord(record, 0); // add the record to the index

	// Create another record
	record->clear();
	record->setPrimaryKey(200);
	record->setSearchableAttributeValue(0, "Cheese-cake factory");
	record->setSearchableAttributeValue(1, "cheese-cake factory serves awesome cheese-cakes loved by children. It tastes great with starbucks coffee ");
	index->addRecord(record, 0); // add the record to the index

	// Create another record
	record->clear();
	record->setPrimaryKey(300);
	record->setSearchableAttributeValue(0, "starbucks");
	record->setSearchableAttributeValue(1, "Starbucks is one of the famous coffee stores in United States");
	index->addRecord(record, 0); // add the record to the index

	record->clear();
	record->setPrimaryKey(500);
	record->setSearchableAttributeValue(0, "star-bucks");
	record->setSearchableAttributeValue(1, "Star-bucks is one of the famous coffee stores in United States");
	index->addRecord(record, 0);

	// Create another record
//	record->clear();
//	record->setPrimaryKey(500);
//	record->setSearchableAttributeValue(0, "pink floyd");
//	record->setSearchableAttributeValue(1, "cambric cambyses adversary pencils");
//	indexer->addRecord(record); // add the record to the index

	// Step 3: Commit and build the index
	index->commit();
	index->save(); // after commit(), no more records can be added

	// free references
	delete schema;
	delete analyzer;
	delete index;
}

bool test(string INDEX_DIR, vector<unsigned> &recordId, int attributeId, unsigned noofhits, string keywords[], bool isStemmed,srch2is::TermType type = srch2is::PREFIX)
{
	// Create an index reader
	unsigned mergeEveryNSeconds = 3;
	unsigned mergeEveryMWrites = 5;
	IndexMetaData *indexMetaData1 = new IndexMetaData( new Cache(), mergeEveryNSeconds, mergeEveryMWrites, "", INDEX_DIR, "");
	Indexer *indexer = Indexer::load(indexMetaData1);

	// Create an index searcher
	srch2is::IndexSearcher *indexSearcher = srch2is::IndexSearcher::create(indexer);

	// STEP 2: Create a Query object and a QueryResults object
	srch2is::Query *query = new srch2is::Query(srch2is::TopKQuery);

	//std::cout << "SearchableAttributeId:" << indexReader->getSchema()->getSearchableAttributeId("article_title") << std::endl;
	// For each keyword above, add a corresponding fuzzy term to the query
	for (unsigned i = 0; i < 2; ++i)
	{
		//srch2is::TermType type = srch2is::PREFIX; // prefix matching
		//srch2is::TermType type = srch2is::COMPLETE; // use it for complete matching
		unsigned termBoost = 1;
		unsigned similarityBoost = 100;
		srch2is::Term *term = srch2is::ExactTerm::create(keywords[i],
				type,
				termBoost,
				similarityBoost);
		//term->addAttributeToFilterTermHits(attributeId);
		query->add(term);
	}

	srch2is::QueryResults *queryResults = new srch2is::QueryResults(new QueryResultFactory(),indexSearcher, query);

	// Step 3: Search the index and display results

	// Search for records
	unsigned offset = 0;
	unsigned resultsToRetrieve = 4;

	// Do the search
	indexSearcher->search(query, queryResults, offset, resultsToRetrieve);

	// Iterate through the results

	bool returnvalue = checkOutput(queryResults, noofhits, isStemmed);

	printResults(queryResults, offset);
	cout<<boolalpha;
	cout << "return information: "<<returnvalue<<endl;

	// Free the objects
	delete query;
	delete indexSearcher;
	delete indexer;

	return (returnvalue); //& stemValidation);
}

/**
 * The main function
 */
int main(int argc, char **argv)
{
	// STEP 1: Create IndexReader and IndexSearcher
	// Define a folder for the index files
	string INDEX_DIR = getenv("index_dir");
	//string INDEX_DIR = ".";
	cout << INDEX_DIR <<endl;

	//Testing with Normalizer and Stemmer

	buildIndexWithDefaultStemmerAndNormalizer(INDEX_DIR);

	vector<unsigned> recordId;

	recordId.clear();
	string keywords [] = {
			"starbuck","coffee"  // starbuck is a stemmed word in the records
	};
	recordId.push_back(300);
	recordId.push_back(200);
	recordId.clear();

	//First 3 ASSERTS test for correct #records and stemmed information

	//correct record info and stem info provided
	ASSERT(test(INDEX_DIR, recordId, 1, 3, keywords, true,srch2is::PREFIX )==true);

	//correct record info and wrong stem info provided
	ASSERT(test(INDEX_DIR, recordId, 1, 3 , keywords,false,srch2is::PREFIX)==false);

	//wrong record info and correct stem info provided
	ASSERT(test(INDEX_DIR, recordId, 1, 0, keywords,true,srch2is::PREFIX)==false);

	//changing the query "starbuck" to "starbucks"
	keywords[0] = "starbucks";

	recordId.push_back(500);

    //correct record info and stem info provided
   	ASSERT(test(INDEX_DIR, recordId, 1, 3, keywords, true,srch2is::PREFIX )==true);

   	//correct record info and wrong stem info provided
    ASSERT(test(INDEX_DIR, recordId, 1, 3 , keywords,false,srch2is::PREFIX)==false);

   	//wrong record info and correct stem info provided
    ASSERT(test(INDEX_DIR, recordId, 1, 0, keywords,true,srch2is::PREFIX)==false);

    keywords[0] = "walmart"; // This is a stemmed word in the records
    keywords[1] = "store";

    //correct record and stem info
    ASSERT(test(INDEX_DIR, recordId, 1, 1, keywords, true,srch2is::PREFIX )==true);

    //correct record and wrong stem info
    ASSERT(test(INDEX_DIR, recordId, 1, 1, keywords, false,srch2is::PREFIX )==false);

    std::cout << "Stemmer API tests passed." << std::endl;

	return 0;
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace CJia.Health.App
{
    public partial class LoginFrom : CJia.Health.Tools.WinFrom, CJia.Health.Views.ILoginView
    {
        public LoginFrom()
        {
            InitializeComponent();
            Init();
            txtUserName.Focus();
            cJiaLabel6.Text = "Version V" + CJia.Health.Tools.ConfigHelper.GetAppStrings("Version");
        }
        //protected override object CreatePresenter()
        //{
        //    return new Presenters.LoginViewPresenter(this);
        //}

        protected override object CreatePresenter()
        {
            return new Presenters.LoginViewPresenter(this);
        }
        /// <summary>
        /// 登录参数设置
        /// </summary>
        Views.LoginEventArgs loginEventArgs = new Views.LoginEventArgs();

        #region ILoginView成员
        //登录事件
        public event EventHandler<Views.LoginEventArgs> OnLogin;
        //用户名输入框获得焦点
        public void TxtUserNOFocus()
        {
            txtUserName.Focus();
            txtUserName.SelectAll();
        }
        #endregion

        #region 界面事件
        private void closeBtn_Click(object sender, EventArgs e)
        {
            this.ParentForm.Close();
        }

        private void pnlLogin_Click(object sender, EventArgs e)
        {
            if (!isRightUser()) return;
            loginEventArgs.UserNo = txtUserName.Text;
            loginEventArgs.Password = txtPassword.Text;
            if (ckUser.Checked)
                RememberUserNO();
            if (OnLogin != null) OnLogin(sender, loginEventArgs);
        }

        private void txtPassword_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                pnlLogin_Click(sender, e);
            }
        }

        #endregion

        #region 内部调用方法
        /// <summary>
        /// 界面校验
        /// </summary>
        /// <returns></returns>
        bool isRightUser()
        {
            if (txtUserName.Text.Length == 0)
            {
                MessageBox.Show("用户名不能为空");
                txtUserName.Focus();
                return false;
            }
            if (txtPassword.Text.Length == 0)
            {
                MessageBox.Show("密码不能为空");
                txtPassword.Focus();
                return false;
            }
            return true;
        }
        /// <summary>
        /// 获得上次记住的用户名
        /// </summary>
        void Init()
        {
            string userNO = CJia.Health.Tools.ConfigHelper.GetAppStrings("UserNO");
            txtUserName.Text = userNO;
        }
        /// <summary>
        /// 记住用户名
        /// </summary>
        void RememberUserNO()
        {
            string userNO = txtUserName.Text;
            CJia.Health.Tools.ConfigHelper.UpdateAppStrings("UserNO", userNO);
        }
        #endregion

        private void txtUserName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                txtPassword.Focus();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}


text:
Developer-Bus
=============

Developer Bus


text:
package com.onebus.view;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.onebus.IPAdress;
import com.onebus.OneBusApplication;
import com.onebus.R;
import com.onebus.util.MD5;
import com.onebus.util.NetWorkUtil;

public class RegisterActivity extends Activity {

	private String URLGETCODE = "/onebus/android/registerGetCode";
	private String URLREGISTER = "/onebus/android/register";
	private IPAdress IPadress;

	private final static int SENDSUCCESS = 0x114;
	private final static int USEREXIST = 0x115;
	private final static int REGISTERSUCCESS = 0x116;
	private final static int REGISTERFAIL = 0x117;
	private final static int REGISTERINTER = 0x118;

	private Handler registerHandler;

	private ImageButton backButton;

	private EditText userName;
	private EditText passWord;
	private EditText passWord2;
	private EditText userPhone;

	private Button getCode;
	private EditText inputCode;

	private Button register;
	private TextView userDeal;

	private TimeCount time;

	private String securityCode;
	private String securityPhone;
	private ProgressDialog mProgressDialog;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register);

		time = new TimeCount(30000, 1000);

		initView();

		// 点击回退按钮
		backButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				onBackPressed();
			}
		});

		// 点击获取验证码按钮
		getCode.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				try {
					if (isSuitablyGetCodeMessage()) {

						if (!NetWorkUtil
								.isNetWorkConnected(getApplicationContext())) {

							Toast.makeText(getApplicationContext(),
									"网络连接失败,请检查网络是否可用!", Toast.LENGTH_SHORT)
									.show();

							return;

						}

						securityPhone = userPhone.getText().toString();

						getCodeFromServer();

						time.start();

					}
				} catch (Exception e) {

					e.printStackTrace();
				}

			}
		});

		register.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (isSuitablyRegisterMessage()) {

					if (!NetWorkUtil
							.isNetWorkConnected(getApplicationContext())) {

						Toast.makeText(getApplicationContext(),
								"网络连接失败,请检查网络是否可用!", Toast.LENGTH_SHORT).show();

						return;

					}

					if (inputCode.getText().toString().equals(securityCode)) {

						if (inputCode.getText().toString().equals(securityCode)
								&& userPhone.getText().toString()
										.equals(securityPhone)) {

							RegisterUser();

							mProgressDialog = new ProgressDialog(
									RegisterActivity.this);
							mProgressDialog
									.setIcon(R.drawable.common_topbar_route_foot_pressed);
							mProgressDialog.setMessage("请稍等....");
							mProgressDialog.show();

						} else {

							Toast.makeText(getApplicationContext(),
									"手机号与验证码不匹配!", Toast.LENGTH_SHORT).show();

						}
					} else {

						Toast.makeText(getApplicationContext(), "验证码错误!",
								Toast.LENGTH_SHORT).show();

					}

				}

			}
		});

		userDeal.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Toast.makeText(getApplicationContext(), "用户服务协议!",
						Toast.LENGTH_SHORT).show();

			}
		});

		registerHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case SENDSUCCESS: {

					// mProgressDialog.dismiss();

					try {
						JSONArray jsonArray = new JSONArray(msg.obj.toString());
						JSONObject jsonObject = (JSONObject) jsonArray.get(0);

						securityCode = jsonObject.optString("securityCode");

						Toast.makeText(getApplicationContext(),
								"验证码已经发送,请注意查收!", Toast.LENGTH_SHORT).show();

					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					break;
				}
				case USEREXIST: {

					// mProgressDialog.dismiss();

					Toast.makeText(getApplicationContext(), "该手机号已经注册,可直接登录!",
							Toast.LENGTH_SHORT).show();

					break;

				}
				case REGISTERSUCCESS: {

					mProgressDialog.dismiss();

					Toast.makeText(getApplicationContext(), "用户注册成功,请进行登录!",
							Toast.LENGTH_SHORT).show();

					finish();

					break;

				}
				case REGISTERFAIL: {

					mProgressDialog.dismiss();

					Toast.makeText(getApplicationContext(), "用户注册失败,请稍后重试!",
							Toast.LENGTH_SHORT).show();

					break;

				}
				case REGISTERINTER: {

					mProgressDialog.dismiss();

					Toast.makeText(getApplicationContext(), "后台服务器故障,请之后重试!",
							Toast.LENGTH_SHORT).show();
					break;
				}
				default:
					super.handleMessage(msg);
				}
			}
		};

	}

	private void initView() {

		IPadress = new IPAdress();
		URLGETCODE = "http://" + IPadress.getIP() + ":" + IPadress.getPORT()
				+ URLGETCODE;

		URLREGISTER = "http://" + IPadress.getIP() + ":" + IPadress.getPORT()
				+ URLREGISTER;

		backButton = (ImageButton) findViewById(R.id.register_btn_back);
		userName = (EditText) findViewById(R.id.register_userName);
		passWord = (EditText) findViewById(R.id.register_userPassword1);
		passWord2 = (EditText) findViewById(R.id.register_userPassword2);
		userPhone = (EditText) findViewById(R.id.register_userPhone);
		getCode = (Button) findViewById(R.id.getCode_register);
		inputCode = (EditText) findViewById(R.id.register_yanzheng);
		register = (Button) findViewById(R.id.register_button);
		userDeal = (TextView) findViewById(R.id.registerTips);

	}

	/**
	 * 验证点击注册按钮前信息是否完整
	 *
	 * @return
	 */
	private boolean isSuitablyRegisterMessage() {

		String userNameStr = userName.getText().toString();
		String passWordStr = passWord.getText().toString();
		String passWord2Str = passWord2.getText().toString();
		String userPhoneStr = userPhone.getText().toString();
		String userCode = inputCode.getText().toString();

		if (userNameStr.equals("") || passWordStr.equals("")
				|| passWord2Str.equals("") || userPhoneStr.equals("")) {

			Toast.makeText(getApplicationContext(), "请填写完整信息!",
					Toast.LENGTH_SHORT).show();

			return false;

		}

		if (passWordStr.length() < 6 || passWordStr.length() > 16) {

			Toast.makeText(getApplicationContext(), "密码格式错误!",
					Toast.LENGTH_SHORT).show();

			return false;

		}

		if (!passWordStr.equals(passWord2Str)) {

			Toast.makeText(getApplicationContext(), "两次密码输入不一致!",
					Toast.LENGTH_SHORT).show();

			return false;

		}

		if (!isMobileNO(userPhoneStr)) {

			Toast.makeText(getApplicationContext(), "手机号格式错误!",
					Toast.LENGTH_SHORT).show();

			return false;

		}

		if (userCode.equals("")) {

			Toast.makeText(getApplicationContext(), "请输入验证码!",
					Toast.LENGTH_SHORT).show();

			return false;

		}

		return true;

	}

	/**
	 * 验证点击获取验证码按钮前信息是否完整
	 *
	 * @return
	 */
	private boolean isSuitablyGetCodeMessage() {

		String userNameStr = userName.getText().toString();
		String passWordStr = passWord.getText().toString();
		String passWord2Str = passWord2.getText().toString();
		String userPhoneStr = userPhone.getText().toString();

		if (userNameStr.equals("") || passWordStr.equals("")
				|| passWord2Str.equals("") || userPhoneStr.equals("")) {

			Toast.makeText(getApplicationContext(), "请填写完整信息!",
					Toast.LENGTH_SHORT).show();

			return false;

		}

		if (passWordStr.length() < 6 || passWordStr.length() > 16) {

			Toast.makeText(getApplicationContext(), "密码格式错误!",
					Toast.LENGTH_SHORT).show();

			return false;

		}

		if (!passWordStr.equals(passWord2Str)) {

			Toast.makeText(getApplicationContext(), "两次密码输入不一致!",
					Toast.LENGTH_SHORT).show();

			return false;

		}

		if (!isMobileNO(userPhoneStr)) {

			Toast.makeText(getApplicationContext(), "手机号格式错误!",
					Toast.LENGTH_SHORT).show();

			return false;

		}

		return true;

	}

	/**
	 * 验证手机号码是否合法
	 *
	 * @param mobiles
	 * @return
	 */
	public static boolean isMobileNO(String mobiles) {
		Pattern p = Pattern
				.compile("^((13[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}

	class TimeCount extends CountDownTimer {

		public TimeCount(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);
		}

		@Override
		public void onTick(long millisUntilFinished) {
			getCode.setBackgroundColor(Color.parseColor("#A2B5CD"));
			getCode.setClickable(false);
			getCode.setText(millisUntilFinished / 1000 + "秒后可重新获取");
		}

		@Override
		public void onFinish() {
			getCode.setText("获取验证码");
			getCode.setClickable(true);
			getCode.setBackgroundResource(R.drawable.shape_modify_btn);
		}
	}

	/**
	 * 向服务器请求验证码
	 */
	private void getCodeFromServer() {

		new Thread() {

			public void run() {

				try {
					String phoneStr = userPhone.getText().toString();

					JSONArray jsonArray = new JSONArray();
					JSONObject jsonObject = new JSONObject();

					jsonObject.put("phone", phoneStr);
					jsonObject.put("type", 1);

					jsonArray.put(jsonObject);

					HttpClient client = new DefaultHttpClient();

					HttpPost httpPost = new HttpPost(URLGETCODE);

					// 设置参数,仿html表单提交
					List<NameValuePair> paramList = new ArrayList<NameValuePair>();
					BasicNameValuePair param = new BasicNameValuePair(
							"registerGetCode", jsonArray + "");
					paramList.add(param);

					httpPost.setEntity(new UrlEncodedFormEntity(paramList,
							"UTF_8"));

					HttpResponse httpResponse = client.execute(httpPost);

					if (httpResponse.getStatusLine().getStatusCode() == 200) {

						String result = EntityUtils.toString(
								httpResponse.getEntity(), HTTP.UTF_8);

						JSONArray jsonArray2 = new JSONArray(result);
						JSONObject jsonObject2 = (JSONObject) jsonArray2.get(0);

						if (jsonObject2.optString("status").equals("success")) {

							Message msg = new Message();
							msg.what = SENDSUCCESS;
							msg.obj = result;
							registerHandler.sendMessage(msg);

						} else {

							Message msg = new Message();
							msg.what = USEREXIST;
							registerHandler.sendMessage(msg);

						}
					}

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

		}.start();

	}

	/**
	 * 向服务器发送注册请求
	 */
	private void RegisterUser() {

		new Thread() {

			public void run() {

				try {
					String userNameStr = userName.getText().toString();
					String passWordStr = passWord.getText().toString();
					String userPhoneStr = userPhone.getText().toString();

					JSONArray jsonArray = new JSONArray();
					JSONObject jsonObject = new JSONObject();

					jsonObject.put("username", userNameStr);
					jsonObject.put("password", MD5.getMD5(passWordStr));
					jsonObject.put("phone", userPhoneStr);
					jsonObject.put("city", OneBusApplication.CURRENT_CITY);

					jsonArray.put(jsonObject);

					HttpClient client = new DefaultHttpClient();

					HttpPost httpPost = new HttpPost(URLREGISTER);

					// 设置参数,仿html表单提交
					List<NameValuePair> paramList = new ArrayList<NameValuePair>();
					BasicNameValuePair param = new BasicNameValuePair(
							"register", jsonArray + "");
					paramList.add(param);

					httpPost.setEntity(new UrlEncodedFormEntity(paramList,
							"UTF_8"));

					HttpResponse httpResponse = client.execute(httpPost);

					if (httpResponse.getStatusLine().getStatusCode() == 200) {

						String result = EntityUtils.toString(
								httpResponse.getEntity(), HTTP.UTF_8);

						JSONArray jsonArray2 = new JSONArray(result);
						JSONObject jsonObject2 = (JSONObject) jsonArray2.get(0);

						if (jsonObject2.getString("status").equals(
								"registerSuccess")) {

							Message msg = new Message();
							msg.what = REGISTERSUCCESS;
							registerHandler.sendMessage(msg);

						} else if (jsonObject2.getString("status").equals(
								"wrongPassword")) {

							Message msg = new Message();
							msg.what = REGISTERFAIL;
							registerHandler.sendMessage(msg);

						}

					} else {

						Message msg = new Message();
						msg.what = REGISTERINTER;
						registerHandler.sendMessage(msg);

					}

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ParseException e) {

					Message msg = new Message();
					msg.what = REGISTERINTER;
					registerHandler.sendMessage(msg);

					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (NoSuchAlgorithmException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

		}.start();

	}
}


text:
title: Ember 2.18 and 3.0 Beta Released
author: Ricardo Mendes, Matthew Beale, Brendan McLoughlin
responsive: true
tags: Releases, Version 2.x, Version 3.x, 2.18, 3.0, 2018
---

Today the Ember project is releasing version 2.18.0 of Ember.js, Ember Data,
and Ember CLI.

**After 2.5 years and 18 minor releases, Ember 2.18 marks the end of the project's 2.x series**.
To ensure a smooth upgrade path going into the 3.x series, 2.18 has been
declared an LTS candidate. In six weeks the latest 2.18 build will succeed
Ember 2.16.2 as the latest LTS release. As an LTS, it will
receive bug fixes until Ember 3.5 is released.

**Today we also kick off the 3.0 beta cycle for all sub-projects.** Ember 3.0
introduces no new features. Instead, it removes support for deprecated public APIs,
all of which have been deprecated since at least Ember 2.14 (released July 2017).
Extended support for removed Ember.js APIs will be provided via an
optional addon through Ember 3.4.

Ember 3.0 removes support for Microsoft Internet Explorer 9,
IE 10, and PhantomJS. This includes support for these platforms by Ember.js,
Ember Data, and Ember CLI. For more details about this decision see
[RFC 252](https://github.com/emberjs/rfcs/blob/master/text/0252-browser-support-changes.md)
and the discussion on [RFC PR #252](https://github.com/emberjs/rfcs/pull/252).

We need the help of the Ember community (especially addon authors) to test
the 3.0 beta builds and transition path for 2.x codebases. If you encounter any
unexpected changes while testing Ember 3.0 beta, especially in features not
previously marked as deprecated by 2.14, please open an issue on the appropriate repo.

You can read more about our detailed transition plans through Ember 3.5
in
[The Road to Ember 3.0](https://www.emberjs.com/blog/2017/10/03/the-road-to-ember-3-0.html)
and below.

You can read more about our general release process here:

* [Release Dashboard](http://emberjs.com/builds/)
* [The Ember Release Cycle](http://emberjs.com/blog/2013/09/06/new-ember-release-process.html)
* [The Ember Project](http://emberjs.com/blog/2015/06/16/ember-project-at-2-0.html)
* [Ember LTS Releases](http://emberjs.com/blog/2016/02/25/announcing-embers-first-lts.html)

---

## Ember.js

Ember.js is the core of the Ember framework. It provides routing,
rendering, and dependency injection features.

### Changes in Ember.js 2.18

Ember.js 2.18 is an incremental and backwards compatible release which
includes minor bug fixes. No new features or public API deprecations are
introduced.

2.18 is light on changes because we want the final release of the 2.x cycle to
be as stable and battle-tested as possible. 2.18 is an LTS candidate, which means
that after six weeks it will be promoted to an LTS release. As an LTS release it
will receive bug fixes until Ember 3.5 is released and security patches until
Ember 3.9 is released.

2.18 is the final release of Ember.js to support IE9, IE10, and PhantomJS. It is
also the final release published for Bower.

"Intimate API" refers to API surface that maintainers never intended to become
public, but which still has some small use in the wild. 2.18.0 adds an intimate
API deprecation for passing `targetObject` to a component invocation. Support
for this API will be removed in Ember 3.5. See
[PR #14590](https://github.com/emberjs/ember.js/pull/14590) for more details.

For more details on changes in Ember.js 2.18, please review the
[Ember.js 2.18.0 release page](https://github.com/emberjs/ember.js/releases/tag/v2.18.0).

### Upcoming Changes in Ember.js 3.0

Ember.js 3.0 is the first release in the 3.x series. It introduces no new
public API or deprecations. Instead, it is comprised of bug fixes and the removal of
previously deprecated public API from the 2.x cycle. This release drops support
for IE9, IE10, and PhantomJS.

#### Removed APIs in Ember.js 3.0

The public APIs removed in 3.0-beta.1 do not yet represent the complete list
of removals planned for 3.0 stable.
For an exhaustive list of planned 3.0 removals and migration guidance see the
[Ember.js 2.x deprecation guide](https://www.emberjs.com/deprecations/v2.x/)
(any entry "until: 3.0") and the quest issue
[emberjs/ember.js#15876](https://github.com/emberjs/ember.js/issues/15876).

The list of public API removals included in 3.0-beta.1 are:

* The `{{render}}` helper has been removed. Any remaining usage should be
  [migrated to components](https://emberjs.com/deprecations/v2.x/#toc_code-render-code-helper).
* `didInitAttrs` is removed and can be [replaced with `init`](https://www.emberjs.com/deprecations/v2.x/#toc_ember-component-didinitattrs)
* Declaring an observer with dependent keys after the callback is removed. Dependent keys should be passed before the callback as described in the [API docs](https://emberjs.com/api/ember/2.17/classes/@ember%2Fobject/methods/observer?anchor=observer).
* `Enumerable#contains` and `Array#contains` methods are removed. Instead usage should be [replaced with `includes`](https://www.emberjs.com/deprecations/v2.x/#toc_enumerable-contains).
* `{{link-to}}` unwrapped the `model` property from passed controllers. This
  behavior has been removed.
* Specifying `defaultLayout` on a component rather than [`layout`](https://www.emberjs.com/deprecations/v2.x/#toc_ember-component-defaultlayout) has been removed.
* `Ember.Handlebars.SafeString` has been removed. Instead, use [`Ember.String.htmlSafe`](https://www.emberjs.com/deprecations/v2.x/#toc_use-ember-string-htmlsafe-over-ember-handlebars-safestring) or the `import { htmlSafe } from '@ember/string'`.
* `Ember.K` has been removed. Usage should be replaced with [inline functions](https://www.emberjs.com/deprecations/v2.x/#toc_deprecations-added-in-2-12).
* Support for legacy initializers with two arguments (container, application)
  has been removed in favor of
  [a single argument of `application`](https://emberjs.com/deprecations/v2.x/#toc_initializer-arity).

Further planned public API removals for 3.0 include:

* Ember's legacy binding system, including `Ember.Binding` and the `fooBinding`
  micro-syntax. See the [migration guide](https://emberjs.com/deprecations/v2.x/#toc_ember-binding) for details.
* Ember's `Map`, `MapWithDefault`, and `OrderedSet` classes. These should be
  replaced with native features or with implementations from other libraries.

Please see [emberjs/ember.js#15876](https://github.com/emberjs/ember.js/issues/15876)
for more details (including about previously deprecated private or intimate
API removals) and updates during the beta cycle.

#### Transitioning to 3.x with ember-2-legacy

Public APIs removed in Ember.js 3.0 have each been ported to the
[ember-2-legacy](https://github.com/emberjs/ember-2-legacy) addon. This addon
makes it possible for applications to adopt 3.0 even if they still
require features unsupported by the core of the framework.

This addon will not include support for removed intimate or private APIs, nor
will it enable support for IE9, IE10, PhantomJS, or Bower. In [The Road to Ember
3.0](https://www.emberjs.com/blog/2017/10/03/the-road-to-ember-3-0.html#toc_transitioning-to-3-0)
we committed to support this addon through Ember.js 3.4, the first LTS
candidate of the 3.x cycle.

#### Other Ember.js 3.0 Changes

Ember.js 3.0 removes support for IE9,
IE 10, and PhantomJS. For more details about this decision see
[RFC 252](https://github.com/emberjs/rfcs/blob/master/text/0252-browser-support-changes.md)
and the discussion on [RFC PR #252](https://github.com/emberjs/rfcs/pull/252).

Finally, Ember.js 3.0 will not be published for Bower.

For more details on the upcoming changes in Ember.js 3.0, please review the
[Ember.js 3.0.0-beta.1 release page](https://github.com/emberjs/ember.js/releases/tag/v3.0.0-beta.1).

---

## Ember Data

Ember Data is the official data persistence library for Ember.js applications.

### Changes in Ember Data 2.18

Ember Data 2.18 contains no new features. The changes introduced in
Ember Data 2.18 mostly focus on bug fixes and improved documentation.

One public API deprecation targeting **Ember Data 4.0** is introduced in Ember Data 2.18:

* Support for "production-like" values of `EMBER_ENV` [will be removed](https://github.com/emberjs/data/pull/5239).
For example, custom production names like `production-qa` should be replaced with `production`

For more details on changes in Ember Data 2.18, please review the
[Ember Data 2.18.0 release page](https://github.com/emberjs/data/releases/tag/v2.18.0).

### Upcoming changes in Ember Data 3.0

Ember Data 3.0 contains major improvements in the testing blueprints
that are shipped with Ember Data and used by Ember CLI when you use
`ember generate` `model`, `adapter`, or `serializer`.  Big thanks to
[@alexander-alvarez](https://github.com/alexander-alvarez) for all his
work on the [QUnit Blueprints Quest
Issue](https://github.com/emberjs/data/issues/5292).

There are no deprecations introduced in Ember Data 3.0.

For more details on the upcoming changes in Ember Data 3.0, please review the
[Ember Data 3.0.0-beta.1 release page](https://github.com/emberjs/data/releases/tag/v3.0.0-beta.1).

---

## Ember CLI

Ember CLI is the command line interface for managing and packaging Ember.js
applications.

### Changes in Ember CLI 2.18

Ember CLI 2.18 is an incremental release featuring bug fixes and improvements.
This release does not introduce any new deprecations.

#### ESLint configuration changes

Newly generate Ember applications will now have only a single `.eslintrc.js`
file. This file uses the "overrides" feature of ESLint to customize rules
appropriately for test or Node files.

For more details see:

* [ember-cli/ember-cli#7443](https://github.com/ember-cli/ember-cli/pull/7443) Use overrides for a single `.eslintrc.js`.
* [ember-cli/ember-cli#7455](https://github.com/ember-cli/ember-cli/pull/7455) Add eslint-plugin-ember to default linting config.

#### Node 7 removed from CI testing matrix

According to the [Node support policy](https://github.com/ember-cli/ember-cli/blob/master/docs/node-support.md) of the Ember CLI project,
Node 7 is removed from the testing matrix.
If you are developing an application using Ember CLI, it is recommended that you upgrade your Node to one of the [active LTS](https://github.com/nodejs/Release) versions to guarantee security updates.

#### Addon dependencies when using npm link

Previously, if you were npm-linking an addon that had itself npm-linked a dependency, Ember CLI would fail to find it. This is now fixed.

#### `crossdomain.xml` removed for new applications

`crossdomain.xml` was originally introduced to limit vulnerabilities when
using the Flash Player.
It did this by declaring which hosts the Flash Player could connect to outside
the one hosting the file.
Browsers have since disabled Flash for security reasons, rendering the file moot.
Ember CLI 2.18 will no longer generate the file for new applications.

For more details on the changes in Ember CLI 2.18 and detailed upgrade
instructions, please review the [Ember CLI 2.18.0 release page](https://github.com/ember-cli/ember-cli/releases/tag/v2.18.0).

### Upcoming Changes in Ember CLI 3.0

Ember CLI 3.0 will feature a much improved README for the addon blueprint.
The improvements include:

* An automatically generated "Installation" section
* An empty "Usage" section
* A "License" section
* [Setext headings](http://spec.commonmark.org/0.28/#setext-heading) to emphasize sections when in raw text mode.

Ember CLI 3.0 does not introduce any new deprecations.

For more details on the changes in Ember CLI 3.0.0-beta.1 and detailed upgrade
instructions, please review the [Ember CLI 3.0.0-beta.1 release page](https://github.com/ember-cli/ember-cli/releases/tag/v3.0.0-beta.1).

## Thank You!

As a community-driven open-source project with an ambitious scope, each of
these releases serve as a reminder that the Ember project would not have been
possible without your continued support. We are extremely grateful to our
contributors for their efforts.


text:
import contextlib
import copy
import mock

from neutron_lbaas.services.loadbalancer.agent import agent_api as api
from neutron_lbaas.tests import base

class TestApiCache(base.BaseTestCase):
    def setUp(self):
        super(TestApiCache, self).setUp()

        self.api = api.LbaasAgentApi('topic', mock.sentinel.context, 'host')

    def test_init(self):
        self.assertEqual(self.api.host, 'host')
        self.assertEqual(self.api.context, mock.sentinel.context)

    def _test_method(self, method, **kwargs):
        add_host = ('get_ready_devices', 'plug_vip_port', 'unplug_vip_port',
                    'update_pool_stats')
        expected_kwargs = copy.copy(kwargs)
        if method in add_host:
            expected_kwargs['host'] = self.api.host

        with contextlib.nested(
            mock.patch.object(self.api.client, 'call'),
            mock.patch.object(self.api.client, 'prepare'),
        ) as (
            rpc_mock, prepare_mock
        ):
            prepare_mock.return_value = self.api.client
            rpc_mock.return_value = 'foo'
            rv = getattr(self.api, method)(**kwargs)

        self.assertEqual(rv, 'foo')

        prepare_args = {}
        prepare_mock.assert_called_once_with(**prepare_args)

        rpc_mock.assert_called_once_with(mock.sentinel.context, method,
                                         **expected_kwargs)

    def test_get_ready_devices(self):
        self._test_method('get_ready_devices')

    def test_get_logical_device(self):
        self._test_method('get_logical_device', pool_id='pool_id')

    def test_pool_destroyed(self):
        self._test_method('pool_destroyed', pool_id='pool_id')

    def test_pool_deployed(self):
        self._test_method('pool_deployed', pool_id='pool_id')

    def test_update_status(self):
        self._test_method('update_status', obj_type='type', obj_id='id',
                          status='status')

    def test_plug_vip_port(self):
        self._test_method('plug_vip_port', port_id='port_id')

    def test_unplug_vip_port(self):
        self._test_method('unplug_vip_port', port_id='port_id')

    def test_update_pool_stats(self):
        self._test_method('update_pool_stats', pool_id='id', stats='stats')


text:
function install {
    ln -s -f `pwd`/vimrc  $HOME/.vimrc
    touch $HOME/.vimrc.local
    yes "" | vim +PlugClean +qall
    yes "" | vim +PlugInstall +qall
}

function update {
    yes "" | vim +PlugUpdate +qall
    yes "" | vim +PlugUpgrade +qall
}

function init {
    echo ">>> Set up plug.vim ..."
    curl -fLo ~/.vim/autoload/plug.vim --create-dirs \
        https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim

    sudo pip install flake8  # for vim-flake8

    install

    mkdir -p ~/.vim/colors && cp ~/.vim/plugged/vim-colorschemes/colors/* ~/.vim/colors

    rebuild --gocode-completer
}

function rebuild() {
    cd ~/.vim/plugged/YouCompleteMe && git submodule update --init --recursive && python3 install.py "$@"
}

function usage {
    printf "Usage:\n"
    printf "    init\t初始化安装插件\n"
    printf "    install\t安装新增变更配置\n"
    printf "    update\t更新配置且更新所有插件。可能会导致ycm不能正常工作,此时需要执行 rebuild 命令\n"
    printf "    rebuild\trebuild YouCompleteMe。可加YCM build的参数,例如:--clang-completer --gocode-completer\n"
}

Action=$1
shift
case "$Action" in
    init)
        init "$@"
        ;;
    update)
        install
        update
        ;;
    install)
        install
        ;;
    rebuild)
        rebuild "$@"
        ;;
    *)
        usage
        exit 1
        ;;
esac
exit 0


text: - General documentation improvements.


text:
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.tab.state;

import org.chromium.chrome.browser.profiles.Profile;
import org.chromium.chrome.browser.profiles.ProfileManager;

import java.util.HashMap;
import java.util.Map;

/**
 * Creates {@link LevelDBPersistedTabDataStorage} instances per profile
 */
public class LevelDBPersistedTabDataStorageFactory
        implements PersistedTabDataStorageFactory<LevelDBPersistedTabDataStorage> {
    public static final Map<Profile, LevelDBPersistedTabDataStorage> sProfileToLevelDBStorageMap =
            new HashMap<>();
    private static ProfileManager.Observer sProfileManagerObserver;

    LevelDBPersistedTabDataStorageFactory() {
        if (sProfileManagerObserver == null) {
            sProfileManagerObserver = new ProfileManager.Observer() {
                @Override
                public void onProfileAdded(Profile profile) {}

                @Override
                public void onProfileDestroyed(Profile destroyedProfile) {
                    LevelDBPersistedTabDataStorage storageToDestroy =
                            sProfileToLevelDBStorageMap.get(destroyedProfile);
                    if (storageToDestroy != null) {
                        storageToDestroy.destroy();
                        sProfileToLevelDBStorageMap.remove(destroyedProfile);
                    }

                    if (sProfileToLevelDBStorageMap.isEmpty()) {
                        ProfileManager.removeObserver(sProfileManagerObserver);
                        sProfileManagerObserver = null;
                    }
                }
            };
            ProfileManager.addObserver(sProfileManagerObserver);
        }
    }

    @Override
    public LevelDBPersistedTabDataStorage create() {
        Profile profile = Profile.getLastUsedRegularProfile();
        LevelDBPersistedTabDataStorage storage = sProfileToLevelDBStorageMap.get(profile);
        if (storage == null) {
            storage = new LevelDBPersistedTabDataStorage(profile);
            sProfileToLevelDBStorageMap.put(profile, storage);
        }
        return storage;
    }
}


text:
//
//  LSYTopMenuView.m
//  LSYReader
//
//  Created by Labanotation on 16/6/1.
//  Copyright © 2016年 okwei. All rights reserved.
//

#import "LSYTopMenuView.h"
#import "LSYMenuView.h"
@interface LSYTopMenuView ()
@property (nonatomic,strong) UIButton *back;
@property (nonatomic,strong) UIButton *more;
@end
@implementation LSYTopMenuView
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setup];
    }
    return self;
}
-(void)setup
{
    [self setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.8]];
    [self addSubview:self.back];
    [self addSubview:self.more];
}
-(void)setState:(BOOL)state
{
    _state = state;
    if (state) {
        [_more setImage:[[UIImage imageNamed:@"sale_discount_yellow"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]forState:UIControlStateNormal];
        return;
    }
    [_more setImage:[[UIImage imageNamed:@"sale_discount_yellow"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]forState:UIControlStateNormal];
}
-(UIButton *)back
{
    if (!_back) {
        _back = [LSYReadUtilites commonButtonSEL:@selector(backView) target:self];
        [_back setImage:[UIImage imageNamed:@"bg_back_white"] forState:UIControlStateNormal];
    }
    return _back;
}
-(UIButton *)more
{
    if (!_more) {
        _more = [LSYReadUtilites commonButtonSEL:@selector(moreOption) target:self];
        [_more setImage:[[UIImage imageNamed:@"sale_discount_yellow"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]forState:UIControlStateNormal];
        [_more setImageEdgeInsets:UIEdgeInsetsMake(7.5, 12.5, 7.5, 12.5)];
    }
    return _more;
}
-(void)moreOption
{
    if ([self.delegate respondsToSelector:@selector(menuViewMark:)]) {
        [self.delegate menuViewMark:self];
    }
}
-(void)backView
{
    [[LSYReadUtilites getCurrentVC] dismissViewControllerAnimated:YES completion:nil];
}
-(void)layoutSubviews
{
    [super layoutSubviews];
    _back.frame = CGRectMake(0, 24, 40, 40);
    _more.frame = CGRectMake(ViewSize(self).width-50, 24, 40, 40);
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end


text:
ActiveRecord::Schema.define(version: 20150903162747) do

  create_table "acts_as_constrained_date_constraints", force: :cascade do |t|
    t.date    "starts_at"
    t.date    "ends_at"
    t.integer "constrained_id"
    t.string  "constrained_type"
  end

  add_index "acts_as_constrained_date_constraints", ["constrained_type", "constrained_id"], name: "index_date_constraints_on_constrained"

  create_table "acts_as_constrained_model_constraints", force: :cascade do |t|
    t.integer "constraining_id"
    t.string  "constraining_type"
    t.integer "constrained_id"
    t.string  "constrained_type"
  end

  add_index "acts_as_constrained_model_constraints", ["constrained_type", "constrained_id"], name: "index_model_constraints_on_constrained"
  add_index "acts_as_constrained_model_constraints", ["constraining_type", "constraining_id"], name: "index_model_constraints_on_constraining"

  create_table "no_cms_blocks_block_slots", force: :cascade do |t|
    t.integer  "container_id"
    t.string   "container_type"
    t.integer  "block_id"
    t.integer  "position",       default: 0
    t.datetime "created_at",                 null: false
    t.datetime "updated_at",                 null: false
    t.integer  "parent_id"
    t.integer  "lft"
    t.integer  "rgt"
    t.integer  "depth"
  end

  add_index "no_cms_blocks_block_slots", ["block_id"], name: "index_no_cms_blocks_block_slots_on_block_id"
  add_index "no_cms_blocks_block_slots", ["container_type", "container_id"], name: "index_no_cms_blocks_block_slots_on_container_type_and_id"
  add_index "no_cms_blocks_block_slots", ["parent_id"], name: "index_no_cms_blocks_block_slots_on_parent_id"

  create_table "no_cms_blocks_block_translations", force: :cascade do |t|
    t.integer "no_cms_blocks_block_id"
    t.string  "locale"
    t.text    "fields_info",            limit: 4294967295
    t.boolean "draft"
  end

  add_index "no_cms_blocks_block_translations", ["no_cms_blocks_block_id"], name: "no_cms_blocks_blocks_translations_block_id"

  create_table "no_cms_blocks_blocks", force: :cascade do |t|
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "parent_id"
    t.integer  "lft"
    t.integer  "rgt"
    t.integer  "depth"
    t.integer  "position"
    t.text     "fields_info"
    t.string   "layout"
  end

  create_table "page_constrained_views", force: :cascade do |t|
    t.integer  "page_id"
    t.datetime "created_at",                       null: false
    t.datetime "updated_at",                       null: false
    t.date     "single_date_constraint_starts_at"
    t.date     "single_date_constraint_ends_at"
    t.string   "skeleton"
  end

  add_index "page_constrained_views", ["page_id"], name: "index_page_constrained_views_on_page_id"

  create_table "pages", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

end


text:
package net.bytebuddy.dynamic.scaffold;

import net.bytebuddy.description.field.FieldDescription;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.MethodRule;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

public class FieldLocatorResolutionTest {

    @Rule
    public MethodRule mockitoRule = MockitoJUnit.rule().silent();

    @Mock
    private FieldDescription fieldDescription;

    @Test
    public void testSimpleResolutionResolved() throws Exception {
        assertThat(new FieldLocator.Resolution.Simple(fieldDescription).isResolved(), is(true));
    }

    @Test
    public void testSimpleResolutionFieldDescription() throws Exception {
        assertThat(new FieldLocator.Resolution.Simple(fieldDescription).getField(), is(fieldDescription));
    }

    @Test
    public void testIllegalResolutionUnresolved() throws Exception {
        assertThat(FieldLocator.Resolution.Illegal.INSTANCE.isResolved(), is(false));
    }

    @Test(expected = IllegalStateException.class)
    public void testIllegalResolutionFieldDescription() throws Exception {
        FieldLocator.Resolution.Illegal.INSTANCE.getField();
    }
}


text:
Matcher
=======

# What is this?
Matcher is a terminal based ruby application that allows people to do in person **double-blind** settlement negotation using a computer.
# Double what?
In a double blind negotiation, neither side knows the other's offer unless certain conditions are met.  In matcher, the condition is that the "ceiling" must be greater than the "floor."
# How do I use it?
If you use a Mac, Ruby is built in.  Download the file, type `ruby match.rb` and follow the directions.  This does include `ansi/code`for colors (just for the heck of it) so you may need to do `gem install ansi` if it's not installed on your machine and this throws an error.  Or just delete the require and the colors -- they're filligree, and not necessary.
# How does it work?
-  Assume you're in a negotiation with two parties and you've reached an impasse.  Neither side will move.

- The parties may each have a bottom-line that they are willing to either (1) pay or (2) accept.

- However, they can't just jump to their bottom line because if the other side doesn't they will have lost massive negotiation leverage, and either created a new floor or new ceiling.

- Ask one side to step out of the room.

- Ask the other side to type their bottom line into **Matcher** and then leave the room.

- The screen will clear and the other side will enter the room and type their 'bottom-line' number into the computer.

- If there is a match, Matcher will report the amount of the match.  (You can, of course, change how this is calculated pretty easily).

- If there is no match, Matcher just says there's no match.  This happens if the paying party is unwilling to pay an amount equal to or greater than the recipient's bottom line.

- That's it.  If the mediator doesn't look at the screen they won't know the number either.  (Yes, they could potentially find it on their computer if they really wanted  to,  But this isn't intended to be a complete solution -- and the full ImpasseBreaker site does solve that problem.)

# Why bother?
I've found that the approach works really well in litigation, and saves people time and money.  A much fancier implementation (with more explanation) can be found at www.impassebreaker.com.  Mediators can be really helpful, but they also add a personal element or dynamic that can get in the way of negotiating.  Sometimes, you may not want the mediator to know what a bottom line is.  This approach allows for comparison without a human intermediary.
# Why no pretty user  interface?
As noted above, there's a fancier version on the web that has nice UI, can send emails, create documents, it can even mix a decent Martini  (well, not just yet).   I was curious how this would look if it were really simple, and what others might do with the idea if it were stripped to its core.   So this is simple by design.

# To-dos & Things that would be cool to add
- p2p communication
- Matching using a form of Yao's protocol for secure two-party computation.

# What can I do with this?
See the license below.  Copy, fork, reinvent.  And code corrections are welcome ; ) I'm a lawyer, after all, not a professional programmer.  Feedback and suggested improvements are certainly welcome.

------

##The MIT License (MIT)

Copyright (c) 2014 Stephen D. Palley

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.