text:
extern crate log;
extern crate futures;
extern crate tokio_core as tokio;
extern crate tokio_service as service;
extern crate tokio_proto as proto;
extern crate tokio_timer;
extern crate env_logger;
extern crate vastatrix;

use std::net::SocketAddr;
use std::time::Duration;

use tokio::reactor::Core;
use futures::Future;
use vastatrix::LogPos;

use vastatrix::hosting::*;

/// Remove ThickClient#add_peer calls, replace with Zarniwhoop^Wetcd config.
#[test]
fn smoketest_single_node() {
    env_logger::init().unwrap_or(());

    let mut core = Core::new().unwrap();
    let timer = tokio_timer::wheel().tick_duration(Duration::from_millis(1)).build();
    let timeout = Duration::from_millis(1000);

    let local_anon_addr: SocketAddr = "127.0.0.1:0".parse().unwrap();

    let server = build_server(
                                        &core.handle(),
                                        local_anon_addr.clone(),
                                        local_anon_addr.clone())
                     .expect("start server");
    println!("running: {:?}", server);

    info!("Head at: {:?}, tail at: {:?}",
          server.head,
          server.tail);
    let client = vastatrix::ThickClient::new(core.handle(),
                                             &server.head,
                                             &server.tail);

    let f = client.log_item(b"hello".to_vec())
                  .and_then(|pos0| {
                      client.log_item(b"world".to_vec()).map(move |pos1| (pos0, pos1))
                  });
    let (wpos0, wpos1) = core.run(timer.timeout(f, timeout)).expect("run write");

    info!("Wrote to offset:{:?}", (wpos0, wpos1));

    let item_f = client.fetch_next(LogPos::zero())
                       .and_then(|(pos0, val0)| {
                           client.fetch_next(pos0).map(move |second| vec![(pos0, val0), second])
                       });

    let read = core.run(timer.timeout(item_f, timeout)).expect("run read");
    info!("Got: {:?}", read);

    assert_eq!(read,
               vec![(wpos0, b"hello".to_vec()), (wpos1, b"world".to_vec())]);
}

#[test]
fn smoketest_two_member_chain() {
    env_logger::init().unwrap_or(());
    let timer = tokio_timer::wheel().tick_duration(Duration::from_millis(1)).build();
    let timeout = Duration::from_millis(1000);
    let mut core = Core::new().unwrap();

    let local_anon_addr: SocketAddr = "127.0.0.1:0".parse().unwrap();
    let mut head_addr = local_anon_addr.clone();
    let mut tail_addr = local_anon_addr.clone();

    head_addr.set_port(11000);
    tail_addr.set_port(11001);
    let server0 = build_server(
                      &core.handle(),
                      head_addr.clone(),
                      tail_addr.clone())
        .expect("start server");
    println!("running: {:?}", server0);

    head_addr.set_port(11010);
    tail_addr.set_port(11011);
    let server1 = build_server(
                      &core.handle(),
                      head_addr.clone(),
                      tail_addr.clone())
        .expect("start server");

    println!("running: {:?}", server1);

    let client = vastatrix::ThickClient::new(core.handle(), &server0.head, &server1.tail);

    let f = client.add_peer(server0.clone())
        .and_then(|_| client.add_peer(server1.clone()))
        .and_then(|_| client.log_item(b"hello".to_vec()))
        .and_then(|pos0| client.log_item(b"world".to_vec()).map(move |pos1| (pos0, pos1)));
    let (wpos0, wpos1) = core.run(timer.timeout(f, timeout)).expect("run write");

    info!("Wrote to offset:{:?}", (wpos0, wpos1));

    let item_f = client.fetch_next(LogPos::zero())
        .and_then(|(pos0, val0)| {
            client.fetch_next(pos0).map(move |second| vec![(pos0, val0), second])
        });

    let read = core.run(timer.timeout(item_f, timeout)).expect("run read");
    info!("Got: {:?}", read);

    assert_eq!(read,
               vec![(wpos0, b"hello".to_vec()), (wpos1, b"world".to_vec())]);
}

#[test]
fn smoketest_three_member_chain() {
    env_logger::init().unwrap_or(());
    let timer = tokio_timer::wheel().tick_duration(Duration::from_millis(1)).build();
    let timeout = Duration::from_millis(1000);
    let mut core = Core::new().unwrap();

    let local_anon_addr: SocketAddr = "127.0.0.1:0".parse().unwrap();
    let mut head_addr = local_anon_addr.clone();
    let mut tail_addr = local_anon_addr.clone();

    head_addr.set_port(11300);
    tail_addr.set_port(11301);
    let server0 = build_server(
                      &core.handle(),
                      head_addr.clone(),
                      tail_addr.clone())
        .expect("start server");
    println!("running: {:?}", server0);

    head_addr.set_port(11310);
    tail_addr.set_port(11311);
    let server1 = build_server(
                      &core.handle(),
                      head_addr.clone(),
                      tail_addr.clone())
        .expect("start server");

    println!("running: {:?}", server1);

    head_addr.set_port(11320);
    tail_addr.set_port(11321);
    let server2 = build_server(
                      &core.handle(),
                      head_addr.clone(),
                      tail_addr.clone())
        .expect("start server");
    println!("running: {:?}", server2);

    let client = vastatrix::ThickClient::new(core.handle(), &server0.head, &server2.tail);

    let f = client.add_peer(server0.clone())
        .and_then(|_| client.add_peer(server1.clone()))
        .and_then(|_| client.log_item(b"hello".to_vec()))
        .and_then(|pos0| client.add_peer(server2.clone()).map(move |_| pos0))
        .and_then(|pos0| client.log_item(b"world".to_vec()).map(move |pos1| (pos0, pos1)));
    let (wpos0, wpos1) = core.run(timer.timeout(f, timeout)).expect("run write");

    info!("Wrote to offset:{:?}", (wpos0, wpos1));

    let (pos0, val0) = core.run(timer.timeout(client.fetch_next(LogPos::zero()), timeout)).expect("fetch first");
    info!("Got: {:?}", (&pos0, &val0));
    let (pos1, val1) = core.run(timer.timeout(client.fetch_next(pos0), timeout)).expect("fetch second");
    info!("Got: {:?}", (&pos1, &val1));

    assert_eq!(vec![(pos0, &*String::from_utf8_lossy(&val0)), (wpos1, &*String::from_utf8_lossy(&val1))],
               vec![(wpos0, "hello"), (wpos1, "world")]);
}


text:
/* eslint-env node */

'use strict';

function isValidLocaleFormat(locale) {
  if (!/^[a-zA-Z0-9-]+$/.test(locale)) {
    return false;
  }

  return true;
}

module.exports = isValidLocaleFormat;

redpajama_set_name: RedPajamaGithub


text:
using ZyGames.Framework.Cache.Generic;
using ZyGames.Framework.Game.Cache;
using ZyGames.Framework.Game.Service;
using ZyGames.Framework.Common;
using ZyGames.Tianjiexing.Lang;
using ZyGames.Tianjiexing.Model;
using ZyGames.Tianjiexing.BLL.Base;

namespace ZyGames.Tianjiexing.BLL.Action
{

    /// <summary>
    /// 3201_赛跑界面接口
    /// </summary>
    public class Action3201 : BaseAction
    {
        private int _runTimes;
        private int _interceptTimes;
        private int _helpTimes;
        private int _coldTime;
        private string _petHead;
        private int _petId;

        public Action3201(ZyGames.Framework.Game.Contract.HttpGet httpGet)
            : base(ActionIDDefine.Cst_Action3201, httpGet)
        {

        }

        public override void BuildPacket()
        {
            this.PushIntoStack(ContextUser.GoldNum);
            this.PushIntoStack(ContextUser.GameCoin);
            this.PushIntoStack(_runTimes);
            this.PushIntoStack(_interceptTimes);
            this.PushIntoStack(_helpTimes);
            this.PushIntoStack(_coldTime);
            this.PushIntoStack(_petHead.ToNotNullString());
            this.PushIntoStack(_petId);
            SaveLog(string.Format("3201下发宠物ID{0}", _petId));
        }

        public override bool GetUrlElement()
        {
            return true;
        }

        public override bool TakeAction()
        {

            if (new GameDataCacheSet<UserFunction>().FindKey(Uid, FunctionEnum.PetRun) == null)
            {
                ErrorCode = LanguageManager.GetLang().ErrorCode;
                ErrorInfo = LanguageManager.GetLang().St_NoFun;
                return false;
            }
            UserDailyRestrain restrain = new GameDataCacheSet<UserDailyRestrain>().FindKey(Uid);
            if (restrain != null && restrain.UserExtend != null)
            {
                var dailyCacheSet = new ShareCacheStruct<DailyRestrainSet>();
                if (dailyCacheSet.FindKey(RestrainType.PetRun) != null)
                    _runTimes = MathUtils.Subtraction(dailyCacheSet.FindKey(RestrainType.PetRun).MaxNum, restrain.UserExtend.PetRunTimes, 0);
                if (dailyCacheSet.FindKey(RestrainType.PetIntercept) != null)
                    _interceptTimes = MathUtils.Subtraction(dailyCacheSet.FindKey(RestrainType.PetIntercept).MaxNum, restrain.UserExtend.PetIntercept, 0);
                if (dailyCacheSet.FindKey(RestrainType.PetHelp) != null)
                    _helpTimes = MathUtils.Subtraction(dailyCacheSet.FindKey(RestrainType.PetHelp).MaxNum, restrain.UserExtend.PetHelp, 0);
            }
            var petRun = new ShareCacheStruct<PetRunPool>().FindKey(Uid);
            if (petRun != null)
            {
                //问题:在赛跑时有重刷点亮宠物后,等赛跑完服务端与客户端记录宠物ID不一致,原因是赛跑完有将宠物ID清除
                if (petRun.PetID > 0 && petRun.ColdTime == 0)
                {
                    UserHelper.ProcessPetPrize(petRun);
                }
                _coldTime = petRun.ColdTime;
                _petHead = (new ConfigCacheSet<PetInfo>().FindKey(petRun.PetID) ?? new PetInfo()).PetHead;
                if (ContextUser.UserExtend != null)
                    _petId = ContextUser.UserExtend.LightPetID;
            }
            return true;
        }
    }
}


text:
def usecases():
   from pprint import pprint

   print '\n--- Sorting Simple Lists ---\n'
   data = ['Jim', 'Will', 'Tom']
   print data
   data.sort( By(len) )
   print data

   print '\n--- Sorting Simple Tables ---\n'
   data = [
      ('Jim', 21),
      ('Will', 24),
      ('Tom', 20),
      ]
   pprint(data)
   data.sort( ByColumn(0) ) # using straight forward comparator closure
   pprint(data)
   data.sort( By(Column(1)) ) # comparator/accessor closure combination
   pprint(data)

   print '\n--- Sorting Object Tables ---\n'
   class Record:
      def __init__(self, **kw): self.__dict__.update(kw)
      def __repr__(self): return '<record %r>' % self.__dict__
   data = [
      Record(name='Jim', age=21),
      Record(name='Will', age=24),
      Record(name='Tom', age=20),
      ]
   pprint(data)
   data.sort( ByAttribute('name') ) # using straight forward comparator closure
   pprint(data)
   data.sort( By(Attribute('age')) ) # comparator/accessor closure combination
   pprint(data)

# -- a straight forward approach: --

def ByColumn(key):
   def compare(obj1, obj2): return cmp(obj1[key], obj2[key])
   return compare

def ByAttribute(name):
   def compare(obj1, obj2): return cmp(getattr(obj1, name), getattr(obj2, name))
   return compare

# -- a somewhat more generic approach: --

def By(accessor):
   def compare(left, right): return cmp( accessor(left), accessor(right) )
   return compare
def Attribute(name):
   def get(obj): return getattr(obj, name)
   return get
def Column(key):
   def get(obj): return obj[key]
   return get

# -- demo: --

if __name__ == '__main__':
   usecases()


text:
FOUNDATION_EXPORT double XMImagePickerVersionNumber;
FOUNDATION_EXPORT const unsigned char XMImagePickerVersionString[];


text:
package org.compass.core.test.rebuildcompass;

/**
 * @author kimchy
 */
public class B {

    int id;

    String value;
}


text:
A few days after setting up my first Mongo Replica set, I found one of the
members had become stale.  It had actually been stale for four days.  I looked around and couldn't find
a script to monitor the replica set with Nagios.

My solution simply pulls the status from the Mongo admin web server and parses it.

# NOTES

Simply save check_mongo_replica_stat.rb with the rest of your Nagios plugins.  I save mine in
/usr/lib/nagios/local-plugins.

Create a Nagios command

    define command {
	    command_name    check-mongo-replica-set
	    command_line    /usr/lib/nagios/local-plugins/check_mongo_replica_stat.rb
	    # Note, you can pass --host and --port as well
    }

Then create a service check

    define service {
        host				            sample_host
        service_description             Mongo Replica Status
        check_command                   check-mongo-replica-set
	    notification_interval		    5
        use                             generic-service
    }

Reload your Nagios configuration and the new monitor should be running.

# License

 Copyright (C) 2011 Tony Nelson.

   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.


text:
from simulation.aivika.modeler.model import *
from simulation.aivika.modeler.port import *

def create_arrival_timer(model, name, descr = None):
    """Return a new timer that allows measuring the processing time of transacts."""
    y = ArrivalTimerPort(model, name = name, descr = descr)
    code = 'newArrivalTimer'
    y.write(code)
    return y

def arrival_timer_stream(arrival_timer_port, stream_port):
    """Measure the processing time of transacts from the specified stream within the resulting stream."""
    t = arrival_timer_port
    s = stream_port
    expect_arrival_timer(t)
    expect_stream(s)
    expect_same_model([t, s])
    model = t.get_model()
    item_data_type = s.get_item_data_type()
    code = 'return $ runProcessor (arrivalTimerProcessor ' + t.read() + ') ' + s.read()
    y = StreamPort(model, item_data_type)
    y.write(code)
    y.bind_to_input()
    s.bind_to_output()
    return y

def reset_arrival_timer(arrival_timer_port, reset_time):
    """Reset the arrival timer statistics at the specified modeling time."""
    t = arrival_timer_port
    expect_arrival_timer(t)
    model = t.get_model()
    code = 'runEventInStartTime $ enqueueEvent ' + str(reset_time)
    code += ' $ resetArrivalTimer ' + t.read()
    model.add_action(code)


text:
using DragonSpark.Model.Selection;
using Microsoft.Extensions.DependencyInjection;

namespace DragonSpark.Composition;

sealed class Service<T> : ISelect<IServiceCollection, T> where T : notnull
{
	public static Service<T> Default { get; } = new();

	Service() {}

	public T Get(IServiceCollection parameter)
	{
		using var provider = parameter.BuildServiceProvider(false);
		var       next     = new ActivationAwareServiceProvider(provider);
		var       result   = new LocateAwareServiceProvider(next, parameter).GetRequiredService<T>();
		return result;
	}
}


text:
package org.seasar.doma.internal.jdbc.mock;

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

public class RowData {

  protected final List<Object> values = new ArrayList<>();

  public RowData(Object... values) {
    this.values.addAll(Arrays.asList(values));
  }

  public Object get(int index) {
    return values.get(index - 1);
  }

  public int size() {
    return values.size();
  }
}


text:
using namespace std;

int main(int argc, const char *argv[])
{
    vector<Student_info> students;
    Student_info record;
    string::size_type maxlen = 0;

    // read and store the data
    while (record.read(cin)) {
        maxlen = max(maxlen, record.name().size());
        students.push_back(record);
    }

    sort(students.begin(), students.end(), Student_info::compare);

    for (vector<Student_info>::size_type i = 0; i != students.size(); i++) {
        cout << students[i].name() << string(maxlen + 1 - students[i].name().size(), ' ');
        try {
            double final_grade = students[i].grade();
            streamsize prec = cout.precision();
            cout << setprecision(3) << final_grade << setprecision(prec) << endl;
        } catch (domain_error e) {
            cout << e.what() << endl;
        }
    }
    return 0;
}


text:
import re

from streamlink.plugin import Plugin, pluginmatcher
from streamlink.stream import HLSStream

API_URL = "http://{}.nhk.or.jp/nhkworld/app/tv/hlslive_web.json"

@pluginmatcher(re.compile(
    r"https?://(?:(\w+)\.)?nhk\.or\.jp/nhkworld"
))
class NHKWorld(Plugin):
    def _get_streams(self):
        # get the HLS json from the same sub domain as the main url, defaulting to www
        sdomain = self.match.group(1) or "www"
        res = self.session.http.get(API_URL.format(sdomain))

        stream_url = self.session.http.json(res)['main']['wstrm']
        return HLSStream.parse_variant_playlist(self.session, stream_url)

__plugin__ = NHKWorld


text:
package org.apach3.http.impl.client.cache;

import org.apach3.commons.logging.Log;
import org.apach3.commons.logging.LogFactory;
import org.apach3.http.Header;
import org.apach3.http.HeaderElement;
import org.apach3.http.HttpRequest;
import org.apach3.http.HttpVersion;
import org.apach3.http.ProtocolVersion;
import org.apach3.http.annotation.Immutable;
import org.apach3.http.client.cache.HeaderConstants;

/**
 * Determines if an HttpRequest is allowed to be served from the cache.
 *
 * @since 4.1
 */
@Immutable
class CacheableRequestPolicy {

    private final Log log = LogFactory.getLog(getClass());

    /**
     * Determines if an HttpRequest can be served from the cache.
     *
     * @param request
     *            an HttpRequest
     * @return boolean Is it possible to serve this request from cache
     */
    public boolean isServableFromCache(HttpRequest request) {
        String method = request.getRequestLine().getMethod();

        ProtocolVersion pv = request.getRequestLine().getProtocolVersion();
        if (HttpVersion.HTTP_1_1.compareToVersion(pv) != 0) {
            log.trace("non-HTTP/1.1 request was not serveable from cache");
            return false;
        }

        if (!method.equals(HeaderConstants.GET_METHOD)) {
            log.trace("non-GET request was not serveable from cache");
            return false;
        }

        if (request.getHeaders(HeaderConstants.PRAGMA).length > 0) {
            log.trace("request with Pragma header was not serveable from cache");
            return false;
        }

        Header[] cacheControlHeaders = request.getHeaders(HeaderConstants.CACHE_CONTROL);
        for (Header cacheControl : cacheControlHeaders) {
            for (HeaderElement cacheControlElement : cacheControl.getElements()) {
                if (HeaderConstants.CACHE_CONTROL_NO_STORE.equalsIgnoreCase(cacheControlElement
                        .getName())) {
                    log.trace("Request with no-store was not serveable from cache");
                    return false;
                }

                if (HeaderConstants.CACHE_CONTROL_NO_CACHE.equalsIgnoreCase(cacheControlElement
                        .getName())) {
                    log.trace("Request with no-cache was not serveable from cache");
                    return false;
                }
            }
        }

        log.trace("Request was serveable from cache");
        return true;
    }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Hendersonia quercina Sacc.

### Remarks
null


text:
package com.wyp.materialqqlite.ui;

import com.material.widget.CircularProgress;
import com.material.widget.FloatingEditText;

import com.wyp.materialqqlite.AbsActivity;
import com.wyp.materialqqlite.AppData;
import com.wyp.materialqqlite.LoginAccountList;
import com.wyp.materialqqlite.R;
import com.wyp.materialqqlite.qqclient.QQClient;
import com.wyp.materialqqlite.qqclient.protocol.protocoldata.QQCallBackMsg;
import com.wyp.materialqqlite.qqclient.protocol.protocoldata.QQLoginResultCode;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;

public class VerifyCodeActivity extends AbsActivity{
	//private TextView m_txtCancel;
	//private Button m_btnFinish;
	private ImageView m_imgVC;
	private CircularProgress m_prgLogining;
	private FloatingEditText m_edtVC;
	private QQClient m_QQClient;

         private SharedPreferences sp;
         private int color_theme;

	private Handler m_Handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			m_prgLogining.setVisibility(View.GONE);
			switch (msg.what) {
			case QQCallBackMsg.LOGIN_RESULT:
				if (msg.arg1 == QQLoginResultCode.SUCCESS) {	// 登录成功
					LoginAccountList accountList = AppData.getAppData().getLoginAccountList();
			    	int nPos = accountList.add(m_QQClient.getQQNum(),
							m_QQClient.getQQPwd(), m_QQClient.getLoginStatus(), true, true);
			    	accountList.setLastLoginUser(nPos);

			    	String strAppPath = AppData.getAppData().getAppPath();
			    	String strFileName = strAppPath + "LoginAccountList.dat";
			    	accountList.saveFile(strFileName);

					m_QQClient.setNullCallBackHandler(m_Handler);
					startActivity(new Intent(VerifyCodeActivity.this, MainActivity.class));
					finish();
				} else if (msg.arg1 == QQLoginResultCode.FAILED) {	// 登录失败
					Toast.makeText(getBaseContext(),
							R.string.login_failed, Toast.LENGTH_LONG).show();
					m_QQClient.setNullCallBackHandler(m_Handler);
					startActivity(new Intent(VerifyCodeActivity.this, LoginActivity.class));
					finish();
				} else if (msg.arg1 == QQLoginResultCode.PASSWORD_ERROR) {	// 密码错误
					Toast.makeText(getBaseContext(),
							R.string.id_or_pwd_err, Toast.LENGTH_LONG).show();
					m_QQClient.setNullCallBackHandler(m_Handler);
					startActivity(new Intent(VerifyCodeActivity.this, LoginActivity.class));
					finish();
				} else if (msg.arg1 == QQLoginResultCode.NEED_VERIFY_CODE) {	// 需要输入验证码
					byte[] bytData = m_QQClient.getVerifyCodePic();
					Bitmap bmp = BitmapFactory.decodeByteArray(bytData, 0, bytData.length);
					m_imgVC.setImageBitmap(bmp);
				} else if (msg.arg1 == QQLoginResultCode.VERIFY_CODE_ERROR) {	// 验证码错误
					Toast.makeText(getBaseContext(),
							R.string.vc_err, Toast.LENGTH_LONG).show();
                    m_edtVC.setText("");
					byte[] bytData = m_QQClient.getVerifyCodePic();
					Bitmap bmp = BitmapFactory.decodeByteArray(bytData, 0, bytData.length);
					m_imgVC.setImageBitmap(bmp);
				}

			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_verifycode);
	}

    @Override
    public void setUpViews() {
        ViewCompat.setElevation(mToolbar, getResources().getDimension(R.dimen.toolbar_elevation));
        sp = getSharedPreferences("theme", MODE_PRIVATE);
        color_theme = sp.getInt("color", -12627531);

		m_QQClient = AppData.getAppData().getQQClient();
		m_QQClient.setCallBackHandler(m_Handler);

	//	m_txtCancel = (TextView)findViewById(R.id.vc_txtCancel);
	//	m_btnFinish = (Button)findViewById(R.id.vc_btnFinish);
		m_imgVC = (ImageView)findViewById(R.id.vc_imgVC);
		m_prgLogining = (CircularProgress)findViewById(R.id.vc_prgLogining);
		m_edtVC = (FloatingEditText)findViewById(R.id.vc_edtVC);

        m_edtVC.setNormalColor(color_theme);
        m_edtVC.setHighlightedColor(color_theme);
        m_prgLogining.setColor(color_theme);

	//	m_txtCancel.setOnClickListener(this);
	//	m_btnFinish.setOnClickListener(this);
	//	m_edtVC.addTextChangedListener(this);

		byte[] bytData = m_QQClient.getVerifyCodePic();
		Bitmap bmp = BitmapFactory.decodeByteArray(bytData, 0, bytData.length);
		m_imgVC.setImageBitmap(bmp);

        mToolbar.setNavigationIcon(R.drawable.qqicon);

        mToolbar.inflateMenu(R.menu.menu_ok);

        setSupportActionBar(mToolbar);
        mToolbar.setOnMenuItemClickListener(onMenuItemClick);
        mToolbar.setNavigationOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                m_QQClient.setCallBackHandler(null);
                startActivity(new Intent(VerifyCodeActivity.this, LoginActivity.class));
                finish();
            }
		});
		// Navigation Icon 要設定在 setSupoortActionBar 才有作用
		// 否則會出現 back button
	}

    private Toolbar.OnMenuItemClickListener onMenuItemClick = new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            switch (menuItem.getItemId()) {

                case R.id.ok:
                    String strVC = m_edtVC.getText().toString();
                    if (strVC.length() < 4)
                        return false;
                    m_prgLogining.setVisibility(View.VISIBLE);
                    m_QQClient.setVerifyCode(strVC);
                    m_QQClient.login();
                    break;

            }
            return true;
        }
    };
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_ok, menu);
        return true;
    }

}


text:
@implementation AMPerson

static id _person;
+ (instancetype)sharePerson
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _person = [[super alloc] init];
    });
    return _person;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _person = [super allocWithZone:zone];
    });
    return _person;
}

- (id)copy
{
    return _person;
}

@end


text:
package myproject.homepage;

import base.BaseScenario;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

import static org.junit.Assert.assertTrue;

public class GoogleSearchScenario extends BaseScenario {

  // You can add custom action code for specific page

}


text:
package com.chrisdempewolf.pinterest.methods.board;

import org.junit.Test;

import java.net.URI;
import java.net.URISyntaxException;

import static org.junit.Assert.assertEquals;

public class BoardEndPointURIBuilderTest {
    private static final String ACCESS_TOKEN = "testaccesstoken123";
    private static final String FIELDS = "myFields";
    private static final String BOARD_NAME = "jsmith/myBoard";

    @Test
    public void testBuildBoardUri() throws URISyntaxException {
        final URI actualURI = BoardEndPointURIBuilder.buildBoardURI(ACCESS_TOKEN, BOARD_NAME, FIELDS);
        final URI expectedURI = new  URI("https://api.pinterest.com/v1/boards/" + BOARD_NAME + "/?access_token=" + ACCESS_TOKEN + "&fields=" + FIELDS);
        assertEquals(expectedURI, actualURI);
    }

    @Test
    public void testBuildMyBoardUri() throws URISyntaxException {
        final URI actualURI = BoardEndPointURIBuilder.buildMyBoardURI(ACCESS_TOKEN, FIELDS);
        final URI expectedURI = new  URI("https://api.pinterest.com/v1/me/boards/?access_token=" + ACCESS_TOKEN + "&fields=" + FIELDS);
        assertEquals(expectedURI, actualURI);
    }
}


text:
"""Kraken - objects.transform module.

Classes:
Transform -- Transform representation.

"""

from kraken.core.objects.object_3d import Object3D

class Transform(Object3D):
    """Transform object."""

    def __init__(self, name, parent=None, flags=None):
        super(Transform, self).__init__(name, parent=parent, flags=flags)


text:
Todo
# Event Delegation ??
  - Basic ... need to pass in eventType :P (needs a wrapper***) (no wrapper needed)
   - Tracking handlers! - done
   - Lastly - need to start individual module!
   # Support vdom view layer
   # Support extensions

## Need get x-config - done
## Still need life cycle - done

   # Stop a module - removed ref - ok
  # Stop module - remove handlers!
# Start module? already started or START
--Done
#### FINISH simplify stack state
# rename Global config ##
## Process common JS modules too - done
## fixed moduleRefs stack

  Event delegation adapter - done
  Streams? Pass in elem type?
  Actions - unique??
# Get global adapter - done
#expose unique ID utility
# Get Module config as store? or just object?
  or data-config
  # More error handling?
  # Fire outside events?
  # destroy module should release event handlers, call passed in cb & call context.destroy
# do not use class system

/*

  Needs Plugin system - requires conventions be followed returns chainable
  Services -
    Public - done
    require done
    Singleton done
  Needs States - done
  Needs stacks - done
  Needs Modules - done
  Modules - run init! - done
  Use fetch ponyfill;
    Module should return init within a closure??
                    Module context should be able to request plugin or submodule
  Needs config - done
  Needs data-* - done
  Has Mini Pub Sub - done
  Allows Views (how does data flow?)
  Allows Streams
  Allows delegation
  Enable custom build
  Allows composition (rambda?)

  todo:
    short hand query All

  What about?
    XHR - fetch

*/
* Init services first
* Add micro pub sub
  import mitt from 'mitt'

  let emitter = mitt()
  -- Behavior
  -- Get global
  -- Error emitter
  -- Views??
  -- Fetch??
  Redo store - using ramda -> models? -> views
  Add - onmessage -> listen to all messages? - ok on CTX and app inc.alias
  Store - get? - ok
  Global State? - ok
  Logging - ok
  Context Base
    -add App methods - ok getService, asSubModule
  Convenience addModule, addService - OK
  Stacks - - working
    services singleton - ok
                                              Dependencies <<-major
      Global API - ok
      Application Services (Pub Sub) - ok
    Module Init per instance - ok
      Dependencies
      No API
      Local State - Redux?
      Context > Element @ Init
        this.Element
        this.subscribe / on ?
        this.publish  / off ?
        this.store ?
          this.store.set
          this.store.get ??
          Context - > composed?
      Application Services (pub Sub)
    Behaviors - N/A
    Plug Ins - Jquery Init?

  Pubsub - OK
  ./scripts/build -- src/compose.js src/curry.js src/chain.js src/pipe.js src/when.js src/lens.js src/set.js > dist/ramda.custom2.js
  File Size?
  Views
  XXX- Routing??
  AJAX


text:
using System;
using System.Collections.Generic;
using MagentoSync.Models.EndlessAisle.ProductLibrary;

namespace MagentoSync.Models.EndlessAisle.ClassificationTree
{
    [Serializable]
    public class ClassificationTreeResourceSummary
    {
        public ClassificationTreeResourceSummary()
        {
            Classifications = new List<ClassificationResource>();
            Categories = new List<ClassificationCategoryResource>();
        }

        public int Id { get; set; }
        public string Name { get; set; }
        public bool IsCanonical { get; set; }
        public string Description { get; set; }
        public EntityRefResource Owner { get; set; }

        public int Version { get; set; }
        public DateTime? LastModifiedUtc { get; set; }

        public List<ClassificationResource> Classifications { get; set; }
        public List<ClassificationCategoryResource> Categories { get; set; }
    }
}


text:
layout: page
title: Logan - Hartman Wedding
date: 2016-05-24
author: Patrick Park
tags: weekly links, java
status: published
summary: Sed non lacus non dui scelerisque posuere.
banner: images/banner/office-01.jpg
booking:
  startDate: 07/24/2016
  endDate: 07/27/2016
  ctyhocn: SUXOCHX
  groupCode: LHW
published: true
---
Pellentesque quam lorem, facilisis at congue ut, condimentum in libero. Praesent eget nibh ac augue luctus dapibus eu non massa. Nunc ut quam neque. Morbi fringilla risus nec massa tempor ornare. Mauris congue ullamcorper fermentum. Sed vulputate ornare odio et tincidunt. Maecenas vitae tellus vel urna sollicitudin rhoncus ut quis neque. Suspendisse finibus lacinia quam, id venenatis est venenatis et. Duis ultricies urna nec orci venenatis, sed pulvinar odio bibendum.

* Suspendisse non sapien id justo semper elementum
* Vivamus a magna vitae justo blandit eleifend ac vitae diam
* Nunc pretium diam in volutpat ornare
* Sed a mauris quis urna elementum feugiat
* Duis ut nunc ultricies, euismod mi eu, finibus lectus.

Aliquam vulputate ullamcorper tortor, quis aliquam lectus ultrices vel. Aenean arcu ligula, blandit sed nibh in, efficitur lobortis odio. Aenean quis ante ut diam condimentum vehicula eu eget enim. Suspendisse potenti. Aliquam vehicula felis in justo semper, eu interdum erat laoreet. Integer nec dictum nunc, nec pellentesque metus. Duis non condimentum ipsum, vitae ullamcorper orci. Sed congue nunc in lacus volutpat pulvinar. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nulla elementum ac nibh facilisis suscipit. Donec rutrum, diam ac mattis commodo, nibh nisi sollicitudin arcu, in posuere ipsum odio sit amet turpis. Sed sed arcu id massa elementum accumsan a vel diam. Nullam feugiat tellus congue dapibus auctor.


text: CREATE INDEX adus_type_idx ON addons (average_daily_users, addontype_id);


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.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.containeranalysis.v1alpha1.model;

/**
 * This represents how a particular software package may be installed on a system.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Container Analysis API. For a detailed explanation
 * see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class Installation extends com.google.api.client.json.GenericJson {

  /**
   * All of the places within the filesystem versions of this package have been found.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<Location> location;

  /**
   * Output only. The name of the installed package.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String name;

  /**
   * All of the places within the filesystem versions of this package have been found.
   * @return value or {@code null} for none
   */
  public java.util.List<Location> getLocation() {
    return location;
  }

  /**
   * All of the places within the filesystem versions of this package have been found.
   * @param location location or {@code null} for none
   */
  public Installation setLocation(java.util.List<Location> location) {
    this.location = location;
    return this;
  }

  /**
   * Output only. The name of the installed package.
   * @return value or {@code null} for none
   */
  public java.lang.String getName() {
    return name;
  }

  /**
   * Output only. The name of the installed package.
   * @param name name or {@code null} for none
   */
  public Installation setName(java.lang.String name) {
    this.name = name;
    return this;
  }

  @Override
  public Installation set(String fieldName, Object value) {
    return (Installation) super.set(fieldName, value);
  }

  @Override
  public Installation clone() {
    return (Installation) super.clone();
  }

}


text:
namespace content {

// Factory of net::ServerSocket. This is to separate instantiating dev tools
// and instantiating server sockets.
// All methods including destructor are called on a separate thread
// different from any BrowserThread instance.
class DevToolsSocketFactory {
 public:
  virtual ~DevToolsSocketFactory() {}

  // Returns a new instance of ServerSocket or nullptr if an error occurred.
  virtual std::unique_ptr<net::ServerSocket> CreateForHttpServer() = 0;

  // Creates a named socket for reversed tethering implementation (used with
  // remote debugging, primarily for mobile).
  virtual std::unique_ptr<net::ServerSocket> CreateForTethering(
      std::string* out_name) = 0;
  };

}  // namespace content

#endif  // CONTENT_PUBLIC_BROWSER_DEVTOOLS_SOCKET_FACTORY_H_


text:
<?php namespace Davispeixoto\ForceDotComToolkitForPhp;

class PackageVersionHeader
{
    /**
     * @var array $packageVersions
     */
    public $packageVersions;

    /**
     * Class constructor.
     *
     * @param array $packageVersions
     * @return void
     */
    public function __construct($packageVersions)
    {
        $this->packageVersions = $packageVersions;
    }
}

?>


text:
// Template Source: BaseEntity.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All Rights Reserved.  Licensed under the MIT License.  See License in the project root for license information.
// ------------------------------------------------------------------------------

package com.microsoft.graph.models;
import com.microsoft.graph.serializer.ISerializer;
import com.microsoft.graph.serializer.IJsonBackedObject;
import com.microsoft.graph.serializer.AdditionalDataManager;
import java.util.EnumSet;

import com.google.gson.JsonObject;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;

// **NOTE** This file was generated by a tool and any changes will be overwritten.

/**
 * The class for the Employee Org Data.
 */
public class EmployeeOrgData implements IJsonBackedObject {

    /** the OData type of the object as returned by the service */
    @SerializedName("@odata.type")
    @Expose
    @Nullable
    public String oDataType;

    private transient AdditionalDataManager additionalDataManager = new AdditionalDataManager(this);

    @Override
    @Nonnull
    public final AdditionalDataManager additionalDataManager() {
        return additionalDataManager;
    }

    /**
     * The Cost Center.
     * The cost center associated with the user. Returned only on $select. Supports $filter.
     */
    @SerializedName(value = "costCenter", alternate = {"CostCenter"})
    @Expose
	@Nullable
    public String costCenter;

    /**
     * The Division.
     * The name of the division in which the user works. Returned only on $select. Supports $filter.
     */
    @SerializedName(value = "division", alternate = {"Division"})
    @Expose
	@Nullable
    public String division;

    /**
     * Sets the raw JSON object
     *
     * @param serializer the serializer
     * @param json the JSON object to set this object to
     */
    public void setRawObject(@Nonnull final ISerializer serializer, @Nonnull final JsonObject json) {

    }
}


text:
<?php
// shortcode handler for [bandcamp], which inserts a bandcamp.com
// music player (iframe, html5)
//
// [bandcamp album=119385304]
// [bandcamp album=3462839126  bgcol=FFFFFF linkcol=4285BB size=venti]
// [bandcamp track=2446959313]
//
function shortcode_handler_bandcamp( $atts ) {
	// there are no default values, but specify here anyway
	// to explicitly list supported atts
	$attributes = shortcode_atts( array(
		'album'       => null,     // integer album id
		'track'       => null,     // integer track id
		'video'       => null,     // integer track id for video player
		'size'        => 'venti',  // one of the supported sizes
		'bgcol'       => 'FFFFFF', // hex, no '#' prefix
		'linkcol'     => null,     // hex, no '#' prefix
		'layout'      => null,     // encoded layout url
		'width'       => null,     // integer with optional "%"
		'height'      => null,     // integer with optional "%"
		'notracklist' => null,     // may be string "true" (defaults false)
		'tracklist'   => null,     // may be string "false" (defaults true)
		'artwork'     => null,     // may be string "false" (alternately: "none") or "small" (default is large)
		'minimal'     => null,     // may be string "true" (defaults false)
		'theme'       => null,     // may be theme identifier string ("light"|"dark" so far)
		'package'     => null,     // integer package id
		't'           => null,     // integer track number
		'tracks'      => null,     // comma separated list of allowed tracks
		'esig'        => null      // hex, no '#' prefix
	), $atts, 'bandcamp' );

	$sizes = array(
		'venti'      => array( 'width' => 400, 'height' => 100 ),
		'grande'     => array( 'width' => 300, 'height' => 100 ),
		'grande2'    => array( 'width' => 300, 'height' => 355 ),
		'grande3'    => array( 'width' => 300, 'height' => 415 ),
		'tall_album' => array( 'width' => 150, 'height' => 295 ),
		'tall_track' => array( 'width' => 150, 'height' => 270 ),
		'tall2'      => array( 'width' => 150, 'height' => 450 ),
		'short'      => array( 'width' => 46, 'height' => 23 ),
		'large'      => array( 'width' => 350, 'height' => 470 ),
		'medium'     => array( 'width' => 450, 'height' => 120 ),
		'small'      => array( 'width' => 350, 'height' => 42 )
	);

	$sizekey = $attributes['size'];
	$height  = null;
	$width   = null;

	$isVideo = false;

	// Build iframe url.  For audio players, args are appended as
	// extra path segments for historical reasons having to
	// do with an IE-only flash bug which required this URL
	// to contain no querystring.  Delay the actual joining
	// of args into a string until after we decide if it's
	// a video player or an audio player
	$argparts = array();

	if ( ! isset( $attributes['album'] ) && ! isset( $attributes['track'] ) && ! isset( $attributes['video'] ) ) {
		return "[bandcamp: shortcode must include 'track', 'album', or 'video' param]";
	}

	if ( isset( $attributes['track'] ) && is_numeric( $attributes['track'] ) ) {
		$track = esc_attr( $attributes['track'] );
		array_push( $argparts, "track={$track}" );
	} elseif ( isset( $attributes['video'] ) && is_numeric( $attributes['video'] ) ) {
		$track = esc_attr( $attributes['video'] ); // videos are referenced by track id
		$urlbase = "//bandcamp.com/EmbeddedPlayer/v=2";
		$isVideo = true;
		array_push( $argparts, "track={$track}" );
	}
	if ( isset( $attributes['album'] ) && is_numeric( $attributes['album'] ) ) {
		$album = esc_attr( $attributes['album'] );
		array_push( $argparts, "album={$album}" );
	}

	if ( $sizekey == 'tall' ) {
		if ( isset( $attributes['album'] ) ) {
			$sizekey .= '_album';
		} else {
			$sizekey .= '_track';
		}
	}

	// if size specified that we don't recognize, fall back on venti
	if ( empty( $sizes[ $sizekey ] ) ) {
		$sizekey            = 'venti';
		$attributes['size'] = 'venti';
	}

	// use strict regex for digits + optional % instead of absint for height/width
	// 'width' and 'height' params in the iframe url get the exact string from the shortcode
	// args, whereas the inline style attribute must have "px" added to it if it has no "%"
	if ( isset( $attributes['width'] ) && preg_match( "|^([0-9]+)(%)?$|", $attributes['width'], $matches ) ) {
		$width = $csswidth = $attributes['width'];
		if ( sizeof( $matches ) < 3 ) {
			$csswidth .= "px";
		}
	}
	if ( isset( $attributes['height'] ) && preg_match( "|^([0-9]+)(%)?$|", $attributes['height'], $matches ) ) {
		$height = $cssheight = $attributes['height'];
		if ( sizeof( $matches ) < 3 ) {
			$cssheight .= "px";
		}
	}

	if ( ! $height ) {
		$height    = $sizes[ $sizekey ]['height'];
		$cssheight = $height . "px";
	}

	if ( ! $width ) {
		$width    = $sizes[ $sizekey ]['width'];
		$csswidth = $width . "px";
	}

	if ( isset( $attributes['layout'] ) ) {
		array_push( $argparts, "layout={$attributes['layout']}" );
	} elseif ( isset( $attributes['size'] ) && preg_match( "|^[a-zA-Z0-9]+$|", $attributes['size'] ) ) {
		array_push( $argparts, "size={$attributes['size']}" );
	}

	if ( isset( $attributes['bgcol'] ) && preg_match( "|^[0-9A-Fa-f]+$|", $attributes['bgcol'] ) ) {
		array_push( $argparts, "bgcol={$attributes['bgcol']}" );
	}

	if ( isset( $attributes['linkcol'] ) && preg_match( "|^[0-9A-Fa-f]+$|", $attributes['linkcol'] ) ) {
		array_push( $argparts, "linkcol={$attributes['linkcol']}" );
	}

	if ( isset( $attributes['package'] ) && preg_match( "|^[0-9]+$|", $attributes['package'] ) ) {
		array_push( $argparts, "package={$attributes['package']}" );
	}

	if ( isset( $attributes['t'] ) && preg_match( "|^[0-9]+$|", $attributes['t'] ) ) {
		array_push( $argparts, "t={$attributes['t']}" );
	}

	if ( $attributes['notracklist'] == "true" ) {
		array_push( $argparts, "notracklist=true" );
	}

	// 'tracklist' arg deprecates 'notracklist=true' to be less weird.  note, behavior
	// if both are specified is undefined
	switch ( $attributes['tracklist'] ) {
		case "false":
		case "none":
			array_push( $argparts, "tracklist=false" );
			break;
	}

	switch ( $attributes['artwork'] ) {
		case "false":
		case "none":
		case "small":
			array_push( $argparts, "artwork=" . $attributes['artwork'] );
			break;
	}

	if ( $attributes['minimal'] == "true" ) {
		array_push( $argparts, "minimal=true" );
	}

	if ( isset( $attributes['theme'] ) && preg_match( "|^[a-zA-Z_]+$|", $attributes['theme'] ) ) {
		array_push( $argparts, "theme={$attributes['theme']}" );
	}

	// param 'tracks' is signed digest param 'esig'
	if ( isset( $attributes['tracks'] ) && preg_match( "|^[0-9\,]+$|", $attributes['tracks'] ) ) {
		if ( isset( $attributes['esig'] ) && preg_match( "|^[0-9A-Fa-f]+$|", $attributes['esig'] ) ) {
			array_push( $argparts, "tracks={$attributes['tracks']}" );
			array_push( $argparts, "esig={$attributes['esig']}" );
		}
	}

	if ( $isVideo ) {
		$url        = "//bandcamp.com/VideoEmbed?" . join( '&', $argparts );
		$extraAttrs = " mozallowfullscreen='1' webkitallowfullscreen='1' allowfullscreen='1'";
	} else {
		$url        = "//bandcamp.com/EmbeddedPlayer/v=2/" . join( '/', $argparts ) . '/';
		$extraAttrs = '';
	}

	return "<iframe width='" . esc_attr( $width ) . "' height='" . esc_attr( $height ) . "' style='position: relative; display: block; width: " . esc_attr( $csswidth ) . "; height: " . esc_attr( $cssheight ) . ";' src='" . esc_url( $url ) . "' allowtransparency='true' frameborder='0'" . $extraAttrs . "></iframe>";
}

add_shortcode( 'bandcamp', 'shortcode_handler_bandcamp' );


text:
module Gecode::BoolEnum
  module BoolEnumOperand
    # Produces a BoolOperand that represents the conjunction (AND) of all
    # boolean operands in this enumeration.
    #
    # ==== Examples
    #
    #   # Conjunction of all elements in +bool_enum+.
    #   bool_enum.conjunction
    def conjunction
      Relation::BoolEnumConjunctionOperand.new(@model, self)
    end

    # Produces a BoolOperand that represents the disjunction (OR) of all
    # boolean operands in this enumeration.
    #
    # ==== Examples
    #
    #   # Disjunction of all elements in +bool_enum+.
    #   bool_enum.disjunction
    def disjunction
      Relation::BoolEnumDisjunctionOperand.new(@model, self)
    end
  end

  # A module that gathers the classes and modules used by boolean enumeration
  # relation constraints.
  module Relation #:nodoc:
    class BoolEnumConjunctionOperand < Gecode::Bool::ShortCircuitEqualityOperand #:nodoc:
      def initialize(model, bool_enum)
        super model
        @enum = bool_enum
      end

      def constrain_equal(bool_operand, constrain_domain, propagation_options)
        Gecode::Raw::rel(@model.active_space, Gecode::Raw::BOT_AND,
          @enum.to_bool_enum.bind_array, bool_operand.to_bool_var.bind,
          *propagation_options)
      end
    end

    class BoolEnumDisjunctionOperand < Gecode::Bool::ShortCircuitEqualityOperand #:nodoc:
      def initialize(model, bool_enum)
        super model
        @enum = bool_enum
      end

      def constrain_equal(bool_operand, constrain_domain, propagation_options)
        Gecode::Raw::rel(@model.active_space, Gecode::Raw::BOT_OR,
          @enum.to_bool_enum.bind_array, bool_operand.to_bool_var.bind,
          *propagation_options)
      end
    end
  end
end


text:
require "#{File.dirname( __FILE__ )}/../spec_helper"

describe GuidesController, "show" do
  describe "published guide" do
    let( :g ) { make_published_guide }
    it "should be visible to signed out visitors" do
      get :show, params: { id: g.id }
      expect( response ).to be_successful
    end
  end
  describe "draft guide" do
    let( :g ) { Guide.make! }
    before do
      expect( g ).not_to be_published
    end
    it "should not be viewable by signed out visitors" do
      get :show, params: { id: g.id }
      expect( response ).to be_not_found
    end
    it "should not be viewable by any signed in visitor" do
      sign_in User.make!
      get :show, params: { id: g.id }
      expect( response ).to be_not_found
    end
    it "should be viewable by guide editor if the guide is a draft" do
      gu = GuideUser.make!( guide: g )
      sign_in gu.user
      get :show, params: { id: g.id }
      expect( response ).to be_successful
    end
  end
end

describe GuidesController, "index" do
  it "should filter by place" do
    p1 = make_place_with_geom
    p2 = make_place_with_geom
    g = make_published_guide( place: p1 )
    get :index, params: { place_id: p1.id }
    expect( assigns( :guides ) ).to include g
    get :index, params: { place_id: p2.id }
    expect( assigns( :guides ) ).not_to include g
  end
end

describe GuidesController, "update" do
  let( :user ) { User.make! }
  let( :guide ) { make_published_guide( user: user ) }
  before do
    sign_in user
  end
  it "should publish the guide based on the publish param" do
    guide.update_attribute( :published_at, nil )
    expect( guide ).not_to be_published
    patch :update, params: { id: guide.id, publish: true }
    guide.reload
    expect( guide ).to be_published
  end
  it "should unpublish the guide" do
    expect( guide ).to be_published
    patch :update, params: { id: guide.id, unpublish: true }
    guide.reload
    expect( guide ).not_to be_published
  end
  it "should change the title" do
    patch :update, params: { id: guide.id, guide: { title: "this is a new title" } }
    guide.reload
    expect( guide.title ).to eq "this is a new title"
  end
  it "should allow assignment of nested guide users" do
    u = User.make!
    patch :update, params: { id: guide.id, guide: { guide_users_attributes: { "0": { user_id: u.id } } } }
    guide.reload
    expect( guide.guide_users.size ).to eq 2
  end
end

describe GuidesController, "import_taxa" do
  describe "from names" do
    before do
      @guide = Guide.make!
      sign_in @guide.user
    end
    it "should add guide taxa" do
      taxa = 3.times.map { Taxon.make! }
      expect( @guide.guide_taxa ).to be_blank
      post :import_taxa, params: { id: @guide, names: taxa.map( &:name ).join( "\n" ), format: :json }
      @guide.reload
      expect( @guide.guide_taxa.count ).to eq 3
    end
  end
end

describe GuidesController, "import_tags_from_csv" do
  let( :guide ) { make_published_guide }
  let( :taxon_names ) { guide.guide_taxa.sort_by( &:name ).map( &:name ) }
  let( :work_path ) { File.join( Dir.tmpdir, "import_tags_from_csv-#{Time.now.to_i}.csv" ) }
  before do
    sign_in guide.user
  end

  it "should add plain tags when no predicate listed" do
    CSV.open( work_path, "w" ) do | csv |
      csv << ["name"]
      csv << [taxon_names[0], "shifty"]
      csv << [taxon_names[1], "forthright"]
      csv << [taxon_names[2], ""]
      csv
    end
    put :import_tags_from_csv, params: { id: guide.id, file: work_path }
    guide.guide_taxa.reload
    guide_taxa = guide.guide_taxa.sort_by( &:name )
    expect( guide_taxa[0].tag_list ).to include "shifty"
    expect( guide_taxa[1].tag_list ).to include "forthright"
  end

  it "should add tags with predicates" do
    CSV.open( work_path, "w" ) do | csv |
      csv << ["name",         "color", "size"]
      csv << [taxon_names[0], "red",   "big"]
      csv << [taxon_names[1], "green", "small"]
      csv << [taxon_names[2], "blue",  "small"]
      csv
    end
    put :import_tags_from_csv, params: { id: guide.id, file: work_path }
    guide.guide_taxa.reload
    guide_taxa = guide.guide_taxa.sort_by( &:name )
    expect( guide_taxa.first.tag_list ).to include "color=red"
    expect( guide_taxa.last.tag_list ).to include "color=blue"
    expect( guide_taxa.first.tag_list ).to include "size=big"
  end

  it "should add tags with namespaces and predicates" do
    CSV.open( work_path, "w" ) do | csv |
      csv << ["name",         "taxonomy:family"]
      csv << [taxon_names[0], "Ranidae"]
      csv << [taxon_names[1], "Lycaenidae"]
      csv << [taxon_names[2], "Pompilidae"]
      csv
    end
    put :import_tags_from_csv, params: { id: guide.id, file: work_path }
    guide.guide_taxa.reload
    guide_taxa = guide.guide_taxa.sort_by( &:name )
    expect( guide_taxa[0].tag_list ).to include "taxonomy:family=Ranidae"
    expect( guide_taxa[1].tag_list ).to include "taxonomy:family=Lycaenidae"
    expect( guide_taxa[2].tag_list ).to include "taxonomy:family=Pompilidae"
  end

  it "should add multiple tags per cell separated by pipes" do
    CSV.open( work_path, "w" ) do | csv |
      csv << ["name",         "color"]
      csv << [taxon_names[0], "red|green",   "big"]
      csv << [taxon_names[1], "green", "small"]
      csv << [taxon_names[2], "blue",  "small|medium"]
      csv
    end
    put :import_tags_from_csv, params: { id: guide.id, file: work_path }
    guide.guide_taxa.reload
    guide_taxa = guide.guide_taxa.sort_by( &:name )
    expect( guide_taxa.first.tag_list ).to include "color=red"
    expect( guide_taxa.first.tag_list ).to include "color=green"
    expect( guide_taxa.last.tag_list ).to include "small"
    expect( guide_taxa.last.tag_list ).to include "medium"
  end

  it "should not add tags for blanks" do
    CSV.open( work_path, "w" ) do | csv |
      csv << ["name",         "color"]
      csv << [taxon_names[0], ""]
      csv << [taxon_names[1], "green"]
      csv << [taxon_names[2], "blue"]
      csv
    end
    put :import_tags_from_csv, params: { id: guide.id, file: work_path }
    guide.guide_taxa.reload
    guide_taxa = guide.guide_taxa.sort_by( &:name )
    expect( guide_taxa.first.tag_list ).to be_blank
    expect( guide_taxa.last.tag_list ).to include "color=blue"
  end

  it "should leave existing tags intact" do
    gt = guide.guide_taxa.sort_by( &:name ).first
    gt.update( tag_list: %w(foo bar) )
    CSV.open( work_path, "w" ) do | csv |
      csv << ["name"]
      csv << [taxon_names[0], "shifty"]
      csv << [taxon_names[1], "forthright"]
      csv << [taxon_names[2], ""]
      csv
    end
    put :import_tags_from_csv, params: { id: guide.id, file: work_path }
    guide.guide_taxa.reload
    guide.guide_taxa.sort_by( &:name )
    gt.reload
    expect( gt.tag_list ).to include "shifty"
    expect( gt.tag_list ).to include "foo"
    expect( gt.tag_list ).to include "bar"
  end

  it "should fail gracefully without a file" do
    put :import_tags_from_csv, params: { id: guide.id }
    expect( response ).not_to be_server_error
  end
end

describe GuidesController, "import_tags_from_csv_template" do
  let( :guide ) { make_published_guide }
  before do
    sign_in guide.user
  end
  it "should include columns for predicates of all tags in the guide" do
    guide.guide_taxa.each do | gt |
      gt.update( tag_list: "size=small,color=red" )
    end
    get :import_tags_from_csv_template, format: :csv, params: { id: guide.id }
    csv = CSV.parse( response.body, headers: true )
    expect( csv.headers ).to include "size"
    expect( csv.headers ).to include "color"
  end
  it "should include rows for all taxa in the guide" do
    get :import_tags_from_csv_template, format: :csv, params: { id: guide.id }
    names = []
    CSV.parse( response.body, headers: true ).each do | row |
      names << row[0]
    end
    guide.guide_taxa.each do | gt |
      expect( names ).to include gt.name
    end
  end
end


text:
void joedb::dump(const Readable &db, Writable &writable, bool schema_only)
/////////////////////////////////////////////////////////////////////////////
{
 //
 // Dump tables
 //
 std::map<Table_Id, Table_Id> table_map;
 {
  Table_Id table_id = 0;
  for (auto table: db.get_tables())
  {
   ++table_id;
   table_map[table.first] = table_id;

   writable.create_table(table.second);
  }
 }

 //
 // Dump fields
 //
 std::map<Table_Id, std::map<Field_Id, Field_Id>> field_maps;
 {
  Table_Id table_id = 0;
  for (auto table: db.get_tables())
  {
   ++table_id;
   Field_Id field_id = 0;
   for (const auto &field: db.get_fields(table.first))
   {
    ++field_id;
    Type type = db.get_field_type(table.first, field.first);
    if (type.get_type_id() == Type::Type_Id::reference)
     type = Type::reference(table_map[type.get_table_id()]);
    field_maps[table.first][field.first] = field_id;

    writable.add_field(table_map[table.first], field.second, type);
   }
  }
 }

 //
 // Dump records
 //
 if (schema_only)
  return;

 for (auto table: db.get_tables())
 {
  const Table_Id table_id = table.first;
  const Record_Id last_record_id = db.get_last_record_id(table_id);

  for (Record_Id record_id = 1; record_id <= last_record_id;)
  {
   while (record_id <= last_record_id &&
          !db.is_used(table_id, record_id))
    record_id++;

   Record_Id size = 0;

   while (record_id + size <= last_record_id &&
          db.is_used(table_id, record_id + size))
    size++;

   if (size)
   {
    writable.insert_vector(table_map[table_id], record_id, size);
    record_id += size;
   }
  }

  for (const auto &field: db.get_fields(table_id))
  {
   const Field_Id field_id = field.first;

   for (Record_Id record_id = 1; record_id <= last_record_id; record_id++)
    if (db.is_used(table_id, record_id))
    {
     switch (db.get_field_type(table_id, field_id).get_type_id())
     {
      case Type::Type_Id::null:
      break;

      #define TYPE_MACRO(type, return_type, type_id, R, W)\
      case Type::Type_Id::type_id:\
       writable.update_##type_id(table_map[table_id], record_id, field_maps[table_id][field_id], db.get_##type_id(table_id, record_id, field_id));\
      break;
      #include "joedb/TYPE_MACRO.h"
     }
    }
  }
 }
}

/////////////////////////////////////////////////////////////////////////////
void joedb::dump_data(const Readable &db, Writable &writable)
/////////////////////////////////////////////////////////////////////////////
{
 for (auto table: db.get_tables())
 {
  const Table_Id table_id = table.first;
  const Record_Id last_record_id = db.get_last_record_id(table_id);

  Record_Id record_id = 1;

  const Compact_Freedom_Keeper &freedom_keeper = db.get_freedom(table_id);

  while (record_id <= last_record_id)
  {
   while
   (
    record_id <= last_record_id &&
    !freedom_keeper.is_used(record_id + 1)
   )
    record_id++;

   Record_Id size = 0;

   while
   (
    record_id + size <= last_record_id &&
    freedom_keeper.is_used(record_id + size + 1)
   )
    size++;

   if (size)
   {
    writable.insert_vector(table_id, record_id, size);

    for (const auto &field: db.get_fields(table_id))
    {
     const Field_Id field_id = field.first;

     switch(db.get_field_type(table_id, field_id).get_type_id())
     {
      case Type::Type_Id::null:
      break;

      #define TYPE_MACRO(type, return_type, type_id, R, W)\
      case Type::Type_Id::type_id:\
      {\
       writable.update_vector_##type_id\
       (\
        table_id,\
        record_id,\
        field_id,\
        size,\
        &db.get_##type_id##_storage\
        (\
         table_id,\
         record_id,\
         field_id\
        )\
       );\
      }\
      break;
      #include "joedb/TYPE_MACRO.h"
     }
    }

    record_id += size;
   }
  }
 }
 writable.checkpoint(Commit_Level::no_commit);
}

/////////////////////////////////////////////////////////////////////////////
void joedb::pack(Readonly_Journal &input_journal, Writable &writable)
/////////////////////////////////////////////////////////////////////////////
{
 Database db;

 Selective_Writable schema_filter(writable, Selective_Writable::Mode::schema);
 Multiplexer multiplexer{db, schema_filter};

 input_journal.replay_log(multiplexer);

 dump_data(db, writable);
}


text:
using System.Collections.Generic;

namespace KBrimble.Dota2.Client.Responses.ResponseWrappers
{
    internal class LiveListingResponseWrapper
    {
        public List<LiveLeagueGameResponse> Games { get; set; }
    }
}


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/**
* @name: S15.5.4.4_A3;
* @section: 15.5.4.4;
* @assertion: When String.prototype.charAt(pos) calls if ToInteger(pos) not less than ToString(this value) the empty string returns;
* @description: pos is bigger of string length;
*/

var __instance = new String("ABC");

//////////////////////////////////////////////////////////////////////////////
//CHECK#1
if (__instance.charAt(3) !== "") {
  $ERROR('#1: __instance = new String("ABC"); __instance.charAt(3) === "". Actual: __instance.charAt(3) ==='+__instance.charAt(3) );
}
//
//////////////////////////////////////////////////////////////////////////////


text:
package elastic

import (
	"encoding/json"
	"testing"
)

func TestStatisticalScriptFacet(t *testing.T) {
	f := NewStatisticalScriptFacet().Script("doc['num1'].value + doc['num2'].value")
	data, err := json.Marshal(f.Source())
	if err != nil {
		t.Fatalf("marshaling to JSON failed: %v", err)
	}
	got := string(data)
	expected := `{"statistical":{"script":"doc['num1'].value + doc['num2'].value"}}`
	if got != expected {
		t.Errorf("expected\n%s\n,got:\n%s", expected, got)
	}
}

func TestStatisticalScriptFacetWithGlobals(t *testing.T) {
	f := NewStatisticalScriptFacet().Script("doc['num1'].value + doc['num2'].value").
		Global(true).
		FacetFilter(NewTermFilter("user", "kimchy"))
	data, err := json.Marshal(f.Source())
	if err != nil {
		t.Fatalf("marshaling to JSON failed: %v", err)
	}
	got := string(data)
	expected := `{"facet_filter":{"term":{"user":"kimchy"}},"global":true,"statistical":{"script":"doc['num1'].value + doc['num2'].value"}}`
	if got != expected {
		t.Errorf("expected\n%s\n,got:\n%s", expected, got)
	}
}


text:
package lfsapi

import (
	"bytes"
	"fmt"
	"os/exec"
	"strings"
)

type CredentialHelper interface {
	Fill(Creds) (Creds, error)
	Reject(Creds) error
	Approve(Creds) error
}

type Creds map[string]string

func bufferCreds(c Creds) *bytes.Buffer {
	buf := new(bytes.Buffer)

	for k, v := range c {
		buf.Write([]byte(k))
		buf.Write([]byte("="))
		buf.Write([]byte(v))
		buf.Write([]byte("\n"))
	}

	return buf
}

type commandCredentialHelper struct {
	SkipPrompt bool
}

func (h *commandCredentialHelper) Fill(creds Creds) (Creds, error) {
	return h.exec("fill", creds)
}

func (h *commandCredentialHelper) Reject(creds Creds) error {
	_, err := h.exec("reject", creds)
	return err
}

func (h *commandCredentialHelper) Approve(creds Creds) error {
	_, err := h.exec("approve", creds)
	return err
}

func (h *commandCredentialHelper) exec(subcommand string, input Creds) (Creds, error) {
	output := new(bytes.Buffer)
	cmd := exec.Command("git", "credential", subcommand)
	cmd.Stdin = bufferCreds(input)
	cmd.Stdout = output
	/*
	   There is a reason we don't hook up stderr here:
	   Git's credential cache daemon helper does not close its stderr, so if this
	   process is the process that fires up the daemon, it will wait forever
	   (until the daemon exits, really) trying to read from stderr.

	   See https://github.com/git-lfs/git-lfs/issues/117 for more details.
	*/

	err := cmd.Start()
	if err == nil {
		err = cmd.Wait()
	}

	if _, ok := err.(*exec.ExitError); ok {
		if h.SkipPrompt {
			return nil, fmt.Errorf("Change the GIT_TERMINAL_PROMPT env var to be prompted to enter your credentials for %s://%s.",
				input["protocol"], input["host"])
		}

		// 'git credential' exits with 128 if the helper doesn't fill the username
		// and password values.
		if subcommand == "fill" && err.Error() == "exit status 128" {
			return nil, nil
		}
	}

	if err != nil {
		return nil, fmt.Errorf("'git credential %s' error: %s\n", subcommand, err.Error())
	}

	creds := make(Creds)
	for _, line := range strings.Split(output.String(), "\n") {
		pieces := strings.SplitN(line, "=", 2)
		if len(pieces) < 2 || len(pieces[1]) < 1 {
			continue
		}
		creds[pieces[0]] = pieces[1]
	}

	return creds, nil
}


text:
class EnemyData
{
public:
	std::string skinFileName;
	double life;
	int speed;
	int gold;
	std::vector<Resistance> resistances;
};

class WaveData
{
public:
	std::vector<EnemyData> enemies;
	int spawnRate;
};

enum WaveManagerEvents
{
	Tick = 2,
	FinalWave
};

class WaveManager : public IObservee
{
	std::vector<WaveData> waves;
	Timer timer;
	int spawnRate;
	bool start;
	unsigned int currentWave;
	int next;
	long period;
public:
	WaveManager(void);
	~WaveManager(void);

	void loadFromFile(std::string fileName);
	void setWaveSpawnRate(int rate);
	void update();

	double getTimeToNextWave();

private:
	void resetTimer();

};


text:
{-# LANGUAGE OverloadedStrings, TypeFamilyDependencies #-}

import Control.Lens (at)
import Control.Lens.Operators
import Data.Set (fromList)
import Hyper
import Hyper.Syntax.Scheme
import Lamdu.Calc.Infer
import Lamdu.Calc.Type
import Test.Framework
import Test.Framework.Providers.HUnit (testCase)
import Test.HUnit (assertBool)

alphaEqTest :: Test
alphaEqTest =
    not (alphaEq (f (TVarP "a")) (f (TRecordP REmptyP)))
    & assertBool "should alpha eq"
    & testCase "alpha-eq"
    where
        f x =
            TFunP (TVarP "a") (TVariantP (RExtendP "t" x (RVarP "c"))) ^. hPlain
            & Scheme
                ( Types
                    (QVars (mempty & at "a" ?~ mempty))
                    (QVars (mempty & at "c" ?~ RowConstraints (fromList ["t"]) mempty))
                )
            & Pure

main :: IO ()
main = defaultMain [alphaEqTest]


text:
extern mod glfw;

pub fn initialize() {
	glfw::init()
		.expect("Failed to initialize GLFW.");
}

pub fn deinitialize() {
	glfw::terminate();
}

pub fn create_window() -> glfw::Window {
	let window = glfw::Window::create(640, 480, "Dungeons of Rust", glfw::Windowed)
		.expect("Failed to create window.");
	window.make_context_current();
	return window;
}


text:
<?php
abstract class Kwc_Abstract_Ajax_Component extends Kwc_Abstract
{
    public static function getSettings()
    {
        $ret = parent::getSettings();
        $ret['contentSender'] = 'Kwc_Abstract_Ajax_ContentSender';
        return $ret;
    }
}


text:
package com.twu.biblioteca.model;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class UserTest {

    @Test
    public void shouldReturnTrueForTheCredentialsGiven() {
        User user = new User("000-0000", "!abcd0123", "Lisa", "lisa@gmail.com", "7890678341");

        assertEquals(true, user.verify("000-0000", "!abcd0123"));
    }

    @Test
    public void shouldReturnFalseIfTheCredentialsDoesNotMatch() {
        User user = new User("000-0000", "!abcd0123", "Lisa", "lisa@gmail.com", "7890678341");

        assertEquals(false, user.verify("000-00000", "!abcd0234"));
    }
}


text:
/**
 * ProductBiddingCategoryData.java
 *
 * This file was auto-generated from WSDL
 * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
 */

package com.google.api.ads.adwords.axis.v201601.cm;

/**
 * The taxonomy of ProductBiddingCategory dimension values.
 *
 *
Clients use this to convert between human-readable
 * category names / display strings and
 *             ProductBiddingCategory instances.
 */
public class ProductBiddingCategoryData  extends com.google.api.ads.adwords.axis.v201601.cm.ConstantData  implements java.io.Serializable {
    /* The dimension value that corresponds to this category. */
    private com.google.api.ads.adwords.axis.v201601.cm.ProductBiddingCategory dimensionValue;

    /* The dimension value that corresponds to parent category. */
    private com.google.api.ads.adwords.axis.v201601.cm.ProductBiddingCategory parentDimensionValue;

    /* The country of the taxonomy. It applies to all categories from
     * the taxonomy.
     *                     This field
     * can be selected using the value "Country".This field can be filtered on. */
    private java.lang.String country;

    /* The status of the taxonomy. It applies to all categories from
     * the taxonomy.
     *                     This field
     * can be selected using the value "BiddingCategoryStatus".This field can be filtered on. */
    private com.google.api.ads.adwords.axis.v201601.cm.ShoppingBiddingDimensionStatus status;

    /* A map of displayValues by their language code. The language
     * code is a 2-letter string
     *                     conforming with ISO 639-1 standard. */
    private com.google.api.ads.adwords.axis.v201601.cm.String_StringMapEntry[] displayValue;

    public ProductBiddingCategoryData() {
    }

    public ProductBiddingCategoryData(
           java.lang.String constantDataType,
           com.google.api.ads.adwords.axis.v201601.cm.ProductBiddingCategory dimensionValue,
           com.google.api.ads.adwords.axis.v201601.cm.ProductBiddingCategory parentDimensionValue,
           java.lang.String country,
           com.google.api.ads.adwords.axis.v201601.cm.ShoppingBiddingDimensionStatus status,
           com.google.api.ads.adwords.axis.v201601.cm.String_StringMapEntry[] displayValue) {
        super(
            constantDataType);
        this.dimensionValue = dimensionValue;
        this.parentDimensionValue = parentDimensionValue;
        this.country = country;
        this.status = status;
        this.displayValue = displayValue;
    }

    /**
     * Gets the dimensionValue value for this ProductBiddingCategoryData.
     *
     * @return dimensionValue   * The dimension value that corresponds to this category.
     */
    public com.google.api.ads.adwords.axis.v201601.cm.ProductBiddingCategory getDimensionValue() {
        return dimensionValue;
    }

    /**
     * Sets the dimensionValue value for this ProductBiddingCategoryData.
     *
     * @param dimensionValue   * The dimension value that corresponds to this category.
     */
    public void setDimensionValue(com.google.api.ads.adwords.axis.v201601.cm.ProductBiddingCategory dimensionValue) {
        this.dimensionValue = dimensionValue;
    }

    /**
     * Gets the parentDimensionValue value for this ProductBiddingCategoryData.
     *
     * @return parentDimensionValue   * The dimension value that corresponds to parent category.
     */
    public com.google.api.ads.adwords.axis.v201601.cm.ProductBiddingCategory getParentDimensionValue() {
        return parentDimensionValue;
    }

    /**
     * Sets the parentDimensionValue value for this ProductBiddingCategoryData.
     *
     * @param parentDimensionValue   * The dimension value that corresponds to parent category.
     */
    public void setParentDimensionValue(com.google.api.ads.adwords.axis.v201601.cm.ProductBiddingCategory parentDimensionValue) {
        this.parentDimensionValue = parentDimensionValue;
    }

    /**
     * Gets the country value for this ProductBiddingCategoryData.
     *
     * @return country   * The country of the taxonomy. It applies to all categories from
     * the taxonomy.
     *                     This field
     * can be selected using the value "Country".This field can be filtered on.
     */
    public java.lang.String getCountry() {
        return country;
    }

    /**
     * Sets the country value for this ProductBiddingCategoryData.
     *
     * @param country   * The country of the taxonomy. It applies to all categories from
     * the taxonomy.
     *                     This field
     * can be selected using the value "Country".This field can be filtered on.
     */
    public void setCountry(java.lang.String country) {
        this.country = country;
    }

    /**
     * Gets the status value for this ProductBiddingCategoryData.
     *
     * @return status   * The status of the taxonomy. It applies to all categories from
     * the taxonomy.
     *                     This field
     * can be selected using the value "BiddingCategoryStatus".This field can be filtered on.
     */
    public com.google.api.ads.adwords.axis.v201601.cm.ShoppingBiddingDimensionStatus getStatus() {
        return status;
    }

    /**
     * Sets the status value for this ProductBiddingCategoryData.
     *
     * @param status   * The status of the taxonomy. It applies to all categories from
     * the taxonomy.
     *                     This field
     * can be selected using the value "BiddingCategoryStatus".This field can be filtered on.
     */
    public void setStatus(com.google.api.ads.adwords.axis.v201601.cm.ShoppingBiddingDimensionStatus status) {
        this.status = status;
    }

    /**
     * Gets the displayValue value for this ProductBiddingCategoryData.
     *
     * @return displayValue   * A map of displayValues by their language code. The language
     * code is a 2-letter string
     *                     conforming with ISO 639-1 standard.
     */
    public com.google.api.ads.adwords.axis.v201601.cm.String_StringMapEntry[] getDisplayValue() {
        return displayValue;
    }

    /**
     * Sets the displayValue value for this ProductBiddingCategoryData.
     *
     * @param displayValue   * A map of displayValues by their language code. The language
     * code is a 2-letter string
     *                     conforming with ISO 639-1 standard.
     */
    public void setDisplayValue(com.google.api.ads.adwords.axis.v201601.cm.String_StringMapEntry[] displayValue) {
        this.displayValue = displayValue;
    }

    public com.google.api.ads.adwords.axis.v201601.cm.String_StringMapEntry getDisplayValue(int i) {
        return this.displayValue[i];
    }

    public void setDisplayValue(int i, com.google.api.ads.adwords.axis.v201601.cm.String_StringMapEntry _value) {
        this.displayValue[i] = _value;
    }

    private java.lang.Object __equalsCalc = null;
    public synchronized boolean equals(java.lang.Object obj) {
        if (!(obj instanceof ProductBiddingCategoryData)) return false;
        ProductBiddingCategoryData other = (ProductBiddingCategoryData) obj;
        if (obj == null) return false;
        if (this == obj) return true;
        if (__equalsCalc != null) {
            return (__equalsCalc == obj);
        }
        __equalsCalc = obj;
        boolean _equals;
        _equals = super.equals(obj) &&
            ((this.dimensionValue==null && other.getDimensionValue()==null) ||
             (this.dimensionValue!=null &&
              this.dimensionValue.equals(other.getDimensionValue()))) &&
            ((this.parentDimensionValue==null && other.getParentDimensionValue()==null) ||
             (this.parentDimensionValue!=null &&
              this.parentDimensionValue.equals(other.getParentDimensionValue()))) &&
            ((this.country==null && other.getCountry()==null) ||
             (this.country!=null &&
              this.country.equals(other.getCountry()))) &&
            ((this.status==null && other.getStatus()==null) ||
             (this.status!=null &&
              this.status.equals(other.getStatus()))) &&
            ((this.displayValue==null && other.getDisplayValue()==null) ||
             (this.displayValue!=null &&
              java.util.Arrays.equals(this.displayValue, other.getDisplayValue())));
        __equalsCalc = null;
        return _equals;
    }

    private boolean __hashCodeCalc = false;
    public synchronized int hashCode() {
        if (__hashCodeCalc) {
            return 0;
        }
        __hashCodeCalc = true;
        int _hashCode = super.hashCode();
        if (getDimensionValue() != null) {
            _hashCode += getDimensionValue().hashCode();
        }
        if (getParentDimensionValue() != null) {
            _hashCode += getParentDimensionValue().hashCode();
        }
        if (getCountry() != null) {
            _hashCode += getCountry().hashCode();
        }
        if (getStatus() != null) {
            _hashCode += getStatus().hashCode();
        }
        if (getDisplayValue() != null) {
            for (int i=0;
                 i<java.lang.reflect.Array.getLength(getDisplayValue());
                 i++) {
                java.lang.Object obj = java.lang.reflect.Array.get(getDisplayValue(), i);
                if (obj != null &&
                    !obj.getClass().isArray()) {
                    _hashCode += obj.hashCode();
                }
            }
        }
        __hashCodeCalc = false;
        return _hashCode;
    }

    // Type metadata
    private static org.apache.axis.description.TypeDesc typeDesc =
        new org.apache.axis.description.TypeDesc(ProductBiddingCategoryData.class, true);

    static {
        typeDesc.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201601", "ProductBiddingCategoryData"));
        org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("dimensionValue");
        elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201601", "dimensionValue"));
        elemField.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201601", "ProductBiddingCategory"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("parentDimensionValue");
        elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201601", "parentDimensionValue"));
        elemField.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201601", "ProductBiddingCategory"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("country");
        elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201601", "country"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("status");
        elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201601", "status"));
        elemField.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201601", "ShoppingBiddingDimensionStatus"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("displayValue");
        elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201601", "displayValue"));
        elemField.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201601", "String_StringMapEntry"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        elemField.setMaxOccursUnbounded(true);
        typeDesc.addFieldDesc(elemField);
    }

    /**
     * Return type metadata object
     */
    public static org.apache.axis.description.TypeDesc getTypeDesc() {
        return typeDesc;
    }

    /**
     * Get Custom Serializer
     */
    public static org.apache.axis.encoding.Serializer getSerializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanSerializer(
            _javaType, _xmlType, typeDesc);
    }

    /**
     * Get Custom Deserializer
     */
    public static org.apache.axis.encoding.Deserializer getDeserializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanDeserializer(
            _javaType, _xmlType, typeDesc);
    }

}


text:
namespace ROCKSDB_NAMESPACE {

class TimerTest : public testing::Test {
 public:
  TimerTest() : mock_env_(new MockTimeEnv(Env::Default())) {}

 protected:
  std::unique_ptr<MockTimeEnv> mock_env_;
};

TEST_F(TimerTest, SingleScheduleOnceTest) {
  const uint64_t kSecond = 1000000;  // 1sec = 1000000us
  const int kIterations = 1;
  uint64_t time_counter = 0;
  mock_env_->set_current_time(0);
  port::Mutex mutex;
  port::CondVar test_cv(&mutex);

  Timer timer(mock_env_.get());
  int count = 0;
  timer.Add(
      [&] {
        MutexLock l(&mutex);
        count++;
        if (count >= kIterations) {
          test_cv.SignalAll();
        }
      },
      "fn_sch_test", 1 * kSecond, 0);

  ASSERT_TRUE(timer.Start());

  // Wait for execution to finish
  {
    MutexLock l(&mutex);
    while(count < kIterations) {
      time_counter += kSecond;
      mock_env_->set_current_time(time_counter);
      test_cv.TimedWait(time_counter);
    }
  }

  ASSERT_TRUE(timer.Shutdown());

  ASSERT_EQ(1, count);
}

TEST_F(TimerTest, MultipleScheduleOnceTest) {
  const uint64_t kSecond = 1000000;  // 1sec = 1000000us
  const int kIterations = 1;
  uint64_t time_counter = 0;
  mock_env_->set_current_time(0);
  port::Mutex mutex1;
  port::CondVar test_cv1(&mutex1);

  Timer timer(mock_env_.get());
  int count1 = 0;
  timer.Add(
      [&] {
        MutexLock l(&mutex1);
        count1++;
        if (count1 >= kIterations) {
          test_cv1.SignalAll();
        }
      },
      "fn_sch_test1", 1 * kSecond, 0);

  port::Mutex mutex2;
  port::CondVar test_cv2(&mutex2);
  int count2 = 0;
  timer.Add(
      [&] {
        MutexLock l(&mutex2);
        count2 += 5;
        if (count2 >= kIterations) {
          test_cv2.SignalAll();
        }
      },
      "fn_sch_test2", 3 * kSecond, 0);

  ASSERT_TRUE(timer.Start());

  // Wait for execution to finish
  {
    MutexLock l(&mutex1);
    while (count1 < kIterations) {
      time_counter += kSecond;
      mock_env_->set_current_time(time_counter);
      test_cv1.TimedWait(time_counter);
      }
  }

  // Wait for execution to finish
  {
    MutexLock l(&mutex2);
    while(count2 < kIterations) {
      time_counter += kSecond;
      mock_env_->set_current_time(time_counter);
      test_cv2.TimedWait(time_counter);
    }
  }

  ASSERT_TRUE(timer.Shutdown());

  ASSERT_EQ(1, count1);
  ASSERT_EQ(5, count2);
}

TEST_F(TimerTest, DISABLED_SingleScheduleRepeatedlyTest) {
  const uint64_t kSecond = 1000000;  // 1sec = 1000000us
  const int kIterations = 5;
  uint64_t time_counter = 0;
  mock_env_->set_current_time(0);
  port::Mutex mutex;
  port::CondVar test_cv(&mutex);

  Timer timer(mock_env_.get());
  int count = 0;
  timer.Add(
      [&] {
        MutexLock l(&mutex);
        count++;
        fprintf(stderr, "%d\n", count);
        if (count >= kIterations) {
          test_cv.SignalAll();
        }
      },
      "fn_sch_test", 1 * kSecond, 1 * kSecond);

  ASSERT_TRUE(timer.Start());

  // Wait for execution to finish
  {
    MutexLock l(&mutex);
    while(count < kIterations) {
      time_counter += kSecond;
      mock_env_->set_current_time(time_counter);
      test_cv.TimedWait(time_counter);
    }
  }

  ASSERT_TRUE(timer.Shutdown());

  ASSERT_EQ(5, count);
}

TEST_F(TimerTest, DISABLED_MultipleScheduleRepeatedlyTest) {
  const uint64_t kSecond = 1000000;  // 1sec = 1000000us
  uint64_t time_counter = 0;
  mock_env_->set_current_time(0);
  Timer timer(mock_env_.get());

  port::Mutex mutex1;
  port::CondVar test_cv1(&mutex1);
  const int kIterations1 = 5;
  int count1 = 0;
  timer.Add(
      [&] {
        MutexLock l(&mutex1);
        count1++;
        fprintf(stderr, "hello\n");
        if (count1 >= kIterations1) {
          test_cv1.SignalAll();
        }
      },
      "fn_sch_test1", 0, 2 * kSecond);

  port::Mutex mutex2;
  port::CondVar test_cv2(&mutex2);
  const int kIterations2 = 5;
  int count2 = 0;
  timer.Add(
      [&] {
        MutexLock l(&mutex2);
        count2++;
        fprintf(stderr, "world\n");
        if (count2 >= kIterations2) {
          test_cv2.SignalAll();
        }
      },
      "fn_sch_test2", 1 * kSecond, 2 * kSecond);

  ASSERT_TRUE(timer.Start());

  // Wait for execution to finish
  {
    MutexLock l(&mutex1);
    while(count1 < kIterations1) {
      time_counter += kSecond;
      mock_env_->set_current_time(time_counter);
      test_cv1.TimedWait(time_counter);
    }
  }

  timer.Cancel("fn_sch_test1");

  // Wait for execution to finish
  {
    MutexLock l(&mutex2);
    while(count2 < kIterations2) {
      time_counter += kSecond;
      mock_env_->set_current_time(time_counter);
      test_cv2.TimedWait(time_counter);
    }
  }

  timer.Cancel("fn_sch_test2");

  ASSERT_TRUE(timer.Shutdown());

  ASSERT_EQ(count1, 5);
  ASSERT_EQ(count2, 5);
}

}  // namespace ROCKSDB_NAMESPACE

int main(int argc, char** argv) {
  ::testing::InitGoogleTest(&argc, argv);

  return RUN_ALL_TESTS();
}


text:
package dispatcher

import (
	"fmt"

	"github.com/docker/swarmkit/api"
	"github.com/docker/swarmkit/api/equality"
	"github.com/docker/swarmkit/api/validation"
	"github.com/docker/swarmkit/manager/drivers"
	"github.com/docker/swarmkit/manager/state/store"
	"github.com/sirupsen/logrus"
)

type typeAndID struct {
	id      string
	objType api.ResourceType
}

type assignmentSet struct {
	dp                   *drivers.DriverProvider
	tasksMap             map[string]*api.Task
	tasksUsingDependency map[typeAndID]map[string]struct{}
	changes              map[typeAndID]*api.AssignmentChange
	log                  *logrus.Entry
}

func newAssignmentSet(log *logrus.Entry, dp *drivers.DriverProvider) *assignmentSet {
	return &assignmentSet{
		dp:                   dp,
		changes:              make(map[typeAndID]*api.AssignmentChange),
		tasksMap:             make(map[string]*api.Task),
		tasksUsingDependency: make(map[typeAndID]map[string]struct{}),
		log:                  log,
	}
}

func assignSecret(a *assignmentSet, readTx store.ReadTx, mapKey typeAndID, t *api.Task) {
	a.tasksUsingDependency[mapKey] = make(map[string]struct{})
	secret, err := a.secret(readTx, t, mapKey.id)
	if err != nil {
		a.log.WithFields(logrus.Fields{
			"resource.type": "secret",
			"secret.id":     mapKey.id,
			"error":         err,
		}).Debug("failed to fetch secret")
		return
	}
	a.changes[mapKey] = &api.AssignmentChange{
		Assignment: &api.Assignment{
			Item: &api.Assignment_Secret{
				Secret: secret,
			},
		},
		Action: api.AssignmentChange_AssignmentActionUpdate,
	}
}

func assignConfig(a *assignmentSet, readTx store.ReadTx, mapKey typeAndID) {
	a.tasksUsingDependency[mapKey] = make(map[string]struct{})
	config := store.GetConfig(readTx, mapKey.id)
	if config == nil {
		a.log.WithFields(logrus.Fields{
			"resource.type": "config",
			"config.id":     mapKey.id,
		}).Debug("config not found")
		return
	}
	a.changes[mapKey] = &api.AssignmentChange{
		Assignment: &api.Assignment{
			Item: &api.Assignment_Config{
				Config: config,
			},
		},
		Action: api.AssignmentChange_AssignmentActionUpdate,
	}
}

func (a *assignmentSet) addTaskDependencies(readTx store.ReadTx, t *api.Task) {
	for _, resourceRef := range t.Spec.ResourceReferences {
		mapKey := typeAndID{objType: resourceRef.ResourceType, id: resourceRef.ResourceID}
		if len(a.tasksUsingDependency[mapKey]) == 0 {
			switch resourceRef.ResourceType {
			case api.ResourceType_SECRET:
				assignSecret(a, readTx, mapKey, t)
			case api.ResourceType_CONFIG:
				assignConfig(a, readTx, mapKey)
			default:
				a.log.WithField(
					"resource.type", resourceRef.ResourceType,
				).Debug("invalid resource type for a task dependency, skipping")
				continue
			}
		}
		a.tasksUsingDependency[mapKey][t.ID] = struct{}{}
	}

	var secrets []*api.SecretReference
	container := t.Spec.GetContainer()
	if container != nil {
		secrets = container.Secrets
	}

	for _, secretRef := range secrets {
		secretID := secretRef.SecretID
		mapKey := typeAndID{objType: api.ResourceType_SECRET, id: secretID}

		if len(a.tasksUsingDependency[mapKey]) == 0 {
			assignSecret(a, readTx, mapKey, t)
		}
		a.tasksUsingDependency[mapKey][t.ID] = struct{}{}
	}

	var configs []*api.ConfigReference
	if container != nil {
		configs = container.Configs
	}
	for _, configRef := range configs {
		configID := configRef.ConfigID
		mapKey := typeAndID{objType: api.ResourceType_CONFIG, id: configID}

		if len(a.tasksUsingDependency[mapKey]) == 0 {
			assignConfig(a, readTx, mapKey)
		}
		a.tasksUsingDependency[mapKey][t.ID] = struct{}{}
	}
}

func (a *assignmentSet) releaseDependency(mapKey typeAndID, assignment *api.Assignment, taskID string) bool {
	delete(a.tasksUsingDependency[mapKey], taskID)
	if len(a.tasksUsingDependency[mapKey]) != 0 {
		return false
	}
	// No tasks are using the dependency anymore
	delete(a.tasksUsingDependency, mapKey)
	a.changes[mapKey] = &api.AssignmentChange{
		Assignment: assignment,
		Action:     api.AssignmentChange_AssignmentActionRemove,
	}
	return true
}

func (a *assignmentSet) releaseTaskDependencies(t *api.Task) bool {
	var modified bool

	for _, resourceRef := range t.Spec.ResourceReferences {
		var assignment *api.Assignment
		switch resourceRef.ResourceType {
		case api.ResourceType_SECRET:
			assignment = &api.Assignment{
				Item: &api.Assignment_Secret{
					Secret: &api.Secret{ID: resourceRef.ResourceID},
				},
			}
		case api.ResourceType_CONFIG:
			assignment = &api.Assignment{
				Item: &api.Assignment_Config{
					Config: &api.Config{ID: resourceRef.ResourceID},
				},
			}
		default:
			a.log.WithField(
				"resource.type", resourceRef.ResourceType,
			).Debug("invalid resource type for a task dependency, skipping")
			continue
		}

		mapKey := typeAndID{objType: resourceRef.ResourceType, id: resourceRef.ResourceID}
		if a.releaseDependency(mapKey, assignment, t.ID) {
			modified = true
		}
	}

	container := t.Spec.GetContainer()

	var secrets []*api.SecretReference
	if container != nil {
		secrets = container.Secrets
	}

	for _, secretRef := range secrets {
		secretID := secretRef.SecretID
		mapKey := typeAndID{objType: api.ResourceType_SECRET, id: secretID}
		assignment := &api.Assignment{
			Item: &api.Assignment_Secret{
				Secret: &api.Secret{ID: secretID},
			},
		}
		if a.releaseDependency(mapKey, assignment, t.ID) {
			modified = true
		}
	}

	var configs []*api.ConfigReference
	if container != nil {
		configs = container.Configs
	}

	for _, configRef := range configs {
		configID := configRef.ConfigID
		mapKey := typeAndID{objType: api.ResourceType_CONFIG, id: configID}
		assignment := &api.Assignment{
			Item: &api.Assignment_Config{
				Config: &api.Config{ID: configID},
			},
		}
		if a.releaseDependency(mapKey, assignment, t.ID) {
			modified = true
		}
	}

	return modified
}

func (a *assignmentSet) addOrUpdateTask(readTx store.ReadTx, t *api.Task) bool {
	// We only care about tasks that are ASSIGNED or higher.
	if t.Status.State < api.TaskStateAssigned {
		return false
	}

	if oldTask, exists := a.tasksMap[t.ID]; exists {
		// States ASSIGNED and below are set by the orchestrator/scheduler,
		// not the agent, so tasks in these states need to be sent to the
		// agent even if nothing else has changed.
		if equality.TasksEqualStable(oldTask, t) && t.Status.State > api.TaskStateAssigned {
			// this update should not trigger a task change for the agent
			a.tasksMap[t.ID] = t
			// If this task got updated to a final state, let's release
			// the dependencies that are being used by the task
			if t.Status.State > api.TaskStateRunning {
				// If releasing the dependencies caused us to
				// remove something from the assignment set,
				// mark one modification.
				return a.releaseTaskDependencies(t)
			}
			return false
		}
	} else if t.Status.State <= api.TaskStateRunning {
		// If this task wasn't part of the assignment set before, and it's <= RUNNING
		// add the dependencies it references to the assignment.
		// Task states > RUNNING are worker reported only, are never created in
		// a > RUNNING state.
		a.addTaskDependencies(readTx, t)
	}
	a.tasksMap[t.ID] = t
	a.changes[typeAndID{objType: api.ResourceType_TASK, id: t.ID}] = &api.AssignmentChange{
		Assignment: &api.Assignment{
			Item: &api.Assignment_Task{
				Task: t,
			},
		},
		Action: api.AssignmentChange_AssignmentActionUpdate,
	}
	return true
}

func (a *assignmentSet) removeTask(t *api.Task) bool {
	if _, exists := a.tasksMap[t.ID]; !exists {
		return false
	}

	a.changes[typeAndID{objType: api.ResourceType_TASK, id: t.ID}] = &api.AssignmentChange{
		Assignment: &api.Assignment{
			Item: &api.Assignment_Task{
				Task: &api.Task{ID: t.ID},
			},
		},
		Action: api.AssignmentChange_AssignmentActionRemove,
	}

	delete(a.tasksMap, t.ID)

	// Release the dependencies being used by this task.
	// Ignoring the return here. We will always mark this as a
	// modification, since a task is being removed.
	a.releaseTaskDependencies(t)
	return true
}

func (a *assignmentSet) message() api.AssignmentsMessage {
	var message api.AssignmentsMessage
	for _, change := range a.changes {
		message.Changes = append(message.Changes, change)
	}

	// The the set of changes is reinitialized to prepare for formation
	// of the next message.
	a.changes = make(map[typeAndID]*api.AssignmentChange)

	return message
}

// secret populates the secret value from raft store. For external secrets, the value is populated
// from the secret driver.
func (a *assignmentSet) secret(readTx store.ReadTx, task *api.Task, secretID string) (*api.Secret, error) {
	secret := store.GetSecret(readTx, secretID)
	if secret == nil {
		return nil, fmt.Errorf("secret not found")
	}
	if secret.Spec.Driver == nil {
		return secret, nil
	}
	d, err := a.dp.NewSecretDriver(secret.Spec.Driver)
	if err != nil {
		return nil, err
	}
	value, err := d.Get(&secret.Spec, task)
	if err != nil {
		return nil, err
	}
	if err := validation.ValidateSecretPayload(value); err != nil {
		return nil, err
	}
	// Assign the secret
	secret.Spec.Data = value
	return secret, nil
}


text:
package com.spike.giantdataanalysis.task.store.repository;

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

import org.apache.commons.collections4.CollectionUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit4.SpringRunner;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.spike.giantdataanalysis.task.store.domain.TaskInfo;

// 注意: 不回滚事务.
@RunWith(SpringRunner.class)
@SpringBootTest
@Rollback(false)
public class TestPrepareData {

  @Autowired
  private TaskInfoRepository taskInfoDao;

  private ObjectMapper objectMapper;

  @Before
  public void setUp() {
    objectMapper = new ObjectMapper();
  }

  @Test
  public void prepareData() {

    Set<String> workloadIds = StatisticDataFactory.I().getWorkloadIds(9);
    if (CollectionUtils.isEmpty(workloadIds)) {
      return;
    }

    long initStart = 1l;
    long initEnd = 100l;

    for (String workloadId : workloadIds) {
      TaskInfo taskInfo = new TaskInfo();
      taskInfo.setWorkloadShardKey(workloadId);
      Map<String, String> workloadShardInfo = new HashMap<String, String>();
      workloadShardInfo.put("start", String.valueOf(initStart));
      workloadShardInfo.put("end", String.valueOf(initEnd));

      try {
        taskInfo.setWorkloadShardInfo(objectMapper.writeValueAsString(workloadShardInfo));
      } catch (JsonProcessingException e) {
        taskInfo.setWorkloadShardInfo("UNKNOWN");
      }

      taskInfoDao.save(taskInfo);
      System.out.println(taskInfo.getId());
    }

  }
}