text:
package org.kie.services.client.api;

import java.net.URL;

import org.jboss.resteasy.client.ClientRequest;
import org.jboss.resteasy.client.ClientRequestFactory;
import org.jboss.resteasy.client.ClientResponse;
import org.jbpm.process.instance.impl.demo.DoNothingWorkItemHandler;
import org.junit.Assert;
import org.junit.Test;
import org.kie.api.runtime.process.WorkItemHandler;

public class RemoteApiTest extends Assert {

    @Test
    public void notAceptedMethodTest() throws Exception {
        URL deploymentUrl = new URL( "http://localhost:8080/kie-wb/" );
        RemoteRestRuntimeEngineFactory restSessionFactory
            = RemoteRestRuntimeEngineFactory.newBuilder()
                .addDeploymentId("deployment")
                .addUrl(deploymentUrl)
                .addUserName("mary")
                .addPassword("pass")
                .build();

        WorkItemHandler wih = new DoNothingWorkItemHandler();
        try {
            restSessionFactory.newRuntimeEngine().getKieSession().getWorkItemManager().registerWorkItemHandler("test", wih);
            fail( "The above call should have failed.");
        } catch( UnsupportedOperationException uoe ) {
            assertEquals("The .registerWorkItemHandler(..) method is not supported on the remote api.", uoe.getMessage());
        }
    }

    @Test
    public void reRequestTest() throws Exception {
        String urlString = "http://localhost:8080/appBase/";
        URL appBaseUrl = new URL(urlString);
        ClientRequestFactory factory = new ClientRequestFactory(appBaseUrl.toURI());

        String pathAdd = "/j_security_check";
        ClientRequest formRequest = factory.createRelativeRequest(pathAdd);
        formRequest.formParameter("test", "test");

        assertEquals(urlString + pathAdd , formRequest.getUri());
    }

}


text:
using UnityEngine;
using Swrve;
using Swrve.Helpers;
using System.Collections.Generic;

/// <summary>
/// Swrve SDK Unity3D Script. Use this script to easily include the SDK
/// in your scene.
/// </summary>
public class SwrveComponent : MonoBehaviour
{
    /// <summary>
    /// Instance of the Swrve SDK.
    /// </summary>
    public SwrveSDK SDK;

    /// <summary>
    /// ID for your game, as supplied by Swrve.
    /// </summary>
    public int GameId = 0;

    /// <summary>
    /// Secret API key, as supplied by Swrve.
    /// </summary>
    public string ApiKey = "your_api_key_here";

    /// <summary>
    /// SDK configuration.
    /// </summary>
    public SwrveConfig Config;

    /// <summary>
    /// Automatically flush events on application quit.
    /// </summary>
    public bool FlushEventsOnApplicationQuit = true;

    /// <summary>
    /// Automatically initialise the SDK on Start.
    /// </summary>
    public bool InitialiseOnStart = true;

    /// Singleton instance access.
    protected static SwrveComponent instance;

    /// <summary>
    /// Return a SwrveComponent located in the scene.
    /// </summary>
    public static SwrveComponent Instance
    {
        get {
            if (!instance) {
                // Obtain the first instance of the SwrveComponent in the scene
                SwrveComponent[] instances = Resources.FindObjectsOfTypeAll (typeof(SwrveComponent)) as SwrveComponent[];
                if (instances != null && instances.Length > 0) {
                    instance = instances [0];
                } else {
                    SwrveLog.LogError ("There needs to be one active SwrveComponent script on a GameObject in your scene.");
                }
            }

            return instance;
        }
    }

    /// <summary>
    /// Default constructor. Will be called by Unity when
    /// placing this script in your scene.
    /// </summary>
    public SwrveComponent ()
    {
        Config = new SwrveConfig ();
        SDK = new SwrveSDK ();
    }

    /// <summary>
    /// Manually initialize the SDK.
    /// </summary>
    /// <param name="gameId">
    /// ID for your game, as supplied by Swrve.
    /// </param>
    /// <param name="apiKey">
    /// Scret API key for your game, as supplied by Swrve.
    /// </param>
    public void Init (int gameId, string apiKey)
    {
        SDK.Init (this, gameId, apiKey, Config);
    }

    /// <summary>
    /// Initialize the SDK on start.
    /// </summary>
    public void Start ()
    {
        useGUILayout = false;
        if (InitialiseOnStart) {
            Init (GameId, ApiKey);
        }
    }

    /// <summary>
    /// Render in-app messages.
    /// </summary>
    public void OnGUI ()
    {
        SDK.OnGUI ();
    }

#if UNITY_IPHONE
    protected bool deviceTokenSent = false;
#endif

    public void Update ()
    {
        if (SDK != null && SDK.Initialised) {
            SDK.Update ();
#if UNITY_IPHONE
            if (!deviceTokenSent) {
                deviceTokenSent = SDK.ObtainIOSDeviceToken();
            }
            SDK.ProcessRemoteNotifications();
#endif
        }
    }

#if UNITY_ANDROID
    /// Called by the Google Cloud Messaging plugin to notify
    /// of a device registration id.
    public virtual void OnDeviceRegistered(string registrationId)
    {
        SwrveLog.LogError("Obtained registration id: " + registrationId);
        if (SDK != null && SDK.Initialised) {
            SDK.RegistrationIdReceived(registrationId);
        }
    }

    /// Called by the Google Cloud Messaging plugin to notify
    /// of a received push notification.
    public virtual void OnNotificationReceived(string notificationJson)
    {
        if (SDK != null && SDK.Initialised) {
            SDK.NotificationReceived(notificationJson);
        }
    }

    /// Called by the Google Cloud Messaging plugin to notify
    /// of the push notification that opened the app.
    public virtual void OnOpenedFromPushNotification(string notificationJson)
    {
        if (SDK != null && SDK.Initialised) {
            SDK.OpenedFromPushNotification(notificationJson);
        }
    }
#endif

    /// <summary>
    /// Stop all the work of the SDK.
    /// </summary>
    public void OnDestroy ()
    {
        if (SDK.Initialised) {
            SDK.OnSwrveDestroy ();
        }
        StopAllCoroutines ();
    }

    /// <summary>
    /// Automatically called by Unity3D when the application quits.
    /// </summary>
    public void OnApplicationQuit ()
    {
        if (SDK.Initialised && FlushEventsOnApplicationQuit) {
            SDK.OnSwrveDestroy ();
        }
    }

    /// <summary>
    /// Automatically called by Unity3D when the app is paused or resumed.
    /// </summary>
    public void OnApplicationPause (bool pauseStatus)
    {
        if (SDK != null && SDK.Initialised && Config != null && Config.AutomaticSessionManagement) {
            if (pauseStatus) {
                SDK.OnSwrvePause ();
            } else {
                SDK.OnSwrveResume ();
            }
        }

#if UNITY_IPHONE
        if (!pauseStatus) {
            // Refresh token after application resume
            deviceTokenSent = false;
        }
#endif
    }
}

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Caralluma flava N.E.Br.

### Remarks
null


text:
/**
* \file
* DebugFunction option using functor as a callback.
*/

#include <cstdlib>

#include <curlpp/cURLpp.hpp>
#include <curlpp/Easy.hpp>
#include <curlpp/Options.hpp>
#include <curlpp/Exception.hpp>

class MyWindow
{
public:
	int writeDebug(curl_infotype, char *data, size_t size)
	{
		fprintf(stderr, "Debug: ");
		fwrite(data, size, 1, stderr);
		return size;
	}
};

int main(int argc, char *argv[])
{

	if(argc != 2)
	{
		std::cerr	<< "Example 3: Wrong number of arguments" << std::endl
							<< "Example 3: Usage: example3 url"
							<< std::endl;
		return EXIT_FAILURE;
	}
	char *url = argv[1];

	MyWindow myWindow;

	try
	{
		curlpp::Cleanup cleaner;
		curlpp::Easy request;

		using namespace curlpp::Options;
		request.setOpt(Verbose(true));
		request.setOpt(DebugFunction(curlpp::types::DebugFunctionFunctor(&myWindow,
			&MyWindow::writeDebug)));
		request.setOpt(Url(url));

		request.perform();
	}

	catch ( curlpp::LogicError & e )
	{
		std::cout << e.what() << std::endl;
	}

	catch ( curlpp::RuntimeError & e )
	{
		std::cout << e.what() << std::endl;
	}

	return 0;
}


text:
package org.n3r.aoc.file.impl.filter.text;

public interface TextFileFieldValidator {
    Object validate(Object convertedValue, String fieldStringValue);
}


text:
<?php

namespace MwbExporter\Formatter\Doctrine2\ZF2InputFilterAnnotation;

use MwbExporter\Formatter\Doctrine2\Annotation\DatatypeConverter as BaseDatatypeConverter;

class DatatypeConverter extends BaseDatatypeConverter
{

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Qt 4.8: BrowserWindow.cpp Example File (demos/embedded/anomaly/src/BrowserWindow.cpp)</title>
  <link rel="stylesheet" type="text/css" href="style/style.css" />

  <link rel="stylesheet" type="text/css" href="style/superfish.css" />
  <link rel="stylesheet" type="text/css" href="style/narrow.css" />

      Home

    Qt Reference Documentation

Qt HOME

DEV

          DOC

BLOG

Qt 4.8

ALL VERSIONS

API Lookup

Class index

Function index

Modules

Namespaces

Global Declarations

QML elements

Qt Topics

Programming with Qt

Device UIs & Qt Quick

UI Design with Qt

Supported Platforms

Qt and Key Technologies

How-To's and Best Practices

Examples

Examples

Tutorials

Demos

QML Examples

          Search index:

          <form id="qtdocsearch" action="" onsubmit="return false;">
            <fieldset>
              <input type="text" name="searchstring" id="pageType" value="" />

 Close

All | API | Articles | Examples

 results:

            </fieldset>
          </form>

            API Lookup

Class index

Function index

Modules

Namespaces

Global Declarations

QML elements

            Qt Topics

Programming with Qt

Device UIs & Qt Quick

UI Design with Qt

Supported Platforms

Qt and Key Technologies

How-To's and Best Practices

            Examples

Examples

Tutorials

Demos

QML Examples

Home

A

A

A

                Print

BrowserWindow.cpp Example File

demos/embedded/anomaly/src/BrowserWindow.cpp

 #include "BrowserWindow.h"

 #include <QtCore>
 #include <QtGui>
 #include <QPropertyAnimation>
 #include <QResizeEvent>

 #include "BrowserView.h"
 #include "HomeView.h"

 BrowserWindow::BrowserWindow()
     : m_slidingSurface(new QWidget(this))
     , m_homeView(new HomeView(m_slidingSurface))
     , m_browserView(new BrowserView(m_slidingSurface))
     , m_animation(new QPropertyAnimation(this, "slideValue"))
 {
     m_slidingSurface->setAutoFillBackground(true);

     m_homeView->resize(size());

     m_browserView->resize(size());

     connect(m_homeView, SIGNAL(addressEntered(QString)), SLOT(gotoAddress(QString)));
     connect(m_homeView, SIGNAL(urlActivated(QUrl)), SLOT(navigate(QUrl)));

     connect(m_browserView, SIGNAL(menuButtonClicked()), SLOT(showHomeView()));

     m_animation->setDuration(200);
     connect(m_animation, SIGNAL(finished()), SLOT(animationFinished()));

     setSlideValue(0.0f);
 }

 void BrowserWindow::gotoAddress(const QString &address)
 {
     m_browserView->navigate(QUrl::fromUserInput(address));
     showBrowserView();
 }

 void BrowserWindow::animationFinished()
 {
     m_animation->setDirection(QAbstractAnimation::Forward);
 }

 void BrowserWindow::navigate(const QUrl &url)
 {
     m_browserView->navigate(url);
     showBrowserView();
 }

 void BrowserWindow::setSlideValue(qreal slideRatio)
 {
     // we use a ratio to handle resize corectly
     const int pos = -qRound(slideRatio * width());
     m_slidingSurface->scroll(pos - m_homeView->x(), 0);

     if (qFuzzyCompare(slideRatio, static_cast<qreal>(1.0f))) {
         m_browserView->show();
         m_homeView->hide();
     } else if (qFuzzyCompare(slideRatio, static_cast<qreal>(0.0f))) {
         m_homeView->show();
         m_browserView->hide();
     } else {
         m_browserView->show();
         m_homeView->show();
     }
 }

 qreal BrowserWindow::slideValue() const
 {
     Q_ASSERT(m_slidingSurface->x() < width());
     return static_cast<qreal>(qAbs(m_homeView->x())) / width();
 }

 void BrowserWindow::showHomeView()
 {
     m_animation->setStartValue(slideValue());
     m_animation->setEndValue(0.0f);
     m_animation->start();
     m_homeView->setFocus();
 }

 void BrowserWindow::showBrowserView()
 {
     m_animation->setStartValue(slideValue());
     m_animation->setEndValue(1.0f);
     m_animation->start();

     m_browserView->setFocus();
 }

 void BrowserWindow::keyReleaseEvent(QKeyEvent *event)
 {
     QWidget::keyReleaseEvent(event);

     if (event->key() == Qt::Key_F3) {
         if (m_animation->state() == QAbstractAnimation::Running) {
             const QAbstractAnimation::Direction direction =  m_animation->direction() == QAbstractAnimation::Forward
                                                              ? QAbstractAnimation::Forward
                                                                  : QAbstractAnimation::Backward;
             m_animation->setDirection(direction);
         } else if (qFuzzyCompare(slideValue(), static_cast<qreal>(1.0f)))
             showHomeView();
         else
             showBrowserView();
         event->accept();
     }
 }

 void BrowserWindow::resizeEvent(QResizeEvent *event)
 {
     const QSize oldSize = event->oldSize();
     const qreal oldSlidingRatio = static_cast<qreal>(qAbs(m_homeView->x())) / oldSize.width();

     const QSize newSize = event->size();
     m_slidingSurface->resize(newSize.width() * 2, newSize.height());

     m_homeView->resize(newSize);
     m_homeView->move(0, 0);

     m_browserView->resize(newSize);
     m_browserView->move(newSize.width(), 0);

     setSlideValue(oldSlidingRatio);
 }

      <acronym title="Copyright">©</acronym> 2013 Digia Plc and/or its
      subsidiaries. Documentation contributions included herein are the copyrights of
      their respective owners.

      The documentation provided herein is licensed under the terms of the
      GNU Free Documentation
      License version 1.3 as published by the Free Software Foundation.

      Documentation sources may be obtained from
      www.qt-project.org.

      Digia, Qt and their respective logos are trademarks of Digia Plc
      in Finland and/or other countries worldwide. All other trademarks are property
      of their respective owners. Privacy Policy


text:
class ChangeSqlVariableStyle < ActiveRecord::Migration[5.1]
  def up
    Query.transaction do
      Query.all.each do |query|
        query.update_attribute :sql, query.sql.gsub(/\%\{([^\}]+)\}/, ':\1')
      end
    end
  end

  def down
    Query.transaction do
      Query.all.each do |query|
        query.update_attribute :sql, query.sql.gsub(/:([a-zA-Z0-9_]+)/, '%{\1}')
      end
    end
  end
end


text: pip install gdapi-python


text:
import org.junit.Test;

import static org.assertj.core.api.Assertions.assertThat;

class Vertex {

    public String label;

    public boolean isVisited;

    public Vertex(String label) {

        this.label = label;
    }
}

class Grapi {

    int numOfVertices = 100;

    Vertex[] vertices;

    int[][] adjMatrix;

    int indicesCount = 0;

    public Grapi(int numOfVertices) {

        this.numOfVertices = numOfVertices;

        adjMatrix = new int[this.numOfVertices][this.numOfVertices];

        this.vertices = new Vertex[this.numOfVertices];

        initAdjMatrix();

    }

    void initAdjMatrix() {

        for (int i = 0; i < this.numOfVertices; i++) {
            for (int j = 0; j < this.numOfVertices; j++) {
                this.adjMatrix[i][j] = 0;
            }
        }
    }
}

public class GrapiTest {

    @Test
    public void bidi_Test() {

        assertThat(true).isEqualTo(true);
    }
}


text:
<?php

namespace Konani\VideoBundle\Services;

/**
 * Searches for a value of specified field and returns it's key if found or false if not found
 *
 * Class JsonHelper
 * @package Konani\VideoBundle\Services
 */
class ArraySearch
{
     /**
     * Returns key if found
     *
     * @param $videos
     * @param $field
     * @param $value
     * @return array
     */
    public function search($videos, $field, $value)
    {
        foreach($videos as $key => $video) {
            if ( $video[$field] === $value ) {
                return $key;
            }
        }
        return false;
    }
}


text:
import { Resource } from 'kolibri.lib.apiResource';

class LessonReportResource extends Resource {
  static resourceName() {
    return 'kolibri:coach:lessonreport';
  }
}

export default new LessonReportResource();


text:
using System;
using System.Collections.Generic;
using System.Linq;
using MassTransit;
using Nybus.MassTransit;

namespace Nybus.Configuration.ServiceBusFactories.Loopback
{
    public class LoopbackServiceBusFactory : IServiceBusFactory
    {
        public IBusControl CreateServiceBus(MassTransitOptions options, IReadOnlyList<Action<IReceiveEndpointConfigurator>> commandSubscriptions, IReadOnlyList<Action<IReceiveEndpointConfigurator>> eventSubscriptions)
        {
            return Bus.Factory.CreateUsingInMemory(cfg =>
            {
                cfg.UseJsonSerializer();
                cfg.UseConcurrencyLimit(options.ConcurrencyLimit);

                if (commandSubscriptions.Any())
                {
                    cfg.ReceiveEndpoint(options.CommandQueueNameStrategy.GetQueueName(), endpoint =>
                    {
                        endpoint.UseRetry(options.CommandErrorPolicy);

                        foreach (var subscription in commandSubscriptions)
                            subscription(endpoint);
                    });
                }

                if (eventSubscriptions.Any())
                {
                    cfg.ReceiveEndpoint(options.EventQueueNameStrategy.GetQueueName(), endpoint =>
                    {
                        endpoint.UseRetry(options.EventErrorPolicy);

                        foreach (var subscription in eventSubscriptions)
                            subscription(endpoint);
                    });
                }
            });
        }
    }
}


text:
package main

import "io"

type SizeReaderAt interface {
	io.ReaderAt
	Size() int64
}

// START_DOC OMIT
// NewChunkAlignedReaderAt returns a ReaderAt wrapper that is backed
// by a ReaderAt r of size totalSize where the wrapper guarantees that
// all ReadAt calls are aligned to chunkSize boundaries and of size
// chunkSize (except for the final chunk, which may be shorter).
//
// A chunk-aligned reader is good for caching, letting upper layers have
// any access pattern, but guarantees that the wrapped ReaderAt sees
// only nicely-cacheable access patterns & sizes.
func NewChunkAlignedReaderAt(r SizeReaderAt, chunkSize int) SizeReaderAt {
	// ...
	return nil // OMIT
}

// END_DOC OMIT


text:
![alt tag](https://raw2.github.com/Hypfer/hostapd-statistics/master/hostapd-statistics-demo.png)

Webinterface with statistics for Hostapd

FIRST! Read the Manpage

service hostapd-statistics start

--> ##hostapd on freenode
________________________________
Needs: socat, nmap, inotifywait, arp-scan, iw

Optional: vnstati, sensors, mplayer


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PawPrints
{
    public partial class AnimalDetailForm : Form
    {
        Animal animal;
        public AnimalDetailForm(Animal ani)
        {
            InitializeComponent();
            animal = ani;
        }

        private void AnimalForm_Load(object sender, EventArgs e)
        {
            //autofills form with current information on animal
            txtName.Text = animal.name;
            dtpBirthday.Value = animal.age;
            txtBreed.Text = animal.breed;
            txtAnimalType.Text = animal.animal_type;
            txtWeight.Text = animal.weight.ToString();
            txtSize.Text = animal.size;
            txtNotes.Text = animal.notes;
        }

        //redirects to AddEditForm
        private void btnEdit_Click(object sender, EventArgs e)
        {
            using (AddEditForm editForm = new AddEditForm(animal))
            {
                editForm.ShowDialog();
            }

            animal = WebHandeler.getAnimal(animal.id).Item1;
            AnimalForm_Load(sender, e);
        }

        //redirects to UploadByID form
        private void btnUpload_Click(object sender, EventArgs e)
        {
            using (UploadImageForm uploadForm = new UploadImageForm(false))
            {
                if(uploadForm.ShowDialog() == DialogResult.OK)
                {
                    string fname = uploadForm.filename;
                    WebHandeler.addPicture(fname, animal.id);
                }
            }

        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            WebHandeler.deleteAnimal(animal.id);
            this.Close();
        }
    }
}


text:
//******************************************************************************************************
//  CapBankRelay..cs - Gbtc
//
//  Copyright © 2020, Grid Protection Alliance.  All Rights Reserved.
//
//  Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
//  the NOTICE file distributed with this work for additional information regarding copyright ownership.
//  The GPA licenses this file to you under the MIT License (MIT), the "License"; you may
//  not use this file except in compliance with the License. You may obtain a copy of the License at:
//
//      http://opensource.org/licenses/MIT
//
//  Unless agreed to in writing, the subject software distributed under the License is distributed on an
//  "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
//  License for the specific language governing permissions and limitations.
//
//  Code Modification History:
//  ----------------------------------------------------------------------------------------------------
//  07/22/2020 - Christoph Lackner
//      Generated original version of source code.
//
//******************************************************************************************************

using System.ComponentModel.DataAnnotations;
using GSF.Data;
using GSF.Data.Model;

namespace openXDA.Model
{
    /// <summary>
    /// The following Lines are from Asset:
    /// 34 : VoltageKV
    ///
    /// The following Lines are Systemwide Settings
    /// 33
    /// </summary>
    [MetadataType(typeof(Asset))]
    public class CapBankRelay : Asset
    {
        #region [ Members ]

        #endregion

        #region [ Properties ]

        /// <summary>
        /// Line 35
        /// </summary>
        public double OnVoltageThreshhold { get; set; }

        public int CapBankNumber { get; set; }
        #endregion

        #region [ Methods ]

        public static CapBankRelay DetailedCapBankRelay(Asset asset, AdoDataConnection connection)
        {
            if ((object)connection == null)
                return null;

            TableOperations<CapBankRelay> capBankTable = new TableOperations<CapBankRelay>(connection);
            CapBankRelay capBank = capBankTable.QueryRecordWhere("ID = {0}", asset.ID);
            capBank.LazyContext = asset.LazyContext;
            capBank.ConnectionFactory = asset.ConnectionFactory;

            return capBank;
        }

        public static CapBankRelay DetailedCapBankRelay(Asset asset)
        {
            return DetailedCapBankRelay(asset, asset.ConnectionFactory.Invoke());
        }

        #endregion
    }
}


text:
<?php

use Phug\Cli;
use Pug\Optimizer;
use Pug\Pug;
use Pug\Test\AbstractTestCase;

class PugCachePerformanceTest extends AbstractTestCase
{
    protected function removeDirectory($directory)
    {
        foreach (scandir($directory) as $entity) {
            if ($entity === '.' || $entity === '..') {
                continue;
            }

            if (is_dir($directory.'/'.$entity)) {
                $this->removeDirectory($directory.'/'.$entity);
                continue;
            }

            @unlink($directory.'/'.$entity);
        }

        return @rmdir($directory);
    }

    protected function getPerformanceTemplate($template)
    {
        return TEMPLATES_DIRECTORY . DIRECTORY_SEPARATOR . 'performance' . DIRECTORY_SEPARATOR . $template . '.pug';
    }

    protected function getPhpFromTemplate($template)
    {
        return $this->getPhp(file_get_contents($this->getPerformanceTemplate($template)));
    }

    protected function getPhp($template)
    {
        $pug = new Pug([
            'debug' => false,
            'singleQuote' => false,
            'prettyprint' => false,
            'restrictedScope' => true,
        ]);

        return trim($pug->compile($template));
    }

    protected function getHtmlFromTemplate($template, array $vars = array())
    {
        $pug = new Pug([
            'debug' => true,
            'exit_on_error' => false,
            'singleQuote' => false,
            'prettyprint' => false,
            'restrictedScope' => true,
        ]);

        return trim($pug->render($this->getPerformanceTemplate($template), $vars));
    }

    /**
     * Cache weight.
     */
    public function testCacheWeight()
    {
        self::assertSame('
Hello world!
', $this->getPhp('p Hello world!'), 'Simple template should output simple code.');
    }

    /**
     * @group cli
     */
    public function testCliAndOptimizerTogether()
    {
        // Load the pug CLI command (will be ./vendor/bin/pug in real life).
        $command = escapeshellarg(realpath(__DIR__.'/../../pug'));

        // Working directory has a views directory and a cache directory.
        $baseDir = sys_get_temp_dir() . '/pug-' . mt_rand(0, 9999999);
        mkdir($baseDir, 0777, true);
        chdir($baseDir);
        mkdir('views', 0777, true);
        mkdir('cache', 0777, true);

        // Write a view sample with an include.
        file_put_contents('views/index.pug', "p=foo\ninclude inc.pug");
        file_put_contents('views/inc.pug', 'h1=bar');

        // Use cache option and no up_to_date_check
        $options = [
            'up_to_date_check' => false,
            'debug'            => false,
            'cache_dir'        => 'cache',
            'paths'            => ['views'],
        ];

        // On deploy, run ./vendor/bin/pug compile-directory views cache '{...}'
        // views and cache are the paths to the directories
        // {...} should be the same options you will use at runtime stringified as JSON
        $json = json_encode($options);

        exec("php $command compile-directory views cache '$json'", $cliOutput, $cliReturn);

        ob_start();

        $cli = new Cli('Pug\Facade', [
            'render',
            'renderFile',
            'renderDirectory',
            'compile',
            'compileFile',
            'compileDirectory' => 'textualCacheDirectory',
            'display'          => 'render',
            'displayFile'      => 'renderFile',
            'displayDirectory' => 'renderDirectory',
            'cacheDirectory'   => 'textualCacheDirectory',
        ]);

        $cliReturn = $cli->run([$command, 'compile-directory', 'views', 'cache', $json]);
        $cliOutput = ob_get_contents();

        ob_end_clean();

        // Optional step: the views directory is no longer needed as cached,
        // it can be emptied.
        unlink('views/index.pug');
        unlink('views/inc.pug');
        rmdir('views');

        // On runtime, use \Pug\Optimizer::call to render/display the pre-compiled views
        // with local variables
        $variables = [
            'foo' => 'FOO',
            'bar' => 'BAR',
        ];
        $content = Optimizer::call('renderFile', ['index', $variables], $options);

        // Unit test clean-up
        $this->removeDirectory($baseDir);

        $this->assertSame('
FOO

BAR
', $content);
        $this->assertTrue($cliReturn);
        $this->assertSame("2 templates cached.\n0 templates failed to be cached.\n", $cliOutput);
    }
}


text:
import Frame from './Frame';
import {Base64} from 'js-base64';

/**
 * Class containing recorded frames
 */
export default class Movie {

  /**
   * Create movie
   * @param {Object} opts Options
   * @param {Array<Frame|Object>} [opts.frames=[]] Array of frames
   * @param {number} [opts.top=0] Top position of the movie, relative to document
   * @param {number} [opts.left=0] Left position of the movie, relative to document
   * @param {number} [opts.scrollX=0] The initial horizontal scroll position inside player target
   * @param {number} [opts.scrollY=0] The initial vertical scroll position inside player target
   * @param {string} [opts.scene=''] Base64 encoded HTML string
   * @example
   * let frame = new cimice.Frame({eventType: 'click'});
   * let movie = new cimice.Movie({
   *     top: 100,
   *     left: 100,
   *     scene: 'SGFja2VyIERldGVjdGVkIQ==',
   *     frames: [
   *       {eventType: 'click'},
   *       frame,
   *       {eventType: 'mousemove'}
   *     ],
   * });
   */
  constructor(opts = {}) {
    this.top = opts.top || 0;
    this.left = opts.left || 0;
    this.scrollX = opts.scrollX || 0;
    this.scrollY = opts.scrollY || 0;
    this.scene = opts.scene || '';
    this.frames = [];
    let frames = opts.frames || [];

    for(let i = 0; i < frames.length; i++) {
      this.addFrame(new Frame(frames[i]));
    }
  }

  /**
   * Add new frame to the collection. If the object passed is an instance of Frame
   * it will added as it is, in case of simple object will create a new Frame
   * and set actual timestamp.
   * @param {Frame|Object} frame Frame instance or object
   * @returns {Frame|undefined} Added frame
   * @example
   * let frame1 = movie.addFrame({eventType: 'click'});
   * // Or
   * let frame = new cimice.Frame({eventType: 'click'});
   * let frame2 = movie.addFrame(frame);
   */
  addFrame(frame = {}) {
    let result;

    if(frame instanceof Frame ){
      result = frame;
    }else if(frame !== null && typeof frame === 'object'){
      result = new Frame(frame);
      let d = new Date();
      result.ts = d.getTime();
    }

    if(result){
      this.frames.push(result);
      return result;
    }
  }

  /**
   * Get the collection of frames
   * @returns {Array<Frame>} Array of frames
   */
  getFrames() {
    return this.frames;
  }

  /**
   * Set a new collection of frames.
   * @param {Frame|Object|Array<Frame|Object>} Array of frames or also a single Frame/object
   * @returns {this}
   * @example
   * let frame = new cimice.Frame({});
   * movie.setFrames(frame);
   * // frames -> 1
   * movie.setFrames([frame, {eventType: 'click'}]);
   * // frames -> 2
   * movie.setFrames({eventType: 'click'});
   * // frames -> 1
   */
  setFrames(frames) {
    let f = [].concat(frames || []);
    this.frames = [];
    for (let i = 0; i < f.length; i++) {
      this.addFrame(f[i]);
    }
    return this;
  }

  /**
   * Returns movie and related frames in JSON format. Generally coulde be used to extract data
   * during the recording and send back to server
   * @returns {string} JSON data
   * @example
   * let json = JSON.stringify(movie);
   * let xhr = new XMLHttpRequest();
   * xhr.open('POST', url);
   * xhr.send(json);
   */
  toJSON(){
    return {
      top: this.top,
      left: this.left,
      scrollX: this.scrollX,
      scrollY: this.scrollY,
      scene: this.scene,
      frames: this.frames,
    };
  }

  /**
   * Decode and cache base64 encoded scene
   * @return {string} Decoded scene
   * @private
   */
  getDecodedScene(){
    if(!this.sceneDecoded)
      this.sceneDecoded = Base64.decode(this.scene);
    return this.sceneDecoded;
  }
}


text:
package soapmocks.generic;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;

import javax.servlet.AsyncContext;
import javax.servlet.DispatcherType;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import org.apache.commons.io.IOUtils;

public final class BackupHttpServletRequest implements HttpServletRequest {

    private HttpServletRequest delegate;
    private byte[] body;

    BackupHttpServletRequest(HttpServletRequest delegate) {
	this.delegate = delegate;
    }

    @Override
    public Object getAttribute(String name) {
	return delegate.getAttribute(name);
    }

    @Override
    public String getAuthType() {
	return delegate.getAuthType();
    }

    @Override
    public Cookie[] getCookies() {
	return delegate.getCookies();
    }

    @Override
    public Enumeration<String> getAttributeNames() {
	return delegate.getAttributeNames();
    }

    @Override
    public long getDateHeader(String name) {
	return delegate.getDateHeader(name);
    }

    @Override
    public String getCharacterEncoding() {
	return delegate.getCharacterEncoding();
    }

    @Override
    public void setCharacterEncoding(String env)
	    throws UnsupportedEncodingException {
	delegate.setCharacterEncoding(env);
    }

    @Override
    public String getHeader(String name) {
	return delegate.getHeader(name);
    }

    @Override
    public int getContentLength() {
	return delegate.getContentLength();
    }

    @Override
    public String getContentType() {
	return delegate.getContentType();
    }

    @Override
    public Enumeration<String> getHeaders(String name) {
	return delegate.getHeaders(name);
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
	createBodyAsNeeded();
	final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
		body);
	ServletInputStream servletInputStream = new ServletInputStream() {
	    @Override
	    public int read() throws IOException {
		return byteArrayInputStream.read();
	    }
	};
	return servletInputStream;
    }

    @Override
    public String getParameter(String name) {
	return delegate.getParameter(name);
    }

    @Override
    public Enumeration<String> getHeaderNames() {
	return delegate.getHeaderNames();
    }

    @Override
    public int getIntHeader(String name) {
	return delegate.getIntHeader(name);
    }

    @Override
    public Enumeration<String> getParameterNames() {
	return delegate.getParameterNames();
    }

    @Override
    public String[] getParameterValues(String name) {
	return delegate.getParameterValues(name);
    }

    @Override
    public String getMethod() {
	return delegate.getMethod();
    }

    @Override
    public String getPathInfo() {
	return delegate.getPathInfo();
    }

    @Override
    public Map<String, String[]> getParameterMap() {
	return delegate.getParameterMap();
    }

    @Override
    public String getProtocol() {
	return delegate.getProtocol();
    }

    @Override
    public String getPathTranslated() {
	return delegate.getPathTranslated();
    }

    @Override
    public String getScheme() {
	return delegate.getScheme();
    }

    @Override
    public String getServerName() {
	return delegate.getServerName();
    }

    @Override
    public String getContextPath() {
	return delegate.getContextPath();
    }

    @Override
    public int getServerPort() {
	return delegate.getServerPort();
    }

    @Override
    public BufferedReader getReader() throws IOException {
	return delegate.getReader();
    }

    @Override
    public String getQueryString() {
	return delegate.getQueryString();
    }

    @Override
    public String getRemoteAddr() {
	return delegate.getRemoteAddr();
    }

    @Override
    public String getRemoteUser() {
	return delegate.getRemoteUser();
    }

    @Override
    public String getRemoteHost() {
	return delegate.getRemoteHost();
    }

    @Override
    public boolean isUserInRole(String role) {
	return delegate.isUserInRole(role);
    }

    @Override
    public void setAttribute(String name, Object o) {
	delegate.setAttribute(name, o);
    }

    @Override
    public Principal getUserPrincipal() {
	return delegate.getUserPrincipal();
    }

    @Override
    public String getRequestedSessionId() {
	return delegate.getRequestedSessionId();
    }

    @Override
    public void removeAttribute(String name) {
	delegate.removeAttribute(name);
    }

    @Override
    public String getRequestURI() {
	return delegate.getRequestURI();
    }

    @Override
    public Locale getLocale() {
	return delegate.getLocale();
    }

    @Override
    public Enumeration<Locale> getLocales() {
	return delegate.getLocales();
    }

    @Override
    public StringBuffer getRequestURL() {
	return delegate.getRequestURL();
    }

    @Override
    public boolean isSecure() {
	return delegate.isSecure();
    }

    @Override
    public RequestDispatcher getRequestDispatcher(String path) {
	return delegate.getRequestDispatcher(path);
    }

    @Override
    public String getServletPath() {
	return delegate.getServletPath();
    }

    @Override
    public HttpSession getSession(boolean create) {
	return delegate.getSession(create);
    }

    @Override
    @SuppressWarnings("deprecation")
    public String getRealPath(String path) {
	return delegate.getRealPath(path);
    }

    @Override
    public int getRemotePort() {
	return delegate.getRemotePort();
    }

    @Override
    public String getLocalName() {
	return delegate.getLocalName();
    }

    @Override
    public String getLocalAddr() {
	return delegate.getLocalAddr();
    }

    @Override
    public HttpSession getSession() {
	return delegate.getSession();
    }

    @Override
    public int getLocalPort() {
	return delegate.getLocalPort();
    }

    @Override
    public ServletContext getServletContext() {
	return delegate.getServletContext();
    }

    @Override
    public boolean isRequestedSessionIdValid() {
	return delegate.isRequestedSessionIdValid();
    }

    @Override
    public AsyncContext startAsync() throws IllegalStateException {
	return delegate.startAsync();
    }

    @Override
    public boolean isRequestedSessionIdFromCookie() {
	return delegate.isRequestedSessionIdFromCookie();
    }

    @Override
    public boolean isRequestedSessionIdFromURL() {
	return delegate.isRequestedSessionIdFromURL();
    }

    @Override
    @SuppressWarnings("deprecation")
    public boolean isRequestedSessionIdFromUrl() {
	return delegate.isRequestedSessionIdFromUrl();
    }

    @Override
    public boolean authenticate(HttpServletResponse response)
	    throws IOException, ServletException {
	return delegate.authenticate(response);
    }

    @Override
    public AsyncContext startAsync(ServletRequest servletRequest,
	    ServletResponse servletResponse) throws IllegalStateException {
	return delegate.startAsync(servletRequest, servletResponse);
    }

    @Override
    public void login(String username, String password) throws ServletException {
	delegate.login(username, password);
    }

    @Override
    public void logout() throws ServletException {
	delegate.logout();
    }

    @Override
    public Collection<Part> getParts() throws IOException, ServletException {
	return delegate.getParts();
    }

    @Override
    public boolean isAsyncStarted() {
	return delegate.isAsyncStarted();
    }

    @Override
    public Part getPart(String name) throws IOException, ServletException {
	return delegate.getPart(name);
    }

    @Override
    public boolean isAsyncSupported() {
	return delegate.isAsyncSupported();
    }

    @Override
    public AsyncContext getAsyncContext() {
	return delegate.getAsyncContext();
    }

    @Override
    public DispatcherType getDispatcherType() {
	return delegate.getDispatcherType();
    }

    private void createBodyAsNeeded() throws IOException {
	if (body == null) {
	    body = IOUtils.toByteArray(delegate.getInputStream());
	}
    }
}


text:
// <copyright file="EntityTagConverter.cs" company="Fubar Development Junker">
// Copyright (c) Fubar Development Junker. All rights reserved.
// </copyright>

using System.Xml.Linq;

using FubarDev.WebDavServer.Model.Headers;

namespace FubarDev.WebDavServer.Props.Converters
{
    /// <summary>
    /// Property converter for an <see cref="EntityTag"/>
    /// </summary>
    public class EntityTagConverter : IPropertyConverter<EntityTag>
    {
        /// <inheritdoc />
        public EntityTag FromElement(XElement element)
        {
            return EntityTag.FromXml(element);
        }

        /// <inheritdoc />
        public XElement ToElement(XName name, EntityTag value)
        {
            return value.ToXml();
        }

        /// <inheritdoc />
        public bool IsValidValue(EntityTag value)
        {
            return true;
        }
    }
}


text:
<?php

/*
	Class: SpotlightWidgetkitHelper
		Spotlight helper class
*/
class SpotlightWidgetkitHelper extends WidgetkitHelper {

	/* type */
	public $type;

	/* options */
	public $options;

	/*
		Function: Constructor
			Class Constructor.
	*/
	public function __construct($widgetkit) {
		parent::__construct($widgetkit);

		// init vars
		$this->type    = strtolower(str_replace('WidgetkitHelper', '', get_class($this)));
		$this->options = $this['system']->options;

		// register path
        $this['path']->register(dirname(__FILE__), $this->type);
	}

	/*
		Function: site
			Site init actions

		Returns:
			Void
	*/
	public function site() {

		$options = array();

		// get options
		foreach (array('duration' => 300) as $option => $value) {
			$val = $this->options->get('spotlight_'.$option, $value);
			$options[$option] = is_numeric($val) ? (float) $val : $val;
		}

		// is enabled ?
		if ($this->options->get('spotlight_enable', 1)) {

			$pluginPath = $this["path"]->url('spotlight:');
			$selector   = $this->options->get('spotlight_selector', '[data-spotlight]');
			$options    = json_encode($options);

			// add stylesheets/javascripts
			$this['asset']->addFile('css', 'spotlight:css/spotlight.css');
			$this['asset']->addString('js', "\$widgetkit.load('{$pluginPath}/js/spotlight.js').done(function(){jQuery(function($){ $('{$selector}').spotlight({$options}); });});");
		}

	}

	/*
		Function: dashboard
			Render dashboard layout

		Returns:
			Void
	*/
	public function dashboard() {

		// get xml
		$xml = simplexml_load_file($this['path']->path('spotlight:spotlight.xml'));

		// add js
        $this['asset']->addFile('js', 'spotlight:js/dashboard.js');

		// render dashboard
		echo $this['template']->render('spotlight:layouts/dashboard', compact('xml'));
	}

	/*
		Function: config
			Save configuration

		Returns:
			Void
	*/
	public function config() {

		// save configuration
	    foreach ($this['request']->get('post:', 'array') as $option => $value) {
	        if (preg_match('/^spotlight_/', $option)) {
				$this['system']->options->set($option, $value);
	        }
	    }

		$this['system']->saveOptions();
	}

}

// bind events
$widgetkit = Widgetkit::getInstance();
$widgetkit['event']->bind('site', array($widgetkit['spotlight'], 'site'));
$widgetkit['event']->bind('dashboard', array($widgetkit['spotlight'], 'dashboard'));
$widgetkit['event']->bind('task:config_spotlight', array($widgetkit['spotlight'], 'config'));


text:
title:  "Google Apps Email for your Domain"
date:   2009-10-17 00:00:00
categories:
tags:
comments: true
---
Google Apps has been around for some time but I have only recently used it to set-up email from a domain i.e. *user@mydomain.com*. It is straight forward to configure and you get allot for free using Standard Edition with up to 50 users with 7GB per user of email storage.

There are only two step required:

* Register for Google Apps Standard Edition
* Change your domains DNS MX record to point to the Google mail servers

How you change the MX record will depend on how your domain is managed but there are good instructions on this for the uninitiated.

For $50 per user per year you can upgrade  to the Premium Edition  which adds additional storage,  phone and email support and an  SLA. There is also information available on how to migrating from Microsoft Exchange.


text:
//-----------------------------------------------------------------------------
// Copyright (c) 2015, IBM Corp.
// All rights reserved.
//
// Distributed under the terms of the BSD Simplified License.
//
// The full license is in the LICENSE file, distributed with this software.
//
// You may not use this file except in compliance with the License.
//------------------------------------------------------------------------------

var stateTweetData = [];
var stateBoxOffieData = [];
var gTweet;
var gBoxOffice;

// DOM Ready =============================================================
initialize();

$(document).ready(function () {
  $('.scroll-top').hide();
  //Check to see if the window is top if not then display button
  $(window).scroll(function () {
  if ($(this).scrollTop() > 200) {
    $('.scroll-top').fadeIn();
  } else {
    $('.scroll-top').fadeOut();
  }
});

//Click event to scroll to top
$('.scroll-top').click(function () {
  $('html, body').animate({ scrollTop: 0 }, 800);
  return false;
  });
});

$('input[name="date-range-tweets-per-day"]').datepicker({
  changeMonth: true,
  changeYear: true,
  showButtonPanel: true,
}).focus(function() {
  var thisCalendar = $(this);
  $('.ui-datepicker-calendar').detach();
  $('.ui-datepicker-close').click(function() {
    var month = parseInt($("#ui-datepicker-div .ui-datepicker-month :selected").val())+1;
    var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
    thisCalendar.datepicker('setDate', new Date(year, month-1, 1));
    getData('tweetsperday', drawDailyTweets, month, year);
  });
});

$('input[name="date-range-tweets-over-time"]').datepicker({
  changeMonth: true,
  changeYear: true,
  showButtonPanel: true
}).focus(function() {
  var thisCalendar = $(this);
  $('.ui-datepicker-calendar').detach();
  $('.ui-datepicker-close').click(function() {
    var month = parseInt($("#ui-datepicker-div .ui-datepicker-month :selected").val())+1;
    var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
    thisCalendar.datepicker('setDate', new Date(year, month-1, 1));
    var state = $('.select-us-state option:selected').val();
    getData('sentimentsandcountovertime', drawSentimentCountOverTime, month, year, state);
  });
});

$('input[name="date-range-map1"]').daterangepicker({
  format: 'MM-DD-YYYY',
  startDate: '01/01/2014',
  endDate: moment(),
  minDate: '01/01/2014',
  maxDate: moment(),
  showDropdowns: true,
  showWeekNumbers: false,
  timePicker: false,
  ranges: {
     'Today': [moment(), moment()],
     'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
     'Last 7 Days': [moment().subtract(6, 'days'), moment()],
     'Last 30 Days': [moment().subtract(29, 'days'), moment()],
     'This Month': [moment().startOf('month'), moment().endOf('month')],
     'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
  },
  opens: 'left',
  drops: 'down',
  buttonClasses: ['btn', 'btn-sm'],
  applyClass: 'btn-primary',
  cancelClass: 'btn-default',
  separator: ' to ',
  locale: {
      applyLabel: 'Submit',
      cancelLabel: 'Cancel',
      fromLabel: 'From',
      toLabel: 'To',
      customRangeLabel: 'Custom',
      daysOfWeek: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr','Sa'],
      monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
      firstDay: 1
  }
}, function(start, end, label) {
  fetchTweetsJson(start.format('YYYY-MM-DD'), end.format('YYYY-MM-DD'));
});

var width = 960,
    height = 500,
    active = d3.select(null);

var projection = d3.geo.albersUsa()
    .scale(1000)
    .translate([width / 2, height / 2]);

var path = d3.geo.path()
    .projection(projection);

/* First Map */

var svg1 = d3.select(".map1").append("svg")
  .attr("width", width)
  .attr("height", height);

svg1.append("rect")
  .attr("class", "background")
  .attr("width", width)
  .attr("height", height)
  .on("click", reset);

function drawTweetsMap() {
  gTweet = svg1.append("g").style("stroke-width", "1.5px");

  d3.json("/javascripts/us.json", function(error, us) {

    var states = gTweet.selectAll("path")
      .data(topojson.feature(us, us.objects.states).features)
      .enter().append("path")
      .attr("d", path)
      .attr("class", "feature tooltips")
      .attr("id", function (d) {
        return d.id;
      })
      .style("fill", getTweetMapColor)
      .attr("title", getTweetTitle)
      // .html('
This is some information about whatever
')
      .on("mouseover", onMouseOverTweetMap)
      .on('mouseout', onMouseOutTweetMap);
      // .on("click", clicked);

    gTweet.append("path")
      .datum(topojson.mesh(us, us.objects.states, function(a, b) { return a !== b; }))
      .attr("class", "mesh")
      .attr("d", path);

    $('.tooltips').tooltipsy();

  });
}

function getTweetTitle(d) {
  var stateID = d.id.split("-")[1].toString();
  var title = 'No Data Available';
  if(stateTweetData["count"][stateID]) {
    var count = stateTweetData["count"][stateID];
    var name = stateTweetData["name"][stateID];
    title = name + ": " + count;
  }
  return title;
}

function onMouseOverTweetMap(d) {
  var nodeSelection = d3.select(this).style({opacity:'0.8'});
  var stateID = d.id.split("-")[1].toString();
  var display = '
Tweets Per State
No Data Available';
  if (stateTweetData["count"][stateID]) {
    var count = stateTweetData["count"][stateID];
    var name = stateTweetData["name"][stateID];
    display = '
Tweets Per State
' + name + ' : ' + count;
  }
  d3.select(".map1 .info").html(display);
}

function onMouseOutTweetMap(d) {
  var nodeSelection = d3.select(this).style({opacity:'1.0'});
  //nodeSelection.select("text").style({opacity:'0.8'});
  d3.select(".map1 .info").html('
Tweets Per State
Hover over a state to see');
}

// get color depending on population density value
function getTweetMapColor(d) {
  var stateID = d.id.split("-")[1].toString();
  var count = stateTweetData["count"][stateID];
  return count > 50000  ? '#800026' :
         count > 40000  ? '#BD0026' :
         count > 30000  ? '#E31A1C' :
         count > 20000  ? '#FC4E2A' :
         count > 10000  ? '#FD8D3C' :
         count > 5000   ? '#FEB24C' :
         count > 2000   ? '#FED976' :
         count > 0      ? '#FFEDA0' :
                          '#ccc';
}

var svg2 = d3.select(".map2").append("svg")
  .attr("width", width)
  .attr("height", height);

svg2.append("rect")
  .attr("class", "background")
  .attr("width", width)
  .attr("height", height)
  .on("click", reset);

function drawBoxOfficeMap() {
  gBoxOffice = svg2.append("g").style("stroke-width", "1.5px");

  d3.json("/javascripts/us.json", function(error, us) {
    var states = gBoxOffice.selectAll("path")
      .data(topojson.feature(us, us.objects.states).features)
      .enter().append("path")
      .attr("d", path)
      .attr("class", "feature tooltips")
      .attr("id", function (d) {
        return d.id;
      })
      .style("fill", getBoxOfficeMapColor)
      .attr("title", getBoxOfficeTitle)
      // .html('
This is some information about whatever
')
      .on("mouseover", onMouseOverBoxOfficeMap)
      .on('mouseout', onMouseOutBoxOfficeMap);
      // .on("click", clicked);

    gBoxOffice.append("path")
      .datum(topojson.mesh(us, us.objects.states, function(a, b) { return a !== b; }))
      .attr("class", "mesh")
      .attr("d", path);
  });
}

function getBoxOfficeTitle(d) {
  var title = 'No data available';
  var stateID = d.id.split("-")[1].toString();
  if(stateBoxOffieData["declineRate"][stateID]) {
    var declineRate = stateBoxOffieData["declineRate"][stateID];
    var name = stateBoxOffieData["name"][stateID];
    title =  name + ": " + declineRate + "%"
  }
  return title;
}

function onMouseOverBoxOfficeMap(d) {
  var nodeSelection = d3.select(this).style({opacity:'0.8'});
  //nodeSelection.select("text").style({opacity:'1.0'});
  var display = '
Tweet percentage left
No data available';
  var stateID = d.id.split("-")[1].toString();
  if(stateBoxOffieData["declineRate"][stateID]) {
    var declineRate = stateBoxOffieData["declineRate"][stateID];
    var name = stateBoxOffieData["name"][stateID];
    display = '
Tweet percentage left
' + name + ' : ' + declineRate + '%';
  }
  d3.select(".map2 .info").html(display);
}

function onMouseOutBoxOfficeMap(d) {
  var nodeSelection = d3.select(this).style({opacity:'1.0'});
  //nodeSelection.select("text").style({opacity:'0.8'});
  d3.select(".map2 .info").html('
Tweet percentage left
Hover over a state to see');
}

// get color depending on population density value
function getBoxOfficeMapColor(d) {
  var stateID = d.id.split("-")[1].toString();
  var rate = stateBoxOffieData["declineRate"][stateID];
  return rate > 15.0  ? '#234d20' :
         rate > 10.0  ? '#36802d' :
         rate > 8.0   ? '#77ab59' :
         rate > 5.0   ? '#c9df8a' :
         rate > 4.0   ? '#f9db57' :
         rate > 2.0   ? '#f8aa38' :
         rate > 1.0   ? '#f7614b' :
         rate >= 0.0   ? '#F5361A' :
                       '#ccc';
}

function clicked(d) {
  if (active.node() === this) return reset();
  active.classed("active", false);
  active = d3.select(this).classed("active", true);

  var bounds = path.bounds(d),
      dx = bounds[1][0] - bounds[0][0],
      dy = bounds[1][1] - bounds[0][1],
      x = (bounds[0][0] + bounds[1][0]) / 2,
      y = (bounds[0][1] + bounds[1][1]) / 2,
      scale = .9 / Math.max(dx / width, dy / height),
      translate = [width / 2 - scale * x, height / 2 - scale * y];

  g.transition()
      .duration(750)
      .style("stroke-width", 1.5 / scale + "px")
      .attr("transform", "translate(" + translate + ")scale(" + scale + ")");
}

function reset() {
  active.classed("active", false);
  active = d3.select(null);

  g.transition()
      .duration(750)
      .style("stroke-width", "1.5px")
      .attr("transform", "");
}

// Fill table with data
function fetchTweetsJson(start, end) {
  start = typeof start !== 'undefined' ? start : "2015-01-01";
  end = typeof end !== 'undefined' ? end : moment().format('YYYY-MM-DD');
  // jQuery AJAX call for JSON
  $.getJSON( '/api/service/get/data/visualize/tweetsperstate',
  {
    start: start,
    end: end
  }, function(result) {
    var stateCount = {};
    var stateNames = {};
    console.log(result)
    if(!result.err && result.data) {
      var data = result.data;
      for (var i = 0; i < data.length; i++) {
        if(data[i].STATECODE !== null) {
          stateCount[data[i].STATECODE] = data[i].COUNT;
          stateNames[data[i].STATECODE] = data[i].STATENAME;
        }
      };
      stateTweetData["count"] = stateCount;
      stateTweetData["name"] = stateNames;
      drawTweetsMap();
    } else {
      console.log("Error: Tweet Per State Data Returned is Invalid/Empty.");
    }
  });
  return false;
};

// Fill table with data
function fetchBoxOfficeJson(start, end) {
  // jQuery AJAX call for JSON
  $.getJSON( '/api/service/get/data/visualize/tweetsdeclinerate', function(result) {
    var stateDecRates = {};
    var stateNames = {};
    var num;
    if(!result.err && result.data) {
      var data = result.data;
      for (var i = 0; i < data.length; i++) {
        if(data[i].STATECODE !== null) {
          num = data[i].DECLINERATE;
          stateDecRates[data[i].STATECODE] = Math.round(num * 100) / 100;
          stateNames[data[i].STATECODE] = data[i].STATENAME;
        }
      };
      stateBoxOffieData["declineRate"] = stateDecRates;
      stateBoxOffieData["name"] = stateNames;
      drawBoxOfficeMap();
    } else {
      console.log("Error: Tweet Decline Rate Data Returned is Invalid/Empty.");
    }
  });
  return false;
};

function fetchUSstates() {
  $.getJSON('/api/service/get/data/list/usstates',
    function(result) {
      var select = $('.select-us-state');
      select.empty();
      $.each(result.data, function(key, value) {
        $(select)
          .append($("<option></option>")
          .attr("value",key)
          .text(value));
      });
  });
}

$('.select-us-state').on('change', function() {
  var date = $('input[name="date-range-tweets-over-time"]').datepicker("getDate");
  getData('sentimentsandcountovertime', drawSentimentCountOverTime, $.datepicker.formatDate("m", date), $.datepicker.formatDate("yy", date), this.value);
})

function initialize() {
  //$.getJSON( '/login', function(response) {
    // if(response && response.success) {
      getData('topmonth', drawGraphicsWithDatePicker);
      getData('topday', drawTopDay);
      getData('topstate', drawTopState);
      getData('topcity', drawTopCity);
      getData('topsentiment', drawTopSentiment);
      getData('topthreelanguages', drawDonut);
      getData('tweetcountpergender', drawGenderChart);
      getData('tweetscountpersentiment', drawDonut);
      getData('tweetspermonth', drawDailyTweets);
      getData('tweetscountpersentimentandlanguage', drawSentimentsPerLanugage);
      fetchUSstates();
      fetchTweetsJson();
      fetchChartJson(); //chart.js
      fetchBoxOfficeJson();
    //} else {
      //console.log("Error: Login Failed");
    //}
  //});
}

function getData(service, callback, start, end, extra) {
  var start = typeof start !== 'undefined' ? start : moment().format('MM'),
      end = typeof end !== 'undefined' ? end : moment().format('YYYY');

  $.getJSON('/api/service/get/data/visualize/'+service,
    {
      start: start,
      end: end,
      extra: extra
    },
    function(result) {
      callback(result.err, result.data, service)
  });
  return false;
}

function drawGraphicsWithDatePicker(err, data) {
  if(!err && data) {
    var date = new moment(data[0].DATE);
    $('input[name="date-range-tweets-per-day"]').val(date.format('MM/DD/YYYY'));
    getData('tweetsperday', drawDailyTweets, date.format('MM'), date.format('YYYY'), "ALL");
    $('input[name="date-range-tweets-over-time"]').val(date.format('MM/DD/YYYY'));
    getData('sentimentsandcountovertime', drawSentimentCountOverTime, date.format('MM'), date.format('YYYY'), "ALL");
  }
}

function drawTopCity(err, data) {
  if(!err && data) {
    $('.top-city h4').html(data[0].CITYNAME);
    $('.top-city h5').html('with ' + data[0].COUNT + ' Tweets');
  }
}

function drawTopState(err, data) {
  if(!err && data) {
    $('.top-state h4').html(data[0].STATENAME);
    $('.top-state h5').html('with ' + data[0].COUNT + ' Tweets');
  }
}

function drawTopDay(err, data) {
  if(!err && data) {
    $('.top-day h4').html(data[0].DAY);
    $('.top-day h5').html('with ' + data[0].COUNT + ' Tweets');
  }
}

function drawTopSentiment(err, data) {
  if(!err && data) {
    $('.top-sentiment h4').html(data[0].SENTIMENT);
    $('.top-sentiment h5').html('with ' + data[0].COUNT + ' Tweets');
  }
}

function drawDonut(err, dataset, service) {
  if(!err && dataset) {
    var chartClass;
    if(service.indexOf('language')>-1) {
      chartClass = "top-languages";
    } else {
      chartClass = "top-sentiments";
    }

    var width = 300;
    var height = 300;
    var radius = Math.min(width, height) / 2;
    var donutWidth = 60;
    var legendRectSize = 18;
    var legendSpacing = 4;

    var color = d3.scale.ordinal()
        .range(["#4CAF50", "#CC3333", "#FFCC00", "#2196F3"]);

    var svg = d3.select('.'+chartClass)
      .append('svg')
      .attr('width', width)
      .attr('height', height)
      .append('g')
      .attr('transform', 'translate(' + (width / 2) +
        ',' + (height / 2) + ')');

    var arc = d3.svg.arc()
      .innerRadius(radius - donutWidth)
      .outerRadius(radius);

    var pie = d3.layout.pie()
      .value(function(d) { return d.COUNT; })
      .sort(null);

    var tooltip = d3.select('.'+chartClass)
      .append('div')
      .attr('class', 'donut-tooltip');

    tooltip.append('div')
      .attr('class', 'label');

    tooltip.append('div')
      .attr('class', 'count');

    tooltip.append('div')
      .attr('class', 'percent');

    var path = svg.selectAll('path')
      .data(pie(dataset))
      .enter()
      .append('path')
      .attr('d', arc)
      .attr('fill', function(d, i) {
        return color(d.data.LABEL);
      });

    path.on('mouseover', function(d) {
      var total = d3.sum(dataset.map(function(d) {
        return d.COUNT;
      }));
      var percent = Math.round(1000 * d.data.COUNT / total) / 10;
      tooltip.select('.label').html(d.data.LABEL.toUpperCase());
      tooltip.select('.count').html(d.data.COUNT);
      tooltip.select('.percent').html(percent + '%');
      tooltip.style('display', 'block');
    });

    path.on('mouseout', function() {
      tooltip.style('display', 'none');
    });

    var legend = svg.selectAll('.legend')
      .data(color.domain())
      .enter()
      .append('g')
      .attr('class', 'legend')
      .attr('transform', function(d, i) {
        var height = legendRectSize + legendSpacing;
        var offset =  height * color.domain().length / 2;
        var horz = -3 * legendRectSize;
        var vert = i * height - offset;
        return 'translate(' + horz + ',' + vert + ')';
      });

    legend.append('rect')
      .attr('width', legendRectSize)
      .attr('height', legendRectSize)
      .style('fill', color)
      .style('stroke', color);

    legend.append('text')
      .attr('x', legendRectSize + legendSpacing)
      .attr('y', legendRectSize - legendSpacing)
      .text(function(d) { return d.toUpperCase(); });
  }
}

function drawGenderChart(err, data) {
  if(!err && data) {
    var margin = {top: 30, right: 10, bottom: 20, left: 70},
        width = 300 - margin.left - margin.right,
        height = 300 - margin.top - margin.bottom;

    var x = d3.scale.ordinal()
      .rangeRoundBands([0, width], .1);

    var y = d3.scale.linear()
        .range([height, 0]);

    var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom");

    var yAxis = d3.svg.axis()
        .scale(y)
        .orient("left");

    var svg = d3.select(".gender-tweets-count").append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

      x.domain(data.map(function(d) {return d.GENDER;}));
      y.domain([0, d3.max(data, function(d) {return d.COUNT; })]);

      svg.append("g")
          .attr("class", "x axis")
          .attr("transform", "translate(0," + height + ")")
          .call(xAxis);

      svg.append("g")
          .attr("class", "y axis")
          .call(yAxis)
        .append("text")
          .attr("transform", "rotate(-90)")
          .attr("y", 6)
          .attr("dy", ".71em")
          .style("text-anchor", "end")
          .text("Tweets");

      svg.selectAll(".bar")
          .data(data)
        .enter().append("rect")
          .attr("class", "bar")
          .attr("x", function(d) { return x(d.GENDER); })
          .attr("width", x.rangeBand())
          .attr("y", function(d) { return y(d.COUNT); })
          .attr("height", function(d) { return height - y(d.COUNT); });

    } else {
      console.log("Error: Tweet Count per Gender Data Returned is Invalid/Empty.");
    }
}

function filterData(data) {
  var obj;
  var next = false;
  var date = "";
  var fileteredData = [];
  for (var i = 0; i < data.length; i++) {
    if(date === data[i].DATE) {
      obj[data[i].SENTIMENT] = data[i].COUNT;
    } else {
      if(next) fileteredData.push(obj)
      obj = {DATE:data[i].DATE,POSITIVE:0,NEGATIVE:0,NEUTRAL:0,AMBIVALENT:0};
      date = data[i].DATE;
      obj[data[i].SENTIMENT] = data[i].COUNT;
      next = true;
    }
  };
  return filterData;
}

function drawDailyTweets(err, data, service) {
  if(!err && data) {
    var chartclass, chartformat, incomingFormat;
    if(service.indexOf('day')>-1){
      chartclass = ".day-tweets-count";
      incomingFormat = "%Y-%m-%d";
      chartformat = "%d";
    } else {
      chartclass = ".monthly-tweets-count";
      incomingFormat = "%Y-%m";
      chartformat = "%b";
    }

    var margin = {top: 50, right: 55, bottom: 30, left: 75},
      width  = 1000 - margin.left - margin.right,
      height = 500  - margin.top  - margin.bottom,
      parse = d3.time.format(incomingFormat).parse,
      format = d3.time.format(chartformat);

    var x = d3.scale.ordinal()
        .rangeRoundBands([0, width], .1);
    var y = d3.scale.linear()
        .rangeRound([height, 0]);
    var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom");
    var yAxis = d3.svg.axis()
        .scale(y)
        .orient("left");
    var color = d3.scale.ordinal()
        .range(["#4CAF50", "#CC3333", "#FFCC00", "#2196F3"]);

    var svg = d3.select(chartclass).html("").append("svg")
    .attr("width",  '100%')
    .attr("height", height + margin.top  + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    var labelVar = 'DATE';
    var varNames = d3.keys(data[0]).filter(function (key) { return key !== labelVar;});
    color.domain(varNames);

    data.forEach(function (d) {
      var y0 = 0;
      d.mapping = varNames.map(function (name) {
        return {
          name: name,
          label: d[labelVar],
          y0: y0,
          y1: y0 += +d[name]
        };
      });
      d.total = d.mapping[d.mapping.length - 1].y1;
    });

    x.domain(data.map(function (d) { return format(parse(d.DATE)); }));
    y.domain([0, d3.max(data, function (d) { return d.total; })]);

    svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);

    svg.append("g")
        .attr("class", "y axis")
        .call(yAxis)
      .append("text")
        .attr("transform", "rotate(-90)")
        .attr("y", 6)
        .attr("dy", ".71em")
        .style("text-anchor", "end")
        .text("Number of Tweets");

    var selection = svg.selectAll(".series")
        .data(data)
      .enter().append("g")
        .attr("class", "series")
        .attr("transform", function (d) { return "translate(" + x(format(parse(d.DATE))) + ",0)"; });

    selection.selectAll("rect")
      .data(function (d) { return d.mapping; })
    .enter().append("rect")
      .attr("width", x.rangeBand())
      .attr("y", function (d) { return y(d.y1); })
      .attr("height", function (d) { return y(d.y0) - y(d.y1); })
      .style("fill", function (d) { return color(d.name); })
      .style("stroke", "grey")
      .on("mouseover", function (d) { showPopover.call(this, d); })
      .on("mouseout",  function (d) { removePopovers(); })

    var legend = svg.selectAll(".legend")
        .data(varNames.slice().reverse())
      .enter().append("g")
        .attr("class", "legend")
        .attr("transform", function (d, i) { return "translate(90," + i * 20 + ")"; });
    legend.append("rect")
        .attr("x", width - 18)
        .attr("width", 18)
        .attr("height", 18)
        .style("fill", color);
    legend.append("text")
        .attr("x", width - 18)
        .attr("y", 9)
        .attr("dy", ".35em")
        .style("text-anchor", "end")
        .text(function (d) { return d; });

    function removePopovers () {
      $('.popover').each(function() {
        $(this).remove();
      });
    }
    function showPopover (d) {
      $(this).popover({
        title: d.name,
        placement: 'auto top',
        container: 'body',
        trigger: 'manual',
        html : true,
        content: function() {
          return "Date: " + d.label +
                 "
Tweets: " + d3.format(",")(d.value ? d.value: d.y1 - d.y0); }
      });
      $(this).popover('show')
    }
  }
}

function drawSentimentCountOverTime (err, data) {
  if(!err && data) {
    var incomingFormat = "%Y-%m-%d",
        chartformat = "%d";
        parse = d3.time.format(incomingFormat).parse,
        format = d3.time.format(chartformat);

    var margin = {top: 50, right: 55, bottom: 30, left: 75},
        width  = 1000 - margin.left - margin.right,
        height = 500  - margin.top  - margin.bottom;
    var x = d3.scale.ordinal()
        .rangeRoundBands([0, width], .1);
    var y = d3.scale.linear()
        .rangeRound([height, 0]);
    var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom");
    var yAxis = d3.svg.axis()
        .scale(y)
        .orient("left");
    var stack = d3.layout.stack()
        .offset("zero")
        .values(function (d) { return d.values; })
        .x(function (d) { return x(d.label) + x.rangeBand() / 2; })
        .y(function (d) { return d.value; });
    var area = d3.svg.area()
        .interpolate("cardinal")
        .x(function (d) { return x(d.label) + x.rangeBand() / 2; })
        .y0(function (d) { return y(d.y0); })
        .y1(function (d) { return y(d.y0 + d.y); });

    var color = d3.scale.ordinal()
        .range(["#4CAF50", "#CC3333", "#FFCC00", "#2196F3"]);
    var svg = d3.select(".sentiments-tweets-count-over-time").html("").append("svg")
        .attr("width",  '100%')
        .attr("height", height + margin.top  + margin.bottom)
      .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    var labelVar = 'DATE';
    var varNames = d3.keys(data[0])
        .filter(function (key) { return key !== labelVar;});
    color.domain(varNames);

    var seriesArr = [], series = {};
    varNames.forEach(function (name) {
      series[name] = {name: name, values:[]};
      seriesArr.push(series[name]);
    });

    data.forEach(function (d) {
      varNames.map(function (name) {
        series[name].values.push({name: name, label: format(parse(d[labelVar])), value: +d[name]});
      });
    });

    x.domain(data.map(function (d) { return format(parse(d.DATE)); }));
    stack(seriesArr);

    y.domain([0, d3.max(seriesArr, function (c) {
      return d3.max(c.values, function (d) { return d.y0 + d.y; });
    })]);

    svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);
    svg.append("g")
        .attr("class", "y axis")
        .call(yAxis)
      .append("text")
        .attr("transform", "rotate(-90)")
        .attr("y", 6)
        .attr("dy", ".71em")
        .style("text-anchor", "end")
        .text("Number of Tweets");

    var selection = svg.selectAll(".series")
      .data(seriesArr)
      .enter().append("g")
        .attr("class", "series");
    selection.append("path")
      .attr("class", "streamPath")
      .attr("d", function (d) { return area(d.values); })
      .style("fill", function (d) { return color(d.name); })
      .style("stroke", "grey");

    var points = svg.selectAll(".seriesPoints")
      .data(seriesArr)
      .enter().append("g")
        .attr("class", "seriesPoints");
    points.selectAll(".point")
      .data(function (d) { return d.values; })
      .enter().append("circle")
       .attr("class", "point")
       .attr("cx", function (d) { return x(d.label) + x.rangeBand() / 2; })
       .attr("cy", function (d) { return y(d.y0 + d.y); })
       .attr("r", "10px")
       .style("fill",function (d) { return color(d.name); })
       .on("mouseover", function (d) { showPopover.call(this, d); })
       .on("mouseout",  function (d) { removePopovers(); })

    var legend = svg.selectAll(".legend")
        .data(varNames.slice().reverse())
      .enter().append("g")
        .attr("class", "legend")
        .attr("transform", function (d, i) { return "translate(90," + i * 20 + ")"; });
    legend.append("rect")
        .attr("x", width - 18)
        .attr("width", 18)
        .attr("height", 18)
        .style("fill", color);
    legend.append("text")
        .attr("x", width - 18)
        .attr("y", 9)
        .attr("dy", ".35em")
        .style("text-anchor", "end")
        .text(function (d) { return d; });

    function removePopovers () {
      $('.popover').each(function() {
        $(this).remove();
      });
    }
    function showPopover (d) {
      $(this).popover({
        title: d.name,
        placement: 'auto top',
        container: 'body',
        trigger: 'manual',
        html : true,
        content: function() {
          return "Date: " + d.label +
                 "
Tweets: " + d3.format(",")(d.value ? d.value: d.y1 - d.y0); }
      });
      $(this).popover('show')
    }
  }
}

function drawSentimentsPerLanugage(err, data) {
  if(!err && data) {
  var margin = {top: 50, right: 55, bottom: 30, left: 75},
      width = 1000 - margin.left - margin.right,
      height = 500 - margin.top - margin.bottom;

  var x0 = d3.scale.ordinal()
      .rangeRoundBands([0, width], 0.1);

  var x1 = d3.scale.ordinal();

  var y = d3.scale.linear()
      .range([height, 0]);

  var xAxis = d3.svg.axis()
      .scale(x0)
      .orient("bottom");

  var yAxis = d3.svg.axis()
      .scale(y)
      .orient("left")
      .tickFormat(d3.format(".2s"));

    var color = d3.scale.ordinal()
        .range(["#4CAF50", "#CC3333", "#FFCC00", "#2196F3"]);

  var svg = d3.select(".sentiments-tweets-count-per-lanugage").append("svg")
      .attr("width",  '100%')
      .attr("height", height + margin.top + margin.bottom)
    .append("g")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  var yBegin;

  var innerColumns = {
    "column1" : ["POSITIVE"],
    "column2" : ["NEGATIVE"],
    "column3" : ["NEUTRAL"],
    "column4" : ["AMBIVALENT"]
  }

  var columnHeaders = d3.keys(data[0]).filter(function(key) { return key !== "LANGUAGE"; });
  color.domain(d3.keys(data[0]).filter(function(key) { return key !== "LANGUAGE"; }));
  data.forEach(function(d) {
    var yColumn = new Array();
    d.columnDetails = columnHeaders.map(function(name) {
      for (ic in innerColumns) {
        if($.inArray(name, innerColumns[ic]) >= 0){
          if (!yColumn[ic]){
            yColumn[ic] = 0;
          }
          yBegin = yColumn[ic];
          yColumn[ic] += +d[name];
          return {name: name, column: ic, yBegin: yBegin, yEnd: +d[name] + yBegin,};
        }
      }
    });
    d.total = d3.max(d.columnDetails, function(d) {
      return d.yEnd;
    });
  });

  x0.domain(data.map(function(d) { return d.LANGUAGE; }));
  x1.domain(d3.keys(innerColumns)).rangeRoundBands([0, x0.rangeBand()]);

  y.domain([0, d3.max(data, function(d) {
    return d.total;
  })]);

  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);

  svg.append("g")
      .attr("class", "y axis")
      .call(yAxis)
    .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", 6)
      .attr("dy", ".7em")
      .style("text-anchor", "end")
      .text("");

  var project_stackedbar = svg.selectAll(".project_stackedbar")
      .data(data)
    .enter().append("g")
      .attr("class", "g")
      .attr("transform", function(d) { return "translate(" + x0(d.LANGUAGE) + ",0)"; });

  project_stackedbar.selectAll("rect")
      .data(function(d) { return d.columnDetails; })
    .enter().append("rect")
      .attr("width", x1.rangeBand())
      .attr("x", function(d) {
        return x1(d.column);
         })
      .attr("y", function(d) {
        return y(d.yEnd);
      })
      .attr("height", function(d) {
        return y(d.yBegin) - y(d.yEnd);
      })
      .style("fill", function(d) { return color(d.name); });

  var legend = svg.selectAll(".legend")
      .data(columnHeaders.slice().reverse())
    .enter().append("g")
      .attr("class", "legend")
      .attr("transform", function(d, i) { return "translate(90," + i * 20 + ")"; });

  legend.append("rect")
      .attr("x", width - 18)
      .attr("width", 18)
      .attr("height", 18)
      .style("fill", color);

  legend.append("text")
      .attr("x", width - 18)
      .attr("y", 9)
      .attr("dy", ".35em")
      .style("text-anchor", "end")
      .text(function(d) { return d; });
  }
}


text:
<core:FragmentDefinition
    xmlns="sap.m"
    xmlns:core="sap.ui.core">
	<Dialog id="helloDialog"
	        title="Hello {/recipient/name}">
	   <content>
	   	  <core:Icon src="sap-icon://hello-world"
	   	             size="8rem"
	   	             class="sapUiMediumMargin"/>
	   </content>
	   <beginButton>
	   	  <Button
	   	     text="{i18n>dialogCloseButtonText}"
	   	     press="onCloseDialog" />
	   </beginButton>
	</Dialog>
</core:FragmentDefinition>


text:
package OptimizationTests.ShortLeafMethodsInlining.InvokeVirtual_div_long_001;
class Main {
    final static int iterations = 10;

    public static void main(String[] args) {
        Test test = new Test();
        long workJ = 10;
        long workK = 15;

        System.out.println("Initial workJ value is " + workJ);

        for(long i = 0; i < iterations; i++) {
            workJ = test.simple_method(workJ, workK) + i;
        }

        System.out.println("Final workJ value is " + workJ);
    }
}


text:
namespace Waguu.Web.Services.Test
{
    public class TestImplementation : ITestInterface
    {
        public string GetName()
        {
            return "I'm testing IOC";
        }
    }
}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/ads/googleads/v12/services/campaign_feed_service.proto

package com.google.ads.googleads.v12.services;

public interface MutateCampaignFeedResultOrBuilder extends
    // @@protoc_insertion_point(interface_extends:google.ads.googleads.v12.services.MutateCampaignFeedResult)
    com.google.protobuf.MessageOrBuilder {

  /**
   *

   * Returned for successful operations.
   *

   *
   * string resource_name = 1 [(.google.api.resource_reference) = { ... }
   * @return The resourceName.
   */
  java.lang.String getResourceName();
  /**
   *

   * Returned for successful operations.
   *

   *
   * string resource_name = 1 [(.google.api.resource_reference) = { ... }
   * @return The bytes for resourceName.
   */
  com.google.protobuf.ByteString
      getResourceNameBytes();

  /**
   *

   * The mutated campaign feed with only mutable fields after mutate. The field
   * will only be returned when response_content_type is set to
   * "MUTABLE_RESOURCE".
   *

   *
   * .google.ads.googleads.v12.resources.CampaignFeed campaign_feed = 2;
   * @return Whether the campaignFeed field is set.
   */
  boolean hasCampaignFeed();
  /**
   *

   * The mutated campaign feed with only mutable fields after mutate. The field
   * will only be returned when response_content_type is set to
   * "MUTABLE_RESOURCE".
   *

   *
   * .google.ads.googleads.v12.resources.CampaignFeed campaign_feed = 2;
   * @return The campaignFeed.
   */
  com.google.ads.googleads.v12.resources.CampaignFeed getCampaignFeed();
  /**
   *

   * The mutated campaign feed with only mutable fields after mutate. The field
   * will only be returned when response_content_type is set to
   * "MUTABLE_RESOURCE".
   *

   *
   * .google.ads.googleads.v12.resources.CampaignFeed campaign_feed = 2;
   */
  com.google.ads.googleads.v12.resources.CampaignFeedOrBuilder getCampaignFeedOrBuilder();
}


text:
package io.gatling.core.pause

import java.util.concurrent.ThreadLocalRandom

import scala.concurrent.duration.Duration

import io.gatling.core.session._

sealed abstract class PauseType {
  def generator(duration: Duration): Expression[Long] = generator(duration.expressionSuccess)
  def generator(duration: Expression[Duration]): Expression[Long]
}

object Disabled extends PauseType {
  override def generator(duration: Expression[Duration]): Expression[Long] = throw new UnsupportedOperationException
}

object Constant extends PauseType {
  override def generator(duration: Expression[Duration]): Expression[Long] = duration.map(_.toMillis)
}

object Exponential extends PauseType {

  private def nextValue = {
    val rnd = ThreadLocalRandom.current
    var u = 0d
    do {
      u = rnd.nextDouble
    } while (u == 0d)
    -Math.log(u)
  }

  override def generator(duration: Expression[Duration]): Expression[Long] =
    duration.map(duration => (nextValue * duration.toMillis).round)
}

case class NormalWithPercentageDuration(stdDev: Double) extends PauseType {

  private val stdDevPercent = stdDev / 100.0

  override def generator(duration: Expression[Duration]): Expression[Long] =
    duration.map(d => math.max(0L, ((1 + ThreadLocalRandom.current.nextGaussian * stdDevPercent) * d.toMillis).toLong))
}

case class NormalWithStdDevDuration(stdDev: Duration) extends PauseType {
  override def generator(duration: Expression[Duration]): Expression[Long] =
    duration.map(d => math.max(0L, (ThreadLocalRandom.current.nextGaussian * stdDev.toMillis + d.toMillis).toLong))
}

case class Custom(custom: Expression[Long]) extends PauseType {
  override def generator(duration: Expression[Duration]): Expression[Long] = custom
}

case class UniformPercentage(plusOrMinus: Double) extends PauseType {

  private val plusOrMinusPercent = plusOrMinus / 100.0

  override def generator(duration: Expression[Duration]): Expression[Long] =
    duration.map { d =>
      val mean = d.toMillis
      val halfWidth = (mean * plusOrMinusPercent).round
      val least = math.max(0L, mean - halfWidth)
      val bound = mean + halfWidth + 1
      ThreadLocalRandom.current.nextLong(least, bound)
    }
}

case class UniformDuration(plusOrMinus: Duration) extends PauseType {

  private val halfWidth = plusOrMinus.toMillis

  override def generator(duration: Expression[Duration]): Expression[Long] =
    duration.map { duration =>
      val mean = duration.toMillis
      val least = math.max(0L, mean - halfWidth)
      val bound = mean + halfWidth + 1
      ThreadLocalRandom.current.nextLong(least, bound)
    }
}


text:
import { UserModel } from '../domain/user-model';

export interface UserRepositoryInterface {
    getUsers(conditions: Object): Promise<UserModel[]>;
    getUser(id: string): Promise<UserModel>;
    createUser(user: UserModel): Promise<UserModel>;
    updateUser(id: string, user: UserModel): Promise<UserModel>;
    getUserBySession(sessionId: string): Promise<UserModel>;
    getByAuth(strategyId: string, authId: string): Promise<UserModel>;
    getByAuthOrCreateUser(user: UserModel): Promise<UserModel>;
    clearSession(sessionId: string): Promise<void>;
}