text:
<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer/autoload_real.php';

return ComposerAutoloaderIniteeef8cfdbb4e09f9e5888ec76d0c578a::getLoader();

redpajama_set_name: RedPajamaGithub


text:
/**
 * Logging components.
 *
 * @author mprimi
 * @since 4.0.0
 */
@ParametersAreNonnullByDefault
package com.netflix.genie.agent.cli.logging;

import javax.annotation.ParametersAreNonnullByDefault;


text:
package org.jasig.cas.grouper.services;

import edu.internet2.middleware.grouperClient.api.GcGetGroups;
import edu.internet2.middleware.grouperClient.ws.beans.WsGetGroupsResult;
import edu.internet2.middleware.grouperClient.ws.beans.WsGroup;
import org.jasig.cas.services.TimeBasedRegisteredServiceAccessStrategy;

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

/**
 * The {@link GrouperRegisteredServiceAccessStrategy} is an access strategy
 * that consults a grouper instance to figure out affiliations associated
 * with a user.
 *
 * @author Misagh Moayyed
 * @since 4.2
 */
public class GrouperRegisteredServiceAccessStrategy extends TimeBasedRegisteredServiceAccessStrategy {

    private static final long serialVersionUID = -3557247044344135788L;
    private static final String GROUPER_GROUPS_ATTRIBUTE_NAME = "grouperAttributes";

    /**
     * The enum Grouper group field.
     */
    public enum GrouperGroupField {
        /**
         * Name grouper group field.
         */
        NAME,
        /**
         * Extension grouper group field.
         */
        EXTENSION,
        /**
         * Display name grouper group field.
         */
        DISPLAY_NAME,
        /**
         * Display extension grouper group field.
         */
        DISPLAY_EXTENSION
    }

    private GrouperGroupField groupField = GrouperGroupField.NAME;

    @Override
    public boolean doPrincipalAttributesAllowServiceAccess(final String principal, final Map<String, Object> principalAttributes) {
        final Map<String, Object> allAttributes = new HashMap<>(principalAttributes);
        final List<String> grouperGroups = new ArrayList<>();

        final WsGetGroupsResult[] results;

        try {
            final GcGetGroups groupsClient = new GcGetGroups().addSubjectId(principal);
            results = groupsClient.execute().getResults();
        } catch (final Exception e) {
            logger.warn("Grouper WS did not respond successfully. Ensure your credentials are correct "
                    + ", the url endpoint for Grouper WS is correctly configured and the subject " + principal
                    + "  exists in Grouper.", e);
            return false;
        }

        if (results == null || results.length == 0) {
            logger.warn("Subject id [{}] could not be located. Access denied", principal);
            return false;
        }

        for (final WsGetGroupsResult groupsResult : results) {
            if (groupsResult.getWsGroups() == null || groupsResult.getWsGroups().length == 0) {
                logger.warn("No groups could be found for subject [{}]. Access denied", groupsResult.getWsSubject().getName());
                return false;
            }

            for (final WsGroup group : groupsResult.getWsGroups()) {
                final String groupName = constructGrouperGroupAttribute(group);
                logger.debug("Found group name [{}] for [{}]", groupName, principal);
                grouperGroups.add(groupName);
            }
        }
        logger.debug("Adding [{}] under attribute name [{}] to collection of CAS attributes",
                grouperGroups, GROUPER_GROUPS_ATTRIBUTE_NAME);

        allAttributes.put(GROUPER_GROUPS_ATTRIBUTE_NAME, grouperGroups);
        return super.doPrincipalAttributesAllowServiceAccess(principal, allAttributes);
    }

    public void setGroupField(final GrouperGroupField groupField) {
        this.groupField = groupField;
    }

    public GrouperGroupField getGroupField() {
        return groupField;
    }

    /**
     * Construct grouper group attribute.
     * This is the name of every individual group attribute
     * transformed into a CAS attribute value.
     * @param group the group
     * @return the final attribute name
     */
    protected String constructGrouperGroupAttribute(final WsGroup group) {
        switch (this.groupField) {
            case DISPLAY_EXTENSION:
                return group.getDisplayExtension();
            case DISPLAY_NAME:
                return group.getDisplayName();
            case EXTENSION:
                return group.getExtension();
            default:
                return group.getName();
        }
    }

}


text:
Planet PHitness
===

I'm a member of Planet Fitness and enjoy doing the non-cardio stuff there, which is also harder to track.  So, I'm creating
this webapp in PHP using the Symfony 3 framework to make this more possible.

There's no scientific backing of what results are displayed as of this writing.  This is more or less a fun little project
 I decided to partake on.


text:
const log = require('../util/logger');

const FlightDelayDatabase = artifacts.require('FlightDelayDatabase.sol');

module.exports = (deployer, network, accounts) => {

    log.info('Deploy FlightDelayDatabase contract');

    return deployer.deploy(FlightDelayDatabase);

};


text:
// start monitoring with new relic
require('newrelic');
// creating global parameters and start
// listening to 'process.env.PORT', we are creating an express
// server and then we are binding it with socket.io
var express      = require('express');
var app          = express();
var server       = require('http').createServer(app);
var io           = require('socket.io').listen(server);
process.env.PORT = process.env.PORT || 1337;
var path         = require('path');
var url          = 'http://localhost:' + process.env.PORT + '/';
var db           = require('./db/queries');

/* We can access nodejitsu enviroment variables from process.env */
/* Note: the SUBDOMAIN variable will always be defined for a nodejitsu app */
if(process.env.SUBDOMAIN){
  url = 'http://' + process.env.SUBDOMAIN + '.jit.su/';
}

// listening to process.env.PORT...
server.listen(process.env.PORT);
console.log("Express server listening on port " + process.env.PORT);
console.log(url);

// log it all
io.set('log level', 2);

// give the client access to all client files
app.use(express.static(path.join(__dirname, '../build/client')));

// serving the main applicaion file (index.html)
// when a client makes a request to the app root
// http://localhost:1337
app.get('/', function (req, res) {
    res.sendfile(path.join(__dirname, '../build/client/index.html'));
});
// serves basic room details
app.get('/rooms', function (req, res) {
    db.getRooms(function(err, rooms){
        if (err) { res.send(403, err); throw err; }
        res.json(rooms);
    });
});

// serves player stats for in-game menu
app.get('/rooms/:id', function (req, res) {
    db.getRoomInfo(req.param('id'), function(err, roomInfo){
        if (err) { res.send(403, err); throw err; }
        res.json(roomInfo);
    });
});

// Holds players
var players = {};

var mapItems = [
    { type: 'Alien Space Station', pos: [0, 1000], rot: 0, hp: 100 },
    { type: 'Human Space Station',  pos: [0, -1000], rot: Math.PI*2, hp: 100 }
];

var mapSize = 1600;
var maxSpeed = 200; // units per second

function getRandomCoord() {
    return Math.random()*mapSize - mapSize/2;
}

function getRandomPosition() {
    return [getRandomCoord(), 140, getRandomCoord()];
}

function getTime() {
    return (new Date()).getTime();
}

var socketManager = require('./io/manager.js')(mapItems, io);
io.sockets.on('connection', socketManager);


text:
This template deploys **OMS Monitoring solution for Azure backup** on an OMS log analytics workspace. This allows you to monitor key backup parameters such as backup and restore jobs, backup alerts and Cloud storage usage across Recovery services vaults

`Tags: Azure Backup, OMS Log Analytics, Monitoring`

## Prerequisites

You need to configure the OMS log analytics workspace to receive backup related data from Azure Recovery Services vaults. To do so, loggin into Azure portal –> Click "Monitor" service –> "Diagnostic settings" in Settings section –> Specify the relevant Subscription, Resource Group and Recovery Services Vault. In the Diagnostic settings window, as shown below, in addition to specifying a storage account, you can select "Send data to log analytics" and then select the relevant OMS workspace. You can choose any existing log analytics workspace such that all vaults pump the data to the same workspace

Please select the relevant log, "AzureBackupReport" in this case, to be sent to the log analytics workspace. Click "Save" to save the setting.

![alt text](images/DiagnosticSettings.JPG "Azure log analytics workspace diagnostic setting")

## Solution overview and deployed resources

Upon deploying the solution, you would view an overview tile which reflects backup jobs and their status.

![alt text](images/OverviewTile.JPG "OMS Monitoring solution for Azure backup monitoring tile")

Clicking on the solution would let you explore Alerts, backups, restores, Cloud Storage and active data source details.

![alt text](images/KeyBackupJobsParameters.jpg "OMS Monitoring solution for Azure backup alerts, backups, restores")

![alt text](images/ActiveDatasources.png "OMS Monitoring solution for Azure backup active data sources distribution")

![alt text](images/CloudStorageInGB.png "OMS Monitoring solution for Azure backup cloud storage distribution")

You can click on each tile to get more details about the queries used to create it and you can configure it as per your requirement. Clicking further on values appearing in the tiles will lead you to Log analytics screen where you can raise alerts for configurable event thresholds and automate actions to be performed when those thresholds are met/crossed.

![alt text](images/LogAnalyticsScreen.JPG "OMS Monitoring solution for Azure backup Log search")

More information about configuring alerts can be found [here](https://docs.microsoft.com/azure/log-analytics/log-analytics-tutorial-response)


text:
Cassanova-migrate is a incremental migration tool for Cassandra.

## Features
- Uses Cassanova to run incremental migrations on Cassandra database.
- Uses Cassandra keyspace mentioned in commandline to keep track of ran migrations.
- Automatically builds and run UP or DOWN until any migration number.
- Creates a new incremental migration template by a single command.

## Installation

Install [node.js](http://nodejs.org/) and [cassandra](http://cassandra.apache.org/) and [cassanova](https://www.npmjs.com/package/cassanova). Then:

```
npm install cassanova-migrate
```

```
cd cassanova-migrate
```

```
npm install
```

## Overview

### Basic Usage

Runs all migrations available in current directory.

```
    cassanova-migrate -k <keyspace>
```

Creates a new migration with incremental migration number ( Used for tracking migrations ).

```
    cassanova-migrate create <title>
```

Goes back/forward to a particular migration automatically.

```
    cassanova-migrate -k <keyspace> -n <migration-number>
```

Runs a cql command.

```
    cassanova-migrate -k <keyspace> -c "<cql-script>"
```

Runs a cql command.

```
    cassanova-migrate -k <keyspace> -c "<cql-script>"
```

Define host and port number. By default connects to [localhost] and default cassandra port [9042].

```
    cassanova-migrate -h [10.10.10.1] -p 9252
```

More help.

```
    cassanova-migrate --help
```

## License

cassanova-migrate is distributed under the [MIT license](http://opensource.org/licenses/MIT).

## Contributions

Feel free to join in and support the project!

Check the [Issue tracker](https://github.com/keswanikaran/cassanova-migrate/issues)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OfficeDevPnP.Core.Extensions;

namespace OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.Resolvers.V201705
{
    /// <summary>
    /// Resolves the IRM Settings of a List from Schema to Domain Model
    /// </summary>
    internal class IRMSettingsFromSchemaToModelTypeResolver : ITypeResolver
    {
        public string Name => this.GetType().Name;
        public bool CustomCollectionResolver => true;

        public IRMSettingsFromSchemaToModelTypeResolver()
        {
        }

        public object Resolve(object source, Dictionary<String, IResolver> resolvers = null, Boolean recursive = false)
        {
            Object result = null;

            var irmSettings = source.GetPublicInstancePropertyValue("IRMSettings");
            if (null != irmSettings)
            {
                result = new Model.IRMSettings();
                PnPObjectsMapper.MapProperties(irmSettings, result, resolvers, recursive);
            }

            return (result);
        }
    }
}


text:
namespace fun {

using namespace std;
using namespace Poco;

Breakpoint::Breakpoint(const location& location) :
        _location(location), _type(LOCATION) {
}

Breakpoint::Breakpoint(unsigned int line, unsigned int startColumn, unsigned int endColumn):
    Breakpoint(location(position(nullptr, line, startColumn), position(nullptr, line, endColumn))) {
}

Breakpoint::Breakpoint(unsigned int line):
    _location(position{nullptr, line, 0}), _type(LINE) {
}

Breakpoint::~Breakpoint() {
}

bool Breakpoint::operator ==(const Breakpoint& rhs) const {
    return _location == rhs._location;
}

bool Breakpoint::operator !=(const Breakpoint& rhs) const {
    return !(rhs == *this);
}

ostream& operator<<(ostream& out, const Breakpoint& rhs){
    return out << "Breakpoint(" << rhs._location << ")";
}

Debugger::Debugger() :
        _state(new Normal) {
}

void Debugger::setBreakpoint(const Breakpoint &breakpoint) {
    _breakpoints.push_back(breakpoint);

    stringstream ss;
    ss.seekg(0);
}

void Debugger::enableBreakpoint(const Breakpoint &breakpoint) {
}

void Debugger::disableBreakpoint(const Breakpoint &breakpoint) {
}

void Debugger::removeBreakpoint(const Breakpoint &breakpoint) {
    auto it = find(begin(_breakpoints), end(_breakpoints), breakpoint);
    if (it == _breakpoints.end())
        return;
    _breakpoints.erase(it);
}

const Breakpoints &Debugger::getBreakpoints() const {
    return _breakpoints;
}

void Debugger::Normal::onEnter(Debugger *debugger) {
}

void Debugger::Normal::onExit(Debugger *debugger) {
}

void Debugger::Normal::pause(Debugger *d) {
}

void Debugger::Normal::resume(Debugger *d) {
    Mutex::ScopedLock lock(d->_mutex);
    d->_run = true;
    d->_cond.signal();
}

void Debugger::Normal::stepOver(Debugger *d) {
    Mutex::ScopedLock lock(d->_mutex);
    d->switchState<StepOver>(true);
}

void Debugger::Normal::stepIn(Debugger *d) {
}

void Debugger::Normal::stepOut(Debugger *d) {
}

void Debugger::Normal::onBeforeStep(Debugger *d, Statement *statement) {
    Mutex::ScopedLock lock(d->_mutex);

    auto line = statement->loc.begin.line;

    d->_currentStatement = statement;
    for (auto &breakpoint : d->_breakpoints) {
        if (breakpoint.getType() == Breakpoint::LOCATION ?
                (breakpoint.getLocation() == statement->loc):
                (breakpoint.getLocation().begin.line == line && d->_lastBreakpointLine != line)) {
            while (!d->_run) {
                d->onCatchBreakpoint(breakpoint);
                d->_cond.wait(d->_mutex);
            }
            d->_run = false;
        }
    }
    d->_lastBreakpointLine = line;
}

void Debugger::StepOver::onEnter(Debugger *d) {
    if (_resume)
        resume(d);
}

void Debugger::StepOver::onExit(Debugger *debugger) {
}

void Debugger::StepOver::pause(Debugger *d) {
}

void Debugger::StepOver::resume(Debugger *d) {
    Mutex::ScopedLock lock(d->_mutex);
    d->switchState<Normal>();
    d->_run = true;
    d->_cond.signal();
}

void Debugger::StepOver::stepOver(Debugger *d) {
    Mutex::ScopedLock lock(d->_mutex);
    d->_run = true;
    d->_cond.signal();
}

void Debugger::StepOver::stepIn(Debugger *d) {
}

void Debugger::StepOver::stepOut(Debugger *d) {
}

void Debugger::StepOver::onBeforeStep(Debugger *d, Statement *statement) {
    Mutex::ScopedLock lock(d->_mutex);
    d->_currentStatement = statement;
    while (!d->_run)
        d->_cond.wait(d->_mutex);
    d->onCatchBreakpoint(Breakpoint{statement->loc});
    d->_run = false;
}
}


text:
![Travis](https://travis-ci.org/andersondanilo/modelform.svg?branch=master)
[![Code Climate](https://codeclimate.com/github/andersondanilo/modelform/badges/gpa.svg)](https://codeclimate.com/github/andersondanilo/modelform)
[![Test Coverage](https://codeclimate.com/github/andersondanilo/modelform/badges/coverage.svg)](https://codeclimate.com/github/andersondanilo/modelform)
[![Latest Stable Version](https://poser.pugx.org/andersondanilo/modelform/v/stable.svg)](https://packagist.org/packages/andersondanilo/modelform)
[![Latest Unstable Version](https://poser.pugx.org/andersondanilo/modelform/v/unstable.svg)](https://packagist.org/packages/andersondanilo/modelform)
[![License](https://poser.pugx.org/andersondanilo/modelform/license.svg)](https://packagist.org/packages/andersondanilo/modelform)

What is
=======
ModelForm is a PHP Form Abstraction for Laravel based on Django Forms and Formset, but completely integrated with the Laravel FormBuilder.

Instalation
===========
To get the latest version of ModelForm simply require it in your composer.json file

    php composer.phar require "andersondanilo/modelform:dev-master"

Examples of usage
================

Simple example: Without model
-----------------------------

```php
// SimpleForm.php
use ModelForm\Form;
use ModelForm\Fields\CharField;
use ModelForm\Fields\IntegerField;

class SimpleForm extends Form
{
    public function makeFields()
    {
        $this->name = new CharField(['label' => 'Name']);
        $this->age = new IntegerField(['label' => 'Age']);
    }
}
```

Instancializing Form

```php
$simpleForm = new SimpleForm(['data' => Input::old() ?: Input::all()]);
```

Rendering model in view

```php
    {{ $simpleForm->name->label() }}:
    {{ $simpleForm->name->text(['class' => 'form-control']) }}
```

Acessing values after

```php
    $name = $simpleForm->name->value;
```

With Model and Validator
------------------------

```php
use ModelForm\Form;
use ModelForm\Fields\CharField;
use ModelForm\Fields\IntegerField;

class SimpleForm extends Form
{
    public function makeFields()
    {
        $this->name = new CharField(['label' => 'Name']);
        $this->age = new IntegerField(['label' => 'Age']);
    }

    public function makeModel()
    {
        return new MyModel();
    }

    public function makeValidator($data)
    {
        return Validator::make($data, [
            'name' => 'required'
        ]);
    }
}
```

You can instancialize without model and then the model is created by form, or start with a already existing model.

```php
$model10 = MyModel::find(10);
$form = new SimpleForm(['model' => $model10, 'data' => Input::old() ?: Input::all()]);
```

Validating

```php
if(!$simpleForm->isValid()) {
    return Redirect::back()->withErrors($simpleForm->errors())->withInput();
}
```

Saving your model
```php
$simpleForm->save();
```

Formsets
--------
```php
use ModelForm\FormSet;

class SimpleFormSet extends FormSet
{
    public function makeForm($model=null)
    {
        return new SimpleForm(['model'=>$model]);
    }
}
```

Create the empty formset instance:
```php
$simpleFormSet = new SimpleFormSet(['data' => Input::old() ?: Input::all());
```

Or create a formset filled with a model relation:
```php
$addressFormSet = new AddressFormSet(['relation'=>$customer->addresses(), 'data' => Input::old() ?: Input::all());
```

The validation and saving of formset is the symmetric with form.
```php
if(!$addressFormSet->isValid()) {
    return Redirect::back()->withErrors($addressFormSet->errors())->withInput();
}
$addressFormSet->save();
```


text:
package janala.logger.inst;

public class IOR extends Instruction {
  public IOR(int iid, int mid) {
    super(iid, mid);
  }

  public void visit(IVisitor visitor) {
    visitor.visitIOR(this);
  }

  @Override
  public String toString() {
    return "IOR iid=" + iid + " mid=" + mid;
  }
}


text:
import pytest

from selenium.webdriver.common.options import ArgOptions

@pytest.fixture
def options():
    return ArgOptions()

def test_add_arguments(options):
    options.add_argument("foo")
    assert "foo" in options._arguments

def test_get_arguments(options):
    options._arguments = ["foo"]
    assert "foo" in options.arguments

def test_enables_mobile(options):
    options.enable_mobile(android_package="cheese")
    assert options.mobile_options["androidPackage"] == "cheese"
    assert not hasattr(options.mobile_options, "androidActivity")
    assert not hasattr(options.mobile_options, "androidDeviceSerial")

def test_enable_mobile_errors_without_package(options):
    with pytest.raises(AttributeError):
        options.enable_mobile()

def test_enable_mobile_with_activity(options):
    options.enable_mobile(android_package="sausages", android_activity="eating")
    assert options.mobile_options["androidActivity"] == "eating"

def test_enable_mobile_with_device_serial(options):
    options.enable_mobile(android_package="cheese", android_activity="crackers", device_serial="1234")
    options.mobile_options["androidDeviceSerial"] == "1234"

def test_missing_capabilities_return_false_rather_than_none():
    options = ArgOptions()
    assert options.strict_file_interactability is False
    assert options.set_window_rect is False
    assert options.accept_insecure_certs is False


text:
package io.netty.channel.unix;

/**
 * Different modes of reading from a {@link DomainSocketChannel}.
 */
public enum DomainSocketReadMode {

    /**
     * Read (@link ByteBuf)s from the {@link DomainSocketChannel}.
     */
    BYTES,

    /**
     * Read (@link FileDscriptor)s from the {@link DomainSocketChannel}.
     */
    FILE_DESCRIPTORS
}


text:
package chen.testchat.bean;

import java.io.Serializable;
import java.util.List;

/**
 * 项目名称:    TestChat
 * 创建人:        陈锦军
 * 创建时间:    2017/1/8      20:38
 * QQ:             1981367757
 */
public class HappyContentData implements Serializable {
        private List<HappyContentBean> data;

        public List<HappyContentBean> getData() {
                return data;
        }

        public void setData(List<HappyContentBean> data) {
                this.data = data;
        }
}


text:
/* jasmine specs for directives go here */

describe('directives', function() {
    'use strict';

    beforeEach(module('myApp.directives'));

    describe('gims-link-new', function() {
        it('should print link to create object', function() {
//  TODO find out how to inject $routeParams
//            inject(function($compile, $rootScope) {
//                var element = $compile('<gims-link-new target="filter"></gims-link-new>')($rootScope);
//                expect(element.text()).toEqual('new filter');
//            });
        });
    });
});


text:
/*
 * Created on Jul 14, 2004
 */
package org.jkiss.dbeaver.ext.erd.layout.algorithm.direct;

import org.eclipse.draw2d.graph.*;
import org.eclipse.gef.NodeEditPart;
import org.eclipse.gef.editparts.AbstractGraphicalEditPart;
import org.eclipse.swt.graphics.Point;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Creates dummy edges between nodes, to be used with NodeJoiningDirectedGraphLayout
 *
 * @author Serge Rider
 */
public class StandaloneNodeConnector {

    private AbstractGraphicalEditPart diagram;

    private NodeList nodeList;
    private EdgeList edgeList;

    public StandaloneNodeConnector(AbstractGraphicalEditPart diagram)
    {
        this.diagram = diagram;
    }

    //private boolean cleanNextTime = false;

    public void visit(DirectedGraph graph)
    {
        this.nodeList = graph.nodes;
        this.edgeList = graph.edges;

        setDummyEdges();
    }

    protected void setDummyEdges()
    {
        //if node count is only one then we don't have to worry about whether
        // the nodes are connected
        if (nodeList.size() > 1) {

            // Order nodes by their connections count
            // Order unconnected nodes by their geometrical size
            Collections.sort(nodeList, new Comparator<Node>() {
                @Override
                public int compare(Node o1, Node o2)
                {
                    final int connCount1 = o2.outgoing.size() + o2.incoming.size();
                    final int connCount2 = o1.outgoing.size() + o1.incoming.size();
                    if (connCount1 == 0 && connCount1 == connCount2) {
                        if (o1.data instanceof NodeEditPart && o2.data instanceof NodeEditPart) {
                            return ((NodeEditPart) o1.data).getFigure().getMinimumSize().height - ((NodeEditPart) o2.data).getFigure().getMinimumSize().height;
                        } else {
                            return 0;
                        }
                    } else {
                        return connCount1 - connCount2;
                    }
                }
            });

            // Find unconnected nodes
            List<Node> unconnectedNodes = new ArrayList<>();
            for (int i = 0; i < nodeList.size(); i++) {
                Node sourceNode = (Node) nodeList.get(i);
                if (sourceNode.outgoing.size() + sourceNode.incoming.size() == 0) {
                    unconnectedNodes.add(sourceNode);
                }
            }

            final int nodeCount = unconnectedNodes.size();
            if (nodeCount > 1) {
                // Connect all unconnected nodes between each other
                final Point diagramSize = diagram.getViewer().getControl().getSize();
                double horizontalRatio = (float)diagramSize.x / (float)diagramSize.y;
                double middleRowSize = Math.sqrt(nodeCount);

                int nodesInLine = (int)(middleRowSize * horizontalRatio) + 1;//(int)Math.sqrt(nodeCount) + 1;

                for (int i = 0; i < nodeCount; i++) {
                    for (int k = 0; k < nodesInLine - 1 && i < nodeCount - 1; k++, i++) {
                        Node sourceNode = unconnectedNodes.get(i);
                        Node targetNode = unconnectedNodes.get(i + 1);

                        Edge edge = new Edge(null, sourceNode, targetNode);
                        edge.weight = 2;
                        edgeList.add(edge);
                    }
                }
            }

        }
    }

}


text:
describe('Documentation service', function() {
  var $scope, Documentation, $httpBackend;

  beforeEach(angular.mock.module('PraxisDocBrowser'));

  beforeEach(inject(function($rootScope, $injector) {
    $httpBackend = $injector.get('$httpBackend');
    $httpBackend.expectGET('api/index-new.json').respond({
      versions: ['1.0', '2.0']
    });
    $httpBackend.expectGET('api/1.0.json').respond({
      resources: {
        foo: {

        }
      },
      schemas: {
        bar: {

        }
      }
    });
    $httpBackend.expectGET('api/2.0.json').respond({
      resources: {
        test: 'TestCTRL'
      },
      schemas: {
        testType: 'TestType'
      }
    });
    $scope = $rootScope.$new();
    Documentation = $injector.get('Documentation');
    $httpBackend.flush();
  }));

  afterEach(function() {
    $httpBackend.verifyNoOutstandingExpectation();
    $httpBackend.verifyNoOutstandingRequest();
  });

  describe('#versions', function() {
    var versions;
    beforeEach(function() {
      Documentation.versions().then(function(v) {
        versions = v;
      });
      $scope.$apply();
    });
    it('returns both versions', function() {
      expect(versions).toEqual(['1.0', '2.0']);
    });
  });

  describe('#items', function() {
    var items;
    beforeEach(function() {
      Documentation.items('1.0').then(function(data) {
        items = data;
      });
      $scope.$apply();
    });

    it('returns all items for 1.0', function() {
      expect(items).toEqual({
        resources: {
          foo: { }
        },
        schemas: {
          bar: {}
        }
      });
    });
  });
  describe('#controller', function() {
    var item;
    beforeEach(function() {
      Documentation.controller('2.0', 'test').then(function(data) {
        item = data;
      });
      $scope.$apply();
    });

    it('returns all items for 1.0', function() {
      expect(item).toEqual('TestCTRL');
    });
  });
  describe('#type', function() {
    var item;
    beforeEach(function() {
      Documentation.type('2.0', 'testType').then(function(data) {
        item = data;
      });
      $scope.$apply();
    });

    it('returns all items for 1.0', function() {
      expect(item).toEqual('TestType');
    });
  });
});


text:
Fabricator(:pricelist) do
  valid_from 1.year.ago
  valid_to 1.year.since
  category 'ee'
  duration '1year'
  operation_category 'create'
  price 10
end


text:
var parent = require('../../stable/typed-array/slice');

module.exports = parent;


text:
@interface CTViewController ()

@end

@implementation CTViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
}

- (void)click:(id)sender{

    [self presentViewController:[[CTTestViewController alloc]init] animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


text:
module ActionView
  # The TemplateError exception is raised when the compilation of the template fails. This exception then gathers a
  # bunch of intimate details and uses it to report a very precise exception message.
  class TemplateError < ActionViewError #:nodoc:
    SOURCE_CODE_RADIUS = 3

    attr_reader :original_exception

    def initialize(base_path, file_name, assigns, source, original_exception)
      @base_path, @assigns, @source, @original_exception =
        base_path, assigns, source, original_exception
      @file_name = file_name
    end

    def message
      original_exception.message
    end

    def sub_template_message
      if @sub_templates
        "Trace of template inclusion: " +
        @sub_templates.collect { |template| strip_base_path(template) }.join(", ")
      else
        ""
      end
    end

    def source_extract(indention = 0)
      source_code = IO.readlines(@file_name)

      start_on_line = [ line_number - SOURCE_CODE_RADIUS - 1, 0 ].max
      end_on_line   = [ line_number + SOURCE_CODE_RADIUS - 1, source_code.length].min

      line_counter = start_on_line
      extract = source_code[start_on_line..end_on_line].collect do |line|
        line_counter += 1
        "#{' ' * indention}#{line_counter}: " + line
      end

      extract.join
    end

    def sub_template_of(file_name)
      @sub_templates ||= []
      @sub_templates << file_name
    end

    def line_number
      if file_name
        regexp = /#{Regexp.escape File.basename(file_name)}:(\d+)/
        [@original_exception.message, @original_exception.clean_backtrace].flatten.each do |line|
          return $1.to_i if regexp =~ line
        end
      end
      0
    end

    def file_name
      stripped = strip_base_path(@file_name)
      stripped[0] == ?/ ? stripped[1..-1] : stripped
    end

    def to_s
      "\n\n#{self.class} (#{message}) on line ##{line_number} of #{file_name}:\n" +
      source_extract + "\n    " +
      original_exception.clean_backtrace.join("\n    ") +
      "\n\n"
    end

    def backtrace
      [
        "On line ##{line_number} of #{file_name}\n\n#{source_extract(4)}\n    " +
        original_exception.clean_backtrace.join("\n    ")
      ]
    end

    private
      def strip_base_path(file_name)
        file_name = File.expand_path(file_name).gsub(/^#{Regexp.escape File.expand_path(RAILS_ROOT)}/, '')
        file_name.gsub(@base_path, "")
      end
  end
end

Exception::TraceSubstitutions << [/:in\s+`_run_(html|xml).*'\s*$/, ''] if defined?(Exception::TraceSubstitutions)
Exception::TraceSubstitutions << [%r{^\s*#{Regexp.escape RAILS_ROOT}}, '#{RAILS_ROOT}'] if defined?(RAILS_ROOT)


text:
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;

public class Dpad : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IDragHandler
{

	public RectTransform directionalPad;
	public PlayerMovement player;
	public PlayerAnimation anim;

	public AudioClip gunShot;
	public AudioSource source;

	int moveRange = 80;
	int baseX;
	int baseY;
	bool isPointerDown = false;

	// Use this for initialization
	void Start ()
	{
		baseX = (int)directionalPad.position.x;
		baseY = (int)directionalPad.position.y;
	}

	// Update is called once per frame
	void Update ()
	{
		if (isPointerDown) {
			UpdatePlayer ();
		}

		if (Input.GetKeyDown (KeyCode.X)) {
			OnShootButton ();
		}

		if (Input.GetKeyDown (KeyCode.Z)) {
			OnJumpButton ();
		}
	}

	public void OnJumpButton ()
	{
		player.Jump ();
	}

	public void OnShootButton ()
	{
		if (gunShot != null && source != null)
			source.PlayOneShot (gunShot);
	}

	public void OnDrag (PointerEventData data)
	{
		UpdateButtonPosition (data);
	}

	public void OnPointerUp (PointerEventData data)
	{
		isPointerDown = false;
		directionalPad.anchoredPosition = Vector2.zero;
		player.UpdateAim (0);
		player.Stop ();
		anim.StopMovement (directionalPad.anchoredPosition);
	}

	public void OnPointerDown (PointerEventData data)
	{
		isPointerDown = true;
		UpdateButtonPosition (data);
	}

	private void UpdateButtonPosition (PointerEventData data)
	{
		Vector2 newPos = Vector2.zero;
		int delta = (int)(data.position.x - baseX);
		delta = Mathf.Clamp (delta, -moveRange, moveRange);
		newPos.x = delta;
		delta = (int)(data.position.y - baseY);
		delta = Mathf.Clamp (delta, -moveRange, moveRange);
		newPos.y = delta;
		directionalPad.anchoredPosition = newPos;
	}

	private float GetAngle ()
	{
		float angle = Vector2.Angle (Vector2.right, directionalPad.anchoredPosition);
		if (angle > 90) {
			angle = 180 - angle;
		}
		if (directionalPad.anchoredPosition.y < 0)
			angle = -angle;
		return angle;
	}

	private void UpdatePlayer ()
	{
		//if (directionalPad.anchoredPosition.x < 0){
		//	player.MoveLeft (-directionalPad.anchoredPosition.x / 80);
		//} else if (directionalPad.anchoredPosition.x > 0) {
		//	player.MoveRight (directionalPad.anchoredPosition.x / 80);
		//}
		//player.UpdateAim (GetAngle ());
		//anim.StartWalking ();
	}

}


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>upkeeper: mainpage.doc File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>

upkeeper 1

Main Page

Modules

Data Structures

Files

File List

Globals

mainpage.doc File Reference

<address class="footer">Generated on Wed Dec 7 2011 for upkeeper by

 1.7.4 </address>


text:
<?php
class mtmdImage {

    /** Format constants. */
    const PORTRAIT = 1;
    const LANDSCAPE = 2;

    /** EXIF orientation constants. */
    const ORIENTATION_ORIGINAL                        = 1;
    const ORIENTATION_FLIP_HORIZONTAL                 = 2;
    const ORIENTATION_ROTATE_180_LEFT                 = 3;
    const ORIENTATION_FLIP_VERTICAL                   = 4;
    const ORIENTATION_FLIP_VERTICAL_ROTATE_90_RIGHT   = 5;
    const ORIENTATION_ROTATE_90_RIGHT                 = 6;
    const ORIENTATION_FLIP_HORIZONTAL_ROTATE_90_RIGHT = 7;
    const ORIENTATION_ROTATE_90_LEFT                  = 8;

    /** File info properties. */
    protected $fileName      = '';
    protected $size          = 0;
    protected $width         = 0;
    protected $height        = 0;
    protected $imageType     = null;
    protected $mimeType      = 0;
    protected $bitDepth      = 0;
    protected $channels      = 0;
    protected $format        = null;
    protected $thumbFileName = '';
    protected $thumbWidth    = 0;
    protected $thumbHeight   = 0;
    protected $exifData      = array();
    protected $orientation   = self::ORIENTATION_ORIGINAL;

    /**
     * Constructor.
     *
     * @param string $file
     *
     * @throws Exception
     */
    public function __construct($file)
    {
        if (empty($file)) {
            throw new Exception('Please provide a file!');
        }
        if (!file_exists($file)) {
            throw new Exception('File does not exist!');
        }
        $this->fileName = $file;

        $this->initialize();

    }

    private function initialize()
    {
        $this->getFileInfo();

    }

    /**
     * Determine all file info.
     *
     * @return void
     */
    private function getFileInfo()
    {
        $info            = getimagesize($this->fileName);
        $this->size      = filesize($this->fileName);
        if ($info !== false) {
            $this->width     = $info[0];
            $this->height    = $info[1];
            $this->imageType = $info[2];
            $this->bitDepth  = $info['bits'];
            if (array_key_exists('channels', $info)) {
                $this->channels  = $info['channels'];
            }
        }
        $this->mimeType  = $info['mime'];
        $this->format    = $this->determineFormat();

        if ($this->getType() === IMAGETYPE_JPEG) {
            $this->setExifData();
        }

    }

    /**
     * Sets EXIF orientation.
     *
     * @return void
     */
    private function setExifOrientation()
    {
        if (!array_key_exists('Orientation', $this->exifData)) {
            $this->orientation = self::ORIENTATION_ORIGINAL;
        }

        switch ($this->exifData['Orientation']) {
            case self::ORIENTATION_FLIP_HORIZONTAL:
                $this->orientation = self::ORIENTATION_FLIP_HORIZONTAL;
                break;
            case self::ORIENTATION_ROTATE_180_LEFT:
                $this->orientation = self::ORIENTATION_ROTATE_180_LEFT;
                break;
            case self::ORIENTATION_FLIP_VERTICAL:
                $this->orientation = self::ORIENTATION_FLIP_VERTICAL;
                break;
            case self::ORIENTATION_FLIP_VERTICAL_ROTATE_90_RIGHT:
                $this->orientation = self::ORIENTATION_FLIP_VERTICAL_ROTATE_90_RIGHT;
                break;
            case self::ORIENTATION_ROTATE_90_RIGHT:
                $this->orientation = self::ORIENTATION_ROTATE_90_RIGHT;
                break;
            case self::ORIENTATION_FLIP_HORIZONTAL_ROTATE_90_RIGHT:
                $this->orientation = self::ORIENTATION_FLIP_HORIZONTAL_ROTATE_90_RIGHT;
                break;
            case self::ORIENTATION_ROTATE_90_LEFT:
                $this->orientation = self::ORIENTATION_ROTATE_90_LEFT;
                break;
            default:
                $this->orientation = self::ORIENTATION_ORIGINAL;
                break;
        }

    }

    /**
     * Rotates/Flips image resource if necessary using EXIF data. If no EXIF data present nothing will be done.
     *
     * @param resource $imageResource
     *
     * @return resource
     */
    private function rotateOrFlip($imageResource)
    {
        $retResource = $imageResource;

        switch ($this->getOrientation()) {
            case self::ORIENTATION_FLIP_HORIZONTAL:
                $this->flip($imageResource);
                break;
            case self::ORIENTATION_ROTATE_180_LEFT:
                $retResource = imagerotate($imageResource, 180, -1);
                break;
            case self::ORIENTATION_FLIP_VERTICAL:
                $this->flip($imageResource);
                break;
            case self::ORIENTATION_FLIP_VERTICAL_ROTATE_90_RIGHT:
                $this->flip($imageResource);
                $retResource = imagerotate($imageResource, -90, -1);
                break;
            case self::ORIENTATION_ROTATE_90_RIGHT:
                $retResource = imagerotate($imageResource, -90, -1);
                break;
            case self::ORIENTATION_FLIP_HORIZONTAL_ROTATE_90_RIGHT:
                $this->flip($imageResource);
                $retResource = imagerotate($imageResource, -90, -1);
                break;
            case self::ORIENTATION_ROTATE_90_LEFT:
                $retResource = imagerotate($imageResource, 90, -1);
                break;
        }

        if ($retResource === false) {
            return $imageResource;
        }
        return $retResource;

    }

    /**
     * Flip image (UNTESTED)!!!
     *
     * @param resource $imageResource
     * @param int      $x
     * @param int      $y
     * @param null     $width
     * @param null     $height
     *
     * @return bool
     */
    private function flip(&$imageResource, $x = 0, $y = 0, $width = null, $height = null)
    {
        mtmdUtils::output('FLIPPING!');
        if ($width  < 1) {
            $width  = imagesx($imageResource);
        }
        if ($height < 1) {
            $height = imagesy($imageResource);
        }

        // Truecolor provides better results, if possible.
        if (function_exists('imageistruecolor') && imageistruecolor($imageResource)) {
            $tmp = imagecreatetruecolor(1, $height);
        } else {
            $tmp = imagecreate(1, $height);
        }

        $x2 = $x + $width - 1;

        for ($i = (int)floor(($width - 1) / 2); $i >= 0; $i--)
        {
            // Backup right stripe.
            imagecopy($tmp, $imageResource, 0, 0, $x2 - $i, $y, 1, $height);

            // Copy left stripe to the right.
            imagecopy($imageResource, $imageResource, $x2 - $i, $y, $x + $i, $y, 1, $height);

            // Copy backuped right stripe to the left.
            imagecopy($imageResource, $tmp, $x + $i,  $y, 0, 0, 1, $height);
        }

        imagedestroy($tmp);

        return true;
    }

    /**
     * Return exif data array.
     *
     * @return array
     */
    private function setExifData()
    {
        $this->exifData = exif_read_data($this->getFileName());

        if (array_key_exists('COMPUTED', $this->exifData)) {
            $exifWidth = $this->getWidth();
            if (array_key_exists('Width', $this->exifData['COMPUTED'])) {
                $exifWidth = $this->exifData['COMPUTED']['Width'];
            }
            $exifHeight = $this->getHeight();
            if (array_key_exists('Height', $this->exifData['COMPUTED'])) {
                $exifWidth = $this->exifData['COMPUTED']['Height'];
            }

            if ($exifWidth != $this->getWidth() && $exifHeight != $this->getHeight()) {
                $this->width = $exifWidth;
                $this->height = $exifHeight;
                $this->format = self::PORTRAIT;
                if ($this->getWidth() > $this->getHeight()) {
                    $this->format = self::LANDSCAPE;
                }
            }
        }

        $this->setExifOrientation();

    }

    /**
     * Determine format landscape/portrait.
     *
     * @return int
     */
    public function determineFormat()
    {
        if ( $this->getWidth() > $this->getHeight() ) {
            return self::LANDSCAPE;
        }
        return self::PORTRAIT;

    }

    /**
     * Create a new image instance using proper imagecreatefrom method.
     *
     * @return resource
     */
    private function createImage()
    {
        switch($this->getType()) {
            case IMAGETYPE_JPEG:
                return imagecreatefromjpeg($this->getFileName());
            case IMAGETYPE_GIF:
                return imagecreatefromgif($this->getFileName());
            case IMAGETYPE_PNG:
                return imagecreatefrompng($this->getFileName());
        }
    }

    /**
     * Resize image using width/height and orientation information and saves it to cache folder.
     *
     * @param string  $dstPath
     * @param integer $width
     * @param integer $height
     *
     * @return void
     */
    public function resizeImage($dstPath, $width, $height)
    {
        $cacheFile = $dstPath.DIRECTORY_SEPARATOR.basename($this->getFileName());

        // Handle regular measures.
        $measures = $this->getNewMeasures($width, $height);

        // Set thumbnail stuff.
        $this->thumbFileName = $cacheFile;
        $this->thumbWidth    = $measures[0];
        $this->thumbHeight   = $measures[1];

        // Correct possible orientation flaws (There seems to be a bug in some images regarding EXIF orientation marks).
        $this->setMeasuresByOrientation();

        // Once file is there don't generate it again.
        if (file_exists($cacheFile)) {
            return;
        }

        $oldFile = $this->createImage();
        $oldFile = $this->rotateOrFlip($oldFile);

        // In case of orientation change determine correct measures.
        $newFile = imagecreatetruecolor($this->getThumbWidth(), $this->getThumbHeight());

        imagecopyresampled(
            $newFile,
            $oldFile,
            0,
            0,
            0,
            0,
            $this->getThumbWidth(),
            $this->getThumbHeight(),
            $this->getWidth(),
            $this->getHeight()
        );

        $this->saveImage($newFile, $dstPath);
        imagedestroy($oldFile);
        imagedestroy($newFile);

    }

    /**
     * Calculate new measures of thumbnail.
     *
     * @param integer $width
     * @param integer $height
     *
     * @return array Array containing width/height
     */
    private function getNewMeasures($width, $height)
    {
        $newWidth = $width;
        $newHeight = $height;
        if ($this->getWidth() > $this->getHeight() && $height < $this->getHeight()) {
            $newHeight = $this->getHeight() / ($this->getWidth() / $width);
        } else if ($this->getWidth() < $this->getHeight() && $width < $this->getWidth()) {
            $newWidth = $this->getWidth() / ($this->getHeight() / $height);
        } else if ($this->getWidth() == $this->getHeight()) {
            if ($width > $height) {
                $newHeight = $width;
            }
        } else {
            $newWidth = $this->getWidth();
            $newHeight = $this->getHeight();
        }

        // Take format type into account.
        if ($this->getFormat() === self::LANDSCAPE) {
            if ($newWidth < $newHeight) {
                return array(
                    $newHeight,
                    $newWidth
                );
            }
        } else if ($this->getFormat() === self::PORTRAIT) {
            if ($newHeight < $width) {
                $newHeight = $width;
                $newWidth = $this->getWidth() / ($this->getHeight() / $newHeight);
            }
        }

        return array(
            $newWidth,
            $newHeight
        );

    }

    /**
     * Sets measures internally dependant to image orientation.
     *
     * @return void
     */
    private function setMeasuresByOrientation()
    {
        // Set to default.
        $thumbWidth     = $this->getThumbWidth();
        $thumbHeight    = $this->getThumbHeight();
        $originalWidth  = $this->getWidth();
        $originalHeight = $this->getHeight();

        switch ($this->getOrientation()) {
            // Orientations that do not need a measure change.
            case self::ORIENTATION_FLIP_HORIZONTAL:
            case self::ORIENTATION_ROTATE_180_LEFT:
            case self::ORIENTATION_FLIP_VERTICAL:
                break;
            // Orientations that need flipping of measures.
            case self::ORIENTATION_FLIP_VERTICAL_ROTATE_90_RIGHT:
            case self::ORIENTATION_ROTATE_90_RIGHT:
            case self::ORIENTATION_FLIP_HORIZONTAL_ROTATE_90_RIGHT:
            case self::ORIENTATION_ROTATE_90_LEFT:
                // Interchange measures.
                $thumbWidth     = $this->getThumbHeight();
                $thumbHeight    = $this->getThumbWidth();
                $originalWidth  = $this->getHeight();
                $originalHeight = $this->getWidth();
                break;
            // Original.
            default:
                break;
        }

        // Write to properties.
        $this->thumbWidth  = $thumbWidth;
        $this->thumbHeight = $thumbHeight;
        $this->width       = $originalWidth;
        $this->height      = $originalHeight;

    }

    /**
     * Saves image instance as new file to destination/cache folder.
     *
     * @param resource $newFile
     * @param string   $dstPath
     *
     * @return void
     */
    private function saveImage($newFile, $dstPath)
    {
        $dstPath = $dstPath.DIRECTORY_SEPARATOR.basename($this->getFileName());

        switch($this->getType()) {
            case IMAGETYPE_JPEG:
                imagejpeg($newFile, $dstPath);
                break;
            case IMAGETYPE_GIF:
                imagegif($newFile, $dstPath);
                break;
            case IMAGETYPE_PNG:
                imagepng($newFile, $dstPath);
                break;
        }
        return;

    }

    public function getFileName()
    {
        return $this->fileName;
    }

    public function getSize()
    {
        return $this->size;
    }

    public function getWidth()
    {
        return $this->width;
    }

    public function getHeight()
    {
        return $this->height;
    }

    public function getType()
    {
        return $this->imageType;
    }

    public function getMimeType()
    {
        return $this->mimeType;
    }

    public function getChannels()
    {
        return $this->channels;
    }

    public function getBitDepth()
    {
        return $this->bitDepth;
    }

    public function getFormat()
    {
        return $this->format;
    }

    public function getThumbFileName()
    {
        return $this->thumbFileName;
    }

    public function getThumbWidth()
    {
        return $this->thumbWidth;
    }

    public function getThumbHeight()
    {
        return $this->thumbHeight;
    }

    public function getOrientation()
    {
        return $this->orientation;
    }

}


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

class Amenities_model extends CI_Model{

	public function __construct()	{
		parent::__construct();
	}
	public function list_amenities($search,$start=FALSE,$show_by=FALSE){
		$this->db->like('name_am',$search);
		if ($start !== FALSE && $show_by !== FALSE) {
			$this->db->limit($show_by,$start);
		}
		$this->db->order_by('id','DESC');
		$query=$this->db->get('amenities');
		$amenities=$query->result();
		return $amenities;
	}

	public function filter_amenities(){
		$this->db->select("amenities.id,amenities.name_am,detail_tram.typeroom_id,detail_tram.amenity_id");
		$this->db->join('amenities','detail_tram.amenity_id=amenities.id','inner');
		$query=$this->db->get('detail_tram');
		$amenities=$query->result();
		return $amenities;
	}

	public function add($data){
		$this->db->insert('amenities',$data);
	}
	public function show_amenity($id){
		$this->db->where('id',$id);
		$query=$this->db->get('amenities');
		$author=$query->row();
		return $author;
	}
	public function update_amenity($id,$data){
		$this->db->where('id',$id);
		$this->db->update('amenities',$data);
	}

	public function delete_amenity($id){
   		$this->db->where(array('id'=>$id));
   		$this->db->delete('amenities');

   }

}


text:
/*
 *= require formtastic_ie7
*/


text:
import React from 'react'
import PropsList from 'private/modules/PropsList'
import tabWrapperDocs from '!!docgen!react-ions/lib/components/TabWrapper/TabWrapper'
import tabDocs from '!!docgen!react-ions/lib/components/TabWrapper/Tab'
import CodeExample from 'private/modules/CodeExample'
import styles from 'private/css/content'
import ExampleTabWrapperDefault from './ExampleTabWrapperDefault'
import exampleTabWrapperDefaultCode from '!raw!./ExampleTabWrapperDefault'
import ExampleTabWrapperSecondary from './ExampleTabWrapperSecondary'
import exampleTabWrapperSecondaryCode from '!raw!./ExampleTabWrapperSecondary'
import ExampleTabWrapperTitlePrefix from './ExampleTabWrapperTitlePrefix'
import exampleTabWrapperTitlePrefixCode from '!raw!./ExampleTabWrapperTitlePrefix'

const TabWrapperPage = () => (

        <CodeExample
          title='Default Tabs'
          markup={exampleTabWrapperDefaultCode}>
          <ExampleTabWrapperDefault />
        </CodeExample>
        <CodeExample
          title='Secondary tab style'
          markup={exampleTabWrapperSecondaryCode}>
          <ExampleTabWrapperSecondary />
        </CodeExample>
        <CodeExample
          title='Prefixed and Suffixed Tabs'
          markup={exampleTabWrapperTitlePrefixCode}>
          <ExampleTabWrapperTitlePrefix />
        </CodeExample>

Tab Wrapper Props

          <PropsList list={tabWrapperDocs[0].props} />

Tab Props

          <PropsList list={tabDocs[0].props} />

)

export default TabWrapperPage


text:
using Ninject.Extensions.Factory;
using Ninject.Modules;
using SmartHive.Factories;
using SmartHive.Web.Factories;

namespace SmartHive.Web.App_Start.NinjectModules
{
    public class FactoriesNinjectModule : NinjectModule
    {
        public override void Load()
        {
            //Models factories
            this.Bind<IUserFactory>().ToFactory().InSingletonScope();
            this.Bind<IHiveFactory>().ToFactory().InSingletonScope();

            //View models
            this.Bind<IViewModelFactory>().ToFactory().InSingletonScope();
        }
    }
}


text:
namespace System.ServiceModel.Channels
{
    using System.Collections.ObjectModel;
    using System.Diagnostics;
    using System.Globalization;
    using System.IdentityModel.Policy;
    using System.IdentityModel.Selectors;
    using System.IdentityModel.Tokens;
    using System.Net;
    using System.Runtime;
    using System.Security.Cryptography.X509Certificates;
    using System.Security.Principal;
    using System.ServiceModel;
    using System.ServiceModel.Activation;
    using System.ServiceModel.Description;
    using System.ServiceModel.Diagnostics;
    using System.ServiceModel.Security;

    class HttpsChannelListener<TChannel> : HttpChannelListener<TChannel>
                        where TChannel : class, IChannel
    {
        readonly bool useCustomClientCertificateVerification;
        bool shouldValidateClientCertificate;
        bool useHostedClientCertificateMapping;
        bool requireClientCertificate;
        SecurityTokenAuthenticator certificateAuthenticator;
        const HttpStatusCode CertificateErrorStatusCode = HttpStatusCode.Forbidden;
        IChannelBindingProvider channelBindingProvider;

        public HttpsChannelListener(HttpsTransportBindingElement httpsBindingElement, BindingContext context)
            : base(httpsBindingElement, context)
        {
            this.requireClientCertificate = httpsBindingElement.RequireClientCertificate;
            this.shouldValidateClientCertificate = ShouldValidateClientCertificate(this.requireClientCertificate, context);

            // Pick up the MapCertificateToWindowsAccount setting from the configured token authenticator.
            SecurityCredentialsManager credentialProvider =
                context.BindingParameters.Find<SecurityCredentialsManager>();
            if (credentialProvider == null)
            {
                credentialProvider = ServiceCredentials.CreateDefaultCredentials();
            }
            SecurityTokenManager tokenManager = credentialProvider.CreateSecurityTokenManager();
            this.certificateAuthenticator =
                    TransportSecurityHelpers.GetCertificateTokenAuthenticator(tokenManager, context.Binding.Scheme,
                    TransportSecurityHelpers.GetListenUri(context.ListenUriBaseAddress, context.ListenUriRelativeAddress));

            ServiceCredentials serviceCredentials = credentialProvider as ServiceCredentials;

            if (serviceCredentials != null &&
                serviceCredentials.ClientCertificate.Authentication.CertificateValidationMode == X509CertificateValidationMode.Custom)
            {
                useCustomClientCertificateVerification = true;
            }
            else
            {
                useCustomClientCertificateVerification = false;

                X509SecurityTokenAuthenticator authenticator = this.certificateAuthenticator as X509SecurityTokenAuthenticator;

                if (authenticator != null)
                {
                    this.certificateAuthenticator = new X509SecurityTokenAuthenticator(X509CertificateValidator.None,
                        authenticator.MapCertificateToWindowsAccount, this.ExtractGroupsForWindowsAccounts, false);
                }
            }

            if (this.RequireClientCertificate &&
                this.AuthenticationScheme.IsNotSet(AuthenticationSchemes.Anonymous))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelper(new InvalidOperationException(SR.GetString(
                    SR.HttpAuthSchemeAndClientCert, this.AuthenticationScheme)), TraceEventType.Error);
            }

            this.channelBindingProvider = new ChannelBindingProviderHelper();
        }

        public bool RequireClientCertificate
        {
            get
            {
                return this.requireClientCertificate;
            }
        }

        public override string Scheme
        {
            get
            {
                return Uri.UriSchemeHttps;
            }
        }

        public override bool IsChannelBindingSupportEnabled
        {
            get
            {
                return this.channelBindingProvider.IsChannelBindingSupportEnabled;
            }
        }

        internal override UriPrefixTable<ITransportManagerRegistration> TransportManagerTable
        {
            get
            {
                return SharedHttpsTransportManager.StaticTransportManagerTable;
            }
        }

        public override T GetProperty<T>()
        {
            if (typeof(T) == typeof(IChannelBindingProvider))
            {
                return (T)(object)this.channelBindingProvider;
            }

            return base.GetProperty<T>();
        }

        internal override void ApplyHostedContext(string virtualPath, bool isMetadataListener)
        {
            base.ApplyHostedContext(virtualPath, isMetadataListener);
            useHostedClientCertificateMapping = AspNetEnvironment.Current.ValidateHttpsSettings(virtualPath, ref this.requireClientCertificate);

            // We want to validate the certificate if IIS is set to require a client certificate
            if (this.requireClientCertificate)
            {
                this.shouldValidateClientCertificate = true;
            }
        }

        internal override ITransportManagerRegistration CreateTransportManagerRegistration(Uri listenUri)
        {
            return new SharedHttpsTransportManager(listenUri, this);
        }

        // Note: the returned SecurityMessageProperty has ownership of certificate and identity.
        SecurityMessageProperty CreateSecurityProperty(X509Certificate2 certificate, WindowsIdentity identity, string authType)
        {
            SecurityToken token;
            if (identity != null)
            {
                token = new X509WindowsSecurityToken(certificate, identity, authType, false);
            }
            else
            {
                token = new X509SecurityToken(certificate, false);
            }

            ReadOnlyCollection<IAuthorizationPolicy> policies = this.certificateAuthenticator.ValidateToken(token);
            SecurityMessageProperty result = new SecurityMessageProperty();
            result.TransportToken = new SecurityTokenSpecification(token, policies);
            result.ServiceSecurityContext = new ServiceSecurityContext(policies);
            return result;
        }

        public override SecurityMessageProperty ProcessAuthentication(IHttpAuthenticationContext authenticationContext)
        {
            if (this.shouldValidateClientCertificate)
            {
                SecurityMessageProperty retValue;
                X509Certificate2 certificate = null;

                try
                {
                    bool isCertificateValid;
                    certificate = authenticationContext.GetClientCertificate(out isCertificateValid);
                    Fx.Assert(!this.requireClientCertificate || certificate != null, "ClientCertificate must be present");

                    if (certificate != null)
                    {
                        if (!this.useCustomClientCertificateVerification)
                        {
                            Fx.Assert(isCertificateValid, "ClientCertificate must be valid");
                        }

                        WindowsIdentity identity = null;
                        string authType = base.GetAuthType(authenticationContext);

                        if (this.useHostedClientCertificateMapping)
                        {
                            identity = authenticationContext.LogonUserIdentity;
                            if (identity == null || !identity.IsAuthenticated)
                            {
                                identity = WindowsIdentity.GetAnonymous();
                            }
                            else
                            {
                                // it is not recommended to call identity.AuthenticationType as this is a privileged instruction.
                                // when the identity is cloned, it will be created with an authtype indicating WindowsIdentity from a cert.
                                identity = SecurityUtils.CloneWindowsIdentityIfNecessary(identity, SecurityUtils.AuthTypeCertMap);
                                authType = SecurityUtils.AuthTypeCertMap;
                            }
                        }

                        retValue = CreateSecurityProperty(certificate, identity, authType);
                    }
                    else if (this.AuthenticationScheme == AuthenticationSchemes.Anonymous)
                    {
                        return new SecurityMessageProperty();
                    }
                    else
                    {
                        return base.ProcessAuthentication(authenticationContext);
                    }
                }
#pragma warning suppress 56500 // covered by FXCop
                catch (Exception exception)
                {
                    if (Fx.IsFatal(exception))
                        throw;

                    // Audit Authentication failure
                    if (AuditLevel.Failure == (this.AuditBehavior.MessageAuthenticationAuditLevel & AuditLevel.Failure))
                        WriteAuditEvent(AuditLevel.Failure, (certificate != null) ? SecurityUtils.GetCertificateId(certificate) : String.Empty, exception);

                    throw;
                }

                // Audit Authentication success
                if (AuditLevel.Success == (this.AuditBehavior.MessageAuthenticationAuditLevel & AuditLevel.Success))
                    WriteAuditEvent(AuditLevel.Success, (certificate != null) ? SecurityUtils.GetCertificateId(certificate) : String.Empty, null);

                return retValue;
            }
            else if (this.AuthenticationScheme == AuthenticationSchemes.Anonymous)
            {
                return new SecurityMessageProperty();
            }
            else
            {
                return base.ProcessAuthentication(authenticationContext);
            }
        }

        public override SecurityMessageProperty ProcessAuthentication(HttpListenerContext listenerContext)
        {
            if (this.shouldValidateClientCertificate)
            {
                SecurityMessageProperty retValue;
                X509Certificate2 certificateEx = null;

                try
                {
                    X509Certificate certificate = listenerContext.Request.GetClientCertificate();
                    Fx.Assert(!this.requireClientCertificate || certificate != null,
                        "HttpListenerRequest.ClientCertificate is not present");

                    if (certificate != null)
                    {
                        if (!useCustomClientCertificateVerification)
                        {
                            Fx.Assert(listenerContext.Request.ClientCertificateError == 0,
                                "HttpListenerRequest.ClientCertificate is not valid");
                        }
                        certificateEx = new X509Certificate2(certificate);
                        retValue = CreateSecurityProperty(certificateEx, null, string.Empty);
                    }
                    else if (this.AuthenticationScheme == AuthenticationSchemes.Anonymous)
                    {
                        return new SecurityMessageProperty();
                    }
                    else
                    {
                        return base.ProcessAuthentication(listenerContext);
                    }
                }
#pragma warning suppress 56500 // covered by FXCop
                catch (Exception exception)
                {
                    if (Fx.IsFatal(exception))
                        throw;

                    // Audit Authentication failure
                    if (AuditLevel.Failure == (this.AuditBehavior.MessageAuthenticationAuditLevel & AuditLevel.Failure))
                        WriteAuditEvent(AuditLevel.Failure, (certificateEx != null) ? SecurityUtils.GetCertificateId(certificateEx) : String.Empty, exception);

                    throw;
                }

                // Audit Authentication success
                if (AuditLevel.Success == (this.AuditBehavior.MessageAuthenticationAuditLevel & AuditLevel.Success))
                    WriteAuditEvent(AuditLevel.Success, (certificateEx != null) ? SecurityUtils.GetCertificateId(certificateEx) : String.Empty, null);

                return retValue;
            }
            else if (this.AuthenticationScheme == AuthenticationSchemes.Anonymous)
            {
                return new SecurityMessageProperty();
            }
            else
            {
                return base.ProcessAuthentication(listenerContext);
            }
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage(FxCop.Category.ReliabilityBasic, "Reliability103",
                            Justification = "The exceptions are wrapped already.")]
        public override HttpStatusCode ValidateAuthentication(IHttpAuthenticationContext authenticationContext)
        {
            HttpStatusCode result = base.ValidateAuthentication(authenticationContext);
            if (result == HttpStatusCode.OK)
            {
                if (this.shouldValidateClientCertificate)
                {
                    bool isValidCertificate;
                    X509Certificate2 clientCertificate = authenticationContext.GetClientCertificate(out isValidCertificate);
                    if (clientCertificate == null)
                    {
                        if (this.RequireClientCertificate)
                        {
                            if (DiagnosticUtility.ShouldTraceError)
                            {
                                TraceUtility.TraceEvent(TraceEventType.Error, TraceCode.HttpsClientCertificateNotPresent, SR.GetString(SR.TraceCodeHttpsClientCertificateNotPresent),
                                    authenticationContext.CreateTraceRecord(), this, null);
                            }
                            result = CertificateErrorStatusCode;
                        }
                    }
                    else if (!isValidCertificate && !this.useCustomClientCertificateVerification)
                    {
                        if (DiagnosticUtility.ShouldTraceError)
                        {
                            TraceUtility.TraceEvent(TraceEventType.Error, TraceCode.HttpsClientCertificateInvalid, SR.GetString(SR.TraceCodeHttpsClientCertificateInvalid),
                                authenticationContext.CreateTraceRecord(), this, null);
                        }
                        result = CertificateErrorStatusCode;
                    }

                    // Audit Authentication failure
                    if (result != HttpStatusCode.OK && (AuditLevel.Failure == (this.AuditBehavior.MessageAuthenticationAuditLevel & AuditLevel.Failure)))
                    {
                        string message = SR.GetString(SR.HttpAuthenticationFailed, this.AuthenticationScheme, result);
                        Exception exception = DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(message));
                        WriteAuditEvent(AuditLevel.Failure, (clientCertificate != null) ? SecurityUtils.GetCertificateId(clientCertificate) : String.Empty, exception);
                    }
                }
            }

            return result;
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage(FxCop.Category.ReliabilityBasic, "Reliability103",
                            Justification = "The exceptions are wrapped already.")]
        public override HttpStatusCode ValidateAuthentication(HttpListenerContext listenerContext)
        {
            HttpStatusCode result = base.ValidateAuthentication(listenerContext);
            if (result == HttpStatusCode.OK)
            {
                if (this.shouldValidateClientCertificate)
                {
                    HttpListenerRequest request = listenerContext.Request;
                    X509Certificate2 certificateEx = request.GetClientCertificate();
                    if (certificateEx == null)
                    {
                        if (this.RequireClientCertificate)
                        {
                            if (DiagnosticUtility.ShouldTraceWarning)
                            {
                                TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.HttpsClientCertificateNotPresent,
                                    SR.GetString(SR.TraceCodeHttpsClientCertificateNotPresent),
                                    new HttpListenerRequestTraceRecord(listenerContext.Request), this, null);
                            }
                            result = CertificateErrorStatusCode;
                        }
                    }
                    else if (request.ClientCertificateError != 0 && !useCustomClientCertificateVerification)
                    {
                        if (DiagnosticUtility.ShouldTraceWarning)
                        {
                            TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.HttpsClientCertificateInvalid,
                                SR.GetString(SR.TraceCodeHttpsClientCertificateInvalid1, "0x" + (request.ClientCertificateError & 65535).ToString("X", CultureInfo.InvariantCulture)),
                                new HttpListenerRequestTraceRecord(listenerContext.Request), this, null);
                        }
                        result = CertificateErrorStatusCode;
                    }

                    // Audit Authentication failure
                    if (result != HttpStatusCode.OK && (AuditLevel.Failure == (this.AuditBehavior.MessageAuthenticationAuditLevel & AuditLevel.Failure)))
                    {
                        string message = SR.GetString(SR.HttpAuthenticationFailed, this.AuthenticationScheme, result);
                        Exception exception = DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(message));
                        WriteAuditEvent(AuditLevel.Failure, (certificateEx != null) ? SecurityUtils.GetCertificateId(certificateEx) : String.Empty, exception);
                    }
                }
            }
            return result;
        }

        private static bool ShouldValidateClientCertificate(bool requireClientCertificateValidation, BindingContext context)
        {
            if (requireClientCertificateValidation)
            {
                return true;
            }

            return EndpointSettings.GetValue<bool>(context, EndpointSettings.ValidateOptionalClientCertificates, false);
        }
    }
}


text:
'use strict';
var Point = require('../prefabs/point');

function GameData(object) {
  this.startPoint = object.startPoint;
  this.endPoint = object.endPoint;
  this.points = object.points;
  this.image = object.image;
  this.name = object.name;
  this.boyCongratulatoryStrings = object.boyCongratulatoryStrings;
  this.girlCongratulatoryStrings = object.girlCongratulatoryStrings;

  if (object.wrongAnswers !== undefined && object.selectedAvatarKey !== undefined) {
    this.wrongAnswers = object.wrongAnswers;
    this.selectedAvatarKey = object.selectedAvatarKey;
  } else {
    this.wrongAnswers = 0;
    this.selectedAvatarKey = 'avatar_1';
  }
}
GameData.prototype = {
  markPointAs: function(oldState, newState) {
    for (var i = 0; i < this.points.length; i++) {
      if (this.points[i].state === oldState) {
        this.points[i].state = newState;
        break;
      }
    }
  },
  getTaskForCurrentPoint: function() {
    for (var i = 0; i < this.points.length; i++) {
      if (this.points[i].state === Point.STATES.CURRENT) {
        var randomTaskIndex = Math.floor(Math.random() * this.points[i].tasks.length);
        console.log('Random index between 0 and ' + this.points[i].tasks.length + ' is ' + randomTaskIndex);
        return this.points[i].tasks[randomTaskIndex];
      }
    }
  },
  getBackgroundForCurrentPoint: function() {
    for (var i = 0; i < this.points.length; i++) {
      if (this.points[i].state === Point.STATES.CURRENT) {
        return this.points[i].image;
      }
    }
  },
  isEndReachable: function() {
    for (var i = 0; i < this.points.length; i++) {
      var unvisitedPointsExist = this.points[i].state === Point.STATES.UNVISITED;
      var nextPointExists = this.points[i].state === Point.STATES.NEXT;
      if (unvisitedPointsExist || nextPointExists) {
        return false;
      }
    }
    return true;
  },
  saveToLocalStorage: function() {
    window.localStorage.setItem('lukuinto-2015', JSON.stringify(this));
  }
};

module.exports = GameData;


text:
<resources>
    <string name="app_name">CollapsingToolBarWithWebView</string>
    <string name="name">Ramesh Bhupathi</string>
    <string name="developer">Android Developer</string>
    <string name="company">VTAPL</string>
</resources>


text:
///
/// \file  console.cpp
/// \brief This file contains the implementation of all console-related functions for the
///        Triclysm program itself, including the command output and command history.
///

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 *                               PREPROCESSOR DIRECTIVES                               *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

#include "console.h"    // Complimentary header to this source file.
#include "main.h"
#include "TCCube.h"     // Required for the GetConstantValue function.
#include "SDL.h"

#include <string>       // Strings library.
#include <cctype>       // Used for string comparison.
#include <list>         // STL List container.
#include <vector>       // STL Vector container.
#include <fstream>      // Used for Triclysm script I/O.
#include <queue>        // Used to queue console commands if a delay is required.

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 *                                  GLOBAL VARIABLES                                   *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

bool consoleEnabled;    ///< Set to true to enable the console, false to disable it.

size_t      maxInputLength,     ///< The maximum number of input characters in a command.
            cursorPos;          ///< The current position of the cursor in the input.
std::string currInput;          ///< String containing the user's current input.
bool        historyRetrieved;   ///< True if history has been retrieved, false otherwise.

size_t maxHistoryLines,         ///< The maximum number of history entires to cache.
       maxOutputLines;          ///< The maximum number of output lines to cache.

std::list<ConsoleCommand*>       cmdList;       ///< The list of console commands.
std::list<CommandAlias*>         aliasList;     ///< The list of command aliases.

std::list<std::string>           outputList,    ///< The list of output lines.
                                 historyList;   ///< The list of history entries.
std::list<std::string>::iterator outputIt,      ///< Output list iterator.
                                 historyIt;     ///< History list iterator.

const std::string inputPrefix = " > ";  ///< Prefix for the current command input.

std::queue<std::string> commandQueue;   ///< The command queue (used to queue any
                                        ///  commands after a wait is issued).
unsigned int waitMode,                  ///< The current wait mode (0 to run).
             waitAmount,                ///< The current wait amount.
             waitInitAmount;            ///< The initial value of the wait condition.

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 *                                FUNCTION DEFINITIONS                                 *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

///
/// \brief Initialize Console
///
/// Sets all required console parameters, and registers all console commands defined in
/// console_commands.cpp.
///
/// \param maxInputLen
/// \param maxHistLines
/// \param maxOutLines
///
/// \see maxInputLength | maxHistoryLines | maxOutputLines | RegisterCommands
///
void InitConsole(size_t maxInputLen, size_t maxHistLines, size_t maxOutLines)
{
    maxInputLength  = maxInputLen;
    maxHistoryLines = maxHistLines;
    maxOutputLines  = maxOutLines;
    TC_Console_Commands::RegisterCommands();
    consoleEnabled = false;
}

///
/// \brief Write Output
///
/// Appends the passed string to the console output list (\ref outputList).  If the number
/// of output entries exceeds the maximum (\ref maxOutputLines), the remaining output
/// lines are discarded.
///
/// \param outputStr The string to append to the output list.
///
void WriteOutput(std::string const& outputStr)
{
    std::string newOutput(outputStr);
    size_t newLinePos = newOutput.find('\n');
    while (newLinePos != std::string::npos)
    {
        outputList.push_front(newOutput.substr(0, newLinePos));
        newOutput.erase(0, newLinePos + 1);
        newLinePos = newOutput.find('\n');
    }
    outputList.push_front(newOutput);
    while (outputList.size() > maxOutputLines)
    {
        outputList.pop_back();
    }
}

///
/// \brief Write History
///
/// Appends the passed string to the console history list (\ref historyList), and resets
/// the history iterator (\ref historyIt) to the beginning of the list.  If the number
/// of history entries exceeds the maximum (\ref maxHistLines), the remaining history
/// entries are discarded.
///
/// \param historyStr The string to append to the history list.
///
void WriteHistory(std::string const& historyStr)
{
    historyList.push_front(historyStr);
    while (historyList.size() > maxHistoryLines) historyList.pop_back();
    historyIt = historyList.begin();
    historyRetrieved = false;
}

///
/// \brief Clear Output
///
/// Clears everything from the \ref outputList.
///
void ClearOutput()
{
    outputList.clear();
}

///
/// \brief Clear History
///
/// Clears everything from the \ref historyList.
///
void ClearHistory()
{
    historyList.clear();
}

///
/// \brief Compare Console Command
///
/// \returns True if the first command comes before the second, false otherwise.
/// \see     cmpCmdAlias
///
bool cmpConsoleCmd(ConsoleCommand const *first, ConsoleCommand const *second)
{
    return cmpStrNoCase(first->name, second->name);
}

///
/// \brief Compare Command Alias
///
/// \returns True if the first alias comes before the second, false otherwise.
/// \see     cmpCmdAlias
///
bool cmpCmdAlias(CommandAlias const *first, CommandAlias const *second)
{
    return cmpStrNoCase(first->alias, second->alias);
}

///
/// \brief Compare String (No Case)
///
/// \returns True if the first string comes before the second, false otherwise.
///
bool cmpStrNoCase(std::string const& first, std::string const& second)
{
    // First, we store the length of both strings.
    size_t firstLen  = first.length(),
           secondLen = second.length();
    // Next, looping through every possible character in both strings...
    for (size_t i = 0; (i < firstLen) && (i < secondLen); i++)
    {
        // If the current character in the first is a lower letter then the second...
        if (tolower(first[i]) < tolower(second[i]))
        {
            return true;    // Then we return true (first comes before the the second).
        }
        // Otherwise, if the current character is a higher letter...
        else if (tolower(first[i]) > tolower(second[i]))
        {
            return false;   // Then we return false (second comes before the the first).
        }
    }
    // If we get here, all the characters so far were equal, so we compare lengths.
    if (firstLen < secondLen)   // So, if the second string is longer than the first...
    {
        return true;                // Then the first must come before the second.
    }
    return false;       // If we get here, then the second must come before the first.
}

///
/// \brief Parse Input
///
/// Parses the passed string as a command by stripping all excess whitespace, splitting
/// the string at every command delimiter (';'), and calling \ref CallCommand for every
/// individual command that is passed.
///
/// \param inputStr The string to be parsed as a command.
///
void ParseInput(std::string const& inputStr)
{
    std::string cmdStr = inputStr;
    bool quotesMode = false;
    for (size_t i = 0; i < cmdStr.length(); i++)
    {
        switch (cmdStr[i])
        {
            case '"':  // Quotation Mark (") - Switch quotesMode
                // We only need to switch quotesMode if the quotation mark was not escaped.
                if (i > 0 && cmdStr[i-1] != '\\')
                {
                    quotesMode = !quotesMode;
                }
                break;
            case ';':   // Semicolon (;) - Parse Existing Input
            {
                if (!quotesMode)    // So, as long as we're not in quotes mode...
                {
                    // Create a substring with everything before the semicolon.
                    std::string currCmd = cmdStr.substr(0, i);
                    if (!currCmd.empty())           // If there are remaining characters...
                    {
                        StripWhitespaceLT(currCmd);     // Strip any excess whitespace and
                        CallCommand(currCmd);           // attempt to call it as a command.
                    }
                    cmdStr.erase(0, i + 1);         // Finally, erase the semicolon itself.
                    i = 0;
                }
                break;
            }
            default:
                break;
        }
    }
    // Finally, parse whatever remains (if anything).
    StripWhitespaceLT(cmdStr);
    if (cmdStr.length() > 0)
    {
        CallCommand(cmdStr);
    }
}

///
/// \brief Parse Input
///
/// Parses the \ref currInput string as a command by passing it to the other overload
/// of this function, and then clearing the input and resetting the cursor position.
///
/// \remarks This function is called when the user presses Enter in the console.
///
void ParseInput()
{
    if (!currInput.empty())
    {
        // First we add the current input to the console output and command history.
        WriteOutput(inputPrefix + currInput);
        WriteHistory(currInput);
        // Next, we call the other ParseInput function to actually parse the input string.
        ParseInput(currInput);
    }
    // Finally, we clear the current input, and reset the cursor position.
    currInput.clear();
    cursorPos = 0;
}

///
/// \brief Call Command
///
/// Parses the passed command string as a console command.  This function will first
/// try to find the command (or command alias) that is trying to be called.  It then
/// will go through and detect all passed command arguments, and pass these in a vector
/// to the appropriate command in console_commands.cpp.  If the command cannot be found,
/// an error message is written to the console.
///
/// \param cmd The command string to parse as a command.
/// \see   GetCommand
///
void CallCommand(std::string const& cmd)
{
    // If the wait mode is non-zero (i.e. we are currently in a wait of some kind), then
    // we queue the command instead of running it right now.
    if (waitMode != 0)
    {
        commandQueue.push(cmd);
        return;
    }
    std::string icmd;   // Holds just the name of the command (not the whole string).
    // First, we need to get the value of icmd.
    if (cmd.find(' ') != std::string::npos)     // So, if there is a space in the string...
    {
        icmd = cmd.substr(0, cmd.find(' '));        // Then get the command name substring.
    }
    else                                        // Else, if there is no space...
    {
        icmd = cmd;                                 // Then cmd is the command name.
    }
    ConsoleCommand *command = GetCommand(icmd);
    if (command != NULL)
    {
        // First, we need to parse the command into its argument vectors.
        std::vector<std::string> argVect;
        bool                     quotesMode = false;
        std::string              currArg;
        for (size_t i = icmd.length(); i < cmd.length(); i++)
        {
            if (cmd[i] == '"')     // If we have a double quote...
            {
                // Do we have an escape character behind us?
                if ((i - 1) > 0 && cmd[i-1] == '\\')  // Is the quote escaped?
                {
                    // If so, then just replace the last character with the quote.
                    if (currArg.length() > 0)
                    {
                        currArg[currArg.length() - 1] = '"';
                    }
                }
                else
                {
                    quotesMode = !quotesMode;       // Otherwise, toggle quotes mode.
                }
            }
            else
            {
                if (cmd[i] == ' ')
                {
                    if (quotesMode)
                    {
                        currArg.push_back(' ');
                    }
                    else if (currArg.length() > 0)
                    {
                        argVect.push_back(currArg);
                        currArg.clear();
                    }
                }
                else
                {
                    currArg.push_back(cmd[i]);
                }
            }
        }
        if (currArg.length() > 0) argVect.push_back(currArg);
        // Lastly, we call the command (passing the arguments vector), and return.
        command->func(argVect);
        return;
    }
    // If we get here, then the command wasn't found, so we show an error to the user.
    WriteOutput("'" + icmd + "' is not a recognized command.");
}

///
/// \brief Scroll History
///
/// Advances or decrements the history list iterator (\ref historyIt) to display either
/// the previous or next history entry
///
/// \param next True to scroll to the next history entry (an earlier command), or false
///             to go to the previous entry (a later command).
///
void ScrollHistory(bool next)
{
    if (historyList.size() == 0) return;

    if (next)
    {
        if (historyRetrieved)
        {
            historyIt++;
            if (historyIt == historyList.end()) historyIt--;
        }
        else
        {
            historyRetrieved = true;
        }
    }
    else if (historyRetrieved && !next && historyIt != historyList.begin())
    {
        historyIt--;
    }
    currInput = *historyIt;
    cursorPos = currInput.length();
}

///
/// \brief Move Cursor
///
/// Moves the console cursor to the left or right by one character.
///
/// \param left True to move the cursor to the left, false to move it to the right.
///
void MoveCursor(bool left)
{
    if      ( left && cursorPos > 0)                  cursorPos--;
    else if (!left && cursorPos < currInput.length()) cursorPos++;
}

///
/// \brief Strip Whitespace (Leading & Trailing)
///
/// Modifies the passed string by removing all leading and trailing whitespace.
///
/// \param toTrim The string to trim the whitespace from.
///
void StripWhitespaceLT(std::string &toTrim)
{
    while (toTrim.length() > 0 && toTrim[0] == ' ')
    {
        toTrim.erase(0, 1);
    }
    while (toTrim.length() > 0 && toTrim[toTrim.length() - 1] == ' ')
    {
        toTrim.erase(toTrim.length() - 1, 1);
    }
}

///
/// \brief Input Backspace
///
/// Removes the last entered character, and moves the cursor to the left by one character.
///
void InputBackspace()
{
    if (cursorPos > 0)
    {
        cursorPos--;
        currInput.erase(cursorPos, 1);
    }
}

///
/// \brief Input Add Character
///
/// Adds the passed character to the \ref currInput string at the current \ref cursorPos.
///
/// \param c The character to add to the current input string.
/// \see   currInput | maxInputLength | cursorPos
///
void InputAddChar(char c)
{
    if (currInput.length() < maxInputLength)
    {
        if (currInput.length() == cursorPos)
        {
            currInput.push_back(c);
        }
        else
        {
            currInput.insert(cursorPos, 1, c);
        }
        cursorPos++;
    }
}

///
/// \brief Get Command
///
/// Attempts to find and return a pointer to the ConsoleCommand object representing the
/// command or alias passed to the function (or NULL if the command couldn't be found).
///
/// \param   cmdName String containing the command name or alias to find.
/// \returns A pointer to the console command, or NULL if no command could be found.
///
/// \see aliasList | cmdList | CommandAlias | ConsoleCommand
///
ConsoleCommand *GetCommand(std::string const& cmdName)
{
    std::list<CommandAlias*>::iterator aliasIt;
    for (aliasIt = aliasList.begin(); aliasIt != aliasList.end(); aliasIt++)
    {
        if (cmdName.compare((*aliasIt)->alias) == 0)
        {
            return GetCommand((*aliasIt)->name);
        }
    }

    std::list<ConsoleCommand*>::iterator cmdIt;
    for (cmdIt = cmdList.begin(); cmdIt != cmdList.end(); cmdIt++)
    {
        if (cmdName.compare((*cmdIt)->name) == 0)
        {
            return *cmdIt;
        }
    }
    return NULL;
}

///
/// \brief Suggest Command
///
/// Attempts to "auto-complete" the user's current input into the appropriate command.
/// If there is one (and only one) possible match, the command is auto-completed into
/// the currInput string.  If there are no matches, or more then one, nothing is modified.
///
/// \see aliasList | cmdList | currInput
///
void SuggestCommand()
{
    std::string toSuggest;                          // The name to suggest.
    unsigned char numMatches = 0;                   // Number of possible matches.
    size_t        matchLen,                         // Length of the current match.
                  currLen  = currInput.length();    // Length of the current input.
    bool matchFound = false;                        // Flag to set if a match is found.
    std::list<CommandAlias*>::iterator aliasIt;     // Iterator for the alias list.
    // So, looping through each entry in the alias list...
    for (aliasIt = aliasList.begin(); aliasIt != aliasList.end(); aliasIt++)
    {
        matchFound = true;                          // Assume we have a match initially.
        matchLen   = (*aliasIt)->alias.length();    // We store the length of the alias.
        // So, looping through the characters in both the input and command alias...
        for (size_t i = 0; (i < matchLen) && (i < currLen); i++)
        {
            if ((*aliasIt)->alias[i] != currInput[i])   // If any characters don't match...
            {
                matchFound = false;                         // Then toggle the match flag.
            }
        }
        if (matchFound)             // So, if we did find a match...
        {
            numMatches++;                   // Increment the match counter,
            toSuggest = (*aliasIt)->alias;  // and update the command to suggest.
        }
    }
    std::list<ConsoleCommand*>::iterator cmdIt;     // Iterator for the command list.
    // So, repeating the above steps, but this time looping through the command list...
    for (cmdIt = cmdList.begin(); cmdIt != cmdList.end(); cmdIt++)
    {
        matchFound = true;                          // Assume we have a match initially.
        matchLen   = (*cmdIt)->name.length();       // We store the length of the command.
        // So, looping through the characters in both the input and the command name...
        for (size_t i = 0; (i < matchLen) && (i < currLen); i++)
        {
            if ((*cmdIt)->name[i] != currInput[i])      // If any characters don't match...
            {
                matchFound = false;                         // Then toggle the match flag.
            }
        }
        if (matchFound)             // So, if we did find a match...
        {
            numMatches++;                   // Increment the match counter,
            toSuggest = (*cmdIt)->name;     // and update the command to suggest.
        }
    }
    if (numMatches == 1)        // Finally, if and only if we found one single match...
    {
        currInput = toSuggest;          // Replace the current input with the suggested
        cursorPos = toSuggest.length(); // command, and move the cursor to the end.
    }
}

///
/// \brief Load Script
///
/// Attempts to open a stream to the passed fileName.  If the file stream was opened, each
/// line in the file is read and passed to the \ref ParseInput function.
///
/// \returns True if the file was successfully opened and parsed, false otherwise.
///
/// \see ParseInput
///
bool LoadScript(char const *fileName)
{
    bool read = false;
    std::ifstream inFile(fileName);
    if (inFile.is_open())
    {
        while (inFile.peek() != EOF)
        {
            std::string currLine;
            getline(inFile, currLine);
            ParseInput(currLine);
        }
        inFile.close();
        return true;
    }
    else
    {
        return false;
    }
}

///
/// \brief Run Command Queue
///
/// Runs all commands currently held within the command queue,
///
///
void RunCommandQueue()
{
    while (!commandQueue.empty())
    {
        CheckWaitMode();    // First, we check the wait condition and update the wait mode.
        if (waitMode == 0)  // So, if the condition was met, or we don't have to wait...
        {
            CallCommand(commandQueue.front());
            commandQueue.pop();
        }
        else                // Else, if we are still waiting...
        {
            break;              // Break out of the loop, so we don't parse any more.
        }
    }
}

///
/// \brief Check Wait Mode
///
/// Checks the condition on the current wait command, and resets the waitMode variable if
/// the wait condition was met.  Otherwise, nothing is modified.
///
/// \see SetWaitMode | waitMode | waitAmount | waitInitAmount
///
void CheckWaitMode()
{
    switch (waitMode)
    {
        case 0:         // Mode 0: No Wait
            break;

        case 1:         // Mode 1: Wait Time (milliseconds)
        case 2:         // Mode 2: Wait Time (seconds, waitAmount is in milliseconds)
        {
            // If it has been at least waitAmount ticks since the wait command...
            if ((SDL_GetTicks() - waitInitAmount) >= waitAmount)
            {
                // Reset the wait mode so the command queue continues.
                waitMode = 0;
            }
            break;
        }

        case 3:         // Mode 3: Wait Ticks
        {
            LockAnimMutex();        // First, we lock the animation mutex.
            // So, if the current animation's tick count is large enough...
            if ((currAnim->GetTicks() - waitInitAmount) >= waitAmount)
            {
                waitMode = 0;           // We can reset the wait mode.
            }
            UnlockAnimMutex();      // Finally, we unlock the mutex.
            break;
        }

        case 4:         // Mode 4: Wait Iterations
        {
            LockAnimMutex();        // First, we lock the animation mutex.
            // So, if the current animation's iteration count is large enough...
            if ((currAnim->GetIterations() - waitInitAmount) >= waitAmount)
            {
                waitMode = 0;           // We can reset the wait mode.
            }
            UnlockAnimMutex();      // Finally, we unlock the mutex.
            break;
        }

        default:        // There should be no other modes, so reset the mode.
            waitMode = 0;
            break;
    }
}

///
/// \brief Set Wait Mode
///
/// Sets the current wait mode to the passed amounts.  If mode is an invalid value, or is
/// zero, the wait mode is reset.  This function also initializes \ref waitInitAmount.
///
/// \param mode  The waiting mode to set (ms = 1, seconds = 2, ticks = 3, iterations = 4).
/// \param delay The amount to wait for (units as specified per the mode).
///
/// \see CheckWaitAmount | waitMode | waitAmount | waitInitAmount
///
void SetWaitMode(unsigned int mode, unsigned int delay)
{
    // First, we simply copy the mode and delay values into the proper variables.
    waitMode   = mode;
    waitAmount = (mode == 2) ? (delay * 1000) : (delay);
    // And finally, we set the value of waitInitAmount based on the current mode.
    switch (mode)
    {
        case 0:     // Mode 0: No Wait
            waitInitAmount = 0;
            break;

        case 1:     // Mode 1: Wait Time (milliseconds)// Mode
        case 2:     // Mode 2: Wait Time (seconds, waitAmount is in milliseconds)
            waitInitAmount = SDL_GetTicks();
            break;

        case 3:     // Mode 3: Wait Ticks
            LockAnimMutex();        // First, we lock the animation mutex.
            // Next, we store the animation's current tick count.
            waitInitAmount = currAnim->GetTicks();
            UnlockAnimMutex();      // Finally, we unlock the mutex.
            break;

        case 4:     // Mode 4: Wait Iterations
            LockAnimMutex();        // First, we lock the animation mutex.
            // Next, we store the animation's current iteration count.
            waitInitAmount = currAnim->GetIterations();
            UnlockAnimMutex();      // Finally, we unlock the mutex.
            break;

        default:    // There should be no other modes, so reset the mode.
            SetWaitMode(0, 0);
            break;
    }
}