text:
{-# LANGUAGE TupleSections, OverloadedStrings #-}
module Handler.Home where

import Import

-- This is a handler function for the GET request method on the HomeR
-- resource pattern. All of your resource patterns are defined in
-- config/routes
--
-- The majority of the code you will write in Yesod lives in these handler
-- functions. You can spread them across multiple files if you are so
-- inclined, or create a single monolithic file.
getHomeR :: Handler RepHtml
getHomeR = do
    (formWidget, formEnctype) <- generateFormPost sampleForm
    let submission = Nothing :: Maybe (FileInfo, Text)
        handlerName = "getHomeR" :: Text
    defaultLayout $ do
        aDomId <- lift newIdent
        setTitle "Yesod Masters Project"
        $(widgetFile "homepage")

postHomeR :: Handler RepHtml
postHomeR = do
    ((result, formWidget), formEnctype) <- runFormPost sampleForm
    let handlerName = "postHomeR" :: Text
        submission = case result of
            FormSuccess res -> Just res
            _ -> Nothing

    defaultLayout $ do
        aDomId <- lift newIdent
        setTitle "Yesod Masters Project"
        $(widgetFile "homepage")

sampleForm :: Form (FileInfo, Text)
sampleForm = renderDivs $ (,)
    <$> fileAFormReq "Choose a file"
    <*> areq textField "What's on the file?" Nothing

getContactR :: Handler RepHtml
getContactR = do
    (formWidget, formEnctype) <- generateFormPost sampleForm
    let submission = Nothing :: Maybe (FileInfo, Text)
        handlerName = "getContactR" :: Text
    defaultLayout $ do
        aDomId <- lift newIdent
        setTitle "Contact Me"
        $(widgetFile "contact")

getQuickR :: Handler RepHtml
getQuickR = do
    (formWidget, formEnctype) <- generateFormPost sampleForm
    let submission = Nothing :: Maybe (FileInfo, Text)
        handlerName = "getQuickR" :: Text
    defaultLayout $ do
        aDomId <- lift newIdent
        setTitle "Quick Start"
        $(widgetFile "quick")

getAboutR :: Handler RepHtml
getAboutR = do
    (formWidget, formEnctype) <- generateFormPost sampleForm
    let submission = Nothing :: Maybe (FileInfo, Text)
        handlerName = "getAboutR" :: Text
    defaultLayout $ do
        aDomId <- lift newIdent
        setTitle "About"
        $(widgetFile "about")

getLinksR :: Handler RepHtml
getLinksR = do
    (formWidget, formEnctype) <- generateFormPost sampleForm
    let submission = Nothing :: Maybe (FileInfo, Text)
        handlerName = "getLinksR" :: Text
    defaultLayout $ do
        aDomId <- lift newIdent
        setTitle "Links"
        $(widgetFile "links")

getSpeedtestR :: Handler RepHtml
getSpeedtestR = do
    (formWidget, formEnctype) <- generateFormPost sampleForm
    let submission = Nothing :: Maybe (FileInfo, Text)
        handlerName = "getSpeedtestR" :: Text
    defaultLayout $ do
        aDomId <- lift newIdent
        setTitle "Speed Test"
        $(widgetFile "speedtest")

getDbtestR :: Handler RepHtml
getDbtestR = do
    (formWidget, formEnctype) <- generateFormPost sampleForm
    let submission = Nothing :: Maybe (FileInfo, Text)
        handlerName = "getDbtestR" :: Text
    defaultLayout $ do
        aDomId <- lift newIdent
        setTitle "Database Test"
        $(widgetFile "dbtest")

getLogictestR :: Handler RepHtml
getLogictestR = do
    (formWidget, formEnctype) <- generateFormPost sampleForm
    let submission = Nothing :: Maybe (FileInfo, Text)
        handlerName = "getLogictestR" :: Text
    defaultLayout $ do
        aDomId <- lift newIdent
        setTitle "Logic Test"
        $(widgetFile "logictest")

getAjaxtestR :: Handler RepHtml
getAjaxtestR = do
    (formWidget, formEnctype) <- generateFormPost sampleForm
    let submission = Nothing :: Maybe (FileInfo, Text)
        handlerName = "getAjaxtestR" :: Text
    defaultLayout $ do
        aDomId <- lift newIdent
        setTitle "Ajax Test"
        $(widgetFile "ajaxtest")

getAsynctestR :: Handler RepHtml
getAsynctestR = do
    (formWidget, formEnctype) <- generateFormPost sampleForm
    let submission = Nothing :: Maybe (FileInfo, Text)
        handlerName = "getAsynctestR" :: Text
    defaultLayout $ do
        aDomId <- lift newIdent
        setTitle "Asynchronous Test"
        $(widgetFile "asynctest")

getTutorialR :: Handler RepHtml
getTutorialR = do
    (formWidget, formEnctype) <- generateFormPost sampleForm
    let submission = Nothing :: Maybe (FileInfo, Text)
        handlerName = "getTutorialR" :: Text
    defaultLayout $ do
        aDomId <- lift newIdent
        setTitle "Tutorial"
        $(widgetFile "tutorial")


text:
namespace native
{
	namespace ui
	{
		handle_t App::_handle = nullptr;
		volatile App* App::_instance = nullptr;

		class MenuBar : public Menu
		{
		public:
			MenuBar(Component* component) : Menu(new MenuAdapter(::CreateMenu())), _component(component)
			{
				if (component != App::getInstance())
					throw UserInterfaceException("Only the App component can currently have a MenuBar.");

				::SetMenu(HWND(component->getAdapter()->getHandle()), HMENU(getAdapter()->getHandle()));
			}

			virtual void onHierarchyUpdate() override
			{
				::DrawMenuBar(HWND(_component->getAdapter()->getHandle()));
			}

		private:
			// Instance Variables
			Component* _component;
		};

		App::App() : _menu(nullptr)
		{
			if (Atomic::compareExchange((volatile void*&) _instance, (void*) this, (void*) nullptr) != nullptr)
				throw AppInitializationException("App already exists");
		}

		App::~App()
		{
			delete _menu;

			_instance = nullptr;
		}

        float App::getDisplayScale()
        {
            static float scale;

            if (scale == 0.0f)
            {
				HDC hdc = ::GetDC(NULL);
				scale = float(::GetDeviceCaps(hdc, LOGPIXELSX)) / 96.0f;
				::ReleaseDC(NULL, hdc);
            }

            return scale;
        }

		int App::run()
		{
			setVisible(true);

			while (isVisible() && EventQueue::handleEvent())
				;	// No-op.

			return EventQueue::getExitCode();
		}

		Menu& App::getMenu()
		{
			if (_menu == nullptr)
				_menu = new MenuBar(this);

			return *_menu;
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
package org.deri.iris.rules.safety;

import java.util.ArrayList;
import java.util.List;

import org.deri.iris.RuleUnsafeException;
import org.deri.iris.api.basics.ILiteral;
import org.deri.iris.api.basics.IRule;
import org.deri.iris.api.terms.IVariable;
import org.deri.iris.factory.Factory;
import org.deri.iris.facts.FiniteUniverseFacts;
import org.deri.iris.rules.IRuleSafetyProcessor;
import org.deri.iris.rules.RuleValidator;

/**
 * Uses the trick of augmenting rules to artificially limit variables. If any
 * head variable is found that does not occur in a positive ordinary predicate
 * then a literal is added to the rule body $UNIVERSE$( variable ). This has the
 * effect of binding the variable to the 'universe' of known ground terms.
 */
public class AugmentingRuleSafetyProcessor implements IRuleSafetyProcessor {
    public List<IRule> process(List<IRule> rules) throws RuleUnsafeException {
	List<IRule> processedRules = new ArrayList<IRule>();

	for (IRule rule : rules)
	    processedRules.add(process(rule));

	return processedRules;
    }

    public IRule process(IRule rule) throws RuleUnsafeException {
	RuleValidator validator = new RuleValidator(rule, true, true, false);

	List<IVariable> unlimitedVariables = validator
		.getAllUnlimitedVariables();

	if (unlimitedVariables.size() > 0) {
	    List<ILiteral> body = new ArrayList<ILiteral>();

	    for (ILiteral literal : rule.getBody())
		body.add(literal);

	    for (IVariable variable : unlimitedVariables) {
		ILiteral newLiteral = Factory.BASIC.createLiteral(true,
			FiniteUniverseFacts.UNIVERSE, Factory.BASIC
				.createTuple(variable));
		body.add(newLiteral);
	    }

	    return Factory.BASIC.createRule(rule.getHead(), body);
	} else
	    return rule;
    }
}


text:
import numpy as np
import pandas as pd
import scipy as sp
import sklearn as sk
import sklearn.cross_validation as skcv
import sklearn.ensemble as skens
import sklearn.metrics as skmetric
import sklearn.naive_bayes as sknb
import sklearn.tree as sktree
import matplotlib.pyplot as plt
import pydot_ng as pydot
import sklearn.externals.six as sksix
import IPython.display as ipd
from sklearn.preprocessing import OneHotEncoder

def train(data_fn):
	df = pd.read_csv(data_fn)

	enc = OneHotEncoder()
	enc.fit(df.ix[:,0:5])
	df_transformed = enc.transform(df.ix[:,0:5]).toarray()

	dt_model = sktree.DecisionTreeClassifier( criterion='entropy')

	dt_model.fit(df_transformed, df.ix[:,6])
	return dt_model

def predict(model, x):
	enc = OneHotEncoder()
	enc.fit(x)
	x_transformed = enc.transform(x).toarray()

	return model.predict(x_transformed)


text:
# -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.

import json
import unittest
from datetime import datetime

import numpy

from airflow.hooks.oracle_hook import OracleHook
from airflow.models import Connection
from tests.compat import mock

try:
    import cx_Oracle
except ImportError:
    cx_Oracle = None

@unittest.skipIf(cx_Oracle is None, 'cx_Oracle package not present')
class TestOracleHookConn(unittest.TestCase):

    def setUp(self):
        super().setUp()

        self.connection = Connection(
            login='login',
            password='password',
            host='host',
            port=1521
        )

        self.db_hook = OracleHook()
        self.db_hook.get_connection = mock.Mock()
        self.db_hook.get_connection.return_value = self.connection

    @mock.patch('airflow.hooks.oracle_hook.cx_Oracle.connect')
    def test_get_conn_host(self, mock_connect):
        self.db_hook.get_conn()
        assert mock_connect.call_count == 1
        args, kwargs = mock_connect.call_args
        self.assertEqual(args, ())
        self.assertEqual(kwargs['user'], 'login')
        self.assertEqual(kwargs['password'], 'password')
        self.assertEqual(kwargs['dsn'], 'host')

    @mock.patch('airflow.hooks.oracle_hook.cx_Oracle.connect')
    def test_get_conn_sid(self, mock_connect):
        dsn_sid = {'dsn': 'dsn', 'sid': 'sid'}
        self.connection.extra = json.dumps(dsn_sid)
        self.db_hook.get_conn()
        assert mock_connect.call_count == 1
        args, kwargs = mock_connect.call_args
        self.assertEqual(args, ())
        self.assertEqual(kwargs['dsn'],
                         cx_Oracle.makedsn(dsn_sid['dsn'],
                                           self.connection.port, dsn_sid['sid']))

    @mock.patch('airflow.hooks.oracle_hook.cx_Oracle.connect')
    def test_get_conn_service_name(self, mock_connect):
        dsn_service_name = {'dsn': 'dsn', 'service_name': 'service_name'}
        self.connection.extra = json.dumps(dsn_service_name)
        self.db_hook.get_conn()
        assert mock_connect.call_count == 1
        args, kwargs = mock_connect.call_args
        self.assertEqual(args, ())
        self.assertEqual(kwargs['dsn'], cx_Oracle.makedsn(
            dsn_service_name['dsn'], self.connection.port,
            service_name=dsn_service_name['service_name']))

    @mock.patch('airflow.hooks.oracle_hook.cx_Oracle.connect')
    def test_get_conn_encoding_without_nencoding(self, mock_connect):
        self.connection.extra = json.dumps({'encoding': 'UTF-8'})
        self.db_hook.get_conn()
        assert mock_connect.call_count == 1
        args, kwargs = mock_connect.call_args
        self.assertEqual(args, ())
        self.assertEqual(kwargs['encoding'], 'UTF-8')
        self.assertEqual(kwargs['nencoding'], 'UTF-8')

    @mock.patch('airflow.hooks.oracle_hook.cx_Oracle.connect')
    def test_get_conn_encoding_with_nencoding(self, mock_connect):
        self.connection.extra = json.dumps({'encoding': 'UTF-8', 'nencoding': 'gb2312'})
        self.db_hook.get_conn()
        assert mock_connect.call_count == 1
        args, kwargs = mock_connect.call_args
        self.assertEqual(args, ())
        self.assertEqual(kwargs['encoding'], 'UTF-8')
        self.assertEqual(kwargs['nencoding'], 'gb2312')

    @mock.patch('airflow.hooks.oracle_hook.cx_Oracle.connect')
    def test_get_conn_nencoding(self, mock_connect):
        self.connection.extra = json.dumps({'nencoding': 'UTF-8'})
        self.db_hook.get_conn()
        assert mock_connect.call_count == 1
        args, kwargs = mock_connect.call_args
        self.assertEqual(args, ())
        self.assertNotIn('encoding', kwargs)
        self.assertEqual(kwargs['nencoding'], 'UTF-8')

    @mock.patch('airflow.hooks.oracle_hook.cx_Oracle.connect')
    def test_get_conn_mode(self, mock_connect):
        mode = {
            'sysdba': cx_Oracle.SYSDBA,
            'sysasm': cx_Oracle.SYSASM,
            'sysoper': cx_Oracle.SYSOPER,
            'sysbkp': cx_Oracle.SYSBKP,
            'sysdgd': cx_Oracle.SYSDGD,
            'syskmt': cx_Oracle.SYSKMT,
        }
        first = True
        for m in mode:
            self.connection.extra = json.dumps({'mode': m})
            self.db_hook.get_conn()
            if first:
                assert mock_connect.call_count == 1
                first = False
            args, kwargs = mock_connect.call_args
            self.assertEqual(args, ())
            self.assertEqual(kwargs['mode'], mode.get(m))

    @mock.patch('airflow.hooks.oracle_hook.cx_Oracle.connect')
    def test_get_conn_threaded(self, mock_connect):
        self.connection.extra = json.dumps({'threaded': True})
        self.db_hook.get_conn()
        assert mock_connect.call_count == 1
        args, kwargs = mock_connect.call_args
        self.assertEqual(args, ())
        self.assertEqual(kwargs['threaded'], True)

    @mock.patch('airflow.hooks.oracle_hook.cx_Oracle.connect')
    def test_get_conn_events(self, mock_connect):
        self.connection.extra = json.dumps({'events': True})
        self.db_hook.get_conn()
        assert mock_connect.call_count == 1
        args, kwargs = mock_connect.call_args
        self.assertEqual(args, ())
        self.assertEqual(kwargs['events'], True)

    @mock.patch('airflow.hooks.oracle_hook.cx_Oracle.connect')
    def test_get_conn_purity(self, mock_connect):
        purity = {
            'new': cx_Oracle.ATTR_PURITY_NEW,
            'self': cx_Oracle.ATTR_PURITY_SELF,
            'default': cx_Oracle.ATTR_PURITY_DEFAULT
        }
        first = True
        for p in purity:
            self.connection.extra = json.dumps({'purity': p})
            self.db_hook.get_conn()
            if first:
                assert mock_connect.call_count == 1
                first = False
            args, kwargs = mock_connect.call_args
            self.assertEqual(args, ())
            self.assertEqual(kwargs['purity'], purity.get(p))

@unittest.skipIf(cx_Oracle is None, 'cx_Oracle package not present')
class TestOracleHook(unittest.TestCase):
    def setUp(self):
        super().setUp()

        self.cur = mock.MagicMock()
        self.conn = mock.MagicMock()
        self.conn.cursor.return_value = self.cur
        conn = self.conn

        class UnitTestOracleHook(OracleHook):
            conn_name_attr = 'test_conn_id'

            def get_conn(self):
                return conn

        self.db_hook = UnitTestOracleHook()

    def test_run_without_parameters(self):
        sql = 'SQL'
        self.db_hook.run(sql)
        self.cur.execute.assert_called_once_with(sql)
        assert self.conn.commit.called

    def test_run_with_parameters(self):
        sql = 'SQL'
        param = ('p1', 'p2')
        self.db_hook.run(sql, parameters=param)
        self.cur.execute.assert_called_once_with(sql, param)
        assert self.conn.commit.called

    def test_insert_rows_with_fields(self):
        rows = [("'basestr_with_quote", None, numpy.NAN,
                 numpy.datetime64('2019-01-24T01:02:03'),
                 datetime(2019, 1, 24), 1, 10.24, 'str')]
        target_fields = ['basestring', 'none', 'numpy_nan', 'numpy_datetime64',
                         'datetime', 'int', 'float', 'str']
        self.db_hook.insert_rows('table', rows, target_fields)
        self.cur.execute.assert_called_once_with(
            "INSERT /*+ APPEND */ INTO table "
            "(basestring, none, numpy_nan, numpy_datetime64, datetime, int, float, str) "
            "VALUES ('''basestr_with_quote',NULL,NULL,'2019-01-24T01:02:03',"
            "to_date('2019-01-24 00:00:00','YYYY-MM-DD HH24:MI:SS'),1,10.24,'str')")

    def test_insert_rows_without_fields(self):
        rows = [("'basestr_with_quote", None, numpy.NAN,
                 numpy.datetime64('2019-01-24T01:02:03'),
                 datetime(2019, 1, 24), 1, 10.24, 'str')]
        self.db_hook.insert_rows('table', rows)
        self.cur.execute.assert_called_once_with(
            "INSERT /*+ APPEND */ INTO table "
            " VALUES ('''basestr_with_quote',NULL,NULL,'2019-01-24T01:02:03',"
            "to_date('2019-01-24 00:00:00','YYYY-MM-DD HH24:MI:SS'),1,10.24,'str')")

    def test_bulk_insert_rows_with_fields(self):
        rows = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
        target_fields = ['col1', 'col2', 'col3']
        self.db_hook.bulk_insert_rows('table', rows, target_fields)
        self.cur.prepare.assert_called_once_with(
            "insert into table (col1, col2, col3) values (:1, :2, :3)")
        self.cur.executemany.assert_called_once_with(None, rows)

    def test_bulk_insert_rows_with_commit_every(self):
        rows = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
        target_fields = ['col1', 'col2', 'col3']
        self.db_hook.bulk_insert_rows('table', rows, target_fields, commit_every=2)
        calls = [
            mock.call("insert into table (col1, col2, col3) values (:1, :2, :3)"),
            mock.call("insert into table (col1, col2, col3) values (:1, :2, :3)"),
        ]
        self.cur.prepare.assert_has_calls(calls)
        calls = [
            mock.call(None, rows[:2]),
            mock.call(None, rows[2:]),
        ]
        self.cur.executemany.assert_has_calls(calls, any_order=True)

    def test_bulk_insert_rows_without_fields(self):
        rows = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
        self.db_hook.bulk_insert_rows('table', rows)
        self.cur.prepare.assert_called_once_with(
            "insert into table  values (:1, :2, :3)")
        self.cur.executemany.assert_called_once_with(None, rows)

    def test_bulk_insert_rows_no_rows(self):
        rows = []
        self.assertRaises(ValueError, self.db_hook.bulk_insert_rows, 'table', rows)


text:
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Composing;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Tests.TestHelpers;
using Umbraco.Web.Routing;

namespace Umbraco.Tests.Routing
{
    [TestFixture]
    public class ContentFinderByIdTests : BaseWebTest
    {

        [TestCase("/1046", 1046)]
        [TestCase("/1046.aspx", 1046)]
        public void Lookup_By_Id(string urlAsString, int nodeMatch)
        {
            var umbracoContext = GetUmbracoContext(urlAsString);
            var publishedRouter = CreatePublishedRouter();
            var frequest = publishedRouter.CreateRequest(umbracoContext);
            var lookup = new ContentFinderByIdPath(Factory.GetInstance<IUmbracoSettingsSection>().WebRouting, Logger);

            var result = lookup.TryFindContent(frequest);

            Assert.IsTrue(result);
            Assert.AreEqual(frequest.PublishedContent.Id, nodeMatch);
        }
    }
}


text:
package io.lineage;

import static io.lineage.Assert.notNull;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

public class Population implements Iterable<Chromosome>, Cloneable
{

    /**
     * Generation that this population was generated at.
     */
    int generation;

    /**
     * Fitesst chromosome
     */
    private Chromosome fittest;

    private List<Chromosome> population;

    public Population()
    {
        population = new ArrayList<>();
    }

    public Population(final List<Chromosome> population)
    {
        notNull(population);
        this.population = population;
    }

    public void add(final Chromosome chromosome)
    {
        notNull(chromosome);
        population.add(chromosome);
    }

    public Chromosome get(final int index)
    {
        return population.get(index);
    }

    @Override
    public Iterator<Chromosome> iterator()
    {
        return population.iterator();
    }

    public Chromosome getFittest()
    {
        return fittest;
    }

    public void setFittest(final Chromosome fittest)
    {
        notNull(fittest);
        // System.out.println("Setting fittest : " + fittest);
        // System.out.println("    -- CH " + fittest.hashCode());
        this.fittest = fittest;
    }

    public int size()
    {
        return population.size();
    }

    public void set(final List<Chromosome> population)
    {
        Objects.nonNull(population);
        this.population = population;
    }

    public void addAll(final List<Chromosome> chromosomes)
    {
        Objects.nonNull(chromosomes);
        this.population.addAll(chromosomes);
    }

    public boolean contains(final Chromosome next)
    {
        return this.population.contains(next);
    }

    @Override
    protected Population clone()
    {
        return  new Population(new ArrayList<>(population));
    }

    public void dump(final String msg)
    {
        System.out.println(msg);
        for (final Chromosome c : population)
        {
            System.out.println("  -- " + c);
        }

    }

    public void sort()
    {
        final Comparator<Chromosome> fitnessComparator = GAExecutionContext.currentExecutionContext().getFitnessComparator();
        Collections.sort(population,fitnessComparator);
    }

    public List<Chromosome> getRange(final int fromIndex, final int toIndex)
    {
        return population.subList(fromIndex,toIndex);
    }

    /**
     * Remove elements from given population
     * @param elements
     */
    public void removeAll(final Collection<Chromosome> elements)
    {
        population.removeAll(elements);
    }
}


text:
I am from South Africa, the rainbow nation, we have 12 official languages and 3 capital cities. Ten years ago I left
    South Africa to embark on a new teaching career after having spent 18 years in the IT industry. I was a computer
    programmer working on mainframe computers.

South Africa is a beautiful country and I used to love going hiking in the mountains and forests. I also used to like
    going to the gym and jogging. In 2000 I ran and finished the comrades marathon, a grueling 90 km race. My other
    hobbies are reading, travelling and I also enjoy watching movies, but my great love is teaching, so work is always a
    pleasure for me.

I have been teaching English since 2001. I have taught English in South Africa, Poland, Russia, China, Kazakhstan,
    Azerbaijan and India. I have worked in various different positions, teacher, senior teacher Ados, Dos and Academic
    Director. I have taught all levels and ages. I have also been an IELTS examiner and local tutor for the IHC.

I really enjoy living and working in the former USSR, it has been a dream of mine to visit and work in Yakutsk, ever
    since I first heard of the place.


text:
package Armadillo.Analytics.Optimisation.Base.Operators.LocalSearch;

import Armadillo.Analytics.Optimisation.Base.Operators.SearchDirectionOperator;
import Armadillo.Analytics.Optimisation.Base.Problem.HeuristicProblem;

public abstract class ANearNeigLocalSearch0 extends ALocalSearch
{
    protected int m_intSearchIterations;
    protected SearchDirectionOperator m_searchDirectionOperator;

    public ANearNeigLocalSearch0(
        HeuristicProblem heuristicProblem)
    {
    	super(heuristicProblem);
        m_searchDirectionOperator = new SearchDirectionOperator(
            heuristicProblem);
    }
}


text:
using SOURCE.Domaine;
using System.Linq;

namespace SOURCE.Business.Depots
{
    public partial interface IDepotParametre : IDepot<Parametre>
    {

    }
}


text:
namespace PIXL{ namespace physics{

	enum ColliderType
	{
		STATIC = 0x1,
		DYNAMIC = 0x2
	};

	namespace PIXL{ struct Transform; }
	struct Collider : public Component
	{
	public:
		Collider(const ColliderType& colliderType);
		virtual ~Collider();
		void Init() override;
		void Update(float deltaTime) override;

		void SetPositionToSimUnits(const math::Vector2f ps);
		math::Vector2f GetPositionFromSimUnits();

	protected:
		ColliderType m_colliderType;
		b2World& m_world;
		b2Body* m_body;
		Transform* m_transform;
		math::Vector2f m_simPosition;

		math::Vector2f ToSimValue(const math::Vector2f ps);

	};

} }


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

#include "chrome/updater/win/test/test_executables.h"

#include <memory>

#include "base/base_paths.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/process/launch.h"
#include "base/strings/string_number_conversions.h"
#include "base/synchronization/waitable_event.h"
#include "base/win/win_util.h"
#include "chrome/updater/constants.h"
#include "chrome/updater/win/test/test_inheritable_event.h"
#include "chrome/updater/win/test/test_strings.h"

namespace updater {

// If you add another test executable here, also add it to the data_deps in
// the "test_executables" target of updater/win/test/BUILD.gn.
const base::char16 kTestProcessExecutableName[] = L"updater_test_process.exe";

base::Process LongRunningProcess(base::CommandLine* cmd) {
  base::FilePath exe_dir;
  if (!base::PathService::Get(base::DIR_EXE, &exe_dir)) {
    LOG(ERROR) << "Failed to get the executable path, unable to create always "
                  "running process";
    return base::Process();
  }

  base::FilePath exe_path = exe_dir.Append(updater::kTestProcessExecutableName);
  base::CommandLine command_line(exe_path);

  // This will ensure this new process will run for one minute before dying.
  command_line.AppendSwitchASCII(updater::kTestSleepMinutesSwitch, "1");

  auto init_done_event = updater::CreateInheritableEvent(
      base::WaitableEvent::ResetPolicy::AUTOMATIC,
      base::WaitableEvent::InitialState::NOT_SIGNALED);
  command_line.AppendSwitchNative(
      updater::kInitDoneNotifierSwitch,
      base::NumberToString16(
          base::win::HandleToUint32(init_done_event->handle())));

  if (cmd)
    *cmd = command_line;

  base::LaunchOptions launch_options;
  launch_options.handles_to_inherit.push_back(init_done_event->handle());
  base::Process result = base::LaunchProcess(command_line, launch_options);

  if (!init_done_event->TimedWait(base::TimeDelta::FromSeconds(10))) {
    LOG(ERROR) << "Process did not signal";
    result.Terminate(/*exit_code=*/1, /*wait=*/false);
    return base::Process();
  }

  return result;
}

}  // namespace updater


text:
#pragma once

#include <stdint.h>

namespace watchman {

inline constexpr uint32_t kIoBufSize = 1024 * 1024;
inline constexpr uint32_t kBatchLimit = 16 * 1024;

} // namespace watchman

#define WATCHMAN_IO_BUF_SIZE (::watchman::kIoBufSize)
#define WATCHMAN_BATCH_LIMIT (::watchman::kBatchLimit)


text:
<?php

namespace App\Http\Controllers;

// use Illuminate\Http\Request;

use App\Http\Requests;
use Excel;				//使用excel包
use App\SettingThing;   //使用实物奖项设置表
use App\SettingLink;    //使用链接奖项设置表
use App\SettingCode;   	//使用领取码奖项设置表
use App\Code;   		//使用领取码子表
use App\Category;   	//使用分类奖项设置表
use App\AwardUsers;  	//使用个人信息表
use App\Cuid;           //使用cuid表
use Request;   			//输入类
use DB;  				//数据连接类
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Config;

class SetprizeController extends Controller
{
    //显示设置信息
    public function index(){

    	$rates  =  Category::all()->toArray();
    	$links  =  SettingLink::all()->toArray();
        $codes  =  SettingCode::all()->toArray();
        $things =  SettingThing::all()->toArray();
        // print_r($rates);
        return view('setPrize',['rates'=>$rates,'links' => $links, 'codes' => $codes, 'things' => $things]);
    }
    //设置三大奖项的概率
    public function setcategory(){

    	//链接
    	$lin_rate=Request::input('link_rate')*100;
    	Category::where('type','=','link')->update(['award_rate'=>$lin_rate]);
    	//领取码
    	$code_rate=Request::input('code_rate')*100;
    	Category::where('type','=','code')->update(['award_rate'=>$code_rate]);
    	//实物
    	$thing_rate=Request::input('thing_rate')*100;
    	Category::where('type','=','thing')->update(['award_rate'=>$thing_rate]);
    	//重定向设置视图
    	return redirect('/admin/setPrize');
    }

    //增加链接奖项
    public function addlink(){

    	$new_link=new SettingLink;
    	$new_link->category_id=1;
    	$new_link->prize=Request::input('prize');
    	$new_link->name=Request::input('name');
    	$new_link->prize_url=Request::input('prizeurl');
    	$new_link->weight=Request::input('weight');
    	//上传图片并保存链接
    	$destinationPath = public_path().'/uploads/img';
    	$pic=Request::file('inputImg');
    	$fileName = md5(date('ymdhis')).'.'.$pic->getClientOriginalExtension();
        $file = Request::file('inputImg')->move($destinationPath, $fileName);
        $new_link->url=$fileName;
        $new_link->save();
        return redirect('/admin/setPrize');
    }

    //修改链接奖项
    public function editlink($id){

    	$link=SettingLink::find($id);
    	$link->prize=Request::input('prize');
    	$link->name=Request::input('name');
    	$link->prize_url=Request::input('prize_url');
    	$link->weight=Request::input('weight');
    	$pic= Request::file('inputImg');
    	if(!empty($pic)){
    		$fileName = md5(date('ymdhis')).'.'.$pic->getClientOriginalExtension();
	    	$destinationPath = public_path().'/uploads/img';
	        $file = Request::file('inputImg')->move($destinationPath, $fileName);
	        $link->url=$fileName;
    	}
        $link->save();
        return redirect('/admin/setPrize');
    }
    //删除链接奖项
    public function dellink($id){
    	SettingLink::destroy($id);
    	return redirect('/admin/setPrize');
    }
    //增加领取码奖项
    public function addcode(){

    	$new_code=new SettingCode;
    	$new_code->category_id=2;
    	$new_code->prize=Request::input('prize');
    	$new_code->name=Request::input('name');
    	$new_code->prize_url=Request::input('prize_url');
    	$new_code->weight=Request::input('weight');
    	 //上传图片并保存链接
    	$destinationPath = public_path().'/uploads/img';
    	$pic=Request::file('inputImg');
    	$fileName = md5(date('ymdhis')).'.'.$pic->getClientOriginalExtension();
        $file = Request::file('inputImg')->move($destinationPath, $fileName);
        $new_code->url=$fileName;
        $new_code->save();

        //上传领取码
        $excelpath = Request::file('inputExcel');
   		$excel_data = Excel::load($excelpath, function($reader) {
	    $excel_data = $reader->all();
	    $excel_data = $excel_data->toArray();
	    $pd=$excel_data['0']['0'];
	    if(key($pd)=='领取码')
	    {
	    	return $excel_data;

	     }
	         else
	         {
	        		echo  "格式错误";
	         }
	     })->toArray();
   		foreach ($excel_data['0'] as  $value)
	    {

	        	$new_code_data= new Code;
	        	$new_code_data->code=$value['领取码'];
	        	$new_code_data->status=1;
	        	$new_code_data->cid=$new_code->id;
	        	$new_code_data->save();
	    }

        return redirect('/admin/setPrize');
    }
    //更新领取码奖项
    public function editcode($id){

    	$code=SettingCode::find($id);
    	$code->prize=Request::input('prize');
    	$code->name=Request::input('name');
    	$code->prize_url=Request::input('prize_url');
    	$code->weight=Request::input('weight');
    	$pic= Request::file('inputImg');
    	if(!empty($pic)){
    		$fileName = md5(date('ymdhis')).'.'.$pic->getClientOriginalExtension();
	    	$destinationPath = public_path().'/uploads/img';
	        $file = Request::file('inputImg')->move($destinationPath, $fileName);
	        $code->url=$fileName;
    	}
        $code->save();
        return redirect('/admin/setPrize');
    }
    //删除领取码奖项
    public function delcode($id){

    	SettingCode::destroy($id);
    	return redirect('/admin/setPrize');
    }
    //增加实物奖项
   	public function addthing(){

   		$new_thing=new SettingThing;
   		$new_thing->category_id=3;
    	$new_thing->prize=Request::input('prize');
    	$new_thing->name=Request::input('name');
    	// $new_thing->prizeurl=Request::input('prizeurl');
    	$new_thing->weight=Request::input('weight');
    	$new_thing->amount=Request::input('amount');
    	//上传图片并保存链接
    	$destinationPath = public_path().'/uploads/img';
    	$pic=Request::file('inputImg');
    	$fileName = md5(date('ymdhis')).'.'.$pic->getClientOriginalExtension();
        $file = Request::file('inputImg')->move($destinationPath, $fileName);
        $new_thing->url=$fileName;
        $new_thing->save();
        return redirect('/admin/setPrize');
   	}
   	//更新实物奖项
   	public function editthing($id){

   		$thing=SettingThing::find($id);
   		$thing->prize=Request::input('prize');
    	$thing->name=Request::input('name');
    	// $thing->priz_eurl=Request::input('prize_url');
    	$thing->weight=Request::input('weight');
    	$thing->amount=Request::input('amount');
    	$pic= Request::file('inputImg');
    	if(!empty($pic)){
    		$fileName = md5(date('ymdhis')).'.'.$pic->getClientOriginalExtension();
	    	$destinationPath = public_path().'/uploads/img';
	        $file = Request::file('inputImg')->move($destinationPath, $fileName);
	        $thing->url=$fileName;
    	}
    	$thing->save();
    	return redirect('/admin/setPrize');
   	}
   	//删除实物奖项
   	public function delthing($id){

   		SettingThing::destroy($id);
   		return redirect('/admin/setPrize');
   	}
   	//查询中奖信息
   	public function queryaward(){
   		//查询所有信息并分页
   		$querys = DB::table('award_user')->orderBy('created_at','desc')->Paginate(10);
   		return view('queryPrize')->with('querys',$querys);

   	}
   	//搜索中奖信息
   	public function searchaward(){
   		//搜索关键字查询中奖信息
   		$search=Request::input('search');
        $select=Request::input('optionsRadios');
        if($select=='all')
   		$querys = DB::table('award_user')->where('award_content','like','%'.$search.'%')->orderBy('created_at','desc')->Paginate(99999);
        else
            $querys = DB::table('award_user')->where('award_type','=',$select)->where('award_content','like','%'.$search.'%')->orderBy('created_at','desc')->Paginate(99999);
   		 return view('queryPrize')->with('querys',$querys)->with('search',$search);
   	}
    //清空所有数据
    public function flush(){

        AwardUsers::truncate();
        Cuid::truncate();
        SettingThing::truncate();
        SettingLink::truncate();
        SettingCode::truncate();
        Code::truncate();
        return redirect('/admin/setPrize');
    }
    public function export(){
        $cellData=array();
        $cellData[0]=['中奖奖项','奖品名称','中奖者姓名','中奖者电话','中奖者地址','中奖时间'];

        $Data=AwardUsers::all()->toArray();

        for($i=1;$i<count($Data);$i++)
        {
            $cellData[$i]=[$Data[$i-1]['award_prize'],$Data[$i-1]['award_content'],
                           $Data[$i-1]['award_realname'],$Data[$i-1]['award_phone'],
                           $Data[$i-1]['award_address'],$Data[$i-1]['created_at']];
        }
        Excel::create('实物中奖信息表',function($excel) use ($cellData){
            $excel->sheet('score', function($sheet) use ($cellData){
                $sheet->rows($cellData);
            });
        })->export('xls');
    }
}


text:
package hedgehog

import java.util.concurrent.{ConcurrentHashMap, Executors}

import org.scalatest.{FunSpec, Matchers}

import scala.collection.JavaConversions._
import scala.concurrent.{ExecutionContext, Future}
import scala.util.Random

import java.util.{Map => JavaMap}

class PerformanceSpec extends FunSpec with Matchers {
  describe("Performance") {
    it("on average, should be no more than three times as slow as ConcurrentHashMap putting large values") {
      val concurrentHashMap = new ConcurrentHashMap[Integer, String]
      val hedgehogMap = HedgehogMap.createEphemeralMap[Integer, String]()
      Timer.reset()

      (0 until 500).foreach(i => Timer.time(concurrentHashMap.put(i, "x" * 1024 * 1024)))
      val concurrentPutAverage = Timer.average
      Timer.reset()

      (0 until 500).foreach(i => Timer.time(hedgehogMap.put(i, "x" * 1024 * 1024)))
      val hedgehogPutAverage = Timer.average

      hedgehogPutAverage shouldBe < (concurrentPutAverage * 3.0)
    }

    it("on average, should take no more than 2.5ms to retrieve an item for a given index") {
      val hedgehogMap = HedgehogMap.createEphemeralMap[Integer, String]()
      Timer.reset()
      (0 until 500).foreach(i => hedgehogMap.put(i, "x" * 1024 * 1024))

      (0 until 500).foreach(i => Timer.time(hedgehogMap.get(i)) shouldEqual "x" * 1024 * 1024)

      Timer.average shouldBe < (2.5)
    }

    it("Supports storage of data larger than Max Integer") {
      val hedgehogMap = HedgehogMap.createEphemeralMap[Integer, String]()
      (0 until 2047 + 100).foreach(i => hedgehogMap.put(i, "x" * 1024 * 1024))
      hedgehogMap.size shouldBe 2047 + 100
    }

    it("should be thread safe") {
      implicit val executionContext = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(3))
      val hedgehogMap = HedgehogMap.createEphemeralMap[String, String]()

      val inputTasks: Seq[Future[Unit]] = (0 until 3).map(_ => Future((0 until 100).foreach(_ => putValue(hedgehogMap))))
      while(!inputTasks.forall(_.isCompleted)) Thread.`yield`()
      throwableFromFutures(inputTasks).foreach(t => throw t)

      hedgehogMap.size shouldBe 300

      def verifyAValue(): Unit = {
        val randomKeyAndValue = hedgehogMap.keySet.toList.get(Random.nextInt(hedgehogMap.size))
        hedgehogMap.get(randomKeyAndValue) shouldEqual randomKeyAndValue
      }

      val outputTasks: Seq[Future[Unit]] = (0 until 3).map(_ => Future((0 until 100).foreach(_ => verifyAValue())))
      while(!outputTasks.forall(_.isCompleted)) Thread.`yield`()
      throwableFromFutures(outputTasks).foreach(t => throw t)
    }

    it("should perform concurrent puts comparable to ConcurrentHashMap") {
      val concurrentHashMap = new ConcurrentHashMap[String, String]
      val hedgehogMap = HedgehogMap.createEphemeralMap[String, String]()
      val executor = Executors.newFixedThreadPool(3)
      implicit val executionContext = ExecutionContext.fromExecutor(executor)

      Timer.reset()
      Timer.time {
        val tasks = (0 to 1000).map(_ => Future(putValue(concurrentHashMap)))
        while(!tasks.forall(_.isCompleted)) Thread.`yield`()
      }

      val concurrentHashMapTime = Timer.average

      Timer.reset()
      Timer.time {
        val tasks = (0 to 1000).map(_ => Future(putValue(hedgehogMap)))
        while(!tasks.forall(_.isCompleted)) Thread.`yield`()
      }

      val hedgehogMapTime = Timer.average

      executor.shutdown()
      hedgehogMapTime shouldBe < (concurrentHashMapTime * 3.0)
    }

    it("should perform concurrent puts comparable to a single threaded process") {
      val hedgehogMap1 = HedgehogMap.createEphemeralMap[String, String](concurrencyFactor = 1)
      val hedgehogMap2 = HedgehogMap.createEphemeralMap[String, String](concurrencyFactor = 3)
      val executor = Executors.newFixedThreadPool(3)
      implicit val executionContext = ExecutionContext.fromExecutor(executor)

      Timer.reset()
      Timer.time((0 to 1000).foreach(_ => putValue(hedgehogMap1)))

      val singleThreadTime = Timer.average

      Timer.reset()
      Timer.time {
        val tasks = (0 to 1000).map(_ => Future(putValue(hedgehogMap2)))
        while(!tasks.forall(_.isCompleted)) Thread.`yield`()
      }

      val multiThreadTime = Timer.average
      multiThreadTime shouldBe < (singleThreadTime / 2)
    }
  }

  private def putValue(map: JavaMap[String, String]): Unit = {
    val randomKeyAndValue = Random.nextString(5)
    map.put(randomKeyAndValue, randomKeyAndValue)
  }

  private def throwableFromFutures(futures: Seq[Future[_]]): Option[Throwable] =
    futures
      .flatMap(_.value)
      .filter(_.isFailure)
      .map(_.failed.get)
      .reduceOption[Throwable] { case (f1, f2) => f1.addSuppressed(f2); f1 }
}


text:
package es.upm.fi.dia.oeg.map4rdf.client.action;

import net.customware.gwt.dispatch.shared.Action;
import es.upm.fi.dia.oeg.map4rdf.share.BoundingBox;
import es.upm.fi.dia.oeg.map4rdf.share.GeoResource;

/**
 * @author Alexander De Leon
 */
public class GetGeoResources extends GetGeoResourcesBase implements Action<ListResult<GeoResource>> {

	GetGeoResources() {
		// for serialization
		super();
	}

	public GetGeoResources(BoundingBox boundingBox) {
		super(boundingBox);
	}

}


text:
module VGH
module System

# This class is able to suspend or resume logical volumes. The +lvm2+ package
# needs to be installed for this to work.
#
# Suspending a volume becomes useful if you want for example a consistent
# EC2 snapshot of it. Any I/O that has already been mapped by the device but
# has not yet completed will be flushed. Any further I/O to that device will
# be postponed for as long as the device is suspended.
#
#
# == Usage:
#
#     lvm = System::LVM.new
#     lvm.suspend
#     # run the code that takes the snapshot
#     lvm.resume
#
class LVM

  # @return [String] The dmsetup system command
  def dm_cmd
    @dmcmd ||= '/sbin/dmsetup'
  end

  # Warn message if LVM tools are not installed
  def installed?
    if File.exists?(dm_cmd)
      return true
    else
      message.warn "LVM Tools are not installed"
      return false
    end
  end

  # @return [String] A list of logical volumes present
  def lvs
    @lvs = []
    if ( installed? and System.is_root? )
      lv_list = `#{dm_cmd} ls | /bin/grep -E -v 'swap|root'`
      @lvs.push(lv_list.split[0]) unless lv_list == "No devices found\n"
    else
      message.warn "Listing logical volume needs root privileges!"
    end
    return @lvs
  end

  # The actual suspend action
  def suspend
    for lv_name in lvs
      message.info "Suspending Logical Volume '#{lv_name}'..."
      `#{dm_cmd} suspend #{lv_name}`
    end
  end

  # The actual resume action
  def resume
    for lv_name in lvs
      message.info "Resuming Logical Volume '#{lv_name}'..."
      `#{dm_cmd} resume #{lv_name}`
    end
  end

end # class LVM
end # module System
end # module VGH

require 'vgh/output'
require 'vgh/system'


text:
package offer;

/**
 * @program: Java
 * @description: 单例模式
 * @author: huyida
 * @create: 2019-02-06 17:31
 **/

public class Singleton {
    private static Singleton uniqueInstance;

    private Singleton() {

    }

    public static synchronized Singleton getUniqueInstance() {
        if (uniqueInstance == null) {
            uniqueInstance = new Singleton();
        }
        return uniqueInstance;
    }
}


text:
using Discore.Voice;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Discore.Http
{
    partial class DiscordHttpClient
    {
        /// <summary>
        /// Gets a list of available voice regions.
        /// </summary>
        /// <exception cref="DiscordHttpApiException"></exception>
        public async Task<IReadOnlyList<DiscordVoiceRegion>> ListVoiceRegions()
        {
            DiscordApiData data = await rest.Get("voice/regions", "voice/regions").ConfigureAwait(false);

            DiscordVoiceRegion[] regions = new DiscordVoiceRegion[data.Values.Count];
            for (int i = 0; i < regions.Length; i++)
                regions[i] = new DiscordVoiceRegion(data.Values[i]);

            return regions;
        }

        /// <summary>
        /// Gets a list of all voice regions available to the specified guild.
        /// </summary>
        /// <exception cref="DiscordHttpApiException"></exception>
        public async Task<IReadOnlyList<DiscordVoiceRegion>> GetGuildVoiceRegions(Snowflake guildId)
        {
            DiscordApiData data = await rest.Get($"guilds/{guildId}/regions",
                $"guilds/{guildId}/regions").ConfigureAwait(false);

            DiscordVoiceRegion[] regions = new DiscordVoiceRegion[data.Values.Count];
            for (int i = 0; i < regions.Length; i++)
                regions[i] = new DiscordVoiceRegion(data.Values[i]);

            return regions;
        }
    }
}


text:
<?php

namespace Biz\Course\Accessor;

use Biz\Accessor\AccessorAdapter;
use Biz\Course\Service\MemberService;

class LearnCourseMemberAccessor extends AccessorAdapter
{
    public function access($course)
    {
        $user = $this->getCurrentUser();

        if ($user->isAdmin()) {
            return null;
        }

        if (null === $user || !$user->isLogin()) {
            return $this->buildResult('user.not_login');
        }

        if ($user['locked']) {
            return $this->buildResult('user.locked', array('userId' => $user['id']));
        }

        $member = $this->getMemberService()->getCourseMember($course['id'], $user['id']);

        if (empty($member)) {
            return $this->buildResult('member.not_found');
        }

        if ($member['deadline'] > 0 && $member['deadline'] < time()) {
            return $this->buildResult('member.expired', array('userId' => $user['id']));
        }

        return null;
    }

    /**
     * @return MemberService
     */
    protected function getMemberService()
    {
        return $this->biz->service('Course:MemberService');
    }
}


text:
/**
 * EnableMethodEventInterceptorTest Controller test class
 */
Aria.classDefinition({
    $classpath : 'test.aria.templates.EnableMethodEventInterceptorTestCase',
    $extends : 'aria.jsunit.TestCase',
    $dependencies : ['aria.templates.ModuleCtrlFactory'],
    $constructor : function () {
        this.$TestCase.constructor.call(this);
        this.defaultTestTimeout = 2000;
    },
    $prototype : {

        testAsyncDefaultInterceptor : function () {
            aria.templates.ModuleCtrlFactory.createModuleCtrl({
                classpath : "test.aria.templates.test.SampleModuleCtrl"
            }, {
                fn : this._testAsyncDefaultInterceptorCb,
                scope : this
            });
        },

        _testAsyncDefaultInterceptorCb : function (res) {
            try {
                var mc = res.moduleCtrlPrivate;
                this.assertTrue(mc.__$interceptors != null);
                mc.incrementCount();
                aria.core.Timer.addCallback({
                    fn : this._endTestAsyncDisableInterceptor,
                    scope : this,
                    args : {
                        "mc" : mc,
                        "testName" : "testAsyncDefaultInterceptor"
                    },
                    delay : 16
                });
            } catch (ex) {
                this.handleAsyncTestError(ex);
            }
        },

        testAsyncDisableInterceptor : function () {
            aria.templates.ModuleCtrlFactory.createModuleCtrl({
                classpath : "test.aria.templates.test.DisableMethodEventsModuleCtrl"
            }, {
                fn : this._testAsyncDisableInterceptorCb,
                scope : this
            });
        },

        _testAsyncDisableInterceptorCb : function (res) {
            try {
                var mc = res.moduleCtrlPrivate;
                this.assertTrue(!mc.__$interceptors);
                mc.testMethod();
                aria.core.Timer.addCallback({
                    fn : this._endTestAsyncDisableInterceptor,
                    scope : this,
                    args : {
                        "mc" : mc
                    },
                    delay : 16
                });
            } catch (ex) {
                this.handleAsyncTestError(ex);
            }
        },
        _endTestAsyncDisableInterceptor : function (args) {
            this.assertFalse(args.mc.eventCallBeginRaised);
            this.assertFalse(args.mc.eventCallEndRaised);
            args.mc.$dispose();
            this.notifyTestEnd("testAsyncDisableInterceptor");
        },

        testAsyncEnableInterceptor : function () {
            aria.templates.ModuleCtrlFactory.createModuleCtrl({
                classpath : "test.aria.templates.test.EnableMethodEventsModuleCtrl"
            }, {
                fn : this._testAsyncEnableInterceptorCb,
                scope : this
            });
        },

        _testAsyncEnableInterceptorCb : function (res) {
            try {
                var mc = res.moduleCtrlPrivate;
                this.assertTrue(mc.__$interceptors != null);
                mc.testMethod();
                aria.core.Timer.addCallback({
                    fn : this._endTestAsyncEnableInterceptor,
                    scope : this,
                    args : {
                        "mc" : mc,
                        "testName" : "testAsyncEnableInterceptor"
                    },
                    delay : 16
                });
            } catch (ex) {
                this.handleAsyncTestError(ex);
            }
        },
        _endTestAsyncEnableInterceptor : function (args) {
            this.assertTrue(args.mc.eventCallBeginRaised);
            this.assertTrue(args.mc.eventCallEndRaised);
            args.mc.$dispose();
            this.notifyTestEnd(args.testName);
        }

    }
});


text:
<?php
/**
 * Handles install stuff
 * @author pekkis
 *
 */
class EmCore_Model_Install
{

    /**
     * Installs a new Emerald customer
     *
     * @param Emerald_Common_Application_Customer $customer Customer
     * @param EmCore_Form_Install $form Install form
     */
    public function install(Emerald_Common_Application_Customer $customer, EmCore_Form_Install $form)
    {
        $userModel = new EmCore_Model_User();
        $groupTbl = new EmCore_Model_DbTable_Ugroup();
        $userTbl = new EmCore_Model_DbTable_User();
        $ugTbl = new EmCore_Model_DbTable_UserGroup();
        $folderTbl = new Emerald\Filelib\Backend\ZendDb\FolderTable();

        $db = $groupTbl->getAdapter();

        try {

            $db->beginTransaction();
            $groupTbl->insert(array('name' => 'Anonymous'));

            $groupId = $groupTbl->insert(array('name' => 'Root'));
            $userId = $userTbl->insert(array('email' => $form->email->getValue(), 'passwd' => $userModel->hash($form->email->getValue(), $form->password->getValue()), 'status' => 1));

            $ugTbl->insert(array('user_id' => $userId, 'ugroup_id' => $groupId));

            $customer->setOption('installed', '1');

            $db->commit();

        } catch(Exception $e) {

            $db->rollBack();
            throw $e;
        }

    }

}


text:
require 'rails_helper'

RSpec.describe PrisonVisits::Api do
  subject { described_class.instance }

  # These UUIDs can be found in PVB2/prison_uuid_mappings.yml
  let(:cardiff_prison_id)   { '0614760e-a773-49c0-a29c-35e743e72555' }
  let(:leeds_prison_id)     { '8076d43d-429d-4e19-aac1-178ff9d112d3' }
  let(:leicester_prison_id) { 'bf29bf0f-a046-43d1-911b-59ac58730eff' }
  # Note regarding re-recording VCR cassettes: these tests are date dependent.
  # If you need to re-record the VCR data for any reason, you can follow this
  # approach:
  # * delete and re-record the get_slots cassette
  # * populate bookable_slots below with the first 3 returned slots
  # * delete and re-record all the other cassettes
  let(:bookable_slots) {
    [
      "2016-07-29T13:30/14:30",
      "2016-07-29T14:45/15:45",
      "2016-07-30T09:45/11:15"
    ]
  }

  let(:valid_booking_params) {
    {
      prison_id: cardiff_prison_id,
      prisoner: {
        first_name: "Oscar",
        last_name: "Wilde",
        date_of_birth: Date.new(1980, 12, 31),
        number: "a1234bc"
      },
      visitors: [{
        first_name: "Ada",
        last_name: "Lovelace",
        date_of_birth: Date.new(1970, 11, 30)
      }, {
        first_name: "Charlie",
        last_name: "Chaplin",
        date_of_birth: Date.new(2005, 1, 2)
      }],
      contact_email_address: "ada@test.example.com",
      contact_phone_no: "01154960222",
      slot_options: bookable_slots
    }
  }

  before do
    # Specs use vcr cassettes, no real calls are made
    WebMock.allow_net_connect!

    # Needs to be set for all the requests, otherwise the recorded request's
    # wont match the valid_uuid matcher. This is just a random but valid UUID.
    RequestStore.store[:request_id] = '5cd2ef1a-4b7e-11e7-a919-92ebcb67fe33'
  end

  describe 'request_id' do
    it "sets the 'X-Request-Id' header", vcr: { cassette_name: 'get_prisons' } do
      subject.get_prisons

      expect(WebMock).
        to have_requested(:get, /api/).
        with(headers: { 'X-Request-Id' => RequestStore.store[:request_id] })
    end
  end

  describe 'API localisation' do
    it "uses 'en' locale by default", vcr: { cassette_name: 'get_prisons' } do
      subject.get_prisons

      expect(WebMock).
        to have_requested(:get, /api/).
        with(headers: { 'Accept-Language' => 'en' })
    end

    it 'uses the I18n locale', vcr: { cassette_name: 'get_prisons_cy' } do
      I18n.locale = 'cy'

      subject.get_prisons

      expect(WebMock).
        to have_requested(:get, /api/).
        with(headers: { 'Accept-Language' => 'cy' })
    end
  end

  describe 'get_prisons', vcr: { cassette_name: 'get_prisons' } do
    subject { super().get_prisons }

    it 'returns an array of prisons' do
      expect(subject).to be_kind_of(Array)
      expect(subject.first).to be_kind_of(Prison)
    end

    it 'returns prison names and ids' do
      prison = subject.first
      expect(prison.name).to eq('Askham Grange')
      expect(prison.id.length).to eq(36)
    end
  end

  describe 'get_prison', vcr: { cassette_name: 'get_prison' } do
    subject { super().get_prison(cardiff_prison_id) }

    it { is_expected.to be_kind_of(Prison) }

    it 'returns information about the prison' do
      expect(subject.name).to eq("Cardiff")
      expect(subject.address).to eq("Knox Road\nCardiff")
      expect(subject.prison_finder_url).
        to eq("http://www.justice.gov.uk/contacts/prison-finder/cardiff")
      expect(subject.adult_age).to eq(18)
      expect(subject.max_visitors).to eq(6)
    end
  end

  describe 'validate_prisoner', vcr: { cassette_name: 'validate_prisoner' } do
    subject {
      super().validate_prisoner(
        number: 'A1459AE',
        date_of_birth: Date.parse('1976-06-12')
      )
    }

    it 'returns the (raw) validation response' do
      expect(subject).to eq('valid' => true)
    end
  end

  describe 'validate_visitors', vcr: { cassette_name: 'validate_visitors' } do
    subject {
      super().validate_visitors(
        prison_id: cardiff_prison_id,
        lead_date_of_birth: Date.parse('1976-06-12'),
        dates_of_birth: [Date.parse('1976-06-12')]
      )
    }

    it 'returns the (raw) validation response' do
      expect(subject).to eq('valid' => true)
    end
  end

  describe 'get_slots', vcr: { cassette_name: 'get_slots' } do
    let(:params) {
      {
        prison_id: leicester_prison_id,
        prisoner_number: 'A1410AE',
        prisoner_dob: Date.parse('1960-06-01')
      }
    }

    let(:bookable_slot) do
      '2017-02-15T14:15/16:15'
    end

    subject { super().get_slots(params) }

    it 'returns an array of concrete slots' do
      expect(subject).to be_kind_of(Array)
      expect(subject.first).to be_kind_of(CalendarSlot)
    end

    it 'returns sensible looking concrete slots' do
      expect(subject.first.slot.iso8601).to eq(bookable_slot)
    end
  end

  describe 'request_visit', vcr: { cassette_name: 'request_visit' } do
    subject { super().request_visit(valid_booking_params) }

    it { is_expected.to be_kind_of(Visit) }

    it 'returns the UUID of the visit booking' do
      expect(subject.id.length).to eq(36)
    end

    it 'returns the id of the prison' do
      expect(subject.prison_id).to eq(cardiff_prison_id)
    end

    it 'returns a list of the requested slots' do
      expect(subject.slots.first.iso8601).to eq(bookable_slots.first)
    end

    it 'returns the booking contact email address' do
      expect(subject.contact_email_address).to eq("ada@test.example.com")
    end
  end

  describe 'get_visit', vcr: { cassette_name: 'get_visit' } do
    subject { super().get_visit(visit_id) }

    let(:visit_id) {
      # Create a visit to use in specs
      described_class.instance.request_visit(valid_booking_params).id
    }

    it { is_expected.to be_kind_of(Visit) }

    it 'returns the processing state of the visit booking' do
      expect(subject.processing_state).to eq(:requested)
    end
  end

  describe 'cancel_visit', vcr: { cassette_name: 'cancel_visit' } do
    subject { super().cancel_visit(visit_id) }

    let(:visit_id) {
      # Create a visit to use in specs
      described_class.instance.request_visit(valid_booking_params).id
    }

    it { is_expected.to be_kind_of(Visit) }

    it 'returns the processing state of the visit booking' do
      expect(subject.processing_state).to eq(:withdrawn)
    end
  end

  describe 'create_feedback', vcr: { cassette_name: 'create_feedback' } do
    let(:feedback_attrs) {
      {
        body: 'the feedback',
        prisoner_number: 'A1234BC',
        prisoner_date_of_birth: Date.parse('1999-01-01'),
        prison_id: 'abc123',
        email_address: 'user@example.com',
        referrer: 'referrer',
        user_agent: 'user agent'
      }
    }

    let(:feedback_submission) { FeedbackSubmission.new(feedback_attrs) }

    it 'makes a request to the api' do
      expect(subject.create_feedback(feedback_submission)).to be_nil
      expect(WebMock).to have_requested(:post, %r{\/api\/feedback}).
        with(body: JSON.generate(feedback: feedback_attrs))
    end
  end
end


text:
import {Component, NgModule, ViewChild,ViewContainerRef, ViewEncapsulation,OnInit, NgZone} from '@angular/core';
import {FormBuilder, FormGroup, Validators, FormControl} from '@angular/forms';
import {FORM_DIRECTIVES, REACTIVE_FORM_DIRECTIVES} from "@angular/forms/src/directives";
//import {FORM_DIRECTIVES, REACTIVE_FORM_DIRECTIVES} from '@angular/forms';
import {Routes, RouterModule, Router, ActivatedRoute} from '@angular/router';
import {ModalModule} from "ng2-modal";
import {Headers,Http} from "@angular/http";
import {AppCommonservices} from  '../../services/app.commonservices'
import {CookieService} from 'angular2-cookie/core';

@Component({
    selector: 'my-app',
    //template: '<h1>Welcome to my First Angular 2 App </h1>'
    templateUrl:'app/pages/editbannersize/home.html',
    providers: [AppCommonservices]
    //directives: [FORM_DIRECTIVES, REACTIVE_FORM_DIRECTIVES]
})
export class AppEditbannersize {

    // /@ViewChild(Modal) modal;
    addbannersizeform: FormGroup;
    myModal :ModalModule;
    data:any;
    http:Http;
    items:any;
    getusastates:any;
    serverUrl:any;
    commonservices:AppCommonservices;
    private userInfo:CookieService;
    private router: Router;
    id: number;
    private sub: any;
    bannersizedetails: any;
    text:any;

    constructor(fb: FormBuilder , http:Http ,commonservices: AppCommonservices ,userInfo:CookieService ,router: Router,private route: ActivatedRoute) {

        this.items = commonservices.getItems();
        this.http=http;
        this.router=router;
        this.userInfo=userInfo;
        this.serverUrl = this.items[0].serverUrl;
        this.sub = this.route.params.subscribe(params => {
            this.id = params['id']; // (+) converts string 'id' to a number
            let ids={id:this.id};
            this.http.post(this.serverUrl+'editbannersize',ids)
                .subscribe(data => {
                    console.log(data);
                    this.bannersizedetails=data.json()[0];
                    this.addbannersizeform = fb.group({
                        sizename: [this.bannersizedetails.sizename, Validators.required],
                        _id: [this.bannersizedetails._id, Validators.required],
                        height: [this.bannersizedetails.height, Validators.required],
                        width: [this.bannersizedetails.width, Validators.required],
                    });

                }, error => {
                    console.log("Oooops!");
                });

            // In a real app: dispatch action to load the details here.
        });

        this.addbannersizeform = fb.group({
            sizename: ["", Validators.required],
            height: ["", Validators.required],
            width: ["", Validators.required]
        });

        //this.router.navigate(['/about']);
    }

    submitform(){
        let x:any;
        for(x in this.addbannersizeform.controls){
            this.addbannersizeform.controls[x].markAsTouched();

        }
       // console.log(this.addsharelinkform.dirty);
        this.addbannersizeform.markAsDirty();
        if(this.addbannersizeform.valid){
           let link = this.serverUrl+'updatebannersize';
            var submitdata = this.addbannersizeform.value;
            this.http.post(link,submitdata)
                .subscribe(data => {
                    console.log(344444);
                   // this.data = data.json();
                    //console.log(this.data);
                    //this.router.navigateByUrl('/bannersizelist');
                    this.router.navigateByUrl('/bannersizelist(adminheader:adminheader//adminfooter:adminfooter)');

                }, error => {
                    console.log("Oooops!");
                });

            //this.navCtrl.push(ProfilePage);
        }
    }

}


text:
(function(angular) {
  'use strict';
  angular.module('uiComponents.components')
    .controller('ListadoEntidadController', ListadoEntidadController);

  /** @ngInject */
  function ListadoEntidadController($log, $scope, $timeout, uiGridConstants, TABLEMAPPING, GenericService, i18nService) {
    var conDatos = false;
    var vm = this;
    vm.$onInit = function() {
      vm.selected = {};
      vm.deselectedAll = false; // EXPONER
      i18nService.setCurrentLang('es');
      vm.gridApi = null;
      vm.optionsEntidades = angular.copy(vm.gridOptions);

      vm.metodosInternos = vm.metodos || {}; // por si no envian ningun metodo, inicio el objeto
      vm.metodosInternos.actualizarDatos = actualizarDatos;

      if (vm.entidades === undefined || vm.entidades.length === 0) {
        cargarDatos(vm.path, 100, undefined, vm.config.links);
      } else {
        conDatos = true;
        vm.optionsEntidades.data = vm.entidades;

      }
      setRowListeners();
    };

    function actualizarDatos() {
      cargarDatos(vm.path, 100, undefined, vm.config.links);
    }

    function cargarDatos(url, pageSize, numPage, links) {

      vm.servicio.obtenerDatos(url, links, pageSize, numPage).then(function(entidades) {

        vm.entidades = entidades;
        vm.optionsEntidades.data = entidades;
        vm.optionsEntidades.totalItems = vm.entidades.length;
        checkSelectAll();
        // SI HAY ALGUNA FILA SELECCIONADA VEO CUAL ES, ESTO PARA EL CASO DE QUE LA PAGINACION SEA EXTERNA, HAY
        // QUE RECORDAR CUALES FILAS FUERON SELECCIONADAS
        //if(numPage!==undefined)setSelected(numPage,pageSize);
      });

    }

    function checkSelectAll() {

      if (vm.selectAll) {
        vm.gridApi.grid.modifyRows(vm.optionsEntidades.data);
        vm.gridApi.selection.selectAllRows();
      }
    }

    function setRowListeners() {
      console.log(vm.optionsEntidades);
      vm.optionsEntidades.onRegisterApi = function(gridApi) {
        vm.gridApi = gridApi;

        gridApi.expandable.on.rowExpandedStateChanged($scope, function(row) {

          if (row.isExpanded) {

            row.entity.subGridOptions = angular.copy(vm.optionsEntidades.subGridColumnDefs);
            if(!vm.config.datosSubgrilla){
              vm.servicio.obtenerDatosSubgrilla(row.entity._links[vm.config.subGrilla].href).then(function(subEntity) {

                row.entity.subGridOptions.data = subEntity;

              });
            } else {
              row.entity.subGridOptions.data = vm.servicio.agregarFuncionesSubgrilla(row.entity[vm.config.campoDatosSubgrilla])||[];
            }

          }
        });
        gridApi.pagination.on.paginationChanged($scope, function(numPage, pageSize) {
          //ESTA PARTE CONSULTA POR PAGINA Y POR EL TAMAÑO DE PAGINA, PARA DESPUES DEJO
          // vm.optionsEntidades.pageNumber = numPage;
          // console.log(vm.entidadesSeleccionadas);
          //  vm.optionsEntidades.pageSize = pageSize;
          //  cargarDatos(vm.path,pageSize,numPage-1);

          // getPage();
        });
        gridApi.selection.on.rowSelectionChanged($scope, function(row) {
          vm.entidadesSeleccionadas = gridApi.selection.getSelectedRows();
          if (typeof vm.clickItem !== 'undefined') vm.clickItem({
            $entidad: vm.entidadesSeleccionadas,
            $entidadesSeleccionadas: vm.entidadesSeleccionadas
          });
        });
        gridApi.selection.on.rowSelectionChangedBatch($scope, function(row) {
          vm.entidadesSeleccionadas = gridApi.selection.getSelectedRows();
          if (typeof vm.clickItem !== 'undefined') vm.clickItem({
            $entidad: vm.entidadesSeleccionadas,
            $entidadesSeleccionadas: vm.entidadesSeleccionadas
          });
        });

        // en honor a Pablo Guidici
        if (conDatos) {
          $timeout(function() {
            checkSelectAll();
          }, 150);
        }

      };
    }

    function setSelected(numPage, pageSize) {
      var elementSelected = [];
      var size = (vm.optionsEntidades.data.length <= pageSize * (numPage + 1)) ? vm.optionsEntidades.data.length : pageSize * (numPage + 1);
      for (var index in vm.entidadesSeleccionadas) {
        for (var i = 0; i < size; i++) {
          if (vm.optionsEntidades.data[i].codigoComprobante == vm.entidadesSeleccionadas[index].codigoComprobante) {
            elementSelected.push(vm.optionsEntidades.data[i]);
            vm.gridApi.grid.modifyRows(vm.optionsEntidades.data[i])
            vm.gridApi.selection.unSelectRow(vm.optionsEntidades.data[i]);

            // vm.gridApi.grid.modifyRows(vm.optionsEntidades.data);
            // vm.gridApi.selection.selectRow(vm.optionsEntidades.data[i]);

          }
        }
      }
    }

  }
})(angular);


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<title>Making Peach Ice Cream</title>
	<link href="https://fonts.googleapis.com/css?family=Lato:400,300,700" rel="stylesheet">
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css">
	<link href="css/styles.css" rel="stylesheet">
	<meta name="udacity-grader" content="http://udacity.github.io/fend/lessons/L5/problem-set/07-making-peach-ice-cream/tests.json">

Homemade Peach Ice Cream

Recipe by: James Parkes

 20+ servings

 30 min

 20 min

Ingredients

2 (1 lb) bags of ice

1 box of rock/ice cream salt

15-20 fresh peaches

1 egg beater

3 cups sugar

1 tbsp vanilla flavoring

1 tbsp lemon juice

1 cup whole milk

Directions

Wash, peel, and cut peaches into medium size pieces.

Add at least 1 tbsp lemon juice to peaches until all peaches are lightly covered. The lemon juice will keep the peaches from browning.

Add peaches, sugar, and milk into the blender/food processor and blend until all ingredients are fully incorporated. The peaches are not meant to be fine pieces, but rather small chunks. Pour the mixture into ice cream container to be used in the freezing process. Repeat this process until all the peaches have been blended. Once this step is complete, at least 3 cups of sugar and 1 cup of milk should be incorporated into the mixture. Make sure that once during the blending process you add the egg beater to the mixture to be incorporated.

To fill the ice cream container to the fill line, continue to add milk. Once the mixture has been topped off to the fill line, add sugar to taste. Almost always, the mixture requires more sugar to be added than the recipe calls.

Place the ice cream container inside the ice cream machine. Start the ice cream machine. While the ice cream machine is running, continue to add layers of ice and rock salt to the sides of the machine to freeze the ice cream so that the entire container is surrounded by ice and rock salt. Once the machine finishes, the ice cream can be served immediately or placed into the freezer to serve later.


text:
int main ()
{
  cgicc::Cgicc cgi;
  std::string name = cgi.getElement("name")->getValue();
  std::string email = cgi.getElement("email")->getValue();
  Persondata *p = new Persondata(name, email);
  Database db("lottery.db");
  db.add(p);
  HtmlDisplayer html;
  html.showConfirmation(p);

  return 0;
}


text:
layout: page
tags: [biological complexity, evolution, research]
image:
  feature: orangelichen.jpg
  credit: elibby #WeGraphics
  creditlink: #http://wegraphics.net/downloads/free-ultimate-blurred-background-pack/
---

My research focuses on the evolution of biological complexity-- particularly the origins of multicellularity, life cycles, syntrophy, and organizational scales. Essentially, I am interested in how simple organisms evolve into complex ones. This topic is not only fascinating but it is fundamental to understanding the evolution and ecology of life-- both on earth and elsewhere in the "verse".

### --- NEWS ---

- 12/01/17: I have officially started a faculty position in the Department of Mathematics and Statistics at Umeå University.

- 2/27/17: I am lucky to collaborate with great scientists including Luz Tavera-Mendoza. Our [paper](http://www.pnas.org/content/early/2017/02/24/1615015114) "Vitamin D receptor regulates autophagy in the normal mammary gland and in luminal breast cancer cells" is now available on the PNAS website.

- 1/31/17: "Drivers of microbial maintenance and minimal energy requirements" was published in [Frontiers in Microbiology](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5281582/pdf/fmicb-08-00031.pdf). Thanks to lead author and SFI racquetball "God of Thunder" Chris Kempes for his tour de force.

- 12/09/16: Posted our paper "Paradoxes in Leaky Microbial Trade" to [bioRxiv](http://biorxiv.org/content/early/2016/12/09/092882). Yoav Kallus, John Miller, and I found interesting behavior in a model of microbial communities producing metabolites.

- 11/30/16: Our paper "A quantitative definition of organismality and its application to lichen" is on the [arXiv](https://arxiv.org/abs/1612.00036). We use state space compression to determine the best "organisms" for prediction.

- 11/16/16: Participated in "Statistical Physics, Information Processing and Biology" [workshop](https://www.santafe.edu/events/statistical-physics-information-processing-an) at the Santa Fe Institute. Interesting discussions on a variety of topics.

- 8/22/16: Gave a talk at "Limits to Prediction" [workshop](https://www.santafe.edu/events/limits-to-prediction1) on predictability in microbial evolution.

- 8/05/16: Presenting poster "The Influence of Genetic Architecture and Mutation Hot Spots on Evolutionary Predictability" at [ASM Experimental Evolution](http://conferences.asm.org/index.php/upcoming-conferences/2ndasm-conference-on-experimental-microbial-evolution).

- 8/02/16: Giving talk at [IAL8 Lichens in Deep Time](http://ial8.luomus.fi/) conference entitled "Is a lichen an evolutionary individual".

- 7/15/16: We posted our paper with adaptive networks and voting paradoxes called "Strategic tradeoffs in competitor dynamics on adaptive networks" on [arXiv](https://arxiv.org/abs/1607.04632)

- 6/21/16: Gave talk at [Evolution](http://www.evolutionmeetings.org/evolution-2016---austin-texas.html) conference entitled "Predicting life's tape". There were lots of great talks and it was fun hearing what was going on in the field.

- 6/15/16: Posted "Programmed cell death can increase the efficacy of microbial bet-hedging" to [bioRxiv](http://biorxiv.org/content/early/2016/06/15/059071). With cell death and bet-hedging it is like Russian roulette with microbes.

- 5/18/16: "Time-dependent fitness effects can drive bet-hedging populations extinct" article with Will Ratcliff posted to [bioRxiv](http://biorxiv.org/content/early/2016/05/18/054007).

- 4/26/16: Gave a colloquium on "The Evolution of New Kinds of Individuals" as part of the University of Arizona's quantitative biology colloquium series. Loved meeting with faculty and students to talk about the great research going on at U of A.

- 4/7/16: Finished 72 hours of science  #72hoursofscience with a successful upload to the arXiv [Dynamics of beneficial epidemics](http://arxiv.org/abs/1604.02096)! It is such an honor working with my fantastic colleagues at SFI.

- 3/30/16: Our paper "Differences in epigenetic information between cells promotes the evolution of a germline" was just accepted at <I> Phil. Trans. R. Soc. B </I>!

- 3/25/16: There's now an extracurricular section on this webpage featuring posts about some of my other interests. The first post describes a preserved algae dish that is tasty with a heavy dose of umami.

- 3/10/16: Our paper "Stabilizing Multicellularity Through Ratcheting" was just accepted at <I> Phil. Trans. R. Soc. B </I>!


text:
import sys
import re

def setup_python3():
    # Taken from "distribute" setup.py
    from distutils.filelist import FileList
    from distutils import dir_util, file_util, util, log
    from os.path import join

    tmp_src = join("build", "src")
    log.set_verbosity(1)
    fl = FileList()
    for line in open("MANIFEST.in"):
        if not line.strip():
            continue
        fl.process_template_line(line)
    dir_util.create_tree(tmp_src, fl.files)
    outfiles_2to3 = []
    for f in fl.files:
        outf, copied = file_util.copy_file(f, join(tmp_src, f), update=1)
        if copied and outf.endswith(".py"):
            outfiles_2to3.append(outf)

    util.run_2to3(outfiles_2to3)

    # arrange setup to use the copy
    sys.path.insert(0, tmp_src)

    return tmp_src

kwargs = {}
if sys.version_info[0] >= 3:
    from setuptools import setup
    kwargs['use_2to3'] = True
    kwargs['install_requires'] = ['html5lib', 'rdflib>3.0.0']
    kwargs['src_root'] = setup_python3()
else:
    try:
        from setuptools import setup
        kwargs['test_suite'] = "nose.collector"
        kwargs['install_requires'] = ['html5lib', 'rdflib>3.0.0']
    except ImportError:
        from distutils.core import setup

# Find version. We have to do this because we can't import it in Python 3 until
# its been automatically converted in the setup process.
def find_version(filename):
    _version_re = re.compile(r'__version__ = "(.*)"')
    for line in open(filename):
        version_match = _version_re.match(line)
        if version_match:
            return version_match.group(1)

version = find_version('pyRdfa/__init__.py')

setup(
    name = 'pyRdfa',
    version = version,
    description = "",
    author = "",
    author_email = "",
    maintainer = "",
    maintainer_email = "",
    url = "",
    license = "LICENSE",
    platforms = ["any"],
    classifiers = ["Programming Language :: Python",
                   "Programming Language :: Python :: 2",
                   "Programming Language :: Python :: 3",
                   "Programming Language :: Python :: 2.4",
                   "Programming Language :: Python :: 2.5",
                   "Programming Language :: Python :: 2.6",
                   "Programming Language :: Python :: 2.7",
                   "Programming Language :: Python :: 3.2",
                   "License :: OSI Approved :: BSD License",
                   "Topic :: Software Development :: Libraries :: Python Modules",
                   "Operating System :: OS Independent",
                   "Natural Language :: English",
                   ],
    long_description = \
    """
    """,
    download_url = "%s.tar.gz" % version,
    packages = ['pyRdfa',
                'pyRdfa/host',
                'pyRdfa/rdfs',
                'pyRdfa/serializers',
                'pyRdfa/transform',
                ],
    **kwargs
    )


text:
require 'spec_helper'

class Convection::Model::Template::Resource
  describe SNSSubscription do
    let(:template) do
      Convection.template do
        sns_subscription 'MySubscription' do
          endpoint 'failures@example.com'
          protocol 'email'
          topic_arn 'arn:aws:sns:us-west-2:123456789012:example-topic'
          filter_policy 'Type' => 'Notification', 'MessageId' => 'e3c4e17a-819b-5d95-a0e8-b306c25afda0', 'MessageAttributes' => { 'AttributeName' => 'Name', 'KeyType' => 'HASH' }
        end
      end
    end

    subject do
      template_json
        .fetch('Resources')
        .fetch('MySubscription')
        .fetch('Properties')
    end

    it 'sets the Endpoint' do
      expect(subject['Endpoint']).to eq('failures@example.com')
    end

    it 'sets the Protocol' do
      expect(subject['Protocol']).to eq('email')
    end

    it 'sets the TopicArn' do
      expect(subject['TopicArn']).to eq('arn:aws:sns:us-west-2:123456789012:example-topic')
    end

    it 'sets the FilterPolicy' do
      expect(subject['FilterPolicy']).to include('Type' => 'Notification',
                                                 'MessageId' => 'e3c4e17a-819b-5d95-a0e8-b306c25afda0',
                                                 'MessageAttributes' => { 'AttributeName' => 'Name', 'KeyType' => 'HASH' })
    end

    private

    def template_json
      JSON.parse(template.to_json)
    end
  end
end


text:
<?php

namespace AndyDuneTest;
use AndyDune\Pipeline\Pipeline;
use AndyDune\Pipeline\Stage\ExceptionCatch;
use AndyDune\Pipeline\Stage\ArrayKeysToLower;
use PHPUnit\Framework\TestCase;

class StagesTest extends TestCase
{
    /**
     * @return void
     */
    public function testArrayKeysToLower()
    {
        $array = [
            'id' => 12,
            'ID' => 13,
            'aRRay' => [
                'RU' => 'RU',
                'EN' => 'EN',
            ]
        ];

        $result = (new Pipeline())
                  ->send($array)
            ->pipe(ArrayKeysToLower::class)->execute();

        $this->assertCount(2, $result);
        $this->arrayHasKey('array', $result);
        $this->assertArrayNotHasKey('ID', $result);
        $this->assertEquals(13, $result['id']);
        $this->assertArrayNotHasKey('RU', $result['array']);
        $this->assertArrayNotHasKey('EN', $result['array']);

        $result = (new Pipeline())
            ->send($array)
            ->pipe(ArrayKeysToLower::class, null, false)->execute();

        $this->assertCount(2, $result);
        $this->arrayHasKey('array', $result);
        $this->arrayHasKey('id', $result);
        $this->assertEquals(13, $result['id']);
        $this->assertArrayNotHasKey('ru', $result['array']);
        $this->assertArrayNotHasKey('en', $result['array']);

        $result = (new Pipeline())
            ->send($array)
            ->pipe(ArrayKeysToLower::class, null, true, ['aRRay'])->execute();

        $this->assertCount(3, $result);
        $this->assertArrayHasKey('aRRay', $result);
        $this->assertArrayHasKey('ID', $result);
        $this->assertArrayHasKey('id', $result);
        $this->assertArrayHasKey('ru', $result['aRRay']);
        $this->assertArrayHasKey('en', $result['aRRay']);

    }

}


text:
package com.codepath.apps.restclienttemplate;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.codepath.apps.restclienttemplate.models.Tweet;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.json.JSONArray;
import org.json.JSONObject;
import org.parceler.Parcels;

import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * Created by samerk on 6/26/17.
 */

public class TweetAdapter extends RecyclerView.Adapter<TweetAdapter.ViewHolder> {
    static private List<Tweet> mTweets;
    static Context context;

    // pass in tweet array into constructor
    public TweetAdapter(List<Tweet> tweets) {
        mTweets = tweets;
    }

    // for each row inflate layout and pass to viewholder
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        context = parent.getContext();
        LayoutInflater inflater = LayoutInflater.from(context);

        View tweetView = inflater.inflate(R.layout.item_tweet, parent, false);
        ViewHolder viewHolder = new ViewHolder(tweetView);
        return viewHolder;
    }

    // Clean all elements of the recycler
    public void clear() {
        mTweets.clear();
        notifyDataSetChanged();
    }

    // Add a list of items -- change to type used
    public void addAll(List<Tweet> list) {
        mTweets.addAll(list);
        notifyDataSetChanged();
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        // get data according to position
        Tweet tweet = mTweets.get(position);

        if (tweet.favorited) {
            holder.favBtn.setImageResource(R.drawable.ic_vector_heart);
        }
        // populate views according to data
        holder.tvUsername.setText(tweet.user.name);
        holder.tvBody.setText(tweet.body);
        holder.tvTime.setText(TimeFormatter.getTimeDifference(tweet.createdAt));
        holder.tvHandle.setText("@" + tweet.user.screenName);
        holder.tvFav.setText(tweet.favoriteCount + "");
        Glide.with(context).load(tweet.user.profileImageUrl).into(holder.ivProfileImage);
    }

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

    // create viewholder class

    public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        @Override
        public void onClick(final View v) {
            // get position of item
            final int pos = getAdapterPosition();
            TwitterClient client = new TwitterClient(context);
            // make sure position is valid
            if (pos != RecyclerView.NO_POSITION) {
                // get the movie at the position, this won't work if the class is static
                final Tweet tweet = mTweets.get(pos);
                if (v.getId() == replyBtn.getId()) {
                    Toast.makeText(v.getContext(), "reply button clicked", Toast.LENGTH_LONG).show();
                } else if (v.getId() == rtBtn.getId()) {
                    Toast.makeText(v.getContext(), "retweet button clicked", Toast.LENGTH_LONG).show();
                } else if (v.getId() == favBtn.getId()) {

                    // check if tweet was favorited
                    if (!tweet.favorited) {

                        client.favTweet(tweet.uid, new JsonHttpResponseHandler() {

                            @Override
                            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {

                                try {
                                    Toast.makeText(v.getContext(), "favorite button clicked", Toast.LENGTH_SHORT).show();
                                    favBtn.setImageResource(R.drawable.ic_vector_heart);
                                    tvFav.setText(tweet.favoriteCount + "");
                                    // Tweet newTweet = Tweet.fromJSON(response);
//                                  mTweets.add(pos, newTweet);

                                } finally {

                                }
                                // super.onSuccess(statusCode, headers, response);
                            }

                            @Override
                            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                                super.onFailure(statusCode, headers, responseString, throwable);
                            }

                            @Override
                            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                                super.onFailure(statusCode, headers, throwable, errorResponse);
                            }

                            @Override
                            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
                                super.onFailure(statusCode, headers, throwable, errorResponse);
                            }
                        });
                        // populateTimeline();

                    } else if (tweet.favorited) {
                        client.unFavTweet(tweet.uid, new JsonHttpResponseHandler() {
                            @Override
                            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                                try {
                                    Toast.makeText(v.getContext(), "unfavorite", Toast.LENGTH_SHORT).show();
                                    favBtn.setImageResource(R.drawable.ic_vector_heart_stroke);
                                } finally {

                                }
//                                catch (JSONException e) {
//                                    Log.e("TweetAdapter", "error unfavoriting tweet", e);
//                                }
                            }
                        });
                    }
                } else if (v.getId() == dmBtn.getId()) {
                    Toast.makeText(v.getContext(), "dm button clicked", Toast.LENGTH_LONG).show();
                } else {
                    // create intent for the new activity
                    Intent intent = new Intent(context, DetailsActivity.class);
                    // serialize the movie using parceler, use its short name as a key
                    intent.putExtra(Tweet.class.getSimpleName(), Parcels.wrap(tweet));
                    // show the activity
                    context.startActivity(intent);
                }
            }
        }

        public ImageView ivProfileImage;
        public TextView tvUsername;
        public TextView tvBody;
        public TextView tvTime;
        public TextView tvHandle;
        public TextView tvFav;
        public ImageButton replyBtn;
        public ImageButton rtBtn;
        public ImageButton favBtn;
        public ImageButton dmBtn;

        public ViewHolder(View itemView) {
            super(itemView);

            // perform findViewById lookups
            ivProfileImage = (ImageView) itemView.findViewById(R.id.ivProfileImage);
            tvFav = (TextView) itemView.findViewById(R.id.tvFav);
            tvUsername = (TextView) itemView.findViewById(R.id.tvUserName);
            tvBody = (TextView) itemView.findViewById(R.id.tvBody);
            tvTime = (TextView) itemView.findViewById(R.id.tvTime);
            tvHandle = (TextView) itemView.findViewById(R.id.tvHandle);
            replyBtn = (ImageButton) itemView.findViewById(R.id.replyBtn);
            rtBtn = (ImageButton) itemView.findViewById(R.id.rtBtn);
            favBtn = (ImageButton) itemView.findViewById(R.id.favBtn);
            dmBtn = (ImageButton) itemView.findViewById(R.id.dmBtn);
            itemView.setOnClickListener(this);
            // add click listeners for each button
            replyBtn.setOnClickListener(this);
            rtBtn.setOnClickListener(this);
            favBtn.setOnClickListener(this);
            dmBtn.setOnClickListener(this);

        }

    }
}


text: module.exports = require("core-js-pure/stable/parse-int");


text:
<?php
// Title
self::$lang['planet-title'] = 'Galaxy Explorer';

// View
self::$lang['planet-uninhabited'] = 'This planet is currently uninhabited';


text:
package main

import (
	"encoding/csv"
	"fmt"
	"os"
	"path"
	"strconv"
	"strings"
	"text/tabwriter"

	"github.com/alecthomas/kong"
	"github.com/codahale/tinystat"
	"github.com/vdobler/chart"
	"github.com/vdobler/chart/txtg"
)

var version = "dev"

func main() {
	//nolint:maligned // ordering of fields matters
	var cli struct {
		//nolint:lll // can't format struct field tags
		Confidence      float64          `short:"C" default:"95" help:"Confidence level for statistical significance (0,100)."`
		Column          int              `short:"c" default:"0" help:"The CSV column to analyze."`
		Delimiter       string           `short:"d" default:"," help:"The CSV delimiter to use."`
		NoChart         bool             `default:"false" help:"Don't display the box chart.'"`
		Width           int              `default:"74" help:"The width of the box chart in chars."`
		Height          int              `default:"20" help:"The height of the box chart in chars."`
		Version         kong.VersionFlag `help:"Display the application version."`
		ControlPath     string           `arg:"" type:"existingfile" help:"The CSV file containing measurements of the control group."`            //nolint:lll // can't format struct field tags
		ExperimentPaths []string         `arg:"" optional:"" type:"existingfile" help:"CSV files containing measurements of experimental groups."` //nolint:lll // can't format struct field tags
	}

	ctx := kong.Parse(&cli, kong.Vars{"version": version})
	if ctx.Error != nil {
		_, _ = fmt.Fprintln(os.Stderr, ctx.Error)
		os.Exit(1)
	}

	// read the data
	controlData, experimentData, err := readData(cli.ControlPath, cli.ExperimentPaths, cli.Column, cli.Delimiter)
	if err != nil {
		_, _ = fmt.Fprintln(os.Stderr, err)
		os.Exit(-1)
	}

	// chart the data
	if !cli.NoChart {
		printChart(cli.ExperimentPaths, cli.ControlPath, controlData, experimentData, cli.Width, cli.Height)
	}

	// compare the data
	if len(cli.ExperimentPaths) > 0 {
		printComparison(cli.ControlPath, controlData, cli.ExperimentPaths, experimentData, cli.Confidence)
	}
}

func printComparison(
	controlFilename string, controlData []float64,
	experimentFilenames []string, experimentData map[string][]float64,
	confidence float64,
) {
	t := tabwriter.NewWriter(os.Stdout, 2, 0, 2, ' ', 0)
	_, _ = fmt.Fprintf(t, "File\tN\tMean\tStddev\t\n")

	control := tinystat.Summarize(controlData)
	_, _ = fmt.Fprintf(t, "%s\t%.0f\t%.2f\t%0.2f\t%s\n", path.Base(controlFilename),
		control.N, control.Mean, control.StdDev(), "(control)")

	for _, filename := range experimentFilenames {
		experiment := tinystat.Summarize(experimentData[filename])
		d := tinystat.Compare(control, experiment, confidence)
		p := strings.TrimLeft(fmt.Sprintf("%.3f", d.PValue), "0")

		var results string

		if d.Significant() {
			operator := ">"
			if experiment.Mean < control.Mean {
				operator = "<"
			}

			results = fmt.Sprintf("(%.2f %s %.2f ± %.2f, p = %s)",
				experiment.Mean, operator, control.Mean, d.CriticalValue, p)
		} else {
			results = fmt.Sprintf("(no difference, p = %s)", p)
		}

		_, _ = fmt.Fprintf(t, "%s\t%.0f\t%.2f\t%0.2f\t%s\n",
			path.Base(filename), experiment.N, experiment.Mean, experiment.StdDev(), results)
	}

	_ = t.Flush()
}

func readData(
	controlFilename string, experimentFilenames []string,
	column int, delimiter string,
) ([]float64, map[string][]float64, error) {
	controlData, err := readFile(controlFilename, column, delimiter)
	if err != nil {
		return nil, nil, err
	}

	experimentData := make(map[string][]float64)

	for _, filename := range experimentFilenames {
		expData, err := readFile(filename, column, delimiter)
		if err != nil {
			return nil, nil, err
		}

		experimentData[filename] = expData
	}

	return controlData, experimentData, nil
}

func printChart(
	experimentFilenames []string, controlFilename string, controlData []float64,
	experimentData map[string][]float64, width, height int,
) {
	c := chart.BoxChart{}
	c.XRange.Fixed(-1, float64(len(experimentFilenames))+1, 1)
	c.XRange.Category = make([]string, len(experimentFilenames)+1)
	c.XRange.Category[0] = path.Base(controlFilename)

	for i, file := range experimentFilenames {
		c.XRange.Category[i+1] = path.Base(file)
	}

	c.AddSet(0, controlData, true)

	for i, filename := range experimentFilenames {
		c.AddSet(float64(i+1), experimentData[filename], true)
	}

	txt := txtg.New(width, height)
	c.Plot(txt)
	fmt.Println(txt)
}

func readFile(filename string, col int, del string) ([]float64, error) {
	f, err := os.Open(filename)
	if err != nil {
		return nil, err
	}

	defer func() { _ = f.Close() }()

	r := csv.NewReader(f)
	r.Comma = []rune(del)[0]

	records, err := r.ReadAll()
	if err != nil {
		return nil, err
	}

	data := make([]float64, len(records))

	for i, s := range records {
		n, err := strconv.ParseFloat(s[col], 64)
		if err != nil {
			return nil, err
		}

		data[i] = n
	}

	return data, nil
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>
  Module: UartDriver

    — Documentation by YARD 0.9.12

</title>

  <link rel="stylesheet" href="css/style.css" type="text/css" charset="utf-8" />

  <link rel="stylesheet" href="css/common.css" type="text/css" charset="utf-8" />

    Index (U) »

    UartDriver

        <svg width="24" height="24">
          <rect x="0" y="4" width="24" height="4" rx="1" ry="1"></rect>
          <rect x="0" y="12" width="24" height="4" rx="1" ry="1"></rect>
          <rect x="0" y="20" width="24" height="4" rx="1" ry="1"></rect>
        </svg>

Module: UartDriver

Defined in:

app/models/drivers/uart_driver.rb

      Class Method Summary
      collapse

      .description  ⇒ Object

      .get_port(address)  ⇒ Object

      .scan  ⇒ Object

      Instance Method Summary
      collapse

      #set_driver_value(v)  ⇒ Object

Class Method Details

    .description  ⇒ <tt>Object</tt>

19
20
21

# File 'app/models/drivers/uart_driver.rb', line 19

def self.description
  "Serial port driver"
end

    .get_port(address)  ⇒ <tt>Object</tt>

27
28
29
30
31
32
33
34
35

# File 'app/models/drivers/uart_driver.rb', line 27

def self.get_port(address)
  @ports ||= {}
  p = @ports[address]
  unless p
    p = Serial.new(address, 9600, 8)
    @ports[address] = p
  end
  return p
end

    .scan  ⇒ <tt>Object</tt>

23
24
25

# File 'app/models/drivers/uart_driver.rb', line 23

def self.scan
  ['/dev/serial0', '/dev/serial1']
end

Instance Method Details

    #set_driver_value(v)  ⇒ <tt>Object</tt>

13
14
15
16
17

# File 'app/models/drivers/uart_driver.rb', line 13

def set_driver_value(v)
  v = [v].pack('c')
  UartDriver.get_port(address).write(v)
  puts v.inspect
end

  Generated on Sun Apr  1 09:41:22 2018 by
  yard
  0.9.12 (ruby-2.2.6).