text:
InputManager::InputManager()
{
	m_bAltDown = false;
	m_bLeftButtonDown = false;
	m_bRightButtonDown = false;
	m_bMiddleButtonDown = false;
	m_bSideButton1Down = false;
	m_bSideButton2Down = false;
	m_iMouseWheelDelta = 0;
	m_ixPos = 0;
	m_iyPos = 0;

	m_bLRButtonHold = false;
	m_ixPosPrevious = 0;
	m_iyPosPrevious = 0;
}

InputManager* InputManager::Instance()
{
	static InputManager instance;
	return &instance;

}

InputManager::~InputManager()

{

}

void InputManager::Initialise(FontManager* Fmanager, CameraManager* CManager,
							  CollisionManager* CollManager)
{
	m_pFmanager = Fmanager;
	m_pCmanager = CManager;
	m_pCollmanager = CollManager;

}

void InputManager::CatchKeyboardDown(UINT nChar, bool bKeyDown, bool bAltDown)
{
	D3DXVECTOR3 viewvector = m_pCmanager->GetViewVector(); //use the x->z and z_x relationship
	viewvector.y = 0;
	D3DXVec3Normalize(&viewvector, &viewvector);
	float XRotation = ((1 * viewvector.z) / 10);
	float ZRotation = -((1 * viewvector.x) / 10);

	//convert to switch when got time
	if ((nChar == 0x26) && m_pCmanager->OrbitAboveCheck()) //up arrow
	{
		Quaternion Qrotation = Quaternion(XRotation, 0, ZRotation);
		m_pCmanager->SetCameraPosition(Qrotation.RotationV3(m_pCmanager->GetCameraPosition()));
	}
	if ((nChar == 0x28) && m_pCmanager->OrbitBelowCheck())//down arrow
	{
		Quaternion Qrotation = Quaternion(-XRotation, 0, -ZRotation);
		m_pCmanager->SetCameraPosition(Qrotation.RotationV3(m_pCmanager->GetCameraPosition()));
	}
	if (nChar == 0x25)//left arrow
	{
		Quaternion Qrotation = Quaternion(0.0f, 0.05f, 0.0f);
		m_pCmanager->SetCameraPosition(Qrotation.RotationV3(m_pCmanager->GetCameraPosition()));
	}
	if (nChar == 0x27)//right arrow
	{
		Quaternion Qrotation = Quaternion(0.0f, -0.05f, 0.0f);
		m_pCmanager->SetCameraPosition(Qrotation.RotationV3(m_pCmanager->GetCameraPosition()));
	}
	m_bAltDown = bAltDown;
	m_pFmanager->update(nChar);
}

void InputManager::CatchMouse ( bool bLeftButtonDown, bool bRightButtonDown, bool bMiddleButtonDown,
							    bool bSideButton1Down, bool bSideButton2Down, int nMouseWheelDelta,
							    int xPos, int yPos )
{
	//Colour Fonts
	m_bLeftButtonDown = bLeftButtonDown;
	if(m_bLeftButtonDown){m_pFmanager->SetcMouseButtonL(Green);} else {m_pFmanager->SetcMouseButtonL(Red);}
	m_bRightButtonDown = bRightButtonDown;
	if(bRightButtonDown){m_pFmanager->SetcMouseButtonR(Green);} else {m_pFmanager->SetcMouseButtonR(Red);}
	//Save mouse history
	m_bMiddleButtonDown = bMiddleButtonDown;
	m_bSideButton1Down = bSideButton1Down;
	m_bSideButton2Down = bSideButton2Down;
	m_iMouseWheelDelta = nMouseWheelDelta;
	//save coords and update font
	m_ixPos = xPos;
	m_pFmanager->SetMouseXwchar(xPos);
	m_iyPos = yPos;
	m_pFmanager->SetMouseYwchar(yPos);

	//Considered using update call to effect input events but choose direct methods for now

	//Method calls here
	MouseWheel();
	MouseButtons ();

}

void InputManager::MouseWheel ()
{
	//ZoomInput
	D3DXVECTOR3 eyeNormal;
	if (m_iMouseWheelDelta < 0)
	{
		m_pCmanager->ZoomIn();
	}
	if (m_iMouseWheelDelta > 0)
	{
		m_pCmanager->ZoomOut();
	}
}

void InputManager::MouseButtons ()
{

	//RotationInput
	if (m_bLeftButtonDown && m_bRightButtonDown)//Start rotating
	{
		D3DXVECTOR3 viewvector = m_pCmanager->GetViewVector(); //use the x->z and z_x relationship
		viewvector.y = 0;
		D3DXVec3Normalize(&viewvector, &viewvector);
		float XRotation = (viewvector.z / 100);
		float ZRotation = -(viewvector.x / 100); // Some day I'll realise why this needs to be negative, perhaps due to left handed system
		float YRotation = -0.005;

		float mouseDeltaX = m_ixPos - m_ixPosPrevious;
		float mouseDeltaY = m_iyPos - m_iyPosPrevious;
		XRotation *= -mouseDeltaY;
		ZRotation *= -mouseDeltaY;
		YRotation *= mouseDeltaX;
		Quaternion Qrotation = Quaternion(XRotation, YRotation, ZRotation);
		m_pCmanager->SetCameraPosition(Qrotation.RotationV3(m_pCmanager->GetCameraPosition()));
	}

// 	if (m_bLeftButtonDown && !m_bRightButtonDown)//move deformation point
// 	{
// 		std::list<CustomModel*>::iterator i;
//
// 		for(i=m_lModels->begin(); i != m_lModels->end(); ++i)
// 		{
// 			CustomModel* x = *i;
// 			CollisionResult collisionResult = m_pCollmanager->pointerCollision(m_ixPos, m_iyPos,
// 																		x->GetMesh(), x->GetWorldMatrix());
// 			if (collisionResult.result == TRUE)
// 			{
// 				D3DXVECTOR3 vpos = x->GetFaceVertex(collisionResult.faceCollision);
// 				D3DXVec3TransformCoord(&vpos, &vpos, x->GetWorldMatrix());
// 				D3DXVECTOR4 vpos4 = vpos;
// 				D3DXVECTOR4 offset = (vpos4 - x->GetPosition());
// 				vpos4 += offset;
// 				*m_pForcePosition = vpos4;
//
// 			}
//
// 		};
//
//
// 	}

	//remember previous mouse coords
	m_ixPosPrevious = m_ixPos;
	m_iyPosPrevious = m_iyPos;
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.turnguard.ldp.utils.http.header.impl.value;

import com.turnguard.ldp.utils.http.header.Pair;
import com.turnguard.ldp.utils.http.header.SingleHeaderValue;
import com.turnguard.ldp.utils.http.header.impl.pairs.MaxAge;

/**
 *
 * @author http://www.turnguard.com/turnguard
 */
public class CacheControlValue implements SingleHeaderValue<Pair<Integer>>{

    private MaxAge pair;

    public CacheControlValue(MaxAge pair){
        this.pair = pair;
    }

    public Pair<Integer> getValue() {
        return this.pair;
    }

    public String getStringValue() {
        return this.pair.toString();
    }

}

redpajama_set_name: RedPajamaGithub


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

namespace Project
{
    public partial class Changelog : Form
    {
        public Changelog()
        {
            InitializeComponent();
        }

        private void ok_btn_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void Changelog_Load(object sender, EventArgs e)
        {
            StreamReader reader = new StreamReader("changelog.txt");
            text_txt.Text = reader.ReadToEnd();
            reader.Close();
        }
    }
}


text:
package progress_fixture_test

import (
	. "github.com/chai2010/gopkg/database/leveldb/internal/ginkgo"
	. "github.com/chai2010/gopkg/database/leveldb/internal/gomega"

	"testing"
)

func TestProgressFixture(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "ProgressFixture Suite")
}


text:
package com.dustyneuron.txmarket.schema;

import java.util.ArrayList;
import java.util.List;

import com.dustyneuron.bitprivacy.TransactionSchemaProtos.SinglePartyData;
import com.dustyneuron.bitprivacy.TransactionSchemaProtos.TransactionSchema;

public class Trade {
    final private TransactionSchema schema;
    final private List<SinglePartyData> allPartiesData;

    public Trade(TransactionSchema schema) {
        this(schema, new ArrayList<SinglePartyData>());
    }

    public Trade(TransactionSchema schema, List<SinglePartyData> allPartiesData) {
        this.schema = schema;
        this.allPartiesData = allPartiesData;
    }

    public TransactionSchema getSchema() {
        return schema;
    }

    public List<SinglePartyData> getAllPartiesData() {
        return allPartiesData;
    }
}


text:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <corners
        android:bottomLeftRadius="@dimen/message_bubble_corners_radius"
        android:bottomRightRadius="@dimen/message_bubble_corners_radius"
        android:topLeftRadius="0dp"
        android:topRightRadius="@dimen/message_bubble_corners_radius" />

    <solid android:color="@color/selector_incoming_bubble" />

</shape>


text:
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { MODULE_COMPONENTS, MODULE_ROUTES } from './dashboard.routes';
import {HttpModule} from "@angular/http";
import {BrowserModule} from "@angular/platform-browser";
// import {AlertModule} from "../authentication/alert/alert.module";
import { FormsModule, ReactiveFormsModule } from "@angular/forms";
import { Ng2Bs3ModalModule } from 'ng2-bs3-modal/ng2-bs3-modal';
import {MyDatePickerModule} from "mydatepicker";
import { SwitchComponent } from 'angular2-bootstrap-switch/components';
import { ChartsModule } from 'ng2-charts/ng2-charts';

@NgModule({
    imports: [
      MyDatePickerModule,
        HttpModule,
        BrowserModule,
        // AlertModule,
        ReactiveFormsModule,
        RouterModule.forChild(MODULE_ROUTES),
        Ng2Bs3ModalModule,
      ChartsModule

    ],
    declarations: [  MODULE_COMPONENTS ]
})

export class DashboardModule{}


text:
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Humanizer;

namespace Benchmarking
{
	public class Results
	{
		public string TesterName { get; set; }

		public double RatePerSecond { get; set; }

		public double ElapsedMillisecond { get; set; }

		public int IndexedDocuments { get; set; }

		public IEnumerable<int> EsTimings { get; set; }

		public Metrics Before { get; set; }

		public Metrics After { get; set; }

		public void Write(TextWriter output)
		{
			output.WriteLine("---{0}\t---------------", TesterName);
			output.WriteLine("  {0:0,0} msg/s {1} ms {2} docs", RatePerSecond, ElapsedMillisecond, IndexedDocuments);
			output.WriteLine("  max es-time:{0} mean es-time:{1}", EsTimings.Max(), EsTimings.GetMedian());
			output.WriteLine("  memory before:{0} thread count before:{1}", Before.MemorySize.Bytes(), Before.ThreadCount);
			output.WriteLine("  memory after:{0} thread count after:{1}", After.MemorySize.Bytes(), After.ThreadCount);
		}
	}
}


text:
(function() {
  angular
    .module('weMessageApp')
    .controller('notFoundCtrl', notFoundCtrl);

    notFoundCtrl.$inject = ['$scope', 'constants'];
    function notFoundCtrl($scope, constants) {
      var vm = this;
      vm.pageTitle = 'Page Not Found';
      vm.onClickBack = constants.onClickBack;
      vm.content = {};
      vm.content.header = 'Ahh, now you've done it!';
      vm.content.main = 'Head to the homepage and try again.';
    }
})();


text:
var _ = require('lodash');
var bucker = require('bucker');

module.exports.create = function(options) {
	var logger = null;

	options = _.defaults(options || {}, {
		"handleExceptions": false,
		"console":{
			'color':true
		},
	  "level": "error"
	});

	//due to the way bucker Handles uncaught exceptions we need to overload that option
	//THIS IS A REALLY NASTY HACK, WE SHOULD SUBMIT A PATCH TO BUCKER.
	var buckerOptions = _.clone(options,true);
	buckerOptions.handleExceptions = false;

	// create logger instance
	logger = bucker.createLogger(buckerOptions);

	//TODO::FIND A BETTER WAY TO DO THIS! We should use domains or something
	if(options.handleExceptions) {
		logger.options.handleExceptions = true;
		var exHandler = function(err) {
	  	message = "uncaught exception: " + err.message;
	  	logger.error(message);
		}

		process.on('uncaughtException', exHandler);

		logger.clear = function(){
			process.removeListender('uncaughtException',exHandler);
		}

	}

	logger.clear = function(){};

	return logger;
};


text:
require "spec_helper"

describe OmniAuth::Strategies::Fake do

  let(:app) do
    Rack::Builder.new {
      use OmniAuth::Test::PhonySession
      use OmniAuth::Strategies::Fake, dotfiles: [File.expand_path('../../../omniauth-fake.yml', __FILE__)]
      run lambda { |env| [404, {'Content-Type' => 'text/plain'}, [env.key?('omniauth.auth').to_s]] }
    }.to_app
  end

  context 'client options' do
    subject do
      OmniAuth::Strategies::Fake.new({})
    end

    it { expect(subject.options.dotfiles).to eq([File.join(ENV['HOME'], '.omniauth-fake')]) }
  end

  describe 'get /auth/fake' do
    before(:each) { get '/auth/fake' }

    it 'should display a form' do
      expect(last_response.body).to include('<form')
    end

    it 'should have the callback as the form action' do
      expect(last_response.body).to include(%q{action='/auth/fake/callback'})
    end

    it 'should have the correct title' do
      expect(last_response.body).to include('Identity Selection')
    end

    it 'should have the Identities as options' do
      expect(last_response.body).to include('<option value="user1">user1 - John Doe')
    end
  end # get /auth/fake

  describe 'post /auth/fake/callback' do
    context 'no uid present' do
      it 'should redirect to the error page' do
        post('/auth/fake/callback', {})
        expect(last_response).to be_redirect
        expect(last_response.headers['location']).to match(/missing_credentials/)

        post('/auth/fake/callback', {uid: ''})
        expect(last_response).to be_redirect
        expect(last_response.headers['location']).to match(/missing_credentials/)
      end
    end

    context 'unknown uid present' do
      it 'should redirect to the error page' do
        post('/auth/fake/callback', {uid: "does not exist"})
        expect(last_response).to be_redirect
        expect(last_response.headers['location']).to match(/invalid_credentials/)
      end
    end

    context 'valid uid' do
      let(:auth_hash) { last_request.env['omniauth.auth'] }

      it 'should not redirect to the error page' do
        post('/auth/fake/callback', {uid: "user1"})
        expect(last_response).to_not be_redirect
      end

      it 'should map all user1 info to the Auth Hash' do
        post('/auth/fake/callback', {uid: "user1"})
        expect(auth_hash.provider).to eq('fake')
        expect(auth_hash.uid).to eq('user1')

        expect(auth_hash.info.name).to eq('John Doe')
        expect(auth_hash.info.email).to eq('user1@example.com')

        expect(auth_hash.credentials.token).to eq('my_app_token')
        expect(auth_hash.credentials.secret).to eq('super-secret-token')

        expect(auth_hash.extra.raw_info.uid).to eq('user1')
        expect(auth_hash.extra.raw_info.name).to eq('John Doe')
        expect(auth_hash.extra.raw_info.email).to eq('user1@example.com')
        expect(auth_hash.extra.raw_info.credentials).to eq({
          "token" => 'my_app_token',
          "secret" => 'super-secret-token'
        })
        expect(auth_hash.extra.raw_info.sAMAccountName).to eq('abcuser1')
        expect(auth_hash.extra.raw_info.attribute_x).to eq('Value')
      end

      it 'should map all user1 info to the Auth Hash' do
        post('/auth/fake/callback', {uid: "user2"})
        expect(auth_hash.provider).to eq('fake')
        expect(auth_hash.uid).to eq('user2')

        expect(auth_hash.info.name).to eq('Jane Doe')
        expect(auth_hash.extra.raw_info.uid).to eq('user2')
        expect(auth_hash.extra.raw_info.name).to eq('Jane Doe')
      end
    end

  end # post /auth/fake/callback
end


text:
This middleware is designed to compile LESS on the fly.

[![NPM](https://nodei.co/npm/express-less-middleware.png?downloads=true)](https://nodei.co/npm/express-less-middleware/) [![Greenkeeper badge](https://badges.greenkeeper.io/vernak2539/express-less-middleware.svg)](https://greenkeeper.io/)

### Installing

```js
npm install --save express-less-middleware
```

**Should only be used for development. LESS should be compiled during a build process**

### What this does (per request)

1. Determines if file requested is: (if conditions aren't met it runs `next()`)
   1. requested via GET method
   2. a CSS file
2. Looks for CSS file requested
   - if found it will let it go through the original flow via next
3. Looks for a LESS file with the same name as the CSS file requested
   - if LESS file is found it will read that file and compile it to CSS and deliever the response
4. If no LESS or CSS file is found, it will give you a 404 like usual

### What this doesn't do

1. Look for changes on save (if you use it, you won't need a grunt watch on less files)

### Setup

**lessMiddleware( options )**

- `options`
  - required: no
  - default: `./public` (string)
  - Type: `String` or `Object`
    - `String` - will be path to express public directory.__*__
    - `Object` - [less parser options][1]
      - `options.publicDir` - same value as if `options` were a string. Same default value
      - `options.paths`__*__

\* **paths should be relative to cwd.** `path.join` is used with `process.cwd()` as first argument when processing all paths

### Example

```js
const http = require("http");
const express = require("express");
const app = express();

// this assumes that the publicly available folder is on the same directory level
// as the file that starts your express server
const lessCompiler = require("express-less-middleware")();

// if that's not the case, initialize it with the path to your public/client-side folder
// the path should be relative to the directory where the file that starts your express server is
// Example below.
//
//    const lessCompiler = require( 'express-less-middleware' );
//    lessCompiler     = lessCompiler( '../path/to/public/folder' );
// OR
//    const lessCompiler = require( 'express-less-middleware' );
//    lessCompiler     = lessCompiler({ publicDir: '../path/to/public/folder', ... });

// ....everything else that has to do with configuring

// you should only use this when developing. Not meant for production
if (process.env.NODE_ENV === "dev") {
  // this must be "used" before express.use( express.static() ) or it will not work (no next())
  app.use(lessCompiler);
}

// ....other stuff relative to your express app

http.createServer(app).listen(8000);
```

#### License

MIT

[1]: https://www.npmjs.org/package/less


text:
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools"
  tools:ignore="MissingTranslation">
  <string name="key_enable_namedays">enable_disable_namedays</string>
  <string name="key_version_name">version_name</string>
  <string name="key_contact_dev">contact_dev</string>
  <string name="key_daily_reminder">daily_reminder</string>
  <string name="key_daily_reminder_screen">key_daily_reminder_screen</string>
  <string name="key_daily_reminder_ringtone">key_daily_reminder_ringtone</string>
  <string name="key_daily_reminder_vibrate_enabled">key_daily_reminder_vibrate_enabled</string>
  <string name="key_daily_reminder_time">key_daily_reminder_time</string>
  <string name="key_daily_reminder_hour">key_daily_reminder_hour</string>
  <string name="key_daily_reminder_minute">key_daily_reminder_minute</string>
  <string name="key_translucent_bars">key_translucent_bars</string>
  <string name="key_notification_namedays">key_notification_namedays</string>
  <string name="key_has_played_about_anim">key_has_played_about_anim</string>
  <string name="key_nameday_lang">key_nameday_lang</string>
  <string name="key_namedays_language">key_namedays_language</string>
  <string name="pref_app">pref_app</string>
  <string name="prev_app_version">prev_app_version</string>
  <string name="key_enable_namedays_notification">key_enable_namedays_notification</string>
  <string name="key_namedays_contacts_only">key_namedays_contacts_only</string>
  <string name="key_selected_starting_page">key_selected_starting_page</string>
  <string name="pref_call_to_rate">pref_call_to_rate</string>
  <string name="key_has_user_rated">key_has_user_rated</string>
  <string name="key_rate_previous_time_asked">key_rate_previous_time_asked</string>
  <string name="key_rate_triggered">key_rate_triggered</string>
  <string name="pref_namedays">pref_namedays</string>
  <string name="key_app_theme_id">key_app_theme_id</string>
  <string name="key_daily_reminder_settings">key_daily_reminder_settings</string>
  <string name="pref_upcoming_widget_config">pref_upcoming_widget_config</string>
  <string name="key_upcoming_widget_variant">key_upcoming_widget_variant</string>
  <string name="key_upcoming_widget_opacity">key_upcoming_widget_opacity</string>
  <string name="key_enable_bank_holidays">key_enable_bank_holidays</string>
  <string name="key_bankholidays_language">key_bankholidays_language</string>
  <string name="key_namedays_full_name">key_namedays_full_name</string>
  <string name="key_has_donated">key_has_donated</string>
  <string name="key_donate_restore">key_donate_restore</string>
  <string name="pref_facebook">pref_facebook</string>
  <string name="key_facebook_user_id">key_facebook_user_id</string>
  <string name="key_facebook_user_key">key_facebook_user_key</string>
  <string name="key_facebook_user_name">key_facebook_user_name</string>
  <string name="pref_events">pref_events</string>
  <string name="key_events_are_initialised">key_events_are_initialised</string>
  <string name="key_database_version">key_database_version</string>
  <string name="key_daily_reminder_advanced_settings">key_daily_reminder_advanced_settings</string>

</resources>


text: <link rel="stylesheet" type="text/css" href="/src/templates/pages/tournaments/tournaments.css">


text:
@implementation UIScrollView (TouchesBegan)

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [super touchesBegan:touches withEvent:event];
    if ( !self.dragging )
    {
        [[self nextResponder] touchesBegan:touches withEvent:event];
    }
}

-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    [super touchesEnded:touches withEvent:event];
    if ( !self.dragging )
    {
        [[self nextResponder] touchesEnded:touches withEvent:event];
    }
}

@end


text:
'use strict'

const logger									= require('./../../libs/logger.js'),
			to											= require('./../../libs/to.js'),
			{ errors, validations } = require('./../../libs/errors.js'),
			validator 							= require('express-validator')

const getAll = async function(req, res, next) {
	next()
}

const create = async function(req, res, next) {

	req.checkBody('name', validations.EMPTY).notEmpty()

	req.checkBody('price', validations.EMPTY).notEmpty()
	req.checkBody('price', validations.DECIMAL).isDecimal()
	req.checkBody('price', validations.NEGATIVE).gte(0)

	req.checkBody('stock', validations.EMPTY).notEmpty()
	req.checkBody('stock', validations.INTEGER).isInt()
	req.checkBody('stock', validations.NEGATIVE).gte(0)

	const [err, result] = await to(req.getValidationResult())

	if(err) {
		logger.error(err)
		return res.status(errors.INTERNAL_SERVER.status)
							.json(errors.INTERNAL_SERVER.message)
							.end()
	}

	if(!result.isEmpty()) {
		logger.info(new Error(errors.BAD_REQUEST.message))
		return res.status(errors.BAD_REQUEST.status)
							.json(result.mapped())
							.end()
	}

	next()
}

const buy = async function(req, res, next) {

	req.checkBody('pokemonUUID', validations.EMPTY).notEmpty()
	req.checkBody('pokemonUUID', validations.UUID).isUUID(4)

	req.checkBody('card.number', validations.EMPTY).notEmpty()
	req.checkBody('card.number', validations.CARD).isCreditCard()

	req.checkBody('card.expiration_date', validations.EMPTY).notEmpty()

	req.checkBody('card.holder_name', validations.EMPTY).notEmpty()

	req.checkBody('card.cvv', validations.EMPTY).notEmpty()
	req.checkBody('card.cvv', validations.INTEGER).isInt()

	req.checkBody('quantity', validations.EMPTY).notEmpty()
	req.checkBody('quantity', validations.INTEGER).isInt()
	req.checkBody('quantity', validations.NEGATIVE).gte(0)

	const [err, result] = await to(req.getValidationResult())

	if(err) {
		logger.error(err)
		return res.status(errors.INTERNAL_SERVER.status)
							.json(errors.INTERNAL_SERVER.message)
							.end()
	}

	if(!result.isEmpty()) {
		logger.info(new Error(errors.BAD_REQUEST.message))
		return res.status(errors.BAD_REQUEST.status)
							.json(result.mapped())
							.end()
	}

	next()
}

module.exports = {
	getAll,
	create,
	buy
}


text:
namespace DigitalLibrary.Models
{
    using System;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;

    using DigitalLibrary.Data.Contracts;

    public class Comment : DeletableEntity
    {
        [Key]
        public int Id { get; set; }

        public string Content { get; set; }

        [Editable(false)]
        [Column(TypeName = "DateTime")]
        public DateTime DatePosted { get; set; }

        [Required]
        public string PostedById { get; set; }

        public virtual User PostedBy { get; set; }

        [Required]
        public int WorkId { get; set; }

        public virtual Work Work { get; set; }
    }
}


text:
""" Testing suite for the PyTorch UniSpeech model. """

import math
import unittest

import numpy as np
import pytest
from datasets import load_dataset

from transformers import UniSpeechConfig, is_torch_available
from transformers.testing_utils import require_soundfile, require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import (
    ModelTesterMixin,
    _config_zero_init,
    floats_tensor,
    ids_tensor,
    random_attention_mask,
)

if is_torch_available():
    import torch

    from transformers import (
        UniSpeechForCTC,
        UniSpeechForPreTraining,
        UniSpeechForSequenceClassification,
        UniSpeechModel,
        Wav2Vec2FeatureExtractor,
        Wav2Vec2Processor,
    )

class UniSpeechModelTester:
    def __init__(
        self,
        parent,
        batch_size=13,
        seq_length=1024,  # speech is longer
        is_training=False,
        hidden_size=16,
        feat_extract_norm="group",
        feat_extract_dropout=0.0,
        feat_extract_activation="gelu",
        conv_dim=(32, 32, 32),
        conv_stride=(4, 4, 4),
        conv_kernel=(8, 8, 8),
        conv_bias=False,
        num_conv_pos_embeddings=16,
        num_conv_pos_embedding_groups=2,
        num_hidden_layers=4,
        num_attention_heads=2,
        hidden_dropout_prob=0.1,  # this is most likely not correctly set yet
        intermediate_size=20,
        layer_norm_eps=1e-5,
        hidden_act="gelu",
        initializer_range=0.02,
        vocab_size=32,
        do_stable_layer_norm=False,
        scope=None,
    ):
        self.parent = parent
        self.batch_size = batch_size
        self.seq_length = seq_length
        self.is_training = is_training
        self.hidden_size = hidden_size
        self.feat_extract_norm = feat_extract_norm
        self.feat_extract_dropout = feat_extract_dropout
        self.feat_extract_activation = feat_extract_activation
        self.conv_dim = conv_dim
        self.conv_stride = conv_stride
        self.conv_kernel = conv_kernel
        self.conv_bias = conv_bias
        self.num_conv_pos_embeddings = num_conv_pos_embeddings
        self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups
        self.num_hidden_layers = num_hidden_layers
        self.num_attention_heads = num_attention_heads
        self.hidden_dropout_prob = hidden_dropout_prob
        self.intermediate_size = intermediate_size
        self.layer_norm_eps = layer_norm_eps
        self.hidden_act = hidden_act
        self.initializer_range = initializer_range
        self.vocab_size = vocab_size
        self.do_stable_layer_norm = do_stable_layer_norm
        self.scope = scope

        output_seq_length = self.seq_length
        for kernel, stride in zip(self.conv_kernel, self.conv_stride):
            output_seq_length = (output_seq_length - (kernel - 1)) / stride
        self.output_seq_length = int(math.ceil(output_seq_length))
        self.encoder_seq_length = self.output_seq_length

    def prepare_config_and_inputs(self):
        input_values = floats_tensor([self.batch_size, self.seq_length], scale=1.0)
        attention_mask = random_attention_mask([self.batch_size, self.seq_length])

        config = self.get_config()

        return config, input_values, attention_mask

    def get_config(self):
        return UniSpeechConfig(
            hidden_size=self.hidden_size,
            feat_extract_norm=self.feat_extract_norm,
            feat_extract_dropout=self.feat_extract_dropout,
            feat_extract_activation=self.feat_extract_activation,
            conv_dim=self.conv_dim,
            conv_stride=self.conv_stride,
            conv_kernel=self.conv_kernel,
            conv_bias=self.conv_bias,
            num_conv_pos_embeddings=self.num_conv_pos_embeddings,
            num_conv_pos_embedding_groups=self.num_conv_pos_embedding_groups,
            num_hidden_layers=self.num_hidden_layers,
            num_attention_heads=self.num_attention_heads,
            hidden_dropout_prob=self.hidden_dropout_prob,
            intermediate_size=self.intermediate_size,
            layer_norm_eps=self.layer_norm_eps,
            hidden_act=self.hidden_act,
            initializer_range=self.initializer_range,
            vocab_size=self.vocab_size,
        )

    def create_and_check_model(self, config, input_values, attention_mask):
        model = UniSpeechModel(config=config)
        model.to(torch_device)
        model.eval()
        result = model(input_values, attention_mask=attention_mask)
        self.parent.assertEqual(
            result.last_hidden_state.shape, (self.batch_size, self.output_seq_length, self.hidden_size)
        )

    def create_and_check_batch_inference(self, config, input_values, *args):
        # test does not pass for models making use of `group_norm`
        # check: https://github.com/pytorch/fairseq/issues/3227
        model = UniSpeechModel(config=config)
        model.to(torch_device)
        model.eval()

        input_values = input_values[:3]
        attention_mask = torch.ones(input_values.shape, device=torch_device, dtype=torch.bool)

        input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]]

        # pad input
        for i in range(len(input_lengths)):
            input_values[i, input_lengths[i] :] = 0.0
            attention_mask[i, input_lengths[i] :] = 0.0

        batch_outputs = model(input_values, attention_mask=attention_mask).last_hidden_state

        for i in range(input_values.shape[0]):
            input_slice = input_values[i : i + 1, : input_lengths[i]]
            output = model(input_slice).last_hidden_state

            batch_output = batch_outputs[i : i + 1, : output.shape[1]]
            self.parent.assertTrue(torch.allclose(output, batch_output, atol=1e-3))

    def check_ctc_loss(self, config, input_values, *args):
        model = UniSpeechForCTC(config=config)
        model.to(torch_device)

        # make sure that dropout is disabled
        model.eval()

        input_values = input_values[:3]
        attention_mask = torch.ones(input_values.shape, device=torch_device, dtype=torch.long)

        input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]]
        max_length_labels = model._get_feat_extract_output_lengths(torch.tensor(input_lengths))
        labels = ids_tensor((input_values.shape[0], min(max_length_labels) - 1), model.config.vocab_size)

        # pad input
        for i in range(len(input_lengths)):
            input_values[i, input_lengths[i] :] = 0.0
            attention_mask[i, input_lengths[i] :] = 0

        model.config.ctc_loss_reduction = "sum"
        sum_loss = model(input_values, attention_mask=attention_mask, labels=labels).loss.item()

        model.config.ctc_loss_reduction = "mean"
        mean_loss = model(input_values, attention_mask=attention_mask, labels=labels).loss.item()

        self.parent.assertTrue(isinstance(sum_loss, float))
        self.parent.assertTrue(isinstance(mean_loss, float))

    def check_seq_classifier_loss(self, config, input_values, *args):
        model = UniSpeechForSequenceClassification(config=config)
        model.to(torch_device)

        # make sure that dropout is disabled
        model.eval()

        input_values = input_values[:3]
        attention_mask = torch.ones(input_values.shape, device=torch_device, dtype=torch.long)

        input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]]
        labels = ids_tensor((input_values.shape[0], 1), len(model.config.id2label))

        # pad input
        for i in range(len(input_lengths)):
            input_values[i, input_lengths[i] :] = 0.0
            attention_mask[i, input_lengths[i] :] = 0

        masked_loss = model(input_values, attention_mask=attention_mask, labels=labels).loss.item()
        unmasked_loss = model(input_values, labels=labels).loss.item()

        self.parent.assertTrue(isinstance(masked_loss, float))
        self.parent.assertTrue(isinstance(unmasked_loss, float))
        self.parent.assertTrue(masked_loss != unmasked_loss)

    def check_ctc_training(self, config, input_values, *args):
        config.ctc_zero_infinity = True
        model = UniSpeechForCTC(config=config)
        model.to(torch_device)
        model.train()

        # freeze feature encoder
        model.freeze_feature_encoder()

        input_values = input_values[:3]

        input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]]
        max_length_labels = model._get_feat_extract_output_lengths(torch.tensor(input_lengths))
        labels = ids_tensor((input_values.shape[0], max(max_length_labels) - 2), model.config.vocab_size)

        # pad input
        for i in range(len(input_lengths)):
            input_values[i, input_lengths[i] :] = 0.0

            if max_length_labels[i] < labels.shape[-1]:
                # it's important that we make sure that target lenghts are at least
                # one shorter than logit lenghts to prevent -inf
                labels[i, max_length_labels[i] - 1 :] = -100

        loss = model(input_values, labels=labels).loss
        self.parent.assertFalse(torch.isinf(loss).item())

        loss.backward()

    def check_seq_classifier_training(self, config, input_values, *args):
        config.ctc_zero_infinity = True
        model = UniSpeechForSequenceClassification(config=config)
        model.to(torch_device)
        model.train()

        # freeze everything but the classification head
        model.freeze_base_model()

        input_values = input_values[:3]

        input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]]
        labels = ids_tensor((input_values.shape[0], 1), len(model.config.id2label))

        # pad input
        for i in range(len(input_lengths)):
            input_values[i, input_lengths[i] :] = 0.0

        loss = model(input_values, labels=labels).loss
        self.parent.assertFalse(torch.isinf(loss).item())

        loss.backward()

    def check_labels_out_of_vocab(self, config, input_values, *args):
        model = UniSpeechForCTC(config)
        model.to(torch_device)
        model.train()

        input_values = input_values[:3]

        input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]]
        max_length_labels = model._get_feat_extract_output_lengths(torch.tensor(input_lengths))
        labels = ids_tensor((input_values.shape[0], max(max_length_labels) - 2), model.config.vocab_size + 100)

        with pytest.raises(ValueError):
            model(input_values, labels=labels)

    def prepare_config_and_inputs_for_common(self):
        config, input_values, attention_mask = self.prepare_config_and_inputs()
        inputs_dict = {"input_values": input_values, "attention_mask": attention_mask}
        return config, inputs_dict

@require_torch
class UniSpeechRobustModelTest(ModelTesterMixin, unittest.TestCase):
    all_model_classes = (
        (UniSpeechForCTC, UniSpeechModel, UniSpeechForSequenceClassification, UniSpeechForPreTraining)
        if is_torch_available()
        else ()
    )
    test_pruning = False
    test_headmasking = False

    def setUp(self):
        self.model_tester = UniSpeechModelTester(
            self, conv_stride=(3, 3, 3), feat_extract_norm="layer", do_stable_layer_norm=True
        )
        self.config_tester = ConfigTester(self, config_class=UniSpeechConfig, hidden_size=37)

    def test_config(self):
        self.config_tester.run_common_tests()

    def test_model(self):
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*config_and_inputs)

    def test_batched_inference(self):
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_batch_inference(*config_and_inputs)

    def test_ctc_loss_inference(self):
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
        self.model_tester.check_ctc_loss(*config_and_inputs)

    def test_seq_classifier_loss_inference(self):
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
        self.model_tester.check_seq_classifier_loss(*config_and_inputs)

    def test_ctc_train(self):
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
        self.model_tester.check_ctc_training(*config_and_inputs)

    def test_seq_classifier_train(self):
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
        self.model_tester.check_seq_classifier_training(*config_and_inputs)

    def test_labels_out_of_vocab(self):
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
        self.model_tester.check_labels_out_of_vocab(*config_and_inputs)

    # UniSpeech has no inputs_embeds
    def test_inputs_embeds(self):
        pass

    # `input_ids` is renamed to `input_values`
    def test_forward_signature(self):
        pass

    # UniSpeech cannot resize token embeddings
    # since it has no tokens embeddings
    def test_resize_tokens_embeddings(self):
        pass

    # UniSpeech has no inputs_embeds
    # and thus the `get_input_embeddings` fn
    # is not implemented
    def test_model_common_attributes(self):
        pass

    def test_retain_grad_hidden_states_attentions(self):
        config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
        config.output_hidden_states = True
        config.output_attentions = True

        # no need to test all models as different heads yield the same functionality
        model_class = self.all_model_classes[0]
        model = model_class(config)
        model.to(torch_device)

        # set layer drop to 0
        model.config.layerdrop = 0.0

        input_values = inputs_dict["input_values"]

        input_lengths = torch.tensor(
            [input_values.shape[1] for _ in range(input_values.shape[0])], dtype=torch.long, device=torch_device
        )
        output_lengths = model._get_feat_extract_output_lengths(input_lengths)

        labels = ids_tensor((input_values.shape[0], output_lengths[0] - 2), self.model_tester.vocab_size)
        inputs_dict["attention_mask"] = torch.ones_like(inputs_dict["attention_mask"])
        inputs_dict["labels"] = labels

        outputs = model(**inputs_dict)

        output = outputs[0]

        # Encoder-/Decoder-only models
        hidden_states = outputs.hidden_states[0]
        attentions = outputs.attentions[0]

        hidden_states.retain_grad()
        attentions.retain_grad()

        output.flatten()[0].backward(retain_graph=True)

        self.assertIsNotNone(hidden_states.grad)
        self.assertIsNotNone(attentions.grad)

    def test_initialization(self):
        config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()

        configs_no_init = _config_zero_init(config)
        for model_class in self.all_model_classes:
            model = model_class(config=configs_no_init)
            for name, param in model.named_parameters():
                uniform_init_parms = [
                    "conv.weight",
                    "masked_spec_embed",
                    "codevectors",
                    "quantizer.weight_proj.weight",
                    "project_hid.weight",
                    "project_hid.bias",
                    "project_q.weight",
                    "project_q.bias",
                    "feature_projection.projection.weight",
                    "feature_projection.projection.bias",
                ]
                if param.requires_grad:
                    if any([x in name for x in uniform_init_parms]):
                        self.assertTrue(
                            -1.0 <= ((param.data.mean() * 1e9).round() / 1e9).item() <= 1.0,
                            msg=f"Parameter {name} of model {model_class} seems not properly initialized",
                        )
                    else:
                        self.assertIn(
                            ((param.data.mean() * 1e9).round() / 1e9).item(),
                            [0.0, 1.0],
                            msg=f"Parameter {name} of model {model_class} seems not properly initialized",
                        )

    # overwrite from test_modeling_common
    def _mock_init_weights(self, module):
        if hasattr(module, "weight") and module.weight is not None:
            module.weight.data.fill_(3)
        if hasattr(module, "weight_g") and module.weight_g is not None:
            module.weight_g.data.fill_(3)
        if hasattr(module, "weight_v") and module.weight_v is not None:
            module.weight_v.data.fill_(3)
        if hasattr(module, "bias") and module.bias is not None:
            module.bias.data.fill_(3)
        if hasattr(module, "codevectors") and module.codevectors is not None:
            module.codevectors.data.fill_(3)
        if hasattr(module, "masked_spec_embed") and module.masked_spec_embed is not None:
            module.masked_spec_embed.data.fill_(3)

    def test_mask_feature_prob_ctc(self):
        model = UniSpeechForCTC.from_pretrained(
            "hf-internal-testing/tiny-random-unispeech", mask_feature_prob=0.2, mask_feature_length=2
        )
        model.to(torch_device).train()
        processor = Wav2Vec2Processor.from_pretrained(
            "hf-internal-testing/tiny-random-unispeech", return_attention_mask=True
        )

        batch_duration_in_seconds = [1, 3, 2, 6]
        input_features = [np.random.random(16_000 * s) for s in batch_duration_in_seconds]

        batch = processor(
            input_features, padding=True, sampling_rate=processor.feature_extractor.sampling_rate, return_tensors="pt"
        )

        logits = model(
            input_values=batch["input_values"].to(torch_device),
            attention_mask=batch["attention_mask"].to(torch_device),
        ).logits

        self.assertEqual(logits.shape, (4, 1498, 32))

    def test_mask_time_prob_ctc(self):
        model = UniSpeechForCTC.from_pretrained(
            "hf-internal-testing/tiny-random-unispeech", mask_time_prob=0.2, mask_time_length=2
        )
        model.to(torch_device).train()
        processor = Wav2Vec2Processor.from_pretrained(
            "hf-internal-testing/tiny-random-unispeech", return_attention_mask=True
        )

        batch_duration_in_seconds = [1, 3, 2, 6]
        input_features = [np.random.random(16_000 * s) for s in batch_duration_in_seconds]

        batch = processor(
            input_features, padding=True, sampling_rate=processor.feature_extractor.sampling_rate, return_tensors="pt"
        )

        logits = model(
            input_values=batch["input_values"].to(torch_device),
            attention_mask=batch["attention_mask"].to(torch_device),
        ).logits

        self.assertEqual(logits.shape, (4, 1498, 32))

    def test_mask_time_feature_prob_ctc_single_batch(self):
        model = UniSpeechForCTC.from_pretrained(
            "hf-internal-testing/tiny-random-unispeech",
            mask_time_prob=0.2,
            mask_feature_prob=0.2,
            mask_time_length=2,
            mask_feature_length=2,
        )
        model.to(torch_device).train()
        processor = Wav2Vec2Processor.from_pretrained(
            "hf-internal-testing/tiny-random-unispeech", return_attention_mask=True
        )

        batch_duration_in_seconds = [6]
        input_features = [np.random.random(16_000 * s) for s in batch_duration_in_seconds]

        batch = processor(
            input_features, padding=True, sampling_rate=processor.feature_extractor.sampling_rate, return_tensors="pt"
        )

        logits = model(
            input_values=batch["input_values"].to(torch_device),
            attention_mask=batch["attention_mask"].to(torch_device),
        ).logits

        self.assertEqual(logits.shape, (1, 1498, 32))

    @unittest.skip(reason="Feed forward chunking is not implemented")
    def test_feed_forward_chunking(self):
        pass

    @slow
    def test_model_from_pretrained(self):
        model = UniSpeechModel.from_pretrained("microsoft/unispeech-large-1500h-cv")
        self.assertIsNotNone(model)

@require_torch
@require_soundfile
@slow
class UniSpeechModelIntegrationTest(unittest.TestCase):
    def _load_datasamples(self, num_samples):
        ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
        # automatic decoding with librispeech
        speech_samples = ds.sort("id").filter(
            lambda x: x["id"] in [f"1272-141231-000{i}" for i in range(num_samples)]
        )[:num_samples]["audio"]

        return [x["array"] for x in speech_samples]

    def _load_superb(self, task, num_samples):

        ds = load_dataset("anton-l/superb_dummy", task, split="test")

        return ds[:num_samples]

    def test_inference_pretraining(self):
        model = UniSpeechForPreTraining.from_pretrained("microsoft/unispeech-large-1500h-cv")
        model.to(torch_device)
        feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained("facebook/wav2vec2-large-xlsr-53")
        input_speech = self._load_datasamples(2)

        inputs_dict = feature_extractor(input_speech, return_tensors="pt", padding=True)

        with torch.no_grad():
            torch.manual_seed(0)
            outputs = model(
                inputs_dict.input_values.to(torch_device),
                attention_mask=inputs_dict.attention_mask.to(torch_device),
            )

        # compute cosine similarity
        cosine_sim = torch.cosine_similarity(outputs.projected_states, outputs.projected_quantized_states, dim=-1)

        # pretrained model should have learned a high cosine similarity
        self.assertTrue(cosine_sim.mean() > 0.5)

        # fmt: off
        expected_cosine_sim_slice = torch.tensor(
            [[0.8290, 0.8335, 0.8815, 0.8580, 0.8249],
             [0.8892, 0.9221, 0.8711, 0.8601, 0.8482]],
            device=torch_device,
        )
        # fmt: on

        self.assertTrue(torch.allclose(cosine_sim[:, :5], expected_cosine_sim_slice, atol=1e-3))


text:
const passportService = require('./services/passport');
const Authentication = require('./controllers/authentication');
const passport = require('passport');

const requireAuth = passport.authenticate('jwt', { session: false });
const requireSignin = passport.authenticate('local', { session: false });

module.exports = function (app) {
    /*
    app.get('/', requireAuth, function (req, res) {
        res.send({message: 'Super secret code is ABC123' });
    });
    app.post('/signin', requireSignin, Authentication.signin);
    app.post('/signup', Authentication.signup);
*/
}


text:
namespace _GUI_
{

// --- _BaseControl ---

class _BaseControl
{
public:
   virtual bool checkHandle(void* param) const = 0;

   virtual ~_BaseControl() {}
};

// --- Control ---

class Control : public _BaseControl
{
protected:
   HINSTANCE _instance;
   HWND      _handle;

   int       _left;
   int       _top;
   size_t    _width;
   size_t    _height;

   size_t    _minWidth;
   size_t    _minHeight;

public:
   virtual bool checkHandle(void* param) const
   {
      return (_handle == (HWND)param);
   }

   HWND getToolTipHandle()
   {
      return TabCtrl_GetToolTips(_handle);
   }

   HWND getHandle() const { return _handle; }
   HINSTANCE _getInstance() const { return _instance; }

   virtual bool isVisible();

   virtual int getLeft() const { return _left; }
   virtual int getTop() const { return _top; }
   virtual size_t getWidth() const { return _width; }
   virtual size_t getHeight() const { return _height; }
   virtual Rectangle getRectangle();

   virtual void _setCoordinate(int x, int y);
   virtual void _setConstraint(int minWidth, int minHeight);
   virtual void _setWidth(size_t width);
   virtual void _setHeight(size_t height);

   virtual void setFocus();
   virtual void show();
   virtual void hide();
   virtual void refresh();

   virtual void _resize();

   virtual void _onDrawItem(DRAWITEMSTRUCT* item) {}

   void _notify(HWND receptor, int code);
   void _notify(HWND receptor,   int code, int extParam);

   Control(int left, int top, size_t width, size_t height);
   virtual ~Control() {}
};

// --- Window ---

class Window : public Control
{
protected:
   virtual LRESULT _WindProc(HWND hWnd, size_t Message, WPARAM wParam, LPARAM lParam);

   virtual bool onClose();
   virtual void onResize() {}
   virtual bool _onSetCursor() { return false; }
   virtual void onSetFocus() {}
   virtual void onLoseFocus() {}

   void _setCursor(int type);

public:
   void setCaption(const wchar_t* caption);

   static void _registerClass(HINSTANCE hInstance, const wchar_t* name, size_t style, HCURSOR cursor = NULL,
                             HBRUSH background = NULL, HICON icon = NULL, wchar_t* menu = NULL);

   static LRESULT CALLBACK _Proc(HWND hWnd, size_t Message, WPARAM wParam, LPARAM lParam);

   Window(int left, int top, size_t width, size_t height)
      : Control(left, top, width, height)
   {
   }
};

// --- Clipboard ---

class Clipboard
{
public:
   static bool isAvailable();

   bool begin(Window* window)
   {
      return open(window->getHandle());
   }

   void end()
   {
      close();
   }

   bool open(HWND id);
   HGLOBAL create(int size);
   wchar_t* allocate(HGLOBAL buffer);
   void free(HGLOBAL buffer);
   void copy(HGLOBAL buffer);
   int getSize(HGLOBAL buffer);
   HGLOBAL get();

   void clear();
   void close();
};

// --- DateTime ---

struct DateTime
{
private:
   SYSTEMTIME _time;

public:
   static DateTime getFileTime(const wchar_t* path);

   bool operator > (const DateTime dt) const
   {
      if (_time.wYear > dt._time.wYear)
         return true;

      if (_time.wYear==dt._time.wYear) {
         if (_time.wMonth > dt._time.wMonth)
            return true;

         if (_time.wMonth==dt._time.wMonth) {
            if (_time.wDay > dt._time.wDay)
               return true;

            if (_time.wDay==dt._time.wDay) {
               if (_time.wHour > dt._time.wHour)
                  return true;

               if (_time.wHour==dt._time.wHour) {
                  if (_time.wMinute > dt._time.wMinute)
                     return true;

                  if (_time.wMinute==dt._time.wMinute) {
                     if (_time.wSecond > dt._time.wSecond)
                        return true;

                     if (_time.wSecond==dt._time.wSecond) {
                        return (_time.wMilliseconds > dt._time.wMilliseconds);
                     }
                  }
               }
            }
         }
      }
      return false;
   }

   DateTime()
   {
      _time.wYear = 0;
      //memset(&_time, 0, sizeof(_time));
   }
};

// --- misc functions ---

inline bool isPathRelative(const wchar_t* path)
{
   return (::PathIsRelative(path) == TRUE);
}

inline void canonicalize(_ELENA_::Path& path)
{
   wchar_t p[MAX_PATH];

   ::PathCanonicalize(p, path);

   path.copy(p);
}

inline void makePathRelative(_ELENA_::Path& path, const wchar_t* rootPath)
{
   wchar_t tmpPath[MAX_PATH];

   ::PathRelativePathTo(tmpPath, rootPath, FILE_ATTRIBUTE_DIRECTORY, path, FILE_ATTRIBUTE_NORMAL);
   if (!_ELENA_::emptystr(tmpPath)) {
      if (_ELENA_::StringHelper::compare(tmpPath, _T(".\\"), 2)) {
         path.copy(tmpPath + 2);
      }
      else path.copy(tmpPath);
   }
}

// --- ExtNMHDR ---

struct ExtNMHDR
{
   NMHDR nmhrd;
   int   extParam;
};

// --- ContextMenuNMHDR ---

struct ContextMenuNMHDR
{
   NMHDR nmhrd;
   int   x, y;
};

// --- MessageNMHDR ---

struct MessageNMHDR
{
   NMHDR        nmhrd;
   const wchar_t* message;
   int          param;
};

struct Message2NMHDR
{
   NMHDR        nmhrd;
   const wchar_t* message;
   int          param1;
   int          param2;
};

struct Message3NMHDR
{
   NMHDR          nmhrd;
   const wchar_t* message;
   const wchar_t* param;
};

// --- LineInfoNMHDR ---

struct LineInfoNMHDR
{
   NMHDR             nmhrd;
   const wchar_t*    ns;
   const wchar_t*    file;
   HighlightInfo     position;
};

} // _GUI_

#endif // wincommonH


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".AddProductActivity">

    <LinearLayout
        android:id="@+id/add_product_form"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="25dp">

            <EditText
                android:id="@+id/product_name_input"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/prompt_product_name"
                android:inputType="textAutoCorrect"
                android:maxLines="1"
                android:singleLine="true" />

        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/product_description"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/prompt_product_description"
                android:inputType="textAutoCorrect|textMultiLine"
                android:lines="2"
                android:maxLines="4" />

        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/product_starting_price"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/prompt_product_starting_price"
                android:inputType="numberDecimal"
                android:maxLines="1"
                android:singleLine="true" />

        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/product_final_price"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/prompt_product_final_price"
                android:inputType="numberDecimal"
                android:maxLines="1"
                android:singleLine="false" />

        </android.support.design.widget.TextInputLayout>

        <LinearLayout
            android:id="@+id/LinearLayout02"
            android:layout_height="wrap_content"
            android:layout_width="fill_parent"
            android:layout_alignParentBottom="true">

            <TextView
                android:id="@+id/image_select_text"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/prompt_add_image"
                android:layout_gravity="center_vertical"
                style="?android:textAppearanceLarge">

            </TextView>

            <Button
                android:id="@+id/select_image"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:layout_gravity="center_vertical"
                android:text="@string/prompt_add_image_select">
            </Button>
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <Button
                android:id="@+id/action_add_product"
                style="?android:textAppearanceSmall"
                android:layout_weight="1"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="16dp"
                android:text="@string/action_add_product"
                android:textStyle="bold" />

        </LinearLayout>

    </LinearLayout>

</RelativeLayout>


text:
/**
 * This barrel file provides the exports for the shared resources (services, components).
 */
export * from './topnav/index';
export * from './sidebar/index';

export * from './name-list/index';

export * from './config/env.config';


text:
<!DOCTYPE html>

Layer tree appears here in DRT.


text:
amqp-tee
========

Work In Progress
----------------
API is unstable.

[![Build Status](https://travis-ci.org/modcloth-labs/amqp-tee.png?branch=master)](https://travis-ci.org/modcloth-labs/amqp-tee) [![Godoc](http://img.shields.io/badge/godoc-reference-blue.svg?style=flat)](https://godoc.org/github.com/modcloth-labs/amqp-tee)

AMQP consumer which will consume all messages from a given queue and insert
them into a configurable database with a static schema (you can see the schema
in `delivery_store.go`). Currently it only stores the properties and body of
the message, but not any headers.

## Usage

Run `amqp-tee -h` for a listing of flags.

## Development

Requires SQLite3 header files to be present for testing.

Requires gosqlite package for testing (`go get -v code.google.com/p/gosqlite/sqlite3`)

Test via `go test github.com/modcloth-labs/amqptee`.


text:
BEGIN;

SELECT *
   INTO TABLE xacttest
   FROM aggtest;

INSERT INTO xacttest (a, b) VALUES (777, 777.777);

END;

-- should retrieve one value--
SELECT a FROM xacttest WHERE a > 100;

BEGIN;

CREATE TABLE disappear (a int4);

DELETE FROM aggtest;

-- should be empty
SELECT * FROM aggtest;

ABORT;

-- should not exist
SELECT oid FROM pg_class WHERE relname = 'disappear';

-- should have members again
SELECT * FROM aggtest;

-- Read-only tests

CREATE TABLE writetest (a int);
CREATE TEMPORARY TABLE temptest (a int);

SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY;

DROP TABLE writetest; -- fail
INSERT INTO writetest VALUES (1); -- fail
SELECT * FROM writetest; -- ok
DELETE FROM temptest; -- ok
UPDATE temptest SET a = 0 FROM writetest WHERE temptest.a = 1 AND writetest.a = temptest.a; -- ok
PREPARE test AS UPDATE writetest SET a = 0; -- ok
EXECUTE test; -- fail
SELECT * FROM writetest, temptest; -- ok
CREATE TABLE test AS SELECT * FROM writetest; -- fail

START TRANSACTION READ WRITE;
DROP TABLE writetest; -- ok
COMMIT;

-- Subtransactions, basic tests
-- create & drop tables
SET SESSION CHARACTERISTICS AS TRANSACTION READ WRITE;
CREATE TABLE foobar (a int);
BEGIN;
	CREATE TABLE foo (a int);
	SAVEPOINT one;
		DROP TABLE foo;
		CREATE TABLE bar (a int);
	ROLLBACK TO SAVEPOINT one;
	RELEASE SAVEPOINT one;
	SAVEPOINT two;
		CREATE TABLE baz (a int);
	RELEASE SAVEPOINT two;
	drop TABLE foobar;
	CREATE TABLE barbaz (a int);
COMMIT;
-- should exist: barbaz, baz, foo
SELECT * FROM foo;		-- should be empty
SELECT * FROM bar;		-- shouldn't exist
SELECT * FROM barbaz;	-- should be empty
SELECT * FROM baz;		-- should be empty

-- inserts
BEGIN;
	INSERT INTO foo VALUES (1);
	SAVEPOINT one;
		INSERT into bar VALUES (1);
	ROLLBACK TO one;
	RELEASE SAVEPOINT one;
	SAVEPOINT two;
		INSERT into barbaz VALUES (1);
	RELEASE two;
	SAVEPOINT three;
		SAVEPOINT four;
			INSERT INTO foo VALUES (2);
		RELEASE SAVEPOINT four;
	ROLLBACK TO SAVEPOINT three;
	RELEASE SAVEPOINT three;
	INSERT INTO foo VALUES (3);
COMMIT;
SELECT * FROM foo;		-- should have 1 and 3
SELECT * FROM barbaz;	-- should have 1

-- test whole-tree commit
BEGIN;
	SAVEPOINT one;
		SELECT foo;
	ROLLBACK TO SAVEPOINT one;
	RELEASE SAVEPOINT one;
	SAVEPOINT two;
		CREATE TABLE savepoints (a int);
		SAVEPOINT three;
			INSERT INTO savepoints VALUES (1);
			SAVEPOINT four;
				INSERT INTO savepoints VALUES (2);
				SAVEPOINT five;
					INSERT INTO savepoints VALUES (3);
				ROLLBACK TO SAVEPOINT five;
COMMIT;
COMMIT;		-- should not be in a transaction block
SELECT * FROM savepoints;

-- test whole-tree rollback
BEGIN;
	SAVEPOINT one;
		DELETE FROM savepoints WHERE a=1;
	RELEASE SAVEPOINT one;
	SAVEPOINT two;
		DELETE FROM savepoints WHERE a=1;
		SAVEPOINT three;
			DELETE FROM savepoints WHERE a=2;
ROLLBACK;
COMMIT;		-- should not be in a transaction block

SELECT * FROM savepoints;

-- test whole-tree commit on an aborted subtransaction
BEGIN;
	INSERT INTO savepoints VALUES (4);
	SAVEPOINT one;
		INSERT INTO savepoints VALUES (5);
		SELECT foo;
COMMIT;
SELECT * FROM savepoints;

BEGIN;
	INSERT INTO savepoints VALUES (6);
	SAVEPOINT one;
		INSERT INTO savepoints VALUES (7);
	RELEASE SAVEPOINT one;
	INSERT INTO savepoints VALUES (8);
COMMIT;
-- rows 6 and 8 should have been created by the same xact
SELECT a.xmin = b.xmin FROM savepoints a, savepoints b WHERE a.a=6 AND b.a=8;
-- rows 6 and 7 should have been created by different xacts
SELECT a.xmin = b.xmin FROM savepoints a, savepoints b WHERE a.a=6 AND b.a=7;

BEGIN;
	INSERT INTO savepoints VALUES (9);
	SAVEPOINT one;
		INSERT INTO savepoints VALUES (10);
	ROLLBACK TO SAVEPOINT one;
		INSERT INTO savepoints VALUES (11);
COMMIT;
SELECT a FROM savepoints WHERE a in (9, 10, 11);
-- rows 9 and 11 should have been created by different xacts
SELECT a.xmin = b.xmin FROM savepoints a, savepoints b WHERE a.a=9 AND b.a=11;

BEGIN;
	INSERT INTO savepoints VALUES (12);
	SAVEPOINT one;
		INSERT INTO savepoints VALUES (13);
		SAVEPOINT two;
			INSERT INTO savepoints VALUES (14);
	ROLLBACK TO SAVEPOINT one;
		INSERT INTO savepoints VALUES (15);
		SAVEPOINT two;
			INSERT INTO savepoints VALUES (16);
			SAVEPOINT three;
				INSERT INTO savepoints VALUES (17);
COMMIT;
SELECT a FROM savepoints WHERE a BETWEEN 12 AND 17;

BEGIN;
	INSERT INTO savepoints VALUES (18);
	SAVEPOINT one;
		INSERT INTO savepoints VALUES (19);
		SAVEPOINT two;
			INSERT INTO savepoints VALUES (20);
	ROLLBACK TO SAVEPOINT one;
		INSERT INTO savepoints VALUES (21);
	ROLLBACK TO SAVEPOINT one;
		INSERT INTO savepoints VALUES (22);
COMMIT;
SELECT a FROM savepoints WHERE a BETWEEN 18 AND 22;

DROP TABLE savepoints;

-- only in a transaction block:
SAVEPOINT one;
ROLLBACK TO SAVEPOINT one;
RELEASE SAVEPOINT one;

-- Only "rollback to" allowed in aborted state
BEGIN;
  SAVEPOINT one;
  SELECT 0/0;
  SAVEPOINT two;    -- ignored till the end of ...
  RELEASE SAVEPOINT one;      -- ignored till the end of ...
  ROLLBACK TO SAVEPOINT one;
  SELECT 1;
COMMIT;
SELECT 1;			-- this should work

-- check non-transactional behavior of cursors
BEGIN;
	DECLARE c CURSOR FOR SELECT unique2 FROM tenk1 ORDER BY unique2;
	SAVEPOINT one;
		FETCH 10 FROM c;
	ROLLBACK TO SAVEPOINT one;
		FETCH 10 FROM c;
	RELEASE SAVEPOINT one;
	FETCH 10 FROM c;
	CLOSE c;
	DECLARE c CURSOR FOR SELECT unique2/0 FROM tenk1 ORDER BY unique2;
	SAVEPOINT two;
		FETCH 10 FROM c;
	ROLLBACK TO SAVEPOINT two;
	-- c is now dead to the world ...
		FETCH 10 FROM c;
	ROLLBACK TO SAVEPOINT two;
	RELEASE SAVEPOINT two;
	FETCH 10 FROM c;
COMMIT;

--
-- Check that "stable" functions are really stable.  They should not be
-- able to see the partial results of the calling query.  (Ideally we would
-- also check that they don't see commits of concurrent transactions, but
-- that's a mite hard to do within the limitations of pg_regress.)
--
select * from xacttest;

create or replace function max_xacttest() returns smallint language sql as
'select max(a) from xacttest' stable READS SQL DATA;

begin;
update xacttest set a = max_xacttest() + 10 where a > 0;
select * from xacttest;
rollback;

-- But a volatile function can see the partial results of the calling query
create or replace function max_xacttest() returns smallint language sql as
'select max(a) from xacttest' volatile READS SQL DATA;

begin;
update xacttest set a = max_xacttest() + 10 where a > 0;
select * from xacttest;
rollback;

-- Now the same test with plpgsql (since it depends on SPI which is different)
create or replace function max_xacttest() returns smallint language plpgsql as
'begin return max(a) from xacttest; end' stable READS SQL DATA;

begin;
update xacttest set a = max_xacttest() + 10 where a > 0;
select * from xacttest;
rollback;

create or replace function max_xacttest() returns smallint language plpgsql as
'begin return max(a) from xacttest; end' volatile READS SQL DATA;

begin;
update xacttest set a = max_xacttest() + 10 where a > 0;
select * from xacttest;
rollback;

-- test case for problems with dropping an open relation during abort
BEGIN;
	savepoint x;
		CREATE TABLE koju (a INT UNIQUE);
		INSERT INTO koju VALUES (1);
		INSERT INTO koju VALUES (1);
	rollback to x;

	CREATE TABLE koju (a INT UNIQUE);
	INSERT INTO koju VALUES (1);
	INSERT INTO koju VALUES (1);
ROLLBACK;

DROP TABLE foo;
DROP TABLE baz;
DROP TABLE barbaz;

-- verify that cursors created during an aborted subtransaction are
-- closed, but that we do not rollback the effect of any FETCHs
-- performed in the aborted subtransaction
begin;

savepoint x;
create table abc (a int);
insert into abc values (5);
insert into abc values (10);
declare foo cursor for select * from abc;
fetch from foo;
rollback to x;

-- should fail
fetch from foo;
commit;

begin;

create table abc (a int);
insert into abc values (5);
insert into abc values (10);
insert into abc values (15);
declare foo cursor for select * from abc;

fetch from foo;

savepoint x;
fetch from foo;
rollback to x;

fetch from foo;

abort;

-- tests for the "tid" type
SELECT '(3, 3)'::tid = '(3, 4)'::tid;
SELECT '(3, 3)'::tid = '(3, 3)'::tid;
SELECT '(3, 3)'::tid <> '(3, 3)'::tid;
SELECT '(3, 3)'::tid <> '(3, 4)'::tid;


text:
aura
****
Play media files simultaneously on different computers. **Work in Progress, do not use**


text:
[![Build Status](https://travis-ci.org/NoamB/sorcery.svg?branch=master)](https://travis-ci.org/NoamB/sorcery)
[![Code Climate](https://codeclimate.com/github/NoamB/sorcery.png)](https://codeclimate.com/github/NoamB/sorcery)
[![Inline docs](http://inch-ci.org/github/NoamB/sorcery.png?branch=master)](http://inch-ci.org/github/NoamB/sorcery)

# sorcery
Magical Authentication for Rails 3 and 4. Supports ActiveRecord,
DataMapper, Mongoid and MongoMapper.

Inspired by restful_authentication, Authlogic and Devise. Crypto code taken
almost unchanged from Authlogic. OAuth code inspired by OmniAuth and Ryan
Bates's railscasts about it.

**What's happening now?** We are working on 1.0 version, which will include some API-breaking changes. It should be released about April 2015.
Until then we'll continue releasing `0.9.x` version with bug fixed.

**Rails 4 status:** [Sorcery 0.9.0](http://rubygems.org/gems/sorcery/versions/0.9.0) is fully tested and ready for Rails 4.0, 4.1 and 4.2.
**Mongoid status:** Version 0.9.0 works with Mongoid 4.

https://github.com/NoamB/sorcery/wiki/Simple-Password-Authentication

## Philosophy

Sorcery is a stripped-down, bare-bones authentication library, with which you
can write your own authentication flow. It was built with a few goals in mind:

*   Less is more - less than 20 public methods to remember for the entire
    feature-set make the lib easy to 'get'.
*   No built-in or generated code - use the library's methods inside *your
    own* MVC structures, and don't fight to fix someone else's.
*   Magic yes, Voodoo no - the lib should be easy to hack for most developers.
*   Configuration over Confusion - Centralized (1 file), Simple & short
    configuration as possible, not drowning in syntactic sugar.
*   Keep MVC cleanly separated - DB is for models, sessions are for
    controllers. Models stay unaware of sessions.

Hopefully, I've achieved this. If not, let me know.

## Useful Links

[Documentation](http://rubydoc.info/gems/sorcery) |
[Railscast](http://railscasts.com/episodes/283-authentication-with-sorcery) | [Simple tutorial](https://github.com/NoamB/sorcery/wiki/Simple-Password-Authentication) | [Example Rails 3 app](https://github.com/NoamB/sorcery-example-app)

Check out the tutorials in the [Wiki](https://github.com/NoamB/sorcery/wiki) for more!

## API Summary

Below is a summary of the library methods. Most method names are self
explaining and the rest are commented:

### core
```ruby
require_login # this is a before filter
login(email, password, remember_me = false)
auto_login(user)# login without credentials
logout
logged_in?      # available to view
current_user    # available to view
redirect_back_or_to # used when a user tries to access a page while logged out, is asked to login, and we want to return him back to the page he originally wanted.
@user.external? # external users, such as facebook/twitter etc.
@user.active_for_authentication? # add this method to define behaviour that will prevent selected users from signing in
User.authenticates_with_sorcery!
```

### http basic auth
```ruby
require_login_from_http_basic # this is a before filter
```

### external
```ruby
login_at(provider) # sends the user to an external service (twitter etc.) to authenticate.
login_from(provider) # tries to login from the external provider's callback.
create_from(provider) # create the user in the local app db.
```

### remember me
```ruby
auto_login(user, should_remember=false)  # login without credentials, optional remember_me
remember_me!
forget_me!
```

### reset password
```ruby
User.load_from_reset_password_token(token)
@user.generate_reset_password_token! # if you want to send the email by youself
@user.deliver_reset_password_instructions! # generates the token and sends the email
@user.change_password!(new_password)
```

### user activation
```ruby
User.load_from_activation_token(token)
@user.setup_activation
@user.activate!
```

Please see the tutorials in the github wiki for detailed usage information.

## Installation

If using bundler, first add 'sorcery' to your Gemfile:

```ruby
gem "sorcery"
```

And run

```ruby
bundle install
```

Otherwise simply

```ruby
gem install sorcery
```

## Rails configuration

```bash
rails generate sorcery:install
```

This will generate the core migration file, the initializer file and the
'User' model class.

```bash
rails generate sorcery:install remember_me reset_password
```

This will generate the migrations files for remember_me and reset_password
submodules and will create the initializer file (and add submodules to it),
and create the 'User' model class.

```bash
rails generate sorcery:install --model Person
```

This will generate the core migration file, the initializer and change the
model class (in the initializer and migration files) to the class 'Person'
(and its pluralized version, 'people')

```bash
rails generate sorcery:install http_basic_auth external remember_me --only-submodules
```

This will generate only the migration files for the specified submodules and
will add them to the initializer file.

Inside the initializer, the comments will tell you what each setting does.

## DelayedJob Integration

By default emails are sent synchronously. You can send them asynchronously by
using the [delayed_job gem](https://github.com/collectiveidea/delayed_job).

After implementing the `delayed_job` into your project add the code below at
the end of the `config/initializers/sorcery.rb` file. After that all emails
will be sent asynchronously.

```ruby
module Sorcery
  module Model
    module InstanceMethods
      def generic_send_email(method, mailer)
        config = sorcery_config
        mail = config.send(mailer).delay.send(config.send(method), self)
      end
    end
  end
end
```

Sidekiq and Resque integrations are coming soon.

## Single Table Inheritance (STI) Support
STI is supported via a single setting in config/initializers/sorcery.rb.

## Full Features List by module

**Core** (see [lib/sorcery/model.rb](https://github.com/NoamB/sorcery/blob/master/lib/sorcery/model.rb) and
[lib/sorcery/controller.rb](https://github.com/NoamB/sorcery/blob/master/lib/sorcery/controller.rb)):

*   login/logout, optional return user to requested url on login, configurable
    redirect for non-logged-in users.
*   password encryption, algorithms: bcrypt(default), md5, sha1, sha256,
    sha512, aes256, custom(yours!), none. Configurable stretches and salt.
*   configurable attribute names for username, password and email.
*   allow multiple fields to serve as username.

**User Activation** (see [lib/sorcery/model/submodules/user_activation.rb](https://github.com/NoamB/sorcery/blob/master/lib/sorcery/model/submodules/user_activation.rb)):

*   User activation by email with optional success email.
*   configurable attribute names.
*   configurable mailer, method name, and attribute name.
*   configurable temporary token expiration.
*   Optionally prevent non-active users to login.

**Reset Password** (see [lib/sorcery/model/submodules/reset_password.rb](https://github.com/NoamB/sorcery/blob/master/lib/sorcery/model/submodules/reset_password.rb)):

*   Reset password with email verification.
*   configurable mailer, method name, and attribute name.
*   configurable temporary token expiration.
*   configurable time between emails (hammering protection).

**Remember Me** (see [lib/sorcery/model/submodules/remember_me.rb](https://github.com/NoamB/sorcery/blob/master/lib/sorcery/model/submodules/remember_me.rb)):

*   Remember me with configurable expiration.
*   configurable attribute names.

**Session Timeout** (see [lib/sorcery/controller/submodules/session_timeout.rb](https://github.com/NoamB/sorcery/blob/master/lib/sorcery/controller/submodules/session_timeout.rb)):

*   Configurable session timeout.
*   Optionally session timeout will be calculated from last user action.

**Brute Force Protection** (see [lib/sorcery/model/submodules/brute_force_protection.rb](https://github.com/NoamB/sorcery/blob/master/lib/sorcery/model/submodules/brute_force_protection.rb)):

*   Brute force login hammering protection.
*   configurable logins before lock and lock duration.

**Basic HTTP Authentication** (see [lib/sorcery/controller/submodules/http_basic_auth.rb](https://github.com/NoamB/sorcery/blob/master/lib/sorcery/controller/submodules/http_basic_auth.rb)):

*   A before filter for requesting authentication with HTTP Basic.
*   automatic login from HTTP Basic.
*   automatic login is disabled if session key changed.

**Activity Logging** (see [lib/sorcery/model/submodules/activity_logging.rb](https://github.com/NoamB/sorcery/blob/master/lib/sorcery/model/submodules/activity_logging.rb)):

*   automatic logging of last login, last logout, last activity time and IP
    address for last login.
*   an easy method of collecting the list of currently logged in users.
*   configurable timeout by which to decide whether to include a user in the
    list of logged in users.

**External** (see [lib/sorcery/controller/submodules/external.rb](https://github.com/NoamB/sorcery/blob/master/lib/sorcery/controller/submodules/external.rb)):

*   OAuth1 and OAuth2 support (currently: Twitter, Facebook, Github, Google, Heroku,
    LinkedIn, VK, LiveID, Xing, and Salesforce)
*   configurable db field names and authentications table.

## Next Planned Features

I've got some thoughts which include (unordered):

*   Passing a block to encrypt, allowing the developer to define his own mix
    of salting and encrypting
*   Forgot username, maybe as part of the reset_password module
*   Scoping logins (to a subdomain or another arbitrary field)
*   Allowing storing the salt and crypted password in the same DB field for
    extra security
*   Other reset password strategies (security questions?)
*   Other brute force protection strategies (captcha)

Have an idea? Let me know, and it might get into the gem!

## Backward compatibility

While the lib is young and evolving fast I'm breaking backward compatibility
quite often. I'm constantly finding better ways to do things and throwing away
old ways. To let you know when things are changing in a non-compatible way,
I'm bumping the minor version of the gem. The patch version changes are
backward compatible.

In short, an app that works with x.3.1 should be able to upgrade to x.3.2 with
no code changes. The same cannot be said about upgrading to x.4.0 and above,
however.

## DataMapper Support

Important notes:

*   Expected to work with DM adapters: dm-mysql-adapter,
    dm-redis-adapter.
*   Submodules DM adapter dependent: activity_logging (dm-mysql-adapter)
*   Usage: include DataMapper::Resource in user model, follow sorcery
    instructions (remember to add property id, validators and accessor
attributes such as password and password_confirmation)
*   Option downcase__username_before_authenticating and dm-mysql,
    http://datamapper.lighthouseapp.com/projects/20609/tickets/1105-add-support-for-definingchanging-default-collation

## Upgrading

Important notes while upgrading:

*   If you are upgrading from <= **0.8.6** and you use Sorcery model methods in your app,
    you might need to change them from `user.method` to `user.sorcery_adapter.method` and from
    `User.method` to `User.sorcery_adapter_method`

*   If you are upgrading from <= **0.8.5** and you're using Sorcery test helpers,
    you need to change the way you include them to following code:

    ```ruby
    RSpec.configure do |config|
      config.include Sorcery::TestHelpers::Rails::Controller, type: :controller
      config.include Sorcery::TestHelpers::Rails::Integration, type: :feature
    end
    ```

*   If are upgrading to **0.8.2** and use activity_logging feature with
    ActiveRecord, you will have to add a new column
    `last_login_from_ip_address`
    [#465](https://github.com/NoamB/sorcery/issues/465)
*   Sinatra support existed until **v0.7.0** (including), but was dropped
    later due to being a maintenance nightmare.
*   If upgrading from <= **0.6.1 to >= **0.7.0** you need to change
    'username
    _attribute_name' to 'username_attribute_names' in initializer.
*   If upgrading from <= **v0.5.1** to >= **v0.5.2** you need to explicitly
    set your user_class model in the initializer file.

    ```ruby
    # This line must come after the 'user config' block.
    config.user_class = User
    ```

## Contributing to sorcery

Your feedback is very welcome and will make this gem much much better for you,
me and everyone else. Besides feedback on code, features, suggestions and bug
reports, you may want to actually make an impact on the code. For this:

*   Fork it.
*   Fix it.
*   Test it.
*   Commit it.
*   Send me a pull request so I'll... Pull it.

If you feel sorcery has made your life easier, and you would like to express
your thanks via a donation, my paypal email is in the contact details.

## Contact

Feel free to ask questions using these contact details:

#### Noam Ben-Ari

email: nbenari@gmail.com ( also for paypal )

twitter: @nbenari

#### Kir Shatrov

email: shatrov@me.com

twitter: @Kiiiir

#### Grzegorz Witek

email: arnvald.to@gmail.com

twitter: @arnvald

## Copyright

Copyright (c) 2010-2014 Noam Ben Ari (nbenari@gmail.com). See LICENSE.txt for
further details.


text:
namespace dp
{
class Handle;
typedef shared_ptr<Handle> HandleSPtr;
typedef weak_ptr<Handle> HandleWPtr;

class Handle
{
public:
    class Controller
    {
    public:
        Controller(const HandleSPtr& handle)
            : mHandle(handle)
        {
        }

        bool expired() const
        {
            return mHandle.expired();
        }

    private:
        HandleWPtr mHandle;
    };

    typedef shared_ptr<Controller> ControllerSPtr;
    typedef std::function<void()> ClearFunction;

    static HandleSPtr create(const ClearFunction& function)
    {
        struct make_shared_enabler : public Handle
        {
        };

        auto handle = std::make_shared<make_shared_enabler>();
        handle->mController = std::make_shared<Controller>(handle);
        handle->mClearFunction = function;
        return handle;
    }

    Handle(const Handle&) = delete;
    Handle(Handle&&) = delete;

    ~Handle()
    {
        if (mClearFunction != nullptr)
            mClearFunction();
    }

    ControllerSPtr controller()
    {
        return mController;
    }

private:
    Handle()
    {
    }

    ControllerSPtr mController;
    ClearFunction mClearFunction;
};
} // namespace dp


text:
<?xml version="1.0" encoding="ISO-8859-1"?>

<screensaver name="hypnowheel" _label="Hypnowheel" gl="yes">

  <command arg="-root"/>

  <hgroup>
   <vgroup>
    <number id="delay" type="slider" arg="-delay %"
            _label="Frame rate" _low-label="Slow" _high-label="Fast"
            low="0" high="100000" default="20000"
            convert="invert"/>

    <number id="speed" type="slider" arg="-speed %"
            _label="Speed" _low-label="Slow" _high-label="Fast"
            low="0.1" high="20.0" default="1.0"/>

    <hgroup>
    <boolean id="wander"    _label="Wander"             arg-set="-wander"/>
    <boolean id="symmetric" _label="Symmetric twisting" arg-set="-symmetric"/>
    </hgroup>

    <boolean id="showfps" _label="Show frame rate" arg-set="-fps"/>

   </vgroup>
   <vgroup>

    <number id="layers" type="slider" arg="-layers %"
            _label="Layers" _low-label="1" _high-label="50"
            low="1" high="50" default="4"/>

    <number id="count" type="slider" arg="-count %"
            _label="Arms" _low-label="2" _high-label="50"
            low="2" high="50" default="13"/>

    <number id="twistiness" type="slider" arg="-twistiness %"
            _label="Twistiness" _low-label="Low" _high-label="High"
            low="0.2" high="10.0" default="4.0"/>
   </vgroup>
  </hgroup>

  <xscreensaver-updater />

  <_description>
Draws a series of overlapping, translucent spiral patterns.
The tightness of their spirals fluctuates in and out.

http://en.wikipedia.org/wiki/Moire_pattern

Written by Jamie Zawinski; 2008.
  </_description>
</screensaver>


text:
var webdriver = require('selenium-webdriver'),
    By = webdriver.By,
    until = webdriver.until;

var driver = new webdriver.Builder()
    .forBrowser('chrome')
    .setChromeOptions()
    .build();

driver.get("http://www.google.com/ncr");
driver.findElement(By.id("lst-ib")).then(elem => {
    elem.sendKeys("ChromeDriver");
    elem.submit();
});
driver.wait(until.titleIs('ChromeDriver - Google Search'), 1000);
driver.quit();


text:
#include "modules/desktop_capture/window_finder_x11.h"

#include "modules/desktop_capture/x11/window_list_utils.h"
#include "rtc_base/checks.h"
#include "rtc_base/ptr_util.h"

namespace webrtc {

WindowFinderX11::WindowFinderX11(XAtomCache* cache)
    : cache_(cache) {
  RTC_DCHECK(cache_);
}

WindowFinderX11::~WindowFinderX11() = default;

WindowId WindowFinderX11::GetWindowUnderPoint(DesktopVector point) {
  WindowId id = kNullWindowId;
  GetWindowList(cache_,
                [&id, this, point](::Window window) {
                  DesktopRect rect;
                  if (GetWindowRect(this->cache_->display(), window, &rect) &&
                      rect.Contains(point)) {
                    id = window;
                    return false;
                  }
                  return true;
                });
  return id;
}

// static
std::unique_ptr<WindowFinder> WindowFinder::Create(
    const WindowFinder::Options& options) {
  if (options.cache == nullptr) {
    return nullptr;
  }

  return rtc::MakeUnique<WindowFinderX11>(options.cache);
}

}  // namespace webrtc


text:
/**
 * Poster v0.1.0
 * A React webapp to list upcoming movies and maintain a watchlist, powered by TMDb
 *
 * Author: Kushal Pandya <kushalspandya@gmail.com> (https://doublslash.com)
 * Date: 01 June, 2016
 * License: MIT
 *
 * React App Entry-point
 */

/*
 * Library
 */
import React from "react";
import ReactDOM from "react-dom";
import { Router, Route, IndexRoute, hashHistory } from "react-router";
import { Provider } from "react-redux";

/*
 * Page Components
 */
import Home             from "./components/Views/Home";
import SearchResults    from "./components/Views/Section/SearchResults";
import TopRated         from "./components/Views/Section/TopRated/TopRated";
import Upcoming         from "./components/Views/Section/Upcoming/Upcoming";
import Watchlist        from "./components/Views/Section/Watchlist/Watchlist";
import MovieDetail      from "./components/Views/Section/MovieDetail/MovieDetail";

/*
 * Poster Redux Store
 */
import Store from "./store";

ReactDOM.render(
    <Provider store={Store}>
        <Router history={hashHistory}>
            <Route path="/" component={Home}>
                <Route path="search" component={SearchResults}></Route>
                <Route path="top_rated" component={TopRated}></Route>
                <Route path="upcoming" component={Upcoming}></Route>
                <Route path="watchlist" component={Watchlist}></Route>
                <Route path="movie/:movieId" component={MovieDetail}></Route>
            </Route>
        </Router>
    </Provider>,
    document.getElementById('poster-app')
);


text:
package org.apache.hedwig.server.netty;

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

import org.apache.log4j.Logger;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipelineCoverage;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.handler.codec.frame.CorruptedFrameException;
import org.jboss.netty.handler.codec.frame.TooLongFrameException;
import org.jboss.netty.handler.ssl.SslHandler;

import org.apache.hedwig.exceptions.PubSubException.MalformedRequestException;
import org.apache.hedwig.protocol.PubSubProtocol;
import org.apache.hedwig.protocol.PubSubProtocol.OperationType;
import org.apache.hedwig.protocol.PubSubProtocol.PubSubResponse;
import org.apache.hedwig.protoextensions.PubSubResponseUtils;
import org.apache.hedwig.server.handlers.ChannelDisconnectListener;
import org.apache.hedwig.server.handlers.Handler;

@ChannelPipelineCoverage("all")
public class UmbrellaHandler extends SimpleChannelHandler {
    static Logger logger = Logger.getLogger(UmbrellaHandler.class);

    private Map<OperationType, Handler> handlers;
    private ChannelGroup allChannels;
    private ChannelDisconnectListener subscribeHandler;
    private boolean isSSLEnabled = false;

    public UmbrellaHandler(ChannelGroup allChannels, Map<OperationType, Handler> handlers,
            boolean isSSLEnabled) {
        this.allChannels = allChannels;
        this.isSSLEnabled = isSSLEnabled;
        this.handlers = handlers;
        subscribeHandler = (ChannelDisconnectListener) handlers.get(OperationType.SUBSCRIBE);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
        Throwable throwable = e.getCause();

        // Add here if there are more exceptions we need to be able to tolerate.
        // 1. IOException may be thrown when a channel is forcefully closed by
        // the other end, or by the ProtobufDecoder when an invalid protobuf is
        // received
        // 2. TooLongFrameException is thrown by the LengthBasedDecoder if it
        // receives a packet that is too big
        // 3. CorruptedFramException is thrown by the LengthBasedDecoder when
        // the length is negative etc.
        if (throwable instanceof IOException || throwable instanceof TooLongFrameException
                || throwable instanceof CorruptedFrameException) {
            e.getChannel().close();
            if (logger.isDebugEnabled()) {
                logger.debug("Uncaught exception", throwable);
            }
        } else {
            // call our uncaught exception handler, which might decide to
            // shutdown the system
            Thread thread = Thread.currentThread();
            thread.getUncaughtExceptionHandler().uncaughtException(thread, throwable);
        }

    }

    @Override
    public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        // If SSL is NOT enabled, then we can add this channel to the
        // ChannelGroup. Otherwise, that is done when the channel is connected
        // and the SSL handshake has completed successfully.
        if (!isSSLEnabled) {
            allChannels.add(ctx.getChannel());
        }
    }

    @Override
    public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        if (isSSLEnabled) {
            ctx.getPipeline().get(SslHandler.class).handshake(e.getChannel()).addListener(new ChannelFutureListener() {
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("SSL handshake has completed successfully!");
                        }
                        allChannels.add(future.getChannel());
                    } else {
                        future.getChannel().close();
                    }
                }
            });
        }
    }

    @Override
    public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        Channel channel = ctx.getChannel();
        // subscribe handler needs to know about channel disconnects
        subscribeHandler.channelDisconnected(channel);
        channel.close();
    }

    public static void sendErrorResponseToMalformedRequest(Channel channel, long txnId, String msg) {
        if (logger.isDebugEnabled()) {
            logger.debug("Malformed request from " + channel.getRemoteAddress() + " msg, = " + msg);
        }
        MalformedRequestException mre = new MalformedRequestException(msg);
        PubSubResponse response = PubSubResponseUtils.getResponseForException(mre, txnId);
        channel.write(response);
    }

    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {

        if (!(e.getMessage() instanceof PubSubProtocol.PubSubRequest)) {
            ctx.sendUpstream(e);
            return;
        }

        PubSubProtocol.PubSubRequest request = (PubSubProtocol.PubSubRequest) e.getMessage();

        Handler handler = handlers.get(request.getType());
        Channel channel = ctx.getChannel();
        long txnId = request.getTxnId();

        if (handler == null) {
            sendErrorResponseToMalformedRequest(channel, txnId, "Request type " + request.getType().getNumber()
                    + " unknown");
            return;
        }

        handler.handleRequest(request, channel);
    }

}


text:
Android-GPS
===========

first project


text:
Add new cat

    <form [formGroup]="addCatForm" (ngSubmit)="addCat()">

          <input class="form-control" type="text" name="name"
            formControlName="name" placeholder="Name">

          <input class="form-control" type="number" name="age"
            formControlName="age" placeholder="Age" min="0">

          <input class="form-control" type="number" name="weight"
            formControlName="weight" placeholder="Weight" step="any" min="0">

          <button class="btn btn-primary" type="submit" [disabled]="!addCatForm.valid">
             Add
          </button>

    </form>


text:
import morphdom from 'morphdom'

const onBeforeElUpdated = (fromEl, toEl) => !fromEl.isEqualNode(toEl)

export default (container, ...elms) => {
  const children = [...container.childNodes]
  const length = Math.max(children.length, elms.length)
  for (let i = 0; i < length; i += 1) {
    let elm = elms[i]
    let child = children[i]
    if (child) {
      if (elm) {
        if (child.nodeType !== elm.nodeType) {
          container.replaceChild(elm, child)
        } else {
          if (!child.isEqualNode(elm)) {
            morphdom(child, elm, {onBeforeElUpdated})
          }
        }
      } else {
        container.removeChild(child)
      }
    } else {
      container.appendChild(elm)
    }
  }
}


text:
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-missing-fields #-}
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}

-----------------------------------------------------------------
-- Autogenerated by Thrift
--                                                             --
-- DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
--  @generated
-----------------------------------------------------------------

module My.Namespacing.Test.Hsmodule_Types where
import Prelude ( Bool(..), Enum, Float, IO, Double, String, Maybe(..),
                 Eq, Show, Ord,
                 concat, error, fromIntegral, fromEnum, length, map,
                 maybe, not, null, otherwise, return, show, toEnum,
                 enumFromTo, Bounded, minBound, maxBound, seq, succ,
                 pred, enumFrom, enumFromThen, enumFromThenTo,
                 (.), (&&), (||), (==), (++), ($), (-), (>>=), (>>))

import qualified Control.Applicative as Applicative (ZipList(..))
import Control.Applicative ( (<*>) )
import qualified Control.DeepSeq as DeepSeq
import qualified Control.Exception as Exception
import qualified Control.Monad as Monad ( liftM, ap, when )
import qualified Data.ByteString.Lazy as BS
import Data.Functor ( (<$>) )
import qualified Data.Hashable as Hashable
import qualified Data.Int as Int
import Data.List
import qualified Data.Maybe as Maybe (catMaybes)
import qualified Data.Text.Lazy.Encoding as Encoding ( decodeUtf8, encodeUtf8 )
import qualified Data.Text.Lazy as LT
import qualified Data.Typeable as Typeable ( Typeable )
import qualified Data.HashMap.Strict as Map
import qualified Data.HashSet as Set
import qualified Data.Vector as Vector
import qualified Test.QuickCheck.Arbitrary as Arbitrary ( Arbitrary(..) )
import qualified Test.QuickCheck as QuickCheck ( elements )

import qualified Thrift
import qualified Thrift.Types as Types
import qualified Thrift.Serializable as Serializable
import qualified Thrift.Arbitraries as Arbitraries

data HsFoo = HsFoo
  { hsFoo_MyInt :: Int.Int64
  } deriving (Show,Eq,Typeable.Typeable)
instance Serializable.ThriftSerializable HsFoo where
  encode = encode_HsFoo
  decode = decode_HsFoo
instance Hashable.Hashable HsFoo where
  hashWithSalt salt record = salt   `Hashable.hashWithSalt` hsFoo_MyInt record
instance DeepSeq.NFData HsFoo where
  rnf _record0 =
    DeepSeq.rnf (hsFoo_MyInt _record0) `seq`
    ()
instance Arbitrary.Arbitrary HsFoo where
  arbitrary = Monad.liftM HsFoo (Arbitrary.arbitrary)
  shrink obj | obj == default_HsFoo = []
             | otherwise = Maybe.catMaybes
    [ if obj == default_HsFoo{hsFoo_MyInt = hsFoo_MyInt obj} then Nothing else Just $ default_HsFoo{hsFoo_MyInt = hsFoo_MyInt obj}
    ]
from_HsFoo :: HsFoo -> Types.ThriftVal
from_HsFoo record = Types.TStruct $ Map.fromList $ Maybe.catMaybes
  [ (\_v3 -> Just (1, ("MyInt",Types.TI64 _v3))) $ hsFoo_MyInt record
  ]
write_HsFoo :: (Thrift.Protocol p, Thrift.Transport t) => p t -> HsFoo -> IO ()
write_HsFoo oprot record = Thrift.writeVal oprot $ from_HsFoo record
encode_HsFoo :: (Thrift.Protocol p, Thrift.Transport t) => p t -> HsFoo -> BS.ByteString
encode_HsFoo oprot record = Thrift.serializeVal oprot $ from_HsFoo record
to_HsFoo :: Types.ThriftVal -> HsFoo
to_HsFoo (Types.TStruct fields) = HsFoo{
  hsFoo_MyInt = maybe (hsFoo_MyInt default_HsFoo) (\(_,_val5) -> (case _val5 of {Types.TI64 _val6 -> _val6; _ -> error "wrong type"})) (Map.lookup (1) fields)
  }
to_HsFoo _ = error "not a struct"
read_HsFoo :: (Thrift.Transport t, Thrift.Protocol p) => p t -> IO HsFoo
read_HsFoo iprot = to_HsFoo <$> Thrift.readVal iprot (Types.T_STRUCT typemap_HsFoo)
decode_HsFoo :: (Thrift.Protocol p, Thrift.Transport t) => p t -> BS.ByteString -> HsFoo
decode_HsFoo iprot bs = to_HsFoo $ Thrift.deserializeVal iprot (Types.T_STRUCT typemap_HsFoo) bs
typemap_HsFoo :: Types.TypeMap
typemap_HsFoo = Map.fromList [("MyInt",(1,Types.T_I64))]
default_HsFoo :: HsFoo
default_HsFoo = HsFoo{
  hsFoo_MyInt = 0}


text:
module Main where

import Data.Numbers.Primes (isPrime, primes)

sumPrimesMod :: Int -> Bool
sumPrimesMod n = isPrime (sum (take n primes) `mod` n)

main :: IO ()
main = do
  let ns = filter sumPrimesMod [1 .. 367]
  print ns
  print $ length ns


text:
package rovak.steamkit.steam.language;

import java.util.HashMap;

public enum EResult {
	Invalid(0),
	OK(1),
	Fail(2),
	NoConnection(3),
	InvalidPassword(5),
	LoggedInElsewhere(6),
	InvalidProtocolVer(7),
	InvalidParam(8),
	FileNotFound(9),
	Busy(10),
	InvalidState(11),
	InvalidName(12),
	InvalidEmail(13),
	DuplicateName(14),
	AccessDenied(15),
	Timeout(16),
	Banned(17),
	AccountNotFound(18),
	InvalidSteamID(19),
	ServiceUnavailable(20),
	NotLoggedOn(21),
	Pending(22),
	EncryptionFailure(23),
	InsufficientPrivilege(24),
	LimitExceeded(25),
	Revoked(26),
	Expired(27),
	AlreadyRedeemed(28),
	DuplicateRequest(29),
	AlreadyOwned(30),
	IPNotFound(31),
	PersistFailed(32),
	LockingFailed(33),
	LogonSessionReplaced(34),
	ConnectFailed(35),
	HandshakeFailed(36),
	IOFailure(37),
	RemoteDisconnect(38),
	ShoppingCartNotFound(39),
	Blocked(40),
	Ignored(41),
	NoMatch(42),
	AccountDisabled(43),
	ServiceReadOnly(44),
	AccountNotFeatured(45),
	AdministratorOK(46),
	ContentVersion(47),
	TryAnotherCM(48),
	PasswordRequiredToKickSession(49),
	AlreadyLoggedInElsewhere(50),
	Suspended(51),
	Cancelled(52),
	DataCorruption(53),
	DiskFull(54),
	RemoteCallFailed(55),
	PasswordNotSet(56),
	PSNAccountNotLinked(57),
	InvalidPSNTicket(58),
	PSNAccountAlreadyLinked(59),
	RemoteFileConflict(60),
	IllegalPassword(61),
	SameAsPreviousValue(62),
	AccountLogonDenied(63),
	CannotUseOldPassword(64),
	InvalidLoginAuthCode(65),
	AccountLogonDeniedNoMailSent(66),
	HardwareNotCapableOfIPT(67),
	IPTInitError(68),
	ParentalControlRestricted(69),
	FacebookQueryError(70),
	ExpiredLoginAuthCode(71),
	IPLoginRestrictionFailed(72),
	AccountLocked(73),
	AccountLogonDeniedVerifiedEmailRequired(74), ;

	private int code;

	private EResult(int code) {
		this.code = code;
	}

	public int v() {
		return code;
	}

	private static HashMap<Integer, EResult> values = new HashMap<Integer, EResult>();

	static {
		for (final EResult type : EResult.values()) {
			EResult.values.put(type.v(), type);
		}
	}

	public static EResult f(int code) {
		return EResult.values.get(code);
	}
}