text:
using System;
using System.Runtime.InteropServices;

// Internal C# wrapper for OVRPlugin.

internal static class OVRPlugin
{
	public const string WrapperVersion = "0.1.0";

	public enum Bool
	{
		False = 0,
		True
	}

	public enum Eye
	{
		None = -1,
		Left = 0,
		Right = 1,
		Count = 2
	}

	public enum Tracker
	{
		Default = 0,
		Count,
	}

	public enum BatteryStatus
	{
		Charging = 0,
		Discharging,
		Full,
		NotCharging,
		Unknown,
	}

	public enum PlatformUI
	{
		GlobalMenu = 0,
		ConfirmQuit,
	}

	private enum Key
	{
		Version = 0,
		ProductName,
		Latency,
		EyeDepth,
		EyeHeight,
		BatteryLevel,
		BatteryTemperature,
		CpuLevel,
		GpuLevel,
		SystemVolume,
		QueueAheadFraction,
		IPD,
#if OVR_LEGACY
		NativeTextureScale,
		VirtualTextureScale,
        Frequency,
#endif
    }

	private enum Caps
	{
		SRGB = 0,
		Chromatic,
		FlipInput,
		Rotation,
		HeadModel,
		Position,
		CollectPerf,
		DebugDisplay,
		Monoscopic,
#if OVR_LEGACY
		ShareTexture,
#endif
	}

	private enum Status
	{
		Debug = 0,
		HSWVisible,
		PositionSupported,
		PositionTracked,
		PowerSaving,
#if OVR_LEGACY
		Initialized,
#endif
	}

	[StructLayout(LayoutKind.Sequential)]
	public struct Vector3f
	{
		public float x;
		public float y;
		public float z;
	}

	[StructLayout(LayoutKind.Sequential)]
	public struct Quatf
	{
		public float x;
		public float y;
		public float z;
		public float w;
	}

	[StructLayout(LayoutKind.Sequential)]
	public struct Posef
	{
		public Quatf Orientation;
		public Vector3f Position;
	}

	[StructLayout(LayoutKind.Sequential)]
	public struct Sizei
	{
		public int w;
		public int h;
	}

	[StructLayout(LayoutKind.Sequential)]
	public struct Frustumf
	{
		public float zNear;
		public float zFar;
		public float fovX;
		public float fovY;
	}

	public static bool srgb
	{
		get { return GetCap(Caps.SRGB); }
		set { SetCap(Caps.SRGB, value); }
	}

	public static bool chromatic
	{
		get { return GetCap(Caps.Chromatic); }
		set { SetCap(Caps.Chromatic, value); }
	}

	public static bool flipInput
	{
		get { return GetCap(Caps.FlipInput); }
		set { SetCap(Caps.FlipInput, value); }
	}

	public static bool rotation
	{
		get { return GetCap(Caps.Rotation); }
		set { SetCap(Caps.Rotation, value); }
	}

	public static bool headModel
	{
		get { return GetCap(Caps.HeadModel); }
		set { SetCap(Caps.HeadModel, value); }
	}

	public static bool position
	{
		get { return GetCap(Caps.Position); }
		set { SetCap(Caps.Position, value); }
	}

	public static bool collectPerf
	{
		get { return GetCap(Caps.CollectPerf); }
		set { SetCap(Caps.CollectPerf, value); }
	}

	public static bool debugDisplay
	{
		get { return GetCap(Caps.DebugDisplay); }
		set { SetCap(Caps.DebugDisplay, value); }
	}

	public static bool monoscopic
	{
		get { return GetCap(Caps.Monoscopic); }
		set { SetCap(Caps.Monoscopic, value); }
	}

	public static bool debug { get { return GetStatus(Status.Debug); } }

	public static bool hswVisible { get { return GetStatus(Status.HSWVisible); } }

	public static bool positionSupported { get { return GetStatus(Status.PositionSupported); } }

	public static bool positionTracked { get { return GetStatus(Status.PositionTracked); } }

	public static bool powerSaving { get { return GetStatus(Status.PowerSaving); } }

	public static string version { get { return GetString(Key.Version); } }

	public static string productName { get { return GetString(Key.ProductName); } }

	public static string latency { get { return GetString(Key.Latency); } }

	public static float eyeDepth
	{
		get { return ovrp_GetFloat(Key.EyeDepth); }
		set { ovrp_SetFloat(Key.EyeDepth, value); }
	}

	public static float eyeHeight
	{
		get { return ovrp_GetFloat(Key.EyeHeight); }
		set { ovrp_SetFloat(Key.EyeHeight, value); }
	}

	public static float batteryLevel
	{
		get { return ovrp_GetFloat(Key.BatteryLevel); }
		set { ovrp_SetFloat(Key.BatteryLevel, value); }
	}

	public static float batteryTemperature
	{
		get { return ovrp_GetFloat(Key.BatteryTemperature); }
		set { ovrp_SetFloat(Key.BatteryTemperature, value); }
	}

	public static int cpuLevel
	{
		get { return (int)ovrp_GetFloat(Key.CpuLevel); }
		set { ovrp_SetFloat(Key.CpuLevel, (float)value); }
	}

	public static int gpuLevel
	{
		get { return (int)ovrp_GetFloat(Key.GpuLevel); }
		set { ovrp_SetFloat(Key.GpuLevel, (float)value); }
	}

	public static float systemVolume
	{
		get { return ovrp_GetFloat(Key.SystemVolume); }
		set { ovrp_SetFloat(Key.SystemVolume, value); }
	}

	public static float queueAheadFraction
	{
		get { return ovrp_GetFloat(Key.QueueAheadFraction); }
		set { ovrp_SetFloat(Key.QueueAheadFraction, value); }
	}

	public static float ipd
	{
		get { return ovrp_GetFloat(Key.IPD); }
		set { ovrp_SetFloat(Key.IPD, value); }
	}

#if OVR_LEGACY
	public static bool initialized { get { return ovrp_GetStatus(Status.Initialized); } }

	public static bool shareTexture
	{
		get { return ovrp_GetCap(Caps.ShareTexture); }
		set { SetCap(Caps.ShareTexture, value); }
	}

	public static float nativeTextureScale
	{
		get { return ovrp_GetFloat(Key.NativeTextureScale); }
		set { ovrp_SetFloat(Key.NativeTextureScale, value); }
	}

	public static float virtualTextureScale
	{
		get { return ovrp_GetFloat(Key.VirtualTextureScale); }
		set { ovrp_SetFloat(Key.VirtualTextureScale, value); }
	}
#endif

	public static BatteryStatus batteryStatus
	{
		get { return ovrp_GetBatteryStatus(); }
	}

	private static bool GetStatus(Status bit)
	{
		return ((int)ovrp_GetStatus() & (1 << (int)bit)) != 0;
	}

	private static bool GetCap(Caps cap)
	{
		return ((int)ovrp_GetCaps() & (1 << (int)cap)) != 0;
	}

	private static void SetCap(Caps cap, bool value)
	{
		if (GetCap(cap) == value)
			return;

		int caps = (int)ovrp_GetCaps();
		if (value)
			caps |= (1 << (int)cap);
		else
			caps &= ~(1 << (int)cap);

		ovrp_SetCaps((Caps)caps);
	}

	[DllImport("OVRPlugin", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_GetNativePointer")]
	public static extern IntPtr GetNativePointer();

	[DllImport("OVRPlugin", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_GetBufferCount")]
	public static extern int GetBufferCount();

	[DllImport("OVRPlugin", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_GetEyePose")]
	public static extern Posef GetEyePose(Eye eyeId);

	[DllImport("OVRPlugin", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_GetEyeVelocity")]
	public static extern Posef GetEyeVelocity(Eye eyeId);

	[DllImport("OVRPlugin", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_GetEyeAcceleration")]
	public static extern Posef GetEyeAcceleration(Eye eyeId);

	[DllImport("OVRPlugin", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_GetEyeFrustum")]
	public static extern Frustumf GetEyeFrustum(Eye eyeId);

	[DllImport("OVRPlugin", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_GetEyeTextureSize")]
	public static extern Sizei GetEyeTextureSize(Eye eyeId);

	[DllImport("OVRPlugin", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_GetTrackerPose")]
	public static extern Posef GetTrackerPose(Tracker trackerId);

	[DllImport("OVRPlugin", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_GetTrackerFrustum")]
	public static extern Frustumf GetTrackerFrustum(Tracker trackerId);

	[DllImport("OVRPlugin", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_DismissHSW")]
	public static extern Bool DismissHSW();

	[DllImport("OVRPlugin", CallingConvention = CallingConvention.Cdecl)]
	private static extern Caps ovrp_GetCaps();

	[DllImport("OVRPlugin", CallingConvention = CallingConvention.Cdecl)]
	private static extern Bool ovrp_SetCaps(Caps caps);

	[DllImport("OVRPlugin", CallingConvention = CallingConvention.Cdecl)]
	private static extern Status ovrp_GetStatus();

	[DllImport("OVRPlugin", CallingConvention = CallingConvention.Cdecl)]
	private static extern float ovrp_GetFloat(Key key);

	[DllImport("OVRPlugin", CallingConvention = CallingConvention.Cdecl)]
	private static extern Bool ovrp_SetFloat(Key key, float value);

	[DllImport("OVRPlugin", CallingConvention = CallingConvention.Cdecl)]
	private static extern BatteryStatus ovrp_GetBatteryStatus();

	[DllImport("OVRPlugin", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_SetOverlayQuad")]
	public static extern Bool SetOverlayQuad(Bool onTop, IntPtr texture, IntPtr device, Posef pose, Vector3f scale);

	[DllImport("OVRPlugin", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_ShowUI")]
	public static extern Bool ShowUI(PlatformUI ui);

	[DllImport("OVRPlugin", CallingConvention = CallingConvention.Cdecl)]
	private static extern IntPtr ovrp_GetString(Key key);
	private static string GetString(Key key) { return Marshal.PtrToStringAnsi(ovrp_GetString(key)); }

#if OVR_LEGACY
	//[DllImport("OVRPlugin", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_PreInitialize")]
	//public static extern Bool PreInitialize();

	//[DllImport("OVRPlugin", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_Initialize")]
	//public static extern Bool Initialize(RenderAPIType apiType, IntPtr platformArgs);

	//[DllImport("OVRPlugin", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_Shutdown")]
	//public static extern Bool Shutdown();

	[DllImport("OVRPlugin", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_SetupDistortionWindow")]
	public static extern Bool SetupDistortionWindow();

	[DllImport("OVRPlugin", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_DestroyDistortionWindow")]
	public static extern Bool DestroyDistortionWindow();

	//[DllImport("OVRPlugin", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_RecreateEyeTexture")]
	//public static extern Bool RecreateEyeTexture(Eye eyeId, int stage, void* device, int height, int width, int samples, Bool isSRGB, void* result);

	//[DllImport("OVRPlugin", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_SetEyeTexture")]
	//public static extern Bool SetEyeTexture(Eye eyeId, IntPtr texture);

	[DllImport("OVRPlugin", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_Update")]
	public static extern Bool ovrp_Update(int frameIndex);

	//[DllImport("OVRPlugin", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_BeginFrame")]
	//public static extern Bool BeginFrame(int frameIndex);

	//[DllImport("OVRPlugin", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_EndEye")]
	//public static extern Bool EndEye(Eye eye);

	//[DllImport("OVRPlugin", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_EndFrame")]
	//public static extern Bool EndFrame(int frameIndex);

	[DllImport("OVRPlugin", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_RecenterPose")]
	public static extern Bool RecenterPose();
#endif
}


text:
package de.webtwob.mbma.core;

import de.webtwob.mbma.core.common.MBMALog;
import de.webtwob.mbma.core.common.proxy.CommonProxy;
import de.webtwob.mbma.core.common.registration.MBMAPacketHandler;
import de.webtwob.mbma.core.common.registration.MBMATileEntityList;

import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.*;

/**
 * Created by BB20101997 on 16. Mär. 2017.
 */
@Mod.EventBusSubscriber
@Mod(modid = MBMA_CORE.MODID, useMetadata = true)
public class MBMA_CORE {

    public static final String MODID = "mbmacore";
    public static final String COMMON_PROXY = "de.webtwob.mbma.core.common.proxy.CommonProxy";
    public static final String CLIENT_PROXY = "de.webtwob.mbma.core.client.proxy.ClientProxy";

    @Mod.Instance(MODID)
    public static MBMA_CORE INSTANCE;

    @SidedProxy(clientSide = CLIENT_PROXY, serverSide = COMMON_PROXY)
    public static CommonProxy proxy;

    public MBMA_CORE() {
        MBMALog.info("ModInstance created!");
    }

    @SuppressWarnings("unused")
    @Mod.EventHandler
    public void preInit(FMLPreInitializationEvent event) {
        MBMALog.info("Starting PreInit!");
        MBMATileEntityList.registerTileEntities();
        /*
         * other stuff that would go here:
         * Ore-Dict assignment
         */
        MBMALog.info("Finished PreInit!");
    }

    @SuppressWarnings("unused")
    @Mod.EventHandler
    public void inti(FMLInitializationEvent event) {
        MBMALog.info("Starting Init!");
        MBMAPacketHandler.init();
        proxy.register();
        /*
         * other stuff that would go here:
         * Register WorldGenerators
         * Register EventHandler
         */
        MBMALog.info("Finished Init!");
    }

    @Mod.EventHandler
    public void postInit(FMLPostInitializationEvent event) {
        //cross-mod-stuff
        MBMALog.info("Nothing to do in PostInit!");
    }

    @Mod.EventHandler
    public void serverStarting(FMLServerStartingEvent event) {
        //register commands when existent
        MBMALog.info("Nothing to do on ServerStart!");
    }

    @Mod.EventHandler
    public void imc(FMLInterModComms.IMCEvent event) {
        for (FMLInterModComms.IMCMessage message : event.getMessages()) {
            MBMALog.warn("Received unexpected IMCMessage from ", message.getSender());
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
.PHONY: release

TAG ?= $(shell git tag --points-at HEAD | head -q -n1)
ifeq ($(TAG),)
$(error You must specify TAG with the name of an existing tag)
endif

FPC ?= $(shell which fpc)
ifeq ($(FPC),)
$(error You must specify FPC with full path to compiler)
endif

TARGET_CPU := $(shell $(FPC) -iTP)
TARGET_OS := $(shell $(FPC) -iTO)

OUTFILE := androli-$(TAG)-$(TARGET_CPU)-$(TARGET_OS)

ifneq (,$(filter $(TARGET_OS),win32 win64))
EXT = .exe
else
EXT =
endif

OUTDIR := $(shell mktemp -d)

release:
	rm -rf "$(OUTDIR)"
	git clone -q --single-branch -b $(TAG) --shared . "$(OUTDIR)"
	cd "$(OUTDIR)" && lazbuild Androli.lpi --bm=Release --os=$(TARGET_OS) --cpu=$(TARGET_CPU) --compiler=$(FPC)
	cd "$(OUTDIR)" && mv androli$(EXT) $(OUTFILE)$(EXT)
	cd "$(OUTDIR)" && zip -r $(OUTFILE).zip dumps media README.md LICENSE $(OUTFILE)$(EXT)
	mv -f "$(OUTDIR)/$(OUTFILE).zip" ./


text:
/*
    Module dependencies
*/
const express = require('express');
const bodyParser = require('body-parser');
const logger = require('morgan');
const path = require('path');
const request = require('request');
const xml2json = require('xml2json').toJson;

/*
    Create app
 */
const app = express();

/*
    Basic setup
*/
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
	extended: false
}));
app.use(express.static(path.join(__dirname, 'client')));
app.use('/bower_components',  express.static(__dirname + '/bower_components'));

/*
    Define your routes
*/
const router = express.Router();

router.post('/emojify', function(req, res) {

	/*
	    Get the song name,
	    get lyrics
	    transform lyrics to emoji
	 */

    const parseArtist = req.body.artist.split(' ').join('+');
    const parseTrack =req.body.track.split(' ').join('+');

    const url = `http://api.lololyrics.com/0.5/getLyric?artist=${parseArtist}&track=${parseTrack}`;

	request(url, (err, response, body) => {

			//var json = JSON.stringify(xml2json(body));
			var json = JSON.parse(xml2json(body));
			//console.log(json);
			//res.json({response: json.result.response});

			const emojifyData = {
				emoji_slova: json.result.response,
				emoji_kluc: 'fmgvzz.zrv',
				jezyk_s: 'en',
				jezyk_na: 'en-x-emoji',
				emoji_options: '-emoji_s_0-'
			};

			request.post({
				url: 'http://emojitranslate.com/api/',
				formData: emojifyData
			}, (err2, response2, body2) => {

				if (!err && response2.statusCode == 200) {
					res.json({
						response: body2.split('\n')
					});
				} else {
					console.error(err);
					res.json({
						response: 'error'
					});
				}
			});

		});
})

app.use('/', router);

/*
    Server error handling
*/
app.use((req, res, next) => {
	var err = new Error('Not Found');
	err.status = 404;
	next(err);
});

if (app.get('env') === 'development') {
	app.use((err, req, res, next) => {
		res.status(err.status || 500);
		res.json({
			message: err.message,
			error: err
		});
	});
}

app.use((err, req, res, next) => {
	res.status(err.status || 500);
	res.json({
		message: err.message,
		error: err
	});
});

/*
    Start the server
*/
const debug = require('debug')('emojitune:server');
const http = require('http');
const port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

const server = http.createServer(app);
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

/*
    Helper functions
*/

// Normalize a port into a number, string, or false.

function normalizePort(val) {
	var port = parseInt(val, 10);

	if (isNaN(port)) {
		// named pipe
		return val;
	}

	if (port >= 0) {
		// port number
		return port;
	}

	return false;
}

// Event listener for HTTP server "error" event.

function onError(error) {
	if (error.syscall !== 'listen') {
		throw error;
	}

	var bind = typeof port === 'string' ?
		'Pipe ' + port :
		'Port ' + port

	// handle specific listen errors with friendly messages
	switch (error.code) {
		case 'EACCES':
			console.error(bind + ' requires elevated privileges');
			process.exit(1);
			break;
		case 'EADDRINUSE':
			console.error(bind + ' is already in use');
			process.exit(1);
			break;
		default:
			throw error;
	}
}

// Event listener for HTTP server "listening" event.

function onListening() {
	var addr = server.address();
	var bind = typeof addr === 'string' ?
		'pipe ' + addr :
		'port ' + addr.port;
	debug('Listening on ' + bind);
}


text:
import numpy as np

RADIX_SCALE = 2**52

class ExactRep(object):
    """Fixed-point representation of arrays with auxilliary bits such
    that + - * / ops are all exactly invertible (except for
    overflow)."""
    def __init__(self, val, from_intrep=False):
        if from_intrep:
            self.intrep = val
        else:
            self.intrep = self.float_to_intrep(val)

        self.aux = BitStore(len(val))

    def add(self, A):
        """Reversible addition of vector or scalar A."""
        self.intrep += self.float_to_intrep(A)
        return self

    def sub(self, A):
        self.add(-A)
        return self

    def rational_mul(self, n, d):
        self.aux.push(self.intrep % d, d) # Store remainder bits externally
        self.intrep = self.intrep / d                  # Divide by denominator
        self.intrep = self.intrep * n                  # Multiply by numerator
        self.intrep = self.intrep + self.aux.pop(n)    # Pack bits into the remainder

    def mul(self, a):
        n, d = self.float_to_rational(a)
        self.rational_mul(n, d)
        return self

    def div(self, a):
        n, d = self.float_to_rational(a)
        self.rational_mul(d, n)
        return self

    def float_to_rational(self, a):
        assert np.all(a > 0.0)
        d = 2**16 / np.fix(a+1).astype(int) # Uglier than it used to be: np.int(a + 1)
        n = np.fix(a * d + 1).astype(int)
        return  n, d

    def float_to_intrep(self, x):
        return (x * RADIX_SCALE).astype(np.int64)

    @property
    def val(self):
        return self.intrep.astype(np.float64) / RADIX_SCALE

class BitStore(object):
    """Efficiently stores information with non-integer number of bits (up to 16)."""
    def __init__(self, length):
        # Use an array of Python 'long' ints which conveniently grow
        # as large as necessary. It's about 50X slower though...
        self.store = np.array([0L] * length, dtype=object)

    def push(self, N, M):
        """Stores integer N, given that 0 <= N < M"""
        assert np.all(M <= 2**16)
        self.store *= M
        self.store += N

    def pop(self, M):
        """Retrieves the last integer stored."""
        N = self.store % M
        self.store /= M
        return N

class LongIntArray(object):
    """Behaves like np.array([0L] * length, dtype=object) but faster."""
    def __init__(self, length):
        self.val = []
        self.nbits = 0
        self.grow()

    def grow(self):
        self.val.append(np.zeros(length, dtype=np.int32))
        self.nbits += 32

    def __mod__(self, other):
        pass

    def __iadd__(self, other):
        self.val[-1] += other

    def __imul__(self, other):
        pass

    def __idiv__(self, other):
        pass


text:
package org.deepjava.runtime.mpc555.demo;

import org.deepjava.runtime.mpc555.driver.SCI;
import org.deepjava.runtime.mpc555.driver.SCIInputStream;
import org.deepjava.runtime.mpc555.driver.SCIOutputStream;
import org.deepjava.runtime.ppc32.Task;

/**
 * Demo for InputStream and OutputStream using SCI2.<br>
 * Received characters will be sent back immediately.
 *
 * @author Urs Graf
 */
public class SystemInOutReflector extends Task {
	static SCIOutputStream out;
	static SCIInputStream in;

	/**
	 * Reflect input on in stream to out stream.
	 */
	public void action() {
		if (in.available() > 0)	out.write(in.read());
	}

	static {
		SCI sci = SCI.getInstance(SCI.pSCI2);
		sci.start(9600, SCI.NO_PARITY, (short)8);
		out = sci.out;
		in = sci.in;
		out.write((byte)'x');

		Task t = new SystemInOutReflector();
		t.period = 0;
		Task.install(t);
	}
}


text:
<?php
	require_once('config.php');

	function dbCheck()
	{
		global $conf;
		$link = @mysql_connect($conf['db_server'] . ':' . $conf['db_port'], $conf['db_user'], $conf['db_pass']);
		if (false === $link)
		{
			return false;
		}

		$status = @mysql_select_db($conf['db_name'], $link);
		if (false === $status)
		{
			return false;
		}

		return true;
	}

	if (dbCheck())
	{
		echo('Successfully connected to the database');
	}
	else
	{
		echo('Error connecting to the database');
	}
?>


text:
#state {
    position: absolute;
    top: 0;
    right: 55px;
    height: 44px;
    z-index: 11;
    overflow: hidden;

    transition: right .3s ease-in-out;
    -moz-transition: right .3s ease-in-out;
    -webkit-transition: right .3s ease-in-out;
    -ms-transition: right .3s ease-in-out;
    -o-transition: right .3s ease-in-out;

    background: white;
}

#viewport.show-search #state {
    right: 150px;
}

#state .downloading,
#state .offline,
#state .loading,
#state .synch {
    float: left;
    line-height: 24px;
    padding: 10px 20px;
    font-size: 12px;

    margin: 1px;
    color: white;
    display: none;
}

#state .downloading {
    background: green;
}

#state .offline {
    background: darkred;
}

#state .loading {
    background: #333;
}

#state .downloading.show,
#state .offline.show,
#state .loading.show,
#state .synch.show {
    display: block;
}

#state .downloading .text,
#state .offline .text,
#state .loading .text {
    float: left;
    text-transform: uppercase;
}

#state .loading .text {
    margin-right: 10px;
}

#state .downloading .icon,
#state .offline .icon,
#state .loading .icon {
    float: left;
    width: 16px;
    height: 24px;
}

#state .downloading .icon:before {
    font-family: awesome;
    content: '\\f019'
}

#state .offline .icon:before {
    font-family: awesome;
    content: '\\f0e7'
}

#state .loading .icon {
    background: url(#host.layout#/static/loading.gif) no-repeat center center;
}

/* Smartphones */
@media only screen and (max-width: 640px) {

    #state {
        height: 38px;
        background: none;
        color: white;
    }

    #state .downloading,
    #state .offline,
    #state .loading,
    #state .synch {
        width: 38px;
        height: 38px;
        line-height: 38px;
        padding: 0;
    }

    #state .downloading .text,
    #state .offline .text,
    #state .loading .text {
        display: none;
    }

    #state .downloading .icon,
    #state .offline .icon,
    #state .loading .icon {
        width: 100%;
        height: 36px;
        line-height: 38px;
        text-align: center;
    }

}


text:
![](readme_images/index-thumb.png)
# WHERE TO
WHERE TO is an app that encourages users to explore and share images from their previous trips.  Along with the picture they can add a title, where it was taken, and a decription of their experience!  Its a great way to get to see the world through other peoples eyes.

**Built with:**
Rails, BassCss, PaperClip, JavaScript, AJAX, jQuery

**Begin your journey here:** [Where To](http://warm-atoll-6305.herokuapp.com/)

###Ideation Process
#####Wireframing - original
We began the process by wireframing a basic mockup of all the pages that we would need to deliver a simple and beautiful UX

![](readme_images/ideation-wireframes.png)

#####Wireframing - complete
We then fleshed out the wireframes to have a clear understanding of what each page would look like and what features would be needed.

![](readme_images/complete-wireframe1.png)![](readme_images/complete-wireframe2.png)![](readme_images/complete-wireframe3.png)

#####Schema - original
Our basic schema design subject to change

![](readme_images/ideation-schema.png)

#####Schema - complete
Coming soon

##Team Members

####James Parseghian
* GitHub: https://github.com/jjparseghian
* LinkedIn: www.linkedin.com/pub/james-parseghian/13/326/304/en
* Email: jjparseghian@gmail.com

####Michael Angelo
* GitHub: https://github.com/Yamikamisama
* LinkedIn: http://www.linkedin.com/pub/michael-angelo/9a/a93/1b0/
* Email: yamikamisama@gmail.com


text:
static int init_hw(struct echoaudio *chip, u16 device_id, u16 subdevice_id)
{
	int err;

	DE_INIT(("init_hw() - Darla20\n"));
	if (snd_BUG_ON((subdevice_id & 0xfff0) != DARLA20))
		return -ENODEV;

	if ((err = init_dsp_comm_page(chip))) {
		DE_INIT(("init_hw - could not initialize DSP comm page\n"));
		return err;
	}

	chip->device_id = device_id;
	chip->subdevice_id = subdevice_id;
	chip->bad_board = TRUE;
	chip->dsp_code_to_load = &card_fw[FW_DARLA20_DSP];
	chip->spdif_status = GD_SPDIF_STATUS_UNDEF;
	chip->clock_state = GD_CLOCK_UNDEF;
	/* Since this card has no ASIC, mark it as loaded so everything
	   works OK */
	chip->asic_loaded = TRUE;
	chip->input_clock_types = ECHO_CLOCK_BIT_INTERNAL;

	if ((err = load_firmware(chip)) < 0)
		return err;
	chip->bad_board = FALSE;

	if ((err = init_line_levels(chip)) < 0)
		return err;

	DE_INIT(("init_hw done\n"));
	return err;
}

/* The Darla20 has no external clock sources */
static u32 detect_input_clocks(const struct echoaudio *chip)
{
	return ECHO_CLOCK_BIT_INTERNAL;
}

/* The Darla20 has no ASIC. Just do nothing */
static int load_asic(struct echoaudio *chip)
{
	return 0;
}

static int set_sample_rate(struct echoaudio *chip, u32 rate)
{
	u8 clock_state, spdif_status;

	if (wait_handshake(chip))
		return -EIO;

	switch (rate) {
	case 44100:
		clock_state = GD_CLOCK_44;
		spdif_status = GD_SPDIF_STATUS_44;
		break;
	case 48000:
		clock_state = GD_CLOCK_48;
		spdif_status = GD_SPDIF_STATUS_48;
		break;
	default:
		clock_state = GD_CLOCK_NOCHANGE;
		spdif_status = GD_SPDIF_STATUS_NOCHANGE;
		break;
	}

	if (chip->clock_state == clock_state)
		clock_state = GD_CLOCK_NOCHANGE;
	if (spdif_status == chip->spdif_status)
		spdif_status = GD_SPDIF_STATUS_NOCHANGE;

	chip->comm_page->sample_rate = cpu_to_le32(rate);
	chip->comm_page->gd_clock_state = clock_state;
	chip->comm_page->gd_spdif_status = spdif_status;
	chip->comm_page->gd_resampler_state = 3;	/* magic number - should always be 3 */

	/* Save the new audio state if it changed */
	if (clock_state != GD_CLOCK_NOCHANGE)
		chip->clock_state = clock_state;
	if (spdif_status != GD_SPDIF_STATUS_NOCHANGE)
		chip->spdif_status = spdif_status;
	chip->sample_rate = rate;

	clear_handshake(chip);
	return send_vector(chip, DSP_VC_SET_GD_AUDIO_STATE);
}


text:
package net.sf.jxls.transformer;

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

import net.sf.jxls.formula.ListRange;
import net.sf.jxls.parser.Cell;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

/**
 * Represents excel worksheet
 * @author Leonid Vysochyn
 */
public class Sheet {

    Workbook workbook;

    /**
     * POI Excel workbook object
     */
    HSSFWorkbook hssfWorkbook;

    /**
     * POI Excel sheet representation
     */
    HSSFSheet hssfSheet;
    /**
     * This variable stores all list ranges found while processing template file
     */
    private Map listRanges = new HashMap();
    /**
     * Stores all named HSSFCell objects
     */
    private Map namedCells = new HashMap();

    Configuration configuration = new Configuration();

    public Sheet() {
    }

    public Sheet(HSSFWorkbook hssfWorkbook, HSSFSheet hssfSheet, Configuration configuration) {
        this.hssfWorkbook = hssfWorkbook;
        this.hssfSheet = hssfSheet;
        this.configuration = configuration;
    }

    public Sheet(HSSFWorkbook hssfWorkbook, HSSFSheet hssfSheet) {
        this.hssfWorkbook = hssfWorkbook;
        this.hssfSheet = hssfSheet;
    }

    public String getSheetName(){
        return sheetName;
    }

    public void setSheetName(String sheetName){
        this.sheetName = sheetName;
    }

    String sheetName;

    public void initSheetName(){
        for(int i = 0; i < hssfWorkbook.getNumberOfSheets(); i++){
            HSSFSheet sheet = hssfWorkbook.getSheetAt( i );
            if( sheet == hssfSheet ){
                sheetName = hssfWorkbook.getSheetName( i );
                if( sheetName.indexOf(' ') >=0 ){
                    sheetName = "'" + sheetName + "'";
                }
            }
        }
    }

    public HSSFWorkbook getHssfWorkbook() {
        return hssfWorkbook;
    }

    public void setHssfWorkbook(HSSFWorkbook hssfWorkbook) {
        this.hssfWorkbook = hssfWorkbook;
    }

    public void setHssfSheet(HSSFSheet hssfSheet) {
        this.hssfSheet = hssfSheet;
    }

    public HSSFSheet getHssfSheet() {
        return hssfSheet;
    }

    public Configuration getConfiguration() {
        return configuration;
    }

    public Map getListRanges() {
        return listRanges;
    }

    public Map getNamedCells() {
        return namedCells;
    }

    public Workbook getWorkbook() {
        return workbook;
    }

    public void setWorkbook(Workbook workbook) {
        this.workbook = workbook;
    }

    public void addNamedCell(String label, Cell cell){
        namedCells.put( label, cell );
    }

    public void addListRange(String name, ListRange range){
        listRanges.put( name, range );
    }

    public int getMaxColNum(){
        int maxColNum = 0;
        for(int i = hssfSheet.getFirstRowNum(); i <= hssfSheet.getLastRowNum(); i++){
            HSSFRow hssfRow = hssfSheet.getRow( i );
            if( hssfRow != null ){
                if( hssfRow.getLastCellNum() > maxColNum ){
                    maxColNum = hssfRow.getLastCellNum();
                }
            }
        }
        return maxColNum;
    }

}


text:
angular
  .module('app')
  .config(function($routeProvider) {
    $routeProvider
      .when('/users', {
        template: '<user-list users="$ctrl.users" on-delete="$ctrl.delete"></user-list>',
        controller: 'listController',
        controllerAs: '$ctrl'
      })
      .when('/users/:id', {
        template: '<user-form user="$ctrl.user" on-update="$ctrl.update" back-to="/users"></user-form>',
        controller: 'formController',
        controllerAs: '$ctrl'
      })
      .when('/users-create', {
        template: '<user-form user="$ctrl.user" on-update="$ctrl.create" back-to="/users"></user-form>',
        controller: 'formController',
        controllerAs: '$ctrl'
      })
      .otherwise({ redirectTo: '/users' })
      ;
  });


text:
from pyramid.view import view_config
from pyramid.httpexceptions import HTTPFound, HTTPForbidden
from pyramid.session import check_csrf_token

from wf_blog.resources import Root
from wf_blog.helper import login_required
from wf_blog.model import Post

class PostView(Root):
    @view_config(renderer='/posts/detail.html', route_name='post_detail')
    def post_detail(self):
        post = Post.get_post(self.request.mongodb, str(self.request.matchdict['id']))
        last = list(Post.get_last_posts(self.request.mongodb, post['add_time']))
        next = list(Post.get_next_posts(self.request.mongodb, post['add_time']))
        last = last[0] if last else None
        next = next[0] if next else None

        return {'post': post, 'next': next, 'last': last}

    @view_config(renderer='/posts/new_post.html', route_name='new_post', permission='admin', decorator=login_required)
    def new_post(self):
        if self.request.method == 'POST':
            check_csrf_token(self.request)   # 检查csrf
            title = self.request.POST['title']
            content = self.request.POST['content']
            category = self.request.POST['category']
            if not category:
                category = u"未分类"
            if title and content:
                Post.add_post(self.request.mongodb, title, content, category)
                return HTTPFound('/admin/all_posts')  # TODO: 跳转到详细页
            else:
                return {'error': 'error'}
        return {}

    @view_config(renderer='/posts/edit.html', route_name='post_edit', permission='admin', decorator=login_required)
    def post_edit(self):
        tid = self.request.matchdict['id']
        if self.request.method == 'POST':
            check_csrf_token(self.request)
            title = self.request.POST['title']
            content = self.request.POST['content']
            category = self.request.POST['category']
            if not category:
                category = u"未分类"
            if title and content:
                Post.update_post(self.request.mongodb, str(tid), title, content, category)
                return HTTPFound('/admin/all_posts')  # TODO: 跳转到详细页
        post = Post.get_post(self.request.mongodb, str(tid))
        return {'post': post}

    @view_config(renderer='string', route_name='post_delete', permission='admin', decorator=login_required)
    def post_delete(self):
        tid = self.request.matchdict['id']
        if self.request.method == 'POST':
            check_csrf_token(self.request)
            Post.del_post(self.request.mongodb, tid)
            return HTTPFound('/admin/all_posts')


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="SecondActivity"/>

    <Button
        android:id="@+id/btn_second_tomain"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAllCaps="false"
        android:text="To Main Activity"/>

    <Button
        android:id="@+id/btn_second_goback"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAllCaps="false"
        android:text="Go Back"/>

</LinearLayout>


text:
package jo.vecmath.logic;

import jo.vecmath.AxisAngle4f;
import jo.vecmath.Matrix3f;
import jo.vecmath.Matrix4d;
import jo.vecmath.Matrix4f;
import jo.vecmath.Quat4f;
import jo.vecmath.Tuple3f;
import jo.vecmath.Vector3f;

public class TransformQ extends Matrix4f
{
    /**
     *
     */
    private static final long serialVersionUID = -6216638219578138997L;

    private Quat4f      mRotation = new Quat4f(0f, 0f, 0f, -1f);
    private Vector3f    mTranslation = new Vector3f();
    private float       mScale = 1.0f;

    public TransformQ()
    {
        super();
    }

    public TransformQ(float m00, float m01, float m02, float m03, float m10,
            float m11, float m12, float m13, float m20, float m21, float m22,
            float m23, float m30, float m31, float m32, float m33)
    {
        super(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31,
                m32, m33);
    }

    public TransformQ(float[] v)
    {
        super(v);
    }

    public TransformQ(Matrix3f m1, Vector3f t1, float s)
    {
        super(m1, t1, s);
    }

    public TransformQ(Matrix4d m1)
    {
        super(m1);
    }

    public TransformQ(Matrix4f m1)
    {
        super(m1);
    }

    public TransformQ(Quat4f q1, Vector3f t1, float s)
    {
        super(q1, t1, s);
    }

    private void assemble()
    {
        set(mRotation, mTranslation, mScale);
    }

    private void apply(Quat4f rot)
    {
        System.out.print(mRotation+" x "+rot);
        mRotation.mul(rot, mRotation);
        mRotation.normalize();
        System.out.println(" = "+mRotation);
        assemble();
    }

    public void rotate(Tuple3f angles)
    {
        apply(Quat4fLogic.makeRotate(angles));
    }

    public void rotate(float xRadians, float yRadians, float zRadians)
    {
        apply(Quat4fLogic.makeRotate(xRadians, yRadians, zRadians));
    }

    public void rotate(float x, float y, float z, float aRadians)
    {
        apply(Quat4fLogic.makeRotate(x, y, z, aRadians));
    }

    public void rotateX(float aRadians)
    {
        apply(Quat4fLogic.makeRotX(aRadians));
    }

    public void rotateY(float aRadians)
    {
        apply(Quat4fLogic.makeRotY(aRadians));
    }

    public void rotateZ(float aRadians)
    {
        apply(Quat4fLogic.makeRotZ(aRadians));
    }

    public void rotateEuler(float xEuler, float yEuler, float zEuler)
    {
        rotate(xEuler*MathUtils.DEG_TO_RAD, yEuler*MathUtils.DEG_TO_RAD, zEuler*MathUtils.DEG_TO_RAD);
    }

    public void rotateEuler(float x, float y, float z, float aEuler)
    {
        rotate(x, y, z, aEuler*MathUtils.DEG_TO_RAD);
    }

    public void rotateXEuler(float aEuler)
    {
        rotateX(aEuler*MathUtils.DEG_TO_RAD);
    }

    public void rotateYEuler(float aEuler)
    {
        rotateY(aEuler*MathUtils.DEG_TO_RAD);
    }

    public void rotateZEuler(float aEuler)
    {
        rotateZ(aEuler*MathUtils.DEG_TO_RAD);
    }

    public void rotate(AxisAngle4f axis)
    {
        apply(Quat4fLogic.makeRotate(axis));
    }

    public void rotate(Matrix3f rot)
    {
        apply(Quat4fLogic.makeRotate(rot));
    }

    public void scale(float s)
    {
        mScale *= s;
        assemble();
    }

    public void translate(float x, float y, float z)
    {
        System.out.print("Translating from "+mTranslation);
        mTranslation.x += x;
        mTranslation.y += y;
        mTranslation.z += z;
        System.out.println(" to "+mTranslation);
        assemble();
    }

    public void translate(Tuple3f scale)
    {
        translate(scale.x, scale.y, scale.z);
    }

    public Vector3f getForward()
    {
        Vector3f fwd = new Vector3f(0, 0, 1);
        Matrix3f rot = new Matrix3f();
        get(rot);
        rot.transform(fwd);
        return fwd;
    }

    public Vector3f getUp()
    {
        Vector3f up = new Vector3f(0, 1, 0);
        Matrix3f rot = new Matrix3f();
        get(rot);
        rot.transform(up);
        return up;
    }

    public Vector3f getRight()
    {
        Vector3f right = new Vector3f(1, 0, 0);
        Matrix3f rot = new Matrix3f();
        get(rot);
        rot.transform(right);
        return right;
    }

    public void advance(float dist)
    {
        Vector3f fwd = getForward();
        fwd.scale(dist);
        translate(fwd);
    }

    public void rotateAround(Tuple3f around, Tuple3f rot)
    {
        translate(around);
        rotate(rot);
        translate(around.scaleBy(-1));
    }

    public void yaw(float aRadians)
    {
        Vector3f axis = getUp();
        System.out.println("Yawing around "+axis);
        rotate(axis.x, axis.y, axis.z, aRadians);
        //rotate(0, 1, 0, aRadians);
    }

    public void pitch(float aRadians)
    {
        Vector3f axis = getRight();
        System.out.println("Pitching around "+axis);
        rotate(axis.x, axis.y, axis.z, aRadians);
        //rotate(1, 0, 0, aRadians);
    }

    public void roll(float aRadians)
    {
        Vector3f axis = getForward();
        System.out.println("Rolling around "+axis);
        rotate(axis.x, axis.y, axis.z, aRadians);
        //rotate(0, 0, 1, aRadians);
    }

    public void reset()
    {
        mRotation = new Quat4f(0f, 0f, 0f, -1f);
        assemble();
    }
}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Vipr.Core.CodeModel;

namespace Vipr.Writer.CSharp
{
    public class FetcherUpcastMethod : UpcastMethodBase
    {
        public FetcherUpcastMethod(OdcmType baseType, OdcmType derivedType) : base(baseType, derivedType)
        {
            Name = "To" + derivedType.Name;
            Parameters = global::Vipr.Writer.CSharp.Parameters.Empty;
            ReturnType = new Type(NamesService.GetFetcherInterfaceName(derivedType));
        }
    }
}


text:
package main

/*
	Example of Logger with a time prefix
*/

import (
	logo "github.com/nurza/logo"
)

func main() {
	var l logo.Logger                  // Create a simple Logger
	t := l.AddTransport(logo.Console)  // Add a transport: Console
	t.AddColor(logo.ConsoleColor)      // Add a color: Console color
	l.AddTime("[2006-01-02 15:04:05]") // Add time template
	l.GoRoutineId = true               // Add Go routine id
	l.EnableAllLevels()                // Enable all logging levels

	l.Silly("Silly")
	l.Debug("Debug")
	l.Verbose("Verbose")
	l.Info("Info")
	l.Warn("Warn")
	l.Error("Error")
	l.Critical("Critical")
}


text:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveGeneric #-}

module Domen where

import GHC.Generics
import Data.Aeson (FromJSON, ToJSON)

data PhotoStruct = PhotoStruct  {
                                userName :: String,
                                image_src :: String,
                                date :: String,
                                description :: String
                                } deriving (Show, Generic)

data UserInfo = UserInfo {
						 userN :: String,
						 realName :: String,
						 email :: String
						 } deriving (Show, Generic)

instance ToJSON PhotoStruct
instance FromJSON PhotoStruct

instance ToJSON UserInfo
instance FromJSON UserInfo


text:
/* AVRm68k [emulator subproject]
 * (c) 2012 Justin Gottula
 * The source code of this project is distributed under the terms of the
 * simplified BSD license. See the LICENSE file for details. */

#include "all.h"

static uint8_t currentSR = SRAM_SR_MODE_BYTE;

static void setMode(uint8_t mode)
{
#warning sram codebase contains references to shift reg code
#if 0
	/* this function should only be called after an instruction sequence has
	 * been started; it will reopen an instruction sequence when finished */

	if (currentSR != mode)
	{
		/* write to the status register */
		spiByte(SRAM_INSTR_WRSR);
		spiByte(mode);

		currentSR = mode;

		/* start another instruction sequence */
		spiEnd();
		spiBeginQuick(SREG_SS_SRAM);
	}
#endif
}

uint8_t sramReadByte(uint16_t addr)
{
#warning sram codebase contains references to shift reg code
#if 0
	uint8_t byte;

	/* start an instruction sequence */
	spiBegin(SREG_SS_SRAM, SPIMODE_SRAM, SPIENDIAN_SRAM, SPIDIV_SRAM);

	/* set to byte mode (if necessary) */
	setMode(SRAM_SR_MODE_BYTE);

	/* issue the read instruction */
	spiByte(SRAM_INSTR_READ);

	/* write the address */
	spiByte(addr >> 8);
	spiByte(addr);

	/* read the data */
	byte = spiByte(0xff);

	spiEnd();

	return byte;
#endif
}

void sramWriteByte(uint16_t addr, uint8_t byte)
{
#warning sram codebase contains references to shift reg code
#if 0
	/* start an instruction sequence */
	spiBegin(SREG_SS_SRAM, SPIMODE_SRAM, SPIENDIAN_SRAM, SPIDIV_SRAM);

	/* set to byte mode (if necessary) */
	setMode(SRAM_SR_MODE_BYTE);

	/* issue the write instruction */
	spiByte(SRAM_INSTR_WRITE);

	/* write the address */
	spiByte(addr >> 8);
	spiByte(addr);

	/* write the data */
	spiByte(byte);

	spiEnd();
#endif
}

void sramReadSeq(uint16_t addr, uint16_t len, uint8_t *dest)
{
#warning sram codebase contains references to shift reg code
#if 0
	/* start an instruction sequence */
	spiBegin(SREG_SS_SRAM, SPIMODE_SRAM, SPIENDIAN_SRAM, SPIDIV_SRAM);

	/* set to sequential mode (if necessary) */
	setMode(SRAM_SR_MODE_SEQ);

	/* issue the read instruction */
	spiByte(SRAM_INSTR_READ);

	/* write the address */
	spiByte(addr >> 8);
	spiByte(addr);

	/* read the data */
	do
		*(dest++) = spiByte(0x00);
	while (--len != 0);

	spiEnd();
#endif
}

void sramWriteSeq(uint16_t addr, uint16_t len, const uint8_t *src)
{
#warning sram codebase contains references to shift reg code
#if 0
	/* start an instruction sequence */
	spiBegin(SREG_SS_SRAM, SPIMODE_SRAM, SPIENDIAN_SRAM, SPIDIV_SRAM);

	/* set to sequential mode (if necessary) */
	setMode(SRAM_SR_MODE_SEQ);

	/* issue the write instruction */
	spiByte(SRAM_INSTR_WRITE);

	/* write the address */
	spiByte(addr >> 8);
	spiByte(addr);

	/* write the data */
	do
		spiByte(*(src++));
	while (--len != 0);

	spiEnd();
#endif
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.kinesis;

import static com.google.common.base.Preconditions.checkNotNull;
import io.airlift.log.Logger;

import java.util.List;
import java.util.Map;
import java.util.Set;

import com.facebook.presto.kinesis.decoder.dummy.DummyKinesisRowDecoder;
import com.facebook.presto.spi.ColumnMetadata;
import com.facebook.presto.spi.ColumnHandle;
import com.facebook.presto.spi.ConnectorSession;
import com.facebook.presto.spi.ConnectorTableHandle;
import com.facebook.presto.spi.ConnectorTableMetadata;
import com.facebook.presto.spi.ReadOnlyConnectorMetadata;
import com.facebook.presto.spi.SchemaTableName;
import com.facebook.presto.spi.SchemaTablePrefix;
import com.facebook.presto.spi.TableNotFoundException;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Inject;
import com.google.inject.name.Named;

public class KinesisMetadata
        extends ReadOnlyConnectorMetadata
{
    private static final Logger log = Logger.get(KinesisMetadata.class);

    private final String connectorId;
    private final KinesisConnectorConfig kinesisConnectorConfig;
    private final KinesisHandleResolver handleResolver;

    private final Supplier<Map<SchemaTableName, KinesisStreamDescription>> kinesisTableDescriptionSupplier;
    private final Set<KinesisInternalFieldDescription> internalFieldDescriptions;

    @Inject
    KinesisMetadata(@Named("connectorId") String connectorId,
            KinesisConnectorConfig kinesisConnectorConfig,
            KinesisHandleResolver handleResolver,
            Supplier<Map<SchemaTableName, KinesisStreamDescription>> kinesisTableDescriptionSupplier,
            Set<KinesisInternalFieldDescription> internalFieldDescriptions)
    {
        this.connectorId = checkNotNull(connectorId, "connectorId is null");
        this.kinesisConnectorConfig = checkNotNull(kinesisConnectorConfig, "kinesisConfig is null");
        this.handleResolver = checkNotNull(handleResolver, "handleResolver is null");

        log.debug("Loading kinesis table definitions from %s", kinesisConnectorConfig.getTableDescriptionDir().getAbsolutePath());

        this.kinesisTableDescriptionSupplier = Suppliers.memoize(kinesisTableDescriptionSupplier);
        this.internalFieldDescriptions = checkNotNull(internalFieldDescriptions, "internalFieldDescriptions is null");
    }

    @Override
    public List<String> listSchemaNames(ConnectorSession session)
    {
        ImmutableSet.Builder<String> builder = ImmutableSet.builder();
        for (SchemaTableName tableName : getDefinedTables().keySet()) {
            builder.add(tableName.getSchemaName());
        }
        return ImmutableList.copyOf(builder.build());
    }

    @Override
    public KinesisTableHandle getTableHandle(ConnectorSession session, SchemaTableName schemaTableName)
    {
        KinesisStreamDescription table = getDefinedTables().get(schemaTableName);
        if (table == null) {
            throw new TableNotFoundException(schemaTableName);
        }

        return new KinesisTableHandle(connectorId,
                schemaTableName.getSchemaName(),
                schemaTableName.getTableName(),
                table.getStreamName(),
                getDataFormat(table.getMessage()));
    }

    @Override
    public ConnectorTableMetadata getTableMetadata(ConnectorTableHandle tableHandle)
    {
        KinesisTableHandle kinesisTableHandle = handleResolver.convertTableHandle(tableHandle);
        return getTableMetadata(kinesisTableHandle.toSchemaTableName());
    }

    @Override
    public List<SchemaTableName> listTables(ConnectorSession session, String schemaNameOrNull)
    {
        ImmutableList.Builder<SchemaTableName> builder = ImmutableList.builder();
        for (SchemaTableName tableName : getDefinedTables().keySet()) {
            if (schemaNameOrNull == null || tableName.getSchemaName().equals(schemaNameOrNull)) {
                builder.add(tableName);
            }
        }

        return builder.build();
    }

    @Override
    public ColumnHandle getSampleWeightColumnHandle(ConnectorTableHandle tableHandle)
    {
        return null;
    }

    @Override
    public Map<String, ColumnHandle> getColumnHandles(ConnectorTableHandle tableHandle)
    {
        KinesisTableHandle kinesisTableHandle = handleResolver.convertTableHandle(tableHandle);

        KinesisStreamDescription kinesisStreamDescription = getDefinedTables().get(kinesisTableHandle.toSchemaTableName());
        if (kinesisStreamDescription == null) {
            throw new TableNotFoundException(kinesisTableHandle.toSchemaTableName());
        }

        ImmutableMap.Builder<String, ColumnHandle> columnHandles = ImmutableMap.builder();

        int index = 0;
       /* KinesisStreamFieldGroup key = kinesisStreamDescription.getPartitionKey();
        if (key != null) {
            List<KinesisStreamFieldDescription> fields = key.getFields();
            if (fields != null) {
                for (KinesisStreamFieldDescription kinesisStreamFieldDescription : fields) {
                    columnHandles.put(kinesisStreamFieldDescription.getName(), kinesisStreamFieldDescription.getColumnHandle(connectorId, true, index++));
                }
            }
        }*/

        KinesisStreamFieldGroup message = kinesisStreamDescription.getMessage();
        if (message != null) {
            List<KinesisStreamFieldDescription> fields = message.getFields();
            if (fields != null) {
                for (KinesisStreamFieldDescription kinesisStreamFieldDescription : fields) {
                    columnHandles.put(kinesisStreamFieldDescription.getName(), kinesisStreamFieldDescription.getColumnHandle(connectorId, index++));
                }
            }
        }

        for (KinesisInternalFieldDescription kinesisInternalFieldDescription : internalFieldDescriptions) {
            columnHandles.put(kinesisInternalFieldDescription.getName(), kinesisInternalFieldDescription.getColumnHandle(connectorId, index++, kinesisConnectorConfig.isHideInternalColumns()));
        }

        return columnHandles.build();
    }

    @Override
    public ColumnMetadata getColumnMetadata(ConnectorTableHandle tableHandle, ColumnHandle columnHandle)
    {
        handleResolver.convertTableHandle(tableHandle);
        KinesisColumnHandle kinesisColumnHandle = handleResolver.convertColumnHandle(columnHandle);

        return kinesisColumnHandle.getColumnMetadata();
    }

    @Override
    public Map<SchemaTableName, List<ColumnMetadata>> listTableColumns(ConnectorSession session, SchemaTablePrefix prefix)
    {
        checkNotNull(prefix, "prefix is null");

        ImmutableMap.Builder<SchemaTableName, List<ColumnMetadata>> columns = ImmutableMap.builder();

        // what if prefix.getTableName == null
        List<SchemaTableName> tableNames = prefix.getSchemaName() == null ? listTables(session, null) : ImmutableList.of(new SchemaTableName(prefix.getSchemaName(), prefix.getTableName()));

        for (SchemaTableName tableName : tableNames) {
            ConnectorTableMetadata tableMetadata = getTableMetadata(tableName);
            if (tableMetadata != null) {
                columns.put(tableName, tableMetadata.getColumns());
            }
        }
        return columns.build();
    }

    private static String getDataFormat(KinesisStreamFieldGroup fieldGroup)
    {
        return (fieldGroup == null) ? DummyKinesisRowDecoder.NAME : fieldGroup.getDataFormat();
    }

    @VisibleForTesting
    Map<SchemaTableName, KinesisStreamDescription> getDefinedTables()
    {
        return kinesisTableDescriptionSupplier.get();
    }

    private ConnectorTableMetadata getTableMetadata(SchemaTableName schemaTableName)
    {
        KinesisStreamDescription table = getDefinedTables().get(schemaTableName);
        if (table == null) {
            throw new TableNotFoundException(schemaTableName);
        }

        ImmutableList.Builder<ColumnMetadata> builder = ImmutableList.builder();

        KinesisStreamFieldGroup message = table.getMessage();
        if (message != null) {
            List<KinesisStreamFieldDescription> fields = message.getFields();
            if (fields != null) {
                for (KinesisStreamFieldDescription fieldDescription : fields) {
                    builder.add(fieldDescription.getColumnMetadata());
                }
            }
        }

        for (KinesisInternalFieldDescription fieldDescription : internalFieldDescriptions) {
            builder.add(fieldDescription.getColumnMetadata(kinesisConnectorConfig.isHideInternalColumns()));
        }

        return new ConnectorTableMetadata(schemaTableName, builder.build());
    }
}


text:
NS_ASSUME_NONNULL_BEGIN

FOUNDATION_EXTERN NSString * const POSRxErrorDomain;
FOUNDATION_EXTERN NSInteger const POSHTTPSystemError;

#pragma mark - Gateway

@protocol POSHTTPRequest;
@protocol POSTask;
@class POSHTTPRequestExecutionOptions;

/// Performs network requests.
@protocol POSHTTPGateway <POSSchedulable>

/// Default options for request execution.
@property (nonatomic, nullable) POSHTTPRequestExecutionOptions *options;

/// Session, which manages foreground requests.
@property (nonatomic, readonly) NSURLSession *foregroundSession;

/// Session, which manages background requests.
@property (nonatomic, readonly, nullable) NSURLSession *backgroundSession;

/// @brief Sends request to specified host.
/// @param request Request which will be send to host with specified baseURL. It can not be nil.
/// @param hostURL URL, which will be combined with request's endpoint method to construct full URL. May be nil.
/// @param options Request options. May be nil.
- (id<POSTask>)taskForRequest:(id<POSHTTPRequest>)request
                       toHost:(NSURL *)hostURL
                      options:(nullable POSHTTPRequestExecutionOptions *)options;

/// @brief Recovers all background upload requests as array of POSRecoveredHTTPBackgroundUpload objects.
- (void)recoverBackgroundUploadRequestsUsingBlock:(void(^)(NSArray *uploadRequests))block;

/// @brief Invalidates all sessions, which is mandatory requirement to free memory allocated by HTTPGateway.
/// @param cancelPendingRequests YES if you want to free all allocated resources ASAP or NO to complete active requests.
- (RACSignal *)invalidateCancelingRequests:(BOOL)cancelPendingRequests;

/// @brief Asynchronously creates new backgroundSession instance.
- (void)reconnectToBackgroundSession;

@end

/// Performs network requests.
@interface POSHTTPGateway : POSSchedulableObject <POSHTTPGateway>

/// The designated initializer for launching in a background.
- (instancetype)initWithScheduler:(RACTargetQueueScheduler *)scheduler
      backgroundSessionIdentifier:(nullable NSString *)ID;

POSRX_SCHEDULABLE_INIT_RECURSIVELY_UNAVAILABLE

@end

NS_ASSUME_NONNULL_END


text:
package hu.petabyte.redflags.engine.tedintf.cached;

import static com.google.common.base.Preconditions.checkNotNull;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Scanner;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import hu.petabyte.redflags.engine.model.DisplayLanguage;
import hu.petabyte.redflags.engine.model.NoticeID;
import hu.petabyte.redflags.engine.model.Tab;

/**
 * @author Zsolt Jurányi
 */
public class GzippedNoticeCache extends SimpleNoticeCache {

	private static final Logger LOG = LoggerFactory.getLogger(GzippedNoticeCache.class);

	public GzippedNoticeCache(String directory) {
		super(directory);
	}

	@Override
	public synchronized String fetch(NoticeID id, DisplayLanguage lang, Tab tab) {
		checkNotNull(id, "id should not be null.");
		checkNotNull(lang, "lang should not be null.");
		checkNotNull(tab, "tab should not be null.");
		String fn = filename(id, lang, tab);
		File f = new File(fn);
		String r = null;
		if (f.exists()) {
			try {
				FileInputStream fileInput = new FileInputStream(f);
				InputStream gzipFileInput = new GZIPInputStream(fileInput);
				Scanner scanner = new Scanner(gzipFileInput, "UTF8");
				r = scanner.useDelimiter("\\Z").next();
				scanner.close();
				gzipFileInput.close();
				fileInput.close();
			} catch (Exception e) {
				LOG.warn("Failed to read file: " + f.getAbsolutePath(), e);
			}
		}
		return r;
	}

	@Override
	public String filename(NoticeID id, DisplayLanguage lang, Tab tab) {
		return super.filename(id, lang, tab) + ".gz";
	}

	@Override
	public synchronized boolean store(NoticeID id, DisplayLanguage lang, Tab tab, String raw) {
		checkNotNull(id, "id should not be null.");
		checkNotNull(lang, "lang should not be null.");
		checkNotNull(tab, "tab should not be null.");
		String fn = filename(id, lang, tab);
		File f = new File(fn);
		File d = f.getParentFile();
		if (null != d) {
			d.mkdirs();
		}
		FileOutputStream fileOutput = null;
		try {
			fileOutput = new FileOutputStream(fn);
			OutputStream gzipFileOutput = new GZIPOutputStream(fileOutput);
			Writer writer = new OutputStreamWriter(gzipFileOutput, "UTF-8");
			try {
				writer.write(raw);
				writer.flush();
			} finally {
				writer.close();
			}
			fileOutput.close();
			LOG.trace("Saved to cache: {}", f.getAbsolutePath());
			return true;
		} catch (Exception e) {
			LOG.warn("Failed to write file: " + f.getAbsolutePath(), e);
			return false;
		}
	}

}


text:
'use strict';

var Server = require('../core/server');
var supertest = require('supertest');

describe('base-path-support', function () {
    it('Should support base path', function (done) {
        var server = new Server({
            logging: {
                logLevel: 'SILENT'
            },
            router: {
                basePath: '/site'
            }
        });

        server.route('GET /page/', 'index');

        server.unit({
            name: 'index',
            main: function (track) {
                track.status(200).send('Okay');
            }
        });

        server.ready().done(function () {
            supertest(server.getHandler()).
                get('/site/page/').
                expect('Okay').
                end(done);
        });
    });

    it('Should respond 404', function (done) {
        var server = new Server({
            logging: {
                logLevel: 'SILENT'
            },
            router: {
                basePath: '/site'
            }
        });

        server.route('GET /page/', 'index');

        server.unit({
            name: 'index',
            main: function (track) {
                track.status(200).send('Okay');
            }
        });

        server.ready().done(function () {
            supertest(server.getHandler()).
                get('/page/').
                expect(404).
                end(done);
        });
    });

    it('Should autocomplete redirect urls with base path', function (done) {
        var server = new Server({
            logging: {
                logLevel: 'SILENT'
            },
            router: {
                basePath: '/site'
            }
        });

        server.route('GET /page/', 'index');

        server.unit({
            name: 'index',
            main: function (track) {
                track.redirect('/dest-page', 302);
            }
        });

        server.ready().done(function () {
            supertest(server.getHandler()).
                get('/site/page/').
                expect(302).
                expect('Location', /\/site\/dest-page/).
                end(done);
        });
    });

    it('Should not autocomplete redirect url pathname if the url is absolute', function (done) {
        var server = new Server({
            logging: {
                logLevel: 'SILENT'
            },
            router: {
                basePath: '/site'
            }
        });

        server.route('GET /page/', 'index');

        server.unit({
            name: 'index',
            main: function (track) {
                track.redirect('//example.com/dest-page', 302);
            }
        });

        server.ready().done(function () {
            supertest(server.getHandler()).
                get('/site/page/').
                expect(302).
                expect('Location', /\/example\.com\/dest-page/).
                end(done);
        });
    });
});


text:
"""
:mod:`ironic.tests.unit` -- ironic unit tests
=====================================================

.. automodule:: ironic.tests.unit
   :platform: Unix
"""

# TODO(deva): move eventlet imports to ironic.__init__ once we move to PBR

import eventlet

from ironic import objects

eventlet.monkey_patch(os=False)

# NOTE(comstud): Make sure we have all of the objects loaded. We do this
# at module import time, because we may be using mock decorators in our
# tests that run at import time.
objects.register_all()


text:
module V1
  def_model 'users' do
    DEFAULT_PIC_URL = 'http://coursemology.s3.amazonaws.com/public/default_profile_pic.png'
    # All photos in this CDN are not accessible any more
    INVALID_URL = 'https://fbcdn-profile-a.akamaihd.net/'

    def transform_profile_photo(logger)
      if profile_photo_url.present? &&
        profile_photo_url != DEFAULT_PIC_URL &&
        !profile_photo_url.starts_with?(INVALID_URL)

        file_name = nil
        file_name = 'facebook.jpg' if facebook_url?(profile_photo_url)
        Downloader.download_to_local(profile_photo_url, self, logger, file_name)
      end
    end

    private

    def facebook_url?(url)
      !url.starts_with?('http://coursemology.s3.amazonaws.com'.freeze) &&
        !url.starts_with?('http://coursemology.org/'.freeze)
    end
  end

  ::User.class_eval do
    # Do not create read marks, for performance.
    def setup_new_reader
    end
  end

  ::InstanceUser.before_create do
    # enum role: { normal: 0, instructor: 1, administrator: 2, auto_grader: 3 }
    v1_email = user.email
    v1_user = User.find_by(email: v1_email)
    if v1_user && v1_user.system_role_id == 3
      self.role = :instructor
    end
  end
end


text:
title: "Picoliter Dispenser for Medical Device Testing (2003)"
date: 2003-12-01T12:00:00-08:00
draft: false
short_name: "picoliter-dispenser"
tags: applications, C++, communications protocols, medical, Windows

resources:
- src: "Picoliter_Dispenser.jpg"
  name: Picoliter_Dispenser
- src: "Picoliter_Dispenser_tiny.jpg"
  name: Picoliter_Dispenser_tiny

entry_media:
- image:
    resource: "Picoliter_Dispenser"
    lazyload: "Picoliter_Dispenser_tiny"
    alt: "Photo of a picoliter print head and illustration of the piezo dispensing action"
---
A medical device startup needed to precisely dispense very tiny droplets of fluid for testing and
characterization of their product. They asked Mindtribe to help them drive a piezoelectric dispenser
for this purpose.

I created a Windows application that controls a 3NETICS PicoSpot piezoelectric dispensing head over
an RS485 link (via an off-the-shelf RS485 to RS232 adapter). The application gave our client fine
control over the quantity and location of the dispensed fluid.


text:
{% extends "shop/base.html" %}
{% load i18n %}
{% load thumbnail %}
{% load satchmo_price %}
{% load satchmo_currency %}
{% load satchmo_util satchmo_discounts %}
{% load app_plugins %}

{% block navbar %}

{% trans "Home" %}

{% trans "Quick Order Form" %}

{% endblock %}

{% block content %}

{% trans "Quick Order Form" %}

<form name="quickorder" method="post" action="{% url satchmo_quick_order %}">{% csrf_token %}

			{% trans "Price" %}
			{% trans "Qty" %}

		{% for field in form %}
		{% with field.field.product as product %}

			    {% thumbnail product.main_image.picture "84x84" as image %}

				{% endthumbnail %}

{{ product.name }}

					{{ product.description }}

				{% if sale %}{{ product|discount_price:""|currency }}{% endif %}
				{{ product|discount_price:storewide_sale|currency }}

				{{ field }}

		{% if field.errors %}

			{{ field.errors|join:"," }}

{% endif %}
		{% endwith %}
		{% endfor %}

			<input type="submit" value='{% trans "Add to Cart" %}' />

{% endblock content %}


text:
package com.communote.server.api.core.attachment;

import com.communote.server.api.core.common.IdentifiableEntityData;

/**
 * Value object for attachments.
 *
 * @author Communote GmbH - http://www.communote.com/
 */
public class AttachmentData extends IdentifiableEntityData {
    private static final long serialVersionUID = -2127376532550324997L;

    private String contentId;

    private String mimeTyp;

    private String fileName;

    private String repositoryId;

    private Long size;

    private Long noteId;

    /**
     * Does nothing.
     */
    public AttachmentData() {
        // Do nothing.
    }

    public AttachmentData(String contentId, String mimeTyp, String fileName, String repositoryId) {
        this.contentId = contentId;
        this.mimeTyp = mimeTyp;
        this.fileName = fileName;
        this.repositoryId = repositoryId;
    }

    /**
     * @return the contentId
     */
    public String getContentId() {
        return contentId;
    }

    /**
     * @return the file name of the attachment
     */
    public String getFileName() {
        return fileName;
    }

    /**
     * @return the MIME type of the attachment
     */
    public String getMimeTyp() {
        return mimeTyp;
    }

    /**
     *
     * @return id of the note the attachment is associated with. null if no note connected.
     */
    public Long getNoteId() {
        return noteId;
    }

    /**
     * @return the repositoryId
     */
    public String getRepositoryId() {
        return repositoryId;
    }

    /**
     * @return the size of the attachment in bytes
     */
    public Long getSize() {
        return size;
    }

    /**
     * @param contentId
     *            the contentId to set
     */
    public void setContentId(String contentId) {
        this.contentId = contentId;
    }

    /**
     * @param fileName
     *            the fileName to set
     */
    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    /**
     * @param mimeTyp
     *            the mimeTyp to set
     */
    public void setMimeTyp(String mimeTyp) {
        this.mimeTyp = mimeTyp;
    }

    /**
     *
     * @param noteId
     *            id of the note the attachment is associated with. null if no note connected.
     */
    public void setNoteId(Long noteId) {
        this.noteId = noteId;
    }

    /**
     * @param repositoryId
     *            the repositoryId to set
     */
    public void setRepositoryId(String repositoryId) {
        this.repositoryId = repositoryId;
    }

    /**
     * @param size
     *            the size to set
     */
    public void setSize(Long size) {
        this.size = size;
    }

}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.

namespace Microsoft.Azure.Search.Tests.Utilities
{
    using System;
    using Microsoft.Azure.Search.Models;
    using Microsoft.Rest.ClientRuntime.Azure.TestFramework;

    public class IndexerFixture : SearchServiceFixture
    {
        // The connection string we use here, as well as table name and target index schema, use the USGS database
        // that we set up to support our code samples.
        //
        // ASSUMPTION: Change tracking has already been enabled on the database with ALTER DATABASE ... SET CHANGE_TRACKING = ON
        // and it has been enabled on the table with ALTER TABLE ... ENABLE CHANGE_TRACKING
        public const string AzureSqlReadOnlyConnectionString =
            "Server=tcp:azs-playground.database.windows.net,1433;Database=usgs;User ID=reader;Password=EdrERBt3j6mZDP;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;"; // [SuppressMessage("Microsoft.Security", "CS001:SecretInline")]

        public const string AzureSqlTestTableName = "GeoNamesRI";

        public string TargetIndexName { get; private set; }

        public string DataSourceName { get; private set; }

        public override void Initialize(MockContext context)
        {
            base.Initialize(context);

            SearchServiceClient searchClient = this.GetSearchServiceClient();

            TargetIndexName = SearchTestUtilities.GenerateName();

            DataSourceName = SearchTestUtilities.GenerateName();

            var index = new Index(
                TargetIndexName,
                new[]
                {
                    new Field("feature_id", DataType.String) { IsKey = true },
                    new Field("feature_name", DataType.String) { IsFilterable = true, IsSearchable = true },
                    new Field("feature_class", DataType.String),
                    new Field("state", DataType.String) { IsFilterable = true, IsSearchable = true },
                    new Field("county_name", DataType.String) { IsFilterable = true, IsSearchable = true },
                    new Field("elevation", DataType.Int32) { IsFilterable = true },
                    new Field("map_name", DataType.String) { IsFilterable = true, IsSearchable = true },
                    new Field("history", DataType.Collection(DataType.String)) { IsSearchable = true }
                });

            searchClient.Indexes.Create(index);

            var dataSource =
                DataSource.AzureSql(
                    name: DataSourceName,
                    sqlConnectionString: AzureSqlReadOnlyConnectionString,
                    tableOrViewName: AzureSqlTestTableName);

            searchClient.DataSources.Create(dataSource);
        }

        public Indexer CreateTestIndexer()
        {
            return new Indexer(SearchTestUtilities.GenerateName(), DataSourceName, TargetIndexName)
            {
                // We can't test startTime because it's an absolute time that must be within 24 hours of the current
                // time. That doesn't play well with recorded mock payloads.
                Schedule = new IndexingSchedule(interval: TimeSpan.FromDays(1)),
                FieldMappings = new[]
                {
                    // Try all the field mapping functions (even if they don't make sense in the context of the test DB).
                    new FieldMapping("feature_class", FieldMappingFunction.Base64Encode()),
                    new FieldMapping("state_alpha", "state"),
                    new FieldMapping("county_name", FieldMappingFunction.ExtractTokenAtPosition(" ", 0)),
                    new FieldMapping("elev_in_m", "elevation"),
                    new FieldMapping("map_name", FieldMappingFunction.Base64Decode()),
                    new FieldMapping("history", FieldMappingFunction.JsonArrayToStringCollection())
                }
            };
        }

        public Indexer MutateIndexer(Indexer indexer)
        {
            indexer.Description = "Mutated Indexer";
            return indexer;
        }
    }
}


text:
FROM gcr.io/fuzzbench/base-image

# honggfuzz requires libfd and libunwid
RUN apt-get update -y && apt-get install -y libbfd-dev libunwind-dev


text:
package com.flowpowered.components;

/**
 * Represents an object that defines an attribute and stores its data.
 */
public interface Component {
}


text:
function pluck(list, propertyName) {
    // YOUR CODE HERE
}

// tests
// ---
var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}]
console.assert(pluck(stooges, 'name')[0] === 'moe')
console.assert(pluck(stooges, 'age')[2] === 60)

// -----------
// Write a function reject() that does the opposite of filter,
// if the callback function returns a "truthy" value then that
// item is **not** inserted into the new collection,
// otherwise it is.
// -----------
function reject(list, predicate) {
    // YOUR CODE HERE
}

// tests
// ---
var lt10 = [0,1,2,3,4,5,6,7,8,9,10]
var odds = reject(lt10, function(n){ return n%2 === 0 })
console.assert(odds[0] === 1)
console.assert(odds[1] === 3)
console.assert(odds[4] === 9)

// -----------
// Write a function find() that returns the very first item
// in a collection when the callback function returns true;
// otherwise returns undefined.
// -----------
function find(list, predicate) {
    // YOUR CODE HERE
}

// tests
// ---
var people = [
    {name: "Justin", teaches: "JS"},
    {name: "Jwo", teaches: "Ruby"},
    {name: "Dorton", teaches: "life"}
]
var JS = find(people, function(n){ return n.teaches === "JS" })
console.assert(JS.name === "Justin")

// -----------
// Write a function where() that filters for all the values
// in the properties object.
// -----------
function where(list, properties) {
    // YOUR CODE HERE
}

// tests
// ---
var plays = [
    {title: "Cymbeline", author: "Shakespeare", year: 1623},
    {title: "The Tempest", author: "Shakespeare", year: 1623},
    {title: "Hamlet", author: "Shakespeare", year: 1603},
    {title: "A Midsummer Night's Dream", author: "Shakespeare", year: 1600},
    {title: "Macbeth", author: "Shakespeare", year: 1620},
    {title: "Death of a Salesman", author: "Arthur Miller", year: 1949},
    {title: "Two Blind Mice", author: "Samuel and Bella Spewack", year: 1949}
]

var sh8spr = where(plays, {author: "Shakespeare"})
console.assert(sh8spr instanceof Array)
console.assert(sh8spr.length === 5)
console.assert(sh8spr[0].title === "Cymbeline")

sh8spr = where(plays, {author: "Shakespeare", year: 1611})
console.assert(sh8spr.length === 0)

sh8spr = where(plays, {author: "Shakespeare", year: 1623})
console.assert(sh8spr.length === 2)

var midcentury = where(plays, {year: 1949})
console.assert(midcentury.length === 2)


text:
import React, {Component, PropTypes} from 'react';
import {
  StyleSheet,
  View,
  Text,
  Image,
  ListView,
  ScrollView,
  TouchableOpacity,
  TouchableHighlight,
  ToolbarAndroid,
  ActivityIndicator,
  InteractionManager
} from 'react-native';

import {
  Avatar
  , Checkbox
  , Subheader
  , Divider
  , IconToggle
  , Ripple
  , Toolbar
  , Button
  , Card
  , COLOR
  , TYPO
} from 'react-native-material-design';

import { List } from './List';

import Icon from 'react-native-vector-icons/Ionicons';

import { styles } from '../app.styles';

import {OrderService} from '../services/orderservice';

import {OrderHeading} from './order-heading';
import {OrderItemList} from './order-item-list';
import {OrderPayment} from './order-payment';

export default class OrderDetailsView extends Component {
  static propTypes = {
    order_id: React.PropTypes.string.isRequired,
  };

  constructor(props) {
    super(props);
    this.state = {
      order: null,
      isLoading: false
    };
    this.service = new OrderService();
  }

  componentDidMount() {
    this.setState({
      isLoading: true
    });
    InteractionManager.runAfterInteractions(() => {
      this.loadOrderDetail();
    });
  }

  loadOrderDetail() {
    this.service.getOrderDetail(this.props.order_id).then(x => {
      this.setState({
        isLoading: false,
        order: x
      });
    });
  }

  render() {
    let spinner = this.state.isLoading ?
      (<ActivityIndicator
        color={COLOR.paperIndigo400.color}
        style={[styles.centering, { height: 80 }]}
        size="large"
        />) : (<View/>);
    let order = this.state.order;
    return (
      <ScrollView style={{ flex: 1, marginTop: 50  }}>
        {spinner}
        {order &&
          <OrderHeading order={order} />
        }
        {order &&
          <OrderItemList order={order} />
        }
        {order &&
          <OrderPayment order={order} />
        }
      </ScrollView>
    );
  }
}


text:
"""Implements a list of atoms where the data is stored in multiarrays.

Two versions are implemented, one where all information is stored in
cartesian coordinates, and one where they are stored in scaled space.

In both versions most access is done through __getattr__ to data
specified as arguments to the constructor.  If the object was
constructed with xxxx=array then they can be accessed through
GetXxxx() and SetXxxx().  The exception is positions, momenta and
forces that are accessed through GetCartesianXxxx() and
SetCartesianXxxx().

In Asap version 2.9 and later, this module is only used to create
empty atoms for use in MakeParallelAtoms.
"""

import string
import types
import Numeric
import LinearAlgebra
#import AtomInList
#import DocumentedAttributes
#from Structures.TypesFromAtomicNumbers import TypesFromAtomicNumbers
#from Structures.FakeUnitCell import FakeUnitCell
# Delayed imports:
# Visualization.Avatars.RasMol is imported in AtomsInCmFile.GetPlot()

class ListOfCartesianAtoms:
    """A list of atoms where the storage is in the form of multiarrays.

    The object is created like this:
        ListOfCartesianAtoms(positions=data, momenta=data, .....)

    The data is then accessed through the usual access functions, i.e.
    GetCartesianPositions(), GetCartesianMomenta(),
    GetCartesianForces().  Other information can be given when the
    object is initialized, for example stresses can be given as
    stesses=data.  They can then be accessed with GetStresses() and
    changed with SetStresses().
    """

    _specials = {"positions":1, "momenta":1, "forces":1}

    def __init__(self, periodicboundaries=None, **kargs):
        # Check that positions are specified, and that they are a 3xN
        # multiarray
        if not kargs.has_key("positions"):
            raise ArgumentError, "positions missing"
        try:
            shape = kargs["positions"].shape
        except AttributeError:
            raise TypeError, "positions should be a multiarray"
        if shape[1] != 3:
            raise ValueError, "positions should be an Nx3 multiarray"

	if periodicboundaries is not None:
	    self.SetPeriodicBoundaries(periodicboundaries)

        len = shape[0]
        self._len = len
        self._data = {}
        for arg in kargs.keys():
            if kargs[arg] is not None:
                shape = kargs[arg].shape
                if shape[0] != len:
                    msg = ("%s has shape %t, expected (%d, ?)." %
                           (arg, shape, len))
                    raise ValueError, msg
                self._data[arg] = kargs[arg]

    # List functions
    def __len__(self):
        return self._len

    def __getitem__(self, n):
        if n < 0 or n >= self._len:
            raise IndexError
        return AtomInList.AtomInList(self, n)

    def __getslice__(self, low, high):
        # Select the data to be used in the slice object
        newdata = {}
        for key in self._data.keys():
            newdata[key] = self._data[key][low:high]
        # Now create a new list of atoms object passing the data to the
        # constructor
        return apply(self.__class__, (), newdata)

    def extend(self, other):
	"""Extend the list of atoms by adding atoms from another list.

	The other list must at least contain the same type of data as this
	one.
	"""
	newdata = {}
	for key in self._data.keys():
	    accessfunc = "GetCartesian"+string.capitalize(key)
	    try:
		newdata[key] = getattr(other, accessfunc)()
	    except AttributeError:
		accessfunc = "Get"+string.capitalize(key)
		newdata[key] = getattr(other, accessfunc)()
	for key in self._data.keys():
	    self._data[key] = Numeric.concatenate((self._data[key], newdata[key]))

    def __add__(self, other):
	"""Add two lists of atoms."""
	newdata = {}
	for key in self._data.keys():
	    accessfunc = "GetCartesian"+string.capitalize(key)
	    try:
		otherdata = getattr(other, accessfunc)()
	    except AttributeError:
		accessfunc = "Get"+string.capitalize(key)
		otherdata = getattr(other, accessfunc)()
	    selfdata = self._data[key]
	    newdata[key] = Numeric.concatenate((selfdata, otherdata))
	return apply(self.__class__, (self.GetPeriodicBoundaries(),), newdata)

    def __delitem__(self, n):
	"""Delete an atom."""
	if n < 0 or n >= self._len:
	    raise IndexError, "list deletion index out of range."
	for key in self._data.keys():
	    d = self._data[key]
	    self._data[key] = Numeric.concatenate((d[:n], d[n+1:]))
	self._len = self._len - 1

    # We should also implement access functions that change/delete the
    # elements in the list

    # Some access functions are not handled by the generic ones

    def GetPeriodicBoundaries(self):
        """Get the periodic boundary conditions."""
        return self._periodicboundaries

    def SetPeriodicBoundaries(self, pbc):
        """Set the periodic boundary conditions."""
        if not isinstance(pbc, types.TupleType):
            raise TypeError, "Not a tuple"
        if len(pbc) != 3:
            raise ValueError, "Not a tuple of length 3"
        self._periodicboundaries = pbc

    # Visualization
    def GetPlot(self, interactive=0, debug=0):
	"""Get a RasMol avatar plotting the simulation."""
	from Visualization.Avatars.RasMol import RasMol
	return RasMol(self, interactive=interactive, debug=debug)

    # Generic access functions
    def _getdata(self):
        if self._data.has_key(self._attrname):
            return self._data[self._attrname]
        else:
            # Attempting to access a missing "attribute"
            raise AttributeError, self._requested

    def _setdata(self, coordinates):
        a = self._attrname
        if self._data.has_key(a):
            if coordinates.shape != self._data[a].shape:
                raise ValueError, "wrong shape"
        else:
            # Introducing a new sort of data
            if coordinates.shape[0] != self._len:
                raise ValueError, "wrong shape"
        self._data[a] = coordinates

    def _getsingledata(self, n):
        if self._data.has_key(self._attrname):
            return self._data[self._attrname][n]
        else:
            # Attempting to access a missing "attribute"
            raise AttributeError, self._requested

    def _setsingledata(self, n, coordinates):
        if self._data.has_key(self._attrname):
            self._data[self._attrname][n] = coordinates
        else:
            # Attempting to access a missing "attribute"
            raise AttributeError, self._requested

    def _isspecial(self):
        """Checks if access through [GS]etCartesianXXXX is meaningful."""
        if self._attrname == "momentums":
            self._attrname = "momenta"
        if not self._specials.has_key(self._attrname):
            # The access function is not allowed to exist
            raise AttributeError, self._requested

    def __getattr__(self, name):
        """Implement the access functions.

        Catches names of the type GetXXXX or GetCartesianXXXX
        or the similar SetXXXX names.
        """
        self._requested = name
        if name[:18] == "GetSingleCartesian":
            self._attrname = string.lower(name[18:])+"s"
            self._isspecial()
            return self._getsingledata
        elif name[:18] == "SetSingleCartesian":
            self._attrname = string.lower(name[18:])+"s"
            self._isspecial()
            return self._setsingledata
        elif name[:9] == "GetSingle":
            self._attrname = string.lower(name[9:])+"s"
            return self._getsingledata
        elif name[:9] == "SetSingle":
            self._attrname = string.lower(name[9:])+"s"
            return self._setsingledata
        if name[:12] == "GetCartesian":
            self._attrname = string.lower(name[12:])
            self._isspecial()
            return self._getdata
        elif name[:12] == "SetCartesian":
            self._attrname = string.lower(name[12:])
            self._isspecial()
            return self._setdata
        elif name[:3] == "Get":
            self._attrname = string.lower(name[3:])
            return self._getdata
        elif name[:3] == "Set":
            self._attrname = string.lower(name[3:])
            return self._setdata
        else:
            raise AttributeError, name

def _lowerplural(str):
    """Returns the plural of an attribute name converted to lower case."""
    try:
        return string.lower(_pluralmap[str])
    except KeyError:
        return string.lower(str+"s")

Attributes = (
    ("Position", "The position."),
    ("Momentum", "The momentum of the atom.", "Momenta"),
    ("Force", "The forces on the atoms."),
    ("Class", "An integer 'classifying' the atoms.", "Classes"),
    ("Type",
     "An object describing the type of the atoms, e.g. the chemical element."),
    ("AtomicNumber", "The atomic number of the atom."),
    ("Energy", "The energy of the atom", "Energies"),
    ("Mass", "The mass of the atom", "Masses"),
    ("Velocity", "The derivative of the position.", "Velocities"))

def _pl(t):
    l = len(t)
    assert l == 2 or l == 3
    if l == 2:
        return (t[0], t[0]+"s")
    elif l == 3:
        return (t[0], t[2])
    else:
        raise AssertionError, "Internal error in _pl, length is not 2 or 3."

Plurals = map(_pl, Attributes)

del _pl

_pluralmap = {}
for _i in Plurals:
    _pluralmap[_i[0]] = _i[1]
del _i


text:
using System;
using System.Threading.Tasks;
using Azimuth.DataAccess.Entities;
using Azimuth.Infrastructure.Concrete;
using Azimuth.Infrastructure.Interfaces;
using Azimuth.Shared.Dto;
using Newtonsoft.Json;

namespace Azimuth.DataProviders.Concrete
{
    public class FacebookAccountProvider: AccountProvider
    {
        public string UserInfoUrl { get; private set; }

        public FacebookAccountProvider(IWebClient webClient, UserCredential userCredential)
            :base(webClient)
        {
            if (userCredential.AccessToken == null)
            {
                throw new ArgumentException("FacebookAccountProvider didn't receive accessToken");
            }

            var accessToken = userCredential.AccessToken;
            UserInfoUrl = String.Format(@"https://graph.facebook.com/v2.0/me?access_token={0}&fields=id,first_name,last_name,name,gender,email,birthday,timezone,location,picture.type(large)",
                    accessToken);
        }

        public override async Task<User> GetUserInfoAsync(string email = "")
        {
            // Make query to Facebook Api
            var userDataJson = await _webClient.GetWebData(UserInfoUrl);
            var userData = JsonConvert.DeserializeObject<FacebookUserData>(userDataJson);

            return Mapper.Map(userData, new User());
        }
    }
}


text:
namespace rpc
{

typedef boost::shared_ptr<class Buffer> BufferPtr;

class Buffer
{
public:
	struct end_of_data: public std::exception
	{
		char const *what() const throw()
		{
			return "end of data";
		}
	};

	Buffer():
		data_((char *) malloc(size_)),
		size_(SIZE_1),
		read_(data_),
		write_(data_)
	{
		if (!data_) throw std::bad_alloc();
	}

	Buffer(Buffer const &rhs):
		data_((char *) malloc(rhs.size_)),
		size_(rhs.size_),
		read_(rhs.read_offset() + data_),
		write_(rhs.write_offset() + data_)
	{
		if (!data_) throw std::bad_alloc();
		memcpy(data_, rhs.data_, rhs.write_offset());
	}

	void swap(Buffer &rhs)
	{
		std::swap(data_, rhs.data_);
		std::swap(size_, rhs.size_);
		std::swap(read_, rhs.read_);
		std::swap(write_, rhs.write_);
	}

	Buffer &operator =(Buffer const &rhs)
	{
		if (&rhs != this)
		{
			Buffer(rhs).swap(*this);
		}

		return *this;
	}

	~Buffer()
	{
		if (data_)
		{
			free(data_);
		}
	}

	void enlarge()
	{
		if (size_ != SIZE_1) throw std::bad_alloc();

		char *data = (char *) realloc(data_, SIZE_2);
		if (!data) throw std::bad_alloc();

		read_ = (read_ - data_) + data;
		write_ = (write_ - data_) + data;
		data_ = data;
		size_ = SIZE_2;
	}

	void *begin_ptr() const { return data_; }
	void *read_ptr() const { return read_; }
	size_t read_offset() const { return read_ - data_; }
	size_t read_bytes_available() const { return write_ - read_; }
	void seek_read(ptrdiff_t delta) { read_ += delta; }
	void set_read(size_t offset) { read_ = data_ + offset; }
	void *write_ptr() const { return write_; }
	size_t write_offset() const { return write_ - data_; }
	size_t write_bytes_available() const { return size_ - write_offset(); }
	void seek_write(ptrdiff_t delta) { write_ += delta; }
	void set_write(size_t offset) { write_ = data_ + offset; }

	void read(void *buffer, size_t size)
	{
		if (read_ + size > write_) throw end_of_data();

		memcpy(buffer, read_, size);
		read_ += size;
	}

	void write(void const *buffer, size_t size)
	{
		if (write_offset() + size >= size_) enlarge();

		memcpy(write_, buffer, size);
		write_ += size;
	}

	void consume(size_t size)
	{
		memcpy(data_, data_ + size, size_ - size);

		read_ -= size;
		write_ -= size;
	}

private:
	static size_t const SIZE_1 = 4096;
	static size_t const SIZE_2 = SIZE_1 + 65536;

	size_t size_;
	char *data_;
	char *read_, *write_;
};

}


text:
package tw.edu.ncu.cc.manage.dao;

import java.util.List;
import java.util.Optional;

import tw.edu.ncu.cc.manage.domain.AuthorizedToken;

public interface IAuthorizedTokenDao {
	List<AuthorizedToken> findByUsername(String username);

	Optional<AuthorizedToken> find(String tokenId);

	void revoke(AuthorizedToken token);
}


text:
package com.senseidb.search.client.json.req;

public class Path extends Selection {

  private String value;
  private boolean strict;
  private int depth;

  public Path(String value, boolean strict, int depth) {
    super();

    this.value = value;
    this.strict = strict;
    this.depth = depth;
  }

  public Path() {

  }

  public String getValue() {
    return value;
  }

}