text:
FGameMenuPage::FGameMenuPage()
{
	SelectedIndex = INDEX_NONE;
}

TSharedRef<FGameMenuItem> FGameMenuPage::AddMenuItem(const FText& Text, TSharedPtr<FGameMenuPage> InSubMenu)
{
	TSharedRef<FGameMenuItem> Item = MakeShareable(new FGameMenuItem(Text));
	Item->SubMenu = InSubMenu;
	MenuItems.Add(Item);
	return Item;
}

void FGameMenuPage::ShowRootMenu()
{
	RootMenuPageWidget->BuildAndShowMenu(this->AsShared());
	// Select the first item in the menu
	RootMenuPageWidget->SelectItem(0);
}

bool FGameMenuPage::InitialiseRootMenu(APlayerController* InPCOwner, const FString& InStyleName, UGameViewportClient* InGameViewport)
{
	if (FModuleManager::Get().IsModuleLoaded("GameMenuBuilder") == false)
	{
		FModuleManager::LoadModuleChecked<FGameMenuBuilderModule>("GameMenuBuilder");
	}

	TArray<FString> SplitString;
	InStyleName.ParseIntoArray(SplitString, TEXT("/"), true);
	FString StylePath = InStyleName.Replace(*SplitString[SplitString.Num() - 1],TEXT(""));
	StylePath.RemoveFromEnd("/");
	FGameMenuBuilderStyle::Initialize(StylePath);

	FString InStyleName2(TEXT("/Game/UI/Styles/PlatformerMenuStyle"));
	bool bResult = false;
	if (InGameViewport)
	{
		SAssignNew(RootMenuPageWidget, SGameMenuPageWidget)
			.MenuStyle(&FGameMenuBuilderStyle::Get().GetWidgetStyle<FGameMenuStyle>(*InStyleName))
			.Cursor(EMouseCursor::Default)
			.PCOwner(TWeakObjectPtr<APlayerController>(InPCOwner));

		InGameViewport->AddViewportWidgetContent(
			SNew(SWeakWidget)
			.PossiblyNullContent(RootMenuPageWidget));
		PCOwner = InPCOwner;
		RootMenuPageWidget->MyGameViewport = InGameViewport;
		bResult = true;
	}
	return bResult;
}

void FGameMenuPage::DestroyRootMenu()
{
	if (RootMenuPageWidget.IsValid() && RootMenuPageWidget->MyGameViewport.IsValid())
	{
		RootMenuPageWidget->ResetMenu();
		RootMenuPageWidget->MyGameViewport->RemoveViewportWidgetContent(RootMenuPageWidget.ToSharedRef());
		RootMenuPageWidget = nullptr;
		MenuItems.Empty();
	}
}

int32 FGameMenuPage::NumItems() const
{
	return MenuItems.Num();
}

TSharedPtr<FGameMenuItem> FGameMenuPage::GetItem(int32 Index) const
{
	check(IsValidMenuEntryIndex(Index));
	return MenuItems[Index];
}

bool FGameMenuPage::IsValidMenuEntryIndex(int32 Index) const
{
	return MenuItems.IsValidIndex(Index);
}

void FGameMenuPage::LockControls(bool bLockState)
{
	if (RootMenuPageWidget.IsValid())
	{
		RootMenuPageWidget->LockControls(bLockState);
	}
}

void FGameMenuPage::HideMenu()
{
	RootMenuPageWidget->HideMenu();
}

void FGameMenuPage::RemoveAllItems()
{
	MenuItems.Empty();
}


text:
s.Controls.Touch = function() {
  this.handleTouches = this.handleTouches.bind(this);
  this.setScreenVariables = this.setScreenVariables.bind(this);

  this.fire = false;

  // Joysticks
  var joyWidth = window.innerWidth / 3.5;
  var joyOptions = {
    // binary: true, // Don't calculate joystick position along a continuum (8 position joystick)
    width: joyWidth,
    deadZone: joyWidth * 0.25,
    margin: joyWidth * 0.15
  };

  this.rightStick = new s.Controls.Touch.Joystick(joyOptions);
  this.leftStick = new s.Controls.Touch.Joystick(joyOptions);

  // Buttons
  var buttonWidth = joyWidth * 0.40;
  var buttonOptions = {
    width: buttonWidth,
    margin: buttonWidth * 0.025
  };

  var fireButtonWidth = joyWidth * 0.50
  this.fireButton = new s.Controls.Touch.Button({
    width: fireButtonWidth,
    margin: fireButtonWidth * 0.025,
    fill: 'rgba(255, 0, 0, 0.5)',
    color: 'red'
  });

  // Set parameters
  this.setScreenVariables();

  // Listen to events
  window.addEventListener('touchstart', this.handleTouches, false);
  window.addEventListener('touchmove', this.handleTouches, false);
  window.addEventListener('touchend', this.handleTouches, false);
  window.addEventListener('resize', this.setScreenVariables, false);
};

s.Controls.Touch.prototype.destruct = function() {
  window.removeEventListener('resize', this.setScreenVariables, false);
  window.removeEventListener('touchstart', this.handleTouches, false);
  window.removeEventListener('touchmove', this.handleTouches, false);
  window.removeEventListener('touchend', this.handleTouches, false);
};

s.Controls.Touch.prototype.setScreenVariables = function() {
  this.width = window.innerWidth;
  this.height = window.innerHeight;

  // Use previously passed margin
  var joyWidth = this.rightStick.width;
  var joyMargin = this.rightStick.margin;

  var fireButtonWidth = this.fireButton.width;

  var joyX = this.width - joyMargin - joyWidth/2;
  var joyY = this.height - joyMargin - joyWidth/2;

  var leftControlX = joyMargin + joyWidth/2;

  this.rightStick.configure({
    position: {
      x: joyX,
      y: joyY
    }
  });

  this.leftStick.configure({
    position: {
      x: leftControlX,
      y: joyY
    }
  });

  this.fireButton.configure({
    position: {
      x: leftControlX,
      y: joyY
    }
  });
};

s.Controls.Touch.prototype.handleTouches = function(evt) {
  // Stop scrolling
  evt.preventDefault();

  this.fire = false;

  // Reset state before trying each touch
  this.rightStick.reset();
  this.leftStick.reset();
  this.fireButton.reset();

  for (var i = 0; i < evt.touches.length; i++) {
    var touch = evt.touches[i];

    this.rightStick.update(touch);
    this.leftStick.update(touch);
    this.fireButton.update(touch);
  }

  this.pitch = 0;
  this.roll = 0;
  this.yaw = 0;
  this.thrust = 0;
  this.fire = false;

  this.pitch = this.rightStick.y;
  this.yaw = -1 * this.rightStick.x;

  // If Y is outside the deadzone, give full thrust
  if (this.leftStick.y > 0) {
    this.thrust = 1;
  }
  else if (this.leftStick.y < 0) {
    this.thrust = -1;
  }

  // If X is outside the deadzone, give partial roll
  if (this.leftStick.x > 0) {
    this.roll = 0.75;
  }
  else if (this.leftStick.x < 0) {
    this.roll = -0.75;
  }

  this.fire = this.fireButton.pressed;
};

redpajama_set_name: RedPajamaGithub


text:
package com.github.binarywang.wxpay.bean.result;

import com.thoughtworks.xstream.annotations.XStreamAlias;

/**
 *

 * 关闭订单结果对象类
 * Created by Binary Wang on 2016-10-27.
 * @author binarywang(Binary Wang)
 *

 */
@XStreamAlias("xml")
public class WxPayOrderCloseResult extends WxPayBaseResult {

    /**
     * 业务结果描述
     */
    @XStreamAlias("result_msg")
    private String resultMsg;

    public String getResultMsg() {
        return this.resultMsg;
    }

    public void setResultMsg(String resultMsg) {
        this.resultMsg = resultMsg;
    }
}


text:
__author__ = 'Lothilius'

import csv
import os
import numpy as np
import matplotlib.pyplot as plt
import skimage as ski
import math
import getpass
import time

from skimage import data, filter
from skimage.color import rgb2gray
from skimage.transform import hough_circle
from skimage.feature import peak_local_max
from skimage.draw import circle_perimeter

measured_data = []
start = time.time()
np.set_printoptions(suppress=True)

#Pull data from CSV file
def arrayFromFile(filename):
    """Given an external file containing numbers,
            create an array from those numbers."""
    dataArray = []
    with open(filename, 'r+') as csvfile:
        spamreader = csv.reader(csvfile, delimiter=',', quotechar='"')
        for row in spamreader:
            dataArray.append(row)
    return dataArray[1565]

# Return Radius given two peaks on the same ring
def radius(peakL, peakR):
    rad = (peakR - peakL)
    return rad

#write an array to a file.
def arrayTofile(dataArray, fileNum):
    fileName = "/Users/admin/Dropbox/School/Spring-2014/PHY-474/Labs/Zeeman/play_data/dataManipulation/ImageData" + fileNum + "_a.csv"
    print(fileName)
    with open(fileName, 'w+', newline='') as csvfile:
        linewriter = csv.writer(csvfile, delimiter=",")
        for each in dataArray:
            linewriter.writerow([each])
    print("done")

#Create file from array with finaldata.csv as the name and append.
def dataTofile(dataArray):
    fileName = "Finaldata.csv"
    with open(fileName, 'w') as csvfile:
        linewriter = csv.writer(csvfile, delimiter=",")
        linewriter.writerows(dataArray)
    csvfile.close()

#Create array of data for creating the Delta enregy function.
def dataArray(peakL1, peakR1, peakL2, peakI, peakO):
    rad1 = radius(peakL1, peakR1) / 2
    halfPoint = peakL1 + rad1
    rad2 = radius(peakL2, halfPoint)
    radI = radius(peakI, halfPoint)
    radO = radius(peakO, halfPoint)
    radArray = [rad1, rad2, radI, radO]
    return radArray

def ternarySearch(f, left, right, absolutePrecision):
    """Ternary Search algorithm search for peak within a bound.

    Return location of peak and value
    """

    #left and right are the current bounds; the maximum is between them
    if (right - left) <= absolutePrecision or (right - left) <= 2:
        return round((left + right) / 2), f[(left + right) / 2]

    leftThird = (2 * left + right) / 3
    rightThird = (left + 2 * right) / 3

    if f[leftThird] < f[rightThird]:
        return ternarySearch(f, leftThird, right, absolutePrecision)
    else:
        return ternarySearch(f, left, rightThird, absolutePrecision)

def jpg_to_array(file_path, file_name):
    """Processes jpg file

    Return the numpy array of pixel values of the image.
    """
    full_path = file_path + file_name
    image = data.load(full_path)
    #plt.imshow(image)
    #plt.show()
    return image

def strip_color(image_rgb1, color_of_interest, sig):
    """Remove all but one color

    Return monochromatic image and image with canny filter
    """

    image_rgb = ski.img_as_ubyte(image_rgb1)

    if color_of_interest == 0:
        colorow = np.array([[1.0, 0, 0]] * len(image_rgb[0]))
    elif color_of_interest == 1:
        colorow = np.array([[0, 1.0, 0]] * len(image_rgb[0]))
    elif color_of_interest == 2:
        colorow = np.array([[0, 0, 1.0]] * len(image_rgb[0]))

    image_stripped = np.array([colorow] * len(image_rgb))

    image_stripped = image_stripped * image_rgb

    image_stripped = rgb2gray(image_stripped)

    # Todo generalize the sigma and threshold values based on the color and the image.
    image_proc = ski.filter.canny(image_stripped, sigma=sig, low_threshold=0, high_threshold=7)

    #Uses up the majority of time.
    img, radii = get_center(image_proc)

    print('The red and blue have been stripped from image.')

    return image_stripped, image_proc, radii

def get_center(edges):
    """Use edges to calculate the center.

    Return edges image and array of detected best guess center coordinates.
    """

    #image = ski.img_as_ubyte(edges[977:2277, 1650:3150])
    image = edges

    hough_radii = np.arange(400, 500, 5)
    hough_res = hough_circle(edges, hough_radii)

    centers = []
    accums = []
    radii = []

    for radius, h in zip(hough_radii, hough_res):
        # For each radius, extract two circles
        peaks = peak_local_max(h, num_peaks=2)
        centers.extend(peaks)
        accums.extend(h[peaks[:, 0], peaks[:, 1]])
        radii.extend([radius, radius])

    # Draw the most prominent 15 circles
    center_array = []
    image = ski.color.gray2rgb(image)
    for idx in np.argsort(accums)[::-1][:15]:
        center_x, center_y = centers[idx]
        radius = radii[idx]
        center_array.append([center_x, center_y])
        cx, cy = circle_perimeter(center_y, center_x, radius)
        image[cy, cx] = (220, 0, 0)

    return image, center_array

def plotevents(datalist):
    """Plot data"""
    x = range(0, len(datalist))
    x = np.array(x)
    y = datalist

    plt.plot(y)
    #fig, ax = plt.subplots()
    #plt.scatter(x, y, s=20, marker='.', c='blue')

    #plt.show()
    return "done"

def histo_plot(data, num_bins=10):
    """Plot histogram for array of values."""
    plt.figure('Data Histogram')
    n, bins, patches = plt.hist(data, bins=num_bins)

def getedge(center, slice):
    """ Get edges from processed image given a slice and the determined center

    Return the arrays for the edges of the left and right of center
    """
    r1 = []
    l1 =[]
    #Build right of center array
    for i, item in enumerate(slice[center:]):
        if item != False:
            r1.append(i)

     #Build left of center array
    for i, item in enumerate(slice[:center]):
        if item != False:
            l1.append(i)

    return l1, r1 + center

def space_freq(rn, rm, rj, etelon=.01):
    """Calculate the spacial frequency

    Return spacial frequency
    """
    sf = np.divide(1, 2 * etelon) * np.divide(np.square(rn) - np.square(rj), (np.square(rn) - np.square(rm)))
    return sf

def cal_center(calcenter, center):
    """Compare Radius from calibration image and sub radius image. Not implemented.

    Return the difference from the calibration center and the center of a given image.
    """
    dif_x = 0
    dif_y = 0
    if calcenter == center:
        return dif_x, dif_y
    elif calcenter[0] > center[0]:
        dif_x = calcenter[0] - center[0]
        if calcenter[1] > center[1]:
            dif_y = calcenter[1] - center[1]
        elif calcenter[1] > center[1]:
            dif_y = center[1] - calcenter[1]
        else:
            pass
        return dif_x, dif_y
    else:
        dif_x = center[0] - calcenter[0]
        if calcenter[1] > center[1]:
            dif_y = calcenter[1] - center[1]
        elif calcenter[1] > center[1]:
            dif_y = center[1] - calcenter[1]
        else:
            pass
        return dif_x, dif_y

#Get magnetic field function
def mag_field():
    """Calculate the magnetic filed relation in Tesla when provided an array of amps and
    magnetic field readings.

    Return the polynomial for the relation.
    """
    raw_mag = [[3, .465], [3.4, .530], [3.8, .590], [4.2, .651], [4.6, .712], [5, .774],
               [5.4, .832]]  #raw_input("Type in Amps and magnetic field tuples: ")
    b_field = []

    raw_mag = np.array(raw_mag)

    x = raw_mag[:, 0]
    y = raw_mag[:, 1]

    coefficients = np.polyfit(x, y, 2)
    polynomial = np.poly1d(coefficients)
    print(polynomial)
    ys = polynomial(x)

    #plt.subplot(5, 4, 9)
    plt.figure(0)
    plt.errorbar(x, y, color='k', ecolor='red', xerr=0, yerr=(y * 0.008), marker='o', markersize=4.0, linestyle='')
    plt.plot(x, ys)

    plt.ylabel('Measured Magnetic Field (T)')
    plt.xlabel('Applied Current (amps)')
    plt.xlim(x[0] * .95, x[-1] * 1.02)
    #plt.show()

    return polynomial

def best_fit(data_x, data_y, weights=None):
    """Find then plot best fit line

    Return none
    """
    x = data_x
    y = data_y

    coefficients, res, _, _, _ = np.polyfit(x, y, 1, full=True, w=weights)
    polynomial = np.poly1d(coefficients)
    ys = polynomial(x)
    # print coefficients
    print polynomial

    sd_of_slope, sd_of_y_intercept = calc_fit_uncertainty(data_x, res[0], len(data_x))

    max_error = np.poly1d([coefficients[0] + sd_of_slope, coefficients[1] + sd_of_y_intercept])
    min_error = np.poly1d([coefficients[0] - sd_of_slope, coefficients[1] - sd_of_y_intercept])
    plt.plot(x, max_error(x), '--', color='m')
    plt.plot(x, min_error(x), '--', color='m')

    print '+\-', round(sd_of_slope, 2), ' +\-', round(sd_of_y_intercept, 2)
    #plt.subplot(5, 4, 10)
    plt.plot(x, ys)

def create_calibration_pair(image_stripped, image_proc, edges_left, edges_right,
                            uncertanty_center, avrg_bisection, amps):
    """Create the calibration arrays for the left and right of center for the cross section giver.

    Return left and right detected edges and peaks.
    """
    peakPrec = uncertanty_center
    right_main_peak_list = []

    for i, item in enumerate(edges_right):
        if i + 1 < len(edges_right):
            peakL1, value = ternarySearch(image_stripped, item, edges_right[i + 1], peakPrec)
            right_main_peak_list.append([peakL1, item, edges_right[i + 1], round(value)])

    #Remove any peak with less than half the maximum peak intensity
    new = []
    for item in right_main_peak_list[::2]:
        new.append(item[3])

    print(new)

    half_largest_peak = max(new) * .42

    main_peaks = []
    for i, item in enumerate(right_main_peak_list[::2]):
        if item[3] > half_largest_peak:
            main_peaks.append(item)

    right_main_peak_list = main_peaks

    #Array of edges used to define boundaries for the primary peaks
    right_calibration = np.array(right_main_peak_list)

    # Find left Edges
    left_main_peak_list = []
    edges_left = edges_left[::-1]
    for i, item in enumerate(edges_left):
        if i + 1 < len(edges_right):
            #print(edges_left[i + 1], item)
            peakL2, value = ternarySearch(image_stripped, edges_left[i + 1], item, peakPrec)
            left_main_peak_list.append([peakL2, edges_left[i + 1], item, round(value)])

    #Remove any peak with less than half the maximum peak intensity
    new = []
    for item in left_main_peak_list:
        new.append(item[3])

    half_largest_peak = max(new) / 2

    main_peaks = []
    for i, item in enumerate(left_main_peak_list):
        if item[3] > half_largest_peak:
            main_peaks.append(item)

    left_main_peak_list = main_peaks

    #Array of edges used to define boundaries for the primary peaks
    left_calibration = np.array(left_main_peak_list)

    #Build and graph main image
    field_image = np.array([image_stripped] * 300)
    field_image_proc = np.array([image_proc] * 300)

    #Plot Intensity field with edges
    #plt.subplot(5, 4, 1)
    #plt.figure(2, figsize=(5, 1.5))
    plt.figure()
    plt.title(str(amps) + ' amps')

    plt.imshow(field_image_proc, origin='lower')
    #plt.imshow(field_image_proc2, origin='lower')
    plt.imshow(field_image, origin='lower', alpha=.5)
    #plt.xlim(avrg_x * .98, right_main_peak_list[-1][0] * 1.02)
    l = plt.axvline(x=avrg_bisection, color='r')
    plt.margins(0)

    #Plot intensities
    #plt.figure(3, figsize=(5, 1.5))
    plt.figure()
    plt.title(str(amps) + ' amps')

    for each in right_main_peak_list[:-1]:
         l = plt.axvline(x=each[0], color='r')
    for each in left_main_peak_list[:-1]:
         l = plt.axvline(x=each[0], color='r')
    plotevents(image_stripped)
    l = plt.axvline(x=avrg_bisection, color='r')
    plt.margins(0)
    plt.ylabel('Intensity ')
    plt.xlabel('Pixel Bin')
    #plt.xlim(avrg_x * .98, right_main_peak_list[-1][0] * 1.02)

    return left_calibration, right_calibration, left_main_peak_list, right_main_peak_list,

def get_calibration(inputFileDer, file_name):
    """Create calibration file for top, bottom, left and rights of center peaks.

    Return monochromatic image, a proceced image, the original image, arrays for the right, left, bottom, and top
      calibration, the selected color of interest, and the averages for the center coordinates.
    """
    color_of_interest = raw_input("What color is of interest?(red, green, or blue): ")
    if ('Red' in color_of_interest) or ('red' in color_of_interest):
        color_of_interest = 0
    elif ('Green' in color_of_interest) or ('green' in color_of_interest):
        color_of_interest = 1
    elif ('Blue' in color_of_interest) or ('blue' in color_of_interest):
        color_of_interest = 2

    #data = arrayFromFile(inputFileDer+fileNum)
    org_image = jpg_to_array(inputFileDer, file_name)

    image_stripped, image_proc, center = strip_color(org_image, color_of_interest, sig=7)

    #Show detected rings using the canny algorithm
    #plt.subplot(5, 4, 1)
    plt.figure(1)
    # plt.subplot(2, 1, 1)
    amps = file_name.replace('.jpg', '').replace('_', '.')
    amps = float(amps)

    plt.title(str(amps) + ' amps')
    plt.ylabel('Pixel Bin')
    plt.xlabel('Pixel Bin')
    plt.imshow(image_proc, origin='lower')
    plt.gray()

    #Show the stripped down image
    plt.imshow(image_stripped, origin='lower', alpha=.5)
    plt.gray()

    #Print average of the center in the y axis.
    avrg_y = np.round(np.mean(center, axis=0)[0], decimals=0)
    print('Average y value for center: ' + str(avrg_y))
    uncertanty_y = np.round(np.std(center, axis=0)[0] / (math.sqrt(len(center)) * 2), decimals=1)
    print('Uncertainty in y: ' + str(uncertanty_y))

    #Print average of the center in the x axis.
    avrg_x = np.round(np.mean(center, axis=0)[1], decimals=1)
    print('Average x value for center: ' + str(avrg_x))
    uncertanty_x = np.round(np.std(center, axis=0)[1] / (math.sqrt(len(center)) * 2), decimals=1)
    print('Uncertainty in x: ' + str(uncertanty_x))

    #y value will give horizontal slice.
    l = plt.axhline(y=avrg_y, color='r')
    l = plt.axvline(x=avrg_x, color='r')
    #plt.show()

    #Use edge array to get peak lists for horizontal and vertical cross sections
    edges_left, edges_right = getedge(avrg_x, image_proc[avrg_y])
    edges_botton, edges_top = getedge(avrg_y, image_proc[::, avrg_x])

    left_calibration, right_calibration, left_main_peak_list, right_main_peak_list = \
        create_calibration_pair(image_stripped[avrg_y], image_proc[avrg_y], edges_left, edges_right, uncertanty_x, avrg_x, amps)
    bottom_calibration, top_calibration, bottom_main_peak_list, top_main_peak_list = \
        create_calibration_pair(image_stripped[::, avrg_x], image_proc[::, avrg_x], edges_botton, edges_top, uncertanty_y, avrg_y, amps)

    os.system("afplay woohoo.wav")

    plt.show()

    return image_stripped, image_proc, org_image, left_calibration, right_calibration, \
           bottom_calibration, top_calibration, color_of_interest, avrg_y, avrg_x

def find_j_peaks(image_stripped, image_proc,
                 left_calibration, right_calibration, uncertanty_center, avrg_bisection, amps, run):
    """Calculate the spatial frequency using a slice of the fringe pattern image. The slice used represents
    both sides of center.

    Return Spatial frequency value of plus and minus j peaks.
    """

    #Find main peaks for non calibration files.
    edges_array = right_calibration
    peakPrec = uncertanty_center
    main_peak_list = []
    for i, item in enumerate(edges_array):
        if i < len(edges_array):
            peakL1, value = ternarySearch(image_stripped, item[1], item[2], peakPrec)
            main_peak_list.append([peakL1, item[1], item[2], value])

    end_of_right = len(main_peak_list)
    main_peak_list = np.array(main_peak_list)

    #Find and Graph lines for 1st secondary peaks
    jminus_peak_list = []
    for i, edge in enumerate(main_peak_list):
        if i + 1 < len(main_peak_list):
            j = i + 1
            limit = (main_peak_list[:, 0][i] - main_peak_list[:, 0][j]) / 2
            peakL1, value = ternarySearch(image_stripped, edge[1] + limit, edge[1], peakPrec)
            jminus_peak_list.append([peakL1, i, edge[1] + limit, edge[1], value])

    #jminus_peak_list = np.array(jminus_peak_list)

    #Find and Graph lines for 2nd secondary peaks
    jplus_peak_list = []
    for i, edge in enumerate(main_peak_list):
        if i + 1 < len(main_peak_list):
            j = i + 1
            limit = (main_peak_list[:, 0][i] - main_peak_list[:, 0][j]) / 2
            peakL1, value = ternarySearch(image_stripped, edge[2], edge[2] - limit, peakPrec)
            jplus_peak_list.append([peakL1, i, edge[2], edge[2] - limit, value])

    #jplus_peak_list = np.array(jplus_peak_list)

    ##Left Side
    #Find and Graph lines of main peaks for non calibration files.
    edges_array = left_calibration
    peakPrec = uncertanty_center
    left_main_peak_list = []
    for i, item in enumerate(edges_array):
        if i < len(edges_array):
            peakL1, value = ternarySearch(image_stripped, item[1], item[2], peakPrec)
            left_main_peak_list.append([peakL1, item[1], item[2], value])

    left_main_peak_list = np.array(left_main_peak_list)
    main_peak_list = np.append(main_peak_list, left_main_peak_list, axis=0)

    ##Left Side
    #Find and Graph lines for 1st secondary peaks
    for i, edge in enumerate(left_main_peak_list):
        if i + 1 < len(left_main_peak_list):
            j = i + 1
            limit = (left_main_peak_list[:, 0][i] - left_main_peak_list[:, 0][j]) / 2
            peakL1, value = ternarySearch(image_stripped, edge[2], edge[2] + limit, peakPrec)
            jminus_peak_list.append([peakL1, i, edge[2], edge[2] - limit, value])

    jminus_peak_list = np.array(jminus_peak_list)

    ##Left Side
    #Find and Graph lines for 2nd secondary peaks
    for i, edge in enumerate(left_main_peak_list):
        if i + 1 < len(left_main_peak_list):
            j = i + 1
            limit = (left_main_peak_list[:, 0][i] - left_main_peak_list[:, 0][j]) / 2
            peakL1, value = ternarySearch(image_stripped, edge[1] - limit, edge[1], peakPrec)
            jplus_peak_list.append([peakL1, i, edge[1] + limit, edge[1], value])

    jplus_peak_list = np.array(jplus_peak_list)

    sfreq_minus = []
    sfreq_plus = []
    global measured_data
    for i, each in enumerate(main_peak_list):
        if i + 2 < len(main_peak_list):
            if i == end_of_right - 1:
                pass
            elif each[0] > avrg_bisection:
                measured_data.append([amps, main_peak_list[i][0], main_peak_list[i + 1][0], jminus_peak_list[i][0],
                                      jplus_peak_list[i][0]])

                sfreq_minus.append(np.round(space_freq(main_peak_list[i][0], main_peak_list[i + 1][0], jminus_peak_list[i][0]), 2))
                sfreq_plus.append(np.round(space_freq(main_peak_list[i][0], main_peak_list[i + 1][0], jplus_peak_list[i][0]), 2))
            else:
                measured_data.append([amps, avrg_bisection - main_peak_list[i][0], avrg_bisection - main_peak_list[i + 1][0],
                                      avrg_bisection - jminus_peak_list[i][0], avrg_bisection - jplus_peak_list[i][0]])

                sfreq_minus.append(np.round(space_freq(avrg_bisection - main_peak_list[i][0], avrg_bisection - main_peak_list[i + 1][0],
                                                       avrg_bisection - jminus_peak_list[i - 1][0]), 2))
                sfreq_plus.append(np.round(space_freq(avrg_bisection - main_peak_list[i][0], avrg_bisection - main_peak_list[i + 1][0],
                                                      avrg_bisection - jplus_peak_list[i - 1][0]), 2))

    #Get first right peak
    placement = run + 12
    #plt.figure(run + 6, figsize=(5, 1.5))
    plt.figure()

    #plt.subplot(5, 4, placement)
    #plt.subplot(2, 1, 2)
    plt.title(str(amps) + ' amps')

    #Build and graph field image
    field_image = np.array([image_stripped] * 300)
    field_image_proc = np.array([image_proc] * 300)

    plt.imshow(field_image_proc, origin='lower')
    plt.imshow(field_image, origin='lower', alpha=.5)
    l = plt.axvline(x=avrg_bisection, color='r')

    plt.xlabel('Pixel Bin')
    plt.xlim(avrg_bisection * .98, main_peak_list[-1][0] * 1.02)

    plt.margins(0)

    #Plot intensity graph with peak indicator lines.
    #plt.figure(run + 7, figsize=(5, 1.5))
    plt.figure()

    plt.title(str(amps) + ' amps')
    l = plt.axvline(x=avrg_bisection, color='r')

    for each in main_peak_list[:-1]:
        l = plt.axvline(x=each[0], color='r')
    for each in jminus_peak_list:
        l = plt.axvline(x=each[0], color='b')
    for each in jplus_peak_list:
        l = plt.axvline(x=each[0], color='g')

    #plotevents(org_image[avrg_center][:, 1])
    plotevents(image_stripped)
    l = plt.axvline(x=avrg_bisection, color='r')
    plt.ylabel('Intensity')
    plt.xlabel('Pixel Bin')
    #plt.xlim(avrg_bisection * .98, main_peak_list[-1][0] * 1.02)

    plt.margins(0)

    return sfreq_minus, sfreq_plus

def get_sf(right_calibration, left_calibration, bottom_calibration, top_calibration,
           inputFileDer, file_name, color_of_interest, run):
    """Find the spatial frequency given calibration for the top, bottom, left, and
        right initial peaks.

    Return the plus and minus average values and their uncertainty and amps
    """

    #Strip file name in to the amps for the file.
    amps = file_name.replace('.JPG', '').replace('_', '.')
    amps = float(amps)

    #Strip color and get center
    org_image = jpg_to_array(inputFileDer, file_name)

    image_stripped, image_proc, center = strip_color(org_image, color_of_interest, sig=5)

    #Show detected rings using the canny algorithm
    placement = run + 8

    #plt.subplot(5, 4, placement)
    plt.figure(run + 5)
    #plt.subplot(2, 1, 1)
    plt.title(str(amps) + 'amps')
    plt.imshow(image_proc, origin='lower')
    plt.gray()

    #Show the stripped down image
    plt.imshow(image_stripped, origin='lower', alpha=.5)
    plt.gray()

    #Print average of the center in the y axis.
    avrg_y = np.round(np.mean(center, axis=0)[0], decimals=0)
    print('Average y value for center: ' + str(avrg_y))
    uncertanty_y = np.round(np.std(center, axis=0)[0] / (math.sqrt(len(center)) * 2), decimals=1)
    print('Uncertainty in y: ' + str(uncertanty_y))

    #Print average of the center in the x axis.
    avrg_x = np.round(np.mean(center, axis=0)[1], decimals=0)
    print('Average x value for center: ' + str(avrg_x))
    uncertanty_x = np.round(np.std(center, axis=0)[1] / (math.sqrt(len(center)) * 2), decimals=1)
    print('Uncertainty in x: ' + str(uncertanty_x))

    #y value will give horizontal slice.
    # base_line = avrg_y - org_image[avrg_y][avrg_x][1]
    # plotevents(org_image[avrg_y][:, 1] + base_line)
    l = plt.axhline(y=avrg_y, color='r')
    # plotevents(image_stripped[avrg_y] + base_line)
    l = plt.axvline(x=avrg_x, color='r')
    plt.margins(0)
    plt.ylabel('Pixel Bin')
    plt.xlabel('Pixel Bin')
    os.system("afplay woohoo.wav")
    #plt.show()

    sfreq_minus, sfreq_plus = \
        find_j_peaks(image_stripped[avrg_y], image_proc[avrg_y],
                     left_calibration, right_calibration, uncertanty_y, avrg_x, amps, run)
    sfreq_minus_bt, sfreq_plus_bt = \
        find_j_peaks(image_stripped[::, avrg_x], image_proc[::, avrg_x],
                     bottom_calibration, top_calibration, uncertanty_x, avrg_y, amps, run)

    #Combine horizontal and vertical value lists before averaging.
    sfreq_minus.extend(sfreq_minus_bt)
    sfreq_plus.extend(sfreq_plus_bt)

    #build spatial frequency array of values using all peaks
    sfm_mean = np.round(np.mean(sfreq_minus), decimals=2)
    sfp_mean = np.round(np.mean(sfreq_plus), decimals=2)

    #Create uncertainty based on standard deviation
    un_sfm = np.round((np.std(sfreq_minus) / math.sqrt(len(sfreq_minus)) * 2), decimals=2)
    un_sfp = np.round((np.std(sfreq_plus) / math.sqrt(len(sfreq_minus)) * 2), decimals=2)

    print(np.round(sfreq_minus, 2))
    print(np.round(sfreq_plus, 2))

    plt.show()

    return sfm_mean, un_sfm, sfp_mean, un_sfp, amps

def calc_fit_uncertainty(list_x, residuals, number_of_points):
    """Calculate the Standard deviation of the slope and y intercept of a fit line.

    Return standard deviation of slope and y intercept
    """
    xi_squared = []
    for item in list_x:
        xi_squared.append(math.pow(item, 2))

    sd_of_y = math.sqrt(residuals / (number_of_points - 2))
    sd_of_slope = sd_of_y * math.sqrt(number_of_points / ((number_of_points * sum(xi_squared)) - math.pow(sum(list_x), 2)))
    sd_of_y_intercept = sd_of_y * math.sqrt(sum(xi_squared) / ((number_of_points * sum(xi_squared)) - math.pow(sum(list_x), 2)))

    return sd_of_slope, sd_of_y_intercept

def main():
    user_name = getpass.getuser()
    if user_name == 'admin':
        print("Welcome Admin")
        inputFileDer = "/Users/admin/Dropbox/School/Summer-2014/SSC-479R/comp-cert/as_images/"
    else:
        print "Welcome", str(user_name)
        inputFileDer = raw_input("Please enter directory of image files ending with a slash: ")

    #Initialize Some variables
    run = 1
    final_data = np.array([[0, 0, 0, 0]])
    uncertainty_b = .008
    global measured_data
    b_field = mag_field()

    file_name = raw_input("Type in B=0 file name: ")

    #create list of image files in inputFileDer directory
    image_list = os.listdir(inputFileDer)
    if image_list[0][-3:] == 'ore':
        stupid_hidden_file = 2
    else:
        stupid_hidden_file = 1

    #Get the calibration data.
    image_stripped, image_proc, org_image, left_calibration, right_calibration, \
           bottom_calibration, top_calibration, color_of_interest, avrg_y, avrg_x \
        = get_calibration(inputFileDer, file_name)

    for item in image_list[stupid_hidden_file:]:
        sfm_mean, un_sfm, sfp_mean, un_sfp, amps = get_sf(right_calibration, left_calibration,
                                               bottom_calibration, top_calibration,
                                               inputFileDer, item, color_of_interest, run)

        #Place data in to final j array
        if run == 1:
            final_minus = np.array([[sfm_mean, un_sfm, b_field(amps), uncertainty_b]])
            final_plus = np.array([[sfp_mean, un_sfp, b_field(amps), uncertainty_b]])
        else:
            final_minus = np.append(final_minus, [[sfm_mean, un_sfm, b_field(amps), uncertainty_b]], axis=0)
            final_plus = np.append(final_plus, [[sfp_mean, un_sfp, b_field(amps), uncertainty_b]], axis=0)

        final_data = np.append(final_data, [[sfm_mean, un_sfm, b_field(amps), uncertainty_b]], axis=0)
        final_data = np.append(final_data, [[sfp_mean, un_sfp, b_field(amps), uncertainty_b]], axis=0)
        print(np.round(final_plus, 2))
        print(np.round(final_minus, 2))

        os.system("afplay woohoo.wav")

        run += 1

    #Create master file of all peaks without averaging
    dataTofile(measured_data)

    #Transfer final data to x and y with errors for error plot
    y = final_data[:, 0]
    un_y = final_data[:, 1]
    x = final_data[:, 2]
    un_x = final_data[:, 3]

    plt.figure()

    os.system("afplay about_time.m4a")
    best_fit(final_minus[:, 2], final_minus[:, 0])
    best_fit(final_plus[:, 2], final_plus[:, 0])

    #Plot delta nu function
    plt.errorbar(x, y, xerr=un_x, yerr=un_y, fmt='+')
    plt.ylabel(r'$\Delta{\nu}  (mm^{-1})$')
    plt.xlabel('Magnetic Field (T)')
    plt.xlim(x[1] * .95, x[-1] * 1.02)
    #plt.ylim(0, 1)
    plt.subplot_tool()
    duration = time.time() - start

    print "Program duration: ", duration/60

    plt.show()

while True:
    try:
        main()
    except TypeError:
        print "An error occurred. Most likely related to inadequate sigma and threshold " \
              "values in canny function for color selected."
    except:
        print "An unexpected error occurred: ", sys.exc_info()[0]
    print "\n\nWould you like to start another session? (Y/N)"
    do_again = str(raw_input(""))
    if ('N' not in do_again) and ('n' not in do_again):
        break
    else:
        print "Good Bye!"


text:
using UnityEngine;
using System.Collections;

namespace Fungus
{
    /// <summary>
    /// Vector3 variable type.
    /// </summary>
    [VariableInfo("Other", "Vector3")]
    [AddComponentMenu("")]
    [System.Serializable]
    public class Vector3Variable : VariableBase<Vector3>
    {
        public static readonly CompareOperator[] compareOperators = { CompareOperator.Equals, CompareOperator.NotEquals };
        public static readonly SetOperator[] setOperators = { SetOperator.Assign, SetOperator.Add, SetOperator.Subtract };

        public virtual bool Evaluate(CompareOperator compareOperator, Vector3 value)
        {
            bool condition = false;

            switch (compareOperator)
            {
                case CompareOperator.Equals:
                    condition = Value == value;
                    break;
                case CompareOperator.NotEquals:
                    condition = Value != value;
                    break;
                default:
                    Debug.LogError("The " + compareOperator.ToString() + " comparison operator is not valid.");
                    break;
            }

            return condition;
        }

        public override void Apply(SetOperator setOperator, Vector3 value)
        {
            switch (setOperator)
            {
                case SetOperator.Assign:
                    Value = value;
                    break;
                case SetOperator.Add:
                    Value += value;
                    break;
                case SetOperator.Subtract:
                    Value -= value;
                    break;
                default:
                    Debug.LogError("The " + setOperator.ToString() + " set operator is not valid.");
                    break;
            }
        }
    }

    /// <summary>
    /// Container for a Vector3 variable reference or constant value.
    /// </summary>
    [System.Serializable]
    public struct Vector3Data
    {
        [SerializeField]
        [VariableProperty("<Value>", typeof(Vector3Variable))]
        public Vector3Variable vector3Ref;

        [SerializeField]
        public Vector3 vector3Val;

        public Vector3Data(Vector3 v)
        {
            vector3Val = v;
            vector3Ref = null;
        }

        public static implicit operator Vector3(Vector3Data vector3Data)
        {
            return vector3Data.Value;
        }

        public Vector3 Value
        {
            get { return (vector3Ref == null) ? vector3Val : vector3Ref.Value; }
            set { if (vector3Ref == null) { vector3Val = value; } else { vector3Ref.Value = value; } }
        }

        public string GetDescription()
        {
            if (vector3Ref == null)
            {
                return vector3Val.ToString();
            }
            else
            {
                return vector3Ref.Key;
            }
        }
    }
}


text:
//
//  DPPageViewController.h
//  DPIkcrm
//
//  Created by 王的 MacBook pro on 16/4/19.
//  Copyright © 2016年 王的 MacBook Pro. All rights reserved.
//

@import UIKit;
@class DPPageViewController;

@protocol DPPageViewControllerDelegate <NSObject>

@optional

- (void)pageViewController:(DPPageViewController *)pageViewController displayIndex:(NSInteger)index;

/**
 自定义小title
 */
- (void)pageViewController:(DPPageViewController *)pageViewController titleItem:(UIButton *)item;

@end

typedef enum : NSUInteger {
    /// 等宽(默认)
    ItemEqualWidth = 0,
    /// 等间距
    ItemEqualSpacing,
} ItemWidthStyle;

@interface DPPageViewController : UIViewController
@property (nonatomic, strong, readonly) UIView *headView;
@property (nonatomic, strong, readonly) UIScrollView *headScrollView;
@property (nonatomic, strong, readonly) UIScrollView *bodyView;
/// 当前显示的view
@property (nonatomic, strong, readonly) UIView *displayView;

/// 顶部的view使用时直接赋值(位置在headView上面,会根据滑动移动)
@property (nonatomic, strong) UIView *topView;

/// 中间的view使用时直接赋值
@property (nonatomic, strong) UIView *middleView;

/// 底部的view使用时直接赋值
@property (nonatomic, strong) UIView *bottomView;

/// 当前页的索引
@property (nonatomic, assign) NSInteger displayIndex;

/// 按钮高度 (默认50)
@property (nonatomic, assign) CGFloat itemHeight;

/// item宽度样式 默认ItemEqualWidth
@property (nonatomic, assign) ItemWidthStyle itemWidthStyle;

/// 按钮间距 (默认50) widthStyle = ItemEqualSpacing 有效
@property (nonatomic, assign) CGFloat itemSpace;

/// 按钮到左右两边的距离(默认10) widthStyle = ItemEqualSpacing 有效
@property (nonatomic, assign) CGFloat itemMarginLR;

/// 按钮最小宽度 (默认90) widthStyle = ItemEqualWidth 有效
@property (nonatomic, assign) CGFloat minItemWidth;

@property (nonatomic, weak) id<DPPageViewControllerDelegate> delegate;

@property (nonatomic, copy, readonly) NSArray<UIViewController *> *viewControllers;

/// 普通的颜色
@property (nonatomic, strong) UIColor *commonColor;

/// 选中的颜色
@property (nonatomic, strong) UIColor *selectColor;

/// title字体
@property (nonatomic, strong) UIFont *titleFont;

/// title字体大小
@property (nonatomic, assign, readonly) CGFloat titleSize;

/// 选中的title放大倍数 (默认1)
@property (nonatomic, assign) CGFloat selectTitleZoomMultiple;

/// title底部滑块
@property (nonatomic, strong) UIView *markLine;

- (instancetype)initWithTitle:(NSString *)title viewControllers:(NSArray<UIViewController *> *)viewControllers;

- (void)reloadView;

// 移动topView
- (void)moveTopViewByScrollView:(UIScrollView *)scrollView;

- (void)reloadViewControllers:(NSArray<UIViewController *> *)viewControllers;

//- (void)items:(NSArray *)items delegate:(id<DPPageViewControllerDelegate>) delegate;

@end


text:
<?php

namespace SymfonyRollbarBundle\Tests\Command;

use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Console\Tester\CommandTester;
use SymfonyRollbarBundle\Command\DeployCommand;
use SymfonyRollbarBundle\Tests\Fixtures\ApiClientMock;

/**
 * Class DeployCommandTest
 */
class DeployCommandTest extends KernelTestCase
{
    public function setUp()
    {
        parent::setUp();
        static::bootKernel();
    }

    public function testRegistration()
    {
        $container = static::$kernel->getContainer();
        $application = new Application(static::$kernel);
        $application->add(new DeployCommand($container));

        try {
            $application->find('rollbar:deploy');
        } catch (\Exception $e) {
            $this->fail($e->getMessage());

            return;
        }

        // it's should not be risky test
        $this->assertTrue(true);
    }

    /**
     * @dataProvider generateExecuteInput
     *
     * @param array $input
     * @param       $expected
     * @param       $message
     */
    public function testExecute($input, $expected, $message)
    {
        $container = static::$kernel->getContainer();

        /** @var \SymfonyRollbarBundle\Tests\Fixtures\ApiClientMock $client */
        $client = new ApiClientMock($container);
        $client->setCallback(function ($payload) use ($input) {
            $this->assertEquals('SOME_ROLLBAR_ACCESS_TOKEN_123456', $payload['access_token']);
            $this->assertNotEmpty($payload['environment']);
            $this->assertEquals($input['revision'], $payload['revision']);

            if (!empty($input['-c'])) {
                $this->assertEquals($input['-c'], $payload['comment']);
            }

            if (!empty($input['-ru'])) {
                $this->assertEquals($input['-ru'], $payload['rollbar_username']);
            }

            if (!empty($input['-lu'])) {
                $this->assertEquals($input['-lu'], $payload['local_username']);
            }

            return true;
        });
        $container->set('symfony_rollbar.provider.api_client', $client);

        $application = new Application(static::$kernel);
        $application->add(new DeployCommand($container));

        try {
            $command = $application->find('rollbar:deploy');
        } catch (\Exception $e) {
            $this->fail($e->getMessage());

            return;
        }

        $commandTester = new CommandTester($command);

        if ($expected === 'exception-args') {
            $this->expectException(\Symfony\Component\Console\Exception\RuntimeException::class);
            $this->expectExceptionMessageRegExp($message);
        }

        $commandTester->execute($input);

        if ($expected === 'general') {
            $output = $commandTester->getDisplay();
            $this->assertContains($message, $output);
        }
    }

    /**
     * @return array
     */
    public function generateExecuteInput()
    {
        return [
            [[], 'exception-args', '/revision/'],
            [['revision' => 'R1.0.0'], 'general', 'Done.'],
            [['revision' => 'R1.0.0', '-c' => 'World'], 'general', 'Done.'],
            [['revision' => 'R1.0.0', '-ru' => 'Rollbar'], 'general', 'Done.'],
            [['revision' => 'R1.0.0', '-lu' => get_current_user()], 'general', 'Done.'],
        ];
    }

    public function testExecuteGeneric()
    {
        $container = static::$kernel->getContainer();
        $application = new Application(static::$kernel);
        $application->add(new DeployCommand($container));

        $command       = $application->find('rollbar:deploy');
        $commandTester = new CommandTester($command);

        $commandTester->execute([
            'revision' => 'R1.0.0',
            '-c'       => 'World',
            '-lu'      => get_current_user(),
        ]);

        $output = $commandTester->getDisplay();
        $this->assertContains('Build has been not tracked:', $output);
    }
}


text:
<?php

// Language definitions for online.php
$lang_online = array(

    //common language used
    'users online' => 'Users Currently Online',
    'user currently' => 'Location',
    'last active' => 'Last Active',
    'currently' => 'Currently:',

    // Time intervals
    'second ago' => '%s Second ago',
    'seconds ago' => '%s Seconds ago',
    'minute ago' => '%s Minute ago',
    'minutes ago' => '%s Minutes ago',

    // Language for online location
    'bot' => '- - - - -',
    'viewing index' => 'Viewing Board Index',
    'searching' => 'Searching...',
    'viewing userlist' => 'Viewing Userlist',
    'viewing online' => 'Viewing Users Online',
    'viewing rules' => 'Viewing Site Rules',
    'bbcode help' => 'Viewing BBCode Help',
    'viewing profile' => 'Viewing Profile:',
    'private messaging' => 'Using Private Messaging',
    'administration' => 'In Administration',
    'login' => 'Logging In',
    'register' => 'Registering',
    'viewing forum' => 'Viewing Forum:',
    'viewing topic' => 'Viewing Topic:',
    'posting topic' => 'Posting New Topic in Forum:',
    'replying to topic' => 'Replying to Topic:',
    'editing topic' => 'Editing Post in Topic:',
    'deleting post' => 'Deleting Post in Topic:',
    'moderating' => 'Moderating A Forum',
    'viewing team' => 'Viewing the moderating team',
    'posting' => 'Posting...',
    'in hidden forum' => 'In Hidden Forum',

    //Language for viewforum & viewtopic
	'Guest' => 'guest',
	'Guests' => 'guests',
    'online topic' => 'Users in this topic: %s %s, %s',
    'no users' => '0 registered users',
    'online forum' => 'Users browsing this forum: %s %s, %s',

    // Language for profile.php
    'user is offline' => 'User is Offline',
    'user is online' => 'User is Online',
    'not online' => 'Not Online',

    //Language for misc.php
    'the team' => 'The Moderating Team',
    'admin' => 'Administrators',
    'global mod' => 'Global Moderators',
    'mod' => 'Forum Moderators',
    'all forums' => 'All Forums',
    'forums' => 'Forums',
    'currently 1' => 'Currently',
    'online' => 'Online',
    'total forums' => '%s Total Forums'

);


text:
<?php
/**
 *
 */

namespace Middleware;

use Mvc5\Plugins\Response as _Response;
use Mvc5\Plugins\Service;
use Mvc5\Plugins\Url;
use Request;
use Response;

class Authenticate
{
    /**
     *
     */
    use _Response;
    use Service;
    use Url;

    /**
     * @param Request $request
     * @param Response $response
     * @param callable $next
     * @return mixed
     */
    function __invoke(Request $request, Response $response, callable $next)
    {
        return $request->user()->authenticated()
            ? $next($request, $response) : $this->redirect($this->url('app', ['controller' => 'login']));
    }
}


text:
//
// Please report any problems with this app template to contact@estimote.com
//

#import "ViewController.h"
#import "CloudManager.h"
#import "ProximityManager.h"

@interface ViewController () <ProximityManagerDelegate>

@property (nonatomic, strong) ProximityManager *proximityManager;
@property (nonatomic, strong) CloudManager *cloudManager;

@property (nonatomic, strong) NSMutableDictionary<NSString *, UIView *> *zoneViewByBeaconIdentifier;
@property (nonatomic, strong) NSArray<NSString *> *beaconIdentifiers;

@property (weak, nonatomic) IBOutlet UIStackView *stackView;
@property (weak, nonatomic) IBOutlet UIView *noBeaconsView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    /** TODO: Make sure your beacons have Estimote Monitoring feature set enabled:
     https://community.estimote.com/hc/en-us/articles/226144728
     */

    /** TODO: Replace with identifiers of your beacons.
     You can find identifiers of your beacon at https://cloud.estimote.com/#/beacons
     */
    self.beaconIdentifiers = @[@"B34C0N-1-CL0UD-1D3NT1F13R",
                               @"B34C0N-2-CL0UD-1D3NT1F13R",
                               @"B34C0N-3-CL0UD-1D3NT1F13R"];

    self.zoneViewByBeaconIdentifier = [NSMutableDictionary new];
    self.cloudManager = [CloudManager new];

    // Step 1: Pre-fetch content related to your beacons
    __weak ViewController *weakSelf = self;
    [self.cloudManager fetchColorsForBeaconsWithIdentifiers:self.beaconIdentifiers
                                                 completion:^(BOOL success, NSDictionary<NSString *, UIColor *> *colorByIdentifier)
     {
         if (!success || !colorByIdentifier) {
             [weakSelf presentFetchingColorsFailedAlert];
             return;
         }

         [weakSelf addBeaconZoneViewsForBeaconColorIdentifier:colorByIdentifier];

         // Step 2: Start monitoring proximity of your beacons
         weakSelf.proximityManager = [ProximityManager new];
         weakSelf.proximityManager.delegate = weakSelf;
         [weakSelf.proximityManager startMonitoringProximityOfBeaconsWithIdentifiers:weakSelf.beaconIdentifiers];
     }];
}

#pragma mark - ProximityManagerDelegate

- (void)proximityManager:(ProximityManager *)manager didUpdateBeaconsInRange:(NSArray<NSString *> *)identifiers {

    // Step 3: Update UI dependant on which beacons are in range
    [self updateBeaconZoneViewsWithBeaconIdentifiersInRange:identifiers];
}

- (void)proximityManager:(ProximityManager *)manager didFailWithError:(NSError *)error {
    [self presentMonitoringFailedAlert];
}

#pragma mark - UI-related methods

- (void)addBeaconZoneViewsForBeaconColorIdentifier:(NSDictionary<NSString *, UIColor *> *)colorByIdentifier {

    for (NSString *identifier in colorByIdentifier.allKeys) {

        UIView *zoneView = [UIView new];
        zoneView.translatesAutoresizingMaskIntoConstraints = false;
        zoneView.backgroundColor = colorByIdentifier[identifier];

        UIImageView *beaconImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Beacon"]];
        beaconImageView.contentMode = UIViewContentModeScaleAspectFit;
        beaconImageView.translatesAutoresizingMaskIntoConstraints = false;
        [zoneView addSubview:beaconImageView];

        UILabel *identifierLabel = [UILabel new];
        identifierLabel.translatesAutoresizingMaskIntoConstraints = false;
        identifierLabel.textAlignment = NSTextAlignmentCenter;
        identifierLabel.font = [UIFont boldSystemFontOfSize:18.0];
        identifierLabel.numberOfLines = 0;
        identifierLabel.textColor = UIColor.whiteColor;
        identifierLabel.text = identifier;
        [zoneView addSubview:identifierLabel];

        // Setup constraints
        NSArray<NSLayoutConstraint *> *verticalAlignmentConstraints = [NSLayoutConstraint constraintsWithVisualFormat: @"V:|-24-[beacon]-8@999-[identifier]-|"
                                                                                options: NSLayoutFormatAlignAllCenterX
                                                                                metrics: nil
                                                                                views: @{@"beacon": beaconImageView, @"identifier": identifierLabel}];
        [NSLayoutConstraint activateConstraints:verticalAlignmentConstraints];
        [[beaconImageView.centerXAnchor constraintEqualToAnchor:zoneView.centerXAnchor] setActive:true];
        [identifierLabel setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];
        [identifierLabel setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];

        self.zoneViewByBeaconIdentifier[identifier] = zoneView;
        [self.stackView addArrangedSubview:zoneView];
        [self hide:true viewIfNeeded:zoneView];
    }

}

- (void)updateBeaconZoneViewsWithBeaconIdentifiersInRange:(NSArray<NSString *> *)identifiersInRange {
    [UIView animateWithDuration:0.2 animations:^{

        BOOL thereAreBeaconsInRange = identifiersInRange.count != 0;
        [self hide:thereAreBeaconsInRange viewIfNeeded:self.noBeaconsView];

        for (NSString *identifier in self.beaconIdentifiers) {
            UIView *zoneView;
            if ((zoneView = self.zoneViewByBeaconIdentifier[identifier]) == nil) { return; }

            BOOL identifierIsNotInRange = ![identifiersInRange containsObject:identifier];
            [self hide:identifierIsNotInRange viewIfNeeded:zoneView];
        }
    }];
}

- (void)hide:(BOOL)shouldBeHidden viewIfNeeded:(UIView *)view {
    if (view.isHidden != shouldBeHidden) {
        [view setHidden:shouldBeHidden];
    }
}

- (void)presentMonitoringFailedAlert {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle: @"Monitoring failed" message: @"Make sure bluetooth is on and the app has permission to use it." preferredStyle: UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:alert animated:true completion:nil];
}

- (void)presentFetchingColorsFailedAlert {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle: @"Fetching colors failed" message: @"Check your internet connection, App ID and App Token." preferredStyle: UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:alert animated:true completion:nil];
}

@end


text:
<?php

/* :elevesViews:myProfileEleve.html.twig */
class __TwigTemplate_93e08e31f14a4871ea72396fcd6134cda5e193de3d84e19ab0837b460ab284af extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        // line 1
        $this->parent = $this->loadTemplate("base.html.twig", ":elevesViews:myProfileEleve.html.twig", 1);
        $this->blocks = array(
            'body' => array($this, 'block_body'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "base.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $__internal_f3f1c7c5dcf33be459cc85029a1f6bc491a04798b4e652fe45e726d71aa7b52d = $this->env->getExtension("Symfony\\Bundle\\WebProfilerBundle\\Twig\\WebProfilerExtension");
        $__internal_f3f1c7c5dcf33be459cc85029a1f6bc491a04798b4e652fe45e726d71aa7b52d->enter($__internal_f3f1c7c5dcf33be459cc85029a1f6bc491a04798b4e652fe45e726d71aa7b52d_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", ":elevesViews:myProfileEleve.html.twig"));

        $__internal_dae208369b8bba457c9178626a154d4ada589676297498acca73c2bb8b3d80ba = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension");
        $__internal_dae208369b8bba457c9178626a154d4ada589676297498acca73c2bb8b3d80ba->enter($__internal_dae208369b8bba457c9178626a154d4ada589676297498acca73c2bb8b3d80ba_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", ":elevesViews:myProfileEleve.html.twig"));

        $this->parent->display($context, array_merge($this->blocks, $blocks));

        $__internal_f3f1c7c5dcf33be459cc85029a1f6bc491a04798b4e652fe45e726d71aa7b52d->leave($__internal_f3f1c7c5dcf33be459cc85029a1f6bc491a04798b4e652fe45e726d71aa7b52d_prof);

        $__internal_dae208369b8bba457c9178626a154d4ada589676297498acca73c2bb8b3d80ba->leave($__internal_dae208369b8bba457c9178626a154d4ada589676297498acca73c2bb8b3d80ba_prof);

    }

    // line 3
    public function block_body($context, array $blocks = array())
    {
        $__internal_c97d38bc42c41d91187fd4371c420d7b4f62044abaf6813d59d498ea7882a90b = $this->env->getExtension("Symfony\\Bundle\\WebProfilerBundle\\Twig\\WebProfilerExtension");
        $__internal_c97d38bc42c41d91187fd4371c420d7b4f62044abaf6813d59d498ea7882a90b->enter($__internal_c97d38bc42c41d91187fd4371c420d7b4f62044abaf6813d59d498ea7882a90b_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "body"));

        $__internal_f80210f71461a488dbd2ecc55a5bb5c3c6467967c9758c043b387ec5964b0545 = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension");
        $__internal_f80210f71461a488dbd2ecc55a5bb5c3c6467967c9758c043b387ec5964b0545->enter($__internal_f80210f71461a488dbd2ecc55a5bb5c3c6467967c9758c043b387ec5964b0545_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "body"));

        // line 4
        echo "
Mon Profile ";
        echo twig_escape_filter($this->env, $this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : $this->getContext($context, "app")), "user", array()), "nom", array()), "html", null, true);
        echo " ";
        echo twig_escape_filter($this->env, $this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : $this->getContext($context, "app")), "user", array()), "prenom", array()), "html", null, true);
        echo "

\t

\t\t
photo :getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : $this->getContext($context, "app")), "user", array()), "photo", array())) {
            echo twig_escape_filter($this->env, $this->env->getExtension('Symfony\Bridge\Twig\Extension\AssetExtension')->getAssetUrl(("uploads/photos/" . $this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : $this->getContext($context, "app")), "user", array()), "photo", array()))), "html", null, true);
        } else {
            echo twig_escape_filter($this->env, $this->env->getExtension('Symfony\Bridge\Twig\Extension\AssetExtension')->getAssetUrl("uploads/photos/avatar.png"), "html", null, true);
        }
        echo "\" alt=\"\">

\t\t
nom :";
        // line 7
        echo twig_escape_filter($this->env, $this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : $this->getContext($context, "app")), "user", array()), "nom", array()), "html", null, true);
        echo "

\t\t
prenom :";
        // line 8
        echo twig_escape_filter($this->env, $this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : $this->getContext($context, "app")), "user", array()), "prenom", array()), "html", null, true);
        echo "

\t\t
genre :";
        // line 9
        echo twig_escape_filter($this->env, $this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : $this->getContext($context, "app")), "user", array()), "genre", array()), "html", null, true);
        echo "

\t\t
date et lieu de naissance :";
        // line 10
        echo twig_escape_filter($this->env, twig_date_format_filter($this->env, $this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : $this->getContext($context, "app")), "user", array()), "dateDeNaissance", array()), "Y-m-d"), "html", null, true);
        echo " à ";
        echo twig_escape_filter($this->env, $this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : $this->getContext($context, "app")), "user", array()), "lieuDeNaissance", array()), "html", null, true);
        echo "

\t\t
adresse :";
        // line 11
        echo twig_escape_filter($this->env, $this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : $this->getContext($context, "app")), "user", array()), "adresse", array()), "html", null, true);
        echo "

\t\t
code postal :";
        // line 12
        echo twig_escape_filter($this->env, $this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : $this->getContext($context, "app")), "user", array()), "codePostal", array()), "html", null, true);
        echo "

\t\t
telephone :";
        // line 13
        echo twig_escape_filter($this->env, $this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : $this->getContext($context, "app")), "user", array()), "telephone", array()), "html", null, true);
        echo "

\t\t
username :";
        // line 14
        echo twig_escape_filter($this->env, $this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : $this->getContext($context, "app")), "user", array()), "username", array()), "html", null, true);
        echo "

\t\t
email :";
        // line 15
        echo twig_escape_filter($this->env, $this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : $this->getContext($context, "app")), "user", array()), "email", array()), "html", null, true);
        echo "

\t\t
type :";
        // line 16
        echo twig_escape_filter($this->env, twig_upper_filter($this->env, $this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : $this->getContext($context, "app")), "user", array()), "typeUser", array())), "html", null, true);
        echo "

\t\t
derniere connexion :";
        // line 17
        echo twig_escape_filter($this->env, twig_date_format_filter($this->env, $this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : $this->getContext($context, "app")), "user", array()), "lastLogin", array()), "Y-m-d"), "html", null, true);
        echo "

\t\t
parent :";
        // line 18
        echo twig_escape_filter($this->env, $this->getAttribute($this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : $this->getContext($context, "app")), "user", array()), "parent", array()), "nom", array()), "html", null, true);
        echo " ";
        echo twig_escape_filter($this->env, $this->getAttribute($this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : $this->getContext($context, "app")), "user", array()), "parent", array()), "nom", array()), "html", null, true);
        echo "

\t

\t
\t
";

        $__internal_f80210f71461a488dbd2ecc55a5bb5c3c6467967c9758c043b387ec5964b0545->leave($__internal_f80210f71461a488dbd2ecc55a5bb5c3c6467967c9758c043b387ec5964b0545_prof);

        $__internal_c97d38bc42c41d91187fd4371c420d7b4f62044abaf6813d59d498ea7882a90b->leave($__internal_c97d38bc42c41d91187fd4371c420d7b4f62044abaf6813d59d498ea7882a90b_prof);

    }

    public function getTemplateName()
    {
        return ":elevesViews:myProfileEleve.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  111 => 18,  107 => 17,  103 => 16,  99 => 15,  95 => 14,  91 => 13,  87 => 12,  83 => 11,  77 => 10,  73 => 9,  69 => 8,  65 => 7,  57 => 6,  49 => 4,  40 => 3,  11 => 1,);
    }

    /** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
    public function getSource()
    {
        @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);

        return $this->getSourceContext()->getCode();
    }

    public function getSourceContext()
    {
        return new Twig_Source("{% extends 'base.html.twig' %}

{% block body %}

Mon Profile {{app.user.nom}} {{app.user.prenom}}

\t

\t\t
photo :

\t\t
nom :{{app.user.nom}}

\t\t
prenom :{{app.user.prenom}}

\t\t
genre :{{app.user.genre}}

\t\t
date et lieu de naissance :{{app.user.dateDeNaissance|date('Y-m-d')}} à {{app.user.lieuDeNaissance}}

\t\t
adresse :{{app.user.adresse}}

\t\t
code postal :{{app.user.codePostal}}

\t\t
telephone :{{app.user.telephone}}

\t\t
username :{{app.user.username}}

\t\t
email :{{app.user.email}}

\t\t
type :{{app.user.typeUser|upper}}

\t\t
derniere connexion :{{app.user.lastLogin|date('Y-m-d')}}

\t\t
parent :{{app.user.parent.nom}} {{app.user.parent.nom}}

\t

\t
\t
{% endblock %}", ":elevesViews:myProfileEleve.html.twig", "/Applications/MAMP/htdocs/Symfony/app/Resources/views/elevesViews/myProfileEleve.html.twig");
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>The GNU C Library: General Limits</title>

<meta name="description" content="The GNU C Library: General Limits">
<meta name="keywords" content="The GNU C Library: General Limits">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="makeinfo">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="index.html#Top" rel="start" title="Top">
<link href="Concept-Index.html#Concept-Index" rel="index" title="Concept Index">
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
<link href="System-Configuration.html#System-Configuration" rel="up" title="System Configuration">
<link href="System-Options.html#System-Options" rel="next" title="System Options">
<link href="System-Configuration.html#System-Configuration" rel="prev" title="System Configuration">

Next: System Options, Up: System Configuration   [Contents][Index]

32.1 General Capacity Limits

The POSIX.1 and POSIX.2 standards specify a number of parameters that
describe capacity limitations of the system.  These limits can be fixed
constants for a given operating system, or they can vary from machine to
machine.  For example, some limit values may be configurable by the
system administrator, either at run time or by rebuilding the kernel,
and this should not require recompiling application programs.

Each of the following limit parameters has a macro that is defined in
<samp>limits.h</samp> only if the system has a fixed, uniform limit for the
parameter in question.  If the system allows different file systems or
files to have different limits, then the macro is undefined; use
sysconf to find out the limit that applies at a particular time
on a particular machine.  See Sysconf.

Each of these parameters also has another macro, with a name starting
with ‘<samp>_POSIX</samp>’, which gives the lowest value that the limit is
allowed to have on any POSIX system.  See Minimums.

Macro: int ARG_MAX

If defined, the unvarying maximum combined length of the <var>argv</var> and
<var>environ</var> arguments that can be passed to the exec functions.

Macro: int CHILD_MAX

If defined, the unvarying maximum number of processes that can exist
with the same real user ID at any one time.  In BSD and GNU, this is
controlled by the RLIMIT_NPROC resource limit; see Limits on Resources.

Macro: int OPEN_MAX

If defined, the unvarying maximum number of files that a single process
can have open simultaneously.  In BSD and GNU, this is controlled
by the RLIMIT_NOFILE resource limit; see Limits on Resources.

Macro: int STREAM_MAX

If defined, the unvarying maximum number of streams that a single
process can have open simultaneously.  See Opening Streams.

Macro: int TZNAME_MAX

If defined, the unvarying maximum length of a time zone name.
See Time Zone Functions.

These limit macros are always defined in <samp>limits.h</samp>.

Macro: int NGROUPS_MAX

The maximum number of supplementary group IDs that one process can have.

The value of this macro is actually a lower bound for the maximum.  That
is, you can count on being able to have that many supplementary group
IDs, but a particular machine might let you have even more.  You can use
sysconf to see whether a particular machine will let you have
more (see Sysconf).

Macro: ssize_t SSIZE_MAX

The largest value that can fit in an object of type ssize_t.
Effectively, this is the limit on the number of bytes that can be read
or written in a single operation.

This macro is defined in all POSIX systems because this limit is never
configurable.

Macro: int RE_DUP_MAX

The largest number of repetitions you are guaranteed is allowed in the
construct ‘<samp>\{<var>min</var>,<var>max</var>\}</samp>’ in a regular expression.

The value of this macro is actually a lower bound for the maximum.  That
is, you can count on being able to have that many repetitions, but a
particular machine might let you have even more.  You can use
sysconf to see whether a particular machine will let you have
more (see Sysconf).  And even the value that sysconf tells
you is just a lower bound—larger values might work.

This macro is defined in all POSIX.2 systems, because POSIX.2 says it
should always be defined even if there is no specific imposed limit.

Next: System Options, Up: System Configuration   [Contents][Index]


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <android.support.v4.view.ViewPager
        android:id="@+id/strategy_header_vp"
        android:layout_width="match_parent"
        android:layout_height="150dp"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_height="50dp">
        <TextView
            android:layout_width="80dp"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="最近想去"/>
        <View
            android:layout_width="1dp"
            android:layout_height="match_parent"
            android:background="@color/View_bg"
            android:layout_margin="5dp"/>
        <LinearLayout
            android:layout_width="0dp"
            android:layout_weight="1"
            android:orientation="horizontal"
            android:layout_height="match_parent">

        </LinearLayout>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="250dp"

        android:orientation="vertical">
        <TextView
            android:id="@+id/strategy_item_title"
            android:layout_width="match_parent"
            android:layout_margin="5dp"
            android:layout_height="30dp"
            android:textSize="16sp"
            android:text="标题" />
        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:paddingRight="10dp"
            android:paddingLeft="10dp"
            android:background="@color/View_bg"
            />
        <com.xcc.advancedday13.widget.CustomGridView
            android:id="@+id/strategy_item_nearby_city"
            android:layout_width="match_parent"
            android:numColumns="3"
            android:layout_height="wrap_content"/>

        <TextView
            android:id="@+id/strategy_item_more"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:text="更多附近目的地"
            android:gravity="center"
            android:textColor="@color/text_color_one"
            android:textSize="18sp"/>
    </LinearLayout>

</LinearLayout>


text:
package org.teavm.backend.c.analyze;

import com.carrotsearch.hppc.IntHashSet;
import com.carrotsearch.hppc.IntSet;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.teavm.ast.AssignmentStatement;
import org.teavm.ast.RecursiveVisitor;
import org.teavm.ast.Statement;
import org.teavm.ast.TryCatchStatement;
import org.teavm.ast.VariableExpr;

public class VolatileDefinitionFinder {
    private static final int[] EMPTY_INT_ARRAY = new int[0];
    private Map<AssignmentStatement, StackElement> defHandlers = new HashMap<>();
    private Set<AssignmentStatement> definitionsToBackup = new HashSet<>();
    private Map<TryCatchStatement, IntSet> usagesToRestoreByHandler = new HashMap<>();

    public void findVolatileDefinitions(Statement statement) {
        AstDefinitionUsageAnalysis defuse = new AstDefinitionUsageAnalysis();
        defuse.analyze(statement);
        statement.acceptVisitor(handlerAnalyzer);

        for (AstDefinitionUsageAnalysis.Definition definition : defuse.getDefinitions()) {
            StackElement stack = defHandlers.get(definition.getStatement());
            if (stack == null || definition.getExceptionHandlingUsages().isEmpty()) {
                continue;
            }

            while (stack != null) {
                if (definition.getExceptionHandlingUsages().get(stack.statement) != null) {
                    IntSet usagesToRestore = usagesToRestoreByHandler.get(stack.statement);
                    if (usagesToRestore == null) {
                        usagesToRestore = new IntHashSet();
                        usagesToRestoreByHandler.put(stack.statement, usagesToRestore);
                    }
                    usagesToRestore.add(definition.getVariableIndex());
                    definitionsToBackup.add(definition.getStatement());
                }
                stack = stack.next;
            }
        }

        defHandlers = null;
    }

    public boolean shouldBackup(AssignmentStatement statement) {
        return definitionsToBackup.contains(statement);
    }

    public int[] variablesToRestore(TryCatchStatement tryCatch) {
        IntSet result = usagesToRestoreByHandler.get(tryCatch);
        if (result == null) {
            return EMPTY_INT_ARRAY;
        }
        int[] array = result.toArray();
        Arrays.sort(array);
        return array;
    }

    static class StackElement {
        final TryCatchStatement statement;
        final StackElement next;

        StackElement(TryCatchStatement statement, StackElement next) {
            this.statement = statement;
            this.next = next;
        }
    }

    private RecursiveVisitor handlerAnalyzer = new RecursiveVisitor() {
        StackElement surroundingTryCatches;
        StackElement handlingTryCatches;

        @Override
        public void visit(TryCatchStatement statement) {
            surroundingTryCatches = new StackElement(statement, surroundingTryCatches);
            visit(statement.getProtectedBody());
            surroundingTryCatches = surroundingTryCatches.next;

            visit(statement.getHandler());
        }

        @Override
        public void visit(AssignmentStatement statement) {
            super.visit(statement);
            if (statement.getLeftValue() instanceof VariableExpr && surroundingTryCatches != null) {
                defHandlers.put(statement, surroundingTryCatches);
            }
        }
    };
}


text:
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.

// Copyright (C) 2016, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.

/*
C++ wrappers over OpenVX 1.x C API ("openvx-debug" module)
Details: TBD
*/

#pragma once
#ifndef IVX_LIB_DEBUG_HPP
#define IVX_LIB_DEBUG_HPP

#include "ivx.hpp"

namespace ivx
{
namespace debug
{
/*
* "openvx-debug" module
*/

//
void fReadImage(vx_context c, const std::string& path, vx_image img)
{
    IVX_CHECK_STATUS( vxuFReadImage(c, (vx_char*)path.c_str(), img) );
}

//
void fWriteImage(vx_context c, vx_image img, const std::string& path)
{
    IVX_CHECK_STATUS( vxuFWriteImage(c, img, (vx_char*)path.c_str()) );
}

} // namespace debug
} // namespace ivx

#endif //IVX_LIB_DEBUG_HPP


text:
package com.fincatto.documentofiscal.nfe400.classes.nota.assinatura;

import org.junit.Assert;
import org.junit.Test;

import com.fincatto.documentofiscal.nfe310.classes.nota.assinatura.NFDigestMethod;
import com.fincatto.documentofiscal.nfe310.classes.nota.assinatura.NFReference;
import com.fincatto.documentofiscal.nfe310.classes.nota.assinatura.NFTransform;

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

public class NFReferenceTest {

    @Test
    public void deveObterDigestValueComoFoiSetado() {
        final NFReference reference = new NFReference();
        final String digestValue = "digest value";
        reference.setDigestValue(digestValue);
        Assert.assertEquals(digestValue, reference.getDigestValue());
    }

    @Test
    public void deveObterTransformComoFoiSetado() {
        final NFReference reference = new NFReference();
        final List<NFTransform> transform = new ArrayList<>();
        reference.setTransform(transform);
        Assert.assertEquals(transform, reference.getTransform());
    }

    @Test
    public void deveObterUriComoFoiSetado() {
        final NFReference reference = new NFReference();
        final String uri = "uri";
        reference.setUri(uri);
        Assert.assertEquals(uri, reference.getUri());
    }

    @Test
    public void deveObterDigestMethodComoFoiSetado() {
        final NFReference reference = new NFReference();
        final NFDigestMethod digestMethod = new NFDigestMethod();
        digestMethod.setAlgorithm("digest method");
        reference.setDigestMethod(digestMethod);
        Assert.assertEquals(digestMethod, reference.getDigestMethod());
    }
}


text:
package de.tub.eyes.gui.customelements;

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;

import java.util.Vector;
import java.util.Map;
import java.util.TreeMap;
import java.util.Iterator;

import de.tub.eyes.diagram.*;
import de.tub.eyes.comm.MessageReceiver;
import de.tub.eyes.apps.demonstrator.Demonstrator;
import de.tub.eyes.apps.PS.PSSubscription;

import net.tinyos.message.Message;
import de.tub.eyes.ps.*;
import net.tinyos.drain.*;

/**
 *
 * @author Till Wimmer
 */
public class NodePropertyViewer extends JTree implements SelectionListener, MessageReceiver {
    private MyTreeModel model = null;
    private NodePS node = null;
    private final static int DATANODE_TIMEOUT = 30;

    public NodePropertyViewer() {
        setModel(model);
        Demonstrator.getMoteComm().addListener(this);
    }

    public void selectionChanged(Node n) {
        if (n != null && n instanceof NodePS) {
            if (n != node) {
                node = (NodePS)n;
                model = new MyTreeModel("Node " + node.getId());
                setModel(model);
                updateUI();
            }
        }
    }

    public void receiveMessage(Message m) {
        if (node == null || model == null)
            return;

        if (!(m instanceof DrainMsg)) {
            System.err.println("NodePropertyViewer.class: No implementation for this message type yet.");
            return;
        }

        DrainMsg mhmsg = (DrainMsg)m;
        PSNotificationMsg msgTemp = new PSNotificationMsg(mhmsg, mhmsg.offset_data(0));
        PSNotificationMsg ps2Msg = new PSNotificationMsg(mhmsg, mhmsg.offset_data(0),
                    msgTemp.DEFAULT_MESSAGE_SIZE + msgTemp.get_dataLength());

        if (ps2Msg.get_sourceAddress() != node.getId())
            return;
        model.updateNode(new String [] {"Epoch"},
                String.valueOf(node.getEpoch()));
        model.updateNode(new String [] {"Subcription" + String.valueOf(ps2Msg.get_subscriptionID()),"Header", "parentAddress"},
                String.valueOf(ps2Msg.get_parentAddress()));
        model.updateNode(new String [] {"Subcription" + String.valueOf(ps2Msg.get_subscriptionID()),"Header", "subscriberID"},
                String.valueOf(ps2Msg.get_subscriberID()));
        model.updateNode(new String [] {"Subcription" + String.valueOf(ps2Msg.get_subscriptionID()),"Header","modificationCounter"},
                String.valueOf(ps2Msg.get_modificationCounter()));

        for (int i=0; i< ps2Msg.getAVPairCount(); i++) {
            int attr = ps2Msg.getAVPairAttributeID(i);
            String attrName = PSSubscription.getAttribName(attr);

            model.updateNode(new String [] {"Subcription" + String.valueOf(ps2Msg.get_subscriptionID()),"Data", attrName},
                    PSSubscription.arrayToObject(ps2Msg.getAVPairValue(i), attr).toString());
        }
    }

    class MyTreeModel implements TreeModel {
        Vector treeModelListeners = new Vector();
        DataNode root;

        public MyTreeModel(String Name) {
           root = new DataNode(null, Name);
        }

        public void addNode(String [] path, String value) {
            String [] base = new String [path.length-1];

            for (int i=0; i<path.length-1; i++)
                base[i] = path[i];

            DataNode parent = getNode(base);
            if (parent == null) {
                System.err.println("Path" + base + "does not exits!");
                return;
            }

            DataNode node = new DataNode(parent, path[path.length-1]);
            node.setValue(value);
            parent.addChild(node);
        }

        public void updateNode(String [] path, String value) {
            DataNode node;

            node = makePath(path);
            //node = getNode(path);
            fireTreeNodesChanged(node.setValue(value));
        }

        private DataNode makePath(String [] path) {
            DataNode root = null;
            int level = path.length;
            String [] newpath;

            while ( root == null ) {
                newpath = new String [level];
                for (int i=0; i<level; i++)
                    newpath[i] = path[i];

                if ( (root = getNode(newpath)) == null)
                    level--;
            }

            if (level < path.length) {
                DataNode node = new DataNode(root, path[level]);
                fireTreeNodesInserted(root.addChild(node));
                return makePath(path);
            }

            return root;
        }

        private DataNode getNode(String [] path) {
            DataNode node = this.root;

            for (int i=0; i<path.length; i++) {
                node = getNode(node, path[i]);
                if (node == null)
                    break;
            }

            return node;
        }

        private DataNode getNode(DataNode root, String Name) {
            Vector childs = root.getChilds();

            for (Iterator it=childs.iterator(); it.hasNext();) {
                DataNode child = (DataNode)it.next();
                if (child.getName().equals(Name)) {
                    return child;
                }
            }

            return null;
        }

        public void setID(String id) {
            root.setValue("Node " + id);
        }

        /**
         * Adds a listener for the TreeModelEvent posted after the tree changes.
         */
        public void addTreeModelListener(TreeModelListener l) {
            treeModelListeners.addElement(l);
        }

        /**
         * Returns the child of parent at index index in the parent's child array.
         */
        public Object getChild(Object parent, int index) {
            DataNode dn = (DataNode)parent;
            return dn.getChilds().get(index);
        }

        /**
         * Returns the number of children of parent.
         */
        public int getChildCount(Object parent) {
            DataNode dn = (DataNode)parent;
            return dn.getChilds().size();
        }

        /**
         * Returns the index of child in parent.
         */
        public int getIndexOfChild(Object parent, Object child) {
            DataNode dn = (DataNode)parent;
            return dn.getChilds().indexOf(child);
        }

        /**
         * Returns the root of the tree.
         */
        public Object getRoot() {
            return root;
        }

        /**
         * Returns true if node is a leaf.
         */
        public boolean isLeaf(Object node) {
            DataNode dn = (DataNode)node;
            return dn.getChilds().size() == 0;
        }

        /**
         * Removes a listener previously added with addTreeModelListener().
         */
        public void removeTreeModelListener(TreeModelListener l) {
            treeModelListeners.removeElement(l);
        }

        /**
         * Messaged when the user has altered the value for the item
         * identified by path to newValue.  Not used by this model.
         */
        public void valueForPathChanged(TreePath path, Object newValue) {
            System.out.println("*** valueForPathChanged : "
                    + path + " --> " + newValue);
        }

        private void fireTreeNodesInserted(TreeModelEvent e) {

            for (Iterator it= treeModelListeners.iterator(); it.hasNext();) {
                ((TreeModelListener)it.next()).treeNodesInserted(e);
            }
        }

        private void fireTreeNodesChanged(TreeModelEvent e) {

            for (Iterator it= treeModelListeners.iterator(); it.hasNext();) {
                ((TreeModelListener)it.next()).treeNodesChanged(e);
            }
        }
    }

    /*
     * DataNodes have a lifetime DATANODE_TIMEOUT. A DataNode which isn't updated
     * for DATANODE_TIMEOUT secs erases himself by changing the childs list of his parent
     */

    class DataNode {
        DataNode parent;
        String name;
        String value = "null";
        Vector childs = new Vector();
        DataNode [] path = null;

        public DataNode(DataNode parent, String name) {
            this.parent = parent;
            this.name = name;

            if (parent == null)
                return;

            int size = 0;
            if (parent.getPath() != null)
                size = parent.getPath().length;

            path = new DataNode [size+1];
            for (int i=0; i<size; i++)
                path[i] = parent.getPath()[i];

            path[size] = parent;
        }

        public DataNode getParent() {
            return this.parent;
        }

        public DataNode [] getPath() {
            return this.path;
        }

        public String getName() {
            return this.name;
        }

        public Vector getChilds() {
            return this.childs;
        }

        public TreeModelEvent addChild(DataNode child) {
            Object [] children = new Object[1];
            int [] childIndices = new int[1];

            childs.addElement(child);

            childIndices[0] = childs.indexOf(child);
            children[0] = child;
            TreeModelEvent event = new TreeModelEvent(this, child.getPath(), childIndices, children);

            System.out.println("Event = " + event.toString());
            return event;
        }

        public void removeChild(DataNode child) {
            childs.remove(child);
        }

        public String toString() {
            if (childs.size() == 0)
                return name + ": " + value;
            else
                return (name);
        }

        public TreeModelEvent setValue(String value) {
            Object [] children = new Object[1];
            int [] childIndices = new int[1];

            this.value = value;

            childIndices[0] = parent.getChilds().indexOf(this);
            children[0] = this;
            TreeModelEvent event = new TreeModelEvent(parent, this.getPath(), childIndices, children);
            touch();

            return event;
        }

        private void onTimeout() {
            if ( parent != null )
                parent.removeChild(this);
        }

        /*
         * touch() is called every time the DataNode is updated so the lifetime doesn't exceed.
         */
        private void touch() {
            /*
             *TODO: Update (kill + star new) timer
             */
            if ( parent != null )
                parent.touch();
        }
    }
}


text:
namespace Microsoft.Azure.Management.Sql
{
    using Microsoft.Rest;
    using Microsoft.Rest.Azure;
    using Models;
    using System.Collections;
    using System.Collections.Generic;
    using System.Threading;
    using System.Threading.Tasks;

    /// <summary>
    /// Extension methods for ElasticPoolDatabaseActivitiesOperations.
    /// </summary>
    public static partial class ElasticPoolDatabaseActivitiesOperationsExtensions
    {
            /// <summary>
            /// Returns activity on databases inside of an elastic pool.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group that contains the resource. You can obtain
            /// this value from the Azure Resource Manager API or the portal.
            /// </param>
            /// <param name='serverName'>
            /// The name of the server.
            /// </param>
            /// <param name='elasticPoolName'>
            /// The name of the elastic pool.
            /// </param>
            public static IEnumerable<ElasticPoolDatabaseActivity> ListByElasticPool(this IElasticPoolDatabaseActivitiesOperations operations, string resourceGroupName, string serverName, string elasticPoolName)
            {
                return operations.ListByElasticPoolAsync(resourceGroupName, serverName, elasticPoolName).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Returns activity on databases inside of an elastic pool.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group that contains the resource. You can obtain
            /// this value from the Azure Resource Manager API or the portal.
            /// </param>
            /// <param name='serverName'>
            /// The name of the server.
            /// </param>
            /// <param name='elasticPoolName'>
            /// The name of the elastic pool.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<IEnumerable<ElasticPoolDatabaseActivity>> ListByElasticPoolAsync(this IElasticPoolDatabaseActivitiesOperations operations, string resourceGroupName, string serverName, string elasticPoolName, CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.ListByElasticPoolWithHttpMessagesAsync(resourceGroupName, serverName, elasticPoolName, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

    }
}


text:
@interface ILProductCell()
@property (weak, nonatomic) IBOutlet UIImageView *imgView;

@property (weak, nonatomic) IBOutlet UILabel *title;

@end
@implementation ILProductCell

-(void)setProduct:(ILProduct *)product{
    _product = product;

    _imgView.image = [UIImage imageNamed:product.icon];
    _title.text = product.title;
    //return _product;
}

//设置图片圆角
-(void)awakeFromNib{
    _imgView.layer.cornerRadius = 10;
    _imgView.clipsToBounds = YES;
    //_imgView.layer.masksToBounds

}

@end


text:
@interface TableCellOne ()
@property (unsafe_unretained, nonatomic) IBOutlet WKInterfaceLabel *label;
@end
@implementation TableCellOne
- (void)setLabelText:(NSString *)text {
    [self.label setText: text];
}
@end


text:
using System;
using System.Collections.Generic;
using Android.Content;
using Toggl.Phoebe;
using Toggl.Phoebe.Data.Models;
using Toggl.Phoebe.Net;
using XPlatUtils;

namespace Toggl.Joey.Widget
{
    public class WidgetUpdateService : IWidgetUpdateService
    {
        private Context context;

        public WidgetUpdateService (Context ctx)
        {
            context = ctx;

            // Update auth state from platform service.
            //
            // Phoebe services are initializated first,
            // if we try to update auth state from Phoebe
            // WidgetUpdateService still doesn't exists.

            var authManager = ServiceContainer.Resolve<AuthManager>();
            IsUserLogged = authManager.IsAuthenticated;
        }

        #region IWidgetUpdateService implementation

        public string RunningEntryDuration { get; set; }

        private List<WidgetSyncManager.WidgetEntryData> lastEntries;

        public List<WidgetSyncManager.WidgetEntryData> LastEntries
        {
            get {
                if (lastEntries == null) {
                    lastEntries = new List<WidgetSyncManager.WidgetEntryData>();
                }
                return lastEntries;
            } set {
                lastEntries = value;
                WidgetProvider.RefreshWidget (context, WidgetProvider.RefreshListAction);
            }
        }

        private bool isUserLogged;

        public bool IsUserLogged
        {
            get {
                return isUserLogged;
            } set {
                if (isUserLogged == value) {
                    return;
                }
                isUserLogged = value;
                WidgetProvider.RefreshWidget (context, WidgetProvider.RefreshCompleteAction);
            }
        }

        private Guid entryIdStarted;

        public Guid EntryIdStarted
        {
            get {
                return entryIdStarted;
            } set {
                if (entryIdStarted == value) {
                    return;
                }
                entryIdStarted = value;
            }
        }

        public void ShowNewTimeEntryScreen (TimeEntryModel currentTimeEntry)
        {
            var startAppIntent = new Intent (Intent.ActionMain)
            .AddCategory (Intent.CategoryLauncher)
            .AddFlags (ActivityFlags.NewTask)
            .SetComponent (
                new ComponentName (
                    context.ApplicationContext.PackageName,
                    "toggl.joey.ui.activities.MainDrawerActivity"
                )
            );
            context.StartActivity (startAppIntent);
        }
        #endregion
    }
}


text:
__author__ = "Pedro Werneck (pjwerneck@gmail.com)"
__date__ = "Sun Sep 29 23:07:46 2013"

from functools import wraps

from flask import request, g

from sqlalchemy import func

from werkzeug.exceptions import BadRequest, Unauthorized, Forbidden, NotImplemented

from mesh.models.user import check_user

def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.authorization

        if not auth:
            raise Unauthorized('Basic auth required.')

        email = auth['username']
        password = auth['password']

        id_user, valid = check_user(email, password)

        if not id_user:
            raise Unauthorized('User does not exist.')

        if not valid:
            raise Unauthorized('Invalid user or password.')

        g.id_user = id_user
        g.valid = valid

        return f(*args, **kwargs)

    return decorated

def _total_items(query):
    # sqlalchemy uses a subquery to make counts, so this hack below
    # rebuilds the query into a more efficient one
    counter = query.with_entities(func.count('*'))

    if counter.whereclause is None:
        counter = counter.select_from(query._entities[0].type)

    return counter.scalar()

def apply_query_parameters(query, model):

    joins = [model]
    types = {}

    for arg, value in request.args.items():
        if arg in ('limit', 'offset', 'order_by', '_debug'):
            continue

        # check for a join
        if '.' in arg:
            type_, arg = arg.split('.', 1)

            try:
                type_ = types[type_]
            except KeyError:
                raise BadRequest("Type %s not allowed." % type_)

            if type_ not in joins:
                query = query.join(type_)
                joins.append(type_)
        # otherwise, use the base model
        else:
            type_ = model

        # check for operators
        if arg.endswith('_from') or arg.endswith('_to') or arg.endswith('_ne'):
            arg, op = arg.rsplit('_', 1)
        # othwerise, use ==
        else:
            op = 'equal'

        # get the field
        try:
            field = getattr(type_, arg)
        except AttributeError:
            raise BadRequest("Invalid field: %s" % arg)

        # normalize the value for active checks
        if arg == 'active':
            if value.lower() in ('1', 'true'):
                value = True

            elif value.lower() in ('0', 'false', 'null'):
                value = None

            else:
                raise BadRequest("Invalid value for field 'active': %s" % value)

        # apply the operator and finally the filter clause
        if op == 'equal':
            query = query.filter(field == value)
        elif op == 'from':
            query = query.filter(field >= value)
        elif op == 'to':
            query = query.filter(field <= value)
        elif op == 'ne':
            query = query.filter(field != value)
        else:
            raise BadRequest("Invalid operator: %s" % arg)

    return query

def apply_order_by(query):
    order_by = request.args.get('order_by')

    if order_by is not None:
        model = query.column_descriptions[0]['type']
        desc = False
        if order_by.startswith('-'):
            desc = True
            order_by = order_by.strip('-')

        try:
            field = getattr(model, order_by)
        except AttributeError:
            raise BadRequest("Invalid order_by field: %s" % order_by)

        if desc:
            field = field.desc()

        query = query.order_by(field)

    return query

def paginate(query):
    limit = min(int(request.args.get('limit', 50)), 1000)
    offset = int(request.args.get('offset', 0))

    # total items has to be count before applying limit and order by
    total_items = _total_items(query)

    query = apply_order_by(query)
    query = query.limit(limit).offset(offset)

    # is this just too magical?
    name = query.column_descriptions[0]['name'].lower() + 's'

    response = {'total_items': total_items,
                'limit': limit,
                'offset': offset,
                name: [dict(c) for c in query.all()],
                }

    if request.args.get('order_by'):
        response['order_by'] = request.args['order_by']

    if request.args.get('_debug'):
        response['_query'] = str(query)

    return response