text:
package com.mocircle.cidrawing.mode;

import com.mocircle.cidrawing.core.CiPaint;
import com.mocircle.cidrawing.core.Vector2;
import com.mocircle.cidrawing.element.DrawElement;
import com.mocircle.cidrawing.element.shape.ShapeElement;

public class InsertShapeMode extends InsertVectorElementMode {

    private static final String TAG = "InsertShapeMode";

    private Class<? extends ShapeElement> shapeType;
    private ShapeElement shapeInstance;

    public InsertShapeMode() {
    }

    /**
     * Sets shape type, it has the lower priority then {@link #setShapeInstance(ShapeElement)},
     * which means if shape instance has been set, it will ignore shape type.
     *
     * @param shapeType shape type
     */
    public void setShapeType(Class<? extends ShapeElement> shapeType) {
        this.shapeType = shapeType;
    }

    /**
     * Sets shape instance, it will create shape according to this sample instance. And it has the
     * higher priority then {@link #setShapeType(Class)}, which means if we set shape type and shape
     * instance, shape instance will take effect.
     *
     * @param shapeInstance shape instance
     */
    public void setShapeInstance(ShapeElement shapeInstance) {
        this.shapeInstance = shapeInstance;
    }

    @Override
    protected DrawElement createPreviewElement() {
        previewElement = getShapeInstance();
        previewElement.setPaint(paintBuilder.createPreviewPaint(drawingContext.getPaint()));
        return previewElement;
    }

    @Override
    protected DrawElement createRealElement(Vector2 vector) {
        ShapeElement element = getShapeInstance();
        element.setPaint(new CiPaint(drawingContext.getPaint()));
        element.setupElementByVector(vector);
        return element;
    }

    private ShapeElement getShapeInstance() {
        if (shapeInstance != null) {
            return (ShapeElement) shapeInstance.clone();
        } else if (shapeType != null) {
            try {
                return shapeType.newInstance();
            } catch (InstantiationException e) {
                throw new RuntimeException("Cannot create shape.", e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException("Cannot create shape.", e);
            }
        } else {
            throw new RuntimeException("Cannot find shape type or shape sample instance to create the new shape.");
        }
    }

}


text:
<?php

namespace JDesrosiers\Silex\Provider;

use Doctrine\Common\Annotations\AnnotationRegistry;
use Silex\Application;
use Silex\ServiceProviderInterface;
use Swagger\Logger;

/**
 * The SwaggerServiceProvider adds a swagger-php service to a silex app.  It also adds the routes necessary for
 * integrating with swagger-ui.
 */
class SwaggerServiceProvider implements ServiceProviderInterface
{
    /**
     * Add routes to the app that generate swagger documentation based on your annotations
     *
     * @param Application $app
     */
    public function boot(Application $app)
    {
        AnnotationRegistry::registerAutoloadNamespace("Swagger\Annotations", $app["swagger.srcDir"]);

        if ($app["logger"]) {
            $logger = Logger::getInstance();
            $originalLog = $logger->log;
            $logger->log = function ($entry, $type) use ($app, $originalLog) {
                $app["logger"]->notice($entry);
                $originalLog($entry, $type);
            };
        }

        $app->get($app["swagger.apiDocPath"], new ResourceListController());
        $app->get("{$app["swagger.apiDocPath"]}/{service}", new ResourceDefinitionController());
    }

    /**
     * Registers the swagger service
     *
     * @param Application $app
     */
    public function register(Application $app)
    {
        $app["swagger.apiDocPath"] = "/api/api-docs";
        $app["swagger.excludePath"] = array();
        $app["swagger.prettyPrint"] = true;
        $app["swagger.cache"] = array();
        $app["swagger.basePath"] = null;
        $app["swagger.apiVersion"] = null;
        $app["swagger.swaggerVersion"] = "1.2";
        $app["swagger.resourcePrefix"] = "/";
        $app["swagger.resourceSuffix"] = "";

        $app["swagger"] = $app->share(new SwaggerService());
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.twitter.finagle.loadbalancer.aperture

import com.twitter.util.Closable
import org.scalacheck.Gen
import org.scalatest.FunSuite
import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks

class ProcessCoordinateTest extends FunSuite with ScalaCheckDrivenPropertyChecks {
  import ProcessCoordinate._

  test("update coordinate") {
    var coordinate: Option[Coord] = None
    val closable = ProcessCoordinate.changes.respond(coordinate = _)
    ProcessCoordinate.setCoordinate(2, 10)
    assert(coordinate.isDefined)

    assert(ProcessCoordinate() == coordinate)

    ProcessCoordinate.unsetCoordinate()
    assert(coordinate.isEmpty)
  }

  test("setCoordinate") {
    intercept[Exception] { ProcessCoordinate.setCoordinate(0, 0) }

    val numInstances = 10

    ProcessCoordinate.setCoordinate(1, numInstances)
    val coord0 = ProcessCoordinate()

    ProcessCoordinate.setCoordinate(2, numInstances)
    val coord1 = ProcessCoordinate()

    assert(coord0.isDefined)
    assert(coord1.isDefined)
    assert(coord0 != coord1)
  }

  private[this] val IdAndCount = for {
    count <- Gen.choose[Int](1, Int.MaxValue)
    id <- Gen.choose[Int](0, count - 1)
  } yield id -> count

  test("setCoordinate range") {
    ProcessCoordinate.setCoordinate(0, 1)
    val sample = ProcessCoordinate()
    assert(sample.isDefined)
    assert(1.0 - sample.get.unitWidth <= 1e-6)

    forAll(IdAndCount) {
      case (instanceId, numInstances) =>
        ProcessCoordinate.setCoordinate(instanceId, numInstances)
        val sample = ProcessCoordinate()
        assert(sample.isDefined)
        val offset = sample.get.offset
        val width = sample.get.unitWidth
        assert(offset >= 0 && offset < 1.0)
        assert(width > 0 && width <= 1.0)
    }
  }

  test("apply returns the most current value") {
    val closables = (1 to 100).map { i =>
      val closable = ProcessCoordinate.changes.respond { coord =>
        assert(ProcessCoordinate() == coord)
      }
      ProcessCoordinate.setCoordinate(2, i)
      closable
    }

    // Cleanup global state
    Closable.all(closables: _*).close()
  }
}


text:
        Chemfiles

    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbar-collapsed" aria-controls="navbar-collapsed" aria-expanded="false" aria-label="Toggle navigation">

    </button>

            {% octoicon 'organization' %} Contact

            {% octoicon 'book' %} Documentation

C++ and C

            Latest
            Stable (0.10.0)

Python

            Latest
            Stable (0.10.0)

Fortran

            Latest
            Stable (0.10.0)

Julia

            Latest
            Stable (0.10.0)

Rust

            Latest
            Stable (0.10.0)

                {% octoicon 'mark-github' %} Sources


text:
const DrawCard = require('../../drawcard.js');
const AbilityDsl = require('../../abilitydsl');

class BlackmailArtist extends DrawCard {
    setupCardAbilities() {
        this.reaction({
            title: 'Take 1 honor',
            when: {
                afterConflict: (event, context) => context.source.isParticipating() && event.conflict.winner === context.player &&
                                                   context.player.opponent && event.conflict.conflictType === 'political'
            },
            gameAction: AbilityDsl.actions.takeHonor()
        });
    }
}

BlackmailArtist.id = 'blackmail-artist';

module.exports = BlackmailArtist;


text:
package es.daniel.somanalisys.Model;

public interface ModelManagerListener {
    public void iterationEvent(ModelManager src, int iteration);
}


text:
                        Yemory

                            {{element}}

            <form ng-submit="add()">

                    <input type="text" class="form-control" ng-model="element">

                        <button type="submit" class="btn btn-primary">

                        </button>

            </form>


text:
<?php

final class PhabricatorEnumConfigType
  extends PhabricatorTextConfigType {

  const TYPEKEY = 'enum';

  public function validateStoredValue(
    PhabricatorConfigOption $option,
    $value) {

    if (!is_string($value)) {
      throw $this->newException(
        pht(
          'Option "%s" is of type "%s", but the configured value is not '.
          'a string.',
          $option->getKey(),
          $this->getTypeKey()));
    }

    $map = $option->getEnumOptions();
    if (!isset($map[$value])) {
      throw $this->newException(
        pht(
          'Option "%s" is of type "%s", but the current value ("%s") is not '.
          'among the set of valid values: %s.',
          $option->getKey(),
          $this->getTypeKey(),
          $value,
          implode(', ', array_keys($map))));
    }
  }

  protected function newControl(PhabricatorConfigOption $option) {
    $map = array(
      '' => pht('(Use Default)'),
    ) + $option->getEnumOptions();

    return id(new AphrontFormSelectControl())
      ->setOptions($map);
  }

}


text:
using SolrExpress.Search.Parameter;
using System;

namespace SolrExpress.Solr5.UnitTests
{
    public class FakeParameter : ISearchParameter
    {
        public bool Equals(ISearchParameter other)
        {
            throw new NotImplementedException();
        }
    }
}


text:
import sys
import os
import re

from setuptools import setup, find_packages

here = os.path.dirname(__file__)
package_path = os.path.join(here, 'zengin_code')

version = ''
with open(os.path.join(package_path, '__init__.py'), 'r') as f:
    version = re.compile(
        r".*__version__ = '(.*?)'\n", re.S).match(f.read()).group(1)

version = '{0}.{1}'.format(version, open(os.path.join(
    package_path, 'source-data', 'data', 'updated_at'
), 'r').read().strip())

readme = open(os.path.join(here, 'README.rst')).read()

requires = [
    'six',
]

setup_requires = [
   'pytest-runner',
]

tests_require = [
   'pytest-cov',
   'pytest',
]

classifiers = [
    'Development Status :: 5 - Production/Stable',
    'Intended Audience :: Developers',
    'License :: OSI Approved :: MIT License',
    'Programming Language :: Python :: 2',
    'Programming Language :: Python :: 2.7',
    'Programming Language :: Python :: 3',
    'Programming Language :: Python :: 3.4',
    'Programming Language :: Python :: 3.5',
    'Programming Language :: Python :: 3.6',
    'Programming Language :: Python :: 3.7',
    'Programming Language :: Python :: Implementation :: CPython',
    'Programming Language :: Python :: Implementation :: PyPy',
    'Topic :: Internet :: WWW/HTTP',
    'Topic :: Software Development :: Libraries',
]

setup(
    name='zengin_code',
    version=version,
    description='bank codes and branch codes for Japanese.',
    long_description=readme,
    url='https://github.com/zengin-code/zengin-py',
    author='Zengin Code',
    author_email='zengin-code@zeny.io',
    classifiers=classifiers,
    keywords=['zengin', 'bank', 'japanese'],
    install_requires=requires,
    setup_requires=setup_requires,
    tests_require=tests_require,
    packages=find_packages(exclude=['tests']),
    include_package_data=True,
    package_data={
        'zengin_code': [
            'source-data/data/md5', 'source-data/data/updated_at',
            'source-data/data/*.json', 'source-data/data/branches/*.json'
        ]
    },
    license='MIT',
)


text:
package org.petitparser;

import org.junit.Test;
import org.petitparser.parser.Parser;

import static org.petitparser.Assertions.assertSuccess;
import static org.petitparser.parser.primitive.CharacterParser.of;

/**
 * Various regressions amd tricky examples.
 */
public class RegressionsTest {

  @Test
  public void testFlattenTrim() {
    Parser parser = of('a').flatten().trim();
    assertSuccess(parser, "a", "a");
    assertSuccess(parser, " a ", "a");
    assertSuccess(parser, "  a  ", "a");
  }

  @Test
  public void testTrimFlatten() {
    Parser parser = of('a').trim().flatten();
    assertSuccess(parser, "a", "a");
    assertSuccess(parser, " a ", " a ");
    assertSuccess(parser, "  a  ", "  a  ");
  }
}


text:
package sarama

type (
	AclOperation int

	AclPermissionType int

	AclResourceType int

	AclResourcePatternType int
)

// ref: https://github.com/apache/kafka/blob/trunk/clients/src/main/java/org/apache/kafka/common/acl/AclOperation.java
const (
	AclOperationUnknown AclOperation = iota
	AclOperationAny
	AclOperationAll
	AclOperationRead
	AclOperationWrite
	AclOperationCreate
	AclOperationDelete
	AclOperationAlter
	AclOperationDescribe
	AclOperationClusterAction
	AclOperationDescribeConfigs
	AclOperationAlterConfigs
	AclOperationIdempotentWrite
)

// ref: https://github.com/apache/kafka/blob/trunk/clients/src/main/java/org/apache/kafka/common/acl/AclPermissionType.java
const (
	AclPermissionUnknown AclPermissionType = iota
	AclPermissionAny
	AclPermissionDeny
	AclPermissionAllow
)

// ref: https://github.com/apache/kafka/blob/trunk/clients/src/main/java/org/apache/kafka/common/resource/ResourceType.java
const (
	AclResourceUnknown AclResourceType = iota
	AclResourceAny
	AclResourceTopic
	AclResourceGroup
	AclResourceCluster
	AclResourceTransactionalID
)

// ref: https://github.com/apache/kafka/blob/trunk/clients/src/main/java/org/apache/kafka/common/resource/PatternType.java
const (
	AclPatternUnknown AclResourcePatternType = iota
	AclPatternAny
	AclPatternMatch
	AclPatternLiteral
	AclPatternPrefixed
)


text:
"""Timeout-related output things and filters.
"""
from thingflow.base import OutputThing, DirectOutputThingMixin, FunctionFilter,\
                           FatalError, filtermethod

class Timeout(OutputThing, DirectOutputThingMixin):
    """An output thing that can shedule timeouts for itself. When a
    timeout occurs, an event is sent on the default port.
    The timeout_thunk is called to get the actual event.
    """
    def __init__(self, scheduler, timeout_thunk):
        super().__init__()
        self.scheduler = scheduler
        self.timeout_thunk = timeout_thunk
        self.cancel = None

    def start(self, interval):
        if self.cancel:
            self.cancel()
        self.cancel = self.scheduler.schedule_later_one_time(self, interval)

    def clear(self):
        if self.cancel:
            self.cancel()
            self.cancel = None

    def _observe(self):
        """If this gets called, we hit the timeout
        """
        self.cancel = None
        self._dispatch_next(self.timeout_thunk())

class EventWatcher:
    """Watch the event stream and then produce an event for a timeout
    when asked. This can be subclassed to implement different
    policies.
    """
    def on_next(self, x):
        pass # we get a regular event
    def produce_event_for_timeout(self):
        return None # return the timeout event
    def close(self): # called for on_completed or on_error
        pass

class SupplyEventWhenTimeout(FunctionFilter):
    """This filter sits in a chain and passes incoming events through to
    its output. It also passes all events to the on_next() method of the
    event watcher. If no event arrives on the input after the interval has
    passed since the last event, event_watcher.produce_event_for_timeout()
    is called to get a dummy event, which is passed upstream.
    """
    def __init__(self, previous_in_chain, event_watcher, scheduler, interval):
        self.event_watcher = event_watcher
        self.timeout_thing = \
            Timeout(scheduler, self.event_watcher.produce_event_for_timeout)
        self.interval = interval
        def on_next(self, x):
            self.event_watcher.on_next(x)
            # reset the timer
            self.timeout_thing.start(self.interval)
            self._dispatch_next(x)
        def on_completed(self):
            self.event_watcher.close()
            self.timeout_thing.clear()
            self._dispatch_completed()
        def on_error(self, e):
            self.event_watcher.close()
            self.timeout_thing.clear()
            self._dispatch_error(e)
        super().__init__(previous_in_chain, on_next=on_next,
                         on_completed=on_completed, on_error=on_error,
                         name='supply_event_when_timeout')
        # pass the timeout_thing's timeout events to my on_timeout_next()
        # method<
        self.timeout_thing.connect(self,
                                   port_mapping=('default','timeout'))
        # We start the timeout now - if we don't get a first event from the
        # input within the timeout, we should supply a timeout event. This
        # timeout won't start counting down until we start the scheduler.
        self.timeout_thing.start(interval)

    def on_timeout_next(self, x):
        """This method is connected to the Timeout thing's output. If it
        gets called, the timeout has fired. We need to reschedule the timeout
        as well, so that we continue to produce events in the case of multiple
        consecutive timeouts.
        """
        self.timeout_thing.start(self.interval)
        self._dispatch_next(x)

    def on_timeout_error(self, e):
        """This won't get called, as the Timeout thing does not republish any
        errors it receives.
        """
        raise FatalError("%s.on_timeout_error should not be called" % self)

    def on_timeout_completed(self):
        """This won't get called, as the timeout thing does not propate
        any completions. We just use the primary event stream to figure out when
        things are done and clear any pending timeouts at that time.
        """
        raise FatalError("%s.on_timeout_completed should not be called" % self)

@filtermethod(OutputThing)
def supply_event_when_timeout(this, event_watcher, scheduler, interval):
    return SupplyEventWhenTimeout(this, event_watcher, scheduler, interval)


text:
/* global __dirname */

var path = require('path');

var webpack = require('webpack');
//var CopyWebpackPlugin = require('copy-webpack-plugin');

var dir_js = path.resolve(__dirname, 'js');
var dir_html = path.resolve(__dirname, 'html');
var dir_build = path.resolve(__dirname, 'build');

module.exports = {
   /* entry: [
        'webpack-dev-server/client?http://localhost:8090',
        'webpack/hot/dev-server',
        path.resolve(dir_js, 'index.js')
    ],*/
    entry:{
        citrus:['webpack-dev-server/client?http://localhost:8090',
                'webpack/hot/dev-server',
                path.resolve(dir_js,'index.js')],
        hostedFields:path.resolve(dir_js,'hosted-field-index.js')
    },

    output: {
        path: dir_build,
        //publicPath: '/release',
        publicPath: '/jsv2/release',
        filename: '[name].min.js'
    },
    devServer: {
        //contentBase: dir_build,
        proxy: {
            "*": "http://localhost:3500"
        },
        hot: true,
        port: '8090'
    },
    module: {
        loaders: [
            {
                loader: 'babel-loader',
                test: dir_js
            }
        ]
    },
    plugins: [
        /*// Simply copies the files over
         new CopyWebpackPlugin([
         { from: dir_html } // to: output.path
         ]),
         */
        // Avoid publishing files when compilation fails
        new webpack.NoErrorsPlugin(),
        new webpack.HotModuleReplacementPlugin(),
        /*http://webpack.github.io/docs/shimming-modules.html
         new webpack.ProvidePlugin({
         fetch: "whatwg-fetch",
         "window.fetch": "whatwg-fetch"
         })*/
        //http://mts.io/2015/04/08/webpack-shims-polyfills/
        new webpack.ProvidePlugin({
            'fetch': 'imports?this=>global!exports?global.fetch!whatwg-fetch'
        })
        // new webpack.optimize.UglifyJsPlugin({
        //    sourceMap: true
        // })
    ],
    stats: {
        // Nice colored output
        colors: true
    },
    // Create Sourcemaps for the bundle
    devtool: 'source-map'
};


text:
@class FRPPhotoModel;

@interface FRPCell : UICollectionViewCell

-(void)setPhotoModel:(FRPPhotoModel *)photoModel;

@end


text:
package org.mifos.test.acceptance.savings;

import java.io.IOException;
import java.net.URISyntaxException;
import java.sql.SQLException;

import org.dbunit.DatabaseUnitException;
import org.dbunit.dataset.IDataSet;
import org.joda.time.DateTime;
import org.mifos.framework.util.DbUnitUtilities;
import org.mifos.test.acceptance.framework.MifosPage;
import org.mifos.test.acceptance.framework.UiTestCaseBase;
import org.mifos.test.acceptance.framework.savings.DepositWithdrawalSavingsParameters;
import org.mifos.test.acceptance.framework.testhelpers.SavingsAccountHelper;
import org.mifos.test.acceptance.remote.DateTimeUpdaterRemoteTestingService;
import org.mifos.test.acceptance.remote.InitializeApplicationRemoteTestingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.test.context.ContextConfiguration;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

@ContextConfiguration(locations={"classpath:ui-test-context.xml"})
@Test(sequential=true, groups={"savings","acceptance","ui"})
public class SavingsDepositTest extends UiTestCaseBase {

    private SavingsAccountHelper savingsAccountHelper;
    public static final String SAVINGS_TRXN_DETAIL = "SAVINGS_TRXN_DETAIL";

    @Autowired
    private DriverManagerDataSource dataSource;
    @Autowired
    private DbUnitUtilities dbUnitUtilities;

    @Autowired
    private InitializeApplicationRemoteTestingService initRemote;

    private static final String startDataSet = "acceptance_small_008_dbunit.xml.zip";

    @SuppressWarnings("PMD.SignatureDeclareThrowsException") // one of the dependent methods throws Exception
    @BeforeMethod
    public void setUp() throws Exception {
        super.setUp();

        DateTimeUpdaterRemoteTestingService dateTimeUpdaterRemoteTestingService = new DateTimeUpdaterRemoteTestingService(selenium);
        DateTime targetTime = new DateTime(2009,9,9,8,0,0,0);
        dateTimeUpdaterRemoteTestingService.setDateTime(targetTime);
        savingsAccountHelper = new SavingsAccountHelper(selenium);

    }

    @AfterMethod
    public void logOut() {
        (new MifosPage(selenium)).logout();
    }

    @SuppressWarnings("PMD.SignatureDeclareThrowsException") // one of the dependent methods throws Exception
    public void makeDepositToClientSavingsAccount() throws Exception {
        initData();

        DepositWithdrawalSavingsParameters params = new DepositWithdrawalSavingsParameters();

        params.setTrxnDateMM("09");
        params.setTrxnDateDD("09");
        params.setTrxnDateYYYY("2009");
        params.setAmount("543.2");
        params.setPaymentType(DepositWithdrawalSavingsParameters.CASH);
        params.setTrxnType(DepositWithdrawalSavingsParameters.DEPOSIT);
        params.setReceiptDateDD("09");
        params.setReceiptDateMM("09");
        params.setReceiptDateYYYY("2009");

        savingsAccountHelper.makeDepositOrWithdrawalOnSavingsAccount("000100000000036", params);

        String[] tablesToRetrieve = { "SAVINGS_ACTIVITY_DETAILS", "SAVINGS_ACCOUNT", "SAVINGS_PERFORMANCE", "SAVINGS_TRXN_DETAIL" };
        String[] tablesToValidate = { "SAVINGS_ACTIVITY_DETAILS", "SAVINGS_ACCOUNT", "SAVINGS_PERFORMANCE" };

        IDataSet expectedDataSet = dbUnitUtilities.getDataSetFromDataSetDirectoryFile("SavingsDeposit_001_result_dbunit.xml.zip");
        IDataSet databaseDataSet = dbUnitUtilities.getDataSetForTables(dataSource, tablesToRetrieve);
        dbUnitUtilities.verifyTables(tablesToValidate, databaseDataSet, expectedDataSet);

        // verify savings transaction table with sorting
        String[] orderSavingsTrxnByColumns =  new String[]{"deposit_amount"};
        dbUnitUtilities.verifyTableWithSort(orderSavingsTrxnByColumns,SavingsDepositTest.SAVINGS_TRXN_DETAIL, expectedDataSet, databaseDataSet );

    }

    private void initData() throws DatabaseUnitException, SQLException, IOException, URISyntaxException {
        initRemote.dataLoadAndCacheRefresh(dbUnitUtilities, startDataSet, dataSource, selenium);
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
		http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>org.scijava</groupId>
		<artifactId>pom-scijava</artifactId>
		<version>26.0.0</version>
		<relativePath />
	</parent>

	<groupId>PHANTAST</groupId>
	<artifactId>PHANTAST_</artifactId>
	<version>0.3</version>

	<name>Phase Contrast Segmentation Toolbox (PHANTAST)</name>
	<description>The phae contrast segmentation toolbox (PHANTAST) enables high performance segmentation of phase contrast microscopy images</description>
	<url>http://phantast.googlecode.com</url>
	<organization>
		<name>University College London</name>
		<url>http://www.ucl.ac.uk</url>
	</organization>

	<developers>
		<developer>
			<id>nicjac</id>
			<name>Nicolas Jaccard</name>
			<email>nicolas.jaccard@gmail.com</email>
			<url>http://www.nicjac.net</url>
			<organization>University College London</organization>
			<organizationUrl>http://www.ucl.ac.uk</organizationUrl>
			<roles>
				<role>architect</role>
				<role>developer</role>
			</roles>
			<timezone>-6</timezone>
		</developer>
		<developer>
			<id>oburri</id>
			<name>Olivier Burri</name>
			<email>olivier.burri@gmail.com</email>
			<url>https://biop.epfl.ch/INFO_Facility.html</url>
			<organization>Ecole Polytechnique Fédérale de Lausanne</organization>
			<organizationUrl>https://epfl.ch</organizationUrl>
			<roles>
				<role>architect</role>
				<role>developer</role>
			</roles>
			<timezone>+1</timezone>
		</developer>
	</developers>

	<scm>
		<connection>scm:git:git://github.com/nicjac/PHANTAST-FIJI</connection>
		<developerConnection>scm:git:git@github.com:nicjac/PHANTAST-FIJI</developerConnection>
		<tag>HEAD</tag>
		<url>https://github.com/nicjac/PHANTAST-FIJI</url>
	</scm>

	<repositories>
		<repository>
			<id>scijava.public</id>
			<url>https://maven.scijava.org/content/groups/public</url>
		</repository>
	</repositories>

	<dependencies>
		<dependency>
			<groupId>net.imagej</groupId>
			<artifactId>ij</artifactId>
		</dependency>
		<dependency>
			<groupId>sc.fiji</groupId>
			<artifactId>fiji-lib</artifactId>
		</dependency>
		<dependency>
			<groupId>net.imglib2</groupId>
			<artifactId>imglib2</artifactId>
		</dependency>
		<dependency>
			<groupId>net.imglib2</groupId>
			<artifactId>imglib2-ij</artifactId>
		</dependency>
		<dependency>
			<groupId>net.imglib2</groupId>
			<artifactId>imglib2-algorithm</artifactId>
		</dependency>
	</dependencies>

	<properties>
		<enforcer.skip>true</enforcer.skip>
	</properties>
</project>


text:
var Spreadsheet = require('edit-google-spreadsheet');
var MongoClient = require('mongodb').MongoClient;
var prompt      = require('prompt');
var dbSocket    = null;

var GSSync = function (aConfig) {
  this.config = null;

  if (aConfig) {
    this.config = aConfig;

    // Modules
    dbSocket = this.config.dbSocket();
  }
  else {
    console.log('Configuration is not provided. ');
    process.exit();
  }
};

GSSync.prototype.getCollection = function () {
  return this.config.prefix + this.config.mongo.collection.replace(/-/g, '');
};

GSSync.prototype.doSpreadsheet = function () {

  var loginCredential = this.config;
  var spreadsheet = loginCredential.spreadsheet;

  spreadsheet.worksheets.forEach(function (worksheet) {

    Spreadsheet.load({
      debug: loginCredential.debug,
      spreadsheetId: spreadsheet.spreadsheetId ? spreadsheet.spreadsheetId : null,
      spreadsheetName: spreadsheet.spreadsheetName ? spreadsheet.spreadsheetName : null,
      worksheetName: worksheet.worksheetName ? worksheet.worksheetName : null,
      username: loginCredential.username ? loginCredential.username : null,
      password: loginCredential.password ? loginCredential.password : null
    }, function sheetReady(err, spreadsheet) {
      if (err) {
        console.log(err);
        process.exit(1);
      }

      spreadsheet.receive(function (err, rows, info) {
        MongoClient.connect(dbSocket, function (err, db) {
          if (err) {
            console.log(err);
            process.exit(1);
          }

          var collection = db.collection(loginCredential.mongo.collection);
          var batch = collection.initializeUnorderedBulkOp();

          console.log("Preparing to insert collection: " + loginCredential.mongo.collection);

          for (var i in rows) {
            batch.insert(rows[i]);
          }

          batch.execute(function (err, result) {
            console.log('Done. ');
            process.exit();
          });

        });
      });

    });

  });

};

GSSync.prototype.init = function () {
  var self = this;

  if (self.config.username === '' || self.config.password === '') {

    // Ask for input
    var prompt = require('prompt');

    var properties = [
      {
        name: 'username'
      },
      {
        name: 'password',
        hidden: true
      }
    ];

    prompt.start();

    prompt.get(properties, function (err, userInput) {
      self.config.username = userInput.username;
      self.config.password = userInput.password;

      self.doSpreadsheet();
    });
  }
  else {
    self.doSpreadsheet();
  }

};

module.exports = GSSync;


text:
App.ObstacleLocationController = Ember.ObjectController.extend({
	needs: ['environment','experiment'],
	obstacles: function(){
		return this.get('controllers.environment.model.obstacle')
	}.property('controllers.environment.model.obstacle'),
	shapeName: function(){
		if(this.get('model.shape')=='CY'){
			return 'Cylinder';
		}
		else if(this.get('model.shape')=='CU'){
			return 'Cube';
		}
		else if(this.get('model.shape')=='HE'){
			return 'Hexagon';
		}
		else{
			return 'error';
		}
	}.property('model.shape'),
	distanceXId: function(){
		return "obstacleDistanceXSlider" + this.get('model.id');
	}.property('model.id'),
	distanceYId: function(){
		return "obstacleDistanceYSlider" + this.get('model.id');
	}.property('model.id'),
	stiffnessId: function(){
		return "obstacleStiffnessSlider" + this.get('model.id');
	}.property('model.id'),
	updateXDistance : function () {
		var slider = this.get('model.obstacleDistanceXSlider' + this.get('model.id'));
		if (slider) {
			if (slider.getValue() != this.get('model.xCoordFromPlateCentre')) {
				slider.setValue(parseFloat(this.get('model.xCoordFromPlateCentre')));
			}
		}
		var signals = this.get('controllers.experiment.signals');
		if(signals){
			signals.obstacleXChanged.dispatch(this.get('model.xCoordFromPlateCentre'),this.get('model.id'));
		}
	}
	.observes('model.xCoordFromPlateCentre'),
	updateYDistance : function () {
		var slider = this.get('model.obstacleDistanceYSlider' + this.get('model.id'));
		if (slider) {
			if (slider.getValue() != this.get('model.yCoorDFromPlateCentre')) {
				slider.setValue(parseFloat(this.get('model.yCoorDFromPlateCentre')));
			}
		}
		var signals = this.get('controllers.experiment.signals');
		if(signals){
			signals.obstacleYChanged.dispatch(this.get('model.yCoorDFromPlateCentre'),this.get('model.id'));
		}
	}
	.observes('model.yCoorDFromPlateCentre'),
	updateStiffness : function () {
		var slider = this.get('model.obstacleStiffnessSlider' + this.get('model.id'));
		if (slider) {
			if (slider.getValue() != this.get('model.Stiffness')) {
				slider.setValue(parseFloat(this.get('model.Stiffness')));
			}
		}
	}
	.observes('model.Stiffness'),
	isCylinder: function(){
		if(this.get('model.shape')=='CY'){
			return true;
		}
		else{
			return false;
		}
	}.property('model.shape'),
	isCube: function(){
		if(this.get('model.shape')=='CU'){
			return true;
		}
		else{
			return false;
		}
	}.property('model.shape'),
	isHexagon: function(){
		if(this.get('model.shape')=='HE'){
			return true;
		}
		else{
			return false;
		}
	}.property('model.shape'),
	actions: {
		removeObstacle: function(id){
			var experimentController = this.get('controllers.experiment');
			var proxySend = jQuery.proxy(experimentController.send, experimentController);
			proxySend('removeObstacle', id);
		}
	}
});


text:
using System;
using System.IO;
using System.Net;
using System.IO.Ports;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using System.Collections.Concurrent;

namespace ZwaveExplorer
{
	public abstract class Message
	{
		public byte Length = 0;

		public abstract IEnumerable<byte> GetBytes ();

		public static Message Parse(int bytes, ConcurrentQueue<byte> queue)
		{
			var messageBytes = new byte[bytes];
			for (int index = 0; index < bytes; index++) {
				queue.TryDequeue (out messageBytes [index]);
			}

			switch ((Preamble)messageBytes [0]) {
			case Preamble.SOF:
				{
					UInt16 length = messageBytes [1];
					FrameType frameType = (FrameType) messageBytes [2];
					MessageFunction function = (MessageFunction)messageBytes [3];
					//	Home ID ..
					//	Source Node ID
					//	Frame header ..
					//	Length
					//	Destination address ..
					//	Data byte 0-x
					//		..
					//		..
					//	Checksum
					break;
				}
			case Preamble.ACK:
				{
					return new Acknowledge ();
				}
			}

			return null;
		}

		public IEnumerable<byte> GetChecksumBytes()
		{
			var byteEnumerator = this.GetBytes ().GetEnumerator ();;
			byteEnumerator.MoveNext ();

			// skip preamble

			yield return byteEnumerator.Current;

			byte checksum = 0xff;
			while (byteEnumerator.MoveNext ()) {

				var currentByte = byteEnumerator.Current;
				checksum ^= currentByte;
				yield return currentByte;
			}

			yield return checksum;
		}
	}

	public enum FrameType : byte
	{
		Request = 0x00,
		Response = 0x01
	}

	public abstract class SingleCast : Message
	{
	}

	public class Acknowledge : Message
	{
		public override IEnumerable<byte> GetBytes ()
		{
			return new byte[] { (byte) Preamble.ACK };
		}
	}

	public class Discovery : SingleCast
	{
		public Discovery()
		{
			this.Length = 0x03;
		}

		public override IEnumerable<byte> GetBytes ()
		{
			yield return (byte) Preamble.SOF;
			yield return this.Length;
			yield return (byte) FrameType.Request;
			yield return (byte) MessageFunction.DiscoveryNodes;
		}
	}

}


text:
FROM ambroisemaupate/debian:latest
MAINTAINER Ambroise Maupate <ambroise@rezo-zero.com>

RUN apt-key adv --keyserver keyserver.ubuntu.com --recv-keys ABF5BD827BD9BF62 && \
    echo "deb http://nginx.org/packages/mainline/debian/ buster nginx" > /etc/apt/sources.list.d/nginx.list && \
    apt-get update && \
    apt-get install -y -q --no-install-recommends nginx && \
    apt-get clean && \
    echo -n > /var/lib/apt/extended_states && \
    rm -rf /etc/nginx/*.d && \
    mkdir -p /etc/nginx/addon.d /etc/nginx/conf.d /etc/nginx/host.d /etc/nginx/nginx.d && \
    rm -f /var/cache/apt/archives/*.deb /var/cache/apt/archives/partial/*.deb /var/cache/apt/*.bin

ADD config /config
ADD etc /etc
ADD supervisord.conf /etc/supervisor/conf.d/nginx.conf
EXPOSE 80


text:
package pgclient

import (
	"bytes"
	"crypto/rand"
	"crypto/tls"
	"encoding/binary"
	"fmt"
	"io"
	"net"
	"regexp"

	log "github.com/Sirupsen/logrus"
)

const (
	mockUserName     = "mock"
	mockPassword     = "mocketty"
	mockDatabaseName = "turtle"
)

type mockState int

const (
	mockIdle mockState = 1
)

// MockAuth specifies what type of authentication the server supports
type MockAuth int

// Different auth types
const (
	MockTrust MockAuth = 0
	MockClear MockAuth = 1
	MockMD5   MockAuth = 2
)

var insertRE = regexp.MustCompile("insert into mock values \\('([\\w]+)', '([\\w]+)'\\)")

/*
A MockServer is a server that implements a little bit of the Postgres wire
protocol. We can use it for testing of the wire protocol client. In particular,
we can use it to test the myriad of password authentication and TLS options
without having to start and stop a real Postgres server in the test suite.
*/
type MockServer struct {
	listener  net.Listener
	mockTable map[string]string
	authType  MockAuth
	tlsConfig *tls.Config
	forceTLS  bool
}

/*
NewMockServer starts a new server in the current process, listening on the
specified port.
*/
func NewMockServer() *MockServer {
	return &MockServer{
		mockTable: make(map[string]string),
		authType:  MockTrust,
	}
}

/*
SetAuthType sets what kind of password authentication to require
*/
func (m *MockServer) SetAuthType(auth MockAuth) {
	m.authType = auth
}

/*
SetTLSInfo sets the cert and key file and makes it possible for the server
to support TLS.
*/
func (m *MockServer) SetTLSInfo(certFile, keyFile string) error {
	cert, err := tls.LoadX509KeyPair(certFile, keyFile)
	if err != nil {
		return err
	}
	m.tlsConfig = &tls.Config{
		Certificates: []tls.Certificate{cert},
	}
	return nil
}

/*
SetForceTLS sets up the server to reject any non-TLS clients.
*/
func (m *MockServer) SetForceTLS() {
	m.forceTLS = true
}

/*
Start listening for stuff.
*/
func (m *MockServer) Start(port int) (err error) {
	listener, err := net.ListenTCP("tcp", &net.TCPAddr{
		Port: port,
	})

	if err != nil {
		return err
	}

	m.listener = listener
	go m.acceptLoop()
	return nil
}

/*
Address returns the listen address in host:port format.
*/
func (m *MockServer) Address() string {
	return m.listener.Addr().String()
}

/*
Stop stops the server listening for new connections.
*/
func (m *MockServer) Stop() {
	if m.listener != nil {
		m.listener.Close()
	}
}

/*
acceptLoop sits and accepts new connections.
*/
func (m *MockServer) acceptLoop() {
	for {
		conn, err := m.listener.Accept()
		if err != nil {
			return
		}
		go m.connectLoop(conn)
	}
}

/*
connectLoop responds to a new connection by handling the Postgres
authentication and startup protocol.
*/
func (m *MockServer) connectLoop(c net.Conn) {
	defer c.Close()

	startup, err := readMockMessage(c, true)
	if err != nil {
		log.Errorf("Error reading startup message: %s\n", err)
		return
	}

	protoVersion, _ := startup.ReadInt32()

	if protoVersion == sslMagicNumber {
		// SSL startup attempt. Respond with "S" or "N"
		if m.tlsConfig == nil {
			c.Write([]byte{'N'})
		} else {
			// Respond with the appropriate byte and upgrade to TLS
			c.Write([]byte{'S'})
			c = tls.Server(c, m.tlsConfig)
		}

		// Look for a new startup packet now.
		startup, err = readMockMessage(c, true)
		if err != nil {
			// This might happen if TLS handshake failed, which is a valid test case
			return
		}
		protoVersion, _ = startup.ReadInt32()
	} else if m.forceTLS {
		// We will just close any connection that doesn't ask for TLS
		return
	}

	if protoVersion != protocolVersion {
		sendError(c, fmt.Sprintf("Invalid read protocol version %d\n", protoVersion))
		return
	}

	var paramName, paramVal string
	for {
		paramName, _ = startup.ReadString()
		if paramName == "" {
			break
		}
		paramVal, _ = startup.ReadString()

		if paramName == "user" {
			if paramVal != mockUserName {
				sendError(c, fmt.Sprintf("Invalid user name %s", paramVal))
				return
			}
		}
		if paramName == "database" {
			if paramVal != mockDatabaseName {
				sendError(c, fmt.Sprintf("Invalid database name %s\n", paramVal))
				return
			}
		}
	}

	authOK := m.authLoop(c)

	if authOK {
		sendAuthResponse(c, 0)
		sendReady(c)
		m.readLoop(c)
	}
}

/*
authLoop runs the various Postgres authentication options.
*/
func (m *MockServer) authLoop(c net.Conn) bool {
	switch m.authType {
	case MockTrust:
		return true

	case MockClear:
		sendAuthResponse(c, 3)
		return m.readPassword(c, mockPassword)

	case MockMD5:
		salt := make([]byte, 4)
		rand.Read(salt)
		out := NewServerOutputMessage(AuthenticationResponse)
		out.WriteInt32(5)
		out.WriteBytes(salt)
		c.Write(out.Encode())
		return m.readPassword(c, passwordMD5(mockUserName, mockPassword, salt))

	default:
		return false
	}
}

func (m *MockServer) readPassword(c net.Conn, expected string) bool {
	msg, _ := readMockMessage(c, false)
	if msg.ServerType() != PasswordMessage {
		sendError(c, "Expected PasswordMessage")
		return false
	}

	pwd, _ := msg.ReadString()
	if pwd == expected {
		return true
	}
	sendError(c, "Invalid password")
	return false
}

/*
readLoop now reads and parses SQL commands until it's time to shut the
connection down.
*/
func (m *MockServer) readLoop(c net.Conn) {
	state := mockIdle

	for {
		msg, err := readMockMessage(c, false)
		if err != nil {
			return
		}

		switch state {
		case mockIdle:
			m.readIdle(c, msg)
		}
	}
}

func (m *MockServer) readIdle(c net.Conn, msg *InputMessage) {
	switch msg.ServerType() {
	case Query:
		sql, _ := msg.ReadString()
		match := insertRE.FindStringSubmatch(sql)
		if match != nil {
			m.mockTable[match[1]] = match[2]
			out := NewServerOutputMessage(CommandComplete)
			out.WriteString("INSERT 1")
			c.Write(out.Encode())
			sendReady(c)

		} else {
			sendError(c, fmt.Sprintf("Invalid SQL \"%s\"", sql))
			sendReady(c)
		}

	default:
		sendError(c, fmt.Sprintf("Invalid message %s", msg.ServerType()))
		sendReady(c)
	}
}

func readMockMessage(c net.Conn, isStartup bool) (msg *InputMessage, err error) {
	var hdr []byte
	if isStartup {
		hdr = make([]byte, 4)
	} else {
		hdr = make([]byte, 5)
	}

	_, err = io.ReadFull(c, hdr)
	if err != nil {
		return
	}

	hdrBuf := bytes.NewBuffer(hdr)
	var msgType PgOutputType

	if !isStartup {
		var msgTypeVal byte
		msgTypeVal, err = hdrBuf.ReadByte()
		if err != nil {
			return
		}
		msgType = PgOutputType(msgTypeVal)
	}

	var msgLen int32
	err = binary.Read(hdrBuf, networkByteOrder, &msgLen)
	if err != nil {
		return
	}

	if msgLen < 4 {
		err = fmt.Errorf("Invalid message length %d", msgLen)
		return
	}

	bodBuf := make([]byte, msgLen-4)
	_, err = io.ReadFull(c, bodBuf)
	if err != nil {
		return
	}

	msg = NewServerInputMessage(msgType, bodBuf)
	return
}

func sendError(c net.Conn, msg string) {
	out := NewServerOutputMessage(ErrorResponse)
	out.WriteByte('S')
	out.WriteString("FATAL")
	out.WriteByte('M')
	out.WriteString(msg)
	out.WriteByte(0)
	c.Write(out.Encode())
}

func sendAuthResponse(c net.Conn, code int32) {
	out := NewServerOutputMessage(AuthenticationResponse)
	out.WriteInt32(code)
	c.Write(out.Encode())
}

func sendReady(c net.Conn) {
	out := NewServerOutputMessage(ReadyForQuery)
	out.WriteByte('I')
	c.Write(out.Encode())
}


text:
package org.apache.hadoop.hive.llap;

import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.mapred.InputFormat;
import org.apache.hadoop.mapred.InputSplit;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.RecordReader;
import org.apache.hadoop.mapred.Reporter;
import java.io.IOException;

/*
 * Adapts an Arrow batch reader to a row reader
 */
public class LlapArrowRowInputFormat implements InputFormat<NullWritable, Row> {

  private LlapBaseInputFormat baseInputFormat;

  public LlapArrowRowInputFormat(long arrowAllocatorLimit) {
    baseInputFormat = new LlapBaseInputFormat(true, arrowAllocatorLimit);
  }

  @Override
  public InputSplit[] getSplits(JobConf job, int numSplits) throws IOException {
    return baseInputFormat.getSplits(job, numSplits);
  }

  @Override
  public RecordReader<NullWritable, Row> getRecordReader(InputSplit split, JobConf job, Reporter reporter)
      throws IOException {
    LlapInputSplit llapSplit = (LlapInputSplit) split;
    LlapArrowBatchRecordReader reader =
        (LlapArrowBatchRecordReader) baseInputFormat.getRecordReader(llapSplit, job, reporter);
    return new LlapArrowRowRecordReader(job, reader.getSchema(), reader);
  }
}


text:
package com.amazonaws.waiters;

import com.amazonaws.AmazonWebServiceRequest;
import com.amazonaws.annotation.SdkProtectedApi;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;

@SdkProtectedApi
public class WaiterBuilder<Input extends AmazonWebServiceRequest, Output> {

    private SdkFunction<Input, Output> sdkFunction;

    private List<WaiterAcceptor<Output>> acceptors = new ArrayList<WaiterAcceptor<Output>>();

    private PollingStrategy defaultPollingStrategy;

    private ExecutorService executorService;

    public WaiterBuilder<Input, Output> withSdkFunction(SdkFunction<Input, Output> sdkFunction) {
        this.sdkFunction = sdkFunction;
        return this;
    }

    public WaiterBuilder<Input, Output> withAcceptors(WaiterAcceptor<Output>... acceptors) {
        Collections.addAll(this.acceptors, acceptors);
        return this;
    }

    public WaiterBuilder<Input, Output> withDefaultPollingStrategy(PollingStrategy pollingStrategy) {
        this.defaultPollingStrategy = pollingStrategy;
        return this;
    }

    public WaiterBuilder<Input, Output> withExecutorService(ExecutorService executorService) {
        this.executorService = executorService;
        return this;
    }

    public List<WaiterAcceptor<Output>> getAcceptor() {
        return this.acceptors;
    }

    public SdkFunction<Input, Output> getSdkFunction() {
        return this.sdkFunction;
    }

    PollingStrategy getDefaultPollingStrategy() {
        return this.defaultPollingStrategy;
    }

    public ExecutorService getExecutorService() {
        return this.executorService;
    }

    public Waiter<Input> build() {
        return new WaiterImpl<Input, Output>(this);
    }

}


text:
package utils

import play.api.mvc.RequestHeader

/**
  * @author Yaroslav Derman <yaroslav.derman@gmail.com>.
  *         created on 28.01.2017.
  */
object RequestHelper {

  private val HTTP_IP_HEADERS = Seq(
    "X-Real-IP", "X-Forwarded-For", "Proxy-Client-IP", "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR", "WL-Proxy-Client-IP"
  )

  implicit class RichRequest(val r: RequestHeader) extends AnyVal {
    def clientIp: String = {
      val header = HTTP_IP_HEADERS.find(name => r.headers.get(name).exists(h => h.nonEmpty && !h.equalsIgnoreCase("unknown")))

      header match {
        case Some(name) => r.headers(name)
        case None => r.remoteAddress
      }
    }

    def clientAgent: String = r.headers.get("User-Agent").getOrElse("not set")
  }

}


text:
var constants = require('./constants.js');

// candidates can be passed for performance optimization
var getRole = function(el, candidates) {
	if (el.hasAttribute('role')) {
		return el.getAttribute('role');
	}
	for (var role in constants.roles) {
		var selector = (constants.roles[role].selectors || []).join(',');
		if (selector && (!candidates || candidates.includes(role)) && el.matches(selector)) {
			return role;
		}
	}

	if (!candidates ||
			candidates.includes('banner') ||
			candidates.includes('contentinfo')) {
		if (!el.matches(constants.scoped)) {
			if (el.matches('header')) {
				return 'banner';
			}
			if (el.matches('footer')) {
				return 'contentinfo';
			}
		}
	}
};

var hasRole = function(el, roles) {
	var candidates = [].concat.apply([], roles.map(function(role) {
		return (constants.roles[role] || {}).subRoles || [role];
	}));
	var actual = getRole(el, candidates);
	return candidates.includes(actual);
};

var getAttribute = function(el, key) {
	if (constants.attributeStrongMapping.hasOwnProperty(key)) {
		var value = el[constants.attributeStrongMapping[key]];
		if (value) {
			return value;
		}
	}
	if (key === 'readonly' && el.contentEditable) {
		return false;
	} else if (key === 'invalid' && el.checkValidity) {
		return !el.checkValidity();
	} else if (key === 'hidden') {
		// workaround for chromium
		if (el.matches('noscript')) {
			return true;
		}
		if (el.matches('details:not([open]) > :not(summary)')) {
			return true;
		}
		var style = window.getComputedStyle(el);
		if (style.display === 'none' || style.visibility === 'hidden') {
			return true;
		}
	}

	var type = constants.attributes[key];
	var raw = el.getAttribute('aria-' + key);

	if (raw) {
		if (type === 'bool') {
			return raw === 'true';
		} else if (type === 'tristate') {
			return raw === 'true' ? true : raw === 'false' ? false : 'mixed';
		} else if (type === 'bool-undefined') {
			return raw === 'true' ? true : raw === 'false' ? false : undefined;
		} else if (type === 'id-list') {
			return raw.split(/\s+/);
		} else if (type === 'integer') {
			return parseInt(raw, 10);
		} else if (type === 'number') {
			return parseFloat(raw);
		} else if (type === 'token-list') {
			return raw.split(/\s+/);
		} else {
			return raw;
		}
	}

	// TODO
	// autocomplete
	// contextmenu -> aria-haspopup
	// indeterminate -> aria-checked="mixed"
	// list -> aria-controls

	if (key === 'level') {
		for (var i = 1; i <= 6; i++) {
			if (el.tagName.toLowerCase() === 'h' + i) {
				return i;
			}
		}
	} else if (constants.attributeWeakMapping.hasOwnProperty(key)) {
		return el[constants.attributeWeakMapping[key]];
	}

	if (key in constants.attrsWithDefaults) {
		var role = getRole(el);
		var defaults = (constants.roles[role] || {}).defaults;
		if (defaults && defaults.hasOwnProperty(key)) {
			return defaults[key];
		}
	}

	if (type === 'bool' || type === 'tristate') {
		return false;
	}
};

module.exports = {
	getRole: getRole,
	hasRole: hasRole,
	getAttribute: getAttribute,
};


text:
<?php

/**
 * Things that look like symbols
 */
class Modyllic_Token_Symbol extends Modyllic_Token { }


text:
@implementation MDHTTPAPIFactory

+(MDHTTPAPIFactory *)factoryWithAccessToken:(NSString *)anAccessToken
                                    service:(NSString *)aService
{
    MDHTTPAPIFactory *factory = [[MDHTTPAPIFactory alloc] init];
    factory.accessToken = anAccessToken;
    factory.service = aService;

    return factory;
}

-(NSDictionary *)dictionaryWithDictionary:(NSMutableDictionary *)aDictionary
{
    [aDictionary setObject:self.accessToken forKey:@"access_token"];
    [aDictionary setObject:self.service forKey:@"service"];

    return aDictionary;
}

-(NSDictionary *)dictionaryForAccessToken
{
    return [self dictionaryWithDictionary:[NSMutableDictionary dictionary]];
}

-(NSDictionary *)dictionaryForCreateActivity:(MDActivity *)anActivity
{
    NSMutableDictionary *dictionary;
    dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                  anActivity.subject, @"subject",
                  [anActivity.invitation componentsJoinedByString:@","],
                  @"invitation",
                  nil];

    return [self dictionaryWithDictionary:dictionary];
}

-(NSDictionary *)dictionaryForDeleteActivity:(MDActivity *)anActivity
{
    NSMutableDictionary *dictionary;
    dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                  [NSString stringWithFormat:@"%d", anActivity.id], @"activity_id",
                  nil];

    return [self dictionaryWithDictionary:dictionary];
}

-(NSDictionary *)dictionaryForInvite:(MDActivity *)anActivity
                                user:(MDUser *)anUser
{
    NSString *activity_id = [NSString stringWithFormat:@"%d", anActivity.id];
    NSMutableDictionary *dictionary;
    dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                  activity_id, @"activity_id", anUser.username, @"username",
                  anUser.name, @"name", nil];

    return [self dictionaryWithDictionary:dictionary];
}

-(NSDictionary *)dictionaryForUploadAvatar
{
    return [self dictionaryWithDictionary:[NSMutableDictionary dictionary]];
}

-(NSDictionary *)dictionaryForSendMessage:(MDMessage *)aMessage
{
    NSMutableDictionary *dictionary;
    NSString *activity_id;
    activity_id = [NSString stringWithFormat:@"%d", aMessage.activity.id];
    dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                  activity_id, @"activity_id",
                  aMessage.body, @"body", nil];
    return [self dictionaryWithDictionary:dictionary];
}

-(NSDictionary *)dictionaryForSendChat:(MDChat *)aChat
{
    NSMutableDictionary *dictionary;
    NSString *activity_id;
    activity_id = [NSString stringWithFormat:@"%d", aChat.activity.id];
    dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                  aChat.text, @"text",
                  activity_id, @"activity_id", nil];
    return [self dictionaryWithDictionary:dictionary];
}

-(NSDictionary *)dictionaryForMessagesWithActivity:(MDActivity *)anActivity
                                              page:(NSInteger)aPage
{
    NSMutableDictionary *dictionary;
    NSString *activity_id;
    activity_id = [NSString stringWithFormat:@"%d", anActivity.id];
    dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                  activity_id, @"activity_id",
                  [NSString stringWithFormat:@"%d", aPage], @"page", nil];

    return [self dictionaryWithDictionary:dictionary];
}

-(NSDictionary *)dictionaryForChatsWithActivity:(MDActivity *)anActivity
                                           page:(NSInteger)aPage
                                       pageSize:(NSInteger)aPageSize;
{
    NSMutableDictionary *dictionary;
    NSString *activity_id;
    activity_id = [NSString stringWithFormat:@"%d", anActivity.id];
    dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                  activity_id, @"activity_id",
                  [NSString stringWithFormat:@"%d", aPage], @"page",
                  [NSString stringWithFormat:@"%d", aPageSize], @"page_size",
                  nil];

    return [self dictionaryWithDictionary:dictionary];
}

-(NSDictionary *)dictionaryForChatsWithActivity:(MDActivity *)anActivity
                                           page:(NSInteger)aPage
{
    return [self dictionaryForChatsWithActivity:anActivity
                                           page:aPage
                                       pageSize:0];
}

-(NSDictionary *)dictionaryForLogoutWithUser:(MDUser *)user
{
    NSMutableArray *dictionary;
//    dictionary = [NSMutableDictionary diction]
}

@end


text:
package bufanalysis

import (
	"bytes"
	"strconv"
)

type fileAnnotation struct {
	fileInfo    FileInfo
	startLine   int
	startColumn int
	endLine     int
	endColumn   int
	typeString  string
	message     string
}

func newFileAnnotation(
	fileInfo FileInfo,
	startLine int,
	startColumn int,
	endLine int,
	endColumn int,
	typeString string,
	message string,
) *fileAnnotation {
	return &fileAnnotation{
		fileInfo:    fileInfo,
		startLine:   startLine,
		startColumn: startColumn,
		endLine:     endLine,
		endColumn:   endColumn,
		typeString:  typeString,
		message:     message,
	}
}

func (f *fileAnnotation) FileInfo() FileInfo {
	return f.fileInfo
}

func (f *fileAnnotation) StartLine() int {
	return f.startLine
}

func (f *fileAnnotation) StartColumn() int {
	return f.startColumn
}

func (f *fileAnnotation) EndLine() int {
	return f.endLine
}

func (f *fileAnnotation) EndColumn() int {
	return f.endColumn
}

func (f *fileAnnotation) Type() string {
	return f.typeString
}

func (f *fileAnnotation) Message() string {
	return f.message
}

func (f *fileAnnotation) String() string {
	if f == nil {
		return ""
	}
	path := "<input>"
	line := f.startLine
	column := f.startColumn
	message := f.message
	if f.fileInfo != nil {
		path = f.fileInfo.ExternalPath()
	}
	if line == 0 {
		line = 1
	}
	if column == 0 {
		column = 1
	}
	if message == "" {
		message = f.typeString
		// should never happen but just in case
		if message == "" {
			message = "FAILURE"
		}
	}
	buffer := bytes.NewBuffer(nil)
	_, _ = buffer.WriteString(path)
	_, _ = buffer.WriteRune(':')
	_, _ = buffer.WriteString(strconv.Itoa(line))
	_, _ = buffer.WriteRune(':')
	_, _ = buffer.WriteString(strconv.Itoa(column))
	_, _ = buffer.WriteRune(':')
	_, _ = buffer.WriteString(message)
	return buffer.String()
}


text:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { JhiEventManager } from 'ng-jhipster';

import { Groups } from './groups.model';
import { GroupsPopupService } from './groups-popup.service';
import { GroupsService } from './groups.service';

@Component({
    selector: 'jhi-groups-delete-dialog',
    templateUrl: './groups-delete-dialog.component.html'
})
export class GroupsDeleteDialogComponent {

    groups: Groups;

    constructor(
        private groupsService: GroupsService,
        public activeModal: NgbActiveModal,
        private eventManager: JhiEventManager
    ) {
    }

    clear() {
        this.activeModal.dismiss('cancel');
    }

    confirmDelete(id: number) {
        this.groupsService.delete(id).subscribe((response) => {
            this.eventManager.broadcast({
                name: 'groupsListModification',
                content: 'Deleted an groups'
            });
            this.activeModal.dismiss(true);
        });
    }
}

@Component({
    selector: 'jhi-groups-delete-popup',
    template: ''
})
export class GroupsDeletePopupComponent implements OnInit, OnDestroy {

    routeSub: any;

    constructor(
        private route: ActivatedRoute,
        private groupsPopupService: GroupsPopupService
    ) {}

    ngOnInit() {
        this.routeSub = this.route.params.subscribe((params) => {
            this.groupsPopupService
                .open(GroupsDeleteDialogComponent as Component, params['id']);
        });
    }

    ngOnDestroy() {
        this.routeSub.unsubscribe();
    }
}


text:
SHELL = /usr/bin/env bash
OS_NAME = $(shell uname -s)
NUGET_PACKAGE_NAME = nuget.71
BUILD_CONFIGURATION = Debug
BINARIES_PATH = $(shell pwd)/Binaries
TOOLSET_TMP_PATH = $(BINARIES_PATH)/toolset
BOOTSTRAP_PATH = $(BINARIES_PATH)/Bootstrap
BUILD_LOG_PATH =
XUNIT_VERSION = 2.1.0
HOME_DIR = $(shell cd ~ && pwd)

MSBUILD_ADDITIONALARGS := /v:m /fl /fileloggerparameters:Verbosity=normal /p:Configuration=$(BUILD_CONFIGURATION)

ifeq ($(OS_NAME),Linux)
	MSBUILD_ADDITIONALARGS := $(MSBUILD_ADDITIONALARGS) /p:BaseNuGetRuntimeIdentifier=ubuntu.14.04
	ROSLYN_TOOLSET_NAME = roslyn.linux.5
else ifeq ($(OS_NAME),Darwin)
	MSBUILD_ADDITIONALARGS := $(MSBUILD_ADDITIONALARGS) /p:BaseNuGetRuntimeIdentifier=osx.10.10
	ROSLYN_TOOLSET_NAME = roslyn.mac.4
endif

ifneq ($(BUILD_LOG_PATH),)
	MSBUILD_ADDITIONALARGS := $(MSBUILD_ADDITIONALARGS) /fileloggerparameters:LogFile=$(BUILD_LOG_PATH)
endif

ROSLYN_TOOLSET_PATH = $(TOOLSET_TMP_PATH)/$(ROSLYN_TOOLSET_NAME)

ifeq ($(BOOTSTRAP),true)
	MSBUILD_ARGS = $(MSBUILD_ADDITIONALARGS) /p:CscToolPath=$(BOOTSTRAP_PATH) /p:CscToolExe=csc /p:VbcToolPath=$(BOOTSTRAP_PATH) /p:VbcToolExe=vbc
else
	MSBUILD_ARGS = $(MSBUILD_ADDITIONALARGS) /p:CscToolExe=csc /p:VbcToolExe=vbc
endif

MSBUILD_CMD = $(ROSLYN_TOOLSET_PATH)/corerun $(ROSLYN_TOOLSET_PATH)/MSBuild.exe $(MSBUILD_ARGS)

all: toolset
	export ReferenceAssemblyRoot=$(ROSLYN_TOOLSET_PATH)/reference-assemblies/Framework ; \
	export HOME=$(HOME_DIR) ; \
	$(MSBUILD_CMD) CrossPlatform.sln

bootstrap: toolset
	export ReferenceAssemblyRoot=$(ROSLYN_TOOLSET_PATH)/reference-assemblies/Framework ; \
	export HOME=$(HOME_DIR) ; \
	$(MSBUILD_CMD) src/Compilers/CSharp/CscCore/CscCore.csproj && \
	$(MSBUILD_CMD) src/Compilers/VisualBasic/VbcCore/VbcCore.csproj && \
	mkdir -p $(BOOTSTRAP_PATH) && \
	cp -f Binaries/$(BUILD_CONFIGURATION)/csccore/* $(BOOTSTRAP_PATH) && \
	cp -f Binaries/$(BUILD_CONFIGURATION)/vbccore/* $(BOOTSTRAP_PATH) && \
	build/scripts/crossgen.sh $(BOOTSTRAP_PATH) && \
	rm -rf Binaries/$(BUILD_CONFIGURATION)

test:
	build/scripts/tests.sh $(BUILD_CONFIGURATION)

clean:
	@rm -rf Binaries

clean_toolset:
	@rm -rf $(TOOLSET_TMP_PATH)

toolset: $(TOOLSET_TMP_PATH)/$(ROSLYN_TOOLSET_NAME) $(TOOLSET_TMP_PATH)/$(NUGET_PACKAGE_NAME).zip

$(TOOLSET_TMP_PATH)/$(ROSLYN_TOOLSET_NAME): | $(TOOLSET_TMP_PATH)
	@pushd $(TOOLSET_TMP_PATH) ; \
	curl -O https://dotnetci.blob.core.windows.net/roslyn/$(ROSLYN_TOOLSET_NAME).tar.bz2 && \
	tar -jxf $(ROSLYN_TOOLSET_NAME).tar.bz2 && \
	chmod +x $(ROSLYN_TOOLSET_NAME)/corerun

$(TOOLSET_TMP_PATH)/$(NUGET_PACKAGE_NAME).zip: | $(TOOLSET_TMP_PATH)
	@pushd $(TOOLSET_TMP_PATH) && \
	curl -O https://dotnetci.blob.core.windows.net/roslyn/$(NUGET_PACKAGE_NAME).zip && \
	unzip -uoq $(NUGET_PACKAGE_NAME).zip -d ~/

$(TOOLSET_TMP_PATH):
	mkdir -p $(TOOLSET_TMP_PATH)


text:
<?php

return [
    'spiffy.assetic.assetic-service' => 'Spiffy\AsseticPackage\AsseticServiceFactory',

    // plugins
    'spiffy.assetic.plugin.twig-loader-plugin' => [
        'Spiffy\Assetic\Plugin\TwigLoaderPlugin',
        ['@twig.environment', '$assetic[cache_dir]']
    ],
    'spiffy.assetic.plugin.asset-loader-plugin' => [
        'Spiffy\Assetic\Plugin\AssetLoaderPlugin',
        ['$assetic[assets]']
    ],
    'spiffy.assetic.plugin.directory-loader-plugin' => [
        'Spiffy\Assetic\Plugin\DirectoryLoaderPlugin',
        ['$assetic[directories]', '$assetic[cache_dir]']
    ],
    'spiffy.assetic-package.plugin.filter-loader-plugin' => 'Spiffy\AsseticPackage\Plugin\FilterLoaderPluginFactory',
    'spiffy.assetic-package.plugin.resolve-alias-plugin' => [
        'Spiffy\AsseticPackage\Plugin\ResolveAliasPlugin',
        ['@PackageManager']
    ]
];


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace SampleProject
{
    using SunokoLibrary.Windows.Controls;

    /// <summary>
    /// MainWindow.xaml の相互作用ロジック
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1() { InitializeComponent(); }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var test = bay;
        }
    }
}


text:
<?php

class Lisphp_Runtime_Predicate_NotEqual
    extends Lisphp_Runtime_ComparingPredicate {
    protected $logicalOr = true;

    protected function compare($a, $b)
    {
        return $a != $b;
    }
}


text:
/**
 * Created by User on 25.04.2016.
 */

function ToWork(patient_id)
{
    $("#f_patient_id").val(patient_id);
    $('#ModalToWork').modal('show');
}

$(document).ready(function() {

    $('.hasDatepicker2').datetimepicker({
        format:'Y-m-d',
        lang:'ru',
        timepicker:false,
        closeOnDateSelect:true,
    });

    $("#search-button").click(function () {

        console.info('earch');

       var ff = $('#search_form_1').serializeArray();

        $.get(
            "/ajax/search_new",
            ff,
            function (data) {
                $('#patients_table').bootstrapTable('load', data);
            }, "json"
        ); //$.get  END*/
    });

});

function LoadSearchXML()
{
    console.info("load");
    var ff = $('#search_form_1').serializeArray();
    $('#ModalLoadXML').modal('show');

}


text:
package com.wootric.androidsdk.views.support;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import androidx.fragment.app.DialogFragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.wootric.androidsdk.OfflineDataHandler;
import com.wootric.androidsdk.R;
import com.wootric.androidsdk.Wootric;
import com.wootric.androidsdk.WootricSurveyCallback;
import com.wootric.androidsdk.network.WootricRemoteClient;
import com.wootric.androidsdk.objects.EndUser;
import com.wootric.androidsdk.objects.Settings;
import com.wootric.androidsdk.objects.User;
import com.wootric.androidsdk.utils.PreferencesUtils;
import com.wootric.androidsdk.utils.SHAUtil;
import com.wootric.androidsdk.utils.ScreenUtils;
import com.wootric.androidsdk.utils.SocialHandler;
import com.wootric.androidsdk.utils.Utils;
import com.wootric.androidsdk.views.OnSurveyFinishedListener;
import com.wootric.androidsdk.views.SurveyLayout;
import com.wootric.androidsdk.views.SurveyLayoutListener;
import com.wootric.androidsdk.views.phone.ThankYouDialogFactory;

import java.lang.ref.WeakReference;
import java.util.Date;
import java.util.HashMap;

/**
 * Created by maciejwitowski on 9/4/15.
 */
public class SurveyFragment extends DialogFragment implements SurveyLayoutListener {
    private static final String ARG_ORIGIN_URL = "com.wootric.androidsdk.arg.origin_url";
    private static final String ARG_END_USER = "com.wootric.androidsdk.arg.end_user";
    private static final String ARG_USER = "com.wootric.androidsdk.arg.user";
    private static final String ARG_SETTINGS = "com.wootric.androidsdk.arg.settings";
    private static final String ARG_RESPONSE_SENT = "com.wootric.androidsdk.arg.response_sent";
    private static final String ARG_ACCESS_TOKEN = "com.wootric.androidsdk.arg.access_token";

    private SurveyLayout mSurveyLayout;
    private LinearLayout mFooter;
    private WootricSurveyCallback mSurveyCallback;
    private OnSurveyFinishedListener mOnSurveyFinishedListener;

    private EndUser mEndUser;
    private User mUser;
    private String mOriginUrl;
    private String mAccessToken;
    private String mUniqueLink;
    private Settings mSettings;
    private LinearLayout mPoweredBy;
    private TextView mBtnOptOut;

    private int mScore = -1;
    private String mText;
    private boolean mResponseSent;
    private boolean mShouldShowSimpleDialog;

    private WootricRemoteClient mWootricApiClient;
    private SocialHandler mSocialHandler;

    private boolean mIsTablet;

    private boolean isResumedOnConfigurationChange;

    private int priority = 0;

    public static SurveyFragment newInstance(EndUser endUser, String originUrl, String accessToken,
                                             Settings settings, User user) {
        SurveyFragment fragment = new SurveyFragment();

        Bundle args = new Bundle();
        args.putParcelable(ARG_END_USER, endUser);
        args.putParcelable(ARG_USER, user);
        args.putString(ARG_ORIGIN_URL, originUrl);
        args.putString(ARG_ACCESS_TOKEN, accessToken);
        args.putParcelable(ARG_SETTINGS, settings);

        fragment.setArguments(args);
        return fragment;
    }

    public void setSurveyCallback(WootricSurveyCallback surveyCallback) {
        mSurveyCallback = surveyCallback;
    }

    public void setOnSurveyFinishedListener(OnSurveyFinishedListener onSurveyFinishedListener) {
        mOnSurveyFinishedListener = onSurveyFinishedListener;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(android.app.DialogFragment.STYLE_NO_TITLE, 0);
        setupState(savedInstanceState);

        mSocialHandler = new SocialHandler(getActivity());
        PreferencesUtils prefUtils = new PreferencesUtils(new WeakReference<Context>(this.getActivity()));
        OfflineDataHandler offlineDataHandler = new OfflineDataHandler(prefUtils);
        mWootricApiClient = new WootricRemoteClient(offlineDataHandler, mUser.getAccountToken());

        mIsTablet = getResources().getBoolean(R.bool.isTablet);

        Date date = new Date();
        mUniqueLink = SHAUtil.buildUniqueLink(mUser.getAccountToken(), mEndUser.getEmail(), (date.getTime() / 1000), SHAUtil.randomString());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.wootric_fragment_survey, container, false);
        mPoweredBy = (LinearLayout) view.findViewById(R.id.wootric_powered_by);

        if (!mIsTablet) {
            getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
        }

        mSurveyLayout = (SurveyLayout) view.findViewById(R.id.wootric_survey_layout);
        mSurveyLayout.setSurveyLayoutListener(this);

        mFooter = (LinearLayout) view.findViewById(R.id.wootric_footer);
        mBtnOptOut = (TextView) view.findViewById(R.id.wootric_btn_opt_out);
        mBtnOptOut.setText(mSettings.getBtnOptOut());

        if (mSettings.isShowOptOut()) {
            mBtnOptOut.setVisibility(View.VISIBLE);
            mBtnOptOut.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    optOut();
                }
            });

            if(!mIsTablet) {
                mPoweredBy.setGravity(Gravity.RIGHT);
            } else {
                TextView mDotSeparator = (TextView) view.findViewById(R.id.footer_dot_separator);
                mDotSeparator.setVisibility(View.VISIBLE);
            }
        }

        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mSurveyLayout.initWithSettings(mSettings, mEndUser.getEmail());
    }

    @Override
    public void onStart() {
        super.onStart();

        if(!mIsTablet)
            measurePhoneDialog();
    }

    private void measurePhoneDialog() {
        final Activity activity = getActivity();
        if (activity == null) return;

        Dialog dialog = getDialog();
        if (dialog == null) return;

        final Window window = dialog.getWindow();
        if (window == null) return;

        final WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(window.getAttributes());

        final int screenHeight = ScreenUtils.getScreenHeight(activity);
        final int screenWidth = ScreenUtils.getScreenWidth(activity);

        final boolean launchedInPortrait = (screenHeight > screenWidth);
        final boolean isPortraitMode = (activity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT);

        if(launchedInPortrait) {
            if(isPortraitMode) {
                lp.height = screenHeight*4/5;
                lp.width = screenWidth;
            } else {
                lp.height = screenWidth*19/20;
                lp.width = screenHeight*4/5;
            }
        } else {
            if(isPortraitMode) {
                lp.height = screenWidth*4/5;
                lp.width = screenHeight;
            } else {
                lp.height = screenHeight;
                lp.width = screenWidth*4/5;
            }
        }

        window.setAttributes(lp);
    }

    private void setupState(Bundle savedInstanceState) {
        Bundle args = getArguments();
        mEndUser = args.getParcelable(ARG_END_USER);
        mUser = args.getParcelable(ARG_USER);
        mOriginUrl = args.getString(ARG_ORIGIN_URL);
        mAccessToken = args.getString(ARG_ACCESS_TOKEN);
        mSettings = args.getParcelable(ARG_SETTINGS);

        if(savedInstanceState != null) {
            mResponseSent = savedInstanceState.getBoolean(ARG_RESPONSE_SENT);
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putBoolean(ARG_RESPONSE_SENT, mResponseSent);
        super.onSaveInstanceState(outState);
    }

    private void createDecline() {
        mWootricApiClient.createDecline(mEndUser.getId(), mSettings.getUserID(), mSettings.getAccountID(), priority, mAccessToken, mOriginUrl, mUniqueLink);
    }

    @Override
    public void onSurveySubmit(int score, String text) {
        mWootricApiClient.createResponse(mEndUser.getId(), mSettings.getUserID(), mSettings.getAccountID(), mAccessToken, mOriginUrl, score, priority, text, mUniqueLink);
        mScore = score;
        mText = text;
        mResponseSent = true;
        priority++;
    }

    @Override
    public void onHideOptOut() {
        if (mSettings.isShowOptOut() && mBtnOptOut != null && !mIsTablet) {
            mPoweredBy.setGravity(Gravity.CENTER);
            mBtnOptOut.setVisibility(View.GONE);
        }
    }

    @Override
    public void onFacebookLikeBtnClick() {
        if (mSocialHandler == null) return;

        String facebookId = mSettings.getFacebookPageId();
        mSocialHandler.goToFacebook(facebookId);

        dismiss();
    }

    @Override
    public void onFacebookBtnClick() {
        if (mSocialHandler == null) return;

        String facebookId = mSettings.getFacebookPageId();
        mSocialHandler.shareOnFacebook(facebookId);

        dismiss();
    }

    @Override
    public void onTwitterBtnClick() {
        if (mSocialHandler == null) return;

        String twitterPage = mSettings.getTwitterPage();
        mSocialHandler.goToTwitter(twitterPage, mSurveyLayout.getFeedback());

        dismiss();
    }

    @Override
    public void onThankYouActionClick() {
        final Uri uri = mSettings.getThankYouLinkUri(mSurveyLayout.getEmail(), mSurveyLayout.getSelectedScore(), mSurveyLayout.getFeedback());
        final Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        final Activity activity = getActivity();

        if (activity != null) {
            activity.startActivity(intent);
        }

        dismiss();
    }

    @Override
    public void dismiss() {
        super.dismiss();

        if(mIsTablet) {
            notifySurveyFinished();
        }
    }

    @Override
    public void onDismissClick() {
        if (!mResponseSent) {
            createDecline();
        }

        dismiss();
    }

    @Override
    public void onShouldShowSimpleDialog() {
        final Activity activity = getActivity();

        if (activity != null) {
            mShouldShowSimpleDialog = true;
            ThankYouDialogFactory.create(activity, mSettings, mSurveyLayout.getSelectedScore(), mText, mSurveyCallback, mOnSurveyFinishedListener).show();
        }

        dismiss();
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mSurveyCallback != null) {
            mSurveyCallback.onSurveyWillHide();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        isResumedOnConfigurationChange = true;

        if (!mShouldShowSimpleDialog) {
            if (mOnSurveyFinishedListener != null) {
                mOnSurveyFinishedListener.onSurveyFinished();
            }
            if (mSurveyCallback != null) {
                HashMap<String, Object> hashMap = new HashMap();
                if (mScore != -1) {
                    hashMap.put("score", mScore);
                }
                hashMap.put("text", mText);
                mSurveyCallback.onSurveyDidHide(hashMap);
            }
        }

    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);

        if(!isResumedOnConfigurationChange) {
            notifySurveyFinished();
        }
    }

    private void notifySurveyFinished() {
        Integer resurvey_days = mResponseSent ? mSettings.getResurveyThrottle() : mSettings.getDeclineResurveyThrottle();
        Wootric.notifySurveyFinished(true, mResponseSent, resurvey_days);
    }

    private void optOut() {
        String tld = Utils.startsWithEU(mUser.getAccountToken()) ? "eu" : "com";
        String optOutUrl = "https://app.wootric." + tld + "/opt_out?token=" + mUser.getAccountToken()
                + "&metric_type=" + mSettings.getSurveyType()
                + "&end_user_id=" + Long.toString(mEndUser.getId())
                + "&end_user_email=" + mEndUser.getEmail()
                + "&unique_link=" + mUniqueLink
                + "&opt_out_token=" + mAccessToken;

        Intent optOut = new Intent(Intent.ACTION_VIEW, Uri.parse(optOutUrl));
        startActivity(optOut);

        dismiss();
    }
}


text:
package mil.nga.giat.geowave.vector.plugin;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

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

import org.geotools.data.DataAccessFactory.Param;
import org.junit.Test;

public class GeoWavePluginConfigTest
{

	@Test
	public void test()
			throws GeoWavePluginException {
		List<Param> params = GeoWavePluginConfig.getPluginParams();
		HashMap<String, Serializable> paramValues = new HashMap<String, Serializable>();
		for (Param param : params) {
			if (param.getName().equals(
					GeoWavePluginConfig.LOCK_MGT_KEY)) {
				List<String> options = (List<String>) param.metadata.get(Param.OPTIONS);
				assertNotNull(options);
				assertTrue(options.size() > 0);
				paramValues.put(
						param.getName(),
						options.get(0));
			}
			else if (!param.getName().equals(GeoWavePluginConfig.AUTH_URL_KEY))
			  paramValues.put(param.getName(), (Serializable)( param.getDefaultValue() == null ? "" :param.getDefaultValue()  ));
		}
		GeoWavePluginConfig config = new GeoWavePluginConfig(
				paramValues);
		assertNotNull(config.getLockingManagementFactory());
		assertNotNull(config.getLockingManagementFactory().createLockingManager(
				config));

	}

}


text:
// ReSharper disable InheritdocConsiderUsage
namespace NExpect.Interfaces
{
    /// <summary>
    /// Provides the ".Contain" grammar extension
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public interface IContain<T> : ICanAddMatcher<T>
    {
        /// <summary>
        /// Prepares for setting an expected count to test for, eg:
        /// At.Least, At.Most
        /// </summary>
        IContainAt<T> At { get; }
    }
}


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/gkebackup/v1/gkebackup.proto

namespace Google\Cloud\GkeBackup\V1;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * Request message for DeleteBackupPlan.
 *
 * Generated from protobuf message google.cloud.gkebackup.v1.DeleteBackupPlanRequest
 */
class DeleteBackupPlanRequest extends \Google\Protobuf\Internal\Message
{
    /**
     * Required. Fully qualified BackupPlan name.
     * Format: projects/*/locations/*/backupPlans/*
     *
     * Generated from protobuf field string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {
     */
    private $name = '';
    /**
     * If provided, this value must match the current value of the
     * target BackupPlan's [etag][google.cloud.gkebackup.v1.BackupPlan.etag] field or the request is
     * rejected.
     *
     * Generated from protobuf field string etag = 2;
     */
    private $etag = '';

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type string $name
     *           Required. Fully qualified BackupPlan name.
     *           Format: projects/*/locations/*/backupPlans/*
     *     @type string $etag
     *           If provided, this value must match the current value of the
     *           target BackupPlan's [etag][google.cloud.gkebackup.v1.BackupPlan.etag] field or the request is
     *           rejected.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Cloud\Gkebackup\V1\Gkebackup::initOnce();
        parent::__construct($data);
    }

    /**
     * Required. Fully qualified BackupPlan name.
     * Format: projects/*/locations/*/backupPlans/*
     *
     * Generated from protobuf field string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Required. Fully qualified BackupPlan name.
     * Format: projects/*/locations/*/backupPlans/*
     *
     * Generated from protobuf field string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {
     * @param string $var
     * @return $this
     */
    public function setName($var)
    {
        GPBUtil::checkString($var, True);
        $this->name = $var;

        return $this;
    }

    /**
     * If provided, this value must match the current value of the
     * target BackupPlan's [etag][google.cloud.gkebackup.v1.BackupPlan.etag] field or the request is
     * rejected.
     *
     * Generated from protobuf field string etag = 2;
     * @return string
     */
    public function getEtag()
    {
        return $this->etag;
    }

    /**
     * If provided, this value must match the current value of the
     * target BackupPlan's [etag][google.cloud.gkebackup.v1.BackupPlan.etag] field or the request is
     * rejected.
     *
     * Generated from protobuf field string etag = 2;
     * @param string $var
     * @return $this
     */
    public function setEtag($var)
    {
        GPBUtil::checkString($var, True);
        $this->etag = $var;

        return $this;
    }

}


text:
<?php
/**
 * Reason
 *
 * PHP version 5
 *
 * @category Class
 * @package  DataExchange\SIFUK20
 * @author   DataExchange team
 * @link     https://developer.dataexchange.education
 */

/**
 * SIF (UK), v.2.0
 *
 * OpenAPI specification for the SIF (UK), v.2.0 data model. Generated by DataExchange (dataexchange.educaton) at 2017-08-13 19:14:57
 *
 * OpenAPI spec version: 1.0.0.20170813191457
 * Contact: support@dataexchange.education
 * Generated by: https://developer.dataexchange.education
 *
 */

/**
 * NOTE: This class is auto generated.
 * https://developer.dataexchange.education
 * Do not edit the class manually.
 */

namespace DataExchange\SIFUK20\Models;

use \ArrayAccess;

/**
 * Reason Class Doc Comment
 *
 * @category    Class
 * @package     DataExchange\SIFUK20
 * @author      DataExchange team
 * @link        https://developer.dataexchange.education
 */
class Reason implements ArrayAccess
{
    const DISCRIMINATOR = null;

    const IS_ARRAY = false;
    const ITEMS = null;

    /**
      * The original name of the model.
      * @var string
      */
    protected static $swaggerModelName = 'Reason';

    /**
      * Array of property to type mappings. Used for (de)serialization
      * @var string[]
      */
    protected static $swaggerTypes = [
        'code' => 'string',
        'type' => 'string',
        'status' => 'string',
        'total' => 'int'
    ];

    /**
      * Array of property to format mappings. Used for (de)serialization
      * @var string[]
      */
    protected static $swaggerFormats = [
        'code' => null,
        'type' => null,
        'status' => null,
        'total' => 'int64'
    ];

    public static function swaggerTypes()
    {
        return self::$swaggerTypes;
    }

    public static function swaggerFormats()
    {
        return self::$swaggerFormats;
    }

    /**
     * Array of attributes where the key is the local name, and the value is the original name
     * @var string[]
     */
    protected static $attributeMap = [
        'code' => 'Code',
        'type' => 'Type',
        'status' => 'Status',
        'total' => 'Total'
    ];

    /**
     * Array of attributes to setter functions (for deserialization of responses)
     * @var string[]
     */
    protected static $setters = [
        'code' => 'setCode',
        'type' => 'setType',
        'status' => 'setStatus',
        'total' => 'setTotal'
    ];

    /**
     * Array of attributes to getter functions (for serialization of requests)
     * @var string[]
     */
    protected static $getters = [
        'code' => 'getCode',
        'type' => 'getType',
        'status' => 'getStatus',
        'total' => 'getTotal'
    ];

    public static function attributeMap()
    {
        return self::$attributeMap;
    }

    public static function setters()
    {
        return self::$setters;
    }

    public static function getters()
    {
        return self::$getters;
    }

    /**
     * Associative array for storing property values
     * @var mixed[]
     */
    protected $container = [];

    /**
     * Constructor
     * @param mixed[] $data Associated array of property values initializing the model
     */
    public function __construct(array $data = null)
    {
        $this->container['code'] = isset($data['code']) ? $data['code'] : null;
        $this->container['type'] = isset($data['type']) ? $data['type'] : null;
        $this->container['status'] = isset($data['status']) ? $data['status'] : null;
        $this->container['total'] = isset($data['total']) ? $data['total'] : null;
    }

    /**
     * show all the invalid properties with reasons.
     *
     * @return array invalid properties with reasons
     */
    public function listInvalidProperties()
    {
        $invalid_properties = [];

        if ($this->container['code'] === null) {
            $invalid_properties[] = "'code' can't be null";
        }
        if ($this->container['type'] === null) {
            $invalid_properties[] = "'type' can't be null";
        }
        if ($this->container['status'] === null) {
            $invalid_properties[] = "'status' can't be null";
        }
        if ($this->container['total'] === null) {
            $invalid_properties[] = "'total' can't be null";
        }
        return $invalid_properties;
    }

    /**
     * validate all the properties in the model
     * return true if all passed
     *
     * @return bool True if all properties are valid
     */
    public function valid()
    {

        if ($this->container['code'] === null) {
            return false;
        }
        if ($this->container['type'] === null) {
            return false;
        }
        if ($this->container['status'] === null) {
            return false;
        }
        if ($this->container['total'] === null) {
            return false;
        }
        return true;
    }

    /**
     * Gets code
     * @return string
     */
    public function getCode()
    {
        return isset($this->container['code']) ? $this->container['code'] : null;
    }

    /**
     * Sets code
     * @param string $code The attendance code.
     * @return $this
     */
    public function setCode($code)
    {
        $this->container['code'] = $code;

        return $this;
    }

    /**
     * Gets type
     * @return string
     */
    public function getType()
    {
        return isset($this->container['type']) ? $this->container['type'] : null;
    }

    /**
     * Sets type
     * @param string $type The attendance code type.
     * @return $this
     */
    public function setType($type)
    {
        $this->container['type'] = $type;

        return $this;
    }

    /**
     * Gets status
     * @return string
     */
    public function getStatus()
    {
        return isset($this->container['status']) ? $this->container['status'] : null;
    }

    /**
     * Sets status
     * @param string $status The authorised status of the attendance code.
     * @return $this
     */
    public function setStatus($status)
    {
        $this->container['status'] = $status;

        return $this;
    }

    /**
     * Gets total
     * @return int
     */
    public function getTotal()
    {
        return isset($this->container['total']) ? $this->container['total'] : null;
    }

    /**
     * Sets total
     * @param int $total The total number of sessions attributed to this reason between StartDate and EndDate for the specified reason.
     * @return $this
     */
    public function setTotal($total)
    {
        $this->container['total'] = $total;

        return $this;
    }
    /**
     * Returns true if offset exists. False otherwise.
     * @param  integer $offset Offset
     * @return boolean
     */
    public function offsetExists($offset)
    {
        return isset($this->container[$offset]);
    }

    /**
     * Gets offset.
     * @param  integer $offset Offset
     * @return mixed
     */
    public function offsetGet($offset)
    {
        return isset($this->container[$offset]) ? $this->container[$offset] : null;
    }

    /**
     * Sets value based on offset.
     * @param  integer $offset Offset
     * @param  mixed   $value  Value to be set
     * @return void
     */
    public function offsetSet($offset, $value)
    {
        if (is_null($offset)) {
            $this->container[] = $value;
        } else {
            $this->container[$offset] = $value;
        }
    }

    /**
     * Unsets offset.
     * @param  integer $offset Offset
     * @return void
     */
    public function offsetUnset($offset)
    {
        unset($this->container[$offset]);
    }

    /**
     * Gets the string presentation of the object in JSON format
     * @return string
     */
    public function toJson()
    {
        if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print
            return json_encode(\DataExchange\SIFUK20\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT);
        }

        return json_encode(\DataExchange\SIFUK20\ObjectSerializer::sanitizeForSerialization($this));
    }

    /**
     * Gets the string presentation of the object in XML format
     * @return string
     */
    public function toXml()
    {
        $dom = new \DOMDocument();

        $node = $dom->importNode($this->toXmlNode(), true);

        $dom->preserveWhiteSpace = false;
        $dom->formatOutput = true;
        $xml = $dom->saveXML($node);

        unset($node);
        unset($dom);

        return $xml;
    }

    /**
     * Gets the string presentation of the object in XML format
     * @return string
     */
    public function toXmlNode()
    {
        $dom = new \DOMDocument();
        $elem = $dom->createElement(self::$swaggerModelName);

        foreach (self::attributeMap() as $key => $property) {
            $value = $this->{$this->getters()[$key]}();

            if (is_null($value)) {
                // Do nothing
                continue;
            }

            if ($property[0] === '@') {
                $elem->setAttribute(substr($property, 1), $value);
            } else {
                if (is_scalar($value)) {
                    $elem->appendChild($dom->createElement($property, $value));
                } elseif ($value instanceof \DateTime) {
                    $format = $this->swaggerFormats()[$key];
                    $str = ($format === 'date') ? $value->format('Y-m-d') : $value->format(\DateTime::ATOM);
                    $elem->appendChild($dom->createElement($property, $str));
                } elseif (is_array($value)) {
                    if (is_scalar($value)) {
                        // TODO
                        /*
                        foreach ($value as $property => $value) {
                            $elem->appendChild($dom->createElement($property, (string) $value));
                        }
                        */
                    } else {
                        // TODO
                        /*
                        foreach ($value as $property => $value) {
                            $elem->appendChild($dom->importNode($value->toXmlNode(), true));
                            // $elem->appendChild($dom->createElement($property, (string) $value));
                        }
                        */
                    }
                } elseif (is_object($value)) {
                    $elem->appendChild($dom->importNode($value->toXmlNode(), true));
                } else {
                    $elem->appendChild($dom->createElement($property, (string) $value));
                }
            }
        }

        if (self::IS_ARRAY) {
            foreach ($this->container as $key => $item) {
                $elem->appendChild($dom->importNode($item->toXmlNode(), true));
            }
        }

        return $elem;
    }

    /**
     * Gets the string presentation of the object
     * @return string
     */
    public function __toString()
    {
        return $this->toXml();
    }
}


text:
layout: post
title: "Enlarge your RSS"
category: analytics
tags: [php,selfoss,Data science]
---

Le spam est un fléau tel que de nombreuses recherches ont été effectuées pour le combattre.
Parmi les découvertes réalisées, les filtres bayésiens figurent en bonne place des plus efficaces.

Les RSS sont une bénédiction (si, si). Google s'en fout, mais pas moi.
Je suis actuellement plus de 330 flux RSS, ce qui fait au-moins-tout-ça de nouveaux articles à consulter quotidiennement.
Je pourrais en suivre davantage, mais je manque de temps pour tout lire.

Il faut donc que je trouve une solution pour effectuer un premier tri.

Il faut bien entendu que mon agrégateur de flux RSS réalise ce tri et me propose les articles susceptibles de m'intéresser en tête.
Les autres sont toujours affichés bien sûr, mais en seconde partie de liste.

Je passe sur les modifications nécessaires au moteur d'affichage, c'est trivial et sans grand intérêt ici.

Le tri, en revanche, est beaucoup plus intéressant: on peut en effet faire un parallèle avec les filtres anti-spam.
Schématiquement cela donnerait:

* SPAM: l'article n'est pas intéressant
* NON SPAM: l'article est intéressant

Reste à l'implémenter...

### L'outil
Mon agrégateur de flux RSS, [SelfOSS](http://selfoss.aditu.de/), est écrit en PHP. La mise à jour des flux est également réalisée via PHP.
Il paraît donc raisonnable de trouver un filtre lui aussi écrit en PHP. C'est le cas de [php-classifier](http://php-classifier.com/).

### L'apprentissage

Une fois l'outil trouvé, il faut lui apprendre à distinguer le bon grain de l'ivraie.
Pour cela, je dispose de la base existante de mon agrégateur, soit:

* 20037 articles lus au total
* 2296 articles lus et marqués ("starred" dans le jargon Selfoss)

J'ai donc marqué un peu plus de 11% des articles lus.
J'ai de plus, réalisé manuellement le travail de tri pour pouvoir tester le filtre.

Parmi les articles dénombrés au dessus, on trouve donc:

* 330 articles non lus
* 133 articles non lus et marqués

J'ai donc marqué un peu plus de 40% des articles non lus (Ceci pourrait me jouer des tours quant à la qualité de détection lors des tests).

### Le test

L'idée est ici de construire un index à partir des articles lus en indiquant la catégorie (marqués ou non marqués).
Ensuite, l'outil classifiera chacun des articles non lus comme "starred" ou "normal", sans savoir s'il a, ou non, été marqué au préalable.

Il sera alors possible de vérifier l'acuité du filtre.

### Utiliser le titre
En se basant sur le titre de l'article, on trouve:

    # time php examples/basic_title.php
    Should be starred - Total: 133
                    not found: 92
                        found: 41
                        error: 69.17%
    Should be normal  - Total: 197
                    not found: 31
                        found: 166
                        error: 15.74%

    real	0m6.735s
    user	0m6.604s
    sys		0m0.084s

Comme on le voit, on obtient un taux d'erreur de détection des articles intéressants de près de 70%.
Le taux d'article "normaux", mais détectés comme intéressant est lui de 15%.

Néanmoins, les filtres bayésiens peuvent être entraînés.
Il est donc envisageable de réduire le taux d'erreur au fil du temps.

70% de non détection des articles intéressants peut paraître beaucoup.
C'est sans compter sur le fait que le corpus est sans doute incomplet.
Je ne sauvegardais pas tous les articles que je jugeais intéressant par exemple.

A priori, on peut se dire que la classification basée sur le titre est un peu limitée.
Il paraît évident qu'utiliser le contenu de l'article est plus pertinent.

### Utiliser le contenu

Testons.En se basant sur le contenu de l'article, on trouve:

    # time php examples/basic_content.php
    Should be starred - Total: 133
                    not found: 133
                        found: 0
                        error: 100%
    Should be normal  - Total: 197
                    not found: 0
                        found: 197
                        error: 0%

    real	1m21.964s
    user	1m19.432s
    sys		0m0.708s

Le script est évidemment plus long, mais ce qui surprend surtout, c'est le taux de détection des articles intéressant: 0%.

#### Conclusion

Quelques pistes de réflexion, qui pourraient expliquer l'échec de l'utilisation du contenu:

* Flux RSS incomplets (merci la presse hein... entre autres)
* Flux RSS d'images/BD. Pas ou très peu de texte, sans doute trop peu.
* Problème de langue (flux RSS en anglais ou en français pour moi)
* Pourcentage d'articles intéressants très différent entre le corpus de test et le corpus d'apprentissage

Il convient également de regarder le détails des scores obtenus.
Il est en effet possible que certains articles soient à la limite du seuil de détection.
Mais, pour cela, il va me falloir quelque chose de plus souple, 'R' par exemple.

À suivre donc...


text:
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Reflection;
using Microsoft.Practices.ServiceLocation;

namespace OpenCube.Nbt.Mapping
{
	internal sealed class ConversionContext
		: IConversionContext
	{
		private readonly IServiceLocator _serviceLocator;
		private readonly MemberInfo _memberInfo;
		private readonly IReadOnlyDictionary<string, object> _nbtDictionary;

		public ConversionContext(IServiceLocator serviceLocator, MemberInfo memberInfo = null, IReadOnlyDictionary<string, object> nbtDictionary = null)
		{
			Contract.Requires<ArgumentNullException>(serviceLocator != null, "serviceLocator");

			_serviceLocator = serviceLocator;
			_memberInfo = memberInfo;
			_nbtDictionary = nbtDictionary;
		}

		/// <summary>
		/// Gets the service locator
		/// </summary>
		public IServiceLocator ServiceLocator
		{
			get { return _serviceLocator; }
		}

		/// <summary>
		/// Gets the member info that provides you with property or class being convert to/from
		/// </summary>
		public MemberInfo MemberInfo
		{
			get { return _memberInfo; }
		}

		/// <summary>
		/// Gets the NBT dictionary holding the source/target NBT key value store.
		/// </summary>
		public IReadOnlyDictionary<string, object> NbtDictionary
		{
			get { return _nbtDictionary; }
		}
	}
}