text:
/******************************************************************************
 * 版权所有 刘大磊 2013-07-01												  *
 *	作者:刘大磊								                                              *
 * 电话:13336390671                                                               *
 * email:ldlqdsd@126.com						                              *
 *****************************************************************************/
package com.delmar.system.web.action;

import com.delmar.base.model.DatadictTrl;
import com.delmar.base.model.DatadictType;
import com.delmar.base.service.DatadictService;
import com.delmar.core.web.action.CoreEditPrivAction;
import com.delmar.core.web.bean.UserResource;
import com.delmar.core.web.util.FacesUtils;
import com.delmar.sys.model.*;
import com.delmar.sys.service.*;
import com.delmar.system.web.WebConst;
import com.delmar.system.web.dwr.UserDwr;
import com.delmar.system.web.model.PrivilegesDataFilter;
import com.delmar.utils.*;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.*;

/**
 * @author 刘大磊 2015年1月16日 下午5:27:52
 */
public class UserAction extends CoreEditPrivAction{
	@Autowired
	private UserService userService;
	private UserDwr userDwr;
	private String passwordConfirm;
	private String oldPassword;
	private String orgString;

	private String roleString;
	private List<Org> orgs;

	private List<Client> clients;

	private List<DatadictTrl> userTypeList;
	private List<UserSubstitute> userSubstituteList;

	private List<Usergroup> usergroupList;

	private List<UsergroupAccess> userGroupaccessList;
	private List<UserorgAccess> userOrgaccessList;
	@Autowired
	private UserRoleService userRoleService;
	@Autowired
	private OrgService orgService;
	@Autowired
	private ClientService clientService;
	@Autowired
	private UserorgAccessService userorgAccessService;
	@Autowired
	private UsergroupService usergroupService;
	@Autowired
	private UsergroupAccessService usergourpAccessService;
	@Autowired
	private UserThirdPartyService userThirdPartyService;
	@Autowired
	private UserExtraService userExtraService;
	@Autowired
	private DatadictService datadictService;

	private User user=new User();

	private File userPic;
	private String userPicContentType;
	private String userPicFileName;

	public String getPurpose()
	{
		return  ResourceMessage.getMessageWithDefault("public.javaaction."+this.getClass().getName(), "用户信息");
	}

	@Override
	public String delete() {

		return this.list();
	}

	@Override
	public void deleteList(Integer[] ids)
	{
		if(ids!=null)
		{
			for(Integer id:ids)
			{
				userService.deleteByPrimaryKey(id);
			}
		}
	}
	/**
	 * 组织和实体是否修改
	 * 当用户选择用户组权限后,组织和实体不允许修改。
	 * @return
	 */
	public boolean isModifyClientOrg()
	{
		if(this.user.isnew())
		{
			return true;
		}
		Map<String,Object> param=new HashMap<String,Object>();
		param.put("userId", user.getId());
		int count=usergourpAccessService.countObjects(param);
		if(count>0)
		{
			return false;
		}
		return true;
	}

	public String saveForm()
	{

		HttpServletRequest request=ServletActionContext.getRequest();

		if(userService.validateUsernameExist(user.getUsername(), user.getId()))
		{
			userInit();
			addActionMessage("该用户名已经存在,保存失败!");
			return EDIT;
		}

		PrivilegesDataFilter up=(PrivilegesDataFilter)FacesUtils.getSession().getAttribute(WebConst.SESSION_USERPRIVILEGES);
		if(user.isnew())
		{
			user.setCreated(new Date());
			user.setCreatedBy(up.getLoginUserId());
			user.setCreatedByName(up.getLoginUser().getName());
			user.setPassNextDate(ProDateUtil.getHisDate(-90));  //密码过期日期
		}

		user.setUpdated(new Date());
		user.setUpdatedBy(up.getLoginUserId());
		user.setUpdatedByName(up.getLoginUser().getName());

		if (user.getIsActive()==null)
			user.setIsActive(1);

				List<Integer> roles=new ArrayList<Integer>();
				String[] rolevalues=request.getParameterValues("roles") ;
				for(String value:rolevalues)
				{
					roles.add(new Integer(value));
				}
				boolean isnew= user.getId() == null;
				if(user.getPassword().length()<30)
				{
					MD5 md5=new MD5();
					user.setPassword(md5.getMD5ofStr(user.getPassword()));

					if (!isnew)   //判断密码是否做过改动,如果改动过,则需要修改密码更改日期
					{
					   if (!oldPassword.equals(user.getPassword()))
  				       {
						   user.setPassNextDate(ProDateUtil.getHisDate(-90));  //密码过期日期
					    }
					}
				}
				String[] ids=request.getParameterValues("ids");

				String[] ugids=request.getParameterValues("ugids");

			Map<String,Object> param=new HashMap<String,Object>();
			param.put("orgId", user.getOrgId());
			usergroupList=	this.usergroupService.selectByExample(param);

			//对User当中的图片进行处理

			if ("image/pjpeg".equals(userPicContentType)
				||("image/gif").equals(userPicContentType)
				||("image/jpeg").equals(userPicContentType)
				||("image/png").equals(userPicContentType))
			{
				String newFileName="user"+user.getId().toString()+userPicFileName.substring(userPicFileName.lastIndexOf("."));
				//在服务器创建文件
				String realpath=ServletActionContext.getServletContext().getRealPath("/userPic");
				File destFile=new File(realpath,newFileName);
				if (!destFile.getParentFile().exists())
					destFile.getParentFile().mkdir();

				try{
					InputStream inStream=new FileInputStream(userPic);
					OutputStream outStream=new FileOutputStream(destFile);
					ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
					byte[] data=new byte[1024];
					int len=0;
					while ((len=inStream.read(data))!=-1)
					{
						outStream.write(data,0,len);
						bos.write(data,0,len);
					}

					outStream.flush();
					outStream.close();
					inStream.close();
					bos.close();

					user.setUserPic(bos.toByteArray());

				} catch (IOException e)
				{
					e.printStackTrace();
				}
			}

				id=this.userService.saveUser(user, roles,ids,ugids);
				if(isnew)
				{
					this.getIdList().add(id);
					addActionMessage("添加用户信息成功!");
				}
				else
				{
					addActionMessage("修改用户信息成功!");
				}

		return edit();
	}
	@Override
	public void createForm() {
		UserResource ur=(UserResource)ServletActionContext.getRequest().getSession().getAttribute("resource");
		user=new User();
		Integer[] ids=null;

		Integer[] ids2=null;
		clients=clientService.selectByExample(null);

		Map<String,Object> param=new HashMap<String,Object>();
		param.put("sysClientId", clients.get(0).getId());
		this.orgs=orgService.selectByExample(param);
		param=new HashMap<String,Object>();
		param.put("orgId", orgs.get(0).getId());
		usergroupList=this.usergroupService.selectByExample(param);
		ids=new Integer[]{orgs.get(0).getId()};
		user.setOrgId(orgs.get(0).getId());

		//Integer[] orgIds,Integer[] roleIds,Integer roleCount
		this.roleString=userDwr.getRoles(ids, ids2, 5);
		passwordConfirm=user.getPassword();
		oldPassword=user.getPassword();

		userTypeList=datadictService.getDatadictTrlByValue(DatadictType.USER_USERTYPE,ur.getLocale().toString());

	}
	@Override
	public void editForm() {
		user=userService.getUserById(id);

		userSubstituteList=userService.getUserSubstituteById(id);

		//Check whether userpic existed or not
		String newFileName="user"+user.getId().toString()+".png";
		String realpath=ServletActionContext.getServletContext().getRealPath("/userPic");
		String fileName=realpath+"/"+newFileName;
		File file2 = new File(fileName);
		if (!file2.getParentFile().exists())
			file2.getParentFile().mkdir();

		//判断文件是否存在并且是一个文件
		if (!(file2.exists() && file2.isFile())){
			ProDirFileUtil.getFile(user.getUserPic(), realpath, newFileName);
		}

		userInit();
	}
	private void userInit()
	{

		UserResource ur=(UserResource)ServletActionContext.getRequest().getSession().getAttribute("resource");

		Integer[] ids=null;

		Integer[] ids2=null;
		List<Role> roles=user.getRoles();
		if(roles==null||roles.size()==0)
		{

			ids2=null;
		}
		else
		{
			ids2=new Integer[roles.size()];
			for(int i=0;i<roles.size();i++)
			{
				ids2[i]=roles.get(i).getId();
			}

		}
		//获取实体列表
		this.clients=this.clientService.selectByExample(null);
		Map<String,Object>param1=new HashMap<String,Object>();
		param1.put("sysClientId", user.getClientId());

		//获取组织列表
		this.orgs=orgService.selectByExample(param1);
		param1=new HashMap<String,Object>();
		param1.put("orgId", user.getOrgId());

		if(user.getOrgId()==null||user.getOrgId()==0)
		{
			ids=new Integer[]{orgs.get(0).getId()};
		}
		else
		{
			ids=new Integer[]{user.getOrgId()};
		}
		//可访问组织列表
		this.userOrgaccessList=new ArrayList<UserorgAccess>();
		for(Org org:this.orgs)
		{
			UserorgAccess uoa=new UserorgAccess();
			uoa.setOrg(org);
			uoa.setOrgId(org.getId());
			userOrgaccessList.add(uoa);
		}

		//得到System List
		userTypeList=datadictService.getDatadictTrlByValue(DatadictType.USER_USERTYPE,ur.getLocale().toString());

		/**
		 * 用户可访问用户组
		 */
		userGroupaccessList=new ArrayList<UsergroupAccess>();

		//可访问用户组
		usergroupList=new ArrayList<Usergroup>();

		if(id!=null&&id!=0)
		{
			//设置可访问组织
			Map param=new HashMap();
			param.put("accessString", " user_id="+id);
			List<UserorgAccess> userorgaccessList=userorgAccessService.selectByExample(param);
			for(UserorgAccess uoa:userOrgaccessList)
			{
				for(UserorgAccess u:userorgaccessList)
				{
					if(uoa.getOrgId().equals(u.getOrgId()))
					{
						uoa.setId(u.getId());
						uoa.setUserId(u.getUserId());
					}
				}
				Map groupMap=new HashMap();
				groupMap.put("orgId", uoa.getOrgId());
				List<Usergroup> orgUsergroupList=usergroupService.selectByExample(groupMap);

				usergroupList.addAll(orgUsergroupList);
			}

			for(Usergroup ug:usergroupList)
			{
				UsergroupAccess ua=new UsergroupAccess();
				ua.setUsergroupId(ug.getId());
				ua.setUserId(id);
				ua.setUsergroup(ug);
				this.userGroupaccessList.add(ua);
			}

			param.put("accessString", "  user_id="+id);
			//设置可访问用户组
			List<UsergroupAccess> usergroupaccessList=this.usergourpAccessService.selectByExample(param);
			for(UsergroupAccess uoa:this.userGroupaccessList)
			{
				for(UsergroupAccess u:usergroupaccessList)
				{
					if(uoa.getUsergroupId().equals(u.getUsergroupId()))
					{
						uoa.setId(u.getId());
						uoa.setUserId(u.getUserId());
					}
				}
			}

		}

		this.roleString=userDwr.getRoles2(ids, ids2, 5);
		passwordConfirm=user.getPassword();

	}
	@Override
	public Integer getModelId() {

		return user.getId();
	}

	@Override
	public String getModuleName() {

		return "user";
	}

	@Override
	public List search() {
		Map<String,Object> param=new HashMap();
		//统一配置查询界面
		//Charels 隐藏掉

/*		SearchColumnList searchColumnList=(SearchColumnList)FacesUtils.getValueInHashtableOfSession("searchColumnList");
		if(searchColumnList!=null)
		{
			param.put("accessString", searchColumnList.buildSql());
		}*/
		param.put("searchString",getSearchWhere());
		StringBuilder sb=new StringBuilder();

		HttpServletRequest request=ServletActionContext.getRequest();
		String invalid=request.getParameter("invalid");
		FacesUtils.setValueInHashtableOfSession("invalid", invalid);
		if (StringUtil.isEmpty(invalid))  //是否包含作废的
			FacesUtils.setValueInHashtableOfSession("invalid", "N");

		if (StringUtil.isEmpty(invalid))  //是否包含作废的
		{
			sb.append(" and IsActive=1 ");
		}

         String name=request.getParameter("name");
         FacesUtils.setValueInHashtableOfSession("name", name);
		if (StringUtil.isNotEmpty(name))  //是否包含作废的
		{
			sb.append(" and name like '%").append(StringUtil.fullYhStr(name)).append("%' ");
		}

		if (sb.length()>0)
			param.put("accessString", sb.toString());

		return userService.getUsers(param);
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public void setUserDwr(UserDwr userDwr) {
		this.userDwr = userDwr;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String getPasswordConfirm() {
		return passwordConfirm;
	}

	public void setPasswordConfirm(String passwordConfirm) {
		this.passwordConfirm = passwordConfirm;
	}

	/**
	 * @return the orgString
	 */
	public String getOrgString() {
		return orgString;
	}

	/**
	 * @param orgString the orgString to set
	 */
	public void setOrgString(String orgString) {
		this.orgString = orgString;
	}

	public String getRoleString() {
		return roleString;
	}

	public void setRoleString(String roleString) {
		this.roleString = roleString;
	}
	/**
	 * @return the orgs
	 */
	public List<Org> getOrgs() {
		return orgs;
	}

	/**
	 * @param orgs the orgs to set
	 */
	public void setOrgs(List<Org> orgs) {
		this.orgs = orgs;
	}
	/**
	 * @return the userOrgaccessList
	 */
	public List<UserorgAccess> getUserOrgaccessList() {
		return userOrgaccessList;
	}

	/**
	 * @param userOrgaccessList the userOrgaccessList to set
	 */
	public void setUserOrgaccessList(List<UserorgAccess> userOrgaccessList) {
		this.userOrgaccessList = userOrgaccessList;
	}

	/**
	 * @return the clients
	 */
	public List<Client> getClients() {
		return clients;
	}

	/**
	 * @param clients the clients to set
	 */
	public void setClients(List<Client> clients) {
		this.clients = clients;
	}
	/**
	 * @return the usergroupList
	 */
	public List<Usergroup> getUsergroupList() {
		return usergroupList;
	}

	/**
	 * @param usergroupList the usergroupList to set
	 */
	public void setUsergroupList(List<Usergroup> usergroupList) {
		this.usergroupList = usergroupList;
	}

	/**
	 * @return the userGroupaccessList
	 */
	public List<UsergroupAccess> getUserGroupaccessList() {
		return userGroupaccessList;
	}

	/**
	 * @param userGroupaccessList the userGroupaccessList to set
	 */
	public void setUserGroupaccessList(List<UsergroupAccess> userGroupaccessList) {
		this.userGroupaccessList = userGroupaccessList;
	}

	public File getUserPic() {
		return userPic;
	}

	public void setUserPic(File userPic) {
		this.userPic = userPic;
	}

	public String getUserPicContentType() {
		return userPicContentType;
	}

	public void setUserPicContentType(String userPicContentType) {
		this.userPicContentType = userPicContentType;
	}

	public String getUserPicFileName() {
		return userPicFileName;
	}

	public void setUserPicFileName(String userPicFileName) {
		this.userPicFileName = userPicFileName;
	}

	public List<DatadictTrl> getUserTypeList() {
		return userTypeList;
	}

	public void setUserTypeList(List<DatadictTrl> userTypeList) {
		this.userTypeList = userTypeList;
	}

	public String getOldPassword() {
		return oldPassword;
	}

	public void setOldPassword(String oldPassword) {
		this.oldPassword = oldPassword;
	}

	public List<UserSubstitute> getUserSubstituteList() {
		return userSubstituteList;
	}

	public void setUserSubstituteList(List<UserSubstitute> userSubstituteList) {
		this.userSubstituteList = userSubstituteList;
	}

}


text:
package com.facebook.infrastructure.net.sink;

import com.facebook.infrastructure.net.Message;

/**
 * Author : Avinash Lakshman ( alakshman@facebook.com) & Prashant Malik (
 * pmalik@facebook.com )
 */

public interface IMessageSink {
  public Message handleMessage(Message message);
}

redpajama_set_name: RedPajamaGithub


text:
@interface OTTableView()<MTTableViewSectionIndexBarDelegate>

@end

@implementation OTTableView
@dynamic dataSource;
@dynamic delegate;

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    [self handlePoint:point event:event];
    return [super hitTest:point withEvent:event];
}

- (void)handlePoint:(CGPoint)point event:(UIEvent *)event
{
    __block UITableViewCell *touchCell;
    [self.visibleCells enumerateObjectsUsingBlock:^(__kindof UITableViewCell * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (CGRectContainsPoint(obj.frame, point)) {
            touchCell = obj;
            *stop = YES;
        }
    }];

    if (touchCell) {
        NSIndexPath *indexPath = [self indexPathForCell:touchCell];
        if ([self.delegate respondsToSelector:@selector(visibleCellRespondEventAtIndexPath:event:)]) {
            [self.delegate visibleCellRespondEventAtIndexPath:indexPath event:event];
        }
    }
}

- (void)sectionIndexBar:(MTTableViewSectionIndexBar *)sectionIndexBar sectionDidSelected:(NSUInteger)index title:(NSString *)title{
    [self scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:index] atScrollPosition:UITableViewScrollPositionTop animated:NO];
}

- (void)reloadData
{
    [super reloadData];
    if ([self.dataSource respondsToSelector:@selector(customSectionIndexTitlesForTableView:)]) {
        NSArray <NSString *>*sectionTitles = [self.dataSource customSectionIndexTitlesForTableView:self];
        self.mtSectionIndexBarDataSource = sectionTitles;

    }
}

@end


text:
@interface SelectScene : CCScene
{
    GameManager *manager;
}

- (instancetype)init;

@end


text:
LabelPositions::LabelPositions(std::map<int, Eigen::Vector3f> positionsNDC,
                               std::map<int, Eigen::Vector3f> positions3d)
  : positionsNDC(positionsNDC), positions3d(positions3d)
{
}

void LabelPositions::update(int labelId, Eigen::Vector3f positionNDC,
                            Eigen::Vector3f position3d)
{
  positionsNDC[labelId] = positionNDC;
  positions3d[labelId] = position3d;
}

int LabelPositions::size() const
{
  return positionsNDC.size();
}

int LabelPositions::count(int labelId) const
{
  return positionsNDC.count(labelId);
}

Eigen::Vector3f LabelPositions::getNDCFor(int labelId) const
{
  return positionsNDC.at(labelId);
}

Eigen::Vector3f LabelPositions::get3dFor(int labelId) const
{
  return positions3d.at(labelId);
}


text:
set -e

source scripts/language_environment.sh "$@"

which sqlite3
which diff

{
    cat<<EOF
CREATE TABLE t1 (id INTEGER PRIMARY KEY, name TEXT);
INSERT INTO t1 VALUES(1,"test");
CREATE TABLE t2 (id INTEGER PRIMARY KEY, count INTEGER, note TEXT);
INSERT INTO t2 VALUES(1,15,"hello");
INSERT INTO t2 VALUES(2,82,"world");
EOF
} | sqlite3 v1.sqlite

{
    cat<<EOF
CREATE TABLE t1 (id INTEGER PRIMARY KEY, name TEXT);
INSERT INTO t1 VALUES(1,"testy");
CREATE TABLE t2 (id INTEGER PRIMARY KEY, count INTEGER, note TEXT);
INSERT INTO t2 VALUES(1,15,"hello");
INSERT INTO t2 VALUES(3,64,"space");
EOF
} | sqlite3 v2.sqlite

{
    cat<<EOF
CREATE TABLE t2 (id INTEGER PRIMARY KEY, count INTEGER, note TEXT);
INSERT INTO t2 VALUES(1,15,"hello");
INSERT INTO t2 VALUES(2,82,"world");
INSERT INTO t2 VALUES(4,101,"news");
EOF
} | sqlite3 v3.sqlite

{
    cat<<EOF
CREATE TABLE birds (id INTEGER PRIMARY KEY, name TEXT, count TEXT);
INSERT INTO birds VALUES(1,"robin","251");
INSERT INTO birds VALUES(2,"eagle","10");
INSERT INTO birds VALUES(3,"pigeon","140");
EOF
} | sqlite3 birds_v1.sqlite

{
    cat<<EOF
CREATE TABLE birds (id INTEGER PRIMARY KEY, name TEXT, count INTEGER, weather TEXT);
INSERT INTO birds VALUES(1,"robin",251,"warm");
INSERT INTO birds VALUES(2,"eagle",10,"");
INSERT INTO birds VALUES(3,"pigeon",140,"");
INSERT INTO birds VALUES(4,"penguin",5,"cold");
EOF
} | sqlite3 birds_v2.sqlite

{
    cat<<EOF
CREATE TABLE birds (id INTEGER PRIMARY KEY, name TEXT, count TEXT);
INSERT INTO birds VALUES(1,"robin","251");
INSERT INTO birds VALUES(2,"eagle","10");
INSERT INTO birds VALUES(3,"pigeon","140");

CREATE TABLE birds2 (id INTEGER PRIMARY KEY, name TEXT, count INTEGER, weather TEXT);
INSERT INTO birds2 VALUES(1,"robin",251,"warm");
INSERT INTO birds2 VALUES(2,"eagle",10,"");
INSERT INTO birds2 VALUES(3,"pigeon",140,"");
INSERT INTO birds2 VALUES(4,"penguin",5,"cold");
EOF
} | sqlite3 birds_v12.sqlite

{
    cat<<EOF
CREATE TABLE birds (id INTEGER, name TEXT, count TEXT);
INSERT INTO birds VALUES(1,"robin","251");
INSERT INTO birds VALUES(2,"eagle","10");
INSERT INTO birds VALUES(3,"pigeon","140");

CREATE TABLE birds2 (id INTEGER, name TEXT, count INTEGER, weather TEXT);
INSERT INTO birds2 VALUES(1,"robin",251,"warm");
INSERT INTO birds2 VALUES(2,"eagle",10,"");
INSERT INTO birds2 VALUES(3,"pigeon",140,"");
INSERT INTO birds2 VALUES(4,"penguin",5,"cold");
EOF
} | sqlite3 birds_v12_no_key.sqlite

function run_diff {
    v1="$1"
    v2="$2"
    ref_diff="$3"
    save_diff="$4"
    shift
    shift
    shift
    shift
    $DAFF_SCRIPT $v1 $v2 "$@" > $save_diff
    echo ""
    echo "$v1 -> $v2 ($save_diff)"
    $DAFF_SCRIPT $v1 $v2 "$@" # run separately to see color
    if [ -e $org/test/sqlite/${ref_diff} ]; then
        diff -w ${save_diff} $org/test/sqlite/${ref_diff} || {
            echo "${save_diff} not created correctly."
            exit 1
        } && {
            echo "${save_diff} created correctly."
        }
    else
        echo "${save_diff} has nothing to compare with."
    fi
}

run_diff v1.sqlite v2.sqlite basic.diff basic.diff
run_diff v1.sqlite v3.sqlite remove_table.diff remove_table.diff
run_diff v3.sqlite v1.sqlite add_table.diff add_table.diff
run_diff birds_v1.sqlite birds_v2.sqlite type_change.diff type_change.diff
run_diff $org/test/sqlite/blank.sqlite $org/test/sqlite/awkward.sqlite create_all.diff create_all.diff
if [ "$DAFF_LANGUAGE" = "js" ]; then
    # only have energy to tweak this on js for the moment
    run_diff $org/test/sqlite/blobby1.sqlite $org/test/sqlite/blobby2.sqlite with_blobs.diff with_blobs.diff
fi

run_diff birds_v12.sqlite birds_v12.sqlite type_change.diff type_change_v12.diff --table birds:birds2

run_diff birds_v12_no_key.sqlite birds_v12_no_key.sqlite type_change.diff \
  type_change_v12_no_key.diff --table birds:birds2 --id id


text:
package gov.nih.nci.nbia.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public final class DicomFileSizeCorrectorUtil {
    private static final int elementsPerExecute = 1000;
    private static Logger logger = Logger
            .getLogger(DicomFileSizeCorrectorUtil.class);
    private String connectionUrl;
    private String driverClass;
    private String userName;
    private String password;

    public String getConnectionUrl() {
        return connectionUrl;
    }

    public void setConnectionUrl(String connectionUrl) {
        this.connectionUrl = connectionUrl;
    }

    public String getDriverClass() {
        return driverClass;
    }

    public void setDriverClass(String driverClass) {
        this.driverClass = driverClass;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        String LOG_FILE = "dbUpdatorLog4j.properties";
        String PROP_FILE = "dbUpdator.properties";
        Properties logProp = new Properties();
        ClassLoader classLoader = DicomFileSizeCorrectorUtil.class
                .getClassLoader();
        try {
            logProp.load(classLoader.getResourceAsStream(LOG_FILE));
            PropertyConfigurator.configure(logProp);
            System.out.println("Logging enabled");
            logger.info("Logging enabled");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Logging not enabled");
        }
        Properties prop = new Properties();
        try {
            // load a properties file from class path, inside static method
            prop.load(classLoader.getResourceAsStream(PROP_FILE));
            // get the property value and print it out
            String mysqlDriverClass = prop
                    .getProperty("connection.driver_class");
            logger.info("mysqlDriverClass:-" + mysqlDriverClass);
            String databaseConnectionUrl = prop.getProperty("connection.url");
            logger.info("databaseConnectionUrl:-" + databaseConnectionUrl);
            String dbUserName = prop.getProperty("connection.username");
            logger.info("dbUserName:-" + dbUserName);
            String dbPassword = prop.getProperty("connection.password");
            DicomFileSizeCorrectorUtil sizeCorrector = new DicomFileSizeCorrectorUtil();
            sizeCorrector.setConnectionUrl(databaseConnectionUrl);
            sizeCorrector.setDriverClass(mysqlDriverClass);
            sizeCorrector.setUserName(dbUserName);
            sizeCorrector.setPassword(dbPassword);
            sizeCorrector.runFileSizeCorrector();
        } catch (IOException ex) {
            ex.printStackTrace();
            logger.error(ex.getMessage());
        }
    }

    private Connection getJDBCConnection() throws ClassNotFoundException,
            SQLException {
        // Load the JDBC-ODBC bridge
        Class.forName(driverClass);
        // specify the ODBC data source's URL
        return DriverManager.getConnection(connectionUrl, userName, password);
    }

    public void runFileSizeCorrector() {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            Connection con = getJDBCConnection();
            con.setAutoCommit(false);
            Statement stmt = con.createStatement();
            ResultSet rs = stmt
                    .executeQuery("Select image_pk_id,dicom_file_uri,dicom_size from general_image order by image_pk_id asc");
            logger.info("looping through......");
            int batchSize = 0;
            // String sql =
            // "UPDATE general_image SET dicom_size =? , md5_digest=? where image_pk_id=?";
            String sql = "UPDATE general_image SET dicom_size =? where image_pk_id=?";
            PreparedStatement prepStmt = con.prepareStatement(sql);
            while (rs.next()) {
                String imageId = rs.getString(1);
                String storedFileName = rs.getString(2);
                long storedFileSize = rs.getLong(3);
                File storedFile = new File(storedFileName);
                if (!storedFile.exists()) {
                    logger.info("Current file Name: " + storedFileName
                            + " was not found...");
                } else if (storedFileSize != storedFile.length()) {
                    logger.info("File size mismatch####### " + imageId + "|| "
                            + storedFileName + " || " + storedFileSize);
                    setCorrectFileSize(prepStmt, storedFile, imageId, md);
                    batchSize++;
                    if (batchSize == elementsPerExecute) {
                        excuteBatchStmt(prepStmt);
                        batchSize = 0;
                        con.commit();
                    }
                } else {
                    // Do nothing
                    // System.out.println("file size is same.....");
                }
            }
            // final update
            excuteBatchStmt(prepStmt);
            // close statement and connection
            con.commit();
            prepStmt.close();
            stmt.close();
            con.close();
        } catch (java.lang.Exception ex) {
            logger.info("Error occured:-" + ex.getMessage());
            return;
        }
        logger.info("DICOM File size correction has been completed....");
    }

    private void excuteBatchStmt(PreparedStatement prepStmt)
            throws SQLException {
        logger.info("doing batch update...");
        prepStmt.executeBatch();
        prepStmt.clearBatch();
    }

    private void setCorrectFileSize(PreparedStatement stmt, File file,
            String imageId, MessageDigest md) throws Exception {
        long actualFileSize = file.length();
        FileInputStream fIs = new FileInputStream(file);
        try {
            // String md5 = getDigest(fIs, md);
            // logger.info("updated filesize " + actualFileSize + "updated md5 "
            // + md5);
            logger.info("updated filesize " + actualFileSize);
            stmt.setBigDecimal(1, BigDecimal.valueOf(actualFileSize));
            // stmt.setString(2, md5);
            stmt.setString(2, imageId);
            stmt.addBatch();
        } catch (Exception ex) {
            logger.error("update failed for imageId " + imageId
                    + " exception is:- " + ex.getMessage());
        } finally {
            fIs.close();
        }
    }

    // private String getDigest(InputStream is, MessageDigest md)
    // throws NoSuchAlgorithmException, IOException {
    // int byteArraySize = 2048;
    // md.reset();
    // byte[] bytes = new byte[byteArraySize];
    // int numBytes;
    // while ((numBytes = is.read(bytes)) != -1) {
    // md.update(bytes, 0, numBytes);
    // }
    // byte[] digest = md.digest();
    // String result = new String(Hex.encodeHex(digest));
    // return result == null ? " " : result;
    // }
}


text:
package com.plexobject.order;

import java.util.Collection;

import javax.jws.WebService;

@WebService
public interface OrderService {
    Order create(Order order);

    Order get(long orderId);

    Collection<Order> findByAccounts(long accountId);
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Uppy example: Redux</title>

A counter

          Clicked: 0 times
          <button id="increment">+</button>
          <button id="decrement">-</button>
          <button id="incrementIfOdd">Increment if odd</button>
          <button id="incrementAsync">Increment async</button>

An Uppy

    <link href="uppy.min.css" rel="stylesheet">


text:
namespace content {

class ServiceWorkerURLRequestJobTest;

namespace {

const int kProcessID = 1;
const int kProviderID = 100;
const char kTestData[] = "Here is sample text for the blob.";

class MockHttpProtocolHandler
    : public net::URLRequestJobFactory::ProtocolHandler {
 public:
  MockHttpProtocolHandler(
      base::WeakPtr<ServiceWorkerProviderHost> provider_host,
      base::WeakPtr<webkit_blob::BlobStorageContext> blob_storage_context)
      : provider_host_(provider_host),
        blob_storage_context_(blob_storage_context) {}
  virtual ~MockHttpProtocolHandler() {}

  virtual net::URLRequestJob* MaybeCreateJob(
      net::URLRequest* request,
      net::NetworkDelegate* network_delegate) const OVERRIDE {
    ServiceWorkerURLRequestJob* job = new ServiceWorkerURLRequestJob(
        request, network_delegate, provider_host_, blob_storage_context_);
    job->ForwardToServiceWorker();
    return job;
  }

 private:
  base::WeakPtr<ServiceWorkerProviderHost> provider_host_;
  base::WeakPtr<webkit_blob::BlobStorageContext> blob_storage_context_;
};

// Returns a BlobProtocolHandler that uses |blob_storage_context|. Caller owns
// the memory.
webkit_blob::BlobProtocolHandler* CreateMockBlobProtocolHandler(
    webkit_blob::BlobStorageContext* blob_storage_context) {
  // The FileSystemContext and MessageLoopProxy are not actually used but a
  // MessageLoopProxy is needed to avoid a DCHECK in BlobURLRequestJob ctor.
  return new webkit_blob::BlobProtocolHandler(
      blob_storage_context, NULL, base::MessageLoopProxy::current().get());
}

}  // namespace

class ServiceWorkerURLRequestJobTest : public testing::Test {
 protected:
  ServiceWorkerURLRequestJobTest()
      : thread_bundle_(TestBrowserThreadBundle::IO_MAINLOOP),
        blob_data_(new webkit_blob::BlobData("blob-id:myblob")) {}
  virtual ~ServiceWorkerURLRequestJobTest() {}

  virtual void SetUp() OVERRIDE {
    browser_context_.reset(new TestBrowserContext);
    SetUpWithHelper(new EmbeddedWorkerTestHelper(kProcessID));
  }

  void SetUpWithHelper(EmbeddedWorkerTestHelper* helper) {
    helper_.reset(helper);

    registration_ = new ServiceWorkerRegistration(
        GURL("http://example.com/*"),
        GURL("http://example.com/service_worker.js"),
        1L,
        helper_->context()->AsWeakPtr());
    version_ = new ServiceWorkerVersion(
        registration_, 1L, helper_->context()->AsWeakPtr());

    scoped_ptr<ServiceWorkerProviderHost> provider_host(
        new ServiceWorkerProviderHost(
            kProcessID, kProviderID, helper_->context()->AsWeakPtr(), NULL));
    provider_host->SetActiveVersion(version_.get());

    ChromeBlobStorageContext* chrome_blob_storage_context =
        ChromeBlobStorageContext::GetFor(browser_context_.get());
    // Wait for chrome_blob_storage_context to finish initializing.
    base::RunLoop().RunUntilIdle();
    webkit_blob::BlobStorageContext* blob_storage_context =
        chrome_blob_storage_context->context();

    url_request_job_factory_.reset(new net::URLRequestJobFactoryImpl);
    url_request_job_factory_->SetProtocolHandler(
        "http",
        new MockHttpProtocolHandler(provider_host->AsWeakPtr(),
                                    blob_storage_context->AsWeakPtr()));
    url_request_job_factory_->SetProtocolHandler(
        "blob", CreateMockBlobProtocolHandler(blob_storage_context));
    url_request_context_.set_job_factory(url_request_job_factory_.get());

    helper_->context()->AddProviderHost(provider_host.Pass());
  }

  virtual void TearDown() OVERRIDE {
    version_ = NULL;
    registration_ = NULL;
    helper_.reset();
  }

  void TestRequest(int expected_status_code,
                   const std::string& expected_status_text,
                   const std::string& expected_response,
                   const std::map<std::string, std::string>& expected_headers) {
    request_ = url_request_context_.CreateRequest(
        GURL("http://example.com/foo.html"),
        net::DEFAULT_PRIORITY,
        &url_request_delegate_,
        NULL);

    request_->set_method("GET");
    request_->Start();
    base::RunLoop().RunUntilIdle();
    EXPECT_TRUE(request_->status().is_success());
    EXPECT_EQ(expected_status_code,
              request_->response_headers()->response_code());
    EXPECT_EQ(expected_status_text,
              request_->response_headers()->GetStatusText());
    for (std::map<std::string, std::string>::const_iterator
             i = expected_headers.begin(); i != expected_headers.end(); ++i) {
      EXPECT_TRUE(request_->response_headers()->HasHeaderValue(i->first,
                                                               i->second));
    }
    EXPECT_EQ(expected_response, url_request_delegate_.response_data());
  }

  void TestRequest(int expected_status_code,
                   const std::string& expected_status_text,
                   const std::string& expected_response) {
    TestRequest(expected_status_code, expected_status_text, expected_response,
                std::map<std::string, std::string>());
  }

  TestBrowserThreadBundle thread_bundle_;

  scoped_ptr<TestBrowserContext> browser_context_;
  scoped_ptr<EmbeddedWorkerTestHelper> helper_;
  scoped_refptr<ServiceWorkerRegistration> registration_;
  scoped_refptr<ServiceWorkerVersion> version_;

  scoped_ptr<net::URLRequestJobFactoryImpl> url_request_job_factory_;
  net::URLRequestContext url_request_context_;
  MockURLRequestDelegate url_request_delegate_;
  scoped_ptr<net::URLRequest> request_;

  scoped_refptr<webkit_blob::BlobData> blob_data_;

  DISALLOW_COPY_AND_ASSIGN(ServiceWorkerURLRequestJobTest);
};

TEST_F(ServiceWorkerURLRequestJobTest, Simple) {
  version_->SetStatus(ServiceWorkerVersion::ACTIVATED);
  TestRequest(200, "OK", std::string());
}

// Responds to fetch events with a blob.
class BlobResponder : public EmbeddedWorkerTestHelper {
 public:
  BlobResponder(int mock_render_process_id, const std::string& blob_uuid)
      : EmbeddedWorkerTestHelper(mock_render_process_id),
        blob_uuid_(blob_uuid) {}
  virtual ~BlobResponder() {}

 protected:
  virtual void OnFetchEvent(int embedded_worker_id,
                            int request_id,
                            const ServiceWorkerFetchRequest& request) OVERRIDE {
    SimulateSend(new ServiceWorkerHostMsg_FetchEventFinished(
        embedded_worker_id,
        request_id,
        SERVICE_WORKER_FETCH_EVENT_RESULT_RESPONSE,
        ServiceWorkerResponse(200,
                              "OK",
                              std::map<std::string, std::string>(),
                              blob_uuid_)));
  }

  std::string blob_uuid_;
  DISALLOW_COPY_AND_ASSIGN(BlobResponder);
};

TEST_F(ServiceWorkerURLRequestJobTest, BlobResponse) {
  ChromeBlobStorageContext* blob_storage_context =
      ChromeBlobStorageContext::GetFor(browser_context_.get());
  std::string expected_response;
  for (int i = 0; i < 1024; ++i) {
    blob_data_->AppendData(kTestData);
    expected_response += kTestData;
  }
  scoped_ptr<webkit_blob::BlobDataHandle> blob_handle =
      blob_storage_context->context()->AddFinishedBlob(blob_data_);
  SetUpWithHelper(new BlobResponder(kProcessID, blob_handle->uuid()));

  version_->SetStatus(ServiceWorkerVersion::ACTIVATED);
  TestRequest(200, "OK", expected_response);
}

TEST_F(ServiceWorkerURLRequestJobTest, NonExistentBlobUUIDResponse) {
  SetUpWithHelper(new BlobResponder(kProcessID, "blob-id:nothing-is-here"));
  version_->SetStatus(ServiceWorkerVersion::ACTIVATED);
  TestRequest(500, "Service Worker Response Error", std::string());
}

TEST_F(ServiceWorkerURLRequestJobTest, FetchGeneratedResponse) {
  ChromeBlobStorageContext* blob_storage_context =
      ChromeBlobStorageContext::GetFor(browser_context_.get());
  std::string expected_response;
  for (int i = 0; i < 1024; ++i) {
    blob_data_->AppendData(kTestData);
    expected_response += kTestData;
  }
  scoped_ptr<webkit_blob::BlobDataHandle> blob_handle =
      blob_storage_context->context()->AddFinishedBlob(blob_data_);
  SetUpWithHelper(new BlobResponder(kProcessID, blob_handle->uuid()));

  version_->SetStatus(ServiceWorkerVersion::ACTIVATED);

  std::map<std::string, std::string> expected_headers;
  expected_headers["Service-Worker"] = "generated";

  TestRequest(200, "OK", expected_response, expected_headers);
}

// TODO(kinuko): Add more tests with different response data and also for
// FallbackToNetwork case.

}  // namespace content


text:
package org.apache.streams.fullcontact;

import org.apache.streams.fullcontact.api.EnrichCompanyRequest;
import org.apache.streams.fullcontact.pojo.CompanySummary;

import org.apache.juneau.http.annotation.Body;
import org.apache.juneau.remote.RemoteInterface;
import org.apache.juneau.rest.client.remote.RemoteMethod;

@RemoteInterface(path = "https://api.fullcontact.com/v3/company.enrich")
public interface CompanyEnrichment {

  @RemoteMethod(method ="POST")
  public CompanySummary enrichCompany(@Body EnrichCompanyRequest request);

}


text:
<?php

class Aitsu_Persistence_Lastopened extends Aitsu_Persistence_Abstract {

	protected $_userid = null;
	protected $_idart = null;
	protected $_idlang = null;
	protected $_data = null;

	protected function __construct($idart) {

		$this->_userid = Aitsu_Adm_User :: getInstance()->getId();
		$this->_idart = $idart;
		$this->_idlang = Aitsu_Registry :: get()->session->currentLanguage;
	}

	public static function factory($id = null) {

		static $instance = array ();

		if (!isset ($instance[$id])) {
			$instance[$id] = new self($id);
		}

		return $instance[$id];
	}

	public function load() {

		if ($this->_data !== null) {
			return $this;
		}

		$this->_data = Aitsu_Db :: fetchAll('' .
		'select ' .
		'	artlang.*, ' .
		'	catlang.* ' .
		'from _lastopened as lopen ' .
		'left join _art_lang as artlang on lopen.idart = artlang.idart and lopen.idlang = artlang.idlang ' .
		'left join _cat_art as catart on artlang.idart = catart.idart ' .
		'left join _cat_lang as catlang on catart.idcat = catlang.idcat and catlang.idlang = artlang.idlang ' .
		'where ' .
		'	lopen.userid = :userid ' .
		'	and artlang.idlang = :idlang ' .
		'order by ' .
		'	lopen.time desc ' .
		'limit 0, 100', array (
			':userid' => $this->_userid,
			':idlang' => $this->_idlang
		));

		return $this;
	}

	public function get($limit = 12) {

		return array_slice($this->_data, 0, $limit);
	}

	public function __get($key) {

		if ($this->_data === null) {
			$this->load();
		}

		if (!isset ($this->_data[$key])) {
			return null;
		}

		return stripslashes($this->_data[$key]);
	}

	public function __set($key, $value) {

		if ($this->_data === null) {
			$this->_data = array ();
		}

		$this->_data[$key] = $value;
	}

	public function save() {

		Aitsu_Db :: query('' .
		'insert into _lastopened (idart, idlang, userid, time) ' .
		'values (:idart, :idlang, :userid, now()) ' .
		'on duplicate key update time = now()', array (
			':idart' => $this->_idart,
			':idlang' => $this->_idlang,
			':userid' => $this->_userid
		));

		return $this;
	}

	public function remove() {

		return $this;
	}

}


text:
// <copyright file="EqualsOverrideOtherSuccessiveAssertionTests.cs" company="natsnudasoft">
// Copyright (c) Adrian John Dunstan. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>

namespace Natsnudasoft.NatsnudasoftTests.TestExtension
{
    using System;
    using System.Collections.Generic;
    using AutoFixture;
    using AutoFixture.Idioms;
    using AutoFixture.Kernel;
    using Moq;
    using Natsnudasoft.NatsnudaLibrary.TestExtensions;
    using Natsnudasoft.NatsnudasoftTests.Helper;
    using Xunit;
    using SutAlias =
        Natsnudasoft.NatsnudaLibrary.TestExtensions.EqualsOverrideOtherSuccessiveAssertion;

    public sealed class EqualsOverrideOtherSuccessiveAssertionTests
    {
        private static readonly Type SutType = typeof(SutAlias);
        private static readonly Type TestHelperType = typeof(EqualsOverrideAssertionVerifyHelper);

        [Fact]
        public void ConstructorHasCorrectGuardClauses()
        {
            var fixture = new Fixture();
            var assertion = new GuardClauseAssertion(fixture);

            assertion.Verify(SutType.GetConstructors());
        }

        [Fact]
        public void ConstructorSetsCorrectInitializedMembers()
        {
            var fixture = new Fixture();
            var assertion = new ConstructorInitializedMemberAssertion(fixture);

            assertion.Verify(SutType.GetProperty(nameof(EqualsOverrideAssertion.SpecimenBuilder)));
        }

        [Fact]
        public void ConstructorDoesNotThrow()
        {
            var ex = Record.Exception(() => new SutAlias(new Mock<ISpecimenBuilder>().Object));

            Assert.Null(ex);
        }

        [Fact]
        public void VerifyEqualsMethodWithObjectParameterTypeDoesNotInvokeEquals()
        {
            var fixture = new Fixture();
            var verifyHelperMock = new Mock<EqualsOverrideAssertionVerifyHelper>(false, true, false)
            {
                CallBase = true,
            };
            fixture.Inject(verifyHelperMock.Object);
            var sut = fixture.Create<SutAlias>();

            sut.Verify(TestHelperType.GetMethod(
                nameof(EqualsOverrideAssertionVerifyHelper.Equals),
                new[] { typeof(object) }));

            verifyHelperMock.Verify(h => h.Equals(It.IsAny<object>()), Times.Never());
        }

        [Fact]
        public void VerifyEqualsMethodViolatesEqualsSuccessiveContractThrows()
        {
            var fixture = new Fixture();
            var equalsResultQueue = new Queue<bool>(new[] { true, false, true });
            var verifyHelperQueue = new Queue<EqualsOverrideAssertionVerifyHelper>(new[]
            {
                new EqualsOverrideAssertionVerifyHelper(false, false, false),
                new EqualsOverrideAssertionVerifyHelper(
                    false,
                    false,
                    () => equalsResultQueue.Dequeue()),
            });
            fixture.Register(() => verifyHelperQueue.Dequeue());
            var sut = fixture.Create<SutAlias>();

            var ex = Record.Exception(() => sut.Verify(TestHelperType.GetMethod(
                nameof(EqualsOverrideAssertionVerifyHelper.Equals),
                new[] { typeof(EqualsOverrideAssertionVerifyHelper) })));

            Assert.IsType<EqualsOverrideException>(ex);
        }

        [Fact]
        public void VerifyEqualsMethodCorrectBehaviourInvokesEquals()
        {
            var fixture = new Fixture();
            var verifyHelperMock = new Mock<EqualsOverrideAssertionVerifyHelper>(false, false, true)
            {
                CallBase = true,
            };
            var verifyHelperQueue = new Queue<EqualsOverrideAssertionVerifyHelper>(new[]
            {
                verifyHelperMock.Object,
                new EqualsOverrideAssertionVerifyHelper(false, false, true),
            });
            fixture.Register(() => verifyHelperQueue.Dequeue());
            var sut = fixture.Create<SutAlias>();

            sut.Verify(TestHelperType.GetMethod(
                nameof(EqualsOverrideAssertionVerifyHelper.Equals),
                new[] { typeof(EqualsOverrideAssertionVerifyHelper) }));

            verifyHelperMock.Verify(
                h => h.Equals(It.IsAny<EqualsOverrideAssertionVerifyHelper>()),
                Times.Exactly(3));
        }
    }
}


text:
package syntaxtree;
import visitor.Visitor;

/**
 * a default-label within a switch statement
 */
public class Default extends Label {

	/**
	 * constructor
	 * @param pos file position
	 */
	public Default(int pos) {
		super(pos);
	}

	/*************** remaining methods are visitor- and display-related ****************/

	public Object accept(Visitor v) {
		return v.visitDefault(this);
	}

}


text:
<?xml version="1.0"?>
<!--

-->
<config>
    <acl>
        <resources>
            <admin>
                <children>
                    <system>
                        <children>
                            <config>
                                <children>
                                    <banners_nikolai translate="title" module="banners_nikolai">
                                        <title>Nikolai</title>
                                    </banners_nikolai>
                                </children>
                            </config>
                        </children>
                    </system>
                    <banners_nikolai translate="title" module="banners_nikolai">
                        <title>Banners DT Store</title>
                        <children>
                            <bannerdt translate="title" module="banners_nikolai">
                                <title>Banner DT Store</title>
                                <sort_order>0</sort_order>
                            </bannerdt>
                        </children>
                    </banners_nikolai>
                </children>
            </admin>
        </resources>
    </acl>
    <menu>
        <banners_nikolai translate="title" module="banners_nikolai">
            <title>Banners DT Store</title>
            <sort_order>22</sort_order>
            <children>
                <bannerdt translate="title" module="banners_nikolai">
                    <title>Banner DT Store</title>
                    <action>adminhtml/nikolai_bannerdt</action>
                    <sort_order>0</sort_order>
                </bannerdt>
            </children>
        </banners_nikolai>
    </menu>
</config>


text:
'use strict';
// https://github.com/tc39/proposal-iterator-helpers
var $ = require('../internals/export');
var anObject = require('../internals/an-object');
var createAsyncIteratorProxy = require('../internals/create-async-iterator-proxy');

var AsyncIteratorProxy = createAsyncIteratorProxy(function (arg, Promise) {
  var state = this;
  var iterator = state.iterator;

  return Promise.resolve(anObject(state.next.call(iterator, arg))).then(function (step) {
    if (anObject(step).done) {
      state.done = true;
      return { done: true, value: undefined };
    }
    return { done: false, value: [state.index++, step.value] };
  });
});

$({ target: 'AsyncIterator', proto: true, real: true }, {
  asIndexedPairs: function asIndexedPairs() {
    return new AsyncIteratorProxy({
      iterator: anObject(this),
      index: 0
    });
  }
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>my.Blog</groupId>
	<artifactId>blog</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>blog</name>
	<description>My Project - SoftUni_2017</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.4.2.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.thymeleaf.extras</groupId>
			<artifactId>thymeleaf-extras-springsecurity4</artifactId>
			<version>2.1.2.RELEASE</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>


text:
layout: page
title: Downloads
permalink: /downloads
---

The latest **stable** release is [**v{{ site.version }}**](https://github.com/tstack/lnav/releases/latest).

The following options are available for installing **lnav**:

## Linux

<!-- markdown-link-check-disable-next-line -->
Download a [statically linked 64-bit binary](https://github.com/tstack/lnav/releases/download/v{{site.version}}/lnav-{{site.version}}-x86_64-linux-musl.zip).

Install from the [Snap Store](https://snapcraft.io/lnav):

```console
$ sudo snap install lnav
```

## MacOS

<!-- markdown-link-check-disable-next-line -->
Download a [statically linked 64-bit binary](https://github.com/tstack/lnav/releases/download/v{{site.version}}/lnav-{{site.version}}-x86_64-macos.zip)

Install using [Homebrew](https://formulae.brew.sh/formula/lnav):

```console
$ brew install lnav
```

## Source

<!-- markdown-link-check-disable-next-line -->
Download the [source](https://github.com/tstack/lnav/releases/download/v{{site.version}}/lnav-{{site.version}}.tar.gz)
and install any dependencies.  The following commands will unpack the source
tar ball, configure the build for your system, build, and then install:

```console
$ tar xvfz lnav-{{site.version}}.tar.gz
$ cd lnav-{{site.version}}
$ ./configure
$ make
$ make install
```

### GitHub

If you would like to contribute to the development of lnav, visit our page on
[GitHub](https://github.com/tstack/lnav).

# VSCode Extension

The [lnav VSCode Extension](https://marketplace.visualstudio.com/items?itemName=lnav.lnav)
can be used to add syntax highlighting to lnav scripts.

![Screenshot of an lnav script](/assets/images/lnav-vscode-extension.png)


text:
<!doctype>
<html>
<head>
<link rel="stylesheet" href="alert.css" />
<script type="text/javascript" src="alert.js"></script>
</head>
<body>
<input type="button" value="Alert Popup" onclick="javascript:alert('Ceci est une alerte personnalisé','title')" /> <!--- Bouton pour appeler la fonction -->

<script>
alertConfig={
			boxBgClass:"myButton",//Background class
			boxBgColor:"red",
			boxBtnCloseClass:"bouton-dialog2",//Button close class
};
alert(new Array(4,4,54,4,4,4,4));

</script>
<style>
.myButton {
	-moz-box-shadow: 0px 1px 0px 0px #f0f7fa;
	-webkit-box-shadow: 0px 1px 0px 0px #f0f7fa;
	box-shadow: 0px 1px 0px 0px #f0f7fa;
	background:-webkit-gradient(linear, left top, left bottom, color-stop(0.05, #33bdef), color-stop(1, #019ad2));
	background:-moz-linear-gradient(top, #33bdef 5%, #019ad2 100%);
	background:-webkit-linear-gradient(top, #33bdef 5%, #019ad2 100%);
	background:-o-linear-gradient(top, #33bdef 5%, #019ad2 100%);
	background:-ms-linear-gradient(top, #33bdef 5%, #019ad2 100%);
	background:linear-gradient(to bottom, #33bdef 5%, #019ad2 100%);
	filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#33bdef', endColorstr='#019ad2',GradientType=0);
	background-color:#33bdef;
	-moz-border-radius:6px;
	-webkit-border-radius:6px;
	border-radius:6px;
	border:1px solid #057fd0;
	display:inline-block;
	color:#ffffff;
	font-family:arial;
	font-size:15px;
	font-weight:bold;
	padding:6px 24px;
	text-decoration:none;
	text-shadow:0px -1px 0px #5b6178;
}
.myButton:hover {
	background:-webkit-gradient(linear, left top, left bottom, color-stop(0.05, #019ad2), color-stop(1, #33bdef));
	background:-moz-linear-gradient(top, #019ad2 5%, #33bdef 100%);
	background:-webkit-linear-gradient(top, #019ad2 5%, #33bdef 100%);
	background:-o-linear-gradient(top, #019ad2 5%, #33bdef 100%);
	background:-ms-linear-gradient(top, #019ad2 5%, #33bdef 100%);
	background:linear-gradient(to bottom, #019ad2 5%, #33bdef 100%);
	filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#019ad2', endColorstr='#33bdef',GradientType=0);
	background-color:#019ad2;
}
.myButton:active {
	position:relative;
	top:1px;
}

.bouton-dialog2 {
	-moz-box-shadow: inset 0px 1px 0px 0px #a4e271;
	-webkit-box-shadow: inset 0px 1px 0px 0px #a4e271;
	box-shadow: inset 0px 1px 0px 0px #a4e271;
	background: -webkit-gradient(linear, left top, left bottom, color-stop(0.05, #89c403), color-stop(1, #77a809));
	background: -moz-linear-gradient(top, #89c403 5%, #77a809 100%);
	background: -webkit-linear-gradient(top, #89c403 5%, #77a809 100%);
	background: -o-linear-gradient(top, #89c403 5%, #77a809 100%);
	background: -ms-linear-gradient(top, #89c403 5%, #77a809 100%);
	background: linear-gradient(to bottom, #89c403 5%, #77a809 100%);
	filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#89c403', endColorstr='#77a809',GradientType=0);
	background-color: #89c403;
	-moz-border-radius: 6px;
	-webkit-border-radius: 6px;
	border-radius: 6px;
	border: 1px solid #74b807;
	display: inline-block;
	cursor: pointer;
	color: #ffffff;
	font-family: arial;
	font-size: 15px;
	font-weight: bold;
	padding: 6px 24px;
	text-decoration: none;
	text-shadow: 0px 1px 0px #528009;
	float: right;

}
</style>
</body>
</html>


text:
#ifdef CONFIG_BOARD_CRASHDUMP

#include <board_config.h>

#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <limits.h>
#include <errno.h>
#include <sys/ioctl.h>

#include <nuttx/board.h>

#include "up_internal.h"
#include <systemlib/hardfault_log.h>

#if defined(CONFIG_STM32F7_BBSRAM) && defined(CONFIG_STM32F7_SAVE_CRASHDUMP)
#  define HAS_BBSRAM CONFIG_STM32F7_BBSRAM
#  define BBSRAM_FILE_COUNT CONFIG_STM32F7_BBSRAM_FILES
#  define SAVE_CRASHDUMP CONFIG_STM32F7_SAVE_CRASHDUMP
#elif defined(CONFIG_STM32_BBSRAM) && defined(CONFIG_STM32_SAVE_CRASHDUMP)
#  define HAS_BBSRAM CONFIG_STM32_BBSRAM
#  define BBSRAM_FILE_COUNT CONFIG_STM32_BBSRAM_FILES
#  define SAVE_CRASHDUMP CONFIG_STM32_SAVE_CRASHDUMP
#endif

int board_hardfault_init(int display_to_console, bool allow_prompt)
{

	int hadCrash = -1;
#if defined(HAS_BBSRAM)

	/* NB. the use of the console requires the hrt running
	 * to poll the DMA
	 */

	/* Using Battery Backed Up SRAM */

	int filesizes[BBSRAM_FILE_COUNT + 1] = BSRAM_FILE_SIZES;

	stm32_bbsraminitialize(BBSRAM_PATH, filesizes);

#if defined(SAVE_CRASHDUMP)

	/* Panic Logging in Battery Backed Up Files */

	/*
	 * In an ideal world, if a fault happens in flight the
	 * system save it to BBSRAM will then reboot. Upon
	 * rebooting, the system will log the fault to disk, recover
	 * the flight state and continue to fly.  But if there is
	 * a fault on the bench or in the air that prohibit the recovery
	 * or committing the log to disk, the things are too broken to
	 * fly. So the question is:
	 *
	 * Did we have a hard fault and not make it far enough
	 * through the boot sequence to commit the fault data to
	 * the SD card?
	 */

	/* Do we have an uncommitted hard fault in BBSRAM?
	 *  - this will be reset after a successful commit to SD
	 */
	hadCrash = hardfault_check_status("boot");

	if (hadCrash == OK) {

		syslog(LOG_ERR, "[boot] There is a hard fault logged. Hold down the SPACE BAR," \
		       " while booting to review!\n");

		/* Yes. So add one to the boot count - this will be reset after a successful
		 * commit to SD
		 */

		int reboots = hardfault_increment_reboot("boot", false);

		if (reboots < 0) {
			return -EIO;
		}

		if (reboots >= 32000) {
			reboots = hardfault_increment_reboot("boot", true);
			return -ENOSPC;
		}

		/* Also end the misery for a user that holds for a key down on the console */

		int bytesWaiting;
		ioctl(fileno(stdin), FIONREAD, (unsigned long)((uintptr_t) &bytesWaiting));

		if (reboots > display_to_console || bytesWaiting != 0) {

			/* Since we can not commit the fault dump to disk. Display it
			 * to the console.
			 */

			if (!allow_prompt) {
				bytesWaiting = 0;
			}

			if (display_to_console != INT_MAX) {
				hardfault_write("boot", fileno(stdout), HARDFAULT_DISPLAY_FORMAT, false);
			}

			syslog(LOG_ERR, "[boot] There were %d reboots with Hard fault that were not committed to disk%s\n",
			       reboots,
			       (bytesWaiting == 0 ? "" : " - Boot halted Due to Key Press\n"));

			/* For those of you with a debugger set a break point on up_assert and
			 * then set dbgContinue = 1 and go.
			 */

			/* Clear any key press that got us here */

			volatile bool dbgContinue = bytesWaiting == 0;
			int c = '>';

			while (!dbgContinue) {

				switch (c) {

				case EOF:
				case '\n':
				case '\r':
				case ' ':
					goto read;

				default:

					putchar(c);
					putchar('\n');

					switch (c) {

					case 'D':
					case 'd':
						hardfault_write("boot", fileno(stdout), HARDFAULT_DISPLAY_FORMAT, false);
						break;

					case 'C':
					case 'c':
						hardfault_rearm("boot");
						hardfault_increment_reboot("boot", true);
						break;

					case 'B':
					case 'b':
						dbgContinue = true;
						break;

					default:
						break;
					} // Inner Switch

					syslog(LOG_INFO, "\nEnter B - Continue booting\n" \
					       "Enter C - Clear the fault log\n" \
					       "Enter D - Dump fault log\n\n?>");
					fflush(stdout);

read:

					if (!dbgContinue) {
						c = getchar();
					}

					break;

				} // outer switch
			} // for

		} // inner if
	} // outer if

#endif // SAVE_CRASHDUMP
#endif // HAS_BBSRAM
	return hadCrash == OK ? 1 : 0;
}

static void copy_reverse(stack_word_t *dest, stack_word_t *src, int size)
{
	while (size--) {
		*dest++ = *src--;
	}
}

static uint32_t *__attribute__((noinline)) __sdata_addr(void)
{
	return &_sdata;
}

__EXPORT void board_crashdump(uintptr_t currentsp, FAR void *tcb, FAR const uint8_t *filename, int lineno)
{
#ifndef BOARD_CRASHDUMP_RESET_ONLY
	/* We need a chunk of ram to save the complete context in.
	 * Since we are going to reboot we will use &_sdata
	 * which is the lowest memory and the amount we will save
	 * _should be_ below any resources we need herein.
	 * Unfortunately this is hard to test. See dead below
	 */

	fullcontext_s *pdump = (fullcontext_s *)__sdata_addr();

	(void)enter_critical_section();

	struct tcb_s *rtcb = (struct tcb_s *)tcb;

	/* Zero out everything */

	memset(pdump, 0, sizeof(fullcontext_s));

	/* Save Info */

	pdump->info.lineno = lineno;

	if (filename) {

		int offset = 0;
		unsigned int len = strlen((char *)filename) + 1;

		if (len > sizeof(pdump->info.filename)) {
			offset = len - sizeof(pdump->info.filename) ;
		}

		strncpy(pdump->info.filename, (char *)&filename[offset], sizeof(pdump->info.filename));
	}

	/* Save the value of the pointer for current_regs as debugging info.
	 * It should be NULL in case of an ASSERT and will aid in cross
	 * checking the validity of system memory at the time of the
	 * fault.
	 */

	pdump->info.current_regs = (uintptr_t) CURRENT_REGS;

	/* Save Context */

#if CONFIG_TASK_NAME_SIZE > 0
	strncpy(pdump->info.name, rtcb->name, CONFIG_TASK_NAME_SIZE);
#endif

	pdump->info.pid = rtcb->pid;

	/* If  current_regs is not NULL then we are in an interrupt context
	 * and the user context is in current_regs else we are running in
	 * the users context
	 */

	if (CURRENT_REGS) {
		pdump->info.stacks.interrupt.sp = currentsp;

		pdump->info.flags |= (eRegsPresent | eUserStackPresent | eIntStackPresent);
		memcpy(pdump->info.regs, (void *)CURRENT_REGS, sizeof(pdump->info.regs));
		pdump->info.stacks.user.sp = pdump->info.regs[REG_R13];

	} else {

		/* users context */
		pdump->info.flags |= eUserStackPresent;

		pdump->info.stacks.user.sp = currentsp;
	}

	if (pdump->info.pid == 0) {

		pdump->info.stacks.user.top = g_idle_topstack - 4;
		pdump->info.stacks.user.size = CONFIG_IDLETHREAD_STACKSIZE;

	} else {
		pdump->info.stacks.user.top = (uint32_t) rtcb->adj_stack_ptr;
		pdump->info.stacks.user.size = (uint32_t) rtcb->adj_stack_size;
	}

#if CONFIG_ARCH_INTERRUPTSTACK > 3

	/* Get the limits on the interrupt stack memory */

	pdump->info.stacks.interrupt.top = (uint32_t)&g_intstackbase;
	pdump->info.stacks.interrupt.size  = (CONFIG_ARCH_INTERRUPTSTACK & ~3);

	/* If In interrupt Context save the interrupt stack data centered
	 * about the interrupt stack pointer
	 */

	if ((pdump->info.flags & eIntStackPresent) != 0) {
		stack_word_t *ps = (stack_word_t *) pdump->info.stacks.interrupt.sp;
		copy_reverse(pdump->istack, &ps[arraySize(pdump->istack) / 2], arraySize(pdump->istack));
	}

	/* Is it Invalid? */

	if (!(pdump->info.stacks.interrupt.sp <= pdump->info.stacks.interrupt.top &&
	      pdump->info.stacks.interrupt.sp > pdump->info.stacks.interrupt.top - pdump->info.stacks.interrupt.size)) {
		pdump->info.flags |= eInvalidIntStackPrt;
	}

#endif

	/* If In interrupt context or User save the user stack data centered
	 * about the user stack pointer
	 */
	if ((pdump->info.flags & eUserStackPresent) != 0) {
		stack_word_t *ps = (stack_word_t *) pdump->info.stacks.user.sp;
		copy_reverse(pdump->ustack, &ps[arraySize(pdump->ustack) / 2], arraySize(pdump->ustack));
	}

	/* Is it Invalid? */

	if (!(pdump->info.stacks.user.sp <= pdump->info.stacks.user.top &&
	      pdump->info.stacks.user.sp > pdump->info.stacks.user.top - pdump->info.stacks.user.size)) {
		pdump->info.flags |= eInvalidUserStackPtr;
	}

	int rv = px4_savepanic(HARDFAULT_FILENO, (uint8_t *)pdump, sizeof(fullcontext_s));

	/* Test if memory got wiped because of using _sdata */

	if (rv == -ENXIO) {
		char *dead = "Memory wiped - dump not saved!";

		while (*dead) {
			up_lowputc(*dead++);
		}

	} else if (rv == -ENOSPC) {

		/* hard fault again */

		up_lowputc('!');
	}

#endif /* BOARD_CRASHDUMP_RESET_ONLY */

	/* All boards need to do a reset here!
	 *
	 * Since we needed a chunk of ram to save the complete
	 * context in and have corrupted it.  We can not allow
	 * the OS to run again. We used &_sdata which is the lowest memory
	 * and it could be used by the OS.
	*/

	board_reset(CONFIG_BOARD_ASSERT_RESET_VALUE);
}

#endif /* CONFIG_BOARD_CRASHDUMP */


text:
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Cocos2d-html5 Hello World test</title>
    <link rel="icon" type="image/GIF" href="res/favicon.ico"/>
    <meta name="viewport" content="width=320,target-densitydpi=device-dpi,user-scalable=no" />
    <meta name="apple-mobile-web-app-capable" content="yes"/>
    <meta name="full-screen" content="yes"/>
    <meta name="screen-orientation" content="portrait"/>
    <meta name="x5-fullscreen" content="true"/>
    <meta name="360-fullscreen" content="true"/>
    <style>
        body, canvas, div {
            -moz-user-select: none;
            -webkit-user-select: none;
            -ms-user-select: none;
            -khtml-user-select: none;
            -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
        }
    </style>
</head>
<body style="padding:0; margin: 0; background: #000;">
<canvas id="gameCanvas" width="320" height="480"></canvas>
<script src="cocos2d.js"></script>
</body>
</html>


text:
package com.google.code.validationframework.base.rule.string;

/**
 * Rule checking whether the data, being a string, has a length greater than or equal to a specific value.
 *
 * @see AbstractStringBooleanRule
 */
public class StringLengthGreaterThanOrEqualToRule extends AbstractStringBooleanRule {

    /**
     * String length to which the data string length is to be compared.
     */
    private int minLength = Integer.MIN_VALUE;

    /**
     * Default constructor.
     */
    public StringLengthGreaterThanOrEqualToRule() {
        super();
    }

    /**
     * Constructor specifying the string length to which the data string length is to be compared.
     *
     * @param minLength String length to which the data string length is to be compared.
     */
    public StringLengthGreaterThanOrEqualToRule(final int minLength) {
        super();
        setMinLength(minLength);
    }

    /**
     * Gets the string length to which the data string length is compared.
     *
     * @return String length to which the data string length is compared.
     */
    public int getMinLength() {
        return minLength;
    }

    /**
     * Sets the string length to which the data string length is compared.
     *
     * @param minLength String length to which the data string length is compared.
     */
    public void setMinLength(final int minLength) {
        this.minLength = minLength;
    }

    /**
     * @see AbstractStringBooleanRule#validate(Object)
     */
    @Override
    public Boolean validate(final String data) {
        int length = 0;
        if (data != null) {
            length = trimIfNeeded(data).length();
        }

        return (length >= minLength);
    }
}


text:
describe('Chart', function() {

	// https://github.com/chartjs/Chart.js/issues/2481
	// See global.deprecations.tests.js for backward compatibility
	it('should be defined and prototype of chart instances', function() {
		var chart = acquireChart({});
		expect(Chart).toBeDefined();
		expect(Chart instanceof Object).toBeTruthy();
		expect(chart.constructor).toBe(Chart);
		expect(chart instanceof Chart).toBeTruthy();
		expect(Chart.prototype.isPrototypeOf(chart)).toBeTruthy();
	});

	describe('config initialization', function() {
		it('should create missing config.data properties', function() {
			var chart = acquireChart({});
			var data = chart.data;

			expect(data instanceof Object).toBeTruthy();
			expect(data.labels instanceof Array).toBeTruthy();
			expect(data.labels.length).toBe(0);
			expect(data.datasets instanceof Array).toBeTruthy();
			expect(data.datasets.length).toBe(0);
		});

		it('should not alter config.data references', function() {
			var ds0 = {data: [10, 11, 12, 13]};
			var ds1 = {data: [20, 21, 22, 23]};
			var datasets = [ds0, ds1];
			var labels = [0, 1, 2, 3];
			var data = {labels: labels, datasets: datasets};

			var chart = acquireChart({
				type: 'line',
				data: data
			});

			expect(chart.data).toBe(data);
			expect(chart.data.labels).toBe(labels);
			expect(chart.data.datasets).toBe(datasets);
			expect(chart.data.datasets[0]).toBe(ds0);
			expect(chart.data.datasets[1]).toBe(ds1);
			expect(chart.data.datasets[0].data).toBe(ds0.data);
			expect(chart.data.datasets[1].data).toBe(ds1.data);
		});

		it('should define chart.data as an alias for config.data', function() {
			var config = {data: {labels: [], datasets: []}};
			var chart = acquireChart(config);

			expect(chart.data).toBe(config.data);

			chart.data = {labels: [1, 2, 3], datasets: [{data: [4, 5, 6]}]};

			expect(config.data).toBe(chart.data);
			expect(config.data.labels).toEqual([1, 2, 3]);
			expect(config.data.datasets[0].data).toEqual([4, 5, 6]);

			config.data = {labels: [7, 8, 9], datasets: [{data: [10, 11, 12]}]};

			expect(chart.data).toBe(config.data);
			expect(chart.data.labels).toEqual([7, 8, 9]);
			expect(chart.data.datasets[0].data).toEqual([10, 11, 12]);
		});

		it('should initialize config with default options', function() {
			var callback = function() {};

			var defaults = Chart.defaults;
			defaults.global.responsiveAnimationDuration = 42;
			defaults.global.hover.onHover = callback;
			defaults.line.hover.mode = 'x-axis';
			defaults.line.spanGaps = true;

			var chart = acquireChart({
				type: 'line'
			});

			var options = chart.options;
			expect(options.defaultFontSize).toBe(defaults.global.defaultFontSize);
			expect(options.showLines).toBe(defaults.line.showLines);
			expect(options.spanGaps).toBe(true);
			expect(options.responsiveAnimationDuration).toBe(42);
			expect(options.hover.onHover).toBe(callback);
			expect(options.hover.mode).toBe('x-axis');
		});

		it('should override default options', function() {
			var defaults = Chart.defaults;
			defaults.global.responsiveAnimationDuration = 42;
			defaults.line.hover.mode = 'x-axis';
			defaults.line.spanGaps = true;

			var chart = acquireChart({
				type: 'line',
				options: {
					responsiveAnimationDuration: 4242,
					spanGaps: false,
					hover: {
						mode: 'dataset',
					},
					title: {
						position: 'bottom'
					}
				}
			});

			var options = chart.options;
			expect(options.responsiveAnimationDuration).toBe(4242);
			expect(options.spanGaps).toBe(false);
			expect(options.hover.mode).toBe('dataset');
			expect(options.title.position).toBe('bottom');
		});

		it('should override axis positions that are incorrect', function() {
			var chart = acquireChart({
				type: 'line',
				options: {
					scales: {
						xAxes: [{
							position: 'left',
						}],
						yAxes: [{
							position: 'bottom'
						}]
					}
				}
			});

			var scaleOptions = chart.options.scales;
			expect(scaleOptions.xAxes[0].position).toBe('bottom');
			expect(scaleOptions.yAxes[0].position).toBe('left');
		});

		it('should throw an error if the chart type is incorrect', function() {
			function createChart() {
				acquireChart({
					type: 'area',
					data: {
						datasets: [{
							label: 'first',
							data: [10, 20]
						}],
						labels: ['0', '1'],
					},
					options: {
						scales: {
							xAxes: [{
								position: 'left',
							}],
							yAxes: [{
								position: 'bottom'
							}]
						}
					}
				});
			}
			expect(createChart).toThrow(new Error('"area" is not a chart type.'));
		});
	});

	describe('config.options.responsive: false', function() {
		it('should not inject the resizer element', function() {
			var chart = acquireChart({
				options: {
					responsive: false
				}
			});

			var wrapper = chart.canvas.parentNode;
			expect(wrapper.childNodes.length).toBe(1);
			expect(wrapper.firstChild.tagName).toBe('CANVAS');
		});
	});

	describe('config.options.responsive: true (maintainAspectRatio: false)', function() {
		it('should fill parent width and height', function() {
			var chart = acquireChart({
				options: {
					responsive: true,
					maintainAspectRatio: false
				}
			}, {
				canvas: {
					style: 'width: 150px; height: 245px'
				},
				wrapper: {
					style: 'width: 300px; height: 350px'
				}
			});

			expect(chart).toBeChartOfSize({
				dw: 300, dh: 350,
				rw: 300, rh: 350,
			});
		});

		it('should resize the canvas when parent width changes', function(done) {
			var chart = acquireChart({
				options: {
					responsive: true,
					maintainAspectRatio: false
				}
			}, {
				canvas: {
					style: ''
				},
				wrapper: {
					style: 'width: 300px; height: 350px; position: relative'
				}
			});

			expect(chart).toBeChartOfSize({
				dw: 300, dh: 350,
				rw: 300, rh: 350,
			});

			var wrapper = chart.canvas.parentNode;
			wrapper.style.width = '455px';
			waitForResize(chart, function() {
				expect(chart).toBeChartOfSize({
					dw: 455, dh: 350,
					rw: 455, rh: 350,
				});

				wrapper.style.width = '150px';
				waitForResize(chart, function() {
					expect(chart).toBeChartOfSize({
						dw: 150, dh: 350,
						rw: 150, rh: 350,
					});

					done();
				});
			});
		});

		it('should resize the canvas when parent height changes', function(done) {
			var chart = acquireChart({
				options: {
					responsive: true,
					maintainAspectRatio: false
				}
			}, {
				canvas: {
					style: ''
				},
				wrapper: {
					style: 'width: 300px; height: 350px; position: relative'
				}
			});

			expect(chart).toBeChartOfSize({
				dw: 300, dh: 350,
				rw: 300, rh: 350,
			});

			var wrapper = chart.canvas.parentNode;
			wrapper.style.height = '455px';
			waitForResize(chart, function() {
				expect(chart).toBeChartOfSize({
					dw: 300, dh: 455,
					rw: 300, rh: 455,
				});

				wrapper.style.height = '150px';
				waitForResize(chart, function() {
					expect(chart).toBeChartOfSize({
						dw: 300, dh: 150,
						rw: 300, rh: 150,
					});

					done();
				});
			});
		});

		it('should not include parent padding when resizing the canvas', function(done) {
			var chart = acquireChart({
				type: 'line',
				options: {
					responsive: true,
					maintainAspectRatio: false
				}
			}, {
				canvas: {
					style: ''
				},
				wrapper: {
					style: 'padding: 50px; width: 320px; height: 350px; position: relative'
				}
			});

			expect(chart).toBeChartOfSize({
				dw: 320, dh: 350,
				rw: 320, rh: 350,
			});

			var wrapper = chart.canvas.parentNode;
			wrapper.style.height = '355px';
			wrapper.style.width = '455px';
			waitForResize(chart, function() {
				expect(chart).toBeChartOfSize({
					dw: 455, dh: 355,
					rw: 455, rh: 355,
				});

				done();
			});
		});

		it('should resize the canvas when the canvas display style changes from "none" to "block"', function(done) {
			var chart = acquireChart({
				options: {
					responsive: true,
					maintainAspectRatio: false
				}
			}, {
				canvas: {
					style: 'display: none;'
				},
				wrapper: {
					style: 'width: 320px; height: 350px'
				}
			});

			var canvas = chart.canvas;
			canvas.style.display = 'block';
			waitForResize(chart, function() {
				expect(chart).toBeChartOfSize({
					dw: 320, dh: 350,
					rw: 320, rh: 350,
				});

				done();
			});
		});

		it('should resize the canvas when the wrapper display style changes from "none" to "block"', function(done) {
			var chart = acquireChart({
				options: {
					responsive: true,
					maintainAspectRatio: false
				}
			}, {
				canvas: {
					style: ''
				},
				wrapper: {
					style: 'display: none; width: 460px; height: 380px'
				}
			});

			var wrapper = chart.canvas.parentNode;
			wrapper.style.display = 'block';
			waitForResize(chart, function() {
				expect(chart).toBeChartOfSize({
					dw: 460, dh: 380,
					rw: 460, rh: 380,
				});

				done();
			});
		});

		// https://github.com/chartjs/Chart.js/issues/3790
		it('should resize the canvas if attached to the DOM after construction', function(done) {
			var canvas = document.createElement('canvas');
			var wrapper = document.createElement('div');
			var body = window.document.body;
			var chart = new Chart(canvas, {
				type: 'line',
				options: {
					responsive: true,
					maintainAspectRatio: false
				}
			});

			expect(chart).toBeChartOfSize({
				dw: 0, dh: 0,
				rw: 0, rh: 0,
			});

			wrapper.style.cssText = 'width: 455px; height: 355px';
			wrapper.appendChild(canvas);
			body.appendChild(wrapper);

			waitForResize(chart, function() {
				expect(chart).toBeChartOfSize({
					dw: 455, dh: 355,
					rw: 455, rh: 355,
				});

				body.removeChild(wrapper);
				chart.destroy();
				done();
			});
		});

		it('should resize the canvas when attached to a different parent', function(done) {
			var canvas = document.createElement('canvas');
			var wrapper = document.createElement('div');
			var body = window.document.body;
			var chart = new Chart(canvas, {
				type: 'line',
				options: {
					responsive: true,
					maintainAspectRatio: false
				}
			});

			expect(chart).toBeChartOfSize({
				dw: 0, dh: 0,
				rw: 0, rh: 0,
			});

			wrapper.style.cssText = 'width: 455px; height: 355px';
			wrapper.appendChild(canvas);
			body.appendChild(wrapper);

			waitForResize(chart, function() {
				var resizer = wrapper.firstChild;
				expect(resizer.className).toBe('chartjs-size-monitor');
				expect(resizer.tagName).toBe('DIV');
				expect(chart).toBeChartOfSize({
					dw: 455, dh: 355,
					rw: 455, rh: 355,
				});

				var target = document.createElement('div');
				target.style.cssText = 'width: 640px; height: 480px';
				target.appendChild(canvas);
				body.appendChild(target);

				waitForResize(chart, function() {
					expect(target.firstChild).toBe(resizer);
					expect(wrapper.firstChild).toBe(null);
					expect(chart).toBeChartOfSize({
						dw: 640, dh: 480,
						rw: 640, rh: 480,
					});

					body.removeChild(wrapper);
					body.removeChild(target);
					chart.destroy();
					done();
				});
			});
		});

		// https://github.com/chartjs/Chart.js/issues/3521
		it('should resize the canvas after the wrapper has been re-attached to the DOM', function(done) {
			var chart = acquireChart({
				options: {
					responsive: true,
					maintainAspectRatio: false
				}
			}, {
				canvas: {
					style: ''
				},
				wrapper: {
					style: 'width: 320px; height: 350px'
				}
			});

			expect(chart).toBeChartOfSize({
				dw: 320, dh: 350,
				rw: 320, rh: 350,
			});

			var wrapper = chart.canvas.parentNode;
			var parent = wrapper.parentNode;
			parent.removeChild(wrapper);
			parent.appendChild(wrapper);
			wrapper.style.height = '355px';

			waitForResize(chart, function() {
				expect(chart).toBeChartOfSize({
					dw: 320, dh: 355,
					rw: 320, rh: 355,
				});

				parent.removeChild(wrapper);
				wrapper.style.width = '455px';
				parent.appendChild(wrapper);

				waitForResize(chart, function() {
					expect(chart).toBeChartOfSize({
						dw: 455, dh: 355,
						rw: 455, rh: 355,
					});

					done();
				});
			});
		});

		// https://github.com/chartjs/Chart.js/issues/4737
		it('should resize the canvas when re-creating the chart', function(done) {
			var chart = acquireChart({
				options: {
					responsive: true
				}
			}, {
				wrapper: {
					style: 'width: 320px'
				}
			});

			waitForResize(chart, function() {
				var canvas = chart.canvas;
				expect(chart).toBeChartOfSize({
					dw: 320, dh: 320,
					rw: 320, rh: 320,
				});

				chart.destroy();
				chart = new Chart(canvas, {
					type: 'line',
					options: {
						responsive: true
					}
				});

				canvas.parentNode.style.width = '455px';
				waitForResize(chart, function() {
					expect(chart).toBeChartOfSize({
						dw: 455, dh: 455,
						rw: 455, rh: 455,
					});

					done();
				});
			});
		});
	});

	describe('config.options.responsive: true (maintainAspectRatio: true)', function() {
		it('should resize the canvas with correct aspect ratio when parent width changes', function(done) {
			var chart = acquireChart({
				type: 'line', // AR == 2
				options: {
					responsive: true,
					maintainAspectRatio: true
				}
			}, {
				canvas: {
					style: ''
				},
				wrapper: {
					style: 'width: 300px; height: 350px; position: relative'
				}
			});

			expect(chart).toBeChartOfSize({
				dw: 300, dh: 150,
				rw: 300, rh: 150,
			});

			var wrapper = chart.canvas.parentNode;
			wrapper.style.width = '450px';
			waitForResize(chart, function() {
				expect(chart).toBeChartOfSize({
					dw: 450, dh: 225,
					rw: 450, rh: 225,
				});

				wrapper.style.width = '150px';
				waitForResize(chart, function() {
					expect(chart).toBeChartOfSize({
						dw: 150, dh: 75,
						rw: 150, rh: 75,
					});

					done();
				});
			});
		});

		it('should not resize the canvas when parent height changes', function(done) {
			var chart = acquireChart({
				options: {
					responsive: true,
					maintainAspectRatio: true
				}
			}, {
				canvas: {
					style: ''
				},
				wrapper: {
					style: 'width: 320px; height: 350px; position: relative'
				}
			});

			expect(chart).toBeChartOfSize({
				dw: 320, dh: 160,
				rw: 320, rh: 160,
			});

			var wrapper = chart.canvas.parentNode;
			wrapper.style.height = '455px';
			waitForResize(chart, function() {
				expect(chart).toBeChartOfSize({
					dw: 320, dh: 160,
					rw: 320, rh: 160,
				});

				wrapper.style.height = '150px';
				waitForResize(chart, function() {
					expect(chart).toBeChartOfSize({
						dw: 320, dh: 160,
						rw: 320, rh: 160,
					});

					done();
				});
			});
		});
	});

	describe('Retina scale (a.k.a. device pixel ratio)', function() {
		beforeEach(function() {
			this.devicePixelRatio = window.devicePixelRatio;
			window.devicePixelRatio = 3;
		});

		afterEach(function() {
			window.devicePixelRatio = this.devicePixelRatio;
		});

		// see https://github.com/chartjs/Chart.js/issues/3575
		it ('should scale the render size but not the "implicit" display size', function() {
			var chart = acquireChart({
				options: {
					responsive: false
				}
			}, {
				canvas: {
					width: 320,
					height: 240,
				}
			});

			expect(chart).toBeChartOfSize({
				dw: 320, dh: 240,
				rw: 960, rh: 720,
			});
		});

		it ('should scale the render size but not the "explicit" display size', function() {
			var chart = acquireChart({
				options: {
					responsive: false
				}
			}, {
				canvas: {
					style: 'width: 320px; height: 240px'
				}
			});

			expect(chart).toBeChartOfSize({
				dw: 320, dh: 240,
				rw: 960, rh: 720,
			});
		});
	});

	describe('config.options.devicePixelRatio', function() {
		beforeEach(function() {
			this.devicePixelRatio = window.devicePixelRatio;
			window.devicePixelRatio = 1;
		});

		afterEach(function() {
			window.devicePixelRatio = this.devicePixelRatio;
		});

		// see https://github.com/chartjs/Chart.js/issues/3575
		it ('should scale the render size but not the "implicit" display size', function() {
			var chart = acquireChart({
				options: {
					responsive: false,
					devicePixelRatio: 3
				}
			}, {
				canvas: {
					width: 320,
					height: 240,
				}
			});

			expect(chart).toBeChartOfSize({
				dw: 320, dh: 240,
				rw: 960, rh: 720,
			});
		});

		it ('should scale the render size but not the "explicit" display size', function() {
			var chart = acquireChart({
				options: {
					responsive: false,
					devicePixelRatio: 3
				}
			}, {
				canvas: {
					style: 'width: 320px; height: 240px'
				}
			});

			expect(chart).toBeChartOfSize({
				dw: 320, dh: 240,
				rw: 960, rh: 720,
			});
		});
	});

	describe('controller.destroy', function() {
		it('should remove the resizer element when responsive: true', function(done) {
			var chart = acquireChart({
				options: {
					responsive: true
				}
			});

			waitForResize(chart, function() {
				var wrapper = chart.canvas.parentNode;
				var resizer = wrapper.firstChild;
				expect(wrapper.childNodes.length).toBe(2);
				expect(resizer.className).toBe('chartjs-size-monitor');
				expect(resizer.tagName).toBe('DIV');

				chart.destroy();

				expect(wrapper.childNodes.length).toBe(1);
				expect(wrapper.firstChild.tagName).toBe('CANVAS');

				done();
			});
		});
	});

	describe('controller.reset', function() {
		it('should reset the chart elements', function() {
			var chart = acquireChart({
				type: 'line',
				data: {
					labels: ['A', 'B', 'C', 'D'],
					datasets: [{
						data: [10, 20, 30, 0]
					}]
				},
				options: {
					responsive: true
				}
			});

			var meta = chart.getDatasetMeta(0);

			// Verify that points are at their initial correct location,
			// then we will reset and see that they moved
			expect(meta.data[0]._model.y).toBeCloseToPixel(333);
			expect(meta.data[1]._model.y).toBeCloseToPixel(183);
			expect(meta.data[2]._model.y).toBe(32);
			expect(meta.data[3]._model.y).toBe(484);

			chart.reset();

			// For a line chart, the animation state is the bottom
			expect(meta.data[0]._model.y).toBe(484);
			expect(meta.data[1]._model.y).toBe(484);
			expect(meta.data[2]._model.y).toBe(484);
			expect(meta.data[3]._model.y).toBe(484);
		});
	});

	describe('config update', function() {
		it ('should update options', function() {
			var chart = acquireChart({
				type: 'line',
				data: {
					labels: ['A', 'B', 'C', 'D'],
					datasets: [{
						data: [10, 20, 30, 100]
					}]
				},
				options: {
					responsive: true
				}
			});

			chart.options = {
				responsive: false,
				scales: {
					yAxes: [{
						ticks: {
							min: 0,
							max: 10
						}
					}]
				}
			};
			chart.update();

			var yScale = chart.scales['y-axis-0'];
			expect(yScale.options.ticks.min).toBe(0);
			expect(yScale.options.ticks.max).toBe(10);
		});

		it ('should update scales options', function() {
			var chart = acquireChart({
				type: 'line',
				data: {
					labels: ['A', 'B', 'C', 'D'],
					datasets: [{
						data: [10, 20, 30, 100]
					}]
				},
				options: {
					responsive: true
				}
			});

			chart.options.scales.yAxes[0].ticks.min = 0;
			chart.options.scales.yAxes[0].ticks.max = 10;
			chart.update();

			var yScale = chart.scales['y-axis-0'];
			expect(yScale.options.ticks.min).toBe(0);
			expect(yScale.options.ticks.max).toBe(10);
		});

		it ('should update scales options from new object', function() {
			var chart = acquireChart({
				type: 'line',
				data: {
					labels: ['A', 'B', 'C', 'D'],
					datasets: [{
						data: [10, 20, 30, 100]
					}]
				},
				options: {
					responsive: true
				}
			});

			var newScalesConfig = {
				yAxes: [{
					ticks: {
						min: 0,
						max: 10
					}
				}]
			};
			chart.options.scales = newScalesConfig;

			chart.update();

			var yScale = chart.scales['y-axis-0'];
			expect(yScale.options.ticks.min).toBe(0);
			expect(yScale.options.ticks.max).toBe(10);
		});

		it ('should remove discarded scale', function() {
			var chart = acquireChart({
				type: 'line',
				data: {
					labels: ['A', 'B', 'C', 'D'],
					datasets: [{
						data: [10, 20, 30, 100]
					}]
				},
				options: {
					responsive: true,
					scales: {
						yAxes: [{
							id: 'yAxis0',
							ticks: {
								min: 0,
								max: 10
							}
						}]
					}
				}
			});

			var newScalesConfig = {
				yAxes: [{
					ticks: {
						min: 0,
						max: 10
					}
				}]
			};
			chart.options.scales = newScalesConfig;

			chart.update();

			var yScale = chart.scales.yAxis0;
			expect(yScale).toBeUndefined();
			var newyScale = chart.scales['y-axis-0'];
			expect(newyScale.options.ticks.min).toBe(0);
			expect(newyScale.options.ticks.max).toBe(10);
		});

		it ('should update tooltip options', function() {
			var chart = acquireChart({
				type: 'line',
				data: {
					labels: ['A', 'B', 'C', 'D'],
					datasets: [{
						data: [10, 20, 30, 100]
					}]
				},
				options: {
					responsive: true
				}
			});

			var newTooltipConfig = {
				mode: 'dataset',
				intersect: false
			};
			chart.options.tooltips = newTooltipConfig;

			chart.update();
			expect(chart.tooltip._options).toEqual(jasmine.objectContaining(newTooltipConfig));
		});

		it ('should reset the tooltip on update', function() {
			var chart = acquireChart({
				type: 'line',
				data: {
					labels: ['A', 'B', 'C', 'D'],
					datasets: [{
						data: [10, 20, 30, 100]
					}]
				},
				options: {
					responsive: true,
					tooltip: {
						mode: 'nearest'
					}
				}
			});

			// Trigger an event over top of a point to
			// put an item into the tooltip
			var meta = chart.getDatasetMeta(0);
			var point = meta.data[1];

			var node = chart.canvas;
			var rect = node.getBoundingClientRect();

			var evt = new MouseEvent('mousemove', {
				view: window,
				bubbles: true,
				cancelable: true,
				clientX: rect.left + point._model.x,
				clientY: 0
			});

			// Manually trigger rather than having an async test
			node.dispatchEvent(evt);

			// Check and see if tooltip was displayed
			var tooltip = chart.tooltip;

			expect(chart.lastActive).toEqual([point]);
			expect(tooltip._lastActive).toEqual([]);

			// Update and confirm tooltip is reset
			chart.update();
			expect(chart.lastActive).toEqual([]);
			expect(tooltip._lastActive).toEqual([]);
		});

		it ('should update the metadata', function() {
			var cfg = {
				data: {
					labels: ['A', 'B', 'C', 'D'],
					datasets: [{
						type: 'line',
						data: [10, 20, 30, 0]
					}]
				},
				options: {
					responsive: true,
					scales: {
						xAxes: [{
							type: 'time'
						}],
						yAxes: [{
							scaleLabel: {
								display: true,
								labelString: 'Value'
							}
						}]
					}
				}
			};
			var chart = acquireChart(cfg);
			var meta = chart.getDatasetMeta(0);
			expect(meta.type).toBe('line');

			// change the dataset to bar and check that meta was updated
			chart.config.data.datasets[0].type = 'bar';
			chart.update();
			meta = chart.getDatasetMeta(0);
			expect(meta.type).toBe('bar');
		});
	});

	describe('plugin.extensions', function() {
		it ('should notify plugin in correct order', function(done) {
			var plugin = this.plugin = {};
			var sequence = [];
			var hooks = {
				init: [
					'beforeInit',
					'afterInit'
				],
				update: [
					'beforeUpdate',
					'beforeLayout',
					'afterLayout',
					'beforeDatasetsUpdate',
					'beforeDatasetUpdate',
					'afterDatasetUpdate',
					'afterDatasetsUpdate',
					'afterUpdate',
				],
				render: [
					'beforeRender',
					'beforeDraw',
					'beforeDatasetsDraw',
					'beforeDatasetDraw',
					'afterDatasetDraw',
					'afterDatasetsDraw',
					'beforeTooltipDraw',
					'afterTooltipDraw',
					'afterDraw',
					'afterRender',
				],
				resize: [
					'resize'
				],
				destroy: [
					'destroy'
				]
			};

			Object.keys(hooks).forEach(function(group) {
				hooks[group].forEach(function(name) {
					plugin[name] = function() {
						sequence.push(name);
					};
				});
			});

			var chart = window.acquireChart({
				type: 'line',
				data: {datasets: [{}]},
				plugins: [plugin],
				options: {
					responsive: true
				}
			}, {
				wrapper: {
					style: 'width: 300px'
				}
			});

			chart.canvas.parentNode.style.width = '400px';
			waitForResize(chart, function() {
				chart.destroy();

				expect(sequence).toEqual([].concat(
					hooks.init,
					hooks.update,
					hooks.render,
					hooks.resize,
					hooks.update,
					hooks.render,
					hooks.destroy
				));

				done();
			});
		});

		it('should not notify before/afterDatasetDraw if dataset is hidden', function() {
			var sequence = [];
			var plugin = this.plugin = {
				beforeDatasetDraw: function(chart, args) {
					sequence.push('before-' + args.index);
				},
				afterDatasetDraw: function(chart, args) {
					sequence.push('after-' + args.index);
				}
			};

			window.acquireChart({
				type: 'line',
				data: {datasets: [{}, {hidden: true}, {}]},
				plugins: [plugin]
			});

			expect(sequence).toEqual([
				'before-2', 'after-2',
				'before-0', 'after-0'
			]);
		});
	});

	describe('controller.update', function() {
		beforeEach(function() {
			this.chart = acquireChart({
				type: 'doughnut',
				options: {
					animation: {
						easing: 'linear',
						duration: 500
					}
				}
			});

			this.addAnimationSpy = spyOn(Chart.animationService, 'addAnimation');
		});

		it('should add an animation with the default options', function() {
			this.chart.update();

			expect(this.addAnimationSpy).toHaveBeenCalledWith(
				this.chart,
				jasmine.objectContaining({easing: 'linear'}),
				undefined,
				undefined
			);
		});

		it('should add an animation with the provided options', function() {
			this.chart.update({
				duration: 800,
				easing: 'easeOutBounce',
				lazy: false,
			});

			expect(this.addAnimationSpy).toHaveBeenCalledWith(
				this.chart,
				jasmine.objectContaining({easing: 'easeOutBounce'}),
				800,
				false
			);
		});
	});
});