text:
//
// Copyright (c) 2002-2018 WEINZIERL ENGINEERING GmbH
// All rights reserved.
//
// 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY,
// WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE
//

#include "pch/kdrive_pch.h"
#include "kdrive/utility/Logger.h"
#include "kdrive/connector/CallbackThread.h"
#include <Poco/Logger.h>
#include <Poco/Mutex.h>
#include <Poco/Timer.h>
#include <Poco/SingletonHolder.h>
#include <boost/assert.hpp>

using Poco::AbstractTimerCallback;
using Poco::Exception;
using Poco::Runnable;
using Poco::Thread;
using Poco::ThreadPool;
using Poco::Event;
using Poco::Logger;
using Poco::FastMutex;
using Poco::ScopedLock;
using Poco::SingletonHolder;
using Poco::Timer;
using namespace kdrive::connector;

CLASS_LOGGER("kdrive.connector.CallbackThread")

/**********************************
** Anonymous namespace
***********************************/

namespace
{

struct StopConstants
{
	enum
	{
		Initial = -1,
		Stop = 0,
		Run = 1,
		RequestStop = 2
	};
};

static FastMutex uniqueIdMutex;

int uniqueId()
{
	FastMutex::ScopedLock lock(uniqueIdMutex);

	static unsigned count = 0;
	++count;
	return count;
}

void notifyStart(CallbackThread::Signals& signals)
{
	try
	{
		signals.start();
	}
	catch (...)
	{
		poco_error(LOGGER(), "notifyStart failed with unhandled exception");
	}
}

void notifyStop(CallbackThread::Signals& signals)
{
	try
	{
		signals.stop();
	}
	catch (...)
	{
		poco_error(LOGGER(), "notifyStop failed with unhandled exception");
	}
}

void notifyException(CallbackThread::Signals& signals, std::exception& e)
{
	try
	{
		signals.exception(e);
	}
	catch (...)
	{
		poco_error(LOGGER(), "notifyException failed with unhandled exception");
	}
}

void setEvent(Event& e)
{
	try
	{
		e.set();
	}
	catch (...)
	{
		poco_error(LOGGER(), "setEvent failed with unhandled exception");
	}
}

void resetEvent(Event& e)
{
	try
	{
		e.reset();
	}
	catch (...)
	{
		poco_error(LOGGER(), "resetEvent failed with unhandled exception");
	}
}

} // end anonymous namespace

/**********************************
** CallbackThread
***********************************/

CallbackThread::CallbackThread(Callback callback, long sleep, const std::string& name)

	: sleep_(sleep),
	  id_(0),
	  callback_(callback),
	  status_(StopConstants::Initial),
	  yield_(true),
	  name_(name)
{
	BOOST_ASSERT(callback_ && "Invalid Callback");
}

CallbackThread::~CallbackThread()
{
	try
	{
		stop();
	}
	catch (...)
	{
	}
}

int CallbackThread::getId() const
{
	return id_;
}

void CallbackThread::setSleep(long sleep)
{
	sleep_ = sleep;
}

long CallbackThread::getSleep() const
{
	return sleep_;
}

void CallbackThread::setName(const std::string& name)
{
	name_ = name;
}

const std::string& CallbackThread::getName() const
{
	return name_;
}

void CallbackThread::stop()
{
	if (isRunning())
	{
		requestStopInternal();
		waitStopSync();
	}
	else if (isStopRequested())
	{
		// Wait until the thread is stopped
		// (e.g. stop request from the thread self or from ActiveFunction)
		waitStopSync();
	}
}

bool CallbackThread::tryWaitStop(long milliseconds)
{
	return stopEvent_.tryWait(milliseconds);
}

bool CallbackThread::isRunning() const
{
	return status_ == StopConstants::Run;
}

bool CallbackThread::isStopRequested() const
{
	return status_ == StopConstants::RequestStop;
}

bool CallbackThread::isStopped() const
{
	return status_ == StopConstants::Stop;
}

/*
	Our stop condition is either:
	sleep is 0, which means we have a fast loop,
	and we use the stop value to determine the stop event

	sleep is > 0 and we use the event to handle the stop case

	Special case: On the first loop we wait check only the current stop event value and do not wait the sleep time.
*/
bool CallbackThread::canLoop(bool firstLoop)
{
	const bool fastLoop = !sleep_;
	if (fastLoop)
	{
		return (status_ == StopConstants::Run) ? true : false;
	}
	else
	{
		const bool shouldStop = tryWaitStop(firstLoop ? 1 : sleep_);
		return shouldStop ? false : true;
	}
}

void CallbackThread::setYield(bool yield)
{
	yield_ = yield;
}

void CallbackThread::set()
{
	userEvent_.set();
}

void CallbackThread::wait()
{
	userEvent_.wait();
}

void CallbackThread::wait(long milliseconds)
{
	userEvent_.wait(milliseconds);
}

bool CallbackThread::tryWait(long milliseconds)
{
	return userEvent_.tryWait(milliseconds);
}

CallbackThread::Signals& CallbackThread::getSignals()
{
	return signals_;
}

/*!
	Our stop condition is either:
	sleep is 0, which means we have a fast loop,
	and we use the stop value to determine the stop event

	sleep is > 0 and we use the event to handle the stop case

	We use the two separate mechanisms for performance reasons,
	using the event is slow when we have a sleep of 0
	i.e. we still block a little, performance is much better when
	we use the atomic counter stop.

	Also, if sleep is 0 we add a thread yield to stop the case where
	a receive thread takes all the processing. You can disable this
	by setting yield to 0
*/
void CallbackThread::run()
{
	bool firstLoop = true;
	bool setStopEvent = false;

	id_ = uniqueId();
	status_ = StopConstants::Run;

	Logger& logger = LOGGER();
	poco_debug_f2(logger, "Callback thread running [id %d, %s]", getId(), getName());

	notifyStart(signals_);

	while (canLoop(firstLoop))
	{
		if (firstLoop)
		{
			setEvent(syncStartEvent_);
			firstLoop = false;
		}

		try
		{
			callback_();

			if (!sleep_ && yield_)
			{
				Thread::yield();
			}
		}
		catch (Exception& exception)
		{
			poco_error_f2(logger, "Callback thread terminated by unhandled Poco exception [id %d]: %s",
			              getId(), exception.displayText());

			notifyException(signals_, exception);
			setStopEvent = true;
		}
		catch (std::exception& exception)
		{
			const std::string what = exception.what();
			poco_error_f2(logger, "Callback thread terminated by unhandled std::exception [id %d]: %s",
			              getId(), what);

			notifyException(signals_, exception);
			setStopEvent = true;
		}
		catch (...)
		{
			poco_error_f1(logger, "Callback thread terminated by unhandled exception [id %d]", getId());

			std::exception e;
			setStopEvent = true;
		}

		if (setStopEvent)
		{
			requestStopInternal();
		}
	}

	notifyStop(signals_);
	status_ = StopConstants::Stop;
	setEvent(syncStopEvent_);

	poco_debug_f2(logger, "Callback thread stopped [id %d, name %s]", getId(), getName());
}

void CallbackThread::waitStartSync(long milliseconds)
{
	if (!syncStartEvent_.tryWait(milliseconds))
	{
		poco_warning_f2(LOGGER(), "Callback thread timeout start sync [id %d, name %s]", getId(), getName());
	}
}

void CallbackThread::waitStopSync(long milliseconds)
{
	if (!syncStopEvent_.tryWait(milliseconds))
	{
		poco_warning_f2(LOGGER(), "Callback thread timeout stop sync [id %d, name %s]", getId(), getName());
	}
}

void CallbackThread::requestStopInternal()
{
	status_ = StopConstants::RequestStop;
	setEvent(stopEvent_);
	poco_debug_f2(LOGGER(), "Callback thread stop requested [id %d, %s]", getId(), getName());
}

void CallbackThread::setToInitialState()
{
	status_ = StopConstants::Initial;
	resetEvent(syncStartEvent_);
	resetEvent(syncStartEvent_);
	resetEvent(syncStopEvent_);
}

/**********************************
** CallbackThreadManager
***********************************/

CallbackThreadManager::CallbackThreadManager(CallbackThread& callbackThread, bool scoped, bool useThreadPool)

	: callbackThread_(callbackThread),
	  scoped_(scoped),
	  useThreadPool_(useThreadPool)
{
	if (scoped_)
	{
		start();
	}
}

CallbackThreadManager::~CallbackThreadManager()
{
	try
	{
		stop();
	}
	catch (...)
	{
	}
}

void CallbackThreadManager::start()
{
	if (!callbackThread_.isRunning())
	{
		callbackThread_.setToInitialState();

		if (useThreadPool_)
		{
			ThreadPool& threadPool = ThreadPoolHolder::instance().threadPool_;
			threadPool.start(callbackThread_);
			callbackThread_.waitStartSync();
		}
		else
		{
			BOOST_ASSERT(!thread_ && "Thread must be null, this is a serious problem. Fix now.");

			thread_ = std::make_shared<Thread>();
			thread_->start(callbackThread_);
			callbackThread_.waitStartSync();
		}
	}
}

void CallbackThreadManager::start(long sleep)
{
	callbackThread_.setSleep(sleep);
	start();
}

void CallbackThreadManager::stop()
{
	callbackThread_.stop();

	if (useThreadPool_)
	{
		ThreadPool& threadPool = ThreadPoolHolder::instance().threadPool_;
		threadPool.collect();
	}
	else if (thread_)
	{
		if (!thread_->tryJoin(5000))
		{
			poco_error_f2(LOGGER(), "Unable to join thread [id %d, name %s]", callbackThread_.getId(), callbackThread_.getName());
		}
		thread_.reset();
	}

	callbackThread_.setToInitialState();
}

bool CallbackThreadManager::isRunning() const
{
	return callbackThread_.isRunning();
}

ThreadPool& CallbackThreadManager::getThreadPool()
{
	ThreadPool& threadPool = ThreadPoolHolder::instance().threadPool_;
	return threadPool;
}

CallbackThreadManager::ThreadPoolHolder::ThreadPoolHolder()

	: threadPool_(MinCapacity, MaxCapacity)
{
}

CallbackThreadManager::ThreadPoolHolder& CallbackThreadManager::ThreadPoolHolder::instance()
{
	static SingletonHolder<ThreadPoolHolder> holder;
	return *holder.get();
}

/**********************************
** ActiveFunction
***********************************/

ActiveFunction::ActiveFunction(Callback callback, long sleep, const std::string& name, bool useThreadPool)

	: callback_(callback),
	  callbackThread_(std::bind(&ActiveFunction::callbackAdaptor, this), sleep, name),
	  callbackThreadManager_(callbackThread_, false, useThreadPool)
{
}

ActiveFunction::~ActiveFunction()
{
}

CallbackThread& ActiveFunction::getCallbackThread()
{
	return callbackThread_;
}

const CallbackThread& ActiveFunction::getCallbackThread() const
{
	return callbackThread_;
}

void ActiveFunction::start()
{
	callbackThreadManager_.start();
}

void ActiveFunction::start(long sleep)
{
	callbackThreadManager_.start(sleep);
}

void ActiveFunction::stop()
{
	callbackThreadManager_.stop();
}

void ActiveFunction::stopFromWithinCallback()
{
	callbackThread_.requestStopInternal();
}

bool ActiveFunction::isRunning() const
{
	return callbackThreadManager_.isRunning();
}

void ActiveFunction::callbackAdaptor()
{
	if (callback_)
	{
		callback_(*this);
	}
}

/**********************************
** utility functions
***********************************/

Poco::Timer& kdrive::connector::startTimer(Timer& timer, const AbstractTimerCallback& method)
{
	timer.start(method, CallbackThreadManager::getThreadPool());
	return timer;
}


text:
/*
 * DS Desktop Notify
 * A small utility to show small notifications in your Desktop anytime!
 */
package ds.desktop.notify;

import java.awt.AlphaComposite;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.event.ActionListener;
import java.awt.geom.AffineTransform;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.ArrayList;

/**
 * Main class of DS Desktop Notify. Use it to create and show notifications on
 * the Desktop.
 * @version 0.9
 * @author  DragShot
 */
public class DesktopNotify {
    //Some constants
    public static final int DEFAULT = 0;
    public static final int INFORMATION = 1;
    public static final int WARNING = 2;
    public static final int ERROR = 3;
    public static final int HELP = 4;
    public static final int TIP = 5;
    public static final int INPUT_REQUEST = 6;
    public static final int SUCCESS = 7;
    public static final int FAIL = 8;

    public static final int LEFT_TO_RIGHT = 0;
    public static final int RIGHT_TO_LEFT = 1;

    private static NotifyTheme defTheme = NotifyTheme.Dark;

    /**
     * Sets the theme to use by default when creating notifications.
     * @param theme The theme to use.
     */
    public static void setDefaultTheme(NotifyTheme theme) {
        DesktopNotify.defTheme = theme;
    }

    /**
     * Gets the theme currently in use when creating notifications.
     * @return The theme in use.
     */
    public static NotifyTheme getDefaultTheme() {
        return DesktopNotify.defTheme;
    }

    protected static int defTextOrientation = LEFT_TO_RIGHT;

    /**
     * Gets the current default text orientation.
     * @return The text orientation.
     * @see #RIGHT_TO_LEFT
     * @see #LEFT_TO_RIGHT
     */
    public static int getDefaultTextOrientation() {
        return defTextOrientation;
    }

    /**
     * Sets the default text orientation to use for new notifications. Useful
     * for displaying languages that aren't read left-to-right.
     * @param defTextOrientation The new text orientation.
     * @see #RIGHT_TO_LEFT
     * @see #LEFT_TO_RIGHT
     */
    public static void setDefaultTextOrientation(int defTextOrientation) {
        DesktopNotify.defTextOrientation = defTextOrientation;
    }

    /**
     * Creates and shows a new notification. If there isn't an instance of the
     * DesktopNotifyDriver thread running, it will be created and started to
     * show your notification window.
     *
     * This notification does not bring any icon. Notifications created from
     * this method will stay on screen until the user clicks it. No actions can
     * be specified from this method.
     *
     * @param title         The title, if any.
     * @param message       The message, if any.
     */
    public static void showDesktopMessage(String title, String message) {
        showDesktopMessage(title, message, DEFAULT, null, null, 0);
    }

    /**
     * Creates and shows a new notification. If there isn't an instance of the
     * DesktopNotifyDriver thread running, it will be created and started to
     * show your notification window.
     *
     * A default icon will be used, depending of the type, unless it is DEFAULT.
     * A DEFAULT type notification does not bring an icon by default, no matter
     * how ironic this sounds. Notifications created from this method will stay
     * on screen until the user clicks it. No actions can be specified from this
     * method.
     *
     * @param title         The title, if any.
     * @param message       The message, if any.
     * @param type          An int that denotes a valid message type. Invalid
     *                      values will be treated as DEFAULT.
     */
    public static void showDesktopMessage(String title, String message,
            int type) {
        showDesktopMessage(title, message, type, null, null, 0);
    }

    /**
     * Creates and shows a new notification. If there isn't an instance of the
     * DesktopNotifyDriver thread running, it will be created and started to
     * show your notification window.
     *
     * A default icon will be used, depending of the type, unless it is DEFAULT.
     * A DEFAULT type notification does not bring an icon by default, no matter
     * how ironic this sounds. Notifications created from this method will stay
     * on screen until the user clicks it, firing the action specified (if any).
     *
     * @param title         The title, if any.
     * @param message       The message, if any.
     * @param type          An int that denotes a valid message type. Invalid
     *                      values will be treated as DEFAULT.
     * @param action        An ActionListener with the action to execute when
     *                      the user clicks the notification.
     */
    public static void showDesktopMessage(String title, String message,
            int type, ActionListener action) {
        showDesktopMessage(title, message, type, null, action, 0);
    }

    /**
     * Creates and shows a new notification. If there isn't an instance of the
     * DesktopNotifyDriver thread running, it will be created and started to
     * show your notification window.
     *
     * Notifications created from this method will stay on screen until the user
     * clicks it, firing the action specified (if any).
     *
     * @param title         The title, if any.
     * @param message       The message, if any.
     * @param type          An int that denotes a valid message type. Invalid
     *                      values will be treated as DEFAULT.
     * @param icon          A custom Image to use instead of the default icon
     *                      assigned by type.
     * @param action        An ActionListener with the action to execute when
     *                      the user clicks the notification.
     */
    public static void showDesktopMessage(String title, String message,
            int type, Image icon, ActionListener action) {
        showDesktopMessage(title, message, type, icon, action, 0);
    }

    /**
     * Creates and shows a new notification. If there isn't an instance of the
     * DesktopNotifyDriver thread running, it will be created and started to
     * show your notification window.
     *
     * A default icon will be used, depending of the type, unless it is DEFAULT.
     * A DEFAULT type notification does not bring an icon by default, no matter
     * how ironic this sounds. No actions can be specified from this method.
     *
     * @param title         The title, if any.
     * @param message       The message, if any.
     * @param type          An int that denotes a valid message type. Invalid
     *                      values will be treated as DEFAULT.
     * @param maxTimeMillis The maximum time in milliseconds that this
     *                      notification will stay on the screen. If set to 0,
     *                      the user will have to close it manually by clicking
     *                      it.
     */
    public static void showDesktopMessage(String title, String message,
            int type, long maxTimeMillis) {
        showDesktopMessage(title, message, type, null, null, maxTimeMillis);
    }

    /**
     * Creates and shows a new notification. If there isn't an instance of the
     * DesktopNotifyDriver thread running, it will be created and started to
     * show your notification window.
     *
     * A default icon will be used, depending of the type, unless it is DEFAULT.
     * A DEFAULT type notification does not bring an icon by default, no matter
     * how ironic this sounds.
     *
     * @param title         The title, if any.
     * @param message       The message, if any.
     * @param type          An int that denotes a valid message type. Invalid
     *                      values will be treated as DEFAULT.
     * @param maxTimeMillis The maximum time in milliseconds that this
     *                      notification will stay on the screen. If set to 0,
     *                      the user will have to close it manually by clicking
     *                      it. Such value is recommended if you want to add an
     *                      action for it.
     * @param action        An ActionListener with the action to execute when
     *                      the user clicks the notification.
     */
    public static void showDesktopMessage(String title, String message,
            int type, long maxTimeMillis, ActionListener action) {
        showDesktopMessage(title, message, type, null, action, maxTimeMillis);
    }

    /**
     * Creates and shows a new notification. If there isn't an instance of the
     * DesktopNotifyDriver thread running, it will be created and started to
     * show your notification window.
     *
     * Notifications created from this method will stay on screen until the user
     * clicks it. No actions can be specified from this method.
     *
     * @param title         The title, if any.
     * @param message       The message, if any.
     * @param type          An int that denotes a valid message type. Invalid
     *                      values will be treated as DEFAULT.
     * @param icon          A custom Image to use instead of the default icon
     *                      assigned by type.
     */
    public static void showDesktopMessage(String title, String message,
            int type, Image icon) {
        showDesktopMessage(title, message, type, icon, null, 0);
    }

    /**
     * Creates and shows a new notification. If there isn't an instance of the
     * DesktopNotifyDriver thread running, it will be created and started to
     * show your notification window.
     *
     * @param title         The title, if any.
     * @param message       The message, if any.
     * @param type          An int that denotes a valid message type. Invalid
     *                      values will be treated as DEFAULT.
     * @param icon          A custom Image to use instead of the default icon
     *                      assigned by type.
     * @param maxTimeMillis The maximum time in milliseconds that this
     *                      notification will stay on the screen. If set to 0,
     *                      the user will have to close it manually by clicking
     *                      it. Such value recommended if you want to add an
     *                      action for it.
     * @param action        An ActionListener with the action to execute if
     *                      the user clicks the notification.
     */
    public static void showDesktopMessage(String title, String message,
            int type, Image icon, ActionListener action, long maxTimeMillis) {
        DesktopNotify pane=new DesktopNotify(title, message, type, defTextOrientation, icon);
        pane.setTimeout(maxTimeMillis);
        pane.setAction(action);
        pane.show();
    }

    String title;
    String message;
    Image icon;
    int type;
    int orientation;

    /**
     * A NotifyTheme object with the color and Font parameters to
     * be used when this notification is being painted.
     */
    NotifyTheme theme;

    /**
     * A String array with the lines of the title.
     * It is refreshed automatically when the title is set.
     */
    String[] tlts = new String[0];
    /**
     * A String array with the lines of the message.
     * It is refreshed automatically when the message is set.
     */
    String[] msgs = new String[0];

    int w = 0;
    int h = 0;
    boolean visible = false;
    boolean markedForHide = false;

    int highl = 0;

    long popupStart = 0L;
    long timeOut = 8000L;

    /**
     * An action to perform when the notification is clicked.
     */
    ActionListener action;

    /**
     * A protected constructor for a DesktopNotify object, called internally.
     * You can use any of the showDesktopMessage() static methods
     * or a {@link NotificationBuilder} in order to create and display a
     * notification instead.
     * @param title       The notification title. Can be {@code null} when the
     *                    notification isn't meant to have one.
     * @param message     The notification message. Can be {@code null} when
     *                    the notification isn't meant to have one.
     * @param orientation The text orientation, either {@link #LEFT_TO_RIGHT} or
     *                    {@link #RIGHT_TO_LEFT}.
     * @param type        The notification type. Check the type contans in the
     *                    class for the ones you can use.
     * @param icon        The icon to display. Can be {@code null} when the
     *                    notification isn't meant to have one.
     */
    protected DesktopNotify(String title, String message, int type,
            int orientation, Image icon){
        this.title = (title==null? "":title);
        this.message = (message==null? "":message);
        this.type = type;
        this.orientation = orientation;
        this.icon = icon;
        this.theme = DesktopNotify.defTheme;
    }

    /**
     * @return The NotifyTheme in use for this notification.
     */
    public NotifyTheme getTheme() {
        return theme;
    }

    /**
     * Allows to set a NotifyTheme for this notification. One of
     * these defines stuff as the colors for text and background, the fonts and
     * even images for the default icons.
     * @param theme The NotifyTheme to use for this notification.
     */
    public void setTheme(NotifyTheme theme) {
        if (theme != null) this.theme = theme;
    }

    /**
     * @return the ActionListener binded to this notification.
     */
    public ActionListener getAction() {
        return action;
    }

    /**
     * Allows to bind an action to this notification. It will be executed when
     * the notification gets clicked. Notifications with an action set will wait
     * for the user to click them.
     * @param action he ActionListener to bind to this notification.
     */
    public void setAction(ActionListener action) {
        this.action = action;
    }

    /**
     * Allows to set a timeout for this notification, in milliseconds.
     * After the time is 'out', and if there isn't an action set, the
     * notification will just fade away.
     * @param millis the timeout.
     */
    public void setTimeout(long millis){
        timeOut = millis < 0 ? 0 : millis;
    }

    protected long expTime(){
        return timeOut == 0 ? Long.MAX_VALUE : popupStart + timeOut;
    }

    /**
     * Polls the Driver in order to show this notification, so you don't have to
     * do it yourself.
     */
    public void show(){
        markedForHide = false;
        DesktopNotifyDriver.postPane(this);
    }

    /**
     * Hides this notification immediately if it is already being displayed.
     * The action itself is handled by the Driver, this method only marks this
     * notification for hiding.
     */
    public void hide() {
        markedForHide = true;
    }

    protected void setWidth(int w){
        this.w = w;
    }

    /**
     * @return true if this notification is currently being shown.
     */
    public boolean isVisible() {
        return visible;
    }

    /**
     * Used by he driver to mark this notification as visible or not.
     * @param visible {@code true} if the notification is currently visible.
     */
    protected void setVisible(boolean visible) {
        this.visible = visible;
    }

    /**
     * The painting routine for the notification goes here.
     * @param x     Where to start painting (X)
     * @param y     Where to start painting (Y)
     * @param hover A boolean that is true if the user is hovering
     *              this notification with the mouse pointer.
     * @param rd    The Graphics2D object to use for painting.
     * @param l     The current time.
     */
    public void render(int x, int y, boolean hover, Graphics2D rd, long l) {
        long i = l - popupStart;
        if (i > 500) i = expTime()-l;
        if (i < 0) i = 0;
        if (i > 500) i = -1;
        rd.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        AffineTransform trans=rd.getTransform();
        rd.translate(x, y);
        if (i != -1) {
            double d = i/500.0;
            rd.translate(w/2-((w/2)*d), h/2-((h/2)*d));
            rd.scale(d, d);
            rd.setComposite(AlphaComposite
                    .getInstance(AlphaComposite.SRC_OVER,(float)d));
        }
        rd.setPaint(new GradientPaint(0, (title.isEmpty()? 0:25),
                /*hover? new Color(50,57,65):*/theme.bgGrad[0],
                0, h, theme.bgGrad[highl+1]/*new Color(theme.bgGrad[0].getRed()+(int)((theme.bgGrad[1].getRed()-theme.bgGrad[0].getRed())*highl/20.0F),
                                theme.bgGrad[0].getGreen()+(int)((theme.bgGrad[1].getGreen()-theme.bgGrad[0].getGreen())*highl/20.0F),
                                theme.bgGrad[0].getBlue()+(int)((theme.bgGrad[1].getBlue()-theme.bgGrad[0].getBlue())*highl/20.0F),
                120+(int)(135*highl/20.0F))*//*hover? new Color(0x3B4B5B):new Color(50,50,50,120)*/, false));
        if (hover && highl<20) highl++;
        if (!hover && highl>0) highl--;
        rd.fillRect(0, 0, w, h);
        rd.setPaint(null);
        rd.setColor(theme.borderColor);
        rd.drawRect(0, 0, w-1, h-1);
        if (i==-1) {
            int titleH = getLineHeight(theme.titleFont);
            int textH = getLineHeight(theme.contentFont);
            if (!title.isEmpty()) {
                rd.setColor(theme.titleColor);
                rd.setFont(theme.titleFont);
                int tX = 5 + ((icon==null && type==0)? 0:38);
                for (int j = 0; j < tlts.length; j++) {
                    if (orientation == RIGHT_TO_LEFT) {
                        FontMetrics ftm = DesktopNotifyDriver.getFontMetrics(theme.titleFont);
                        tX = w - 4 - ((icon==null && type==0)? 0:38) - ftm.stringWidth(tlts[j]);
                    }
                    rd.drawString(tlts[j], tX, 20+(titleH*j));
                }
            }
            if (!message.isEmpty()) {
                rd.setColor(theme.contentColor);
                rd.setFont(theme.contentFont);
                int tX = 6 + ((icon==null && type==0)? 0:38);
                for (int j = 0; j < msgs.length; j++) {
                    if (orientation == RIGHT_TO_LEFT) {
                        FontMetrics ftm = DesktopNotifyDriver.getFontMetrics(theme.contentFont);
                        tX = w - 5 - ((icon==null && type==0)? 0:38) - ftm.stringWidth(msgs[j]);
                    }
                    rd.drawString(msgs[j], tX, 20+(titleH*tlts.length)+(textH*j));
                }
            }
        }
//        if(expTime()==Long.MAX_VALUE){
//            rd.setFont(theme.titleFont);
//            rd.setColor(new Color(120,120,120));
//            rd.drawString("X", w-16, 18);
//        }
        Image icon = this.icon == null ?
                (type == 0 ? null : theme.iconSet[type-1]) : this.icon;
        if (icon != null) {
            rd.drawImage(icon, orientation == RIGHT_TO_LEFT ? (w - 7 - 32) : 6, (h/2)-15, 32, 32, null);
        }
        rd.setTransform(trans);
        rd.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
    }

    private int getLineHeight(Font font) {
        FontMetrics ftm = DesktopNotifyDriver.getFontMetrics(font);
        return ftm.getHeight() - ftm.getLeading();
    }

    /**
     * Splits the words of the text across lines that fit inside the
     * notification. It is called by the {@link DesktopNotifyDriver}.
     */
    protected void sortMessage() {
        if (!title.isEmpty()) tlts = splitLines(title, theme.titleFont);
        if (!message.isEmpty()) msgs = splitLines(message, theme.contentFont);
        h = 15 + (getLineHeight(theme.titleFont)*tlts.length)
                + (getLineHeight(theme.contentFont)*msgs.length);
    }

    private String[] splitLines(String in, Font font) {
        String[] out;
        ArrayList<String> list=new ArrayList();
        String[] strs=in.split("\n");
        StringBuilder builder = new StringBuilder();
        FontMetrics ftm = DesktopNotifyDriver.getFontMetrics(font);
        for(String str:strs){
            String[] words=str.split(" ");
            for(String word:words){
                //System.out.println(str);
                //System.out.println(ftm.stringWidth(builder.toString())+"+"+ftm.stringWidth(str)+"<"+(w-10));
                if (ftm.stringWidth(builder.toString()) + ftm.stringWidth(word)
                        < (w-12-((icon==null && type==0)? 0:38))){
                    builder.append(word).append(" ");
                } else {
                    list.add(builder.toString());
                    builder=new StringBuilder().append(word).append(" ");
                }
            }
            list.add(builder.toString());
            builder.setLength(0);
        }
        out = new String[list.size()];
        out = list.toArray(out);
        return out;
    }

    // Integrated Logging
    public static final int DEBUG = 0;
    public static final int NONE = 10;

    /**
     * Allows to specify the level allowed for logging messages. Attempts to log
     * messages with a priority level below what's been set will be ignored.
     * @param level The logging priority level to allow as minimum.
     */
    public static void setLogLevel(int level) {
        logger.setLoggingLevel(level);
    }

    /**
     * Returns the level allowed for logging messages. Attempts to log
     * messages with a priority level below what's been set will be ignored.
     * @return The logging priority level curently allowed as minimum.
     */
    public static int getLogLevel() {
        return logger.getLoggingLevel();
    }

    public static void setLogOutput(OutputStream outStream) {
         logger.setOutput(outStream);
    }

    /**
     * Logs a debug message. Parameters can't be {@code null}.
     * @param tag     The tag associated to this message.
     * @param message The message to include.
     */
    public static void logDebug(String tag, String message) {
        logger.post(DEBUG, tag, message, null);
    }

    /**
     * Logs an information message. Parameters can't be {@code null}.
     * @param tag     The tag associated to this message.
     * @param message The message to include.
     */
    public static void logInfo(String tag, String message) {
        logger.post(INFORMATION, tag, message, null);
    }

    /**
     * Logs a warning message. Parameters can't be {@code null}.
     * @param tag     The tag associated to this message.
     * @param message The message to include.
     */
    public static void logWarning(String tag, String message) {
        logger.post(WARNING, tag, message, null);
    }

    /**
     * Logs an error message. Parameters other than the caught throwable can't
     * be {@code null}.
     * @param tag     The tag associated to this message.
     * @param message The message to include.
     * @param tr      A Throable object (an Exception, for example), whose
     *                message and stack trace should be logged too.
     */
    public static void logError(String tag, String message, Throwable tr) {
        logger.post(ERROR, tag, message, tr);
    }

    private static final Logger logger = new Logger();

    /**
     * Utilitary subclass used for logging.
     */
    private static class Logger {
        private OutputStream outStream;
        private PrintWriter outWritter;

        private int level;

        Logger() {
            this.level = INFORMATION;
            this.setOutput(System.out);
        }

        /**
         * Lets you specify an OutputStream for use in this Logger.
         * @param outStream The OutputStream you wish to log messages into.
         */
        public synchronized void setOutput(OutputStream outStream) {
            this.outStream = outStream;
            this.outWritter = new PrintWriter(outStream);
        }

        /**
         * @return true if a proper output destiny has been set, like
         *         an output file or stream.
         */
        public boolean isReady() {
            return outWritter != null;
        }

        private String levelToString(int level) {
            String str = "OTHER";
            switch(level) {
                case DEBUG: str = "DEBUG"; break;
                case INFORMATION: str = "INFO"; break;
                case WARNING: str = "WARNING"; break;
                case ERROR: str = "ERROR"; break;
            }
            return str;
        }

        public synchronized void setLoggingLevel(int level) {
            this.level = level;
        }

        public synchronized int getLoggingLevel() {
            return this.level;
        }

        /**
         * Checks for you if a given level is enabled in this logger.
         * @param level The level to check.
         * @return true if the given level is found to be enabled,
         *         false otherwise.
         */
        public boolean isEnabled(int level) {
            return this.level <= level;
        }

        /**
         * Full form of the method. This method lets you post a message into this
         * logger, so it can be logged or not depending of the assigned settings.
         * You can specify a title (tag), message, flag and a Throwable object (like
         * an Exception or Error) to include in the log.
         * @param level   The level to mark this message with.
         * @param tag     The tag associated to this message. It cannot be null.
         * @param message The message to include. It cannot be null.
         * @param tr      A Throwable whose message and stack trace should be
         *                printed.
         */
        public synchronized void post(int level, String tag, String message, Throwable tr) {
            if (tag == null) throw new NullPointerException("Tag please");
            if (message == null) throw new NullPointerException("Message please");
            if (isReady() && isEnabled(level)) {
                StringBuilder builder = new StringBuilder();
                builder.append(levelToString(level)).append(":").append(tag)
                       .append(" at [").append(new java.util.Date().toString())
                       .append("] -> ").append(message.trim());
                if (outStream instanceof PrintStream) {
                    ((PrintStream)outStream).println(builder.toString());
                } else {
                    outWritter.println(builder.toString());
                    outWritter.flush();
                }
                if (tr != null) {
                    if (outStream instanceof PrintStream) {
                        ((PrintStream)outStream).println("Caused by:");
                        tr.printStackTrace((PrintStream)outStream);
                    } else {
                        outWritter.println("Caused by:");
                        tr.printStackTrace(outWritter);
                        outWritter.flush();
                    }
                }
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import isProjectExportInProgress from './isProjectExportInProgress';

export default function isRepoExportInProgress(state) {
  return isProjectExportInProgress(state, 'repo');
}


text:
<?php

namespace Craft;

/**
 * The class name is the UTC timestamp in the format of
 * mYYMMDD_HHMMSS_pluginHandle_migrationName
 */
class m160704_000000_retour_addReferrerStats extends BaseMigration
{
    /**
     * Any migration code in here is wrapped inside of a transaction.
     *
     * @return bool
     */
    public function safeUp()
    {
        // specify columns and AttributeType
        $newColumns = array(
            'referrerUrl' => ColumnType::Varchar,
        );

        $this->_addColumnsAfter("retour_stats", $newColumns, "redirectSrcUrl");

        // return true and let craft know its done
        return true;
    }

    private function _addColumnsAfter($tableName, $newColumns, $afterColumnHandle)
    {

        // this is a foreach loop, enough said
        foreach ($newColumns as $columnName => $columnType) {
            // check if the column does NOT exist
            if (!craft()->db->columnExists($tableName, $columnName)) {
                $this->addColumnAfter(
                    $tableName,
                    $columnName,
                    array(
                        'column' => $columnType,
                        'null'   => false,
                    ),
                    $afterColumnHandle
                );

                // log that we created the new column
                RetourPlugin::log("Created the `$columnName` in the `$tableName` table.", LogLevel::Info, true);
            } // if the column already exists in the table
            else {
                // tell craft that we couldn't create the column as it alredy exists.
                RetourPlugin::log("Column `$columnName` already exists in the `$tableName` table.", LogLevel::Info, true);
            }
        }
    }
}


text:
'use strict';

const RSVP = require('rsvp');
const Task = require('../models/task');
const path = require('path');
const pkg = require('../../package.json');
const fs = require('fs');
const execa = require('../utilities/execa');

const Promise = RSVP.Promise;

class GitInitTask extends Task {
  run(_commandOptions) {
    let commandOptions = _commandOptions || {};
    const template = require('lodash.template');
    const chalk = require('chalk');
    let ui = this.ui;

    if (commandOptions.skipGit) {
      return Promise.resolve();
    }

    let gitVersionWorked = false;
    return this._gitVersion().then(() => {
      gitVersionWorked = true;

      return this._gitInit()
        .then(() => this._gitAdd())
        .then(() => {
          let commitTemplate = fs.readFileSync(path.join(__dirname, '../utilities/COMMIT_MESSAGE.txt'));
          let commitMessage = template(commitTemplate)(pkg);
          return this._gitCommit(commitMessage);
        })
        .then(() => ui.writeLine(chalk.green('Successfully initialized git.')));
    })
      .catch(error => {
        if (gitVersionWorked) {
          throw error;
        }
        // otherwise git version failed, so we skip git stuff.
      });
  }

  _gitVersion() {
    return execa('git', ['--version']);
  }

  _gitInit() {
    return execa('git', ['init']);
  }

  _gitAdd() {
    return execa('git', ['add', '.']);
  }

  _gitCommit(commitMessage) {
    return execa('git', ['commit', '-m', commitMessage], { env: this.buildGitEnvironment() });
  }

  buildGitEnvironment() {
    // Make sure we merge in the current environment so that git has access to
    // important environment variables like $HOME.
    return Object.assign({}, process.env, {
      GIT_AUTHOR_NAME: 'Tomster',
      GIT_AUTHOR_EMAIL: 'tomster@emberjs.com',
      GIT_COMMITTER_NAME: 'Tomster',
      GIT_COMMITTER_EMAIL: 'tomster@emberjs.com',
    });
  }
}

module.exports = GitInitTask;


text:
/**
 * @file node 测试
 * @author mengke01(kekee000@gmail.com)
 */

require('./adjustttf.spec');
require('./font.spec');
require('./otf2ttf.spec');
require('./readotf.spec');
require('./readttf.spec');
require('./svg2ttf.spec');
require('./writettf.spec');


text:
package mnm.mods.achget;

import java.io.File;
import java.util.Map;

import mnm.mods.achget.net.AchSyncPacket;
import mnm.mods.achget.net.AchievementChannel;
import mnm.mods.achget.proxy.CommonProxy;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.stats.StatBase;
import net.minecraft.stats.StatList;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.living.LivingEvent.LivingUpdateEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.Mod.Instance;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.event.FMLServerStartingEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.PlayerEvent.PlayerLoggedInEvent;

import org.apache.logging.log4j.Logger;

import com.google.common.collect.Maps;

@Mod(modid = AchievementGet.MODID, name = "Achievement Get", version = AchievementGet.VERSION, acceptableRemoteVersions = "*")
public class AchievementGet {

    public static final String MODID = "achget";
    public static final String VERSION = "1.0";

    public static Logger logger;
    @Instance
    public static AchievementGet instance;
    @SidedProxy(clientSide = "mnm.mods.achget.proxy.ClientProxy", serverSide = "mnm.mods.achget.proxy.CommonProxy")
    public static CommonProxy proxy;
    public AchievementChannel network = new AchievementChannel();

    /**
     * Mirror to {@link StatList#oneShotStats}.
     */
    public Map<String, StatBase> oneShotStats;
    public String jsonAch;
    public Map<String, StatAchievement> achievements = Maps.newHashMap();
    private File config;

    @EventHandler
    public void init(FMLPreInitializationEvent event) {
        logger = event.getModLog();
        this.config = new File(event.getModConfigurationDirectory(), "achievements.json");
        this.oneShotStats = StatListEx.getOneShotStats();
        MinecraftForge.EVENT_BUS.register(this);
        network.init();
    }

    @EventHandler
    public void serverStart(FMLServerStartingEvent start) {
        proxy.init(config);
    }

    @SubscribeEvent
    public void join(PlayerLoggedInEvent join) {
        network.sendTo((EntityPlayerMP) join.player, new AchSyncPacket(jsonAch));
    }

    @SubscribeEvent
    public void onLiving(LivingUpdateEvent event) {
        // disconnect is an event (or something)
        if (event.entity == null)
            return;
        if (event.entity instanceof EntityPlayerMP) {
            checkStats((EntityPlayerMP) event.entity);
        }
    }

    public void registerAchivements(String json) {
        proxy.register(json);
    }

    private void checkStats(EntityPlayerMP player) {
        for (StatAchievement sa : achievements.values()) {
            StatHandler handler = new StatHandler(sa);
            if (handler.shouldAward(player)) {
                handler.giveAchievement(player);
            }
        }
    }

    /**
     * Class to access protected field.
     */
    private static class StatListEx extends StatList {
        @SuppressWarnings("unchecked")
        private static Map<String, StatBase> getOneShotStats() {
            return StatList.oneShotStats;
        }
    }

}


text:
require.config({
    baseUrl: '/static/',
    shim : {
        "bootstrap" : { "deps" :['jquery'] },
        // "jquery-cookie"  : ["jquery"]
    },
    paths: {
        select2: 'libs/select2/js/select2.full',
        jquery: 'libs/jquery',
        underscore: 'libs/underscore',
        backbone: 'libs/backbone',
        domReady: 'libs/domReady',
        bootstrap: 'libs/bootstrap/js/bootstrap'
    }
});

require(['model/inspiration',
         'view/inspiration-list-view',
         'jquery', 'underscore', 'backbone',
         'bootstrap', 'select2', 'domReady!'],
        function(
            Inspiration,
            InspirationListView,
            $, _, Backbone) {

    // console.log($);
    // console.log(_);
    // console.log(Backbone);

    var Page = {};
    Page.currentPage = null;
    Page.labelFilter = new InspirationListView({el: "#label-filter-view.sentence-container"});
    Page.search = new InspirationListView({el: "#search-view.sentence-container"});

    Page.switchPage = function(page){
        if(Page.currentPage === page){
            return ;
        }

        if(Page.currentPage){
            Page.currentPage.hide();
        }

        Page.currentPage = page;
        page.show();

    }

    var router = new (Backbone.Router.extend({
        routes: {
            "": "labelFilter",
            "labelFilter=:labelId": "labelFilter", // #search/kiwis/p7
            "search=:keyword": "search"
        },

        labelFilter: function(labelId){
            var labelId = labelId || "all"

            function _renderLabelFilter(data){
                var inspirationData = _.sortBy(_.pluck(data.objects, "inspiration"), function(obj){
                    return -obj.id
                });
                Page.labelFilter.clear();
                Page.labelFilter.next = data.meta.next
                Page.labelFilter.setCollection(inspirationData);
                Page.labelFilter.render();
                Page.switchPage(Page.labelFilter);
            }

            if(labelId === "0"){
                $.get("/api/nolabel-inspiration/")
                 .done(function(data){
                    var inspirationData = data.objects;
                    Page.labelFilter.clear();
                    Page.labelFilter.setCollection(inspirationData);
                    Page.labelFilter.render();
                    Page.switchPage(Page.labelFilter);
                 })

                 return ;
            }

            if(labelId === "all"){
                $.get("/api/labelinspirationrelationship/")
                 .done(function(data){
                    _renderLabelFilter(data);
                 });
                 return ;
            }

            $.get("/api/labelinspirationrelationship/?label="+labelId)
             .done(function(data){
                _renderLabelFilter(data);
             });
        },

        search: function(keyword){
            $.get("/api/inspiration/search?q="+keyword)
             .done(function(data){
                var inspirationData = data.objects;
                Page.search.clear();
                Page.search.next = data.meta.next
                Page.search.setCollection(inspirationData);
                Page.search.render();
                Page.switchPage(Page.search);

             });
        },

    }))

    $(document).on("click", "#search-btn", function(e){
        var keyword = $("#keyword-input").val();
        router.navigate("search="+keyword, {trigger: true});
    })

    $(document).on("submit", "#search-form", function(e){
        e.preventDefault();
        var keyword = $("#keyword-input").val();
        router.navigate("search="+keyword, {trigger: true});
    })

    Backbone.on("next-page", function(){
        var curTime = new Date();
        var $loading = $(".loading-container").show();

        if(! Page.currentPage.next){
            $loading.hide()
            return ;
        }

        function _render(data){
            Page.currentPage.next = data.meta.next;
            Page.currentPage.setCollection(_.pluck(data.objects, "inspiration"));
            Page.currentPage.render();
        }

        $.get(Page.currentPage.next)
         .done(function(data){
            var delta = (new Date()) - curTime;
            if( delta < 550){
                _.delay(function(){
                    _render(data);
                }, 550 - delta);
            }else{
                _render(data);
            }

         })

    })

    var throttle = _.throttle(function() {
        if ($(window).scrollTop() + $(window).height() >= $('body').height() - 260) {
            Backbone.trigger('next-page');
        }
    }, 200);
    $(window).off("scroll")
    $(window).scroll(throttle);

    Backbone.history.start()

});


text:
const common = require("./webpack.config");

module.exports = Object.assign(common, {
    mode: 'production',
});


text:
package scdn

//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.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

// Task is a nested struct in scdn response
type Task struct {
	Status       string `json:"Status" xml:"Status"`
	CreationTime string `json:"CreationTime" xml:"CreationTime"`
	ObjectType   string `json:"ObjectType" xml:"ObjectType"`
	Process      string `json:"Process" xml:"Process"`
	Description  string `json:"Description" xml:"Description"`
	ObjectPath   string `json:"ObjectPath" xml:"ObjectPath"`
	TaskId       string `json:"TaskId" xml:"TaskId"`
}


text:
set(CTEST_SOURCE_DIRECTORY "$ENV{APPVEYOR_BUILD_FOLDER}")
set(CTEST_BINARY_DIRECTORY "C:/projects/tomviz-build")
# We need to set this otherwise we yet 255 as our return code!
set(CTEST_COMMAND ctest)
include(${CTEST_SOURCE_DIRECTORY}/CTestConfig.cmake)
set(CTEST_SITE "AppVeyor")
set(_prefix "master")
if (DEFINED ENV{APPVEYOR_PULL_REQUEST_NUMBER})
  set(_prefix "pull/$ENV{APPVEYOR_PULL_REQUEST_NUMBER}")
endif()
set(CTEST_BUILD_NAME "${_prefix}-#$ENV{APPVEYOR_BUILD_NUMBER}")
set(CTEST_CMAKE_GENERATOR "Visual Studio 14 2015 Win64")
set(CTEST_CONFIGURATION_TYPE "Release")
set(cfg_options
  -DQt5_DIR:PATH=C:/Qt/5.10.0/msvc2015_64/lib/cmake/Qt5
  -DParaView_DIR:PATH=C:/projects/paraview-build/
  -DITK_DIR:PATH=C:/projects/itk/lib/cmake/ITK-4.9
  -DGTEST_LIBRARY:PATH=C:/projects/googletest-install/lib/gtest.lib
  -DGTEST_MAIN_LIBRARY:PATH=C:/projects/googletest-install/lib/gtest_main.lib
  -DGTEST_INCLUDE_DIR:PATH=C:/projects/googletest-install/include
  -DPYTHON_EXECUTABLE:PATH=C:/projects/python/bin/python.exe
  -DENABLE_TESTING:BOOL=ON
  -DSKIP_PARAVIEW_ITK_PYTHON_CHECKS:BOOL=ON
  -DCMAKE_BUILD_TYPE:STRING="Release")

ctest_start("Continuous")
ctest_configure(OPTIONS "${cfg_options}")
ctest_build()
ctest_test(EXCLUDE "Docker" RETURN_VALUE rv)
ctest_submit()

if(NOT rv EQUAL 0)
  message(FATAL_ERROR "Test failures occurred.")
endif()


text:
<!DOCTYPE html>

<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<meta http-equiv="X-UA-Compatible" content="chrome=1"/>
<link rel="icon" type="image/png" href="images/logo.png"/>
<link rel="stylesheet" href="svg-editor.css" type="text/css"/>

<title>Browser does not support SVG | SVG-edit</title>

Sorry, but your browser does not support SVG. Below is a list of alternate browsers and versions that support SVG and SVG-edit (from caniuse.com).

Try the latest version of Firefox, Google Chrome, Safari, Opera or Internet Explorer.

If you are unable to install one of these and must use an old version of Internet Explorer, you can install the Google Chrome Frame plugin.


text:
<ivysettings>
	<caches defaultCacheDir="/tmp/.ivy2/cache/"/>
	<settings defaultResolver="default" />
	<resolvers>
		<chain name="public">
			<ibiblio name="ibiblio" m2compatible="true" />

			<url name="com.springsource.repository.bundles.milestone" m2compatible="true">
				<artifact pattern="http://maven.springframework.org/milestone/[organisation]/[module]/[revision]/[artifact]-[revision].[ext]" />
			</url>
			<url name="jboss" m2compatible="true">
				<artifact pattern="http://repository.jboss.org/nexus/content/groups/public-jboss/[organisation]/[module]/[revision]/[artifact]-[revision].[ext]" />
			</url>
		</chain>
	</resolvers>

	<include url="${ivy.default.settings.dir}/ivysettings-shared.xml" />
	<include url="${ivy.default.settings.dir}/ivysettings-local.xml" />
	<include url="${ivy.default.settings.dir}/ivysettings-main-chain.xml" />
	<include url="${ivy.default.settings.dir}/ivysettings-default-chain.xml" />
</ivysettings>


text:
package cloudwatch

import (
	"fmt"
	"sync"
	"time"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/cloudwatch"
	"github.com/aws/aws-sdk-go/service/cloudwatch/cloudwatchiface"

	"github.com/go-kit/kit/log"
	"github.com/go-kit/kit/metrics"
	"github.com/go-kit/kit/metrics/generic"
)

const (
	maxConcurrentRequests = 20
)

// CloudWatch receives metrics observations and forwards them to CloudWatch.
// Create a CloudWatch object, use it to create metrics, and pass those metrics as
// dependencies to the components that will use them.
//
// To regularly report metrics to CloudWatch, use the WriteLoop helper method.
type CloudWatch struct {
	mtx                   sync.RWMutex
	sem                   chan struct{}
	namespace             string
	numConcurrentRequests int
	svc                   cloudwatchiface.CloudWatchAPI
	counters              map[string]*counter
	gauges                map[string]*gauge
	histograms            map[string]*histogram
	logger                log.Logger
}

// New returns a CloudWatch object that may be used to create metrics.
// Namespace is applied to all created metrics and maps to the CloudWatch namespace.
// NumConcurrent sets the number of simultaneous requests to Amazon.
// A good default value is 10 and the maximum is 20.
// Callers must ensure that regular calls to Send are performed, either
// manually or with one of the helper methods.
func New(namespace string, svc cloudwatchiface.CloudWatchAPI, numConcurrent int, logger log.Logger) *CloudWatch {
	if numConcurrent > maxConcurrentRequests {
		numConcurrent = maxConcurrentRequests
	}

	return &CloudWatch{
		sem:                   make(chan struct{}, numConcurrent),
		namespace:             namespace,
		numConcurrentRequests: numConcurrent,
		svc:        svc,
		counters:   map[string]*counter{},
		gauges:     map[string]*gauge{},
		histograms: map[string]*histogram{},
		logger:     logger,
	}
}

// NewCounter returns a counter. Observations are aggregated and emitted once
// per write invocation.
func (cw *CloudWatch) NewCounter(name string) metrics.Counter {
	cw.mtx.Lock()
	defer cw.mtx.Unlock()
	c := &counter{c: generic.NewCounter(name)}
	cw.counters[name] = c
	return c
}

// NewGauge returns a gauge. Observations are aggregated and emitted once per
// write invocation.
func (cw *CloudWatch) NewGauge(name string) metrics.Gauge {
	cw.mtx.Lock()
	defer cw.mtx.Unlock()
	g := &gauge{g: generic.NewGauge(name)}
	cw.gauges[name] = g
	return g
}

// NewHistogram returns a histogram. Observations are aggregated and emitted as
// per-quantile gauges, once per write invocation. 50 is a good default value
// for buckets.
func (cw *CloudWatch) NewHistogram(name string, buckets int) metrics.Histogram {
	cw.mtx.Lock()
	defer cw.mtx.Unlock()
	h := &histogram{h: generic.NewHistogram(name, buckets)}
	cw.histograms[name] = h
	return h
}

// WriteLoop is a helper method that invokes Send every time the passed
// channel fires. This method blocks until the channel is closed, so clients
// probably want to run it in its own goroutine. For typical usage, create a
// time.Ticker and pass its C channel to this method.
func (cw *CloudWatch) WriteLoop(c <-chan time.Time) {
	for range c {
		if err := cw.Send(); err != nil {
			cw.logger.Log("during", "Send", "err", err)
		}
	}
}

// Send will fire an API request to CloudWatch with the latest stats for
// all metrics. It is preferred that the WriteLoop method is used.
func (cw *CloudWatch) Send() error {
	cw.mtx.RLock()
	defer cw.mtx.RUnlock()
	now := time.Now()

	var datums []*cloudwatch.MetricDatum

	for name, c := range cw.counters {
		datums = append(datums, &cloudwatch.MetricDatum{
			MetricName: aws.String(name),
			Dimensions: makeDimensions(c.c.LabelValues()...),
			Value:      aws.Float64(c.c.Value()),
			Timestamp:  aws.Time(now),
		})
	}

	for name, g := range cw.gauges {
		datums = append(datums, &cloudwatch.MetricDatum{
			MetricName: aws.String(name),
			Dimensions: makeDimensions(g.g.LabelValues()...),
			Value:      aws.Float64(g.g.Value()),
			Timestamp:  aws.Time(now),
		})
	}

	for name, h := range cw.histograms {
		for _, p := range []struct {
			s string
			f float64
		}{
			{"50", 0.50},
			{"90", 0.90},
			{"95", 0.95},
			{"99", 0.99},
		} {
			datums = append(datums, &cloudwatch.MetricDatum{
				MetricName: aws.String(fmt.Sprintf("%s_%s", name, p.s)),
				Dimensions: makeDimensions(h.h.LabelValues()...),
				Value:      aws.Float64(h.h.Quantile(p.f)),
				Timestamp:  aws.Time(now),
			})
		}
	}

	var batches [][]*cloudwatch.MetricDatum
	for len(datums) > 0 {
		var batch []*cloudwatch.MetricDatum
		lim := min(len(datums), maxConcurrentRequests)
		batch, datums = datums[:lim], datums[lim:]
		batches = append(batches, batch)
	}

	var errors = make(chan error, len(batches))
	for _, batch := range batches {
		go func(batch []*cloudwatch.MetricDatum) {
			cw.sem <- struct{}{}
			defer func() {
				<-cw.sem
			}()
			_, err := cw.svc.PutMetricData(&cloudwatch.PutMetricDataInput{
				Namespace:  aws.String(cw.namespace),
				MetricData: batch,
			})
			errors <- err
		}(batch)
	}
	var firstErr error
	for i := 0; i < cap(errors); i++ {
		if err := <-errors; err != nil && firstErr != nil {
			firstErr = err
		}
	}

	return firstErr
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

// counter is a CloudWatch counter metric.
type counter struct {
	c *generic.Counter
}

// With implements counter
func (c *counter) With(labelValues ...string) metrics.Counter {
	c.c = c.c.With(labelValues...).(*generic.Counter)
	return c
}

// Add implements counter.
func (c *counter) Add(delta float64) {
	c.c.Add(delta)
}

// gauge is a CloudWatch gauge metric.
type gauge struct {
	g *generic.Gauge
}

// With implements gauge
func (g *gauge) With(labelValues ...string) metrics.Gauge {
	g.g = g.g.With(labelValues...).(*generic.Gauge)
	return g
}

// Set implements gauge
func (g *gauge) Set(value float64) {
	g.g.Set(value)
}

// Add implements gauge
func (g *gauge) Add(delta float64) {
	g.g.Add(delta)
}

// histogram is a CloudWatch histogram metric
type histogram struct {
	h *generic.Histogram
}

// With implements histogram
func (h *histogram) With(labelValues ...string) metrics.Histogram {
	h.h = h.h.With(labelValues...).(*generic.Histogram)
	return h
}

// Observe implements histogram
func (h *histogram) Observe(value float64) {
	h.h.Observe(value)
}

func makeDimensions(labelValues ...string) []*cloudwatch.Dimension {
	dimensions := make([]*cloudwatch.Dimension, len(labelValues)/2)
	for i, j := 0, 0; i < len(labelValues); i, j = i+2, j+1 {
		dimensions[j] = &cloudwatch.Dimension{
			Name:  aws.String(labelValues[i]),
			Value: aws.String(labelValues[i+1]),
		}
	}
	return dimensions
}


text:
package corp.mahisan.medicinastore;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;

import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;

import com.oguzdev.circularfloatingactionmenu.library.FloatingActionButton;
import com.oguzdev.circularfloatingactionmenu.library.FloatingActionMenu;
import com.oguzdev.circularfloatingactionmenu.library.SubActionButton;

public class ListView4 extends ActionBarActivity implements View.OnClickListener{

    ListView lv;
    Context context;
    Toolbar toolbar;
    // flag for Internet connection status
    Boolean isInternetPresent = false;

    // Connection detector class
    ConnectionDetector cd;
    private static final String TAG_Tour_Travel = "tourTravel";
    private static final String TAG_Medicina = "Medicina";
    private static final String TAG_Social_Network = "socialNetwork";
    private static final String TAG_Shopping_Utility = "shoppingUtility";
    private static final String TAG_NewsPaper = "newsPaper";
    public static int [] prgmImages={R.drawable.flipkart,R.drawable.snapdeal,R.drawable.myntra,R.drawable.amazon,R.drawable.freecharge,R.drawable.bookmyshow};
    public static String [] prgmNameList={"Flipkart","Snapdeal","Myntra","Amazon","FreeCharge","BookMyShow"};
    public static  String[] prgmDesc={"The Flipkart App lets you purchase most valuable products.","Snapdeal App provides you interface to shopping","Myntra App lets you shop Clothing & Goods that are valuable in daily life","Amazon App is shopping & utility app through which user can grab in user carts","Freecharge App recharge your mobile & DTH service provider","BookMyShow App lets you bring to movie interface through which you can book movie tickets and events."};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listview4);
        toolbar = (Toolbar) findViewById(R.id.app_bar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("Shopping-Utility");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        context=this;

        lv=(ListView) findViewById(R.id.listView);
        // creating connection detector class instance
        cd = new ConnectionDetector(getApplicationContext());
        // get Internet status
        isInternetPresent = cd.isConnectingToInternet();
        // check for Internet status
        if (isInternetPresent) {
            lv.setAdapter(new CustomAdapter4(this, prgmNameList, prgmImages, prgmDesc));
        }else {
            // Internet connection is not present
            // Ask user to connect to Internet
            showAlertDialog(ListView4.this, "No Internet Connection",
                    "You don't have internet connection.", false);
        }
        actionBarButton();

    }

    private void actionBarButton() {
        //define the icon for the main floating action button
        ImageView iconActionButton = new ImageView(this);
        iconActionButton.setImageResource(R.drawable.ic_action_new);

        FloatingActionButton actionButton = new FloatingActionButton.Builder(this)
                .setContentView(iconActionButton)
                .setBackgroundDrawable(R.drawable.selector_button_red)
                .build();

        //define the icons for the sub action buttons
        ImageView TourAndTravel = new ImageView(this);
        TourAndTravel.setImageResource(R.drawable.tourtravel);
        ImageView MedicinaStore = new ImageView(this);
        MedicinaStore.setImageResource(R.drawable.medicina);
        ImageView SocialNetwork = new ImageView(this);
        SocialNetwork.setImageResource(R.drawable.socialnetwork);
        ImageView ShoppingAndUtility = new ImageView(this);
        ShoppingAndUtility.setImageResource(R.drawable.shopping);
        ImageView Newspaper = new ImageView(this);
        Newspaper.setImageResource(R.drawable.newspaper);

        //set the background for all the sub buttons
        SubActionButton.Builder itemBuilder = new SubActionButton.Builder(this);
        itemBuilder.setBackgroundDrawable(getResources().getDrawable(R.drawable.selector_sub_button_gray));

        //build the sub buttons
        SubActionButton Tour = itemBuilder.setContentView(TourAndTravel).build();
        SubActionButton Med = itemBuilder.setContentView(MedicinaStore).build();
        SubActionButton Social = itemBuilder.setContentView(SocialNetwork).build();
        SubActionButton Shopping = itemBuilder.setContentView(ShoppingAndUtility).build();
        SubActionButton News = itemBuilder.setContentView(Newspaper).build();

        Tour.setTag(TAG_Tour_Travel);
        Med.setTag(TAG_Medicina);
        Social.setTag(TAG_Social_Network);
        Shopping.setTag(TAG_Shopping_Utility);
        News.setTag(TAG_NewsPaper);

        Tour.setOnClickListener(this);
        Med.setOnClickListener(this);
        Social.setOnClickListener(this);
        Shopping.setOnClickListener(this);
        News.setOnClickListener(this);

        //add the sub buttons to the main floating action button
        FloatingActionMenu actionMenu = new FloatingActionMenu.Builder(this)
                .addSubActionView(Tour)
                .addSubActionView(Med)
                .addSubActionView(Social)
                .addSubActionView(Shopping)
                .addSubActionView(News)
                .attachTo(actionButton)
                .build();
    }

    public void showAlertDialog(Context context, String title, String message, Boolean status) {
        AlertDialog alertDialog = new AlertDialog.Builder(context).create();

        // Setting Dialog Title
        alertDialog.setTitle(title);

        // Setting Dialog Message
        alertDialog.setMessage(message);

        // Setting alert dialog icon
        alertDialog.setIcon(R.drawable.fail);

        // Setting OK Button
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.my, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if(id ==android.R.id.home){
            NavUtils.navigateUpFromSameTask(this);
        }
        if(id == R.id.tour){
            Intent intent = new Intent(this,ListView1.class);
            startActivity(intent);
        }
        if(id == R.id.Medicina){
            Intent intent = new Intent(this,ListView2.class);
            startActivity(intent);
        }
        if(id == R.id.Social){
            Intent intent = new Intent(this,ListView3.class);
            startActivity(intent);
        }
        if(id == R.id.Shopping){
            Intent intent = new Intent(this,ListView4.class);
            startActivity(intent);
        }
        if(id == R.id.News){
            Intent intent = new Intent(this,ListView5.class);
            startActivity(intent);
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        Intent i = new Intent(ListView4.this,MyActivity.class);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(i);
        super.onBackPressed();
    }

    @Override
    public void onClick(View v) {
        if (v.getTag().equals(TAG_Tour_Travel)) {
            Intent i = new Intent (this,ListView1.class);
            startActivity(i);
        }
        if (v.getTag().equals(TAG_Medicina)) {
            Intent i = new Intent (this,ListView2.class);
            startActivity(i);
        }
        if (v.getTag().equals(TAG_Social_Network)) {
            Intent i = new Intent (this,ListView3.class);
            startActivity(i);
        }
        if (v.getTag().equals(TAG_Shopping_Utility)) {
            Intent i = new Intent (this,ListView4.class);
            startActivity(i);
        }
        if (v.getTag().equals(TAG_NewsPaper)) {
            Intent i = new Intent (this,ListView5.class);
            startActivity(i);
        }
    }
}


text:
License
~~~~~~~

cern-cpymad must be used in compliance with the licenses as described in
the following sections:

License for cern-cpymad source
==============================

applies to the python source of the cern-cpymad package::

    Copyright (c) 2011, CERN. All rights reserved.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use cern-cpymad 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.

License for MAD-X
=================

applies to binary distributions that do not require a separate
installation of MAD-X, i.e. binaries that are statically linked to MAD-X::

    CERN

    EUROPEAN ORGANISATION FOR NUCLEAR RESEARCH

    Program name:                 MAD --- Methodical Accelerator Design

    CERN program library entry:   T5001

    Authors or contacts:          mad@cern.ch
                                  BE-ABP Group
                                  CERN
                                  CH-1211 GENEVA 23
                                  SWITZERLAND

    Copyright CERN, Geneva 1990 - Copyright and any other appropriate legal
    protection of this computer program and associated documentation reserved
    in all countries of the world. Organisations collaborating with CERN may
    receive this program and documentation freely and without charge. CERN
    undertakes no obligation for the maintenance of this program, nor
    responsibility for its correctness, and accepts no liability whatsoever
    resulting from its use. Program and documentation are provided solely for
    the use of the organisation to which they are distributed. This program
    may not be copied or otherwise distributed without permission. This
    message must be retained on this and any other authorised copies. The
    material cannot be sold. CERN should be given credit in all references.

Additional SDDS License
=======================

applies to binary distributions that include the online model::

    Copyright (c) 2002 University of Chicago. All rights reserved.

    SDDS ToolKit is distributed subject to the following license conditions:

     SOFTWARE LICENSE AGREEMENT
     Software: SDDS ToolKit

     1. The "Software", below, refers to SDDS ToolKit (in either source code,
        or binary form and accompanying documentation). Each licensee is
        addressed as "you" or "Licensee."

     2. The copyright holders shown above and their third-party licensors
        hereby grant Licensee a royalty-free nonexclusive license, subject to
        the limitations stated herein and U.S. Government license rights.

     3. You may modify and make a copy or copies of the Software for use
        within your organization, if you meet the following conditions:
          a. Copies in source code must include the copyright notice and this
             Software License Agreement.
          b. Copies in binary form must include the copyright notice and this
             Software License Agreement in the documentation and/or other
             materials provided with the copy.

     4. You may modify a copy or copies of the Software or any portion of it,
        thus forming a work based on the Software, and distribute copies of
        such work outside your organization, if you meet all of the following
        conditions:
          a. Copies in source code must include the copyright notice and this
             Software License Agreement;
          b. Copies in binary form must include the copyright notice and this
             Software License Agreement in the documentation and/or other
             materials provided with the copy;
          c. Modified copies and works based on the Software must carry
             prominent notices stating that you changed specified portions of
             the Software.

     5. Portions of the Software resulted from work developed under a U.S.
        Government contract and are subject to the following license: the
        Government is granted for itself and others acting on its behalf a
        paid-up, nonexclusive, irrevocable worldwide license in this computer
        software to reproduce, prepare derivative works, and perform publicly
        and display publicly.

     6. WARRANTY DISCLAIMER. THE SOFTWARE IS SUPPLIED "AS IS" WITHOUT
        WARRANTY OF ANY KIND. THE COPYRIGHT HOLDERS, THEIR THIRD PARTY
        LICENSORS, THE UNITED STATES, THE UNITED STATES DEPARTMENT OF
        ENERGY, AND THEIR EMPLOYEES: (1) DISCLAIM ANY WARRANTIES,
        EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY IMPLIED
        WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
        TITLE OR NON-INFRINGEMENT, (2) DO NOT ASSUME ANY LEGAL LIABILITY
        OR RESPONSIBILITY FOR THE ACCURACY, COMPLETENESS, OR USEFULNESS
        OF THE SOFTWARE, (3) DO NOT REPRESENT THAT USE OF THE SOFTWARE
        WOULD NOT INFRINGE PRIVATELY OWNED RIGHTS, (4) DO NOT WARRANT
        THAT THE SOFTWARE WILL FUNCTION UNINTERRUPTED, THAT IT IS
        ERROR-FREE OR THAT ANY ERRORS WILL BE CORRECTED.

     7. LIMITATION OF LIABILITY. IN NO EVENT WILL THE COPYRIGHT HOLDERS,
        THEIR THIRD PARTY LICENSORS, THE UNITED STATES, THE UNITED
        STATES DEPARTMENT OF ENERGY, OR THEIR EMPLOYEES: BE LIABLE FOR
        ANY INDIRECT, INCIDENTAL, CONSEQUENTIAL, SPECIAL OR PUNITIVE
        DAMAGES OF ANY KIND OR NATURE, INCLUDING BUT NOT LIMITED TO LOSS
        OF PROFITS OR LOSS OF DATA, FOR ANY REASON WHATSOEVER, WHETHER
        SUCH LIABILITY IS ASSERTED ON THE BASIS OF CONTRACT, TORT
        (INCLUDING NEGLIGENCE OR STRICT LIABILITY), OR OTHERWISE, EVEN
        IF ANY OF SAID PARTIES HAS BEEN WARNED OF THE POSSIBILITY OF
        SUCH LOSS OR DAMAGES.


text:
<?php

namespace assegai\modules\forms\fields;

class NumberField extends SizedField
{
    public $_min_value = null;
    public $_max_value = null;
    public $_decimal = false;
    public $_max_length = 10;

    protected $_type = 'number';

    function validate()
    {
        $errors = parent::validate();
        $validator = new Validator($this->_value);

        if($this->_decimal) {
            $validator->float(sprintf("%s must be a number", $this->getName()));
        }
        else {
            $validator->integer(sprintf("%s must be a number", $this->getName()));
        }

        if($this->_min_value) {
            $validator->min($this->_min_value, sprintf(
                "%s must be greater than %f",
                $this->getName(), $this->_min_value
            ));
        }
        if($this->_max_value) {
            $validator->max($this->_max_value, sprintf(
                "%s must be less than %f",
                $this->getName(), $this->_max_value
            ));
        }

        $this->_errors = array_merge($errors, $validator->allErrors());
        return $this->allErrors();
    }

    function minValue($val)
    {
        $this->_min_value = $val;
        return $this;
    }

    function maxValue($val)
    {
        $this->_max_value = $val;
        return $this;
    }

    function decimal()
    {
        $this->_decimal = true;
    }
}


text:
Orderjs
=======

Order js in order.


text:
extern int ProcXkbUseExtension(ClientPtr client);
extern int ProcXkbSelectEvents(ClientPtr client);
extern int ProcXkbBell(ClientPtr client);
extern int ProcXkbGetState(ClientPtr client);
extern int ProcXkbLatchLockState(ClientPtr client);
extern int ProcXkbGetControls(ClientPtr client);
extern int ProcXkbSetControls(ClientPtr client);
extern int ProcXkbGetMap(ClientPtr client);
extern int ProcXkbSetMap(ClientPtr client);
extern int ProcXkbGetCompatMap(ClientPtr client);
extern int ProcXkbSetCompatMap(ClientPtr client);
extern int ProcXkbGetIndicatorState(ClientPtr client);
extern int ProcXkbGetIndicatorMap(ClientPtr client);
extern int ProcXkbSetIndicatorMap(ClientPtr client);
extern int ProcXkbGetNamedIndicator(ClientPtr client);
extern int ProcXkbSetNamedIndicator(ClientPtr client);
extern int ProcXkbGetNames(ClientPtr client);
extern int ProcXkbSetNames(ClientPtr client);
extern int ProcXkbGetGeometry(ClientPtr client);
extern int ProcXkbSetGeometry(ClientPtr client);
extern int ProcXkbPerClientFlags(ClientPtr client);
extern int ProcXkbListComponents(ClientPtr client);
extern int ProcXkbGetKbdByName(ClientPtr client);
extern int ProcXkbGetDeviceInfo(ClientPtr client);
extern int ProcXkbSetDeviceInfo(ClientPtr client);
extern int ProcXkbSetDebuggingFlags(ClientPtr client);
#endif


text:
import path from 'path';
import crypto from 'crypto';

import uuid from 'node-uuid';

export default function(musicDir) {
    return function(file) {
        const [genre, artist, album, songFile] = path.relative(musicDir, file).split(path.sep);
        const id = crypto.createHash('sha256').update(file).digest('hex');
        const {number, title} = createTrackData(songFile);
        return {
            genre,
            artist,
            album,
            file,
            number,
            title,
            id
        };
    }
}

export function createTrackData(songFile) {
    const [number, song] = songFile.split('-');
    const [title, ] = song.split('.');
    return {
        number, title
    };
}

export function buildFileInfoForBackend(map, track) {
    map[track.genre] = map[track.genre] || {};
    map[track.genre][track.artist] = map[track.genre][track.artist] || {};
    map[track.genre][track.artist][track.album] = map[track.genre][track.artist][track.album] || {};
    map[track.genre][track.artist][track.album][track.number] = {id: track.id, title: track.title};
    return map;
}


text:
<?php

namespace App\Http\Controllers;

use App\User;
use App\Http\Requests\ProfileRequest;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class ProfileController extends Controller
{
    public function __construct()
    {
        $this->middleware('checkPermission:'.\App\Permission::SYSTEM_MANAGER);
    }

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        $users = User::all();

        return view('profiles.index', compact('users'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store()
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function edit(User $user)
    {
        return view('profiles.edit', compact('user'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function update(User $user, ProfileRequest $request)
    {
        $user->setPermissions($user, $request);

        return redirect('profiles');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($id)
    {
        //
    }
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Register extends CI_Controller{

  public function __construct()
  {
    parent::__construct();
    $this->load->library('session');
    $this->load->model('Users_model');
  }

  public function index()
  {
      $data['title'] = 'Rejestracja';
      $data['background'] = 'black';
      $data['body'] = 'user/register';
      $this->load->view('main/main', $data);
  }
  public function register()
  {
      $data = json_decode(file_get_contents("php://input"));

      if ($data->name == "")
      {
        echo json_encode("empty name");
        return 0;
      }
      else
      {
        $fullname = $data->name;
      }

      if ($data->username == "")
      {
        echo json_encode("empty username");
        return 0;
      }
      else
      {
        $username = $data->username;
      }

      if ($data->password == "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" || $data->password_confirm == "")
      {
        echo json_encode("empty password");
        return 0;
      }
      else
      {
        $password = $data->password;
      }

      if ($data->password_confirm == "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" || $data->password_confirm == "")
      {
        echo json_encode("empty password_confirm");
        return 0;
      }
      else
      {
        $passwordconfirm = $data->password_confirm;
      }

      if ($data->email == "")
      {
        echo json_encode("empty email");
        return 0;
      }
      else
      {
        $email = $data->email;
      }
      if ($data->refferal == "")
      {
        echo json_encode("empty refferal");
        return 0;
      }
      else
      {
        $refferal = $data->refferal;
      }

      if ($data->name != "" && $data->username != "" && $data->email != "" && $data->password != "" && $data->password_confirm != "" && $data->refferal != "")
      {
        if($password == $passwordconfirm)
        {
          $this->Users_model->user_register($fullname, $username, $password, $email, $refferal);
          echo json_encode("true");
        }
        else
        {
          echo json_encode("confirm_password error");
        }
      }
      else
        echo json_encode("empty form");
  }
}


text:
using System;

namespace _5.BooleanVariable
{
    class Gender
    {
        static void Main()
        {

            bool isFemale;
            string gender;

            do
            {
                Console.Write("Enter gender(male / female): ");
                gender = Console.ReadLine();
                gender.ToLowerInvariant();

                if (gender[0].Equals('m'))
                {
                    isFemale = false;
                    Console.WriteLine("Are you a female? \n{0}", isFemale);
                }
                else if (gender[0].Equals('f'))
                {
                    isFemale = true;
                    Console.WriteLine("Are you a female? \n{0}", isFemale);
                }
                else
                {
                    Console.WriteLine("Incorrect input!!!");
                }
            }
            while (!gender[0].Equals('m') && !gender[0].Equals('f'));
        }
    }
}


text:
cd jni
call ndk-build
if %ERRORLEVEL% EQU 0 (
	cd..

	mkdir "assets\shaders\base"
	xcopy "..\..\data\shaders\base\*.spv" "assets\shaders\base" /Y

	mkdir "assets\shaders\terraintessellation"
	xcopy "..\..\data\shaders\terraintessellation\*.*" "assets\shaders\terraintessellation" /Y

	mkdir "assets\textures"
	xcopy "..\..\data\textures\terrain_heightmap_r16.ktx" "assets\textures" /Y
	xcopy "..\..\data\textures\terrain_texturearray_bc3.ktx" "assets\textures" /Y
	xcopy "..\..\data\textures\skysphere_bc3.ktx" "assets\textures" /Y

	mkdir "assets\models"
	xcopy "..\..\data\models\geosphere.obj" "assets\models" /Y

	mkdir "res\drawable"
	xcopy "..\..\android\images\icon.png" "res\drawable" /Y

	call ant debug -Dout.final.file=vulkanTerraintessellation.apk
) ELSE (
	echo error : ndk-build failed with errors!
	cd..
)


text:
require 'spec_helper.rb'

describe 'SyncMap' do
  it "can fetch" do
    @holodeck.mock(Twilio::Response.new(500, ''))

    expect {
      @client.preview.sync.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
                          .sync_maps('MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').fetch()
    }.to raise_exception(Twilio::REST::TwilioError)

    expect(
    @holodeck.has_request?(Holodeck::Request.new(
        method: 'get',
        url: 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Maps/MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
    ))).to eq(true)
  end

  it "receives fetch responses" do
    @holodeck.mock(Twilio::Response.new(
        200,
      %q[
      {
          "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
          "created_by": "created_by",
          "date_created": "2015-07-30T20:00:00Z",
          "date_updated": "2015-07-30T20:00:00Z",
          "links": {
              "items": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items",
              "permissions": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions"
          },
          "revision": "revision",
          "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
          "sid": "MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
          "unique_name": "unique_name",
          "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
      }
      ]
    ))

    actual = @client.preview.sync.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
                                 .sync_maps('MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').fetch()

    expect(actual).to_not eq(nil)
  end

  it "can delete" do
    @holodeck.mock(Twilio::Response.new(500, ''))

    expect {
      @client.preview.sync.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
                          .sync_maps('MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').delete()
    }.to raise_exception(Twilio::REST::TwilioError)

    expect(
    @holodeck.has_request?(Holodeck::Request.new(
        method: 'delete',
        url: 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Maps/MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
    ))).to eq(true)
  end

  it "receives delete responses" do
    @holodeck.mock(Twilio::Response.new(
        204,
      nil,
    ))

    actual = @client.preview.sync.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
                                 .sync_maps('MPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').delete()

    expect(actual).to eq(true)
  end

  it "can create" do
    @holodeck.mock(Twilio::Response.new(500, ''))

    expect {
      @client.preview.sync.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
                          .sync_maps.create()
    }.to raise_exception(Twilio::REST::TwilioError)

    expect(
    @holodeck.has_request?(Holodeck::Request.new(
        method: 'post',
        url: 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Maps',
    ))).to eq(true)
  end

  it "receives create responses" do
    @holodeck.mock(Twilio::Response.new(
        201,
      %q[
      {
          "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
          "created_by": "created_by",
          "date_created": "2015-07-30T20:00:00Z",
          "date_updated": "2015-07-30T20:00:00Z",
          "links": {
              "items": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items",
              "permissions": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions"
          },
          "revision": "revision",
          "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
          "sid": "MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
          "unique_name": "unique_name",
          "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
      }
      ]
    ))

    actual = @client.preview.sync.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
                                 .sync_maps.create()

    expect(actual).to_not eq(nil)
  end

  it "can read" do
    @holodeck.mock(Twilio::Response.new(500, ''))

    expect {
      @client.preview.sync.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
                          .sync_maps.list()
    }.to raise_exception(Twilio::REST::TwilioError)

    expect(
    @holodeck.has_request?(Holodeck::Request.new(
        method: 'get',
        url: 'https://preview.twilio.com/Sync/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Maps',
    ))).to eq(true)
  end

  it "receives read_empty responses" do
    @holodeck.mock(Twilio::Response.new(
        200,
      %q[
      {
          "maps": [],
          "meta": {
              "first_page_url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps?PageSize=50&Page=0",
              "key": "maps",
              "next_page_url": null,
              "page": 0,
              "page_size": 50,
              "previous_page_url": null,
              "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps?PageSize=50&Page=0"
          }
      }
      ]
    ))

    actual = @client.preview.sync.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
                                 .sync_maps.list()

    expect(actual).to_not eq(nil)
  end

  it "receives read_full responses" do
    @holodeck.mock(Twilio::Response.new(
        200,
      %q[
      {
          "maps": [
              {
                  "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                  "created_by": "created_by",
                  "date_created": "2015-07-30T20:00:00Z",
                  "date_updated": "2015-07-30T20:00:00Z",
                  "links": {
                      "items": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Items",
                      "permissions": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions"
                  },
                  "revision": "revision",
                  "service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                  "sid": "MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                  "unique_name": "unique_name",
                  "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps/MPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
              }
          ],
          "meta": {
              "first_page_url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps?PageSize=50&Page=0",
              "key": "maps",
              "next_page_url": null,
              "page": 0,
              "page_size": 50,
              "previous_page_url": null,
              "url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Maps?PageSize=50&Page=0"
          }
      }
      ]
    ))

    actual = @client.preview.sync.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
                                 .sync_maps.list()

    expect(actual).to_not eq(nil)
  end
end


text:
(function(){

function loadUser(user) {
  var userAlreadyExists = typeof Meteor.users.findOne({ username : user.username }) === 'object';

  if (!userAlreadyExists) {
    Accounts.createUser(user);
  }
}

function InitializeUserProfile(user){
  console.log(user);
  //HB_Profiles.insert({"user_id": })
}

Meteor.startup(function () {

  var users = YAML.eval(Assets.getText('users.yml'));

  //console.log(this)

  for (key in users) if (users.hasOwnProperty(key)) {
    loadUser(users[key]);
  }

});

})();


text:
using System.Web.Mvc;

namespace Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult FlotCharts()
        {
            return View("FlotCharts");
        }

        public ActionResult MorrisCharts()
        {
            return View("MorrisCharts");
        }

        public ActionResult Tables()
        {
            return View("Tables");
        }

        public ActionResult Forms()
        {
            return View("Forms");
        }

        public ActionResult Panels()
        {
            return View("Panels");
        }

        public ActionResult Buttons()
        {
            return View("Buttons");
        }

        public ActionResult Notifications()
        {
            return View("Notifications");
        }

        public ActionResult Typography()
        {
            return View("Typography");
        }

        public ActionResult Icons()
        {
            return View("Icons");
        }

        public ActionResult Grid()
        {
            return View("Grid");
        }

        public ActionResult Blank()
        {
            return View("Blank");
        }

        public ActionResult Login()
        {
            return View("Login");
        }

        public ActionResult MyUser()
        {
            return View("MyUser");
        }

    }
}


text:
template <class Key>
class EXPORT ObjectPoolPattern_Texture : public ObjectPoolPattern<Key,TexturePtr>
{
protected:
	void DeleteVal(TexturePtr value);
};

template <class Key>
void ObjectPoolPattern_Texture<Key>::DeleteVal(TexturePtr value)
{
	value.Delete();
}


text:
package so.ontolog.formula.runtime;

/**
 *

 * @author Ikchan Kwon
 *
 */
public class VarQName extends QName {
	private static final long serialVersionUID = 5362874983450995326L;

	private QName index;

	/**
	 * @param parent
	 * @param name
	 */
	public VarQName(QName parent, QName index) {
		super(parent, "[" + index.getFullName() + "]");
		this.index = index;
	}

	/**
	 * @return the index
	 */
	public QName getIndex() {
		return index;
	}
}


text:
<?php

namespace Piplin\Composers;

use Illuminate\Contracts\View\View;
use Piplin\Services\Update\LatestReleaseInterface;

/**
 * Update composer for the update bar.
 */
class UpdateComposer
{
    private $release;

    /**
     * Class constructor.
     *
     * @param LatestReleaseInterface $release
     */
    public function __construct(LatestReleaseInterface $release)
    {
        $this->release = $release;
    }

    /**
     * Determines if the update prompt should show.
     *
     * @param  \Illuminate\Contracts\View\View $view
     * @return void
     */
    public function compose(View $view)
    {
        $latest_tag = str_replace(['V', 'v'], '', $this->release->latest());

        $is_outdated = version_compare($latest_tag, APP_VERSION, '>');

        $view->with('is_outdated', $is_outdated);
        $view->with('current_version', APP_VERSION);
        $view->with('latest_version', $latest_tag);
    }
}