text:
//=============================================================================================================

//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "sourcespacetreeitem.h"
#include "../common/metatreeitem.h"
#include "../../3dhelpers/renderable3Dentity.h"
#include "../../materials/pervertexphongalphamaterial.h"

#include <fs/label.h>
#include <fs/surface.h>

#include <mne/mne_hemisphere.h>

//*************************************************************************************************************
//=============================================================================================================
// Qt INCLUDES
//=============================================================================================================

#include <QList>
#include <QVariant>
#include <QStringList>
#include <QColor>
#include <QStandardItem>
#include <QStandardItemModel>
#include <QMatrix4x4>

#include <Qt3DExtras/QSphereMesh>
#include <Qt3DExtras/QPhongMaterial>
#include <Qt3DCore/QTransform>
#include <QUrl>

//*************************************************************************************************************
//=============================================================================================================
// Eigen INCLUDES
//=============================================================================================================

#include <Eigen/Core>

//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace Eigen;
using namespace MNELIB;
using namespace DISP3DLIB;

//*************************************************************************************************************
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================

SourceSpaceTreeItem::SourceSpaceTreeItem(int iType, const QString& text)
: AbstractTreeItem(iType, text)
, m_pRenderable3DEntity(new Renderable3DEntity())
{
    this->setEditable(false);
    this->setCheckable(true);
    this->setCheckState(Qt::Checked);
    this->setToolTip("Source space item");
}

//*************************************************************************************************************

SourceSpaceTreeItem::~SourceSpaceTreeItem()
{
    //Schedule deletion/Decouple of all entities so that the SceneGraph is NOT plotting them anymore.
    if(m_pRenderable3DEntity) {
        m_pRenderable3DEntity->deleteLater();
    }
}

//*************************************************************************************************************

QVariant SourceSpaceTreeItem::data(int role) const
{
    return AbstractTreeItem::data(role);
}

//*************************************************************************************************************

void  SourceSpaceTreeItem::setData(const QVariant& value, int role)
{
    AbstractTreeItem::setData(value, role);

    switch(role) {
    case Data3DTreeModelItemRoles::SurfaceCurrentColorVert:
        m_pRenderable3DEntity->getCustomMesh()->setColor(value.value<MatrixX3f>());
        break;
    }
}

//*************************************************************************************************************

void SourceSpaceTreeItem::addData(const MNEHemisphere& tHemisphere, Qt3DCore::QEntity* parent)
{
    //Create renderable 3D entity
    m_pRenderable3DEntity->setParent(parent);

    //Create sources as small 3D spheres
    RowVector3f sourcePos;
    QVector3D pos;

    if(tHemisphere.isClustered()) {
        for(int i = 0; i < tHemisphere.cluster_info.centroidVertno.size(); i++) {
            Renderable3DEntity* pSourceSphereEntity = new Renderable3DEntity(m_pRenderable3DEntity);

            sourcePos = tHemisphere.rr.row(tHemisphere.cluster_info.centroidVertno.at(i));
            pos.setX(sourcePos(0));
            pos.setY(sourcePos(1));
            pos.setZ(sourcePos(2));

            Qt3DExtras::QSphereMesh* sourceSphere = new Qt3DExtras::QSphereMesh();
            sourceSphere->setRadius(0.001f);
            pSourceSphereEntity->addComponent(sourceSphere);

            pSourceSphereEntity->setPosition(pos);

            Qt3DExtras::QPhongMaterial* material = new Qt3DExtras::QPhongMaterial();
            material->setAmbient(Qt::yellow);
            pSourceSphereEntity->addComponent(material);

            m_lSpheres.append(pSourceSphereEntity);
        }
    } else {
        for(int i = 0; i < tHemisphere.vertno.rows(); i++) {
            Renderable3DEntity* pSourceSphereEntity = new Renderable3DEntity(m_pRenderable3DEntity);

            sourcePos = tHemisphere.rr.row(tHemisphere.vertno(i));
            pos.setX(sourcePos(0));
            pos.setY(sourcePos(1));
            pos.setZ(sourcePos(2));

            Qt3DExtras::QSphereMesh* sourceSphere = new Qt3DExtras::QSphereMesh();
            sourceSphere->setRadius(0.001f);
            pSourceSphereEntity->addComponent(sourceSphere);

            pSourceSphereEntity->setPosition(pos);

            Qt3DExtras::QPhongMaterial* material = new Qt3DExtras::QPhongMaterial();
            material->setAmbient(Qt::yellow);
            pSourceSphereEntity->addComponent(material);

            m_lSpheres.append(pSourceSphereEntity);
        }
    }

    //Create color from curvature information with default gyri and sulcus colors
    MatrixX3f matVertColor = createVertColor(tHemisphere.rr);

    //Set renderable 3D entity mesh and color data
    m_pRenderable3DEntity->getCustomMesh()->setMeshData(tHemisphere.rr, tHemisphere.nn, tHemisphere.tris, matVertColor, Qt3DRender::QGeometryRenderer::Triangles);

    //Set shaders
    PerVertexPhongAlphaMaterial* pPerVertexPhongAlphaMaterial = new PerVertexPhongAlphaMaterial();
    m_pRenderable3DEntity->addComponent(pPerVertexPhongAlphaMaterial);

    //Add data which is held by this SourceSpaceTreeItem
    QVariant data;

    data.setValue(matVertColor);
    this->setData(data, Data3DTreeModelItemRoles::SurfaceCurrentColorVert);

    data.setValue(tHemisphere.rr);
    this->setData(data, Data3DTreeModelItemRoles::SurfaceVert);

    //Add surface meta information as item children
    QList<QStandardItem*> list;

    MetaTreeItem* pItemSurfCol = new MetaTreeItem(MetaTreeItemTypes::SurfaceColor, "Surface color");
    connect(pItemSurfCol, &MetaTreeItem::surfaceColorChanged,
            this, &SourceSpaceTreeItem::onSurfaceColorChanged);
    list << pItemSurfCol;
    list << new QStandardItem(pItemSurfCol->toolTip());
    this->appendRow(list);
    data.setValue(QColor(100,100,100));
    pItemSurfCol->setData(data, MetaTreeItemRoles::SurfaceColor);
    pItemSurfCol->setData(data, Qt::DecorationRole);
}

//*************************************************************************************************************

void SourceSpaceTreeItem::setVisible(bool state)
{
    for(int i = 0; i < m_lSpheres.size(); ++i) {
        m_lSpheres.at(i)->setEnabled(state);
    }

    m_pRenderable3DEntity->setEnabled(state);
}

//*************************************************************************************************************

void SourceSpaceTreeItem::onSurfaceColorChanged(const QColor& color)
{
    QVariant data;
    MatrixX3f matNewVertColor = createVertColor(this->data(Data3DTreeModelItemRoles::SurfaceVert).value<MatrixX3f>(), color);

    data.setValue(matNewVertColor);
    this->setData(data, Data3DTreeModelItemRoles::SurfaceCurrentColorVert);
}

//*************************************************************************************************************

void SourceSpaceTreeItem::onCheckStateChanged(const Qt::CheckState& checkState)
{
    this->setVisible(checkState==Qt::Unchecked ? false : true);
}

//*************************************************************************************************************

MatrixX3f SourceSpaceTreeItem::createVertColor(const MatrixXf& vertices, const QColor& color) const
{
    MatrixX3f matColor(vertices.rows(),3);

    for(int i = 0; i<vertices.rows(); i++) {
        matColor(i,0) = color.redF();
        matColor(i,1) = color.greenF();
        matColor(i,2) = color.blueF();
    }

    return matColor;
}


text:
(function (buster, define) {
	'use strict';

	var assert, refute, fail;

	assert = buster.assertions.assert;
	refute = buster.assertions.refute;
	fail = buster.assertions.fail;

	define('rest/mime/registry-test', function (require) {

		var mimeRegistry, when, registry;

		mimeRegistry = require('rest/mime/registry');
		when = require('when');

		buster.testCase('rest/mime/registry', {
			setUp: function () {
				registry = mimeRegistry.child();
			},
			'should discover unregisted converter': function () {
				return registry.lookup('text/plain').then(function (converter) {
					assert.isFunction(converter.read);
					assert.isFunction(converter.write);
				}).otherwise(fail);
			},
			'should return registed converter': function () {
				var converter = {};
				registry.register('application/vnd.com.example', converter);
				return registry.lookup('application/vnd.com.example').then(function (c) {
					assert.same(converter, c);
				}).otherwise(fail);
			},
			'should reject for non-existant converter': function () {
				return registry.lookup('application/bogus').then(
					fail,
					function () {
						assert(true);
					}
				);
			},
			'should resolve converters from parent registries': function () {
				var child, converter;
				child = registry.child();
				converter = {};
				registry.register('application/vnd.com.example', converter);
				return child.lookup('application/vnd.com.example').then(function (c) {
					assert.same(converter, c);
				}).otherwise(fail);
			},
			'should override parent registries when registering in a child': function () {
				var child, converterParent, converterChild;
				child = registry.child();
				converterParent = {};
				converterChild = {};
				registry.register('application/vnd.com.example', converterParent);
				child.register('application/vnd.com.example', converterChild);
				return child.lookup('application/vnd.com.example').then(function (c) {
					assert.same(converterChild, c);
				}).otherwise(fail);
			},
			'should not have any side effects in a parent registry from a child': function () {
				var child, converterParent, converterChild;
				child = registry.child();
				converterParent = {};
				converterChild = {};
				registry.register('application/vnd.com.example', converterParent);
				child.register('application/vnd.com.example', converterChild);
				return registry.lookup('application/vnd.com.example').then(function (c) {
					assert.same(converterParent, c);
				}).otherwise(fail);
			}
		});

	});

}(
	this.buster || require('buster'),
	typeof define === 'function' && define.amd ? define : function (id, factory) {
		var packageName = id.split(/[\/\-]/)[0], pathToRoot = id.replace(/[^\/]+/g, '..');
		pathToRoot = pathToRoot.length > 2 ? pathToRoot.substr(3) : pathToRoot;
		factory(function (moduleId) {
			return require(moduleId.indexOf(packageName) === 0 ? pathToRoot + moduleId.substr(packageName.length) : moduleId);
		});
	}
	// Boilerplate for AMD and Node
));

redpajama_set_name: RedPajamaGithub


text:
<?php require_once 'app.php'; ?>

	<svg><use xlink:href="assets/images/sprite.svg#back" /></svg>

2019

2018

2017

2016

2015

2014

2013

2012

2010

2009

2008

		<form class="form-inline pull-xs-right hidden-md-down">
			<svg><use xlink:href="assets/images/sprite.svg#search" /></svg>
			<input class="form-control" type="text" placeholder="Search" />
		</form>

				<?php gallery('projects/ariston'); ?>

Ariston Timepieces

July 2019 - Lausannne, Switzerland

					Ariston is the first luxury watch that encompass crypto wallet. A physical encryption key is embedded in the case and allows the customer to access his assets (Bitcoin, Ether, etc.).

Development the iOS and Android apps

Industrialization of the coin

Project management

						Website
						Playstore

							<svg><use xlink:href="assets/images/sprite.svg#react" /></svg>

							<svg><use xlink:href="assets/images/sprite.svg#bitcoin" /></svg>

							<svg><use xlink:href="assets/images/sprite.svg#ethereum" /></svg>

							<svg><use xlink:href="assets/images/sprite.svg#nodejs" /></svg>

				<?php gallery('projects/mineority'); ?>

Mineority

June 2018 - Lausanne, Suisse

					Mineority.io allows you to buy graphic cards to mine crypto currencies using a smart contract (Solidity). The goal is to allow full control on the cards for the users and full traceability for the manufacturer.

Develop the frontend and backend interacting with the Ethereum smart contract

Team Management

							<svg><use xlink:href="assets/images/sprite.svg#react" /></svg>

							<svg><use xlink:href="assets/images/sprite.svg#ethereum" /></svg>

							<svg><use xlink:href="assets/images/sprite.svg#nodejs" /></svg>

							<svg><use xlink:href="assets/images/sprite.svg#postgres" /></svg>

					<video autoplay loop muted playsinline>
					  <source src="assets/images/projects/festy/festy-app-demo.webm" type="video/webm">
					  <source src="assets/images/projects/festy/festy-app-demo.mp4" type="video/mp4">
					</video>

Festy

December 2017 - Cork, Ireland

					Festy is a payment system that leverages the use of both cryptocurrencies and blockchain data structure to lower fees and improve security for shop owners.

Secured a 594 Dash (200'00USD) funding from Dash community (link)

Architectured backend and mobile app allowing to pay with multiple cryptocurrencies (Bitcoin, Dash, Ether, Litecoin)

Led a team of five developers

						Website

							<svg><use xlink:href="assets/images/sprite.svg#bitcoin" /></svg>

							<svg><use xlink:href="assets/images/sprite.svg#ethereum" /></svg>

							<svg><use xlink:href="assets/images/sprite.svg#dash" /></svg>

							<svg><use xlink:href="assets/images/sprite.svg#tendermint" /></svg>

							<svg><use xlink:href="assets/images/sprite.svg#nodejs" /></svg>

							<svg><use xlink:href="assets/images/sprite.svg#react" /></svg>

				<?php gallery('projects/horizon'); ?>

Horizon

July 2016 - Social Media Lab at EPFL

					The Horizon project aims at gathering and analyzing data from social network (Facebook, Tweeter, YouTube ...) in order to create emotional indicators linked to specific topics and questions. My role was to industrialize the different steps of the process and create a SAAS platform.

Audit the existing architecture and emit recommendations

Automate  time-consuming operation and optimize the architecture

Participate in daily operations (bug fixing, client support)

						Screenshots

							<svg><use xlink:href="assets/images/sprite.svg#nodejs" /></svg>

							<svg><use xlink:href="assets/images/sprite.svg#python" /></svg>

							<svg><use xlink:href="assets/images/sprite.svg#rabbitmq" /></svg>

							<svg><use xlink:href="assets/images/sprite.svg#docker" /></svg>

							<svg><use xlink:href="assets/images/sprite.svg#mongodb" /></svg>

							<svg><use xlink:href="assets/images/sprite.svg#neo4j" /></svg>

					<?php lazypicture('projects/wallogram/teaser.jpg'); ?>

					<svg><use xlink:href="assets/images/sprite.svg#youtube" /></svg>

Wallogram

January 2015 - Interactive video mapping at Maison d'ailleurs Museum, Yverdon

Turn a wall into a game playground

Let player use his mobile phone as a gamepad

Present the project during Portrait Robot exhibit at Maison d'ailleurs

						Website
						<?php hiddenGallery('projects/wallogram'); ?>
						Pictures
						Github

							<svg><use xlink:href="assets/images/sprite.svg#nodejs" /></svg>

							<svg><use xlink:href="assets/images/sprite.svg#mongodb" /></svg>

							<svg><use xlink:href="assets/images/sprite.svg#javascript" /></svg>

							<svg><use xlink:href="assets/images/sprite.svg#websocket" /></svg>

			<?php lazygallery('projects/proggame'); ?>

Programming game

March 2014 - UX Engineer at School for Business & Engineering Vaud (Heig)

Teach javascript with fun

Get funded by the E-Creation grant from HES-SO Cyberlearn unit

					Play online
					Screenshots
					Github

						<svg><use xlink:href="assets/images/sprite.svg#java" /></svg>

						<svg><use xlink:href="assets/images/sprite.svg#javascript" /></svg>

						<svg><use xlink:href="assets/images/sprite.svg#html" /></svg>

			<?php lazygallery("projects/stalker", "ar=3:2&crop-to-fit"); ?>

Stalker - Experimenting the Zone

September 2013 - Exhibit design at Maison d'Ailleurs Museum, Yverdon

Make the visitor experiment the secret room present in Tarkovski's movie

Let the visitor draw his wish on a tangible surface and project it among other's on a cloud of wires

					Website
					Pictures

						<svg><use xlink:href="assets/images/sprite.svg#javascript" /></svg>

						<svg><use xlink:href="assets/images/sprite.svg#websocket" /></svg>

						<svg><use xlink:href="assets/images/sprite.svg#webgl" /></svg>

			<?php lazygallery("projects/wegas", "ar=1.83&crop-to-fit"); ?>

Wegas

January 2012 - UX Engineer at School for Business & Engineering Vaud (Heig-vd)

Create a Web Game Authoring System for rapid development of serious games

Allow teachers to create games without programming skills

Get funding from RCSO, Western Switzerland School for Applied Science

					Try online
					Screenshots
					Github

					<div class="icon" data-toggle="tooltip" title="JavaEE (Glassfish 3)">
						<svg><use xlink:href="assets/images/sprite.svg#java" /></svg>

						<svg><use xlink:href="assets/images/sprite.svg#postgres" /></svg>

						<svg><use xlink:href="assets/images/sprite.svg#javascript" /></svg>

						<svg><use xlink:href="assets/images/sprite.svg#selenium" /></svg>

				<?php lazypicture('projects/mjte.jpg') ?>

				<svg><use xlink:href="assets/images/sprite.svg#youtube" /></svg>

Michael Jackson: The Experience - Wii

August 2010 - User Interface Engineer at Ubisoft

Design and implement the in-game user interface on Nintendo Wii

					Official website

						<svg><use xlink:href="assets/images/sprite.svg#cplusplus" /></svg>

					<div class="icon" data-toggle="tooltip" title="Nintendo Revolution SDK (Wii)">
						<svg><use xlink:href="assets/images/sprite.svg#nintendo" /></svg>

					<div class="icon" data-toggle="tooltip" title="Actionscript 2.0 (in-game interfaces)">
						<svg><use xlink:href="assets/images/sprite.svg#flash" /></svg>

				<?php lazypicture('projects/mjte_minigame.jpg') ?>

Michael Jackson: The Exerience - Web

August 2010 - User Interface Engineer at Ubisoft

Create a rhythm game where player uses keyboard to mimic Michael

Implement in a Facebook app

					Play online

						<svg><use xlink:href="assets/images/sprite.svg#flash" /></svg>

						<svg><use xlink:href="assets/images/sprite.svg#facebook2" /></svg>

				<?php lazypicture('projects/justdance2.jpg') ?>

				<svg><use xlink:href="assets/images/sprite.svg#youtube" /></svg>

Just Dance 2 - Wii & PS3

February 2010 - Gameplay Programmer at Ubisoft

Design and implement the connection between the game (PS3 and Wii) and Social Networks (Facebook & iPhone applications)

					Official website

						<svg><use xlink:href="assets/images/sprite.svg#cplusplus" /></svg>

					<div class="icon" data-toggle="tooltip" title="Objective C (iPhone application)">
						<svg><use xlink:href="assets/images/sprite.svg#csharp" /></svg>

						<svg><use xlink:href="assets/images/sprite.svg#opengl" /></svg>

						<svg><use xlink:href="assets/images/sprite.svg#playstation" /></svg>

						<svg><use xlink:href="assets/images/sprite.svg#nintendo" /></svg>

					<div class="icon" data-toggle="tooltip" title="Actionscript 2.0 (in-game interfaces)">
						<svg><use xlink:href="assets/images/sprite.svg#flash" /></svg>

			<?php lazygallery("projects/3DBlogosphere", "ff&ar=3:2"); ?>

3DBlogosphere

October 2009 - Knowledge Management Engineer at Siemens Corporate Research

Use virtual worlds to enhance collaboration in a company

Publish the result in a recognized conference

					"3DBlogosphere: A Multisynchronous Approach of Virtual Worlds to Sustain Company Wide Communication"Aeberhard Francois-Xavier, Steve Russell, ICIMT 2009, ACM

					<div class="icon" data-toggle="tooltip" title="Java (J2EE, J2SE, Project Wonderland, JMonkey & Glassfish)">
						<svg><use xlink:href="assets/images/sprite.svg#java" /></svg>

						<svg><use xlink:href="assets/images/sprite.svg#xml" /></svg>

						<svg><use xlink:href="assets/images/sprite.svg#javascript" /></svg>

				<?php lazypicture('projects/dtouch.jpg') ?>

				<svg><use xlink:href="assets/images/sprite.svg#youtube" /></svg>

Audio D-Touch

June 2009 - Research project at Design and Media Laboratory (LDM, EPFL)

Design and implement a tangible user interface (TUI) for audio sequencing

Conduct a user study to validate this work

					Website

						<svg><use xlink:href="assets/images/sprite.svg#cplusplus" /></svg>

			<?php lazygallery("projects/webdesign", "ar=4:3&ff"); ?>

Web design

February 2009 - Lausanne, Switzerland

Create websites and e-commerce platforms for small businesses

Get some money while being a student

					juliecampiche.com
					samiralaoui.ch
					marisolimage.ch
					smagonline.ch
					swissdesignnetwork.org
					velo-migrateur.com
					hopiclowns.ch
					espace-est-ouest.com
					freshprod.com
					fiduswiss.ch
					one-appointment.com
					micronarc.ch
					timetotime.com
					ultra-son.ch
					fag-avenches.ch

						<svg><use xlink:href="assets/images/sprite.svg#php" /></svg>

						<svg><use xlink:href="assets/images/sprite.svg#laravel" /></svg>

						<svg><use xlink:href="assets/images/sprite.svg#ruby" /></svg>

						<svg><use xlink:href="assets/images/sprite.svg#python" /></svg>

						<svg><use xlink:href="assets/images/sprite.svg#rabbitmq" /></svg>

						<svg><use xlink:href="assets/images/sprite.svg#mysql" /></svg>

						<svg><use xlink:href="assets/images/sprite.svg#mongodb" /></svg>

						<svg><use xlink:href="assets/images/sprite.svg#neo4j" /></svg>

						<svg><use xlink:href="assets/images/sprite.svg#javascript" /></svg>

						<svg><use xlink:href="assets/images/sprite.svg#docker" /></svg>

RedCMS

February 2009 - Open source project

Create a lightweight CMS designed with AJAX in mind

					Website

						<svg><use xlink:href="assets/images/sprite.svg#php" /></svg>

						<svg><use xlink:href="assets/images/sprite.svg#mysql" /></svg>

					<div class="icon" data-toggle="tooltip" title="JavaScript (YUI 3)">
						<svg><use xlink:href="assets/images/sprite.svg#javascript" /></svg>

						<svg><use xlink:href="assets/images/sprite.svg#smarty" /></svg>

			<?php lazygallery("projects/eyekidz", "cf&ar=4:3"); ?>

EyeKidz

August 2008 - User interface designer at EverMore Innovation

Design and implement the interface of EyeKidz, a browser for children

					Download

						<svg><use xlink:href="assets/images/sprite.svg#flash" /></svg>

			<?php lazygallery("projects/schlempf"); ?>

Schlempf

January 2008 - Student game contest

Create a mobile game mixing life simulation and adventure

Participate to the Logiquest programming contest sponsored by Sun and Swisscom

					Website

						<svg><use xlink:href="assets/images/sprite.svg#java" /></svg>

	<?php footer('projects'); ?>


text:
package com.google.j2cl.jre.java8.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

/**
 * Tests for java.util.List Java 8 API emulation.
 */
public class ListTest extends AbstractJava8ListTest {
  @Override
  protected List<String> createEmptyList() {
    return new TestList<>();
  }

  private static class TestList<T> implements List<T> {
    private final List<T> container = new ArrayList<>();

    @Override
    public int size() {
      return container.size();
    }

    @Override
    public boolean isEmpty() {
      return container.isEmpty();
    }

    @Override
    public boolean contains(Object o) {
      return container.contains(o);
    }

    @Override
    public Iterator<T> iterator() {
      return container.iterator();
    }

    @Override
    public Object[] toArray() {
      return container.toArray();
    }

    @Override
    public <E> E[] toArray(E[] a) {
      return container.toArray(a);
    }

    @Override
    public boolean add(T t) {
      return container.add(t);
    }

    @Override
    public boolean remove(Object o) {
      return container.remove(o);
    }

    @Override
    public boolean containsAll(Collection<?> c) {
      return container.containsAll(c);
    }

    @Override
    public boolean addAll(Collection<? extends T> c) {
      return container.addAll(c);
    }

    @Override
    public boolean addAll(int index, Collection<? extends T> c) {
      return container.addAll(index, c);
    }

    @Override
    public boolean removeAll(Collection<?> c) {
      return container.removeAll(c);
    }

    @Override
    public boolean retainAll(Collection<?> c) {
      return container.retainAll(c);
    }

    @Override
    public void clear() {
      container.clear();
    }

    @Override
    public T get(int index) {
      return container.get(index);
    }

    @Override
    public T set(int index, T element) {
      return container.set(index, element);
    }

    @Override
    public void add(int index, T element) {
      container.add(index, element);
    }

    @Override
    public T remove(int index) {
      return container.remove(index);
    }

    @Override
    public int indexOf(Object o) {
      return container.indexOf(o);
    }

    @Override
    public int lastIndexOf(Object o) {
      return container.lastIndexOf(o);
    }

    @Override
    public ListIterator<T> listIterator() {
      return container.listIterator();
    }

    @Override
    public ListIterator<T> listIterator(int index) {
      return container.listIterator(index);
    }

    @Override
    public List<T> subList(int fromIndex, int toIndex) {
      return container.subList(fromIndex, toIndex);
    }
  }
}


text:
This is an automatic test framework that is designed to test the day to day performance changes in Moses.

### Set up

#### Set up a Moses repo
Set up a Moses repo and build it with the desired configuration.
```bash
git clone https://github.com/moses-smt/mosesdecoder.git
cd mosesdecoder
./bjam -j10 --with-cmph=/usr/include/
```
You need to build Moses first, so that the testsuite knows what command you want it to use when rebuilding against newer revisions.

#### Create a parent directory.
Create a parent directory where the **runtests.py** and related scripts and configuration file should reside.
This should also be the location of the TEST_DIR and TEST_LOG_DIR as explained in the next section.

#### Set up a global configuration file.
You need a configuration file for the testsuite. A sample configuration file is provided in **testsuite\_config**

MOSES_REPO_PATH: /home/moses-speedtest/moses-standard/mosesdecoder
DROP_CACHES_COMM: sys_drop_caches 3
TEST_DIR: /home/moses-speedtest/phrase_tables/tests
TEST_LOG_DIR: /home/moses-speedtest/phrase_tables/testlogs
BASEBRANCH: RELEASE-2.1.1

The _MOSES\_REPO\_PATH_ is the place where you have set up and built moses.
The _DROP\_CACHES\_COMM_ is the command that would beused to drop caches. It should run without needing root access.
_TEST\_DIR_ is the directory where all the tests will reside.
_TEST\_LOG\_DIR_ is the directory where the performance logs will be gathered. It should be created before running the testsuite for the first time.
_BASEBRANCH_ is the branch against which all new tests will be compared. It should normally be set to be the latest Moses stable release.

### Creating tests

In order to create a test one should go into the TEST_DIR and create a new folder. That folder will be used for the name of the test.
Inside that folder one should place a configuration file named **config**. The naming is mandatory.
An example such configuration file is **test\_config**

Command: moses -f ... -i fff #Looks for the command in the /bin directory of the repo specified in the testsuite_config
LDPRE: ldpreloads #Comma separated LD_LIBRARY_PATH:/,
Variants: vanilla, cached, ldpre #Can't have cached without ldpre or vanilla

The _Command:_ line specifies the executable (which is looked up in the /bin directory of the repo.) and any arguments necessary. Before running the test, the script cds to the current test directory so you can use relative paths.
The _LDPRE:_ specifies if tests should be run with any LD\_PRELOAD flags.
The _Variants:_ line specifies what type of tests should we run. This particular line will run the following tests:
1. A Vanilla test meaning just the command after _Command_ will be issued.
2. A vanilla cached test meaning that after the vanilla test, the test will be run again without dropping caches in order to benchmark performance on cached filesystem.
3. A test with LD_PRELOAD ldpreloads moses -f command. For each available LDPRELOAD comma separated library to preload.
4. A cached version of all LD_PRELOAD tests.

### Running tests.
Running the tests is done through the **runtests.py** script.

#### Running all tests.
To run all tests, with the base branch and the latests revision (and generate new basebranch test data if such is missing) do a:
```bash
python3 runtests.py -c testsuite_config
```

#### Running specific tests.
The script allows the user to manually run a particular test or to test against a specific branch or revision:

moses-speedtest@crom:~/phrase_tables$ python3 runtests.py --help
usage: runtests.py [-h] -c CONFIGFILE [-s SINGLETESTDIR] [-r REVISION]
                   [-b BRANCH]

A python based speedtest suite for moses.

optional arguments:
  -h, --help            show this help message and exit
  -c CONFIGFILE, --configfile CONFIGFILE
                        Specify test config file
  -s SINGLETESTDIR, --singletest SINGLETESTDIR
                        Single test name directory. Specify directory name,
                        not full path!
  -r REVISION, --revision REVISION
                        Specify a specific revison for the test.
  -b BRANCH, --branch BRANCH
                        Specify a branch for the test.

### Generating HTML report.
To generate a summary of the test results use the **html\_gen.py** script. It places a file named *index.html* in the current script directory.
```bash
python3 html_gen.py testsuite_config
```
You should use the generated file with the **style.css** file provided in the html directory.

### Command line regression testing.
Alternatively you could check for regressions from the command line using the **check\_fo\r_regression.py** script:
```bash
python3 check_for_regression.py TESTLOGS_DIRECTORY
```

Alternatively the results of all tests are logged inside the the specified TESTLOGS directory so you can manually check them for additional information such as date, time, revision, branch, etc...

### Create a cron job:
Create a cron job to run the tests daily and generate an html report. An example *cronjob* is available.
```bash
#!/bin/sh
cd /home/moses-speedtest/phrase_tables

python3 runtests.py -c testsuite_config #Run the tests.
python3 html_gen.py testsuite_config #Generate html

cp index.html /fs/thor4/html/www/speed-test/ #Update the html
```

Place the script in _/etc/cron.daily_ for dayly testing

###### Author
Nikolay Bogoychev, 2014

###### License
This software is licensed under the LGPL.


text:
Uruchom zadanie kopii zapasowej

<<<<<<>>>>>> upstream/master
wyników.


text:
package com.mattallen.loaned.addloan;

import java.util.Date;

import com.mattallen.loaned.Item;
import com.mattallen.loaned.Loan;
import com.mattallen.loaned.Person;
import com.mattallen.loaned.R;
import com.mattallen.loaned.notifier.SetAlarm;
import com.mattallen.loaned.storage.DatabaseManager;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

public class AddLoanActivity extends Activity implements AddLoanCallback {

	private static final String				TAG = AddLoanActivity.class.getSimpleName();

	private ActionBar						mActionBar;
	private int								mFrameLayout = R.id.addloan_frame;
	private Fragment						mChoosePerson, mChooseItem;
	private Person							mSelectedPerson;
	private Item							mSelectedItem;
	private DatabaseManager					mDB;
	private ProgressBar						mProgress;
	private FrameLayout						mFrame;
	private Context							mContext;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_addloan);
		// If the available screen size is that of an average tablet (as defined
		// in the Android documentation) then allow the screen to rotate
		if(getResources().getBoolean(R.bool.lock_orientation)){
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		}
		mActionBar = getActionBar();
		mActionBar.setDisplayHomeAsUpEnabled(true);
		mActionBar.setHomeButtonEnabled(true);

		// Instatiate Fragments
		mChooseItem = new ChooseItemFragment();
		mChoosePerson = new ChoosePersonFragment();

		// Show first Fragment
		FragmentTransaction mFragMan = getFragmentManager().beginTransaction();
		mFragMan.add(mFrameLayout, mChoosePerson);
		mFragMan.commit();
		mDB = new DatabaseManager(this);
		mProgress = (ProgressBar)findViewById(R.id.addloan_progress);
		mFrame = (FrameLayout)findViewById(R.id.addloan_frame);
		mContext = this;
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data){
		super.onActivityResult(requestCode, resultCode, data);
		if(data!=null && requestCode==ChoosePersonFragment.PICK_CONTACT_REQUEST
				&&resultCode==RESULT_OK){
			((ChoosePersonFragment)mChoosePerson).addContactCallback(data);
		}
	}

	@Override
	public void onNextButtonClicked(Person person) {
		Log.d(TAG, "Next button clicked");
		mSelectedPerson = person;
		FragmentTransaction mFragMan = getFragmentManager().beginTransaction();
		mFragMan.replace(mFrameLayout, mChooseItem);
		mFragMan.addToBackStack(null);
		mFragMan.commit();
	}

	@Override
	public void onSaveLoan(Item item) {
		Log.d(TAG, "Save loan button clicked");
		mSelectedItem = item;
		if(mSelectedItem.isCurrentlyOnLoan()){
			AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
			dialog.setTitle(R.string.loanhistory_itemdetails_onloan).setMessage(R.string.dialog_addloan_alreadyonloan);
			dialog.setPositiveButton(R.string.okay, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			}).show();
		} else {
			new SaveLoan().execute();
		}
	}

	private class SaveLoan extends AsyncTask<Void, Void, Exception>{
		private Loan loan;
		@Override
		protected void onPreExecute(){
			mProgress.setVisibility(ProgressBar.VISIBLE);
			mFrame.setVisibility(FrameLayout.INVISIBLE);
		}
		@Override
		protected Exception doInBackground(Void... params) {
			try{
				mDB.addLoan(mSelectedPerson.getPersonID(), mSelectedItem.getItemID(), new Date(), true);
				mSelectedPerson.setItemsLoaned(mSelectedPerson.getItemsLoaned()+1);
				mSelectedPerson.setItemsOnLoan(mSelectedPerson.getItemsOnLoan()+1);
				mDB.updatePerson(mSelectedPerson);
				mSelectedItem.setCurrentlyOnLoan(true);
				mSelectedItem.setTimesLoaned(mSelectedItem.getTimesLoaned()+1);
				mDB.updateItem(mSelectedItem);
				loan = mDB.getMostRecentLoanByBothIDs(mSelectedPerson.getPersonID(), mSelectedItem.getItemID());
				return null;
			} catch (Exception e){
				return e;
			}
		}
		@Override
		protected void onPostExecute(Exception e){
			if(e!=null){
				mProgress.setVisibility(ProgressBar.INVISIBLE);
				mFrame.setVisibility(FrameLayout.VISIBLE);
				Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_SHORT).show();
			} else {
				new SetAlarm(mContext, loan);
				finish();
			}
		}
	}
}


text:
<?xml version="1.0"?>
<package>
  <name>ihmc_msgs</name>
  <version>0.9.2</version>
  <description>The ihmc_msgs package defines the IHMC ROS API</description>

  <maintainer email="dstephen@ihmc.us">Doug Stephen</maintainer>

  <license>Apache 2.0</license>

  <url type="website">http://github.com/ihmcrobotics/ihmc_ros_core</url>

  <author email="dstephen@ihmc.us">Doug Stephen</author>

  <buildtool_depend>catkin</buildtool_depend>
  <build_depend>geometry_msgs</build_depend>
  <build_depend>message_generation</build_depend>
  <build_depend>std_msgs</build_depend>
  <run_depend>geometry_msgs</run_depend>
  <run_depend>message_runtime</run_depend>
  <run_depend>std_msgs</run_depend>

</package>


text:
<?xml version="1.0" encoding="utf-8"?>
<ApplicationManifest xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ApplicationTypeName="MicroDemoType" ApplicationTypeVersion="1.0.0" xmlns="http://schemas.microsoft.com/2011/01/fabric">
  <Parameters>
    <Parameter Name="CounterService_MinReplicaSetSize" DefaultValue="2" />
    <Parameter Name="CounterService_PartitionCount" DefaultValue="1" />
    <Parameter Name="CounterService_TargetReplicaSetSize" DefaultValue="3" />
    <Parameter Name="InvoiceService_MinReplicaSetSize" DefaultValue="2" />
    <Parameter Name="InvoiceService_PartitionCount" DefaultValue="1" />
    <Parameter Name="InvoiceService_TargetReplicaSetSize" DefaultValue="3" />
    <Parameter Name="CustomerService_MinReplicaSetSize" DefaultValue="2" />
    <Parameter Name="CustomerService_PartitionCount" DefaultValue="1" />
    <Parameter Name="CustomerService_TargetReplicaSetSize" DefaultValue="3" />
    <Parameter Name="CacheService_MinReplicaSetSize" DefaultValue="2" />
    <Parameter Name="CacheService_PartitionCount" DefaultValue="1" />
    <Parameter Name="CacheService_TargetReplicaSetSize" DefaultValue="3" />
    <Parameter Name="Host_InstanceCount" DefaultValue="-1" />
  </Parameters>
  <ServiceManifestImport>
    <ServiceManifestRef ServiceManifestName="InvoiceAnalyticsPkg" ServiceManifestVersion="1.0.0" />
  </ServiceManifestImport>
  <ServiceManifestImport>
    <ServiceManifestRef ServiceManifestName="CounterServicePkg" ServiceManifestVersion="1.0.0" />
    <ConfigOverrides />
  </ServiceManifestImport>
  <ServiceManifestImport>
    <ServiceManifestRef ServiceManifestName="InvoiceServicePkg" ServiceManifestVersion="1.0.0" />
    <ConfigOverrides />
  </ServiceManifestImport>
  <ServiceManifestImport>
    <ServiceManifestRef ServiceManifestName="CustomerServicePkg" ServiceManifestVersion="1.0.0" />
    <ConfigOverrides />
  </ServiceManifestImport>
  <ServiceManifestImport>
    <ServiceManifestRef ServiceManifestName="CacheServicePkg" ServiceManifestVersion="1.0.0" />
    <ConfigOverrides />
  </ServiceManifestImport>
  <ServiceManifestImport>
    <ServiceManifestRef ServiceManifestName="MicroDemo.HostPkg" ServiceManifestVersion="1.0.0" />
    <ConfigOverrides />
  </ServiceManifestImport>
  <DefaultServices>
    <Service Name="CounterService">
      <StatefulService ServiceTypeName="CounterServiceType" TargetReplicaSetSize="[CounterService_TargetReplicaSetSize]" MinReplicaSetSize="[CounterService_MinReplicaSetSize]">
        <UniformInt64Partition PartitionCount="[CounterService_PartitionCount]" LowKey="-9223372036854775808" HighKey="9223372036854775807" />
      </StatefulService>
    </Service>
    <Service Name="InvoiceService">
      <StatefulService ServiceTypeName="InvoiceServiceType" TargetReplicaSetSize="[InvoiceService_TargetReplicaSetSize]" MinReplicaSetSize="[InvoiceService_MinReplicaSetSize]">
        <UniformInt64Partition PartitionCount="[InvoiceService_PartitionCount]" LowKey="-9223372036854775808" HighKey="9223372036854775807" />
      </StatefulService>
    </Service>
    <Service Name="CustomerService">
      <StatefulService ServiceTypeName="CustomerServiceType" TargetReplicaSetSize="[CustomerService_TargetReplicaSetSize]" MinReplicaSetSize="[CustomerService_MinReplicaSetSize]">
        <UniformInt64Partition PartitionCount="[CustomerService_PartitionCount]" LowKey="-9223372036854775808" HighKey="9223372036854775807" />
      </StatefulService>
    </Service>
    <Service Name="CacheService">
      <StatefulService ServiceTypeName="CacheServiceType" TargetReplicaSetSize="[CacheService_TargetReplicaSetSize]" MinReplicaSetSize="[CacheService_MinReplicaSetSize]">
        <UniformInt64Partition PartitionCount="[CacheService_PartitionCount]" LowKey="-9223372036854775808" HighKey="9223372036854775807" />
      </StatefulService>
    </Service>
    <Service Name="Host">
      <StatelessService ServiceTypeName="HostType" InstanceCount="[Host_InstanceCount]">
        <SingletonPartition />
      </StatelessService>
    </Service>
  </DefaultServices>
</ApplicationManifest>


text:
import L from 'leaflet';
import ClipperLib from 'js-clipper';
import { openDB } from 'idb';
import './OverPassLayer.css';
import './MinZoomIndicator';

const OverPassLayer = L.FeatureGroup.extend({
  options: {
    debug: false,
    minZoom: 15,
    endPoint: 'https://overpass-api.de/api/',
    query: '(node({{bbox}})[organic];node({{bbox}})[second_hand];);out qt;',
    loadedBounds: [],
    markerIcon: null,
    timeout: 30 * 1000, // Milliseconds
    retryOnTimeout: false,
    noInitialRequest: false,
    cacheEnabled: false,
    cacheTTL: 1800, // Seconds

    beforeRequest() {},

    afterRequest() {},

    onSuccess(data) {
      for (let i = 0; i < data.elements.length; i++) {
        let pos;
        let marker;
        const e = data.elements[i];

        if (e.id in this._ids) {
          continue;
        }

        this._ids[e.id] = true;

        if (e.type === 'node') {
          pos = L.latLng(e.lat, e.lon);
        } else {
          pos = L.latLng(e.center.lat, e.center.lon);
        }

        if (this.options.markerIcon) {
          marker = L.marker(pos, { icon: this.options.markerIcon });
        } else {
          marker = L.circle(pos, 20, {
            stroke: false,
            fillColor: '#E54041',
            fillOpacity: 0.9
          });
        }

        const popupContent = this._getPoiPopupHTML(e.tags, e.id);
        const popup = L.popup().setContent(popupContent);
        marker.bindPopup(popup);

        this._markers.addLayer(marker);
      }
    },

    onError() {},

    onTimeout() {},

    minZoomIndicatorEnabled: true,
    minZoomIndicatorOptions: {
      minZoomMessageNoLayer: 'No layer assigned',
      minZoomMessage:
        'Current zoom Level: CURRENTZOOM. Data are visible at Level: MINZOOMLEVEL.'
    }
  },

  initialize(options) {
    L.Util.setOptions(this, options);

    this._ids = {};
    this._loadedBounds = options.loadedBounds || [];
    this._requestInProgress = false;

    if (this.options.cacheEnabled) {
      this._initCacheDb();
    }
  },

  async _initCacheDb() {
    this._cacheDb = await openDB('leaflet-overpass-layer', 1, {
      upgrade(db) {
        db.createObjectStore('cache', { autoIncrement: true });
      }
    });

    const layerAddedToMap = !!this._map;
    if (layerAddedToMap) {
      this._loadCachedItems();
    }
  },

  _getPoiPopupHTML(tags, id) {
    let row;
    const link = document.createElement('a');
    const table = document.createElement('table');
    const div = document.createElement('div');

    link.href = `https://www.openstreetmap.org/edit?editor=id&node=${id}`;
    link.appendChild(document.createTextNode('Edit this entry in iD'));

    table.style.borderSpacing = '10px';
    table.style.borderCollapse = 'separate';

    for (const key in tags) {
      row = table.insertRow(0);
      row.insertCell(0).appendChild(document.createTextNode(key));
      row.insertCell(1).appendChild(document.createTextNode(tags[key]));
    }

    div.appendChild(link);
    div.appendChild(table);

    return div;
  },

  _buildRequestBox(bounds) {
    return L.rectangle(bounds, {
      bounds: bounds,
      color: '#204a87',
      stroke: false,
      fillOpacity: 0.1,
      clickable: false
    });
  },

  _addRequestBox(box) {
    return this._requestBoxes.addLayer(box);
  },

  _getRequestBoxes() {
    return this._requestBoxes.getLayers();
  },

  _removeRequestBox(box) {
    this._requestBoxes.removeLayer(box);
  },

  _removeRequestBoxes() {
    return this._requestBoxes.clearLayers();
  },

  _addResponseBox(box) {
    return this._responseBoxes.addLayer(box);
  },

  _addResponseBoxes(requestBoxes) {
    this._removeRequestBoxes();

    requestBoxes.forEach(box => {
      box.setStyle({
        color: 'black',
        weight: 2
      });
      this._addResponseBox(box);
    });
  },

  _isFullyLoadedBounds(bounds, loadedBounds) {
    if (loadedBounds.length === 0) {
      return false;
    }

    const subjectClips = this._buildClipsFromBounds([bounds]);
    const knownClips = this._buildClipsFromBounds(loadedBounds);
    const clipper = new ClipperLib.Clipper();
    const solutionPolyTree = new ClipperLib.PolyTree();

    clipper.AddPaths(subjectClips, ClipperLib.PolyType.ptSubject, true);
    clipper.AddPaths(knownClips, ClipperLib.PolyType.ptClip, true);

    clipper.Execute(
      ClipperLib.ClipType.ctDifference,
      solutionPolyTree,
      ClipperLib.PolyFillType.pftNonZero,
      ClipperLib.PolyFillType.pftNonZero
    );

    const solutionExPolygons = ClipperLib.JS.PolyTreeToExPolygons(
      solutionPolyTree
    );

    if (solutionExPolygons.length === 0) {
      return true;
    } else {
      return false;
    }
  },

  _getLoadedBounds() {
    return this._loadedBounds;
  },

  _addLoadedBounds(bounds) {
    this._loadedBounds.push(bounds);
  },

  _buildClipsFromBounds(bounds) {
    return bounds.map(bound => [
      {
        X: bound._southWest.lng * 1000000,
        Y: bound._southWest.lat * 1000000
      },
      {
        X: bound._southWest.lng * 1000000,
        Y: bound._northEast.lat * 1000000
      },
      {
        X: bound._northEast.lng * 1000000,
        Y: bound._northEast.lat * 1000000
      },
      {
        X: bound._northEast.lng * 1000000,
        Y: bound._southWest.lat * 1000000
      }
    ]);
  },

  _buildBoundsFromClips(clips) {
    return clips.map(clip =>
      L.latLngBounds(
        L.latLng(clip[0].Y / 1000000, clip[0].X / 1000000).wrap(),
        L.latLng(clip[2].Y / 1000000, clip[2].X / 1000000).wrap()
      )
    );
  },

  _buildOverpassQueryFromQueryAndBounds(query, bounds) {
    const sw = bounds._southWest;
    const ne = bounds._northEast;
    const coordinates = [sw.lat, sw.lng, ne.lat, ne.lng].join(',');

    query = query.replace(/(\/\/.*)/g, '');
    query = query.replace(/(\{\{bbox\}\})/g, coordinates);

    return query;
  },

  _buildOverpassUrlFromEndPointAndQuery(endPoint, query) {
    return `${endPoint}interpreter?data=[out:json];${query}`;
  },

  _buildLargerBounds(bounds) {
    const width = Math.abs(bounds._northEast.lng - bounds._southWest.lng);
    const height = Math.abs(bounds._northEast.lat - bounds._southWest.lat);
    const biggestDimension = width > height ? width : height;

    bounds._southWest.lat -= biggestDimension / 2;
    bounds._southWest.lng -= biggestDimension / 2;
    bounds._northEast.lat += biggestDimension / 2;
    bounds._northEast.lng += biggestDimension / 2;

    return L.latLngBounds(
      L.latLng(bounds._southWest.lat, bounds._southWest.lng).wrap(),
      L.latLng(bounds._northEast.lat, bounds._northEast.lng).wrap()
    );
  },

  _setRequestInProgress(isInProgress) {
    this._requestInProgress = isInProgress;
  },

  _isRequestInProgress() {
    return this._requestInProgress;
  },

  _hasNextRequest() {
    if (this._nextRequest) {
      return true;
    }

    return false;
  },

  _getNextRequest() {
    return this._nextRequest;
  },

  _setNextRequest(nextRequest) {
    this._nextRequest = nextRequest;
  },

  _removeNextRequest() {
    this._nextRequest = null;
  },

  _prepareRequest() {
    if (this._map.getZoom() < this.options.minZoom) {
      return false;
    }

    const bounds = this._buildLargerBounds(this._map.getBounds());
    const nextRequest = this._sendRequest.bind(this, bounds);

    if (this._isRequestInProgress()) {
      this._setNextRequest(nextRequest);
    } else {
      this._removeNextRequest();
      nextRequest();
    }
  },

  _sendRequest(bounds) {
    const loadedBounds = this._getLoadedBounds();

    if (this._isFullyLoadedBounds(bounds, loadedBounds)) {
      this._setRequestInProgress(false);
      return;
    }

    const requestBounds = this._buildLargerBounds(bounds);
    const url = this._buildOverpassUrlFromEndPointAndQuery(
      this.options.endPoint,
      this._buildOverpassQueryFromQueryAndBounds(
        this.options.query,
        requestBounds
      )
    );
    const request = new XMLHttpRequest();
    const beforeRequestResult = this.options.beforeRequest.call(this);

    if (beforeRequestResult === false) {
      this.options.afterRequest.call(this);

      return;
    }

    this._setRequestInProgress(true);

    if (this.options.debug) {
      this._addRequestBox(this._buildRequestBox(requestBounds));
    }

    request.open('GET', url, true);
    request.timeout = this.options.timeout;

    request.ontimeout = () =>
      this._onRequestTimeout(request, url, requestBounds);
    request.onload = () => this._onRequestLoad(request, requestBounds);

    request.send();
  },

  _onRequestLoad(xhr, bounds) {
    if (xhr.status >= 200 && xhr.status < 400) {
      let result = JSON.parse(xhr.response);
      this.options.onSuccess.call(this, result);

      const cacheDbInitialized = typeof this._cacheDb !== 'undefined';
      if (this.options.cacheEnabled && cacheDbInitialized) {
        let expireDate = new Date();
        expireDate.setSeconds(expireDate.getSeconds() + this.options.cacheTTL);

        this._getCachedItems().then(cachedItems => {
          let existingCacheKey = undefined;

          cachedItems.forEach((cachedItem, key) => {
            const queryEquals = cachedItem.query === this.options.query;
            const northEast = L.latLng(cachedItem.bounds._northEast);
            const southWest = L.latLng(cachedItem.bounds._southWest);
            const cachedItemBounds = L.latLngBounds(northEast, southWest);
            if (queryEquals && bounds.equals(cachedItemBounds)) {
              existingCacheKey = key;
            }
          });

          this._cacheDb.put(
            'cache',
            {
              query: this.options.query,
              result: result,
              bounds: bounds,
              expires: expireDate
            },
            existingCacheKey
          );
        });
      }

      this._onRequestLoadCallback(bounds);
    } else {
      this._onRequestErrorCallback(bounds);

      this.options.onError.call(this, xhr);
    }

    this._onRequestCompleteCallback(bounds);
  },

  _onRequestTimeout(xhr, url, bounds) {
    this.options.onTimeout.call(this, xhr);

    if (this.options.retryOnTimeout) {
      this._sendRequest(url);
    } else {
      this._onRequestErrorCallback(bounds);
      this._onRequestCompleteCallback(bounds);
    }
  },

  _onRequestLoadCallback(bounds) {
    this._addLoadedBounds(bounds);

    if (this.options.debug) {
      this._addResponseBoxes(this._getRequestBoxes());
    }
  },

  _onRequestErrorCallback(bounds) {
    if (this.options.debug) {
      this._removeRequestBox(this._buildRequestBox(bounds));
    }
  },

  _onRequestCompleteCallback() {
    this.options.afterRequest.call(this);

    if (this._hasNextRequest()) {
      const nextRequest = this._getNextRequest();

      this._removeNextRequest();

      nextRequest();
    } else {
      this._setRequestInProgress(false);
    }
  },

  async _getCachedItems() {
    const cacheDbInitialized = typeof this._cacheDb !== 'undefined';
    if (!cacheDbInitialized) return;

    const keys = await this._cacheDb.getAllKeys('cache');
    const items = await this._cacheDb.getAll('cache');

    const itemsMap = new Map();
    items.forEach((item, i) => {
      const key = keys[i];
      itemsMap.set(key, item);
    });

    return itemsMap;
  },

  async _loadCachedItems() {
    const cacheDbInitialized = typeof this._cacheDb !== 'undefined';
    if (!cacheDbInitialized || !this._map) return;

    const cachedItems = await this._getCachedItems();
    cachedItems.forEach((cachedItem, key) => {
      if (new Date() > cachedItem.expires) {
        this._cacheDb.delete('cache', key);
      } else {
        if (cachedItem.query === this.options.query) {
          this.options.onSuccess.call(this, cachedItem.result);
          this._onRequestLoadCallback(cachedItem.bounds);
        }
      }
    });
  },

  onAdd(map) {
    this._map = map;

    if (this.options.minZoomIndicatorEnabled === true) {
      if (this._map.zoomIndicator) {
        this._zoomControl = this._map.zoomIndicator;
        this._zoomControl._addLayer(this);
      } else {
        this._zoomControl = new L.Control.MinZoomIndicator(
          this.options.minZoomIndicatorOptions
        );

        this._map.addControl(this._zoomControl);

        this._zoomControl._addLayer(this);
      }
    }

    if (this.options.debug) {
      this._requestBoxes = L.featureGroup().addTo(this._map);
      this._responseBoxes = L.featureGroup().addTo(this._map);
    }

    this._markers = L.featureGroup().addTo(this._map);

    if (this.options.cacheEnabled) {
      const cacheDbInitialized = typeof this._cacheDb !== 'undefined';
      if (cacheDbInitialized) {
        this._loadCachedItems();
      }
    }

    if (!this.options.noInitialRequest) {
      this._prepareRequest();
    }

    this._map.on('moveend', this._prepareRequest, this);
  },

  onRemove(map) {
    L.LayerGroup.prototype.onRemove.call(this, map);

    if (this.options.minZoomIndicatorEnabled === true) {
      if (this._map.zoomIndicator) {
        this._zoomControl._removeLayer(this);
        this._map.removeControl(this._zoomControl);
        this._zoomControl = null;

        this._map.zoomIndicator = null;
      }
    }

    if (this.options.debug) {
      this._map.removeLayer(this._requestBoxes);
      this._map.removeLayer(this._responseBoxes);
    }

    this._resetData();

    this._map.removeLayer(this._markers);

    this._map.off('moveend', this._prepareRequest, this);
  },

  setQuery(query) {
    this.options.query = query;
    this._resetData();
    this._prepareRequest();
  },

  _resetData() {
    this._ids = {};
    this._loadedBounds = [];
    this._requestInProgress = false;

    this._markers.clearLayers();

    if (this.options.debug) {
      this._requestBoxes.clearLayers();
      this._responseBoxes.clearLayers();
    }
  },

  getData() {
    return this._data;
  }
});

L.OverPassLayer = OverPassLayer;
L.overpassLayer = options => new L.OverPassLayer(options);

export default OverPassLayer;


text:
using System;

namespace Hacon.Motash
{
    /// <summary>
    /// Information about a failed task
    /// </summary>
    public class Failure
    {
        /// <summary>
        /// Name of the task
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// Full path of the task in the tree, including the name
        /// </summary>
        public string Path { get; set; }
        /// <summary>
        /// The numeric return value
        /// </summary>
        public int Result { get; set; }
        /// <summary>
        /// The date/time when the task was last running
        /// </summary>
        public DateTime LastRun { get; set; }
    }
}


text:
int overflow[numPidTotal];
//int offset[numPidTotal];
int raw[numPidTotal];
float recent[numPidTotal];
BYTE initialized = FALSE;
BYTE busy =0;
#define jump 3000
void encoderSPIInit();
void AS5055ResetErrorFlag(BYTE index);
void printSystemConfig(BYTE index);
UINT16 AS5055send(BYTE index, UINT16 data);

BOOL enableWrapping=TRUE;

void disableWrapping(){
    enableWrapping=FALSE;
}

void initializeEncoders(){
    DelayMs(200);
    int i;
    println_I("Starting SPI");
    encoderSPIInit();
    // AC: Do we still need this?
    mJTAGPortEnable(0); // Disable JTAG and free up channels 0 and 1
    ENC_CSN_INIT(); // Set pin modes for CS pins
    for(i=0;i<numPidTotal;i++){
        println_I("Encoder ");p_int_I(i);
        AS5055reset(i);
        print_I(" | reset ");
        overflow[i]=0;
        //offset[i]=0;
        recent[i]=0;
        raw[i]=AS5055readAngle(i);
        Delay10us(50);// Delay for the encoders to perform read
        raw[i]=AS5055readAngle(i);
    }
}

float readEncoderWithoutOffset(BYTE index){
    int tmp=0;
    int diff=0;
    if(!busy){
        busy = 1;
        tmp = AS5055readAngle(index);
        diff = raw[index]-tmp;
        print_E(" diff : ");
        p_int_E(diff);
        raw[index]=tmp;
        busy = 0;
    }else{
        diff=0;
    }
    float oflw=0;
    if(enableWrapping){
        if(diff > jump || diff < (-1*jump)){
            if(diff>0)
                overflow[index]++;
            else
                 overflow[index]--;
        }
       oflw= (4096*overflow[index]);
    }
    print_W(" overflow Index : ");
    p_int_W(overflow[index]);
    print_E(" overflow adjustment  : ");
    p_fl_E(oflw);

    float ret = ((((float)tmp)+oflw));
    print_W(" Return value : ");
    p_fl_W(ret);
    return ret;
}

float getRecentEncoderReading(int index){
    float value= recent[index];
    return value;
}

void updateAllEncoders(){
    int i;
    for (i=0;i<numPidMotors;i++){
        // Set the read command to the chip
        readEncoderWithoutOffset(i);
    }
    Delay10us(50);// Delay for the encoders to perform read
    for (i=0;i<numPidMotors;i++){
        // Take a reading after waiting
        println_I("RAW Data:  ");p_int_I(i);
        recent[i] = readEncoderWithoutOffset(i);
        print_I(" raw : ");p_int_I( raw[i]);
        print_I(" val: ");p_int_I( recent[i]);
        print_I(" Done\r\n");
        //AS5055reset(i);
        AS5055ResetErrorFlag(i);
    }
}

//float readEncoder(BYTE index){
//    float size=1;
//    float ret=0;
//    int i;
//    for(i=0;i<size;i++)
//        ret += (readEncoderWithoutOffset(index));
//    recent[index]=ret/size;
//    return getRecentEncoderReading(index);
//}

void encoderSPIInit(){
    SPI_CLK_TRIS=OUTPUT;
    SPI_MISO_TRIS=INPUT;
    SPI_MOSI_TRIS=OUTPUT;
    if(initialized )
        return;
    initialized=TRUE;
#if defined(__32MX795F512L__)
    OpenSPI1(CLK_POL_ACTIVE_HIGH\
            |SPI_MODE8_ON|ENABLE_SDO_PIN|SLAVE_ENABLE_OFF|SPI_CKE_OFF\
            |MASTER_ENABLE_ON|SEC_PRESCAL_3_1|PRI_PRESCAL_4_1
            , SPI_ENABLE);
#elif defined(__32MX440F128H__)
    OpenSPI2(CLK_POL_ACTIVE_HIGH\
            |SPI_MODE8_ON|ENABLE_SDO_PIN|SLAVE_ENABLE_OFF|SPI_CKE_OFF\
            |MASTER_ENABLE_ON|SEC_PRESCAL_3_1|PRI_PRESCAL_4_1
            , SPI_ENABLE);
#endif
}

UINT8   AS5055CalculateParity(UINT16 data){
    UINT8 bits=0;
    UINT8 shift=0;
    for (shift=1; shift<16; shift++){
        if ((data >>  shift)&0x0001)
            bits++;
    }
    if (bits % 2)
        return 1;
    return 0;
}

UINT16 AS5055reset(BYTE index){
    //println_I("[AS5055] Resetting ");p_int_I(index);
    AS5055CommandPacket cmd;
    AS5055ReadPacket read;

    cmd.regs.Address=AS5055REG_SoftwareReset;
    cmd.regs.RWn=AS5055_WRITE;
    cmd.regs.PAR=AS5055CalculateParity(cmd.uint0_15);

    AS5055send(index, cmd.uint0_15);

    return read.uint0_15;
}

void AS5055ResetErrorFlag(BYTE index){
    //println_I("[AS5055send] Clear Error Flags");
    AS5055CommandPacket cmd;

    cmd.regs.Address=AS5055REG_MasterReset;
    cmd.regs.RWn=AS5055_READ;
    cmd.regs.PAR=AS5055CalculateParity(cmd.uint0_15);

    AS5055send(index, cmd.uint0_15);

}

void printSystemConfig(BYTE index){
    AS5055CommandPacket cmd;
    AS5055SystemConfigPacket read;
    cmd.regs.Address=AS5055REG_SystemConfig1;
    cmd.regs.RWn=AS5055_READ;
    cmd.regs.PAR=AS5055CalculateParity(cmd.uint0_15);

    read.uint0_15 = AS5055send(index, cmd.uint0_15);
    Print_Level l = getPrintLevel();
    if(l!=NO_PRINT){
        println_I("System config: ");       prHEX16(read.uint0_15,INFO_PRINT);
        println_I("\tResolution: ");        p_int(read.regs.resolution,INFO_PRINT);
        println_I("\tchip ID: ");           p_int(read.regs.id,INFO_PRINT);
        println_I("\tinvert_spinning: ");   p_int(read.regs.invert,INFO_PRINT);
        println_I("\tFE_bw_setting: ");     p_int(read.regs.bw,INFO_PRINT);
        println_I("\tFE_gain_setting: ");   p_int(read.regs.gain,INFO_PRINT);
        println_I("\tbreak_AGC_loop: ");    p_int(read.regs.break_loop,INFO_PRINT);
    }
    setPrintLevel(l);
}

UINT16 AS5055readAngle(BYTE index){
    Print_Level l = getPrintLevel();

    AS5055AngularDataPacket read;

    int tmp =  AS5055send(index, 0xffff);
    read.uint0_15 = tmp;

    setPrintLevel(l);
    return read.regs.Data;
}

BYTE lock = FALSE;
UINT16 AS5055send(BYTE index, UINT16 data){
    if(lock)
        return 0xffff;
    lock = TRUE;
    UINT16_UNION tmp;
    UINT16_UNION back;
    if(data ==0)
        data = 0xffff;
    tmp.Val=data;
    EncoderSS(index,CSN_Enabled);
    //println_I("[AS5055send] Sending data: ");prHEX8(tmp.byte.SB,INFO_PRINT);prHEX8(tmp.byte.LB,INFO_PRINT);println_I("");
    back.byte.SB = SPITransceve(tmp.byte.SB);
    back.byte.LB = SPITransceve(tmp.byte.LB);
    EncoderSS(index,CSN_Disabled);
//    Delay10us(50);
//    EncoderSS(index,CSN_Enabled);
//   // AC: This gives you the response from the previous command. You need to send outa nop to get the response for this command
//    back.byte.SB = SPITransceve(0);
//    back.byte.LB = SPITransceve(0);
//    EncoderSS(index,CSN_Disabled);
    //println_I("[AS5055send] Got data: ");prHEX8(back.byte.SB,INFO_PRINT);prHEX8(back.byte.LB,INFO_PRINT);println_I("");

    lock = FALSE;
    //print_I("`");
    return back.Val;
}

void EncoderSS(BYTE index, BYTE state){
    if(state == CSN_Enabled){
        encoderSPIInit();
    }else{
         Delay10us(1);
    }
    switch(index){
        case 0:
            ENC0_CSN=state;
            break;
        case 1:
            ENC1_CSN=state;
            break;
        case 2:
            ENC2_CSN=state;
            break;
        case 3:
            ENC3_CSN=state;
            break;
        case 4:
            ENC4_CSN=state;
            break;
        case 5:
            ENC5_CSN=state;
            break;
        case 6:
            ENC6_CSN=state;
            break;
        case 7:
            ENC7_CSN=state;
            break;
    }
    if(state == CSN_Enabled)
        Delay10us(1);
}


text:
#include <ks/gui/KsGuiApplication.hpp>
#include <ks/platform/KsPlatformMain.hpp>

using namespace ks;

int main(int argc, char* argv[])
{
    (void)argc;
    (void)argv;

    // Create application
    shared_ptr<gui::Application> app =
            MakeObject<gui::Application>();

    // Dump screen information
    auto list_screens = app->GetScreens();
    for(auto& screen : list_screens) {
        LOG.Trace() << "Screen: " << screen->name.Get();
        LOG.Trace() << "Rotation: "
                    << static_cast<uint>(screen->rotation.Get());
        LOG.Trace() << "Resolution: "
                    << screen->size_px.Get().first << ","
                    << screen->size_px.Get().second;
        LOG.Trace() << "X DPI: " << screen->xdpi.Get();
        LOG.Trace() << "Y DPI: " << screen->ydpi.Get();
    }

    return 0;
}


text:
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/autofill/payments/save_card_bubble_controller_impl.h"

#include <memory>

#include "base/callback_helpers.h"
#include "base/json/json_reader.h"
#include "base/memory/raw_ptr.h"
#include "base/values.h"
#include "chrome/browser/ui/autofill/payments/save_card_ui.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/test/test_browser_dialog.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/autofill/core/browser/autofill_test_utils.h"
#include "components/autofill/core/browser/payments/legal_message_line.h"
#include "content/public/test/browser_test.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace autofill {

class SaveCardBubbleControllerImplTest : public DialogBrowserTest {
 public:
  SaveCardBubbleControllerImplTest() = default;
  SaveCardBubbleControllerImplTest(const SaveCardBubbleControllerImplTest&) =
      delete;
  SaveCardBubbleControllerImplTest& operator=(
      const SaveCardBubbleControllerImplTest&) = delete;

  void SetUpCommandLine(base::CommandLine* command_line) override {
    DialogBrowserTest::SetUpCommandLine(command_line);
  }

  LegalMessageLines GetTestLegalMessage() {
    absl::optional<base::Value> value(base::JSONReader::Read(
        "{"
        "  \"line\" : [ {"
        "     \"template\": \"The legal documents are: {0} and {1}.\","
        "     \"template_parameter\" : [ {"
        "        \"display_text\" : \"Terms of Service\","
        "        \"url\": \"http://www.example.com/tos\""
        "     }, {"
        "        \"display_text\" : \"Privacy Policy\","
        "        \"url\": \"http://www.example.com/pp\""
        "     } ]"
        "  } ]"
        "}"));
    base::DictionaryValue* dictionary;
    value->GetAsDictionary(&dictionary);
    LegalMessageLines legal_message_lines;
    LegalMessageLine::Parse(*dictionary, &legal_message_lines,
                            /*escape_apostrophes=*/true);
    return legal_message_lines;
  }

  // DialogBrowserTest:
  void ShowUi(const std::string& name) override {
    content::WebContents* web_contents =
        browser()->tab_strip_model()->GetActiveWebContents();

    // Do lazy initialization of SaveCardBubbleControllerImpl. Alternative:
    // invoke via ChromeAutofillClient.
    SaveCardBubbleControllerImpl::CreateForWebContents(web_contents);
    controller_ = SaveCardBubbleControllerImpl::FromWebContents(web_contents);
    DCHECK(controller_);

    AutofillClient::SaveCreditCardOptions options =
        AutofillClient::SaveCreditCardOptions()
            .with_should_request_name_from_user(
                name.find("WithCardholderNameTextfield") != std::string::npos)
            .with_should_request_expiration_date_from_user(
                name.find("WithCardExpirationDateDropDownBox") !=
                std::string::npos)
            .with_show_prompt(true);

    BubbleType bubble_type = BubbleType::INACTIVE;
    if (name.find("Local") != std::string::npos)
      bubble_type = BubbleType::LOCAL_SAVE;
    if (name.find("Server") != std::string::npos)
      bubble_type = BubbleType::UPLOAD_SAVE;
    if (name.find("Manage") != std::string::npos)
      bubble_type = BubbleType::MANAGE_CARDS;
    if (name.find("Failure") != std::string::npos)
      bubble_type = BubbleType::FAILURE;

    switch (bubble_type) {
      case BubbleType::LOCAL_SAVE:
        controller_->OfferLocalSave(
            test::GetCreditCard(),
            AutofillClient::SaveCreditCardOptions().with_show_prompt(true),
            base::DoNothing());
        break;
      case BubbleType::UPLOAD_SAVE:
        controller_->OfferUploadSave(test::GetMaskedServerCard(),
                                     GetTestLegalMessage(), options,
                                     base::DoNothing());
        break;
      case BubbleType::MANAGE_CARDS:
        controller_->ShowBubbleForManageCardsForTesting(test::GetCreditCard());
        break;
      case BubbleType::FAILURE:
        controller_->ShowBubbleForSaveCardFailureForTesting();
        break;
      case BubbleType::UPLOAD_IN_PROGRESS:
      case BubbleType::INACTIVE:
        break;
    }
  }

  SaveCardBubbleControllerImpl* controller() { return controller_; }

 private:
  raw_ptr<SaveCardBubbleControllerImpl> controller_ = nullptr;
};

// Invokes a bubble asking the user if they want to save a credit card locally.
IN_PROC_BROWSER_TEST_F(SaveCardBubbleControllerImplTest, InvokeUi_Local) {
  ShowAndVerifyUi();
}

// Invokes a bubble asking the user if they want to save a credit card to the
// server.
IN_PROC_BROWSER_TEST_F(SaveCardBubbleControllerImplTest, InvokeUi_Server) {
  ShowAndVerifyUi();
}

// Invokes a bubble asking the user if they want to save a credit card to the
// server, with an added textfield for entering/confirming cardholder name.
IN_PROC_BROWSER_TEST_F(SaveCardBubbleControllerImplTest,
                       InvokeUi_Server_WithCardholderNameTextfield) {
  ShowAndVerifyUi();
}

// Invokes a bubble asking the user if they want to save a credit card to the
// server, with a pair of dropdowns for entering expiration date.
IN_PROC_BROWSER_TEST_F(SaveCardBubbleControllerImplTest,
                       InvokeUi_Server_WithCardExpirationDateDropDownBox) {
  ShowAndVerifyUi();
}

// Invokes a sign-in promo bubble.
// TODO(crbug.com/855186): This browsertest isn't emulating the environment
//   quite correctly; disabling test for now until cause is found.
/*
IN_PROC_BROWSER_TEST_F(SaveCardBubbleControllerImplTest, InvokeUi_Promo) {
  ShowAndVerifyUi();
}
*/

// Invokes a bubble displaying the card just saved and an option to
// manage cards.
IN_PROC_BROWSER_TEST_F(SaveCardBubbleControllerImplTest, InvokeUi_Manage) {
  ShowAndVerifyUi();
}

// Invokes a bubble displaying the card saving just failed.
IN_PROC_BROWSER_TEST_F(SaveCardBubbleControllerImplTest, InvokeUi_Failure) {
  ShowAndVerifyUi();
}

// Tests that opening a new tab will hide the save card bubble.
IN_PROC_BROWSER_TEST_F(SaveCardBubbleControllerImplTest, NewTabHidesDialog) {
  ShowUi("Local");
  EXPECT_NE(nullptr, controller()->GetSaveCardBubbleView());
  // Open a new tab page in the foreground.
  ui_test_utils::NavigateToURLWithDisposition(
      browser(), GURL(chrome::kChromeUINewTabURL),
      WindowOpenDisposition::NEW_FOREGROUND_TAB,
      ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB |
          ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP);
  EXPECT_EQ(nullptr, controller()->GetSaveCardBubbleView());
}

}  // namespace autofill


text:
package com.rvantwisk.cnctools.misc;

import com.dooapp.xstreamfx.*;
import com.rvantwisk.cnctools.data.*;
import com.rvantwisk.cnctools.data.tools.BallMill;
import com.rvantwisk.cnctools.data.tools.EndMill;
import com.sun.javafx.collections.ObservableListWrapper;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.XppDomDriver;
import javafx.beans.property.*;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.ArrayList;

/**
 * Created with IntelliJ IDEA.
 * User: rvt
 * Date: 10/6/13
 * Time: 1:05 PM
 * To change this template use File | Settings | File Templates.
 */
public class ProjectModel {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private static String SEPARATOR = System.getProperty("line.separator");

    private static final String PROJECTS_XML = "projects.xml";
    private static final String TOOLS_XML = "tools.xml";
    private static final String POSTPROCESSORS_XML = "postprocessors.xml";
    final private ObservableList<Project> projectsProperty = FXCollections.observableArrayList();
    final private ObservableList<ToolParameter> toolDBProperty = FXCollections.observableArrayList();
    final private ObservableList<CNCToolsPostProcessConfig> postProcessors = FXCollections.observableArrayList();

    private transient ToolDBManager toolDBManager;

    public ToolDBManager getToolDBManager() {
        if (toolDBManager==null) {
            toolDBManager = new ToolDBManager(toolDBProperty);
        }
        return toolDBManager;
    }

    public ObservableList<Project> projectsProperty() {
        return projectsProperty;
    }

    public ObservableList<ToolParameter> toolDBProperty() {
        return toolDBProperty;
    }
    public ObservableList<CNCToolsPostProcessConfig> postProcessorsProperty() {
        return postProcessors;
    }

    public void addProject(String projectname, String description) {
        Project project = new Project(projectname, description);
        projectsProperty.add(project);
    }

    public void addProject(final Project p) {
        projectsProperty.add(p);
    }

    private static Converter lookupTypeConverter(XStream xStream, Class clazz) {
        return xStream.getConverterLookup().lookupConverterForType(clazz);
    }

    private static XStream getXStream() {

        XStream xStream = new XStream(new XppDomDriver() {
            public HierarchicalStreamWriter createWriter(Writer out) {
                CdataWrapper cdw = new CdataWrapper(out);
                cdw.setToWrap(new String[]{"gcode"});
                return cdw;
            }
        }
        );

        xStream.registerConverter(new StringPropertyConverter(xStream.getMapper()));
        xStream.registerConverter(new BooleanPropertyConverter(xStream.getMapper()));
//        xStream.registerConverter(new ObjectPropertyConverter(xStream.getMapper()));
        xStream.registerConverter(new DoublePropertyConverter(xStream.getMapper()));
        xStream.registerConverter(new LongPropertyConverter(xStream.getMapper()));
        xStream.registerConverter(new IntegerPropertyConverter(xStream.getMapper()));
//        xStream.registerConverter(new ObservableListConverter(xStream.getMapper()));

//        xStream.registerConverter(new ConverterWrapper(lookupTypeConverter(xStream, List.class), ObservableListWrapper.class));
//        xStream.registerConverter(new ConverterWrapper(lookupTypeConverter(xStream, List.class), ObservableList.class));
//        xStream.registerConverter(new ConverterWrapper(lookupTypeConverter(xStream, Map.class), ObservableMap.class));

        xStream.omitField(ObservableListWrapper.class, "listenerHelper");

    //    FXConverters.configure(xstream);

        // JavaFX aliases
        xStream.alias("IntProp", SimpleIntegerProperty.class);
        xStream.alias("StrProp", SimpleStringProperty.class);
        xStream.alias("DblProp", SimpleDoubleProperty.class);
        xStream.alias("Boolprop", SimpleBooleanProperty.class);
        xStream.alias("ObjProp", SimpleObjectProperty.class);
        xStream.alias("LongProp", SimpleLongProperty.class);
        xStream.alias("OListWrapper", ObservableListWrapper.class);

        // Program properties aliases
        xStream.alias("Task", TaskRunnable.class);
        xStream.alias("Project", Project.class);
        xStream.alias("StockToolParameter", StockToolParameter.class);
        xStream.alias("EndMill", EndMill.class);
        xStream.alias("BallMill", BallMill.class);
        xStream.alias("AvailableTask", AbstractTask.class);
        xStream.alias("ToolParameter", ToolParameter.class);

        String contents = "<tag>my data conents</tag>";
        String xml = "              <gcode class=\"StrProp\"><![CDATA[asd\n" +
                "asd\n" +
                "asd\n" +
                "]]></gcode>";
        SimpleStringProperty results = (SimpleStringProperty) xStream.fromXML(xml);

        return xStream;
    }

    public void saveProjects() {
        XStream xstream = getXStream();

        File file = new File(PROJECTS_XML);
        try {
            String xml = xstream.toXML(new ArrayList<>(projectsProperty));
            FileUtil.saveFile(xml, file);
        } catch (Exception e) { // catches ANY exception
            logger.error("saveProjects", e);
        }
    }

    public void saveToolDB() {
        XStream xstream = getXStream();
        File file = new File(TOOLS_XML);
        try {
            String xml = xstream.toXML(new ArrayList<>(toolDBProperty));
            FileUtil.saveFile(xml, file);
        } catch (Exception e) { // catches ANY exception
            logger.error("saveToolDB", e);
        }
    }

    public void savePostProcessors() {
        XStream xstream = getXStream();
        File file = new File(POSTPROCESSORS_XML);
        try {
            String xml = xstream.toXML(new ArrayList<>(postProcessors));
            FileUtil.saveFile(xml, file);
        } catch (Exception e) { // catches ANY exception
            logger.error("savePostProcessors", e);
        }
    }

    public void loadToolsFromDB () {
        XStream xstream = getXStream();
        try {
            File file = new File(TOOLS_XML);
            ArrayList<ToolParameter> tools = (ArrayList<ToolParameter>) xstream.fromXML(readFileIntoString(file).toString());
            toolDBProperty.clear();
            toolDBProperty.addAll(tools);
        } catch (Exception e) { // catches ANY exception
            logger.error("Error loading tools DB", e);
        }
    }

    public void loadProjectsFromDB() {
        XStream xstream = getXStream();
        try {

            File file = new File(PROJECTS_XML);
            ArrayList<Project> projects = (ArrayList<Project>) xstream.fromXML(readFileIntoString(file).toString());
            projectsProperty.clear();
            projectsProperty.addAll(projects);
        } catch (Exception e) { // catches ANY exception
            logger.error("Error tools projects DB", e);
        }
    }

    public void loadPostProcessors() {
        XStream xstream = getXStream();
        try {

            File file = new File(POSTPROCESSORS_XML);
            ArrayList<CNCToolsPostProcessConfig> data = (ArrayList<CNCToolsPostProcessConfig>) xstream.fromXML(readFileIntoString(file).toString());
            postProcessors.clear();
            postProcessors.addAll(data);
        } catch (Exception e) { // catches ANY exception
            logger.error("Error loading post processors from DB", e);
        }
    }

    /**
     * Read a file into a String
     * @param file
     * @return
     */
    public static String readFileIntoString(File file) throws IOException {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader br = new BufferedReader(new FileReader(file.getPath())))
        {
            String sCurrentLine;
            while ((sCurrentLine = br.readLine()) != null) {
                sb.append(sCurrentLine).append(SEPARATOR);
            }
        }
        return sb.toString();
    }

    /**
     * Create a deep copy of a java bean
     * WARNING: Unesure you are doing this on beans only!
     * @param obj
     * @param <T>
     * @return
     */
    public static <T extends Object> T deepCopy(final Object obj){
        return (T)getXStream().fromXML(getXStream().toXML(obj));
    }

}


text:
<?php

namespace Bavarianlabs\Omnipay\Moip;

use Omnipay\Common\AbstractGateway;

class Gateway extends AbstractGateway
{

    /**
     * Get gateway display name
     *
     * This can be used by carts to get the display name gateway.
     *
     * @return string
     */
    public function getName()
    {
        return 'MoIP Payment';
    }

    /**
     * Get gateway display short name
     *
     * This can be used by developers to get the short display name gateway.
     *
     * @return string
     */
    public function getShortName()
    {
        return 'MoIP';
    }

    /**
     * Set token authorization service
     *
     * @param string $token
     */
    public function setToken($token)
    {
        $this->setParameter('token', $token);
    }

    /**
     * Get token authorization service
     *
     * @return string
     */
    public function getToken()
    {
        return $this->getParameter('token');
    }

    /**
     * Set api key authentication service
     *
     * @param string $apiKey
     */
    public function setApiKey($apiKey)
    {
        $this->setParameter('apiKey', $apiKey);
    }

    /**
     * Get api key authentication service
     *
     * @return string $apiKey
     */
    public function getApiKey()
    {
        return $this->getParameter('apiKey');
    }

    /**
     * Create request for to consume service
     *
     * @param array $parameters
     * @return \Omnipay\Common\Message\AbstractRequest
     */
    public function authorize(array $parameters = array())
    {
        return $this->createRequest('\Bavarianlabs\Omnipay\Moip\Message\AuthorizeRequest', $parameters);
    }

}


text:
package org.jzy3d.plot3d.primitives.axes.layout.providers;

/** Compute the ticks placements automatically between values min and max.
 *
 * @author Jerome Kodjabachian
 */
public class SmartTickProvider extends AbstractTickProvider implements ITickProvider{
	public SmartTickProvider(){
		this(5);
	}

	public SmartTickProvider(int steps){
		this.steps = steps;
	}

	@Override
	public float[] generateTicks(float min, float max, int steps) {
		if(min == max){
			float[] ticks = new float[1];
			ticks[0] = min;
			return ticks;
		}
		else if(min > max)
			return new float[0];

		double absscale = Math.floor(Math.log10(max-min));
		double relscale = Math.log10(max-min) - absscale;
		float ticksize = 0;

		if( relscale < Math.log10(0.2*steps) )
		    ticksize = (float) (Math.pow(10,absscale)*0.2);
		else if( relscale < Math.log10(0.5*steps) )
		    ticksize = (float) (Math.pow(10,absscale)*0.5);
		else if( relscale < Math.log10(1*steps) )
		    ticksize = (float) Math.pow(10,absscale)*1;
		else
		    ticksize = (float) Math.pow(10,absscale)*2;

		int start = (int)Math.ceil(min/ticksize);
		int stop  = (int)Math.floor(max/ticksize);

		float[] ticks = new float[stop-start+1];

		for(int t=start; t<=stop; t++)
			ticks[t-start] = (t*ticksize);

		return ticks;
	}

	@Override
	public int getDefaultSteps() {
		return steps;
	}

	protected int steps;
}


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCollectionsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('collections', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->string('slug');
            $table->text('preview');
            $table->string('image');
            $table->integer('priority');
            $table->tinyInteger('on_main');
            $table->tinyInteger('active');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('collections');
    }
}


text:
class CubeClient :
	public TcpClient
{
public:

	typedef void (CubeClient::*CommandHandlerPtr)(Value&);

	bool Succeeded = false;
	SessionErrorType LastErrorCode = SESSIONERROR_UNKNOWN;
	string LastErrorMessage;

	CubeClient();
	~CubeClient();

	void Start();
	void Close();
	bool Auth(string);

	void OnPackage(Package*&);

private:

	map<string, CommandHandlerPtr> commandHandlers;
	void initCommandHandlers();

	ManualEvent ackEvent, responseEvent;

	thread *threadHeartbeat = NULL;

	void handleCommandAndAck(Document&);

	void heartbeat();
};


text:
<!doctype html>

<meta charset="utf-8">
<title>Syntax Highlighting Post – R.o.A.S</title>
<meta name="description" content="Demo post displaying the various ways of highlighting code in Markdown.">
<meta name="keywords" content="sample-post, code, highlighting">

<meta name="twitter:title" content="Syntax Highlighting Post">
<meta name="twitter:description" content="Demo post displaying the various ways of highlighting code in Markdown.">

<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="http://blog.morequalifiedleads.co.uk/images/so-simple-sample-image-5.jpg">

<meta property="og:locale" content="en_US">
<meta property="og:type" content="article">
<meta property="og:title" content="Syntax Highlighting Post">
<meta property="og:description" content="Demo post displaying the various ways of highlighting code in Markdown.">
<meta property="og:url" content="http://blog.morequalifiedleads.co.uk/articles/code-highlighting-post/">
<meta property="og:site_name" content="R.o.A.S">

<link rel="canonical" href="http://blog.morequalifiedleads.co.uk/articles/code-highlighting-post/">
<link href="http://blog.morequalifiedleads.co.uk/feed.xml" type="application/atom+xml" rel="alternate" title="R.o.A.S Feed">

<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link rel="stylesheet" href="http://blog.morequalifiedleads.co.uk/assets/css/main.css">

<meta http-equiv="cleartype" content="on">

<link rel="shortcut icon" href="http://blog.morequalifiedleads.co.uk/favicon.ico">

<link rel="shortcut icon" href="http://blog.morequalifiedleads.co.uk/favicon.png">

<link rel="apple-touch-icon-precomposed" href="http://blog.morequalifiedleads.co.uk/images/apple-touch-icon-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="72x72" href="http://blog.morequalifiedleads.co.uk/images/apple-touch-icon-72x72-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="114x114" href="http://blog.morequalifiedleads.co.uk/images/apple-touch-icon-114x114-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="144x144" href="http://blog.morequalifiedleads.co.uk/images/apple-touch-icon-144x144-precomposed.png">

Articles

More Qualified Leads

Mobile Advertising

Display intel

About

Search

        sample-post • code • highlighting

Syntax Highlighting Post

        By Jen-Lars Brannstrom
        <time datetime="2013-08-16T00:00:00+05:30"> August 16, 2013</time>

         Comment

   Tweet

   Like

   +1

Syntax highlighting is a feature that displays source code, in different colors and fonts according to the category of terms. This feature facilitates writing in a structured language such as a programming language or a markup language as both structures and syntax errors are visually distinct. Highlighting does not affect the meaning of the text itself; it is intended only for human readers.1

Pygments or Rouge Code Blocks

To modify styling and highlight colors edit /_sass/_syntax.scss.

#container {
  float: left;
  margin: 0 -240px 0 0;
  width: 100%;
}

<nav class="pagination" role="navigation">
    {% if page.previous %}
        <a href="{{ site.url }}{{ page.previous.url }}" class="btn" title="{{ page.previous.title }}">Previous article</a>
    {% endif %}
    {% if page.next %}
        <a href="{{ site.url }}{{ page.next.url }}" class="btn" title="{{ page.next.title }}">Next article</a>
    {% endif %}
</nav><!-- /.pagination -->

module Jekyll
  class TagIndex < Page
    def initialize(site, base, dir, tag)
      @site = site
      @base = base
      @dir = dir
      @name = 'index.html'
      self.process(@name)
      self.read_yaml(File.join(base, '_layouts'), 'tag_index.html')
      self.data['tag'] = tag
      tag_title_prefix = site.config['tag_title_prefix'] || 'Tagged: '
      tag_title_suffix = site.config['tag_title_suffix'] || '&#8211;'
      self.data['title'] = "#{tag_title_prefix}#{tag}"
      self.data['description'] = "An archive of posts tagged #{tag}."
    end
  end
end

Standard Code Block

<nav class="pagination" role="navigation">
    {% if page.previous %}
        <a href="{{ site.url }}{{ page.previous.url }}" class="btn" title="{{ page.previous.title }}">Previous article</a>
    {% endif %}
    {% if page.next %}
        <a href="{{ site.url }}{{ page.next.url }}" class="btn" title="{{ page.next.title }}">Next article</a>
    {% endif %}
</nav><!-- /.pagination -->

Fenced Code Blocks

To modify styling and highlight colors edit /_sass/_coderay.scss. Line numbers and a few other things can be modified in _config.yml. Consult Jekyll's documentation for more information.

#container {
    float: left;
    margin: 0 -240px 0 0;
    width: 100%;
}

<nav class="pagination" role="navigation">
    {% if page.previous %}
        <a href="{{ site.url }}{{ page.previous.url }}" class="btn" title="{{ page.previous.title }}">Previous article</a>
    {% endif %}
    {% if page.next %}
        <a href="{{ site.url }}{{ page.next.url }}" class="btn" title="{{ page.next.title }}">Next article</a>
    {% endif %}
</nav><!-- /.pagination -->

module Jekyll
  class TagIndex < Page
    def initialize(site, base, dir, tag)
      @site = site
      @base = base
      @dir = dir
      @name = 'index.html'
      self.process(@name)
      self.read_yaml(File.join(base, '_layouts'), 'tag_index.html')
      self.data['tag'] = tag
      tag_title_prefix = site.config['tag_title_prefix'] || 'Tagged: '
      tag_title_suffix = site.config['tag_title_suffix'] || '&#8211;'
      self.data['title'] = "#{tag_title_prefix}#{tag}"
      self.data['description'] = "An archive of posts tagged #{tag}."
    end
  end
end

http://en.wikipedia.org/wiki/Syntax_highlighting ↩

Please enable JavaScript to view the comments powered by Disqus.
comments powered by Disqus

        Previous

        Next

© 2015 Jen-Lars Brannstrom. Powered by Jekyll using the So Simple Theme.


text:
FILES_FILE=$1

# where are the raw fastqs?
ORIG_LOCATION=/mnt/EXT/Schloss-data/zackular/WT-Nod1-analyses

# where are we putting the fastqs?
RAW_FOLDER=data/raw

# let's clean the fastq files out of the raw folder
rm $RAW_FOLDER/*.fastq

# the second column of the files file contains the file names for read 1 and the
# third column contains the file names for read 2
FASTQ="$(cut -f 2 $FILES_FILE) $(cut -f 3 $FILES_FILE)"

# cycle through the FASTQ file names and copy them from one place to the next
for FILE in $FASTQ
do
    echo $FILE
    cp "$ORIG_LOCATION/$FILE" "$RAW_FOLDER"
done