text:
package edu.mit.ll.nics.nicsdao.impl;

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

import org.joda.time.DateTime;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import edu.mit.ll.dao.QueryModel;

import edu.mit.ll.nics.common.entity.Assignment;
import edu.mit.ll.nics.common.entity.AssignmentId;
import edu.mit.ll.nics.common.entity.OperationalPeriod;
import edu.mit.ll.nics.common.entity.ResourceAssign;
import edu.mit.ll.nics.common.entity.TaskAssign;
import edu.mit.ll.nics.common.entity.Unit;
import edu.mit.ll.jdbc.JoinRowCallbackHandler;
import edu.mit.ll.jdbc.JoinRowMapper;
import edu.mit.ll.nics.common.entity.CollabroomPermission;
import edu.mit.ll.nics.common.entity.Form;
import edu.mit.ll.nics.common.entity.User;
import edu.mit.ll.nics.common.constants.TaskingConstants;
import edu.mit.ll.nics.common.constants.SADisplayConstants;
//import edu.mit.ll.nics.sadisplay.util.Util;
import edu.mit.ll.nics.nicsdao.CollabRoomDAO;
import edu.mit.ll.nics.nicsdao.FormDAO;
import edu.mit.ll.nics.nicsdao.GenericDAO;
import edu.mit.ll.nics.nicsdao.QueryManager;
import edu.mit.ll.nics.nicsdao.TaskingDAO;
import edu.mit.ll.nics.nicsdao.mappers.CollabRoomPermissionRowMapper;
import edu.mit.ll.nics.nicsdao.mappers.FormRowMapper;
import edu.mit.ll.nics.nicsdao.mappers.AssignmentRowMapper;
import edu.mit.ll.nics.nicsdao.mappers.OperationalPeriodRowMapper;
import edu.mit.ll.nics.nicsdao.mappers.ResourceAssignRowMapper;
import edu.mit.ll.nics.nicsdao.mappers.TaskAssignRowMapper;
import edu.mit.ll.nics.nicsdao.mappers.UnitRowMapper;
import edu.mit.ll.nics.nicsdao.mappers.UserRowMapper;

public class TaskingDAOImpl extends GenericDAO implements TaskingDAO {

	private Logger log;

	private static final FormDAOImpl formDao = new FormDAOImpl();
	private static final CollabRoomDAOImpl collabRoomDao = new CollabRoomDAOImpl();

	private NamedParameterJdbcTemplate template;

	final public static int SUCCESS = 0;
	final public static int FAILURE = 1;
	final public static int ALREADY_EXISTS = 2;

	@Override
	public void initialize() {
		log = LoggerFactory.getLogger(TaskingDAOImpl.class);
		this.template = new NamedParameterJdbcTemplate(datasource);
	}

	private int getNextOpPeriodId() {
    	QueryModel queryModel = QueryManager.createQuery("operational_period_seq").selectNextVal();
    	try{
    		return this.template.queryForInt(queryModel.toString(), new HashMap<String, Object>());
    	}catch(Exception e){
    		log.info("Could not retrieve next operational_period_id #0", e.getMessage());
    	}
    	return -1;
	}

	private int getNextTaskAssignId() {
		QueryModel queryModel = QueryManager.createQuery("task_assign_seq").selectNextVal();
    	int id = -1;
		try{
    		id = this.template.queryForInt(queryModel.toString(), new HashMap<String, Object>());
    		log.info("Got next sequence value for task_assign: " + id);
    		return id;
    	}catch(Exception e){
    		log.info("Could not retrieve next task_assign_id #0", e.getMessage());
    	}
    	return id;
	}

	/**
	 * Checks to see if the specified op period exists.
	 *
	 * @param start
	 * @param end
	 * @param incidentId
	 * @return The id of the op period, if it exists, -1 otherwise
	 */
	public long opPeriodExists(long start, long end, long incidentId) {
		/*
		QueryModel query = QueryManager.createQuery(TaskingConstants.OPPERIOD_TABLE)
				.selectFromTableWhere()
				.equals(TaskingConstants.OPPERIOD_INCIDENT_ID, incidentId).and()
				.equals("start_utc", start).and()
				.equals("end_utc", end);
		*/

		// TODO: unsafe to just concatenate parameters, but can't find way to simply get a count
		// via spring jdbc or QueryManager/QueryModel

		//String sql = "SELECT COUNT(*) FROM operational_period where incident_id=" + incidentId +
		// 		" and " + "start_utc=" + start + " and end_utc=" + end;

		QueryModel query = QueryManager.createQuery(TaskingConstants.OPPERIOD_TABLE)
				.selectFromTable("id").where()
				.equals("incident_id", incidentId).and()
				.equals("start_utc", start).and()
				.equals("end_utc", end);
		long existingId = -1;
		try {
			existingId = this.template.queryForLong(query.toString(), query.getParameters());
		} catch(EmptyResultDataAccessException e) {
			log.info("Op Period does not exist!");
		} catch(DataAccessException e) {
			log.error("got an exception checking for existing OpPeriod", e);
		} catch(Exception e) {
			log.error("Caught unhandled exception checking for existing OpPeriod", e);
		}

		return existingId;

		/*
		// Really still need to pass in a map? ...
		MapSqlParameterSource paramMap = new MapSqlParameterSource();
		paramMap.addValue("incident_id", incidentId);
		paramMap.addValue("start_utc", start);
		paramMap.addValue("end_utc", end);
		int count = this.template.queryForInt(sql, paramMap);

		if(count > 0) {
			return true;
		} else {
			return false;
		}
		*/
	}

	public int createOperationalPeriod(long start, long end, long incidentId) {

		if(opPeriodExists(start, end, incidentId) > 0) {
			log.info("The opPeriod with the specified start and end already exists(" +
					incidentId + "), so not adding");

			// TODO: why return all op periods? Wasteful
			//return this.getOperationalPeriodsString((int)incidentId);
			return ALREADY_EXISTS;
		}

		try {
			List<String> fields = new ArrayList<String>();
			fields.add("id");
			fields.add(TaskingConstants.OPPERIOD_INCIDENT_ID);
			fields.add(TaskingConstants.OPPERIOD_START_UTC);
			fields.add(TaskingConstants.OPPERIOD_END_UTC);

			long id = getNextOpPeriodId();
			// TODO: handle if -1, means there was a failure retrieving it

			MapSqlParameterSource paramMap = new MapSqlParameterSource();
			paramMap.addValue("id", id);
			paramMap.addValue(TaskingConstants.OPPERIOD_INCIDENT_ID, incidentId);
			paramMap.addValue(TaskingConstants.OPPERIOD_START_UTC, start);
			paramMap.addValue(TaskingConstants.OPPERIOD_END_UTC, end);

			QueryModel query = QueryManager.createQuery(TaskingConstants.OPPERIOD_TABLE)
					.insertInto(fields);

			int result = this.template.update(query.toString(), paramMap);
			log.info("Affected rows on addOpPeriod: " + result);
			// TODO: check if affected 1 row as expected, or if 0 comes back?
			if(result == 1) {
				return SUCCESS;
			}

		} catch(Exception e) {
			log.error("failed persisting new opPeriod: " + e.getMessage());
		}
		// TODO: why return all op periods? Wasteful
		//return this.getOperationalPeriods();
		//return this.getOperationalPeriodsString((int)incidentId);
		return FAILURE;
	}

	public String getOperationalPeriodsString(int incidentId) {
		QueryModel query = QueryManager.createQuery(TaskingConstants.OPPERIOD_TABLE)
				.selectAllFromTableWhere()
				.equals(TaskingConstants.OPPERIOD_INCIDENT_ID, incidentId);
		log.info("\n\nQuery for OP Periods with id set to " + incidentId + ": " + query.toString() + "\n\n");
		List<OperationalPeriod> ops = this.template.query(query.toString(),
				new MapSqlParameterSource(TaskingConstants.OPPERIOD_INCIDENT_ID, incidentId),
				new OperationalPeriodRowMapper());

		JSONArray arr = new JSONArray();
		for(OperationalPeriod pop : ops) {
			arr.put(pop.toJSONObject());
		}

		return arr.toString();
	}

	public int createAssignment(long unitId, long operationalPeriodId) {
		int status = FAILURE;

		// TODO: check to see if assignment exists, Try finding out in exception first
		// 	rather than querying and checking for results
		if(getAssignment(unitId, operationalPeriodId) != null) {
			return ALREADY_EXISTS;
		}

		List<String> fields = new ArrayList<String>();
		fields.add("unit_id");
		fields.add("operational_period_id");
		fields.add("published");

		MapSqlParameterSource paramMap = new MapSqlParameterSource();
		paramMap.addValue("unit_id", unitId);
		paramMap.addValue("operational_period_id", operationalPeriodId);
		paramMap.addValue("published", false);

		QueryModel query = QueryManager.createQuery(TaskingConstants.ASSIGNMENT_TABLE)
				.insertInto(fields);

		try {
			int result = this.template.update(query.toString(), paramMap);

			if(result == 1) {
				status = SUCCESS;
			}
		} catch(DataAccessException e) {
			log.error("DataAccessException while creating assignment: " + e.getMessage() +
					"\nMost Specific Cause: "
					+ ((e.getMostSpecificCause() != null) ? "Unknown" : e.getMostSpecificCause().getMessage()));

			log.debug("Exception", e);

			// TODO: See if you can find out if it hit an already exists exception, and return ALREADY_EXISTS
		} catch(Exception e) {
			log.error("Unhandled exception while creating assignment: " + e.getMessage(), e);
		}

		return status;
	}

	public int publishAssignment(int unitId, int opPeriod) {

		QueryModel query = QueryManager.createQuery(TaskingConstants.ASSIGNMENT_TABLE)
				.update().equals("published", true)
				.where()
				.equals("unit_id").and()
				.equals("operational_period_id");

		MapSqlParameterSource paramMap = new MapSqlParameterSource();
		paramMap.addValue("published", true);
		paramMap.addValue("unit_id", unitId);
		paramMap.addValue("operational_period_id", opPeriod);

		int ret = this.template.update(query.toString(), paramMap);

		if(ret == 0) {
			return FAILURE;
		}

		return SUCCESS;
	}

	public Assignment getAssignment(AssignmentId id) {
		return getAssignment(id.getUnitId(), id.getOperationalPeriodId());
	}

	public Assignment getAssignment(long unitId, long opPeriodId) {
		QueryModel queryAssignment = QueryManager.createQuery(TaskingConstants.ASSIGNMENT_TABLE)
				.selectAllFromTableWhere()
				.equals(TaskingConstants.ASSIGNMENT_UNIT_ID, unitId)
				.and()
				.equals(TaskingConstants.ASSIGNMENT_OPPERIOD_ID, opPeriodId);

		Assignment assignment = null;
		Unit unit = null;
		OperationalPeriod opPeriod = null;

		log.info("Attempting to query for Assignment with unitId and opPeriod: #?, #?", unitId, opPeriodId);

		try{
			unit = (Unit) this.template.queryForObject("select * from unit where id=" + unitId,
					new MapSqlParameterSource("id", unitId),
					new UnitRowMapper());

			log.info("unit: " + ((unit != null)? unit.toJSONObject().toString() : "null"));

			opPeriod = (OperationalPeriod) this.template.queryForObject(
					"select * from operational_period where id=" + opPeriodId,
					new MapSqlParameterSource("id", opPeriodId),
					new OperationalPeriodRowMapper());
			log.info("opPeriod: " + ((opPeriod != null) ? opPeriod.toJSONObject().toString() : "null"));

			assignment = (Assignment) this.template.queryForObject(queryAssignment.toString(),
					queryAssignment.getParameters(),
					new AssignmentRowMapper());

			assignment.setOperationalPeriod(opPeriod);
			assignment.setUnit(unit);

			if(assignment != null) {
				log.info("\n!!!Got assignment(unitid, opperiodid, published: " +
						assignment.getUnit().getId() + ", " +
						assignment.getOperationalPeriod().getId() + ", " +
						assignment.isPublished());
			}

			MapSqlParameterSource paramMap = new MapSqlParameterSource();
			paramMap.addValue("unit_id", unitId);
			paramMap.addValue("operational_period_id", opPeriodId);

			List<ResourceAssign> resourceAssigns = this.template.query(
					"select * from resource_assign where unit_id="+unitId +
						" and operational_period_id="+opPeriodId,
					paramMap,
					new ResourceAssignRowMapper());
			log.info("Got resourceAssigns?" + ((resourceAssigns != null) ? resourceAssigns.size() : "none"));

			// Populate assignment, since the row mapper currently DOES NOT
			//for(ResourceAssign ra : resourceAssigns) {
			//	ra.setAssignment(assignment);
			//}

			// Populate assignment, since the row mapper currently DOES NOT
			List<TaskAssign> taskAssigns = this.template.query(
					"select * from task_assign where unit_id="+unitId+
						" and operational_period_id="+opPeriodId,
						paramMap, new TaskAssignRowMapper());
			log.info("Got taskAssigns?" + ((taskAssigns != null) ? taskAssigns.size() : "none"));

			// TODO: TaskAssignRowMapper doesn't set all Form fields, just ID
			//for(TaskAssign ta : taskAssigns) {
			//	ta.setAssignment(assignment);
			//}

			assignment.setResourceAssigns(new HashSet<ResourceAssign>(resourceAssigns));
			assignment.setTaskAssigns(new HashSet<TaskAssign>(taskAssigns));

			/* join mappers method...
			JoinRowCallbackHandler<Assignment> handler = getAssignmentHandlerWith(
					new OperationalPeriodRowMapper(), new UnitRowMapper()
					);

			this.template.query(query.toString(), query.getParameters(),
					handler);
			assignment = handler.getSingleResult();
			log.info( ((assignment != null) ? "Got Assignment: \n" +
					assignment.toJSONObject().toString() : "NULL"));
			*/

		} catch(EmptyResultDataAccessException e) {
			log.debug("No results with unitid and opperiodid ("+unitId+","+opPeriodId+")");
		} catch(Exception e) {
			log.error("Caught unhandled exception querying for single assignment with " +
					"unitid and opperiodid ("+unitId+","+opPeriodId+")", e);
		}

		return assignment;
	}

	public String getAssignmentString(long unitId, long opPeriodId) {
		Assignment pa = getAssignment(unitId, opPeriodId);
		return pa.toJSONObject().toString();
	}

	public String getAssignmentString(AssignmentId id) {
		Assignment pa = getAssignment(id);
		return pa.toJSONObject().toString();
	}

	public List<Assignment> getAssignments(int userId, Map<String, Object> queryOpts) {

		List<Assignment> assignments = null;

		StringBuilder sql = new StringBuilder();
		DateTime now = new DateTime();
		if (userId < 0) {
			sql.append("SELECT * from assignment where published = 't'");
		} else {
			boolean activeOnly = false;
			if (queryOpts.containsKey("activeOnly")) {
				activeOnly = (Boolean)queryOpts.get("activeOnly");
			}
			sql.append("SELECT a.unit_id, a.operational_period_id, a.published from assignment a, resource_assign r");
			if (activeOnly) {
				sql.append(", operational_period p");
			}
			sql.append(" WHERE a.published = 't' AND a.unit_id = r.unit_id");
			sql.append(" AND a.operational_period_id = r.operational_period_id");
			if (activeOnly) {
				sql.append(" AND a.operational_period_id = p.id");
			}
			sql.append(" AND r.user_id = ").append(userId);
			if (activeOnly) {
				sql.append(" AND ").append(now.getMillis()).append(" BETWEEN p.start_utc and p.end_utc");
			}
		}

		// TODO: We cannot implement Date range based queries at this time due
		// to the fact that task assignment entities do not have a seqTime
		// or other date column. The only concept of time is its association
		// with an Operational Period, which does have a beginning and ending
		// time. While this could be used, it is a deviation from the boiler
		// plate code written to handle NICS entities.
		// processQueryConstraintOptions(sql, queryOpts);

		//List<Object> entities = nicsDbUtil.sqlExecuteNative(sql.toString(), Assignment.class, em, log);
		//List<Assignment> ret = new ArrayList<Assignment>(entities.size());
		//for (Object e : entities) {
		//	ret.add((Assignment)e);
		//}

		JoinRowCallbackHandler<Assignment> handler = new JoinRowCallbackHandler<Assignment>(new AssignmentRowMapper());
		template.query(sql.toString(), handler);
		assignments = handler.getResults();

		return assignments;
	}

	public List<Assignment> getAssignments(int incidentId) {
//	public List<Object[]> getAssignments(int incidentId) {
		// TODO: Constants with relation names were being used, but a native query is being used
		//		 so I think the actual table names need used?
		/*String query = "SELECT * FROM " + TaskingConstants.ASSIGNMENT_TABLE + " where " +
				TaskingConstants.UNIT_TABLE + " IN (SELECT " + TaskingConstants.UNIT_ID +
				" FROM " + TaskingConstants.UNIT_TABLE + " WHERE " +
				TaskingConstants.UNIT_INCIDENT_ID + " = :incId)";*/

		String query = "SELECT * FROM " + "assignment" + " where " +
				"unit_id" + " IN (SELECT " + "id" +
				" FROM " + "unit" + " WHERE " +
				TaskingConstants.UNIT_INCIDENT_ID + " = :incId)";
		/* Original... native query isn't returning Assignments, but arrays with
		 * each index being a field from the assignment table
		List<Assignment> assignments = (List<Assignment>) em.createNativeQuery(query)
				.setParameter("incId", incidentId)
				.getResultList();*/

		QueryModel queryModel = QueryManager.createQuery("assignment").
				selectAllFromTable()
				.join("unit").on().equals("incident_id", incidentId);
				//.where().equals("incident_id", incidentId);

		List<Assignment> assignments = this.template.query(queryModel.toString(),
				queryModel.getParameters(), new AssignmentRowMapper());

		//List<Object[]> assignments = em.createNativeQuery(query)
			//	.setParameter("incId", incidentId)
			//	.getResultList();

		// DEBUGGING
		//for(int i = 0; i < assignments.size(); i++) {
		//	Object obj[] = assignments.get(i);
		//	log.info("\n!!! ArrayAssignment: " + obj[0] + ", " + obj[1] + ", " + obj[2]);
		//}
		// DEBUGGING

		return assignments;
	}

	public String getAssignmentsString(int incidentId) {
		List<Assignment> assignments = getAssignments(incidentId);

		if(assignments.isEmpty()) {
			log.info("NO assignments returned for incident id: " + incidentId);
			return new JSONArray().toString();
		}

		JSONArray arr = new JSONArray();

		/* works if this was actually a list of full assignments, but narrowing it to
		 * just return the 3 fields in a assignment
		for(Assignment a : assignments) {
			arr.put(a.toJSONObject());
		}*/
		JSONObject json;
		//for(Object[] objArr : assignments) {
		for(Assignment assign : assignments) {

			if(assign == null) {
				continue;
			}

			json = new JSONObject();

			try {
				AssignmentId id = assign.getId();

				if(id == null) {
					log.info("Warning! AssignmentId was null on Assignment, cannot return Assignment");
					continue;
				}

				json.put("unitid", id.getUnitId());
				json.put("opperiodid", id.getOperationalPeriodId());
				json.put("published", assign.isPublished());

				arr.put(json);
			} catch (JSONException e) {
				log.error("JSONException while building Assignment object: " + e.getMessage());
				e.printStackTrace();
			}

		}

		return arr.toString();
	}

	public int assignTask(AssignmentId id, long taskId) {
		return assignTask(id.getUnitId(), id.getOperationalPeriodId(), taskId);
	}

	public int assignTask(long unitId, long opPeriodId, long taskId) {

		List<String> fields = new ArrayList<String>();
		fields.add("id");
		fields.add("unit_id");
		fields.add("operational_period_id");
		fields.add("form_id");
		fields.add("completed");

		MapSqlParameterSource paramMap = new MapSqlParameterSource();
		paramMap.addValue("id", getNextTaskAssignId());
		paramMap.addValue("unit_id", unitId);
		paramMap.addValue("operational_period_id", opPeriodId);
		paramMap.addValue("form_id", taskId);
		paramMap.addValue("completed", false);

		QueryModel query = QueryManager.createQuery("task_assign")
				.insertInto(fields);

		int result = -1;

		try {
			result = this.template.update(query.toString(), paramMap);
		} catch(DataAccessException e) {
			log.error("There was an exception attempting to insert a Task Assignment: " + e.getMessage(), e);
		}

		return result;
	}

	public int unassignTask(int taskId) {
		int result = -1;

		QueryModel query = QueryManager.createQuery("task_assign")
				.deleteFromTableWhere()
				.equals("id", taskId);

		try {
			result = this.template.update(query.toString(), query.getParameters());
		} catch(DataAccessException e) {
			log.error("Exception removing Task Assignment with ID: " + taskId, e);
		}

		return result;
	}

	public List<Form> getTasks(int[] formIds) {
		ArrayList<Form> forms = new ArrayList<Form> ();

		Form f = null;
		JoinRowCallbackHandler<Form> handler = new JoinRowCallbackHandler<Form>(new FormRowMapper());
		QueryModel query = null;
		for(int id : formIds) {
			query = QueryManager.createQuery("form")
					.selectAllFromTableWhere().equals("formid", id);
			this.template.query(
					query.toString(),
					//"SELECT from form where formid = ?",
					new MapSqlParameterSource("formid", id),
					//new BeanPropertyRowMapper<Form>(Form.class));
					handler);

			f = handler.getSingleResult();

			if(f != null) {
				log.info("Got form with formid("+id+")!: " + f.getMessage());
				forms.add(f);
			} else {
				log.info("Query for form with id: " + id + " resulted in a null Form");
			}
		}

		return forms;
	}

	public String getTasksString(int[] formIds) {
		List<Form> forms = getTasks(formIds);

		JSONArray arr = new JSONArray();
		for(Form f : forms) {
			arr.put(f.toJSONObject());
		}

		return arr.toString();
	}

	public List<Form> getTasks(int incidentId) {
		return getForms(incidentId, TaskingConstants.TASK_TYPE);
	}

	/* (non-Javadoc)
	 * @see edu.mit.ll.nics.sadisplay.dao.TaskingDAOGenerated#getTasksString(int)
	 */
	/* (non-Javadoc)
	 * @see edu.mit.ll.nics.sadisplay.dao.TaskingDaoGen2#getTasksString(int)
	 */
	@Override
	public String getTasksString(int incidentId) {
		List<Form> tasks = getTasks(incidentId);
		JSONArray arr = new JSONArray();
		for(Form f : tasks) {
			arr.put(f.toJSONObject());
		}

		return arr.toString();
	}

	public String getTaskString(long seqnum, long seqtime, long incidentid, long formtypeid) {

		Form f = formDao.getForm(seqnum, seqtime, incidentid, formtypeid);
		if(f != null) {
			return f.toJSONObject().toString();
		}

		return new JSONObject().toString();
	}

	// Unit Accessors

	public List<Unit> getUnits(int incidentId) {
		QueryModel query = QueryManager.createQuery(TaskingConstants.UNIT_TABLE)
				.selectAllFromTableWhere()
				.equals(TaskingConstants.UNIT_INCIDENT_ID, incidentId);

		List<Unit> units = this.template.query(query.toString(),
				query.getParameters(), new UnitRowMapper());

		return units;
	}

	public String getUnitsString(int incidentId) {

		List<Unit> units = getUnits(incidentId);

		JSONArray arr = new JSONArray();
		for(Unit u : units) {
			arr.put(u.toJSONObject());
		}

		return arr.toString();
	}

	public String getUnitString(int incidentId, int collabRoomId) {
		QueryModel query = QueryManager.createQuery(TaskingConstants.UNIT_TABLE)
				.selectAllFromTableWhere()
				.equals(TaskingConstants.UNIT_INCIDENT_ID, incidentId).and()
				.equals("collabroom_id", collabRoomId);

		JoinRowCallbackHandler<Unit> handler = new JoinRowCallbackHandler<Unit>(new UnitRowMapper());

		this.template.query(query.toString(),
				query.getParameters(), handler);

		Unit unit = null;

		try {
			unit = handler.getSingleResult();
		} catch(Exception e) {
			log.error("Exception while querying for Unit with incidentid, collabroomid: " + incidentId +
					", " + collabRoomId);
			return null;
		}

		return unit.toJSONObject().toString();
	}

	/**
	 *  TODO: maybe collabDao should have this query of permissions?
	 * 	TODO: maybe not... it additionally queries permissions and only adds permission based on results
	 */
	public void addCollabRoomPermission(int userid, int collabroomid, int roleid) {
		QueryModel query = QueryManager.createQuery(SADisplayConstants.COLLAB_ROOM_PERMISSION_TABLE)
				.selectAllFromTableWhere().equals(SADisplayConstants.USER_ID, userid).and()
				.equals(SADisplayConstants.COLLAB_ROOM_ID, collabroomid);

		List<CollabroomPermission> perms = this.template.query(query.toString(),
				query.getParameters(), new CollabRoomPermissionRowMapper());

		log.info("Found permissions on room?: " + ((perms != null) ? perms.size() : "none"));

		boolean add = true;
		for(CollabroomPermission cp : perms) {
			if(cp.getSystemRoleId() == roleid) {
				add = false;
			}
		}

		if(add) {
			log.info("ADD is true, so adding permission with id " + roleid + " to collabroomid " +
					collabroomid + " for user with id: " + userid);
			// TODO: no indication whether or not this fails or succeeds, since its return type is void
			collabRoomDao.createCollabPermission(collabroomid, roleid, userid);
		} else {
			log.info("NO permissions were found to add for " + "permission with id " + roleid + " to collabroomid " +
					collabroomid + " for user with id: " + userid);
		}
	}

	// Util function
//	private static JSONArray getJSONArray(List<SADisplayMessageEntity> entities) {
//		JSONArray arr = new JSONArray();
//		for(SADisplayMessageEntity e : entities) {
//			try {
//				arr.put(e.toJSONObject());
//			} catch (JSONException e1) {
//				log.error("failure producign JSONObject: " + e1.getMessage());
//			}
//		}
//
//		return arr;
//	}

/*
	private static List<Form> getForms_(EntityManager em, int incidentId, String type){
		List<Form> results = new ArrayList<Form>();

		int formTypeId = Util.getFormTypeId(type);
		if(formTypeId == -1){
			//formTypeId = Util.getFormTypeId(em, type);
		}

		if(formTypeId != -1){
			QueryModel incidentQuery = QueryManager.createQuery(SADisplayConstants.FORM_TABLE)
			.selectFromTableWhere().equals(SADisplayConstants.FORM_TYPE_ID, formTypeId)
			.and()
			.equals(SADisplayConstants.INCIDENT_ID, incidentId)
			.orderBy(SADisplayConstants.SEQ_TIME).asc();

			results = QueryManager.getResultList(em, incidentQuery);

			//log.debug("got result list of size #0 for incident status messages", results.size());
		}

		return results;
	}
*/

	private List<Form> getForms(int incidentId, String type){
		List<Form> results = new ArrayList<Form>();

		//int formTypeId = Util.getFormTypeId(type);
		int formTypeId = formDao.getFormTypeId(type);
		if(formTypeId == -1){
			log.error("Formtypeid not found for type: " + type + ", unable to get forms");
		} else {
			results = formDao.getForms(incidentId, formTypeId);
			log.debug("got result list of size #0 for forms of type: " + type + ", ", results.size());
		}

		return results;
	}

	public int updateAssignmentLeader(long unitId, long userId, long opPeriodId) {
		QueryModel query = QueryManager.createQuery("resource_assign")
				.update().equals("leader", false)
				.where().equals("unit_id")
				.and().equals("operational_period_id")
				.and().notEqual("user_id");

		MapSqlParameterSource paramMap = new MapSqlParameterSource();
		paramMap.addValue("unit_id", unitId);
		paramMap.addValue("leader", false);
		paramMap.addValue("operational_period_id", opPeriodId);
		paramMap.addValue("user_id", userId);

		int falsify = this.template.update(
				query.toString(),
				paramMap
		);
		log.debug("Set " + falsify + " members to leader=false");

		MapSqlParameterSource paramMapTrue = new MapSqlParameterSource();
		paramMapTrue.addValue("unit_id", unitId);
		paramMapTrue.addValue("leader", true);
		paramMapTrue.addValue("operational_period_id", opPeriodId);
		paramMapTrue.addValue("user_id", userId);

		QueryModel update = QueryManager.createQuery("resource_assign")
				.update().equals("leader", true)
				.where().equals("unit_id", unitId)
				.and().equals("operational_period_id", opPeriodId)
				.and().equals("user_id", userId);

		//String updateQuery = "update resource_assign set leader=? where unit_id=? and " +
				//"operational_period_id=? and user_id =?";
		int newLeader = this.template.update(
				//updateQuery,
				update.toString(),
				//update.getParameters()
				paramMapTrue
			);

		if(newLeader == 1) {
			log.info("Set user with id " + userId + " as the leader");
		} else {
			log.warn("Failed to set new leader with userId: " + userId);
		}

		return newLeader;
	}

	public long getNextAssignResourceId() {
		QueryModel queryModel = QueryManager.createQuery("resource_assign_seq").selectNextVal();
    	try{
    		return this.template.queryForInt(queryModel.toString(), new HashMap<String, Object>());
    	}catch(Exception e){
    		log.info("Could not retrieve next resource_assign_seq #0", e.getMessage());
    	}
    	return -1;
	}

	public long getNextUnitId() {
		QueryModel queryModel = QueryManager.createQuery("unit_seq").selectNextVal();
    	try{
    		return this.template.queryForInt(queryModel.toString(), new HashMap<String, Object>());
    	}catch(Exception e){
    		log.info("Could not retrieve next unit_seq #0", e.getMessage());
    	}
    	return -1;
	}

	// TODO: don't use/delete? Look at updateAssignmentLeader
	public int assignLeader(int unitId, int opPeriodId, int userId) {

		int result = -1;

		QueryModel query = QueryManager.createQuery("resource_assign")
				.update("leader").value("f")
				.where()
				.equals("user_id", userId).and()
				.equals("unit_id", unitId).and()
				.equals("operational_period_id", opPeriodId);

		try {
			result = this.template.update(query.toString(), query.getParameters());
		} catch(DataAccessException e) {
			log.error("Exception assigning new leader: " + e.getMessage());
		}

		return result;
	}

	public int assignResource(ResourceAssign resourceAssignment) {

		List<String> fields = new ArrayList<String>();
		fields.add("id");
		fields.add("user_id");
		fields.add("unit_id");
		fields.add("operational_period_id");
		fields.add("leader");

		MapSqlParameterSource paramMap = new MapSqlParameterSource();
		paramMap.addValue("id", getNextAssignResourceId());
		paramMap.addValue("user_id", resourceAssignment.getUserid());
		paramMap.addValue("unit_id", resourceAssignment.getAssignment().getUnit().getId());
		paramMap.addValue("operational_period_id", resourceAssignment.getAssignment().getOperationalPeriod().getId());
		paramMap.addValue("leader", resourceAssignment.isLeader());

		QueryModel query = QueryManager.createQuery("resource_assign")
				.insertInto(fields);

		int ret = this.template.update(query.toString(), paramMap);
		if(ret == 0) {
			return FAILURE;
		}

		return SUCCESS;
	}

	public int assignResource(int userId, int unitId, int opPeriodId, boolean leader) {

		List<String> fields = new ArrayList<String>();
		fields.add("id");
		fields.add("user_id");
		fields.add("unit_id");
		fields.add("operational_period_id");
		fields.add("leader");

		MapSqlParameterSource paramMap = new MapSqlParameterSource();
		paramMap.addValue("id", getNextAssignResourceId());
		paramMap.addValue("user_id", userId);
		paramMap.addValue("unit_id", unitId);
		paramMap.addValue("operational_period_id", opPeriodId);
		paramMap.addValue("leader", leader);

		QueryModel query = QueryManager.createQuery("resource_assign")
				.insertInto(fields);

		int ret = this.template.update(query.toString(), paramMap);
		if(ret == 0) {
			return FAILURE;
		}

		return SUCCESS;
	}

	public int removeResourceAssign(ResourceAssign resourceAssign) {

		QueryModel query = QueryManager.createQuery("resource_assign")
				.deleteFromTableWhere().equals("id", resourceAssign.getId());

		int result = 0;
		try {
			result = this.template.update(query.toString(), query.getParameters());
		} catch(Exception e) {
			log.error("Exception deleting Resource Assignment with id("+resourceAssign.getId()+"): " +
					e.getMessage(), e);
		}

		return result;
	}

	public ResourceAssign getResourceAssign(long unitId, long opPeriodId, long userId) {

		QueryModel query = QueryManager.createQuery("resource_assign").selectAllFromTableWhere()
			.equals("unit_id", unitId).and().equals("operational_period_id", opPeriodId)
			.and().equals("user_id", userId);

		ResourceAssign resource = (ResourceAssign) this.template.queryForObject(query.toString(),
				query.getParameters(),
				new ResourceAssignRowMapper());

		log.info("getResourceAssign: Found resource: " + ((resource != null) ? resource.getId() : "null"));

		return resource;
	}

	public boolean isResourceAssignedForOpPeriod(long opPeriodId, long userId) {
		QueryModel query = QueryManager.createQuery("resource_assign")
				.selectAllFromTableWhere()
				.equals("operational_period_id", opPeriodId)
				.and()
				.equals("user_id", userId);

		MapSqlParameterSource paramMap = new MapSqlParameterSource();
		paramMap.addValue("operational_period_id", opPeriodId);
		paramMap.addValue("user_id", userId);

		ResourceAssign ra = null;
		try {
			ra = this.template.queryForObject(query.toString(), paramMap, new ResourceAssignRowMapper());
		} catch(EmptyResultDataAccessException e) {
			log.warn("No Resource assignment found for [userId, opPeriodId]: " +
					userId + ", " + opPeriodId);
		}

		if( ra != null) {
			log.info("Testing to see if resource was assigned for op period, got: " +
					ra.toJSONObject().toString());
			return true;
		} else {
			log.info("NO resource found assigned for that op period!");
		}

		return false;
	}

	public List<User> getAssignedUsers() {

		QueryModel query = QueryManager.createQuery("resource_assign")
				.selectDistinctFromTable("user_id")
				.join(SADisplayConstants.USER_ESCAPED);

		String queryStr = "select * from " + SADisplayConstants.USER_ESCAPED + ", resource_assign where " +
				"user_id = user_id";

		// TODO: there aren't really any mapped parameters, but...
		List<User> assignedUsers = this.template.query(queryStr, query.getParameters(),
				new UserRowMapper());

		return assignedUsers;
	}

	public int createUnit(Unit unit) {
		int status = FAILURE;

		List<String> fields = new ArrayList<String>();
		fields.add("id");
		fields.add("incident_id");
		fields.add("unitname");
		fields.add("collabroom_id");

		MapSqlParameterSource paramMap = new MapSqlParameterSource();
		long newId = getNextUnitId();
		if(newId == -1) {
			log.info("Failed to get a valid id for the next unit!");
			return FAILURE;
		}
		paramMap.addValue("id", newId);
		paramMap.addValue("incident_id", unit.getIncidentid());
		paramMap.addValue("unitname", unit.getUnitname());
		paramMap.addValue("collabroom_id", unit.getCollabroomid());

		QueryModel query = QueryManager.createQuery(TaskingConstants.UNIT_TABLE)
				.insertInto(fields);

		try {
			int result = this.template.update(query.toString(), paramMap);

			if(result == 1) {
				status = SUCCESS;
			}
		} catch(DataAccessException e) {
			log.error("DataAccessException while creating Unit: " + e.getMessage() +
					"\nMost Specific Cause: "
					+ ((e.getMostSpecificCause() != null) ? "Unknown" : e.getMostSpecificCause().getMessage()));

			log.debug("Exception", e);

			// TODO: See if you can find out if it hit an already exists exception, and return ALREADY_EXISTS
		} catch(Exception e) {
			log.error("Unhandled exception while creating Unit: " + e.getMessage(), e);
		}

		return status;
	}

	@SuppressWarnings({"rawtypes"})
	private JoinRowCallbackHandler<Assignment> getAssignmentHandlerWith(JoinRowMapper...mappers) {
		return new JoinRowCallbackHandler<Assignment>(new AssignmentRowMapper(), mappers);
	}
}


text:
package AsposeCellsExamples.Tables;

import com.aspose.cells.Cell;
import com.aspose.cells.Cells;
import com.aspose.cells.ListObject;
import com.aspose.cells.TableStyleType;
import com.aspose.cells.TotalsCalculation;
import com.aspose.cells.Workbook;
import com.aspose.cells.Worksheet;
import AsposeCellsExamples.Utils;

public class FormataListObject {
	public static void main(String[] args) throws Exception {
		// The path to the documents directory.
		String dataDir = Utils.getSharedDataDir(FormataListObject.class) + "Tables/";
		// Create a workbook.
		Workbook workbook = new Workbook();

		// Obtaining the reference of the default(first) worksheet
		Worksheet sheet = workbook.getWorksheets().get(0);

		// Obtaining Worksheet's cells collection
		Cells cells = sheet.getCells();

		// Setting the value to the cells
		Cell cell = cells.get("A1");
		cell.putValue("Employee");
		cell = cells.get("B1");
		cell.putValue("Quarter");
		cell = cells.get("C1");
		cell.putValue("Product");
		cell = cells.get("D1");
		cell.putValue("Continent");
		cell = cells.get("E1");
		cell.putValue("Country");
		cell = cells.get("F1");
		cell.putValue("Sale");

		cell = cells.get("A2");
		cell.putValue("David");
		cell = cells.get("A3");
		cell.putValue("David");
		cell = cells.get("A4");
		cell.putValue("David");
		cell = cells.get("A5");
		cell.putValue("David");
		cell = cells.get("A6");
		cell.putValue("James");
		cell = cells.get("A7");
		cell.putValue("James");
		cell = cells.get("A8");
		cell.putValue("James");
		cell = cells.get("A9");
		cell.putValue("James");
		cell = cells.get("A10");
		cell.putValue("James");
		cell = cells.get("A11");
		cell.putValue("Miya");
		cell = cells.get("A12");
		cell.putValue("Miya");
		cell = cells.get("A13");
		cell.putValue("Miya");
		cell = cells.get("A14");
		cell.putValue("Miya");
		cell = cells.get("A15");
		cell.putValue("Miya");

		cell = cells.get("B2");
		cell.putValue(1);
		cell = cells.get("B3");
		cell.putValue(2);
		cell = cells.get("B4");
		cell.putValue(3);
		cell = cells.get("B5");
		cell.putValue(4);
		cell = cells.get("B6");
		cell.putValue(1);
		cell = cells.get("B7");
		cell.putValue(2);
		cell = cells.get("B8");
		cell.putValue(3);
		cell = cells.get("B9");
		cell.putValue(4);
		cell = cells.get("B10");
		cell.putValue(4);
		cell = cells.get("B11");
		cell.putValue(1);
		cell = cells.get("B12");
		cell.putValue(1);
		cell = cells.get("B13");
		cell.putValue(2);
		cell = cells.get("B14");
		cell.putValue(2);
		cell = cells.get("B15");
		cell.putValue(2);

		cell = cells.get("C2");
		cell.putValue("Maxilaku");
		cell = cells.get("C3");
		cell.putValue("Maxilaku");
		cell = cells.get("C4");
		cell.putValue("Chai");
		cell = cells.get("C5");
		cell.putValue("Maxilaku");
		cell = cells.get("C6");
		cell.putValue("Chang");
		cell = cells.get("C7");
		cell.putValue("Chang");
		cell = cells.get("C8");
		cell.putValue("Chang");
		cell = cells.get("C9");
		cell.putValue("Chang");
		cell = cells.get("C10");
		cell.putValue("Chang");
		cell = cells.get("C11");
		cell.putValue("Geitost");
		cell = cells.get("C12");
		cell.putValue("Chai");
		cell = cells.get("C13");
		cell.putValue("Geitost");
		cell = cells.get("C14");
		cell.putValue("Geitost");
		cell = cells.get("C15");
		cell.putValue("Geitost");

		cell = cells.get("D2");
		cell.putValue("Asia");
		cell = cells.get("D3");
		cell.putValue("Asia");
		cell = cells.get("D4");
		cell.putValue("Asia");
		cell = cells.get("D5");
		cell.putValue("Asia");
		cell = cells.get("D6");
		cell.putValue("Europe");
		cell = cells.get("D7");
		cell.putValue("Europe");
		cell = cells.get("D8");
		cell.putValue("Europe");
		cell = cells.get("D9");
		cell.putValue("Europe");
		cell = cells.get("D10");
		cell.putValue("Europe");
		cell = cells.get("D11");
		cell.putValue("America");
		cell = cells.get("D12");
		cell.putValue("America");
		cell = cells.get("D13");
		cell.putValue("America");
		cell = cells.get("D14");
		cell.putValue("America");
		cell = cells.get("D15");
		cell.putValue("America");

		cell = cells.get("E2");
		cell.putValue("China");
		cell = cells.get("E3");
		cell.putValue("India");
		cell = cells.get("E4");
		cell.putValue("Korea");
		cell = cells.get("E5");
		cell.putValue("India");
		cell = cells.get("E6");
		cell.putValue("France");
		cell = cells.get("E7");
		cell.putValue("France");
		cell = cells.get("E8");
		cell.putValue("Germany");
		cell = cells.get("E9");
		cell.putValue("Italy");
		cell = cells.get("E10");
		cell.putValue("France");
		cell = cells.get("E11");
		cell.putValue("U.S.");
		cell = cells.get("E12");
		cell.putValue("U.S.");
		cell = cells.get("E13");
		cell.putValue("Brazil");
		cell = cells.get("E14");
		cell.putValue("U.S.");
		cell = cells.get("E15");
		cell.putValue("U.S.");

		cell = cells.get("F2");
		cell.putValue(2000);
		cell = cells.get("F3");
		cell.putValue(500);
		cell = cells.get("F4");
		cell.putValue(1200);
		cell = cells.get("F5");
		cell.putValue(1500);
		cell = cells.get("F6");
		cell.putValue(500);
		cell = cells.get("F7");
		cell.putValue(1500);
		cell = cells.get("F8");
		cell.putValue(800);
		cell = cells.get("F9");
		cell.putValue(900);
		cell = cells.get("F10");
		cell.putValue(500);
		cell = cells.get("F11");
		cell.putValue(1600);
		cell = cells.get("F12");
		cell.putValue(600);
		cell = cells.get("F13");
		cell.putValue(2000);
		cell = cells.get("F14");
		cell.putValue(500);
		cell = cells.get("F15");
		cell.putValue(900);

		// Adding a new List Object to the worksheet
		ListObject listObject = sheet.getListObjects().get(sheet.getListObjects().add("A1", "F15", true));

		// Adding Default Style to the table
		listObject.setTableStyleType(TableStyleType.TABLE_STYLE_MEDIUM_10);

		// Show Total
		listObject.setShowTotals(true);

		// Set the Quarter field's calculation type
		listObject.getListColumns().get(1).setTotalsCalculation(TotalsCalculation.COUNT);

		// Saving the Excel file
		workbook.save(dataDir + "FormataListObject_out.xlsx");
	}
}

redpajama_set_name: RedPajamaGithub


text:
{-# LANGUAGE BangPatterns, PatternGuards #-}

module SECDH.Eval
       ( secdhEval
       , secdhInit
       , secdhInitProgram
       , secdhFinish
       , secdhEvalStats
       , secdhFinishStats
       , secdhIter
       , Rule (..)
       ) where

--import Debug.Trace

import Language.Slambda.Types
import Language.Slambda.Show
import Language.Slambda.Util

import SECDH.Types
import SECDH.Show

import Control.Monad
import Data.Bits (shiftL, shiftR)
import Data.Char
import Data.List
import Data.Monoid
import Data.Map (Map, (!))
import qualified Data.Map as Map
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Sequence (Seq, (|>))
import qualified Data.Sequence as Seq

secdhStats :: SECDH -> Rule -> SECDHStats
secdhStats (SECDH s e c d h) r =
  SECDHStats
  { secdhStatsIters       = 1
  , secdhStatsMaxStack    = length s
  , secdhStatsMaxEnv      = Map.size e
  , secdhStatsMaxControl  = length c
  , secdhStatsMaxDump     = length d
  , secdhStatsMaxHeap     = Seq.length h
  , secdhStatsMaxRetained = 0
  , secdhStatsGCs         = 0
  , secdhStatsRuleExecs   = Map.singleton r 1
  }

emptyEnv :: Env
emptyEnv = Map.empty
emptyHeap :: Heap
emptyHeap = Seq.empty

loopA :: Atom
loopA = ErrorA "loop"

termToClosure :: Term -> Atom
termToClosure (AbsT s i t) = ClosureA emptyEnv s i t
termToClosure t = error $ "cannot make closure from non-abstraction term: " ++ termToString t

trueA, falseA :: Atom
trueA  = termToClosure trueT
falseA = termToClosure falseT

pruneEnv :: Term -> Env -> Env
pruneEnv t =
  let vs = freeVars t
  in Map.filterWithKey (\v n -> Set.member v vs)

mkClosure :: Env -> Strictness -> Var -> Term -> Atom
mkClosure e s i t =
  ClosureA (pruneEnv t e) s i t

mkObject :: Env -> Term -> Object
mkObject _ (ConstT k)   = AtomOb (ConstA k)
mkObject _ (PrimT p)    = AtomOb (primToAtom p)
mkObject e (AbsT s i t) = AtomOb (mkClosure e s i t)
mkObject e t            = SuspOb (pruneEnv t e) t

primToAtom :: Prim -> Atom
primToAtom IOReadP = IOActionA ReadIO
primToAtom p       = PrimA p []

primArity :: Prim -> Arity
primArity IOReturnP = 1
primArity IOBindP   = 2
primArity IOReadP   = 0
primArity IOWriteP  = 1
primArity UnitPP    = 1
primArity IntegerPP = 1
primArity LambdaPP  = 1
primArity NegP      = 1
primArity SuccP     = 1
primArity PredP     = 1
primArity Mul2P     = 1
primArity Div2P     = 1
primArity ZeroPP    = 1
primArity PosPP     = 1
primArity EvenPP    = 1
primArity OddPP     = 1
primArity AddP      = 2
primArity SubP      = 2
primArity MulP      = 2
primArity DivP      = 2
primArity ModP      = 2
primArity EqPP      = 2
primArity ChrP      = 1
primArity OrdP      = 1

invalidPrimAppError :: Prim -> [Atom] -> Atom
invalidPrimAppError p xs =
  ErrorA ("invalid application of primitive %" ++ primName p ++ " to arguments " ++
          concat (intersperse ", " (map atomToString xs)))

applyPrim :: Prim -> [Atom] -> Atom

applyPrim p         xs | length xs /= primArity p                  =
  error $ "invalid number of arguments (" ++ show (length xs) ++ ") supplied for primitive " ++ primName p

applyPrim IOReturnP [a]                                            = IOActionA (ReturnIO a)

applyPrim IOBindP   [ErrorA s, _]                                  = ErrorA s
applyPrim IOBindP   [ConstA BottomC, _]                            = ConstA BottomC
applyPrim IOBindP   [IOActionA io, a]                              = IOActionA (BindIO io a)
applyPrim IOBindP   xs                                             = invalidPrimAppError IOBindP xs

-- the remaining primitives are strict in both arguments
applyPrim _         args
  | Just a <- find (\a -> case a of ErrorA _ -> True; _ -> False) args = a
applyPrim _         args
  | Just a <- find (\a -> case a of ConstA BottomC -> True; _ -> False) args = a

applyPrim IOWriteP  [ConstA (CharC ch)]                            = IOActionA (WriteIO ch)

applyPrim UnitPP    [ConstA UnitC]                                 = trueA
applyPrim UnitPP    [_]                                            = falseA

applyPrim IntegerPP [ConstA (IntegerC _)]                          = trueA
applyPrim IntegerPP [_]                                            = falseA

applyPrim LambdaPP  [ClosureA _ _ _ _]                             = trueA
applyPrim LambdaPP  [PrimA p args] | primArity p - length args > 0 = trueA
applyPrim LambdaPP  [_]                                            = falseA

applyPrim NegP      [ConstA (IntegerC x)]                          = ConstA (IntegerC (negate x))

applyPrim SuccP     [ConstA (IntegerC x)]                          = ConstA (IntegerC (succ x))

applyPrim PredP     [ConstA (IntegerC x)]                          = ConstA (IntegerC (pred x))

applyPrim Mul2P     [ConstA (IntegerC x)]                          = ConstA (IntegerC (x * 2))

applyPrim Div2P     [ConstA (IntegerC x)]                          = ConstA (IntegerC (x `div` 2))

applyPrim ZeroPP    [ConstA (IntegerC 0)]                          = trueA
applyPrim ZeroPP    [_]                                            = falseA

applyPrim PosPP     [ConstA (IntegerC n)] | n > 0                  = trueA
applyPrim PosPP     [_]                                            = falseA

applyPrim EvenPP    [ConstA (IntegerC n)] | even n                 = trueA
applyPrim EvenPP    [_]                                            = falseA

applyPrim OddPP     [ConstA (IntegerC n)] | odd n                  = trueA
applyPrim OddPP     [_]                                            = falseA

applyPrim AddP      [ConstA (IntegerC x), ConstA (IntegerC y)]     = ConstA (IntegerC (x + y))
applyPrim SubP      [ConstA (IntegerC x), ConstA (IntegerC y)]     = ConstA (IntegerC (x - y))
applyPrim MulP      [ConstA (IntegerC x), ConstA (IntegerC y)]     = ConstA (IntegerC (x * y))
applyPrim DivP      [ConstA (IntegerC x), ConstA (IntegerC y)]     = ConstA (IntegerC (x `div` y))
applyPrim ModP      [ConstA (IntegerC x), ConstA (IntegerC y)]     = ConstA (IntegerC (x `mod` y))

applyPrim EqPP      [ConstA (IntegerC x), ConstA (IntegerC y)] | x == y = trueA
applyPrim EqPP      [ConstA (CharC x),    ConstA (CharC y)]    | x == y = trueA
applyPrim EqPP      [ConstA UnitC,        ConstA UnitC]                 = trueA
applyPrim EqPP      [_, _]                                              = falseA

applyPrim ChrP      [ConstA (IntegerC n)]                          = ConstA (CharC (chr (fromInteger n)))
applyPrim OrdP      [ConstA (CharC c)]                             = ConstA (IntegerC (toInteger (ord c)))

applyPrim p         xs                                             =
  invalidPrimAppError p xs

secdhEval :: MonadSECDHIO m => Program -> m Atom
secdhEval =
  liftM snd . secdhFinish . secdhGC . secdhInitProgram

secdhEvalStats :: MonadSECDHIO m => Program -> m (Atom, SECDHStats)
secdhEvalStats =
  liftM (\(_, r, s) -> (r, s)) . secdhFinishStats . secdhGC . secdhInitProgram

secdhInit :: Env -> Heap -> Term -> SECDH
secdhInit e h t =
  SECDH
  { secdhStack   = []
  , secdhEnv     = e
  , secdhControl = [TermI t]
  , secdhDump    = []
  , secdhHeap    = h
  }

secdhInitProgram :: Program -> SECDH
secdhInitProgram prog =
  secdhInit emptyEnv emptyHeap (LetRecT prog (VarT (Var mainProgramName)))

secdhGCFactor = 4
secdhGCInitLimit = 1024

secdhFinish :: MonadSECDHIO m => SECDH -> m (SECDH, Atom)
secdhFinish = secdhFinish' secdhGCInitLimit
  where secdhFinish' !gcLim !secdh = do
          (secdh', _, mbResult) <- secdhIter secdh
          case mbResult of
            Just r ->
              return (secdh', r)
            Nothing ->
              if Seq.length (secdhHeap secdh') > gcLim
              then let secdh'' = secdhGC secdh'
                       gcLim' = max gcLim (secdhGCFactor * Seq.length (secdhHeap secdh''))
                   in --trace ("Retained: " ++ show (Seq.length (secdhHeap secdh'')) ++ "\nGC Limit: " ++ show gcLim') $
                      secdhFinish' gcLim' secdh''
              else secdhFinish' gcLim secdh'

secdhFinishStats :: MonadSECDHIO m => SECDH -> m (SECDH, Atom, SECDHStats)
secdhFinishStats = secdhFinishStats' mempty secdhGCInitLimit
  where secdhFinishStats' !stats !gcLim secdh = do
          (secdh', rule, mbResult) <- secdhIter secdh
          case mbResult of
            Just r ->
              return (secdh', r, stats)
            Nothing ->
              if Seq.length (secdhHeap secdh') > gcLim
              then let !secdh'' = secdhGC secdh'
                       !gcLim'  = max gcLim (secdhGCFactor * Seq.length (secdhHeap secdh''))
                       !stats'  = stats { secdhStatsGCs = succ (secdhStatsGCs stats)
                                        , secdhStatsMaxRetained = max (secdhStatsMaxRetained stats) (Seq.length (secdhHeap secdh'')) }
                   in secdhFinishStats' (mappend stats' (secdhStats secdh rule)) gcLim' secdh''
              else secdhFinishStats' (mappend stats (secdhStats secdh rule)) gcLim secdh'

secdhApplyNonFunctionError :: String -> Atom
secdhApplyNonFunctionError s =
  ErrorA (s ++ " is not a function, but treated as one")

invalidSECDHState :: SECDH -> a
invalidSECDHState secdh =
  error $ "invalid secdh state:\n" ++ secdhToString secdh

secdhIter :: MonadSECDHIO m => SECDH -> m (SECDH, Rule, Maybe Atom)
-- Perform IO
secdhIter secdh@(SECDH [AtomV (IOActionA io)] _ [] [] h) =
  case io of
    ReturnIO a ->
      return ( secdh
             , Rule 1
             , Just a )
    BindIO io a ->
      return ( SECDH [AtomV (IOActionA io),AtomV a] emptyEnv [IOBindI] [] h
             , Rule 2
             , Nothing )
    ReadIO -> do
      mbc <- secdhRead
      return ( SECDH [AtomV (ConstA (maybe UnitC CharC mbc))] emptyEnv [] [] h
             , Rule 3
             , Nothing )
    WriteIO ch -> do
      secdhWrite ch
      return ( SECDH [AtomV (ConstA UnitC)] emptyEnv [] [] h
             , Rule 4
             , Nothing )
-- Termination condition.
secdhIter secdh@(SECDH [v@(AtomV a)] _ [] [] _) =
  return ( secdh
         , Rule 5
         , Just a )
-- Pop off the dump stack when a sub-computation is completed.
secdhIter (SECDH [v] _ [] ((s', e', c'):d') h) =
  return ( SECDH (v:s') e' c' d' h
         , Rule 6
         , Nothing )
-- If a pointer is all that's left, dereference it and, if necessary,
-- set up an update and enter a suspension.
secdhIter (SECDH [PointerV n] e [] [] h) | n < Seq.length h =
  case Seq.index h n of
    AtomOb a ->
      return ( SECDH [AtomV a] e [] [] h
             , Rule 7
             , Nothing )
    SuspOb e' t ->
      return ( SECDH [] e' [TermI t] [([],e,[UpdateI n])] (Seq.update n UpdatingOb h)
             , Rule 8
             , Nothing )
    IndirOb n' ->
      return ( SECDH [PointerV n'] e [] [] h
             , Rule 9
             , Nothing )
    UpdatingOb ->
      return ( SECDH [AtomV loopA] e [] [] h
             , Rule 10
             , Nothing )
secdhIter (SECDH (PointerV n:s) e (IOBindI:c) [] h) =
  case Seq.index h n of
    AtomOb a ->
      return ( SECDH (AtomV a:s) e (IOBindI:c) [] h
             , Rule 11
             , Nothing )
    SuspOb e' t ->
      return ( SECDH [] e' [TermI t] [(s,e,UpdateI n:IOBindI:c)] (Seq.update n UpdatingOb h)
             , Rule 12
             , Nothing )
    IndirOb n' ->
      return ( SECDH (PointerV n':s) e (IOBindI:c) [] h
             , Rule 13
             , Nothing )
    UpdatingOb ->
      return ( SECDH (AtomV loopA:s) e (IOBindI:c) [] h
             , Rule 14
             , Nothing )
secdhIter (SECDH (AtomV (IOActionA io):s) e (IOBindI:c) [] h) =
  case io of
    ReturnIO a ->
      return ( SECDH (AtomV a:s) e (ApI True:c) [] h
             , Rule 15
             , Nothing )
    BindIO io a ->
      return ( SECDH (AtomV (IOActionA io):AtomV a:s) e (IOBindI:IOBindI:c) [] h
             , Rule 16
             , Nothing )
    ReadIO -> do
      mbc <- secdhRead
      return ( SECDH (AtomV (ConstA (maybe UnitC CharC mbc)):s) e (ApI True:c) [] h
             , Rule 17
             , Nothing )
    WriteIO ch -> do
      secdhWrite ch
      return ( SECDH (AtomV (ConstA UnitC):s) e (ApI True:c) [] h
             , Rule 18
             , Nothing )
secdhIter (SECDH (AtomV (ErrorA r):s) e (IOBindI:c) [] h) =
  return ( SECDH (AtomV (ErrorA r):s) e (ApI True:c) [] h
         , Rule 19
         , Nothing )
secdhIter (SECDH (AtomV (ConstA BottomC):s) e (IOBindI:c) [] h) =
  return ( SECDH (AtomV (ConstA BottomC):s) e (ApI True:c) [] h
         , Rule 20
         , Nothing )
secdhIter (SECDH (AtomV a:s) e (IOBindI:c) [] h) =
  return ( SECDH (AtomV (ErrorA ("trying to leave io monad; result was: " ++ atomToString a)):s) e (ApI True:c) [] h
         , Rule 21
         , Nothing )
-- Handle tail calls.
secdhIter (SECDH [f,x] e [ApI False] ((s', e', c'):d) h) =
  return ( SECDH (f:x:s') e' (ApI False:c') d h
         , Rule 22
         , Nothing )
-- If the next instruction is UpdateI, and we have an atom, then
-- update the heap and pop the instruction
secdhIter (SECDH s@(AtomV a:_) e (UpdateI n:c) d h) =
  return ( SECDH s e c d (Seq.update n (AtomOb a) h)
         , Rule 23
         , Nothing )
-- If the next instruction is UpdateI, and we have a pointer:
-- If the pointer is to an atom, just replace the pointer with the atom
-- (the next iteration will do the update).
-- If the pointer is to a suspension, then replace the suspension being pointed to by an indirection
-- to the block being updated, and enter the suspension (this prevents a chain of updates from piling up on the C stack).
-- If the pointer is already being updated, we're in a loop.
secdhIter (SECDH (PointerV n:s) e c@(UpdateI u:c') d h) | n < Seq.length h =
  case Seq.index h n of
    AtomOb a ->
      return ( SECDH (AtomV a:s) e c d h
             , Rule 24
             , Nothing )
    SuspOb e' t ->
      return ( SECDH [] e' [TermI t] ((s,e,c):d) (Seq.update n (IndirOb u) h)
             , Rule 25
             , Nothing )
    IndirOb r ->
      return ( SECDH (PointerV r:s) e c d (Seq.update n (IndirOb u) h)
             , Rule 26
             , Nothing )
    UpdatingOb ->
      return ( SECDH (AtomV loopA:s) e c d h
             , Rule 27
             , Nothing )
-- If the next instruction is TermI, move the term onto the stack,
-- making abstractions into closures, and pushing ApI instructions for
-- applications.
-- LetRec creates a suspension in the updated environment.
secdhIter (SECDH s e (TermI t:c) d h)
  | VarT i <- t = do
    let v = case Map.lookup i e of
              Just n  -> PointerV n
              Nothing -> AtomV (ErrorA ("undefined variable: " ++ varName i))
    return ( SECDH (v:s) e c d h
           , Rule 28
           , Nothing )
  | ConstT k <- t =
    return ( SECDH (AtomV (ConstA k):s) e c d h
           , Rule 29
           , Nothing )
  | PrimT p <- t =
    return ( SECDH (AtomV (primToAtom p):s) e c d h
           , Rule 30
           , Nothing )
  | AbsT a i t' <- t = do
    return ( SECDH (AtomV (mkClosure e a i t'):s) e c d h
           , Rule 31
           , Nothing )
  | AppT f x <- t =
    return ( SECDH (PointerV (Seq.length h):s) e (TermI f:ApI False:c) d (h |> mkObject e x)
           , Rule 32
           , Nothing )
  | LetRecT ds t' <- t = do
    let e' = foldl (flip (uncurry Map.insert)) e (zip (map fst ds) (enumFrom (Seq.length h)))
        h' = foldl (|>) h (map (mkObject e' . snd) ds)
    return ( SECDH (PointerV (Seq.length h'):s) e c d (h' |> mkObject e' t')
           , Rule 33
           , Nothing )
-- Apply a function.  If the function is a non-strict closure, just
-- make an updated environment and heap for the argument, and enter
-- the function after pushing the current state on the dump.  The
-- function is strict, swap the top 2 stack positions, and replace the
-- (ApI False) instruction with an (ApI True) instruction.  If the
-- function is a pointer, deference the pointer and enter the
-- suspension if necessary.
secdhIter (SECDH (f:x:s) e (ApI False:c) d h)
  | AtomV (ErrorA str) <- f =
    return ( SECDH (f:s) e c d h
           , Rule 34
           , Nothing )
  | AtomV (ConstA BottomC) <- f =
    return ( SECDH (AtomV (ConstA BottomC):s) e c d h
           , Rule 35
           , Nothing )
  | AtomV (ConstA k) <- f =
    return ( SECDH (AtomV (secdhApplyNonFunctionError (constToString k)):s) e c d h
           , Rule 36
           , Nothing )
  | AtomV (PrimA p []) <- f, primArity p < 1 =
    return ( SECDH (AtomV (secdhApplyNonFunctionError ('%':primName p)):s) e c d h
           , Rule 37
           , Nothing )
  | AtomV (IOActionA io) <- f =
    return ( SECDH (AtomV (secdhApplyNonFunctionError (ioActionToString io)):s) e c d h
           , Rule 38
           , Nothing )
  | AtomV (PrimA p _) <- f, primArity p >= 1 =
    return ( SECDH (x:f:s) e (ApI True:c) d h
           , Rule 39
           , Nothing )
  | AtomV (ClosureA e False i t) <- f = do
    let (e', h') =
          case x of
            AtomV xA   -> (Map.insert i (Seq.length h) e, h |> AtomOb xA)
            PointerV n -> (Map.insert i n e, h)
    return ( SECDH [] e' [TermI t] ((s,e,c):d) h'
           , Rule 40
           , Nothing )
  | AtomV (ClosureA e True i t) <- f =
    return ( SECDH (x:f:s) e (ApI True:c) d h
           , Rule 41
           , Nothing )
  | PointerV n <- f, n < Seq.length h =
    case Seq.index h n of
      AtomOb f' ->
        return ( SECDH (AtomV f':x:s) e (ApI False:c) d h
               , Rule 42
               , Nothing )
      SuspOb e' t' ->
        return ( SECDH [] e' [TermI t'] ((x:s,e,UpdateI n:ApI False:c):d) h
               , Rule 43
               , Nothing )
      IndirOb n' ->
        return ( SECDH (PointerV n':x:s) e (UpdateI n:ApI False:c) d h
               , Rule 44
               , Nothing )
      UpdatingOb ->
        return ( SECDH (AtomV loopA:s) e c d h
               , Rule 45
               , Nothing )
-- Apply a strict function. If the argument is a pointer, deference it
-- and, if necessary, set up the update and enter the suspension.
secdhIter (SECDH (x:f:s) e (ApI True:c) d h)
  | PointerV n <- x, n < Seq.length h =
    case Seq.index h n of
      AtomOb xA ->
        return ( SECDH (AtomV xA:f:s) e (ApI True:c) d h
               , Rule 46
               , Nothing )
      SuspOb e' t' ->
        return ( SECDH [] e' [TermI t'] ((f:s,e,UpdateI n:ApI True:c):d) h
               , Rule 47
               , Nothing )
      IndirOb n' ->
        return ( SECDH (PointerV n':f:s) e (UpdateI n:ApI True:c) d h
               , Rule 48
               , Nothing )
      UpdatingOb ->
        return ( SECDH (AtomV loopA:s) e c d h
               , Rule 49
               , Nothing )
  | AtomV (ErrorA str) <- x =
    return ( SECDH (x:s) e c d h
           , Rule 50
           , Nothing )
  | AtomV xA <- x, AtomV (PrimA p args) <- f =
    if 1 + length args == primArity p
    then return ( SECDH (AtomV (applyPrim p (reverse (xA:args))):s) e c d h
                , Rule 51
                , Nothing )
    else return ( SECDH (AtomV (PrimA p (xA:args)):s) e c d h
                , Rule 52
                , Nothing )
  | AtomV xA <- x, AtomV (ClosureA e _ i t) <- f =
    return ( SECDH [] (Map.insert i (Seq.length h) e) [TermI t] ((s,e,c):d) (h |> AtomOb xA)
           , Rule 53
           , Nothing )
-- Should never, ever, ever, ever get here.
-- Ever.
secdhIter secdh =
  invalidSECDHState secdh

secdhGC :: SECDH -> SECDH
secdhGC secdh@(SECDH s e c d h) =
  let ns = sRefs s ++ eRefs e ++ cRefs c ++ dRefs d
      (m, h') = copy ns h
  in SECDH (remaps m s) (remape m e) (remapc m c) (remapd m d) (remaph m h')

  where atomRefs :: Atom -> [Addr]
        atomRefs (PrimA _ args)     = args >>= atomRefs
        atomRefs (ClosureA e _ _ _) = eRefs e
        atomRefs (IOActionA io)     = ioRefs io
        atomRefs _                  = mzero

        ioRefs (ReturnIO a)  = atomRefs a
        ioRefs (BindIO io a) = ioRefs io `mplus` atomRefs a
        ioRefs _             = mzero

        sRefs :: Stack -> [Addr]
        sRefs s = do
          v <- s
          case v of
            AtomV a    -> atomRefs a
            PointerV n -> return n
        eRefs :: Env -> [Addr]
        eRefs e =
          Map.elems e
        cRefs :: Control -> [Addr]
        cRefs c = do
          i <- c
          case i of
            UpdateI n -> return n
            _         -> mzero
        dRefs :: Dump -> [Addr]
        dRefs d = do
          (s,e,c) <- d
          sRefs s `mplus` eRefs e `mplus` cRefs c

        copy :: [Addr] -> Heap -> (Map Addr Addr, Heap)
        copy =
          let copy' :: Map Addr Addr -> Heap -> [Addr] -> Heap -> (Map Addr Addr, Heap)
              copy' m hn nos ho =
                case nos of
                  [] -> (m, hn)
                  no:nos' ->
                    case Map.lookup no m of
                      Just _ ->
                        copy' m hn nos' ho
                      Nothing ->
                        let nn = Seq.length hn
                            o = Seq.index h no
                            m' = Map.insert no nn m
                            hn' = hn |> o
                        in case Seq.index ho no of
                             SuspOb e _ ->
                               copy' m' hn' (Map.elems e ++ nos') ho
                             IndirOb po ->
                               case Map.lookup po m of
                                 Just pn ->
                                   copy' (Map.insert no pn m) hn nos' ho
                                 Nothing ->
                                   copy' m hn (po:no:nos') ho
                             AtomOb a ->
                               copy' m' hn' (atomRefs a ++ nos') ho
                             o ->
                               copy' m' hn' nos' ho
          in copy' Map.empty Seq.empty

        remapio :: Map Addr Addr -> IOAction -> IOAction
        remapio m (ReturnIO a)  = ReturnIO (remapAtom m a)
        remapio m (BindIO io a) = BindIO (remapio m io) (remapAtom m a)
        remapio _ io            = io

        remapAtom :: Map Addr Addr -> Atom -> Atom
        remapAtom m (PrimA p args)     = PrimA p (map (remapAtom m) args)
        remapAtom m (IOActionA io)     = IOActionA (remapio m io)
        remapAtom m (ClosureA e s i t) = ClosureA (remape m e) s i t
        remapAtom _ a                  = a

        remaps :: Map Addr Addr -> Stack -> Stack
        remaps m = map $ \v ->
          case v of
            AtomV a ->
              AtomV (remapAtom m a)
            PointerV n ->
              PointerV (m ! n)

        remape :: Map Addr Addr -> Env -> Env
        remape m = Map.map (m!)

        remapc :: Map Addr Addr -> Control -> Control
        remapc m = map $ \i ->
          case i of
            UpdateI n -> UpdateI (m ! n)
            _         -> i

        remapd :: Map Addr Addr -> Dump -> Dump
        remapd m = map $ \(s, e, c) ->
          (remaps m s, remape m e, remapc m c)

        remaph :: Map Addr Addr -> Heap -> Heap
        remaph m = fmap $ \o ->
          case o of
            AtomOb a -> AtomOb (remapAtom m a)
            SuspOb e t -> SuspOb (remape m e) t
            IndirOb p -> IndirOb (m ! p)
            _ -> o


text:
from __future__ import absolute_import
# Copyright (c) 2010-2019 openpyxl

from openpyxl.descriptors import Bool
from openpyxl.descriptors.serialisable import Serialisable

class Protection(Serialisable):
    """Protection options for use in styles."""

    tagname = "protection"

    locked = Bool()
    hidden = Bool()

    def __init__(self, locked=True, hidden=False):
        self.locked = locked
        self.hidden = hidden


text:
package com.gzsll.hupu.api.login;

import com.gzsll.hupu.bean.CookieData;
import com.gzsll.hupu.components.retrofit.FastJsonConverterFactory;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import rx.Observable;
import rx.schedulers.Schedulers;

/**
 * Created by sll on 2015/3/8.
 */
public class CookieApi {
    private CookieService mCookieService;

    private static final String BASE_URL = "http://passport.hupu.com/pc/login/";

    public CookieApi(OkHttpClient mOkHttpClient) {
        Retrofit retrofit =
                new Retrofit.Builder().addConverterFactory(FastJsonConverterFactory.create())
                        .client(mOkHttpClient)
                        .baseUrl(BASE_URL)
                        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                        .build();
        mCookieService = retrofit.create(CookieService.class);
    }

    public Observable<CookieData> login(String userName, String passWord) {
        return mCookieService.login(userName, passWord).subscribeOn(Schedulers.io());
    }
}


text:
package lila

package object tv extends PackageObject {

  private[tv] def logger = lila.log("tv")
}


text:
package mobi.anoda.archinamon.kernel.persefone.ui.async.binder;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import mobi.anoda.archinamon.kernel.persefone.annotation.Implement;
import mobi.anoda.archinamon.kernel.persefone.service.AbstractIntentService.RendezvousBinder;
import mobi.anoda.archinamon.kernel.persefone.service.async.AbstractAsyncServer;
import mobi.anoda.archinamon.kernel.persefone.service.async.AsyncRequest;
import mobi.anoda.archinamon.kernel.persefone.ui.context.StableContext;
import mobi.anoda.archinamon.kernel.persefone.ui.delegate.NetworkState;

/**
 * Created by matsukov-ea on 22.09.2014.
 */
public final class UiAffectionChain {

    private final          Object              MUTEX            = new Object();
    protected static final Stack<AsyncRequest> POSTPONED_CALLS  = new Stack<>();
    private final          List<OnServerReady> mServerListeners = new ArrayList<>();
    private final StableContext mStableContext;
    private final NetworkState  mNetworkWatchdog;

    protected RendezvousBinder                     mServerBinder;
    protected Class<? extends AbstractAsyncServer> mAsyncServiceImpl;
    protected volatile boolean           mIsBound    = false;
    private            ServiceConnection mConnection = new ServiceConnection() {

        @Implement
        public void onServiceConnected(ComponentName className, IBinder service) {
            mServerBinder = (RendezvousBinder) service;
            mIsBound = true;

            if (mServerListeners.size() > 0) {
                for (OnServerReady listener : mServerListeners) {
                    listener.onBind(service);
                }
            }

            if (mNetworkWatchdog.assertInternetAccess(false))
                untwistStack();
        }

        @Implement
        public void onServiceDisconnected(ComponentName className) {
            mServerBinder = null;
            mIsBound = false;

            if (mServerListeners.size() > 0) {
                for (OnServerReady listener : mServerListeners) {
                    listener.onDisconnect();
                }
            }
        }
    };

    public UiAffectionChain(StableContext stableContext) {
        this.mNetworkWatchdog = NetworkState.obtain(stableContext);
        this.mStableContext = stableContext;
    }

    public final void setServerListener(OnServerReady l) {
        mServerListeners.add(l);

        if (mIsBound) {
            l.onBind(mServerBinder);
        }
    }

    public final void removeServerListener(OnServerReady l) {
        mServerListeners.remove(l);
        l.onDisconnect();
    }

    public void doBindService(Class<? extends AbstractAsyncServer> service) {
        mAsyncServiceImpl = service;
        mNetworkWatchdog.linkWithAsyncChainBinder(this);
        mStableContext.bindService(new Intent(mStableContext.obtainAppContext(), service), mConnection, Context.BIND_AUTO_CREATE);
    }

    /**
     * Unbinding randevu binder always processing in abstract instance
     */
    public void doUnbindService() {
        if (mIsBound) {
            mStableContext.unbindService(mConnection);
            mNetworkWatchdog.unlinkFromAsyncChainBinder();
            mConnection.onServiceDisconnected(mStableContext.getInfo());
        }
    }

    /* Helper for asynchronous starting REST requests */
    private void startAsyncServer(AsyncRequest request) {
        AsyncRequest.send(mStableContext.obtainAppContext(), request, mAsyncServiceImpl);

        if (mServerListeners.size() > 0) {
            for (OnServerReady listener : mServerListeners) {
                listener.onRendezvous(request);
            }
        }
    }

    /* Helper to postpone REST tasks */
    public void postponeRequest(AsyncRequest request) {
        if (mNetworkWatchdog.assertInternetAccess(false) && mIsBound) {
            startAsyncServer(request);
        } else {
            addCallToStack(request);
        }
    }

    public void addCallToStack(AsyncRequest request) {
        mNetworkWatchdog.assertInternetAccess(true);
        synchronized (MUTEX) {
            POSTPONED_CALLS.push(request);
        }
    }

    /* Helper for untwisting postponed REST tasks */
    public void untwistStack() {
        if (!POSTPONED_CALLS.empty()) {
            synchronized (MUTEX) {
                while (!POSTPONED_CALLS.empty()) {
                    AsyncRequest request = POSTPONED_CALLS.pop();
                    AsyncRequest.send(mStableContext.obtainAppContext(), request, mAsyncServiceImpl);

                    if (mServerListeners.size() > 0) {
                        for (OnServerReady listener : mServerListeners) {
                            listener.onRendezvous(request);
                        }
                    }
                }
            }
        }
    }
}


text:
class Host
  include Mongoid::Document
  include Mongoid::Timestamps

  # Router host type value
  TYPE_ROUTER = :router
  # Switch host type value
  TYPE_SWITCH = :switch
  # Server host type value
  TYPE_SERVER = :server
  # Computer host type value
  TYPE_COMPUTER = :computer
  # Generic host type value
  TYPE_GENERIC = :generic

  # Array with the available types of a host
  AVAILABLE_TYPES = [:router, :switch, :server, :computer, :generic]

  # Fields of the model
  field :name,          :type => String, :default => ""
  field :description,   :type => String, :default => ""
  field :active,        :type => Boolean, :default => true
  field :address,       :type => String, :default => ""
  field :type,          :type => Symbol, :default => Host::TYPE_GENERIC

  # Services of this host
  has_and_belongs_to_many :services, :dependent => :nullify

  # Alerts of this host
  has_and_belongs_to_many :alerts, :dependent => :nullify

  before_destroy :remove_services

  # Name validations
  validates_length_of :name, :minimum => 2, :maximum => 30

  # Host type validations
  validates_inclusion_of :type, in: AVAILABLE_TYPES

  # Address validations
  validates_uniqueness_of :address
  validate :check_address

  # Validations to check the presence of required fields
  validates_presence_of :name
  validates_presence_of :active
  validates_presence_of :address
  validates_presence_of :type

  # Function to get the IP address of the host.
  #
  # [Returns]
  #   A string with IP address resolved, or nil if it fails to resolve.
  #
  def ip_address
    begin
      return Resolv.getaddress(self.address)
    rescue Resolv::ResolvError
      return nil
    end
  end

  # Function to check if the host is active.
  #
  # [Returns]
  #   A boolean that indicates if the host is active.
  #
  def is_active?
    return self.active
  end

  # Function to check if the host is a router.
  #
  # [Returns]
  #   A boolean that indicates if the host is a router.
  #
  def is_router?
    return (self.type == Host::TYPE_ROUTER)
  end

  # Function to check if the host is a switch.
  #
  # [Returns]
  #   A boolean that indicates if the host is a switch.
  #
  def is_switch?
    return (self.type == Host::TYPE_SWITCH)
  end

  # Function to check if the host is a server.
  #
  # [Returns]
  #   A boolean that indicates if the host is a server.
  #
  def is_server?
    return (self.type == Host::TYPE_SERVER)
  end

  # Function to check if the host is a computer.
  #
  # [Returns]
  #   A boolean that indicates if the host is a computer.
  #
  def is_computer?
    return (self.type == Host::TYPE_COMPUTER)
  end

  # Function to check if the host type is generic.
  #
  # [Returns]
  #   A boolean that indicates if the host type is generic.
  #
  def is_generic?
    return (self.type == Host::TYPE_GENERIC)
  end

  # Function to check if a host type is valid.
  #
  # [Parameters]
  #   * *type* - The host type to check.
  #
  # [Returns]
  #   A boolean indicating if the host type received is valid or not.
  #
  def self.valid_type?(type)
    return false if (type.blank?)

    # Is a valid level?
    return Host::AVAILABLE_TYPES.include?(type)
  end

  protected

  # Validation to check if the content of the :address field is
  # a valid IP or can be resolved to an IP.
  #
  # [Returns]
  #   A boolean that indicates if the address is valid.
  #
  def check_address
    begin
      # Try to resolve the address
      ip = Resolv.getaddress(self.address)
      return true
    rescue Resolv::ResolvError
      # If an error raises, add it to the response
      errors.add(:address, 'invalid address')
      return false
    end
  end

  # Function to remove the services assigned to this host before
  # destroying it.
  #
  def remove_services
    self.services.each do |serv|
      serv.hosts.delete(self)
    end
  end
end


text:
package org.apache.drill.exec.physical.impl.xsort.managed;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

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

import org.apache.drill.common.expression.FieldReference;
import org.apache.drill.common.logical.data.Order.Ordering;
import org.apache.drill.common.types.TypeProtos.DataMode;
import org.apache.drill.common.types.TypeProtos.MinorType;
import org.apache.drill.exec.ops.OperExecContext;
import org.apache.drill.exec.physical.config.Sort;
import org.apache.drill.exec.physical.impl.xsort.managed.PriorityQueueCopierWrapper.BatchMerger;
import org.apache.drill.exec.record.VectorContainer;
import org.apache.drill.exec.record.BatchSchema;
import org.apache.drill.exec.record.BatchSchema.SelectionVectorMode;
import org.apache.drill.test.OperatorFixture;
import org.apache.drill.test.rowSet.DirectRowSet;
import org.apache.drill.test.rowSet.RowSet;
import org.apache.drill.test.rowSet.RowSetComparison;
import org.apache.drill.test.rowSet.RowSetSchema;
import org.apache.drill.test.rowSet.SchemaBuilder;
import org.apache.drill.test.rowSet.RowSet.SingleRowSet;

import com.google.common.collect.Lists;

public class SortTestUtilities {

  private SortTestUtilities() { }

  public static BatchSchema makeSchema(MinorType type, boolean nullable) {
    return new SchemaBuilder()
        .add("key", type, nullable ? DataMode.OPTIONAL : DataMode.REQUIRED)
        .add("value", MinorType.VARCHAR)
        .build();
  }

  public static BatchSchema nonNullSchema() {
    return makeSchema(MinorType.INT, false);
  }

  public static BatchSchema nullableSchema() {
    return makeSchema(MinorType.INT, true);
  }

  public static PriorityQueueCopierWrapper makeCopier(OperatorFixture fixture, String sortOrder, String nullOrder) {
    FieldReference expr = FieldReference.getWithQuotedRef("key");
    Ordering ordering = new Ordering(sortOrder, expr, nullOrder);
    Sort popConfig = new Sort(null, Lists.newArrayList(ordering), false);
    OperExecContext opContext = fixture.newOperExecContext(popConfig);
    return new PriorityQueueCopierWrapper(opContext);
  }

  public static class CopierTester {
    List<SingleRowSet> rowSets = new ArrayList<>();
    List<SingleRowSet> expected = new ArrayList<>();
    String sortOrder = Ordering.ORDER_ASC;
    String nullOrder = Ordering.NULLS_UNSPECIFIED;
    private OperatorFixture fixture;

    public CopierTester(OperatorFixture fixture) {
      this.fixture = fixture;
    }

    public void addInput(SingleRowSet input) {
      rowSets.add(input);
    }

    public void addOutput(SingleRowSet output) {
      expected.add(output);
    }

    public void run() throws Exception {
      PriorityQueueCopierWrapper copier = makeCopier(fixture, sortOrder, nullOrder);
      List<BatchGroup> batches = new ArrayList<>();
      RowSetSchema schema = null;
      for (SingleRowSet rowSet : rowSets) {
        batches.add(new BatchGroup.InputBatch(rowSet.container(), rowSet.getSv2(),
                    fixture.allocator(), rowSet.size()));
        if (schema == null) {
          schema = rowSet.schema();
        }
      }
      int rowCount = outputRowCount();
      VectorContainer dest = new VectorContainer();
      @SuppressWarnings("resource")
      BatchMerger merger = copier.startMerge(schema.toBatchSchema(SelectionVectorMode.NONE),
                                             batches, dest, rowCount, null);

      verifyResults(merger, dest);
      dest.clear();
      merger.close();
    }

    public int outputRowCount() {
      if (! expected.isEmpty()) {
        return expected.get(0).rowCount();
      }
      return 10;
    }

    protected void verifyResults(BatchMerger merger, VectorContainer dest) {
      for (RowSet expectedSet : expected) {
        assertTrue(merger.next());
        RowSet rowSet = new DirectRowSet(fixture.allocator(), dest);
        new RowSetComparison(expectedSet)
              .verifyAndClearAll(rowSet);
      }
      assertFalse(merger.next());
    }
  }

}


text:
'use strict';

//Setting up route
// angular.module('core').config(['$compileProvider', 'localStorageServiceProvider',
//   function ($compileProvider, localStorageServiceProvider) {

angular.module('core').config(['$compileProvider',
  function ($compileProvider) {

    // when `false`, turns off debugging for prod
    // https://docs.angularjs.org/guide/production
    $compileProvider.debugInfoEnabled(true);

     String.prototype.toCapitalCase = function() {
      return this.charAt(0).toUpperCase() + this.slice(1);
    };

  }
]);


text:
[![CI Status](http://img.shields.io/travis/Xiaohuihui/HHTools.svg?style=flat)](https://travis-ci.org/Xiaohuihui/HHTools)
[![Version](https://img.shields.io/cocoapods/v/HHTools.svg?style=flat)](http://cocoapods.org/pods/HHTools)
[![License](https://img.shields.io/cocoapods/l/HHTools.svg?style=flat)](http://cocoapods.org/pods/HHTools)
[![Platform](https://img.shields.io/cocoapods/p/HHTools.svg?style=flat)](http://cocoapods.org/pods/HHTools)

## Example

To run the example project, clone the repo, and run `pod install` from the Example directory first.

## Requirements

## Installation

HHTools is available through [CocoaPods](http://cocoapods.org). To install
it, simply add the following line to your Podfile:

```ruby
pod 'HHTools'
```

## Author

Xiaohuihui, chhhithuihui@gmail.com

## License

HHTools is available under the MIT license. See the LICENSE file for more info.


text:
"""
Copyright 2017 D. de Vries

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

This file contains the definition of the Sellar F1 discipline.
"""
from __future__ import absolute_import, division, print_function

from math import exp

from lxml import etree

from openlego.api import AbstractDiscipline
from openlego.utils.xml_utils import xml_safe_create_element
from openlego.test_suite.test_examples.sellar_competences.kb import root_tag, x_x1, x_y1, x_y2, x_z2, x_f1
from openlego.partials.partials import Partials

class F(AbstractDiscipline):

    @property
    def creator(self):
        return u'D. de Vries'

    @property
    def description(self):
        return u'Objective function of the Sellar problem'

    @property
    def supplies_partials(self):
        return True

    def generate_input_xml(self):
        root = etree.Element(root_tag)
        doc = etree.ElementTree(root)

        xml_safe_create_element(doc, x_z2, 0.)
        xml_safe_create_element(doc, x_x1, 0.)
        xml_safe_create_element(doc, x_y1, 0.)
        xml_safe_create_element(doc, x_y2, 0.)

        return etree.tostring(doc, encoding='utf-8', pretty_print=True, xml_declaration=True)

    def generate_output_xml(self):
        root = etree.Element(root_tag)
        doc = etree.ElementTree(root)

        xml_safe_create_element(doc, x_f1, 0.)

        return etree.tostring(doc, encoding='utf-8', pretty_print=True, xml_declaration=True)

    def generate_partials_xml(self):
        partials = Partials()
        partials.declare_partials(x_f1, [x_x1, x_y1, x_y2, x_z2])
        return partials.get_string()

    @staticmethod
    def execute(in_file, out_file):
        doc = etree.parse(in_file)
        z2 = float(doc.xpath(x_z2)[0].text)
        x1 = float(doc.xpath(x_x1)[0].text)
        y1 = float(doc.xpath(x_y1)[0].text)
        y2 = float(doc.xpath(x_y2)[0].text)

        f1 = x1**2. + z2 + y1 + exp(-y2)

        root = etree.Element(root_tag)
        doc = etree.ElementTree(root)
        xml_safe_create_element(doc, x_f1, f1)
        doc.write(out_file, encoding='utf-8', pretty_print=True, xml_declaration=True)

    @staticmethod
    def linearize(in_file, partials_file):
        doc = etree.parse(in_file)
        x1 = float(doc.xpath(x_x1)[0].text)
        y2 = float(doc.xpath(x_y2)[0].text)

        partials = Partials()
        partials.declare_partials(x_f1, [x_x1, x_y1, x_y2, x_z2], [2.*x1, 1., -exp(-y2), 1.])
        partials.write(partials_file)


text:
function testOutput1()
%Test
datapath = glazer.tests.getDataPath();
infile = [datapath '/' 'input_gold1.txt'];

pass = glazer.tests.outputEqual(infile);

if ~(pass)
  error('testOutput1:notEqual', 'Gold and gotten mismatch.')
end


text:
package mantra.errors;

import mantra.Tool;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.Token;
import org.stringtemplate.v4.ST;
import org.stringtemplate.v4.STErrorListener;
import org.stringtemplate.v4.STGroup;
import org.stringtemplate.v4.STGroupFile;
import org.stringtemplate.v4.misc.ErrorBuffer;
import org.stringtemplate.v4.misc.STMessage;

import java.net.URL;
import java.util.EnumSet;
import java.util.Locale;
import java.util.Set;

public class ErrorManager {
	public static final String FORMATS_DIR = "mantra/templates/messages/formats/";

	public Tool tool;
	public int errors;
	public int warnings;

	/** All errors that have been generated */
	public Set<ErrorType> errorTypes = EnumSet.noneOf(ErrorType.class);

    /** The group of templates that represent the current message format. */
	public STGroup format;

    /** Messages should be sensitive to the locale. */
	public Locale locale;
	public String formatName;

	public ErrorBuffer initSTListener = new ErrorBuffer();

    STErrorListener theDefaultSTListener =
        new STErrorListener() {
            @Override
            public void compileTimeError(STMessage msg) {
                ErrorManager.internalError(msg.toString());
            }

            @Override
            public void runTimeError(STMessage msg) {
                ErrorManager.internalError(msg.toString());
            }

            @Override
            public void IOError(STMessage msg) {
                ErrorManager.internalError(msg.toString());
            }

            @Override
            public void internalError(STMessage msg) {
                ErrorManager.internalError(msg.toString());
            }
        };

	public ErrorManager(Tool tool) {
		this.tool = tool;
	}

	public void resetErrorState() {
		errors = 0;
		warnings = 0;
	}

	public ST getMessageTemplate(MantraMessage msg) {
		ST messageST = msg.getMessageTemplate(false);
		ST locationST = getLocationFormat();
		ST reportST = getReportFormat(msg.getErrorType().severity);
		ST messageFormatST = getMessageFormat();

		boolean locationValid = false;
		if (msg.line != -1) {
			locationST.add("line", msg.line);
			locationValid = true;
		}
		if (msg.charPosition != -1) {
			locationST.add("column", msg.charPosition);
			locationValid = true;
		}
		if (msg.fileName != null) {
			locationST.add("file", msg.fileName);
			locationValid = true;
		}

		messageFormatST.add("id", msg.getErrorType().code);
		messageFormatST.add("text", messageST);

		if (locationValid) reportST.add("location", locationST);
		reportST.add("message", messageFormatST);
		//((DebugST)reportST).inspect();
//		reportST.impl.dump();
		return reportST;
	}

    /** Return a StringTemplate that refers to the current format used for
     * emitting messages.
     */
    public ST getLocationFormat() {
        return format.getInstanceOf("location");
    }

    public ST getReportFormat(ErrorSeverity severity) {
        ST st = format.getInstanceOf("report");
        st.add("type", severity.getText());
        return st;
    }

    public ST getMessageFormat() {
        return format.getInstanceOf("message");
    }
    public boolean formatWantsSingleLineMessage() {
        return format.getInstanceOf("wantsSingleLineMessage").render().equals("true");
    }

	public void info(String msg) { tool.info(msg); }

	public void syntaxError(ErrorType etype,
								   String fileName,
								   Token token,
								   RecognitionException antlrException,
								   Object... args)
	{
		MantraMessage msg = new SyntaxMessage(etype,fileName,token,antlrException,args);
		emit(etype, msg);
	}

	public static void fatalInternalError(String error, Throwable e) {
		internalError(error, e);
		throw new RuntimeException(error, e);
	}

	public static void internalError(String error, Throwable e) {
        StackTraceElement location = getLastNonErrorManagerCodeLocation(e);
		internalError("Exception "+e+"@"+location+": "+error);
    }

    public static void internalError(String error) {
        StackTraceElement location =
            getLastNonErrorManagerCodeLocation(new Exception());
        String msg = location+": "+error;
        System.err.println("internal error: "+msg);
    }

    /**
     * Raise a predefined message with some number of paramters for the StringTemplate but for which there
     * is no location information possible.
     * @param errorType The Message Descriptor
     * @param args The arguments to pass to the StringTemplate
     */
	public void toolError(ErrorType errorType, Object... args) {
		ToolMessage msg = new ToolMessage(errorType, args);
		emit(errorType, msg);
	}

	public void toolError(ErrorType errorType, Throwable e, Object... args) {
		ToolMessage msg = new ToolMessage(errorType, e, args);
		emit(errorType, msg);
	}

    public int getNumErrors() {
        return errors;
    }

    /** Return first non ErrorManager code location for generating messages */
    private static StackTraceElement getLastNonErrorManagerCodeLocation(Throwable e) {
        StackTraceElement[] stack = e.getStackTrace();
        int i = 0;
        for (; i < stack.length; i++) {
            StackTraceElement t = stack[i];
            if (!t.toString().contains("ErrorManager")) {
                break;
            }
        }
        StackTraceElement location = stack[i];
        return location;
    }

    // S U P P O R T  C O D E

	@SuppressWarnings("fallthrough")
	public void emit(ErrorType etype, MantraMessage msg) {
		switch ( etype.severity ) {
			case WARNING_ONE_OFF:
				if ( errorTypes.contains(etype) ) break;
				// fall thru
			case WARNING:
				warnings++;
				tool.warning(msg);
				break;
			case ERROR_ONE_OFF:
				if ( errorTypes.contains(etype) ) break;
				// fall thru
			case ERROR:
				errors++;
				tool.error(msg);
				break;
		}
		errorTypes.add(etype);
	}

    /** The format gets reset either from the Tool if the user supplied a command line option to that effect
     *  Otherwise we just use the default "antlr".
     */
    public void setFormat(String formatName) {
        this.formatName = formatName;
        String fileName = FORMATS_DIR +formatName+STGroup.GROUP_FILE_EXTENSION;
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        URL url = cl.getResource(fileName);
        if ( url==null ) {
            cl = ErrorManager.class.getClassLoader();
            url = cl.getResource(fileName);
        }
        if ( url==null && formatName.equals("antlr") ) {
            rawError("Mantra installation corrupted; cannot find Mantra messages format file "+fileName);
            panic();
        }
        else if ( url==null ) {
            rawError("no such message format file "+fileName+" retrying with default Mantra format");
            setFormat("antlr"); // recurse on this rule, trying the default message format
            return;
        }

        format = new STGroupFile(fileName, "UTF-8");
        format.load();

        if ( !initSTListener.errors.isEmpty() ) {
            rawError("Mantra installation corrupted; can't load messages format file:\n"+
                     initSTListener.toString());
            panic();
        }

        boolean formatOK = verifyFormat();
        if ( !formatOK && formatName.equals("antlr") ) {
            rawError("Mantra installation corrupted; Mantra messages format file "+formatName+".stg incomplete");
            panic();
        }
        else if ( !formatOK ) {
            setFormat("antlr"); // recurse on this rule, trying the default message format
        }
    }

    /** Verify the message format template group */
    protected boolean verifyFormat() {
        boolean ok = true;
        if (!format.isDefined("location")) {
            System.err.println("Format template 'location' not found in " + formatName);
            ok = false;
        }
        if (!format.isDefined("message")) {
            System.err.println("Format template 'message' not found in " + formatName);
            ok = false;
        }
        if (!format.isDefined("report")) {
            System.err.println("Format template 'report' not found in " + formatName);
            ok = false;
        }
        return ok;
    }

    /** If there are errors during ErrorManager init, we have no choice
     *  but to go to System.err.
     */
    static void rawError(String msg) {
        System.err.println(msg);
    }

    static void rawError(String msg, Throwable e) {
        rawError(msg);
        e.printStackTrace(System.err);
    }

	public static void panic(String msg) {
		rawError(msg);
		panic();
	}

    public static void panic() {
        // can't call tool.panic since there may be multiple tools; just
        // one error manager
        throw new Error("Mantra ErrorManager panic");
    }}


text:
// This code is auto-generated, do not modify

using System;
using System.Collections.Generic;

namespace Ds3.Models
{
    public class JobChunk
    {
        public JobChunkBlobStoreState BlobStoreState { get; set; }
        public int ChunkNumber { get; set; }
        public Guid Id { get; set; }
        public DateTime JobCreationDate { get; set; }
        public Guid JobId { get; set; }
        public Guid? NodeId { get; set; }
        public bool PendingTargetCommit { get; set; }
        public Guid? ReadFromAzureTargetId { get; set; }
        public Guid? ReadFromDs3TargetId { get; set; }
        public Guid? ReadFromPoolId { get; set; }
        public Guid? ReadFromS3TargetId { get; set; }
        public Guid? ReadFromTapeId { get; set; }
    }
}