text:
package com.example.android.common.devices;

import android.graphics.Color;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.style.BackgroundColorSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.util.Range;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TreeMap;

/**
 * Created by pims on 7/3/15.
 */
public class DigestDevices {
    private final TreeMap<String,DeviceDeltas> mSortedMap;
    private final List<String> mIgnoreDevices;
    private List<SpannableString> mResults;
    private SpannableString mDeviceLines = new SpannableString("");
    private SpannableString mResultTitle = new SpannableString("");
    private SpannableString mResultDetails = new SpannableString("");
    private Range<Integer> mDeltaHostRange, mDeltaKuRange;
    //private SpannableStringBuilder mDeviceLines = new SpannableStringBuilder();
    private int mCountBadDeltaHosts;
    private int mCountBadDeltaKus;
    private Boolean mBadPhoneHostDelta = Boolean.TRUE;

    private int mResultStateInteger;
    private ResultState mResultState;
    private static State mGoodResultState = new ResultStateGood();
    private static State mBadResultState = new ResultStateBad();
    //private static State mLimboResultState = new ResultStateLimbo();

    private static final SimpleDateFormat DOY = new SimpleDateFormat("DDD:");
    private static final SimpleDateFormat HHMMSS = new SimpleDateFormat("HH:mm:ss");

    public DigestDevices(TreeMap<String, DeviceDeltas> sorted_map, List<String> ignore_devices,
                         Range<Integer> delta_host_range, Range<Integer> delta_ku_range) {
        mSortedMap = sorted_map;
        mIgnoreDevices = ignore_devices;
        mDeltaHostRange = delta_host_range;
        mDeltaKuRange = delta_ku_range;
        mCountBadDeltaKus = 0;
        mCountBadDeltaHosts = 0;
        mResultStateInteger = 0;
        mResultState = new ResultState(); // initial limbo state
        mResults = null;
    }

    public DigestDevices(TreeMap<String, DeviceDeltas> sorted_map, List<String> ignore_devices) {
        mSortedMap = sorted_map;
        mIgnoreDevices = ignore_devices;
        mDeltaHostRange = Range.create(13, 17);
        mDeltaKuRange = Range.create(-3, 3);
        mCountBadDeltaKus = 0;
        mCountBadDeltaHosts = 0;
        mResultStateInteger = 0;
        mResultState = new ResultState(); // initial limbo state
        mResults = null;
    }

    // setters
    public void setDeltaHostRange(Integer rmin, Integer rmax) { mDeltaHostRange = Range.create(rmin, rmax); }

    public void setDeltaKuRange(Integer rmin, Integer rmax) { mDeltaKuRange = Range.create(rmin, rmax); }

    private void setCountBadDeltaKus(int value) { mCountBadDeltaKus = value; }

    private void setCountBadDeltaHosts(int value) { mCountBadDeltaHosts = value; }

    private void setResultStateInteger(int value) { mResultStateInteger = value; }

    // getters
    public TreeMap<String, DeviceDeltas> getSortedMap() {
        return mSortedMap;
    }

    public List<String> getIgnoreDevices() {
        return mIgnoreDevices;
    }

    public Range<Integer> getDeltaHostRange() {
        return mDeltaHostRange;
    }

    public Range<Integer> getDeltaKuRange() {
        return mDeltaKuRange;
    }

    public SpannableString getDeviceLines() {
        return mDeviceLines;
    }

    public SpannableString getResultTitle() {
        return mResultTitle;
    }

    public SpannableString getResultDetails() {
        return mResultDetails;
    }

    public List<SpannableString> getResults() {
        return mResults;
    }

    public int getCountBadDeltaHosts() {
        return mCountBadDeltaHosts;
    }

    public int getCountBadDeltaKus() {
        return mCountBadDeltaKus;
    }

    public Boolean isBadPhoneHostDelta() {
        return mBadPhoneHostDelta;
    }

    public int getResultStateInteger() {
        return mResultStateInteger;
    }

    private static String padRight(String s, int n) {
        return String.format("%1$-" + n + "s", s);
    }

    // TODO set one of 3 result states: (1) GREEN okay, (2) YELLOW unknown, (3) RED bad
    // NEED NEW DELTA = (TextClockGMT - host) SHOULD BE LESS THAN [ 10 SEC? ]
    // if bad dPhone, then bad; maybe bigtime on butters host is down or butters crashed
    // any bad dKu is bad
    // all dHost bad is unknown (because ku is in that set), SO YELLOW COLOR & CHIME SOUND (no alarm)
    // otherwise (all other criteria above failed) go with okay so GREEN COLOR & CHIME SOUND
    public void processMap() {

        // get formatted spannable string for device lines & result one-line PLUS set result state
        try {

            // iterate over device lines to get deltas with formatting and bad host/ku delta counts
            mDeviceLines = getFormattedDeviceLines();

            // examine bad host/ku delta counts and such to determine result state & formatted one-liner
            mResults = getFormattedResults();
            mResultDetails = mResults.get(0);
            mResultTitle = mResults.get(1);

            // TODO main activity change sound to chime/alarm based on mResultStateInteger

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

    private SpannableString getFormattedDeviceLines() {

        // at this point, we should have sorted map, so iterate to build formatted spannable strings
        SpannableStringBuilder devLines = new SpannableStringBuilder();

        // counter for setting spans in growing-formatted spannable string
        int start;

        // FIXME seems like sometimes you use setter/getters and elsewhere just use member variable?
        // to start out, we assume all deltas are okay
        setCountBadDeltaHosts(0);
        setCountBadDeltaKus(0);

        // header line
        devLines.append("DOY:hh:mm:ss  dHost    dKu  device\n");
        devLines.append("----------------------------------\n");
        devLines.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, devLines.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        for (TreeMap.Entry<String, DeviceDeltas> entry: mSortedMap.entrySet()) {
            DeviceDeltas dev = entry.getValue();
            String device_name = dev.getDevice();
            Date device_time = dev.getTime();
            float device_dh = dev.getDeltaHost();
            float device_dk = dev.getDeltaKu();

            // FIXME when we get to host entry, entire line background gets distinct color
            // FIXME user config for dimmed devices

            // TODO make a home for snippet keeper for repeat character like this
            // the next line shows how to repeat char "-" 80 times
            //    Log.i("SEP", new String(new char[80]).replace("\0", "-"));

            // if host, then make this a distinctive line via bg color
            if (device_name.equals("host")) {

                start = devLines.length();

                devLines.append(DOY.format(device_time));
                devLines.append(HHMMSS.format(device_time));
                devLines.append(String.format(" %6.1f", device_dh));
                devLines.append(String.format(" %6.1f", device_dk));
                devLines.append("  ").append(device_name).append("      ");
                devLines.setSpan(new ForegroundColorSpan(Color.BLACK), start, devLines.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                devLines.setSpan(new BackgroundColorSpan(Color.WHITE), start, devLines.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

            }
            // if this is device to ignore, dim this row
            else if (mIgnoreDevices.contains(device_name)) {

                start = devLines.length();

                devLines.append(DOY.format(device_time));
                devLines.append(HHMMSS.format(device_time));
                devLines.append("       ");
                devLines.append("       ");
                devLines.append("  ").append(device_name).append("      ");
                devLines.setSpan(new ForegroundColorSpan(Color.DKGRAY), start, devLines.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                //devLines.setSpan(new BackgroundColorSpan(Color.BLACK), start, devLines.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

            }
            // if this is phone device, then if dHost delta is too big, make it red
            else if (device_name.equals("phone")) {
                start = devLines.length();
                devLines.append(DOY.format(device_time));
                devLines.append(HHMMSS.format(device_time));
                devLines.append(String.format(" %6.1f", device_dh));
                devLines.append(String.format(" %6.1f", device_dk));
                devLines.append("  ").append(device_name).append("----< ");
                if (Math.abs(device_dh) < 121.0f) {
                    mBadPhoneHostDelta = Boolean.FALSE;
                } else if (Math.abs(device_dh) >= 121.0f) {
                    mBadPhoneHostDelta = Boolean.TRUE;
                    devLines.setSpan(new ForegroundColorSpan(Color.RED), start, devLines.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
            }
            // otherwise, we have a device to consider for sound notify (check its dh and dk)
            else {

                // device time DOY: is plain
                devLines.append(DOY.format(device_time));

                // device time HH:MM:SS is white
                start = devLines.length();
                devLines.append(HHMMSS.format(device_time));
                //devLines.setSpan(new ForegroundColorSpan(0xFFCC5500), start, devLines.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                // TODO for out of range dh (or dk), make red that value and device name too
                // deltaHost span
                //start = devLines.length();
                float dh = device_dh;
                if (dh < -999.9) {
                    dh = -999.9f;
                } else if (dh > 999.9f) {
                    dh = 999.9f;
                }
                devLines.append(String.format(" %6.1f", dh));
                //devLines.setSpan(new ForegroundColorSpan(0xFFCC5500), start, devLines.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                //devLines.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), start, devLines.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                // deltaKu span
                //start = devLines.length();
                float dk = device_dk;
                boolean clipped = false;
                if (dk < -999.9) {
                    dk = -999.9f; clipped = true;
                } else if (dk > 999.9f) {
                    dk = 999.9f;  clipped = true;
                }
                devLines.append(String.format(" %6.1f", dk));
                if (clipped) {
                    //devLines.setSpan(new ForegroundColorSpan(0x80ff0000), start, devLines.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    devLines.setSpan(new ForegroundColorSpan(Color.RED), start, devLines.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    //devLines.setSpan(new ForegroundColorSpan(0xFFCC5500), start, devLines.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    //devLines.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), start, devLines.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }

                // device name is clickable linked to WHAT?
                devLines.append("  ");
                //start = devLines.length();
                devLines.append(padRight(device_name, 12));
                //devLines.setSpan(new URLSpan("http://pims.grc.nasa.gov/plots/sams/121f03/121f03.jpg"), start, devLines.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                // check dh
                if (dh < 13.0f || dh > 17.0f) { mCountBadDeltaHosts++; }

                // check dk
                if (Math.abs(dk) > 3.0f) { mCountBadDeltaKus++; }

            }

            devLines.append("\n");

        }
        return SpannableString.valueOf(devLines);
    }

    private SpannableString getFormattedResultOneLiner() {

        // init state to zero (i.e. unknown state)
        setResultStateInteger(0);

        // note: we used limbo as initial state at this point

        // construct result one-liner spannable string
        SpannableStringBuilder resultLine = new SpannableStringBuilder();
        SpannableStringBuilder titleLine = new SpannableStringBuilder();
        int startResLine = resultLine.length();
        int countBadDeltaHosts = getCountBadDeltaHosts();
        int countBadDeltaKus = getCountBadDeltaKus();
        if (countBadDeltaHosts + countBadDeltaKus == 0) {
            resultLine.append("All dHost okay, and all dKu okay.");
            resultLine.setSpan(new ForegroundColorSpan(Color.GREEN), startResLine, resultLine.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            setResultStateInteger(1);
            mResultState.setState(mGoodResultState);
            mResultState.setText("ALL DELTAS IN RANGE.");
        }
        else if (isBadPhoneHostDelta()) {
            resultLine.append("Bad phone host delta.");
            resultLine.setSpan(new ForegroundColorSpan(Color.RED), startResLine, resultLine.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            setResultStateInteger(-1);
            mResultState.setState(mBadResultState);
            mResultState.setText("ABS(PHONE-HOST) DELTA TOO BIG.");
        }
        else {
            startResLine = resultLine.length();
            if (countBadDeltaHosts > 0) {
                resultLine.append(String.format("%d bad dHost, ", countBadDeltaHosts));
                resultLine.setSpan(new ForegroundColorSpan(Color.RED), startResLine, resultLine.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            else {
                resultLine.append("all dHost okay, ");
                resultLine.setSpan(new ForegroundColorSpan(Color.GREEN), startResLine, resultLine.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            startResLine = resultLine.length();
            if (countBadDeltaKus > 0) {
                resultLine.append(String.format("%d bad dKu.", countBadDeltaKus));
                resultLine.setSpan(new ForegroundColorSpan(Color.RED), startResLine, resultLine.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                setResultStateInteger(-1);
                mResultState.setState(mBadResultState);
                mResultState.setText("KU DELTA(S) OUT OF RANGE.");
            }
            else {
                resultLine.append("all dKu okay.");
                resultLine.setSpan(new ForegroundColorSpan(Color.GREEN), startResLine, resultLine.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        titleLine.append(mResultState.getText());
        titleLine.setSpan(new ForegroundColorSpan(mResultState.getColor()), 0, titleLine.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return SpannableString.valueOf(resultLine);
        //return SpannableString.valueOf(titleLine);
    }

    private List<SpannableString> getFormattedResults() {

        // init state to zero (i.e. unknown state)
        setResultStateInteger(0);

        // note: we used limbo as initial state at this point

        // construct result one-liner spannable string
        List<SpannableString> results = new ArrayList<SpannableString>();
        SpannableStringBuilder resultLine = new SpannableStringBuilder();
        SpannableStringBuilder titleLine = new SpannableStringBuilder();
        int startResLine = resultLine.length();
        int countBadDeltaHosts = getCountBadDeltaHosts();
        int countBadDeltaKus = getCountBadDeltaKus();
        if (countBadDeltaHosts + countBadDeltaKus == 0) {
            resultLine.append("All dHost okay, and all dKu okay.");
            resultLine.setSpan(new ForegroundColorSpan(Color.GREEN), startResLine, resultLine.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            setResultStateInteger(1);
            mResultState.setState(mGoodResultState);
            mResultState.setText("ALL DELTAS IN RANGE.");
        }
        else if (isBadPhoneHostDelta()) {
            resultLine.append("Bad phone host delta.");
            resultLine.setSpan(new ForegroundColorSpan(Color.RED), startResLine, resultLine.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            setResultStateInteger(-1);
            mResultState.setState(mBadResultState);
            mResultState.setText("ABS(PHONE-HOST) DELTA TOO BIG.");
        }
        else {
            startResLine = resultLine.length();
            if (countBadDeltaHosts > 0) {
                resultLine.append(String.format("%d bad dHost, ", countBadDeltaHosts));
                resultLine.setSpan(new ForegroundColorSpan(Color.RED), startResLine, resultLine.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            else {
                resultLine.append("all dHost okay, ");
                resultLine.setSpan(new ForegroundColorSpan(Color.GREEN), startResLine, resultLine.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            startResLine = resultLine.length();
            if (countBadDeltaKus > 0) {
                resultLine.append(String.format("%d bad dKu.", countBadDeltaKus));
                resultLine.setSpan(new ForegroundColorSpan(Color.RED), startResLine, resultLine.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                setResultStateInteger(-1);
                mResultState.setState(mBadResultState);
                mResultState.setText("KU DELTA(S) OUT OF RANGE.");
            }
            else {
                resultLine.append("all dKu okay.");
                resultLine.setSpan(new ForegroundColorSpan(Color.GREEN), startResLine, resultLine.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        titleLine.append(mResultState.getText());
        titleLine.setSpan(new ForegroundColorSpan(mResultState.getColor()), 0, titleLine.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        results.add(SpannableString.valueOf(resultLine));
        results.add(SpannableString.valueOf(titleLine));
        return results;
    }

}


text:
/**
 * @fileoverview Prevent usage of setState in componentDidUpdate
 * @author Yannick Croissant
 */
'use strict';

// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------

module.exports = function(context) {

  var mode = context.options[0] || 'never';

  // --------------------------------------------------------------------------
  // Public
  // --------------------------------------------------------------------------

  return {

    CallExpression: function(node) {
      var callee = node.callee;
      if (
        callee.type !== 'MemberExpression' ||
        callee.object.type !== 'ThisExpression' ||
        callee.property.name !== 'setState'
      ) {
        return;
      }
      var ancestors = context.getAncestors(callee).reverse();
      var depth = 0;
      for (var i = 0, j = ancestors.length; i < j; i++) {
        if (/Function(Expression|Declaration)$/.test(ancestors[i].type)) {
          depth++;
        }
        if (
          (ancestors[i].type !== 'Property' && ancestors[i].type !== 'MethodDefinition') ||
          ancestors[i].key.name !== 'componentDidUpdate' ||
          (mode === 'allow-in-func' && depth > 1)
        ) {
          continue;
        }
        context.report(callee, 'Do not use setState in componentDidUpdate');
        break;
      }
    }
  };

};

module.exports.schema = [{
  enum: ['allow-in-func']
}];

redpajama_set_name: RedPajamaGithub


text:
<?php
/** @noinspection PhpFullyQualifiedNameUsageInspection */
/** @noinspection PhpUnhandledExceptionInspection */

namespace ePHP\Exception;

class CommonException extends \Exception
{
    // 错误堆栈
    protected $ephpTraceString = '';

    /**
     * @param string $message 错误消息
     * @param integer $code 错误码
     * @param mixed $previous
     * @noinspection SpellCheckingInspection
     */
    public function __construct($message, $code = 0, $previous = null)
    {
        // 5.3.0  The previous parameter was added.
        // 5.3.0 以后previous才新增的
        parent::__construct($message, $code);

        $this->ephpTraceString = $this->getTraceAsString();

        if (is_array($previous)) {
            $this->file = $previous['errfile'];
            $this->line = $previous['errline'];
        } elseif (is_object($previous)) {
            $this->file            = $previous->getFile();
            $this->line            = $previous->getLine();
            $this->ephpTraceString = $previous->getTraceAsString();
        }
    }

    public function __toString()
    {
        $str = "异常信息\n-----------------------------------\n" . $this->getMessage() . "\n"
        . "-----------------------------------\n" . $this->ephpTraceString . "\n-----------------------------------\n";

        // 记录异常信息到文件中
        wlog('ExceptionLog', $str);

        if (PHP_SAPI == 'cli' || serverv('HTTP_X_REQUESTED_WITH') == "XMLHttpRequest" ) {
            echo '<meta charset="UTF-8"/><pre>' . $str . '</pre>';
        } else {
            \cc('error', $str);
        }

        return '';
    }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
in Saccardo, Syll. fung. (Abellini) 22: 20 (1913)

#### Original name
Alphitomorpha fuliginea Schltdl., 1819

### Remarks
null


text:
package edu.mum.lab3;

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

/**
 * Created by dewei.xiang on 7/11/2017.
 */
public class AbstractMarket {
    Map<String,Double> stocklist = new HashMap<String,Double>();
    public Map<String, Double> getStocklist() {
        return stocklist;
    }
}


text:
package org.apache.hadoop.chukwa.extraction.demux.processor.mapper;

public class UnknownRecordTypeException extends Exception {

  /**
	 *
	 */
  private static final long serialVersionUID = 8925135975093252279L;

  public UnknownRecordTypeException() {
  }

  public UnknownRecordTypeException(String message) {
    super(message);
  }

  public UnknownRecordTypeException(Throwable cause) {
    super(cause);
  }

  public UnknownRecordTypeException(String message, Throwable cause) {
    super(message, cause);
  }

}


text:
using System;
using System.Linq;
using SSW.DataOnion.Interfaces;
using SSW.DataOnion.Sample.Data;
using SSW.DataOnion.Sample.Entities;
using SSW.DataOnion.Sample.Entities.Exceptions;

namespace SSW.DataOnion.Sample.WebUI.Services.Query
{
    public interface ISchoolQueryService
    {
        Student GetStudentDetails(Guid studentId);
        Student GetStudentDetails2(Guid studentId);
    }

    public class SchoolQueryService : ISchoolQueryService
    {
        private readonly IAmbientDbContextLocator dbContextLocator;
        private readonly IRepositoryLocator repositoryLocator;

        public SchoolQueryService(IAmbientDbContextLocator dbContextLocator, IRepositoryLocator repositoryLocator)
        {
            Guard.AgainstNull(dbContextLocator, nameof(dbContextLocator));
            Guard.AgainstNull(repositoryLocator, nameof(repositoryLocator));

            this.dbContextLocator = dbContextLocator;
            this.repositoryLocator = repositoryLocator;
        }

        public Student GetStudentDetails(Guid studentId)
        {
            Guard.AgainstNullOrEmptyGuid(studentId, nameof(studentId));
            var student = this.repositoryLocator.GetRepository<Student>().Get().SingleOrDefault(s => s.Id == studentId);
            return student;
        }

        public Student GetStudentDetails2(Guid studentId)
        {
            Guard.AgainstNullOrEmptyGuid(studentId, nameof(studentId));
            var student = this.dbContextLocator.Get<SchoolDbContext>().Students.SingleOrDefault(s => s.Id == studentId);
            return student;
        }
    }
}


text:
class UnitsController < ApplicationController
  before_action :load_enrollment
  before_action :check_prerequisites

  def complete
    if @unit_enrollment.completed?
      logger.info "Unit is already completed"
      redirect_to next_step
    elsif @unit_enrollment.can_be_completed?
      logger.info "Marking unit as complete"
      @unit_enrollment.complete!
      redirect_to next_step
    else
      head :forbidden
    end
  end

private
  def load_enrollment
    @unit = Unit.find(params[:id])
    @lesson = @unit.lesson
    @course = @lesson.course
    @course_enrollment = current_user.enrollments.find_by!(course: @course)
    @lesson_enrollment = @course_enrollment.lesson_enrollments.find_by!(lesson: @lesson)
    @unit_enrollment = @lesson_enrollment.start_unit!(@unit)
  end

  def check_prerequisites
    unless @unit.first? || @lesson_enrollment.has_completed?(@unit.prev)
      redirect_to lesson_path(@lesson), alert: 'You must complete the previous units before you can access this unit'
    end
  end

  def next_step
    @unit.next || @lesson.first_question || @lesson
  end

  helper_method def next_label
    case next_step
    when Unit then 'Next Unit'
    when Question then 'Take Quiz'
    when Lesson then 'Complete Lesson'
    end
  end

end


text:
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;

namespace Com.Aspose.PDF.Model {
  public class FieldResponse {
    public Field Field { get; set; }

    public string Code { get; set; }

    public string Status { get; set; }

    public override string ToString()  {
      var sb = new StringBuilder();
      sb.Append("class FieldResponse {\n");
      sb.Append("  Field: ").Append(Field).Append("\n");
      sb.Append("  Code: ").Append(Code).Append("\n");
      sb.Append("  Status: ").Append(Status).Append("\n");
      sb.Append("}\n");
      return sb.ToString();
    }
  }
  }


text:
package v1

import (
	"github.com/google/go-containerregistry/pkg/v1/types"
)

// ImageIndex defines the interface for interacting with an OCI image index.
type ImageIndex interface {
	// MediaType of this image's manifest.
	MediaType() (types.MediaType, error)

	// Digest returns the sha256 of this index's manifest.
	Digest() (Hash, error)

	// IndexManifest returns this image index's manifest object.
	IndexManifest() (*IndexManifest, error)

	// RawIndexManifest returns the serialized bytes of IndexManifest().
	RawIndexManifest() ([]byte, error)
}


text:
using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;

namespace You {
namespace Utils {
namespace UnitTests {

TEST_CLASS(StringSimilarityTests) {
	/// Tests the class for both narrow and wide strings.
	template<typename T>
	void testContainsImpl(const T& lhs, const T& rhs, bool expect) {
		Assert::AreEqual(expect, similar_to<T>()(lhs, rhs));
	}

	/// Tests the class from narrow string input.
	void testContains(const char* lhs, const char* rhs, bool expect) {
		std::wstring lhsWString(boost::lexical_cast<std::wstring>(lhs));
		std::wstring rhsWString(boost::lexical_cast<std::wstring>(rhs));
		std::string lhsString(boost::lexical_cast<std::string>(lhs));
		std::string rhsString(boost::lexical_cast<std::string>(rhs));

		testContainsImpl(lhsWString, rhsWString, expect);
		testContainsImpl(lhsString, rhsString, expect);
	}

	TEST_METHOD(emptyStringDoesNotContain) {
		testContains("", "", false);
	}

	TEST_METHOD(emptySearchDoesNotMatch) {
		testContains("abc", "", false);
	}

	TEST_METHOD(singleWordContains) {
		testContains("ab", "a", true);
		testContains("ab", "b", true);
	}

	TEST_METHOD(singleWordSupersetDoesNotContain) {
		testContains("a", "ab", false);
	}

	TEST_METHOD(multiWordContains) {
		testContains("ab cd", "cd", true);
	}

	TEST_METHOD(searchMustMatchAll) {
		testContains("abc", "ab bc", true);
		testContains("abc", "ab cd", false);
	}

	TEST_METHOD(caseInsensitiveCompare) {
		testContains("abc", "AB BC", true);
	}
};

}  // namespace UnitTests
}  // namespace Utils
}  // namespace You


text:
/***************************************************************************
                           ImportResources.java  -  description
                             -------------------
    begin                : may 2003

 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

package net.sourceforge.ganttproject.action;

import java.awt.event.ActionEvent;
import java.io.File;
import java.net.URL;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ImageIcon;

import net.sourceforge.ganttproject.GanttProject;
import net.sourceforge.ganttproject.io.GanttXMLOpen;
import net.sourceforge.ganttproject.gui.OpenFileDialog;
import net.sourceforge.ganttproject.language.GanttLanguage;
import net.sourceforge.ganttproject.parser.DependencyTagHandler;
import net.sourceforge.ganttproject.parser.ResourceTagHandler;
import net.sourceforge.ganttproject.parser.RoleTagHandler;
import net.sourceforge.ganttproject.resource.ResourceManager;
import net.sourceforge.ganttproject.roles.RoleManager;
import net.sourceforge.ganttproject.task.TaskManager;
/**
  *Action connected to the menu item for importe some resources
  */
public class ImportResources extends AbstractAction {
    private final TaskManager myTaskManager;
    private final ResourceManager myResourceManager;
    private final GanttProject myproject;
    private final RoleManager myRoleManager;

    public ImportResources(ResourceManager resourceManager, TaskManager taskManager, RoleManager roleManager, GanttProject project) {
        myTaskManager = taskManager;
        myRoleManager = roleManager;
		GanttLanguage language = GanttLanguage.getInstance();

		this.putValue(AbstractAction.NAME, language.getText("importResources"));
        myResourceManager = resourceManager;

		URL iconUrl = this.getClass().getClassLoader().getResource("icons/impres_16.gif");
        if(iconUrl!=null) {
            this.putValue(Action.SMALL_ICON, new ImageIcon(iconUrl));
        }

				myproject=project;
    }
	/**
	 * @see java.awt.event.ActionListener#actionPerformed(ActionEvent)
	 */
	public void actionPerformed(ActionEvent event) {
        File file = getResourcesFile();
        if (file!=null) {
            GanttXMLOpen loader = new GanttXMLOpen(myTaskManager);
            ResourceTagHandler tagHandler = new ResourceTagHandler(myResourceManager, myRoleManager);
            DependencyTagHandler dependencyHandler = new DependencyTagHandler(loader.getContext(), myTaskManager);
			RoleTagHandler rolesHandler = new RoleTagHandler(RoleManager.Access.getInstance());
            loader.addTagHandler(tagHandler);
            loader.addTagHandler(dependencyHandler);
			loader.addTagHandler(rolesHandler);
            loader.load(file);
        }
	}

    private File getResourcesFile() {
        OpenFileDialog openDialog = new OpenFileDialog(myproject);
        File result = openDialog.show();
        return result;
    }

}


text:
#ifndef __YAFFS_GETBLOCKINFO_H__
#define __YAFFS_GETBLOCKINFO_H__

#include "yaffs_guts.h"
#include "yaffs_trace.h"

/* Function to manipulate block info */
static inline struct yaffs_block_info *yaffs_get_block_info(struct yaffs_dev
							      *dev, int blk)
{
	if (blk < dev->internal_start_block || blk > dev->internal_end_block) {
		yaffs_trace(YAFFS_TRACE_ERROR,
			"**>> yaffs: get_block_info block %d is not valid",
			blk);
		BUG();
	}
	return &dev->block_info[blk - dev->internal_start_block];
}

#endif


text:
<?php

namespace Radiant\Language;

class JavaScript extends Generic {
    protected function _preProcess() {
        parent::_addStringPattern();

        parent::_preProcess();
        $this->_addPattern('/\$\(/', '$(');
        $this->_addPattern('/(.*)(\.)(.*)(\s?=\s?)function/', '$1$2$3$4function');
        $this->_addPattern('/(.*?(\s)?)=(\s)?function/', '$1=$2function');
        $this->_addPattern('/(.*?(\s)?)\:(\s)?function/', '$1:$2function');
        $this->_addPattern('/\./', '.');
        $this->_addPattern('/(document|window)/', '$1');
    }

    protected function _addStringPattern() {
    }
}


text:
#pragma once
#ifndef OGLPLUS_FWD_1107121519_HPP
#define OGLPLUS_FWD_1107121519_HPP

#include <oglplus/config_compiler.hpp>
#include <type_traits>
#include <cstddef>

namespace oglplus {

// Nothing
struct Nothing { typedef int _value_type; };

// Angle
template <typename T>
class Angle;

template <typename T>
T Radians(const Angle<T>&);

template <typename T>
T Degrees(const Angle<T>&);

template <typename T>
T Sin(const Angle<T>&);

template <typename T>
T Cos(const Angle<T>&);

template <typename T>
T Tan(const Angle<T>&);

// Vector
template <typename T, std::size_t N>
class Vector;

template <typename T, std::size_t N>
const T* Data(const Vector<T, N>& a);

template <typename T, std::size_t N>
std::size_t Size(const Vector<T, N>&);

template <typename T, std::size_t N>
T At(const Vector<T, N>& a, std::size_t i);

template <typename T, std::size_t N>
T At(const Vector<T, N>& a, std::size_t i, T fallback);

// Quaternion
template <typename T>
class Quaternion;

// Matrix
template <typename T, std::size_t Rows, std::size_t Cols>
class Matrix;

template <typename T, std::size_t R, std::size_t C>
const T* Data(const Matrix<T, R, C>& matrix);

template <typename T, std::size_t R, std::size_t C>
std::size_t Size(const Matrix<T, R, C>&);

template <typename T, std::size_t R, std::size_t C>
std::size_t Rows(const Matrix<T, R, C>&);

template <typename T, std::size_t R, std::size_t C>
std::size_t Cols(const Matrix<T, R, C>&);

template <typename T, std::size_t R, std::size_t C>
T At(const Matrix<T, R, C>& matrix, std::size_t i, std::size_t j);

// ObjectTypeId
template <typename ObjectOps>
struct ObjectTypeId;

template <typename Id>
struct ObjectTypeById;

#define OGLPLUS_OBJECT_TYPE_ID(OBJECT, ID) \
template <> struct ObjectTypeId<OBJECT##Ops> \
 : public std::integral_constant<int, ID> { }; \
template <> struct ObjectTypeById<std::integral_constant<int, ID> > \
{ typedef OBJECT##Ops Type; };

class RenderbufferOps;
OGLPLUS_OBJECT_TYPE_ID(Renderbuffer, 1)

class FramebufferOps;
OGLPLUS_OBJECT_TYPE_ID(Framebuffer, 2)

class TextureOps;
OGLPLUS_OBJECT_TYPE_ID(Texture, 3)

class BufferOps;
OGLPLUS_OBJECT_TYPE_ID(Buffer, 4)

class QueryOps;
OGLPLUS_OBJECT_TYPE_ID(Query, 5)

class ProgramPipelineOps;
OGLPLUS_OBJECT_TYPE_ID(ProgramPipeline, 6)

class ProgramOps;
OGLPLUS_OBJECT_TYPE_ID(Program, 7)

class TransformFeedbackOps;
OGLPLUS_OBJECT_TYPE_ID(TransformFeedback, 8)

class SamplerOps;
OGLPLUS_OBJECT_TYPE_ID(Sampler, 9)

class VertexArrayOps;
OGLPLUS_OBJECT_TYPE_ID(VertexArray, 10)

class ShaderOps;
OGLPLUS_OBJECT_TYPE_ID(Shader, 11)

class PerfMonitorAMDOps;
OGLPLUS_OBJECT_TYPE_ID(PerfMonitorAMD, 12)

class PathNVOps;
OGLPLUS_OBJECT_TYPE_ID(PathNV, 13)

class DSATextureEXTOps;
OGLPLUS_OBJECT_TYPE_ID(DSATextureEXT, 14)

class DSABufferEXTOps;
OGLPLUS_OBJECT_TYPE_ID(DSABufferEXT, 15)

class DSAFramebufferEXTOps;
OGLPLUS_OBJECT_TYPE_ID(DSAFramebufferEXT, 16)

class DSARenderbufferEXTOps;
OGLPLUS_OBJECT_TYPE_ID(DSARenderbufferEXT, 17)

class DSAVertexArrayEXTOps;
OGLPLUS_OBJECT_TYPE_ID(DSAVertexArrayEXT, 18)

} // namespace oglplus

#endif // include guard


text:
nanostat compares statistics about nanobench results.

## Installation

You need to have [Go](https://golang.org) installed. Then run:

    go get -u go.skia.org/infra/perf/nanostat

If you have `$GOPATH` or `$GOBIN` set then `nanostat` should appear in your
path, otherwise it will be installed at `$HOME/go/bin/nanostat`.

## Description

Each input file should be a JSON output file from nanobench.

Invoked on a pair of input files, nanostat computes statistics for each
file and a column showing the percent change in mean from the first to
the second file. Next to the percent change, nanostat shows the p-value
and sample sizes from a test of the two distributions of nanobench
results.

For example in the results below, 'p' equals 0.001 or 0.1%, and the
analysis was done with 10 samples from the first file and 8 samples from
the second file.

             old          new  delta     stats            name
      2.15 ±  5%   2.00 ±  2%   -7%   (p=0.001, n=10+ 8)  tabl_digg.skp

Small p-values indicate that the two distributions are
significantly different. If the test indicates that there was no
significant change between the two benchmarks (defined as p > alpha),
nanostat displays a single ~ instead of the percent change.

## Example

Suppose we collect benchmark results from running

    out/Release/nanobench --config gl 8888 --outResultsFile old.json

Then make some changes to the code, recompile nanobench and run:

    out/Release/nanobench --config gl 8888 --outResultsFile new.json

Then nanostat summarizes the differences between the old and new runs:

    $ nanostat --iqrr old.json new.json
              old          new  delta         s            name
       0.78 ±  3%   0.72 ±  3%   -8%   (p=0.000, n=10+10)  desk_wowwiki.skp
       2.15 ±  5%   2.00 ±  2%   -7%   (p=0.001, n=10+ 8)  tabl_digg.skp
       3.08 ±  2%   2.96 ±  3%   -4%   (p=0.001, n= 9+10)  desk_facebook.skp
       0.71 ±  2%   0.69 ±  3%   -3%   (p=0.028, n= 9+10)  desk_ebay.skp
       4.59 ±  1%   4.46 ±  1%   -3%   (p=0.000, n=10+ 8)  desk_linkedin.skp
       1.40 ±  1%   1.39 ±  0%   -1%   (p=0.011, n= 9+ 9)  desk_css3gradients.skp
    $

## Usage

    usage: nanostat [options] old.json new.json
    options:
      -all
           If true then include insignificant changes in output.
      -alpha float
           Consider a change significant if p < α. Must be > 0. (default 0.05).
      -iqrr
           If true then remove outliers in the samples using the Interquartile Range Rule.
      -sort order
           Sort by order: [-]delta, [-]name (default "delta")
      -test string
           The type of test to do, 'utest' for Mann-Whitney U test, and 'ttest' for a Two Sample Welch T test. (default "utest")

To get help:

    $ nanostat -h


text:
namespace Slash.AI.BehaviorTrees.Implementations.Composites
{
    using System;
    using System.Collections.Generic;
    using System.Xml.Serialization;

    using Slash.AI.BehaviorTrees.Enums;
    using Slash.AI.BehaviorTrees.Interfaces;
    using Slash.AI.BehaviorTrees.Tree;

    /// <summary>
    ///   The Parallel composite acts in a similar way to the Sequence composite. It has a set of child tasks, and it runs them until one of them fails. At that point, the Parallel task as a whole fails. If all of the child tasks complete successfully, the Parallel task returns with success. In this way, it is identical to the Sequence task and its non-deterministic variations. The difference is the way it runs those tasks. Rather than running them one at a time, it runs them all simultaneously. We can think of it as creating a bunch of new threads, one per child, and setting the child tasks off together.
    /// </summary>
    [Serializable]
    public class Parallel : Composite<Parallel.Data>
    {
        #region Constructors and Destructors

        /// <summary>
        ///   Initializes a new instance of the <see cref="Parallel" /> class. Constructor.
        /// </summary>
        /// <param name="children"> Child tasks. </param>
        public Parallel(List<ITask> children)
            : base(children)
        {
        }

        /// <summary>
        ///   Initializes a new instance of the <see cref="Parallel" /> class. Constructor.
        /// </summary>
        public Parallel()
        {
        }

        #endregion

        #region Public Properties

        /// <summary>
        ///   Main task. If set the parallel will run as long as the main task runs. When the main task ends, all other tasks which still run are aborted. If not set the parallel will run as long as any task runs.
        /// </summary>
        [XmlIgnore]
        public ITask MainTask { get; set; }

        /// <summary>
        ///   Xml serialization of the main task index.
        /// </summary>
        [XmlElement("MainTask")]
        public int MainTaskIndex
        {
            get
            {
                return this.Children.IndexOf(this.MainTask);
            }

            set
            {
                this.MainTask = value >= 0 && value < this.Children.Count ? this.Children[value] : null;
            }
        }

        #endregion

        #region Public Methods and Operators

        /// <summary>
        ///   Activation. This method is called when the task was chosen to be executed. It's called right before the first update of the task. The task can setup its specific task data in here and do initial actions.
        /// </summary>
        /// <param name="agentData"> Agent data. </param>
        /// <param name="decisionData"> Decision data to use in activate method. </param>
        /// <returns> The SlashGames.AI.BehaviorTrees.Enums.ExecutionStatus. </returns>
        public override ExecutionStatus Activate(IAgentData agentData, IDecisionData decisionData)
        {
            DecisionData parallelDecisionData = decisionData as DecisionData;
            if (parallelDecisionData == null)
            {
                throw new ArgumentException("Got invalid decision data, expected data for Parallel task.");
            }

            Data data = new Data();

            // Activate all children.
            ExecutionStatus executionStatus = ExecutionStatus.Running;
            data.ChildrenData = new ITaskData[this.Children.Count];
            ++agentData.CurrentDeciderLevel;
            for (int childIdx = 0; childIdx < this.Children.Count; childIdx++)
            {
                ExecutionStatus childExecutionStatus = this.Children[childIdx].Activate(
                    agentData, parallelDecisionData.ChildrenDecisionData[childIdx]);
                if (childExecutionStatus == ExecutionStatus.Failed)
                {
                    // If one fails, all others also fail.
                    executionStatus = ExecutionStatus.Failed;

                    // Don't continue as we already have a result.
                    break;
                }

                // If main task already succeeded, sub tasks don't have to be activated.
                if (childExecutionStatus == ExecutionStatus.Success && childIdx == this.MainTaskIndex)
                {
                    executionStatus = ExecutionStatus.Success;
                    break;
                }

                // If not running, the child task don't have to be added to running children.
                if (childExecutionStatus != ExecutionStatus.Running)
                {
                    continue;
                }

                data.ChildrenData[childIdx] = agentData.CurrentTaskData;
                data.RunningChildren.Add(childIdx);
            }

            if (executionStatus != ExecutionStatus.Running)
            {
                // Deactivate remaining running children.
                foreach (int childIdx in data.RunningChildren)
                {
                    agentData.CurrentTaskData = data.ChildrenData[childIdx];
                    this.Children[childIdx].Deactivate(agentData);
                }
            }

            --agentData.CurrentDeciderLevel;

            // Store task data.
            agentData.CurrentTaskData = data;

            return executionStatus;
        }

        /// <summary>
        ///   Deactivation.
        /// </summary>
        /// <param name="agentData"> Agent data. </param>
        public override void Deactivate(IAgentData agentData)
        {
            Data data = agentData.CurrentTaskData as Data;
            if (data == null)
            {
                throw new ArgumentException("Got invalid task data, expected data for Parallel task.");
            }

            // Deactivate all running children.
            ++agentData.CurrentDeciderLevel;
            foreach (int childIdx in data.RunningChildren)
            {
                agentData.CurrentTaskData = data.ChildrenData[childIdx];
                this.Children[childIdx].Deactivate(agentData);
            }

            --agentData.CurrentDeciderLevel;

            base.Deactivate(agentData);
        }

        /// <summary>
        ///   Depending on the group policy of its parent, the floating point return value indicates whether the task will be activated.
        /// </summary>
        /// <param name="agentData"> Agent data. </param>
        /// <param name="decisionData"> Decision data to use in activate method. </param>
        /// <returns> Floating point value used to decide if the task will be activated. </returns>
        public override float Decide(IAgentData agentData, ref IDecisionData decisionData)
        {
            List<IDecisionData> childrenDecisionData = new List<IDecisionData>();

            // Check if all children want to run.
            float maxChildDecisionValue = 0.0f;
            foreach (ITask child in this.Children)
            {
                IDecisionData childDecisionData = null;
                float childDecisionValue = child.Decide(agentData, ref childDecisionData);
                maxChildDecisionValue = Math.Max(maxChildDecisionValue, childDecisionValue);

                // If one doesn't want to run, we don't run the whole task.
                if (childDecisionValue <= 0.0f)
                {
                    return 0.0f;
                }

                childrenDecisionData.Add(childDecisionData);
            }

            decisionData = new DecisionData { ChildrenDecisionData = childrenDecisionData };

            return maxChildDecisionValue;
        }

        /// <summary>
        ///   The equals.
        /// </summary>
        /// <param name="other"> The other. </param>
        /// <returns> The System.Boolean. </returns>
        public bool Equals(Parallel other)
        {
            if (ReferenceEquals(null, other))
            {
                return false;
            }

            if (ReferenceEquals(this, other))
            {
                return true;
            }

            return base.Equals(other) && Equals(other.MainTask, this.MainTask);
        }

        /// <summary>
        ///   The equals.
        /// </summary>
        /// <param name="obj"> The obj. </param>
        /// <returns> The System.Boolean. </returns>
        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj))
            {
                return false;
            }

            if (ReferenceEquals(this, obj))
            {
                return true;
            }

            return this.Equals(obj as Parallel);
        }

        /// <summary>
        ///   Generates a collection of active task nodes under this task. Used for debugging only.
        /// </summary>
        /// <param name="agentData"> Agent data. </param>
        /// <param name="taskNode"> Task node this task is located in. </param>
        /// <param name="activeTasks"> Collection of active task nodes. </param>
        public override void GetActiveTasks(
            IAgentData agentData, TaskNode taskNode, ref ICollection<TaskNode> activeTasks)
        {
            Data data = agentData.CurrentTaskData as Data;
            if (data == null)
            {
                throw new ArgumentException(string.Format("Expected parallel data for task '{0}'.", this.Name));
            }

            // Check if selector has an active child.
            if (data.RunningChildren.Count == 0)
            {
                return;
            }

            // Add task to active tasks and collect active tasks of active child.
            ++agentData.CurrentDeciderLevel;
            foreach (int childIdx in data.RunningChildren)
            {
                TaskNode childTaskNode = taskNode.CreateChildNode(this.Children[childIdx], childIdx);
                activeTasks.Add(childTaskNode);

                agentData.CurrentTaskData = data.ChildrenData[childIdx];
                this.Children[childIdx].GetActiveTasks(agentData, childTaskNode, ref activeTasks);
            }

            --agentData.CurrentDeciderLevel;
        }

        /// <summary>
        ///   The get hash code.
        /// </summary>
        /// <returns> The System.Int32. </returns>
        public override int GetHashCode()
        {
            unchecked
            {
                return (base.GetHashCode() * 397) ^ (this.MainTask != null ? this.MainTask.GetHashCode() : 0);
            }
        }

        /// <summary>
        ///   Per frame update.
        /// </summary>
        /// <param name="agentData"> Agent data. </param>
        /// <returns> Execution status after this update. </returns>
        public override ExecutionStatus Update(IAgentData agentData)
        {
            Data data = agentData.CurrentTaskData as Data;
            if (data == null)
            {
                throw new ArgumentException("Got invalid task data, expected data for Parallel task.");
            }

            if (data.RunningChildren.Count == 0)
            {
                return ExecutionStatus.Success;
            }

            ExecutionStatus executionStatus = ExecutionStatus.Running;
            List<int> runningChildren = new List<int>(data.RunningChildren);
            ++agentData.CurrentDeciderLevel;
            foreach (int childIdx in runningChildren)
            {
                agentData.CurrentTaskData = data.ChildrenData[childIdx];
                ExecutionStatus childExecutionStatus = this.Children[childIdx].Update(agentData);

                if (childExecutionStatus == ExecutionStatus.Failed)
                {
                    // Remove from running children.
                    data.RunningChildren.Remove(childIdx);

                    // If one fails, all others also fail.
                    executionStatus = ExecutionStatus.Failed;

                    // Don't continue as we already have a result.
                    break;
                }

                if (childExecutionStatus == ExecutionStatus.Success)
                {
                    // Remove from running children.
                    data.RunningChildren.Remove(childIdx);

                    if (data.RunningChildren.Count == 0 || this.MainTaskIndex == childIdx)
                    {
                        // If all succeeded or if main task succeeded, parallel is done.
                        executionStatus = ExecutionStatus.Success;

                        break;
                    }
                }
            }

            if (executionStatus != ExecutionStatus.Running)
            {
                // Deactivate remaining running children.
                foreach (int childIdx in data.RunningChildren)
                {
                    agentData.CurrentTaskData = data.ChildrenData[childIdx];
                    this.Children[childIdx].Deactivate(agentData);
                }
            }

            --agentData.CurrentDeciderLevel;

            return executionStatus;
        }

        #endregion

        /// <summary>
        ///   task data of a parallel task.
        /// </summary>
        public class Data : ITaskData
        {
            #region Fields

            /// <summary>
            ///   Data of running children.
            /// </summary>
            public IList<ITaskData> ChildrenData;

            /// <summary>
            ///   List of running children.
            /// </summary>
            public List<int> RunningChildren = new List<int>();

            #endregion
        }

        /// <summary>
        ///   The decision data.
        /// </summary>
        public class DecisionData : IDecisionData
        {
            #region Public Properties

            /// <summary>
            ///   Decision data of selected child.
            /// </summary>
            public List<IDecisionData> ChildrenDecisionData { get; set; }

            #endregion
        }
    }
}


text:
require File.expand_path(File.join(File.dirname(__FILE__), "..", "..", "spec_helper"))
startup_merb

require "mongrel"

describe Merb::Request do
  it "should handle file upload for multipart/form-data posts" do
    file = Struct.new(:read, :filename, :path).
      new("This is a text file with some small content in it.", "sample.txt", "sample.txt")
    m = Merb::Test::MultipartRequestHelper::Post.new :file => file
    body, head = m.to_multipart
    request = fake_request({:request_method => "POST", :content_type => head, :content_length => body.length}, :req => body)
    request.params[:file].should_not be_nil
    request.params[:file][:tempfile].class.should == Tempfile
    request.params[:file][:content_type].should == 'text/plain'
  end

  it "should accept env['rack.input'] as IO object (instead of StringIO)" do
    file = Struct.new(:read, :filename, :path).
      new("This is a text file with some small content in it.", "sample.txt", "sample.txt")
    m = Merb::Test::MultipartRequestHelper::Post.new :file => file
    body, head = m.to_multipart

    t = Tempfile.new("io")
    t.write(body)
    t.close

    fd = IO.sysopen(t.path)
    io = IO.for_fd(fd,"r")
    request = Merb::Test::RequestHelper::FakeRequest.new({:request_method => "POST", :content_type => 'multipart/form-data, boundary=----------0xKhTmLbOuNdArY', :content_length => body.length},io)

    running {request.params}.should_not raise_error
    request.params[:file].should_not be_nil
    request.params[:file][:tempfile].class.should == Tempfile
    request.params[:file][:content_type].should == 'text/plain'
  end

  it "should handle GET with a content_type but an empty body (happens in some browsers such as safari after redirect)" do
      request = fake_request({:request_method => "GET", :content_type => 'multipart/form-data, boundary=----------0xKhTmLbOuNdArY', :content_length => 0}, :req => '')
      running {request.params}.should_not raise_error
  end

end


text:
[« return to the patterns overview](../index.md)

# Resource Patterns

Resource events are essential to any non-trivial LaxarJS application, as they allow to share application resources and to collaborate on them.
Because events are always delivered _by copy_, there is no danger of widgets and activities performing conflicting operations on shared mutable state.

## The Master/Slave Pattern

When using the LaxarJS resource pattern, for a given resource there is usually a single widget (or activity) responsible for _providing_ it, in order for others to collaborate.
If applicable, that widget (the _resource master_) is also capable of persisting modifications to the resource.
The other collaborators are _slaves_ with respect to the shared resource.

Only the resource master may change the _identity_ of a shared resource, while the slaves may only trigger _modifications to the state_ of the resource.

### Example: Shopping Cart

As an example, consider a shopping cart widget that displays a list of _positions_ (articles and quantities) in a web shop application.
The user may select any of the positions, and a second widget will then show details on the _selected-position_ resource, such as a photo of the corresponding article.
The shopping cart widget is the resource master here, because it alone determines which article is currently selected.
The details widget is a slave, it can only act with respect to the currently selected article.

The details widget might even allow to modify the quantity of a given article within the cart, causing the shopping cart to remove a position when its quantity reaches zero.
However, the slave can never change _which_ position is currently the _selected-position_ .

### The _didReplace_ and _didUpdate_ Events

The identity and initial state of a resource is published through the _didReplace_ event by the resource master.
Modifications to a resource may be published through the _didUpdate_ event, by master or slaves.

| Event name                 | Payload Attribute | Type   | Description
|----------------------------|-------------------|--------|-------------------------------------------------------------
| `didReplace.{resource}`    |                   |        | _published by a resource master to define state and identity of a shared resource_
|                            | `resource`        | string | the topic through which the resource is shared (used in the payload _as well as_ in the event name)
|                            | `data`            | object | the (initial or new) state of the resource
| `didUpdate.{resource}`     |                   |        | _published by a resource master or by its slaves to publish modifications to the state of a shared resource_
|                            | `resource`        | string | _see above_
|                            | `patches`         | array  | A [JSON-Patch](https://tools.ietf.org/html/rfc6902) document (an array representing a sequence of incremental modifications)

Because modifications _(didUpdate)_ are transmitted incrementally, the resource master may use the `patches` attribute of the event payload to persist modifications using an [HTTP PATCH](http://tools.ietf.org/html/rfc5789) request.
To create and apply patches, you require `laxar-patterns` into your widget controller and use `createPatch` and `applyPatch` from its `json` API.

In support of a unidirectional data flow we strongly advise to only send updates from the master to the slaves and not the other way around.
This ensures that there really is only one source for the most recent state of a resource, and changes to it are encapsulated in just one location.
So instead of sending a _didUpdate_ event a slave expresses its wish to induce a modification on a resource via _takeActionRequest_ to the master.
The master then can modify the resource accordingly (possibly via server roundtrip) and publish the updated version as a whole via _didReplace_ or partially via _didUpdate_ event.

When sharing resources, keep in mind that resource events (like all LaxarJS events) are cloned for each receiver.
This makes it easy to write robust applications, but can lead to inefficiencies if very large resources are published.
In some cases, it might be worthwhile to factor out sub-resources relevant to the consumers.

## Asynchronous Resource Validation

Often the individual widgets sharing a resource know best how to validate their specific user input.
However, in the context of persistence or navigation the validity state of the overall resource or of the entire page is of interest.

Widgets and activities concerned with navigation and persistence should not be exposed to the details of resource validation [1].
To separate these concerns, widgets may issue _requests to validate a resource_ which other widgets may respond to.
Respondents may choose to validate immediately or asynchronously.

### The _validateRequest, willValidate_ and _didValidate_ Events

A widget may request validation of a resource using a `validateRequest` event.
Collaborators capable of performing validation on this resource respond by publishing a `willValidate` event.
After they have performed validation, possibly asynchronously, collaborators publish a `didValidate` event.

| Event name                   | Payload Attribute | Type   | Description
|------------------------------|-------------------|--------|------------------------------------------------------------
| `validateRequest.{resource}` |                   |        | _published by any widget that requires validation of the given resource_
|                              | `resource`        | string | the topic through which the resource is shared (used in the payload _as well as_ in the event name)
| `willValidate.{resource}`    |                   |        | _published by a widget that is about to perform validation of the given resource_
|                              | `resource`        | string | _see above_
| `didValidate.{resource}`     |                   |        | _published by a widget that has performed validation of the given resource_
|                              | `resource`        | string | _see above_
|                              | `outcome`         | string | One of `ERROR`, `WARNING`, `INFO` and `SUCCESS`
|                              | `data`            | array  | A list of _validation messages_ for the application user (see below)

### Validation Outcome and Validation Messages

The `didValidate` event contains information on the results of a validation:

- The _outcome_ determines if validation was successful:

  - `ERROR`: The resource is in an invalid state. If the receiver would normally persist the resource, it will probably not do so.
  - `WARNING`: The resource _probably_ contains problems. If the receiver would normally persist the resource, it should probably obtain user confirmation before doing so.
  - `INFO`: The resource _might_ contain problems or require user intervention. If the receiver would normally persist the resource, it might obtain confirmation or otherwise inform the user.
  - `SUCCESS`: No problems were found _by the sender_ of the event. If the receiver would normally persist the resource, it should proceed as far as the sender is concerned.

- The _validation messages_ (`data` array) contains additional details for the user. Each message is an object with at least these attributes:

  - `htmlMessage`: A validation message for the user (a _string_), to be interpreted as HTML markup
  - `level`: The severity of this particular vaidation message (a _string_), using the outcomes specified above
  - `sortKey`: The message priority (a _string_) that should be used for sorting messages lexicographically.

[1]: As an exception to this rule, a resource master may perform a (semantic) _overall_ validation after the individual editor widgets had their say.

## Saving Resources

Usually the resource master is responsible for saving user input where appropriate.
This can be achieved by performing a REST call for example, or by putting state into a container resource (as a slave) and requesting for the container to be persisted.

### The _saveRequest, willSave_ and _didSave_ Events

To request saving a resource, widgets may publish a `saveRequest` event.
Widgets capable of and configured for persisting the resource respond by publishing a `willSave` event.
After they have ensured persistence, usually asynchronously, collaborators publish a `didSave` event.

| Event name  - | Payload Attribute | Type   | Description
|------------------------------|-------------------|--------|------------------------------------------------------------
| `saveRequest.{resource}`     |                   |        | _published by any widget that requires persisting the given resource_
|                              | `resource`        | string | the topic through which the resource is shared (used in the payload _as well as_ in the event name)
| `willSave.{resource}`        |                   |        | _published by a widget that is about to persist the given resource_
|                              | `resource`        | string | _see above_
| `didSave.{resource}`         |                   |        | _published by a widget after saving the given resource_
|                              | `resource`        | string | _see above_
|                              | `outcome`         | string | `ERROR` or `SUCCESS`

The `didSave` event contains information on the _outcome_:

- `ERROR`: The resource could not be saved. The sender should also publish a `didEncounterError` event in this case.
- `SUCCESS`: The resource was saved successfully.

Depending on the use case, widgets might persist resources automatically every time they have been modified.
In this case, it is recommended for them to still respond to save requests, for best interoperability.

### RESTful State Management

The _saveRequest, willSave_ and _didSave_ events are mainly useful for CRUD driven frontends.
When building a RESTful application, resources are most probably shared frequently with services, and user interactions very often directly induce a server side effect.
A dedicated phase for persistence (i.e. saving all relevant resources) is less likely to occur.
Instead, consistency should somehow be checked before leaving a page, but how that is achieved depends on the functional use case.


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.spi.type;

import java.util.List;

import static java.lang.String.format;

public class QuantileDigestParametricType
        implements ParametricType
{
    public static final QuantileDigestParametricType QDIGEST = new QuantileDigestParametricType();

    @Override
    public String getName()
    {
        return StandardTypes.QDIGEST;
    }

    @Override
    public Type createType(TypeManager typeManager, List<TypeParameter> parameters)
    {
        checkArgument(parameters.size() == 1, "QDIGEST type expects exactly one type as a parameter, got %s", parameters);
        checkArgument(
                parameters.get(0).getKind() == ParameterKind.TYPE,
                "QDIGEST expects type as a parameter, got %s",
                parameters);
        // Validation check on the acceptable type (bigint, real, double) intentionally omitted
        // because this is validated in each function and to allow for consistent error messaging
        return new QuantileDigestType(parameters.get(0).getType());
    }

    private static void checkArgument(boolean argument, String format, Object... args)
    {
        if (!argument) {
            throw new IllegalArgumentException(format(format, args));
        }
    }
}


text:
Not my code! Included for something to speed-test against. It's a great library: more polished and featureful than
this one, but at the cost of speed and flexibility. Also needs to be compiled separately.

See http://jsoncpp.sourceforge.net/


text:
package io.sarl.pythongenerator.generator.configuration;

/** Configuration for the SARL-to-Python generator.
 *
 * @author $Author: sgalland$
 * @version $FullVersion$
 * @mavengroupid $GroupId$
 * @mavenartifactid $ArtifactId$
 * @since 0.8
 */
public class PyGeneratorConfiguration {

	/** Default value for the flag that indicates if the JVM types (not in {@code io.sarl.*})
	 * are implicitly supported by the type converter.
	 */
	public static final boolean DEFAULT_IMPLICIT_JVM_TYPES = true;

	/**
	 * Whether the JVM types are implicitly recognized by the type converter..
	 */
	private boolean isImplicitJvmTypes = DEFAULT_IMPLICIT_JVM_TYPES;

	/** Replies if the JVM types (not in {@code io.sarl.*}) are implicitly supported by the type converter.
	 *
	 * @return {@code true} if the implicit types are converted. {@code false} if no implicit type is converted.
	 */
	public boolean isImplicitJvmTypes() {
		return this.isImplicitJvmTypes;
	}

	/** Set if the JVM types (not in {@code io.sarl.*}) are implicitly supported by the type converter.
	 *
	 * @param enable {@code true} if the implicit types are converted. {@code false} if no implicit type is converted.
	 */
	public void setImplicitJvmTypes(boolean enable) {
		this.isImplicitJvmTypes = enable;
	}

}


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;

namespace SocialExplorer.IO.FastDBF
{

  public class DbfDataTruncateException: Exception
  {

    public DbfDataTruncateException(string smessage): base(smessage)
    {
    }

    public DbfDataTruncateException(string smessage, Exception innerException)
      : base(smessage, innerException)
    {
    }

    public DbfDataTruncateException(SerializationInfo info, StreamingContext context)
      : base(info, context)
    {
    }

  }
}


text:
var videoCOU=(function(config,functions){
    return{
        submitForm:function(form){
            var me=this;
            functions.showLoading();
            $(form).ajaxSubmit({
                dataType:"json",
                success:function(response){
                    if(response.success){
                        $().toastmessage("showSuccessToast",config.messages.optSuccess);
                        setTimeout(function(){
                            switch(category_id){
                                case 26:
                                    window.location.href="video/index";
                                    break;
                                case 17:
                                    window.location.href="video/child-draw";
                                    break;
                            }
                        },3000);
                    }else{
                        functions.ajaxReturnErrorHandler(response.error_code);
                    }
                },
                error:function(){
                    functions.ajaxErrorHandler();
                }
            });
        }
    }
})(config,functions);

$(document).ready(function(){
    $("#date").date_input();

    functions.createQiNiuUploader({
        maxSize:config.uploader.sizes.img,
        filter:config.uploader.filters.img,
        uploadBtn:"uploadBtn",
        multiSelection:false,
        multipartParams:null,
        uploadContainer:"uploadContainer",
        fileAddCb:null,
        progressCb:null,
        uploadedCb:function(info,file,up){
            if(info.w/info.h==16/9&&800<=info.w&&info.w<=1000){
                $("#imageUrl").val(info.url);

                $("#image").attr("src",info.url);

                $(".error[for='imageUrl']").remove();
            }else{
                $().toastmessage("showErrorToast",config.messages.imageSizeError);
            }
        }
    });
    $("#myForm").validate({
        ignore:[],
        rules:{
            thumb:{
                required:true
            },
            date:{
                required:true
            },
            title:{
                required:true,
                maxlength:32
            },
            memo:{
                required:true,
                maxlength:255
            }
        },
        messages:{
            thumb:{
                required:config.validErrors.required
            },
            date:{
                required:config.validErrors.required
            },
            title:{
                required:config.validErrors.required,
                maxlength:config.validErrors.maxLength.replace("${max}",32)
            },
            memo:{
                required:config.validErrors.required,
                maxlength:config.validErrors.maxLength.replace("${max}",255)
            }
        },
        submitHandler:function(form) {
            videoCOU.submitForm(form);
        }
    });
});


text:
from django.db.models import Count
from django.views.generic import View
from djangular.views.mixins import allowed_action, JSONResponseMixin

from core.mixins import AngularAppMixin, ChartsUtilityMixin
from core.helpers import cache_until_midnight

class OverviewJSONView(AngularAppMixin, ChartsUtilityMixin, JSONResponseMixin, View):

    @allowed_action
    def get_data(self, in_data):
        return {'views': self.view_count_today(),
                'visitors': self.visitor_count_today(),
                'unique_visitors': self.unique_visitor_count_today(),
                'mobile': self.mobile_percent(),
                'top_pages': self.top_pages()}

    def view_count_today(self):
        return len(self.pageviews_today.all())

    def visitor_count_today(self):
        return len(self.sessions_today.all())

    def unique_visitor_count_today(self):
        return len(set(self.sessions_today.values_list('user_id')))  # Turn list into a set to remove duplicates

    @cache_until_midnight
    def mobile_percent(self):
        pageviews = self.pageviews.filter(view_timestamp__gt=self.past_timestamp(days=5))
        if len(pageviews) == 0:
            return 0
        return int(100*len(self.pageviews.filter(session__user__mobile=True))/float(len(self.pageviews)))

    def top_pages(self):
        query = self.pageviews_today.values('path').annotate(count=Count('path')).order_by('-count')
        return list(query[:4])


text:
module Dogviz
  class MissingMatchBlockError < LookupError
    def initialize(context)
      super context, 'need to provide match block'
    end
  end
end


text:
import asyncio
import signal
import sys

import functools

from aiotinder.controllers.tinder import Tinder

facebook_id = ""
facebook_token = ""

async def shutdown(loop: asyncio.events.AbstractEventLoop) -> None:
    await asyncio.sleep(0.1)
    loop.close()

async def result(tinder: Tinder) -> None:
    users = await tinder.prospective_matches()
    for user in users:
        print("Name: {0}, Age: {1}".format(user.name, user.age))

def main() -> None:
    loop = asyncio.get_event_loop()
    loop.set_debug(True)
    loop.add_signal_handler(signal.SIGINT, functools.partial(shutdown, loop))
    tinder = Tinder(facebook_id, facebook_token)
    loop.run_until_complete(result(tinder))
    sys.exit(1)

if __name__ == "__main__":
    main()


text:
#ifndef CSSGroupingRule_h
#define CSSGroupingRule_h

#include "core/css/CSSRule.h"
#include "core/css/StyleRule.h"
#include "wtf/Vector.h"

namespace blink {

class ExceptionState;
class CSSRuleList;

class CSSGroupingRule : public CSSRule {
public:
    virtual ~CSSGroupingRule();

    virtual void reattach(StyleRuleBase*) OVERRIDE;

    CSSRuleList* cssRules() const;

    unsigned insertRule(const String& rule, unsigned index, ExceptionState&);
    void deleteRule(unsigned index, ExceptionState&);

    // For CSSRuleList
    unsigned length() const;
    CSSRule* item(unsigned index) const;

    virtual void trace(Visitor*) OVERRIDE;

protected:
    CSSGroupingRule(StyleRuleGroup* groupRule, CSSStyleSheet* parent);

    void appendCSSTextForItems(StringBuilder&) const;

    RefPtrWillBeMember<StyleRuleGroup> m_groupRule;
    mutable WillBeHeapVector<RefPtrWillBeMember<CSSRule> > m_childRuleCSSOMWrappers;
    mutable OwnPtrWillBeMember<CSSRuleList> m_ruleListCSSOMWrapper;
};

} // namespace blink

#endif // CSSGroupingRule_h


text:
The Most Effective way to make a InfiniteScrollView
1.master is a normal effect
2.another bransh is a show right side view effect
3.another2 bransh is a show left right side view effect

Support Cocoapod
pod 'PWInfiniteScrollViewLib'


text:
window.addEventListener('load', function() {

  /**
   * Fires off a request to get a remote manifest file
   */
  function init() {

    // get the local resources
    parseLocalImages();

    // start by loading the remote asset list
    RAL.Loader.load("remote_images.json",
      'text', // xhr response type
      onSuccessfulRMGet,
      onFailedRMGet);
  }

  function onSuccessfulRMGet(data) {
    var toLoad = JSON.parse(data);
    var imageToLoad = null;
    var remoteImage = null;
    var container = document.getElementById('mid');

    for(var i = 0; i < toLoad.images.length; i++) {

      imageToLoad = toLoad.images[i];

      // next add in an image directly from the script
      // with the highest queue priority
      remoteImage = new RAL.RemoteImage(imageToLoad);

      // attach the new image element to the DOM
      // (we could've passed in an image to the RemoteImage call
      // but since we didn't it created an image element)
      container.appendChild(remoteImage.element);

      // listen for the image being loaded
      // and spit out a console message
      remoteImage.addEventListener('loaded',
        onRemoteImageLoaded.bind(remoteImage));

      // also listen for cache problems like 'no-cache'
      remoteImage.addEventListener('cacheerror',
        onCacheError);

      // add it to the queue
      RAL.Queue.add(remoteImage);
    }

    go();
  }

  function onRemoteImageLoaded() {
    console.log("I have loaded the image from remote: " + this.src);
  }

  function onFailedRMGet() {
    console.warn("Could not load remote manifest");

    // just go get what we have queued
    go();
  }

  /**
   * Gets the images that are embedded in the page itself
   * and creates an additional image asset directly
   */
  function parseLocalImages() {

    // grab all images in the page
    var images = document.querySelectorAll('img');

    for (var i = 0; i < images.length; i++) {

      // wrap the image in a remote image
      // object and pass it to the queue
      // - set the image priority to the reverse
      //   of the querySelectorAll order
      var remoteImage = new RAL.RemoteImage({
        element: images[i],
        priority: i
      });

      // declared in app.js - lets us know if we
      // hit cache errors, e.g. no-cache
      remoteImage.addEventListener('cacheerror', onCacheError);

      RAL.Queue.add(remoteImage);
    }

    // next add in an image (sample-5.png) directly from the script
    // with the highest queue priority
    var finalImage = new RAL.RemoteImage({
      src: "images/sample-5.png",
      priority: RAL.Queue.getNextHighestPriority(),
      width: 376,
      height: 201
    });

    // just listen for the image being loaded
    // and add it into the document
    finalImage.addEventListener('loaded', function() {
      var img = finalImage.element;
      document.getElementById('mid').appendChild(img);
    });

    // add it to the queue
    RAL.Queue.add(finalImage);
  }

  function go() {

    // start the queue, maxed out
    // to 4 connections
    RAL.Queue.setMaxConnections(4);
    RAL.Queue.start();
  }

  // wait for the file manifest to be loaded
  // before attempting anything
  if(RAL.FileManifest.isReady()) {
    init();
  } else {
    RAL.FileManifest.registerOnReady(init);
  }

});


text:
'''
Test the cert_update plugin.
'''
#  Licensed to the Apache Software Foundation (ASF) under one
#  or more contributor license agreements.  See the NOTICE file
#  distributed with this work for additional information
#  regarding copyright ownership.  The ASF licenses this file
#  to you under the Apache License, Version 2.0 (the
#  "License"); you may not use this file except in compliance
#  with the License.  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import ports

Test.Summary = '''
Test cert_update plugin.
'''

Test.SkipUnless(
    Condition.HasProgram("openssl", "Openssl need to be installed on system for this test to work"),
    Condition.PluginExists('cert_update.so')
)

# Set up origin server
server = Test.MakeOriginServer("server")
request_header = {
    "headers": "GET / HTTP/1.1\r\nHost: doesnotmatter\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
response_header = {"headers": "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
server.addResponse("sessionlog.json", request_header, response_header)

# Set up ATS
ts = Test.MakeATSProcess("ts", command="traffic_manager", enable_tls=1)

# Set up ssl files
ts.addSSLfile("ssl/server1.pem")
ts.addSSLfile("ssl/server2.pem")
ts.addSSLfile("ssl/client1.pem")
ts.addSSLfile("ssl/client2.pem")

# reserve port, attach it to 'ts' so it is released later
ports.get_port(ts, 's_server_port')

ts.Disk.records_config.update({
    'proxy.config.diags.debug.enabled': 1,
    'proxy.config.diags.debug.tags': 'cert_update',
    'proxy.config.ssl.server.cert.path': '{0}'.format(ts.Variables.SSLDir),
    'proxy.config.ssl.server.private_key.path': '{0}'.format(ts.Variables.SSLDir),
    'proxy.config.ssl.client.cert.path': '{0}'.format(ts.Variables.SSLDir),
    'proxy.config.ssl.client.private_key.path': '{0}'.format(ts.Variables.SSLDir),
    'proxy.config.url_remap.pristine_host_hdr': 1
})

ts.Disk.ssl_multicert_config.AddLine(
    'dest_ip=* ssl_cert_name=server1.pem ssl_key_name=server1.pem'
)

ts.Disk.remap_config.AddLines([
    'map https://bar.com http://127.0.0.1:{0}'.format(server.Variables.Port),
    'map https://foo.com https://127.0.0.1:{0}'.format(ts.Variables.s_server_port)
])

ts.Disk.sni_yaml.AddLines([
    'sni:',
    '- fqdn: "*foo.com"',
    '  client_cert: "client1.pem"',
])

# Set up plugin
Test.PrepareInstalledPlugin('cert_update.so', ts)

# Server-Cert-Pre
# curl should see that Traffic Server presents bar.com cert from alice
tr = Test.AddTestRun("Server-Cert-Pre")
tr.Processes.Default.StartBefore(server)
tr.Processes.Default.StartBefore(Test.Processes.ts)
tr.Processes.Default.Command = (
    'curl --verbose --insecure --ipv4 --resolve bar.com:{0}:127.0.0.1 https://bar.com:{0}'.format(ts.Variables.ssl_port)
)
tr.Processes.Default.Streams.stderr = "gold/server-cert-pre.gold"
tr.Processes.Default.ReturnCode = 0
tr.StillRunningAfter = server

# Server-Cert-Update
tr = Test.AddTestRun("Server-Cert-Update")
tr.Processes.Default.Env = ts.Env
tr.Processes.Default.Command = (
    '{0}/traffic_ctl plugin msg cert_update.server {1}/server2.pem'.format(ts.Variables.BINDIR, ts.Variables.SSLDir)
)
ts.Disk.traffic_out.Content = "gold/update.gold"
ts.StillRunningAfter = server

# Server-Cert-After
# after use traffic_ctl to update server cert, curl should see bar.com cert from bob
tr = Test.AddTestRun("Server-Cert-After")
tr.Processes.Default.Env = ts.Env
tr.Command = 'curl --verbose --insecure --ipv4 --resolve bar.com:{0}:127.0.0.1 https://bar.com:{0}'.format(ts.Variables.ssl_port)
tr.Processes.Default.Streams.stderr = "gold/server-cert-after.gold"
tr.Processes.Default.ReturnCode = 0
ts.StillRunningAfter = server

# Client-Cert-Pre
# s_server should see client (Traffic Server) as alice.com
tr = Test.AddTestRun("Client-Cert-Pre")
s_server = tr.Processes.Process(
    "s_server",
    "openssl s_server -www -key {0}/server1.pem -cert {0}/server1.pem -accept {1} -Verify 1 -msg".format(
        ts.Variables.SSLDir,
        ts.Variables.s_server_port))
s_server.Ready = When.PortReady(ts.Variables.s_server_port)
tr.Command = 'curl --verbose --insecure --ipv4 --header "Host: foo.com" https://localhost:{}'.format(ts.Variables.ssl_port)
tr.Processes.Default.StartBefore(s_server)
s_server.Streams.all = "gold/client-cert-pre.gold"
tr.Processes.Default.ReturnCode = 0
ts.StillRunningAfter = server

# Client-Cert-Update
tr = Test.AddTestRun("Client-Cert-Update")
tr.Processes.Default.Env = ts.Env
tr.Processes.Default.Command = (
    'mv {0}/client2.pem {0}/client1.pem && {1}/traffic_ctl plugin msg cert_update.client {0}/client1.pem'.format(
        ts.Variables.SSLDir, ts.Variables.BINDIR)
)
ts.Disk.traffic_out.Content = "gold/update.gold"
ts.StillRunningAfter = server

# Client-Cert-After
# after use traffic_ctl to update client cert, s_server should see client (Traffic Server) as bob.com
tr = Test.AddTestRun("Client-Cert-After")
s_server = tr.Processes.Process(
    "s_server",
    "openssl s_server -www -key {0}/server1.pem -cert {0}/server1.pem -accept {1} -Verify 1 -msg".format(
        ts.Variables.SSLDir,
        ts.Variables.s_server_port))
s_server.Ready = When.PortReady(ts.Variables.s_server_port)
tr.Processes.Default.Env = ts.Env
# Move client2.pem to replace client1.pem since cert path matters in client context mapping
tr.Command = 'curl --verbose --insecure --ipv4 --header "Host: foo.com" https://localhost:{0}'.format(ts.Variables.ssl_port)
tr.Processes.Default.StartBefore(s_server)
s_server.Streams.all = "gold/client-cert-after.gold"
tr.Processes.Default.ReturnCode = 0
ts.StillRunningAfter = server


text:
package edu.wpi.disco.plugin;

import edu.wpi.cetask.*;
import edu.wpi.disco.Agenda;

/**
 * Plugin to enquire about optional tasks which have live successors
 * (and therefore would be passed if the successors proposed first).
 */
public class AskShouldPassablePlugin extends AskShouldPlugin {

   @Override
   public boolean isApplicable (Plan plan) {
      Plan parent = plan.getParent();
      return super.isApplicable(plan) &&
            // defer to AskShouldPlugin for parent
            !(parent != null && super.isApplicablePlan(parent)) &&
            plan.hasLiveSuccessor();
   }

   public AskShouldPassablePlugin (Agenda agenda, int priority) {
      super(agenda, priority);
   }
}


text:
namespace html_viewer {
namespace {

scoped_ptr<WebLayerTreeViewImpl> CreateWebLayerTreeView(
    GlobalState* global_state) {
  return make_scoped_ptr(new WebLayerTreeViewImpl(
      global_state->compositor_thread(),
      global_state->gpu_memory_buffer_manager(),
      global_state->raster_thread_helper()->task_graph_runner()));
}

void InitializeWebLayerTreeView(WebLayerTreeViewImpl* web_layer_tree_view,
                                mojo::ApplicationImpl* app,
                                mus::Window* window,
                                blink::WebWidget* widget) {
  DCHECK(window);
  mus::mojom::GpuPtr gpu_service;
  app->ConnectToService("mojo:mus", &gpu_service);
  web_layer_tree_view->Initialize(std::move(gpu_service), window, widget);
}

void UpdateWebViewSizeFromViewSize(mus::Window* window,
                                   blink::WebWidget* web_widget,
                                   WebLayerTreeViewImpl* web_layer_tree_view) {
  const gfx::Size size_in_pixels(window->bounds().size());
  const gfx::Size size_in_dips = gfx::ConvertSizeToDIP(
      window->viewport_metrics().device_pixel_ratio, size_in_pixels);
  web_widget->resize(
      blink::WebSize(size_in_dips.width(), size_in_dips.height()));
  web_layer_tree_view->setViewportSize(size_in_pixels);
}

}  // namespace

// HTMLWidgetRootRemote -------------------------------------------------------

HTMLWidgetRootRemote::HTMLWidgetRootRemote(GlobalState* global_state)
    : web_view_(blink::WebView::create(this)) {
  global_state->blink_settings()->ApplySettingsToWebView(web_view_);
}

HTMLWidgetRootRemote::~HTMLWidgetRootRemote() {}

blink::WebStorageNamespace*
HTMLWidgetRootRemote::createSessionStorageNamespace() {
  return new WebStorageNamespaceImpl();
}

bool HTMLWidgetRootRemote::allowsBrokenNullLayerTreeView() const {
  return true;
}

blink::WebWidget* HTMLWidgetRootRemote::GetWidget() {
  return web_view_;
}

void HTMLWidgetRootRemote::OnWindowBoundsChanged(mus::Window* window) {}

// HTMLWidgetRootLocal --------------------------------------------------------

HTMLWidgetRootLocal::CreateParams::CreateParams(mojo::ApplicationImpl* app,
                                                GlobalState* global_state,
                                                mus::Window* window)
    : app(app), global_state(global_state), window(window) {}

HTMLWidgetRootLocal::CreateParams::~CreateParams() {}

HTMLWidgetRootLocal::HTMLWidgetRootLocal(CreateParams* create_params)
    : app_(create_params->app),
      global_state_(create_params->global_state),
      window_(create_params->window),
      web_view_(nullptr) {
  web_view_ = blink::WebView::create(this);
  ime_controller_.reset(new ImeController(window_, web_view_));
  // Creating the widget calls initializeLayerTreeView() to create the
  // |web_layer_tree_view_impl_|. As we haven't yet assigned the |web_view_|
  // we have to set it here.
  if (web_layer_tree_view_impl_) {
    InitializeWebLayerTreeView(web_layer_tree_view_impl_.get(), app_, window_,
                               web_view_);
    UpdateWebViewSizeFromViewSize(window_, web_view_,
                                  web_layer_tree_view_impl_.get());
  }
  global_state_->blink_settings()->ApplySettingsToWebView(web_view_);
}

HTMLWidgetRootLocal::~HTMLWidgetRootLocal() {}

blink::WebStorageNamespace*
HTMLWidgetRootLocal::createSessionStorageNamespace() {
  return new WebStorageNamespaceImpl();
}

void HTMLWidgetRootLocal::initializeLayerTreeView() {
  web_layer_tree_view_impl_ = CreateWebLayerTreeView(global_state_);
}

blink::WebLayerTreeView* HTMLWidgetRootLocal::layerTreeView() {
  return web_layer_tree_view_impl_.get();
}

void HTMLWidgetRootLocal::didMeaningfulLayout(
    blink::WebMeaningfulLayout layout_type) {
  static bool called = false;
  if (!called && layout_type == blink::WebMeaningfulLayout::VisuallyNonEmpty) {
    const int64_t ticks = base::TimeTicks::Now().ToInternalValue();
    tracing::StartupPerformanceDataCollectorPtr collector =
        StatsCollectionController::ConnectToDataCollector(app_);
    if (collector)
      collector->SetFirstVisuallyNonEmptyLayoutTicks(ticks);
    called = true;
  }
}

void HTMLWidgetRootLocal::resetInputMethod() {
  ime_controller_->ResetInputMethod();
}

void HTMLWidgetRootLocal::didHandleGestureEvent(
    const blink::WebGestureEvent& event,
    bool event_cancelled) {
  ime_controller_->DidHandleGestureEvent(event, event_cancelled);
}

void HTMLWidgetRootLocal::didUpdateTextOfFocusedElementByNonUserInput() {
  ime_controller_->DidUpdateTextOfFocusedElementByNonUserInput();
}

void HTMLWidgetRootLocal::showImeIfNeeded() {
  ime_controller_->ShowImeIfNeeded();
}

blink::WebWidget* HTMLWidgetRootLocal::GetWidget() {
  return web_view_;
}

void HTMLWidgetRootLocal::OnWindowBoundsChanged(mus::Window* window) {
  UpdateWebViewSizeFromViewSize(window, web_view_,
                                web_layer_tree_view_impl_.get());
}

// HTMLWidgetLocalRoot --------------------------------------------------------

HTMLWidgetLocalRoot::HTMLWidgetLocalRoot(mojo::ApplicationImpl* app,
                                         GlobalState* global_state,
                                         mus::Window* window,
                                         blink::WebLocalFrame* web_local_frame)
    : app_(app), global_state_(global_state), web_frame_widget_(nullptr) {
  web_frame_widget_ = blink::WebFrameWidget::create(this, web_local_frame);
  ime_controller_.reset(new ImeController(window, web_frame_widget_));
  // Creating the widget calls initializeLayerTreeView() to create the
  // |web_layer_tree_view_impl_|. As we haven't yet assigned the
  // |web_frame_widget_|
  // we have to set it here.
  if (web_layer_tree_view_impl_) {
    InitializeWebLayerTreeView(web_layer_tree_view_impl_.get(), app_, window,
                               web_frame_widget_);
    UpdateWebViewSizeFromViewSize(window, web_frame_widget_,
                                  web_layer_tree_view_impl_.get());
  }
}

HTMLWidgetLocalRoot::~HTMLWidgetLocalRoot() {}

blink::WebWidget* HTMLWidgetLocalRoot::GetWidget() {
  return web_frame_widget_;
}

void HTMLWidgetLocalRoot::OnWindowBoundsChanged(mus::Window* window) {
  UpdateWebViewSizeFromViewSize(window, web_frame_widget_,
                                web_layer_tree_view_impl_.get());
}

void HTMLWidgetLocalRoot::initializeLayerTreeView() {
  web_layer_tree_view_impl_ = CreateWebLayerTreeView(global_state_);
}

blink::WebLayerTreeView* HTMLWidgetLocalRoot::layerTreeView() {
  return web_layer_tree_view_impl_.get();
}

void HTMLWidgetLocalRoot::resetInputMethod() {
  ime_controller_->ResetInputMethod();
}

void HTMLWidgetLocalRoot::didHandleGestureEvent(
    const blink::WebGestureEvent& event,
    bool event_cancelled) {
  ime_controller_->DidHandleGestureEvent(event, event_cancelled);
}

void HTMLWidgetLocalRoot::didUpdateTextOfFocusedElementByNonUserInput() {
  ime_controller_->DidUpdateTextOfFocusedElementByNonUserInput();
}

void HTMLWidgetLocalRoot::showImeIfNeeded() {
  ime_controller_->ShowImeIfNeeded();
}

}  // namespace html_viewer


text:
/**
 *
 */
package com.browseengine.bobo.api;

/**
 * @author "Xiaoyang Gu<xgu@linkedin.com>"
 *
 */
public abstract class DoubleFacetIterator extends FacetIterator {
  public double facet;

  public abstract double nextDouble();

  public abstract double nextDouble(int minHits);

  public abstract String format(double val);
}


text:
let assert = require('chai').assert;
let handlebars = require('handlebars');

suite('ConfigReader', ()=> {

    test('Process Templates', () => {
        let config = "{{#if A}}{{B}}{{/if}}"
        let params = { A: "true", B: "XYZ" };

        let template = handlebars.compile(config);
        let result = template(params);

		assert.equal(result, "XYZ");
    });

});


text:
namespace Beginners.PartialMatching
{
	public interface ITrainYard
	{
		void StoreCar(TrainCar trainCar);
		void RetrieveLuggage(LuggageTicket ticket);
	}
}


text:
This package implements the methods discussed in [1].
## Running the Particle Filter

1. Clone the repo.
2. Open MATLAB script particle_filter/particle_filter.m.
3. Modify lines 10-11 to set record_name as the path to your file.
4. Run the script.  Currently, it'll print out the sensitivity and positive predictivity for the PF, GQRS, and WABP.

## Misc. Notes

* The scripts that were used to prepare the MIT-BIH and MGH/MF databases and to generate statistics can be found in the scripts/ directory.
* The repo comes with setp1 and setp2 available at the Physionet 2014 challenge website.
* We assume that the signals come in a form compatible with the WFDB toolbox (we've included the toolbox in this repo).
* We utilized some of the SQI functions from Alistair Johnson's entry.  The original source can be found here.  Their paper detailing their work can be found here.
* We'll be updating the functions/scripts over time to improve documentation.
* We've provided the utility script that we used to generate our graphs.

## Reference
[1] Hugh Chen, Yusuf B. Erol, Eric Shen, Stuart Russell, "Probabilistic Model-Based Approach for Heart Beat Detection", _Physiological Measurement_, Vol. 37, No. 9, August 2016, link.

## Questions/Contact

If you have any questions, feel free to send an email to hugh.chen1{at}gmail.com and ericshen{at}berkeley.edu.


text:
FactoryGirl.define do
  factory :bill do
    meal
    resident
    amount 4000
  end
end


text:
package org.fest.util;

import static java.util.Arrays.asList;
import static junit.framework.Assert.assertEquals;
import static org.fest.util.Collections.nonNullElements;
import static org.junit.Assert.*;

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

import org.junit.Test;

/**
 * Tests for <code>{@link Collections#nonNullElements(List)}</code>.
 *
 * @author Joel Costigliola
 * @author Alex Ruiz
 */
public class Collections_nonNullElements_List_Test {

  @Test public void should_return_null_if_given_list_is_null() {
    List<?> l = null;
    assertNull(nonNullElements(l));
  }

  @Test public void should_return_an_empty_list_if_given_list_has_only_null_elements() {
    List<String> l = new ArrayList<String>();
    l.add(null);
    assertTrue(nonNullElements(l).isEmpty());
  }

  @Test public void should_return_an_empty_list_if_given_list_is_empty() {
    List<String> l = new ArrayList<String>();
    assertEquals(0, nonNullElements(l).size());
  }

  @Test public void should_return_a_list_without_null_elements() {
    List<String> c = asList("Frodo", null, "Sam", null);
    List<String> expected = asList("Frodo", "Sam");
    List<String> nonNullElements = nonNullElements(c);
    assertEquals(expected, nonNullElements);
  }
}


text:
package ch.ethz.inf.vs.californium.coapbench;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * Log file. Works like System.out.println() but stores all Strings into a file.
 */
public class LogFile {

	private BufferedWriter out;

	public LogFile(String name) throws Exception {
		File file = createLogFile(name);
		out = new BufferedWriter(new FileWriter(file));
		System.out.println("Created log file "+file.getAbsolutePath());

	}

	public void println(String line) {
		try {
			while (line.startsWith("\n")) {
				System.out.println();
				out.write("\r\n");
				line = line.substring(1);
			}
			System.out.println("< "+line);
			out.write(line+"\r\n");
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void format(String str, Object... args){
		try {
			String line = String.format(str, args);
			System.out.print("< "+line);
			out.write(line.replace("\n", "\r\n"));
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void errln(String line) {
		try {
			System.err.println("< "+line);
			out.write(line+"\r\n");
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private File createLogFile(String name) throws Exception {
//		String date = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss").format(new Date());
//		name = name + "_" + date;
		File file = new File(name);
		if (!file.exists()) {
			file.createNewFile();
			return file;
		} else {
			int c = 0;
			do {
				file = new File(name+"("+(++c)+")");
			} while (file.exists());
			file.createNewFile();
			return file;
		}
	}
}


text:
using System;
using System.Linq;

namespace Microsoft.Azure.Management.Dns.Models
{
    /// <summary>
    /// The status of the asynchronous request.
    /// </summary>
    public static partial class DnsOperationStatus
    {
        public const string InProgress = "InProgress";

        public const string Succeeded = "Succeeded";

        public const string Failed = "Failed";
    }
}