text:
package cacheOfAnno;

import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;

public class AccountPutService {
	private Account getFromDB(String acctName) {
		System.out.println("real querying db..." + acctName);
		return new Account(acctName);
	}

	@Cacheable(value = "accountCache") // 使用了一个缓存名叫 accountCache
	public Account getAccountByName(String userName) {
		// 方法内部实现不考虑缓存逻辑,直接实现业务
		return getFromDB(userName);
	}

	@CachePut(value = "accountCache", key = "#account.getName()") // 更新accountCache缓存
	public Account updateAccount(Account account) {
		return updateDB(account);
	}

	private Account updateDB(Account account) {
		System.out.println("real updating db..." + account.getName());
		return account;
	}
}


text:
package node

import (
	"errors"
	"fmt"
	"net"
	"sync"
	"time"

	"github.com/golang/glog"
	apiequality "k8s.io/apimachinery/pkg/api/equality"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/fields"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/apimachinery/pkg/types"
	utilruntime "k8s.io/apimachinery/pkg/util/runtime"
	"k8s.io/apimachinery/pkg/util/wait"
	v1core "k8s.io/client-go/kubernetes/typed/core/v1"
	clientv1 "k8s.io/client-go/pkg/api/v1"
	"k8s.io/client-go/tools/cache"
	"k8s.io/client-go/tools/record"
	"k8s.io/client-go/util/flowcontrol"
	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/api/v1"
	"k8s.io/kubernetes/pkg/client/clientset_generated/clientset"
	"k8s.io/kubernetes/pkg/client/legacylisters"
	"k8s.io/kubernetes/pkg/cloudprovider"
	"k8s.io/kubernetes/pkg/controller/informers"
	"k8s.io/kubernetes/pkg/util/metrics"
	utilnode "k8s.io/kubernetes/pkg/util/node"
	"k8s.io/kubernetes/pkg/util/system"
	utilversion "k8s.io/kubernetes/pkg/util/version"
)

func init() {
	// Register prometheus metrics
	Register()
}

var (
	ErrCloudInstance        = errors.New("cloud provider doesn't support instances.")
	gracefulDeletionVersion = utilversion.MustParseSemantic("v1.1.0")

	// The minimum kubelet version for which the nodecontroller
	// can safely flip pod.Status to NotReady.
	podStatusReconciliationVersion = utilversion.MustParseSemantic("v1.2.0")
)

const (
	// nodeStatusUpdateRetry controls the number of retries of writing NodeStatus update.
	nodeStatusUpdateRetry = 5
	// controls how often NodeController will try to evict Pods from non-responsive Nodes.
	nodeEvictionPeriod = 100 * time.Millisecond
	// Burst value for all eviction rate limiters
	evictionRateLimiterBurst = 1
	// The amount of time the nodecontroller polls on the list nodes endpoint.
	apiserverStartupGracePeriod = 10 * time.Minute
	// The amount of time the nodecontroller should sleep between retrying NodeStatus updates
	retrySleepTime = 20 * time.Millisecond
)

type zoneState string

const (
	stateInitial           = zoneState("Initial")
	stateNormal            = zoneState("Normal")
	stateFullDisruption    = zoneState("FullDisruption")
	statePartialDisruption = zoneState("PartialDisruption")
)

type nodeStatusData struct {
	probeTimestamp           metav1.Time
	readyTransitionTimestamp metav1.Time
	status                   v1.NodeStatus
}

type NodeController struct {
	allocateNodeCIDRs bool
	cloud             cloudprovider.Interface
	clusterCIDR       *net.IPNet
	serviceCIDR       *net.IPNet
	knownNodeSet      map[string]*v1.Node
	kubeClient        clientset.Interface
	// Method for easy mocking in unittest.
	lookupIP func(host string) ([]net.IP, error)
	// Value used if sync_nodes_status=False. NodeController will not proactively
	// sync node status in this case, but will monitor node status updated from kubelet. If
	// it doesn't receive update for this amount of time, it will start posting "NodeReady==
	// ConditionUnknown". The amount of time before which NodeController start evicting pods
	// is controlled via flag 'pod-eviction-timeout'.
	// Note: be cautious when changing the constant, it must work with nodeStatusUpdateFrequency
	// in kubelet. There are several constraints:
	// 1. nodeMonitorGracePeriod must be N times more than nodeStatusUpdateFrequency, where
	//    N means number of retries allowed for kubelet to post node status. It is pointless
	//    to make nodeMonitorGracePeriod be less than nodeStatusUpdateFrequency, since there
	//    will only be fresh values from Kubelet at an interval of nodeStatusUpdateFrequency.
	//    The constant must be less than podEvictionTimeout.
	// 2. nodeMonitorGracePeriod can't be too large for user experience - larger value takes
	//    longer for user to see up-to-date node status.
	nodeMonitorGracePeriod time.Duration
	// Value controlling NodeController monitoring period, i.e. how often does NodeController
	// check node status posted from kubelet. This value should be lower than nodeMonitorGracePeriod.
	// TODO: Change node status monitor to watch based.
	nodeMonitorPeriod time.Duration
	// Value used if sync_nodes_status=False, only for node startup. When node
	// is just created, e.g. cluster bootstrap or node creation, we give a longer grace period.
	nodeStartupGracePeriod time.Duration
	// per Node map storing last observed Status together with a local time when it was observed.
	// This timestamp is to be used instead of LastProbeTime stored in Condition. We do this
	// to aviod the problem with time skew across the cluster.
	nodeStatusMap map[string]nodeStatusData
	now           func() metav1.Time
	// Lock to access evictor workers
	evictorLock sync.Mutex
	// workers that evicts pods from unresponsive nodes.
	zonePodEvictor     map[string]*RateLimitedTimedQueue
	podEvictionTimeout time.Duration
	// The maximum duration before a pod evicted from a node can be forcefully terminated.
	maximumGracePeriod time.Duration
	recorder           record.EventRecorder
	podInformer        informers.PodInformer
	nodeInformer       informers.NodeInformer
	daemonSetInformer  informers.DaemonSetInformer

	podStore       listers.StoreToPodLister
	nodeStore      listers.StoreToNodeLister
	daemonSetStore listers.StoreToDaemonSetLister
	// allocate/recycle CIDRs for node if allocateNodeCIDRs == true
	cidrAllocator CIDRAllocator

	forcefullyDeletePod        func(*v1.Pod) error
	nodeExistsInCloudProvider  func(types.NodeName) (bool, error)
	computeZoneStateFunc       func(nodeConditions []*v1.NodeCondition) (int, zoneState)
	enterPartialDisruptionFunc func(nodeNum int) float32
	enterFullDisruptionFunc    func(nodeNum int) float32

	zoneStates                  map[string]zoneState
	evictionLimiterQPS          float32
	secondaryEvictionLimiterQPS float32
	largeClusterThreshold       int32
	unhealthyZoneThreshold      float32

	// internalPodInformer is used to hold a personal informer.  If we're using
	// a normal shared informer, then the informer will be started for us.  If
	// we have a personal informer, we must start it ourselves.   If you start
	// the controller using NewDaemonSetsController(passing SharedInformer), this
	// will be null
	internalPodInformer cache.SharedIndexInformer
}

// NewNodeController returns a new node controller to sync instances from cloudprovider.
// This method returns an error if it is unable to initialize the CIDR bitmap with
// podCIDRs it has already allocated to nodes. Since we don't allow podCIDR changes
// currently, this should be handled as a fatal error.
func NewNodeController(
	podInformer informers.PodInformer,
	nodeInformer informers.NodeInformer,
	daemonSetInformer informers.DaemonSetInformer,
	cloud cloudprovider.Interface,
	kubeClient clientset.Interface,
	podEvictionTimeout time.Duration,
	evictionLimiterQPS float32,
	secondaryEvictionLimiterQPS float32,
	largeClusterThreshold int32,
	unhealthyZoneThreshold float32,
	nodeMonitorGracePeriod time.Duration,
	nodeStartupGracePeriod time.Duration,
	nodeMonitorPeriod time.Duration,
	clusterCIDR *net.IPNet,
	serviceCIDR *net.IPNet,
	nodeCIDRMaskSize int,
	allocateNodeCIDRs bool) (*NodeController, error) {
	eventBroadcaster := record.NewBroadcaster()
	recorder := eventBroadcaster.NewRecorder(api.Scheme, clientv1.EventSource{Component: "controllermanager"})
	eventBroadcaster.StartLogging(glog.Infof)
	if kubeClient != nil {
		glog.V(0).Infof("Sending events to api server.")
		eventBroadcaster.StartRecordingToSink(&v1core.EventSinkImpl{Interface: v1core.New(kubeClient.Core().RESTClient()).Events("")})
	} else {
		glog.V(0).Infof("No api server defined - no events will be sent to API server.")
	}

	if kubeClient != nil && kubeClient.Core().RESTClient().GetRateLimiter() != nil {
		metrics.RegisterMetricAndTrackRateLimiterUsage("node_controller", kubeClient.Core().RESTClient().GetRateLimiter())
	}

	if allocateNodeCIDRs {
		if clusterCIDR == nil {
			glog.Fatal("NodeController: Must specify clusterCIDR if allocateNodeCIDRs == true.")
		}
		mask := clusterCIDR.Mask
		if maskSize, _ := mask.Size(); maskSize > nodeCIDRMaskSize {
			glog.Fatal("NodeController: Invalid clusterCIDR, mask size of clusterCIDR must be less than nodeCIDRMaskSize.")
		}
	}

	nc := &NodeController{
		cloud:                       cloud,
		knownNodeSet:                make(map[string]*v1.Node),
		kubeClient:                  kubeClient,
		recorder:                    recorder,
		podEvictionTimeout:          podEvictionTimeout,
		maximumGracePeriod:          5 * time.Minute,
		zonePodEvictor:              make(map[string]*RateLimitedTimedQueue),
		nodeStatusMap:               make(map[string]nodeStatusData),
		nodeMonitorGracePeriod:      nodeMonitorGracePeriod,
		nodeMonitorPeriod:           nodeMonitorPeriod,
		nodeStartupGracePeriod:      nodeStartupGracePeriod,
		lookupIP:                    net.LookupIP,
		now:                         metav1.Now,
		clusterCIDR:                 clusterCIDR,
		serviceCIDR:                 serviceCIDR,
		allocateNodeCIDRs:           allocateNodeCIDRs,
		forcefullyDeletePod:         func(p *v1.Pod) error { return forcefullyDeletePod(kubeClient, p) },
		nodeExistsInCloudProvider:   func(nodeName types.NodeName) (bool, error) { return nodeExistsInCloudProvider(cloud, nodeName) },
		evictionLimiterQPS:          evictionLimiterQPS,
		secondaryEvictionLimiterQPS: secondaryEvictionLimiterQPS,
		largeClusterThreshold:       largeClusterThreshold,
		unhealthyZoneThreshold:      unhealthyZoneThreshold,
		zoneStates:                  make(map[string]zoneState),
		podInformer:                 podInformer,
		nodeInformer:                nodeInformer,
		daemonSetInformer:           daemonSetInformer,
	}
	nc.enterPartialDisruptionFunc = nc.ReducedQPSFunc
	nc.enterFullDisruptionFunc = nc.HealthyQPSFunc
	nc.computeZoneStateFunc = nc.ComputeZoneState

	podInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
		AddFunc:    nc.maybeDeleteTerminatingPod,
		UpdateFunc: func(_, obj interface{}) { nc.maybeDeleteTerminatingPod(obj) },
	})
	nc.podStore = *podInformer.Lister()

	nodeEventHandlerFuncs := cache.ResourceEventHandlerFuncs{}
	if nc.allocateNodeCIDRs {
		var nodeList *v1.NodeList
		var err error
		// We must poll because apiserver might not be up. This error causes
		// controller manager to restart.
		if pollErr := wait.Poll(10*time.Second, apiserverStartupGracePeriod, func() (bool, error) {
			nodeList, err = kubeClient.Core().Nodes().List(metav1.ListOptions{
				FieldSelector: fields.Everything().String(),
				LabelSelector: labels.Everything().String(),
			})
			if err != nil {
				glog.Errorf("Failed to list all nodes: %v", err)
				return false, nil
			}
			return true, nil
		}); pollErr != nil {
			return nil, fmt.Errorf("Failed to list all nodes in %v, cannot proceed without updating CIDR map", apiserverStartupGracePeriod)
		}
		nc.cidrAllocator, err = NewCIDRRangeAllocator(kubeClient, clusterCIDR, serviceCIDR, nodeCIDRMaskSize, nodeList)
		if err != nil {
			return nil, err
		}

		nodeEventHandlerFuncs = cache.ResourceEventHandlerFuncs{
			AddFunc: func(originalObj interface{}) {
				obj, err := api.Scheme.DeepCopy(originalObj)
				if err != nil {
					utilruntime.HandleError(err)
					return
				}
				node := obj.(*v1.Node)

				if err := nc.cidrAllocator.AllocateOrOccupyCIDR(node); err != nil {
					utilruntime.HandleError(fmt.Errorf("Error allocating CIDR: %v", err))
				}
			},
			UpdateFunc: func(_, obj interface{}) {
				node := obj.(*v1.Node)
				// If the PodCIDR is not empty we either:
				// - already processed a Node that already had a CIDR after NC restarted
				//   (cidr is marked as used),
				// - already processed a Node successfully and allocated a CIDR for it
				//   (cidr is marked as used),
				// - already processed a Node but we did saw a "timeout" response and
				//   request eventually got through in this case we haven't released
				//   the allocated CIDR (cidr is still marked as used).
				// There's a possible error here:
				// - NC sees a new Node and assigns a CIDR X to it,
				// - Update Node call fails with a timeout,
				// - Node is updated by some other component, NC sees an update and
				//   assigns CIDR Y to the Node,
				// - Both CIDR X and CIDR Y are marked as used in the local cache,
				//   even though Node sees only CIDR Y
				// The problem here is that in in-memory cache we see CIDR X as marked,
				// which prevents it from being assigned to any new node. The cluster
				// state is correct.
				// Restart of NC fixes the issue.
				if node.Spec.PodCIDR == "" {
					nodeCopy, err := api.Scheme.Copy(node)
					if err != nil {
						utilruntime.HandleError(err)
						return
					}

					if err := nc.cidrAllocator.AllocateOrOccupyCIDR(nodeCopy.(*v1.Node)); err != nil {
						utilruntime.HandleError(fmt.Errorf("Error allocating CIDR: %v", err))
					}
				}
			},
			DeleteFunc: func(originalObj interface{}) {
				obj, err := api.Scheme.DeepCopy(originalObj)
				if err != nil {
					utilruntime.HandleError(err)
					return
				}

				node, isNode := obj.(*v1.Node)
				// We can get DeletedFinalStateUnknown instead of *v1.Node here and we need to handle that correctly. #34692
				if !isNode {
					deletedState, ok := obj.(cache.DeletedFinalStateUnknown)
					if !ok {
						glog.Errorf("Received unexpected object: %v", obj)
						return
					}
					node, ok = deletedState.Obj.(*v1.Node)
					if !ok {
						glog.Errorf("DeletedFinalStateUnknown contained non-Node object: %v", deletedState.Obj)
						return
					}
				}
				if err := nc.cidrAllocator.ReleaseCIDR(node); err != nil {
					glog.Errorf("Error releasing CIDR: %v", err)
				}
			},
		}
	}

	nodeInformer.Informer().AddEventHandler(nodeEventHandlerFuncs)
	nc.nodeStore = *nodeInformer.Lister()

	nc.daemonSetStore = *daemonSetInformer.Lister()

	return nc, nil
}

// Run starts an asynchronous loop that monitors the status of cluster nodes.
func (nc *NodeController) Run() {
	go func() {
		defer utilruntime.HandleCrash()

		if !cache.WaitForCacheSync(wait.NeverStop, nc.nodeInformer.Informer().HasSynced, nc.podInformer.Informer().HasSynced, nc.daemonSetInformer.Informer().HasSynced) {
			utilruntime.HandleError(errors.New("NodeController timed out while waiting for informers to sync..."))
			return
		}

		// Incorporate the results of node status pushed from kubelet to master.
		go wait.Until(func() {
			if err := nc.monitorNodeStatus(); err != nil {
				glog.Errorf("Error monitoring node status: %v", err)
			}
		}, nc.nodeMonitorPeriod, wait.NeverStop)

		// Managing eviction of nodes:
		// When we delete pods off a node, if the node was not empty at the time we then
		// queue an eviction watcher. If we hit an error, retry deletion.
		go wait.Until(func() {
			nc.evictorLock.Lock()
			defer nc.evictorLock.Unlock()
			for k := range nc.zonePodEvictor {
				nc.zonePodEvictor[k].Try(func(value TimedValue) (bool, time.Duration) {
					obj, exists, err := nc.nodeStore.GetByKey(value.Value)
					if err != nil {
						glog.Warningf("Failed to get Node %v from the nodeStore: %v", value.Value, err)
					} else if !exists {
						glog.Warningf("Node %v no longer present in nodeStore!", value.Value)
					} else {
						node, _ := obj.(*v1.Node)
						zone := utilnode.GetZoneKey(node)
						EvictionsNumber.WithLabelValues(zone).Inc()
					}

					nodeUid, _ := value.UID.(string)
					remaining, err := deletePods(nc.kubeClient, nc.recorder, value.Value, nodeUid, nc.daemonSetStore)
					if err != nil {
						utilruntime.HandleError(fmt.Errorf("unable to evict node %q: %v", value.Value, err))
						return false, 0
					}

					if remaining {
						glog.Infof("Pods awaiting deletion due to NodeController eviction")
					}
					return true, 0
				})
			}
		}, nodeEvictionPeriod, wait.NeverStop)
	}()
}

// monitorNodeStatus verifies node status are constantly updated by kubelet, and if not,
// post "NodeReady==ConditionUnknown". It also evicts all pods if node is not ready or
// not reachable for a long period of time.
func (nc *NodeController) monitorNodeStatus() error {
	// We are listing nodes from local cache as we can tolerate some small delays
	// comparing to state from etcd and there is eventual consistency anyway.
	nodes, err := nc.nodeStore.List()
	if err != nil {
		return err
	}
	added, deleted := nc.checkForNodeAddedDeleted(&nodes)
	for i := range added {
		glog.V(1).Infof("NodeController observed a new Node: %#v", added[i].Name)
		recordNodeEvent(nc.recorder, added[i].Name, string(added[i].UID), v1.EventTypeNormal, "RegisteredNode", fmt.Sprintf("Registered Node %v in NodeController", added[i].Name))
		nc.knownNodeSet[added[i].Name] = added[i]
		// When adding new Nodes we need to check if new zone appeared, and if so add new evictor.
		zone := utilnode.GetZoneKey(added[i])
		if _, found := nc.zonePodEvictor[zone]; !found {
			nc.zonePodEvictor[zone] =
				NewRateLimitedTimedQueue(
					flowcontrol.NewTokenBucketRateLimiter(nc.evictionLimiterQPS, evictionRateLimiterBurst))
			// Init the metric for the new zone.
			glog.Infof("Initializing eviction metric for zone: %v", zone)
			EvictionsNumber.WithLabelValues(zone).Add(0)
		}
		nc.cancelPodEviction(added[i])
	}

	for i := range deleted {
		glog.V(1).Infof("NodeController observed a Node deletion: %v", deleted[i].Name)
		recordNodeEvent(nc.recorder, deleted[i].Name, string(deleted[i].UID), v1.EventTypeNormal, "RemovingNode", fmt.Sprintf("Removing Node %v from NodeController", deleted[i].Name))
		delete(nc.knownNodeSet, deleted[i].Name)
	}

	zoneToNodeConditions := map[string][]*v1.NodeCondition{}
	for i := range nodes.Items {
		var gracePeriod time.Duration
		var observedReadyCondition v1.NodeCondition
		var currentReadyCondition *v1.NodeCondition
		nodeCopy, err := api.Scheme.DeepCopy(&nodes.Items[i])
		if err != nil {
			utilruntime.HandleError(err)
			continue
		}
		node := nodeCopy.(*v1.Node)
		if err := wait.PollImmediate(retrySleepTime, retrySleepTime*nodeStatusUpdateRetry, func() (bool, error) {
			gracePeriod, observedReadyCondition, currentReadyCondition, err = nc.tryUpdateNodeStatus(node)
			if err == nil {
				return true, nil
			}
			name := node.Name
			node, err = nc.kubeClient.Core().Nodes().Get(name, metav1.GetOptions{})
			if err != nil {
				glog.Errorf("Failed while getting a Node to retry updating NodeStatus. Probably Node %s was deleted.", name)
				return false, err
			}
			return false, nil
		}); err != nil {
			glog.Errorf("Update status  of Node %v from NodeController error : %v. "+
				"Skipping - no pods will be evicted.", node.Name, err)
			continue
		}

		// We do not treat a master node as a part of the cluster for network disruption checking.
		if !system.IsMasterNode(node.Name) {
			zoneToNodeConditions[utilnode.GetZoneKey(node)] = append(zoneToNodeConditions[utilnode.GetZoneKey(node)], currentReadyCondition)
		}

		decisionTimestamp := nc.now()
		if currentReadyCondition != nil {
			// Check eviction timeout against decisionTimestamp
			if observedReadyCondition.Status == v1.ConditionFalse &&
				decisionTimestamp.After(nc.nodeStatusMap[node.Name].readyTransitionTimestamp.Add(nc.podEvictionTimeout)) {
				if nc.evictPods(node) {
					glog.V(2).Infof("Evicting pods on node %s: %v is later than %v + %v", node.Name, decisionTimestamp, nc.nodeStatusMap[node.Name].readyTransitionTimestamp, nc.podEvictionTimeout)
				}
			}
			if observedReadyCondition.Status == v1.ConditionUnknown &&
				decisionTimestamp.After(nc.nodeStatusMap[node.Name].probeTimestamp.Add(nc.podEvictionTimeout)) {
				if nc.evictPods(node) {
					glog.V(2).Infof("Evicting pods on node %s: %v is later than %v + %v", node.Name, decisionTimestamp, nc.nodeStatusMap[node.Name].readyTransitionTimestamp, nc.podEvictionTimeout-gracePeriod)
				}
			}
			if observedReadyCondition.Status == v1.ConditionTrue {
				if nc.cancelPodEviction(node) {
					glog.V(2).Infof("Node %s is ready again, cancelled pod eviction", node.Name)
				}
			}

			// Report node event.
			if currentReadyCondition.Status != v1.ConditionTrue && observedReadyCondition.Status == v1.ConditionTrue {
				recordNodeStatusChange(nc.recorder, node, "NodeNotReady")
				if err = markAllPodsNotReady(nc.kubeClient, node); err != nil {
					utilruntime.HandleError(fmt.Errorf("Unable to mark all pods NotReady on node %v: %v", node.Name, err))
				}
			}

			// Check with the cloud provider to see if the node still exists. If it
			// doesn't, delete the node immediately.
			if currentReadyCondition.Status != v1.ConditionTrue && nc.cloud != nil {
				exists, err := nc.nodeExistsInCloudProvider(types.NodeName(node.Name))
				if err != nil {
					glog.Errorf("Error determining if node %v exists in cloud: %v", node.Name, err)
					continue
				}
				if !exists {
					glog.V(2).Infof("Deleting node (no longer present in cloud provider): %s", node.Name)
					recordNodeEvent(nc.recorder, node.Name, string(node.UID), v1.EventTypeNormal, "DeletingNode", fmt.Sprintf("Deleting Node %v because it's not present according to cloud provider", node.Name))
					go func(nodeName string) {
						defer utilruntime.HandleCrash()
						// Kubelet is not reporting and Cloud Provider says node
						// is gone. Delete it without worrying about grace
						// periods.
						if err := forcefullyDeleteNode(nc.kubeClient, nodeName); err != nil {
							glog.Errorf("Unable to forcefully delete node %q: %v", nodeName, err)
						}
					}(node.Name)
				}
			}
		}
	}
	nc.handleDisruption(zoneToNodeConditions, &nodes)

	return nil
}

func (nc *NodeController) handleDisruption(zoneToNodeConditions map[string][]*v1.NodeCondition, nodes *v1.NodeList) {
	newZoneStates := map[string]zoneState{}
	allAreFullyDisrupted := true
	for k, v := range zoneToNodeConditions {
		ZoneSize.WithLabelValues(k).Set(float64(len(v)))
		unhealthy, newState := nc.computeZoneStateFunc(v)
		ZoneHealth.WithLabelValues(k).Set(float64(100*(len(v)-unhealthy)) / float64(len(v)))
		UnhealthyNodes.WithLabelValues(k).Set(float64(unhealthy))
		if newState != stateFullDisruption {
			allAreFullyDisrupted = false
		}
		newZoneStates[k] = newState
		if _, had := nc.zoneStates[k]; !had {
			nc.zoneStates[k] = stateInitial
		}
	}

	allWasFullyDisrupted := true
	for k, v := range nc.zoneStates {
		if _, have := zoneToNodeConditions[k]; !have {
			ZoneSize.WithLabelValues(k).Set(0)
			ZoneHealth.WithLabelValues(k).Set(100)
			UnhealthyNodes.WithLabelValues(k).Set(0)
			delete(nc.zoneStates, k)
			continue
		}
		if v != stateFullDisruption {
			allWasFullyDisrupted = false
			break
		}
	}

	// At least one node was responding in previous pass or in the current pass. Semantics is as follows:
	// - if the new state is "partialDisruption" we call a user defined function that returns a new limiter to use,
	// - if the new state is "normal" we resume normal operation (go back to default limiter settings),
	// - if new state is "fullDisruption" we restore normal eviction rate,
	//   - unless all zones in the cluster are in "fullDisruption" - in that case we stop all evictions.
	if !allAreFullyDisrupted || !allWasFullyDisrupted {
		// We're switching to full disruption mode
		if allAreFullyDisrupted {
			glog.V(0).Info("NodeController detected that all Nodes are not-Ready. Entering master disruption mode.")
			for i := range nodes.Items {
				nc.cancelPodEviction(&nodes.Items[i])
			}
			// We stop all evictions.
			for k := range nc.zonePodEvictor {
				nc.zonePodEvictor[k].SwapLimiter(0)
			}
			for k := range nc.zoneStates {
				nc.zoneStates[k] = stateFullDisruption
			}
			// All rate limiters are updated, so we can return early here.
			return
		}
		// We're exiting full disruption mode
		if allWasFullyDisrupted {
			glog.V(0).Info("NodeController detected that some Nodes are Ready. Exiting master disruption mode.")
			// When exiting disruption mode update probe timestamps on all Nodes.
			now := nc.now()
			for i := range nodes.Items {
				v := nc.nodeStatusMap[nodes.Items[i].Name]
				v.probeTimestamp = now
				v.readyTransitionTimestamp = now
				nc.nodeStatusMap[nodes.Items[i].Name] = v
			}
			// We reset all rate limiters to settings appropriate for the given state.
			for k := range nc.zonePodEvictor {
				nc.setLimiterInZone(k, len(zoneToNodeConditions[k]), newZoneStates[k])
				nc.zoneStates[k] = newZoneStates[k]
			}
			return
		}
		// We know that there's at least one not-fully disrupted so,
		// we can use default behavior for rate limiters
		for k, v := range nc.zoneStates {
			newState := newZoneStates[k]
			if v == newState {
				continue
			}
			glog.V(0).Infof("NodeController detected that zone %v is now in state %v.", k, newState)
			nc.setLimiterInZone(k, len(zoneToNodeConditions[k]), newState)
			nc.zoneStates[k] = newState
		}
	}
}

func (nc *NodeController) setLimiterInZone(zone string, zoneSize int, state zoneState) {
	switch state {
	case stateNormal:
		nc.zonePodEvictor[zone].SwapLimiter(nc.evictionLimiterQPS)
	case statePartialDisruption:
		nc.zonePodEvictor[zone].SwapLimiter(
			nc.enterPartialDisruptionFunc(zoneSize))
	case stateFullDisruption:
		nc.zonePodEvictor[zone].SwapLimiter(
			nc.enterFullDisruptionFunc(zoneSize))
	}
}

// For a given node checks its conditions and tries to update it. Returns grace period to which given node
// is entitled, state of current and last observed Ready Condition, and an error if it occurred.
func (nc *NodeController) tryUpdateNodeStatus(node *v1.Node) (time.Duration, v1.NodeCondition, *v1.NodeCondition, error) {
	var err error
	var gracePeriod time.Duration
	var observedReadyCondition v1.NodeCondition
	_, currentReadyCondition := v1.GetNodeCondition(&node.Status, v1.NodeReady)
	if currentReadyCondition == nil {
		// If ready condition is nil, then kubelet (or nodecontroller) never posted node status.
		// A fake ready condition is created, where LastProbeTime and LastTransitionTime is set
		// to node.CreationTimestamp to avoid handle the corner case.
		observedReadyCondition = v1.NodeCondition{
			Type:               v1.NodeReady,
			Status:             v1.ConditionUnknown,
			LastHeartbeatTime:  node.CreationTimestamp,
			LastTransitionTime: node.CreationTimestamp,
		}
		gracePeriod = nc.nodeStartupGracePeriod
		nc.nodeStatusMap[node.Name] = nodeStatusData{
			status:                   node.Status,
			probeTimestamp:           node.CreationTimestamp,
			readyTransitionTimestamp: node.CreationTimestamp,
		}
	} else {
		// If ready condition is not nil, make a copy of it, since we may modify it in place later.
		observedReadyCondition = *currentReadyCondition
		gracePeriod = nc.nodeMonitorGracePeriod
	}

	savedNodeStatus, found := nc.nodeStatusMap[node.Name]
	// There are following cases to check:
	// - both saved and new status have no Ready Condition set - we leave everything as it is,
	// - saved status have no Ready Condition, but current one does - NodeController was restarted with Node data already present in etcd,
	// - saved status have some Ready Condition, but current one does not - it's an error, but we fill it up because that's probably a good thing to do,
	// - both saved and current statuses have Ready Conditions and they have the same LastProbeTime - nothing happened on that Node, it may be
	//   unresponsive, so we leave it as it is,
	// - both saved and current statuses have Ready Conditions, they have different LastProbeTimes, but the same Ready Condition State -
	//   everything's in order, no transition occurred, we update only probeTimestamp,
	// - both saved and current statuses have Ready Conditions, different LastProbeTimes and different Ready Condition State -
	//   Ready Condition changed it state since we last seen it, so we update both probeTimestamp and readyTransitionTimestamp.
	// TODO: things to consider:
	//   - if 'LastProbeTime' have gone back in time its probably an error, currently we ignore it,
	//   - currently only correct Ready State transition outside of Node Controller is marking it ready by Kubelet, we don't check
	//     if that's the case, but it does not seem necessary.
	var savedCondition *v1.NodeCondition
	if found {
		_, savedCondition = v1.GetNodeCondition(&savedNodeStatus.status, v1.NodeReady)
	}
	_, observedCondition := v1.GetNodeCondition(&node.Status, v1.NodeReady)
	if !found {
		glog.Warningf("Missing timestamp for Node %s. Assuming now as a timestamp.", node.Name)
		savedNodeStatus = nodeStatusData{
			status:                   node.Status,
			probeTimestamp:           nc.now(),
			readyTransitionTimestamp: nc.now(),
		}
	} else if savedCondition == nil && observedCondition != nil {
		glog.V(1).Infof("Creating timestamp entry for newly observed Node %s", node.Name)
		savedNodeStatus = nodeStatusData{
			status:                   node.Status,
			probeTimestamp:           nc.now(),
			readyTransitionTimestamp: nc.now(),
		}
	} else if savedCondition != nil && observedCondition == nil {
		glog.Errorf("ReadyCondition was removed from Status of Node %s", node.Name)
		// TODO: figure out what to do in this case. For now we do the same thing as above.
		savedNodeStatus = nodeStatusData{
			status:                   node.Status,
			probeTimestamp:           nc.now(),
			readyTransitionTimestamp: nc.now(),
		}
	} else if savedCondition != nil && observedCondition != nil && savedCondition.LastHeartbeatTime != observedCondition.LastHeartbeatTime {
		var transitionTime metav1.Time
		// If ReadyCondition changed since the last time we checked, we update the transition timestamp to "now",
		// otherwise we leave it as it is.
		if savedCondition.LastTransitionTime != observedCondition.LastTransitionTime {
			glog.V(3).Infof("ReadyCondition for Node %s transitioned from %v to %v", node.Name, savedCondition.Status, observedCondition)

			transitionTime = nc.now()
		} else {
			transitionTime = savedNodeStatus.readyTransitionTimestamp
		}
		if glog.V(5) {
			glog.V(5).Infof("Node %s ReadyCondition updated. Updating timestamp: %+v vs %+v.", node.Name, savedNodeStatus.status, node.Status)
		} else {
			glog.V(3).Infof("Node %s ReadyCondition updated. Updating timestamp.", node.Name)
		}
		savedNodeStatus = nodeStatusData{
			status:                   node.Status,
			probeTimestamp:           nc.now(),
			readyTransitionTimestamp: transitionTime,
		}
	}
	nc.nodeStatusMap[node.Name] = savedNodeStatus

	if nc.now().After(savedNodeStatus.probeTimestamp.Add(gracePeriod)) {
		// NodeReady condition was last set longer ago than gracePeriod, so update it to Unknown
		// (regardless of its current value) in the master.
		if currentReadyCondition == nil {
			glog.V(2).Infof("node %v is never updated by kubelet", node.Name)
			node.Status.Conditions = append(node.Status.Conditions, v1.NodeCondition{
				Type:               v1.NodeReady,
				Status:             v1.ConditionUnknown,
				Reason:             "NodeStatusNeverUpdated",
				Message:            fmt.Sprintf("Kubelet never posted node status."),
				LastHeartbeatTime:  node.CreationTimestamp,
				LastTransitionTime: nc.now(),
			})
		} else {
			glog.V(4).Infof("node %v hasn't been updated for %+v. Last ready condition is: %+v",
				node.Name, nc.now().Time.Sub(savedNodeStatus.probeTimestamp.Time), observedReadyCondition)
			if observedReadyCondition.Status != v1.ConditionUnknown {
				currentReadyCondition.Status = v1.ConditionUnknown
				currentReadyCondition.Reason = "NodeStatusUnknown"
				currentReadyCondition.Message = fmt.Sprintf("Kubelet stopped posting node status.")
				// LastProbeTime is the last time we heard from kubelet.
				currentReadyCondition.LastHeartbeatTime = observedReadyCondition.LastHeartbeatTime
				currentReadyCondition.LastTransitionTime = nc.now()
			}
		}

		// Like NodeReady condition, NodeOutOfDisk was last set longer ago than gracePeriod, so update
		// it to Unknown (regardless of its current value) in the master.
		// TODO(madhusudancs): Refactor this with readyCondition to remove duplicated code.
		_, oodCondition := v1.GetNodeCondition(&node.Status, v1.NodeOutOfDisk)
		if oodCondition == nil {
			glog.V(2).Infof("Out of disk condition of node %v is never updated by kubelet", node.Name)
			node.Status.Conditions = append(node.Status.Conditions, v1.NodeCondition{
				Type:               v1.NodeOutOfDisk,
				Status:             v1.ConditionUnknown,
				Reason:             "NodeStatusNeverUpdated",
				Message:            fmt.Sprintf("Kubelet never posted node status."),
				LastHeartbeatTime:  node.CreationTimestamp,
				LastTransitionTime: nc.now(),
			})
		} else {
			glog.V(4).Infof("node %v hasn't been updated for %+v. Last out of disk condition is: %+v",
				node.Name, nc.now().Time.Sub(savedNodeStatus.probeTimestamp.Time), oodCondition)
			if oodCondition.Status != v1.ConditionUnknown {
				oodCondition.Status = v1.ConditionUnknown
				oodCondition.Reason = "NodeStatusUnknown"
				oodCondition.Message = fmt.Sprintf("Kubelet stopped posting node status.")
				oodCondition.LastTransitionTime = nc.now()
			}
		}

		_, currentCondition := v1.GetNodeCondition(&node.Status, v1.NodeReady)
		if !apiequality.Semantic.DeepEqual(currentCondition, &observedReadyCondition) {
			if _, err = nc.kubeClient.Core().Nodes().UpdateStatus(node); err != nil {
				glog.Errorf("Error updating node %s: %v", node.Name, err)
				return gracePeriod, observedReadyCondition, currentReadyCondition, err
			} else {
				nc.nodeStatusMap[node.Name] = nodeStatusData{
					status:                   node.Status,
					probeTimestamp:           nc.nodeStatusMap[node.Name].probeTimestamp,
					readyTransitionTimestamp: nc.now(),
				}
				return gracePeriod, observedReadyCondition, currentReadyCondition, nil
			}
		}
	}

	return gracePeriod, observedReadyCondition, currentReadyCondition, err
}

func (nc *NodeController) checkForNodeAddedDeleted(nodes *v1.NodeList) (added, deleted []*v1.Node) {
	for i := range nodes.Items {
		if _, has := nc.knownNodeSet[nodes.Items[i].Name]; !has {
			added = append(added, &nodes.Items[i])
		}
	}
	// If there's a difference between lengths of known Nodes and observed nodes
	// we must have removed some Node.
	if len(nc.knownNodeSet)+len(added) != len(nodes.Items) {
		knowSetCopy := map[string]*v1.Node{}
		for k, v := range nc.knownNodeSet {
			knowSetCopy[k] = v
		}
		for i := range nodes.Items {
			delete(knowSetCopy, nodes.Items[i].Name)
		}
		for i := range knowSetCopy {
			deleted = append(deleted, knowSetCopy[i])
		}
	}
	return
}

// cancelPodEviction removes any queued evictions, typically because the node is available again. It
// returns true if an eviction was queued.
func (nc *NodeController) cancelPodEviction(node *v1.Node) bool {
	zone := utilnode.GetZoneKey(node)
	nc.evictorLock.Lock()
	defer nc.evictorLock.Unlock()
	wasDeleting := nc.zonePodEvictor[zone].Remove(node.Name)
	if wasDeleting {
		glog.V(2).Infof("Cancelling pod Eviction on Node: %v", node.Name)
		return true
	}
	return false
}

// evictPods queues an eviction for the provided node name, and returns false if the node is already
// queued for eviction.
func (nc *NodeController) evictPods(node *v1.Node) bool {
	nc.evictorLock.Lock()
	defer nc.evictorLock.Unlock()
	return nc.zonePodEvictor[utilnode.GetZoneKey(node)].Add(node.Name, string(node.UID))
}

// Default value for cluster eviction rate - we take nodeNum for consistency with ReducedQPSFunc.
func (nc *NodeController) HealthyQPSFunc(nodeNum int) float32 {
	return nc.evictionLimiterQPS
}

// If the cluster is large make evictions slower, if they're small stop evictions altogether.
func (nc *NodeController) ReducedQPSFunc(nodeNum int) float32 {
	if int32(nodeNum) > nc.largeClusterThreshold {
		return nc.secondaryEvictionLimiterQPS
	}
	return 0
}

// This function is expected to get a slice of NodeReadyConditions for all Nodes in a given zone.
// The zone is considered:
// - fullyDisrupted if there're no Ready Nodes,
// - partiallyDisrupted if at least than nc.unhealthyZoneThreshold percent of Nodes are not Ready,
// - normal otherwise
func (nc *NodeController) ComputeZoneState(nodeReadyConditions []*v1.NodeCondition) (int, zoneState) {
	readyNodes := 0
	notReadyNodes := 0
	for i := range nodeReadyConditions {
		if nodeReadyConditions[i] != nil && nodeReadyConditions[i].Status == v1.ConditionTrue {
			readyNodes++
		} else {
			notReadyNodes++
		}
	}
	switch {
	case readyNodes == 0 && notReadyNodes > 0:
		return notReadyNodes, stateFullDisruption
	case notReadyNodes > 2 && float32(notReadyNodes)/float32(notReadyNodes+readyNodes) >= nc.unhealthyZoneThreshold:
		return notReadyNodes, statePartialDisruption
	default:
		return notReadyNodes, stateNormal
	}
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * @provides phui-timeline-view-css
 */

.phui-timeline-view {
  padding: 0 16px;
  background-image: url('/rsrc/image/d5d8e1.png');
  background-repeat: repeat-y;
  background-position: 96px;
}

.device .phui-timeline-view {
  padding: 0 8px;
}

.device-tablet .phui-timeline-view {
  background-position: 24px;
}

.device-phone .phui-timeline-view {
  padding: 0;
  background-position: 24px;
}

.phui-timeline-major-event .phui-timeline-group {
  border-left: 1px solid {$timeline};
  border-right: 1px solid {$timeline};
  border-radius: 3px;
}

.device-desktop .phui-timeline-event-view {
  margin-left: 62px;
  position: relative;
}

.device-desktop .phui-timeline-event-view.phui-timeline-minor-event {
  margin-left: 67px;
}

.device-desktop .phui-timeline-spacer {
  min-height: 16px;
}

.device-desktop .phui-timeline-event-view.the-worlds-end {
  background: {$lightblueborder};
  width: 9px;
  height: 9px;
  border-radius: 2px;
  margin-left: 76px;
}

.device-desktop .phui-timeline-wedge {
  border-bottom: 1px solid {$timeline};
  position: absolute;
  width: 12px;
}

.device-phone .phui-timeline-minor-event,
.device-tablet .phui-timeline-minor-event {
  padding-left: 3px;
}

.phui-timeline-major-event .phui-timeline-content {
  border-top: 1px solid {$timeline};
  border-bottom: 1px solid {$timeline};
  border-radius: 3px;
}

.phui-timeline-title {
  line-height: 24px;
  min-height: 19px;
  position: relative;
  color: {$greytext};
}

.phui-timeline-minor-event .phui-timeline-title {
  padding: 1px 8px 4px 33px;
}

.phui-timeline-title a {
  font-weight: bold;
  color: {$darkgreytext};
}

.device-desktop .phui-timeline-wedge {
  left: -12px;
}

.device-desktop .phui-timeline-major-event .phui-timeline-wedge {
  top: 26px;
}

.device-desktop .phui-timeline-minor-event .phui-timeline-wedge {
  top: 12px;
  left: -18px;
  width: 20px;
}

.phui-timeline-image {
  background-repeat: no-repeat;
  position: absolute;
  border-radius: 3px;
  background-size: 100%;
  display: block;
}

.device-desktop .phui-timeline-major-event .phui-timeline-image {
  width: 50px;
  height: 50px;
  top: 0px;
  left: -62px;
}

.device-desktop .phui-timeline-minor-event .phui-timeline-image {
  width: 26px;
  height: 26px;
  background-size: 26px auto;
  left: -41px;
}

.phui-timeline-major-event .phui-timeline-title {
  background: {$lightgreybackground};
  min-height: 22px;
  border-top-right-radius: 3px;
  border-top-left-radius: 3px;
}

.phui-timeline-major-event .phui-timeline-title + .phui-timeline-title {
  border-radius: 0;
  padding-top: 0;
}

.phui-timeline-major-event .phui-timeline-title + .phui-timeline-title
  .phui-timeline-icon-fill {
    margin-top: 0;
  }

.phui-timeline-title {
  padding: 5px 8px;
  overflow-x: auto;
  overflow-y: hidden;
}

.phui-timeline-title-with-icon {
  padding-left: 36px;
}

.phui-timeline-title-with-menu {
  padding-right: 36px;
}

.phui-timeline-view .phui-icon-view.phui-timeline-token {
  vertical-align: middle;
  margin-right: 4px;
}

.phui-timeline-token.strikethrough {
  position: relative;
}

.phui-timeline-token.strikethrough:before {
  position: absolute;
  content: "";
  left: 0;
  top: 50%;
  right: 0;
  border-top: 3px solid;
  border-color: {$darkbluetext};

  -webkit-transform:rotate(-40deg);
  -moz-transform:rotate(-40deg);
  -ms-transform:rotate(-40deg);
  -o-transform:rotate(-40deg);
  transform:rotate(-40deg);
}

.phui-timeline-major-event .phui-timeline-content
  .phui-timeline-core-content {
  padding: 16px;
  line-height: 18px;
  background: #fff;
  border-top: 1px solid rgba({$alphablue},.1);
  border-bottom-left-radius: 3px;
  border-bottom-right-radius: 3px;
}

.phui-timeline-core-content {
  overflow-x: auto;
}

.phui-timeline-core-content .comment-deleted {
  font-style: italic;
}

.device .phui-timeline-event-view {
  min-height: 23px;
  position: relative;
}

.device-phone .phui-timeline-event-view {
  margin: 0 8px;
}

.device .phui-timeline-image {
  display: none;
}

.device .phui-timeline-spacer {
  min-height: 8px;
  border-width: 0;
}

.phui-timeline-icon-fill {
  position: absolute;
  width: 34px;
  height: 34px;
  top: 0;
  left: 0;
  text-align: center;
}

.phui-timeline-icon {
  color: {$sh-blueicon};
}

.phui-icon-view.phui-timeline-icon {
  font-size: 14px;
}

.phui-timeline-icon-fill {
  height: 26px;
  width: 26px;
  border-radius: 3px;
  background-color: #E6E9F1;
}

.phui-timeline-major-event .phui-timeline-icon-fill {
  margin: 4px;
}

.phui-timeline-icon-fill .phui-timeline-icon {
  margin-top: 6px;
}

.phui-timeline-extra,
.phui-timeline-extra .phabricator-content-source-view {
  font-size: {$smallerfontsize};
  font-weight: normal;
  color: {$lightgreytext};
  margin-left: 8px;
}

.phui-timeline-title .phui-timeline-extra a {
  font-weight: normal;
  color: {$lightgreytext};
}

.device-desktop .phui-timeline-extra {
  float: right;
}

.device .phui-timeline-extra {
  display: inline-block;
  line-height: 16px;
  margin-left: 8px;
  white-space: nowrap;
}

.device-phone .phui-timeline-extra {
  display: block;
  margin: 0;
}

.phui-timeline-icon-fill.fill-has-color .phui-icon-view {
  color: #fff;
}

.phui-timeline-icon-fill-red {
  background-color: {$red};
}

.phui-timeline-icon-fill-orange {
  background-color: {$orange};
}

.phui-timeline-icon-fill-yellow {
  background-color: {$yellow};
}

.phui-timeline-icon-fill-green {
  background-color: {$green};
}

.phui-timeline-icon-fill-sky {
  background-color: {$sky};
}

.phui-timeline-icon-fill-blue {
  background-color: {$blue};
}

.phui-timeline-icon-fill-indigo {
  background-color: {$indigo};
}

.phui-timeline-icon-fill-violet {
  background-color: {$violet};
}

.phui-timeline-icon-fill-grey {
  background-color: #888;
}

.phui-timeline-icon-fill-black {
  background-color: #000;
}

.phui-timeline-shell.anchor-target {
  background: {$lightyellow};
  padding: 4px;
  margin: -4px;
}

.phui-timeline-preview-header {
  background: #e0e3ec;
  color: {$darkgreytext};
  padding: 4px 1.25%;
  border: solid {$blueborder} 1px 0;
}

.phui-timeline-change-details {
  padding: 10px 0;
  border-style: solid;
  border-color: #efefef;
  border-width: 1px 0;
}

.phui-timeline-older-transactions-are-hidden {
  background: {$sh-yellowbackground};
  border: 1px solid {$sh-yellowborder};
  text-align: center;
  padding: 12px;
  color: {$darkgreytext};
  cursor: pointer;
  border-radius: 3px;
}

.device-phone .phui-timeline-older-transactions-are-hidden {
  margin: 0 8px;
}

.phui-timeline-title .phui-timeline-extra-information a {
  font-weight: normal;
  color: {$greytext};
}

.phui-timeline-comment-actions .phui-icon-view {
  width: 16px;
  height: 16px;
  font-size: 16px;
  text-align: center;
  overflow: hidden;
}

.phui-timeline-menu {
  position: absolute;
  right: 3px;
  top: 6px;
  width: 28px;
  height: 24px;
  text-align: center;
  line-height: 22px;
  font-size: 16px;
  border-left: 1px solid {$thinblueborder};
}

.phui-timeline-menu:focus {
  outline: none;
}

.phui-timeline-menu .phui-icon-view {
  color: {$lightgreytext};
}

a.phui-timeline-menu .phui-icon-view {
  color: {$bluetext};
}

.device-desktop a.phui-timeline-menu:hover .phui-icon-view {
  color: {$sky};
}

.phui-timeline-menu.phuix-dropdown-open {
  background: rgba({$alphablue},0.1);
  border: none;
  border-radius: 3px;
}

.phui-timeline-view + .phui-object-box {
  margin-top: 0;
}

.phui-timeline-badges {
  position: absolute;
  left: -64px;
  top: 52px;
  width: 54px;
}

.phui-timeline-badges .phui-badge-mini {
  height: 18px;
  width: 18px;
  line-height: 16px;
}

.phui-timeline-badges .phui-badge-mini .phui-icon-view {
  font-size: 10px;
}


text:
package com.daviancorp.android.ui.list;

import java.io.IOException;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.daviancorp.android.data.classes.Decoration;
import com.daviancorp.android.data.database.DecorationCursor;
import com.daviancorp.android.loader.DecorationListCursorLoader;
import com.daviancorp.android.mh4udatabase.R;
import com.daviancorp.android.ui.ClickListeners.DecorationClickListener;
import com.daviancorp.android.ui.detail.ASBActivity;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class DecorationListFragment extends ListFragment implements
        LoaderCallbacks<Cursor> {

//	private static final String DIALOG_WISHLIST_DATA_ADD_MULTI = "wishlist_data_add_multi";
//	private static final int REQUEST_ADD_MULTI = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setHasOptionsMenu(true);
        // Initialize the loader to load the list of runs
        getLoaderManager().initLoader(R.id.decoration_list_fragment, null, this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_generic_list, container, false);
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        // You only ever load the runs, so assume this is the case
        return new DecorationListCursorLoader(getActivity());
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
        // Create an adapter to point at this cursor
        DecorationListCursorAdapter adapter = new DecorationListCursorAdapter(
                getActivity(), (DecorationCursor) cursor);
        setListAdapter(adapter);

    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        // Stop using the cursor (via the adapter)
        setListAdapter(null);
    }

    private static class DecorationListCursorAdapter extends CursorAdapter {

        private DecorationCursor mDecorationCursor;

        private Activity activity;
        private boolean fromAsb;

        public DecorationListCursorAdapter(Context context,
                                           DecorationCursor cursor) {
            super(context, cursor, 0);
            mDecorationCursor = cursor;

            // ASB stuff
            if (context instanceof Activity && ((Activity) context).getIntent().getBooleanExtra(ASBActivity.EXTRA_FROM_SET_BUILDER, false)) {
                activity = (Activity) context;
                fromAsb = true;

            }
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            // Use a layout inflater to get a row view
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            return inflater.inflate(R.layout.fragment_decoration_listitem,
                    parent, false);
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            // Get the decoration for the current row
            Decoration decoration = mDecorationCursor.getDecoration();

            RelativeLayout itemLayout = (RelativeLayout) view.findViewById(R.id.listitem);

            // Set up the text view
            ImageView itemImageView = (ImageView) view.findViewById(R.id.item_image);
            TextView decorationNameTextView = (TextView) view.findViewById(R.id.item);
            TextView skill1TextView = (TextView) view.findViewById(R.id.skill1);
            TextView skill1amtTextView = (TextView) view.findViewById(R.id.skill1_amt);
            TextView skill2TextView = (TextView) view.findViewById(R.id.skill2);
            TextView skill2amtTextView = (TextView) view.findViewById(R.id.skill2_amt);

            String decorationNameText = decoration.getName();
            String skill1Text = decoration.getSkill1Name();
            String skill1amtText = "" + decoration.getSkill1Point();
            String skill2Text = decoration.getSkill2Name();
            String skill2amtText = "";
            if (decoration.getSkill2Point() != 0) {
                skill2amtText = skill2amtText + decoration.getSkill2Point();
            }

            Drawable i = null;
            String cellImage = "icons_items/" + decoration.getFileLocation();
            try {
                i = Drawable.createFromStream(
                        context.getAssets().open(cellImage), null);
            } catch (IOException e) {
                e.printStackTrace();
            }

            itemImageView.setImageDrawable(i);

            decorationNameTextView.setText(decorationNameText);
            skill1TextView.setText(skill1Text);
            skill1amtTextView.setText(skill1amtText);

            skill2TextView.setVisibility(View.GONE);
            skill2amtTextView.setVisibility(View.GONE);

            if (!skill2amtText.equals("")) {
                skill2TextView.setText(skill2Text);
                skill2amtTextView.setText(skill2amtText);
                skill2TextView.setVisibility(View.VISIBLE);
                skill2amtTextView.setVisibility(View.VISIBLE);
            }

            itemLayout.setTag(decoration.getId());

            if (fromAsb) {
                itemLayout.setOnClickListener(new DecorationClickListener(context, decoration.getId(), true, activity));
            } else {
                itemLayout.setOnClickListener(new DecorationClickListener(context, decoration.getId()));
            }
        }
    }
}


text:
from __future__ import unicode_literals

from abenity.client import Abenity
from base64 import b64encode
from Crypto.Cipher import PKCS1_v1_5
from Crypto.PublicKey import RSA
import datetime
import pprint
import binascii
from random import randint
import pytest
import six
import sys

version = sys.version_info[0]
is_py2 = (version == 2)
is_py3 = (version == 3)

if is_py2:
    from urllib import quote_plus
    from urllib import unquote_plus
    from urllib import urlencode
elif is_py3:
    from urllib.parse import quote_plus
    from urllib.parse import unquote_plus
    from urllib.parse import urlencode
else:
    raise ImportError("urllib quote_plus or unquote_plus cannot be imported!")

class TestClass:
    abenity_api_username = 'username'
    abenity_api_password = 'password'
    abenity_api_key = 'EP89f4pVQbEoUXc3JcT7asdktThBVR3K'

    f = open('private-key-test.txt', 'r')
    abenity_your_private_key = f.read()

    member_profile = {'creation_time': '2017-04-10T18:51:23.053883',
                      'salt': 10000,
                      'send_welcome_email': 1,
                      'client_user_id': '1',
                      'email': 'john@acme.com',
                      'firstname': 'John',
                      'lastname': 'Smith',
                      'address': '2134 Main Street',
                      'city': 'Mountain View',
                      'state': 'CA',
                      'zip': '90210',
                      'country': 'US'}

    abenity = Abenity(abenity_api_username, abenity_api_password,
                      abenity_api_key, version=2, environment='sandbox',
                      timeout=10)

    def test_set_triple_des_key(self):
        self.abenity.set_triple_des_key('IoAZqZ3RCezxj7eKWeKj00mT')
        assert self.abenity._triple_des_key == 'IoAZqZ3RCezxj7eKWeKj00mT'

    def test_encrypt_payload(self):
        self.abenity.set_triple_des_key('IoAZqZ3RCezxj7eKWeKj00mT')
        payload = urlencode(self.member_profile)
        init_vector = binascii.unhexlify("41420c2d32373c3e")
        payload_encrypted = self.abenity._encrypt_payload(payload, init_vector)
        # TODO: add a better test, right now random and no easy way to override
        #       an easy function to make it not random, that I can see.
        assert payload_encrypted is not None

    def test_encrypt_cipher(self):
        self.abenity.set_triple_des_key('IoAZqZ3RCezxj7eKWeKj00mT')

        # remove RSA randomness, so can test
        def newRand(obj=None):
            return six.b('a')

        cipher = self.abenity._encrypt_cipher(rand_function=newRand)
        assert cipher == 'vDUtFs8K8pvy0db7D1EXTrUkWv5PTeldb77BBXpQN7SM521b' + \
            'INUcgbDbNc5Cn66ukeSNykeYPSAA4fzX3CGb1fuuO5stE19FP8cabJZFQL2GL' + \
            '6UrWu%2FAz6tAx06hl4R9CUSLu0ZQPwweW%2BrLKeFluvnlHIMsdzdmiybeuS' + \
            'UhucE%3Ddecode'

    def test_sign_message(self, monkeypatch):
        self.abenity.set_triple_des_key('IoAZqZ3RCezxj7eKWeKj00mT')

        # remove RSA randomness, so can test
        def mockreturn(key=None):
            keyObj = RSA.importKey(key)

            def newRand(obj=None):
                return six.b('abc')
            keyObj._randfunc = newRand
            return keyObj

        monkeypatch.setattr(self.abenity, '_generate_rsa_key', mockreturn)
        dummy_encrypted_payload = "asdf09asdf8a0s8df0a8sd09f8a0s98df0as8df09ad"
        cipher = self.abenity._sign_message(dummy_encrypted_payload,
                                            self.abenity_your_private_key)
        assert cipher == 'LL6DS2gEQxwYUjxfNQZdKOtv1MSP7bpK0PP9LdQ%2FYG3pF' + \
            '1Sy2e2LYxkZt6M9HidkXMKc3F73gVsiBomj91YRAlKV23VNMY31wNeMmISVi' + \
            'jk24vmbNttI6Pqy6In0kOtqUgVGCJDWSMPC2P7RWL655J%2FE7QF7f0MizF5' + \
            '3Gk3DoSgx7PuNigz9YYPDe%2BSOcIpdAUOYaeJ8ahMje8cij0uOi0%2FORPr' + \
            'jvb9t4RSvO2%2FKilY%2BDn2QvMFH79l91BsZ8EpCNxgnhSAiYQXuCTnd32W' + \
            'fTWLfKvj4smxtk9TbiCIueiM9DmtIU1np8OVruu%2FFwNxnHwD09ssL8fYz1' + \
            'PLfkE%2BJhw%3D%3Ddecode'

    def test_request_data(self):
        self.abenity.set_triple_des_key('IoAZqZ3RCezxj7eKWeKj00mT')
        payload = urlencode(self.member_profile)
        init_vector = binascii.unhexlify("41420c2d32373c3e")
        iv_urlencoded = quote_plus(b64encode(init_vector).decode("utf-8")) + \
            "decode"


text:
goog.provide('API.Client.GithubRespositoryContainer');

/**
 * @record
 */
API.Client.GithubRespositoryContainer = function() {}

/**
 * @type {!string}
 * @export
 */
API.Client.GithubRespositoryContainer.prototype._class;

/**
 * @type {!API.Client.GithubRespositoryContainerlinks}
 * @export
 */
API.Client.GithubRespositoryContainer.prototype.links;

/**
 * @type {!API.Client.GithubRepositories}
 * @export
 */
API.Client.GithubRespositoryContainer.prototype.repositories;


text:
package com.soundcloud.lightcycle.sample.real_world.home;

import com.soundcloud.lightcycle.DefaultActivityLightCycle;

import android.os.Bundle;

import androidx.annotation.Nullable;

import javax.inject.Inject;

class DescriptionPresenter extends DefaultActivityLightCycle<HomeView> {

    @Inject
    public DescriptionPresenter() {
    }

    @Override
    public void onCreate(HomeView homeView, @Nullable Bundle bundle) {
        homeView.showDescription("LightCycle", "https://github.com/soundcloud/lightcycle");
    }

}


text:
import urllib2
import re
import json

def get_chart(symbol, timeframe = 'D', country = "US"):
    dash = '-'
    to_slash = re.compile(dash)
    symbol = to_slash.sub('/', symbol)
    print symbol
    url = "http://bloomberg.com/markets/chart/data/1{}/{}:{}".format(timeframe,symbol,country)
    resp = urllib2.urlopen(url)
    if resp.getcode() == 200:
        data = json.load(resp)
        datapoints = data["data_values"]
    else:
        print symbol, "\tN/A"
        datapoints = 'N/A'
    return datapoints


text:
<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="../bower_components/paper-button/paper-button.html">
<link rel="import" href="../bower_components/paper-card/paper-card.html">

<link rel="import" href="aof-pagelist.html">
<link rel="import" href="page-shared-styles.html">

<dom-module id="aof-page-dashboard">
  <template>

    <paper-card heading="Welcome card">

Ut labores minimum atomorum pro. Laudem tibique ut has.

Lorem ipsum dolor sit amet, per in nusquam nominavi periculis, sit elit oportere ea.Lorem ipsum dolor sit amet, per in nusquam nominavi periculis, sit elit oportere ea.Cu mei vide viris gloriatur, at populo eripuit sit.

        <paper-button>Dismiss</paper-button>

    </paper-card>

    <aof-pagelist hidden$="[[!user]]"></aof-pagelist>

  </template>

</dom-module>


text:
![PipelineAI Logo](http://pipeline.ai/assets/img/logo/pipelineai-logo.png)

### PipelineAI Quick Start (CPU + GPU)
Train and Deploy your ML and AI Models in the Following Environments:
* [Hosted Community Edition](/docs/quickstart/community)
* [Docker](/docs/quickstart/docker)
* [Kubernetes](/docs/quickstart/kubernetes)
* [AWS SageMaker](/docs/quickstart/sagemaker)

# Having Issues?  Contact Us Anytime... We're Always Awake.
* Slack:  https://joinslack.pipeline.ai
* Email:  [help@pipeline.ai](mailto:help@pipeline.ai)
* Web:  https://support.pipeline.ai
* YouTube:  https://youtube.pipeline.ai
* Slideshare:  https://slideshare.pipeline.ai
* [Troubleshooting Guide](/docs/troubleshooting)


text:
$("#deleteOffer").on("click", function () {
    var currentOfferInputId = $(this).next('#offerHiddenIdForDeletingINModalWindow');
    var offerIdValue = currentOfferInputId.val();
    var currentUserRoleName = MY_APP_VARS.currentUser.roleName;

    if (currentUserRoleName === '' || currentUserRoleName === null) {
        currentUserRoleName = "anonymous"
    }

    $.ajax({
        url: "/" + currentUserRoleName + '/delete' + "/" + offerIdValue,
        scriptCharset: 'UTF-8',
        method: 'DELETE',
        success: function (data, textStatus, jqXHR) {
            if (jqXHR.status === 204 || jqXHR.status === 200) {
                var id = data.id;
                var selector = ".main_out_wrapper_user_offers input#offerHiddenId[value=\""+id+"\"]";
                var hiddenInputWithOfferId = $(selector);
                var parent = hiddenInputWithOfferId.closest("div.inner_main_out_wrapper_user_offers");
                parent.detach();
                $("#no").click();
            } else {
                alert("Can't delete the offer, something goes wrong on the server side");
            }
        },
        error: function (data, textStatus, jqXHR) {
            var div = $(document.createElement('div'));
            var col = $(document.createElement('div'));
            var span = $("<span>"+data.responseText+"</span>");
            div.addClass("modal-footer");
            div.addClass("errorFromDeleteOffer");
            div.append(span);
            $("input#deleteOffer").closest("div.modal-content").append(div);
            div.show(1000);
            div.delay(5000);
            div.hide(1000);
        }
    });

});


text:
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

Imports System.Collections.Immutable
Imports System.Composition
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Shared.TestHooks
Imports Microsoft.CodeAnalysis.Snippets
Imports Microsoft.VisualStudio.LanguageServices.CSharp.Snippets
Imports Roslyn.Test.Utilities

Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Completion
    <ExportLanguageService(GetType(ISnippetInfoService), LanguageNames.CSharp), [Shared]>
    Friend Class TestCSharpSnippetInfoService
        Inherits CSharpSnippetInfoService

        <ImportingConstructor>
        Friend Sub New(<ImportMany> asyncListeners As IEnumerable(Of Lazy(Of IAsynchronousOperationListener, FeatureMetadata)))
            MyBase.New(Nothing, asyncListeners)
        End Sub

        Friend Sub SetSnippetShortcuts(newSnippetShortcuts As String())
            SyncLock cacheGuard
                snippets = newSnippetShortcuts.Select(Function(shortcut) New SnippetInfo(shortcut, "title", "description", "path")).ToImmutableArray()
                snippetShortcuts = GetShortcutsHashFromSnippets(snippets)
            End SyncLock
        End Sub
    End Class
End Namespace


text:
"use strict";

let config    		= require("../config");
let logger    		= require("../core/logger");
let C 				= require("../core/constants");
let fs 				= require("fs");
let path 			= require("path");

let _ 				= require("lodash");
let crypto 			= require("crypto");
let bcrypt 			= require("bcrypt-nodejs");

let db	    		= require("../core/mongo")();
let mongoose 		= require("mongoose");
let Schema 			= mongoose.Schema;
let hashids 		= require("../libs/hashids")("users");
let autoIncrement 	= require("mongoose-auto-increment");

let schemaOptions = {
	timestamps: true,
	toObject: {
		virtuals: true
	},
	toJSON: {
		virtuals: true
	}
};

let validateLocalStrategyProperty = function(property) {
	return (this.provider !== "local" && !this.updated) || property.length;
};

let validateLocalStrategyPassword = function(password) {
	return this.provider !== "local" || (password && password.length >= 6);
};

let UserSchema = new Schema({
	fullName: {
		type: String,
		trim: true,
		"default": "",
		validate: [validateLocalStrategyProperty, "Please fill in your full name"]
	},
	email: {
		type: String,
		trim: true,
		unique: true,
		index: true,
		lowercase: true,
		"default": "",
		validate: [validateLocalStrategyProperty, "Please fill in your email"],
		match: [/.+\@.+\..+/, "Please fill a valid email address"]
	},
	username: {
		type: String,
		unique: true,
		index: true,
		lowercase: true,
		required: "Please fill in a username",
		trim: true,
		match: [/^[\w][\w\-\._\@]*[\w]$/, "Please fill a valid username"]
	},
	password: {
		type: String,
		"default": "",
		validate: [validateLocalStrategyPassword, "Password should be longer"]
	},
	passwordLess: {
		type: Boolean,
		default: false
	},
	passwordLessToken: {
		type: String
	},
	provider: {
		type: String,
		"default": "local"
	},
	profile: {
		name: { type: String },
		gender: { type: String },
		picture: { type: String },
		location: { type: String }
	},
	socialLinks: {
		facebook: { type: String, unique: true, sparse: true },
		twitter: { type: String, unique: true, sparse: true },
		google: { type: String, unique: true, sparse: true },
		github: { type: String, unique: true, sparse: true }
	},
	roles: {
		type: [
			{
				type: String,
				"enum": [
					C.ROLE_ADMIN,
					C.ROLE_USER,
					C.ROLE_GUEST
				]
			}
		],
		"default": [C.ROLE_USER]
	},
	resetPasswordToken: String,
	resetPasswordExpires: Date,

	verified: {
		type: Boolean,
		default: false
	},

	verifyToken: {
		type: String
	},

	apiKey: {
		type: String,
		unique: true,
		index: true,
		sparse: true
	},

	lastLogin: {
		type: Date
	},

	locale: {
		type: String
	},

	status: {
		type: Number,
		default: 1
	},

	metadata: {}

}, schemaOptions);

/**
 * Virtual `code` field instead of _id
 */
UserSchema.virtual("code").get(function() {
	return this.encodeID();
});

/**
 * Auto increment for `_id`
 */
UserSchema.plugin(autoIncrement.plugin, {
	model: "User",
	startAt: 1
});

/**
 * Password hashing
 */
UserSchema.pre("save", function(next) {
	let user = this;
	if (!user.isModified("password"))
		return next();

	bcrypt.genSalt(10, function(err, salt) {
		bcrypt.hash(user.password, salt, null, function(err, hash) {
			user.password = hash;
			next();
		});
	});
});

/**
 * Password compare
 */
UserSchema.methods.comparePassword = function(password, cb) {
	bcrypt.compare(password, this.password, function(err, isMatch) {
		cb(err, isMatch);
	});
};

/**
 * Virtual field for `avatar`.
 */
UserSchema.virtual("avatar").get(function() {
	// Load picture from profile
	if (this.profile && this.profile.picture)
		return this.profile.picture;

	// Generate a gravatar picture
	if (!this.email)
		return "https://gravatar.com/avatar/?s=64&d=wavatar";

	let md5 = crypto.createHash("md5").update(this.email).digest("hex");
	return "https://gravatar.com/avatar/" + md5 + "?s=64&d=wavatar";
});

/**
 * Encode `_id` to `code`
 */
UserSchema.methods.encodeID = function() {
	return hashids.encodeHex(this._id);
};

/**
 * Decode `code` to `_id`
 */
UserSchema.methods.decodeID = function(code) {
	return hashids.decodeHex(code);
};

/**
 * Pick is only some fields of object
 *
 * http://mongoosejs.com/docs/api.html#document_Document-toObject
 *
UserSchema.methods.pick = function(props, model) {
	return _.pick(model || this.toJSON(), props || [
		"code",
		"fullName",
		"email",
		"username",
		"roles",
		"lastLogin",
		"avatar"
	]);
};

UserSchema.method('toJSON', function() {
    var user = this.toObject();
    delete user.salt;
    delete user.hash;
    delete user.__v;
    return user;
  });
*/

/*
UserSchema.methods.gravatar = function (size, defaults) {
	if (!size)
		size = 200;

	if (!defaults)
		defaults = 'wavatar';

	if (!this.email)
		return `https://gravatar.com/avatar/?s=${size}&d=${defaults}`;

	let md5 = crypto.createHash('md5').update(this.email).digest("hex");
	return `https://gravatar.com/avatar/${md5}?s=${size}&d=${defaults}`;
};*/

let User = mongoose.model("User", UserSchema);

module.exports = User;


text:
import React from "react";

export default function About() {
  return (
    <>

Know the Unknown

            There are known knowns. These are things we know that we know. There
            are known unknowns. That is to say, there are things that we know we
            don't know. But there are also unknown unknowns. There are things we
            don't know we don't know.

-- Donald Rumsfeld

    </>
  );
}


text:
package com.siimkinks.sqlitemagic;

import com.siimkinks.sqlitemagic.internal.SimpleArrayMap;

import java.util.ArrayList;
import java.util.LinkedList;

import androidx.annotation.NonNull;

final class BinaryExpr extends Expr {
  @NonNull
  final Expr lhs;
  @NonNull
  final Expr rhs;

  BinaryExpr(@NonNull String op, @NonNull Expr lhs, @NonNull Expr rhs) {
    //noinspection ConstantConditions
    super(null, op); // null is ok here, we override all calls related to column
    this.lhs = lhs;
    this.rhs = rhs;
  }

  @Override
  void addArgs(@NonNull ArrayList<String> args) {
    lhs.addArgs(args);
    rhs.addArgs(args);
  }

  @Override
  void appendToSql(@NonNull StringBuilder sb) {
    sb.append('(');
    lhs.appendToSql(sb);
    sb.append(op);
    rhs.appendToSql(sb);
    sb.append(')');
  }

  @Override
  void appendToSql(@NonNull StringBuilder sb, @NonNull SimpleArrayMap<String, LinkedList<String>> systemRenamedTables) {
    sb.append('(');
    lhs.appendToSql(sb, systemRenamedTables);
    sb.append(op);
    rhs.appendToSql(sb, systemRenamedTables);
    sb.append(')');
  }

  @Override
  boolean containsColumn(@NonNull Column<?, ?, ?, ?, ?> column) {
    return lhs.containsColumn(column) || rhs.containsColumn(column);
  }
}


text:
<?php

namespace BookStack\Exceptions;

class FileUploadException extends PrettyException
{
}


text:
<?php

namespace Karma\Generator\NameTranslators;

class FilePrefixTranslatorTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider providerTestTranslate
     */
    public function testTranslate($file, $variable, $expected)
    {
        $t = new FilePrefixTranslator();

        $this->assertSame($expected, $t->translate($file, $variable));
    }

    public function providerTestTranslate()
    {
        return array(
            // no prefix for master.conf
            array('master.conf', 'burger', 'burger'),
            array('master.conf', 'worker.level', 'worker.level'),
            array('master.conf', 'app.master.var.pony.master', 'app.master.var.pony.master'),
            array('master.conf', 'master', 'master'),
            array('master.conf', 'master.master', 'master.master'),

            // prefix for other files
            array('db.conf', 'port', 'db.port'),
            array('db.conf', 'db', 'db.db'),
            array('logger.conf', 'worker.level', 'logger.worker.level'),
            array('logger.conf', 'worker.file', 'logger.worker.file'),
            array('logger_levels.conf', 'worker', 'logger_levels.worker'),
            array('ldap.conf', 'host', 'ldap.host'),
            array('ldap.auth.conf', 'host', 'ldap.auth.host'),
            array('app.conf', 'app.debug', 'app.app.debug'),
        );
    }

    /**
     * @dataProvider providerTestTranslateWithDifferentMasterFile
     */
    public function testTranslateWithDifferentMasterFile($file, $variable, $expected)
    {
        $t = new FilePrefixTranslator();
        $t->changeMasterFile('db.conf');

        $this->assertSame($expected, $t->translate($file, $variable));
    }

    public function providerTestTranslateWithDifferentMasterFile()
    {
        return array(
            // no prefix for master.conf
            array('master.conf', 'burger', 'master.burger'),
            array('master.conf', 'worker.level', 'master.worker.level'),
            array('master.conf', 'app.master.var.pony.master', 'master.app.master.var.pony.master'),
            array('master.conf', 'master', 'master.master'),
            array('master.conf', 'master.master', 'master.master.master'),

            // prefix for other files
            array('db.conf', 'port', 'port'),
            array('db.conf', 'db', 'db'),
            array('logger.conf', 'worker.level', 'logger.worker.level'),
            array('logger.conf', 'worker.file', 'logger.worker.file'),
            array('logger_levels.conf', 'worker', 'logger_levels.worker'),
            array('ldap.conf', 'host', 'ldap.host'),
            array('ldap.auth.conf', 'host', 'ldap.auth.host'),
            array('app.conf', 'app.debug', 'app.app.debug'),
        );
    }

    /**
     * @dataProvider providerTestTranslateWithPrefixForMasterFile
     */
    public function testTranslateWithPrefixForMasterFile($file, $variable, $expected)
    {
        $t = new FilePrefixTranslator();
        $t->setPrefixForMasterFile('pony');

        $this->assertSame($expected, $t->translate($file, $variable));
    }

    public function providerTestTranslateWithPrefixForMasterFile()
    {
        return array(
            // no prefix for master.conf
            array('master.conf', 'burger', 'pony.burger'),
            array('master.conf', 'worker.level', 'pony.worker.level'),
            array('master.conf', 'app.master.var.pony.master', 'pony.app.master.var.pony.master'),
            array('master.conf', 'master', 'pony.master'),
            array('master.conf', 'master.master', 'pony.master.master'),

            // prefix for other files
            array('db.conf', 'port', 'db.port'),
            array('db.conf', 'db', 'db.db'),
            array('logger.conf', 'worker.level', 'logger.worker.level'),
            array('logger.conf', 'worker.file', 'logger.worker.file'),
            array('logger_levels.conf', 'worker', 'logger_levels.worker'),
            array('ldap.conf', 'host', 'ldap.host'),
            array('ldap.auth.conf', 'host', 'ldap.auth.host'),
            array('app.conf', 'app.debug', 'app.app.debug'),
        );
    }
}


text:
.PHONY:	build push

TAG=2.0
REGISTRY?="gcr.io/google_containers"

# Architectures supported: amd64, arm, arm64 and ppc64le
ARCH?=amd64
GOLANG_VERSION=1.6
TEMP_DIR:=$(shell mktemp -d)

all: push-legacy-too

build:
	cp pause.go Dockerfile $(TEMP_DIR)

	docker run -it -v $(TEMP_DIR):/build golang:$(GOLANG_VERSION) /bin/bash -c \
		"cd /build && CGO_ENABLED=0 GOARM=6 GOARCH=$(ARCH) go build -a -installsuffix cgo -ldflags '-w' ./pause.go"

ifeq ($(ARCH),$(filter $(ARCH),amd64 arm))
# Run goupx for amd64 and arm. The condition above is equal to 'if [[ $ARCH == "amd64" || $ARCH == "arm" ]]' in bash
	docker run -it -v $(TEMP_DIR):/build golang:$(GOLANG_VERSION) /bin/bash -c \
		"cd /build && apt-get update && apt-get install -y upx \
		&& go get github.com/pwaller/goupx && goupx pause"
endif

	# And build the image
	docker build -t $(REGISTRY)/pause-$(ARCH):$(TAG) $(TEMP_DIR)

ifeq ($(ARCH),amd64)
	docker tag -f $(REGISTRY)/pause-$(ARCH):$(TAG) $(REGISTRY)/pause:$(TAG)
endif

push: build
	gcloud docker --server=gcr.io push $(REGISTRY)/pause-$(ARCH):$(TAG)

push-legacy-too: push
ifeq ($(ARCH),amd64)
	gcloud docker push $(REGISTRY)/pause:$(TAG)
endif


text:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@id/id_stickynavlayout_innerscrollview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scrollbars="none" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:layout_marginTop="15dp"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        >

        <TextView
            android:id="@+id/strategy_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="20sp"
            />

        <WebView
            android:id="@+id/webview"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            />

    </LinearLayout>
</ScrollView>


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
Copyright (C) 2009 Teleca Poland Sp. z o.o. <android@teleca.com>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical" android:layout_width="fill_parent"
	android:layout_height="fill_parent" android:background="#000000">

	<LinearLayout android:layout_width="fill_parent"
		android:layout_height="wrap_content" android:background="@drawable/gradient_dark_purple"
		android:orientation="horizontal" android:gravity="center"
		android:minHeight="75dip">
		<LinearLayout android:layout_height="wrap_content"
			android:minHeight="75dip" android:layout_width="fill_parent"
			android:orientation="horizontal" android:gravity="center_vertical"
			android:paddingLeft="13dip" android:paddingRight="13dip">
			<ImageView android:layout_width="48dip"
				android:layout_height="48dip" android:src="@drawable/settings"></ImageView>
			<LinearLayout android:layout_height="wrap_content"
				android:paddingLeft="13dip" android:orientation="vertical"
				android:layout_width="fill_parent">
				<TextView android:layout_width="wrap_content"
					android:singleLine="true" android:layout_height="wrap_content"
					android:textSize="18dip" android:textColor="#ffffff" android:text="@string/settings"></TextView>
				<TextView android:layout_width="wrap_content"
					android:layout_height="wrap_content" android:textSize="12dip"
					android:textColor="#ffffff"></TextView>
				<TextView android:id="@+id/ItemsCountTextView"
					android:layout_width="wrap_content" android:layout_height="wrap_content"
					android:layout_gravity="right" android:textSize="12dip"
					android:textColor="#ffffff" android:text=" "></TextView>
			</LinearLayout>
		</LinearLayout>
	</LinearLayout>

	<ListView android:layout_width="fill_parent" android:id="@android:id/list"
		android:layout_weight="1" android:layout_height="fill_parent">
	</ListView>
</LinearLayout>


text:
#include <boost/thread/win32/basic_timed_mutex.hpp>
#include <boost/thread/exceptions.hpp>
#include <boost/thread/locks.hpp>

#include <boost/config/abi_prefix.hpp>

namespace boost
{
    namespace detail
    {
        typedef ::boost::detail::basic_timed_mutex underlying_mutex;
    }

    class mutex:
        public ::boost::detail::underlying_mutex
    {
    public:
        BOOST_THREAD_NO_COPYABLE(mutex)
        mutex()
        {
            initialize();
        }
        ~mutex()
        {
            destroy();
        }

        typedef unique_lock<mutex> scoped_lock;
        typedef detail::try_lock_wrapper<mutex> scoped_try_lock;
    };

    typedef mutex try_mutex;

    class timed_mutex:
        public ::boost::detail::basic_timed_mutex
    {
    public:
        BOOST_THREAD_NO_COPYABLE(timed_mutex)
        timed_mutex()
        {
            initialize();
        }

        ~timed_mutex()
        {
            destroy();
        }

        typedef unique_lock<timed_mutex> scoped_timed_lock;
        typedef detail::try_lock_wrapper<timed_mutex> scoped_try_lock;
        typedef scoped_timed_lock scoped_lock;
    };
}

#include <boost/config/abi_suffix.hpp>

#endif


text:
MyPlugin::MyPlugin(float inputSampleRate) :
    Plugin(inputSampleRate)
    // Also be sure to set your plugin parameters (presumably stored
    // in member variables) to their default values here -- the host
    // will not do that for you
{
}

MyPlugin::~MyPlugin()
{
}

string
MyPlugin::getIdentifier() const
{
    return "myplugin";
}

string
MyPlugin::getName() const
{
    return "My Plugin";
}

string
MyPlugin::getDescription() const
{
    // Return something helpful here!
    return "";
}

string
MyPlugin::getMaker() const
{
    // Your name here
    return "";
}

int
MyPlugin::getPluginVersion() const
{
    // Increment this each time you release a version that behaves
    // differently from the previous one
    return 1;
}

string
MyPlugin::getCopyright() const
{
    // This function is not ideally named.  It does not necessarily
    // need to say who made the plugin -- getMaker does that -- but it
    // should indicate the terms under which it is distributed.  For
    // example, "Copyright (year). All Rights Reserved", or "GPL"
    return "";
}

MyPlugin::InputDomain
MyPlugin::getInputDomain() const
{
    return TimeDomain;
}

size_t
MyPlugin::getPreferredBlockSize() const
{
    return 0; // 0 means "I can handle any block size"
}

size_t
MyPlugin::getPreferredStepSize() const
{
    return 0; // 0 means "anything sensible"; in practice this
              // means the same as the block size for TimeDomain
              // plugins, or half of it for FrequencyDomain plugins
}

size_t
MyPlugin::getMinChannelCount() const
{
    return 1;
}

size_t
MyPlugin::getMaxChannelCount() const
{
    return 1;
}

MyPlugin::ParameterList
MyPlugin::getParameterDescriptors() const
{
    ParameterList list;

    // If the plugin has no adjustable parameters, return an empty
    // list here (and there's no need to provide implementations of
    // getParameter and setParameter in that case either).

    // Note that it is your responsibility to make sure the parameters
    // start off having their default values (e.g. in the constructor
    // above).  The host needs to know the default value so it can do
    // things like provide a "reset to default" function, but it will
    // not explicitly set your parameters to their defaults for you if
    // they have not changed in the mean time.

    ParameterDescriptor d;
    d.identifier = "parameter";
    d.name = "Some Parameter";
    d.description = "";
    d.unit = "";
    d.minValue = 0;
    d.maxValue = 10;
    d.defaultValue = 5;
    d.isQuantized = false;
    list.push_back(d);

    return list;
}

float
MyPlugin::getParameter(string identifier) const
{
    if (identifier == "parameter") {
        return 5; // return the ACTUAL current value of your parameter here!
    }
    return 0;
}

void
MyPlugin::setParameter(string identifier, float value)
{
    if (identifier == "parameter") {
        // set the actual value of your parameter
    }
}

MyPlugin::ProgramList
MyPlugin::getPrograms() const
{
    ProgramList list;

    // If you have no programs, return an empty list (or simply don't
    // implement this function or getCurrentProgram/selectProgram)

    return list;
}

string
MyPlugin::getCurrentProgram() const
{
    return ""; // no programs
}

void
MyPlugin::selectProgram(string name)
{
}

MyPlugin::OutputList
MyPlugin::getOutputDescriptors() const
{
    OutputList list;

    // See OutputDescriptor documentation for the possibilities here.
    // Every plugin must have at least one output.

    OutputDescriptor d;
    d.identifier = "output";
    d.name = "My Output";
    d.description = "";
    d.unit = "";
    d.hasFixedBinCount = true;
    d.binCount = 1;
    d.hasKnownExtents = false;
    d.isQuantized = false;
    d.sampleType = OutputDescriptor::OneSamplePerStep;
    d.hasDuration = false;
    list.push_back(d);

    return list;
}

bool
MyPlugin::initialise(size_t channels, size_t stepSize, size_t blockSize)
{
    if (channels < getMinChannelCount() ||
	channels > getMaxChannelCount()) return false;

    // Real initialisation work goes here!

    return true;
}

void
MyPlugin::reset()
{
    // Clear buffers, reset stored values, etc
}

MyPlugin::FeatureSet
MyPlugin::process(const float *const *inputBuffers, Vamp::RealTime timestamp)
{
    // Do actual work!
    return FeatureSet();
}

MyPlugin::FeatureSet
MyPlugin::getRemainingFeatures()
{
    return FeatureSet();
}


text:
<!DOCTYPE html>

  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"/>
  <title>SuccessWhale Configuration</title>
  <link rel="stylesheet" href="/css/normalize.css"/>
  <link rel="stylesheet" href="/css/style.css"/>
  <link rel="stylesheet" href="/css/font-awesome.min.css">
  <link rel="stylesheet" data-bind="attr: { href: '/css/themes/'+theme()+'.css' }"/>
  <link rel="icon" href="/img/favicon.ico" type="image/x-icon"/>
  <link rel="shortcut icon" href="/img/favicon.ico" type="image/x-icon"/>

       Back

Configuration

Accounts

        <form>

Service Accounts

                Post to: <input type="checkbox" data-bind="attr: { name: (service + '/' + uid) }, checked: enabled"/>

 Add Twitter   Add Facebook

 Save

        </form>

        <form>

Alternative Login

Creating an alternative login will

            allow you to use SuccessWhale from

            networks that block Twitter and

            Facebook. To set one up, enter a

            username and password below.

Username: 	<input id="altloginusername" data-bind="value: altLoginUsername" />

Password: 	<input id="altloginpassword" type="password" data-bind="value: altLoginPassword" />

 Save

        </form>

        <form>

Delete All Data

If you want to leave SuccessWhale

             permanently, click the link below.

             All your settings and the details

             of all your service accounts will

             be deleted.

 Delete All Data

        </form>

Appearance

        <form>

Theme: <select data-bind="value: theme, options: availableThemes"></select>

Columns per screen: <input data-bind="value: colsPerScreen" size="4" />

<input type="checkbox" data-bind="checked: inlineMedia"/> Show inline media

Highlight new items for <input data-bind="value: highlightTime" size="4" /> minutes
(0 = no highlighting)

 Save

        </form>

        <form>

Banned Phrases

Items containing the following phrases
will not be displayed. (One per line)
Advanced users can specify regexes
between / characters, e.g. /\d*/.

          <textarea cols="30" rows="5" id="bannedphrases" data-bind="value: bannedPhrases"></textarea>

 Save

        </form>

Columns

        <form>

                    All sources:

                    <select size="5" data-bind="options: $parent.sources, optionsText: 'fullname', value: selectedNewSource">
                    </select>

                    Included in this column:

                    <select size="5" data-bind="options: sources, optionsText: 'fullname', value: selectedExistingSource">
                    </select>

 Add Column  Save

        </form>


text:
from unittest import TestCase
from Triangle import Triangle

class TestTriangle2(TestCase):
    def test_Triangle(self):
        self.assertEqual(Triangle(4, 8), 16)
        self.assertEqual(Triangle(6, 2), 6)
        self.assertEqual(Triangle(2, 4), 4)
        self.fail()

if __name__ == '__main__':
    unittest.main()


text:
This is a standard for writing ES6 JavaScript based on eslint configurations. This document goes through an entire eslint configuration object and explains why the configurations are set as they are and how to comply with them. This document can be used as a general guideline for writing well-formed and well-reasoned ES6 compliant JavaScript, or as a learning tool for adapting your own eslint configurations. You can view and study the actual [.eslintrc](.eslintrc.json) file or copy it into your existing repository. This uses the babel-eslint package which you can install into your project via the command line:

```
$ npm install eslint@1.x babel-eslint@5 --save-dev

$ npm install eslint@2.x babel-eslint@6 --save-dev
```
and then run the parser with:
```
$ eslint <dir|filepath>
```

You can learn more about ESLint at [http://eslint.org/](http://eslint.org/). There you will find a complete list of all available rules. You can visit the main rules page at [http://eslint.org/docs/rules/](http://eslint.org/docs/rules/).

ESLint has three settings for each rule: "off", "warn", and "error". The rules, as set in forth in the [.eslintrc](.eslintrc.json) file, represent best practices for writing ES6 compliant JavaScript, and as such the rules that are enabled are generally set to throw errors to indicate that problems must be addressed before merging code. There are situations where we must bend these rules slightly, such as the maximum length of a line of code, or having a `TODO` comment. In these situations, these rules have been set to "warn". This should still allow code integration, but provides a reminder for places in the codebase that should be revisited and revised.

Rules can be disabled inline in the event that there is no feasible way to write your code and comply with the ESLint settings. See [here](http://eslint.org/docs/user-guide/configuring#disabling-rules-with-inline-comments) for details.

## Table of Contents
###  In Like Lint
 - [Possible Errors](eslint/errors.md#top)
 - [Best Practices](eslint/best-practices.md#top)
 - [Strict Mode](eslint/strict.md#top)
 - [Variables](eslint/variables.md#top)
 - [Stylistic Issues](eslint/stylistic.md#top)
 - [ECMAScript 6](eslint/es6.md#top)

### By Subject
 -  [Variables](variables/#top)
 -  [Functions](functions/#top)
 -  [Arrays](arrays/#top)
 -  [Objects & Classes](objects/#top)
 -  [Private Properties](private-properties/)
 -  [Native](native/#top)
 -  [Type Casting & Coercion](types/#top)
 -  [Numbers](numbers/#top)
 -  [Strings](#strings)
 -  [Regular Expressions](regexp/#top)
 -  [Operators](operators/#top)
 -  [Syntax](syntax/#top)
 -  [Structure](structure/#top)
 -  [Loops](loops/#top)
 -  [Try-Catch](try-catch/#top)
 -  [Conditionals](conditionals/#top)
 -  [Blocks](blocks/#top)
 -  [Evaluating](evaluating/#top)
 -  [Whitespace](whitespace/#top)
 -  [Comments](comments/#top)
 -  [ES6](es6/#top)

### By Rule
 - [accessor-pairs](objects/#accessor-pairs)
 - [array-bracket-spacing](arrays/#array-bracket-spacing)
 - [array-callback-return](arrays/#array-callback-return)
 - [arrow-body-style](es6/#arrow-body-style)
 - [arrow-parens](es6/#arrow-parens)
 - [arrow-spacing](es6/#arrow-spacing)
 - [block-scoped-var](blocks/#block-scoped-var)
 - [block-spacing](whitespace/#block-spacing)
 - [brace-style](blocks/#brace-style)
 - [camelcase](variables/#camelcase)
 - [comma-dangle](syntax/#comma-dangle)
 - [comma-spacing](syntax/#comma-spacing)
 - [comma-style](syntax/#comma-style)
 - [complexity](structure/#complexity)
 - [computed-property-spacing](objects/#computed-property-spacing)
 - [consistent-return](structure/#consistent-return)
 - [consistent-this](variables/#consistent-this)
 - [constructor-super](es6/#constructor-super)
 - [curly](blocks/#curly)
 - [default-case](conditionals/#default-case)
 - [dot-location](objects/#dot-location)
 - [dot-notation](objects/#dot-notation)
 - [eol-last](whitespace/#eol-last)
 - [eqeqeq](operators/#eqeqeq)
 - [func-names](functions/#func-names)
 - [func-style](functions/#func-style)
 - [generator-star-spacing](es6/#generator-star-spacing)
 - [guard-for-in](loops/#guard-for-in)
 - [id-blacklist](variables/#id-blacklist)
 - [id-length](variables/#id-length)
 - [id-match](variables/#id-match)
 - [indent](whitespace/#indent)
 - [init-declarations](variables/#init-declarations)
 - [jsx-quotes](syntax/#jsx-quotes)
 - [key-spacing](objects/#key-spacing)
 - [keyword-spacing](whitespace/#keyword-spacing)
 - [linebreak-style](whitespace/#linebreak-style)
 - [lines-around-comment](whitespace/#lines-around-comment)
 - [max-depth](structure/#max-depth)
 - [max-len](structure/#max-len)
 - [max-nested-callbacks](structure/#max-nested-callbacks)
 - [max-params](functions/#max-params)
 - [max-statements-per-line](structure/#max-statements-per-line)
 - [max-statements](structure/#max-statements)
 - [new-cap](objects/#new-cap)
 - [new-parens](objects/#new-parens)
 - [newline-after-var](whitespace/#newline-after-var)
 - [newline-before-return](whitespace/#newline-before-return)
 - [newline-per-chained-call](objects/#newline-per-chained-call)
 - [no-alert](native/#no-alert)
 - [no-array-constructor](arrays/#no-array-constructor)
 - [no-bitwise](operators/#no-bitwise)
 - [no-caller](functions/#no-caller)
 - [no-case-declarations](conditionals/#no-case-declarations)
 - [no-catch-shadow](try-catch/#no-catch-shadow)
 - [no-class-assign](es6/#no-class-assign)
 - [no-cond-assign](conditionals/#no-cond-assign)
 - [no-confusing-arrow](es6/#no-confusing-arrow)
 - [no-console](native/#no-console)
 - [no-const-assign](es6/#no-const-assign)
 - [no-constant-condition](conditionals/#no-constant-condition)
 - [no-continue](native/#no-continue)
 - [no-control-regex](regexp/#no-control-regex)
 - [no-debugger](native/#no-debugger)
 - [no-delete-var](native/#no-delete-var)
 - [no-div-regex](regexp/#no-div-regex)
 - [no-dupe-args](functions/#no-dupe-args)
 - [no-dupe-class-members](es6/#no-dupe-class-members)
 - [no-dupe-keys](objects/#no-dupe-keys)
 - [no-duplicate-case](conditionals/#no-duplicate-case)
 - [no-duplicate-imports](es6/#no-duplicate-imports)
 - [no-else-return](conditionals/#no-else-return)
 - [no-empty-character-class](regexp/#no-empty-character-class)
 - [no-empty-function](functions/#no-empty-function)
 - [no-empty-pattern](variables/#no-empty-pattern)
 - [no-empty](blocks/#no-empty)
 - [no-eq-null](conditionals/#no-eq-null)
 - [no-eval](evaluating/#no-eval)
 - [no-ex-assign](try-catch/#no-ex-assign)
 - [no-extend-native](native/#no-extend-native)
 - [no-extra-bind](functions/#no-extra-bind)
 - [no-extra-boolean-cast](types/#no-extra-boolean-cast)
 - [no-extra-label](blocks/#no-extra-label)
 - [no-extra-parens](syntax/#no-extra-parens)
 - [no-extra-semi](syntax/#no-extra-semi)
 - [no-fallthrough](conditionals/#no-fallthrough)
 - [no-floating-decimal](numbers/#no-floating-decimal)
 - [no-func-assign](functions/#no-func-assign)
 - [no-implicit-coercion](types/#no-implicit-coercion)
 - [no-implicit-globals](variables/#no-implicit-globals)
 - [no-implied-eval](evaluating/#no-implied-eval)
 - [no-inline-comments](comments/#no-inline-comments)
 - [no-inner-declarations](blocks/#no-inner-declarations)
 - [no-invalid-regexp](regexp/#no-invalid-regexp)
 - [no-invalid-this](objects/#no-invalid-this)
 - [no-irregular-whitespace](whitespace/#no-irregular-whitespace)
 - [no-iterator](native/#no-iterator)
 - [no-label-var](variables/#no-label-var)
 - [no-labels](blocks/#no-labels)
 - [no-lone-blocks](blocks/#no-lone-blocks)
 - [no-lonely-if](conditionals/#no-lonely-if)
 - [no-loop-func](functions/#no-loop-func)
 - [no-magic-numbers](numbers/#no-magic-numbers)
 - [no-mixed-spaces-and-tabs](whitespace/#no-mixed-spaces-and-tabs)
 - [no-multi-spaces](whitespace/#no-multi-spaces)
 - [no-multi-str](strings/#no-multi-str)
 - [no-multiple-empty-lines](whitespace/#no-multiple-empty-lines)
 - [no-native-reassign](native/#no-native-reassign)
 - [no-negated-condition](conditionals/#no-negated-condition)
 - [no-negated-in-lhs](loops/#no-negated-in-lhs)
 - [no-nested-ternary](conditionals/#no-nested-ternary)
 - [no-new-func](evaluating/#no-new-func)
 - [no-new-object](objects/#no-new-object)
 - [no-new-symbol](es6/#no-new-symbol)
 - [no-new-wrappers](native/#no-new-wrappers)
 - [no-new](objects/#no-new)
 - [no-obj-calls](native/#no-obj-calls)
 - [no-octal-escape](strings/#no-octal-escape)
 - [no-octal](numbers/#no-octal)
 - [no-param-reassign](functions/#no-param-reassign)
 - [no-plusplus](operators/#no-plusplus)
 - [no-proto](objects/#no-proto)
 - [no-redeclare](variables/#no-redeclare)
 - [no-regex-spaces](regexp/#no-regex-spaces)
 - [no-restricted-globals](variables/#no-restricted-globals)
 - [no-restricted-imports](es6/#no-restricted-imports)
 - [no-restricted-syntax](syntax/#no-restricted-syntax)
 - [no-return-assign](structure/#no-return-assign)
 - [no-script-url](evaluating/#no-script-url)
 - [no-self-assign](variables/#no-self-assign)
 - [no-self-compare](conditionals/#no-self-compare)
 - [no-sequences](syntax/#no-sequences)
 - [no-shadow-restricted-names](variables/#no-shadow-restricted-names)
 - [no-shadow](variables/#no-shadow)
 - [no-spaced-func](functions/#no-spaced-func)
 - [no-sparse-arrays](arrays/#no-sparse-arrays)
 - [no-ternary](conditionals/#no-ternary)
 - [no-this-before-super](es6/#no-this-before-super)
 - [no-throw-literal](try-catch/#no-throw-literal)
 - [no-trailing-spaces](whitespace/#no-trailing-spaces)
 - [no-undef-init](variables/#no-undef-init)
 - [no-undef](variables/#no-undef)
 - [no-undefined](variables/#no-undefined)
 - [no-underscore-dangle](variables/#no-underscore-dangle)
 - [no-unexpected-multiline](whitespace/#no-unexpected-multiline)
 - [no-unmodified-loop-condition](loops/#no-unmodified-loop-condition)
 - [no-unneeded-ternary](conditionals/#no-unneeded-ternary)
 - [no-unreachable](structure/#no-unreachable)
 - [no-unsafe-finally](try-catch/#no-unsafe-finally)
 - [no-unused-expressions](structure/#no-unused-expressions)
 - [no-unused-labels](blocks/#no-unused-labels)
 - [no-unused-vars](variables/#no-unused-vars)
 - [no-use-before-define](variables/#no-use-before-define)
 - [no-useless-call](functions/#no-useless-call)
 - [no-useless-computed-key](es6/#no-useless-computed-key)
 - [no-useless-concat](strings/#no-useless-concat)
 - [no-useless-constructor](es6/#no-useless-constructor)
 - [no-useless-escape](strings/#no-useless-escape)
 - [no-var](es6/#no-var)
 - [no-void](native/#no-void)
 - [no-warning-comments](comments/#no-warning-comments)
 - [no-whitespace-before-property](objects/#no-whitespace-before-property)
 - [no-with](native/#no-with)
 - [object-curly-spacing](objects/#object-curly-spacing)
 - [object-shorthand](es6/#object-shorthand)
 - [one-var-declaration-per-line](variables/#one-var-declaration-per-line)
 - [one-var](variables/#one-var)
 - [operator-assignment](operators/#operator-assignment)
 - [operator-linebreak](operators/#operator-linebreak)
 - [padded-blocks](blocks/#padded-blocks)
 - [prefer-arrow-callback](es6/#prefer-arrow-callback)
 - [prefer-const](es6/#prefer-const)
 - [prefer-reflect](es6/#prefer-reflect)
 - [prefer-rest-params](es6/#prefer-rest-params)
 - [prefer-spread](es6/#prefer-spread)
 - [prefer-template](es6/#prefer-template)
 - [quote-props](objects/#quote-props)
 - [quotes](strings/#quotes)
 - [radix](numbers/#radix)
 - [require-jsdoc](comments/#require-jsdoc)
 - [require-yield](es6/#require-yield)
 - [semi-spacing](syntax/#semi-spacing)
 - [semi](syntax/#semi)
 - [sort-imports](es6/#sort-imports)
 - [sort-vars](variables/#sort-vars)
 - [space-before-blocks](whitespace/#space-before-blocks)
 - [space-before-function-paren](functions/#space-before-function-paren)
 - [space-in-parens](whitespace/#space-in-parens)
 - [space-infix-ops](operators/#space-infix-ops)
 - [space-unary-ops](operators/#space-unary-ops)
 - [spaced-comment](comments/#spaced-comment)
 - [strict](structure/#strict)
 - [template-curly-spacing](es6/#template-curly-spacing)
 - [use-isnan](native/#use-isnan)
 - [valid-jsdoc](comments/#valid-jsdoc)
 - [valid-typeof](native/#valid-typeof)
 - [vars-on-top](variables/#vars-on-top)
 - [wrap-iife](functions/#wrap-iife)
 - [wrap-regex](regexp/#wrap-regex)
 - [yield-star-spacing](es6/#yield-star-spacing)
 - [yoda](conditionals/#yoda)