text:
package org.ofbiz.webapp;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.ilscipio.scipio.ce.util.SafeOptional;
import org.apache.tomcat.util.descriptor.web.WebXml;
import org.ofbiz.base.component.ComponentConfig.WebappInfo;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.webapp.control.ConfigXMLReader.ControllerConfig;
import org.ofbiz.webapp.control.WebAppConfigurationException;
import org.ofbiz.webapp.renderer.RenderEnvType;
import org.ofbiz.webapp.website.WebSiteProperties;
import org.ofbiz.webapp.website.WebSiteWorker;
import org.xml.sax.SAXException;

/**
 * SCIPIO: Contextual, "full" information about a webapp, including
 * webSiteId, WebappInfo, ExtWebappInfo, WebSiteProperties,
 * and ControllerConfig - with webapp request or static rendering context scope.
 *

 * IMPORTANT: This class is intended for short scopes only,
 * mainly single requests. It should not be cached in static
 * variables because it relies on database lookups.
 *

 * This serves as a request cache.
 *

 * FullWebappInfo is basically thread-safe, as long as client does not need
 * objects returned by getters to be truly unique.
 * However, the Cache below is NOT thread-safe.
 *

 * All factory methods may throw IllegalArgumentException.
 *

 * NOTE: 2018-08-09: This used to perform lazy initialization, but because of cache
 * this shouldn't hold a reference to HttpServletRequest (circular), and is not worth
 * doing it for render context alone (delegator only), so for now all
 * is initialized during construction. This is subject to change in future.
 *

 * DEV NOTE: Do not make this serializable, so as to avoid this
 * getting transferred into session attributes by RequestHandler.
 *

 * Added 2018-08-02.
 */
public class FullWebappInfo {

    //private static final Debug.OfbizLogger module = Debug.getOfbizLogger(java.lang.invoke.MethodHandles.lookup().lookupClass());

    //private final Delegator delegator; // REMOVED lazy initialization - not worth it
    private ExtWebappInfo extWebappInfo;
    private WebSiteProperties webSiteProperties;

    private SafeOptional<ControllerConfig> controllerConfig;
    private OfbizUrlBuilder ofbizUrlBuilder;

    protected FullWebappInfo(Delegator delegator, ExtWebappInfo extWebappInfo, WebSiteProperties webSiteProperties,
                             SafeOptional<ControllerConfig> controllerConfig, OfbizUrlBuilder ofbizUrlBuilder) {
        //this.delegator = delegator; // can be null if all others are non-null
        this.extWebappInfo = extWebappInfo;
        this.webSiteProperties = webSiteProperties;
        this.controllerConfig = controllerConfig;
        this.ofbizUrlBuilder = ofbizUrlBuilder;
    }

    protected FullWebappInfo(Delegator delegator, ExtWebappInfo extWebappInfo) {
        //this.delegator = delegator;
        this.extWebappInfo = extWebappInfo;
    }

    protected FullWebappInfo(HttpServletRequest request) {
        try {
            // SPECIAL: in this case we must initialize WebSiteProperties immediately because
            // we can't store the HttpServletRequest object in FullWebappInfo
            this.ofbizUrlBuilder = OfbizUrlBuilder.from(request);
            this.extWebappInfo = ExtWebappInfo.fromRequest(request);
            this.webSiteProperties = this.ofbizUrlBuilder.getWebSiteProperties();
            this.controllerConfig = SafeOptional.ofNullable(this.ofbizUrlBuilder.getControllerConfig());
        } catch (GenericEntityException e) {
            throw new IllegalArgumentException(e);
        } catch (WebAppConfigurationException e) {
            throw new IllegalArgumentException(e);
        }
    }

    protected FullWebappInfo(ExtWebappInfo extWebappInfo, HttpServletRequest request) {
        try {
            // SPECIAL: in this case we must initialize WebSiteProperties immediately because
            // we can't store the HttpServletRequest object in FullWebappInfo
            this.ofbizUrlBuilder = OfbizUrlBuilder.from(extWebappInfo, request);
            this.extWebappInfo = extWebappInfo;
            this.webSiteProperties = this.ofbizUrlBuilder.getWebSiteProperties();
            this.controllerConfig = SafeOptional.ofNullable(this.ofbizUrlBuilder.getControllerConfig());
        } catch (GenericEntityException e) {
            throw new IllegalArgumentException(e);
        } catch (WebAppConfigurationException e) {
            throw new IllegalArgumentException(e);
        }
    }

    protected FullWebappInfo(ExtWebappInfo extWebappInfo, Map<String, Object> context) {
        this(extWebappInfo, (Delegator) context.get("delegator"));
    }

    protected FullWebappInfo(ExtWebappInfo extWebappInfo, Delegator delegator) {
        try {
            // SPECIAL: in this case we must initialize WebSiteProperties immediately because
            // we can't store the HttpServletRequest object in FullWebappInfo
            this.ofbizUrlBuilder = OfbizUrlBuilder.from(extWebappInfo, delegator);
            this.extWebappInfo = extWebappInfo;
            this.webSiteProperties = this.ofbizUrlBuilder.getWebSiteProperties();
            this.controllerConfig = SafeOptional.ofNullable(this.ofbizUrlBuilder.getControllerConfig());
        } catch (GenericEntityException e) {
            throw new IllegalArgumentException(e);
        } catch (WebAppConfigurationException e) {
            throw new IllegalArgumentException(e);
        } catch (IOException e) {
            throw new IllegalArgumentException(e);
        } catch (SAXException e) {
            throw new IllegalArgumentException(e);
        }
    }

    /*
     * ******************************************************
     * Intra-webapp live request factory methods
     * ******************************************************
     */

    /**
     * Gets webapp info for current webapp from request.
     * For intra-webapp links.
     */
    public static FullWebappInfo fromRequest(HttpServletRequest request) throws IllegalArgumentException {
        return fromRequest(request, Cache.fromRequest(request));
    }

    /**
     * Gets webapp info for current webapp from request.
     * For intra-webapp links.
     */
    public static FullWebappInfo fromRequest(HttpServletRequest request, Cache cache) throws IllegalArgumentException {
        if (cache == null) return new FullWebappInfo(request);
        FullWebappInfo fullWebappInfo = cache.getCurrentWebappInfo();
        if (fullWebappInfo == null) {
            fullWebappInfo = new FullWebappInfo(request);
            cache.setCurrentWebappInfo(fullWebappInfo);
        }
        return fullWebappInfo;
    }

    /**
     * Reads webapp info from request, but if the request does not appear set up properly
     * yet (i.e. by ContextFilter), prevent caching the result, so as to not pollute the rest
     * of the request with an uncertain state.
     * For intra-webapp links.
     *

     * DEV NOTE: WARN: This is dirty to maintain, beware.
     */
    public static FullWebappInfo fromRequestFilterSafe(HttpServletRequest request) throws IllegalArgumentException {
        if (request.getAttribute("delegator") != null) {
            // request appears set up already (e.g. by ContextFilter)
            return fromRequest(request);
        } else {
            // no delegator, request is not set up
            request.setAttribute("delegator", WebAppUtil.getDelegatorFilterSafe(request));
            boolean hadOfbizUrlBuilderAttr = (request.getAttribute("_OFBIZ_URL_BUILDER_") != null);
            boolean hadWebSitePropsAttr = (request.getAttribute("_WEBSITE_PROPS_") != null);
            boolean addedControlPathAttr = false;
            if (request.getAttribute("_CONTROL_PATH_") == null) {
                // From ControlServlet logic
                addedControlPathAttr = true;
                String contextPath = request.getContextPath();
                if (contextPath == null || "/".equals(contextPath)) {
                    contextPath = "";
                }
                request.setAttribute("_CONTROL_PATH_", contextPath + request.getServletPath());
            }
            try {
                return new FullWebappInfo(request);
            } finally {
                // do not let filter state affect rest of request - clear cached objects
                if (!hadOfbizUrlBuilderAttr) request.removeAttribute("_OFBIZ_URL_BUILDER_");
                if (!hadWebSitePropsAttr) request.removeAttribute("_WEBSITE_PROPS_");
                if (addedControlPathAttr) request.removeAttribute("_CONTROL_PATH_");
                Cache.clearRequestCache(request);
                request.removeAttribute("delegator");
            }
        }
    }
    /*
     * ******************************************************
     * Inter-webapp live request factory methods
     * ******************************************************
     */

    /**
     * Gets full webapp info, using webapp request for caching and context information.
     * For inter-webapp links.
     */
    public static FullWebappInfo fromWebapp(ExtWebappInfo extWebappInfo, HttpServletRequest request) throws IllegalArgumentException {
        return fromWebapp(extWebappInfo, request, Cache.fromRequest(request));
    }

    /**
     * Gets full webapp info, using webapp request for caching and context information.
     * For inter-webapp links.
     */
    public static FullWebappInfo fromWebapp(ExtWebappInfo extWebappInfo, HttpServletRequest request, Cache cache) throws IllegalArgumentException {
        if (cache == null) return new FullWebappInfo(extWebappInfo, request);
        FullWebappInfo fullWebappInfo = cache.getByContextPath(extWebappInfo.getContextPath());
        if (fullWebappInfo == null) {
            fullWebappInfo = new FullWebappInfo(extWebappInfo, request);
            cache.addWebappInfo(fullWebappInfo);
        }
        return fullWebappInfo;
    }

    /*
     * ******************************************************
     * Intra-webapp static context factory methods
     * ******************************************************
     */

    /**
     * Gets webapp info for current webapp from render context.
     * For intra-webapp links.
     *

     * NOTE: This only works if there is a webSiteId (or baseWebSiteId) in context..
     * For now only webapp requests can return an instance without webSiteId.
     */
    public static FullWebappInfo fromContext(Map<String, Object> context, RenderEnvType renderEnvType) throws IllegalArgumentException {
        return fromContext(context, renderEnvType, Cache.fromContext(context, renderEnvType));
    }

    /**
     * Gets webapp info for current webapp from render context.
     * For intra-webapp links.
     *

     * NOTE: This only works if there is a webSiteId (or baseWebSiteId) in context..
     * For now only webapp requests can return an instance without webSiteId.
     */
    public static FullWebappInfo fromContext(Map<String, Object> context) throws IllegalArgumentException {
        RenderEnvType renderEnvType = RenderEnvType.fromContext(context);
        return fromContext(context, renderEnvType, Cache.fromContext(context, renderEnvType));
    }

    /**
     * Gets webapp info for current webapp from render context.
     * For intra-webapp links.
     *

     * NOTE: This only works if there is a webSiteId (or baseWebSiteId) in context..
     * For now only webapp requests can return an instance without webSiteId.
     */
    public static FullWebappInfo fromContext(Map<String, Object> context, RenderEnvType renderEnvType, Cache cache) throws IllegalArgumentException {
        if (renderEnvType.isStatic()) {
            FullWebappInfo fullWebappInfo = null;
            if (cache != null) {
                fullWebappInfo = cache.getCurrentWebappInfo();
                if (fullWebappInfo != null) {
                    return fullWebappInfo;
                }
            }
            String webSiteId = WebSiteWorker.getWebSiteIdFromContext(context, renderEnvType);
            if (webSiteId != null) {
                fullWebappInfo = FullWebappInfo.fromWebapp(ExtWebappInfo.fromWebSiteId(webSiteId),
                        (Delegator) context.get("delegator"), cache);
                if (cache != null) {
                    cache.setCurrentWebappInfoOnly(fullWebappInfo);
                }
            }
            return fullWebappInfo;
        } else if (renderEnvType.isWebapp()) { // NOTE: it is important to check isWebapp here and not (request != null), because these could disassociate in future
            return fromRequest((HttpServletRequest) context.get("request"), cache);
        }
        return null;
    }

    /*
     * ******************************************************
     * Inter-webapp static context factory methods
     * ******************************************************
     */

    /**
     * Gets webapp info, using render context for caching and context information.
     * For inter-webapp links.
     */
    public static FullWebappInfo fromWebapp(ExtWebappInfo extWebappInfo, Map<String, Object> context) throws IllegalArgumentException {
        return fromWebapp(extWebappInfo, context, Cache.fromContext(context));
    }

    /**
     * Gets webapp info, using render context for caching and context information.
     * For inter-webapp links.
     */
    public static FullWebappInfo fromWebapp(ExtWebappInfo extWebappInfo, Map<String, Object> context, Cache cache) throws IllegalArgumentException {
        if (cache == null) return new FullWebappInfo(extWebappInfo, context);
        FullWebappInfo fullWebappInfo = cache.getByContextPath(extWebappInfo.getContextPath());
        if (fullWebappInfo == null) {
            fullWebappInfo = new FullWebappInfo(extWebappInfo, context);
            cache.addWebappInfo(fullWebappInfo);
        }
        return fullWebappInfo;
    }

    /**
     * Gets webapp info, without any context information (low-level no-context factory method).
     * For inter-webapp links.
     *

     * WARN: Prefer method with context or request wherever available, instead of this one.
     * This method has less information to work with compared to request and context overloads.
     */
    public static FullWebappInfo fromWebapp(ExtWebappInfo extWebappInfo, Delegator delegator, Cache cache) throws IllegalArgumentException {
        if (cache == null) return new FullWebappInfo(extWebappInfo, delegator);
        FullWebappInfo fullWebappInfo = cache.getByContextPath(extWebappInfo.getContextPath());
        if (fullWebappInfo == null) {
            fullWebappInfo = new FullWebappInfo(extWebappInfo, delegator);
            cache.addWebappInfo(fullWebappInfo);
        }
        return fullWebappInfo;
    }

    /**
     * Gets webapp info, without any context information (low-level no-context factory method) - no caching.
     * For inter-webapp links.
     *

     * WARN: Prefer method with context or request wherever available, instead of this one.
     * This method has less information to work with compared to request and context overloads.
     */
    public static FullWebappInfo fromWebapp(ExtWebappInfo extWebappInfo, Delegator delegator) throws IllegalArgumentException {
        return new FullWebappInfo(extWebappInfo, delegator);
    }

    /*
     * ******************************************************
     * High-level/combination factory methods
     * ******************************************************
     */

    /**
     * Gets webapp info for webSiteId or contextPath, otherwise null (high-level factory method).
     * Caches in request if available, otherwise context.
     */
    public static FullWebappInfo fromWebSiteIdOrContextPathOrNull(String webSiteId,
            String contextPath, HttpServletRequest request, Map<String, Object> context) throws IllegalArgumentException {
        if (UtilValidate.isNotEmpty(webSiteId)) {
            if (request != null) {
                return fromWebapp(ExtWebappInfo.fromWebSiteId(webSiteId), request, Cache.fromRequest(request));
            } else {
                return fromWebapp(ExtWebappInfo.fromWebSiteId(webSiteId), context, Cache.fromContext(context));
            }
        } else if (UtilValidate.isNotEmpty(contextPath)) {
            if (request != null) {
                return fromWebapp(ExtWebappInfo.fromContextPath(WebAppUtil.getServerId(request), contextPath), request, Cache.fromRequest(request));
            } else {
                return fromWebapp(ExtWebappInfo.fromContextPath(WebAppUtil.getServerId(context), contextPath), context, Cache.fromContext(context));
            }
        }
        return null;
    }

    /*
     * ******************************************************
     * Other type factory methods (mainly to exploit the cache).
     * ******************************************************
     */

    public static OfbizUrlBuilder getOfbizUrlBuilderFromWebSiteIdOrDefaults(String webSiteId, Delegator delegator, Cache cache) throws IllegalArgumentException {
        if (UtilValidate.isNotEmpty(webSiteId)) {
            if (cache != null && cache.getByWebSiteId(webSiteId) != null) {
                return cache.getByWebSiteId(webSiteId).getOfbizUrlBuilder();
            }
            try {
                return OfbizUrlBuilder.fromWebSiteId(webSiteId, delegator);
            } catch (Exception e) {
                throw new IllegalStateException(e);
            }
        } else {
            if (cache != null && cache.getDefaultOfbizUrlBuilder() != null) {
                return cache.getDefaultOfbizUrlBuilder();
            }
            OfbizUrlBuilder builder;
            try {
                builder = OfbizUrlBuilder.fromServerDefaults(delegator);
            } catch (Exception e) {
                throw new IllegalStateException(e);
            }
            if (cache != null) cache.setDefaultOfbizUrlBuilder(builder);
            return builder;
        }
    }

    /*
     * ******************************************************
     * Object getters
     * ******************************************************
     */

    public ExtWebappInfo getExtWebappInfo() {
        return extWebappInfo;
    }

    public WebSiteProperties getWebSiteProperties() {
        /* REMOVED lazy initialization - not worth it
        WebSiteProperties webSiteProperties = this.webSiteProperties;
        if (webSiteProperties == null) {
            String webSiteId = getWebSiteId();
            try {
                if (webSiteId != null) {
                    webSiteProperties = WebSiteProperties.from(delegator, webSiteId);
                } else {
                    webSiteProperties = WebSiteProperties.defaults(delegator);
                }
            } catch (Exception e) {
                if (webSiteId != null) {
                    Debug.logError(e, "Error getting WebSiteProperties for webSiteId '" + webSiteId + "'; trying defaults...", module);
                    try {
                        webSiteProperties = WebSiteProperties.defaults(delegator);
                    } catch (Exception e2) {
                        throw new IllegalStateException("Could not get default system WebSiteProperties", e); // very unlikely...
                    }
                } else {
                    throw new IllegalStateException("Could not get default system WebSiteProperties", e); // very unlikely...
                }
            }
            this.webSiteProperties = webSiteProperties;
        }
        return webSiteProperties;
        */
        return webSiteProperties;
    }

    /**
     * Returns the ControllerConfig for this webapp or null if it has none.
     */
    public ControllerConfig getControllerConfig() {
        SafeOptional<ControllerConfig> controllerConfig = this.controllerConfig;
        if (controllerConfig == null) {
            controllerConfig = SafeOptional.ofNullable(extWebappInfo.getControllerConfig());
            this.controllerConfig = controllerConfig;
        }
        return controllerConfig.orElse(null);
    }

    /**
     * Returns a URL builder or throws exception.
     */
    public OfbizUrlBuilder getOfbizUrlBuilder() throws IllegalArgumentException {
        /* REMOVED lazy initialization - not worth it
        OfbizUrlBuilder ofbizUrlBuilder = this.ofbizUrlBuilder;
        if (ofbizUrlBuilder == null) {
            try {
                ofbizUrlBuilder = OfbizUrlBuilder.from(this, delegator);
                this.ofbizUrlBuilder = ofbizUrlBuilder;
            } catch (Exception e) {
                throw new IllegalArgumentException(e); // caller isn't expecting null
            }
        }
        return ofbizUrlBuilder;
        */
        return ofbizUrlBuilder;
    }

    /*
     * ******************************************************
     * Helpers
     * ******************************************************
     */

    @Override
    public int hashCode() {
        return extWebappInfo.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        return (this == obj) ||
               ((obj instanceof FullWebappInfo) && this.isSameServerWebapp(((FullWebappInfo) obj)));
    }

    public boolean equalsProtoHostPort(FullWebappInfo other) {
        return this.getWebSiteProperties().equalsServerFields(other.getWebSiteProperties());
    }

    public boolean equalsProtoHostPortWithHardDefaults(FullWebappInfo other) {
        return this.getWebSiteProperties().equalsServerFieldsWithHardDefaults(other.getWebSiteProperties());
    }

    @Override
    public String toString() {
        return "[contextPath=" + getContextPath() + ", webSiteId=" + getWebSiteId() + "]";
    }

    /*
     * ******************************************************
     * ExtWebappInfo-delegated methods
     * ******************************************************
     */

    /**
     * @return
     * @see org.ofbiz.webapp.ExtWebappInfo#getServerId()
     */
    public String getServerId() {
        return extWebappInfo.getServerId();
    }

    /**
     * @return
     * @see org.ofbiz.webapp.ExtWebappInfo#getWebSiteId()
     */
    public String getWebSiteId() {
        return extWebappInfo.getWebSiteId();
    }

    /**
     * @return
     * @see org.ofbiz.webapp.ExtWebappInfo#getWebappInfo()
     */
    public WebappInfo getWebappInfo() {
        return extWebappInfo.getWebappInfo();
    }

    /**
     * @return
     * @see org.ofbiz.webapp.ExtWebappInfo#getWebXml()
     */
    public WebXml getWebXml() {
        return extWebappInfo.getWebXml();
    }

    public String getWebappName() {
        return extWebappInfo.getWebappName();
    }

    /**
     * @return
     * @see org.ofbiz.webapp.ExtWebappInfo#getContextPath()
     */
    public String getContextPath() {
        return extWebappInfo.getContextPath();
    }

    /**
     * @return
     * @deprecated
     * @see org.ofbiz.webapp.ExtWebappInfo#getContextRoot()
     */
    public String getContextRoot() {
        return extWebappInfo.getContextRoot();
    }

    /**
     * @return
     * @see org.ofbiz.webapp.ExtWebappInfo#getControlServletPath()
     */
    public String getControlServletPath() {
        return extWebappInfo.getControlServletPath();
    }

    /**
     * @return
     * @see org.ofbiz.webapp.ExtWebappInfo#getControlServletMapping()
     */
    public String getControlServletMapping() {
        return extWebappInfo.getControlServletMapping();
    }

    /**
     * @return
     * @see org.ofbiz.webapp.ExtWebappInfo#getFullControlPath()
     */
    public String getFullControlPath() {
        return extWebappInfo.getFullControlPath();
    }

    /**
     * @return
     * @see org.ofbiz.webapp.ExtWebappInfo#getContextParams()
     */
    public Map<String, String> getContextParams() {
        return extWebappInfo.getContextParams();
    }

    /**
     * @return
     * @see org.ofbiz.webapp.ExtWebappInfo#getForwardRootControllerUris()
     */
    public Boolean getForwardRootControllerUris() {
        return extWebappInfo.getForwardRootControllerUris();
    }

    /**
     * @return
     * @see org.ofbiz.webapp.ExtWebappInfo#getForwardRootControllerUrisValidated()
     */
    public Boolean getForwardRootControllerUrisValidated() {
        return extWebappInfo.getForwardRootControllerUrisValidated();
    }

    /**
     * @return
     * @see org.ofbiz.webapp.ExtWebappInfo#hasUrlRewriteFilter()
     */
    public boolean hasUrlRewriteFilter() {
        return extWebappInfo.hasUrlRewriteFilter();
    }

    /**
     * @return
     * @see org.ofbiz.webapp.ExtWebappInfo#getUrlRewriteConfPath()
     */
    public String getUrlRewriteConfPath() {
        return extWebappInfo.getUrlRewriteConfPath();
    }

    /**
     * @return
     * @see org.ofbiz.webapp.ExtWebappInfo#getUrlRewriteFullConfPath()
     */
    public String getUrlRewriteFullConfPath() {
        return extWebappInfo.getUrlRewriteFullConfPath();
    }

    /**
     * @return
     * @see org.ofbiz.webapp.ExtWebappInfo#getUrlRewriteRealConfPath()
     */
    public String getUrlRewriteRealConfPath() {
        return extWebappInfo.getUrlRewriteRealConfPath();
    }

    /**
     * @return
     * @see org.ofbiz.webapp.ExtWebappInfo#useUrlManualInterWebappFilter()
     */
    public boolean useUrlManualInterWebappFilter() {
        return extWebappInfo.useUrlManualInterWebappFilter();
    }

    /**
     * @param request
     * @return
     * @see org.ofbiz.webapp.ExtWebappInfo#isRequestWebapp(javax.servlet.http.HttpServletRequest)
     */
    public boolean isRequestWebapp(HttpServletRequest request) {
        return extWebappInfo.isRequestWebapp(request);
    }

    public boolean isSameServerWebapp(ExtWebappInfo other) {
        return extWebappInfo.isSameServerWebapp(other);
    }

    public boolean isSameWebSite(ExtWebappInfo other) {
        return extWebappInfo.isSameWebSite(other);
    }

    public boolean isSameServerWebapp(FullWebappInfo other) {
        return extWebappInfo.isSameServerWebapp(other.extWebappInfo);
    }

    public boolean isSameWebSite(FullWebappInfo other) {
        return extWebappInfo.isSameWebSite(other.extWebappInfo);
    }

    /**
     * WARN: not thread-safe at current time (meant for request scope only).
     */
    public static class Cache {

        public static final String FIELD_NAME = "scpFWICache";

        private FullWebappInfo currentWebappInfo;
        private WebSiteProperties defaultWebSiteProperties;
        private OfbizUrlBuilder defaultOfbizUrlBuilder;
        private Map<String, FullWebappInfo> webSiteIdCache = new HashMap<>();
        private Map<String, FullWebappInfo> contextPathCache = new HashMap<>();

        protected Cache(Delegator delegator) {
            //this.delegator = delegator;
        }

        public static Cache newCache(Delegator delegator) {
            return new Cache(delegator);
        }

        public static Cache fromRequest(HttpServletRequest request) {
            Cache cache = (Cache) request.getAttribute(FIELD_NAME);
            if (cache == null) {
                cache = new Cache((Delegator) request.getAttribute("delegator"));
                request.setAttribute(FIELD_NAME, cache);
            }
            return cache;
        }

        public static void clearRequestCache(HttpServletRequest request) {
            request.removeAttribute(FIELD_NAME);
        }

        public static Cache fromContext(Map<String, Object> context, RenderEnvType renderEnvType) {
            if (renderEnvType.isStatic()) {
                @SuppressWarnings("unchecked")
                Map<String, Object> srcContext = (Map<String, Object>) context.get("globalContext");
                if (srcContext == null) srcContext = context; // fallback

                Cache cache = (Cache) srcContext.get(FIELD_NAME);
                if (cache == null) {
                    cache = new Cache((Delegator) context.get("delegator"));
                    srcContext.put(FIELD_NAME, cache);
                }
                return cache;
            } else if (renderEnvType.isWebapp()) { // NOTE: it is important to check isWebapp here and not (request != null), because these could disassociate in future
                return fromRequest((HttpServletRequest) context.get("request"));
            }
            return null;
        }

        public static Cache fromContext(Map<String, Object> context) {
            return fromContext(context, RenderEnvType.fromContext(context)); // TODO?: optimize
        }

        public static void clearContextCache(Map<String, Object> context, RenderEnvType renderEnvType) {
            if (renderEnvType.isStatic()) {
                @SuppressWarnings("unchecked")
                Map<String, Object> srcContext = (Map<String, Object>) context.get("globalContext");
                if (srcContext == null) srcContext = context; // fallback

                srcContext.remove(FIELD_NAME);
            } else if (renderEnvType.isWebapp()) {
                clearRequestCache((HttpServletRequest) context.get("request"));
            }
        }

        public static void clearContextCache(Map<String, Object> context) {
            clearContextCache(context, RenderEnvType.fromContext(context)); // TODO?: optimize
        }

        public static Cache fromRequestOrContext(HttpServletRequest request, Map<String, Object> context,
                RenderEnvType renderEnvType) {
            return (request != null) ? fromRequest(request) : fromContext(context, renderEnvType);
        }

        public FullWebappInfo getCurrentWebappInfo() {
            return currentWebappInfo;
        }

        public String getCurrentWebappWebSiteId() {
            return (currentWebappInfo != null) ? currentWebappInfo.getWebSiteId() : null;
        }

        public void setCurrentWebappInfo(FullWebappInfo currentWebappInfo) {
            this.currentWebappInfo = currentWebappInfo;
            addWebappInfo(currentWebappInfo);
        }

        public void setCurrentWebappInfoOnly(FullWebappInfo currentWebappInfo) {
            this.currentWebappInfo = currentWebappInfo;
        }

        public WebSiteProperties getDefaultWebSiteProperties() {
            return defaultWebSiteProperties;
        }

        public void setDefaultWebSiteProperties(WebSiteProperties defaultWebSiteProperties) {
            this.defaultWebSiteProperties = defaultWebSiteProperties;
        }

        public OfbizUrlBuilder getDefaultOfbizUrlBuilder() {
            return defaultOfbizUrlBuilder;
        }

        public void setDefaultOfbizUrlBuilder(OfbizUrlBuilder defaultOfbizUrlBuilder) {
            this.defaultOfbizUrlBuilder = defaultOfbizUrlBuilder;
        }

        public void addWebappInfo(FullWebappInfo webappInfo) {
            contextPathCache.put(webappInfo.getContextPath(), webappInfo);
            if (webappInfo.getWebSiteId() != null) {
                webSiteIdCache.put(webappInfo.getWebSiteId(), webappInfo);
            }
        }

        public FullWebappInfo getByWebSiteId(String webSiteId) {
            return webSiteIdCache.get(webSiteId);
        }

        public FullWebappInfo getByContextPath(String contextPath) {
            return contextPathCache.get(contextPath);
        }
    }

    public String getServletMappingMountPoint(String servletMapping) {
        return extWebappInfo.getServletMappingMountPoint(servletMapping);
    }
}


text:
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>or-tools/examples/cpp/: operations_research::NetworkRoutingDataBuilder Class Reference - Doxy</title>
    <link rel="shortcut icon" href="../../../favicon.ico">

    <link href="../../../doxygen.css" rel="stylesheet" type="text/css">
    <link href="../../../tabs.css" rel="stylesheet" type="text/css">

          Generated on: Thu Mar 29 07:46:58 PDT 2012
            for custom file set

        <tt>//
            doxy/
            or-tools/
            examples/
            cpp/
            </tt>

Main Page

Related Pages

Namespaces

Classes

Files

Class List

Class Hierarchy

Class Members

operations_research::NetworkRoutingDataBuilder

operations_research::NetworkRoutingDataBuilder Class Reference
Data Generation.
More...

List of all members.

Public Member Functions

 	NetworkRoutingDataBuilder ()

void 	BuildModelFromParameters (int num_clients, int num_backbones, int num_demands, int traffic_min, int traffic_max, int min_client_degree, int max_client_degree, int min_backbone_degree, int max_backbone_degree, int max_capacity, int fixed_charge_cost, int seed, NetworkRoutingData *const data)

Detailed Description

Data Generation.

Random generator of problem. This generator creates a random problem. This problem uses a special topology. There are 'num_backbones' nodes and 'num_clients' nodes. if 'num_clients' is null, then all backbones nodes are also client nodes. All traffic originates and terminates in client nodes. Each client node is connected to 'min_client_degree' - 'max_client_degree' backbone nodes. Each backbone node is connected to 'min_backbone_degree' - 'max_backbone_degree' other backbone nodes. There are 'num_demands' demands, with a traffic between 'traffic_min' and 'traffic_max'. Each arc has a capacity of 'max_capacity'. Using an arc incurs a fixed cost of 'fixed_charge_cost'.

Definition at line 175 of file network_routing.cc.

Constructor & Destructor Documentation

          operations_research::NetworkRoutingDataBuilder::NetworkRoutingDataBuilder
          (

           )
           [inline]

Definition at line 177 of file network_routing.cc.

Member Function Documentation

          void operations_research::NetworkRoutingDataBuilder::BuildModelFromParameters
          (
          int
           num_clients,

          int
           num_backbones,

          int
           num_demands,

          int
           traffic_min,

          int
           traffic_max,

          int
           min_client_degree,

          int
           max_client_degree,

          int
           min_backbone_degree,

          int
           max_backbone_degree,

          int
           max_capacity,

          int
           fixed_charge_cost,

          int
           seed,

          NetworkRoutingData *const
           data

          )
          		 [inline]

Definition at line 179 of file network_routing.cc.

The documentation for this class was generated from the following file:

or-tools/examples/cpp/network_routing.cc

redpajama_set_name: RedPajamaGithub


text:
using RenderingLibrary.Content;
using SkiaSharp;
using System;
using System.Collections.Generic;
using System.Text;
using SKSvg = SkiaSharp.Extended.Svg.SKSvg;

namespace SkiaGum.Content
{
    public class EmbeddedResourceContentLoader : IContentLoader
    {
        public Func<string, string> AdjustContentName;
        public void AddDisposable(string contentName, IDisposable disposable)
        {
            throw new NotImplementedException();
        }

        public T LoadContent<T>(string contentName)
        {
            if (typeof(T) == typeof(SKTypeface))
            {
                return (T)(object)LoadSKTypeface(contentName);
            }
            else if (typeof(T) == typeof(SKSvg))
            {
                return (T)(object)LoadSKSvg(contentName);
            }
            else if (typeof(T) == typeof(SKBitmap))
            {
                return (T)(object)LoadSKBitmap(contentName);
            }
            else

            {
                return default(T);
            }
        }

        private SKSvg LoadSKSvg(string contentName)
        {
            var modifiedContentName = AdjustContentName?.Invoke(contentName) ?? contentName;

            return SkiaResourceManager.GetSvg(modifiedContentName);
        }

        private SKBitmap LoadSKBitmap(string contentName)
        {
            var modifiedContentName = AdjustContentName?.Invoke(contentName) ?? contentName;

            return SkiaResourceManager.GetSKBitmap(modifiedContentName);
        }

        private SKTypeface LoadSKTypeface(string contentName)
        {
            var modifiedContentName = AdjustContentName?.Invoke(contentName) ?? contentName;

            return SkiaResourceManager.GetTypeface(modifiedContentName);
        }

        public T TryGetCachedDisposable<T>(string contentName)
        {
            throw new NotImplementedException();
        }

        public T TryLoadContent<T>(string contentName)
        {
            throw new NotImplementedException();
        }
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>io.leopard</groupId>
		<artifactId>leopard</artifactId>
		<version>0.9.13-SNAPSHOT</version>
	</parent>
	<artifactId>beanunit</artifactId>
	<packaging>pom</packaging>
	<name>BeanUnit</name>
	<description>Bean单元测试,支持测试方法加参数,并支持参数解析(类似Leopard MVC)、支持Test类注册为Spring Bean。</description>
</project>


text:
require 'spec_helper'

feature 'viewing entry revisions' do
  scenario 'view depublished revision' do
    entry = create(:entry)
    revision = create(:revision, :depublished, :entry => entry)
    storyline = create(:storyline, :revision => revision)
    chapter = create(:chapter, :storyline => storyline)
    create(:page, :chapter => chapter, :template => 'background_image')

    user = Dom::Admin::Page.sign_in_as(:editor)
    create(:membership, :entry => revision.entry, :user => user)

    visit(admin_entry_path(entry))
    Dom::Admin::EntryRevision.first.show_link.click

    expect(Dom::Page.find_by_template('background_image')).to be_present
  end
end


text:
package com.appleframework.orm.mybatis.pagehelper;

import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ResultMap;
import org.apache.ibatis.mapping.ResultMapping;

import java.util.ArrayList;
import java.util.List;

/**
 * 创建新的MappedStatement,主要是Count返回值int
 *
 * @author liuzh
 */
public class MSUtils implements Constant {
    private static final List<ResultMapping> EMPTY_RESULTMAPPING = new ArrayList<ResultMapping>(0);

    /**
     * 新建count查询和分页查询的MappedStatement
     *
     * @param ms
     * @return
     */
    public static MappedStatement newCountMappedStatement(MappedStatement ms) {
        MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), ms.getId() + "_COUNT", ms.getSqlSource(), ms.getSqlCommandType());
        builder.resource(ms.getResource());
        builder.fetchSize(ms.getFetchSize());
        builder.statementType(ms.getStatementType());
        builder.keyGenerator(ms.getKeyGenerator());
        if (ms.getKeyProperties() != null && ms.getKeyProperties().length != 0) {
            StringBuilder keyProperties = new StringBuilder();
            for (String keyProperty : ms.getKeyProperties()) {
                keyProperties.append(keyProperty).append(",");
            }
            keyProperties.delete(keyProperties.length() - 1, keyProperties.length());
            builder.keyProperty(keyProperties.toString());
        }
        builder.timeout(ms.getTimeout());
        builder.parameterMap(ms.getParameterMap());
        //count查询返回值int
        List<ResultMap> resultMaps = new ArrayList<ResultMap>();
        ResultMap resultMap = new ResultMap.Builder(ms.getConfiguration(), ms.getId(), int.class, EMPTY_RESULTMAPPING).build();
        resultMaps.add(resultMap);
        builder.resultMaps(resultMaps);
        builder.resultSetType(ms.getResultSetType());
        builder.cache(ms.getCache());
        builder.flushCacheRequired(ms.isFlushCacheRequired());
        builder.useCache(ms.isUseCache());

        return builder.build();
    }
}


text:
package namesgenerator

import (
	"testing"
)

type FalseChecker struct{}

func (n *FalseChecker) Exists(name string) bool {
	return false
}

type TrueChecker struct{}

func (n *TrueChecker) Exists(name string) bool {
	return true
}

func TestGenerateRandomName(t *testing.T) {
	if _, err := GenerateRandomName(&FalseChecker{}); err != nil {
		t.Error(err)
	}

	if _, err := GenerateRandomName(&TrueChecker{}); err == nil {
		t.Error("An error was expected")
	}

}


text:
function Method
{
	(New-Object -TypeName System.Object)
}


text:
var colorSelected       = 0xFFA500ff;
var colorNonSelected    = 0x009ee8;
QueryResult = new Mongo.Collection("resultHDT"); //FIXME : tabular

/*$('.row .btn').on('click', function(e) {
    e.preventDefault();
    var $this = $(this);
    var $collapse = $this.closest('.collapse-group').find('collapse');
    $collapse.collapse('toggle');
    console.log("TOTO");
});*/

Template.visuVivaGraphGlobal.rendered = function() {
    //onLoad();
    //Session.set("vivagraphjs", true);
    pixelOnLoad();
    Session.set("vivagraphjs", false);
};

function pixelOnLoad() {
    if (typeof(App.graph) == "undefined") {
        App.graph = ngraphgraph();
        console.log(App.graph);

        App.graph.addLink(1,2);

        var pixelRender = ngraphpixel;
        App.renderer = pixelRender(App.graph, {
            container: document.getElementById('graph-container')
        });

        App.addCurrentNodeSettings = createNodeSettings;
        App.settingsView = configpixel(App.renderer);
        App.gui = App.settingsView.gui();
        App.nodeSettings = App.addCurrentNodeSettings(App.gui, App.renderer);

        App.renderer.on('nodehover', showNodeDetailsHover);
        App.renderer.on('nodeclick', showNodeDetailsClick);

        console.log(App.renderer);
    }
}

function showNodeDetailsHover(node) {
    if (typeof(node) != "undefined") {
        if (!freeze) {
            updateMetaNode(node);
            App.nodeSettings.id = node.id;
            App.nodeSettings.color = App.renderer.nodeColor(node.id);
            App.nodeSettings.size = App.renderer.nodeSize(node.id);

            var freeze = Session.get("freezeNodeSelection");
            updateRessourceURL(node.id);
            App.nodeSettings.url = Session.get("URLRessource");

            var layout = App.renderer.layout();
            if (layout && layout.pinNode) {
                App.nodeSettings.isPinned = layout.pinNode(node.id);
            }
            App.gui.update();
        }
    }
}
function showNodeDetailsClick(node) {
    Session.set("freezeNodeSelection", !Session.get("freezeNodeSelection"));
    updateMetaNode(node);
    updateRessourceURL(node.id);

    showNodeDetailsHover(node);
}

function createNodeSettings(gui, renderer) {
    var nodeSettings = gui.addFolder('Current Node');
    var currentNode = {
        id: '',
        url: '',
        color: 0,
        size: 0,
        isPinned: false
    };

    nodeSettings.add(currentNode,'id');
    nodeSettings.add(currentNode, 'url');
    nodeSettings.addColor(currentNode, 'color').onChange(setColor);
    nodeSettings.add(currentNode, 'size', 0, 200).onChange(setSize);
    nodeSettings.add(currentNode, 'isPinned').onChange(setPinned);

    return currentNode;

    function setColor(){
        if (currentNode.id) {
            renderer.nodeColor(currentNode.id, currentNode.color);
            renderer.focus();
        }
    }

    function setSize() {
        if (currentNode.id) {
            renderer.nodeSize(currentNode.id, currentNode.size);
            renderer.focus();
        }
    }

    function setPinned() {
        if (!currentNode.id) return;

        var layout = renderer.layout();
        if (layout.pinNode) {
            layout.pinNode(currentNode.id, currentNode.isPinned);
        } else {
            currentNode.isPinned = false;
            gui.update();
        }
        renderer.focus();
    }
}

Template.visualisation.helpers({
    queryResult: function () {
        return QueryResult.find({});
    },
    settingsTable: function () {
        return {
            collection: QueryResult,
            rowsPerPage: 10,
            showFilter: true,
            //fields: ['subject', 'predicate', 'object']
        };
    },
    listPredicate: function(){
        return Session.get('listPredicates');
    },
    URLRessource: function() {
        return Session.get('URLRessource');
    }, vivagraphjs: function() {
        return Session.get('vivagraphjs');
    }
});

Template.visualisation.events({
    "click button[value=renderQuery]": function(event, t) {
        event.preventDefault();
        //var query = t.$('textarea[name=querySparql]')[0].value;
        var query = Session.get("queryUserSPARQL");

        var sparqlChooser1 = t.$('input[name=selectSPARQL]')[0].checked;
        var sparqlChooser2 = t.$('input[name=selectSPARQL]')[1].checked;

        if (sparqlChooser1) {
            Meteor.call('querySelectMarmotta', query, function(errors, results) {
                var settings = {
                    dataset: results.results.bindings,
                    graph: App.graph,
                    extend: true
                }
                //loadNewGraph(settings);
                extendGraph(settings);
                console.log(settings);
            });
        } else if(sparqlChooser2) {
            Meteor.call('querySelectFuseki', query, function(errors, results) {
                console.log(results.head.vars); // FIXME : may be useful to use these headers for object/subject
                var settings = {
                    dataset: results.results.bindings,
                    extend: false
                }
                loadNewGraph(settings);
            });
        }
   }, "click button[id=loadRandomGraph]":function() {
        loadRandomGraph();
    }, "click button[id=toggleRender]":function() {
        if ($('#toggleRender')[0].value == "pause") {
            $('#toggleRender')[0].value = 'resume';
            $('#toggleRender')[0].innerHTML = 'Resume render';
            pauseRender();
        }
        else if ($('#toggleRender')[0].value == "resume") {
            $('#toggleRender')[0].value = 'pause';
            $('#toggleRender')[0].innerHTML = 'Pause render';
            resumeRender();
        }
    }, "click button[id=toggleFreeze]":function() {
        event.preventDefault();
        // Already set by cliking on a node
        /*if ($('#toggleFreeze')[0].value == "unfreezed") {
            $('#toggleFreeze')[0].value = 'freezed';
            $('#toggleFreeze')[0].innerHTML = 'Release the node selected';
            Session.set('freezeNodeSelection', true);
        }
        else*/
        releaseNodeSelection();
    }, "click button[id=cutSelection]":function() {
        event.preventDefault();
        App.graph.forEachNode(function(node) {
            var nodeUI = App.graphics.getNodeUI(node.id);
            if (nodeUI.color == colorSelected)
                App.graph.removeNode(node.id);
            App.renderer.rerender();
        });
    }, "click button[id=keepSelection]":function() {
        event.preventDefault();

        App.graph.forEachNode(function(node) {
            var nodeUI = App.graphics.getNodeUI(node.id);
            if (nodeUI.color == colorNonSelected)
                App.graph.removeNode(node.id);
            App.renderer.rerender();
        });
    }
});

function releaseNodeSelection() {
    if ($('#toggleFreeze')[0].value == "freezed") {
        $('#toggleFreeze')[0].value = 'unfreezed';
        $('#toggleFreeze')[0].innerHTML = 'No node selected';
        Session.set('freezeNodeSelection', false);
        uncheckNode();
    }
}
function pauseRender() {
    App.renderer.pause();
}
function resumeRender() {
    App.renderer.resume();
}
function storeResultsFull(settings) {
    var dataset = settings.dataset;
    //console.log(dataset);

    QueryResult._collection.remove({});
    for (var cur in dataset)
        QueryResult._collection.insert({
            subject: dataset[cur].subject,
            predicate: dataset[cur].predicate,
            object: dataset[cur].object
        });
    //QueryResult.batchInsert(dataset);
}

App = {};

function filterResultByURI(subject, object) { //don't care about order
    // For now, we filter on the dbpedia
    var t1 = "undefined";
    var t2 = "undefined";
    if (typeof(subject) != "undefined")
        t1 = subject;
    if (typeof(object) != "undefined")
        t2 = object;

    var filters = Session.get("filtersURI");
    if (typeof(filters) == "undefined")
        filters = ['http://dbpedia.org/resource/'];

    for (var cur in filters)
        if ((t1.search(filters[cur]) != -1) || t2.search(filters[cur]) != -1)
            return false;
    return true;
}

function newGraphFromDataset(settings){
    var COLOR = Math.random() * 0xFFFFFF | 0;
    var i = 0;
    var dataset = settings.dataset;
    var root = settings.root;

    var resG;
    if (settings.extend)
        resG = settings.graph;
    else
        resG = Viva.Graph.graph();
        //resG = ngraphgraph();

    if (typeof(root) != "undefined") {
        resG.addNode(root);
        if (dataset.length > 0) {
            var tmpObject = dataset[0].object;
            if (typeof(tmpObject) != "undefined")
                for (var cur in dataset) {
                    var object = dataset[cur].object.value;
                    if (filterResultByURI(object)) {
                        resG.addNode(object);
                        resG.addLink(root, object);

                        App.renderer.nodeColor(object, COLOR);
                        i++;
                    }
                }
            else {
                //impossible :
                // subject is the 'root'
                // predicate may be null
                // object is defined
                //resG.addNode('ROOT');
            }
        } else {
            //resG.addNode('ROOT');
            //resG.addLink(root, 'ROOT');
        }
    } else if (dataset.length > 0) {
        var tmpObject = dataset[0].object;
        var tmpSubject = dataset[0].subject;
        if (typeof(tmpObject) != "undefined")
            if (typeof(tmpSubject) != "undefined")
                // <Subject, predicate?, Object>
                for (var cur in dataset) {
                    var subject = dataset[cur].subject.value;
                    var object = dataset[cur].object.value;
                    if (filterResultByURI(subject, object)) {
                        resG.addNode(object);
                        resG.addNode(subject);
                        resG.addLink(subject, object);

                        App.renderer.nodeColor(subject, COLOR);
                        App.renderer.nodeColor(object, COLOR);
                        i += 2;
                    }
                }
            else {
                // <Subject?, predicate?, Object>
                tmpSubject = "rootSubject"; // FIXME : get the real value from SPARQL query
                resG.addNode(tmpSubject);
                for (var cur in dataset) {
                    var object = dataset[cur].object.value;
                    if (filterResultByURI(subject, object)) {
                        resG.addNode(object);
                        resG.addLink(tmpSubject, object);

                        App.renderer.nodeColor(object, COLOR);
                        i++;
                    }
                }
            }
        else {
            if (typeof(tmpSubject) != "undefined") {
                // <Subject, predicate?, Object?>
                tmpObject = "rootObject"; // FIXME : get the real value from SPARQL query
                resG.addNode(tmpObject);
                for (var cur in dataset) {
                    var subject = dataset[cur].subject.value;
                    if (filterResultByURI(subject)) {
                        resG.addNode(subject);
                        resG.addLink(tmpObject, subject);

                        App.renderer.nodeColor(subject, COLOR);
                        i++;
                    }
                }
            } else {
                // <Subject?, predicate?, Object?>
                // error ?
                //root = "toto";
                //resG.addNode('ROOT');
                //resG.addLink(root, 'ROOT');
            }
        }
    } else {
        //root = "toto";
        //resG.addNode('ROOT');
        //resG.addLink(root, 'ROOT');
    }
    console.log(i);
    var COLOR_A = Math.random() * 0xFFFFFF | 0;
    resG.forEachNode(function(node){
        var tmp = node.id;
        if (typeof(tmp) == "number") return;
        if (tmp.search("http://alignmentsGraph") != -1)
            App.renderer.nodeColor(node.id, COLOR_A);
    });
    return resG;
}

function onLoad() {
    App.graphGenerator = Viva.Graph.generator();
    App.graph = App.graphGenerator.grid(50, 10);
//Def values
//    App.layout = Viva.Graph.Layout.forceDirected(App.graph, {
//        springLength : 30,
//        springCoeff: 0.0008,
//        gravity : -1.2,
//        theta : 0.8,
//        dragCoeff : 0.02,
//        timeStep : 20
//    });

    App.layout = Viva.Graph.Layout.forceDirected(App.graph, {
        springLength : 80,
        springCoeff: 0.0008,
        gravity : -8,
        theta : 0.4,
        dragCoeff : 0.09,
        timeStep : 15
    });

    App.graphics = Viva.Graph.View.webglGraphics();

    var circleNode = buildCircleNodeShader();
    App.graphics.setNodeProgram(circleNode);

    var nodeSize = 12;
    var nodeColor = 0x009ee8;

    App.graphics.node(function (node) {
        return new WebglCircle(nodeSize, nodeColor);
    });

    App.renderer = Viva.Graph.View.renderer(App.graph, {
        layout: App.layout, // FIXME
        graphics: App.graphics,
        renderLinks: true,
        prerender: true,
        container: document.getElementById('graph-container')
    });

    var events = Viva.Graph.webglInputEvents(App.graphics, App.graph);
    events.mouseEnter(function (node) {
        console.log('Mouse entered node: ' + node.id);

        var freeze = Session.get("freezeNodeSelection");
        if (!freeze) {
            updateMetaNode(node);
            updateRessourceURL(node.id);
        }
    }).mouseLeave(function (node) {
        console.log('Mouse left node: ' + node.id);
    }).dblClick(function (node) {
        console.log('Double click on node: ' + node.id);
    }).click(function (node) {
        console.log('Single click on node: ' + node.id);
        var currentNodeColor  = getNodeColor(node);

        if (currentNodeColor == colorSelected) {
            // Click on the same node again
            // Extend node by predicate choosen by UI
            //
            // SELECT ?predicate (COUNT(DISTINCT ?object) AS ?nb_object)
            // WHERE {
            //  <node.id> <predicateUI[x]> ?object .
            // }
            // GROUP BY ?predicate

            var predicateUI = $('select[name=predicateC]')[0];
            predicateUI = predicateUI[predicateUI.selectedIndex];
            if (typeof(predicateUI) != "undefined") {
                predicateUI = predicateUI.value;

                var sparqlChooser1 = $('input[name=selectSPARQL]')[0].checked;
                var sparqlChooser2 = $('input[name=selectSPARQL]')[1].checked;
                var query =
                    "PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema#>"+
                    "SELECT *"+
                    " WHERE {"+
                    "<"+node.id+"> <"+predicateUI+"> ?object" +
                    "}";
                console.log(query);
                if (sparqlChooser1) {
                    Meteor.call('querySelectMarmotta', query, function(errors, results) {
                        var settings = {
                            dataset: results.results.bindings,
                            root: node.id,
                            extend: true,
                            graph: App.graph
                        }
                        extendGraph(settings);
                        releaseNodeSelection();
                        App.renderer.rerender();
                    });
                } else if(sparqlChooser2) {
                    Meteor.call('querySelectFuseki', query, function(errors, results) {
                        var settings = {
                            dataset: results.results.bindings,
                            root: node.id,
                            extend: true,
                            graph: App.graph
                        }
                        extendGraph(settings);
                        releaseNodeSelection();
                        App.renderer.rerender();
                    });
                }
            }
        } else {
            // First click on the node, unckeck previously checked node
            // --> freeze the selection to freeze the metaNode UI.
            // for now : temporary button to 'release' the selection
            var current  = Session.get("currentNodeSelected");
            updateMetaNode(node);
            updateRessourceURL(node.id);
            uncheckNode(node);
            if (typeof(current) != "undefined" && currentNodeColor != colorSelected)
                setNodeColor(current, colorNonSelected);
            current = Session.get("currentNodeSelected");
            setNodeColor(current, colorSelected);

            var freezeNodeSelection = Session.get('freezeNodeSelection');
            if (typeof(freezeNodeSelection) == 'undefined' || !freezeNodeSelection)
                if ($('#toggleFreeze')[0].value == 'unfreezed') {
                    $('#toggleFreeze')[0].value = 'freezed';
                    $('#toggleFreeze')[0].innerHTML = 'Release the node selected';
                    Session.set('freezeNodeSelection', true);
                }
            App.renderer.rerender();
        }
    });
    var multiSelectOverlay;
    App.renderer.run();

    document.addEventListener('keydown', function(e) {
        if (e.which === 16 && !multiSelectOverlay) { // shift key
            multiSelectOverlay = startMultiSelect(App.graph, App.renderer, App.layout);
        }
    });
    document.addEventListener('keyup', function(e) {
        if (e.which === 16 && multiSelectOverlay) {
            multiSelectOverlay.destroy();
            multiSelectOverlay = null;
        }
    });
}
function updateMetaNode(node) {
    var metaNode = $('textarea[name=tmpMetaNode]');

    var res = "" + node.id +  "\n";
    metaNode.val(res);

    var sparqlChooser1 = $('input[name=selectSPARQL]')[0].checked;
    var sparqlChooser2 = $('input[name=selectSPARQL]')[1].checked;
    var query = "";

    if (!nodeIsIndividual(node.id))
        query = "SELECT ?predicate (COUNT(DISTINCT ?object) AS ?nb_object)"+
            "WHERE {"+
            '<'+node.id+"> ?predicate ?object"+
            "}"+
            "GROUP BY ?predicate";
    else
        query = "SELECT ?predicate (COUNT(DISTINCT ?object) AS ?nb_object)"+
            "WHERE {"+
            "?subject ?predicate ?name."+
            "FILTER (STR(?name)='"+node.id+"')"+
            "}"+
            "GROUP BY ?predicate";

    if (sparqlChooser1)
        Meteor.call('querySelectMarmotta', query, function(errors, results) {
            updateMetaRes(results.results.bindings, metaNode);
        });
    else if(sparqlChooser2)
        Meteor.call('querySelectFuseki', query, function(errors, results) {
            updateMetaRes(results.results.bindings, metaNode);
        });

    function updateMetaRes(results, metaNode) {
        var predicates = [];
        for (var cur in results)
            if (typeof(results[cur].predicate) != "undefined")
                predicates.push(results[cur].predicate.value);
        Session.set('listPredicates', predicates);
    }
}

function updateRessourceURL(node) {
    Meteor.call('testIfRessourceFromRepo', node, function(err, results) {
        Session.set('URLRessource', results);
    });
}
function uncheckNode(node) {
    var nodeTo;
    if (typeof(node) != "undefined")
        nodeTo = node;
    else
        nodeTo = "UNCHECKED";

    var current  = Session.get("currentNodeSelected");
    var previous = Session.get("previousNodeSelected");
    if (typeof(previous) == "undefined")
        Session.set("previousNodeSelected", nodeTo);
    else
        Session.set("previousNodeSelected", current);

    if (typeof(current) != "undefined")
        if (current != nodeTo)
            setNodeColor(current, colorNonSelected);

    Session.set("currentNodeSelected", nodeTo);

    //FIXME ? case if we do a rectangular selection
    App.graph.forEachNode(function clear(node) {
        var nodeUI = App.graphics.getNodeUI(node.id);
        nodeUI.color = colorNonSelected;
    });
}
function setNodeColor(node, color) {
    console.log(node);
    var nodeUII = App.graphics.getNodeUI(node.id);
    if (typeof(nodeUII) != "undefined")
        nodeUII.color = color;
}
function getNodeColor(node) {
    var nodeUII = App.graphics.getNodeUI(node.id);
    return nodeUII.color;
}
function nodeIsIndividual(nodeName) {
    // TODO Blank nodes are not supported for the moment
    if (nodeName.search("http://") == -1)
        //if (nodeName.search("genid-start-") == -1) // Only from HDT/Fuseki SPARQL endpoint
            if (testIfIndividualBySPARQL())
                return true;
    return false;

    function testIfIndividualBySPARQL() { // Marmotta
        // an object can begin with _:
        // so : _:node can be an object
        // as in _:14e481d5eebd6
        // SELECT *
        // WHERE {
        //  _:14e67b500b833a ?predicate ?object
        // }
        // LIMIT 10
        //
        // TODO TODO
        return true; // Test if 'node' is individual or entity via SPARQL query
    }
}
function loadRandomGraph() {
    App.graph.clear();
    var newGraph = App.graphGenerator.grid(Math.random() * 20 |0 , Math.random() * 20 |0);
    copyGraph(newGraph, App.graph);
}
function loadNewGraph(settings) {
    App.graph.clear();
    var newGraph = newGraphFromDataset(settings);
    copyGraph(newGraph, App.graph);

    console.log(App.renderer.layout());
    precompute(5000);
    App.renderer.focus();
    //App.renderer.autofit();

    function precompute(iterations) {
        var i = 0;
        while(iterations > 0 && i <40) {
            App.renderer.layout().step();
            iterations--;
            i++;
        }
        if (iterations > 0) {
            if (!App.renderer.stable())
                setTimeout(function(){
                    precompute(iterations);
                }, 0);
        }
    }
}
function extendGraph(settings) {
    //settings.extend=true;
    newGraphFromDataset(settings);

    precompute(5000);
    App.renderer.focus();
    //App.renderer.autofit();

    function precompute(iterations) {
        var i = 0;
        while(iterations > 0 && i <40) {
            App.renderer.layout().step();
            iterations--;
            i++;
        }
        if (iterations > 0) {
            if (!App.renderer.stable())
                setTimeout(function(){
                    precompute(iterations);
                }, 0);
        }
    }
}
function copyGraph(from, to) {
    to.beginUpdate();
    from.forEachLink(copyLink);
    to.endUpdate();
    function copyLink(link) {
        to.addLink(link.fromId, link.toId);
    }
}
function WebglCircle(size, color) {
    this.size = size;
    this.color = color;
}
function buildCircleNodeShader() {
    var ATTRIBUTES_PER_PRIMITIVE = 4,
        nodesFS = [
            'precision mediump float;',
        'varying vec4 color;',
        'void main(void) {',
            '   if ((gl_PointCoord.x - 0.5) * (gl_PointCoord.x - 0.5) + (gl_PointCoord.y - 0.5) * (gl_PointCoord.y - 0.5) < 0.25) {',
                '     gl_FragColor = color;',
                '   } else {',
                    '     gl_FragColor = vec4(0);',
                    '   }',
                '}'].join('\n'),
                nodesVS = [
                    'attribute vec2 a_vertexPos;',
                // Pack clor and size into vector. First elemnt is color, second - size.
                // Since it's floating point we can only use 24 bit to pack colors...
                // thus alpha channel is dropped, and is always assumed to be 1.
                'attribute vec2 a_customAttributes;',
                'uniform vec2 u_screenSize;',
                'uniform mat4 u_transform;',
                'varying vec4 color;',
                'void main(void) {',
                    '   gl_Position = u_transform * vec4(a_vertexPos/u_screenSize, 0, 1);',
                    '   gl_PointSize = a_customAttributes[1] * u_transform[0][0];',
                    '   float c = a_customAttributes[0];',
                    '   color.b = mod(c, 256.0); c = floor(c/256.0);',
                    '   color.g = mod(c, 256.0); c = floor(c/256.0);',
                    '   color.r = mod(c, 256.0); c = floor(c/256.0); color /= 255.0;',
                    '   color.a = 1.0;',
                    '}'].join('\n');
                    var program,
                        gl,
                        buffer,
                        locations,
                        utils,
                        nodes = new Float32Array(64),
                        nodesCount = 0,
                        canvasWidth, canvasHeight, transform,
                        isCanvasDirty;
                    return {
                        /**
                         * Called by webgl renderer to load the shader into gl context.
                         */
                        load : function (glContext) {
                            gl = glContext;
                            webglUtils = Viva.Graph.webgl(glContext);
                            program = webglUtils.createProgram(nodesVS, nodesFS);
                            gl.useProgram(program);
                            locations = webglUtils.getLocations(program, ['a_vertexPos', 'a_customAttributes', 'u_screenSize', 'u_transform']);
                            gl.enableVertexAttribArray(locations.vertexPos);
                            gl.enableVertexAttribArray(locations.customAttributes);
                            buffer = gl.createBuffer();
                        },
                             /**
                              * Called by webgl renderer to update node position in the buffer array
                              *
                              * @param nodeUI - data model for the rendered node (WebGLCircle in this case)
                              * @param pos - {x, y} coordinates of the node.
                              */
                             position : function (nodeUI, pos) {
                                 var idx = nodeUI.id;
                                 nodes[idx * ATTRIBUTES_PER_PRIMITIVE] = pos.x;
                                 nodes[idx * ATTRIBUTES_PER_PRIMITIVE + 1] = pos.y;
                                 nodes[idx * ATTRIBUTES_PER_PRIMITIVE + 2] = nodeUI.color;
                                 nodes[idx * ATTRIBUTES_PER_PRIMITIVE + 3] = nodeUI.size;
                             },
                             /**
                              * Request from webgl renderer to actually draw our stuff into the
                              * gl context. This is the core of our shader.
                              */
                             render : function() {
                                 gl.useProgram(program);
                                 gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
                                 gl.bufferData(gl.ARRAY_BUFFER, nodes, gl.DYNAMIC_DRAW);
                                 if (isCanvasDirty) {
                                     isCanvasDirty = false;
                                     gl.uniformMatrix4fv(locations.transform, false, transform);
                                     gl.uniform2f(locations.screenSize, canvasWidth, canvasHeight);
                                 }
                                 gl.vertexAttribPointer(locations.vertexPos, 2, gl.FLOAT, false, ATTRIBUTES_PER_PRIMITIVE * Float32Array.BYTES_PER_ELEMENT, 0);
                                 gl.vertexAttribPointer(locations.customAttributes, 2, gl.FLOAT, false, ATTRIBUTES_PER_PRIMITIVE * Float32Array.BYTES_PER_ELEMENT, 2 * 4);
                                 gl.drawArrays(gl.POINTS, 0, nodesCount);
                             },
                             /**
                              * Called by webgl renderer when user scales/pans the canvas with nodes.
                              */
                             updateTransform : function (newTransform) {
                                 transform = newTransform;
                                 isCanvasDirty = true;
                             },
                             /**
                              * Called by webgl renderer when user resizes the canvas with nodes.
                              */
                             updateSize : function (newCanvasWidth, newCanvasHeight) {
                                 canvasWidth = newCanvasWidth;
                                 canvasHeight = newCanvasHeight;
                                 isCanvasDirty = true;
                             },
                             /**
                              * Called by webgl renderer to notify us that the new node was created in the graph
                              */
                             createNode : function (node) {
                                 nodes = webglUtils.extendArray(nodes, nodesCount, ATTRIBUTES_PER_PRIMITIVE);
                                 nodesCount += 1;
                             },
                             /**
                              * Called by webgl renderer to notify us that the node was removed from the graph
                              */
                             removeNode : function (node) {
                                 if (nodesCount > 0) { nodesCount -=1; }
                                 if (node.id < nodesCount && nodesCount > 0) {
                                     // we do not really delete anything from the buffer.
                                     // Instead we swap deleted node with the "last" node in the
                                     // buffer and decrease marker of the "last" node. Gives nice O(1)
                                     // performance, but make code slightly harder than it could be:
                                     webglUtils.copyArrayPart(nodes, node.id*ATTRIBUTES_PER_PRIMITIVE, nodesCount*ATTRIBUTES_PER_PRIMITIVE, ATTRIBUTES_PER_PRIMITIVE);
                                 }
                             },
                             /**
                              * This method is called by webgl renderer when it changes parts of its
                              * buffers. We don't use it here, but it's needed by API (see the comment
                              * in the removeNode() method)
                              */
                             replaceProperties : function(replacedNode, newNode) {},
                    };
                }

            function startMultiSelect(graph, renderer, layout) {
                var graphics = renderer.getGraphics();
                var domOverlay = document.querySelector('.graph-overlay');
                var overlay = createOverlay(domOverlay);
                overlay.onAreaSelected(handleAreaSelected);

                return overlay;

                function handleAreaSelected(area) {
                    // For the sake of this demo we are using silly O(n) implementation.
                    // Could be improved with spatial indexing if required.
                    var topLeft = graphics.transformClientToGraphCoordinates({
                        x: area.x,
                        y: area.y
                    });

                    var bottomRight = graphics.transformClientToGraphCoordinates({
                        x: area.x + area.width,
                        y: area.y + area.height
                    });

                    graph.forEachNode(higlightIfInside);
                    renderer.rerender();

                    return;

                    function higlightIfInside(node) {
                        var nodeUI = graphics.getNodeUI(node.id);
                        if (isInside(node.id, topLeft, bottomRight)) {
                            nodeUI.color = colorSelected; //0xFFA500ff;
                            nodeUI.size = 10;
                        } else {
                            nodeUI.color = colorNonSelected;//0x009ee8ff;
                            nodeUI.size = 10;
                        }
                    }

                    function isInside(nodeId, topLeft, bottomRight) {
                        var nodePos = layout.getNodePosition(nodeId);
                        return (topLeft.x < nodePos.x && nodePos.x < bottomRight.x &&
                                topLeft.y < nodePos.y && nodePos.y < bottomRight.y);
                    }
                }
            }
            function createOverlay(overlayDom) {
                var selectionClasName = 'graph-selection-indicator';
                var selectionIndicator = overlayDom.querySelector('.' + selectionClasName);
                if (!selectionIndicator) {
                    selectionIndicator = document.createElement('div');
                    selectionIndicator.className = selectionClasName;
                    overlayDom.appendChild(selectionIndicator);
                }

                var notify = [];
                var dragndrop = Viva.Graph.Utils.dragndrop(overlayDom);
                var selectedArea = {
                    x: 0,
                    y: 0,
                    width: 0,
                    height: 0
                };
                var startX = 0;
                var startY = 0;

                dragndrop.onStart(function(e) {
                    startX = selectedArea.x = e.clientX;
                    startY = selectedArea.y = e.clientY;
                    selectedArea.width = selectedArea.height = 0;

                    updateSelectedAreaIndicator();
                    selectionIndicator.style.display = 'block';
                });

                dragndrop.onDrag(function(e) {
                    recalculateSelectedArea(e);
                    updateSelectedAreaIndicator();
                    notifyAreaSelected();
                });

                dragndrop.onStop(function() {
                    selectionIndicator.style.display = 'none';
                });

                overlayDom.style.display = 'block';
                return {
                    onAreaSelected: function(cb) {
                        notify.push(cb);
                    },
                        destroy: function () {
                            overlayDom.style.display = 'none';
                            dragndrop.release();
                        }
                };

                function notifyAreaSelected() {
                    notify.forEach(function(cb) {
                        cb(selectedArea);
                    });
                }

                function recalculateSelectedArea(e) {
                    selectedArea.width = Math.abs(e.clientX - startX);
                    selectedArea.height = Math.abs(e.clientY - startY);
                    selectedArea.x = Math.min(e.clientX, startX);
                    selectedArea.y = Math.min(e.clientY, startY);
                }

                function updateSelectedAreaIndicator() {
                    selectionIndicator.style.left = selectedArea.x + 'px';
                    selectionIndicator.style.top = selectedArea.y + 'px';
                    selectionIndicator.style.width = selectedArea.width + 'px';
                    selectionIndicator.style.height = selectedArea.height + 'px';
                }
            }


text:
module('Autoplay tests');

function FakeClock() {
	// Instantiate a new controllable clock which overrides the built in Date
	// class on construction.
	var value = 1;

	this.tick = function(duration) {
		value += duration;
	};
	// TODO: This is broken and has to be fixed in the near future
	this.Date = function() {
		this.getTime = function() {
			return value;
		}
	}
}

function change_timeout(autoplay, first, second, wait) {
	var clock = new FakeClock();

	// This is a helper function to test multiple consecutive play calls with
	// different timeout values. Four steps will be completed by this function:

	// 1. The autoplay will be played in a stopped state with the first timeout.
	autoplay.stop();
	autoplay.play(first);

	// 2. Time will be forwarded a given wait time.
	clock.tick(wait);

	// 3. The autoplay will be paused.
	autoplay.pause();

	// 4. The autoplay will be played with the second timeout.
	autoplay.play(second);
}

// test('stopping the autoplay timer', function() {
// 	expect(2);
//
// 	var clock = new FakeClock();
//
// 	var carousel = $('#simple').owlCarousel().data('owl.carousel');
// 	var autoplay = carousel._plugins.autoplay;
//
// 	clock.tick(1);
//
// 	autoplay.stop();
// 	autoplay.play();
//
// 	equal(autoplay.read(), 0);
//
// 	autoplay.pause();
// 	autoplay.play();
//
// 	equal(autoplay.read(), 0);
// });
// TODO: See todo above, seems to be broken since a while as we are trying to assign the global const Date to a new function
// test('changing autoplay timeout values', function() {
// 	expect(4);
//
// 	var carousel = $('#simple').owlCarousel().data('owl.carousel');
// 	var autoplay = carousel._plugins.autoplay;
//
// 	// Changing the timeout from 2000 to 3000 after 3000 ticks should maintain
// 	// the elapsed time (1000) since the last transition.
// 	change_timeout(autoplay, 2000, 3000, 3000);
// 	equal(autoplay.read() % 3000, 1000);
//
// 	// Changing the timeout from 4000 to 5000 after 12000 ticks should maintain
// 	// the elapsed time (0) since the last transition.
// 	change_timeout(autoplay, 4000, 5000, 12000);
// 	equal(autoplay.read() % 5000, 0);
//
// 	// Changing the timeout from 5000 to 4000 after 12000 ticks should maintain
// 	// the elapsed time (2000) since the last transition.
// 	change_timeout(autoplay, 5000, 4000, 12000);
// 	equal(autoplay.read() % 4000, 2000);
//
// 	// Changing the timeout from 11000 to 6000 after 19000 ticks should reset
// 	// the elapsed timer value (7000) since the last transition to 0, because
// 	// it is larger than the timeout value.
// 	change_timeout(autoplay, 11000, 6000, 19000);
// 	equal(autoplay.read() % 6000, 0);
// });


text:
package gov.nasa.worldwind.formats.rpf;

import gov.nasa.worldwind.formats.nitfs.NITFSUtil;

/**
 * @author Lado Garakanidze
 * @version $Id: RPFHeaderSection.java 1171 2013-02-11 21:45:02Z dcollins $
 */
class RPFHeaderSection
{
    public static final String DATA_TAG = "RPFHDR";

    public boolean  endianIndicator;
    public short    headerLength;
    public String   filename;
    public short    updateIndicator; // new | replacement | update
    public String   govSpecNumber;
    public String   govSpecDate;
    public String   securityClass;
    public String   securityCountryCode;
    public String   securityReleaseMark;
    public int      locationSectionLocation;

    public RPFHeaderSection(java.nio.ByteBuffer buffer)
    {
        this.endianIndicator = ((byte) 0 != buffer.get());         // reads 1 byte, 0 for big endian
        this.headerLength = buffer.getShort();                     // reads 2 bytes
        this.filename = NITFSUtil.getString(buffer, 12);
        this.updateIndicator = NITFSUtil.getByteAsShort(buffer);       // reads 1 byte (short)
        this.govSpecNumber = NITFSUtil.getString(buffer, 15);
        this.govSpecDate = NITFSUtil.getString(buffer, 8);
        this.securityClass = NITFSUtil.getString(buffer, 1);
        this.securityCountryCode = NITFSUtil.getString(buffer, 2);
        this.securityReleaseMark = NITFSUtil.getString(buffer, 2);
        this.locationSectionLocation = buffer.getInt();            // read 4 bytes (int)
    }
}


text:
/**
 * @author Aleksei V. Ivaschenko
 * @version $Revision: 1.2 $
 */

package org.apache.harmony.x.print;

import java.io.OutputStream;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.ServiceUIFactory;
import javax.print.StreamPrintService;
import javax.print.StreamPrintServiceFactory;
import javax.print.attribute.Attribute;
import javax.print.attribute.AttributeSet;
import javax.print.attribute.PrintServiceAttribute;
import javax.print.attribute.PrintServiceAttributeSet;
import javax.print.attribute.standard.ColorSupported;
import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.JobName;
import javax.print.attribute.standard.Media;
import javax.print.attribute.standard.MediaPrintableArea;
import javax.print.attribute.standard.MediaSizeName;
import javax.print.attribute.standard.Sides;
import javax.print.event.PrintServiceAttributeListener;

/*
 * Image2PSStreamPrintService
 */
public class All2PSStreamPrintService extends StreamPrintService {

    private static final String outputFormat = "application/postscript";
    private static final MediaSizeName mediaSizes[] = {
            MediaSizeName.ISO_A3,
            MediaSizeName.ISO_A4,
            MediaSizeName.ISO_A5};

    private static final Class supportedAttributeCategories[] = {
            ColorSupported.class,
            Copies.class,
            JobName.class,
            Media.class,
            MediaPrintableArea.class,
            Sides.class};

    private static final DocFlavor supportedDocFlavors[] = {
            DocFlavor.SERVICE_FORMATTED.PRINTABLE,
            DocFlavor.SERVICE_FORMATTED.PAGEABLE,
            DocFlavor.BYTE_ARRAY.GIF,
            DocFlavor.INPUT_STREAM.GIF,
            DocFlavor.URL.GIF,
            DocFlavor.BYTE_ARRAY.JPEG,
            DocFlavor.INPUT_STREAM.JPEG,
            DocFlavor.URL.JPEG,
            DocFlavor.BYTE_ARRAY.PNG,
            DocFlavor.INPUT_STREAM.PNG,
            DocFlavor.URL.PNG};

    public All2PSStreamPrintService(OutputStream outputstream,
            StreamPrintServiceFactory factory) {
        super(outputstream);
        if (factory == null) {
            throw new NullPointerException("factory is null");
        }
    }

     public String getOutputFormat() {
        return outputFormat;
    }

    public Class[] getSupportedAttributeCategories() {
        Class copy_supportedAttrCats[]
                     = new Class[supportedAttributeCategories.length];
        for (int i = 0; i < supportedAttributeCategories.length; i++) {
            copy_supportedAttrCats[i] = supportedAttributeCategories[i];
        }
        return copy_supportedAttrCats;
    }

    public boolean isAttributeCategorySupported(Class category) {
        if (category == null) {
            throw new NullPointerException("Argument category is null");
        }
        if (!(javax.print.attribute.Attribute.class).isAssignableFrom(category)) {
            throw new IllegalArgumentException(category.toString()
                    + " is not an Attribute");
        }

        for (int i = 0; i < supportedAttributeCategories.length; i++) {
            if (category.equals(supportedAttributeCategories[i]))
                return true;
        }
        return false;
    }

    public String getName() {
        return "Convert source to Postscript language";
    }

    public DocFlavor[] getSupportedDocFlavors() {
        DocFlavor copy_supportedDocFlavors[]
                       = new DocFlavor[supportedDocFlavors.length];
        for (int i = 0; i < supportedDocFlavors.length; i++) {
            copy_supportedDocFlavors[i] = supportedDocFlavors[i];
        }
        return copy_supportedDocFlavors;
    }

    public boolean isDocFlavorSupported(DocFlavor flavor) {
        if (flavor == null) {
            throw new NullPointerException("Argument flavor is null");
        }

        for(int i = 0; i < supportedDocFlavors.length; i++){
            if(flavor.equals(supportedDocFlavors[i]))
                return true;
            }
        return false;
    }

    public DocPrintJob createPrintJob() {
        return new All2PSDocPrintJob(this);
    }

    public int hashCode() {
        return getName().hashCode();
    }

    public boolean equals(Object obj) {
        return obj == this || (obj instanceof All2PSStreamPrintService)
            && ((All2PSStreamPrintService) obj).getName().equals(getName());
    }

    public ServiceUIFactory getServiceUIFactory() {
        return null;
    }
    /* methods below this line must be completed */

    public PrintServiceAttributeSet getAttributes() {
        return null;
    }

    public void addPrintServiceAttributeListener(
            PrintServiceAttributeListener arg0) {
    }

    public void removePrintServiceAttributeListener(
            PrintServiceAttributeListener arg0) {
    }

    public Object getDefaultAttributeValue(Class arg0) {
        return null;
    }

    public PrintServiceAttribute getAttribute(Class arg0) {
        return null;
    }

    public boolean isAttributeValueSupported(Attribute arg0, DocFlavor arg1,
            AttributeSet arg2) {
        return false;
    }

    public AttributeSet getUnsupportedAttributes(DocFlavor arg0,
            AttributeSet arg1) {
        return arg1;
    }

    public Object getSupportedAttributeValues(Class arg0, DocFlavor arg1,
            AttributeSet arg2) {
        return null;
    }

}


text:
class CStringSplite : public CStringList {

public:
	CString m_pSpt;   // the actual array of data

// Construction
	CStringSplite();
	CStringSplite(TCHAR *src);

// Operations
	void Splite(TCHAR *src);
	void Separator(TCHAR *scr);
	LPCTSTR operator[](int nIndex) const;

};
#endif	//__MYJ_CStringSplite_H__


text:
from setuptools import setup

setup(
    name='django-cacheops',
    version='1.3.1',
    author='Alexander Schepanovski',
    author_email='suor.web@gmail.com',

    description='A slick ORM cache with automatic granular event-driven invalidation for Django.',
    long_description=open('README.rst').read(),
    url='http://github.com/Suor/django-cacheops',
    license='BSD',

    packages=[
        'cacheops',
        'cacheops.management',
        'cacheops.management.commands',
        'cacheops.templatetags'
    ],
    install_requires=[
        'django>=1.2',
        'redis>=2.9.1',
        'simplejson>=2.2.0',
        'six>=1.4.0',
    ],

    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',

        'Framework :: Django',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ],

    zip_safe=False,
    include_package_data=True,
)


text:
<?php

namespace PHPCR\Shell\Test;

use Symfony\Component\Console\Application;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Output\StreamOutput;
use PHPCR\Shell\Console\Input\StringInput;
use PHPCR\Shell\Console\Application\ShellApplication;

/**
 * Eases the testing of console applications.
 *
 * When testing an application, don't forget to disable the auto exit flag:
 *
 *     $application = new Application();
 *     $application->setAutoExit(false);
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
class ApplicationTester
{
    private $application;
    private $shellApplication;
    private $input;
    private $output;
    private $lastExitCode;

    /**
     * Constructor.
     *
     * @param Application $application An Application instance to test.
     */
    public function __construct(Application $application, ShellApplication $shellApplication = null)
    {
        $this->output = new StreamOutput(fopen('php://memory', 'w', false));

        $this->application = $application;
        $this->shellApplication = $shellApplication;
    }

    /**
     * Executes the application.
     *
     * Available options:
     *
     *  * interactive: Sets the input interactive flag
     *  * decorated:   Sets the output decorated flag
     *  * verbosity:   Sets the output verbosity flag
     *
     * @param array $input   An array of arguments and options
     * @param array $options An array of options
     *
     * @return integer The command exit code
     */
    public function run(array $input, $options = array())
    {
        $this->input = new ArrayInput($input);

        if (isset($options['decorated'])) {
            $this->output->setDecorated($options['decorated']);
        }
        if (isset($options['verbosity'])) {
            $this->output->setVerbosity($options['verbosity']);
        }

        $this->application->setAutoExit(false);

        if ($this->shellApplication) {
            $this->shellApplication->setAutoExit(false);
        }
        $this->application->setCatchExceptions(false);

        return $this->application->run($this->input, $this->output);
    }

    /**
     * Gets the display returned by the last execution of the application.
     *
     * @param Boolean $normalize Whether to normalize end of lines to \n or not
     *
     * @return string The display
     */
    public function getDisplay($normalize = false)
    {
        rewind($this->output->getStream());

        $display = stream_get_contents($this->output->getStream());

        if ($normalize) {
            $display = str_replace(PHP_EOL, "\n", $display);
        }

        return $display;
    }

    public function getLastLine()
    {
        $display = trim($this->getDisplay());
        $lines = explode("\n", $display);

        if ($lines) {
            return end($lines);
        }

        return $display;
    }

    /**
     * Gets the input instance used by the last execution of the application.
     *
     * @return InputInterface The current input instance
     */
    public function getInput()
    {
        return $this->input;
    }

    /**
     * Gets the output instance used by the last execution of the application.
     *
     * @return OutputInterface The current output instance
     */
    public function getOutput()
    {
        return $this->output;
    }

    public function runShellCommand($command)
    {
        if ($this->shellApplication) {
            $ret = $this->shellApplication->run(new StringInput($command), $this->output);
        } else {
            $ret = $this->application->run(new StringInput($command), $this->output);
        }

        $this->lastExitCode = $ret;

        return $ret;
    }

    public function getLastExitCode()
    {
        return $this->lastExitCode;
    }
}


text:
namespace FastAndFurious.ConsoleApplication.Models.MotorVehicles
{
    using FastAndFurious.ConsoleApplication.Models.MotorVehicles.Abstract;

    /// <summary>
    /// 45999,1850000,280,50
    /// </summary>
    public class NissanSkylineR34 : MotorVehicle
    {
        public NissanSkylineR34()
            : base(45999, 1850000, 280, 50)
        {
        }
    }
}


text:
BPlusResult::BPlusResult(const bool &exist, const long &filePosition) : exist(exist), filePosition(filePosition) {
}

BPlusResult::operator const long & ()const {
	return filePosition;
}


text:
This project contains the [Appassembler Maven Plugin project](http://www.mojohaus.org/appassembler/).

[![Build Status](https://travis-ci.org/mojohaus/appassembler.svg?branch=master)](https://travis-ci.org/mojohaus/appassembler)


text:
import React from 'react';
import { compose, mapProps, withHandlers } from 'recompose';
import _ from 'lodash';

import { storiesOf } from '@storybook/react';
import { boolean, number } from '@storybook/addon-knobs';
import { MuiThemeProvider } from 'material-ui';
import { Collapse } from 'antd';

import { Accordion, AccordionItem, asAccordion, asAccordionItem } from '../../src/Accordion';

storiesOf('Accordion', module)
  .addDecorator(story => <MuiThemeProvider>{story()}</MuiThemeProvider>)
  .add('Accordion(mui)', () => {
    const wide = boolean('wide screen', false);
    const listSize = number('list size', 10);
    const animation = boolean('animation', true);
    const list = _.fill(Array(listSize), '1').map((value, index) => index + 1);

    return (

Accordion List

        <Accordion wide={wide}>
          {list.map(value => (
            <AccordionItem
              key={value}
              animation={animation}
              title={`title-${value}`}
            >
              {_.padEnd(`content-${value}: `, 300, 'blabla ')}
            </AccordionItem>
          ))}
        </Accordion>

    );
  })
  .add('antd', () => {
    const wide = boolean('wide screen', false);
    const animation = boolean('animation', true);
    const list = [1, 2, 3, 4, 5];

    const Container = compose(
      asAccordion,
      withHandlers({ onChange: ({ onActivate }) => key => onActivate(undefined, key) }),
    )(Collapse);

    const border = '1px solid #d9d9d9';
    const itemPropsMapper = ({
      activeKey, isLast, itemKey, expanded, style, ...rest
    }) => {
      const rootStyle = { ...style, border, borderBottom: 0 };

      if (isLast || expanded || activeKey - itemKey === 1) {
        rootStyle.borderBottom = border;
      }

      return {
        ...rest,
        isActive: expanded,
        style: rootStyle,
      };
    };

    const Item = compose(
      asAccordionItem,
      mapProps(itemPropsMapper),
    )(Collapse.Panel);

    return (

        <Container style={{ border: 0 }} accordion wide={wide}>
          {list.map(value => (
            <Item
              key={value}
              animation={animation}
              header={`title-${value}`}
            >
              {_.padEnd(`content-${value}: `, 300, 'blabla ')}
            </Item>
          ))}
        </Container>

    );
  });


text:
@implementation MyTuiGuangModel
-(id)initWithTuiGuangDic:(NSDictionary*)dic{
    self=[super init];
    if (self) {
        _imagename=[ToolClass isString:[NSString stringWithFormat:@"%@",[dic objectForKey:@""]]];
        _titlename=[ToolClass isString:[NSString stringWithFormat:@"%@",[dic objectForKey:@"name"]]];
        _phonename=[ToolClass isString:[NSString stringWithFormat:@"%@",[dic objectForKey:@"phone"]]];
        _yaoQingMa=[ToolClass isString:[NSString stringWithFormat:@"%@",[dic objectForKey:@"inviterSpreadCode"]]];
        _timename=[ToolClass isString:[NSString stringWithFormat:@"%@",[dic objectForKey:@"createTime"]]];
    }

    return self;
}
//我要兑换
-(id)initWithDuiHuanDic:(NSDictionary*)dic{
    self=[super init];
    if (self) {
        _dhimage=[ToolClass isString:[NSString stringWithFormat:@"%@",[dic objectForKey:@"filePath"]]];
        _dhTitle=[ToolClass isString:[NSString stringWithFormat:@"%@",[dic objectForKey:@"title"]]];
        _dhContent=[ToolClass isString:[NSString stringWithFormat:@"%@",[dic objectForKey:@"content"]]];
        _dhID=[ToolClass isString:[NSString stringWithFormat:@"%@",[dic objectForKey:@"id"]]];
    }

    return self;
}
@end


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace Clifton.Tools.Strings.Extensions
{
	public static class StringHelpersExtensions
	{
		public static bool IsInt32(this String src)
		{
			int result;
			bool ret = Int32.TryParse(src, out result);

			return ret;
		}

		public static string ParseQuote(this String src)
		{
			return src.Replace("\"", "'");
		}

		public static string Quote(this String src)
		{
			return "\"" + src + "\"";
		}

		public static string Brace(this String src)
		{
			return "[" + src + "]";
		}

		public static string Between(this String src, char c1, char c2)
		{
			return Clifton.Tools.Strings.StringHelpers.Between(src, c1, c2);
		}

		public static string Between(this String src, string s1, string s2)
		{
			return src.RightOf(s1).LeftOf(s2);
		}

		public static string RightOf(this String src, char c)
		{
			return Clifton.Tools.Strings.StringHelpers.RightOf(src, c);
		}

		public static bool BeginsWith(this String src, string s)
		{
			return src.StartsWith(s);
		}

		public static string RightOf(this String src, string s)
		{
			string ret = String.Empty;
			int idx = src.IndexOf(s);

			if (idx != -1)
			{
				ret = src.Substring(idx + s.Length);
			}

			return ret;
		}

		public static string RightOfRightmostOf(this String src, char c)
		{
			return Clifton.Tools.Strings.StringHelpers.RightOfRightmostOf(src, c);
		}

		public static string LeftOf(this String src, char c)
		{
			return Clifton.Tools.Strings.StringHelpers.LeftOf(src, c);
		}

		public static string LeftOf(this String src, string s)
		{
			string ret = s;
			int idx = src.IndexOf(s);

			if (idx != -1)
			{
				ret = src.Substring(0, idx);
			}

			return ret;
		}

		public static string LeftOfRightmostOf(this String src, char c)
		{
			return Clifton.Tools.Strings.StringHelpers.LeftOfRightmostOf(src, c);
		}

		public static string LeftOfRightmostOf(this String src, string s)
		{
			string ret = src;
			int idx = src.IndexOf(s);
			int idx2 = idx;

			while (idx2 != -1)
			{
				idx2 = src.IndexOf(s, idx + s.Length);

				if (idx2 != -1)
				{
					idx = idx2;
				}
			}

			if (idx != -1)
			{
				ret = src.Substring(0, idx);
			}

			return ret;
		}

		public static string RightOfRightmostOf(this String src, string s)
		{
			string ret = src;
			int idx = src.IndexOf(s);
			int idx2 = idx;

			while (idx2 != -1)
			{
				idx2 = src.IndexOf(s, idx + s.Length);

				if (idx2 != -1)
				{
					idx = idx2;
				}
			}

			if (idx != -1)
			{
				ret = src.Substring(idx + s.Length, src.Length - (idx + s.Length));
			}

			return ret;
		}

		public static char Rightmost(this String src)
		{
			return Clifton.Tools.Strings.StringHelpers.Rightmost(src);
		}

		public static string TrimLastChar(this String src)
		{
			string ret = String.Empty;
			int len = src.Length;

			if (len > 1)
			{
				ret = src.Substring(0, len - 1);
			}

			return ret;
		}

		public static bool IsBlank(this string src)
		{
			return String.IsNullOrEmpty(src) || (src.Trim()==String.Empty);
		}

		/// <summary>
		/// Returns the first occurance of any token given the list of tokens.
		/// </summary>
		public static string Contains(this String src, string[] tokens)
		{
			string ret = String.Empty;
			int firstIndex=9999;

			// Find the index of the first index encountered.
			foreach (string token in tokens)
			{
				int idx = src.IndexOf(token);

				if ( (idx != -1) && (idx < firstIndex) )
				{
					ret = token;
					firstIndex = idx;
				}
			}

			return ret;
		}

		public static int to_i(this string src)
		{
			return Convert.ToInt32(src);
		}

		public static bool to_b(this string src)
		{
			return Convert.ToBoolean(src);
		}

		public static T ToEnum<T>(this string src)
		{
			T enumVal = (T)Enum.Parse(typeof(T), src);

			return enumVal;
		}
	}
}