text:
// The MIT License (MIT)
//
// Copyright (c) 2015-2017 Simon Ninon <simon.ninon@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

#include <cpp_redis/core/sentinel.hpp>
#include <cpp_redis/misc/error.hpp>
#include <cpp_redis/misc/logger.hpp>
#include <cpp_redis/network/redis_connection.hpp>

namespace cpp_redis {

#ifndef __CPP_REDIS_USE_CUSTOM_TCP_CLIENT
sentinel::sentinel(void)
: m_callbacks_running(0) {
  __CPP_REDIS_LOG(debug, "cpp_redis::sentinel created");
}
#endif /* __CPP_REDIS_USE_CUSTOM_TCP_CLIENT */

sentinel::sentinel(const std::shared_ptr<network::tcp_client_iface>& tcp_client)
: m_client(tcp_client)
, m_callbacks_running(0) {
  __CPP_REDIS_LOG(debug, "cpp_redis::sentinel created");
}

sentinel::~sentinel(void) {
  m_sentinels.clear();
  if (m_client.is_connected())
    m_client.disconnect(true);
  __CPP_REDIS_LOG(debug, "cpp_redis::sentinel destroyed");
}

sentinel&
sentinel::add_sentinel(const std::string& host, std::size_t port, std::uint32_t timeout_msecs) {
  m_sentinels.push_back({host, port, timeout_msecs});
  return *this;
}

void
sentinel::clear_sentinels() {
  m_sentinels.clear();
}

bool
sentinel::get_master_addr_by_name(const std::string& name, std::string& host, std::size_t& port, bool autoconnect) {
  //! reset connection settings
  host = "";
  port = 0;

  //! we must have some sentinels to connect to if we are in autoconnect mode
  if (autoconnect && m_sentinels.size() == 0) {
    throw redis_error("No sentinels available. Call add_sentinel() before get_master_addr_by_name()");
  }

  //! if we are not connected and we are not in autoconnect mode, we can't go further in the process
  if (!autoconnect && !is_connected()) {
    throw redis_error("No sentinel connected. Call connect() first or enable autoconnect.");
  }

  if (autoconnect) {
    try {
      //! Will round robin all attached sentinels until it finds one that is online.
      connect_sentinel(nullptr);
    }
    catch (const redis_error&) {
    }

    //! we failed to connect
    if (!is_connected()) {
      return false;
    }
  }

  //! By now we have a connection to a redis sentinel.
  //! Ask it who the master is.
  send({"SENTINEL", "get-master-addr-by-name", name}, [&](cpp_redis::reply& reply) {
    if (reply.is_array()) {
      auto arr = reply.as_array();
      host     = arr[0].as_string();
      port     = std::stoi(arr[1].as_string(), nullptr, 10);
    }
  });
  sync_commit();

  //! We always close any open connection in auto connect mode
  //! since the sentinel may not be around next time we ask who the master is.
  if (autoconnect) {
    disconnect(true);
  }

  return port != 0;
}

void
sentinel::connect_sentinel(const sentinel_disconnect_handler_t& sentinel_disconnect_handler) {
  if (m_sentinels.size() == 0) {
    throw redis_error("No sentinels available. Call add_sentinel() before connect_sentinel()");
  }

  auto disconnect_handler = std::bind(&sentinel::connection_disconnect_handler, this, std::placeholders::_1);
  auto receive_handler    = std::bind(&sentinel::connection_receive_handler, this, std::placeholders::_1, std::placeholders::_2);

  //! Now try to connect to first sentinel
  std::vector<sentinel_def>::iterator it = m_sentinels.begin();
  bool not_connected                     = true;

  while (not_connected && it != m_sentinels.end()) {
    try {
      __CPP_REDIS_LOG(debug, std::string("cpp_redis::sentinel attempting to connect to host ") + it->get_host());
      m_client.connect(it->get_host(), it->get_port(), disconnect_handler, receive_handler, it->get_timeout_msecs());
    }
    catch (const redis_error&) {
      __CPP_REDIS_LOG(info, std::string("cpp_redis::sentinel unable to connect to sentinel host ") + it->get_host());
    }

    if (is_connected()) {
      not_connected = false;
      __CPP_REDIS_LOG(info, std::string("cpp_redis::sentinel connected ok to host ") + it->get_host());
    }
    else {
      //! Make sure its closed.
      disconnect(true);
      //! Could not connect.  Try the next sentinel.
      ++it;
    }
  }

  if (not_connected) {
    throw redis_error("Unable to connect to any sentinels");
  }

  m_disconnect_handler = sentinel_disconnect_handler;
}

void
sentinel::connect(const std::string& host, std::size_t port,
  const sentinel_disconnect_handler_t& sentinel_disconnect_handler,
  std::uint32_t timeout_msecs) {
  __CPP_REDIS_LOG(debug, "cpp_redis::sentinel attempts to connect");

  auto disconnect_handler = std::bind(&sentinel::connection_disconnect_handler, this, std::placeholders::_1);
  auto receive_handler    = std::bind(&sentinel::connection_receive_handler, this, std::placeholders::_1, std::placeholders::_2);

  m_client.connect(host, port, disconnect_handler, receive_handler, timeout_msecs);

  __CPP_REDIS_LOG(info, "cpp_redis::sentinel connected");

  m_disconnect_handler = sentinel_disconnect_handler;
}

void
sentinel::connection_receive_handler(network::redis_connection&, reply& reply) {
  reply_callback_t callback = nullptr;

  __CPP_REDIS_LOG(info, "cpp_redis::sentinel received reply");
  {
    std::lock_guard<std::mutex> lock(m_callbacks_mutex);
    m_callbacks_running += 1;

    if (m_callbacks.size()) {
      callback = m_callbacks.front();
      m_callbacks.pop();
    }
  }

  if (callback) {
    __CPP_REDIS_LOG(debug, "cpp_redis::sentinel executes reply callback");
    callback(reply);
  }

  {
    std::lock_guard<std::mutex> lock(m_callbacks_mutex);
    m_callbacks_running -= 1;
    m_sync_condvar.notify_all();
  }
}

void
sentinel::clear_callbacks(void) {
  std::lock_guard<std::mutex> lock(m_callbacks_mutex);

  std::queue<reply_callback_t> empty;
  std::swap(m_callbacks, empty);

  m_sync_condvar.notify_all();
}

void
sentinel::call_disconnect_handler(void) {
  if (m_disconnect_handler) {
    __CPP_REDIS_LOG(info, "cpp_redis::sentinel calls disconnect handler");
    m_disconnect_handler(*this);
  }
}

void
sentinel::connection_disconnect_handler(network::redis_connection&) {
  __CPP_REDIS_LOG(warn, "cpp_redis::sentinel has been disconnected");
  clear_callbacks();
  call_disconnect_handler();
}

void
sentinel::disconnect(bool wait_for_removal) {
  __CPP_REDIS_LOG(debug, "cpp_redis::sentinel attempts to disconnect");
  m_client.disconnect(wait_for_removal);
  __CPP_REDIS_LOG(info, "cpp_redis::sentinel disconnected");
}

bool
sentinel::is_connected(void) {
  return m_client.is_connected();
}

const std::vector<sentinel::sentinel_def>&
sentinel::get_sentinels(void) const {
  return m_sentinels;
}

std::vector<sentinel::sentinel_def>&
sentinel::get_sentinels(void) {
  return m_sentinels;
}

sentinel&
sentinel::send(const std::vector<std::string>& redis_cmd, const reply_callback_t& callback) {
  std::lock_guard<std::mutex> lock_callback(m_callbacks_mutex);

  __CPP_REDIS_LOG(info, "cpp_redis::sentinel attempts to store new command in the send buffer");
  m_client.send(redis_cmd);
  m_callbacks.push(callback);
  __CPP_REDIS_LOG(info, "cpp_redis::sentinel stored new command in the send buffer");

  return *this;
}

//! commit pipelined transaction
sentinel&
sentinel::commit(void) {
  try_commit();

  return *this;
}

sentinel&
sentinel::sync_commit() {
  try_commit();
  std::unique_lock<std::mutex> lock_callback(m_callbacks_mutex);
  __CPP_REDIS_LOG(debug, "cpp_redis::sentinel waiting for callbacks to complete");
  m_sync_condvar.wait(lock_callback, [=] { return m_callbacks_running == 0 && m_callbacks.empty(); });
  __CPP_REDIS_LOG(debug, "cpp_redis::sentinel finished waiting for callback completion");
  return *this;
}

void
sentinel::try_commit(void) {
  try {
    __CPP_REDIS_LOG(debug, "cpp_redis::sentinel attempts to send pipelined commands");
    m_client.commit();
    __CPP_REDIS_LOG(info, "cpp_redis::sentinel sent pipelined commands");
  }
  catch (const cpp_redis::redis_error&) {
    __CPP_REDIS_LOG(error, "cpp_redis::sentinel could not send pipelined commands");
    clear_callbacks();
    throw;
  }
}

sentinel&
sentinel::ping(const reply_callback_t& reply_callback) {
  send({"PING"}, reply_callback);
  return *this;
}

sentinel&
sentinel::masters(const reply_callback_t& reply_callback) {
  send({"SENTINEL", "MASTERS"}, reply_callback);
  return *this;
}

sentinel&
sentinel::master(const std::string& name, const reply_callback_t& reply_callback) {
  send({"SENTINEL", "MASTER", name}, reply_callback);
  return *this;
}

sentinel&
sentinel::slaves(const std::string& name, const reply_callback_t& reply_callback) {
  send({"SENTINEL", "SLAVES", name}, reply_callback);
  return *this;
}

sentinel&
sentinel::sentinels(const std::string& name, const reply_callback_t& reply_callback) {
  send({"SENTINEL", "SENTINELS", name}, reply_callback);
  return *this;
}

sentinel&
sentinel::ckquorum(const std::string& name, const reply_callback_t& reply_callback) {
  send({"SENTINEL", "CKQUORUM", name}, reply_callback);
  return *this;
}

sentinel&
sentinel::failover(const std::string& name, const reply_callback_t& reply_callback) {
  send({"SENTINEL", "FAILOVER", name}, reply_callback);
  return *this;
}

sentinel&
sentinel::reset(const std::string& pattern, const reply_callback_t& reply_callback) {
  send({"SENTINEL", "RESET", pattern}, reply_callback);
  return *this;
}

sentinel&
sentinel::flushconfig(const reply_callback_t& reply_callback) {
  send({"SENTINEL", "FLUSHCONFIG"}, reply_callback);
  return *this;
}

sentinel&
sentinel::monitor(const std::string& name, const std::string& ip, std::size_t port, std::size_t quorum,
  const reply_callback_t& reply_callback) {
  send({"SENTINEL", "MONITOR", name, ip, std::to_string(port), std::to_string(quorum)}, reply_callback);
  return *this;
}

sentinel&
sentinel::remove(const std::string& name, const reply_callback_t& reply_callback) {
  send({"SENTINEL", "REMOVE", name}, reply_callback);
  return *this;
}

sentinel&
sentinel::set(const std::string& name, const std::string& option, const std::string& value,
  const reply_callback_t& reply_callback) {
  send({"SENTINEL", "SET", name, option, value}, reply_callback);
  return *this;
}

} // namespace cpp_redis


text:
    404

Stand Back, I know JavaScript

Exception: <%= exception.title %>

<%= exception.message %>

Quick Links:

Clayburn Docs

Code on Github

IRC: on freenode clayburn

Joyent Smart

Becoming Smart

Smart Docs

Welcome to Clayburn

Clayburn is a light-weight MVC framework written in JavaScript.

Where can I find help?

If you have any questions or if you can't figure something out, please take a
      look at our  Google Group.

What if I've found a bug?

If you want to file a bug or make your own contribution to Clayburn,
      feel free to fork the project on Github

How do I edit this page?

You're seeing this page because you need to edit the following files:

bootstrap.js (recommended)

web/views/exceptions/notfound.html (recommended)

web/layouts/application.html (change this layout)

© 2009 the clayburn dev team

redpajama_set_name: RedPajamaGithub


text:
set -e
echo "${OS_DISTRO}: Launching Container Application"
################################################################################
exec sudo httpd -D FOREGROUND


text:
package com.travelersun.schedule.admin.core.model;

/**
 * xxl-job log for glue, used to track job code process
 * @author xuxueli 2016-5-19 17:57:46
 */
public class XxlJobLogGlue {

	private int id;
	private int jobId;				// 任务主键ID
	private String glueSource;
	private String glueRemark;
	private String addTime;
	private String updateTime;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public int getJobId() {
		return jobId;
	}

	public void setJobId(int jobId) {
		this.jobId = jobId;
	}

	public String getGlueSource() {
		return glueSource;
	}

	public void setGlueSource(String glueSource) {
		this.glueSource = glueSource;
	}

	public String getGlueRemark() {
		return glueRemark;
	}

	public void setGlueRemark(String glueRemark) {
		this.glueRemark = glueRemark;
	}

	public String getAddTime() {
		return addTime;
	}

	public void setAddTime(String addTime) {
		this.addTime = addTime;
	}

	public String getUpdateTime() {
		return updateTime;
	}

	public void setUpdateTime(String updateTime) {
		this.updateTime = updateTime;
	}

	@Override
	public String toString() {
		return "XxlJobLogGlue{" +
				"id=" + id +
				", jobId=" + jobId +
				", glueSource='" + glueSource + '\'' +
				", glueRemark='" + glueRemark + '\'' +
				", addTime='" + addTime + '\'' +
				", updateTime='" + updateTime + '\'' +
				'}';
	}
}


text:
**A URL Shortener**

Built using CodeIgniter framework as a foundation
Admin dashboard is still a WIP

Currently in use at *http://Linq.at*

A product of Purple Monkey Studio, LLC
*http://PurpleMonkeyPower.com*


text:
class <%= migration_class_name %> < ActiveRecord::Migration
  def change
    add_column :<%= table_name %>, :namespace, :string, :null => false, :default => 'default'
    add_column :<%= table_name %>, :name, :string, :null => false
    add_column :<%= table_name %>, :value, :text

    add_index :<%= table_name %>, [:namespace, :name], :unique => true
    add_index :<%= table_name %>, :name
  end
end


text:
layout: page
title: Megan Shea's 77th Birthday
date: 2016-05-24
author: Jerry Delgado
tags: weekly links, java
status: published
summary: Integer ornare condimentum metus in.
banner: images/banner/leisure-03.jpg
booking:
  startDate: 07/03/2017
  endDate: 07/05/2017
  ctyhocn: CLWNOHX
  groupCode: MS7B
published: true
---
Morbi lacinia tortor felis, nec ullamcorper augue hendrerit non. Vivamus mollis ultrices luctus. Proin nec scelerisque dui, nec condimentum dolor. Proin sit amet massa maximus massa blandit accumsan ac vitae purus. Donec vel eros ac metus tempor iaculis non sed purus. Nullam scelerisque orci metus, non malesuada nulla eleifend efficitur. Ut nisi felis, vehicula eu scelerisque ac, tincidunt ac dui. Nam vitae facilisis risus, non gravida mauris. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras non nisl tincidunt, viverra lectus quis, molestie nunc. Nam ultricies dolor vitae arcu sollicitudin, a porttitor nunc aliquet. Nam leo justo, consectetur ac iaculis et, imperdiet id ipsum. Etiam non ipsum posuere, tristique lectus eu, aliquam arcu. Sed condimentum risus diam, in mollis quam consequat non. Ut id facilisis sapien, ut consectetur ipsum.
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Mauris vel vehicula tortor. Ut dui neque, ornare a velit vel, tristique efficitur nisi. Aliquam molestie sapien ac metus tempor, ut euismod magna sollicitudin. In sed tincidunt massa. Etiam porttitor tellus ex, id malesuada lectus viverra id. Sed ornare nulla id risus sollicitudin eleifend. Donec congue viverra libero interdum facilisis.

* Quisque volutpat mi eget massa porta, tempor interdum lorem semper
* Suspendisse efficitur risus eu ultricies ultricies
* Sed quis elit hendrerit, pharetra enim ac, vestibulum eros
* Morbi at nisi facilisis, molestie arcu ornare, pretium tellus
* Sed et velit in nunc euismod cursus.

Vivamus sed faucibus ipsum. Donec viverra aliquam enim, eget fringilla urna mattis sit amet. Fusce luctus erat id sapien placerat, et aliquet ante vehicula. Integer quis suscipit odio. Aliquam et condimentum nisi. Vivamus efficitur hendrerit elit, id malesuada metus cursus eu. Suspendisse iaculis interdum felis.


text:
<?php declare(strict_types=1);

namespace Granam\ExceptionsHierarchy\Exceptions;

class ExceptionClassNotFoundByAutoloader extends \RuntimeException implements Runtime
{

}


text:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Windows.UI.Xaml.Controls;
using Windows.ApplicationModel.Background;
using Windows.Storage;
using BackgroundTask;

namespace SDKTemplate
{
    public partial class MainPage : Page
    {
        public const string FEATURE_NAME = "BackgroundTask";

        List<Scenario> scenarios = new List<Scenario>
        {
            new Scenario() { Title="Background Task", ClassType=typeof(BackgroundTask.SampleBackgroundTask)},
            new Scenario() { Title="Background Task with Condition", ClassType=typeof(BackgroundTask.SampleBackgroundTaskWithCondition)},
            new Scenario() { Title="Servicing Complete Task", ClassType=typeof(BackgroundTask.ServicingCompleteTask)},
            new Scenario() { Title="Background Task with Time Trigger", ClassType=typeof(BackgroundTask.TimeTriggeredTask) },
            new Scenario() { Title="Background Task with Application Trigger", ClassType=typeof(BackgroundTask.ApplicationTriggerTask) }
        };
    }

    public class Scenario
    {
        public string Title { get; set; }
        public Type ClassType { get; set; }
    }
}

namespace BackgroundTask
{
    class BackgroundTaskSample
    {
        public const string SampleBackgroundTaskEntryPoint = "Tasks.SampleBackgroundTask";
        public const string SampleBackgroundTaskName = "SampleBackgroundTask";
        public static string SampleBackgroundTaskProgress = "";
        public static bool SampleBackgroundTaskRegistered = false;

        public const string SampleBackgroundTaskWithConditionName = "SampleBackgroundTaskWithCondition";
        public static string SampleBackgroundTaskWithConditionProgress = "";
        public static bool SampleBackgroundTaskWithConditionRegistered = false;

        public const string ServicingCompleteTaskEntryPoint = "Tasks.ServicingComplete";
        public const string ServicingCompleteTaskName = "ServicingCompleteTask";
        public static string ServicingCompleteTaskProgress = "";
        public static bool ServicingCompleteTaskRegistered = false;

        public const string TimeTriggeredTaskName = "TimeTriggeredTask";
        public static string TimeTriggeredTaskProgress = "";
        public static bool TimeTriggeredTaskRegistered = false;

        public const string ApplicationTriggerTaskName = "ApplicationTriggerTask";
        public static string ApplicationTriggerTaskProgress = "";
        public static string ApplicationTriggerTaskResult = "";
        public static bool ApplicationTriggerTaskRegistered = false;

        /// <summary>
        /// Register a background task with the specified taskEntryPoint, name, trigger,
        /// and condition (optional).
        /// </summary>
        /// <param name="taskEntryPoint">Task entry point for the background task.</param>
        /// <param name="name">A name for the background task.</param>
        /// <param name="trigger">The trigger for the background task.</param>
        /// <param name="condition">An optional conditional event that must be true for the task to fire.</param>
        public static async Task<BackgroundTaskRegistration> RegisterBackgroundTask(String taskEntryPoint, String name, IBackgroundTrigger trigger, IBackgroundCondition condition)
        {
            if (TaskRequiresBackgroundAccess(name))
            {
                await BackgroundExecutionManager.RequestAccessAsync();
            }

            var builder = new BackgroundTaskBuilder();

            builder.Name = name;
            builder.TaskEntryPoint = taskEntryPoint;
            builder.SetTrigger(trigger);

            if (condition != null)
            {
                builder.AddCondition(condition);

                //
                // If the condition changes while the background task is executing then it will
                // be canceled.
                //
                builder.CancelOnConditionLoss = true;
            }

            BackgroundTaskRegistration task = builder.Register();

            UpdateBackgroundTaskStatus(name, true);

            //
            // Remove previous completion status from local settings.
            //
            var settings = ApplicationData.Current.LocalSettings;
            settings.Values.Remove(name);

            return task;
        }

        /// <summary>
        /// Unregister background tasks with specified name.
        /// </summary>
        /// <param name="name">Name of the background task to unregister.</param>
        public static void UnregisterBackgroundTasks(String name)
        {
            //
            // Loop through all background tasks and unregister any with SampleBackgroundTaskName or
            // SampleBackgroundTaskWithConditionName.
            //
            foreach (var cur in BackgroundTaskRegistration.AllTasks)
            {
                if (cur.Value.Name == name)
                {
                    cur.Value.Unregister(true);
                }
            }

            UpdateBackgroundTaskStatus(name, false);
        }

        /// <summary>
        /// Store the registration status of a background task with a given name.
        /// </summary>
        /// <param name="name">Name of background task to store registration status for.</param>
        /// <param name="registered">TRUE if registered, FALSE if unregistered.</param>
        public static void UpdateBackgroundTaskStatus(String name, bool registered)
        {
            switch (name)
            {
                case SampleBackgroundTaskName:
                    SampleBackgroundTaskRegistered = registered;
                    break;
                case SampleBackgroundTaskWithConditionName:
                    SampleBackgroundTaskWithConditionRegistered = registered;
                    break;
                case ServicingCompleteTaskName:
                    ServicingCompleteTaskRegistered = registered;
                    break;
                case TimeTriggeredTaskName:
                    TimeTriggeredTaskRegistered = registered;
                    break;
                case ApplicationTriggerTaskName:
                    ApplicationTriggerTaskRegistered = registered;
                    break;
            }
        }

        /// <summary>
        /// Get the registration / completion status of the background task with
        /// given name.
        /// </summary>
        /// <param name="name">Name of background task to retreive registration status.</param>
        public static String GetBackgroundTaskStatus(String name)
        {
            var registered = false;
            switch (name)
            {
                case SampleBackgroundTaskName:
                    registered = SampleBackgroundTaskRegistered;
                    break;
                case SampleBackgroundTaskWithConditionName:
                    registered = SampleBackgroundTaskWithConditionRegistered;
                    break;
                case ServicingCompleteTaskName:
                    registered = ServicingCompleteTaskRegistered;
                    break;
                case TimeTriggeredTaskName:
                    registered = TimeTriggeredTaskRegistered;
                    break;
                case ApplicationTriggerTaskName:
                    registered = ApplicationTriggerTaskRegistered;
                    break;
            }

            var status = registered ? "Registered" : "Unregistered";

            var settings = ApplicationData.Current.LocalSettings;
            if (settings.Values.ContainsKey(name))
            {
                status += " - " + settings.Values[name].ToString();
            }

            return status;
        }

        /// <summary>
        /// Determine if task with given name requires background access.
        /// </summary>
        /// <param name="name">Name of background task to query background access requirement.</param>
        public static bool TaskRequiresBackgroundAccess(String name)
        {
            if ((name == TimeTriggeredTaskName) ||
                (name == ApplicationTriggerTaskName))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}


text:
CREATE TABLE [dbo].[UserSecurityQuestions] (
    [Id]       UNIQUEIDENTIFIER NOT NULL,
    [Question] NVARCHAR (255)   NULL,
    [Answer]   NVARCHAR (255)   NULL,
    [UserId]   UNIQUEIDENTIFIER NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [FK_SecurityQuestions_Users] FOREIGN KEY ([UserId]) REFERENCES [dbo].[Users] ([Id]) ON UPDATE CASCADE ON DELETE CASCADE
);


text:
package com.hp.hpl.jena.reasoner.rulesys.builtins;

import com.hp.hpl.jena.reasoner.rulesys.*;
import com.hp.hpl.jena.graph.*;

/**
 * Can be used in two arg form (X, P) or three arg form (X, P, V).
 * In three arg form it succeeds if the triple  (X, P, V) is not
 * currently present, in two arg form it succeeds if there is not value
 * for (X, P, *).
 *
 * @author Dave Reynolds
 * @version $Revision: 1.1 $ on $Date: 2009-06-29 08:55:36 $
 */
public class NoValue extends BaseBuiltin {

    /**
     * Return a name for this builtin, normally this will be the name of the
     * functor that will be used to invoke it.
     */
    @Override
    public String getName() {
        return "noValue";
    }

    /**
     * This method is invoked when the builtin is called in a rule body.
     * @param args the array of argument values for the builtin, this is an array
     * of Nodes, some of which may be Node_RuleVariables.
     * @param length the length of the argument list, may be less than the length of the args array
     * for some rule engines
     * @param context an execution context giving access to other relevant data
     * @return return true if the buildin predicate is deemed to have succeeded in
     * the current environment
     */
    @Override
    public boolean bodyCall(Node[] args, int length, RuleContext context) {
        if (length !=2 && length != 3) {
            throw new BuiltinException(this, context, "builtin " + getName() + " requires 2 or 3 arguments but saw " + length);
        }
        Node obj = null;
        if (length == 3) {
            obj = getArg(2, args, context);
        }
        Node subj = getArg(0, args, context);
        // Allow variables in subject position to correspond to wild cards
        if (subj.isVariable()) {
            subj = null;
        }
        Node pred = getArg(1, args, context);
        if (pred.isVariable()) {
            pred = null;
        }
        return !context.contains(subj, pred, obj);
    }

    /**
     * Flag as non-monotonic so the guard clause will get rerun after deferal
     * as part of a non-trivial conflict set.
     */
    @Override
    public boolean isMonotonic() {
        return false;
    }

}


text:
[ ![Download](https://maven-badges.herokuapp.com/maven-central/com.nhaarman/asyncawait-android/badge.svg) ](https://maven-badges.herokuapp.com/maven-central/com.nhaarman/asyncawait-android)

**Warning!**
This library was created for Kotlin 1.1-M03. Since M04, the API has changed. See [Kotlin-Coroutines](https://github.com/Kotlin/kotlin-coroutines) for more info.

A library that provides the async/await concept for Android using the coroutines feature in Kotlin 1.1.

## Install

AsyncAwait-Android is available on Maven Central.
For Gradle users, add the following to your `build.gradle`, replacing `x.x.x` with the latest version:

```groovy
repositories {
    mavenCentral()
}
dependencies {
    compile "com.nhaarman:asyncawait-android:x.x.x"
}
```

AsyncAwait-Android uses the 1.1-M03 eap of Kotlin. See the [How to try it](https://blog.jetbrains.com/kotlin/2016/07/first-glimpse-of-kotlin-1-1-coroutines-type-aliases-and-more/) section for details.

## Example

A typical scenario is provided below:

```kotlin

fun onCreate(savedInstanceState: Bundle?) {
  super.onCreate(savedInstanceState)

  asyncUI {
    val textView = TextView(this@MainActivity)
    setContentView(textView)
    val githubUserName = await(retrieveGithubUser()).name
    textView.text = githubUserName
  }
}

fun retrieveGithubUser() = async<User> {
  ...
}

```

In this snippet the coroutine is suspended at `await(retrieveGithubUser())`, and
resumed when the task returned by `retrieveGithubUser()` finishes.
The coroutine is resumed on the main thread, as indicated by `asyncUI`.

## How it works
_Inspired by http://blog.stephencleary.com/2012/02/async-and-await.html._

An asynchronous method looks something like this:

```kotlin
fun foo() = async<String> {
  await(delay(1, SECONDS))
  "bar"
}
```

The call to `async` provides access to the `await` function, and changes the way the method is executed.
It does _not_ move the method call on another thread.
The method is executed synchronously until the first call to `await`, which _may_ result in an asynchronous call.

If the parameter provided to `await` has already completed, the method continuous running synchronously.
If the parameter has not yet completed, `await` tells the awaitable to run the rest of the method when it completes, and then returns from the async method.

Later on, when the awaitable completes, it will execute the remainder of the async method.
The thread on which the remainder is executed is determined by whether the async method was called by `async` or `asyncUI`

## Async

There are two flavors of `async`: one that takes in a parameter (e.g. `async<String>`), and one that does not.
The type passed to `async` determines the result type of the coroutine.

When using `async`, the coroutine will continue on the thread the awaitable ended on.
For example, if you call `await` with a `Task` that is executed on some io thread, the remainder of the coroutine will continue on that io thread:

```
fun foo() = async {
  // Runs on calling thread
  await(someIoTask()) // someIoTask() runs on an io thread
  // Continues on the io thread
}
```

## AsyncUI

If you want to modify UI elements, or do other things that require you to be on the main thread, you can use `asyncUI`.
In contrast to `async`, `asyncUI` _does_ continue on the main thread after a call to `await`:

```
// Runs on main thread
await(someIoTask()) // someIoTask() runs on an io thread
// Continues on the main thread
```

## Await

Inside a coroutine, you can await on a `Task` or pass a lambda.
Since `async` returns a `Task`, you can await on asynchronous methods.
The return type of `await` is either the type parameter passed to `Task` or the return type of the lambda.

When awaiting on a `Task<T>`, there is no thread switching, unless specified explicitly by that task.
When awaiting on a lambda, the lambda _will_ be executed on another thread:

```kotlin
fun foo() = asyncUI {
  // Main thread
  var result = await(bar()) // bar() is executed on the main thread
  // Main thread
  result = await { // Lambda is executed on another thread
    "Bar"
  }
  // Main thread
}

fun bar() = async<String> {
  "Bar"
}
```


text:
//
// Copyright (C) 2016 OpenSim Ltd.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program; if not, see http://www.gnu.org/licenses/.
//

#include "RecipientAckProcedure.h"

namespace inet {
namespace ieee80211 {

void RecipientAckProcedure::processReceivedFrame(Ieee80211DataOrMgmtFrame *dataOrMgmtFrame, IRecipientAckPolicy *ackPolicy, IProcedureCallback *callback)
{
    numReceivedAckableFrame++;
    // After a successful reception of a frame requiring acknowledgment, transmission of the ACK frame
    // shall commence after a SIFS period, without regard to the busy/idle state of the medium. (See Figure 9-9.)
    if (ackPolicy->isAckNeeded(dataOrMgmtFrame)) {
        auto ackFrame = buildAck(dataOrMgmtFrame);
        ackFrame->setDuration(ackPolicy->computeAckDurationField(dataOrMgmtFrame));
        callback->transmitControlResponseFrame(ackFrame, dataOrMgmtFrame);
    }
}

void RecipientAckProcedure::processTransmittedAck(Ieee80211ACKFrame* ack)
{
    numSentAck++;
}

Ieee80211ACKFrame* RecipientAckProcedure::buildAck(Ieee80211DataOrMgmtFrame *dataOrMgmtFrame) const
{
    Ieee80211ACKFrame *ack = new Ieee80211ACKFrame("ACK");
    ack->setReceiverAddress(dataOrMgmtFrame->getTransmitterAddress());
    return ack;
}

} /* namespace ieee80211 */
} /* namespace inet */


text:
require 'rmagick'
include Magick

puts('Creating colors.miff. This may take a few seconds...')

colors = ImageList.new

# Add a row of "null" colors so we'll have
# room to add the title at the top.
4.times { colors.read('null:') }

puts("\tCreating color swatches...")

# Create a 200x25 image for each named color.
# Label with the name, RGB values, and compliance type.
colors do |c|
  if c.name !~ /grey/ # omit SVG 'grays'
    colors.new_image(200, 25) do
      self.background_color = c.color
      self.border_color = 'gray50'
    end
    rgb  = sprintf('#%02x%02x%02x', c.color.red&0xff,  c.color.green&0xff, c.color.blue&0xff)
    rgb += sprintf('%02x', c.color.opacity&0xff) if c.color.opacity != 0
    m = /(.*?)Compliance/.match c.compliance.to_s
    colors.cur_image['Label'] = "#{c.name} (#{rgb}) #{m[1]}"
  end
end

puts("\tCreating montage...")

# Montage. Each image will have 40 tiles.
# There will be 16 images.
montage = colors.montage do
  self.geometry = '200x25+10+5'
  self.gravity = CenterGravity
  self.tile = '4x10'
  self.background_color = 'black'
  self.border_width = 1
  self.fill = 'white'
  self.stroke = 'transparent'
end

# Add the title at the top, over the 'null:'
# tiles we added at the very beginning.
title = Draw.new
title.annotate(montage, 0,0,0,20, 'Named Colors') do
  self.fill = 'white'
  self.stroke = 'transparent'
  self.pointsize = 32
  self.font_weight = BoldWeight
  self.gravity = NorthGravity
end

puts("\tWriting ./colors.miff")
montage.each { |f| f.compression = ZipCompression }
montage.write('colors.miff')

# Make a small sample of the full montage to display in the HTML file.
sample = montage[8].crop(55, 325, 495, 110)
sample.page = Rectangle.new(495,110)
sample.write('colors.gif')

exit


text:
import os, sys

sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

import test
print (test.__file__)
suite = test.suite

if __name__ == '__main__':
    test.main()


text:
FROM ubuntu:16.04

MAINTAINER Aleena Ma
RUN apt-get update
RUN apt-get install -y openjdk-8-jdk
RUN apt-get install -y python


text:
define(function(require) {
    'use strict';

    var $ = require('jquery');
    var _ = require('lodash');
    var AwesomeMap = require('wf-js-uicomponents/awesome_map/AwesomeMap');
    var DOMUtil = require('wf-js-common/DOMUtil');
    var EventSynthesizer = require('wf-js-uicomponents/awesome_map/EventSynthesizer');
    var EventTypes = require('wf-js-uicomponents/awesome_map/EventTypes');
    var Gesture = require('wf-js-uicomponents/awesome_map/Gesture');
    var InteractionEvent = require('wf-js-uicomponents/awesome_map/InteractionEvent');
    var InterceptorMixin = require('wf-js-uicomponents/awesome_map/InterceptorMixin');
    var InteractionSimulator = require('wf-js-uicomponents/awesome_map/InteractionSimulator');
    var TransformState = require('wf-js-uicomponents/awesome_map/TransformState');
    var TransformationQueue = require('wf-js-uicomponents/awesome_map/TransformationQueue');
    var TransformUtil = require('wf-js-uicomponents/awesome_map/TransformUtil');

    describe('AwesomeMap', function() {
        var awesomeMap;
        var $host = $('<div>');
        var configuration = { host: $host[0] };

        function FakeInterceptor() {}
        function FakeInterceptor2() {}
        _.assign(FakeInterceptor.prototype, InterceptorMixin);
        _.assign(FakeInterceptor2.prototype, InterceptorMixin);

        beforeEach(function() {
            spyOn(TransformUtil, 'clearTransformationOrigin');

            $host.empty().css({ position: 'absolute', top: -10000, width: 500, height: 500 }).appendTo('body');

            awesomeMap = new AwesomeMap($host[0]);
        });

        afterEach(function() {
            $host.remove();
            awesomeMap.dispose();
        });

        describe('construction', function() {

            it('should require specifying a host element', function() {
                var constructor = function() {
                    return new AwesomeMap();
                };
                expect(constructor).toThrow('AwesomeMap configuration: host is required.');
            });

            it('should require the host element to be in the DOM', function() {
                var ctor = function() {
                    return new AwesomeMap($('<div>')[0]);
                };
                expect(ctor).toThrow('AwesomeMap configuration: host is not in the DOM.');
            });

            it('should require the host element to have a width', function() {
                var ctor = function() {
                    return new AwesomeMap($host[0]);
                };

                $host.css({ width: 0 });
                expect(ctor).toThrow('AwesomeMap configuration: host does not have any size.');
            });

            it('should require the host element to have a height', function() {
                var ctor = function() {
                    return new AwesomeMap($host[0]);
                };

                $host.css({ height: 0 });
                expect(ctor).toThrow('AwesomeMap configuration: host does not have any size.');
            });

            it('should initialize HTML elements', function() {
                var host = awesomeMap._host;
                var viewport = awesomeMap._viewport;
                var transformationPlane = awesomeMap._transformationPlane;
                var hostChildren;
                var viewportChildren;

                function testElementStyle(element) {
                    expect(element).not.toBeNull();
                    expect(element.style.position).toBe('absolute');
                    expect(element.style.top).toBe('0px');
                    expect(element.style.bottom).toBe('0px');
                    expect(element.style.left).toBe('0px');
                    expect(element.style.right).toBe('0px');
                }

                // Expecting:
                // - the host is the configured host;
                // - the viewport, transformation plane and hit area are created;
                // - the viewport, transformation plane and hit area have host relative position and dimensions;
                // - the host contains the viewport; and,
                // - the viewport contains the transformation plane and hit area.

                expect(host).toBe(configuration.host);

                testElementStyle(viewport);
                expect(viewport.style.overflow).toBe('hidden');

                expect(transformationPlane).not.toBeNull();
                expect(transformationPlane.style.position).toBe('absolute');
                expect(transformationPlane.style.top).toBe('');
                expect(transformationPlane.style.bottom).toBe('');
                expect(transformationPlane.style.left).toBe('');
                expect(transformationPlane.style.right).toBe('');
                expect(TransformUtil.clearTransformationOrigin).toHaveBeenCalledWith(transformationPlane);

                hostChildren = host.childNodes;
                expect(hostChildren.length).toBe(1);
                expect(hostChildren[0]).toBe(viewport);

                viewportChildren = viewport.childNodes;
                expect(viewportChildren.length).toBe(1);
                expect(viewportChildren[0]).toBe(transformationPlane);
            });

            it('should initialize the current transform state', function() {
                expect(awesomeMap._currentTransformState).not.toBeNull();
                expect(new TransformState().equals(awesomeMap._currentTransformState)).toBe(true);
            });

            it('should initialize the event synthesizer', function() {
                expect(awesomeMap._eventSynthesizer).not.toBeNull();
                expect(awesomeMap._eventSynthesizer instanceof EventSynthesizer).toBeTruthy();
            });

            it('should initialize the interaction simulator', function() {
                expect(awesomeMap._interactionSimulator).not.toBeNull();
                expect(awesomeMap._interactionSimulator instanceof InteractionSimulator).toBeTruthy();
            });

            it('should initialize the transformation queue', function() {
                expect(awesomeMap._transformationQueue).not.toBeNull();
                expect(awesomeMap._transformationQueue instanceof TransformationQueue).toBeTruthy();
            });
        });

        describe('interceptors', function() {
            it('should add interceptors', function() {
                var interceptor = new FakeInterceptor();

                spyOn(interceptor, 'register');
                awesomeMap.addInterceptor(interceptor);

                expect(awesomeMap._interceptors.length).toBe(1);
                expect(awesomeMap._interceptors[0]).toBe(interceptor);
                expect(interceptor.register).toHaveBeenCalled();
            });

            it('should remove interceptors by Type', function() {
                awesomeMap.addInterceptor(new FakeInterceptor());
                awesomeMap.addInterceptor(new FakeInterceptor2());
                awesomeMap.removeInterceptor(FakeInterceptor);

                expect(awesomeMap.getInterceptor(FakeInterceptor)).toBeNull();
                expect(awesomeMap.getInterceptor(FakeInterceptor2)).not.toBeNull();
            });
        });

        describe('content', function() {
            function createContent(width, height) {
                return $('<div>').css({
                    width: width || 400,
                    height: height || 600
                })[0];
            }

            //---------------------------------------------------------
            // These cases are well-tested because if these assertions fail
            // we will likely have screen flickering in mobile WebKit
            // when adding/panning content very quickly.
            //---------------------------------------------------------

            describe('when appending content', function() {

                it('should append content to the transformation plane', function() {
                    var content = createContent();
                    var transformationPlaneChildren;

                    awesomeMap.appendContent(content);

                    transformationPlaneChildren = awesomeMap._transformationPlane.childNodes;
                    expect(transformationPlaneChildren.length).toBe(1);
                    expect(transformationPlaneChildren[0]).toBe(content);
                });

                it('should invalidate the content dimensions', function() {
                    var content = createContent();
                    var contentDimensions = awesomeMap.getContentDimensions();

                    expect(contentDimensions.width).toBe(0);
                    expect(contentDimensions.height).toBe(0);

                    awesomeMap.appendContent(content);

                    contentDimensions = awesomeMap.getContentDimensions();

                    expect(contentDimensions.width).toBe(parseInt(content.style.width, 10));
                    expect(contentDimensions.height).toBe(parseInt(content.style.height, 10));
                });
            });

            describe('when clearing content', function() {

                it('should clear all content from the transformation plane', function() {
                    var transformationPlane = awesomeMap.getTransformationPlane();

                    awesomeMap.appendContent(createContent());
                    awesomeMap.appendContent(createContent());
                    expect(transformationPlane.childNodes.length).toBe(2);

                    awesomeMap.clearContent();

                    expect(transformationPlane.childNodes.length).toBe(0);
                });

                it('should invalidate the content dimensions', function() {
                    var content = createContent();
                    var contentDimensions;

                    awesomeMap.appendContent(content);
                    awesomeMap.clearContent(content);

                    contentDimensions = awesomeMap.getContentDimensions();

                    expect(contentDimensions.width).toBe(0);
                    expect(contentDimensions.height).toBe(0);
                });
            });

            describe('when removing content', function() {

                it('should remove content from the transformation plane', function() {
                    var transformationPlane = awesomeMap.getTransformationPlane();

                    awesomeMap.appendContent(createContent());
                    awesomeMap.clearContent();

                    expect(transformationPlane.childNodes.length).toBe(0);
                });

                it('should invalidate the content dimensions', function() {
                    var content = createContent();
                    var contentDimensions;

                    awesomeMap.appendContent(content);
                    awesomeMap.removeContent(content);

                    contentDimensions = awesomeMap.getContentDimensions();

                    expect(contentDimensions.width).toBe(0);
                    expect(contentDimensions.height).toBe(0);
                });
            });

            it('should get total content dimensions', function() {
                // TODO: Test borders/margin/padding too.
                var content1 = createContent(200, 500);
                var content2 = createContent(300, 700);
                var contentDimensions;

                awesomeMap.appendContent(content1);
                awesomeMap.appendContent(content2);
                contentDimensions = awesomeMap.getContentDimensions();

                expect(contentDimensions.width).toBe(300);
                expect(contentDimensions.height).toBe(1200);
            });

            it('should get custom content dimensions if set', function() {
                var content1 = createContent(200, 500);
                var content2 = createContent(300, 700);
                var customDimensions = { width: 42000, height: 31000 };
                var contentDimensions;

                awesomeMap.appendContent(content1);
                awesomeMap.setContentDimensions(customDimensions);
                awesomeMap.appendContent(content2);
                contentDimensions = awesomeMap.getContentDimensions();

                expect(contentDimensions.width).toBe(customDimensions.width);
                expect(contentDimensions.height).toBe(customDimensions.height);
            });
        });

        describe('properties', function() {

            it('should get the current transform state', function() {
                var state = awesomeMap.getCurrentTransformState();

                expect(state).toBe(awesomeMap._currentTransformState);
            });

            it('should get the current scale', function() {
                var scale;

                awesomeMap.transform({ scale: 2 });
                scale = awesomeMap.getScale();

                expect(scale).toBe(2);
            });

            it('should get the current translation', function() {
                var position;

                awesomeMap.transform({ x: -100, y: -200 });
                position = awesomeMap.getTranslation();

                expect(position.x).toBe(-100);
                expect(position.y).toBe(-200);
            });

            it('should get the host element', function() {
                var host = awesomeMap.getHost();

                expect(host).toBe(awesomeMap._host);
            });

            it('should get whether the map is enabled', function() {
                expect(awesomeMap.isDisabled()).toBe(false);

                awesomeMap.disable();
                expect(awesomeMap.isDisabled()).toBe(true);

                awesomeMap.enable();
                expect(awesomeMap.isDisabled()).toBe(false);
            });

            describe('getting the viewport dimensions', function() {
                it('should make the host measure ready', function() {
                    spyOn(DOMUtil, 'makeMeasureReady');
                    awesomeMap.getViewportDimensions();
                    expect(DOMUtil.makeMeasureReady).toHaveBeenCalled();
                });
            });

            describe('setting current transform state', function() {

                it('should set the current transform state', function() {
                    var state = new TransformState({
                        scale: 2,
                        translateX: 100,
                        translateY: 200
                    });
                    awesomeMap.setCurrentTransformState(state);

                    expect(awesomeMap.getCurrentTransformState()).toEqual(state);
                });

                it('should dispatch "onScaleChanged" if scale changed', function() {
                    var state = new TransformState({ scale: 2 });
                    spyOn(awesomeMap.onScaleChanged, 'dispatch');

                    awesomeMap.setCurrentTransformState(state);

                    expect(awesomeMap.onScaleChanged.dispatch)
                        .toHaveBeenCalledWith([awesomeMap, { scale: 2 }]);
                });

                it('should dispatch "onTranslationChanged" if translation changed', function() {
                    var state = new TransformState({ translateX: 100, translateY: 200 });
                    spyOn(awesomeMap.onTranslationChanged, 'dispatch');

                    awesomeMap.setCurrentTransformState(state);

                    expect(awesomeMap.onTranslationChanged.dispatch)
                        .toHaveBeenCalledWith([awesomeMap, { x: 100, y: 200 }]);
                });
            });
        });

        describe('viewport', function() {
            it('should get viewport dimensions', function() {
                var dimensions = awesomeMap.getViewportDimensions();

                expect(dimensions.width).toBe(500);
                expect(dimensions.height).toBe(500);
            });
        });

        describe('disabling', function() {

            it('should cause map to ignore direct user interaction', function() {
                var gesture = new Gesture();
                var evt = new InteractionEvent({ simulated: false }, gesture, gesture);

                spyOn(awesomeMap._transformationQueue, 'enqueue');

                awesomeMap.disable();
                awesomeMap.handleInteractionEvent(null, { event: evt });

                expect(awesomeMap._transformationQueue.enqueue).not.toHaveBeenCalled();
            });
        });

        describe('enabling', function() {

            it('should cause map to respond to direct user interaction', function() {
                var gesture = new Gesture();
                var evt = new InteractionEvent({ simulated: false }, gesture, gesture);

                spyOn(awesomeMap._transformationQueue, 'enqueue');

                awesomeMap.disable();
                awesomeMap.enable();
                awesomeMap.handleInteractionEvent(null, { event: evt });

                expect(awesomeMap._transformationQueue.enqueue).toHaveBeenCalled();
            });
        });

        describe('setting mousePanningEnabled to false', function() {
            var args = {};

            beforeEach(function() {
                awesomeMap = new AwesomeMap($host[0], { mousePanningEnabled: false });
                var gesture = new Gesture();
                args.event = new InteractionEvent({ simulated: false }, gesture, gesture);
                var sourceEvent = document.createEvent('MouseEvent');
                args.event.source = sourceEvent;

                spyOn(awesomeMap._transformationQueue, 'enqueue');
            });

            it('should not respond to drag events', function() {
                args.event.type = EventTypes.DRAG;
                awesomeMap.handleInteractionEvent(null, args);
                expect(awesomeMap._transformationQueue.enqueue).not.toHaveBeenCalled();
            });

            it('should not respond to swipe events', function() {
                args.event.type = EventTypes.SWIPE;
                awesomeMap.handleInteractionEvent(null, args);
                expect(awesomeMap._transformationQueue.enqueue).not.toHaveBeenCalled();
            });

            it('should not respond to dragstart events', function() {
                args.event.type = EventTypes.DRAG_START;
                awesomeMap.handleInteractionEvent(null, args);
                expect(awesomeMap._transformationQueue.enqueue).not.toHaveBeenCalled();
            });

            it('should not respond to dragend events', function() {
                args.event.type = EventTypes.DRAG_END;
                awesomeMap.handleInteractionEvent(null, args);
                expect(awesomeMap._transformationQueue.enqueue).not.toHaveBeenCalled();
            });
        });

        describe('panning', function() {
            it('should pan by relative distance', function() {
                var finished = false;
                var done = function() { finished = true; };

                runs(function() {
                    awesomeMap.panBy({ x: 100, y: 200, duration: 0, done: done });
                });

                waitsFor(function() { return finished; }, 250);

                runs(function() {
                    var state = awesomeMap.getCurrentTransformState();
                    expect(state.translateX).toBe(100);
                    expect(state.translateY).toBe(200);
                });
            });

            it('should pan to a position', function() {
                var finished = false;
                var done = function() { finished = true; };

                runs(function() {
                    awesomeMap.panTo({ x: 50, y: 75, duration: 0, done: done });
                });

                waitsFor(function() { return finished; }, 250);

                runs(function() {
                    var state = awesomeMap.getCurrentTransformState();
                    expect(state.translateX).toBe(50);
                    expect(state.translateY).toBe(75);
                });
            });
        });

        describe('swiping', function() {

            it('should simulate a swipe', function() {
                var done = function() {};
                var options = { direction: 'up', velocity: 1, duration: 1000, done: done };

                spyOn(awesomeMap._interactionSimulator, 'simulateSwipe');

                awesomeMap.swipe(options);

                expect(awesomeMap._interactionSimulator.simulateSwipe).toHaveBeenCalledWith(options);
            });
        });

        describe('transforming', function() {

            it('should apply a transform directly', function() {
                runs(function() {
                    var target = awesomeMap.getTransformationPlane();
                    var options = { x: -10, y: -20, scale: 2 };

                    spyOn(TransformUtil, 'applyTransform');
                    awesomeMap.transform(options);

                    expect(TransformUtil.applyTransform).toHaveBeenCalled();
                    var call = TransformUtil.applyTransform.calls[0];
                    var appliedTarget = call.args[0];
                    expect(appliedTarget).toBe(target);
                    var appliedState = call.args[1];
                    expect(appliedState.translateX).toBe(options.x);
                    expect(appliedState.translateY).toBe(options.y);
                    expect(appliedState.scale).toBe(options.scale);
                });
            });

            it('should set the current transform state', function() {
                spyOn(TransformUtil, 'applyTransform');
                spyOn(awesomeMap, 'setCurrentTransformState');

                var options = { x: -10, y: -20, scale: 2 };
                awesomeMap.transform(options);

                expect(awesomeMap.setCurrentTransformState).toHaveBeenCalled();
                var appliedState = awesomeMap.setCurrentTransformState.calls[0].args[0];
                expect(appliedState.translateX).toBe(options.x);
                expect(appliedState.translateY).toBe(options.y);
                expect(appliedState.scale).toBe(options.scale);
            });
        });

        describe('zooming', function() {

            it('should zoom by relative scale', function() {
                var finished = false;
                var done =  function() { finished = true; };

                runs(function() {
                    awesomeMap.zoomBy({ scale: 2, duration: 0, done: done });
                });

                waitsFor(function() { return finished; }, 250);

                runs(function() {
                    var state = awesomeMap.getCurrentTransformState();
                    expect(state.scale).toBe(2);
                });
            });

            it('should zoom to a scale', function() {
                var finished = false;
                var done = function() { finished = true; };

                runs(function() {
                    awesomeMap.zoomTo({ scale: 1.5, duration: 0, done: done });
                });

                waitsFor(function() { return finished; }, 250);

                runs(function() {
                    var state = awesomeMap.getCurrentTransformState();
                    expect(state.scale).toBe(1.5);
                });
            });
        });

        describe('handling interaction events', function() {

            function createInteractionEvent(eventType) {
                return new InteractionEvent(eventType, new Gesture(), new Gesture());
            }

            it('should not handle an event if an onInteraction subscriber returns false', function() {
                var evt = createInteractionEvent(EventTypes.RESIZE);

                spyOn(awesomeMap._transformationQueue, 'enqueue');
                spyOn(awesomeMap._transformationQueue, 'processEvents');
                awesomeMap.onInteraction(function() { return false; });
                awesomeMap.handleInteractionEvent(null, { event: evt });

                expect(evt.cancelled).toBe(true);
                expect(awesomeMap._transformationQueue.enqueue).not.toHaveBeenCalled();
                expect(awesomeMap._transformationQueue.processEvents).not.toHaveBeenCalled();
            });

            it('should cancel the current transformation on touch and set the current state', function() {
                var touch = createInteractionEvent(EventTypes.TOUCH);
                var queue = awesomeMap._transformationQueue;
                var cancelledState = new TransformState();

                spyOn(queue, 'cancelCurrentTransformation').andReturn(cancelledState);
                spyOn(awesomeMap, 'setCurrentTransformState');
                awesomeMap.handleInteractionEvent(null, { event: touch });

                expect(queue.cancelCurrentTransformation).toHaveBeenCalled();
                expect(awesomeMap.setCurrentTransformState).toHaveBeenCalledWith(cancelledState);
            });

            it('should dispatch "onInteractionStarted" observable on mouse wheel start events', function() {
                var evt = createInteractionEvent(EventTypes.MOUSE_WHEEL_START);

                spyOn(awesomeMap.onInteractionStarted, 'dispatch');
                awesomeMap.handleInteractionEvent(null, { event: evt });

                expect(awesomeMap.onInteractionStarted.dispatch).toHaveBeenCalledWith([awesomeMap]);
            });

            it('should dispatch "onInteractionStarted" observable on touch events', function() {
                var evt = createInteractionEvent(EventTypes.TOUCH);

                spyOn(awesomeMap.onInteractionStarted, 'dispatch');
                awesomeMap.handleInteractionEvent(null, { event: evt });

                expect(awesomeMap.onInteractionStarted.dispatch).toHaveBeenCalledWith([awesomeMap]);
            });

            it('should not dispatch "onInteractionStarted" observable on touch events that interrupt transformations', function() {
                var evt = createInteractionEvent(EventTypes.TOUCH);
                var queue = awesomeMap._transformationQueue;
                var cancelledState = new TransformState();

                spyOn(queue, 'cancelCurrentTransformation').andReturn(cancelledState);
                spyOn(awesomeMap.onInteractionStarted, 'dispatch');
                awesomeMap.handleInteractionEvent(null, { event: evt });

                expect(awesomeMap.onInteractionStarted.dispatch).not.toHaveBeenCalledWith([awesomeMap]);
            });

            it('should invalidate viewport dimensions on resize', function() {
                var evt = createInteractionEvent(EventTypes.RESIZE);
                var viewportDimensions = awesomeMap.getViewportDimensions();

                // Resize the element, should still have stale values
                // (haven't yet handled resize event)
                $host.css({ width: 1000, height: 1000 });
                expect(viewportDimensions.width).toBe(500);
                expect(viewportDimensions.height).toBe(500);

                // Now handle the resize event, which should invalidate the viewport dimensions.
                awesomeMap.handleInteractionEvent(null, { event: evt });
                viewportDimensions = awesomeMap.getViewportDimensions();
                expect(viewportDimensions.width).toBe(1000);
                expect(viewportDimensions.height).toBe(1000);
            });

            it('should dispatch "onInteraction" observable', function() {
                var callback = function() {};
                var evt = createInteractionEvent(null);
                var transformState = new TransformState();

                spyOn(awesomeMap.onInteraction, 'dispatch');
                spyOn(awesomeMap, 'getCurrentTransformState').andReturn(transformState);
                awesomeMap.onInteraction(callback);
                awesomeMap.handleInteractionEvent(null, { event: evt });

                expect(awesomeMap.onInteraction.dispatch).toHaveBeenCalledWith([
                    awesomeMap,
                    { event: evt, currentState: transformState }
                ], jasmine.any(Function));
            });

            it('should set current state to end state of event transformation', function() {
                var evt = createInteractionEvent(EventTypes.Drag);

                spyOn(awesomeMap, 'setCurrentTransformState');
                awesomeMap.handleInteractionEvent(null, { event: evt });

                expect(awesomeMap.setCurrentTransformState).toHaveBeenCalled();
            });

            it('should apply a 2d transform at the end of the interaction', function() {
                var evt = createInteractionEvent(EventTypes.MOUSE_WHEEL_END);

                spyOn(TransformUtil, 'applyTransform');
                awesomeMap.handleInteractionEvent(null, { event: evt });

                expect(TransformUtil.applyTransform).toHaveBeenCalledWith(
                    awesomeMap.getTransformationPlane(),
                    awesomeMap.getCurrentTransformState(),
                    true /* use2d */
                );
            });

            it('should dispatch "onInteractionFinished" observable on mouse wheel end events', function() {
                var evt = createInteractionEvent(EventTypes.MOUSE_WHEEL_END);

                spyOn(awesomeMap.onInteractionFinished, 'dispatch');
                awesomeMap.handleInteractionEvent(null, { event: evt });

                expect(awesomeMap.onInteractionFinished.dispatch).toHaveBeenCalledWith([awesomeMap]);
            });

            it('should dispatch "onInteractionFinished" observable on release events', function() {
                var evt = createInteractionEvent(EventTypes.RELEASE);

                spyOn(awesomeMap.onInteractionFinished, 'dispatch');
                awesomeMap.handleInteractionEvent(null, { event: evt });

                expect(awesomeMap.onInteractionFinished.dispatch).toHaveBeenCalledWith([awesomeMap]);
            });

            it('should dispatch "onInteractionStarted" observable on release events when dispatch is deferred', function() {
                var touch = createInteractionEvent(EventTypes.TOUCH);
                var release = createInteractionEvent(EventTypes.RELEASE);

                spyOn(awesomeMap._transformationQueue, 'cancelCurrentTransformation').andReturn(new TransformState());
                spyOn(awesomeMap.onInteractionStarted, 'dispatch');
                awesomeMap.handleInteractionEvent(null, { event: touch });
                awesomeMap.handleInteractionEvent(null, { event: release });

                expect(awesomeMap.onInteractionStarted.dispatch).toHaveBeenCalledWith([awesomeMap]);
            });
        });
    });
});


text:
class StatefulSSLHostStateDelegate;
class Profile;

// Singleton that associates all StatefulSSLHostStateDelegates with
// Profiles.
class StatefulSSLHostStateDelegateFactory
    : public BrowserContextKeyedServiceFactory {
 public:
  static StatefulSSLHostStateDelegate* GetForProfile(Profile* profile);

  static StatefulSSLHostStateDelegateFactory* GetInstance();

  StatefulSSLHostStateDelegateFactory(
      const StatefulSSLHostStateDelegateFactory&) = delete;
  StatefulSSLHostStateDelegateFactory& operator=(
      const StatefulSSLHostStateDelegateFactory&) = delete;

  // Returns the default factory, useful in tests where it's null by default.
  static TestingFactory GetDefaultFactoryForTesting();

 private:
  friend struct base::DefaultSingletonTraits<
      StatefulSSLHostStateDelegateFactory>;

  StatefulSSLHostStateDelegateFactory();
  ~StatefulSSLHostStateDelegateFactory() override;

  // BrowserContextKeyedServiceFactory methods:
  KeyedService* BuildServiceInstanceFor(
      content::BrowserContext* context) const override;
  content::BrowserContext* GetBrowserContextToUse(
      content::BrowserContext* context) const override;
  bool ServiceIsNULLWhileTesting() const override;
};

#endif  // CHROME_BROWSER_SSL_STATEFUL_SSL_HOST_STATE_DELEGATE_FACTORY_H_


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace _01.WebFormsAppWithMasterPage
{
    public partial class Site : System.Web.UI.MasterPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
    }
}


text:
#region License

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

#endregion

using System.Collections.Generic;
using System.Diagnostics.Contracts;

namespace Paraiba.Algorithm {
    public static class Sort {
        private static void Merge<T>(
            IList<T> list, IComparer<T> cmp, int left, int center, int right,
            T[] work) {
            Contract.Requires(list != null);
            Contract.Requires(cmp != null);
            Contract.Requires(work != null);
            Contract.Requires(0 <= left);
            Contract.Requires(left < center);
            Contract.Requires(center < right);
            Contract.Requires(right <= list.Count);

            var leftMax = list[center - 1];
            {
                var tmp = list[center];
                // 既に整列済みかどうか調べる(番兵的)
                if (cmp.Compare(leftMax, tmp) <= 0) {
                    return;
                }
                // 左端の要素で移動する必要がないものはスキップする
                while (cmp.Compare(list[left], tmp) <= 0) {
                    left++;
                }
            }

            // 一時的にコピー
            for (int i = left; i < center; i++) {
                work[i - left] = list[i];
            }

            int l = 0, r = center, o = left, endl = center - left;
            // 最後に移動する要素は左側か右側か
            if (cmp.Compare(leftMax, list[right - 1]) <= 0) {
                do {
                    if (cmp.Compare(work[l], list[r]) <= 0) {
                        list[o] = work[l++];
                    } else {
                        list[o] = list[r++];
                    }
                    o++;
                } while (l < endl); // 左側がなくなれば、残った右側はそのままで良い
            } else {
                int endr = right;
                do {
                    if (cmp.Compare(work[l], list[r]) <= 0) {
                        list[o] = work[l++];
                    } else {
                        list[o] = list[r++];
                    }
                    o++;
                } while (r < endr); // 右側がなくなるまで

                // 残った左側の移動
                do {
                    list[o++] = work[l++];
                } while (l < endl);
            }
        }

        public static void MergeSort<T>(
            IList<T> list, IComparer<T> cmp, int left, int right, T[] work) {
            Contract.Requires(list != null);
            Contract.Requires(cmp != null);
            Contract.Requires(0 <= left);
            Contract.Requires(right <= list.Count);
            Contract.Requires(work != null);
            Contract.Requires(work.Length >= list.Count >> 1);

            var n = right - left;
            if (n <= 16) {
                InsertionSort(list, cmp, left, right);
                return;
            }

            n >>= 1;
            MergeSort(list, cmp, left, left + n, work);
            MergeSort(list, cmp, left + n, right, work);

            Merge(list, cmp, left, left + n, right, work);
        }

        public static void MergeSort<T>(IList<T> list, IComparer<T> cmp) {
            Contract.Requires(list != null);
            Contract.Requires(cmp != null);

            var count = list.Count;
            var work = new T[count >> 1];
            MergeSort(list, cmp, 0, count, work);
        }

        public static void MergeSort<T>(IList<T> list) {
            Contract.Requires(list != null);

            MergeSort(list, Comparer<T>.Default);
        }

        public static void InsertionSort<T>(
            IList<T> list, IComparer<T> cmp, int left, int right) {
            Contract.Requires(list != null);
            Contract.Requires(cmp != null);
            Contract.Requires(0 <= left);
            Contract.Requires(right <= list.Count);

            for (int i = right - 2; i >= left; i--) {
                if (cmp.Compare(list[i], list[i + 1]) > 0) {
                    var tmp = list[i];
                    list[i] = list[i + 1];
                    list[i + 1] = tmp;
                }
            }
            for (int i = left + 2; i < right; i++) {
                var item = list[i];
                if (cmp.Compare(list[i - 1], item) > 0) {
                    var j = i - 1;
                    do {
                        list[j + 1] = list[j];
                        j--;
                    } while (cmp.Compare(list[j], item) > 0);
                    list[j + 1] = item;
                }
            }
        }
    }
}


text:
from pygametk.color import ColorFunction
from pygametk.geometry import Size
from pygametk.store import StoreListener
from pygametk.widget import VExpand, HExpand, Entry
from pygametk.widgets.grid import GridView, make_text_row
from pygametk.widgets.layout import LayoutHBox, LayoutVBox, make_centerized

import api.font.icon

from plugin.common.templates import *

from plugin.svtplay.actions.dialogs import SvtPlayProgramDialogRunner
from plugin.svtplay.data.search import SvtPlaySearchStoreListener

def format_title(program, _key):
    return program.title

def get_image_url(program):
    return program.image_url

def make_image_getter(images):
    return lambda program: images.get(get_image_url(program), None)

def make_grid_view(store, theme, images):
    view_theme = {
        "image_ratio": Size(160, 90),
        "items_per_row": 4,
        "padding": theme["grid"]["view"]["padding"],
        "border": theme["grid"]["view"]["border"],
        "textbox": theme["grid"]["view"]["textbox"]
    }

    text_rows = [
        make_text_row(format_title, None, 1.0)
    ]

    view = GridView(store, text_rows, view_theme, make_image_getter(images))
    view.show()

    return view

class SubLabelUpdater(SvtPlaySearchStoreListener):

    def __init__(self, label):
        self.label = label

    def store_changed(self, store):
        if len(store) > 0:
            text = "%i items" % len(store)
            self.label.set_text(text)
        else:
            self.label.set_text("")

class ViewFocuser(SvtPlaySearchStoreListener):

    def __init__(self, view):
        self.view = view

    def search_finished(self, store):
        self.view.focus()

class MainWidgetViewer(SvtPlaySearchStoreListener):

    def __init__(self, label_box, view, label, sub_label):
        self.label_box = label_box
        self.view = view
        self.label = label
        self.sub_label = sub_label

        self.label.set_text("No search active")

    def only_show_view(self):
        self.label_box.hide()
        self.sub_label.show()
        self.view.show()

    def only_show_label(self, text):
        self.view.hide()
        self.sub_label.hide()
        self.label_box.show()
        self.label.set_text(text)

    def fix(self, store, search):
        if search:
            if len(store) > 0:
                self.only_show_view()
            else:
                self.only_show_label("No results found!")
        else:
            self.only_show_label("No active search")

    def search_started(self, store):
        self.only_show_label("Searching...")

    def search_finished(self, store):
        self.fix(store, True)

    def search_cleared(self, store):
        self.fix(store, False)

class ProgramImageFetcher(SvtPlaySearchStoreListener):

    def __init__(self, images, imagefetcher_handler):
        self.images = images
        self.imagefetcher_handler = imagefetcher_handler

    def _update_image(self, result):
        if "image" in result and "url" in result:
            self.images[result["url"]] = result["image"]

    def _fetch_images(self, store):
        image_items = []

        for program in store:
            image_items.append({"url": get_image_url(program)})

        self.imagefetcher_handler.fetch_multiple("svtplay", image_items, False,
                self._update_image)

    def search_finished(self, store):
        self.images.clear()
        self._fetch_images(store)

def setup_activated_signal(view, context):
    action = SvtPlayProgramDialogRunner(context)
    view.connect("activated", action)

def svtplay_search_widget_factory(name, args, context):
    search = context.data["svtplay"].search  # TODO: get_search_store(context)
    theme = context.theme
    config = context.config

    images = {}

    view = make_grid_view(search, theme, images)

    sub_label = make_h3("", theme)

    search.add_listener(SubLabelUpdater(sub_label))

    main_label = make_h2("No active search", theme)
    search_label_box = make_centerized(main_label)

    vbox = LayoutVBox()
    vbox.add(make_h1_padding(theme))
    vbox.add(sub_label)
    vbox.add(make_h3_padding(theme))
    vbox.add(search_label_box)
    vbox.show_all()

    vbox.add(view)
    view.hide()

    view.focus()

    viewer = MainWidgetViewer(search_label_box, view, main_label, sub_label)
    viewer.fix(search, False)

    focuser = ViewFocuser(view)

    imagefetcher_handler = context.handlers["imagefetcher"]
    program_image_fetcher = ProgramImageFetcher(images, imagefetcher_handler)

    search.add_listener(viewer)
    search.add_listener(focuser)
    search.add_listener(program_image_fetcher)

    vbox.set_attribute("view", view)

    setup_activated_signal(view, context)

    return vbox

def get_widget_factories():
    return {"svtplay_search": svtplay_search_widget_factory}


text:
class LongitudinalFeaturesLagger {
 protected:
  ulong n_intervals;
  SArrayULongPtr n_lags;
  ArrayULong col_offset;
  ulong n_samples;
  ulong n_observations;
  ulong n_features;
  ulong n_lagged_features;

 public:
  LongitudinalFeaturesLagger(const SBaseArrayDouble2dPtrList1D &features,
                             const SArrayULongPtr n_lags);

  void dense_lag_preprocessor(ArrayDouble2d &features, ArrayDouble2d &out,
                              ulong censoring) const;

  void sparse_lag_preprocessor(ArrayULong &row, ArrayULong &col,
                               ArrayDouble &data, ArrayULong &out_row,
                               ArrayULong &out_col, ArrayDouble &out_data,
                               ulong censoring) const;

  template <class Archive>
  void serialize(Archive &ar) {
    ar(CEREAL_NVP(n_intervals));
    ar(CEREAL_NVP(n_lags));
    ar(CEREAL_NVP(col_offset));
    ar(CEREAL_NVP(n_samples));
    ar(CEREAL_NVP(n_observations));
    ar(CEREAL_NVP(n_features));
    ar(CEREAL_NVP(n_lagged_features));
  }
};

#endif  // LIB_INCLUDE_TICK_PREPROCESSING_LONGITUDINAL_FEATURES_LAGGER_H_


text:
namespace DAVA
{
TransformCommand::TransformCommand(Selectable object_, const Transform& origTransform_, const Transform& newTransform_)
    : RECommand("Transform")
    , object(object_)
    , undoTransform(origTransform_)
    , redoTransform(newTransform_)
{
}

void TransformCommand::Undo()
{
    object.SetLocalTransform(undoTransform);
}

void TransformCommand::Redo()
{
    object.SetLocalTransform(redoTransform);
}

const Selectable& TransformCommand::GetTransformedObject() const
{
    return object;
}

Entity* TransformCommand::GetEntity() const
{
    return object.AsEntity();
}

DAVA_VIRTUAL_REFLECTION_IMPL(TransformCommand)
{
    ReflectionRegistrator<TransformCommand>::Begin()
    .End();
}
} // namespace DAVA


text:
package main

import "fmt"

func main() {
	ferrari := Ferrari{}.New()
	aston := NewCarFromValue(carType{"Aston Martin", "Lagonda", 6})
	lamborghini := Lamborghini{}.New()

	fmt.Println("Ferrari is", ferrari)
	fmt.Println("Aston Martin is", aston)
	fmt.Println("Lamborghini is", lamborghini)
}


text:
package ameba.mvc.template.internal;

import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.server.model.ModelProcessor;
import org.glassfish.jersey.server.mvc.spi.ViewableContext;

import javax.inject.Singleton;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.WriterInterceptor;

/**
 * Provides MVC functionality.
 *
 * @author Michal Gajdos (michal.gajdos at oracle.com)
 * @author icode
 */
public class MvcBinder extends AbstractBinder {

    @Override
    protected void configure() {
        bind(TemplateMethodInterceptor.class).to(WriterInterceptor.class).in(Singleton.class);
        //noinspection unchecked
        bind(TemplateMessageBodyWriter.class).to(MessageBodyWriter.class).in(Singleton.class);
        bind(ViewableMessageBodyWriter.class).to(MessageBodyWriter.class).in(Singleton.class);

        bind(TemplateModelProcessor.class).to(ModelProcessor.class).in(Singleton.class);
        bindAsContract(ResolvingViewableContext.class).in(Singleton.class);
        bind(ResolvingViewableContext.class).to(ViewableContext.class).in(Singleton.class).ranked(Integer.MIN_VALUE);
    }
}


text:
package ru.stqa.pft.mantis.appmanager;

import biz.futureware.mantis.rpc.soap.client.*;
import ru.stqa.pft.mantis.model.Issue;
import ru.stqa.pft.mantis.model.Project;

import javax.xml.rpc.ServiceException;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;

public class SoapHelper {

    private final ApplicationManager app;

    public SoapHelper (ApplicationManager app){
        this.app = app;
    }

    public Set<Project> getProjects() throws MalformedURLException, ServiceException, RemoteException {
        MantisConnectPortType mc = getMantisConnect();
        ProjectData[] projects = mc.mc_projects_get_user_accessible(
                app.getProperty("web.adminLogin"),
                app.getProperty("web.adminPassword")
        );
        return Arrays.asList(projects).stream()
                .map(
                        (p) -> new Project()
                                .withId(p.getId().intValue())
                                .withName(p.getName())
                )
                .collect(Collectors.toSet());
    }

    private MantisConnectPortType getMantisConnect() throws ServiceException, MalformedURLException {
        return new MantisConnectLocator()
                    .getMantisConnectPort(
                            new URL(app.getProperty("wsdl.url"))
                    );
    }

    public Issue addIssue(Issue issue) throws MalformedURLException, ServiceException, RemoteException {
        MantisConnectPortType mc = getMantisConnect();
        String[] categories = mc.mc_project_get_categories(
                app.getProperty("web.adminLogin"),
                app.getProperty("web.adminPassword"),
                BigInteger.valueOf(issue.getProject().getId())
        );
        IssueData issueData = new IssueData();
        issueData.setSummary(issue.getSummary());
        issueData.setDescription(issue.getDescription());
        issueData.setProject(
                new ObjectRef(
                        BigInteger.valueOf(issue.getProject().getId()),
                        issue.getProject().getName()
                )
        );
        issueData.setCategory(categories[0]);
        BigInteger issueId = mc.mc_issue_add(
                app.getProperty("web.adminLogin"),
                app.getProperty("web.adminPassword"),
                issueData
        );
        IssueData createdIssueData = mc.mc_issue_get(
                app.getProperty("web.adminLogin"),
                app.getProperty("web.adminPassword"),
                issueId
        );
        return new Issue()
                .withId(createdIssueData.getId().intValue())
                .withSummary(createdIssueData.getSummary())
                .withDescription(createdIssueData.getDescription())
                .withProject(
                        new Project()
                                .withId(createdIssueData.getProject().getId().intValue())
                                .withName(createdIssueData.getProject().getName())
                );
    }

    public Issue getIssue(int issueId) throws MalformedURLException, ServiceException, RemoteException {
        MantisConnectPortType mc = getMantisConnect();
        IssueData issue = mc.mc_issue_get(
                app.getProperty("web.adminLogin"),
                app.getProperty("web.adminPassword"),
                BigInteger.valueOf(issueId)
        );
        return new Issue()
                .withId(issue.getId().intValue())
                .withSummary(issue.getSummary())
                .withDescription(issue.getDescription())
                .withProject( new Project()
                                .withId(issue.getProject().getId().intValue())
                                .withName(issue.getProject().getName()))
                .withStatus(issue.getStatus().getName());
    }
}


text:
package utils.events;

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

import java.util.List;

import info.novatec.testit.webtester.events.Event;
import info.novatec.testit.webtester.events.EventSystem;

public class MultiEventCaptor<E extends Event> {

    private final EventSystem eventSystem;
    private final Class<E> eventClass;
    private MultiEventCollectingListener listener;

    private MultiEventCaptor(EventSystem eventSystem, Class<E> eventClass) {
        this.eventSystem = eventSystem;
        this.eventClass = eventClass;
    }

    public MultiEventCaptor<E> execute(Runnable runnable) {
        listener = new MultiEventCollectingListener();
        eventSystem.register(listener);
        try {
            runnable.run();
        } finally {
            eventSystem.deregister(listener);
        }
        return this;
    }

    public MultiEventCaptor<E> assertEventsWereFired(int count) throws ClassCastException {
        List<Event> events = listener.getEvents();
        assertThat(events).hasSize(count);
        events.forEach(event -> assertThat(event).isExactlyInstanceOf(eventClass));
        return this;
    }

    public void assertEventsWereNotFired() {
        List<Event> events = listener.getEvents();
        assertThat(events).isEmpty();
    }

    public static <E extends Event> MultiEventCaptor<E> capture(EventSystem eventSystem, Class<E> eventClass) {
        return new MultiEventCaptor<>(eventSystem, eventClass);
    }

}


text:
package com.capitalone.dashboard.rest;

import com.capitalone.dashboard.model.DataResponse;
import com.capitalone.dashboard.model.Feature;
import com.capitalone.dashboard.service.FeatureService;

import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

import static org.springframework.web.bind.annotation.RequestMethod.GET;

/**
 * REST service managing all requests to the feature repository.
 *
 * @author KFK884
 *
 */
@RestController
public class FeatureController {
	private static final String JSON = MediaType.APPLICATION_JSON_VALUE;
	private final FeatureService featureService;

	@Autowired
	public FeatureController(FeatureService featureService) {
		this.featureService = featureService;
	}

	/**
	 * REST endpoint for retrieving all features for a given sprint and team
	 * (the sprint is derived)
	 *
	 * @param teamId
	 *            A given scope-owner's source-system ID
	 * @return A data response list of type Feature containing all features for
	 *         the given team and current sprint
	 */
	@RequestMapping(value = "/feature/{teamId}", method = GET, produces = JSON)
	public DataResponse<List<Feature>> relevantStories(
			@RequestParam(value = "component", required = true) String cId,
			@PathVariable String teamId) {
		ObjectId componentId = new ObjectId(cId);
		return this.featureService.getRelevantStories(componentId, teamId);
	}

	/**
	 * REST endpoint for retrieving all features for a given sprint and team
	 * (the sprint is derived)
	 *
	 * @param teamId
	 *            A given scope-owner's source-system ID
	 * @return A data response list of type Feature containing all features for
	 *         the given team and current sprint
	 */
	@RequestMapping(value = "/feature", method = GET, produces = JSON)
	public DataResponse<List<Feature>> story(
			@RequestParam(value = "component", required = true) String cId,
			@RequestParam(value = "number", required = true) String storyNumber) {
		ObjectId componentId = new ObjectId(cId);
		return this.featureService.getStory(componentId, storyNumber);
	}

	/**
	 * REST endpoint for retrieving the current sprint detail for a team
	 *
	 * @param teamId
	 *            A given scope-owner's source-system ID
	 * @return A response list of type Feature containing the done estimate of
	 *         current features
	 */
	@RequestMapping(value = "/iteration/{teamId}", method = GET, produces = JSON)
	public DataResponse<List<Feature>> currentSprintDetail(
			@RequestParam(value = "component", required = true) String cId,
			@PathVariable String teamId) {
		ObjectId componentId = new ObjectId(cId);
		return this.featureService.getCurrentSprintDetail(componentId, teamId);
	}

	/**
	 * REST endpoint for retrieving only the unique super features for a given
	 * team and sprint and their related estimates
	 *
	 * @param teamId
	 *            A given scope-owner's source-system ID
	 * @return A response list of type Feature containing the unique features
	 *         plus their sub features' estimates associated to the current
	 *         sprint and team
	 */
	@RequestMapping(value = "/feature/estimates/super/{teamId}", method = GET, produces = JSON)
	public DataResponse<List<Feature>> featureEstimates(
			@RequestParam(value = "component", required = true) String cId,
			@PathVariable String teamId) {
		ObjectId componentId = new ObjectId(cId);
		return this.featureService.getFeatureEstimates(componentId, teamId);
	}

	/**
	 * REST endpoint for retrieving the current total estimate for a team and
	 * sprint
	 *
	 * @param teamId
	 *            A given scope-owner's source-system ID
	 * @return A response list of type Feature containing the total estimate of
	 *         current features
	 */
	@RequestMapping(value = "/feature/estimates/total/{teamId}", method = GET, produces = JSON)
	public DataResponse<List<Feature>> featureTotalEstimate(
			@RequestParam(value = "component", required = true) String cId,
			@PathVariable String teamId) {
		ObjectId componentId = new ObjectId(cId);
		return this.featureService.getTotalEstimate(componentId, teamId);
	}

	/**
	 * REST endpoint for retrieving the current in-progress estimate for a team
	 * and sprint
	 *
	 * @param teamId
	 *            A given scope-owner's source-system ID
	 * @return A response list of type Feature containing the in-progress
	 *         estimate of current features
	 */
	@RequestMapping(value = "/feature/estimates/wip/{teamId}", method = GET, produces = JSON)
	public DataResponse<List<Feature>> featureInProgressEstimate(
			@RequestParam(value = "component", required = true) String cId,
			@PathVariable String teamId) {
		ObjectId componentId = new ObjectId(cId);
		return this.featureService.getInProgressEstimate(componentId, teamId);
	}

	/**
	 * REST endpoint for retrieving the current done estimate for a team and
	 * sprint
	 *
	 * @param teamId
	 *            A given scope-owner's source-system ID
	 * @return A response list of type Feature containing the done estimate of
	 *         current features
	 */
	@RequestMapping(value = "/feature/estimates/done/{teamId}", method = GET, produces = JSON)
	public DataResponse<List<Feature>> featureDoneEstimate(
			@RequestParam(value = "component", required = true) String cId,
			@PathVariable String teamId) {
		ObjectId componentId = new ObjectId(cId);
		return this.featureService.getDoneEstimate(componentId, teamId);
	}
}


text:
import React, {Component} from 'react';
import {
    StyleSheet,
    Animated,
    TouchableWithoutFeedback,
    View,
    ScrollView,
    ART,
    Dimensions
} from 'react-native';

import Morph from 'art/morph/path';

let {
    Surface,
    Shape,

    LinearGradient,
    RadialGradient,
    Pattern,
    Transform,
    Path,
    Group,
    ClippingRectangle,
    Text

} = ART;

let BatmanLogoSVGs = [
    'M 10,0 L 90,0 M 10,40 L 90,40 M 10,80 L 90,80',
    'M 10,40 L 40,0 M 10,40 L 90,40 M 10,40 L 40,80',
    'M 10,0 L 90,0 M 10,40 L 90,40 M 10,80 L 90,80'
];

var BatmanLogoPaths = BatmanLogoSVGs.map((svg) => Morph.Path(svg));

export default class AnimateButton extends Component {
    constructor (props) {
        super(props);

        this.state = {
            transition: Morph.Tween(BatmanLogoPaths[0], BatmanLogoPaths[1]),
        };

        this._current = 1;
    }

    nextAnimation = () => {
        console.log('do next animation');

        this._current += 1;
        if (this._current >= BatmanLogoPaths.length) {
            return;
        }

        this.setState({
            transition: Morph.Tween(BatmanLogoPaths[this._current - 1], BatmanLogoPaths[this._current])
        });

        this.animate(null, this.nextAnimation);
    };

    animate (start, callback) {
        requestAnimationFrame((timestamp) => {
            if (!start) {
                start = timestamp;
            }

            let delta = (timestamp - start) / 500;

            if (delta > 1) {
                return callback();
            }

            this.state.transition.tween(delta);
            this.setState(this.state);
            this.animate(start, callback);
        });

    }

    render () {
        return (
            <View>
                <TouchableWithoutFeedback
                    onPress={() => {
                        this.animate(null, this.nextAnimation)
                    }}
                >
                    <View style={{flex: 1, backgroundColor: '#fff'}}>
                        <Surface width={100} height={100}>
                            <Shape
                                x={0}
                                y={2}
                                d={this.state.transition}
                                stroke="#000000"
                                strokeWidth="2"
                            />
                        </Surface>
                    </View>
                </TouchableWithoutFeedback>
            </View>
        )
    }
}


text:
package com.mozilla.fhr.pig.eval;

import java.io.IOException;
import java.util.Map;

import org.apache.pig.EvalFunc;
import org.apache.pig.data.BagFactory;
import org.apache.pig.data.DataBag;
import org.apache.pig.data.Tuple;
import org.apache.pig.data.TupleFactory;

public class CrashTuples extends EvalFunc<DataBag> {

    private static final String CRASHES_FIELD = "org.mozilla.crashes.crashes";
    private static final String CRASHES_PENDING_FIELD = "pending";
    private static final String CRASHES_SUBMITTED_FIELD = "submitted";

    private static final String ADDON_COUNTS_FIELD = "org.mozilla.addons.counts";
    private static final String EXTENSION_FIELD = "extension";
    private static final String PLUGIN_FIELD = "plugin";
    private static final String THEME_FIELD = "theme";

    private static final String APPSESSIONS_FIELD = "org.mozilla.appSessions.previous";
    private static final String ABORTED_TOTALTIME_FIELD = "abortedTotalTime";

    private static BagFactory bagFactory = BagFactory.getInstance();
    private static TupleFactory tupleFactory = TupleFactory.getInstance();

    private int getSafeInt(Object o) {
        if (o == null) {
            return 0;
        }

        return ((Number)o).intValue();
    }

    @SuppressWarnings("unchecked")
    @Override
    public DataBag exec(Tuple input) throws IOException {
        if (input == null || input.size() == 0) {
            return null;
        }

        DataBag dbag = bagFactory.newDefaultBag();
        Map<String,Object> dataPoints = (Map<String,Object>)input.get(0);
        for (Map.Entry<String, Object> dayEntry : dataPoints.entrySet()) {

            String dayStr = dayEntry.getKey();
            Map<String,Object> dayMap = (Map<String,Object>)dayEntry.getValue();

            if ((dayMap.containsKey(CRASHES_FIELD) || dayMap.containsKey(ADDON_COUNTS_FIELD)) || dayMap.containsKey(APPSESSIONS_FIELD)) {

                // crash info
                Map<String,Object> crashesMap = (Map<String,Object>)dayMap.get(CRASHES_FIELD);
                int crashCountPending = 0, crashCountSubmitted = 0;
                if (crashesMap != null) {
                    crashCountPending = getSafeInt(crashesMap.get(CRASHES_PENDING_FIELD));
                    crashCountSubmitted = getSafeInt(crashesMap.get(CRASHES_SUBMITTED_FIELD));
                }

                // aborted sessions info
                Map<String,Object> sessionsMap = (Map<String,Object>)dayMap.get(APPSESSIONS_FIELD);
                int abortedSessionsCount = 0;
                if (sessionsMap != null) {
                    DataBag abortedSessionTimesBag = (DataBag) sessionsMap.get(ABORTED_TOTALTIME_FIELD);
                    if (abortedSessionTimesBag != null)
                        abortedSessionsCount = (int) abortedSessionTimesBag.size();
                }

                // addons info
                Map<String,Object> addonCountMap = (Map<String,Object>)dayMap.get(ADDON_COUNTS_FIELD);
                int themeCount = 0, extensionCount = 0, pluginCount = 0;
                if (addonCountMap != null) {
                    themeCount = getSafeInt(addonCountMap.get(THEME_FIELD));
                    extensionCount = getSafeInt(addonCountMap.get(EXTENSION_FIELD));
                    pluginCount = getSafeInt(addonCountMap.get(PLUGIN_FIELD));
                }

                VersionOnDate vod = new VersionOnDate("yyyy-MM-dd", dayStr);
                final String productVersionOnDate = vod.exec(input);

                Tuple t = tupleFactory.newTuple(8);
                t.set(0, dayStr);
                t.set(1, productVersionOnDate);
                t.set(2, crashCountPending);
                t.set(3, crashCountSubmitted);
                t.set(4, themeCount);
                t.set(5, extensionCount);
                t.set(6, pluginCount);
                t.set(7, abortedSessionsCount);
                dbag.add(t);
            }
        }

        return dbag;
    }

}