text:
package com.glaf.core.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.glaf.core.cache.CacheFactory;
import com.glaf.core.domain.Database;
import com.glaf.core.domain.DatabaseAccess;
import com.glaf.core.domain.SysKey;
import com.glaf.core.domain.util.DatabaseAccessJsonFactory;
import com.glaf.core.id.IdGenerator;
import com.glaf.core.mapper.DatabaseAccessMapper;
import com.glaf.core.mapper.DatabaseMapper;
import com.glaf.core.query.DatabaseQuery;
import com.glaf.core.security.SecurityUtils;
import com.glaf.core.service.IDatabaseService;
import com.glaf.core.service.SysKeyService;
import com.glaf.core.util.UUID32;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service("databaseService")
@Transactional(readOnly = true)
public class DatabaseServiceImpl implements IDatabaseService {
	private final Logger logger = LoggerFactory.getLogger(getClass());

	private IdGenerator idGenerator;

	private SqlSessionTemplate sqlSessionTemplate;

	private DatabaseMapper databaseMapper;

	private DatabaseAccessMapper databaseAccessMapper;

	private SysKeyService sysKeyService;

	public DatabaseServiceImpl() {

	}

	public int count(DatabaseQuery query) {
		return databaseMapper.getDatabaseCount(query);
	}

	@Transactional
	public void createAccessor(long databaseId, String actorId) {
		String cacheKey = "sys_db_" + databaseId;
		CacheFactory.remove("database", cacheKey);
		cacheKey = "sys_dbaccess_" + databaseId;
		CacheFactory.remove("database", cacheKey);
		cacheKey = "sys_db_actor_" + actorId;
		CacheFactory.remove("database", cacheKey);
		DatabaseAccess model = new DatabaseAccess();
		model.setId(idGenerator.nextId("SYS_DATABASE_ACCESS"));
		model.setActorId(actorId);
		model.setDatabaseId(databaseId);
		databaseAccessMapper.insertDatabaseAccess(model);
	}

	@Transactional
	public void deleteAccessor(long databaseId, String actorId) {
		String cacheKey = "sys_db_" + databaseId;
		CacheFactory.remove("database", cacheKey);
		cacheKey = "sys_dbaccess_" + databaseId;
		CacheFactory.remove("database", cacheKey);
		cacheKey = "sys_db_actor_" + actorId;
		CacheFactory.remove("database", cacheKey);
		DatabaseAccess model = new DatabaseAccess();
		model.setActorId(actorId);
		model.setDatabaseId(databaseId);
		databaseAccessMapper.deleteAccessor(model);
	}

	@Transactional
	public void deleteById(long databaseId) {
		if (databaseId != 0) {
			Database database = this.getDatabase(databaseId);
			if (database.getRemoveFlag() == null || StringUtils.equalsIgnoreCase(database.getRemoveFlag(), "Y")) {
				String cacheKey = "sys_db_" + databaseId;
				CacheFactory.remove("database", cacheKey);
				cacheKey = "sys_dbaccess_" + databaseId;
				CacheFactory.remove("database", cacheKey);
				databaseAccessMapper.deleteDatabaseAccessByDatabaseId(databaseId);
				sysKeyService.deleteById("sys_database_" + database.getId());
				databaseMapper.deleteDatabaseById(databaseId);
			}
		}
	}

	@Transactional
	public void deleteByIds(List<Long> ids) {
		if (ids != null && !ids.isEmpty()) {
			for (Long databaseId : ids) {
				String cacheKey = "sys_db_" + databaseId;
				CacheFactory.remove("database", cacheKey);
				cacheKey = "sys_dbaccess_" + databaseId;
				CacheFactory.remove("database", cacheKey);
				databaseAccessMapper.deleteDatabaseAccessByDatabaseId(databaseId);
				sysKeyService.deleteById("sys_database_" + databaseId);
				databaseMapper.deleteDatabaseById(databaseId);
			}
		}
	}

	public List<DatabaseAccess> getAllDatabaseAccesses() {
		return databaseAccessMapper.getAllDatabaseAccesses();
	}

	private Database getDatabase(long databaseId) {
		if (databaseId == 0) {
			return null;
		}
		return databaseMapper.getDatabaseById(databaseId);
	}

	/**
	 * 获取某个数据库访问权限
	 *
	 * @return
	 */
	public List<DatabaseAccess> getDatabaseAccesses(long databaseId) {
		String cacheKey = "sys_dbaccess_" + databaseId;
		String text = CacheFactory.getString("database", cacheKey);
		if (StringUtils.isNotEmpty(text)) {
			try {
				JSONArray array = JSON.parseArray(text);
				return DatabaseAccessJsonFactory.arrayToList(array);
			} catch (Exception ignored) {
			}
		}
		List<DatabaseAccess> accesses = databaseAccessMapper.getDatabaseAccessesByDatabaseId(databaseId);
		if (accesses != null && !accesses.isEmpty()) {
			JSONArray array = DatabaseAccessJsonFactory.listToArray(accesses);
			CacheFactory.put("database", cacheKey, array.toJSONString());
		}
		return accesses;
	}

	/**
	 * 获取某个数据库访问用户
	 *
	 * @return
	 */
	public List<String> getDatabaseAccessors(long databaseId) {
		List<String> actorIds = new ArrayList<String>();
		List<DatabaseAccess> accesses = this.getDatabaseAccesses(databaseId);
		if (accesses != null && !accesses.isEmpty()) {
			for (DatabaseAccess access : accesses) {
				if (!actorIds.contains(access.getActorId())) {
					actorIds.add(access.getActorId());
				}
			}
		}
		return actorIds;
	}

	/**
	 * 根据编码获取一条记录
	 *
	 * @return
	 */
	public Database getDatabaseByCode(String code) {
		if (StringUtils.isEmpty(code)) {
			return null;
		}
		DatabaseQuery query = new DatabaseQuery();
		query.active("1");
		List<Database> list = databaseMapper.getDatabases(query);
		if (list != null && !list.isEmpty()) {
			for (Database database : list) {
				if (StringUtils.equals(database.getActive(), "1") && StringUtils.equals(code, database.getCode())) {
					List<DatabaseAccess> accesses = this.getDatabaseAccesses(database.getId());
					database.setAccesses(accesses);
					return database;
				}
			}
		}
		return null;
	}

	public Database getDatabaseById(long databaseId) {
		if (databaseId == 0) {
			return null;
		}
		Database database = databaseMapper.getDatabaseById(databaseId);
		if (database != null) {
			List<DatabaseAccess> accesses = databaseAccessMapper.getDatabaseAccessesByDatabaseId(databaseId);
			if (accesses != null && !accesses.isEmpty()) {
				for (DatabaseAccess access : accesses) {
					database.addAccessor(access.getActorId());
				}
			}
		}
		return database;
	}

	/**
	 * 根据mapping获取一条记录
	 *
	 * @return
	 */
	public Database getDatabaseByMapping(String mapping) {
		if (StringUtils.isEmpty(mapping)) {
			return null;
		}
		DatabaseQuery query = new DatabaseQuery();
		query.active("1");
		List<Database> list = databaseMapper.getDatabases(query);
		if (list != null && !list.isEmpty()) {
			for (Database database : list) {
				if (StringUtils.equals(database.getActive(), "1")
						&& StringUtils.equals(mapping, database.getMapping())) {
					List<DatabaseAccess> accesses = this.getDatabaseAccesses(database.getId());
					database.setAccesses(accesses);
					return database;
				}
			}
		}
		return null;
	}

	/**
	 * 根据name获取一条记录
	 *
	 * @return
	 */
	public Database getDatabaseByName(String name) {
		if (StringUtils.isEmpty(name)) {
			return null;
		}
		DatabaseQuery query = new DatabaseQuery();
		query.active("1");
		List<Database> list = databaseMapper.getDatabases(query);
		if (list != null && !list.isEmpty()) {
			for (Database database : list) {
				if (StringUtils.equals(database.getActive(), "1") && StringUtils.equals(name, database.getName())) {
					List<DatabaseAccess> accesses = this.getDatabaseAccesses(database.getId());
					database.setAccesses(accesses);
					return database;
				}
			}
		}
		return null;
	}

	/**
	 * 根据查询参数获取记录总数
	 *
	 * @return
	 */
	public int getDatabaseCountByQueryCriteria(DatabaseQuery query) {
		return databaseMapper.getDatabaseCount(query);
	}

	public List<Database> getDatabases() {
		List<Database> databases = new ArrayList<Database>();
		DatabaseQuery query = new DatabaseQuery();
		List<Database> list = databaseMapper.getDatabases(query);
		if (list != null && !list.isEmpty()) {
			for (Database database : list) {
				if (StringUtils.equals(database.getActive(), "1")) {
					List<DatabaseAccess> accesses = this.getDatabaseAccesses(database.getId());
					database.setAccesses(accesses);
					if (accesses != null && !accesses.isEmpty()) {
						for (DatabaseAccess access : accesses) {
							database.addAccessor(access.getActorId());
						}
					}
					databases.add(database);
				}
			}
		}
		logger.debug("databases size:" + databases.size());
		if (!databases.isEmpty()) {
			Collections.sort(databases);
		}
		return databases;
	}

	/**
	 * 根据查询参数获取记录列表
	 *
	 * @return
	 */
	public List<Database> getDatabases(String actorId) {
		List<Database> databases = new ArrayList<Database>();
		DatabaseQuery query = new DatabaseQuery();
		query.setCreateBy(actorId);
		List<Database> list = databaseMapper.getDatabases(query);
		if (list != null && !list.isEmpty()) {
			for (Database database : list) {
				if (StringUtils.equals(database.getActive(), "1")) {
					List<DatabaseAccess> accesses = this.getDatabaseAccesses(database.getId());
					database.setAccesses(accesses);
					if (accesses != null && !accesses.isEmpty()) {
						for (DatabaseAccess access : accesses) {
							database.addAccessor(access.getActorId());
						}
					}
					databases.add(database);
				}
			}
		}

		List<Database> list2 = databaseMapper.getDatabasesByActorId(actorId);
		if (list2 != null && !list2.isEmpty()) {
			databases.addAll(list2);
		}

		return databases;
	}

	/**
	 * 根据查询参数获取一页的数据
	 *
	 * @return
	 */
	public List<Database> getDatabasesByQueryCriteria(int start, int pageSize, DatabaseQuery query) {
		RowBounds rowBounds = new RowBounds(start, pageSize);
		return sqlSessionTemplate.selectList("getDatabases", query, rowBounds);
	}

	/**
	 * 保存一条数据库信息
	 *
	 * @return
	 */
	@Transactional
	public void insert(Database database) {
		database.setId(idGenerator.nextId("SYS_DATABASE"));
		database.setName("db_" + database.getId());
		database.setCode("db_" + database.getId());
		database.setToken(UUID32.getUUID() + UUID32.getUUID());
		database.setCreateTime(new Date());
		database.setActive("1");

		if (database.getIntToken() < 1000 || database.getIntToken() > 9999) {
			database.setIntToken(Math.abs(1000 + new Random().nextInt(8999)));
		}

		databaseMapper.insertDatabase(database);
	}

	public List<Database> list(DatabaseQuery query) {
		List<Database> list = databaseMapper.getDatabases(query);
		for (Database database : list) {
			if (StringUtils.equals(database.getActive(), "1")) {
				List<DatabaseAccess> accesses = this.getDatabaseAccesses(database.getId());
				database.setAccesses(accesses);
				if (accesses != null && !accesses.isEmpty()) {
					for (DatabaseAccess access : accesses) {
						database.addAccessor(access.getActorId());
					}
				}
			}
		}
		return list;
	}

	@Transactional
	public void save(Database database) {
		String password = database.getPassword();
		if (database.getId() == 0) {
			SysKey sysKey = new SysKey();
			sysKey.setCreateBy(database.getCreateBy());
			sysKey.setCreateDate(new Date());
			sysKey.setType("DATABASE");

			if (!"88888888".equals(password) && password.length() != 32) {
				String key = SecurityUtils.genKey();
				String pass = SecurityUtils.encode(key, password);
				database.setKey(key);
				database.setPassword(pass);
				sysKey.setData(Base64.encodeBase64(key.getBytes()));
			}

			database.setId(idGenerator.nextId("SYS_DATABASE"));
			database.setName("db_" + database.getId());
			database.setCode("db_" + database.getId());
			database.setToken(UUID32.getUUID() + UUID32.getUUID());
			database.setCreateTime(new Date());
			database.setActive("1");

			if (database.getIntToken() < 1000 || database.getIntToken() > 9999) {
				database.setIntToken(Math.abs(1000 + new Random().nextInt(8999)));
			}

			sysKey.setId("sys_database_" + database.getId());

			if (StringUtils.isEmpty(database.getQueueName())) {
				String queueName = database.getSysId();
				if (StringUtils.isEmpty(queueName)) {
					// queueName = database.getHost() + "_" +
					// database.getDbname();
					// queueName = StringTools.replace(queueName, ".", "_");
					queueName = database.getSysId();
					// queueName=queueName.toLowerCase();
				}
				database.setQueueName(queueName);
			}

			databaseMapper.insertDatabase(database);

			sysKey.setName(database.getName());
			sysKey.setTitle(database.getTitle());
			sysKeyService.save(sysKey);

		} else {
			Database model = this.getDatabase(database.getId());

			if (model.getIntToken() != database.getIntToken()) {
				model.setToken(UUID32.getUUID() + UUID32.getUUID());
			}
			model.setId(database.getId());
			model.setTitle(database.getTitle());
			model.setProviderClass(database.getProviderClass());
			model.setRemoteUrl(database.getRemoteUrl());
			model.setLevel(database.getLevel());
			model.setPriority(database.getPriority());
			model.setOperation(database.getOperation());
			model.setHost(database.getHost());
			model.setPort(database.getPort());
			model.setUser(database.getUser());
			model.setActive(database.getActive());
			model.setParentId(database.getParentId());
			model.setMapping(database.getMapping());
			model.setRunType(database.getRunType());
			model.setUseType(database.getUseType());
			model.setSection(database.getSection());
			model.setCatalog(database.getCatalog());
			model.setInfoServer(database.getInfoServer());
			model.setLoginAs(database.getLoginAs());
			model.setLoginUrl(database.getLoginUrl());
			model.setTicket(database.getTicket());
			model.setProgramId(database.getProgramId());
			model.setProgramName(database.getProgramName());
			model.setUserNameKey(database.getUserNameKey());
			model.setServerId(database.getServerId());
			model.setSysId(database.getSysId());
			model.setQueueName(database.getQueueName());
			model.setDiscriminator(database.getDiscriminator());
			model.setIntToken(database.getIntToken());
			model.setToken(database.getToken());
			model.setSort(database.getSort());
			model.setUpdateTime(new Date());

			if (model.getIntToken() < 1000 || model.getIntToken() > 9999) {
				model.setIntToken(Math.abs(1000 + new Random().nextInt(8999)));
				model.setToken(UUID32.getUUID() + UUID32.getUUID());
			}

			SysKey sysKey = new SysKey();
			sysKey.setId("sys_database_" + database.getId());
			sysKey.setCreateBy(database.getCreateBy());
			sysKey.setCreateDate(new Date());
			sysKey.setName(database.getName());
			sysKey.setTitle(database.getTitle());
			sysKey.setType("DATABASE");

			if (!"88888888".equals(password) && password.length() != 32) {
				String key = SecurityUtils.genKey();
				String pass = SecurityUtils.encode(key, password);
				model.setKey(key);
				model.setPassword(pass);
				model.setVerify("N");
				sysKey.setData(Base64.encodeBase64(key.getBytes()));
			}

			if (!StringUtils.equals(model.getDbname(), database.getDbname())) {
				model.setVerify("N");
			}
			if (!StringUtils.equals(model.getHost(), database.getHost())) {
				model.setVerify("N");
			}
			if (!StringUtils.equals(model.getUser(), database.getUser())) {
				model.setVerify("N");
			}
			/**
			 * 只有没有初始化时可以更新库名及表名
			 */
			if (!StringUtils.equals(model.getInitFlag(), "Y")) {
				model.setDbname(database.getDbname());
			}

			if (StringUtils.isEmpty(model.getToken())) {
				model.setToken(UUID32.getUUID() + UUID32.getUUID());
			}

			if (StringUtils.isEmpty(model.getQueueName())) {
				// String queueName = model.getHost() + "_" + model.getDbname();
				// queueName = StringTools.replace(queueName, ".", "_");
				// model.setQueueName(queueName.toLowerCase());
				String queueName = model.getSysId();
				model.setQueueName(queueName);
			}

			databaseMapper.updateDatabase(model);

			sysKeyService.save(sysKey);

			String cacheKey = "sys_db_" + model.getId();
			CacheFactory.remove("database", cacheKey);

			if (model.getCode() != null) {
				cacheKey = "sys_db_" + model.getCode();
				CacheFactory.remove("database", cacheKey);
			}

			if (model.getName() != null) {
				cacheKey = "sys_db_" + model.getName();
				CacheFactory.remove("database", cacheKey);
			}

			if (model.getMapping() != null) {
				cacheKey = "sys_db_" + model.getMapping();
				CacheFactory.remove("database", cacheKey);
			}

			cacheKey = "sys_dbaccess_" + model.getId();
			CacheFactory.remove("database", cacheKey);
		}

		databaseAccessMapper.deleteDatabaseAccessByDatabaseId(database.getId());
		if (database.getActorIds() != null && database.getActorIds().isEmpty()) {
			for (String actorId : database.getActorIds()) {
				DatabaseAccess access = new DatabaseAccess();
				access.setId(idGenerator.nextId("SYS_DATABASE_ACCESS"));
				access.setActorId(actorId);
				access.setDatabaseId(database.getId());
				databaseAccessMapper.insertDatabaseAccess(access);
			}
		}
	}

	/**
	 * 保存数据库访问者
	 *
	 * @return
	 */
	@Transactional
	public void saveAccessors(long databaseId, Collection<String> accessors) {
		databaseAccessMapper.deleteDatabaseAccessByDatabaseId(databaseId);
		for (String actorId : accessors) {
			String cacheKey = "sys_db_" + databaseId;
			CacheFactory.remove("database", cacheKey);
			cacheKey = "sys_dbaccess_" + databaseId;
			CacheFactory.remove("database", cacheKey);
			cacheKey = "sys_db_actor_" + actorId;
			CacheFactory.remove("database", cacheKey);
			DatabaseAccess access = new DatabaseAccess();
			access.setId(idGenerator.nextId("SYS_DATABASE_ACCESS"));
			access.setActorId(actorId);
			access.setDatabaseId(databaseId);
			databaseAccessMapper.insertDatabaseAccess(access);
		}
	}

	/**
	 * 保存数据库访问者
	 *
	 * @return
	 */
	@Transactional
	public void saveAccessors(String accessor, Collection<Long> databaseIds) {
		databaseAccessMapper.deleteDatabaseAccessByActorId(accessor);
		for (Long databaseId : databaseIds) {
			String cacheKey = "sys_db_" + databaseId;
			CacheFactory.remove("database", cacheKey);
			cacheKey = "sys_dbaccess_" + databaseId;
			CacheFactory.remove("database", cacheKey);
			cacheKey = "sys_db_actor_" + accessor;
			CacheFactory.remove("database", cacheKey);
			DatabaseAccess access = new DatabaseAccess();
			access.setId(idGenerator.nextId("SYS_DATABASE_ACCESS"));
			access.setActorId(accessor);
			access.setDatabaseId(databaseId);
			databaseAccessMapper.insertDatabaseAccess(access);
		}
	}

	@javax.annotation.Resource
	public void setDatabaseAccessMapper(DatabaseAccessMapper databaseAccessMapper) {
		this.databaseAccessMapper = databaseAccessMapper;
	}

	@javax.annotation.Resource
	public void setDatabaseMapper(DatabaseMapper databaseMapper) {
		this.databaseMapper = databaseMapper;
	}

	@javax.annotation.Resource
	public void setIdGenerator(IdGenerator idGenerator) {
		this.idGenerator = idGenerator;
	}

	@javax.annotation.Resource
	public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
		this.sqlSessionTemplate = sqlSessionTemplate;
	}

	@javax.annotation.Resource
	public void setSysKeyService(SysKeyService sysKeyService) {
		this.sysKeyService = sysKeyService;
	}

	@Transactional
	public void update(Database database) {
		String cacheKey = "sys_db_" + database.getId();
		CacheFactory.remove("database", cacheKey);
		if (database.getCode() != null) {
			cacheKey = "sys_db_" + database.getCode();
			CacheFactory.remove("database", cacheKey);
		}
		if (database.getName() != null) {
			cacheKey = "sys_db_" + database.getName();
			CacheFactory.remove("database", cacheKey);
		}
		if (database.getMapping() != null) {
			cacheKey = "sys_db_" + database.getMapping();
			CacheFactory.remove("database", cacheKey);
		}

		cacheKey = "sys_dbaccess_" + database.getId();
		CacheFactory.remove("database", cacheKey);
		Database model = this.getDatabase(database.getId());

		if (model.getIntToken() != database.getIntToken()) {
			model.setToken(UUID32.getUUID() + UUID32.getUUID());
		}

		model.setActive(database.getActive());
		model.setVerify(database.getVerify());
		model.setInitFlag(database.getInitFlag());

		if (model.getIntToken() < 1000 || model.getIntToken() > 9999) {
			model.setIntToken(Math.abs(1000 + new Random().nextInt(8999)));
			model.setToken(UUID32.getUUID() + UUID32.getUUID());
		}

		if (StringUtils.isEmpty(model.getToken())) {
			model.setToken(UUID32.getUUID() + UUID32.getUUID());
		}

		databaseMapper.updateDatabase(model);
	}

	@Transactional
	public void verify(Database database) {
		Database model = this.getDatabase(database.getId());
		model.setActive(database.getActive());
		model.setVerify(database.getVerify());
		model.setInitFlag(database.getInitFlag());
		model.setUpdateBy(database.getUpdateBy());
		model.setUpdateTime(new Date());
		databaseMapper.verifyDatabase(model);
	}

	public Database getDatabaseBySysId(String sysId) {
		if (StringUtils.isEmpty(sysId)) {
			return null;
		}
		return databaseMapper.getDatabaseBySysId(sysId);
	}

}


text:
package main

import (
	"html/template"
	"log"
	"net/http"
	"os"
	"path/filepath"
)

var templates *template.Template

// custom template delimiters since the Go default delimiters clash
// with Angular's default.
var templateDelims = []string{"{{%", "%}}"}

func init() {
	// initialize the templates,
	// couldn't have used http://golang.org/pkg/html/template/#ParseGlob
	// since we have custom delimiters.
	basePath := "resources/templates/"
	err := filepath.Walk(basePath, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		// don't process folders themselves
		if info.IsDir() {
			return nil
		}
		templateName := path[len(basePath):]
		if templates == nil {
			templates = template.New(templateName)
			templates.Delims(templateDelims[0], templateDelims[1])
			_, err = templates.ParseFiles(path)
		} else {
			_, err = templates.New(templateName).ParseFiles(path)
		}
		log.Printf("Processed template %s\n", templateName)
		return err
	})
	if err != nil {
		log.Fatal(err)
	}
}

func main() {
	// serve static assets showing how to strip/change the path.
	http.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir("resources/images"))))
	http.Handle("/js/", http.StripPrefix("/js/", http.FileServer(http.Dir("resources/javascripts"))))
	http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("resources/stylesheets"))))
	// home page handler, defined in handlers.go
	http.HandleFunc("/", homeHandler)
	// start the server on port 1313
	// go to http://localhost:1313 to see the rendered content.
	http.ListenAndServe(":1313", nil)
}

redpajama_set_name: RedPajamaGithub


text:
package com.anji_ahni.nn.activationfunction;

/**
 * Linear activation function.
 *
 * @author Philip Tucker
 */
public class LinearActivationFunction implements ActivationFunction {

	/**
	 * identifying string
	 */
	public final static String NAME = "linear";

	/**
	 * @see Object#toString()
	 */
	public String toString() {
		return NAME;
	}

	/**
	 * This class should only be accessd via ActivationFunctionFactory.
	 */
	LinearActivationFunction() {
		// no-op
	}

	/**
	 * Return input with no transformation.
	 *
	 * @see com.anji_ahni.nn.activationfunction.ActivationFunction#apply(double)
	 */
	public double apply(double input) {
		return input;
	}

	/**
	 * @see com.anji_ahni.nn.activationfunction.ActivationFunction#getMaxValue()
	 */
	public double getMaxValue() {
		return Float.MAX_VALUE;
	}

	/**
	 * @see com.anji_ahni.nn.activationfunction.ActivationFunction#getMinValue()
	 */
	public double getMinValue() {
		return -Float.MAX_VALUE;
	}

	/**
	 * @see com.anji_ahni.nn.activationfunction.ActivationFunction#cost()
	 */
	public long cost() {
		return 42;
	}
}


text:
require 'minitest/autorun'
require 'minitest/test'
require 'minitest/unit'
require 'minitest/pride'
include MiniTest::Assertions
require File.expand_path('../../lib/passivedns/client.rb', __FILE__)


text:
#ifndef WebExternalPopupMenuClient_h
#define WebExternalPopupMenuClient_h

namespace WebKit {

class WebExternalPopupMenuClient {
public:
    // Should be called when the currently selected item in the popup menu
    // changed. Can be -1 if there is no selection.
    virtual void didChangeSelection(int index) = 0;

    // Should be called when an index has been accepted.
    // Note that it is not safe to access this WebExternalPopupClientMenu after
    // this has been called as it might not be valid anymore.
    virtual void didAcceptIndex(int index) = 0;

    // Should be called when the popup menu was discarded (closed without a
    // selection.
    // Note that it is not safe to access this WebExternalPopupClientMenu after
    // this has been called as it might not be valid anymore.
    virtual void didCancel() = 0;
};

} // namespace WebKit

#endif // WebExternalPopupMenuClient_h


text:
from __future__ import division
from __future__ import print_function
import pandas as pd
import numpy as np
import string

class Validation(object):
    """

    Parameters
    ----------
    shots : str, optional
        Path to list of test shots. When provided, submission should only
        provide labels for these very shots.
    videos : str, optional
        Path to list of videos. When provided, evidence should only be coming
        from these very videos.
    """

    def __init__(self, shots=None, videos=None):
        super(Validation, self).__init__()
        self.shots = shots
        if self.shots:
            self.shots_ = self._load_shots(self.shots)
        self.videos = videos
        if self.videos:
            self.videos_ = self._load_videos(self.videos)

    def _load_shots(self, path):
        names = ['corpus_id', 'video_id', 'shot_id', 'start_time', 'end_time']
        dtype = {'corpus_id': str, 'video_id': str, 'shot_id': str}
        shots = pd.read_table(path, delim_whitespace=True,
                              header=None, names=names, dtype=dtype)
        shots = set((c, v, s) for _, (c, v, s, _, _) in shots.iterrows())
        return shots

    def _load_videos(self, path):
        names = ['corpus_id', 'video_id']
        dtype = {'corpus_id': str, 'video_id': str}
        videos = pd.read_table(path, delim_whitespace=True,
                               header=None, names=names, dtype=dtype)
        videos = set((c, v) for _, (c, v) in videos.iterrows())
        return videos

    def _load_submission(self, fp):

        names = ['corpus_id', 'video_id', 'shot_id',
                 'person_name', 'confidence']
        dtype = {'corpus_id': str, 'video_id': str, 'shot_id': str,
                 'person_name': str, 'confidence': np.float32}

        try:
            submission = pd.read_table(fp, delim_whitespace=True,
                                       header=None, names=names,
                                       dtype=dtype)
        except Exception as e:
            # TODO
            raise e

        return submission

    def _load_evidence(self, fp):

        names = ['person_name',
                 'corpus_id', 'video_id',
                 'modality', 'timestamp']
        dtype = {'person_name': str,
                 'corpus_id': str, 'video_id': str,
                 'modality': str, 'timestamp': np.float32}

        try:
            evidence = pd.read_table(fp, delim_whitespace=True,
                                     header=None, names=names,
                                     dtype=dtype)
        except Exception as e:
            # TODO
            raise e

        return evidence

    ALLOWED_CHARACTERS = set(string.ascii_lowercase + '_')

    def __submission_person_names(self, submission):

        person_names = set(submission['person_name'].unique())
        for person_name in person_names:
            if not set(person_name).issubset(self.ALLOWED_CHARACTERS):
                MESSAGE = 'Invalid person name ({person_name})'
                raise ValueError(MESSAGE.format(person_name=person_name))
        return True

    def __submission_shots(self, submission):

        shots = set((c, v, s) for _, (c, v, s, _, _) in submission.iterrows())

        invalid_shots = shots - self.shots_
        if invalid_shots:
            c, v, s = invalid_shots.pop()
            MESSAGE = 'Invalid shot ({corpus_id} {video_id} {shot_id})'
            message = MESSAGE.format(corpus_id=c, video_id=v, shot_id=s)
            raise ValueError(message)

        return True

    def __submission_confidence(self, submission):
        confidence = submission['confidence']

        not_finite = np.where(~np.isfinite(confidence))[0]
        if len(not_finite):
            MESSAGE = 'Incorrect confidence in submission at line {line:d}'
            raise ValueError(MESSAGE.format(line=not_finite[0]+1))

        return True

    def __evidence_videos(self, evidence):
        videos = set((c, v) for _, (_, c, v, _, _) in evidence.iterrows())
        invalid_videos = videos - self.videos_
        if invalid_videos:
            c, v = invalid_videos.pop()
            MESSAGE = 'Invalid video ({corpus_id} {video_id}) in evidence.'
            message = MESSAGE.format(corpus_id=c, video_id=v)
            raise ValueError(message)

        return True

    def __evidence_person_names(self, submission, evidence):

        duplicated = evidence.duplicated('person_name')
        if any(duplicated):
            person_name = set(evidence[duplicated]['person_name']).pop()
            MESSAGE = 'Duplicate person name in evidence ({person_name})'
            raise ValueError(MESSAGE.format(person_name=person_name))

        submission_person_names = set(submission['person_name'].unique())
        evidence_person_names = set(evidence['person_name'].unique())

        extra = evidence_person_names - submission_person_names
        if extra:
            person_name = extra.pop()
            MESSAGE = 'Extra person name in evidence ({person_name})'
            raise ValueError(MESSAGE.format(person_name=person_name))

        missing = submission_person_names - evidence_person_names
        if missing:
            person_name = missing.pop()
            MESSAGE = 'Missing person name in evidence ({person_name})'
            raise ValueError(MESSAGE.format(person_name=person_name))

        return True

    def __evidence_modalities(self, evidence):
        modalities = set(evidence['modality'].unique())
        if not modalities.issubset({'written', 'pronounced'}):
            modality = (modalities - {'written', 'pronounced'}).pop()
            MESSAGE = 'Incorrect modality in evidence ({modality})'
            raise ValueError(MESSAGE.format(modality=modality))

    def __evidence_timestamps(self, evidence):
        timestamps = evidence['timestamp']

        not_finite = np.where(~np.isfinite(timestamps))[0]
        if len(not_finite):
            MESSAGE = 'Incorrect timestamp in evidence at line {line:d}'
            raise ValueError(MESSAGE.format(line=not_finite[0]+1))

        negative = np.where(timestamps < 0.)[0]
        if len(negative):
            MESSAGE = 'Negative timestamp in evidence at line {line:d}'
            raise ValueError(MESSAGE.format(line=negative[0]+1))

        return True

    def __call__(self, fp_submission, fp_evidence=None):

        try:
            submission = self._load_submission(fp_submission)
        except ValueError as e:
            raise e

        # validate person names
        self.__submission_person_names(submission)

        # validate shots
        if self.shots:
            self.__submission_shots(submission)

        # validate confidence
        self.__submission_confidence(submission)

        if fp_evidence:

            try:
                evidence = self._load_evidence(fp_evidence)
            except ValueError as e:
                raise e

            # validate videos
            if self.videos:
                self.__evidence_videos(evidence)

            # validate timestamps
            self.__evidence_timestamps(evidence)

            # validate evidence person names
            self.__evidence_person_names(submission, evidence)

            # validate evidence modality
            self.__evidence_modalities(evidence)

        return True


text:
dojo.provide("bespin.syntax.simple.arduino");

/**
 * Tracks syntax highlighting data on a per-line basis.
 * This is a quick-and-dirty implementation that supports five basic highlights:
 * keywords, punctuation, strings, comments, and "everything else", all lumped
 * into one last bucket.
 */
bespin.syntax.simple.ArduinoConstants = {
    C_STYLE_COMMENT: "c-comment",
    LINE_COMMENT: "comment",
    STRING: "string",
    KEYWORD: "keyword",
    PUNCTUATION: "punctuation",
    OTHER: "plain"
};

/**
 * Module for syntax highlighting Arduino PDE files.
 */
dojo.declare("bespin.syntax.simple.Arduino", null, {
    keywords: 'HIGH LOW INPUT OUTPUT SERIAL DISPLAY DEC BIN HEX OCT BYTE PI ' +
    'HALF_PI TWO_PI LSBFIRST MSBFIRST CHANGE FALLING RISING DEFAULT EXTERNAL INTERAL ' +
    'boolean  byte case char class default  do double else false float for if ' +
    'int long new null private  protected public return short signed static switch ' +
    'this throw try true unsigned void while word abs acos asin atan atan2 ceil ' +
    'constrain cos degrees exp floor log map max min radians  random randomSeed ' +
    'round sin sq sqrt tan bitRead bitWrite bitSet bitClear bit highByte lowByte ' +
    'analogReference analogRead analogWrite attachInterrupt detachInterrupt delay ' +
    'delayMicroseconds digitalWrite digitalRead interrupts millis micros ' +
    'noInterrupts pinMode pulseIn shiftOut Serial begin read print println available ' +
    'flush setup loop'.split(" "),

    punctuation: '{ } > < / + - % * . , ; ( ) ? : = " \''.split(" "),

    highlight: function(line, meta) {
        if (!meta) meta = {};

        // aliasing the constants for shorter reference ;-)
        var K = bespin.syntax.ArduinoConstants;

        // contains the individual style types as keys, with array of start/stop
        // positions as value
        var regions = {};

        // current state, maintained as we parse through each character in the
        // line; values at any time should be consistent
        var currentStyle = (meta.inMultilineComment) ? K.C_STYLE_COMMENT : undefined;
        // should always have a start property for a non-blank buffer
        var currentRegion = {};
        var buffer = "";

        // these properties are related to the parser state above but are special cases
        // the character used to start the current string
        var stringChar = "";
        var multiline = meta.inMultilineComment;

        for (var i = 0; i < line.length; i++) {
            var c = line.charAt(i);

            // check if we're in a comment and whether this character ends the comment
            if (currentStyle == K.C_STYLE_COMMENT) {
                // has the c-style comment just ended?
                if (c == "/" && /\*$/.test(buffer)) {
                    currentRegion.stop = i + 1;
                    this.addRegion(regions, currentStyle, currentRegion);
                    currentRegion = {};
                    currentStyle = undefined;
                    multiline = false;
                    buffer = "";
                } else {
                    if (buffer == "") currentRegion = { start: i };
                    buffer += c;
                }

                continue;
            }

            if (this.isWhiteSpaceOrPunctuation(c)) {
                // check if we're in a string
                if (currentStyle == K.STRING) {
                    // if this is not an unescaped end quote (either a single
                    // quote or double quote to match how the string started)
                    // then keep going
                    if (!(c == stringChar && !/\\$/.test(buffer))) {
                        if (buffer == "") currentRegion = { start: i };
                        buffer += c;
                        continue;
                    }
                }

                // if the buffer is full, add it to the regions
                if (buffer != "") {
                    currentRegion.stop = i;

                    // if this is a string, we're all set to add it; if not,
                    // figure out if its a keyword
                    if (currentStyle != K.STRING) {
                        if (this.keywords.indexOf(buffer) != -1) {
                            // the buffer contains a keyword
                            currentStyle = K.KEYWORD;
                        } else {
                            currentStyle = K.OTHER;
                        }
                    }
                    this.addRegion(regions, currentStyle, currentRegion);
                    currentRegion = {};
                    stringChar = "";
                    buffer = "";
                    // I don't clear the current style here so I can check if it
                    // was a string below
                }

                if (this.isPunctuation(c)) {
                    if (c == "*" && i > 0 && (line.charAt(i - 1) == "/")) {
                        // Remove the previous region in the punctuation bucket,
                        // which is a forward slash
                        regions[K.PUNCTUATION].pop();

                        // We are in a c-style comment
                        multiline = true;
                        currentStyle = K.C_STYLE_COMMENT;
                        currentRegion = { start: i - 1 };
                        buffer = "/*";
                        continue;
                    }

                    // Check for a line comment; this ends the parsing for the
                    // rest of the line
                    if (c == '/' && i > 0 && (line.charAt(i - 1) == '/')) {
                        currentRegion = { start: i - 1, stop: line.length };
                        currentStyle = K.LINE_COMMENT;
                        this.addRegion(regions, currentStyle, currentRegion);
                        buffer = "";
                        currentStyle = undefined;
                        currentRegion = {};
                        // once we get a line comment, we're done!
                        break;
                    }

                    // add an ad-hoc region for just this one punctuation character
                    this.addRegion(regions, K.PUNCTUATION, { start: i, stop: i + 1 });
                }

                // find out if the current quote is the end or the beginning of the string
                if ((c == "'" || c == '"') && (currentStyle != K.STRING)) {
                    currentStyle = K.STRING;
                    stringChar = c;
                } else {
                    currentStyle = undefined;
                }

                continue;
            }

            if (buffer == "") currentRegion = { start: i };
            buffer += c;
        }

        // check for a trailing character inside of a string or a comment
        if (buffer != "") {
            if (!currentStyle) currentStyle = K.OTHER;
            currentRegion.stop = line.length;
            this.addRegion(regions, currentStyle, currentRegion);
        }

        return { regions: regions, meta: { inMultilineComment: multiline } };
    },

    addRegion: function(regions, type, data) {
        if (!regions[type]) regions[type] = [];
        regions[type].push(data);
    },

    isWhiteSpaceOrPunctuation: function(ch) {
        return this.isPunctuation(ch) || this.isWhiteSpace(ch);
    },

    isPunctuation: function(ch) {
        return this.punctuation.indexOf(ch) != -1;
    },

    isWhiteSpace: function(ch) {
        return ch == " ";
    }
});


text:
const { createNote } = require('../createNote.note.repository');
const { getNotes } = require('../getNotes.note.repository');
const bootstrap = require('../../../bootstrap/bootstrap.js');

beforeEach(() => bootstrap());

it('should add new note', async () => {
  await createNote('note text');

  const actual = await getNotes();

  expect(actual).toMatchSnapshot();
});

it('should return new note', async () => {
  const actual = await createNote('note text');

  expect(actual).toMatchSnapshot();
});


text:
This repository is a community project to write tutorials and exercises to
help people interested in writing their own programming language on the
Rubinius language platform.

## License

All authors of contributed code consent to their code being licensed under the
BSD 3-clause license.


text:
#ifndef QD_HTTP_H
#define QD_HTTP_H

typedef struct qd_http_listener_t qd_http_listener_t;
typedef struct qd_http_server_t qd_http_server_t;

struct qd_server_t;
struct qd_server_config_t;
struct qd_listener_t;
struct qd_log_source_t;

/* Create a HTTP server */
qd_http_server_t *qd_http_server(struct qd_server_t *server, struct qd_log_source_t *log);

/* Free the HTTP server */
void qd_http_server_free(qd_http_server_t*);

/* Listening for HTTP, thread safe. */
qd_http_listener_t *qd_http_server_listen(qd_http_server_t *s, struct qd_listener_t *li);

#endif // QD_HTTP_H


text:
/* This file was generated by SableCC (http://www.sablecc.org/). */

package wolf.node;

import wolf.analysis.*;

@SuppressWarnings("nls")
public final class ATailFuncName extends PFuncName
{
    private TTail _tail_;

    public ATailFuncName()
    {
        // Constructor
    }

    public ATailFuncName(
        @SuppressWarnings("hiding") TTail _tail_)
    {
        // Constructor
        setTail(_tail_);

    }

    @Override
    public Object clone()
    {
        return new ATailFuncName(
            cloneNode(this._tail_));
    }

    @Override
    public void apply(Switch sw)
    {
        ((Analysis) sw).caseATailFuncName(this);
    }

    public TTail getTail()
    {
        return this._tail_;
    }

    public void setTail(TTail node)
    {
        if(this._tail_ != null)
        {
            this._tail_.parent(null);
        }

        if(node != null)
        {
            if(node.parent() != null)
            {
                node.parent().removeChild(node);
            }

            node.parent(this);
        }

        this._tail_ = node;
    }

    @Override
    public String toString()
    {
        return ""
            + toString(this._tail_);
    }

    @Override
    void removeChild(@SuppressWarnings("unused") Node child)
    {
        // Remove child
        if(this._tail_ == child)
        {
            this._tail_ = null;
            return;
        }

        throw new RuntimeException("Not a child.");
    }

    @Override
    void replaceChild(@SuppressWarnings("unused") Node oldChild, @SuppressWarnings("unused") Node newChild)
    {
        // Replace child
        if(this._tail_ == oldChild)
        {
            setTail((TTail) newChild);
            return;
        }

        throw new RuntimeException("Not a child.");
    }
}


text:
package jsettlers.main.swing;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Locale;
import java.util.Properties;

import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

import jsettlers.common.CommonConstants;
import jsettlers.common.ai.EPlayerType;
import jsettlers.common.map.MapLoadException;
import jsettlers.common.menu.IMapInterfaceConnector;
import jsettlers.common.menu.IStartedGame;
import jsettlers.common.menu.IStartingGame;
import jsettlers.common.resources.ResourceManager;
import jsettlers.common.utils.MainUtils;
import jsettlers.common.utils.OptionableProperties;
import jsettlers.graphics.localization.AbstractLabels;
import jsettlers.graphics.localization.Labels;
import jsettlers.graphics.swing.resources.ConfigurationPropertiesFile;
import jsettlers.graphics.swing.resources.SwingResourceLoader;
import jsettlers.logic.constants.MatchConstants;
import jsettlers.logic.map.MapLoader;
import jsettlers.logic.map.save.DirectoryMapLister;
import jsettlers.logic.player.PlayerSetting;
import jsettlers.main.JSettlersGame;
import jsettlers.main.ReplayStartInformation;
import jsettlers.main.swing.foldertree.SelectSettlersFolderDialog;
import jsettlers.main.swing.lookandfeel.JSettlersLookAndFeel;
import jsettlers.main.swing.lookandfeel.JSettlersLookAndFeelExecption;
import jsettlers.network.client.OfflineNetworkConnector;

/**
 * @author codingberlin
 * @author Andreas Eberle
 */
public class SwingManagedJSettlers {
	static {
		CommonConstants.USE_SAVEGAME_COMPRESSION = true;
	}

	public static void main(String[] args) throws IOException, MapLoadException, JSettlersLookAndFeelExecption {
		OptionableProperties optionableProperties = MainUtils.loadOptions(args);
		loadOptionalSettings(optionableProperties);
		SwingManagedJSettlers.setupResourceManagers(optionableProperties, "config.prp");

		JSettlersFrame settlersFrame = createJSettlersFrame();
		handleStartOptions(optionableProperties, settlersFrame);
	}

	public static void loadOptionalSettings(OptionableProperties options) {
		CommonConstants.CONTROL_ALL = options.isOptionSet("control-all");
		CommonConstants.ACTIVATE_ALL_PLAYERS = options.isOptionSet("activate-all-players");
		CommonConstants.ENABLE_CONSOLE_LOGGING = options.isOptionSet("console-output");
		CommonConstants.ENABLE_AI = !options.isOptionSet("disable-ai");
		CommonConstants.ALL_AI = options.isOptionSet("all-ai");
		CommonConstants.DISABLE_ORIGINAL_MAPS = options.isOptionSet("disable-original-maps");

		if (options.containsKey("fixed-ai-type")) {
			CommonConstants.FIXED_AI_TYPE = EPlayerType.valueOf(options.getProperty("fixed-ai-type"));
		}

		if (options.isOptionSet("localhost")) {
			CommonConstants.DEFAULT_SERVER_ADDRESS = "localhost";
		}

		if (options.containsKey("locale")) {
			String localeString = options.getProperty("locale");
			String[] localeParts = localeString.split("_");
			if (localeParts.length == 2) {
				AbstractLabels.setPreferredLocale(new Locale(localeParts[0], localeParts[1]));
			} else {
				System.err.println("Please specify the locale with language and country. (For example: de_de or en_us)");
			}
		}
	}

	/**
	 * Sets up the {@link ResourceManager} by using a configuration file.

	 * First it is checked, if the given argsMap contains a "configFile" parameter. If so, the path specified for this parameter is used to get the
	 * file.

	 * If the parameter is not given, the defaultConfigFile is used.
	 *
	 * @param argsMap
	 * @param defaultConfigFileName
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public static void setupResourceManagers(OptionableProperties options, String defaultConfigFileName) throws FileNotFoundException, IOException {
		ConfigurationPropertiesFile configFile = SwingManagedJSettlers.getConfigFile(options, defaultConfigFileName);
		SwingResourceLoader.setupResourcesManager(configFile);

		boolean firstRun = true;

		while (!configFile.isValidSettlersFolderSet() || !SwingManagedJSettlers.trySettingUpResources(configFile)) {
			if (!firstRun) {
				JOptionPane.showMessageDialog(null, Labels.getString("settlers-folder-still-invalid"));
			}
			firstRun = false;

			final SelectSettlersFolderDialog folderChooser = new SelectSettlersFolderDialog();
			SwingUtilities.invokeLater(new Runnable() {
				@Override
				public void run() {
					folderChooser.setVisible(true);
				}
			});

			File selectedFolder = folderChooser.waitForUserInput();
			if (selectedFolder == null) {
				String noFolderSelctedMessage = Labels.getString("error-no-settlers-3-folder-selected");
				JOptionPane.showMessageDialog(null, noFolderSelctedMessage);
				System.err.println(noFolderSelctedMessage);
				System.exit(1);
			}

			System.out.println(selectedFolder);
			try {
				configFile.setSettlersFolder(selectedFolder);
			} catch (IOException ex) {
				String errorSavingSettingsMessage = Labels.getString("error-settings-not-saveable");
				System.err.println(errorSavingSettingsMessage);
				JOptionPane.showMessageDialog(null, errorSavingSettingsMessage);
				ex.printStackTrace();
			}
		}

		if (!firstRun) { // the dialog was shown => settlers folder might have changed
			SwingResourceLoader.setupResourcesManager(configFile);
		}
	}

	private static boolean trySettingUpResources(ConfigurationPropertiesFile configFile) {
		try {
			SwingResourceLoader.setupGraphicsAndSoundResources(configFile);
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}

	public static ConfigurationPropertiesFile getConfigFile(Properties options, String defaultConfigFileName) throws IOException {
		String configFileName = defaultConfigFileName;
		if (options.containsKey("config")) {
			configFileName = options.getProperty("config");
		}
		return new ConfigurationPropertiesFile(new File(configFileName));
	}

	private static void handleStartOptions(OptionableProperties options, JSettlersFrame settlersFrame) throws IOException, MapLoadException {
		String mapfile = null;
		long randomSeed = 0;
		File loadableReplayFile = null;
		int targetGameTime = 0;

		mapfile = options.getProperty("mapfile");
		if (options.containsKey("random")) {
			randomSeed = Long.parseLong(options.getProperty("random"));
		}
		if (options.containsKey("replayFile")) {
			String loadableReplayFileString = options.getProperty("replayFile");
			File replayFile = new File(loadableReplayFileString);
			if (replayFile.exists()) {
				loadableReplayFile = replayFile;
				System.out.println("Found loadable replay file and loading it: " + loadableReplayFile);
			} else {
				System.err.println("Found replayFile parameter, but file can not be found!");
			}
		}
		if (options.containsKey("targetTime")) {
			targetGameTime = Integer.valueOf(options.getProperty("targetTime")) * 60 * 1000;
		}

		if (mapfile != null || loadableReplayFile != null) {
			IStartingGame game;
			if (loadableReplayFile == null) {
				MapLoader mapLoader = MapLoader.getLoaderForListedMap(new DirectoryMapLister.ListedMapFile(new File(mapfile)));
				byte playerId = 0;
				PlayerSetting[] playerSettings = PlayerSetting.createDefaultSettings(playerId, (byte) mapLoader.getMaxPlayers());
				game = new JSettlersGame(mapLoader, randomSeed, playerId, playerSettings).start();
			} else {
				game = JSettlersGame.loadFromReplayFile(loadableReplayFile, new OfflineNetworkConnector(), new ReplayStartInformation()).start();
			}
			settlersFrame.showStartingGamePanel(game);

			if (targetGameTime > 0) {
				while (!game.isStartupFinished()) {
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
					}
				}
				MatchConstants.clock().fastForwardTo(targetGameTime);
			}
		}
	}

	public static IMapInterfaceConnector showJSettlers(IStartedGame startedGame) throws JSettlersLookAndFeelExecption {
		JSettlersFrame jSettlersFrame = createJSettlersFrame();
		return jSettlersFrame.showStartedGame(startedGame);
	}

	private static JSettlersFrame createJSettlersFrame() throws JSettlersLookAndFeelExecption {
		JSettlersLookAndFeel.install();
		return new JSettlersFrame();
	}
}


text: package httpclient


text:
package org.apache.bookkeeper.stats;

public class BookkeeperServerStatsLogger extends BookkeeperStatsLogger {
    public static enum BookkeeperServerOp {
        ADD_ENTRY_REQUEST, ADD_ENTRY,
        READ_ENTRY_REQUEST, READ_ENTRY, READ_ENTRY_SCHEDULING_DELAY,
        READ_ENTRY_FENCE_REQUEST, READ_ENTRY_FENCE_WAIT, READ_ENTRY_FENCE_READ,
        READ_ENTRY_LONG_POLL_REQUEST, READ_ENTRY_LONG_POLL_PRE_WAIT, READ_ENTRY_LONG_POLL_WAIT, READ_ENTRY_LONG_POLL_READ,
        BOOKIE_ADD_ENTRY, BOOKIE_RECOVERY_ADD_ENTRY, BOOKIE_READ_ENTRY, BOOKIE_READ_LAST_CONFIRMED,
        BOOKIE_ADD_ENTRY_BYTES, BOOKIE_READ_ENTRY_BYTES,
        JOURNAL_ADD_ENTRY, JOURNAL_MEM_ADD_ENTRY, JOURNAL_PREALLOCATION, JOURNAL_FLUSH_IN_MEM_ADD,
        JOURNAL_FORCE_WRITE_LATENCY, JOURNAL_FORCE_WRITE_GROUPING_COUNT,
        JOURNAL_FORCE_WRITE_BATCH_ENTRIES, JOURNAL_FORCE_WRITE_BATCH_BYTES,
        JOURNAL_FLUSH_LATENCY, JOURNAL_CREATION_LATENCY,
        STORAGE_GET_OFFSET, STORAGE_GET_ENTRY,
        SKIP_LIST_GET_ENTRY, SKIP_LIST_PUT_ENTRY, SKIP_LIST_SNAPSHOT,
        GC_NUM_LEDGERS_DELETED_PER_GC, GC_NUM_ENTRYLOGS_DELETED_PER_COMPACTION,
        CHANNEL_WRITE
    }

    public static enum BookkeeperServerCounter {
        JOURNAL_WRITE_BYTES, JOURNAL_QUEUE_SIZE, READ_BYTES, WRITE_BYTES,
        NUM_MINOR_COMP, NUM_MAJOR_COMP, NUM_GC,
        INDEX_INMEM_ILLEGAL_STATE_RESET, INDEX_INMEM_ILLEGAL_STATE_DELETE,
        BUFFERED_READER_NUM_READ_REQUESTS, BUFFERED_READER_NUM_READ_CACHE_HITS,
        JOURNAL_FORCE_WRITE_QUEUE_SIZE, JOURNAL_NUM_FORCE_WRITES,
        JOURNAL_NUM_FLUSH_EMPTY_QUEUE, JOURNAL_NUM_FLUSH_MAX_OUTSTANDING_BYTES, JOURNAL_NUM_FLUSH_MAX_WAIT,
        SKIP_LIST_FLUSH_BYTES, SKIP_LIST_THROTTLING, READ_LAST_ENTRY_NOENTRY_ERROR,
        LEDGER_CACHE_NUM_EVICTED_LEDGERS,
        GC_NUM_LEDGERS_DELETED, GC_NUM_ENTRYLOGS_DELETED, GC_NUM_ENTRYLOGS_COMPACTED,
    }

    public static enum BookkeeperServerGauge {
        NUM_INDEX_PAGES, NUM_OPEN_LEDGERS,
        JOURNAL_FORCE_WRITE_QUEUE_SIZE, JOURNAL_FORCE_WRITE_GROUPING_COUNT,
        NUM_PENDING_LONG_POLL, NUM_PENDING_READ, NUM_PENDING_ADD,
        NUM_PENDING_ENTRY_LOG_FILES, LEAST_UNFLUSHED_ENTRYLOG_ID, CURRENT_ENTRYLOG_ID,
        GC_TOTAL_SCANNED_BYTES, GC_TOTAL_SCANNED_ENTRYLOG_FILES, GC_LAST_SCANNED_ENTRYLOG_ID,
        GC_NUM_ENTRYLOG_FILES_SPACE_USAGE,
        SERVER_STATUS
    }

    public BookkeeperServerStatsLogger(StatsLogger underlying) {
        super(underlying, BookkeeperServerOp.values(), BookkeeperServerCounter.values(),
                BookkeeperServerGauge.values());
    }
}


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class LtiConnectionContentId extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('lti_connections', function (Blueprint $table) {
            $table->string('content_id')->nullable()->after('lti_consumer_key');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('lti_connections', function (Blueprint $table) {
            $table->dropColumn('content_id');
        });
    }
}


text:
import org.apache.commons.lang.StringUtils;

public class Foo {
  public String toString() {
    return StringUtils.normalizeSpace("hi  there!");
  }
}


text:
Wrangler
========

The goal of Wrangler: get your got'dang data into your got'dang webpage and stop worrying about it.

To use it with an object (or an array of objects):

    var w = new Wrangler(myObject, 'object-template')

This creates a two-way binding between the data in `myObject` and the `object-template` div.

API reference
=============

Wrangler object
---------------

All of these are methods of a `Wrangler` instance.

* **constructor**: `new Wrangler(model, template, options)`

  Wrangles the `model` to a `template`.

* `get(property, escaped)`

  Gets a property. It first checks the Wrangler to see if it has this property; if not, it finds the property in the model. If the property happens to be a function, it executes the function and returns the result. Otherwise, it just returns the property.

  `escaped` defaults to `true`; set it to `false` and it won't escape your HTML.

* `set(property, value)`

  Sets a property of the model (NOT of the Wrangler) and updates. Has some special stuff if your model is an array:

        // ... some logic for defining tasks ...
        tasksWrangler.set(0, { name: "Say hello to the world", done: false });
        tasksWrangler.set("done", true);

* `destroy(alsoDestroyModel)`

  Removes my element. Calling `myWrangler.destroy(true)` also destroys the model.

* `update()`

  Manually updates the DOM from the model (you could call it after the model changes without using `set()`).

Misc. utilities
---------------

* `Wrangler.addEvent(element, name, callback)`

  Binds the browser event `name` to the `element` you choose, and executes the `callback` when it happens.

* `Wrangler.escape(html)`

  Escapes tags, ampersands, and breaking spaces.


text:
layout:     post
title:      "Hacking at Facebook's Global Finals"
subtitle:   ""
date:       2013-12-11 10:00
author:     "Ben Chin"
header-img: "img/post-bg-06.jpg"
---

Meet the team.

That's **James** on the left. He's a front end dev with me. In the middle is **Ains**, our polyglot, super-efficient, hacker, and to the right, **Preeya**, back end dev and chief of all things operational.

And that's me, **Ben**, in the little circle up there. I'm the UX/UI and general front end dev guy.

---

At an hour of the morning rarely seen by Computing students, and unable to stop yawning, we sat in Heathrow airport waiting for BA 285. It would take us to San Francisco, and the global final of Facebook's College Hackathons. We (sleepily!) talked over our hack idea - an application to make travel planning with friends painless - as we boarded the plane. We had qualified for the finals by taking first place at the college hackathon held at Facebook's London office earlier in the year, and we hoped to do the same at Menlo Park.

---

## Touchdown SFO

After settling into our hotel, we went bowling in SF with Facebook. We met their awesome engineers, the other finalists, and found out who sucked the most at throwing a ball in a straight line (me…).

Once back at the hotel though, we slept like logs.

---

## Hack Day

The morning of the hack had arrived, and after the bus dropped us at 1 Hacker Way, Menlo Park, we were led to the hack space.

*Holy cheeseballs, it was awesome.*

They hadn't spared any expense. Each hacker was given a Hackathon rucksack, a gigantic monitor, a keyboard and mouse, and a pair of the sweetest Sennheisers I have ever known. The swag didn't stop there though. During the hack we managed to end up with a Facebook Snuggie as well as a Macbook Pro (because James' eMachine had a mild inferiority complex).

Once we'd set up, we were assigned a mentor, a Facebook engineer named Alok, who worked on the Hip-Hop Virtual Machine. He took us on a tour of the campus, and if we'd been blown away by the hack setups, that was nothing compared to seeing the campus.

It was like Disneyland...

...but for hackers.

Nearly all of the onsite restaurants served free food, there was an arcade, sweet shops and ice cream shops, and bicycles could be seen scattered all over campus in case you got bored of walking between buildings. It goes without saying that we cycled more than we walked!

It felt more like a theme park than a multibillion dollar company, and it wasn't hard to see why it attracted the best engineers.

After lunch with our mentor, we heard Sheryl Sandberg, **Facebook COO**, talk to us about building things that solve problems and the importance of hack culture at the company. Once the applause died down, the hackathon kicked off.

---

## Get Hacking!

With the ideation already started, we began with sketching out wireframes and listing out all the different views and interfaces we would need, as well as all the APIs we could use and how they would plug into the front-end. We'd somehow managed to wrangle two TripAdvisor api keys by pouncing on a Technical Manager at the Imperial Careers fair, which was a perfect fit for what we wanted to do.

Next, we confirmed our app stack - Django, Underscore, Handlebars for templating, and of course trusty Bootstrap 3 for building the interface (we would later add Pusher for realtime notifications). With a plan laid out, we set to work.

Meanwhile, around the room, a frightening array of gadgets could be seen (two Oculus Rifts, several pairs of Google Glass and a LeapMotion controller), and everyone was deep in conversation, or beginning to code.

Time seemed to disappear quicker than it ever did, and time was our team's most prized commodity, because we'd set ourselves a lot to do! Before we knew it, dinner had arrived, and as the saying goes - *what's a hackathon without pizza?*

We did however, get time during the night to talk to the other teams, visit the arcade, and even get signed books from the Andrei Alexandrescu, creator of the D programming language (who, as it turned out, worked on the seat next to our mentor).

The night was not without its challenges. We had to hack a jQuery calendar plugin beyond recognition both functionally and visually (thank God, because it was horrendously ugly), wrap APIs, and merge our work at unholy hours of the morning.

By breakfast however, we had an app. We named it **Indago**. We had the APIs working and most of the interface was complete, with just realtime notifications to implement. After a quick run to the canteen for breakfast, we spent the rest of the morning in the same cycle.

*Tweak. Polish. Bugfix. Repeat.*

With twenty minutes to go, I threw together a home page, and suddenly, the hack was over.

---

## Demo Time

As we migrated to a presentation room, eyes bleary and checking we hadn't broken anything, we were given the rules. Two minute demo and no more, PowerPoints were banned, and if your hack doesn't work - *heaven help you*.

The judges entered - two from Mobile and Advertising, and a senior engineer - and the demos began.

We watched in fascination as the other finalists presented their ideas - an educational Python game, a Glass facial recognition app, a VR hack with an Oculus Rift and suddenly **we were up**.

Ains and Preeya led the demo, as James and I sat with the judges so they could see both sides of the story with our app. Preeya explained how the idea for our hack came about - struggling to plan our next couple of days together in California - and then, using our app and with the help of both the judges and audience, we planned, live, our weekend in the Bay Area.

It seemed a hit. People *ooh*ed when James shared an event suggestion to Ains on the big screen, and people *aah*ed when we hit the merge button to create the event schedule. With only a few seconds left, as we showed off our last feature, exporting the schedule to iCal, we hit a **server 500** error, and the groans of disappointment from the crowd echoed ours. What a shame! Still, we felt pretty proud.

We watched the rest of the presentations (featuring a Leap Motion controller to turn any screen into a touch screen) and headed back to pack up.

---

## The Results!

In the hack space, the results were announced.

Special mentions went to an app that connected strangers with social similarity, third place went to Mexico for their brilliant iOS game. As we applauded them receiving their prize (*Facebook hammocks!*), the rest of the results were announced.

Suddenly we realised - **we'd taken second place**!

Feeling incredibly proud, we went up to collect our prize (Sphero's!) as one of the judges praised our slick interface, our targeting of an unsolved problem, and the huge amount of features we'd managed to implement in 24 hours.

First prize went to Vancouver, who had built upon their qualifying hack to use iBeacons to provide additional information and social recommendations based on where you walked in a shop. The grand prize was $1,000 for each team member and a severe amount of kudos!

With the hack over, we headed back to the hotel, grabbed food with the other finalists, and caught some long needed sleep. It had been an amazing experience, and it had been great to hack amongst some of the best universities in the US and South America. Facebook's company culture and pretty spectacular hosting had given everyone a taste of a company culture that was exciting, engineer-oriented, and just downright fun. We came away with some awesome friends, a new app, and even a title to bring back home.

*P.S. If you happen to be interested, we're going to continue working on the app - keep an ear out for news!*


text:
package org.zmlx.hg4idea.log;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.FileStatus;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.vcs.log.Hash;
import com.intellij.vcs.log.VcsUser;
import com.intellij.vcs.log.impl.VcsChangesLazilyParsedDetails;
import com.intellij.vcs.log.impl.VcsStatusDescriptor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.zmlx.hg4idea.HgRevisionNumber;
import org.zmlx.hg4idea.provider.HgChangeProvider;

import java.util.List;

import static org.zmlx.hg4idea.log.HgHistoryUtil.createChange;

public class HgCommit extends VcsChangesLazilyParsedDetails {
  @NotNull private final HgRevisionNumber myRevisionNumber;

  public HgCommit(@NotNull Project project, VirtualFile root, @NotNull Hash hash,
                  @NotNull List<Hash> parentsHashes,
                  @NotNull HgRevisionNumber vcsRevisionNumber,
                  @NotNull VcsUser author,
                  long time,
                  List<List<HgFileStatusInfo>> reportedChanges) {
    super(hash, parentsHashes, time, root, vcsRevisionNumber.getSubject(), author, vcsRevisionNumber.getCommitMessage(), author, time);
    myRevisionNumber = vcsRevisionNumber;
    myChanges.set(reportedChanges.isEmpty() ? EMPTY_CHANGES : new UnparsedChanges(project, reportedChanges));
  }

  private class UnparsedChanges extends VcsChangesLazilyParsedDetails.UnparsedChanges<HgFileStatusInfo> {
    private UnparsedChanges(@NotNull Project project,
                            @NotNull List<List<HgFileStatusInfo>> changesOutput) {
      super(project, changesOutput, new HgChangesDescriptor());
    }

    @NotNull
    @Override
    protected List<Change> parseStatusInfo(@NotNull List<HgFileStatusInfo> changes, int parentIndex) {
      List<Change> result = ContainerUtil.newArrayList();
      for (HgFileStatusInfo info : changes) {
        String filePath = info.getFirstPath();
        HgRevisionNumber parentRevision = myRevisionNumber.getParents().isEmpty() ? null : myRevisionNumber.getParents().get(parentIndex);
        switch (info.getType()) {
          case MODIFICATION:
            result.add(createChange(myProject, getRoot(), filePath, parentRevision, filePath, myRevisionNumber, FileStatus.MODIFIED));
            break;
          case NEW:
            result.add(createChange(myProject, getRoot(), null, null, filePath, myRevisionNumber, FileStatus.ADDED));
            break;
          case DELETED:
            result.add(createChange(myProject, getRoot(), filePath, parentRevision, null, myRevisionNumber, FileStatus.DELETED));
            break;
          case MOVED:
            result.add(createChange(myProject, getRoot(), filePath, parentRevision, info.getSecondPath(), myRevisionNumber,
                                    HgChangeProvider.RENAMED));
            break;
        }
      }
      return result;
    }
  }

  private static class HgChangesDescriptor extends VcsStatusDescriptor<HgFileStatusInfo> {
    @NotNull
    @Override
    protected HgFileStatusInfo createStatus(@NotNull Change.Type type, @NotNull String path, @Nullable String secondPath) {
      return new HgFileStatusInfo(type, path, secondPath);
    }

    @NotNull
    @Override
    public String getFirstPath(@NotNull HgFileStatusInfo info) {
      return info.getFirstPath();
    }

    @Nullable
    @Override
    public String getSecondPath(@NotNull HgFileStatusInfo info) {
      return info.getSecondPath();
    }

    @NotNull
    @Override
    public Change.Type getType(@NotNull HgFileStatusInfo info) {
      return info.getType();
    }
  }

  public static class HgFileStatusInfo {
    @NotNull private final Change.Type myType;
    @NotNull private final String myFirstPath;
    @Nullable private final String mySecondPath;

    public HgFileStatusInfo(@NotNull Change.Type type, @NotNull String firstPath, @Nullable String secondPath) {
      myType = type;
      myFirstPath = firstPath;
      mySecondPath = secondPath;
    }

    @NotNull
    public Change.Type getType() {
      return myType;
    }

    @NotNull
    public String getFirstPath() {
      return myFirstPath;
    }

    @Nullable
    public String getSecondPath() {
      return mySecondPath;
    }
  }
}


text:
	<meta http-equiv="content-type" content="text/html;charset=utf-8">
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=EDGE">
	<meta content="width=device-width,initial-scale=1, user-scalable=no" name="viewport">

	<title>极简煮义 </title>
	<meta name="keywords" content="">
	<meta name="description" content="">

	<link media="all" type="text/css" rel="stylesheet" href="css/styles.css">
	<link media="all" type="text/css" rel="stylesheet" href="css/base.css">
	<link media="all" type="text/css" rel="stylesheet" href="css/register.css">

重置密码

		<input placeholder="请输入手机号" class="name"></input>

帐号已存在

		<input placeholder="请输入验证码" class="input_msg
		"></input>
		<input type="button" value="59秒后重发验证码" class="sending_msg
		"></input>

验证码有误

		<input placeholder="请输入密码" class=""></input>

		<input placeholder="请再次输入密码" class=""></input>

用户名或密码错误,请重新输入

重置密码

		登陆 | 注册

		TEL:021-82203039
		9:00 - 18:00


text:
@implementation SRNCappedQueue {
    NSMutableArray *queue;
    NSInteger size;
}

- (instancetype)initWithSize:(NSInteger)aSize {
    NSParameterAssert( aSize > 0 );
    self = [super init];
    if (self) {
        queue = [[NSMutableArray alloc] init];
        size = aSize;
    }
    return self;
}

- (id)init {
    return nil;
}

- (void)enqueue:(id)object {
    [queue addObject:object];
    if ([queue count] > size) {
        [queue removeObjectAtIndex:0];
    };
}

- (id)dequeue {
    id returnObject = [queue lastObject];
    if (returnObject) {
        [queue removeLastObject];
    }
    return returnObject;
}

- (NSArray *)dequeueAll {
    return [self dequeueWithCount:[self count]];
}

- (NSArray *)dequeueWithCount:(NSInteger)count {
    NSMutableArray *result = [[NSMutableArray alloc] init];
    for (int i = 0; i < count; ++i) {
        id obj = [self dequeue];
        if(obj) {
            [result addObject:obj];
        }
    }
    return result;
}

- (NSUInteger)count {
    return [queue count];
}

- (NSArray *)queueCopy {
    return [NSArray arrayWithArray:queue];
}

- (NSArray *)newestObjects:(NSInteger)count {
    NSUInteger totalCount = [self count];
    NSUInteger start;
    if(count >= totalCount) {
        start = 0;
    } else {
        start = totalCount-count;
    }
    return [queue subarrayWithRange:(NSRange){start, totalCount}];
}

@end


text:
# HAML-Lint

[![Gem Version](https://badge.fury.io/rb/haml_lint.svg)](http://badge.fury.io/rb/haml_lint)
[![Build Status](https://travis-ci.org/brigade/haml-lint.svg)](https://travis-ci.org/brigade/haml-lint)
[![Code Climate](https://codeclimate.com/github/brigade/haml-lint.png)](https://codeclimate.com/github/brigade/haml-lint)
[![Coverage Status](https://coveralls.io/repos/brigade/haml-lint/badge.svg)](https://coveralls.io/r/brigade/haml-lint)
[![Dependency Status](https://gemnasium.com/brigade/haml-lint.svg)](https://gemnasium.com/brigade/haml-lint)
[![Inline docs](http://inch-ci.org/github/brigade/haml-lint.svg?branch=master)](http://inch-ci.org/github/brigade/haml-lint)

`haml-lint` is a tool to help keep your [HAML](http://haml.info) files
clean and readable. In addition to HAML-specific style and lint checks, it
integrates with [RuboCop](https://github.com/bbatsov/rubocop) to bring its
powerful static analysis tools to your HAML documents.

You can run `haml-lint` manually from the command line, or integrate it into
your [SCM hooks](https://github.com/brigade/overcommit).

* [Requirements](#requirements)
* [Installation](#installation)
* [Usage](#usage)
* [Configuration](#configuration)
* [Linters](#linters)
* [Editor Integration](#editor-integration)
* [Git Integration](#git-integration)
* [Rake Integration](#rake-integration)
* [Documentation](#documentation)
* [Contributing](#contributing)
* [Community](#community)
* [Changelog](#changelog)
* [License](#license)

## Requirements

 * Ruby 2.0.0+
 * HAML 4.0+

## Installation

```bash
gem install haml_lint
```

## Usage

Run `haml-lint` from the command line by passing in a directory (or multiple
directories) to recursively scan:

```bash
haml-lint app/views/
```

You can also specify a list of files explicitly:

```bash
haml-lint app/**/*.html.haml
```

`haml-lint` will output any problems with your HAML, including the offending
filename and line number.

Command Line Flag         | Description
--------------------------|----------------------------------------------------
`-c`/`--config`           | Specify which configuration file to use
`-e`/`--exclude`          | Exclude one or more files from being linted
`-i`/`--include-linter`   | Specify which linters you specifically want to run
`-x`/`--exclude-linter`   | Specify which linters you _don't_ want to run
`--[no-]color`            | Whether to output in color
`--show-linters`          | Show all registered linters
`-h`/`--help`             | Show command line flag documentation
`-v`/`--version`          | Show `haml-lint` version
`-V`/`--verbose-version`  | Show `haml-lint`, `haml`, and `ruby` version information

## Configuration

`haml-lint` will automatically recognize and load any file with the name
`.haml-lint.yml` as a configuration file. It loads the configuration based on
the directory `haml-lint` is being run from, ascending until a configuration
file is found. Any configuration loaded is automatically merged with the
default configuration (see `config/default.yml`).

Here's an example configuration file:

```yaml
linters:
  ImplicitDiv:
    enabled: false
    severity: error

  LineLength:
    max: 100
```

All linters have an `enabled` option which can be `true` or `false`, which
controls whether the linter is run, along with linter-specific options. The
defaults are defined in [`config/default.yml`](config/default.yml).

### Linter Options

Option        | Description
--------------|----------------------------------------------------------------
`enabled`     | If `false`, this linter will never be run. This takes precedence over any other option.
`include`     | List of files or glob patterns to scope this linter to. This narrows down any files specified via the command line.
`exclude`     | List of files or glob patterns to exclude from this linter. This excludes any files specified via the command line or already filtered via the `include` option.
`severity`    | The severity of the linter. External tools consuming `haml-lint` output can use this to determine whether to warn or error based on the lints reported.

### Global File Exclusion

The `exclude` global configuration option allows you to specify a list of files
or glob patterns to exclude from all linters. This is useful for ignoring
third-party code that you don't maintain or care to lint. You can specify a
single string or a list of strings for this option.

### Skipping Frontmatter

Some static blog generators such as [Jekyll](http://jekyllrb.com/) include
leading frontmatter to the template for their own tracking purposes.
`haml-lint` allows you to ignore these headers by specifying the
`skip_frontmatter` option in your `.haml-lint.yml` configuration:

```yaml
skip_frontmatter: true
```

## Linters

### [» Linters Documentation](lib/haml_lint/linter/README.md)

`haml-lint` is an opinionated tool that helps you enforce a consistent style in
your HAML files. As an opinionated tool, we've had to make calls about what we
think are the "best" style conventions, even when there are often reasonable
arguments for more than one possible style. While all of our choices have a
rational basis, we think that the opinions themselves are less important than
the fact that `haml-lint` provides us with an automated and low-cost means of
enforcing consistency.

## Editor Integration

### Vim

If you use `vim`, you can have `haml-lint` automatically run against your HAML
files after saving by using the
[Syntastic](https://github.com/scrooloose/syntastic) plugin. If you already
have the plugin, just add `let g:syntastic_haml_checkers = ['haml_lint']` to
your `.vimrc`.

### Sublime Text 3

If you use `SublimeLinter 3` with `Sublime Text 3` you can install the
[SublimeLinter-haml-lint](https://github.com/jeroenj/SublimeLinter-contrib-haml-lint)
plugin using [Package Control](https://sublime.wbond.net).

### Atom

If you use `atom`, you can install the [linter-haml](https://atom.io/packages/linter-haml) plugin.

## Git Integration

If you'd like to integrate `haml-lint` into your Git workflow, check out our
Git hook manager, [overcommit](https://github.com/brigade/overcommit).

## Rake Integration

To execute `haml-lint` via a [Rake](https://github.com/ruby/rake) task, add the
following to your `Rakefile`:

```ruby
require 'haml_lint/rake_task'

HamlLint::RakeTask.new
```

By default, when you execute `rake haml_lint`, the above configuration is
equivalent to running `haml-lint .`, which will lint all `.haml` files in the
current directory and its descendants.

You can customize your task by writing:

```ruby
require 'haml_lint/rake_task'

HamlLint::RakeTask.new do |t|
  t.config = 'custom/config.yml'
  t.files = ['app/views', 'custom/*.haml']
  t.quiet = true # Don't display output from haml-lint to STDOUT
end
```

You can also use this custom configuration with a set of files specified via
the command line:

```
# Single quotes prevent shell glob expansion
rake 'haml_lint[app/views, custom/*.haml]'
```

Files specified in this manner take precedence over the task's `files`
attribute.

## Documentation

[Code documentation] is generated with [YARD] and hosted by [RubyDoc.info].

[Code documentation]: http://rdoc.info/github/brigade/haml-lint/master/frames
[YARD]: http://yardoc.org/
[RubyDoc.info]: http://rdoc.info/

## Contributing

We love getting feedback with or without pull requests. If you do add a new
feature, please add tests so that we can avoid breaking it in the future.

Speaking of tests, we use `rspec`, which can be run by executing the following
from the root directory of the repository:

```bash
bundle exec rspec
```

## Community

All major discussion surrounding HAML-Lint happens on the
[GitHub issues page](https://github.com/brigade/haml-lint/issues).

You can also follow [@haml_lint on Twitter](https://twitter.com/haml_lint).

## Changelog

If you're interested in seeing the changes and bug fixes between each version
of `haml-lint`, read the [HAML-Lint Changelog](CHANGELOG.md).

## License

This project is released under the [MIT license](MIT-LICENSE).


text:
'use strict';

var gulp = require('gulp-help')(require('gulp'));

var sass = require('gulp-sass');

var sourcemaps = require('gulp-sourcemaps');
var postcss = require('gulp-postcss');
var plumber = require('gulp-plumber');

var autoprefixer = require('autoprefixer-core');

var config = require('./../config.js');
var reload = require('./browserSync.js').reload;
var handleError = require('./../utils/handleError.js');

// Complie scss using libsass

gulp.task('styles', 'Compile Sass to CSS', function () {
  return gulp.src(config.styles.src)
    .pipe(sourcemaps.init())
    .pipe(sass(config.styles.sassCfg))
    .pipe(postcss([
      autoprefixer(config.styles.autoprefixerCfg)
    ]))
    .pipe(sourcemaps.write())
    .pipe(gulp.dest(config.styles.dest))
    .on('error', handleError)
    .pipe(reload({stream:true}));
});


text:
package com.dangdang.ddframe.job.cloud.scheduler.boot.env;

import lombok.Getter;
import lombok.RequiredArgsConstructor;

/**
 * Restful服务器配置项.
 *
 * @author zhangliang
 */
@RequiredArgsConstructor
@Getter
public final class RestfulServerConfiguration {

    private final int port;
}


text:
<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * Modelo para el módulo de contactos
 *
 * @author Sara Alamillo Arroyo
 */
class Instalador_model extends CI_Model {
    public function mostrarTablas() {
        $tablas = [];

        $consulta = $this->db->query("show tables from {$this->db->select()->database}");

        foreach ($consulta->result() as $registro) {
            foreach ($registro as $campo) {
                $tablas[] = $campo;
            }
        }

        return $tablas;
    }

    public function eliminarTablas($tablas) {
        $this->db->query("SET FOREIGN_KEY_CHECKS = 0");
        foreach ($tablas as $nombre) {
            $this->db->query("drop table $nombre cascade");
        }
    }
    public function importSql($fichero) {
        $lines = file($fichero);
        foreach ($lines as $key => $line) {
            if (substr($line, 0, 2) == "--") {
                unset($lines[$key]);
            }
        }
        $lines = array_values($lines);
        $lines = implode(" ", $lines);
        $lines = explode(";", $lines);

        foreach ($lines as &$line) {
            $line = trim($line);
            if ($line != '') {
                $this->db->query($line);
            }
        }
    }
}


text:
<!doctype html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="description" content="Listado de equipos de fotografía robados en Argentina">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Equipos robados</title>

	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

	<link rel="stylesheet" href="css/main.css">

		<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbar-body" aria-expanded="false">

		</button>
		Cámaras robadas

					Listado

					Cargar equipo

					Registro

					Iniciar sesión

						<form class="dropdown-item form-signin" id="login-form">

									<input class="form-control login" type="text" id="emailField" placeholder="E-mail" required>

									<input class="form-control login" type="password" id="passwordField" placeholder="Contraseña" required>

							Usuario o contraseña inválidos

								<button type="submit" class="btn btn-primary btn-block" id="loginButton">Ingresar</button>

						</form>

						<form class="dropdown-item form" id="logout-form">

								<button type="submit" class="btn btn-primary btn-block" id="logOutButton">Cerrar sesión</button>

						</form>

Hecho con amor usando Firebase y GitHub Pages.


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Bulletin Board</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="css/main.css">

Bulletin Board

       	      <input type="text" id="words" value="" maxlength="26"/>

           <form id="fonts">
              Font:
                <input type="radio" name="font" value="font1" id="font1">

                <input type="radio" name="font" value="font2" id="font2">

                <input type="radio" name="font" value="font3" id="font3">

                <input type="radio" name="font" value="font4" id="font4">

                <input type="radio" name="font" value="font5" id="font5">

            </form>

            <form id="backgrounds">
              Theme:
                <input type="radio" name="background" value="background1" id="background1">

                <input type="radio" name="background" value="background2" id="background2">

                <input type="radio" name="background" value="background3" id="background3">

                <input type="radio" name="background" value="background4" id="background4">

                <input type="radio" name="background" value="background5" id="background5">

            </form>

Characters: 26


text:
#ifndef PCL_MODELER_SCENE_TREE_IMPL_H_
#define PCL_MODELER_SCENE_TREE_IMPL_H_

#include <pcl/apps/modeler/scene_tree.h>

namespace pcl
{
  namespace modeler
  {
    /////////////////////////////////////////////////////////////////////////////////////////////
    template <class T> QList<T*>
    pcl::modeler::SceneTree::selectedTypeItems() const
    {
       QList<QTreeWidgetItem*> selected_items = selectedItems();
       QList<T*> selected_t_items;
       for (auto &selected_item : selected_items)
       {
         T* t_item = dynamic_cast<T*>(selected_item);
         if(t_item != nullptr)
           selected_t_items.push_back(t_item);
       }

       return (selected_t_items);
    }
  }
}

#endif // PCL_MODELER_SCENE_TREE_IMPL_H_


text:
<?php
  jRequire("../Query/Query.php");
  jRequire("../File/File.php");
  class Module {
    use Query {
      Query::__construct as private __queryConstruct;
      Query::addConnectionMan as private __addConnectionMan;
    }
    use File {
      File::__construct as private __fileConstruct;
    }
    public $name;
    public $modules;
    public function __construct() {
      $this->name    = get_class($this);
      $this->modules = [];
      $this->__queryConstruct();
      $this->__fileConstruct();
    }
    public function addModules( $_modules ) {
      if(!is_array($_modules))
        throw new JException("Parameter must be an array.");
      foreach ($_modules as $value)
        $this->addModule($value);
    }
    public function addModule( $_module ) {
      if(!is_object($_module))
        throw new JException("Parameter must be a object.");
      if(! is_subclass_of ($_module, "Module"))
        throw new JException("Parameter must be a object inherited from Module object.");
      $this->modules[$_module->name] = $_module;
      if($this->currentConnection)
        $this->modules[$_module->name]->addConnectionMan($this->currentConnection);
    }
    public function addConnectionMan( $_connection, $_name = "default") {
      try {
        $this->__addConnectionMan($_connection, $_name);
        foreach ($this->modules as &$module)
          if(isset($this->currentConnection))
            $module->addConnectionMan($this->currentConnection, $_name);
      } catch (Exception $e) {
        throw new JException($e->getMessage(), 1);
      }
    }
  }
?>


text:
#include "hardwarebuffer.h"
#include "graphics.h"

#include <framework/core/application.h>
#include <framework/core/logger.h>

HardwareBuffer::HardwareBuffer(Type type)
{
    m_type = type;
    m_id = 0;
    glGenBuffers(1, &m_id);
    if(!m_id)
        g_logger.fatal("Unable to create hardware buffer.");
}

HardwareBuffer::~HardwareBuffer()
{
#ifndef NDEBUG
    assert(!g_app.isTerminated());
#endif
    if(g_graphics.ok())
        glDeleteBuffers(1, &m_id);
}


text:
\begin{figure}[H]
\centering
\includegraphics[width=6in]{figs/run_69/run_69_ctke_vs_r_mesh_scatter}
\caption{Scatter plot of turbulent kinetic energy vs radius at $z/c$=10.00, $V_{free}$=31.31, station7}
\label{fig:run_69_ctke_vs_r_mesh_scatter}
\end{figure}


text:
package org.apache.zeppelin.rest.message;

/**
 * CheckpointNoteRequest rest api request message.
 */
public class CheckpointNoteRequest {
  private final String commitMessage;

  public CheckpointNoteRequest(String commitMessage) {
    this.commitMessage = commitMessage;
  }

  public String getCommitMessage() {
    return commitMessage;
  }
}


text:
<?xml version='1.0' encoding='UTF-8'?>
<TimeML xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://timeml.org/timeMLdocs/TimeML_1.2.1.xsd">
Let's #Celebrate #Adidas #Dope #DidierDrogba #Allin #Astonishing #Abidjan #Cotedivoire #Addict #Africa #Stripes http://t.co/gdJkqSzh4V
<SOURCE implicit="AUTHOR" ssid="s0" />
<RELEVANT_SOURCE rsid="s0" />
</TimeML>


text:
<!DOCTYPE html>

		<meta charset="utf-8">
		<title>Pacha Rossa</title>
		<link rel="stylesheet" type="text/css" href="style.css">

			<input type="file" id="fileData"/>
			<input type="text" id="search" />

Current Effects

Add effect

Reset Usage

<input type="submit" id="resetEncounters" value="Short Rest" />

<input type="submit" id="resetDailies" value="Extended Rest" />

Basic Tactics

Move with center of the team

Downgrade when no attacks possible

Stay out of danger

Don't react

Be aware of teammates' health

Save non-damaging powers

Debuff solo monsters, and buff against group

Reminders

Fully heal before and after any combat.

Critical hits give an additional use of Healing Word (see Gambler's Word).

Gain +4 to non-violent attacks by using an Action Point (see Peacemaker's Action).

Extend effects with Peacemaker's Pronouncement.

Action Points grant +2 to defenses (see Hero's Armor)

Use your Jade Macetail.

Do not downgrade your initiative.


text:
"""
Support for repeating alerts when conditions are met.

For more details about this component, please refer to the documentation at
https://home-assistant.io/components/alert/
"""
import asyncio
from datetime import datetime, timedelta
import logging
import os

import voluptuous as vol

from homeassistant.core import callback
from homeassistant.config import load_yaml_config_file
from homeassistant.const import (
    CONF_ENTITY_ID, STATE_IDLE, CONF_NAME, CONF_STATE, STATE_ON, STATE_OFF,
    SERVICE_TURN_ON, SERVICE_TURN_OFF, SERVICE_TOGGLE, ATTR_ENTITY_ID)
from homeassistant.helpers.entity import ToggleEntity
from homeassistant.helpers import service, event
import homeassistant.helpers.config_validation as cv

_LOGGER = logging.getLogger(__name__)

DOMAIN = 'alert'
ENTITY_ID_FORMAT = DOMAIN + '.{}'

CONF_DONE_MESSAGE = 'done_message'
CONF_CAN_ACK = 'can_acknowledge'
CONF_NOTIFIERS = 'notifiers'
CONF_REPEAT = 'repeat'
CONF_SKIP_FIRST = 'skip_first'

DEFAULT_CAN_ACK = True
DEFAULT_SKIP_FIRST = False

ALERT_SCHEMA = vol.Schema({
    vol.Required(CONF_NAME): cv.string,
    vol.Optional(CONF_DONE_MESSAGE, default=None): cv.string,
    vol.Required(CONF_ENTITY_ID): cv.entity_id,
    vol.Required(CONF_STATE, default=STATE_ON): cv.string,
    vol.Required(CONF_REPEAT): vol.All(cv.ensure_list, [vol.Coerce(float)]),
    vol.Required(CONF_CAN_ACK, default=DEFAULT_CAN_ACK): cv.boolean,
    vol.Required(CONF_SKIP_FIRST, default=DEFAULT_SKIP_FIRST): cv.boolean,
    vol.Required(CONF_NOTIFIERS): cv.ensure_list})

CONFIG_SCHEMA = vol.Schema({
    DOMAIN: vol.Schema({
        cv.slug: ALERT_SCHEMA,
    }),
}, extra=vol.ALLOW_EXTRA)

ALERT_SERVICE_SCHEMA = vol.Schema({
    vol.Required(ATTR_ENTITY_ID): cv.entity_ids,
})

def is_on(hass, entity_id):
    """Return if the alert is firing and not acknowledged."""
    return hass.states.is_state(entity_id, STATE_ON)

def turn_on(hass, entity_id):
    """Reset the alert."""
    hass.add_job(async_turn_on, hass, entity_id)

@callback
def async_turn_on(hass, entity_id):
    """Async reset the alert."""
    data = {ATTR_ENTITY_ID: entity_id}
    hass.async_add_job(
        hass.services.async_call(DOMAIN, SERVICE_TURN_ON, data))

def turn_off(hass, entity_id):
    """Acknowledge alert."""
    hass.add_job(async_turn_off, hass, entity_id)

@callback
def async_turn_off(hass, entity_id):
    """Async acknowledge the alert."""
    data = {ATTR_ENTITY_ID: entity_id}
    hass.async_add_job(
        hass.services.async_call(DOMAIN, SERVICE_TURN_OFF, data))

def toggle(hass, entity_id):
    """Toggle acknowledgement of alert."""
    hass.add_job(async_toggle, hass, entity_id)

@callback
def async_toggle(hass, entity_id):
    """Async toggle acknowledgement of alert."""
    data = {ATTR_ENTITY_ID: entity_id}
    hass.async_add_job(
        hass.services.async_call(DOMAIN, SERVICE_TOGGLE, data))

@asyncio.coroutine
def async_setup(hass, config):
    """Set up the Alert component."""
    alerts = config.get(DOMAIN)
    all_alerts = {}

    @asyncio.coroutine
    def async_handle_alert_service(service_call):
        """Handle calls to alert services."""
        alert_ids = service.extract_entity_ids(hass, service_call)

        for alert_id in alert_ids:
            alert = all_alerts[alert_id]
            if service_call.service == SERVICE_TURN_ON:
                yield from alert.async_turn_on()
            elif service_call.service == SERVICE_TOGGLE:
                yield from alert.async_toggle()
            else:
                yield from alert.async_turn_off()

    # Setup alerts
    for entity_id, alert in alerts.items():
        entity = Alert(hass, entity_id,
                       alert[CONF_NAME], alert[CONF_DONE_MESSAGE],
                       alert[CONF_ENTITY_ID], alert[CONF_STATE],
                       alert[CONF_REPEAT], alert[CONF_SKIP_FIRST],
                       alert[CONF_NOTIFIERS], alert[CONF_CAN_ACK])
        all_alerts[entity.entity_id] = entity

    # Read descriptions
    descriptions = yield from hass.async_add_job(
        load_yaml_config_file, os.path.join(
            os.path.dirname(__file__), 'services.yaml'))
    descriptions = descriptions.get(DOMAIN, {})

    # Setup service calls
    hass.services.async_register(
        DOMAIN, SERVICE_TURN_OFF, async_handle_alert_service,
        descriptions.get(SERVICE_TURN_OFF), schema=ALERT_SERVICE_SCHEMA)
    hass.services.async_register(
        DOMAIN, SERVICE_TURN_ON, async_handle_alert_service,
        descriptions.get(SERVICE_TURN_ON), schema=ALERT_SERVICE_SCHEMA)
    hass.services.async_register(
        DOMAIN, SERVICE_TOGGLE, async_handle_alert_service,
        descriptions.get(SERVICE_TOGGLE), schema=ALERT_SERVICE_SCHEMA)

    tasks = [alert.async_update_ha_state() for alert in all_alerts.values()]
    if tasks:
        yield from asyncio.wait(tasks, loop=hass.loop)

    return True

class Alert(ToggleEntity):
    """Representation of an alert."""

    def __init__(self, hass, entity_id, name, done_message, watched_entity_id,
                 state, repeat, skip_first, notifiers, can_ack):
        """Initialize the alert."""
        self.hass = hass
        self._name = name
        self._alert_state = state
        self._skip_first = skip_first
        self._notifiers = notifiers
        self._can_ack = can_ack
        self._done_message = done_message

        self._delay = [timedelta(minutes=val) for val in repeat]
        self._next_delay = 0

        self._firing = False
        self._ack = False
        self._cancel = None
        self._send_done_message = False
        self.entity_id = ENTITY_ID_FORMAT.format(entity_id)

        event.async_track_state_change(
            hass, watched_entity_id, self.watched_entity_change)

    @property
    def name(self):
        """Return the name of the alert."""
        return self._name

    @property
    def should_poll(self):
        """HASS need not poll these entities."""
        return False

    @property
    def state(self):
        """Return the alert status."""
        if self._firing:
            if self._ack:
                return STATE_OFF
            return STATE_ON
        return STATE_IDLE

    @property
    def hidden(self):
        """Hide the alert when it is not firing."""
        return not self._can_ack or not self._firing

    @asyncio.coroutine
    def watched_entity_change(self, entity, from_state, to_state):
        """Determine if the alert should start or stop."""
        _LOGGER.debug("Watched entity (%s) has changed", entity)
        if to_state.state == self._alert_state and not self._firing:
            yield from self.begin_alerting()
        if to_state.state != self._alert_state and self._firing:
            yield from self.end_alerting()

    @asyncio.coroutine
    def begin_alerting(self):
        """Begin the alert procedures."""
        _LOGGER.debug("Beginning Alert: %s", self._name)
        self._ack = False
        self._firing = True
        self._next_delay = 0

        if not self._skip_first:
            yield from self._notify()
        else:
            yield from self._schedule_notify()

        self.hass.async_add_job(self.async_update_ha_state)

    @asyncio.coroutine
    def end_alerting(self):
        """End the alert procedures."""
        _LOGGER.debug("Ending Alert: %s", self._name)
        self._cancel()
        self._ack = False
        self._firing = False
        if self._done_message and self._send_done_message:
            yield from self._notify_done_message()
        self.hass.async_add_job(self.async_update_ha_state)

    @asyncio.coroutine
    def _schedule_notify(self):
        """Schedule a notification."""
        delay = self._delay[self._next_delay]
        next_msg = datetime.now() + delay
        self._cancel = \
            event.async_track_point_in_time(self.hass, self._notify, next_msg)
        self._next_delay = min(self._next_delay + 1, len(self._delay) - 1)

    @asyncio.coroutine
    def _notify(self, *args):
        """Send the alert notification."""
        if not self._firing:
            return

        if not self._ack:
            _LOGGER.info("Alerting: %s", self._name)
            self._send_done_message = True
            for target in self._notifiers:
                yield from self.hass.services.async_call(
                    'notify', target, {'message': self._name})
        yield from self._schedule_notify()

    @asyncio.coroutine
    def _notify_done_message(self, *args):
        """Send notification of complete alert."""
        _LOGGER.info("Alerting: %s", self._done_message)
        self._send_done_message = False
        for target in self._notifiers:
            yield from self.hass.services.async_call(
                'notify', target, {'message': self._done_message})

    @asyncio.coroutine
    def async_turn_on(self, **kwargs):
        """Async Unacknowledge alert."""
        _LOGGER.debug("Reset Alert: %s", self._name)
        self._ack = False
        yield from self.async_update_ha_state()

    @asyncio.coroutine
    def async_turn_off(self, **kwargs):
        """Async Acknowledge alert."""
        _LOGGER.debug("Acknowledged Alert: %s", self._name)
        self._ack = True
        yield from self.async_update_ha_state()

    @asyncio.coroutine
    def async_toggle(self):
        """Async toggle alert."""
        if self._ack:
            return self.async_turn_on()
        return self.async_turn_off()


text:
/*
 * @file            tracks_request.h
 * @author       Arthur Fait
 * @date          23.05.14
 */

#ifndef TRACKS_REQUEST_H
#define TRACKS_REQUEST_H

#include <memory>
#include <string>
#include <types/track.h>
#include "query.h"

namespace soundcloud {

class requestCurl;
class Parser;

class TracksRequest {
public:
    TracksRequest(const std::string& query);
    ~TracksRequest();

    bool hasNext();
    uint32_t pageNumber() {
        return m_pageNumber;
    }
    std::vector<Track> next();

private:
    uint32_t m_pageNumber;
    std::string m_query;
    std::unique_ptr<requestCurl> m_request;
    std::unique_ptr<Parser> m_parser;
};

} // soundcloud

#endif // TRACKS_REQUEST_H