text:
package org.codehaus.enunciate;

import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.Resource;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectHelper;
import org.apache.maven.shared.filtering.MavenFileFilter;
import org.apache.maven.shared.filtering.MavenFilteringException;
import org.codehaus.enunciate.config.EnunciateConfiguration;
import org.codehaus.enunciate.main.Enunciate;
import org.codehaus.enunciate.modules.*;
import org.xml.sax.SAXException;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * Goal which initializes an Enunciate build process.
 *
 * @goal config
 * @phase validate
 * @requiresDependencyResolution test
 */
public class ConfigMojo extends AbstractMojo {

  public static final String ENUNCIATE_PROPERTY = "urn:" + ConfigMojo.class.getName() + "#enunciate";
  public static final String ENUNCIATE_STEPPER_PROPERTY = "urn:" + ConfigMojo.class.getName() + "#stepper";
  public static final String SOURCE_JAR_MAP_PROPERTY = "urn:" + ConfigMojo.class.getName() + "#source_jars";

  /**
   * The Maven project reference.
   *
   * @parameter expression="${project}"
   * @required
   * @readonly
   */
  protected MavenProject project;

  /**
   * Maven ProjectHelper
   *
   * @component
   * @readonly
   */
  private MavenProjectHelper projectHelper;

  /**
   * @parameter expression="${plugin.artifacts}"
   * @required
   * @readonly
   */
  protected Collection<org.apache.maven.artifact.Artifact> pluginDepdendencies;

  /**
   * Project artifacts.
   *
   * @parameter
   */
  private org.codehaus.enunciate.Artifact[] artifacts;

  /**
   * The enunciate configuration file to use.
   *
   * @parameter
   */
  private File configFile = null;

  /**
   * The output directory for the "generate" step.
   *
   * @parameter expression="${enunciate.generateDir}" default-value="${project.build.directory}/enunciate/generate"
   */
  private File generateDir = null;

  /**
   * The output directory for the "compile" step.
   *
   * @parameter expression="${enunciate.compileDir}" default-value="${project.build.directory}/enunciate/compile"
   */
  private File compileDir = null;

  /**
   * The -encoding argument for the Java compiler.
   *
   * @parameter expression="${compilationEncoding}" default-value="${project.build.sourceEncoding}"
   */
  private String compilationEncoding = null;

  /**
   * The output directory for the "build" step.
   *
   * @parameter expression="${enunciate.buildDir}" default-value="${project.build.directory}/enunciate/build"
   */
  private File buildDir = null;

  /**
   * The output directory for the "package" step.
   *
   * @parameter expression="${enunciate.packageDir}" default-value="${project.build.directory}/enunciate/package"
   */
  private File packageDir = null;

  /**
   * The directory where Enunciate puts scratch files.
   *
   * @parameter expression="${enunciate.scratchDir}" default-value="${project.build.directory}/enunciate-scratch"
   */
  private File scratchDir = null;

  /**
   * The directory for the generated WAR.
   *
   * @parameter expression="${project.build.directory}"
   * @required
   */
  private File outputDir = null;

  /**
   * Whether to add the GWT sources to the project compile sources.
   *
   * @parameter
   */
  private boolean addGWTSources = true;

  /**
   * Whether to add the actionscript sources to the project compile sources.
   *
   * @parameter
   */
  private boolean addActionscriptSources = true;

  /**
   * Whether to add the XFire client sources to the project test sources.
   *
   * @parameter
   */
  private boolean addXFireClientSourcesToTestClasspath = false;

  /**
   * Whether to add the Java client sources to the project test sources.
   *
   * @parameter alias="addJAXWSClientSourcesToTestClasspath"
   */
  private boolean addJavaClientSourcesToTestClasspath = false;

  /**
   * List of modules that are to be excluded as extensions to this project.
   *
   * @parameter
   */
  private String[] excludeProjectExtensions;

  /**
   * List of extra arguments to Enunciate's javac.
   *
   * @parameter
   */
  private String[] javacArguments;

  /**
   * Whether to include reference trail information in validation errors.
   *
   * @parameter expression="${includeReferenceTrailInErrors}" default-value="false"
   */
  private boolean includeReferenceTrailInErrors = false;

  /**
   * The GWT home.
   *
   * @parameter
   */
  private String gwtHome = null;

  /**
   * The Flex home.
   *
   * @parameter
   */
  private String flexHome = null;

  /**
   * Whether to compile with debug information.
   *
   * @parameter
   */
  private boolean compileDebug = true;

  /**
   * The exports.
   *
   * @parameter
   */
  private Map<String, String> exports = new HashMap<String, String>();

  /**
   * The include patterns.
   *
   * @parameter
   */
  private String[] includes;

  /**
   * The exclude patterns.
   *
   * @parameter
   */
  private String[] excludes;

  /**
   * Additional classpath entries.
   *
   * @parameter
   */
  private String[] additionalClasspathEntries;

  /**
   * @parameter expression="${session}"
   * @readonly
   */
  private MavenSession session;

  /**
   * Maven file filter.
   *
   * @component role="org.apache.maven.shared.filtering.MavenFileFilter" role-hint="default"
   * @readonly
   */
  private MavenFileFilter configFilter;

  /**
   * @parameter expression="${enunciate.javac.check}" default-value="false"
   */
  private boolean javacCheck = false;

  /**
   * javac -source version parameter
   *
   * @parameter
   */
  private String javacSourceVersion = null;

  /**
   * javac -target version parameter
   *
   * @parameter
   */
  private String javacTargetVersion = null;

  /**
   * List of source directories that are enunciate-added.
   */
  private /*static final */ TreeSet<String> ENUNCIATE_ADDED = new TreeSet<String>();

  /**
   * A flag used to disable enunciate. This is primarily intended for usage from the command line to occasionally
   * adjust the build.
   *
   * @parameter expression="${enunciate.skip}" default-value="false"
   */
  protected boolean skipEnunciate;
  /**
   * Used to look up Artifacts in the remote repository.
   *
   * @parameter expression= "${component.org.apache.maven.artifact.factory.ArtifactFactory}"
   * @required
   * @readonly
   */
  private ArtifactFactory artifactFactory;
  /**
   * Used to look up Artifacts in the remote repository.
   *
   * @parameter expression="${component.org.apache.maven.artifact.resolver.ArtifactResolver}"
   * @required
   * @readonly
   */
  private ArtifactResolver artifactResolver;
  /**
   * Location of the local repository.
   *
   * @parameter expression="${localRepository}"
   * @readonly
   * @required
   */
  private ArtifactRepository localRepository;

  public void execute() throws MojoExecutionException {
    if (skipEnunciate) {
      getLog().info("Skipping enunciate per configuration.");
      return;
    }

    Set<File> sourceDirs = new HashSet<File>();
    Collection<String> sourcePaths = (Collection<String>) project.getCompileSourceRoots();
    for (String sourcePath : sourcePaths) {
      File sourceDir = new File(sourcePath);
      if (!isEnunciateAdded(sourceDir)) {
        sourceDirs.add(sourceDir);
      }
      else {
        getLog().info(sourceDir + " appears to be added to the source roots by Enunciate.  Excluding from original source roots....");
      }
    }

    MavenSpecificEnunciate enunciate = loadMavenSpecificEnunciate(sourceDirs);
    enunciate.setJavacCheck(this.javacCheck);
    EnunciateConfiguration config = createEnunciateConfiguration();
    config.setLabel(project.getArtifactId());
    if (this.configFile != null) {
      try {
        loadConfig(config, this.configFile);
      }
      catch (Exception e) {
        throw new MojoExecutionException("Problem with enunciate config file " + this.configFile, e);
      }
      enunciate.setConfigFile(this.configFile);
    }
    else {
      File defaultConfig = new File(project.getBasedir(), "enunciate.xml");
      if (defaultConfig.exists()) {
        getLog().info(defaultConfig.getAbsolutePath() + " exists, so it will be used.");
        try {
          loadConfig(config, defaultConfig);
        }
        catch (Exception e) {
          throw new MojoExecutionException("Problem with enunciate config file " + defaultConfig, e);
        }
        enunciate.setConfigFile(defaultConfig);
      }
    }

    postProcessConfig(config);
    enunciate.setConfig(config);
    Set<org.apache.maven.artifact.Artifact> classpathEntries = new LinkedHashSet<org.apache.maven.artifact.Artifact>();
    classpathEntries.addAll(((Set<org.apache.maven.artifact.Artifact>) this.project.getArtifacts()));
    Iterator<org.apache.maven.artifact.Artifact> it = classpathEntries.iterator();
    while (it.hasNext()) {
      org.apache.maven.artifact.Artifact artifact = it.next();
      String artifactScope = artifact.getScope();
      if (org.apache.maven.artifact.Artifact.SCOPE_TEST.equals(artifactScope)) {
        //remove just the test-scope artifacts from the classpath.
        it.remove();
      }
    }

    StringBuffer classpath = new StringBuffer();
    Iterator<org.apache.maven.artifact.Artifact> classpathIt = classpathEntries.iterator();
    while (classpathIt.hasNext()) {
      classpath.append(classpathIt.next().getFile().getAbsolutePath());
      if (classpathIt.hasNext()) {
        classpath.append(File.pathSeparatorChar);
      }
    }
    if (additionalClasspathEntries != null) {
      for (String additionalClasspathEntry : additionalClasspathEntries) {
        classpath.append(File.pathSeparatorChar).append(additionalClasspathEntry);
      }
    }
    enunciate.setRuntimeClasspath(classpath.toString());

    classpathEntries.clear();
    classpathEntries.addAll(this.pluginDepdendencies);
    classpath = new StringBuffer();
    classpathIt = classpathEntries.iterator();
    while (classpathIt.hasNext()) {
      classpath.append(classpathIt.next().getFile().getAbsolutePath());
      if (classpathIt.hasNext()) {
        classpath.append(File.pathSeparatorChar);
      }
    }
    enunciate.setBuildClasspath(classpath.toString());

    if (this.generateDir != null) {
      enunciate.setGenerateDir(this.generateDir);
    }

    if (this.compileDir != null) {
      enunciate.setCompileDir(this.compileDir);
    }

    if (this.buildDir != null) {
      enunciate.setBuildDir(this.buildDir);
    }

    if (this.packageDir != null) {
      enunciate.setPackageDir(this.packageDir);
    }

    if (this.scratchDir != null) {
      enunciate.setScratchDir(this.scratchDir);
    }

    if (this.javacSourceVersion != null)
    {
    	enunciate.setJavacSourceVersion(this.javacSourceVersion);
    }

    if (this.javacTargetVersion != null)
    {
    	enunciate.setJavacTargetVersion(this.javacTargetVersion);
    }

    if (this.exports != null) {
      for (String exportId : this.exports.keySet()) {
        String filename = this.exports.get(exportId);
        if (filename == null || "".equals(filename)) {
          throw new MojoExecutionException("Invalid (empty or null) filename for export " + exportId + ".");
        }
        File exportFile = new File(filename);
        if (!exportFile.isAbsolute()) {
          exportFile = new File(this.outputDir, filename);
        }

        enunciate.addExport(exportId, exportFile);
      }
    }

    enunciate.setCompileDebugInfo(this.compileDebug);

    try {
      enunciate.loadMavenConfiguration();
      Enunciate.Stepper stepper = enunciate.getStepper();
      getPluginContext().put(ENUNCIATE_STEPPER_PROPERTY, stepper);
      getPluginContext().put(ENUNCIATE_PROPERTY, enunciate);
    }
    catch (Exception e) {
      throw new MojoExecutionException("Error initializing Enunciate mechanism.", e);
    }
  }

  /**
   * Does any post-processing of the enunciate configuration.
   *
   * @param config The config.
   */
  protected void postProcessConfig(EnunciateConfiguration config) {
    if (this.includes != null) {
      for (String include : this.includes) {
        config.addApiIncludePattern(include);
      }
    }

    if (this.excludes != null) {
      for (String exclude : this.excludes) {
        config.addApiExcludePattern(exclude);
      }
    }

    config.setIncludeReferenceTrailInErrors(this.includeReferenceTrailInErrors);
  }

  /**
   * Load the config, do filtering as needed.
   *
   * @param config     The config to load into.
   * @param configFile The config file.
   */
  protected void loadConfig(EnunciateConfiguration config, File configFile) throws IOException, SAXException, MavenFilteringException {
    if (this.configFilter == null) {
      getLog().debug("No maven file filter was provided, so no filtering of the config file will be done.");
      config.load(configFile);
    }
    else {
      this.scratchDir.mkdirs();
      File filteredConfig = File.createTempFile("enunciateConfig", ".xml", this.scratchDir);
      getLog().debug("Filtering " + configFile + " to " + filteredConfig + "...");
      this.configFilter.copyFile(configFile, filteredConfig, true, this.project, new ArrayList(), true, "utf-8", this.session);
      config.load(filteredConfig);
    }
  }

  /**
   * Whether the given source directory is Enunciate-generated.
   *
   * @param sourceDir The source directory.
   * @return Whether the given source directory is Enunciate-generated.Whether the given source directory is Enunciate-generated.
   */
  protected boolean isEnunciateAdded(File sourceDir) {
    return ENUNCIATE_ADDED.contains(sourceDir.getAbsolutePath());
  }

  /**
   * Adds the specified source directory to the Maven project.
   *
   * @param dir The directory to add to the project.
   */
  protected void addSourceDirToProject(File dir) {
    String sourceDir = dir.getAbsolutePath();
    ENUNCIATE_ADDED.add(sourceDir);
    if (!project.getCompileSourceRoots().contains(sourceDir)) {
      getLog().debug("Adding '" + sourceDir + "' to the compile source roots.");
      project.addCompileSourceRoot(sourceDir);
    }
  }

  /**
   * Create an Enunciate configuration.
   *
   * @return The enunciate configuration.
   */
  protected EnunciateConfiguration createEnunciateConfiguration() {
    return new EnunciateConfiguration();
  }

  /**
   * Loads a correct instance of the Maven-specific Enunciate mechanism.
   *
   * @param sourceDirs The directories where the source files exist.
   * @return The maven-specific Enunciate mechanism.
   */
  protected MavenSpecificEnunciate loadMavenSpecificEnunciate(Set<File> sourceDirs) {
    return new MavenSpecificEnunciate(sourceDirs);
  }

  protected Set<String> getExcludedProjectExtensions() {
    TreeSet<String> excluded = new TreeSet<String>();
    if (excludeProjectExtensions != null) {
      excluded.addAll(Arrays.asList(excludeProjectExtensions));
    }

    if (!addActionscriptSources) {
      excluded.add("amf");
    }

    if (!addGWTSources) {
      excluded.add("gwt");
    }

    if (!addJavaClientSourcesToTestClasspath) {
      excluded.add("java-client");
    }

    if (!addXFireClientSourcesToTestClasspath) {
      excluded.add("xfire-client");
    }

    return excluded;
  }

  protected String lookupSourceJar(File pathEntry) {
    Map<File, String> sourceJars = (Map<File, String>) getPluginContext().get(SOURCE_JAR_MAP_PROPERTY);
    if (sourceJars == null) {
      sourceJars = new TreeMap<File, String>();
      getPluginContext().put(SOURCE_JAR_MAP_PROPERTY, sourceJars);
    }

    if (sourceJars.containsKey(pathEntry)) {
      return sourceJars.get(pathEntry);
    }

    String sourceJar = null;
    for (org.apache.maven.artifact.Artifact projectDependency : ((Set<org.apache.maven.artifact.Artifact>) this.project.getArtifacts())) {
      if (pathEntry.equals(projectDependency.getFile())) {
        if (skipSourceJarLookup(projectDependency)) {
          getLog().debug("Skipping the source lookup for " + projectDependency.toString() + "...");
        }

        getLog().debug("Attemping to lookup source artifact for " + projectDependency.toString() + "...");
        try {
          org.apache.maven.artifact.Artifact sourceArtifact = this.artifactFactory.createArtifactWithClassifier(projectDependency.getGroupId(), projectDependency.getArtifactId(),
                                                                                projectDependency.getVersion(), projectDependency.getType(), "sources");
          this.artifactResolver.resolve(sourceArtifact, this.project.getRemoteArtifactRepositories(), this.localRepository);
          String path = sourceArtifact.getFile().getAbsolutePath();
          getLog().debug("Source artifact found at " + path + ".");
          sourceJar = path;
          break;
        }
        catch (Exception e) {
          getLog().debug("Unable to lookup source artifact for path entry " + pathEntry, e);
          break;
        }
      }
    }

    sourceJars.put(pathEntry, sourceJar);

    return sourceJar;
  }

  /**
   * Whether to skip the source-jar lookup for the given dependency.
   *
   * @param projectDependency The dependency.
   * @return Whether to skip the source-jar lookup for the given dependency.
   */
  protected boolean skipSourceJarLookup(org.apache.maven.artifact.Artifact projectDependency) {
    String groupId = String.valueOf(projectDependency.getGroupId());
    return groupId.startsWith("com.sun.") //skip com.sun.*
      || "com.sun".equals(groupId) //skip com.sun
      || groupId.startsWith("javax."); //skip "javax.*"
  }

  /**
   * Enunciate mechanism that logs via the Maven logging mechanism.
   */
  protected class MavenSpecificEnunciate extends Enunciate {

    public MavenSpecificEnunciate(Collection<File> rootDirs) {
      super();
      ArrayList<String> sources = new ArrayList<String>();
      for (File rootDir : rootDirs) {
        sources.addAll(getJavaFiles(rootDir));
      }

      setSourceFiles(sources.toArray(new String[sources.size()]));
      setEncoding(compilationEncoding);
      if (javacArguments != null) {
        getConfiguredJavacArguments().addAll(Arrays.asList(javacArguments));
      }
    }

    public void loadMavenConfiguration() throws IOException {
      for (DeploymentModule module : getConfig().getAllModules()) {
        if (!module.isDisabled()) {
          if (gwtHome != null && (module instanceof GWTHomeAwareModule)) {
            ((GWTHomeAwareModule) module).setGwtHome(gwtHome);
          }
          else if (flexHome != null && (module instanceof FlexHomeAwareModule)) {
            ((FlexHomeAwareModule) module).setFlexHome(flexHome);
          }
        }
      }
    }

    @Override
    protected void initModules(Collection<DeploymentModule> modules) throws EnunciateException, IOException {
      super.initModules(modules);

      if (compileDir == null) {
        //set an explicit compile dir if one doesn't exist because we're going to need to reference it to set the output directory for Maven.
        setCompileDir(createTempDir());
      }

      for (DeploymentModule module : modules) {
        if (!module.isDisabled()) {
          if (project.getName() != null && !"".equals(project.getName().trim()) && module instanceof ProjectTitleAware) {
            ((ProjectTitleAware) module).setTitleConditionally(project.getName());
          }
          if (project.getVersion() != null && !"".equals(project.getVersion().trim()) && module instanceof ProjectVersionAware) {
            ((ProjectVersionAware) module).setProjectVersion(project.getVersion());
          }
        }
      }
    }

    @Override
    protected void doGenerate() throws IOException, EnunciateException {
      super.doGenerate();

      Set<String> excludedExtensions = getExcludedProjectExtensions();
      for (DeploymentModule module : getConfig().getAllModules()) {
        if (!module.isDisabled() && (module instanceof ProjectExtensionModule) && !excludedExtensions.contains(module.getName())) {
          ProjectExtensionModule extensions = (ProjectExtensionModule) module;
          for (File projectSource : extensions.getProjectSources()) {
            addSourceDirToProject(projectSource);
          }

          for (File testSource : extensions.getProjectTestSources()) {
            project.addTestCompileSourceRoot(testSource.getAbsolutePath());
          }

          for (File resourceDir : extensions.getProjectResourceDirectories()) {
            Resource restResource = new Resource();
            restResource.setDirectory(resourceDir.getAbsolutePath());
            project.addResource(restResource);
          }

          for (File resourceDir : extensions.getProjectTestResourceDirectories()) {
            Resource resource = new Resource();
            resource.setDirectory(resourceDir.getAbsolutePath());
            project.addTestResource(resource);
          }
        }
      }
    }

    @Override
    protected String lookupSourceEntry(File pathEntry) {
      return lookupSourceJar(pathEntry);
    }

    @Override
    public void info(String message, Object... formatArgs) {
      getLog().info(String.format(message, formatArgs));
    }

    @Override
    public void debug(String message, Object... formatArgs) {
      getLog().debug(String.format(message, formatArgs));
    }

    @Override
    public void warn(String message, Object... formatArgs) {
      getLog().warn(String.format(message, formatArgs));
    }

    @Override
    public void error(String message, Object... formatArgs) {
      getLog().error(String.format(message, formatArgs));
    }

    @Override
    public boolean isDebug() {
      return getLog().isDebugEnabled();
    }

    @Override
    public boolean isVerbose() {
      return getLog().isInfoEnabled();
    }

    @Override
    protected void doClose() throws EnunciateException, IOException {
      super.doClose();

      if (artifacts != null) {
        for (org.codehaus.enunciate.Artifact projectArtifact : artifacts) {
          if (projectArtifact.getEnunciateArtifactId() == null) {
            getLog().warn("No enunciate export id specified.  Skipping project artifact...");
            continue;
          }

          org.codehaus.enunciate.main.Artifact artifact = null;
          for (org.codehaus.enunciate.main.Artifact enunciateArtifact : getArtifacts()) {
            if (projectArtifact.getEnunciateArtifactId().equals(enunciateArtifact.getId())
              || enunciateArtifact.getAliases().contains(projectArtifact.getEnunciateArtifactId())) {
              artifact = enunciateArtifact;
              break;
            }
          }

          if (artifact != null) {
            File tempExportFile = createTempFile(project.getArtifactId() + "-" + projectArtifact.getClassifier(), projectArtifact.getArtifactType());
            artifact.exportTo(tempExportFile, this);
            projectHelper.attachArtifact(project, projectArtifact.getArtifactType(), projectArtifact.getClassifier(), tempExportFile);
          }
          else {
            getLog().warn("Enunciate artifact '" + projectArtifact.getEnunciateArtifactId() + "' not found in the project...");
          }
        }
      }
    }
  }
}


text:
class Cuisine < ApplicationRecord
  has_many :recipes
  has_many :users, through: :recipes

  validates :name, presence: true
end

redpajama_set_name: RedPajamaGithub


text:
require "rails_helper"

RSpec.describe Event, type: :model do
  context 'users want mail' do
    before :each do
      @user = FactoryGirl.create(:user)
      @user_ability = Ability.new(@user)
      @user2 = FactoryGirl.create(:user)
      @user2_ability = Ability.new(@user2)
      @event = FactoryGirl.create(:event, user: @user, target_user: @user2)
      expect(@user_ability.can? :receive_email, @event).to be false
      expect(@user2_ability.can? :receive_email, @event).to be true
      @user2.update(event_settings: [@event.type_id])
    end

    it 'doesn\'t send an email to the person that initiated' do
      expect(@event.users_want_mail).to_not include(@user)
    end

    it 'contains only users that can? :receive_email for the event' do
      expect(@event.users_want_mail).to include(@user2)
    end

    it 'contains only users that include the event type in the email settings' do
      expect(@event.users_want_mail).to include(@user2)
      @user2.update(event_settings: [])
      expect(@event.users_want_mail).to eq([])
    end
  end

  context 'mails are' do
    before :each do
      @user = FactoryGirl.create(:user)
      @user2 = FactoryGirl.create(:user)
      @event = FactoryGirl.build(:event, user: @user, target_user: @user2)
      @user2.update(event_settings: [@event.type_id])
    end

    it 'sent on event creation' do
      expect(@event.users_want_mail).to include(@user2)
      expect { @event.save! }.to change(ActionMailer::Base.deliveries, :count).by(1)
    end

    it 'not sent on creation if the event has mail disabled' do
      # enum mapping is stored in hash, thus first twice
      allow(Event).to receive(:NOMAIL) {[Event.types.first.first]}
      @event.type = Event.types.first.first
      expect(@event).to have_mail_disabled
      expect { @event.save! }.to change(ActionMailer::Base.deliveries, :count).by(0)
    end

    it 'not sent if no user wants mail for it' do
      @user.update(event_settings: [])
      @user2.update(event_settings: [])
      expect(@event).not_to have_mail_disabled
      expect(@event.always_send?).to be false
      expect { @event.save! }.to change(ActionMailer::Base.deliveries, :count).by(0)
    end

    it 'always sent if event type is in Event.ALWAYS_SEND' do
      @user2.update!(event_settings: [])
      allow(Event).to receive(:ALWAYS_SEND) {[Event.types.first.first]}
      @event.type = Event.types.first.first
      expect(@event.always_send?).to be true
      expect { @event.save! }.to change(ActionMailer::Base.deliveries, :count).by(1)
    end
  end
end


text:
         {% assign counter = 0 %}
         {% assign blogPosts = site.posts | where: "category", filter %}
         {% for post in blogPosts %}
            {% if post.featured == {{featured}} %}

                  {% if post.image != null %}

                  {% else %}

                  {% endif %}

                      {{ post.title }}

                     {% if post.featured == "true" %}Featured Post{% else %}
                     {{ post.date | date_to_string }}
                     {% endif %}
                     ">{% include social-media.html %}

                     {{ post.content | truncate:200 | split:'<a href' | first }}

Read More

            {% assign counter = counter | plus: 1 %}
            {% endif %}

            {% if counter == maxPost %}
               {% break %} {% comment %}exit the for loop{% endcomment %}
            {% endif %}
         {% endfor %}


text:
  Spécifie optionnellement l'adresse HTTP de l'installation de Hudson,
  comme <tt>http://yourhost.yourdomain/hudson/</tt>.
  Cette valeur est utilisée pour mettre des liens dans les emails envoyés
  par Hudson.

  Cela est nécessaire parce que Hudson ne peut pas détecter de façon
  fiable sa propre URL.


text:
<?xml version="1.0" encoding="UTF-8"?>
<ldswebml type="image" uri="/media-library/images/seasons/summer#feet-sand-905822" xml:lang="eng" locale="eng" status="publish" xmlns:its="http://www.w3.org/2005/11/its">
  <search-meta>
      <uri-title its:translate="no">feet-sand-905822</uri-title>
      <source>feet-sand-905822</source>
      <publication-type its:translate="no">image</publication-type>
      <media-type its:translate="no">image</media-type>
      <publication value="ldsorg">LDS.org</publication>
      <publication-date value="2012-11-08">2012-11-08</publication-date>
      <title/>
      <description/>
      <collections>
          <collection its:translate="no">global-search</collection>
          <collection its:translate="no">media</collection>
          <collection its:translate="no">images</collection>
      </collections>
      <subjects>
          <subject>Beaches</subject>
          <subject>Feet</subject>
          <subject>Sand</subject>
          <subject>Toes</subject>
      </subjects>
  </search-meta>
  <no-search>
      <path>http://media.ldscdn.org/images/media-library/seasons/summer/feet-sand-905822-gallery.jpg</path>
      <images>
          http://media.ldscdn.org/images/media-library/seasons/summer/feet-sand-905822-thumbnail.jpg
      </images>
          <download-urls>
              <download-url>
                  Mobile
                  <size>234 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/seasons/summer/feet-sand-905822-mobile.jpg</path>
              </download-url>
              <download-url>
                  Tablet
                  <size>319 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/seasons/summer/feet-sand-905822-tablet.jpg</path>
              </download-url>
              <download-url>
                  Print
                  <size>649 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/seasons/summer/feet-sand-905822-print.jpg</path>
              </download-url>
          </download-urls>
  </no-search>
</ldswebml>


text:
package org.apache.abdera.ext.serializer.annotation;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

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

@Retention(RUNTIME)
@Target( {TYPE, METHOD, FIELD})
@Convention(".*author(?:s)?")
public @interface Author {
}


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

<TITLE>
StringUtil (PlayMorphia API)
</TITLE>

<META NAME="date" CONTENT="2011-11-15">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

play.modules.morphia.utils

Class StringUtil

java.lang.Object
  play.modules.morphia.utils.StringUtil

public class StringUtil
extends java.lang.Object

Field Summary

static int
IGNORECASE

static int
IGNORESPACE

Constructor Summary

StringUtil()

Method Summary

static boolean
isEmpty(java.lang.String s)

static boolean
isEqual(java.lang.String s1,
        java.lang.String s2)

static boolean
isEqual(java.lang.String s1,
        java.lang.String s2,
        int modifier)

static java.lang.String
join(java.lang.String separator,
     java.util.Collection<?> list)

static java.lang.String
join(java.lang.String separator,
     java.util.Collection<?> list,
     boolean quoted)

static java.lang.String
join(java.lang.String separator,
     java.lang.String... list)

static java.lang.String
join(java.lang.String separator,
     java.lang.String prefix,
     java.lang.String suffix,
     java.util.Collection<?> list)

static java.lang.String
join(java.lang.String separator,
     java.lang.String prefix,
     java.lang.String suffix,
     java.util.Collection<?> list,
     boolean quoted)

static java.lang.String
lowerFirstChar(java.lang.String s)

static void
main(java.lang.String[] sa)

static java.lang.String
upperFirstChar(java.lang.String s)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

IGNORECASE

public static final int IGNORECASE

See Also:
Constant Field Values

IGNORESPACE

public static final int IGNORESPACE

See Also:
Constant Field Values

Constructor Detail

StringUtil

public StringUtil()

Method Detail

join

public static java.lang.String join(java.lang.String separator,
                                    java.util.Collection<?> list)

join

public static java.lang.String join(java.lang.String separator,
                                    java.util.Collection<?> list,
                                    boolean quoted)

join

public static java.lang.String join(java.lang.String separator,
                                    java.lang.String prefix,
                                    java.lang.String suffix,
                                    java.util.Collection<?> list,
                                    boolean quoted)

join

public static java.lang.String join(java.lang.String separator,
                                    java.lang.String prefix,
                                    java.lang.String suffix,
                                    java.util.Collection<?> list)

join

public static java.lang.String join(java.lang.String separator,
                                    java.lang.String... list)

isEmpty

public static boolean isEmpty(java.lang.String s)

isEqual

public static boolean isEqual(java.lang.String s1,
                              java.lang.String s2)

isEqual

public static boolean isEqual(java.lang.String s1,
                              java.lang.String s2,
                              int modifier)

upperFirstChar

public static java.lang.String upperFirstChar(java.lang.String s)

lowerFirstChar

public static java.lang.String lowerFirstChar(java.lang.String s)

main

public static void main(java.lang.String[] sa)

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
package sn.analytics.factgen.processor;

import org.apache.avro.Schema;
import org.apache.avro.file.DataFileWriter;
import org.apache.avro.specific.SpecificDatumWriter;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import parquet.avro.AvroParquetWriter;
import parquet.hadoop.metadata.CompressionCodecName;
import sn.analytics.factgen.FactGenerator;
import sn.analytics.factgen.type.AccessLogDatum;
import sn.analytics.type.LogData;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by Sumanth on 06/05/15.
 */
public class AvroDataProcessor implements DataProcessor {
    private Logger logger = LoggerFactory.getLogger(ParquetDataProcessor.class);
    //to generate schema
    // java -jar avro-tools-1.7.7.jar compile schema <schemafile> <outdir>

    private final String outFile;
    public Schema FACT_SCHEMA;

    SpecificDatumWriter<LogData> writer;
    DataFileWriter<LogData> dataFileWriter;

    public AvroDataProcessor(String outFile) {
        this.outFile = outFile;
    }

    @Override
    public void init() {
       initSchema();
        initWriter();
    }

    @Override
    public void processDataItem(AccessLogDatum datum) {
        LogData logData = new LogData();
        logData.accessUrl=datum.accessUrl;
        logData.responseStatusCode=datum.responseStatusCode;
        logData.responseTime=datum.responseTime;
        logData.accessTimestamp= DateTime.parse(datum.accessTimestamp, FactGenerator.MILL_SECONDS_FORMAT).getMillis();

        logData.requestVerb=datum.requestVerb;
        logData.requestSize=datum.requestSize;
        logData.dataExchangeSize=datum.dataExchangeSize;
        logData.serverIp=datum.serverIp;
        logData.clientIp=datum.clientIp;
        logData.clientId=datum.clientId;
        logData.sessionId=datum.sessionId;
        logData.userAgentDevice=datum.userAgentDevice;
        logData.UserAgentType=datum.UserAgentType;
        logData.userAgentFamily=datum.userAgentFamily;
        logData.userAgentOSFamily=datum.userAgentOSFamily;
        logData.userAgentVersion=datum.userAgentVersion;
        logData.userAgentOSVersion=datum.userAgentOSVersion;
        logData.city=datum.city;
        logData.country=datum.country;
        logData.region=datum.region;
        logData.minOfDay=datum.minOfDay;
        logData.hourOfDay=datum.hourOfDay;
        logData.dayOfWeek=datum.dayOfWeek;
        logData.monthOfYear=datum.monthOfYear;
        logData.day=datum.day;

        try {
            dataFileWriter.append(logData);

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

    @Override
    public void close() {

        try {
            dataFileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void initSchema(){
        InputStream streamReader =ParquetDataProcessor.class.getResourceAsStream("/LogData.avsc");
        try {
            FACT_SCHEMA= Schema.parse(streamReader);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private void initWriter(){
       File outStream= new File(outFile);

        writer=new SpecificDatumWriter<LogData>(FACT_SCHEMA);
        dataFileWriter=new DataFileWriter<LogData>(writer);
        try {
            dataFileWriter.create(FACT_SCHEMA,outStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}


text:
"""Tests that lint python conventions are followed throughout the codebase"""

from pylint import epylint as lint

from django.test import TestCase
from django.conf import settings

###############################################################################
class AutoLintTests(TestCase):
    """Python convention lint test class"""

    def test_pylint_check(self):
        """
        Use pylint to check ID codes from pylint features

        List of codes: http://docs.pylint.org/features.html
        """

        test_modules = ' '.join([settings.PROJECT_ROOT + mod for mod in\
            ['/apps', '/academicspam']])
        check_codes = ','.join(['W0401', 'W0611']) #'C0103' Names

        # Call pylint
        command = '--reports=n --disable=all --ignore=migrations\
                                --enable={checker} {modules}'.format(
            modules=test_modules,
            checker=check_codes
            )

        # command = '--reports=n --ignore=migrations {modules}'.format(
        #     modules=test_modules,
        #     checker=check_codes
        #     )

        # Run pylint, get results, returns (pylint_sdout, pylint_sderr)
        lint_sdout = lint.py_run(command, return_std=True, script='pylint')[0]

        pylintlog = lint_sdout.read()
        self.assertTrue(pylintlog == '', 'PyLint Log not empty\n' + pylintlog)


text:
namespace net {
namespace test {

namespace {
// Constant based on TCP defaults.
const QuicByteCount kMaxSegmentSize = kDefaultTCPMSS;
}  // namespace

class PrrSenderTest : public ::testing::Test {};

TEST_F(PrrSenderTest, SingleLossResultsInSendOnEveryOtherAck) {
  PrrSender prr;
  QuicPacketCount num_packets_in_flight = 50;
  QuicByteCount bytes_in_flight = num_packets_in_flight * kMaxSegmentSize;
  const QuicPacketCount ssthresh_after_loss = num_packets_in_flight / 2;
  const QuicByteCount congestion_window = ssthresh_after_loss * kMaxSegmentSize;

  prr.OnPacketLost(bytes_in_flight);
  // Ack a packet. PRR allows one packet to leave immediately.
  prr.OnPacketAcked(kMaxSegmentSize);
  bytes_in_flight -= kMaxSegmentSize;
  EXPECT_EQ(QuicTime::Delta::Zero(),
            prr.TimeUntilSend(congestion_window, bytes_in_flight,
                              ssthresh_after_loss * kMaxSegmentSize));
  // Send retransmission.
  prr.OnPacketSent(kMaxSegmentSize);
  // PRR shouldn't allow sending any more packets.
  EXPECT_EQ(QuicTime::Delta::Infinite(),
            prr.TimeUntilSend(congestion_window, bytes_in_flight,
                              ssthresh_after_loss * kMaxSegmentSize));

  // One packet is lost, and one ack was consumed above. PRR now paces
  // transmissions through the remaining 48 acks. PRR will alternatively
  // disallow and allow a packet to be sent in response to an ack.
  for (uint64_t i = 0; i < ssthresh_after_loss - 1; ++i) {
    // Ack a packet. PRR shouldn't allow sending a packet in response.
    prr.OnPacketAcked(kMaxSegmentSize);
    bytes_in_flight -= kMaxSegmentSize;
    EXPECT_EQ(QuicTime::Delta::Infinite(),
              prr.TimeUntilSend(congestion_window, bytes_in_flight,
                                ssthresh_after_loss * kMaxSegmentSize));
    // Ack another packet. PRR should now allow sending a packet in response.
    prr.OnPacketAcked(kMaxSegmentSize);
    bytes_in_flight -= kMaxSegmentSize;
    EXPECT_EQ(QuicTime::Delta::Zero(),
              prr.TimeUntilSend(congestion_window, bytes_in_flight,
                                ssthresh_after_loss * kMaxSegmentSize));
    // Send a packet in response.
    prr.OnPacketSent(kMaxSegmentSize);
    bytes_in_flight += kMaxSegmentSize;
  }

  // Since bytes_in_flight is now equal to congestion_window, PRR now maintains
  // packet conservation, allowing one packet to be sent in response to an ack.
  EXPECT_EQ(congestion_window, bytes_in_flight);
  for (int i = 0; i < 10; ++i) {
    // Ack a packet.
    prr.OnPacketAcked(kMaxSegmentSize);
    bytes_in_flight -= kMaxSegmentSize;
    EXPECT_EQ(QuicTime::Delta::Zero(),
              prr.TimeUntilSend(congestion_window, bytes_in_flight,
                                ssthresh_after_loss * kMaxSegmentSize));
    // Send a packet in response, since PRR allows it.
    prr.OnPacketSent(kMaxSegmentSize);
    bytes_in_flight += kMaxSegmentSize;

    // Since bytes_in_flight is equal to the congestion_window,
    // PRR disallows sending.
    EXPECT_EQ(congestion_window, bytes_in_flight);
    EXPECT_EQ(QuicTime::Delta::Infinite(),
              prr.TimeUntilSend(congestion_window, bytes_in_flight,
                                ssthresh_after_loss * kMaxSegmentSize));
  }
}

TEST_F(PrrSenderTest, BurstLossResultsInSlowStart) {
  PrrSender prr;
  QuicByteCount bytes_in_flight = 20 * kMaxSegmentSize;
  const QuicPacketCount num_packets_lost = 13;
  const QuicPacketCount ssthresh_after_loss = 10;
  const QuicByteCount congestion_window = ssthresh_after_loss * kMaxSegmentSize;

  // Lose 13 packets.
  bytes_in_flight -= num_packets_lost * kMaxSegmentSize;
  prr.OnPacketLost(bytes_in_flight);

  // PRR-SSRB will allow the following 3 acks to send up to 2 packets.
  for (int i = 0; i < 3; ++i) {
    prr.OnPacketAcked(kMaxSegmentSize);
    bytes_in_flight -= kMaxSegmentSize;
    // PRR-SSRB should allow two packets to be sent.
    for (int j = 0; j < 2; ++j) {
      EXPECT_EQ(QuicTime::Delta::Zero(),
                prr.TimeUntilSend(congestion_window, bytes_in_flight,
                                  ssthresh_after_loss * kMaxSegmentSize));
      // Send a packet in response.
      prr.OnPacketSent(kMaxSegmentSize);
      bytes_in_flight += kMaxSegmentSize;
    }
    // PRR should allow no more than 2 packets in response to an ack.
    EXPECT_EQ(QuicTime::Delta::Infinite(),
              prr.TimeUntilSend(congestion_window, bytes_in_flight,
                                ssthresh_after_loss * kMaxSegmentSize));
  }

  // Out of SSRB mode, PRR allows one send in response to each ack.
  for (int i = 0; i < 10; ++i) {
    prr.OnPacketAcked(kMaxSegmentSize);
    bytes_in_flight -= kMaxSegmentSize;
    EXPECT_EQ(QuicTime::Delta::Zero(),
              prr.TimeUntilSend(congestion_window, bytes_in_flight,
                                ssthresh_after_loss * kMaxSegmentSize));
    // Send a packet in response.
    prr.OnPacketSent(kMaxSegmentSize);
    bytes_in_flight += kMaxSegmentSize;
  }
}

}  // namespace test
}  // namespace net


text:
var _ = require('underscore');
var expect = require('chai').expect;
var helpers = require('../helpers');
var UserNatural = require('../../lib/models/UserNatural');

describe('Cards', function () {
    var john = new UserNatural(helpers.data.getUserNatural());

    before(function (done) {
        api.Users.create(john).then(function (data, response) {
            john = data;
            done();
        });
    });

    describe('Get PreAuthorizations', function () {
        var getPreAuthorizations;

        before(function (done) {
            helpers.getNewPayInCardDirect(api, john, function (data) {
                api.Cards.getPreAuthorizations(data.CardId, function (data, response) {
                    getPreAuthorizations = data;
                    done();
                });
            });
        });

        it('should be retrieved', function () {
            expect(getPreAuthorizations).not.to.be.undefined;
            expect(getPreAuthorizations).to.be.an('array');
        });
    });
});


text:
package com.heyzap.sdk;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.text.Html;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class LeaderboardFullOverlay extends ClickableToast {
    ImageView people;
    View whiteBg;
    private long shownAt;

    public LeaderboardFullOverlay(Context context) {
        super(context);
        this.setContentView(Rzap.layout("leaderboard_full_overlay"));
        this.setFocusable(true);
        this.setFocusableInTouchMode(true);

        TextView bigText = (TextView) findViewById(Rzap.id("big_text"));
        people = (ImageView) findViewById(Rzap.id("people"));
        whiteBg = (View) findViewById(Rzap.id("white_bg"));

        bigText.setText(Html.fromHtml("Play and rank
 against millions of players"));

        Button rejectButton = (Button) findViewById(Rzap.id("reject_button"));
        rejectButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                LeaderboardFullOverlay.this.hide();
            }
        });

        trackIfNotSubclassed(String.format("score-full-overlay-shown-first"));

        Button installButton = (Button) findViewById(Rzap.id("install_button"));

        OnClickListener marketListener = new OnClickListener() {

            @Override
            public void onClick(View v) {
            	launchMarket();
                hide();
            };
        };
        installButton.setOnClickListener(marketListener);

        setOrientation(getResources().getConfiguration().orientation);
    }

    @Override
    public WindowManager.LayoutParams getWmParams() {
        WindowManager.LayoutParams params = super.getWmParams();
        params.width = WindowManager.LayoutParams.FILL_PARENT;
        params.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
        params.verticalMargin = 0.0f;
        params.flags &= ~WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
        params.flags &= ~WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        params.flags |= WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH;
        return params;
    }

    @Override
    public void onConfigurationChanged(Configuration config) {
        setOrientation(config.orientation);
    }

    public void setOrientation(int orientation) {
        android.view.ViewGroup.LayoutParams params = null;
        if (whiteBg != null) {
            params = whiteBg.getLayoutParams();
        }
        if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
            if (people != null) {
                people.setVisibility(View.GONE);
            }
            if (params != null) {
                params.height = Utils.getScaledSize(getContext(), 206 - 64);
            }
        } else if (orientation == Configuration.ORIENTATION_PORTRAIT) {
            if (people != null) {
                people.setVisibility(View.VISIBLE);
            }
            if (params != null) {
                params.height = Utils.getScaledSize(getContext(), 206);
            }
        }
        if (whiteBg != null && params != null) {
            whiteBg.setLayoutParams(params);
        }
    }

    public void trackIfNotSubclassed(String event){
    	if(this.getClass().equals(LeaderboardFullOverlay.class)){
    		HeyzapAnalytics.trackEvent(getContext(), event);
    	}
    }

    public void launchMarket(){
        // Launch the android market and close this dialog
        String uri = String.format("market://details?id=%s&referrer=%s", HeyzapLib.HEYZAP_PACKAGE,
        HeyzapAnalytics.getAnalyticsReferrer(getContext(), "action=leaderboard-first"));

        HeyzapAnalytics.trackEvent(getContext(), String.format("score-full-overlay-clicked-first"));
        Intent popup = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
        popup.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
        getContext().startActivity(popup);
    }

    @Override
    public void show() {
        shownAt = System.currentTimeMillis();
        super.show();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_OUTSIDE && System.currentTimeMillis() > shownAt + 1000) {
            this.hide();
            return false;
        } else {
            return super.onTouchEvent(event);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            this.hide();
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

}


text:
package org.drools.guvnor.client.modeldriven.ui;

import java.math.BigDecimal;
import java.util.Date;

import org.drools.guvnor.client.widgets.decoratedgrid.AbstractCellValueFactory;
import org.drools.guvnor.client.widgets.decoratedgrid.CellValue;
import org.drools.ide.common.client.modeldriven.SuggestionCompletionEngine;
import org.drools.ide.common.client.modeldriven.dt.DTDataTypes;

/**
 * A Factory to create CellValues applicable to given columns.
 */
public class TemplateDataCellValueFactory extends AbstractCellValueFactory<TemplateDataColumn> {

    /**
     * Construct a Cell Value Factory for a specific Template data editor
     *
     * @param sce
     *            SuggestionCompletionEngine to assist with drop-downs
     */
    public TemplateDataCellValueFactory(SuggestionCompletionEngine sce) {
        super( sce );
    }

    /**
     * Serialise value to a String
     *
     * @param column
     *            The model column
     * @param cv
     *            CellValue for which value will be serialised
     * @return String representation of value
     */
    public String convertValueToString(TemplateDataColumn column,
                                       CellValue< ? > cv) {
        DTDataTypes dataType = getDataType( column );

        switch ( dataType ) {
            case BOOLEAN :
                return convertBooleanValueToString( cv );
            case DATE :
                return convertDateValueToString( cv );
            case NUMERIC :
                return convertNumericValueToString( cv );
            default :
                return convertStringValueToString( cv );
        }

    }

    /**
     * Make a CellValue applicable for the column. This is used by legacy UI
     * Models (Template Data Editor and legacy Guided Decision Tables) that
     * store values in a two-dimensional array of Strings.
     *
     * @param column
     *            The model column
     * @param iRow
     *            Row coordinate for initialisation
     * @param iCol
     *            Column coordinate for initialisation
     * @param initialValue
     *            The initial value of the cell
     * @return A CellValue
     */
    public CellValue< ? extends Comparable< ? >> makeCellValue(TemplateDataColumn column,
                                                               int iRow,
                                                               int iCol,
                                                               String initialValue) {
        DTDataTypes dataType = getDataType( column );
        CellValue< ? extends Comparable< ? >> cell = null;

        switch ( dataType ) {
            case BOOLEAN :
                Boolean b = Boolean.FALSE;
                try {
                    b = Boolean.valueOf( initialValue );
                } catch ( Exception e ) {
                }
                cell = makeNewBooleanCellValue( iRow,
                                                iCol,
                                                b );
                break;
            case DATE :
                Date d = null;
                try {
                    if ( DATE_CONVERTOR == null ) {
                        throw new IllegalArgumentException( "DATE_CONVERTOR has not been initialised." );
                    }
                    d = DATE_CONVERTOR.parse( initialValue );
                } catch ( Exception e ) {
                }
                cell = makeNewDateCellValue( iRow,
                                             iCol,
                                             d );
                break;
            case NUMERIC :
                BigDecimal bd = null;
                try {
                    bd = new BigDecimal( initialValue );
                } catch ( Exception e ) {
                }
                cell = makeNewNumericCellValue( iRow,
                                                iCol,
                                                bd );
                break;
            default :
                cell = makeNewStringCellValue( iRow,
                                               iCol,
                                               initialValue );
        }

        return cell;
    }

    //Convert a Boolean value to a String
    private String convertBooleanValueToString(CellValue< ? > value) {
        return (value.getValue() == null ? null : ((Boolean) value.getValue()).toString());
    }

    //Convert a Date value to a String
    private String convertDateValueToString(CellValue< ? > value) {
        String result = null;
        if ( value.getValue() != null ) {
            if ( DATE_CONVERTOR == null ) {
                throw new IllegalArgumentException( "DATE_CONVERTOR has not been initialised." );
            }
            result = DATE_CONVERTOR.format( (Date) value.getValue() );
        }
        return result;
    }

    //Convert a BigDecimal value to a String
    private String convertNumericValueToString(CellValue< ? > value) {
        return (value.getValue() == null ? null : ((BigDecimal) value.getValue()).toPlainString());
    }

    //Convert a String value to a String
    private String convertStringValueToString(CellValue< ? > value) {
        return (value.getValue() == null ? null : (String) value.getValue());
    }

    // Get the Data Type corresponding to a given column
    protected DTDataTypes getDataType(TemplateDataColumn column) {

        // Columns with lists of values, enums etc are always Text (for now)
        String[] vals = null;
        String factType = column.getFactType();
        String factField = column.getFactField();
        if ( factType != null && factField != null ) {
            vals = sce.getEnumValues( factType,
                                      factField );
            if ( vals != null && vals.length > 0 ) {
                return DTDataTypes.STRING;
            }
        }

        //Otherwise use data type extracted from model
        String dataType = column.getDataType();
        if ( dataType.equals( SuggestionCompletionEngine.TYPE_BOOLEAN ) ) {
            return DTDataTypes.BOOLEAN;
        } else if ( dataType.equals( SuggestionCompletionEngine.TYPE_DATE ) ) {
            return DTDataTypes.DATE;
        } else if ( dataType.equals( SuggestionCompletionEngine.TYPE_NUMERIC ) ) {
            return DTDataTypes.NUMERIC;
        } else {
            return DTDataTypes.STRING;
        }
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="dpyl.eddy.nomorse.view.DrawerActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <FrameLayout
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="?attr/actionBarSize"/>

</android.support.design.widget.CoordinatorLayout>


text:
<!DOCTYPE html>
<link rel="help" href="https://crbug.com/1034461">
<link rel="match" href="webkit-box-rtl-flex-ref.html">

There should be a green box followed by a red box, both on the same line.

A

B


text:
package org.ehcache;

import org.ehcache.config.CacheConfiguration;
import org.ehcache.config.CacheManagerConfiguration;
import org.ehcache.config.Configuration;
import org.ehcache.config.ConfigurationBuilder;
import org.ehcache.config.persistence.CacheManagerPersistenceConfiguration;
import org.ehcache.config.persistence.PersistenceConfiguration;
import org.ehcache.spi.service.Service;
import org.ehcache.spi.service.ServiceCreationConfiguration;

import java.io.File;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import static java.util.Collections.emptySet;
import static java.util.Collections.unmodifiableSet;
import static org.ehcache.config.ConfigurationBuilder.newConfigurationBuilder;

/**
 * @author Alex Snaps
 */
public class CacheManagerBuilder<T extends CacheManager> {

  private final ConfigurationBuilder configBuilder;
  private final Set<Service> services;

  public T build(final boolean init) {
    final T cacheManager = newCacheManager(services, configBuilder.build());
    if(init) {
      cacheManager.init();
    }
    return cacheManager;
  }

  private CacheManagerBuilder() {
    this.configBuilder = newConfigurationBuilder();
    this.services = emptySet();
  }

  private CacheManagerBuilder(CacheManagerBuilder<T> builder, Set<Service> services) {
    this.configBuilder = builder.configBuilder;
    this.services = unmodifiableSet(services);
  }

  private CacheManagerBuilder(CacheManagerBuilder<T> builder, ConfigurationBuilder configBuilder) {
    this.configBuilder = configBuilder;
    this.services = builder.services;
  }

  public static CacheManager newCacheManager(final Configuration configuration) {
    return new EhcacheManager(configuration);
  }

  T newCacheManager(Collection<Service> services, final Configuration configuration) {
    final EhcacheManager ehcacheManager = new EhcacheManager(configuration, services);
    return cast(ehcacheManager);
  }

  @SuppressWarnings("unchecked")
  T cast(EhcacheManager ehcacheManager) {
    return (T) ehcacheManager;
  }

  public <K, V> CacheManagerBuilder<T> withCache(String alias, CacheConfiguration<K, V> configuration) {
    return new CacheManagerBuilder<T>(this, configBuilder.addCache(alias, configuration));
  }

  public <N extends T> CacheManagerBuilder<N> with(CacheManagerConfiguration<N> cfg) {
    return cfg.builder(this);
  }

  public CacheManagerBuilder<T> using(Service service) {
    Set<Service> newServices = new HashSet<Service>(services);
    newServices.add(service);
    return new CacheManagerBuilder<T>(this, newServices);
  }

  public CacheManagerBuilder<T> using(ServiceCreationConfiguration<?> service) {
    return new CacheManagerBuilder<T>(this, configBuilder.addService(service));
  }

  public CacheManagerBuilder<T> withClassLoader(ClassLoader classLoader) {
    return new CacheManagerBuilder<T>(this, configBuilder.withClassLoader(classLoader));
  }

  public static CacheManagerBuilder<CacheManager> newCacheManagerBuilder() {
    return new CacheManagerBuilder<CacheManager>();
  }

  public static PersistenceConfiguration persistence(String location) {
    return new CacheManagerPersistenceConfiguration(new File(location));
  }
}


text:
var express         = require('express');
var bodyParser      = require('body-parser');
var morgan          = require('morgan');
var methodOverride  = require('method-override');
var sessions        = require("client-sessions");
var soap            = require('soap');
var db_handler      = require('./db_handler');
var path            = require("path");
var fs              = require("fs");
var multipart       = require('connect-multiparty');

//uploading files with multer
var multer  = require('multer');
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './public/uploads');
  },
  filename: function (req, file, cb) {
    cb(null, req.carPoolSession.username+".png");
  }
});
var upload = multer({ storage: storage });

var POLLING_INTERVAL = 3000;
var pollingTimer;

var app             = express();
var http            = require('http').Server(app);
var io              = require('socket.io')(http);
var PORT            = 8080;
var usuariosOnline  = {};

var usuariosOnlineMensaje = [];

function printResult(res){
    console.log(res);
}
function notificacionPrivadaCallback(socket, usu, mensaje, tipo, de, timeStamp){
    db_handler.obtener_usuario(de, function(queryRes){
        var nom = queryRes[0].nombre;
        console.log("enviando notif a " + usu);
        socket.broadcast.to(usu).emit("notificarMensajePrivado",mensaje,nom.substring(0,nom.indexOf(' ')), tipo,de, timeStamp);
        console.log("*********************");
    });
}
io.on('connection', function(socket){

	socket.on("inicioSesion",function(username){
        console.log(usuariosOnlineMensaje);
        console.log("-----------------------------------------------------------");
        var gr = {nick: username, id: socket.id};
          if(usuariosOnlineMensaje.length===0){
            usuariosOnlineMensaje.push(gr);
          }
          else{
            var i = 0,bandera=0;
            for(i=0;i<usuariosOnlineMensaje.length;i++){
              var name = usuariosOnlineMensaje[i].nick;
              var id = usuariosOnlineMensaje[i].id;
              if(name==username && id!=socket.id){
                //usuariosOnline.push(gr);
                usuariosOnlineMensaje[i].id = socket.id;
                bandera=1;
                console.log("nuevo usuario");
              }
              else{
                console.log("el usuario ya esta");
              }
            }
            if(bandera!=1){
              usuariosOnlineMensaje.push(gr);
            }
          }
          console.log(usuariosOnlineMensaje);
      });

     socket.on("loginUser",function(username){

          console.log(username);
          socket.username = username;
          usuariosOnline[username] = socket.username;

          console.log(usuariosOnline);

          socket.emit("message","yo","Bienvenido " + socket.username + ", te has conectado correctamente");
          socket.broadcast.emit("message","conectado","El usuario "+socket.username + "se ha conectado al chat.");

          io.sockets.emit("updateSidebarUsers",usuariosOnline);
    });

    socket.on('addNewMessage', function(de,para,message){
        var i = 0;
        var nom;
        for(i=0;i<usuariosOnlineMensaje.length;i++){
                console.log(usuariosOnlineMensaje[i].nick);
                console.log(usuariosOnlineMensaje[i].id);
                console.log("+++++++++++");
                nom = usuariosOnlineMensaje[i].nick;
                if(nom==para){
                    var usu = usuariosOnlineMensaje[i].id;
                    console.log(usu);
                    socket.broadcast.to(usu).emit("message","msg",usuariosOnlineMensaje[i].nick+ " dice: "+ message);
                    console.log("+++++++++++");
                }
        }
        for(i=0;i<usuariosOnlineMensaje.length;i++){
                console.log(usuariosOnlineMensaje[i].nick);
                console.log(usuariosOnlineMensaje[i].id);
                console.log("999999999999999999999999999999");
                nom = usuariosOnlineMensaje[i].nick;
                if(nom==de){
                    var usuario = usuariosOnlineMensaje[i].id;
                    console.log(usuario);
                    console.log(usuariosOnlineMensaje[i].nick);
                    socket.to(usuario).emit("message","msg", "Yo: " +message + ".");
                    console.log("999999999999999999999999999999");
                }
        }
          //socket.emit('message',"msg", "Yo: " +message + ".");
          //socket.broadcast.emit("message","msg",socket.username+ "dice: "+ message);
    });

    socket.on("enviarMensaje", function (de,para,mensaje){
      console.log(para);
      console.log(mensaje);
      console.log("-----------------------------");
      var i = 0;

      for(i=0;i<usuariosOnlineMensaje.length;i++){
              console.log(usuariosOnlineMensaje[i].nick);
              console.log(usuariosOnlineMensaje[i].id);
              var nom = usuariosOnlineMensaje[i].nick;
              if(nom==para){

                  var usu = usuariosOnlineMensaje[i].id;
                  console.log(usu);
                  console.log("/////////////////////++++++++++++++++++++++++++++++");
                  socket.broadcast.to(usu).emit("notificar","msg",de+ " dice: "+ mensaje);
                  console.log("/////////////////////++++++++++++++++++++++++++++++");

            }

      }
      console.log("/////////////////////-----------------------");
      socket.emit("notificar","msg", "Yo: " +mensaje + ".");
      console.log("/////////////////////-----------------------");
      console.log("-----------------------------");
    });

    socket.on('notificacion',function (de,para,mensaje,tipo){
      console.log("nueva notificacion");
      console.log("de: " + de);
      console.log("para: " + para);
      console.log(mensaje);
      console.log("-----------------------------");
      timeStamp = Date.now();
      //timeStamp = 0;
          var i = 0;
		  var flag = 0;
		  var fecha = new Date();
		  var hora = new Date();
		  var dd = fecha.getDate();
		  var mm = fecha.getMonth()+1; //hoy es 0!
		  var yyyy = fecha.getFullYear();

		  hora = hora.getHours() + ":" + hora.getMinutes() + ":" + hora.getSeconds();
		  fecha = yyyy+"-"+ mm+'-'+dd;
		  var ubicacion = "";
		  var leido = 0;
          for(i=0;i<usuariosOnlineMensaje.length;i++){
                  console.log("++++++++++++++++++++++++++++++");
                  console.log(usuariosOnlineMensaje[i].nick);
                  console.log(usuariosOnlineMensaje[i].id);
                  var nom = usuariosOnlineMensaje[i].nick;
                  if(nom==para){
                      console.log("*********************");
                      var usu = usuariosOnlineMensaje[i].id;

                      console.log(usu);
                      //guardar en la base el mensaje
                      //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                      var mensajeTotal = new db_handler.mensajeria(de,para,mensaje,fecha,timeStamp,ubicacion,tipo,leido);
                      console.log(mensajeTotal);
                      db_handler.enviar_mensaje(mensajeTotal,printResult);
                      notificacionPrivadaCallback(socket, usu, mensaje, tipo, de, timeStamp);
                      //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                      flag = 1;

                  }
                console.log("++++++++++++++++++++++++++++++");
          }
		  if(flag === 0){
            var mensajeT= new db_handler.mensajeria(de,para,mensaje,fecha,timeStamp,ubicacion,tipo,leido);
            console.log(mensajeT);
            db_handler.enviar_mensaje(mensajeT,function(queryRes){
              console.log(queryRes);
            });
          }
    });

});
/*
var pollingLoop = function () {
  var mensajeria = new db_handler.mensajeria(req.carPoolSession.username,'hjupiter','llevame','12-12-2015','null','1','0');
    db_handler.enviar_mensaje(mensajeria,function(queryRes){
      res.redirect('/inicio');
    });
};
*/

app.use(express.static(__dirname + '/public'));       // set the static files location /public/img will be /img for users
app.use(express.static(__dirname + '/public/images'));
app.use(morgan('dev'));                           // log every request to the console
app.use(bodyParser.urlencoded({ extended: false }));    // parse application/x-www-form-urlencoded
app.use(bodyParser.json());                 // parse application/json
app.use(methodOverride());
app.use(bodyParser());
app.use(multipart());
//app.use(bodyParser.({uploadDIr:'./uploads'}));

app.use(sessions({
  cookieName: 'carPoolSession', // cookie name dictates the key name added to the request object
  secret: 'tDSg8Iw8hcODgqK6olqL2vUiCqxoKPt1LgBWv8G6wSvTA0d7IV3ZWfbf5oENpcO', // should be a large unguessable string
  duration: 30 * 60 * 1000, // how long the session will stay valid in ms
  activeDuration: 1000 * 60 * 15 // if expiresIn < activeDuration, the session will be extended by activeDuration milliseconds
}));

app.get('/chatPrivado/:idChat',function(req,res){
  console.log("-----------------------------------------------------------");
  console.log(req.carPoolSession.username);
  console.log("-----------------------------------------------------------");

  db_handler.obtener_mensajes(function(queryMensaje){
    console.log(queryMensaje);
    res.render('chatPrivado.jade',{usuario: req.carPoolSession.username, usuario2:req.params.idChat, mensajes: queryMensaje});
  });
});

app.get('/chat', function (req, res) {
  /*if(req.carPoolSession.username != null)
        res.redirect('/inicio');
  else*/
        res.render('chat.jade',{user: req.carPoolSession.username});
});

/**
* Pagina de login
**/
app.get('/', function (req, res) {
  if(req.carPoolSession.username){
    res.redirect('/inicio');
  }
  else{
    res.render('login.jade');
  }
});

/**
* Pagina de perfil
**/
app.get('/inicio', function (req, res) {
  if(!req.carPoolSession.username){
    res.redirect('/');
  }
  else{
    var user = new db_handler.user('', '', req.carPoolSession.username, '', '','');
    db_handler.obtener_usuario(req.carPoolSession.username,function(queryRes){
      db_handler.obtener_lista_seguidores(user,function(querySeguidores){
        db_handler.obtener_usuarios(function(queryUsuarios){
            res.render('perfil.jade',{listaPerfil : queryRes,
                                      usuario : req.carPoolSession.username,
                                      listaSeguidor : querySeguidores,
                                      listaUsuarios : queryUsuarios});
          });
        });
      });
  }
});

app.get('/inicio/:id',function (req,res){
  if(!req.carPoolSession.username){
    res.redirect('/');
  }
  else{
    var user = new db_handler.user('', '', req.params.id, '', '','');
    db_handler.obtener_usuario(req.params.id,function (queryRes){
      db_handler.obtener_lista_seguidores(req.params.id,function (querySeguidores){
        db_handler.obtener_usuarios(function (queryUsuarios){
            res.render('perfil.jade',{listaPerfil : queryRes,
                                      usuario : req.carPoolSession.username,
                                      listaSeguidor : querySeguidores,
                                      listaUsuarios : queryUsuarios});
          });
        });
      });
  }
});

app.get('/editar',function (req,res){
  if(!req.carPoolSession.username){
    res.redirect('/');
  }
  else{
      db_handler.obtener_usuario(req.carPoolSession.username,function(queryRes){
           res.render('editar_perfil.jade',{listaPerfil : queryRes,usuario : req.carPoolSession.username});
      });
  }
});

app.get('/subirImagen',function (req,res){
  console.dir(req.files);
  res.render('subirImagen.jade');
});

app.post('/subir', function (req, res) {
    console.log("-->>>>>>>>>>>>>>>>>>>>>>>>>>>");
    //console.log(req.body.miArchivo.path);
    //res.send({message:'Archivo guardado', file:req.file});
    var path = req.files.miArchivo.path;
    var type = req.files.miArchivo.type;
    var name = req.carPoolSession.username+".jpeg";

    if(type=="image/jpeg" || type=="image/png"){
        var newPath = "./public/uploads/" + name;
        var is = fs.createReadStream(path);
        var os = fs.createWriteStream(newPath);
        is.pipe(os);
        is.on('end', function() {
          //eliminamos el archivo temporal
          fs.unlinkSync(path);
        });

        db_handler.update_usuario_imagen(1,req.carPoolSession.username,function(queryRes){
          res.redirect('/inicio');
          console.log(queryRes);
          console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        });

    }
    //console.log(tmp_path);
    ///res.redirect('/inicio');
});
/*
app.post('/subir', upload.single('file'), function (req, res, next) {
    //res.send({message:'Archivo guardado', file:req.file});
    res.redirect('/inicio');
});
*/
app.get('/registro', function (req, res) {
  res.render('registro.jade');
});

app.post('/actualiza',function (req,res){
  if(!req.carPoolSession.username){
        res.redirect('/');
  }else{
      var user = new db_handler.user( req.body.nombre,
                                      req.body.apellido,
                                      req.carPoolSession.username,
                                      req.body.placa,
                                      req.body.capacidadCarro,
                                      req.body.bio);
      db_handler.update_usuario(user,function(queryRes){
          db_handler.obtener_usuario(req.carPoolSession.username,function(queryRes){
              res.redirect('/inicio');
          });
      });
    }
});

app.post('/enviar_notificacion_llevame/:id',function (req,res){
  var llevameON = new db_handler.mensajeria(req.carPoolSession.username,
                                            req.body.usuarioSeguidor,
                                            'llevame',
                                            '',
                                            '',
                                            1,
                                            0);
  db_handler.enviar_mensaje(llevameON,function (req,res){
    res.redirect('/inicio');
  });
});

app.get('/llevame',function (req, res){
  if(!req.carPoolSession.username){
        res.redirect('/');
  }else{
    var mensajeria = new db_handler.mensajeria(req.carPoolSession.username,'hjupiter','llevame','12-12-2015','null','1','0');
    db_handler.enviar_mensaje(mensajeria,function(queryRes){
      res.redirect('/inicio');
    });
  }
});

/**
* logout
* Esto deberia de ser un post, pero por ahora por conveniencia es un get.
**/
app.post('/logout', function (req, res) {
  if(req.carPoolSession.username){
        req.carPoolSession.reset();
  }
  res.redirect('/');
});

var url = 'http://ws.espol.edu.ec/saac/wsandroid.asmx?WSDL';
app.post('/crear', function (req, res){
     /*var args = {authUser: req.body.inUsuario, authContrasenia: req.body.inContraseña};
     var argsCrear = {usuario: req.body.inUsuario};
     soap.createClient(url, function(err, client) {
          client.autenticacion(args, function(err, result) {
               re = result.autenticacionResult;
               if(re){
                    db_handler.verificar_usuario(mariaClient,req.body.inUsuario,function(queryRes){
                      if(queryRes[0].FALSE){*/
                        var usrname = req.body.inUsuario.toLowerCase();
                        var argsCrear = {usuario: usrname};
                        soap.createClient(url, function(err , client){
                          client.wsInfoUsuario(argsCrear, function(err, result){
                            var Nombres = "";
                            var Apellidos = "";
                            var user;
                            if(result.wsInfoUsuarioResult === undefined){
                              user = new db_handler.user(Nombres, Apellidos, usrname, req.body.inPlaca, req.body.inCapacidad,req.body.inBiografia);
                              db_handler.crear_usuario(user,function(queryRes){
                                   res.redirect('/');
                              });
                            }
                            else{
                              Nombres = result.wsInfoUsuarioResult.diffgram.NewDataSet.INFORMACIONUSUARIO.NOMBRES;
                              Apellidos = result.wsInfoUsuarioResult.diffgram.NewDataSet.INFORMACIONUSUARIO.APELLIDOS;
                              //var bio = "--";
                             var imagenRuta = 0;
                              user = new db_handler.user(Nombres, Apellidos, usrname, req.body.inPlaca, req.body.inCapacidad,req.body.inBiografia,imagenRuta);
                              db_handler.crear_usuario(user,function(queryRes){
                                   res.redirect('/');
                              });
                            }
                          });
                        });/*
                      }
                      else{
                        res.redirect('/registro?error=' + 2);
                      }
                    })
               }
               else{
                    res.redirect('/registro?error=' + 1);
               }

          });
     });*/
});
/*
app.post('/inicio', function (req, res){
  var args = {authUser: req.body.Email, authContrasenia: req.body.Password};
  soap.createClient(url, function(err, client) {
      client.autenticacion(args, function(err, result) {
        re = result.autenticacionResult;
        if(re){
                    //req.carPoolSession.username = req.body.Email; //Coloco el username en el session
                         var user = new db_handler.user("Hector", "Jupiter", "hjupiter", "GKT-723", "123");
                         db_handler.crear_usuario(mariaClient, user, function(queryRes){
                              console.log("asdsadsa");
                         })
          //res.render('perfil.jade',req.body.Email);
                               // });
        }
        else{
          res.redirect('/?error=' + 1);
        }

      });
  });
})
*/

app.post('/inicio', function (req, res){
    var usrname = req.body.Email.toLowerCase();
     var args = {authUser: usrname, authContrasenia: req.body.Password};
     soap.createClient(url, function(err, client) {
            client.autenticacion(args, function(err, result) {
                re = result.autenticacionResult;
                if(re){
                      db_handler.verificar_usuario(usrname,function(queryRes){
                          if(queryRes[0].FALSE){
                              res.render('registro.jade',{usu: usrname,con:req.body.Password});
                          }
                          else{
                              req.carPoolSession.username = usrname;
                              res.redirect('/inicio/?');
                          }
                      });
                }
                else{
                    res.redirect('/?error=' + 1);
                }

            });
     });
});

app.get('/pass', function (req, res){
    if(!req.carPoolSession.username)
        res.redirect('/');
    else
        res.render('pasajero.jade', {usuario: req.carPoolSession.username});
});

app.get('/driver', function (req, res){
    if(!req.carPoolSession.username)
        res.redirect('/');
    else
        res.render('driver.jade', {usuario: req.carPoolSession.username});
});

app.post('/nuevaRuta', function (req, res){
    if(!req.carPoolSession.username)
        res.redirect('/');
    else{
        db_handler.insertar_ruta(req.carPoolSession.username, req.body.nombre, req.body.dias, req.body.hora, JSON.parse(req.body.array),function(queryRes){
        });
        res.end('{"success" : "Updated Successfully", "status" : 200}');
    }
});

app.get('/misRutas', function (req, res){
     if(!req.carPoolSession.username)
        res.redirect('/');
     else{
        db_handler.getMisRutas(req.carPoolSession.username, function misRutasCallback(queryRes){
            res.end('{"status" : 200, "array" : ' + JSON.stringify(queryRes) +  '}');
        });
     }
});
app.get('/rutasCerca', function (req, res){
        db_handler.getRutasCerca(req.query.day, req.query.time, req.query.startX, req.query.startY, req.query.endX, req.query.endY, function misRutasCallback(queryRes){
            res.end('{"status" : 200, "array" : ' + JSON.stringify(queryRes) +  '}');
        });
});

app.get('/seguir', function (req, res) {
  if(!req.carPoolSession.username){
    res.redirect('/');
  }
  else{
    //var user = new db_handler.user('req.carPoolSession.Nombre','req.carPoolSession.apellido','','','','req.carPoolSession.bio');
    db_handler.obtener_seguidor(req.carPoolSession.username,function(queryResult){
      res.render('seguir.jade', {listaSeguidor : queryResult,usuario: req.carPoolSession.username});

    });
  }
});

app.get('/guardar/:id', function (req, res){
     if(!req.carPoolSession.username)
        res.redirect('/');
    else{

        db_handler.agregar_seguidor(req.params.id,req.carPoolSession.username,function(queryRes){
        });
        res.redirect('/seguir');
        console.log(req.params.id);
        console.log(req.carPoolSession.username);
    }
});

app.get('/siguiendo', function (req, res) {
  if(!req.carPoolSession.username){
    res.redirect('/');
  }
  else{
    //var user = new db_handler.user('req.carPoolSession.Nombre','req.carPoolSession.apellido','','','','req.carPoolSession.bio');
    db_handler.obtener_siguiendo(req.carPoolSession.username,function(queryResult){
      res.render('siguiendo.jade', {listaSiguiendo : queryResult});

    });
  }
});

http.listen(PORT, function() {
  console.log('el Servidor esta escuchando en el puerto %s',PORT);
});


text: scons build/X86/gem5.opt PROTOCOL=MESI_Two_Level RUBY=True


text:
#include "config.h"
#include "core/imagebitmap/ImageBitmapFactories.h"

#include "bindings/core/v8/ExceptionState.h"
#include "bindings/core/v8/ScriptPromiseResolver.h"
#include "core/dom/ExecutionContext.h"
#include "core/fileapi/Blob.h"
#include "core/frame/ImageBitmap.h"
#include "core/frame/LocalDOMWindow.h"
#include "core/html/ImageData.h"
#include "core/workers/WorkerGlobalScope.h"
#include "platform/SharedBuffer.h"
#include "platform/graphics/ImageSource.h"
#include "platform/graphics/StaticBitmapImage.h"
#include "public/platform/WebSize.h"
#include "third_party/skia/include/core/SkImage.h"
#include <v8.h>

namespace blink {

static ScriptPromise fulfillImageBitmap(ScriptState* scriptState, PassRefPtrWillBeRawPtr<ImageBitmap> imageBitmap)
{
    ScriptPromiseResolver* resolver = ScriptPromiseResolver::create(scriptState);
    ScriptPromise promise = resolver->promise();
    if (imageBitmap) {
        resolver->resolve(imageBitmap);
    } else {
        resolver->reject(ScriptValue(scriptState, v8::Null(scriptState->isolate())));
    }
    return promise;
}

ScriptPromise ImageBitmapFactories::createImageBitmap(ScriptState* scriptState, EventTarget& eventTarget, Blob* blob, ExceptionState& exceptionState)
{
    ImageBitmapLoader* loader = ImageBitmapFactories::ImageBitmapLoader::create(from(eventTarget), IntRect(), scriptState);
    ScriptPromise promise = loader->promise();
    from(eventTarget).addLoader(loader);
    loader->loadBlobAsync(eventTarget.executionContext(), blob);
    return promise;
}

ScriptPromise ImageBitmapFactories::createImageBitmap(ScriptState* scriptState, EventTarget& eventTarget, Blob* blob, int sx, int sy, int sw, int sh, ExceptionState& exceptionState)
{
    if (!sw || !sh) {
        exceptionState.throwDOMException(IndexSizeError, String::format("The source %s provided is 0.", sw ? "height" : "width"));
        return ScriptPromise();
    }
    ImageBitmapLoader* loader = ImageBitmapFactories::ImageBitmapLoader::create(from(eventTarget), IntRect(sx, sy, sw, sh), scriptState);
    ScriptPromise promise = loader->promise();
    from(eventTarget).addLoader(loader);
    loader->loadBlobAsync(eventTarget.executionContext(), blob);
    return promise;
}

ScriptPromise ImageBitmapFactories::createImageBitmap(ScriptState* scriptState, EventTarget& eventTarget, ImageData* data, ExceptionState& exceptionState)
{
    return createImageBitmap(scriptState, eventTarget, data, 0, 0, data->width(), data->height(), exceptionState);
}

ScriptPromise ImageBitmapFactories::createImageBitmap(ScriptState* scriptState, EventTarget& eventTarget, ImageData* data, int sx, int sy, int sw, int sh, ExceptionState& exceptionState)
{
    if (!sw || !sh) {
        exceptionState.throwDOMException(IndexSizeError, String::format("The source %s provided is 0.", sw ? "height" : "width"));
        return ScriptPromise();
    }
    if (data->data()->bufferBase()->isNeutered()) {
        exceptionState.throwDOMException(InvalidStateError, "The source data has been neutered.");
        return ScriptPromise();
    }
    // FIXME: make ImageBitmap creation asynchronous crbug.com/258082
    return fulfillImageBitmap(scriptState, ImageBitmap::create(data, IntRect(sx, sy, sw, sh)));
}

ScriptPromise ImageBitmapFactories::createImageBitmap(ScriptState* scriptState, EventTarget& eventTarget, ImageBitmap* bitmap, ExceptionState& exceptionState)
{
    return createImageBitmap(scriptState, eventTarget, bitmap, 0, 0, bitmap->width(), bitmap->height(), exceptionState);
}

ScriptPromise ImageBitmapFactories::createImageBitmap(ScriptState* scriptState, EventTarget& eventTarget, ImageBitmap* bitmap, int sx, int sy, int sw, int sh, ExceptionState& exceptionState)
{
    if (!sw || !sh) {
        exceptionState.throwDOMException(IndexSizeError, String::format("The source %s provided is 0.", sw ? "height" : "width"));
        return ScriptPromise();
    }
    // FIXME: make ImageBitmap creation asynchronous crbug.com/258082
    return fulfillImageBitmap(scriptState, ImageBitmap::create(bitmap, IntRect(sx, sy, sw, sh)));
}

const char* ImageBitmapFactories::supplementName()
{
    return "ImageBitmapFactories";
}

ImageBitmapFactories& ImageBitmapFactories::from(EventTarget& eventTarget)
{
    if (LocalDOMWindow* window = eventTarget.toDOMWindow())
        return fromInternal(*window);

    ASSERT(eventTarget.executionContext()->isWorkerGlobalScope());
    return ImageBitmapFactories::fromInternal(*toWorkerGlobalScope(eventTarget.executionContext()));
}

template<class GlobalObject>
ImageBitmapFactories& ImageBitmapFactories::fromInternal(GlobalObject& object)
{
    ImageBitmapFactories* supplement = static_cast<ImageBitmapFactories*>(WillBeHeapSupplement<GlobalObject>::from(object, supplementName()));
    if (!supplement) {
        supplement = new ImageBitmapFactories();
        WillBeHeapSupplement<GlobalObject>::provideTo(object, supplementName(), adoptPtrWillBeNoop(supplement));
    }
    return *supplement;
}

void ImageBitmapFactories::addLoader(ImageBitmapLoader* loader)
{
    m_pendingLoaders.add(loader);
}

void ImageBitmapFactories::didFinishLoading(ImageBitmapLoader* loader)
{
    ASSERT(m_pendingLoaders.contains(loader));
    m_pendingLoaders.remove(loader);
}

ImageBitmapFactories::ImageBitmapLoader::ImageBitmapLoader(ImageBitmapFactories& factory, const IntRect& cropRect, ScriptState* scriptState)
    : m_loader(FileReaderLoader::ReadAsArrayBuffer, this)
    , m_factory(&factory)
    , m_resolver(ScriptPromiseResolver::create(scriptState))
    , m_cropRect(cropRect)
{
}

void ImageBitmapFactories::ImageBitmapLoader::loadBlobAsync(ExecutionContext* context, Blob* blob)
{
    m_loader.start(context, blob->blobDataHandle());
}

DEFINE_TRACE(ImageBitmapFactories)
{
    visitor->trace(m_pendingLoaders);
    WillBeHeapSupplement<LocalDOMWindow>::trace(visitor);
    WillBeHeapSupplement<WorkerGlobalScope>::trace(visitor);
}

void ImageBitmapFactories::ImageBitmapLoader::rejectPromise()
{
    m_resolver->reject(ScriptValue(m_resolver->scriptState(), v8::Null(m_resolver->scriptState()->isolate())));
    m_factory->didFinishLoading(this);
}

void ImageBitmapFactories::ImageBitmapLoader::didFinishLoading()
{
    if (!m_loader.arrayBufferResult()) {
        rejectPromise();
        return;
    }
    RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create((char*)m_loader.arrayBufferResult()->data(), m_loader.arrayBufferResult()->byteLength());

    OwnPtr<ImageSource> source = adoptPtr(new ImageSource());
    source->setData(*sharedBuffer, true);

    RefPtr<SkImage> frame = source->createFrameAtIndex(0);
    ASSERT(!frame || (frame->width() && frame->height()));
    if (!frame) {
        rejectPromise();
        return;
    }

    RefPtr<Image> image = StaticBitmapImage::create(frame);
    if (!m_cropRect.width() && !m_cropRect.height()) {
        // No cropping variant was called.
        m_cropRect = IntRect(IntPoint(), image->size());
    }

    RefPtrWillBeRawPtr<ImageBitmap> imageBitmap = ImageBitmap::create(image.get(), m_cropRect);
    m_resolver->resolve(imageBitmap.release());
    m_factory->didFinishLoading(this);
}

void ImageBitmapFactories::ImageBitmapLoader::didFail(FileError::ErrorCode)
{
    rejectPromise();
}

DEFINE_TRACE(ImageBitmapFactories::ImageBitmapLoader)
{
    visitor->trace(m_factory);
    visitor->trace(m_resolver);
}

} // namespace blink


text:
This buildpack is meant to be used with the [Heroku Buildpack for Elixir](https://github.com/HashNuke/heroku-buildpack-elixir). When deploying Phoenix apps to Heroku, static assets will need to be compiled. This buildpack sees to it that static assets are compiled and that a corresponding asset manifest is generated.

## Features
* Easily customizable to your build needs with its `compile` hook!
* Works much like the [Heroku Buildpack for Elixir](https://github.com/HashNuke/heroku-buildpack-elixir)!
* **Easy configuration** with `phoenix_static_buildpack.config` file
* Automatically sets `DATABASE_URL` and includes `heroku-postgresql:hobby-dev` addon
* If your app doesn't have a Procfile, default web task `mix phoenix.server` will be run
* Can configure versions for Node and NPM
* Auto-installs Bower deps if `bower.json` is in your app's root path
* Caches Node, NPM modules and Bower components

## Usage

```bash
# Set the buildpack for your Heroku app
heroku buildpacks:set https://github.com/gjaldon/phoenix-static-buildpack

# Add this buildpack after the Elixir buildpack
heroku buildpacks:add --index 1 https://github.com/HashNuke/heroku-buildpack-elixir
```

## Configuration

Create a `phoenix_static_buildpack.config` file in your app's root dir if you want to override the defaults. The file's syntax is bash.

If you don't specify a config option, then the default option from the buildpack's [`phoenix_static_buildpack.config`](https://github.com/gjaldon/phoenix-static-buildpack/blob/master/phoenix_static_buildpack.config) file will be used.

__Here's a full config file with all available options:__

```bash
# We can set the version of Node to use for the app here
node_version=0.12.4

# We can set the version of NPM to use for the app here
npm_version=2.10.1

# Add the config vars you want to be exported here
config_vars_to_export=(DATABASE_URL)

# We can change the filename for the compile script with this option
compile="compile"
```

## Compile

By default, Phoenix uses `brunch` and recommends you to use `mix phoenix.digest` in production. For that, we have a default `compile` shell script which gets run after building dependencies and
just before finalizing the build. The `compile` file looks like this:

```bash
info "Building Phoenix static assets"
brunch build --production
mix phoenix.digest
```

To customize your app's compile hook, just add a `compile` file to your app's root directory.
`compile` is just a shell script, so you can use any valid `bash` code. Keep in mind you'll have
access to your `node_modules` and `mix`. This means that if you're using a Node build tool other than `brunch`, you can just do something like:

```bash
# app_root/compile
gulp build:dist
mix phoenix.digest
```

The above `compile` overrides the default one. :)


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

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="initial-scale=1.0">
<title>Términos del Servicio Adicionales de Google Chrome y Chrome OS</title>

 Términos del Servicio Adicionales de Google Chrome y Chrome OS

 Última modificación: 1 de enero del 2021

 Al utilizar Google Chrome o Chrome OS, aceptas los Términos del Servicio de Google disponibles en https://policies.google.com/terms y estos Términos del Servicio Adicionales de Google Chrome y Chrome OS.

 Estos Términos del Servicio Adicionales de Google Chrome y de Chrome OS se aplican a la versión de código ejecutable de Google Chrome y de Chrome OS. La mayor parte del código fuente de Google Chrome está disponible de forma gratuita y se rige por los acuerdos de licencia de software libre disponibles en la página https://code.google.com/chromium/terms.html.

 El uso que hagas de determinados componentes de Google Chrome y Chrome OS está sujeto a los siguientes términos:

   AVC

  ESTE PRODUCTO ESTÁ SUJETO A LA LICENCIA DE CARTERA DE PATENTES AVC PARA USO PERSONAL O PARA OTROS USOS NO REMUNERADOS POR PARTE DE UN CONSUMIDOR PARA i) CODIFICAR VÍDEOS DE CONFORMIDAD CON EL ESTÁNDAR AVC (EN ADELANTE, "VÍDEOS AVC") O PARA ii) DECODIFICAR VÍDEOS AVC CODIFICADOS POR UN CONSUMIDOR COMO PARTE DE UNA ACTIVIDAD DE CARÁCTER PERSONAL U OBTENIDOS DE UN PROVEEDOR DE VÍDEOS CON LICENCIA PARA OFRECER VÍDEOS AVC. NO SE CONCEDE NINGÚN TIPO DE LICENCIA, NI EXPLÍCITA NI IMPLÍCITA, PARA NINGÚN OTRO USO. PARA OBTENER INFORMACIÓN ADICIONAL, CONSULTA LA PÁGINA DE MPEG LA, LLC (HTTP://WWW.MPEGLA.COM).

 Además, el uso que haces de determinados componentes de Chrome OS está sujeto a los siguientes términos:

   MPEG-4

  ESTE PRODUCTO ESTÁ SUJETO A LA LICENCIA DE CARTERA DE PATENTES VISUALES MPEG-4 PARA USO PERSONAL Y NO COMERCIAL POR PARTE DE UN CONSUMIDOR PARA i) CODIFICAR VÍDEOS DE CONFORMIDAD CON EL ESTÁNDAR VISUAL MPEG-4 (EN ADELANTE, "VÍDEOS MPEG-4") O PARA ii) DECODIFICAR VÍDEOS MPEG-4 CODIFICADOS POR UN CONSUMIDOR COMO PARTE DE UNA ACTIVIDAD DE CARÁCTER PERSONAL Y NO COMERCIAL U OBTENIDOS A TRAVÉS DE UN PROVEEDOR DE VÍDEOS CON LICENCIA DE MPEG LA PARA OFRECER VÍDEOS MPEG-4. NO SE CONCEDE NINGÚN TIPO DE LICENCIA, NI EXPLÍCITA NI IMPLÍCITA, PARA NINGÚN OTRO USO. PARA OBTENER INFORMACIÓN ADICIONAL, INCLUIDA LA RELACIONADA CON LICENCIAS Y CON USOS PROMOCIONALES, INTERNOS Y COMERCIALES, CONSULTA LA PÁGINA DE MPEG LA, LLC (HTTP://WWW.MPEGLA.COM).


text:
import React from 'react';

import styles from './SideBar.scss';

export interface IShellSideBarProps {
    title: string;
    rightButtonTitle?: string;
};

interface IShellSideBarCallbacks {
    rightButtonOnClick?: () => void;
};

class SideBar extends React.Component<IShellSideBarProps & IShellSideBarCallbacks, {}> {
    public render() {
        const {
            title,
            children,
            rightButtonOnClick,
            rightButtonTitle
        } = this.props;

        return (

 {title}

                            {rightButtonTitle}

                {children}

        );
    }
}

export default SideBar;

// WEBPACK FOOTER //
// ./src/client/common/components/SideBar.tsx


text:
from setuptools import setup, find_packages

setup(
    name='home',
    version="0.1",
    author='encorehu',
    author_email='huyoo353@126.com',
    description='a django project specific app.',
    url='https://github.com/encorehu/django-home',
    packages=find_packages(),
    package_dir={'home':'home'},
    package_data={'home':['*.*','templates/*.*', 'templates/home/*.*']},
    zip_safe = False,
    include_package_data=True,
    classifiers=[
        "Framework :: Django",
        "Intended Audience :: Developers",
        "Intended Audience :: System Administrators",
        "Operating System :: OS Independent",
        "Topic :: Software Development"
    ],
)


text:
module React
  module Rails
    class Engine < ::Rails::Engine
      initializer "react_rails.setup_engine", :group => :all do |app|
        app.assets.register_engine '.jsx', React::JSX::Template
      end
    end
  end
end