code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231
values | license stringclasses 13
values | size int64 1 2.01M |
|---|---|---|---|---|---|
package com.zyeeda.framework.validation;
import javax.validation.ValidatorFactory;
import com.zyeeda.framework.service.Service;
public interface ValidationService extends Service {
public ValidatorFactory getPreInsertValidatorFactory();
public ValidatorFactory getPreUpdateValidatorFactory();
public ValidatorFactory getPreDeleteValidatorFactory();
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/validation/ValidationService.java | Java | asf20 | 364 |
package com.zyeeda.framework.security.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Virtual {
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/security/annotations/Virtual.java | Java | asf20 | 378 |
package com.zyeeda.framework.security.internal;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.tapestry5.ioc.annotations.Marker;
import org.apache.tapestry5.ioc.annotations.Primary;
import org.apache.tapestry5.ioc.annotations.ServiceId;
import org.apache.tapestry5.ioc.services.RegistryShutdownHub;
import com.zyeeda.framework.openid.consumer.shiro.OpenIdConsumerRealm;
@Marker(Primary.class)
@ServiceId("openid-consumer-security-service")
public class OpenIdConsumerSecurityServiceProvider extends AbstractSecurityServiceProvider {
private SecurityManager securityMgr;
public OpenIdConsumerSecurityServiceProvider(RegistryShutdownHub shutdownHub) {
super(shutdownHub);
this.securityMgr = new ShiroSecurityManager();
}
@Override
public SecurityManager getSecurityManager() {
return this.securityMgr;
}
private class ShiroSecurityManager extends DefaultWebSecurityManager {
public ShiroSecurityManager() {
super(new OpenIdConsumerRealm());
}
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/security/internal/OpenIdConsumerSecurityServiceProvider.java | Java | asf20 | 1,089 |
package com.zyeeda.framework.security.internal;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.tapestry5.ioc.annotations.Marker;
import org.apache.tapestry5.ioc.annotations.ServiceId;
import org.apache.tapestry5.ioc.services.RegistryShutdownHub;
import com.zyeeda.framework.openid.consumer.shiro.OpenIdConsumerRealm;
import com.zyeeda.framework.security.annotations.Virtual;
@Marker(Virtual.class)
@ServiceId("virtual-consumer-security-service")
public class VirtualConsumerSecurityServiceProvider extends AbstractSecurityServiceProvider {
private SecurityManager securityMgr;
public VirtualConsumerSecurityServiceProvider(RegistryShutdownHub shutdownHub) {
super(shutdownHub);
this.securityMgr = new ShiroSecurityManager();
}
@Override
public SecurityManager getSecurityManager() {
return this.securityMgr;
}
private class ShiroSecurityManager extends DefaultSecurityManager {
public ShiroSecurityManager() {
super(new OpenIdConsumerRealm());
}
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/security/internal/VirtualConsumerSecurityServiceProvider.java | Java | asf20 | 1,087 |
package com.zyeeda.framework.security.internal;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.tapestry5.ioc.annotations.Marker;
import org.apache.tapestry5.ioc.annotations.Primary;
import org.apache.tapestry5.ioc.annotations.ServiceId;
import org.apache.tapestry5.ioc.services.RegistryShutdownHub;
import com.zyeeda.framework.ldap.LdapService;
import com.zyeeda.framework.security.realms.LdapRealm;
@Marker(Primary.class)
@ServiceId("openid-provider-security-service")
public class OpenIdProviderSecurityServiceProvider extends AbstractSecurityServiceProvider {
// Injected
private final LdapService ldapSvc;
private final SecurityManager securityMgr;
public OpenIdProviderSecurityServiceProvider(
@Primary LdapService ldapSvc,
RegistryShutdownHub shutdownHub) {
super(shutdownHub);
this.ldapSvc = ldapSvc;
this.securityMgr = new ShiroSecurityManager();
}
@Override
public SecurityManager getSecurityManager() {
return this.securityMgr;
}
private class ShiroSecurityManager extends DefaultWebSecurityManager {
public ShiroSecurityManager() {
super(new LdapRealm(ldapSvc));
}
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/security/internal/OpenIdProviderSecurityServiceProvider.java | Java | asf20 | 1,240 |
package com.zyeeda.framework.security.internal;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.tapestry5.ioc.services.RegistryShutdownHub;
import com.zyeeda.framework.security.SecurityService;
import com.zyeeda.framework.service.AbstractService;
public abstract class AbstractSecurityServiceProvider extends AbstractService implements
SecurityService<SecurityManager> {
public AbstractSecurityServiceProvider(RegistryShutdownHub shutdownHub) {
super(shutdownHub);
}
@Override
public abstract SecurityManager getSecurityManager();
@Override
public String getCurrentUser() {
Subject current = SecurityUtils.getSubject();
Object principal = current.getPrincipal();
if (principal == null) {
throw new AuthenticationException("Subject not signed in.");
}
return principal.toString();
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/security/internal/AbstractSecurityServiceProvider.java | Java | asf20 | 998 |
package com.zyeeda.framework.security.realms;
import java.io.IOException;
import javax.naming.NamingException;
import javax.naming.ldap.LdapContext;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.ldap.LdapUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zyeeda.framework.ldap.LdapService;
public class LdapRealm extends AuthorizingRealm {
private final static Logger logger = LoggerFactory.getLogger(LdapRealm.class);
private final LdapService ldapSvc;
public LdapRealm(LdapService ldapSvc) {
this.ldapSvc = ldapSvc;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(
AuthenticationToken token) throws AuthenticationException {
logger.debug("authentication token type = {}", token.getClass().getName());
if (!(token instanceof UsernamePasswordToken)) {
throw new AuthenticationException("Invalid authentication token.");
}
UsernamePasswordToken upToken = (UsernamePasswordToken) token;
logger.debug("username = {}", upToken.getUsername());
logger.debug("password = ******");
LdapContext ctx = null;
try {
ctx = this.ldapSvc.getLdapContext(upToken.getUsername(), new String(upToken.getPassword()));
} catch (NamingException e) {
throw new AuthenticationException(e);
} catch (IOException e) {
throw new AuthenticationException(e);
} finally {
LdapUtils.closeContext(ctx);
}
return new SimpleAuthenticationInfo(upToken.getUsername(), upToken.getPassword(), this.getName());
}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(
PrincipalCollection principals) {
// TODO Auto-generated method stub
return null;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/security/realms/LdapRealm.java | Java | asf20 | 2,121 |
package com.zyeeda.framework.security.realms;
import java.io.IOException;
import javax.naming.NamingException;
import javax.naming.ldap.LdapContext;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.ldap.LdapUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zyeeda.framework.ldap.LdapService;
public class ShiroCombinedRealm extends AuthorizingRealm {
private static final Logger logger = LoggerFactory.getLogger(ShiroCombinedRealm.class);
// Injected
private final LdapService ldapSvc;
//private final RoleManager roleMgr;
public ShiroCombinedRealm(LdapService ldapSvc) {
this.ldapSvc = ldapSvc;
//this.roleMgr = roleMgr;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
logger.debug("authentication token type = {}", token.getClass().getName());
if (!(token instanceof UsernamePasswordToken)) {
throw new AuthenticationException("Invalid authentication token.");
}
UsernamePasswordToken upToken = (UsernamePasswordToken) token;
logger.debug("username = {}", upToken.getUsername());
logger.debug("password = ******");
LdapContext ctx = null;
try {
ctx = this.ldapSvc.getLdapContext(upToken.getUsername(), new String(upToken.getPassword()));
} catch (NamingException e) {
throw new AuthenticationException(e);
} catch (IOException e) {
throw new AuthenticationException(e);
} finally {
LdapUtils.closeContext(ctx);
}
return new SimpleAuthenticationInfo(upToken.getUsername(), upToken.getPassword(), this.getName());
}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//String username = (String) this.getAvailablePrincipal(principals);
//List<?> roles = this.roleMgr.getRolesBySubject(username);
//SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
// for (Iterator<?> it = roles.iterator(); it.hasNext(); ) {
// Role role = (Role) it.next();
// logger.debug("role name = {}", role.getName());
// logger.debug("role perms = {}", role.getPermissions());
// info.addRole(role.getName());
// info.addStringPermissions(role.getPermissionSet());
// }
//
//return info;
return null;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/security/realms/ShiroCombinedRealm.java | Java | asf20 | 2,724 |
package com.zyeeda.framework.security;
import com.zyeeda.framework.service.Service;
public interface SecurityService<T> extends Service {
public T getSecurityManager();
public String getCurrentUser();
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/security/SecurityService.java | Java | asf20 | 225 |
/**
*
*/
package com.zyeeda.framework.ftp;
import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import com.zyeeda.framework.ftp.internal.FtpConnectionRefusedException;
import com.zyeeda.framework.ftp.internal.FtpServerLoginFailedException;
import com.zyeeda.framework.service.Service;
/**
*
*
* @creator Qi Zhao
* @date 2011-6-23
*
* @LastChanged
* @LastChangedBy $LastChangedBy: $
* @LastChangedDate $LastChangedDate: $
* @LastChangedRevision $LastChangedRevision: $
*/
public interface FtpService extends Service {
public FTPClient connectThenLogin() throws IOException, FtpConnectionRefusedException, FtpServerLoginFailedException;
public void deleteFiles(FTPClient ftpClient, FTPFile[] ftpFiles) throws IOException;
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/ftp/FtpService.java | Java | asf20 | 815 |
package com.zyeeda.framework.ftp.internal;
public class FtpConnectionRefusedException extends Exception {
private static final long serialVersionUID = 3210431136164484133L;
public FtpConnectionRefusedException(String msg) {
super(msg);
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/ftp/internal/FtpConnectionRefusedException.java | Java | asf20 | 248 |
/**
*
*/
package com.zyeeda.framework.ftp.internal;
import java.io.IOException;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.tapestry5.ioc.annotations.Marker;
import org.apache.tapestry5.ioc.annotations.Primary;
import org.apache.tapestry5.ioc.annotations.ServiceId;
import org.apache.tapestry5.ioc.services.RegistryShutdownHub;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zyeeda.framework.config.ConfigurationService;
import com.zyeeda.framework.ftp.FtpService;
import com.zyeeda.framework.service.AbstractService;
/**
*
*
* @creator Qi Zhao
* @date 2011-6-24
*
* @LastChanged
* @LastChangedBy $LastChangedBy: $
* @LastChangedDate $LastChangedDate: $
* @LastChangedRevision $LastChangedRevision: $
*/
@ServiceId("commons-ftp-service-provider")
@Marker(Primary.class)
public class CommonsFtpServiceProvider extends AbstractService implements FtpService {
private static final Logger logger = LoggerFactory.getLogger(CommonsFtpServiceProvider.class);
private static final String FTP_HOST = "ftpHost";
private static final String FTP_USER_NAME = "ftpUserName";
private static final String FTP_PASSWORD = "ftpPassword";
private static final String FTP_PORT = "ftpPort";
private static final String DEFAULT_FTP_HOST = "10.118.250.131";
private static final String DEFAULT_FTP_USER_NAME = "gzsc";
private static final String DEFAILT_FTP_PASSWORD = "gzsc";
private static final int DEFAULT_FTP_PORT = 21;
private String ftpHost;
private String ftpUserName;
private String ftpPassword;
private int ftpPort;
public CommonsFtpServiceProvider(ConfigurationService configSvc,
RegistryShutdownHub shutdownHub) {
super(shutdownHub);
Configuration config = this.getConfiguration(configSvc);
this.init(config);
}
private void init(Configuration config) {
this.ftpHost = config.getString(FTP_HOST, DEFAULT_FTP_HOST);
this.ftpUserName = config.getString(FTP_USER_NAME, DEFAULT_FTP_USER_NAME);
this.ftpPassword = config.getString(FTP_PASSWORD, DEFAILT_FTP_PASSWORD);
this.ftpPort = config.getInt(FTP_PORT, DEFAULT_FTP_PORT);
}
public FTPClient connectThenLogin() throws IOException,
FtpConnectionRefusedException, FtpServerLoginFailedException {
FTPClient ftp = new FTPClient();
ftp.connect(this.ftpHost, this.ftpPort);
logger.debug("connected to server = {} ", this.ftpHost);
String[] messages = ftp.getReplyStrings();
for (String msg : messages) {
logger.debug(msg);
}
int replyCode = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
ftp.disconnect();
throw new FtpConnectionRefusedException(
"Refused to connect to server " + this.ftpHost + ".");
}
boolean sucessful = ftp.login(this.ftpUserName, this.ftpPassword);
if (!sucessful) {
ftp.disconnect();
throw new FtpServerLoginFailedException(
"Failed to login to server " + this.ftpHost + ".");
}
return ftp;
}
public void deleteFiles(FTPClient client, FTPFile[] ftpFiles) throws IOException {
logger.debug("delete file size = {}", ftpFiles.length);
for (FTPFile ftpFile : ftpFiles) {
client.deleteFile(ftpFile.getName());
}
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/ftp/internal/CommonsFtpServiceProvider.java | Java | asf20 | 3,745 |
package com.zyeeda.framework.ftp.internal;
public class FtpServerLoginFailedException extends Exception {
private static final long serialVersionUID = -2706394949864309918L;
public FtpServerLoginFailedException(String msg) {
super(msg);
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/ftp/internal/FtpServerLoginFailedException.java | Java | asf20 | 249 |
/*
* Copyright 2010 Zyeeda Co. Ltd.
*
* 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.
*/
package com.zyeeda.framework;
/**
* All framework level constants.
*
* @author $Author$
* @date $Date$
* @version $Revision$
* @since 1.5
*/
public class FrameworkConstants {
public static final String SERVICE_REGISTRY = "service.registry";
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/FrameworkConstants.java | Java | asf20 | 858 |
package com.zyeeda.framework.ldap;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.naming.Binding;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.OperationNotSupportedException;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.ModificationItem;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.Control;
import javax.naming.ldap.LdapContext;
import org.apache.shiro.realm.ldap.LdapUtils;
/**
* Ldap Common operation class
* @author gary.wang
* @since 1.5
* @version 1.6
*
*/
public class LdapTemplate{
private static String DN = ",dc=ehv,dc=csg,dc=cn";
@SuppressWarnings("unused")
private LdapService ldapSvc;
private LdapContext ctx;
public LdapTemplate(LdapService ldapSvc) {
this.ldapSvc = ldapSvc;
}
public LdapTemplate(LdapContext ctx) {
this.ctx = ctx;
}
/**
* Create a context
* @param dn - the full path of the context, dn not existing
* @param attrs - the dn's attributes
* @throws NamingException - if a naming exception is encountered
*/
public void bind(String dn, Attributes attrs) throws NamingException{
try {
this.ctx.bind(dn, null, attrs);
} catch (NamingException e) {
throw new RuntimeException(e);
} finally {
LdapUtils.closeContext(this.ctx);
}
}
/**
* Binds a dn to an object, overwriting any existing binding
* @param dn, the full path of the context
* @param attrs the dn's attributes
* @throws NamingException - if a naming exception is encountered
*/
public void rebind(String dn, Attributes attrs) throws NamingException {
try {
this.ctx.rebind(dn, null, attrs);
} catch (NamingException e) {
throw new RuntimeException(e);
} finally {
LdapUtils.closeContext(this.ctx);
}
}
public void modifyAttributes(String dn, Attributes attrs) throws NamingException {
this.ctx.modifyAttributes(dn, DirContext.REPLACE_ATTRIBUTE, attrs);
}
public void modifyAttributes(String dn, ModificationItem[] mods) throws NamingException {
this.ctx.modifyAttributes(dn, mods);
}
/**
* Delete a context by dn, not cascade
* @param dn - the full path of the context
* @throws NamingException - if a naming exception is encountered
*/
public void unbind(String dn) throws NamingException {
this.unbind(dn, false);
}
/**
* Delete a context by dn
* @param dn - the full path of the context
* @param cascade - if cascade is true it will delete all children
* @throws NamingException - if a naming exception is encountered
*/
public void unbind(String dn, Boolean cascade) throws NamingException {
try {
if (!cascade){
this.ctx.unbind(dn);
} else {
this.deleteRecursively(dn);
}
} catch (NamingException e) {
throw new RuntimeException(e);
}
}
/**
* @param dn - the full path of the context
* @return - a Attributes
* @throws NamingException - if a naming exception is encountered
*/
public Attributes findByDn(String dn) throws NamingException{
try {
return this.ctx.getAttributes(dn);
} catch (NamingException e) {
throw new RuntimeException(e);
} finally {
LdapUtils.closeContext(this.ctx);
}
}
/**
* @param name - the name of the context to search
* @param matchingAttributes - the attributes to search for
* @return - the list of Attributes
* @throws NamingException - if a naming exception is encountered
*/
public List<Attributes> getResultList(String name,
Attributes matchingAttributes)
throws NamingException {
NamingEnumeration<SearchResult> ne = this.ctx.search(name, matchingAttributes);
return this.searchResultToList(ne);
}
/**
* @param name - the name of the context or object to search
* @filter - the filter expression to use for the search; may not be null
* @param cons - the search controls that control the search. If null, the default search controls are used (equivalent to (new SearchControls())).
* @return - the list of Attributes
* @throws NamingException - if a naming exception is encountered
* @throws IOException
*/
public List<Attributes> getResultList(String name,
String filter,
SearchControls cons)
throws NamingException {
NamingEnumeration<SearchResult> ne = this.ctx.search(name, filter, cons);
return this.searchResultToList(ne);
}
/**
* @param name - the name of the context or object to search
* @param matchingAttributes - the attributes to search for
* @param attributesToReturn - the attributes to return
* @return - the list of Attributes
* @throws NamingException - if a naming exception is encountered
*/
public List<Attributes> getResultList(String name,
Attributes matchingAttributes,
String[] attributesToReturn)
throws NamingException {
NamingEnumeration<SearchResult> ne = this.ctx.search(name,
matchingAttributes,
attributesToReturn);
return this.searchResultToList(ne);
}
/**
* @param name - the name of the context or object to search
* @param filterExpr - the filter expression to use for the search. The expression may contain variables of the form "{i}" where i is a nonnegative integer. May not be null.
* @param filterArgs - the array of arguments to substitute for the variables in filterExpr. The value of filterArgs[i] will replace each occurrence of "{i}". If null, equivalent to an empty array.
* @param cons - the search controls that control the search. If null, the default search controls are used (equivalent to (new SearchControls())).
* @return - the list of Attributes
* @throws NamingException - if a naming exception is encountered
*/
public List<Attributes> getResultList(String name,
String filterExpr,
Object[] filterArgs,
SearchControls cons)
throws NamingException {
NamingEnumeration<SearchResult> ne = this.ctx.search(name,
filterExpr,
filterArgs,
cons);
return this.searchResultToList(ne);
}
/**
* @param name - the name of the context or object to search
* @param matchingAttributes - the attributes to search for
* @param attributesToReturn - the attributes to return
* @return - QueryResult, it contains total record and result list
* @throws NamingException - if a naming exception is encountered
*/
public QueryResult<Attributes> search(String name,
Attributes matchingAttributes,
String[] attributesToReturn)
throws NamingException {
NamingEnumeration<SearchResult> ne = this.ctx.search(name,
matchingAttributes,
attributesToReturn);
return this.searchResultToQueryResult(ne);
}
/**
* @param name - the name of the context to search
* @param matchingAttributes - the attributes to search for
* @return - QueryResult, it contains total record and result list
* @throws NamingException - if a naming exception is encountered
*/
public QueryResult<Attributes> search(String name,
Attributes matchingAttributes)
throws NamingException {
NamingEnumeration<SearchResult> ne = this.ctx.search(name, matchingAttributes);
return this.searchResultToQueryResult(ne);
}
/**
* @param name - the name of the context or object to search
* @filter - the filter expression to use for the search; may not be null
* @param cons - the search controls that control the search. If null, the default search controls are used (equivalent to (new SearchControls())).
* @return - QueryResult, it contains total record and result list
* @throws NamingException - if a naming exception is encountered
*/
public QueryResult<Attributes> search(String name,
String filter,
SearchControls cons)
throws NamingException {
NamingEnumeration<SearchResult> ne = this.ctx.search(name, filter, cons);
return this.searchResultToQueryResult(ne);
}
/**
* @param name - the name of the context or object to search
* @param filterExpr - the filter expression to use for the search. The expression may contain variables of the form "{i}" where i is a nonnegative integer. May not be null.
* @param filterArgs - the array of arguments to substitute for the variables in filterExpr. The value of filterArgs[i] will replace each occurrence of "{i}". If null, equivalent to an empty array.
* @param cons - the search controls that control the search. If null, the default search controls are used (equivalent to (new SearchControls())).
* @return - QueryResult, it contains total record and result list
* @throws NamingException - if a naming exception is encountered
*/
public QueryResult<Attributes> search(String name,
String filterExpr,
Object[] filterArgs,
SearchControls cons)
throws NamingException {
NamingEnumeration<SearchResult> ne = this.ctx.search(name,
filterExpr,
filterArgs,
cons);
return this.searchResultToQueryResult(ne);
}
public Map<String, Attributes> searchResultToMap(NamingEnumeration<SearchResult> ne)
throws NamingException{
Map<String, Attributes> map = null;
if(ne != null){
SearchResult entry = null;
map = new HashMap<String, Attributes>();
while(ne.hasMore()){
entry = ne.next();
Attributes attrs = entry.getAttributes();
map.put(entry.getNameInNamespace().replaceAll(DN, ""), attrs);
}
}
return map;
}
private List<Attributes> searchResultToList(
NamingEnumeration<SearchResult> ne)
throws NamingException {
List<Attributes> attrList = new ArrayList<Attributes>();
while (ne.hasMore()) {
Attributes atrrs = ne.next().getAttributes();
if (atrrs != null) {
attrList.add(atrrs);
}
}
return attrList;
}
private QueryResult<Attributes> searchResultToQueryResult(
NamingEnumeration<SearchResult> ne)
throws NamingException {
List<Attributes> attrList = this.searchResultToList(ne);
QueryResult<Attributes> qr = new QueryResult<Attributes>();
qr.setResultList(attrList);
qr.setTotalRecords(attrList.size() + 0l);
return qr;
}
private void deleteRecursively(String dn) throws NamingException {
LdapContext entry = (LdapContext) ctx.lookup(dn);
entry.setRequestControls(new Control[] {new TreeDeleteControl()});
try {
entry.unbind("");
} catch (OperationNotSupportedException e) {
entry.setRequestControls(new Control[0]);
deleteRecursively(entry);
}
}
@SuppressWarnings("rawtypes")
public void deleteRecursively(LdapContext entry)
throws NamingException {
NamingEnumeration<Binding> ne = entry.listBindings("");
while (ne.hasMore()) {
Binding b = (Binding) ne.next();
if (b.getObject() instanceof LdapContext) {
deleteRecursively((LdapContext) b.getObject());
}
}
entry.unbind("");
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/ldap/LdapTemplate.java | Java | asf20 | 11,699 |
package com.zyeeda.framework.ldap;
import java.io.IOException;
import javax.naming.NamingException;
import javax.naming.ldap.LdapContext;
import com.zyeeda.framework.service.Service;
public interface LdapService extends Service {
public LdapContext getLdapContext() throws NamingException;
public LdapContext getLdapContext(String username, String password) throws NamingException, IOException;
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/ldap/LdapService.java | Java | asf20 | 424 |
package com.zyeeda.framework.ldap;
import java.util.ArrayList;
import java.util.List;
public class QueryResult<T> {
private Long totalRecords;
private List<T> resultList = new ArrayList<T>();
public Long getTotalRecords() {
return totalRecords;
}
public void setTotalRecords(Long totalRecords) {
this.totalRecords = totalRecords;
}
public List<T> getResultList() {
return resultList;
}
public void setResultList(List<T> resultList) {
this.resultList = resultList;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/ldap/QueryResult.java | Java | asf20 | 519 |
package com.zyeeda.framework.ldap;
public class LdapServiceException extends RuntimeException {
private static final long serialVersionUID = 3829097670222114184L;
public LdapServiceException(String message) {
super(message);
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/ldap/LdapServiceException.java | Java | asf20 | 239 |
package com.zyeeda.framework.ldap.internal;
import java.io.IOException;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.realm.ldap.LdapUtils;
import org.apache.tapestry5.ioc.annotations.Marker;
import org.apache.tapestry5.ioc.annotations.Primary;
import org.apache.tapestry5.ioc.annotations.ServiceId;
import org.apache.tapestry5.ioc.services.RegistryShutdownHub;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zyeeda.framework.config.ConfigurationService;
import com.zyeeda.framework.ldap.LdapService;
import com.zyeeda.framework.ldap.LdapServiceException;
import com.zyeeda.framework.ldap.SearchControlsFactory;
import com.zyeeda.framework.service.AbstractService;
@ServiceId("sun-ldap-service")
@Marker(Primary.class)
public class SunLdapServiceProvider extends AbstractService implements LdapService {
private static final Logger logger = LoggerFactory.getLogger(SunLdapServiceProvider.class);
private static final String PROVIDER_URL = "providerUrl";
private static final String SECURITY_AUTHENTICATION = "securityAuthentication";
private static final String SYSTEM_SECURITY_PRINCIPAL = "systemSecurityPrincipal";
private static final String SYSTEM_SECURITY_CREDENTIALS = "systemSecurityCredentials";
private static final String SECURITY_PRINCIPAL_TEMPLATE = "securityPrincipalTemplate";
private static final String BASE_DN = "baseDN";
private static final String DEFAULT_INITIAL_CONTEXT_FACTORY = "com.sun.jndi.ldap.LdapCtxFactory";
private static final String DEFAULT_SECURITY_AUTHENTICATION = "simple";
private static final String DEFAULT_SECURITY_PRINCIPAL_TEMPLATE = "(uid=%s)";
private static final String DEFAULT_BASE_DN = "";
private String providerUrl;
private String securityAuthentication;
private String systemSecurityPrincipal;
private String systemSecurityCredentials;
private String securityPrincipalTemplate;
private String baseDn;
public SunLdapServiceProvider(
ConfigurationService configSvc,
RegistryShutdownHub shutdownHub) throws Exception {
super(shutdownHub);
Configuration config = this.getConfiguration(configSvc);
this.init(config);
}
public void init(Configuration config) throws Exception {
this.providerUrl = config.getString(PROVIDER_URL);
this.securityAuthentication = config.getString(SECURITY_AUTHENTICATION, DEFAULT_SECURITY_AUTHENTICATION);
this.systemSecurityPrincipal = config.getString(SYSTEM_SECURITY_PRINCIPAL);
this.systemSecurityCredentials = config.getString(SYSTEM_SECURITY_CREDENTIALS);
this.securityPrincipalTemplate = config.getString(SECURITY_PRINCIPAL_TEMPLATE, DEFAULT_SECURITY_PRINCIPAL_TEMPLATE);
this.baseDn = config.getString(BASE_DN, DEFAULT_BASE_DN);
logger.debug("provider url = {}", this.providerUrl);
logger.debug("security authentication = {}", this.securityAuthentication);
logger.debug("system security principal = {}", this.systemSecurityPrincipal);
logger.debug("system security credentials = ******");
logger.debug("security principal template = {}", this.securityPrincipalTemplate);
logger.debug("base dn = {}", this.baseDn);
}
@Override
public LdapContext getLdapContext() throws NamingException {
Hashtable<String, String> env = this.setupEnvironment();
env.put(Context.SECURITY_PRINCIPAL, this.systemSecurityPrincipal);
env.put(Context.SECURITY_CREDENTIALS, this.systemSecurityCredentials);
return new InitialLdapContext(env, null);
}
@Override
public LdapContext getLdapContext(String username, String password) throws NamingException, IOException {
logger.debug("username = {}", username);
logger.debug("password = ******");
LdapContext ctx = null;
try {
ctx = this.getLdapContext();
SearchControls sc = SearchControlsFactory.getSearchControls(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<SearchResult> ne = ctx.search(this.baseDn, String.format(this.securityPrincipalTemplate, username), sc);
SearchResult result = ne.hasMore() ? ne.next() : null;
if (result == null) {
throw new NamingException("User not found.");
}
if (ne.hasMore()) {
throw new NamingException("More than one user has the same name.");
}
String principal = result.getNameInNamespace();
logger.debug("searched principal = {}", principal);
Hashtable<String, String> env = this.setupEnvironment();
env.put(Context.SECURITY_PRINCIPAL, principal);
env.put(Context.SECURITY_CREDENTIALS, password);
return new InitialLdapContext(env, null);
} finally {
LdapUtils.closeContext(ctx);
}
}
private Hashtable<String, String> setupEnvironment() {
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, DEFAULT_INITIAL_CONTEXT_FACTORY);
if (StringUtils.isBlank(this.providerUrl)) {
throw new LdapServiceException("The provider url must be specified in form of ldap(s)://<hostname>:<port>/<baseDN>");
}
env.put(Context.PROVIDER_URL, this.providerUrl);
env.put(Context.SECURITY_AUTHENTICATION, this.securityAuthentication);
return env;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/ldap/internal/SunLdapServiceProvider.java | Java | asf20 | 5,435 |
package com.zyeeda.framework.ldap;
import javax.naming.ldap.Control;
/*
* By default, LDAP compliant directories forbid the deletion of entries with children.
* It is only permitted to delete leaf entries. However the Tree Delete Control provided
* by IBM Tivoli Directory Server 5.2/6.0 extends the delete operation and allows the removal
* of sub trees within a directory using a single delete request.
* In addition to Tivoli Directory Server this control is also supported by Microsoft Active Directory.
* When using JNDI methods to delete an entry within a directory, it is also not possible to remove whole subtrees at once.
* This is an expected behaviour because the underlying JNDI service provider uses LDAP.
* It is also possible to utilize the described LDAP control within JNDI to overcome this limitation.
* In order to demonstrate this, Listing 3 contains a Java class which implements the JNDI interface Control (see above).
* The method getId provides the OID of the Tree Delete Control. isCritical signals that the client considers the support of the control as critical.
* This property could be made configurable, but in this case a constant value is adequate. Since the definition of the control does not provide specific parameters, the method getEncodedValue returns null.
*/
public class TreeDeleteControl implements Control {
private static final long serialVersionUID = 765855337893417383L;
public String getID() {
return "1.2.840.113556.1.4.805";
}
public boolean isCritical() {
return Control.CRITICAL;
}
public byte[] getEncodedValue() {
return null;
}
} | zyeeda-framework | core/src/main/java/com/zyeeda/framework/ldap/TreeDeleteControl.java | Java | asf20 | 1,682 |
package com.zyeeda.framework.ldap;
import javax.naming.directory.SearchControls;
public class SearchControlsFactory {
public static SearchControls getSearchControls(int scope) {
SearchControls sc = SearchControlsFactory.getDefaultSearchControls();
sc.setSearchScope(scope);
return sc;
}
public static SearchControls getDefaultSearchControls() {
SearchControls sc = new SearchControls();
return sc;
}
}
| zyeeda-framework | core/src/main/java/com/zyeeda/framework/ldap/SearchControlsFactory.java | Java | asf20 | 442 |
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ page import="org.apache.shiro.SecurityUtils" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>
用户组织管理系统
</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta http-equiv="pragma" content="no-cache"/>
<meta http-equiv="cache-control" content="no-cache"/>
<meta http-equiv="expires" content="0"/>
<meta http-equiv="keywords" content="ehvgz"/>
<meta http-equiv="description" content="China South Power Grid Guang Zhou High Voltage User Organization Structure Management Project."/>
<link rel="shortcut icon" href="favicon.ico" />
<style>
.loading {
border:1px solid #8d8d8d;
margin:auto;
background:#d7d9e0;
width:240px;
height:80px;
left:50%;
top:50%;
margin-left:-120px;
margin-top:-40px;
position:absolute;
}
.loading span {
display:block;
font-size:14px;
font-weight:bold;
color:#4a4a4a;
padding-left:50px;
line-height:65px;
margin:5px;
height:65px;
background-image:url(public/img/loading.gif);
background-position:9px ;
background-repeat:no-repeat;
background-color: #FFFFFF;
border:#cecece 1px solid;
}
</style>
<div id="loading" class="loading"><span>正在为您加载,请稍候</span></div>
<script type="text/javascript">
//<![CDATA[
var loadDocument = document.getElementById("loading");
loadDocument.style.display = "block"; //显示
var systemLoginUser = "<%=SecurityUtils.getSubject().getPrincipal() %>";//"admin";
//]]>
</script>
<link rel="stylesheet" type="text/css" href="public/style/css.css" />
<link rel="stylesheet" type="text/css" href="public/style/style.css" />
<link rel="stylesheet" type="text/css" href="public/style/table.css" />
<link rel="stylesheet" type="text/css" href="public/style/form.css" />
<link rel="stylesheet" type="text/css" href="public/style/yui-override.css" />
<link rel="stylesheet" type="text/css" href="public/style/zui-messagebox.css" />
<link rel="stylesheet" type="text/css" href="public/style/exceptionpage.css" />
<link type="text/css" rel="stylesheet" href="public/lib/yui3-gallery/build/gallery-aui-skin-base/css/gallery-aui-skin-base.css"/>
<link type="text/css" rel="stylesheet" href="public/lib/yui3-gallery/build/gallery-aui-skin-classic/css/gallery-aui-skin-classic.css"/>
<link type="text/css" rel="stylesheet" href="public/lib/yui3-gallery/build/gallery-aui-tree-view/assets/skins/sam/gallery-aui-tree-view.css"/>
<link type="text/css" rel="stylesheet" href="public/lib/yui3-gallery/build/gallery-calendar/assert/skin.css"/>
<link type="text/css" rel="stylesheet" href="public/lib/yui3-gallery/build/gallerycss-xarno-skins/gallerycss-xarno-skins.css"/>
<!--自定义样式-->
<link rel="stylesheet" type="text/css" href="static/style/style.css" />
<link rel="stylesheet" type="text/css" href="static/style/department.css" />
<link rel="stylesheet" type="text/css" href="static/style/user.css" />
<link rel="stylesheet" type="text/css" href="static/style/tree.css" />
<script type="text/javascript" src="public/lib/yui3/build/yui/yui-min.js"></script>
<script type="text/javascript" src="public/lib/mustache/mustache.js"></script>
<script type="text/javascript" src="public/lib/zui/build/zui-common/zui-common.js"></script>
<script type="text/javascript" src="public/lib/zui/build/zui-messagebox/zui-messagebox.js"></script>
<script type="text/javascript" src="public/lib/zui/build/zui-tabview/zui-tabview.js"></script>
<!--自定义javascript-->
<script type="text/javascript" src="static/lib/zyeeda/common/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="static/lib/zyeeda/common/init.js"></script>
<script type="text/javascript" src="static/lib/zyeeda/common/utils.js"></script>
<script type="text/javascript" src="static/lib/zyeeda/common/tree.js"></script>
<script type="text/javascript" src="static/lib/zyeeda/deparment/department_action.js"></script>
<script type="text/javascript" src="static/lib/zyeeda/deparment/department_detail.js"></script>
<script type="text/javascript" src="static/lib/zyeeda/user/user_action.js"></script>
<script type="text/javascript" src="static/lib/zyeeda/user/user_detail.js"></script>
<script type="text/javascript" src="static/lib/zyeeda/search/searchData.js"></script>
<script type="text/javascript" src="static/lib/zyeeda/common/main.js"></script>
</head>
<body class="yui-skin-sam yui3-skin-xarno yui3-skin-xarno-growl" ><!--onbeforeunload="ZDA.listenFormsChange('user_form', 'department_form');"-->
<div class="box" style="display:none">
<div class="top">
<div class="top1">
<div class="top2"></div>
</div>
<div class="logo">
<div class="logo-bj"></div>
<div class="welcome">
<!-- <a href="#">
<span class="pic">
<img src="public/img/welcome_06.png" alt="a" width="21" height="24" border="0"
/>
</span>
欢迎您:张三(站长)
</a> -->
<a href="#" class="returnToMain">
<span class="pic">
<img src="public/img/home.png" alt="a" width="22" height="24" border="0"/>
</span>
返回首页
</a>
<a href="accounts/openid/signout.jsp">
<span class="pic">
<img src="public/img/welcome_10.png" alt="a" width="23" height="24" border="0"/>
</span>
安全退出
</a>
</div>
</div>
<div class="top-bj2"></div>
</div>
<div class="content">
<div class="c-left">
<div class="warp_l">
<div class="left_tree_top">
<img src="static/img/user-left-title_03.jpg" alt="user" />
</div>
<div class="left_tree_content">
<div class="left_tree_content2">
<div class="user">
<img src="static/img/user_08.jpg" alt="user" width="37" height="40" align="absmiddle"/>
欢迎您:<%=SecurityUtils.getSubject().getPrincipal() %>
<br />
(站长)
</div>
<div class="left_tree" id="left_tree_menu" style="white-space:nowrap; "></div>
<div style="clear:both"></div>
</div>
</div>
</div>
</div> <!-- <div id="Layer1"><img src="public/img/aa_19.png" alt="a" width="13" height="101" /></div> -->
<div class="c-right">
<div class="main-operation-zone">
</div>
</div>
<div style="clear:both">
</div>
</div>
<div class="box-down0">
<div class="box-down2">
</div>
南方电网 版权所有Copyright Notice 2011 All rights reserved.
</div>
</div>
</body>
</html> | zyeeda-framework | drivebox/src/main/webapp/index.jsp | Java Server Pages | asf20 | 7,136 |
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ page import="org.apache.shiro.SecurityUtils" %>
<%@ page import="org.openid4java.message.ParameterList"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>单点登录</title>
<link href="style/login.css" rel="stylesheet" type="text/css" />
</head>
<%
boolean authenticated = SecurityUtils.getSubject().isAuthenticated();
ParameterList params = (ParameterList) session.getAttribute("params");
if (authenticated) {
if (params == null) { // 直接访问登录界面
%>
<body class="logined">
<!--<h1>当前用户已登录!</h1>-->
</body>
<% }
} else {
if (params != null) {
String realm = params.hasParameter("openid.realm") ? params.getParameterValue("openid.realm") : null;
String returnTo = params.hasParameter("openid.return_to") ? params.getParameterValue("openid.return_to") : null;
String claimedId = params.hasParameter("openid.claimed_id") ? params.getParameterValue("openid.claimed_id") : null;
String identity = params.hasParameter("openid.identity") ? params.getParameterValue("openid.identity") : null;
String site = (realm == null ? returnTo : realm); %>
<body class="unlogin">
<div class="login_box">
<div class="login_top"></div>
<div class="login_body">
<form class="login_form " method="post">
<div class="clear">
<!--<strong>ClaimedID:</strong><%= claimedId%><br />
<strong>Identity:</strong><%= identity %><br />-->
<em>站点:</em>
<span class="login_label"><%= site %></span>
</div>
<% } %>
<div class="tips">
<div class="tip_wrong">
<span>
密码提示密码提示,填写错误示,填
</span>
</div>
</div>
<div class="clear">
<em>
用户名:
</em>
<input name="username" type="text" class="input_user"/><!--onmouseover="this.className='input_user_hover'"
onmouseout="this.className='input_user'"-->
</div>
<div class="clear">
<em>
密 码:
</em>
<input name="password" type="password" class="input_password"/><!-- onmouseover="this.className='input_password_hover'"
onmouseout="this.className='input_password'" -->
</div>
<div class="forget">
<em></em>
<div class="forget_content ">
<label>
<input type="checkbox" name="checkbox" id="checkbox" style="margin:0"/>
记住登录信息
</label>
<!--<a href="#">
<img src="images/Help-Circle.jpg" border="0" />
忘记密码
</a>-->
</div>
</div>
<div class="login_bt">
<em></em>
<input type="submit" class="" value=" " />
</div>
<div class="clear"></div>
</form>
</div>
<div class="login_bottom"></div>
</div>
</body>
<% } %>
</html> | zyeeda-framework | drivebox/src/main/webapp/provider/signin.jsp | Java Server Pages | asf20 | 3,205 |
<%@ page contentType="application/xrds+xml"%>
<xrds:XRDS xmlns:xrds="xri://$xrds"
xmlns:openid="http://openid.net/xmlns/1.0" xmlns="xri://$xrd*($v*2.0)">
<XRD>
<Service priority="0">
<Type>http://specs.openid.net/auth/2.0/signon</Type>
<Type>http://specs.openid.net/extensions/pape/1.0</Type>
<Type>http://openid.net/srv/ax/1.0</Type>
<Type>http://specs.openid.net/extensions/oauth/1.0</Type>
<Type>http://specs.openid.net/extensions/ui/1.0/lang-pref</Type>
<Type>http://specs.openid.net/extensions/ui/1.0/mode/popup</Type>
<Type>http://schemas.xmlsoap.org/ws/2005/05/identity/claims/privatepersonalidentifier</Type>
<Type>http://www.idmanagement.gov/schema/2009/05/icam/no-pii.pdf</Type>
<Type>http://www.idmanagement.gov/schema/2009/05/icam/openid-trust-level1.pdf</Type>
<Type>http://csrc.nist.gov/publications/nistpubs/800-63/SP800-63V1_0_2.pdf</Type>
<URI><%= request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath()%>/provider/endpoint</URI>
<LocalID><%= request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath()%>/provider/user.jsp?id=<%= request.getParameter("id")%></LocalID>
</Service>
</XRD>
</xrds:XRDS>
| zyeeda-framework | drivebox/src/main/webapp/provider/user.jsp | Java Server Pages | asf20 | 1,419 |
@charset "utf-8";
.unlogin {
margin: 0px;
padding: 0px;
background-color:#348bd1;
background-image:url(../images/login_bg.jpg);
background-repeat:no-repeat;
background-position:0px 0px;
background-position:center top;
}
.logined {
margin: 0px;
padding: 0px;
background-color:#FFFFFF;
background-image:url(../images/logined_bg.jpg);
background-repeat:no-repeat;
background-position:0px 0px;
background-position:center top;
}
html{overflow-y:hidden; font-size:12px}
.body_middle{
width:432px;
height:572px;
background:url(../images/login_middle.jpg) no-repeat;
position:relative;
margin:0px auto;
}
.login_box {
width: 498px;
top: auto;
margin-top: 156px;
margin-right: auto;
margin-bottom: auto;
margin-left: auto;
}
.login_top,.login_bottom,.s_login_top{
background-image:url(../images/login_box_top.gif);
background-repeat:no-repeat;
height:5px;
}
.login_top{
height:15px;
}
.login_bottom{
height:5px!important;
background-position:0px -15px;
font-size:0px;
}
.login_title{
line-height:200%;
margin-bottom:5px;
}
.s_login_top{
background-position:0px -20px;
height:5px!important;
*height:5px;
_height:5px;
font-size:0px;
}
.login_body {
background-image: url(../images/login_body_bg.gif);
background-repeat: repeat-y;
min-height: 210px;
height:auto!important;
padding-bottom:10px;
}
.login_form{
width:422px;
margin:0px auto;
padding-top:5px;
}
.login_form em{
font-size:14px;
font-weight:bold;
font-style:normal;
color:#4a4a4a;
width:80px;
line-height:30px;
_line-height:32px;
height:30px;
display:block;
float:left;
text-align:right;text-justify:inter-ideograph;
}
.login_form .login_input{
float:left
}
.clear{ clear:both}
.input_user,
.input_password,
.input_user_hover,
.input_password_hover{
background:url(../images/input_bg.gif);
background-repeat: no-repeat;
height:28px;
line-height:25px;
width:200px;
border:0px;
padding-left:30px;
font-size:14px;
}
.login_label {
height:28px;
line-height:28px;
width:200px;
border:0px;
font-size:14px;
color : #3963c8;
}
.input_password{
background-position:0px -30px;
}
.input_user_hover{
background-position:0px -60px;
}
.input_password_hover{
background-position:0px -90px;
}
.forget {
vertical-align: middle;
height:30px;
margin-top:10px;
}
.forget_content *{
vertical-align:bottom;
_vertical-align:baseline
}
.forget label input{
margin:0px;
padding:0px;
vertical-align:bottom;
_vertical-align:baseline
}
.forget a{
text-decoration:none;
}
.login_bt input{
width:98px;
height:34px;
background: url(../images/login_bt.gif) no-repeat;
border:0px;
cursor:pointer
}
/*提示信息*/
.tips{
display : none;
padding-left: 83px;
min-width:200px;
width:228px;
margin-bottom:5px
}
.tip_wrong{
border:1px solid #ff624d;
background-color:#fff5c7;
font-size:12px;
}
.tip_true,.tip_prompt,.tip_normal {
border:1px solid #3ba2e8;
background-color:#eff4ff;
font-size:12px;
}
.tip_wrong span,.tip_true span,.tip_prompt span,.tip_normal span{
background-image:url(../images/tip.gif);
background-repeat:no-repeat;
padding-left:20px;
margin:3.5px;
display:block;
}
.tip_wrong span{
background-position:0px -32px ;
}
.tip_true span{
background-position:0px -16px ;
}
.tip_normal span{
background-image: none;
}
.forget_content {
display : block;
}
| zyeeda-framework | drivebox/src/main/webapp/provider/style/login.css | CSS | asf20 | 3,534 |
<%@ page contentType="application/xrds+xml"%>
<xrds:XRDS xmlns:xrds="xri://$xrds"
xmlns:openid="http://openid.net/xmlns/1.0" xmlns="xri://$xrd*($v*2.0)">
<XRD>
<Service priority="0">
<Type>http://specs.openid.net/auth/2.0/server</Type>
<Type>http://specs.openid.net/extensions/pape/1.0</Type>
<Type>http://openid.net/srv/ax/1.0</Type>
<Type>http://specs.openid.net/extensions/oauth/1.0</Type>
<Type>http://specs.openid.net/extensions/ui/1.0/lang-pref</Type>
<Type>http://specs.openid.net/extensions/ui/1.0/mode/popup</Type>
<Type>http://schemas.xmlsoap.org/ws/2005/05/identity/claims/privatepersonalidentifier</Type>
<Type>http://www.idmanagement.gov/schema/2009/05/icam/no-pii.pdf</Type>
<Type>http://www.idmanagement.gov/schema/2009/05/icam/openid-trust-level1.pdf</Type>
<Type>http://csrc.nist.gov/publications/nistpubs/800-63/SP800-63V1_0_2.pdf</Type>
<URI><%= request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()%>/provider/endpoint</URI>
</Service>
</XRD>
</xrds:XRDS>
| zyeeda-framework | drivebox/src/main/webapp/provider/xrds.jsp | Java Server Pages | asf20 | 1,187 |
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ page import="org.apache.shiro.SecurityUtils"%>
<%
SecurityUtils.getSubject().logout();
/* out.println("已登出"); */
%>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>该用户已退出</title>
<link href="style/login2.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="status_frame">
<div class="status_box">
<div class="status_body ">
<h1 class="islogout"> 该用户已退出</h1>
<p>您已经安全退出本系统</p>
</div>
</div>
</div>
</body>
</html> | zyeeda-framework | drivebox/src/main/webapp/accounts/openid/signout.jsp | Java Server Pages | asf20 | 682 |
<%@ page import="java.util.Map"%>
<%@ page import="org.openid4java.message.AuthRequest"%>
<%@ page import="com.zyeeda.framework.FrameworkConstants" %>
<%@ page import="org.apache.tapestry5.ioc.Registry" %>
<%@ page import="com.zyeeda.framework.security.SecurityService" %>
<%@ page import="com.zyeeda.framework.security.internal.OpenIdConsumerSecurityServiceProvider" %>
<%@ page import="com.zyeeda.framework.utils.IocUtils" %>
<%@ page contentType="text/html;charset=UTF-8" %>
<%
AuthRequest authReq = (AuthRequest) request.getAttribute("message");
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>单点登录</title>
<link href="style/login2.css" rel="stylesheet" type="text/css" />
</head>
<% if (authReq == null) { %>
<body>
<div class="status_frame">
<div class="status_box">
<div class="status_body ">
<h1 class="islogin_icon"> 该用户已经登录</h1>
<%
Registry reg = (Registry) application.getAttribute(FrameworkConstants.SERVICE_REGISTRY);
SecurityService securityService = reg.getService(IocUtils.getServiceId(OpenIdConsumerSecurityServiceProvider.class), SecurityService.class);
String username = securityService.getCurrentUser();
%>
<p>登录名:<%=username%></p>
</div>
</div>
</div>
</body>
<% } else {
Map<?, ?> params = authReq.getParameterMap(); %>
<body onload="document.forms['openid-form-redirection'].submit();">
<div class="status_frame">
<div class="status_box">
<div class="status_body ">
<h1> <img src="img/loading.gif" width="37" height="37" />正在向单点登录服务器发送请求,请稍后</h1>
<!--<h1>正在向单点登录服务器发送请求,请稍候……</h1>
<p> <%= authReq.getOPEndpoint() %> </p>-->
<form name="openid-form-redirection" action="<%= authReq.getOPEndpoint() %>" method="post" accept-charset="utf-8">
<% for (Map.Entry<?, ?> entry : params.entrySet()) { %>
<input type="hidden" name="<%= (String) entry.getKey() %>" value="<%= (String) entry.getValue() %>" />
<% } %>
</form>
</div>
</div>
</div>
</body>
<% } %>
</html> | zyeeda-framework | drivebox/src/main/webapp/accounts/openid/signin.jsp | Java Server Pages | asf20 | 2,378 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function callback() {
var url = '<%= request.getParameter("_url")%>';
var method = '<%= request.getParameter("_method")%>';
parent.ZDA.contextLoginPanel.hide();
}
</script>
</head>
<body onload='callback();'></body>
</html> | zyeeda-framework | drivebox/src/main/webapp/accounts/openid/callback.jsp | Java Server Pages | asf20 | 512 |
@charset "utf-8";
body {
margin: 0px;
padding: 0px;
background-color:#348bd1;
/* background-image:url(../img/login_bg.jpg); */
background-repeat:no-repeat;
background-position:0px 0px;
background-position:center top;
}
html{overflow-y:hidden; font-size:12px}
.body_middle{
width:432px;
height:572px;
background:url(../img/login_middle.jpg) no-repeat;
position:relative;
margin:0px auto;
}
.login_box {
width: 498px;
top: auto;
margin-top: 156px;
margin-right: auto;
margin-bottom: auto;
margin-left: auto;
}
.login_top,.login_bottom,.s_login_top{
background-image:url(../img/login_box_top.gif);
background-repeat:no-repeat;
height:5px;
}
.login_top{
height:15px;
}
.login_bottom{
height:5px!important;
background-position:0px -15px;
font-size:0px;
}
.login_title{
line-height:200%;
margin-bottom:5px;
}
.s_login_top{
background-position:0px -20px;
height:5px!important;
*height:5px;
_height:5px;
font-size:0px;
}
.login_body {
background-image: url(../img/login_body_bg.gif);
background-repeat: repeat-y;
min-height: 210px;
height:auto!important;
padding-bottom:10px;
}
.login_form{
width:422px;
margin:0px auto;
padding-top:5px;
}
.login_form em{
font-size:14px;
font-weight:bold;
font-style:normal;
color:#4a4a4a;
width:80px;
line-height:30px;
_line-height:32px;
height:30px;
display:block;
float:left;
text-align:right;text-justify:inter-ideograph;
}
.login_form .login_input{
float:left
}
.clear{ clear:both}
.input_user,
.input_password,
.input_user_hover,
.input_password_hover{
background:url(../img/input_bg.gif);
background-repeat: no-repeat;
height:28px;
line-height:25px;
width:200px;
border:0px;
padding-left:30px;
font-size:14px;
}
.input_password{
background-position:0px -30px;
}
.input_user_hover{
background-position:0px -60px;
}
.input_password_hover{
background-position:0px -90px;
}
.forget {
vertical-align: middle;
height:30px;
margin-top:10px;
}
.forget_content *{
vertical-align:bottom;
_vertical-align:baseline
}
.forget label input{
margin:0px;
padding:0px;
vertical-align:bottom;
_vertical-align:baseline
}
.forget a{
text-decoration:none;
}
.login_bt input{
width:98px;
height:34px;
background: url(../img/login_bt.gif) no-repeat;
border:0px;
cursor:pointer
}
/*提示信息*/
.tips{
padding-left: 83px;
min-width:200px;
width:228px;
margin-bottom:5px}
.tip_wrong{
border:1px solid #ff624d;
background-color:#fff5c7;
font-size:12px;
}
.tip_true,.tip_prompt,.tip_normal {
border:1px solid #3ba2e8;
background-color:#eff4ff;
font-size:12px;
}
.tip_wrong span,.tip_true span,.tip_prompt span,.tip_normal span{
background-image:url(../img/tip.gif);
background-repeat:no-repeat;
padding-left:20px;
margin:3.5px;
display:block;
}
.tip_wrong span{
background-position:0px -32px ;
}
.tip_true span{
background-position:0px -16px ;
}
.tip_normal span{
background-image: none;
}
/*判断登录状态*/
.status_frame{
width:868px;
height:600px;
/* margin:0px auto; */
margin:-300px 0 0 -434px;
position:absolute;
left:50%;
top:50%;
background: url(../img/login_status.jpg) no-repeat;
}
.status_box{
width:500px;
height:100px;
padding-top:173px;
margin-left:247px;
}
.status_body{
margin-left:32px;
padding-top:30px;
}
.status_body h1{
line-height:26px;
font-size:18px;
font: "微软雅黑";
font-weight:bold;
display:block;
margin:0px;
}
.status_body h1 *{ vertical-align:middle}
.status_body p{
display:block;
line-height:200%;
font-style:16px;
font-weight:bold;
color:#00497f;
margin:0px;
padding-left:40px;
}
.islogin_icon,.islogout{
height:26px;
background-image:url(../img/islogin_icon.gif);
background-repeat:no-repeat;
padding-left:40px;
}
.islogout{background-position:0px -26px;} | zyeeda-framework | drivebox/src/main/webapp/accounts/openid/style/login2.css | CSS | asf20 | 3,994 |
.unlogin {
margin: 0px;
padding: 0px;
background-color:#FFFFFF;
background-image:url(../img/unlogin_bg.jpg);
background-repeat:no-repeat;
background-position:0px 0px;
background-position:center top;
}
.logined {
margin: 0px;
padding: 0px;
background-color:#FFFFFF;
background-image:url(../img/logined_bg.jpg);
background-repeat:no-repeat;
background-position:0px 0px;
background-position:center top;
} | zyeeda-framework | drivebox/src/main/webapp/accounts/openid/style/login.css | CSS | asf20 | 442 |
<%@ page import="org.apache.tapestry5.ioc.Registry" %>
<%@ page import="com.zyeeda.framework.FrameworkConstants" %>
<%@ page import="com.zyeeda.framework.nosql.MongoDbService" %>
<%@ page import="com.zyeeda.framework.managers.DocumentManager" %>
<%@ page import="com.zyeeda.framework.managers.internal.MongoDbDocumentManager" %>
<%
String foreignId = request.getParameter("foreignId");
Registry reg = (Registry) application.getAttribute(FrameworkConstants.SERVICE_REGISTRY);
MongoDbService mongoSvc = reg.getService(MongoDbService.class);
DocumentManager docMgr = new MongoDbDocumentManager(mongoSvc);
System.out.println("count = " + docMgr.countBySuffixes("tangrui", foreignId, "doc", "docx"));
docMgr.replaceForeignId(foreignId, "tangrui");
out.print("OK");
%> | zyeeda-framework | drivebox/src/main/webapp/attachments/commit.jsp | Java Server Pages | asf20 | 785 |
ZUI.call(function(Z) {
Z.cfg = {
uploader : {
totalCountUrl : '/drivebox/rs/docs/count',
uploadUrl : '/drivebox/rs/docs',
listUrl : '/drivebox/rs/docs'
}
};
ZYEEDA.com.zyeeda.zui.framework.demo.AttachmentDemo.main(Z);
});
| zyeeda-framework | drivebox/src/main/webapp/attachments/lib/zyeeda/main.js | JavaScript | asf20 | 298 |
ZYEEDA.namespace('com.zyeeda.zui.framework.demo').AttachmentDemo = function() {
return {
main : function(Z) {
var attach = new Z.AttachmentManager({
totalCountUrl : Z.cfg.uploader.totalCountUrl,
uploadUrl : Z.cfg.uploader.uploadUrl,
listUrl : Z.cfg.uploader.listUrl,
foreignId : 'tangrui'
});
attach.render('#attachment');
var uploadedList = new Z.AttachmentUploadedList({
listUrl : Z.cfg.uploader.listUrl,
foreignId : 'zhaoqi',
width : '800px',
height : '335px',
readOnly : true
});
uploadedList.render('#manager');
Z.one('#destroyBtn').on('click', function() {
uploadedList.destroy();
attach.destroy();
});
}
}
}();
| zyeeda-framework | drivebox/src/main/webapp/attachments/lib/zyeeda/attachment-demo.js | JavaScript | asf20 | 947 |
<%@ page contentType="text/plain;charset=UTF-8" isErrorPage="true"%>
<%@ page import="java.io.PrintWriter"%>
<%= exception.getMessage() %> | zyeeda-framework | drivebox/src/main/webapp/exception.jsp | Java Server Pages | asf20 | 142 |
<%@ page import="com.zyeeda.framework.utils.IocUtils" %>
<%@ page import="com.zyeeda.framework.scheduler.SchedulerService" %>
<%@ page import="org.apache.tapestry5.ioc.Registry" %>
<%@ page import="org.quartz.TriggerKey" %>
<%@ page import="org.quartz.Trigger" %>
<%@ page import="org.quartz.Scheduler" %>
<%@ page import="org.quartz.TriggerBuilder" %>
<%@ page import="org.quartz.SimpleScheduleBuilder" %>
<%@ page import="org.quartz.impl.matchers.GroupMatcher" %>
<%
Registry registry = IocUtils.getRegistry(application);
SchedulerService<?> schedulerSvc = registry.getService(SchedulerService.class);
Scheduler scheduler = (Scheduler) schedulerSvc.getScheduler();
Trigger oldTrigger = scheduler.getTrigger(TriggerKey.triggerKey("test-trigger", "test-trigger-group"));
System.out.println(scheduler.getTriggerKeys(GroupMatcher.groupEquals("test-trigger-group")));
if (oldTrigger != null) {
TriggerBuilder builder = oldTrigger.getTriggerBuilder();
Trigger newTrigger = builder.withSchedule(
SimpleScheduleBuilder.simpleSchedule()
.withRepeatCount(3)
.withIntervalInSeconds(1)).startNow().build();
scheduler.rescheduleJob(oldTrigger.getKey(), newTrigger);
} else {
out.print("old trigger is null");
}
%> | zyeeda-framework | drivebox/src/main/webapp/quartz/reschedule.jsp | Java Server Pages | asf20 | 1,247 |
<#import "/lib/zyeeda/html.ftl" as z>
<@z.html>
<@z.head />
<script type="text/javascript">
YUI().use('dd', 'yui2-calendar', function(Y) {});
</script>
</@z.html> | zyeeda-framework | drivebox/src/main/webapp/WEB-INF/templates/index.ftl | Fluent | asf20 | 180 |
<#macro html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh_CN" lang="zh_CN">
<#nested>
</html>
</#macro>
<#macro yui_include filter="min">
<script type="text/javascript" src="${CONTEXT_PATH}/static/yui/3.2.0/build/yui/yui-min.js"></script>
<script type="text/javascript">
YUI_config = {
lang : 'zh-CN,en-US',
base : '${CONTEXT_PATH}/static/yui/3.2.0/build/',
charset : 'utf-8',
loadOptional : true,
combine : false,
filter : '${filter}',
timeout : 10000,
groups : {
yui2 : {
lang : 'zh-CN,en-US',
base : '${CONTEXT_PATH}/static/yui/2.8.2/build/',
combine : false,
patterns : {
'yui2-' : {
configFn : function(me) {
if (/-skin|reset|fonts|grids|base/.test(me.name)) {
me.type = 'css';
me.path = me.path.replace(/\.js/, '.css');
me.path = me.path.replace(/\/yui2-skin/, '/assets/skins/sam/yui2-skin');
}
}
}
}
}
}
};
</script>
</#macro>
<#macro head title="中昱达">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>${title}</title>
<@yui_include />
<#nested>
</head>
</#macro>
| zyeeda-framework | drivebox/src/main/webapp/WEB-INF/templates/lib/zyeeda/html.ftl | Fluent | asf20 | 1,750 |
package com.zyeeda.framework.vos;
import java.util.Collection;
import javax.xml.bind.annotation.XmlRootElement;
import com.zyeeda.framework.entities.Role;
@XmlRootElement(name = "roles")
public class Roles {
private Collection<Role> roles;
public void setRole(Collection<Role> roles) {
this.roles = roles;
}
public Collection<Role> getRole() {
return this.roles;
}
}
| zyeeda-framework | drivebox/src/main/java/com/zyeeda/framework/vos/Roles.java | Java | asf20 | 387 |
package com.zyeeda.framework.resources;
import java.util.List;
import javax.persistence.EntityManager;
import javax.servlet.ServletContext;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import org.apache.tapestry5.ioc.Registry;
import com.zyeeda.framework.FrameworkConstants;
import com.zyeeda.framework.entities.Role;
import com.zyeeda.framework.persistence.PersistenceService;
import com.zyeeda.framework.persistence.internal.DefaultPersistenceServiceProvider;
import com.zyeeda.framework.utils.IocUtils;
import com.zyeeda.framework.vos.Roles;
@Path("/hello")
public class RoleResource {
@GET
@Produces("application/json")
public Roles getRoles(@Context ServletContext context) {
Registry reg = (Registry) context.getAttribute(FrameworkConstants.SERVICE_REGISTRY);
PersistenceService persistenceSvc = reg.getService(IocUtils.getServiceId(DefaultPersistenceServiceProvider.class), PersistenceService.class);
EntityManager session = persistenceSvc.openSession();
List<Role> roleList = session.createNamedQuery("getRoles", Role.class).getResultList();
Roles roles = new Roles();
roles.setRole(roleList);
return roles;
}
}
| zyeeda-framework | drivebox/src/main/java/com/zyeeda/framework/resources/RoleResource.java | Java | asf20 | 1,210 |
package com.zyeeda.framework.resources;
import javax.servlet.ServletContext;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import org.apache.tapestry5.ioc.Registry;
import org.drools.runtime.StatefulKnowledgeSession;
import com.zyeeda.framework.FrameworkConstants;
import com.zyeeda.framework.knowledge.KnowledgeService;
import com.zyeeda.framework.knowledge.AbstractStatefulSessionCommand;
@Path("sample")
public class SampleFlowResource {
@GET
@Produces("text/plain")
public String start(@Context ServletContext context) throws Exception {
Registry reg = (Registry) context.getAttribute(FrameworkConstants.SERVICE_REGISTRY);
final KnowledgeService ksvc = reg.getService(KnowledgeService.class);
AbstractStatefulSessionCommand<String> command = new AbstractStatefulSessionCommand<String>() {
private static final long serialVersionUID = 803619017440949193L;
@Override
public String execute(StatefulKnowledgeSession ksession) {
//JPASessionMarshallingHelper helper = new JPASessionMarshallingHelper(ksession, null);
//System.out.println(helper.getSnapshot());
System.out.println(ksession.getId());
//ksession.startProcess("com.zyeeda.system.TestFlow");
return "OK";
}
};
//command.setSessionId(10);
return ksvc.execute(command);
/*return ksvc.execute(new AbstractStatefulSessionCommand<String>() {
private static final long serialVersionUID = 803619017440949193L;
@Override
public String execute(StatefulKnowledgeSession ksession) {
ksession.startProcess("com.zyeeda.system.TestFlow");
return "OK";
}
});*/
}
}
| zyeeda-framework | drivebox/src/main/java/com/zyeeda/framework/resources/SampleFlowResource.java | Java | asf20 | 1,713 |
package com.zyeeda.drivebox.ioc;
import org.apache.tapestry5.ioc.ServiceBinder;
import org.apache.tapestry5.ioc.annotations.Primary;
import org.apache.tapestry5.ioc.annotations.Startup;
import org.quartz.Job;
import com.zyeeda.drivebox.jobs.TestJob;
import com.zyeeda.framework.config.ConfigurationService;
import com.zyeeda.framework.config.internal.DefaultConfigurationServiceProvider;
import com.zyeeda.framework.knowledge.KnowledgeService;
import com.zyeeda.framework.knowledge.internal.DroolsKnowledgeServiceProvider;
import com.zyeeda.framework.ldap.LdapService;
import com.zyeeda.framework.ldap.internal.SunLdapServiceProvider;
import com.zyeeda.framework.nosql.MongoDbService;
import com.zyeeda.framework.nosql.internal.DefaultMongoDbServiceProvider;
import com.zyeeda.framework.openid.consumer.OpenIdConsumerService;
import com.zyeeda.framework.openid.consumer.internal.DefaultOpenIdConsumerServiceProvider;
import com.zyeeda.framework.persistence.PersistenceService;
import com.zyeeda.framework.persistence.annotations.DroolsTask;
import com.zyeeda.framework.persistence.internal.DefaultPersistenceServiceProvider;
import com.zyeeda.framework.persistence.internal.DroolsTaskPersistenceServiceProvider;
import com.zyeeda.framework.scheduler.SchedulerService;
import com.zyeeda.framework.scheduler.internal.QuartzSchedulerServiceProvider;
import com.zyeeda.framework.security.SecurityService;
import com.zyeeda.framework.security.annotations.Virtual;
import com.zyeeda.framework.security.internal.OpenIdConsumerSecurityServiceProvider;
import com.zyeeda.framework.security.internal.VirtualConsumerSecurityServiceProvider;
import com.zyeeda.framework.sync.UserSyncService;
import com.zyeeda.framework.sync.internal.HttpClientUserSyncServiceProvider;
import com.zyeeda.framework.template.TemplateService;
import com.zyeeda.framework.template.internal.FreemarkerTemplateServiceProvider;
import com.zyeeda.framework.transaction.TransactionService;
import com.zyeeda.framework.transaction.internal.DefaultTransactionServiceProvider;
import com.zyeeda.framework.validation.ValidationService;
import com.zyeeda.framework.validation.internal.HibernateValidationServiceProvider;
public class Module {
public static void bind(ServiceBinder binder) {
binder.bind(ConfigurationService.class, DefaultConfigurationServiceProvider.class);
binder.bind(TemplateService.class, FreemarkerTemplateServiceProvider.class);
binder.bind(PersistenceService.class, DefaultPersistenceServiceProvider.class);
binder.bind(PersistenceService.class, DroolsTaskPersistenceServiceProvider.class);
binder.bind(ValidationService.class, HibernateValidationServiceProvider.class);
binder.bind(LdapService.class, SunLdapServiceProvider.class);
binder.bind(SecurityService.class, OpenIdConsumerSecurityServiceProvider.class);
binder.bind(SecurityService.class, VirtualConsumerSecurityServiceProvider.class);
binder.bind(KnowledgeService.class, DroolsKnowledgeServiceProvider.class);
binder.bind(TransactionService.class, DefaultTransactionServiceProvider.class);
binder.bind(OpenIdConsumerService.class, DefaultOpenIdConsumerServiceProvider.class);
binder.bind(UserSyncService.class, HttpClientUserSyncServiceProvider.class);
binder.bind(SchedulerService.class, QuartzSchedulerServiceProvider.class);
binder.bind(MongoDbService.class, DefaultMongoDbServiceProvider.class);
binder.bind(Job.class, TestJob.class);
}
@Startup
public static void startServices(
@Primary final ConfigurationService configSvc,
@Primary final TemplateService tplSvc,
@Primary final TransactionService txSvc,
@Primary final ValidationService validationSvc,
@Primary final PersistenceService defaultPersistenceSvc,
@DroolsTask final PersistenceService droolsTaskPersistenceSvc,
@Primary final LdapService ldapSvc,
@Primary final SecurityService<?> securitySvc,
@Virtual final SecurityService<?> virtualSecuritySvc,
@Primary final KnowledgeService knowledgeSvc,
@Primary final OpenIdConsumerService consumerSvc,
@Primary final UserSyncService userSyncSvc,
@Primary final SchedulerService<?> schedulerSvc,
@Primary final MongoDbService mongodbSvc) throws Exception {
configSvc.start();
tplSvc.start();
mongodbSvc.start();
//txSvc.start();
//validationSvc.start();
//defaultPersistenceSvc.start();
//droolsTaskPersistenceSvc.start();
ldapSvc.start();
securitySvc.start();
virtualSecuritySvc.start();
//knowledgeSvc.start();
consumerSvc.start();
//userSyncSvc.start();
//schedulerSvc.start();
mongodbSvc.start();
}
}
| zyeeda-framework | drivebox/src/main/java/com/zyeeda/drivebox/ioc/Module.java | Java | asf20 | 4,674 |
package com.zyeeda.drivebox.jobs;
import java.util.Date;
import java.util.concurrent.Callable;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.tapestry5.ioc.ScopeConstants;
import org.apache.tapestry5.ioc.annotations.Scope;
import org.apache.tapestry5.ioc.annotations.ServiceId;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zyeeda.framework.openid.consumer.shiro.PasswordFreeAuthenticationToken;
import com.zyeeda.framework.security.SecurityService;
import com.zyeeda.framework.security.annotations.Virtual;
@ServiceId("test-job")
@Scope(ScopeConstants.PERTHREAD)
public class TestJob implements Job {
private final static Logger logger = LoggerFactory.getLogger(TestJob.class);
private SecurityService<SecurityManager> securitySvc;
public TestJob(@Virtual SecurityService<SecurityManager> securitySvc) {
this.securitySvc = securitySvc;
}
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
logger.info("current time = {}", new Date());
final Subject subject = new Subject.Builder(this.securitySvc.getSecurityManager()).buildSubject();
subject.execute(new Callable<Void>() {
@Override
public Void call() throws Exception {
subject.login(new PasswordFreeAuthenticationToken("system"));
logger.info("current user = {}", securitySvc.getCurrentUser());
return null;
}
});
}
}
| zyeeda-framework | drivebox/src/main/java/com/zyeeda/drivebox/jobs/TestJob.java | Java | asf20 | 1,600 |
function v = Lpnorm(X, p, d)
%Compute Lp-norm values of vectors
%
% v = Lpnorm(X, p);
% v = Lpnorm(X, p, d);
% compute the Lp-norm values of the vectors contained in X along
% dimension d. If d is omitted, by default, it is set to 1.
%
% v = Lpnorm(X, p, []);
% compute the Lp-norm of the entire array X.
%
% Remarks:
% - For this function, p should be a scalar that has p >= 1.
%
% Created by Dahua Lin, on Aug 1, 2010
%
%% verify input
if nargin < 3
d = 1;
end
if p < 1
error('Lpnorm:invalidarg', 'p must have p >= 1.');
end
%% main
if p == 1
v = L1norm(X, d);
elseif p == 2
v = L2norm(X, d);
elseif isinf(p)
v = Linfnorm(X, d);
else
if ~isempty(d)
v = sum(abs(X).^p, d);
else
v = sum(abs(X(:)).^p);
end
v = v.^(1/p);
end
| zzhangumd-smitoolbox | base/metrics/Lpnorm.m | MATLAB | mit | 831 |
function D = pwsqL2dist(X1, X2, w)
% Compute the pairwise squared L2-norm distances
%
% D = pwsqL2dist(X1, X2);
% computes the squared L2-norm distance between pairs of column
% vectors in X1 and X2.
%
% Suppose the vector dimension is d, then X1 and X2 should be
% matrices of size d x m and d x n. In this case, the output
% is a matrix of size m x n, where D(i, j) is the distance between
% X1(:,i) and X2(:,j).
%
% D = pwsqL2dist(X);
% D = pwsqL2dist(X, []);
% computes the squared L2-norm distance between pairs of column
% vectors in X. The implementation for this case is more efficient
% than pwsqL2dist(X, X), despite that both yield the same result.
%
% D = pwsqL2dist(X, [], w);
% D = pwsqL2dist(X1, X2, w);
% computes the weighted squared L2-norm distance between column
% vectors in X1 and X2. The weighted squared L2-norm distance is
% defined by
%
% d = sum_i w(i) * |x1(i) - x2(i)|^2
%
% In the input, w should be a column vector.
%
% Created by Dahua Lin, on Aug 2, 2010
%
%% verify input
if nargin < 2
X2 = [];
end
if ~(ndims(X1) == 2 && isfloat(X1) && isreal(X1))
error('pwsqL2dist:invalidarg', 'X1 should be a real matrix.');
end
if ~isempty(X2)
if ~(ndims(X2) == 2 && isfloat(X2) && isreal(X2))
error('pwsqL2dist:invalidarg', 'X2 should be a matrix.');
end
if size(X1,1) ~= size(X2,1)
error('pwsqL2dist:invalidarg', 'X1 and X2 should have the same #rows.');
end
end
if nargin < 3 || isempty(w)
weighted = false;
else
if ~(ndims(w) == 2 && size(w, 2) == 1 && isreal(w))
error('pwsqL2dist:invalidarg', 'w should be a real row vector.');
end
weighted = true;
end
%% main
if isempty(X2)
n = size(X1, 2);
if ~weighted
D = X1' * X1;
else
D = X1' * bsxfun(@times, w, X1);
end
% take the diagonal elements, which equals sum(X1 .* X1, 1);
sx = D(1 + (n+1) * (0:n-1));
D = bsxfun(@plus, (-2) * D, sx);
D = bsxfun(@plus, D, sx');
else
if ~weighted
D = (-2) * (X1' * X2);
D = bsxfun(@plus, D, sum(X1 .^ 2, 1).');
D = bsxfun(@plus, D, sum(X2 .^ 2, 1));
else
wX1 = bsxfun(@times, w, X1);
wX2 = bsxfun(@times, w, X2);
D = (-2) * (X1' * wX2);
D = bsxfun(@plus, D, sum(X1 .* wX1, 1).');
D = bsxfun(@plus, D, sum(X2 .* wX2, 1));
end
end
% enforce non-negativeness (rounding error may lead to negative values)
D(D < 0) = 0;
| zzhangumd-smitoolbox | base/metrics/pwsqL2dist.m | MATLAB | mit | 2,606 |
function dists = raddiff(X1, X2)
%RADIANDIFF Computes the radian differences between corresponding vectors
%
% dists = radiandiff(X1, X2);
% computes the radian differences between corresponding vectors in X1
% and X2.
%
% The radian difference is the angle between two vectors in unit of
% radian. In mathematics, it can be defined as arccos of normalized
% correlation, which ranges from 0 (when correlation is 1) to pi
% (when correlation is -1). If the radian difference between two
% vectors is pi / 2, they are orthogonal to each other.
%
% X1 and X2 should be matrices of the same size. Let their size be
% d x n, then dists will be a 1 x n vector, with dists(i) being the
% radian difference betwen X1(:, i) and X2(:, i).
%
% History
% - Created by Dahua Lin, on Jun 3, 2008
% - Modified by Dahua Lin, on Jul 22, 2010
% - based on nrmdot
% - Modified by Dahua Lin, on Aug 2, 2010
% - rename: radiandiff -> raddiff
%
%% main
nds = nrmdot(X1, X2);
nds(nds > 1) = 1;
nds(nds < -1) = -1;
dists = acos(nds);
| zzhangumd-smitoolbox | base/metrics/raddiff.m | MATLAB | mit | 1,121 |
function D = Linfdist(X1, X2, d)
%Compute the L_infinity norm distances between corresponding vectors
%
% D = Linfdist(X1, X2);
% D = Linfdist(X1, X2, d);
% computes the L_infinity norm distances between corresponding
% vectors in X1 and X2 along dimension d.
%
% In the input X1 and X2 should be arrays of the same size.
%
% D = Linfdist(X1, X2, []);
% computes the L_infinity norm distances between X1 and X2 as a
% whole.
%
% Created by Dahua Lin, on Aug 2, 2010
%
%% main
if nargin < 3
d = 1;
end
D = Linfnorm(X1 - X2, d);
| zzhangumd-smitoolbox | base/metrics/Linfdist.m | MATLAB | mit | 574 |
function D = Lpdist(X1, X2, p, d)
%Compute the Lp-norm distances between corresponding vectors
%
% D = Lpdist(X1, X2, p);
% D = Lpdist(X1, X2, p, d);
% computes the Lp-norm distances between corresponding vectors in
% X1 and X2 along dimension d.
%
% In the input X1 and X2 should be arrays of the same size.
%
% D = Lpdist(X1, X2, p, []);
% computes the Lp-norm distances between X1 and X2 as a whole.
%
% Created by Dahua Lin, on Aug 2, 2010
%
%% main
if nargin < 4
d = 1;
end
D = Lpnorm(X1 - X2, p, d);
| zzhangumd-smitoolbox | base/metrics/Lpdist.m | MATLAB | mit | 547 |
function v = sqL2norm(X, d)
%Compute squared L2-norm values of vectors
%
% v = sqL2norm(X);
% v = sqL2norm(X, d);
% compute the squared L2-norm values of the vectors contained in X
% along dimension d. If d is omitted, by default, it is set to 1.
%
% v = sqL2norm(X, []);
% compute the squared L2-norm of the entire array X.
%
% Created by Dahua Lin, on Aug 1, 2010
%
%% verify input
if nargin < 2
d = 1;
end
%% main
if ~isempty(d)
v = sum(X.^2, d);
else
v = sum(X(:).^2);
end
| zzhangumd-smitoolbox | base/metrics/sqL2norm.m | MATLAB | mit | 519 |
function dists = hamdist(X1, X2, w)
%HAMDIST Computes the hamming distances between corresponding vectors.
%
% dists = hamdist(X1, X2)
% computes the hamming distances between corresponding vectors in X1
% and X2.
%
% Hamming distance between two sequence of 0-1 codes is defined as
%
% d(x, y) = sum_i 1(x(i) <> y(i))
%
% which is the number of different code symbols in corresponding
% positions.
%
% X1 and X2 should be logical or numeric matrices with the same
% size. Let the size be d x n, then dists will be a 1 x n row
% vector, with dists(i) being the hamming distance between X1(:,i)
% and X2(:,i).
%
% dists = hamdist(X1, X2, w);
% computes the weighted hamming distances between corresponding
% vectors in X1 and X2.
%
% The weighted hamming distance is defined as
%
% d(x, y) = sum_i w_i * 1(x(i) <> y(i))
%
% The size of w should be d x m, where each column of w gives a
% set of weights. The output dists will be a matrix of size
% m x n.
%
% History
% - Created by Dahua Lin, on Jun 2, 2008
% - Modified by Dahua Lin, on Jul 22, 2010
% - support weighted hamming distances
% - simplify error handling
% - Modified by Dahua Lin, on Aug 2, 2010
% - allow multiple sets of weights
%
%% verify input arguments
if ~(ndims(X1) == 2 && ndims(X2) == 2)
error('hamdist:invalidarg', ...
'X1 and X2 should be both matrices.');
end
weighted = (nargin >= 3);
%% main
if ~weighted
dists = sum(X1 ~= X2, 1);
else
dists = w.' * (X1 ~= X2);
end
| zzhangumd-smitoolbox | base/metrics/hamdist.m | MATLAB | mit | 1,642 |
function v = L2norm(X, d)
%Compute squared L2-norm values of vectors
%
% v = L2norm(X);
% v = L2norm(X, d);
% compute the L2-norm values of the vectors contained in X along
% dimension d. If d is omitted, by default, it is set to 1.
%
% v = L2norm(X, []);
% compute the L2-norm of the entire array X.
%
% Created by Dahua Lin, on Aug 1, 2010
%
if nargin < 2
d = 1;
end
v = sqrt(sqL2norm(X, d)); | zzhangumd-smitoolbox | base/metrics/L2norm.m | MATLAB | mit | 425 |
function D = wL2dist(X1, X2, w)
% Compute weighted L2-norm distances between corresponding vectors
%
% D = wL2dist(X1, X2, w);
% computes weighted L2-norm distances between the corresponding
% column vectors in X1 and X2, defined by
%
% d = sqrt(sum_i w(i) * |x1(i) - x2(i)|^2)
%
% X1 and X2 should be matrices of the same size. Suppose their size
% is d x n, then w should be a matrix of size d x m. Each column of
% w gives a set of weights. The output is of size m x n, where
% D(i, :) corresponds to the weights given in w(:, i).
%
% Created by Dahua Lin, on Aug 2, 2010
%
%% main
D = sqrt(wsqL2dist(X1, X2, w));
| zzhangumd-smitoolbox | base/metrics/wL2dist.m | MATLAB | mit | 672 |
function r = L1diff(A, B)
% Compute L1-norm of the difference between two arrays
%
% r = L1diff(A, B);
% computes the L1-norm (sum of absolute value) of the difference
% between A and B.
%
% History
% -------
% - Created by Dahua Lin, on Sep 12, 2010
%
%% main
D = A - B;
D = abs(D(:));
r = sum(D);
| zzhangumd-smitoolbox | base/metrics/L1diff.m | MATLAB | mit | 349 |
function Y = Linfnormalize(X, d)
% Normalize vectors w.r.t. L_infinity norm
%
% Y = Linfnormalize(X);
% Y = Linfnormalize(X, d);
% normalize vectors in X along dimension d w.r.t. L_infinity norm.
% When d is omitted, by default, it is set to 1.
%
% Y = Linfnormalize(X, []);
% normalize X as a whole w.r.t. L_infinity norm.
%
% Created by Dahua Lin, on Aug 1, 2010
%
if nargin < 2
d = 1;
end
Y = bsxfun(@times, X, 1 ./ Linfnorm(X, d)); | zzhangumd-smitoolbox | base/metrics/Linfnormalize.m | MATLAB | mit | 467 |
function r = Linfdiff(A, B)
% Compute Linf-norm of the difference between two arrays
%
% r = Linfdiff(A, B);
% computes the L_infinity norm (maximum of absolute value) of the
% difference between A and B.
%
% History
% -------
% - Created by Dahua Lin, on Sep 12, 2010
%
%% main
D = A - B;
D = abs(D(:));
r = max(D);
| zzhangumd-smitoolbox | base/metrics/Linfdiff.m | MATLAB | mit | 367 |
function D = wsqL2dist(X1, X2, w)
% Compute weighted squared L2-norm distances between corresponding vectors
%
% D = wL2dist(X1, X2, w);
% computes weighted squared L2-norm distances between corresponding
% column vectors in X1 and X2, defined by
%
% d = sqrt(sum_i w(i) * |x1(i) - x2(i)|^2)
%
% X1 and X2 should be matrices of the same size. Suppose their size
% is d x n, then w should be a matrix of size d x m. Each column of
% w gives a set of weights. The output is of size m x n, where
% D(i, :) corresponds to the weights given in w(:, i).
%
% Created by Dahua Lin, on Aug 2, 2010
%
%% verify input
if ~(ndims(X1) == 2 && ndims(X2) == 2)
error('wL1dist:invalidarg', 'X1 and X2 should be both matrices.');
end
%% main
D = w.' * ((X1 - X2).^2);
| zzhangumd-smitoolbox | base/metrics/wsqL2dist.m | MATLAB | mit | 813 |
function V = pwnrmdot(X1, X2)
% Compute pairwise normalized dot products
%
% V = pwnrmdot(X1, X2);
% computes pairwise dot products between column vectors in X1 and X2.
%
% Normalized dot-product is defined as the dot-product between
% vectors after L2-normalization, as
%
% normalized dot-product(x, y) = x' * y / (||x|| * ||y||)
%
% Suppose X1 and X2 are respectively d x n1 and d x n2 matrices, then
% V will be a n1 x n2 matrix, with V(i, j) being the normalized dot
% product between X1(:, i) and X2(:, j).
%
% V = pwnrmdot(X);
% computes pairwise dot products between columns in X, which is
% functionally equivalent to pwnrmdot(X, X).
%
% However, it takes advantages of the fact that X1 = X2 = X to make
% slightly faster implementation.
%
% History
% - Created by Dahua Lin, on Jun 2, 2008
% - Modified by Dahua Lin, on Aug 2, 2010
% - simplify error handling
%
%% parse and verify input arguments
if nargin < 2
X2 = [];
end
if ~(ndims(X1) == 2 && isreal(X1))
error('pwnrmdot:invalidarg', 'X1 should be a real matrix.');
end
if ~isempty(X2) && ~(ndims(X2) == 2 && isreal(X2))
error('pwnrmdot:invalidarg', 'X2 should be either empty or a real matrix.');
end
%% main
if isempty(X2)
n = size(X1, 2);
V = X1' * X1;
s = V(1 + (n+1) *(0:n-1)); % take the diagonal elements
q = 1 ./ sqrt(s);
V = bsxfun(@times, V, q);
V = bsxfun(@times, V, q');
else
s1 = sum(X1 .* X1, 1);
s2 = sum(X2 .* X2, 1);
V = X1' * X2;
V = bsxfun(@times, V, 1 ./ sqrt(s1)');
V = bsxfun(@times, V, 1 ./ sqrt(s2));
end
V(V > 1) = 1;
V(V < -1) = -1;
| zzhangumd-smitoolbox | base/metrics/pwnrmdot.m | MATLAB | mit | 1,742 |
function v = Linfnorm(X, d)
%Compute L_infinity norm values of vectors
%
% v = Linfnorm(X);
% v = Linfnorm(X, d);
% compute the L_infinity norm values of the vectors contained in X
% along dimension d. If d is omitted, by default, it is set to 1.
%
% v = Linfnorm(X, []);
% compute the L_infinity norm of the entire array X.
%
% Created by Dahua Lin, on Aug 1, 2010
%
%% verify input
if nargin < 2
d = 1;
end
%% main
if ~isempty(d)
v = max(abs(X), [], d);
else
v = max(abs(X(:)));
end
| zzhangumd-smitoolbox | base/metrics/Linfnorm.m | MATLAB | mit | 527 |
function Y = L1normalize(X, d)
% Normalize vectors w.r.t. L1-norm
%
% Y = L1normalize(X);
% Y = L1normalize(X, d);
% normalize vectors in X along dimension d w.r.t. L1-norm. When d is
% omitted, by default, it is set to 1.
%
% Y = L1normalize(X, []);
% normalize X as a whole w.r.t. L1-norm.
%
% Created by Dahua Lin, on Aug 1, 2010
%
if nargin < 2
d = 1;
end
Y = bsxfun(@times, X, 1 ./ L1norm(X, d)); | zzhangumd-smitoolbox | base/metrics/L1normalize.m | MATLAB | mit | 432 |
function r = L2diff(A, B)
% Compute L2-norm of the difference between two arrays
%
% r = L2diff(A, B);
% computes the L2-norm (square root of sum of squared value) of the
% difference between A and B.
%
% History
% -------
% - Created by Dahua Lin, on Sep 12, 2010
%
%% main
D = A - B;
D = D(:);
r = sqrt(sum(D.^2));
| zzhangumd-smitoolbox | base/metrics/L2diff.m | MATLAB | mit | 367 |
function dists = mahdist(X1, X2, A)
%MAHDIST Computes the Mahalanobis distances
%
% dists = mahdist(X1, X2, A);
% computes the Mahalanobis distances between the corresponding
% columns in X1 and X2.
%
% Mahalanobis distances are defined as follows
%
% d(x, y) = sqrt((x - y)' * A * (x - y));
%
% In a d-dimensional space, both X1 and X2 should be d x n matrices,
% and A should be a d x d symmetric matrix.
%
% In the output, dists will be a 1 x n vector, with
%
% dists(i) = dist(X1(:,i), X2(:,i));
%
% dists = mahdist(X1, X2, A, 'square');
% computes the squares of the Mahalanobis distances, i.e. not
% taking the square root in the above formula.
%
% Remarks
% - The matrix A should be a positive definite matrix, the
% function in itself does not perform the checking for efficiency.
%
% History
% - Created by Dahua Lin, on Jun 2, 2008
% - Modified by Dahua Lin, on Jul 22, 2010
% - based on sqmahdist.m
%
dists = sqrt(sqmahdist(X1, X2, A));
| zzhangumd-smitoolbox | base/metrics/mahdist.m | MATLAB | mit | 1,074 |
function D = L1dist(X1, X2, d)
%Compute the L1-norm distances between corresponding vectors
%
% D = L1dist(X1, X2);
% D = L1dist(X1, X2, d);
% computes the L1-norm distances between corresponding vectors in
% X1 and X2 along dimension d.
%
% In the input X1 and X2 should be arrays of the same size.
%
% D = L1dist(X1, X2, []);
% computes the L1-norm distances between X1 and X2 as a whole.
%
% Created by Dahua Lin, on Aug 2, 2010
%
%% main
if nargin < 3
d = 1;
end
D = L1norm(X1 - X2, d);
| zzhangumd-smitoolbox | base/metrics/L1dist.m | MATLAB | mit | 533 |
function D = pwhamdist(X1, X2)
% Compute pairwise Hamming distances
%
% D = pwhamdist(X1, X2);
% compute pairwise Hamming distances between the column vectors in
% X1 and X2. The hamming distance is defined to be the number of
% different entries in two vectors.
%
% Let X1 and X2 be d x m and d x n numerical or logical matrices.
% Then in the output, D will be a matrix of size m x n, where
% D(i, j) is the hamming distance between X1(:,i) and X2(:,j).
%
% Note that this function supports the following value types:
% double, single, logical, int32, and uint32.
%
% Created by Dahua Lin, on Aug 2, 2010
%
%% verify input
if nargin < 2 || isempty(X2)
X2 = X1;
end
if ~((isnumeric(X1) || islogical(X1)) && ndims(X1) == 2 && ...
(isnumeric(X2) || islogical(X2)) && ndims(X2) == 2)
error('pwhamdist:invalidarg', ...
'X1 and X2 should be both numeric matrices');
end
if size(X1,1) ~= size(X2,1)
error('pwhamdist:invalidarg', ...
'X1 and X2 should have the same number of rows.');
end
%% main
n1 = size(X1, 2);
n2 = size(X2, 2);
D = zeros(n1, n2);
if n1 < n2
for i = 1 : n1
D(i, :) = sum(bsxfun(@ne, X2, X1(:,i)), 1) ;
end
else
for i = 1 : n2
D(:, i) = sum(bsxfun(@ne, X1, X2(:,i)), 1).';
end
end
| zzhangumd-smitoolbox | base/metrics/pwhamdist.m | MATLAB | mit | 1,334 |
function D = pwL1dist(X1, X2, w)
% Compute the pairwise L1-norm distances
%
% D = pwL1dist(X1, X2);
% computes the L1-norm distance between pairs of column vectors in
% X1 and X2.
%
% Suppose the vector dimension is d, then X1 and X2 should be
% matrices of size d x m and d x n. In this case, the output
% is a matrix of size m x n, where D(i, j) is the distance between
% X1(:,i) and X2(:,j).
%
% D = pwL1dist(X1, X2, w);
% computes the weighted L1-norm distance between column vectors
% in X1 and X2. The weighted L1-norm distance is defined by
%
% d = sum_i w(i) * |x1(i) - x2(i)|
%
% In the input, w should be a column vector.
%
% Created by Dahua Lin, on Aug 2, 2010
%
%% verify input
if nargin < 2 || isempty(X2)
X2 = X1;
end
if ~(isfloat(X1) && ndims(X1) == 2 && isfloat(X2) && ndims(X2) == 2)
error('pwL1dist:invalidarg', 'X1 and X2 should be both real matrices.');
end
if size(X1,1) ~= size(X2,1)
error('pwL1dist:invalidarg', 'X1 and X2 should have the same number of rows.');
end
if nargin >= 3
if ~(ndims(w) == 2 && size(w, 2) == 1 && isreal(w))
error('pwL1dist:invalidarg', 'w should be a real row vector.');
end
X1 = bsxfun(@times, X1, w);
X2 = bsxfun(@times, X2, w);
end
%% main
n1 = size(X1, 2);
n2 = size(X2, 2);
D = zeros(n1, n2);
if n1 < n2
for i = 1 : n1
D(i, :) = sum(abs(bsxfun(@minus, X2, X1(:,i))), 1) ;
end
else
for i = 1 : n2
D(:, i) = sum(abs(bsxfun(@minus, X1, X2(:,i))), 1).';
end
end
| zzhangumd-smitoolbox | base/metrics/pwL1dist.m | MATLAB | mit | 1,574 |
function D = sqL2dist(X1, X2, d)
%Compute the squared L2-norm distances between corresponding vectors
%
% D = L2dist(X1, X2);
% D = L2dist(X1, X2, d);
% computes the squared L2-norm distances between corresponding
% vectors in X1 and X2 along dimension d.
%
% In the input X1 and X2 should be arrays of the same size.
%
% D = L2dist(X1, X2, []);
% computes the squared L2-norm distances between X1 and X2 as a
% whole.
%
% Created by Dahua Lin, on Aug 2, 2010
%
%% main
if nargin < 3
d = 1;
end
D = sqL2norm(X1 - X2, d);
| zzhangumd-smitoolbox | base/metrics/sqL2dist.m | MATLAB | mit | 569 |
function s = sumsqdist(X, Y, W)
% Compute weighted sum of square distances
%
% s = sumsqdist(X, Y, W);
% computes the weighted sum of squared distance as follows:
%
% s = \sum_{i=1}^m \sum_{j=1}^n W(i,j) ||X(:,i) - Y(:,j)||^2.
%
% Here, X is a d x m matrix, Y is a d x n matrix, and
% W is an m x n matrix.
%
% s = sumsqdist(X, [], W);
% computes the weighted sum with X = Y and a symmetric matrix W.
% More efficient implementation will be used for this case.
%
% Created by Dahua Lin, on Apr 17, 2010
%
%% verify input arguments
if ~(isfloat(X) && isreal(X) && ndims(X) == 2)
error('sumsqdist:invalidarg', 'X should be a real matrix.');
end
if isempty(Y)
use_sym = true;
Y = X;
else
if ~(isfloat(Y) && isreal(Y) && ndims(Y) == 2)
error('sumsqdist:invalidarg', 'Y should be a real matrix.');
end
use_sym = false;
end
if size(X, 1) ~= size(Y, 1)
error('sumsqdist:invalidarg', ...
'x-vectors and y-vectors have different dimension.');
end
d = size(X, 1);
m = size(X, 2);
n = size(Y, 2);
if ~(isfloat(W) && isreal(W) && isequal(size(W), [m n]))
error('sumsqdist:invalidarg', 'W should be an m x n real matrix.');
end
%% main
if d == 1
sx = sum((X.^2) .* sum(W, 2).');
if use_sym
sy = sx;
else
sy = sum((Y.^2) .* sum(W, 1));
end
sxy = sum((X * W) .* Y);
else
sx = sum(sum(bsxfun(@times, X, sum(W, 2).') .* X, 1), 2);
if use_sym
sy = sx;
else
sy = sum(sum(bsxfun(@times, Y, sum(W, 1)) .* Y, 1), 2);
end
sxy = sum(sum((X * W) .* Y, 1), 2);
end
s = sx + sy - 2 * sxy;
| zzhangumd-smitoolbox | base/metrics/sumsqdist.m | MATLAB | mit | 1,656 |
function D = L2dist(X1, X2, d)
%Compute the L2-norm distances between corresponding vectors
%
% D = L2dist(X1, X2);
% D = L2dist(X1, X2, d);
% computes the L2-norm distances between corresponding vectors in
% X1 and X2 along dimension d.
%
% In the input X1 and X2 should be arrays of the same size.
%
% D = L2dist(X1, X2, []);
% computes the L2-norm distances between X1 and X2 as a whole.
%
% Created by Dahua Lin, on Aug 2, 2010
%
%% main
if nargin < 3
d = 1;
end
D = L2norm(X1 - X2, d);
| zzhangumd-smitoolbox | base/metrics/L2dist.m | MATLAB | mit | 532 |
function r = sqL2diff(A, B)
% Compute sqaured L2-norm of the difference between two arrays
%
% r = L2diff(A, B);
% computes the squared L2-norm (sum of squared value) of the
% difference between A and B.
%
% History
% -------
% - Created by Dahua Lin, on Sep 12, 2010
%
%% main
D = A - B;
D = D(:);
r = sum(D.^2);
| zzhangumd-smitoolbox | base/metrics/sqL2diff.m | MATLAB | mit | 364 |
function D = pwL2dist(X1, X2, w)
% Compute the pairwise L2-norm distances
%
% D = pwL2dist(X1, X2);
% computes the L2-norm distance between pairs of column vectors in
% X1 and X2.
%
% Suppose the vector dimension is d, then X1 and X2 should be
% matrices of size d x m and d x n. In this case, the output
% is a matrix of size m x n, where D(i, j) is the distance between
% X1(:,i) and X2(:,j).
%
% D = pwL2dist(X);
% D = pwL2dist(X, []);
% computes the L2-norm distance between pairs of column
% vectors in X. The implementation for this case is more efficient
% than pwsqL2dist(X, X), despite that both yield the same result.
%
% D = pwL2dist(X, [], w);
% D = pwL2dist(X1, X2, w);
% computes the weighted L2-norm distance between column vectors
% in X1 and X2. The weighted L2-norm distance is defined by
%
% d = sqrt(sum_i w(i) * |x1(i) - x2(i)|^2)
%
% In the input, w should be a row vector.
%
% Created by Dahua Lin, on Aug 2, 2010
%
%% main
if nargin < 2
X2 = [];
end
if nargin < 3
D = sqrt(pwsqL2dist(X1, X2));
else
D = sqrt(pwsqL2dist(X2, X2, w));
end
| zzhangumd-smitoolbox | base/metrics/pwL2dist.m | MATLAB | mit | 1,174 |
function dists = pwmetric(metricfun, X1, X2)
%PWMETRIC Computes the pairwise metric matrix based on a supplied metric
%function
%
% dists = pwmetric(metricfun, X1, X2);
% computes the pairwise metric matrix based on metricfun.
%
% The metricfun should be a function supporting the following syntax:
%
% v = metricfun(Y1, Y2);
%
% with Y1 and Y2 both being d x n matrices, v should be a 1 x n
% vector, with v(i) = d(Y1(:, i), Y2(:, i));
%
% This function uses metricfun to compute pairwise metrics, and
% outputs dists, which has
%
% dists(i, j) = d(X1(:, i), X2(:, i));
%
% Suppose X1 and X2 respectively have n1 and n2 columns, then
% dists is an n1 x n2 matrix.
%
% dists = pwmetric(metricfun, X);
% computes pairwise metrics between the columns in X, which is
% equivalent to pwmetric(metricfun, X, X);
%
% History
% - Created by Dahua Lin, on Jun 2, 2008
% - Modified by Dahua Lin, on Jun 3, 2008
% - automatic decide the class of output based on first batch
% of results.
%
%% parse and verify input arguments
if nargin < 3
X2 = X1;
end
assert(ndims(X1) == 2 && ndims(X2) == 2 && size(X1, 1) == size(X2, 1), ...
'pwmetric:invalidarg', ...
'X1 and X2 should be matrices with the same length along 1st dimension.');
%% main
n1 = size(X1, 2);
n2 = size(X2, 2);
if n1 < n2
y = X1(:, 1);
r1 = metricfun(y(:, ones(1, n2)), X2);
dists = zeros(n1, n2, class(r1));
dists(1, :) = r1;
for i = 2 : n1
y = X1(:, i);
dists(i, :) = metricfun(y(:, ones(1, n2)), X2);
end
else
y = X2(:, 1);
r1 = metricfun(X1, y(:, ones(1, n1)))';
dists = zeros(n1, n2, class(r1));
dists(:, 1) = r1;
for i = 2 : n2
y = X2(:, i);
dists(:, i) = metricfun(X1, y(:, ones(1, n1)))';
end
end
| zzhangumd-smitoolbox | base/metrics/pwmetric.m | MATLAB | mit | 1,936 |
function D = pwLinfdist(X1, X2)
% Compute the pairwise L_infinity norm distances
%
% D = pwLinfdist(X1, X2);
% computes the L_infinity norm distance between pairs of column
% vectors in X1 and X2.
%
% Suppose the vector dimension is d, then X1 and X2 should be
% matrices of size d x m and d x n. In this case, the output
% is a matrix of size m x n, where D(i, j) is the distance between
% X1(:,i) and X2(:,j).
%
% Created by Dahua Lin, on Aug 2, 2010
%
%% verify input
if ~(ndims(X1) == 2 && ndims(X2) == 2)
error('pwL1dist:invalidarg', 'X1 and X2 should be both matrices.');
end
%% main
D = pwLpdist(X1, X2, inf);
| zzhangumd-smitoolbox | base/metrics/pwLinfdist.m | MATLAB | mit | 673 |
function r = sum_xlogy(X, Y, dim)
% Compute the sum of the terms x * log(y) in a safe way
%
% r = sum_xlogy(X, Y);
%
% Here, X and Y should be matrices or vectors of the same type.
%
% If X and Y are both vectors, then r is a scalar.
% Otherwise, if they are m x n matrices, then the sum is taken
% along the first dimension, resuling in r of size 1 x n.
%
% Note that in this function, 0 * log(y) is zero for every y,
% in particular, 0 * log(0) is regarded as 0. This is very useful
% for computing information theoretical quantities.
%
% r = sum_xlogy(X, Y, dim);
%
% Perform the sum of x * log(y) along the specified dimension.
% Here, dim should be either 1 or 2.
%
% Note that the sizes of X and Y along the specified dimension
% should be the same. However, the following input is allowed:
% one is vector, while the other is a matrix.
%
% History
% -------
% - Created by Dahua Lin, on Mar 28, 2011
%
%% verify input arguments
if ~(isfloat(X) && ndims(X) == 2 && isfloat(Y) && ndims(Y) == 2)
error('sum_xlogy:invalidarg', 'X and Y should be numeric matrices.');
end
%% main
Y(X == 0) = 1;
if nargin < 3
r = sum(X .* log(Y));
else
r = sum(X .* log(Y), dim);
end
| zzhangumd-smitoolbox | base/metrics/sum_xlogy.m | MATLAB | mit | 1,278 |
function v = L1norm(X, d)
%Compute L1-norm values of vectors
%
% v = L1norm(X);
% v = L1norm(X, d);
% compute the L1-norm values of the vectors contained in X along
% dimension d. If d is omitted, by default, it is set to 1.
%
% v = L1norm(X, []);
% compute the L1-norm of the entire array X.
%
% Created by Dahua Lin, on Aug 1, 2010
%
%% verify input
if nargin < 2
d = 1;
end
%% main
if ~isempty(d)
v = sum(abs(X), d);
else
v = sum(abs(X(:)));
end
| zzhangumd-smitoolbox | base/metrics/L1norm.m | MATLAB | mit | 491 |
function D = pwsqmahdist(X1, X2, A)
% Computes pairwise squared Mahalanobis distances
%
% D = pwsqmahdist(X1, X2, A);
% computes pairwise squared Mahalanobis distances between the
% columns in X1 and X2.
%
% The squared Mahalanobis distances are defined as follows
%
% d(x, y) = (x - y)' * A * (x - y);
%
% In a d-dimensional space, both X1 and X2 should be respectively
% d x n1 and d x n2 matrices, and A should be a d x d symmetric
% positive definite matrix.
%
% In the output, dists will be a n1 x n2 matrix, with
%
% dists(i, j) = dist(X1(:,i), X2(:,j));
%
% X2 can be input as an empty matrix, which indicates X2 = X1.
%
% Created by Dahua Lin, on Aug 2, 2010
%
%% verify input
if ~(ndims(X1) == 2 && isreal(X1))
error('pwsqmahdist:invalidarg', 'X1 should be a real matrix.');
end
if ~isempty(X2) && ~(ndims(X1) == 2 && isreal(X2))
error('pwsqmahdist:invalidarg', 'X2 should be either empty or a real matrix.');
end
d = size(X1, 1);
if ~(ndims(A) == 2 && size(A, 1) == d && size(A, 2) == d)
error('pwsqmahdist:invalidarg', 'The size of A should be d x d.');
end
%% main
if isempty(X2)
AX2 = A * X1;
s1 = sum(X1 .* AX2, 1);
s2 = s1;
else
AX2 = A * X2;
s1 = sum(X1 .* (A * X1), 1);
s2 = sum(X2 .* AX2, 1);
end
D = (-2) * (X1' * AX2);
D = bsxfun(@plus, D, s1');
D = bsxfun(@plus, D, s2);
D(D < 0) = 0;
| zzhangumd-smitoolbox | base/metrics/pwsqmahdist.m | MATLAB | mit | 1,444 |
function Y = Lpnormalize(X, p, d)
% Normalize vectors w.r.t. Lp-norm
%
% Y = Lpnormalize(X, p);
% Y = Lpnormalize(X, p, d);
% normalize vectors in X along dimension d w.r.t. Lp-norm. When d is
% omitted, by default, it is set to 1.
%
% Y = Lpnormalize(X, p, []);
% normalize X as a whole w.r.t. Lp-norm.
%
% Created by Dahua Lin, on Aug 1, 2010
%
if nargin < 3
d = 1;
end
Y = bsxfun(@times, X, 1 ./ Lpnorm(X, p, d)); | zzhangumd-smitoolbox | base/metrics/Lpnormalize.m | MATLAB | mit | 447 |
function v = nrmdot(X1, X2)
%NRMDOT Computes the normalized dot-product between corresponding vectors
%
% v = nrmdot(X1, X2);
% computes the normalized dot-product between corresponding column
% vectors in X1 and X2.
%
% Normalized dot-product is defined as the dot-product between
% vectors after L2-normalization, as
%
% normalized dot-product(x, y) = x' * y / (||x|| * ||y||)
%
% X1 and X2 should be matrices of the same size. Let their size be
% d x n, then v will be a 1 x n vector with v(i) being the normalized
% dot product between X1(:, i), and X2(:, i);
%
% History
% - Created by Dahua Lin, on Jun 2, 2008
% - Modified by Dahua Lin, on Jul 22, 2010
% - simplify error handling
%
%% parse and verify input arguments
if ~(ndims(X1) == 2 && ndims(X2) == 2)
error('nrmdot:invalidarg', ...
'X1 and X2 should be both matrices.');
end
%% main
s1 = sum(X1 .* X1, 1);
s2 = sum(X2 .* X2, 1);
v = sum(X1 .* X2, 1) ./ sqrt(s1 .* s2);
| zzhangumd-smitoolbox | base/metrics/nrmdot.m | MATLAB | mit | 1,039 |
function D = pwmahdist(X1, X2, A)
%PWMAHDIST Computes the pairwise Mahalanobis distances
%
% D = pwmahdist(X1, X2, A);
% computes the pairwise Mahalanobis distances between the columns in
% X1 and X2.
%
% Mahalanobis distances are defined as follows
%
% d(x, y) = sqrt((x - y)' * A * (x - y));
%
% In a d-dimensional space, both X1 and X2 should be respectively
% d x n1 and d x n2 matrices, and A should be a d x d symmetric
% positive definite matrix.
%
% In the output, dists will be a n1 x n2 matrix, with
%
% dists(i, j) = dist(X1(:,i), X2(:,j));
%
% X2 can be input as an empty matrix, which indicates X2 = X1.
%
% History
% - Created by Dahua Lin, on Jun 2, 2008
% - Modified by Dahua Lin, on Aug 2, 2008
% - based on pwsqmahdist
%
%% main
D = sqrt(pwsqmahdist(X1, X2, A));
| zzhangumd-smitoolbox | base/metrics/pwmahdist.m | MATLAB | mit | 895 |
function Y = L2normalize(X, d)
% Normalize vectors w.r.t. L2-norm
%
% Y = L2normalize(X);
% Y = L2normalize(X, d);
% normalize vectors in X along dimension d w.r.t. L2-norm. When d is
% omitted, by default, it is set to 1.
%
% Y = L2normalize(X, []);
% normalize X as a whole w.r.t. L2-norm.
%
% Created by Dahua Lin, on Aug 1, 2010
%
if nargin < 2
d = 1;
end
Y = bsxfun(@times, X, 1 ./ L2norm(X, d)); | zzhangumd-smitoolbox | base/metrics/L2normalize.m | MATLAB | mit | 432 |
function D = wL1dist(X1, X2, w)
% Compute weighted L1-norm distances between corresponding vectors
%
% D = wL1dist(X1, X2, w);
% computes weighted L1-norm distances between the corresponding
% column vectors in X1 and X2, defined by
%
% d = sum_i w(i) * |x1(i) - x2(i)|
%
% X1 and X2 should be matrices of the same size. Suppose their size
% is d x n, then w should be a matrix of size d x m. Each column of
% w gives a set of weights. The output is of size m x n, where
% D(i, :) corresponds to the weights given in w(:, i).
%
% Created by Dahua Lin, on Aug 2, 2010
%
%% verify input
if ~(ndims(X1) == 2 && ndims(X2) == 2)
error('wL1dist:invalidarg', 'X1 and X2 should be both matrices.');
end
%% main
D = w.' * abs(X1 - X2);
| zzhangumd-smitoolbox | base/metrics/wL1dist.m | MATLAB | mit | 789 |
function dists = sqmahdist(X1, X2, A)
%MAHDIST Computes the squared Mahalanobis distances
%
% dists = sqmahdist(X1, X2, A);
% computes the squared Mahalanobis distances between corresponding
% columns in X1 and X2.
%
% Squared Mahalanobis distances are defined as follows
%
% d(x, y) = (x - y)' * A * (x - y);
%
% In a d-dimensional space, both X1 and X2 should be d x n matrices,
% and A should be a d x d symmetric matrix.
%
% In the output, dists will be a 1 x n vector, with
%
% dists(i) = d(X1(:,i), X2(:,i));
%
% Remarks
% - The matrix A should be a positive definite matrix, the
% function in itself does not perform the checking for efficiency.
%
% History
% - Created by Dahua Lin, on Jun 2, 2008
% - Modified by Dahua Lin, on Jul 22, 2010
% - based on sqmahdist.m
%
%% verify input arguments
if ~(ndims(X1) == 2 && isreal(X1) && ndims(X2) == 2 && isreal(X2))
error('sqmahdist:invalidarg', ...
'X1 and X2 should be real matrices.');
end
%% main
D = X1 - X2;
dists = sum(D .* (A * D), 1);
| zzhangumd-smitoolbox | base/metrics/sqmahdist.m | MATLAB | mit | 1,124 |
function dists = pwraddiff(X1, X2)
%Compute the pairwise radian differences
%
% dists = pwraddiff(X);
% dists = pwraddiff(X1, X2);
% computes the pairwise radian differences between column vectors in
% X1 and X2.
%
% The radian difference is the angle between two vectors in unit of
% radian. In mathematics, it can be defined as arccos of normalized
% correlation, which ranges from 0 (when correlation is 1) to pi
% (when correlation is -1). If the radian difference between two
% vectors is pi / 2, they are orthogonal to each other.
%
% Suppose X1 and X2 are respectively d x n1 and d x n2 matrices,
% then dists will be an n1 x n2 matrix with dists(i, j) being the
% radian difference between the two vectors X1(:, i) and X2(:, j).
%
% History
% - Created by Dahua Lin, on Jun 3, 2008
%
%% main
if nargin < 2
X2 = [];
end
dists = acos(pwnrmdot(X1, X2));
| zzhangumd-smitoolbox | base/metrics/pwraddiff.m | MATLAB | mit | 942 |
function D = pwLpdist(X1, X2, p)
% Compute the pairwise Lp-norm distances
%
% D = pwLpdist(X1, X2, p);
% computes the Lp-norm distance between pairs of column vectors in
% X1 and X2.
%
% Suppose the vector dimension is d, then X1 and X2 should be
% matrices of size d x m and d x n. In this case, the output
% is a matrix of size m x n, where D(i, j) is the distance between
% X1(:,i) and X2(:,j).
%
% - Created by Dahua Lin, on Aug 2, 2010
% - Modified by Dahua Lin, on Aug 10, 2011
% - use pure matlab implementation
%
%% verify input
if nargin < 2 || isempty(X2)
X2 = X1;
end
if ~(isfloat(X1) && ndims(X1) == 2 && isfloat(X2) && ndims(X2) == 2)
error('pwLpdist:invalidarg', 'X1 and X2 should be both real matrices.');
end
if size(X1,1) ~= size(X2,1)
error('pwLpdist:invalidarg', 'X1 and X2 should have the same number of rows.');
end
%% main
if p == 1
D = pwL2dist(X1, X2);
elseif p == 2
D = pwL2dist(X1, X2);
elseif p == inf
D = pwLinfdist(X1, X2);
else
n1 = size(X1, 2);
n2 = size(X2, 2);
D = zeros(n1, n2);
if n1 < n2
for i = 1 : n1
D(i, :) = sum(abs(bsxfun(@minus, X2, X1(:,i))) .^ p, 1) .^ (1/p);
end
else
for i = 1 : n2
D(:, i) = sum(abs(bsxfun(@minus, X1, X2(:,i))) .^ p, 1).' .^ (1/p);
end
end
end
| zzhangumd-smitoolbox | base/metrics/pwLpdist.m | MATLAB | mit | 1,398 |
function M = wmedian(X, w)
% Compute the weighted median
%
% M = wmedian(X, w);
% computes the weighted median of X (along the first non-singleton
% dimension of w).
%
% Let X be an m x n matrix, and w can be either an m x 1 or 1 x n
% vector. In the former case, it computes the weighted median along
% the first dimension, and in the latter case, it computes the
% weighted median along the second dimension.
%
% History
% -------
% - Created by Dahua Lin, on Sep 28, 2010
%
%% verify input
if ~(isfloat(X) && ndims(X) == 2 && isreal(X) && ~issparse(X))
error('wmedian:invalidarg', 'X should be a non-sparse real matrix.');
end
if ~(isfloat(w) && isvector(w) && isreal(w) && ~issparse(w))
error('wmedian:invalidarg', 'w should be a non-sparse real vector.');
end
[m, n] = size(X);
if size(w,1) == m && size(w,2) == 1
dim = 1;
elseif size(w,1) == 1 && size(w,2) == n
dim = 2;
else
error('wmedian:invalidarg', 'The size of w is inconsistent with X.');
end
if ~isa(w, class(X))
w = cast(w, class(X));
end
%% main
if dim == 2
X = X.';
w = w.';
end
[sX, si] = sort(X, 1);
F = cumsum(w(si), 1);
M = wmedian_cimp(sX, F);
if dim == 2
M = M.';
end
| zzhangumd-smitoolbox | base/data/wmedian.m | MATLAB | mit | 1,252 |
function [H, N0] = hist2d(x, y, xb, yb)
% Compute histogram of 2D data
%
% [H, N0] = hist2d(x, y, xb, yb);
% computes the histogram of the 2D data given by x and y, which
% are vectors of the same size.
%
% The histogram bins are divided according to the xb and yb.
% Suppose xb and yb respectively have (n+1) and (m+1) values,
% then it divides the 2D region into n columns and m rows.
%
% In the output, H is a matrix of size m x n, and H(i, j) is
% the number of points in the bin at i-th row and j-th column.
%
% N0 is the number of points falling out of the region.
%
% H = hist2d(x, y, n, m);
% This statement is equivalent to
%
% hist2d(x, y, linspace(min(x), max(x), n+1),
% linspace(min(y), max(y), m+1));
%
% Created by Dahua Lin, on Nov 19, 2010
%
%% verify input
if ~(isfloat(x) && isvector(x) && isreal(x) && ~issparse(x))
error('hist2d:invalidarg', 'x should be a non-sparse real vector.');
end
if ~(isfloat(y) && isvector(y) && isreal(y) && ~issparse(y))
error('hist2d:invalidarg', 'x should be a non-sparse real vector.');
end
if ~isequal(size(x), size(y))
error('hist2d:invalidarg', 'x and y should have the same size.');
end
if ~(isfloat(xb) && isvector(xb))
error('hist2d:invalidarg', 'xb should be a numeric vector.');
end
if ~(isfloat(yb) && isvector(yb))
error('hist2d:invalidarg', 'xb should be a numeric scalar or vector.');
end
if isscalar(xb)
xb = linspace(min(x), max(x), xb+1);
yb = linspace(min(y), max(y), yb+1);
end
n = numel(xb) - 1;
m = numel(yb) - 1;
%% main
ix = pieces(x, xb);
iy = pieces(y, yb);
sr = ix >= 1 & ix <= n & iy >= 1 & iy <= m;
ix = ix(sr);
iy = iy(sr);
i = sub2ind([m n], iy, ix);
H = intcount(m*n, i);
H = reshape(H, [m, n]);
N0 = numel(x) - numel(ix);
| zzhangumd-smitoolbox | base/data/hist2d.m | MATLAB | mit | 1,834 |
/********************************************************************
*
* merge_sorted.cpp
*
* The C++ mex implementation of merge_sorted
*
* Created by Dahua Lin, on Mar 28, 2011
*
********************************************************************/
#include <bcslib/matlab/bcs_mex.h>
using namespace bcs;
using namespace bcs::matlab;
template<typename T>
marray do_merge_1(const mxArray *srcs[], int dim)
{
const_marray mS(srcs[0]);
return duplicate(mS);
}
template<typename T>
marray do_merge_2(const mxArray *srcs[], int dim)
{
const_marray mS1(srcs[0]);
const_marray mS2(srcs[1]);
const T *v1 = mS1.data<T>();
const T *v2 = mS2.data<T>();
size_t n1 = mS1.nelems();
size_t n2 = mS2.nelems();
marray mC = dim == 1 ?
create_marray<T>(n1+n2, 1) :
create_marray<T>(1, n1+n2);
T *c = mC.data<T>();
size_t i1 = 0;
size_t i2 = 0;
while (i1 < n1 && i2 < n2)
{
if (v1[i1] <= v2[i2])
{
*c++ = v1[i1++];
}
else
{
*c++ = v2[i2++];
}
}
while (i1 < n1)
{
*c++ = v1[i1++];
}
while (i2 < n2)
{
*c++ = v2[i2++];
}
return mC;
}
template<typename T>
marray do_merge_multi(int K, const mxArray *srcs[], int dim)
{
// extract input
const T** ptrs = new const T*[K];
size_t *ns = new size_t[K];
int *ps = new int[K];
size_t N = 0;
for (int k = 0; k < K; ++k)
{
const_marray mS(srcs[k]);
ptrs[k] = mS.data<T>();
ns[k] = mS.nelems();
ps[k] = 0;
N += ns[k];
}
// prepare output
marray mC = dim == 1 ?
create_marray<T>(N, 1) :
create_marray<T>(1, N);
T *c = mC.data<T>();
// main loop
for (size_t i = 0; i < N; ++i)
{
int sk = -1;
T cv = 0;
for (int k = 0; k < K; ++k)
{
if (ps[k] < (int)ns[k])
{
if (sk < 0 || ptrs[k][ps[k]] < cv)
{
sk = k;
cv = ptrs[k][ps[k]];
}
}
}
*(c++) = cv;
++ ps[sk];
}
// release
delete[] ptrs;
delete[] ns;
delete[] ps;
return mC;
}
template<typename T>
marray do_merge_sorted(int K, const mxArray *srcs[], int dim)
{
if (K == 1)
{
return do_merge_1<T>(srcs, dim);
}
else if (K == 2)
{
return do_merge_2<T>(srcs, dim);
}
else
{
return do_merge_multi<T>(K, srcs, dim);
}
}
/**
* main entry:
*
* Input: sorted vectors
*
* Output: combined vectors
*/
void bcsmex_main(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
marray mR;
if (nrhs > 0)
{
int K = nrhs;
int dim = 0;
// check inputs and determine dim
mxClassID cid = (mxClassID)(0);
for (int k = 0; k < K; ++k)
{
const_marray mS(prhs[k]);
if (!( mS.is_vector() && mS.is_numeric() && !mS.is_sparse() ))
{
throw mexception("merge_sorted:invalidarg",
"each input should be a numeric vector.");
}
if (k == 0)
{
cid = mS.class_id();
}
else
{
if (mS.class_id() != cid)
{
throw mexception("merge_sorted:invalidarg",
"The types of input vectors are inconsistent.");
}
}
if (dim == 0)
{
if (mS.nrows() > 1)
{
dim = 1;
}
else if (mS.ncolumns() > 1)
{
dim = 2;
}
}
}
if (dim == 0) dim = 2; // by default
// main delegate
switch (cid)
{
case mxDOUBLE_CLASS:
mR = do_merge_sorted<double>(K, prhs, dim);
break;
case mxSINGLE_CLASS:
mR = do_merge_sorted<float>(K, prhs, dim);
break;
case mxINT32_CLASS:
mR = do_merge_sorted<int32_t>(K, prhs, dim);
break;
case mxUINT32_CLASS:
mR = do_merge_sorted<uint32_t>(K, prhs, dim);
break;
case mxINT16_CLASS:
mR = do_merge_sorted<int16_t>(K, prhs, dim);
break;
case mxUINT16_CLASS:
mR = do_merge_sorted<uint16_t>(K, prhs, dim);
break;
case mxINT8_CLASS:
mR = do_merge_sorted<int8_t>(K, prhs, dim);
break;
case mxUINT8_CLASS:
mR = do_merge_sorted<uint8_t>(K, prhs, dim);
break;
default:
throw mexception("merge_sorted:invalidarg",
"Unsupported numeric class encountered.");
}
}
else
{
mR = create_marray<double>((size_t)0, (size_t)0);
}
plhs[0] = mR.mx_ptr();
}
BCSMEX_MAINDEF
| zzhangumd-smitoolbox | base/data/merge_sorted.cpp | C++ | mit | 5,739 |
function y = pieces(x, edges, dir, alg)
% PIECES Locates the piece that the input values are in
%
% y = pieces(x, edges);
% y = pieces(x, edges, 'L');
% y = pieces(x, edges, 'R');
%
% determines which bins each value of x is in. Particularly,
% let edges be a vector of length m+1 as [e_0, ..., e_m].
% These edges divide the real line into m+2 bins.
%
% If the third argument is 'L' (or omitted), the bins are
% left-closed, as given by
% (-inf, e_0), [e_0, e_1), ..., [e_{m-1}, e_m), [e_m, inf).
%
% If the third argument is 'R', the bins are right-closed, as
% given by
% (-inf, e_0], (e_0, e_1], ..., (e_{m-1}, e_m], (e_m, inf).
%
% The indices of these bins are 0, 1, ..., m+1. If x(i) falls in
% the bin whose index is k, then y(i) is k.
%
% x should be a matrix of class double, or single, then y will be
% a matrix of the same size of class double.
%
%
% y = pieces(x, edges, dir, alg);
% further specifies which algorithm the function should use.
%
% The value of alg can be either if the following:
% - 'std': the standard implementation. The complexity is
% O(m n), where m is the number of bins and n the
% number of values in x.
% - 'sorted': the implementation specially for the case when
% x is sorted. This should be used only when x is
% really sorted. The complexity is O(m + n).
% - 'auto': it automatically chooses the algorithm.
% In particular,
% if m > 2 * log(n), then it first sort x and then
% use the method designed for sorted values;
% otherwise, it uses the standard implementation.
%
% If alg is not specified, it uses the default 'auto'.
%
% History
% -------
% - Created by Dahua Lin, on June 8, 2010
%
%% verify input
if ~(ndims(x) == 2 && isfloat(x) && ~issparse(x) && isreal(x))
error('pieces:invalidarg', 'x should be a non-sparse real matrix.');
end
if ~(isvector(edges) && isa(edges, class(edges)) && ~issparse(edges))
error('pieces:invalidarg', 'edges should be a vector of the same class as x.');
end
if nargin < 3
is_left = true;
else
if strcmp(dir, 'L')
is_left = true;
elseif strcmp(dir, 'R')
is_left = false;
else
error('pieces:invalidarg', ...
'dir should be a char with value ''L'' or ''R''.');
end
end
if nargin < 4
alg = 'auto';
else
if ~ischar(alg)
error('pieces:invalidarg', ...
'alg should be a string giving the algorithm name.');
end
end
%% main
switch alg
case 'std'
y = pieces_cimp(x, edges, is_left, false);
case 'sorted'
y = pieces_cimp(x, edges, is_left, true);
case 'auto'
if numel(edges) > 2 * log(numel(x))
[sx, si] = sort(x);
sy = pieces_cimp(sx, edges, is_left, true);
y = zeros(size(sy));
y(si) = sy;
else
y = pieces_cimp(x, edges, is_left, false);
end
end
| zzhangumd-smitoolbox | base/data/pieces.m | MATLAB | mit | 3,212 |
function R = coaggreg(fun, X, siz, varargin)
% Perform aggregation with multiple indices
%
% R = coaggreg(fun, X, [K1, K2, ...], I1, I2, ...);
% performs the aggregation specified by fun on data X with multiple
% indices I1, I2, ...
%
% Here, fun can be either of the following strings:
% 'sum', 'min', 'max', 'mean', 'var', 'std'.
%
% In the input, I1, I2, ... should have the same size of X.
%
% The returned array R will be an array of size K1 x K2 x ...
% Concretely, R(k1, k2, ...) corresponds to the aggregation of
% the values in X(I1==k1 & I2 == k2 & ...)
%
% If siz is a scalar K, then R will be a column vector of size
% K x 1.
%
% History
% -------
% - Created by Dahua Lin, on Nov 11, 2010
%
%% prepare
if ~(isnumeric(siz) && ndims(siz) == 2 && size(siz,1) == 1)
error('coaggreg:invalidarg', ...
'The 3rd argument siz should be a numeric row vector.');
end
d = numel(siz);
if numel(varargin) ~= d
error('coaggreg:invalidarg', ...
'The number of index arrays is invalid.');
end
I = sub2ind(siz, varargin{:});
if ~isequal(size(I), size(X))
error('coaggreg:invalidarg', ...
'The size of the indices arrays is invalid.');
end
%% main
if size(X, 1) ~= numel(X)
X = X(:);
I = I(:);
end
K = prod(siz);
R = aggreg(X, K, I, fun);
if d > 1
R = reshape(R, siz);
end
| zzhangumd-smitoolbox | base/data/coaggreg.m | MATLAB | mit | 1,399 |
function G = cogroup(siz, varargin)
% Groups the indices for different integer combinations
%
% G = cogroup(m, vs);
% returns a cell vector of size m x 1, where G{k} is a vector of
% indices, such that all(vs(G{k}) == k).
%
% C = cogroup([m, n], vs1, vs2);
% returns a matrix of size m x n, where all(vs1(G{i,j}) == i) and
% all(vs2(G{i,j}) == j).
%
% C = cogroup([n1, n2, n3, ...], vs1, vs2, vs3, ...);
% returns an array C of size n1 x n2 x n3 x ... in a similar manner.
%
% History
% -------
% - Created by Dahua Lin, on Nov 10, 2010
%
%% verify input arguments
if ~(isnumeric(siz) && ndims(siz) == 2 && size(siz,1) == 1)
error('cogroup:invalidarg', 'siz should be a row vector.');
end
d = numel(siz);
if numel(varargin) ~= d
error('cogroup:invalidarg', 'The number of value vectors is invalid.');
end
%% main
if d == 1
vs = varargin{1};
else
vs = sub2ind(siz, varargin{:});
end
N = prod(siz);
G = intgroup(N, vs);
if d == 1
G = G(:);
else
G = reshape(G, siz);
end
| zzhangumd-smitoolbox | base/data/cogroup.m | MATLAB | mit | 1,053 |
function [u, varargout] = uniqvalues(x, tags)
% Get a list of sorted values with no repetition
%
% u = uniqvalues(x);
% returns a row vector v that contains all values in array x with
% no repetition.
%
% [u, I] = uniqvalues(x, 'I');
% additionally returns an integer map, such that x(i) == u(I(i)).
%
% [u, G] = uniqvalues(x, 'G');
% additionally returns a cell array of grouped indices, such that
% all(x(G{k}) == u(k)).
%
% [u, C] = uniqvalues(x, 'C');
% additionally returns the counts of all distinct values.
%
% [u, ...] = uniqvalues(x, tags);
% returns additional information according to tags.
%
% For example, one can write the following to have the function
% return both the grouped indices and the counts.
%
% [u, G, C] = uniqvalues(x, 'GC');
%
%
% Remarks
% -------
% - It is similar to the builtin unique function.
% However, it is implemented with C++ mex, and specifically
% designed for numeric arrays. Hence, it is much more efficient.
%
% History
% -------
% - Created by Dahua Lin, on June 6, 2010
% - Modified by Dahua Lin, on Nov 11, 2010
% - supports multiple outputs
%
%% verify input
if ~isnumeric(x) || issparse(x)
error('uniqvalues:invalidarg', ...
'x should be a non-sparse numeric array.');
end
xsiz = size(x);
if ~(ndims(x) == 2 && xsiz(1) == 1)
x = reshape(x, 1, numel(x));
end
use_I = 0;
use_C = 0;
use_G = 0;
if nargin >= 2 && ~isempty(tags)
if ~ischar(tags)
error('uniqvalues:invalidarg', 'the tags should be a char array.');
end
if any(tags == 'C')
use_C = 1;
end
if any(tags == 'I')
use_C = 1;
use_I = 1;
end
if any(tags == 'G')
use_G = 1;
end
else
tags = [];
end
%% main
% extract unique values
if use_I || use_G
[sx, si] = sort(x);
else
sx = sort(x);
end
p = valueseg(sx);
u = sx(p);
% additional output
if use_C
C = [p(2:end), numel(x)+1] - p;
end
if use_I
I = zeros(xsiz);
I(si) = repnum(C);
end
if use_G
K = numel(p);
ep = [p(2:end)-1, numel(x)];
G = cell(1, K);
for k = 1 : K
G{k} = si(p(k):ep(k));
end
end
if ~isempty(tags)
nt = numel(tags);
varargout = cell(1, nt);
for i = 1 : numel(tags)
t = tags(i);
if t == 'C'
varargout{i} = C;
elseif t == 'I'
varargout{i} = I;
elseif t == 'G'
varargout{i} = G;
else
error('uniqvalues:invalidarg', ...
'Invalid output tag symbol.');
end
end
end
| zzhangumd-smitoolbox | base/data/uniqvalues.m | MATLAB | mit | 2,721 |
function C = cocounts(siz, varargin)
% Counts the numbers of different integer combinations
%
% C = cocounts(m, vs);
% returns a vector of size m x 1, where C(k) being the number of
% occurrences of k in vs.
%
% C = cocounts([m, n], vs1, vs2);
% returns a matrix of size m x n, where
% C(i, j) = sum(vs1 == i & vs2 == j), which counts the occurrences
% of the case where the value in vs1 is i and the corresponding
% value in vs2 is j.
%
% C = cocounts([n1, n2, n3, ...], vs1, vs2, vs3, ...);
% returns an array C of size n1 x n2 x n3 x ... in a similar manner.
%
% History
% -------
% - Created by Dahua Lin, on Nov 10, 2010
%
%% verify input arguments
if ~(isnumeric(siz) && ndims(siz) == 2 && size(siz,1) == 1)
error('cocounts:invalidarg', 'siz should be a row vector.');
end
d = numel(siz);
if numel(varargin) ~= d
error('cocounts:invalidarg', 'The number of value vectors is invalid.');
end
%% main
if d == 1
vs = varargin{1};
else
vs = sub2ind(siz, varargin{:});
end
N = prod(siz);
C = intcount(N, vs);
if d == 1
C = C(:);
else
C = reshape(C, siz);
end
| zzhangumd-smitoolbox | base/data/cocounts.m | MATLAB | mit | 1,158 |
/********************************************************************
*
* valueseg_cimp.cpp
*
* The C++ mex implementation of valueseg
*
* Created by Dahua Lin, on May 26, 2010
*
********************************************************************/
#include <bcslib/matlab/bcs_mex.h>
#include <vector>
using namespace bcs;
using namespace bcs::matlab;
template<typename T>
void find_seg(size_t n, const T *v, std::vector<int>& offsets)
{
offsets.push_back(0);
for (size_t i = 1; i < n; ++i)
{
if (v[i] != v[i-1]) offsets.push_back(i);
}
}
void do_make_segs(int n, const std::vector<int>& offsets, bool make_row,
marray& mSp, marray& mEp)
{
int m = (int)offsets.size() - 1;
mSp = make_row ? create_marray<double>(1, m+1) : create_marray<double>(m+1, 1);
mEp = make_row ? create_marray<double>(1, m+1) : create_marray<double>(m+1, 1);
double *sp = mSp.data<double>();
double *ep = mEp.data<double>();
for (int i = 0; i < m; ++i)
{
sp[i] = offsets[i] + 1;
ep[i] = offsets[i + 1];
}
sp[m] = offsets[m] + 1;
ep[m] = n;
}
/***********
*
* Main entry:
*
* Input:
* [0]: v: the value vector to segment (numeric or logical or char)
* Output:
* [0]: sp: the starting positions
* [1]: ep: the ending positions
*
*/
void bcsmex_main(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
// take input
const_marray mV(prhs[0]);
if (!(mV.is_vector() && !mV.is_sparse() && !mV.is_empty()))
{
throw mexception("valueseg:invalidarg",
"x should be a full non-empty vector.");
}
size_t n = mV.nelems();
bool make_row = mV.nrows() == 1;
// delegate by type
mxClassID cid = mV.class_id();
std::vector<int> offsets;
switch (cid)
{
case mxDOUBLE_CLASS:
find_seg(n, mV.data<double>(), offsets);
break;
case mxSINGLE_CLASS:
find_seg(n, mV.data<float>(), offsets);
break;
case mxINT32_CLASS:
find_seg(n, mV.data<int32_t>(), offsets);
break;
case mxCHAR_CLASS:
find_seg(n, mV.data<char>(), offsets);
break;
case mxUINT8_CLASS:
find_seg(n, mV.data<uint8_t>(), offsets);
break;
case mxUINT32_CLASS:
find_seg(n, mV.data<uint32_t>(), offsets);
break;
case mxLOGICAL_CLASS:
find_seg(n, mV.data<bool>(), offsets);
break;
case mxINT8_CLASS:
find_seg(n, mV.data<int8_t>(), offsets);
break;
case mxINT16_CLASS:
find_seg(n, mV.data<int16_t>(), offsets);
break;
case mxUINT16_CLASS:
find_seg(n, mV.data<uint16_t>(), offsets);
break;
default:
throw mexception("valueseg:invalidarg",
"valueseg only supports numeric, char, or logical types.");
}
marray mSp, mEp;
do_make_segs(n, offsets, make_row, mSp, mEp);
// output
plhs[0] = mSp.mx_ptr();
plhs[1] = mEp.mx_ptr();
}
BCSMEX_MAINDEF
| zzhangumd-smitoolbox | base/data/valueseg.cpp | C++ | mit | 3,267 |
function r = fast_median(X, dim)
% Find the median value using O(n) algorithm
%
% r = fast_median(X);
% If X is a vector, it returns the median of X.
% If X is a matrix of size m x n where m > 1 and n > 1, then
% it returns a row vector r, such that r(j) is the median value
% for X(:, j).
%
% r = fast_median(X, dim);
% compute the median values along the dimension specified by dim.
%
% Remarks
% -------
% - Note the current version only supports the case where X is
% a matrix.
%
% - The implementation is based on an O(n) selection algorithm
% in C++ STL (std::nth_element).
%
% History
% -------
% - Created by Dahua Lin, on Nov 11, 2010
% - Modified by Dahua Lin, on Mar 28, 2010
%
%% verify input arguments
if ~(isfloat(X) && ~issparse(X) && isreal(X))
error('fast_median:invalidarg', 'X should be a non-sparse real array.');
end
if nargin < 2
dim = 0;
else
if ~(isnumeric(dim) && isscalar(dim) && (dim == 1 || dim == 2))
error('fast_median:invalidarg', 'dim should be either 1 or 2');
end
dim = double(dim);
end
%% main
if ~isempty(X)
if dim == 0
if isvector(X)
r = fast_median_cimp(X, 0);
else
r = fast_median_cimp(X, 1);
end
elseif dim == 1
if size(X,1) == 1
r = X;
elseif size(X,2) == 1
r = fast_median_cimp(X, 0);
else
r = fast_median_cimp(X, 1);
end
else % dim == 2
if size(X,2) == 1
r = X;
elseif size(X,1) == 1
r = fast_median_cimp(X, 0);
else
r = fast_median_cimp(X.', 1).';
end
end
else
% let median itself to deal with empty cases for conformant behavior
if nargin == 1
r = median(X);
else
r = median(X, dim);
end
end
| zzhangumd-smitoolbox | base/data/fast_median.m | MATLAB | mit | 1,960 |
/********************************************************************
*
* intgroup.cpp
*
* The C++ mex implementation of intgroup
*
* Created by Dahua Lin, on June 6, 2010
*
********************************************************************/
#include <bcslib/matlab/bcs_mex.h>
#include <vector>
#include <utility>
using namespace bcs;
using namespace bcs::matlab;
template<typename T>
inline void get_vs(const_marray mRgn, int& v0, int& v1)
{
size_t ne = mRgn.nelems();
const T *v = mRgn.data<T>();
if (ne == 1)
{
v0 = 1;
v1 = (int)(*v);
}
else
{
v0 = (int)(v[0]);
v1 = (int)(v[1]);
}
}
inline void get_range(const_marray mRgn, int& v0, int& v1)
{
size_t ne = mRgn.nelems();
if (!( (ne == 1 || ne == 2) && !mRgn.is_sparse() ) )
{
throw mexception("intgroup:invalidarg",
"The range [v0 v1] should be a (non-sparse) scalar or pair.");
}
if (mRgn.is_double())
{
get_vs<double>(mRgn, v0, v1);
}
else if (mRgn.is_single())
{
get_vs<float>(mRgn, v0, v1);
}
else if (mRgn.is_int32())
{
get_vs<int32_t>(mRgn, v0, v1);
}
else
{
throw mexception("intgroup:invalidarg",
"The range [v0 v1] should be of class double, single, or int32");
}
}
template<typename T>
void group(int v0, int v1, const T *v, size_t n, std::vector<double>* gs)
{
for (size_t i = 0; i < n; ++i)
{
int cv = (int)(v[i]);
if (cv >= v0 && cv <= v1)
{
gs[cv - v0].push_back(i + 1);
}
}
}
inline void do_group(int v0, int v1, const_marray mVals, std::vector<double>* gs)
{
size_t n = mVals.nelems();
if (mVals.is_double())
{
group(v0, v1, mVals.data<double>(), n, gs);
}
else if (mVals.is_single())
{
group(v0, v1, mVals.data<float>(), n, gs);
}
else if (mVals.is_int32())
{
group(v0, v1, mVals.data<int32_t>(), n, gs);
}
else
{
mexErrMsgIdAndTxt("intgroup:invalidarg",
"The class of values should be either double, single, int32");
}
}
marray groups_to_cells(size_t ng, const std::vector<double>* gs)
{
marray mC = create_mcell_array(1, ng);
for (int i = 0; i < (int)ng; ++i)
{
mC.set_cell(i, to_matlab_row(gs[i]));
}
return mC;
}
/**
* Main entry:
*
* Input:
* [0]: rgn: the integer range in form of [v0, v1] (pair)
* [1]: V: the values array (double|single|int32)
* Output:
* [0]: G: the cell array of indices for each value
*
*/
void bcsmex_main(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
if (nrhs != 2)
{
throw mexception("intgroup:invalidarg",
"The number of inputs to intgroup should be 2.");
}
const_marray mRgn(prhs[0]);
const_marray mVals(prhs[1]);
int v0, v1;
get_range(mRgn, v0, v1);
size_t ng = v1 - v0 + 1;
std::vector<double> *vecs = new std::vector<double>[ng];
do_group(v0, v1, mVals, vecs);
plhs[0] = groups_to_cells(ng, vecs).mx_ptr();
delete[] vecs;
}
BCSMEX_MAINDEF
| zzhangumd-smitoolbox | base/data/intgroup.cpp | C++ | mit | 3,244 |
% Find the set of indices of the occurrences of integers in a given range
%
% G = intgroup([v0, v1], V);
% finds the set of indices of occurrences of integers in range
% [v0, v1] in the array V.
%
% In the input, V is a numeric array containing integers (whose
% value class can be either double, single, or int32).
% In the output, G is a cell array of size 1 x (v1 - v0 + 1),
% where G{i} is the indices of entries in V whose values equal
% v0 + i - 1.
%
% G = intgroup(K, V);
% This is equivalent to intgroup([1, K], V);
%
% History
% -------
% - Created by Dahua Lin, on June 6, 2010
%
| zzhangumd-smitoolbox | base/data/intgroup.m | MATLAB | mit | 656 |
function c = intcount(rgn, V, dim)
%INTCOUNT Count the number of occurrence of integers
%
% c = INTCOUNT([v0, v1], V);
% counts the number of integers in [v0, v1] that occurs in V.
%
% In the input, V is an array containing integer values (whose
% type can be double or single nonetheless).
% In the output, c is a row vector of length v1 - v0 + 1.
% In particular, c(i) counts the number of times that the value
% v0 + (i-1) occurs in V.
%
% c = INTCOUNT(K, V);
% This is equivalent to intcount([1, K], V);
%
% c = INTCOUNT([v0, v1], V, dim);
% c = INTCOUNT(K, V, dim);
%
% performs the counting along specified direction. Here, dim
% can be either 1 or 2.
%
% If dim == 1, it counts for each column, resulting a vector
% of counts, whose size is K x n.
%
% If dim == 2, it counts for each row, resulting a vector of
% counts, whose size is m x K.
%
% History
% -------
% - Created by Dahua Lin, on May 26, 2010
% - Modified by Dahua Lin, on Jun 6, 2010
% - Use pure C++ mex implementation
% - Modified by Dahua Lin, on Feb 26, 2012
% - Support per column/row counting
%
%% verify input arguments
if isnumeric(rgn) && isvector(rgn)
if isscalar(rgn)
v0 = 1;
v1 = rgn;
if v1 < 1
error('intcount:invalidarg', 'K should be a positive number.');
end
elseif numel(rgn) == 2
v0 = rgn(1);
v1 = rgn(2);
if v0 > v1
error('intcount:invalidarg', 'The condition v0 <= v1 is not met.');
end
else
error('intcount:invalidarg', 'The first argument is invalid.');
end
else
error('intcount:invalidarg', 'The first argument is invalid.');
end
v0 = int32(v0);
v1 = int32(v1);
if ~(isnumeric(V) && isreal(V) && ~issparse(V))
error('intcount:invalidarg', ...
'V should be a non-sparse numeric array of integers.');
end
if nargin < 3
dim = 0;
else
if ndims(V) > 2
error('intcount:invalidarg', ...
'V need to be a matrix when dim is explicitly specified.');
end
if isequal(dim, 1)
dim = 1;
elseif isequal(dim, 2)
dim = 2;
V = V.';
end
end
%% main
c = intcount_cimp(v0, v1, V, dim > 0);
if dim == 2
c = c.';
end
| zzhangumd-smitoolbox | base/data/intcount.m | MATLAB | mit | 2,359 |
function [R, I] = top_k(X, op, K, dim)
% Find the top k elements
%
% R = top_k(X, 'min', K);
% R = top_k(X, 'max', K);
%
% If X is a row/column vector, it returns a row/column vector of
% length K, which contains the K smallest elements sorted in
% ascending order, or the K largest elements sorted in descending
% order.
%
% If X is a matrix, it returns a matrix R with K rows, where R(:,i)
% corresponds to the K top elements for X(:,i).
%
% R = top_k( ..., dim);
%
% One can additionally specify the dimension along which the
% too k elements are extracted.
%
% [R, I] = top_k( ... );
%
% This statement additionally returns the indices of the top-K
% elements within their own vector.
%
% Remarks
% -------
% 1. The implementation is based on a partial sorting algorithm
% implemented in C++. It is expected to be more efficient
% then first launching a full sorting.
% The complexity is O(n + k logk).
%
% History
% -------
% - Created by Dahua Lin, on Nov 11, 2010
% - Modified by Dahua Lin, on Mar 28, 2011
% - re-implemented the core mex using bcslib
%
%% verify input
if ~(isnumeric(X) && ndims(X) == 2)
error('top_k:invalidarg', 'X should be a numeric matrix.');
end
if ~(ischar(op))
error('top_k:invalidarg', 'The 2nd argument should be a string.');
end
switch op
case 'max'
code = 1;
case 'min'
code = 2;
otherwise
error('top_k:invalidarg', 'The 2nd argument is invalid.');
end
if ~(isnumeric(K) && isscalar(K) && K >= 1)
error('top_k:invalidarg', 'K should be a positive integer scalar.');
end
K = double(K);
if nargin < 4
dim = 0;
else
if ~(isnumeric(dim) && isscalar(dim) && (dim == 1 || dim == 2))
error('top_k:invalidarg', 'dim should be either 1 or 2.');
end
dim = double(dim);
end
% check K and get d (vector or matrix form)
if dim == 0
if size(X, 1) > 1
dim = 1;
else
dim = 2;
end
end
check_K(K, size(X, dim));
%% main
if dim == 2
X = X.';
end
if nargout <= 1
R = top_k_cimp(X, K, code);
if dim == 2
R = R.';
end
else
[R, I] = top_k_cimp(X, K, code);
if dim == 2
R = R.';
I = I.';
end
end
function check_K(K, ub)
if K > ub
error('top_k:invalidarg', 'The value of K exceeds upper bound.');
end
| zzhangumd-smitoolbox | base/data/top_k.m | MATLAB | mit | 2,465 |
function R = aggreg_percol(X, K, I, fun)
%AGGREG_PERCOL Per-column index-based aggregation
%
% R = AGGREG_PERCOL(X, K, I, 'sum');
% R = AGGREG_PERCOL(X, K, I, 'mean');
% R = AGGREG_PERCOL(X, K, I, 'min');
% R = AGGREG_PERCOL(X, K, I, 'max');
% R = AGGREG_PERCOL(X, K, I, 'var');
% R = AGGREG_PERCOL(X, K, I, 'std');
%
% performs per-column aggregation of X based on the indices given
% by I. K is the number of distinct indices.
%
% X and I should be matrices of the same size. Suppose this size
% is m x n, then R will be a matrix of size K x n, such that
%
% R(k, i) = afun(X(I(:,i) == k, i));
%
% Here, afun is the given aggregation function.
%
% If the 4th argument is omitted, it is set to 'sum' by default.
%
% Created by Dahua Lin, on Feb 26, 2012
%
%% verify inputs
if ~((isnumeric(X) || islogical(X)) && ~issparse(X) && ismatrix(X))
error('aggreg_percol:invalidarg', ...
'X should be a non-sparse numeric or logical matrix.');
end
if ~(isnumeric(K) && isscalar(K) && K >= 1)
error('aggreg_percol:invalidarg', ...
'K should be a positive integer scalar.');
end
K = double(K);
if ~(isnumeric(I) && ~issparse(I) && isreal(I) && ismatrix(I))
error('aggreg_percol:invalidarg', ...
'I should be a real non-sparse real vector.');
end
if ~(size(X,1) == size(I,1) && size(X,2) == size(I,2))
error('aggreg_percol:invalidarg', ...
'X and I should be matrices of the same size.');
end
if nargin < 4
fun = 'sum';
else
if ~ischar(fun)
error('aggreg_percol:invalidarg', 'The fun name must be a string.');
end
end
%% main
switch fun
case 'sum'
R = agx_sum(X, K, I);
case 'mean'
R = agx_mean(X, K, I);
case 'min'
R = agx_min(X, K, I);
case 'max'
R = agx_max(X, K, I);
case 'var'
R = agx_var(X, K, I);
case 'std'
R = sqrt(agx_var(X, K, I));
otherwise
error('aggreg:invalidarg', 'The fun name is invalid.');
end
%% Core functions
function R = agx_sum(X, K, I)
R = aggreg_percol_cimp(X, K, int32(I)-1, 1);
function R = agx_mean(X, K, I)
S = agx_sum(X, K, I);
if ~isfloat(S)
S = double(S);
end
N = intcount(K, I, 1);
R = S ./ N;
function R = agx_min(X, K, I)
R = aggreg_percol_cimp(X, K, int32(I)-1, 2);
function R = agx_max(X, K, I)
R = aggreg_percol_cimp(X, K, int32(I)-1, 3);
function R = agx_var(X, K, I)
S1 = agx_sum(X, K, I);
S2 = agx_sum(X.^2, K, I);
if ~isfloat(S1)
S1 = double(S1);
end
if ~isfloat(S2)
S2 = double(S2);
end
N = intcount(K, I, 1);
EX = S1 ./ N;
EX2 = S2 ./ N;
R = EX2 - EX.^2;
R(R < 0) = 0;
| zzhangumd-smitoolbox | base/data/aggreg_percol.m | MATLAB | mit | 2,747 |
function R = aggreg(X, K, I, fun)
%AGGREG Index-based aggregation
%
% R = AGGREG(X, K, I, 'sum');
% R = AGGREG(X, K, I, 'mean');
% R = AGGREG(X, K, I, 'min');
% R = AGGREG(X, K, I, 'max');
% R = AGGREG(X, K, I, 'var');
% R = AGGREG(X, K, I, 'std');
%
% performs aggregation of the rows or columns in X based on the
% indices given by I. K is the number of distinct indices.
%
% Suppose X is a matrix of size m x n, then I can be a vector
% of size m x 1 or size 1 x n.
%
% (1) size(I) == [m, 1], then size(R) will be [K, n]:
% R(k, :) is the aggregation of the rows in X whose
% corresponding index in I is k.
%
% (2) size(I) == [1, n], then size(R) will be [m, K]
% R(:, k) is the aggregation of the columns in X whose
% corresponding index in I is k.
%
% If the 4th argument is omitted, it is set to 'sum' by default.
%
% Remarks
% -------
% - For the index k which corresponds to no elements in X, the
% corresponding output value will be set to 0, NaN, Inf, and
% -Inf, respectively for sum, mean, max, and min.
%
% - In computing the variance, we use n rather than n-1 to normalize
% the output. In other words, it results in the maximum likelihood
% estimation, instead of the unbiased estimation.
%
% - This function is partly similar to the built-in function
% accumarray. There are two main differences:
% (1) it is based on optimized C++ code, and thus runs much
% faster for the aggregation functions that it can support
% (2) it supports aggregation of rows and columns, where
% accumarray only supports aggregation of scalars.
%
% History
% -------
% - Created by Dahua Lin, on Nov 11, 2010
% - Modified by Dahua Lin, on Mar 27, 2011
% - re-implement the mex using bcslib
% - now additionally supports int32 and bool.
%
%% verify input
if ~((isnumeric(X) || islogical(X)) && ~issparse(X) && ndims(X) == 2)
error('aggreg:invalidarg', ...
'X should be a non-sparse numeric or logical matrix.');
end
[m, n] = size(X);
if ~(isnumeric(K) && isscalar(K) && K >= 1)
error('aggreg:invalidarg', ...
'K should be a positive integer scalar.');
end
K = double(K);
if ~(isnumeric(I) && ~issparse(I) && isreal(I) && isvector(I))
error('aggreg:invalidarg', ...
'I should be a real non-sparse real vector.');
end
[mI, nI] = size(I);
if mI == m && nI == 1 % m x 1
dim = 1;
elseif mI == 1 && nI == n % 1 x n
dim = 2;
else
error('aggreg:invalidarg', ...
'I should be a vector of size 1 x n or size m x 1.');
end
if nargin < 4
fun = 'sum';
else
if ~ischar(fun)
error('aggreg:invalidarg', 'The fun name must be a string.');
end
end
%% main
switch fun
case 'sum'
R = ag_sum(X, K, I, dim);
case 'mean'
R = ag_mean(X, K, I, dim);
case 'min'
R = ag_min(X, K, I, dim);
case 'max'
R = ag_max(X, K, I, dim);
case 'var'
R = ag_var(X, K, I, dim);
case 'std'
R = sqrt(ag_var(X, K, I, dim));
otherwise
error('aggreg:invalidarg', 'The fun name is invalid.');
end
%% sub functions
function R = ag_sum(X, K, I, dim)
R = aggreg_cimp(X, K, int32(I)-1, dim, 1);
function R = ag_mean(X, K, I, dim)
S = ag_sum(X, K, I, dim);
if ~isfloat(S)
S = double(S);
end
C = intcount(K, I);
R = make_mean(S, C, dim);
function R = ag_min(X, K, I, dim)
R = aggreg_cimp(X, K, int32(I)-1, dim, 2);
function R = ag_max(X, K, I, dim)
R = aggreg_cimp(X, K, int32(I)-1, dim, 3);
function R = ag_var(X, K, I, dim)
S1 = ag_sum(X, K, I, dim);
S2 = ag_sum(X.^2, K, I, dim);
C = intcount(K, I);
if ~isfloat(S1); S1 = double(S1); end
if ~isfloat(S2); S2 = double(S2); end
E1 = make_mean(S1, C, dim);
E2 = make_mean(S2, C, dim);
R = E2 - E1.^2;
R(R < 0) = 0;
%% auxiliary function
function R = make_mean(S, C, dim)
if dim == 1
C = C.';
if size(S, 2) == 1
R = S ./ C;
else
R = bsxfun(@times, S, 1./C);
end
else % dim == 2
if size(S, 1) == 1
R = S ./ C;
else
R = bsxfun(@times, S, 1./C);
end
end
| zzhangumd-smitoolbox | base/data/aggreg.m | MATLAB | mit | 4,348 |
/********************************************************************
*
* pieces_cimp.cpp
*
* The C++ mex implementation for pieces
*
* Created by Dahua Lin, on Mar 22, 2010
*
********************************************************************/
#include <bcslib/matlab/bcs_mex.h>
using namespace bcs;
using namespace bcs::matlab;
template<typename T>
void do_pieces_left_u(const T* edges, const T* x, double* y, int n, int m)
{
for (int i = 0; i < n; ++i)
{
int k = 0;
T v = x[i];
while (k <= m && v >= edges[k]) ++k;
y[i] = k;
}
}
template<typename T>
void do_pieces_right_u(const T* edges, const T* x, double* y, int n, int m)
{
for (int i = 0; i < n; ++i)
{
int k = 0;
T v = x[i];
while (k <= m && v > edges[k]) ++k;
y[i] = k;
}
}
template<typename T>
void do_pieces_left_s(const T* edges, const T* x, double* y, int n, int m)
{
int k = 0;
for (int i = 0; i < n; ++i)
{
T v = x[i];
while (k <= m && v >= edges[k]) ++k;
y[i] = k;
}
}
template<typename T>
void do_pieces_right_s(const T* edges, const T* x, double* y, int n, int m)
{
int k = 0;
for (int i = 0; i < n; ++i)
{
T v = x[i];
while (k <= m && v > edges[k]) ++k;
y[i] = k;
}
}
template<typename T>
inline void do_pieces(const T* edges, const T* x, double *y, int n, int m,
bool is_left, bool is_sorted)
{
if (is_left)
{
if (is_sorted)
do_pieces_left_s<T>(edges, x, y, n, m);
else
do_pieces_left_u<T>(edges, x, y, n, m);
}
else
{
if (is_sorted)
do_pieces_right_s<T>(edges, x, y, n, m);
else
do_pieces_right_u<T>(edges, x, y, n, m);
}
}
/**
* The main entry
*
* Input:
* [0] x: the values [double or single matrix]
* [1] edges: the edges of the bins [1 x (m+1) or (m+1) x 1]
* [2] dir: whether it is left-close: 1-left close, 0-right close
* [3] sorted: whether the input x is sorted
* if true, it uses a more efficient implementation O(n + m)
* if not, it uses a standard implementation O(n m)
* Output:
* [0] y: the output (int32, 1 x n)
*/
void bcsmex_main(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
// take input
const_marray mX(prhs[0]);
const_marray mEdges(prhs[1]);
const_marray mDir(prhs[2]);
const_marray mSorted(prhs[3]);
bool is_left = mDir.get_scalar<bool>();
bool is_sorted = mSorted.get_scalar<bool>();
// main
int nr = (int)mX.nrows();
int nc = (int)mX.ncolumns();
int n = nr * nc;
int m = (int)mEdges.nelems() - 1;
marray mY = create_marray<double>(nr, nc);
double *y = mY.data<double>();
if (mX.is_double())
{
do_pieces<double>(mEdges.data<double>(), mX.data<double>(),
y, n, m, is_left, is_sorted);
}
else if (mX.is_double())
{
do_pieces<float>(mEdges.data<float>(), mX.data<float>(),
y, n, m, is_left, is_sorted);
}
// output
plhs[0] = mY.mx_ptr();
}
BCSMEX_MAINDEF
| zzhangumd-smitoolbox | base/data/private/pieces_cimp.cpp | C++ | mit | 3,372 |
/********************************************************************
*
* top_k_cimp.cpp
*
* The C++ mex implementation of top_k.m
*
* Created by Dahua Lin, on Nov 11, 2010
*
********************************************************************/
#include <bcslib/matlab/bcs_mex.h>
#include <functional>
#include <algorithm>
#include <bcslib/array/array1d.h>
using namespace bcs;
using namespace bcs::matlab;
template<typename T>
struct indexed_value
{
T v;
int i;
void set(int idx, T val)
{
v = val;
i = idx;
}
bool operator < (const indexed_value<T>& rhs) const
{
return v < rhs.v;
}
bool operator > (const indexed_value<T>& rhs) const
{
return v > rhs.v;
}
bool operator == (const indexed_value<T>& rhs) const
{
return v == rhs.v;
}
};
template<typename T>
inline void export_with_inds(const T *src, indexed_value<T>* dst, index_t n)
{
for (index_t i = 0; i < n; ++i)
{
dst[i].set(i, src[i]);
}
}
template<typename T, class Comp>
inline void top_k(aview1d<T> temp, aview1d<T> r, Comp comp)
{
T *ws = temp.pbase();
index_t n = temp.nelems();
index_t K = r.nelems();
std::nth_element(ws, ws + (K-1), ws + n, comp);
std::sort(ws, ws + K, comp);
for (index_t i = 0; i < K; ++i)
{
r(i) = temp(i);
}
}
template<typename T, class Comp>
inline void top_k(aview1d<indexed_value<T> > temp,
aview1d<T> R, aview1d<double> I, Comp comp)
{
indexed_value<T> *ws = temp.pbase();
index_t n = temp.nelems();
index_t K = R.nelems();
std::nth_element(ws, ws + (K-1), ws + n, comp);
std::sort(ws, ws + K, comp);
for (index_t i = 0; i < K; ++i)
{
R(i) = temp(i).v;
I(i) = temp(i).i + 1;
}
}
template<typename T, template<typename U> class TComp>
inline marray do_top_k(const_marray mX, size_t K)
{
index_t m = (index_t)mX.nrows();
index_t n = (index_t)mX.ncolumns();
if (n == 1)
{
array1d<T> temp(m);
marray mR = create_marray<T>(K,1);
aview1d<T> R = view1d<T>(mR);
copy(view1d<T>(mX), temp);
top_k(temp.view(), R, TComp<T>());
return mR;
}
else
{
marray mR = create_marray<T>(K, n);
array1d<T> temp(m);
caview2d<T> X = view2d<T>(mX);
aview2d<T> R = view2d<T>(mR);
for (index_t i = 0; i < n; ++i)
{
copy(X.column(i), temp);
top_k(temp.view(), R.column(i), TComp<T>());
}
return mR;
}
}
template<typename T, template<typename U> class TComp>
inline void do_indexed_top_k(const_marray mX, index_t K, marray& mR, marray& mI)
{
index_t m = (index_t)mX.nrows();
index_t n = (index_t)mX.ncolumns();
if (n == 1)
{
mR = create_marray<T>((size_t)K, 1);
mI = create_marray<double>((size_t)K, 1);
array1d<indexed_value<T> > temp(m);
caview1d<T> X = view1d<T>(mX);
aview1d<T> R = view1d<T>(mR);
aview1d<double> I = view1d<double>(mI);
export_with_inds(X.pbase(), temp.pbase(), m);
top_k(temp.view(), R, I, TComp<indexed_value<T> >() );
}
else
{
mR = create_marray<T>((size_t)K, (size_t)n);
mI = create_marray<double>((size_t)K, (size_t)n);
array1d<indexed_value<T> > temp(m);
caview2d<T> X = view2d<T>(mX);
aview2d<T> R = view2d<T>(mR);
aview2d<double> I = view2d<double>(mI);
for (index_t i = 0; i < n; ++i)
{
export_with_inds(&(X(0, i)), temp.pbase(), m);
top_k(temp.view(), R.column(i), I.column(i), TComp<indexed_value<T> >() );
}
}
}
template<template<typename U> class TComp>
inline marray do_top_k_dtype(const_marray mX, index_t K)
{
switch (mX.class_id())
{
case mxDOUBLE_CLASS:
return do_top_k<double, TComp>(mX, K);
case mxSINGLE_CLASS:
return do_top_k<float, TComp>(mX, K);
case mxINT32_CLASS:
return do_top_k<int32_t, TComp>(mX, K);
case mxUINT32_CLASS:
return do_top_k<uint32_t, TComp>(mX, K);
default:
throw mexception("top_k:invalidarg",
"The X should be of type double, single, int32, or uint32.");
}
}
template<template<typename U> class TComp>
inline void do_indexed_top_k_dtype(const_marray mX, index_t K, marray& mR, marray& mI)
{
switch (mX.class_id())
{
case mxDOUBLE_CLASS:
do_indexed_top_k<double, TComp>(mX, K, mR, mI);
break;
case mxSINGLE_CLASS:
do_indexed_top_k<float, TComp>(mX, K, mR, mI);
break;
case mxINT32_CLASS:
do_indexed_top_k<int32_t, TComp>(mX, K, mR, mI);
break;
case mxUINT32_CLASS:
do_indexed_top_k<uint32_t, TComp>(mX, K, mR, mI);
break;
default:
throw mexception("top_k:invalidarg",
"The X should be of type double, single, int32, or uint32.");
}
}
/**
* main entry:
*
* [0]: X: the input data matrix
* [1]: K: the number of top elements
* [2]: code: 1 - max, 2 - min
*
* output
* [0]: R: top values
* [1]: I: top indices (optional)
*/
void bcsmex_main(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
const_marray mX(prhs[0]);
const_marray mK(prhs[1]);
const_marray mCode(prhs[2]);
index_t K = (index_t)mK.get_scalar<double>();
int code = (int)mCode.get_scalar<double>();
marray mR, mI;
if (nlhs <= 1)
{
if (code == 1)
{
mR = do_top_k_dtype<std::greater>(mX, K);
}
else
{
mR = do_top_k_dtype<std::less>(mX, K);
}
plhs[0] = mR.mx_ptr();
}
else
{
if (code == 1)
{
do_indexed_top_k_dtype<std::greater>(mX, K, mR, mI);
}
else
{
do_indexed_top_k_dtype<std::less>(mX, K, mR, mI);
}
plhs[0] = mR.mx_ptr();
plhs[1] = mI.mx_ptr();
}
}
BCSMEX_MAINDEF
| zzhangumd-smitoolbox | base/data/private/top_k_cimp.cpp | C++ | mit | 6,494 |