text:
all: clean build

.PHONY: clean
clean:
	./gradlew clean

.PHONY: build
build:
	./gradlew --parallel build -x test -x :h2o-assemblies:minimal:shadowJar -x :h2o-assemblies:steam:shadowJar

.PHONY: minimal
minimal:
	./gradlew -PmainAssemblyName=minimal --parallel build -x test -x :h2o-assemblies:main:shadowJar -x :h2o-assemblies:steam:shadowJar

redpajama_set_name: RedPajamaGithub


text:
package org.javasimon.source;

import org.javasimon.Manager;
import org.javasimon.Simon;

/**
 * Monitor source provides monitors (Simons) for a specific name. This mechanism enables
 * caching of monitors for "locations" that do not change but may be expensive to transform to
 * Simon names, for instance.
 *
 * @param <L> Location/invocation context
 * @param <M> Simon type
 * @author gquintana
 */
public interface MonitorSource<L, M extends Simon> {
	/**
	 * Indicates whether given location should be monitored or not.
	 *
	 * @param location Location
	 * @return true means monitored
	 */
	boolean isMonitored(L location);

	/**
	 * Returns the monitor for given location.
	 *
	 * @param location Location
	 * @return Monitor
	 */
	M getMonitor(L location);

	/**
	 * Returns the {@link Manager} used as a real source of monitors.
	 *
	 * @return Manager to get the monitors from
	 */
	Manager getManager();
}


text:
package org.programmiersportgruppe.redis.commands

import akka.util.ByteString

import org.programmiersportgruppe.redis._
import org.programmiersportgruppe.redis.test.Test

class RecognisedCommandTest extends Test {

  behavior of classOf[RecognisedCommand].getName

  it should "have a short string representation" in {
    assertResult("RecognisedCommand: SET abc <bytes=5> EX 7") {
      SET(Key("abc"), ByteString("yays!"), Some(ExpiresInSeconds(7))).toString
    }
  }

}


text: {{$ctrl.user.username}}


text:
react rc-radio component

[![NPM version][npm-image]][npm-url]
[![build status][travis-image]][travis-url]
[![Test coverage][coveralls-image]][coveralls-url]
[![gemnasium deps][gemnasium-image]][gemnasium-url]
[![node version][node-image]][node-url]
[![npm download][download-image]][download-url]

[npm-image]: http://img.shields.io/npm/v/rc-radio.svg?style=flat-square
[npm-url]: http://npmjs.org/package/rc-radio
[travis-image]: https://img.shields.io/travis/react-component/radio.svg?style=flat-square
[travis-url]: https://travis-ci.org/react-component/radio
[coveralls-image]: https://img.shields.io/coveralls/react-component/radio.svg?style=flat-square
[coveralls-url]: https://coveralls.io/r/react-component/radio?branch=master
[gemnasium-image]: http://img.shields.io/gemnasium/react-component/radio.svg?style=flat-square
[gemnasium-url]: https://gemnasium.com/react-component/radio
[node-image]: https://img.shields.io/badge/node.js-%3E=_0.10-green.svg?style=flat-square
[node-url]: http://nodejs.org/download/
[download-image]: https://img.shields.io/npm/dm/rc-radio.svg?style=flat-square
[download-url]: https://npmjs.org/package/rc-radio

## install

[![rc-radio](https://nodei.co/npm/rc-radio.png)](https://npmjs.org/package/rc-radio)

## Usage

```js
var Radio = require('rc-radio');
// use rc-radio
```

## Api

same with <input type='radio' />, but only support controlled radio.

## Development

```
npm install
npm start
```

## Test Case

http://localhost:9090/tests/runner.html?coverage

https://travis-ci.org/react-component/radio

## Coverage

http://localhost:9090/node_modules/rc-server/node_modules/node-jscover/lib/front-end/jscoverage.html?w=http://localhost:9090/tests/runner.html?coverage

## License

rc-radio is released under the MIT license.


text:
<?php

class privilegeController extends controller {

	function __construct($registry) {

		parent::__construct($registry);

		$this->_cpath = dirname(__FILE__);
		$this->_mdl_name = "privilege";

		// privileges
		$this->_class_privilege = $this->_mdl_name;
		$this->_view_privilege = 1;
	}

	public function manage() {

		access::check($this->_registry, $this->_class_privilege, $this->_view_privilege, array("exitOnFailure"=>true));

		$at = new adminTable($this->_registry, TBL_SYS_PRIVILEGES, array('insertion'=>false, 'edit_deny'=>'all'));

		$text = __("ManagePrivilegesExp");

		$table = $at->manage();

		$this->_view->setTpl('manage_table');
		$this->_view->assign('text', $text);
		$this->_view->assign('title', __("TableContent")." ".TBL_SYS_PRIVILEGES);
		$this->_view->assign('table', $table);

		return $this->_view->render();
	}

}

?>


text:
function usage {
    cat <<EOF
Usage:
$0 output_filename min_page_size step_size max_page_size
$0 output_filename min_page_size max_page_size
$0 output_filename max_page_size
$0 output_filename
$0
  - Page size unit is 100 bytes.
EOF
}

# string 100 bytes long
str="123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 "

# make the test
make writetest

case $1 in
    -h|--help|-*|[0-9]*)
	usage
	exit
	;;
    *)
	filename=${1:-testout}
	echo "The basename of the output file is ${filename}."
	shift;
	;;
esac

number_re='^[0-9]+$'
for arg in $@; do
    echo "testing ${arg}"
    if ! [[ $arg =~ ${number_re} ]]; then usage; exit 1; fi
done

# if the rest of the arguments are not accepted by seq,
# then something is wrong.
if ! seq ${@:-1} &> /dev/null; then usage; exit 1; fi

case $# in
    0)
	maxPageSize=10
	stepSize=1
	minPageSize=1
	;;
    1)
	maxPageSize=$1
	stepSize=1
	minPageSize=1
	;;
    2)
	maxPageSize=$2
	stepSize=1
	minPageSize=$1
	;;

    3)
	maxPageSize=$3
	stepSize=$2
	minPageSize=$1
	;;
    *)
	usage
	exit 1
	;;
esac

echo "Running simulation with minPageSize ${minPageSize}, stepSize ${stepSize}, maxPageSize ${maxPageSize}"

cat <<EOF
Putting tabular results in:
  ${filename}.pages (varying number of pages of fixed size) and "
  ${filename}.page_sizes (one page of varying sizes)."
Putting output graph in ${filename}.png.
EOF

echo -e "page_size\tmmap_paging\twrite_paging" > ${filename}.pages
for pages in $(seq ${minPageSize} ${stepSize} ${maxPageSize}); do
    output=${filename}.${pages}.1
    ./writetest ${output} ${pages} 1 ${str} | tee -a ${filename}.pages > /dev/null
    # check to make sure that the writetest output files are the same, then remove them
    diff ${output}.mmap ${output}.write
    rm ${output}.mmap ${output}.write
done
echo -e "page_size\tmmap\twrite" > ${filename}.page_sizes
for page_size in $(seq ${minPageSize} ${stepSize} ${maxPageSize}); do
    output=${filename}.1.${page_size}
    ./writetest ${output} 1 ${page_size} ${str} | tee -a ${filename}.page_sizes > /dev/null
    diff ${output}.mmap ${output}.write
    rm ${output}.mmap ${output}.write
done
gnuplot -p <<EOF
# set terminal wxt
set terminal png
set output "${filename}.png"
set xlabel "Bytes"
set ylabel "Seconds"
plot for[col=2:3] "${filename}.pages" using 1:col title columnheader(col) with lines, \
     for[col=2:3] "${filename}.page_sizes" using 1:col title columnheader(col) with lines
EOF
eog "${filename}.png"


text:
export default {
  home: {
    path: "/",
    method: "get",
    handler: require("src/components/Home"),
    action: (context, payload, done) => {
      context.dispatch("UPDATE_PAGE_TITLE", { pageTitle: "Home" });
      done();
    }
  },
  mypage: {
    path: "/mypage/:userCode",
    method: "get",
    handler: require("src/components/MyPage"),
    action: (context, payload, done) => {
      const userCode = payload.get("params").get("userCode");
      context.dispatch("UPDATE_PAGE_TITLE", { pageTitle: `${userCode}さんのマイページ`});
      done();
    }
  }
};


text:
<?php

namespace Chalk\Core\Backend\Controller;

use Coast\Controller\Action,
    Coast\Request,
    Coast\Response;

class Auth extends Action
{
    public function login(Request $req, Response $res)
    {
        if (!$req->isPost()) {
            return;
        }

        $this->model->graphFromArray($req->bodyParams());
        if (!$this->model->graphIsValid()) {
            return;
        }

        $user = $this->em('core_user')->one(['emailAddress' => $this->model->emailAddress]);
        if (!isset($user)) {
            $this->model->password = null;
            $this->model->addError('emailAddress', 'login');
            return;
        } else if (!$user->verifyPassword($this->model->password)) {
            $this->model->password = null;
            $this->model->addError('emailAddress', 'login');
            return;
        }

        $user->loginDate = new \Carbon\Carbon();
        $this->em->flush();

        // $this->session->regenerate();
        $session = $this->session->data('__Chalk\Backend');
        $session->user = $user;

        if (isset($this->model->redirect)) {
            return $res->redirect($this->model->redirect);
        } else {
            return $res->redirect($this->url([], 'core_index', true));
        }
    }

    public function passwordRequest(Request $req, Response $res)
    {
        if (!$req->isPost()) {
            return;
        }

        $this->model->graphFromArray($req->bodyParams());
        if (!$this->model->graphIsValid()) {
            return;
        }

        $user = $this->em('core_user')->one(['emailAddress' => $this->model->emailAddress]);
        if (!isset($user)) {
            $this->model->addError('emailAddress', 'Sorry, that account could not be found');
            return;
        }

        $user->token     = sha1(uniqid(mt_rand(), true));
        $user->tokenDate = new \DateTime('+24 hour');
        $this->em->flush();

        $this->swift->send((new \Swift_Message())
            ->setSubject("{$this->domain->label} Password Reset")
            ->setTo($user->emailAddress)
            ->setFrom($this->domain->emailAddress)
            ->setBody((string) $this->view->render('email/password-request', [
                'domain' => $this->domain,
                'user' => $user,
            ], 'core')));

        $this->notify('Please check your email for password reset instructions');
        return $res->redirect($this->url([], 'core_login', true));
    }

    public function passwordReset(Request $req, Response $res)
    {
        $user = $this->em('core_user')->one(['token' => $req->token]);
        if (!isset($user)) {
          $this->notify('Sorry, your password reset link has expired, please request a new one', 'negative');
            return $res->redirect($this->url([], 'core_passwordRequest', true));
        }

        if (!$req->isPost()) {
            return;
        }

        $this->model->graphFromArray($req->bodyParams());
        if (!$this->model->graphIsValid()) {
            return;
        }

        $user->passwordPlain = $this->model->password;
        $user->token         = null;
        $user->tokenDate     = null;
        $this->em->flush();

        $this->notify('Your password has been reset successfully', 'positive');
        return $res->redirect($this->url([], 'core_login', true));
    }

    public function logout(Request $req, Response $res)
    {
        // $this->session->regenerate();
        $session = $this->session->data('__Chalk\Backend');
        $session->user = null;

        return $res->redirect($this->url([], 'core_login', true));
    }

    public function jump(Request $req, Response $res)
    {}
}


text:
import Control.Exception
import Data.Typeable
import System.Directory
import System.Exit
import System.FilePath.Posix
import System.Posix.Temp
import System.Process

main :: IO ()
main = do
    testcase1

tempdir :: String -> IO FilePath
tempdir x = do
    tmp <- getTemporaryDirectory
    mkdtemp $ (combine tmp "git-yrp.") ++ x

-- testcase1 tests a patch is created in ./pull-request/
-- TODO: should work without configured yrp remotes/branches as well as
-- without any remote
-- TODO: add tempdir cleanups
testcase1 :: IO ()
testcase1 = do
    d <- tempdir "tc1"

    let local  = combine d "local"
        foo    = combine local "foo"
        bar    = combine local "bar"
        pr     = combine local "pull-request"
        remote = combine d "remote"
        p      = combine pr "0001-add-bar.patch"

    git d $ "init " ++ local
    writeFile foo "foo"
    git local $ "add " ++ foo
    git local "commit -a -m init"

    testShell d $ "cp -a " ++ local ++ " " ++ remote

    git local $ "remote add origin file:///" ++ remote
    git local $ "fetch origin"
    git local "checkout -b bar"

    writeFile bar "bar"
    git local $ "add " ++ bar
    git local "commit -a -m 'add bar'"

    git local "config --local yrp.stableRemote origin"
    git local "config --local yrp.stableBranch master"
    git local "config --local yrp.userRemote yac"

    git local "config --local yrp.subjectPrefix repo"
    git local "config --local yrp.to repo-reviewers@example.com"
    git local "config --local yrp.cc repo-bikeshed@lists.example.com"

    gitYrp local

    fok_ "patch doesn't exist" (doesFileExist p)

testShell :: FilePath -> String -> IO ()
testShell d cmd = do
    let c = (shell cmd) {
              cwd = Just d
            , close_fds = True
            , std_out = CreatePipe
        }
    (_, _, _, h) <- createProcess c
    ec <- waitForProcess h
    checkFailure ec
    return ()

git :: FilePath -> String -> IO ()
git d args = testShell d $ "git " ++ args

gitYrp d = testShell d "git-yrp"

checkFailure ExitSuccess = return ()
checkFailure (ExitFailure x) = throw $ ExitFailure x

data AssertionFailure = AssertionFailure { message :: String }
    deriving (Show, Typeable)

instance Exception AssertionFailure

fok_ :: String -> IO Bool -> IO ()
fok_ m fb = do
    b <- fb
    ok_ m b

ok_ :: String -> Bool -> IO ()
ok_ m True  = return ()
ok_ m False = throw $ AssertionFailure m


text:
class PagesController < ApplicationController

  skip_authorization_check

  def root
  end

end


text:
<?php

namespace Hubzero\Debug\Profile;

/**
 * Represents a time mark for the profiler.
 */
class Mark
{
	/**
	 * The label.
	 *
	 * @var  string
	 */
	private $label;

	/**
	 * The time of the start of the period (in milliseconds)
	 *
	 * @var  float
	 */
	private $start;

	/**
	 * The time of the end of the period (in milliseconds)
	 *
	 * @var  float
	 */
	private $end;

	/**
	 * The memory usage at the time of the mark
	 *
	 * @var  integer
	 */
	private $memory;

	/**
	 * Constructor.
	 *
	 * @param  string   $label   The label or identifier for a mark
	 * @param  integer  $start   The relative time of the start of the period (in milliseconds)
	 * @param  integer  $end     The relative time of the end of the period (in milliseconds)
	 * @param  integer  $memory  The memory usage (in bytes)
	 */
	public function __construct($label, $start = 0.0, $end = 0.0, $memory = 0)
	{
		$this->label  = (string) $label;
		$this->start  = (float) $start;
		$this->end    = (float) $end;
		$this->memory = (int) $memory;
	}

	/**
	 * Gets the label.
	 *
	 * @return  string  The label
	 */
	public function label()
	{
		return $this->label;
	}

	/**
	 * Gets the relative time of the start of the period.
	 *
	 * @return  integer  The time (in milliseconds)
	 */
	public function started()
	{
		return $this->start;
	}

	/**
	 * Gets the relative time of the end of the period.
	 *
	 * @return  integer  The time (in milliseconds)
	 */
	public function ended()
	{
		return $this->end;
	}

	/**
	 * Gets the time spent in this period.
	 *
	 * @return  integer  The period duration (in milliseconds)
	 */
	public function duration()
	{
		return $this->end - $this->start;
	}

	/**
	 * Gets the memory usage.
	 *
	 * @return  integer  The memory usage (in bytes)
	 */
	public function memory()
	{
		return $this->memory;
	}

	/**
	 * Get string output
	 *
	 * @return  string
	 */
	public function __toString()
	{
		return $this->toString();
	}

	/**
	 * Get string output
	 *
	 * @return  string
	 */
	public function toString()
	{
		return sprintf('%s: %.2F MiB - %d ms', $this->label(), $this->memory() / 1024 / 1024, $this->duration());
	}

	/**
	 * Get array output
	 *
	 * @return  array
	 */
	public function toArray()
	{
		return array(
			'label'  => $this->label(),
			'start'  => $this->started(),
			'end'    => $this->ended(),
			'memory' => $this->memory()
		);
	}
}


text:
    <link rel="stylesheet" type="text/css" href="css/tips.css">

Make your printouts (File | Print) nice and informative with the help of keywords.

For example, use $DATE$ and $TIME$ to specify the exact date and time of the printout.


text:
package avrora.sim;

import avrora.sim.util.MulticastIORWatch;

/**
 * The ProbedActiveRegister class implements a register that has
 * probes attached to it. It behaves like a normal ActiveRegister,
 * except that it will notify its watches before each read and write.
 *
 * @author Ben L. Titzer
 */
public class ProbedActiveRegister implements ActiveRegister {
    protected final int ioreg_num;
    protected final ActiveRegister ioreg;
    protected final MulticastIORWatch watches;
    private BaseInterpreter interpreter;

    protected ProbedActiveRegister(BaseInterpreter interpreter, ActiveRegister ar, int inum) {
        this.interpreter = interpreter;
        ioreg_num = inum;
        ioreg = ar;
        watches = new MulticastIORWatch();
    }

    /**
     * The add() method adds another watch to the list of watches for this active register.
     * @param w the watch to add to this active register
     */
    void add(Simulator.IORWatch w) {
        watches.add(w);
    }

    /**
     * The remove() method removes a watch from the list of watches for this active register.
     * @param w the watch to remove from this active register
     */
    void remove(Simulator.IORWatch w) {
        watches.remove(w);
    }

    /**
     * The isEmpty() method checks whether there are any watches for this active register.
     * @return true if there is at least one watch on this active register; false otherwise
     */
    boolean isEmpty() {
        return watches.isEmpty();
    }

    /**
     * The write() method writes an 8-bit value to the IO register as a byte. For special IO
     * registers, this may cause some action like device activity, masking/unmasking of interrupts, etc.
     * In the implementation of the ProbedActiveRegister class,
     * this method will notify the watch(es) for this register before and after the write.
     *
     * @param value the value to write
     */
    public void write(byte value) {
        watches.fireBeforeWrite(interpreter.state, ioreg_num, value);
        ioreg.write(value);
        watches.fireAfterWrite(interpreter.state, ioreg_num, value);
    }

    /**
     * The writeBit() method writes a single bit value into the IO register at the specified
     * bit offset. In the implementation of the ProbedActiveRegister class,
     * this method will notify the watch(es) for this register before and after the write.
     *
     * @param bit the number of the bit to write
     * @param val the value of the bit to write
     */
    public void writeBit(int bit, boolean val) {
        watches.fireBeforeBitWrite(interpreter.state, ioreg_num, bit, val);
        ioreg.writeBit(bit, val);
        watches.fireAfterBitWrite(interpreter.state, ioreg_num, bit, val);
    }

    /**
     * The read() method reads the 8-bit value of the IO register as a byte. For special IO
     * registers, this may cause some action like device activity, or the actual value of the register may
     * need to be fetched or computed. In the implementation of the ProbedActiveRegister class,
     * this method will notify the watch(es) for this register before and after the read.
     *
     * @return the value of the register as a byte
     */
    public byte read() {
        watches.fireBeforeRead(interpreter.state, ioreg_num);
        byte value = ioreg.read();
        watches.fireAfterRead(interpreter.state, ioreg_num, value);
        return value;
    }

    /**
     * The readBit() method reads a single bit from the IO register.
     * In the implementation of the ProbedActiveRegister class,
     * this method will notify the watch(es) for this register before and after the read.
     *
     * @param bit the number of the bit to read
     * @return the value of the bit as a boolean
     */
    public boolean readBit(int bit) {
        watches.fireBeforeBitRead(interpreter.state, ioreg_num, bit);
        boolean value = ioreg.readBit(bit);
        watches.fireAfterBitRead(interpreter.state, ioreg_num, bit, value);
        return value;
    }
}


text:
package com.lorenzobraghetto.compasslibrary;

import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;

import rx.Observable;
import rx.Observable.OnSubscribe;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.observables.ConnectableObservable;
import rx.subjects.BehaviorSubject;
import rx.subscriptions.CompositeSubscription;
import rx.subscriptions.Subscriptions;
import android.content.Context;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;

public class GeoDataProvider implements OnSubscribe<IGeoData> {

	private static final String LAST_LOCATION_PSEUDO_PROVIDER = "last";
	private final LocationManager geoManager;
	private final LocationData gpsLocation = new LocationData();
	private final LocationData netLocation = new LocationData();
	private final BehaviorSubject<IGeoData> subject;
	private static final StartableHandlerThread handlerThread =
			new StartableHandlerThread("GeoDataProvider thread", android.os.Process.THREAD_PRIORITY_BACKGROUND);
	static {
		handlerThread.start();
	}

	public boolean gpsEnabled = false;
	public int satellitesVisible = 0;
	public int satellitesFixed = 0;

	private static class LocationData {
		public Location location;
		public long timestamp = 0;

		public void update(final Location location) {
			this.location = location;
			timestamp = System.currentTimeMillis();
		}

		public boolean isRecent() {
			return isValid() && System.currentTimeMillis() < timestamp + 30000;
		}

		public boolean isValid() {
			return location != null;
		}
	}

	/**
	 * Build a new geo data provider object.
	 * <p/>
	 * There is no need to instantiate more than one such object in an
	 * application, as observers can be added at will.
	 *
	 * @param context
	 *            the context used to retrieve the system services
	 */
	protected GeoDataProvider(final Context context) {
		geoManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
		subject = BehaviorSubject.create(findInitialLocation());
	}

	public static Observable<IGeoData> create(final Context context) {
		final GeoDataProvider provider = new GeoDataProvider(context);
		return provider.worker.refCount();
	}

	@Override
	public void call(final Subscriber<? super IGeoData> subscriber) {
		subject.subscribe(subscriber);
	}

	final ConnectableObservable<IGeoData> worker = new ConnectableObservable<IGeoData>(this) {
		private int debugSessionCounter = 0;

		private final Object lock = new Object();
		private int count = 0;

		final private GpsStatus.Listener gpsStatusListener = new GpsStatusListener();
		final private Listener networkListener = new Listener(LocationManager.NETWORK_PROVIDER, netLocation);
		final private Listener gpsListener = new Listener(LocationManager.GPS_PROVIDER, gpsLocation);

		@Override
		public Subscription connect() {
			final CompositeSubscription subscription = new CompositeSubscription();
			AndroidSchedulers.handlerThread(handlerThread.getHandler()).createWorker().schedule(new Action0() {
				@Override
				public void call() {
					synchronized (lock) {
						if (count++ == 0) {
							Log.d("GeoDataProvider: starting the GPS and network listeners" + " (" + ++debugSessionCounter + ")", "");
							geoManager.addGpsStatusListener(gpsStatusListener);
							for (final Listener listener : new Listener[] { networkListener, gpsListener }) {
								try {
									geoManager.requestLocationUpdates(listener.locationProvider, 0, 0, listener);
								} catch (final Exception e) {
									Log.w("There is no location provider " + listener.locationProvider, "");
								}
							}
						}
					}

					subscription.add(Subscriptions.create(new Action0() {
						@Override
						public void call() {
							AndroidSchedulers.handlerThread(handlerThread.getHandler()).createWorker().schedule(new Action0() {
								@Override
								public void call() {
									synchronized (lock) {
										if (--count == 0) {
											Log.d("GeoDataProvider: stopping the GPS and network listeners" + " (" + debugSessionCounter + ")", "");
											geoManager.removeUpdates(networkListener);
											geoManager.removeUpdates(gpsListener);
											geoManager.removeGpsStatusListener(gpsStatusListener);
										}
									}
								}
							}, 2500, TimeUnit.MILLISECONDS);
						}
					}));
				}
			});
			return subscription;
		}
	};

	private IGeoData findInitialLocation() {
		final Location initialLocation = new Location(LAST_LOCATION_PSEUDO_PROVIDER);
		try {
			// Try to find a sensible initial location from the last locations known to Android.
			final Location lastGpsLocation = geoManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
			final Location lastNetworkLocation = geoManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

			// If both providers are non-null, take the most recent one
			if (lastGpsLocation != null && lastNetworkLocation != null) {
				if (lastGpsLocation.getTime() >= lastNetworkLocation.getTime()) {
					copyCoords(initialLocation, lastGpsLocation);
				} else {
					copyCoords(initialLocation, lastNetworkLocation);
				}
			} else if (lastGpsLocation != null) {
				copyCoords(initialLocation, lastGpsLocation);
			} else if (lastNetworkLocation != null) {
				copyCoords(initialLocation, lastNetworkLocation);
			} else {
				Log.i("GeoDataProvider: no last known location available", "");
			}
		} catch (final Exception e) {
			// This error is non-fatal as its only consequence is that we will start with a dummy location
			// instead of a previously known one.
			Log.e("GeoDataProvider: error when retrieving last known location", e.toString());
		}
		// Start with an historical GeoData just in case someone queries it before we get
		// a chance to get any information.
		return new GeoData(initialLocation, false, 0, 0, true);
	}

	private static void copyCoords(final Location target, final Location source) {
		target.setLatitude(source.getLatitude());
		target.setLongitude(source.getLongitude());
	}

	private class Listener implements LocationListener {
		private final String locationProvider;
		private final LocationData locationData;

		Listener(final String locationProvider, final LocationData locationData) {
			this.locationProvider = locationProvider;
			this.locationData = locationData;
		}

		@Override
		public void onStatusChanged(final String provider, final int status, final Bundle extras) {
			// nothing
		}

		@Override
		public void onProviderDisabled(final String provider) {
			// nothing
		}

		@Override
		public void onProviderEnabled(final String provider) {
			// nothing
		}

		@Override
		public void onLocationChanged(final Location location) {
			locationData.update(location);
			selectBest();
		}
	}

	private final class GpsStatusListener implements GpsStatus.Listener {

		@Override
		public void onGpsStatusChanged(final int event) {
			boolean changed = false;
			switch (event) {
			case GpsStatus.GPS_EVENT_FIRST_FIX:
			case GpsStatus.GPS_EVENT_SATELLITE_STATUS: {
				final GpsStatus status = geoManager.getGpsStatus(null);
				int visible = 0;
				int fixed = 0;
				for (final GpsSatellite satellite : status.getSatellites()) {
					if (satellite.usedInFix()) {
						fixed++;
					}
					visible++;
				}
				if (visible != satellitesVisible || fixed != satellitesFixed) {
					satellitesVisible = visible;
					satellitesFixed = fixed;
					changed = true;
				}
				break;
			}
			case GpsStatus.GPS_EVENT_STARTED:
				if (!gpsEnabled) {
					gpsEnabled = true;
					changed = true;
				}
				break;
			case GpsStatus.GPS_EVENT_STOPPED:
				if (gpsEnabled) {
					gpsEnabled = false;
					satellitesFixed = 0;
					satellitesVisible = 0;
					changed = true;
				}
				break;
			default:
				throw new IllegalStateException();
			}

			if (changed) {
				selectBest();
			}
		}
	}

	private LocationData best() {
		if (gpsLocation.isRecent() || !netLocation.isValid()) {
			return gpsLocation.isValid() ? gpsLocation : null;
		}
		if (!gpsLocation.isValid()) {
			return netLocation;
		}
		return gpsLocation.timestamp > netLocation.timestamp ? gpsLocation : netLocation;
	}

	private void selectBest() {
		assign(best());
	}

	private void assign(final LocationData locationData) {
		if (locationData == null) {
			return;
		}

		// We do not necessarily get signalled when satellites go to 0/0.
		final int visible = gpsLocation.isRecent() ? satellitesVisible : 0;
		final boolean pseudoLocation = StringUtils.equals(locationData.location.getProvider(), LAST_LOCATION_PSEUDO_PROVIDER);
		final IGeoData current = new GeoData(locationData.location, gpsEnabled, visible, satellitesFixed, pseudoLocation);
		subject.onNext(current);
	}

}


text:
require "randomiser/version.rb"
require "randomiser/dev/base"
require "randomiser/dev/generate_random_string"

module Randomiser
  # Your code goes here...
end


text:
title: XmlResolver Goodness
disqus_identifier: 2004-05-xmlresolver-goodness
comments: true
---

Today I was looking through the best way to transform some XML documents using XSLTs from a database instead of from a file system.

Typically, this would be no problem, via the following simple code:

``` csharp
XslTransform xsl = new XslTransform();
Stream strm = SomeMethodToLoadTheXslFromTheDatabase();
XmlTextReader rdr = new XmlTextReader(strm);
xsl.Load(rdr);
```

Now, the snag happens when you do an xsl:import or xsl:include in your XSLT. In this case, the XslTransform will try to load the specified file from the filesystem, which is obviously not what we want.

I started to panic a little bit while reading the MSDN documentation when all of the sudden, the XmlResolver class came to my rescue. The XmlResolver class resolves external XML resources named by a URI.

To resolve my problem, I ended up subclassing XmlUrlResolver and overriding the GetEntity method. The GetEntity method maps a URI to an object containing the actual resource. You're supposed to return a Stream out of it. The only changes to the original code is passing an instance of this custom Resolver to XslTransform.Load().

``` csharp
class MyResolver : XmlUrlResolver
{
    public override object GetEntity(Uri absoluteUri,
        string role, Type ofObjectToReturn)
    {
        string doc = Path.GetFileName(absoluteUri.AbsoluteUri);
        Stream strm = SomeMethodToLoadTheUriFromTheDatabase(doc);
    }
}

XslTransform xsl = new XslTransform();
Stream strm = SomeMethodToLoadTheXslFromTheDatabase();
XmlTextReader rdr = new XmlTextReader(strm);
xsl.Load(rdr, new MyResolver(), null);
```

This is a great little class to remember if you ever need to do something like this...


text:
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)

require 'simplecov'

SimpleCov.start do
  add_group 'Lib', 'lib'
  add_group 'Tests', 'spec'
end
SimpleCov.minimum_coverage 99

require 'ostruct'
require 'julia'


text:
require 'json'

require 'fuzzy_set'
require 'sinatra/base'
require 'slim'

require 'wikimd/renderer'
require 'wikimd/repository'

module WikiMD
  # Main Sinatra application
  class App < Sinatra::Base
    TYPE_MARKDOWN = %w(md mdown markdown)
    TYPE_TEXT = %w(txt rb js slim css scss coffee)

    # Use gzip compression
    use Rack::Deflater

    configure do
      # disable stuff not needed
      disable :method_override

      enable :sessions

      set :views, File.expand_path('../app/views', __FILE__)
      set :markdown_renderer, WikiMD::Renderer.build
      set :public_folder, File.expand_path('../app/public', __FILE__)

      set :fs_created, Time.new(0)
      set :fs, nil
      set(:repo) { WikiMD::Repository.new(settings.repo_path) }
    end

    # :nocov:
    configure :development do
      # settings for easier debugging
      Slim::Engine.set_options pretty: true, sort_attrs: false
      set :show_exceptions, :after_handler
    end
    # :nocov:

    helpers do
      # returns the URI for a static asset.
      #
      # @param name [#to_s] name of the asset file
      # @return [String] the full URI
      def asset_path(name)
        url("assets/#{name}")
      end

      # Include an Octicon! (see https://octicons.github.com/)
      #
      # @param name [#to_s] Name of the Octicon
      # @return [String] HTML Code for the Octicon
      def octicon(name)
        %()
      end

      # Get the directory-Tree from the root of the repo
      def tree_root
        repo.tree
      end

      # URL helper for the History page of a document
      #
      # @param path [String] relative path of the document in the Repository
      # @return [String] full URI to the history page
      def history_path(path)
        url('/h/' + path)
      end

      # URL helper for the Edit page of a document
      #
      # @param path [String] relative path of the document in the Repository
      # @return [String] full URI to the edit page
      def edit_path(path)
        url('/e/' + path)
      end

      # CSS class for a diff line
      #
      # @param line [String] the line in question
      # @return [String] "addition", if the line starts with "+", "removal" if
      #   the line starts with "-", nil otherwise.
      def class_for_diff(line)
        case line[0]
        when '+'
          'addition'
        when '-'
          'removal'
        end
      end
    end

    # If no route matches, render the 404 page
    not_found do
      @path = env['PATH_INFO'].sub(%r{^/([ceh]/)?}, '')
      slim :'404'
    end

    before do
      @flash = session[:flash]
      session[:flash] = nil
    end

    get('/') { redirect to('index.md') }

    post '/c/*' do |path|
      if (params[:compare] || []).length != 2
        session[:flash] = {
          'error' => 'Must select exactly 2 revisions!'
        }
        redirect to('/h/' + path)
      end

      @from, @to = params['compare'][1], params['compare'][0]
      begin
        @diff = repo.diff(path, @from, @to)
      rescue WikiMD::Repository::FileNotFound
        pass
      end

      @path = path
      slim :diff
    end

    # Quick/Fuzzy Search
    get '/search.json' do
      headers 'Content-Type' => 'application/json'
      files_set.get(params[:query]).to_json
    end

    # History Page
    get '/h/*' do |path|
      @path = path
      begin
        @history = repo.history(@path)
      rescue WikiMD::Repository::GitError
        @history = []
      end
      slim :history
    end

    # Update
    post '/e/*' do |path|
      repo.update(path, params[:content])
      session[:flash] = { 'info' => "'#{path}' has been saved!" }
      redirect to(path)
    end

    # Edit page
    get '/e/*' do |path|
      begin
        @content = repo.read(path)
      rescue WikiMD::Repository::FileNotFound
        pass
      end
      @path = path
      slim :edit
    end

    # Document Page
    get '/*' do |path|
      begin
        @content = repo.read(path, params[:at])
      rescue WikiMD::Repository::FileNotFound
        pass
      end
      @path = path
      @extension = (m = path.match(/(?:\.)([^.]+)$/)) ? m[1].downcase : ''
      slim :file
    end

    private

    # Render Markdown to HTML
    def render_markdown(markdown)
      settings.markdown_renderer.render(markdown)
    end

    # create or return Repository
    def repo
      settings.repo
    end

    # create or return the Search Index
    def files_set
      if settings.fs_created + 12 < Time.now
        settings.fs = FuzzySet.new(repo.files)
        settings.fs_created = Time.now
      end
      settings.fs
    end
  end
end


text:
"""Definition of BlobStorage base class."""

class BlobStorage(object):
  """Base class for defining how blobs are stored.

  This base class merely defines an interface that all stub blob-storage
  mechanisms must implement.
  """

  def StoreBlob(self, blob_key, blob_stream):
    """Store blob stream.

    Implement this method to persist blob data.

    Args:
      blob_key: Blob key of blob to store.
      blob_stream: Stream or stream-like object that will generate blob content.
    """
    raise NotImplementedError('Storage class must override StoreBlob method.')

  def OpenBlob(self, blob_key):
    """Open blob for streaming.

    Args:
      blob_key: Blob-key of existing blob to open for reading.

    Returns:
      Open file stream for reading blob. Caller is responsible for closing file.
    """
    raise NotImplementedError('Storage class must override OpenBlob method.')

  def DeleteBlob(self, blob_key):
    """Delete blob data from storage.

    Args:
      blob_key: Blob-key of existing blob to delete.
    """
    raise NotImplementedError('Storage class must override DeleteBlob method.')


text:
using System;
using System.Linq;
using System.Threading;
using System.Collections.Generic;
using System.Collections.Concurrent;

namespace System.Linq.Parallel.QueryNodes
{
	internal class QueryReverseNode<TSource> : QueryStreamNode<TSource, TSource>
	{
		ParallelQuery<TSource> source;

		public QueryReverseNode (ParallelQuery<TSource> source)
			: base (source.Node, false)
		{
			this.source = source;
		}

		internal override IEnumerable<TSource> GetSequential ()
		{
			return Parent.GetSequential ().Reverse ();
		}

		// As stated in the doc, in this case we do nothing
		internal override IList<IEnumerable<TSource>> GetEnumerables (QueryOptions options)
		{
			return Parent.GetEnumerables (options);
		}

		internal override IList<IEnumerable<KeyValuePair<long, TSource>>> GetOrderedEnumerables (QueryOptions options)
		{
			ReverseList<TSource> reversed = new ReverseList<TSource> (source.ToListOrdered ());
			OrderablePartitioner<TSource> partitioner = ParallelPartitioner.CreateForStrips (reversed, 1);

			return WrapHelper.Wrap (partitioner.GetOrderablePartitions (options.PartitionCount));
		}
	}
}

#endif


text:
import styled from "styled-components";
import React from "react";

const Form = styled.div``;

const Row = styled.div``;

const Label = styled.label`
  display: inline-block;
  min-width: 5rem;
  font-weight: bold;
`;

const Input = styled.input`
  line-height: 2.2rem;
`;

interface Props {
  types: { [key: string]: string };
  value: { [key: string]: any };
  onChange: (value: any) => void;
  onBlur: () => void;
}

class PropertiesForm extends React.Component<Props> {
  public static defaultProps: Props = {
    types: {},
    value: {},
    onChange: () => {},
    onBlur: () => {},
  };

  render() {
    const types = this.props.types;
    const values = this.props.value;

    return (
      <Form>
        {Object.keys(types).map((name) => {
          const type = types[name];
          let inputType = "";
          let onChange = this.bindValue.bind(this);
          if (type === "string") {
            inputType = "text";
          } else if (type === "number") {
            inputType = "number";
          } else if (type === "boolean") {
            inputType = "checkbox";

            // Settings are saved onBlur, but checkbox does not fire it
            onChange = (e) => {
              this.bindValue(e);
              this.props.onBlur();
            };
          } else {
            return null;
          }
          return (
            <Row key={name}>
              <Label>
                <span>{name}</span>
                <Input
                  type={inputType}
                  name={name}
                  value={values[name] ? values[name] : ""}
                  onChange={onChange}
                  onBlur={this.props.onBlur}
                  checked={values[name]}
                />
              </Label>
            </Row>
          );
        })}
      </Form>
    );
  }

  bindValue(e: React.ChangeEvent<HTMLInputElement>) {
    const name = e.target.name;
    const next = { ...this.props.value };
    if (e.target.type.toLowerCase() === "checkbox") {
      next[name] = e.target.checked;
    } else if (e.target.type.toLowerCase() === "number") {
      next[name] = Number(e.target.value);
    } else {
      next[name] = e.target.value;
    }

    this.props.onChange(next);
  }
}

export default PropertiesForm;


text:
package org.jasig.portlet.notice.action.read;

import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletPreferences;
import javax.portlet.PortletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.builder.HashCodeBuilder;
import org.jasig.portlet.notice.NotificationEntry;
import org.jasig.portlet.notice.NotificationState;
import org.jasig.portlet.notice.filter.ReadStateAction;
import org.jasig.portlet.notice.rest.EventDTO;
import org.jasig.portlet.notice.util.JpaServices;
import org.jasig.portlet.notice.util.SpringContext;
import org.jasig.portlet.notice.util.UsernameFinder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ReadAction extends ReadStateAction {

    private static final long serialVersionUID = 1L;

    protected static Logger logger = LoggerFactory.getLogger(ReadAction.class);

    /**
     * This INSTANCE is only for convenience -- READ and UNREAD not singletons.
     * There may be situations where de-serialization will create additional
     * instances, and that's okay.
     */
    public static final ReadAction READ = new ReadAction();

    /**
     * Stores the Ids of read notices.
     */
    private static final String READ_NOTIFICATION_IDS_PREFERENCE =
            ReadAction.class.getName() + ".READ_NOTIFICATION_IDS_PREFERENCE";

    /**
     * Must remain public, no-arg for de-serialization.
     */
    public ReadAction() {
        // Set a default label;  most use cases will use the setter and override
        setLabel("MARK AS READ");
    }

    public ReadAction(String label){
        setLabel(label);
    }

    public static final ReadAction createReadInstance() {
        return new ReadAction();
    }

    public static final ReadAction createUnReadInstance() {
        return new ReadAction("MARK AS UNREAD");
    }

    /**
     * Invoking a ReadAction toggles it.
     */
    @Override
    public void invoke(final ActionRequest req, final ActionResponse res) throws IOException {
        final NotificationEntry entry = getTarget();
        final String notificationId = entry.getId();
        final Set<String> readNotices = this.getReadNotices(req);
        if (readNotices.contains(notificationId)) {
            readNotices.remove(notificationId);
        } else {
            readNotices.add(notificationId);
        }
        setReadNotices(req, readNotices);
    }

    @Override
    public void invoke(HttpServletRequest request, HttpServletResponse response) throws IOException {
        final NotificationEntry entry = getTarget();
        final String username =
                ((UsernameFinder) SpringContext.getApplicationContext().getBean("usernameFinder"))
                        .findUsername(request);
        if (!isRead(entry, username)) {
            // NB:  Currently there is no way to un-apply the READ state
            final JpaServices jpaServices = (JpaServices) SpringContext.getApplicationContext().getBean("jpaServices");
            jpaServices.applyState(entry, username, NotificationState.READ);
        }
    }

    @Override
    public int hashCode(){
        return new HashCodeBuilder(17, 31).
                append(super.getId()).
                toHashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        // At present, any instance ReadAction is equal to another
        return true;
    }

    public void removeReadNotices (final PortletRequest req, Set<String> idsToRemove) {
        Set<String> currentIds = getReadNotices(req);
        currentIds.removeAll(idsToRemove);
        setReadNotices(req, currentIds);
    }

    /*
     * Non-public API
     */

    /* package-private */ Set<String> getReadNotices(final PortletRequest req) {
        final HashSet<String> rslt = new HashSet<>();
        final PortletPreferences prefs = req.getPreferences();
        final String[] ids = prefs.getValues(READ_NOTIFICATION_IDS_PREFERENCE, new String[0]);
        for (int i=0; i < ids.length; i++) {
            rslt.add(ids[i]);
        }
        return rslt;
    }

    /* package-private */ void setReadNotices(final PortletRequest req, final Set<String> favoriteNotices) {
        final String[] ids = favoriteNotices.toArray(new String[favoriteNotices.size()]);
        final PortletPreferences prefs = req.getPreferences();
        try {
            prefs.setValues(READ_NOTIFICATION_IDS_PREFERENCE, ids);
            prefs.store();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    protected boolean isRead(NotificationEntry entry, String username) {

        final JpaServices jpaServices = (JpaServices) SpringContext.getApplicationContext().getBean("jpaServices");
        final List<EventDTO> history = jpaServices.getHistory(entry, username);

        boolean rslt = false;  // default (clearly)

        // Review the history...
        for (EventDTO event : history) {
            if (NotificationState.READ.equals(event.getState())) {
                logger.debug("Found a READ event:  {}", event);
                rslt = true;
                // NB:  Currently there is no way to un-apply the READ state
                break;
            }
        }

        return rslt;

    }

}


text:
layout: default
---

    {% include box.html section=site.data.sections.about %}
    {% include box.html section=site.data.sections.projects %}

    {% include box.html section=site.data.sections.resume %}
    {% include box.html section=site.data.sections.contact %}


text:
"""Super class of comment and post item"""

from scrapy.item import Item

class ObjectItem(Item):
  """Extends Scrapy Item interface to be usable with the standard object
  attribute notation.

    >>> from scrapy.item import Field
    >>> class I(ObjectItem):
    ...   myField = Field()
    >>> i = I()
    >>> i.myField = 1
    >>> i.myField
    1
    >>> try:
    ...   i.notAField
    ... except KeyError:
    ...   pass
    ... else:
    ...   fail
  """

  def __setattr__(self, key, value):
    """Sets a fild of the item using object attribute notation."""
    if key in self.fields:
      super(ObjectItem, self).__setitem__(key, value)
    else:
      super(ObjectItem, self).__setattr__(key, value)

  def __getattr__(self, key):
    """Gets a fild of the item using object attribute notation."""
    # This is enough because __getattr__ is a fallback...
    return self[key]


text:
We tried to keep the test/exercise as simple as we could trying to be able to determine whether we will work fine together or not.

## The Code

The test is based in symfony and we used a basic instalation without much plugins, feel free to add as much plugins/bundles as you require.

Everything you see is open to comments/valorations from your part, we will be glad to hear your comments!!

### Installation

We tried to include all the tools necessary to do the test here, that's why we have composer.phar into the repo for example, so the installation is quite simple.
The only external thing you will need is a Mysql server somewhere, as you can use symfony's bundled server if needed, but feel free to use the stack you prefer.

The steps to start with the test are:

1. Clone this repository

2. Execute composer to install the required dependencies. (You will be required with some information, mainly about the mysql configuration)

3. Execute npm install to install all js required dependecies.

4. We have provided you with a fully functional webpack setup. To make it work, just execute npm start. This will run a webpack-dev-server for frontend renderind and a webpack --watch for server rendering.

5. Do an empty commit with the message "I'm ready to start" for us to know the timing.

6. Ready to go!!

## The Test

There are two small user stories we'll like you to implement on the test. If you had any doubt make the assumptions you need, and just comment them as a comment on your pull request.

### User Story

1. Right now our blog lets everyone create authors and write posts. We want to add a security layer to avoid this. The user has to be able to:
    * **Register:** Will need to introduce his name, email, password. A registered user has to act as an author.
    * **Login:** Will be able to login using his email and password.
    * **Write Posts:** Once logged in the user will be able to write posts. Right now we can assign the autorship of a blogpost to any user. We don't want this anymore. The user who writes a post will need to be its author

### How to deliver

We ask you to deliver a pull request to this same repository with your solution to the specified user stories.

### Notes
* We encourage you to make as much commits as possible with meaninful messages instead of one big bang commit at the end.
* The blog design is quite nice. Please don't screw it up with awful styles.
* Write as much tests as you feel. This test is using PHPUnit + Jest/Enzyme but if you prefer another solution feel free to use it.
* If you use vagrant, docker or any other solution please include the config files so we can take a look.
* Use [symfony 2 coding standards](http://symfony.com/doc/current/contributing/code/standards.html).
* Use [airbnb javascript style guide](https://github.com/airbnb/javascript).
* Usage of ES6 is highly encouraged.
* If you see something you don't like in the code feel free to improve it.


text:
package edu.ucdenver.ccp.datasource.identifiers.impl.bio;

import edu.ucdenver.ccp.datasource.fileparsers.CcpExtensionOntology;

import edu.ucdenver.ccp.datasource.identifiers.DataSource;
import edu.ucdenver.ccp.datasource.identifiers.Identifier;
import edu.ucdenver.ccp.datasource.identifiers.StringDataSourceIdentifier;

/**
 *
 * Represents an ID from the International Molecular Exchange Consortium
 *
 * (http://www.imexconsortium.org/)
 *
 *
 *
 * @author
 *
 *
 */

@Identifier(ontClass=CcpExtensionOntology.IMEX_IDENTIFIER)
public class ImexId extends StringDataSourceIdentifier {

	public ImexId(String resourceID) {

		super(resourceID, DataSource.IMEX);
}

}


text:
package io.crnk.example.springboot.microservice;

import io.crnk.example.springboot.microservice.project.ProjectApplication;
import io.crnk.example.springboot.microservice.task.TaskApplication;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ConfigurableApplicationContext;

import java.util.HashMap;
import java.util.Map;

/**
 * Launches both micro services within the same JVM for demonstration purposes.
 */
public class MicroServiceApplication {

	public static final Integer TASK_PORT = 12001;

	public static final Integer PROJECT_PORT = 12002;

	public static ConfigurableApplicationContext startTaskApplication() {
		Map<String, Object> taskProperties = new HashMap<>();
		taskProperties.put("server.port", Integer.toString(TASK_PORT));
		SpringApplication taskApp = new SpringApplication(TaskApplication.class);
		taskApp.setDefaultProperties(taskProperties);
		return taskApp.run();
	}

	public static ConfigurableApplicationContext startProjectApplication() {
		Map<String, Object> projectProperties = new HashMap<>();
		projectProperties.put("server.port", Integer.toString(PROJECT_PORT));
		SpringApplication projectApp = new SpringApplication(ProjectApplication.class);
		projectApp.setDefaultProperties(projectProperties);
		return projectApp.run();
	}

	public static void main(String[] args) {
		startTaskApplication();
		startProjectApplication();
		System.out.println("visit http://127.0.0.1:12001/ and  http://127.0.0.1:12002/ in your browser");
	}
}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="EXTRA bool: "
            />

        <TextView
            android:id="@+id/extra_boolean_val_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="EXTRA String: "
            />

        <TextView
            android:id="@+id/extra_string_val_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="EXTRA flaot: "
            />

        <TextView
            android:id="@+id/extra_float_val_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="EXTRA string array: "
            />

        <TextView
            android:id="@+id/extra_string_aray_val_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />
    </LinearLayout>

</LinearLayout>


text:
"""Shorthand notations for physical constants

This module is using scipy.constants.physical_constants.
All constants are in SI units in order to allow for arbitrary
conversions between them.
"""

from scipy.constants import physical_constants

# Energies
eV = physical_constants['electron volt-joule relationship'][0]
Ha = physical_constants['Hartree energy'][0]
Ry = Ha / 2.0

# Distances
a0 = physical_constants['Bohr radius'][0]
Angstrom = 1e-10


text: for (const x in x) {} // error: can not reference undeclared x in right-hand expr


text: Mia's phase 0 github pages site


text:
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;

namespace DSharpPlus.VoiceNext.Codec
{
    internal sealed class Sodium : IDisposable
    {
        public static IReadOnlyDictionary<string, EncryptionMode> SupportedModes { get; }

        public static int NonceSize => Interop.SodiumNonceSize;

        private RandomNumberGenerator CSPRNG { get; }
        private byte[] Buffer { get; }
        private ReadOnlyMemory<byte> Key { get; }

        static Sodium()
        {
            SupportedModes = new ReadOnlyDictionary<string, EncryptionMode>(new Dictionary<string, EncryptionMode>()
            {
                ["xsalsa20_poly1305_lite"] = EncryptionMode.XSalsa20_Poly1305_Lite,
                ["xsalsa20_poly1305_suffix"] = EncryptionMode.XSalsa20_Poly1305_Suffix,
                ["xsalsa20_poly1305"] = EncryptionMode.XSalsa20_Poly1305
            });
        }

        public Sodium(ReadOnlyMemory<byte> key)
        {
            if (key.Length != Interop.SodiumKeySize)
                throw new ArgumentException($"Invalid Sodium key size. Key needs to have a length of {Interop.SodiumKeySize} bytes.", nameof(key));

            this.Key = key;

            this.CSPRNG = RandomNumberGenerator.Create();
            this.Buffer = new byte[Interop.SodiumNonceSize];
        }

        public void GenerateNonce(ReadOnlySpan<byte> rtpHeader, Span<byte> target)
        {
            if (rtpHeader.Length != Rtp.HeaderSize)
                throw new ArgumentException($"RTP header needs to have a length of exactly {Rtp.HeaderSize} bytes.", nameof(rtpHeader));

            if (target.Length != Interop.SodiumNonceSize)
                throw new ArgumentException($"Invalid nonce buffer size. Target buffer for the nonce needs to have a capacity of {Interop.SodiumNonceSize} bytes.", nameof(target));

            // Write the header to the beginning of the span.
            rtpHeader.CopyTo(target);

            // Zero rest of the span.
            Helpers.ZeroFill(target.Slice(rtpHeader.Length));
        }

        public void GenerateNonce(Span<byte> target)
        {
            if (target.Length != Interop.SodiumNonceSize)
                throw new ArgumentException($"Invalid nonce buffer size. Target buffer for the nonce needs to have a capacity of {Interop.SodiumNonceSize} bytes.", nameof(target));

            this.CSPRNG.GetBytes(this.Buffer);
            this.Buffer.AsSpan().CopyTo(target);
        }

        public void GenerateNonce(uint nonce, Span<byte> target)
        {
            if (target.Length != Interop.SodiumNonceSize)
                throw new ArgumentException($"Invalid nonce buffer size. Target buffer for the nonce needs to have a capacity of {Interop.SodiumNonceSize} bytes.", nameof(target));

            // Write the uint to memory
            BinaryPrimitives.WriteUInt32BigEndian(target, nonce);

            // Zero rest of the buffer.
            Helpers.ZeroFill(target.Slice(4));
        }

        public void AppendNonce(ReadOnlySpan<byte> nonce, Span<byte> target, EncryptionMode encryptionMode)
        {
            switch (encryptionMode)
            {
                case EncryptionMode.XSalsa20_Poly1305:
                    return;

                case EncryptionMode.XSalsa20_Poly1305_Suffix:
                    nonce.CopyTo(target.Slice(target.Length - 12));
                    return;

                case EncryptionMode.XSalsa20_Poly1305_Lite:
                    nonce.Slice(0, 4).CopyTo(target.Slice(target.Length - 4));
                    return;

                default:
                    throw new ArgumentException("Unsupported encryption mode.", nameof(encryptionMode));
            }
        }

        public void GetNonce(ReadOnlySpan<byte> source, Span<byte> target, EncryptionMode encryptionMode)
        {
            if (target.Length != Interop.SodiumNonceSize)
                throw new ArgumentException($"Invalid nonce buffer size. Target buffer for the nonce needs to have a capacity of {Interop.SodiumNonceSize} bytes.", nameof(target));

            switch (encryptionMode)
            {
                case EncryptionMode.XSalsa20_Poly1305:
                    source.Slice(0, 12).CopyTo(target);
                    return;

                case EncryptionMode.XSalsa20_Poly1305_Suffix:
                    source.Slice(source.Length - Interop.SodiumNonceSize).CopyTo(target);
                    return;

                case EncryptionMode.XSalsa20_Poly1305_Lite:
                    source.Slice(source.Length - 4).CopyTo(target);
                    return;

                default:
                    throw new ArgumentException("Unsupported encryption mode.", nameof(encryptionMode));
            }
        }

        public void Encrypt(ReadOnlySpan<byte> source, Span<byte> target, ReadOnlySpan<byte> nonce)
        {
            if (nonce.Length != Interop.SodiumNonceSize)
                throw new ArgumentException($"Invalid nonce size. Nonce needs to have a length of {Interop.SodiumNonceSize} bytes.", nameof(nonce));

            if (target.Length != Interop.SodiumMacSize + source.Length)
                throw new ArgumentException($"Invalid target buffer size. Target buffer needs to have a length that is a sum of input buffer length and Sodium MAC size ({Interop.SodiumMacSize} bytes).", nameof(target));

            int result;
            if ((result = Interop.Encrypt(source, target, this.Key.Span, nonce)) != 0)
                throw new CryptographicException($"Could not encrypt the buffer. Sodium returned code {result}.");
        }

        public void Decrypt(ReadOnlySpan<byte> source, Span<byte> target, ReadOnlySpan<byte> nonce)
        {
            if (nonce.Length != Interop.SodiumNonceSize)
                throw new ArgumentException($"Invalid nonce size. Nonce needs to have a length of {Interop.SodiumNonceSize} bytes.", nameof(nonce));

            if (target.Length != source.Length - Interop.SodiumMacSize)
                throw new ArgumentException($"Invalid target buffer size. Target buffer needs to have a length that is input buffer decreased by Sodium MAC size ({Interop.SodiumMacSize} bytes).", nameof(target));

            int result;
            if ((result = Interop.Decrypt(source, target, this.Key.Span, nonce)) != 0)
                throw new CryptographicException($"Could not decrypt the buffer. Sodium returned code {result}.");
        }

        public void Dispose()
        {
            this.CSPRNG.Dispose();
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static KeyValuePair<string, EncryptionMode> SelectMode(IEnumerable<string> availableModes)
        {
            foreach (var kvMode in SupportedModes)
                if (availableModes.Contains(kvMode.Key))
                    return kvMode;

            throw new CryptographicException("Could not negotiate Sodium encryption modes, as none of the modes offered by Discord are supported. This is usually an indicator that something went very wrong.");
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static int CalculateTargetSize(ReadOnlySpan<byte> source)
            => source.Length + Interop.SodiumMacSize;

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static int CalculateSourceSize(ReadOnlySpan<byte> source)
            => source.Length - Interop.SodiumMacSize;
    }

    /// <summary>
    /// Specifies an encryption mode to use with Sodium.
    /// </summary>
    public enum EncryptionMode
    {
        /// <summary>
        /// The nonce is an incrementing uint32 value. It is encoded as big endian value at the beginning of the nonce buffer. The 4 bytes are also appended at the end of the packet.
        /// </summary>
        XSalsa20_Poly1305_Lite,

        /// <summary>
        /// The nonce consists of random bytes. It is appended at the end of a packet.
        /// </summary>
        XSalsa20_Poly1305_Suffix,

        /// <summary>
        /// The nonce consists of the RTP header. Nothing is appended to the packet.
        /// </summary>
        XSalsa20_Poly1305
    }
}


text:
"""Head (logits and sampling) blocks."""

from typing import Sequence

from alphastar import types
from alphastar.architectures import modular
from alphastar.architectures import util
from alphastar.architectures.components import common
from alphastar.architectures.components import merge
from alphastar.architectures.components import units
from alphastar.architectures.components import vector
from alphastar.architectures.components import visual
import jax.numpy as jnp
import ml_collections

def _get_sampling(argument_name: types.ArgumentName,
                  num_logits: int,
                  is_training: bool,
                  config: ml_collections.ConfigDict) -> modular.Component:
  """Sampling module during inference, or teacher forcing during training."""
  if is_training:
    return common.ActionFromBehaviourFeatures(
        name="action_from_behaviour_features",
        argument_name=argument_name,
        max_action_value=num_logits - 1)
  else:
    return common.Sample(
        name="sample",
        argument_name=argument_name,
        num_logits=num_logits,
        **config.sample)

def get_vector_head(argument_name: types.ArgumentName,
                    action_spec: types.ActionSpec,
                    vector_stream_size: int,
                    is_training: bool,
                    overlap_len: int,
                    config: ml_collections.ConfigDict
                    ) -> modular.Component:
  """Produce logits and action for an argument and embed it to vector_stream."""
  num_logits = action_spec[argument_name].maximum + 1
  component = modular.SequentialComponent(name=f"{argument_name}_head")
  component.append(vector.Resnet(
      name="resnet",
      input_size=vector_stream_size,
      input_name="vector_stream",
      output_name=f"{argument_name}_logits_vector_stream",
      **config.resnet))
  component.append(vector.Logits(
      name="logits",
      logits_output_name=("logits", argument_name),
      mask_output_name=("masks", argument_name),
      num_logits=num_logits,
      input_size=vector_stream_size,
      input_name=f"{argument_name}_logits_vector_stream",
      **config.logits))
  component.append(_get_sampling(
      argument_name=argument_name,
      num_logits=num_logits,
      is_training=is_training,
      config=config.sampling))
  if argument_name == util.Argument.FUNCTION:
    component.append(common.ArgumentMasks(
        name="argument_masks",
        action_spec=action_spec))
  component.append(common.FeatureToNextState(
      name="action_to_next_state",
      input_name=("action", argument_name),
      output_name=("action", argument_name),
      stream_shape=(),
      stream_dtype=jnp.int32,
      overlap_len=overlap_len))
  component.append(vector.Embedding(
      name="action_embedding",
      input_name=("action", argument_name),
      output_name=f"{argument_name}_embedding",
      mask_name=("argument_masks", argument_name),
      num_classes=num_logits,
      output_size=vector_stream_size))
  component.append(merge.VectorMerge(
      name="embedding_merge",
      input_sizes={"vector_stream": vector_stream_size,
                   f"{argument_name}_embedding": vector_stream_size},
      output_name="vector_stream",
      output_size=vector_stream_size,
      **config.embedding_merge))
  return component

def get_unit_tags_head(obs_spec: types.ObsSpec,
                       action_spec: types.ActionSpec,
                       vector_stream_size: int,
                       units_stream_size: int,
                       is_training: bool,
                       config: ml_collections.ConfigDict) -> modular.Component:
  """Produce logits and action for unit_tags and embed it to vector_stream."""
  num_logits = action_spec["unit_tags"].maximum + 1
  max_num_selected_units = action_spec["unit_tags"].shape[0]
  max_num_observed_units = obs_spec["raw_units"].shape[0]
  assert num_logits == max_num_observed_units + 1
  inner_component = modular.SequentialComponent(name="inner_component")
  inner_component.append(units.PointerLogits(
      name="logits",
      max_num_observed_units=max_num_observed_units,
      num_raw_unit_features=obs_spec["raw_units"].shape[1],
      logits_output_name=("pre_logits", util.Argument.UNIT_TAGS),
      mask_output_name=("pre_masks", util.Argument.UNIT_TAGS),
      query_input_size=vector_stream_size,
      keys_input_size=config.keys_mlp.layer_sizes[-1],
      key_size=config.keys_mlp.layer_sizes[-1],
      unit_tags_masking=units.UnitTagsMasking.SELECTABLE,
      query_input_name="unit_tags_query",
      keys_input_name="unit_tags_keys",
      **config.inner_component.logits))
  inner_component.append(units.FinalizeUnitTagsLogits(
      name="finalize_unit_tags_logits",
      input_logits_name=("pre_logits", util.Argument.UNIT_TAGS),
      input_mask_name=("pre_masks", util.Argument.UNIT_TAGS),
      output_logits_name=("logits", util.Argument.UNIT_TAGS),
      output_mask_name=("masks", util.Argument.UNIT_TAGS),
      max_num_observed_units=max_num_observed_units,
      vector_input_name="unit_tags_query",
      vector_input_size=vector_stream_size))
  inner_component.append(_get_sampling(
      argument_name=util.Argument.UNIT_TAGS,
      num_logits=num_logits,
      is_training=is_training,
      config=config.inner_component.sampling))
  inner_component.append(units.PointerEmbedding(
      name="embedding",
      num_embeddings=max_num_observed_units,
      embeddings_size=config.small_embeddings_mlp.layer_sizes[-1],
      index_input_name=("action", util.Argument.UNIT_TAGS),
      embeddings_input_name="small_unit_tag_embeddings",
      output_name="unit_tags_embedding"))
  inner_component.append(merge.VectorMerge(
      name="embedding_merge",
      input_sizes={
          "unit_tags_query": vector_stream_size,
          "unit_tags_embedding": config.small_embeddings_mlp.layer_sizes[-1]},
      output_name="unit_tags_query",
      output_size=vector_stream_size,
      **config.inner_component.embedding_merge))

  component = modular.SequentialComponent(name="unit_tag_head")
  component.append(vector.Resnet(
      name="query_resnet",
      input_size=vector_stream_size,
      input_name="vector_stream",
      output_name="unit_tags_query",
      **config.query_resnet))
  component.append(units.MLP(
      name="keys_mlp",
      max_num_observed_units=max_num_observed_units,
      units_stream_size=units_stream_size,
      input_name="units_stream",
      output_name="unit_tags_keys",
      **config.keys_mlp))
  component.append(units.MLP(
      name="small_embeddings_mlp",
      max_num_observed_units=max_num_observed_units,
      units_stream_size=units_stream_size,
      input_name="units_stream",
      output_name="small_unit_tag_embeddings",
      **config.small_embeddings_mlp))
  component.append(units.MLP(
      name="large_embeddings_mlp",
      max_num_observed_units=max_num_observed_units,
      units_stream_size=units_stream_size,
      input_name="units_stream",
      output_name="large_unit_tag_embeddings",
      **config.large_embeddings_mlp))
  unit_tags_head_per_step_inputs = []
  if is_training:
    unit_tags_head_per_step_inputs.append(
        ("behaviour_features", "action", util.Argument.UNIT_TAGS))
  component.append(units.UnitTagsHead(
      name="recurrent_unit_tags_head",
      inner_component=inner_component,
      constant_inputs=["unit_tags_keys",
                       "small_unit_tag_embeddings",
                       ("observation", "raw_units")],
      carries=["unit_tags_query"],
      per_step_inputs=unit_tags_head_per_step_inputs,
      per_step_outputs=[("logits", util.Argument.UNIT_TAGS),
                        ("masks", util.Argument.UNIT_TAGS),
                        ("action", util.Argument.UNIT_TAGS)],
      max_num_selected_units=max_num_selected_units,
      max_num_observed_units=max_num_observed_units,
      action_output=("action", util.Argument.UNIT_TAGS)))
  component.append(units.BinaryVectorPointerEmbedding(
      name="embedding",
      num_embeddings=max_num_observed_units,
      embeddings_size=config.large_embeddings_mlp.layer_sizes[-1],
      mask_input_name="selected_unit_tags",
      embeddings_input_name="large_unit_tag_embeddings",
      output_name="unit_tags_embedding"))
  component.append(merge.VectorMerge(
      name="embedding_merge",
      input_sizes={
          "vector_stream": vector_stream_size,
          "unit_tags_embedding": config.large_embeddings_mlp.layer_sizes[-1]},
      output_name="vector_stream",
      output_size=vector_stream_size,
      **config.embedding_merge))
  component.append(merge.UnitsMerge(
      name="selected_units_merge",
      input_sizes={"units_stream": units_stream_size,
                   "selected_unit_tags": None},
      input_dtypes={"selected_unit_tags": jnp.bool_},
      max_num_observed_units=max_num_observed_units,
      output_name="units_stream_after_embedding",
      output_size=units_stream_size,
      **config.selected_units_merge))
  return component

def get_target_unit_tag_head(obs_spec: types.ObsSpec,
                             action_spec: types.ActionSpec,
                             vector_stream_size: int,
                             units_stream_size: int,
                             is_training: bool,
                             config: ml_collections.ConfigDict
                             ) -> modular.Component:
  """Produce logits and action for target_unit_tag."""
  num_logits = action_spec["target_unit_tag"].maximum + 1
  assert num_logits == obs_spec["raw_units"].shape[0]
  component = modular.SequentialComponent(name="target_unit_tag_head")
  component.append(vector.Resnet(
      name="resnet",
      input_size=vector_stream_size,
      input_name="vector_stream",
      output_name="target_unit_tag_query",
      **config.resnet))
  component.append(units.PointerLogits(
      name="logits",
      max_num_observed_units=obs_spec["raw_units"].shape[0],
      num_raw_unit_features=obs_spec["raw_units"].shape[1],
      logits_output_name=("logits", util.Argument.TARGET_UNIT_TAG),
      mask_output_name=("masks", util.Argument.TARGET_UNIT_TAG),
      query_input_size=vector_stream_size,
      keys_input_size=units_stream_size,
      unit_tags_masking=units.UnitTagsMasking.TARGETABLE_WITH_CAMERA,
      query_input_name="target_unit_tag_query",
      keys_input_name="units_stream_after_embedding",
      **config.logits))
  component.append(_get_sampling(
      argument_name=util.Argument.TARGET_UNIT_TAG,
      num_logits=num_logits,
      is_training=is_training,
      config=config.sampling))
  return component

def get_world_head(obs_spec: types.ObsSpec,
                   action_spec: types.ActionSpec,
                   vector_stream_size: int,
                   visual_stream_sizes: Sequence[int],
                   is_training: bool,
                   config: ml_collections.ConfigDict
                   ) -> modular.Component:
  """Produce logits and action for an argument and embed it to vector stream."""
  num_logits = action_spec["world"].maximum + 1
  world_size = util.get_world_size(action_spec)
  spatial_size = obs_spec["minimap_height_map"].shape[0]
  component = modular.SequentialComponent(name="world_head")
  full_downscale_factor = (
      config.visual_upscale.upscale_factor ** len(visual_stream_sizes))
  component.append(vector.ToVisual(
      name="vector_to_visual",
      input_name="vector_stream",
      output_name=f"visual_stream_ds{full_downscale_factor}_from_vector",
      input_size=vector_stream_size,
      output_spatial_size=spatial_size // full_downscale_factor,
      output_features_size=visual_stream_sizes[-1],
      **config.vector_to_visual))
  component.append(merge.SumMerge(
      name="vector_to_visual_merge",
      input_names=[
          f"visual_stream_ds{full_downscale_factor}_from_vector",
          f"visual_stream_ds{full_downscale_factor}"],
      output_name=f"visual_stream_ds{full_downscale_factor}",
      stream_shape=(spatial_size // full_downscale_factor,
                    spatial_size // full_downscale_factor,
                    visual_stream_sizes[-1]),
      ))
  component.append(visual.Resnet(
      name="resnet",
      input_name=f"visual_stream_ds{full_downscale_factor}",
      output_name=f"visual_stream_ds{full_downscale_factor}",
      input_spatial_size=spatial_size // full_downscale_factor,
      input_features_size=visual_stream_sizes[-1],
      **config.resnet))
  for i in range(len(visual_stream_sizes) - 1, 0, -1):
    us = config.visual_upscale.upscale_factor
    ids = int(us**(i + 1))  # input downsampling factor
    ods = int(us**i)  # output downsampling factor
    component.append(visual.Upscale(
        name=f"downscale_ds{ods}",
        input_name=f"visual_stream_ds{ids}",
        output_name=f"visual_stream_ds{ods}_upsample",
        input_spatial_size=spatial_size // ids,
        input_features_size=visual_stream_sizes[i],
        output_features_size=visual_stream_sizes[i - 1],
        **config.visual_upscale))
    component.append(merge.SumMerge(
        name=f"visual_head_merge_ds{ods}",
        input_names=[
            f"visual_stream_ds{ods}", f"visual_stream_ds{ods}_upsample"],
        output_name=f"visual_stream_ds{ods}",
        stream_shape=(spatial_size // ods,
                      spatial_size // ods,
                      visual_stream_sizes[i - 1]),
        ))
  component.append(visual.Upscale(
      name="downscale_ds1",
      input_name=f"visual_stream_ds{ods}",
      output_name="visual_stream_ds1",
      input_spatial_size=spatial_size // ods,
      input_features_size=visual_stream_sizes[0],
      output_features_size=config.visual_feature_size_ds1,
      **config.visual_upscale))
  component.append(visual.Logits(
      name="logits",
      input_name="visual_stream_ds1",
      input_spatial_size=spatial_size,
      input_features_size=config.visual_feature_size_ds1,
      logits_output_name=("logits", util.Argument.WORLD),
      mask_output_name=("masks", util.Argument.WORLD),
      upscale_factor=world_size // spatial_size,
      kernel_size=world_size // spatial_size,
      **config.logits))
  component.append(_get_sampling(
      argument_name=util.Argument.WORLD,
      num_logits=num_logits,
      is_training=is_training,
      config=config.sampling))
  return component


text:
This library converts absolute JavaScript module paths to relative.

## Installation
yarn: `yarn add --dev absolute-path-converter`

npm: `npm install --save-dev absolute-path-converter`

## Build pipeline integration

Just run `abspath` after any script that you use to build your app. For example:

```
"build": "tsc && abspath"
```

The example script first compiles - in this case TypeScript - source files containing internal imports (i.e. modules outside node_modules) with absolute paths. As TypeScript does not transform import paths, we need to transform the internal import paths from absolute to relative in order for Node to be able to execute our app.

There are many ways to transform the paths, and the most suitable method depends on the project. For frontend projects, I recommend using Babel and/or Webpack for the path transformation. This project targets mainly TypeScript projects for backend, where there is usually no need for heavyweight tools such as Babel and Webpack.


text:
package io.github.andreybgm.gigreminder.repository.db.entity;

import android.content.ContentValues;
import android.database.Cursor;

import java.util.Date;

import io.github.andreybgm.gigreminder.data.Artist;
import io.github.andreybgm.gigreminder.data.Location;
import io.github.andreybgm.gigreminder.data.SyncState;
import io.github.andreybgm.gigreminder.repository.DataSource;
import io.github.andreybgm.gigreminder.repository.db.Contract.SyncStatesTable;
import io.github.andreybgm.gigreminder.repository.db.DbUtils;

public class SyncStateEntity extends BaseEntity<SyncState> {

    private static final String[] PROJECTION = new String[]{
            SyncStatesTable.COLUMN_ARTIST_ID,
            SyncStatesTable.COLUMN_LOCATION_ID,
            SyncStatesTable.COLUMN_LAST_SYNC_TIME
    };

    public SyncStateEntity(DataSource dataSource) {
        super(dataSource);
    }

    @Override
    public String getTableName() {
        return SyncStatesTable.TABLE_NAME;
    }

    @Override
    public String[] getProjection() {
        return PROJECTION;
    }

    @Override
    public String getIdColumn() {
        return SyncStatesTable.COLUMN_ID;
    }

    @Override
    public ContentValues toContentValues(SyncState entity) {
        ContentValues values = new ContentValues();
        values.put(SyncStatesTable.COLUMN_ARTIST_ID, entity.getArtist().getId());
        values.put(SyncStatesTable.COLUMN_LOCATION_ID, entity.getLocation().getId());
        values.put(SyncStatesTable.COLUMN_LAST_SYNC_TIME, entity.getLastSync().getTime());

        return values;
    }

    @Override
    public SyncState fromCursor(Cursor cursor) {
        String artistId = DbUtils.getStringFromCursor(cursor, SyncStatesTable.COLUMN_ARTIST_ID);
        String locationId = DbUtils.getStringFromCursor(cursor, SyncStatesTable.COLUMN_LOCATION_ID);
        Date lastSyncTime = new Date(DbUtils.getLongFromCursor(cursor,
                SyncStatesTable.COLUMN_LAST_SYNC_TIME));
        Artist artist = getDataSource().getArtist(artistId).blockingGet();
        Location location = getDataSource().getLocation(locationId).blockingGet();

        return new SyncState(artist, location, lastSyncTime);
    }
}


text:
from globus_sdk.authorizers import NullAuthorizer
from tests.framework import CapturedIOTestCase

class NullAuthorizerTests(CapturedIOTestCase):

    def setUp(self):
        """
        Initializes a NullAuthorizer for testing
        """
        super(NullAuthorizerTests, self).setUp()
        self.authorizer = NullAuthorizer()

    def test_set_authorization_header(self):
        """
        Sets authorization header in a test dictionary,
        Confirms that nothing happens.
        and any existing Authorization header is removed
        """
        header_dict = {}
        self.authorizer.set_authorization_header(header_dict)
        self.assertEqual(header_dict, {})

    def test_set_authorization_header_existing(self):
        """
        Confirms that an existing Authorization field is removed
        """
        header_dict = {"Header": "value",
                       "Authorization": "previous_value"}
        self.authorizer.set_authorization_header(header_dict)
        self.assertEqual(header_dict, {"Header": "value"})

    def test_handle_missing_authorization(self):
        """
        Confirms that NullAuthorizer doesn't handle missing authorization
        """
        self.assertFalse(self.authorizer.handle_missing_authorization())


text:
[![Join the chat at https://gitter.im/JasperFx/Marten](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/JasperFx/Marten?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
![Twitter Follow](https://img.shields.io/twitter/follow/marten_lib?logo=Twitter&style=flat-square)
[![Windows Build Status](https://ci.appveyor.com/api/projects/status/va5br63j7sbx74cm/branch/master?svg=true)](https://ci.appveyor.com/project/jasper-ci/marten/branch/master)
[![Linux Build status](https://dev.azure.com/jasperfx-marten/marten/_apis/build/status/marten?branchName=master)](https://dev.azure.com/jasperfx-marten/marten/_build/latest?definitionId=1&branchName=master)
[![Nuget Package](https://badgen.net/nuget/v/marten)](https://www.nuget.org/packages/Marten/)
[![Nuget](https://img.shields.io/nuget/dt/marten)](https://www.nuget.org/packages/Marten/)

![marten logo](https://martendb.io/v3/content/images/banner.png)

The Marten library provides .NET developers with the ability to use the proven [PostgreSQL database engine](http://www.postgresql.org/) and its [fantastic JSON support](https://www.compose.io/articles/is-postgresql-your-next-json-database/) as a fully fledged [document database](https://en.wikipedia.org/wiki/Document-oriented_database). The Marten team believes that a document database has far reaching benefits for developer productivity over relational databases with or without an ORM tool.

Marten also provides .NET developers with an ACID-compliant event store with user-defined projections against event streams.

Access docs [here](https://martendb.io/) and v3.x docs [here](https://martendb.io/v3).

## Working with the Code

Before getting started you will need the following in your environment:

**1. .NET Core SDK 5.0+ and the .NET Core 3.1 Runtime**

Available [here](https://dotnet.microsoft.com/download)

**2. PostgreSQL 9.6 or above database with PLV8**

The fastest possible way to develop with Marten is to run PostgreSQL in a Docker container. Assuming that you have
Docker running on your local box, type `dotnet run --framework net6.0 -- init-db` at the command line to spin up a Postgresql database with
PLv8 enabled and configured in the database. The default Marten test configuration tries to find this database if no
PostgreSQL database connection string is explicitly configured following the steps below:

You need to enable the PLV8 extension inside of PostgreSQL for running JavaScript stored procedures for the nascent projection support.

Ensure the following:

- The login you are using to connect to your database is a member of the `postgres` role
- An environment variable of `marten_testing_database` is set to the connection string for the database you want to use as a testbed. (See the [Npgsql documentation](http://www.npgsql.org/doc/connection-string-parameters.html) for more information about PostgreSQL connection strings ).

_Help with PSQL/PLV8_

- On Windows, see [this link](http://www.postgresonline.com/journal/archives/360-PLV8-binaries-for-PostgreSQL-9.5-windows-both-32-bit-and-64-bit.html) for pre-built binaries of PLV8
- On *nix, check [marten-local-db](https://github.com/eouw0o83hf/marten-local-db) for a Docker based PostgreSQL instance including PLV8.

Once you have the codebase and the connection string file, run the [build command](https://github.com/JasperFx/marten#build-commands) or use the dotnet CLI to restore and build the solution.

You are now ready to contribute to Marten.

See more in [Contribution Guidelines](CONTRIBUTING.md).

### Tooling

* Unit Tests rely on [xUnit](http://xunit.github.io/) and [Shouldly](https://github.com/shouldly/shouldly)
* [Bullseye](https://github.com/adamralph/bullseye) is used for build automation.
* [Node.js](https://nodejs.org/en/) runs our Mocha specs.
* [Storyteller](http://storyteller.github.io) for some of the data intensive automated tests

### Build Commands

| Description                         | Windows Commandline      | PowerShell               | Linux Shell             | DotNet CLI                                         |
| ----------------------------------- | ------------------------ | ------------------------ |-------------------------| -------------------------------------------------- |
| Run restore, build and test         | `build.cmd`              | `build.ps1`              | `build.sh`              | `dotnet build src\Marten.sln`                      |
| Run all tests including mocha tests | `build.cmd test`         | `build.ps1 test`         | `build.sh test`         | `dotnet run -p build/build.csproj -- test`         |
| Run just mocha tests                | `build.cmd mocha`        | `build.ps1 mocha`        | `build.sh mocha`        | `dotnet run -p build/build.csproj -- mocha`        |
| Run StoryTeller tests               | `build.cmd storyteller`  | `build.ps1 storyteller`  | `build.sh storyteller`  | `dotnet run -p build/build.csproj -- storyteller`  |
| Open StoryTeller editor             | `build.cmd open_st`      | `build.ps1 open_st`      | `build.sh open_st`      | `dotnet run -p build/build.csproj -- open_st`      |
| Run docs website locally            | `build.cmd docs`         | `build.ps1 docs`         | `build.sh docs`         | `dotnet run -p build/build.csproj -- docs`         |
| Publish docs                        | `build.cmd publish-docs` | `build.ps1 publish-docs` | `build.sh publish-docs` | `dotnet run -p build/build.csproj -- publish-docs` |
| Run benchmarks                      | `build.cmd benchmarks`   | `build.ps1 benchmarks`   | `build.sh benchmarks`   | `dotnet run -p build/build.csproj -- benchmarks`   |

> Note: You should have a running Postgres instance while running unit tests or StoryTeller tests.

### xUnit.Net Specs

The tests for the main library are now broken into three testing projects:

1. `CoreTests` -- basic services like retries, schema management basics
1. `DocumentDbTests` -- anything specific to the document database features of Marten
1. `EventSourcingTests` -- anything specific to the event sourcing features of Marten

To aid in integration testing, Marten.Testing has a couple reusable base classes that can be use
to make integration testing through Postgresql be more efficient and allow the xUnit.Net tests
to run in parallel for better throughput.

- `IntegrationContext` -- if most of the tests will use an out of the box configuration
  (i.e., no fluent interface configuration of any document types), use this base type. Warning though,
  this context type will **not** clean out the main `public` database schema between runs,
  but will delete any existing data
- `DestructiveIntegrationContext` -- similar to `IntegrationContext`, but will wipe out any and all
  Postgresql schema objects in the `public` schema between tests. Use this sparingly please.
- `OneOffConfigurationsContext` -- if a test suite will need to frequently re-configure
  the `DocumentStore`, this context is appropriate. You do *not* need to decorate any of these
  test classes with the `[Collection]` attribute. This fixture will use an isolated schema using the name of the
  test fixture type as the schema name
- `BugIntegrationContext` -- the test harnesses for bugs tend to require custom `DocumentStore`
  configuration, and this context is a specialization of `OneOffConfigurationsContext` for
  the *bugs* schema.
- `StoreFixture` and `StoreContext` are helpful if a series of tests use the same custom
  `DocumentStore` configuration. You'd need to write a subclass of `StoreFixture`, then use
  `StoreContext<YourNewStoreFixture>` as the base class to share the `DocumentStore` between
  test runs with xUnit.Net's shared context (`IClassFixture<T>`)

### Mocha Specs

Refer to the build commands section to look up the commands to run Mocha tests. There is also `npm run tdd` to run the mocha specifications
in a watched mode with growl turned on.

> Note: remember to run `npm install`

### Storyteller Specs

Refer to build commands section to look up the commands to open the StoryTeller editor or run the StoryTeller specs.

## Documentation

All the documentation is written in Markdown and the docs are published as a static site hosted in Netlify. v4.x and v3.x use different documentation tools hence are detailed below in separate sub-sections.

### v4.x and above

[VitePress](https://vitepress.vuejs.org/) is used as documentation tool. Along with this, [MarkdownSnippets](https://github.com/SimonCropp/MarkdownSnippets) is used for adding code snippets to docs from source code and [Algolia DocSearch](https://docsearch.algolia.com/) is used for searching the docs via the search box.

The documentation content is the Markdown files in the `/docs` directory directly under the project root. To run the docs locally use `npm run docs` with auto-refresh on any changes.

To add code samples/snippets from the tests in docs, follow the steps below:

Use C# named regions to mark a code block as described in the sample below

```csharp
#region sample_my_snippet
// code sample/snippet
// ...
#endregion
```

All code snippet identifier starts with `sample_` as a convention to clearly identify that the region block corresponds to a sample code/snippet used in docs. Recommend to use snake case for the identifiers with words in lower case.

Use the below to include the code snippet in a docs page

<pre>
<!-- snippet: sample_my_snippet -->
<!-- endSnippet -->
</pre>

Note that when you run the docs locally, the above placeholder block in the Markdown file will get updated inline with the actual code snippet from the source code. Please commit the changes with the auto-generated inline code snippet as-is after you preview the docs page. This helps with easier change tracking when you send PR's.

Few gotchas:

- Any changes to the code snippets will need to done in the source code. Do not edit/update any of the auto-generated inline code snippet directly in the Markdown files.
- The latest snippet are always pulled into the docs while we publish the docs. Hence do not worry about the inline code snippet in Markdown file getting out of sync with the snippet in source code.

### v3.x

[stdocs](https://www.nuget.org/packages/dotnet-stdocs/) is used as documentation tool. The documentation content is the markdown files in the `/documentation` directory directly under the project root. Any updates to v3.x docs will need to done in [3.14 branch](https://github.com/JasperFx/marten/tree/3.14). To run the documentation website locally with auto-refresh, refer to the build commands section above.

If you wish to insert code samples/snippet to a documentation page from the tests, wrap the code you wish to insert with
`// SAMPLE: name-of-sample` and `// ENDSAMPLE`.
Then to insert that code to the documentation, add `<[sample:name-of-sample]>`.

> Note: content is published to the `gh-pages` branch of this repository. Refer to build commands section to lookup the command for publishing docs.

## License

Copyright © Jeremy D. Miller, Babu Annamalai, Oskar Dudycz, Joona-Pekka Kokko and contributors.

Marten is provided as-is under the MIT license. For more information see [LICENSE](LICENSE).

## Code of Conduct

This project has adopted the code of conduct defined by the [Contributor Covenant](http://contributor-covenant.org/) to clarify expected behavior in our community.


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=9"/>
    <meta name="generator" content="Doxygen 1.8.6"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <title>Generic Image Library: pixel_reference_is_proxy< PixelReference > Struct Template Reference</title>
    <link href="tabs.css" rel="stylesheet" type="text/css"/>

    <link href="doxygen.css" rel="stylesheet" type="text/css" />
    <link href="doxygen-boost.css" rel="stylesheet" type="text/css"/>

Main Page

Modules

Classes

Files

Class List

Class Index

Class Hierarchy

Class Members

boost

gil

pixel_reference_is_proxy

pixel_reference_is_proxy< PixelReference > Struct Template Reference
Type Analysis Metafunctions

Determines whether the given pixel reference is a proxy class or a native C++ reference.
 More...

#include <metafunctions.hpp>

Inherits not_< is_same< remove_const_and_reference< PixelReference >::type, remove_const_and_reference< PixelReference >::type::value_type > >.

Detailed Description

template<typename PixelReference>

struct boost::gil::pixel_reference_is_proxy< PixelReference >

Determines whether the given pixel reference is a proxy class or a native C++ reference.

The documentation for this struct was generated from the following file:

metafunctions.hpp

     <address class="footer">

        Generated on Wed Dec 5 2018 20:05:51 for Generic Image Library by  doxygen 1.8.6

    </address>


text:
<?php

/**
 * @file
 * Contains \Drupal\field_test\Plugin\field\formatter\TestFieldDefaultFormatter.
 */

namespace Drupal\field_test\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;

/**
 * Plugin implementation of the 'field_test_default' formatter.
 *
 * @FieldFormatter(
 *   id = "field_test_default",
 *   label = @Translation("Default"),
 *   description = @Translation("Default formatter"),
 *   field_types = {
 *     "test_field",
 *     "test_field_with_preconfigured_options"
 *   },
 *   weight = 1
 * )
 */
class TestFieldDefaultFormatter extends FormatterBase {

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return array(
      'test_formatter_setting' => 'dummy test string',
    ) + parent::defaultSettings();
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $element['test_formatter_setting'] = array(
      '#title' => t('Setting'),
      '#type' => 'textfield',
      '#size' => 20,
      '#default_value' => $this->getSetting('test_formatter_setting'),
      '#required' => TRUE,
    );
    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    $summary = array();
    $summary[] = t('@setting: @value', array('@setting' => 'test_formatter_setting', '@value' => $this->getSetting('test_formatter_setting')));
    return $summary;
  }

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items) {
    $elements = array();

    foreach ($items as $delta => $item) {
      $elements[$delta] = array('#markup' => $this->getSetting('test_formatter_setting') . '|' . $item->value);
    }

    return $elements;
  }
}


text:
package exportcmd

import "github.com/jfrog/jfrog-cli-core/v2/utils/coreutils"

var Usage = []string{"config export [server ID]"}

func GetDescription() string {
	return `Creates a server configuration token. The generated Config Token can be imported by the "` + coreutils.GetCliExecutableName() + ` config import <Config Token>" command.`
}


text:
using System;
using System.Text;
using System.Diagnostics;
using System.Security.Cryptography.Pkcs;

namespace Internal.Cryptography
{
    internal abstract class KeyTransRecipientInfoPal : RecipientInfoPal
    {
        internal KeyTransRecipientInfoPal()
            : base()
        {
        }
    }
}


text:
""" setuptools for stalkerweb """

from setuptools import setup, find_packages
from stalkerweb import __version__ as version

setup(
    name='stalkerweb',
    version=version,
    author="Florian Hines",
    author_email="syn@ronin.io",
    description="Simple Monitoring System",
    url="http://github.com/pandemicsyn/stalker",
    packages=find_packages(),
    classifiers=[
        'Development Status :: 4 - Beta',
        'License :: OSI Approved :: Apache Software License',
        'Operating System :: POSIX :: Linux',
        'Programming Language :: Python :: 2.6',
        'Environment :: No Input/Output (Daemon)',
    ],
    install_requires=[
        'stalkerutils==2.0.2',
        'eventlet==0.17.4',
        'flask==0.10.1',
        'redis==2.10.3',
        'pymongo==3.0.3',
        'mmh3==2.3.1',
        'flask-rethinkdb==0.2',
        'rethinkdb==2.1.0.post2',
        'flask-bcrypt==0.7.1',
        'flask-wtf==0.12',
    ],
    include_package_data=True,
    zip_safe=False,
    scripts=['bin/stalker-web',],
    data_files=[('share/doc/stalkerweb',
                 ['README.md', 'INSTALL',
                  'etc/stalker-web.conf',
                  'etc/init.d/stalker-web',
                 ])]
)