text:
package main

import (
	"fmt"
	"reflect"
	"strings"
	"time"

	"k8s.io/contrib/cluster-autoscaler/cloudprovider"
	"k8s.io/contrib/cluster-autoscaler/clusterstate"
	"k8s.io/contrib/cluster-autoscaler/simulator"
	"k8s.io/contrib/cluster-autoscaler/utils/deletetaint"
	kube_util "k8s.io/contrib/cluster-autoscaler/utils/kubernetes"

	"k8s.io/kubernetes/pkg/api/errors"
	apiv1 "k8s.io/kubernetes/pkg/api/v1"
	kube_client "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5"
	kube_record "k8s.io/kubernetes/pkg/client/record"
	"k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache"

	"github.com/golang/glog"
)

// ScaleDownResult represents the state of scale down.
type ScaleDownResult int

const (
	// ScaleDownError - scale down finished with error.
	ScaleDownError ScaleDownResult = iota
	// ScaleDownNoUnneeded - no unneeded nodes and no errors.
	ScaleDownNoUnneeded ScaleDownResult = iota
	// ScaleDownNoNodeDeleted - unneeded nodes present but not available for deletion.
	ScaleDownNoNodeDeleted ScaleDownResult = iota
	// ScaleDownNodeDeleted - a node was deleted.
	ScaleDownNodeDeleted ScaleDownResult = iota
)

const (
	// MaxKubernetesEmptyNodeDeletionTime is the maximum time needed by Kubernetes to delete an empty node.
	MaxKubernetesEmptyNodeDeletionTime = 3 * time.Minute
	// MaxCloudProviderNodeDeletionTime is the maximum time needed by cloud provider to delete a node.
	MaxCloudProviderNodeDeletionTime = 5 * time.Minute
)

// ScaleDown is responsible for maintaining the state needed to perform unneded node removals.
type ScaleDown struct {
	context            *AutoscalingContext
	unneededNodes      map[string]time.Time
	podLocationHints   map[string]string
	nodeUtilizationMap map[string]float64
	usageTracker       *simulator.UsageTracker
}

// NewScaleDown builds new ScaleDown object.
func NewScaleDown(context *AutoscalingContext) *ScaleDown {
	return &ScaleDown{
		context:            context,
		unneededNodes:      make(map[string]time.Time),
		podLocationHints:   make(map[string]string),
		nodeUtilizationMap: make(map[string]float64),
		usageTracker:       simulator.NewUsageTracker(),
	}
}

// CleanUp cleans up the internal ScaleDown state.
func (sd *ScaleDown) CleanUp(timestamp time.Time) {
	sd.usageTracker.CleanUp(time.Now().Add(-(sd.context.ScaleDownUnneededTime)))
}

// UpdateUnneededNodes calculates which nodes are not needed, i.e. all pods can be scheduled somewhere else,
// and updates unneededNodes map accordingly. It also computes information where pods can be rescheduled and
// node utilization level. Timestamp is the current timestamp.
func (sd *ScaleDown) UpdateUnneededNodes(
	nodes []*apiv1.Node,
	pods []*apiv1.Pod,
	timestamp time.Time) error {

	currentlyUnneededNodes := make([]*apiv1.Node, 0)
	nodeNameToNodeInfo := schedulercache.CreateNodeNameToInfoMap(pods, nodes)
	utilizationMap := make(map[string]float64)

	// Phase1 - look at the nodes utilization.
	for _, node := range nodes {
		nodeInfo, found := nodeNameToNodeInfo[node.Name]
		if !found {
			glog.Errorf("Node info for %s not found", node.Name)
			continue
		}
		utilization, err := simulator.CalculateUtilization(node, nodeInfo)

		if err != nil {
			glog.Warningf("Failed to calculate utilization for %s: %v", node.Name, err)
		}
		glog.V(4).Infof("Node %s - utilization %f", node.Name, utilization)
		utilizationMap[node.Name] = utilization

		if utilization >= sd.context.ScaleDownUtilizationThreshold {
			glog.V(4).Infof("Node %s is not suitable for removal - utilization too big (%f)", node.Name, utilization)
			continue
		}
		currentlyUnneededNodes = append(currentlyUnneededNodes, node)
	}

	// Phase2 - check which nodes can be probably removed using fast drain.
	nodesToRemove, newHints, err := simulator.FindNodesToRemove(currentlyUnneededNodes, nodes, pods,
		nil, sd.context.PredicateChecker,
		len(currentlyUnneededNodes), true, sd.podLocationHints, sd.usageTracker, timestamp)
	if err != nil {
		glog.Errorf("Error while simulating node drains: %v", err)
		return fmt.Errorf("error while simulating node drains: %v", err)
	}

	// Update the timestamp map.
	result := make(map[string]time.Time)
	for _, node := range nodesToRemove {
		name := node.Node.Name
		if val, found := sd.unneededNodes[name]; !found {
			result[name] = timestamp
		} else {
			result[name] = val
		}
	}

	sd.unneededNodes = result
	sd.podLocationHints = newHints
	sd.nodeUtilizationMap = utilizationMap
	return nil
}

// TryToScaleDown tries to scale down the cluster. It returns ScaleDownResult indicating if any node was
// removed and error if such occured.
func (sd *ScaleDown) TryToScaleDown(nodes []*apiv1.Node, pods []*apiv1.Pod) (ScaleDownResult, error) {

	now := time.Now()
	candidates := make([]*apiv1.Node, 0)
	for _, node := range nodes {
		if val, found := sd.unneededNodes[node.Name]; found {

			glog.V(2).Infof("%s was unneeded for %s", node.Name, now.Sub(val).String())

			ready, _, _ := kube_util.GetReadinessState(node)

			// Check how long the node was underutilized.
			if ready && !val.Add(sd.context.ScaleDownUnneededTime).Before(now) {
				continue
			}

			// Unready nodes may be deleted after a different time than unrerutilized.
			if !ready && !val.Add(sd.context.ScaleDownUnreadyTime).Before(now) {
				continue
			}

			nodeGroup, err := sd.context.CloudProvider.NodeGroupForNode(node)
			if err != nil {
				glog.Errorf("Error while checking node group for %s: %v", node.Name, err)
				continue
			}
			if nodeGroup == nil || reflect.ValueOf(nodeGroup).IsNil() {
				glog.V(4).Infof("Skipping %s - no node group config", node.Name)
				continue
			}

			size, err := nodeGroup.TargetSize()
			if err != nil {
				glog.Errorf("Error while checking node group size %s: %v", nodeGroup.Id(), err)
				continue
			}

			if size <= nodeGroup.MinSize() {
				glog.V(1).Infof("Skipping %s - node group min size reached", node.Name)
				continue
			}

			candidates = append(candidates, node)
		}
	}
	if len(candidates) == 0 {
		glog.Infof("No candidates for scale down")
		return ScaleDownNoUnneeded, nil
	}

	// Trying to delete empty nodes in bulk. If there are no empty nodes then CA will
	// try to delete not-so-empty nodes, possibly killing some pods and allowing them
	// to recreate on other nodes.
	emptyNodes := getEmptyNodes(candidates, pods, sd.context.MaxEmptyBulkDelete, sd.context.CloudProvider)
	if len(emptyNodes) > 0 {
		confirmation := make(chan error, len(emptyNodes))
		for _, node := range emptyNodes {
			glog.V(0).Infof("Scale-down: removing empty node %s", node.Name)
			simulator.RemoveNodeFromTracker(sd.usageTracker, node.Name, sd.unneededNodes)
			go func(nodeToDelete *apiv1.Node) {
				confirmation <- deleteNodeFromCloudProvider(nodeToDelete, sd.context.CloudProvider,
					sd.context.Recorder, sd.context.ClusterStateRegistry)
			}(node)
		}
		var finalError error

		startTime := time.Now()
		for range emptyNodes {
			timeElapsed := time.Now().Sub(startTime)
			timeLeft := MaxCloudProviderNodeDeletionTime - timeElapsed
			if timeLeft < 0 {
				finalError = fmt.Errorf("Failed to delete nodes in time")
				break
			}
			select {
			case err := <-confirmation:
				if err != nil {
					glog.Errorf("Problem with empty node deletion: %v", err)
					finalError = err
				}
			case <-time.After(timeLeft):
				finalError = fmt.Errorf("Failed to delete nodes in time")
			}
		}
		if finalError == nil {
			return ScaleDownNodeDeleted, nil
		}
		return ScaleDownError, fmt.Errorf("failed to delete at least one empty node: %v", finalError)
	}

	// We look for only 1 node so new hints may be incomplete.
	nodesToRemove, _, err := simulator.FindNodesToRemove(candidates, nodes, pods, sd.context.ClientSet,
		sd.context.PredicateChecker, 1, false,
		sd.podLocationHints, sd.usageTracker, time.Now())

	if err != nil {
		return ScaleDownError, fmt.Errorf("Find node to remove failed: %v", err)
	}
	if len(nodesToRemove) == 0 {
		glog.V(1).Infof("No node to remove")
		return ScaleDownNoNodeDeleted, nil
	}
	toRemove := nodesToRemove[0]
	utilization := sd.nodeUtilizationMap[toRemove.Node.Name]
	podNames := make([]string, 0, len(toRemove.PodsToReschedule))
	for _, pod := range toRemove.PodsToReschedule {
		podNames = append(podNames, pod.Namespace+"/"+pod.Name)
	}
	glog.V(0).Infof("Scale-down: removing node %s, utilization: %v, pods to reschedule: %s", toRemove.Node.Name, utilization,
		strings.Join(podNames, ","))

	// Nothing super-bad should happen if the node is removed from tracker prematurely.
	simulator.RemoveNodeFromTracker(sd.usageTracker, toRemove.Node.Name, sd.unneededNodes)
	err = deleteNode(sd.context, toRemove.Node, toRemove.PodsToReschedule)
	if err != nil {
		return ScaleDownError, fmt.Errorf("Failed to delete %s: %v", toRemove.Node.Name, err)
	}

	return ScaleDownNodeDeleted, nil
}

// This functions finds empty nodes among passed candidates and returns a list of empty nodes
// that can be deleted at the same time.
func getEmptyNodes(candidates []*apiv1.Node, pods []*apiv1.Pod, maxEmptyBulkDelete int, cloudProvider cloudprovider.CloudProvider) []*apiv1.Node {
	emptyNodes := simulator.FindEmptyNodesToRemove(candidates, pods)
	availabilityMap := make(map[string]int)
	result := make([]*apiv1.Node, 0)
	for _, node := range emptyNodes {
		nodeGroup, err := cloudProvider.NodeGroupForNode(node)
		if err != nil {
			glog.Errorf("Failed to get group for %s", node.Name)
			continue
		}
		if nodeGroup == nil || reflect.ValueOf(nodeGroup).IsNil() {
			continue
		}
		var available int
		var found bool
		if _, found = availabilityMap[nodeGroup.Id()]; !found {
			size, err := nodeGroup.TargetSize()
			if err != nil {
				glog.Errorf("Failed to get size for %s: %v ", nodeGroup.Id(), err)
				continue
			}
			available = size - nodeGroup.MinSize()
			if available < 0 {
				available = 0
			}
			availabilityMap[nodeGroup.Id()] = available
		}
		if available > 0 {
			available -= 1
			availabilityMap[nodeGroup.Id()] = available
			result = append(result, node)
		}
	}
	limit := maxEmptyBulkDelete
	if len(result) < limit {
		limit = len(result)
	}
	return result[:limit]
}

func deleteNode(context *AutoscalingContext, node *apiv1.Node, pods []*apiv1.Pod) error {
	if err := drainNode(node, pods, context.ClientSet, context.Recorder, context.MaxGratefulTerminationSec); err != nil {
		return err
	}
	return deleteNodeFromCloudProvider(node, context.CloudProvider, context.Recorder, context.ClusterStateRegistry)
}

// Performs drain logic on the node. Marks the node as unschedulable and later removes all pods, giving
// them up to MaxGracefulTerminationTime to finish.
func drainNode(node *apiv1.Node, pods []*apiv1.Pod, client kube_client.Interface, recorder kube_record.EventRecorder,
	maxGratefulTerminationSec int) error {
	if err := deletetaint.MarkToBeDeleted(node, client); err != nil {
		recorder.Eventf(node, apiv1.EventTypeWarning, "ScaleDown", "failed to mark the node as toBeDeleted/unschedulable: %v", err)
		return err
	}
	recorder.Eventf(node, apiv1.EventTypeNormal, "ScaleDown", "marked the node as toBeDeleted/unschedulable")

	maxGraceful64 := int64(maxGratefulTerminationSec)
	for _, pod := range pods {
		recorder.Eventf(pod, apiv1.EventTypeNormal, "ScaleDown", "deleting pod for node scale down")
		err := client.Core().Pods(pod.Namespace).Delete(pod.Name, &apiv1.DeleteOptions{
			GracePeriodSeconds: &maxGraceful64,
		})
		if err != nil {
			glog.Errorf("Failed to delete %s/%s: %v", pod.Namespace, pod.Name, err)
		}
	}
	allGone := true

	// Wait up to MaxGracefulTerminationTime.
	for start := time.Now(); time.Now().Sub(start) < time.Duration(maxGratefulTerminationSec)*time.Second; time.Sleep(5 * time.Second) {
		allGone = true
		for _, pod := range pods {
			podreturned, err := client.Core().Pods(pod.Namespace).Get(pod.Name)
			if err == nil {
				glog.Errorf("Not deleted yet %v", podreturned)
				allGone = false
				break
			}
			if !errors.IsNotFound(err) {
				glog.Errorf("Failed to check pod %s/%s: %v", pod.Namespace, pod.Name, err)
				allGone = false
			}
		}
		if allGone {
			glog.V(1).Infof("All pods removed from %s", node.Name)
			break
		}
	}
	if !allGone {
		glog.Warningf("Not all pods were removed from %s, proceeding anyway", node.Name)
	}
	return nil
}

// cleanToBeDeleted cleans ToBeDeleted taints.
func cleanToBeDeleted(nodes []*apiv1.Node, client kube_client.Interface, recorder kube_record.EventRecorder) {
	for _, node := range nodes {
		cleaned, err := deletetaint.CleanToBeDeleted(node, client)
		if err != nil {
			glog.Warningf("Error while releasing taints on node %v: %v", node.Name, err)
			recorder.Eventf(node, apiv1.EventTypeWarning, "ClusterAutoscalerCleanup",
				"failed to clean toBeDeletedTaint: %v", err)
		} else if cleaned {
			glog.V(1).Infof("Successfully released toBeDeletedTaint on node %v", node.Name)
			recorder.Eventf(node, apiv1.EventTypeNormal, "ClusterAutoscalerCleanup", "marking the node as schedulable")
		}
	}
}

// Removes the given node from cloud provider. No extra pre-deletion actions are executed on
// the Kubernetes side.
func deleteNodeFromCloudProvider(node *apiv1.Node, cloudProvider cloudprovider.CloudProvider,
	recorder kube_record.EventRecorder, registry *clusterstate.ClusterStateRegistry) error {
	nodeGroup, err := cloudProvider.NodeGroupForNode(node)
	if err != nil {
		return fmt.Errorf("failed to node group for %s: %v", node.Name, err)
	}
	if nodeGroup == nil || reflect.ValueOf(nodeGroup).IsNil() {
		return fmt.Errorf("picked node that doesn't belong to a node group: %s", node.Name)
	}
	if err = nodeGroup.DeleteNodes([]*apiv1.Node{node}); err != nil {
		return fmt.Errorf("failed to delete %s: %v", node.Name, err)
	}
	recorder.Eventf(node, apiv1.EventTypeNormal, "ScaleDown", "node removed by cluster autoscaler")
	registry.RegisterScaleDown(&clusterstate.ScaleDownRequest{
		NodeGroupName:      nodeGroup.Id(),
		NodeName:           node.Name,
		Time:               time.Now(),
		ExpectedDeleteTime: time.Now().Add(MaxCloudProviderNodeDeletionTime),
	})
	return nil
}


text:
from __future__ import unicode_literals

import frappe
import frappe.translate
import frappe.modules.patch_handler
import frappe.model.sync
from frappe.utils.fixtures import sync_fixtures
from frappe.sessions import clear_global_cache
from frappe.desk.notifications import clear_notifications
from frappe.website import render
from frappe.desk.doctype.desktop_icon.desktop_icon import sync_desktop_icons

def migrate(verbose=True, rebuild_website=False):
	'''Migrate all apps to the latest version, will:

	- run patches
	- sync doctypes (schema)
	- sync fixtures
	- sync desktop icons
	- sync web pages (from /www)'''
	clear_global_cache()

	# run patches
	frappe.modules.patch_handler.run_all()
	# sync
	frappe.model.sync.sync_all(verbose=verbose)
	frappe.translate.clear_cache()
	sync_fixtures()
	sync_desktop_icons()
	frappe.get_doc('Portal Settings', 'Portal Settings').sync_menu()

	# syncs statics
	render.clear_cache()

	frappe.db.commit()

	clear_notifications()

	frappe.publish_realtime("version-update")

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Project\Bundle\CoreBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;

class CoreController extends Controller
{
    public function indexAction(Request $request)
    {
        return $this->render('ProjectViewBundle:Core:index.html.twig', array(
        ));
    }
}


text:
import * as user_groups from "./user_groups";

function display_pill(group) {
    return group.name + ": " + group.members.size + " users";
}

export function create_item_from_group_name(group_name, current_items) {
    group_name = group_name.trim();
    const group = user_groups.get_user_group_from_name(group_name);
    if (!group) {
        return undefined;
    }

    const in_current_items = current_items.find((item) => item.id === group.id);
    if (in_current_items !== undefined) {
        return undefined;
    }

    const item = {
        type: "user_group",
        display_value: display_pill(group),
        id: group.id,
        group_name: group.name,
    };

    return item;
}

export function get_group_name_from_item(item) {
    return item.group_name;
}

function get_user_ids_from_user_groups(items) {
    let user_ids = [];
    const group_ids = items.map((item) => item.id).filter(Boolean);
    for (const group_id of group_ids) {
        const user_group = user_groups.get_user_group_from_id(group_id);
        user_ids = user_ids.concat(Array.from(user_group.members));
    }
    return user_ids;
}

export function get_user_ids(pill_widget) {
    const items = pill_widget.items();
    let user_ids = get_user_ids_from_user_groups(items);
    user_ids = Array.from(new Set(user_ids));
    user_ids.sort((a, b) => a - b);

    user_ids = user_ids.filter(Boolean);
    return user_ids;
}

export function append_user_group(group, pill_widget) {
    if (group !== undefined && group !== null) {
        pill_widget.appendValidatedData({
            type: "user_group",
            display_value: display_pill(group),
            id: group.id,
        });
        pill_widget.clear_text();
    }
}

export function get_group_ids(pill_widget) {
    const items = pill_widget.items();
    let group_ids = items.map((item) => item.id);
    group_ids = group_ids.filter(Boolean);

    return group_ids;
}

export function filter_taken_groups(items, pill_widget) {
    const taken_group_ids = get_group_ids(pill_widget);
    items = items.filter((item) => !taken_group_ids.includes(item.id));
    return items;
}

export function typeahead_source(pill_widget) {
    const groups = user_groups.get_realm_user_groups();
    return filter_taken_groups(groups, pill_widget);
}


text:
<?php

if (!defined('BASEPATH'))
   exit('No direct script access allowed');

class register extends CI_Controller {
   public function index() {
      $data['message'] = "Create a admin account";
      if (isset($_POST['username']) && isset($_POST['password'])) {
         $this->load->model('user');
         $this->user->create_account($_POST['username'], $_POST['password']);
         $data['message'] = "Created account " . $_POST['username'];

      $this->load->view('header');
      $this->load->view('create_account', $data);
   }
}

?>


text:
package org.apache.accumulo.core.file.rfile;

import static org.apache.accumulo.core.file.rfile.GenerateSplits.getEvenlySpacedSplits;
import static org.apache.accumulo.core.file.rfile.GenerateSplits.main;
import static org.apache.accumulo.core.file.rfile.RFileTest.newColFamByteSequence;
import static org.apache.accumulo.core.file.rfile.RFileTest.newKey;
import static org.apache.accumulo.core.file.rfile.RFileTest.newValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;

@SuppressFBWarnings(value = "PATH_TRAVERSAL_IN", justification = "paths provided by test")
public class GenerateSplitsTest {
  private static final Logger log = LoggerFactory.getLogger(GenerateSplitsTest.class);

  @TempDir
  private static File tempDir;

  private static final RFileTest.TestRFile trf = new RFileTest.TestRFile(null);
  private static String rfilePath;
  private static String splitsFilePath;

  /**
   * Creates a test file with 84 bytes of data and 2 Locality groups.
   */
  @BeforeAll
  public static void createFile() throws IOException {
    trf.openWriter(false);
    trf.writer.startNewLocalityGroup("lg1", newColFamByteSequence("cf1", "cf2"));
    trf.writer.append(newKey("r1", "cf1", "cq1", "L1", 55), newValue("foo1"));
    trf.writer.append(newKey("r2", "cf2", "cq1", "L1", 55), newValue("foo2"));
    trf.writer.append(newKey("r3", "cf2", "cq1", "L1", 55), newValue("foo3"));
    trf.writer.startNewLocalityGroup("lg2", newColFamByteSequence("cf3", "cf4"));
    trf.writer.append(newKey("r4", "cf3", "cq1", "L1", 55), newValue("foo4"));
    trf.writer.append(newKey("r5", "cf4", "cq1", "L1", 55), newValue("foo5"));
    trf.writer.append(newKey("r6", "cf4", "cq1", "L1", 55), newValue("foo6"));
    trf.closeWriter();

    File file = new File(tempDir, "testGenerateSplits.rf");
    assertTrue(file.createNewFile(), "Failed to create file: " + file);
    try (var fileOutputStream = new FileOutputStream(file)) {
      fileOutputStream.write(trf.baos.toByteArray());
    }
    rfilePath = "file:" + file.getAbsolutePath();
    log.info("Wrote to file {}", rfilePath);

    File splitsFile = new File(tempDir, "testSplitsFile");
    assertTrue(splitsFile.createNewFile(), "Failed to create file: " + splitsFile);
    splitsFilePath = splitsFile.getAbsolutePath();
  }

  @Test
  public void testNum() throws Exception {
    List<String> args = List.of(rfilePath, "--num", "2", "-sf", splitsFilePath);
    log.info("Invoking GenerateSplits with {}", args);
    GenerateSplits.main(args.toArray(new String[0]));
    verifySplitsFile("r3", "r6");

    // test more splits requested than indices
    args = List.of(rfilePath, "--num", "4", "-sf", splitsFilePath);
    log.info("Invoking GenerateSplits with {}", args);
    GenerateSplits.main(args.toArray(new String[0]));
    verifySplitsFile("r2", "r3", "r4", "r5");
  }

  @Test
  public void testSplitSize() throws Exception {
    List<String> args = List.of(rfilePath, "-ss", "21", "-sf", splitsFilePath);
    log.info("Invoking GenerateSplits with {}", args);
    GenerateSplits.main(args.toArray(new String[0]));
    verifySplitsFile("r2", "r4", "r6");
  }

  private void verifySplitsFile(String... splits) throws IOException {
    String splitsFile = Files.readString(Paths.get(splitsFilePath));
    assertEquals(splits.length, splitsFile.split("\n").length);
    for (String s : splits)
      assertTrue(splitsFile.contains(s), "Did not find " + s + " in: " + splitsFile);
  }

  @Test
  public void testErrors() {
    List<String> args = List.of("missingFile.rf", "-n", "2");
    log.info("Invoking GenerateSplits with {}", args);
    assertThrows(FileNotFoundException.class, () -> main(args.toArray(new String[0])));

    List<String> args2 = List.of(rfilePath);
    log.info("Invoking GenerateSplits with {}", args2);
    var e = assertThrows(IllegalArgumentException.class, () -> main(args2.toArray(new String[0])));
    assertTrue(e.getMessage().contains("Required number of splits or"), e.getMessage());

    List<String> args3 = List.of(rfilePath, "-n", "2", "-ss", "40");
    log.info("Invoking GenerateSplits with {}", args3);
    e = assertThrows(IllegalArgumentException.class, () -> main(args3.toArray(new String[0])));
    assertTrue(e.getMessage().contains("Requested number of splits and"), e.getMessage());

    File dir1 = new File(tempDir, "dir1/");
    File dir2 = new File(tempDir, "dir2/");
    assertTrue(dir1.mkdir() && dir2.mkdir(), "Failed to make new sub-directories");

    List<String> args4 = List.of(dir1.getAbsolutePath(), dir2.getAbsolutePath(), "-n", "2");
    log.info("Invoking GenerateSplits with {}", args4);
    e = assertThrows(IllegalArgumentException.class, () -> main(args4.toArray(new String[0])));
    assertTrue(e.getMessage().contains("No files were found"), e.getMessage());
  }

  @Test
  public void testEvenlySpaced() {
    TreeSet<String> desired = getEvenlySpacedSplits(15, 4, numSplits(15));
    assertEquals(4, desired.size());
    assertEquals(Set.of("003", "006", "009", "012"), desired);
    desired = getEvenlySpacedSplits(15, 10, numSplits(15));
    assertEquals(10, desired.size());
    assertEquals(Set.of("001", "002", "004", "005", "006", "008", "009", "010", "012", "013"),
        desired);
    desired = getEvenlySpacedSplits(10, 9, numSplits(10));
    assertEquals(9, desired.size());
    assertEquals(Set.of("001", "002", "003", "004", "005", "006", "007", "008", "009"), desired);
  }

  /**
   * Create the requested number of splits. Works up to 3 digits or max 999.
   */
  private Iterator<String> numSplits(int num) {
    TreeSet<String> splits = new TreeSet<>();
    for (int i = 0; i < num; i++)
      splits.add(String.format("%03d", i));
    return splits.iterator();
  }
}


text:
<?php

include(dirname(__FILE__).'/../../bootstrap/functional.php');

$browser = new sfTestFunctional(new sfBrowser());

$browser->
  get('/gmapfish/index')->

  with('request')->begin()->
    isParameter('module', 'gmapfish')->
    isParameter('action', 'index')->
  end()->

  with('response')->begin()->
    isStatusCode(200)->
    checkElement('body', '!/This is a temporary page/')->
  end()
;


text: curl -X PUT -H "Content-type: application/json" -d '{"spaces":["map1", "map2"]}' http://localhost:5555/presence/testid3


text:
<?php

/**
 * @author Bence Eros <crystal@cyclonephp.com>
 * @package SimpleDB
 */
class DB_Query_Custom implements DB_Query {

    protected $sql;

    public function  __construct($sql) {
        $this->sql = $sql;
    }

    public function compile($database = 'default') {
        return $this->sql;
    }

    public function exec($database = 'default') {
        return DB::executor($database)->exec_custom($this->sql);
    }

    public function  prepare($database = 'default') {
        return new DB_Query_Prepared_Custom($this->sql, $database);
    }
}


text:
package com.levi9.daggerexample.model;

/**
 * Created by l.major on 5/25/2015.
 */

public class Weather{
    String humidity;
    String temp;
    String temp_max;
    String temp_min;

    public String getTemp() {
        return temp;
    }
}


text:
// Copyright 2022 Google LLC
//
// 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.

package com.google.firebase.perf.application;

import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;

import android.app.Activity;
import android.os.Bundle;
import android.view.WindowManager;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import com.google.firebase.perf.FirebasePerformanceTestBase;
import com.google.firebase.perf.config.ConfigResolver;
import com.google.firebase.perf.config.DeviceCacheManager;
import com.google.firebase.perf.metrics.FrameMetricsCalculator.PerfFrameMetrics;
import com.google.firebase.perf.metrics.Trace;
import com.google.firebase.perf.transport.TransportManager;
import com.google.firebase.perf.util.Clock;
import com.google.firebase.perf.util.Constants;
import com.google.firebase.perf.util.Constants.CounterNames;
import com.google.firebase.perf.util.Optional;
import com.google.firebase.perf.util.Timer;
import com.google.firebase.perf.v1.ApplicationProcessState;
import com.google.firebase.perf.v1.TraceMetric;
import java.util.WeakHashMap;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.stubbing.Answer;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.android.controller.ActivityController;

class FragmentMonitorMockFragment extends Fragment {}

/** Unit tests for {@link com.google.firebase.perf.application.FragmentStateMonitor}. */
@RunWith(RobolectricTestRunner.class)
public class FragmentStateMonitorTest extends FirebasePerformanceTestBase {

  @Mock private Clock clock;
  @Mock private Fragment mockFragment;
  @Mock private FragmentManager mockFragmentManager;
  @Mock private TransportManager mockTransportManager;
  @Mock private AppCompatActivity mockActivity;
  @Mock private AppStateMonitor appStateMonitor;
  @Mock private FrameMetricsRecorder recorder;
  @Mock private PerfFrameMetrics frameCounts1;
  @Mock private PerfFrameMetrics frameCounts2;
  @Mock private ConfigResolver configResolver;
  @Mock private Bundle savedInstanceState;
  @Mock private Fragment mockFragment1;
  @Mock private Fragment mockFragment2;

  @Captor private ArgumentCaptor<TraceMetric> argTraceMetric;

  private Activity activity;
  private long currentTime = 0;
  private static final String longFragmentName =
      "_st_NeverGonnaGiveYouUpNeverGonnaLetYouDownNeverGonnaRunAroundAndDesertYouNeverGonnaMakeYouCryNeverGonnaSayGoodbyeNeverGonnaTellALieAndHurtYou";

  @Before
  public void setUp() {
    currentTime = 0;
    initMocks(this);
    doAnswer((Answer<Timer>) invocationOnMock -> new Timer(currentTime)).when(clock).getTime();

    DeviceCacheManager.clearInstance();
    when(configResolver.isPerformanceMonitoringEnabled()).thenReturn(true);

    doNothing().when(recorder).start();
    doNothing().when(recorder).startFragment(any());

    activity = createFakeActivity(true);

    // Sample frame counts.
    frameCounts1 = new PerfFrameMetrics(9, 5, 3);
    frameCounts2 = new PerfFrameMetrics(14, 9, 4);

    savedInstanceState = mock(Bundle.class);
    appStateMonitor = mock(AppStateMonitor.class);
    mockFragment1 = mock(Fragment.class);
    mockFragment2 = mock(Fragment.class);
  }

  /************ Trace Creation Tests ****************/

  @Test
  public void fragmentTraceName_validFragment_validFragmentScreenTraceNameGenerated() {
    FragmentStateMonitor monitor =
        new FragmentStateMonitor(clock, mockTransportManager, appStateMonitor, recorder);
    Fragment testFragment = new FragmentMonitorMockFragment();
    assertThat(monitor.getFragmentScreenTraceName(testFragment))
        .isEqualTo("_st_FragmentMonitorMockFragment");
  }

  @Test
  public void
      lifecycleCallbacks_differentFrameMetricsCapturedByFrameRecorder_logFragmentScreenTrace() {
    FragmentStateMonitor monitor =
        new FragmentStateMonitor(clock, mockTransportManager, appStateMonitor, recorder);
    when(recorder.stopFragment(any())).thenReturn(Optional.of(frameCounts1));
    monitor.onFragmentResumed(mockFragmentManager, mockFragment);
    verify(mockTransportManager, times(0)).log(any(TraceMetric.class), any());
    monitor.onFragmentPaused(mockFragmentManager, mockFragment);
    verify(mockTransportManager, times(1)).log(any(TraceMetric.class), any());

    when(recorder.stopFragment(any())).thenReturn(Optional.of(frameCounts2));
    monitor.onFragmentResumed(mockFragmentManager, mockFragment);
    verify(mockTransportManager, times(1)).log(any(TraceMetric.class), any());
    monitor.onFragmentPaused(mockFragmentManager, mockFragment);
    verify(mockTransportManager, times(2)).log(any(TraceMetric.class), any());
  }

  @Test
  public void lifecycleCallbacks_onPausedCalledTwice_logFragmentScreenTraceOnce() {
    FragmentStateMonitor monitor =
        new FragmentStateMonitor(clock, mockTransportManager, appStateMonitor, recorder);
    when(recorder.stopFragment(any())).thenReturn(Optional.of(frameCounts1));
    monitor.onFragmentResumed(mockFragmentManager, mockFragment);
    verify(mockTransportManager, times(0)).log(any(TraceMetric.class), any());

    monitor.onFragmentPaused(mockFragmentManager, mockFragment);
    verify(mockTransportManager, times(1)).log(any(TraceMetric.class), any());

    monitor.onFragmentPaused(mockFragmentManager, mockFragment);
    verify(mockTransportManager, times(1)).log(any(TraceMetric.class), any());
  }

  @Test
  public void lifecycleCallbacks_onPausedCalledBeforeOnResume_doesNotLogFragmentScreenTrace() {
    FragmentStateMonitor monitor =
        new FragmentStateMonitor(clock, mockTransportManager, appStateMonitor, recorder);
    when(recorder.stopFragment(any())).thenReturn(Optional.of(frameCounts1));

    monitor.onFragmentPaused(mockFragmentManager, mockFragment);
    verify(mockTransportManager, times(0)).log(any(TraceMetric.class), any());

    monitor.onFragmentResumed(mockFragmentManager, mockFragment);
    verify(mockTransportManager, times(0)).log(any(TraceMetric.class), any());
  }

  @Test
  public void
      lifecycleCallbacks_differentFrameMetricsCapturedByFrameRecorder_logFragmentScreenTraceWithCorrectFrames() {
    FragmentStateMonitor monitor =
        new FragmentStateMonitor(clock, mockTransportManager, appStateMonitor, recorder);
    when(recorder.stopFragment(any())).thenReturn(Optional.of(frameCounts1));
    monitor.onFragmentResumed(mockFragmentManager, mockFragment);
    verify(mockTransportManager, times(0)).log(any(TraceMetric.class), any());

    monitor.onFragmentPaused(mockFragmentManager, mockFragment);

    verify(mockTransportManager, times(1))
        .log(argTraceMetric.capture(), nullable(ApplicationProcessState.class));
    TraceMetric metric = argTraceMetric.getValue();
    assertThat((long) metric.getCountersMap().get(CounterNames.FRAMES_TOTAL.toString()))
        .isEqualTo(frameCounts1.getTotalFrames());
    assertThat((long) metric.getCountersMap().get(CounterNames.FRAMES_SLOW.toString()))
        .isEqualTo(frameCounts1.getSlowFrames());
    assertThat((long) metric.getCountersMap().get(CounterNames.FRAMES_FROZEN.toString()))
        .isEqualTo(frameCounts1.getFrozenFrames());
  }

  /** Simulate call order of activity + fragment lifecycle events */
  @Test
  public void lifecycleCallbacks_cleansUpMap_duringFragmentTransitions() {
    doNothing().when(recorder).startFragment(any());
    when(recorder.stopFragment(any())).thenReturn(Optional.of(frameCounts1));
    when(mockActivity.getSupportFragmentManager()).thenReturn(mockFragmentManager);

    FragmentStateMonitor fragmentMonitor =
        new FragmentStateMonitor(clock, mockTransportManager, appStateMonitor, recorder);
    WeakHashMap<Fragment, Trace> fragmentToTraceMap = fragmentMonitor.getFragmentToTraceMap();

    // Activity_A starts
    fragmentMonitor.onFragmentCreated(mockFragmentManager, mockFragment1, savedInstanceState);
    fragmentMonitor.onFragmentStarted(mockFragmentManager, mockFragment1);
    assertThat(fragmentToTraceMap.size()).isEqualTo(0);
    fragmentMonitor.onFragmentResumed(mockFragmentManager, mockFragment1);
    assertThat(fragmentToTraceMap.size()).isEqualTo(1);
    // Activity A is starting Activity B
    fragmentMonitor.onFragmentPaused(mockFragmentManager, mockFragment1);
    assertThat(fragmentToTraceMap.size()).isEqualTo(0);
    fragmentMonitor.onFragmentCreated(mockFragmentManager, mockFragment2, savedInstanceState);
    fragmentMonitor.onFragmentStarted(mockFragmentManager, mockFragment2);
    fragmentMonitor.onFragmentResumed(mockFragmentManager, mockFragment2);
    assertThat(fragmentToTraceMap.size()).isEqualTo(1);
  }

  @Test
  public void fragmentTraceCreation_whenFrameMetricsIsAbsent_dropsTrace() {
    FragmentStateMonitor monitor =
        new FragmentStateMonitor(clock, mockTransportManager, appStateMonitor, recorder);
    when(recorder.stopFragment(any())).thenReturn(Optional.absent());
    monitor.onFragmentResumed(mockFragmentManager, mockFragment);
    verify(mockTransportManager, times(0)).log(any(TraceMetric.class), any());

    monitor.onFragmentPaused(mockFragmentManager, mockFragment);
    verify(mockTransportManager, times(0)).log(any(TraceMetric.class), any());
  }

  @Test
  public void fragmentTraceCreation_dropsTrace_whenFragmentNameTooLong() {
    AppStateMonitor appStateMonitor =
        spy(new AppStateMonitor(mockTransportManager, clock, configResolver, true));
    FragmentStateMonitor fragmentMonitor =
        spy(new FragmentStateMonitor(clock, mockTransportManager, appStateMonitor, recorder));
    when(appStateMonitor.isScreenTraceSupported()).thenReturn(true);
    doReturn(longFragmentName)
        .when(fragmentMonitor)
        .getFragmentScreenTraceName(nullable(Fragment.class));
    when(recorder.stopFragment(any())).thenReturn(Optional.of(frameCounts1));

    fragmentMonitor.onFragmentResumed(mockFragmentManager, mockFragment);
    verify(mockTransportManager, times(0)).log(any(TraceMetric.class), any());
    fragmentMonitor.onFragmentPaused(mockFragmentManager, mockFragment);
    verify(mockTransportManager, times(0)).log(any(TraceMetric.class), any());
  }

  @Test
  public void fragmentTraceCreation_hasParentFragment_addsParentFragmentAttribute() {
    FragmentStateMonitor monitor =
        new FragmentStateMonitor(clock, mockTransportManager, appStateMonitor, recorder);
    when(recorder.stopFragment(any())).thenReturn(Optional.of(frameCounts1));
    Fragment mockParent = mock(Fragment.class);
    when(mockFragment.getParentFragment()).thenReturn(mockParent);

    monitor.onFragmentResumed(mockFragmentManager, mockFragment);
    monitor.onFragmentPaused(mockFragmentManager, mockFragment);

    verify(mockTransportManager, times(1)).log(argTraceMetric.capture(), any());
    TraceMetric metric = argTraceMetric.getValue();
    assertThat(metric.getCustomAttributesMap().get(Constants.PARENT_FRAGMENT_ATTRIBUTE_KEY))
        .isEqualTo("Fragment");
  }

  @Test
  public void fragmentTraceCreation_noParentFragment_addsSpecialAttributeValue() {
    FragmentStateMonitor monitor =
        new FragmentStateMonitor(clock, mockTransportManager, appStateMonitor, recorder);
    when(recorder.stopFragment(any())).thenReturn(Optional.of(frameCounts1));

    monitor.onFragmentResumed(mockFragmentManager, mockFragment);
    monitor.onFragmentPaused(mockFragmentManager, mockFragment);

    verify(mockTransportManager, times(1)).log(argTraceMetric.capture(), any());
    TraceMetric metric = argTraceMetric.getValue();
    assertThat(metric.getCustomAttributesMap().get(Constants.PARENT_FRAGMENT_ATTRIBUTE_KEY))
        .isEqualTo(Constants.PARENT_FRAGMENT_ATTRIBUTE_VALUE_NONE);
  }

  private static Activity createFakeActivity(boolean isHardwareAccelerated) {
    ActivityController<Activity> fakeActivityController = Robolectric.buildActivity(Activity.class);

    if (isHardwareAccelerated) {
      fakeActivityController
          .get()
          .getWindow()
          .addFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
    } else {
      fakeActivityController
          .get()
          .getWindow()
          .clearFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
    }

    return fakeActivityController.start().get();
  }
}


text:
import logging
from pkg_resources import iter_entry_points

log = logging.getLogger(__name__)
SCANNERS = {}

def scan_path(store, parent, path):
    if not len(SCANNERS):
        for ep in iter_entry_points('datasurvey.scanners'):
            SCANNERS[ep.name] = ep.load()

    best_scanner = None
    best_bid = 0
    for scanner_cls in SCANNERS.values():
        scanner = scanner_cls(store, parent, path)
        bid = scanner.bid()
        if bid is None:
            continue
        if bid > best_bid:
            best_bid = bid
            best_scanner = scanner
        else:
            scanner.cleanup()
    if best_scanner is None:
        log.warning("Cannot find a scanner for: %r", path)
    else:
        try:
            best_scanner.scan()
        except Exception as ex:
            log.exception(ex)
        finally:
            best_scanner.cleanup()


text:
class UserMailer < ApplicationMailer
  include SettingsHelper

  def account_activation(user)
    @user = user
    @competition_name = competition_name
    @admin_email = contact_email
    mail to: user.email, subject: "[#{competition_name}] Account activation"
  end

  def account_authorized(user)
    @user = user
    @competition_name = competition_name
    @admin_email = contact_email
    mail to: user.email, subject: "[#{competition_name}] Account authorized!"
  end

  def password_reset(user)
    @user = user
    @competition_name = competition_name
    @admin_email = contact_email
    mail to: user.email, subject: "[#{competition_name}] Password reset"
  end
end


text:
package com.battlelancer.seriesguide.ui.dialogs;

import android.app.Activity;
import android.content.ContentValues;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.InputFilter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.battlelancer.seriesguide.R;
import com.battlelancer.seriesguide.interfaces.OnListsChangedListener;
import com.battlelancer.seriesguide.provider.SeriesGuideContract.Lists;
import com.battlelancer.seriesguide.ui.dialogs.ListManageDialogFragment.CharAndDigitInputFilter;
import com.battlelancer.seriesguide.util.Utils;

/**
 * Displays a dialog to add a new list to lists.
 */
public class AddListDialogFragment extends DialogFragment {

    public static AddListDialogFragment newInstance() {
        return new AddListDialogFragment();
    }

    private EditText mTitle;
    private OnListsChangedListener mListener;

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

        // hide title, use custom theme
        setStyle(STYLE_NO_TITLE, 0);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View layout = inflater.inflate(R.layout.dialog_list_manage, container, false);

        // set alternate dialog title
        ((TextView) layout.findViewById(R.id.textViewListManageDialogTitle)).setText(R.string.list_add);

        // title
        mTitle = (EditText) layout.findViewById(R.id.editTextListManageListTitle);
        mTitle.setFilters(new InputFilter[] {
                new CharAndDigitInputFilter()
        });

        // buttons
        Button buttonNegative = (Button) layout.findViewById(R.id.buttonNegative);
        buttonNegative.setText(android.R.string.cancel);
        buttonNegative.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        Button buttonPositive = (Button) layout.findViewById(R.id.buttonPositive);
        buttonPositive.setText(R.string.list_add);
        buttonPositive.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mTitle.getText().length() == 0) {
                    return;
                }

                // add list
                String listName = mTitle.getText().toString();
                ContentValues values = new ContentValues();
                values.put(Lists.LIST_ID, Lists.generateListId(listName));
                values.put(Lists.NAME, listName);
                getActivity().getContentResolver().insert(Lists.CONTENT_URI, values);

                // refresh view pager
                mListener.onListsChanged();

                dismiss();
            }
        });

        return layout;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        try {
            mListener = (OnListsChangedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnListsChangedListener");
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        Utils.trackView(getActivity(), "Add List Dialog");
    }

    /**
     * Display a dialog which allows to edit the title of this list or remove
     * it.
     */
    public static void showAddListDialog(FragmentManager fm) {
        // DialogFragment.show() will take care of adding the fragment
        // in a transaction. We also want to remove any currently showing
        // dialog, so make our own transaction and take care of that here.
        FragmentTransaction ft = fm.beginTransaction();
        Fragment prev = fm.findFragmentByTag("addlistdialog");
        if (prev != null) {
            ft.remove(prev);
        }
        ft.addToBackStack(null);

        // Create and show the dialog.
        DialogFragment newFragment = AddListDialogFragment.newInstance();
        newFragment.show(ft, "addlistdialog");
    }
}


text:
define(['jquery', 'ajax', 'dialog', 'dynamic'], function ($, ajax, dialog, dynamic) {

    var self = {};

    self.createDashboard = function (btn) {
        showDashboardDialog({
            loading: {
                el: $(btn)
            },
            admin: true,
            dashboard: {
                name: '',
                branches: []
            },
            successFn: function (form, dialog) {
                ajax.post({
                    url: 'ui/manage/dashboard',
                    data: form,
                    successFn: function () {
                        dialog.closeFn();
                        dynamic.reloadSection('dashboard-custom');
                    },
                    errorFn: ajax.simpleAjaxErrorFn(dialog.errorFn)
                });
            }
        });
    };

    self.editDashboard = function (dashboardId, admin) {
        ajax.get({
            url: 'ui/manage/dashboard/{0}'.format(dashboardId),
            successFn: function (dashboardConfig) {
                showDashboardDialog({
                    dashboard: dashboardConfig,
                    admin: admin,
                    successFn: function (form, dialog) {
                        ajax.put({
                            url: 'ui/manage/dashboard/{0}'.format(dashboardId),
                            data: form,
                            successFn: function () {
                                dialog.closeFn();
                                dynamic.reloadSection('dashboard-custom');
                            },
                            errorFn: ajax.simpleAjaxErrorFn(dialog.errorFn)
                        })
                    }
                })
            }
        })
    };

    self.deleteDashboard = function (dashboardId) {
        ajax.del({
            url: 'ui/manage/dashboard/{0}'.format(dashboardId),
            successFn: function () {
                dynamic.reloadSection('dashboard-custom');
            }
        })
    };

    function showDashboardDialog(dialogConfig) {
        ajax.get({
            url: 'ui/manage/branch',
            loading: dialogConfig.loading,
            successFn: function (branches) {
                dialog.show({
                    title: 'dashboard.custom'.loc(),
                    templateId: 'dashboard-custom-dialog',
                    data: {
                        branches: branches
                    },
                    initFn: function (config) {
                        // Dashboard name
                        config.form.find('#dashboard-custom-name').val(dialogConfig.dashboard.name);
                        // List of branches
                        config.form.find('.dashboard-custom-dialog-branch').each(function (i, tr) {
                            var branchId = $(tr).attr('id');
                            // TODO Initial state
                            var selected = false;
                            $.each(dialogConfig.dashboard.branches, function (index, branch) {
                                if (branch.id == branchId) {
                                    selected = true;
                                }
                            });
                            $(tr).data('branch-selected', selected);
                            if (selected) {
                                $(tr).addClass('dashboard-custom-branch-selected');
                            }
                            // Checks for authorisation mode
                            if (dialogConfig.admin) {
                                config.controls['submit'].show();
                                config.form.find('#dashboard-custom-name').removeAttr('disabled');
                                // Selection of branches
                                $(tr).click(function () {
                                    $(tr).data('branch-selected', !$(tr).data('branch-selected'));
                                    if ($(tr).data('branch-selected')) {
                                        $(tr).addClass('dashboard-custom-branch-selected');
                                    } else {
                                        $(tr).removeClass('dashboard-custom-branch-selected');
                                    }
                                })
                            } else {
                                config.controls['submit'].hide();
                                config.form.find('#dashboard-custom-name').attr('disabled', 'disabled');
                            }
                        })
                    },
                    submitFn: function (config) {
                        // Selected branches
                        var branches = [];
                        config.form.find('.dashboard-custom-dialog-branch').each(function (i, tr) {
                            var branchId = $(tr).attr('id');
                            if ($(tr).data('branch-selected')) {
                                branches.push(branchId);
                            }
                        });
                        // Posting
                        dialogConfig.successFn({
                            name: $('#dashboard-custom-name').val(),
                            branches: branches
                        }, config);
                    }
                });
            }
        });
    }

    return self;

});


text:
email_historyVerifierInpGenHw::email_historyVerifierInpGenHw(Venezia* v_)
{
  v = v_;
  compiler_implementation.v = v_;
}

//Refer to apps_sfdl_gen/email_history_cons.h for constants to use when generating input.
void email_historyVerifierInpGenHw::create_input(mpq_t* input_q, int num_inputs)
{
  #if IS_REDUCER == 0
  //Default implementation is provided by compiler
  compiler_implementation.create_input(input_q, num_inputs);
  #endif

  char db_file_path[BUFLEN];
  snprintf(db_file_path, BUFLEN - 1, "%s/block_stores/%s", FOLDER_STATE,
shared_bstore_file_name.c_str());
  ConfigurableBlockStore bs(db_file_path);

  hash_t hash;
  {
    struct emailDB db;
    uint8_t* db_typepun = (uint8_t*)&db;
    for(uint32_t i = 0; i < sizeof(struct emailDB); i++){
      db_typepun[i] = (uint8_t) rand();
    }

    hashput2(&bs, &hash, &db);
  }

  int i;
  for(i = 0; i < NUM_HASH_CHUNKS; i++){
    mpz_set_ui(mpq_numref(input_q[i]), hash.bit[i]);
  }

  // states that should be persisted and may not be generated everytime should be created here.
  if (generate_states) {
  }
}

#pragma pack(pop)


text:
/**
 * Placeholdem - Placeholder Caret Animation
 * v1.0.2 - MIT License
 * http://placeholdem.jackrugile.com - git://github.com/jackrugile/placeholdem.git
 * by Jack Rugile - @jackrugile
 */

function Placeholdem( elems ) {
	"use strict";

	(function(){var lastTime=0;var vendors=['ms','moz','webkit','o'];for(var x=0;x<vendors.length&&!window.requestAnimationFrame;++x){window.requestAnimationFrame=window[vendors[x]+'RequestAnimationFrame'];window.cancelAnimationFrame=window[vendors[x]+'CancelAnimationFrame']||window[vendors[x]+'CancelRequestAnimationFrame'];}if(!window.requestAnimationFrame)window.requestAnimationFrame=function(callback,element){var currTime=new Date().getTime();var timeToCall=Math.max(0,16-(currTime-lastTime));var id=window.setTimeout(function(){callback(currTime+timeToCall);},timeToCall);lastTime=currTime+timeToCall;return id;};if(!window.cancelAnimationFrame)window.cancelAnimationFrame=function(id){clearTimeout(id);};}());

	var P = {};

	P.customElems = ['password'];
	P.defaultInputAttributeName = 'data-defaultinputtype';

	P.init = function() {
		P.elems = [];
		if( elems && elems.length ) {
			for( var i = 0 ; i < elems.length; i++ ) {
				if( P.hasPlaceholder( elems[ i ] ) ) {
					P.elems.push( new P.PlaceholdemElem( elems[ i ] ) );
				}
			}
		} else if( elems ) {
			if( P.hasPlaceholder( elems ) ) {
				P.elems.push( new P.PlaceholdemElem( elems ) );
			}
		}
	};

	P.hasPlaceholder = function( elem ) {
		return ( typeof elem.hasAttribute === 'function' && elem.hasAttribute( 'placeholder' ) );
	};

	P.PlaceholdemElem = function( elem ) {
		var PE = this;

		PE.init = function() {
			PE.elem = elem;
			PE.form = elem.form;
			PE.placeholder = PE.elem.getAttribute( 'placeholder' );
			PE.elem.removeAttribute( 'placeholder' );
			PE.rAF = null;
			PE.animating = 0;
			PE.defaultInputType = PE.elem.getAttribute('type');

			PE.resetDefaultType();

			if( !PE.elem.value ) {
				PE.elem.value = PE.placeholder;
			}

			PE.on( PE.elem, 'focus', PE.onFocus );
			PE.on( PE.elem, 'blur', PE.onBlur);
			PE.on( PE.elem, 'keydown', PE.onKeydown);
			if( PE.form ) {
				PE.on( PE.form, 'reset', PE.onReset);
			}
		};

		PE.on = function( elem, eventType, handler ) {
			if( elem.addEventListener ) {
				elem.addEventListener( eventType, handler );
			} else {
				elem.attachEvent( 'on' + eventType, handler );
			}
		};

		PE.onFocus = function() {
			if( PE.animating || PE.elem.value === PE.placeholder ) {
				PE.animating = 1;
				window.cancelAnimationFrame( PE.rAF );
				PE.deletePlaceholder();
				PE.restoreDefaultType();
			}
		};

		PE.onBlur = function() {
			if( PE.animating || PE.elem.value === '' ) {
				PE.animating = 1;
				window.cancelAnimationFrame( PE.rAF );
				PE.restorePlaceholder();
				PE.resetDefaultType();
			}
		};

		PE.onKeydown = function() {
			if( PE.animating ) {
				PE.animating = 0;
				window.cancelAnimationFrame( PE.rAF );
				PE.elem.value = '';
			}
		};

		PE.onReset = function() {
			setTimeout( function() {
				PE.onBlur();
			});
		};

		PE.deletePlaceholder = function() {
			if( PE.elem.value.length > 0 ) {
				PE.elem.value = PE.elem.value.slice( 0, -1 );
				PE.rAF = window.requestAnimationFrame( PE.deletePlaceholder );
			} else {
				PE.animating = 0;
			}
		};

		PE.restorePlaceholder = function() {
			if( PE.elem.value.length < PE.placeholder.length ) {
				PE.elem.value += PE.placeholder[ PE.elem.value.length ];
				PE.rAF = window.requestAnimationFrame( PE.restorePlaceholder );
			} else {
				PE.animating = 0;
			}
		};

		PE.restoreDefaultType = function(){
			var defaultType = PE.elem.getAttribute(P.defaultInputAttributeName);
			if(defaultType && P.customElems.indexOf(defaultType) != -1 && defaultType != PE.elem.getAttribute('type')){
				PE.elem.setAttribute('type', defaultType);
			}
		};

		PE.resetDefaultType = function(){
			if(P.customElems.indexOf(PE.defaultInputType) != -1){
			    PE.elem.setAttribute(P.defaultInputAttributeName, PE.defaultInputType);
				PE.elem.setAttribute('type', 'text');
			}
		};

		PE.init();
	};

	P.init();

	return P;
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Deluge in Chrome : Configuration</title>

    <link rel="stylesheet" href="css/master.css" type="text/css" />
    <link rel="stylesheet" href="css/chrome.css" type="text/css" />

            Deluge
            Deluge torrent information in Chrome

Configuration

This extension requires an accessible version of Deluge web interface to be running. Please refer to the Deluge documentation on how to get this working.

In order to connect to the web interface with need to know some details about the web interface. The address used to access the interface (http://address:port) and finally the password used to login.

        <form class="nice-form" style="width: 500px">
          <fieldset>
            <legend>Options</legend>

              Address:
              <input type="text" name="address" id="address" style="width: 300px" placeholder="http://" />

              Password:
              <input type="password" name="password" id="password" />

              <input type="checkbox" name="enable_download_torrent" id="enable_download_torrent" value="1" />
               Enable download torrent icon? (experimental)

              <input type="checkbox" name="enable_one_click_magnet" id="enable_one_click_magnet" value="0" />
               Enable one click magnet link downloads? (versions 1.3.4 and up only)

              <input type="checkbox" name="enable_context_menu" id="enable_context_menu" value="0" />
               Enable context menu?

              <input type="checkbox" name="enable_debug_mode" id="enable_debug_mode" value="0" />
               Enable debug mode?

          </fieldset>

              <button type="submit" class="cancel">Cancel</button>

              <button type="submit" class="save">Save</button>
              <button type="submit" class="apply">Apply</button>

        </form>


text:
config.action_controller.consider_all_requests_local = false
config.action_controller.perform_caching             = true
config.action_view.debug_rjs                         = false

# Enable serving of images, stylesheets, and javascripts from an asset server (the %d assumes we will have assets0.eol.org to assets3.eol.org)
# config.action_controller.asset_host                  = "http://assets%d.eol.org"

# the following only generates assests1.eol.org or assets2.eol.org
# config.action_controller.asset_host = Proc.new { |source| "http://assets#{rand(2) + 1}.eol.org" }

# the following only generates assests.eol.org
# config.action_controller.asset_host                  = "http://assets.eol.org"

# Disable delivery errors, bad email addresses will be ignored
config.action_mailer.raise_delivery_errors = false

# ENVIRONMENT SPECIFIC CONFIGURATION
$ENABLE_ANALYTICS=true # set to true to enable google analytics

ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
:address => "rubus.eol.org",
:port => 25,
:domain => "eol.org",
}

# The production environment is meant for finished, "live" apps.
# Code is not reloaded between requests
config.cache_classes = true


text:
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <title>jqKeyboard</title>
    <link rel="stylesheet" href="css/style.css" />
    <link rel="stylesheet" href="css/jqkeyboard.css" />

    <input type="text" placeholder="" />

    <textarea placeholder=""></textarea>


text:
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
--
-- Database: `photerras_DB`
--
DROP DATABASE IF EXISTS photerras_DB;
CREATE DATABASE photerras_DB;
USE photerras_DB;

CREATE TABLE IF NOT EXISTS `Users` (
  `id` MEDIUMINT(8) unsigned NOT NULL AUTO_INCREMENT,
  `username` VARCHAR(50) NOT NULL,
  `password` VARCHAR(250) NOT NULL,
  `email` VARCHAR(100) NOT NULL,
  `firstname` VARCHAR(50) NOT NULL,
  `lastname` VARCHAR(50) NOT NULL,
  `salt` VARCHAR(100) NOT NULL,
  `createdOn` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY `uid` (`id`),
  UNIQUE KEY `username` (`username`),
  UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=10000 ;

CREATE TABLE IF NOT EXISTS `Photos` (
  `id` MEDIUMINT(8) unsigned NOT NULL AUTO_INCREMENT,
  `uid` MEDIUMINT(8) unsigned NOT NULL,
  `lat` float NOT NULL,
  `lng` float NOT NULL,
  `title` VARCHAR(100) NOT NULL,
  `isPremium` BIT DEFAULT 0,
  `filename` VARCHAR(250) NOT NULL,
  `createdOn` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY `photoid` (`id`),
  FOREIGN KEY (`uid`) REFERENCES Users(`id`),
  CHECK (`lat` >= -90.0 and `lat` <= 90.0),
  CHECK (`lng` >= -180.0 and `lng` <= 180.0)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=10000 ;

CREATE TABLE IF NOT EXISTS `PaymentTypes` (
  `id` INT unsigned NOT NULL AUTO_INCREMENT,
  `desc` varchar(150) NOT NULL,
  `code` varchar (3) NOT NULL,
  PRIMARY KEY `typeid` (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=0 ;

CREATE TABLE IF NOT EXISTS `Payments` (
  `id` MEDIUMINT(8) unsigned NOT NULL AUTO_INCREMENT,
  `uid` MEDIUMINT(8) unsigned NOT NULL,
  `typeid` INT unsigned NOT NULL,
  `createdOn` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY `id` (`id`),
  FOREIGN KEY (`uid`) REFERENCES Users(`id`),
  FOREIGN KEY (`typeid`) REFERENCES PaymentTypes(`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=10000 ;

INSERT INTO `Users` (`username`, `password`, `email`, `firstname`, `lastname`, `salt`) VALUES
('Rphello101', 'FSE', 'aowdija', '', '', ''),
('testuser', '123456', 'ggggg', '', '', ''),
('andrew', '123456', 'fffff', '', '', ''),
('test111', 'dddd', 'aherzberg5@gmail.com', 'Andrew', 'Herzberg', ''),
('rapratt', '123456', 'asdf@asdf', 'Reese', 'Pratt', ''),
('rapratt101', '123456', 'asdf@asdff', 'Reese3', 'Pratt3', ''),
('wtneal', 'S3cur3', 'wtneal@asu.edu', 'Weston', 'Neal', ''),
('Kurvani', 'fse301', 'kkeyvan1@asu.edu', 'Kurosh', 'Keyvani', '');

INSERT INTO `PaymentTypes` (`desc`, `code`) VALUES
('Premium Photo', 'pp'),
('Increase Photo Limit', 'il');


text:
--TEST--
Test imap_8bit() function : basic functionality
--SKIPIF--
<?php
extension_loaded('imap') or die('skip imap extension not available in this build');
?>
--FILE--
<?php
/* Prototype  : string imap_8bit  ( string $string  )
 * Description: Convert an 8bit string to a quoted-printable string.
 * Source code: ext/imap/php_imap.c
 */

echo "*** Testing imap_8bit() : basic functionality ***\n";

var_dump(imap_8bit("String with CRLF at end \r\n"));
//NB this appears to be a bug in cclient; a space at end of string should be encoded as =20
var_dump(imap_8bit("String with space at end "));
var_dump(imap_8bit("String with tabs \t\t in middle"));
var_dump(imap_8bit("String with tab at end \t"));
var_dump(imap_8bit("\x00\x01\x02\x03\x04\xfe\xff\x0a\x0d"));

?>
===Done===
--EXPECT--
*** Testing imap_8bit() : basic functionality ***
string(28) "String with CRLF at end=20
"
string(25) "String with space at end "
string(33) "String with tabs =09=09 in middle"
string(26) "String with tab at end =09"
string(27) "=00=01=02=03=04=FE=FF=0A=0D"
===Done===


text:
@implementation NSImage (GrowlAdditions)

- (NSImage *) flippedImage
{
    NSImage *l_result = [[NSImage alloc] initWithSize:[self size]];
    [l_result lockFocus];
    [[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationNone];
    [[NSGraphicsContext currentContext] setShouldAntialias:NO];
    NSRect l_target = NSZeroRect;
    l_target.size = [self size];

    NSAffineTransform* xform = [NSAffineTransform transform];
    [xform translateXBy:0.0 yBy:l_target.size.height];
    [xform scaleXBy:1.0 yBy:-1.0];
    [xform concat];

    [self drawInRect:l_target fromRect:l_target operation:NSCompositeCopy fraction:1.0f];
    [l_result unlockFocus];

    return [l_result autorelease];
}

- (NSImage *) imageSizedToDimension:(int)dimension
{
	NSSize imageSize = [self size];

	if ((imageSize.width <= dimension) && (imageSize.height <= dimension))
		return self;

	return [self imageSizedToDimensionScalingUp:dimension];
}

- (NSImage *) imageSizedToDimensionScalingUp:(int)dimension
{
	NSSize imageSize = [self size];
	double ratio = 1;

	if (imageSize.width > imageSize.height) {
		ratio = imageSize.height / imageSize.width;
		imageSize.width = dimension;
		imageSize.height = (CGFloat)(dimension * ratio);
	}
	else {
		ratio = imageSize.width / imageSize.height;
		imageSize.height = dimension;
		imageSize.width = (CGFloat)(dimension * ratio);
	}

	NSImage *result = [[[NSImage alloc] initWithSize:imageSize] autorelease];
	[result lockFocus];
	[[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];

	NSRect destRect = NSZeroRect;
	destRect.size = imageSize;
	NSRect sourceRect = NSZeroRect;
	sourceRect.size = [self size];

	[self drawInRect:destRect fromRect:sourceRect operation:NSCompositeCopy fraction:1.0f];

	[result unlockFocus];

	return result;
}

- (NSImage *) imageSizedToDimensionSquaring:(int)dimension
{
	NSSize imageSize = [self size];
	double ratio = 1;

	if (imageSize.width > imageSize.height) {
		ratio = imageSize.height / imageSize.width;
		imageSize.width = dimension;
		imageSize.height = (CGFloat)(dimension * ratio);
	}
	else {
		ratio = imageSize.width / imageSize.height;
		imageSize.height = dimension;
		imageSize.width = (CGFloat)(dimension * ratio);
	}

	NSSize finalSize = NSMakeSize(dimension, dimension);

	NSImage *result = [[[NSImage alloc] initWithSize:finalSize] autorelease];
	[result lockFocus];
	[[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];

	NSRect destRect = NSZeroRect;
	destRect.size = imageSize;

	destRect.origin.y = truncf((float)(dimension - destRect.size.height) / 2);
	destRect.origin.x = truncf((float)(dimension - destRect.size.width) / 2);

	NSRect sourceRect = NSZeroRect;
	sourceRect.size = [self size];

	[self drawInRect:destRect fromRect:sourceRect operation:NSCompositeCopy fraction:1.0f];

	[result unlockFocus];

	return result;
}

- (void) drawInRect:(NSRect)rect
{
	NSRect sourceRect = NSZeroRect;
	sourceRect.size = [self size];
	[self drawInRect:rect fromRect:sourceRect operation:NSCompositeSourceOver fraction:1.0f];
}

@end


text:
from tinkerforge.bricklet_temperature import BrickletTemperature
from tinkerforge.bricklet_temperature_ir import BrickletTemperatureIR
from tinkerforge.bricklet_uv_light import BrickletUVLight
from tinkerforge.bricklet_humidity import BrickletHumidity
from tinkerforge.bricklet_voltage_current import BrickletVoltageCurrent
from tinkerforge.bricklet_sound_intensity import BrickletSoundIntensity
from tinkerforge.bricklet_ambient_light_v2 import BrickletAmbientLightV2
from tinkerforge.bricklet_distance_ir import BrickletDistanceIR
from tinkerforge.bricklet_co2 import BrickletCO2
from tinkerforge.bricklet_color import BrickletColor
from tinkerforge.bricklet_barometer import BrickletBarometer
from tinkerforge.bricklet_line import BrickletLine
from tinkerforge.bricklet_hall_effect import BrickletHallEffect
from tinkerforge.bricklet_accelerometer import BrickletAccelerometer
from tinkerforge.bricklet_moisture import BrickletMoisture
from tinkerforge.bricklet_dual_relay import BrickletDualRelay
from tinkerforge.bricklet_motion_detector import BrickletMotionDetector
from tinkerforge.bricklet_rgb_led_button import BrickletRGBLEDButton
from tinkerforge.bricklet_dual_button import BrickletDualButton
from tinkerforge.bricklet_motion_detector_v2 import BrickletMotionDetectorV2
from tinkerforge.bricklet_rotary_poti import BrickletRotaryPoti
from tinkerforge.bricklet_tilt import BrickletTilt
from tinkerforge.bricklet_distance_us import BrickletDistanceUS
from tinkerforge.bricklet_rotary_encoder_v2 import BrickletRotaryEncoderV2
from tinkerforge.bricklet_linear_poti import BrickletLinearPoti
from tinkerforge.bricklet_thermal_imaging import BrickletThermalImaging
from tinkerforge.bricklet_line import BrickletLine
from tinkerforge.bricklet_humidity_v2 import BrickletHumidityV2
from tinkerforge.brick_imu_v2 import BrickIMUV2

SENSORS = {
    "temp": {
        "name": "Temperature",
        "class": BrickletTemperature,
        "units": "C",
        "brick_tag": "Temperature_Sensor",
        "value_func": "get_temperature",
        "multiplier": 0.01,
        "callback_func": "CALLBACK_TEMPERATURE",
        "variance": 1,
    },
    "ir_temp": {
        "name": "IR Temperature",
        "class": BrickletTemperatureIR,
        "units": "degC",
        "brick_tag": "IRTemperature_Sensor",
        "value_func": "get_object_temperature",
        "multiplier": 0.1,
        "callback_func": "CALLBACK_OBJECT_TEMPERATURE",
        "variance": 1,
    },
    "uv": {
        "name": "Ultraviolet",
        "class": BrickletUVLight,
        "units": "nanoW/cm2",
        "brick_tag": "UV_Light",
        "value_func": "get_uv_light",
    },
    "humidity": {
        "name": "Humidity",
        "class": BrickletHumidity,
        "units": "%RH",
        "brick_tag": "Humidity_Sensor",
        "value_func": "get_humidity",
        "multiplier": 0.1,
        "callback_func": "CALLBACK_HUMIDITY",
    },
    "light": {
        "name": "Ambient Light",
        "class": BrickletAmbientLightV2,
        "units": "lux",
        "brick_tag": "LightingSystem_Illuminance_Sensor",
        "value_func": "get_illuminance",
        "multiplier": 0.01,
        "callback_func": "CALLBACK_ILLUMINANCE",
    },
    "sound": {
        "name": "Sound Intensity",
        "class": BrickletSoundIntensity,
        "units": "",
        "brick_tag": "Noise_Sensor",
        "value_func": "get_intensity",
        "callback_func": "CALLBACK_INTENSITY",
        "publish_limit": 30,
        "variance": 400,
    },
    "co2": {
        "name": "Carbon Dioxide",
        "class": BrickletCO2,
        "units": "ppm",
        "brick_tag": "CO2_Sensor",
        "value_func": "get_co2_concentration",
        "callback_func": "CALLBACK_CO2_CONCENTRATION",
        "publish_limit": 10,
        "variance": 50,
    },
    "voltage": {
        "name": "Voltage",
        "class": BrickletVoltageCurrent,
        "units": "V",
        "brick_tag": "Electrical_Power_Meter",
        "value_func": "get_voltage",
        "multiplier": 0.001,
        "value_offset": 0,
        "callback_func": "CALLBACK_VOLTAGE",
    },
    "current": {
        "name": "Current",
        "class": BrickletVoltageCurrent,
        "units": "A",
        "brick_tag": "Electrical_Power_Meter",
        "value_func": "get_current",
        "multiplier": 0.001,
        "callback_func": "CALLBACK_CURRENT",
    },
    "power": {
        "name": "Power",
        "class": BrickletVoltageCurrent,
        "units": "W",
        "brick_tag": "Electrical_Power_Meter",
        "value_func": "get_power",
        "multiplier": 0.001,
        "callback_func": "CALLBACK_POWER",
    },
    "dist": {
        "name": "Desk Height",
        "class": BrickletDistanceIR,
        "units": "cm",
        "brick_tag": "Range_Sensor",
        "value_func": "get_distance",
        "multiplier": 0.1,
        "callback_func": "CALLBACK_DISTANCE",
    },
    "colour": {
        "name": "Colour",
        "class": BrickletColor,
        "units": "",
        "brick_tag": "Colour_Sensor",
        "value_func": "get_color",
        "callback_func": "CALLBACK_COLOR",
    },
    "colour_temp": {
        "name": "Colour Temp",
        "class": BrickletColor,
        "units": "K",
        "brick_tag": "Colour_Temperature_Sensor",
        "value_func": "get_color_temperature",
        "callback_func": "CALLBACK_COLOR_TEMPERATURE",
    },
	"colour_illuminance": {
        "name": "Colour Illuminance",
        "class": BrickletColor,
        "units": "lux",
        "multiplier": 700,
        "brick_tag": "Colour_Illuminance_Sensor",
        "value_func": "get_illuminance",
        "callback_func": "CALLBACK_ILLUMINANCE",
    },
    "air_pressure": {
        "name": "Air Pressure",
        "class": BrickletBarometer,
        "units": "mbar",
        "brick_tag": "Air_Pressure_Sensor",
        "value_func": "get_air_pressure",
        "multiplier": 0.001,
        "callback_func": "CALLBACK_AIR_PRESSURE",
    },
    "reflectivity": {
        "name": "Reflectivity",
        "class": BrickletLine,
        "units": "",
        "brick_tag": "Line_Sensor",
        "value_func": "get_reflectivity",
        "callback_func": "CALLBACK_REFLECTIVITY",
    },
    "magfield": {
        "name": "Magn. Field",
        "class": BrickletHallEffect,
        "units": "",
        "brick_tag": "Magnetic_Field_Sensor",
        "value_func": "get_edge_count",
        "callback_func": "CALLBACK_EDGE_COUNT",
    },
    "acceleration_xyz": {
        "name": "Vibration",
        "class": BrickletAccelerometer,
        "units": "g",
        "brick_tag": "Accelerometer_Sensor",
        "value_func": "get_acceleration",
        "multiplier": 0.001,
        "callback_func": "CALLBACK_ACCELERATION",
    },
    "acceleration_X": {
        "name": "Vibration X-Axis",
        "class": BrickletAccelerometer,
        "units": "g",
        "brick_tag": "Accelerometer_Sensor_X",
        "value_func": "get_acceleration",
        "multiplier": 0.001,
        "callback_func": "CALLBACK_ACCELERATION",
    },
    "acceleration_Y": {
        "name": "Vibration Y-Axis",
        "class": BrickletAccelerometer,
        "units": "g",
        "brick_tag": "Accelerometer_Sensor_Y",
        "value_func": "get_acceleration",
        "multiplier": 0.001,
        "callback_func": "CALLBACK_ACCELERATION",
    },
    "acceleration_Z": {
        "name": "Vibration Z-Axis",
        "class": BrickletAccelerometer,
        "units": "g",
        "brick_tag": "Accelerometer_Sensor_Z",
        "value_func": "get_acceleration",
        "multiplier": 0.001,
        "callback_func": "CALLBACK_ACCELERATION",
    },
    "moisture": {
        "name": "Moisture",
        "class": BrickletMoisture,
        "units": "",
        "brick_tag": "Moisture_Sensor",
        "value_func": "get_moisture_value",
        "callback_func": "CALLBACK_MOISTURE",
    },
    "dual_relay": {
        "name": "Dual Relay Bricklet",
        "class": BrickletDualRelay,
        "units": "",
        "brick_tag": "Relay_Sensor",
        "value_func": "get_state",
    },
    "motion": {
        "name": "Motion Detector",
        "class": BrickletMotionDetector,
        "units": "",
        "brick_tag": "Motion_Detector",
        "value_func": "get_motion_detected",
    },
    "rgb_led_button_colour": {
        "name": "Brightness",
        "class": BrickletRGBLEDButton,
        "units": "",
        "brick_tag": "RGB_LED_Button",
        "value_func": "get_color",
    },
    "rgb_led_button_colour_r": {
        "name": "Red",
        "class": BrickletRGBLEDButton,
        "units": "",
        "brick_tag": "RGB_LED_Button",
        "value_func": "get_color",
    },
    "rgb_led_button_colour_g": {
        "name": "Green",
        "class": BrickletRGBLEDButton,
        "units": "",
        "brick_tag": "RGB_LED_Button",
        "value_func": "get_color",
    },
    "rgb_led_button_colour_b": {
        "name": "Blue",
        "class": BrickletRGBLEDButton,
        "units": "",
        "brick_tag": "RGB_LED_Button",
        "value_func": "get_color",
    },
    "rgb_led_button_state": {
        "name": "RGB LED Button",
        "class": BrickletRGBLEDButton,
        "units": "",
        "brick_tag": "RGB_LED_Button",
        "value_func": "get_button_state",
        "callback_func": "CALLBACK_BUTTON_STATE_CHANGED",
    },
    "dual_button_state": {
        "name": "Dual Button",
        "class": BrickletDualButton,
        "units": "",
        "brick_tag": "Dual_Button",
        "value_func": "get_button_state",
        "callback_func": "CALLBACK_STATE_CHANGED",
    },
    "motion_2": {
        "name": "Motion Detector",
        "class": BrickletMotionDetectorV2,
        "units": "",
        "brick_tag": "Motion_Detector",
        "value_func": "get_motion_detected",
        "callback_func": "CALLBACK_MOTION_DETECTED",
    },
    "rotation_poti": {
        "name": "Rotary Poti",
        "class": BrickletRotaryPoti,
        "units": "",
        "brick_tag": "Rotary_Poti",
        "value_func": "get_position",
        "callback_func": "CALLBACK_POSITION",
    },
    "tilt": {
        "name": "Tilt",
        "class": BrickletTilt,
        "units": "",
        "brick_tag": "Tilt",
        "value_func": "get_tilt_state",
        "callback_func": "CALLBACK_TILT_STATE",
    },
	"dist_us": {
        "name": "Distance US",
        "class": BrickletDistanceUS,
        "units": "cm",
        "brick_tag": "Range_Sensor",
        "value_func": "get_distance_value",
        "multiplier": 0.1,
        "callback_func": "CALLBACK_DISTANCE",
    },
	"rotation_encoder_2": {
        "name": "Rotary Encoder",
        "class": BrickletRotaryEncoderV2,
        "units": "",
        "brick_tag": "Rotary_Encoder",
        "value_func": "get_count",
        "callback_func": "CALLBACK_COUNT",
    },
	"linear_poti": {
		    "name": "Linear Poti",
		    "class": BrickletLinearPoti,
		    "units": "",
		    "brick_tag": "Linear_Poti",
		    "value_func": "get_position",
		    "callback_func": "CALLBACK_POSITION",
	},
	"thermal_image": {
		    "name": "Thermal Imaging",
		    "class": BrickletThermalImaging,
		    "units": "K",
		    "multiplier": 0.01,
		    "brick_tag": "Thermal_Imaging",
		    "value_func": "get_statistics",
	},
	"reflectivity": {
		    "name": "Line",
		    "class": BrickletLine,
		    "units": "",
		    "brick_tag": "Line",
		    "value_func": "get_reflectivity",
		    "callback_func": "CALLBACK_REFLECTIVITY",
	},
	"humidity_v2":{
		    "name": "Humidity",
		    "class": BrickletHumidityV2,
		    "units": "%",
		    "multiplier": 0.01,
		    "brick_tag": "Humidity",
		    "value_func": "get_humidity",
		    "callback_func": "CALLBACK_HUMIDITY",
	},
	"humidity_temp":{
		    "name": "Temperature",
		    "class": BrickletHumidityV2,
		    "units": "degC",
		    "multiplier": 0.01,
		    "brick_tag": "Humidity",
		    "value_func": "get_temperature",
		    "callback_func": "CALLBACK_TEMPERATURE",
	},
    "heading": {
        "name": "Heading",
        "class": BrickIMUV2,
        "units": "deg",
        "brick_tag": "IMU",
        "multiplier":1/16,
        "value_func": "get_orientation",
        "callback_func": "CALLBACK_ORIENTATION",
    },
    "roll": {
        "name": "Roll",
        "class": BrickIMUV2,
        "units": "deg",
        "brick_tag": "IMU",
        "offset": 180,
        "multiplier":2/16,
        "value_func": "get_orientation",
        "callback_func": "CALLBACK_ORIENTATION",
    },
    "pitch": {
        "name": "Pitch",
        "class": BrickIMUV2,
        "units": "deg",
        "brick_tag": "IMU",
        "offset": 180,
        "value_func": "get_orientation",
        "multiplier":1/16,
        "callback_func": "CALLBACK_ORIENTATION",
    },
    "linear_acceleration_X": {
        "name": "Linear Acceleration X-Axis",
        "class": BrickIMUV2,
        "units": "m/s^2",
        "brick_tag": "IMU",
        "value_func": "get_linear_acceleration",
        "multiplier": 0.01,
        "callback_func": "CALLBACK_LINEAR_ACCELERATION",
    },
    "linear_acceleration_Y": {
        "name": "Linear Acceleration Y-Axis",
        "class": BrickIMUV2,
        "units": "m/s^2",
        "brick_tag": "IMU",
        "value_func": "get_linear_acceleration",
        "multiplier": 0.01,
        "callback_func": "CALLBACK_LINEAR_ACCELERATION",
    },
    "linear_acceleration_Z": {
        "name": "Linear Acceleration Z-Axis",
        "class": BrickIMUV2,
        "units": "m/s^2",
        "brick_tag": "IMU",
        "value_func": "get_linear_acceleration",
        "multiplier": 0.01,
        "callback_func": "CALLBACK_LINEAR_ACCELERATION",
    },
    "gravity_acceleration_X": {
        "name": "Gravity X-Axis",
        "class": BrickIMUV2,
        "units": "m/s^2",
        "brick_tag": "IMU",
        "value_func": "get_gravity_vector",
        "multiplier": 0.01,
        "callback_func": "CALLBACK_GRAVITY_VECTOR",
    },
    "gravity_acceleration_Y": {
        "name": "Gravity Y-Axis",
        "class": BrickIMUV2,
        "units": "m/s^2",
        "brick_tag": "IMU",
        "value_func": "get_gravity_vector",
        "multiplier": 0.01,
        "callback_func": "CALLBACK_GRAVITY_VECTOR",
    },
    "gravity_acceleration_Z": {
        "name": "Gravity Z-Axis",
        "class": BrickIMUV2,
        "units": "m/s^2",
        "brick_tag": "IMU",
        "value_func": "get_gravity_vector",
        "multiplier": 0.01,
        "callback_func": "CALLBACK_GRAVITY_VECTOR",
    },
    "IMU_leds":{
        "name": "IMU LEDs",
        "class": BrickIMUV2,
        "brick_tag": "IMU",
        "units": "",
        "value_func": "are_leds_on",
    },
    "IMU_acceleration_Z": {
        "name": "Acceleration Z-Axis",
        "class": BrickIMUV2,
        "units": "m/s^2",
        "brick_tag": "IMU",
        "value_func": "get_acceleration",
        "multiplier": 0.01,
        "callback_func": "CALLBACK_ACCELERATION",
    },
    "IMU_acceleration_X": {
        "name": "Acceleration X-Axis",
        "class": BrickIMUV2,
        "units": "m/s^2",
        "brick_tag": "IMU",
        "value_func": "get_acceleration",
        "multiplier": 0.01,
        "callback_func": "CALLBACK_ACCELERATION",
    },
    "IMU_acceleration_Y": {
        "name": "Acceleration Y-Axis",
        "class": BrickIMUV2,
        "units": "m/s^2",
        "brick_tag": "IMU",
        "value_func": "get_acceleration",
        "multiplier": 0.01,
        "callback_func": "CALLBACK_ACCELERATION",
    },
    "angular_velocity_X": {
        "name": "Angular Velocity X-Axis",
        "class": BrickIMUV2,
        "units": "deg/s",
        "brick_tag": "IMU",
        "value_func": "get_angular_velocity",
        "multiplier": 0.01,
        "callback_func": "CALLBACK_ANGULAR_VELOCITY",
    },
    "angular_velocity_Y": {
        "name": "Angular Velocity Y-Axis",
        "class": BrickIMUV2,
        "units": "deg/s",
        "brick_tag": "IMU",
        "value_func": "get_angular_velocity",
        "multiplier": 0.01,
        "callback_func": "CALLBACK_ANGULAR_VELOCITY",
    },
    "angular_velocity_Z": {
        "name": "Angular Velocity Z-Axis",
        "class": BrickIMUV2,
        "units": "deg/s",
        "brick_tag": "IMU",
        "value_func": "get_angular_velocity",
        "multiplier": 0.01,
        "callback_func": "CALLBACK_ANGULAR_VELOCITY",
    },
    "linear_acceleration_xyz": {
        "name": "Linear Acceleration",
        "class": BrickIMUV2,
        "units": "m/s^2",
        "brick_tag": "IMU",
        "value_func": "get_linear_acceleration",
        "multiplier": 0.01,
        "callback_func": "CALLBACK_LINEAR_ACCELERATION",
    },
    "gravity_acceleration_xyz": {
        "name": "Gravity",
        "class": BrickIMUV2,
        "units": "m/s^2",
        "brick_tag": "IMU",
        "value_func": "get_gravity_vector",
        "multiplier": 0.01,
        "callback_func": "CALLBACK_GRAVITY_VECTOR",
    },
    "IMU_acceleration_xyz": {
        "name": "Acceleration",
        "class": BrickIMUV2,
        "units": "m/s^2",
        "brick_tag": "IMU",
        "value_func": "get_acceleration",
        "multiplier": 0.01,
        "callback_func": "CALLBACK_ACCELERATION",
    },
    "angular_velocity_xyz": {
        "name": "Angular Velocity",
        "class": BrickIMUV2,
        "units": "deg/s",
        "brick_tag": "IMU",
        "value_func": "get_angular_velocity",
        "multiplier": 0.01,
        "callback_func": "CALLBACK_ANGULAR_VELOCITY",
    },
    "quaternion_W": {
        "name": "Quaternion W-Axis",
        "class": BrickIMUV2,
        "units": "",
        "brick_tag": "IMU",
        "value_func": "get_quaternion",
        "multiplier": 1/16383.0,
        "callback_func": "CALLBACK_QUATERNION",
    },
    "quaternion_X": {
        "name": "Quaternion X-Axis",
        "class": BrickIMUV2,
        "units": "",
        "brick_tag": "IMU",
        "value_func": "get_quaternion",
        "multiplier": 1/16383.0,
        "callback_func": "CALLBACK_QUATERNION",
    },
    "quaternion_Y": {
        "name": "Quaternion Y-Axis",
        "class": BrickIMUV2,
        "units": "",
        "brick_tag": "IMU",
        "value_func": "get_quaternion",
        "multiplier": 1/16383.0,
        "callback_func": "CALLBACK_QUATERNION",
    },
    "quaternion_Z": {
        "name": "Quaternion Z-Axis",
        "class": BrickIMUV2,
        "units": "",
        "brick_tag": "IMU",
        "value_func": "get_quaternion",
        "multiplier": 1/16383.0,
        "callback_func": "CALLBACK_QUATERNION",
    },
    "IMU_temp":{
        "name": "IMU Temperature",
        "class": BrickIMUV2,
        "brick_tag": "IMU",
        "units": "degC",
        "value_func": "get_temperature",
    },
    "magnetic_field_X": {
        "name": "Magnetic Field X-Axis",
        "class": BrickIMUV2,
        "units": "nanoT",
        "brick_tag": "IMU",
        "value_func": "get_magnetic_field",
        "multiplier": 1/16.0,
        "callback_func": "CALLBACK_MAGNETIC_FIELD",
    },
    "magnetic_field_Y": {
        "name": "Magnetic Field Y-Axis",
        "class": BrickIMUV2,
        "units": "nanoT",
        "brick_tag": "IMU",
        "value_func": "get_magnetic_field",
        "multiplier": 1/16.0,
        "callback_func": "CALLBACK_MAGNETIC_FIELD",
    },
    "magnetic_field_Z": {
        "name": "Magnetic Field Z-Axis",
        "class": BrickIMUV2,
        "units": "nanoT",
        "brick_tag": "IMU",
        "value_func": "get_magnetic_field",
        "multiplier": 1/16.0,
        "callback_func": "CALLBACK_MAGNETIC_FIELD",
    },
    "magnetic_field_xyz": {
        "name": "Magnetic Field",
        "class": BrickIMUV2,
        "units": "nanoT",
        "brick_tag": "IMU",
        "value_func": "get_magnetic_field",
        "multiplier": 1/16.0,
        "callback_func": "CALLBACK_MAGNETIC_FIELD",
    },
}


text:
module AnsiblePlaybookHelper::TextualSummary
  include TextualMixins::TextualGroupTags
  include TextualMixins::TextualName
  include TextualMixins::TextualDescription

  def textual_group_properties
    TextualGroup.new(_("Properties"), %i[name description created updated])
  end

  def textual_group_relationships
    TextualGroup.new(_("Relationships"), %i[provider repository])
  end

  def textual_group_smart_management
    TextualTags.new(_("Smart Management"), %i[tags])
  end

  def textual_created
    {:label => _("Created On"), :value => format_timezone(@record.created_at)}
  end

  def textual_updated
    {:label => _("Updated On"), :value => format_timezone(@record.updated_at)}
  end

  def textual_provider
    {:label => _("Provider"), :value => @record.manager.try(:name)}
  end

  def textual_repository
    h = {:label => _("Repository")}
    if role_allows?(:feature => "embedded_configuration_script_source_view") && @record.configuration_script_source.try(:name)
      h.update(:value => @record.configuration_script_source.name,
               :icon  => "pficon pficon-repository",
               :link  => url_for_only_path(:controller => 'ansible_repository', :action => 'show', :id => @record.configuration_script_source),
               :title => _("Show Repository"))
    end
    h
  end
end


text:
package org.springframework.cloud.deployer.spi.test.app;

import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * Configuration properties for the IntegrationTestProcessor app.
 *
 * @author Eric Bottard
 */
@ConfigurationProperties
public class DeployerIntegrationTestProperties {

	public static final String FUNNY_CHARACTERS = "&'\"|< é\\(";

	/**
	 * The delay in milliseconds to stall the initialization of this app.
	 * Useful for testing the 'deploying' state of a app.
	 */
	private int initDelay = 0;

	/**
	 * The delay in milliseconds after which this app will kill itself.
	 *
-1 means don't kill

	 */
	private int killDelay = -1;

	/**
	 * The exit code used when this app will kill itself.
	 *
Set this to 0 for normal exit

	 */
	private int exitCode = 1;

	/**
	 * If not empty, only the app intances whose number(s) are contained in this set
	 * will behave according to the other configuration parameters.
	 */
	private Set<Integer> matchInstances = new HashSet<>();

	/**
	 * If not null, this property will be tested against {@link #FUNNY_CHARACTERS}.
	 * This makes sure that a deployer knows how to properly propagate application properties, including
	 * those that contain chars that often require some form of escaping.
	 */
	private String parameterThatMayNeedEscaping;

	/**
	 * If not null, this property will be tested against {@link #FUNNY_CHARACTERS}.
	 * This makes sure that a deployer knows how to properly propagate deployment properties, including
	 * those that contain chars that often require some form of escaping.
	 */
	private String commandLineArgValueThatMayNeedEscaping;

	@Value("${INSTANCE_INDEX:${CF_INSTANCE_INDEX:0}}")
	private Integer instanceIndex;

	public int getInitDelay() {
		return initDelay;
	}

	public void setInitDelay(int initDelay) {
		this.initDelay = initDelay;
	}

	public int getKillDelay() {
		return killDelay;
	}

	public void setKillDelay(int killDelay) {
		this.killDelay = killDelay;
	}

	public int getExitCode() {
		return exitCode;
	}

	public void setExitCode(int exitCode) {
		this.exitCode = exitCode;
	}

	public Set<Integer> getMatchInstances() {
		return matchInstances;
	}

	public void setMatchInstances(Set<Integer> matchInstances) {
		this.matchInstances = matchInstances;
	}

	public String getParameterThatMayNeedEscaping() {
		return parameterThatMayNeedEscaping;
	}

	public void setParameterThatMayNeedEscaping(String parameterThatMayNeedEscaping) {
		this.parameterThatMayNeedEscaping = parameterThatMayNeedEscaping;
	}

	public Integer getInstanceIndex() {
		return instanceIndex;
	}

	public void setInstanceIndex(Integer instanceIndex) {
		this.instanceIndex = instanceIndex;
	}

	public String getCommandLineArgValueThatMayNeedEscaping() {
		return commandLineArgValueThatMayNeedEscaping;
	}

	public void setCommandLineArgValueThatMayNeedEscaping(String commandLineArgValueThatMayNeedEscaping) {
		this.commandLineArgValueThatMayNeedEscaping = commandLineArgValueThatMayNeedEscaping;
	}
}


text:
package com.palantir.common.streams;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * Java 8 {@link Collector} for immutable collections.
 */
public final class MoreCollectors {

    /**
     * This collector has similar semantics to {@link Collectors#toSet} except that the resulting set will be
     * immutable.
     *
     * @deprecated Use {@link ImmutableSet#toImmutableSet}, available in Guava 21+
     */
    @Deprecated
    public static <T> Collector<T, ?, Set<T>> toImmutableSet() {
        return Collector.of(
                ImmutableSet::<T>builder,
                ImmutableSet.Builder::<T>add,
                (left, right) -> left.addAll(right.build()),
                ImmutableSet.Builder::build,
                Collector.Characteristics.UNORDERED);
    }

    /**
     * This collector has similar semantics to {@link Collectors#toList} except that the resulting list will be
     * immutable.
     *
     * @deprecated Use {@link ImmutableList#toImmutableList}, available in Guava 21+
     */
    @Deprecated
    public static <T> Collector<T, ?, List<T>> toImmutableList() {
        return Collector.of(
                ImmutableList::<T>builder,
                ImmutableList.Builder::<T>add,
                (left, right) -> left.addAll(right.build()),
                ImmutableList.Builder::build);
    }

    /**
     * This collector has similar semantics to {@link Collectors#toMap} except that the resulting map will be
     * immutable. Duplicate keys will result in an error.
     *
     * @deprecated Use {@link ImmutableMap#toImmutableMap}, available in Guava 21+
     */
    @Deprecated
    public static <T, K, V> Collector<T, ?, Map<K, V>> toImmutableMap(
            Function<T, K> keyFunction, Function<T, V> valueFunction) {
        return Collector.of(
                ImmutableMap::<K, V>builder,
                (builder, value) -> builder.put(keyFunction.apply(value), valueFunction.apply(value)),
                (left, right) -> left.putAll(right.build()),
                ImmutableMap.Builder::build);
    }

    private MoreCollectors() {}
}


text:
package im.mange.driveby.conditions

import im.mange.driveby.browser.UnSafeBrowser
import im.mange.driveby.{By, Condition, Describer}

case class ElementHidden(by: By) extends Condition {
  import Describer._

  def expectation = expect("ElementHidden", List(by.toString))
  def isSatisfied(browser: UnSafeBrowser) = { browser.isDisplayed(by) == false }
  def describeFailure(browser: UnSafeBrowser) = { expectation + butWas(() => if (browser.exists(by)) "visible" else "does not exist") }
}


text:
package client

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net"
	"net/http"
	"strconv"

	"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/health"
)

// ErrPodInfoNotAvailable may be returned when the requested pod info is not available.
var ErrPodInfoNotAvailable = errors.New("no pod info available")

// KubeletClient is an interface for all kubelet functionality
type KubeletClient interface {
	KubeletHealthChecker
	PodInfoGetter
}

// KubeletHealthchecker is an interface for healthchecking kubelets
type KubeletHealthChecker interface {
	HealthCheck(host string) (health.Status, error)
}

// PodInfoGetter is an interface for things that can get information about a pod's containers.
// Injectable for easy testing.
type PodInfoGetter interface {
	// GetPodInfo returns information about all containers which are part
	// Returns an api.PodInfo, or an error if one occurs.
	GetPodInfo(host, podNamespace, podID string) (api.PodInfo, error)
}

// HTTPKubeletClient is the default implementation of PodInfoGetter and KubeletHealthchecker, accesses the kubelet over HTTP.
type HTTPKubeletClient struct {
	Client      *http.Client
	Port        uint
	EnableHttps bool
}

func NewKubeletClient(config *KubeletConfig) (KubeletClient, error) {
	transport := http.DefaultTransport
	if config.CAFile != "" {
		t, err := NewClientCertTLSTransport(config.CertFile, config.KeyFile, config.CAFile)
		if err != nil {
			return nil, err
		}
		transport = t
	}

	c := &http.Client{Transport: transport}
	return &HTTPKubeletClient{
		Client:      c,
		Port:        config.Port,
		EnableHttps: config.EnableHttps,
	}, nil
}

func (c *HTTPKubeletClient) url(host string) string {
	scheme := "http://"
	if c.EnableHttps {
		scheme = "https://"
	}

	return fmt.Sprintf(
		"%s%s",
		scheme,
		net.JoinHostPort(host, strconv.FormatUint(uint64(c.Port), 10)))
}

// GetPodInfo gets information about the specified pod.
func (c *HTTPKubeletClient) GetPodInfo(host, podNamespace, podID string) (api.PodInfo, error) {
	request, err := http.NewRequest(
		"GET",
		fmt.Sprintf(
			"%s/podInfo?podID=%s&podNamespace=%s",
			c.url(host),
			podID,
			podNamespace),
		nil)
	if err != nil {
		return nil, err
	}
	response, err := c.Client.Do(request)
	if err != nil {
		return nil, err
	}
	defer response.Body.Close()
	if response.StatusCode == http.StatusNotFound {
		return nil, ErrPodInfoNotAvailable
	}
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return nil, err
	}
	// Check that this data can be unmarshalled
	info := api.PodInfo{}
	err = json.Unmarshal(body, &info)
	if err != nil {
		return nil, err
	}
	return info, nil
}

func (c *HTTPKubeletClient) HealthCheck(host string) (health.Status, error) {
	return health.DoHTTPCheck(fmt.Sprintf("%s/healthz", c.url(host)), c.Client)
}

// FakeKubeletClient is a fake implementation of KubeletClient which returns an error
// when called.  It is useful to pass to the master in a test configuration with
// no kubelets.
type FakeKubeletClient struct{}

// GetPodInfo is a fake implementation of PodInfoGetter.GetPodInfo.
func (c FakeKubeletClient) GetPodInfo(host, podNamespace string, podID string) (api.PodInfo, error) {
	return api.PodInfo{}, errors.New("Not Implemented")
}

func (c FakeKubeletClient) HealthCheck(host string) (health.Status, error) {
	return health.Unknown, errors.New("Not Implemented")
}


text:
using SX.WebCore.MvcControllers;

namespace GE.WebUI.Areas.Admin.Controllers
{
    public sealed class UsersController : SxUsersController
    {

    }
}


text:
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>

<link href="doc-style.css" type="text/css" rel="StyleSheet">

		Local Properties

Managed Object Types	Data Object Types	All Properties	All Methods

Data Object - ClusterInitialPlacementAction

Extends

ClusterAction

See also

HostSystem, ResourcePool

Since

VI API 2.5

Data Object
                  Description

         Describes an initial placement of a single virtual machine

Properties

	          Name

	          Type

	          Description

pool*	ManagedObjectReference

 to a
                  ResourcePool

         The resource pool to place the virtual machine into in case this
       action is for migrating from outside cluster.

targetHost	ManagedObjectReference

 to a
                  HostSystem

         The host where the virtual machine should be initially placed.

						Properties inherited from ClusterAction

target, type

						Properties inherited from DynamicData

dynamicProperty, dynamicType

*Need not be set

Show WSDL type definition

<textarea cols="20" rows="10" name="wsdl-textarea" wrap="off" readonly="1" id="wsdl-textarea">         <complexType xmlns="http://www.w3.org/2001/XMLSchema" xmlns:vim25="urn:vim25" name="ClusterInitialPlacementAction">
            <complexContent>
               <extension base="vim25:ClusterAction">
                  <sequence>
                     <element name="targetHost" type="vim25:ManagedObjectReference"/>
                     <element name="pool" type="vim25:ManagedObjectReference" minOccurs="0"/>
                  </sequence>
               </extension>
            </complexContent>
         </complexType></textarea>

Top of page		Local Properties

Managed Object Types	Data Object Types	All Properties	All Methods