text:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Rs317.Sharp
{
	public sealed class RsWinFormsClient : Client<Graphics>
	{
		public Graphics GraphicsObject { get; }

		public RsWinFormsClient(ClientConfiguration config, Graphics graphicsObject)
			: base(config, new DefaultBufferFactory(), new DefaultRunnableStarterStrategy(), new DefaultRsSocketFactory(new DefaultRunnableStarterStrategy()))
		{
			if (config == null) throw new ArgumentNullException(nameof(config));
			GraphicsObject = graphicsObject ?? throw new ArgumentNullException(nameof(graphicsObject));
		}

		public RsWinFormsClient(ClientConfiguration config, Graphics graphicsObject, IRsSocketFactory socketFactory)
			: base(config, new DefaultBufferFactory(), new DefaultRunnableStarterStrategy(), socketFactory)
		{
			if(config == null) throw new ArgumentNullException(nameof(config));
			GraphicsObject = graphicsObject ?? throw new ArgumentNullException(nameof(graphicsObject));
		}

		protected override IRSGraphicsProvider<Graphics> CreateGraphicsProvider()
		{
			return new SystemDrawingRsGraphicsProvider(GraphicsObject);
		}

		protected override BaseRsImageProducer<Graphics> CreateNewImageProducer(int xSize, int ySize, string producerName)
		{
			return new SystemDrawingRsImageProducer(xSize, ySize, producerName);
		}
	}
}


text:
using System;
using System.Threading.Tasks;
using Elasticsearch.Net;
using Tests.Framework;
using static Elasticsearch.Net.AuditEvent;

namespace Tests.ClientConcepts.ConnectionPooling.RequestOverrides
{
	public class DisableSniffPingPerRequest
	{
		/**[[disable-sniff-ping-per-request]]
		 * === Disable sniffing and pinging per request
		*
		* Even if you are using a sniffing connection pool thats set up to sniff on start/failure
		* and pinging enabled, you can opt out of this behaviour on a _per request_ basis.
		*
		* In our first test we set up a cluster that pings and sniffs on startup
		* but we disable the sniffing on our first request so we only see the ping and the response
		*/
		[U] public async Task DisableSniff()
		{
			/** Let's set up the cluster and configure clients to **always** sniff on startup */
			var audit = new Auditor(() => Framework.Cluster
				.Nodes(10)
				.ClientCalls(r => r.SucceedAlways())
				.SniffingConnectionPool()
				.Settings(s => s.SniffOnStartup()) // <1> sniff on startup
			);

            /** Now We disable sniffing on the request so even though it's our first call,
             * we do not want to sniff on startup.
             *
             * Instead, the sniff on startup is deferred to the second call into the cluster that
			 * does not disable sniffing on a per request basis.
             *
             * And after that no sniff on startup will happen again
             */
            audit = await audit.TraceCalls(
				new ClientCall(r => r.DisableSniffing()) // <1> disable sniffing
				{
					{ PingSuccess, 9200 }, // <2> first call is a successful ping
					{ HealthyResponse, 9200 }
				},
				new ClientCall()
				{
					{ SniffOnStartup }, // <3> sniff on startup call happens here, on the second call
					{ SniffSuccess, 9200 },
					{ PingSuccess, 9200 },
					{ HealthyResponse, 9200 }
				},
				new ClientCall()
				{
					{ PingSuccess, 9201 }, // <4> No sniff on startup again
					{ HealthyResponse, 9201 }
				}
            );
		}

		/** Now, let's disable pinging on the request */
		[U] public async Task DisablePing()
		{
			var audit = new Auditor(() => Framework.Cluster
				.Nodes(10)
				.ClientCalls(r => r.SucceedAlways())
				.SniffingConnectionPool()
				.Settings(s => s.SniffOnStartup())
			);

			audit = await audit.TraceCall(
				new ClientCall(r => r.DisablePing()) // <1> disable ping
				{
					{ SniffOnStartup },
					{ SniffSuccess, 9200 }, // <2> No ping after sniffing
					{ HealthyResponse, 9200 }
				}
            );
		}

		/** Finally, let's demonstrate disabling both sniff and ping on the request */
		[U] public async Task DisableSniffAndPing()
		{
			var audit = new Auditor(() => Framework.Cluster
				.Nodes(10)
				.ClientCalls(r => r.SucceedAlways())
				.SniffingConnectionPool()
				.Settings(s => s.SniffOnStartup())
			);

			audit = await audit.TraceCall(
				new ClientCall(r=>r.DisableSniffing().DisablePing()) // <1> diable ping and sniff
				{
					{ HealthyResponse, 9200 } // <2> no ping or sniff before the call
				}
            );
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
import { tokenize } from 'simple-html-tokenizer';

function generateTokens(containerOrHTML) {
  if (typeof containerOrHTML === 'string') {
    return {
      tokens: tokenize(containerOrHTML),
      html: containerOrHTML
    };
  } else {
    return {
      tokens: tokenize(containerOrHTML.innerHTML),
      html: containerOrHTML.innerHTML
    };
  }
}

function normalizeTokens(tokens) {
  tokens.forEach(token => {
    if (token.type === 'StartTag') {
      token.attributes = token.attributes.sort(function(a, b) {
        if (a[0] > b[0]) { return 1; }
        if (a[0] < b[0]) { return -1; }
        return 0;
      });
    }
  });
}

export function equalTokens(actualContainer, expectedHTML, message = null) {
  let actual = generateTokens(actualContainer);
  let expected = generateTokens(expectedHTML);

  normalizeTokens(actual.tokens);
  normalizeTokens(expected.tokens);

  let equiv = QUnit.equiv(actual.tokens, expected.tokens);

  if (equiv && expected.html !== actual.html) {
    deepEqual(actual.tokens, expected.tokens, message);
  } else {
    QUnit.push(QUnit.equiv(actual.tokens, expected.tokens), actual.html, expected.html, message);
  }
}

const MATCHER_BRAND = '3d4ef194-13be-4ccf-8dc7-862eea02c93e';

function isMatcher(obj) {
  return typeof obj === 'object' && MATCHER_BRAND in obj;
}

const HTMLElement = window.HTMLElement;

export function equalsElement(element, tagName, attributes, content) {
  QUnit.push(element.tagName === tagName.toUpperCase(), element.tagName.toLowerCase(), tagName, `expect tagName to be ${tagName}`);

  let expectedAttrs = {};
  let expectedCount = 0;

  for (let name in attributes) {
    expectedCount++;

    let expected = attributes[name];

    let matcher = isMatcher(expected) ? expected : equalsAttr(expected);

    expectedAttrs[name] = matcher;

    QUnit.push(
      expectedAttrs[name].match(element.getAttribute(name)),
      element.getAttribute(name),
      matcher.expected(),
      `Element's ${name} attribute ${matcher.message()}`
    );
  }

  let actualAttributes = {};

  for (let i = 0, l = element.attributes.length; i < l; i++) {
    actualAttributes[element.attributes[i].name] = element.attributes[i].value;
  }

  if (!(element instanceof HTMLElement)) {
    QUnit.push(element instanceof HTMLElement, null, null, 'Element must be an HTML Element, not an SVG Element');
  } else {
    QUnit.push(
      element.attributes.length === expectedCount || !attributes,
      element.attributes.length,
      expectedCount,
      `Expected ${expectedCount} attributes; got ${element.outerHTML}`
    );

    if (content !== null) {
      QUnit.push(element.innerHTML === content, element.innerHTML, content, `The element had '${content}' as its content`);
    }
  }
}

function equalsAttr(expected) {
  return {
    [MATCHER_BRAND]: true,

    match(actual) {
      return expected === actual;
    },

    expected() {
      return expected;
    },

    message() {
      return `should equal ${this.expected()}`;
    }
  };
}

export function regex(r) {
  return {
    [MATCHER_BRAND]: true,

    match(v) {
      return r.test(v);
    },

    expected() {
      return r.toString();
    },

    message() {
      return `should match ${this.expected()}`;
    }
  };
}

export function classes(expected) {
  return {
    [MATCHER_BRAND]: true,

    match(actual) {
      actual = actual.trim();
      return actual && (expected.split(/\s+/).sort().join(' ') === actual.trim().split(/\s+/).sort().join(' '));
    },

    expected() {
      return expected;
    },

    message() {
      return `should match ${this.expected()}`;
    }
  };
}

export function styles(expected) {
  return {
    [MATCHER_BRAND]: true,

    match(actual) {
      actual = actual.trim();
      return actual && (
        expected.split(';').map(s => s.trim()).filter(s => s).sort().join('; ') ===
        actual.split(';').map(s => s.trim()).filter(s => s).sort().join('; ')
      );
    },

    expected() {
      return expected;
    },

    message() {
      return `should match ${this.expected()}`;
    }
  };
}


text:
package com.glaf.base.modules.todo.service;

import java.util.*;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jbpm.JbpmConfiguration;
import org.jbpm.JbpmContext;
import org.jpage.jbpm.context.Context;
import org.jpage.jbpm.model.TaskItem;
import org.jpage.jbpm.service.ProcessContainer;
import org.jpage.util.DateTools;

import com.glaf.base.modules.others.service.WorkCalendarService;
import com.glaf.base.modules.sys.model.SysDepartment;
import com.glaf.base.modules.sys.model.SysUser;
import com.glaf.base.modules.sys.service.SysUserService;
import com.glaf.base.modules.todo.model.ToDo;
import com.glaf.base.modules.todo.model.ToDoInstance;

public class TodoJobBean {
	private final static Log logger = LogFactory.getLog(TodoJobBean.class);

	private TodoService todoService;

	private MembershipService membershipService;

	private WorkCalendarService workCalendarService;

	private SysUserService sysUserService;

	public TodoJobBean() {

	}

	public void create(ToDo todo) {
		todoService.create(todo);
	}

	public void createTasks(Collection processInstanceIds) {
		List tasks = this.getJbpmTasksByProcessInstanceIds(processInstanceIds);
		todoService.createTasks(processInstanceIds, tasks);
		logger.info("Á÷³Ì " + processInstanceIds + " µÄÈÎÎñÒѾ¸üÐÂ,ÏÖÔÚÓÐÈÎÎñ:"
				+ tasks.size());
	}

	public void createTasks(String processInstanceId) {
		List tasks = this.getJbpmTasksByProcessInstanceId(processInstanceId);
		todoService.createTasks(processInstanceId, tasks);
		logger.info("Á÷³Ì " + processInstanceId + " µÄÈÎÎñÒѾ¸üÐÂ,ÏÖÔÚÓÐÈÎÎñ:"
				+ tasks.size());
	}

	public void createTasksFromSQL() {
		List rows = this.getTasks();
		todoService.createTasksOfSQL(rows);
	}

	public void createTasksFromWorkflow() {
		List tasks = this.getAllJbpmTasks();
		todoService.createTasksOfWorkflow(tasks);
	}

	public void createTasksFromWorkflow(String actorId) {
		List tasks = this.getJbpmTasks(actorId);
		todoService.createTasksOfWorkflow(actorId, tasks);
	}

	public void createTodoInstances(long todoId) {
		ToDo todo = todoService.getToDo(todoId);
		Map rowsMap = new HashMap();
		JbpmContext jbpmContext = null;
		try {
			jbpmContext = ProcessContainer.getContainer().createJbpmContext();
			java.sql.Connection con = jbpmContext.getConnection();
			java.sql.PreparedStatement psmt = con.prepareStatement(todo
					.getSql());
			java.sql.ResultSet rs = psmt.executeQuery();
			java.sql.ResultSetMetaData rsmd = rs.getMetaData();
			while (rs.next()) {
				ToDoInstance model = new ToDoInstance();
				model.setRowId(rs.getString(1));
				model.setStartDate(rs.getDate(2));
				if (rsmd.getColumnCount() == 3) {
					switch (new Long(todo.getId()).intValue()) {
					case 8005:// ÉÐδÖúÏͬÉúЧÈÕ£¡
					case 7001:
					case 7002:
					case 7003:
					case 7004:
					case 17001:// ²É¹º¸¶¿î´ý½»²ÆÎñ
					case 17010:
					case 18001:
					case 19001:
					case 20001:
					case 20084001:// ×ʲú³õ²½²ÆÎñÈ·ÈÏ
						model.setDeptId(rs.getLong(3));
						break;
					default:
						model.setActorId(rs.getString(3));
						break;
					}
				}
				rowsMap.put(model.getRowId(), model);
			}
			rs.close();
			psmt.close();
			rs = null;
			psmt = null;
		} catch (java.sql.SQLException ex) {
			ex.printStackTrace();
		} finally {
			Context.close(jbpmContext);
		}

		List rows = new ArrayList();

		if (rowsMap.size() > 0) {
			Iterator iter = rowsMap.keySet().iterator();
			while (iter.hasNext()) {
				String rowId = (String) iter.next();
				ToDoInstance model = (ToDoInstance) rowsMap.get(rowId);
				Date startDate = model.getStartDate();
				if (startDate == null) {
					startDate = new java.util.Date();
				}

				model.setProvider("sql");
				model.setLinkType(todo.getLinkType());
				model.setAppId(todo.getAppId());
				model.setModuleId(todo.getModuleId());
				model.setTodoId(todo.getId());
				model.setRoleId(todo.getRoleId());
				model.setRoleCode(todo.getRoleCode());
				model.setTitle(todo.getTitle());
				model.setCreateDate(new Date(System.currentTimeMillis()));
				model.setStartDate(startDate);
				int limitDay = todo.getLimitDay();
				int ahour = todo.getXa();
				int bhour = todo.getXb();

				Date limitWorkDate = workCalendarService.getWorkDate(startDate,
						limitDay);
				long time = limitWorkDate.getTime();

				Date cautionDate = new Date(time - ahour * DateTools.HOUR);
				Date pastDueDate = new Date(time + bhour * DateTools.HOUR);
				model.setAlarmDate(cautionDate);
				model.setPastDueDate(pastDueDate);
				model.setRowId(rowId);
				model.setVersionNo(System.currentTimeMillis());
				rows.add(model);
			}
		}

		todoService.createTodoInstances(todoId, rows);

	}

	public void execute() {
		this.createTasksFromWorkflow();
	}

	public List getAllJbpmTasks() {
		List rows = new ArrayList();
		List taskItems = ProcessContainer.getContainer().getAllTaskItems();
		if (taskItems != null && taskItems.size() > 0) {
			logger.info("---------->taskItems size:" + taskItems.size());
			rows = this.getTodoInstances(taskItems);
		}
		return rows;
	}

	public List getAllToDoList() {
		return todoService.getAllToDoList();
	}

	public Collection getAllUsers() {
		SysUserService sysUserService = this.getSysUserService();
		Collection users = sysUserService.getSysUserList();
		return users;
	}

	public Collection getAppActorIds(String appId) {
		Collection actorIds = new HashSet();
		String sql = " select a.account, a.name, c.appId from sys_user a inner join sys_user_role b on a.id = b.userId inner join sys_access c on b.roleId = c.roleId where c.appId = ? ";
		JbpmContext jbpmContext = null;
		try {
			JbpmConfiguration cfg = JbpmConfiguration.getInstance();
			jbpmContext = cfg.createJbpmContext();
			java.sql.Connection con = jbpmContext.getConnection();
			java.sql.PreparedStatement psmt = con.prepareStatement(sql);
			psmt.setString(1, appId);
			java.sql.ResultSet rs = psmt.executeQuery();
			while (rs.next()) {
				actorIds.add(rs.getString(1));
			}
			rs.close();
			psmt.close();
			rs = null;
			psmt = null;
		} catch (java.sql.SQLException ex) {
			ex.printStackTrace();
		} finally {
			Context.close(jbpmContext);
		}
		return actorIds;
	}

	public Map getDepartmentMap() {
		return todoService.getDepartmentMap();
	}

	public Map getEnabledToDoMap() {
		return todoService.getEnabledToDoMap();
	}

	public List getJbpmTasks(String actorId) {
		List rows = new ArrayList();
		List taskItems = ProcessContainer.getContainer().getTaskItems(actorId);
		if (taskItems != null && taskItems.size() > 0) {
			rows = this.getTodoInstances(taskItems);
		}
		return rows;
	}

	public List getJbpmTasksByProcessInstanceId(String processInstanceId) {
		List rows = new ArrayList();
		List taskItems = ProcessContainer.getContainer()
				.getTaskItemsByProcessInstanceId(processInstanceId);
		if (taskItems != null && taskItems.size() > 0) {
			rows = this.getTodoInstances(taskItems);
		}
		return rows;
	}

	public List getJbpmTasksByProcessInstanceIds(Collection processInstanceIds) {
		List rows = new ArrayList();
		List taskItems = ProcessContainer.getContainer()
				.getTaskItemsByProcessInstanceIds(processInstanceIds);
		if (taskItems != null && taskItems.size() > 0) {
			rows = this.getTodoInstances(taskItems);
		}
		return rows;
	}

	public MembershipService getMembershipService() {
		return membershipService;
	}

	public SysDepartment getParentDepartment(long id) {
		return todoService.getParentDepartment(id);
	}

	public Map getRoleMap() {
		return todoService.getRoleMap();
	}

	public SysUserService getSysUserService() {
		return sysUserService;
	}

	public List getTasks() {
		List todos = todoService.getSQLToDos();
		List rows = new ArrayList();
		if (todos != null && todos.size() > 0) {
			Iterator iterator = todos.iterator();
			while (iterator.hasNext()) {
				ToDo todo = (ToDo) iterator.next();
				if (StringUtils.isNotEmpty(todo.getSql())) {
					logger.info(todo.getId() + ":" + todo.getSql());
					Map rowsMap = new HashMap();
					JbpmContext jbpmContext = null;
					try {
						JbpmConfiguration cfg = JbpmConfiguration.getInstance();
						jbpmContext = cfg.createJbpmContext();
						java.sql.Connection con = jbpmContext.getConnection();
						java.sql.PreparedStatement psmt = con
								.prepareStatement(todo.getSql());
						java.sql.ResultSet rs = psmt.executeQuery();
						java.sql.ResultSetMetaData rsmd = rs.getMetaData();
						while (rs.next()) {
							ToDoInstance model = new ToDoInstance();
							model.setRowId(rs.getString(1));
							model.setStartDate(rs.getDate(2));
							if (rsmd.getColumnCount() == 3) {
								switch (new Long(todo.getId()).intValue()) {
								case 8005:// ÉÐδÖúÏͬÉúЧÈÕ£¡
								case 7001:
								case 7002:
								case 7003:
								case 7004:
								case 17001:// ²É¹º¸¶¿î´ý½»²ÆÎñ
								case 17010:
								case 18001:
								case 19001:
								case 20001:
								case 20084001:// ×ʲú³õ²½²ÆÎñÈ·ÈÏ
									model.setDeptId(rs.getLong(3));
									break;
								default:
									model.setActorId(rs.getString(3));
									break;
								}
							}
							rowsMap.put(model.getRowId(), model);
						}
						rs.close();
						psmt.close();
						rs = null;
						psmt = null;

					} catch (java.sql.SQLException ex) {
						System.out.println(todo.getId() + ":" + todo.getSql());
						ex.printStackTrace();
					} finally {
						Context.close(jbpmContext);
					}

					if (rowsMap.size() > 0) {
						Iterator iter = rowsMap.keySet().iterator();
						while (iter.hasNext()) {
							String rowId = (String) iter.next();
							ToDoInstance model = (ToDoInstance) rowsMap
									.get(rowId);
							Date startDate = model.getStartDate();
							if (startDate == null) {
								startDate = new java.util.Date();
							}

							model.setProvider("sql");
							model.setLinkType(todo.getLinkType());
							model.setAppId(todo.getAppId());
							model.setModuleId(todo.getModuleId());
							model.setTodoId(todo.getId());
							model.setRoleId(todo.getRoleId());
							model.setRoleCode(todo.getRoleCode());
							model.setTitle(todo.getTitle());
							model.setCreateDate(new Date(System
									.currentTimeMillis()));
							model.setStartDate(startDate);
							int limitDay = todo.getLimitDay();
							int ahour = todo.getXa();
							int bhour = todo.getXb();

							Date limitWorkDate = workCalendarService
									.getWorkDate(startDate, limitDay);
							long time = limitWorkDate.getTime();

							Date cautionDate = new Date(time - ahour
									* DateTools.HOUR);
							Date pastDueDate = new Date(time + bhour
									* DateTools.HOUR);
							model.setAlarmDate(cautionDate);
							model.setPastDueDate(pastDueDate);
							model.setRowId(rowId);
							model.setVersionNo(System.currentTimeMillis());
							rows.add(model);
						}
					}
				}
			}

		}
		return rows;
	}

	public ToDo getToDo(long todoId) {
		return todoService.getToDo(todoId);
	}

	public List getToDoInstanceList(Map paramMap) {
		return todoService.getToDoInstanceList(paramMap);
	}

	public List getTodoInstances(List taskItems) {
		List rows = new ArrayList();
		if (taskItems != null && taskItems.size() > 0) {
			logger.info("---------->taskItems size:" + taskItems.size());
			Map userMap = this.getUserMap();
			Map todoMap = this.getToDoMap();

			Iterator iterator = taskItems.iterator();
			while (iterator.hasNext()) {
				TaskItem taskItem = (TaskItem) iterator.next();

				SysUser user = (SysUser) userMap.get(taskItem.getActorId());
				if (user == null) {
					continue;
				}

				ToDo todo = null;

				String key001 = taskItem.getProcessName() + "_"
						+ taskItem.getTaskName();
				String key = taskItem.getProcessName() + "_"
						+ taskItem.getTaskName() + "_"
						+ user.getDepartment().getId();

				todo = (ToDo) todoMap.get(key);

				if (todo == null) {
					todo = (ToDo) todoMap.get(key001);
				}

				if (todo == null) {
					logger.info(key001 + " no todo config .................");
				}

				if (todo != null) {
					boolean exist = false;
					JbpmContext jbpmContext = null;
					try {
						JbpmConfiguration cfg = JbpmConfiguration.getInstance();
						jbpmContext = cfg.createJbpmContext();
						java.sql.Connection con = jbpmContext.getConnection();
						String sql = " select processinstanceid from "
								+ todo.getTablename()
								+ " where processinstanceid = ? ";
						java.sql.PreparedStatement psmt = con
								.prepareStatement(sql);
						psmt.setString(1, taskItem.getProcessInstanceId());
						java.sql.ResultSet rs = psmt.executeQuery();
						if (rs.next()) {
							exist = true;
						}
						rs.close();
						psmt.close();
						rs = null;
						psmt = null;
					} catch (java.sql.SQLException ex) {
						ex.printStackTrace();
					} finally {
						Context.close(jbpmContext);
					}

					if (!exist) {
						continue;
					}

					ToDoInstance model = new ToDoInstance();
					model.setProvider("jbpm");
					model.setLinkType(todo.getLinkType());
					model.setAppId(todo.getAppId());
					model.setModuleId(todo.getModuleId());
					model.setTodoId(todo.getId());
					model.setRoleId(todo.getRoleId());
					model.setRoleCode(todo.getRoleCode());
					model.setTitle(todo.getTitle());
					model.setActorId(taskItem.getActorId());
					model.setActorName(user.getName());
					model.setDeptId(user.getDepartment().getId());
					model.setDeptName(user.getDepartment().getName());
					model.setCreateDate(new Date(System.currentTimeMillis()));
					model.setStartDate(taskItem.getTaskCreateDate());
					int limitDay = todo.getLimitDay();
					int ahour = todo.getXa();
					int bhour = todo.getXb();

					Date limitWorkDate = workCalendarService.getWorkDate2(
							model.getStartDate(), limitDay);
					long time = limitWorkDate.getTime();

					Date cautionDate = new Date(time - ahour * DateTools.HOUR);
					Date pastDueDate = new Date(time + bhour * DateTools.HOUR);
					model.setAlarmDate(cautionDate);
					model.setPastDueDate(pastDueDate);
					model.setProcessInstanceId(taskItem.getProcessInstanceId());
					model.setTaskInstanceId(taskItem.getTaskInstanceId());
					model.setRowId(taskItem.getBusinessValue());
					model.setVersionNo(System.currentTimeMillis());
					String content = todo.getContent();
					if (StringUtils.isNotEmpty(taskItem.getTaskDescription())) {
						content = content + taskItem.getTaskDescription();
						model.setContent(content);
					} else {
						if (StringUtils.isNotEmpty(taskItem.getBusinessValue())) {
							content = content + " µ¥¾Ý±àºÅ£¨"
									+ taskItem.getBusinessValue() + "£©";
							model.setContent(content);
						}
					}
					rows.add(model);
				}
			}
		}
		return rows;
	}

	public List getTodoInstances(String actorId) {
		SendMessageBean bean = new SendMessageBean();
		bean.setSysUserService(this.getSysUserService());
		bean.setMembershipService(membershipService);
		bean.setTodoService(todoService);
		return bean.getTodoInstances(actorId);
	}

	public List getToDoList() {
		return todoService.getToDoList();
	}

	public Map getToDoMap() {
		return todoService.getToDoMap();
	}

	public TodoService getTodoService() {
		return todoService;
	}

	public SysUser getUser(String actorId) {
		return todoService.getUser(actorId);
	}

	public Map getUserMap() {
		return todoService.getUserMap();
	}

	public Map getUserRoleMap(String actorId) {
		return todoService.getUserRoleMap(actorId);
	}

	public Map getUserTodoMap(String actorId) {
		return todoService.getUserTodoMap(actorId);
	}

	public WorkCalendarService getWorkCalendarService() {
		return workCalendarService;
	}

	public List getXYTodoInstances(String actorId) {
		SendMessageBean bean = new SendMessageBean();
		bean.setSysUserService(this.getSysUserService());
		bean.setMembershipService(membershipService);
		bean.setTodoService(todoService);
		return bean.getXYTodoInstances(actorId);
	}

	public void sendMessage() {
		// logger.info("sendMessage");
		// System.out.println("sendMessage");
		if (todoService.isWorkDate(new Date())) {
			// logger.info("ok--------");
			// System.out.println("ok--------");
			this.sendMessageToAllUsers();
		}
	}

	public void sendMessageToAllUsers() {
		if (todoService.isWorkDate(new Date())) {
			List rows = this.getTasks();
			todoService.createTasksOfSQL(rows);
			List tasks = this.getAllJbpmTasks();
			todoService.createTasksOfWorkflow(tasks);
			SysUserService sysUserService = this.getSysUserService();
			Collection users = sysUserService.getSysUserList();
			if (users != null && users.size() > 0) {
				logger.info("########user size:" + users.size());
				Iterator iterator = users.iterator();
				while (iterator.hasNext()) {
					SysUser user = (SysUser) iterator.next();
					if (user.getBlocked() == 0) {
						try {
							this.sendMessageToUser(user.getAccount());
						} catch (Exception ex) {
							logger.error(ex);
						}
					}
				}
			}
		}
	}

	public void sendMessageToUser(String actorId) {
		SendMessageBean bean = new SendMessageBean();
		bean.setSysUserService(this.getSysUserService());
		bean.setMembershipService(membershipService);
		bean.setTodoService(todoService);
		bean.sendMessageToUser(actorId);
	}

	public void setMembershipService(MembershipService membershipService) {
		this.membershipService = membershipService;
	}

	public void setSysUserService(SysUserService sysUserService) {
		this.sysUserService = sysUserService;
	}

	public void setTodoService(TodoService todoService) {
		this.todoService = todoService;
	}

	public void setWorkCalendarService(WorkCalendarService workCalendarService) {
		this.workCalendarService = workCalendarService;
		logger.info("setWorkCalendarService");
	}

	public void update(ToDo todo) {
		todoService.update(todo);
	}
}


text:
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/preloading/prefetch/prefetch_params.h"

#include "base/command_line.h"
#include "base/metrics/field_trial_params.h"
#include "base/rand_util.h"
#include "content/browser/preloading/prefetch/prefetch_features.h"
#include "content/public/browser/prefetch_service_delegate.h"

namespace content {

bool PrefetchContentRefactorIsEnabled() {
  return base::FeatureList::IsEnabled(features::kPrefetchUseContentRefactor);
}

GURL PrefetchProxyHost(const GURL& default_proxy_url) {
  // Command line overrides take priority.
  std::string cmd_line_value =
      base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
          "isolated-prerender-tunnel-proxy");
  if (!cmd_line_value.empty()) {
    GURL cmd_line_url(cmd_line_value);
    if (cmd_line_url.is_valid()) {
      return cmd_line_url;
    }
    LOG(ERROR) << "--isolated-prerender-tunnel-proxy value is invalid";
  }

  GURL url(base::GetFieldTrialParamValueByFeature(
      features::kPrefetchUseContentRefactor, "proxy_host"));
  if (url.is_valid() && url.SchemeIs(url::kHttpsScheme)) {
    return url;
  }

  return default_proxy_url;
}

std::string PrefetchProxyHeaderKey() {
  std::string header = base::GetFieldTrialParamValueByFeature(
      features::kPrefetchUseContentRefactor, "proxy_header_key");
  if (!header.empty()) {
    return header;
  }
  return "chrome-tunnel";
}

std::string PrefetchProxyServerExperimentGroup() {
  return base::GetFieldTrialParamValueByFeature(
      features::kPrefetchUseContentRefactor, "server_experiment_group");
}

bool PrefetchAllowAllDomains() {
  return base::GetFieldTrialParamByFeatureAsBool(
             features::kPrefetchUseContentRefactor, "allow_all_domains",
             false) ||
         base::CommandLine::ForCurrentProcess()->HasSwitch(
             "isolated-prerender-allow-all-domains");
}

bool PrefetchAllowAllDomainsForExtendedPreloading() {
  return base::GetFieldTrialParamByFeatureAsBool(
      features::kPrefetchUseContentRefactor,
      "allow_all_domains_for_extended_preloading", true);
}

size_t PrefetchServiceMaximumNumberOfConcurrentPrefetches() {
  return base::GetFieldTrialParamByFeatureAsInt(
      features::kPrefetchUseContentRefactor, "max_concurrent_prefetches", 1);
}

absl::optional<int> PrefetchServiceMaximumNumberOfPrefetchesPerPage() {
  if (base::CommandLine::ForCurrentProcess()->HasSwitch(
          "isolated-prerender-unlimited-prefetches")) {
    return absl::nullopt;
  }

  int max = base::GetFieldTrialParamByFeatureAsInt(
      features::kPrefetchUseContentRefactor, "max_srp_prefetches", 5);
  if (max < 0) {
    return absl::nullopt;
  }
  return max;
}

bool PrefetchServiceSendDecoyRequestForIneligblePrefetch(
    bool disabled_based_on_user_settings) {
  if (base::CommandLine::ForCurrentProcess()->HasSwitch(
          "prefetch-proxy-never-send-decoy-requests-for-testing")) {
    return false;
  }
  if (base::CommandLine::ForCurrentProcess()->HasSwitch(
          "prefetch-proxy-always-send-decoy-requests-for-testing")) {
    return true;
  }

  if (base::GetFieldTrialParamByFeatureAsBool(
          features::kPrefetchUseContentRefactor,
          "disable_decoys_based_on_user_settings", true) &&
      disabled_based_on_user_settings) {
    return false;
  }

  double probability = base::GetFieldTrialParamByFeatureAsDouble(
      features::kPrefetchUseContentRefactor,
      "ineligible_decoy_request_probability", 1.0);

  // Clamp to [0.0, 1.0].
  probability = std::max(0.0, probability);
  probability = std::min(1.0, probability);

  // RandDouble returns [0.0, 1.0) so don't use <= here since that may return
  // true when the probability is supposed to be 0 (i.e.: always false).
  return base::RandDouble() < probability;
}

base::TimeDelta PrefetchTimeoutDuration() {
  return base::Milliseconds(base::GetFieldTrialParamByFeatureAsInt(
      features::kPrefetchUseContentRefactor, "prefetch_timeout_ms",
      10 * 1000 /* 10 seconds */));
}

size_t PrefetchMainframeBodyLengthLimit() {
  return 1024 * base::GetFieldTrialParamByFeatureAsInt(
                    features::kPrefetchUseContentRefactor,
                    "max_mainframe_body_length_kb", 5 * 1024);
}

bool PrefetchCloseIdleSockets() {
  return base::GetFieldTrialParamByFeatureAsBool(
      features::kPrefetchUseContentRefactor, "close_idle_sockets", true);
}

bool PrefetchStartsSpareRenderer() {
  return base::CommandLine::ForCurrentProcess()->HasSwitch(
             "isolated-prerender-start-spare-renderer") ||
         base::GetFieldTrialParamByFeatureAsBool(
             features::kPrefetchUseContentRefactor, "start_spare_renderer",
             true);
}

base::TimeDelta PrefetchContainerLifetimeInPrefetchService() {
  // A value of 0 or less, indicates that |PrefetchService| should keep the
  // prefetch forever.
  return base::Seconds(base::GetFieldTrialParamByFeatureAsInt(
      features::kPrefetchUseContentRefactor, "prefetch_container_lifetime_s",
      10 * 60 /* 10 minutes */));
}

bool PrefetchServiceHTMLOnly() {
  return base::GetFieldTrialParamByFeatureAsBool(
      features::kPrefetchUseContentRefactor, "html_only", false);
}

absl::optional<std::string> PrefetchBypassProxyForHost() {
  absl::optional<std::string> value;
  auto val_str = base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
      "bypass-prefetch-proxy-for-host");
  if (val_str.size())
    value = std::move(val_str);
  return value;
}

base::TimeDelta PrefetchCacheableDuration() {
  return base::Seconds(base::GetFieldTrialParamByFeatureAsInt(
      features::kPrefetchUseContentRefactor, "cacheable_duration", 300));
}

bool PrefetchProbingEnabled() {
  return base::GetFieldTrialParamByFeatureAsBool(
      features::kPrefetchUseContentRefactor, "must_probe_origin", true);
}

bool PrefetchCanaryCheckEnabled() {
  return base::GetFieldTrialParamByFeatureAsBool(
      features::kPrefetchUseContentRefactor, "do_canary", true);
  ;
}

bool PrefetchTLSCanaryCheckEnabled() {
  return base::GetFieldTrialParamByFeatureAsBool(
      features::kPrefetchUseContentRefactor, "do_tls_canary", false);
  ;
}

GURL PrefetchTLSCanaryCheckURL(const GURL& default_tls_canary_check_url) {
  GURL url(base::GetFieldTrialParamValueByFeature(
      features::kPrefetchUseContentRefactor, "tls_canary_url"));
  if (url.is_valid())
    return url;

  return default_tls_canary_check_url;
}

GURL PrefetchDNSCanaryCheckURL(const GURL& default_dns_canary_check_url) {
  GURL url(base::GetFieldTrialParamValueByFeature(
      features::kPrefetchUseContentRefactor, "dns_canary_url"));
  if (url.is_valid())
    return url;

  return default_dns_canary_check_url;
}

base::TimeDelta PrefetchCanaryCheckCacheLifetime() {
  return base::Hours(base::GetFieldTrialParamByFeatureAsInt(
      features::kPrefetchUseContentRefactor, "canary_cache_hours", 24));
}

base::TimeDelta PrefetchCanaryCheckTimeout() {
  return base::Milliseconds(base::GetFieldTrialParamByFeatureAsInt(
      features::kPrefetchUseContentRefactor, "canary_check_timeout_ms",
      5 * 1000 /* 5 seconds */));
}

int PrefetchCanaryCheckRetries() {
  return base::GetFieldTrialParamByFeatureAsInt(
      features::kPrefetchUseContentRefactor, "canary_check_retries", 1);
}

}  // namespace content


text:
/*global File*/
//////////////////////////////////////////////////////////////////////////////
/**
 * Create a new instance of class jsonReader
 *
 * @class
 * @extends geo.fileReader
 * @returns {geo.jsonReader}
 */
//////////////////////////////////////////////////////////////////////////////
geo.jsonReader = function (arg) {
  'use strict';
  if (!(this instanceof geo.jsonReader)) {
    return new geo.jsonReader(arg);
  }

  var m_this = this, m_style = arg.style || {};
  m_style = $.extend({
      'strokeWidth': 2,
      'strokeColor': {r: 0, g: 0, b: 0},
      'strokeOpacity': 1,
      'fillColor': {r: 1, g: 0, b: 0},
      'fillOpacity': 1
    }, m_style);

  geo.fileReader.call(this, arg);

  this.canRead = function (file) {
    if (file instanceof File) {
      return (file.type === 'application/json' || file.name.match(/\.json$/));
    } else if (typeof file === 'string') {
      try {
        JSON.parse(file);
      } catch (e) {
        return false;
      }
      return true;
    }
    try {
      if (Array.isArray(m_this._featureArray(file))) {
        return true;
      }
    } catch (e) {}
    return false;
  };

  this._readObject = function (file, done, progress) {
    var object;
    function onDone(fileString) {
      if (typeof fileString !== 'string') {
        done(false);
      }

      // We have two possibilities here:
      // 1) fileString is a JSON string or is
      // a URL.
      try {
        object = JSON.parse(fileString);
        done(object);
      } catch (e) {
        if (!object) {
          $.ajax({
            type: 'GET',
            url: fileString,
            dataType: 'text'
          }).done(function (data) {
            object = JSON.parse(data);
            done(object);
          }).fail(function () {
            done(false);
          });
        }
      }
    }

    if (file instanceof File) {
      m_this._getString(file, onDone, progress);
    } else if (typeof file === 'string') {
      onDone(file);
    } else {
      done(file);
    }
  };

  this._featureArray = function (spec) {
    if (spec.type === 'FeatureCollection') {
      return spec.features || [];
    }
    if (spec.type === 'GeometryCollection') {
      throw 'GeometryCollection not yet implemented.';
    }
    if (Array.isArray(spec.coordinates)) {
      return spec;
    }
    throw 'Unsupported collection type: ' + spec.type;
  };

  this._featureType = function (spec) {
    var geometry = spec.geometry || {};
    if (geometry.type === 'Point' || geometry.type === 'MultiPoint') {
      return 'point';
    }
    if (geometry.type === 'LineString') {
      return 'line';
    }
    if (geometry.type === 'Polygon') {
      return 'polygon';
    }
    if (geometry.type === 'MultiPolygon') {
      return 'multipolygon';
    }
    return null;
  };

  this._getCoordinates = function (spec) {
    var geometry = spec.geometry || {},
        coordinates = geometry.coordinates || [], elv;

    if ((coordinates.length === 2 || coordinates.length === 3) &&
        (isFinite(coordinates[0]) && isFinite(coordinates[1]))) {

      // Do we have a elevation component
      if (isFinite(coordinates[2])) {
        elv = coordinates[2];
      }

      // special handling for single point coordinates
      return [{x: coordinates[0], y: coordinates[1], z: elv}];
    }

    // need better handling here, but we can plot simple polygons
    // by taking just the outer linearring
    if (Array.isArray(coordinates[0][0])) {
      coordinates = coordinates[0];
    }

    // return an array of points for LineString, MultiPoint, etc...
    return coordinates.map(function (c) {
      return {
        x: c[0],
        y: c[1],
        z: c[2]
      };
    });
  };

  this._getStyle = function (spec) {
    return spec.properties;
  };

  this.read = function (file, done, progress) {

    function _done(object) {
      var features, allFeatures = [];

      features = m_this._featureArray(object);

      features.forEach(function (feature) {
        var type = m_this._featureType(feature),
            coordinates = m_this._getCoordinates(feature),
            style = m_this._getStyle(feature);
        if (type) {
          if (type === 'line') {
            style.fill = style.fill || false;
            allFeatures.push(m_this._addFeature(
              type,
              [coordinates],
              style,
              feature.properties
            ));
          } else if (type === 'point') {
            style.stroke = style.stroke || false;
            allFeatures.push(m_this._addFeature(
              type,
              coordinates,
              style,
              feature.properties
            ));
          } else if (type === 'polygon') {
            style.fill = style.fill === undefined ? true : style.fill;
            style.fillOpacity = (
              style.fillOpacity === undefined ? 0.25 : style.fillOpacity
            );
            // polygons not yet supported
            allFeatures.push(m_this._addFeature(
              'line',
              [coordinates],
              style,
              feature.properties
            ));
          } else if (type === 'multipolygon') {
            style.fill = style.fill === undefined ? true : style.fill;
            style.fillOpacity = (
              style.fillOpacity === undefined ? 0.25 : style.fillOpacity
            );

            coordinates = feature.geometry.coordinates.map(function (c) {
              return c[0].map(function (el) {
                return {
                  x: el[0],
                  y: el[1],
                  z: el[2]
                };
              });
            });

            allFeatures.push(m_this._addFeature(
                'line',
                coordinates,
                style,
                feature.properties
            ));
          }
        } else {
          console.log('unsupported feature type: ' + feature.geometry.type);
        }
      });

      if (done) {
        done(allFeatures);
      }
    }

    m_this._readObject(file, _done, progress);
  };

  ////////////////////////////////////////////////////////////////////////////
  /**
   * Build the data array for a feature given the coordinates and properties
   * from the geojson.
   *
   * @private
   * @param {Object[]} coordinates Coordinate data array
   * @param {Object} properties Geojson properties object
   * @param {Object} style Global style defaults
   * @returns {Object[]}
   */
  //////////////////////////////////////////////////////////////////////////////
  this._buildData = function (coordinates, properties, style) {
    return coordinates.map(function (coord) {
      return {
        coordinates: coord,
        properties: properties,
        style: style
      };
    });
  };

  this._addFeature = function (type, coordinates, style, properties) {
    var _style = $.extend({}, m_style, style);
    var feature = m_this.layer().createFeature(type)
      .data(m_this._buildData(coordinates, properties, style))
      .style(_style);

    if (type === 'line') {
      feature.line(function (d) { return d.coordinates; });
    } else {
      feature.position(function (d) { return d.coordinates; });
    }
    return feature;
  };

};

inherit(geo.jsonReader, geo.fileReader);

geo.registerFileReader('jsonReader', geo.jsonReader);


text:
package tasks.generator;

import java.util.ArrayList;
import java.util.Random;

import org.javatuples.Pair;

import com.systemincloud.modeler.tasks.javatask.api.InputPort;
import com.systemincloud.modeler.tasks.javatask.api.JavaTask;
import com.systemincloud.modeler.tasks.javatask.api.OutputPort;
import com.systemincloud.modeler.tasks.javatask.api.annotations.InputPortInfo;
import com.systemincloud.modeler.tasks.javatask.api.annotations.JavaTaskInfo;
import com.systemincloud.modeler.tasks.javatask.api.annotations.OutputPortInfo;
import com.systemincloud.modeler.tasks.javatask.api.annotations.SicParameter;
import com.systemincloud.modeler.tasks.javatask.api.annotations.SicParameters;
import com.systemincloud.modeler.tasks.javatask.api.data.Int32;

@JavaTaskInfo
@SicParameters({
	@SicParameter(name=LocalMotions.NUMBER),
	@SicParameter(name=LocalMotions.SIZE),
	@SicParameter(name=LocalMotions.SPEED)
})
public class LocalMotions extends JavaTask {

	protected static final String NUMBER = "number";
	protected static final String SIZE   = "size";
	protected static final String SPEED  = "speed";

	private Random rand = new Random();

	@InputPortInfo(name = "In", dataType = Int32.class)
	public InputPort in;
	@OutputPortInfo(name = "Out", dataType = Int32.class)
	public OutputPort out;

	private int nb;
	private int sz;
	private int sp;

	private boolean initialized = false;
	private ArrayList<Pair<Integer, Integer>> initPositions;
	private ArrayList<Pair<Integer, Integer>> vectors;

	private int[] mask;

	@Override
	public void runnerStart() {
		nb = Integer.parseInt(getParameter(NUMBER));
		sz = Integer.parseInt(getParameter(SIZE));
		sp = Integer.parseInt(getParameter(SPEED));
		initPositions = new ArrayList<>(nb);
		vectors       = new ArrayList<>(nb);
	}

	@Override
	public void execute(int grp) {
		Int32 inData    = in.getData(Int32.class);
		int[] inValues  = inData.getValues();
		int   ne        = inData.getNumberOfElements();
		int   h         = inData.getDimensions().get(0);
		int   w         = inData.getDimensions().get(1);

		int[] outValues = new int[ne];

		if(!initialized) initMask(h, w);

		for(int i = 0; i < ne; i++) outValues[i] = inValues[i];

		for(int i = 1; i <= nb; i++)
			for(int j = 0; j < ne; j++)
				if(mask[j] == i)
					outValues[j + vectors.get(i - 1).getValue1()*w + vectors.get(i - 1).getValue0()] = inValues[j];

		for(int i = 0; i < nb; i++) {
			int move = rand.nextInt(9);
			Pair<Integer, Integer> p = vectors.get(i);
			int new_x = 0;
			int new_y = 0;
			switch(move) {
				case 0 : new_x = p.getValue0() - sp; new_y = p.getValue1() - sp; break;
				case 1 : new_x = p.getValue0() - sp; new_y = p.getValue1()     ; break;
				case 2 : new_x = p.getValue0() - sp; new_y = p.getValue1() + sp; break;
				case 3 : new_x = p.getValue0()     ; new_y = p.getValue1() - sp; break;
				case 4 : new_x = p.getValue0()     ; new_y = p.getValue1()     ; break;
				case 5 : new_x = p.getValue0()     ; new_y = p.getValue1() + sp; break;
				case 6 : new_x = p.getValue0() + sp; new_y = p.getValue1() - sp; break;
				case 7 : new_x = p.getValue0() + sp; new_y = p.getValue1()     ; break;
				case 8 : new_x = p.getValue0() + sp; new_y = p.getValue1() + sp; break;
			}
			if((initPositions.get(i).getValue0() + new_x) < 0) new_x = -initPositions.get(i).getValue0();
			if((initPositions.get(i).getValue1() + new_y) < 0) new_y = -initPositions.get(i).getValue1();
			if((initPositions.get(i).getValue0() + sz + new_x) >= w) new_x = w - initPositions.get(i).getValue0() - sz;
			if((initPositions.get(i).getValue1() + sz + new_y) >= h) new_y = h - initPositions.get(i).getValue1() - sz;

			vectors.add(i, new Pair<>(new_x, new_y));
		}
		out.putData(new Int32(inData.getDimensions(), outValues));
	}

	private void initMask(int h, int w) {
		mask = new int[h*w];
		for(int i = 1; i <= nb; i++) {
			vectors.add(new Pair<Integer, Integer>(0, 0));
		    int x = rand.nextInt(w - sz);
		    int y = rand.nextInt(h - sz);
		    initPositions.add(new Pair<Integer, Integer>(x, y));
			for(int j = 0; j < h; j++)
				for(int k = 0; k < w; k++)
					if((j >= y) && (j < y + sz) && (k >= x) && (k < x + sz)) mask[j*w + k] = i;
		}
		initialized = true;
	}
}


text:
import { ColorPicker } from "../../sequences/color_picker";
import { colors } from "../../util";
import * as React from "react";
import { mount } from "enzyme";
import { } from "jasmine";

describe("Color picker", () => {
  it("initializes.", function () {
    // let colpik = new ColorPicker({ current: "red" });
    // expect(colpik.state.isHovered).toBeFalsy(
    //   "ColorPicker.state.isHovered should initialize to 'false'.");
    // expect(colpik.notHovered()).toEqual(<div />,
    //   "#notHovered() should return an empty div");
    // let hovered = colpik.isHovered();
    // expect(hovered.props.className).toEqual("colorpicker-text");
    // let actualColors = hovered.props.children.map((c: JSX.Element) => (
    //   c.props.children.props.color
    // )).sort();
    // expect(actualColors).toEqual(colors.sort());
  });

  it("picks colors.", () => {
    // Render
    let callback = jasmine.createSpy("<ColorPicker/> onChange property");
    let el = mount(<ColorPicker current="red" onChange={callback} />);

    function saucerCount() { return el.find(".saucer").length; }
    // Unhovered
    expect(saucerCount()).toEqual(1,
      "Color picker shows 1 color saucer when unhovered.");

    // hover
    el.simulate("mouseEnter");
    expect(saucerCount()).toEqual((colors.length + 1),
      `Color picker shows all possible colors (plus current choice)
      when unhovered.`);

    // Select a color
    let saucer = el.find(".saucer").last();
    let color = (saucer.props().style as any)["background"];
    saucer.simulate("click");
    expect(callback).toHaveBeenCalledWith(color);

    // unhover
    el.simulate("mouseLeave");
    expect(saucerCount()).toEqual(1,
      "Color picker shows 1 color saucer when unhovered.");
  });
});


text:
package org.apache.flink.runtime.rpc;

import akka.actor.ActorSystem;

import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.akka.AkkaUtils;
import org.apache.flink.runtime.concurrent.FutureUtils;
import org.apache.flink.runtime.rpc.akka.AkkaRpcService;
import org.apache.flink.runtime.rpc.exceptions.RpcConnectionException;
import org.apache.flink.runtime.taskexecutor.TaskExecutorGateway;
import org.apache.flink.util.TestLogger;

import akka.actor.Terminated;
import org.junit.Test;

import scala.Option;
import scala.Tuple2;

import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import static org.junit.Assert.*;

/**
 * This test validates that the RPC service gives a good message when it cannot
 * connect to an RpcEndpoint.
 */
public class RpcConnectionTest extends TestLogger {

	@Test
	public void testConnectFailure() throws Exception {
		ActorSystem actorSystem = null;
		RpcService rpcService = null;
		try {
			actorSystem = AkkaUtils.createActorSystem(
					new Configuration(), Option.<Tuple2<String, Object>>apply(new Tuple2<>("localhost", 0)));

			// we start the RPC service with a very long timeout to ensure that the test
			// can only pass if the connection problem is not recognized merely via a timeout
			rpcService = new AkkaRpcService(actorSystem, Time.of(10000000, TimeUnit.SECONDS));

			CompletableFuture<TaskExecutorGateway> future = rpcService.connect("foo.bar.com.test.invalid", TaskExecutorGateway.class);

			future.get(10000000, TimeUnit.SECONDS);
			fail("should never complete normally");
		}
		catch (TimeoutException e) {
			fail("should not fail with a generic timeout exception");
		}
		catch (ExecutionException e) {
			// that is what we want
			assertTrue(e.getCause() instanceof RpcConnectionException);
			assertTrue("wrong error message", e.getCause().getMessage().contains("foo.bar.com.test.invalid"));
		}
		catch (Throwable t) {
			fail("wrong exception: " + t);
		}
		finally {
			final CompletableFuture<Void> rpcTerminationFuture;

			if (rpcService != null) {
				rpcTerminationFuture = rpcService.stopService();
			} else {
				rpcTerminationFuture = CompletableFuture.completedFuture(null);
			}

			final CompletableFuture<Terminated> actorSystemTerminationFuture;

			if (actorSystem != null) {
				actorSystemTerminationFuture = FutureUtils.toJava(actorSystem.terminate());
			} else {
				actorSystemTerminationFuture = CompletableFuture.completedFuture(null);
			}

			FutureUtils
				.waitForAll(Arrays.asList(rpcTerminationFuture, actorSystemTerminationFuture))
				.get();
		}
	}
}


text:
/**
* @module kafe
* @main kafe
*/
(function(global, $, undefined) {

	var
		// check if module imported
		_exists = function(name) {
			try {
				return eval("("+name+" != undefined)");
			} catch(e) {
				return false;
			}
		},

		// delete var (try/catch for ie8)
		_delete = function(name) {
			try {
				eval("delete "+name+";");
			} catch(e) {
				eval(name+" = undefined;");
			}
		},

		// ie version
		_ie = (function(){
			var
				v = 3,
				div = document.createElement('div'),
				all = div.getElementsByTagName('i')
			;
			while ((
				div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
				all[0]
			));

			return v > 4 ? v : undefined;
		})(),

		// jquery methods
		_jQueryMethods = {},

		/**
		* ### Version 3.2.10
		* kafe core
		*
		* @module kafe
		* @class kafe
		*/
		core = {

			/**
			* kafe version
			*
			* @property VESYON
			* @type String
			**/
			VESYON: '3.2.10',

			/**
			* kafe author
			*
			* @property PARAN
			* @type String
			**/
			PARAN: 'absolunet.com',

			/**
			* Versions of dependencies / kafe modules
			*
			* @property chaje
			* @type Object
			**/
			chaje: {
				'dependencies.jQuery':    $().jquery,
				'dependencies.lodash':    _.VERSION,
				'dependencies.Modernizr': Modernizr._version
			},

			// isolate core dependencies
			dependencies: {

				/**
				* local jQuery copy
				* ref: [http://jquery.com/](http://jquery.com/)
				*
				* @property dependencies.jQuery
				* @type Object
				**/
				jQuery: $

			},

			cms:    {},
			ext:    {},
			plugin: {}
		}
	;

	// miscellaneous core functions
	core.fn = {

		/**
		* Create a instantiable object
		* By John Resig (MIT Licensed)
		* ref: [http://ejohn.org/blog/simple-class-instantiation/](http://ejohn.org/blog/simple-class-instantiation/)
		*
		* @method fn.createInstantiableObject
		* @return {Object} The instantiable object
		*/
		createInstantiableObject: function() {
			return function(args){
				if (this instanceof arguments.callee) {
					if (typeof this.__constructor == 'function') {
						this.__ = {};
						this.__constructor.apply(this, (args.callee) ? args : arguments);
					}
				} else {
					return new arguments.callee(arguments);
				}
			};
		},

		/**
		* Return the language if available or else 'en'
		*
		* @method fn.lang
		* @param {Object} dict The dictionary to check against
		* @param {String} lang The language to check
		* @return {String} The available language
		*/
		lang: function(dict, lang) {
			lang = (!!lang) ? lang : core.env.lang;
			return (!!dict[lang]) ? lang : 'en';
		},

		/**
		* Delete the variable (patch for ie8)
		*
		* @method fn.deleteVar
		* @param {String} name Name of the variable to delete
		*/
		deleteVar: function(name) {
			_delete(name);
		},

		/**
		* Add method as jQuery plugin
		*
		* @method fn.plugIntojQuery
		* @param {String} name The jQuery plugin name
		* @param {Object[Function]} methods Action:Method hash
		*/
		plugIntojQuery: function(name, methods) {
			var id = 'kafe'+name;
			name = name || 'CORE';

			if ($.fn[id] === undefined) {
				_jQueryMethods[name] = {};

				$.fn[id] = function() {
					var args = $.makeArray(arguments);
					var method = args.shift();
					return this.each(function() {
						_jQueryMethods[name][method]( this, args );
					});
				};
			}

			$.extend(_jQueryMethods[name], methods);
		}
	};

	// environment constants
	core.env = {

		/**
		* Current lang
		*
		* @property env.lang
		* @type String
		**/
		lang: document.documentElement.lang.toLowerCase().substr(0,2),

		/**
		* Internet Explorer version
		*
		* @property env.ie
		* @type Number
		**/
		ie: _ie
	};

	/**
	* Add module to core
	*
	* @method bonify
	* @param {Object} options The options
	*	@param {String} options.name The module name
	*	@param {String} options.version The module version
	*	@param {Object} options.obj The module itself
	*/
	core.bonify = function(options) {

		// if not already extended
		if (!_exists('core.'+options.name)) {

			core.chaje[options.name] = options.version;
			eval('this.'+options.name+' = arguments[0].obj;');

		// throw error
		} else {
			throw core.error('kafe.'+options.name+' already exists');
		}
	};

	/**
	* Throw kafe errors
	*
	* @method error
	* @param {Error} error The error with description
	* @return {Error} error The error
	* @example
	*	kafe.error(new Error('barf'));
	*/
	core.error = function(e) {
		var msg = ((!!e.description) ? e.description : e.message);
		e.description = e.message = '<kafe:erè> : '+ ((!!msg) ? msg : 'anonim');
		return (_ie && _ie == 8) ? new Error(e) : e;
	};

	global.kafe = core;

})(typeof window !== 'undefined' ? window : this, jQuery);


text:
require 'spec_helper'

describe Function::Predicate, '.call' do
  subject { object.call(left, right) }

  let(:left)   { 1               }
  let(:right)  { 1               }
  let(:object) { described_class }

  specify { expect { subject }.to raise_error(NotImplementedError, "#{object}.call is not implemented") }
end


text:
export * from "./device-definition.model";
export * from "./device-function.model";


text:
ES5Harness.registerTest({
    id: "15.2.3.3-4-244",

    path: "TestCases/chapter15/15.2/15.2.3/15.2.3.3/15.2.3.3-4-244.js",

    description: "Object.getOwnPropertyDescriptor - ensure that 'set' property of returned object is data property with correct 'writable' attribute",

    test: function testcase() {
        var obj = {};
        var fun = function () {
            return "ownSetProperty";
        };
        Object.defineProperty(obj, "property", {
            set: fun,
            configurable: true
        });

        var desc = Object.getOwnPropertyDescriptor(obj, "property");

        try {
            desc.set = "overwriteSetProperty";
            return desc.set === "overwriteSetProperty";
        } catch (e) {
            return false;
        }
    },

    precondition: function prereq() {
        return fnExists(Object.getOwnPropertyDescriptor) && fnExists(Object.defineProperty);
    }
});


text:
namespace kmsp11 {
namespace {

using ::testing::HasSubstr;
using ::testing::IsEmpty;
using ::testing::Not;
using ::testing::SizeIs;
using ::testing::internal::CaptureStderr;
using ::testing::internal::GetCapturedStderr;

TEST(LoggingTest, StandardErrorIsEmptyWhenNoLogMessageAreEmitted) {
  CaptureStderr();

  ASSERT_OK(InitializeLogging("", ""));
  ShutdownLogging();

  EXPECT_THAT(GetCapturedStderr(), IsEmpty());
}

TEST(LoggingTest, NoDirectoryLogsInfoToStandardError) {
  CaptureStderr();
  ASSERT_OK(InitializeLogging("", ""));
  absl::Cleanup c = ShutdownLogging;

  std::string message = "Here is a sample message";
  LOG(INFO) << message;

  EXPECT_THAT(GetCapturedStderr(), HasSubstr(message));
}

TEST(LoggingTest, NoDirectoryLogsWarningToStandardError) {
  CaptureStderr();
  ASSERT_OK(InitializeLogging("", ""));
  absl::Cleanup c = ShutdownLogging;

  std::string message = "Here is a sample message";
  LOG(WARNING) << message;

  EXPECT_THAT(GetCapturedStderr(), HasSubstr(message));
}

TEST(LoggingTest, NoDirectoryLogsErrorToStandardError) {
  CaptureStderr();
  ASSERT_OK(InitializeLogging("", ""));
  absl::Cleanup c = ShutdownLogging;

  std::string message = "Here is a sample message";
  LOG(ERROR) << message;

  EXPECT_THAT(GetCapturedStderr(), HasSubstr(message));
}

TEST(LoggingTest, NoDirectoryLogsFatalToStandardError) {
  ASSERT_OK(InitializeLogging("", ""));
  absl::Cleanup c = ShutdownLogging;

  std::string message = "Here is a sample message";
  EXPECT_DEATH({ LOG(FATAL) << message; }, HasSubstr(message));
}

TEST(LoggingTest, FilenameSuffixIgnoredWhenNoDirectoryIsSpecified) {
  CaptureStderr();
  ASSERT_OK(InitializeLogging("", "foobar"));
  absl::Cleanup c = ShutdownLogging;

  std::string message = "Here is a sample message";
  LOG(ERROR) << message;
  EXPECT_THAT(GetCapturedStderr(), HasSubstr(message));
}

class LogDirectoryTest : public testing::Test {
 protected:
  void SetUp() override {
    log_directory_ =
        std::filesystem::temp_directory_path().append(RandomId()).string();
    ASSERT_TRUE(std::filesystem::create_directory(log_directory_));
  }

  void TearDown() override {
    std::error_code code;
    std::filesystem::remove_all(log_directory_, code);
    ASSERT_EQ(code.value(), 0);
  }

  std::vector<std::filesystem::directory_entry> LogDirectoryEntries() {
    std::filesystem::recursive_directory_iterator iter(log_directory_);
    return std::vector<std::filesystem::directory_entry>(
        std::filesystem::begin(iter), std::filesystem::end(iter));
  }

  std::string log_directory_;
};

TEST_F(LogDirectoryTest, DirectorySpecifiedDoesNotLogInfoToStandardError) {
  CaptureStderr();
  ASSERT_OK(InitializeLogging(log_directory_, ""));
  absl::Cleanup c = ShutdownLogging;

  LOG(INFO) << "Here is a sample message";

  EXPECT_THAT(GetCapturedStderr(), IsEmpty());
}

TEST_F(LogDirectoryTest, DirectorySpecifiedDoesNotLogWarningToStandardError) {
  CaptureStderr();
  ASSERT_OK(InitializeLogging(log_directory_, ""));
  absl::Cleanup c = ShutdownLogging;

  LOG(WARNING) << "Here is a sample message";

  EXPECT_THAT(GetCapturedStderr(), IsEmpty());
}

TEST_F(LogDirectoryTest, DirectorySpecifiedDoesNotLogErrorToStandardError) {
  CaptureStderr();
  ASSERT_OK(InitializeLogging(log_directory_, ""));
  absl::Cleanup c = ShutdownLogging;

  LOG(ERROR) << "Here is a sample message";

  EXPECT_THAT(GetCapturedStderr(), IsEmpty());
}

TEST_F(LogDirectoryTest, DirectorySpecifiedLogsFatalToStandardError) {
  ASSERT_OK(InitializeLogging(log_directory_, ""));
  absl::Cleanup c = ShutdownLogging;

  std::string message = "Here is a sample message";
  EXPECT_DEATH({ LOG(FATAL) << message; }, HasSubstr(message));
}

TEST_F(LogDirectoryTest, LogFilenameMatchesExpectedPattern) {
  ASSERT_OK(InitializeLogging(log_directory_, ""));
  absl::Cleanup c = ShutdownLogging;

  LOG(WARNING) << "Here is a sample message";

  std::vector<std::filesystem::directory_entry> files = LogDirectoryEntries();
  ASSERT_THAT(files, SizeIs(1));
  EXPECT_THAT(files[0].path().filename().string(),
              MatchesStdRegex("libkmsp11\\.log-\\d{8}-\\d{6}\\.\\d+"));
}

TEST_F(LogDirectoryTest, LogFilenameMatchesExpectedPatternWithSuffix) {
  ASSERT_OK(InitializeLogging(log_directory_, "foobar"));
  absl::Cleanup c = ShutdownLogging;

  LOG(ERROR) << "Here is a sample message";

  std::vector<std::filesystem::directory_entry> files = LogDirectoryEntries();
  ASSERT_THAT(files, SizeIs(1));
  EXPECT_THAT(files[0].path().filename().string(),
              MatchesStdRegex("libkmsp11\\.log-foobar-\\d{8}-\\d{6}\\.\\d+"));
}

TEST_F(LogDirectoryTest, SingleFileContainsAllLogLevels) {
  std::string info_message = "Info message";
  std::string warning_message = "Warning message";
  std::string error_message = "Error message";

  {
    // Using a separate scope to ensure logfiles are flushed.
    ASSERT_OK(InitializeLogging(log_directory_, ""));
    absl::Cleanup c = ShutdownLogging;

    LOG(INFO) << info_message;
    LOG(WARNING) << warning_message;
    LOG(ERROR) << error_message;
  }

  std::vector<std::filesystem::directory_entry> files = LogDirectoryEntries();
  ASSERT_THAT(files, SizeIs(1));
  EXPECT_THAT(
      ReadFileToString(files[0].path().string()),
      IsOkAndHolds(AllOf(HasSubstr(error_message), HasSubstr(warning_message),
                         HasSubstr(info_message))));
}

TEST_F(LogDirectoryTest, GrpcErrorsAreLoggedToGlogDestination) {
  std::string error_message = "Error message";
  std::string info_message = "Info message";
  std::string debug_message = "Debug message";
  CaptureStderr();

  // In customer code, this would be set using the GRPC_VERBOSITY environment
  // variable. However, that environment variable is only read once per process,
  // so isn't reliable in the context of unit tests that share a process.
  gpr_set_log_verbosity(GPR_LOG_SEVERITY_DEBUG);
  absl::Cleanup c = [] { gpr_set_log_verbosity(GPR_LOG_SEVERITY_ERROR); };

  {
    // Using a separate scope to ensure logfiles are flushed.
    ASSERT_OK(InitializeLogging(log_directory_, ""));
    absl::Cleanup c = ShutdownLogging;

    grpc_init();
    gpr_log(GPR_ERROR, error_message.c_str());
    gpr_log(GPR_INFO, info_message.c_str());
    gpr_log(GPR_DEBUG, debug_message.c_str());
  }

  std::vector<std::filesystem::directory_entry> files = LogDirectoryEntries();
  ASSERT_THAT(files, SizeIs(1));
  EXPECT_THAT(
      ReadFileToString(files[0].path().string()),
      IsOkAndHolds(AllOf(HasSubstr(error_message), HasSubstr(info_message),
                         HasSubstr(debug_message))));
  EXPECT_THAT(GetCapturedStderr(), IsEmpty());
}

}  // namespace
}  // namespace kmsp11


text:
#define JPEG_INTERNALS
#include "jinclude.h"
#include "jpeglib.h"

/* Pointer to routine to upsample a single component */
typedef JMETHOD(void, upsample1_ptr,
        (j_decompress_ptr cinfo, jpeg_component_info * compptr,
         JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));

/* Private subobject */

typedef struct {
  struct jpeg_upsampler pub;    /* public fields */

  /* Color conversion buffer.  When using separate upsampling and color
   * conversion steps, this buffer holds one upsampled row group until it
   * has been color converted and output.
   * Note: we do not allocate any storage for component(s) which are full-size,
   * ie do not need rescaling.  The corresponding entry of color_buf[] is
   * simply set to point to the input data array, thereby avoiding copying.
   */
  JSAMPARRAY color_buf[MAX_COMPONENTS];

  /* Per-component upsampling method pointers */
  upsample1_ptr methods[MAX_COMPONENTS];

  int next_row_out;        /* counts rows emitted from color_buf */
  JDIMENSION rows_to_go;    /* counts rows remaining in image */

  /* Height of an input row group for each component. */
  int rowgroup_height[MAX_COMPONENTS];

  /* These arrays save pixel expansion factors so that int_expand need not
   * recompute them each time.  They are unused for other upsampling methods.
   */
  UINT8 h_expand[MAX_COMPONENTS];
  UINT8 v_expand[MAX_COMPONENTS];
} my_upsampler;

typedef my_upsampler * my_upsample_ptr;

/*
 * Initialize for an upsampling pass.
 */

METHODDEF(void)
start_pass_upsample (j_decompress_ptr cinfo)
{
  my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;

  /* Mark the conversion buffer empty */
  upsample->next_row_out = cinfo->max_v_samp_factor;
  /* Initialize total-height counter for detecting bottom of image */
  upsample->rows_to_go = cinfo->output_height;
}

/*
 * Control routine to do upsampling (and color conversion).
 *
 * In this version we upsample each component independently.
 * We upsample one row group into the conversion buffer, then apply
 * color conversion a row at a time.
 */

METHODDEF(void)
sep_upsample (j_decompress_ptr cinfo,
          JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
          JDIMENSION in_row_groups_avail,
          JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
          JDIMENSION out_rows_avail)
{
  my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  int ci;
  jpeg_component_info * compptr;
  JDIMENSION num_rows;

  /* Fill the conversion buffer, if it's empty */
  if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
    for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
     ci++, compptr++) {
      /* Invoke per-component upsample method.  Notice we pass a POINTER
       * to color_buf[ci], so that fullsize_upsample can change it.
       */
      (*upsample->methods[ci]) (cinfo, compptr,
    input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
    upsample->color_buf + ci);
    }
    upsample->next_row_out = 0;
  }

  /* Color-convert and emit rows */

  /* How many we have in the buffer: */
  num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  /* Not more than the distance to the end of the image.  Need this test
   * in case the image height is not a multiple of max_v_samp_factor:
   */
  if (num_rows > upsample->rows_to_go)
    num_rows = upsample->rows_to_go;
  /* And not more than what the client can accept: */
  out_rows_avail -= *out_row_ctr;
  if (num_rows > out_rows_avail)
    num_rows = out_rows_avail;

  (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
                     (JDIMENSION) upsample->next_row_out,
                     output_buf + *out_row_ctr,
                     (int) num_rows);

  /* Adjust counts */
  *out_row_ctr += num_rows;
  upsample->rows_to_go -= num_rows;
  upsample->next_row_out += num_rows;
  /* When the buffer is emptied, declare this input row group consumed */
  if (upsample->next_row_out >= cinfo->max_v_samp_factor)
    (*in_row_group_ctr)++;
}

/*
 * These are the routines invoked by sep_upsample to upsample pixel values
 * of a single component.  One row group is processed per call.
 */

/*
 * For full-size components, we just make color_buf[ci] point at the
 * input buffer, and thus avoid copying any data.  Note that this is
 * safe only because sep_upsample doesn't declare the input row group
 * "consumed" until we are done color converting and emitting it.
 */

METHODDEF(void)
fullsize_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
           JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
{
  *output_data_ptr = input_data;
}

/*
 * This is a no-op version used for "uninteresting" components.
 * These components will not be referenced by color conversion.
 */

METHODDEF(void)
noop_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
           JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
{
  *output_data_ptr = NULL;    /* safety check */
}

/*
 * This version handles any integral sampling ratios.
 * This is not used for typical JPEG files, so it need not be fast.
 * Nor, for that matter, is it particularly accurate: the algorithm is
 * simple replication of the input pixel onto the corresponding output
 * pixels.  The hi-falutin sampling literature refers to this as a
 * "box filter".  A box filter tends to introduce visible artifacts,
 * so if you are actually going to use 3:1 or 4:1 sampling ratios
 * you would be well advised to improve this code.
 */

METHODDEF(void)
int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
          JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
{
  my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  JSAMPARRAY output_data = *output_data_ptr;
  register JSAMPROW inptr, outptr;
  register JSAMPLE invalue;
  register int h;
  JSAMPROW outend;
  int h_expand, v_expand;
  int inrow, outrow;

  h_expand = upsample->h_expand[compptr->component_index];
  v_expand = upsample->v_expand[compptr->component_index];

  inrow = outrow = 0;
  while (outrow < cinfo->max_v_samp_factor) {
    /* Generate one output row with proper horizontal expansion */
    inptr = input_data[inrow];
    outptr = output_data[outrow];
    outend = outptr + cinfo->output_width;
    while (outptr < outend) {
      invalue = *inptr++;    /* don't need GETJSAMPLE() here */
      for (h = h_expand; h > 0; h--) {
    *outptr++ = invalue;
      }
    }
    /* Generate any additional output rows by duplicating the first one */
    if (v_expand > 1) {
      jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
            v_expand-1, cinfo->output_width);
    }
    inrow++;
    outrow += v_expand;
  }
}

/*
 * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
 * It's still a box filter.
 */

METHODDEF(void)
h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
           JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
{
  JSAMPARRAY output_data = *output_data_ptr;
  register JSAMPROW inptr, outptr;
  register JSAMPLE invalue;
  JSAMPROW outend;
  int outrow;

  for (outrow = 0; outrow < cinfo->max_v_samp_factor; outrow++) {
    inptr = input_data[outrow];
    outptr = output_data[outrow];
    outend = outptr + cinfo->output_width;
    while (outptr < outend) {
      invalue = *inptr++;    /* don't need GETJSAMPLE() here */
      *outptr++ = invalue;
      *outptr++ = invalue;
    }
  }
}

/*
 * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
 * It's still a box filter.
 */

METHODDEF(void)
h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
           JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
{
  JSAMPARRAY output_data = *output_data_ptr;
  register JSAMPROW inptr, outptr;
  register JSAMPLE invalue;
  JSAMPROW outend;
  int inrow, outrow;

  inrow = outrow = 0;
  while (outrow < cinfo->max_v_samp_factor) {
    inptr = input_data[inrow];
    outptr = output_data[outrow];
    outend = outptr + cinfo->output_width;
    while (outptr < outend) {
      invalue = *inptr++;    /* don't need GETJSAMPLE() here */
      *outptr++ = invalue;
      *outptr++ = invalue;
    }
    jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
              1, cinfo->output_width);
    inrow++;
    outrow += 2;
  }
}

/*
 * Module initialization routine for upsampling.
 */

GLOBAL(void)
jinit_upsampler (j_decompress_ptr cinfo)
{
  my_upsample_ptr upsample;
  int ci;
  jpeg_component_info * compptr;
  boolean need_buffer;
  int h_in_group, v_in_group, h_out_group, v_out_group;

  upsample = (my_upsample_ptr)
    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
                SIZEOF(my_upsampler));
  cinfo->upsample = (struct jpeg_upsampler *) upsample;
  upsample->pub.start_pass = start_pass_upsample;
  upsample->pub.upsample = sep_upsample;
  upsample->pub.need_context_rows = FALSE; /* until we find out differently */

  if (cinfo->CCIR601_sampling)    /* this isn't supported */
    ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);

  /* Verify we can handle the sampling factors, select per-component methods,
   * and create storage as needed.
   */
  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
       ci++, compptr++) {
    /* Compute size of an "input group" after IDCT scaling.  This many samples
     * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
     */
    h_in_group = (compptr->h_samp_factor * compptr->DCT_h_scaled_size) /
         cinfo->min_DCT_h_scaled_size;
    v_in_group = (compptr->v_samp_factor * compptr->DCT_v_scaled_size) /
         cinfo->min_DCT_v_scaled_size;
    h_out_group = cinfo->max_h_samp_factor;
    v_out_group = cinfo->max_v_samp_factor;
    upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
    need_buffer = TRUE;
    if (! compptr->component_needed) {
      /* Don't bother to upsample an uninteresting component. */
      upsample->methods[ci] = noop_upsample;
      need_buffer = FALSE;
    } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
      /* Fullsize components can be processed without any work. */
      upsample->methods[ci] = fullsize_upsample;
      need_buffer = FALSE;
    } else if (h_in_group * 2 == h_out_group &&
           v_in_group == v_out_group) {
      /* Special case for 2h1v upsampling */
      upsample->methods[ci] = h2v1_upsample;
    } else if (h_in_group * 2 == h_out_group &&
           v_in_group * 2 == v_out_group) {
      /* Special case for 2h2v upsampling */
      upsample->methods[ci] = h2v2_upsample;
    } else if ((h_out_group % h_in_group) == 0 &&
           (v_out_group % v_in_group) == 0) {
      /* Generic integral-factors upsampling method */
      upsample->methods[ci] = int_upsample;
      upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
      upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
    } else
      ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
    if (need_buffer) {
      upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
    ((j_common_ptr) cinfo, JPOOL_IMAGE,
     (JDIMENSION) jround_up((long) cinfo->output_width,
                (long) cinfo->max_h_samp_factor),
     (JDIMENSION) cinfo->max_v_samp_factor);
    }
  }
}


text:
/**
 * @file
 *   This file contains definitions for Network Data CLI commands.
 */

#ifndef CLI_NETWORK_DATA_HPP_
#define CLI_NETWORK_DATA_HPP_

#include "openthread-core-config.h"

#include <openthread/netdata.h>

#include "cli/cli_output.hpp"

namespace ot {
namespace Cli {

/**
 * This class implements the Network Data CLI.
 *
 */
class NetworkData : private OutputWrapper
{
public:
    typedef Utils::CmdLineParser::Arg Arg;

    /**
     * This constant specifies the string size for representing Network Data prefix/route entry flags.
     *
     * BorderRouter (OnMeshPrefix) TLV uses `uint16_t` for its flags and ExternalRoute uses `uint8_t`, though some of
     * the bits are not currently used and reserved for future, so 17 chars string (16 flags plus null char at end of
     * string) covers current and future flags.
     *
     */
    static constexpr uint16_t kFlagsStringSize = 17;

    typedef char FlagsString[kFlagsStringSize]; ///< Flags String type (char array of `kFlagsStringSize`).

    /**
     * Constructor
     *
     * @param[in]  aOutput The CLI console output context
     *
     */
    explicit NetworkData(Output &aOutput)
        : OutputWrapper(aOutput)
    {
    }

    /**
     * This method interprets a list of CLI arguments.
     *
     * @param[in]  aArgs        An array of command line arguments.
     *
     */
    otError Process(Arg aArgs[]);

    /**
     * This method outputs the prefix config.
     *
     * @param[in]  aConfig  The prefix config.
     *
     */
    void OutputPrefix(const otBorderRouterConfig &aConfig);

    /**
     * This method outputs the route config.
     *
     * @param[in]  aConfig  The route config.
     *
     */
    void OutputRoute(const otExternalRouteConfig &aConfig);

    /**
     * This method outputs the service config.
     *
     * @param[in]  aConfig  The service config.
     *
     */
    void OutputService(const otServiceConfig &aConfig);

    /**
     * This method converts the flags from a given prefix config to string.
     *
     * @param[in]  aConfig  The prefix config.
     * @param[out] aString  The string to populate from @a Config flags.
     *
     */
    static void PrefixFlagsToString(const otBorderRouterConfig &aConfig, FlagsString &aString);

    /**
     * This method converts the flags from a given route config to string.
     *
     * @param[in]  aConfig  The route config.
     * @param[out] aString  The string to populate from @a Config flags.
     *
     */
    static void RouteFlagsToString(const otExternalRouteConfig &aConfig, FlagsString &aString);

private:
    using Command = CommandEntry<NetworkData>;

    template <CommandId kCommandId> otError Process(Arg aArgs[]);

    otError GetNextPrefix(otNetworkDataIterator *aIterator, otBorderRouterConfig *aConfig, bool aLocal);
    otError GetNextRoute(otNetworkDataIterator *aIterator, otExternalRouteConfig *aConfig, bool aLocal);
    otError GetNextService(otNetworkDataIterator *aIterator, otServiceConfig *aConfig, bool aLocal);

    otError OutputBinary(bool aLocal);
    void    OutputPrefixes(bool aLocal);
    void    OutputRoutes(bool aLocal);
    void    OutputServices(bool aLocal);
};

} // namespace Cli
} // namespace ot

#endif // CLI_NETWORK_DATA_HPP_


text:
.class Landroid/support/v4/app/FragmentTabHost$SavedState;
.super Landroid/view/View$BaseSavedState;
.source "FragmentTabHost.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/support/v4/app/FragmentTabHost;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = "SavedState"
.end annotation

.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Landroid/support/v4/app/FragmentTabHost$SavedState$1;
    }
.end annotation

# static fields
.field public static final CREATOR:Landroid/os/Parcelable$Creator;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Landroid/os/Parcelable$Creator",
            "<",
            "Landroid/support/v4/app/FragmentTabHost$SavedState;",
            ">;"
        }
    .end annotation
.end field

# instance fields
.field curTab:Ljava/lang/String;

# direct methods
.method static constructor <clinit>()V
    .locals 1

    new-instance v0, Landroid/support/v4/app/FragmentTabHost$SavedState$1;

    invoke-direct {v0}, Landroid/support/v4/app/FragmentTabHost$SavedState$1;-><init>()V

    sput-object v0, Landroid/support/v4/app/FragmentTabHost$SavedState;->CREATOR:Landroid/os/Parcelable$Creator;

    return-void
.end method

.method constructor <init>(Landroid/os/Parcel;)V
    .locals 1

    invoke-direct {p0, p1}, Landroid/view/View$BaseSavedState;-><init>(Landroid/os/Parcel;)V

    invoke-virtual {p1}, Landroid/os/Parcel;->readString()Ljava/lang/String;

    move-result-object v0

    iput-object v0, p0, Landroid/support/v4/app/FragmentTabHost$SavedState;->curTab:Ljava/lang/String;

    return-void
.end method

.method constructor <init>(Landroid/os/Parcelable;)V
    .locals 0

    invoke-direct {p0, p1}, Landroid/view/View$BaseSavedState;-><init>(Landroid/os/Parcelable;)V

    return-void
.end method

# virtual methods
.method public toString()Ljava/lang/String;
    .locals 2

    new-instance v0, Ljava/lang/StringBuilder;

    invoke-direct {v0}, Ljava/lang/StringBuilder;-><init>()V

    const-string/jumbo v1, "FragmentTabHost.SavedState{"

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-static {p0}, Ljava/lang/System;->identityHashCode(Ljava/lang/Object;)I

    move-result v1

    invoke-static {v1}, Ljava/lang/Integer;->toHexString(I)Ljava/lang/String;

    move-result-object v1

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    const-string/jumbo v1, " curTab="

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    iget-object v1, p0, Landroid/support/v4/app/FragmentTabHost$SavedState;->curTab:Ljava/lang/String;

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    const-string/jumbo v1, "}"

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v0

    return-object v0
.end method

.method public writeToParcel(Landroid/os/Parcel;I)V
    .locals 1

    invoke-super {p0, p1, p2}, Landroid/view/View$BaseSavedState;->writeToParcel(Landroid/os/Parcel;I)V

    iget-object v0, p0, Landroid/support/v4/app/FragmentTabHost$SavedState;->curTab:Ljava/lang/String;

    invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeString(Ljava/lang/String;)V

    return-void
.end method


text:
"""Models for the wiki module

Author: Logan Gore
This file is responsible for defining models that belong in the wiki module.
"""

import datetime

from dli_app import db

from flask_login import current_user

class WikiPage(db.Model):
    """Model for a page on the wiki"""
    __tablename__ = 'wiki_page'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), index=True, unique=True)
    content = db.Column(db.Text)
    modtime = db.Column(db.String(32))
    editor = db.Column(db.String(64))
    views = db.Column(db.Integer, index=True)

    def __init__(self, name, content):
        """Initiialize a WikiPage model"""
        self.name = name
        self.content = content
        self.modtime = datetime.datetime.now().strftime('%m/%d/%Y %I:%M %p')
        if current_user:
            self.editor = current_user.name
        else:
            self.editor = 'DLI'
        self.views = 0

    def __repr__(self):
        """Return a descriptive representation of a WikiPage"""
        return '<WikiPage %r>' % self.name

    def with_toc(self):
        """Return the page contents with a Table of Contents header"""
        full_text = """
        [TOC]

        {content}
        """.format(content=self.content)
        return full_text


text:
package scalan.compilation

import java.io.{File, PrintWriter}

import scalan.ScalanDslExp
import scalan.util.FileUtil

case class IndentLevel(level: Int) {
  def incr = IndentLevel(level + 1)
}

// based on scala.lms.internal.GenericCodegen
/** Base class for code generators */
abstract class BaseCodegen[+ScalanCake <: ScalanDslExp](val scalan: ScalanCake) {
  import scalan._

  /** Codegen name (used in error messages) */
  lazy val codegenName = this.getClass.getSimpleName

  override def toString = codegenName

  /** Name of language generated (used in error messages) */
  def languageName: String

  /** File extension for generated code */
  def fileExtension: String = !!!(s"$codegenName must override either `fileExtension` or `fileName`")

  /** Standard indentation for one level */
  protected def indent = "    "

  /** File name (with extension) for generated code */
  def fileName(baseName: String) = baseName + "." + fileExtension

  /** Prepares to work with a kernel */
  def init(functionName: String, graph: PGraph) = {}

  /** Finishes working with a kernel */
  def reset() = {}

  def indented(f: IndentLevel => Unit)(implicit indentLevel: IndentLevel) = f(indentLevel.incr)

  def emit(string: String)(implicit stream: PrintWriter, indentLevel: IndentLevel) = {
    stream.print(indent * indentLevel.level)
    stream.println(string)
  }

  // May need to be split into emitFileHeader and emitKernelHeader if there are multiple kernels
  /** Emits the initial part of the file (before the kernel) */
  def emitHeader(graph: PGraph, functionName: String)(implicit stream: PrintWriter)

  /** Emits the kernel */
  def emitKernel(graph: PGraph, functionName: String)(implicit stream: PrintWriter) =
    emitSchedule(graph)(stream, IndentLevel(0))

  /** Emits the final part of the file (after the kernel) */
  def emitFooter(graph: PGraph, functionName: String)(implicit stream: PrintWriter)

  /** Emits the complete source file */
  def emitSourceFile(graph: PGraph, functionName: String, sourcesDir: File) = {
    init(functionName, graph)
    val sourceFile = this.sourceFile(sourcesDir, functionName)
    FileUtil.withFile(sourceFile) { implicit stream =>
      emitHeader(graph, functionName)
      emitKernel(graph, functionName)
      emitFooter(graph, functionName)
    }
    reset()
    sourceFile
  }

  def sourceFile(sourcesDir: File, functionName: String): File = {
    new File(sourcesDir, fileName(functionName))
  }

  def emitSchedule(graph: AstGraph, f: Schedule => Schedule = identity)(implicit stream: PrintWriter, indentLevel: IndentLevel) = {
    val originalSchedule = graph.schedule
    val schedule = f(originalSchedule)
    schedule.foreach { te =>
      emitNode(te.sym, te.rhs, graph)
    }
  }

  /** Emits a node in the schedule. Override this for nodes which need more than one line, and
    * `rhs` for the simple cases. */
  def emitNode(sym: Exp[_], d: Def[_], graph: AstGraph)(implicit stream: PrintWriter, indentLevel: IndentLevel) = d match {
    case Lambda(lam, _, x, y) =>
      val args = argList(sym, x)
      emitFunction(sym, args, Some(y), lam)
    case th @ ThunkDef(root, schedule) =>
      emitFunction(sym, Nil, Some(root), th)
    case _ => emit(simpleNode(sym, d))
  }

  def argList(f: Exp[_], x: Exp[_]): List[Exp[_]] = {
    def argList(x: Exp[_], n: Int): List[Exp[_]] =
      n match {
        case 1 =>
          x :: Nil
        case _ =>
          x.elem match {
            case _: PairElem[a, b] =>
              val Pair(head, tail) = x.asRep[(a, b)]
              head :: argList(tail, n -1)
            case _ =>
              !!!(s"$n arguments expected, but ${x.toStringWithDefinition} is not a nested tuple")
          }
      }

    val numArgs = getMetadata(f, MultipleArgsKey).getOrElse(1)
    argList(x, numArgs)
  }

  def emitFunction(sym: Exp[_], args: List[Exp[_]], returnValue: Option[Exp[Any]], lambdaOrThunk: AstGraph, f: Schedule => Schedule = identity)(implicit stream: PrintWriter, indentLevel: IndentLevel): Unit = {
    emit(functionHeader(sym, args))
    indented { implicit indentLevel =>
      emitSchedule(lambdaOrThunk, (s: Schedule) => f(s.filterNot(te => args.contains(te.sym))))
      returnValue.foreach(x => emit(functionReturn(x)))
    }
    functionFooter().foreach(emit(_))
  }

  def functionHeader(sym: Exp[_], args: List[Exp[_]]): String
  def functionReturn(y: Exp[_]): String
  def functionFooter(): Option[String]

  /** Translation of a simple (non-complex) node. Normally calls `tpe(sym.elem)` (in typed languages),
    * `id(sym)` and `rhs(d)`. Example for C: `src"${sym.elem} $sym = $d;`.
    */
  protected def simpleNode(sym: Exp[_], d: Def[_]): String

  /** Translation of the type represented by an `Elem` to the generated language
    * (no need to implement for weakly typed or fully type-inferred languages). */
  def tpe(elem: Elem[_]): String = !!!(s"$codegenName can't map ${elem.name} to $languageName")

  /** Translation of an `Exp` */
  def id(s: Exp[_]) = s.varName

  /** Translation of a literal. The default is C/Java literals for primitives and `null`. */
  def literal(value: Any): String = value match {
    case Double.PositiveInfinity => specialNumericLiteral(PosInf, DOUBLE)
    case Float.PositiveInfinity => specialNumericLiteral(PosInf, FLOAT)
    case Double.NegativeInfinity => specialNumericLiteral(NegInf, DOUBLE)
    case Float.NegativeInfinity => specialNumericLiteral(NegInf, FLOAT)
    case d: Double if d.isNaN => specialNumericLiteral(NaN, DOUBLE)
    case f: Float if f.isNaN => specialNumericLiteral(NaN, FLOAT)
    case (_: Int) | (_: Double) | (_: Boolean) => value.toString
    case f: Float => "%1.10f".format(f) + "F"
    case l: Long => l.toString + "L"
    case s: String =>
      "\""+s.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n").replace("\r", "\\r").replace("\t", "\\t")+"\""
    case c: Char =>
      "'"+c.toString.replace("'", "\\'").replace("\n", "\\n").replace("\r", "\\r").replace("\t", "\\t")+"'"
    case null => "null"
    case _ => !!!(s"$codegenName doesn't know literals for ${value.getClass} in $languageName")
  }

  sealed trait SpecialNumericValue
  case object PosInf extends SpecialNumericValue
  case object NegInf extends SpecialNumericValue
  case object NaN extends SpecialNumericValue

  sealed trait BaseNumericType
  case object FLOAT extends BaseNumericType
  case object DOUBLE extends BaseNumericType

  def specialNumericLiteral(x: SpecialNumericValue, t: BaseNumericType): String

  def unOp(op: UnOp[_, _], x: Exp[_]): String =
    src"${op.opName} $x"

  def binOp(op: BinOp[_, _], x: Exp[_], y: Exp[_]): String =
    src"$x ${op.opName} $y"

  /** Translation of a `Def` */
  def rhs(d: Def[_]): String = d match {
    case Const(x) => literal(x)
    case ApplyUnOp(op, x) => unOp(op, x)
    case ApplyBinOp(op, x, y) => binOp(op, x, y)
    case Apply(f, x) =>
      val args = argList(f, x)
      applyFunction(f, args)
    case ThunkForce(th) =>
      applyFunction(th, Nil)
    case _ => !!!(s"$codegenName can't translate definition $d (type ${d.selfType.name}) to $languageName")
  }

  def applyFunction(f: Exp[_], args: Seq[Exp[_]]): String = src"$f($args)"

  protected def translate(arg: Any): String = arg match {
    case elem: Elem[_] => tpe(elem)
    case e: Exp[_] => id(e)
    case d: Def[_] => rhs(d)
    case str: String => str
    case num: Number => num.toString
    case xs: Seq[_] => xs.map(translate).mkString(", ")
    case xs: Array[_] => xs.map(translate).mkString(", ")
    case _ => !!!(s"$codegenName can't translate $arg to $languageName")
  }

  implicit class CodegenHelper(sc: StringContext) {
    /** Generates code from interpolated string using `translate` for Scalan types (`Exp`, `Def`) */
    def src(args: Any*): String = {
      sc.raw(args.map(translate): _*).stripMargin
    }
  }
}


text:
@interface ISProductSettings : NSObject

@property (readonly, strong)    NSArray         *placements;
@property (readonly, assign)    NSUInteger      maxNumOfAdaptersToLoadOnStart;
@property (readonly, assign)    BOOL            advancedLoading;
@property (readonly, assign)    double          adapterTimeOutInSeconds;
@property (readonly, strong)    NSString        *algo;
@property (nonatomic, copy)     NSString        *backFillProviderName;
@property (nonatomic, copy)     NSString        *premiumProviderName;
@property (assign)              NSInteger       bannerInterval;
@property (assign)              NSInteger       loadRVInterval;
@property (assign)              NSUInteger      delayLoadFailureNotificationInSeconds;
@property (readonly,assign)     NSInteger       expiredDurationInMinutes;

- (instancetype) initWithplacements:(NSArray *)placements
      maxNumOfAdaptersToLoadOnStart:(NSUInteger)maxAdapters
                    advancedLoading:(BOOL)advancedLoading
            adapterTimeOutInSeconds:(double)adapterTimeout
delayLoadFailureNotificationInSeconds:(NSUInteger)delayLoadFailure
                               algo:(NSString *)algo
               backFillProviderName:(NSString *)backFillProviderName
                premiumProviderName:(NSString *)premiumProviderName
           expiredDurationInMinutes:(NSInteger)expiredDurationInMinutes;
@end


text:
export default {
  bind () {
    this.onClick = (event) => {
      if (this.el.contains(event.target)) return false
      if (this.expression) this.vm[this.expression]()
    }
    setTimeout(() => {
      document.addEventListener('click', this.onClick)
    })
  },
  unbind () {
    document.removeEventListener('click', this.onClick)
  }
}


text:
<?php
namespace jubianchi\BehatViewerBundle\Command;

use \Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand,
    \Symfony\Component\Console\Input\InputInterface,
    \Symfony\Component\Console\Output\OutputInterface,
    \Symfony\Component\Console\Input\InputOption,
    \Symfony\Component\Console\Input\InputArgument;

/**
 *
 */
class DeleteCommand extends ContainerAwareCommand
{
    /**
     *
     */
    protected function configure()
    {
        $this
            ->setName('behat-viewer:delete')
            ->setDescription('Deletes selected builds')
            ->setDefinition(
                array(
                    new InputArgument('builds', InputArgument::REQUIRED, 'The builds to delete'),
                    new InputArgument('project', InputArgument::OPTIONAL, 'The project to build'),
                )
            )
        ;
    }

  /**
   * @param InputInterface $input
   * @param OutputInterface $output
   *
   * @throws \RuntimeException
   *
   * @return int
   */
  protected function execute(InputInterface $input, OutputInterface $output)
    {
        $repository = $this->getContainer()->get('doctrine')->getRepository('BehatViewerBundle:Project');
        $project = $repository->findOneById(1);

        $builds = $input->getArgument('builds');
        $matches = array();
        $repository = $this->getContainer()->get('doctrine')->getRepository('BehatViewerBundle:Build');

        $output->writeln(sprintf('<info>[INFO]</info> Deleting builds for project <comment>%s</comment>', $project->getSlug()));

        switch (true) {
          case preg_match('/^(\d+)\.\.(\d+)$/', $builds, $matches):
              $output->writeln(sprintf(
                '<info>[INFO]</info> Deleting builds by <comment>ID interval [%d - %d]</comment>',
                $matches[1],
                $matches[2]
              ));

              $count = $repository->removeBuildsByIdIntervalForProject($matches[1], $matches[2], $project);
              break;
          case preg_match('/^([\d\-]+)\.\.([\d\-]+)$/', $builds, $matches):
              try {
                  $start = new \DateTime($matches[1]);
                  $end = new \DateTime($matches[2]);
              } catch (\Exception $e) {
                  throw new \RuntimeException('Invalid date');
              }

              $output->writeln(sprintf(
                '<info>[INFO]</info> Deleting builds by <comment>date interval [%s - %s]</comment>',
                $start->format('Y-m-d'),
                $end->format('Y-m-d')
              ));

              $count = $repository->removeBuildsByDateIntervalForProject($start, $end, $project);
              break;
          default:
              $count = $repository->removeBuildsByDateIntervalForProject(
                  $repository->findOneById((int) $builds),
                  $project
              );
              break;
        }

        $output->writeln(sprintf('<info>[INFO]</info> Deleted <comment>%d</comment> build(s)', $count));

        return 0;
    }
}


text:
import * as React from 'react';
import { IconBaseProps } from 'react-icon-base';
export default class GoCloudUpload extends React.Component<IconBaseProps> { }


text:
@interface PodsDummy_Pods_todTests : NSObject
@end
@implementation PodsDummy_Pods_todTests
@end


text:
namespace Cards{
class Odbicie : public virtual Prioritized, public virtual Modification, public BaseCardImpl{
public:
    string getName() override;
    bool canBePlayedAt(CardPtr card, GameServer* game) override;
    CardPtr makeNew() override;

    int& getPriority() override;
    void reset() override;
    void apply(BaseCard* parent) override;

    inline virtual ~Odbicie(){}
protected:
    int priority;
};
}

#endif


text:
<title>MMIX-Opts - Using as</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Using as">
<meta name="generator" content="makeinfo 4.11">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="MMIX_002dDependent.html#MMIX_002dDependent" title="MMIX-Dependent">
<link rel="next" href="MMIX_002dExpand.html#MMIX_002dExpand" title="MMIX-Expand">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">

<meta http-equiv="Content-Style-Type" content="text/css">

Next: MMIX-Expand,
Up: MMIX-Dependent

9.27.1 Command-line Options

The MMIX version of as has some machine-dependent options.

When ‘<samp>--fixed-special-register-names</samp>’ is specified, only the register
names specified in MMIX-Regs are recognized in the instructions
PUT and GET.

You can use the ‘<samp>--globalize-symbols</samp>’ to make all symbols global.
This option is useful when splitting up a mmixal program into
several files.

The ‘<samp>--gnu-syntax</samp>’ turns off most syntax compatibility with
mmixal.  Its usability is currently doubtful.

The ‘<samp>--relax</samp>’ option is not fully supported, but will eventually make
the object file prepared for linker relaxation.

If you want to avoid inadvertently calling a predefined symbol and would
rather get an error, for example when using as with a
compiler or other machine-generated code, specify
‘<samp>--no-predefined-syms</samp>’.  This turns off built-in predefined
definitions of all such symbols, including rounding-mode symbols, segment
symbols, ‘<samp>BIT</samp>’ symbols, and TRAP symbols used in mmix
“system calls”.  It also turns off predefined special-register names,
except when used in PUT and GET instructions.

By default, some instructions are expanded to fit the size of the operand
or an external symbol (see MMIX-Expand).  By passing
‘<samp>--no-expand</samp>’, no such expansion will be done, instead causing errors
at link time if the operand does not fit.

The mmixal documentation (see mmixsite) specifies that global
registers allocated with the ‘<samp>GREG</samp>’ directive (see MMIX-greg) and
initialized to the same non-zero value, will refer to the same global
register.  This isn't strictly enforceable in as since the
final addresses aren't known until link-time, but it will do an effort
unless the ‘<samp>--no-merge-gregs</samp>’ option is specified.  (Register merging
isn't yet implemented in ld.)

as will warn every time it expands an instruction to fit an
operand unless the option ‘<samp>-x</samp>’ is specified.  It is believed that
this behaviour is more useful than just mimicking mmixal's
behaviour, in which instructions are only expanded if the ‘<samp>-x</samp>’ option
is specified, and assembly fails otherwise, when an instruction needs to
be expanded.  It needs to be kept in mind that mmixal is both an
assembler and linker, while as will expand instructions
that at link stage can be contracted.  (Though linker relaxation isn't yet
implemented in ld.)  The option ‘<samp>-x</samp>’ also imples
‘<samp>--linker-allocated-gregs</samp>’.

If instruction expansion is enabled, as can expand a
‘<samp>PUSHJ</samp>’ instruction into a series of instructions.  The shortest
expansion is to not expand it, but just mark the call as redirectable to a
stub, which ld creates at link-time, but only if the
original ‘<samp>PUSHJ</samp>’ instruction is found not to reach the target.  The
stub consists of the necessary instructions to form a jump to the target.
This happens if as can assert that the ‘<samp>PUSHJ</samp>’
instruction can reach such a stub.  The option ‘<samp>--no-pushj-stubs</samp>’
disables this shorter expansion, and the longer series of instructions is
then created at assembly-time.  The option ‘<samp>--no-stubs</samp>’ is a synonym,
intended for compatibility with future releases, where generation of stubs
for other instructions may be implemented.

Usually a two-operand-expression (see GREG-base) without a matching
‘<samp>GREG</samp>’ directive is treated as an error by as.  When
the option ‘<samp>--linker-allocated-gregs</samp>’ is in effect, they are instead
passed through to the linker, which will allocate as many global registers
as is needed.