text:
package org.apache.ambari.server.state;

import com.google.common.base.Function;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import org.apache.ambari.server.api.services.AmbariMetaInfo;
import org.apache.ambari.server.stack.StackDirectory;
import org.apache.ambari.server.stack.Validable;
import org.apache.ambari.server.state.stack.MetricDefinition;
import org.apache.ambari.server.state.stack.StackRoleCommandOrder;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.map.annotate.JsonFilter;

import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlTransient;
import java.io.File;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

@XmlAccessorType(XmlAccessType.FIELD)
@JsonFilter("propertiesfilter")
public class ServiceInfo implements Validable{

  public static final AbstractMap.SimpleEntry<String, String> DEFAULT_SERVICE_INSTALLABLE_PROPERTY = new AbstractMap.SimpleEntry("installable", "true");
  public static final AbstractMap.SimpleEntry<String, String> DEFAULT_SERVICE_MANAGED_PROPERTY = new AbstractMap.SimpleEntry("managed", "true");
  public static final AbstractMap.SimpleEntry<String, String> DEFAULT_SERVICE_MONITORED_PROPERTY = new AbstractMap.SimpleEntry("monitored", "true");
  /**
   * Format version. Added at schema ver 2
   */
  @XmlTransient
  private String schemaVersion;

  private String name;
  private String displayName;
  private String version;
  private String comment;
  private String serviceType;
  private Selection selection;

  @XmlTransient
  private List<PropertyInfo> properties;

  @XmlElementWrapper(name="components")
  @XmlElements(@XmlElement(name="component"))
  private List<ComponentInfo> components;

  @XmlElement(name="deleted")
  private boolean isDeleted = false;

  @JsonIgnore
  @XmlTransient
  private volatile Map<String, Set<String>> configLayout = null;

  @XmlElementWrapper(name="configuration-dependencies")
  @XmlElement(name="config-type")
  private List<String> configDependencies;

  @XmlElementWrapper(name="excluded-config-types")
  @XmlElement(name="config-type")
  private Set<String> excludedConfigTypes = new HashSet<String>();

  @XmlTransient
  private Map<String, Map<String, Map<String, String>>> configTypes;

  @JsonIgnore
  private Boolean monitoringService;

  @JsonIgnore
  @XmlElement(name = "restartRequiredAfterChange")
  private Boolean restartRequiredAfterChange;

  @JsonIgnore
  @XmlElement(name = "restartRequiredAfterRackChange")
  private Boolean restartRequiredAfterRackChange;

  @XmlElement(name = "extends")
  private String parent;

  @XmlElement(name = "widgetsFileName")
  private String widgetsFileName = StackDirectory.WIDGETS_DESCRIPTOR_FILE_NAME;

  @XmlElement(name = "metricsFileName")
  private String metricsFileName = StackDirectory.SERVICE_METRIC_FILE_NAME;

  @XmlTransient
  private volatile Map<String, PropertyInfo> requiredProperties;

  /**
   * Credential store information
   */
  @XmlElements(@XmlElement(name = "credential-store"))
  private CredentialStoreInfo credentialStoreInfo;

  public Boolean isRestartRequiredAfterChange() {
    return restartRequiredAfterChange;
  }

  public void setRestartRequiredAfterChange(Boolean restartRequiredAfterChange) {
    this.restartRequiredAfterChange = restartRequiredAfterChange;
  }

  @XmlTransient
  private File metricsFile = null;

  @XmlTransient
  private Map<String, Map<String, List<MetricDefinition>>> metrics = null;

  @XmlTransient
  private File advisorFile = null;

  @XmlTransient
  private String advisorName = null;

  @XmlTransient
  private File alertsFile = null;

  @XmlTransient
  private File kerberosDescriptorFile = null;

  @XmlTransient
  private File widgetsDescriptorFile = null;

  private StackRoleCommandOrder roleCommandOrder;

  @XmlTransient
  private boolean valid = true;

  @XmlElementWrapper(name = "properties")
  @XmlElement(name="property")
  private List<ServicePropertyInfo> servicePropertyList = Lists.newArrayList();

  @XmlTransient
  private Map<String, String> servicePropertyMap = ImmutableMap.copyOf(ensureMandatoryServiceProperties(Maps.<String, String>newHashMap()));

  /**
   *
   * @return valid xml flag
   */
  @Override
  public boolean isValid() {
    return valid;
  }

  /**
   *
   * @param valid set validity flag
   */
  @Override
  public void setValid(boolean valid) {
    this.valid = valid;
  }

  @XmlTransient
  private Set<String> errorSet = new HashSet<String>();

  @Override
  public void addError(String error) {
    errorSet.add(error);
  }

  @Override
  public Collection<String> getErrors() {
    return errorSet;
  }

  @Override
  public void addErrors(Collection<String> errors) {
    this.errorSet.addAll(errors);
  }
  /**
   * Internal list of os-specific details (loaded from xml). Added at schema ver 2
   */
  @JsonIgnore
  @XmlElementWrapper(name="osSpecifics")
  @XmlElements(@XmlElement(name="osSpecific"))
  private List<ServiceOsSpecific> serviceOsSpecifics;

  @JsonIgnore
  @XmlElement(name="configuration-dir")
  private String configDir = StackDirectory.SERVICE_CONFIG_FOLDER_NAME;

  @JsonIgnore
  @XmlElement(name = "themes-dir")
  private String themesDir = StackDirectory.SERVICE_THEMES_FOLDER_NAME;

  @JsonIgnore
  @XmlElementWrapper(name = "themes")
  @XmlElements(@XmlElement(name = "theme"))
  private List<ThemeInfo> themes;

  @XmlTransient
  private volatile Map<String, ThemeInfo> themesMap;

  @JsonIgnore
  @XmlElement(name = "quickLinksConfigurations-dir")
  private String quickLinksConfigurationsDir = StackDirectory.SERVICE_QUICKLINKS_CONFIGURATIONS_FOLDER_NAME;

  @JsonIgnore
  @XmlElementWrapper(name = "quickLinksConfigurations")
  @XmlElements(@XmlElement(name = "quickLinksConfiguration"))
  private List<QuickLinksConfigurationInfo> quickLinksConfigurations;

  @XmlTransient
  private volatile Map<String, QuickLinksConfigurationInfo> quickLinksConfigurationsMap;

  /**
   * Map of of os-specific details that is exposed (and initialised from list)
   * at getter.
   * Added at schema ver 2
   */
  private volatile Map<String, ServiceOsSpecific> serviceOsSpecificsMap;

  /**
   * This is used to add service check actions for services.
   * Added at schema ver 2
   */
  private CommandScriptDefinition commandScript;

  /**
   * Added at schema ver 2
   */
  @XmlElementWrapper(name="customCommands")
  @XmlElements(@XmlElement(name="customCommand"))
  private List<CustomCommandDefinition> customCommands;

  @XmlElementWrapper(name="requiredServices")
  @XmlElement(name="service")
  private List<String> requiredServices = new ArrayList<String>();

  /**
   * Meaning: stores subpath from stack root to exact directory, that contains
   * service scripts and templates. Since schema ver 2,
   * we may have multiple service metadata inside folder.
   * Added at schema ver 2
   */
  @XmlTransient
  private String servicePackageFolder;

  /**
   * Stores the path to the upgrades folder which contains the upgrade xmls for the given service.
   */
  @XmlTransient
  private File serviceUpgradesFolder;

  /**
   * Stores the path to the checks folder which contains prereq check jars for the given service.
   */
  @XmlTransient
  private File checksFolder;

  /**
   * Stores the path to the server actions folder which contains server actions jars for the given service.
   */
  @XmlTransient
  private File serverActionsFolder;

  public boolean isDeleted() {
    return isDeleted;
  }

  public void setDeleted(boolean deleted) {
    isDeleted = deleted;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getParent() {
    return parent;
  }

  public void setParent(String parent) {
    this.parent = parent;
  }

  public String getDisplayName() {
    return displayName;
  }

  public void setDisplayName(String displayName) {
    this.displayName = displayName;
  }

  public String getServiceType() {
	return serviceType;
  }

  public void setServiceType(String serviceType) {
	this.serviceType = serviceType;
  }

public String getVersion() {
    return version;
  }

  public void setVersion(String version) {
    this.version = version;
  }

  public Selection getSelection() {
    if (selection == null) {
      return Selection.DEFAULT;
    }
    return selection;
  }

  public void setSelection(Selection selection) {
    this.selection = selection;
  }

  /**
   * Check if selection was presented in xml. We need this for proper stack inheritance, because {@link ServiceInfo#getSelection}
   * by default returns {@link Selection#DEFAULT}, even if no value found in metainfo.xml.
   * @return true, if selection not defined in metainfo.xml
   */
  public boolean isSelectionEmpty() {
    return selection == null;
  }

  public String getComment() {
    return comment;
  }

  public void setComment(String comment) {
    this.comment = comment;
  }
  public List<String> getRequiredServices() {
    return requiredServices;
  }

  public String getWidgetsFileName() {
    return widgetsFileName;
  }

  public void setWidgetsFileName(String widgetsFileName) {
    this.widgetsFileName = widgetsFileName;
  }

  public String getMetricsFileName() {
    return metricsFileName;
  }

  public void setMetricsFileName(String metricsFileName) {
    this.metricsFileName = metricsFileName;
  }

  public void setRequiredServices(List<String> requiredServices) {
    this.requiredServices = requiredServices;
  }
  public List<PropertyInfo> getProperties() {
    if (properties == null) properties = new ArrayList<PropertyInfo>();
    return properties;
  }

  public void setProperties(List properties) {
    this.properties = properties;
  }

  public List<ComponentInfo> getComponents() {
    if (components == null) components = new ArrayList<ComponentInfo>();
    return components;
  }

  /**
   * Finds ComponentInfo by component name
   * @param componentName  name of the component
   * @return ComponentInfo componentName or null
   */
  public ComponentInfo getComponentByName(String componentName){
    for(ComponentInfo componentInfo : getComponents()) {
      if(componentInfo.getName().equals(componentName)){
        return componentInfo;
      }
    }
    return null;
  }
  public boolean isClientOnlyService() {
    if (components == null || components.isEmpty()) {
      return false;
    }
    for (ComponentInfo compInfo : components) {
      if (!compInfo.isClient()) {
        return false;
      }
    }
    return true;
  }

  public ComponentInfo getClientComponent() {
    ComponentInfo client = null;

    if (components != null) {
      for (ComponentInfo compInfo : components) {
        if (compInfo.isClient()) {
          client = compInfo;
          break;
        }
      }
    }
    return client;
  }

  public File getAdvisorFile() {
    return advisorFile;
  }

  public void setAdvisorFile(File advisorFile) {
    this.advisorFile = advisorFile;
  }

  public String getAdvisorName() {
    return advisorName;
  }

  public void setAdvisorName(String advisorName) {
    this.advisorName = advisorName;
  }

  /**
   * Indicates if this service supports credential store.
   * False, it was not specified.
   *
   * @return true or false
   */
  public boolean isCredentialStoreSupported() {
    if (credentialStoreInfo != null) {
      if (credentialStoreInfo.isSupported() != null) {
        return credentialStoreInfo.isSupported();
      }
    }

    return false;
  }

  /**
   * Set a value indicating if this service supports credential store.
   * @param credentialStoreSupported
   */
  public void setCredentialStoreSupported(boolean credentialStoreSupported) {
    if (credentialStoreInfo == null) {
      credentialStoreInfo = new CredentialStoreInfo();
    }
    credentialStoreInfo.setSupported(credentialStoreSupported);
  }

  /**
   * Indicates if this service is requires credential store.
   * False if it was not specified.
   *
   * @return true or false
   */
  public boolean isCredentialStoreRequired() {
    if (credentialStoreInfo != null) {
      if (credentialStoreInfo.isRequired() != null) {
        return credentialStoreInfo.isRequired();
      }
    }

    return false;
  }

  /**
   * Set a value indicating if this service requires credential store.
   * @param credentialStoreRequired
   */
  public void setCredentialStoreRequired(boolean credentialStoreRequired) {
    if (credentialStoreInfo == null) {
      credentialStoreInfo = new CredentialStoreInfo();
    }
    credentialStoreInfo.setRequired(credentialStoreRequired);
  }

  /**
   * Indicates if this service is enabled for credential store use.
   * False if it was not specified.
   *
   * @return true or false
   */
  public boolean isCredentialStoreEnabled() {
    if (credentialStoreInfo != null) {
      if (credentialStoreInfo.isEnabled() != null) {
        return credentialStoreInfo.isEnabled();
      }
    }

    return false;
  }

  /**
   * Set a value indicating if this service is enabled for credential store use.
   * @param credentialStoreEnabled
   */
  public void setCredentialStoreEnabled(boolean credentialStoreEnabled) {
    if (credentialStoreInfo == null) {
      credentialStoreInfo = new CredentialStoreInfo();
    }
    credentialStoreInfo.setEnabled(credentialStoreEnabled);
  }

  /**
   * Get the credential store information object.
   *
   * @return
   */
  public CredentialStoreInfo getCredentialStoreInfo() {
    return credentialStoreInfo;
  }

  /**
   * Set a new value for the credential store information.
   *
   * @param credentialStoreInfo
   */
  public void setCredentialStoreInfo(CredentialStoreInfo credentialStoreInfo) {
    this.credentialStoreInfo = credentialStoreInfo;
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("Service name:");
    sb.append(name);
    sb.append("\nService type:");
    sb.append(serviceType);
    sb.append("\nversion:");
    sb.append(version);
    sb.append("\ncomment:");
    sb.append(comment);

    //for (PropertyInfo property : getProperties()) {
    //  sb.append("\tProperty name=" + property.getName() +
    //"\nproperty value=" + property.getValue() + "\ndescription=" + property.getDescription());
    //}
    for (ComponentInfo component : getComponents()) {
      sb.append("\n\n\nComponent:\n");
      sb.append("name=");
      sb.append(component.getName());
      sb.append("\tcategory=");
      sb.append(component.getCategory());
    }

    return sb.toString();
  }

  /**
   * Obtain the config types associated with this service.
   * The returned map is an unmodifiable view.
   * @return unmodifiable map of config types associated with this service
   */
  public synchronized Map<String, Map<String, Map<String, String>>> getConfigTypeAttributes() {
    Map<String, Map<String, Map<String, String>>> tmpConfigTypes = configTypes == null ?
        new HashMap<String, Map<String, Map<String, String>>>() : configTypes;

    for(String excludedtype : excludedConfigTypes){
      tmpConfigTypes.remove(excludedtype);
    }

    return Collections.unmodifiableMap(tmpConfigTypes);
  }

  /**
   * Add the given type and set it's attributes.
   * If the type is marked for exclusion, it will not be added.
   *
   * @param type            configuration type
   * @param typeAttributes  attributes associated with the type
   */
  public synchronized void setTypeAttributes(String type, Map<String, Map<String, String>> typeAttributes) {
    if (this.configTypes == null) {
      configTypes = new HashMap<String, Map<String, Map<String, String>>>();
    }
    configTypes.put(type, typeAttributes);
  }

  /**
   * Set all types and associated attributes.  Any previously existing types and
   * attributes are removed prior to setting the new values.
   *
   * @param types map of type attributes
   */
  public synchronized void setAllConfigAttributes(Map<String, Map<String, Map<String, String>>> types) {
    configTypes = new HashMap<String, Map<String, Map<String, String>>>();
    for (Map.Entry<String, Map<String, Map<String, String>>> entry : types.entrySet()) {
      setTypeAttributes(entry.getKey(), entry.getValue());
    }
  }

  /**
   * Determine of the service has a dependency on the provided configuration type.
   * @param type the config type
   * @return true if the service defines a dependency on the provided type
   */
  public boolean hasConfigDependency(String type) {
    return configDependencies != null && configDependencies.contains(type);
  }

  /**
   * Determine if the service contains the specified config type
   * @param type  config type to check
   * @return true if the service has the specified config type; false otherwise
   */
  public boolean hasConfigType(String type) {
    return configTypes != null && configTypes.containsKey(type)
        && !excludedConfigTypes.contains(type);
  }

  /**
   * Determine if the service has a dependency on the provided type and contains any of the provided properties.
   * This can be used in determining if a property is stale.

   * @param type the config type
   * @param keyNames the names of all the config keys for the given type
   * @return true if the config is stale
   */
  public boolean hasDependencyAndPropertyFor(String type, Collection<String> keyNames) {
    if (!hasConfigDependency(type))
      return false;

    buildConfigLayout();
    Set<String> keys = configLayout.get(type);

    for (String staleCheck : keyNames) {
      if (keys != null && keys.contains(staleCheck))
        return true;
    }

    return false;
  }

  /**
   * Builds the config map specific to this service.
   */
  private void buildConfigLayout() {
    if (null == configLayout) {
      synchronized(this) {
        if (null == configLayout) {
          configLayout = new HashMap<String, Set<String>>();

          for (PropertyInfo pi : getProperties()) {
            String type = pi.getFilename();
            int idx = type.indexOf(".xml");
            type = type.substring(0, idx);

            if (!configLayout.containsKey(type))
              configLayout.put(type, new HashSet<String>());

            configLayout.get(type).add(pi.getName());
          }
        }
      }
    }
  }

  public List<String> getConfigDependencies() {
    return configDependencies;
  }
  public List<String> getConfigDependenciesWithComponents(){
    List<String> retVal = new ArrayList<String>();
    if(configDependencies != null){
      retVal.addAll(configDependencies);
    }
    if(components != null){
      for (ComponentInfo c : components) {
        if(c.getConfigDependencies() != null){
          retVal.addAll(c.getConfigDependencies());
        }
      }
    }
    return retVal.size() == 0 ? (configDependencies == null ? null : configDependencies) : retVal;
  }

  public void setConfigDependencies(List<String> configDependencies) {
    this.configDependencies = configDependencies;
  }

  public String getSchemaVersion() {
    if (schemaVersion == null) {
      return AmbariMetaInfo.SCHEMA_VERSION_2;
    } else {
      return schemaVersion;
    }
  }

  public void setSchemaVersion(String schemaVersion) {
    this.schemaVersion = schemaVersion;
  }

  public String getServicePackageFolder() {
    return servicePackageFolder;
  }

  public void setServicePackageFolder(String servicePackageFolder) {
    this.servicePackageFolder = servicePackageFolder;
  }

  public File getServiceUpgradesFolder() {
    return serviceUpgradesFolder;
  }

  public void setServiceUpgradesFolder(File serviceUpgradesFolder) {
    this.serviceUpgradesFolder = serviceUpgradesFolder;
  }

  public File getChecksFolder() {
    return checksFolder;
  }

  public void setChecksFolder(File checksFolder) {
    this.checksFolder = checksFolder;
  }

  public File getServerActionsFolder() {
    return serverActionsFolder;
  }

  public void setServerActionsFolder(File serverActionsFolder) {
    this.serverActionsFolder = serverActionsFolder;
  }

  /**
   * Exposes (and initializes on first use) map of os-specific details.
   * @return  map of OS specific details keyed by family
   */
  public Map<String, ServiceOsSpecific> getOsSpecifics() {
    if (serviceOsSpecificsMap == null) {
      synchronized (this) { // Double-checked locking pattern
        if (serviceOsSpecificsMap == null) {
          Map<String, ServiceOsSpecific> tmpMap =
                  new TreeMap<String, ServiceOsSpecific>();
          if (serviceOsSpecifics != null) {
            for (ServiceOsSpecific osSpecific : serviceOsSpecifics) {
              tmpMap.put(osSpecific.getOsFamily(), osSpecific);
            }
          }
          serviceOsSpecificsMap = tmpMap;
        }
      }
    }
    return serviceOsSpecificsMap;
  }

  public void setOsSpecifics(Map<String, ServiceOsSpecific> serviceOsSpecificsMap) {
    this.serviceOsSpecificsMap = serviceOsSpecificsMap;
  }

  public List<CustomCommandDefinition> getCustomCommands() {
    if (customCommands == null) {
      customCommands = new ArrayList<CustomCommandDefinition>();
    }
    return customCommands;
  }

  public void setCustomCommands(List<CustomCommandDefinition> customCommands) {
    this.customCommands = customCommands;
  }

  public CommandScriptDefinition getCommandScript() {
    return commandScript;
  }

  public void setCommandScript(CommandScriptDefinition commandScript) {
    this.commandScript = commandScript;
  }

  /**
   * @param file the file containing the metrics definitions
   */
  public void setMetricsFile(File file) {
    metricsFile = file;
  }

  /**
   * @return the metrics file, or null if none exists
   */
  public File getMetricsFile() {
    return metricsFile;
  }

  /**
   * @return the metrics defined for this service
   */
  public Map<String, Map<String, List<MetricDefinition>>> getMetrics() {
    return metrics;
  }

  /**
   * @param map the metrics for this service
   */
  public void setMetrics(Map<String, Map<String, List<MetricDefinition>>> map) {
    metrics = map;
  }

  /**
   * @return the configuration directory name
   */
  public String getConfigDir() {
    return configDir;
  }

  /**
   * @return whether the service is a monitoring service
   */
  public Boolean isMonitoringService() {
    return monitoringService;
  }

  /**
   * @param monitoringService whether the service is a monitoring service
   */
  public void setMonitoringService(Boolean monitoringService) {
    this.monitoringService = monitoringService;
  }

  /**
   * @param file the file containing the alert definitions
   */
  public void setAlertsFile(File file) {
    alertsFile = file;
  }

  /**
   * @return the alerts file, or null if none exists
   */
  public File getAlertsFile() {
    return alertsFile;
  }

  /**
   * @param file the file containing the alert definitions
   */
  public void setKerberosDescriptorFile(File file) {
    kerberosDescriptorFile = file;
  }

  /**
   * @return the kerberos descriptor file, or null if none exists
   */
  public File getKerberosDescriptorFile() {
    return kerberosDescriptorFile;
  }

  /**
   * @return the widgets descriptor file, or null if none exists
   */
  public File getWidgetsDescriptorFile() {
    return widgetsDescriptorFile;
  }

  public void setWidgetsDescriptorFile(File widgetsDescriptorFile) {
    this.widgetsDescriptorFile = widgetsDescriptorFile;
  }

  public StackRoleCommandOrder getRoleCommandOrder() {
    return roleCommandOrder;
  }

  public void setRoleCommandOrder(StackRoleCommandOrder roleCommandOrder) {
    this.roleCommandOrder = roleCommandOrder;
  }

  /**
   * @return config types this service contains configuration for, but which are primarily related to another service
   */
  public Set<String> getExcludedConfigTypes() {
    return excludedConfigTypes;
  }

  public void setExcludedConfigTypes(Set<String> excludedConfigTypes) {
    this.excludedConfigTypes = excludedConfigTypes;
  }

  //todo: ensure that required properties are never modified...
  public Map<String, PropertyInfo> getRequiredProperties() {
    Map<String, PropertyInfo> result = requiredProperties;
    if (result == null) {
      synchronized(this) {
        result = requiredProperties;
        if (result == null) {
          requiredProperties = result = new HashMap<String, PropertyInfo>();
          List<PropertyInfo> properties = getProperties();
          for (PropertyInfo propertyInfo : properties) {
            if (propertyInfo.isRequireInput()) {
              result.put(propertyInfo.getName(), propertyInfo);
            }
          }
        }
      }
    }
    return result;
  }

  /**
   * Determine whether or not a restart is required for this service after a host rack info change.
   *
   * @return true if a restart is required
   */
  public Boolean isRestartRequiredAfterRackChange() {
    return restartRequiredAfterRackChange;
  }

  /**
   * Set indicator for required restart after a host rack info change.
   *
   * @param restartRequiredAfterRackChange  true if a restart is required
   */
  public void setRestartRequiredAfterRackChange(Boolean restartRequiredAfterRackChange) {
    this.restartRequiredAfterRackChange = restartRequiredAfterRackChange;
  }

  public String getThemesDir() {
    return themesDir;
  }

  public void setThemesDir(String themesDir) {
    this.themesDir = themesDir;
  }

  public List<ThemeInfo> getThemes() {
    return themes;
  }

  public void setThemes(List<ThemeInfo> themes) {
    this.themes = themes;
  }

  public Map<String, ThemeInfo> getThemesMap() {
    if (themesMap == null) {
      synchronized (this) {
      }
      if (themesMap == null) {
        Map<String, ThemeInfo> tmp = new TreeMap<String, ThemeInfo>();
        if (themes != null) {
          for (ThemeInfo theme : themes) {
            tmp.put(theme.getFileName(), theme);
          }
        }
        themesMap = tmp;
      }
    }
    return themesMap;
  }

  public void setThemesMap(Map<String, ThemeInfo> themesMap) {
    this.themesMap = themesMap;
  }

  //Quick links configurations
  public String getQuickLinksConfigurationsDir() {
    return quickLinksConfigurationsDir;
  }

  public void setQuickLinksConfigurationsDir(String quickLinksConfigurationsDir) {
    this.quickLinksConfigurationsDir = quickLinksConfigurationsDir;
  }

  public List<QuickLinksConfigurationInfo> getQuickLinksConfigurations() {
    return quickLinksConfigurations;
  }

  public void setQuickLinksConfigurations(List<QuickLinksConfigurationInfo> quickLinksConfigurations) {
    this.quickLinksConfigurations = quickLinksConfigurations;
  }

  public Map<String, QuickLinksConfigurationInfo> getQuickLinksConfigurationsMap() {
    if (quickLinksConfigurationsMap == null) {
      synchronized (this) {
      }
      if (quickLinksConfigurationsMap == null) {
        Map<String, QuickLinksConfigurationInfo> tmp = new TreeMap<String, QuickLinksConfigurationInfo>();
        if (quickLinksConfigurations != null) {
          for (QuickLinksConfigurationInfo quickLinksConfiguration : quickLinksConfigurations) {
            tmp.put(quickLinksConfiguration.getFileName(), quickLinksConfiguration);
          }
        }
        quickLinksConfigurationsMap = tmp;
      }
    }
    return quickLinksConfigurationsMap;
  }

  public void setQuickLinksConfigurationsMap(Map<String, QuickLinksConfigurationInfo> quickLinksConfigurationsMap) {
    this.quickLinksConfigurationsMap = quickLinksConfigurationsMap;
  }

  public List<ServicePropertyInfo> getServicePropertyList() {
    return servicePropertyList;
  }

  public void setServicePropertyList(List<ServicePropertyInfo> servicePropertyList) {
    this.servicePropertyList = servicePropertyList;
    afterServicePropertyListSet();
  }

  private void afterServicePropertyListSet(){
    validateServiceProperties();
    buildServiceProperties();
  }

  /**
   * Returns the service properties defined in the xml service definition.
   * @return Service property map
   */
  public Map<String, String> getServiceProperties()  {
    return servicePropertyMap;
  }

  /**
   * Constructs the map that stores the service properties defined in the xml service definition.
   * The keys are the property names and values the property values.
   * It ensures that missing required service properties are added with default values.
   */
  private void buildServiceProperties() {
    if (isValid()) {
      Map<String, String> properties = Maps.newHashMap();
      for (ServicePropertyInfo property : getServicePropertyList()) {
        properties.put(property.getName(), property.getValue());
      }
      servicePropertyMap = ImmutableMap.copyOf(ensureMandatoryServiceProperties(properties));
    }
    else
      servicePropertyMap = ImmutableMap.of();

  }

  private Map<String, String> ensureMandatoryServiceProperties(Map<String, String> properties) {
    return ensureVisibilityServiceProperties(properties);
  }

  private Map<String, String> ensureVisibilityServiceProperties(Map<String, String> properties) {
    if (!properties.containsKey(DEFAULT_SERVICE_INSTALLABLE_PROPERTY.getKey()))
      properties.put(DEFAULT_SERVICE_INSTALLABLE_PROPERTY.getKey(), DEFAULT_SERVICE_INSTALLABLE_PROPERTY.getValue());

    if (!properties.containsKey(DEFAULT_SERVICE_MANAGED_PROPERTY.getKey()))
      properties.put(DEFAULT_SERVICE_MANAGED_PROPERTY.getKey(), DEFAULT_SERVICE_MANAGED_PROPERTY.getValue());

    if (!properties.containsKey(DEFAULT_SERVICE_MONITORED_PROPERTY.getKey()))
      properties.put(DEFAULT_SERVICE_MONITORED_PROPERTY.getKey(), DEFAULT_SERVICE_MONITORED_PROPERTY.getValue());

    return properties;
  }

  void afterUnmarshal(Unmarshaller unmarshaller, Object parent) {
    afterServicePropertyListSet();
  }

  private void validateServiceProperties() {
    // Verify if there are duplicate service properties by name
    Multimap<String, ServicePropertyInfo> servicePropsByName = Multimaps.index(
      getServicePropertyList(),
      new Function<ServicePropertyInfo, String>() {
        @Override
        public String apply(ServicePropertyInfo servicePropertyInfo) {
          return servicePropertyInfo.getName();
        }
      }

    );

    for (String propertyName: servicePropsByName.keySet()) {
      if (servicePropsByName.get(propertyName).size() > 1) {
        setValid(false);
        addError("Duplicate service property with name '" + propertyName + "' found in " + getName() + ":" + getVersion() + " service definition !");
      }
    }

    for (ComponentInfo component : getComponents()) {
      int primaryLogs = 0;
      for (LogDefinition log : component.getLogs()) {
        primaryLogs += log.isPrimary() ? 1 : 0;
      }

      if (primaryLogs > 1) {
        setValid(false);
        addError("More than one primary log exists for the component " + component.getName());
      }
    }

    // validate credential store information
    if (credentialStoreInfo != null) {
      // if both are specified, supported must be true if enabled is false or true.
      if (credentialStoreInfo.isSupported() != null && credentialStoreInfo.isEnabled() != null) {
        if (!credentialStoreInfo.isSupported() && credentialStoreInfo.isEnabled()) {
          setValid(false);
          addError("Credential store cannot be enabled for service " + getName() + " as it does not support it.");
        }
      }

      // Must be specified
      if (credentialStoreInfo.isSupported() == null) {
        setValid(false);
        addError("Credential store supported is not specified for service " + getName());
      }

      // Must be specified
      if (credentialStoreInfo.isEnabled() == null) {
        setValid(false);
        addError("Credential store enabled is not specified for service " + getName());
      }
    }
  }

  public enum Selection {
    DEFAULT,
    TECH_PREVIEW,
    MANDATORY,
    DEPRECATED
  }
}


text:
<?php

namespace Propel\Tests\Generator\Schema;

use org\bovigo\vfs\vfsStream;
use org\bovigo\vfs\visitor\vfsStreamPrintVisitor;
use Propel\Tests\TestCase;
use Propel\Tests\VfsTrait;

class ReaderTestCase extends TestCase
{
    use VfsTrait;

    protected function addJsonSchema(): void
    {
        $content = <<<EOF
{
  "database": {
    "name": "bookstore",
    "defaultIdMethod": "native",
    "namespace": "Propel\\\Tests\\\Bookstore",
    "activeRecord": "true",
    "entities": [
      {
        "name": "Book",
        "fields": [
          {
            "name": "id",
            "required": "true",
            "primaryKey": "true",
            "autoIncrement": "true",
            "type": "INTEGER"
          },
          {
            "name": "title",
            "type": "VARCHAR",
            "required": "true",
            "primaryString": "true"
          },
          {
            "name": "ISBN",
            "required": "true",
            "type": "VARCHAR",
            "size": "24"
          },
          {
            "name": "price",
            "required": "false",
            "type": "FLOAT"
          }
        ],
        "relations": [
          {
            "target": "Publisher",
            "onDelete": "setnull"
          },
          {
            "target": "Author",
            "onDelete": "setnull",
            "onUpdate": "cascade"
          }
        ]
      },
      {
        "name": "Publisher",
        "defaultStringFormat": "XML",
        "fields": [
          {
            "name": "id",
            "required": "true",
            "primaryKey": "true",
            "autoIncrement": "true",
            "type": "INTEGER"
          },
          {
            "name": "name",
            "required": "true",
            "type": "VARCHAR",
            "size": "128",
            "default": "Penguin"
          }
        ]
      },
      {
        "name": "Author",
        "fields": [
          {
            "name": "id",
            "required": "true",
            "primaryKey": "true",
            "autoIncrement": "true",
            "type": "INTEGER"
          },
          {
            "name": "firstName",
            "required": "true",
            "type": "VARCHAR",
            "size": "128"
          },
          {
            "name": "lastName",
            "required": "true",
            "type": "VARCHAR",
            "size": "128"
          },
          {
            "name": "email",
            "type": "VARCHAR",
            "size": "128"
          }
        ]
      }
    ]
  }
}
EOF;
        $this->newFile('schema.json', $content);
    }

    protected function addPhpSchema(): void
    {
        $content = <<<EOF
<?php

return [
  "database" => [
    "name" => "bookstore",
    "defaultIdMethod" => "native",
    "namespace" => "Propel\Tests\Bookstore",
    "activeRecord" => true,
    "entities" => [
      [
        "name" => "Book",
        "fields" => [
          [
            "name" => "id",
            "required" => true,
            "primaryKey" => true,
            "autoIncrement" => true,
            "type" => "INTEGER"
          ],
          [
            "name" => "title",
            "type" => "VARCHAR",
            "required" => true,
            "primaryString" => true
          ],
          [
            "name" => "ISBN",
            "required" => true,
            "type" => "VARCHAR",
            "size" => 24
          ],
          [
            "name" => "price",
            "required" => false,
            "type" => "FLOAT"
          ]
        ],
        "relations" => [
          [
            "target" => "Publisher",
            "onDelete" => "setnull"
          ],
          [
            "target" => "Author",
            "onDelete" => "setnull",
            "onUpdate" => "cascade"
          ]
        ]
      ],
      [
        "name" => "Publisher",
        "defaultStringFormat" => "XML",
        "fields" => [
          [
            "name" => "id",
            "required" => true,
            "primaryKey" => true,
            "autoIncrement" => true,
            "type" => "INTEGER"
          ],
          [
            "name" => "name",
            "required" => true,
            "type" => "VARCHAR",
            "size" => 128,
            "default" => "Penguin"
          ]
        ]
      ],
      [
        "name" => "Author",
        "fields" => [
          [
            "name" => "id",
            "required" => true,
            "primaryKey" => true,
            "autoIncrement" => true,
            "type" => "INTEGER"
          ],
          [
            "name" => "firstName",
            "required" => true,
            "type" => "VARCHAR",
            "size" => 128
          ],
          [
            "name" => "lastName",
            "required" => true,
            "type" => "VARCHAR",
            "size" => 128
          ],
          [
            "name" => "email",
            "type" => "VARCHAR",
            "size" => 128
          ]
        ]
      ]
    ]
  ]
];
EOF;
        $this->newFile('schema.php', $content);
    }

    protected function addXmlSchema(): void
    {
        $content = <<<XML
<database name="bookstore" defaultIdMethod="native" namespace="Propel\Tests\Bookstore" activeRecord="true">
    <entity name="Book" description="Book Table">
        <field name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" description="Book Id"/>
        <field name="title" type="VARCHAR" required="true" description="Book Title" primaryString="true"/>
        <field name="ISBN" required="true" type="VARCHAR" size="24" description="ISBN Number" primaryString="false"/>
        <field name="price" required="false" type="FLOAT" description="Price of the book."/>
        <relation target="Publisher" onDelete="setnull"/>
        <relation target="Author" onDelete="setnull" onUpdate="cascade"/>
    </entity>

    <entity name="Publisher" description="Publisher Table" defaultStringFormat="XML">
        <field name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER"
               description="Publisher Id"/>
        <field name="name" required="true" type="VARCHAR" size="128" default="Penguin" description="Publisher Name"/>
    </entity>

    <entity name="Author" description="Author Table">
        <field name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" description="Author Id"/>
        <field name="firstName" required="true" type="VARCHAR" size="128" description="First Name"/>
        <field name="lastName" required="true" type="VARCHAR" size="128" description="Last Name"/>
        <field name="email" type="VARCHAR" size="128" description="E-Mail Address"/>
    </entity>
</database>
XML;

        $this->newFile('schema.xml', $content);
    }

    protected function addYamlSchema()
    {
        $content = <<<YML
database:
    name: bookstore
    defaultIdMethod: native
    namespace: Propel\Tests\Bookstore
    activeRecord: true

    entities:
        Book:
            name: Book
            description: Book Table
            fields:
                id:
                    name: id
                    required: true
                    primaryKey: true
                    autoIncrement: true
                    type: INTEGER
                title:
                    name: title
                    type: VARCHAR
                    required: true
                    primaryString: true
                ISBN:
                    name: ISBN
                    required: true
                    type: VARCHAR
                    size: 24
                price:
                    name: price
                    required: false
                    type: FLOAT
            relations:
                - {target: Publisher, onDelete: setnull}
                - {target: Author, onDelete: setnull, onUpdate: cascade}
        Publisher:
            name: Publisher
            defaultStringFormat: XML
            fields:
                id:
                    name: id
                    required: true
                    primaryKey: true
                    autoIncrement: true
                    type: INTEGER
                name:
                    name: name
                    required: true
                    type: VARCHAR
                    size: 128
                    default: Penguin
        Author:
            name: Author
            fields:
                id:
                    name: id
                    required: true
                    primaryKey: true
                    autoIncrement: true
                    type: INTEGER
                firstName:
                    name: firstName
                    required: true
                    type: VARCHAR
                    size: 128
                lastName:
                    name: lastName
                    required: true
                    type: VARCHAR
                    size: 128
                email:
                    name: email
                    type: VARCHAR
                    size: 128
YML;

        $this->newFile('schema.yaml', $content);
    }

    public function addExternalSchemas()
    {
        $content = <<<XML
<database name="bookstore">
  <external-schema filename="external/author.schema.xml" />
  <external-schema filename="external/publisher.schema.xml" />
  <entity name="Book">
      <field name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" />
      <field name="title" type="VARCHAR" required="true" primaryString="true" />
      <field name="ISBN" required="true" type="VARCHAR" primaryString="false" />
      <field name="price" required="false" type="FLOAT" />
      <relation target="Publisher" onDelete="setnull"/>
      <relation target="Author" onDelete="setnull" onUpdate="cascade"/>
  </entity>
</database>
XML;
        $this->newFile('book.schema.xml', $content);

        $externalAuthor = <<<XML
<database name="bookstore">
  <entity name="Author">
    <field name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" />
    <field name="firstName" required="true" type="VARCHAR" size="128" />
    <field name="lastName" required="true" type="VARCHAR" size="128" />
    <field name="email" type="VARCHAR" />
   </entity>
</database>
XML;
        $this->newFile('external/author.schema.xml', $externalAuthor);

        $externalPublisher = <<<XML
<database name="bookstore">
  <entity name="Publisher">
    <field name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" />
    <field name="name" required="true" type="VARCHAR" default="Penguin" description="Publisher Name"/>
  </entity>
</database>
XML;
        $this->newFile('external/publisher.schema.xml', $externalPublisher);
    }
}

redpajama_set_name: RedPajamaGithub


text:
from django.conf.urls import patterns, url

from .views import (
    WorkoutList, WorkoutDetail,
    ImportFitView,
    GraphOverview,
    AdminMassCategory
)

urlpatterns = patterns('workout.views',
    url(r'^/$', WorkoutList.as_view(), name='workout_list'),
    url(r'^/graphs/$', GraphOverview.as_view(), name='workout_graphs'),
    url(r'^/importfile/$', ImportFitView.as_view(), name='workout_importfile'),
    url(r'^/(?P<pk>\d+)', WorkoutDetail.as_view(), name='workout_detail'),
    url(r'^/masscategories/$', AdminMassCategory.as_view(), name='workout_admin_masscategories'),
)


text:
// Code generated by injection-gen. DO NOT EDIT.

package fake

import (
	context "context"

	fake "github.com/tektoncd/pipeline/pkg/client/injection/informers/factory/fake"
	taskrun "github.com/tektoncd/pipeline/pkg/client/injection/informers/pipeline/v1/taskrun"
	controller "knative.dev/pkg/controller"
	injection "knative.dev/pkg/injection"
)

var Get = taskrun.Get

func init() {
	injection.Fake.RegisterInformer(withInformer)
}

func withInformer(ctx context.Context) (context.Context, controller.Informer) {
	f := fake.Get(ctx)
	inf := f.Tekton().V1().TaskRuns()
	return context.WithValue(ctx, taskrun.Key{}, inf), inf.Informer()
}


text:
package org.netcrusher.core.throttle;

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

public final class Throttlers {

    private Throttlers() {
    }

    /**
     * Sum delays
     * @param throttlerFactories Throttler factories
     * @return Combined throttler
     */
    public static ThrottlerFactory sum(final ThrottlerFactory... throttlerFactories) {
        if (throttlerFactories == null || throttlerFactories.length == 0) {
            throw new IllegalArgumentException("Empty throttler array");
        }

        return (clientAddress) -> {
            final List<Throttler> throttlers = new ArrayList<>(throttlerFactories.length);

            for (ThrottlerFactory factory : throttlerFactories) {
                throttlers.add(factory.allocate(clientAddress));
            }

            return (bb) -> {
                long delayNs = 0;
                for (Throttler throttler : throttlers) {
                    delayNs += throttler.calculateDelayNs(bb);
                }
                return delayNs;
            };
        };
    }

    /**
     * Select maximum delay
     * @param throttlerFactories Throttler factories
     * @return Combined throttler
     */
    public static ThrottlerFactory max(final ThrottlerFactory... throttlerFactories) {
        if (throttlerFactories == null || throttlerFactories.length == 0) {
            throw new IllegalArgumentException("Empty throttler array");
        }

        return (clientAddress) -> {
            final List<Throttler> throttlers = new ArrayList<>(throttlerFactories.length);

            for (ThrottlerFactory factory : throttlerFactories) {
                throttlers.add(factory.allocate(clientAddress));
            }

            return (bb) -> {
                long delayNs = Long.MIN_VALUE;
                for (Throttler throttler : throttlers) {
                    delayNs = Math.max(delayNs, throttler.calculateDelayNs(bb));
                }
                return delayNs;
            };
        };
    }

    /**
     * Select minimum delay
     * @param throttlerFactories Throttler factories
     * @return Combined throttler
     */
    public static ThrottlerFactory min(final ThrottlerFactory... throttlerFactories) {
        if (throttlerFactories == null || throttlerFactories.length == 0) {
            throw new IllegalArgumentException("Empty throttler array");
        }

        return (clientAddress) -> {
            final List<Throttler> throttlers = new ArrayList<>(throttlerFactories.length);

            for (ThrottlerFactory factory : throttlerFactories) {
                throttlers.add(factory.allocate(clientAddress));
            }

            return (bb) -> {
                long delayNs = Long.MAX_VALUE;
                for (Throttler throttler : throttlers) {
                    delayNs = Math.min(delayNs, throttler.calculateDelayNs(bb));
                }
                return delayNs;
            };
        };
    }
}


text:
layout: post
title: "Thenga Chutney, Coconut Relish"
modified:
category: "Big-Boys-Curry-Book"
excerpt: "This is a dry coconut chutney that will not freeze. It can be kept for"
tags: ["almond","basmati","bay","butter","cardomoms","cashew","chicken","cinnamon","cloves","cumin","ghee","lamb","mace","nuts","pepper","rice","saffron","turmeric"]
image:
  feature: the-matrix-slim.jpg
date: 2011-10-09T20:52:26+00:00
comments: true
redirect_from:
  - /bbcb/recipe/Thenga+Chutney+Coconut+Relish.html
  - /bbcbrecipe/Thenga+Chutney+Coconut+Relish.html
redirect_to: http://bbcb.co.uk/thenga-chutney-coconut-relish
---

A typical view of youngsters outside of the big cities, these lads exhibit shyness

This is a dry coconut chutney that will not freeze. It can be kept for up to 3 days in the fridge however.

## Ingredients

Relish

1 tbspn. oil

1/2 tin chickpeas

4 green chillies

10 curry leaves

1/2 fresh coconut grated

Juice 1 lime

Salt to taste

Tarka

1 tbspn. oil

1 tsp. mustard seed

Pinch asafeotida

## Method

Heat tbspn. oil and saute chickpeas, chillies and curry leaves until chickpeas are golden brown.

In food processor, grind all relish ingredients together.

Heat Tarka ingredients together until mustard crackles and add to relish.

Back to recipe index


text:
var Mystique = require('mystique');

var AppointmentItemTransformer = Mystique.Transformer.extend({
  resourceName: 'appointmentItem',
  mapOut: function (appointmentItem) {
    return {
      id: appointmentItem.id,
      service: appointmentItem.service ? appointmentItem.service.id : undefined,
      name: appointmentItem.name,
      startTime: appointmentItem.startTime,
      length: appointmentItem.service ? appointmentItem.service.time : appointmentItem.length,
      title: appointmentItem.title,
      client: appointmentItem.client,
      professional: appointmentItem.professional,
      profile: appointmentItem.professional,
    };
  },

  mapIn(req) {
    return {
      service: req.getJson('appointmentItem.service'),
      name: req.getJson('appointmentItem.name'),
      startTime: req.getJson('appointmentItem.startTime'),
      length: req.getJson('appointmentItem.length'),
      title: req.getJson('appointmentItem.title'),
      professional: req.getJson('appointmentItem.professional') || req.getJson('appointmentItem.profile'),
    };
  },
});

Mystique.registerTransformer('AppointmentItem', AppointmentItemTransformer);


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Class Hierarchy</title>
<meta name="date" content="2015-10-29">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For All Packages

Package Hierarchies:

com.soctec.soctec.achievements,

com.soctec.soctec.core,

com.soctec.soctec.network,

com.soctec.soctec.profile,

com.soctec.soctec.test,

com.soctec.soctec.utils

Class Hierarchy

java.lang.Object

com.soctec.soctec.achievements.Achievement (implements java.io.Serializable)

com.soctec.soctec.core.AchievementsFragment

com.soctec.soctec.achievements.AchievementUnlocker (implements java.util.Observer)

android.app.Activity

android.support.v4.app.FragmentActivity (implements android.support.v4.app.ActivityCompat.OnRequestPermissionsResultCallback, android.support.v4.app.ActivityCompatApi23.RequestPermissionsRequestCodeValidator)

android.support.v7.app.AppCompatActivity (implements android.support.v7.app.ActionBarDrawerToggle.DelegateProvider, android.support.v7.app.AppCompatCallback, android.support.v4.app.TaskStackBuilder.SupportParentable)

com.soctec.soctec.core.MainActivity (implements android.support.v7.app.ActionBar.TabListener)

Activity

com.soctec.soctec.core.ScanActivity

Activity

com.soctec.soctec.core.AchievementShowerActivity

Activity

com.soctec.soctec.profile.ProfileMatchActivity

Activity

com.soctec.soctec.profile.ProfileActivity

AndroidTestCase

com.soctec.soctec.test.APIHandlerTest

AndroidTestCase

com.soctec.soctec.test.AchievementTest

AndroidTestCase

com.soctec.soctec.test.ProfileTest

com.soctec.soctec.utils.APIHandler

ArrayAdapter

com.soctec.soctec.core.AchievementsAdapter

ArrayAdapter

com.soctec.soctec.profile.ProfileMatchAdapter

BroadcastReceiver

com.soctec.soctec.network.ConnectionChecker

com.soctec.soctec.utils.Encryptor

com.soctec.soctec.utils.FileHandler

android.support.v4.app.Fragment (implements android.content.ComponentCallbacks, android.view.OnCreateContextMenuListener)

com.soctec.soctec.core.ScanFragment

com.soctec.soctec.core.HelpFragment

com.soctec.soctec.core.InfoFragment

com.soctec.soctec.core.MainActivity.PageChangeListener (implements android.support.v4.view.ViewPager.OnPageChangeListener)

com.soctec.soctec.core.MainFragment

com.soctec.soctec.network.NetworkHandler

java.util.Observable

com.soctec.soctec.achievements.AchievementCreator

com.soctec.soctec.achievements.Demand (implements java.lang.Runnable, java.io.Serializable)

android.support.v4.view.PagerAdapter

android.support.v4.app.FragmentPagerAdapter

com.soctec.soctec.core.MainActivity.SectionsPagerAdapter

com.soctec.soctec.profile.Profile

com.soctec.soctec.network.QRGen

com.soctec.soctec.core.ScanActivity.OnSwipeTouchListener

GestureDetector.SimpleOnGestureListener

com.soctec.soctec.core.ScanActivity.OnSwipeTouchListener.GestureListener

com.soctec.soctec.achievements.Stats (implements java.io.Serializable)

com.soctec.soctec.achievements.Stats.UserPair (implements java.io.Serializable)

java.lang.Thread (implements java.lang.Runnable)

com.soctec.soctec.network.NetworkHandler.ActiveThread

com.soctec.soctec.network.NetworkHandler.PassiveThread

com.soctec.soctec.network.NetworkHandler.ServerThread

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
/* not type checking this file because flow doesn't play well with Proxy */

import config from 'core/config'
import { warn, makeMap, isNative } from '../util/index'

let initProxy

if (process.env.NODE_ENV !== 'production') {
  const allowedGlobals = makeMap(
    'Infinity,undefined,NaN,isFinite,isNaN,' +
    'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' +
    'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt,' +
    'require' // for Webpack/Browserify
  )

  const warnNonPresent = (target, key) => {
    warn(
      `Property or method "${key}" is not defined on the instance but ` +
      'referenced during render. Make sure that this property is reactive, ' +
      'either in the data option, or for class-based components, by ' +
      'initializing the property. ' +
      'See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.',
      target
    )
  }

  const warnReservedPrefix = (target, key) => {
    warn(
      `Property "${key}" must be accessed with "$data.${key}" because ` +
      'properties starting with "$" or "_" are not proxied in the Vue instance to ' +
      'prevent conflicts with Vue internals. ' +
      'See: https://vuejs.org/v2/api/#data',
      target
    )
  }

  const hasProxy =
    typeof Proxy !== 'undefined' && isNative(Proxy)

  if (hasProxy) {
    const isBuiltInModifier = makeMap('stop,prevent,self,ctrl,shift,alt,meta,exact')
    config.keyCodes = new Proxy(config.keyCodes, {
      set (target, key, value) {
        if (isBuiltInModifier(key)) {
          warn(`Avoid overwriting built-in modifier in config.keyCodes: .${key}`)
          return false
        } else {
          target[key] = value
          return true
        }
      }
    })
  }

  const hasHandler = {
    has (target, key) {
      const has = key in target
      const isAllowed = allowedGlobals(key) ||
        (typeof key === 'string' && key.charAt(0) === '_' && !(key in target.$data))
      if (!has && !isAllowed) {
        if (key in target.$data) warnReservedPrefix(target, key)
        else warnNonPresent(target, key)
      }
      return has || !isAllowed
    }
  }

  const getHandler = {
    get (target, key) {
      if (typeof key === 'string' && !(key in target)) {
        if (key in target.$data) warnReservedPrefix(target, key)
        else warnNonPresent(target, key)
      }
      return target[key]
    }
  }

  initProxy = function initProxy (vm) {
    if (hasProxy) {
      // determine which proxy handler to use
      const options = vm.$options
      const handlers = options.render && options.render._withStripped
        ? getHandler
        : hasHandler
      vm._renderProxy = new Proxy(vm, handlers)
    } else {
      vm._renderProxy = vm
    }
  }
}

export { initProxy }


text:
class SkBitmap;
struct SkIRect;

namespace skia {

class ImageOperations {
 public:
  enum ResizeMethod {
    // Box filter. This is a weighted average of all of the pixels touching
    // the destination pixel. For enlargement, this is nearest neighbor.
    //
    // You probably don't want this, it is here for testing since it is easy to
    // compute. Use RESIZE_LANCZOS3 instead.
    RESIZE_BOX,

    // 3-cycle Lanczos filter. This is tall in the middle, goes negative on
    // each side, then oscillates 2 more times. It gives nice sharp edges.
    RESIZE_LANCZOS3,
  };

  // Resizes the given source bitmap using the specified resize method, so that
  // the entire image is (dest_size) big. The dest_subset is the rectangle in
  // this destination image that should actually be returned.
  //
  // The output image will be (dest_subset.width(), dest_subset.height()). This
  // will save work if you do not need the entire bitmap.
  //
  // The destination subset must be smaller than the destination image.
  static SkBitmap Resize(const SkBitmap& source,
                         ResizeMethod method,
                         int dest_width, int dest_height,
                         const SkIRect& dest_subset);

  // Alternate version for resizing and returning the entire bitmap rather than
  // a subset.
  static SkBitmap Resize(const SkBitmap& source,
                         ResizeMethod method,
                         int dest_width, int dest_height);

 private:
  ImageOperations();  // Class for scoping only.
};

}  // namespace skia

#endif  // SKIA_EXT_IMAGE_OPERATIONS_H_


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

namespace Spark.Win32
{
    [Flags]
    internal enum Win32ProcessAccess : uint
    {
        None = 0x0,
        Terminate = 0x1,
        CreateThread = 0x2,
        VmOperation = 0x8,
        VmRead = 0x10,
        VmWrite = 0x20,
        QueryInformation = 0x400
    }
}


text:
Pages

                                    <a class="btn btn-info" href="<?=  base_url()?>admin/pagenew">Add New
                                    <button type="button" id="deleteall" class="btn btn-danger">Delete</button>

                                                        <input type="checkbox" class="checkall" /> Page Title
                                                        Date of Publish
                                                        Edit / Delete

                        <?php $defaultpage="no"; ?>
                       <?php foreach($results as $obj): ?>
                                                    <?php if($obj->post_password == 'front'){$defaultpage='yes';}else{$defaultpage='no';}?>

<input type="checkbox" value="<?=$obj->ID?>" name="selectcheck" class="selectcheck">  <?=  substr($obj->post_title,0,100);?><?php if($defaultpage=='yes'){echo ' (Front Page)';} ?>	<?=date("d-m-Y",strtotime($obj->post_date)); ?>	<a href="<?=base_url()?>admin/pageedit/<?=$obj->ID?>">Edit <a href="#" class="deletepost" role="<?=$obj->ID?>">Delete

                          <?php endforeach; ?>

                <?php echo $links; ?>


text:
function[f] = iwfft_galerkin(F,varargin)
% [f] = iwfft_galerkin(F,{s=1, t=0, scale=1, shift=0})
%
%     Uses the IFFT 'galerkin' approach to compute function evaluations f from the
%     Wiener basis modal coefficients F. The nodal locations are assumed to be
%     the canonical Fourier points mapped to the real line. Both parameters s
%     and t must be integers.

persistent wiener fourier wconnect
if isempty(wiener)
  from speclab import wiener
  from speclab import fourier
  from speclab.fourier.connection import negative_integer_separation_connection as wconnect
end

opt = wiener.defaults(varargin{:});

[fftable,S,T] = wiener.fft.fftable(opt);
if not(fftable)
  error('This basis set is not fft-able: s and t must be integers');
end

% First connect down from unweighted s=s ----> s=1 modes
if S>0
  F = wconnect(F,S,T,S,T);
end

% Now compute (s=1,t=0) modes for f*w^s
F = wiener.operators.wiener_weight_multiply(F,opt);

% Finally compute nodal evaluations
f = fourier.fft.iffft(F);


text:
from typing import List
class Solution:
    def stringMatching(self, words: List[str]) -> List[str]:
        result = []
        for word in words:
            for superWord in words:
                if word == superWord:
                    continue
                if word in superWord:
                    result.append(word)
                    break
        return result

words = ["leetcoder","leetcode","od","hamlet","am"]
ob = Solution()
print(ob.stringMatching(words))


text:
<?php

namespace ZPHP\Socket\Callback;

use ZPHP\Core;
use ZPHP\Protocol;

abstract class Hprose extends Swoole
{

    protected $protocol;
    protected $serv;

    public function setServ($serv)
    {
        $this->serv = $serv;
    }

    public function onReceive()
    {

    }

    abstract public function onRegister();
}


text:
Templates
=========
For demos and more information about these templates visit:
http://www.templates.lavinmontoro.com/


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('cbh_core_model', '0028_auto_20151211_0501'),
    ]

    operations = [
        migrations.AddField(
            model_name='pinnedcustomfield',
            name='visible_to_editors_only',
            field=models.BooleanField(default=False),
            preserve_default=True,
        ),
    ]


text:
package org.m4m.domain.dsl;

import org.junit.Assert;
import org.m4m.domain.Command;
import org.m4m.domain.IInput;
import org.m4m.domain.IOutput;
import org.m4m.domain.IOutputRaw;
import org.m4m.domain.Pair;

import static org.junit.Assert.assertNotNull;

public class CommandProcessorAssert {
    private final CommandProcessorSpy commandProcessor;
    private CommandProcessorSpy.LogEntry currentLogEntry;

    public CommandProcessorAssert(CommandProcessorSpy commandProcessor) {
        this.commandProcessor = commandProcessor;
    }

    public CommandProcessorAssert processed(IOutput expectedOutput, IInput expectedInput) {
        currentLogEntry = commandProcessor.poll();
        assertPairEquals(expectedOutput, expectedInput, currentLogEntry);
        return this;
    }

    public CommandProcessorAssert commands(Command expectedOutputCommand, Command expectedInputCommand) {
        Pair<Pair<Command, Integer>, Pair<Command, Integer>> currentCommandPair = currentLogEntry.commands.poll();
        assertNotNull("(" + expectedOutputCommand + ", " + expectedInputCommand + ") pair was expected but not queued", currentCommandPair);
        Assert.assertEquals(new Pair<Command, Integer>(expectedOutputCommand, 0), currentCommandPair.left);
        Assert.assertEquals(new Pair<Command, Integer>(expectedInputCommand, 0), currentCommandPair.right);
        return this;
    }

    private void assertPairEquals(IOutput expectedOutput, IInput expectedInput, CommandProcessorSpy.LogEntry actual) {
        IOutputRaw actualOutput = actual.output;
        IInput actualInput = actual.input;

        String message = "\nExpected pair: ('" + expectedOutput + "', '" + expectedInput + "')\n" +
            "Actual pair: ('" + actualOutput + "', '" + actualInput + "')\n";
        Assert.assertEquals(message, expectedOutput, actualOutput);
        Assert.assertEquals(message, expectedInput, actualInput);
    }
}


text:
var log = require('./log');

function generateClientId() {
    generateClientId.count = ++generateClientId.count || 1;
    return generateClientId.count;
}

var clients = {};
module.exports = {
  get: function(filter) {
    return clients;
  },

  create: function (name) {
    // NOTE(jose): this is a struct so we can keep adding components to users (like win, losses, friends, etc...)
    var new_client = {};
    new_client.name = name;
    new_client.id = generateClientId();

    clients[new_client.id] = new_client;

    log().info('new user ( ' + new_client.id + ' )');

    return new_client;
  },
};


text:
// Template Source: BaseEntity.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All Rights Reserved.  Licensed under the MIT License.  See License in the project root for license information.
// ------------------------------------------------------------------------------

package com.microsoft.graph.models;
import com.microsoft.graph.serializer.ISerializer;
import com.microsoft.graph.serializer.IJsonBackedObject;
import com.microsoft.graph.serializer.AdditionalDataManager;
import java.util.EnumSet;
import com.microsoft.graph.http.BaseCollectionPage;
import com.microsoft.graph.models.Entity;
import com.microsoft.graph.requests.TeamsAppCollectionPage;

import com.google.gson.JsonObject;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;

// **NOTE** This file was generated by a tool and any changes will be overwritten.

/**
 * The class for the App Catalogs.
 */
public class AppCatalogs extends Entity implements IJsonBackedObject {

    /**
     * The Teams Apps.
     *
     */
    @SerializedName(value = "teamsApps", alternate = {"TeamsApps"})
    @Expose
	@Nullable
    public com.microsoft.graph.requests.TeamsAppCollectionPage teamsApps;

    /**
     * Sets the raw JSON object
     *
     * @param serializer the serializer
     * @param json the JSON object to set this object to
     */
    public void setRawObject(@Nonnull final ISerializer serializer, @Nonnull final JsonObject json) {

        if (json.has("teamsApps")) {
            teamsApps = serializer.deserializeObject(json.get("teamsApps"), com.microsoft.graph.requests.TeamsAppCollectionPage.class);
        }
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: root
 * Date: 21.01.15
 * Time: 22:53
 */

namespace AppBundle\Controller\Admin;

use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Validator\ErrorElement;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Show\ShowMapper;

class CategoryAdmin  extends Admin{
    protected $baseRouteName = 'sonata_category';
    protected $baseRoutePattern = 'category';
    /**
     * @param \Sonata\AdminBundle\Form\FormMapper $formMapper
     *
     * @return void
     */
    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            ->add('name')
        ;
    }

    /**
     * @param \Sonata\AdminBundle\Show\ShowMapper $showMapper
     *
     * @return void
     */
    protected function configureShowField(ShowMapper $showMapper)
    {
        $showMapper
            ->add('name')
        ;
    }

    /**
     * @param \Sonata\AdminBundle\Datagrid\ListMapper $listMapper
     *
     * @return void
     */
    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
            ->addIdentifier('name')
            ->add('_action', 'actions', array(
                'actions' => array(
                    'show' => array(),
                    'edit' => array(),
                    'delete' => array(),
                )
            ))

        ;
    }
    /**
     * @param \Sonata\AdminBundle\Datagrid\DatagridMapper $datagridMapper
     *
     * @return void
     */
    protected function configureDatagridFilters(DatagridMapper $datagridMapper)
    {
        $datagridMapper
            ->add('name')

        ;
    }
    // setup the default sort column and order
    protected $datagridValues = array(
        '_sort_order' => 'ASC',
        '_sort_by' => 'id'
    );
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<XMLTooling xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:saml1="urn:oasis:names:tc:SAML:1.0:assertion" xmlns:saml1p="urn:oasis:names:tc:SAML:1.0:protocol" xmlns="http://www.opensaml.org/xmltooling-config" xsi:schemaLocation="http://www.opensaml.org/xmltooling-config ../../src/schema/xmltooling-config.xsd">

    <!-- Validation rules for SAML 1.0/1.1 SAMLObjects -->
    <ValidatorSuites>

        <!--  SAML 1.0/1.1 Schema Validation Rules -->
        <ValidatorSuite id="saml1-schema-validator">
            <Validator qualifiedName="saml1:Assertion" className="org.opensaml.saml1.core.validator.AssertionSchemaValidator"/>
            <Validator qualifiedName="saml1:AttributeDesignator" className="org.opensaml.saml1.core.validator.AttributeDesignatorSchemaValidator"/>
            <Validator qualifiedName="saml1:Attribute" className="org.opensaml.saml1.core.validator.AttributeSchemaValidator"/>
            <Validator qualifiedName="saml1:AttributeStatement" className="org.opensaml.saml1.core.validator.AttributeStatementSchemaValidator"/>
            <Validator qualifiedName="saml1:AudienceRestrictionCondition" className="org.opensaml.saml1.core.validator.AudienceRestrictionConditionSchemaValidator"/>
            <Validator qualifiedName="saml1p:AuthenticationQuery" className="org.opensaml.saml1.core.validator.AuthenticationQuerySchemaValidator"/>
            <Validator qualifiedName="saml1:AuthenticationStatement" className="org.opensaml.saml1.core.validator.AuthenticationStatementSchemaValidator"/>
            <Validator qualifiedName="saml1:AuthorityBinding" className="org.opensaml.saml1.core.validator.AuthorityBindingSchemaValidator"/>
            <Validator qualifiedName="saml1p:AuthorizationDecisionQuery" className="org.opensaml.saml1.core.validator.AuthorizationDecisionQuerySchemaValidator"/>
            <Validator qualifiedName="saml1:AuthorizationDecisionStatement" className="org.opensaml.saml1.core.validator.AuthorizationDecisionStatementSchemaValidator"/>
            <Validator qualifiedName="saml1:Evidence" className="org.opensaml.saml1.core.validator.EvidenceSchemaValidator"/>
            <Validator qualifiedName="saml1p:Request" className="org.opensaml.saml1.core.validator.RequestSchemaValidator"/>
            <Validator qualifiedName="saml1p:Response" className="org.opensaml.saml1.core.validator.ResponseSchemaValidator"/>
            <Validator qualifiedName="saml1p:Status" className="org.opensaml.saml1.core.validator.StatusSchemaValidator"/>
            <Validator qualifiedName="saml1p:StatusCode" className="org.opensaml.saml1.core.validator.StatusCodeSchemaValidator"/>
            <Validator qualifiedName="saml1:Subject" className="org.opensaml.saml1.core.validator.SubjectSchemaValidator"/>
            <Validator qualifiedName="saml1:SubjectConfirmation" className="org.opensaml.saml1.core.validator.SubjectConfirmationSchemaValidator"/>
            <Validator qualifiedName="saml1:SubjectStatement" className="org.opensaml.saml1.core.validator.SubjectStatementSchemaValidator"/>
        </ValidatorSuite>

        <!-- SAML 1.0/1.1 Specification Validation Rules -->
        <ValidatorSuite id="saml1-spec-validator">
            <Validator qualifiedName="saml1:Action" className="org.opensaml.saml1.core.validator.ActionSpecValidator"/>
            <Validator qualifiedName="saml1:Assertion" className="org.opensaml.saml1.core.validator.AssertionSpecValidator"/>
            <Validator qualifiedName="saml1:Audience" className="org.opensaml.saml1.core.validator.AudienceSpecValidator"/>
        </ValidatorSuite>

    </ValidatorSuites>

</XMLTooling>


text:
package org.rapidoid.net.impl;

import org.rapidoid.RapidoidThing;
import org.rapidoid.annotation.Authors;
import org.rapidoid.annotation.Since;
import org.rapidoid.buffer.Buf;
import org.rapidoid.buffer.BufGroup;
import org.rapidoid.buffer.BufUtil;
import org.rapidoid.data.JSON;
import org.rapidoid.expire.Expiring;
import org.rapidoid.job.Jobs;
import org.rapidoid.log.Log;
import org.rapidoid.log.LogHP;
import org.rapidoid.net.AsyncLogic;
import org.rapidoid.net.Protocol;
import org.rapidoid.net.TLSParams;
import org.rapidoid.net.abstracts.Channel;
import org.rapidoid.net.abstracts.ChannelHolder;
import org.rapidoid.net.abstracts.IRequest;
import org.rapidoid.net.tls.RapidoidTLS;
import org.rapidoid.u.U;
import org.rapidoid.util.Constants;
import org.rapidoid.util.Resetable;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.concurrent.atomic.AtomicLong;

@Authors("Nikolche Mihajlovski")
@Since("2.0.0")
public class RapidoidConnection extends RapidoidThing implements Resetable, Channel, Expiring, Constants {

    private static final CtxListener IGNORE = new IgnorantConnectionListener();

    private static final AtomicLong ID_N = new AtomicLong();

    private static final AtomicLong SERIAL_N = new AtomicLong();

    final boolean hasTLS;

    final RapidoidTLS tls;

    final NetWorker worker;

    public final Buf input;

    public final Buf output;

    public final Buf outgoing;

    private final ConnState state = new ConnState();

    private volatile boolean waitingToWrite = false;

    public volatile SelectionKey key;

    private volatile boolean closeAfterWrite = false;

    volatile boolean closed = true;

    volatile boolean closing = false;

    volatile int completedInputPos;

    private volatile CtxListener listener;

    private final long serialN = SERIAL_N.incrementAndGet();

    private volatile long id;

    private volatile boolean initial;

    volatile boolean async;

    volatile boolean done;

    private volatile boolean isClient;

    private volatile Protocol protocol;

    volatile long requestId;

    final AtomicLong readSeq = new AtomicLong();

    final AtomicLong writeSeq = new AtomicLong();

    volatile boolean resumeInProgress = false;

    volatile IRequest request;

    private volatile long expiresAt;

    private volatile ChannelHolderImpl holder;

    public volatile int nextOp = SelectionKey.OP_READ;

    public volatile int mode = 0;

    private volatile boolean autoReconnect;

    public RapidoidConnection(NetWorker worker, BufGroup bufs, TLSParams tlsParams) {
        this.worker = worker;

        this.hasTLS = worker.sslContext() != null;
        this.tls = hasTLS ? new RapidoidTLS(worker.sslContext(), this, tlsParams) : null;

        this.input = bufs.newBuf("input#" + serialN);
        this.output = bufs.newBuf("output#" + serialN);
        this.outgoing = hasTLS ? bufs.newBuf("outgoing#" + serialN) : this.output;

        reset();
    }

    @Override
    public synchronized void reset() {
        IRequest req = request;
        if (req != null) {
            req.stop();
            request = null;
        }

        id = ID_N.incrementAndGet();
        key = null;
        closed = true;
        closing = false;
        input.clear();
        output.clear();
        outgoing.clear();
        closeAfterWrite = false;
        waitingToWrite = false;
        completedInputPos = 0;
        listener = IGNORE;
        initial = true;
        async = false;
        done = false;
        isClient = false;
        protocol = null;
        requestId = 0;
        readSeq.set(0);
        writeSeq.set(0);
        expiresAt = 0;
        state.reset();

        if (tls != null) tls.reset();

        // extended net:
        holder = null;
        mode = 0;
        autoReconnect = false;
        nextOp = SelectionKey.OP_READ;
    }

    @Override
    public void log(String msg) {
        state().log(msg);
    }

    @Override
    public synchronized InetSocketAddress getAddress() {
        if (key == null) return null;

        SocketChannel socketChannel = (SocketChannel) key.channel();
        SocketAddress addr = socketChannel.socket().getRemoteSocketAddress();
        if (addr instanceof InetSocketAddress) {
            InetSocketAddress address = (InetSocketAddress) addr;
            return address;
        } else {
            throw new IllegalStateException("Cannot get remote address!");
        }
    }

    @Override
    public synchronized Channel write(String s) {
        output.append(s);
        return this;
    }

    @Override
    public synchronized Channel writeln(String s) {
        output.append(s);
        output.append(CR_LF);
        return this;
    }

    @Override
    public synchronized Channel write(byte[] bytes) {
        return write(bytes, 0, bytes.length);
    }

    @Override
    public synchronized Channel write(byte[] bytes, int offset, int length) {
        output.append(bytes, offset, length);
        return this;
    }

    @Override
    public synchronized Channel write(ByteBuffer buf) {
        output.append(buf);
        return this;
    }

    @Override
    public synchronized Channel write(File file) {
        try {
            FileInputStream stream = new FileInputStream(file);
            FileChannel fileChannel = stream.getChannel();
            output.append(fileChannel);
            stream.close();
        } catch (IOException e) {
            throw U.rte(e);
        }

        return this;
    }

    @Override
    public Channel writeJSON(Object value) {
        JSON.stringify(value, output.asOutputStream());
        return this;
    }

    public boolean closeAfterWrite() {
        return closeAfterWrite;
    }

    Channel done() {
        async = false;

        if (!done) {
            done = true;
            askToSend();
        }

        return this;
    }

    void processedSeq(long processedHandle) {

        if (processedHandle == 0) return; // a new connection

        U.must(processedHandle > 0);

        boolean increased = writeSeq.compareAndSet(processedHandle - 1, processedHandle);

        if (!increased) {
            // the current response might be already marked as processed (e.g. in non-async handlers)
            long writeSeqN = writeSeq.get();
            if (writeSeqN != processedHandle) {
                LogHP.warn("Invalid response order!", "expected", processedHandle - 1, "real", writeSeqN);
                close(false);
            }
        }
    }

    @Override
    public Channel send() {
        askToSend();
        return this;
    }

    public void error() {
        askToSend();
    }

    private synchronized void askToSend() {
        synchronized (outgoing) {
            if (hasTLS) {
                synchronized (output) {
                    tls.wrapToOutgoing();
                }
            }

            if (!waitingToWrite && outgoing.size() > 0) {
                waitingToWrite = true;
                worker.wantToWrite(this);
            }
        }
    }

    public synchronized void close(boolean waitToWrite) {
        if (waitToWrite) {
            done();
        }

        if (waitToWrite && waitingToWrite) {
            closeAfterWrite = true;
        } else {
            worker.close(this);
        }
    }

    synchronized void wrote(boolean complete) {
        if (complete) {
            waitingToWrite = false;
        }

        input.deleteBefore(completedInputPos);
        completedInputPos = 0;
    }

    @Override
    public void resume(final long expectedConnId, final long handle, final AsyncLogic asyncLogic) {

        if (expectedConnId != connId()) return;

        long seq = writeSeq.get();

        if (seq < handle - 1) {
            // too early

            Jobs.execute(new Runnable() {
                @Override
                public void run() {
                    resume(expectedConnId, handle, asyncLogic);
                }

                @Override
                public String toString() {
                    return U.frmt("RapidoidConnection.ResumeJob(handle=%s, expectedConnId=%s, logic=%s)", handle, expectedConnId, asyncLogic);
                }
            });

        } else if (seq == handle - 1) {

            synchronized (this) {

                if (expectedConnId != connId()) {
                    return;
                }

//				TODO investigate options for stricter flow control:
//				U.must(!resumeInProgress, "Resume is already in progress!");

                resumeInProgress = true;

                try {
                    doResume(handle, asyncLogic, seq);

                } finally {
                    resumeInProgress = false;
                }
            }

        } else {
            Log.error("Tried to resume a job that already has finished!", "handle", handle, "currentHandle", seq, "job", asyncLogic);
            throw U.rte("Tried to resume a job that already has finished!");
        }
    }

    private void doResume(long handle, AsyncLogic asyncLogic, long seq) {
        U.must(seq == writeSeq.get());

        // execute the logic
        boolean finished = false;

        synchronized (output) {
            BufUtil.startWriting(output);

            try {
                finished = asyncLogic.resumeAsync();
            } catch (Throwable e) {
                Log.error("Error while resuming an asynchronous operation!", e);
            }

            BufUtil.doneWriting(output);
        }

        if (finished) {
            processedSeq(handle);
        }
    }

    @Override
    public Buf input() {
        return input;
    }

    @Override
    public Buf output() {
        return output;
    }

    @Override
    public OutputStream outputStream() {
        return output.asOutputStream();
    }

    @Override
    public boolean onSameThread() {
        return worker.onSameThread();
    }

    @Override
    public RapidoidHelper helper() {
        return worker.helper();
    }

    public CtxListener listener() {
        return listener;
    }

    public void setListener(CtxListener listener) {
        this.listener = listener;
    }

    @Override
    public String address() {
        InetSocketAddress inetSocketAddress = getAddress();
        return inetSocketAddress != null ? inetSocketAddress.getAddress().getHostAddress() : null;
    }

    @Override
    public Channel close() {
        close(true);
        return this;
    }

    @Override
    public Channel closeIf(boolean condition) {
        if (condition) {
            close();
        }
        return this;
    }

    @Override
    public String readln() {
        return input().readLn();
    }

    @Override
    public String readN(int count) {
        return input().readN(count);
    }

    @Override
    public ConnState state() {
        return state;
    }

    @Override
    public long handle() {
        return readSeq.get();
    }

    @Override
    public boolean isInitial() {
        return initial;
    }

    @Override
    public String toString() {
        return "conn#" + connId();
    }

    public void setInitial(boolean initial) {
        this.initial = initial;
    }

    @Override
    public synchronized long async() {
        U.must(onSameThread(), "The connection can be marked as 'async' only on its I/O worker thread!");

        this.async = true;
        this.done = false;
        return handle();
    }

    @Override
    public synchronized boolean isAsync() {
        return async;
    }

    public boolean isClient() {
        return isClient;
    }

    public void setClient(boolean isClient) {
        this.isClient = isClient;
    }

    public void setProtocol(Protocol protocol) {
        this.protocol = protocol;
    }

    public Protocol getProtocol() {
        return protocol;
    }

    @Override
    public boolean isClosing() {
        return closing;
    }

    @Override
    public boolean isClosed() {
        return closed;
    }

    @Override
    public void waitUntilClosing() {
        if (!isClosing()) {
            throw Buf.INCOMPLETE_READ;
        }
    }

    @Override
    public long connId() {
        return id;
    }

    @Override
    public long requestId() {
        return requestId;
    }

    @Override
    public void setRequest(IRequest request) {
        this.request = request;
    }

    @Override
    public void setExpiresAt(long expiresAt) {
        this.expiresAt = expiresAt;
    }

    @Override
    public long getExpiresAt() {
        return expiresAt;
    }

    @Override
    public void expire() {
        close(false);
    }

    public boolean finishedWriting() {
        return outgoing.size() == 0;
    }

    public ChannelHolderImpl holder() {
        return holder;
    }

    public RapidoidConnection holder(ChannelHolderImpl holder) {
        this.holder = holder;
        return this;
    }

    public int nextOp() {
        return nextOp;
    }

    @Override
    public RapidoidConnection nextOp(int nextOp) {
        this.nextOp = nextOp;
        return this;
    }

    public int mode() {
        return mode;
    }

    @Override
    public RapidoidConnection mode(int mode) {
        this.mode = mode;
        return this;
    }

    public boolean autoReconnect() {
        return autoReconnect;
    }

    public RapidoidConnection autoReconnect(boolean autoReconnect) {
        this.autoReconnect = autoReconnect;
        return this;
    }

    @Override
    public Channel restart() {
        return null; // FIXME
    }

    @Override
    public ChannelHolder createHolder() {
        return null; // FIXME
    }

    @Override
    public Channel nextWrite() {
        return null; // FIXME
    }

    public ChannelHolderImpl getHolder() {
        return holder;
    }

    public void setHolder(ChannelHolderImpl holder) {
        this.holder = holder;
    }
}


text:
// This file is part of libigl, a simple c++ geometry processing library.
//
// Copyright (C) 2015 Alec Jacobson <alecjacobson@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public License
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.
#include "decimate.h"
#include "collapse_edge.h"
#include "edge_flaps.h"
#include "remove_unreferenced.h"
#include "max_faces_stopping_condition.h"
#include <iostream>

IGL_INLINE bool igl::decimate(
  const Eigen::MatrixXd & V,
  const Eigen::MatrixXi & F,
  const size_t max_m,
  Eigen::MatrixXd & U,
  Eigen::MatrixXi & G)
{
  int m = F.rows();
  const auto & shortest_edge_and_midpoint = [](
    const int e,
    const Eigen::MatrixXd & V,
    const Eigen::MatrixXi & /*F*/,
    const Eigen::MatrixXi & E,
    const Eigen::VectorXi & /*EMAP*/,
    const Eigen::MatrixXi & /*EF*/,
    const Eigen::MatrixXi & /*EI*/,
    double & cost,
    Eigen::RowVectorXd & p)
  {
    cost = (V.row(E(e,0))-V.row(E(e,1))).norm();
    p = 0.5*(V.row(E(e,0))+V.row(E(e,1)));
  };
  return decimate(
    V,
    F,
    shortest_edge_and_midpoint,
    max_faces_stopping_condition(m,max_m),
    U,
    G);
}

IGL_INLINE bool igl::decimate(
  const Eigen::MatrixXd & OV,
  const Eigen::MatrixXi & OF,
  const std::function<void(
    const int,
    const Eigen::MatrixXd &,
    const Eigen::MatrixXi &,
    const Eigen::MatrixXi &,
    const Eigen::VectorXi &,
    const Eigen::MatrixXi &,
    const Eigen::MatrixXi &,
    double &,
    Eigen::RowVectorXd &)> & cost_and_placement,
  const std::function<bool(
      const Eigen::MatrixXd &,
      const Eigen::MatrixXi &,
      const Eigen::MatrixXi &,
      const Eigen::VectorXi &,
      const Eigen::MatrixXi &,
      const Eigen::MatrixXi &,
      const std::set<std::pair<double,int> > &,
      const std::vector<std::set<std::pair<double,int> >::iterator > &,
      const Eigen::MatrixXd &,
      const int,
      const int,
      const int,
      const int,
      const int)> & stopping_condition,
  Eigen::MatrixXd & U,
  Eigen::MatrixXi & G)
{
  using namespace Eigen;
  using namespace std;
  // Working copies
  Eigen::MatrixXd V = OV;
  Eigen::MatrixXi F = OF;
  VectorXi EMAP;
  MatrixXi E,EF,EI;
  typedef std::set<std::pair<double,int> > PriorityQueue;
  PriorityQueue Q;
  std::vector<PriorityQueue::iterator > Qit;
  edge_flaps(F,E,EMAP,EF,EI);
  Qit.resize(E.rows());
  // If an edge were collapsed, we'd collapse it to these points:
  MatrixXd C(E.rows(),V.cols());
  for(int e = 0;e<E.rows();e++)
  {
    double cost = e;
    RowVectorXd p(1,3);
    cost_and_placement(e,V,F,E,EMAP,EF,EI,cost,p);
    C.row(e) = p;
    Qit[e] = Q.insert(std::pair<double,int>(cost,e)).first;
  }

  int prev_e = -1;
  bool clean_finish = false;
  while(true)
  {
    if(Q.empty())
    {
      break;
    }
    if(Q.begin()->first == std::numeric_limits<double>::infinity())
    {
      // min cost edge is infinite cost
      break;
    }
    int e,e1,e2,f1,f2;
    if(collapse_edge(cost_and_placement,V,F,E,EMAP,EF,EI,Q,Qit,C,e,e1,e2,f1,f2))
    {
      if(stopping_condition(V,F,E,EMAP,EF,EI,Q,Qit,C,e,e1,e2,f1,f2))
      {
        clean_finish = true;
        break;
      }
    }else
    {
      if(prev_e == e)
      {
        assert(false && "Edge collapse no progress... bad stopping condition?");
        break;
      }
      // Edge was not collapsed... must have been invalid. collapse_edge should
      // have updated its cost to inf... continue
    }
    prev_e = e;
  }
  // remove all IGL_COLLAPSE_EDGE_NULL faces
  MatrixXi F2(F.rows(),3);
  int m = 0;
  for(int f = 0;f<F.rows();f++)
  {
    if(
      F(f,0) != IGL_COLLAPSE_EDGE_NULL ||
      F(f,1) != IGL_COLLAPSE_EDGE_NULL ||
      F(f,2) != IGL_COLLAPSE_EDGE_NULL)
    {
      F2.row(m++) = F.row(f);
    }
  }
  F2.conservativeResize(m,F2.cols());
  VectorXi _1;
  remove_unreferenced(V,F2,U,G,_1);
  return clean_finish;
}


text:
package org.apache.xmlbeans.impl.values;

import org.apache.xmlbeans.XmlDuration;
import org.apache.xmlbeans.SchemaType;

public class XmlDurationImpl extends JavaGDurationHolderEx implements XmlDuration
{
    public XmlDurationImpl()
        { super(XmlDuration.type, false); }
    public XmlDurationImpl(SchemaType type, boolean complex)
        { super(type, complex); }
}


text:
\c dsp_db1
Drop table if exists dsp_ck_1;
Create table dsp_ck_1 ( i int, j int);
select relstorage, reloptions,checksum from pg_class c , pg_appendonly a where c.oid=a.relid and c.relname='dsp_ck_1';
Drop table dsp_ck_1;

-- Database - checksum=true ; Role - checksum=false

\c dsp_db1 dsp_role1
Create table dsp_ck_1 ( i int, j int);
select relstorage, reloptions,checksum from pg_class c , pg_appendonly a where c.oid=a.relid and c.relname='dsp_ck_1';
Drop table dsp_ck_1;

-- Database - checksum=true ; Role - checksum=false, Session - checksum=true

\c dsp_db1 dsp_role1
SET gp_default_storage_options='appendonly=true, checksum=true';
Create table dsp_ck_1 ( i int, j int);
select relstorage, reloptions,checksum from pg_class c , pg_appendonly a where c.oid=a.relid and c.relname='dsp_ck_1';
Drop table dsp_ck_1;

-- Database - checksum=true ; Role - checksum=false, Session - checksum=true, Table - checksum=false

\c dsp_db1 dsp_role1
SET gp_default_storage_options='appendonly=true, checksum=true';
Create table dsp_ck_1 ( i int, j int) with (checksum=false);
select relstorage, reloptions,checksum from pg_class c , pg_appendonly a where c.oid=a.relid and c.relname='dsp_ck_1';
Drop table dsp_ck_1;


text:
title: Server-side
page_title: Server-side - RadMap
description: Check our Web Forms article about Server-side.
slug: map/data-binding/server-side
tags: server-side
published: True
position: 1
---

# Server-side

The markers and layers of the **ASP.NET AJAX Map** control can be bound both [client-side]({%slug map/data-binding/client-side%}) client-side and server-side, as the way to achieve the later is described in this article.	In **Example 1** you will see how to bind RadMap with a server-side collection, as the result from this sample is shown in **Figure 1**.	You can also use the RadMap's **OnItemCreared** and **OnItemDataBound** server-side events to additionally manipulate the data.

**RadMap** can use the standard data sources for binding an ASP.NET control:

* Declarative ASP.NET data sources (SqlDatasource, ObjectDataSource, LinqDataSource, etc.)

* Server-side collections that implement the **IEnumerable** interface.

>caption **Figure 1**: Binding layers and markers in RadMap to a collection of custom objects.

![map-server-side-binding](images/map-server-side-binding.png)

## Binding Markers

Similar to setting a data source for an ASP.NET control, you should either use the **DataSourceID** property when data binding markers declaratively or **DataSource** when the data source of the control is set on the server (such is the case in **Example 1**).

The data source should have columns for each of the map fields that you want to specify. For example, if you want to pull the title of the markers from the data source, this will require a separate column that contains the titles of each marker.

The columns of the data source are attached to their corresponding data fields in the markers via the properties with the structure **Data[*field name*]Name** in **RadMap > DataBindings > MarkerBinding**. For example: **DataShapeField**, **DataTitleField**, etc. You can find the full set of the MapMarker object's properties in the [Server-Side API of RadMap](https://www.telerik.com/help/aspnet-ajax/t_telerik_web_ui_radmap.html).

Binding the **Marker**'s **Shape** value can enable you to create an optional, custom look of the bound markers. You can examine the [Customizing Markers in RadMap]({%slug map/appearance-and-styling/customizing-markers-in-radmap%}) article.

## Binding Layers

Following the same logic, when binding layers you should use either the **LayersDataSourceID** property when data binding layers declaratively or **LayersDataSource** when the data source of the control is set on the server (you can refer **Example 1** for a sample configuration).

The columns of the data source here are also attached to their corresponding data fields in the layers via the properties with the structure **Data[*field name*]Name** in **RadMap > DataBindings > LayerBinding**. For example: **DataTypeField**, **DataUrlTemplateField**, etc. You can find the full set of the MapLayer object's properties in the [Server-Side API of RadMap](https://www.telerik.com/help/aspnet-ajax/t_telerik_web_ui_radmap.html).

## Examples

In the example below you will see a way to databind the layers and the markers of a RadMap control to a server-side object. The result of this code is shown in **Figure 1**.

>caption **Example 1**: Data binding layers and markers in a map to a collection of custom objects.

````ASP.NET
<telerik:RadMap RenderMode="Lightweight" runat="server" ID="RadMap1" Zoom="3" Width="800" Height="400">
	<CenterSettings Latitude="40" Longitude="30" />
	<DataBindings>
		<LayerBinding
			DataTypeField="type"
			DataUrlTemplateField="urlTemplate"
			DataAttributionField="attribution"
			DataSubdomainsField="subdomains"
			DataMaxZoomField="maxZoom"
			DataMinZoomField="minZoom"
			DataOpacityField="opacity" />
		<MarkerBinding
			DataShapeField="shape"
			DataTitleField="title"
			DataLocationLatitudeField="locationLatitude"
			DataLocationLongitudeField="locationLongitude"
			DataTooltipTemplateField="tooltipTemplate" />
	</DataBindings>
</telerik:RadMap>
````
````C#
protected void Page_Load(object sender, EventArgs e)
{
	if (!IsPostBack)
	{
		RadMap1.LayersDataSource = GetLayers();
		RadMap1.DataSource = GetMarkers();
		RadMap1.DataBind();
	}
}

private IEnumerable GetLayers()
{
	return new[] {
		new {type=Telerik.Web.UI.Map.LayerType.Tile,
			urlTemplate="https://#= subdomain #.tile.openstreetmap.org/#= zoom #/#= x #/#= y #.png",
			attribution="© <a href='https://osm.org/copyright' title='OpenStreetMap contributors' target='_blank'>OpenStreetMap contributors</a>.",
			subdomains="a,b,c",
			maxZoom="3",
			minZoom="1",
			opacity="1"
		}
	};
}

private IEnumerable GetMarkers()
{
	return new[] {
		new {shape="pinTarget", title="Sofia",   locationLatitude=42.650613, locationLongitude=23.379025, tooltipTemplate="#= location.lat # #= marker.options.title #"},
		new {shape="pinTarget", title="Munich",  locationLatitude=48.117227, locationLongitude=11.601990, tooltipTemplate="#= location.lat # #= marker.options.title #"},
		new {shape="pinTarget", title="London",  locationLatitude=51.515986, locationLongitude=-0.085798, tooltipTemplate="#= location.lat # #= marker.options.title #"},
		new {shape="pinTarget", title="Gurgaon", locationLatitude=28.410139, locationLongitude=77.042439, tooltipTemplate="#= location.lat # #= marker.options.title #"}
	};
}
````
````VB
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
	If Not IsPostBack Then
		RadMap1.LayersDataSource = GetLayers()
		RadMap1.DataSource = GetMarkers()
		RadMap1.DataBind()
	End If
End Sub

Private Function GetLayers() As IEnumerable
	Return New Object() {New With { _
		.type = Telerik.Web.UI.Map.LayerType.Tile, _
		.urlTemplate = "https://#= subdomain #.tile.openstreetmap.org/#= zoom #/#= x #/#= y #.png", _
		.attribution = "© <a href='https://osm.org/copyright' title='OpenStreetMap contributors' target='_blank'>OpenStreetMap contributors</a>.", _
		.subdomains = "a,b,c", _
		.maxZoom = "3", _
		.minZoom = "1", _
		.opacity = "1" _
	}}
End Function

Private Function GetMarkers() As IEnumerable
	Return New Object() {
		New With {.shape = "pinTarget", .title = "Sofia", .locationLatitude = 42.650613, .locationLongitude = 23.379025, .tooltipTemplate = "#= location.lat # #= marker.options.title #"},
		New With {.shape = "pinTarget", .title = "Munich", .locationLatitude = 48.117227, .locationLongitude = 11.60199, .tooltipTemplate = "#= location.lat # #= marker.options.title #"},
		New With {.shape = "pinTarget", .title = "London", .locationLatitude = 51.515986, .locationLongitude = -0.085798, .tooltipTemplate = "#= location.lat # #= marker.options.title #"},
		New With {.shape = "pinTarget", .title = "Gurgaon", .locationLatitude = 28.410139, .locationLongitude = 77.042439, .tooltipTemplate = "#= location.lat # #= marker.options.title #"}
	}
End Function
````

# See Also

 * [RadMap Server-Side API](https://www.telerik.com/help/aspnet-ajax/t_telerik_web_ui_radmap.html)


text:
using Ds3.Helpers.Strategies.ChunkStrategies;
using Ds3.Helpers.Strategies.StreamFactory;

namespace Ds3.Helpers.Strategies
{
    /// <summary>
    /// The WriteRandomAccessHelperStrategy bundle WriteRandomAccessChunkStrategy with WriteRandomAccessStreamFactory
    /// </summary>
    public class WriteRandomAccessHelperStrategy : IHelperStrategy<string>
    {
        private readonly IChunkStrategy _writeRandomAccessChunkStrategy;
        private readonly IStreamFactory<string> _writeRandomAccessStreamFactory;

        public WriteRandomAccessHelperStrategy(int retryAfter = -1, bool withAggregation = false)
        {
            this._writeRandomAccessChunkStrategy = new WriteRandomAccessChunkStrategy(retryAfter, withAggregation);
            this._writeRandomAccessStreamFactory = new WriteRandomAccessStreamFactory();
        }

        public IChunkStrategy GetChunkStrategy()
        {
            return this._writeRandomAccessChunkStrategy;
        }

        public IStreamFactory<string> GetStreamFactory()
        {
            return this._writeRandomAccessStreamFactory;
        }
    }
}