text:
class SetRegistrantDefaultWheelSize < ActiveRecord::Migration
  class EventConfiguration < ActiveRecord::Base
  end
  class WheelSize < ActiveRecord::Base
  end

  class Registrant < ActiveRecord::Base
    def age
      start_date = EventConfiguration.singleton.start_date
      if start_date.nil? || birthday.nil?
        99
      else
        if (birthday.month < start_date.month) || (birthday.month == start_date.month && birthday.day <= start_date.day)
          start_date.year - birthday.year
        else
          (start_date.year - 1) - birthday.year
        end
      end
    end

    def set_default_wheel_size
      if default_wheel_size.nil?
        if age > 10
          self.default_wheel_size = WheelSize.find_by_description("24\" Wheel")
        else
          self.default_wheel_size = WheelSize.find_by_description("20\" Wheel")
        end
      end
    end

    belongs_to :default_wheel_size, class_name: "WheelSize", foreign_key: :wheel_size_id
  end

  def up
    WheelSize.find_or_create_by(position: 1, description: "16\" Wheel")
    WheelSize.find_or_create_by(position: 2, description: "20\" Wheel")
    WheelSize.find_or_create_by(position: 3, description: "24\" Wheel")
    EventConfiguration.reset_column_information
    WheelSize.reset_column_information
    Registrant.reset_column_information
    Registrant.all.each do |reg|
      reg.set_default_wheel_size
      reg.save(validate: false)
    end
  end

  def down
    EventConfiguration.reset_column_information
    WheelSize.reset_column_information
    Registrant.reset_column_information
    Registrant.all.each do |reg|
      reg.default_wheel_size = nil
      reg.save(validate: false)
    end
  end
end


text:
import styled, { css } from "styled-components";

export const LineGroup = styled.g`
  stroke-width: 2.25;
  stroke-linecap: round;
  will-change: stroke;
  transition: stroke 0.2s;
  transform: translate(9px,1px);
  ${({ theme }: { theme: Theme }) => css`
    stroke: ${theme.color.black};
    &:hover {
      stroke: ${theme.effect.darken(0.2, theme.color.black)};
    }
  `}
`;

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace ztn\UtilisateurBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use FOS\UserBundle\Form\Type\RegistrationFormType as baseType;

class RegistrationFormType extends baseType
{
    private $container;

    /**
     * @param string $class The User class name
     */
    public function __construct($container)
    {

       parent::__construct('ztn\UtilisateurBundle\Entity\User');

       $this->container = $container;

    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {

        $builder
            ->add('utilisateurNom', 'text', array(
                'label' => 'nom'))
            ->add('utilisateurPrenom', 'text', array(
                'label' => 'prenom'))
           /* ->add('civilite', 'choice', array(
                'choices' => array('m' => 'Homme', 'f' => 'Femme')))*/
            ->add('email', 'email', array('label' => 'email'))
            ->add('plainPassword', 'repeated', array(
                'type' => 'password',
                'options' => array('translation_domain' => 'FOSUserBundle'),
                'first_options' => array('label' => 'mot de passe', 'label_attr' => array('class' => 'control-label')),
                'second_options' => array('label' => 'Nouveau mot de passe', 'label_attr' => array('class' => 'control-label')),
                'invalid_message' => 'Les 2 mots de passes saisis sont différents',
                ))
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'ztn\UtilisateurBundle\Entity\User',
        ));
    }

    public function getName()
    {
        return 'ztn_utilisateur_registration';
    }
}


text:
var application_root = __dirname,
    express = require('express'),
    path = require('path'),
    bodyParser = require('body-parser'),
    errorHandler = require('errorhandler'),
    mongoose = require('mongoose');

var app = express();

var env = process.env.NODE_ENV || 'development';

app.use(bodyParser.urlencoded({
  extended: true
}));

app.use(express.static(path.join(application_root, 'site')));

app.use(errorHandler({
  dumpExceptions: true,
  showStack: true
}));

app.get('/api', function(req, res){
	res.send('hello world');
});

mongoose.connect('mongodb://localhost/library');

var Book = new mongoose.Schema({
	title: String,
	author: String,
	releaseDate: Date
});

var BookModel = mongoose.model('Book', Book);

app.get('/api/books', function(request, response) {
	return BookModel.find(function(err, books) {
		if (!err) {
			return response.send(books);
		} else {
			return console.log(err);
		}
	});
});

app.post('/api/books', function(request, response) {
	console.log(request.body.title);

	var book = new BookModel({
		title: request.body.title,
		author: request.body.author,
		releaseDate: request.body.releaseDate
	});

	book.save(function(err) {
		if (!err) {
			return console.log('created');
		} else {
			return console.log(err);
		}
	});

	return response.send(book);
});

app.get('/api/books/:id', function(request, response) {
	console.log(request.params.id);

	return BookModel.findById(request.params.id, function(err, book) {
		if (!err) {
			return response.send(book);
		} else {
			return console.log(err);
		}
	})
});

app.put('/api/books/:id', function(request, response) {
	console.log('Updating book' + request.body.title);

	return BookModel.findById(request.params.id, function(err, book) {
		book.title = request.body.title;
		book.author = request.body.author;
		book.releaseDate = request.body.releaseDate;

		return book.save(function(err) {
			if (!err) {
				console.log('book updated');
			} else {
				console.log(err);
			}

			return response.send(book);
		})
	});
});

app.delete('/api/books/:id', function(request, response) {
	console.log('Deleting book with id: ' + request.params.id);

	return BookModel.findById(request.params.id, function(err, book) {
		return book.remove(function(err) {
			if (!err) {
				console.log('Book removed');

				return response.send('');
			} else {
				console.log(err);
			}
		});
	});
});

var port = 4711;

app.listen(port, function () {
  console.log('Express server listening on port %d in %s mode', port, app.settings.env);
});


text:
package net.java.sip.communicator.impl.gui.main.call.conference;

import java.awt.*;

import net.java.sip.communicator.impl.gui.main.call.*;
import net.java.sip.communicator.service.gui.call.*;
import net.java.sip.communicator.service.protocol.*;

/**
 * The <tt>ThumbnailConferenceCallPanel</tt> is the panel containing all video
 * conference participants as thumbnails.
 *
 * @author Yana Stamcheva
 */
public class ThumbnailConferenceCallPanel
    extends AudioConferenceCallPanel
{
    /**
     * Initializes a new <tt>ThumbnailConferenceCallPanel</tt> instance which is
     * to be used by a specific <tt>CallPanel</tt> to depict a specific
     * <tt>CallConference</tt>. The new instance will depict both the
     * audio-related and the video-related information.
     *
     * @param callPanel the <tt>CallPanel</tt> which will use the new instance
     * to depict the specified <tt>CallConference</tt>.
     * @param callConference the <tt>CallConference</tt> to be depicted by the
     * new instance
     * @param uiVideoHandler the utility which is to aid the new instance in
     * dealing with the video-related information
     */
    public ThumbnailConferenceCallPanel(CallPanel callPanel,
                                        CallConference callConference,
                                        UIVideoHandler2 uiVideoHandler)
    {
        super(callPanel, callConference);

        setBackground(Color.DARK_GRAY);
    }

    /**
     * Updates the thumbnail of the given <tt>callPeer</tt>.
     *
     * @param callPeer the <tt>CallPeer</tt>, which thumbnail
     * to update
     * @param isVideo indicates if the video is enabled for the
     * <tt>callPeer</tt>
     */
    public void updateThumbnail(CallPeer callPeer, boolean isVideo)
    {
        CallPeerRenderer peerRenderer = getCallPeerRenderer(callPeer);

        if (peerRenderer instanceof ConferencePeerPanel)
        {
            ((ConferencePeerPanel) peerRenderer)
                .enableVideoIndicator(isVideo);
        }

        if (peerRenderer instanceof ConferenceFocusPanel)
        {
            ((ConferenceFocusPanel) peerRenderer)
                .enableVideoIndicator(isVideo);
        }
    }

    /**
     * Updates the thumbnail of the given <tt>conferenceMember</tt>.
     *
     * @param conferenceMember the <tt>ConferenceMember</tt>, which thumbnail
     * to update
     * @param isVideo indicates if the video is enabled for the conference
     * member
     */
    public void updateThumbnail(ConferenceMember conferenceMember,
                                boolean isVideo)
    {
        CallPeerRenderer focusRenderer
            = getCallPeerRenderer(conferenceMember.getConferenceFocusCallPeer());

        if (focusRenderer instanceof ConferenceFocusPanel)
        {
            ((ConferenceFocusPanel) focusRenderer)
                .enableVideoIndicator(conferenceMember, isVideo);
        }
    }

    /**
     * Updates the local user thumbnail.
     *
     * @param isVideo indicates if the video is enabled for the local user
     */
    public void updateThumbnail(boolean isVideo)
    {
        CallPeerRenderer peerRenderer = getCallPeerRenderer(null);

        if (peerRenderer instanceof ConferencePeerPanel)
        {
            ((ConferencePeerPanel) peerRenderer)
                .enableVideoIndicator(isVideo);
        }
    }
}


text:
<!DOCTYPE html>

		<title>Cat fight</title>

A canvas game with cats

	<canvas id="canvas1" width="700" height="300" style="border:1px dotted" ></canvas>


text:
<?php
/**
 * Created by PhpStorm.
 * User: Jean
 * Date: 09/10/2014
 * Time: 23:22
 */

namespace RumeauLibAppConfig\Controller;

use RumeauLibAppConfig\Entity\AppConfig;
use Zend\Form\Form;
use Zend\Http\Response;
use Zend\Mvc\Controller\AbstractActionController;

/**
 * Class ConfigController
 * @package RumeauLibAppConfig\Controller
 */
class ConfigController extends AbstractActionController
{
    public function indexAction()
    {
        $appConfigEvent = $this->getServiceLocator()->get('RumeauLibAppConfig\Event\AppConfigEvent');
        /**
         * @var \Zend\Form\Form $form
         */
        $form           = $appConfigEvent->loadForm();

        $url            = $this->getRequest()->getRequestUri();
        $prg            = $this->getConfigPrg($form, $url);
        if ($prg instanceof Response) {
            return $prg;
        } elseif (is_array($prg)) {
            $modelManager = $this->getServiceLocator()->get('ModelManager');
            $model        = $modelManager->get('RumeauLibAppConfig\Model\AppConfig', [new AppConfig()]);
            $result = $model->saveConfig($form, $prg);
            if ($result instanceof Response) {
                return $result;
            }
        }

        $form->prepare();

        return [
            'form' => $form,
        ];
    }

    /**
     * @param Form $form
     * @param null $url
     * @return array|bool|Response
     */
    protected function getConfigPrg(Form $form, $url = null)
    {
        if ($form->getAttribute('enctype') == 'multipart/form-data') {
            $prg = $this->fileprg($form, $url, $url != null ? true : false);
        } else {
            $prg = $this->prg($url, $url != null ? true : false);
        }

        return $prg;
    }
}


text:
/**
 * Created by perlerd on 2017-07-09.
 */

export class ConfigurationError extends Error {}

export class RuntimeError extends Error {}


text:
using namespace clang;
using namespace clang::frontend;

#define LANGSTANDARD(id, name, desc, features) \
  static const LangStandard Lang_##id = { name, desc, features };
#include "clang/Frontend/LangStandards.def"

const LangStandard &LangStandard::getLangStandardForKind(Kind K) {
  switch (K) {
  case lang_unspecified:
    llvm::report_fatal_error("getLangStandardForKind() on unspecified kind");
#define LANGSTANDARD(id, name, desc, features) \
    case lang_##id: return Lang_##id;
#include "clang/Frontend/LangStandards.def"
  }
  llvm_unreachable("Invalid language kind!");
}

const LangStandard *LangStandard::getLangStandardForName(StringRef Name) {
  Kind K = llvm::StringSwitch<Kind>(Name)
#define LANGSTANDARD(id, name, desc, features) \
    .Case(name, lang_##id)
#include "clang/Frontend/LangStandards.def"
    .Default(lang_unspecified);
  if (K == lang_unspecified)
    return 0;

  return &getLangStandardForKind(K);
}


text:
package htsjdk.samtools;

import static org.junit.Assert.assertTrue;
import htsjdk.samtools.cram.ref.ReferenceSource;
import htsjdk.samtools.seekablestream.SeekableFileStream;
import htsjdk.samtools.seekablestream.SeekableStream;
import htsjdk.samtools.util.Log;
import htsjdk.samtools.util.Log.LogLevel;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

public class CrossIndexTest {
	static Log log = Log.getInstance(CrossIndexTest.class);

	public static void main(String[] args) throws IOException {
		Log.setGlobalLogLevel(LogLevel.INFO);
		File cramFile = new File(args[0]);
		File refFile = new File(args[1]);
		File craiFile = new File(cramFile.getAbsolutePath() + ".crai");
		File baiFile = new File(cramFile.getAbsolutePath() + ".bai");

		assertTrue(cramFile.isFile());
		assertTrue(craiFile.isFile());
		assertTrue(baiFile.isFile());
		assertTrue(refFile.isFile());

		SeekableStream cramStream = new SeekableFileStream(cramFile);
		CRAMFileReader reader = new CRAMFileReader(cramFile, new ReferenceSource(refFile));
		IndexAggregate indexAgg = IndexAggregate
				.forDataFile(cramStream, reader.getFileHeader().getSequenceDictionary());

		IndexAggregate craiAgg = IndexAggregate.fromCraiFile(new FileInputStream(craiFile), reader.getFileHeader()
				.getSequenceDictionary());

		IndexAggregate baiAgg = IndexAggregate.fromBaiFile(new SeekableFileStream(baiFile), reader.getFileHeader()
				.getSequenceDictionary());

		SAMSequenceRecord seq = reader.getFileHeader().getSequence(19);
		// {
		// // 2669001-2669057
		// long craiOffset = craiAgg.seek(19, 2669001, 2669057, cramStream);
		// long baiOffset = baiAgg.seek(19, 2669001, 2669057, cramStream);
		// System.out.println(craiOffset);
		// System.out.println(baiOffset);
		// }
		// {
		// // 19:4163001-4163002
		// long craiOffset = craiAgg.seek(19, 4163001, 4163002, cramStream);
		// long baiOffset = baiAgg.seek(19, 4163001, 4163002, cramStream);
		// System.out.println(craiOffset);
		// System.out.println(baiOffset);
		// }
		// System.exit(1);

		Set<Long> offsets = new HashSet<Long>();
		long time = System.currentTimeMillis();

		int seqId = 19;
		for (int span = 1; span < 100000; span++) {
			for (int start = 1; start < seq.getSequenceLength() - span; start += 1000) {
				long craiOffset = craiAgg.seek(seqId, start, start + span, cramStream);
				long baiOffset = baiAgg.seek(seqId, start, start + span, cramStream);
				long offset = indexAgg.seek(seqId, start, start + span, cramStream);

				if (craiOffset != baiOffset || craiOffset != offset)
					throw new RuntimeException(String.format("Offsets mismatch for query: %d:%d-%d", seqId, start,
							start + span));

				offsets.add(craiOffset);

				if (System.currentTimeMillis() - time > 10000) {
					log.info(String.format("Tested: start=%d, span=%d, unique offsets=%d", start, span, offsets.size()));
					time = System.currentTimeMillis();
				}
			}
		}

		for (long offset : offsets) {
			System.out.println(offset);
		}
	}
}


text:
<?xml version="1.0" encoding="utf-8"?><!--
  ~ Copyright 2015. Alex Zhang aka. ztc1997
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@mipmap/ic_star_blue_24dp" android:state_activated="true" />
    <item android:drawable="@mipmap/ic_star_blue_24dp" android:state_pressed="true" />
    <item android:drawable="@mipmap/ic_star_grey600_24dp" />
</selector><!-- From: file:/C:/Users/qweas/Desktop/ZprogrammerTool/app/src/main/res/drawable/ic_item_drawer_main_favorites.xml -->


text:
/*! iris - v0.5.6-SNAPSHOT - 2014-01-13 (http://thegameofcode.github.io/iris) licensed New-BSD */

var iris = {};

// Expose iris to the global object
window.iris = iris;

(function ($) {

    // static object to store all app callbacks
    var _events;

    function _init() {

        _events = {};

        iris.on("iris-reset", _init);
    }

    iris.on = function (p_eventName, f_func) {

        if ( ! $.isFunction(f_func) ) {
            throw "invalid function";
        }

        if ( !_events.hasOwnProperty(p_eventName) ) {
            _events[p_eventName] = [];
        }

        var callbacks = _events[p_eventName];
        var index = $.inArray(f_func, callbacks);
        if ( index === -1 ) {
            callbacks.push(f_func);
        }

    };

    iris.off = function (p_eventName, f_func){
        if ( _events.hasOwnProperty(p_eventName) ){
            if (f_func !== undefined) {

                if ( ! $.isFunction(f_func) ) {
                    throw "invalid function";
                }

                var index = $.inArray(f_func, _events[p_eventName]);
                if ( index !== -1 ) {
                    _events[p_eventName].splice(index, 1);
                }

            } else {
                delete _events[p_eventName];
            }
        }
    };

    iris.notify = function (p_eventName, p_data){
        if ( p_eventName === undefined ) {
            throw "event name undefined";
        }

        if ( _events[p_eventName] ) {
            var callbacks = _events[p_eventName];
            for ( var i=0; i < callbacks.length; i++ ) {
                callbacks[i](p_data);
            }
        }
    };

    iris.destroyEvents = function (p_eventName, p_callbacks) {
        // Create an array copy, to prevent concurrent modification of _events[p_eventName] array.
        // This occur if an event that destroy uis is notified
        var callbacks = _events[p_eventName].concat([]);
        for ( var i=0; i < p_callbacks.length; i++ ) {
            var index = $.inArray(p_callbacks[i], callbacks);
            if ( index !== -1 ) {
                callbacks.splice(index, 1);
            }
        }
        _events[p_eventName] = callbacks;
    };

    iris.Event = function () {

        this.events = {}; // { "event1" : [f1, f2], "event2" : [f3, f4, f5, f6] }

    };

    var eventPrototype = iris.Event.prototype;

    eventPrototype.on = function (p_eventName, f_func) {
        if ( ! $.isFunction(f_func) ) {
            throw "invalid function";
        }

        if ( !this.events.hasOwnProperty(p_eventName) ) {
            this.events[p_eventName] = [];
        }

        var callbacks = this.events[p_eventName];
        var index = $.inArray(f_func, callbacks);
        if ( index === -1 ) {
            callbacks.push(f_func);
            iris.on(p_eventName, f_func);
        }

    };

    eventPrototype.off = function (p_eventName, f_func) {

        // if f_func is undefined removes all callbacks
        if ( f_func !== undefined && ! $.isFunction(f_func) ) {
            throw "invalid function";
        }

        var callbacks = this.events[p_eventName];
        if ( callbacks ) {

            if (f_func !== undefined) {
                var index = $.inArray(f_func, callbacks);

                if ( index !== -1 ) {
                    callbacks.splice(index, 1);
                    iris.off(p_eventName, f_func);
                }

            } else {

                for (var i = 0; i < callbacks.length; i++ ) {
                    iris.off(p_eventName, callbacks[i]);
                }

                this.events[p_eventName] = {};
            }
        }
    };

    eventPrototype.notify = function (p_eventName, p_data){
        iris.notify(p_eventName, p_data);
    };

    //
    // Iris custom events
    //
    iris.BEFORE_NAVIGATION = "iris_before_navigation";
    iris.AFTER_NAVIGATION = "iris_after_navigation";
    iris.RESOURCE_ERROR = "iris_resource_error";
    iris.SCREEN_NOT_FOUND = "iris_screen_not_found";

    _init();

})(jQuery);

(function($) {

    var _JQ_MIN_VER = 1.5,
        _appBaseUri,
        _cache,
        _cacheVersion,
        _log,
        _logEnabled;

    //
    // Private
    //
    function _init() {

        if ( typeof jQuery === "undefined" ) {
            throw "jQuery " + _JQ_MIN_VER + "+ previous load required";
        } else if($().jquery < _JQ_MIN_VER) {
            throw "jQuery " + $().jquery + " currently loaded, jQuery " + _JQ_MIN_VER + "+ required";
        }

        var console = window.console;
        if ( typeof console !== 'undefined' && typeof console.log === 'object' ) {
            var bind = Function.prototype.bind;
            if ( bind ) {
                // Fix IE 9 Problem with console.
                // http://stackoverflow.com/questions/5538972/console-log-apply-not-working-in-ie9
                _log = bind.call(console.log, console);
            } else {
                // Fix IE 8 Problem with console.
                // http://patik.com/blog/complete-cross-browser-console-log/
                _log = function () {
                    Function.prototype.call.call(console.log, console, Array.prototype.slice.call(arguments));
                };
            }
        } else if ( console && console.log ) {
            // Modern browser
            _log = console.log;
        }

        var isLocalEnv = urlContains("localhost", "127.0.0.1");
        _logEnabled = isLocalEnv;
        _cache = !isLocalEnv;

        iris.on("iris-reset", _init);
    }

    function urlContains () {
        for(var i = 0 ; i< arguments.length; i++) {
            if ( document.location.href.indexOf(arguments[i]) > -1 ) {
                return true;
            }
        }
        return false;
}

    //
    // Public
    //
    iris.baseUri = function (p_baseUri) {
        if ( p_baseUri !== undefined ) {
            _appBaseUri = p_baseUri;

        } else if ( _appBaseUri === undefined ) {
            var base = document.getElementsByTagName("base");
            base = base.length > 0 ? base[0].attributes.href.value : "/";
            _appBaseUri = document.location.protocol + "//" + document.location.host + base;
        }
        return _appBaseUri;
    };

    iris.cache = function (p_value) {
        if(p_value !== undefined) {
            _cache = p_value;
        } else {
            return _cache;
        }
    };

    iris.cacheVersion = function (p_value) {
        if(p_value !== undefined) {
            _cacheVersion = p_value;
        } else {
            return _cacheVersion;
        }
    };

    iris.log = function () {
        if ( _logEnabled && _log ) {
            _log.apply(window.console, arguments);
        }
    };

    iris.enableLog = function () {
        if ( typeof arguments[0] === "boolean" ) {
            _logEnabled = arguments[0];

        } else if ( arguments.length > 0 ) {
            _logEnabled = urlContains.apply(this, arguments);

        } else {
            return _logEnabled;
        }
    };

    iris.noCache = function () {
        if ( arguments.length > 0 ) {
            _cache = !urlContains.apply(this, arguments);
        } else {
            return !_cache;
        }
    };

    _init();

})(jQuery);

(function($) {

    var _translations;

    function _init() {
        _translations = {};
    }

    //
    // Private
    //
    function _addTranslations(p_locale, p_data) {
        iris.log("[translations]", p_locale, p_data);

        if(iris.locale() === undefined) {
            iris.locale(p_locale);
        }

        if(!_translations.hasOwnProperty(p_locale)) {
            _translations[p_locale] = {};
        }

        $.extend(_translations[p_locale], p_data);
    }

    function _loadTranslations(p_locale, p_uri, p_settings) {

        iris.log("[translations]", p_locale, p_uri);

        var ajaxSettings = {
            url: p_uri,
            dataType: "json",
            async: false,
            cache: iris.cache()
        };

        if(iris.cache() && iris.cacheVersion()) {
            ajaxSettings.data = "_=" + iris.cacheVersion();
        }

        iris.ajax(ajaxSettings)
        .done(function (p_data) {
            _addTranslations(p_locale, p_data);
            iris.log("[translations]", p_data);

            if(p_settings && p_settings.hasOwnProperty("success")) {
                p_settings.success(p_locale);
            }
        })
        .fail(function(p_err) {
            if(p_settings && p_settings.hasOwnProperty("error")) {
                p_settings.error(p_locale);
            }
            throw "Error " + p_err.status + " loading lang file[" + p_uri + "]";
        });
    }

    //
    // Public
    //
    iris.translations = function (p_locale, p_value, p_settings) {
        if(typeof p_value === "object") {
            _addTranslations(p_locale, p_value);
        } else {
            _loadTranslations(p_locale, p_value, p_settings);
        }
    };

    iris.translate = function (p_label, p_locale) {
        var value;
        var locale = null;
        if (p_locale !== undefined) {
            locale = p_locale;
        } else {
            locale = iris.locale();
        }

        var logPrefix = "[translate]";
        if(_translations.hasOwnProperty(locale)) {
            value = iris.val(_translations[locale], p_label);
            if(value === undefined) {
                iris.log(logPrefix + " label '" + p_label + "' not found in Locale '" + locale + "'", _translations[locale]);
            }
            if(typeof value === "object") {
                iris.log(logPrefix + "label '" + p_label + "' is an object but must be a property in Locale '" + locale + "'", _translations[locale]);
            }
        } else {
            iris.log(logPrefix + " locale '" + locale + "' not loaded", this);
        }
        return (value !== undefined) ? value : "??" + p_label + "??";
    };

    _init();

})(jQuery);

(function() {

    var _locale, _regional;

    function _init() {
        _locale = undefined;
        _regional = {};

        iris.on("iris-reset", _init);
    }

    iris.locale = function (p_locale, p_regional) {
        if ( typeof p_regional === "object" ) {
            if ( !_regional[p_locale] ) {
                _regional[p_locale] = {};
            }
            $.extend(_regional[p_locale], p_regional);

            if ( _locale === undefined ) {
                _locale = p_locale;
            }

        } else if ( p_locale !== undefined ) {
            _locale = p_locale;

        } else {
            return _locale;
        }
    };

    iris.regional = function (p_label) {
        if(_regional.hasOwnProperty(_locale)) {
            if(typeof p_label === "undefined") {
                return _regional[_locale];
            } else if(_regional[_locale].hasOwnProperty(p_label)) {
                return _regional[_locale][p_label];
            } else {
                return undefined;
                //throw "[regional] setting '" + p_label + "' not found for locale '" + _locale + "'";
            }
        } else {
            throw "[regional] for locale '" + _locale + "' not found";
        }
    };

    _init();

})();

(function($) {

    //
    // Private
    //

    var browser;

    function setBrowser (ua) {
        ua = ua.toLowerCase();

        var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
            /(webkit)[ \/]([\w.]+)/.exec( ua ) ||
            /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
            /(msie) ([\w.]+)/.exec( ua ) ||
            ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
            [];

        return {
            name: match[ 1 ] || "",
            version: match[ 2 ] || "0"
        };
    }

    function leadingZero(p_number) {
        return(p_number < 10) ? "0" + p_number : p_number;
    }

    function formatDateChar(p_formatChar, p_date) {
        var regional = iris.regional();
        switch(p_formatChar) {
        case "y":
            return String(p_date.getFullYear()).substring(2);
        case "Y":
            return p_date.getFullYear();
        case "m":
            var m = p_date.getMonth() + 1;
            return leadingZero(m);
        case "n":
            return p_date.getMonth() + 1;
        case "M":
            return regional.monthNames[p_date.getMonth()].substring(0, 3);
        case "b":
            return regional.monthNames[p_date.getMonth()].substring(0, 3).toLowerCase();
        case "F":
            return regional.monthNames[p_date.getMonth()];
        case "d":
            var d = p_date.getDate();
            return leadingZero(d);
        case "D":
            return regional.dayNames[p_date.getDay()].substring(0, 3);
        case "l":
            return regional.dayNames[p_date.getDay()];
        case "s":
            var s = p_date.getSeconds();
            return leadingZero(s);
        case "i":
            var i = p_date.getMinutes();
            return leadingZero(i);
        case "H":
            var h = p_date.getHours();
            return leadingZero(h);
        case "h":
            var hour = p_date.getHours();
            hour = (hour % 12) === 0 ? 12 : hour % 12;
            return leadingZero(hour);
        case "a":
            return(p_date.getHours() > 12) ? "p.m." : "a.m.";
        case "A":
            return(p_date.getHours() > 12) ? "PM" : "AM";
        case "U":
            return Math.floor(p_date.getTime() * 0.001);
        default:
            return p_formatChar;
        }
    }

    //
    // Public
    //

    iris.date = function (p_date, p_format) {
        if ( p_date === null ) {
            return "";
        }

        if(!p_format) {
            p_format = iris.regional("dateFormat");
        }

        if(typeof p_date !== "object") {
            p_date = new Date(p_date);
        }

        var dateFormat = "";
        for(var f = 0, F = p_format.length; f < F; f++) {
            dateFormat += formatDateChar(p_format[f], p_date);
        }
        return dateFormat;
    };

    iris.ajax = function (p_settings) {
        return $.ajax(p_settings);
    };

    iris.currency = function (value, config) {
        var settings = {
            formatPos: "sn",
            formatNeg: "(sn)",
            symbol : "$"
        };
        $.extend(settings, iris.regional("currency"), config);

        var num = iris.number(value, settings);

        return num.replace("s", settings.symbol);
    };

    iris.number = function (value, config) {
        var settings = {
            formatPos: "n",
            formatNeg: "- n",
            decimal: ".",
            thousand: ",",
            precision: 2
        };
        $.extend(settings, iris.regional("number"), config);

        var val = Number(value);
        var format = (val >= 0) ? settings.formatPos : settings.formatNeg;

        var dec = val % 1;
        var num = String(Math.abs(val - dec));

        for(var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) {
            num = num.substring(0, num.length - (4 * i + 3)) + settings.thousand + num.substring(num.length - (4 * i + 3));
        }

        if ( settings.precision > 0 ) {
            dec = String(Math.abs(dec).toFixed(settings.precision));
            dec = dec.substr(2);
            num = num + settings.decimal + dec;
        }

        return format.replace("n", num);
    };

    iris.val = function (p_obj, p_label) {
        var value;
        if(p_label.indexOf(".") > -1) {
            var labels = p_label.split(".");
            var f, F = labels.length;
            for(f = 0; f < F; f++) {
                if(p_obj !== undefined) {
                    p_obj = p_obj[labels[f]];
                } else {
                    break;
                }
            }
            value = p_obj;
        } else {
            value = p_obj[p_label];
        }
        return value;
    };

    // The jQuery.browser() method has been deprecated since jQuery 1.3 and is removed in 1.9. If needed, it is available as part of the jQuery Migrate plugin
    // https://github.com/jquery/jquery-migrate/blob/master/src/core.js
    iris.browser = function () {
        if ( !browser ) {
            var matched = setBrowser( navigator.userAgent );
            browser = {};

            if ( matched.name ) {
                browser[ matched.name ] = true;
                browser.version = matched.version;
            }

            // Chrome is Webkit, but Webkit is also Safari.
            if ( browser.chrome ) {
                browser.webkit = true;
            } else if ( browser.webkit ) {
                browser.safari = true;
            }
        }
        return browser;
    };

    iris.inherits = function (subClass, superClass) {
        var Aux = function() {};
        Aux.prototype = superClass.prototype;
        subClass.prototype = new Aux();
    };

})(jQuery);

(function($) {

  /**
   * Settable class to manage object configurations.
   */
  var Settable = function() {
      iris.Event.call(this);

      this.cfg = {};
  };

  iris.inherits(Settable, iris.Event);

  var pSettable = Settable.prototype;

  pSettable.settings = function(settings) {
    return $.extend(this.cfg, settings);
  };

  pSettable.setting = function(label, value) {
    if ( value === undefined ) {
      if ( !this.cfg.hasOwnProperty(label) ) {
        iris.log("setting '" + label + "' missing", this.cfg, this);
      }
      return this.cfg[label];
    } else {
      this.cfg[label] = value;
    }
  };

  iris.Settable = Settable;

})(jQuery);

(function($) {

    var _screen,
        _includes,
        _welcomeCreated,
        _head = document.getElementsByTagName('head')[0],
        _paths,
        _loadJsCallback,
        _dependencyCount,
        _lastLoadedDependencies,
        FORMAT_REG_EXP = /(date|currency|number)(?:\(([^\)]+)\))/,
        PATH_PARAM_REGEX = /:[\d\w_\-\.]+/g,
        SCREEN_PARAM_REGEX = '[;?&][^=]+=[^;\/&]+', // Validates matrix & url params: ';param=value' & '?param=value' & '&param=value'
        _gotoCancelled,
        _prevNavigationHash, // The hash for the last navigation (finished)
        _navMap,
        _prevNav,
        _prevNavRaw,
        _screenJsUrl,
        _screenContainer,
        _screenHashFragment,
        _screenParentNavMap,
        _jsUrlScreens
        ;

    // Navigation
    // TODO join _screenHashFragment, _screenParentNavMap, _screenJsUrl, _screenContainer in
    // _screenMetadata["#parent/hash/:id"] = { hashFragment: "hash/:id", js:"path.js", container: $, parentNavMap: {} }

    function _init() {
        // _screenJsUrl["#hash"] return the js-url associated with #hash
        _screenJsUrl = {};

        // _screenContainer["#hash"] return the parent container associated with #hash
        _screenContainer = {};

        // _screen["#hash"] return the screen instance
        _screen = {};

        // _jsUrlScreens["/path/to/file.js"] indicates if a js-URL has been used by some screen
        _jsUrlScreens = {};

        _includes = {};
        _welcomeCreated = false;

        // Navigation
        _navMap = {};
        _screenParentNavMap = {};
        _screenHashFragment = {};
        _prevNav = [];
        _prevNavRaw = [];
        _gotoCancelled = false;
        _prevNavigationHash = "";

        // dependencies
        _dependencyCount = 0;
        _lastLoadedDependencies = [];

        _paths = [];

        iris.on("iris-reset", function () {
            $(window).off("hashchange");
            document.location.hash = "#";

            _init();
        });
    }

    function _welcome(p_jsUrl) {
        if ( _welcomeCreated ) {
            throw "welcome screen already exists";
        }
        _welcomeCreated = true;
        _screenJsUrl["#"] = p_jsUrl;
        _screenContainer["#"] = $(document.body);
        _navMap["#"] = {};

        if ( iris.hasOwnProperty("path") ) {
            _loadPaths(iris.path);
        }
        if ( _paths.length > 0 ) {
            _load(_paths, _pathsLoaded);
        } else {
            _pathsLoaded();
        }
    }

    function _loadPaths (paths) {
        if ( typeof paths === "string" ) {
            if ( !_includes.hasOwnProperty(paths) ) {
                _paths.push(paths);
            }
        } else {
            for ( var p in paths ) {
                _loadPaths(paths[p]);
            }
        }
    }

    // Ensure include is defined
    function _setInclude (include, path, type) {
        if ( $.type(path) !== "string" || path === "" ) {
            iris.log("[error] path[" + path + "]", include);
            throw "Invalid path on " + type +" registration";
        }
        _includes[path] = include;
    }

    function _pathsLoaded () {

        // check hashchange event support
        if(!("onhashchange" in window)) {
            throw "hashchange event unsupported";
        } else {

            // force to do an initial navigation according to the actual hash
            // when finished the hashChange listener is added
            _startHashChange();
            $(window).on("hashchange", _startHashChange);
        }
    }

    //
    // Scripts load
    //
    function _load (paths, callback) {
        iris.log("[load-js]", paths);

        _loadJsCallback = callback;

        var path, script;
        for (var i = 0; i < paths.length; i++) {
            if ( !_includes.hasOwnProperty(paths[i]) ) {
                _dependencyCount++;

                // If the path doesn't start with http or https, it's concatenated to the iris base uri
                path = /^https?:\/\//.test(paths[i]) ? paths[i] : String(iris.baseUri() + paths[i]);

                if ( !iris.cache() ) {
                    path += "?_=" + new Date().getTime();
                } else if( iris.cacheVersion() ) {
                    path += "?_=" + iris.cacheVersion();
                }

                if ( /\.html$/.test(paths[i]) ) {
                    iris.ajax({
                        url: path,
                        dataType: "html",
                        async: true,
                        componentPath: paths[i]
                    })
                    .done(_templateLoaded);
                } else {
                    script = document.createElement("script");
                    script.type = "text/javascript";
                    script.src = path;
                    script.charset = "UTF-8";
                    if (iris.browser().msie  && parseInt(iris.browser().version, 10) < 9) {
                        script.onreadystatechange = onReadyStateChange;
                    } else {
                        script.onload = _checkLoadFinish;
                    }
                    _head.appendChild(script);
                }
            }
        }
    }

    function onReadyStateChange () {
        if ( this.readyState === "loaded" ) {
            _checkLoadFinish();
        }
    }

    function _templateLoaded (data, textStatus, jqXHR) {
        _includes[this.componentPath] = data;
        _checkLoadFinish();
    }

    function _checkLoadFinish () {
        if ( --_dependencyCount === 0 ) {
            _loadJsCallback();
        }
    }

    //
    // Navigation
    //
    function _goto(p_hashUri) {
        document.location.hash = p_hashUri; // Trigger hashchange event, then execute _startHashChange()
    }

    function _getHashRegex (hash) {
        return new RegExp('^' + hash.replace(PATH_PARAM_REGEX, '([^/]+)') + '(?:' + SCREEN_PARAM_REGEX + ')*/*' );
    }

    function _getScreenPathParams (screenHash, hash, hashRegex) {
        // Get screen path params
        var params = {};
        var paramsValues = hash.match(hashRegex);
        var i;

        if ( paramsValues ) {
            paramsValues = paramsValues.slice(1); // the first item is the whole match
            if ( paramsValues.length > 0 ) {
                var paramsNames = screenHash.match(PATH_PARAM_REGEX);
                for ( i = 0; i < paramsValues.length; i++ ) {
                    params[ paramsNames[i].substr(1) ] = paramsValues[i]; // Remove first ':'
                }
            }
        }

        // Get matrix params
        var mpRegex = new RegExp('^' + screenHash + '(' + SCREEN_PARAM_REGEX + ')+');
        var screenHashRaw = hash.match(mpRegex);
        if ( screenHashRaw && screenHashRaw.length > 0 ) {

            var matrixParams = screenHashRaw[0].match(new RegExp(SCREEN_PARAM_REGEX, 'g'));
            var idx;
            for ( i = 0; i < matrixParams.length; i++ ) {
                idx = matrixParams[i].indexOf('=');
                params[ matrixParams[i].substr(1, idx - 1) ] = matrixParams[i].substr(idx + 1);
            }
        }

        return params;
    }

    function _getRawHashRegex (hash) {
        return hash.replace(PATH_PARAM_REGEX, '(?:[^/]+)') + '(?:' + SCREEN_PARAM_REGEX + ')*(?:/?)';
    }

    function _startHashChange(e) {

        // when document.location.href is [http://localhost:8080/#], the document.location.hash is [] (empty string)
        // to avoid the use of empty strings and prevent mistakes, we replace it by #. (# == welcome-screen)
        var currHash = document.location.hash || "#",
            fullHash = currHash,
            hashRegex,
            fullRawHashRegex,
            currNav = _navMap,
            screenFound,
            deep = 0,
            i,
            fullScreenHash = '', // e.g.: #/user/:id/friends
            fullScreenHashRaw = '', // e.g.: #/user/1234/friends;filter=all
            historyNavRaw = [],
            historyNav = [],
            firstNodeToSleep,
            hashRaw,
            screenHash, // e.g.: user/:id
            screenChilds; // used to add the screenHashes of the current deep to search

        // If a screen cannot sleep, finish navigation
        if ( _gotoCancelled ) {
            _gotoCancelled = false;
            iris.notify(iris.AFTER_NAVIGATION);
            return false;
        }

        // Notify that a valid navigation is started
        iris.notify(iris.BEFORE_NAVIGATION);

        while ( currHash ) {

            //
            // Find the screen according to the current level.
            // Sort screenChilds (alphabetically and descending) to get the correct screen in case of contained screens, e.g.
            //
            // screenChilds = ['screen/other', 'screen'] // 'screen/other' contains 'screen' (The array is sorted alphabetically and descending)
            //
            // currHash = 'screen/other'
            //   - search child['screen/other'] in currHash['screen/other'] : screenFound!
            //
            // currHash = 'screen'
            //   - search child['screen/other'] in currHash['screen'] : Not screenFound, screen/other contains screen but is skipped
            //   - search child['screen'] in currHash['screen'] : screenFound!
            screenFound = false;

            screenChilds = [];
            for ( screenHash in currNav ) {
                screenChilds.push(screenHash);
            }
            screenChilds.sort();
            screenChilds.reverse();

            for ( i = 0; i < screenChilds.length; i++ ) {

                screenHash = screenChilds[i];
                hashRegex = _getHashRegex(screenHash);

                if ( hashRegex.test(currHash) ) {
                    screenFound = true;

                    // fullScreenHash will be like #/user/:id/friends
                    // If it's the first screen dont add '/'
                    if ( fullScreenHash ) {
                        fullScreenHash += '/' + screenHash;
                    } else {
                        fullScreenHash = screenHash;
                    }

                    // fullRawHashRegex will match hashes like #/user/1234/friends;filter=all
                    if ( fullRawHashRegex ) {
                        fullRawHashRegex += '/' + _getRawHashRegex(screenHash);
                    } else {
                        fullRawHashRegex = '^' + _getRawHashRegex(screenHash);
                    }

                    fullScreenHashRaw = fullHash.match(fullRawHashRegex)[0].replace(/\/?$/, ''); // remove last '/'
                    break;
                }
            }

            if ( screenFound ) {

                var screenInPrevNav = _prevNav[deep] && _prevNav[deep] === fullScreenHash;

                // Prepare to the next iteration
                historyNav.push(fullScreenHash);
                historyNavRaw.push(fullScreenHashRaw);

                hashRaw = currHash;
                currHash = currHash.replace(hashRegex, '');
                currNav = currNav[screenHash];

                if ( !currHash && _prevNav.length > deep ) {

                    firstNodeToSleep = screenInPrevNav ? deep + 1 : deep;

                    // Can sleep?
                    for ( i = _prevNav.length-1; i >= firstNodeToSleep; i-- ) {
                        if ( _prevNav[i] !== "#" && _screen[_prevNav[i]].canSleep() === false ) {
                            _gotoCancelled = true;
                            document.location.href = _prevNavigationHash;
                            return false;
                        }
                    }

                    // Hide previous screens
                    while ( _prevNav.length > firstNodeToSleep ) {
                        var pathToSleep = _prevNav.pop();
                        _prevNavRaw.pop();

                        if ( pathToSleep !== "#" ) {
                            var screenToSleep = _screen[pathToSleep];
                            screenToSleep._sleep();
                            screenToSleep.hide();
                        }
                    }
                }

                // Wake up the screen at this deep (if not exists, create before)
                var hashNewParams = _prevNavRaw[deep] && _prevNavRaw[deep] !== fullScreenHashRaw;
                var params = _getScreenPathParams(screenHash, hashRaw, hashRegex);
                var screenInstance;

                if ( screenInPrevNav ) {

                    // The screen is in the previous navigation. If the screen receives new parameters, wake up
                    screenInstance = _screen[fullScreenHash];
                    if ( hashNewParams ) {
                        screenInstance.params = params;
                        screenInstance._awake(params);
                    }

                } else {
                    // The screen is not in the previous navigation

                    // Instantiate the screen if it wasn't created previously
                    if ( !_screen.hasOwnProperty(fullScreenHash) ) {

                        if ( !_screenJsUrl.hasOwnProperty(fullScreenHash) ) {
                            throw 'Invalid screenPath = ' + fullScreenHash;
                        }

                        // Instantiate the new screen
                        screenInstance = new Screen(fullScreenHash);
                        screenInstance.params = params;
                        screenInstance.create();
                        _screen[fullScreenHash] = screenInstance;

                    } else {
                        // Get the screen instance
                        screenInstance = _screen[fullScreenHash];
                    }

                    // Wake up
                    screenInstance.show();
                    screenInstance._awake(params);
                }

            } else {
                // Invalid hash, screen not found

                iris.notify(iris.SCREEN_NOT_FOUND, fullHash);
                iris.log("[warning] '" + fullHash + "' must be registered using self.screens()");
                return;
            }

            deep++;
        }

        // Prepare to the next iteration
        _prevNavigationHash = fullHash;
        _prevNav = historyNav;
        _prevNavRaw = historyNavRaw;

        iris.log("Navigation finished");
        iris.notify(iris.AFTER_NAVIGATION);
    }

    function _parseLangTags(p_html) {
        var html = p_html;
        var matches = html.match(/@@[0-9A-Za-z_\.]+@@/g);
        if(matches) {
            var f, F = matches.length;
            for(f = 0; f < F; f++) {
                html = html.replace(matches[f], iris.translate(matches[f].substring(2, matches[f].length - 2)));
            }
        }
        return html;
    }

    //
    // UI
    //

    function _registerTmpl(path, html) {
        _includes[path] = html;
    }

    function _registerUI(ui, path) {
        _setInclude(ui, path, "ui");
    }

    function _jqToHash(p_$obj) {
        var hash = {};
        var attrs = p_$obj.get(0).attributes;
        var label;
        for(var f = 0, F = attrs.length; f < F; f++) {
            label = attrs[f].name;
            if(label.indexOf("data-") === 0) {
                label = label.substr(5);
            }
            hash[label] = attrs[f].value;
        }
        return hash;
    }

    //
    // SCREEN
    //

    function _registerScreen(screen, path) {
        _setInclude(screen, path, "screen");
    }

    function _destroyScreenByPath(p_screenPath) {

        if(_screen.hasOwnProperty(p_screenPath)) {

            if ( p_screenPath === "#" ) {
                throw "Welcome screen cannot be deleted";
            }

            var hash = document.location.hash;

            // if url=http://example.com/#, the document.location.hash="" empty string
            // check if current screen is welcome screen (hash !== "")
            // check if the current hash belongs to the path to delete
            if ( hash !== "#" && hash !== "" && (p_screenPath.indexOf(hash) === 0 || hash.indexOf(p_screenPath) === 0) ) {
                throw "Cannot delete the current screen or its parents";
            }

            _destroyScreen(p_screenPath);

        } else {
            iris.log("Error removing the screen \"" + p_screenPath + "\", path not screenFound.");
        }
    }

    function _destroyScreen (path) {

        var screen = _screen[path];

        // the screen can be register using self.screens() but no instanciated using navigation
        if ( screen !== undefined ) {

            // destroy child screens
            if ( screen.screenChilds !== undefined ) {
                for (var i = 0; i < screen.screenChilds.length; i++ ) {
                    _destroyScreen(screen.screenChilds[i]);
                }
            }

            screen._destroy();
            screen.get().remove();
            delete _jsUrlScreens[_screenJsUrl[path]];
            delete _screen[path];
            delete _screenJsUrl[path];
            delete _screenContainer[path];
        }

    }

    var Component = function(id, $container, fileJs) {
        iris.Settable.call(this);

        this.id = id;
        this.uis = []; // child UIs
        this.uisMap = {}; // UIs sorted by id
        this.el = {}; // Map contains data-id elements

        this.con = $container; // JQ container
        this.fileJs = fileJs; // Path to the script

        this.fileTmpl = null;
        this.template = null;
        this.sleeping = null;

        _includes[fileJs](this);
    };

    iris.inherits(Component, iris.Settable);

    var pComponent = Component.prototype;

    pComponent.APPEND = "append";
    pComponent.REPLACE = "replace";
    pComponent.PREPEND = "prepend";

    pComponent._sleep = function() {
        for(var f = 0, F = this.uis.length; f < F; f++) {
            this.uis[f]._sleep();
        }
        this.sleeping = true;
        this.sleep();
    };

    pComponent._awake = function(p_params) {
        this.sleeping = false;
        this.awake(p_params);
        for(var f = 0, F = this.uis.length; f < F; f++) {
            if (this.uis[f].sleeping !== false) {
                this.uis[f]._awake();
            }
        }
    };

    pComponent._destroy = function() {
        if(!this.sleeping) {
            this._sleep();
        }

        // propage destroys
        for(var f = 0, F = this.uis.length; f < F; f++) {
            this.uis[f]._destroy();
        }

        // remove component events
        for ( var eventName in this.events ) {
            iris.destroyEvents(eventName, this.events[eventName]);
        }
        this.destroy();

        this.uis = null;
        this.events = null;
    };

    pComponent._tmpl = function(p_htmlUrl, p_mode) {

        var f, childrens, tmpl;

        if (this.template !== null) {
            throw "self.tmpl() has already been called in '" + this.fileJs + "'";
        }

        this.fileTmpl = p_htmlUrl;

        tmpl = $( _parseLangTags(_includes[p_htmlUrl]) );

        this.template = tmpl;
        if(tmpl.size() > 1) {
            throw "'" + p_htmlUrl + "' must have only one root node";
        }
        switch(p_mode) {
            case this.APPEND:
                this.con.append(tmpl);
                break;
            case this.REPLACE:
                this.con.replaceWith(tmpl);
                this.con = {selector: this.con.selector};
                break;
            case this.PREPEND:
                this.con.prepend(tmpl);
                break;
            default:
                throw "Unknown template mode '" + p_mode + "'";
        }

        // Process elements with data-* attributes
        this.el = {};
        this.inflateTargets = {};

        // The tmpl root node
        this._data_attrs(tmpl);

        // And all tmpl child nodes
        childrens = tmpl.get(0).getElementsByTagName("*");
        for (f = childrens.length; f--;) {
            this._data_attrs( $(childrens[f]) );
        }
    };

    pComponent._data_attrs = function ($el) {
        var f, key, attr, attrs = $el.get(0).attributes,
            inflate, inflateFormats = {}, inflatesByKeys = {},
            target, targetParams, format, formatParams, formatMatches
            ;

        for (f = attrs.length; f--;) {
            attr = attrs[f];

            if ( attr.name.indexOf("data-") === 0 ) {
                key = attr.name.substr(5);
            } else {
                continue;
            }

            // data-id
            if ( key === "id" ) {
                this.el[ attr.value ] = $el;
                continue;
            }

            // data-*-format
            if ( key.indexOf("-format", key.length - 7) !== -1 ) {
                format = attr.value;
                formatParams = undefined;

                if ( format && FORMAT_REG_EXP.test(format) ) {
                    formatMatches = format.match(FORMAT_REG_EXP);

                    format = formatMatches[1];
                    formatParams = formatMatches[2]; // TODO manage multiple parameter using: formatParams[2].splice(",");
                }
                // inflateFormats key = "jq-xxxx-format" -> "xxxx"
                inflateFormats[ key.substr(3, key.length - 10) ] = { key: format, params: formatParams };
                continue;
            }

            if ( key.indexOf("jq-") === 0 ) {
                key = key.substr(3);
                if ( /^(text|html|val|toggle)$/.test(key) ) {
                    target = key;

                } else if ( /^(prop-|attr-)/.test(key) ) {
                    target = key.substr(0, 4);
                    targetParams = key.substr(5);

                } else {
                    // Other data-* attribute
                    continue;
                }
            }

            if ( !this.inflateTargets.hasOwnProperty(attr.value) ) {
                this.inflateTargets[ attr.value ] = [];
            }

            inflate = { target: target, targetParams: targetParams, el: $el };

            this.inflateTargets[ attr.value ].push( inflate );
            inflatesByKeys[key] = inflate;
        }

        // After of iterate the element data attributes, set the formatting to each target
        for ( key in inflateFormats ) {
            if ( inflatesByKeys.hasOwnProperty(key) ) {
                inflatesByKeys[key].format = inflateFormats[key].key;
                inflatesByKeys[key].formatParams = inflateFormats[key].params;
            }
        }
    };

    pComponent.inflate = function(data) {

        var dataKey, f, F, targets, inflate, format, unformattedValue, value;

        for ( dataKey in this.inflateTargets ) {
            unformattedValue = iris.val(data, dataKey);

            if ( unformattedValue !== undefined ) {

                targets = this.inflateTargets[dataKey];

                for ( f = 0, F = targets.length; f < F; f++ ) {
                    inflate = targets[f];

                    switch ( inflate.format ) {
                        case "date":
                            value = iris.date(unformattedValue, inflate.formatParams);
                            break;
                        case "currency":
                            value = iris.currency(unformattedValue);
                            break;
                        case "number":
                            value = iris.number(unformattedValue);
                            break;
                        default:
                            value = unformattedValue;
                    }

                    switch ( inflate.target ) {
                        case "text":
                            inflate.el.text(value);
                            break;
                        case "html":
                            inflate.el.html(value);
                            break;
                        case "val":
                            inflate.el.val(value);
                            break;
                        case "toggle":
                            inflate.el.toggle(value);
                            break;
                        case "prop":
                            inflate.el.prop(inflate.targetParams, value);
                            break;
                        case "attr":
                            inflate.el.attr(inflate.targetParams, value);
                    }
                }
            }
        }
    };

    // Check if the template is set (https://github.com/intelygenz/iris/issues/19)
    pComponent._checkTmpl = function() {
        if(this.template === null) {
            throw "Set a template using self.tmpl() in '" + this.fileJs + "'";
        }
    };

    pComponent.show = function() {
        this._checkTmpl();
        this.template.show();
    };

    pComponent.hide = function() {
        this._checkTmpl();
        this.template.hide();
    };

    pComponent.get = function(p_id) {
        this._checkTmpl();

        if(p_id) {

            if(!this.el.hasOwnProperty(p_id)) {
                var id = "[data-id=" + p_id + "]",
                filter = this.template.filter(id),
                $element = null;

                if(filter.length > 0) {
                    $element = filter;
                } else {
                    var find = this.template.find(id);
                    if(find.size() > 0) {
                        $element = find;
                    }
                }

                if($element === null) {
                    throw "[data-id=" + p_id + "] not screenFound in '" + this.fileTmpl + "' used by '" + this.fileJs + "'";
                } else if($element.size() > 1) {
                    throw "[data-id=" + p_id + "] must be unique in '" + this.fileTmpl + "' used by '" + this.fileJs + "'";
                }

                this.el[p_id] = $element;
            }

            return this.el[p_id];
        }

        return this.template;
    };

    pComponent._ui = function(p_id, p_jsUrl, p_uiSettings, p_templateMode) {
        if ( p_jsUrl === undefined ) {
            // Get UI

            var ui = this.uisMap[p_id];
            if ( ui === undefined ) {
                ui = [];
            }
            return ui;

        } else {
            // Create UI
            return this._createUi(p_id, p_jsUrl, p_uiSettings, p_templateMode);
        }
    };

    pComponent._createUi = function(p_id, p_jsUrl, p_uiSettings, p_templateMode) {
        var $container = this.get(p_id);

        if($container !== undefined && $container.size() === 1) {
            var uiInstance = new UI($container, $container.data("id"), p_jsUrl, p_uiSettings, p_templateMode, this);
            if (uiInstance._tmplMode === undefined || uiInstance._tmplMode === uiInstance.REPLACE) {
                this.el[p_id] = undefined;
            }
            this.uis.push(uiInstance);

            // Add uiInstance to the UIs map
            if ( uiInstance._tmplMode === uiInstance.REPLACE ) {
                this.uisMap[p_id] = uiInstance;
            } else {
                if ( !this.uisMap.hasOwnProperty(p_id) ) {
                    this.uisMap[p_id] = [];
                }
                this.uisMap[p_id].push(uiInstance);
            }

            return uiInstance;
        } else {
            throw "The container does not exist or has been replaced.";
        }
    };

    pComponent.destroyUI = function(p_ui) {
        if ( p_ui === undefined ) {
            // Self destroy
            this.parentUI.destroyUI(this);
        } else {
            var idx;

            // Remove p_ui from the UIs array
            idx = $.inArray(p_ui, this.uis);
            if ( idx !== -1 ) {
                this.uis.splice(idx, 1);
            }

            // Remove p_ui from the UIs map
            if ( p_ui._tmplMode === p_ui.REPLACE ) {
                this.uisMap[p_ui.id] = null;
                delete this.uisMap[p_ui.id];
            } else {
                var uis = this.uisMap[p_ui.id];

                idx = $.inArray(p_ui, uis);
                if ( idx !== -1 ) {
                    uis.splice(idx, 1);
                }
            }

            // Destroy p_ui
            p_ui._destroy();
            p_ui.get().remove();
        }
    };

    pComponent.destroyUIs = function(id) {
        var uis = this.uisMap[id];
        if ( $.isArray(uis) ) {
            var f, F;
            for ( f=uis.length-1; f >= 0; f-- ) {
                this.destroyUI(uis[f]);
            }

        } else if ( uis && uis._tmplMode === this.REPLACE ) {
            // uis is a single UI
            this.destroyUI(uis);
        }
    };

    pComponent.container = function() {
        return this.con;
    };

    //
    // To override functions
    //
    pComponent.create = function() {};

    pComponent.awake = function() {};

    pComponent.sleep = function() {};

    pComponent.destroy = function() {};

    //
    // UI
    //
    var UI = function($container, id, fileJs, settings, tmplMode, parentUI) {
        Component.call(this, id, $container, fileJs);

        var jqToHash = _jqToHash($container);

        this.parentUI = parentUI;
        this._tmplMode = tmplMode || "replace";

        $.extend(this.cfg, jqToHash, settings || {});

        this.create();
        this._awake();
    };

    iris.inherits(UI, Component);

    var pUI = UI.prototype;
    pUI.tmplMode = function(p_mode) {
        this._tmplMode = p_mode;
    };

    pUI.tmpl = function(p_htmlUrl) {
        this._tmpl(p_htmlUrl, this._tmplMode);
    };

    pUI.ui = function(p_id, p_jsUrl, p_uiSettings, p_templateMode) {
        return this._ui(p_id, p_jsUrl, p_uiSettings, p_templateMode);
    };

    //
    // SCREEN
    //
    var Screen = function(path) {
        Component.call(this, path, _screenContainer[path], _screenJsUrl[path]);

        this.params = {};
        this.screenConId = null;
        this.navMap = null;
        this.hash = null;
    };

    iris.inherits(Screen, Component);

    var pScreen = Screen.prototype;
    pScreen.param = function(p_key) {
        return this.params[p_key];
    };

    pScreen.ui = function(p_id, p_jsUrl, p_uiSettings, p_templateMode) {
        if ( p_id === this.screenConId ) {
            throw "'" + p_id + "' has already been registered as a screen container";
        }

        return this._ui(p_id, p_jsUrl, p_uiSettings, p_templateMode);
    };

    pScreen.tmpl = function(p_htmlUrl) {
        this._tmpl(p_htmlUrl, this.APPEND);
    };

    pScreen.screens = function(p_containerId, p_screens) {

        this.screenConId = p_containerId;

        if (this.hasOwnProperty("screenChilds")) {
            throw "Multiple calls to self.screens() are not allowed: " + this.id;

        } else if (this.template === null){
            throw "self.tmpl() must be called before self.screens(): " + this.id;

        } else {
            var $cont = this.get(p_containerId);
            this.screenChilds = [];

            // TODO use screenMetadata isntead of _screenParentNavMap, _screenHashFragment
            this.navMap =  ( this.id === '#' ) ? _navMap['#'] : _screenParentNavMap[this.id][_screenHashFragment[this.id]];

            for ( var i=0; i < p_screens.length; i++ ) {

                var screen = p_screens[i];
                var hashUrl = screen[0];
                if ( hashUrl.indexOf("#") !== -1 ) {
                    throw "[" + hashUrl + "] cannot contain #";
                }
                hashUrl = this.id + "/" + hashUrl;

                var js = screen[1];
                if ( _jsUrlScreens.hasOwnProperty(js) ) {
                    throw "js-URL repeated '" + js + "': " + this.id;
                }

                if ( _screenContainer.hasOwnProperty(hashUrl) ) {
                    throw "hash-URL repeated  '" + hashUrl + "' in " + this.fileJs;
                }

                iris.log("Register screen hash[" + hashUrl + "] js[" + js + "]");

                _screenJsUrl[hashUrl] = js;
                _screenContainer[hashUrl] = $cont;
                _jsUrlScreens[js] = true;

                _screenParentNavMap[hashUrl] = this.navMap;
                _screenHashFragment[hashUrl] = screen[0];

                this.screenChilds[i] = hashUrl;

                this.navMap[screen[0]] = {};
            }
        }
    };

    // To override
    pScreen.canSleep = function() {
        return true;
    };

    function _registerRes (resourceOrPath, path) {

        if ( typeof resourceOrPath === "string" ) {
            // resourceOrPath == path
            if ( !_includes.hasOwnProperty(resourceOrPath) ) {
                throw "add service[" + resourceOrPath + "] to iris.path";
            }
            return _includes[resourceOrPath];

        } else {
            // resourceOrPath == resource
            var serv = new iris.Resource();
            serv.cfg = {};
            serv.settings({ type: "json", path: "" });
            resourceOrPath(serv);

            _setInclude(serv, path, "resource");
        }

    }

    iris.screen = _registerScreen;
    iris.destroyScreen = _destroyScreenByPath;
    iris.welcome = _welcome;
    iris.navigate = _goto;
    iris.ui = _registerUI;
    iris.tmpl = _registerTmpl;
    iris.resource = _registerRes;
    iris.include = _load;

    //
    // Classes
    //
    iris.Component = Component;
    iris.UI = UI;
    iris.Screen = Screen;

    _init();

})(jQuery);

(function() {

    var Resource = function() {};

    Resource.prototype = new iris.Settable();

    Resource.prototype.ajax = function(p_method, p_path, p_params, f_success, f_error) {

        return iris.ajax({
            "url": this.setting("path") + p_path,
            "type": p_method,
            "data": p_params,
            "cache": false,
            "dataType": this.setting("type"),
            "async": true,
            "success": f_success,
            "error": function (p_request, p_textStatus, p_errorThrown) {

                iris.notify(iris.RESOURCE_ERROR, {request: p_request, status: p_textStatus, error: p_errorThrown});

                if ( f_error !== undefined ) {
                    f_error( p_request, p_textStatus, p_errorThrown );
                }
            }
        });
    };

    Resource.prototype.get = function(p_path, f_success, f_error) {
        return this.ajax("GET", p_path, null, f_success, f_error);
    };

    Resource.prototype.del = function(p_path, f_success, f_error) {
        return this.ajax("DELETE", p_path, null, f_success, f_error);
    };

    Resource.prototype.put = function(p_path, p_params, f_success, f_error) {
        return this.ajax("PUT", p_path, p_params, f_success, f_error);
    };

    Resource.prototype.post = function(p_path, p_params, f_success, f_error) {
        return this.ajax("POST", p_path, p_params, f_success, f_error);
    };

    iris.Resource = Resource;

})();


text:
import _plotly_utils.basevalidators

class ProjectValidator(_plotly_utils.basevalidators.CompoundValidator):
    def __init__(
        self, plotly_name="project", parent_name="surface.contours.z", **kwargs
    ):
        super(ProjectValidator, self).__init__(
            plotly_name=plotly_name,
            parent_name=parent_name,
            data_class_str=kwargs.pop("data_class_str", "Project"),
            data_docs=kwargs.pop(
                "data_docs",
                """
            x
                Determines whether or not these contour lines
                are projected on the x plane. If `highlight` is
                set to True (the default), the projected lines
                are shown on hover. If `show` is set to True,
                the projected lines are shown in permanence.
            y
                Determines whether or not these contour lines
                are projected on the y plane. If `highlight` is
                set to True (the default), the projected lines
                are shown on hover. If `show` is set to True,
                the projected lines are shown in permanence.
            z
                Determines whether or not these contour lines
                are projected on the z plane. If `highlight` is
                set to True (the default), the projected lines
                are shown on hover. If `show` is set to True,
                the projected lines are shown in permanence.
""",
            ),
            **kwargs,
        )


text:
package org.gradle.test;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class ATest {

  @Test
  public void itWorks() {
    assertTrue(true);
  }
}


text:
import hashlib
import time
import zlib

try:
    import ujson as json
except ImportError:
    import json

from aredis.utils import b
from aredis.exceptions import (SerializeError,
                               CompressError)

class IdentityGenerator:
    """
    Generator of identity for unique key,
    you may overwrite it to meet your customize requirements.
    """

    TEMPLATE = '{app}:{key}:{content}'

    def __init__(self, app, encoding='utf-8'):
        self.app = app
        self.encoding = encoding

    def _trans_type(self, content):
        if isinstance(content, str):
            content = content.encode(self.encoding)
        elif isinstance(content, int):
            content = b(str(content))
        elif isinstance(content, float):
            content = b(repr(content))
        return content

    def generate(self, key, content):
        content = self._trans_type(content)
        md5 = hashlib.md5()
        md5.update(content)
        hash = md5.hexdigest()
        identity = self.TEMPLATE.format(app=self.app, key=key, content=hash)
        return identity

class Compressor:
    """
    Uses zlib to compress and decompress Redis cache. You may implement your
    own Compressor implementing `compress` and `decompress` methods
    """

    min_length = 15
    preset = 6

    def __init__(self, encoding='utf-8'):
        self.encoding = encoding

    def _trans_type(self, content):
        if isinstance(content, str):
            content = content.encode(self.encoding)
        elif isinstance(content, int):
            content = b(str(content))
        elif isinstance(content, float):
            content = b(repr(content))
        if not isinstance(content, bytes):
            raise TypeError('Wrong data type({}) to compress'.format(type(content)))
        return content

    def compress(self, content):
        content = self._trans_type(content)
        if len(content) > self.min_length:
            try:
                return zlib.compress(content, self.preset)
            except zlib.error as exc:
                raise CompressError('Content can not be compressed.')
        return content

    def decompress(self, content):
        content = self._trans_type(content)
        try:
            return zlib.decompress(content)
        except zlib.error as exc:
            raise CompressError('Content can not be decompressed.')

class Serializer:
    """
    Uses json to serialize and deserialize cache to str. You may implement
    your own Serializer implemting `serialize` and `deserialize` methods.
    """

    def __init__(self, encoding='utf-8'):
        self.encoding = encoding

    def _trans_type(self, content):
        if isinstance(content, bytes):
            content = content.decode(self.encoding)
        if not isinstance(content, str):
            raise TypeError('Wrong data type({}) to compress'.format(type(content)))
        return content

    def serialize(self, content):
        try:
            return json.dumps(content)
        except Exception as exc:
            raise SerializeError('Content can not be serialized.')

    def deserialize(self, content):
        content = self._trans_type(content)
        try:
            return json.loads(content)
        except Exception as exc:
            raise SerializeError('Content can not be deserialized.')

class BasicCache:
    """Basic cache class, should not be used explicitly"""

    def __init__(self, client, app='', identity_generator_class=IdentityGenerator,
                 compressor_class=Compressor, serializer_class=Serializer,
                 encoding='utf-8'):
        self.client = client
        self.identity_generator = self.compressor = self.serializer = None
        # set identity generator, compressor and serializer to None if not needed
        if identity_generator_class:
            self.identity_generator = identity_generator_class(app, encoding)
        if compressor_class:
            self.compressor = compressor_class(encoding)
        if serializer_class:
            self.serializer = serializer_class(encoding)

    def __repr__(self):
        return "{}<{}>".format(type(self).__name__, repr(self.client))

    def _gen_identity(self, key, param=None):
        """generate identity according to key and param given"""
        if self.identity_generator and param is not None:
            if self.serializer:
                param = self.serializer.serialize(param)
            if self.compressor:
                param = self.compressor.compress(param)
            identity = self.identity_generator.generate(key, param)
        else:
            identity = key
        return identity

    def _pack(self, content):
        """Packs the content using serializer and compressor"""
        if self.serializer:
            content = self.serializer.serialize(content)
        if self.compressor:
            content = self.compressor.compress(content)
        return content

    def _unpack(self, content):
        """Unpacks cache using serializer and compressor"""
        if self.compressor:
            try:
                content = self.compressor.decompress(content)
            except CompressError:
                pass
        if self.serializer:
            content = self.serializer.deserialize(content)
        return content

    async def delete(self, key, param=None):
        """
        Deletes cache corresponding to identity
        generated from key and param
        """
        identity = self._gen_identity(key, param)
        return await self.client.delete(identity)

    async def delete_pattern(self, pattern, count=None):
        """
        Deletes cache according to pattern in redis,
        delete `count` keys each time
        """
        cursor = '0'
        count_deleted = 0
        while cursor != 0:
            cursor, identities = await self.client.scan(
                cursor=cursor, match=pattern, count=count
            )
            count_deleted += await self.client.delete(*identities)
        return count_deleted

    async def exist(self, key, param=None):
        """Checks if specific identity exists"""
        identity = self._gen_identity(key, param)
        return await self.client.exists(identity)

    async def ttl(self, key, param=None):
        """Gets time to live of a specific identity"""
        identity = self._gen_identity(key, param)
        return await self.client.ttl(identity)

class Cache(BasicCache):
    """Provides basic caching"""

    async def get(self, key, param=None):
        identity = self._gen_identity(key, param)
        res = await self.client.get(identity)
        if res:
            res = self._unpack(res)
        return res

    async def set(self, key, value, param=None, expire_time=None):
        identity = self._gen_identity(key, param)
        value = self._pack(value)
        return await self.client.set(identity, value, ex=expire_time)

    async def set_many(self, data, param=None, expire_time=None):
        async with await self.client.pipeline() as pipeline:
            for key, value in data.items():
                identity = self._gen_identity(key, param)
                value = self._pack(value)
                await pipeline.set(identity, value, expire_time)
            return await pipeline.execute()

class HerdCache(BasicCache):
    """
    Cache that handles thundering herd problem
    (https://en.wikipedia.org/wiki/Thundering_herd_problem)
    by cacheing expiration time in set instead of directly using expire
    operation of redis.
    This kind of cache is suitable for low consistency scene where update
    operations are expensive.
    """

    def __init__(self, client, app='', identity_generator_class=IdentityGenerator,
                 compressor_class=Compressor, serializer_class=Serializer,
                 default_herd_timeout=1, extend_herd_timeout=1, encoding='utf-8'):
        self.default_herd_timeout = default_herd_timeout
        self.extend_herd_timeout = extend_herd_timeout
        super(HerdCache, self).__init__(client, app, identity_generator_class,
                                        compressor_class, serializer_class,
                                        encoding)

    async def set(self, key, value, param=None, expire_time=None, herd_timeout=None):
        """
        Uses key and param to generate identity and pack the content,
        expire the key within real_timeout if expire_time is given.
        real_timeout is equal to the sum of expire_time and herd_time.
        The content is cached with expire_time.
        """
        identity = self._gen_identity(key, param)
        expected_expired_ts = int(time.time())
        if expire_time:
            expected_expired_ts += expire_time
        expected_expired_ts += herd_timeout or self.default_herd_timeout
        value = self._pack([value, expected_expired_ts])
        return await self.client.set(identity, value, ex=expire_time)

    async def set_many(self, data, param=None, expire_time=None, herd_timeout=None):
        async with await self.client.pipeline() as pipeline:
            for key, value in data.items():
                identity = self._gen_identity(key, param)
                expected_expired_ts = int(time.time())
                if expire_time:
                    expected_expired_ts += expire_time
                expected_expired_ts += herd_timeout or self.default_herd_timeout
                value = self._pack([value, expected_expired_ts])
                await pipeline.set(identity, value, ex=expire_time)
            return await pipeline.execute()

    async def get(self, key, param=None, extend_herd_timeout=None):
        """
        Uses key or identity generated from key and param to get cached
        content and expiratiom time.
        Uses time.now() to check expiration. If not expired, returns unpacked
        content. Otherwise returns None and sets cache with extended timeout
        """
        identity = self._gen_identity(key, param)
        res = await self.client.get(identity)
        if res:
            res, timeout = self._unpack(res)
            now = int(time.time())
            if timeout <= now:
                extend_timeout = extend_herd_timeout or self.extend_herd_timeout
                expected_expired_ts = now + extend_timeout
                value = self._pack([res, expected_expired_ts])
                await self.client.set(identity, value, extend_timeout)
                return None
        return res


text:
function eph = get_ephemeris(probe, start_datenum, end_datenum)
% eph = get_ephemeris(probe, start_datenum, end_datenum)
%
% Get THEMIS ephemeris data for a given probe in a given time range
%
% INPUTS
% probe: one of 'A', 'B', 'C', 'D' or 'E'
%
% OUTPUTS
% eph: struct with the following fields:
%   epoch (Nx1, UTC)
%   xyz_sm  (Nx3, dipole solar magnetic, earth radii)
%   lat     (Nx1, dipole, degrees)
%   MLT     (Nx1, dipole, hours)
%   L       (Nx1, dipole, earth radii)

% By Daniel Golden (dgolden1 at stanford dot edu) March 2011
% $Id$

%% Setup
eph_dir = fullfile(scottdataroot, 'spacecraft', 'themis', 'ephemeris');

if ~ischar(probe) || ~any(strcmpi({'A', 'B', 'C', 'D', 'E'}, probe))
  error('Probe should be one of ''A'', ''B'', ''C'', ''D'' or ''E''');
end

if ~exist('start_datenum', 'var') || isempty(start_datenum)
  start_datenum = 0;
end
if ~exist('end_datenum', 'var') || isempty(end_datenum)
  end_datenum = Inf;
end

%% Get ephemeris
filename = sprintf('th%s_ephemeris.mat', lower(probe));
eph_raw = load(fullfile(eph_dir, filename));

%% Parse out time range
idx = eph_raw.epoch >= start_datenum & eph_raw.epoch < end_datenum;
for field = fieldnames(eph_raw).'
  eph.(field{1}) = eph_raw.(field{1})(idx, :);
end

%% Tack on latitude, MLT and L
[eph.lat, eph.MLT, eph.L] = xyz_to_lat_mlt_L(eph.xyz_sm);


text:
<?php

namespace NTLAB\JS;

use NTLAB\JS\Util\Asset;

class Backend implements BackendInterface
{
    /**
     * {@inheritDoc}
     * @see \NTLAB\JS\BackendInterface::getConfig()
     */
    public function getConfig($name, $default = null)
    {
        return $default;
    }

    /**
     * {@inheritDoc}
     * @see \NTLAB\JS\BackendInterface::trans()
     */
    public function trans($text, $vars = [], $domain = null)
    {
        return $text;
    }

    /**
     * {@inheritDoc}
     * @see \NTLAB\JS\BackendInterface::url()
     */
    public function url($url, $options = [])
    {
        return $url;
    }

    /**
     * {@inheritDoc}
     * @see \NTLAB\JS\BackendInterface::asset()
     */
    public function asset($asset, $type = self::ASSET_JS)
    {
        return $asset;
    }

    /**
     * {@inheritDoc}
     * @see \NTLAB\JS\BackendInterface::addAsset()
     */
    public function addAsset($asset, $type = self::ASSET_JS, $priority = self::ASSET_PRIORITY_DEFAULT, $attributes = null)
    {
    }

    /**
     * {@inheritDoc}
     * @see \NTLAB\JS\BackendInterface::removeAsset()
     */
    public function removeAsset($asset, $type = self::ASSET_JS)
    {
    }

    /**
     * {@inheritDoc}
     * @see \NTLAB\JS\BackendInterface::getAssetDir()
     */
    public function getAssetDir($repo)
    {
    }

    /**
     * {@inheritDoc}
     * @see \NTLAB\JS\BackendInterface::generateAsset()
     */
    public function generateAsset(Asset $asset, $name, $type = self::ASSET_JS)
    {
    }

    /**
     * {@inheritDoc}
     * @see \NTLAB\JS\BackendInterface::tag()
     */
    public function tag($name, $options = [])
    {
    }

    /**
     * {@inheritDoc}
     * @see \NTLAB\JS\BackendInterface::ctag()
     */
    public function ctag($name, $content, $options = [])
    {
    }
}


text:
        Currency Symbol

            <button class="btn btn-default text-left dropdown-toggle"
                    data-toggle="dropdown" dropdown-toggle aria-expanded="true">
                    {{SettingsHome.data.settings.currency.name||SettingsHome.currency[0].name}}

            </button  >

                        {{currency.name}}


text:
Peachpie is continuously tested on build servers. Before any contribution it is recommended to run tests locally in order to avoid unnecessary pull requests.

### Prerequisites

1. successfully compiled solution `./Peachpie.sln`
2. local installation of latest `php` which is used by tests

### Running tests on shell

Test projects are maintained in `./src/tests` project directory. Each of the subdirectories contains a test project.

Navigate to `./src/tests/ ... ` individually and run following sequence of commands

1. `dotnet restore`
2. `dotnet test`

Example:

```
D:\Projects\peachpie\src\Tests\Peachpie.DiagnosticTests>dotnet restore
  Restoring packages ...

D:\Projects\peachpie\src\Tests\Peachpie.DiagnosticTests>dotnet test
Build started, please wait...
Build completed.

Test run for D:\Projects\peachpie\src\Tests\Peachpie.DiagnosticTests\bin\Debug\netcoreapp1.0\Peachpie.DiagnosticTests.dll(.NETCoreApp,Version=v1.0)
Microsoft (R) Test Execution Command Line Tool Version 15.0.0.0
Copyright (c) Microsoft Corporation.  All rights reserved.

Starting test execution, please wait...
[xUnit.net 00:00:01.3152602]   Discovering: Peachpie.DiagnosticTests
[xUnit.net 00:00:01.5641356]   Discovered:  Peachpie.DiagnosticTests
[xUnit.net 00:00:01.6565120]   Starting:    Peachpie.DiagnosticTests
[xUnit.net 00:00:03.7684150]   Finished:    Peachpie.DiagnosticTests

Total tests: 9. Passed: 9. Failed: 0. Skipped: 0.
Test Run Successful.
Test execution time: 4,6788 Seconds
```

### Running tests in Visual Studio

After opening `./Peachpie.sln`, the test projects are placed within `Tests` solution folders. Build contained projects and use `Test Explorer` to run and debug test cases.

## Configuration

### PEACHPIE_TEST_PHP

Environment variable `PEACHPIE_TEST_PHP` controls whether *ScriptTests* will compare the results of test cases with actual `php`.

Setting the variable to `0` will disable the feature.

```
SET PEACHPIE_TEST_PHP=0
```


text:
<?php

namespace Oro\Component\Action\Action;

use Doctrine\Common\Persistence\ManagerRegistry;
use Doctrine\Common\Util\ClassUtils;
use Doctrine\ORM\EntityManager;
use Oro\Component\Action\Exception\NotManageableEntityException;
use Oro\Component\ConfigExpression\ContextAccessor;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

/**
 * Creates a managed entity clone
 */
class CloneEntity extends CloneObject
{
    const OPTION_KEY_FLUSH = 'flush';

    /** @var ManagerRegistry */
    protected $registry;

    /** @var TranslatorInterface */
    protected $translator;

    /** @var FlashBagInterface */
    protected $flashBag;

    /** @var LoggerInterface */
    protected $logger;

    /**
     * @param ContextAccessor $contextAccessor
     * @param ManagerRegistry $registry
     * @param TranslatorInterface $translator
     * @param FlashBagInterface $flashBag
     * @param LoggerInterface $logger
     */
    public function __construct(
        ContextAccessor $contextAccessor,
        ManagerRegistry $registry,
        TranslatorInterface $translator,
        FlashBagInterface $flashBag = null,
        LoggerInterface $logger = null
    ) {
        parent::__construct($contextAccessor);

        $this->registry   = $registry;
        $this->translator = $translator;
        $this->flashBag   = $flashBag;
        $this->logger     = $logger != null ? $logger : new NullLogger();
    }

    /** {@inheritdoc} */
    protected function cloneObject($context)
    {
        $target = $this->contextAccessor->getValue($context, $this->options[self::OPTION_KEY_TARGET]);
        /** @var EntityManager $entityManager */
        $entityClassName = ClassUtils::getClass($target);
        $entityManager = $this->getEntityManager($entityClassName);
        $entity = parent::cloneObject($context);

        // avoid duplicate ids
        $classMeta = $entityManager->getClassMetadata($entityClassName);
        $targetId = $classMeta->getIdentifierValues($target);
        $entityId = $classMeta->getIdentifierValues($entity);

        if ($targetId == $entityId) {
            $classMeta->setIdentifierValues($entity, array_fill_keys(array_keys($entityId), null));
        }

        $saved = false;
        try {
            // save
            $entityManager->persist($entity);

            if ($this->doFlush()) {
                $entityManager->flush($entity);
            }
            $saved = true;
        } catch (\Exception $e) {
            $saved = false;
            if ($this->flashBag) {
                $this->flashBag->add('error', $this->translator->trans('oro.action.clone.error'));
            }

            $this->logger->error($e->getMessage());
        }

        if ($saved && $this->flashBag) {
            $this->flashBag->add('success', $this->translator->trans('oro.action.clone.success'));
        }

        return $entity;
    }

    /**
     * @param string $entityClassName
     * @return EntityManager
     * @throws NotManageableEntityException
     */
    protected function getEntityManager($entityClassName)
    {
        /** @var EntityManager $entityManager */
        $entityManager = $this->registry->getManagerForClass($entityClassName);
        if (!$entityManager) {
            throw new NotManageableEntityException($entityClassName);
        }

        return $entityManager;
    }

    /**
     * Whether perform flush immediately after entity creation or later
     *
     * @return bool
     */
    protected function doFlush()
    {
        return $this->getOption($this->options, self::OPTION_KEY_FLUSH, true);
    }
}


text:
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using Markdig.Extensions.Tables;
using Markdig.Syntax;
using osu.Framework.Allocation;
using osu.Framework.Graphics.Shapes;
using osuTK.Graphics;

namespace osu.Framework.Graphics.Containers.Markdown
{
    /// <summary>
    /// Visualises a cell of a <see cref="MarkdownTable"/>.
    /// </summary>
    /// <code>
    /// |  cell 1   |  cell 2   |
    /// </code>
    public class MarkdownTableCell : CompositeDrawable, IMarkdownTextFlowComponent
    {
        public float ContentWidth => textFlow.TotalTextWidth;
        public float ContentHeight => textFlow.DrawHeight;

        private MarkdownTextFlowContainer textFlow;

        private readonly TableCell cell;
        private readonly TableColumnDefinition definition;

        [Resolved]
        private IMarkdownTextFlowComponent parentFlowComponent { get; set; }

        public MarkdownTableCell(TableCell cell, TableColumnDefinition definition)
        {
            this.cell = cell;
            this.definition = definition;

            RelativeSizeAxes = Axes.Both;

            BorderThickness = 1.8f;
            BorderColour = Color4.White;
            Masking = true;
        }

        [BackgroundDependencyLoader]
        private void load()
        {
            InternalChildren = new Drawable[]
            {
                new Box
                {
                    RelativeSizeAxes = Axes.Both,
                    Alpha = 0,
                    AlwaysPresent = true
                },
                textFlow = CreateTextFlow()
            };

            textFlow.Anchor = Anchor.CentreLeft;
            textFlow.Origin = Anchor.CentreLeft;

            if (cell.LastChild is ParagraphBlock paragraphBlock)
                textFlow.AddInlineText(paragraphBlock.Inline);

            switch (definition.Alignment)
            {
                case TableColumnAlign.Center:
                    textFlow.TextAnchor = Anchor.Centre;
                    break;

                case TableColumnAlign.Right:
                    textFlow.TextAnchor = Anchor.CentreRight;
                    break;

                default:
                    textFlow.TextAnchor = Anchor.CentreLeft;
                    break;
            }
        }

        public virtual MarkdownTextFlowContainer CreateTextFlow()
        {
            var flow = parentFlowComponent.CreateTextFlow();
            flow.Padding = new MarginPadding(10);
            return flow;
        }
    }
}


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

namespace WorkWhit3DPoint
{
    public static class PathStorage
    {
        private static string filePath = "Points3D.txt";

        public static void Save(Path path)
        {
            using(StreamWriter writer = new StreamWriter(filePath))
            {
                foreach (var point3D in path.Points3D)
                {
                    writer.WriteLine("{0} {1} {2}", point3D.X, point3D.Y, point3D.Z);
                }
            }
        }

        public static Path Load()
        {
            List<Point3D> points3D = new List<Point3D>();

            using (StreamReader reader = new StreamReader(filePath))
            {
                while (!reader.EndOfStream)
                {
                    string[] coordinates = reader.ReadLine().Split(' ');

                    int x = int.Parse(coordinates[0]);
                    int y = int.Parse(coordinates[1]);
                    int z = int.Parse(coordinates[2]);

                    points3D.Add(new Point3D(x, y, z));
                }
            }

            return new Path() { Points3D = points3D };
        }
    }
}


text:
class ManageIQ::Providers::Google::NetworkManager::RefreshWorker::Runner < ManageIQ::Providers::BaseManager::RefreshWorker::Runner
end


text:
using System.Runtime.CompilerServices;

[assembly: InternalsVisibleTo("Nerdle.AutoConfig.Tests.Unit")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]


text:
require 'rails_helper'

describe ApiV1::Dashboard::PipelineGroupRepresenter do
  include PipelineModelMother

  it 'renders pipeline dashboard  with hal representation' do
    pipeline_group = PipelineGroupModel.new('MyPipelines')
    pipeline_model = pipeline_model('pipeline-name', 'pipeline-label')
    pipeline_group.add(pipeline_model)
    presenter   = ApiV1::Dashboard::PipelineGroupRepresenter.new(pipeline_group)
    actual_json = presenter.to_hash(url_builder: UrlBuilder.new)
    expect(actual_json).to have_links(:self, :doc)
    expect(actual_json).to have_link(:self).with_url('http://test.host/api/config/pipeline_groups')
    expect(actual_json).to have_link(:doc).with_url(com.thoughtworks.go.CurrentGoCDVersion.apiDocsUrl '#pipeline-groups')
    actual_json.delete(:_links)
    expect(actual_json.delete(:_embedded)[:pipelines]).to eq([expected_embedded_pipeline(pipeline_model)])
    expect(actual_json).to eq({name: 'MyPipelines'})
  end

  private

  def expected_embedded_pipeline(pipeline_model)
    ApiV1::Dashboard::PipelineRepresenter.new(pipeline_model).to_hash(url_builder: UrlBuilder.new)
  end

end