text:
import { NgModule, ApplicationRef } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';
import { removeNgStyles, createNewHosts, createInputTransfer } from '@angularclass/hmr';
import { AngularFireModule, FIREBASE_PROVIDERS, AuthProviders, AuthMethods, firebaseAuthConfig } from 'angularfire2';
import { HammerGestureConfig, HAMMER_GESTURE_CONFIG } from '@angular/platform-browser';
import { CollapseDirective } from 'ng2-bootstrap'

/*
 * Platform and Environment providers/directives/pipes
 */
import { ENV_PROVIDERS } from './environment';
import { ROUTES } from './app.routes';
// App is our top level component
import { AppComponent } from './app.component';
import { APP_RESOLVER_PROVIDERS } from './app.resolver';
import { AppState, InternalStateType } from './app.service';
import { HomeComponent } from './home';
import { AboutComponent } from './about';
import { NoContentComponent } from './no-content';
import { XLarge } from './home/x-large';
import { GameComponent } from './game';
import { CreationToolComponent } from './creation-tool';
import { ImgModalWindow } from './modal-img/modal-img';
import { ImgViewModalWindow } from './modal-view-entry/modal-view-entry';
import { CreateGameModalWindow } from './modal-create-game/modal-create-game';
import { LoginComponent } from './login';
import { AuthGuard } from './common/auth.guard'
import { UserService } from './common/user.service'
import { GameService } from './common/game.service'

import { ModalModule } from 'angular2-modal';
import { BootstrapModalModule } from 'angular2-modal/plugins/bootstrap';

// Application wide providers
const APP_PROVIDERS = [
  ...APP_RESOLVER_PROVIDERS,
  AppState
];

type StoreType = {
  state: InternalStateType,
  restoreInputValues: () => void,
  disposeOldHosts: () => void
};

//Firebase
export const firebaseConfig = {
  apiKey: "AIzaSyCzG1IQAkNJLr8hXcqgStltB897BMs_jK8",
  authDomain: "touristbingo-2a6b3.firebaseapp.com",
  databaseURL: "https://touristbingo-2a6b3.firebaseio.com",
  storageBucket: "touristbingo-2a6b3.appspot.com",
  messagingSenderId: "889266554830"
};

export const myFirebaseAuthConfig = {
  provider: AuthProviders.Google,
  method: AuthMethods.Redirect
}

/**
 * `AppModule` is the main entry point into Angular2's bootstraping process
 */
@NgModule({
  bootstrap: [ AppComponent ],
  declarations: [
    AppComponent,
    AboutComponent,
    HomeComponent,
    NoContentComponent,
    XLarge,
    GameComponent,
    CreationToolComponent,
    ImgModalWindow,
    ImgViewModalWindow,
    CreateGameModalWindow,
    CollapseDirective,
    LoginComponent
  ],
  imports: [ // import Angular's modules
    BrowserModule,
    FormsModule,
    HttpModule,
    RouterModule.forRoot(ROUTES, { useHash: true }),
    AngularFireModule.initializeApp(firebaseConfig, myFirebaseAuthConfig),
    ModalModule.forRoot(),
    BootstrapModalModule
  ],
  providers: [ // expose our Services and Providers into Angular's dependency injection
    ENV_PROVIDERS,
    APP_PROVIDERS,
    AuthGuard,
    UserService,
    GameService
  ],
  entryComponents: [
    ImgModalWindow,
    ImgViewModalWindow,
    CreateGameModalWindow
  ]
})
export class AppModule {
  constructor(public appRef: ApplicationRef, public appState: AppState) {}

  hmrOnInit(store: StoreType) {
    if (!store || !store.state) return;
    console.log('HMR store', JSON.stringify(store, null, 2));
    // set state
    this.appState._state = store.state;
    // set input values
    if ('restoreInputValues' in store) {
      let restoreInputValues = store.restoreInputValues;
      setTimeout(restoreInputValues);
    }

    this.appRef.tick();
    delete store.state;
    delete store.restoreInputValues;
  }

  hmrOnDestroy(store: StoreType) {
    const cmpLocation = this.appRef.components.map(cmp => cmp.location.nativeElement);
    // save state
    const state = this.appState._state;
    store.state = state;
    // recreate root elements
    store.disposeOldHosts = createNewHosts(cmpLocation);
    // save input values
    store.restoreInputValues  = createInputTransfer();
    // remove styles
    removeNgStyles();
  }

  hmrAfterDestroy(store: StoreType) {
    // display new elements
    store.disposeOldHosts();
    delete store.disposeOldHosts;
  }

}


text:
export const configFileNames = [
  'renovate.json',
  'renovate.json5',
  '.github/renovate.json',
  '.github/renovate.json5',
  '.gitlab/renovate.json',
  '.gitlab/renovate.json5',
  '.renovaterc',
  '.renovaterc.json',
  'package.json',
];

redpajama_set_name: RedPajamaGithub


text:
@interface HAPListMigrationTest : SenTestCase {
@private
    NSString* dbFilePath;
    HAEntityManager* manager;
}

@end


text:
#ifndef OSMIUM_IO_PBF_HPP
#define OSMIUM_IO_PBF_HPP

#include <string>
#include <vector>

namespace osmium {

    namespace io {

        /**
         * Get a list of all compression types supported for PBF files.
         */
        inline std::vector<std::string> supported_pbf_compression_types() {
            std::vector<std::string> types{"none", "zlib"};

#ifdef OSMIUM_WITH_LZ4
            types.emplace_back("lz4");
#endif

            return types;
        }

    } // namespace io

} // namespace osmium

#endif // OSMIUM_IO_PBF_HPP


text:
<?php
namespace Chamilo\Core\Repository\Feedback\Component;

use Chamilo\Core\Repository\Feedback\Manager;
use Chamilo\Libraries\Architecture\Exceptions\NoObjectSelectedException;
use Chamilo\Libraries\Architecture\Exceptions\NotAllowedException;
use Chamilo\Libraries\Platform\Session\Request;
use Chamilo\Libraries\Platform\Translation;
use Chamilo\Libraries\Utilities\Utilities;

/**
 * Controller to delete the feedback
 */
class DeleterComponent extends Manager
{

    /**
     * Executes this controller
     */
    public function run()
    {
        $feedback_ids = Request::get(self::PARAM_FEEDBACK_ID);

        try
        {
            if (empty($feedback_ids))
            {
                throw new NoObjectSelectedException(Translation::get('Feedback'));
            }

            if (! is_array($feedback_ids))
            {
                $feedback_ids = array($feedback_ids);
            }

            foreach ($feedback_ids as $feedback_id)
            {
                $feedback = $this->get_parent()->retrieve_feedback($feedback_id);

                if (! $this->get_parent()->is_allowed_to_delete_feedback($feedback))
                {
                    throw new NotAllowedException();
                }

                if (! $feedback->delete())
                {
                    throw new \Exception(
                        Translation::get(
                            'ObjectNotDeleted',
                            array('OBJECT' => Translation::get('Feedback')),
                            Utilities::COMMON_LIBRARIES));
                }
            }

            $success = true;
            $message = Translation::get(
                'ObjectDeleted',
                array('OBJECT' => Translation::get('Feedback')),
                Utilities::COMMON_LIBRARIES);
        }
        catch (\Exception $ex)
        {
            $success = false;
            $message = $ex->getMessage();
        }

        $this->redirect($message, ! $success, array(self::PARAM_ACTION => self::ACTION_BROWSE));
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Filter (Aggregator Reference)
</TITLE>

<META NAME="date" CONTENT="2010-11-15">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

gr.forth.ics.jbenchy

Interface Filter

public interface Filter

An SQL-based filter. A filters is the direct analog of SQL's WHERE clause,
 for example <tt>Filters.eq("VAR", "X")</tt> allows only those results
 which do have the value "X" for variable "VAR", filtering out all the rest.

Author:

andreou

See Also:
Filters

Method Summary

 java.lang.String
toSql(Schema schema)

          Returns the SQL part that can be embedded in a WHERE clause and express the semantics of this filter.

Method Detail

toSql

java.lang.String toSql(Schema schema)

Returns the SQL part that can be embedded in a WHERE clause and express the semantics of this filter.

Parameters:
schema - the schema of the aggregator/table that the filter will apply to. This is needed to be
 able to correctly render values in the SQL string, something for which in some cases the data type of the
 value is required

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
30 Second Tour of Armstrong
===========================

Armstrong is an open-source News Publishing Platform built on top of Django.
90% of all media websites are the same.  Armstrong gives you that first 90%
and lets you focus on the parts of your organization that make you unique.

Armstrong provides a lot of CMS bits, but its main focus is developer-
friendliness.  It works great as a replacement for other CMS/bloggy-type
systems when you have a tech team or consultant that can help get you
off the ground.

Want to see it in action?  Here's the commands to run:

::

    pip install armstrong
    armstrong init --template=demo demo-site
    cd demo-site
    armstrong runserver

Armstrong is the result of a collaboration between the `Texas Tribune`_ and the
`Bay Citizen`_ and a grant from the `John S. and James L. Knight Foundation`_.

Up Next
-------
Now that you know what Armstrong is, you should visit :ref:`getting-start/5-minutes`.

.. _Bay Citizen: http://www.baycitizen.org/
.. _John S. and James L. Knight Foundation: http://www.knightfoundation.org/
.. _Texas Tribune: http://www.texastribune.org/


text:
import pickle
import numpy
numpy.random.seed(42)

# The words (features) and authors (labels), already largely processed.
# These files should have been created from the previous (Lesson 10)
# mini-project.
words_file = "../text_learning/your_word_data.pkl"
authors_file = "../text_learning/your_email_authors.pkl"
word_data = pickle.load(open(words_file, "r"))
authors = pickle.load(open(authors_file, "r"))

# test_size is the percentage of events assigned to the test set (the
# remainder go into training)
# feature matrices changed to dense representations for compatibility with
# classifier functions in versions 0.15.2 and earlier
from sklearn import cross_validation
features_train, features_test, labels_train, labels_test = cross_validation.train_test_split(
    word_data,
    authors,
    test_size=0.1,
    random_state=42)

from sklearn.feature_extraction.text import TfidfVectorizer
vectorizer = TfidfVectorizer(sublinear_tf=True, max_df=0.5,
                             stop_words='english')
features_train = vectorizer.fit_transform(features_train)
features_test = vectorizer.transform(features_test).toarray()

# a classic way to overfit is to use a small number
# of data points and a large number of features;
# train on only 150 events to put ourselves in this regime
features_train = features_train[:150].toarray()
labels_train = labels_train[:150]

# your code goes here

from sklearn import tree
import sys
sys.path.append("../tools/")
from timed import Timed
from sklearn.metrics import accuracy_score

print len(features_train[0])

clf = tree.DecisionTreeClassifier(min_samples_split=40)

with Timed("Training"):
    clf.fit(features_train, labels_train)

with Timed("Predicting"):
    pred = clf.predict(features_test)

accuracy = accuracy_score(labels_test, pred)

print "accuracy: {}".format(accuracy)

print "feature_importances: {}".format(len(clf.feature_importances_))
i = 0
important_features = []
for f in clf.feature_importances_:
    if f > 0.2:
        print "feature {}: {}".format(i, f)
        important_features.append((i, f))
    i += 1

features = vectorizer.get_feature_names()
for f in important_features:
    print "feature {} with importance {}".format(features[f[0]], f[1])


text:
require 'rubygems'
require 'bundler'

require 'simplecov'

SimpleCov.start do
  project_name 'lifeguard'
  add_filter '/coverage/'
  add_filter '/doc/'
  add_filter '/pkg/'
  add_filter '/spec/'
  add_filter '/tasks/'
end

Bundler.require(:default, :development, :test)

require 'lifeguard'

# import all the support files
Dir[File.join(File.dirname(__FILE__), 'support/**/*.rb')].each { |f| require File.expand_path(f) }

RSpec.configure do |config|
  config.after(:each) do
    Thread.list.each do |thread|
      thread.kill unless thread == Thread.current
    end
  end
end


text:
# Conv [![Coverage Status](https://coveralls.io/repos/thaumant/conv/badge.svg?branch=master)](https://coveralls.io/r/thaumant/conv?branch=master) [![Build Status](https://travis-ci.org/thaumant/conv.svg?branch=master)](https://travis-ci.org/thaumant/conv)

Represent JS datatypes as JSON values, serialize to and restore from any format.

- [Features](#features)
- [Basic usage](#basic-usage)
- [Adding your types](#adding-your-types)
- [Gotchas](#gotchas)
- [Documentation](#documentation)

# Features
- Simple and readable way to serialize JS Date, RegExp, Buffer and ES6 types.
- Define converters for your own types.
- Use JSON, BSON, YAML or any format you want.
- Converters composition with consistency checks included.
- Performance optimized, no dependencies.

# Basic usage
```javascript
conv.parse('{"$Buffer":"Aw4P"}'); // returns <Buffer 03 0e 0f>

console.log(conv.serialize(new Date, null, 4));
/* arguments are passed to JSON.stringify, so it prints:
{
    "$Date": "2015-06-07T12:34:56.789Z"
}
*/
```
Following types are supported:
- Date,
- Buffer,
- ES6 Map,
- ES6 Set.

Last three are enabled only when found in the environment. For example, in node v0.10 only Date and Buffer will be enabled, and in Chrome v41 you will get all but Buffer.

# Adding your types
To add a new class you must provide a **spec** - an object that describes rules for dumping a value in JSON values and restoring it back. There is a working spec for Date:
```javascript
var spec = {
    class: Date,
    dump: (date) => date.toJSON(),
    restore: (str) => new Date(str)
};
```
Dump and restore method are optional. So there is a minimal working spec for Date class:
```javascript
var spec = {class: Date};
```
Make new extended converter using the spec:
```javascript
var conv = conv.extendWith([{class: Date}]);
```
When you are defining converters for domain-specific types, use namespaces. There is a more elaborate example:
```javascript
class User {
    constructor(data) {
        this.id = data.id;
        this.name = data.name;
    }
    toJSON() {
        return {id: this.id, name: this.name};
    }
    // ...
}

var conv = conv.extendWith([{
    class: User,
    namespace: 'mycompany'
    // user.toJSON() as dump() will be used by default
    // new User(dumped) as restore() will be used by default
}]);

var user = new User({id: 13, name: "John"});

console.log(conv.serialize(user, null, 4))
/* prints:
{
    "$mycompany.User": {
        "id": 12
        "name": "John"
    }
}
*/
```

There are three kinds of specs: class, proto and predicate specs. See [documentation](../../wiki) for more info.

# Gotchas

- In `dump` method don't wrap the result in `{$Constructor: result}`, Conv will do that for you.
- Do not transform properties of the dumped value, Conv will do that recursively after calling `spec.dump()` on source value. Dump works from top to bottom.
- Restore works in the opposite direction: when dumped object is passed to `spec.restore()`, it's properties are already restored.
- Check your spec: in almost all cases `val` should be equal `spec.restore(spec.dump(val))`, as well as `dumped` shold be equal `spec.dump(spec.restore(dumped))`.

# Documentation
See the [wiki](../../wiki) for documentation and **conv-immutable** for more examples.


text:
const execSync = require('child_process').execSync,
  packages = [
    'core',
    'bootstrap',
    'material',
    'ionic',
    'primeng',
    'kendo',
    'schematics',
    'nativescript',
  ];

packages.map(package => {
  const packagePath = `${__dirname}/../dist/@ngx-formly/${package}`;

  execSync(`cd ${packagePath} && npm publish --access public`);
});


text:
/*
* Build mincer
*/
'use strict';
var Mincer = require('mincer');
var rimraf = require('rimraf').sync;
var chalk = require('chalk');
var path = require('path');
var Manifest = require('./manifest');

module.exports = function (cwd, options, callback) {

  // Remove duplicate paths
  options.include = options.include.filter(function(item, pos) {
    return options.include.indexOf(item) === pos;
  });

  // Setup environment
  var
    self = this,
    environment = new Mincer.Environment(cwd);

  // Configure engines

  Object.keys(options.engines).forEach(function (name) {
    var engine = Mincer[name + 'Engine'] || Mincer[name];
    if (!engine || typeof engine.configure !== 'function') {
      throw 'Invalid mincer engine ' + name;
    }
    engine.configure(options.engines[name]);
  });

  // Enable environment features
  var features = options.enable || [];
  features.forEach(function (feature) {
    environment.enable(feature);
  });

  // Auto enable source_maps-feature
  if (options.sourceMaps) {
    environment.enable('source_maps');
  }

  // Setup environment compressors
  if (options.jsCompressor) {
    environment.jsCompressor = options.jsCompressor;
  }
  if (options.cssCompressor) {
    environment.cssCompressor = options.cssCompressor;
  }

  // Register environment helpers
  Object.keys(options.helpers).forEach(function (name) {
    var helper = options.helpers[name].bind(environment);
    environment.registerHelper(name, helper);
  });

  options.include.forEach(function (path) {
    environment.appendPath(path);
  });

  var files = options.files.map(function(file) {
    return path.join(cwd, file);
  });

  var output = path.resolve( options.output ) === path.normalize( options.output ).replace(/\/*$/g, "") ? options.output : path.join(cwd, options.output);

  if (options.clean && cwd !== options.output) {
    console.log(chalk.reset(chalk.cyan("Clean " + output + "...")));
    rimraf(output);
  }

  if (options.manifest) {
    options.manifest = typeof options.manifest === 'boolean' ? 'manifest.json' : options.manifest;
    output = options.manifest && path.resolve( options.manifest ) === path.normalize( options.manifest ).replace(/\/*$/g, "") ? options.manifest : path.join(output, options.manifest);
  }

  var ManifestImpl = !options.manifest || !options.digest ? Manifest : Mincer.Manifest;

  var manifest = new ManifestImpl(environment, output);

  try {
    console.log(chalk.cyan("Build assets to output " + chalk.cyan(output) + "..."));
    manifest.compile(options.files, options);
  } catch (e) {
    console.log(chalk.reset(chalk.red(e)));
    process.exit();
  }

};


text:
radvd
==========

[![Build Status](https://img.shields.io/travis/com/amylum/radvd.svg)](https://travis-ci.com/amylum/radvd)
[![GitHub release](https://img.shields.io/github/release/amylum/radvd.svg)](https://github.com/amylum/radvd/releases)
[![Inner Net Licensed](http://img.shields.io/badge/license-InnerNet-green.svg)](https://github.com/reubenhwk/radvd/blob/master/COPYRIGHT)

Package repo for [radvd](http://www.litech.org/radvd/)

## Usage

To build a new package, update the submodule and run `make`. This launches the docker build container and builds the package.

To start a shell in the build environment for manual actions, run `make manual`.

## License

This repo is released under the MIT License. See the bundled LICENSE file for details.


text:
package eu.ydp.empiria.player.client.module.dictionary.external.controller;

import com.google.gwt.user.client.ui.Widget;
import eu.ydp.empiria.player.client.gin.factory.DictionaryModuleFactory;
import eu.ydp.empiria.player.client.module.dictionary.external.view.ExplanationView;
import eu.ydp.empiria.player.client.module.media.MediaWrapper;
import eu.ydp.empiria.player.client.util.events.internal.callback.CallbackReceiver;
import eu.ydp.empiria.player.client.util.events.internal.media.MediaEvent;
import eu.ydp.empiria.player.client.util.events.internal.media.MediaEventHandler;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class)
public class ExplanationDescriptionSoundControllerTest {

    private ExplanationDescriptionSoundController testObj;
    private static final String FILE_NAME = "test.mp3";

    @Mock
    private ExplanationView explanationView;

    @Mock
    private DictionaryModuleFactory dictionaryModuleFactory;

    @Mock
    private DescriptionSoundController descriptionSoundController;

    @Mock
    private MediaEvent mediaEvent;

    @Mock
    private MediaWrapper<Widget> mediaWrapper;

    @Captor
    private ArgumentCaptor<CallbackReceiver<MediaWrapper<Widget>>> callbackReceiverCaptor;

    @Captor
    private ArgumentCaptor<MediaEventHandler> abstractMediaHandlerCaptor;

    @Before
    public void setUp() {
        testObj = spy(new ExplanationDescriptionSoundController(explanationView, descriptionSoundController));
    }

    @Test
    public void shouldPlay_whenIsNotPlayingAndPlayOrStopMethodIsCalled() {
        // given
        when(descriptionSoundController.isPlaying()).thenReturn(false);

        // when
        testObj.playOrStopExplanationSound(FILE_NAME);

        // then
        verify(descriptionSoundController).createMediaWrapper(eq(FILE_NAME), callbackReceiverCaptor.capture());
        CallbackReceiver<MediaWrapper<Widget>> value = callbackReceiverCaptor.getValue();
        value.setCallbackReturnObject(mediaWrapper);
        verify(descriptionSoundController).playFromMediaWrapper(abstractMediaHandlerCaptor.capture(), eq(mediaWrapper));
        verify(explanationView).setExplanationPlayButtonStyle();
        abstractMediaHandlerCaptor.getValue().onMediaEvent(mediaEvent);
        verify(explanationView).setExplanationStopButtonStyle();
        verify(descriptionSoundController).stopPlaying();
    }

    @Test
    public void shouldStopPlaying_whenPlayingAndPlayOrStopMethodIsCalled() {
        // given
        when(descriptionSoundController.isPlaying()).thenReturn(true);

        // when
        testObj.playOrStopExplanationSound(FILE_NAME);

        // then
        verify(testObj).stop();
    }
}


text:
<?php
namespace Disco\classes;
/**
 * This file holds the \Disco\classes\DataModel class.
*/

/**
 * The DataModel class is used to ensure the validity and integrity of data. This is done by a defining a definition for each datum
 * in the data model. The class ensures that any data defined by the definition conforms to its specified
 * conditions, and when it does not it sets errors specific to each datum which can then be used to communicate
 * what type of datum should have been passed.
 *
 * Data models are primarily used to verify incoming user data from forms in the browser, but can also be used as
 * contracts in class communications.
 *
 * The only thing necessary to implement a data model is defining the data models definition in `protected
 * $definition = Array()`. You would then use it in real code like:
 * ```
 * $dm = new MyDataModel($data);
 * $dm->someField = 'foo';
 * $dm['otherField'] = 'bar';
 * if(!$dm->verify()){
 *      $errors = $dm->getErrors();
 * }
 * ```
 *
 * Notice that data models can be accessed via object syntax and array access syntax, this is because the data model
 * class implements `\ArrayAccess` and implements the necessary methods for object access.
*/
class DataModel implements \ArrayAccess {

    /**
     * A definition is defined by a key, which is the name of the data/field, and an array which defines the
     * conditions verifying the data/field.
     *
     *
     * Conditions used to define a data/field:
     *

     *
`type` : `string` (int, uint, float, ufloat, string, boolean, char, array, object, closure)

     *
`nullable` : `boolean` (optional) Data can be null.

     *
`truthy` : `boolean` (optional) Data can be a boolean.

     *
`in` : `array` (optional) Data must be contained in this array.

     *
`notin` : `array` (optional) Data must NOT be contained in this array.

     *
`instanceof` : `string` (optional)(only applies to object) Data must be an instance of class.

     *
`max` : `numeric` (optional)(only applies to int, uint, float, ufloat) Max value of data.

     *
`min` : `numeric` (optional)(only applies to int, uint, float, ufloat) Min value of data.

     *
`maxlen` : `int` (optional)(only applies to string) Max length of data.

     *
`minlen` : `int` (optional)(only applies to string) Min length of data.

     *

     *
     *
     * Conditions that when set will disregard all conditions listed above (aka are mutually exclusive with any
     * other condition):
     *

     *
`regexp` : `string` A regular expression that the data must match, can be one of the default matching
     *      conditions provided by Disco.

     *
`method` : `string` The name of a method of the class that is passed the value of the data and returns
     *      a boolean value indicating whether the data is valid.

     *

     *
     *
     * Conditions that aren't mutually exclusive to any data type and can be used to augment a piece of data:
     *

     *
`required` : `boolean` Whether the data is required in the data model.
     *
`default` : `mixed` A default value to give the data when its not set, mutually exclusive with `required`.
     *
`premassage` : `string` The name of the method of the class that can massage the data value prior to validation.
     *
`postmassage` : `string` The name of the method of the class that can massage the data value after successful validation.
     *
`error` : `string` The error message returned when the data doesn't validate. If this is not set
     *      a custom one will be generated for you based on the conditions.

     *

     *
     *
     * @var array $definition Definitions of the data this data model contains.
    */
    protected $definition = Array();

    /**
     * @var array $data The data set in the data model.
    */
    protected $data = Array();

    /**
     * @var array $errors The errors that occured while validating the data.
    */
    protected $errors = Array();

    /**
     * @var string $defaultErrorMessage The default error message used for general data errors. Use `%1\$s` in the
     * string to get the key of the data the error message is regarding.
    */
    protected $defaultErrorMessage = "Invalid value provided for `%1\$s`";

    /**
     * Set initial data in the data model. Any keys set in the passed data that do not exist in the definition will
     * be disregarded.
     *
     * @param array $data Initial data to set in the model, will be merged with any values already set in data.
    */
    public function __construct($data = Array()){

        if(is_object($data)){
            $data = (array) $data;
        }//if

        if(count($data)){
            $this->data = array_merge( array_intersect_key($data, array_flip(array_keys($this->definition) ) ) );
        }//if

    }//__construct

    /**
     * Verify the data in the data model. If the data model failed to verify use the method `getErrors()` to get
     * a list of the errors in the model.
     *
     * @return boolean Whether the data in the data model passed verification.
    */
    public final function verify(){

        foreach($this->definition as $k => $v){
            $this->verifyData($k);
        }//foreach

        if(count($this->errors)){
            return false;
        }//if

        return true;

    }//verify

    /**
     * Verify only the passed fields data. This comes in handy when you only want to verify a subset of the data
     * models definition.
     *
     * @param array $fields The field data keys to verify.
     *
     * @return boolean Whether the data in the passed fields passed verification.
    */
    public final function verifyOnly($fields){

        foreach($fields as $k){
            $this->verifyData($k);
        }//foreach

        if(count($this->errors)){
            return false;
        }//if

        return true;

    }//verifyOnly

    /**
     * Verify only data that has been set in the data model and not all data defined by the definitions.
     *
     * @return boolean Whether the set data passed verification.
    */
    public final function verifySetData(){

        foreach($this->data as $k => $v){
            $this->verifyData($k);
        }//foreach

        if(count($this->errors)){
            return false;
        }//if

        return true;

    }//verifySetData

    /**
     * Verify a single piece of data in the model. If the data fails to validate its corresponding error message
     * will be set in the errors by the same key.
     *
     * @param string $key The key of the data.
     *
     * @return boolean Whether the data passed verification.
     *
     * @throws \Disco\exceptions\Exception When the data model doesn't define the field specified by `$key`.
    */
    public final function verifyData($key){

        unset($this->errors[$key]);

        if(!array_key_exists($key,$this->data)){

            if(!array_key_exists($key,$this->definition)){
                throw new \Disco\exceptions\Exception("Field `{$key}` is not defined by this data model");
            }//if

            //DEFAULT
            if(array_key_exists('default',$this->definition[$key])){
                $this->data[$key] = $this->definition[$key]['default'];
            }//if
            //REQUIRED
            else if($this->getDefinitionValue($key,'required')){
                return $this->setError($key,"`{$key}` is required");
            }//elif
            else {
                return false;
            }//el

        }//if

        //PREMASSAGE
        if(($massage = $this->getDefinitionValue($key,'premassage')) !== false){
            $this->data[$key] = $this->{$massage}($this->data[$key]);
        }//if

        $value = $this->data[$key];

        //REGEXP
        if(($regexp = $this->getDefinitionValue($key,'regexp')) !== false){
            if(($default = \App::getCondition($regexp)) !== false && !\App::matchCondition($default,$value)){
                return $this->setError($key);
            }//if
            if(!preg_match("/{$regexp}/",$value)){
                return $this->setError($key);
            }//if
            $this->_postMassage($key,$value);
            return true;
        }//if

        //METHOD
        if(($method = $this->getDefinitionValue($key,'method')) !== false){
            if(!$this->{$method}($value)){
                return $this->setError($key);
            }//if
            $this->_postMassage($key,$value);
            return true;
        }//if

        //NULLABLE
        if($this->getDefinitionValue($key,'nullable') && $value === null){
            $this->_postMassage($key,$value);
            return true;
        }//if

        $type = $this->getDefinitionValue($key,'type');

        //TRUTHY
        if($type != 'boolean' && $this->getDefinitionValue($key,'truthy') && is_bool($value)){
            $this->_postMassage($key,$value);
            return true;
        }//if

        switch($type){

            case 'int':

                if(!$this->_isValidInt($key,$value)){
                    return false;
                }//if

                break;

            case 'uint':

                if(!$this->_isValidInt($key,$value)){
                    return false;
                }//if

                if($value < 0){
                    return $this->setError($key,"`{$key}` must be a positive integer");
                }//if

                break;

            case 'float':

                if(!$this->_isValidFloat($key,$value)){
                    return false;
                }//if

                break;

            case 'ufloat':

                if(!$this->_isValidFloat($key,$value)){
                    return false;
                }//if

                if($value < 0){
                    return $this->setError($key,"`{$key}` must be a positive number");
                }//if

                break;

            case 'string':

                if(!is_string($value)){
                    return $this->setError($key,"`{$key}` must be a string");
                }//if

                if(($min = $this->getDefinitionValue($key,'minlen')) !== false && strlen($value) < $min){
                    return $this->setError($key,"`{$key}` must be greater than {$min} characters long");
                }//if

                if(($max = $this->getDefinitionValue($key,'maxlen')) !== false && strlen($value) > $max){
                    return $this->setError($key,"`{$key}` must be less than {$max} characters long");
                }//if

                break;

            case 'char':

                if(!is_string($value) || strlen($value) != 1){
                    return $this->setError($key,"`{$key}` must be a single character");
                }//if

                break;

            case 'boolean':

                if(!is_bool($value)){
                    return $this->setError($key,"`{$key}` must be a boolean value");
                }//if

                break;

            case 'array':

                if(!is_array($value)){
                    return $this->setError($key,"`{$key}` must be an array");
                }//if

                break;

            case 'object':

                if(is_object($value)){
                    if(($instanceof = $this->getDefinitionValue($key,'instanceof')) !== false && !$value instanceof $instanceof){
                        return $this->setError($key,"`{$key}` must be an instance of `{$instanceof}`");
                    }//if
                } //if
                else {
                    return $this->setError($key,"`{$key}` must be an object");
                }//if

                break;

            case 'closure':

                if(!is_object($value) || !$value instanceof \Closure){
                    return $this->setError($key,"`{$key}` must be a closure");
                }//if

                break;

            default:
                return $this->setError($key);

        }//switch

        //IN
        if(($in = $this->getDefinitionValue($key,'in')) !== false && !in_array($value,$in)){
            $in = implode(', ',$in);
            return $this->setError($key,"`{$key}` must be a value of `{$in}`");
        }//if

        //NOTIN
        if(($in = $this->getDefinitionValue($key,'notin')) !== false && in_array($value,$in)){
            $in = implode(', ',$in);
            return $this->setError($key,"`{$key}` must not be a value of `{$in}`");
        }//if

        $this->_postMassage($key,$value);

    }//verify

    /**
     * Set an error.
     *
     * @param string $key The data key.
     * @param null|string The error message to set, if null, the `defaultErrorMessage` will be used.
     *
     * @return boolean Always returns false, which eases chaining in the `verifyData` method.
    */
    protected final function setError($key, $error = null){
        if($e = $this->getDefinitionValue($key,'error')){
            $error = $e;
        } else if($error === null){
            $error = sprintf($this->defaultErrorMessage,$key);
        }//elif
        $this->errors[$key] = $error;
        return false;
    }//setError

    /**
     * Get an error.
     *
     * @param string $key The data key.
     *
     * @return boolean|string False if no error for `$key`, otherwise the error string.
    */
    public function getError($key){

        if(!isset($this->errors[$key])){
            return false;
        }//if

        return $this->errors[$key];

    }//getError

    /**
     * Get all the errors in the data model. Errors being set are dependent on calling the methods `verify` and
     * `verifyData`.
     *
     * @return array
    */
    public final function getErrors(){
        return $this->errors;
    }//getErrors

    /**
     * Clear all errors from the data model.
    */
    public final function clearErrors(){
        $this->errors = Array();
    }//clearErrors

    /**
     * Get all the data models definitions.
     *
     * @return array The entire data model definition.
    */
    public final function getAllDefinitions(){
        return $this->definition;
    }//getAllDefinitions

    /**
     * Get a datums definition.
     *
     * @param string $key The data key.
     *
     * @return array The definition.
    */
    public final function getDefinition($key){
        return $this->definition[$key];
    }//getDefinition

    /**
     * Set a datums definition. Cannot overwrite previously defined definitions.
     *
     * @param string $key The definition key.
     * @param array $value The definition.
     *
     * @throws \Disco\exceptions\Exception When setting the definition would override a frozen data model definition.
    */
    public final function setDefinition($key, $value){
        if(array_key_exists($key, $this->definition)){
            throw new \Disco\exceptions\Exception("Cannot override frozen data model definition `{$key}`");
        }//if
        $this->definition[$key] = $value;
    }//setDefinition

    /**
     * Get a single value that resides within a single data definition.
     *
     * @param string $key The definition key.
     * @param string $condition The definition key child key.
     * @param mixed False when the condition is not set, otherwise the condition value.
     *
     * @return mixed
    */
    public final function getDefinitionValue($key, $condition){
        if(!array_key_exists($key, $this->definition) || !array_key_exists($condition, $this->definition[$key])){
            return false;
        }//if
        return $this->definition[$key][$condition];
    }//getDefinitionValue

    /**
     * Get all the data set in the data model.
     *
     * @return array
    */
    public final function getData(){
        return $this->data;
    }//getData

    /**
     * Get a field of the data model using object syntax.
     *
     *
     * @param string $key The key.
     *
     * @return mixed
    */
    public function __get($key){
        return $this->data[$key];
    }//__get

    /**
     * Set a field of the data model using object syntax.
     *
     *
     * @param string $key The key.
     * @param mixed $value The value.
     *
     * @throws \Disco\exceptions\Exception When the data model doesn't support that field.
    */
    public function __set($key,$value){
        if(!array_key_exists($key,$this->definition)){
            throw new \Disco\exceptions\Exception("Field `{$key}` is not defined by this data model");
        }//if
        $this->data[$key] = $value;
    }//__set

    /**
     * Determine whether a field exists in the data model.
     *
     *
     * @param string $key The key.
     *
     * @return boolean
    */
    public function __isset($key){
        return isset($this->data[$key]);
    }//__isset

    /**
     * Delete a field from the data model (Set it to null).
     *
     *
     * @param string $key The key.
    */
    public function __unset($key){
        if(isset($this->data[$key])){
            $this->data[$key] = null;
        }//if
    }//__unset

    /**
     * Get a field of the data model using array access syntax.
     *
     *
     * @param string $key The key.
     *
     * @return mixed
    */
    public function offsetGet($key){
        return $this->offsetExists($key) ? $this->data[$key] : null;
    }//offsetGet

    /**
     * Set a field of the data model using array access syntax.
     *
     *
     * @param string $key The key.
     * @param mixed $value The value.
     *
     * @throws \Disco\exceptions\Exception When the data model doesn't support that field.
    */
    public function offsetSet($key,$value){
        if(!array_key_exists($key,$this->definition)){
            throw new \Disco\exceptions\Exception("Field `{$key}` is not defined by this data model");
        }//if
        $this->data[$key] = $value;
    }//offsetSet

    /**
     * Determine whether a field exists in the data model.
     *
     *
     * @param string $key The key.
     *
     * @return boolean
    */
    public function offsetExists($key){
        return isset($this->data[$key]);
    }//offsetExists

    /**
     * Delete a field from the data model (Set it to null).
     *
     *
     * @param string $key The key.
    */
    public function offsetUnset($key){
        if($this->offsetExists($key)){
            unset($this->data[$key]);
        }//if
    }//offsetUnset

    /**
     * Apply a post massage function to a data value.
     *
     * @param string $key The data key.
     * @param mixed $value The data value.
    */
    protected final function _postMassage($key,$value){

        //POSTMASSAGE
        if(($massage = $this->getDefinitionValue($key,'postmassage')) !== false){
            $this->data[$key] = $this->{$massage}($value);
        }//if

    }//_postMassage

    /**
     * Determine if the value is a valid int.
     *
     * @param string $key The data key.
     * @param mixed $value The data value.
     *
     * @return boolean
    */
    protected final function _isValidInt($key,$value){

        if(!is_numeric($value) || strpos($value,'.') !== false){
            return $this->setError($key,"`{$key}` must be a integer");
        }//if

        if(!$this->_isBetweenMinAndMax($key,$value)){
            return false;
        }//if

        return true;

    }//_isValidInt

    /**
     * Determine if the value is a valid float.
     *
     * @param string $key The data key.
     * @param mixed $value The data value.
     *
     * @return boolean
    */
    protected final function _isValidFloat($key,$value){

        if(!is_numeric($value)){
            return $this->setError($key,"`{$key}` must be numeric");
        }//if

        if(!$this->_isBetweenMinAndMax($key,$value)){
            return false;
        }//if

        return true;

    }//_isValidFloat

    /**
     * Determine if the value is greater than `min` if set, and less than `max` if set.
     *
     * @param string $key The data key.
     * @param mixed $value The data value.
     *
     * @return boolean
    */
    protected final function _isBetweenMinAndMax($key,$value){

        if(($min = $this->getDefinitionValue($key,'min')) !== false && $value < $min){
            return $this->setError($key,"`{$key}` must be greater than {$min}");
        }//if

        if(($max = $this->getDefinitionValue($key,'max')) !== false && $value > $max){
            return $this->setError($key,"`{$key}` must be less than {$max}");
        }//if

        return true;

    }//_isBetweenMinAndMax

}//DataModel