text:
/*
 * This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file
 * at the root of this project for more details.
 */
package io.github.nucleuspowered.nucleus.core.scaffold.service.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface APIService {

    Class<?> value();
}


text:
package com.appleframework.security.auth.token.store.redis;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;

import com.appleframework.security.auth.token.AuthenticationKeyGenerator;
import com.appleframework.security.auth.token.DefaultAuthenticationKeyGenerator;
import com.appleframework.security.auth.token.TokenStore;
import com.appleframework.security.core.auth.Authentication;
import com.appleframework.security.core.token.AccessToken;
import com.appleframework.security.core.token.ExpiringRefreshToken;
import com.appleframework.security.core.token.RefreshToken;

/**
 * @author efenderbosch
 */
public class RedisTokenStore implements TokenStore {

	private static final String ACCESS = "access:";
	private static final String AUTH_TO_ACCESS = "auth_to_access:";
	private static final String AUTH = "auth:";
	private static final String REFRESH_AUTH = "refresh_auth:";
	private static final String ACCESS_TO_REFRESH = "access_to_refresh:";
	private static final String REFRESH = "refresh:";
	private static final String REFRESH_TO_ACCESS = "refresh_to_access:";
	private static final String CLIENT_ID_TO_ACCESS = "client_id_to_access:";
	private static final String UNAME_TO_ACCESS = "uname_to_access:";

	private final RedisConnectionFactory connectionFactory;
	private AuthenticationKeyGenerator authenticationKeyGenerator = new DefaultAuthenticationKeyGenerator();
	private RedisTokenStoreSerializationStrategy serializationStrategy = new JdkSerializationStrategy();

	public RedisTokenStore(RedisConnectionFactory connectionFactory) {
		this.connectionFactory = connectionFactory;
	}

	public void setAuthenticationKeyGenerator(AuthenticationKeyGenerator authenticationKeyGenerator) {
		this.authenticationKeyGenerator = authenticationKeyGenerator;
	}

	public void setSerializationStrategy(RedisTokenStoreSerializationStrategy serializationStrategy) {
		this.serializationStrategy = serializationStrategy;
	}

	private RedisConnection getConnection() {
		return connectionFactory.getConnection();
	}

	private byte[] serialize(Object object) {
		return serializationStrategy.serialize(object);
	}

	private AccessToken deserializeAccessToken(byte[] bytes) {
		return serializationStrategy.deserialize(bytes, AccessToken.class);
	}

	private Authentication deserializeAuthentication(byte[] bytes) {
		return serializationStrategy.deserialize(bytes, Authentication.class);
	}

	private RefreshToken deserializeRefreshToken(byte[] bytes) {
		return serializationStrategy.deserialize(bytes, RefreshToken.class);
	}

	private byte[] serialize(String string) {
		return serializationStrategy.serialize(string);
	}

	private String deserializeString(byte[] bytes) {
		return serializationStrategy.deserializeString(bytes);
	}

	@Override
	public AccessToken getAccessToken(Authentication authentication) {
		String key = authenticationKeyGenerator.extractKey(authentication);
		byte[] serializedKey = serialize(AUTH_TO_ACCESS + key);
		byte[] bytes = null;
		RedisConnection conn = getConnection();
		try {
			bytes = conn.get(serializedKey);
		} finally {
			conn.close();
		}
		AccessToken accessToken = deserializeAccessToken(bytes);
		if (accessToken != null
				&& !key.equals(authenticationKeyGenerator.extractKey(readAuthentication(accessToken.getValue())))) {
			// Keep the stores consistent (maybe the same user is
			// represented by this authentication but the details have
			// changed)
			storeAccessToken(accessToken, authentication);
		}
		return accessToken;
	}

	@Override
	public Authentication readAuthentication(AccessToken token) {
		return readAuthentication(token.getValue());
	}

	@Override
	public Authentication readAuthentication(String token) {
		byte[] bytes = null;
		RedisConnection conn = getConnection();
		try {
			bytes = conn.get(serialize(AUTH + token));
		} finally {
			conn.close();
		}
		Authentication auth = deserializeAuthentication(bytes);
		return auth;
	}

	@Override
	public Authentication readAuthenticationForRefreshToken(RefreshToken token) {
		return readAuthenticationForRefreshToken(token.getValue());
	}

	public Authentication readAuthenticationForRefreshToken(String token) {
		RedisConnection conn = getConnection();
		try {
			byte[] bytes = conn.get(serialize(REFRESH_AUTH + token));
			Authentication auth = deserializeAuthentication(bytes);
			return auth;
		} finally {
			conn.close();
		}
	}

	@Override
	public void storeAccessToken(AccessToken token, Authentication authentication) {
		byte[] serializedAccessToken = serialize(token);
		byte[] serializedAuth = serialize(authentication);
		byte[] accessKey = serialize(ACCESS + token.getValue());
		byte[] authKey = serialize(AUTH + token.getValue());
		byte[] authToAccessKey = serialize(AUTH_TO_ACCESS + authenticationKeyGenerator.extractKey(authentication));
		byte[] approvalKey = serialize(UNAME_TO_ACCESS + getApprovalKey(authentication));
		byte[] clientId = serialize(CLIENT_ID_TO_ACCESS + authentication.getClientDetails().getClientId());

		RedisConnection conn = getConnection();
		try {
			conn.openPipeline();
			conn.set(accessKey, serializedAccessToken);
			conn.set(authKey, serializedAuth);
			conn.set(authToAccessKey, serializedAccessToken);
			if (!authentication.isClientOnly()) {
				conn.rPush(approvalKey, serializedAccessToken);
			}
			conn.rPush(clientId, serializedAccessToken);
			if (token.getExpiration() != null) {
				int seconds = token.getExpiresIn();
				conn.expire(accessKey, seconds);
				conn.expire(authKey, seconds);
				conn.expire(authToAccessKey, seconds);
				conn.expire(clientId, seconds);
				conn.expire(approvalKey, seconds);
			}
			RefreshToken refreshToken = token.getRefreshToken();
			if (refreshToken != null && refreshToken.getValue() != null) {
				byte[] refresh = serialize(token.getRefreshToken().getValue());
				byte[] auth = serialize(token.getValue());
				byte[] refreshToAccessKey = serialize(REFRESH_TO_ACCESS + token.getRefreshToken().getValue());
				conn.set(refreshToAccessKey, auth);
				byte[] accessToRefreshKey = serialize(ACCESS_TO_REFRESH + token.getValue());
				conn.set(accessToRefreshKey, refresh);
				if (refreshToken instanceof ExpiringRefreshToken) {
					ExpiringRefreshToken expiringRefreshToken = (ExpiringRefreshToken) refreshToken;
					Date expiration = expiringRefreshToken.getExpiration();
					if (expiration != null) {
						int seconds = (int) (expiration.getTime() / 1000);
						conn.expireAt(refreshToAccessKey, seconds);
						conn.expireAt(accessToRefreshKey, seconds);
					}
				}
			}
			conn.closePipeline();
		} finally {
			conn.close();
		}
	}

	private static String getApprovalKey(Authentication authentication) {
		String userName = authentication.getUser().getUsername() == null ? "" : authentication.getUser().getUsername();
		return getApprovalKey(authentication.getClientDetails().getClientId(), userName);
	}

	private static String getApprovalKey(String clientId, String userName) {
		return clientId + (userName == null ? "" : ":" + userName);
	}

	@Override
	public void removeAccessToken(AccessToken accessToken) {
		removeAccessToken(accessToken.getValue());
	}

	@Override
	public AccessToken readAccessToken(String tokenValue) {
		byte[] key = serialize(ACCESS + tokenValue);
		byte[] bytes = null;
		RedisConnection conn = getConnection();
		try {
			bytes = conn.get(key);
		} finally {
			conn.close();
		}
		AccessToken accessToken = deserializeAccessToken(bytes);
		return accessToken;
	}

	public void removeAccessToken(String tokenValue) {
		byte[] accessKey = serialize(ACCESS + tokenValue);
		byte[] authKey = serialize(AUTH + tokenValue);
		byte[] accessToRefreshKey = serialize(ACCESS_TO_REFRESH + tokenValue);
		RedisConnection conn = getConnection();
		try {
			conn.openPipeline();
			conn.get(accessKey);
			conn.get(authKey);
			conn.del(accessKey);
			conn.del(accessToRefreshKey);
			// Don't remove the refresh token - it's up to the caller to do that
			conn.del(authKey);
			List<Object> results = conn.closePipeline();
			byte[] access = (byte[]) results.get(0);
			byte[] auth = (byte[]) results.get(1);

			Authentication authentication = deserializeAuthentication(auth);
			if (authentication != null) {
				String key = authenticationKeyGenerator.extractKey(authentication);
				byte[] authToAccessKey = serialize(AUTH_TO_ACCESS + key);
				byte[] unameKey = serialize(UNAME_TO_ACCESS + getApprovalKey(authentication));
				byte[] clientId = serialize(CLIENT_ID_TO_ACCESS + authentication.getClientDetails().getClientId());
				conn.openPipeline();
				conn.del(authToAccessKey);
				conn.lRem(unameKey, 1, access);
				conn.lRem(clientId, 1, access);
				conn.del(serialize(ACCESS + key));
				conn.closePipeline();
			}
		} finally {
			conn.close();
		}
	}

	@Override
	public void storeRefreshToken(RefreshToken refreshToken, Authentication authentication) {
		byte[] refreshKey = serialize(REFRESH + refreshToken.getValue());
		byte[] refreshAuthKey = serialize(REFRESH_AUTH + refreshToken.getValue());
		byte[] serializedRefreshToken = serialize(refreshToken);
		RedisConnection conn = getConnection();
		try {
			conn.openPipeline();
			conn.set(refreshKey, serializedRefreshToken);
			conn.set(refreshAuthKey, serialize(authentication));
			if (refreshToken instanceof ExpiringRefreshToken) {
				ExpiringRefreshToken expiringRefreshToken = (ExpiringRefreshToken) refreshToken;
				Date expiration = expiringRefreshToken.getExpiration();
				if (expiration != null) {
					int seconds = (int) (expiration.getTime() / 1000);
					conn.expireAt(refreshKey, seconds);
					conn.expireAt(refreshAuthKey, seconds);
				}
			}
			conn.closePipeline();
		} finally {
			conn.close();
		}
	}

	@Override
	public RefreshToken readRefreshToken(String tokenValue) {
		byte[] key = serialize(REFRESH + tokenValue);
		byte[] bytes = null;
		RedisConnection conn = getConnection();
		try {
			bytes = conn.get(key);
		} finally {
			conn.close();
		}
		RefreshToken refreshToken = deserializeRefreshToken(bytes);
		return refreshToken;
	}

	@Override
	public void removeRefreshToken(RefreshToken refreshToken) {
		removeRefreshToken(refreshToken.getValue());
	}

	public void removeRefreshToken(String tokenValue) {
		byte[] refreshKey = serialize(REFRESH + tokenValue);
		byte[] refresh2AccessKey = serialize(REFRESH_TO_ACCESS + tokenValue);
		byte[] access2RefreshKey = serialize(ACCESS_TO_REFRESH + tokenValue);
		RedisConnection conn = getConnection();
		try {
			conn.openPipeline();
			conn.del(refreshKey);
			conn.del(refresh2AccessKey);
			conn.del(access2RefreshKey);
			conn.closePipeline();
		} finally {
			conn.close();
		}
	}

	@Override
	public void removeAccessTokenUsingRefreshToken(RefreshToken refreshToken) {
		removeAccessTokenUsingRefreshToken(refreshToken.getValue());
	}

	private void removeAccessTokenUsingRefreshToken(String refreshToken) {
		byte[] key = serialize(REFRESH_TO_ACCESS + refreshToken);
		List<Object> results = null;
		RedisConnection conn = getConnection();
		try {
			conn.openPipeline();
			conn.get(key);
			conn.del(key);
			results = conn.closePipeline();
		} finally {
			conn.close();
		}
		if (results == null) {
			return;
		}
		byte[] bytes = (byte[]) results.get(0);
		String accessToken = deserializeString(bytes);
		if (accessToken != null) {
			removeAccessToken(accessToken);
		}
	}

	@Override
	public Collection<AccessToken> findTokensByClientIdAndUserName(String clientId, String userName) {
		byte[] approvalKey = serialize(UNAME_TO_ACCESS + getApprovalKey(clientId, userName));
		List<byte[]> byteList = null;
		RedisConnection conn = getConnection();
		try {
			byteList = conn.lRange(approvalKey, 0, -1);
		} finally {
			conn.close();
		}
		if (byteList == null || byteList.size() == 0) {
			return Collections.<AccessToken> emptySet();
		}
		List<AccessToken> accessTokens = new ArrayList<AccessToken>(byteList.size());
		for (byte[] bytes : byteList) {
			AccessToken accessToken = deserializeAccessToken(bytes);
			accessTokens.add(accessToken);
		}
		return Collections.<AccessToken> unmodifiableCollection(accessTokens);
	}

	@Override
	public Collection<AccessToken> findTokensByClientId(String clientId) {
		byte[] key = serialize(CLIENT_ID_TO_ACCESS + clientId);
		List<byte[]> byteList = null;
		RedisConnection conn = getConnection();
		try {
			byteList = conn.lRange(key, 0, -1);
		} finally {
			conn.close();
		}
		if (byteList == null || byteList.size() == 0) {
			return Collections.<AccessToken> emptySet();
		}
		List<AccessToken> accessTokens = new ArrayList<AccessToken>(byteList.size());
		for (byte[] bytes : byteList) {
			AccessToken accessToken = deserializeAccessToken(bytes);
			accessTokens.add(accessToken);
		}
		return Collections.<AccessToken> unmodifiableCollection(accessTokens);
	}
}

redpajama_set_name: RedPajamaGithub


text:
package com.cebedo.pmsys.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cebedo.pmsys.bean.PairCountValue;
import com.cebedo.pmsys.bean.PayrollResultComputation;
import com.cebedo.pmsys.constants.ConstantsRedis;
import com.cebedo.pmsys.domain.Attendance;
import com.cebedo.pmsys.domain.ProjectPayroll;
import com.cebedo.pmsys.enums.StatusAttendance;
import com.cebedo.pmsys.helper.AuthHelper;
import com.cebedo.pmsys.helper.MessageHelper;
import com.cebedo.pmsys.model.Project;
import com.cebedo.pmsys.model.Staff;
import com.cebedo.pmsys.pojo.JSONPayrollResult;
import com.cebedo.pmsys.service.AttendanceService;
import com.cebedo.pmsys.service.ProjectPayrollComputerService;
import com.cebedo.pmsys.service.StaffService;
import com.cebedo.pmsys.utils.DataStructUtils;
import com.google.gson.Gson;

/**
 * TODO Don't make this a service. Just a computer/statistics class.
 */
@Service
public class ProjectPayrollComputerServiceImpl implements ProjectPayrollComputerService {

    private AuthHelper authHelper = new AuthHelper();
    private MessageHelper messageHelper = new MessageHelper();
    private AttendanceService attendanceService;
    private StaffService staffService;

    public void setStaffService(StaffService staffService) {
	this.staffService = staffService;
    }

    public void setAttendanceService(AttendanceService s) {
	this.attendanceService = s;
    }

    public ProjectPayrollComputerServiceImpl() {
	;
    }

    // In this "proj", we are computing "staffIDsToCompute",
    // in range "startDate", "endDate".
    private ProjectPayroll projectPayroll;
    private List<Long> staffIDsToCompute;
    private Date startDate, endDate;

    // Map of staff and corresponding wage.
    private Map<Staff, Double> staffToWageMap = new HashMap<Staff, Double>();

    // Total wage for group "managersTotal".
    private double overallTotalOfStaff = 0;

    // "allStaffWageBreakdown" Attendance status with corresponding count map.
    // This is the breakdown of total for each staff.
    private Map<Staff, Map<StatusAttendance, PairCountValue>> staffPayrollBreakdownMap = new HashMap<Staff, Map<StatusAttendance, PairCountValue>>();

    // JSON tree grid.
    private List<JSONPayrollResult> treeGrid = new ArrayList<JSONPayrollResult>();

    // Results.
    private PayrollResultComputation payrollResult = new PayrollResultComputation();
    private Map<StatusAttendance, Integer> overallBreakdownCountMap = new HashMap<StatusAttendance, Integer>();
    private Map<StatusAttendance, Double> overallBreakdownWageMap = new HashMap<StatusAttendance, Double>();

    /**
     * Clear old data.
     */
    private void clear() {
	this.staffIDsToCompute = null;
	this.startDate = null;
	this.endDate = null;

	this.staffToWageMap = new HashMap<Staff, Double>();
	this.overallTotalOfStaff = 0;

	this.staffPayrollBreakdownMap = new HashMap<Staff, Map<StatusAttendance, PairCountValue>>();
	this.treeGrid = new ArrayList<JSONPayrollResult>();

	this.payrollResult = new PayrollResultComputation();
	this.overallBreakdownCountMap = new HashMap<StatusAttendance, Integer>();
	this.overallBreakdownWageMap = new HashMap<StatusAttendance, Double>();
    }

    /**
     * Put the staff's wage breakdown.
     *
     * @param staff
     */
    private void putStaffBreakdown(Staff staff) {
	Map<StatusAttendance, PairCountValue> attendanceStatusCountMap = getStaffBreakdownMap(
		this.projectPayroll.getProject(), staff, this.startDate, this.endDate);
	this.staffPayrollBreakdownMap.put(staff, attendanceStatusCountMap);
    }

    /**
     * Compute staff.
     */
    private void compute() {

	// this.staffIDsToCompute

	for (Staff staff : this.projectPayroll.getAssignedStaffList()) {

	    // Get the staff,
	    // check if already computed.
	    long staffID = staff.getId();
	    if (!this.staffIDsToCompute.contains(staffID)) {
		continue;
	    }

	    // Get wage then add to map.
	    // Get the total of this guy.
	    double staffWageTotal = this.attendanceService.getTotalWageOfStaffInRange(
		    this.projectPayroll.getProject(), staff, this.startDate, this.endDate);

	    // Add it to the overall total of managers.
	    this.overallTotalOfStaff += staffWageTotal;

	    // Add the value to the map.
	    // And to the "already computed" map.
	    this.staffToWageMap.put(staff, staffWageTotal);

	    // Get the breakdown of this total.
	    // Add the breakdown to the map.
	    putStaffBreakdown(staff);
	}
    }

    /**
     * Get the breakdown of the total wage.
     *
     * @param project
     *
     * @param manager
     * @param min
     * @param max
     * @return
     */
    private Map<StatusAttendance, PairCountValue> getStaffBreakdownMap(Project project, Staff manager,
	    Date min, Date max) {
	// Attendance count map.
	Set<Attendance> attendanceList = this.attendanceService.rangeStaffAttendance(project, manager,
		min, max);
	Map<StatusAttendance, PairCountValue> attendanceStatusCountMap = this.staffService
		.getAttendanceStatusCountMap(attendanceList);
	return attendanceStatusCountMap;
    }

    /**
     * Construct the JSON equivalent of the result computation.
     *
     * @return
     */
    @Transactional
    @Override
    public String getPayrollJSONResult() {
	try {
	    constructTreeGridStaff();
	    return new Gson().toJson(this.treeGrid, ArrayList.class);
	} catch (Exception e) {
	    e.printStackTrace();
	}
	return "";
    }

    /**
     * Get the count breakdown.
     *
     * @param staffWageBreakdown
     * @param overtime
     * @return
     */
    private int getBreakdownCount(Map<StatusAttendance, PairCountValue> staffWageBreakdown,
	    StatusAttendance status) {

	// Get the count, wage and format.
	double count = staffWageBreakdown.get(status).getCount();

	// Get the value.
	// Get the old value.
	// Add new value to old.
	int intValueOfCount = (int) count;
	int oldValue = this.overallBreakdownCountMap.get(status) == null ? 0
		: this.overallBreakdownCountMap.get(status);

	// Update overall breakdown.
	this.overallBreakdownCountMap.put(status, oldValue + intValueOfCount);

	return intValueOfCount;
    }

    /**
     * Get the wage breakdown.
     *
     * @param countAndWage
     * @return
     */
    private double getBreakdownWage(Map<StatusAttendance, PairCountValue> staffWageBreakdown,
	    StatusAttendance status) {

	// Get the count, wage and format.
	double wage = staffWageBreakdown.get(status).getValue();

	// Get the value.
	// Get the old value.
	// Add new value to old.
	double oldValue = this.overallBreakdownWageMap.get(status) == null ? 0
		: this.overallBreakdownWageMap.get(status);

	// Update overall.
	this.overallBreakdownWageMap.put(status, oldValue + wage);

	return wage;
    }

    /**
     * Get the staff's breakdown of attendance count and wage.
     *
     * @param staffWageBreakdown
     * @param rowBean
     * @return
     */
    private JSONPayrollResult setAttendanceBreakdown(
	    Map<StatusAttendance, PairCountValue> staffWageBreakdown, JSONPayrollResult rowBean) {

	// OVERTIME.
	rowBean.setBreakdownOvertimeCount(
		getBreakdownCount(staffWageBreakdown, StatusAttendance.OVERTIME));
	rowBean.setBreakdownOvertimeWage(
		getBreakdownWage(staffWageBreakdown, StatusAttendance.OVERTIME));

	// ABSENT.
	rowBean.setBreakdownAbsentCount(getBreakdownCount(staffWageBreakdown, StatusAttendance.ABSENT));
	rowBean.setBreakdownAbsentWage(getBreakdownWage(staffWageBreakdown, StatusAttendance.ABSENT));

	// HALFDAY.
	rowBean.setBreakdownHalfdayCount(
		getBreakdownCount(staffWageBreakdown, StatusAttendance.HALFDAY));
	rowBean.setBreakdownHalfdayWage(getBreakdownWage(staffWageBreakdown, StatusAttendance.HALFDAY));

	// LATE.
	rowBean.setBreakdownLateCount(getBreakdownCount(staffWageBreakdown, StatusAttendance.LATE));
	rowBean.setBreakdownLateWage(getBreakdownWage(staffWageBreakdown, StatusAttendance.LATE));

	// LEAVE.
	rowBean.setBreakdownLeaveCount(getBreakdownCount(staffWageBreakdown, StatusAttendance.LEAVE));
	rowBean.setBreakdownLeaveWage(getBreakdownWage(staffWageBreakdown, StatusAttendance.LEAVE));

	// PRESENT.
	rowBean.setBreakdownPresentCount(
		getBreakdownCount(staffWageBreakdown, StatusAttendance.PRESENT));
	rowBean.setBreakdownPresentWage(getBreakdownWage(staffWageBreakdown, StatusAttendance.PRESENT));

	return rowBean;
    }

    /**
     * TODO Improve this class.
     *
     * @param staffToWageMap
     * @param staffPayrollBreakdownMap
     * @return
     */
    @Transactional
    @Override
    public String getPayrollJSONResult(Map<Staff, Double> staffToWageMap,
	    Map<Staff, Map<StatusAttendance, PairCountValue>> staffPayrollBreakdownMap) {

	List<JSONPayrollResult> treeGrid = new ArrayList<JSONPayrollResult>();

	// Sort by formal name.
	Set<Staff> staffSet = staffToWageMap.keySet();
	List<Staff> staffList = DataStructUtils.convertSetToList(staffSet);
	Collections.sort(staffList, new Comparator<Staff>() {
	    @Override
	    public int compare(Staff aObj, Staff bObj) {
		if (aObj == null && bObj == null) {
		    return 0;
		} else if (aObj == null) {
		    return 1;
		} else if (bObj == null) {
		    return -1;
		}
		String aName = aObj.getFormalName();
		String bName = bObj.getFormalName();

		int a = aName.compareToIgnoreCase(bName);
		return a < 0 ? -1 : a > 0 ? 1 : 0;
	    }
	});

	// Loop through all staff.
	for (Staff staff : staffList) {

	    if (staff == null) {
		continue;
	    }

	    // Get details.
	    Double rowValue = staffToWageMap.get(staff);
	    if (rowValue == null) {
		rowValue = (double) 0;
	    }

	    // Add to bean.
	    JSONPayrollResult rowBean = new JSONPayrollResult(staff.getFormalName(), rowValue,
		    staff.getWage());

	    // Breakdown.
	    Map<StatusAttendance, PairCountValue> staffWageBreakdown = staffPayrollBreakdownMap
		    .get(staff);
	    rowBean = setAttendanceBreakdown(staffWageBreakdown, rowBean);

	    // Add to tree grid list.
	    treeGrid.add(rowBean);
	}

	return new Gson().toJson(treeGrid, ArrayList.class);
    }

    /**
     * Get partial tree grid for managers.
     *
     * @param managerPayrollMap
     * @param headerManagerPKey
     * @param randomno
     * @param this.formatter
     * @param this.treeGrid
     * @param allStaffWageBreakdown
     * @return
     */
    private void constructTreeGridStaff() {

	// Sort by formal name.
	Set<Staff> staffSet = this.staffToWageMap.keySet();
	List<Staff> staffList = DataStructUtils.convertSetToList(staffSet);
	Collections.sort(staffList, new Comparator<Staff>() {
	    @Override
	    public int compare(Staff aObj, Staff bObj) {
		String aName = aObj.getFormalName();
		String bName = bObj.getFormalName();

		int a = aName.compareToIgnoreCase(bName);
		return a < 0 ? -1 : a > 0 ? 1 : 0;
	    }
	});

	// Loop through all staff.
	for (Staff staff : staffList) {

	    // Get details.
	    double rowValue = this.staffToWageMap.get(staff);

	    // Add to bean.
	    JSONPayrollResult rowBean = new JSONPayrollResult(staff.getFormalName(), rowValue,
		    staff.getWage());

	    // Breakdown.
	    Map<StatusAttendance, PairCountValue> staffWageBreakdown = this.staffPayrollBreakdownMap
		    .get(staff);
	    rowBean = setAttendanceBreakdown(staffWageBreakdown, rowBean);

	    // Add to tree grid list.
	    this.treeGrid.add(rowBean);
	}
    }

    @Transactional
    @Override
    public void compute(Date min, Date max, ProjectPayroll projectPayroll) {

	// Security check.
	if (!this.authHelper.hasAccess(projectPayroll)) {
	    this.messageHelper.unauthorizedKey(ConstantsRedis.OBJECT_PAYROLL, projectPayroll.getKey());
	    return;
	}

	// Clear old data.
	clear();

	// Initialize.
	this.startDate = min;
	this.endDate = max;
	this.projectPayroll = projectPayroll;
	this.staffIDsToCompute = DataStructUtils.convertArrayToList(projectPayroll.getStaffIDs());

	// Compute.
	compute();
	results();
    }

    private void results() {
	this.payrollResult.setStartDate(this.startDate);
	this.payrollResult.setEndDate(this.endDate);
	this.payrollResult.setOverallTotalOfStaff(this.overallTotalOfStaff);
	this.payrollResult.setStaffPayrollBreakdownMap(this.staffPayrollBreakdownMap);
	this.payrollResult.setStaffToWageMap(this.staffToWageMap);
	this.payrollResult.setTreeGrid(this.treeGrid);
    }

    @Transactional
    @Override
    public PayrollResultComputation getPayrollResult() {
	return payrollResult;
    }

}


text:
var searchData=
[
  ['videoimagebuffer',['VideoImageBuffer',['../classVideoImageBuffer.html',1,'']]],
  ['videothread',['VideoThread',['../classVideoThread.html',1,'']]]
];


text:
<title>Zend Framework API Documentation</title><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta><link rel="stylesheet" href="css/black-tie/jquery-ui-1.8.2.custom.css" type="text/css"></link><link rel="stylesheet" href="css/jquery.treeview.css" type="text/css"></link><link rel="stylesheet" href="css/theme.css" type="text/css"></link>

API Documentation

Service/WindowsAzure/Storage/TableInstance.php

Global

                      Classes

\Zend_Service_WindowsAzure_Storage_TableInstance

Zend Framework

LICENSE

This source file is subject to the new BSD license that is bundled
with this package in the file LICENSE.txt.
It is also available through the world-wide-web at this URL:
http://framework.zend.com/license/new-bsd
If you did not receive a copy of the license and are unable to
obtain it through the world-wide-web, please send an email
to license@zend.com so we can send you a copy immediately.

category

Zend

copyright

Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)

license

New BSD License

package

Zend_Service_WindowsAzure

subpackage

Storage

version

$Id: TableInstance.php 23775 2011-03-01 17:25:24Z ralph $

\Zend_Service_WindowsAzure_Storage_TableInstance
jump to top

Extends from

\Zend_Service_WindowsAzure_Storage_StorageEntityAbstract

category

Zend

copyright

Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)

license

New BSD License

package

Zend_Service_WindowsAzure

subpackage

Storage

Properties

string
                 $Href= ''

Href
Href

Details

Type

string

magic

property

Href

string
                 $Id= ''

Id
Id

Details

Type

string

magic

property

Id

string
                 $Name= ''

Name
Name

Details

Type

string

magic

property

Name

string
                 $Updated= ''

Updated
Updated

Details

Type

string

magic

property

Updated

Methods

__construct(
          string $id, string $name, string $href, string $updated
          )

        :
          void

Constructor

Parameters

Name
Type
Description

$id
string
Id

$name
string
Name

$href
string
Href

$updated
string
Updated

__get(
          string $name
          )

        :
          void

Magic overload for getting properties

Inherited from:
                    \Zend_Service_WindowsAzure_Storage_StorageEntityAbstract::__get()

Parameters

Name
Type
Description

$name
string
Name of the property

__set(
          string $name, string $value
          )

        :
          void

Magic overload for setting properties

Inherited from:
                    \Zend_Service_WindowsAzure_Storage_StorageEntityAbstract::__set()

Parameters

Name
Type
Description

$name
string
Name of the property

$value
string
Value to set

Documentation was generated by DocBlox 0.13.3.


text:
package io.irontest.models.testrun;

/**
 * Used for collecting data when running one test case.
 */
public class TestcaseRun extends TestRun {
    private long testcaseId;
    private String testcaseName;
    private String testcaseFolderPath;

    public TestcaseRun() {}

    public TestcaseRun(TestcaseRun testcaseRun) {
        super.setId(testcaseRun.getId());
        super.setResult(testcaseRun.getResult());
        super.setStartTime(testcaseRun.getStartTime());
        super.setDuration(testcaseRun.getDuration());
        this.testcaseId = testcaseRun.getTestcaseId();
        this.testcaseName = testcaseRun.getTestcaseName();
        this.testcaseFolderPath = testcaseRun.getTestcaseFolderPath();
    }

    public long getTestcaseId() {
        return testcaseId;
    }

    public void setTestcaseId(long testcaseId) {
        this.testcaseId = testcaseId;
    }

    public String getTestcaseName() {
        return testcaseName;
    }

    public void setTestcaseName(String testcaseName) {
        this.testcaseName = testcaseName;
    }

    public String getTestcaseFolderPath() {
        return testcaseFolderPath;
    }

    public void setTestcaseFolderPath(String testcaseFolderPath) {
        this.testcaseFolderPath = testcaseFolderPath;
    }
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Andropogon australis var. genuinus Hack.

### Remarks
null


text:
<?php

namespace AppBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use APY\DataGridBundle\Grid\Mapping as GRID;

/**
 * @ORM\Entity
 * @ORM\Table(name="offer")
 * @GRID\Source(columns="id, name, destination, description, isActive, offerCategory.name, brand.name")
 */
class Offer {
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     *
     * @GRID\Column(title="Id", type="number", operatorsVisible=false)
     */
    protected $id;

    /**
     * @ORM\Column(type="string", length=255)
     *
     * @GRID\Column(title="Name", type="text", operatorsVisible=false)
     */
    protected $name;

    /**
     * @ORM\Column(type="string", length=500)
     *
     * @GRID\Column(title="Destination", type="text", operatorsVisible=false)
     */
    protected $destination
    ;
    /**
     * @ORM\Column(type="text")
     *
     * @GRID\Column(title="Description", type="text", operatorsVisible=false)
     */
    protected $description;

    /**
     * @ORM\Column(type="boolean")
     *
     * @GRID\Column(title="Is Active", type="boolean", operatorsVisible=false)
     */
    protected $isActive;

    /**
     * @ORM\ManyToOne(targetEntity="OfferCategory", inversedBy="offers")
     *
     * @GRID\Column(field="offerCategory.name", title="Category", operatorsVisible=false, filter="select", selectFrom="query")
     */
    protected $offerCategory;

    /**
     * @ORM\ManyToOne(targetEntity="Brand", inversedBy="offers")
     *
     * @GRID\Column(field="brand.name", title="Brand", operatorsVisible=false, filter="select", selectFrom="query")
     */
    protected $brand;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return Brand
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @return mixed
     */
    public function getDestination()
    {
        return $this->destination;
    }

    /**
     * @param mixed $destination
     * @return Brand
     */
    public function setDestination($destination)
    {
        $this->destination = $destination;

        return $this;
    }

    /**
     * @return mixed
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * @param mixed $description
     * @return Brand
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Set isActive
     *
     * @param boolean $isActive
     * @return Brand
     */
    public function setIsActive($isActive)
    {
        $this->isActive = $isActive;

        return $this;
    }

    /**
     * Get isActive
     *
     * @return boolean
     */
    public function getIsActive()
    {
        return $this->isActive;
    }

    /**
     * Set brand
     *
     * @param \AppBundle\Entity\User $brand
     * @return User
     */
    public function setBrand(\AppBundle\Entity\User $brand = null)
    {
        $this->brand = $brand;

        return $this;
    }

    /**
     * Get brand
     *
     * @return \AppBundle\Entity\User
     */
    public function getBrand()
    {
        return $this->brand;
    }

    /**
     * Set offerCategory
     *
     * @param \AppBundle\Entity\OfferCategory $offerCategory
     * @return Offer
     */
    public function setOfferCategory(\AppBundle\Entity\OfferCategory $offerCategory = null)
    {
        $this->offerCategory = $offerCategory;

        return $this;
    }

    /**
     * Get offerCategory
     *
     * @return \AppBundle\Entity\OfferCategory
     */
    public function getOfferCategory()
    {
        return $this->offerCategory;
    }
}


text:
import Peer from './peer';

const User = Peer.extend({
  serialize() {
    const data = {
      uuid: this.uuid,
      public_ip: this.public_ip,
      label: this.label,
      avatarUrl: this.avatarUrl,
      peer: {
        id: this.get('peer.id'),
      },
    };

    return data;
  },
});

export default User;


text:
package org.motechproject.mds.util;

import org.apache.commons.lang.StringUtils;

/**
 * Utility class for dealing with lookup names.
 */
public final class LookupName {

    /**
     * Builds lookup method name, based on the lookup name. The resulting method name is
     * camelCase, based on the words in the lookup.
     *
     * @param lookupName name of the lookup
     * @return camelCase lookup method name
     */
    public static String lookupMethod(String lookupName) {
        if (StringUtils.isBlank(lookupName)) {
            return lookupName;
        }
        // first split by space
        String[] words = StringUtils.split(lookupName, ' ');
        // then create camel case
        // first word starts with lower case
        StringBuilder sb = new StringBuilder(StringUtils.uncapitalize(words[0]));
        // rest with upper case
        for (int i = 1; i < words.length; i++) {
            sb.append(StringUtils.capitalize(words[i]));
        }

        return sb.toString();
    }

    /**
     * Builds count lookup name. The resulting method name will be in form: countXxxYyyZzz.
     *
     * @param lookupNameOrMethodName name of the lookup or lookup method name
     * @return count lookup method name
     */
    public static String lookupCountMethod(String lookupNameOrMethodName) {
        return "count" + StringUtils.capitalize(lookupMethod(lookupNameOrMethodName));
    }

    /**
     * Builds lookup field name which may contain information about the searching by relationship.
     *
     * @param fieldName The name of the field from entity
     * @param relatedFieldName The name of the field in related entity
     * @return lookup field name
     */
    public static String buildLookupFieldName(String fieldName, String relatedFieldName) {
        if (StringUtils.isNotBlank(relatedFieldName)) {
            return String.format("%s.%s", fieldName, relatedFieldName);
        }
        return fieldName;
    }

    /**
     * Returns a field name in related entity.
     *
     * @param lookupFieldName the lookup field name
     * @return field name from related entity
     */
    public static String getRelatedFieldName(String lookupFieldName) {
        if (lookupFieldName.contains(".")) {
            return lookupFieldName.split("\\.")[1];
        }
        return null;
    }

    /**
     * Returns the name of the field from entity.
     *
     * @param lookupFieldName the lookup field name
     * @return field name from entity
     */
    public static String getFieldName(String lookupFieldName) {
        if (lookupFieldName.contains(".")) {
            return lookupFieldName.split("\\.")[0];
        }
        return lookupFieldName;
    }

    private LookupName() {
    }
}


text:
package com.example.user.mymapfinal;

import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.MarkerOptions;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class BookDesMap extends FragmentActivity {

    MarkerOptions markerOptions;
    LatLng latLng;
    double lat,lng;
    String addressText;
    String id;
    String source;
    String location;
    private GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRequest;
    SharedPreferences sharedPreferences;
    public static final String TAG = MapsActivity.class.getSimpleName();
    private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
    int locationCount = 0;

    private GoogleMap mMap; // Might be null if Google Play services APK is not available.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_des_map);
        setUpMapIfNeeded();
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(SRILANKA.getCenter(), 8));

        SharedPreferences settings = getApplicationContext().getSharedPreferences("BookLocation", 0);
        settings.edit().remove("dest").commit();
        settings.edit().remove("destAdd").commit();
        SupportMapFragment supportMapFragment = (SupportMapFragment)
                getSupportFragmentManager().findFragmentById(R.id.map);
        Button confirm = (Button) findViewById(R.id.btnconfirm);
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                source= String.valueOf(lat)+","+String.valueOf(lng);

                Intent i = new Intent(getApplicationContext(), PassengerBOOKING.class);

                SharedPreferences pref = getApplicationContext().getSharedPreferences("BookLocation", 0);
                SharedPreferences.Editor editor = pref.edit();

                editor.putString("dest", source);
                editor.putString("destAdd",id);

                editor.commit();
                finish();
                startActivity(i);

            }
        });

        // Getting a reference to the map

        mMap.setMyLocationEnabled(true);

        // Setting a click event handler for the map
        mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {

            @Override
            public void onMapClick(LatLng arg0) {

                // Getting the Latitude and Longitude of the touched location
                latLng = arg0;

                // Clears the previously touched position
                //mMap.clear();

                // Animating to the touched position
                mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));

                // Creating a marker
                markerOptions = new MarkerOptions();

                // Setting the position for the marker
                markerOptions.position(latLng);

                // Placing a marker on the touched position
                mMap.addMarker(markerOptions);

                // Adding Marker on the touched location with address
                new GetAddressTask().execute(latLng);

                // new ReverseGeocodingTask(MainActivity.this).execute(latLng);

            }
        });
    }

    private LatLngBounds SRILANKA = new LatLngBounds(
            new LatLng(5.850, 79.600), new LatLng(9.920, 81.950));

    public class GetAddressTask extends AsyncTask<LatLng, String, Integer> {
        private LatLng loc;
        String filterAddress = "";
        String addressText="";

        @Override
        protected Integer doInBackground(LatLng... params) {
            int mFinalFlag = 0;
            loc = params[0];

            Geocoder geoCoder = new Geocoder(BookDesMap
                    .this, Locale.getDefault());
            try {
                List<Address> addresses = geoCoder.getFromLocation(loc.latitude,
                        loc.longitude, 1);

                if (addresses != null && addresses.size() > 0) {
                    Address address = addresses.get(0);
                    addressText = String.format(
                            "%s, %s, %s",
                            address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
                            address.getLocality(),
                            address.getCountryName());
                    lat = addresses.get(0).getLatitude();
                    lng = addresses.get(0).getLongitude();
                    Log.e("lat", "" + lat);
                    Log.e("lng", "" + lng);

                }

            } catch (IOException ex) {
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            this.publishProgress(addressText);

            return mFinalFlag;
        }

        @Override
        protected void onPostExecute(Integer result) {

            mMap.addMarker(
                    new MarkerOptions()
                            .position(loc)
                            .draggable(true)
                            .icon(BitmapDescriptorFactory
                                    .defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
                            .title(addressText))

                    .showInfoWindow();

            super.onPostExecute(result);

        }
        @Override
        protected void onProgressUpdate(String... values) {
            super.onProgressUpdate(values);

            id= values[0].toString();

        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
    }

    /**
     * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
     * installed) and the map has not already been instantiated.. This will ensure that we only ever
     * call {@link #setUpMap()} once when {@link #mMap} is not null.
     *

     * If it isn't installed {@link SupportMapFragment} (and
     * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
     * install/update the Google Play services APK on their device.
     *

     * A user can return to this FragmentActivity after following the prompt and correctly
     * installing/updating/enabling the Google Play services. Since the FragmentActivity may not
     * have been completely destroyed during this process (it is likely that it would only be
     * stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this
     * method in {@link #onResume()} to guarantee that it will be called.
     */
    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();
            }
        }
    }

    /**
     * This is where we can add markers or lines, add listeners or move the camera. In this case, we
     * just add a marker near Africa.
     *

     * This should only be called once and when we are sure that {@link #mMap} is not null.
     */
    private void setUpMap() {
        //mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
    }
}


text:
package com.gh.mygreen.xlsmapper.cellconverter.impl;

import java.util.Date;

import com.gh.mygreen.xlsmapper.Configuration;
import com.gh.mygreen.xlsmapper.cellconverter.CellConverter;
import com.gh.mygreen.xlsmapper.fieldaccessor.FieldAccessor;

/**
 * {@link java.sql.Date}を処理する{@link CellConverter}を作成するためのファクトリクラス。
 *
 * @version 2.0
 * @author T.TSUCHIE
 *
 */
public class SqlDateCellConverterFactory extends AbstractDateCellConverterFactory<java.sql.Date> {

    @Override
    public SqlDateCellConverter create(final FieldAccessor field, final Configuration config) {

        final SqlDateCellConverter cellConverter = new SqlDateCellConverter(field, config, this);
        setupCellConverter(cellConverter, field, config);

        return cellConverter;

    }

    @Override
    protected java.sql.Date convertTypeValue(final Date date) {
        return new java.sql.Date(date.getTime());
    }

    /**
     * {@inheritDoc}
     *
{@code yyyy-MM-dd}の値を返す。

     */
    @Override
    protected String getDefaultJavaPattern() {
        return "yyyy-MM-dd";
    }

    /**
     * {@inheritDoc}
     *
{@code yyyy-mm-dd}の値を返す。

     */
    @Override
    protected String getDefaultExcelPattern() {
        return "yyyy-mm-dd";
    }

    public class SqlDateCellConverter extends AbstractDateCellConverter<java.sql.Date> {

        private final SqlDateCellConverterFactory convererFactory;

        private SqlDateCellConverter(final FieldAccessor field, final Configuration config,
                final SqlDateCellConverterFactory convererFactory) {
            super(field, config);
            this.convererFactory = convererFactory;
        }

        @Override
        protected java.sql.Date convertTypeValue(final Date value) {
            return convererFactory.convertTypeValue(value);
        }

    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

  <title>Qt 4.8: QMacStyle Class Reference</title>
  <link rel="stylesheet" type="text/css" href="style/style.css" />

  <link rel="stylesheet" type="text/css" href="style/superfish.css" />
  <link rel="stylesheet" type="text/css" href="style/narrow.css" />

      Home

    Qt Reference Documentation

Qt HOME

DEV

          DOC

BLOG

Qt 4.8

ALL VERSIONS

API Lookup

Class index

Function index

Modules

Namespaces

Global Declarations

QML elements

Qt Topics

Programming with Qt

Device UIs & Qt Quick

UI Design with Qt

Supported Platforms

Qt and Key Technologies

How-To's and Best Practices

Examples

Examples

Tutorials

Demos

QML Examples

          Search index:

          <form id="qtdocsearch" action="" onsubmit="return false;">
            <fieldset>
              <input type="text" name="searchstring" id="pageType" value="" />

 Close

All | API | Articles | Examples

 results:

            </fieldset>
          </form>

            API Lookup

Class index

Function index

Modules

Namespaces

Global Declarations

QML elements

            Qt Topics

Programming with Qt

Device UIs & Qt Quick

UI Design with Qt

Supported Platforms

Qt and Key Technologies

How-To's and Best Practices

            Examples

Examples

Tutorials

Demos

QML Examples

Home

Modules

QtGui

QMacStyle

A

A

A

                Print

Contents

Public Types

Public Functions

Detailed Description

QMacStyle Class Reference

The QMacStyle class provides a Mac OS X style using the Apple Appearance Manager. More...

 #include <QMacStyle>

Inherits: QWindowsStyle.

List of all members, including inherited members

Obsolete members

Public Types

 enum 	FocusRectPolicy { FocusEnabled, FocusDisabled, FocusDefault }

 enum 	WidgetSizePolicy { SizeSmall, SizeLarge, SizeMini, SizeDefault }

Public Functions

 	QMacStyle ()

 virtual 	~QMacStyle ()

Reimplemented Public Functions

 virtual void 	drawComplexControl ( ComplexControl cc, const QStyleOptionComplex * opt, QPainter * p, const QWidget * widget = 0 ) const

 virtual void 	drawControl ( ControlElement ce, const QStyleOption * opt, QPainter * p, const QWidget * w = 0 ) const

 virtual void 	drawItemText ( QPainter * p, const QRect & r, int flags, const QPalette & pal, bool enabled, const QString & text, QPalette::ColorRole textRole = QPalette::NoRole ) const

 virtual void 	drawPrimitive ( PrimitiveElement pe, const QStyleOption * opt, QPainter * p, const QWidget * w = 0 ) const

 virtual bool 	event ( QEvent * e )

 virtual QPixmap 	generatedIconPixmap ( QIcon::Mode iconMode, const QPixmap & pixmap, const QStyleOption * opt ) const

 virtual SubControl 	hitTestComplexControl ( ComplexControl cc, const QStyleOptionComplex * opt, const QPoint & pt, const QWidget * widget = 0 ) const

 virtual int 	pixelMetric ( PixelMetric metric, const QStyleOption * opt = 0, const QWidget * widget = 0 ) const

 virtual void 	polish ( QWidget * w )

 virtual void 	polish ( QApplication * )

 virtual void 	polish ( QPalette & pal )

 virtual QSize 	sizeFromContents ( ContentsType ct, const QStyleOption * opt, const QSize & csz, const QWidget * widget = 0 ) const

 virtual QPalette 	standardPalette () const

 virtual QPixmap 	standardPixmap ( StandardPixmap standardPixmap, const QStyleOption * opt, const QWidget * widget = 0 ) const

 virtual int 	styleHint ( StyleHint sh, const QStyleOption * opt = 0, const QWidget * w = 0, QStyleHintReturn * hret = 0 ) const

 virtual QRect 	subControlRect ( ComplexControl cc, const QStyleOptionComplex * opt, SubControl sc, const QWidget * widget = 0 ) const

 virtual QRect 	subElementRect ( SubElement sr, const QStyleOption * opt, const QWidget * widget = 0 ) const

 virtual void 	unpolish ( QWidget * w )

 virtual void 	unpolish ( QApplication * )

13 public functions inherited from QWindowsStyle

16 public functions inherited from QCommonStyle

24 public functions inherited from QStyle

29 public functions inherited from QObject

Additional Inherited Members

1 property inherited from QObject

1 public slot inherited from QObject

1 signal inherited from QObject

6 static public members inherited from QStyle

7 static public members inherited from QObject

2 protected functions inherited from QWindowsStyle

8 protected functions inherited from QObject

2 protected slots inherited from QStyle

Detailed Description

The QMacStyle class provides a Mac OS X style using the Apple Appearance Manager.

This class is implemented as a wrapper to the HITheme APIs, allowing applications to be styled according to the current theme in use on Mac OS X. This is done by having primitives in QStyle implemented in terms of what Mac OS X would normally theme.

Warning: This style is only available on Mac OS X because it relies on the HITheme APIs.

There are additional issues that should be taken into consideration to make an application compatible with the Apple Human Interface Guidelines. Some of these issues are outlined below.

Layout - The restrictions on window layout are such that some aspects of layout that are style-dependent cannot be achieved using QLayout. Changes are being considered (and feedback would be appreciated) to make layouts QStyle-able. Some of the restrictions involve horizontal and vertical widget alignment and widget size (covered below).

Widget size - Mac OS X allows widgets to have specific fixed sizes. Qt does not fully implement this behavior so as to maintain cross-platform compatibility. As a result some widgets sizes may be inappropriate (and subsequently not rendered correctly by the HITheme APIs).The QWidget::sizeHint() will return the appropriate size for many managed widgets (widgets enumerated in QStyle::ContentsType).

Effects - QMacStyle uses HITheme for performing most of the drawing, but also uses emulation in a few cases where HITheme does not provide the required functionality (for example, tab bars on Panther, the toolbar separator, etc). We tried to make the emulation as close to the original as possible. Please report any issues you see in effects or non-standard widgets.

There are other issues that need to be considered in the feel of your application (including the general color scheme to match the Aqua colors). The Guidelines mentioned above will remain current with new advances and design suggestions for Mac OS X.

Note that the functions provided by QMacStyle are reimplementations of QStyle functions; see QStyle for their documentation.

See also QWindowsXPStyle, QWindowsStyle, QPlastiqueStyle, QCDEStyle, and QMotifStyle.

Member Type Documentation

enum QMacStyle::FocusRectPolicy

This type is used to signify a widget's focus rectangle policy.

Constant	Value	Description

<tt>QMacStyle::FocusEnabled</tt>	<tt>0</tt>	show a focus rectangle when the widget has focus.

<tt>QMacStyle::FocusDisabled</tt>	<tt>1</tt>	never show a focus rectangle for the widget.

<tt>QMacStyle::FocusDefault</tt>	<tt>2</tt>	show a focus rectangle when the widget has focus and the widget is a QSpinWidget, QDateTimeEdit, QLineEdit, QListBox, QListView, editable QTextEdit, or one of their subclasses.

enum QMacStyle::WidgetSizePolicy

Constant	Value

<tt>QMacStyle::SizeSmall</tt>	<tt>0</tt>

<tt>QMacStyle::SizeLarge</tt>	<tt>1</tt>

<tt>QMacStyle::SizeMini</tt>	<tt>2</tt>

<tt>QMacStyle::SizeDefault</tt>	<tt>3</tt>

Member Function Documentation

QMacStyle::QMacStyle ()

Constructs a QMacStyle object.

QMacStyle::~QMacStyle ()<tt> [virtual]</tt>

Destructs a QMacStyle object.

void QMacStyle::drawComplexControl ( ComplexControl cc, const QStyleOptionComplex * opt, QPainter * p, const QWidget * widget = 0 ) const<tt> [virtual]</tt>

Reimplemented from QStyle::drawComplexControl().

void QMacStyle::drawControl ( ControlElement ce, const QStyleOption * opt, QPainter * p, const QWidget * w = 0 ) const<tt> [virtual]</tt>

Reimplemented from QStyle::drawControl().

void QMacStyle::drawItemText ( QPainter * p, const QRect & r, int flags, const QPalette & pal, bool enabled, const QString & text, QPalette::ColorRole textRole = QPalette::NoRole ) const<tt> [virtual]</tt>

Reimplemented from QStyle::drawItemText().

void QMacStyle::drawPrimitive ( PrimitiveElement pe, const QStyleOption * opt, QPainter * p, const QWidget * w = 0 ) const<tt> [virtual]</tt>

Reimplemented from QStyle::drawPrimitive().

bool QMacStyle::event ( QEvent * e )<tt> [virtual]</tt>

Reimplemented from QObject::event().

QPixmap QMacStyle::generatedIconPixmap ( QIcon::Mode iconMode, const QPixmap & pixmap, const QStyleOption * opt ) const<tt> [virtual]</tt>

Reimplemented from QStyle::generatedIconPixmap().

SubControl QMacStyle::hitTestComplexControl ( ComplexControl cc, const QStyleOptionComplex * opt, const QPoint & pt, const QWidget * widget = 0 ) const<tt> [virtual]</tt>

Reimplemented from QStyle::hitTestComplexControl().

int QMacStyle::pixelMetric ( PixelMetric metric, const QStyleOption * opt = 0, const QWidget * widget = 0 ) const<tt> [virtual]</tt>

Reimplemented from QStyle::pixelMetric().

void QMacStyle::polish ( QWidget * w )<tt> [virtual]</tt>

Reimplemented from QStyle::polish().

void QMacStyle::polish ( QApplication * )<tt> [virtual]</tt>

Reimplemented from QStyle::polish().

void QMacStyle::polish ( QPalette & pal )<tt> [virtual]</tt>

Reimplemented from QStyle::polish().

QSize QMacStyle::sizeFromContents ( ContentsType ct, const QStyleOption * opt, const QSize & csz, const QWidget * widget = 0 ) const<tt> [virtual]</tt>

Reimplemented from QStyle::sizeFromContents().

QPalette QMacStyle::standardPalette () const<tt> [virtual]</tt>

Reimplemented from QStyle::standardPalette().

QPixmap QMacStyle::standardPixmap ( StandardPixmap standardPixmap, const QStyleOption * opt, const QWidget * widget = 0 ) const<tt> [virtual]</tt>

Reimplemented from QStyle::standardPixmap().

int QMacStyle::styleHint ( StyleHint sh, const QStyleOption * opt = 0, const QWidget * w = 0, QStyleHintReturn * hret = 0 ) const<tt> [virtual]</tt>

Reimplemented from QStyle::styleHint().

QRect QMacStyle::subControlRect ( ComplexControl cc, const QStyleOptionComplex * opt, SubControl sc, const QWidget * widget = 0 ) const<tt> [virtual]</tt>

Reimplemented from QStyle::subControlRect().

QRect QMacStyle::subElementRect ( SubElement sr, const QStyleOption * opt, const QWidget * widget = 0 ) const<tt> [virtual]</tt>

Reimplemented from QStyle::subElementRect().

void QMacStyle::unpolish ( QWidget * w )<tt> [virtual]</tt>

Reimplemented from QStyle::unpolish().

void QMacStyle::unpolish ( QApplication * )<tt> [virtual]</tt>

Reimplemented from QStyle::unpolish().

      <acronym title="Copyright">©</acronym> 2013 Digia Plc and/or its
      subsidiaries. Documentation contributions included herein are the copyrights of
      their respective owners.

      The documentation provided herein is licensed under the terms of the
      GNU Free Documentation
      License version 1.3 as published by the Free Software Foundation.

      Documentation sources may be obtained from
      www.qt-project.org.

      Digia, Qt and their respective logos are trademarks of Digia Plc
      in Finland and/or other countries worldwide. All other trademarks are property
      of their respective owners. Privacy Policy


text:
package io.jboot.db.dialect;

import com.jfinal.plugin.activerecord.dialect.SqlServerDialect;
import io.jboot.db.model.Column;
import io.jboot.db.model.SqlBuilder;
import io.jboot.db.model.Join;
import io.jboot.exception.JbootException;

import java.util.List;

public class JbootSqlServerDialect extends SqlServerDialect implements JbootDialect {

    @Override
    public String forFindByColumns(String alias, List<Join> joins, String table, String loadColumns, List<Column> columns, String orderBy, Object limit) {

        StringBuilder sqlBuilder = SqlBuilder.forFindByColumns(alias, joins, table, loadColumns, columns, orderBy, ' ');

        if (limit == null) {
            return sqlBuilder.toString();
        }

        if (limit instanceof Number) {
            StringBuilder ret = new StringBuilder();
            ret.append("SELECT * FROM ( SELECT row_number() over (order by tempcolumn) temprownumber, * FROM ");
            ret.append(" ( SELECT TOP ").append(limit).append(" tempcolumn=0,");
            ret.append(sqlBuilder.toString().replaceFirst("(?i)select", ""));
            ret.append(")vip)mvp ");
            return ret.toString();

        } else if (limit instanceof String && limit.toString().contains(",")) {
            String[] startAndEnd = limit.toString().split(",");
            String start = startAndEnd[0];
            String end = startAndEnd[1];

            StringBuilder ret = new StringBuilder();
            ret.append("SELECT * FROM ( SELECT row_number() over (order by tempcolumn) temprownumber, * FROM ");
            ret.append(" ( SELECT TOP ").append(end).append(" tempcolumn=0,");
            ret.append(sqlBuilder.toString().replaceFirst("(?i)select", ""));
            ret.append(")vip)mvp where temprownumber>").append(start);
            return ret.toString();
        } else {
            throw new JbootException("sql limit is error!,limit must is Number of String like \"0,10\"");
        }

    }

    @Override
    public String forFindCountByColumns(String alias, List<Join> joins, String table, String loadColumns, List<Column> columns) {
        return SqlBuilder.forFindCountByColumns(alias, joins, table, loadColumns, columns, ' ');
    }

    @Override
    public String forDeleteByColumns(String alias, List<Join> joins, String table, List<Column> columns) {
        return SqlBuilder.forDeleteByColumns(alias, joins, table, columns, ' ');
    }

    @Override
    public String forPaginateSelect(String loadColumns) {
        return "SELECT " + loadColumns;
    }

    @Override
    public String forPaginateFrom(String alias, List<Join> joins, String table, List<Column> columns, String orderBy) {
        return SqlBuilder.forPaginateFrom(alias, joins, table, columns, orderBy, ' ');
    }

    @Override
    public String forPaginateTotalRow(String select, String sqlExceptSelect, Object ext) {
        String distinctSql = SqlBuilder.forPaginateDistinctTotalRow(select, sqlExceptSelect, ext);
        return distinctSql != null ? distinctSql : super.forPaginateTotalRow(select, sqlExceptSelect, ext);
    }

}


text:
namespace cold { namespace script {

struct FunctionDefinition {
	FunctionDefinition(const std::vector<Instruction>& i, const std::vector<Param>& p);

	bool operator==(const FunctionDefinition& fd) const;
	bool operator!=(const FunctionDefinition& fd) const;
	void update_hash();
	std::string repr() const;
	std::vector<Instruction> insts;
	std::vector<Param> params;
	unsigned int hash;
};

} }

#endif


text:
import json

from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.sharing.links.kind import SharingLinkKind
from office365.sharepoint.webs.web import Web
from tests import test_user_credentials, test_team_site_url

ctx = ClientContext(test_team_site_url).with_credentials(test_user_credentials)

sharing_messages = {
    0: "A value has not been initialized",
    1: "A direct link or canonical URL to an object",
    2: "An organization access link with view permissions to an object",
    3: "An organization access link with edit permissions to an object",
    4: "An anonymous access link with view permissions to an object",
    5: "An anonymous access link with edit permissions to an object",
    6: "A tokenized sharing link where properties can change without affecting link URL"
}

file_url = "/sites/team/Shared Documents/SharePoint User Guide.docx"
target_file = ctx.web.get_file_by_server_relative_url(file_url)

# Share a file link
result = target_file.share_link(SharingLinkKind.AnonymousView).execute_query()
print(json.dumps(result.value.to_json(), indent=4))
link_url = result.value.sharingLinkInfo.Url

# Verify a link
result = Web.get_sharing_link_kind(ctx, link_url).execute_query()
print(sharing_messages.get(result.value, "Unknown sharing link"))

# Unshare a file link
target_file.unshare_link(SharingLinkKind.AnonymousView).execute_query()

# Get a file sharing info
info = target_file.get_sharing_information().execute_query()
print("AnonymousViewLink:", info.properties.get('AnonymousViewLink'))


text:
import Ember from 'ember';
import {Canvas, ElementSprite} from '../utils/canvas';
import AnnotationStore from '../utils/annotation-store';

/* global CanvasLoader */

export default Ember.Component.extend({
    _register: function() {
        this.set('document.view', this); // documentView is a new property
    }.on('init'),

    didInsertElement: function() {
        Ember.run.scheduleOnce('afterRender', this, this.initData());
    },

    iframeId: 'scraped-doc-iframe',

    dataSource: null,

    sprites: [],

    listener: null,

    canvas: null,

    ignoredElementTags: ['html', 'body'],

    mouseDown: false,

    loader: null,

    loadingDoc: false,

    cssEnabled: true,

    annotationStore: null,

    spiderPage: null,
    spiderPageShown: true,

    redrawSprites: function() {
        this.redrawNow();
    }.observes('sprites.sprites.@each', 'sprites'),

    /**
        Attaches this documentview to a datasource and event listener
        configuring it according to the options dictionary.
        The options dictionary may contain:

        datasource: the datasource that will be attached.
        listener: the event listener will be attached.
        mode: a string. Possible values are 'select' and 'browse'.
        partialSelects: boolean. Whether to allow partial selections. It only
            has effect for the 'select' mode.
    */
    config: function(options) {
        this.set('dataSource', options.dataSource);
        this.set('listener', options.listener);
        if (options.mode === 'select') {
            this.set('elementSelectionEnabled', true);
            this.set('partialSelectionEnabled', options.partialSelects);
        } else if (options.mode === 'browse') {
            this.set('elementSelectionEnabled', false);
            this.hideHoveredInfo();
            this.installEventHandlersForBrowsing();
        }
    },

    /**
        Detaches the datasource and event listener. Internally,
        it also unbinds all event handlers.
    */
    reset: function() {
        this.uninstallEventHandlers();
        this.set('elementSelectionEnabled', false);
        this.set('partialSelectionEnabled', false);
        this.set('dataSource', null);
        this.set('listener', null);
    },

    /**
        Set this property to a DOM element if you want to restrict element
        selection to the children of the given element.
    */
    restrictToDescendants: null,

    /**
        Returns the document iFrame contents.
    */
    getIframe: function() {
        return Ember.$('#' + this.get('iframeId')).contents();
    },

    /**
        Redraws all datasource sprites and the hovered element (if in select
        mode). This method can be called manually but it gets called
        automatically:

            - Once 10 seconds.
            - After a window resize or iframe scroll.
            - The sprites exposed by the datasource change.
    */
    redrawNow: function() {
        var canvas = this.get('canvas');
        if (!canvas || this.loadingDoc) {
            return;
        }
        canvas = this.get('canvas');
        if (this.get('sprites.sprites')) {
            var sprites = this.get('sprites.sprites').copy();
            if (this.get('hoveredSprite')) {
                sprites = sprites.concat([this.get('hoveredSprite')]);
            }
            canvas.draw(sprites,
                        this.getIframe().scrollLeft(),
                        this.getIframe().scrollTop());
        } else {
            canvas.clear();
        }
    },

    clearNow: function() {
        this.get('canvas').clear();
    },

    /**
        Blocks/unblocks interactions with the document.
    */
    setInteractionsBlocked: function(blocked) {
        if (this.get('canvas.interactionsBlocked') !== blocked) {
            this.set('canvas.interactionsBlocked', blocked);
        }
    },

    /**
        Displays a document by setting it as the content of the iframe.
        readyCallback will be called when the document finishes rendering.
    */
    displayDocument: function(documentContents, readyCallback) {
        Ember.run.schedule('afterRender', this, function() {
            this.set('loadingDoc', true);
            this.setIframeContent(documentContents);
            this.spiderPageShown = false;
            // We need to disable all interactions with the document we are loading
            // until we trigger the callback.
            this.setInteractionsBlocked(true);
            Ember.run.later(this, function() {
                var doc = document.getElementById(this.get('iframeId')).contentWindow.document;
                doc.onscroll = this.redrawNow.bind(this);
                this.setInteractionsBlocked(false);
                if (readyCallback) {
                    readyCallback(this.getIframe());
                }
                this.set('loadingDoc', false);
            }, 1000);
        });
    },

    /**
        Returns the content of the document currently displayed by the
        iframe.
    */
    getAnnotatedDocument: function() {
        return this.getIframe().find('html').get(0).outerHTML;
    },

    /**
        Displays a loading widget on top of the iframe. It should be removed
        by calling hideLoading.
    */
    showLoading: function() {
        this.setInteractionsBlocked(true);
        var loader = this.get('loader');
        if (!loader) {
            loader = new CanvasLoader('loader-container');
            loader.setColor('#2398b2');
            loader.setShape('spiral');
            loader.setDiameter(90);
            loader.setRange(0.9);
            loader.setSpeed(1.0);
            loader.setFPS(60);
            var loaderObj = document.getElementById("canvasLoader");
            loaderObj.style.position = "absolute";
            loaderObj.style["margin-left"] = -loader.getDiameter() / 2 + "px";
            loaderObj.style["margin-top"] = '180px';
            loaderObj.style["width"] = loader.getDiameter() + "px";
            loaderObj.style["left"] = '50%';
            this.set('loader', loader);
        }
        loader.show();
    },

    /**
        Hides the loading widget displayed by a previous call to showLoading.
    */
    hideLoading: function() {
        if (this.get('loader')) {
            this.get('loader').hide();
        }
        this.setInteractionsBlocked(false);
    },

    /**
        Displays the spider image place holder as the content of the
        iframe.
    */
    showSpider: function() {
        Ember.run.schedule('afterRender', this, function() {
            if (!Ember.testing && !this.spiderPageShown) {
                if (this.spiderPage) {
                    this.setIframeContent(this.spiderPage);
                } else  {
                    this.reloadIframeContent();
                }
                this.spiderPageShown = true;
            }
        });
    },

    toggleCSS: function() {
        var iframe = this.getIframe();
        if (this.cssEnabled) {
            iframe.find('link[rel="stylesheet"]').each(function() {
                Ember.$(this).renameAttr('href', '_href');
            });
            iframe.find('style').each(function() {
                var that = Ember.$(this);
                that.renameAttr('type', '_type');
                that.attr('type', 'text/disabled');
            });
            iframe.find('[style]').each(function() {
                Ember.$(this).renameAttr('style', '_style');
            });
        } else {
            iframe.find('link[rel="stylesheet"]').each(function() {
                Ember.$(this).renameAttr('_href', 'href');
            });
            iframe.find('style').each(function() {
                Ember.$(this).renameAttr('_type', 'type');
            });
            iframe.find('*[_style]').each(function() {
                Ember.$(this).renameAttr('_style', 'style');
            });
        }
        this.redrawNow();
        this.cssEnabled = !this.cssEnabled;
    },

    /**
        Scrolls the iframe so the given element appears in the current
        viewport.
    */
    scrollToElement: function(element) {
        var rect = Ember.$(element).boundingBox();
        this.updateHoveredInfo(element);
        Ember.$('#' + this.get('iframeId')).get(0).contentWindow.scrollTo(
            Math.max(0, parseInt(rect.left - 100)),
            Math.max(0, parseInt(rect.top - 100))
        );
    },

    _elementSelectionEnabled: null,

    elementSelectionEnabled: function(key, selectionEnabled) {
        if (arguments.length > 1) {
            if (selectionEnabled) {
                if (!this.get('_elementSelectionEnabled')) {
                    this.set('_elementSelectionEnabled', true);
                    this.showHoveredInfo();
                    this.installEventHandlersForSelecting();
                }
            } else {
                this.set('_elementSelectionEnabled', false);
                this.uninstallEventHandlers();
                this.hideHoveredInfo();
            }
        } else {
            return this.get('_elementSelectionEnabled');
        }
    }.property('_elementSelectionEnabled'),

    partialSelectionEnabled: false,

    installEventHandlersForBrowsing: function() {
        this.uninstallEventHandlers();
        this.getIframe().bind('click', this.clickHandlerBrowse.bind(this));
    },

    installEventHandlersForSelecting: function() {
        this.uninstallEventHandlers();
        this.getIframe().bind('click', this.clickHandler.bind(this));
        this.getIframe().bind('mouseover', this.mouseOverHandler.bind(this));
        this.getIframe().bind('mouseout', this.mouseOutHandler.bind(this));
        this.getIframe().bind('mousedown', this.mouseDownHandler.bind(this));
        this.getIframe().bind('mouseup', this.mouseUpHandler.bind(this));
        this.getIframe().bind('hover', function(event) {event.preventDefault();});
        this.redrawNow();
    },

    uninstallEventHandlers: function() {
        this.getIframe().unbind('click');
        this.getIframe().unbind('mouseover');
        this.getIframe().unbind('mouseout');
        this.getIframe().unbind('mousedown');
        this.getIframe().unbind('mouseup');
        this.getIframe().unbind('hover');
        this.set('hoveredSprite', null);
    },

    reloadIframeContent: function() {
        return Ember.$('#' + this.get('iframeId')).attr('src',
            Ember.$('#' + this.get('iframeId')).attr('src')
        );
    },

    getIframeContent: function() {
        var iframe = this.getIframe().get(0);
        return iframe.documentElement && iframe.documentElement.outerHTML;
    },

    setIframeContent: function(contents) {
        if (this.spiderPageShown && !this.spiderPage) {
            this.spiderPage = this.getIframeContent() || null;
        }

        var iframe = this.getIframe();
        iframe.find('html').html(contents);
        this.set('document.iframe', iframe);
    },

    showHoveredInfo: function() {
        Ember.$("#hovered-element-info").css('display', 'inline');
    },

    hideHoveredInfo: function() {
        Ember.$("#hovered-element-info").css('display', 'none');
    },

    initHoveredInfo: function() {
        var contents = '
' +
            '' +
            '<button class="btn btn-light fa fa-icon fa-arrow-right"/>' +
            '
' +
            '
';
        Ember.$('#hovered-element-info').html(contents);
        Ember.$('#hovered-element-info button').click(function() {
                var element = Ember.$('#hovered-element-info');
                var button = element.find('button');
                button.removeClass('fa-arrow-right');
                button.removeClass('fa-arrow-left');
                var floatPos = element.css('float');
                if (floatPos === 'left') {
                    floatPos = 'right';
                    button.addClass('fa-arrow-left');
                } else {
                    floatPos = 'left';
                    button.addClass('fa-arrow-right');
                }
                element.css('float', floatPos);
            });
    },

    updateHoveredInfo: function(element) {
        var jqElem = Ember.$(element),
            path = jqElem.getPath(),
            attributes = jqElem.getAttributeList();
        if (jqElem.prop('class')) {
            attributes.unshift({name: 'class', value: jqElem.prop('class')});
        }
        if (jqElem.prop('id')) {
            attributes.unshift({name: 'id', value: jqElem.prop('id')});
        }
        var attributesHtml = '';
        attributes.forEach(function(attribute) {
            var value = attribute.value.trim().substring(0, 50);
            attributesHtml += '
' +
                                '' + attribute.name + ": " +
                                '' + value + '' +
                              '
';
        });
        Ember.$('#hovered-element-info .attributes').html(attributesHtml);
        Ember.$('#hovered-element-info .path').html(path);
    },

    sendElementHoveredEvent: function(element, delay, mouseX, mouseY) {
        var handle = this.get('elementHoveredHandle');
        if (handle) {
            Ember.run.cancel(handle);
            this.set('elementHoveredHandle', null);
        }
        if (delay) {
            handle = Ember.run.later(this, function() {
                this.sendDocumentEvent('elementHovered', element, mouseX, mouseY);
            }, delay);
            this.set('elementHoveredHandle', handle);
        } else {
            this.sendDocumentEvent('elementHovered', element, mouseX, mouseY);
        }
    },

    mouseOverHandler:  function(event) {
        event.preventDefault();
        var target = event.target;
        var tagName = Ember.$(target).prop("tagName").toLowerCase();
        if (Ember.$.inArray(tagName, this.get('ignoredElementTags')) === -1 &&
            !this.mouseDown) {
            if (!this.get('restrictToDescendants') ||
                    Ember.$(target).isDescendant(this.get('restrictToDescendants'))) {
                this.setElementHovered(target);
                this.sendElementHoveredEvent(target, 0, event.clientX, event.clientY);
            }
        }
    },

    mouseOutHandler: function() {
        this.set('hoveredSprite', null);
        this.redrawNow();
    },

    clickHandler: function(event) {
        event.preventDefault();
    },

    clickHandlerBrowse: function(event) {
        event.preventDefault();
        var linkingElement = Ember.$(event.target).closest('[href]');
        if (linkingElement.length) {
            var href = Ember.$(linkingElement).get(0).href;
            this.sendDocumentEvent('linkClicked', href);
        }
    },

    mouseDownHandler: function(event) {
        if (event.target.draggable) {
            // Disable dragging of images, links, etc...
            // This interferes with partial selection of links,
            // but it's a lesser evil than dragging.
            event.preventDefault();
        }
        this.set('hoveredSprite', null);
        this.set('mouseDown', true);
        this.redrawNow();
    },

    mouseUpHandler: function(event) {
        this.set('mouseDown', false);
        var selectedText = this.getIframeSelectedText();
        if (selectedText) {
            if (this.get('partialSelectionEnabled')) {
                if (selectedText.anchorNode === selectedText.focusNode) {
                    this.sendDocumentEvent(
                        'partialSelection', selectedText, event.clientX, event.clientY);
                } else {
                    alert('The selected text must belong to a single HTML element');
                    selectedText.collapse(this.getIframe().find('html').get(0), 0);
                }
            } else {
                selectedText.collapse(this.getIframe().find('html').get(0), 0);
            }
        } else if (event && event.target){
            var target = event.target;
            var tagName = Ember.$(target).prop("tagName").toLowerCase();
            if (Ember.$.inArray(tagName, this.get('ignoredElementTags')) === -1) {
                if (!this.get('restrictToDescendants') ||
                    Ember.$(target).isDescendant(this.get('restrictToDescendants'))) {
                    this.sendDocumentEvent('elementSelected', target, event.clientX, event.clientY);
                } else {
                    this.sendDocumentEvent('elementSelected', null);
                }
            }
        }
    },

    sendDocumentEvent: function(name) {
        var actions = this.get('listener.documentActions');
        var args = Array.prototype.slice.call(arguments, 1);
        if (actions && actions[name]) {
            Ember.run(function(){
                actions[name].apply(this.get('listener'), args);
            }.bind(this));
        }
    },

    getIframeSelectedText: function() {
        var range = this.getIframe().get(0).getSelection();
        if (range && !range.isCollapsed) {
            return range;
        } else {
            return null;
        }
    },

    setElementHovered: function(element) {
        this.updateHoveredInfo(element);
        this.set('hoveredSprite',
                 ElementSprite.create({'element': element}));
        this.redrawNow();
    },

    initCanvas: function() {
        if (!this.get('canvas')) {
            this.set('canvas', Canvas.create({ canvasId: 'infocanvas' }));
            this.initHoveredInfo();
            if (!Ember.testing){
                window.resize = function() {
                    this.redrawNow();
                }.bind(this);
            }
        }
    },

    initData: function() {
        this.initCanvas();
        var store = new AnnotationStore(),
            iframe = this.getIframe();
        store.set('document', this.get('document'));
        this.set('document.store', store);
        this.set('document.iframe', iframe);
    },

    call: function() {}
});