text:
fire = {}

-- Register flame nodes

minetest.register_node("fire:basic_flame", {
	drawtype = "firelike",
	tiles = {
		{
			name = "fire_basic_flame_animated.png",
			animation = {
				type = "vertical_frames",
				aspect_w = 16,
				aspect_h = 16,
				length = 1
			},
		},
	},
	inventory_image = "fire_basic_flame.png",
	paramtype = "light",
	light_source = 14,
	walkable = false,
	buildable_to = true,
	sunlight_propagates = true,
	damage_per_second = 4,
	groups = {igniter = 2, dig_immediate = 3, not_in_creative_inventory = 1},
	on_timer = function(pos)
		local f = minetest.find_node_near(pos, 1, {"group:flammable"})
		if not f then
			minetest.remove_node(pos)
			return
		end
		-- restart timer
		return true
	end,
	drop = "",

	on_construct = function(pos)
		minetest.get_node_timer(pos):start(math.random(30, 60))
		minetest.after(0, fire.update_sounds_around, pos)
	end,

	on_destruct = function(pos)
		minetest.after(0, fire.update_sounds_around, pos)
	end,

	on_blast = function()
	end, -- unaffected by explosions
})

minetest.register_node("fire:permanent_flame", {
	description = "Permanent Flame",
	drawtype = "firelike",
	tiles = {
		{
			name = "fire_basic_flame_animated.png",
			animation = {
				type = "vertical_frames",
				aspect_w = 16,
				aspect_h = 16,
				length = 1
			},
		},
	},
	inventory_image = "fire_basic_flame.png",
	paramtype = "light",
	light_source = 14,
	walkable = false,
	buildable_to = true,
	sunlight_propagates = true,
	damage_per_second = 4,
	groups = {igniter = 2, dig_immediate = 3},
	drop = "",

	on_blast = function()
	end,
})

-- Flint and steel

minetest.register_tool("fire:flint_and_steel", {
	description = "Flint and Steel",
	inventory_image = "fire_flint_steel.png",
	on_use = function(itemstack, user, pointed_thing)
		itemstack:add_wear(1000)
		local pt = pointed_thing
		if pt.type == "node" then
			local node_under = minetest.get_node(pt.under).name
			local is_coalblock = node_under == "default:coalblock"
			local is_tnt = node_under == "tnt:tnt"
			local is_gunpowder = node_under == "tnt:gunpowder"
			if minetest.get_item_group(node_under, "flammable") >= 1 or
					is_coalblock or is_tnt or is_gunpowder then
				local flame_pos = pt.above
				if is_coalblock then
					flame_pos = {x = pt.under.x, y = pt.under.y + 1, z = pt.under.z}
				elseif is_tnt or is_gunpowder then
					flame_pos = pt.under
				end
				if minetest.get_node(flame_pos).name == "air" or
						is_tnt or is_gunpowder then
					local player_name = user:get_player_name()
					if not minetest.is_protected(flame_pos, player_name) then
						if is_coalblock then
							minetest.set_node(flame_pos,
								{name = "fire:permanent_flame"})
						elseif is_tnt then
							minetest.set_node(flame_pos,
								{name = "tnt:tnt_burning"})
						elseif is_gunpowder then
							minetest.set_node(flame_pos,
								{name = "tnt:gunpowder_burning"})
						else
							minetest.set_node(flame_pos,
								{name = "fire:basic_flame"})
						end
					else
						minetest.chat_send_player(player_name, "This area is protected")
					end
				end
			end
		end
		if not minetest.setting_getbool("creative_mode") then
			return itemstack
		end
	end
})

minetest.register_craft({
	output = "fire:flint_and_steel",
	recipe = {
		{"default:flint", "default:steel_ingot"}
	}
})

-- Override coalblock to enable permanent flame above
-- Coalblock is non-flammable to avoid unwanted basic_flame nodes

minetest.override_item("default:coalblock", {
	after_destruct = function(pos, oldnode)
		pos.y = pos.y + 1
		if minetest.get_node(pos).name == "fire:permanent_flame" then
			minetest.remove_node(pos)
		end
	end,
})

-- Get sound area of position

fire.D = 6 -- size of sound areas

function fire.get_area_p0p1(pos)
	local p0 = {
		x = math.floor(pos.x / fire.D) * fire.D,
		y = math.floor(pos.y / fire.D) * fire.D,
		z = math.floor(pos.z / fire.D) * fire.D,
	}
	local p1 = {
		x = p0.x + fire.D - 1,
		y = p0.y + fire.D - 1,
		z = p0.z + fire.D - 1
	}
	return p0, p1
end

-- Fire sounds table
-- key: position hash of low corner of area
-- value: {handle=sound handle, name=sound name}
fire.sounds = {}

-- Update fire sounds in sound area of position

function fire.update_sounds_around(pos)
	local p0, p1 = fire.get_area_p0p1(pos)
	local cp = {x = (p0.x + p1.x) / 2, y = (p0.y + p1.y) / 2, z = (p0.z + p1.z) / 2}
	local flames_p = minetest.find_nodes_in_area(p0, p1, {"fire:basic_flame"})
	--print("number of flames at "..minetest.pos_to_string(p0).."/"
	--		..minetest.pos_to_string(p1)..": "..#flames_p)
	local should_have_sound = (#flames_p > 0)
	local wanted_sound = nil
	if #flames_p >= 9 then
		wanted_sound = {name = "fire_large", gain = 0.7}
	elseif #flames_p > 0 then
		wanted_sound = {name = "fire_small", gain = 0.9}
	end
	local p0_hash = minetest.hash_node_position(p0)
	local sound = fire.sounds[p0_hash]
	if not sound then
		if should_have_sound then
			fire.sounds[p0_hash] = {
				handle = minetest.sound_play(wanted_sound,
					{pos = cp, max_hear_distance = 16, loop = true}),
				name = wanted_sound.name,
			}
		end
	else
		if not wanted_sound then
			minetest.sound_stop(sound.handle)
			fire.sounds[p0_hash] = nil
		elseif sound.name ~= wanted_sound.name then
			minetest.sound_stop(sound.handle)
			fire.sounds[p0_hash] = {
				handle = minetest.sound_play(wanted_sound,
					{pos = cp, max_hear_distance = 16, loop = true}),
				name = wanted_sound.name,
			}
		end
	end
end

-- Extinguish all flames quickly with water, snow, ice

minetest.register_abm({
	label = "Extinguish flame",
	nodenames = {"fire:basic_flame", "fire:permanent_flame"},
	neighbors = {"group:puts_out_fire"},
	interval = 3,
	chance = 1,
	catch_up = false,
	action = function(pos, node, active_object_count, active_object_count_wider)
		minetest.remove_node(pos)
		minetest.sound_play("fire_extinguish_flame",
			{pos = pos, max_hear_distance = 16, gain = 0.25})
	end,
})

-- Enable the following ABMs according to 'enable fire' setting

local fire_enabled = minetest.setting_getbool("enable_fire")
if fire_enabled == nil then
	-- New setting not specified, check for old setting.
	-- If old setting is also not specified, 'not nil' is true.
	fire_enabled = not minetest.setting_getbool("disable_fire")
end

if not fire_enabled then

	-- Remove basic flames only

	minetest.register_abm({
		label = "Remove disabled fire",
		nodenames = {"fire:basic_flame"},
		interval = 7,
		chance = 1,
		catch_up = false,
		action = minetest.remove_node,
	})

else -- Fire enabled

	-- Ignite neighboring nodes, add basic flames

	minetest.register_abm({
		label = "Ignite flame",
		nodenames = {"group:flammable"},
		neighbors = {"group:igniter"},
		interval = 7,
		chance = 12,
		catch_up = false,
		action = function(pos, node, active_object_count, active_object_count_wider)
			-- If there is water or stuff like that around node, don't ignite
			if minetest.find_node_near(pos, 1, {"group:puts_out_fire"}) then
				return
			end
			local p = minetest.find_node_near(pos, 1, {"air"})
			if p then
				minetest.set_node(p, {name = "fire:basic_flame"})
			end
		end,
	})

	-- Remove flammable nodes

	minetest.register_abm({
		label = "Remove flammable nodes",
		nodenames = {"fire:basic_flame"},
		neighbors = "group:flammable",
		interval = 5,
		chance = 18,
		catch_up = false,
		action = function(pos, node, active_object_count, active_object_count_wider)
			local p = minetest.find_node_near(pos, 1, {"group:flammable"})
			if p then
				-- remove flammable nodes around flame
				local flammable_node = minetest.get_node(p)
				local def = minetest.registered_nodes[flammable_node.name]
				if def.on_burn then
					def.on_burn(p)
				else
					minetest.remove_node(p)
					nodeupdate(p)
				end
			end
		end,
	})

end

-- Rarely ignite things from far

--[[ Currently disabled to reduce the chance of uncontrollable spreading
	fires that disrupt servers. Also for less lua processing load.

minetest.register_abm({
	nodenames = {"group:igniter"},
	neighbors = {"air"},
	interval = 5,
	chance = 10,
	action = function(pos, node, active_object_count, active_object_count_wider)
		local reg = minetest.registered_nodes[node.name]
		if not reg or not reg.groups.igniter or reg.groups.igniter < 2 then
			return
		end
		local d = reg.groups.igniter
		local p = minetest.find_node_near(pos, d, {"group:flammable"})
		if p then
			-- If there is water or stuff like that around flame, don't ignite
			if fire.flame_should_extinguish(p) then
				return
			end
			local p2 = fire.find_pos_for_flame_around(p)
			if p2 then
				minetest.set_node(p2, {name = "fire:basic_flame"})
			end
		end
	end,
})
--]]


text:
<meta property="og:title" content="{{ site.name }}" />
<meta property="og:site_name" content="{{ site.name }}" />
<meta property="og:url" content="{{ site.url }}" />
<meta property="og:description" content="{{  site.description | truncate: 200 }}" />
<meta name="og:image" content="{{ site.url }}{{ site.logo }}" />
<meta name="og:image:width" content="150" />
<meta name="og:image:height" content="150" />

redpajama_set_name: RedPajamaGithub


text:
title: ServiceWorker を使った XHR のモックテスト - Block Rockin' Codes
author: azu
layout: post
itemUrl: 'http://jxck.hatenablog.com/entry/response-injection'
editJSONPath: 'https://github.com/jser/jser.info/edit/gh-pages/data/2015/01/index.json'
date: '2015-01-17T07:21:14+00:00'
tags:
  - JavaScript
  - ServiceWorker
---
ServiceWorkerを使ったXHRのモック。
`onfetch`に登録すれば、XHR等のリクエストに対してhookができるので、事前に定義しておいたレスポンスを返すようにする。
ServiceWorkerの登録プロセスについて


text:
package org.foxbpm.web.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.zip.ZipInputStream;

import org.apache.commons.fileupload.FileItem;
import org.foxbpm.engine.impl.agent.AgentDetailsEntity;
import org.foxbpm.engine.impl.agent.AgentEntity;
import org.foxbpm.engine.impl.util.GuidUtil;
import org.foxbpm.engine.impl.util.StringUtil;
import org.foxbpm.engine.repository.DeploymentBuilder;
import org.foxbpm.engine.repository.ProcessDefinition;
import org.foxbpm.engine.repository.ProcessDefinitionQuery;
import org.foxbpm.engine.runtime.ProcessInstance;
import org.foxbpm.engine.runtime.ProcessInstanceQuery;
import org.foxbpm.web.common.constant.FoxbpmExceptionCode;
import org.foxbpm.web.common.exception.FoxbpmWebException;
import org.foxbpm.web.common.util.DateUtil;
import org.foxbpm.web.common.util.JSONUtil;
import org.foxbpm.web.common.util.Pagination;
import org.foxbpm.web.service.interfaces.IFlowManageService;
import org.springframework.stereotype.Service;

/**
 * @author yangguangftlp
 * @date 2014年6月12日
 */
@Service("flowManageServiceImpl")
@SuppressWarnings("unchecked")
public class FlowManageServiceImpl extends AbstWorkFlowService implements IFlowManageService {

	public void deployByZip(Map<String, Object> params) {
		ZipInputStream zipInputStream = null;
		try {
			FileItem file = (FileItem) params.get("processFile");
			if (null != file) {
				zipInputStream = new ZipInputStream(file.getInputStream());
				String deploymentId = StringUtil.getString(params.get("deploymentId"));
				DeploymentBuilder deploymentBuilder = modelService.createDeployment();
				deploymentBuilder.addZipInputStream(zipInputStream);
				// 有deploymentID则为更新,否则为新增
				if (StringUtil.isNotEmpty(deploymentId)) {
					deploymentBuilder.updateDeploymentId(deploymentId);
				}
				deploymentBuilder.deploy();
			}
		} catch (IOException e) {
			throw new FoxbpmWebException(e);
		} finally {
			if (null != zipInputStream) {
				try {
					zipInputStream.close();
				} catch (IOException e) {
					throw new FoxbpmWebException(e);
				}
			}
		}
	}

	public void deleteDeploy(Map<String, Object> params) {
		String deploymentId = StringUtil.getString(params.get("deploymentId"));
		try {
			if (StringUtil.isEmpty(deploymentId)) {
				throw new FoxbpmWebException(FoxbpmExceptionCode.FOXBPMEX_DEPLOYMENTID, "deploymentId is null !");
			}
			String[] deploymentIds = deploymentId.split(",");
			for (int i = 0; i < deploymentIds.length; i++) {
				modelService.deleteDeployment(deploymentIds[i]);
			}
		} catch (Exception e) {
			throw new FoxbpmWebException(e);
		}
	}

	public List<Map<String, Object>> queryProcessDef(Pagination<String> pageInfor, Map<String, Object> params) throws FoxbpmWebException {
		// 返回结果
		List<Map<String, Object>> resultData = new ArrayList<Map<String, Object>>();
		// 创建流程定义查询
		ProcessDefinitionQuery pdq = modelService.createProcessDefinitionQuery();
		String processName = StringUtil.getString(params.get("queryProcessName"));
		if (StringUtil.isNotEmpty(processName)) {
			pdq.processDefinitionNameLike(assembleLikeParam(processName));
		}
		String processId = StringUtil.getString(params.get("queryProcessId"));
		if (StringUtil.isNotEmpty(processId)) {
			pdq.processDefinitionId(processId);
		}
		String processCategory = StringUtil.getString(params.get("queryType"));
		if (StringUtil.isNotEmpty(processCategory)) {
			pdq.processDefinitionCategoryLike(assembleLikeParam(processCategory));
		}
		String queryProcessKey = StringUtil.getString(params.get("queryProcessKey"));
		if (StringUtil.isNotEmpty(queryProcessKey)) {
			pdq.processDefinitionKeyLike(assembleLikeParam(queryProcessKey));
		}

		pdq.orderByDeploymentId().desc();
		List<ProcessDefinition> pdList = null;
		if (null == pageInfor) {
			pdList = pdq.list();
		} else {
			pdList = pdq.listPagination(pageInfor.getPageIndex(), pageInfor.getPageSize());
			pageInfor.setTotal(StringUtil.getInt(pdq.count()));
		}
		Map<String, Object> attrMap = null;
		for (int i = 0, size = (null == pdList) ? 0 : pdList.size(); i < size; i++) {
			attrMap = pdList.get(i).getPersistentState();
			resultData.add(attrMap);
		}
		return resultData;
	}

	/**
	 * 查询所有流程实例信息
	 *
	 * @param pageInfor
	 *            分页对象
	 * @param params
	 *            查询条件参数
	 * @return 返回查询结果
	 * @throws FoxbpmWebException
	 */

	public List<Map<String, Object>> queryProcessInst(Pagination<String> pageInfor, Map<String, Object> params) throws FoxbpmWebException {
		// 返回结果
		List<Map<String, Object>> resultData = new ArrayList<Map<String, Object>>();
		ProcessInstanceQuery piq = runtimeService.createProcessInstanceQuery();
		// 获取查询条件参数
		String userId = StringUtil.getString(params.get("userId"));
		String processDefinitionKey = StringUtil.getString(params.get("processDefinitionKey"));
		String processInstanceId = StringUtil.getString(params.get("processInstanceId"));
		String processDefinitionName = StringUtil.getString(params.get("processDefinitionName"));
		String title = StringUtil.getString(params.get("title"));
		String bizKey = StringUtil.getString(params.get("bizKey"));
		String initor = StringUtil.getString(params.get("initor"));
		String status = StringUtil.getString(params.get("status"));
		String processType = StringUtil.getString(params.get("processType"));

		String dss = StringUtil.getString(params.get("startTimeS"));
		String dse = StringUtil.getString(params.get("startTimeE"));
		if (StringUtil.isNotEmpty(processDefinitionKey)) {
			piq.processDefinitionKey(processDefinitionKey);
		}
		if (StringUtil.isNotEmpty(processInstanceId)) {
			piq.processInstanceId(processInstanceId);
		}
		if (StringUtil.isNotEmpty(title)) {
			piq.subjectLike(assembleLikeParam(title));
		}
		if (StringUtil.isNotEmpty(bizKey)) {
			piq.processInstanceBusinessKeyLike(assembleLikeParam(bizKey));
		}
		if (StringUtil.isNotEmpty(status)) {
			piq.processInstanceStatus(status);
		}

		if (StringUtil.isNotEmpty(initor)) {
			piq.initiator(initor);
		}

		if (StringUtil.isNotEmpty(processType)) {
			if (processType.equals("initor")) {
				piq.initiator(userId);
			} else {
				piq.taskParticipants(userId);
			}

		}
		if (StringUtil.isNotEmpty(processDefinitionName)) {
			piq.processDefinitionNameLike(assembleLikeParam(processDefinitionName));
		}
		Date dates = null;
		Date datee = null;

		if (StringUtil.isNotEmpty(dss)) {
			dates = DateUtil.stringToDate(dss, "yyyy-MM-dd");
		}
		if (StringUtil.isNotEmpty(dse)) {
			String endTime = "235959999";
			dse += endTime;
			datee = DateUtil.stringToDate(dse, "yyyy-MM-ddHHmmssSSS");
		}
		if (null != dates) {
			piq.startTimeBefore(dates);
		}
		if (null != datee) {
			piq.startTimeAfter(datee);
		}

		List<ProcessInstance> piList = null;
		piq.orderByUpdateTime().desc();
		if (null == pageInfor) {
			piList = piq.list();
		} else {
			// 执行分页查询
			piList = piq.listPagination(pageInfor.getPageIndex(), pageInfor.getPageSize());
			// 设置分页信息
			pageInfor.setTotal(StringUtil.getInt(piq.count()));
		}
		// 流程实例属性集
		Map<String, Object> attrMap = null;
		ProcessInstance pi = null;
		for (int i = 0, size = (null == piList) ? 0 : piList.size(); i < size; i++) {
			pi = piList.get(i);
			attrMap = pi.getPersistentState();
			attrMap.put("processDefinitionName", modelService.getProcessDefinition(pi.getProcessDefinitionId()).getName());
			attrMap.put("initiatorName", getUserName(StringUtil.getString(attrMap.get("initiator"))));
			resultData.add(attrMap);
		}

		return resultData;
	}

	public void saveUserDelegationInfo(Map<String, Object> params) {
		String addInfo = StringUtil.getString(params.get("add"));
		String updateInfo = StringUtil.getString(params.get("update"));
		String deleteInfo = StringUtil.getString(params.get("delete"));

		String agentUser = StringUtil.getString(params.get("agentUser"));
		String agentId = StringUtil.getString(params.get("agentId"));
		String startTime = StringUtil.getString(params.get("startTime"));
		String endTime = StringUtil.getString(params.get("endTime"));
		String status = StringUtil.getString(params.get("status"));

		if (StringUtil.isNotEmpty(agentUser)) {

			AgentEntity agentEntity = new AgentEntity();
			agentEntity.setAgentFrom(agentUser);
			agentEntity.setStatus(status);
			agentEntity.setId(agentId);
			if (StringUtil.isNotEmpty(startTime)) {
				agentEntity.setStartTime(DateUtil.stringToyyyyMmDdDate(startTime));
			}
			if (StringUtil.isNotEmpty(endTime)) {
				agentEntity.setEndTime(DateUtil.stringToyyyyMmDdDate(endTime));
			}

			// 代理id为空说明是新增
			if (StringUtil.isEmpty(agentId)) {
				agentEntity.setId(GuidUtil.CreateGuid());
				identityService.addAgent(agentEntity);
			} else {
				identityService.updateAgentEntity(agentEntity);
			}

			// 新增
			if (StringUtil.isNotEmpty(addInfo)) {
				Map<String, Object> agentInfo = JSONUtil.parseJSON2Map(addInfo);
				Iterator<String> iterator = agentInfo.keySet().iterator();
				String key = null;
				AgentDetailsEntity agentDetailsEntity = null;
				while (iterator.hasNext()) {
					key = iterator.next();
					agentDetailsEntity = new AgentDetailsEntity();
					agentDetailsEntity.setId(GuidUtil.CreateGuid());
					agentDetailsEntity.setAgentId(agentEntity.getId());
					agentDetailsEntity.setAgentTo(StringUtil.getString(agentInfo.get(key)));
					agentDetailsEntity.setProcessKey(key);
					identityService.addAgentDetails(agentDetailsEntity);
				}
			}
			// 更新
			if (StringUtil.isNotEmpty(updateInfo)) {
				Map<String, Object> agentInfo = JSONUtil.parseJSON2Map(updateInfo);
				Iterator<String> iterator = agentInfo.keySet().iterator();
				String key = null;
				Map<String, String> value = null;
				AgentDetailsEntity agentDetailsEntity = null;
				while (iterator.hasNext()) {
					key = iterator.next();
					value = (Map<String, String>) agentInfo.get(key);
					agentDetailsEntity = new AgentDetailsEntity();
					agentDetailsEntity.setId(key);
					agentDetailsEntity.setAgentId(agentEntity.getId());
					agentDetailsEntity.setAgentTo(value.get("user"));
					agentDetailsEntity.setProcessKey(value.get("key"));
					identityService.updateAgentDetailsEntity(agentDetailsEntity);
				}
			}
			// 删除
			if (StringUtil.isNotEmpty(deleteInfo)) {
				StringTokenizer st = new StringTokenizer(deleteInfo, ",");
				while (st.hasMoreTokens()) {
					identityService.deleteAgentDetails(st.nextToken());
				}
			}
		}

	}

	public void deleUserDelegationInfo(Map<String, Object> params) {
		String agentInfoJson = StringUtil.getString(params.get("deleteIndex"));
		String agentId = StringUtil.getString(params.get("agentId"));
		if (StringUtil.isNotEmpty(agentId)) {
			if (StringUtil.isNotEmpty(agentInfoJson)) {
				StringTokenizer st = new StringTokenizer(agentInfoJson, ",");
				while (st.hasMoreTokens()) {
					identityService.deleteAgentDetails(st.nextToken());
				}
			}
		}
	}

}


text:
package com.example.innf.volleydemo.model.impl;

import com.example.innf.volleydemo.presenter.impl.OnQueryPhoneNumberListener;

/**
 * Author: Inno Fang
 * Time: 2016/12/23 22:42
 * Description:
 */

public interface IQueryPhoneNumberModel {
    void loadPhoneNumberInfo(String phoneNumber, OnQueryPhoneNumberListener listener);
}


text:
import { Dayjs } from "dayjs";
import { Duration } from "dayjs/plugin/duration";
import $ from "jquery";

type RunType = "run" | "segment";

export class Run {
    type: RunType;
    id: string | null;
    started: Dayjs;
    ended: Dayjs;
    isStartedSynced: boolean = false;
    isEndedSynced: boolean = false;
    rta: Duration | null = null;
    igt: Duration | null = null;
    gameName = "";
    categoryName = "";
    segmentName = "";

    constructor(type?: RunType) {
        this.type = type ?? "run";
    }

    static FromXML = function(elem: JQuery): Run {
        const run = new Run();
        run.id = elem.attr("id") ?? null;

        const startedAttr = elem.attr("started");
        if (!startedAttr) {
            // older versions of LiveSplit did not have this and it's impossible to work without it
            throw new Error("Run element has no 'started' attribute");
        }
        const endedAttr = elem.attr("ended");
        if (!endedAttr) {
            throw new Error("Run element has no 'ended' attribute");
        }

        run.started = dayjs(startedAttr, ["MM-DD-YYYY HH:mm:ss", "DD-MM-YYYY HH:mm:ss"]).utc(true);
        run.ended = dayjs(endedAttr, ["MM-DD-YYYY HH:mm:ss", "DD-MM-YYYY HH:mm:ss"]).utc(true);

        run.isStartedSynced = elem.attr("isStartedSynced")?.toLowerCase() === 'true';
        run.isEndedSynced = elem.attr("isEndedSynced")?.toLowerCase() === 'true';

        const realTimeElem = elem.children("RealTime");
        if (realTimeElem.length > 0) {
            run.rta = dayjs.duration(realTimeElem.text());
        }

        const gameTimeElem = elem.children("GameTime");
        if (gameTimeElem.length > 0) {
            run.igt = dayjs.duration(gameTimeElem.text());
        }

        run.gameName = elem.closest("Run").children("GameName")?.text().trim() ?? "";
        run.categoryName = elem.closest("Run").children("CategoryName")?.text().trim() ?? "";

        return run;
    };

    static ArrayFromXML(str: string, max?: number): Run[] {
        max = max || 20;

        const xmlDoc = $.parseXML(str);
        const $doc = $(xmlDoc);

        const $attemptsElem = $doc.find("AttemptHistory");
        if ($attemptsElem && $attemptsElem.length <= 0) { // no history
            return [];
        }

        const attempts: Run[] = [];
        const elems = $attemptsElem.children("Attempt[started]:has(RealTime)");

        // parse only the last attempts
        for (let i = elems.length - 1; i >= 0; i--) {
            try {
                const attempt = Run.FromXML($(elems[i]));
                attempts.push(attempt);
            } catch (e) {
                console.log(`Could not parse run ${i+1}`, e);
            }

            if (attempts.length >= max)
                break;
        }
        return attempts;
    }

    getTitle(): string {
        const useIgt =  this.igt !== null;
        const time = useIgt ? this.igt! : this.rta;
        let timeStr = format_time(time!.asSeconds());
        if (useIgt) {
            timeStr += " IGT (" + format_time(this.rta!.asSeconds()) + " RTA)";
        }
        let catStr = " ";

        if (this.type === "segment") {
            if (this.categoryName.length > 0)
                catStr = " (" + this.categoryName + ") ";
            return this.gameName + catStr + "- " + this.segmentName + " in " + timeStr;
        } else {
            if (this.categoryName.length > 0)
                catStr = " " + this.categoryName + " ";
            return this.gameName + catStr + "speedrun in " + timeStr;
        }
    };
}


text:
/**
 * Liquibase specific code.
 */
package org.skilltracker.app.config.liquibase;


text:
Screen3.html

This screen calls PhoneGap for retrieving device information.

    Platform:

    Version:

    UUID:

You can press one of the buttons below to get the compass reading.

    Heading:

<button type="button" onclick="getCompass();">Get Compass</button>
<button type="button" onclick="watchCompass();">Begin Watch Compass</button>
<button type="button" onclick="stopWatchCompass();">Stop Watch Compass</button>

<button type="button" onclick="loadPage('screen1.html');">Show screen 1</button>
<button type="button" onclick="loadPage('screen2.html');">Show screen 2</button>


text:
function foo() {
    function f1(arguments: number, ...restParameters) { //arguments is error
        var arguments = 10; // no error
    }
    function f12(i: number, ...arguments) { //arguments is error
        var arguments: any[]; // no error
    }
    function f1NoError(arguments: number) { // no error
        var arguments = 10; // no error
    }

    function f3(...restParameters) {
        var arguments = 10; // no error
    }
    function f3NoError() {
        var arguments = 10; // no error
    }

    function f4(arguments: number, ...rest); // no codegen no error
    function f4(arguments: string, ...rest); // no codegen no error
    function f4(arguments: any, ...rest) { // error
        var arguments: any; // No error
    }
    function f42(i: number, ...arguments); // no codegen no error
    function f42(i: string, ...arguments); // no codegen no error
    function f42(i: any, ...arguments) { // error
        var arguments: any[]; // No error
    }
    function f4NoError(arguments: number); // no error
    function f4NoError(arguments: string); // no error
    function f4NoError(arguments: any) { // no error
        var arguments: any; // No error
    }
}


text:
package tw.me.ychuang.rpc.json;

import java.lang.reflect.Type;

import org.apache.commons.lang3.ClassUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import tw.me.ychuang.rpc.Response;
import tw.me.ychuang.rpc.Result;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

/**
 * Serializes and deserializes a response to / from one JSON string.
 *
 * @author Y.C. Huang
 */
public class ResponseTypeAdapter<Respose> implements JsonSerializer<Response>, JsonDeserializer<Response> {
	private static final Logger log = LoggerFactory.getLogger(ResponseTypeAdapter.class);

	/**
	 * Serializes a response to a json element
	 */
	@Override
	public JsonElement serialize(Response response, Type responseClass, JsonSerializationContext context) {
		JsonObject jsonResponse = new JsonObject();
		jsonResponse.addProperty("id", response.getId());

		Result result = response.getResult();
		if (result == null) {
			jsonResponse.add("result", JsonNull.INSTANCE);
			return jsonResponse;
		}

		JsonObject jsonResult = new JsonObject();
		jsonResponse.add("result", jsonResult);

		Class resultClass = result.getReturnClass();
		JsonPrimitive jsonResultClass = new JsonPrimitive(resultClass.getName());
		JsonPrimitive jsonExceptional = new JsonPrimitive(result.isExceptional());

		JsonElement jsonReturn = null;
		if (result.getReturn() != null) {
			if (false == result.isExceptional()) {
				jsonReturn = context.serialize(result.getReturn(), resultClass);
			} else {
				Throwable cause = (Throwable) result.getReturn();
				String stackTraceMessage = ExceptionUtils.getStackTrace(cause);
				jsonReturn = new JsonPrimitive(stackTraceMessage);
			}
		} else {
			jsonReturn = JsonNull.INSTANCE;
		}

		jsonResult.add("return", jsonReturn);
		jsonResult.add("returnClass", jsonResultClass);
		jsonResult.add("exceptional", jsonExceptional);

		return jsonResponse;
	}

	/**
	 * Deserialize a json element to a response
	 */
	@Override
	public Response deserialize(JsonElement jsonElement, Type responseClass, JsonDeserializationContext context) throws JsonParseException {
		JsonObject jsonResponse = (JsonObject) jsonElement;
		long id = jsonResponse.getAsJsonPrimitive("id").getAsLong();
		JsonElement jsonRsElement = jsonResponse.get("result");

		Response response = null;
		if (jsonRsElement.isJsonNull()) {
			response = new Response(id, null, null);
			return response;
		}

		JsonObject jsonResult = jsonRsElement.getAsJsonObject();
		JsonElement jsonReturn = jsonResult.get("return");
		JsonPrimitive jsonReturnClass = jsonResult.getAsJsonPrimitive("returnClass");
		JsonPrimitive jsonExceptional = jsonResult.getAsJsonPrimitive("exceptional");

		Class resultClass = null;
		try {
			resultClass = ClassUtils.getClass(jsonReturnClass.getAsString());
		} catch (ClassNotFoundException e) {
			throw new JsonParseException("Cannot find a matching class by name: " + jsonReturnClass.getAsString(), e);
		}

		Result result = null;
		if (jsonReturn.isJsonNull()) {
			result = new Result(null, resultClass);

		} else {
			Object resultObj = null;

			if (resultClass.isPrimitive()) {
				resultObj = PrimitiveWrapperUtils.toPrimitive(jsonReturn.getAsString(), resultClass);

			} else if (ClassUtils.isPrimitiveOrWrapper(resultClass)) {
				resultObj = PrimitiveWrapperUtils.toPrimitiveWrapper(jsonReturn.getAsString(), resultClass);

			} else if (Throwable.class.isAssignableFrom(resultClass)) {
				resultObj = jsonReturn.getAsString();

			} else {
				resultObj = context.deserialize(jsonReturn, resultClass);
			}

			result = new Result(resultObj, resultClass);
		}

		response = new Response(id, result, resultClass.getName());

		return response;
	}
}


text:
install -Dm755 bin/ipopt $PREFIX/bin/ipopt

# Add more build steps here, if they are necessary.

# See
# http://docs.continuum.io/conda/build.html
# for a list of environment variables that are set during the build process.


text:
GameFileChoice::GameFileChoice(QWidget *parent) : QDialog(parent), ui(new Ui::GameFileChoice)
{
    ui->setupUi(this);

    m_autoChoiceTableView = new QTableWidget(0,1);
    m_autoChoiceTableView->setSelectionBehavior(QAbstractItemView::SelectRows);

    m_autoChoiceTableView->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
    m_autoChoiceTableView->verticalHeader()->hide();
    m_autoChoiceTableView->horizontalHeader()->hide();
    m_autoChoiceTableView->setShowGrid(false);
    m_autoChoiceTableView->setSelectionMode(QAbstractItemView::SingleSelection);

    ui->autoChoiceLayout->addWidget(m_autoChoiceTableView);

    ui->labelChoice->setAlignment(Qt::AlignHCenter);

    QObject::connect(m_autoChoiceTableView, SIGNAL(cellClicked(int,int)),this, SLOT(openFileOfItem(int,int)));
    QObject::connect(m_autoChoiceTableView, SIGNAL(cellDoubleClicked(int,int)),this, SLOT(openFileOfItemAndQuit(int,int)));
    QObject::connect(ui->buttonBox,SIGNAL(accepted()),this,SLOT(callReturn()));
    QObject::connect(ui->buttonChoice,SIGNAL(clicked()),this,SLOT(chooseFile()));

    m_files = findXMLFiles();
    addFilesToTableWidget(m_files);
}

GameFileChoice::~GameFileChoice()
{
    delete ui;
    delete m_autoChoiceTableView;
}

void GameFileChoice::openFileOfItem(int row, int)
{
    m_selectedPath = m_files[row];
    m_selectedFile.setFile(m_files[row]);
}

void GameFileChoice::openFileOfItemAndQuit(int row, int)
{
    m_selectedPath = m_files[row];
    m_selectedFile.setFile(m_files[row]);
    callReturn();
}

void GameFileChoice::chooseFile()
{
    QString fichierTmp = QFileDialog::getOpenFileName(NULL,"choix","../res/games");

    //on sauvegarde le dernier resultat choisi plutôt que de remplacer le path par ""
    if(fichierTmp != "")
    {
        m_selectedFile.setFile(fichierTmp);
        m_selectedPath = fichierTmp;
    }
    ui->labelChoice->setText(m_selectedFile.fileName());
}

void GameFileChoice::callReturn()
{
    emit returnSelectedPath(m_selectedFile.absoluteFilePath());
}

QStringList GameFileChoice::findXMLFiles()
{
    QStringList filtre;
    filtre << "*.xml";
    QDirIterator dirIterator("../res/games", filtre ,QDir::Files | QDir::NoSymLinks, QDirIterator::Subdirectories);
    QStringList fileList;
    while(dirIterator.hasNext()){fileList << dirIterator.next();}
    return fileList;
}

void GameFileChoice::addFilesToTableWidget(QStringList &files)
{
    for (int i = 0; i < files.size(); i++)
    {
        QTableWidgetItem *fileNameItem = new QTableWidgetItem(files[i]);

        int row = m_autoChoiceTableView->rowCount();
        m_autoChoiceTableView->insertRow(row);
        m_autoChoiceTableView->setItem(row, 0, fileNameItem);
    }
}


text:
from uliweb.form import *
from uliweb.i18n import ugettext_lazy as _
import logging

log = logging.getLogger(__name__)

class AddForm(Form):
    def form_validate(self, data):
        from uliweb.utils.common import import_attr, log
        from uliweb.orm import Model

        errors = {}

        if data['basemodel']:
            try:
                m = import_attr(data['basemodel'])
                if not (isinstance(m, type) and issubclass(m, Model)):
                    errors['basemodel'] = _("Object is not a subclass of Model")
            except Exception as e:
                log.exception(e)
                errors['basemodel'] = _("Model can't be imported")

        if data['extension_model']:
            try:
                m = import_attr(data['extension_model'])
                if not (isinstance(m, type) and issubclass(m, Model)):
                    errors['extension_model'] = _("Object is not a subclass of Model")
            except Exception as e:
                log.exception(e)
                errors['extension_model'] = _("Model can't be imported")

        return errors


text:
"""
Classes which read log data from scribe.
"""
from __future__ import print_function

from clog.scribe_net import ScribeS3, ScribeReader

from io import BytesIO
import errno
import logging
import os
import os.path
import random
import re
import socket
import sys
import time
import traceback
import signal
import yaml
from datetime import timedelta
from simplejson import load
from staticconf.errors import ConfigurationError
from tempfile import TemporaryFile

from clog import config
from clog.utils import open_compressed_file

_chunkfile_pat = re.compile(r'^(?P<stream>[a-z][-a-z0-9_]+)-(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})(-(?P<source>[^_]*))?_(?P<chunk>\d+)([.]gz)?$')

COMPRESSED_HEADER_FMT = "<Q"

SETTINGS_FILE = '/nail/srv/configs/yelp_clog.json'

class NoLogDataError(Exception):
    pass

class CLogStreamReader(object):
    """Make a stream reader for a day of :mod:`clog` entries

    :mod:`clog` entries are stored by stream name and date and broken into
    separate chunks which may or may not be compressed with gzip or bzip or be
    plaintext.

    For instance, the entries for a stream called 'foo' on New Years Day 2009
    will be laid out in the file system like

    | STREAM_DIR/foo/foo-2009-01-01_00000.gz
    | STREAM_DIR/foo/foo-2009-01-01_00001.gz
    | ...

    Example usage:

    .. code-block:: python

        reader = CLogStreamReader('stream_name', '/path/to/logs', date.today())
        for line in reader:
            print line

    :param stream_dir: the stream directory like `/storage/coraid5/scribe_logs`
    :param stream_name: the stream name like `biz_views`
    :param date: the date of the logs
    :param fail_on_missing: Fail if there are no log files for the specified
        stream and date
    """

    def __init__(self, stream_name, stream_dir, date, fail_on_missing=False):
        self.stream_dir = stream_dir
        self.stream_name = stream_name
        self.date = date
        self.fail_on_missing = fail_on_missing

    def __repr__(self):
        return '%s(%r, %r, %r)' % (self.__class__.__name__, self.stream_name, self.stream_dir, self.date)

    def chunk_filenames(self):
        """Get an iterator for all the chunk filenames"""
        if not self.stream_name:
            return []
        stream_path = os.path.join(self.stream_dir, self.stream_name)

        result = []
        for root, _dirnames, filenames in os.walk(stream_path):
            for filename in filenames:
                chunk_match = _chunkfile_pat.match(filename)
                if chunk_match:
                    year = int(chunk_match.groupdict()['year'])
                    month = int(chunk_match.groupdict()['month'])
                    day = int(chunk_match.groupdict()['day'])
                    if (year, month, day) == (self.date.year, self.date.month,
                            self.date.day):
                        result.append(os.path.join(root, filename))

        if not result and self.fail_on_missing:
            raise NoLogDataError((stream_path, self.date))

        return sorted(result)

    def __iter__(self):
        return iter(CLogStreamIterator(self))

class CLogStreamIterator(object):
    """Iterator used by :class:`ClogStreamReader` for  iterating over lines
    of chunks of a stream.
    """
    log = logging.getLogger('yelp_lib.clog.CLogStreamIterator')

    def __init__(self, stream_reader, line_num=-1, current_chunk=None, chunk_line_num=-1):
        self.stream_reader = stream_reader
        self.line_num = line_num
        self.chunk_line_num = chunk_line_num
        self.current_chunk = current_chunk

    def __iter__(self):
        """Iterate over all the lines for all of the chunk files for this
        reader's stream and date.

        Yields
        byte string, A line in a chunk file;  e.g. an Apache access log line
        """
        self.line_num = 0
        for chunk_filename in self.stream_reader.chunk_filenames():
            self.log.debug('opening chunk: %s', (chunk_filename, ))

            try:
                self.current_chunk = open_compressed_file(chunk_filename, mode='r')
            except IOError as e:
                if e.errno == errno.ENOENT:
                    # maybe the file was compressed during iteration (see #9735)
                    for ext in ('.gz', '.bz2'):
                        compressed_name = chunk_filename + ext
                        if os.path.exists(compressed_name):
                            self.current_chunk = open_compressed_file(compressed_name, mode='r')
                            break
                    else:
                        raise
                else:
                    raise

            for line in self.current_chunk:
                self.line_num += 1
                self.chunk_line_num += 1
                yield line
            self.current_chunk.close()
            self.current_chunk = None
            self.chunk_line_num = -1

class StreamTailerSetupError(Exception):

    def __init__(self, host, port, message):
        super(StreamTailerSetupError, self).__init__()
        self.host = host
        self.port = port
        self.message = message

    def __str__(self):
        return "StreamTailerSetupError %s:%s -- %s" % (self.host, self.port, self.message)

    def __repr__(self):
        return "<StreamTailerSetupError host=%r port=%r message=%r>" % (self.host, self.port, self.message)

def get_settings(setting):
    with open(SETTINGS_FILE) as settings_file:
        settings = load(settings_file)
    return settings[setting]

def find_tail_host(host=None):
    try:
        if not host:
            host = get_settings('DEFAULT_SCRIBE_TAIL_HOST')
        tail_host = get_settings('HOST_TO_TAIL_HOST')[host]
        if tail_host == 'local':
            ecosystem = get_ecosystem_from_file()
            if ecosystem == 'prod':
                region = get_region_from_file()
                tail_host = get_settings('REGION_TO_TAIL_HOST')[region]
            else:
                tail_host = get_settings('ECOSYSTEM_TO_TAIL_HOST')[ecosystem]
    except KeyError:
        tail_host = host
    except IOError:
        raise
    return tail_host

class StreamTailer(object):
    """Tail a Scribe stream from a tailing server

    Example Usage:

    .. code-block:: python

        tailer = StreamTailer('stream_name', host, port)
        for line in tailer:
            print line

    Configuration:

    This class can be configured by passing a host and port to the constructor
    or by using :mod:`staticconf` with the following setting:

    **scribe_tail_services**
        (list of dicts {'host': host, 'port': port})
        list of host and port addresses of scribe endpoints for tailing logs
        in real time.

    :param stream: the name of the string like 'ranger'
    :type  stream: string
    :param host: the host name
    :type  host: string
    :param port: the port to connect to
    :type  port:
    :param bufsize: the number of bytes to buffer
    :param automagic_recovery: continue to retry connection forever
    :type  automagic_recovery: bool
    :param add_newline: add newlines to the items yielded in the iter
    :type  add_newlines: bool
    :param raise_on_start: raise an error if you get a disconnect immediately
                           after starting (otherwise, returns silently),
                           Default True
    :type  raise_on_start: bool
    :param timeout: connection timeout
    :type  timeout: int
    :param reconnect_callback: callback called when reconnecting
    :type  reconnect_callback: function
    :param protocol_opts: optional protocol parameters
    :type  protocol_opts: dict
    """

    scribe_tail_services = config.clog_namespace.get_list(
        'scribe_tail_services',
        default=None,
        help="List of Scribe endpoints for tailing, "
             "in the form {'host': host, 'port': port}")

    def __init__(self,
                 stream,
                 host=None,
                 port=None,
                 bufsize=4096,
                 automagic_recovery=True,
                 add_newlines=True,
                 raise_on_start=True,
                 timeout=None,
                 reconnect_callback=None,
                 use_kafka=config.use_kafka,
                 lines=None,
                 protocol_opts=None):
        if host is None or port is None:
            try:
                primary_tail_host = random.choice(self.scribe_tail_services)
                host = primary_tail_host['host']
                port = primary_tail_host['port']
            except (IndexError, ConfigurationError):
                host = find_tail_host()
                port = config.default_scribe_tail_port.value

        if use_kafka and not host.startswith('scribekafkaservices-'):
            self.host = find_tail_host(host)
        else:
            self.host = host

        self.port = port
        self.bufsize = bufsize
        self._stream = stream
        self._automagic_recovery = automagic_recovery
        self._add_newlines = add_newlines
        self._raise_on_start = raise_on_start
        self.timeout = timeout
        self._fd = None
        self._running = True
        self._reconnect_callback = reconnect_callback
        self._lines = lines
        self._protocol_opts = protocol_opts
        if self._lines:
            if not use_kafka:
                raise Exception("Last n lines can be only used with new kafka tailer")
            self._automagic_recovery = False
        signal.signal(signal.SIGTERM, self.handle_sigterm)

    def handle_sigterm(self, signum, frame):
        self._running = False
        self.close()

    def connect(self):
        for socket_info in socket.getaddrinfo(self.host,
                                              self.port,
                                              0,
                                              socket.SOCK_STREAM,
                                              0):

            family, socktype, proto, _canonname, sockaddr = socket_info
            try:
                fd = socket.socket(family, socktype, proto)
                fd.settimeout(self.timeout)
                fd.connect(sockaddr)
                self._fd = fd
                break
            except socket.error:
                pass
        if not self._fd:
            raise StreamTailerSetupError(
                    self.host,
                    self.port,
                    'Failed to connect (stream %r)' % (self._stream,))
        bytes_sent = 0
        msg = construct_conn_msg(self._stream, self._lines, self._protocol_opts).encode('utf8')
        while bytes_sent < len(msg):
            bytes_sent += self._fd.send(msg[bytes_sent:])

    def _recv_plaintext(self):
        return self._fd.recv(self.bufsize)

    def _recv_bytes(self, sock, size):
        """Read and return the next 'size' bytes from 'sock'."""
        buf = BytesIO()
        bytes_read = 0

        while bytes_read < size:
            data = sock.recv(size - bytes_read)
            if not data:
                return
            buf.write(data)
            bytes_read += len(data)

        return buf.getvalue()

    def _sockiter(self):
        at_start = True
        buffered = []
        newline_char = b'\n' if self._add_newlines else b''
        def reconnect():
            self._call_reconnect_callback()
            while not self._fd:
                try:
                    print("socket error, reconnecting", file=sys.stderr)
                    self.connect()
                except socket.error:
                    time.sleep(2)

        while self._running:
            try:
                dat = self._recv_plaintext()

                if not dat:
                    self._fd.close()
                    self._fd = None
                    if at_start:
                        if self._raise_on_start:
                            raise StreamTailerSetupError(
                                    self.host,
                                    self.port,
                                    'No data in stream %r' % (self._stream,))
                        else:
                            return
                    elif self._automagic_recovery and self._running:
                        reconnect()
                    else:
                        return
                at_start = False
                lines = dat.split(b'\n')
                if len(lines) > 1:
                    yield b''.join(buffered) + lines[0] + newline_char
                    for l in lines[1:-1]:
                        yield l + newline_char
                    buffered = lines[-1:]
                else:
                    buffered += lines
            except socket.error:
                if self._automagic_recovery:
                    reconnect()
                else:
                    raise

    def __iter__(self):
        if not self._fd:
            self.connect()
        return self._sockiter()

    def close(self):
        if self._fd:
            self._fd.close()

    def _call_reconnect_callback(self):
        try:
            if self._reconnect_callback is not None:
                self._reconnect_callback()
        except:
            traceback.print_exc()

    def list_streams(self):
        """Get a context manager to use for reading list names"""
        towrite = ""
        return NetCLogStreamReader._ContextManager(
            self,
            towrite,
            protocol_opts=self._protocol_opts,
        )

def construct_conn_msg(stream, lines=None, protocol_opts=None):
    """Return a connnection message

    :param stream: stream name
    :param lines: number of messages to consume
    :param protocol_opts: optional arguments
    """
    connection_msg = stream
    if lines:
        connection_msg += ' {0}'.format(lines)
    if protocol_opts:
        connection_msg += ''.join([' {0}={1}'.format(k, v) for k, v in protocol_opts.items()])
    return connection_msg + '\n'

def read_s3_keypair():
    with open("/etc/boto_cfg/scribereader.yaml") as f:
        aws_creds = yaml.load(f.read())
        return aws_creds['aws_access_key_id'], aws_creds['aws_secret_access_key']

def get_s3_info(hostname, stream_name=None):
    """Returns (s3_host, s3_bucket(s), s3_prefix)

    If no stream name is provided (i.e. None), both normal and tmp buckets are
    returned as a dict.
    """
    ecosystem = get_ecosystem(hostname)
    buckets = get_settings('ECOSYSTEM_TO_BUCKETS')[ecosystem]
    if stream_name:
        return get_settings('S3_HOST'), get_bucket(buckets, stream_name)
    return get_settings('S3_HOST'), buckets

def _split_bucket_and_prefix(bucket):
    bucket_prefix = bucket.split('/', 1)
    if len(bucket_prefix) == 1:
        return bucket_prefix[0], None
    else:
        return tuple(bucket_prefix)

def get_ecosystem(hostname):
    if hostname == 'scribe.local.yelpcorp.com':
        return get_ecosystem_from_file()
    else:
        return get_settings('HOST_TO_ECOSYSTEM')[hostname]

def get_ecosystem_from_file():
    with open("/nail/etc/ecosystem") as f:
        return f.read().strip()

def get_region_from_file():
    with open("/nail/etc/region") as f:
        return f.read().strip()

def get_bucket(buckets, stream_name):
    if stream_name.startswith('tmp_'):
        return buckets['tmp']
    else:
        return buckets['standard']

class NetCLogStreamReader(object):
    """Read logs from a scribe server

    .. note::

        This reader will stream logs from the source, it is not recommended
        for large logs.  Use a mrjob instead.

    Example usage:

    .. code-block:: python

        stream_reader = NetCLogStreamReader()
        with stream_reader.read_date_range(
                'ranger',
                date(2010, 1, 1),
                date(2010,12,31)
        ) as reader:
            for line in reader:
                print line

    Configuration:

    This class can be configured either by passing a `host` and `port` to
    the constructor, or by using :mod:`staticconf` to with the following
    settings

    **scribe_net_reader.host**
        hostname of the scribe server used to stream scribe logs

    **scribe_net_reader.port**
        port of the scribe server used to stream scribe logs

    :param bufsize: How many bytes to buffer internally
    :param host: The host to connect to (defaults to scribe_net_reader.host)
    :param port: The port to connect to (defaults to scribe_net_reader.port)
    :param automagic_recovery: Whether to tail the stream, continuously
        retrying the connection (defaults to False)
    """

    reader_host = config.clog_namespace.get_string('scribe_net_reader.host',
                                                   default=None)
    reader_port = config.clog_namespace.get_int('scribe_net_reader.port',
                                                default=None)

    def __init__(self, bufsize=1024, host=None, port=None, automagic_recovery=False, localS3=config.localS3):
        self.host = host or self.reader_host.value
        self.port = port or self.reader_port.value
        self.bufsize = int(bufsize)
        self.automagic_recovery = automagic_recovery
        self.localS3 = localS3

        self.aws_access_key_id, self.aws_secret_access_key = read_s3_keypair()

    class _ContextManager(object):
        """Root context manager. Does not issue any commands.

        All of these context managers strip the newlines when reading.
        """

        def __init__(self, stream_reader, message, protocol_opts=None):
            self.stream_reader = stream_reader
            self.message = message
            self.protocol_opts = protocol_opts

        def _connect(self):
            self._reader = StreamTailer(self.message,
                                        self.stream_reader.host,
                                        self.stream_reader.port,
                                        self.stream_reader.bufsize,
                                        automagic_recovery=False,
                                        add_newlines=False,
                                        raise_on_start=False,
                                        use_kafka=False,
                                        protocol_opts=self.protocol_opts)

        def __enter__(self):
            self._connect()
            return self._reader

        def __exit__(self, exc_type, exc_value, traceback):
            return self._reader.close()

    class DateRangeContextManager(object):
        def __init__(self, host, stream_name, start_date, end_date, aws_access_key_id, aws_secret_access_key):
            self.stream_name = stream_name
            self.start_date = start_date
            self.end_date = end_date
            s3_host, s3_bucket = get_s3_info(host, stream_name)
            bucket, prefix = _split_bucket_and_prefix(s3_bucket)
            self.s3_connection = ScribeS3(
                s3_host=s3_host,
                s3_bucket=bucket,
                s3_key_prefix=prefix,
                aws_access_key_id=aws_access_key_id,
                aws_secret_access_key=aws_secret_access_key,
            )

        def __enter__(self):
            return self

        def __exit__(self, exc_type, exc_value, traceback):
            pass

        def __iter__(self):
            current_date = self.start_date
            while self.end_date >= current_date:
                with TemporaryFile() as temp_file:
                    self.reader = ScribeReader(
                        self.stream_name,
                        s3_connections=[self.s3_connection],
                        ostream=temp_file
                    )

                    for _ in self.reader.get_for_date(current_date):
                        temp_file.flush()
                        temp_file.seek(0)
                        for line in temp_file:
                            # Python 3 will return byte arrays instead of str
                            if isinstance(line, str):
                                yield line
                            else:
                                yield line.decode('utf-8')
                        temp_file.seek(0)
                        temp_file.truncate(0)

                    current_date += timedelta(1)

    def read_date_range(self, stream_name, start_date, end_date):
        """Get a context manager to use for reading a stream for a date range"""
        if self.localS3:
            return NetCLogStreamReader.DateRangeContextManager(
                self.host,
                stream_name,
                start_date,
                end_date,
                self.aws_access_key_id,
                self.aws_secret_access_key,
            )
        else:
            towrite = "get %s %04d-%02d-%02d %04d-%02d-%02d" % (stream_name,
                                                                start_date.year,
                                                                start_date.month,
                                                                start_date.day,
                                                                end_date.year,
                                                                end_date.month,
                                                                end_date.day)
            return NetCLogStreamReader._ContextManager(self, towrite)

    class ListContextManager(object):
        def __init__(self, host, aws_access_key_id, aws_secret_access_key):
            s3_host, s3_buckets = get_s3_info(host)
            s3_bucket, s3_prefix = _split_bucket_and_prefix(s3_buckets['standard'])
            s3_tmp_bucket, s3_tmp_prefix = _split_bucket_and_prefix(s3_buckets['tmp'])

            s3_connection = ScribeS3(
                s3_host=s3_host,
                s3_bucket=s3_bucket,
                s3_key_prefix=s3_prefix,
                aws_access_key_id=aws_access_key_id,
                aws_secret_access_key=aws_secret_access_key,
            )
            streams = s3_connection.streams

            if s3_bucket != s3_tmp_bucket:
                s3_tmp_connection = ScribeS3(
                    s3_host=s3_host,
                    s3_bucket=s3_tmp_bucket,
                    s3_key_prefix=s3_tmp_prefix,
                    aws_access_key_id=aws_access_key_id,
                    aws_secret_access_key=aws_secret_access_key,
                )
                tmp_streams = s3_tmp_connection.streams
            else:
                tmp_streams = []

            self.streams = streams.union(tmp_streams)

        def __enter__(self):
            return self.streams

        def __exit__(self, exc_type, exc_value, traceback):
            pass

    def list_streams(self):
        """Get a context manager to use for reading list names"""
        if self.localS3:
            return NetCLogStreamReader.ListContextManager(self.host, self.aws_access_key_id, self.aws_secret_access_key)
        else:
            towrite = "list"
            return NetCLogStreamReader._ContextManager(self, towrite)


text:
[![Build Status](https://travis-ci.org/rfrancis/asdf-nim.svg?branch=master)](https://travis-ci.org/rfrancis/asdf-nim)

nim plugin for the asdf version manager

NEEDED: Someone to take over maintenance of this plugin.


text:
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}

module BotCommands
    ( BotCmd (..)
    , addNote
    , readCommand
    , showNew
    , showOld
    ) where

import           Control.Monad (void)
import           Data.Char (isSpace)
import           Data.Foldable (for_)
import           Data.Text (Text)
import qualified Data.Text as Text
import           Database.Persist.Extra (Entity (..), SelectOpt (Desc, LimitTo),
                                         getKeyByValue, insertBy, insert_,
                                         selectValList, (==.))
import           Web.Telegram.API.Bot (ChatId (..), TelegramClient,
                                       sendMessageM, sendMessageRequest)

import DB (EntityField (NoteId, NoteOwner), Note (..), User (..), runDB)

data BotCmd = ShowNew | ShowOld | WrongCommand Text

sendMessage :: Integer
            -> Text
            -> TelegramClient ()
sendMessage chatId message = void . sendMessageM $
    sendMessageRequest (ChatId chatId) message

showNew :: Integer -- ^ ChatId for sending notes
        -> Int -- ^ UserId - who wants to show
        -> TelegramClient ()
showNew chatId userId = do
    mUid <- runDB $ getKeyByValue DB.User{userTelegramId = fromIntegral userId}
    case mUid of
        Just uid -> do
            notes <- runDB $
                selectValList [NoteOwner ==. uid] [LimitTo 3, Desc NoteId]
            for_ notes $ \Note{noteText} ->
                sendMessage chatId noteText
        Nothing ->
            sendMessage chatId "Записей нет."

showOld :: Integer -- ^ ChatId for sending notes
        -> Int -- ^ UserId - who wants to show
        -> TelegramClient ()
showOld chatId userId = do
    mUid <- runDB $ getKeyByValue DB.User{userTelegramId = fromIntegral userId}
    case mUid of
        Just uid -> do
            notes <- runDB $
                selectValList [NoteOwner ==. uid] [LimitTo 3]
            for_ notes $ \Note{noteText} ->
                sendMessage chatId noteText
        Nothing ->
            sendMessage chatId "Записей нет."

addNote :: Int -- ^ UserId - who wants to insert
        -> Text -- ^ Note to insert
        -> TelegramClient ()
addNote userId note = do
    uid <-
        runDB $
            either entityKey id <$>
            insertBy DB.User{userTelegramId = fromIntegral userId}
    runDB $ insert_ Note{noteText = note, noteOwner = uid}

readCommand :: Text -> Maybe BotCmd
readCommand messageText =
    case Text.uncons slashCommand of
        Just ('/', tTail) ->
            case Text.strip tTail of
                "show_new" -> Just ShowNew
                "show_old" -> Just ShowOld
                wrongCmd   -> Just (WrongCommand wrongCmd)
        _ -> Nothing
  where slashCommand = Text.takeWhile (not . isSpace) messageText


text:
#ifndef PSORT_ALLTOALL_H
#define PSORT_ALLTOALL_H

#include "psort_util.h"

namespace vpsort {
  using namespace std;

  template <typename _RandomAccessIter, typename _ValueType, typename _Distance>
    static void alltoall (vector< vector<_Distance> > &right_ends,
			  _RandomAccessIter first,
			  _RandomAccessIter last,
			  _ValueType *trans_data,
			  _Distance *boundaries,
			  MPI_Datatype &MPI_valueType,
			  MPI_Datatype &MPI_distanceType,
			  MPI_Comm comm) {

    int nproc, rank;
    MPI_Comm_size (comm, &nproc);
    MPI_Comm_rank (comm, &rank);

    // Should be _Distance, but MPI wants ints
    char errMsg[] = "32-bit limit for MPI has overflowed";
    _Distance n_loc_ = last - first;
    if (n_loc_ > INT_MAX) throw std::overflow_error(errMsg);
    int n_loc = static_cast<int> (n_loc_);

    // Calculate the counts for redistributing data
    int *send_counts = new int[nproc];
	int *send_disps = new int[nproc];
    for (int i = 0; i < nproc; ++i) {
      _Distance scount = right_ends[i + 1][rank] - right_ends[i][rank];
      if (scount > INT_MAX) throw std::overflow_error(errMsg);
      send_counts[i] = static_cast<int> (scount);
    }
    send_disps[0] = 0;
    partial_sum (send_counts, send_counts + nproc - 1, send_disps + 1);

    int *recv_counts = new int[nproc];
	int *recv_disps = new int[nproc];
    for (int i = 0; i < nproc; ++i) {
      _Distance rcount = right_ends[rank + 1][i] - right_ends[rank][i];
      if (rcount > INT_MAX) throw std::overflow_error(errMsg);
      recv_counts[i] = static_cast<int> (rcount);
    }

    recv_disps[0] = 0;
    partial_sum (recv_counts, recv_counts + nproc - 1, recv_disps + 1);

    assert (accumulate (recv_counts, recv_counts + nproc, 0) == n_loc);

    // Do the transpose
    MPI_Alltoallv (first, send_counts, send_disps, MPI_valueType,
                   trans_data, recv_counts, recv_disps, MPI_valueType, comm);

    for (int i=0; i<nproc; ++i) boundaries[i] = (_Distance) recv_disps[i];
    boundaries[nproc] = (_Distance) n_loc;  // for the merging

	delete [] recv_counts;
	delete [] recv_disps;

	delete [] send_counts;
	delete [] send_disps;
    return;
  }

}

#endif /* PSORT_ALLTOALL_H */


text:
export interface State {
    abbreviation: string;
    name: string;
}


text:
This is a node.js module, writen in C++, that uses libjpeg to produce a JPEG
image (in memory) from a buffer of RGBA or RGB values. Since JPEG has no notion
of A (alpha), the module always uses just RGB values.

It was written by Peteris Krumins (peter@catonmat.net).
His blog is at http://www.catonmat.net  --  good coders code, great reuse.

------------------------------------------------------------------------------

## Intallation
```javascript
    npm install jpeg-fresh
```

## Basics

The module exports three objects: Jpeg, FixedJpegStack, DynamicJpegStack.

Jpeg allows to create fixed size jpegs from RGB, BGR, RGBA or BGRA buffers.
FixedJpegStack allows to push multiple jpegs to a fixed size canvas.
DynamicJpegStack allows to push multiple jpegs to a dynamic size canvas (it
grows as you push jpegs to it).

All objects provide synchronous and asynchronous interfaces.

## Jpeg

Jpeg object that takes 4 arguments in its constructor:

```javascript
    var Jpeg = require('jpeg-fresh').Jpeg;
    var jpeg = new Jpeg(buffer, width, height, [buffer_type]);
```

The first argument, `buffer`, is a nodee.js `Buffer` filled with RGBA or RGB
values.
The second argument is integer width of the image.
The third argument is integer height of the image.
The fourth argument is buffer type, either 'rgb' or 'rgba'. [Optional].

After you have constructed the object, call .encode() or .encodeSync to produce
a jpeg:
```javascript
    var jpeg_image = jpeg.encodeSync(); // synchronous encoding (blocks node.js)
```
Or:
```javascript
    jpeg.encode(function (image, error) {
        // jpeg image is in 'image'
    });
```
See `examples/` directory for examples.

## FixedJpegStack

First you create a FixedJpegStack object of fixed width and height:
```javascript
    var stack = new FixedJpegStack(width, height, [buffer_type]);
```
Then you can push individual fragments to it, for example,
```javascript
    stack.push(buf1, 10, 11, 100, 200); // pushes buf1 to (x,y)=(10,11)
                                        // 100 and 200 are width and height.

    // more pushes
```
After you're done, call `.encode()` to produce final jpeg asynchronously or
`.encodeSync()` (just like in Jpeg object). The final jpeg will be of size
width x height.

## DynamicJpegStack

DynamicJpegStack is the same as FixedJpegStack except its canvas grows dynamically.

First, create the stack:
```javascript
    var stack = new DynamicJpegStack([buffer_type]);
```
Next push the RGB(A) buffers to it:
```javascript
    stack.push(buf1, 5, 10, 100, 40);
    stack.push(buf2, 2, 210, 20, 20);
```
Now you can call `encode` to produce the final jpeg:
```javascript
    var jpeg = stack.encodeSync();
```
Now let's see what the dimensions are,
```javascript
    var dims = stack.dimensions();
```
Same asynchronously:
```javascript
    stack.encode(function (jpeg, dims) {
        // jpeg is the image
        // dims are its dimensions
    });
```
In this particular example:

The x position `dims.x` is 2 because the 2nd jpeg is closer to the left.
The y position `dims.y` is 10 because the 1st jpeg is closer to the top.
The width `dims.width` is 103 because the first jpeg stretches from x=5 to
x=105, but the 2nd jpeg starts only at x=2, so the first two pixels are not
necessary and the width is 105-2=103.
The height `dims.height` is 220 because the 2nd jpeg is located at 210 and
its height is 20, so it stretches to position 230, but the first jpeg starts
at 10, so the upper 10 pixels are not necessary and height becomes 230-10= 220.

## MIT license


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta name="robots" content="noindex,nofollow" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="generator" content="0.11.1 (2b48ae40ea1b)" />
<meta http-equiv="X-UA-Compatible" content="IE=8" />
<link rel="icon" href="/source/default/img/icon.png" type="image/png" />
<link rel="stylesheet" type="text/css" media="all"
    title="Default" href="/source/default/style.css" />
<link rel="alternate stylesheet" type="text/css" media="all"
    title="Paper White" href="/source/default/print.css" />
<link rel="stylesheet" type="text/css" href="/source/default/print.css" media="print" />
<link rel="stylesheet" type="text/css" href="/source/default/jquery.tooltip.css" />

<link rel="search" href="/source/opensearch"
    type="application/opensearchdescription+xml"
    title="OpenGrok Search for current project(s)" />

<title>Cross Reference: /kde/Libraries/kactivities/cmake/modules/c++11-test-unique_ptr-none.cpp</title>

        <form action="/source/search">

    {Code
    Search

Cross Reference: c++11-test-unique_ptr-none.cpp

    <tt>xref: /kde/Libraries/kactivities/cmake/modules/c++11-test-unique_ptr-none.cpp</tt>

Home

History

Annotate

Line#

Navigate

Download

<input type="text" id="search" name="q" class="q" />
            <input type="submit" value="Search" class="submit" />

<input type="checkbox" name="path" value="/kde/Libraries/kactivities/cmake/modules/" /> only in c++11-test-unique_ptr-none.cpp

    <input type="hidden" name="project" value="kde" />

        </form>

1#include <memory>
2#include <string>
3#include <iostream>
4#include <utility>
5
6struct Question {
7    long answer;
8    std::string description;
9};
10
11int main()
12{
13    std::unique_ptr < Question > node_original(new Question());
14
15    node_original->answer = 42;
16    node_original->description = "The Answer to the Ultimate Question of Life, the Universe, and Everything";
17
18    std::unique_ptr < Question > node_second(std::move(node_original));
19
20    return (!node_original && (node_second->answer == 42))?0:1;
21}
22

Indexes created Fri Apr 19 11:21:17 CEST 2013

Impressum (legal notice)


text:
package org.xsalefter.springhibernate.service;

import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author xsalefter (xsalefter@gmail.com)
 */
@Service
public interface ApplicationLogService {

    @Transactional
    public List selectAll();

    @Transactional
    public List selectAllWithDTO();
}


text:
// Testacular configuration
// Generated on Fri Nov 30 2012 19:19:10 GMT-0600 (CST)

// base path, that will be used to resolve files and exclude
basePath = '.';

// list of files / patterns to load in the browser
files = [
  JASMINE,
  JASMINE_ADAPTER,
  'build/*.js',
  'lib/jasmine-sinon.js',
  'lib/sinon-1.5.2.js',
  'test/**/*.js'
];

// list of files to exclude
exclude = [

];

// test results reporter to use
// possible values: 'dots', 'progress', 'junit'
reporters = ['progress'];

// web server port
port = 8080;

// cli runner port
runnerPort = 9100;

// enable / disable colors in the output (reporters and logs)
colors = true;

// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel = LOG_INFO;

// enable / disable watching file and executing tests whenever any file changes
autoWatch = true;

// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers = ['Chrome'];

// If browser does not capture in given timeout [ms], kill it
captureTimeout = 5000;

// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun = false;


text:
// Generated by CoffeeScript 1.10.0

/**
 * app
 * @module mcore/app
 * @author vfasky <vfasky@gmail.com>
 */
"use strict";
var $, Stapes, config, exports, route, util;

$ = require('jquery');

Stapes = require('stapes');

route = require('./route');

util = require('./util');

config = require('./config')();

exports = module.exports = Stapes.subclass({
  constructor: function($el1, options) {
    this.$el = $el1;
    if (options == null) {
      options = {};
    }
    this.options = $.extend({
      viewClass: 'mcore-app-view',
      routeChange: route.Route.changeByLocationHash
    }, options);
    this.router = new route.Route(this.options.routeChange);
    this.curView = null;
    this._onLoadViw = false;
    this._middlewares = [];
  },
  route: function(path, viewName) {
    var self;
    self = this;
    this.router.add(path, function() {
      return self.runView(viewName, this, arguments);
    });
    return this;
  },
  use: function(middleware) {
    this._middlewares.push(middleware);
    return this;
  },
  _runView: function(done) {
    if (done == null) {
      done = function() {};
    }
    this.curView.instantiate.route = this.env.route;
    this.curView.instantiate.context = this.env.context;
    this.curView.instantiate.run.apply(this.curView.instantiate, this.env.args);
    this.emit('runView', this.curView);
    return done(this.curView.instantiate);
  },
  stack: function(ix, err, done) {
    var middleware, next, nextIx;
    if (ix == null) {
      ix = 0;
    }
    if (err == null) {
      err = null;
    }
    if (done == null) {
      done = function() {};
    }
    if (ix === this._middlewares.length) {
      return this._runView(done);
    }
    middleware = this._middlewares[ix];
    nextIx = ix + 1;
    next = (function(_this) {
      return function(err) {
        return _this.stack(nextIx, err, done);
      };
    })(this);
    this.env.view = this.curView.instantiate;
    return middleware.call(this.env, err, next);
  },
  runMiddlewares: function(done) {
    if (done == null) {
      done = function() {};
    }
    if (this._middlewares.length === 0) {
      return this._runView(done);
    }
    return this.stack(0, null, done);
  },
  _initView: function(View, viewName) {
    var $el;
    $el = $("<div class='" + this.options.viewClass + "' />");
    this.curView = {
      name: viewName,
      instantiate: new View($el, this)
    };
    return this.runMiddlewares((function(_this) {
      return function() {
        _this.curView.instantiate.$el.appendTo(_this.$el);
        _this.curView.instantiate.afterRun();
        return _this._onLoadViw = false;
      };
    })(this));
  },
  runView: function(viewName, route, args) {
    var View;
    if (this._onLoadViw) {
      return;
    }
    View = false;
    if (false === util.isString(viewName)) {
      View = viewName;
      viewName = View.viewName;
    }
    this.env = {
      route: route,
      context: route.context,
      args: args,
      viewName: viewName,
      app: this
    };
    if (this.curView) {
      if (this.curView.name === viewName) {
        this.runMiddlewares((function(_this) {
          return function() {
            return _this.curView.instantiate.afterRun();
          };
        })(this));
        return;
      } else {
        this.emit('destroyView', this.curView);
        this.curView.instantiate.destroy();
        this.curView = null;
      }
    }
    this._onLoadViw = true;
    if (View) {
      return this._initView(View, viewName);
    } else {
      return config.AMDLoader([viewName], (function(_this) {
        return function(View) {
          return _this._initView(View, viewName);
        };
      })(this));
    }
  },
  run: function() {
    return this.router.run();
  }
});


text:
@(employmentChange: Form[models.domain.CircumstancesEmploymentChange])(implicit claim: models.domain.Claim, lang: Lang, request: Request[AnyContent], flash:Flash, messages: play.api.i18n.Messages)

@implicitField = @{ utils.helpers.CarersTemplate.apply(lang).fieldConstructor }
@import utils.csrf.DwpCSRFFormHelper
@import views.html.helper._
@import views.html.helper.base._
@import views.html.helper.dates._
@import utils.helpers.CarersCrypto
@import models.domain.CircumstancesSelfEmployment
@import views.html.circs.report_changes.main
@import play.api.Play
@import play.api.Play.current

@stillCaring = @{employmentChange("stillCaring")}
@hasWorkStartedYet = @{employmentChange("hasWorkStartedYet")}
@hasWorkFinishedYet = @{employmentChange("hasWorkFinishedYet")}
@typeOfWork = @{employmentChange("typeOfWork")}
@paidMoneyYet = @{employmentChange("paidMoneyYet")}

@main(messages("c2.g9") + " - " + messages("c2.name"), isChanging = false) {
    @errorsSummary(employmentChange)

    @form(action = controllers.circs.report_changes.routes.GEmploymentChange.submit) {
        @DwpCSRFFormHelper.formField

	        <fieldset class="form-elements" data-journey="carers-allowance:report-change:employment">

	            <legend class="heading-medium form-label-bold">@Html(messages("c2.g9"))</legend>

	                @yesNoRadioGroup(stillCaring("answer"))

	                @otherDetailPlaceHolder(
	                    inputDef = Seq(
                            dateTimePickerWithDynamicLabel(stillCaring("date"), 'dynamicDateDays-> 31)
	                    ),
	                    'id -> "stillCaringWrap"
	                )

                    @yesNoRadioGroup(hasWorkStartedYet("answer"),
                        'values -> Seq("yes" -> messages("label.yes1"), "no" -> messages("label.no"))
                    )

                    @otherDetailPlaceHolder(
                        inputDef = Seq(
                            dateTimePickerWithDynamicLabel(hasWorkStartedYet("dateWhenStarted"), 'dynamicDateDays-> 31),
                            yesNoRadioGroup(hasWorkFinishedYet("answer"),
                                'values -> Seq("yes" -> messages("label.yes1"), "no" -> messages("label.no"))
                            ),
                            otherDetailPlaceHolder(
                                inputDef = Seq(
                                    dateTimePickerWithDynamicLabel(hasWorkFinishedYet("dateWhenFinished"), 'dynamicDateDays-> 7)
                                ),
                                'id -> "hasWorkFinishedYetWrap"
                            )
                        ),
                        'id -> "hasWorkStartedYetWrap"
                    )

                    @otherDetailPlaceHolder(
                        inputDef = Seq(
                            dateTimePickerWithDynamicLabel(hasWorkStartedYet("dateWhenWillItStart"), 'dynamicDateDays-> -7)
                        ),
                        'id -> "workNotStartedYetWrap"
                    )

                    @yesNoRadioGroup(typeOfWork("answer"),
                        'values -> Seq("employed" -> messages("typeOfWork.employed"), "self-employed" -> messages("typeOfWork.selfemployed")),
                        'helperAbove -> Html(messages("typeOfWork.help")),
                        '_boltonClass -> "radio-stack" ,
                        'track -> true, 'trackLabel -> "typeOfWork"
                    )

                    @otherDetailPlaceHolder(
                        inputDef = Seq(
                            carersInputText(typeOfWork("employerName"), 'maxLength -> 60, 'minLength -> 2, 'ignoreOptional -> true),
                            inputAddress(typeOfWork("employerNameAndAddress"), 'ignoreOptional -> true, 'addressLabel -> "typeOfWork.employerNameAndAddress"),
                            carersInputPostcode(typeOfWork("employerPostcode"), 'maxLength -> 10, 'class -> "postcode"),
                            carersInputText(typeOfWork("employerContactNumber"), 'maxLength -> 15, 'ignoreOptional -> true)
                        ),
                        'id -> "typeOfWorkEmployedWrap"
                    )

                    @otherDetailPlaceHolder(
                        inputDef = Seq(
                            carersInputText(typeOfWork("selfEmployedTypeOfWork"), 'maxLength -> 35, 'ignoreOptional -> true),
                            yesNoRadioGroup(paidMoneyYet("answer"), 'helperAbove -> messages("paidMoneyYet.helper"),
                                'track -> true, 'trackLabel -> messages("paidMoneyYet.answer"), 'values -> Seq("yes" -> messages("label.yes1"), "no" -> messages("label.no"))),
                            otherDetailPlaceHolder(inputDef = Seq(inputDayMonthYear(paidMoneyYet("date"))), 'id -> "paidMoneyYetWrap"),
                            yesNoRadioGroup(typeOfWork("selfEmployedTotalIncome"), 'ignoreOptional -> true, 'track -> true, 'trackLabel -> messages("typeOfWork.selfEmployedTotalIncome"),
                                'values -> Seq("yes" -> messages("label.yes7"), "no" -> messages("label.no"), "dontknow" -> messages("label.dontknow"))),
                            carersInputTextArea(typeOfWork("selfEmployedMoreAboutChanges"), 'helperAbove-> messages("moreAboutChanges.helper"), '_label -> "moreAboutChanges",
                                'textAreaHelper -> Html(messages(s"${CircumstancesSelfEmployment.textMaxLength}charsLeft")), 'maxLength -> CircumstancesSelfEmployment.textMaxLength)
                        ),
                        'id -> "typeOfWorkSelfEmployedWrap"
                    )

	        </fieldset>

            @views.html.common.bottomNavigation(changing = false, customTrack = Some(Html("onclick=analyticsCallback()")))

    }

}


text:
import Mocha, {
    describe,
    it,
    before
} from 'mocha';
import {
    TrafficLightWidgetData
} from '../../../../../src/DataModel/Config/WidgetData/DataWidgetData/TrafficLightWidgetData.js';
import {View} from '../../../../../src/View/View.js';
import {DashboardServices} from '../../../../../src/DashboardServices/DashboardServices.js';
import {WidgetConfig} from '../../../../../src/DataModel/Config/WidgetConfig.js';
import Jsdom from 'mocha-jsdom';
import Chai, {
    expect
} from 'chai';

/**
 * This one will test the TrafficLightWidgetData Class
 * @param string
 *      The displayed name of this test suite
 */
describe('Class TrafficLightWidgetData: Basic tests: ', () => {
    let _view = null;
    let $ = null;
    let L = null;
    Jsdom();

    // first initialization of view
    before(function (done) {
        // init window and jquery globaly
        this.jsdom = require('jsdom-global')();
        global.$ = global.jQuery = require('jquery');
        $ = require('jquery');
        global.L = require('leaflet');

        global.WIDGET_TYPE_BARGRAPH = 1;
        global.WIDGET_TYPE_GAUGE = 2;
        global.WIDGET_TYPE_LINEGRAPH = 3;
        global.WIDGET_TYPE_MAP = 4;
        global.WIDGET_TYPE_PLAINDATA = 5;
        global.WIDGET_TYPE_PLAINTEXT = 6;
        global.WIDGET_TYPE_THERMOMETER = 7;
        global.WIDGET_TYPE_TRAFFICLIGHT = 8;

        global.MARKER_TYPE_PLAIN = 0;
        global.MARKER_TYPE_PLAINVALUE = 1;
        global.MARKER_TYPE_TRAFFICLIGHT = 2;
        global.MARKER_TYPE_HISTORY = 3;
        done();
    });

    it('constructor works', function (done) {
        let trafficLightWidgetData = new TrafficLightWidgetData();
        expect(trafficLightWidgetData).to.be.instanceof(Object);
        done();
    });

    it('setAttributes & getPosition test', function (done) {
        let trafficLightWidgetData = new TrafficLightWidgetData();
        let temp = {
            "position": {
                "x": 4,
                "y": 2
            },
            "size": {
                "x": 42,
                "y": 24
            }
        };
        trafficLightWidgetData.setAttributes(temp);
        expect(trafficLightWidgetData.getPosition()).equal(temp.position);
        done();
    });

    it('setAttributes & getSize test', function (done) {
        let trafficLightWidgetData = new TrafficLightWidgetData();
        let temp = {
            "position": {
                "x": 4,
                "y": 2
            },
            "size": {
                "x": 42,
                "y": 24
            }
        };
        trafficLightWidgetData.setAttributes(temp);
        expect(trafficLightWidgetData.getSize()).equal(temp.size);
        done();
    });

    it('set- & getPosition test', function (done) {
        let trafficLightWidgetData = new TrafficLightWidgetData();
        let temp = {
            "x": 4,
            "y": 2
        };
        trafficLightWidgetData.setPosition(temp);
        expect(trafficLightWidgetData.getPosition()).equal(temp);
        done();
    });

    it('set- & getSize test', function (done) {
        let trafficLightWidgetData = new TrafficLightWidgetData();
        let temp = {
            "x": 20,
            "y": 12
        };
        trafficLightWidgetData.setSize(temp);
        expect(trafficLightWidgetData.getSize()).equal(temp);
        done();
    });

    it('method getID test', function (done) {
        let trafficLightWidgetData = new TrafficLightWidgetData(10);
        expect(trafficLightWidgetData.getID()).equal(10);
        done();
    });

    it('method getType test', function (done) {
        let trafficLightWidgetData = new TrafficLightWidgetData(22);
        expect(trafficLightWidgetData.getType()).equal(8);
        done();
    });

    it("should call data callback when new data arrives", () => {
        let trafficLightWidgetData = new TrafficLightWidgetData("test");
        let callback = (data) => {
            //make sure that test ends only for non-empty data
            if (data.Observations && data.Observations.length > 0) {
                done();
            }
        };

        trafficLightWidgetData.registerViewCallback(() => {
        }, callback);
        trafficLightWidgetData.newData({
            Observations: [
                {result: "Yay!"}
            ]
        });

    });

    it("should save size and position correctly", () => {
        let trafficLightWidgetData = new TrafficLightWidgetData("test");
        trafficLightWidgetData.setPosition({x: 1, y: 2});
        trafficLightWidgetData.setSize({width: 3, height: 4});
        let position = trafficLightWidgetData.getPosition();
        let size = trafficLightWidgetData.getSize();

        expect([position.x, position.y, size.width, size.height].join("")).to.equal("1234");
    });

    it("should apply passed config on creation", (done) => {
        _view = new View("test");
        _view._setUpLanguage("en");
        _view._gridstack = _view._gridstack || {
                addWidget: () => {
                }
            };
        let dashboardServices = new DashboardServices();
        let params = {
            title: {
                data: 'My test title', type: TYPE_STRING
            },
            lower: {
                data: 7, type: TYPE_NUMBER
            },
            upper: {
                data: 12, type: TYPE_NUMBER
            },
            lowerColor: {
                data: COLOR_GREEN,
                type: TYPE_DROPDOWN,
                options: {
                    red: COLOR_RED,
                    yellow: COLOR_YELLOW,
                    green: COLOR_GREEN
                }
            },
            middleColor: {
                data: COLOR_YELLOW,
                type: TYPE_DROPDOWN,
                options: {
                    red: COLOR_RED,
                    yellow: COLOR_YELLOW,
                    green: COLOR_GREEN
                }
            },
            upperColor: {
                data: COLOR_RED,
                type: TYPE_DROPDOWN,
                options: {
                    red: COLOR_RED,
                    yellow: COLOR_YELLOW,
                    green: COLOR_GREEN
                }
            },
            sensorThingsConfiguration: {
                data: [{
                    data: {
                        dataStreamUrl: {
                            data: '',
                            type: TYPE_FUZZY_SENSOR_SEARCH
                        },
                        mqttEnabled: {
                            data: false,
                            type: TYPE_BOOLEAN
                        },
                        mqttUrl: {
                            data: '',
                            type: TYPE_STRING
                        },
                        mqttBaseTopic: {
                            data: '',
                            type: TYPE_STRING
                        },
                        updateIntervalMs: {
                            data: 1000,
                            type: TYPE_INTEGER
                        }
                    },
                    type: TYPE_OBJECT
                }],
                type: TYPE_ARRAY
            }

        };

        dashboardServices.createWidget(WIDGET_TYPE_TRAFFICLIGHT, params);
        new WidgetConfig().addWidgetData = (data) => {
            expect(data.configurableData.title.data).to.equal("My test title");
            done();
        };
    });

    it("should destroy itself", (done) => {
        let trafficLightWidgetData = new TrafficLightWidgetData("test");
        global.called = false;
        let _view = new View("test");
        _view._gridstack = {removeWidget:() => {}};
        let callback = () => {
                called = !called;
                expect(called).to.be.true;
        };
        trafficLightWidgetData.registerViewCallback(callback, () => {});
        trafficLightWidgetData.allData = [1];
        trafficLightWidgetData.destroy();
        trafficLightWidgetData.newData([2]);
        done();
    });
});


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	errorHandler = require('./errors'),
	Article = mongoose.model('Article'),
	_ = require('lodash');

/**
 * Create a article
 */
exports.create = function(req, res) {
	var article = new Article(req.body);
	article.user = req.user;

	article.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(article);
		}
	});
};

/**
 * Show the current article
 */
exports.read = function(req, res) {
	res.jsonp(req.article);
};

/**
 * Update a article
 */
exports.update = function(req, res) {
	var article = req.article;

	article = _.extend(article, req.body);

	article.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(article);
		}
	});
};

/**
 * Delete an article
 */
exports.delete = function(req, res) {
	var article = req.article;

	article.remove(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(article);
		}
	});
};

/**
 * List of Articles
 */
exports.list = function(req, res) {
	console.log('here babi in article list');
	console.log('query....: ');
	console.log(req.query);

	if (!req.session.articles) {
		req.session.articles = [];
	}
	// console.log('after session');
	// console.log(req.session.articles);

	if (req.query.currentUtc) {
		Article.find({   $and: [{_id: {$nin: req.session.articles }}, {saved_utc: {$lt: parseInt(req.query.currentUtc)}}] })
		// Article.find({   $and: [{saved_utc: {$lt: parseInt(req.query.currentUtc)}}] })
			.sort('-saved_utc')
			.exec(function(err, articles) {
				if (err) {
					return res.status(400).send({
						message: errorHandler.getErrorMessage(err)
					});
				} else {
					var minArticleNumber = Math.min(articles.length, 25);
					var newArticles = articles.slice(0,minArticleNumber);
					console.log('number of the OLD req.session.articles: ');
					console.log(req.session.articles.length);
					req.session.articles = req.session.articles.concat(_.map(newArticles, function(article) { return article._id; }));
					console.log('number of the NEW req.session.articles: ');
					console.log(req.session.articles.length);

					console.log('=========================================\n number of newArticles:');
					console.log(newArticles.length);

					res.jsonp(newArticles);
				}
			});
	} else {

		Article.find().sort('-created').populate('user', 'displayName').exec(function(err, articles) {
			if (err) {
				return res.status(400).send({
					message: errorHandler.getErrorMessage(err)
				});
			} else {
				res.jsonp(articles);
			}
		});

	}

};

/**
 * Article middleware
 */
exports.articleByID = function(req, res, next, id) {
	Article.findById(id).populate('user', 'displayName').exec(function(err, article) {
		if (err) return next(err);
		if (!article) return next(new Error('Failed to load article ' + id));
		req.article = article;
		next();
	});
};

/**
 * Article authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
	if (req.article.user.id !== req.user.id) {
		return res.status(403).send({
			message: 'User is not authorized'
		});
	}
	next();
};


text:
package com.ftfl.ftflicare.adapter;

import java.util.List;

import com.ftfl.ftflicare.R;
import com.ftfl.ftflicare.model.VaccineModel;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class VaccineItemAdapter extends ArrayAdapter<VaccineModel> {

	private static LayoutInflater mInflater = null;
	List<VaccineModel> mVaccine;
	VaccineModel mVaccineModel;

	public VaccineItemAdapter(Activity context, List<VaccineModel> eVaccine) {
		super(context, R.layout.each_vaccine_item, eVaccine);
		this.mVaccine = eVaccine;

		/*********** Layout inflator to call external xml layout () ***********/
		mInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	/********* Create a holder Class to contain inflated xml file elements *********/
	public static class ViewHolder {

		public TextView vaccineName;
		public TextView vaccineDate;
		public TextView vaccineTime;
		public ImageView ivAlarmImage;

	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		View view = convertView;
		ViewHolder holder;
		if (convertView == null) {

			/****** Inflate tabitem.xml file for each row ( Defined below ) *******/
			view = mInflater.inflate(R.layout.each_vaccine_item, null);

			/****** View Holder Object to contain tabitem.xml file elements ******/

			holder = new ViewHolder();
			holder.vaccineName = (TextView) view
					.findViewById(R.id.tvVaccinineName);
			holder.vaccineDate = (TextView) view
					.findViewById(R.id.tvVaccineDate);
			holder.vaccineTime = (TextView) view
					.findViewById(R.id.tvVaccineTime);
			holder.ivAlarmImage = (ImageView) view.findViewById(R.id.ivAlarm);

			/************ Set holder with LayoutInflater ************/
			view.setTag(holder);
		} else {
			holder = (ViewHolder) view.getTag();
		}

		/*getting info from vaccine model to holder*/
		mVaccineModel = mVaccine.get(position);

		holder.vaccineName.setText(mVaccineModel.getVaccineName().toString());
		holder.vaccineDate.setText("Date: "
				+ mVaccineModel.getVaccineDate().toString());
		holder.vaccineTime.setText("Time: "
				+ mVaccineModel.getVaccineTime().toString());

		/*check alarm set or not*/
		if (mVaccineModel.getAlarmCecked() == 1) {

			holder.ivAlarmImage.setImageResource(R.drawable.alarm_on);
		} else {
			holder.ivAlarmImage.setImageResource(R.drawable.alarm_off);
		}

		return view;
	}

}


text:
/**
 * defines.hpp
 *
 *  Created on: Dec 08, 2015
 *      Author: Sundaram
 * This file has the necessary dependant files to be included for the logger to work. Include it in the source file where logging is to be used.
 * To change the logging levels for any of the files you need to change the threshold settings in the log4cpp.properties file.
 * The logging levels can be changed without recompiling the code.
 */
#include <log4cpp/Category.hh>
#include <log4cpp/PropertyConfigurator.hh>

#define LOG_PROG_FLOW log4cpp::Category::getInstance(std::string("prog_flow"))
#define LOG_TRACE log4cpp::Category::getInstance(std::string("trace"))
#define LOG_WARNING log4cpp::Category::getInstance(std::string("warn"))
#define LOG_PERF log4cpp::Category::getInstance(std::string("perf"))
#define LOG_USAGE log4cpp::Category::getInstance(std::string("usage"))