text:
package com.landian.crud.core.dao;

import com.landian.commons.page.PageListSupport;
import com.landian.commons.page.PageRequest;
import com.landian.crud.core.builder.SelectBuilder;
import com.landian.crud.core.builder.SqlBuilder;
import com.landian.crud.core.builder.impl.*;
import com.landian.crud.core.context.ResultMapContext;
import com.landian.crud.core.context.SystemContextFactory;
import com.landian.crud.core.context.impl.HashMapResultContext;
import com.landian.crud.core.converter.ResultContextConverter;
import com.landian.crud.core.converter.ResultContextConverterFactory;
import com.landian.crud.core.converter.impl.JavaBeanConverter;
import com.landian.crud.core.provider.ProviderHelper;
import com.landian.crud.core.result.SingleValue;
import com.landian.crud.core.result.StatisticMap;
import com.landian.crud.core.result.StatisticMapBuilder;
import com.landian.crud.core.sql.DeleteSQLBuilder;
import com.landian.crud.core.sql.InsertSQLBuilder;
import com.landian.crud.core.sql.PageSqlAdapter;
import com.landian.crud.core.sql.UpdateSQLBuilder;
import com.landian.sql.jpa.annotation.IdTypePolicy;
import com.landian.sql.jpa.context.BeanContext;
import com.landian.sql.jpa.context.ResultMapConfig;
import com.landian.sql.jpa.context.ResultMappingVirtual;
import com.landian.sql.jpa.criterion.Criterion;
import com.landian.sql.jpa.criterion.CriterionAppender;
import com.landian.sql.jpa.criterion.FieldAppender;
import com.landian.sql.jpa.criterion.Restrictions;
import com.landian.sql.jpa.log.JieLoggerProxy;
import com.landian.sql.jpa.order.Order;
import com.landian.sql.jpa.order.OrderAppender;
import com.landian.sql.jpa.sql.SelectUnitAppender;
import com.landian.sql.jpa.sql.SelectUnitRestrictions;
import com.landian.sql.jpa.sql.UpdateUnitAppender;
import com.landian.sql.jpa.utils.ConvertUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * ProxyDaoSupport
 * @author cao.jl
 * to be continute
 * * 毫无疑问,SpringData才是大神版的进化封装
 */
@Repository
public class ProxyDaoSupport<T> {

	@SuppressWarnings("unused")
	private static final Logger logger = Logger.getLogger(ProxyDaoSupport.class);

	private static final Logger infoSQLLogger = Logger.getLogger("infoSQL");

	@Autowired
	private ProxyDao proxyDao;

	private void proxyInfo(Object object){
		if(null != infoSQLLogger){
			infoSQLLogger.info(object);
		}
	}

	/**
	 * 指定ID业务Bean是否存在
	 * @param beanId
	 * @param beanContext
	 * @return
	 */
	public boolean isExist(long beanId,BeanContext beanContext) {
		String beanIdColumn = this.getBeanIdColumn(beanContext);
		CommonSelectSQLBuilder builder = CommonSelectSQLBuilder.getInstance(beanContext.getTableName(),
				SelectUnitRestrictions.column(beanIdColumn),
				Restrictions.eq(beanIdColumn, beanId),
				Order.asc(beanIdColumn));
		HashMapResultContext hashMapResultContext = this.doFind(builder.SQL());
		if(hashMapResultContext.getResultCount() > 0){
			return true;
		}
		return false;
	}

	public int doInsert(String sql){
		return proxyDao.doInsert(sql);
	}

	/**
	 * 插入对像bean
	 * @param bean
	 * @param beanContext
	 */
	public int insertWithId(Object bean,BeanContext beanContext){
		String sql = InsertSQLBuilder.insertWithIdSQL(bean, beanContext);
		return proxyDao.doInsertWidthId(sql);
	}

	/**
	 * 插入对像bean
	 * @param bean
	 * @param beanContext
	 */
	public void insert(Object bean,BeanContext beanContext){
		String sql = InsertSQLBuilder.insertSQL(bean, beanContext);
		Object idObject = proxyDao.doInsertAndReturnId(sql);
		//回填ID
		refillId(bean, beanContext, idObject);
	}

	/**
	 * 回填业务Bean ID
	 */
	private void refillId(Object bean, BeanContext beanContext,Object idObject){
		try {
			String idFieldName = beanContext.getIdFieldName();
			String setMethodName = ProviderHelper.toSetMethodName(idFieldName);
			Method idSetMethod = null;
			SingleValue idSingleValue = SingleValue.newInstance(idObject);
			Object fixIdObject = null;
			if(IdTypePolicy.INTEGER == beanContext.getIdType()){
				fixIdObject = idSingleValue.integerValue();
                idSetMethod = bean.getClass().getDeclaredMethod(setMethodName,Integer.class);
            }else if(IdTypePolicy.LONG == beanContext.getIdType()){
				fixIdObject = idSingleValue.longValue();
                idSetMethod = bean.getClass().getDeclaredMethod(setMethodName,Long.class);
            }else if(IdTypePolicy.BIGDECIMAL == beanContext.getIdType()){
				fixIdObject = idSingleValue.bigDecimalValue();
				idSetMethod = bean.getClass().getDeclaredMethod(setMethodName,BigDecimal.class);
			}
			if(null == idSetMethod){
				String msg = MessageFormat.format("ID回填策略未实现,目标对像[{0}],目标类型[{1}]",bean,idObject);
				logger.warn(msg);
			}else{
				idSetMethod.invoke(bean,new Object[]{fixIdObject});
			}
		}catch (Exception e) {
			String errorMsg = "回填业务Bean ID异常!";
			JieLoggerProxy.error(logger, errorMsg);
			JieLoggerProxy.error(logger, e);
			throw new RuntimeException(errorMsg);
		}
	}

	/**
	 * 更新对像非空属性值
	 * @param bean
	 * @param beanContext
	 */
	public int updateNotNull(Object bean, BeanContext beanContext) {
		String sql = UpdateSQLBuilder.updateNotNull(bean, beanContext);
		return proxyDao.doUpdate(sql);
	}

	/**
	 * 更新字段
	 * @param updateUnitAppender 更新单元追加器
	 * @param criterionAppender 条件追加器
	 * @param beanContext
	 * @return
	 * @throws Exception
	 */
	public int update(UpdateUnitAppender updateUnitAppender, CriterionAppender criterionAppender,
			BeanContext beanContext){
		String sql = UpdateSqlBuilder.getInstance(beanContext.getTableName(), updateUnitAppender, criterionAppender).SQL();
		return proxyDao.doUpdate(sql);
	}

	/**
	 * 更新对像非空属性值
	 * @param sql
	 */
	public int doUpdate(String sql) {
		return proxyDao.doUpdate(sql);
	}

	/**
	 * 查询统计
	 * 由于经常需要根据ID(某属性作为key),统计某属性总计(某属性总计作为Value)
	 * @param sql
	 * @param resultMapConfig
	 * @return
	 */
	public StatisticMap queryAsStatisticMap(String sql,ResultMapConfig resultMapConfig) {
		HashMapResultContext hashMapResultContext = doFind(sql);
		return StatisticMapBuilder.buildStatisticMap(resultMapConfig, hashMapResultContext);
	}

	/**
	 * 根据SQL查询,返回结果集
	 * @param sql
	 */
	public HashMapResultContext doFind(String sql){
		proxyInfo(sql);
		List<Map<String, Object>> resultContext = proxyDao.doFind(sql);
		HashMapResultContext hashMapResultContext = new HashMapResultContext(resultContext);
		return hashMapResultContext;
	}

	/**
	 * 根据SQL查询,返回结果集
	 * @param sql
	 */
	public List doFind(String sql,Class clazz){
		proxyInfo(clazz);
		proxyInfo(sql);
		//转换器
		ResultContextConverter converter = JavaBeanConverter.newInstance(clazz);
		//适配调用
		return this.doFind(sql, converter);
	}

	/**
	 * @param sql
	 * @param converter 结果集转换器
	 */
	public List<T> doFindPage(String sql, int start, int pageSize,  ResultContextConverter converter){
		PageSqlAdapter pageSqlAdapter = SystemContextFactory.getPageSqlAdapter();
		String pageSQL = pageSqlAdapter.wrapSQL(sql,start,pageSize);
		//结果集
		List<Map<String, Object>> resultList = proxyDao.doFind(pageSQL);
		//处理结果集
		List<T> beanList = new ArrayList<T>();
		if(CollectionUtils.isNotEmpty(resultList)){
			for(Map<String, Object> dataMap : resultList){
				@SuppressWarnings("unchecked")
				T bean = (T) converter.convert(dataMap);
				beanList.add(bean);
			}
		}
		return beanList;
	}

	/**
	 * @param sql
	 * @param converter 结果集转换器
	 */
	public List<T> doFind(String sql, ResultContextConverter converter){
		//结果集
		HashMapResultContext hashMapResultContext = this.doFind(sql);
		//处理结果集
		List<T> beanList = new ArrayList<T>();
		List<Map<String, Object>> resultList = hashMapResultContext.getResultObject();
		if(CollectionUtils.isNotEmpty(resultList)){
			for(Map<String, Object> dataMap : resultList){
				@SuppressWarnings("unchecked")
				T bean = (T) converter.convert(dataMap);
				beanList.add(bean);
			}
		}
		return beanList;
	}

	/**
	 * 根据ID查询对像
	 * @param beanId
	 * @param beanContext
	 */
	public T queryById(int beanId, BeanContext beanContext){
		Integer id = beanId;
		return this.queryById(id.longValue(), beanContext);
	}

	/**
	 * 根据ID查询对像
	 * @param beanId
	 * @param beanContext
	 */
	public T queryById(long beanId,BeanContext beanContext){
		List<Long> ids = new ArrayList<Long>();
		ids.add(beanId);
		List<T> list = this.queryByIds(ids,beanContext);
		if(!CollectionUtils.isEmpty(list)){
			return list.get(0);
		}
		return null;
	}

	/**
	 * 根据ID列表,查询对像集
	 * @param beanContext
	 * @param ids
	 */
	public List<T> queryByIds(BeanContext beanContext,List<Integer> ids){
		if(CollectionUtils.isEmpty(ids)){
			return Collections.EMPTY_LIST;
		}
		return queryByIds(ConvertUtils.Int2long(ids),beanContext);
	}

	/**
	 * 根据ID列表,查询对像集
	 * @param ids
	 * @param beanContext
	 */
	public List<T> queryByIds(List<Long> ids,BeanContext beanContext){
		if(CollectionUtils.isEmpty(ids)){
			return Collections.EMPTY_LIST;
		}
		CriterionAppender criterionAppender = CriterionAppender.newInstance();
		String column = beanContext.getIdFieldName();
		criterionAppender.add(Restrictions.in(column, ids,0l));
		List<T> beanList = queryBean(beanContext,criterionAppender);
		return beanList;
	}

	/**
	 * 此方法非元数据表,谨慎使用
	 * 查询Bean全部对像
	 * @param beanContext
	 */
	public List<T> queryBeanAll(BeanContext beanContext) {
		return queryBean(beanContext,null,null);
	}

	/**
	 * 查询Bean
	 * @param beanContext
	 * @param criterionAppender
	 */
	public List<T> queryBean(BeanContext beanContext,CriterionAppender criterionAppender) {
		return queryBean(beanContext,criterionAppender,null);
	}

	/**
	 * 查询Bean
	 * @param beanContext
	 * @param proxyOrderAppender
	 */
	public List<T> queryBean(BeanContext beanContext,OrderAppender proxyOrderAppender) {
		return queryBean(beanContext,null,proxyOrderAppender);
	}

	/**
	 * 查询bean
	 * @param beanContext
	 * @param criterionAppender
	 * @param proxyOrderAppender
	 */
	public List<T> queryBean(BeanContext beanContext,CriterionAppender criterionAppender,
			OrderAppender proxyOrderAppender) {
		String tableName = beanContext.getTableName();
		//选择器
		Class<T> beanClass = beanContext.getBeanClass();
		SelectBuilder selectBuilder = SelectBuilderFactory.builder(beanClass);
		SqlBuilder sqlBuilder = SqlBuilderFactory.builder(tableName, beanClass, selectBuilder, criterionAppender, proxyOrderAppender);
		//转换器
		ResultContextConverter resultContextConverter = ResultContextConverterFactory.build(beanContext.getBeanClass());
		//数据集
		List<T> beanList = queryBean(sqlBuilder,resultContextConverter);
		return beanList;
	}

	/**
	 * 查询bean
	 * @param beanContext
	 * @param criterionAppender
	 * @param proxyOrderAppender
	 */
	public List<T> queryBeanField(BeanContext beanContext,FieldAppender fieldAppender, CriterionAppender criterionAppender,
			OrderAppender proxyOrderAppender) {
		String tableName = beanContext.getTableName();
		//选择器
		SelectBuilder selectBuilder = new FieldAppenderSelectBuilder(fieldAppender,beanContext.getBeanClass());
		SqlBuilder sqlBuilder = SqlBuilderFactory.builder(tableName, beanContext.getBeanClass(), selectBuilder, criterionAppender, proxyOrderAppender);
		//转换器
		ResultContextConverter resultContextConverter = ResultContextConverterFactory.build(beanContext.getBeanClass());
		//数据集
		List<T> beanList = queryBean(sqlBuilder, resultContextConverter);
		return beanList;
	}

	/**
	 * 查询对像信息
	 * @param tableName
	 * @param clazz
	 * @param selectUnitAppender
	 * @param criterionAppender
	 * @param proxyOrderAppender
	 * @return
	 */
	public HashMapResultContext queryBeanInfo(String tableName, Class clazz,SelectUnitAppender selectUnitAppender,
			CriterionAppender criterionAppender, OrderAppender proxyOrderAppender) {
		//选择器
		SelectBuilder selectBuilder = SelectBuilderFactory.builder(selectUnitAppender);
		//SQL构建器
		SqlBuilder sqlBuilder = SqlBuilderFactory.builder(tableName, clazz, selectBuilder, criterionAppender, proxyOrderAppender);
		//结果集
		String sql = sqlBuilder.SQL();
		HashMapResultContext hashMapResultContext = this.doFind(sql);
		return hashMapResultContext;
	}

	/**
	 * 决定不重载此方法基于以下理由
	 * 1.分页查询大部份情况需要追加条件和排序
	 * 2.参数已经没有更好重构感觉,个人感觉不能再少了,
	 *   重载会令方法组数量变多
	 * 3.criterionAppender proxyOrderAppender 入参可为null,
	 *   里面的SqlBuilder已作了相应处理,
	 * @param beanContext
	 * @param criterionAppender
	 * @param proxyOrderAppender
	 * @param pageRequest
	 * @return
	 */
	public PageListSupport<T> queryBeanPage(BeanContext beanContext,
			CriterionAppender criterionAppender,OrderAppender proxyOrderAppender,PageRequest pageRequest) {
		String tableName = beanContext.getTableName();
		//选择器
		SelectBuilder selectBuilder = SelectBuilderFactory.builder(beanContext.getBeanClass());
		//加强条件追加器
		if(null == criterionAppender){
			criterionAppender = CriterionAppender.newInstance();
		}
		//SQL建造器
		SqlBuilder sqlBuilder = SqlBuilderFactory.builder(tableName, beanContext.getBeanClass(), selectBuilder, criterionAppender, proxyOrderAppender);
		//转换器
		ResultContextConverter resultContextConverter = ResultContextConverterFactory.build(beanContext.getBeanClass());
		//分页查询
		int start = getPageStart(pageRequest);
		int size = pageRequest.getPageSize();
		List<T> beanList = doFindPage(sqlBuilder.SQL(), start, size, resultContextConverter);
		//封装PageListSupport
		PageListSupport<T> pageListSupport = new PageListSupport<T>();
		//总数查询
		Long count = 0l;
		if(!CollectionUtils.isEmpty(beanList)){
			HashMapResultContext hashMapResultContext = this.doFind(sqlBuilder.SQLCount());
			Object countObj = hashMapResultContext.singleResult();
			if(null != countObj){
				SingleValue singleValue = SingleValue.newInstance(countObj);
				count = singleValue.longValue();
			}
		}
		pageListSupport.setList(beanList);
		pageListSupport.setCount(count);
		pageListSupport.setPageIndex(pageRequest.getPageIndex());
		pageListSupport.setPageSize(pageRequest.getPageSize());
		return pageListSupport;
	}

	/**
	 * 查询Bean
	 * @param sqlBuilder
	 * @param resultContextConverter
	 */
	public List<T> queryBean(SqlBuilder sqlBuilder,ResultContextConverter resultContextConverter) {
		return doFind(sqlBuilder.SQL(), resultContextConverter);
	}

	/**
	 * 得到业务Bean的id字段
	 * @param beanContext
	 * @return
	 */
	public String getBeanIdColumn(BeanContext beanContext){
		String idFieldName = beanContext.getIdFieldName();
		Map<String, ResultMappingVirtual> resultMappingMap = ResultMapContext.getResultMappingMap(beanContext.getBeanClass());
		String columnName = resultMappingMap.get(idFieldName).getColumn();
		return columnName;
	}

	/**
	 * author jie
	 * date 15/08/21
	 * 根据业务BeanID删除业务Bean
	 * @param beanId
	 * @param beanContext
	 * @return
	 */
	public int deleteById(long beanId, BeanContext beanContext) {
		Criterion criterion = buildIdCriterion(beanId, beanContext);
		String sql = DeleteSQLBuilder.buildDeleteSQL(beanContext.getTableName(), criterion);
		return doDelete(sql);
	}

	/**
	 * 构建ID条件
	 * @param id
	 * @param beanContext
	 * @return
	 */
	public Criterion buildIdCriterion(long id, BeanContext beanContext){
		String beanIdColumn = getBeanIdColumn(beanContext);
		return Restrictions.eq(beanIdColumn,id);
	}

	/**
	 * 构建ID条件
	 * @param ids
	 * @param beanContext
	 * @return
	 */
	public Criterion buildIdCriterion(List<Long> ids, BeanContext beanContext){
		String beanIdColumn = getBeanIdColumn(beanContext);
		return Restrictions.in(beanIdColumn,ids,0l);
	}

	/**
	 * 根据ID批量删除
	 * @param ids
	 * @param beanContext
	 * @return
	 */
	public int deleteByIdLong(List<Long> ids,BeanContext beanContext) {
		if(CollectionUtils.isEmpty(ids)){
			return 0;
		}
		Criterion criterion = buildIdCriterion(ids, beanContext);
		String sql = DeleteSQLBuilder.buildDeleteSQL(beanContext.getTableName(), criterion);
		return doDelete(sql);
	}

	public int doDelete(String sql){
		return proxyDao.doDelete(sql);
	}

	/**
	 * 得到构建的查询SQL
	 * @param beanContext
	 * @param criterionAppender
	 * @param proxyOrderAppender
	 * @return
	 */
	public String getQuerySQL(BeanContext beanContext, CriterionAppender criterionAppender, OrderAppender proxyOrderAppender) {
		//选择器
		SelectBuilder selectBuilder = SelectBuilderFactory.builder(beanContext.getBeanClass());
		//SQL建造器
		String tableName = beanContext.getTableName();
		SqlBuilder sqlBuilder = SqlBuilderFactory.builder(tableName, beanContext.getBeanClass(), selectBuilder, criterionAppender, proxyOrderAppender);
		return sqlBuilder.SQL();
	}

	private int getPageStart(PageRequest pageRequest) {
		return pageRequest.getPageIndex() * pageRequest.getPageSize(); //起始分页位置
	}

	/**
	 * 根据SQL查询,返回结果集第一个对像
	 * @param sql
	 */
	public Object queryAsValueFirst(String sql,Class clazz){
		List list = this.doFind(sql, clazz);
		if(CollectionUtils.isEmpty(list)){
			return null;
		}
		return list.get(0);
	}

	/**
	 * 根据SQL查询,返回单值列表结果
	 * @param sql
	 */
	public List queryAsValueList(String sql){
		List list = Collections.EMPTY_LIST;
		HashMapResultContext hashMapResultContext = doFind(sql);
		if(hashMapResultContext.getResultCount() > 0){
			list = hashMapResultContext.singleList();
		}
		return list;
	}

	/**
	 * 查询为SingleValue
	 * @param sql
	 * @return
	 */
	public SingleValue queryAsSingleValue(String sql) {
		HashMapResultContext hashMapResultContext = this.doFind(sql);
		Object object = hashMapResultContext.singleResult();
		SingleValue singleValue = SingleValue.newInstance(object);
		return singleValue;
	}

	/**
	 * 查询为SingleValueInt
	 * @param sql
	 * @return
	 */
	public int queryAsSingleValueInt(String sql) {
		SingleValue singleValue = queryAsSingleValue(sql);
		return singleValue.integerValue();
	}

	/**
	 * 查询为SingleValueLong
	 * @param sql
	 * @return
	 */
	public long queryAsSingleValueLong(String sql) {
		SingleValue singleValue = queryAsSingleValue(sql);
		return singleValue.longValue();
	}

	/**
	 * 查询为Long值列表
	 * @param sql
	 * @return
	 */
	public List<Long> queryAsLongValue(String sql) {
		return proxyDao.queryAsLongValue(sql);
	}

	/**
	 * 查询为Long值列表
	 * @param sql
	 * @param start 开始位置
	 * @param size 查询大小
	 * @return
	 */
	public List<Long> queryAsLongValue(String sql, int start, int size) {
		PageSqlAdapter pageSqlAdapter = SystemContextFactory.getPageSqlAdapter();
		String sqlQ = pageSqlAdapter.wrapSQL(sql, start, size);
		return proxyDao.queryAsLongValue(sqlQ);
	}

	/**
	 * 查询为Integer值列表
	 * @param sql
	 * @return
	 */
	public List<Integer> queryAsIntValue(String sql) {
		return proxyDao.queryAsIntValue(sql);
	}

	/**
	 * 查询为Integer值列表
	 * @param sql
	 * @param start 开始位置
	 * @param size 查询大小
	 * @return
	 */
	public List<Integer> queryAsIntValue(String sql, int start, int size) {
		PageSqlAdapter pageSqlAdapter = SystemContextFactory.getPageSqlAdapter();
		String sqlQ = pageSqlAdapter.wrapSQL(sql, start, size);
		return proxyDao.queryAsIntValue(sqlQ);
	}

}


text:
extern crate xml;
extern crate clap;

mod polyfill;
mod emitter;

use emitter::Emitter;

use std::fs::File;
use std::io::BufReader;

use xml::reader::{EventReader, XmlEvent};
use clap::{Arg, App};

fn matching_element_id<'a>(ids: &str, attr: &'a Vec<xml::attribute::OwnedAttribute>) -> Option<&'a str> {
    let id_attr = match attr.iter().find(|ref a| a.name.local_name == "id") {
        Some(a) => a,
        None => return None
    };

    if ids.is_empty() || ids.split(',').any(|i| id_attr.value == i) {
        Some(&id_attr.value)
    }
    else { None }
}

fn main() {
    let app: App = App::new("grayfx")
        .version("0.1.0")
        .author("Nigel Baillie <metreckk@gmail.com>")
        .about("Converts Inkscape SVGs into C++ rendering and/or physics code for Gray")
        .arg(Arg::with_name("input")
            .help("the svg file to parse")
            .short("f")
            .index(1)
            .takes_value(true)
            .required(true))
        .arg(Arg::with_name("ids")
            .short("i")
            .help("comma-separated ids of the elements to process")
            .takes_value(true)
            .required(false))
        .arg(Arg::with_name("color")
            .short("c")
            .help("expression to use for color")
            .takes_value(true)
            .required(false))
         .arg(Arg::with_name("drawvar")
             .short("d")
             .help("generate rendering code with this variable name")
             .takes_value(true)
             .required(false))
         .arg(Arg::with_name("physicsvar")
             .short("p")
             .help("generate physics setup code with this variable name")
             .takes_value(true)
             .required(false));
    let matches = app.get_matches();

    let filename = matches.value_of("input").unwrap();
    let file = File::open(filename).unwrap();
    let file = BufReader::new(file);

    let ids = matches.value_of("ids").unwrap_or("");
    let color = matches.value_of("color");

    let ids_count = if ids.is_empty() {
        0
    } else {
        ids.chars().fold(1, |n, c| if c == ',' { n + 1 } else { n })
    };

    // === Parse XML ===
    let mut emitter = Emitter::new();
    let parser = EventReader::new(file);
    'parse_xml: for xmlevent in parser {
        match xmlevent {
            // elements:
            Ok(XmlEvent::StartElement { name, attributes, .. }) => {
                if let Some(id) = matching_element_id(ids, &attributes) {
                    emitter.add_shape(id, &name.local_name, &attributes);

                    // Duck out early if possible
                    if ids_count > 0 && emitter.len() >= ids_count {
                        break 'parse_xml;
                    }
                }
            }
            /*
            Ok(XmlEvent::EndElement { name }) => {
                println!("END {}", name);
            }
            */
            Err(e) => {
                println!("// Error: {}", e);
                break;
            }
            _ => {}
        }
    }

    // TODO TODO TODO
    //   Next step is to parse color from style and tag collision shapes appropriately
    // TODO TODO TODO

    // === Now process elements that matched, in specified order ===
    let draw_var = matches.value_of("drawvar");
    let phys_var = matches.value_of("physicsvar");

    if ids_count > 0 {
        let each_id = ids.split(',');
        for id in each_id {

            let id_str = id.to_owned();
            if !emitter.emit(&id_str, draw_var, phys_var, color) {
                panic!("ID \"{}\" not found in {}", id_str, filename);
            }
        }
    }
    else {
        emitter.emit_all(draw_var, phys_var, color);
    }
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

const path = require('path');
const url = require('url');

/**
 * Normalazing result url, before replace decl value
 *
 * @param {String} assetUrl
 * @returns {String}
 */
const normalize = (assetUrl) => {
    assetUrl = path.normalize(assetUrl);

    return path.sep === '\\' ? assetUrl.replace(/\\/g, '\/') : assetUrl;
};

/**
 * @param {String} assetUrl
 * @returns {Boolean}
 */
const isUrlWithoutPathname = (assetUrl) => {
    return assetUrl[0] === '#'
        || assetUrl.indexOf('%23') === 0
        || assetUrl.indexOf('data:') === 0
        || /^[a-z]+:\/\//.test(assetUrl);
};

/**
 * Check if url is absolute, hash or data-uri
 *
 * @param {String} assetUrl
 * @param {PostcssUrl~Options} options
 * @returns {Boolean}
 */
const isUrlShouldBeIgnored = (assetUrl, options) => {
    return isUrlWithoutPathname(assetUrl) || (assetUrl[0] === '/' && !options.basePath);
};

/**
 * @param {String} baseDir - absolute target path
 * @param {String} assetsPath - extend asset path, can be absolute path
 * @param {String} relative - current relative asset path
 * @returns {String}
 */
const getAssetsPath = (baseDir, assetsPath, relative) =>
    path.resolve(baseDir, assetsPath || '', relative || '');

/**
 * Target path, output base dir
 *
 * @param {Dir} dir
 * @returns {String}
 */
const getTargetDir = (dir) =>
    dir.from !== dir.to ? dir.to : process.cwd();

/**
 * Stylesheet file path from decl
 *
 * @param {Decl} decl
 * @returns {String}
 */
const getPathDeclFile = (decl) =>
    decl.source && decl.source.input && decl.source.input.file;

/**
 * Stylesheet file dir from decl
 *
 * @param {Decl} decl
 * @returns {String}
 */
const getDirDeclFile = (decl) => {
    const filename = getPathDeclFile(decl);

    return filename ? path.dirname(filename) : process.cwd();
};

/**
 * Returns paths list, where we can find assets file
 *
 * @param {String[]|String} basePath - base paths where trying search to assets file
 * @param {Dir} dirFrom
 * @param {String} relPath - relative asset path
 * @returns {String[]}
 */
const getPathByBasePath = (basePath, dirFrom, relPath) => {
    if (relPath[0] === '/') {
        relPath = `.${relPath}`;
    }

    basePath = !Array.isArray(basePath) ? [basePath] : basePath;

    return basePath.map((pathItem) =>
        getAssetsPath(dirFrom, pathItem, relPath)
    );
};

/**
 * Preparing asset paths and data
 *
 * @param {String} assetUrl
 * @param {PostcssUrl~Dir} dir
 * @param {Decl} decl
 * @returns {PostcssUrl~Asset}
 */
const prepareAsset = (assetUrl, dir, decl) => {
    const parsedUrl = url.parse(assetUrl);
    const pathname = !isUrlWithoutPathname(assetUrl) ? parsedUrl.pathname : null;
    const absolutePath = pathname
        ? path.resolve(path.join(dir.file, pathname))
        : getPathDeclFile(decl);

    return {
        url: assetUrl,
        originUrl: assetUrl,
        pathname,
        absolutePath: absolutePath || dir.from,
        relativePath: absolutePath ? path.relative(dir.from, absolutePath) : '.',
        search: (parsedUrl.search || ''),
        hash: (parsedUrl.hash || '')
    };
};

module.exports = {
    normalize,
    prepareAsset,
    getAssetsPath,
    getDirDeclFile,
    getPathDeclFile,
    getTargetDir,
    getPathByBasePath,
    isUrlShouldBeIgnored
};

/**
 * @typedef {Object} PostcssUrl~Asset
 * @property {String} url - origin asset url
 * @property {String} name - parsed asset filename
 * @property {String} absolutePath - absolute asset path
 * @property {String} relativePath - relative asset path (relative to target dir)
 * @property {String} search - search from url, ex. ?query=1
 * @property {String} hash - hash from url
 */

/**
 * @typedef {Object} PostcssUrl~Dir
 * @property {String} from - dirname from postcss option 'from'
 * @property {String} to - dirname from postcss option 'to'
 * @property {String} file - decl file dirname (css file)
 */


text:
/* globals window, _, VIZI, dat */
(function() {
	"use strict";

	VIZI.Dat = function() {
		VIZI.Log("Inititialising dat.GUI");

		_.extend(this, VIZI.Mediator);

		this.gui = this.createGUI();

		this.subscribe("addToDat", this.addToDat);
	};

	VIZI.Dat.prototype.createGUI = function() {
		VIZI.Log("Creating dat.GUI");
		var gui = new dat.GUI();
		gui.close();
		return gui;
	};

	VIZI.Dat.prototype.addToDat = function(object, options) {
		VIZI.Log("Adding " + options.name + " to dat.GUI");

		// Create folder
		var folder = this.gui.addFolder(options.name);

		_.each(options.properties, function(property) {
			var controller = folder.add(object, property).listen();

			if (object.datChange) {
				controller.onChange(function() {
					object.datChange();
				});
			}
		});
	};
}());


text:
/*! @license Firebase v4.4.0
Build: rev-380121f
Terms: https://firebase.google.com/terms/ */

'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.ValidationPath = exports.Path = undefined;

var _util = require('./util');

var _utf = require('../../../utils/utf8');

/**
 * An immutable object representing a parsed path.  It's immutable so that you
 * can pass them around to other functions without worrying about them changing
 * it.
 */
/**
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var Path = /** @class */function () {
    /**
     * @param {string|Array.<string>} pathOrString Path string to parse,
     *      or another path, or the raw tokens array
     * @param {number=} pieceNum
     */
    function Path(pathOrString, pieceNum) {
        if (pieceNum === void 0) {
            this.pieces_ = pathOrString.split('/');
            // Remove empty pieces.
            var copyTo = 0;
            for (var i = 0; i < this.pieces_.length; i++) {
                if (this.pieces_[i].length > 0) {
                    this.pieces_[copyTo] = this.pieces_[i];
                    copyTo++;
                }
            }
            this.pieces_.length = copyTo;
            this.pieceNum_ = 0;
        } else {
            this.pieces_ = pathOrString;
            this.pieceNum_ = pieceNum;
        }
    }
    Object.defineProperty(Path, "Empty", {
        /**
         * Singleton to represent an empty path
         *
         * @const
         */
        get: function get() {
            return new Path('');
        },
        enumerable: true,
        configurable: true
    });
    Path.prototype.getFront = function () {
        if (this.pieceNum_ >= this.pieces_.length) return null;
        return this.pieces_[this.pieceNum_];
    };
    /**
     * @return {number} The number of segments in this path
     */
    Path.prototype.getLength = function () {
        return this.pieces_.length - this.pieceNum_;
    };
    /**
     * @return {!Path}
     */
    Path.prototype.popFront = function () {
        var pieceNum = this.pieceNum_;
        if (pieceNum < this.pieces_.length) {
            pieceNum++;
        }
        return new Path(this.pieces_, pieceNum);
    };
    /**
     * @return {?string}
     */
    Path.prototype.getBack = function () {
        if (this.pieceNum_ < this.pieces_.length) return this.pieces_[this.pieces_.length - 1];
        return null;
    };
    Path.prototype.toString = function () {
        var pathString = '';
        for (var i = this.pieceNum_; i < this.pieces_.length; i++) {
            if (this.pieces_[i] !== '') pathString += '/' + this.pieces_[i];
        }
        return pathString || '/';
    };
    Path.prototype.toUrlEncodedString = function () {
        var pathString = '';
        for (var i = this.pieceNum_; i < this.pieces_.length; i++) {
            if (this.pieces_[i] !== '') pathString += '/' + encodeURIComponent(String(this.pieces_[i]));
        }
        return pathString || '/';
    };
    /**
     * Shallow copy of the parts of the path.
     *
     * @param {number=} begin
     * @return {!Array<string>}
     */
    Path.prototype.slice = function (begin) {
        if (begin === void 0) {
            begin = 0;
        }
        return this.pieces_.slice(this.pieceNum_ + begin);
    };
    /**
     * @return {?Path}
     */
    Path.prototype.parent = function () {
        if (this.pieceNum_ >= this.pieces_.length) return null;
        var pieces = [];
        for (var i = this.pieceNum_; i < this.pieces_.length - 1; i++) {
            pieces.push(this.pieces_[i]);
        }return new Path(pieces, 0);
    };
    /**
     * @param {string|!Path} childPathObj
     * @return {!Path}
     */
    Path.prototype.child = function (childPathObj) {
        var pieces = [];
        for (var i = this.pieceNum_; i < this.pieces_.length; i++) {
            pieces.push(this.pieces_[i]);
        }if (childPathObj instanceof Path) {
            for (var i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {
                pieces.push(childPathObj.pieces_[i]);
            }
        } else {
            var childPieces = childPathObj.split('/');
            for (var i = 0; i < childPieces.length; i++) {
                if (childPieces[i].length > 0) pieces.push(childPieces[i]);
            }
        }
        return new Path(pieces, 0);
    };
    /**
     * @return {boolean} True if there are no segments in this path
     */
    Path.prototype.isEmpty = function () {
        return this.pieceNum_ >= this.pieces_.length;
    };
    /**
     * @param {!Path} outerPath
     * @param {!Path} innerPath
     * @return {!Path} The path from outerPath to innerPath
     */
    Path.relativePath = function (outerPath, innerPath) {
        var outer = outerPath.getFront(),
            inner = innerPath.getFront();
        if (outer === null) {
            return innerPath;
        } else if (outer === inner) {
            return Path.relativePath(outerPath.popFront(), innerPath.popFront());
        } else {
            throw new Error('INTERNAL ERROR: innerPath (' + innerPath + ') is not within ' + 'outerPath (' + outerPath + ')');
        }
    };
    /**
     * @param {!Path} left
     * @param {!Path} right
     * @return {number} -1, 0, 1 if left is less, equal, or greater than the right.
     */
    Path.comparePaths = function (left, right) {
        var leftKeys = left.slice();
        var rightKeys = right.slice();
        for (var i = 0; i < leftKeys.length && i < rightKeys.length; i++) {
            var cmp = (0, _util.nameCompare)(leftKeys[i], rightKeys[i]);
            if (cmp !== 0) return cmp;
        }
        if (leftKeys.length === rightKeys.length) return 0;
        return leftKeys.length < rightKeys.length ? -1 : 1;
    };
    /**
     *
     * @param {Path} other
     * @return {boolean} true if paths are the same.
     */
    Path.prototype.equals = function (other) {
        if (this.getLength() !== other.getLength()) {
            return false;
        }
        for (var i = this.pieceNum_, j = other.pieceNum_; i <= this.pieces_.length; i++, j++) {
            if (this.pieces_[i] !== other.pieces_[j]) {
                return false;
            }
        }
        return true;
    };
    /**
     *
     * @param {!Path} other
     * @return {boolean} True if this path is a parent (or the same as) other
     */
    Path.prototype.contains = function (other) {
        var i = this.pieceNum_;
        var j = other.pieceNum_;
        if (this.getLength() > other.getLength()) {
            return false;
        }
        while (i < this.pieces_.length) {
            if (this.pieces_[i] !== other.pieces_[j]) {
                return false;
            }
            ++i;
            ++j;
        }
        return true;
    };
    return Path;
}(); // end Path
exports.Path = Path;
/**
 * Dynamic (mutable) path used to count path lengths.
 *
 * This class is used to efficiently check paths for valid
 * length (in UTF8 bytes) and depth (used in path validation).
 *
 * Throws Error exception if path is ever invalid.
 *
 * The definition of a path always begins with '/'.
 */

var ValidationPath = /** @class */function () {
    /**
     * @param {!Path} path Initial Path.
     * @param {string} errorPrefix_ Prefix for any error messages.
     */
    function ValidationPath(path, errorPrefix_) {
        this.errorPrefix_ = errorPrefix_;
        /** @type {!Array<string>} */
        this.parts_ = path.slice();
        /** @type {number} Initialize to number of '/' chars needed in path. */
        this.byteLength_ = Math.max(1, this.parts_.length);
        for (var i = 0; i < this.parts_.length; i++) {
            this.byteLength_ += (0, _utf.stringLength)(this.parts_[i]);
        }
        this.checkValid_();
    }
    Object.defineProperty(ValidationPath, "MAX_PATH_DEPTH", {
        /** @const {number} Maximum key depth. */
        get: function get() {
            return 32;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(ValidationPath, "MAX_PATH_LENGTH_BYTES", {
        /** @const {number} Maximum number of (UTF8) bytes in a Firebase path. */
        get: function get() {
            return 768;
        },
        enumerable: true,
        configurable: true
    });
    /** @param {string} child */
    ValidationPath.prototype.push = function (child) {
        // Count the needed '/'
        if (this.parts_.length > 0) {
            this.byteLength_ += 1;
        }
        this.parts_.push(child);
        this.byteLength_ += (0, _utf.stringLength)(child);
        this.checkValid_();
    };
    ValidationPath.prototype.pop = function () {
        var last = this.parts_.pop();
        this.byteLength_ -= (0, _utf.stringLength)(last);
        // Un-count the previous '/'
        if (this.parts_.length > 0) {
            this.byteLength_ -= 1;
        }
    };
    ValidationPath.prototype.checkValid_ = function () {
        if (this.byteLength_ > ValidationPath.MAX_PATH_LENGTH_BYTES) {
            throw new Error(this.errorPrefix_ + 'has a key path longer than ' + ValidationPath.MAX_PATH_LENGTH_BYTES + ' bytes (' + this.byteLength_ + ').');
        }
        if (this.parts_.length > ValidationPath.MAX_PATH_DEPTH) {
            throw new Error(this.errorPrefix_ + 'path specified exceeds the maximum depth that can be written (' + ValidationPath.MAX_PATH_DEPTH + ') or object contains a cycle ' + this.toErrorString());
        }
    };
    /**
     * String for use in error messages - uses '.' notation for path.
     *
     * @return {string}
     */
    ValidationPath.prototype.toErrorString = function () {
        if (this.parts_.length == 0) {
            return '';
        }
        return "in property '" + this.parts_.join('.') + "'";
    };
    return ValidationPath;
}();
exports.ValidationPath = ValidationPath;
//# sourceMappingURL=Path.js.map


text:
require 'test/unit'
require_relative '../../app/util'

class TestAppUtil < Test::Unit::TestCase
  include Trepan::Util
  def test_safe_repr
    string = 'The time has come to talk of many things.'
    assert_equal(string, safe_repr(string, 50))
    assert_equal('The time...  things.', safe_repr(string, 17))
    assert_equal('"The tim... things."', safe_repr(string.inspect, 17))
    string = "'The time has come to talk of many things.'"
    assert_equal("'The tim... things.'", safe_repr(string, 17))
  end

  def test_abbrev
    list = %w(disassemble disable distance up)
    [['dis', 'dis'],
     ['disas', 'disassemble'],
     ['u', 'up'],
     ['upper', 'upper'],
     ['foo', 'foo']].each do |name, expect|
      assert_equal expect, uniq_abbrev(list, name)
    end
  end

  def test_extract_expression
    [['if condition("if")',        'condition("if")'],
     ['until until_termination',   'until_termination'],
     ['return return_value',       'return_value'],
     ['nothing_to_be.done',         'nothing_to_be.done'],
    ].each do |stmt, expect|
      assert_equal expect, extract_expression(stmt)
    end
  end
end


text:
<?php

namespace Oro\Bundle\EmailBundle\Tests\Unit\Provider;

use Doctrine\ORM\EntityManager;
use Oro\Bundle\AttachmentBundle\Provider\AttachmentProvider;
use Oro\Bundle\EmailBundle\Entity\Provider\EmailThreadProvider;
use Oro\Bundle\EmailBundle\Provider\EmailAttachmentProvider;
use Oro\Bundle\EmailBundle\Tools\EmailAttachmentTransformer;

class EmailAttachmentProviderTest extends \PHPUnit\Framework\TestCase
{
    /**
     * @var EmailThreadProvider|\PHPUnit\Framework\MockObject\MockObject
     */
    protected $emailThreadProvider;

    /**
     * @var EntityManager|\PHPUnit\Framework\MockObject\MockObject
     */
    protected $em;

    /**
     * @var AttachmentProvider|\PHPUnit\Framework\MockObject\MockObject
     */
    protected $attachmentProvider;

    /**
     * @var EmailAttachmentTransformer|\PHPUnit\Framework\MockObject\MockObject
     */
    protected $emailAttachmentTransformer;

    /**
     * @var EmailAttachmentProvider|\PHPUnit\Framework\MockObject\MockObject
     */
    protected $emailAttachmentProvider;

    protected function setUp()
    {
        $this->emailThreadProvider = $this->createMock('Oro\Bundle\EmailBundle\Entity\Provider\EmailThreadProvider');

        $this->em = $this->getMockBuilder('Doctrine\ORM\EntityManager')
            ->disableOriginalConstructor()
            ->getMock();

        $this->attachmentProvider = $this->getMockBuilder('Oro\Bundle\AttachmentBundle\Provider\AttachmentProvider')
            ->disableOriginalConstructor()
            ->getMock();

        $this->emailAttachmentTransformer = $this
            ->getMockBuilder('Oro\Bundle\EmailBundle\Tools\EmailAttachmentTransformer')
            ->disableOriginalConstructor()
            ->getMock();

        $this->emailAttachmentProvider = new EmailAttachmentProvider(
            $this->emailThreadProvider,
            $this->em,
            $this->attachmentProvider,
            $this->emailAttachmentTransformer
        );
    }

    /**
     * @param $threadEmails
     * @param $transformationCalls
     *
     * @dataProvider threadEmailsProvider
     */
    public function testGetThreadAttachments($threadEmails, $transformationCalls)
    {
        $emailEntity = $this->createMock('Oro\Bundle\EmailBundle\Entity\Email');

        $this->emailThreadProvider->expects($this->once())
            ->method('getThreadEmails')
            ->with($this->em, $emailEntity)
            ->willReturn($threadEmails);

        $this->emailAttachmentTransformer->expects($this->exactly($transformationCalls))
            ->method('entityToModel');

        $result = $this->emailAttachmentProvider->getThreadAttachments($emailEntity);
        $this->assertTrue(is_array($result));
        $this->assertEquals($transformationCalls, sizeof($result));
    }

    /**
     * @return array
     */
    public function threadEmailsProvider()
    {
        $threadEmails = [];
        $transformationCalls = 0;
        $threadEmailCount = 3;
        for ($i = 0; $i < $threadEmailCount; $i++) {
            $emailBody = $this->createMock('Oro\Bundle\EmailBundle\Entity\EmailBody');
            $emailBody->expects($this->once())
                ->method('getHasAttachments')
                ->willReturn(true);

            $attachments = $this->getAttachments($i + 1);
            $transformationCalls += $i + 1;

            $emailBody->expects($this->once())
                ->method('getAttachments')
                ->willReturn($attachments);

            $threadEmail = $this->createMock('Oro\Bundle\EmailBundle\Entity\Email');
            $threadEmail->expects($this->exactly($threadEmailCount))
                ->method('getEmailBody')
                ->willReturn($emailBody);

            $threadEmails[] = $threadEmail;
        }

        return [
            [
                'threadEmails' => $threadEmails,
                'transformationCalls' => $transformationCalls,
            ],
        ];
    }

    public function testGetScopeEntityAttachments()
    {
        $entity = $this->createMock('\stdClass');

        $oroAttachments = [];
        $size = 3;
        for ($i = 0; $i < $size; $i++) {
            $oroAttachments[] = $this->createMock('Oro\Bundle\AttachmentBundle\Entity\Attachment');
        }

        $this->attachmentProvider->expects($this->once())
            ->method('getEntityAttachments')
            ->with($entity)
            ->willReturn($oroAttachments);

        $this->emailAttachmentTransformer->expects($this->exactly($size))
            ->method('oroToModel');

        $result = $this->emailAttachmentProvider->getScopeEntityAttachments($entity);
        $this->assertTrue(is_array($result));
        $this->assertEquals($size, sizeof($result));
    }

    /**
     * @param int $count
     *
     * @return array
     */
    protected function getAttachments($count)
    {
        $attachments = [];
        for ($i = 0; $i < $count; $i++) {
            $attachments[] = $this->createMock('Oro\Bundle\EmailBundle\Entity\EmailAttachment');
        }

        return $attachments;
    }
}


text:
package org.eclipse.rdf4j.rio;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;

import org.eclipse.rdf4j.rio.helpers.ContextStatementCollector;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

public class RioTest {

	private static final InputStream testInputStream = new ByteArrayInputStream("test data".getBytes());

	private static final Reader testReader = new StringReader("test data");

	private static final RDFFormat TEST_FORMAT = new RDFFormat(
			"TestFormat", "text/test", StandardCharsets.UTF_8, "test", false, false, false
	);

	private RDFParser mockParser;

	@BeforeEach
	public void setUp() {
		mockParser = mock(RDFParser.class);
		RDFParserRegistry.getInstance().add(new RDFParserFactory() {
			@Override
			public RDFFormat getRDFFormat() {
				return TEST_FORMAT;
			}

			@Override
			public RDFParser getParser() {
				return mockParser;
			}
		});
	}

	@Test
	public void parseInputStream_DefaultSettings() throws Exception {
		Rio.parse(testInputStream, TEST_FORMAT);

		verify(mockParser).setRDFHandler(any(ContextStatementCollector.class));
		verify(mockParser).parse(testInputStream, null);
	}

	@Test
	public void parseInputStream_BaseURI() throws Exception {
		String baseURI = "test:baseURI";
		Rio.parse(testInputStream, baseURI, TEST_FORMAT);

		verify(mockParser).parse(testInputStream, baseURI);
	}

	@Test
	public void parseInputStream_CustomConfig() throws Exception {
		ParserConfig config = new ParserConfig();
		Rio.parse(testInputStream, TEST_FORMAT, config);

		verify(mockParser).setParserConfig(config);
		verify(mockParser).parse(testInputStream, null);
	}

	@Test
	public void parseReader_DefaultSettings() throws Exception {
		Rio.parse(testReader, TEST_FORMAT);

		verify(mockParser).setRDFHandler(any(ContextStatementCollector.class));
		verify(mockParser).parse(testReader, null);
	}

	@Test
	public void parseReader_CustomConfig() throws Exception {
		ParserConfig config = new ParserConfig();
		Rio.parse(testReader, TEST_FORMAT, config);

		verify(mockParser).setParserConfig(config);
		verify(mockParser).parse(testReader, null);
	}

	@Test
	public void createParser_existing() throws Exception {
		RDFParser parser = Rio.createParser(TEST_FORMAT);
		assertThat(parser).isEqualTo(mockParser);
	}

	public void createParser_unknown() throws Exception {
		RDFFormat unknownFormat = new RDFFormat("unknown", "test/unknown", StandardCharsets.UTF_8, "unknown", false,
				false,
				false);
		assertThatExceptionOfType(UnsupportedRDFormatException.class).isThrownBy(() -> Rio.createParser(unknownFormat));
	}
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Intent.Builder</title>
<meta name="date" content="2016-03-14">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.amazon.speech.slu

Class Intent.Builder

java.lang.Object

com.amazon.speech.slu.Intent.Builder

Enclosing class:

Intent

public static final class Intent.Builder
extends java.lang.Object

Builder used to construct a new Intent.

Method Summary

Methods

Modifier and Type
Method and Description

Intent
build()

Intent.Builder
withName(java.lang.String name)

Intent.Builder
withSlots(java.util.Map<java.lang.String,Slot> slots)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Method Detail

withName

public Intent.Builder withName(java.lang.String name)

withSlots

public Intent.Builder withSlots(java.util.Map<java.lang.String,Slot> slots)

build

public Intent build()

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { AdminMailComponent } from './admin-mail.component';

describe('AdminMailComponent', () => {
  let component: AdminMailComponent;
  let fixture: ComponentFixture<AdminMailComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ AdminMailComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(AdminMailComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});


text:
package vandy.mooc.video.android.model.services;

import vandy.mooc.video.android.model.mediator.VideoDataMediator;
import android.app.IntentService;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.Builder;
import android.support.v4.content.LocalBroadcastManager;

/**
 * Intent Service that runs in background and uploads the Video with a
 * given Id.  After the operation, it broadcasts the Intent to send
 * the result of the upload to the VideoListActivity.
 */
public class UploadVideoService
       extends IntentService {
    /**
     * Custom Action that will be used to send Broadcast to the
     * VideoListActivity.
     */
    public static final String ACTION_UPLOAD_SERVICE_RESPONSE =
                "vandy.mooc.services.UploadVideoService.RESPONSE";

    /**
     * It is used by Notification Manager to send Notifications.
     */
    private static final int NOTIFICATION_ID = 1;

    /**
     * VideoDataMediator mediates the communication between Video
     * Service and local storage in the Android device.
     */
    private VideoDataMediator mVideoMediator;

    /**
     * Manages the Notification displayed in System UI.
     */
    private NotificationManager mNotifyManager;

    /**
     * Builder used to build the Notification.
     */
    private Builder mBuilder;

    /**
     * Constructor for UploadVideoService.
     *
     * @param name
     */
    public UploadVideoService(String name) {
        super("UploadVideoService");
    }

    /**
     * Constructor for UploadVideoService.
     *
     * @param name
     */
    public UploadVideoService() {
        super("UploadVideoService");
    }

    /**
     * Factory method that makes the explicit intent another Activity
     * uses to call this Service.
     *
     * @param context
     * @param videoId
     * @return
     */
    public static Intent makeIntent(Context context,
                                    Uri videoUri) {
        return new Intent(context,
                          UploadVideoService.class)
                   .setData(videoUri);
    }

    /**
     * Hook method that is invoked on the worker thread with a request
     * to process. Only one Intent is processed at a time, but the
     * processing happens on a worker thread that runs independently
     * from other application logic.
     *
     * @param intent
     */
    @Override
    protected void onHandleIntent(Intent intent) {
        // Starts the Notification to show the progress of video
        // upload.
        startNotification();

        // Create VideoDataMediator that will mediate the communication
        // between Server and Android Storage.
        mVideoMediator =
            new VideoDataMediator();

        // Check if Video Upload is successful.
        finishNotification(mVideoMediator.uploadVideo(getApplicationContext(),
                                                   intent.getData()));

        // Send the Broadcast to VideoListActivity that the Video
        // Upload is completed.
        sendBroadcast();
    }

    /**
     * Send the Broadcast to Activity that the Video Upload is
     * completed.
     */
    private void sendBroadcast(){
        // Use a LocalBroadcastManager to restrict the scope of this
        // Intent to the VideoUploadClient application.
        LocalBroadcastManager.getInstance(this)
             .sendBroadcast(new Intent(ACTION_UPLOAD_SERVICE_RESPONSE)
                            .addCategory(Intent.CATEGORY_DEFAULT));
    }

    /**
     * Finish the Notification after the Video is Uploaded.
     *
     * @param status
     */
    private void finishNotification(String status) {
        // When the loop is finished, updates the notification.
        mBuilder.setContentTitle(status)
                // Removes the progress bar.
                .setProgress (0,
                              0,
                              false)
                .setSmallIcon(android.R.drawable.stat_sys_upload_done)
                .setContentText("")
                .setTicker(status);

        // Build the Notification with the given
        // Notification Id.
        mNotifyManager.notify(NOTIFICATION_ID,
                              mBuilder.build());
    }

    /**
     * Starts the Notification to show the progress of video upload.
     */
    private void startNotification() {
        // Gets access to the Android Notification Service.
        mNotifyManager = (NotificationManager)
            getSystemService(Context.NOTIFICATION_SERVICE);

        // Create the Notification and set a progress indicator for an
        // operation of indeterminate length.
        mBuilder = new NotificationCompat
                       .Builder(this)
                       .setContentTitle("Video Upload")
                       .setContentText("Upload in progress")
                       .setSmallIcon(android.R.drawable.stat_sys_upload)
                       .setTicker("Uploading video")
                       .setProgress(0,
                                    0,
                                    true);

        // Build and issue the notification.
        mNotifyManager.notify(NOTIFICATION_ID,
                              mBuilder.build());
    }
}


text:
<?php

namespace Tests\Controllers;

use App\Controllers\ZipController;
use Psr\Http\Message\ResponseInterface;
use Slim\Psr7\Request;
use Slim\Psr7\Response;
use Symfony\Component\Finder\Finder;
use Symfony\Contracts\Translation\TranslatorInterface;
use Tests\TestCase;

/** @covers \App\Controllers\ZipController */
class ZipControllerTest extends TestCase
{
    public function test_it_returns_a_successful_response_for_a_zip_request(): void
    {
        $controller = new ZipController(
            $this->config,
            $this->cache,
            new Finder,
            $this->container->get(TranslatorInterface::class)
        );

        $request = $this->createMock(Request::class);
        $request->method('getQueryParams')->willReturn(['zip' => 'subdir']);

        chdir($this->filePath('.'));
        $response = $controller($request, new Response);

        $this->assertInstanceOf(ResponseInterface::class, $response);
        $this->assertEquals(200, $response->getStatusCode());
        $this->assertEquals('application/zip', finfo_buffer(
            finfo_open(), (string) $response->getBody(), FILEINFO_MIME_TYPE
        ));
    }

    public function test_it_returns_a_404_error_when_not_found(): void
    {
        $controller = new ZipController(
            $this->config,
            $this->cache,
            new Finder,
            $this->container->get(TranslatorInterface::class)
        );

        $request = $this->createMock(Request::class);
        $request->method('getQueryParams')->willReturn(['zip' => '404']);

        chdir($this->filePath('.'));
        $response = $controller($request, new Response);

        $this->assertInstanceOf(ResponseInterface::class, $response);
        $this->assertEquals(404, $response->getStatusCode());
    }

    public function test_it_returns_a_404_error_when_disabled_via_config(): void
    {
        $this->container->set('zip_downloads', false);
        $controller = new ZipController(
            $this->config,
            $this->cache,
            new Finder,
            $this->container->get(TranslatorInterface::class)
        );

        $request = $this->createMock(Request::class);
        $request->method('getQueryParams')->willReturn(['zip' => 'subdir']);

        chdir($this->filePath('.'));
        $response = $controller($request, new Response);

        $this->assertInstanceOf(ResponseInterface::class, $response);
        $this->assertEquals(404, $response->getStatusCode());
    }
}


text:
<?php

require_once 'admin_structure.php';
require_once 'admin_dbquery.php';

class SystemManager_Admin {

    /**
     * @var SystemManager
     */
    public $manager;

    /**
     * @var Ab_Database
     */
    public $db;

    public function __construct(SystemManager $manager){
        $this->manager = $manager;
        $this->db = $manager->db;
    }

    public function IsAdminRole(){
        return $this->manager->IsAdminRole();
    }

    public function AJAX($d){
        switch ($d->do){
            case "coreConfig":
                return $this->CoreConfigToAJAX();
            case "coreConfigSave":
                return $this->CoreConfigSaveToAJAX($d->coreConfig);
            case "moduleList":
                return $this->ModuleListToAJAX();
        }
        return null;
    }

    public function ModuleListToAJAX(){
        if (!$this->IsAdminRole()){
            return 403;
        }
        Abricos::$modules->RegisterAllModule();
        $ret = new stdClass();
        $ret->moduleList = Abricos::$modules->list->ToAJAX();
        return $ret;
    }

    public function TemplateList(){
        if (!$this->IsAdminRole()){
            return null;
        }

        $rows = array();
        $dir = dir(CWD."/tt");
        while (false !== ($entry = $dir->read())){
            if ($entry == "." || $entry == ".." || empty($entry) || $entry == "_sys" || $entry == "_my"){
                continue;
            }
            if (!file_exists(CWD."/tt/".$entry."/main.html")){
                continue;
            }
            $rows[] = $entry;
        }

        return $rows;
    }

    public function CoreConfigToAJAX(){
        $config = $this->CoreConfig();
        if (empty($config)){
            return 403;
        }

        $ret = new stdClass();
        $ret->coreConfig = $config;
        return $ret;
    }

    public function CoreConfig(){
        if (!$this->IsAdminRole()){
            return null;
        }
        $phs = SystemModule::$instance->GetPhrases();

        $ret = new stdClass();
        $ret->site_name = $phs->Get('site_name')->value;
        $ret->site_title = $phs->Get('site_title')->value;
        $ret->admin_mail = $phs->Get('admin_mail')->value;
        $ret->meta_title = $phs->Get('meta_title')->value;
        $ret->meta_keys = $phs->Get('meta_keys')->value;
        $ret->meta_desc = $phs->Get('meta_desc')->value;
        $ret->style = $phs->Get('style')->value;
        $ret->styles = $this->TemplateList();

        return $ret;
    }

    public function CoreConfigSaveToAJAX($d){
        if (!$this->CoreConfigSave($d)){
            return 403;
        }
        return $this->CoreConfigToAJAX();
    }

    public function CoreConfigSave($d){
        if (!$this->IsAdminRole()){
            return false;
        }
        $d = array_to_object($d);

        $phs = SystemModule::$instance->GetPhrases();
        if (isset($d->site_name)){
            $phs->Set('site_name', $d->site_name);
        }
        if (isset($d->site_title)){
            $phs->Set('site_title', $d->site_title);
        }
        if (isset($d->admin_mail)){
            $phs->Set('admin_mail', $d->admin_mail);
        }
        if (isset($d->meta_title)){
            $phs->Set('meta_title', $d->meta_title);
        }
        if (isset($d->meta_keys)){
            $phs->Set('meta_keys', $d->meta_keys);
        }
        if (isset($d->meta_desc)){
            $phs->Set('meta_desc', $d->meta_desc);
        }
        if (isset($d->style)){
            $phs->Set('style', $d->style);
        }

        Abricos::$phrases->Save();

        return true;
    }
}


text:
package nz.co.senanque.workflow;

import java.util.Map;

import nz.co.senanque.process.instances.ComputeType;
import nz.co.senanque.workflow.instances.ProcessInstance;
import nz.co.senanque.workflowtest.instances.Order;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Roger Parkinson
 *
 */
public class OrderComputeClass implements ComputeType<Order> {

	private static final Logger log = LoggerFactory
			.getLogger(OrderComputeClass.class);
	public void execute(ProcessInstance processInstance, Order context, Map<String, String> map) {
		String abort = map.get("abort");
		log.debug(map.get("log"));
		if (abort != null && abort.equals("true")) {
			throw new RuntimeException("generated abort");
		}
	}

}


text:
console.log('BengDB plugin loaded');

var ENDPOINT = 'http://bengdb.beeldengeluid.nl/api/search?q=';

function parse() {
    console.log('Parsing page');

    var matches = ''.concat(
        '[ng-if="metadata.personen"] dd,',
        '[ng-if="metadata.makers"] dd'
    );

    function getTooltip(person, data) {
        var $el = $(''.concat(
            '',
            person + ';'
        ));

        var tt = '';

        if (data.item.image) {
            tt += '
';
        }

        tt += ''.concat(
            '
' + data.item.descriptions,
            ' (' + data.item.birthDeathDetails + ')
'
        );

        $el.tooltipster({
            content : $(tt),
            theme: 'tooltipster-light',
            maxWidth : 220
        });

        return $el;
    }

    function getLinkForPerson(person, cb) {
        var lookup = person.trim().toLowerCase();
        var url = ENDPOINT + encodeURIComponent(lookup);
        console.log(url);

        $.get(url, function(data) {
            console.log('Got data');
            if (data.error) {
                cb(false, person + ';');
            } else {
                var tooltip = getTooltip(person, data);
                cb(false, tooltip);
            }
        });
    }

    $(matches).each(function() {
        var $el = $(this);
        var people = $el.text().split(';');

        async.map(people, getLinkForPerson, function(err, results) {
            $el.html(results);
        });
    });
}

// Wait until 'ui-view="details" is loaded'
var tries = 5;

function goTry() {
    var isLoaded = !!$('[metadata="details.metadata"]').length;

    if (isLoaded) {
        parse();
    } else {
        tries--;

        if (tries > 0) {
            setTimeout(goTry, 500);
        }
    }
}

goTry();


text:
<?php
namespace app\models;
use Yii;
use yii\base\Model;
use app\models\User;

/**
 *
 */
class CreateUser extends Model
{
    public $login;
    public $password;
    public $email;
    public $status;

    public function rules()
    {
        return [
            [['login','password','email','status'],'required'],
            [['login','password','email','status'],'trim'],
            ['login', 'unique',  'targetClass' => '\app\models\User', 'message' => 'This login has already been taken.'],
            ['login', 'string', 'min' => 2, 'max' => 255],
            ['password', 'string', 'min' => 6, 'max' => 255],
            ['email', 'email'],
            ['email', 'unique', 'targetClass' => '\app\models\User', 'message' => 'This email address has already been taken.'],
            ['status', 'in', 'range' => ['moder', 'admin']],
        ];
    }

    public function createUser()
    {
        if ($this->validate()) {
            $user           = new User();
            $user->login    = $this->login;
            $user->email    = $this->email;
            $user->status   = User::STATUS_GUEST;
            $user->setPassword($this->password);
            $user->genereateToken();
            $user->generateAuthKey();
            return $user->save() ? $user : null;
        }
    }
}


text:
<?php
/**
 * Bootstrapper panel facade
 */

namespace Bootstrapper\Facades;

/**
 * Facade for the Panel class
 *
 * @package Bootstrapper\Facades
 */
class Panel extends BootstrapperFacade
{

    const PRIMARY = 'panel-primary';
    const SUCCESS = 'panel-success';
    const INFO = 'panel-info';
    const WARNING = 'panel-warning';
    const DANGER = 'panel-danger';
    const NORMAL = 'panel-default';

    /**
     * {@inheritdoc}
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return 'bootstrapper::panel';
    }
}


text:
TEST(CommonTests, PiShouldBeAroundTrueValue)
{
    auto piValue = fw::pi();
    EXPECT_TRUE(3.13 < piValue && piValue < 3.15);
}


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

namespace Thwip.Accounts.Data.Contracts
{
    public class SignupForm
    {
        public string Name { get; set; }
        public string Email { get; set; }
        public string Mobile { get; set; }
    }
}


text:
#ifndef __TEXTUREPREVIEW_H__
#define __TEXTUREPREVIEW_H__

#include "Preview.h"
#include <gl/glew.h>
#include <glm/glm.hpp>

class Texture;
class Shader;
class ShaderProgram;

/** @ingroup editor
 * @{
 */

/// Previews a texture.
class TexturePreview : public Preview {
	public:
		/// Create new texture preview.
		TexturePreview();

		/// Destructor.
		~TexturePreview();

		/// Set texture to preview.
		/**
		 * @param texture Texture to preview.
		 */
		void setTexture(Texture* texture);

		/// Render the texture.
		/**
		* @param width Width of the render context.
		* @param height Height of the render context.
		*/
		void render(int width, int height) const;

	private:
		void bindQuad();

		Texture* texture = nullptr;

		// Shaders
		Shader* vertexShader;
		Shader* fragmentShader;
		ShaderProgram* shaderProgram;

		// Full screen quad.
		static const glm::vec2 vertices[6];

		// Vertex buffer
		GLuint vertexBuffer;
		GLuint vertexAttribute;
		unsigned int vertexCount;
};

/** @} */

#endif


text:
package net.vvakame.sample.issue2;

import net.vvakame.util.jsonpullparser.annotation.JsonKey;
import net.vvakame.util.jsonpullparser.annotation.JsonModel;

/**
 * Parent 1 output, Child 0 output.
 * @author vvakame
 */
@JsonModel
public class Child0ValueP1 extends Parent1Value {

	@JsonKey(out = false)
	private int hoge;

	/**
	 * @return the hoge
	 * @category accessor
	 */
	public int getHoge() {
		return hoge;
	}

	/**
	 * @param hoge the hoge to set
	 * @category accessor
	 */
	public void setHoge(int hoge) {
		this.hoge = hoge;
	}
}


text:
import hashHistory from 'react-router/lib/hashHistory'

// ------------------------------------
// Constants
// ------------------------------------
export const LOCATION_CHANGE = 'LOCATION_CHANGE'

// ------------------------------------
// Actions
// ------------------------------------
export function locationChange (location = '/') {
  return {
    type    : LOCATION_CHANGE,
    payload : location
  }
}

// ------------------------------------
// Specialized Action Creator
// ------------------------------------
export const updateLocation = ({ dispatch }) => {
  return (nextLocation) => dispatch(locationChange(nextLocation))
}

// ------------------------------------
// Reducer
// ------------------------------------
// const initialState = browserHistory.getCurrentLocation()
const initialState = hashHistory.getCurrentLocation()

export default function locationReducer (state = initialState, action) {
  return action.type === LOCATION_CHANGE
    ? action.payload
    : state
}


text:
using System.Linq;
using System.Threading.Tasks;
using NUnit.Framework;
using SJP.Schematic.Core;
using SJP.Schematic.Tests.Utilities;

namespace SJP.Schematic.Oracle.Tests.Integration
{
    internal partial class OracleRelationalDatabaseTableProviderTests : OracleTest
    {
        [Test]
        public async Task PrimaryKey_WhenGivenTableWithNoPrimaryKey_ReturnsNull()
        {
            var table = await GetTableAsync("table_test_table_1").ConfigureAwait(false);

            Assert.That(table.PrimaryKey, OptionIs.None);
        }

        [Test]
        public async Task PrimaryKey_WhenGivenTableWithPrimaryKey_ReturnsCorrectKeyType()
        {
            var table = await GetTableAsync("table_test_table_2").ConfigureAwait(false);
            var keyType = table.PrimaryKey.UnwrapSome().KeyType;

            Assert.That(keyType, Is.EqualTo(DatabaseKeyType.Primary));
        }

        [Test]
        public async Task PrimaryKey_WhenGivenTableWithColumnAsPrimaryKey_ReturnsPrimaryKeyWithColumnOnly()
        {
            var table = await GetTableAsync("table_test_table_2").ConfigureAwait(false);
            var pk = table.PrimaryKey.UnwrapSome();
            var pkColumns = pk.Columns.ToList();

            Assert.Multiple(() =>
            {
                Assert.That(pkColumns, Has.Exactly(1).Items);
                Assert.That(pkColumns.Single().Name.LocalName, Is.EqualTo("TEST_COLUMN"));
            });
        }

        [Test]
        public async Task PrimaryKey_WhenGivenTableWithSingleColumnConstraintAsPrimaryKey_ReturnsPrimaryKeyWithColumnOnly()
        {
            var table = await GetTableAsync("table_test_table_3").ConfigureAwait(false);
            var pk = table.PrimaryKey.UnwrapSome();
            var pkColumns = pk.Columns.ToList();

            Assert.Multiple(() =>
            {
                Assert.That(pkColumns, Has.Exactly(1).Items);
                Assert.That(pkColumns.Single().Name.LocalName, Is.EqualTo("TEST_COLUMN"));
            });
        }

        [Test]
        public async Task PrimaryKey_WhenGivenTableWithSingleColumnConstraintAsPrimaryKey_ReturnsPrimaryKeyWithCorrectName()
        {
            var table = await GetTableAsync("table_test_table_3").ConfigureAwait(false);
            var pk = table.PrimaryKey.UnwrapSome();

            Assert.That(pk.Name.UnwrapSome().LocalName, Is.EqualTo("PK_TEST_TABLE_3"));
        }

        [Test]
        public async Task PrimaryKey_WhenGivenTableWithMultiColumnConstraintAsPrimaryKey_ReturnsPrimaryKeyWithColumnsInCorrectOrder()
        {
            var expectedColumnNames = new[] { "FIRST_NAME", "LAST_NAME", "MIDDLE_NAME" };

            var table = await GetTableAsync("table_test_table_4").ConfigureAwait(false);
            var pk = table.PrimaryKey.UnwrapSome();
            var pkColumns = pk.Columns.ToList();
            var pkColumnNames = pkColumns.Select(c => c.Name.LocalName).ToList();

            Assert.Multiple(() =>
            {
                Assert.That(pkColumns, Has.Exactly(3).Items);
                Assert.That(pkColumnNames, Is.EqualTo(expectedColumnNames));
            });
        }

        [Test]
        public async Task PrimaryKey_WhenGivenTableWithMultiColumnConstraintAsPrimaryKey_ReturnsPrimaryKeyWithCorrectName()
        {
            var table = await GetTableAsync("table_test_table_4").ConfigureAwait(false);
            var pk = table.PrimaryKey.UnwrapSome();

            Assert.That(pk.Name.UnwrapSome().LocalName, Is.EqualTo("PK_TEST_TABLE_4"));
        }
    }
}