text:
package com.coolweather.app.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.Toolbar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.text.Layout;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.coolweather.app.R;
import com.coolweather.app.service.AutoUpdateService;
import com.coolweather.app.util.HttpCallbackListener;
import com.coolweather.app.util.HttpUtil;
import com.coolweather.app.util.Utility;

import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;

/**
 * Created by lpfox on 2016.12.07.
 */
public class WeatherActivity extends Activity implements View.OnClickListener,NavigationView.OnNavigationItemSelectedListener{

    private LinearLayout weatherInfoLayout;
    /**
     * 用于显示城市名
     */
    private TextView cityNameText;
    /**
     * 用于显示发布时间
     */
    private TextView[] publishText = new TextView[7];
    /**
     * 用于显示天气描述信息
     */
    private ImageView[] weatherDespText = new ImageView[6];
    private TextView weatherDesp;
    /**
     * 用于显示气温1
     */
    private TextView[] temp1Text = new TextView[7];
    /**
     * 用于显示气温2
     */
    private TextView[] temp2Text = new TextView[7];
    /**
     * 用于显示当前日期
     */
    private TextView currentDateText;
    /**
     * 菜单按钮
     */
    private Toolbar menuButton;
    /**
     * 菜单布局
     */
    private DrawerLayout itemLayout;
    //左拉控件
    private NavigationView navigationView;
    /**
     * 切换城市
     */
    //private Button switchCity;
    /**
     * 更新天气按钮
     */
    private Button refreshWeather;

    private static final String TAG = "WeatherActivity";
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            /*case R.id.switch_city:
                Intent intent = new Intent(this, ChooseAreaActivity.class);
                intent.putExtra("from_weather_activity",true);
                startActivity(intent);
                finish();
                break;*/
            case R.id.refresh_weather:
                publishText[6].setText("同步中...");
                SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
                String weatherCode = prefs.getString("city_name","");
                if (!TextUtils.isEmpty(weatherCode)){
                    queryWeatherInfo(weatherCode,"city");
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.item_layout);

        //初始化个控件
        weatherInfoLayout = (LinearLayout)findViewById(R.id.weather_info_layout);
        cityNameText = (TextView)findViewById(R.id.city_name);
        publishText[3] = (TextView)findViewById(R.id.tommorowC1);
        publishText[4] = (TextView)findViewById(R.id.tommorowD1);
        publishText[5] = (TextView)findViewById(R.id.tommorowE1);
        publishText[6] = (TextView)findViewById(R.id.publish_text);

        weatherDesp = (TextView)findViewById(R.id.weather_desp);
        weatherDespText[0] = (ImageView)findViewById(R.id.yesterday2);
        weatherDespText[1] = (ImageView)findViewById(R.id.today2);
        weatherDespText[2] = (ImageView)findViewById(R.id.tommorowB2);
        weatherDespText[3] = (ImageView)findViewById(R.id.tommorowC2);
        weatherDespText[4] = (ImageView)findViewById(R.id.tommorowD2);
        weatherDespText[5] = (ImageView)findViewById(R.id.tommorowE2);

        temp1Text[0] = (TextView)findViewById(R.id.yesterday3);
        temp1Text[1] = (TextView)findViewById(R.id.today3);
        temp1Text[2] = (TextView)findViewById(R.id.tommorowB3);
        temp1Text[3] = (TextView)findViewById(R.id.tommorowC3);
        temp1Text[4] = (TextView)findViewById(R.id.tommorowD3);
        temp1Text[5] = (TextView)findViewById(R.id.tommorowE3);
        temp1Text[6] = (TextView)findViewById(R.id.temp1);

        temp2Text[0] = (TextView)findViewById(R.id.yesterday4);
        temp2Text[1] = (TextView)findViewById(R.id.today4);
        temp2Text[2] = (TextView)findViewById(R.id.tommorowB4);
        temp2Text[3] = (TextView)findViewById(R.id.tommorowC4);
        temp2Text[4] = (TextView)findViewById(R.id.tommorowD4);
        temp2Text[5] = (TextView)findViewById(R.id.tommorowE4);
        temp2Text[6] = (TextView)findViewById(R.id.temp2);

        currentDateText = (TextView)findViewById(R.id.current_date);
        //左拉菜单
        itemLayout = (DrawerLayout)findViewById(R.id.item_layout);
        navigationView = (NavigationView)findViewById(R.id.nav_view);
        menuButton = (Toolbar)findViewById(R.id.menu_button);

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this,itemLayout, menuButton, R.string.navigation_drawer_open,R.string.navigation_drawer_close);
        itemLayout.setDrawerListener(toggle);
        toggle.syncState();
        navigationView.setNavigationItemSelectedListener(this);

        String countyCode = getIntent().getStringExtra("county_code");
        if(!TextUtils.isEmpty(countyCode)){
            //有县级代号时查询天气
            publishText[6].setText("同步中...");
            //weatherInfoLayout.setVisibility(View.INVISIBLE);
            //cityNameText.setVisibility(View.INVISIBLE);
            queryWeatherCode(countyCode);
        }else{
            //没有县级代号显示本地天气
            showWeather();
        }
        //switchCity.setOnClickListener(this);
        //refreshWeather.setOnClickListener(this);
        refreshWeather = (Button)findViewById(R.id.refresh_weather);
        refreshWeather.setOnClickListener(this);
    }

    /**
     * 查询县级代号所对应的天气代号
     * @param countyCode
     */
    private void queryWeatherCode(String countyCode){
        String address = "http://www.weather.com.cn/data/list3/city"+countyCode+".xml";
        queryFromServer(address, "countyCode");
    }

    /**
     * 查询县级代号对应的天气
     * @param
     */
    private void queryWeatherInfo(String weatherCode,String type){
        if ("city".equals(type)){
            try {
                weatherCode = URLEncoder.encode(weatherCode,"UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        String address = "http://wthrcdn.etouch.cn/weather_mini?"+type+"="+weatherCode;
        Log.d(TAG,"address");
        queryFromServer(address, "weatherCode");
    }

    /**
     * 根据传入的地址和类型,从服务器查询天气代号或天气
     * @param address
     * @param type
     */
    private void queryFromServer(final String address, final String type){
        HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {
                if ("countyCode".equals(type)){
                    if (!TextUtils.isEmpty(response)){
                        //从服务器返回的数据中解析出天气代号
                        String[] array = response.split("\\|");
                        if (array != null && array.length == 2){
                            String weatherCode = array[1];
                            Log.d(TAG,weatherCode.toString());
                            queryWeatherInfo(weatherCode,"citykey");
                        }
                    }
                }else if ("weatherCode".equals(type)){
                    //处理服务器返回的天气信息
                    Utility.handleWeatherResponse(WeatherActivity.this, response);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showWeather();
                        }
                    });
                }
            }

            @Override
            public void onError(Exception e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        publishText[6].setText("同步失败");
                    }
                });
            }
        });
    }

    /**
     * 从SharedPreferences文件中读取存储的天气信息,并显示在界面上
     */
    private void showWeather(){
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        cityNameText.setText(prefs.getString("city_name",""));
        /*temp1Text.setText(prefs.getString("temp1",""));
        temp2Text.setText(prefs.getString("temp2",""));
        weatherDespText.setText(prefs.getString("weather_desp",""));
        publishText.setText("今天"+prefs.getString("publish_time","")+"发布");
        currentDateText.setText(prefs.getString("current_date",""));
        weatherInfoLayout.setVisibility(View.INVISIBLE);
        cityNameText.setVisibility(View.VISIBLE);*/
        for (int i = 0; i < 6; i++){
            //日期
            if (i > 2){
                String t = prefs.getString("publish_time["+i+"]","");
                String[] tstrings=t.split("期");
                t=tstrings[1];
                publishText[i].setText("周"+t);
            }
        /*天气*/
            String w=prefs.getString("weather_desp["+i+"]","");
            switch (w){
                case "晴":weatherDespText[i].setImageResource(R.mipmap.qing);break;
                case "阴":weatherDespText[i].setImageResource(R.mipmap.yin);break;
                case "多云":
                    weatherDespText[i].setImageResource(R.mipmap.duoyun);
                    break;
                case "小雨":
                    weatherDespText[i].setImageResource(R.mipmap.xiaoyu);
                    break;
                case "中雨":
                    weatherDespText[i].setImageResource(R.mipmap.yu);
                    break;
                case "大雨":
                    weatherDespText[i].setImageResource(R.mipmap.yu);
                    break;
                case "阵雨":
                    weatherDespText[i].setImageResource(R.mipmap.xiaoyu);
                    break;
                case "雷阵雨":
                    weatherDespText[i].setImageResource(R.mipmap.leizhenyu);
                    break;
                case "小雪":
                    weatherDespText[i].setImageResource(R.mipmap.xiaoxue);
                    break;
                case "中雪":
                    weatherDespText[i].setImageResource(R.mipmap.xiaoxue);
                    break;
                case "大雪":
                    weatherDespText[i].setImageResource(R.mipmap.daxue);
                    break;
                default:
                    weatherDespText[i].setImageResource(R.mipmap.qita);
                    break;
            }
            /*温度*/
            String s=prefs.getString("temp1["+i+"]","");
            String[] strings=s.split(" ");
            s=strings[1];
            s=s.replace('℃','°');
            Log.d("WeatherActivity","temp1Text["+i+"]:"+s);
            temp1Text[i].setText(s);
            s=prefs.getString("temp2["+i+"]","");
            strings=s.split(" ");
            s=strings[1];
            s=s.replace('℃','°');
            Log.d("WeatherActivity","temp2Text["+i+"]:"+s);
            temp2Text[i].setText(s);
            Log.d("WeatherActivity",i+"");
        }
        temp1Text[6].setText(prefs.getString("temp1[1]",""));
        temp2Text[6].setText(prefs.getString("temp2[1]",""));
        weatherDesp.setText(prefs.getString("weather_desp[1]",""));
        publishText[6].setText(prefs.getString("publish_time[1]","")+"发布");
        currentDateText.setText(prefs.getString("current_date",""));
        //weatherInfoLayout.setVisibility(View.VISIBLE);
        //cityNameText.setVisibility(View.VISIBLE);
        Intent intent=new Intent(this, AutoUpdateService.class);
        startService(intent);

    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        switch(id){
            case R.id.select_city:
                Intent intent=new Intent(this,ChooseAreaActivity.class);
                intent.putExtra("from_weather_activity",true);
                startActivity(intent);
                finish();
                break;
            case R.id.share:
                Toast.makeText(WeatherActivity.this, "正在开发中...", Toast.LENGTH_SHORT).show();
                break;
        }
        return false;
    }
}


text:
SORM [![GitHub version](https://badge.fury.io/gh/Jayin%2FSORM.svg)](http://badge.fury.io/gh/Jayin%2FSORM) ![build](https://travis-ci.org/Jayin/SORM.svg?branch=master)   ![license](http://img.shields.io/badge/license-MIT-brightgreen.svg)
====

Simple and stupid ORM for Android

setup
===
add this project as you Android project library

## Usage

### Create a table

the model
```java

@Table
public class User extends Model {

	@Column
	@Index //index support
	private long userid;

	@Column
	private int age;

	@Column
	private String name;

	public long getUserid() {
		return userid;
	}

	public void setUserid(long userid) {
		this.userid = userid;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}

```

### update & automantily insert if not exist
```java

	Admin a1 = new Admin();
	a1.setAdminName("a111");
	a1.setId(1);
	a1.save(getContext());
	//or you can save in async way
	a1.saveAsync(getContext(),  new ORMcallback() {

				@Override
				public void onFinish() {

				}

				@Override
				public void onFaild() {

				}
			});
```

### query
```java

	List<Admin> admins = new Query(new Selector().from(Admin.class))
				.excute(getContext());
	// or query  in async way
	Selector selector = new Selector().from(Admin.class);
	new Query(selector).excuteAsync(getContext(), new QueryCallback() {

			@Override
			public void onFinish(Object result) {
				List<Admin> res = (List<Admin>) result;
			}
		});

```

### delete

```java

	List<Admin> admins = new Query(new Selector().from(Admin.class))
				.excute(getContext());
	for(Admin a: admins){
		a.delete(getContext());
		//or you can save in async way
		a.deleteAsync(getContext(),  new ORMcallback() {

				@Override
				public void onFinish() {

				}

				@Override
				public void onFaild() {

				}
			});
	}

```

### Five Operation
* build entity
```java

	new Creater().from(User.class).build()
```

* insert
```java

    User u = new User();
    u.setAge(11);
    u.setName("aaa");
    String sql = new Inserter().insert(u ).build();
```

* delete
```java

	String sql = new Deletor()
				.from(User.class)
				.where("id", "=", "1")
				.and().where("age", ">", "18")
				.build();

```

* select
```java

	String sql = new Selector("id","title","content") //the result columns. select all(*) when nothing here
					.from(Database.class)  //table
					.distinct() // all() or distinct()
					.where("showFlag","=", 1 + "")   //`where` expression
					.and().where("version", "!=", "0")
					.groupBy("id","title")  //more than one
					.orderBy("id") //ablt to more than one
					.limit(10)
					.offset(10)
					.build();

```

* update
```java

	User u = new User();
	u.setAge(11);
	u.setName("bbb");
	u.setSaveTime(12354546);
	u.setId(1);
	String sql = new Updater()
					.update(u)
					.where("id", "=", "1")
					.build();
```

### advance

* drop table & index

```java

//drop table
String sql = new Droper().Table().from(Animal.class).build();
//drop index
String sql = new Droper().Index().from(Animal.class).build();
//invoke  sql
DBUtils.execSQL(context,sql);

//why not do this:
new Droper().Index().from(cls).excute(getContext());
new Droper().Table().from(cls).excute(getContext());
```

redpajama_set_name: RedPajamaGithub


text:
namespace _04.Recharge.AdapterPattern
{
    using System;

    public class Employee : Worker, ISleeper
    {
        public Employee(string id) : base (id)
        {
        }

        public override void Sleep()
        {
            // sleep...
        }

        public override void Recharge()
        {
            throw new InvalidOperationException("Employees cannot recharge");
        }
    }
}


text:
package gov.sandia.cognition.text.term.vector.weighter.local;

import gov.sandia.cognition.math.matrix.SparseVectorFactory;
import gov.sandia.cognition.math.matrix.Vector;
import gov.sandia.cognition.math.matrix.VectorFactory;
import gov.sandia.cognition.math.matrix.DefaultVectorFactoryContainer;
import gov.sandia.cognition.math.matrix.Vectorizable;

/**
 * Abstract implementation of the {@code LocalTermWeighter} interface. Defaults
 * to a sparse vector factory.
 *
 * @author  Justin Basilico
 * @since   3.0
 */
public abstract class AbstractLocalTermWeighter
    extends DefaultVectorFactoryContainer
    implements LocalTermWeighter
{

    /**
     * Creates a new {@code AbstractLocalTermWeighter}.
     */
    public AbstractLocalTermWeighter()
    {
        this(SparseVectorFactory.getDefault());
    }

    /**
     * Creates a new {@code AbstractLocalTermWeighter}.
     *
     * @param   vectorFactory
     *      The vector factory to use.
     */
    public AbstractLocalTermWeighter(
        final VectorFactory<? extends Vector> vectorFactory)
    {
        super(vectorFactory);
    }

    public Vector computeLocalWeights(
        final Vectorizable document)
    {
        return this.computeLocalWeights(document.convertToVector());
    }

}


text:
#include <aws/connectcampaigns/model/InternalServerException.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace ConnectCampaigns
{
namespace Model
{

InternalServerException::InternalServerException() :
    m_messageHasBeenSet(false),
    m_xAmzErrorTypeHasBeenSet(false)
{
}

InternalServerException::InternalServerException(JsonView jsonValue) :
    m_messageHasBeenSet(false),
    m_xAmzErrorTypeHasBeenSet(false)
{
  *this = jsonValue;
}

InternalServerException& InternalServerException::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("message"))
  {
    m_message = jsonValue.GetString("message");

    m_messageHasBeenSet = true;
  }

  return *this;
}

JsonValue InternalServerException::Jsonize() const
{
  JsonValue payload;

  if(m_messageHasBeenSet)
  {
   payload.WithString("message", m_message);

  }

  return payload;
}

} // namespace Model
} // namespace ConnectCampaigns
} // namespace Aws


text:
require 'nokogiri'
require 'the_community_farm/organic_boxes/box'

module TheCommunityFarm
  # Represents a list of organic veg boxes.
  class OrganicBoxes
    include Enumerable

    def initialize(html:)
      @boxes = Nokogiri::HTML(html).css('.panel').map { |p| Box.new(noko: p) }
    end

    def each(&block)
      boxes.each(&block)
    end

    private

    attr_reader :boxes
  end
end


text:
package com.glowingavenger.dialog

import com.glowingavenger.plan.ActionEdge

import scala.swing._
import Dialog.Options._
import Dialog.Result._
import com.glowingavenger.agent.PlanExecutor
import com.glowingavenger.plan.importexport.PDDL
import com.glowingavenger.plan.model.action.{Question, Action}
import com.glowingavenger.plan.model.state.BeliefState

class SimpleSwingDialogAgent extends AbstractDialogAgent with ChooseFirstQuestion with ChooseFirstAction {
  override def onFinish(state: BeliefState, producer: Option[ActionEdge]) {
    Dialog.showMessage(message = "Hooray!")
  }

  override def onFailure(state: BeliefState, producer: Option[ActionEdge]) {
    Dialog.showMessage(message = "Ooops... Something went wrong!")
  }

  protected override def handleAction(action: Action): Boolean = {
    Dialog.showConfirmation(message = s"Please do the following: ${action.name}",
      optionType = OkCancel) match {
      case Ok => true
      case _ => false
    }
  }

  protected override def handleQuestion(question: Question): Option[Boolean] = {
    Dialog.showConfirmation(message = s"Is it true? ${question.name}\nPress [Cancel] if you don't know",
    optionType = YesNoCancel) match {
      case Yes => Some(true)
      case No => Some(false)
      case _ => None
    }
  }
}

object SwingExample {
  def main(args: Array[String]) {
    new PlanExecutor(PDDL.importProblem("src/main/resources/Bulb.pddl"), new SimpleSwingDialogAgent).exec()
  }
}


text:
package serial;

/**
 * Created by chzhong on 1/20/16.
 */
public class SerialException extends RuntimeException {
    /**
     * Constructs a new {@code SerialException} with the current stack trace
     * and the specified detail message.
     *
     * @param detailMessage the detail message for this exception.
     */
    public SerialException(String detailMessage) {
        super(detailMessage);
    }

    /**
     * Constructs a new {@code PortNotOpenedException} with the current stack trace,
     * the specified detail message and the specified cause.
     *
     * @param detailMessage the detail message for this exception.
     * @param throwable
     */
    public SerialException(String detailMessage, Throwable throwable) {
        super(detailMessage, throwable);
    }
}


text:
namespace NQtScreen {

int GetProcessID(const std::wstring& exeFileName);
bool InjectDll(int pid, const std::string& dll);

} // NQtScreen


text:
Designed to work with webtranslateit.com API.

## Initialization
```
var I18n = require('i18n');
var germanTranslator = new I18n({
  "Hello": "Hallo {{name}}, wie geht es dir heute?",
  "cats": {
    "one": "{{count}} Katze",
    "other": "{{count}} Katzen"
  },
  "dog": {
    "puppy": "Hündchen"
  } // 1 Katze
});
```

## Basic Translation
```
var HelloPerson = germanTranslator.__('Hello', {name: "Marcus"});
console.log(HelloPerson); // Hallo Marcus, wie geht es dir heute?
```

## default Fallback

Third parameter is the default fallback.
This is a good practice as it makes sure that at least one version of text will appear.
```
var HelloPerson = germanTranslator.__(
  'Not a key?',
  {name: "Marcus"},
  "Hallo {{name}}, wie geht es dir heute?");
console.log(HelloPerson); // Hallo Marcus, wie geht es dir heute?
```

## Keys are evaluated
```
var puppy = germanTranslator.__('dog.puppy');
console.log(puppy); // Hündchen
```

## Plurals

Plurals will be automatically evaluated if the object has keys `one` and `other`.

Then it determines the plural based on the count variable passed to it.

Example data:

```
"cats": {
  "one": "{{count}} Katze",
  "other": "{{count}} Katzen"
}
```

and the usage:

```
var one = germanTranslator.__('cats', {count: 1});
var other = germanTranslator.__('cats', {count: 2});
console.log(one); // 1 Katze
console.log(other); // 2 Katzen
```

#### I apologize for the versioning. The 1.* releases are still work in progress releases but too late now!


text:
<?php
namespace Google\Service\Books\Myconfig;

/**
 * The "myconfig" collection of methods.
 * Typical usage is:
 *  <code>
 *   $booksService = new Google_Service_Books(...);
 *   $myconfig = $booksService->myconfig;
 *  </code>
 */
class Resource extends \Google\Service\Resource
{

  /**
   * Release downloaded content access restriction.
   * (myconfig.releaseDownloadAccess)
   *
   * @param string $volumeIds
   * The volume(s) to release restrictions for.
   * @param string $cpksver
   * The device/version ID from which to release the restriction.
   * @param array $optParams Optional parameters.
   *
   * @opt_param string locale
   * ISO-639-1, ISO-3166-1 codes for message localization, i.e. en_US.
   * @opt_param string source
   * String to identify the originator of this request.
   * @return \Google\Service\Books\DownloadAccesses
   */
  public function releaseDownloadAccess($volumeIds, $cpksver, $optParams = array())
  {
    $params = array('volumeIds' => $volumeIds, 'cpksver' => $cpksver);
    $params = array_merge($params, $optParams);
    return $this->call('releaseDownloadAccess', array($params), "\Google\Service\Books\DownloadAccesses");
  }
  /**
   * Request concurrent and download access restrictions. (myconfig.requestAccess)
   *
   * @param string $source
   * String to identify the originator of this request.
   * @param string $volumeId
   * The volume to request concurrent/download restrictions for.
   * @param string $nonce
   * The client nonce value.
   * @param string $cpksver
   * The device/version ID from which to request the restrictions.
   * @param array $optParams Optional parameters.
   *
   * @opt_param string licenseTypes
   * The type of access license to request. If not specified, the default is BOTH.
   * @opt_param string locale
   * ISO-639-1, ISO-3166-1 codes for message localization, i.e. en_US.
   * @return \Google\Service\Books\RequestAccess
   */
  public function requestAccess($source, $volumeId, $nonce, $cpksver, $optParams = array())
  {
    $params = array('source' => $source, 'volumeId' => $volumeId, 'nonce' => $nonce, 'cpksver' => $cpksver);
    $params = array_merge($params, $optParams);
    return $this->call('requestAccess', array($params), "\Google\Service\Books\RequestAccess");
  }
  /**
   * Request downloaded content access for specified volumes on the My eBooks
   * shelf. (myconfig.syncVolumeLicenses)
   *
   * @param string $source
   * String to identify the originator of this request.
   * @param string $nonce
   * The client nonce value.
   * @param string $cpksver
   * The device/version ID from which to release the restriction.
   * @param array $optParams Optional parameters.
   *
   * @opt_param string features
   * List of features supported by the client, i.e., 'RENTALS'
   * @opt_param string locale
   * ISO-639-1, ISO-3166-1 codes for message localization, i.e. en_US.
   * @opt_param bool showPreorders
   * Set to true to show pre-ordered books. Defaults to false.
   * @opt_param string volumeIds
   * The volume(s) to request download restrictions for.
   * @return \Google\Service\Books\Volumes
   */
  public function syncVolumeLicenses($source, $nonce, $cpksver, $optParams = array())
  {
    $params = array('source' => $source, 'nonce' => $nonce, 'cpksver' => $cpksver);
    $params = array_merge($params, $optParams);
    return $this->call('syncVolumeLicenses', array($params), "\Google\Service\Books\Volumes");
  }
}


text:
<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle 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 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

$string['all'] = 'All';
$string['apikey'] = 'API key';
$string['backtosearch'] = 'Back to search screen';
$string['by'] = 'Attribution license';
$string['by-nc'] = 'Attribution-NonCommercial license';
$string['by-nc-nd'] = 'Attribution-NonCommercial-NoDerivs license';
$string['by-nc-sa'] = 'Attribution-NonCommercial-ShareAlike license';
$string['by-nd'] = 'Attribution-NoDerivs license';
$string['by-sa'] = 'Attribution-ShareAlike license';
$string['callbackurl'] = 'Callback URL';
$string['commercialuse'] = 'I want to use the images commercially';
$string['configplugin'] = 'Flickr public configuration';
$string['creativecommonscommercial'] = 'Only creative commons commercial';
$string['emailaddress'] = 'Email address';
$string['flickr_public:view'] = 'Use Flickr public repository in file picker';
$string['fulltext'] = 'Full text';
$string['information'] = '
Get a Flickr API Key for your Moodle site.
';
$string['invalidemail'] = 'Invalid email account for flickr';
$string['license'] = 'License';
$string['modification'] = 'I want to be able to modify the images';
$string['notitle'] = 'notitle';
$string['nullphotolist'] = 'There are no photos in this account';
$string['remember'] = 'Remember me';
$string['pluginname_help'] = 'Repository on flickr.com';
$string['pluginname'] = 'Flickr public';
$string['secret'] = 'Secret';
$string['sharealike'] = 'Yes, as long as others share alike';
$string['tag'] = 'Tag';
$string['username'] = 'Flickr account email';
$string['watermark'] = 'Add watermark to photos';


text:
Workshop-Lab for OAuth2 single-sign-on client.

The SSO client is configured to run on
[localhost:9096/ssoclient](http://localhost:9096/ssoclient)

__Note: Before using this OAuth2 SSO client make sure that you have started the authorization server__

If you locate your web browser to address above you should get redirected to the
OAuth2 authorization server.

Here you can use following user accounts for login:

- Username: __user__, password: __secret__, roles: __USER__
- Username: __admin__, password: __admin__, roles: __ADMIN__

If all OAuth2 processing has been successful then you should be logged in and see something like this in the web browser:

``
Successfully authenticated user 'user', first name 'Mister', last name 'Mister'
``


text:
var _ = require('lodash');
var debug = require('debug')('feathers-passport:authorizer');

// See https://github.com/jfromaniello/passport.socketio/blob/master/lib/index.js
module.exports = function(settings) {
  var parser = settings.cookieParser(settings.secret);

  return function(req, next) {
    parser(req, {}, function(error) {
      debug('parser returned', error);

      if(error) {
        return next(error);
      }

      var cookie = !_.isEmpty(req.signedCookies) ? req.signedCookies : req.cookies;
      var sessionId = (req.query && req.query.session_id) ||
        (req._query && req._query.session_id) ||
        cookie[settings.name || settings.key] || '';

      debug('got session', sessionId);

      settings.store.get(sessionId, function(err, session) {
        debug('session store returned', err, session);

        if(err) {
          return next(new Error('Error in session store:\n' + err.message));
        }

        if(!session) {
          return next(new Error('No session found'));
        }

        if(!session[settings.passport._key]) {
          return next(new Error('Passport was not initialized'));
        }

        var userKey = session[settings.passport._key][settings.userProperty];

        if(typeof userKey === 'undefined') {
          return next(new Error('User not authorized through passport (user property not found)'));
        }

        settings.passport.deserializeUser(userKey, function(err, user) {
          if(err) {
            return next(err);
          }

          if(!user) {
            return next(new Error('User not found'));
          }

          req[settings.userProperty] = user;

          next(null, user);
        });
      });
    });
  };
};


text:
using Melanchall.DryWetMidi.Interaction;

namespace Melanchall.DryWetMidi.Composing
{
    internal sealed class StepForwardAction : StepAction
    {
        #region Constructor

        public StepForwardAction(ITimeSpan step)
            : base(step)
        {
        }

        #endregion

        #region Overrides

        public override PatternActionResult Invoke(long time, PatternContext context)
        {
            if (State != PatternActionState.Enabled)
                return PatternActionResult.DoNothing;

            context.SaveTime(time);
            return new PatternActionResult(time + LengthConverter.ConvertFrom(Step, time, context.TempoMap));
        }

        public override PatternAction Clone()
        {
            return new StepForwardAction(Step.Clone());
        }

        #endregion
    }
}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">

  <title>ngRepeatReorder 0.0.1 Demo</title>

  <meta name="robots" content="noindex">

  <link rel='stylesheet prefetch' href='../bower_components/bootstrap/dist/css/bootstrap.min.css'>
  <link rel='stylesheet prefetch' href='../bower_components/font-awesome/css/font-awesome.css'>

Type in the text box to add new names to the list, delete all text in a box to remove it. Click and drag the  to reorder the names

					Enter Names...

					<input class="form-control form-inline player" type='text'
						tabindex='{{$index + 1}}'
						ng-change='checkForNameDelete($index)'
						ng-model='name.val'
						ng-class="{'last-player': $index == names.length-1}"/>

					<input class="form-control form-inline" type='text'
						ng-model='tempplayer'
						tabindex='{{names.length + 1}}'
						placeholder='Enter a name...'/>
					<button ng-click="updateNames()">Add Name</button>

				{{names}},{{tempplayer}}

					Click and drag to re-order

						{{name.val}}


text:
package de.martinreinhardt.jee;

import org.junit.Test;

public class HelloWorldTest
{
   @Test
   public void testGetText() {
      HelloWorld fixture = new HelloWorld();
      assert "Hello World!".equals(fixture.getText());
   }
}


text:
import { parse, BaseElementNode } from '@vue/compiler-dom'
import extractLeadingComment from './extractLeadingComment'

function isBaseElementNode(a: any): a is BaseElementNode {
	return a.tag !== undefined
}

function compileIt(src: string): { parent: BaseElementNode; child: BaseElementNode } | undefined {
	const [ast] = parse(src).children
	if (isBaseElementNode(ast)) {
		const firstHeader = ast.children.filter(
			a => isBaseElementNode(a) && a.tag === 'h1'
		) as unknown as BaseElementNode[]
		if (firstHeader.length) {
			return { parent: ast, child: firstHeader[0] }
		}
	}
	return undefined
}

describe('extractLeadingComment', () => {
	it('should not fail when no comment', () => {
		const elt = compileIt(
			[
				'
', //
				'
title of the template
',
				'
'
			].join('\n')
		)
		if (!elt) {
			throw Error('fail')
		} else {
			expect(extractLeadingComment([], elt.child).length).toBe(0)
		}
	})

	it('should extract single line comments', () => {
		const elt = compileIt(
			[
				'
',
				'
Hello World !!
',
				'
Happy Day !!
',
				' ',
				'
title of the template
',
				'
'
			].join('\n')
		)
		if (!elt) {
			throw Error('fail')
		} else {
			expect(extractLeadingComment(elt.parent.children, elt.child)[0]).toBe('single line comment')
		}
	})

	it('should extract multi line comments', () => {
		const elt = compileIt(
			[
				'
',
				'
Hello World !!
',
				'  ',
				'  ',
				'
title of the template
',
				'
'
			].join('\n')
		)
		if (elt) {
			expect(extractLeadingComment(elt.parent.children, elt.child)).toEqual([
				'multi line comment',
				'on 2 lines'
			])
		} else {
			throw Error('fail')
		}
	})

	it('should extract multi line comment blocks', () => {
		const elt = compileIt(
			[
				'
',
				'
Hello World !!
',
				'  ',
				'  ',
				'
title of the template
',
				'
'
			].join('\n')
		)
		if (elt) {
			const comments = extractLeadingComment(elt.parent.children, elt.child)
			expect(comments[0]).toEqual(['multi line comment', '   on 2 lines'].join('\n'))
			expect(comments[1]).toEqual('single line comment')
		} else {
			throw Error('fail')
		}
	})

	it('should extract comment blocks when first sibling', () => {
		const elt = compileIt(
			[
				'
',
				'  ',
				'  ',
				'
title of the template
',
				'
'
			].join('\n')
		)
		if (elt) {
			const comments = extractLeadingComment(elt.parent.children, elt.child)
			expect(comments[0]).toEqual(['multi line comment', '   on 2 lines'].join('\n'))
			expect(comments[1]).toEqual('single line comment')
		} else {
			throw Error('fail')
		}
	})

	it('extract comment from js too', () => {
		const elt = compileIt(
			[
				'
', //
				'  {{ //single line comment }}',
				'
title of the template
',
				'
'
			].join('\n')
		)
		if (elt) {
			const comments = extractLeadingComment(elt.parent.children, elt.child)
			expect(comments[0]).toEqual('single line comment')
		} else {
			throw Error('fail')
		}
	})

	it('extract comment from js comment blocks as well', () => {
		const elt = compileIt(
			[
				'
', //
				'  {{ /*block comment*/ }}',
				'
title of the template
',
				'
'
			].join('\n')
		)
		if (elt) {
			const comments = extractLeadingComment(elt.parent.children, elt.child)
			expect(comments[0]).toEqual('block comment')
		} else {
			throw Error('fail')
		}
	})
})


text:
package org.apache.camel.example.springboot.metrics;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

import com.codahale.metrics.MetricFilter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.graphite.GraphiteReporter;
import com.codahale.metrics.graphite.GraphiteSender;
import com.codahale.metrics.graphite.GraphiteUDP;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.metrics.routepolicy.MetricsRoutePolicyFactory;
import org.apache.camel.spring.boot.CamelContextConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

/**
 * A simple Spring Boot application, with a couple of timed camel routes
 * configured with camel-metrics. Reports metrics to Graphite via
 * dropwizard-metrics GraphiteUDP sender. Has standard spring-actuator endpoints
 * such as /beans, /autoconfig, /metrics
 */
@SpringBootApplication
public class Application {

    private static final Logger LOG = LoggerFactory.getLogger(Application.class);

    @Autowired
    private MetricRegistry metricRegistry;

    /**
     * @param args no command line args required
     */
    public static void main(String[] args) {
        LOG.info(" *** STARTING CAMEL METRICS EXAMPLE APPLICATION ***");
        SpringApplication.run(Application.class, args);

    }

    /**
     * Create reporter bean and tell Spring to call stop() when shutting down.
     * UPD must be enabled in carbon.conf
     *
     * @return graphite reporter
     */
    @Bean(destroyMethod = "stop")
    public GraphiteReporter graphiteReporter() {
        final GraphiteSender graphite = new GraphiteUDP(new InetSocketAddress("localhost", 2003));
        final GraphiteReporter reporter = GraphiteReporter.forRegistry(metricRegistry).prefixedWith("camel-spring-boot").convertRatesTo(TimeUnit.SECONDS)
            .convertDurationsTo(TimeUnit.MILLISECONDS).filter(MetricFilter.ALL).build(graphite);
        reporter.start(5, TimeUnit.SECONDS);
        return reporter;
    }

    /**
     * @return timed route that logs output every 6 seconds
     */
    @Bean
    public RouteBuilder slowRoute() {
        return new RouteBuilder() {

            @Override
            public void configure() throws Exception {
                from("timer://foo?period=6000&daemon=false").routeId("slow-route").setBody().constant("Slow hello world!").log("${body}");
            }
        };
    }

    /**
     * @return timed route that logs output every 2 seconds
     */
    @Bean
    public RouteBuilder fastRoute() {
        return new RouteBuilder() {

            @Override
            public void configure() throws Exception {
                from("timer://foo?period=2000&daemon=false").routeId("fast-route").setBody().constant("Fast hello world!").log("${body}");
            }
        };
    }

    @Bean
    CamelContextConfiguration contextConfiguration() {
        return new CamelContextConfiguration() {

            @Override
            public void beforeApplicationStart(CamelContext context) {
                LOG.info("Configuring camel metrics on all routes");
                MetricsRoutePolicyFactory fac = new MetricsRoutePolicyFactory();
                fac.setMetricsRegistry(metricRegistry);
                context.addRoutePolicyFactory(fac);
            }
        };
    }

}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

namespace ServiceFabric.Tests.Tests
{
    using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
    using Xunit;
    using Microsoft.Azure.Management.ServiceFabric;
    using System.Linq;
    using Microsoft.Azure.Management.Resources;
    using System.Collections.Generic;
    using Microsoft.Azure.Management.ServiceFabric.Models;
    using System;

    public class TestUpdateClusterResource : ServiceFabricTestBase
    {
        [Fact]
        public void TestUpdate()
        {
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var serviceFabricClient = GetServiceFabricClient(context);
                var resouceClient = GetResourceManagementClient(context);

                var resourceGroups = resouceClient.ResourceGroups.List();
                foreach (var rg in resourceGroups)
                {
                    var resources = GetAllServiceFabricClusterResources(context, rg);
                    if (resources.Any())
                    {
                        var res = resources.First();
                        var cluster = serviceFabricClient.Clusters.Get(rg.Name, res.Name);

                        serviceFabricClient.Clusters.Update(rg.Name, res.Name,
                            new ClusterUpdateParameters()
                            {
                                FabricSettings = new List<SettingsSectionDescription>()
                                {
                                    new SettingsSectionDescription()
                                    {
                                        Name = "NamingService",
                                        Parameters = new List<SettingsParameterDescription>()
                                        {
                                            new SettingsParameterDescription()
                                            {
                                                Name = "MaxOperationTimeout",
                                                Value = "1000"
                                            }
                                        }
                                    }
                                }
                            });

                        cluster = serviceFabricClient.Clusters.Get(rg.Name, res.Name);
                        while (string.Compare(cluster.ClusterState, "ready",true) != 0)
                        {
                            cluster = serviceFabricClient.Clusters.Get(rg.Name, res.Name);
                            TestUtilities.Wait(TimeSpan.FromMinutes(1));
                        }

                        var ns = cluster.FabricSettings.Where(s => s.Name == "NamingService").First();
                        var p = ns.Parameters.Where(
                            parameter =>
                            parameter.Name == "MaxOperationTimeout").First();

                        Assert.True(p.Value == "1000");

                        break;
                    }
                }
            }
        }
    }
}


text:
<?php
namespace Concrete\Controller\Backend\Board;

use Concrete\Core\Board\Command\ClearSlotFromBoardCommand;
use Concrete\Core\Board\Command\DeleteBoardInstanceSlotRuleCommand;
use Concrete\Core\Board\Command\PinSlotToBoardCommand;
use Concrete\Core\Board\Instance\Slot\RenderedSlotCollectionFactory;
use Concrete\Core\Controller\AbstractController;
use Concrete\Core\Entity\Board\InstanceSlotRule;
use Concrete\Core\Logging\Channels;
use Concrete\Core\Logging\LoggerFactory;
use Concrete\Core\Package\Offline\Exception;
use Concrete\Core\Permission\Checker;
use Doctrine\ORM\EntityManager;
use Concrete\Core\Entity\Board\Instance as InstanceEntity;
use Symfony\Component\HttpFoundation\JsonResponse;

class Instance extends AbstractController
{

    protected function canEditSlotRule(InstanceSlotRule $rule)
    {
        $board = $rule->getInstance()->getBoard();
        if ($board) {
            $permissions = new Checker($board);
            if ($rule->isLocked()) {
                $canEditSlotRule = $permissions->canEditBoardLockedRules();
            } else {
                $canEditSlotRule = $permissions->canEditBoardContents();
            }
            return $canEditSlotRule;
        }
        return false;
    }

    public function deleteRule()
    {
        $entityManager = $this->app->make(EntityManager::class);
        $rule = $entityManager->find(InstanceSlotRule::class, $this->request->request->get('boardInstanceSlotRuleID'));
        if ($rule && $this->canEditSlotRule($rule)) {
            $command = new DeleteBoardInstanceSlotRuleCommand($rule);
            $this->app->executeCommand($command);
            return new JsonResponse($rule);
        }
        throw new \Exception(t('Access Denied.'));
    }

    public function deleteRuleByBatch()
    {
        $token = $this->app->make('token');
        if ($token->validate()) {
            $entityManager = $this->app->make(EntityManager::class);
            $rules = [];
            foreach((array) $this->request->request->get('instances') as $instanceID) {
                $instance = $entityManager->find(InstanceEntity::class, $instanceID);
                if ($instance) {
                    $instanceRules = $instance->getRules();
                    foreach($instanceRules as $instanceRule) {
                        if ($instanceRule->getBatchIdentifier() == $this->request->request->get('batchIdentifier')) {
                            $rules[] = $instanceRule;
                        }
                    }
                }
            }
            $canProceed = false;
            if ($rules) {
                $canProceed = true;
                foreach($rules as $rule) {
                    if (!$this->canEditSlotRule($rule)) {
                        $canProceed = false;
                    }
                }
            }
            if ($canProceed) {
                foreach($rules as $rule) {
                    $command = new DeleteBoardInstanceSlotRuleCommand($rule);
                    $this->app->executeCommand($command);
                }
                return new JsonResponse([]);
            }
            throw new \Exception(t('Access Denied.'));
        }
    }

    public function pinSlot()
    {
        $entityManager = $this->app->make(EntityManager::class);
        $boardInstanceID = $this->request->request->get('boardInstanceID');
        if ($boardInstanceID) {
            $instance = $entityManager->find(InstanceEntity::class, $boardInstanceID);
        }

        if ($instance && $this->canEditSlot($instance, $this->request->request->get('slot'))) {
            $command = new PinSlotToBoardCommand();
            $command->setBlockID($this->request->request->get('bID'));
            $command->setInstance($instance);
            $command->setSlot($this->request->request->get('slot'));
            $this->app->executeCommand($command);

            $renderedSlotCollectionFactory = $this->app->make(RenderedSlotCollectionFactory::class);
            $renderedSlotCollection = $renderedSlotCollectionFactory->createCollection($instance);

            return new JsonResponse($renderedSlotCollection->getRenderedSlot($this->request->request->get('slot')));
        }

        throw new Exception(t('Access Denied.'));
    }

    protected function canEditSlot(InstanceEntity $instance, $slot)
    {
        $rules = $instance->getRules();
        $board = $instance->getBoard();
        $checker = new Checker($board);

        foreach($rules as $rule) {
            if ($rule->getSlot() == $slot) {
                return $this->canEditSlotRule($rule);
            }
        }

        return $checker->canEditBoardContents();
    }

    public function clearSlot()
    {
        $entityManager = $this->app->make(EntityManager::class);
        $boardInstanceID = $this->request->request->get('boardInstanceID');
        if ($boardInstanceID) {
            $instance = $entityManager->find(InstanceEntity::class, $boardInstanceID);
        }

        $rule = $entityManager->find(InstanceSlotRule::class, $this->request->request->get('boardInstanceSlotRuleID'));
        if ($instance && $rule && $this->canEditSlotRule($rule)) {
            $command = new DeleteBoardInstanceSlotRuleCommand($rule);
            $this->app->executeCommand($command);

            $renderedSlotCollectionFactory = $this->app->make(RenderedSlotCollectionFactory::class);
            $renderedSlotCollection = $renderedSlotCollectionFactory->createCollection($instance);

            return new JsonResponse($renderedSlotCollection->getRenderedSlot($rule->getSlot()));
        }

        throw new Exception(t('Access Denied.'));
    }
}


text:
from office365.runtime.client_value import ClientValue

class CertificateAuthority(ClientValue):
    """Represents a certificate authority."""

    def __init__(self, certificate=None, certificate_revocation_list_url=None, is_root_authority=None):
        """
        :param str certificate: The base64 encoded string representing the public certificate.
        :param str certificate_revocation_list_url: The URL of the certificate revocation list.
        :param str is_root_authority: Required. true if the trusted certificate is a root authority, false if the
            trusted certificate is an intermediate authority.
        """
        super(CertificateAuthority, self).__init__()
        self.certificate = certificate
        self.certificateRevocationListUrl = certificate_revocation_list_url
        self.isRootAuthority = is_root_authority


text:
MEAN2 Starter is an MEAN2 stack based project for giving a kickstart to your new project.

**Angular 2 (^2.4.4)** to develop front-end

**Node** as back-end server

**Gulp** and **Webpack** for bundling.

---

This project implements a simple login system and this project is intentionally kept simple so that other developers dont have to spend hours just to integrate this boilerplate project.

---

Setup this project

1. `git clone https://github.com/NishantDesai1306/MEAN2-Starter.git`
2. Open terminal and navgate to `mean2-starter` directory
3. Execute `npm install` to install all npm dependencies for development
4. To start the project execute `npm run start`
5. Open [localhost:3000](https://localhost:3000)

![ ](https://github.com/NishantDesai1306/MEAN2-Starter/blob/master/image/demo.png)
![ ](https://github.com/NishantDesai1306/MEAN2-Starter/blob/master/image/login.png)
![ ](https://github.com/NishantDesai1306/MEAN2-Starter/blob/master/image/user-details.png)

---

###### Both `client` and `server` are under watch so no need to build project everytime you change the code.


text:
package com.threegear.gloveless.network;

import javax.vecmath.Quat4f;
import javax.vecmath.Tuple3f;

/**
 * Messages relating to pressing, releasing, dragging and moving of each hand.
 *

 * Pinch messages are always a single hand at a time.  That is, if
 * the user pinches left and right simultaneously, you will still get
 * two separate PRESS messages (one for the right and one for the left).
 * As a result, there is less lag for pinch messages (which can be reported
 * as soon as they happen) than for the "higher-level" {@link BimanualPinchMessage}
 * messages.
 *

 * Note that we do not recommend responding to both the PinchMessage
 * and the {@link BimanualPinchMessage}; applications should generally
 * pick one or the other.  Responding to both can lead to very
 * confusing interactions (since most pinches will be detected at least
 * twice).
 */
public class PinchMessage extends BasicMessage {

  protected Hand hand;

  /** @return Which hand the message refers to. */
  public Hand getHand() { return hand; }

  protected PinchMessage(BasicMessage message, Hand hand) {
    super(message);
    this.hand = hand;
  }

  public PinchMessage(MessageType type, Hand hand, Tuple3f positionLeft,
      Quat4f rotationLeft, int clickCountLeft, Tuple3f positionRight,
      Quat4f rotationRight, int clickCountRight) {
    super(type, positionLeft, rotationLeft, clickCountLeft,
        positionRight, rotationRight, clickCountRight);
    this.hand = hand;
  }

  public String serialize() {
    StringBuffer buffer = new StringBuffer();
    buffer.append(super.serialize());
    buffer.append(' ');
    buffer.append(hand.toString());
    return buffer.toString();
  }

  public static HandTrackingMessage deserialize(String data) {
    String[] result = data.split(" ");
    ParseResult parseResult = parse(result);
    return new PinchMessage(parseResult.message,
        Hand.valueOf(result[parseResult.parsed]));
  }

}


text:
// Default code generation is disabled for model 'C:\Users\tom\Desktop\effort\Main\Source\Effort.Test.Data\Northwind\Northwind.edmx'.
// To enable default code generation, change the value of the 'Code Generation Strategy' designer
// property to an alternate value. This property is available in the Properties Window when the model is
// open in the designer.


text:
package org.infinispan.util;

import net.jcip.annotations.Immutable;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.lang.reflect.Array;
import java.util.AbstractList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;

/**
 * A lightweight, read-only copy of a List.  Typically used in place of the common idiom:  return
 * Collections.unmodifiableList(new ArrayList( myInternalList ));
 *

 * a it is far more efficient than making a defensive copy and then wrapping the defensive copy in a read-only wrapper.
 *

 * Also used whenever a read-only reference List is needed.
 *

 *
 * @author Manik Surtani (manik@jboss.org)
 * @since 4.0
 */
@Immutable
public class ImmutableListCopy<E> extends AbstractList<E> implements Externalizable, Immutables.Immutable {
   private static final long serialVersionUID = 10929568968966L;
   private E[] elements;
   private int size;

   /**
    * Constructs a new ImmutableListCopy. Required by Serialization.
    */
   public ImmutableListCopy() {
   }

   /**
    * Only one copy constructor since the list is immutable.
    *
    * @param c collection to copy from
    */
   @SuppressWarnings("unchecked")
   public ImmutableListCopy(Collection<? extends E> c) {
      size = c.size();
      Object[] el = new Object[size]; // no room for growth;
      el = c.toArray(el);
      elements = (E[]) el;
   }

   /**
    * Assumes that the array passed in is "safe", i.e., is not referenced from elsewhere.  Use with care!
    *
    * @param array to reference
    */
   public ImmutableListCopy(E[] array) {
      size = array.length;
      elements = array;
   }

   /**
    * Utility constructors to allow combining collections
    *
    * @param collection1 collection to copy from
    * @param collection2 collection to copy from
    */
   @SuppressWarnings("unchecked")
   public ImmutableListCopy(Collection<? extends E> collection1, Collection<? extends E> collection2) {
      size = collection1.size() + collection2.size();
      elements = (E[]) new Object[size]; // no room for growth;
      Object[] c1 = new Object[collection1.size()];
      Object[] c2 = new Object[collection2.size()];
      c1 = collection1.toArray(c1);
      c2 = collection2.toArray(c2);
      System.arraycopy(c1, 0, elements, 0, c1.length);
      System.arraycopy(c2, 0, elements, c1.length, c2.length);
   }

   @Override
   public final int size() {
      return size;
   }

   @Override
   public final boolean isEmpty() {
      return size == 0;
   }

   @Override
   public final boolean contains(Object o) {
      return indexOf(o) >= 0;
   }

   @Override
   public final Iterator<E> iterator() {
      return new ImmutableIterator();
   }

   @Override
   public final Object[] toArray() {
      Object[] result = new Object[size];
      System.arraycopy(elements, 0, result, 0, size);
      return result;
   }

   @Override
   @SuppressWarnings("unchecked")
   public final <T> T[] toArray(T[] a) {
      if (a.length < size) {
         a = (T[]) Array.newInstance(a.getClass().getComponentType(), size);
      }
      System.arraycopy(elements, 0, a, 0, size);
      if (a.length > size) a[size] = null;
      return a;
   }

   @Override
   public final boolean add(E o) {
      throw new UnsupportedOperationException();
   }

   @Override
   public final boolean remove(Object o) {
      throw new UnsupportedOperationException();
   }

   @Override
   public final boolean addAll(Collection<? extends E> c) {
      throw new UnsupportedOperationException();
   }

   @Override
   public final boolean addAll(int index, Collection<? extends E> c) {
      throw new UnsupportedOperationException();
   }

   @Override
   public final boolean removeAll(Collection<?> c) {
      throw new UnsupportedOperationException();
   }

   @Override
   public final boolean retainAll(Collection<?> c) {
      throw new UnsupportedOperationException();
   }

   @Override
   public final E get(int index) {
      if (index >= size || index < 0) throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
      return elements[index];
   }

   @Override
   public final int indexOf(Object o) {
      if (o == null) {
         for (int i = 0; i < size; i++) {
            if (elements[i] == null) return i;
         }
      } else {
         for (int i = 0; i < size; i++) {
            if (o.equals(elements[i])) return i;
         }
      }
      return -1;
   }

   @Override
   public final int lastIndexOf(Object o) {
      if (o == null) {
         for (int i = size - 1; i >= 0; i--) {
            if (elements[i] == null) return i;
         }
      } else {
         for (int i = size - 1; i >= 0; i--) {
            if (o.equals(elements[i])) return i;
         }
      }
      return -1;
   }

   @Override
   public final ListIterator<E> listIterator() {
      return new ImmutableIterator();
   }

   @Override
   public final ListIterator<E> listIterator(int index) {
      return new ImmutableIterator(index);
   }

   @Override
   public final List<E> subList(int fromIndex, int toIndex) {
      return new ImmutableSubList<E>(fromIndex, toIndex);
   }

   /**
    * Format: - entry array size (int) - elements (Object)
    *
    * @param out stream to write to
    * @throws IOException
    */
   @Override
   public void writeExternal(ObjectOutput out) throws IOException {
      out.writeInt(size);
      for (E e : elements) out.writeObject(e);
   }

   /**
    * See {@link #writeExternal(java.io.ObjectOutput)} for serialization format
    *
    * @param in stream
    * @throws IOException
    * @throws ClassNotFoundException
    */
   @Override
   @SuppressWarnings("unchecked")
   public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
      size = in.readInt();
      elements = (E[]) new Object[size];
      for (int i = 0; i < size; i++) elements[i] = (E) in.readObject();
   }

   private class ImmutableIterator implements ListIterator<E> {
      int cursor = 0;

      ImmutableIterator(int index) {
         if (index < 0 || index > size()) throw new IndexOutOfBoundsException("Index: " + index);
         cursor = index;
      }

      ImmutableIterator() {
      }

      @Override
      public boolean hasNext() {
         return cursor != size;
      }

      @Override
      public E next() {
         try {
            return get(cursor++);
         }
         catch (IndexOutOfBoundsException e) {
            throw new NoSuchElementException();
         }
      }

      @Override
      public void remove() {
         throw new UnsupportedOperationException();
      }

      @Override
      public boolean hasPrevious() {
         return cursor != 0;
      }

      @Override
      public E previous() {
         try {
            return get(--cursor);
         }
         catch (IndexOutOfBoundsException e) {
            throw new NoSuchElementException();
         }
      }

      @Override
      public int nextIndex() {
         return cursor;
      }

      @Override
      public int previousIndex() {
         return cursor - 1;
      }

      @Override
      public void set(E o) {
         throw new UnsupportedOperationException();
      }

      @Override
      public void add(E o) {
         throw new UnsupportedOperationException();
      }
   }

   private class ImmutableSubList<E> extends AbstractList<E> {
      private int offset;
      private int size;

      ImmutableSubList(int fromIndex, int toIndex) {
         if (fromIndex < 0 || toIndex > ImmutableListCopy.this.size || fromIndex > toIndex)
            throw new IllegalArgumentException("fromIndex(" + fromIndex + "), toIndex(" + toIndex + "), size (" + ImmutableListCopy.this.size + "), List=" + ImmutableListCopy.this.toString());
         offset = fromIndex;
         size = toIndex - fromIndex;
      }

      @Override
      @SuppressWarnings("unchecked")
      public final E get(int index) {
         if (index < 0 || index >= size) throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
         return (E) ImmutableListCopy.this.get(index + offset);
      }

      @Override
      public final int size() {
         return size;
      }

      @Override
      protected final void removeRange(int fromIndex, int toIndex) {
         throw new UnsupportedOperationException();
      }

      @Override
      public final boolean addAll(Collection<? extends E> c) {
         throw new UnsupportedOperationException();
      }

      @Override
      public final boolean addAll(int index, Collection<? extends E> c) {
         throw new UnsupportedOperationException();
      }

      @Override
      public final Iterator<E> iterator() {
         return super.listIterator();
      }

      @Override
      public final ListIterator<E> listIterator(final int index) {
         if (index < 0 || (index != 0 && index >= size))
            throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);

         return new ListIterator<E>() {
            private ListIterator<?> i = ImmutableListCopy.this.listIterator(index + offset);

            @Override
            public boolean hasNext() {
               return nextIndex() < size;
            }

            @Override
            @SuppressWarnings("unchecked")
            public E next() {
               if (hasNext())
                  return (E) i.next();
               else
                  throw new NoSuchElementException();
            }

            @Override
            public boolean hasPrevious() {
               return previousIndex() >= 0;
            }

            @Override
            @SuppressWarnings("unchecked")
            public E previous() {
               if (hasPrevious())
                  return (E) i.previous();
               else
                  throw new NoSuchElementException();
            }

            @Override
            public int nextIndex() {
               return i.nextIndex() - offset;
            }

            @Override
            public int previousIndex() {
               return i.previousIndex() - offset;
            }

            @Override
            public void remove() {
               throw new UnsupportedOperationException();
            }

            @Override
            public void set(E o) {
               throw new UnsupportedOperationException();
            }

            @Override
            public void add(E o) {
               throw new UnsupportedOperationException();
            }
         };
      }

      @Override
      public final List<E> subList(int fromIndex, int toIndex) {
         return new ImmutableSubList<E>(offset + fromIndex, offset + toIndex);
      }
   }
}


text:
package org.elasticsearch.xpack.core.transform.transforms;

import org.elasticsearch.ElasticsearchStatusException;
import org.elasticsearch.Version;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable.Reader;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.xcontent.XContentBuilder;
import org.elasticsearch.xpack.core.transform.TransformField;
import org.elasticsearch.xpack.core.transform.action.AbstractWireSerializingTransformTestCase;
import org.elasticsearch.xpack.core.transform.transforms.pivot.PivotConfigTests;

import java.io.IOException;
import java.time.Instant;
import java.util.Collections;
import java.util.Map;

import static org.elasticsearch.test.AbstractXContentTestCase.xContentTester;
import static org.elasticsearch.xpack.core.transform.transforms.DestConfigTests.randomDestConfig;
import static org.elasticsearch.xpack.core.transform.transforms.SourceConfigTests.randomSourceConfig;
import static org.elasticsearch.xpack.core.transform.transforms.TransformConfigTests.randomMetadata;
import static org.elasticsearch.xpack.core.transform.transforms.TransformConfigTests.randomRetentionPolicyConfig;
import static org.elasticsearch.xpack.core.transform.transforms.TransformConfigTests.randomSyncConfig;
import static org.elasticsearch.xpack.core.transform.transforms.TransformConfigTests.randomTransformConfig;
import static org.hamcrest.Matchers.equalTo;

public class TransformConfigUpdateTests extends AbstractWireSerializingTransformTestCase<TransformConfigUpdate> {

    public static TransformConfigUpdate randomTransformConfigUpdate() {
        return new TransformConfigUpdate(
            randomBoolean() ? null : randomSourceConfig(),
            randomBoolean() ? null : randomDestConfig(),
            randomBoolean() ? null : TimeValue.timeValueMillis(randomIntBetween(1_000, 3_600_000)),
            randomBoolean() ? null : randomSyncConfig(),
            randomBoolean() ? null : randomAlphaOfLengthBetween(1, 1000),
            randomBoolean() ? null : SettingsConfigTests.randomSettingsConfig(),
            randomBoolean() ? null : randomMetadata(),
            randomBoolean() ? null : randomRetentionPolicyConfig()
        );
    }

    @Override
    protected TransformConfigUpdate createTestInstance() {
        return randomTransformConfigUpdate();
    }

    @Override
    protected Reader<TransformConfigUpdate> instanceReader() {
        return TransformConfigUpdate::new;
    }

    public void testIsNoop() {
        for (int i = 0; i < NUMBER_OF_TEST_RUNS; i++) {
            TransformConfig config = randomTransformConfig();
            TransformConfigUpdate update = TransformConfigUpdate.EMPTY;
            assertTrue("null update is not noop", update.isNoop(config));
            update = new TransformConfigUpdate(
                config.getSource(),
                config.getDestination(),
                config.getFrequency(),
                config.getSyncConfig(),
                config.getDescription(),
                config.getSettings(),
                config.getMetadata(),
                config.getRetentionPolicyConfig()
            );
            assertTrue("equal update is not noop", update.isNoop(config));

            update = new TransformConfigUpdate(
                config.getSource(),
                config.getDestination(),
                config.getFrequency(),
                config.getSyncConfig(),
                "this is a new description",
                config.getSettings(),
                config.getMetadata(),
                config.getRetentionPolicyConfig()
            );
            assertFalse("true update is noop", update.isNoop(config));
        }
    }

    public void testApply() {
        TransformConfig config = new TransformConfig(
            "time-transform",
            randomSourceConfig(),
            randomDestConfig(),
            TimeValue.timeValueMillis(randomIntBetween(1_000, 3_600_000)),
            randomSyncConfig(),
            Collections.singletonMap("key", "value"),
            PivotConfigTests.randomPivotConfig(),
            null,
            randomBoolean() ? null : randomAlphaOfLengthBetween(1, 1000),
            SettingsConfigTests.randomNonEmptySettingsConfig(),
            randomMetadata(),
            randomRetentionPolicyConfig(),
            randomBoolean() ? null : Instant.now(),
            randomBoolean() ? null : Version.V_7_2_0.toString()
        );
        TransformConfigUpdate update = new TransformConfigUpdate(null, null, null, null, null, null, null, null);

        assertThat(config, equalTo(update.apply(config)));
        SourceConfig sourceConfig = new SourceConfig("the_new_index");
        DestConfig destConfig = new DestConfig("the_new_dest", "my_new_pipeline");
        TimeValue frequency = TimeValue.timeValueSeconds(10);
        SyncConfig syncConfig = new TimeSyncConfig("time_field", TimeValue.timeValueSeconds(30));
        String newDescription = "new description";
        SettingsConfig settings = new SettingsConfig(4_000, 4_000.400F, true, true, true);
        Map<String, Object> newMetadata = randomMetadata();
        RetentionPolicyConfig retentionPolicyConfig = new TimeRetentionPolicyConfig("time_field", new TimeValue(60_000));
        update = new TransformConfigUpdate(
            sourceConfig,
            destConfig,
            frequency,
            syncConfig,
            newDescription,
            settings,
            newMetadata,
            retentionPolicyConfig
        );

        Map<String, String> headers = Collections.singletonMap("foo", "bar");
        update.setHeaders(headers);
        TransformConfig updatedConfig = update.apply(config);

        assertThat(updatedConfig.getSource(), equalTo(sourceConfig));
        assertThat(updatedConfig.getDestination(), equalTo(destConfig));
        assertThat(updatedConfig.getFrequency(), equalTo(frequency));
        assertThat(updatedConfig.getSyncConfig(), equalTo(syncConfig));
        assertThat(updatedConfig.getDescription(), equalTo(newDescription));
        assertThat(updatedConfig.getSettings(), equalTo(settings));
        // We only check for the existence of new entries. The map can also contain the old (random) entries.
        assertThat(updatedConfig.getMetadata(), equalTo(newMetadata));
        assertThat(updatedConfig.getRetentionPolicyConfig(), equalTo(retentionPolicyConfig));
        assertThat(updatedConfig.getHeaders(), equalTo(headers));
        assertThat(updatedConfig.getVersion(), equalTo(Version.CURRENT));
    }

    public void testApplySettings() {
        TransformConfig config = new TransformConfig(
            "time-transform",
            randomSourceConfig(),
            randomDestConfig(),
            TimeValue.timeValueMillis(randomIntBetween(1_000, 3_600_000)),
            randomSyncConfig(),
            Collections.singletonMap("key", "value"),
            PivotConfigTests.randomPivotConfig(),
            null,
            randomBoolean() ? null : randomAlphaOfLengthBetween(1, 1000),
            SettingsConfigTests.randomNonEmptySettingsConfig(),
            randomMetadata(),
            randomRetentionPolicyConfig(),
            randomBoolean() ? null : Instant.now(),
            randomBoolean() ? null : Version.V_7_2_0.toString()
        );

        TransformConfigUpdate update = new TransformConfigUpdate(
            null,
            null,
            null,
            null,
            null,
            new SettingsConfig(4_000, null, (Boolean) null, null, null),
            null,
            null
        );
        TransformConfig updatedConfig = update.apply(config);

        // for settings we allow partial updates, so changing 1 setting should not overwrite the other
        // the parser handles explicit nulls, tested in @link{SettingsConfigTests}
        assertThat(updatedConfig.getSettings().getMaxPageSearchSize(), equalTo(4_000));
        assertThat(updatedConfig.getSettings().getDocsPerSecond(), equalTo(config.getSettings().getDocsPerSecond()));
        assertThat(updatedConfig.getSettings().getDatesAsEpochMillis(), equalTo(config.getSettings().getDatesAsEpochMillis()));
        assertThat(updatedConfig.getSettings().getAlignCheckpoints(), equalTo(config.getSettings().getAlignCheckpoints()));

        update = new TransformConfigUpdate(
            null,
            null,
            null,
            null,
            null,
            new SettingsConfig(null, 43.244F, (Boolean) null, null, null),
            null,
            null
        );
        updatedConfig = update.apply(updatedConfig);
        assertThat(updatedConfig.getSettings().getMaxPageSearchSize(), equalTo(4_000));
        assertThat(updatedConfig.getSettings().getDocsPerSecond(), equalTo(43.244F));
        assertThat(updatedConfig.getSettings().getDatesAsEpochMillis(), equalTo(config.getSettings().getDatesAsEpochMillis()));
        assertThat(updatedConfig.getSettings().getAlignCheckpoints(), equalTo(config.getSettings().getAlignCheckpoints()));

        // now reset to default using the magic -1
        update = new TransformConfigUpdate(
            null,
            null,
            null,
            null,
            null,
            new SettingsConfig(-1, null, (Boolean) null, null, null),
            null,
            null
        );
        updatedConfig = update.apply(updatedConfig);
        assertNull(updatedConfig.getSettings().getMaxPageSearchSize());
        assertThat(updatedConfig.getSettings().getDocsPerSecond(), equalTo(43.244F));
        assertThat(updatedConfig.getSettings().getDatesAsEpochMillis(), equalTo(config.getSettings().getDatesAsEpochMillis()));
        assertThat(updatedConfig.getSettings().getAlignCheckpoints(), equalTo(config.getSettings().getAlignCheckpoints()));

        update = new TransformConfigUpdate(
            null,
            null,
            null,
            null,
            null,
            new SettingsConfig(-1, -1F, (Boolean) null, null, null),
            null,
            null
        );
        updatedConfig = update.apply(updatedConfig);
        assertNull(updatedConfig.getSettings().getMaxPageSearchSize());
        assertNull(updatedConfig.getSettings().getDocsPerSecond());
        assertThat(updatedConfig.getSettings().getDatesAsEpochMillis(), equalTo(config.getSettings().getDatesAsEpochMillis()));
        assertThat(updatedConfig.getSettings().getAlignCheckpoints(), equalTo(config.getSettings().getAlignCheckpoints()));
    }

    public void testApplyMetadata() {
        Map<String, Object> oldMetadata = Map.of("foo", 123, "bar", 456);
        TransformConfig config = new TransformConfig(
            "time-transform",
            randomSourceConfig(),
            randomDestConfig(),
            TimeValue.timeValueMillis(randomIntBetween(1_000, 3_600_000)),
            randomSyncConfig(),
            Collections.singletonMap("key", "value"),
            PivotConfigTests.randomPivotConfig(),
            null,
            randomBoolean() ? null : randomAlphaOfLengthBetween(1, 1000),
            SettingsConfigTests.randomNonEmptySettingsConfig(),
            oldMetadata,
            randomRetentionPolicyConfig(),
            randomBoolean() ? null : Instant.now(),
            randomBoolean() ? null : Version.V_7_2_0.toString()
        );

        Map<String, Object> newMetadata = Map.of("bar", 789, "baz", 1000);
        TransformConfigUpdate update = new TransformConfigUpdate(null, null, null, null, null, null, newMetadata, null);
        TransformConfig updatedConfig = update.apply(config);

        // For metadata we apply full replace rather than partial update, so "foo" disappears.
        assertThat(updatedConfig.getMetadata(), equalTo(Map.of("bar", 789, "baz", 1000)));
    }

    public void testApplyWithSyncChange() {
        TransformConfig batchConfig = new TransformConfig(
            "batch-transform",
            randomSourceConfig(),
            randomDestConfig(),
            TimeValue.timeValueMillis(randomIntBetween(1_000, 3_600_000)),
            null,
            null,
            PivotConfigTests.randomPivotConfig(),
            null,
            randomBoolean() ? null : randomAlphaOfLengthBetween(1, 1000),
            SettingsConfigTests.randomNonEmptySettingsConfig(),
            randomMetadata(),
            randomRetentionPolicyConfig(),
            randomBoolean() ? null : Instant.now(),
            randomBoolean() ? null : Version.CURRENT.toString()
        );

        TransformConfigUpdate update = new TransformConfigUpdate(
            null,
            null,
            null,
            TimeSyncConfigTests.randomTimeSyncConfig(),
            null,
            null,
            null,
            null
        );

        ElasticsearchStatusException ex = expectThrows(ElasticsearchStatusException.class, () -> update.apply(batchConfig));
        assertThat(
            ex.getMessage(),
            equalTo("Cannot change the current sync configuration of transform [batch-transform] from [null] to [time]")
        );

        TransformConfig timeSyncedConfig = new TransformConfig(
            "time-transform",
            randomSourceConfig(),
            randomDestConfig(),
            TimeValue.timeValueMillis(randomIntBetween(1_000, 3_600_000)),
            randomSyncConfig(),
            null,
            PivotConfigTests.randomPivotConfig(),
            null,
            randomBoolean() ? null : randomAlphaOfLengthBetween(1, 1000),
            SettingsConfigTests.randomNonEmptySettingsConfig(),
            randomMetadata(),
            randomRetentionPolicyConfig(),
            randomBoolean() ? null : Instant.now(),
            randomBoolean() ? null : Version.CURRENT.toString()
        );

        TransformConfigUpdate fooSyncUpdate = new TransformConfigUpdate(null, null, null, new FooSync(), null, null, null, null);
        ex = expectThrows(ElasticsearchStatusException.class, () -> fooSyncUpdate.apply(timeSyncedConfig));
        assertThat(
            ex.getMessage(),
            equalTo("Cannot change the current sync configuration of transform [time-transform] from [time] to [foo]")
        );

    }

    public void testFromXContent() throws IOException {
        xContentTester(
            this::createParser,
            TransformConfigUpdateTests::randomTransformConfigUpdate,
            this::toXContent,
            TransformConfigUpdate::fromXContent
        ).supportsUnknownFields(false).assertEqualsConsumer(this::assertEqualInstances).test();
    }

    private void toXContent(TransformConfigUpdate update, XContentBuilder builder) throws IOException {
        builder.startObject();
        if (update.getSource() != null) {
            builder.field(TransformField.SOURCE.getPreferredName(), update.getSource());
        }
        if (update.getDestination() != null) {
            builder.field(TransformField.DESTINATION.getPreferredName(), update.getDestination());
        }
        if (update.getFrequency() != null) {
            builder.field(TransformField.FREQUENCY.getPreferredName(), update.getFrequency().getStringRep());
        }
        if (update.getSyncConfig() != null) {
            builder.startObject(TransformField.SYNC.getPreferredName());
            builder.field(update.getSyncConfig().getWriteableName(), update.getSyncConfig());
            builder.endObject();
        }
        if (update.getDescription() != null) {
            builder.field(TransformField.DESCRIPTION.getPreferredName(), update.getDescription());
        }
        if (update.getSettings() != null) {
            builder.field(TransformField.SETTINGS.getPreferredName(), update.getSettings());
        }
        if (update.getMetadata() != null) {
            builder.field(TransformField.METADATA.getPreferredName(), update.getMetadata());
        }
        if (update.getRetentionPolicyConfig() != null) {
            builder.startObject(TransformField.RETENTION_POLICY.getPreferredName());
            builder.field(update.getRetentionPolicyConfig().getWriteableName(), update.getRetentionPolicyConfig());
            builder.endObject();
        }

        builder.endObject();
    }

    static class FooSync implements SyncConfig {

        @Override
        public QueryBuilder getRangeQuery(TransformCheckpoint newCheckpoint) {
            return null;
        }

        @Override
        public QueryBuilder getRangeQuery(TransformCheckpoint oldCheckpoint, TransformCheckpoint newCheckpoint) {
            return null;
        }

        @Override
        public String getWriteableName() {
            return "foo";
        }

        @Override
        public String getField() {
            return "foo";
        }

        @Override
        public void writeTo(StreamOutput out) throws IOException {}

        @Override
        public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
            return null;
        }
    }
}


text:
<!DOCTYPE 5>

    <title>angular-cog demo!</title>

        {{users}}

    <form cog-post="/utopia/api/project/42/users"
    			cog-model="user"
    			cog-success="{function|string}"
    			cog-error="console.log($data)"
    			cog-absolute-url
    			cog-config="{object}">

        <input type="text" ng-model="user.name" required>
        <button type="submit" value="submit">Submit</button>
    </form>

    <form cog-put="/utopia/api/project/42/users"
    			cog-model="user"
    			cog-success="{function|string}"
    			cog-error="users.push($status)"
    			cog-absolute-url
    			cog-config="{object}">

        <input type="text" ng-model="user.name" required>
        <button type="submit" value="submit">Submit</button>

    </form>

		<button cog-delete="/utopia/api" cog-success="users.push($data)">Submit</button>


text:
package com.jiabangou.mtwmsdk.api.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.util.TypeUtils;
import com.jiabangou.mtwmsdk.api.FoodService;
import com.jiabangou.mtwmsdk.api.LogListener;
import com.jiabangou.mtwmsdk.api.MtWmConfigStorage;
import com.jiabangou.mtwmsdk.exception.MtWmErrorException;
import com.jiabangou.mtwmsdk.model.Food;
import com.jiabangou.mtwmsdk.model.FoodCategory;
import com.jiabangou.mtwmsdk.model.FoodCategoryDetail;
import com.jiabangou.mtwmsdk.model.FoodSkuStock;
import org.apache.http.HttpHost;
import org.apache.http.impl.client.CloseableHttpClient;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 菜品类API
 * Created by freeway on 16/3/12.
 */
public class FoodServiceImpl extends BaseServiceImpl implements FoodService {

    private static final String FOODCAT_UPDATE = "/foodCat/update";
    private static final String FOODCAT_DELETE = "/foodCat/delete";
    private static final String FOODCAT_LIST = "/foodCat/list";
    private static final String FOOD_SAVE = "/food/save";
    private static final String FOOD_INITDATA = "/food/initdata";
    private static final String FOOD_DELETE = "/food/delete";
    private static final String FOOD_SKU_DELETE = "/food/sku/delete";
    private static final String FOOD_LIST = "/food/list";
    private static final String FOOD_UPDATE_STOCK = "/food/sku/stock";
    private static final String FOOD_SKU_SELLSTATUS = "/food/sku/sellStatus";

    public FoodServiceImpl(MtWmConfigStorage mtWmConfigStorage, CloseableHttpClient httpClient, HttpHost httpProxy,
                           LogListener listener,  boolean isTest) {
        super(mtWmConfigStorage, httpClient, httpProxy, listener, isTest);
    }

    public void updateCategory(FoodCategory foodCategory) throws MtWmErrorException {
        doPost(FOODCAT_UPDATE, foodCategory);
    }

    public void deleteCategory(String appPoiCode, String categoryName) throws MtWmErrorException {
        Map<String, String> params = new HashMap<String, String>();
        params.put("app_poi_code", appPoiCode);
        params.put("category_name", categoryName);
        doPost(FOODCAT_DELETE, params);
    }

    public List<FoodCategoryDetail> list(String appPoiCode) throws MtWmErrorException {
        Map<String, String> params = new HashMap<String, String>();
        params.put("app_poi_code", appPoiCode);
        return getList(doGet(FOODCAT_LIST, params), DATA, FoodCategoryDetail.class);
    }

    public void save(Food food) throws MtWmErrorException {
        doPost(FOOD_SAVE, food);
    }

    @Override
    public void initdata(Food food) throws MtWmErrorException {
        doPost(FOOD_INITDATA, food);
    }

    public void batchSave(String appPoiCode, List<Food> foods) throws MtWmErrorException {
        Map<String, String> params = new HashMap<String, String>();
        params.put("app_poi_code", appPoiCode);
        params.put("food_data", JSONArray.toJSONString(foods));
        doPost(FOOD_DELETE, params);
    }

    public void delete(String appPoiCode, String appFoodCode) throws MtWmErrorException {
        Map<String, String> params = new HashMap<String, String>();
        params.put("app_poi_code", appPoiCode);
        params.put("app_food_code", appFoodCode);
        doPost(FOOD_DELETE, params);
    }

    @Override
    public void deleteSku(String appPoiCode, String appFoodCode, String skuId) throws MtWmErrorException {

        Map<String, String> params = new HashMap<String, String>();
        params.put("app_poi_code", appPoiCode);
        params.put("app_food_code", appFoodCode);
        params.put("sku_id", skuId);
        doPost(FOOD_SKU_DELETE, params);
    }

    public List<Food> gets(String appPoiCode) throws MtWmErrorException {
        Map<String, String> params = new HashMap<String, String>();
        params.put("app_poi_code", appPoiCode);
        JSONObject jsonObject = doPost(FOOD_LIST, params);
        JSONArray jsonArray = jsonObject.getJSONArray(DATA);
        List<Food> list = new ArrayList<Food>();
        for (Object obj : jsonArray) {
            JSONObject jsonObjectTemp = (JSONObject) obj;
            if(jsonObjectTemp.getString("skus") != null && !jsonObjectTemp.getString("skus").equals("")){
                jsonObjectTemp.put("skus", JSON.parseArray(jsonObjectTemp.getString("skus")));
            }
            list.add(TypeUtils.castToJavaBean(jsonObjectTemp, Food.class));
        }
        return list;
    }

    @Override
    public void updateSkuStock(String appPoiCode, List<FoodSkuStock> foodSkuStocks) throws MtWmErrorException {
        Map<String, String> params = new HashMap<String, String>();
        params.put("app_poi_code", appPoiCode);
        params.put("food_data", JSONArray.toJSONString(foodSkuStocks));
        doPost(FOOD_UPDATE_STOCK, params);
    }

    @Override
    public void skuSellStatus(String appPoiCode, List<FoodSkuStock> foodSkuStocks, int sellStatus) throws MtWmErrorException {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("app_poi_code", appPoiCode);
        params.put("food_data", JSONArray.toJSONString(foodSkuStocks));
        params.put("sell_status",sellStatus);
        doPost(FOOD_SKU_SELLSTATUS, params);
    }

}


text:
package chav1961.purelib.streams.char2char.intern;

import org.junit.Assert;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import chav1961.purelib.streams.char2char.intern.ListManipulationStack;
import chav1961.purelib.testing.OrdinalTestCategory;

@Category(OrdinalTestCategory.class)
public class ListManipulationStackTest {
	@Test
	public void lifeCycleTest() {
		final ListManipulationStack	lms = new ListManipulationStack();

		Assert.assertEquals(lms.size(),0);

		lms.push(ListManipulationStack.ListType.TYPE_UL);
		Assert.assertEquals(lms.size(),1);
		Assert.assertEquals(lms.getTopType(),ListManipulationStack.ListType.TYPE_UL);
		Assert.assertEquals(lms.count(),0);

		lms.inc();
		Assert.assertEquals(lms.count(),1);

		for (int index = 0; index < 10; index++) {
			lms.push(ListManipulationStack.ListType.TYPE_UL);
		}
		Assert.assertEquals(lms.size(),11);
		for (int index = 0; index < 10; index++) {
			Assert.assertEquals(lms.pop(),ListManipulationStack.ListType.TYPE_UL);
		}
		Assert.assertEquals(lms.size(),1);
		Assert.assertEquals(lms.count(),1);

		Assert.assertEquals(lms.pop(),ListManipulationStack.ListType.TYPE_UL);
		Assert.assertEquals(lms.size(),0);
	}
}