text:
package base;

import java.lang.reflect.Method;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Random;

import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;

import listener.ExtentManager;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import utils.APIUtil;
import utils.DateHandler;
import utils.HttpUtil;

import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;

import utils.JsonReader;

public class TestBase {

	static JsonReader jr = new JsonReader();
	public static String access_token = null;

	//static String testjson = jr.ReadFile("./APITest.json");
	//static String testjson = jr.ReadFile("./APITest_84.json");
	//static String testjson = jr.ReadFile("./APITest_207.json");
	//static String testjson = jr.ReadFile("./APITest_214.json");
	//static String testjson = jr.ReadFile("./APITest_Beta.json");
	static String testjson = jr.ReadFile("./APITest_formal.json");

	public static String api_url = jr.parseString(testjson,"urlapi");//api-url
	public static String client_id = jr.parseString(testjson,"client_id");//api-url
	public static String client_secret = jr.parseString(testjson,"client_secret");//api-url

	public static int timeout = 25;

	public CheckPoint check = new CheckPoint();
	private static ExtentReports extentReports;
	protected ExtentTest test;
	private static String reportPath = "report/" + DateHandler.getTimeStamp()
			+ ".html";
	@BeforeMethod
	public void testBegin(Method method) {
		// System.out.println("ledger: " + ledger);
		Log.info("²âÊÔ·½·¨£º " + method.getName() + "¿ªÊ¼Ö´ÐÐ~~~~~");
		// System.out.println(method.getName());
	}

	@BeforeClass
	public void classBegin() {

		Log.info(this.getClass().getCanonicalName() + "¿ªÊ¼Ö´ÐÐ~~~~~");
		// System.out.println(this.getClass().getCanonicalName());
	}

	private static String reportLocation = "report/ExtentReport.html";

	// protected static ExtentReports extent;

	@BeforeSuite
	public void beforeSuite() {
		extentReports = ExtentManager.getReporter(reportLocation);
	}
	// //
	@AfterSuite
	protected void afterSuite() {
		// extentReports.close();
	}

	public static ExtentReports getExtent() {
		return extentReports;
	}

	public static String getReportPath() {
		return reportPath;
	}
	//for api test
	public String getToken()
	{
		return this.getToken(api_url,client_id,client_secret);
	}

	public String getToken(String root_path,String client_id,String client_key)
	{
		System.out.println("=========Get token========");
		String api_path = "/oauth2/token" ;
		LinkedHashMap<String, Object> parameter = new LinkedHashMap<String,Object>();
		parameter.put("client_id",client_id);
		parameter.put("client_secret",client_key);
		parameter.put("grant_type","client_credentials");
		String result = HttpUtil.dopostApi(root_path, api_path, parameter, null);
		JSONObject jsonObject =JSONObject.fromObject(result);
		return jsonObject.getString("access_token");
	}

	public static String createUser(String Token,StringBuffer name,StringBuffer address)
	{

		System.out.println("=========Create user========");
		String api_path = "/account/v1/register" ;
		LinkedHashMap<String, Object> parameter = new LinkedHashMap<String,Object>();

		Map<String, Object> thrMap = new LinkedHashMap<String, Object>();

		parameter.put("access_token",access_token);

		String s = APIUtil.getRandomString(10);

		Random rand = new Random();
		int tradeNoBase = rand.nextInt(10000);
		thrMap.put("user_name", s);
		thrMap.put("password", s);
		thrMap.put("trade_no", (tradeNoBase++)+(System.currentTimeMillis()<<8));
		thrMap.put("metadata", "444");

		JSONObject jsonBody = JSONObject.fromObject(thrMap);

		String result = HttpUtil.dopostApi(api_url, api_path, parameter, jsonBody);
		JSONObject jsonObject =JSONObject.fromObject(result);
		if (jsonObject.getString("err_code").equals("0"))
		{
			name.append(s);
			address.append(jsonObject.getJSONObject("data").get("bubi_address"));

		}
		return result;

	}

	public static String createUser_v2(String Token,StringBuffer name,StringBuffer address)
	{

		System.out.println("=========Create user v2========");
		String api_path = "/account/v2/register" ;
		LinkedHashMap<String, Object> parameter = new LinkedHashMap<String,Object>();

		Map<String, Object> thrMap = new LinkedHashMap<String, Object>();

		parameter.put("access_token",access_token);

		String s = APIUtil.getRandomString(10);

		Random rand = new Random();
		int tradeNoBase = rand.nextInt(10000);
		thrMap.put("user_name", s);
		thrMap.put("password", s);
		thrMap.put("trade_no", (tradeNoBase++)+(System.currentTimeMillis()<<8));
		thrMap.put("metadata", "444");

		JSONObject jsonBody = JSONObject.fromObject(thrMap);

		String result = HttpUtil.dopostApi(api_url, api_path, parameter, jsonBody);
		JSONObject jsonObject =JSONObject.fromObject(result);
		if (jsonObject.getString("err_code").equals("0"))
		{
			name.append(s);
			address.append(jsonObject.getJSONObject("data").get("bubi_address"));

		}
		return result;

	}
	public static String issueAsset(String access_token, String user_name,String address,StringBuffer assetcode,String asset_name,String asset_unit,String metadata,JSONArray... detail)
	{
		System.out.println("=========Issue asset========");
		String api_path = "/asset/v1/issue" ;
		LinkedHashMap<String, Object> parameter = new LinkedHashMap<String,Object>();

		Map<String, Object> thrMap = new LinkedHashMap<String, Object>();

		parameter.put("access_token",access_token);

		Random rand = new Random();
		int tradeNoBase = rand.nextInt(10000);
		thrMap.put("asset_issuer",address );
		thrMap.put("password", user_name);
		thrMap.put("trade_no", (tradeNoBase++)+(System.currentTimeMillis()<<8));
		thrMap.put("asset_name",asset_name);
		thrMap.put("asset_unit",asset_unit);
		thrMap.put("asset_amount","100");
		thrMap.put("metadata", metadata);
		if(detail.length!= 0)
		{
			if(detail[0]!=null)
			{
				thrMap.put("details", detail[0]);
			}
		}

		JSONObject jsonBody = JSONObject.fromObject(thrMap);

		String result = HttpUtil.dopostApi(api_url, api_path, parameter, jsonBody);
		JSONObject jsonObject =JSONObject.fromObject(result);
		if (jsonObject.getString("err_code").equals("0"))
		{
			assetcode.append(jsonObject.getJSONObject("data").get("asset_code"));
		}
		return result;
	}

	public void issueAndSendMultiAsset(String testurl,String access_token, String user_name,String address,String asset_name,String asset_unit,int howmany,JSONArray... detail)
	{
		System.out.println("=========Issue multiple asset========");
		String api_path = "/asset/v1/issue" ;
		LinkedHashMap<String, Object> parameter = new LinkedHashMap<String,Object>();
		String to_address = new String();

		String assetcode = new String();
		parameter.put("access_token",access_token);

		Random rand = new Random();
		int tradeNoBase = rand.nextInt(10000);

		for(int i = 0;i<howmany;i++)
		{
			api_path = "/asset/v1/issue" ;
			Map<String, Object> thrMap = new LinkedHashMap<String, Object>();

			thrMap.put("asset_issuer",address );
			thrMap.put("password", user_name);

			thrMap.put("trade_no", (tradeNoBase++)+(System.currentTimeMillis()<<8));
			thrMap.put("asset_name",asset_name+"-"+rand.nextInt(99999));
			thrMap.put("asset_unit",rand.nextInt(30000));
			thrMap.put("asset_amount",Integer.toString(rand.nextInt(3000000)+3000000));
			//thrMap.put("asset_amount","222");
			thrMap.put("metadata", "444");
			if(detail.length!= 0)
			{
				if(detail[0]!=null)
				{
					thrMap.put("details", detail[0]);
				}
			}

			JSONObject jsonBody = JSONObject.fromObject(thrMap);

			String result = HttpUtil.dopostApi(testurl, api_path, parameter, jsonBody);

			JSONObject jsonObject =JSONObject.fromObject(result);
			if (jsonObject.getString("err_code").equals("0"))
			{
				assetcode=(String)jsonObject.getJSONObject("data").get("asset_code");
			}

			System.out.println("=========Create user========");
			api_path = "/account/v1/register" ;

			Map<String, Object> thrMap1 = new LinkedHashMap<String, Object>();

			parameter.put("access_token",access_token);

			String s = APIUtil.getRandomString(10);

			tradeNoBase = rand.nextInt(10000);
			thrMap1.put("user_name", s);
			thrMap1.put("password", s);
			thrMap1.put("trade_no", (tradeNoBase++)+(System.currentTimeMillis()<<8));
			thrMap1.put("metadata", "444");

			jsonBody = JSONObject.fromObject(thrMap1);

			result = HttpUtil.dopostApi(testurl, api_path, parameter, jsonBody);
			jsonObject =JSONObject.fromObject(result);
			if (jsonObject.getString("err_code").equals("0"))
			{
				to_address = (String)jsonObject.getJSONObject("data").get("bubi_address");

			}
			//send
			api_path = "/asset/v1/send" ;

			Map<String, Object> thrMap2 = new LinkedHashMap<String, Object>();
			thrMap2.put("current_string", APIUtil.getRandomString(32));

			long trade1 = ((tradeNoBase++)+(System.currentTimeMillis()<<8));
			thrMap2.put("trade_no", Long.toString(trade1));
			thrMap2.put("asset_code", assetcode);
			thrMap2.put("asset_amount", Integer.toString(rand.nextInt(2900000)));
			//thrMap2.put("asset_amount", "222");

			thrMap2.put("from_bubi_address", address);
			thrMap2.put("to_bubi_address", to_address);
			String sign1 = APIUtil.sign(thrMap2, "d12ed7f0a30bebb157bdc81770fd2201");
			thrMap2.put("sign", sign1);
			thrMap2.put("password", user_name);
			thrMap2.put("metadata", "444");

			jsonBody = JSONObject.fromObject(thrMap2);

			result = HttpUtil.dopostApi(testurl, api_path, parameter, jsonBody);

		}

	}

	public static String sendAsset(Boolean isAsync,String access_token, String from_address,String user_name,String to_address,String assetcode,int amount)
	{
		System.out.println("=========Send asset========");
		String api_path = new String();
		if(isAsync)
			api_path = "/asset/v1/sendAsync" ;
		else
			api_path = "/asset/v1/send" ;
		LinkedHashMap<String, Object> parameter = new LinkedHashMap<String,Object>();

		Map<String, Object> thrMap = new LinkedHashMap<String, Object>();

		parameter.put("access_token",access_token);

		thrMap.put("current_string", APIUtil.getRandomString(32));
		Random rand = new Random();
		int tradeNoBase = rand.nextInt(10000);
		long trade1 = ((tradeNoBase++)+(System.currentTimeMillis()<<8));
		thrMap.put("trade_no", Long.toString(trade1));
		thrMap.put("asset_code", assetcode);
		thrMap.put("asset_amount", Integer.toString(amount));

		thrMap.put("from_bubi_address", from_address);
		thrMap.put("to_bubi_address", to_address);
		String sign1 = APIUtil.sign(thrMap, client_secret);
		thrMap.put("sign", sign1);
		thrMap.put("password", user_name);
		thrMap.put("metadata", "444");

		JSONObject jsonBody = JSONObject.fromObject(thrMap);

		String result = HttpUtil.dopostApi(api_url, api_path, parameter, jsonBody);
		return result;

	}

	public static String grantAsset(String access_token, String from_address,String user_name,String to_address,String assetcode,int amount)
	{

		System.out.println("=========Grant asset========");

		String api_path = "/asset/v1/grant" ;
		LinkedHashMap<String, Object> parameter = new LinkedHashMap<String,Object>();

		Map<String, Object> thrMap = new LinkedHashMap<String, Object>();

		parameter.put("access_token",access_token);

		thrMap.put("current_string", APIUtil.getRandomString(32));
		Random rand = new Random();
		int tradeNoBase = rand.nextInt(10000);
		long trade1 = ((tradeNoBase++)+(System.currentTimeMillis()<<8));
		thrMap.put("trade_no", Long.toString(trade1));
		thrMap.put("asset_code", assetcode);
		thrMap.put("asset_amount", Integer.toString(amount));

		thrMap.put("from_bubi_address", from_address);
		thrMap.put("to_bubi_address", to_address);
		String sign1 = APIUtil.sign(thrMap, client_secret);
		thrMap.put("sign", sign1);
		thrMap.put("password", user_name);
		thrMap.put("metadata", "444");

		JSONObject jsonBody = JSONObject.fromObject(thrMap);

		String result = HttpUtil.dopostApi(api_url, api_path, parameter, jsonBody);
		return result;

	}
	public static String add2Issue(String access_token, String user_name,String assetcode,int amount)
	{

		System.out.println("=========Add 2 issue========");
		String api_path = "/asset/v1/add2Issue" ;
		LinkedHashMap<String, Object> parameter = new LinkedHashMap<String,Object>();

		Map<String, Object> thrMap = new LinkedHashMap<String, Object>();

		parameter.put("access_token",access_token);
		Random rand = new Random();
		int tradeNoBase = rand.nextInt(10000);
		long trade1 = ((tradeNoBase++)+(System.currentTimeMillis()<<8));
		thrMap.put("trade_no", Long.toString(trade1));
		thrMap.put("asset_code", assetcode.toString());
		thrMap.put("password", user_name.toString());
		thrMap.put("asset_amount", Integer.toString(amount));

		thrMap.put("metadata", "444");
		JSONObject jsonBody = JSONObject.fromObject(thrMap);

		String result = HttpUtil.dopostApi(api_url, api_path, parameter, jsonBody);
		return result;
	}

	public static String changePassword(String access_token, String user_name,String newpw)
	{
		String api_path = "/account/v1/alterPwd" ;
		LinkedHashMap<String, Object> parameter = new LinkedHashMap<String,Object>();
		Map<String, Object> thrMap = new LinkedHashMap<String, Object>();

		parameter.put("access_token",access_token);
		thrMap.put("user_name", user_name);
		thrMap.put("new_password", newpw);
		Random rand = new Random();
		int tradeNoBase = rand.nextInt(10000);
		long trade1 = ((tradeNoBase++)+(System.currentTimeMillis()<<8));
		thrMap.put("trade_no", Long.toString(trade1));
		JSONObject jsonBody = JSONObject.fromObject(thrMap);
		String result = HttpUtil.dopostApi(api_url, api_path, parameter, jsonBody);
		return result;
	}

	public static String checkStatus(String api_path,String access_token, String trade_no,String bc_hash)
	{
		LinkedHashMap<String, Object> parameter = new LinkedHashMap<String,Object>();
		if(trade_no != null)
		{
			parameter.put("trade_no",trade_no);
		}
		if(bc_hash!= null)
		{
			parameter.put("hash",bc_hash);
		}
		parameter.put("access_token",access_token);
		String result = HttpUtil.dogetApi(api_url, api_path, parameter);
		return result;
	}

	public static void batchSendAsset(String url_path, String access_token, String address,String password,String assetname,String key,int count) throws KeyManagementException, NoSuchAlgorithmException
	{
		String api_path = "/asset/v1/issue" ;
		LinkedHashMap<String, Object> parameter = new LinkedHashMap<String,Object>();
		String to_address = new String();

		String assetcode = new String();
		parameter.put("access_token",access_token);

		Random rand = new Random();
		int tradeNoBase = rand.nextInt(10000);

		api_path = "/asset/v1/issue" ;
			Map<String, Object> thrMap = new LinkedHashMap<String, Object>();

			thrMap.put("asset_issuer",address );
			thrMap.put("password", password);

			thrMap.put("trade_no", (tradeNoBase++)+(System.currentTimeMillis()<<8));
			thrMap.put("asset_name",assetname+"-"+rand.nextInt(99999));
			thrMap.put("asset_unit",rand.nextInt(30000));
			//thrMap.put("asset_amount",Integer.toString(rand.nextInt(3000000)+3000000));
			thrMap.put("asset_amount",Integer.toString(count*4));
			thrMap.put("metadata", "444");

			JSONObject jsonBody = JSONObject.fromObject(thrMap);

			String result = HttpUtil.dopostApi(url_path, api_path, parameter, jsonBody);

			JSONObject jsonObject =JSONObject.fromObject(result);
			if (jsonObject.getString("err_code").equals("0"))
			{
				assetcode=(String)jsonObject.getJSONObject("data").get("asset_code");
			}

			JSONArray senders = new JSONArray();

			long tradeno = (tradeNoBase++)+(System.currentTimeMillis()<<8)+count;

			for(int i = 0; i<count; i++)
			{
				//create a user
				System.out.println("=========Create user========");
				api_path = "/account/v1/register" ;

				Map<String, Object> thrMap1 = new LinkedHashMap<String, Object>();

				parameter.put("access_token",access_token);

				String s = APIUtil.getRandomString(10);

				tradeNoBase = rand.nextInt(10000);
				thrMap1.put("user_name", s);
				thrMap1.put("password", s);

				thrMap1.put("trade_no", (tradeNoBase++)+(System.currentTimeMillis()<<8));
				thrMap1.put("metadata", "444");

				jsonBody = JSONObject.fromObject(thrMap1);

				result = HttpUtil.dopostApi(url_path, api_path, parameter, jsonBody);
				jsonObject =JSONObject.fromObject(result);
				if (jsonObject.getString("err_code").equals("0"))
				{
					to_address = (String)jsonObject.getJSONObject("data").get("bubi_address");

				}
				//add to batch send
				Map<String, Object> thrMap_single = new LinkedHashMap<String, Object>();

				thrMap_single.put("trade_no", Long.toString(tradeno));
				thrMap_single.put("from_bubi_address", address);
				thrMap_single.put("asset_code", assetcode);
				thrMap_single.put("to_bubi_address" , to_address);
				thrMap_single.put("asset_amount" , "2");
				thrMap_single.put("current_string" , "1467345122019");
				String sign1 = APIUtil.sign(thrMap_single, key);
				thrMap_single.put("type" , "asset.send");
				thrMap_single.put("sign", sign1);
				thrMap_single.put("password", password);
				jsonBody = JSONObject.fromObject(thrMap_single);
				senders.add(jsonBody);

			}
			System.out.println("=========blend========");
			api_path = "/blend";
			Map<String, Object> thrMap_blend = new LinkedHashMap<String, Object>();
			thrMap_blend.put("trade_no", Long.toString(tradeno));
			thrMap_blend.put("opts", senders);
			jsonBody = JSONObject.fromObject(thrMap_blend);
			result = HttpUtil.dopostApi(url_path, api_path, parameter, jsonBody);

	}

	public static String CreateEvidence(String access_token, JSONArray signers,String metadata, StringBuffer evidence,StringBuffer bchash)
	{

		System.out.println("=========create evidence========");

		evidence.delete(0, evidence.length());
		bchash.delete(0, bchash.length());
		String api_path = "/evidence/v1/create" ;
		LinkedHashMap<String, Object> parameter = new LinkedHashMap<String,Object>();

		Map<String, Object> thrMap = new LinkedHashMap<String, Object>();

		parameter.put("access_token",access_token);

		Random rand = new Random();
		int tradeNoBase = rand.nextInt(10000);
		long trade1 = ((tradeNoBase++)+(System.currentTimeMillis()<<8));
		thrMap.put("trade_no", Long.toString(trade1));

		thrMap.put("signers", signers);
		thrMap.put("metadata", metadata);

		JSONObject jsonBody = JSONObject.fromObject(thrMap);

		String result = HttpUtil.dopostApi(api_url, api_path, parameter, jsonBody);

		JSONObject jsonObject =JSONObject.fromObject(result);
		if (jsonObject.getString("err_code").equals("0"))
		{
			evidence.append(jsonObject.getJSONObject("data").get("evidence_id"));
			bchash.append(jsonObject.getJSONObject("data").get("bc_hash"));
		}
		return result;

	}

	public static String ModifyEvidence(String access_token, JSONArray signers,String metadata, String evidence,StringBuffer bchash)
	{

		System.out.println("=========modify evidence========");

		String api_path = "/evidence/v1/modify" ;
		LinkedHashMap<String, Object> parameter = new LinkedHashMap<String,Object>();

		Map<String, Object> thrMap = new LinkedHashMap<String, Object>();

		parameter.put("access_token",access_token);

		Random rand = new Random();
		int tradeNoBase = rand.nextInt(10000);
		long trade1 = ((tradeNoBase++)+(System.currentTimeMillis()<<8));
		thrMap.put("trade_no", Long.toString(trade1));

		thrMap.put("signers", signers);
		thrMap.put("evidence_id", evidence);
		thrMap.put("metadata", metadata);

		JSONObject jsonBody = JSONObject.fromObject(thrMap);

		String result = HttpUtil.dopostApi(api_url, api_path, parameter, jsonBody);

		JSONObject jsonObject =JSONObject.fromObject(result);
		if (jsonObject.getString("err_code").equals("0"))
		{
			bchash.append(jsonObject.getJSONObject("data").get("bc_hash"));
		}
		return result;

	}

	public static ArrayList<RecordOutput> Record(String access_token,String recorder ,String password,int output_num,int layers,StringBuffer hash)
	{
		System.out.println("=========First Record========");

		String api_path = "/info/v2/record" ;

		//to return a map about output
		ArrayList<RecordOutput> ret = new ArrayList<RecordOutput>();

		{
			LinkedHashMap<String, Object> parameter = new LinkedHashMap<String,Object>();

			Map<String, Object> thrMap = new LinkedHashMap<String, Object>();

			parameter.put("access_token",access_token);

			Random rand = new Random();
			int tradeNoBase = rand.nextInt(10000);
			long trade1 = ((tradeNoBase++)+(System.currentTimeMillis()<<8));
			thrMap.put("trade_no", Long.toString(trade1));

			thrMap.put("recorder_address", recorder);

			thrMap.put("password", password);

			JSONArray outputs = new JSONArray();

			for (int i = 0; i<output_num;i++)
			{
				StringBuffer name = new StringBuffer();
				StringBuffer address = new StringBuffer();
				createUser_v2(access_token, name, address);

				RecordOutput recordOutput = new RecordOutput();
				recordOutput.address = address.toString();
				recordOutput.sid = Integer.toString(i+1);
				recordOutput.metadata =  "this is the output for address:"+address.toString()+" sid:"+Integer.toString(i+1);
				ret.add(recordOutput);

				//format output
				JSONObject output = new JSONObject();
				output.put("address", recordOutput.address);
				output.put("sid", recordOutput.sid);
				output.put("metadata", recordOutput.metadata);
				outputs.add(output);

			}
			JSONObject data = new JSONObject();
			data.put("outputs", outputs);
			thrMap.put("data", data);
			JSONObject jsonBody = JSONObject.fromObject(thrMap);

			String result = HttpUtil.dopostApi(api_url, api_path, parameter, jsonBody);

			JSONObject jsonObject =JSONObject.fromObject(result);
			if (jsonObject.getString("err_code").equals("0"))
			{
				hash.append(jsonObject.getJSONObject("data").get("hash"));
			}
		}
		for (int i = 0;i<layers;i++)
		{
			ret.clear();

			System.out.println(("=========Record time ")+i+("========"));

			LinkedHashMap<String, Object> parameter = new LinkedHashMap<String,Object>();

			Map<String, Object> thrMap = new LinkedHashMap<String, Object>();

			parameter.put("access_token",access_token);

			Random rand = new Random();
			int tradeNoBase = rand.nextInt(10000);
			long trade1 = ((tradeNoBase++)+(System.currentTimeMillis()<<8));
			thrMap.put("trade_no", Long.toString(trade1));

			thrMap.put("recorder_address", recorder);

			thrMap.put("password", password);

			JSONArray inputs = new JSONArray();
			JSONArray outputs = new JSONArray();

			for (int j = 0; j<output_num;j++)
			{
				RecordInput recordInput = new RecordInput();
				recordInput.hash = hash.toString();
				recordInput.index = Integer.toString(j+1);
				recordInput.metadata =  "this is the input of hash:"+hash.toString()+" index:"+Integer.toString(j+1);

				//format input
				JSONObject input = new JSONObject();
				input.put("hash", recordInput.hash);
				input.put("index", recordInput.index);
				//input.put("metadata", recordInput.metadata);
				input.put("metadata", "");
				inputs.add(input);
			}

			for (int j = 0; j<output_num;j++)
			{
				StringBuffer name = new StringBuffer();
				StringBuffer address = new StringBuffer();
				createUser_v2(access_token, name, address);

				RecordOutput recordOutput = new RecordOutput();
				recordOutput.address = address.toString();
				recordOutput.sid = Integer.toString(j+1);
				recordOutput.metadata =  "this is the output for address:"+address.toString()+" sid:"+Integer.toString(j+1);
				ret.add(recordOutput);

				//format output
				JSONObject output = new JSONObject();
				output.put("address", recordOutput.address);
				output.put("sid", recordOutput.sid);
				//output.put("metadata", recordOutput.metadata);
				output.put("metadata", "");
				outputs.add(output);

			}
			JSONObject data = new JSONObject();
			data.put("inputs", inputs);
			data.put("outputs", outputs);
			thrMap.put("data", data);
			JSONObject jsonBody = JSONObject.fromObject(thrMap);

			String result = HttpUtil.dopostApi(api_url, api_path, parameter, jsonBody);

			JSONObject jsonObject =JSONObject.fromObject(result);
			if (jsonObject.getString("err_code").equals("0"))
			{
				hash.delete(0, hash.length());
				hash.append(jsonObject.getJSONObject("data").get("hash"));
			}

		}
		return ret;

	}

	public static String metadataFormat(String asset_type,String asset_unit_code, String annualized_rate,String asset_description)

	{
		String ret = "{";

		if(asset_type!=null)
		{
			ret += "\"asset_type\":"+"\""+asset_type+"\",";
		}
		if(asset_unit_code!=null)
		{
			ret += "\"asset_unit_code\":"+"\""+asset_unit_code+"\",";
		}
		if(annualized_rate!=null)
		{
			ret += "\"annualized_rate\":"+"\""+annualized_rate+"\",";
		}
		if(asset_description!=null)
		{
			ret += "\"asset_description\":"+"\""+asset_description+"\",";
		}
		if(ret.charAt(ret.length()-1) == ',')
		{
			ret = ret.substring(0,ret.length()-1);
		}
		ret+="}";
		return ret;
	}

}


text:
/*
 * @test
 * @bug 7031005
 * @summary javap prints "extends java.lang.Object"
 */

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URI;
import java.util.Arrays;
import javax.tools.JavaCompiler;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;

public class TestSuperclass {
    enum ClassKind {
        CLASS("class"),
        INTERFACE("interface");
        ClassKind(String keyword) {
            this.keyword = keyword;
        }
        final String keyword;
    }

    enum GenericKind {
        NO(""),
        YES("<T>");
        GenericKind(String typarams) {
            this.typarams = typarams;
        }
        final String typarams;
    }

    enum SuperKind {
        NONE(null),
        SUPER("Super");
        SuperKind(String name) {
            this.name = name;
        }
        String extend() {
            return (name == null) ? "" : "extends " + name;
        }
        String decl(ClassKind ck) {
            return (name == null) ? "" : ck.keyword + " " + name + " { }";
        }
        final String name;
    }

    public static void main(String... args) throws Exception {
        JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null);
        int errors = 0;

        for (ClassKind ck: ClassKind.values()) {
            for (GenericKind gk: GenericKind.values()) {
                for (SuperKind sk: SuperKind.values()) {
                    errors += new TestSuperclass(ck, gk, sk).run(comp, fm);
                }
            }
        }

        if (errors > 0)
            throw new Exception(errors + " errors found");
    }

    final ClassKind ck;
    final GenericKind gk;
    final SuperKind sk;

    TestSuperclass(ClassKind ck, GenericKind gk, SuperKind sk) {
        this.ck = ck;
        this.gk = gk;
        this.sk = sk;
    }

    int run(JavaCompiler comp, StandardJavaFileManager fm) throws IOException {
        System.err.println("test: ck:" + ck + " gk:" + gk + " sk:" + sk);
        File testDir = new File(ck + "-" + gk + "-" + sk);
        testDir.mkdirs();
        fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(testDir));

        JavaSource js = new JavaSource();
        System.err.println(js.getCharContent(false));
        CompilationTask t = comp.getTask(null, fm, null, null, null, Arrays.asList(js));
        if (!t.call())
            throw new Error("compilation failed");

        File testClass = new File(testDir, "Test.class");
        String out = javap(testClass);

        // Extract class sig from first line of Java source
        String expect = js.source.replaceAll("(?s)^(.* Test[^{]+?) *\\{.*", "$1");

        // Extract class sig from line from javap output
        String found = out.replaceAll("(?s).*\n(.* Test[^{]+?) *\\{.*", "$1");

        checkEqual("class signature", expect, found);

        return errors;
    }

    String javap(File file) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        String[] args = { file.getPath() };
        int rc = sbql4j8.com.sun.tools.javap.Main.run(args, pw);
        pw.close();
        String out = sw.toString();
        if (!out.isEmpty())
            System.err.println(out);
        if (rc != 0)
            throw new Error("javap failed: rc=" + rc);
        return out;
    }

    void checkEqual(String label, String expect, String found) {
        if (!expect.equals(found))
            error("Unexpected " + label + " found: '" + found + "', expected: '" + expect + "'");
    }

    void error(String msg) {
        System.err.println("Error: " + msg);
        errors++;
    }

    int errors;

    class JavaSource extends SimpleJavaFileObject {
        static final String template =
                  "#CK Test#GK #EK { }\n"
                + "#SK\n";
        final String source;

        public JavaSource() {
            super(URI.create("myfo:/Test.java"), JavaFileObject.Kind.SOURCE);
            source = template
                    .replace("#CK", ck.keyword)
                    .replace("#GK", gk.typarams)
                    .replace("#EK", sk.extend())
                    .replace("#SK", sk.decl(ck));
        }

        @Override
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return source;
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace app\models\faculty;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\faculty\FacultyRecord;

/**
 * FacultySearchModel represents the model behind the search form about `app\models\faculty\FacultyRecord`.
 */
class FacultySearchModel extends FacultyRecord
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'university_id'], 'integer'],
            [['name', 'level'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($data)
    {
        $query=FacultyRecord::find()->where(['university_id'=>$data]);

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);
        return $dataProvider;
    }
}


text:
TT_TEST_BEGIN(is_function)

typedef void foo0_t();
typedef void foo1_t(int);
typedef void foo2_t(int&, double);
typedef void foo3_t(int&, bool, int, int);
typedef void foo4_t(int, bool, int*, int[], int, int, int, int, int);

BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_function<foo0_t>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_function<foo1_t>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_function<foo2_t>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_function<foo3_t>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_function<foo4_t>::value, true);

BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_function<void>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_function<int>::value, false);
#if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION)
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_function<int&>::value, false);
#ifndef BOOST_NO_RVALUE_REFERENCES
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_function<int&&>::value, false);
#endif
#else
std::cout <<
"<note>is_function will fail with some types (references for example)"
"if the compiler doesn't support partial specialisation of class templates."
"These are *not* tested here</note>" << std::endl;
#endif
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_function<int*>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_function<int[]>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_function<test_abc1>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_function<int (*)(int)>::value, false);

#ifdef BOOST_TT_TEST_MS_FUNC_SIGS
typedef void __stdcall sfoo0_t();
typedef void __stdcall sfoo1_t(int);
typedef void __stdcall sfoo2_t(int&, double);
typedef void __stdcall sfoo3_t(int&, bool, int, int);
typedef void __stdcall sfoo4_t(int, bool, int*, int[], int, int, int, int, int);

BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_function<sfoo0_t>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_function<sfoo1_t>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_function<sfoo2_t>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_function<sfoo3_t>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_function<sfoo4_t>::value, true);

#endif

TT_TEST_END


text:
package org.apache.flink.streaming.api.transformations;

import org.apache.flink.annotation.Internal;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.dag.Transformation;
import org.apache.flink.streaming.api.operators.ChainingStrategy;

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

import static org.apache.flink.util.Preconditions.checkNotNull;

/**
 * Base class for Broadcast State transformations. In a nutshell, this transformation allows to take
 * a broadcast (non-keyed) stream, connect it with another keyed or non-keyed stream, and apply a
 * function on the resulting connected stream.
 *
 *
For more information see the
 * Broadcast State Pattern documentation page.
 *
 * @param <IN1> The type of the elements in the non-broadcasted input.
 * @param <IN2> The type of the elements in the broadcasted input.
 * @param <OUT> The type of the elements that result from this transformation.
 */
@Internal
public class AbstractBroadcastStateTransformation<IN1, IN2, OUT>
        extends PhysicalTransformation<OUT> {

    private final List<MapStateDescriptor<?, ?>> broadcastStateDescriptors;

    private final Transformation<IN1> regularInput;

    private final Transformation<IN2> broadcastInput;

    private ChainingStrategy chainingStrategy = ChainingStrategy.DEFAULT_CHAINING_STRATEGY;

    protected AbstractBroadcastStateTransformation(
            final String name,
            final Transformation<IN1> regularInput,
            final Transformation<IN2> broadcastInput,
            final List<MapStateDescriptor<?, ?>> broadcastStateDescriptors,
            final TypeInformation<OUT> outTypeInfo,
            final int parallelism) {
        super(name, outTypeInfo, parallelism);
        this.regularInput = checkNotNull(regularInput);
        this.broadcastInput = checkNotNull(broadcastInput);
        this.broadcastStateDescriptors = broadcastStateDescriptors;
    }

    public Transformation<IN2> getBroadcastInput() {
        return broadcastInput;
    }

    public Transformation<IN1> getRegularInput() {
        return regularInput;
    }

    public List<MapStateDescriptor<?, ?>> getBroadcastStateDescriptors() {
        return broadcastStateDescriptors;
    }

    public ChainingStrategy getChainingStrategy() {
        return chainingStrategy;
    }

    @Override
    public void setChainingStrategy(ChainingStrategy chainingStrategy) {
        this.chainingStrategy = checkNotNull(chainingStrategy);
    }

    @Override
    public List<Transformation<?>> getTransitivePredecessors() {
        final List<Transformation<?>> predecessors = new ArrayList<>();
        predecessors.add(this);
        predecessors.add(regularInput);
        predecessors.add(broadcastInput);
        return predecessors;
    }

    @Override
    public List<Transformation<?>> getInputs() {
        final List<Transformation<?>> predecessors = new ArrayList<>();
        predecessors.add(regularInput);
        predecessors.add(broadcastInput);
        return predecessors;
    }
}


text:
<?xml version="1.0" encoding="dbcs"?>
<!--
SkipUnless:  __import__('codecs').lookup('dbcs')
Description: \x80 character in dbcs encoding
Expect:      not bozo and feed['title'] == '\u20ac'
-->
<feed version="0.3" xmlns="http://purl.org/atom/ns#">
<title>€</title>
</feed>


text:
/**
 *     This code was auto-generated by a Codezu.
 *
 *     Changes to this file may cause incorrect behavior and will be lost if
 *     the code is regenerated.
 */
package com.mozu.api.urls.commerce.catalog.admin.products;

import com.mozu.api.MozuUrl;
import com.mozu.api.utils.UrlFormatter;

public class ProductPropertyUrl
{

	/**
	 * Get Resource Url for GetProperties
	 * @param productCode
	 * @return   String Resource Url
	 */
	public static MozuUrl getPropertiesUrl(String productCode)
	{
		UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/products/{productCode}/Properties");
		formatter.formatUrl("productCode", productCode);
		return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
	}

	/**
	 * Get Resource Url for GetPropertyValueLocalizedContents
	 * @param attributeFQN
	 * @param productCode
	 * @param value
	 * @return   String Resource Url
	 */
	public static MozuUrl getPropertyValueLocalizedContentsUrl(String attributeFQN, String productCode, String value)
	{
		UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/products/{productCode}/Properties/{attributeFQN}/values/{value}/LocalizedContent");
		formatter.formatUrl("attributeFQN", attributeFQN);
		formatter.formatUrl("productCode", productCode);
		formatter.formatUrl("value", value);
		return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
	}

	/**
	 * Get Resource Url for GetPropertyValueLocalizedContent
	 * @param attributeFQN
	 * @param localeCode Language used for the entity. Currently, only "en-US" is supported.
	 * @param productCode
	 * @param responseFields Use this field to include those fields which are not included by default.
	 * @param value
	 * @return   String Resource Url
	 */
	public static MozuUrl getPropertyValueLocalizedContentUrl(String attributeFQN, String localeCode, String productCode, String responseFields, String value)
	{
		UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/products/{productCode}/Properties/{attributeFQN}/values/{value}/LocalizedContent/{localeCode}?responseFields={responseFields}");
		formatter.formatUrl("attributeFQN", attributeFQN);
		formatter.formatUrl("localeCode", localeCode);
		formatter.formatUrl("productCode", productCode);
		formatter.formatUrl("responseFields", responseFields);
		formatter.formatUrl("value", value);
		return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
	}

	/**
	 * Get Resource Url for GetProperty
	 * @param attributeFQN The fully qualified name of the attribute, which is a user defined attribute identifier.
	 * @param productCode Merchant-created code that uniquely identifies the product such as a SKU or item number. Once created, the product code is read-only.
	 * @param responseFields Use this field to include those fields which are not included by default.
	 * @return   String Resource Url
	 */
	public static MozuUrl getPropertyUrl(String attributeFQN, String productCode, String responseFields)
	{
		UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/products/{productCode}/Properties/{attributeFQN}?responseFields={responseFields}");
		formatter.formatUrl("attributeFQN", attributeFQN);
		formatter.formatUrl("productCode", productCode);
		formatter.formatUrl("responseFields", responseFields);
		return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
	}

	/**
	 * Get Resource Url for AddPropertyValueLocalizedContent
	 * @param attributeFQN
	 * @param productCode
	 * @param responseFields Use this field to include those fields which are not included by default.
	 * @param value
	 * @return   String Resource Url
	 */
	public static MozuUrl addPropertyValueLocalizedContentUrl(String attributeFQN, String productCode, String responseFields, String value)
	{
		UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/products/{productCode}/Properties/{attributeFQN}/values/{value}/LocalizedContent?responseFields={responseFields}");
		formatter.formatUrl("attributeFQN", attributeFQN);
		formatter.formatUrl("productCode", productCode);
		formatter.formatUrl("responseFields", responseFields);
		formatter.formatUrl("value", value);
		return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
	}

	/**
	 * Get Resource Url for AddProperty
	 * @param productCode
	 * @param responseFields Use this field to include those fields which are not included by default.
	 * @return   String Resource Url
	 */
	public static MozuUrl addPropertyUrl(String productCode, String responseFields)
	{
		UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/products/{productCode}/Properties?responseFields={responseFields}");
		formatter.formatUrl("productCode", productCode);
		formatter.formatUrl("responseFields", responseFields);
		return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
	}

	/**
	 * Get Resource Url for UpdatePropertyValueLocalizedContents
	 * @param attributeFQN
	 * @param productCode
	 * @param value
	 * @return   String Resource Url
	 */
	public static MozuUrl updatePropertyValueLocalizedContentsUrl(String attributeFQN, String productCode, String value)
	{
		UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/products/{productCode}/Properties/{attributeFQN}/values/{value}/LocalizedContent");
		formatter.formatUrl("attributeFQN", attributeFQN);
		formatter.formatUrl("productCode", productCode);
		formatter.formatUrl("value", value);
		return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
	}

	/**
	 * Get Resource Url for UpdatePropertyValueLocalizedContent
	 * @param attributeFQN
	 * @param localeCode Language used for the entity. Currently, only "en-US" is supported.
	 * @param productCode
	 * @param responseFields Use this field to include those fields which are not included by default.
	 * @param value
	 * @return   String Resource Url
	 */
	public static MozuUrl updatePropertyValueLocalizedContentUrl(String attributeFQN, String localeCode, String productCode, String responseFields, String value)
	{
		UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/products/{productCode}/Properties/{attributeFQN}/values/{value}/LocalizedContent/{localeCode}?responseFields={responseFields}");
		formatter.formatUrl("attributeFQN", attributeFQN);
		formatter.formatUrl("localeCode", localeCode);
		formatter.formatUrl("productCode", productCode);
		formatter.formatUrl("responseFields", responseFields);
		formatter.formatUrl("value", value);
		return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
	}

	/**
	 * Get Resource Url for UpdateProperty
	 * @param attributeFQN The fully qualified name of the attribute, which is a user defined attribute identifier.
	 * @param productCode
	 * @param responseFields Use this field to include those fields which are not included by default.
	 * @return   String Resource Url
	 */
	public static MozuUrl updatePropertyUrl(String attributeFQN, String productCode, String responseFields)
	{
		UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/products/{productCode}/Properties/{attributeFQN}?responseFields={responseFields}");
		formatter.formatUrl("attributeFQN", attributeFQN);
		formatter.formatUrl("productCode", productCode);
		formatter.formatUrl("responseFields", responseFields);
		return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
	}

	/**
	 * Get Resource Url for DeleteProperty
	 * @param attributeFQN The fully qualified name of the attribute, which is a user defined attribute identifier.
	 * @param productCode
	 * @return   String Resource Url
	 */
	public static MozuUrl deletePropertyUrl(String attributeFQN, String productCode)
	{
		UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/products/{productCode}/Properties/{attributeFQN}");
		formatter.formatUrl("attributeFQN", attributeFQN);
		formatter.formatUrl("productCode", productCode);
		return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
	}

	/**
	 * Get Resource Url for DeletePropertyValueLocalizedContent
	 * @param attributeFQN
	 * @param localeCode Language used for the entity. Currently, only "en-US" is supported.
	 * @param productCode
	 * @param value
	 * @return   String Resource Url
	 */
	public static MozuUrl deletePropertyValueLocalizedContentUrl(String attributeFQN, String localeCode, String productCode, String value)
	{
		UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/products/{productCode}/Properties/{attributeFQN}/values/{value}/LocalizedContent/{localeCode}");
		formatter.formatUrl("attributeFQN", attributeFQN);
		formatter.formatUrl("localeCode", localeCode);
		formatter.formatUrl("productCode", productCode);
		formatter.formatUrl("value", value);
		return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
	}

}


text:
__all__ = ['CCMessage', 'assert_msg_req', 'is_msg_req_valid', 'zmsg_size']

import re

MSG_DST_VALID = re.compile (r'^[a-zA-Z0-9_-]+(?:[.][a-zA-Z0-9_-]+)*$')

class CCMessage(object):
    """CC multipart message.

    Format is similar to usual REQ+REP sockets:

    - id_hopX
    - id_hop2
    - id_hop1
    - id_req (optional)
    - empty part
    - cc dest
    - cc payload (json)
    - cc signature
    - cc blob data
    """
    __slots__ = ('zmsg', 'rpos', 'parsed', 'signature')

    def __init__(self, zmsg):
        assert isinstance(zmsg, list)
        self.zmsg = zmsg
        self.rpos = zmsg.index('')
        self.parsed = None
        self.signature = None
        assert_msg_req (self.get_dest())

    def get_route(self):
        """Route parts"""
        return self.zmsg[ : self.rpos]

    def get_non_route(self):
        """Payload parts"""
        return self.zmsg[ self.rpos + 1 : ]

    def get_dest(self):
        """Return destination part"""
        return self.zmsg[self.rpos + 1]

    def get_part1(self):
        """Return body (json) as string"""
        return self.zmsg[self.rpos + 2]

    def get_part2(self):
        """Return signature"""
        if self.rpos + 3 >= len(self.zmsg):
            return ''
        return self.zmsg[self.rpos + 3]

    def get_part3(self):
        """Return blob"""
        if self.rpos + 4 >= len(self.zmsg):
            return None
        return self.zmsg[self.rpos + 4]

    def get_size(self):
        return zmsg_size (self.zmsg)

    def __repr__(self):
        x = repr(self.zmsg)
        if len(x) > 300:
            x = x[:300] + '...'
        return 'CCMessage(%s)' % x

    def __str__(self):
        x = repr(self.get_non_route())
        if len(x) > 300:
            x = x[:300] + '...'
        return 'CCMessage(%s)' % x

    def set_route (self, route):
        """Fill local route with another route."""
        self.zmsg[:self.rpos] = route
        self.rpos = len(route)

    def take_route(self, cmsg):
        """Fill local route with route from another message."""
        r = cmsg.get_route()
        self.set_route(r)

    def get_payload(self, xtx):
        if self.parsed:
            return self.parsed
        msg, sgn = xtx.parse_cmsg(self)
        if not msg:
            return None
        self.parsed = msg
        self.signature = sgn
        return msg

    def get_signature(self, xtx):
        self.get_payload(xtx)
        return self.signature

    def send_to (self, sock):
        sock.send_multipart (self.zmsg)

def assert_msg_req (dest):
    assert MSG_DST_VALID.match (dest) , "invalid msg dest: %r" % dest

def is_msg_req_valid (dest):
    return (MSG_DST_VALID.match (dest) is not None)

def zmsg_size (zmsg):
    n = 0
    for p in zmsg:
        n += len(p)
    return n


text:
Faça o login

    <form name="loginForm" ng-submit="loginForm.$valid && ctrl.submit()" novalidate>
        <input type="text" name="username" placeholder="Nome do usuário" ng-model="login.UserName" ng-model-options="{ debounce : { 'default' : 200, 'blur': 10  } }" required />

        <ng-messages class="alert-danger" for="loginForm.username.$error" ng-if="loginForm.username.$touched || loginForm.$submitted">
            <ng-message when="required">Por favor, entre com o nome de usuário.</ng-message>
        </ng-messages>

        <input type="password" name="password" placeholder="Senha" ng-model="login.Password" required />
        <ng-messages class="alert-danger" for="loginForm.password.$error" ng-if="loginForm.username.$touched || loginForm.$submitted">
            <ng-message when="required">Por favor, entre com a senha.</ng-message>
        </ng-messages>

        <input type="submit" value="Entrar" />
    </form>


text:
module Paths_Numerikell (
    version,
    getBinDir, getLibDir, getDataDir, getLibexecDir,
    getDataFileName
  ) where

import qualified Control.Exception as Exception
import Data.Version (Version(..))
import System.Environment (getEnv)
catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
catchIO = Exception.catch

version :: Version
version = Version {versionBranch = [1,0], versionTags = []}
bindir, libdir, datadir, libexecdir :: FilePath

bindir     = "/home/ankeshs/.cabal/bin"
libdir     = "/home/ankeshs/.cabal/lib/Numerikell-1.0/ghc-7.4.2"
datadir    = "/home/ankeshs/.cabal/share/Numerikell-1.0"
libexecdir = "/home/ankeshs/.cabal/libexec"

getBinDir, getLibDir, getDataDir, getLibexecDir :: IO FilePath
getBinDir = catchIO (getEnv "Numerikell_bindir") (\_ -> return bindir)
getLibDir = catchIO (getEnv "Numerikell_libdir") (\_ -> return libdir)
getDataDir = catchIO (getEnv "Numerikell_datadir") (\_ -> return datadir)
getLibexecDir = catchIO (getEnv "Numerikell_libexecdir") (\_ -> return libexecdir)

getDataFileName :: FilePath -> IO FilePath
getDataFileName name = do
  dir <- getDataDir
  return (dir ++ "/" ++ name)


text:
package chanacceptor

import (
	"testing"

	"github.com/lightningnetwork/lnd/lnwire"
	"github.com/stretchr/testify/require"
)

// dummyAcceptor is a ChannelAcceptor that will never return a failure.
type dummyAcceptor struct{}

func (d *dummyAcceptor) Accept(
	req *ChannelAcceptRequest) *ChannelAcceptResponse {

	return &ChannelAcceptResponse{}
}

// TestZeroConfAcceptorNormal verifies that the ZeroConfAcceptor will let
// requests go through for non-zero-conf channels if there are no
// sub-acceptors.
func TestZeroConfAcceptorNormal(t *testing.T) {
	t.Parallel()

	// Create the zero-conf acceptor.
	zeroAcceptor := NewZeroConfAcceptor()

	// Assert that calling Accept won't return a failure.
	req := &ChannelAcceptRequest{
		OpenChanMsg: &lnwire.OpenChannel{},
	}
	resp := zeroAcceptor.Accept(req)
	require.False(t, resp.RejectChannel())

	// Add a dummyAcceptor to the zero-conf acceptor. Assert that Accept
	// does not return a failure.
	dummy := &dummyAcceptor{}
	dummyID := zeroAcceptor.AddAcceptor(dummy)
	resp = zeroAcceptor.Accept(req)
	require.False(t, resp.RejectChannel())

	// Remove the dummyAcceptor from the zero-conf acceptor and assert that
	// Accept doesn't return a failure.
	zeroAcceptor.RemoveAcceptor(dummyID)
	resp = zeroAcceptor.Accept(req)
	require.False(t, resp.RejectChannel())
}

// TestZeroConfAcceptorZC verifies that the ZeroConfAcceptor will fail
// zero-conf channel opens unless a sub-acceptor exists.
func TestZeroConfAcceptorZC(t *testing.T) {
	t.Parallel()

	// Create the zero-conf acceptor.
	zeroAcceptor := NewZeroConfAcceptor()

	channelType := new(lnwire.ChannelType)
	*channelType = lnwire.ChannelType(*lnwire.NewRawFeatureVector(
		lnwire.ZeroConfRequired,
	))

	// Assert that calling Accept results in failure.
	req := &ChannelAcceptRequest{
		OpenChanMsg: &lnwire.OpenChannel{
			ChannelType: channelType,
		},
	}
	resp := zeroAcceptor.Accept(req)
	require.True(t, resp.RejectChannel())

	// Add a dummyAcceptor to the zero-conf acceptor. Assert that Accept
	// does not return a failure.
	dummy := &dummyAcceptor{}
	dummyID := zeroAcceptor.AddAcceptor(dummy)
	resp = zeroAcceptor.Accept(req)
	require.False(t, resp.RejectChannel())

	// Remove the dummyAcceptor from the zero-conf acceptor and assert that
	// Accept returns a failure.
	zeroAcceptor.RemoveAcceptor(dummyID)
	resp = zeroAcceptor.Accept(req)
	require.True(t, resp.RejectChannel())
}


text:
using JetBrains.Annotations;
using OpenMLTD.MilliSim.Configuration;
using OpenMLTD.MilliSim.Foundation;

namespace OpenMLTD.MilliSim.Graphics {
    // Why BufferedVisualContainer but not VisualContainer?
    // Its children may contain `IBufferedVisual`s, which requires switching render targets.
    // If Stage inherits from VisualContainer, its draw calls are directly send to GraphicsDevice.
    // In this case, when the first child of Stage, which has a parent that doesn't create a render target, ends a draw call,
    // the GraphicsDevice will eventually call SetRenderTarget(null), which clears the screen, all all contents prior to
    // the child's draw call. The result is you will see only the content of the last IBufferedVisual drawn, and the contents
    // that only directly draw on the screen after that IBufferedVisual.
    // For more information, see GraphicsDeviceExtensions.CreateRenderTarget().
    /// <summary>
    /// The main stage.
    /// </summary>
    public sealed class Stage : BufferedVisualContainer {

        /// <summary>
        /// Creates a new <see cref="Stage"/> instance.
        /// </summary>
        /// <param name="game">The base game.</param>
        /// <param name="configurationStore">The <see cref="BaseConfigurationStore"/> for this <see cref="Stage"/>.</param>
        public Stage([NotNull] BaseGame game, [NotNull] BaseConfigurationStore configurationStore)
            // ReSharper disable once AssignNullToNotNullAttribute
            : base(game, null) {
            ConfigurationStore = configurationStore;
        }

    }
}


text:
<?php  namespace Palmabit\Catalog\Tests;
use Carbon\Carbon;
use Palmabit\Catalog\Models\Order;
use Palmabit\Catalog\Presenters\OrderPresenter;
use DB, App;
use Mockery as m;
/**
 * Test OrderPresenterTest
 *
 * @author jacopo beschi jacopo@jacopobeschi.com
 */
class OrderPresenterTest extends DbTestCase {

    public function tearDown()
    {
        m::close();
    }

    /**
     * @test
     **/
    public function it_gets_total_order_price()
    {
        $order = $this->prepareOrderData(Carbon::now());

        $presenter = new OrderPresenter($order);
        $expected_total = 44.44;

        $total = $presenter->total_price;

        $this->assertEquals($expected_total, $total);
    }

    /**
     * @test
     **/
    public function it_show_author_info()
    {
        $date = Carbon::now();
        $order = $this->prepareOrderData($date);

        $user_stub = new \StdClass;
        $expected_email = $this->createMockAuthenticatorFindById($user_stub);
        $expected_id = 1;

        $presenter = new OrderPresenter($order);
        $author_email = $presenter->author_email;
        $author_id = $presenter->author->id;

        $this->assertEquals($expected_email,$author_email);
        $this->assertEquals($expected_id,$author_id);
    }

    public function show_europe_formatted_date()
    {
        $date = Carbon::now();
        $order = $this->prepareOrderData($date);
        $presenter = new OrderPresenter($order);

        $date_formatted = $presenter->date;

        $european_Date = 'd-m-Y';
        $this->assertEquals($date->format($european_Date),$date_formatted);
    }

    protected function prepareOrderData($date)
    {
        DB::table('order')->insert([
                               "user_id" => 1,
                               "date" => $date,
                               "created_at" => $date,
                               "updated_at" => $date,
                               "completed" => 1,
                      ]);
        DB::table('row_order')->insert(
            [
                 "order_id" => 1,
                 "product_id" => 1,
                 "quantity" => 222,
                 "total_price" => 22.22,
                 "single_price" => 0.22,
                 "price_type_used" => "price1",
                 "created_at" => $date,
                 "updated_at" => $date,
            ]
        );
        DB::table('row_order')->insert(
            [
            "order_id" => 1,
            "product_id" => 1,
            "quantity" => 222,
            "total_price" => 22.22,
            "single_price" => 0.22,
            "price_type_used" => "price1",
            "created_at" => $date,
            "updated_at" => $date,
            ]
        );

        return Order::find(1);
    }

    /**
     * @param $user_stub
     * @return string
     */
    protected function createMockAuthenticatorFindById($user_stub)
    {
        $expected_email   = "mail@mail.com";
        $user_stub->email = $expected_email;
        $user_stub->id = 1;

        $mock_authenticator = m::mock('StdClass')->shouldReceive('findById')->andReturn($user_stub)->getMock();
        App::instance('authenticator', $mock_authenticator);

        return $expected_email;
    }
}


text:
<?php

namespace Sylius\Bundle\OrderBundle\Model;

use Doctrine\Common\Collections\Collection;

/**
 * Adjustable model interface.
 *
 * @author Paweł Jędrzejewski <pjedrzejewski@diweb.pl>
 */
interface AdjustableInterface
{
    /**
     * Return all adjustments attached to adjustable subject.
     *
     * @return Collection|AdjustmentInterface[]
     */
    public function getAdjustments();

    /**
     * Add adjustment.
     *
     * @param AdjustmentInterface $adjustment
     */
    public function addAdjustment(AdjustmentInterface $adjustment);

    /**
     * Remove adjustment.
     *
     * @param AdjustmentInterface $adjustment
     */
    public function removeAdjustment(AdjustmentInterface $adjustment);

    /**
     * Get adjustments total.
     *
     * @return integer
     */
    public function getAdjustmentsTotal();

    /**
     * Calculate adjustments total.
     */
    public function calculateAdjustmentsTotal();
}


text:
<?php

namespace WasabiLib\Ajax;

use Zend\Code\Exception\InvalidArgumentException;

class Response{

    private $responses = array();

    public function __construct(ResponseTypeInterface $responseType = null){
        if($responseType)
            $this->add($responseType);
    }
    /**
     * Adds an object which implements the interfaces ResponseTypeInterface or ResponseConfiguratorInterface or an
     * array of objects which implement the ResponseTypeInterface.
     * @param $object array | ResponseConfiguratorInterface | ResponseTypeInterface
     * @throws \Zend\Code\Exception\InvalidArgumentException
     */
    public function add($object){

        if(is_array($object)) {
            $this->responses = array_merge($this->responses, $object);
        } else {
            $implementedInterfaces = class_implements($object);

            if(array_key_exists("WasabiLib\Ajax\ResponseConfiguratorInterface", $implementedInterfaces)) {
                $object->configure();
//                $this->responses = array_merge($this->responses, $object->getResponseTypes());
                foreach($object->getResponseTypes() as $responseType){
                    $implementedInterfacesInResponseType = class_implements($responseType);

                    if(array_key_exists("WasabiLib\Ajax\ResponseConfiguratorInterface", $implementedInterfacesInResponseType)) {
                        $this->add($responseType);
                    }
                    else{
                        $this->responses[]=$responseType;
                    }
                }
            } else if(array_key_exists("WasabiLib\Ajax\ResponseTypeInterface", $implementedInterfaces)) {
                $this->responses[] = $object;
            } else {
                throw new InvalidArgumentException("Invalid parameter type! Given value must be an array or implements the interfaces ResponseConfiguratorInterface or ResponseTypeInterface");
            }
        }
    }

    public function getResponseTypes(){
        return $this->responses;
    }

    public function json(){
        $array = [];
        /* @var $response \WasabiLib\Ajax\ResponseType */
        foreach($this->responses as $response){
            $array[] = $response->toArray();
        }

        return json_encode($array);
    }

    public function __toString(){
        $json = "";
        try{
            $json = $this->json();
        } catch (\Exception $e) {
            print_r($e->getMessage()." ".$e->getTraceAsString());
        }
        return $json;
    }

    public function asInjectedJS() {
        $domManipulator = new DomManipulator("#wasabiInjectedScript:parent", null, null, DomManipulator::ACTION_TYPE_REMOVE_ELEMENT);
        $this->add($domManipulator);
        return "<script id='wasabiInjectedScript' type='text/javascript' >$(document).ready(function(){\$(document).trigger({type: 'wasabiNotification',message: ".$this->__toString()."});});</script>";
    }
}


text:
require 'rubygems'
require 'term/ansicolor'

class String
  include Term::ANSIColor
end
#####################################################

require 'socket'

module Dominion
  class Server

    attr_accessor :match, :number_players, :server, :sockets, :message, :kingdoms

    ###########################################################################
    #                                 S E T U P                               #
    ###########################################################################
    def initialize(port=8000)
      @server   = TCPServer.new '', port
      @sockets  = []
      @kingdoms = []
      puts "Server started on port #{port}"
    end

    def setup
      @match = Match.new :server=>self
      puts "How many players? (2-#{Game.max_players})"
      @number_players = gets.chomp.to_i
      puts "Ready to play a #{number_players} game."
      self
    end

    ###########################################################################
    #                                   P L A Y                               #
    ###########################################################################
    def run
      trap('EXIT'){ server.close }
      puts "Collecting players"
      collect_players
      broadcast("Ready to play with #{match.players.join(', ')}") unless match.players.empty?
      play = true
      while play
        broadcast 'Choosing Kingdoms for this game'
        choose_kingdoms
        @match.use = kingdoms
        scoreboard = match.play
        broadcast "\nGame Over\n#{scoreboard}\n"
        broadcast "Waiting for server to play again\n"
        puts "Play again? (y/N)"
        play = gets.chomp.downcase == 'y'
        @kingdoms = []
      end
      broadcast match
    end

    def collect_players
      trap('INT'){ exit }
      while match.players.size < number_players
        response = select [@server], nil, nil, nil
        add_player unless response.nil?
      end
    end

    def add_player
      socket = @server.accept
      @sockets << socket unless @sockets.include?(socket)
      socket.puts "#{match.players.join(', ')} are already seated in this #{number_players} player game"
      socket.puts "What's your name?"
      name = socket.gets.chomp
      player = Human.new name, socket
      match.players << player
      broadcast "#{player} joined the game"
      puts "#{player} joined the game"
    end

    def choose_kingdoms
      puts 'Choose Kingdoms for this game'
      while true
        say_available_kingdoms
        choice = gets.chomp.to_i
        return if choice == 0
        kingdom = Game.available_kingdoms(:except=>kingdoms)[choice - 1]
        @kingdoms << kingdom
        broadcast "Selected Kingdoms: #{kingdoms.collect{|k|k.new.to_s}.join ', '}"
      end
    end

    def say_available_kingdoms
      puts '0. Done'
      Game.available_kingdoms(:except=>kingdoms).each_with_index do |k, i|
        puts "#{i+1}. #{k.new.to_s}"
      end
    end

    ###########################################################################
    #                              A I    P L A Y E R S                       #
    ###########################################################################
    # Seat BigMoney at the table
    def big_money
      match.players << BigMoney.new('Big Money')
      self
    end

    # Seat Highlander at the table
    def highlander
      highlander = Highlander.new('Highlander')
      highlander.wants = [Chancellor, Smithy, Festival, CouncilRoom, Laboratory]
      match.players << highlander
      self
    end

    ###########################################################################
    #                                    I  /  O                              #
    ###########################################################################
    def broadcast(message)
      sockets.each{|d| d.puts message}
    end

  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Nest;
using Newtonsoft.Json;

namespace Nest
{
	public interface ISnapshotResponse : IResponse
	{
		[JsonProperty("accepted")]
		bool Accepted { get; }

		[JsonProperty("snapshot")]
		Snapshot Snapshot { get; set; }
	}

	[JsonObject]
	public class SnapshotResponse : BaseResponse, ISnapshotResponse
	{
		private bool _accepted = false;
		[JsonProperty("accepted")]
		public bool Accepted
		{
			get
			{
				return  _accepted ? _accepted : this.Snapshot != null;
			}
			internal set { _accepted = value; }
		}

		[JsonProperty("snapshot")]
		public Snapshot Snapshot { get; set; }

	}
}


text:
Authentification à deux facteurs
=========================

Chaque utilisateur peut activer [l'authentification à deux facteurs](http://en.wikipedia.org/wiki/Two_factor_authentication).
Après s'être connecté, un code à usage unique (6 caractères) est demandé à l'utilisateur pour lui autoriser l'accès à Kanboard.

Ce code doit être fourni par un logiciel compatible, généralement installé sur votre smartphone.

Kanboard utilise le [Time-based One-time Password Algorithm](http://en.wikipedia.org/wiki/Time-based_One-time_Password_Algorithm) défini dans la [RFC 6238](http://tools.ietf.org/html/rfc6238).

Il existe de nombreux logiciels compatibles avec le standard TOTP system.
Par exemple, vous pouvez utilisez ces applications libres et open source :

- [Google Authenticator](https://github.com/google/google-authenticator/) (Android, iOS, Blackberry)
- [FreeOTP](https://fedorahosted.org/freeotp/) (Android, iOS)
- [OATH Toolkit](http://www.nongnu.org/oath-toolkit/) (utilitaire en ligne de commande sur Unix/Linux)

Ce système peut fonctionner hors ligne et vous n'avez pas l'obligation d'avoir un téléphone portable.

Paramétrage
-----

1. Allez dans le profil utilisateur.
2. Sur la gauche, cliquez sur **Authentification à deux facteurs** et cochez la case.
3. Une clef secrète est générée pour vous.

![2FA](https://kanboard.net/screenshots/documentation/2fa.png)

- Vous devez sauvegarder votre clef dans votre logiciel TOTP. Si vous utilisez un smartphone, la solution la plus simple est de scanner le QR code avec FreeOTP ou Google Authenticator
- À chaque ouverture de session, un nouveau code sera demandé
- N'oubliez pas de tester votre appareil avant de quitter votre session

Une nouvelle clef est générée à chaque fois que vous activez/désactivez cette fonction


text:
using System;
using System.Windows.Forms;
using Microsoft.Win32;

namespace hardforward.Controller
{
    class AutoStartup
    {
        public static bool Set(bool enabled)
        {
            try
            {
                string path = Application.ExecutablePath;
                RegistryKey runKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);
                if (enabled)
                {
                    runKey.SetValue("Shadowsocks", path);
                }
                else
                {
                    runKey.DeleteValue("Shadowsocks");
                }
                runKey.Close();
                return true;
            }
            catch (Exception e)
            {
                Logging.LogUsefulException(e);
                return false;
            }
        }

        public static bool Check()
        {
            try
            {
                string path = Application.ExecutablePath;
                RegistryKey runKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
                string[] runList = runKey.GetValueNames();
                runKey.Close();
                foreach (string item in runList)
                {
                    if (item.Equals("Shadowsocks"))
                        return true;
                }
                return false;
            }
            catch (Exception e)
            {
                Logging.LogUsefulException(e);
                return false;
            }
        }
    }
}


text:
from __future__ import print_function, division
import numpy as np
import theano
import theano.tensor as T

class MLP(object):
    """
    HiddenLayer + LogisticRegression
    """

    def __init__(self, rng, input, n_in, n_hidden, n_out):
        """Initialize the parameters for the multilayer perceptron

        :type rng: numpy.random.RandomState
        :param rng: a random number generator used to initialize weights

        :type input: theano.tensor.TensorType
        :param input: symbolic variable that describes the input of the
        architecture (one minibatch)

        :type n_in: int
        :param n_in: number of input units, the dimension of the space in
        which the datapoints lie

        :type n_hidden: int
        :param n_hidden: number of hidden units

        :type n_out: int
        :param n_out: number of output units, the dimension of the space in
        which the labels lie

        """

        # Since we are dealing with a one hidden layer MLP, this will translate
        # into a HiddenLayer with a tanh activation function connected to the
        # LogisticRegression layer; the activation function can be replaced by
        # sigmoid or any other nonlinear function
        self.hiddenLayer = HiddenLayer(rng=rng, input=input,
                                       n_in=n_in, n_out=n_hidden,
                                       activation=T.tanh)

        # The logistic regression layer gets as input the hidden units
        # of the hidden layer
        self.logRegressionLayer = LogisticRegression(
            input=self.hiddenLayer.output,
            n_in=n_hidden,
            n_out=n_out)

        # L1 norm ; one regularization option is to enforce L1 norm to
        # be small
        self.L1 = abs(self.hiddenLayer.W).sum() + abs(self.logRegressionLayer.W).sum()

        # square of L2 norm ; one regularization option is to enforce
        # square of L2 norm to be small
        self.L2_sqr = (self.hiddenLayer.W ** 2).sum() + (self.logRegressionLayer.W ** 2).sum()

        # negative log likelihood of the MLP is given by the negative
        # log likelihood of the output of the model, computed in the
        # logistic regression layer
        self.negative_log_likelihood = self.logRegressionLayer.negative_log_likelihood
        # same holds for the function computing the number of errors
        self.errors = self.logRegressionLayer.errors

        # the parameters of the model are the parameters of the two layer it is
        # made out of
        self.params = self.hiddenLayer.params + self.logRegressionLayer.params

class HiddenLayer(object):
    def __init__(self, rng, input, n_in, n_out, W=None, b=None,
                 activation=T.tanh):
        """
        Typical hidden layer of a MLP: units are fully-connected and have
        sigmoidal activation function. Weight matrix W is of shape (n_in,n_out)
        and the bias vector b is of shape (n_out,).

        NOTE : The nonlinearity used here is tanh

        Hidden unit activation is given by: tanh(dot(input,W) + b)

        :type rng: numpy.random.RandomState
        :param rng: a random number generator used to initialize weights

        :type input: theano.tensor.dmatrix
        :param input: a symbolic tensor of shape (n_examples, n_in)

        :type n_in: int
        :param n_in: dimensionality of input

        :type n_out: int
        :param n_out: number of hidden units

        :type activation: theano.Op or function
        :param activation: Non linearity to be applied in the hidden
                           layer
        """
        self.input = input

        # `W` is initialized with `W_values` which is uniformely sampled
        # from sqrt(-6./(n_in+n_hidden)) and sqrt(6./(n_in+n_hidden))
        # for tanh activation function
        # the output of uniform if converted using asarray to dtype
        # theano.config.floatX so that the code is runable on GPU
        # Note : optimal initialization of weights is dependent on the
        #        activation function used (among other things).
        #        For example, results presented in [Xavier10] suggest that you
        #        should use 4 times larger initial weights for sigmoid
        #        compared to tanh
        #        We have no info for other function, so we use the same as
        #        tanh.
        if W is None:
            W_values = np.asarray(rng.uniform(
                low=-np.sqrt(6. / (n_in + n_out)),
                high=np.sqrt(6. / (n_in + n_out)),
                size=(n_in, n_out)), dtype=theano.config.floatX)
            if activation == theano.tensor.nnet.sigmoid:
                W_values *= 4

            W = theano.shared(value=W_values, name='W', borrow=True)

        if b is None:
            b_values = np.zeros((n_out,), dtype=theano.config.floatX)
            b = theano.shared(value=b_values, name='b', borrow=True)

        self.W = W
        self.b = b

        lin_output = T.dot(input, self.W) + self.b
        self.output = (lin_output if activation is None
                       else activation(lin_output))
        # parameters of the model
        self.params = [self.W, self.b]

class LogisticRegression(object):
    """Multi-class Logistic Regression Class

    The logistic regression is fully described by a weight matrix :math:`W`
    and bias vector :math:`b`. Classification is done by projecting data
    points onto a set of hyperplanes, the distance to which is used to
    determine a class membership probability.
    """

    def __init__(self, input, n_in, n_out):
        """ Initialize the parameters of the logistic regression

        :type input: theano.tensor.TensorType
        :param input: symbolic variable that describes the input of the
                      architecture (one minibatch)

        :type n_in: int
        :param n_in: number of input units, the dimension of the space in
                     which the datapoints lie

        :type n_out: int
        :param n_out: number of output units, the dimension of the space in
                      which the labels lie

        """

        # initialize with 0 the weights W as a matrix of shape (n_in, n_out)
        self.W = theano.shared(value=np.zeros((n_in, n_out),
                                                 dtype=theano.config.floatX),
                                name='W', borrow=True)
        # initialize the baises b as a vector of n_out 0s
        self.b = theano.shared(value=np.zeros((n_out,),
                                                 dtype=theano.config.floatX),
                               name='b', borrow=True)

        # compute vector of class-membership probabilities in symbolic form
        self.p_y_given_x = T.nnet.softmax(T.dot(input, self.W) + self.b)

        # compute prediction as class whose probability is maximal in
        # symbolic form
        self.y_pred = T.argmax(self.p_y_given_x, axis=1)

        # parameters of the model
        self.params = [self.W, self.b]

    def negative_log_likelihood(self, y):
        """Return the mean of the negative log-likelihood of the prediction
        of this model under a given target distribution.

        .. math::

            \frac{1}{|\mathcal{D}|} \mathcal{L} (\theta=\{W,b\}, \mathcal{D}) =
            \frac{1}{|\mathcal{D}|} \sum_{i=0}^{|\mathcal{D}|} \log(P(Y=y^{(i)}|x^{(i)}, W,b)) \\
                \ell (\theta=\{W,b\}, \mathcal{D})

        :type y: theano.tensor.TensorType
        :param y: corresponds to a vector that gives for each example the
                  correct label

        Note: we use the mean instead of the sum so that
              the learning rate is less dependent on the batch size
        """
        # y.shape[0] is (symbolically) the number of rows in y, i.e.,
        # number of examples (call it n) in the minibatch
        # T.arange(y.shape[0]) is a symbolic vector which will contain
        # [0,1,2,... n-1] T.log(self.p_y_given_x) is a matrix of
        # Log-Probabilities (call it LP) with one row per example and
        # one column per class LP[T.arange(y.shape[0]),y] is a vector
        # v containing [LP[0,y[0]], LP[1,y[1]], LP[2,y[2]], ...,
        # LP[n-1,y[n-1]]] and T.mean(LP[T.arange(y.shape[0]),y]) is
        # the mean (across minibatch examples) of the elements in v,
        # i.e., the mean log-likelihood across the minibatch.
        return -T.mean(T.log(self.p_y_given_x)[T.arange(y.shape[0]), y])

    def errors(self, y):
        """Return a float representing the number of errors in the minibatch
        over the total number of examples of the minibatch ; zero one
        loss over the size of the minibatch

        :type y: theano.tensor.TensorType
        :param y: corresponds to a vector that gives for each example the
                  correct label
        """

        # check if y has same dimension of y_pred
        if y.ndim != self.y_pred.ndim:
            raise TypeError('y should have the same shape as self.y_pred',
                ('y', target.type, 'y_pred', self.y_pred.type))
        # check if y is of the correct datatype
        if y.dtype.startswith('int'):
            # the T.neq operator returns a vector of 0s and 1s, where 1
            # represents a mistake in prediction
            return T.mean(T.neq(self.y_pred, y))
        else:
            raise NotImplementedError()


text:
import inspect
import sys
from io import StringIO

import pip2.commands.freeze
import pip2.commands.search
import tests.log
from pip2.compat import mock
from pip2.compat import packaging

@mock.patch.object(pip2.commands.freeze, 'freeze')
@mock.patch.object(packaging.pypi.xmlrpc.Client, 'search_projects')
class TestSearchAPI():
    def setup(self):
        test_proj1 = mock.Mock()
        test_proj1.name = 'test_proj1'
        test_proj1.releases = mock.MagicMock()
        test_proj1.releases[0].version = '1.5'
        test_proj1.releases[0].metadata = {}
        test_proj1.releases[0].metadata['summary'] = 'Summary for project 1'

        test_proj2 = mock.Mock()
        test_proj2.name = 'test_proj2'
        test_proj2.releases = mock.MagicMock()
        test_proj2.releases[0].version = '2.5'
        test_proj2.releases[0].metadata = {}
        test_proj2.releases[0].metadata['summary'] = 'Summary for project 2'

        test_proj3 = mock.Mock()
        test_proj3.name = 'test_proj3'
        test_proj3.releases = mock.MagicMock()
        test_proj3.releases[0].version = '3.5'
        test_proj3.releases[0].metadata = {}
        test_proj3.releases[0].metadata['summary'] = 'Summary for project 3'

        return [test_proj1, test_proj2, test_proj3]

    def test_basic_search(self, mock_search_projects, mock_freeze):
        mock_search_projects.return_value = self.setup()
        mock_freeze.return_value = {}

        expected = {'test_proj1': {'summary': 'Summary for project 1'},
                    'test_proj2': {'summary': 'Summary for project 2'},
                    'test_proj3': {'summary': 'Summary for project 3'}}

        result = pip2.commands.search.search('test')

        self.tear_down(result, expected)

    def test_basic_search_matches(self, mock_search_projects, mock_freeze):
        mock_search_projects.return_value = self.setup()
        mock_freeze.return_value = {'test_proj1': {'version': '1.0'},
                                    'test_proj3': {'version': '3.0'}}

        expected = {'test_proj1': {'summary': 'Summary for project 1',
                                   'installed_version': '1.0',
                                  'latest_version': '1.5'},
                    'test_proj2': {'summary': 'Summary for project 2'},
                    'test_proj3': {'summary': 'Summary for project 3',
                                   'installed_version': '3.0',
                                   'latest_version': '3.5'}}
        result = pip2.commands.search.search('test')

        self.tear_down(result, expected)

    def tear_down(self, result, expected):
        try:
            assert result == expected
        except AssertionError:
            print('result  : {0}'.format(result))
            print('expected: {0}'.format(expected))
            raise

@mock.patch.object(pip2.util, 'getTerminalSize')
@mock.patch.object(pip2.commands.search, 'search')
class TestSearchCLI():
    min_term_width = 40
    default_term_width = 80
    term_width = default_term_width
    name_len = 26
    sep = ' - '
    sep_len = len(sep)
    sum_len = term_width - name_len - sep_len - 1
    args = mock.Mock()
    args.project = 'pkgPlaceholder'

    def setup(self):
        result = tests.log.setup_logger()
        return result

    def test_basic_display_no_results(self, mock_search, mock_getTerminalSize):
        result = self.setup()
        self.args.project = 'nonexistantproject'
        mock_getTerminalSize.return_value = (self.term_width, None)
        mock_search.return_value = {}
        expected = 'Search returned no results...\n'
        pip2.cli_wrapper.search(self.args)
        self.tear_down(result.getvalue(), expected)

    def test_basic_display_name_short(self, mock_search, mock_getTerminalSize):
        result = self.setup()
        self.args.project = 'shortproject'
        mock_getTerminalSize.return_value = (self.term_width, None)
        mock_search.return_value = {self.args.project: {'summary': 'sum'}}
        expected = self.args.project
        expected += ' ' * (self.name_len - len(expected)) + self.sep + 'sum\n'
        pip2.cli_wrapper.search(self.args)
        self.tear_down(result.getvalue(), expected)

    def test_basic_display_name_long(self, mock_search, mock_getTerminalSize):
        result = self.setup()
        self.args.project = 'thisIsAVeryLongprojectThatCantDisplayFully'
        mock_getTerminalSize.return_value = (self.term_width, None)
        mock_search.return_value = {self.args.project: {'summary': 'sum'}}
        expected = self.args.project + self.sep + 'sum'
        expected = expected[: (self.sum_len + self.name_len +
                               self.sep_len)] + '\n'
        pip2.cli_wrapper.search(self.args)
        self.tear_down(result.getvalue(), expected)

    def test_basic_display_sum_single_line(self, mock_search,
                                           mock_getTerminalSize):
        result = self.setup()
        self.args.project = 'pkgPlaceholder'
        mock_getTerminalSize.return_value = (self.term_width, None)
        desc = 'X' * (self.sum_len)
        mock_search.return_value = {self.args.project: {'summary': desc}}
        expected = (self.args.project + ' ' * (self.name_len -
                    len(self.args.project)) + self.sep + desc + '\n')
        pip2.cli_wrapper.search(self.args)
        self.tear_down(result.getvalue(), expected)

    def test_basic_display_sum_word_wrap(self, mock_search,
                                         mock_getTerminalSize):
        result = self.setup()
        self.args.project = 'pkgPlaceholder'
        mock_getTerminalSize.return_value = (self.term_width, None)
        desc = 'X' * int(self.sum_len * 1.5)
        mock_search.return_value = {self.args.project: {'summary': desc}}
        desc_ln1 = desc[: self.sum_len]
        desc_ln2 = desc[len(desc_ln1):]
        expected = (self.args.project + ' ' * (self.name_len -
                    len(self.args.project)) + self.sep + desc_ln1 + '\n' +
                    ' ' * (self.name_len + self.sep_len) + desc_ln2 + '\n')
        pip2.cli_wrapper.search(self.args)
        self.tear_down(result.getvalue(), expected)

    def test_basic_display_matches(self, mock_search, mock_getTerminalSize):
        result = self.setup()
        self.args.project = 'pkgPlaceholder'
        mock_getTerminalSize.return_value = (self.term_width, None)
        installed = '1.0'
        latest = '1.5'
        desc = 'X' * self.sum_len
        mock_search.return_value = {self.args.project: {'summary': desc,
                                    'installed_version': installed,
                                    'latest_version': latest}}
        expected = (self.args.project + ' ' * (self.name_len -
                    len(self.args.project)) + self.sep + desc +
                    '\n\tINSTALLED: ' + installed + '\n\tLATEST   : ' +
                    latest + '\n')
        pip2.cli_wrapper.search(self.args)
        self.tear_down(result.getvalue(), expected)

    # System level test. Runs all previous tests at different terminal sizes.
    def test_system_display_terminal_scale(self, mock_search,
                                           mock_getTerminalSize):
        # test case:
        # 35  - too small must be min of 40
        # 60  - small term
        # 180 - large term
        term_widths = [35, 60, 180]

        for term_width in term_widths:
            self.term_width = term_width
            if self.term_width >= self.min_term_width:
                width_used = self.term_width
            else:
                width_used = self.min_term_width
            self.sum_len = width_used - self.name_len - self.sep_len - 1
            self._run_all_project_tests()
            self.term_width = self.default_term_width

    def _run_all_project_tests(self):
        self.test_basic_display_no_results()
        self.test_basic_display_name_short()
        self.test_basic_display_name_long()
        self.test_basic_display_sum_single_line()
        self.test_basic_display_sum_word_wrap()
        self.test_basic_display_matches()

    def tear_down(self, result, expected):
        try:
            assert result == expected
        except AssertionError:
            result = result.replace('\n', '\\n')
            expected = expected.replace('\n', '\\n')
            output = ('\nUnit test : {0}'.format(inspect.stack()[1][3]) +
                      '\nTerm width: {0}'.format(self.term_width) +
                      '\nResult    : \n{0}\n'.format(result) +
                      '\nExpected  : \n{0}'.format(expected))
            print(output)
            raise