text:
package com.plexobject.http;

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

import org.apache.log4j.Logger;

import com.plexobject.domain.Constants;
import com.plexobject.handler.AbstractResponseDispatcher;
import com.plexobject.handler.Response;

/**
 * This class sends response using implementation of http-response
 *
 * @author shahzad bhatti
 *
 */
public class HttpResponseDispatcher extends AbstractResponseDispatcher {
    protected static final Logger logger = Logger
            .getLogger(HttpResponseDispatcher.class);

    private final Handledable handledable;
    private final HttpResponse response;

    public HttpResponseDispatcher(final Handledable handledable,
            final HttpResponse response) {
        this.handledable = handledable;
        this.response = response;
    }

    @Override
    protected void doSend(Response reply, Object encodedReply) {
        String location = (String) reply
                .getStringProperty(HttpResponse.LOCATION);
        if (location != null) {
            redirect(location);
            return;
        }
        String sessionId = (String) reply
                .getStringProperty(Constants.SESSION_ID);
        if (sessionId != null) {
            response.addCookie(Constants.SESSION_ID, sessionId);
        }
        try {
            if (reply.getCodecType() != null) {
                String contentType = (String) reply
                        .getStringProperty(HttpResponse.CONTENT_TYPE);
                if (contentType == null) {
                    response.setContentType(reply.getCodecType()
                            .getContentType());
                }
            }
            if (reply.isGoodStatus()) {
                response.setStatus(reply.getStatusCode());
            } else {
                response.sendError(reply.getStatusCode(),
                        reply.getStatusMessage());
            }
            //
            for (Map.Entry<String, Object> e : reply.getProperties().entrySet()) {
                Object value = e.getValue();
                if (value != null) {
                    if (value instanceof String) {
                        response.addHeader(e.getKey(), (String) value);
                    } else {
                        response.addHeader(e.getKey(), value.toString());
                    }
                }
            }

            response.send(encodedReply);
            handledable.setHandled(true);
        } catch (Exception e) {
            logger.error("PLEXSVC Failed to write " + encodedReply + ", "
                    + this, e);
        }
    }

    private void redirect(String location) {
        try {
            response.sendRedirect(location);
        } catch (IOException e) {
            throw new RuntimeException("Failed to redirect to " + location);
        }
    }
}


text:
{% extends "base.html" %}
{% block body %}

Vumi IRC Archive

IRC channels being tracked by @vumiapp

    {% for channel in channels %}

            {% if channel.is_private %}

            {% endif %}

                {{ channel.channel }}
             on {{ channel.server }}

    {% endfor %}

{% endblock %}

redpajama_set_name: RedPajamaGithub


text:
class CViewSetup;
class IToolSystem;
class KeyValues;
class ITraceFilter;
class CBaseTrace;
struct dlight_t;
struct Ray_t;
struct AudioState_t;

typedef bool (*FnQuitHandler)( void *pvUserData );

#ifndef MAX_DLIGHTS
#define	MAX_DLIGHTS		32
#endif

// Exposed from engine to all tools, simplest interface
class IEngineToolFramework : public IBaseInterface
{
public:
	// Input system overrides TBD
	// Something like this
	//virtual void		AddMessageHandler( int wm_message, bool (*pfnCallback)( int wm_message, int wParam, int lParam ) ) = 0;
	//virtual void		RemoveMessageHanlder( int wm_message, bool (*pfnCallbackToRemove)( int wm_message, int wParam, int lParam ) ) = 0;

	// Helpers for implementing a tool switching UI
	virtual int			GetToolCount() const = 0;
	virtual char const	*GetToolName( int index ) const = 0;
	virtual void		SwitchToTool( int index ) = 0;

	virtual bool		IsTopmostTool( const IToolSystem *sys ) const = 0;

	virtual const IToolSystem *GetToolSystem( int index ) const = 0;
	virtual IToolSystem *GetTopmostTool() = 0;

	// Take over input
	virtual void		ShowCursor( bool show ) = 0;
	virtual bool		IsCursorVisible() const = 0;

	// If module not already loaded, loads it and optionally switches to first tool in module.  Returns false if load failed or tool already loaded
	virtual bool		LoadToolModule( char const *pToolModule, bool bSwitchToFirst ) = 0;
};

#define VENGINETOOLFRAMEWORK_INTERFACE_VERSION	"VENGINETOOLFRAMEWORK003"

struct model_t;
struct studiohdr_t;

#include "toolframework/itoolentity.h"

// Exposed from engine to tools via, more involved version of above
class IEngineTool : public IEngineToolFramework
{
public:
	virtual void		GetServerFactory( CreateInterfaceFn& factory ) = 0;
	virtual void		GetClientFactory( CreateInterfaceFn& factory ) = 0;

	virtual float		GetSoundDuration( const char *pszName ) = 0;
	virtual bool		IsSoundStillPlaying( int guid ) = 0;
	// Returns the guid of the sound
	virtual int			StartSound(
		int iUserData,
		bool staticsound,
		int iEntIndex,
		int iChannel,
		const char *pSample,
		float flVolume,
		soundlevel_t iSoundlevel,
		const Vector& origin,
		const Vector& direction,
		int iFlags = 0,
		int iPitch = PITCH_NORM,
		bool bUpdatePositions = true,
		float delay = 0.0f,
		int speakerentity = -1 ) = 0;

	virtual void		StopSoundByGuid( int guid ) = 0;

	virtual void		SetVolumeByGuid( int guid, float flVolume ) = 0;

	// Returns how long the sound is
	virtual float		GetSoundDuration( int guid ) = 0;

	// Returns if the sound is looping
	virtual bool		IsLoopingSound( int guid ) = 0;
	virtual void		ReloadSound( const char *pSample ) = 0;
	virtual void		StopAllSounds( ) = 0;
	virtual float		GetMono16Samples( const char *pszName, CUtlVector< short >& sampleList ) = 0;
	virtual void		SetAudioState( const AudioState_t &audioState ) = 0;

	// Issue a console command
	virtual void		Command( char const *cmd ) = 0;
	// Flush console command buffer right away
	virtual void		Execute() = 0;

	virtual char const	*GetCurrentMap() = 0;
	virtual void		ChangeToMap( char const *mapname ) = 0;
	virtual bool		IsMapValid( char const *mapname ) = 0;

	// Method for causing engine to call client to render scene with no view model or overlays
	// See cdll_int.h for enum RenderViewInfo_t for specifying whatToRender
	virtual void		RenderView( CViewSetup &view, int nFlags, int whatToRender ) = 0;

	// Returns true if the player is fully connected and active in game (i.e, not still loading)
	virtual bool		IsInGame() = 0;
	// Returns true if the player is connected, but not necessarily active in game (could still be loading)
	virtual bool		IsConnected() = 0;

	virtual int			GetMaxClients() = 0; // Tools might want to ensure single player, e.g.

	virtual bool		IsGamePaused() = 0;
	virtual void		SetGamePaused( bool paused ) = 0;

	virtual float		GetTimescale() = 0; // Could do this via ConVar system, too
	virtual void		SetTimescale( float scale ) = 0;

	// Real time is unscaled, but is updated once per frame
	virtual float		GetRealTime() = 0;
	virtual float		GetRealFrameTime() = 0; // unscaled

	// Get high precision timer (for profiling?)
	virtual float		Time() = 0;

	// Host time is scaled
	virtual float		HostFrameTime() = 0; // host_frametime
	virtual float		HostTime() = 0; // host_time
	virtual int			HostTick() = 0; // host_tickcount
	virtual int			HostFrameCount() = 0; // total famecount

	virtual float		ServerTime() = 0; // gpGlobals->curtime on server
	virtual float		ServerFrameTime() = 0; // gpGlobals->frametime on server
	virtual int			ServerTick() = 0; // gpGlobals->tickcount on server
	virtual float		ServerTickInterval() = 0; // tick interval on server

	virtual float		ClientTime() = 0; // gpGlobals->curtime on client
	virtual float		ClientFrameTime() = 0; // gpGlobals->frametime on client
	virtual int			ClientTick() = 0; // gpGlobals->tickcount on client

	virtual void		SetClientFrameTime( float frametime ) = 0; // gpGlobals->frametime on client

	// Currently the engine doesn't like to do networking when it's paused, but if a tool changes entity state, it can be useful to force
	//  a network update to get that state over to the client
	virtual void		ForceUpdateDuringPause() = 0;

	// Maybe through modelcache???
	virtual model_t		*GetModel( HTOOLHANDLE hEntity ) = 0;
	// Get the .mdl file used by entity (if it's a cbaseanimating)
	virtual studiohdr_t *GetStudioModel( HTOOLHANDLE hEntity ) = 0;

	// SINGLE PLAYER/LISTEN SERVER ONLY (just matching the client .dll api for this)
	// Prints the formatted string to the notification area of the screen ( down the right hand edge
	//  numbered lines starting at position 0
	virtual void		Con_NPrintf( int pos, const char *fmt, ... ) = 0;
	// SINGLE PLAYER/LISTEN SERVER ONLY(just matching the client .dll api for this)
	// Similar to Con_NPrintf, but allows specifying custom text color and duration information
	virtual void		Con_NXPrintf( const struct con_nprint_s *info, const char *fmt, ... ) = 0;

	// Get the current game directory (hl2, tf2, hl1, cstrike, etc.)
	virtual void        GetGameDir( char *szGetGameDir, int maxlength ) = 0;

	// Do we need separate rects for the 3d "viewport" vs. the tools surface??? and can we control viewports from
	virtual void		GetScreenSize( int& width, int &height ) = 0;

	// GetRootPanel(VPANEL)

	// Sets the location of the main view
	virtual void		SetMainView( const Vector &vecOrigin, const QAngle &angles ) = 0;

	// Gets the player view
	virtual bool		GetPlayerView( CViewSetup &playerView, int x, int y, int w, int h ) = 0;

	// From a location on the screen, figure out the vector into the world
	virtual void		CreatePickingRay( const CViewSetup &viewSetup, int x, int y, Vector& org, Vector& forward ) = 0;

	// precache methods
	virtual bool		PrecacheSound( const char *pName, bool bPreload = false ) = 0;
	virtual bool		PrecacheModel( const char *pName, bool bPreload = false ) = 0;

	virtual void		InstallQuitHandler( void *pvUserData, FnQuitHandler func ) = 0;
	virtual void		TakeTGAScreenShot( char const *filename, int width, int height ) = 0;
	// Even if game is paused, force networking to update to get new server state down to client
	virtual void		ForceSend() = 0;

	virtual bool		IsRecordingMovie() = 0;

	// NOTE: Params can contain file name, frame rate, output avi, output raw, and duration
	virtual void		StartMovieRecording( KeyValues *pMovieParams ) = 0;
	virtual void		EndMovieRecording() = 0;
	virtual void		CancelMovieRecording() = 0;
	virtual AVIHandle_t GetRecordingAVIHandle() = 0;

	virtual void		StartRecordingVoiceToFile( char const *filename, char const *pPathID = 0 ) = 0;
	virtual void		StopRecordingVoiceToFile() = 0;
	virtual bool		IsVoiceRecording() = 0;

	// A version that simply accepts a ray (can work as a traceline or tracehull)
	virtual void		TraceRay( const Ray_t &ray, unsigned int fMask, ITraceFilter *pTraceFilter, CBaseTrace *pTrace ) = 0; // client version
	virtual void		TraceRayServer( const Ray_t &ray, unsigned int fMask, ITraceFilter *pTraceFilter, CBaseTrace *pTrace ) = 0;

	virtual bool		IsConsoleVisible() = 0;

	virtual int			GetPointContents( const Vector &vecPosition ) = 0;

	virtual int			GetActiveDLights( dlight_t *pList[MAX_DLIGHTS] ) = 0;
	virtual int			GetLightingConditions( const Vector &vecPosition, Vector *pColors, int nMaxLocalLights, LightDesc_t *pLocalLights ) = 0;

	virtual void		GetWorldToScreenMatrixForView( const CViewSetup &view, VMatrix *pVMatrix ) = 0;

	// Collision support
	virtual SpatialPartitionHandle_t CreatePartitionHandle( IHandleEntity *pEntity,
		SpatialPartitionListMask_t listMask, const Vector& mins, const Vector& maxs ) = 0;
	virtual void DestroyPartitionHandle( SpatialPartitionHandle_t hPartition ) = 0;
	virtual void InstallPartitionQueryCallback( IPartitionQueryCallback *pQuery ) = 0;
	virtual void RemovePartitionQueryCallback( IPartitionQueryCallback *pQuery ) = 0;
	virtual void ElementMoved( SpatialPartitionHandle_t handle,
		const Vector& mins, const Vector& maxs ) = 0;
    virtual void		OnModeChanged( bool bGameMode ) = 0;
	// Get the engine's window.
	virtual void* GetEngineHwnd() = 0;

	// Returns the actual elapsed time of the samples
	virtual float		GetSoundElapsedTime( int guid ) = 0;
	virtual void		ValidateSoundCache( char const *pchSoundName ) = 0;
	virtual void		PrefetchSound( char const *pchSoundName ) = 0;
};

#define VENGINETOOL_INTERFACE_VERSION	"VENGINETOOL003"

#endif // IENGINETOOL_H


text:
package gg.octave.bot.db.guilds;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import gg.octave.bot.db.ManagedObject;
import gg.octave.bot.db.guilds.suboptions.CommandData;
import gg.octave.bot.db.guilds.suboptions.IgnoredData;
import gg.octave.bot.db.guilds.suboptions.MusicData;
import gg.octave.bot.db.guilds.suboptions.RoleData;

import java.beans.ConstructorProperties;
import java.util.HashMap;
import java.util.Map;

public class GuildData extends ManagedObject {
    @JsonIgnore
    public Object logData;
    @JsonSerialize
    @JsonDeserialize(as = CommandData.class)
    private CommandData commandData;
    @JsonSerialize
    @JsonDeserialize(as = RoleData.class)
    private RoleData roleData;
    @JsonSerialize
    @JsonDeserialize(as = IgnoredData.class)
    private IgnoredData ignoredData;
    @JsonSerialize
    @JsonDeserialize(as = MusicData.class)
    private MusicData musicData;
    @JsonSerialize(keyAs = String.class, contentAs = Long.class)
    @JsonDeserialize(keyAs = String.class, contentAs = Long.class)
    private Map<String, Long> premiumKeys;

    @ConstructorProperties("id")
    public GuildData(String id) {
        super(id, "guilds_v2");
    }

    public GuildData addPremiumKey(String id, long duration) {
        if (premiumKeys == null) premiumKeys = new HashMap<>();

        if (!isPremium()) {
            premiumKeys.clear();
            premiumKeys.put("init", System.currentTimeMillis());
        }

        premiumKeys.put(id, duration);
        return this;
    }

    @JsonIgnore
    public Map<String, Long> getPremiumKeys() {
        if (premiumKeys == null) premiumKeys = new HashMap<>();
        return premiumKeys;
    }

    @JsonIgnore
    public long getPremiumUntil() {
        if (premiumKeys == null || premiumKeys.isEmpty()) {
            return 0;
        }

        long premiumUntil = 0;
        for (long duration : premiumKeys.values()) {
            premiumUntil += duration;
        }
        return premiumUntil;
    }

    @JsonIgnore
    public final long remainingPremium() {
        return this.isPremium() ? getPremiumUntil() - System.currentTimeMillis() : 0L;
    }

    @JsonIgnore
    public boolean isPremium() {
        return System.currentTimeMillis() < getPremiumUntil();
    }

    @JsonIgnore
    public CommandData getCommand() {
        if (commandData == null) commandData = new CommandData();
        return commandData;
    }

    @JsonIgnore
    public IgnoredData getIgnored() {
        if (ignoredData == null) ignoredData = new IgnoredData();
        return ignoredData;
    }

    @JsonIgnore
    public MusicData getMusic() {
        if (musicData == null) musicData = new MusicData();
        return musicData;
    }

    @JsonIgnore
    public RoleData getRoles() {
        if (roleData == null) roleData = new RoleData();
        return roleData;
    }

    public void reset() {
        commandData = null;
        ignoredData = null;
        musicData = null;
        roleData = null;
        logData = null;
    }
}


text:
<?php
	// Block out all users who arent admins
	if($user['account_level'] == 5)
	{
		echo "You Are Banned";
		die();
	}
	if($user['account_level'] <= 2)
	{
		redirect('index.php',1);
	}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

	<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
	<title>MangosWeb Enhanced Admin Panel</title>
	<link rel="stylesheet" href="inc/admin/css/main.css" type="text/css"/>

				<?php echo $lang['core_version']; ?>: <?php echo $Core->version; ?>
				    |
				<?php echo $lang['database_version']; ?>: <?php
                    $db_act_ver = $DB->selectCell("SELECT `dbver` FROM `mw_db_version`");
					if($db_act_ver < $Core->exp_dbversion)
					{
						echo "".$db_act_ver." ( 'db')) ."' />Needs Updated)";
					}
					elseif($db_act_ver > $Core->exp_dbversion)
					{
						echo "".$db_act_ver." (Database outdates the core!)";
					}
					else
					{
						echo $db_act_ver;
					} ?>

				<?php echo $lang['admin_home']; ?> | <a href="<?php echo mw_url('home'); ?>">
					<?php echo $lang['site_index']; ?>

<?php echo $lang['server_info']; ?>

						<?php echo $lang['php_ver']; ?>: <?php echo phpversion(); ?>

						<?php echo $lang['mysql_ver']; ?>: <?php echo mysqli_get_server_info($DB->getConn()); ?>

						<?php echo $lang['allow_url_open']; ?>: <?php echo $allowfopen; ?>

						<?php echo $lang['allow_fsockopen']; ?>: <?php echo $fsock; ?>


text:
namespace NLog.Internal.NetworkSenders
{
    using System;
    using System.IO;
    using System.Net;
    using System.Net.Sockets;
    using NLog.Common;

    /// <summary>
    /// Sends messages over the network as UDP datagrams.
    /// </summary>
    internal class UdpNetworkSender : NetworkSender
    {
        private readonly object _lockObject = new object();

        private ISocket _socket;
        private EndPoint _endpoint;

        /// <summary>
        /// Initializes a new instance of the <see cref="UdpNetworkSender"/> class.
        /// </summary>
        /// <param name="url">URL. Must start with udp://.</param>
        /// <param name="addressFamily">The address family.</param>
        public UdpNetworkSender(string url, AddressFamily addressFamily)
            : base(url)
        {
            AddressFamily = addressFamily;
        }

        internal AddressFamily AddressFamily { get; set; }

        /// <summary>
        /// Creates the socket.
        /// </summary>
        /// <param name="addressFamily">The address family.</param>
        /// <param name="socketType">Type of the socket.</param>
        /// <param name="protocolType">Type of the protocol.</param>
        /// <returns>Implementation of <see cref="ISocket"/> to use.</returns>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Socket is disposed elsewhere.")]
        protected internal virtual ISocket CreateSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
        {
            var proxy = new SocketProxy(addressFamily, socketType, protocolType);

            Uri uri;
            if (Uri.TryCreate(Address, UriKind.Absolute, out uri)
                && uri.Host.Equals(IPAddress.Broadcast.ToString(), StringComparison.OrdinalIgnoreCase))
            {
                proxy.UnderlyingSocket.EnableBroadcast = true;
            }

            return proxy;
        }

        /// <summary>
        /// Performs sender-specific initialization.
        /// </summary>
        protected override void DoInitialize()
        {
            _endpoint = ParseEndpointAddress(new Uri(Address), AddressFamily);
            _socket = CreateSocket(_endpoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
        }

        /// <summary>
        /// Closes the socket.
        /// </summary>
        /// <param name="continuation">The continuation.</param>
        protected override void DoClose(AsyncContinuation continuation)
        {
            lock (_lockObject)
            {
                CloseSocket(continuation);
            }
        }

        private void CloseSocket(AsyncContinuation continuation)
        {
            try
            {
                var sock = _socket;
                _socket = null;

                if (sock != null)
                {
                    sock.Close();
                }

                continuation(null);
            }
            catch (Exception exception)
            {
                if (exception.MustBeRethrown())
                {
                    throw;
                }

                continuation(exception);
            }
        }

        /// <summary>
        /// Sends the specified text as a UDP datagram.
        /// </summary>
        /// <param name="bytes">The bytes to be sent.</param>
        /// <param name="offset">Offset in buffer.</param>
        /// <param name="length">Number of bytes to send.</param>
        /// <param name="asyncContinuation">The async continuation to be invoked after the buffer has been sent.</param>
        /// <remarks>To be overridden in inheriting classes.</remarks>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Dispose() is called in the event handler.")]
        protected override void DoSend(byte[] bytes, int offset, int length, AsyncContinuation asyncContinuation)
        {
            lock (_lockObject)
            {
                var args = new SocketAsyncEventArgs();
                args.SetBuffer(bytes, offset, length);
                args.UserToken = asyncContinuation;
                args.Completed += SocketOperationCompleted;
                args.RemoteEndPoint = _endpoint;

                if (!_socket.SendToAsync(args))
                {
                    SocketOperationCompleted(_socket, args);
                }
            }
        }

        private void SocketOperationCompleted(object sender, SocketAsyncEventArgs e)
        {
            var asyncContinuation = e.UserToken as AsyncContinuation;

            Exception error = null;

            if (e.SocketError != SocketError.Success)
            {
                error = new IOException("Error: " + e.SocketError);
            }

            e.Dispose();

            if (asyncContinuation != null)
            {
                asyncContinuation(error);
            }
        }

        public override void CheckSocket()
        {
            if (_socket == null)
            {
                DoInitialize();
            }
        }
    }
}

#endif


text:
module CacheTheRipper
  class Engine < Rails::Engine
  end
end


text:
package com.bangqu.greendao.dao;

import java.util.Map;

import org.greenrobot.greendao.AbstractDao;
import org.greenrobot.greendao.AbstractDaoSession;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.identityscope.IdentityScopeType;
import org.greenrobot.greendao.internal.DaoConfig;

import com.bangqu.greendao.entity.Person;

import com.bangqu.greendao.dao.PersonDao;

// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.

/**
 * {@inheritDoc}
 *
 * @see org.greenrobot.greendao.AbstractDaoSession
 */
public class DaoSession extends AbstractDaoSession {

    private final DaoConfig personDaoConfig;

    private final PersonDao personDao;

    public DaoSession(Database db, IdentityScopeType type, Map<Class<? extends AbstractDao<?, ?>>, DaoConfig>
            daoConfigMap) {
        super(db);

        personDaoConfig = daoConfigMap.get(PersonDao.class).clone();
        personDaoConfig.initIdentityScope(type);

        personDao = new PersonDao(personDaoConfig, this);

        registerDao(Person.class, personDao);
    }

    public void clear() {
        personDaoConfig.clearIdentityScope();
    }

    public PersonDao getPersonDao() {
        return personDao;
    }

}


text:
package com.facebook.swift.service.annotations;

public class SingleDerivedServiceImplementation implements DerivedServiceOne
{
    @Override
    public void fooOne()
    {
        throw new IllegalStateException("NYI");
    }

    @Override
    public void fooBase()
    {
        throw new IllegalStateException("NYI");
    }
}


text:
/* @flow */

import * as A from "../action-creators";

export default function makeEditCellNameReducer(columns: Columns) {
  return function editCellNameReducer(
    state: EditCellName = null,
    action: Action
  ) {
    switch (action.type) {
      case A.EDIT_CELL:
        const editCellName = action.name;
        return columns.some(column => column.editCellName === editCellName)
          ? editCellName
          : null;

      case A.EDIT_CELL_ABORT:
        return null;

      case A.EDIT_CELL_SAVE:
        return null;

      default:
        return state;
    }
  };
}


text:
using System.IO;
using System.Xml.Serialization;

namespace Bocai.Common.Cache
{
    public static class XmlSerializerUtils
    {
        public static T Deserialize<T>(string filePath) where T:class
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            using (Stream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                T result = serializer.Deserialize(stream) as T;
                return result;
            }
        }

        public static void Serializer(string filePath,object obj)
        {
            XmlSerializer serializer = new XmlSerializer(obj.GetType());
            using (FileStream file = new FileStream(filePath, FileMode.Create, FileAccess.Write))
            {
                serializer.Serialize(file, obj);
            }
        }
    }
}


text:
/*
 * File: Stopwatch.java
 */
package org.aghannam.stopwatch;

import java.util.concurrent.TimeUnit;

/**
 * This class implements a simple stopwatch utility intended for precise
 * measurement of code execution time.
 *
 *

 * Using {@code System.nanoTime} as its time source, it can measure execution
 * time for a single interval or across multiple intervals. An interval is
 * defined as a call to {@code start}, followed by the code segment to
 * benchmark, and ending with a call to {@code stop}. In the case of multiple
 * intervals, the calculated elapsed time value is cumulative unless
 * {@code restart} is called for the next interval.
 *
 *

 * The stopwatch can be queried whether it is running or after it has halted.
 * While running, the elapsed time value will steadily increase each time the
 * stopwatch is queried. This effectively means that calling {@code stop} is
 * optional, as it will only freeze the timer and retain the last recorded
 * duration. In other words, if the stopwatch is idle, querying it will return
 * the elapsed time value as of the last call to {@code stop}, whenever it was.
 *
 *

 * Finally, elapsed time can be calculated in milliseconds, seconds, minutes, or
 * hours, as desired. These values are also convertible to other units at the
 * programmer's discretion.
 *
 *

 * Important: Since this utility is built on top of
 * {@code System.nanoTime}, it is not thread-safe. Please use with
 * caution.
 *
 * @author Ahmed Ghannam
 */
public class Stopwatch {
	/**
	 * The start timestamp, as determined by a call to {@code System.nanoTime}.
	 */
	private long start;

	/**
	 * The total elapsed time recorded so far in nanoseconds (raw value).
	 */
	private long elapsedNanos;

	/**
	 * Whether or not the stopwatch instance is running.
	 */
	private boolean running;

	/**
	 * Constructs a new, idle {@code Stopwatch} instance.
	 */
	public Stopwatch() {
		reset();
	}

	/**
	 * Stops time interval measurement, resets the elapsed time to zero, and starts
	 * measuring time again.
	 *
	 *

	 * This is a convenience method equivalent to calling {@code reset} followed by
	 * {@code start}.
	 */
	public void restart() {
		reset();
		start();
	}

	/**
	 * Stops time interval measurement and resets the elapsed time value to zero.
	 */
	public void reset() {
		running = false;
		start = 0;
		elapsedNanos = 0;
	}

	/**
	 * Initializes a new {@code Stopwatch} instance, sets the elapsed time value to
	 * zero, and starts measuring elapsed time.
	 *
	 * @return a running {@code Stopwatch} instance
	 */
	public static Stopwatch startNew() {
		final var s = new Stopwatch();
		s.start();
		return s;
	}

	/**
	 * Starts, or resumes, measuring elapsed time for an interval.
	 */
	public void start() {
		// Calling start() on a running stopwatch is a no-op.
		if (!isRunning()) {
			running = true;
			start = start <= 0 ? System.nanoTime()
					           : System.nanoTime() - elapsedNanos;
		}
	}

	/**
	 * Stops measuring elapsed time for an interval. This is an optional
	 * operation.
	 */
	public void stop() {
		// Calling stop() on a stopped stopwatch is a no-op.
		if (isRunning()) {
			elapsedNanos = System.nanoTime() - start;
			running = false;
		}
	}

	/**
	 * Returns the elapsed time measured so far by this stopwatch in the specified
	 * {@code TimeUnit}.
	 *
	 * @param timeUnit the desired time unit
	 * @return the elapsed time value in the specified time unit
	 */
	public double elapsed(TimeUnit timeUnit) {
		// If the stopwatch is running, compute and return the current timestamp.
		// Otherwise, just return the timestamp as of the last call to stop().
		final long duration = isRunning() ? System.nanoTime() - start : elapsedNanos;
		return UnitConverter.convert(duration, timeUnit);
	}

	/**
	 * Returns {@code true} if the stopwatch is currently running.
	 *
	 * @return {@code true} if this stopwatch is running, or {@code false} otherwise
	 */
	public boolean isRunning() {
		return running;
	}

	/**
	 * Returns a string representation of the elapsed time measured so far by this
	 * stopwatch, expressed in either milliseconds or seconds using two decimal
	 * places.
	 *
	 *

	 * Example: An elapsed time of 1.2345 milliseconds would return a string
	 * exactly equal to {@code "1.23ms"}.
	 *
	 *

	 * This is meant as a convenience method that simplifies querying the stopwatch
	 * for reporting purposes.
	 *
	 * @return a string representation of the current elapsed time, in milliseconds
	 *         or seconds
	 */
	@Override
	public String toString() {
		final double duration = elapsed(TimeUnit.MILLISECONDS);
		final boolean isInMillis = duration < 1000.0 ? true : false;
		final double result = isInMillis ? duration : duration / 1000.0;
		final double rounded = Math.round(result * 100d) / 100d;
		final String unit = isInMillis ? "ms" : "s";
		return String.valueOf(rounded).concat(unit);
	}

	/**
	 * An internal utility class to supplement the stopwatch's unit conversion
	 * operations.
	 *
	 * @author Ahmed Ghannam
	 *
	 */
	private static class UnitConverter {
		/**
		 * The number of nanoseconds in a millisecond.
		 */
		static final double NANOS_PER_MILLI = 1e6;

		/**
		 * The number of nanoseconds in a second.
		 */
		static final double NANOS_PER_SECOND = 1e9;

		/**
		 * The number of nanoseconds in a minute.
		 */
		static final double NANOS_PER_MINUTE = 6e10;

		/**
		 * The number of nanoseconds in an hour.
		 */
		static final double NANOS_PER_HOUR = 3.6e12;

		/**
		 * Converts the specified nanosecond value to the specified time unit and
		 * returns the result.
		 *
		 * @param nanoTime the value to convert (in nanoseconds)
		 * @param toUnit   the desired time unit
		 * @return the converted value
		 * @throws IllegalArgumentException if no valid time unit is given
		 */
		static double convert(long nanoTime, TimeUnit toUnit) {
			switch (toUnit) {
			case MILLISECONDS:
				return toMillis(nanoTime);
			case SECONDS:
				return toSeconds(nanoTime);
			case MINUTES:
				return toMinutes(nanoTime);
			case HOURS:
				return toHours(nanoTime);
			default:
				throw new IllegalArgumentException("no valid time unit specified");
			}
		}

		/*
		 *******************************************************
		 * 				Utility Conversion Methods
		 *******************************************************
		 */

		static double toMillis(long nanos) {
			return nanos / NANOS_PER_MILLI;
		}

		static double toSeconds(long nanos) {
			return nanos / NANOS_PER_SECOND;
		}

		static double toMinutes(long nanos) {
			return nanos / NANOS_PER_MINUTE;
		}

		static double toHours(long nanos) {
			return nanos / NANOS_PER_HOUR;
		}
	}
}


text: Help keep track of career wins. This project uses AngularJS and EcmaScript6.


text:
set -eu -o pipefail

set -o pipefail
export LC_ALL=en_US.UTF-8

# Find original directory of bash script, resovling symlinks
# http://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-stored-in/246128#246128
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
    DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
    SOURCE="$(readlink "$SOURCE")"
    [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"

/opt/anaconda1anaconda2anaconda3/bin/python $DIR/Platypus.py "$@"


text:
<!doctype html>

	<meta charset="UTF-8">
	<title>Chicago Test</title>
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0">
	<meta name="apple-mobile-web-app-capable" content="yes">
	<meta name="apple-mobile-web-app-status-bar-style" content="black">
	<link rel="stylesheet" href="../css/base.css">
	<link rel="stylesheet" href="../css/prism.css">
	<link rel="stylesheet" href="../css/main.css">
	<link rel="stylesheet" href="../../../dist/css/dropdown.css">

Dropdown

Dropdown

UI

Chicago.js Visual Tests

						<legend>Example:</legend>

									<button class="button">Show on Hover</button>

Item

Another item

Header

Item

Another item

Separated item

									<button class="button">Show on Click</button>

Item

Another item

Header

Item

Another item

Separated item

						<legend>Event Console:</legend>


text:
namespace chrono {

void ChPointPointShape::Update(ChPhysicsItem* updater, const ChFrame<>& frame) {
    // Extract two positions from updater if it has any, and then update line geometry from these positions.
    if (auto link_markers = dynamic_cast<ChLinkMarkers*>(updater)) {
        UpdateLineGeometry(frame.TransformPointParentToLocal(link_markers->GetMarker1()->GetAbsCoord().pos),
                           frame.TransformPointParentToLocal(link_markers->GetMarker2()->GetAbsCoord().pos));
    } else if (auto link_dist = dynamic_cast<ChLinkDistance*>(updater)) {
        UpdateLineGeometry(frame.TransformPointParentToLocal(link_dist->GetEndPoint1Abs()),
                           frame.TransformPointParentToLocal(link_dist->GetEndPoint2Abs()));
    } else if (auto link_rs = dynamic_cast<ChLinkRevoluteSpherical*>(updater)) {
        UpdateLineGeometry(frame.TransformPointParentToLocal(link_rs->GetPoint1Abs()),
                           frame.TransformPointParentToLocal(link_rs->GetPoint2Abs()));
    } else if (auto link_tsda = dynamic_cast<ChLinkTSDA*>(updater)) {
        UpdateLineGeometry(frame.TransformPointParentToLocal(link_tsda->GetPoint1Abs()),
                           frame.TransformPointParentToLocal(link_tsda->GetPoint2Abs()));
    } else if (auto link = dynamic_cast<ChLink*>(updater)) {
        UpdateLineGeometry(frame.TransformPointParentToLocal(link->GetBody1()->GetPos()),
                           frame.TransformPointParentToLocal(link->GetBody2()->GetPos()));
    }
}

// Set line geometry as a segment between two end point
void ChSegmentShape::UpdateLineGeometry(const ChVector<>& endpoint1, const ChVector<>& endpoint2) {
    this->SetLineGeometry(std::static_pointer_cast<geometry::ChLine>(
        chrono_types::make_shared<geometry::ChLineSegment>(endpoint1, endpoint2)));
};

// Set line geometry as a coil between two end point
void ChSpringShape::UpdateLineGeometry(const ChVector<>& endpoint1, const ChVector<>& endpoint2) {
    auto linepath = chrono_types::make_shared<geometry::ChLinePath>();

    // Following part was copied from irrlicht::tools::drawSpring()
    ChVector<> dist = endpoint2 - endpoint1;
    ChVector<> Vx, Vy, Vz;
    double length = dist.Length();
    ChVector<> dir = dist.GetNormalized();
    XdirToDxDyDz(dir, VECT_Y, Vx, Vy, Vz);

    ChMatrix33<> rel_matrix(Vx, Vy, Vz);
    ChCoordsys<> mpos(endpoint1, rel_matrix.Get_A_quaternion());

    double phaseA = 0;
    double phaseB = 0;
    double heightA = 0;
    double heightB = 0;

    for (int iu = 1; iu <= resolution; iu++) {
        phaseB = turns * CH_C_2PI * (double)iu / (double)resolution;
        heightB = length * ((double)iu / (double)resolution);
        ChVector<> V1(heightA, radius * cos(phaseA), radius * sin(phaseA));
        ChVector<> V2(heightB, radius * cos(phaseB), radius * sin(phaseB));

        auto segment = geometry::ChLineSegment(mpos.TransformLocalToParent(V1), mpos.TransformLocalToParent(V2));
        linepath->AddSubLine(segment);
        phaseA = phaseB;
        heightA = heightB;
    }

    this->SetLineGeometry(std::static_pointer_cast<geometry::ChLine>(linepath));
}

void ChRotSpringShape::Update(ChPhysicsItem* updater, const ChFrame<>& frame) {
    // Do nothing if not associated with an RSDA.
    auto rsda = dynamic_cast<ChLinkRSDA*>(updater);
    if (!rsda)
        return;

    // The asset frame for an RSDA is the frame on body1.
    auto linepath = chrono_types::make_shared<geometry::ChLinePath>();
    double del_angle = rsda->GetAngle() / m_resolution;
    ChVector<> V1(m_radius, 0, 0);
    for (int iu = 1; iu <= m_resolution; iu++) {
        double crt_angle = iu * del_angle;
        double crt_radius = m_radius - (iu * del_angle / CH_C_2PI) * (m_radius / 10);
        ChVector<> V2(crt_radius * std::cos(crt_angle), crt_radius * std::sin(crt_angle), 0);
        auto segment = geometry::ChLineSegment(V1, V2);
        linepath->AddSubLine(segment);
        V1 = V2;
    }

    this->SetLineGeometry(std::static_pointer_cast<geometry::ChLine>(linepath));
}

}  // end namespace chrono


text:
class Book < ActiveRecord::Base
  validates :title, presence: true
  validates :author, presence: true
  validates :isbn, presence: true

  def to_title
    title
  end
end


text:
namespace weblayer {

WebLayerClientSideDetectionHostDelegate::
    WebLayerClientSideDetectionHostDelegate(content::WebContents* web_contents)
    : web_contents_(web_contents) {}

WebLayerClientSideDetectionHostDelegate::
    ~WebLayerClientSideDetectionHostDelegate() = default;

bool WebLayerClientSideDetectionHostDelegate::
    HasSafeBrowsingUserInteractionObserver() {
  return false;
}

PrefService* WebLayerClientSideDetectionHostDelegate::GetPrefs() {
  BrowserContextImpl* browser_context_impl =
      static_cast<BrowserContextImpl*>(web_contents_->GetBrowserContext());
  DCHECK(browser_context_impl);
  return browser_context_impl->pref_service();
}

scoped_refptr<safe_browsing::SafeBrowsingDatabaseManager>
WebLayerClientSideDetectionHostDelegate::GetSafeBrowsingDBManager() {
  SafeBrowsingService* sb_service =
      BrowserProcess::GetInstance()->GetSafeBrowsingService();
  return sb_service->GetSafeBrowsingDBManager();
}

scoped_refptr<safe_browsing::BaseUIManager>
WebLayerClientSideDetectionHostDelegate::GetSafeBrowsingUIManager() {
  SafeBrowsingService* sb_service =
      BrowserProcess::GetInstance()->GetSafeBrowsingService();
  return sb_service->GetSafeBrowsingUIManager();
}

safe_browsing::ClientSideDetectionService*
WebLayerClientSideDetectionHostDelegate::GetClientSideDetectionService() {
  return ClientSideDetectionServiceFactory::GetForBrowserContext(
      web_contents_->GetBrowserContext());
}

void WebLayerClientSideDetectionHostDelegate::AddReferrerChain(
    safe_browsing::ClientPhishingRequest* verdict,
    GURL current_url) {}

}  // namespace weblayer


text:
package com.savoirtech.hecate.pojo.binding.column;

import java.util.function.Predicate;

import com.datastax.driver.core.DataType;
import com.savoirtech.hecate.pojo.binding.PojoVisitor;
import com.savoirtech.hecate.pojo.convert.Converter;
import com.savoirtech.hecate.pojo.facet.Facet;
import com.savoirtech.hecate.pojo.query.PojoQueryContext;

public abstract class SimpleColumnBinding extends SingleColumnBinding<Object,Object> {
//----------------------------------------------------------------------------------------------------------------------
// Fields
//----------------------------------------------------------------------------------------------------------------------

    private final Converter converter;

//----------------------------------------------------------------------------------------------------------------------
// Constructors
//----------------------------------------------------------------------------------------------------------------------

    public SimpleColumnBinding(Facet facet, String columnName, Converter converter) {
        super(facet, columnName);
        this.converter = converter;
    }

//----------------------------------------------------------------------------------------------------------------------
// Getter/Setter Methods
//----------------------------------------------------------------------------------------------------------------------

    public Converter getConverter() {
        return converter;
    }

//----------------------------------------------------------------------------------------------------------------------
// Other Methods
//----------------------------------------------------------------------------------------------------------------------

    @Override
    public DataType getDataType() {
        return converter.getDataType();
    }

    @Override
    public Object toColumnValue(Object facetValue) {
        return converter.toColumnValue(facetValue);
    }

    @Override
    public Object toFacetValue(Object columnValue, PojoQueryContext context) {
        return converter.toFacetValue(columnValue);
    }

    @Override
    protected void visitFacetChildren(Object facetValue, Predicate<Facet> predicate, PojoVisitor visitor) {
        // Do nothing (no children)!
    }
}


text:
<?php

namespace Tests;

use Anekdotes\FormWrapper\Wrappers\RowExtended;
use PHPUnit\Framework\TestCase;

final class RowExtendedWrapperTest extends TestCase
{
    public function testRowExtendedHandle()
    {
        $wrap = new RowExtended();
        $expected = '
title
input

'."\n";
        $this->assertEquals($wrap->handle('input', 'title'), $expected);
    }
}


text:
/*
 * Copyright 2010 Mario Zechner (contact@badlogicgames.com), Nathan Sweet (admin@esotericsoftware.com)
 *
 * 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.
 */

package com.badlogic.gdx.tests.box2d;

import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.CircleShape;
import com.badlogic.gdx.physics.box2d.EdgeShape;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.physics.box2d.joints.PrismaticJointDef;

public class CollisionFiltering extends Box2DTest {
	private final static short k_smallGroup = 1;
	private final static short k_largeGroup = -1;

	private final static short k_defaultCategory = 0x0001;
	private final static short k_triangleCategory = 0x0002;
	private final static short k_boxCategory = 0x0004;
	private final static short k_circleCategory = 0x0008;

	private final static short k_triangleMask = -1;
	private final static short k_boxMask = -1 ^ k_triangleCategory;
	private final static short k_circleMask = -1;

	@Override
	protected void createWorld (World world) {
		{
			EdgeShape shape = new EdgeShape();
			shape.set(new Vector2(-40.0f, 0), new Vector2(40, 0));

			FixtureDef fd = new FixtureDef();
			fd.shape = shape;
			fd.friction = 0.3f;

			BodyDef bd = new BodyDef();
			Body ground = world.createBody(bd);
			ground.createFixture(fd);
			shape.dispose();
		}

		Vector2[] vertices = new Vector2[3];
		vertices[0] = new Vector2(-1, 0);
		vertices[1] = new Vector2(1, 0);
		vertices[2] = new Vector2(0, 2);
		PolygonShape polygon = new PolygonShape();
		polygon.set(vertices);

		FixtureDef triangleShapeDef = new FixtureDef();
		triangleShapeDef.shape = polygon;
		triangleShapeDef.density = 1.0f;

		triangleShapeDef.filter.groupIndex = k_smallGroup;
		triangleShapeDef.filter.categoryBits = k_triangleCategory;
		triangleShapeDef.filter.maskBits = k_triangleMask;

		BodyDef triangleBodyDef = new BodyDef();
		triangleBodyDef.type = BodyType.DynamicBody;
		triangleBodyDef.position.set(-5, 2);

		Body body1 = world.createBody(triangleBodyDef);
		body1.createFixture(triangleShapeDef);

		vertices[0].scl(2);
		vertices[1].scl(2);
		vertices[2].scl(2);

		polygon.set(vertices);
		triangleShapeDef.filter.groupIndex = k_largeGroup;
		triangleBodyDef.position.set(-5, 6);
		triangleBodyDef.fixedRotation = true;

		Body body2 = world.createBody(triangleBodyDef);
		body2.createFixture(triangleShapeDef);

		{
			BodyDef bd = new BodyDef();
			bd.type = BodyType.DynamicBody;
			bd.position.set(-5, 10);
			Body body = world.createBody(bd);

			PolygonShape p = new PolygonShape();
			p.setAsBox(0.5f, 1.0f);
			body.createFixture(p, 1);

			PrismaticJointDef jd = new PrismaticJointDef();
			jd.bodyA = body2;
			jd.bodyB = body;
			jd.enableLimit = true;
			jd.localAnchorA.set(0, 4);
			jd.localAnchorB.set(0, 0);
			jd.localAxisA.set(0, 1);
			jd.lowerTranslation = -1;
			jd.upperTranslation = 1;

			world.createJoint(jd);

			p.dispose();
		}

		polygon.setAsBox(1, 0.5f);
		FixtureDef boxShapeDef = new FixtureDef();
		boxShapeDef.shape = polygon;
		boxShapeDef.density = 1;
		boxShapeDef.restitution = 0.1f;

		boxShapeDef.filter.groupIndex = k_smallGroup;
		boxShapeDef.filter.categoryBits = k_boxCategory;
		boxShapeDef.filter.maskBits = k_boxMask;

		BodyDef boxBodyDef = new BodyDef();
		boxBodyDef.type = BodyType.DynamicBody;
		boxBodyDef.position.set(0, 2);

		Body body3 = world.createBody(boxBodyDef);
		body3.createFixture(boxShapeDef);

		polygon.setAsBox(2, 1);
		boxShapeDef.filter.groupIndex = k_largeGroup;
		boxBodyDef.position.set(0, 6);

		Body body4 = world.createBody(boxBodyDef);
		body4.createFixture(boxShapeDef);

		CircleShape circle = new CircleShape();
		circle.setRadius(1);

		FixtureDef circleShapeDef = new FixtureDef();
		circleShapeDef.shape = circle;
		circleShapeDef.density = 1.0f;

		circleShapeDef.filter.groupIndex = k_smallGroup;
		circleShapeDef.filter.categoryBits = k_circleCategory;
		circleShapeDef.filter.maskBits = k_circleMask;

		BodyDef circleBodyDef = new BodyDef();
		circleBodyDef.type = BodyType.DynamicBody;
		circleBodyDef.position.set(5, 2);

		Body body5 = world.createBody(circleBodyDef);
		body5.createFixture(circleShapeDef);

		circle.setRadius(2);
		circleShapeDef.filter.groupIndex = k_largeGroup;
		circleBodyDef.position.set(5, 6);

		Body body6 = world.createBody(circleBodyDef);
		body6.createFixture(circleShapeDef);
	}

}


text:
package za.co.tangent.web;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockServletContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import com.fasterxml.jackson.databind.ObjectMapper;

import za.co.tangent.CodeQualityApplication;
import za.co.tangent.domain.File;
import za.co.tangent.service.CodeQualityService;
import za.co.tangent.test.Utilities;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = CodeQualityApplication.class)
@WebAppConfiguration
@ContextConfiguration(classes = MockServletContext.class)
public class CodeQualityControllerTest {

	private MockMvc mockMvc;

	@Mock
	private CodeQualityService codeQualityService;

	@InjectMocks
	CodeQualityController controller;

    @Before
    public void setup() {
    	MockitoAnnotations.initMocks(this);
    	this.mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
    }

	@Test
	public void badRequest() throws Exception {
		this.mockMvc.perform(post("/")).andExpect(status().isBadRequest());
    }

	@Test
	public void successfullRequest() throws Exception {

		String jsonString = Utilities.getFileJSON();

		this.mockMvc.perform(post("/")
				.header("HEADER_buildid", "1")
				.header("HEADER_project", "Some test project")
				.header("HEADER_git_branch", "master")
				.header("Content-Type", MediaType.APPLICATION_JSON)
				.contentType(MediaType.APPLICATION_JSON)
				.content(jsonString)
				.accept(MediaType.APPLICATION_JSON))
				.andExpect(status().is2xxSuccessful());
    }
}


text:
* https://www.linode.com/docs/security/securing-your-server

## ipv6

* https://scottlinux.com/2013/12/09/ipv6-linux-security/


text:
function initial_net()
% INITIAL_NET: Loading VGG-Net-19

global net;
net = load(fullfile('model', 'imagenet-vgg-verydeep-19.mat'));

% Remove the fully connected layers and classification layer
net.layers(37+1:end) = [];

% Switch to GPU mode
global enableGPU;
if enableGPU
    net = vl_simplenn_move(net, 'gpu');
end

net=vl_simplenn_tidy(net);

end


text:
package console

import (
	"bufio"
	"fmt"
	"io"
	"regexp"
	"strings"
	"time"

	"github.com/onsi/ginkgo/v2"

	expect "github.com/google/goexpect"
	"google.golang.org/grpc/codes"

	v1 "kubevirt.io/api/core/v1"
	"kubevirt.io/client-go/kubecli"
	"kubevirt.io/client-go/log"
)

const (
	PromptExpression = `(\$ |\# )`
	CRLF             = "\r\n"
	UTFPosEscape     = "\u001b\\[[0-9]+;[0-9]+H"

	consoleConnectionTimeout = 30 * time.Second
)

var (
	ShellSuccess       = RetValue("0")
	ShellFail          = RetValue("[1-9].*")
	ShellSuccessRegexp = regexp.MustCompile(ShellSuccess)
	ShellFailRegexp    = regexp.MustCompile(ShellFail)
)

// ExpectBatch runs the batch from `expected` connecting to the `vmi` console and
// wait `timeout` for the batch to return.
// NOTE: there is a safer version that validates sended commands `SafeExpectBatch` refer to it about limitations.
func ExpectBatch(vmi *v1.VirtualMachineInstance, expected []expect.Batcher, timeout time.Duration) error {
	virtClient, err := kubecli.GetKubevirtClient()
	if err != nil {
		return err
	}

	expecter, _, err := NewExpecter(virtClient, vmi, consoleConnectionTimeout)
	if err != nil {
		return err
	}
	defer expecter.Close()

	resp, err := expecter.ExpectBatch(expected, timeout)
	if err != nil {
		log.DefaultLogger().Object(vmi).Infof("%v", resp)
	}
	return err
}

// SafeExpectBatch runs the batch from `expected`, connecting to a VMI's console and
// waiting `wait` seconds for the batch to return.
// It validates that the commands arrive to the console.
// NOTE: This functions heritage limitations from `ExpectBatchWithValidatedSend` refer to it to check them.
func SafeExpectBatch(vmi *v1.VirtualMachineInstance, expected []expect.Batcher, wait int) error {
	_, err := SafeExpectBatchWithResponse(vmi, expected, wait)
	return err
}

// SafeExpectBatchWithResponse runs the batch from `expected`, connecting to a VMI's console and
// waiting `wait` seconds for the batch to return with a response.
// It validates that the commands arrive to the console.
// NOTE: This functions inherits limitations from `ExpectBatchWithValidatedSend`, refer to it for more information.
func SafeExpectBatchWithResponse(vmi *v1.VirtualMachineInstance, expected []expect.Batcher, wait int) ([]expect.BatchRes, error) {
	virtClient, err := kubecli.GetKubevirtClient()
	if err != nil {
		panic(err)
	}
	expecter, _, err := NewExpecter(virtClient, vmi, consoleConnectionTimeout)
	if err != nil {
		return nil, err
	}
	defer expecter.Close()

	resp, err := ExpectBatchWithValidatedSend(expecter, expected, time.Second*time.Duration(wait))
	if err != nil {
		log.DefaultLogger().Object(vmi).Infof("%v", resp)
	}
	return resp, err
}

// RunCommand runs the command line from `command` connecting to an already logged in console at vmi
// and waiting `timeout` for command to return.
// NOTE: The safer version `ExpectBatchWithValidatedSend` is not used here since it does not support cases.
func RunCommand(vmi *v1.VirtualMachineInstance, command string, timeout time.Duration) error {
	err := ExpectBatch(vmi, []expect.Batcher{
		&expect.BSnd{S: "\n"},
		&expect.BExp{R: PromptExpression},
		&expect.BSnd{S: command + "\n"},
		&expect.BExp{R: PromptExpression},
		&expect.BSnd{S: "echo $?\n"},
		&expect.BCas{C: []expect.Caser{
			&expect.Case{
				R: ShellSuccessRegexp,
				T: expect.OK(),
			},
			&expect.Case{
				R: ShellFailRegexp,
				T: expect.Fail(expect.NewStatus(codes.Unavailable, command+" failed")),
			},
		}},
	}, timeout)
	if err != nil {
		return fmt.Errorf("failed to run [%s] at VMI %s, error: %v", command, vmi.Name, err)
	}
	return nil
}

// RunCommandAndStoreOutput runs the command line from `command` connecting to an already logged in console in vmi.
// The output of `command` is returned as a string
func RunCommandAndStoreOutput(vmi *v1.VirtualMachineInstance, command string, timeout time.Duration) (string, error) {
	virtClient, err := kubecli.GetKubevirtClient()
	if err != nil {
		return "", err
	}

	opts := &kubecli.SerialConsoleOptions{ConnectionTimeout: timeout}
	stream, err := virtClient.VirtualMachineInstance(vmi.Namespace).SerialConsole(vmi.Name, opts)
	if err != nil {
		return "", err
	}
	conn := stream.AsConn()
	defer conn.Close()

	_, err = fmt.Fprintf(conn, "%s\n", command)
	if err != nil {
		return "", err
	}

	scanner := bufio.NewScanner(conn)
	if !skipInput(scanner) {
		return "", fmt.Errorf("failed to run [%s] at VMI %s (skip input)", command, vmi.Name)
	}
	if !scanner.Scan() {
		return "", fmt.Errorf("failed to run [%s] at VMI %s", command, vmi.Name)
	}
	return scanner.Text(), nil
}

func skipInput(scanner *bufio.Scanner) bool {
	return scanner.Scan()
}

// SecureBootExpecter should be called on a VMI that has EFI enabled
// It will parse the kernel output (dmesg) and succeed if it finds that Secure boot is enabled
// The VMI was just created and may not be running yet. This is because we want to catch early boot logs.
func SecureBootExpecter(vmi *v1.VirtualMachineInstance) error {
	virtClient, err := kubecli.GetKubevirtClient()
	if err != nil {
		return err
	}
	expecter, _, err := NewExpecter(virtClient, vmi, consoleConnectionTimeout)
	if err != nil {
		return err
	}
	defer expecter.Close()

	b := []expect.Batcher{&expect.BExp{R: "secureboot: Secure boot enabled"}}
	const expectBatchTimeout = 180 * time.Second
	res, err := expecter.ExpectBatch(b, expectBatchTimeout)
	if err != nil {
		log.DefaultLogger().Object(vmi).Infof("Kernel: %+v", res)
		return err
	}

	return err
}

// NetBootExpecter should be called on a VMI that has BIOS serial logging enabled
// It will parse the SeaBIOS output and succeed if it finds the string "iPXE"
// The VMI was just created and may not be running yet. This is because we want to catch early boot logs.
func NetBootExpecter(vmi *v1.VirtualMachineInstance) error {
	virtClient, err := kubecli.GetKubevirtClient()
	if err != nil {
		return err
	}
	expecter, _, err := NewExpecter(virtClient, vmi, consoleConnectionTimeout)
	if err != nil {
		return err
	}
	defer expecter.Close()

	esc := UTFPosEscape
	b := []expect.Batcher{
		// SeaBIOS can use escape (\u001b) combinations for letter placement on screen
		// The regex below looks for the string "iPXE" and can detect it
		// even when these escape sequences are present
		&expect.BExp{R: "i(PXE|" + esc + "P" + esc + "X" + esc + "E)"},
	}
	const expectBatchTimeout = 30 * time.Second
	res, err := expecter.ExpectBatch(b, expectBatchTimeout)
	if err != nil {
		log.DefaultLogger().Object(vmi).Infof("BIOS: %+v", res)
		return err
	}

	return err
}

// NewExpecter will connect to an already logged in VMI console and return the generated expecter it will wait `timeout` for the connection.
func NewExpecter(
	virtCli kubecli.KubevirtClient,
	vmi *v1.VirtualMachineInstance,
	timeout time.Duration,
	opts ...expect.Option) (expect.Expecter, <-chan error, error) {
	vmiReader, vmiWriter := io.Pipe()
	expecterReader, expecterWriter := io.Pipe()
	resCh := make(chan error)

	startTime := time.Now()
	serialConsoleOptions := &kubecli.SerialConsoleOptions{ConnectionTimeout: timeout}
	con, err := virtCli.VirtualMachineInstance(vmi.Namespace).SerialConsole(vmi.Name, serialConsoleOptions)
	if err != nil {
		return nil, nil, err
	}
	timeout -= time.Since(startTime)

	go func() {
		resCh <- con.Stream(kubecli.StreamOptions{
			In:  vmiReader,
			Out: expecterWriter,
		})
	}()

	opts = append(opts, expect.SendTimeout(timeout), expect.Verbose(true), expect.VerboseWriter(ginkgo.GinkgoWriter))
	return expect.SpawnGeneric(&expect.GenOptions{
		In:  vmiWriter,
		Out: expecterReader,
		Wait: func() error {
			return <-resCh
		},
		Close: func() error {
			expecterWriter.Close()
			vmiReader.Close()
			return nil
		},
		Check: func() bool { return true },
	}, timeout, opts...)
}

// ExpectBatchWithValidatedSend adds the expect.BSnd command to the exect.BExp expression.
// It is done to make sure the match was found in the result of the expect.BSnd
// command and not in a leftover that wasn't removed from the buffer.
// NOTE: the method contains the following limitations:
//   - Use of `BatchSwitchCase`
//   - Multiline commands
//   - No more than one sequential send or receive
func ExpectBatchWithValidatedSend(expecter expect.Expecter, batch []expect.Batcher, timeout time.Duration) ([]expect.BatchRes, error) {
	sendFlag := false
	expectFlag := false
	previousSend := ""

	const minimumRequiredBatches = 2
	if len(batch) < minimumRequiredBatches {
		return nil, fmt.Errorf("ExpectBatchWithValidatedSend requires at least 2 batchers, supplied %v", batch)
	}

	for i, batcher := range batch {
		switch batcher.Cmd() {
		case expect.BatchExpect:
			if expectFlag {
				return nil, fmt.Errorf("two sequential expect.BExp are not allowed")
			}
			expectFlag = true
			sendFlag = false
			if _, ok := batch[i].(*expect.BExp); !ok {
				return nil, fmt.Errorf("ExpectBatchWithValidatedSend support only expect of type BExp")
			}
			bExp, _ := batch[i].(*expect.BExp)
			previousSend = regexp.QuoteMeta(previousSend)

			// Remove the \n since it is translated by the console to \r\n.
			previousSend = strings.TrimSuffix(previousSend, "\n")
			bExp.R = fmt.Sprintf("%s%s%s", previousSend, "((?s).*)", bExp.R)
		case expect.BatchSend:
			if sendFlag {
				return nil, fmt.Errorf("two sequential expect.BSend are not allowed")
			}
			sendFlag = true
			expectFlag = false
			previousSend = batcher.Arg()
		case expect.BatchSwitchCase:
			return nil, fmt.Errorf("ExpectBatchWithValidatedSend doesn't support BatchSwitchCase")
		default:
			return nil, fmt.Errorf("unknown command: ExpectBatchWithValidatedSend supports only BatchExpect and BatchSend")
		}
	}

	res, err := expecter.ExpectBatch(batch, timeout)
	return res, err
}

func RetValue(retcode string) string {
	return "\n" + retcode + CRLF + ".*" + PromptExpression
}


text:
class ChangeShippingCarrierIdToBigInt < ActiveRecord::Migration[5.1]
  def change
    change_column :shops, :shipping_carrier_id, :integer, limit: 8
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>

<!--
  ~ Copyright 2014 JBoss Inc
  ~
  ~ 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.
  -->

<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui='urn:ui:com.google.gwt.uibinder'
             xmlns:gwt='urn:import:com.google.gwt.user.client.ui'
             xmlns:b="urn:import:org.gwtbootstrap3.client.ui">

  <ui:with field="i18n" type="org.kie.workbench.common.widgets.client.resources.i18n.CommonConstants"/>

  <ui:style>
    .textAlign {
      text-align: center;
    }

    .comment {
      padding-top: 20px;
    }

  </ui:style>

  <b:Container fluid="true" addStyleNames="well">
    <b:Row>
      <b:Heading size="H4" text="{i18n.Comments}" addStyleNames="col-md-12 {style.textAlign}"/>
    </b:Row>
    <b:Row>
      <b:Column size="MD_12">
        <gwt:ScrollPanel ui:field="commentScroll">
          <gwt:VerticalPanel ui:field="lines"/>
        </gwt:ScrollPanel>
      </b:Column>
    </b:Row>
    <b:Row>
      <b:Column size="MD_12" addStyleNames="{style.comment}">
        <b:TextArea ui:field="textBox"/>
      </b:Column>
    </b:Row>
  </b:Container>

</ui:UiBinder>


text:
//
//
//

#pragma once

//
//
//

#include "macros.h"

//
//
//

#if 1

#include <assert.h>

#define SKC_ASSERT_STATE_DECLARE(st)            st state
#define SKC_ASSERT_STATE_MEMBER(sp)             SKC_CONCAT(sp,->state)
#define SKC_ASSERT_STATE_INIT(sp,to)            SKC_ASSERT_STATE_MEMBER(sp) = (to)
#define SKC_ASSERT_STATE_TRANSITION(from,to,sp) assert(SKC_ASSERT_STATE_MEMBER(sp) == (from)); SKC_ASSERT_STATE_INIT(sp,to)
#define SKC_ASSERT_STATE_ASSERT(at,sp)          assert(SKC_ASSERT_STATE_MEMBER(sp) == (at))

#else

#define SKC_ASSERT_STATE_DECLARE(st)
#define SKC_ASSERT_STATE_INIT(sp,to)
#define SKC_ASSERT_STATE_TRANSITION(from,to,sp)
#define SKC_ASSERT_STATE_ASSERT(at,sp)

#endif

//
//
//


text:
<se.par.amsen.shopdesign.gui.view.custom.MainMenuView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="se.par.amsen.shopdesign.MainActivity$PlaceholderFragment" >

</se.par.amsen.shopdesign.gui.view.custom.MainMenuView>


text:
import React, { Component } from 'react';
import { View, Alert, TouchableOpacity, Text, ScrollView } from 'react-native';
import t from 'tcomb-form-native';
import { connect } from 'react-redux';
import { actions as navigationActions } from 'react-native-navigation-redux-helpers';
import { bindActionCreators } from 'redux';
import Icon from 'react-native-vector-icons/MaterialIcons';

import styles from './styles';
import Spinner from '../../components/spiner';
import { validateEmail, validatePassword } from '../../utils/validators';
import formStyles from '../../styles/form-white';
import { COLOR_WHITE } from '../../styles/colors';
import { signUp, signUpSaveForms, cleanErrors } from '../../actions/auth';

const { popRoute } = navigationActions;
const Form = t.form.Form;

const generalFormFields = {
    name: t.String,
    email: validateEmail,
    password: validatePassword,
    confirm_password: validatePassword,
};

const options = {
    stylesheet: formStyles,
    fields: {
        name: {
            error: 'This field is required',
            underlineColorAndroid: COLOR_WHITE,
        },
        email: {
            error: 'This field should be a valid email',
            underlineColorAndroid: COLOR_WHITE,
            keyboardType: 'email-address'
        },
        password: {
            password: true,
            secureTextEntry: true,
            error: 'This field is required',
            placeholder: 'Must have at least 6 characters',
            placeholderTextColor: COLOR_WHITE
        },
        confirm_password: {
            password: true,
            secureTextEntry: true,
            error: 'This field is required',
        },
    }
};

const registerForm = t.struct(generalFormFields);

class Register extends Component {

    static propTypes = {
        actionsSignUpSaveForms: React.PropTypes.func,
        cleanErrors: React.PropTypes.func,
        isFetching: React.PropTypes.bool,
        dispatch: React.PropTypes.func,
        signUp: React.PropTypes.func,
        formData: React.PropTypes.shape(),
        errorCode: React.PropTypes.number,
        errorObject: React.PropTypes.shape({
            non_field_errors: React.PropTypes.arrayOf(React.PropTypes.string)
        }),
    };

    static contextTypes = {
        analytics: React.PropTypes.object
    };

    constructor(props) {
        super(props);
        this.state = {
            formOptions: options,
        };
    }

    componentDidMount() {
        this.context.analytics.trackScreenView('Register');
    }

    componentWillReceiveProps(nextProps) {
        const errorState = {};
        Object.keys(generalFormFields).forEach((item) => {
            errorState[item] = {
                hasError: { $set: false },
                error: { $set: '' }
            };
        });
        if (nextProps.auth.errorObject) {
            Object.keys(nextProps.auth.errorObject).forEach((item) => {
                errorState[item] = {
                    hasError: { $set: true },
                    error: { $set: nextProps.auth.errorObject[item][0] }
                };
            });
        }

        const newFormOptions = t.update(this.state.formOptions, { fields: errorState });
        this.setState({
            formOptions: newFormOptions
        });
    }

    submit = () => {
        this.form.validate();
        const value = this.form.getValue();

        if (value) {
            this.props.actionsSignUpSaveForms(value);
            this.props.signUp(value);
        }
    }

    render() {
        let renderScene;
        if (this.props.isFetching) {
            renderScene = <Spinner/>;
        } else {
            renderScene = (
                <View style={styles.container}>
                    <Icon.ToolbarAndroid style={styles.toolbar}
                                                titleColor={COLOR_WHITE}
                                                navIconName="arrow-back"
                                                onIconClicked={() => { this.props.dispatch(popRoute('global')); }}
                    />
                    <ScrollView>
                        <View style={styles.contentContaier}>
                            <Form ref={(c) => { this.form = c; }}
                                type={registerForm}
                                value={this.props.formData}
                                options={this.state.formOptions}
                            />
                            <TouchableOpacity onPress={() => { this.submit(); }}
                                            style={styles.registerButton}
                            >
                                <Text style={styles.registerButtonTitle}>
                                    Register
                                </Text>
                            </TouchableOpacity>
                        </View>
                    </ScrollView>
                </View>
            );
        }

        if (this.props.errorCode >= 400 && typeof this.props.errorObject.non_field_errors !== 'undefined') {
            Alert.alert('Server Error', this.props.errorObject.non_field_errors[0]);
            this.props.cleanErrors();
        }

        return renderScene;
    }
}

function mapDispatchToProps(dispatch) {
    return {
        dispatch,
        actionsSignUpSaveForms: bindActionCreators(signUpSaveForms, dispatch),
        signUp: bindActionCreators(signUp, dispatch),
        cleanErrors: bindActionCreators(cleanErrors, dispatch)

    };
}

function mapStateToProps(state) {
    return {
        isFetching: state.auth.isAuthenticating,
        formData: state.auth.formData,
        errorCode: state.auth.errorCode,
        errorObject: state.auth.errorObject,
        navigation: state.globalNavigation,
        auth: state.auth,
    };
}

export default connect(mapStateToProps, mapDispatchToProps)(Register);


text:
package gov.nasa.worldwind.applications.gio.ebrim;

/**
 * @author dcollins
 * @version $Id$
 */
public interface LocalizedString
{
    String getLang();

    void setLang(String lang);

    String getCharset();

    void setCharset(String charset);

    String getValue();

    void setValue(String value);
}


text:
package com.fitpay.android.api.models.card;

import com.fitpay.android.api.models.apdu.ApduCommand;

import java.util.List;

/**
 * SE action
 */
public class SeAction {
    private List<ApduCommand> apduCommands;

    public List<ApduCommand> getApduCommands(){
        return apduCommands;
    }
}


text:
[![Known Vulnerabilities](https://snyk.io/test/github/ra100/sails-social-feed/badge.svg)](https://snyk.io/test/github/ra100/sails-social-feed)

[Sails](http://sailsjs.org) application to collect messages from social networks and publish to more social streams.

Used technologies:
- nodejs
- sails
- react
- react-bootstrap
- react-router
- passport
- babel
- es6
- ...

## How to start
- install sailsjs and other global modules

```shell
npm install -g sails babel-cli bower grunt-cli
gem install sass
```

- install local modules

```shell
npm install
bower install
```

- lift sails

```shell
sails lift
```

- or create `local.js` script:

For debuging create bash script where you set local env variables:

```shell
#!/bin/bash

export BASE_URL='https://mygreatapp.com'
export APP_NAME='socialFeed'
export PORT=1338
export ADMIN_NAME='admin'
export ADMIN_PASSWORD='nbusr123'
export ADMIN_EMAIL='admin@mygreatapp.com'
export TWITTER_CONSUMER_KEY='TWITTER_CONSUMER_KEY'
export TWITTER_CONSUMER_SECRET='TWITTER_CONSUMER_SECRET'
export FACEBOOK_APP_ID='FACEBOOK_APP_ID'
export FACEBOOK_APP_SECRET='FACEBOOK_APP_SECRET'
export FACEBOOK_API_VERSION='2.6'
export JWT_SECRET='RANDOMSTRING'
export S3_KEY=''
export S3_SECRET=''
export S3_BUCKET=''
export S3_ROOT=''
export S3_REGION=''
export NODE_ENV=development
export STREAMS=true

sails lift --verbose
```

### Setup SSL

Setup on server, etc nginx <https://www.sitepoint.com/configuring-nginx-ssl-node-js/>

### Set persistent sessions between restarts

In `local.js`, e.g. use redis

```js
  session: {
    adapter: 'redis',
    host: 'localhost',
    port: 6379,
    db: 0,
    prefix: 'sess:',
  }

  sockets: {
    adapter: 'socket.io-redis',
    host: 'localhost',
    port: 6379,
    db: 1,
    prefix: 'socket:',
  },
```

More info on `local.js` file in  [sailsjs.org documentation](http://sailsjs.org/#!/documentation/anatomy/myApp/config/local.js.html).

## Production

Copy `process.default.yml` to `process.yml`, configure env variables and star via pm2.

```shell
pm2 start process.yml
```

## What works
- [x] administration
  - [x] users
  - [x] streams
  - [x] groups
  - [x] feeds

- [x] twitter Streaming API
  - [x] listening for users and hashtags


text:
When using the pretty error page feature, whoops comes with the ability to
open referenced files directly in your IDE or editor.
This feature only works in case your php-source files are locally accessible to the machine on which the editor is installed.

```php
<?php

use Whoops\Handler\PrettyPageHandler;

$handler = new PrettyPageHandler;
$handler->setEditor('sublime');
```

The following editors are currently supported by default.

- `emacs`    - Emacs
- `idea`     - IDEA
- `macvim`   - MacVim
- `phpstorm` - PhpStorm
- `sublime`  - Sublime Text 2 and possibly 3 (on OS X you might need [a special handler](https://github.com/dhoulb/subl))
- `textmate` - Textmate
- `xdebug`   - xdebug (uses [xdebug.file_link_format](http://xdebug.org/docs/all_settings#file_link_format))

Adding your own editor is simple:

```php

$handler->setEditor(function($file, $line) {
    return "whatever://open?file=$file&line=$line";
});

```

You can add [IntelliJ Platform](https://github.com/pinepain/PhpStormOpener#phpstormopener) support like this:
```php

$handler->setEditor(
    function ($file, $line) {
        // if your development server is not local it's good to map remote files to local
        $translations = array('^' . __DIR__ => '~/Development/PhpStormOpener'); // change to your path

        foreach ($translations as $from => $to) {
            $file = preg_replace('#' . $from . '#', $to, $file, 1);
        }

        // Intellig platform requires that you send an Ajax request, else the browser will quit the page
        return array(
            'url' => "http://localhost:63342/api/file/?file=$file&line=$line",
            'ajax' => true
        );
    }
);

```


text:
static void class_swizzleSelector(Class class, SEL originalSelector, SEL newSelector)
{
    Method origMethod = class_getInstanceMethod(class, originalSelector);
    Method newMethod = class_getInstanceMethod(class, newSelector);
    if(class_addMethod(class, originalSelector, method_getImplementation(newMethod), method_getTypeEncoding(newMethod))) {
        class_replaceMethod(class, newSelector, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
    } else {
        method_exchangeImplementations(origMethod, newMethod);
    }
}

@implementation AVSpeechSynthesizer (Hacks)

+ (void)load
{
    class_swizzleSelector([AVSpeechSynthesizer class], @selector(speakUtterance:), @selector(__hacksSpeakUtterance:));
}

- (void)__hacksSpeakUtterance:(AVSpeechUtterance *)utterance
{
    utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"en-US"];
    [self __hacksSpeakUtterance:utterance];
}

@end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>plugin_mmasgis: mmasgis::mysql_sqlalchemy_class::rel_pv_par Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css"/>

plugin_mmasgis

Main Page

Namespaces

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

mmasgis

mysql_sqlalchemy_class

rel_pv_par

Static Public Attributes |
Static Private Attributes

mmasgis::mysql_sqlalchemy_class::rel_pv_par Class Reference

List of all members.

Static Public Attributes

tuple 	ins_data = Column(DateTime)

tuple 	ins_utente = Column(Integer)

tuple 	mod_data = Column(DateTime)

tuple 	mod_utente = Column(Integer)

tuple 	pv_id = Column(Integer, primary_key=True)

tuple 	tc_clpar_id = Column(Integer)

tuple 	tc_par_id = Column(Integer, primary_key=True)

Static Private Attributes

string 	__tablename__ = 'rel_pv_par'

Member Data Documentation

          string mmasgis::mysql_sqlalchemy_class::rel_pv_par::__tablename__ = 'rel_pv_par' [static, private]

          tuple mmasgis::mysql_sqlalchemy_class::rel_pv_par::ins_data = Column(DateTime) [static]

          tuple mmasgis::mysql_sqlalchemy_class::rel_pv_par::ins_utente = Column(Integer) [static]

          tuple mmasgis::mysql_sqlalchemy_class::rel_pv_par::mod_data = Column(DateTime) [static]

          tuple mmasgis::mysql_sqlalchemy_class::rel_pv_par::mod_utente = Column(Integer) [static]

          tuple mmasgis::mysql_sqlalchemy_class::rel_pv_par::pv_id = Column(Integer, primary_key=True) [static]

          tuple mmasgis::mysql_sqlalchemy_class::rel_pv_par::tc_clpar_id = Column(Integer) [static]

          tuple mmasgis::mysql_sqlalchemy_class::rel_pv_par::tc_par_id = Column(Integer, primary_key=True) [static]

The documentation for this class was generated from the following file:

mysql_sqlalchemy_class.py

 All Classes Namespaces Files Functions Variables

<address class="footer">Generated on Tue Apr 17 2012 16:46:03 for plugin_mmasgis by

 1.7.3 </address>


text: Webpa Website


text:
package com.example.android.sunshine.app;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.ShareActionProvider;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.android.sunshine.app.data.WeatherContract;
import com.example.android.sunshine.app.data.WeatherContract.WeatherEntry;
import com.example.android.sunshine.app.sync.SunshineSyncAdapter;

/**
 * A placeholder fragment containing a simple view.
 */
public class DetailFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {

    private static final String LOG_TAG = DetailFragment.class.getSimpleName();

    private static final String FORECAST_SHARE_HASHTAG = " #SunshineApp";

    private static final String LOCATION_KEY = "location";

    private ShareActionProvider mShareActionProvider;
    private String mLocation;
    private String mForecast;
    private String mDateStr;

    private static final int DETAIL_LOADER = 0;

    private static final String[] FORECAST_COLUMNS = {
            WeatherEntry.TABLE_NAME + "." + WeatherEntry._ID,
            WeatherEntry.COLUMN_DATETEXT,
            WeatherEntry.COLUMN_SHORT_DESC,
            WeatherEntry.COLUMN_MAX_TEMP,
            WeatherEntry.COLUMN_MIN_TEMP,
            WeatherEntry.COLUMN_HUMIDITY,
            WeatherEntry.COLUMN_PRESSURE,
            WeatherEntry.COLUMN_WIND_SPEED,
            WeatherEntry.COLUMN_DEGREES,
            WeatherEntry.COLUMN_WEATHER_ID,
            // This works because the WeatherProvider returns location data joined with
            // weather data, even though they're stored in two different tables.
            WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING
    };

    private ImageView mIconView;
    private TextView mFriendlyDateView;
    private TextView mDateView;
    private TextView mDescriptionView;
    private TextView mHighTempView;
    private TextView mLowTempView;
    private TextView mHumidityView;
    private TextView mWindView;
    private TextView mPressureView;

    public DetailFragment() {
        setHasOptionsMenu(true);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putString(LOCATION_KEY, mLocation);
        super.onSaveInstanceState(outState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        Bundle arguments = getArguments();
        if (arguments != null) {
            mDateStr = arguments.getString(DetailActivity.DATE_KEY);
        }

        if (savedInstanceState != null) {
            mLocation = savedInstanceState.getString(LOCATION_KEY);
        }

        View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
        mIconView = (ImageView) rootView.findViewById(R.id.detail_icon);
        mDateView = (TextView) rootView.findViewById(R.id.detail_date_textview);
        mFriendlyDateView = (TextView) rootView.findViewById(R.id.detail_day_textview);
        mDescriptionView = (TextView) rootView.findViewById(R.id.detail_forecast_textview);
        mHighTempView = (TextView) rootView.findViewById(R.id.detail_high_textview);
        mLowTempView = (TextView) rootView.findViewById(R.id.detail_low_textview);
        mHumidityView = (TextView) rootView.findViewById(R.id.detail_humidity_textview);
        mWindView = (TextView) rootView.findViewById(R.id.detail_wind_textview);
        mPressureView = (TextView) rootView.findViewById(R.id.detail_pressure_textview);
        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        Bundle arguments = getArguments();
        if (arguments != null && arguments.containsKey(DetailActivity.DATE_KEY) &&
                mLocation != null &&
                !mLocation.equals(Utility.getPreferredLocation(getActivity()))) {
            getLoaderManager().restartLoader(DETAIL_LOADER, null, this);
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // Inflate the menu; this adds items to the action bar if it is present.
        inflater.inflate(R.menu.detailfragment, menu);

        // Retrieve the share menu item
        MenuItem menuItem = menu.findItem(R.id.action_share);

        // Get the provider and hold onto it to set/change the share intent.
        mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);

        // If onLoadFinished happens before this, we can go ahead and set the share intent now.
        if (mForecast != null) {
            mShareActionProvider.setShareIntent(createShareForecastIntent());
        }
    }

    private Intent createShareForecastIntent() {
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
        shareIntent.setType("text/plain");
        shareIntent.putExtra(Intent.EXTRA_TEXT, mForecast + FORECAST_SHARE_HASHTAG);
        return shareIntent;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (savedInstanceState != null) {
            mLocation = savedInstanceState.getString(LOCATION_KEY);
        }

        Bundle arguments = getArguments();
        if (arguments != null && arguments.containsKey(DetailActivity.DATE_KEY)) {
            getLoaderManager().initLoader(DETAIL_LOADER, null, this);
        }
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        // Sort order:  Ascending, by date.
        String sortOrder = WeatherContract.WeatherEntry.COLUMN_DATETEXT + " ASC";

        if (Utility.getPreferredLocationGPSEnabled(getActivity())){
            mLocation = SunshineSyncAdapter.cityPostCode;
        }else {
            mLocation = Utility.getPreferredLocation(getActivity());
        }

        Uri weatherForLocationUri = WeatherContract.WeatherEntry.buildWeatherLocationWithDate(
                mLocation, mDateStr);

        // Now create and return a CursorLoader that will take care of
        // creating a Cursor for the data being displayed.
        return new CursorLoader(
                getActivity(),
                weatherForLocationUri,
                FORECAST_COLUMNS,
                null,
                null,
                sortOrder
        );
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        if (data != null && data.moveToFirst()) {
            // Read weather condition ID from cursor
            int weatherId = data.getInt(data.getColumnIndex(WeatherEntry.COLUMN_WEATHER_ID));
            // Use weather art image
            mIconView.setImageResource(Utility.getArtResourceForWeatherCondition(weatherId));

            // Read date from cursor and update views for day of week and date
            String date = data.getString(data.getColumnIndex(WeatherEntry.COLUMN_DATETEXT));
            String friendlyDateText = Utility.getDayName(getActivity(), date);
            String dateText = Utility.getFormattedMonthDay(getActivity(), date);
            mFriendlyDateView.setText(friendlyDateText);
            mDateView.setText(dateText);

            // Read description from cursor and update view
            String description = data.getString(data.getColumnIndex(
                    WeatherEntry.COLUMN_SHORT_DESC));
            mDescriptionView.setText(description);

            // For accessibility, add a content description to the icon field
            mIconView.setContentDescription(description);

            // Read high temperature from cursor and update view
            boolean isMetric = Utility.isMetric(getActivity());

            double high = data.getDouble(data.getColumnIndex(WeatherEntry.COLUMN_MAX_TEMP));
            String highString = Utility.formatTemperature(getActivity(), high);
            mHighTempView.setText(highString);

            // Read low temperature from cursor and update view
            double low = data.getDouble(data.getColumnIndex(WeatherEntry.COLUMN_MIN_TEMP));
            String lowString = Utility.formatTemperature(getActivity(), low);
            mLowTempView.setText(lowString);

            // Read humidity from cursor and update view
            float humidity = data.getFloat(data.getColumnIndex(WeatherEntry.COLUMN_HUMIDITY));
            mHumidityView.setText(getActivity().getString(R.string.format_humidity, humidity));

            // Read wind speed and direction from cursor and update view
            float windSpeedStr = data.getFloat(data.getColumnIndex(WeatherEntry.COLUMN_WIND_SPEED));
            float windDirStr = data.getFloat(data.getColumnIndex(WeatherEntry.COLUMN_DEGREES));
            mWindView.setText(Utility.getFormattedWind(getActivity(), windSpeedStr, windDirStr));

            // Read pressure from cursor and update view
            float pressure = data.getFloat(data.getColumnIndex(WeatherEntry.COLUMN_PRESSURE));
            mPressureView.setText(getActivity().getString(R.string.format_pressure, pressure));

            // We still need this for the share intent
            mForecast = String.format("%s - %s - %s/%s", dateText, description, high, low);

            // If onCreateOptionsMenu has already happened, we need to update the share intent now.
            if (mShareActionProvider != null) {
                mShareActionProvider.setShareIntent(createShareForecastIntent());
            }
        }
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) { }
}


text:
import icons from './icons'

const extensions = {
    gif: icons.image,
    jpeg: icons.image,
    jpg: icons.image,
    png: icons.image,

    pdf: icons.pdf,

    doc: icons.word,
    docx: icons.word,

    ppt: icons.powerpoint,
    pptx: icons.powerpoint,

    xls: icons.excel,
    xlsx: icons.excel,

    csv: icons.csv,

    aac: icons.audio,
    mp3: icons.audio,
    ogg: icons.audio,

    avi: icons.video,
    flv: icons.video,
    mkv: icons.video,
    mp4: icons.video,

    gz: icons.archive,
    zip: icons.archive,

    css: icons.code,
    html: icons.code,
    js: icons.code,

    txt: icons.text
}

export default extensions


text:
package org.apache.hadoop.yarn.server.nodemanager.timelineservice;

import org.apache.hadoop.yarn.event.AbstractEvent;

/**
 * Event posted to NMTimelinePublisher which in turn publishes it to
 * timelineservice v2.
 */
public class NMTimelineEvent extends AbstractEvent<NMTimelineEventType> {
  public NMTimelineEvent(NMTimelineEventType type) {
    super(type);
  }

  public NMTimelineEvent(NMTimelineEventType type, long timestamp) {
    super(type, timestamp);
  }
}


text:
var assert = require('assert');
var http = require('http');
var path = require('path');
var decache = require('decache');
var useragent = require('useragent');
var familyMapping = {
  canary: 'chrome',
  chromium: process.platform === 'darwin' ? 'chrome' : 'chromium',
  phantom: 'phantomjs',
  nodeWebkit: 'chrome'
};
var server = http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(6785);

describe('Local browser launcher tests', function() {

  describe('Default env settings', function () {

    var local = require('../lib/local');

    it('does local browser and version discovery', function (done) {
      local(function (error, launcher) {
        launcher.browsers(function (error, browsers) {
          assert.ok(!error, 'No error discovering browsers');
          assert.ok(browsers.length, 'Found at least one browser');
          assert.ok(browsers[0].version, 'First browser has a version');
          assert.ok(browsers[0].path, 'First browser has a path');
          assert.ok(browsers[0].binPath, 'First browser has a binPath');
          done();
        });
      });
    });

    Object.keys(local.platform).forEach(function (name) {
      it('Launches ' + name + ' browser on ' + process.platform, function (done) {
        local(function (error, launcher) {
          launcher[name]('http://localhost:6785', function (error, instance) {
            if (error) {
              // That's the only error we should get
              assert.equal(error.message, 'Browser ' + name + ' not available.');
              return done();
            }

            server.once('request', function (req) {
              var userAgent = useragent.parse(req.headers['user-agent']);
              var expected = familyMapping[name] || name;

              assert.equal(userAgent.family.toLowerCase(), expected, 'Got expected browser family');
              instance.stop(done);
            });
          });
        });
      });
    });
  });

  describe('Custom env settings', function () {

    decache(path.join(__dirname, '..', 'lib', 'local', 'index.js'));

    process.env.LAUNCHPAD_BROWSERS = 'phantom';
    process.env.LAUNCHPAD_PHANTOM = /^win/.test(process.platform) ?
        path.join(__dirname, '..', 'node_modules', 'phantomjs', 'lib', 'phantom', 'phantomjs.exe') :
        path.join(__dirname, '..', 'node_modules', 'phantomjs', 'bin', 'phantomjs');

    var local = require('../lib/local');

    it('detects PhantomJS only due to env settings', function (done) {
      local(function (error, launcher) {
        launcher.browsers(function (error, browsers) {
          assert.ok(!error, 'No error discovering browsers');
          assert.ok(browsers.length == 1, 'Found PhantomJS browser');
          assert.ok(browsers[0].path == process.env.LAUNCHPAD_PHANTOM, 'Found PhantomJS at selected location');
          done();
        });
      });
    });
  });
});


text:
using System;

using Hydra.Framework;
using Hydra.Framework.Helpers;
using Hydra.Framework.Extensions;
using Hydra.Framework.Geometric;
using Hydra.Framework.Pipeline.Segments;
using Hydra.Framework.Pipeline.Visitors;

namespace Hydra.Framework.Pipeline
{
    /// <summary>
    /// Inserts a segment into the pipeline as an inline filter
    /// </summary>
    public class InterceptionBinder :
        AbstractPipeVisitor
    {
        private readonly Type _messageType;
        private readonly Func<Pipe, Pipe> _buildSegment;
        private bool _found;

        public InterceptionBinder(Type messageType, Func<Pipe,Pipe> buildSegment)
        {
            _messageType = messageType;
            _buildSegment = buildSegment;
        }

        public void Bind(Pipe pipe)
        {
            base.Visit(pipe);
        }

        protected override Pipe VisitInput(InputSegment input)
        {
            if (input == null)
                return null;

            var output = input.Output;
            if (output.MessageType == _messageType && !_found)
            {
                _found = true;

                Pipe newOutput = _buildSegment(Visit(output));

                input.ReplaceOutput(output, newOutput);

                return input;
            }

            Pipe pipe = Visit(output);
            if (pipe != output)
            {
                input.ReplaceOutput(output, pipe);
            }

            return input;
        }
    }
}


text:
class CreateOccurences < ActiveRecord::Migration
  def self.up
    create_table :occurences do |t|
      t.integer :error_id
      t.string :name
      t.text :description
      t.text :backtrace
      t.text :properties

      t.timestamps
    end
  end

  def self.down
    drop_table :occurences
  end
end


text:
require "spec_helper"

describe Lita::User, lita: true do
  describe ".create" do
    it "creates and returns new users" do
      user = described_class.create(1, name: "Carl")
      expect(user.id).to eq("1")
      expect(user.name).to eq("Carl")
      persisted_user = described_class.find_by_id(1)
      expect(user).to eq(persisted_user)
    end

    it "returns existing users" do
      described_class.create(1, name: "Carl")
      user = described_class.find_by_id(1)
      expect(user.id).to eq("1")
      expect(user.name).to eq("Carl")
    end

    it "merges and saves new metadata for existing users" do
      described_class.create(1, name: "Carl")
      described_class.create(1, name: "Mr. Carl", foo: "bar")
      user = described_class.find_by_id(1)
      expect(user.name).to eq("Mr. Carl")
      expect(user.metadata["foo"]).to eq("bar")
    end
  end

  describe ".find_by_id" do
    it "finds users with no metadata stored" do
      described_class.create(1)
      user = described_class.find_by_id(1)
      expect(user.id).to eq("1")
    end
  end

  describe ".find_by_mention_name" do
    it "returns nil if no user matches the provided mention name" do
      expect(described_class.find_by_mention_name("carlthepug")).to be_nil
    end

    it "returns a user that matches the provided mention name" do
      described_class.create(1, mention_name: "carlthepug")
      user = described_class.find_by_mention_name("carlthepug")
      expect(user.id).to eq("1")
    end
  end

  describe ".find_by_name" do
    it "returns nil if no user matches the provided name" do
      expect(described_class.find_by_name("Carl")).to be_nil
    end

    it "returns existing users" do
      described_class.create(1, name: "Carl")
      user = described_class.find_by_name("Carl")
      expect(user.id).to eq("1")
    end
  end

  describe ".find_by_partial_name" do
    before { described_class.create(1, name: "José Vicente Cuadra") }

    it "finds users by partial name match" do
      user = described_class.find_by_partial_name("José")
      expect(user.id).to eq("1")
    end

    it "returns nil if no users' names start with the provided string" do
      expect(described_class.find_by_partial_name("Foo")).to be_nil
    end

    it "returns nil if more than one match was found" do
      described_class.create(2, name: "José Contreras")
      expect(described_class.find_by_partial_name("José")).to be_nil
    end
  end

  describe ".fuzzy_find" do
    let!(:user) { described_class.create(1, name: "Carl the Pug", mention_name: "carlthepug") }

    it "finds by ID" do
      expect(described_class.fuzzy_find(1)).to eq(user)
    end

    it "finds by mention name" do
      expect(described_class.fuzzy_find("carlthepug")).to eq(user)
    end

    it "finds by name" do
      expect(described_class.fuzzy_find("Carl the Pug")).to eq(user)
    end

    it "finds by partial mention name" do
      expect(described_class.fuzzy_find("Carl")).to eq(user)
    end
  end

  describe "#mention_name" do
    it "returns the user's mention name from metadata" do
      subject = described_class.new(1, name: "Carl", mention_name: "carlthepug")
      expect(subject.mention_name).to eq("carlthepug")
    end

    it "returns the user's name if there is no mention name in the metadata" do
      subject = described_class.new(1, name: "Carl")
      expect(subject.mention_name).to eq("Carl")
    end
  end

  describe "#save" do
    subject { described_class.new(1, name: "Carl", mention_name: "carlthepug") }

    it "saves an ID to name mapping for the user in Redis" do
      subject.save
      expect(described_class.redis.hgetall("id:1")).to include("name" => "Carl")
    end

    it "saves a name to ID mapping for the user in Redis" do
      subject.save
      expect(described_class.redis.get("name:Carl")).to eq("1")
    end

    it "saves a mention name to ID mapping for the user in Redis" do
      subject.save
      expect(described_class.redis.get("mention_name:carlthepug")).to eq("1")
    end

    context "when a key is deleted" do
      before do
        subject.metadata["example"] = "hello"
        subject.save
        expect(described_class.redis.hkeys("id:1")).to include("example")
        subject.metadata.delete("example")
        subject.save
      end

      it "deletes that key from redis" do
        expect(described_class.redis.hkeys("id:1")).not_to include("example")
      end
    end
  end

  describe "equality" do
    it "considers two users equal if they share an ID and name" do
      user1 = described_class.new(1, name: "Carl")
      user2 = described_class.new(1, name: "Carl")
      expect(user1).to eq(user2)
      expect(user1).to eql(user2)
    end

    it "doesn't assume the comparison object is a Lita::User" do
      user = described_class.new(1, name: "Carl")
      expect(user).not_to eq("not a Lita::User object")
      expect(user).not_to eql("not a Lita::User object")
    end

    it "consistently hashes equal users" do
      user1 = described_class.new(1, name: "Carl")
      user2 = described_class.new(1, name: "Carl")

      expect(user1.hash).to eq(user2.hash)
    end
  end
end


text:
        <title>Login</title>

Login to Your Account

Already a member? Sign in using the form below.

The e-mail address and/or password entered do not match our records.  Please try again

            <blc:form th:action="@{/login_post.htm}" method="post">
                <input type="hidden" name="successUrl" th:if="${successUrl}" th:value="${successUrl}"/>

                    Email
                    <input type="email" name="j_username" th:class="${param.error} ? 'field50 fieldError' : 'field50'" />

                    Password
                    <input type="password" name="j_password" th:class="${param.error} ? 'field50 fieldError' : 'field50'" />

                    <input class="login_button big red" type="submit" th:value="#{login.login}"/>

                    Register

                    Forgot Password

            </blc:form>