text:
require 'helper'
require 'eupathdb_species_data'

class EuPathDBSpeciesDataTest < Test::Unit::TestCase
  def base_dir
    '/home/ben/phd/data'
  end

  def test_method_missing
    spd = EuPathDBSpeciesData.new('Plasmodium yoelii')
    assert_equal 'yoelii', spd.directory
  end

  def test_nickname
    spd = EuPathDBSpeciesData.new('Plasmodium yoelii').fasta_file_species_name
    assert_equal spd, EuPathDBSpeciesData.new('yoelii').fasta_file_species_name
    assert_equal spd, EuPathDBSpeciesData.new('P. yoelii').fasta_file_species_name #check for not exactly the last name but close enough
  end

  def test_protein_data_path
    spd = EuPathDBSpeciesData.new('Plasmodium yoelii', base_dir)
    assert_equal "/home/ben/phd/data/Plasmodium yoelii/genome/PlasmoDB/#{EuPathDBSpeciesData::SOURCE_VERSIONS['PlasmoDB']}/PyoeliiAnnotatedProteins_PlasmoDB-#{EuPathDBSpeciesData::SOURCE_VERSIONS['PlasmoDB']}.fasta",
    spd.protein_fasta_path
  end

  def test_one_word_name
    spd = EuPathDBSpeciesData.new('Plasmodium chabaudi')
    assert_equal 'Pchabaudi', spd.one_word_name
  end

  def test_download_directory
    spd = EuPathDBSpeciesData.new('Plasmodium chabaudi')
    assert_equal "http://plasmodb.org/common/downloads/release-#{EuPathDBSpeciesData::SOURCE_VERSIONS['PlasmoDB']}/Pchabaudi", spd.eu_path_db_download_directory
  end

  def test_transcript_path_default
    spd = EuPathDBSpeciesData.new('Plasmodium chabaudi', base_dir)
    assert_equal "/home/ben/phd/data/Plasmodium chabaudi/genome/PlasmoDB/#{EuPathDBSpeciesData::SOURCE_VERSIONS['PlasmoDB']}/PchabaudiAnnotatedTranscripts_PlasmoDB-#{EuPathDBSpeciesData::SOURCE_VERSIONS['PlasmoDB']}.fasta",
    spd.transcript_fasta_path
  end

  def test_transcript_fasta_filename
    spd = EuPathDBSpeciesData.new('falciparum')
    assert_equal "Pfalciparum_PlasmoDB-#{EuPathDBSpeciesData::SOURCE_VERSIONS['PlasmoDB']}.gff",
    spd.gff_filename
  end

  def test_gzfile_path_toxo
    spd = EuPathDBSpeciesData.new('gondii', base_dir)
    assert_equal "/home/ben/phd/data/Toxoplasma gondii/genome/ToxoDB/#{EuPathDBSpeciesData::SOURCE_VERSIONS['ToxoDB']}/TgondiiME49Gene_ToxoDB-#{EuPathDBSpeciesData::SOURCE_VERSIONS['ToxoDB']}.txt.gz",
    spd.gene_information_gzfile_path
  end

  def test_gzfile_path_default
    spd = EuPathDBSpeciesData.new('falciparum', base_dir)
    assert_equal "/home/ben/phd/data/Plasmodium falciparum/genome/PlasmoDB/#{EuPathDBSpeciesData::SOURCE_VERSIONS['PlasmoDB']}/PfalciparumGene_PlasmoDB-#{EuPathDBSpeciesData::SOURCE_VERSIONS['PlasmoDB']}.txt.gz",
    spd.gene_information_gzfile_path
  end

  def test_gzfile_filename_default
    spd = EuPathDBSpeciesData.new('falciparum')
    assert_equal "PfalciparumGene_PlasmoDB-#{EuPathDBSpeciesData::SOURCE_VERSIONS['PlasmoDB']}.txt.gz",
    spd.gene_information_gzfile_filename
  end

  def test_directories_for_mkdir
    spd = EuPathDBSpeciesData.new('gondii', base_dir)
    assert_equal [
      '/home/ben/phd/data',
      '/home/ben/phd/data/Toxoplasma gondii',
      '/home/ben/phd/data/Toxoplasma gondii/genome',
      '/home/ben/phd/data/Toxoplasma gondii/genome/ToxoDB',
      "/home/ben/phd/data/Toxoplasma gondii/genome/ToxoDB/#{EuPathDBSpeciesData::SOURCE_VERSIONS['ToxoDB']}"
    ],
    spd.directories_for_mkdir
  end

  def test_one_word_name
    assert_equal 'NeosporaCaninum', EuPathDBSpeciesData.new('Neospora caninum').one_word_name
    spd = EuPathDBSpeciesData.new('Plasmodium falciparum')
    assert_equal 'Pfalciparum', spd.one_word_name
  end

  def test_genomic_filename
    spd = EuPathDBSpeciesData.new('falciparum')
    assert_equal "PfalciparumGenomic_PlasmoDB-#{EuPathDBSpeciesData::SOURCE_VERSIONS['PlasmoDB']}.fasta",
    spd.genomic_fasta_filename
  end

  def test_transcripts_name_without_block
    spd = EuPathDBSpeciesData.new('Babesia bovis')
    assert_equal "BbovisT2BoAnnotatedTranscripts_PiroplasmaDB-#{EuPathDBSpeciesData::SOURCE_VERSIONS['PiroplasmaDB']}.fasta",
    spd.transcript_fasta_filename
  end

  def test_behind_usage_policy
    spd = EuPathDBSpeciesData.new('Plasmodium chabaudi')
    assert_equal "http://plasmodb.org/common/downloads/release-#{EuPathDBSpeciesData::SOURCE_VERSIONS['PlasmoDB']}/Pchabaudi/fasta/data",
    spd.eu_path_db_fasta_download_directory
  end

  def test_behind_usage_policy
    spd = EuPathDBSpeciesData.new('Plasmodium vivax')
    assert_equal "http://plasmodb.org/common/downloads/release-#{EuPathDBSpeciesData::SOURCE_VERSIONS['PlasmoDB']}/Pvivax/fasta",
    spd.eu_path_db_fasta_download_directory
  end

  def test_representative_strain_name
    spd = EuPathDBSpeciesData.new('Trypanosoma brucei')
    assert_equal "http://tritrypdb.org/common/downloads/release-#{EuPathDBSpeciesData::SOURCE_VERSIONS['TriTrypDB']}/Tbrucei/fasta/TbruceiTreu927Genomic_TriTrypDB-#{EuPathDBSpeciesData::SOURCE_VERSIONS['TriTrypDB']}.fasta",
    "#{spd.eu_path_db_fasta_download_directory}/#{spd.genomic_fasta_filename}"
  end

  def test_non_default_db_version_of_protein_fasta
    spd = EuPathDBSpeciesData.new('Plasmodium yoelii', base_dir,'100.9')
    assert_equal "/home/ben/phd/data/Plasmodium yoelii/genome/PlasmoDB/100.9/PyoeliiAnnotatedProteins_PlasmoDB-100.9.fasta",
    spd.protein_fasta_path
  end

  def test_species_data_from_database
    plasmos = EuPathDBSpeciesData.species_data_from_database('PlasmoDB')
    # make sure there is only 1 of each species being produced - there was a bug about that multiple species were being generated at one point
    bergs = plasmos.select{|s|
      EuPathDBSpeciesData.new(s.name).name == 'Plasmodium berghei'
    }
    assert_equal ['Plasmodium berghei'], bergs.collect{|d| d.name}
  end
end


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/button_color</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>

    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

    <style name="AppCompatAlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
        <item name="colorAccent">@color/button_color</item>

    </style>

    <style name="RatingBar" parent="Theme.AppCompat">
        <item name="colorControlNormal">@color/gold</item>

    </style>

</resources>

redpajama_set_name: RedPajamaGithub


text:
package com.codepoetics.fluvius.operations;

import com.codepoetics.fluvius.api.Operation;
import com.codepoetics.fluvius.api.functional.ScratchpadFunction;
import com.codepoetics.fluvius.api.scratchpad.Scratchpad;

/**
 * Utility class for working with Operations.
 */
public final class Operations {

  private Operations() {
  }

  /**
   * Construct an Operation from the supplied name and ScratchpadFunction.
   *
   * @param name     The name to give the Operation.
   * @param function The ScratchpadFunction executed by the Operation.
   * @param <T>      The type of the value returned by the Operation.
   * @return The constructed Operation.
   */
  public static <T> Operation<T> fromFunction(String name, ScratchpadFunction<T> function) {
    return new FunctionOperation<>(name, function);
  }

  private static final class FunctionOperation<T> implements Operation<T> {
    private final String name;
    private final ScratchpadFunction<T> function;

    private FunctionOperation(String name, ScratchpadFunction<T> function) {
      this.name = name;
      this.function = function;
    }

    @Override
    public String getName() {
      return name;
    }

    @Override
    public T run(Scratchpad scratchpad) throws Exception {
      return function.apply(scratchpad);
    }
  }
}


text:
CREATE PROCEDURE [dbo].[Security_Create]
	@userId int = 0,
	@websiteId int = 0,
	@pageId int = 0,
	@feature nvarchar(50) = '',
	@security binary(32)

AS
	DECLARE @hasSecurity int = 0;
	SELECT @hasSecurity = COUNT(*) FROM [Security] WHERE userId=@userId AND websiteId=@websiteId AND pageId=@pageId AND feature=@feature
	IF(@hasSecurity = 0) BEGIN
		INSERT INTO [Security] (websiteId, userId, pageId, feature, security)
		VALUES (@websiteId, @userId, @pageId, @feature, @security)
	END


text:
package org.wdm.server;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

/**
 * An application context singleton.
 *
 * @author Akis Papadopoulos
 */
public class ApplicationContext implements ServletContextListener {

    private static final Logger logger = Logger.getLogger(ApplicationContext.class);

    private static SessionFactory sessionFactory;

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        try {
            // Building the datasource session factory using the hibernate.cg.xml
            Configuration conf = new Configuration();
            conf.configure();

            ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(conf.getProperties()).buildServiceRegistry();

            sessionFactory = conf.buildSessionFactory(serviceRegistry);
        } catch (Throwable exc) {
            logger.error("Session Factory creation failed", exc);
        }
    }

    /**
     * A method returning new datasource sessions.
     *
     * @return a datasource session.
     */
    public static Session getSession() {
        return sessionFactory.openSession();
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        sessionFactory.close();
    }
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package es.usc.citius.composit.transformer.wsc.wscxml.model.problem;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * @author Pablo Rodriguez Mier
 */

@XmlRootElement(name = "serviceDesc")
@XmlAccessorType(XmlAccessType.FIELD)
public class XMLServiceDesc extends XMLServiceNode {
    @XmlElement(name = "abstraction")
    private XMLAbstraction abstraction;
    @XmlElement(name = "realizations")
    private XMLRealizations realizations;

    public XMLAbstraction getAbstraction() {
        return abstraction;
    }

    public void setAbstraction(XMLAbstraction abstraction) {
        this.abstraction = abstraction;
    }

    public XMLRealizations getRealizations() {
        return realizations;
    }

    public void setRealizations(XMLRealizations realizations) {
        this.realizations = realizations;
    }

}


text:
package io.jenetics.engine;

import static java.util.Objects.requireNonNull;

import java.util.concurrent.Executor;
import java.util.function.Function;

import io.jenetics.Gene;
import io.jenetics.Genotype;
import io.jenetics.Phenotype;
import io.jenetics.internal.util.Concurrency;
import io.jenetics.util.ISeq;
import io.jenetics.util.Seq;

/**
 * Default phenotype evaluation strategy. It uses the configured {@link Executor}
 * for the fitness evaluation.
 *
 * @author Franz Wilhelmstötter
 * @version 5.0
 * @since 4.2
 */
final class ConcurrentEvaluator<
	G extends Gene<?, G>,
	C extends Comparable<? super C>
>
	implements Evaluator<G, C>
{

	private final Function<? super Genotype<G>, ? extends C> _function;
	private final Executor _executor;

	ConcurrentEvaluator(
		final Function<? super Genotype<G>, ? extends C> function,
		final Executor executor
	) {
		_function = requireNonNull(function);
		_executor = requireNonNull(executor);
	}

	ConcurrentEvaluator<G, C> with(final Executor executor) {
		return new ConcurrentEvaluator<>(_function, executor);
	}

	@Override
	public ISeq<Phenotype<G, C>> eval(final Seq<Phenotype<G, C>> population) {
		final ISeq<PhenotypeFitness<G, C>> evaluate = population.stream()
			.filter(Phenotype::nonEvaluated)
			.map(pt -> new PhenotypeFitness<>(pt, _function))
			.collect(ISeq.toISeq());

		final ISeq<Phenotype<G, C>> result;
		if (evaluate.nonEmpty()) {
			try (var c = Concurrency.with(_executor)) {
				c.execute(evaluate);
			}

			result = evaluate.size() == population.size()
				? evaluate.map(PhenotypeFitness::phenotype)
				: population.stream()
					.filter(Phenotype::isEvaluated)
					.collect(ISeq.toISeq())
					.append(evaluate.map(PhenotypeFitness::phenotype));
		} else {
			result = population.asISeq();
		}

		return result;
	}

	private static final class PhenotypeFitness<
		G extends Gene<?, G>,
		C extends Comparable<? super C>
	>
		implements Runnable
	{
		final Phenotype<G, C> _phenotype;
		final Function<? super Genotype<G>, ? extends C> _function;
		C _fitness;

		PhenotypeFitness(
			final Phenotype<G, C> phenotype,
			final Function<? super Genotype<G>, ? extends C> function
		) {
			_phenotype = phenotype;
			_function = function;
		}

		@Override
		public void run() {
			_fitness = _function.apply(_phenotype.genotype());
		}

		Phenotype<G, C> phenotype() {
			return _phenotype.withFitness(_fitness);
		}

	}

}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Xml;

namespace Protobuild
{
    internal class BinaryPackageResolve : IPackageResolve
    {
        private readonly SourcePackageResolve _sourcePackageResolve;
        private readonly IProjectTemplateApplier _projectTemplateApplier;
        private readonly IPackageGlobalTool _packageGlobalTool;
        private readonly IPackageCacheConfiguration _packageCacheConfiguration;
        private readonly IProgressiveWebOperation _progressiveWebOperation;
        private readonly INuGetPlatformMapping _nugetPlatformMapping;

        public BinaryPackageResolve(
            SourcePackageResolve sourcePackageResolve,
            IProjectTemplateApplier projectTemplateApplier,
            IPackageGlobalTool packageGlobalTool,
            IPackageCacheConfiguration packageCacheConfiguration,
            IProgressiveWebOperation progressiveWebOperation,
            INuGetPlatformMapping nugetPlatformMapping)
        {
            _sourcePackageResolve = sourcePackageResolve;
            _projectTemplateApplier = projectTemplateApplier;
            _packageGlobalTool = packageGlobalTool;
            _packageCacheConfiguration = packageCacheConfiguration;
            _progressiveWebOperation = progressiveWebOperation;
            _nugetPlatformMapping = nugetPlatformMapping;
        }

        public void Resolve(string workingDirectory, IPackageMetadata metadata, string folder, string templateName, bool forceUpgrade)
        {
            var protobuildMetadata = metadata as ProtobuildPackageMetadata;
            var nuGet3Metadata = metadata as NuGet3PackageMetadata;
            var transformedMetadata = metadata as TransformedPackageMetadata;

            if (protobuildMetadata != null)
            {
                ResolveProtobuild(workingDirectory, protobuildMetadata, folder, templateName, forceUpgrade);
                return;
            }

            if (nuGet3Metadata != null)
            {
                ResolveNuGet3(workingDirectory, nuGet3Metadata, folder, templateName, forceUpgrade);
                return;
            }

            if (transformedMetadata != null)
            {
                ResolveTransformed(workingDirectory, transformedMetadata, folder, templateName, forceUpgrade);
                return;
            }

            throw new InvalidOperationException("Unexpected metadata type " + metadata.GetType().Name + " for binary resolve.");
        }

        private void ResolveProtobuild(string workingDirectory, ProtobuildPackageMetadata protobuildMetadata, string folder, string templateName, bool forceUpgrade)
        {
            switch (protobuildMetadata.PackageType)
            {
                case PackageManager.PACKAGE_TYPE_LIBRARY:
                    ResolveLibraryBinary(workingDirectory, protobuildMetadata, Path.Combine(workingDirectory, folder), forceUpgrade, () =>
                    {
                        var package = GetBinaryPackage(protobuildMetadata);
                        if (package == null)
                        {
                            _sourcePackageResolve.Resolve(workingDirectory, protobuildMetadata, folder, null, forceUpgrade);
                            return null;
                        }
                        return package;
                    });
                    break;
                case PackageManager.PACKAGE_TYPE_TEMPLATE:
                    ResolveTemplateBinary(workingDirectory, protobuildMetadata, folder, templateName, forceUpgrade);
                    break;
                case PackageManager.PACKAGE_TYPE_GLOBAL_TOOL:
                    ResolveGlobalToolBinary(workingDirectory, protobuildMetadata, forceUpgrade);
                    break;
                default:
                    throw new InvalidOperationException("Unable to resolve binary package with type '" + protobuildMetadata.PackageType + "' using Protobuild-based package.");
            }
        }

        private void ResolveNuGet3(string workingDirectory, NuGet3PackageMetadata nuGet3Metadata, string folder, string templateName, bool forceUpgrade)
        {
            switch (nuGet3Metadata.PackageType)
            {
                case PackageManager.PACKAGE_TYPE_LIBRARY:
                    ResolveLibraryBinary(workingDirectory, nuGet3Metadata, Path.Combine(workingDirectory, folder), forceUpgrade, () =>
                    {
                        var package = GetBinaryPackage(nuGet3Metadata);
                        if (package == null)
                        {
                            _sourcePackageResolve.Resolve(workingDirectory, nuGet3Metadata, folder, null, forceUpgrade);
                            return null;
                        }
                        return package;
                    });
                    break;
                case PackageManager.PACKAGE_TYPE_TEMPLATE:
                    ResolveTemplateBinary(workingDirectory, nuGet3Metadata, folder, templateName, forceUpgrade);
                    break;
                case PackageManager.PACKAGE_TYPE_GLOBAL_TOOL:
                    ResolveGlobalToolBinary(workingDirectory, nuGet3Metadata, forceUpgrade);
                    break;
                default:
                    throw new InvalidOperationException("Unable to resolve binary package with type '" + nuGet3Metadata.PackageType + "' using Protobuild-based package.");
            }
        }

        private void ResolveTransformed(string workingDirectory, TransformedPackageMetadata transformedMetadata, string folder, string templateName, bool forceUpgrade)
        {
            switch (transformedMetadata.PackageType)
            {
                case PackageManager.PACKAGE_TYPE_LIBRARY:
                    ResolveLibraryBinary(workingDirectory, transformedMetadata, Path.Combine(workingDirectory, folder), forceUpgrade, () =>
                    {
                        var package = GetTransformedBinaryPackage(workingDirectory, transformedMetadata);
                        if (package == null)
                        {
                            throw new InvalidOperationException("Unable to transform " + transformedMetadata.SourceURI + " for usage as a Protobuild package.");
                        }
                        return package;
                    });
                    break;
                default:
                    throw new InvalidOperationException("Unable to resolve binary package with type '" + transformedMetadata.PackageType + "' using transformer-based package.");
            }
        }

        private void ResolveLibraryBinary(string workingDirectory, ICachableBinaryPackageMetadata protobuildMetadata, string folder, bool forceUpgrade, Func<byte[]> getBinaryPackage)
        {
            var platformFolder = Path.Combine(folder, protobuildMetadata.Platform);

            if (File.Exists(Path.Combine(platformFolder, ".pkg")))
            {
                if (!forceUpgrade)
                {
                    RedirectableConsole.WriteLine("Protobuild binary package already present at " + platformFolder);
                    return;
                }
            }

            RedirectableConsole.WriteLine("Creating and emptying " + platformFolder);

            if (File.Exists(Path.Combine(folder, ".pkg")))
            {
                if (Directory.Exists(platformFolder))
                {
                    // Only clear out the target's folder if the reference folder
                    // already contains binary packages (for other platforms)
                    PathUtils.AggressiveDirectoryDelete(platformFolder);
                }
            }
            else
            {
                // The reference folder is holding source code, so clear it
                // out entirely.
                PathUtils.AggressiveDirectoryDelete(folder);
            }

            Directory.CreateDirectory(platformFolder);

            RedirectableConsole.WriteLine("Marking " + folder + " as ignored for Git");
            GitUtils.MarkIgnored(folder);

            var package = getBinaryPackage();
            if (package == null)
            {
                return;
            }

            ExtractTo(workingDirectory, protobuildMetadata.PackageName, protobuildMetadata.BinaryFormat, package, platformFolder, protobuildMetadata.Platform);

            // Only copy ourselves to the binary folder if both "Build/Module.xml" and
            // "Build/Projects" exist in the binary package's folder.  This prevents us
            // from triggering the "create new module?" logic if the package hasn't been
            // setup correctly.
            if (Directory.Exists(Path.Combine(platformFolder, "Build", "Projects")) &&
                File.Exists(Path.Combine(platformFolder, "Build", "Module.xml")))
            {
                var sourceProtobuild = Assembly.GetEntryAssembly().Location;
                File.Copy(sourceProtobuild, Path.Combine(platformFolder, "Protobuild.exe"), true);

                try
                {
                    var chmodStartInfo = new ProcessStartInfo
                    {
                        FileName = "chmod",
                        Arguments = "a+x Protobuild.exe",
                        WorkingDirectory = platformFolder,
                        UseShellExecute = false
                    };
                    Process.Start(chmodStartInfo);
                }
                catch (ExecEnvironment.SelfInvokeExitException)
                {
                    throw;
                }
                catch
                {
                }
            }

            var file = File.Create(Path.Combine(platformFolder, ".pkg"));
            file.Close();

            file = File.Create(Path.Combine(folder, ".pkg"));
            file.Close();

            RedirectableConsole.WriteLine("Binary resolution complete");
        }

        private void ResolveTemplateBinary(string workingDirectory, ICachableBinaryPackageMetadata protobuildMetadata, string folder, string templateName, bool forceUpgrade)
        {
            if (folder != string.Empty)
            {
                throw new InvalidOperationException("Reference folder must be empty for template type.");
            }

            // The template is a reference to a Git repository.
            if (Directory.Exists(Path.Combine(workingDirectory, ".staging")))
            {
                PathUtils.AggressiveDirectoryDelete(Path.Combine(workingDirectory, ".staging"));
            }

            Directory.CreateDirectory(Path.Combine(workingDirectory, ".staging"));

            var package = GetBinaryPackage(protobuildMetadata);
            if (package == null)
            {
                _sourcePackageResolve.Resolve(workingDirectory, protobuildMetadata, folder, templateName, forceUpgrade);
                return;
            }

            ExtractTo(workingDirectory, protobuildMetadata.PackageName, protobuildMetadata.BinaryFormat, package, Path.Combine(workingDirectory, ".staging"), "Template");

            _projectTemplateApplier.Apply(Path.Combine(workingDirectory, ".staging"), templateName);
            PathUtils.AggressiveDirectoryDelete(Path.Combine(workingDirectory, ".staging"));
        }

        private void ResolveGlobalToolBinary(string workingDirectory, ICachableBinaryPackageMetadata protobuildMetadata, bool forceUpgrade)
        {
            var toolFolder = _packageGlobalTool.GetGlobalToolInstallationPath(protobuildMetadata.CanonicalURI);

            if (File.Exists(Path.Combine(toolFolder, ".pkg")))
            {
                if (!forceUpgrade)
                {
                    RedirectableConsole.WriteLine("Protobuild binary package already present at " + toolFolder);
                    return;
                }
            }

            RedirectableConsole.WriteLine("Creating and emptying " + toolFolder);
            PathUtils.AggressiveDirectoryDelete(toolFolder);
            Directory.CreateDirectory(toolFolder);

            RedirectableConsole.WriteLine("Installing " + protobuildMetadata.CanonicalURI + " at version " + protobuildMetadata.GitCommitOrRef);
            var package = GetBinaryPackage(protobuildMetadata);
            if (package == null)
            {
                RedirectableConsole.WriteLine("The specified global tool package is not available for this platform.");
                return;
            }

            ExtractTo(workingDirectory, protobuildMetadata.PackageName, protobuildMetadata.BinaryFormat, package, toolFolder, protobuildMetadata.Platform);

            var file = File.Create(Path.Combine(toolFolder, ".pkg"));
            file.Close();

            _packageGlobalTool.ScanPackageForToolsAndInstall(toolFolder);

            RedirectableConsole.WriteLine("Binary resolution complete");
        }

        private byte[] GetBinaryPackage(ICachableBinaryPackageMetadata metadata)
        {
            if (metadata.BinaryFormat == null || metadata.BinaryUri == null)
            {
                // There is no binary format for this package.
                return null;
            }

            var localFileExists = false;
            try
            {
                localFileExists = File.Exists(metadata.BinaryUri);
            }
            catch
            {
            }

            if (metadata.BinaryFormat != null && localFileExists)
            {
                // This is a local package file, read it directly.
                using (var stream = new FileStream(metadata.BinaryUri, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    var data = new byte[stream.Length];
                    stream.Read(data, 0, data.Length);
                    return data;
                }
            }

            if (this.HasBinaryPackage(metadata))
            {
                // We have it already downloaded in the cache.
                var file = Path.Combine(
                    _packageCacheConfiguration.GetCacheDirectory(),
                    this.GetPackageName(metadata));
                using (var stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    var data = new byte[stream.Length];
                    stream.Read(data, 0, data.Length);
                    return data;
                }
            }

            // We must use the package retrieval interface to download a copy
            // of the package.
            var tempFile = Path.Combine(
                _packageCacheConfiguration.GetCacheDirectory(),
                this.GetPackageName(metadata) + ".tmp");
            if (!DownloadBinaryPackage(metadata, tempFile))
            {
                return null;
            }

            var saveFile = Path.Combine(
                _packageCacheConfiguration.GetCacheDirectory(),
                this.GetPackageName(metadata));
            try
            {
                File.Move(tempFile, saveFile);
            }
            catch (Exception)
            {
                RedirectableConsole.WriteLine("WARNING: Unable to save package to cache.");
                saveFile = tempFile;
            }

            byte[] saveData;
            using (var stream = new FileStream(saveFile, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                saveData = new byte[stream.Length];
                stream.Read(saveData, 0, saveData.Length);
            }

            if (saveFile == tempFile)
            {
                File.Delete(tempFile);
            }

            return saveData;
        }

        private byte[] GetTransformedBinaryPackage(string workingDirectory, TransformedPackageMetadata metadata)
        {
            if (this.HasBinaryPackage(metadata))
            {
                // We have it already downloaded in the cache.
                var file = Path.Combine(
                    _packageCacheConfiguration.GetCacheDirectory(),
                    this.GetPackageName(metadata));
                using (var stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    var data = new byte[stream.Length];
                    stream.Read(data, 0, data.Length);
                    return data;
                }
            }

            var packageData = metadata.Transformer.Transform(
                workingDirectory,
                metadata.SourceURI,
                metadata.GitRef,
                metadata.Platform,
                PackageManager.ARCHIVE_FORMAT_TAR_LZMA);
            if (packageData == null)
            {
                throw new InvalidOperationException("Unable to transform " + metadata.SourceURI + " for usage as a Protobuild package.");
            }

            var saveFile = Path.Combine(
                _packageCacheConfiguration.GetCacheDirectory(),
                this.GetPackageName(metadata));

            var attempts = 10;
            while (attempts > 0)
            {
                try
                {
                    using (var stream = new FileStream(saveFile, FileMode.Create, FileAccess.Write, FileShare.None))
                    {
                        stream.Write(packageData, 0, packageData.Length);
                    }
                    break;
                }
                catch (IOException)
                {
                    // On Windows, we can't write out the package file if another instance of Protobuild
                    // is writing it out at the moment.  Just wait and retry in another second.
                    RedirectableConsole.WriteLine("WARNING: Unable to write downloaded package file (attempt " + (11 - attempts) + " / 10)");
                    System.Threading.Thread.Sleep(5000);
                    attempts--;
                }
            }

            return packageData;
        }

        private bool HasBinaryPackage(ICachableBinaryPackageMetadata metadata)
        {
            var file = Path.Combine(
                _packageCacheConfiguration.GetCacheDirectory(),
                this.GetPackageName(metadata));
            return File.Exists(file);
        }

        private string GetPackageName(ICachableBinaryPackageMetadata metadata)
        {
            var sha1 = new SHA1Managed();

            var urlHashBytes = sha1.ComputeHash(Encoding.UTF8.GetBytes(NormalizeURIForCache(metadata.CanonicalURI)));
            var urlHashString = BitConverter.ToString(urlHashBytes).Replace("-", "").ToLowerInvariant();
            var gitHashString = metadata.GitCommitOrRef.ToLowerInvariant();
            var platformString = metadata.Platform.ToLowerInvariant();

            return urlHashString + "-" + gitHashString + "-" + platformString + TranslateToExtension(metadata.BinaryFormat);
        }

        private string NormalizeURIForCache(string canonicalUri)
        {
            var index = canonicalUri.IndexOf("://", StringComparison.InvariantCulture);

            if (index != -1)
            {
                return canonicalUri.Substring(index + "://".Length);
            }

            return canonicalUri;
        }

        private string TranslateToExtension(string format)
        {
            switch (format)
            {
                case PackageManager.ARCHIVE_FORMAT_TAR_LZMA:
                    return ".tar.lzma";
                case PackageManager.ARCHIVE_FORMAT_TAR_GZIP:
                    return ".tar.gz";
                case PackageManager.ARCHIVE_FORMAT_NUGET_ZIP:
                    return ".nupkg";
                case "":
                    return string.Empty;
                default:
                    throw new InvalidOperationException("Archive format not supported in cache.");
            }
        }

        private bool DownloadBinaryPackage(ICachableBinaryPackageMetadata metadata, string targetPath)
        {
            if (File.Exists(targetPath))
            {
                File.Delete(targetPath);
            }

            var packageData = this.DownloadBinaryPackage(metadata);
            if (packageData == null)
            {
                // There is no binary package available.
                return false;
            }

            var attempts = 10;
            while (attempts > 0)
            {
                try
                {
                    using (var stream = new FileStream(targetPath, FileMode.Create, FileAccess.Write, FileShare.None))
                    {
                        stream.Write(packageData, 0, packageData.Length);
                    }
                    break;
                }
                catch (IOException)
                {
                    // On Windows, we can't write out the package file if another instance of Protobuild
                    // is writing it out at the moment.  Just wait and retry in another second.
                    RedirectableConsole.WriteLine("WARNING: Unable to write downloaded package file (attempt " + (11 - attempts) + " / 10)");
                    System.Threading.Thread.Sleep(5000);
                    attempts--;
                }
            }

            if (attempts == 0)
            {
                RedirectableConsole.WriteLine(
                    "WARNING: Unable to write out downloaded package!  Assuming " +
                    "another instance of Protobuild will provide it.");
            }

            return true;
        }

        private byte[] DownloadBinaryPackage(ICachableBinaryPackageMetadata metadata)
        {
            try
            {
                return _progressiveWebOperation.Get(metadata.BinaryUri);
            }
            catch (InvalidOperationException)
            {
                RedirectableConsole.WriteLine("Unable to download binary package for version \"" + metadata.GitCommitOrRef + "\" and platform \"" + metadata.Platform + "\", falling back to source version");
                return null;
            }
        }

        private void ExtractTo(string workingDirectory, string packageName, string format, byte[] data, string path, string platform)
        {
            RedirectableConsole.WriteLine("Unpacking binary package from " + format + " archive");
            switch (format)
            {
                case PackageManager.ARCHIVE_FORMAT_TAR_GZIP:
                    {
                        using (var memory = new MemoryStream(data))
                        {
                            using (var decompress = new GZipStream(memory, CompressionMode.Decompress))
                            {
                                using (var memory2 = new MemoryStream())
                                {
                                    decompress.CopyTo(memory2);
                                    memory2.Seek(0, SeekOrigin.Begin);
                                    var reader = new tar_cs.TarReader(memory2);
                                    var reduplicator = new Reduplicator();
                                    reduplicator.UnpackTarToFolder(reader, path);
                                }
                            }
                        }
                        break;
                    }
                case PackageManager.ARCHIVE_FORMAT_TAR_LZMA:
                    {
                        using (var inMemory = new MemoryStream(data))
                        {
                            using (var outMemory = new MemoryStream())
                            {
                                LZMA.LzmaHelper.Decompress(inMemory, outMemory);
                                outMemory.Seek(0, SeekOrigin.Begin);
                                var reader = new tar_cs.TarReader(outMemory);
                                var reduplicator = new Reduplicator();
                                reduplicator.UnpackTarToFolder(reader, path);
                            }
                        }
                        break;
                    }
                case PackageManager.ARCHIVE_FORMAT_NUGET_ZIP:
                    {
                        using (var inMemory = new MemoryStream(data))
                        {
                            using (var zipStorer = ZipStorer.Open(inMemory, FileAccess.Read, true))
                            {
                                var reduplicator = new Reduplicator();
                                var extractedFiles = reduplicator.UnpackZipToFolder(
                                    zipStorer,
                                    path,
                                    candidatePath => candidatePath.Replace('\\', '/').StartsWith("protobuild/" + platform + "/"),
                                    outputPath => outputPath.Replace('\\', '/').Substring(("protobuild/" + platform + "/").Length));

                                if (extractedFiles.Count == 0)
                                {
                                    // There were no files that matched protobuild/ which means this is
                                    // not a Protobuild-aware NuGet package.  We need to convert it on-the-fly
                                    // to a compatible Protobuild format.
                                    ConvertNuGetOnlyPackage(reduplicator, zipStorer, path, packageName, workingDirectory, platform);
                                }
                            }
                        }
                        break;
                    }
                default:
                    throw new InvalidOperationException(
                        "This version of Protobuild does not support the " +
                        format + " package format.");
            }
        }

        private void ConvertNuGetOnlyPackage(Reduplicator reduplicator, ZipStorer zipStorer, string path, string packageName, string workingDirectory, string platform)
        {
            var folder = Path.GetTempFileName();
            File.Delete(folder);
            Directory.CreateDirectory(folder);

            try
            {
                reduplicator.UnpackZipToFolder(
                    zipStorer,
                    folder,
                    candidatePath => true,
                    outputPath => outputPath);

                var references = new List<string>();
                var libraryReferences = new Dictionary<string, string>();
                var packageDependencies = new Dictionary<string, string>();

                // Load NuGet specification file.
                var specFile = Directory.GetFiles(folder, "*.nuspec").FirstOrDefault();
                if (specFile != null)
                {
                    specFile = Path.Combine(folder, specFile);
                    if (File.Exists(specFile))
                    {
                        var packageDoc = new XmlDocument();
                        packageDoc.Load(specFile);

                        if (packageDoc?.DocumentElement != null)
                        {
                            // If we have an id in the package, that forms the package name.
                            if (packageDoc.DocumentElement.FirstChild.ChildNodes.OfType<XmlElement>()
                                    .Count(x => x.Name == "id") > 0)
                            {
                                var newName = packageDoc.DocumentElement.FirstChild.ChildNodes.OfType<XmlElement>()
                                    .First(x => x.Name == "id").InnerText.Trim();
                                if (!string.IsNullOrWhiteSpace(newName))
                                {
                                    packageName = newName;
                                }
                            }

                            // If the references are explicitly provided in the nuspec, use
                            // those as to what files should be referenced by the projects.
                            if (packageDoc.DocumentElement.FirstChild.ChildNodes.OfType<XmlElement>()
                                    .Count(x => x.Name == "references") > 0)
                            {
                                references =
                                    packageDoc.DocumentElement.FirstChild.ChildNodes.OfType<XmlElement>()
                                        .First(x => x.Name == "references")
                                        .ChildNodes.OfType<XmlElement>()
                                        .Where(x => x.Name == "reference")
                                        .Select(x => x.Attributes["file"].Value)
                                        .ToList();
                            }

                            // If there are dependencies specified, store them and convert them to
                            // Protobuild references, and reference them in the Module.xml file.
                            if (packageDoc.DocumentElement.FirstChild.ChildNodes.OfType<XmlElement>()
                                    .Count(x => x.Name == "dependencies") > 0)
                            {
                                packageDependencies =
                                    packageDoc.DocumentElement.FirstChild.ChildNodes.OfType<XmlElement>()
                                        .First(x => x.Name == "dependencies")
                                        .ChildNodes.OfType<XmlElement>()
                                        .Where(x => x.Name == "dependency")
                                        .ToDictionarySafe(
                                            k => k.Attributes["id"].Value,
                                            v => v.Attributes["version"].Value,
                                            (dict, c) =>
                                                RedirectableConsole.WriteLine("WARNING: More than one dependency on " +
                                                                              c +
                                                                              " in NuGet package."));
                            }
                        }
                    }
                }

                if (string.IsNullOrWhiteSpace(packageName))
                {
                    throw new InvalidOperationException("Expected package name when converting NuGet-only package!");
                }

                // Determine the priority of the frameworks that we want to target
                // out of the available versions.
                string[] clrNames = _nugetPlatformMapping.GetFrameworkNamesForRead(workingDirectory, platform);

                var referenceDirectories = new string[] { "ref", "lib" };

                foreach (var directory in referenceDirectories)
                {
                    // Determine the base path for all references; that is, the lib/ folder.
                    var referenceBasePath = Path.Combine(
                        folder,
                        directory);

                    if (Directory.Exists(referenceBasePath))
                    {
                        // If no references are in nuspec, reference all of the libraries that
                        // are on disk.
                        if (references.Count == 0)
                        {
                            // Search through all of the target frameworks until we find one that
                            // has at least one file in it.
                            foreach (var clrNameOriginal in clrNames)
                            {
                                var clrName = clrNameOriginal;
                                var foundClr = false;

                                if (clrName[0] == '=')
                                {
                                    // Exact match (strip the equals).
                                    clrName = clrName.Substring(1);

                                    // If this target framework doesn't exist for this library, skip it.
                                    var dirPath = Path.Combine(
                                        referenceBasePath,
                                        clrName);
                                    if (!Directory.Exists(dirPath))
                                    {
                                        continue;
                                    }
                                }
                                else if (clrName[0] == '?')
                                {
                                    // Substring, search the reference base path for any folders
                                    // with a matching substring.
                                    clrName = clrName.Substring(1);

                                    var baseDirPath = referenceBasePath;
                                    var found = false;
                                    foreach (var subdir in new DirectoryInfo(baseDirPath).GetDirectories())
                                    {
                                        if (subdir.Name.Contains(clrName))
                                        {
                                            clrName = subdir.Name;
                                            found = true;
                                            break;
                                        }
                                    }

                                    if (!found)
                                    {
                                        continue;
                                    }
                                }
                                else
                                {
                                    throw new InvalidOperationException("Unknown CLR name match type with '" + clrName +
                                                                        "'");
                                }

                                // Otherwise enumerate through all of the libraries in this folder.
                                foreach (var dll in Directory.EnumerateFiles(
                                    Path.Combine(
                                        referenceBasePath, clrName),
                                    "*.dll"))
                                {
                                    // Determine the relative path to the library.
                                    var packageDll = Path.Combine(
                                        referenceBasePath,
                                        clrName,
                                        Path.GetFileName(dll));

                                    // Confirm again that the file actually exists on disk when
                                    // combined with the root path.
                                    if (File.Exists(
                                        Path.Combine(
                                            packageDll)))
                                    {
                                        // Create the library reference.
                                        if (!libraryReferences.ContainsKey(Path.GetFileNameWithoutExtension(dll)))
                                        {
                                            libraryReferences.Add(
                                                Path.GetFileNameWithoutExtension(dll),
                                                packageDll);
                                        }

                                        // Mark this target framework as having provided at least
                                        // one reference.
                                        foundClr = true;
                                    }
                                }

                                // Break if we have found at least one reference.
                                if (foundClr)
                                    break;
                            }
                        }

                        // For all of the references that were found in the original nuspec file,
                        // add those references.
                        foreach (var reference in references)
                        {
                            // Search through all of the target frameworks until we find the one
                            // that has the reference in it.
                            foreach (var clrName in clrNames)
                            {
                                // If this target framework doesn't exist for this library, skip it.
                                var packageDll = Path.Combine(
                                    referenceBasePath,
                                    clrName,
                                    reference);

                                if (File.Exists(
                                    Path.Combine(
                                        packageDll)))
                                {
                                    if (!libraryReferences.ContainsKey(Path.GetFileNameWithoutExtension(packageDll)))
                                    {
                                        libraryReferences.Add(
                                            Path.GetFileNameWithoutExtension(packageDll),
                                            packageDll);
                                    }
                                    break;
                                }
                            }
                        }
                    }
                }

                foreach (var kv in libraryReferences)
                {
                    RedirectableConsole.WriteLine("Found library to reference: " + kv.Key + " (at " + kv.Value + ")");
                }

                RedirectableConsole.WriteLine("Generating external project reference...");
                var document = new XmlDocument();
                var externalProject = document.CreateElement("ExternalProject");
                externalProject.SetAttribute("Name", packageName);
                document.AppendChild(externalProject);
                foreach (var kv in libraryReferences)
                {
                    var binaryReference = document.CreateElement("Binary");
                    binaryReference.SetAttribute("Name", kv.Key);
                    binaryReference.SetAttribute("Path",
                        kv.Value.Substring(folder.Length).TrimStart(new[] { '/', '\\' }).Replace("%2B", "-"));
                    externalProject.AppendChild(binaryReference);
                }
                foreach (var package in packageDependencies)
                {
                    var externalReference = document.CreateElement("Reference");
                    externalReference.SetAttribute("Include", package.Key);
                    externalProject.AppendChild(externalReference);
                }
                Directory.CreateDirectory(Path.Combine(path, "Build", "Projects"));
                document.Save(Path.Combine(path, "Build", "Projects", packageName + ".definition"));

                RedirectableConsole.WriteLine("Generating module...");
                var generatedModule = new ModuleInfo();
                generatedModule.Name = packageName;
                generatedModule.Packages = new List<PackageRef>();

                foreach (var package in packageDependencies)
                {
                    generatedModule.Packages.Add(new PackageRef
                    {
                        Uri = "https-nuget-v3://api.nuget.org/v3/index.json|" + package.Key,
                        GitRef = package.Value.TrimStart('[').TrimEnd(']'),
                        Folder = package.Key
                    });
                }

                generatedModule.Save(Path.Combine(path, "Build", "Module.xml"));

                foreach (var kv in libraryReferences)
                {
                    var targetFile =
                        new FileInfo(Path.Combine(path,
                            kv.Value.Substring(folder.Length).Replace('\\', '/').TrimStart('/').Replace("%2B", "-")));
                    targetFile.Directory.Create();
                    File.Copy(kv.Value, targetFile.FullName);
                }
            }
            finally
            {
                PathUtils.AggressiveDirectoryDelete(folder);
            }
        }

        public void GetProtobuildPackageBinary(IPackageMetadata metadata, out string archiveType, out byte[] packageData)
        {
            var protobuildPackageMetadata = metadata as ProtobuildPackageMetadata;
            if (protobuildPackageMetadata == null)
            {
                throw new InvalidOperationException("Can't call GetProtobuildPackageBinary on non-Protobuild package metadata");
            }

            archiveType = protobuildPackageMetadata.BinaryFormat;
            packageData = GetBinaryPackage(protobuildPackageMetadata);
        }
    }
}


text:
.oo-ui-icon-bell {
	background-image: /* @embed */ url(themes/mediawiki/images/icons/bell.png);
}
.oo-ui-icon-bellOn {
	background-image: /* @embed */ url(themes/mediawiki/images/icons/bellOn-rtl.png);
}
.oo-ui-icon-eye {
	background-image: /* @embed */ url(themes/mediawiki/images/icons/eye.png);
}
.oo-ui-icon-eyeClosed {
	background-image: /* @embed */ url(themes/mediawiki/images/icons/eyeClosed.png);
}
.oo-ui-icon-message {
	background-image: /* @embed */ url(themes/mediawiki/images/icons/message-rtl.png);
}
.oo-ui-icon-signature {
	background-image: /* @embed */ url(themes/mediawiki/images/icons/signature-rtl.png);
}
.oo-ui-icon-speechBubble {
	background-image: /* @embed */ url(themes/mediawiki/images/icons/speechBubble-rtl.png);
}
.oo-ui-icon-speechBubbleAdd {
	background-image: /* @embed */ url(themes/mediawiki/images/icons/speechBubbleAdd-rtl.png);
}
.oo-ui-icon-speechBubbles {
	background-image: /* @embed */ url(themes/mediawiki/images/icons/speechBubbles-rtl.png);
}


text:
import classnames from 'classnames';
import { sortBy } from 'lodash';
import * as React from 'react';
import { FormattedMessage } from 'react-intl';
import { useDispatch, useSelector } from 'react-redux';
import InlineConsentRadioButtons from '../../components/consent/InlineConsentRadioButtons';
import ProcessingThen from '../../components/ProcessingThen.js';
import api from '../../modules/api';
import consent from '../../modules/consent/consent';
import { updateForm } from '../../state/forms/';
import { Member } from '../../state/member';
import { IAppState, IFormField } from '../../types';
import Button from '../Button/Button';
import PopupMemberConsent from '../consent/PopupMemberConsent';
import FormField from './FormField';

export interface IProps {
  id: number;
  fields: IFormField[];
  outstandingFields: string[];
  values: { [key: string]: string };
  errors: { [key: string]: string[] };
  enableConsent?: boolean;
  className?: string;
  onValidate: (data?: any) => any;
  onSubmit: (data?: any) => any;
}

export default function Form(props: IProps, second?: any) {
  const dispatch = useDispatch();
  const values = useSelector((state: IAppState) => state.forms[props.id]);
  const member = useSelector((state: IAppState) => state.member);
  const [highlightConsent, setHighlightConsent] = React.useState(false);
  const [popupOpen, setPopupOpen] = React.useState(false);
  const submitting = values['submitting'] || false;
  const className = classnames('Form', props.className);
  const country = values['country'] as string;

  const onChange = name => {
    return value => {
      dispatch(updateForm(props.id, { ...values, [name]: value }));
    };
  };

  const withConsentCheck = callback => {
    if (!consent.isRequired(country, member)) {
      return callback;
    }

    return (e: React.SyntheticEvent<HTMLFormElement>) => {
      const required =
        consent.isRequired(country, member) && values['consented'] == null;
      e.preventDefault();
      if (required) {
        setHighlightConsent(required);
        setPopupOpen(required);
      } else {
        return callback(e);
      }
    };
  };

  const onChangeConsent = value => {
    const cb = onChange('consented');
    setHighlightConsent(value === undefined);
    cb(value);
  };
  const submit = (e: React.SyntheticEvent<HTMLFormElement>) => {
    // check if consent is necessary and/or checked
    props.onSubmit(e.currentTarget);
    e.preventDefault();
  };

  const popupSubmit = (consented: boolean) => {
    onChange('consented')(consented);
    props.onSubmit();
  };

  const filterFields = (fields: IFormField[]) => {
    const fieldsByDisplayMode = filterByDisplayMode(fields, member);
    return filterByValue(fieldsByDisplayMode, member);
  };

  const renderFields = (fields: IFormField[]) =>
    fields.map(field => (
      <FormField
        key={field.name}
        {...field}
        {...api.helpers.formErrorFields(props.errors[field.name])}
        onChange={onChange(field.name)}
        default_value={values[field.name] || field.default_value || ''}
      />
    ));

  return (
    <form
      onSubmit={withConsentCheck(submit)}
      className={className}
      id={`form-${props.id}`}
    >
      {renderFields(sortByPosition(filterFields(props.fields)))}
      {consent.isRequired(country, member) && (
        <InlineConsentRadioButtons
          consent={values['consented'] as boolean}
          onChange={onChangeConsent}
          highlight={highlightConsent}
        />
      )}
      <PopupMemberConsent
        open={popupOpen}
        countryCode={values['country'] as string}
        toggleModal={setPopupOpen}
        onSubmit={popupSubmit}
      />
      <Button type="submit" disabled={submitting}>
        <ProcessingThen processing={submitting}>
          <FormattedMessage
            id="petition.sign_it"
            defaultMessage="Sign the petition"
          />
        </ProcessingThen>
      </Button>
    </form>
  );
}

const sortByPosition = arr => sortBy(arr, ['position']);

// Filter out any fields for which we already have a value
const filterByValue = (fields: IFormField[], member: Member) => {
  if (!member) {
    return fields;
  }
  return fields.filter(field => member.more[field.name] === undefined);
};

// Filter by "FormFieldDisplayMode"
const filterByDisplayMode = (fields: IFormField[], member: Member) => {
  return fields.filter(field => {
    switch (field.display_mode) {
      case 'all_members':
        return true;
      case 'new_members_only':
        return !member;
      case 'recognized_members_only':
        return !!member;
      default:
        return true;
    }
  });
};


text:
package org.usfirst.frc620.Warbot2017;

import org.usfirst.frc620.Warbot2017.commands.ClimbDriving;
import org.usfirst.frc620.Warbot2017.commands.DriveDistance;
import org.usfirst.frc620.Warbot2017.commands.LowerBallMech;
import org.usfirst.frc620.Warbot2017.commands.LowerGearArm;
import org.usfirst.frc620.Warbot2017.commands.RaiseBallMech;
import org.usfirst.frc620.Warbot2017.commands.RaiseGearArm;
import org.usfirst.frc620.Warbot2017.commands.StopsAllThings;
import org.usfirst.frc620.Warbot2017.commands.ToggleServo;

import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.XboxController;
import edu.wpi.first.wpilibj.buttons.JoystickButton;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;

/**
 * This class is the glue that binds the controls on the physical operator
 * interface to the commands and command groups that allow control of the robot.
 */
public class OI {

	private XboxController xbox;
	public JoystickButton a;
	public JoystickButton b;
	public JoystickButton x;
	public JoystickButton y;
	public JoystickButton rBumper;
	public JoystickButton back;
	public JoystickButton start;

	public int gyro = 0;

	public OI() {
		xbox = new XboxController(0);

		rBumper = new JoystickButton(xbox, 6);
		rBumper.whenPressed(new ClimbDriving());

		y = new JoystickButton(xbox, 4);
		y.whenPressed(new RaiseGearArm());

		x = new JoystickButton(xbox, 3);
		x.whenPressed(new LowerGearArm());

		a = new JoystickButton(xbox, 1);
		a.whenPressed(new LowerBallMech());

		b = new JoystickButton(xbox, 2);
		b.whenPressed(new RaiseBallMech());

		back = new JoystickButton(xbox, 7);
		back.whenPressed(new StopsAllThings());

		start = new JoystickButton(xbox, 8);
		start.whenPressed(new ToggleServo());

		// SmartDashboard Buttons
//		SmartDashboard.putData("Autonomous Command", new AutonomousCommand());
//		SmartDashboard.putData("DriveWithXbox", new DriveWithXbox());
//		SmartDashboard.putData("RaiseGearArm", new RaiseGearArm());
//		SmartDashboard.putData("LowerGearArm", new LowerGearArm());
//		SmartDashboard.putData("DepositGear", new DepositGear());
//		SmartDashboard.putData("AutoLeftStart", new AutoLeftStart());
//		SmartDashboard.putData("AutoRightStart", new AutoRightStart());
//		SmartDashboard.putData("AutoMidStart", new AutoMidStart());
//		SmartDashboard.putData("DriveUntilDist (20)", new DriveUntilDist(20, .5));
//		SmartDashboard.putData("Drive With Vision (30)", new AlignForGearPeg(30, .3));
//		SmartDashboard.putData("AlignForGearPeg ", new AlignForGearPeg(0, 1.0));
//		SmartDashboard.putData("ToggleRelay", new ToggleRelay());
//		SmartDashboard.putData("DriveTime 9", new DriveTime(-24));
//		SmartDashboard.putData("Lower .5", new LowerGearArm(.5));
//		SmartDashboard.putData("Turn(90)", new Turn(90));
//		SmartDashboard.putData("Turn(-90)", new Turn(-90));
//		SmartDashboard.putData("Toggle Servo", new ToggleServo());
//		SmartDashboard.putData("Is the NavX working???", new ConfirmNavx());
//		SmartDashboard.putData("Darken Camera", new InstantCommand() {
//			@Override
//			protected void execute() {
//				Robot.cameras.darkenCamera(0);
//			}
//		});
//		SmartDashboard.putData("Lighten Camera", new InstantCommand() {
//			@Override
//			protected void execute() {
//				Robot.cameras.brightenCamera(0);
//			}
//		});
		SmartDashboard.putData("DriveDistance (83)", new DriveDistance(83)); // 10 - 60 - 110
//		SmartDashboard.putData("DriveDistance (83)", new DriveDistance(83)); // 10 - 60 - 110
//		SmartDashboard.putData("DriveDistance (83)", new DriveDistance(83)); // 10 - 60 - 110
//		SmartDashboard.putData("DriveDistance (83)", new DriveDistance(83)); // 10 - 60 - 110
//		SmartDashboard.putData("DriveDistance (83)", new DriveDistance(83)); // 10 - 60 - 110
//		SmartDashboard.putData("DriveDistance (83)", new DriveDistance(83)); // 10 - 60 - 110
	}

	public XboxController getXbox() {
		return xbox;
	}

	public boolean getLBumper() {
		return xbox.getRawButton(5);
	}

	public boolean getRBumper() {
		return xbox.getRawButton(6);
	}

	public double getRightXAxis() {
		return xbox.getRawAxis(4);
	}

	public double getLTrigger() {
		return xbox.getRawAxis(2);
	}

	public double getRTrigger() {
		return xbox.getRawAxis(3);
	}
}


text:
'use strict';
var mongoose = require('mongoose');
var uniqueValidator = require('mongoose-unique-validator');
var bcrypt = require('bcrypt-nodejs');
var eat = require('eat');

var userSchema = new mongoose.Schema({
  basic: {
    email: {type: String, required: true, unique: true},
    password: {type: String, required: true}
  },
  username: String
});

userSchema.plugin(uniqueValidator);

userSchema.methods.generateHash = function (passowrd) {
  return bcrypt.hashSync(passowrd, bcrypt.genSaltSync(8), null);
};

userSchema.methods.validPassword = function (password) {
  return bcrypt.compareSync(password, this.basic.password);
};

userSchema.methods.generateToken = function (appSecret, callback) {
  eat.encode({id: this._id, timestamp: new Date()}, appSecret, callback);
};

module.exports = mongoose.model('User', userSchema);


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://www.netbeans.org/ns/project/1">
    <type>org.netbeans.modules.php.project</type>
    <configuration>
        <data xmlns="http://www.netbeans.org/ns/php-project/1">
            <name>wasteline</name>
        </data>
        <spellchecker-wordlist xmlns="http://www.netbeans.org/ns/spellchecker-wordlist/1">
            <word>Wasteline</word>
        </spellchecker-wordlist>
    </configuration>
</project>


text:
<?php
use_helper('opAsset');
op_smt_use_stylesheet('/opCommunityTopicPlugin/css/smt-topic.css', 'last');
op_smt_use_javascript('/opCommunityTopicPlugin/js/moment.min.js', 'last');
op_smt_use_javascript('/opCommunityTopicPlugin/js/lang/ja.js', 'last');
?>

<?php if ($isTopicCreatable): ?>

  <a href="<?php echo public_path('communityTopic/new').'/'.$id ?>" class="btn span11"><?php echo __('Create a new topic');?>

<?php endif; ?>

<?php echo __('List of topics of this %Community%'); ?>

トピックはありません

    <?php echo op_image_tag('ajax-loader.gif');?>

  <button class="span12 btn small hide" id="loadmore"><?php echo __('More'); ?></button>

    <a href="<?php echo public_path('community').'/'.$community->getId() ?>"><?php echo __('%Community% Top Page') ?>


text:
import os
import sys

import nltk
from nltk.tree import ParentedTree
from nltk.stem import WordNetLemmatizer
from nltk.corpus import wordnet

def get_wordnet_pos(treebank_tag):
	if treebank_tag.startswith('J'):
		return wordnet.ADJ
	elif treebank_tag.startswith('V'):
		return wordnet.VERB
	elif treebank_tag.startswith('N'):
		return wordnet.NOUN
	elif treebank_tag.startswith('R'):
		return wordnet.ADV
	else:
		return ''

def token_process(file_in):
	_tokens = nltk.word_tokenize(file_in)
	return _tokens

def sent_process(file_in):
	_sents = nltk.sent_tokenize(file_in)
	return _sents

def pos_process(file_in):
	_pos = []
	_sents = nltk.sent_tokenize(file_in)
	for sent in _sents:
		_tokens = nltk.word_tokenize(sent)
		_pos_tokens = nltk.pos_tag(_tokens)
		for token in _pos_tokens:
			pos = '{}/{}'.format(token[0].encode("ascii", "ignore"),token[1])
			_pos.append(pos)
	return _pos

def lemma_process(file_in):
	_lemmas = []
	_sents = nltk.sent_tokenize(file_in)
	wordnet_lemmatizer = WordNetLemmatizer()
	for sent in _sents:
		_pos = nltk.pos_tag(nltk.word_tokenize(sent))
		for pos in _pos:
			tag = get_wordnet_pos(pos[1])
			lem = ''
			if tag != '':
				lem = '{}/{}/{}'.format(pos[0].encode("ascii", "ignore"),
						pos[1],
						wordnet_lemmatizer.lemmatize(pos[0], tag).encode("ascii", "ignore"))
			else:
				lem = '{}/{}/{}'.format(pos[0].encode("ascii", "ignore"),
						pos[1],
						wordnet_lemmatizer.lemmatize(pos[0]).encode("ascii", "ignore"))
			_lemmas.append(lem)
	return _lemmas

SENTENCE = 'S'
_ners = []
first = 1
current = ''
def ner_process(parent):
	ner = ''
	global SENTENCE, _ners, first, current
	for node in parent:
		if type(node) is nltk.Tree:
			if node.label() == SENTENCE:
				sys.stdout.write('')
			else:
				for leaf in node.leaves():
					ner = '{}/{}/{}'.format(leaf[0].encode("ascii", "ignore"), leaf[1], node.label())
					current = leaf[0]
					_ners.append(ner)
			ner_process(node)
		else:
			if first == 1:
				ner = '{}/{}'.format(node[0].encode("ascii", "ignore"), node[1])
				first = 0
				_ners.append(ner)
			elif node[0] != current:
				ner = '{}/{}'.format(node[0].encode("ascii", "ignore"), node[1])
				_ners.append(ner)
			else:
				pass

def main():
	doc = []
	sents = []
	pos_tagged = []
	lemmas = []
	ner_tagged = []

	file = ''

	with open(sys.argv[1], 'r') as _file:
		file = _file.read()

	if file == '':
		print 'File not read properly'
		sys.exit()

	uni_str = unicode(file, encoding="utf-8")

	if sys.argv[-1] == 'tokenize':
		doc = token_process(uni_str)
		sys.stdout.write(" ".join(doc).encode("ascii", "ignore"))
		#for token in doc:
		#	print token

	elif sys.argv[-1] == 'sent_split':
		sents = sent_process(uni_str)
		for sent in sents:
			print sent.encode("ascii", "ignore")

	elif sys.argv[-1] == 'pos_tag':
		pos_tagged = pos_process(uni_str)
		#print pos_tagged
		#for pos in pos_tagged:
		#	#print pos
		#	sys.stdout.write(pos)
		sys.stdout.write(" ".join(pos_tagged))

	elif sys.argv[-1] == 'lemmatize':
		lemmas = lemma_process(uni_str)
		#for lemma in lemmas:
			#print lemma
		#	sys.stdout.write(lemma)
		sys.stdout.write(" ".join(lemmas))

	elif sys.argv[-1] == 'ner_tag':
		_sents = nltk.sent_tokenize(uni_str)
		_tokens = [nltk.word_tokenize(sent) for sent in _sents]
		_pos = [nltk.pos_tag(sent) for sent in _tokens]
		_chunked = nltk.ne_chunk_sents(_pos, binary=False)
		ner_process(_chunked)
		sys.stdout.write(" ".join(_ners))

main()
#
#inpt = ""
#tokenCount = 0
#
#with open('_raw/posCase-v5.txt', 'r') as f:
#	inpt=f.read().replace('\n', ' ')
#
#ustr = unicode(inpt,encoding="utf-8")
##only use sent_toknize_list for sent splitting
#sent_tokenize_list = nltk.sent_tokenize(ustr)
#
#word_tokenize_list = []
#pos_word_list = []
#for sent in sent_tokenize_list:
#	#TOKENIZE SENT INTO INDIVIDUAL TOKENS
#	word_tokenize_list = nltk.word_tokenize(sent)
#	#POS TAG WORD TOKENS
#	pos_word_list = nltk.pos_tag(word_tokenize_list)
#	for pos in pos_word_list:
#		tokenCount+=1
#		print '{} {}'.format(pos[0].encode('ascii', 'ignore'), pos[1])
#


text:
<?php
namespace Bolt\Tests\Events;

use Bolt\Cache;
use Bolt\Events\CronEvent;
use Bolt\Events\CronEvents;
use Bolt\Tests\BoltUnitTest;
use Symfony\Component\Console\Output\BufferedOutput;

/**
 * Class to test src/Events/CronEvent.
 *
 * @author Ross Riley <riley.ross@gmail.com>
 * @author Gawain Lynch <gawain.lynch@gmail.com>
 */
class CronEventTest extends BoltUnitTest
{
    public function testCronCalls()
    {
        $app = $this->getApp();

        $app['cache'] = $this->getMock('Bolt\Cache', [], [$app['resources']->getPath('cache'), $app]);
        $app['cache']
            ->expects($this->exactly(1))
            ->method('clearCache');

        $changeRepository = $app['storage']->getRepository('Bolt\Storage\Entity\LogChange');
        $systemRepository = $app['storage']->getRepository('Bolt\Storage\Entity\LogSystem');
        $app['logger.manager'] = $this->getMock('Bolt\Logger\Manager', ['trim'], [$app, $changeRepository, $systemRepository]);
        $app['logger.manager']
            ->expects($this->exactly(2))
            ->method('trim');

        $output = new BufferedOutput();

        $listeningEvent = new CronEvent($app, $output);

        $app['dispatcher']->dispatch(CronEvents::CRON_HOURLY, $listeningEvent);
        $app['dispatcher']->dispatch(CronEvents::CRON_DAILY, $listeningEvent);
        $app['dispatcher']->dispatch(CronEvents::CRON_WEEKLY, $listeningEvent);
        $app['dispatcher']->dispatch(CronEvents::CRON_MONTHLY, $listeningEvent);
        $app['dispatcher']->dispatch(CronEvents::CRON_YEARLY, $listeningEvent);

        // Currently only the weekly produces any output for us to call
        $out = $listeningEvent->output->fetch();
        $this->assertRegExp('/Clearing cache/', $out);
        $this->assertRegExp('/Trimming logs/', $out);
    }
}


text:
WebJar for chance.js

More info: http://webjars.org

Upstream: https://github.com/devdetonator/webjar-uri.js

Web-site: http://chancejs.com/


text:
module.exports = {
  name: "getFullYear",
  ns: "date",
  title: "Get Full Year",
  async: true,
  description: "The year (4 digits for 4-digit years) of the specified date according to local time.",
  phrases: {
    active: "Getting Full Year"
  },
  ports: {
    input: {
      "in": {
        title: "Date",
        type: "Date",
        async: true,
        fn: function __IN__(data, source, state, input, $, output) {
          var r = function() {
            output({
              out: $.write($.in.getFullYear())
            });
          }.call(this);
          return {
            state: state,
            return: r
          };
        }
      }
    },
    output: {
      out: {
        title: "Year",
        type: "number",
        description: "The year (4 digits for 4-digit years) of the specified date according to local time."
      }
    }
  },
  state: {},
  on: {}
}


text:
;(function ($) {

    $(document).on('autocompleteLightInitialize', '[data-autocomplete-light-function=select2]', function() {
        var element = $(this);

        // This widget has a clear button
        $(this).find('option[value=""]').remove();

        // Templating helper
        function template(item) {
            if (element.attr('data-html')) {
                var $result = $('<span>');
                $result.html(item.text);
                return $result;
            } else {
                return item.text;
            }
        }

        var ajax = null;
        if ($(this).attr('data-autocomplete-light-url')) {
            ajax = {
                url: $(this).attr('data-autocomplete-light-url'),
                dataType: 'json',
                delay: 250,

                data: function (params) {
                    var data = {
                        q: params.term, // search term
                        page: params.page,
                        create: element.attr('data-autocomplete-light-create') && !element.attr('data-tags'),
                        forward: get_forwards(element)
                    };

                    return data;
                },
                processResults: function (data, page) {
                    if (element.attr('data-tags')) {
                        $.each(data.results, function(index, value) {
                            value.id = value.text;
                        });
                    }

                    return data;
                },
                cache: true
            };
        }

        $(this).select2({
            tokenSeparators: element.attr('data-tags') ? [','] : null,
            debug: true,
            placeholder: '',
            minimumInputLength: 0,
            allowClear: ! $(this).is('required'),
            templateResult: template,
            templateSelection: template,
            ajax: ajax,
        });

        $(this).on('select2:selecting', function (e) {
            var data = e.params.args.data;

            if (data.create_id !== true)
                return;

            e.preventDefault();

            var select = $(this);

            $.ajax({
                url: $(this).attr('data-autocomplete-light-url'),
                type: 'POST',
                dataType: 'json',
                data: {
                    text: data.id,
                    forward: get_forwards($(this))
                },
                beforeSend: function(xhr, settings) {
                    xhr.setRequestHeader("X-CSRFToken", document.csrftoken);
                },
                success: function(data, textStatus, jqXHR ) {
                    select.append(
                        $('<option>', {value: data.id, text: data.text, selected: true})
                    );
                    select.trigger('change');
                    select.select2('close');
                }
            });
        });

    });

    // Remove this block when this is merged upstream:
    // https://github.com/select2/select2/pull/4249
    $(document).on('DOMSubtreeModified', '[data-autocomplete-light-function=select2] option', function() {
        $(this).parents('select').next().find(
            '.select2-selection--single .select2-selection__rendered'
        ).text($(this).text());
    });
})(yl.jQuery);


text:
"""This application demonstrates how to publish messages with an ordering key with
the Pub/Sub Lite API. For more information, see the root level README.md and the
documentation at https://cloud.google.com/pubsub/lite/docs/publishing.
"""

import argparse

def publish_with_odering_key(
    project_number, cloud_region, zone_id, topic_id, num_messages, regional
):
    # [START pubsublite_publish_ordering_key]
    from google.cloud.pubsublite.cloudpubsub import PublisherClient
    from google.cloud.pubsublite.types import (
        CloudRegion,
        CloudZone,
        MessageMetadata,
        TopicPath,
    )

    # TODO(developer):
    # project_number = 1122334455
    # cloud_region = "us-central1"
    # zone_id = "a"
    # topic_id = "your-topic-id"
    # num_messages = 100
    # regional = True

    if regional:
        location = CloudRegion(cloud_region)
    else:
        location = CloudZone(CloudRegion(cloud_region), zone_id)

    topic_path = TopicPath(project_number, location, topic_id)

    # PublisherClient() must be used in a `with` block or have __enter__() called before use.
    with PublisherClient() as publisher_client:
        for message in range(num_messages):
            data = f"{message}"
            # Messages of the same ordering key will always get published to the same partition.
            # When ordering_key is unset, messsages can get published ot different partitions if
            # more than one partition exists for the topic.
            api_future = publisher_client.publish(
                topic_path, data.encode("utf-8"), ordering_key="testing"
            )
            # result() blocks. To resolve api futures asynchronously, use add_done_callback().
            message_id = api_future.result()
            message_metadata = MessageMetadata.decode(message_id)
            print(
                f"Published {data} to partition {message_metadata.partition.value} and offset {message_metadata.cursor.offset}."
            )

    print(
        f"Finished publishing {num_messages} messages with an ordering key to {str(topic_path)}."
    )
    # [END pubsublite_publish_ordering_key]

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    parser.add_argument("project_number", help="Your Google Cloud Project Number")
    parser.add_argument("cloud_region", help="Your Cloud Region, e.g. 'us-central1'")
    parser.add_argument("zone_id", help="Your Zone ID, e.g. 'a'")
    parser.add_argument("topic_id", help="Your topic ID")
    parser.add_argument("num_messages", type=int, help="Number of messages to publish")
    parser.add_argument("regional", help="True if using a regional resource else zonal")

    args = parser.parse_args()

    publish_with_odering_key(
        args.project_number,
        args.cloud_region,
        args.zone_id,
        args.topic_id,
        args.num_messages,
        args.regional,
    )


text:
package domain;

//me conviene tener un paquete con exceptions ?
public class InvalidPasswordException extends Exception {

	public InvalidPasswordException(String msg)
	{
		super(msg);
	}

	public InvalidPasswordException()
	{
		super();
	}

}


text:
#include <aws/chime/model/License.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>

using namespace Aws::Utils;

namespace Aws
{
  namespace Chime
  {
    namespace Model
    {
      namespace LicenseMapper
      {

        static const int Basic_HASH = HashingUtils::HashString("Basic");
        static const int Plus_HASH = HashingUtils::HashString("Plus");
        static const int Pro_HASH = HashingUtils::HashString("Pro");
        static const int ProTrial_HASH = HashingUtils::HashString("ProTrial");

        License GetLicenseForName(const Aws::String& name)
        {
          int hashCode = HashingUtils::HashString(name.c_str());
          if (hashCode == Basic_HASH)
          {
            return License::Basic;
          }
          else if (hashCode == Plus_HASH)
          {
            return License::Plus;
          }
          else if (hashCode == Pro_HASH)
          {
            return License::Pro;
          }
          else if (hashCode == ProTrial_HASH)
          {
            return License::ProTrial;
          }
          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
          if(overflowContainer)
          {
            overflowContainer->StoreOverflow(hashCode, name);
            return static_cast<License>(hashCode);
          }

          return License::NOT_SET;
        }

        Aws::String GetNameForLicense(License enumValue)
        {
          switch(enumValue)
          {
          case License::Basic:
            return "Basic";
          case License::Plus:
            return "Plus";
          case License::Pro:
            return "Pro";
          case License::ProTrial:
            return "ProTrial";
          default:
            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
            if(overflowContainer)
            {
              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
            }

            return "";
          }
        }

      } // namespace LicenseMapper
    } // namespace Model
  } // namespace Chime
} // namespace Aws


text:
                        Add Shipping Line

                    <form role="form" name="form" novalidate>

                            Shipping Line No.

                                <input type="text" class="form-control" name="no" ng-model="shippingline.no" required>
                                {{form.no.message}}

                            Shipping Line Name

                                <input type="text" class="form-control" name="name" ng-model="shippingline.name" required>
                                {{form.name.message}}

                            Shipping Line Address

                                <textarea class="form-control" name="address" ng-model="shippingline.address" required></textarea>
                                {{form.address.message}}

                            Telephone no.

                                <input type="text" class="form-control" name="tel" ng-model="shippingline.tel" required>
                                {{form.tel.message}}

                            Contact Person

                                <input type="text" class="form-control" name="contact" ng-model="shippingline.contact">

                            Email Address

                                <input type="text" class="form-control" name="email" ng-model="shippingline.email">

                                    Valid From

                                             <input type="text" name="valid_from" class="form-control" ng-model="shippingline.valid_from" data-max-date="{{shippingline.valid_to}}" placeholder="From" bs-datepicker required>

                                        {{form.valid_from.message}}

                                    Valid To

                                            <input type="text" name="valid_to" class="form-control" ng-model="shippingline.valid_to" data-min-date="{{shippingline.valid_from}}" placeholder="To" bs-datepicker required>

                                        {{form.valid_to.message}}

                            Remarks

                                <textarea class="form-control" name="address" ng-model="shippingline.remarks"></textarea>

                            <button ng-click="submit(form)" class="btn btn-primary">Add</button>
                            <button ng-click="clear()" class="btn">Clear</button>

                    </form>


text:
package br.com.markuscandido.myapp.servico;

/**
 *
 * @author markus.candido
 *
 */
public class MatematicaMaluca {

	public int contaMaluca(int numero) {
        if(numero > 30) return numero * 4;
        else if(numero > 10) return numero * 3;
        else return numero * 2;
    }

}


text:
using System;
using System.IO;

namespace cstsd
{
    public static class FileHelpers
    {
        /// <summary>
        /// Returns true if the path is a dir, false if it's a file and null if it's neither or doesn't exist.
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static bool? IsDirFile(string path)
        {
            if (!Directory.Exists(path) && !File.Exists(path)) return null;
            var fileAttr = File.GetAttributes(path);
            return !fileAttr.HasFlag(FileAttributes.Directory);
        }

        public static void ScanRecursive(string rootDir, Action<string> fileAction)
        {
            //recurse dirs too
            var dirs = Directory.GetDirectories(rootDir);
            foreach (var d in dirs)
            {
                ScanRecursive(d, fileAction);
            }

            ScanStandard(rootDir, fileAction);
        }

        public static void ScanStandard(string rootDir, Action<string> fileAction)
        {
            var files = Directory.GetFiles(rootDir);

            foreach (var file in files)
            {
                fileAction(file);
            }
        }
    }

}


text:
package com.hotfixs.thinkinginjava.common;

import java.lang.reflect.Array;

/**
 * @author wangjunwei
 */
public class Generated {
    public static <T> T[] array(T[] a, Generator<T> gen) {
        return new CollectionData<>(gen, a.length).toArray(a);
    }

    @SuppressWarnings("unchecked")
    public static <T> T[] array(Class<T> type, Generator<T> gen, int quality) {
        T[] array = (T[]) Array.newInstance(type, quality);
        return new CollectionData<>(gen, quality).toArray(array);
    }
}


text:
@interface BottomDecorativeCurve_OC : UIView

- (id)initWithMainInfoViewFrame:(CGRect)frame andBottomDecorativeViewSize:(CGSize)size;

- (void)refreshAnimation;

@end


text:
openworld
=========

OpenWorld Modeling Framework

# Introduction

OpenWorld is a framework to make modeling simple and reliable, while
leaving control in the hands of the developers.  It is built upon the
OpenDims dimension framework (https://github.com/jrising/opendims),
providing a basis for unit checking throughout the system.

## Components

The elements of OpenWorld can be selectively used, based on the kind
of model being built.  Although there are a number of
cross-dependencies, the broad components are as follows.

* `datastr`: Objects for resolution-invariant numerical modeling.
  These allow one to define, for example, a `TemporalGeographicMap`
  describing a spatiotemporal precipitation field, and then perform
  mathematical operations on the entire field, and compute results
  that combine it with another `TemporalGeographicMap` at a different
  resolution.

* `multi`: A Bayesian model coupling system, which allows (1) models
  to be coupled without recalibration of the component models, (2)
  multiple models to simultaneously inform a single variable, and (3)
  models describing different scales to couple across the scales.

* `sysdyn`: A framework for system dynamics, which allows the entire
  model to be described in equations, and producing variables which
  themselves have dependencies with the other variables in the system.

* `memory`: Tools for serialization and memory management.

* `model`: Tools for nonlinear optimization of model parameters, using
  (amongst other methods) genetic algorithms.

# Examples:

## HydroNet

The most advanced example of a model using the `datastr` framework is
the `hydronet`, a physically-based, high-resolution hydrological
model.  It is available at https://github.com/jrising/hydronet

## SolowModel

A simple example of the system dynamics framework, through the famous
Solow growth model.  However, this model has not been updated since
the C# version of OpenWorld.  See
https://github.com/jrising/openworld/tree/master/examples/sample/SolowModel.cpp

## Environmental Conflict model

The canonical example of the model coupling framework is the
environmental conflict example, in
https://github.com/jrising/openworld/tree/master/examples/coupling.
It includes validation of the method and cross-scale coupling.


text:
import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
import { resource } from '../../actions'

//headline basic structure
export const Headline = ({user,dispatch}) => {
    let status;
    return(

{user.name}

{user.headline}

        <input className="inputmsg2" type="text"ref={(node)=>status = node}/>

        <input id="changeHl" className="btn" type="submit"
        value="Change Headline" onClick={(event) =>
                {event.preventDefault();
                changeHeadline(status, dispatch)}
                }/>

)
}
//change the headline
const changeHeadline=(status,dispatch)=>{
   if(status.value != '') {
        resource('PUT', 'headline', { headline: status.value })
        .then((response) => {
            dispatch({type: 'UPDATE_HEADLINE', username: response.username, headline: response.headline})
        })
        status.value = ''
    }
}
//check the type
Headline.propTypes = {
    user: PropTypes.object.isRequired
}

export default connect(
    (state) => {
        return {
            user: state.user
        }
    },null
)(Headline)


text:
package com.netsteadfast.greenstep.base.sys;

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

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;

import com.netsteadfast.greenstep.base.Constants;
import com.netsteadfast.greenstep.base.model.AccountObj;
import com.netsteadfast.greenstep.util.SimpleUtils;

public class WebSystemHttpSessionListener implements HttpSessionListener, HttpSessionAttributeListener {
	protected Logger log=Logger.getLogger(WebSystemHttpSessionListener.class);
	private static final Map<String, HttpSession> sessionsMap=new HashMap<String, HttpSession>();
	private static Properties props = new Properties();
	private static String invalidateSameAccountSession="Y";
	private IUSessLogHelper uSessLogHelper;

	static {
		try {
			props.load(WebSystemHttpSessionListener.class.getClassLoader().getResource("META-INF/webSystemHttpSessionListener.properties").openStream());
			invalidateSameAccountSession=SimpleUtils.getStr(props.getProperty("INVALIDATE_SAME_ACCOUNT_SESSION"), "Y");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public WebSystemHttpSessionListener() {
		super();
		uSessLogHelper=new USessLogHelperImpl();
	}

	// -----------------------------------------------------------------------------------

	@Override
	public void sessionCreated(HttpSessionEvent event) {
		try {
			sessionsMap.put(event.getSession().getId(), event.getSession());
			if (this.uSessLogHelper.count(event.getSession().getId())>0) {
				this.uSessLogHelper.delete(event.getSession().getId());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent event) {
		try {
			sessionsMap.remove(event.getSession().getId());
			if (this.uSessLogHelper.count(event.getSession().getId())>0) {
				this.uSessLogHelper.delete(event.getSession().getId());
				SecurityUtils.getSubject().logout();
				log.info(Constants.getSystem() + " sessionDestroyed: " + event.getSession().getId() + " and do SecurityUtils.getSubject().logout().... ");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// -----------------------------------------------------------------------------------

	@Override
	public void attributeAdded(HttpSessionBindingEvent event) {
		try {
			this.cleanBeforeLoginUser(event);
			this.writeLoginUser(event);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void attributeRemoved(HttpSessionBindingEvent event) {
		try {
			this.clearLoginUser(event);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void attributeReplaced(HttpSessionBindingEvent event) {
		/*
		try {
			this.updateLoginUser(event);
		} catch (Exception e) {
			e.printStackTrace();
		}
		*/
	}

	/**
	 * 清除之前已有相同帳戶登入的 sessionId 紀錄
	 *
	 * @param arg0
	 * @throws Exception
	 */
	private void cleanBeforeLoginUser(HttpSessionBindingEvent event) throws Exception {
		if (!"Y".equals(invalidateSameAccountSession)) {
			return;
		}
		String name=event.getName();
		Object value=event.getValue();
		if (Constants.SESS_ACCOUNT.equals(name)) {
			String account=((AccountObj)value).getAccount();
			List<String> sessionIdList=uSessLogHelper.findSessionIdByAccount(account);
			for (int ix=0; sessionIdList!=null && ix<sessionIdList.size(); ix++) {
				String sessId=sessionIdList.get(ix);
				HttpSession beforeUserHttpSession=sessionsMap.get(sessId);
				beforeUserHttpSession.invalidate();
				sessionsMap.remove(sessId);
				//uSessLogHelper.delete(sessId); invalidate 時 sessionDestroyed 有做刪除紀錄的功能
				log.warn("invalidate before session:"+sessId + " account:"+account);
			}
		}
	}

	private void writeLoginUser(HttpSessionBindingEvent event) throws Exception {
		String sessionId=event.getSession().getId();
		String name=event.getName();
		Object value=event.getValue();
		if (Constants.SESS_ACCOUNT.equals(name)) {
			if (uSessLogHelper.count(sessionId)>0) {
				uSessLogHelper.delete(sessionId);
			}
			uSessLogHelper.insert(sessionId, ((AccountObj)value).getAccount());
		}
	}

	private void clearLoginUser(HttpSessionBindingEvent event) throws Exception {
		String sessionId=event.getSession().getId();
		String name=event.getName();
		if (Constants.SESS_ACCOUNT.equals(name)) {
			if (uSessLogHelper.count(sessionId)>0) {
				uSessLogHelper.delete(sessionId);
			}
		}
	}

	// -----------------------------------------------------------------------------------

}


text:
package day7;

import org.junit.Test;

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

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

/**
 * Created by JoseLlorens on 08/12/2016.
 */
public class Day07SolverTest {

  @Test
  public void should_check_if_ABBA(){
    Day07Solver solver = new Day07Solver();
    assertThat(solver.isABBA("abba"),is(true));
    assertThat(solver.isABBA("abcd"),is(false));
    assertThat(solver.isABBA("bddb"),is(true));
    assertThat(solver.isABBA("ioxxoj"),is(true));
    assertThat(solver.isABBA("swzexdrctfvygbhunijm"),is(false));
  }

  @Test
  public void should_parse_input(){
    Day07Solver solver = new Day07Solver();
    solver.parseInput("abba[mnop]qrst[fghdgf]adsasd[dgfyh]ghfgh");
  }

  @Test
  public void should_solve_part1() throws IOException {
    Day07Solver solver = new Day07Solver();
    System.out.println(solver.solvePart1());
  }

  @Test
  public void should_solve_part2() throws IOException {
    Day07Solver solver = new Day07Solver();
    System.out.println(solver.solvePart2());
  }

  @Test
  public void should_get_abas(){
    Day07Solver solver = new Day07Solver();

    List<String> list = new ArrayList<>();
    list.add("aba");
    list.add("xyz");
    list.add("aaa");
    list.add("asdhufiui");
    list.add("adaiuytre");

    solver.getABAs(list);
  }

}