text:
#ifndef BMX_WAVE_WRITER_H_
#define BMX_WAVE_WRITER_H_

#include <vector>
#include <deque>

#include <bmx/ByteArray.h>
#include <bmx/wave/WaveIO.h>
#include <bmx/wave/WaveBEXT.h>
#include <bmx/wave/WaveTrackWriter.h>

namespace bmx
{

class WaveWriter
{
public:
    friend class WaveTrackWriter;

public:
    WaveWriter(WaveIO *output, bool take_ownership);
    ~WaveWriter();

    void SetStartTimecode(Timecode start_timecode);     // sets time_reference in bext
    WaveBEXT* GetBroadcastAudioExtension() { return mBEXT; }

public:
    WaveTrackWriter* CreateTrack();

public:
    void PrepareWrite();
    void WriteSamples(uint32_t track_index, const unsigned char *data, uint32_t size, uint32_t num_samples);
    void CompleteWrite();

public:
    Rational GetSamplingRate() const    { return mSamplingRate; }
    int64_t GetDuration() const         { return mSampleCount; }

    uint32_t GetNumTracks() const       { return (uint32_t)mTracks.size(); }
    WaveTrackWriter* GetTrack(uint32_t track_index);

private:
    void SetSamplingRate(Rational sampling_rate);
    void SetQuantizationBits(uint16_t bits);

private:
    WaveIO *mOutput;
    bool mOwnOutput;
    Timecode mStartTimecode;
    bool mStartTimecodeSet;
    WaveBEXT *mBEXT;

    Rational mSamplingRate;
    bool mSamplingRateSet;
    uint16_t mQuantizationBits;
    bool mQuantizationBitsSet;
    uint16_t mChannelCount;
    uint16_t mChannelBlockAlign;
    uint16_t mBlockAlign;

    std::vector<WaveTrackWriter*> mTracks;

    typedef struct
    {
        ByteArray data;
        int64_t start_sample_count;
        uint32_t num_samples;
        uint16_t channel_count;
    } BufferSegment;

    std::deque<BufferSegment*> mBufferSegments;
    uint32_t mBufferSize;
    int64_t mSampleCount;

    int64_t mJunkChunkFilePosition;
    int64_t mBEXTFilePosition;
    int64_t mDataChunkFilePosition;
    int64_t mFactChunkFilePosition;
};

};

#endif


text:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;

using Khronos;

// ReSharper disable CheckNamespace
// ReSharper disable InconsistentNaming
// ReSharper disable JoinDeclarationAndInitializer

namespace OpenGL
{
	public partial class Gl
	{
		/// <summary>
		/// [GL] glExtGetShadersQCOM: Binding for glExtGetShadersQCOM.
		/// </summary>
		/// <param name="shaders">
		/// A <see cref="T:uint[]"/>.
		/// </param>
		/// <param name="numShaders">
		/// A <see cref="T:int[]"/>.
		/// </param>
		[RequiredByFeature("GL_QCOM_extended_get2", Api = "gles1|gles2")]
		public static void ExtGetShadersQCOM(uint[] shaders, int[] numShaders)
		{
			Debug.Assert(numShaders.Length >= 1);
			unsafe {
				fixed (uint* p_shaders = shaders)
				fixed (int* p_numShaders = numShaders)
				{
					Debug.Assert(Delegates.pglExtGetShadersQCOM != null, "pglExtGetShadersQCOM not implemented");
					Delegates.pglExtGetShadersQCOM(p_shaders, shaders.Length, p_numShaders);
					LogCommand("glExtGetShadersQCOM", null, shaders, shaders.Length, numShaders					);
				}
			}
			DebugCheckErrors(null);
		}

		/// <summary>
		/// [GL] glExtGetProgramsQCOM: Binding for glExtGetProgramsQCOM.
		/// </summary>
		/// <param name="programs">
		/// A <see cref="T:uint[]"/>.
		/// </param>
		/// <param name="numPrograms">
		/// A <see cref="T:int[]"/>.
		/// </param>
		[RequiredByFeature("GL_QCOM_extended_get2", Api = "gles1|gles2")]
		public static void ExtGetProgramsQCOM(uint[] programs, int[] numPrograms)
		{
			Debug.Assert(numPrograms.Length >= 1);
			unsafe {
				fixed (uint* p_programs = programs)
				fixed (int* p_numPrograms = numPrograms)
				{
					Debug.Assert(Delegates.pglExtGetProgramsQCOM != null, "pglExtGetProgramsQCOM not implemented");
					Delegates.pglExtGetProgramsQCOM(p_programs, programs.Length, p_numPrograms);
					LogCommand("glExtGetProgramsQCOM", null, programs, programs.Length, numPrograms					);
				}
			}
			DebugCheckErrors(null);
		}

		/// <summary>
		/// [GL] glExtIsProgramBinaryQCOM: Binding for glExtIsProgramBinaryQCOM.
		/// </summary>
		/// <param name="program">
		/// A <see cref="T:uint"/>.
		/// </param>
		[RequiredByFeature("GL_QCOM_extended_get2", Api = "gles1|gles2")]
		public static bool ExtIsProgramBinaryQCOM(uint program)
		{
			bool retValue;

			Debug.Assert(Delegates.pglExtIsProgramBinaryQCOM != null, "pglExtIsProgramBinaryQCOM not implemented");
			retValue = Delegates.pglExtIsProgramBinaryQCOM(program);
			LogCommand("glExtIsProgramBinaryQCOM", retValue, program			);
			DebugCheckErrors(retValue);

			return (retValue);
		}

		/// <summary>
		/// [GL] glExtGetProgramBinarySourceQCOM: Binding for glExtGetProgramBinarySourceQCOM.
		/// </summary>
		/// <param name="program">
		/// A <see cref="T:uint"/>.
		/// </param>
		/// <param name="shadertype">
		/// A <see cref="T:ShaderType"/>.
		/// </param>
		/// <param name="source">
		/// A <see cref="T:string"/>.
		/// </param>
		/// <param name="length">
		/// A <see cref="T:int[]"/>.
		/// </param>
		[RequiredByFeature("GL_QCOM_extended_get2", Api = "gles1|gles2")]
		public static void ExtGetProgramBinarySourceQCOM(uint program, ShaderType shadertype, string source, int[] length)
		{
			unsafe {
				fixed (int* p_length = length)
				{
					Debug.Assert(Delegates.pglExtGetProgramBinarySourceQCOM != null, "pglExtGetProgramBinarySourceQCOM not implemented");
					Delegates.pglExtGetProgramBinarySourceQCOM(program, (int)shadertype, source, p_length);
					LogCommand("glExtGetProgramBinarySourceQCOM", null, program, shadertype, source, length					);
				}
			}
			DebugCheckErrors(null);
		}

		internal static unsafe partial class Delegates
		{
			[RequiredByFeature("GL_QCOM_extended_get2", Api = "gles1|gles2")]
			[SuppressUnmanagedCodeSecurity]
			internal delegate void glExtGetShadersQCOM(uint* shaders, int maxShaders, int* numShaders);

			[RequiredByFeature("GL_QCOM_extended_get2", Api = "gles1|gles2")]
			[ThreadStatic]
			internal static glExtGetShadersQCOM pglExtGetShadersQCOM;

			[RequiredByFeature("GL_QCOM_extended_get2", Api = "gles1|gles2")]
			[SuppressUnmanagedCodeSecurity]
			internal delegate void glExtGetProgramsQCOM(uint* programs, int maxPrograms, int* numPrograms);

			[RequiredByFeature("GL_QCOM_extended_get2", Api = "gles1|gles2")]
			[ThreadStatic]
			internal static glExtGetProgramsQCOM pglExtGetProgramsQCOM;

			[RequiredByFeature("GL_QCOM_extended_get2", Api = "gles1|gles2")]
			[SuppressUnmanagedCodeSecurity]
			[return: MarshalAs(UnmanagedType.I1)]
			internal delegate bool glExtIsProgramBinaryQCOM(uint program);

			[RequiredByFeature("GL_QCOM_extended_get2", Api = "gles1|gles2")]
			[ThreadStatic]
			internal static glExtIsProgramBinaryQCOM pglExtIsProgramBinaryQCOM;

			[RequiredByFeature("GL_QCOM_extended_get2", Api = "gles1|gles2")]
			[SuppressUnmanagedCodeSecurity]
			internal delegate void glExtGetProgramBinarySourceQCOM(uint program, int shadertype, string source, int* length);

			[RequiredByFeature("GL_QCOM_extended_get2", Api = "gles1|gles2")]
			[ThreadStatic]
			internal static glExtGetProgramBinarySourceQCOM pglExtGetProgramBinarySourceQCOM;

		}
	}

}

redpajama_set_name: RedPajamaGithub


text:
module Y2017.M02.D27.Solution where

import Data.List (subsequences)
import Data.Ratio (numerator)

-- below imports available via 1HaskellADay git repository

import Analytics.Math.Combinatorics (choose)
import Control.List (takeout)

{--
So, I'm eyeing http://rosalind.info/problems/lcsq/ which is a problem to find
the largest common subsequence of two 'strings' (lists of n elements). The
problem is not the problem, however, the problem is that Data.List.subsequences
has

1) the combinatorial-explosion problem:

>>> subsequences [1,2,3]
[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]

and 2) I'm looking for longest first, not last.

If only there were a function where I could throttle the results returned by
subsequences and give longest firstest, or, in other words: gives subsequences
of length x in a controlled fashion.

Today's Haskell problem.

Given [a] and a length n (where we hope n is less than list length) return all
subsequences of length n of [a].
--}

subseq :: Int -> [a] -> [[a]]

-- hint: one, or more, of the above imports MAY be helpful here, also you may
-- wish to constrain the type of a? Not sure about that, however.

-- nah. If we put [a] into an array, we can then choose on the indices, or
-- we can just drop the unwanted elements and skip the whole array-translation
-- thing

subseq n = flip (ssq n) [] . length <*> id

ssq :: Int -> Int -> [a] -> [a] -> [[a]]
ssq 0 _ ans _            = return (reverse ans)
ssq n m acc list | n > m = []   -- no more elements to draw from, so we fail out
                 | n < 0 = []   -- and this is just weird, so quit
                 | otherwise = [0 .. m]                >>= \d ->
                               shift acc (drop d list) >>=
                               uncurry (ssq (pred n) (m - d - 1))

shift :: [a] -> [a] -> [([a], [a])]
shift acc (h:t) = return (h:acc, t)
shift acc []    = []  -- no shift occurred, so we fail out.

{--
What are the subsequences of length 2 for the list [1,2,3]?

>>> subseq 2 [1,2,3]
[[1,2],[1,3],[2,3]]

What are the subsequences of length 6 of the String "AACCTTGG"?

>>> subseq 6 "AACCTTGG"
["AACCTT","AACCTG","AACCTG","AACCTG","AACCTG","AACCGG","AACTTG","AACTTG",
 "AACTGG","AACTGG","AACTTG","AACTTG","AACTGG","AACTGG","AATTGG","ACCTTG",
 "ACCTTG","ACCTGG","ACCTGG","ACTTGG","ACTTGG","ACCTTG","ACCTTG","ACCTGG",
 "ACCTGG","ACTTGG","ACTTGG","CCTTGG"]

>>> length (subseq 6 "AACCTTGG")
28

-- Note the redundancies!

>>> Set.fromList (subseq 6 "AACCTTGG")
fromList ["AACCGG","AACCTG","AACCTT","AACTGG","AACTTG","AATTGG","ACCTGG",
          "ACCTTG","ACTTGG","CCTTGG"]

>> length (Set.fromList (subseq 6 "AACCTTGG"))
10
--}

{-- BONUS -----------------------------------------------------------------

A silver bullet?

So, now that we have a 'faster' subsequencing algorithm, can we just waltz to
solving the rosalind-problem?

Hm.

Fake question: what are the subsequences of (subseq 49 [1..75])?
(don't do this at home, kids!)

Unfake question, or, put another way: what is the value of 75 `choose` 49?
--}

alotta :: Integer
alotta = numerator (75 `choose` 49) -- we ... 'know' the demoninator is 1

{--
>>> alotta
101131821425286333900

Hm. So just making a more effient subseq algorithm doesn't make the 'bigness' of
the rosalind-problem go away. We'll look at another approach tomorrow.
--}


text:
module Pakyow
  module Markdown
    VERSION = "2.0.1".freeze
  end
end


text:
//-CRE-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Glass.Mapper.Sc.Integration
{
    public class Class1
    {
    }
}


text:
package ro.dcsi.internship;

import java.util.Set;
import java.util.UUID;
import com.google.common.base.Preconditions;
import com.opencsv.bean.CsvBindByName;

public class User {
  public static String generateUserId() {
    return UUID.randomUUID().toString();
  }

  @CsvBindByName
  public final String id;
  @CsvBindByName
  public final String username;
  @CsvBindByName
  public final String email;
  @CsvBindByName
  public final String firstname;
  @CsvBindByName
  public final String lastname;

  /**
   * @CsvBindByName public final String passwd;
   * @CsvBindByName(required = false) public final String fullname; public final int permissions;
   *                         public final int age; private Set<String> permisions;
   **/

  // TODO Don't remove it. It's used by opencsv via reflection.
  public User() {
    this("<cannot happen: no name-private-constructor>");
  }

  public User(String name) {
    this(name, "", "", "<no-email>");
  }
  //
  // public User(String username, String firstname, String lastname, String email) {
  // this(generateUserId(), username, "", firstname, lastname, "", 0, 0, email);
  // }
  // //
  // public User(String id, String username, String passwd, String firstname, String lastname,
  // String fullname,
  // int permissions, int age, String email) {
  // this.username = username;
  // this.passwd = passwd;
  // this.fullname = fullname;
  // this.firstname = firstname;
  // this.lastname = lastname;
  // this.permissions = permissions;
  // this.age = age;
  // this.id = id;
  // this.email = email;
  // Preconditions.checkNotNull(id);
  // }

  public User(String username, String email) {
    this(username, email, "NoFirstName", "NoLastName");
  }

  public User(String username, String email, String firstname, String lastname) {
    this.id = generateUserId();
    this.username = username;
    this.email = email;
    this.firstname = firstname;
    this.lastname = lastname;
    if (username.contains("\n"))
      throw new RuntimeException(
          "A username shouldn't contain End Of Lines. The username was [" + username + "]");
  }
  // @Override
  // public String toString() {
  // return "User("+username+"<"+email+">)";
  // }

  public String toString() {
    return "TheUser{" + "username='" + username + ", id='" + id + '\'' + ", email='" + email + '\''
        + ", firstname='" + firstname + '\'' + ", lastname='" + lastname + '\'' + '}';
  }

  /** A cleaned up username that can be used by forgerock. */
  // TODO remove a violation of SRP
  public String idFromUsenameForForgeRock() {
    String reg = "[\\\\ \",]";
    return username.replaceAll(reg, "-");
  }

  public String getUsername() {
    return username;
  }
  /*
   * public String getPasswd() { return passwd; }
   *
   * public String getFullname() { return fullname; }
   *
   * public int getPermissions() { return permissions; }
   *
   * public int getAge() { return age; }
   */

  public String getId() {
    return id;
  }

  public String getEmail() {
    return email;
  }

  public String getFirstname() {
    return firstname;
  }

  public String getLastname() {
    return lastname;
  }
}


text:
package com.amazon.ion.util;

import static com.amazon.ion.SystemSymbols.IMPORTS;
import static com.amazon.ion.SystemSymbols.ION_1_0_SID;
import static com.amazon.ion.SystemSymbols.ION_SYMBOL_TABLE;
import static com.amazon.ion.SystemSymbols.SYMBOLS;

import com.amazon.ion.Decimal;
import com.amazon.ion.IonBlob;
import com.amazon.ion.IonBool;
import com.amazon.ion.IonClob;
import com.amazon.ion.IonDatagram;
import com.amazon.ion.IonDecimal;
import com.amazon.ion.IonFloat;
import com.amazon.ion.IonInt;
import com.amazon.ion.IonList;
import com.amazon.ion.IonNull;
import com.amazon.ion.IonReader;
import com.amazon.ion.IonSequence;
import com.amazon.ion.IonSexp;
import com.amazon.ion.IonString;
import com.amazon.ion.IonStruct;
import com.amazon.ion.IonSymbol;
import com.amazon.ion.IonTimestamp;
import com.amazon.ion.IonType;
import com.amazon.ion.IonValue;
import com.amazon.ion.IonWriter;
import com.amazon.ion.SymbolTable;
import com.amazon.ion.SymbolToken;
import com.amazon.ion.Timestamp;
import com.amazon.ion.impl._Private_IonSymbol;
import com.amazon.ion.impl._Private_IonSystem;
import com.amazon.ion.impl._Private_IonTextWriterBuilder;
import com.amazon.ion.impl._Private_IonValue;
import com.amazon.ion.impl._Private_IonValue.SymbolTableProvider;
import com.amazon.ion.system.IonTextWriterBuilder;
import com.amazon.ion.system.IonTextWriterBuilder.LstMinimizing;
import com.amazon.ion.system.IonWriterBuilder.IvmMinimizing;
import com.amazon.ion.util.IonTextUtils.SymbolVariant;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.util.Iterator;

/**
 * Renders {@link IonValue}s to text.
 *

 * By default, output is in a compact format with minimal whitespace.
 * For example:
 *

 *    annot::{f1:["hello","goodbye"],'another field':long::0}
 *

 * The format can be tuned through various properties on the Printer instance,
 * as well as through the {@link Printer.Options} structure.
 *

 * Instances of this class are safe for use by multiple threads.
 *

 * While printers are inexpensive to create, their configuration facilities
 * make them useful as shared resources. Changes to configuration settings
 * (e.g., {@link #setJsonMode()}) do not affect concurrently-running
 * calls to {@link #print}.
 *
 * @see IonWriter
 * @see IonTextWriterBuilder
 */
public class Printer
{
    public class Options
        implements Cloneable
    {
        public boolean blobAsString;
        public boolean clobAsString;
        public boolean datagramAsList;
        public boolean decimalAsFloat;
        public boolean sexpAsList;
        public boolean skipAnnotations;
        public boolean skipSystemValues;
        public boolean simplifySystemValues;
        public boolean stringAsJson;
        public boolean symbolAsString;
        public boolean timestampAsString;
        public boolean timestampAsMillis;
        public boolean untypedNulls;

        @Override
        public Options clone()
        {
            try
            {
                return (Options) super.clone();
            }
            catch (CloneNotSupportedException e)
            {
                throw new InternalError();
            }
        }
    }

    protected Options myOptions = new Options();

    public Printer()
    {
        myOptions = new Options();
    }

    public Printer(Options options)
    {
        myOptions = options.clone();
    }

    //=========================================================================
    // Options

    /* Potential printing options:
     *
     * - Render all times with a specific offset (what about unknowns?)
     * - Render all times with long offset (no Z)
     * - control over decimal-point placement in float and decimal.
     *   (render 12.00 or 1200d-2)
     */

    /**
     * Indicates whether this printer skips (i.e., doesn't print)
     * system IDs and local symbol tables.
     * By default, this property is false.
     */
    public synchronized boolean getSkipSystemValues()
    {
        return myOptions.skipSystemValues;
    }

    /**
     * Sets whether this printer skips (i.e., doesn't print)
     * system IDs and local symbol tables.
     * By default, this property is false.
     */
    public synchronized void setSkipSystemValues(boolean skip)
    {
        myOptions.skipSystemValues = skip;
    }

    /**
     * Indicates whether this printer skips (i.e., doesn't print)
     * annotations.
     * By default, this property is false.
     */
    public synchronized boolean getSkipAnnotations()
    {
        return myOptions.skipAnnotations;
    }

    /**
     * Sets whether this printer skips (i.e., doesn't print)
     * annotations.
     * By default, this property is false.
     */
    public synchronized void setSkipAnnotations(boolean skip)
    {
        myOptions.skipAnnotations = skip;
    }

    /**
     * Indicates whether this printer renders blobs as Base64 strings.
     * By default, this is false.
     */
    public synchronized boolean getPrintBlobAsString()
    {
        return myOptions.blobAsString;
    }

    /**
     * Sets whether this printer renders blobs as Base64 strings.
     * By default, this is false.
     */
    public synchronized void setPrintBlobAsString(boolean blobAsString)
    {
        myOptions.blobAsString = blobAsString;
    }

    /**
     * Indicates whether this printer renders clobs as ASCII strings.
     * By default, this is false.
     */
    public synchronized boolean getPrintClobAsString()
    {
        return myOptions.clobAsString;
    }

    /**
     * Sets whether this printer renders clobs as ASCII strings.
     * By default, this is false.
     */
    public synchronized void setPrintClobAsString(boolean clobAsString)
    {
        myOptions.clobAsString = clobAsString;
    }

    /**
     * Indicates whether this printer renders datagrams as lists.
     * By default, this property is false.
     */
    public synchronized boolean getPrintDatagramAsList()
    {
        return myOptions.datagramAsList;
    }

    /**
     * Sets whether this printer renders datagrams as lists.
     * By default, this property is false.
     */
    public synchronized void setPrintDatagramAsList(boolean datagramAsList)
    {
        myOptions.datagramAsList = datagramAsList;
    }

    /**
     * Indicates whether this printer renders decimals as floats, thus using 'e'
     * notation for all real values.
     * By default, this is false.
     */
    public synchronized boolean getPrintDecimalAsFloat()
    {
        return myOptions.decimalAsFloat;
    }

    /**
     * Sets whether this printer renders decimals as floats, thus using 'e'
     * notation for all real values.
     * By default, this is false.
     */
    public synchronized void setPrintDecimalAsFloat(boolean decimalAsFloat)
    {
        myOptions.decimalAsFloat = decimalAsFloat;
    }

    /**
     * Indicates whether this printer renders sexps as lists.
     * By default, this is false.
     */
    public synchronized boolean getPrintSexpAsList()
    {
        return myOptions.sexpAsList;
    }

    /**
     * Sets whether this printer renders sexps as lists.
     * By default, this is false.
     */
    public synchronized void setPrintSexpAsList(boolean sexpAsList)
    {
        myOptions.sexpAsList = sexpAsList;
    }

    /**
     * Indicates whether this printer renders strings using JSON escapes.
     * By default, this is false.
     */
    public synchronized boolean getPrintStringAsJson()
    {
        return myOptions.stringAsJson;
    }

    /**
     * Sets whether this printer renders strings using JSON escapes.
     * By default, this is false.
     */
    public synchronized void setPrintStringAsJson(boolean stringAsJson)
    {
        myOptions.stringAsJson = stringAsJson;
    }

    /**
     * Indicates whether this printer renders symbols as strings.
     * By default, this is false.
     */
    public synchronized boolean getPrintSymbolAsString()
    {
        return myOptions.symbolAsString;
    }

    /**
     * Sets whether this printer renders symbols as strings.
     * By default, this is false.
     */
    public synchronized void setPrintSymbolAsString(boolean symbolAsString)
    {
        myOptions.symbolAsString = symbolAsString;
    }

    /**
     * Indicates whether this printer renders timestamps as millisecond values.
     * By default, this is false.
     */
    public synchronized boolean getPrintTimestampAsMillis()
    {
        return myOptions.timestampAsMillis;
    }

    /**
     * Sets whether this printer renders timestamps as millisecond values.
     * By default, this is false.
     */
    public synchronized void setPrintTimestampAsMillis(boolean timestampAsMillis)
    {
        myOptions.timestampAsMillis = timestampAsMillis;
    }

    /**
     * Indicates whether this printer renders timestamps as strings.
     * By default, this is false.
     */
    public synchronized boolean getPrintTimestampAsString()
    {
        return myOptions.timestampAsString;
    }

    /**
     * Sets whether this printer renders timestamps as strings.
     * By default, this is false.
     */
    public synchronized void setPrintTimestampAsString(boolean timestampAsString)
    {
        myOptions.timestampAsString = timestampAsString;
    }

    /**
     * Indicates whether this printer renders all null values as {@code null}
     * (i.e., the same as an {@link IonNull}).
     * By default, this is false.
     */
    public synchronized boolean getPrintUntypedNulls()
    {
        return myOptions.untypedNulls;
    }

    /**
     * Sets whether this printer renders all null values as {@code null}
     * (i.e., the same as an {@link IonNull}).
     * By default, this is false.
     */
    public synchronized void setPrintUntypedNulls(boolean untypedNulls)
    {
        myOptions.untypedNulls = untypedNulls;
    }

    /**
     * Configures this printer's options to render legal JSON text.
     * The following options are modified so that:
     *

     *
{@link Options#blobAsString} is {@code true}

     *
{@link Options#clobAsString} is {@code true}

     *
{@link Options#datagramAsList} is {@code true}

     *
{@link Options#decimalAsFloat} is {@code true}

     *
{@link Options#sexpAsList} is {@code true}

     *
{@link Options#skipAnnotations} is {@code true}

     *
{@link Options#skipSystemValues} is {@code true}

     *
{@link Options#stringAsJson} is {@code true}

     *
{@link Options#symbolAsString} is {@code true}

     *
{@link Options#timestampAsString} is {@code false}

     *
{@link Options#timestampAsMillis} is {@code true}

     *
{@link Options#untypedNulls} is {@code true}

     *

     * All other options are left as is.
     */
    public synchronized void setJsonMode()
    {
        myOptions.blobAsString      = true;
        myOptions.clobAsString      = true;
        myOptions.datagramAsList    = true;
        myOptions.decimalAsFloat    = true;
        myOptions.sexpAsList        = true;
        myOptions.skipAnnotations   = true;
        myOptions.skipSystemValues  = true;
        myOptions.stringAsJson      = true;
        myOptions.symbolAsString    = true;
        myOptions.timestampAsString = false;
        myOptions.timestampAsMillis = true;
        myOptions.untypedNulls      = true;
    }

    //=========================================================================
    // Print methods

    public void print(IonValue value, Appendable out)
        throws IOException
    {
        // Copy the options so visitor won't see changes made while printing.
        Options options;
        synchronized (this)  // So we don't clone in the midst of changes
        {
            options = myOptions.clone();
        }

        if (true)
        {
            _print(value, makeVisitor(options, out));
        }
        else
        {
            // Bridge to the configurable text writer. This is here for
            // testing purposes. It *almost* works except for printing
            // datagram as list.

            boolean dg = value instanceof IonDatagram;

            _Private_IonTextWriterBuilder o =
                _Private_IonTextWriterBuilder.standard();
            o.setCharset(IonTextWriterBuilder.ASCII);
            if (dg)
            {
                if (options.skipSystemValues)
                {
                    o.withMinimalSystemData();
                }
                else if (options.simplifySystemValues) {

                    o.setIvmMinimizing(IvmMinimizing.DISTANT);
                    o.setLstMinimizing(LstMinimizing.LOCALS);
                }
            }

            o._blob_as_string      = options.blobAsString;
            o._clob_as_string      = options.clobAsString;
            o._decimal_as_float    = options.decimalAsFloat;
            // TODO datagram as list
            o._sexp_as_list        = options.sexpAsList;
            o._skip_annotations    = options.skipAnnotations;
            o._string_as_json      = options.stringAsJson;
            o._symbol_as_string    = options.symbolAsString;
            o._timestamp_as_millis = options.timestampAsMillis;
            o._timestamp_as_string = options.timestampAsString;
            o._untyped_nulls       = options.untypedNulls;

            IonWriter writer = o.build(out);
            // TODO doesn't work for datagram since it skips system values
            // value.writeTo(writer);
            _Private_IonSystem system = (_Private_IonSystem) value.getSystem();
            IonReader reader = system.newSystemReader(value);
            writer.writeValues(reader);
            writer.finish();
        }
    }

    private void _print(IonValue value, PrinterVisitor pv)
        throws IOException
    {
        try
        {
            if (! (value instanceof IonDatagram))
            {
                pv.setSymbolTableProvider(new BasicSymbolTableProvider(value.getSymbolTable()));
            }
            value.accept(pv);
        }
        catch (IOException e)
        {
            throw e;
        }
        catch (RuntimeException e)
        {
            throw e;
        }
        catch (Exception e)
        {
            // Shouldn't happen.
            throw new RuntimeException(e);
        }
    }

    /**
     * Subclasses can override this if they wish to construct a specialization
     * of the {@link PrinterVisitor}.
     *
     * @param options is a fresh copy of the Printer's options instance,
     * not null.
     * @param out is not null.
     * @return the visitor to invoke for printing.
     */
    protected PrinterVisitor makeVisitor(Options options, Appendable out)
    {
        return new PrinterVisitor(options, out);
    }

    private static class BasicSymbolTableProvider
        implements SymbolTableProvider
    {
        private final SymbolTable symbolTable;

        public BasicSymbolTableProvider(SymbolTable symbolTable)
        {
            this.symbolTable = symbolTable;
        }

        public SymbolTable getSymbolTable()
        {
            return symbolTable;
        }

    }

    //=========================================================================
    // Print methods

    public static class PrinterVisitor
        extends AbstractValueVisitor
    {

        final protected Options    myOptions;
        final protected Appendable myOut;

        /**
         * Should we quote operators at the current level of the hierarchy?
         * As we recurse down into containers, this value is pushed on the
         * stack by {@link #writeChild(IonValue, boolean)}.
         */
        private boolean    myQuoteOperators = true;

        private SymbolTableProvider mySymbolTableProvider = null;

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

        public PrinterVisitor(Options options, Appendable out)
        {
            myOptions = options;
            myOut = out;
        }

        void setSymbolTableProvider(SymbolTableProvider symbolTableProvider)
        {
            mySymbolTableProvider = symbolTableProvider;
        }

        /**
         * Recurse down into a container, we push the current value of
         * {@link #myQuoteOperators} onto the stack and replace it with
         * the given value.
         *
         * @param value
         * @param quoteOperators replaces the current value of
         * {@link #myQuoteOperators} during the recursive visitation.
         * @throws Exception propagated from visitation of value.
         * @throws NullPointerException if value is null.
         */
        protected void writeChild(IonValue value, boolean quoteOperators)
            throws Exception
        {
            boolean oldQuoteOperators = myQuoteOperators;
            myQuoteOperators = quoteOperators;
            value.accept(this);
            myQuoteOperators = oldQuoteOperators;
        }

        public void writeAnnotations(IonValue value) throws IOException
        {
            if (! myOptions.skipAnnotations)
            {
                SymbolToken[] anns = ((_Private_IonValue)value).getTypeAnnotationSymbols(mySymbolTableProvider);
                if (anns != null)
                {
                    for (SymbolToken ann : anns) {
                        String text = ann.getText();
                        if (text == null) {
                            myOut.append('$');
                            myOut.append(Integer.toString(ann.getSid()));
                        }
                        else {
                            IonTextUtils.printSymbol(myOut, text);
                        }
                        myOut.append("::");
                    }
                }
            }
        }

        public void writeNull(String type) throws IOException
        {
            if (myOptions.untypedNulls)
            {
                myOut.append("null");
            }
            else
            {
                myOut.append("null.");
                myOut.append(type);
            }
        }

        public void writeSequenceContent(IonSequence value,
                                         boolean quoteOperators,
                                         char open,
                                         char separator,
                                         char close)
            throws IOException, Exception
        {
            myOut.append(open);

            boolean hitOne = false;
            for (IonValue child : value)
            {
                if (hitOne)
                {
                    myOut.append(separator);
                }
                hitOne = true;

                writeChild(child, quoteOperators);
            }

            myOut.append(close);
        }

        public void writeSymbolToken(SymbolToken sym) throws IOException
        {
            String text = sym.getText();
            if (text != null)
            {
                writeSymbol(text);
            }
            else
            {
                int sid = sym.getSid();
                if (sid < 0)
                {
                    throw new IllegalArgumentException("Bad SID " + sid);
                }

                text = "$" + sym.getSid();
                if (myOptions.symbolAsString)
                {
                    writeString(text);
                }
                else
                {
                    myOut.append(text);  // SID literal is never quoted
                }
            }
        }

        public void writeSymbol(String text) throws IOException
        {
            if (myOptions.symbolAsString)
            {
                writeString(text);
            }
            else
            {
                SymbolVariant variant = IonTextUtils.symbolVariant(text);
                switch (variant)
                {
                    case IDENTIFIER:
                        myOut.append(text);
                        break;
                    case OPERATOR:
                        if (! myQuoteOperators)
                        {
                            myOut.append(text);
                            break;
                        }
                        // else fall through...
                    case QUOTED:
                        IonTextUtils.printQuotedSymbol(myOut, text);
                        break;
                }
            }
        }

        /**
         * @param text may be null
         */
        public void writeString(String text) throws IOException
        {
            if (myOptions.stringAsJson)
            {
                IonTextUtils.printJsonString(myOut, text);
            }
            else
            {
                IonTextUtils.printString(myOut, text);
            }
        }

        //---------------------------------------------------------------------
        // AbstractValueVisitor overrides

        @Override
        protected void defaultVisit(IonValue value)
        {
            String message = "cannot print " + value.getClass().getName();
            throw new UnsupportedOperationException(message);
        }

        @Override
        public void visit(IonBlob value) throws IOException
        {
            writeAnnotations(value);

            if (value.isNullValue())
            {
                writeNull("blob");
            }
            else
            {
                myOut.append(myOptions.blobAsString ? "\"" : "{{");
                value.printBase64(myOut);
                myOut.append(myOptions.blobAsString ? "\"" : "}}");
            }
        }

        @Override
        public void visit(IonBool value)
            throws IOException
        {
            writeAnnotations(value);

            if (value.isNullValue())
            {
                writeNull("bool");
            }
            else
            {
                myOut.append(value.booleanValue() ? "true" : "false");
            }
        }

        @Override
        public void visit(IonClob value) throws IOException
        {
            writeAnnotations(value);

            if (value.isNullValue())
            {
                writeNull("clob");
            }
            else
            {
                if (! myOptions.clobAsString)
                {
                    myOut.append("{{");
                }
                myOut.append('"');

                InputStream byteStream = value.newInputStream();
                try
                {
                    int c;
                    // if-statement hoisted above loop for efficiency
                    if (myOptions.stringAsJson)
                    {
                        while ((c = byteStream.read()) != -1)
                        {
                            IonTextUtils.printJsonCodePoint(myOut, c);
                        }
                    }
                    else
                    {
                        while ((c = byteStream.read()) != -1)
                        {
                            IonTextUtils.printStringCodePoint(myOut, c);
                        }
                    }
                }
                finally
                {
                    byteStream.close();
                }

                myOut.append('"');
                if (! myOptions.clobAsString)
                {
                    myOut.append("}}");
                }
            }
        }

        @Override
        public void visit(IonDatagram value) throws IOException, Exception
        {
            Iterator<IonValue> i = (myOptions.skipSystemValues
                                       ? value.iterator()
                                       : value.systemIterator());

            final boolean asList = myOptions.datagramAsList;
            if (asList)
            {
                myOut.append('[');
            }

            boolean hitOne = false;

            // If we're skipping system values at the iterator level,
            // we don't need to bother trying to simplify them.
            final boolean simplify_system_values =
                myOptions.simplifySystemValues && ! myOptions.skipSystemValues;

            SymbolTable previous_symbols = null;

            while (i.hasNext())
            {
                IonValue child = i.next();
                SymbolTable childSymbolTable = child.getSymbolTable();
                mySymbolTableProvider = new BasicSymbolTableProvider(childSymbolTable); //children of datagrams are top-level values
                if (simplify_system_values)
                {
                    child = simplify(child, previous_symbols);
                    previous_symbols = childSymbolTable;
                }

                if (child != null)
                {
                    if (hitOne)
                    {
                        myOut.append(asList  ?  ','  :  ' ');
                    }
                    writeChild(child, true);
                    hitOne = true; // we've only "hit one" if we wrote it
                }
            }

            if (asList)
            {
                myOut.append(']');
            }
        }

        private final IonValue simplify(IonValue child,
                                        SymbolTable previous_symbols)
        {
            IonType t = child.getType();
            switch (t) {
            case STRUCT:
                if (child.hasTypeAnnotation(ION_SYMBOL_TABLE)) {
                    if (symbol_table_struct_has_imports(child))
                    {
                        return ((IonStruct)child).cloneAndRemove(SYMBOLS);
                    }
                    return null;
                }
                // fall through to default (print the value)
                break;
            case SYMBOL:
                if (((IonSymbol)child).getSymbolId() == ION_1_0_SID) {
                    if (previous_symbols != null && previous_symbols.isSystemTable()) {
                        return null;
                    }
                    // fall through to default (print the value)
                }
                // fall through to default (print the value)
                break;
            default:
                break;
            }
            return child;
        }

        static final private boolean symbol_table_struct_has_imports(IonValue child) {
            IonStruct struct = (IonStruct)child;
            IonValue imports = struct.get(IMPORTS);
            if (imports instanceof IonList) {
                return ((IonList)imports).size() != 0;
            }
            return false;
        }

        @Override
        public void visit(IonDecimal value) throws IOException
        {
            writeAnnotations(value);

            if (value.isNullValue())
            {
                writeNull("decimal");
            }
            else
            {
                Decimal decimal = value.decimalValue();
                BigInteger unscaled = decimal.unscaledValue();

                int signum = decimal.signum();
                if (signum < 0)
                {
                    myOut.append('-');
                    unscaled = unscaled.negate();
                }
                else if (signum == 0 && decimal.isNegativeZero())
                {
                    // for the various forms of negative zero we have to
                    // write the sign ourselves, since neither BigInteger
                    // nor BigDecimal recognize negative zero, but Ion does.
                    myOut.append('-');
                }

                final String unscaledText = unscaled.toString();
                final int significantDigits = unscaledText.length();

                final int scale = decimal.scale();
                final int exponent = -scale;

                if (myOptions.decimalAsFloat)
                {
                    myOut.append(unscaledText);
                    myOut.append('e');
                    myOut.append(Integer.toString(exponent));
                }
                else if (exponent == 0)
                {
                    myOut.append(unscaledText);
                    myOut.append('.');
                }
                else if (0 < scale)
                {
                    int wholeDigits;
                    int remainingScale;
                    if (significantDigits > scale)
                    {
                        wholeDigits = significantDigits - scale;
                        remainingScale = 0;
                    }
                    else
                    {
                        wholeDigits = 1;
                        remainingScale = scale - significantDigits + 1;
                    }

                    myOut.append(unscaledText, 0, wholeDigits);
                    if (wholeDigits < significantDigits)
                    {
                        myOut.append('.');
                        myOut.append(unscaledText, wholeDigits,
                                     significantDigits);
                    }

                    if (remainingScale != 0)
                    {
                        myOut.append("d-");
                        myOut.append(Integer.toString(remainingScale));
                    }
                }
                else // (exponent > 0)
                {
                    // We cannot move the decimal point to the right, adding
                    // rightmost zeros, because that would alter the precision.
                    myOut.append(unscaledText);
                    myOut.append('d');
                    myOut.append(Integer.toString(exponent));
                }
            }
        }

        @Override
        public void visit(IonFloat value) throws IOException
        {
            writeAnnotations(value);

            if (value.isNullValue())
            {
                writeNull("float");
            }
            else
            {
                double real = value.doubleValue();
                IonTextUtils.printFloat(myOut, real);
            }
        }

        @Override
        public void visit(IonInt value) throws IOException
        {
            writeAnnotations(value);

            if (value.isNullValue())
            {
                writeNull("int");
            }
            else
            {
                myOut.append(value.bigIntegerValue().toString(10));
            }
        }

        @Override
        public void visit(IonList value) throws IOException, Exception
        {
            writeAnnotations(value);

            if (value.isNullValue())
            {
                writeNull("list");
            }
            else
            {
                writeSequenceContent(value, true, '[', ',', ']');
            }
        }

        @Override
        public void visit(IonNull value) throws IOException
        {
            writeAnnotations(value);
            myOut.append("null");
        }

        @Override
        public void visit(IonSexp value) throws IOException, Exception
        {
            writeAnnotations(value);

            if (value.isNullValue())
            {
                writeNull("sexp");
            }
            else if (myOptions.sexpAsList)
            {
                writeSequenceContent(value, true, '[', ',', ']');
            }
            else
            {
                writeSequenceContent(value, false, '(', ' ', ')');
            }
        }

        @Override
        public void visit(IonString value) throws IOException
        {
            writeAnnotations(value);

            if (value.isNullValue())
            {
                writeNull("string");
            }
            else
            {
                writeString(value.stringValue());
            }
        }

        @Override
        public void visit(IonStruct value) throws IOException, Exception
        {
            writeAnnotations(value);

            if (value.isNullValue())
            {
                writeNull("struct");
            }
            else
            {
                myOut.append('{');

                boolean hitOne = false;
                for (IonValue child : value)
                {
                    if (hitOne)
                    {
                        myOut.append(',');
                    }
                    hitOne = true;

                    SymbolToken sym = ((_Private_IonValue)child).getFieldNameSymbol(mySymbolTableProvider);
                    writeSymbolToken(sym);
                    myOut.append(':');
                    writeChild(child, true);
                }
                myOut.append('}');
            }
        }

        @Override
        public void visit(IonSymbol value) throws IOException
        {
            writeAnnotations(value);

            SymbolToken is = ((_Private_IonSymbol)value).symbolValue(mySymbolTableProvider);
            if (is == null)
            {
                writeNull("symbol");
            }
            else
            {
                writeSymbolToken(is);
            }
        }

        @Override
        public void visit(IonTimestamp value) throws IOException
        {
            writeAnnotations(value);

            if (value.isNullValue())
            {
                writeNull("timestamp");
            }
            else if (myOptions.timestampAsMillis)
            {
                myOut.append(Long.toString(value.getMillis()));
            }
            else
            {
                Timestamp ts = value.timestampValue();

                if (myOptions.timestampAsString)
                {
                    myOut.append('"');
                    ts.print(myOut);
                    myOut.append('"');
                }
                else
                {
                    ts.print(myOut);
                }
            }
        }
    }
}


text:
bunnicula
=========

Command-line tool for setting up new vhost apps

## Usage

Expects three parameters: name of the project, git repo url, and the domain name for the application.

For example:
    bunnicula.rb foo git@github.com:example/foo.git foo.example.com

Would setup a new virtual host for foo.example.com pointing to code checked out from git@github.com:example/foo.git into /var/www/foo

Run it as sudo.

## Dependencies

* Ubuntu
* Apache
* Ruby
* Git
* Mysql
* User named 'git' that has access to the repo url you give the script
* Mysql user named 'drupal'

## License

Distributed under the MIT License, the same as Rails.


text:
..
      Licensed under the Apache License, Version 2.0 (the "License"); you may
      not use this file except in compliance with the License. You may obtain
      a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

      Unless required by applicable law or agreed to in writing, software
      distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
      WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
      License for the specific language governing permissions and limitations
      under the License.

==============
Test Strategy
==============

A key part of the "four opens" is ensuring the OpenStack delivers well-tested
and usable software. For more details see:
http://docs.openstack.org/project-team-guide/introduction.html#the-four-opens

Experience has shown that untested features are frequently broken, in part
due to the velocity of upstream changes. As we aim to ensure we keep all
features working across upgrades, we must aim to test all features.

Reporting Test Coverage
=======================

For details on plans to report the current test coverage, refer to
:doc:`/user/feature-classification`.

Running tests and reporting results
===================================

Voting in Gerrit
----------------

On every review in gerrit, check tests are run on very patch set, and are
able to report a +1 or -1 vote.
For more details, please see:
http://docs.openstack.org/infra/manual/developers.html#automated-testing

Before merging any code, there is an integrate gate test queue, to ensure
master is always passing all tests.
For more details, please see:
http://docs.openstack.org/infra/zuul/gating.html

Infra vs Third-Party
--------------------

Tests that use fully open source components are generally run by the
OpenStack Infra teams. Test setups that use non-open technology must
be run outside of that infrastructure, but should still report their
results upstream.

For more details, please see:
http://docs.openstack.org/infra/system-config/third_party.html

Ad-hoc testing
--------------

It is particularly common for people to run ad-hoc tests on each released
milestone, such as RC1, to stop regressions.
While these efforts can help stabilize the release, as a community we have a
much stronger preference for continuous integration testing. Partly this is
because we encourage users to deploy master, and we generally have to assume
that any upstream commit may already been deployed in production.

Types of tests
==============

Unit tests
----------

Unit tests help document and enforce the contract for each component.
Without good unit test coverage it is hard to continue to quickly evolve the
codebase.
The correct level of unit test coverage is very subjective, and as such we are
not aiming for a particular percentage of coverage, rather we are aiming for
good coverage.
Generally, every code change should have a related unit test:
http://docs.openstack.org/developer/hacking/#creating-unit-tests

Integration tests
-----------------

Today, our integration tests involve running the Tempest test suite on a
variety of Nova deployment scenarios.

In addition, we have third parties running the tests on their preferred Nova
deployment scenario.

Functional tests
----------------

Nova has a set of in-tree functional tests that focus on things that are out
of scope for tempest testing and unit testing.
Tempest tests run against a full live OpenStack deployment, generally deployed
using devstack. At the other extreme, unit tests typically use mock to test a
unit of code in isolation.
Functional tests don't run an entire stack, they are isolated to nova code,
and have no reliance on external services. They do have a WSGI app, nova
services and a database, with minimal stubbing of nova internals.

Interoperability tests
-----------------------

The DefCore committee maintains a list that contains a subset of Tempest tests.
These are used to verify if a particular Nova deployment's API responds as
expected. For more details, see: https://github.com/openstack/defcore


text:
require "spec_helper"

describe Snippr::Snip do

  describe "initializer" do

    before do
      Snippr::Path.path = 'path'
    end

    context "without I18n" do

      before do
        Snippr::I18n.enabled = false
      end

      it "calls #after_initialize" do
        expect_any_instance_of(Snippr::Snip).to receive(:after_initialize).once
        Snippr::Snip.new(:path_to_snips, :file)
      end

      it "initializes name, path and opts without opts" do
        snip = Snippr::Snip.new(:path_to_snips, :file)
        expect(snip.name).to eq('pathToSnips/file')
        expect(snip.path).to eq('path/pathToSnips/file.snip')
        expect(snip.opts).to eq({})
      end

      it "initializes name, path and opts with opts" do
        snip = Snippr::Snip.new(:path_to_snips, :file, :key => :value)
        expect(snip.name).to eq('pathToSnips/file')
        expect(snip.path).to eq('path/pathToSnips/file.snip')
        expect(snip.opts).to eq({:key => :value})
      end

      it "initializes name, path and opts with given extension" do
        snip = Snippr::Snip.new(:path_to_snips, :file, :extension => :yml)
        expect(snip.name).to eq("pathToSnips/file")
        expect(snip.path).to eq("path/pathToSnips/file.yml")
        expect(snip.opts).to eq({ :extension => :yml })
      end

      it "initializes name, path and opts with given i18n deactivation" do
        snip = Snippr::Snip.new(:path_to_snips, :file, :i18n => true)
        expect(snip.name).to eq("pathToSnips/file_#{::I18n.locale}")
        expect(snip.path).to eq("path/pathToSnips/file_#{::I18n.locale}.snip")
        expect(snip.opts).to eq({ :i18n => true })
      end

      it "returns no double slashes in the path for nil value" do
        snip = Snippr::Snip.new(:path_to_snips, nil ,:file)
        expect(snip.name).to eq('pathToSnips/file')
        expect(snip.path).to eq('path/pathToSnips/file.snip')
      end

      it "returns no double slahes in the path for empty string value" do
        snip = Snippr::Snip.new(:path_to_snips, "" ,:file)
        expect(snip.name).to eq('pathToSnips/file')
        expect(snip.path).to eq('path/pathToSnips/file.snip')
      end

    end

    context "with I18n" do

      before do
        Snippr::I18n.enabled = true
      end

      it "initializes name, path and opts without opts" do
        snip = Snippr::Snip.new(:path_to_snips, :file)
        expect(snip.name).to eq("pathToSnips/file_#{::I18n.locale}")
        expect(snip.path).to eq("path/pathToSnips/file_#{::I18n.locale}.snip")
        expect(snip.opts).to eq({})
      end

      it "initializes name, path and opts with opts" do
        snip = Snippr::Snip.new(:path_to_snips, :file, :key => :value)
        expect(snip.name).to eq("pathToSnips/file_#{::I18n.locale}")
        expect(snip.path).to eq("path/pathToSnips/file_#{::I18n.locale}.snip")
        expect(snip.opts).to eq({:key => :value})
      end

      it "initializes name, path and opts with given extension" do
        snip = Snippr::Snip.new(:path_to_snips, :file, :extension => :yml)
        expect(snip.name).to eq("pathToSnips/file_#{::I18n.locale}")
        expect(snip.path).to eq("path/pathToSnips/file_#{::I18n.locale}.yml")
        expect(snip.opts).to eq({ :extension => :yml })
      end

      it "initializes name, path and opts with given i18n deactivation" do
        snip = Snippr::Snip.new(:path_to_snips, :file, :i18n => false)
        expect(snip.name).to eq("pathToSnips/file")
        expect(snip.path).to eq("path/pathToSnips/file.snip")
        expect(snip.opts).to eq({ :i18n => false })
      end
    end

  end

  describe "#unprocessed_content" do

    it "reads an existing snip" do
      expect(Snippr::Snip.new(:home).unprocessed_content).to eq('
Home
')
    end

    it "stores the read data instead of reading it again" do
      expect(File).to receive(:read).once.and_return('data')
      snip = Snippr::Snip.new(:home)
      expect(snip.unprocessed_content).to eq('data')
      expect(snip.unprocessed_content).to eq('data')
    end

    it "returns an empty string on missing snips" do
      expect(File).to receive(:read).never
      expect(Snippr::Snip.new(:doesnotexist).unprocessed_content).to eq('')
    end

    it "strips the read content" do
      expect(Snippr::Snip.new(:empty).unprocessed_content).to eq('')
    end

  end

  describe "content" do

    it "calls Snippr::Processor.process with opts and return decorated result" do
      expect(Snippr::Processor).to receive(:process).with('
Home
', {:a => :b}, anything()).and_return('processed')
      expect(Snippr::Snip.new(:home, :a => :b).content).to eq("\nprocessed\n")
    end

    it "stores the processed data instead of processing it again" do
      expect(Snippr::Processor).to receive(:process).with('
Home
', {:a => :b}, anything()).once.and_return('processed')
      snip = Snippr::Snip.new(:home, :a => :b)
      expect(snip.content).to eq("\nprocessed\n")
      expect(snip.content).to eq("\nprocessed\n")
    end

    it "doesn't call Snippr::Processor.process and return missing string" do
      expect(Snippr::Processor).to receive(:process).never
      expect(Snippr::Snip.new(:doesnotexist, :a => :b).content).to eq('')
    end

    it "removes the _include key from the metadata" do
      snip = Snippr::Snip.new(:include, :main)
      expect(snip.meta).to_not have_key("_include")
    end
  end

  describe "#missing?" do

    it "returns true when the snip isn't there" do
      expect(Snippr::Snip.new(:doesnotexist)).to be_missing
    end

    it "returns false when the snip is there but empty" do
      expect(Snippr::Snip.new(:empty)).not_to be_missing
    end

    it "returns false when the snip is there and has content" do
      expect(Snippr::Snip.new(:home)).not_to be_missing
    end

  end

  describe "#empty?" do

    it "returns true when the snip isn't there" do
      expect(Snippr::Snip.new(:doesnotexist)).to be_empty
    end

    it "returns false when the snip is there but empty" do
      expect(Snippr::Snip.new(:empty)).to be_empty
    end

    it "returns false when the snip is there and has content" do
      expect(Snippr::Snip.new(:home)).not_to be_empty
    end

  end

  describe '#meta' do
    it 'returns metadata from valid segment' do
      expect(Snippr::Snip.new(:meta, :with_content_and_segmentfilter).meta).to eq({'description' => 'neues meta'})
    end

    it 'initializes meta with empty hash' do
      expect(Snippr::Snip.new(:meta, :missing_snippet).meta).to eq({})
    end
  end

end


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

<TITLE>
com.martiansoftware.jsap.examples (JSAP: the Java Simple Argument Parser)
</TITLE>

<META NAME="keywords" CONTENT="com.martiansoftware.jsap.examples package">

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

com.martiansoftware.jsap.examples

Classes

Example1

Manual_HelloWorld_1

Manual_HelloWorld_2

Manual_HelloWorld_3

Manual_HelloWorld_4

Manual_HelloWorld_5

Manual_HelloWorld_6

Manual_HelloWorld_7

Manual_HelloWorld_8

Manual_HelloWorld_9

Manual_HelloWorld_Simple


text:
/**
  @file         date_entity.h
  @brief        retains a month and a day.
  @author       HRYKY
  @version      $Id: date_entity.h 337 2014-03-23 14:12:33Z hryky.private@gmail.com $
 */
#ifndef DATE_ENTITY_H_20121230142904270
#define DATE_ENTITY_H_20121230142904270
#include "hryky/date/date_common.h"
#include "hryky/date/date_month_common.h"
#include "hryky/date/date_week_common.h"
#include "hryky/pragma.h"
#include "hryky/with_stream_out.h"
#include "hryky/with_swap.h"
//------------------------------------------------------------------------------
// disables warnings
//------------------------------------------------------------------------------
#pragma hryky_pragma_push_warning
#pragma hryky_pragma_disable_warning_padded
//------------------------------------------------------------------------------
// defines macros
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// declares types
//------------------------------------------------------------------------------
namespace hryky
{
namespace date
{
	/// retains a month and a day.
	class Entity;

} // namespace date

typedef date::Entity date_type;

} // namespace hryky
//------------------------------------------------------------------------------
// declares classes
//------------------------------------------------------------------------------
/**
  @brief retains a month and a day.
 */
class hryky::date::Entity :
	public WithStreamOut<Entity>,
	public WithSwap<Entity>
{
public :

	typedef Entity this_type;

	/// default constructor.
	Entity();

	/// copy constructor.
	Entity(this_type const &);

	/// move constructor.
	Entity(this_type && rhs);

	/// destructor.
	~Entity();

	/// assignment operator.
	hryky_assign_op;

	/// move assignment operator.
	hryky_move_assign_op;

	/// releases the internal resources.
	void clear();

	/// decomposes the instance to primitive objects.
	template <typename StreamT>
	StreamT & write_to(StreamT & out) const;

	/// interchanges the each internal resources of two instances.
	void swap(this_type & src);

	/// retrieves the year of this date.
	year_type const & year() const;

	/// retrieves the month of this date.
	month_type const & month() const;

	/// retrieves the day of this date.
	day_type const & day() const;

	/// retrieves the weekday of this date.
	week_type const & week() const;

	/// retrieves the hour of this date.
	hour_type const & hour() const;

	/// retrieves the minute of this date.
	minute_type const & minute() const;

	/// retrieves the second of this date.
	second_type const & second() const;

	/// assigns a new year to this date.
	void year(year_type const src);

	/// assign a new month to this date.
	void month(month_type::raw_type const src);

	/// assign a new day to this date.
	void day(day_type const src);

	/// assigns a new weekday to this date.
	void week(week_type::raw_type const src);

	/// assigns a new hour to this date.
	void hour(hour_type const src);

	/// assigns a new minute to this date.
	void minute(minute_type const src);

	/// assigns a new second to this date.
	void second(second_type const src);

	/// assigns a new time from an arbitrary type.
	template <typename ValueT>
	void time(ValueT const & value);

protected :

private :

	year_type   year_;
	month_type  month_;
	day_type    day_;
	week_type   week_;
	hour_type   hour_;
	minute_type minute_;
	second_type second_;

};
//------------------------------------------------------------------------------
// specializes classes
//------------------------------------------------------------------------------
namespace hryky
{
namespace date
{
} // namespace date
} // namespace hryky
//------------------------------------------------------------------------------
// defines public member functions
//------------------------------------------------------------------------------
/**
  @brief assigns a new time from an arbitrary type.
 */
template <typename ValueT>
void hryky::date::Entity::time(ValueT const & value)
{
	this->hour(value.hour());
	this->minute(value.minute());
	this->second(value.second());
}
/**
  @brief decomposes the instance to primitive objects.
 */
template <typename StreamT>
StreamT &
hryky::date::Entity::write_to(
	StreamT & out) const
{
	stream::map::Scope<StreamT> const map(out);

	hryky_write_member(year);
	hryky_write_member(month);
	hryky_write_member(day);
	hryky_write_member(week);
	hryky_write_member(hour);
	hryky_write_member(minute);
	hryky_write_member(second);

	return out;
}
//------------------------------------------------------------------------------
// defines protected member functions
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// defines private member functions
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// declares global functions
//------------------------------------------------------------------------------
namespace hryky
{
namespace date
{
} // namespace date
} // namespace hryky
//------------------------------------------------------------------------------
// defines global functions
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// restores the warnings
//------------------------------------------------------------------------------
#pragma hryky_pragma_pop_warning
#endif // DATE_ENTITY_H_20121230142904270
// end of file


text:
namespace ToysStore.Data
{
    using System;
    using System.Collections.Generic;

    public partial class Toy
    {
        public Toy()
        {
            this.Categories = new HashSet<Category>();
        }

        public int Id { get; set; }
        public string Name { get; set; }
        public string Type { get; set; }
        public int ManufacturerId { get; set; }
        public decimal Price { get; set; }
        public string Color { get; set; }
        public int AgeRangeId { get; set; }

        public virtual AgeRanx AgeRanx { get; set; }
        public virtual Manufacturer Manufacturer { get; set; }
        public virtual ICollection<Category> Categories { get; set; }
    }
}


text:
package org.opencv.ml;

// C++: class Boost
//javadoc: Boost
public class Boost extends DTrees {

    protected Boost(long addr) {
        super(addr);
    }

    public static final int
            DISCRETE = 0,
            REAL = 1,
            LOGIT = 2,
            GENTLE = 3;

    //
    // C++: static Ptr_Boost create()
    //

    //javadoc: Boost::create()
    public static Boost create() {

        Boost retVal = new Boost(create_0());

        return retVal;
    }

    //
    // C++:  double getWeightTrimRate()
    //

    //javadoc: Boost::getWeightTrimRate()
    public double getWeightTrimRate() {

        double retVal = getWeightTrimRate_0(nativeObj);

        return retVal;
    }

    //
    // C++:  int getBoostType()
    //

    //javadoc: Boost::getBoostType()
    public int getBoostType() {

        int retVal = getBoostType_0(nativeObj);

        return retVal;
    }

    //
    // C++:  int getWeakCount()
    //

    //javadoc: Boost::getWeakCount()
    public int getWeakCount() {

        int retVal = getWeakCount_0(nativeObj);

        return retVal;
    }

    //
    // C++:  void setBoostType(int val)
    //

    //javadoc: Boost::setBoostType(val)
    public void setBoostType(int val) {

        setBoostType_0(nativeObj, val);

        return;
    }

    //
    // C++:  void setWeakCount(int val)
    //

    //javadoc: Boost::setWeakCount(val)
    public void setWeakCount(int val) {

        setWeakCount_0(nativeObj, val);

        return;
    }

    //
    // C++:  void setWeightTrimRate(double val)
    //

    //javadoc: Boost::setWeightTrimRate(val)
    public void setWeightTrimRate(double val) {

        setWeightTrimRate_0(nativeObj, val);

        return;
    }

    @Override
    protected void finalize() throws Throwable {
        delete(nativeObj);
    }

    // C++: static Ptr_Boost create()
    private static native long create_0();

    // C++:  double getWeightTrimRate()
    private static native double getWeightTrimRate_0(long nativeObj);

    // C++:  int getBoostType()
    private static native int getBoostType_0(long nativeObj);

    // C++:  int getWeakCount()
    private static native int getWeakCount_0(long nativeObj);

    // C++:  void setBoostType(int val)
    private static native void setBoostType_0(long nativeObj, int val);

    // C++:  void setWeakCount(int val)
    private static native void setWeakCount_0(long nativeObj, int val);

    // C++:  void setWeightTrimRate(double val)
    private static native void setWeightTrimRate_0(long nativeObj, double val);

    // native support for java finalize()
    private static native void delete(long nativeObj);

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, recorder!</string>
    <string name="app_name">Android-Recorder</string>
</resources>


text:
<!doctype html>
<meta name=description content="Non-stop back-to-back music videos from the 1980s"><title>1980s MTV</title>

34
MTV


text:
import os
import sys
import time
from time import sleep
from selenium import webdriver

appium_Url = 'http://appium.testdroid.com/wd/hub';

##
## IMPORTANT: Set the following parameters.
##
screenshotDir= "/absolute/path/to/desired/directory"
testdroid_username = "username@example.com"
testdroid_password = "p4s$w0rd"
testdroid_device = "Dell Venue 7 3730" # Example device. Change if you desire.

def log(msg):
    print (time.strftime("%H:%M:%S") + ": " + msg)

screenShotCount = 1
def screenshot(name):
    global screenShotCount
    screenshotName = str(screenShotCount) + "_" + name + ".png"
    log ("Taking screenshot: " + screenshotName)
    sleep(1) # wait for animations to complete before taking screenshot
    driver.save_screenshot(screenshotDir + "/" + screenshotName)
    screenShotCount += 1

desired_capabilities_cloud = {}
desired_capabilities_cloud['testdroid_username'] = testdroid_username
desired_capabilities_cloud['testdroid_password'] = testdroid_password
desired_capabilities_cloud['testdroid_target'] = 'chrome'
desired_capabilities_cloud['testdroid_project'] = 'Appium Android Hybrid Demo'
desired_capabilities_cloud['testdroid_testrun'] = 'TestRun 1'
desired_capabilities_cloud['testdroid_device'] = testdroid_device
desired_capabilities_cloud['testdroid_app'] = 'sample/testdroid-sample.apk'
desired_capabilities_cloud['platformName'] = 'Android'
desired_capabilities_cloud['deviceName'] = 'Android Phone'
desired_capabilities_cloud['automationName'] = 'selendroid'
desired_capabilities_cloud['appPackage'] = 'com.testdroid.sample.android'
desired_capabilities_cloud['appActivity'] = '.MA_MainActivity'

desired_caps = desired_capabilities_cloud;

log ("Will save screenshots at: " + screenshotDir)

# set up webdriver
log ("WebDriver request initiated. Waiting for response, this typically takes 2-3 mins")
driver = webdriver.Remote(appium_Url, desired_caps)
log ("WebDriver response received")

log ("Activity-1")
log ("  Getting device screen size")
print driver.get_window_size()

screenshot("appLaunch")

log('clicking button "hybrid app"')
element=driver.find_element_by_id('com.testdroid.sample.android:id/mm_b_hybrid')
element.click()
screenshot('hybridActivity')

log('Typing in the Url')
element=driver.find_element_by_id('com.testdroid.sample.android:id/hy_et_url')
element.send_keys("http://testdroid.com")
screenshot('urlTyped')

log('hiding keyboard')
driver.back()
screenshot('keyboardHidden')

log('clicking Load url button')
element=driver.find_element_by_id('com.testdroid.sample.android:id/hy_ib_loadUrl')
element.click()
log('waiting 10 seconds for url to load completely')
sleep(10)
screenshot('webPageLoaded')

log('finding window handles')
handles = driver.window_handles
for handle in driver.window_handles:
    log("   > Window: " + handle)

log('switching to webview')
webview = handles[1]
driver.switch_to_window(webview)

log ("Clicking 'Products'")
elem = driver.find_element_by_xpath('//*[@id="menu"]/ul/li[1]/a')
elem.click()
sleep(5)
screenshot('webview_products')

log ("Clicking 'Learn More'")
elem = driver.find_element_by_xpath('//*[@id="products"]/div[1]/div/div[1]/div[3]/a')
elem.click()
sleep(5)
screenshot('webview_learnmore')

log ("Clicking 'Supported Frameworks'")
elem = driver.find_element_by_xpath('//*[@id="topBox"]/div[1]/div/a[2]')
elem.click()
sleep(5)
screenshot('webview_supportedframeworks')

log('finding window handles')
handles = driver.window_handles
for handle in driver.window_handles:
    log("   > Window: " + handle)

log('switching back to native app')
nativeapp = handles[0]
driver.switch_to_window(nativeapp)

log('goint back')
driver.back()
screenshot('launchScreen')

sys.exit()


text:
//
//  Copyright (c) 2012 Parse. All rights reserved.

#import "LoginViewController.h"
#import "HomeViewController.h"
#import "Parse/Parse.h"

@implementation LoginViewController

@synthesize activityIndicator;

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.navigationController.navigationBarHidden = YES;
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"splashlogin.background.png"]];
    [self setTitle:@""];

    // Check if user is cached and linked to Facebook, if so, bypass login
    if ([PFUser currentUser] && [PFFacebookUtils isLinkedWithUser:[PFUser currentUser]]) {
        [self.navigationController pushViewController:[[HomeViewController alloc] init] animated:NO];
    }
}

#pragma mark - Login mehtods

/* Login to facebook method */
- (IBAction)loginButtonTouchHandler:(id)sender
{
    // Set permissions required from the facebook user account
    NSArray *permissionsArray = [NSArray arrayWithObjects:@"user_about_me",@"user_relationships",@"user_birthday",@"user_location",@"offline_access", nil];

    // Login PFUser using facebook
    [PFFacebookUtils logInWithPermissions:permissionsArray block:^(PFUser *user, NSError *error) {
        [activityIndicator stopAnimating]; // Hide loading indicator

        if (!user) {
            if (!error) {
                NSLog(@"Uh oh. The user cancelled the Facebook login.");
            } else {
                NSLog(@"Uh oh. An error occurred: %@", error);
            }
        } else if (user.isNew) {
            NSLog(@"User with facebook signed up and logged in!");
            [self.navigationController pushViewController:[[HomeViewController alloc] init] animated:YES];

        } else {
            NSLog(@"User with facebook logged in!");
            [self.navigationController pushViewController:[[HomeViewController alloc] init] animated:YES];
        }
    }];

    [activityIndicator startAnimating]; // Show loading indicator until login is finished
}

@end


text:
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * ServingStatus.java
 *
 * This file was auto-generated from WSDL
 * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
 */

package com.google.api.ads.adwords.axis.v201809.cm;

public class ServingStatus implements java.io.Serializable {
    private java.lang.String _value_;
    private static java.util.HashMap _table_ = new java.util.HashMap();

    // Constructor
    protected ServingStatus(java.lang.String value) {
        _value_ = value;
        _table_.put(_value_,this);
    }

    public static final java.lang.String _SERVING = "SERVING";
    public static final java.lang.String _NONE = "NONE";
    public static final java.lang.String _ENDED = "ENDED";
    public static final java.lang.String _PENDING = "PENDING";
    public static final java.lang.String _SUSPENDED = "SUSPENDED";
    public static final ServingStatus SERVING = new ServingStatus(_SERVING);
    public static final ServingStatus NONE = new ServingStatus(_NONE);
    public static final ServingStatus ENDED = new ServingStatus(_ENDED);
    public static final ServingStatus PENDING = new ServingStatus(_PENDING);
    public static final ServingStatus SUSPENDED = new ServingStatus(_SUSPENDED);
    public java.lang.String getValue() { return _value_;}
    public static ServingStatus fromValue(java.lang.String value)
          throws java.lang.IllegalArgumentException {
        ServingStatus enumeration = (ServingStatus)
            _table_.get(value);
        if (enumeration==null) throw new java.lang.IllegalArgumentException();
        return enumeration;
    }
    public static ServingStatus fromString(java.lang.String value)
          throws java.lang.IllegalArgumentException {
        return fromValue(value);
    }
    public boolean equals(java.lang.Object obj) {return (obj == this);}
    public int hashCode() { return toString().hashCode();}
    public java.lang.String toString() { return _value_;}
    public java.lang.Object readResolve() throws java.io.ObjectStreamException { return fromValue(_value_);}
    public static org.apache.axis.encoding.Serializer getSerializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new org.apache.axis.encoding.ser.EnumSerializer(
            _javaType, _xmlType);
    }
    public static org.apache.axis.encoding.Deserializer getDeserializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new org.apache.axis.encoding.ser.EnumDeserializer(
            _javaType, _xmlType);
    }
    // Type metadata
    private static org.apache.axis.description.TypeDesc typeDesc =
        new org.apache.axis.description.TypeDesc(ServingStatus.class);

    static {
        typeDesc.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "ServingStatus"));
    }
    /**
     * Return type metadata object
     */
    public static org.apache.axis.description.TypeDesc getTypeDesc() {
        return typeDesc;
    }

}


text:
using namespace Upp;

CONSOLE_APP_MAIN
{

}


text:
import { Component, OnInit, AfterViewInit, OnDestroy, ElementRef, Input,
         ViewChild, ViewContainerRef, ComponentFactoryResolver, EventEmitter, ReflectiveInjector  } from '@angular/core';
import { AbstractControl, FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';
import { Observable } from 'rxjs';
import { CSSHelper } from '../../../utils/css.helper';

// Import components
import { WarningPanelComponent } from '../../../shared/shared-module/warning-panel/warning-panel';

// Import Service
import { StreetService } from '../../../service/street-service';

// Import utils
import { EventData } from '../../../utils/event.helper';

@Component({
    moduleId: module.id,
    selector: 'database-street-cmp',
    templateUrl: 'database-street.component.html',
    entryComponents: [
        WarningPanelComponent
    ]
})

export class DatabaseStreetComponent implements OnInit, AfterViewInit, OnDestroy {
    // CONSTANT
    static NUM_ITEMS: number = 10;

    @Input() ComponentId: string;

    // Annoucement panel
    @ViewChild('AnnoucementModalContainer', { read: ViewContainerRef }) AnnoucementModalContainer: ViewContainerRef;
    private AnnoucementModalComponent: any = null;

    // Input form
    private group: FormGroup;
    private fromToGroup: FormGroup;
    private listRoadsForm: AbstractControl;
    private fromForm: AbstractControl;
    private toForm: AbstractControl;
    private graphTypeForm: AbstractControl;
    private viewTypeForm: AbstractControl;

    // Search component
    @ViewChild('searchdiv') private searchDiv: ElementRef;
    private searchStr: string;
    private suggestSearch: any[];
    private selectedSearch: any;
    private streetSearch: any[];

    // Chart
    private chartOptions: any;
    private chart:any;

    // Parameters
    private listRoads: string[];
    private from: string;
    private to: string;
    private graphType: string;
    private viewType: string;

    // Timer
    private timer: any;

    constructor(private streetService: StreetService,
                private element: ElementRef,
                private cssHelper: CSSHelper,
                private fb: FormBuilder,
                private resolver: ComponentFactoryResolver) {
        // Input form
        this.fromToGroup = fb.group({
            'fromForm': ['', Validators.required],
            'toForm': ['',  Validators.required]}
        ,{
            validator: this.fromToValidation.bind(this)
        });
        this.group = fb.group({
            'listRoadsForm': ['', this.listRoadvalidation],
            'fromToGroup': this.fromToGroup,
            'graphTypeForm': ['', Validators.required],
            'viewTypeForm': ['', Validators.required],
        });
        this.listRoadsForm = this.group.controls['listRoadsForm'];
        this.fromForm = this.fromToGroup.controls['fromForm'];
        this.toForm = this.fromToGroup.controls['toForm'];
        this.graphTypeForm = this.group.controls['graphTypeForm'];
        this.viewTypeForm = this.group.controls['viewTypeForm'];

        // Search
        this.searchStr = '';
        this.suggestSearch = [];
        this.selectedSearch = null;
        this.streetSearch = [];

        // Chart
        this.chartOptions = null;
        this.chart = null;

        // Parameters
        this.listRoads = [];
        this.from = '';
        this.to = '';
        this.graphType = '';
        this.viewType = '';

        // Timer
        this.timer = null;
    }

    // Validations (start) ---------------------------

    listRoadvalidation(control: FormControl): any {
        if (control.value === 0) {
            return {'AtLeastOneRoad': true};
        }
    }

    fromToValidation(group: FormGroup): any {
        var from = group.value.fromForm.split(' ').join('-').split(':').join('-').split('-');
        var to = group.value.toForm.split(' ').join('-').split(':').join('-').split('-');

        var fromDate = Date.UTC(from[0], from[1] - 1, from[2], from[3], from[4], from[5]);
        var toDate = Date.UTC(to[0], to[1] - 1, to[2], to[3], to[4], to[5]);
        if ((fromDate - toDate) >= 0) {
            return {'FromLessTo': true};
        }
    }

    // Validations (end) -----------------------------

    ngOnInit(): void {
        // Create event for search input
        this.createSearchEvent();
        this.createChartOptions();
    }

    onGraphTypeChange(graphType: string): void {
        this.graphType = graphType;
        this.createChartOptions();
    }

    onViewTypeChange(viewType: string): void {
        this.viewType = viewType;
    }

    suggestSearchSelected(suggestSearch: any) {
        this.searchStr = suggestSearch ? suggestSearch.name : 'none';
    }

    createSearchEvent(): void {
        Observable.fromEvent(this.searchDiv.nativeElement, 'keyup')
            .map((e: any) => e.target.value)
            .filter((text: string) => text.length > 1)
            .debounceTime(200)
            .map((query: string) => this.streetService.SearchName(query, DatabaseStreetComponent.NUM_ITEMS))
            .switch()
            .subscribe(
                (results: any) => {
                    this.suggestSearch = results.map((result: any) => {
                        return {
                            name: result,
                            searchText: result
                        };
                    });
                },
                (err: any) => {
                    console.log(err);
                }
            );
    }

    // Create Date pick for From and To Div (start) ------------------
    createDatepickerFromDiv(): void {
        var datePickerDiv:any = $('#'+this.ComponentId+'_fromdiv');
        datePickerDiv.datetimepicker({
            format: 'yyyy-mm-dd hh:ii:ss',
            autoclose: true,
            todayBtn: true,
            pickerPosition: 'bottom-left'
        }).on('changeDate', (event: any) => {
            this.from = datePickerDiv.val();
        });
    }

    createDatepickerToDiv(): void {
        var datePickerDiv:any = $('#'+this.ComponentId+'_todiv');
        datePickerDiv.datetimepicker({
            format: 'yyyy-mm-dd hh:ii:ss',
            autoclose: true,
            todayBtn: true,
            pickerPosition: 'bottom-left'
        }).on('changeDate', (event: any) => {
            this.to = datePickerDiv.val();
        });
    }
    // Create Date pick for From and To Div (end) --------------------

    ngAfterViewInit(): void {
        this.createDatepickerFromDiv();
        this.createDatepickerToDiv();
    }

    SaveChart(chart:any): void {
        this.chart = chart;
    }

    createChartOptions(): void {
        this.chartOptions = {
            chart: {
                type: this.graphType === 'LineGraph' ? 'spline' : 'spline'
            },
            title: {
                text: 'Number of vehicles at some streets'
            },
            subtitle: {
                text: ''
            },
            xAxis: {
                type: 'datetime',
                dateTimeLabelFormats: { // don't display the dummy year
                    second: '%H:%M:%S',
                    minute: '%H:%M',
                    hour: '%H:%M',
                    day: '%e. %b',
                },
                title: {
                    text: 'Date'
                }
            },
            yAxis: {
                title: {
                    text: 'Number of vehicles'
                },
                min: 0
            },
            tooltip: {
                headerFormat: '{series.name}
',
                pointFormat: '{point.x:%e. %b}: {point.y:.2f} vehicle(s)'
            },
            plotOptions: {
                spline: {
                    marker: {
                        enabled: true
                    }
                }
            },
            series: []
        };
    }

    ClickSearchRoad(): void {
        var searchDiv: any = $('#' + this.ComponentId + '_typeahead' + ' .typeahead-input');
        this.searchStr = searchDiv.val();
        (this.streetService.SearchStreets(this.searchStr))
            .subscribe((results: any[]) => {
                    this.streetSearch = results;
                },
                (err: any) => {
                    console.log(err);
                }
            );
    }

    ClickDelete(streetName: string): void {
        this.listRoads.splice(this.listRoads.indexOf(streetName), 1);
    }

    ClickAddRoad(streetName: string): void {
        if (this.listRoads.indexOf(streetName) < 0) {
            this.listRoads.push(streetName);
        }
    }

    ClickViewGraph(): void {
        if (this.group.valid) {
            if (this.timer) {
                this.timer.unsubscribe();
            }

            for (let idx:number = 0; idx < this.listRoads.length; idx++) {
                var roadName = this.listRoads[idx];
                this.chart.addSeries({
                    name: roadName,
                    data: [[Date.UTC(2016, 9, 21), 0],
                    [Date.UTC(2016, 10, 4), 28],
                    [Date.UTC(2016, 10, 9), 25],
                    [Date.UTC(2016, 10, 27), 2],
                    [Date.UTC(2016, 11, 2), 28],
                    [Date.UTC(2016, 11, 26), 28],
                    [Date.UTC(2016, 11, 29), 47],
                    [Date.UTC(2017, 0, 11), 79],
                    [Date.UTC(2017, 0, 26), 72],
                    [Date.UTC(2017, 1, 3), 2],
                    [Date.UTC(2017, 1, 11), 12],
                    [Date.UTC(2017, 1, 25), 2],
                    [Date.UTC(2017, 2, 11), 18],
                    [Date.UTC(2017, 3, 11), 19],
                    [Date.UTC(2017, 4, 1), 85],
                    [Date.UTC(2017, 4, 5), 22],
                    [Date.UTC(2017, 4, 19), 15],
                    [Date.UTC(2017, 5, 3), 0]]
                });
            }

            // TODO
            // var observable = Observable.timer(0, this.timeUpdate);
            // this.timer = observable.subscribe(() => {
            //     for (let idx:number = 0; idx < this.listRoads.length; idx++) {
            //         var streetName = this.listRoads[idx];
            //         (this.streetService.GetNumVehiclesStreet(streetName))
            //             .subscribe(
            //                 (result: any) => {
            //                     var dataLength = this.chart.series[idx].data.length;
            //                     if (dataLength === 0) {
            //                         this.chart.series[idx].addPoint([result.utc_time, result.num_vehicles]);
            //                     } else {
            //                         var oldUTC = this.chart.series[idx].data[dataLength - 1].x;
            //                         if (oldUTC < result.utc_time) {
            //                             this.chart.series[idx].addPoint([result.utc_time, result.num_vehicles]);
            //                         }
            //                     }
            //                 },
            //                 (err: any) => {
            //                     console.log(err);
            //                 }
            //             );
            //     }
            // });
        } else {
            // Open modal
            var openDiv = $('#StreetAnnoucementOpenModalBtn');
            openDiv.click();

            // Show warning
            if (this.AnnoucementModalComponent) {
                this.AnnoucementModalComponent.destroy();
            }

            // Create data to pass to modal
            var response = new EventEmitter<EventData>();
            let data = [
                {provide: 'Header', useValue: 'Warning'},
                {provide: 'Message', useValue:
                          'Oops! There is something wrong with the inputs. Please correct them before click "View Graph"'},
                {provide: 'Response', useValue: response}
            ];
            let resolveData = ReflectiveInjector.resolve(data);
            let injector = ReflectiveInjector.fromResolvedProviders(resolveData, this.AnnoucementModalContainer.parentInjector);

            // Create component
            let factory = this.resolver.resolveComponentFactory(WarningPanelComponent);
            let component = factory.create(injector);

            // Add component to modal
            this.AnnoucementModalContainer.insert(component.hostView);
            this.AnnoucementModalComponent = component;

            // Handle response
            response.subscribe(
                (result: string) => {
                    switch (result) {
                        case WarningPanelComponent.CONFIRM:
                            var closeDiv = $('#StreetAnnoucementCloseModalBtn');
                            closeDiv.click();
                            break;
                        default:
                            // Do nothing here
                            break;
                    }
                },
                (err: any) => {
                    console.log(err);
                }
            );
        }
    }

    ngOnDestroy() {
        if (this.timer) {
            this.timer.unsubscribe();
        }
    }

    ClickReset(): void {
        // TODO
        console.log('Click Reset');
    }
}


text:
import { getUserIdFromRequest } from '../helpers';
import {
  listTripLocationsForUser,
  addLocationToTrip,
  getTripLocationForUser,
  removeAllTripLocations,
  removeTripLocationForUser,
  updateTripForUser,
} from '../models/trip-location';

export default {
  list( req, res ) {
    const userId = getUserIdFromRequest( req );
    listTripLocationsForUser( userId )
    .then( ( locations ) => {
      res.status( 200 ).json( locations );
    } )
    .catch( ( err ) => {
      req.error( {}, err.message );
      res.status( 502 ).send( err );
    } );
  },

  create( req, res ) {
    const userId = getUserIdFromRequest( req );
    const { location } = req.body;
    addLocationToTrip( userId, { location } )
    .then( ( tripLocation ) => {
      res.status( 200 ).json( tripLocation );
    } )
    .catch( ( err ) => {
      req.error( {}, err.message );
      res.status( 502 ).send( err );
    } );
  },

  get( req, res ) {
    const userId = getUserIdFromRequest( req );
    const { tripLocationId } = req.params;
    getTripLocationForUser( userId, tripLocationId )
    .then( ( tripLocation ) => {
      res.status( 200 ).json( tripLocation );
    } )
    .catch( ( err ) => {
      req.error( {}, err.message );
      res.status( 502 ).send( err );
    } );
  },

  updateList( req, res ) {
    const userId = getUserIdFromRequest( req );
    const { tripLocationIds } = req.body;
    updateTripForUser( userId, tripLocationIds )
    .then( ( updatedLocations ) => {
      res.status( 200 ).json( updatedLocations );
    } )
    .catch( ( err ) => {
      req.error( {}, err.message );
      res.status( 502 ).send( err );
    } );
  },

  deleteAll( req, res ) {
    const userId = getUserIdFromRequest( req );
    removeAllTripLocations( userId )
    .then( ( tripLocations ) => {
      res.status( 200 ).json( tripLocations );
    } )
    .catch( ( err ) => {
      req.error( {}, err.message );
      res.status( 502 ).send( err );
    } );
  },

  delete( req, res ) {
    const userId = getUserIdFromRequest( req );
    const { tripLocationId } = req.params;
    removeTripLocationForUser( userId, tripLocationId )
    .then( ( tripLocation ) => {
      res.status( 200 ).json( tripLocation );
    } )
    .catch( ( err ) => {
      req.error( {}, err.message );
      res.status( 502 ).send( err );
    } )
  }
};


text:
from django.utils.encoding import force_unicode
from django.utils.functional import lazy

def _lazy_join(separator, strings):
    return separator.join([force_unicode(s)
                           for s in strings])

lazy_join = lazy(_lazy_join, unicode)