text:
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;

namespace GameRes.Formats.Triangle
{
    [Export(typeof(ArchiveFormat))]
    public class BmxOpener : ArchiveFormat
    {
        public override string         Tag { get { return "BMX/TRIANGLE"; } }
        public override string Description { get { return "Triangle resource archive"; } }
        public override uint     Signature { get { return 0; } }
        public override bool  IsHierarchic { get { return false; } }
        public override bool      CanWrite { get { return false; } }

        public BmxOpener ()
        {
            Extensions = new string[] { "bmx", "wax", "fx", "gx" };
        }

        public override ArcFile TryOpen (ArcView file)
        {
            int count = file.View.ReadInt32 (0);
            if (!IsSaneCount (count))
                return null;
            uint index_size = (uint)count * 4 + 8;
            if (index_size > file.View.Reserve (0, index_size))
                return null;
            uint index_offset = 4;
            uint offset = file.View.ReadUInt32 (index_offset);
            if (offset != index_size)
                return null;
            uint last_offset = file.View.ReadUInt32 (index_size - 4);
            if (last_offset != file.MaxOffset)
                return null;
            string default_type = "";
            if (file.Name.HasExtension ("fx"))
                default_type = "audio";
            else if (file.Name.HasExtension ("gx"))
                default_type = "image";
            var base_name = Path.GetFileNameWithoutExtension (file.Name);
            var dir = new List<Entry> (count);
            for (int i = 0; i < count; ++i)
            {
                index_offset += 4;
                var entry = new PackedEntry {
                    Name = string.Format ("{0}#{1:D4}", base_name, i),
                    Type = default_type,
                    Offset = offset,
                };
                offset = file.View.ReadUInt32 (index_offset);
                entry.Size = (uint)(offset - entry.Offset);
                if (!entry.CheckPlacement (file.MaxOffset))
                    return null;
                dir.Add (entry);
            }
            if (string.IsNullOrEmpty (default_type))
            {
                foreach (var entry in dir)
                {
                    uint signature = file.View.ReadUInt32 (entry.Offset);
                    entry.ChangeType (AutoEntry.DetectFileType (signature));
                }
            }
            return new ArcFile (file, this, dir);
        }

        public override Stream OpenEntry (ArcFile arc, Entry entry)
        {
            var pent = entry as PackedEntry;
            if (null == pent)
                return base.OpenEntry (arc, entry);
            if (!pent.IsPacked)
            {
                if (!arc.File.View.AsciiEqual (entry.Offset, "fACE"))
                    return base.OpenEntry (arc, entry);
                pent.IsPacked = true;
                pent.UnpackedSize = arc.File.View.ReadUInt32 (entry.Offset+4) ^ 0x65641538;
            }
            using (var input = arc.File.CreateStream (entry.Offset+8, entry.Size-8))
            {
                var data = new byte[pent.UnpackedSize];
                TriFormat.Unpack (input, data);
                return new BinMemoryStream (data, entry.Name);
            }
        }
    }
}


text:
<?php get_header(); ?>

        <?php //echo do_shortcode("[metaslider id=24881]"); ?>

	<?php welcome_breadcrumbs(); ?>

		<?php if ( function_exists('FoundationPress_pagination') ) { FoundationPress_pagination(); } else if ( is_paged() ) { ?>

<?php next_posts_link( __( '← Older posts', 'FoundationPress' ) ); ?>

<?php previous_posts_link( __( 'Newer posts →', 'FoundationPress' ) ); ?>

	<?php } ?>

	<?php if ( have_posts() ) : ?>

		<?php do_action('foundationPress_before_content'); ?>

		<?php while ( have_posts() ) : the_post(); ?>
		<?php if (function_exists('welcome_breadcrumbs')) { ?>

<?php get_template_part('/includes/post'); ?>

			<?php } else { ?>
				<?php get_template_part( 'content', get_post_format() ); ?>
			<?php } ?>
		<?php endwhile; ?>

		<?php else : ?>
			<?php get_template_part( 'content', 'none' ); ?>

		<?php do_action('foundationPress_before_pagination'); ?>

	<?php endif;?>

	<?php if ( function_exists('FoundationPress_pagination') ) { FoundationPress_pagination(); } else if ( is_paged() ) { ?>

<?php next_posts_link( __( '← Older posts', 'FoundationPress' ) ); ?>

<?php previous_posts_link( __( 'Newer posts →', 'FoundationPress' ) ); ?>

	<?php } ?>

	<?php do_action('foundationPress_after_content'); ?>

	<?php get_sidebar(); ?>

<?php get_footer(); ?>

redpajama_set_name: RedPajamaGithub


text:
package java.awt;

import java.awt.geom.Point2D;

/**
 * A point representing a location in {@code (x,y)} coordinate space,
 * specified in integer precision.
 *
 * @version 	1.40, 02/24/06
 * @author 	Sami Shaio
 * @since       1.0
 */
public class Point extends Point2D implements java.io.Serializable {
    /**
     * The X coordinate of this Point.
     * If no X coordinate is set it will default to 0.
     *
     * @serial
     * @see #getLocation()
     * @see #move(int, int)
     * @since 1.0
     */
    public int x;

    /**
     * The Y coordinate of this Point.
     * If no Y coordinate is set it will default to 0.
     *
     * @serial
     * @see #getLocation()
     * @see #move(int, int)
     * @since 1.0
     */
    public int y;

    /*
     * JDK 1.1 serialVersionUID
     */
    private static final long serialVersionUID = -5276940640259749850L;

    /**
     * Constructs and initializes a point at the origin
     * (0, 0) of the coordinate space.
     * @since       1.1
     */
    public Point() {
	this(0, 0);
    }

    /**
     * Constructs and initializes a point with the same location as
     * the specified Point object.
     * @param       p a point
     * @since       1.1
     */
    public Point(Point p) {
	this(p.x, p.y);
    }

    /**
     * Constructs and initializes a point at the specified
     * {@code (x,y)} location in the coordinate space.
     * @param x the X coordinate of the newly constructed Point
     * @param y the Y coordinate of the newly constructed Point
     * @since 1.0
     */
    public Point(int x, int y) {
	this.x = x;
	this.y = y;
    }

    /**
     * {@inheritDoc}
     * @since 1.2
     */
    public double getX() {
	return x;
    }

    /**
     * {@inheritDoc}
     * @since 1.2
     */
    public double getY() {
	return y;
    }

    /**
     * Returns the location of this point.
     * This method is included for completeness, to parallel the
     * getLocation method of Component.
     * @return      a copy of this point, at the same location
     * @see         java.awt.Component#getLocation
     * @see         java.awt.Point#setLocation(java.awt.Point)
     * @see         java.awt.Point#setLocation(int, int)
     * @since       1.1
     */
    public Point getLocation() {
	return new Point(x, y);
    }

    /**
     * Sets the location of the point to the specified location.
     * This method is included for completeness, to parallel the
     * setLocation method of Component.
     * @param       p  a point, the new location for this point
     * @see         java.awt.Component#setLocation(java.awt.Point)
     * @see         java.awt.Point#getLocation
     * @since       1.1
     */
    public void setLocation(Point p) {
	setLocation(p.x, p.y);
    }

    /**
     * Changes the point to have the specified location.
     *

     * This method is included for completeness, to parallel the
     * setLocation method of Component.
     * Its behavior is identical with move(int, int).
     * @param       x the X coordinate of the new location
     * @param       y the Y coordinate of the new location
     * @see         java.awt.Component#setLocation(int, int)
     * @see         java.awt.Point#getLocation
     * @see         java.awt.Point#move(int, int)
     * @since       1.1
     */
    public void setLocation(int x, int y) {
	move(x, y);
    }

    /**
     * Sets the location of this point to the specified double coordinates.
     * The double values will be rounded to integer values.
     * Any number smaller than Integer.MIN_VALUE
     * will be reset to MIN_VALUE, and any number
     * larger than Integer.MAX_VALUE will be
     * reset to MAX_VALUE.
     *
     * @param x the X coordinate of the new location
     * @param y the Y coordinate of the new location
     * @see #getLocation
     */
    public void setLocation(double x, double y) {
	this.x = (int) Math.floor(x+0.5);
	this.y = (int) Math.floor(y+0.5);
    }

    /**
     * Moves this point to the specified location in the
     * {@code (x,y)} coordinate plane. This method
     * is identical with setLocation(int, int).
     * @param       x the X coordinate of the new location
     * @param       y the Y coordinate of the new location
     * @see         java.awt.Component#setLocation(int, int)
     */
    public void move(int x, int y) {
	this.x = x;
	this.y = y;
    }

    /**
     * Translates this point, at location {@code (x,y)},
     * by {@code dx} along the {@code x} axis and {@code dy}
     * along the {@code y} axis so that it now represents the point
     * {@code (x+dx,y+dy)}.
     *
     * @param       dx   the distance to move this point
     *                            along the X axis
     * @param       dy    the distance to move this point
     *                            along the Y axis
     */
    public void translate(int dx, int dy) {
	this.x += dx;
	this.y += dy;
    }

    /**
     * Determines whether or not two points are equal. Two instances of
     * Point2D are equal if the values of their
     * x and y member fields, representing
     * their position in the coordinate space, are the same.
     * @param obj an object to be compared with this Point2D
     * @return true if the object to be compared is
     *         an instance of Point2D and has
     *         the same values; false otherwise.
     */
    public boolean equals(Object obj) {
	if (obj instanceof Point) {
	    Point pt = (Point)obj;
	    return (x == pt.x) && (y == pt.y);
	}
	return super.equals(obj);
    }

    /**
     * Returns a string representation of this point and its location
     * in the {@code (x,y)} coordinate space. This method is
     * intended to be used only for debugging purposes, and the content
     * and format of the returned string may vary between implementations.
     * The returned string may be empty but may not be null.
     *
     * @return  a string representation of this point
     */
    public String toString() {
	return getClass().getName() + "[x=" + x + ",y=" + y + "]";
    }
}


text:
@servers(['prod' => 'cfp.techcampmemphis.org@cfp.techcampmemphis.org'])

@task('deploy:prod', ['on' => 'prod'])
cd ~/TechCampCFP
git pull origin master
cp ~/configs/production.yml ~/TechCampCFP/config/production.yml
cp ~/configs/phinx.yml ~/TechCampCFP/phinx.yml
#composer update
~/TechCampCFP/vendor/bin/phinx migrate --environment=production
@endtask


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;

namespace LiteDB.Tests.Engine
{
    [TestClass]
    public class Performance_Tests
    {
        const int N1 = 10000;
        const int N2 = 1000;

        [TestMethod]
        public void Simple_Performance_Runner()
        {
            // just a simple example to test performance speed
            using (var file = new TempFile())
            using (var db = new LiteEngine(file.Filename))
            {
                var ti = new Stopwatch();
                var tx = new Stopwatch();
                var tu = new Stopwatch();
                var td = new Stopwatch();

                ti.Start();
                db.Insert("col", GetDocs(N1));
                ti.Stop();

                tx.Start();
                db.EnsureIndex("col", "name");
                tx.Stop();

                tu.Start();
                db.Update("col", GetDocs(N1));
                tu.Stop();

                db.EnsureIndex("col", "name");

                td.Start();
                db.Delete("col", Query.All());
                td.Stop();

                Debug.WriteLine("Insert time: " + ti.ElapsedMilliseconds);
                Debug.WriteLine("EnsureIndex time: " + tx.ElapsedMilliseconds);
                Debug.WriteLine("Update time: " + tu.ElapsedMilliseconds);
                Debug.WriteLine("Delete time: " + td.ElapsedMilliseconds);
            }
        }

        private IEnumerable<BsonDocument> GetDocs(int count)
        {
            var rnd = new Random();

            for(var i = 0; i < count; i++)
            {
                yield return new BsonDocument
                {
                    { "_id", i },
                    { "name", Guid.NewGuid().ToString() },
                    { "type", rnd.Next(1, 100) },
                    { "lorem", TempFile.LoremIpsum(3, 5, 2, 3, 3) }
                };
            }
        }
    }
}


text:
package limelight.io;

public class MockPacker extends Packer
{
  public String unpackPackagePath;
  public String unpackResult;
  public String unpackDestination;
  public String packProductionPath;
  public String packLlpName;

  @Override
  public String unpack(String packagePath, String destination)
  {
    unpackPackagePath = packagePath;
    unpackDestination = destination;
    return unpackResult;
  }

  @Override
  public void pack(String productionPath, String llpName)
  {
    packProductionPath = productionPath;
    packLlpName = llpName;
  }
}


text:
#import <Foundation/NSNotification.h>

@class NSMutableDictionary, NSOperationQueue;

FOUNDATION_EXPORT_CLASS
@interface NSNotificationCenter : NSObject

+(NSNotificationCenter *)defaultCenter;

-(void)addObserver:observer selector:(SEL)selector name:(NSString *)name object:object;

-(void)removeObserver:observer;
-(void)removeObserver:observer name:(NSString *)name object:object;

-(void)postNotification:(NSNotification *)note;

-(void)postNotificationName:(NSString *)name object:object userInfo:(NSDictionary *)userInfo;

-(void)postNotificationName:(NSString *)name object:object;

-(id)addObserverForName:(NSString *)name object:(id)obj queue:(NSOperationQueue *)queue usingBlock:(void (^)(NSNotification *))block;

@end


text:
require 'cgi'
require 'uri'

module Wikilink
  class Converter
    module ArgumentExtractor
      def extract_arguments(*args)
        options = {}
        options = args.pop if args.last.is_a?(Hash)
        name = args.shift

        if name.nil? || name.is_a?(String) || name.is_a?(Symbol)
          name = name.to_s
          converter = args.shift
        else
          converter = name
          name = nil
        end

        throw ArgumentError, "too many arguments" unless args.empty?

        [name, converter, options]
      end
    end

    module LinkHelper
      def link_to(name, url, attributes = {})
        attributes[:class] = Array(attributes[:class]).flatten.join(' ').split.uniq.join(' ')
        attributes.delete(:class) if attributes[:class].empty?
        attributes = attributes.inject('') do |memo, (key, value)|
          memo + key.to_s + '="' + CGI.escape_html(value) + '" '
        end
        url, fragment = url.split('#', 2)
        if fragment
          url << '#' + URI.encode(fragment, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))
        end

        %Q{<a #{attributes}href="#{url}">#{CGI.escape_html name}</a>}
      end
    end

    module HTMLAttributes
      def html_class(extra_classes = nil)
        classes = []
        if respond_to? :options
          classes << options[:class]
          classes << 'external' if options[:external]
        end

        classes << extra_classes if extra_classes

        classes.flatten.join(' ').split.uniq.join(' ')
      end
    end
  end
end


text:
// Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.android_webview.test;

import android.test.suitebuilder.annotation.SmallTest;
import android.util.Pair;

import org.chromium.android_webview.AwContents;
import org.chromium.android_webview.InterceptedRequestData;
import org.chromium.android_webview.test.util.CommonResources;
import org.chromium.base.test.util.Feature;
import org.chromium.base.test.util.TestFileUtil;
import org.chromium.content.browser.test.util.CallbackHelper;
import org.chromium.content.browser.test.util.TestCallbackHelperContainer.OnReceivedErrorHelper;
import org.chromium.net.test.util.TestWebServer;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;

/**
 * Tests for the WebViewClient.shouldInterceptRequest() method.
 */
public class AwContentsClientShouldInterceptRequestTest extends AwTestBase {

    private static class TestAwContentsClient
            extends org.chromium.android_webview.test.TestAwContentsClient {

        public static class ShouldInterceptRequestHelper extends CallbackHelper {
            private List<String> mShouldInterceptRequestUrls = new ArrayList<String>();
            private ConcurrentHashMap<String, InterceptedRequestData> mReturnValuesByUrls
                = new ConcurrentHashMap<String, InterceptedRequestData>();
            // This is read from the IO thread, so needs to be marked volatile.
            private volatile InterceptedRequestData mShouldInterceptRequestReturnValue = null;
            void setReturnValue(InterceptedRequestData value) {
                mShouldInterceptRequestReturnValue = value;
            }
            void setReturnValueForUrl(String url, InterceptedRequestData value) {
                mReturnValuesByUrls.put(url, value);
            }
            public List<String> getUrls() {
                assert getCallCount() > 0;
                return mShouldInterceptRequestUrls;
            }
            public InterceptedRequestData getReturnValue(String url) {
                InterceptedRequestData value = mReturnValuesByUrls.get(url);
                if (value != null) return value;
                return mShouldInterceptRequestReturnValue;
            }
            public void notifyCalled(String url) {
                mShouldInterceptRequestUrls.add(url);
                notifyCalled();
            }
        }

        public static class OnLoadResourceHelper extends CallbackHelper {
            private String mUrl;

            public String getUrl() {
                assert getCallCount() > 0;
                return mUrl;
            }

            public void notifyCalled(String url) {
                mUrl = url;
                notifyCalled();
            }
        }

        @Override
        public InterceptedRequestData shouldInterceptRequest(String url) {
            InterceptedRequestData returnValue = mShouldInterceptRequestHelper.getReturnValue(url);
            mShouldInterceptRequestHelper.notifyCalled(url);
            return returnValue;
        }

        @Override
        public void onLoadResource(String url) {
            super.onLoadResource(url);
            mOnLoadResourceHelper.notifyCalled(url);
        }

        private ShouldInterceptRequestHelper mShouldInterceptRequestHelper;
        private OnLoadResourceHelper mOnLoadResourceHelper;

        public TestAwContentsClient() {
            mShouldInterceptRequestHelper = new ShouldInterceptRequestHelper();
            mOnLoadResourceHelper = new OnLoadResourceHelper();
        }

        public ShouldInterceptRequestHelper getShouldInterceptRequestHelper() {
            return mShouldInterceptRequestHelper;
        }

        public OnLoadResourceHelper getOnLoadResourceHelper() {
            return mOnLoadResourceHelper;
        }
    }

    private String addPageToTestServer(TestWebServer webServer, String httpPath, String html) {
        List<Pair<String, String>> headers = new ArrayList<Pair<String, String>>();
        headers.add(Pair.create("Content-Type", "text/html"));
        headers.add(Pair.create("Cache-Control", "no-store"));
        return webServer.setResponse(httpPath, html, headers);
    }

    private String addAboutPageToTestServer(TestWebServer webServer) {
        return addPageToTestServer(webServer, "/" + CommonResources.ABOUT_FILENAME,
                CommonResources.ABOUT_HTML);
    }

    private InterceptedRequestData stringToInterceptedRequestData(String input) throws Throwable {
        final String mimeType = "text/html";
        final String encoding = "UTF-8";

        return new InterceptedRequestData(
                mimeType, encoding, new ByteArrayInputStream(input.getBytes(encoding)));
    }

    private TestWebServer mWebServer;
    private TestAwContentsClient mContentsClient;
    private AwTestContainerView mTestContainerView;
    private AwContents mAwContents;
    private TestAwContentsClient.ShouldInterceptRequestHelper mShouldInterceptRequestHelper;

    @Override
    protected void setUp() throws Exception {
        super.setUp();

        mContentsClient = new TestAwContentsClient();
        mTestContainerView = createAwTestContainerViewOnMainSync(mContentsClient);
        mAwContents = mTestContainerView.getAwContents();
        mShouldInterceptRequestHelper = mContentsClient.getShouldInterceptRequestHelper();

        mWebServer = new TestWebServer(false);
    }

    @Override
    protected void tearDown() throws Exception {
        mWebServer.shutdown();
        super.tearDown();
    }

    @SmallTest
    @Feature({"AndroidWebView"})
    public void testCalledWithCorrectUrl() throws Throwable {
        final String aboutPageUrl = addAboutPageToTestServer(mWebServer);

        int callCount = mShouldInterceptRequestHelper.getCallCount();
        int onPageFinishedCallCount = mContentsClient.getOnPageFinishedHelper().getCallCount();

        loadUrlAsync(mAwContents, aboutPageUrl);

        mShouldInterceptRequestHelper.waitForCallback(callCount);
        assertEquals(1, mShouldInterceptRequestHelper.getUrls().size());
        assertEquals(aboutPageUrl,
                mShouldInterceptRequestHelper.getUrls().get(0));

        mContentsClient.getOnPageFinishedHelper().waitForCallback(onPageFinishedCallCount);
        assertEquals(CommonResources.ABOUT_TITLE, getTitleOnUiThread(mAwContents));
    }

    @SmallTest
    @Feature({"AndroidWebView"})
    public void testOnLoadResourceCalledWithCorrectUrl() throws Throwable {
        final String aboutPageUrl = addAboutPageToTestServer(mWebServer);
        final TestAwContentsClient.OnLoadResourceHelper onLoadResourceHelper =
            mContentsClient.getOnLoadResourceHelper();

        int callCount = onLoadResourceHelper.getCallCount();

        loadUrlAsync(mAwContents, aboutPageUrl);

        onLoadResourceHelper.waitForCallback(callCount);
        assertEquals(aboutPageUrl, onLoadResourceHelper.getUrl());
    }

    @SmallTest
    @Feature({"AndroidWebView"})
    public void testDoesNotCrashOnInvalidData() throws Throwable {
        final String aboutPageUrl = addAboutPageToTestServer(mWebServer);

        mShouldInterceptRequestHelper.setReturnValue(
                new InterceptedRequestData("text/html", "UTF-8", null));
        int callCount = mShouldInterceptRequestHelper.getCallCount();
        loadUrlAsync(mAwContents, aboutPageUrl);
        mShouldInterceptRequestHelper.waitForCallback(callCount);

        mShouldInterceptRequestHelper.setReturnValue(
                new InterceptedRequestData(null, null, new ByteArrayInputStream(new byte[0])));
        callCount = mShouldInterceptRequestHelper.getCallCount();
        loadUrlAsync(mAwContents, aboutPageUrl);
        mShouldInterceptRequestHelper.waitForCallback(callCount);

        mShouldInterceptRequestHelper.setReturnValue(
                new InterceptedRequestData(null, null, null));
        callCount = mShouldInterceptRequestHelper.getCallCount();
        loadUrlAsync(mAwContents, aboutPageUrl);
        mShouldInterceptRequestHelper.waitForCallback(callCount);
    }

    private static class EmptyInputStream extends InputStream {
        @Override
        public int available() {
            return 0;
        }

        @Override
        public int read() throws IOException {
            return -1;
        }

        @Override
        public int read(byte b[]) throws IOException {
            return -1;
        }

        @Override
        public int read(byte b[], int off, int len) throws IOException {
            return -1;
        }

        @Override
        public long skip(long n) throws IOException {
            if (n < 0)
                throw new IOException("skipping negative number of bytes");
            return 0;
        }
    }

    @SmallTest
    @Feature({"AndroidWebView"})
    public void testDoesNotCrashOnEmptyStream() throws Throwable {
        final String aboutPageUrl = addAboutPageToTestServer(mWebServer);

        mShouldInterceptRequestHelper.setReturnValue(
                new InterceptedRequestData("text/html", "UTF-8", new EmptyInputStream()));
        int shouldInterceptRequestCallCount = mShouldInterceptRequestHelper.getCallCount();
        int onPageFinishedCallCount = mContentsClient.getOnPageFinishedHelper().getCallCount();

        loadUrlAsync(mAwContents, aboutPageUrl);

        mShouldInterceptRequestHelper.waitForCallback(shouldInterceptRequestCallCount);
        mContentsClient.getOnPageFinishedHelper().waitForCallback(onPageFinishedCallCount);
    }

    private static class SlowInterceptedRequestData extends InterceptedRequestData {
        private CallbackHelper mReadStartedCallbackHelper = new CallbackHelper();
        private CountDownLatch mLatch = new CountDownLatch(1);

        public SlowInterceptedRequestData(String mimeType, String encoding, InputStream data) {
            super(mimeType, encoding, data);
        }

        @Override
        public InputStream getData() {
            mReadStartedCallbackHelper.notifyCalled();
            try {
                mLatch.await();
            } catch (InterruptedException e) {
                // ignore
            }
            return super.getData();
        }

        public void unblockReads() {
            mLatch.countDown();
        }

        public CallbackHelper getReadStartedCallbackHelper() {
            return mReadStartedCallbackHelper;
        }
    }

    @SmallTest
    @Feature({"AndroidWebView"})
    public void testDoesNotCrashOnSlowStream() throws Throwable {
        final String aboutPageUrl = addAboutPageToTestServer(mWebServer);
        final String aboutPageData = makePageWithTitle("some title");
        final String encoding = "UTF-8";
        final SlowInterceptedRequestData slowInterceptedRequestData =
            new SlowInterceptedRequestData("text/html", encoding,
                    new ByteArrayInputStream(aboutPageData.getBytes(encoding)));

        mShouldInterceptRequestHelper.setReturnValue(slowInterceptedRequestData);
        int callCount = slowInterceptedRequestData.getReadStartedCallbackHelper().getCallCount();
        loadUrlAsync(mAwContents, aboutPageUrl);
        slowInterceptedRequestData.getReadStartedCallbackHelper().waitForCallback(callCount);

        // Now the AwContents is "stuck" waiting for the SlowInputStream to finish reading so we
        // delete it to make sure that the dangling 'read' task doesn't cause a crash. Unfortunately
        // this will not always lead to a crash but it should happen often enough for us to notice.

        runTestOnUiThread(new Runnable() {
            @Override
            public void run() {
                getActivity().removeAllViews();
            }
        });
        destroyAwContentsOnMainSync(mAwContents);
        pollOnUiThread(new Callable<Boolean>() {
            @Override
            public Boolean call() {
                return AwContents.getNativeInstanceCount() == 0;
            }
        });

        slowInterceptedRequestData.unblockReads();
    }

    @SmallTest
    @Feature({"AndroidWebView"})
    public void testHttpStatusField() throws Throwable {
        final String syncGetUrl = mWebServer.getResponseUrl("/intercept_me");
        final String syncGetJs =
            "(function() {" +
            "  var xhr = new XMLHttpRequest();" +
            "  xhr.open('GET', '" + syncGetUrl + "', false);" +
            "  xhr.send(null);" +
            "  console.info('xhr.status = ' + xhr.status);" +
            "  return xhr.status;" +
            "})();";
        enableJavaScriptOnUiThread(mAwContents);

        final String aboutPageUrl = addAboutPageToTestServer(mWebServer);
        loadUrlSync(mAwContents, mContentsClient.getOnPageFinishedHelper(), aboutPageUrl);

        mShouldInterceptRequestHelper.setReturnValue(
                new InterceptedRequestData("text/html", "UTF-8", null));
        assertEquals("404",
                executeJavaScriptAndWaitForResult(mAwContents, mContentsClient, syncGetJs));

        mShouldInterceptRequestHelper.setReturnValue(
                new InterceptedRequestData("text/html", "UTF-8", new EmptyInputStream()));
        assertEquals("200",
                executeJavaScriptAndWaitForResult(mAwContents, mContentsClient, syncGetJs));
    }

    private String makePageWithTitle(String title) {
        return CommonResources.makeHtmlPageFrom("<title>" + title + "</title>",
                "<div> The title is: " + title + " </div>");
    }

    @SmallTest
    @Feature({"AndroidWebView"})
    public void testCanInterceptMainFrame() throws Throwable {
        final String expectedTitle = "testShouldInterceptRequestCanInterceptMainFrame";
        final String expectedPage = makePageWithTitle(expectedTitle);

        mShouldInterceptRequestHelper.setReturnValue(
                stringToInterceptedRequestData(expectedPage));

        final String aboutPageUrl = addAboutPageToTestServer(mWebServer);

        loadUrlSync(mAwContents, mContentsClient.getOnPageFinishedHelper(), aboutPageUrl);

        assertEquals(expectedTitle, getTitleOnUiThread(mAwContents));
        assertEquals(0, mWebServer.getRequestCount("/" + CommonResources.ABOUT_FILENAME));
    }

    @SmallTest
    @Feature({"AndroidWebView"})
    public void testDoesNotChangeReportedUrl() throws Throwable {
        mShouldInterceptRequestHelper.setReturnValue(
                stringToInterceptedRequestData(makePageWithTitle("some title")));

        final String aboutPageUrl = addAboutPageToTestServer(mWebServer);

        loadUrlSync(mAwContents, mContentsClient.getOnPageFinishedHelper(), aboutPageUrl);

        assertEquals(aboutPageUrl, mContentsClient.getOnPageFinishedHelper().getUrl());
        assertEquals(aboutPageUrl, mContentsClient.getOnPageStartedHelper().getUrl());
    }

    @SmallTest
    @Feature({"AndroidWebView"})
    public void testNullInputStreamCausesErrorForMainFrame() throws Throwable {
        final OnReceivedErrorHelper onReceivedErrorHelper =
            mContentsClient.getOnReceivedErrorHelper();

        mShouldInterceptRequestHelper.setReturnValue(
                new InterceptedRequestData("text/html", "UTF-8", null));

        final String aboutPageUrl = addAboutPageToTestServer(mWebServer);
        final int callCount = onReceivedErrorHelper.getCallCount();
        loadUrlAsync(mAwContents, aboutPageUrl);
        onReceivedErrorHelper.waitForCallback(callCount);
        assertEquals(0, mWebServer.getRequestCount("/" + CommonResources.ABOUT_FILENAME));
    }

    @SmallTest
    @Feature({"AndroidWebView"})
    public void testCalledForImage() throws Throwable {
        final String imagePath = "/" + CommonResources.FAVICON_FILENAME;
        mWebServer.setResponseBase64(imagePath,
                CommonResources.FAVICON_DATA_BASE64, CommonResources.getImagePngHeaders(true));
        final String pageWithImage =
            addPageToTestServer(mWebServer, "/page_with_image.html",
                    CommonResources.getOnImageLoadedHtml(CommonResources.FAVICON_FILENAME));

        int callCount = mShouldInterceptRequestHelper.getCallCount();
        loadUrlSync(mAwContents, mContentsClient.getOnPageFinishedHelper(), pageWithImage);
        mShouldInterceptRequestHelper.waitForCallback(callCount, 2);

        assertEquals(2, mShouldInterceptRequestHelper.getUrls().size());
        assertTrue(mShouldInterceptRequestHelper.getUrls().get(1).endsWith(
                CommonResources.FAVICON_FILENAME));
    }

    @SmallTest
    @Feature({"AndroidWebView"})
    public void testOnReceivedErrorCallback() throws Throwable {
        mShouldInterceptRequestHelper.setReturnValue(new InterceptedRequestData(null, null, null));
        OnReceivedErrorHelper onReceivedErrorHelper = mContentsClient.getOnReceivedErrorHelper();
        int onReceivedErrorHelperCallCount = onReceivedErrorHelper.getCallCount();
        loadUrlSync(mAwContents, mContentsClient.getOnPageFinishedHelper(), "foo://bar");
        onReceivedErrorHelper.waitForCallback(onReceivedErrorHelperCallCount, 1);
    }

    @SmallTest
    @Feature({"AndroidWebView"})
    public void testNoOnReceivedErrorCallback() throws Throwable {
        final String imagePath = "/" + CommonResources.FAVICON_FILENAME;
        final String imageUrl = mWebServer.setResponseBase64(imagePath,
                CommonResources.FAVICON_DATA_BASE64, CommonResources.getImagePngHeaders(true));
        final String pageWithImage =
                addPageToTestServer(mWebServer, "/page_with_image.html",
                        CommonResources.getOnImageLoadedHtml(CommonResources.FAVICON_FILENAME));
        mShouldInterceptRequestHelper.setReturnValueForUrl(
                imageUrl, new InterceptedRequestData(null, null, null));
        OnReceivedErrorHelper onReceivedErrorHelper = mContentsClient.getOnReceivedErrorHelper();
        int onReceivedErrorHelperCallCount = onReceivedErrorHelper.getCallCount();
        loadUrlSync(mAwContents, mContentsClient.getOnPageFinishedHelper(), pageWithImage);
        assertEquals(onReceivedErrorHelperCallCount, onReceivedErrorHelper.getCallCount());
    }

    @SmallTest
    @Feature({"AndroidWebView"})
    public void testCalledForIframe() throws Throwable {
        final String aboutPageUrl = addAboutPageToTestServer(mWebServer);
        final String pageWithIframe = addPageToTestServer(mWebServer, "/page_with_iframe.html",
                CommonResources.makeHtmlPageFrom("",
                    "<iframe src=\"" + aboutPageUrl + "\"/>"));

        int callCount = mShouldInterceptRequestHelper.getCallCount();
        loadUrlSync(mAwContents, mContentsClient.getOnPageFinishedHelper(), pageWithIframe);
        mShouldInterceptRequestHelper.waitForCallback(callCount, 2);
        assertEquals(2, mShouldInterceptRequestHelper.getUrls().size());
        assertEquals(aboutPageUrl, mShouldInterceptRequestHelper.getUrls().get(1));
    }

    private void calledForUrlTemplate(final String url) throws Exception {
        int callCount = mShouldInterceptRequestHelper.getCallCount();
        int onPageStartedCallCount = mContentsClient.getOnPageStartedHelper().getCallCount();
        loadUrlAsync(mAwContents, url);
        mShouldInterceptRequestHelper.waitForCallback(callCount);
        assertEquals(url, mShouldInterceptRequestHelper.getUrls().get(0));

        mContentsClient.getOnPageStartedHelper().waitForCallback(onPageStartedCallCount);
        assertEquals(onPageStartedCallCount + 1,
                mContentsClient.getOnPageStartedHelper().getCallCount());
    }

    private void notCalledForUrlTemplate(final String url) throws Exception {
        int callCount = mShouldInterceptRequestHelper.getCallCount();
        loadUrlSync(mAwContents, mContentsClient.getOnPageFinishedHelper(), url);
        // The intercepting must happen before onPageFinished. Since the IPC messages from the
        // renderer should be delivered in order waiting for onPageFinished is sufficient to
        // 'flush' any pending interception messages.
        assertEquals(callCount, mShouldInterceptRequestHelper.getCallCount());
    }

    @SmallTest
    @Feature({"AndroidWebView"})
    public void testCalledForUnsupportedSchemes() throws Throwable {
        calledForUrlTemplate("foobar://resource/1");
    }

    @SmallTest
    @Feature({"AndroidWebView"})
    public void testCalledForNonexistentFiles() throws Throwable {
        calledForUrlTemplate("file:///somewhere/something");
    }

    @SmallTest
    @Feature({"AndroidWebView"})
    public void testCalledForExistingFiles() throws Throwable {
        final String tmpDir = getInstrumentation().getTargetContext().getCacheDir().getPath();
        final String fileName = tmpDir + "/testfile.html";
        final String title = "existing file title";
        TestFileUtil.deleteFile(fileName);  // Remove leftover file if any.
        TestFileUtil.createNewHtmlFile(fileName, title, "");
        final String existingFileUrl = "file://" + fileName;

        int callCount = mShouldInterceptRequestHelper.getCallCount();
        int onPageFinishedCallCount = mContentsClient.getOnPageFinishedHelper().getCallCount();
        loadUrlAsync(mAwContents, existingFileUrl);
        mShouldInterceptRequestHelper.waitForCallback(callCount);
        assertEquals(existingFileUrl, mShouldInterceptRequestHelper.getUrls().get(0));

        mContentsClient.getOnPageFinishedHelper().waitForCallback(onPageFinishedCallCount);
        assertEquals(title, getTitleOnUiThread(mAwContents));
        assertEquals(onPageFinishedCallCount + 1,
                mContentsClient.getOnPageFinishedHelper().getCallCount());
    }

    @SmallTest
    @Feature({"AndroidWebView"})
    public void testNotCalledForExistingResource() throws Throwable {
        notCalledForUrlTemplate("file:///android_res/raw/resource_file.html");
    }

    @SmallTest
    @Feature({"AndroidWebView"})
    public void testCalledForNonexistentResource() throws Throwable {
        calledForUrlTemplate("file:///android_res/raw/no_file.html");
    }

    @SmallTest
    @Feature({"AndroidWebView"})
    public void testNotCalledForExistingAsset() throws Throwable {
        notCalledForUrlTemplate("file:///android_asset/asset_file.html");
    }

    @SmallTest
    @Feature({"AndroidWebView"})
    public void testCalledForNonexistentAsset() throws Throwable {
        calledForUrlTemplate("file:///android_res/raw/no_file.html");
    }

    @SmallTest
    @Feature({"AndroidWebView"})
    public void testNotCalledForExistingContentUrl() throws Throwable {
        final String contentResourceName = "target";
        final String existingContentUrl = TestContentProvider.createContentUrl(contentResourceName);

        notCalledForUrlTemplate(existingContentUrl);

        int contentRequestCount = TestContentProvider.getResourceRequestCount(
                getInstrumentation().getTargetContext(), contentResourceName);
        assertEquals(1, contentRequestCount);
    }

    @SmallTest
    @Feature({"AndroidWebView"})
    public void testCalledForNonexistentContentUrl() throws Throwable {
        calledForUrlTemplate("content://org.chromium.webview.NoSuchProvider/foo");
    }
}


text:
from __future__ import print_function

import authcode
from sqlalchemy_wrapper import SQLAlchemy

from helpers import SECRET_KEY

def test_user_model():
    db = SQLAlchemy('sqlite:///:memory:')
    auth = authcode.Auth(SECRET_KEY, db=db, roles=True)
    assert auth.users_model_name == 'User'
    assert auth.roles_model_name == 'Role'

    User = auth.User
    db.create_all()
    user = User(login=u'meh', password='foobar')
    db.session.add(user)
    db.commit()

    assert user.login == u'meh'
    assert user.email == user.login
    assert hasattr(user, 'password')
    assert hasattr(user, 'last_sign_in')
    assert repr(user) == '<User meh>'

def test_user_model_to_dict():
    db = SQLAlchemy('sqlite:///:memory:')
    auth = authcode.Auth(SECRET_KEY, db=db, roles=True)
    User = auth.User
    db.create_all()
    user = User(login=u'meh', password='foobar')
    db.session.add(user)
    db.commit()

    user_dict = user.to_dict()
    assert user_dict

def test_backwards_compatibility():
    db = SQLAlchemy('sqlite:///:memory:')
    auth = authcode.Auth(SECRET_KEY, db=db)
    User = auth.User
    db.create_all()
    user = User(login=u'meh', password='foobar')
    db.session.add(user)
    db.commit()

    assert user._password == user.password
    user._password = 'raw'
    assert user.password == 'raw'

def test_user_model_methods():
    db = SQLAlchemy('sqlite:///:memory:')
    auth = authcode.Auth(SECRET_KEY, db=db)
    User = auth.User
    db.create_all()
    user = User(login=u'meh', password='foobar')
    db.session.add(user)
    db.commit()

    assert User.by_id(user.id) == user
    assert User.by_id(33) is None

    assert User.by_login(u'meh') == user
    assert User.by_login(u'foobar') is None

    assert user.has_password('foobar')
    assert not user.has_password('abracadabra')

    assert user.get_token()
    assert user.get_uhmac()

def test_set_raw_password():
    db = SQLAlchemy('sqlite:///:memory:')
    auth = authcode.Auth(SECRET_KEY, db=db, roles=True)
    User = auth.User
    db.create_all()
    user = User(login=u'meh', password='foobar')
    db.session.add(user)
    db.session.commit()

    assert user.password != 'foobar'
    user.set_raw_password('foobar')
    assert user.password == 'foobar'

def test_role_model():
    db = SQLAlchemy('sqlite:///:memory:')
    auth = authcode.Auth(SECRET_KEY, db=db, roles=True)
    Role = auth.Role
    db.create_all()
    role = Role(name=u'admin')
    db.session.add(role)
    db.commit()

    assert role.name == u'admin'
    assert repr(role) == '<Role admin>'

def test_role_model_to_dict():
    db = SQLAlchemy('sqlite:///:memory:')
    auth = authcode.Auth(SECRET_KEY, db=db, roles=True)
    Role = auth.Role
    db.create_all()
    role = Role(name=u'admin')
    db.session.add(role)
    db.commit()

    role_dict = role.to_dict()
    assert role_dict

def test_role_model_methods():
    db = SQLAlchemy('sqlite:///:memory:')
    auth = authcode.Auth(SECRET_KEY, db=db, roles=True)
    Role = auth.Role
    db.create_all()
    role = Role(name=u'admin')
    db.session.add(role)
    db.commit()

    assert Role.by_id(role.id) == role
    assert Role.by_id(33) is None

    assert Role.by_name(u'admin') == role
    assert Role.by_name(u'foobar') is None

    assert Role.get_or_create(u'admin') == role

    role2 = Role.get_or_create(u'owner')
    db.commit()
    assert role2 != role
    assert db.query(Role).count() == 2

    assert list(role.users) == []
    assert list(role2.users) == []

def test_add_role():
    db = SQLAlchemy('sqlite:///:memory:')
    auth = authcode.Auth(SECRET_KEY, db=db, roles=True)
    User = auth.User
    Role = auth.Role
    db.create_all()
    user = User(login=u'meh', password='foobar')
    db.session.add(user)
    role = Role(name=u'loremipsum')
    db.session.add(role)
    db.session.commit()

    assert hasattr(auth, 'Role')
    assert hasattr(User, 'roles')

    # Add nonexistant role creates it
    user.add_role('admin')
    db.session.commit()
    assert user.has_role('admin')
    assert db.query(Role).count() == 2
    assert list(user.roles) == [Role.by_name('admin')]

    # Adding the same role does nothing
    user.add_role('admin')
    db.session.commit()
    assert user.has_role('admin')
    assert db.query(Role).count() == 2
    assert list(user.roles) == [Role.by_name('admin')]

    # Adding an existent role does not create a new one
    user.add_role('loremipsum')
    db.session.commit()
    assert user.has_role('loremipsum')

    result = sorted([role.name for role in user.roles])
    assert result == ['admin', 'loremipsum']
    assert db.query(Role).count() == 2

def test_remove_role():
    db = SQLAlchemy('sqlite:///:memory:')
    auth = authcode.Auth(SECRET_KEY, db=db, roles=True)
    User = auth.User
    Role = auth.Role
    db.create_all()
    user = User(login=u'meh', password='foobar')
    db.session.add(user)
    db.session.commit()

    assert hasattr(auth, 'Role')
    assert hasattr(User, 'roles')

    user.add_role('admin')
    db.session.commit()
    assert user.has_role('admin')
    assert db.query(Role).count() == 1

    # Removed from user but not deleted
    user.remove_role('admin')
    db.session.commit()
    assert not user.has_role('admin')
    assert list(user.roles) == []
    assert db.query(Role).count() == 1

    # Removing a role it doesn't have does nothing
    user.remove_role('admin')
    db.session.commit()
    assert not user.has_role('admin')
    assert list(user.roles) == []
    assert db.query(Role).count() == 1

    # Removing a nonexistant role does nothing
    user.remove_role('foobar')
    db.session.commit()
    assert db.query(Role).count() == 1

def test_models_mixins():
    db = SQLAlchemy('sqlite:///:memory:')

    class UserMixin(object):
        email = db.Column(db.Unicode(300))

        def __repr__(self):
            return 'overwrited'

    class RoleMixin(object):
        description = db.Column(db.UnicodeText)

    auth = authcode.Auth(SECRET_KEY, db=db, UserMixin=UserMixin, RoleMixin=RoleMixin)
    User = auth.User
    Role = auth.Role

    db.create_all()
    user = User(login=u'meh', password='foobar', email=u'text@example.com')
    db.session.add(user)
    db.flush()

    assert User.__tablename__ == 'users'
    assert user.login == u'meh'
    assert user.email == u'text@example.com'
    assert hasattr(user, 'password')
    assert hasattr(user, 'last_sign_in')
    assert repr(user) == 'overwrited'

    assert hasattr(Role, 'description')

def test_naked_sqlalchemy():
    from sqlalchemy import create_engine
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.orm import scoped_session, sessionmaker

    engine = create_engine('sqlite://')

    class DB(object):
        Session = scoped_session(sessionmaker(bind=engine))
        Model = declarative_base()

        @property
        def session(self):
            return self.Session()

    db = DB()
    auth = authcode.Auth(SECRET_KEY, db=db)

    User = auth.User
    db.Model.metadata.create_all(bind=engine)

    user = User(login=u'meh', password='foobar')
    db.session.add(user)
    db.session.commit()

    assert User.by_id(user.id) == user
    assert User.by_id(33) is None

    assert User.by_login(u'meh') == user
    assert User.by_login(u'foobar') is None

    assert user.has_password('foobar')
    assert not user.has_password('abracadabra')

    assert user.get_token()
    assert user.get_uhmac()


text:
package dns.hijacking;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;

import java.util.ArrayList;

/**
 * Created by ben on 2015/9/20.
 */
public class DnsHijackingHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
        System.out.println(packet);
        byte[] buffer = new byte[packet.content().readableBytes()];
        packet.content().readBytes(buffer);
        DnsRequest request = new DnsRequest(buffer, buffer.length);
        int txnId = request.getTxnId();
        ArrayList<DnsQuestion> questions = request.getQuestions();
        for (DnsQuestion question : questions) {

            HostRecord record = new HostRecord(question.getDomainName());
            String ip = Utils.APP.getProperty("hijacking.ipaddr");
            String[] ipstrs = ip.split("\\.");
            byte[] ipaddr = new byte[ipstrs.length];
            for (int i = 0; i < ipstrs.length; i++) {
                ipaddr[i] = (byte) Integer.parseInt(ipstrs[i]);
            }
            record.addIpAddress(new IPAddress(ipaddr));
            byte reply[] = DnsResponse.constructPacket(record, txnId);
            ctx.writeAndFlush(new DatagramPacket(Unpooled.wrappedBuffer(reply), packet.sender()));
        }
    }

}


text:
package com.seatgeek.placesautocomplete.model;

import java.util.Arrays;
import java.util.List;

/**
 * see {@link https://developers.google.com/places/documentation/details#PlaceDetailsResults} for
 * a breakdown of all the values in this object
 */
public final class PlaceDetails {

    public final List<AddressComponent> address_components;

    public final String formatted_address;

    public final String formatted_phone_number;

    public final String international_phone_number;

    public final PlaceGeometry geometry;

    public final String icon;

    public final String name;

    public final String place_id;

    public final OpenHours opening_hours;

    public final boolean permanently_closed;

    public final List<PlacePhoto> photos;

    public final PlaceScope scope;

    public final List<AlternativePlaceId> alt_ids;

    public final int price_level;

    public final double rating;

    public final List<PlaceReview> reviews;

    /**
     * see {@link https://developers.google.com/places/documentation/supported_types} for supported types
     */
    public final List<String> types;

    public final String url;

    public final String vicinity;

    public PlaceDetails(final List<AddressComponent> address_components,
                        final String formatted_address,
                        final String formatted_phone_number,
                        final String international_phone_number,
                        final PlaceGeometry geometry,
                        final String icon,
                        final String name,
                        final String place_id,
                        final OpenHours opening_hours,
                        final boolean permanently_closed,
                        final List<PlacePhoto> photos,
                        final PlaceScope scope,
                        final List<AlternativePlaceId> alt_ids,
                        final int price_level,
                        final double rating,
                        final List<PlaceReview> reviews,
                        final List<String> types,
                        final String url,
                        final String vicinity) {
        this.address_components = address_components;
        this.formatted_address = formatted_address;
        this.formatted_phone_number = formatted_phone_number;
        this.international_phone_number = international_phone_number;
        this.geometry = geometry;
        this.icon = icon;
        this.name = name;
        this.place_id = place_id;
        this.opening_hours = opening_hours;
        this.permanently_closed = permanently_closed;
        this.photos = photos;
        this.scope = scope;
        this.alt_ids = alt_ids;
        this.price_level = price_level;
        this.rating = rating;
        this.reviews = reviews;
        this.types = types;
        this.url = url;
        this.vicinity = vicinity;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof PlaceDetails)) return false;

        PlaceDetails that = (PlaceDetails) o;

        if (address_components != null ? !address_components.equals(that.address_components) : that.address_components != null) return false;
        if (formatted_address != null ? !formatted_address.equals(that.formatted_address) : that.formatted_address != null) return false;
        if (formatted_phone_number != null ? !formatted_phone_number.equals(that.formatted_phone_number) : that.formatted_phone_number != null) return false;
        if (international_phone_number != null ? !international_phone_number.equals(that.international_phone_number) : that.international_phone_number != null) return false;
        if (geometry != null ? !geometry.equals(that.geometry) : that.geometry != null) return false;
        if (icon != null ? !icon.equals(that.icon) : that.icon != null) return false;
        if (name != null ? !name.equals(that.name) : that.name != null) return false;
        if (place_id != null ? !place_id.equals(that.place_id) : that.place_id != null) return false;
        if (opening_hours != null ? !opening_hours.equals(that.opening_hours) : that.opening_hours != null) return false;
        if (permanently_closed != that.permanently_closed) return false;
        if (photos != null ? !photos.equals(that.photos) : that.photos != null) return false;
        if (scope != null ? !scope.equals(that.scope) : that.scope != null) return false;
        if (alt_ids != null ? !alt_ids.equals(that.alt_ids) : that.alt_ids != null) return false;
        if (address_components != null ? !address_components.equals(that.address_components) : that.address_components != null) return false;
        if (price_level != that.price_level) return false;
        if (rating != rating) return false;
        if (reviews != null ? !reviews.equals(that.reviews) : that.reviews != null) return false;
        if (types != null ? !types.equals(that.types) : that.types != null) return false;
        if (url != null ? !url.equals(that.url) : that.url != null) return false;
        if (vicinity != null ? !vicinity.equals(that.vicinity) : that.vicinity != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = address_components != null ? address_components.hashCode() : 0;
        result = 31 * result + (formatted_address != null ? formatted_address.hashCode() : 0);
        result = 31 * result + (formatted_phone_number != null ? formatted_phone_number.hashCode() : 0);
        result = 31 * result + (international_phone_number != null ? international_phone_number.hashCode() : 0);
        result = 31 * result + (geometry != null ? geometry.hashCode() : 0);
        result = 31 * result + (icon != null ? icon.hashCode() : 0);
        result = 31 * result + (name != null ? name.hashCode() : 0);
        result = 31 * result + (place_id != null ? place_id.hashCode() : 0);
        result = 31 * result + (opening_hours != null ? opening_hours.hashCode() : 0);
        result = 31 * result + (permanently_closed ? 1 : 0);
        result = 31 * result + (photos != null ? photos.hashCode() : 0);
        result = 31 * result + (scope != null ? scope.hashCode() : 0);
        result = 31 * result + (alt_ids != null ? alt_ids.hashCode() : 0);
        result = 31 * result + price_level;
        long ratingBits = Double.doubleToLongBits(rating);
        result = 31 * result + (int) (ratingBits ^ (ratingBits >>> 32));
        result = 31 * result + (reviews != null ? reviews.hashCode() : 0);
        result = 31 * result + (types != null ? types.hashCode() : 0);
        result = 31 * result + (url != null ? url.hashCode() : 0);
        result = 31 * result + (vicinity != null ? vicinity.hashCode() : 0);
        return result;
    }
}


text:
require 'rails_helper'

describe 'ApiApplications' do
  describe 'GET /api_applications' do
    context 'when not signed in' do
      it "redirects to 'users/sign_in'" do
        get api_applications_path
        expect(response.status).to be(302)
        expect(response).to redirect_to(new_user_session_path)
      end
    end

    context 'when signed in' do
      it 'returns a 200' do
        user = FactoryBot.create(:user)
        post(
          user_session_path,
          params: { user: { email: user.email, password: user.password } }
        )
        get api_applications_url
        follow_redirect!
        expect(response.status).to be(200)
      end
    end
  end
end


text:
'use strict';

var TestHelper = require('../../../TestHelper');

var TestContainer = require('mocha-test-container-support');

/* global bootstrapModeler, inject */

var propertiesPanelModule = require('lib'),
    domQuery = require('min-dom').query,
    domClasses = require('min-dom').classes,
    coreModule = require('cmmn-js/lib/core'),
    selectionModule = require('diagram-js/lib/features/selection').default,
    modelingModule = require('cmmn-js/lib/features/modeling'),
    propertiesProviderModule = require('lib/provider/cmmn');

function getInput(container, selector) {
  return domQuery('[' + selector + ']', container);
}

function getNameInput(container) {
  return getInput(domQuery('div[data-entry=name]', container), 'name=name');
}

function getDefinitionNameInput(container) {
  return getInput(domQuery('div[data-entry=definitionName]', container), 'name=name');
}

function getTextAnnotationNameInput(container) {
  return getInput(domQuery('div[data-entry=name]', container), 'name=text');
}

describe('name-properties', function() {

  var diagramXML = require('./Name.cmmn');

  var testModules = [
    coreModule, selectionModule, modelingModule,
    propertiesPanelModule,
    propertiesProviderModule
  ];

  var container;

  beforeEach(function() {
    container = TestContainer.get(this);
  });

  beforeEach(bootstrapModeler(diagramXML, {
    modules: testModules
  }));

  beforeEach(inject(function(commandStack, propertiesPanel) {

    var undoButton = document.createElement('button');
    undoButton.textContent = 'UNDO';

    undoButton.addEventListener('click', function() {
      commandStack.undo();
    });

    container.appendChild(undoButton);

    propertiesPanel.attachTo(container);
  }));

  describe('get', function() {

    var item, field, bo;

    it('should fetch the name for root', inject(function(elementRegistry, selection, propertiesPanel) {

      // given
      item = elementRegistry.get('CMMNDiagram_1');
      selection.select(item);

      field = getNameInput(propertiesPanel._container);
      bo = item.businessObject;

      // when selecting element

      // then
      expect(field.textContent).to.equal(bo.get('name'));

    }));

    it('should fetch the name for case plan model', inject(function(elementRegistry, selection, propertiesPanel) {

      // given
      item = elementRegistry.get('CasePlanModel_1');
      selection.select(item);

      field = getNameInput(propertiesPanel._container);
      bo = item.businessObject;

      // when selecting element

      // then
      expect(field.textContent).to.equal(bo.get('name'));

    }));

    it('should fetch the name for a plan item on part connection',
      inject(function(elementRegistry, selection, propertiesPanel) {

        // given
        item = elementRegistry.get('PlanItemOnPart_1_di');
        selection.select(item);

        field = getNameInput(propertiesPanel._container);
        bo = item.businessObject.cmmnElementRef;

        // when selecting element

        // then
        expect(field.textContent).to.equal(bo.get('name'));

      })
    );

    it('should fetch the name for a case file item on part connection',
      inject(function(elementRegistry, selection, propertiesPanel) {

        // given
        item = elementRegistry.get('CaseFileItemOnPart_1_di');
        selection.select(item);

        field = getNameInput(propertiesPanel._container);
        bo = item.businessObject.cmmnElementRef;

        // when selecting element

        // then
        expect(field.textContent).to.equal(bo.get('name'));

      })
    );

    it('should fetch the name from item', inject(function(elementRegistry, selection, propertiesPanel) {

      // given
      item = elementRegistry.get('PI_HumanTask_1');
      selection.select(item);

      field = getNameInput(propertiesPanel._container);
      bo = item.businessObject;

      // when selecting element

      // then
      expect(field.textContent).to.equal(bo.get('name'));

    }));

    it('should fetch the name from definition', inject(function(elementRegistry, selection, propertiesPanel) {

      // given
      item = elementRegistry.get('PI_HumanTask_2');
      selection.select(item);

      field = getNameInput(propertiesPanel._container);
      bo = item.businessObject;
      var definition = bo.definitionRef;

      // when selecting element

      // then
      expect(field.textContent).not.to.equal(bo.get('name'));
      expect(field.textContent).to.equal(definition.get('name'));

    }));

    it('should fetch the name from item (not from definition)', inject(function(elementRegistry, selection, propertiesPanel) {

      // given
      item = elementRegistry.get('PI_HumanTask_3');
      selection.select(item);

      field = getNameInput(propertiesPanel._container);
      bo = item.businessObject;

      // when selecting element

      // then
      expect(field.textContent).to.equal(bo.get('name'));

    }));

    it('should fetch the name from definition (not from item)', inject(function(elementRegistry, selection, propertiesPanel) {

      // given
      item = elementRegistry.get('PI_HumanTask_3');
      selection.select(item);

      field = getDefinitionNameInput(propertiesPanel._container);
      var definition = item.businessObject.definitionRef;

      // when selecting element

      // then
      expect(field.textContent).to.equal(definition.get('name'));

    }));

    it('should fetch the name from text annotation', inject(function(elementRegistry, selection, propertiesPanel) {

      // given
      item = elementRegistry.get('TextAnnotation_1');
      selection.select(item);

      field = getTextAnnotationNameInput(propertiesPanel._container);
      bo = item.businessObject;

      // when selecting element

      // then
      expect(field.textContent).to.equal(bo.get('text'));

    }));

  });

  describe('set', function() {

    describe('should set the name for an element', function() {

      var item, bo, field;

      describe('# root', function() {

        beforeEach(inject(function(elementRegistry, selection, propertiesPanel) {

          // given
          item = elementRegistry.get('CMMNDiagram_1');
          selection.select(item);

          bo = item.businessObject;
          field = getNameInput(propertiesPanel._container);

          // when
          TestHelper.triggerValue(field, 'foo', 'change');

        }));

        describe('in the DOM', function() {

          it('should execute', function() {
            expect(field.textContent).to.equal('foo');
          });

          it('should undo', inject(function(commandStack) {
            // when
            commandStack.undo();

            // then
            expect(field.textContent).to.equal('DIAGRAM');
          }));

          it('should redo', inject(function(commandStack) {
            // when
            commandStack.undo();
            commandStack.redo();

            // then
            expect(field.textContent).to.equal('foo');
          }));

        });

        describe('on the business object', function() {

          it('should execute', function() {
            expect(bo.get('name')).to.equal('foo');
          });

          it('should undo', inject(function(commandStack) {
            // when
            commandStack.undo();

            // then
            expect(bo.get('name')).to.equal('DIAGRAM');
          }));

          it('should redo', inject(function(commandStack) {
            // when
            commandStack.undo();
            commandStack.redo();

            // then
            expect(bo.get('name')).to.equal('foo');
          }));

        });

      });

      describe('# casePlanModel', function() {

        beforeEach(inject(function(elementRegistry, selection, propertiesPanel) {

          // given
          item = elementRegistry.get('CasePlanModel_1');
          selection.select(item);

          bo = item.businessObject;
          field = getNameInput(propertiesPanel._container);

          // when
          TestHelper.triggerValue(field, 'foo', 'change');

        }));

        describe('in the DOM', function() {

          it('should execute', function() {
            expect(field.textContent).to.equal('foo');
          });

          it('should undo', inject(function(commandStack) {
            // when
            commandStack.undo();

            // then
            expect(field.textContent).to.equal('A CasePlanModel');
          }));

          it('should redo', inject(function(commandStack) {
            // when
            commandStack.undo();
            commandStack.redo();

            // then
            expect(field.textContent).to.equal('foo');
          }));

        });

        describe('on the business object', function() {

          it('should execute', function() {
            expect(bo.get('name')).to.equal('foo');
          });

          it('should undo', inject(function(commandStack) {
            // when
            commandStack.undo();

            // then
            expect(bo.get('name')).to.equal('A CasePlanModel');
          }));

          it('should redo', inject(function(commandStack) {
            // when
            commandStack.undo();
            commandStack.redo();

            // then
            expect(bo.get('name')).to.equal('foo');
          }));

        });

      });

      describe('# itemCapable', function() {

        describe('# planItem', function() {

          beforeEach(inject(function(elementRegistry, selection, propertiesPanel) {

            // given
            item = elementRegistry.get('PI_HumanTask_1');
            selection.select(item);

            bo = item.businessObject;
            field = getNameInput(propertiesPanel._container);

            // when
            TestHelper.triggerValue(field, 'foo', 'change');

          }));

          describe('in the DOM', function() {

            it('should execute', function() {
              expect(field.textContent).to.equal('foo');
            });

            it('should undo', inject(function(commandStack) {
              // when
              commandStack.undo();

              // then
              expect(field.textContent).to.equal('ITEM');
            }));

            it('should redo', inject(function(commandStack) {
              // when
              commandStack.undo();
              commandStack.redo();

              // then
              expect(field.textContent).to.equal('foo');
            }));

          });

          describe('on the business object', function() {

            it('should execute', function() {
              expect(bo.get('name')).to.equal('foo');
            });

            it('should undo', inject(function(commandStack) {
              // when
              commandStack.undo();

              // then
              expect(bo.get('name')).to.equal('ITEM');
            }));

            it('should redo', inject(function(commandStack) {
              // when
              commandStack.undo();
              commandStack.redo();

              // then
              expect(bo.get('name')).to.equal('foo');
            }));

          });

        });

        describe('# discretionaryItem', function() {

          beforeEach(inject(function(elementRegistry, selection, propertiesPanel) {

            // given
            item = elementRegistry.get('DIS_Task_2');
            selection.select(item);

            bo = item.businessObject;
            field = getNameInput(propertiesPanel._container);

            // when
            TestHelper.triggerValue(field, 'foo', 'change');

          }));

          describe('in the DOM', function() {

            it('should execute', function() {
              expect(field.textContent).to.equal('foo');
            });

            it('should undo', inject(function(commandStack) {
              // when
              commandStack.undo();

              // then
              expect(field.textContent).to.equal('');
            }));

            it('should redo', inject(function(commandStack) {
              // when
              commandStack.undo();
              commandStack.redo();

              // then
              expect(field.textContent).to.equal('foo');
            }));

          });

          describe('on the business object', function() {

            it('should execute', function() {
              expect(bo.get('name')).to.equal('foo');
            });

            it('should undo', inject(function(commandStack) {
              // when
              commandStack.undo();

              // then
              expect(bo.get('name')).not.to.exist;
            }));

            it('should redo', inject(function(commandStack) {
              // when
              commandStack.undo();
              commandStack.redo();

              // then
              expect(bo.get('name')).to.equal('foo');
            }));

          });

        });

        describe('# caseFileItem', function() {

          beforeEach(inject(function(elementRegistry, selection, propertiesPanel) {

            // given
            item = elementRegistry.get('CaseFileItem_1');
            selection.select(item);

            bo = item.businessObject;
            field = getNameInput(propertiesPanel._container);

            // when
            TestHelper.triggerValue(field, 'foo', 'change');

          }));

          describe('in the DOM', function() {

            it('should execute', function() {
              expect(field.textContent).to.equal('foo');
            });

            it('should undo', inject(function(commandStack) {
              // when
              commandStack.undo();

              // then
              expect(field.textContent).to.equal('');
            }));

            it('should redo', inject(function(commandStack) {
              // when
              commandStack.undo();
              commandStack.redo();

              // then
              expect(field.textContent).to.equal('foo');
            }));

          });

          describe('on the business object', function() {

            it('should execute', function() {
              expect(bo.get('name')).to.equal('foo');
            });

            it('should undo', inject(function(commandStack) {
              // when
              commandStack.undo();

              // then
              expect(bo.get('name')).not.to.exist;
            }));

            it('should redo', inject(function(commandStack) {
              // when
              commandStack.undo();
              commandStack.redo();

              // then
              expect(bo.get('name')).to.equal('foo');
            }));

          });

        });

        describe('should set definition name in the DOM', function() {

          beforeEach(inject(function(elementRegistry, selection, propertiesPanel) {

            // given
            item = elementRegistry.get('PI_HumanTask_3');
            selection.select(item);

            bo = item.businessObject;
            field = getNameInput(propertiesPanel._container);

            // when
            TestHelper.triggerValue(field, '', 'change');

          }));

          it('should execute', function() {
            // then
            expect(field.textContent).to.equal('DEF');
          });

          it('should undo', inject(function(commandStack) {
            // when
            commandStack.undo();

            // then
            expect(field.textContent).to.equal('ITEM');
          }));

          it('should redo', inject(function(commandStack) {
            // when
            commandStack.undo();
            commandStack.redo();

            // then
            expect(field.textContent).to.equal('DEF');
          }));

        });

      });

      describe('# definition', function() {

        var definition;

        describe('# plan item definition', function() {

          beforeEach(inject(function(elementRegistry, selection, propertiesPanel) {

            // given
            item = elementRegistry.get('PI_HumanTask_3');
            selection.select(item);

            bo = item.businessObject;
            definition = bo.definitionRef;

            field = getDefinitionNameInput(propertiesPanel._container);

            // when
            TestHelper.triggerValue(field, 'foo', 'change');

          }));

          describe('in the DOM', function() {

            it('should execute', function() {
              // then
              expect(field.textContent).to.equal('foo');
            });

            it('should undo', inject(function(commandStack) {
              // when
              commandStack.undo();

              // then
              expect(field.textContent).to.equal('DEF');
            }));

            it('should redo', inject(function(commandStack) {
              // when
              commandStack.undo();
              commandStack.redo();

              // then
              expect(field.textContent).to.equal('foo');
            }));

          });

          describe('on the business object', function() {

            it('should execute', function() {
              expect(definition.get('name')).to.equal('foo');
            });

            it('should undo', inject(function(commandStack) {
              // when
              commandStack.undo();

              // then
              expect(definition.get('name')).to.equal('DEF');
            }));

            it('should redo', inject(function(commandStack) {
              // when
              commandStack.undo();
              commandStack.redo();

              // then
              expect(definition.get('name')).to.equal('foo');
            }));

          });

        });

        describe('# case file item definition', function() {

          beforeEach(inject(function(elementRegistry, selection, propertiesPanel) {

            // given
            item = elementRegistry.get('CaseFileItem_1');
            selection.select(item);

            bo = item.businessObject;
            definition = bo.definitionRef;

            field = getDefinitionNameInput(propertiesPanel._container);

            // when
            TestHelper.triggerValue(field, 'foo', 'change');

          }));

          describe('in the DOM', function() {

            it('should execute', function() {
              expect(field.textContent).to.equal('foo');
            });

            it('should undo', inject(function(commandStack) {
              // when
              commandStack.undo();

              // then
              expect(field.textContent).to.equal('');
            }));

            it('should redo', inject(function(commandStack) {
              // when
              commandStack.undo();
              commandStack.redo();

              // then
              expect(field.textContent).to.equal('foo');
            }));

          });

          describe('on the business object', function() {

            it('should execute', function() {
              expect(definition.get('name')).to.equal('foo');
            });

            it('should undo', inject(function(commandStack) {
              // when
              commandStack.undo();

              // then
              expect(definition.get('name')).not.to.exist;
            }));

            it('should redo', inject(function(commandStack) {
              // when
              commandStack.undo();
              commandStack.redo();

              // then
              expect(definition.get('name')).to.equal('foo');
            }));

          });

        });

      });

      describe('# connection', function() {

        describe('# plan item on part', function() {

          beforeEach(inject(function(elementRegistry, selection, propertiesPanel) {

            // given
            item = elementRegistry.get('PlanItemOnPart_1_di');
            selection.select(item);

            bo = item.businessObject.cmmnElementRef;
            field = getNameInput(propertiesPanel._container);

            // when
            TestHelper.triggerValue(field, 'foo', 'change');

          }));

          describe('in the DOM', function() {

            it('should execute', function() {
              expect(field.textContent).to.equal('foo');
            });

            it('should undo', inject(function(commandStack) {
              // when
              commandStack.undo();

              // then
              expect(field.textContent).to.equal('PLAN_ON_PART');
            }));

            it('should redo', inject(function(commandStack) {
              // when
              commandStack.undo();
              commandStack.redo();

              // then
              expect(field.textContent).to.equal('foo');
            }));

          });

          describe('on the business object', function() {

            it('should execute', function() {
              expect(bo.get('name')).to.equal('foo');
            });

            it('should undo', inject(function(commandStack) {
              // when
              commandStack.undo();

              // then
              expect(bo.get('name')).to.equal('PLAN_ON_PART');
            }));

            it('should redo', inject(function(commandStack) {
              // when
              commandStack.undo();
              commandStack.redo();

              // then
              expect(bo.get('name')).to.equal('foo');
            }));

          });

        });

        describe('# case file item on part', function() {

          beforeEach(inject(function(elementRegistry, selection, propertiesPanel) {

            // given
            item = elementRegistry.get('CaseFileItemOnPart_1_di');
            selection.select(item);

            bo = item.businessObject.cmmnElementRef;
            field = getNameInput(propertiesPanel._container);

            // when
            TestHelper.triggerValue(field, 'foo', 'change');

          }));

          describe('in the DOM', function() {

            it('should execute', function() {
              expect(field.textContent).to.equal('foo');
            });

            it('should undo', inject(function(commandStack) {
              // when
              commandStack.undo();

              // then
              expect(field.textContent).to.equal('CASE_ON_PART');
            }));

            it('should redo', inject(function(commandStack) {
              // when
              commandStack.undo();
              commandStack.redo();

              // then
              expect(field.textContent).to.equal('foo');
            }));

          });

          describe('on the business object', function() {

            it('should execute', function() {
              expect(bo.get('name')).to.equal('foo');
            });

            it('should undo', inject(function(commandStack) {
              // when
              commandStack.undo();

              // then
              expect(bo.get('name')).to.equal('CASE_ON_PART');
            }));

            it('should redo', inject(function(commandStack) {
              // when
              commandStack.undo();
              commandStack.redo();

              // then
              expect(bo.get('name')).to.equal('foo');
            }));

          });

        });

      });

      describe('# text annotation', function() {

        beforeEach(inject(function(elementRegistry, selection, propertiesPanel) {

          // given
          item = elementRegistry.get('TextAnnotation_1');
          selection.select(item);

          bo = item.businessObject;
          field = getTextAnnotationNameInput(propertiesPanel._container);

          // when
          TestHelper.triggerValue(field, 'foo', 'change');

        }));

        describe('in the DOM', function() {

          it('should execute', function() {
            expect(field.textContent).to.equal('foo');
          });

          it('should undo', inject(function(commandStack) {
            // when
            commandStack.undo();

            // then
            expect(field.textContent).to.equal('TEXT_ANNOTATION');
          }));

          it('should redo', inject(function(commandStack) {
            // when
            commandStack.undo();
            commandStack.redo();

            // then
            expect(field.textContent).to.equal('foo');
          }));

        });

        describe('on the business object', function() {

          it('should execute', function() {
            expect(bo.get('text')).to.equal('foo');
          });

          it('should undo', inject(function(commandStack) {
            // when
            commandStack.undo();

            // then
            expect(bo.get('text')).to.equal('TEXT_ANNOTATION');
          }));

          it('should redo', inject(function(commandStack) {
            // when
            commandStack.undo();
            commandStack.redo();

            // then
            expect(bo.get('text')).to.equal('foo');
          }));

        });

      });

    });

  });

  describe('control visibility', function() {

    function expectVisible(elementId, visible, getter) {

      if (!getter) {
        getter = getNameInput;
      }

      return inject(function(propertiesPanel, selection, elementRegistry) {

        // given
        var element = elementRegistry.get(elementId);

        // assume
        expect(element).to.exist;

        // when
        selection.select(element);
        var field = getter(propertiesPanel._container);

        // then
        if (visible) {
          expect(field).to.exist;
        } else {
          expect(field).not.to.exist;
        }
      });
    }

    describe('should show', function() {

      it('Root', expectVisible('CMMNDiagram_1', true));
      it('CasePlanModel', expectVisible('CasePlanModel_1', true));

      it('PlanItem', expectVisible('PI_HumanTask_1', true));
      it('DiscretionaryItem', expectVisible('DIS_Task_2', true));
      it('CaseFileItem', expectVisible('CaseFileItem_1', true));

      it('PlanItemDefinition', expectVisible('PI_HumanTask_1', true, getDefinitionNameInput));
      it('CaseFileItemDefinition', expectVisible('CaseFileItem_1', true, getDefinitionNameInput));

      it('CaseFileItemOnPart', expectVisible('CaseFileItemOnPart_1_di', true));
      it('PlanItemOnPart', expectVisible('PlanItemOnPart_1_di', true));

      it('TextAnnotation', expectVisible('TextAnnotation_1', true, getTextAnnotationNameInput));

    });

    describe('should hide', function() {

      it('Criterion', expectVisible('EntryCriterion_1', false));

      it('DiscretionaryConnection', expectVisible('DiscretionaryConnection_1', false));
      it('Association', expectVisible('Association_1_di', false));

    });

  });

  describe('validation', function() {

    describe('warnings', function() {

      it('should not be shown if item name is used',
        inject(function(elementRegistry, selection, propertiesPanel) {

          // given
          var shape = elementRegistry.get('PI_HumanTask_3');
          var container = propertiesPanel._container;

          // when
          selection.select(shape);

          // then
          var field = getNameInput(container);
          expect(domClasses(field).has('warning')).to.be.false;
        })
      );

      it('should be shown if definition name is used',
        inject(function(elementRegistry, selection, propertiesPanel) {

          // given
          var shape = elementRegistry.get('PI_HumanTask_2');
          var container = propertiesPanel._container;

          // when
          selection.select(shape);

          // then
          var field = getNameInput(container);
          expect(domClasses(field).has('warning')).to.be.true;
        })
      );

    });

  });

});


text:
var moment = require('moment');
var moment = require('moment-timezone');
var twix   = require('twix');

// var ts = new Timeseries({ base: '2014-01-01T00:00+01:00', interval: '15m', vector: [1,2,3,4] })
var Timeseries = function(ts) {
  if(ts){
    if(ts.base)     this.base     = ts.base;
    if(ts.interval) this.interval = ts.interval;
    if(ts.vector)   this.vector   = ts.vector;
    if(ts.changes)  this.changes  = ts.changes;
  }
}

Timeseries.prototype.fromCSV = function(csv){
  // return(ts);
}

Timeseries.prototype.toCSV = function(separator, format, timezone){

    if(!this || !this.base || !this.interval || !this.vector) return null;

    if(!separator) separator = ',';
    if(!timezone) timezone = "";

    var delta = parseInt(this.interval.match(/[0-9]+/));
    var unit  = this.interval.match(/s|m|h|d/).toString();

    var start = moment(this.base);
    var end   = moment(start)
    end.add(this.vector.length * delta, unit);

    var time = [];
    var iter = moment(start).twix(end).iterateInner(delta, unit);
    if(!timezone) while(iter.hasNext()) time.push(moment(iter.next()).format(format));
    if( timezone) while(iter.hasNext()) time.push(moment(iter.next()).tz(timezone).format(format));

    var lines = new Array(time.length);
    for(var i = 0; i < time.length; i++) lines[i] = time[i] + separator + this.vector[i];
    var csv = lines.join('\n');

    return(csv);
}

Timeseries.prototype.isValid = function(){

  if(!this)
    return false;

  if(!this.base)
    return false;

  if(!moment(this.base).isValid())
    return false;

  if(!this.interval)
    return false;

  if(typeof(this.interval) != 'string' || !this.interval.match("([0-9]+)(s|m|h|d)", "gi"))
    return false;

  if(!this.vector)
    return false;

  if(!(this.vector instanceof Array) || !this.vector.length)
    return false;

  return true;

}

Timeseries.prototype.isCompatible = function(ts){
}

Timeseries.prototype.add = function(ts){
}

Timeseries.prototype.subtract = function(){
}

// returns [ start, length ] for MongoDB
Timeseries.prototype.slice = function(from, to){

  if(!this.base || !this.interval || !from || !to) return null;

  from = this.roundUp(from);
  //to   = this.roundDown(to);

  var base = moment(this.base);
  var from = moment(from);
  var to   = moment(to);

  if(to.isSame(from)) return [];
  if(to.isBefore(base)) return [];
  if(to.isBefore(from)) return [];
  if(from.isBefore(base)) from = moment(base);

  var delta = this.delta();
  var unit  = this.unit();

  var start = Math.floor((from.valueOf() - base.valueOf()) / moment.duration(delta, unit).valueOf());
  var length = Math.floor((to.valueOf() - from.valueOf()) / moment.duration(delta, unit).valueOf()) + 1;

  return [ start, length ];

}

// Number of intervals
Timeseries.prototype.length = function(from, to, interval){

  var from = moment(from);
  var to   = moment(to);

  var delta = parseInt(interval.match(/[0-9]+/));
  var unit  = interval.match(/s|m|h|d/).toString();

  var length = Math.floor((to.valueOf() - from.valueOf()) / moment.duration(delta, unit).valueOf()) + 1;

  if(length < 1) length = 0;

  return length;
}

Timeseries.prototype.delta = function(){
  if(!this || !this.interval) return null;
  return parseInt(this.interval.match(/[0-9]+/));
}

Timeseries.prototype.unit = function(){
  if(!this || !this.interval) return null;
  return this.interval.match(/s|m|h|d/).toString();
}

// paste ts1 onto ts0
Timeseries.prototype.overlay = function(ts1){

  if(!ts1 || !ts1.interval || !ts1.base || !ts1.vector) return null;
  if(!this       || !this.interval       || !this.base       || !this.vector      ) return null;

  if(this.interval != ts1.interval) return null;

  var nts = new Timeseries({ base: "", interval: this.interval, vector: [], changes: this.changes });

  var base0 = moment(this.base);
  var base1 = moment(ts1.base);

  if(base1.isBefore(base0))
    nts.base = ts1.base;
  else
    nts.base = this.base;

  var base = moment(nts.base);

  var last0 = moment(base0);
  var last1 = moment(base1);
  last0.add(nts.delta() * this.vector.length, nts.unit());
  last1.add(nts.delta() * ts1.vector.length, nts.unit());

  var last;
  if(last1.isBefore(last0)) last = last0;
    else                    last = last1;

  var l = Timeseries.prototype.length(base, last, nts.interval) - 1;
  nts.vector = new Array(l);

  var d = Timeseries.prototype.length(base, base0, nts.interval) - 1;
  for(var i = 0; i < this.vector.length; i++) {
    nts.vector[d+i] = this.vector[i];
  }

  var d = Timeseries.prototype.length(base, base1, nts.interval) - 1;
  for(var i = 0; i < ts1.vector.length; i++) nts.vector[d+i] = ts1.vector[i];

  return nts;
}

Timeseries.prototype.NaNs = function(n){
  if(!n || n < 1) return [];
  var v = new Array(n);
  for(var i = 0; i < n; i++) v[i] = NaN;
  return v;
}

//test();*/

Timeseries.prototype.ones = function(n){
  if(!n || n < 1) return [];
  var v = new Array(n);
  for(var i = 0; i < n; i++) v[i] = 1;
  return v;
}

Timeseries.prototype.zeros = function(n){
  if(!n || n < 1) return [];
  var v = new Array(n);
  for(var i = 0; i < n; i++) v[i] = 0;
  return v;
}

// Distance between two timepoints ... edge case: from 2014-01-01T00:00+01:00 to 2014-01-02T00:00+01:00 is 24, not 25
Timeseries.prototype.distance = function(start, end, interval, float){

  var start = moment(start);
  var end   = moment(end);

  if(start.isSame(end)) return 0;

  var delta = parseInt(interval.match(/[0-9]+/));
  var unit  = interval.match(/s|m|h|d/).toString();

  var time1 = end.valueOf();
  var time0 = start.valueOf();
  var diff  = moment.duration(delta, unit).valueOf();

  var distance = (time1 - time0) / diff;

  if(!float){
    if(distance % 1 > 0) distance = Math.floor(distance) + 1;
    if(distance < 1) distance = 0;
  }

  return distance;
}

/* Padding */
Timeseries.prototype.pad = function(from, to){

  if(!from || !to) return null;

  //var newBase = this.distance(from, base);

  from = this.roundUp(from);
  //to   = this.roundDown(to);

  if(!this.vector.length || moment(to).isBefore(this.base)){
    var padding = this.distance(from, to, this.interval);
    return new Timeseries({ base: from, interval: this.interval, vector: this.NaNs(padding) });
  }

  if(this.vector.length != this.distance(from, to, this.interval)){
    var before = this.distance(from, this.base, this.interval);
    var after  = this.distance(from, to, this.interval) - this.vector.length - before;
    var before = this.NaNs(before);
    var after  = this.NaNs(after);
    var vector = before.concat(this.vector).concat(after);
    return new Timeseries({ base: from, interval: this.interval, vector: vector});
  }

  return new Timeseries({ base: from, interval: this.interval, vector: this.vector});
}

Timeseries.prototype.patch = function(object){
  if(!object) return this;
  object.base     = this.base;
  object.interval = this.interval;
  object.vector   = this.vector;
  return object;
}

/*var request = require('request');
var ts0 = new Timeseries({ base: '2014-01-01T00:00+01:00', interval: '15m', vector: [1,2,3,4] });
var ts1 = { _id: "ts001", _tags: ["ts", "test"] };
var ts = ts0.patch(ts1);
console.log(ts)
request.put({url: 'http://localhost/api/timeseries/ts001', json: ts }, function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body);
  }
});
*/

Timeseries.prototype.roundUp = function(date){
  var unit  = this.unit();
  var delta = this.delta();
  var diff  = this.distance(this.base, date, this.interval, true) % 1;
  var shift = (diff>0?1-diff:0-diff) * delta;
  var nbase = moment(date).add(shift, unit).format();
  return nbase;
}

Timeseries.prototype.roundDown = function(date){
  var unit  = this.unit();
  var delta = this.delta();
  var diff  = this.distance(this.base, date, this.interval, true) % 1;
  var shift = (diff<0?1+diff:0+diff) * delta;
  var nbase = moment(date).subtract(shift, unit).format();
  return nbase;
}

Timeseries.prototype.change = function(timeseries){
  if(!this.changes) this.changes = [];
  timeseries.timestamp = moment().format();
  this.changes.push(timeseries);
}

Timeseries.prototype.reconstruct = function(to){
  if(this.changes && this.changes.length){
    var ts0 = new Timeseries({ base: this.changes[0].base, interval: this.changes[0].interval, vector: this.changes[0].vector });
    this.changes.map(function(ts1){
      if(!to || (to && moment(ts1.timestamp).before(moment(to)))) ts0 = ts0.overlay(ts1);
    })
    this.base     = ts0.base;
    this.interval = ts0.interval;
    this.vector   = ts0.vector;
  }
}

Timeseries.prototype.toJSON = function(nan){

  var ts = { base: (this.base || ''), interval: (this.interval || ''), vector: (this.vector || []), changes: (this.changes || undefined)};

  if(nan) {
    // NaN handling... (always use NaN's, not null's): JSON does not have
    ts.vector = ts.vector.map(function(x){
      if(x === null || x == 'NaN') return NaN;
      return x;
    });
  }

  return(ts);
}

Timeseries.prototype.fromJSON = function(object) {
  if(object && object.base)     this.base     = object.base;
  if(object && object.interval) this.interval = object.interval;
  if(object && object.vector)   this.vector   = object.vector;
  if(object && object.changes)  this.changes  = object.changes;
}

module.exports = Timeseries;


text: export { FlowModeler20 as default } from "../../";


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/ly_drawer"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:fitsSystemWindows="true">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar_homepage"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:title="@string/homepage"
            app:popupTheme="@style/PopupTheme"
            app:navigationIcon="@drawable/icon_drawer"
            style="@style/ToolbarTheme"
            />

        <fragment
            android:id="@+id/fragment_homepage"
            android:name="com.genericdaily.app.fragment.HomePageFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            />

    </LinearLayout>

    <ListView
        android:id="@+id/lv_homepage_drawer"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="start"
        style="@style/lv_drawer"
        android:layoutAnimation="@anim/anim_layout"
        />

</android.support.v4.widget.DrawerLayout>


text:
function component (name, callback) {
    var $el = $('

');
    var componentUrl = 'components/' + name + '/' + name + '.html';
    $.get(componentUrl, function(tpl) {
        $el.append(tpl);
    }, 'text');
    return $el;
}