text:
<?php

namespace Safan\Router;

use Safan\GlobalData\Get;
use Safan\Loader\SplClassLoader;
use Safan\Safan;

class Router
{
    /**
     * @var array
     */
    private $httpRoutes = [];

    /**
     * @var array
     */
    private $cliRoutes = [];

    /**
     * Check http routes for module
     */
    public function checkHttpRoutes()
    {
        // get modules
        $modules = Safan::handler()->getModules();

        $frameworkDefaultRoute = [];

        // get all routes
        foreach ($modules as $moduleName => $modulePath) {
            $routerFile = APP_BASE_PATH . DS . $modulePath . DS . 'Resources' . DS . 'config' . DS . 'router.config.php';

            if (file_exists($routerFile)) {
                $route = include($routerFile);

                if ($moduleName != 'SafanResponse') {
                    $this->httpRoutes = array_replace($this->httpRoutes, $route);
                } else {
                    $frameworkDefaultRoute = $route;
                }
            }
        }

        // merge default route
        foreach ($frameworkDefaultRoute as $route => $routeParam) {
            if (!isset($this->httpRoutes[$route])) {
                $this->httpRoutes[$route] = $routeParam;
            }
        }
    }

    /**
     * Check cli routes for module
     */
    public function checkCliRoutes()
    {
        // get modules
        $modules = Safan::handler()->getModules();

        // get all routes
        foreach ($modules as $moduleName => $modulePath) {
            $routerFile = APP_BASE_PATH . DS . $modulePath . DS . 'Resources' . DS . 'config' . DS . 'cli.router.config.php';

            if (file_exists($routerFile)) {
                $route           = include($routerFile);
                $this->cliRoutes = array_merge($this->cliRoutes, $route);
            }
        }
    }

    /**
     * @param string $uri
     * @return bool
     */
    public function checkUri(string $uri = ''): bool
    {
        $isMatch = false;

        foreach ($this->httpRoutes as $rule => $settings) {
            $matches = [];

            if (preg_match($rule, $uri, $matches)) {
                Get::setParams('module', $settings['module']);
                Get::setParams('controller', $settings['controller']);
                Get::setParams('action', $settings['action']);

                $route['matches'] = [];

                foreach ($settings['matches'] as $key => $varName) {
                    if (empty($varName)) {
                        continue;
                    }

                    if (isset($matches[$key])) {
                        $_GET[$varName] = $matches[$key];
                    }
                }

                return $isMatch = true;
            }
        }

        if (!$isMatch) {
            $this->checkUri('/404');
        }
    }

    /**
     * @param $command
     * @return bool
     */
    public function checkCliCommand(string $command)
    {
        $isMatch        = false;
        $matchedCommand = [];

        foreach ($this->cliRoutes as $rule => $settings) {
            $matches = [];

            if (preg_match($rule, $command, $matches)) {
                $isMatch = true;

                if (isset($settings['important']) && $settings['important']) {
                    $matchedCommand = [
                        'command' => $this->cliRoutes[$rule],
                        'matches' => $matches
                    ];

                    break;
                } else {
                    $matchedCommand = [
                        'command' => $this->cliRoutes[$rule],
                        'matches' => $matches
                    ];
                }
            }
        }

        if ($isMatch) {
            $this->selectCommand($matchedCommand['command'], $matchedCommand['matches']);
        } else {
            $this->checkCliCommand('/404');
        }
    }

    /**
     * @param array $command
     * @param array $matches
     */
    private function selectCommand(array $command, array $matches = [])
    {
        Get::setParams('module', $command['module']);
        Get::setParams('controller', $command['controller']);
        Get::setParams('action', $command['action']);

        $route['matches'] = [];

        foreach ($command['matches'] as $key => $varName) {
            if (empty($varName)) {
                continue;
            }

            if (isset($matches[$key])){
                $_GET[$varName] = $matches[$key];
            }
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
  <application>appinventor</application>
  <version>1</version>

  <!-- Configure serving/caching of GWT files -->
  <static-files>
    <include path="/blockly-all.js">
      <http-header name="Content-Type" value="application/javascript; charset=UTF-8" />
    </include>
    <include path="**" />

    <!-- The following line requires App Engine 1.3.2 SDK -->
    <include path="**.nocache.*" expiration="0s" />

    <include path="**.cache.*" expiration="365d" />
    <exclude path="**.gwt.rpc" />

    <!-- don't serve the key file as a static file! -->
    <exclude path="/keystore/**" />

    <!-- don't serve the whitelist as a static file! -->
    <exclude path="/whitelist" />

  </static-files>

  <!-- Configuration and flags -->
  <system-properties>
    <property name="java.util.logging.config.file" value="WEB-INF/logging.properties"/>

    <!-- note that the file: is necessary as part of the value for this property, because
         the log4j configuration is looking for a URL -->
    <property name="log4j.configuration" value="file:WEB-INF/log4j.properties"/>

    <!-- set to true if users should not be allowed to access the App
         Inventor server unless they are listed in the appengine/war/whitelist file -->
    <property name="use.whitelist" value="false"/>

    <!-- set to true if users need to accept a Terms of Service the first time
      they access App Inventor -->
    <property name="require.tos" value="true" />

    <!-- host[:port] to use for connecting to the build server -->
    <property name="build.server.host" value="localhost:9990" />

    <!-- Interval is seconds between checking for a message of the day.
         Set set to 0 to disable checking for a MOTD.  If you do enable
         MOTD checking, make the interval long, because this check is
         resource expensive on App Engine -->
    <property name="motd.check.interval.secs" value="0" />

    <!-- Set this to false if we should not send the Git build version with build requests.
         This is useful when testing new servers where we don't want to require the
         buildserver to match -->
    <property name="build.send.git.version" value="true" />

    <!-- Set this to true to enable the use of Wifi connections from the blocks editor to
         the phone. The phone must have an up-to-date copy of the MIT AICompanion App to
         use this feature. -->

    <property name="wifi.enabled" value="true" />

  </system-properties>

  <!-- Enable concurrency in the app engine server -->
  <threadsafe>true</threadsafe>

</appengine-web-app>

redpajama_set_name: RedPajamaGithub


text:
package com.jjrili.ui;

import java.util.Observer;

/**
 * SUtils
 * Created by ChuanliangShang
 * on 16/8/3.
 *
 * 正如BaseConfigObservable所描述,一个配置变量改变后,所有的BaseActivity和BaseFragment都会得到这个配置改变的通知,如何做到的呢,就是通过这个interface。
 * 首先BaseActivity实现了这个interface,
 * 其次在BaseApplication中维护了所有BaseActivity向BaseConfigObservable注册|解注册监听。
 * 最后在BaseActivity中维护了其下所有BaseFragment的配置改变通知回调。
 *
 */
public interface BaseConfigObserver extends Observer {
}


text:
package main

import (
	"crypto/rand"
	"database/sql"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"os/exec"
	"sync"
	"time"

	"github.com/gorilla/mux"
	"github.com/gorilla/websocket"
	"github.com/wirepair/gcd"
	"github.com/wirepair/gcd/gcdapi"

	_ "github.com/lib/pq"
)

type websocketMessage struct {
	messageType int
	data        []byte
}

type RequestInfo struct {
	Headers map[string]string `json:"headers"`
	Url     string            `json:"url"`
	Method  string            `json:"method"`
	Key     string            `json:"key"`
	HasBody bool              `json:"hasBody"`
}

type ResponseInfo struct {
	Headers map[string]string `json:"headers"`
	Status  int               `json:"status"`
	Body    string            `json:"body"`
}
type Response struct {
	Key  string       `json:"key"`
	Info ResponseInfo `json:"info"`
}

type DBRequest struct {
	Key   string `json:"key"`
	Value string `json:"value"`
	Type  string `json:"type"`
}

var upgrader = websocket.Upgrader{}
var websocketChannel chan websocketMessage
var requests = map[string](chan ResponseInfo){}
var dbChannel chan DBRequest
var lock = sync.RWMutex{}

const appTableName = "app_table"

func init() {
	// arbitrary buffers
	websocketChannel = make(chan websocketMessage, 100)
	dbChannel = make(chan DBRequest, 100)
}

func main() {
	fmt.Println("hi")
}

func connectToDB() (db *sql.DB) {
	var err error
	db, err = sql.Open("postgres", "postgres://root@cockroach:26257/dcdn?sslmode=disable")
	if err != nil {
		log.Fatal(err)
	}
	return db
}

func dropAppTable(db *sql.DB, tableName string) (err error) {
	_, err = db.Exec(fmt.Sprintf("DROP TABLE %s", tableName))
	return
}

func createAppTable(db *sql.DB, tableName string) (name string, err error) {
	if tableName == "" {
		nameBytes := make([]byte, 15)
		_, err = rand.Read(nameBytes)
		if err != nil {
			fmt.Println("error:", err)
		}
		nameHex := "appKV_" + hex.EncodeToString(nameBytes)
		tableName = nameHex
	}
	name = tableName
	_, err = db.Exec(fmt.Sprintf("CREATE TABLE %s (key TEXT UNIQUE, value TEXT)", tableName))
	return
}

func getKeyValue(db *sql.DB, tableName string,
	key string) (value string, err error) {

	rows, err := db.Query(
		fmt.Sprintf("SELECT value FROM %s where key=$1", tableName), key)
	defer rows.Close()
	if err != nil {
		return
	}
	for rows.Next() {
		err = rows.Scan(&value)
		if err != nil {
			return
		}
		return
	}
	return
}

func writeKeyValue(db *sql.DB, tableName string, key string,
	value string) (err error) {

	_, err = db.Query(fmt.Sprintf(`
        INSERT INTO
            %s(key, value)
            VALUES($1, $2)
        ON CONFLICT (key)
            DO UPDATE SET value = $2
        `, tableName), key, value)
	return
}

func setUpDatabase() {
	db := connectToDB()
	_, err := createAppTable(db, appTableName)
	print(err)
	go func() {
		for {
			dbRequest := <-dbChannel
			_ = dbRequest
			// if dbRequest
		}
	}()
}

func writeRequest(key string) (reqChannel chan ResponseInfo) {
	reqChannel = make(chan ResponseInfo, 1)
	lock.Lock()
	defer lock.Unlock()
	requests[key] = reqChannel
	return reqChannel
}

func getRequestChannel(key string) (reqChannel chan ResponseInfo) {
	lock.RLock()
	defer lock.RUnlock()
	return requests[key]
}

func deleteRequest(key string) {
	lock.Lock()
	defer lock.Unlock()
	delete(requests, key)
}

func fullyLaunchServers() (srvA *http.Server, srvD *http.Server) {
	now := time.Now()
	srvA = launchApplication()
	srvD = launchDriver()

	for {
		// TODO: add endpoint for testing driver?
		resp, err := quickGet("http://localhost:4041/")
		if err != nil {
			fmt.Println(err)
			continue
		}
		if resp.StatusCode == 200 {
			break
		} else {
			time.Sleep(time.Millisecond * 100)
		}
	}
	elapsed := time.Since(now)
	fmt.Printf("Launching servers took %f seconds.\n", elapsed.Seconds())

	return
}

func launchApplication() (srv *http.Server) {
	r := mux.NewRouter()

	setUpDatabase()

	r.HandleFunc("/", userCodeHandler)
	r.HandleFunc("/ws", websocketHandler)
	port := "4041"
	srv = &http.Server{
		Handler:      r,
		Addr:         "0.0.0.0:" + port,
		WriteTimeout: 15 * time.Second,
		ReadTimeout:  15 * time.Second,
	}
	fmt.Println("Websocket comm listening on " + port)
	go func() {
		log.Println(srv.ListenAndServe())
	}()
	return srv
}

func launchDriver() (srv *http.Server) {
	handler := http.HandlerFunc(driverHandler)
	port := "4040"
	srv = &http.Server{
		Handler:      handler,
		Addr:         "0.0.0.0:" + port,
		WriteTimeout: 15 * time.Second,
		ReadTimeout:  15 * time.Second,
	}
	fmt.Println("Driver listening on " + port)
	go func() {
		log.Println(srv.ListenAndServe())
	}()
	return srv
}

func driverHandler(w http.ResponseWriter, r *http.Request) {
	var requestInfo RequestInfo
	requestInfo.Url = r.URL.String()
	requestInfo.Method = r.Method

	requestInfo.Headers = make(map[string]string)

	for k, v := range r.Header {
		// assume there are only single header values
		// for now
		requestInfo.Headers[k] = v[0]
	}

	if requestInfo.Headers["Content-Length"] != "" {
		requestInfo.HasBody = true
	}

	id := make([]byte, 20)
	_, err := rand.Read(id)
	if err != nil {
		fmt.Println("error:", err)
	}
	hexStrId := hex.EncodeToString(id)

	requestInfo.Key = hexStrId
	messageBytes, err := json.Marshal(requestInfo)
	if err != nil {
		fmt.Println("error:", err)
	}
	message := websocketMessage{
		messageType: websocket.TextMessage,
		data:        messageBytes,
	}
	websocketChannel <- message

	if requestInfo.HasBody {
		go func() {
			var total int
			for {
				// decide what the optimal size is here
				chunk := make([]byte, 1500)
				n, err := r.Body.Read(chunk)
				total += n

				if n > 0 {
					toSend := append(id, chunk[:n]...)
					message := websocketMessage{
						messageType: websocket.BinaryMessage,
						data:        toSend,
					}
					websocketChannel <- message
				}
				if err == io.EOF {
					break
				}
			}
		}()
	}

	reqChannel := writeRequest(hexStrId)
	defer deleteRequest(hexStrId)

	resp := <-reqChannel
	for k, v := range resp.Headers {
		w.Header().Add(k, v)
	}
	w.WriteHeader(resp.Status)
	w.Write([]byte(resp.Body))
}

func userCodeHandler(w http.ResponseWriter, r *http.Request) {
	http.ServeFile(w, r, "./index.html")
}

func websocketHandler(w http.ResponseWriter, r *http.Request) {
	conn, err := upgrader.Upgrade(w, r, nil)
	print("websocket connected")
	if err != nil {
		log.Println("error upgrading:", err)
		return
	}
	defer conn.Close()

	go func() {
		for {
			mt, message, err := conn.ReadMessage()
            if err != nil {
                fmt.Println(err)
                break
            }
			_, _ = mt, message
			fmt.Println(string(message))
			var resp Response
			err = json.Unmarshal(message, &resp)
			if err != nil {
				print(message)
				fmt.Println(err)
				continue
			}
			print(resp)
			reqChannel := getRequestChannel(resp.Key)
			reqChannel <- resp.Info
			if err != nil {
				log.Println("read:", err)
				break
			}
		}
	}()

	for {
		toSend := <-websocketChannel
		err = conn.WriteMessage(toSend.messageType, toSend.data)
		if err != nil {
			log.Println("write:", err)
			continue
		}
	}
}

func print(things ...interface{}) {
	fmt.Printf("%#v\n", things...)
}

func quickGet(url string) (resp *http.Response, err error) {
	timeout := time.Duration(100 * time.Millisecond)
	client := http.Client{
		Timeout: timeout,
	}
	return client.Get(url)
}

func launchBrowser(location string) (cmd *exec.Cmd, err error) {
	// unclear if this is better
	// both open 4 chrome processes
	// if you run the process headless without a debugger port it opens 3.
	// so tab, browser view, and something else
	// debugger is one chrome process
	// hmm

	// does not occupy debugging port, gcd does
	cmd = exec.Command(
		"/usr/bin/google-chrome-unstable",
		"--headless",
		"--disable-gpu",
		"--disable-web-security",
		"--remote-debugging-address=0.0.0.0",
		"--remote-debugging-port=9222",
		"--user-data-dir=/data",
		location,
	)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	err = cmd.Start()
	return cmd, err
}

func launchBrowserAndDebugger(location string) (debugger *gcd.Gcd) {
	var wg sync.WaitGroup
	wg.Add(1)

	debugger = gcd.NewChromeDebugger()
	debugger.AddFlags([]string{
		"--disable-gpu", // required currently for headless
		"--headless",
		"--disable-web-security",             // disables CORS
		"--remote-debugging-address=0.0.0.0", // redundant?
		"--remote-debugging-port=9222",       // redundant?
		"--user-data-dir=/data",              // redundant?
		// user-data-dir will tie chrome processes together, consider making this
		// dyanmic
	})
	debugger.StartProcess(
		"/usr/bin/google-chrome-unstable",
		"/data",
		"9222",
	)
	// defer debugger.ExitProcess()

	targets, err := debugger.GetTargets()
	if err != nil {
		log.Fatalf("error getting targets: %s\n", err)
	}
	if err != nil {
		log.Fatalf("error getting targets: %s\n", err)
	}
	target := targets[0]

	target.Subscribe("Page.loadEventFired", func(targ *gcd.ChromeTarget, v []byte) {
		wg.Done()
		// if you wanted to inspect the full response
		// data, you could do that here
	})

	console := target.Console
	runtime := target.Runtime

	target.Subscribe("Console.messageAdded", func(target *gcd.ChromeTarget, v []byte) {

		msg := &gcdapi.ConsoleMessageAddedEvent{}
		err := json.Unmarshal(v, msg)
		if err != nil {
			log.Fatalf("error unmarshalling event data: %v\n", err)
		}
		log.Printf("Console log: %s\n", msg.Params.Message.Text)
	})

	target.Subscribe("Runtime.exceptionThrown", func(target *gcd.ChromeTarget, v []byte) {

		msg := &gcdapi.RuntimeExceptionThrownEvent{}
		err := json.Unmarshal(v, msg)
		if err != nil {
			log.Fatalf("error unmarshalling event data: %v\n", err)
		}
		log.Printf(
			"Error: %s %s\n",
			msg.Params.ExceptionDetails.Text,
			msg.Params.ExceptionDetails.Exception.Description,
		)
	})

	runtime.Enable()
	console.Enable()

	// get the Page API and enable it
	if _, err := target.Page.Enable(); err != nil {
		log.Fatalf("error getting page: %s\n", err)
	}

	ret, err := target.Page.Navigate(location, "", "") // navigate
	if err != nil {
		log.Fatalf("Error navigating: %s\n", err)
	}
	log.Printf("ret: %#v\n", ret)

	wg.Wait()
	print("loaded")
	return debugger
}


text:
using System.Collections.Generic;
using System;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using Debug = UnityEngine.Debug;

namespace AssetHandeling_AtlasLoader
{
    /// <summary>
    /// Body of generated object xml
    /// </summary>
    public class XMLO_AL_IsoObejct : IXmlSerializable
    {

        public string name { get; protected set; }
        public int miplevels { get; protected set; }
        public List<XMLO_AL_Direction> directions;

        public int width { get; protected set; }
        public int length { get; protected set; }
        public int height { get; protected set; }

        public bool is_light { get; protected set; }
        public int light_radius { get; protected set; }

        /// <summary>
        /// Default constructor
        /// </summary>
        public XMLO_AL_IsoObejct()
        {
            name = "VOID";
            miplevels = -1;
            directions = new List<XMLO_AL_Direction>();

            width = -1;
            length = -1;
            height = -1;

            is_light = false;
            light_radius = 8;
        }

        public XmlSchema GetSchema()
        {
            return null;
        }

        public void WriteXml(XmlWriter writer)
        {

        }

        public void ReadXml(XmlReader reader)
        {
            try
            {

                readerRead(reader);

                XmlSerializer serializer = new XmlSerializer(typeof(XMLO_AL_Direction));
                reader.ReadToFollowing("directions");

                if (reader.ReadToDescendant("XMLO_AL_Direction"))
                {
                    do
                    {
                        //Debug.Log("RAN3: "+reader.Name);
                        directions.Add((XMLO_AL_Direction)serializer.Deserialize(reader));
                    } while (reader.ReadToNextSibling("XMLO_AL_Direction"));
                }

            }
            catch (Exception e)
            {
                Debug.Log(e);
            }
        }

        /// <summary>
        /// Main attribute reader
        /// </summary>
        void readerRead(XmlReader reader)
        {
            while (reader.MoveToNextAttribute())
            {
                switch (reader.Name)
                {

                    case "miplevels":
                        miplevels = reader.ReadContentAsInt();
                        break;

                    case "name":
                        name = reader.ReadContentAsString();
                        break;

                    case "length":
                        length = reader.ReadContentAsInt();
                        break;

                    case "width":
                        width = reader.ReadContentAsInt();
                        break;

                    case "height":
                        height = reader.ReadContentAsInt();
                        break;

                    case "is_light":
                        is_light = reader.ReadContentAsBoolean();
                        break;

                    case "light_radius":
                        light_radius = reader.ReadContentAsInt();
                        break;

                    default:
                        Debug.Log("Warning switch: " + reader.Name);
                        break;
                }
            }
        }

        public XMLO_AL_Direction getDirection(string dir)
        {
            foreach (XMLO_AL_Direction d in directions)
            {
                if (dir == d.direction)
                    return d;

            }

            Debug.Log("XMLO_AL_IsoObejct[" + name + "]: Did not find direction: " + dir);
            return null;
        }

    }
}


text:
package tmdb

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"strconv"
)

// create an interface and make a cached version ??
// or like befor where we do it completel diff?

const imageSize = "original"

// Tmdb Types
type TmdbApi struct {
	ApiKey string
	Config tmdbConfig
	client *http.Client
	mirror string
}

func NewTmdbApi(apiKey string, client *http.Client) (*TmdbApi, error) {
	if client == nil {
		client = &http.Client{}
	}
	tmdbApi := &TmdbApi{
		ApiKey: apiKey,
		client: client,
		mirror: "http://api.themoviedb.org/3",
	}

	_url := tmdbApi.mirror + "/configuration"
	err := tmdbApi.get(&tmdbApi.Config, _url, url.Values{})
	if err != nil {
		return nil, err
	}

	return tmdbApi, nil
}

func (tmdbApi *TmdbApi) get(response interface{}, __url string, params url.Values) error {
	params.Set("api_key", tmdbApi.ApiKey)
	_url, err := url.Parse(__url + "?" + params.Encode())
	if err != nil {
		return err
	}

	req, err := http.NewRequest("GET", _url.String(), nil)
	if err != nil {
		return err
	}
	req.Header.Add("Accept", "application/json")

	resp, err := tmdbApi.client.Do(req)
	if err != nil {
		return err
	}

	jsonDec := json.NewDecoder(resp.Body)
	err = jsonDec.Decode(response)
	if err != nil {
		return err
	}

	resp.Body.Close()
	return nil
}

func (t *TmdbApi) LookupMovies(title string, year int) []Movie {
	_url := fmt.Sprintf("%s/search/movie", t.mirror)

	values := make(url.Values)
	values.Set("query", title)
	if year != -1 {
		values.Set("year", strconv.Itoa(year))
	}

	var results []Movie

	maxPages := 1
	more := true
	for more {

		movieResPage := tmdbMovieResultPage{}
		err := t.get(&movieResPage, _url, values)
		if err != nil {
			panic(err) // TODO: handle this
		}
		for _, res := range movieResPage.Results {
			results = append(results, Movie(res))
		}

		maxPages--
		if movieResPage.Page >= movieResPage.Total_pages || maxPages <= 0 {
			more = false
		}
	}

	return results
}

func (t *TmdbApi) DownloadImage(suffix string) (imageBytes []byte, err error) {
	_url := t.url(t.Config.Images.BaseUrl + imageSize + suffix)

	req, err := http.NewRequest("GET", _url, nil)
	if err != nil {
		return nil, err
	}

	resp, err := t.client.Do(req)
	if err != nil {
		return nil, err
	}
	return ioutil.ReadAll(resp.Body)
}

func (t *TmdbApi) url(path string) string {
	return fmt.Sprintf("%s/", path)
}


text:
@class LRMockObject;
@class LRMockery;
@class LRInvocationExpectation;
@class LRMockyState;
@class LRImposterizer;

@interface LRExpectationBuilder : NSObject {
  LRMockery *mockery;
  LRInvocationExpectation *currentExpectation;
  LRImposterizer *imposterizer;
}
+ (id)builderInContext:(LRMockery *)context;
- (id)initWithMockery:(LRMockery *)aMockery;
- (id)receives; // syntatic sugar
- (id)oneOf:(id)mockObject;
- (id)exactly:(int)numberOfTimes of:(id)mockObject;
- (id)atLeast:(int)minimum of:(id)mockObject;
- (id)atMost:(int)maximum of:(id)mockObject;
- (id)between:(int)minimum and:(int)maximum of:(id)mockObject;
- (id)will:(id<LRExpectationAction>)action;
- (id)allowing:(id)mockObject;
- (id)never:(id)mockObject;
- (void)shouldTransitionToState:(LRMockyState *)state;
- (void)requiresState:(LRMockyState *)state;
@end

#ifdef LRMOCKY_SUGAR
#define mockery()           [LRMockery mockeryForTestCase:self]
#define that                LRExpectationBuilder *builder
#define andThen(action)     [builder will:action]
#define andReturn(object)   [builder will:returnsObject(object)];
#define oneOf(arg)          [builder oneOf:arg]
#define allowing(arg)       [builder allowing:arg]
#define never(arg)          [builder never:arg]
#define exactly(x)           builder exactly:x
#define atLeast(x)           builder atLeast:x
#define atMost(x)            builder atMost:x
#define between(x, y)        builder between:x and:y
#define then(state)         [builder shouldTransitionToState:state]
#define when(state)         [builder requiresState:state];
#define stub(arg)           [builder allowing:arg]
#define matching(matcher)   (id)matcher
#endif

#ifndef LRMOCKY_KIWI_COMPATIBILITY_MODE
#define it                  builder
#endif


text: lein do clean, ring uberjar && docker build -t ebot-api .


text:
@class FavoritesItem, NSString;

@protocol FavoritesUploadMgrDelegate <NSObject>

@optional
- (void)onUploadFavoritesItem:(FavoritesItem *)arg1 LocalDataId:(NSString *)arg2 FinishedLength:(int)arg3 TotalLength:(int)arg4;
- (void)onUploadFavoritesItemFinished:(FavoritesItem *)arg1 ErrCode:(int)arg2;
- (void)onUsedCapacityUpdate:(unsigned long long)arg1;
@end


text:
/**
 * GetAccessTokenResponse.java
 *
 * This file was auto-generated from WSDL
 * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
 */

package com.reasonablespread.service;

public class GetAccessTokenResponse  implements java.io.Serializable {
    private java.lang.String getAccessTokenResult;

    public GetAccessTokenResponse() {
    }

    public GetAccessTokenResponse(
           java.lang.String getAccessTokenResult) {
           this.getAccessTokenResult = getAccessTokenResult;
    }

    /**
     * Gets the getAccessTokenResult value for this GetAccessTokenResponse.
     *
     * @return getAccessTokenResult
     */
    public java.lang.String getGetAccessTokenResult() {
        return getAccessTokenResult;
    }

    /**
     * Sets the getAccessTokenResult value for this GetAccessTokenResponse.
     *
     * @param getAccessTokenResult
     */
    public void setGetAccessTokenResult(java.lang.String getAccessTokenResult) {
        this.getAccessTokenResult = getAccessTokenResult;
    }

    private java.lang.Object __equalsCalc = null;
    public synchronized boolean equals(java.lang.Object obj) {
        if (!(obj instanceof GetAccessTokenResponse)) return false;
        GetAccessTokenResponse other = (GetAccessTokenResponse) obj;
        if (obj == null) return false;
        if (this == obj) return true;
        if (__equalsCalc != null) {
            return (__equalsCalc == obj);
        }
        __equalsCalc = obj;
        boolean _equals;
        _equals = true &&
            ((this.getAccessTokenResult==null && other.getGetAccessTokenResult()==null) ||
             (this.getAccessTokenResult!=null &&
              this.getAccessTokenResult.equals(other.getGetAccessTokenResult())));
        __equalsCalc = null;
        return _equals;
    }

    private boolean __hashCodeCalc = false;
    public synchronized int hashCode() {
        if (__hashCodeCalc) {
            return 0;
        }
        __hashCodeCalc = true;
        int _hashCode = 1;
        if (getGetAccessTokenResult() != null) {
            _hashCode += getGetAccessTokenResult().hashCode();
        }
        __hashCodeCalc = false;
        return _hashCode;
    }

    // Type metadata
    private static org.apache.axis.description.TypeDesc typeDesc =
        new org.apache.axis.description.TypeDesc(GetAccessTokenResponse.class, true);

    static {
        typeDesc.setXmlType(new javax.xml.namespace.QName("http://service.reasonablespread.com/", ">GetAccessTokenResponse"));
        org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("getAccessTokenResult");
        elemField.setXmlName(new javax.xml.namespace.QName("http://service.reasonablespread.com/", "GetAccessTokenResult"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
    }

    /**
     * Return type metadata object
     */
    public static org.apache.axis.description.TypeDesc getTypeDesc() {
        return typeDesc;
    }

    /**
     * Get Custom Serializer
     */
    public static org.apache.axis.encoding.Serializer getSerializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanSerializer(
            _javaType, _xmlType, typeDesc);
    }

    /**
     * Get Custom Deserializer
     */
    public static org.apache.axis.encoding.Deserializer getDeserializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanDeserializer(
            _javaType, _xmlType, typeDesc);
    }

}


text:
package gwt.material.errai.client.local;

import com.google.gwt.user.client.ui.Composite;
import gwt.material.design.client.constants.ButtonType;
import gwt.material.design.client.constants.InputType;
import gwt.material.design.client.constants.WavesType;
import gwt.material.design.client.ui.MaterialButton;
import gwt.material.design.client.ui.MaterialTextBox;
import org.jboss.errai.ui.nav.client.local.Navigation;
import org.jboss.errai.ui.nav.client.local.Page;
import org.jboss.errai.ui.shared.api.annotations.DataField;
import org.jboss.errai.ui.shared.api.annotations.Templated;

import javax.annotation.PostConstruct;
import javax.inject.Inject;

@Templated
@Page(path = "page")
public class SignupPage extends Composite {

    @Inject
    @DataField("firstname")
    MaterialTextBox txtFirstName = new MaterialTextBox();

    @Inject
    @DataField("lastname")
    MaterialTextBox txtLastName = new MaterialTextBox();

    @Inject
    @DataField("username")
    MaterialTextBox txtUserName = new MaterialTextBox();

    @DataField("email")
    MaterialTextBox txtEmail = new MaterialTextBox();

    @Inject
    @DataField("password")
    MaterialTextBox txtPassword = new MaterialTextBox();

    @Inject
    @DataField("re-password")
    MaterialTextBox txtRePassword = new MaterialTextBox();

    @Inject
    @DataField("signup")
    MaterialButton btnSignUp = new MaterialButton();

    @Inject
    @DataField("login")
    MaterialButton btnLogin = new MaterialButton();

    @Inject
    Navigation navigation;

    @PostConstruct
    public void init() {
        txtFirstName.setPlaceholder("First Name");
        txtFirstName.setGrid("l6 m6 s12");

        txtLastName.setPlaceholder("Last Name");
        txtLastName.setGrid("l6 m6 s12");

        txtUserName.setPlaceholder("Username");
        txtUserName.setGrid("l6 m6 s12");

        txtEmail.setPlaceholder("Email");
        txtEmail.setGrid("l6 m6 s12");

        txtPassword.setPlaceholder("Password");
        txtPassword.setType(InputType.PASSWORD);
        txtPassword.setGrid("l6 m6 s12");

        txtRePassword.setPlaceholder("Retype your Password");
        txtRePassword.setGrid("l6 m6 s12");
        txtRePassword.setType(InputType.PASSWORD);

        btnLogin.setText("Login");
        btnLogin.setType(ButtonType.FLAT);
        btnLogin.setWaves(WavesType.DEFAULT);

        btnSignUp.setText("Sign Up");
        btnSignUp.setBackgroundColor("blue");
        btnSignUp.setWaves(WavesType.DEFAULT);
    }
}


text:
package org.scorpion.jmugen.core.maths;

public final class Vector3f {

    public final float x, y, z;

    public static final Vector3f ZERO = new Vector3f(0f, 0f, 0f);

    public Vector3f(float x, float y, float z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }
}


text:
#include "extractor/extractor_callbacks.hpp"
#include "extractor/external_memory_node.hpp"
#include "extractor/extraction_containers.hpp"
#include "extractor/extraction_node.hpp"
#include "extractor/extraction_way.hpp"
#include "extractor/guidance/road_classification.hpp"
#include "extractor/restriction.hpp"

#include "util/for_each_pair.hpp"
#include "util/guidance/turn_lanes.hpp"
#include "util/simple_logger.hpp"

#include <boost/numeric/conversion/cast.hpp>
#include <boost/optional/optional.hpp>
#include <boost/tokenizer.hpp>

#include <osmium/osm.hpp>

#include "osrm/coordinate.hpp"

#include <iterator>
#include <limits>
#include <string>
#include <vector>

namespace osrm
{
namespace extractor
{

using TurnLaneDescription = guidance::TurnLaneDescription;
namespace TurnLaneType = guidance::TurnLaneType;

ExtractorCallbacks::ExtractorCallbacks(ExtractionContainers &extraction_containers)
    : external_memory(extraction_containers)
{
    // we reserved 0, 1, 2, 3 for the empty case
    string_map[MapKey("", "", "", "")] = 0;
    lane_description_map[TurnLaneDescription()] = 0;
}

/**
 * Takes the node position from osmium and the filtered properties from the lua
 * profile and saves them to external memory.
 *
 * warning: caller needs to take care of synchronization!
 */
void ExtractorCallbacks::ProcessNode(const osmium::Node &input_node,
                                     const ExtractionNode &result_node)
{
    external_memory.all_nodes_list.push_back(
        {util::toFixed(util::FloatLongitude{input_node.location().lon()}),
         util::toFixed(util::FloatLatitude{input_node.location().lat()}),
         OSMNodeID{static_cast<std::uint64_t>(input_node.id())},
         result_node.barrier,
         result_node.traffic_lights});
}

void ExtractorCallbacks::ProcessRestriction(
    const boost::optional<InputRestrictionContainer> &restriction)
{
    if (restriction)
    {
        external_memory.restrictions_list.push_back(restriction.get());
        // util::SimpleLogger().Write() << "from: " << restriction.get().restriction.from.node <<
        //                           ",via: " << restriction.get().restriction.via.node <<
        //                           ", to: " << restriction.get().restriction.to.node <<
        //                           ", only: " << (restriction.get().restriction.flags.is_only ?
        //                           "y" : "n");
    }
}
/**
 * Takes the geometry contained in the ```input_way``` and the tags computed
 * by the lua profile inside ```parsed_way``` and computes all edge segments.
 *
 * Depending on the forward/backwards weights the edges are split into forward
 * and backward edges.
 *
 * warning: caller needs to take care of synchronization!
 */
void ExtractorCallbacks::ProcessWay(const osmium::Way &input_way, const ExtractionWay &parsed_way)
{
    if (((0 >= parsed_way.forward_speed) ||
         (TRAVEL_MODE_INACCESSIBLE == parsed_way.forward_travel_mode)) &&
        ((0 >= parsed_way.backward_speed) ||
         (TRAVEL_MODE_INACCESSIBLE == parsed_way.backward_travel_mode)) &&
        (0 >= parsed_way.duration))
    { // Only true if the way is specified by the speed profile
        return;
    }

    if (input_way.nodes().size() <= 1)
    { // safe-guard against broken data
        return;
    }

    if (std::numeric_limits<decltype(input_way.id())>::max() == input_way.id())
    {
        util::SimpleLogger().Write(logDEBUG) << "found bogus way with id: " << input_way.id()
                                             << " of size " << input_way.nodes().size();
        return;
    }

    InternalExtractorEdge::WeightData forward_weight_data;
    InternalExtractorEdge::WeightData backward_weight_data;

    if (0 < parsed_way.duration)
    {
        const unsigned num_edges = (input_way.nodes().size() - 1);
        // FIXME We devide by the numer of nodes here, but should rather consider
        // the length of each segment. We would eigther have to compute the length
        // of the whole way here (we can't: no node coordinates) or push that back
        // to the container and keep a reference to the way.
        forward_weight_data.duration = parsed_way.duration / num_edges;
        forward_weight_data.type = InternalExtractorEdge::WeightType::WAY_DURATION;
        backward_weight_data.duration = parsed_way.duration / num_edges;
        backward_weight_data.type = InternalExtractorEdge::WeightType::WAY_DURATION;
    }
    else
    {
        if (parsed_way.forward_speed > 0 &&
            parsed_way.forward_travel_mode != TRAVEL_MODE_INACCESSIBLE)
        {
            forward_weight_data.speed = parsed_way.forward_speed;
            forward_weight_data.type = InternalExtractorEdge::WeightType::SPEED;
        }
        if (parsed_way.backward_speed > 0 &&
            parsed_way.backward_travel_mode != TRAVEL_MODE_INACCESSIBLE)
        {
            backward_weight_data.speed = parsed_way.backward_speed;
            backward_weight_data.type = InternalExtractorEdge::WeightType::SPEED;
        }
    }

    if (forward_weight_data.type == InternalExtractorEdge::WeightType::INVALID &&
        backward_weight_data.type == InternalExtractorEdge::WeightType::INVALID)
    {
        util::SimpleLogger().Write(logDEBUG) << "found way with bogus speed, id: "
                                             << input_way.id();
        return;
    }

    // FIXME this need to be moved into the profiles
    const guidance::RoadClassification road_classification = parsed_way.road_classification;
    const auto laneStringToDescription = [](const std::string &lane_string) -> TurnLaneDescription {
        if (lane_string.empty())
            return {};

        TurnLaneDescription lane_description;

        typedef boost::tokenizer<boost::char_separator<char>> tokenizer;
        boost::char_separator<char> sep("|", "", boost::keep_empty_tokens);
        boost::char_separator<char> inner_sep(";", "");
        tokenizer tokens(lane_string, sep);

        const constexpr std::size_t num_osm_tags = 11;
        const constexpr char *osm_lane_strings[num_osm_tags] = {"none",
                                                                "through",
                                                                "sharp_left",
                                                                "left",
                                                                "slight_left",
                                                                "slight_right",
                                                                "right",
                                                                "sharp_right",
                                                                "reverse",
                                                                "merge_to_left",
                                                                "merge_to_right"};

        const constexpr TurnLaneType::Mask masks_by_osm_string[num_osm_tags + 1] = {
            TurnLaneType::none,
            TurnLaneType::straight,
            TurnLaneType::sharp_left,
            TurnLaneType::left,
            TurnLaneType::slight_left,
            TurnLaneType::slight_right,
            TurnLaneType::right,
            TurnLaneType::sharp_right,
            TurnLaneType::uturn,
            TurnLaneType::merge_to_left,
            TurnLaneType::merge_to_right,
            TurnLaneType::empty}; // fallback, if string not found

        for (auto iter = tokens.begin(); iter != tokens.end(); ++iter)
        {
            tokenizer inner_tokens(*iter, inner_sep);
            guidance::TurnLaneType::Mask lane_mask = inner_tokens.begin() == inner_tokens.end()
                                                         ? TurnLaneType::none
                                                         : TurnLaneType::empty;
            for (auto token_itr = inner_tokens.begin(); token_itr != inner_tokens.end();
                 ++token_itr)
            {
                auto position =
                    std::find(osm_lane_strings, osm_lane_strings + num_osm_tags, *token_itr);
                const auto translated_mask =
                    masks_by_osm_string[std::distance(osm_lane_strings, position)];
                if (translated_mask == TurnLaneType::empty)
                {
                    // if we have unsupported tags, don't handle them
                    util::SimpleLogger().Write(logDEBUG) << "Unsupported lane tag found: \""
                                                         << *token_itr << "\"";
                    return {};
                }

                // In case of multiple times the same lane indicators withn a lane, as in
                // "left;left|.."  or-ing the masks generates a single "left" enum.
                // Which is fine since this is data issue and we can't represent it anyway.
                lane_mask |= translated_mask;
            }
            // add the lane to the description
            lane_description.push_back(lane_mask);
        }
        return lane_description;
    };

    // convert the lane description into an ID and, if necessary, remembr the description in the
    // description_map
    const auto requestId = [&](const std::string &lane_string) {
        if (lane_string.empty())
            return INVALID_LANE_DESCRIPTIONID;
        TurnLaneDescription lane_description = laneStringToDescription(std::move(lane_string));

        const auto lane_description_itr = lane_description_map.find(lane_description);
        if (lane_description_itr == lane_description_map.end())
        {
            const LaneDescriptionID new_id =
                boost::numeric_cast<LaneDescriptionID>(lane_description_map.size());
            lane_description_map[lane_description] = new_id;
            return new_id;
        }
        else
        {
            return lane_description_itr->second;
        }
    };

    // Deduplicates street names, refs, destinations, pronunciation based on the string_map.
    // In case we do not already store the key, inserts (key, id) tuple and return id.
    // Otherwise fetches the id based on the name and returns it without insertion.
    const auto turn_lane_id_forward = requestId(parsed_way.turn_lanes_forward);
    const auto turn_lane_id_backward = requestId(parsed_way.turn_lanes_backward);

    const constexpr auto MAX_STRING_LENGTH = 255u;
    // Get the unique identifier for the street name, destination, and ref
    const auto name_iterator = string_map.find(
        MapKey(parsed_way.name, parsed_way.destinations, parsed_way.ref, parsed_way.pronunciation));
    unsigned name_id = EMPTY_NAMEID;
    if (string_map.end() == name_iterator)
    {
        const auto name_length = std::min<unsigned>(MAX_STRING_LENGTH, parsed_way.name.size());
        const auto destinations_length =
            std::min<unsigned>(MAX_STRING_LENGTH, parsed_way.destinations.size());
        const auto pronunciation_length =
            std::min<unsigned>(MAX_STRING_LENGTH, parsed_way.pronunciation.size());
        const auto ref_length = std::min<unsigned>(MAX_STRING_LENGTH, parsed_way.ref.size());

        // name_offsets already has an offset of a new name, take the offset index as the name id
        name_id = external_memory.name_offsets.size() - 1;

        external_memory.name_char_data.reserve(external_memory.name_char_data.size() + name_length +
                                               destinations_length + pronunciation_length +
                                               ref_length);

        std::copy(parsed_way.name.c_str(),
                  parsed_way.name.c_str() + name_length,
                  std::back_inserter(external_memory.name_char_data));
        external_memory.name_offsets.push_back(external_memory.name_char_data.size());

        std::copy(parsed_way.destinations.c_str(),
                  parsed_way.destinations.c_str() + destinations_length,
                  std::back_inserter(external_memory.name_char_data));
        external_memory.name_offsets.push_back(external_memory.name_char_data.size());

        std::copy(parsed_way.pronunciation.c_str(),
                  parsed_way.pronunciation.c_str() + pronunciation_length,
                  std::back_inserter(external_memory.name_char_data));
        external_memory.name_offsets.push_back(external_memory.name_char_data.size());

        std::copy(parsed_way.ref.c_str(),
                  parsed_way.ref.c_str() + ref_length,
                  std::back_inserter(external_memory.name_char_data));
        external_memory.name_offsets.push_back(external_memory.name_char_data.size());

        auto k = MapKey{
            parsed_way.name, parsed_way.destinations, parsed_way.ref, parsed_way.pronunciation};
        auto v = MapVal{name_id};
        string_map.emplace(std::move(k), std::move(v));
    }
    else
    {
        name_id = name_iterator->second;
    }

    const bool split_edge = (parsed_way.forward_speed > 0) &&
                            (TRAVEL_MODE_INACCESSIBLE != parsed_way.forward_travel_mode) &&
                            (parsed_way.backward_speed > 0) &&
                            (TRAVEL_MODE_INACCESSIBLE != parsed_way.backward_travel_mode) &&
                            ((parsed_way.forward_speed != parsed_way.backward_speed) ||
                             (parsed_way.forward_travel_mode != parsed_way.backward_travel_mode) ||
                             (turn_lane_id_forward != turn_lane_id_backward));

    external_memory.used_node_id_list.reserve(external_memory.used_node_id_list.size() +
                                              input_way.nodes().size());

    std::transform(input_way.nodes().begin(),
                   input_way.nodes().end(),
                   std::back_inserter(external_memory.used_node_id_list),
                   [](const osmium::NodeRef &ref) {
                       return OSMNodeID{static_cast<std::uint64_t>(ref.ref())};
                   });

    const bool is_opposite_way = TRAVEL_MODE_INACCESSIBLE == parsed_way.forward_travel_mode;

    // traverse way in reverse in this case
    if (is_opposite_way)
    {
        BOOST_ASSERT(split_edge == false);
        BOOST_ASSERT(parsed_way.backward_travel_mode != TRAVEL_MODE_INACCESSIBLE);
        util::for_each_pair(
            input_way.nodes().crbegin(),
            input_way.nodes().crend(),
            [&](const osmium::NodeRef &first_node, const osmium::NodeRef &last_node) {
                external_memory.all_edges_list.push_back(
                    InternalExtractorEdge(OSMNodeID{static_cast<std::uint64_t>(first_node.ref())},
                                          OSMNodeID{static_cast<std::uint64_t>(last_node.ref())},
                                          name_id,
                                          backward_weight_data,
                                          true,
                                          false,
                                          parsed_way.roundabout,
                                          parsed_way.is_access_restricted,
                                          parsed_way.is_startpoint,
                                          parsed_way.backward_travel_mode,
                                          false,
                                          turn_lane_id_backward,
                                          road_classification));
            });

        external_memory.way_start_end_id_list.push_back(
            {OSMWayID{static_cast<std::uint32_t>(input_way.id())},
             OSMNodeID{static_cast<std::uint64_t>(input_way.nodes().back().ref())},
             OSMNodeID{
                 static_cast<std::uint64_t>(input_way.nodes()[input_way.nodes().size() - 2].ref())},
             OSMNodeID{static_cast<std::uint64_t>(input_way.nodes()[1].ref())},
             OSMNodeID{static_cast<std::uint64_t>(input_way.nodes()[0].ref())}});
    }
    else
    {
        const bool forward_only =
            split_edge || TRAVEL_MODE_INACCESSIBLE == parsed_way.backward_travel_mode;
        util::for_each_pair(
            input_way.nodes().cbegin(),
            input_way.nodes().cend(),
            [&](const osmium::NodeRef &first_node, const osmium::NodeRef &last_node) {
                external_memory.all_edges_list.push_back(
                    InternalExtractorEdge(OSMNodeID{static_cast<std::uint64_t>(first_node.ref())},
                                          OSMNodeID{static_cast<std::uint64_t>(last_node.ref())},
                                          name_id,
                                          forward_weight_data,
                                          true,
                                          !forward_only,
                                          parsed_way.roundabout,
                                          parsed_way.is_access_restricted,
                                          parsed_way.is_startpoint,
                                          parsed_way.forward_travel_mode,
                                          split_edge,
                                          turn_lane_id_forward,
                                          road_classification));
            });
        if (split_edge)
        {
            BOOST_ASSERT(parsed_way.backward_travel_mode != TRAVEL_MODE_INACCESSIBLE);
            util::for_each_pair(
                input_way.nodes().cbegin(),
                input_way.nodes().cend(),
                [&](const osmium::NodeRef &first_node, const osmium::NodeRef &last_node) {
                    external_memory.all_edges_list.push_back(InternalExtractorEdge(
                        OSMNodeID{static_cast<std::uint64_t>(first_node.ref())},
                        OSMNodeID{static_cast<std::uint64_t>(last_node.ref())},
                        name_id,
                        backward_weight_data,
                        false,
                        true,
                        parsed_way.roundabout,
                        parsed_way.is_access_restricted,
                        parsed_way.is_startpoint,
                        parsed_way.backward_travel_mode,
                        true,
                        turn_lane_id_backward,
                        road_classification));
                });
        }

        external_memory.way_start_end_id_list.push_back(
            {OSMWayID{static_cast<std::uint32_t>(input_way.id())},
             OSMNodeID{static_cast<std::uint64_t>(input_way.nodes().back().ref())},
             OSMNodeID{
                 static_cast<std::uint64_t>(input_way.nodes()[input_way.nodes().size() - 2].ref())},
             OSMNodeID{static_cast<std::uint64_t>(input_way.nodes()[1].ref())},
             OSMNodeID{static_cast<std::uint64_t>(input_way.nodes()[0].ref())}});
    }
}

guidance::LaneDescriptionMap &&ExtractorCallbacks::moveOutLaneDescriptionMap()
{
    return std::move(lane_description_map);
}
} // namespace extractor
} // namespace osrm


text:
package uk.gov.nationalarchives.droid.results.handlers;

import java.net.URI;

import uk.gov.nationalarchives.droid.profile.ProfileResourceNode;
import uk.gov.nationalarchives.droid.profile.ProfileResultObserver;

/**
 * @author rflitcroft
 *
 */
public interface ProgressMonitor {

    /** value for indeterminate answer. */
    int INDETERMINATE_PROGRESS = -1;

    /**
     * Sets the maximum count.
     *
     * @param count
     *            the maximum count to set
     */
    void setTargetCount(long count);

    /**
     * Gets the progress percentage: -1 indicates indeterminate progress.
     *
     * @return the progress as a percentage.
     *
     */
    int getProgressPercentage();

    /**
     * @return the maximum count.
     */
    long getProfileSize();

    /**
     *
     * @return the number of identifications made.
     */
    long getIdentificationCount();

    /**
     * Sets an observer to fired whenever the progress percentage increments.
     *
     * @param observer
     *            the observer to set
     */
    void setPercentIncrementObserver(ProgressObserver observer);

    /**
     * @param uri
     *            the URI of the job.
     */
    void startJob(URI uri);

    /**
     * @param uri
     *            the URI of the job
     */
    void stopJob(ProfileResourceNode uri);

    /**
     * @param resultObserver ResultObserver.
     */
    void setResultObserver(ProfileResultObserver resultObserver);

    /**
     * Initialised the progress monitor to some initial state.
     * @param targetCount the target count
     * @param currentCount the actual count
     */
    void initialise(long targetCount, long currentCount);

    /**
     * @return the target number of identifications (100%)
     */
    long getTargetCount();

}


text:
namespace core
{
	namespace util
	{
		bool parse_json_string_with_callback(const char* buffer, size_t buffer_length, JsonLoaderCallback callback, void* context)
		{
			bool is_success = false;

			Json::Value root;
			Json::Reader reader;
			ConfigLoadStatus status = ConfigLoad_Failure;
			is_success = reader.parse(buffer, buffer+buffer_length, root);
			if (is_success)
			{
				status = callback(root, context);
			}
			else
			{
				LOGV("json parsing failed: %s\n", reader.getFormattedErrorMessages().c_str());
			}

			return is_success && (status == ConfigLoad_Success);
		} // parse_json_string_with_callback

		bool json_load_with_callback(const char* filename, JsonLoaderCallback callback, void* context, bool)
		{
			size_t buffer_size = 0;
			char * buffer = 0;
			bool is_success = false;

			// load the file into a memory buffer
			buffer = core::filesystem::instance()->virtual_load_file(filename, 0, &buffer_size);
			if ( buffer )
			{
				is_success = parse_json_string_with_callback( buffer, buffer_size, callback, context );
				core::filesystem::instance()->free_file_memory(buffer);
			}
			else
			{
				is_success = false;
				// Do we need this at this level? callee should handle this and
				// report an error...
//				fprintf(stderr, "ERROR loading %s\n", filename);
			}

			return is_success;
		} // json_load_with_callback
	} // mamespace util
} // namespace core


text:
using System.Collections.Generic;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Math.EC;

namespace BitcoinUtilities
{
    /// <summary>
    /// Specification: https://en.bitcoin.it/wiki/Private_key
    /// </summary>
    public static class BitcoinPrivateKey
    {
        public const int KeyLength = 32;

        private static readonly byte[] MinValue = new byte[]
        {
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01
        };

        private static readonly byte[] MaxValue = new byte[]
        {
            0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE,
            0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B, 0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x40
        };

        /// <summary>
        /// Creates a valid private key that passes <see cref="IsStrong"/> checks.
        /// </summary>
        /// <param name="random">The source of random data for the key.</param>
        /// <returns>An array of 32 bytes with the generated private key.</returns>
        public static byte[] Create(SecureRandom random)
        {
            bool goodKey = false;
            byte[] privateKey = null;

            while (!goodKey)
            {
                privateKey = random.NextBytes(32);
                goodKey = IsStrong(privateKey);
            }

            return privateKey;
        }

        /// <summary>
        /// Checks that the given array is a valid private key.
        /// </summary>
        /// <param name="privateKey">The array of 32 bytes to validate.</param>
        /// <returns>true if the given byte array is a valid private key; otherwise, false.</returns>
        public static bool IsValid(byte[] privateKey)
        {
            if (privateKey == null)
            {
                return false;
            }
            if (privateKey.Length != KeyLength)
            {
                return false;
            }
            if (Compare(privateKey, MinValue) < 0)
            {
                return false;
            }
            if (Compare(privateKey, MaxValue) > 0)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// Performs checks on the given private key to ensure that it looks random.
        /// </summary>
        /// <param name="privateKey">The array of 32 bytes to validate.</param>
        /// <returns>true if the given byte array is a valid private key that looks random; otherwise, false.</returns>
        public static bool IsStrong(byte[] privateKey)
        {
            if (!IsValid(privateKey))
            {
                return false;
            }

            if (!IsRandomArray(privateKey))
            {
                return false;
            }

            var privateKeyNumber = new BigInteger(1, privateKey);
            var invPrivateKeyNumber = privateKeyNumber.ModInverse(Secp256K1Curve.GroupSize);
            byte[] invPrivateKey = invPrivateKeyNumber.ToByteArrayUnsigned();

            if (!IsRandomArray(invPrivateKey))
            {
                return false;
            }

            return true;
        }

        //todo: add XMLDOC, add tests
        public static byte[] ToEncodedPublicKey(byte[] privateKey, bool compressed)
        {
            // todo: validate parameters
            ECPoint publicKeyPoint = Secp256K1Curve.G.Multiply(new BigInteger(1, privateKey));

            // Compressed and uncopressed formats are defined in "SEC 1: Elliptic Curve Cryptography" in section "2.3.3 Elliptic-Curve-Point-to-Octet-String Conversion".
            // see: http://www.secg.org/sec1-v2.pdf
            return publicKeyPoint.GetEncoded(compressed);
        }

        //todo: add XMLDOC, add tests
        public static byte[] ToEncodedPublicKeyHash(byte[] privateKey, bool compressed)
        {
            // todo: validate parameters
            byte[] publicKey = ToEncodedPublicKey(privateKey, compressed);
            return CryptoUtils.RipeMd160(CryptoUtils.Sha256(publicKey));
        }

        private static bool IsRandomArray(byte[] privateKey)
        {
            HashSet<byte> distinctBytes = new HashSet<byte>();
            HashSet<byte> distinctDeltas = new HashSet<byte>();

            // skip leading zeros
            int from = 0;
            while (from < privateKey.Length && privateKey[from] == 0)
            {
                from++;
            }

            // skip trailing zeros
            int to = privateKey.Length - 1;
            while (to >= 0 && privateKey[to] == 0)
            {
                to--;
            }

            int actualLength = to - from + 1;

            for (int i = 0; i < actualLength; i++)
            {
                byte b0 = privateKey[from + i];
                byte b1 = privateKey[from + (i + 1)%actualLength];
                byte delta = (byte) (b1 - b0);

                distinctBytes.Add(b0);
                distinctDeltas.Add(delta);
            }

            if (distinctBytes.Count < 24)
            {
                return false;
            }

            if (distinctDeltas.Count < 24)
            {
                return false;
            }

            return true;
        }

        private static int Compare(byte[] privateKey1, byte[] privateKey2)
        {
            for (int i = 0; i < KeyLength; i++)
            {
                if (privateKey1[i] < privateKey2[i])
                {
                    return -1;
                }
                if (privateKey1[i] > privateKey2[i])
                {
                    return 1;
                }
            }
            return 0;
        }
    }
}


text:
// Generated from /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar

#pragma once

#include <fwd-POI.hpp>
#include <java/lang/fwd-POI.hpp>
#include <java/util/regex/fwd-POI.hpp>
#include <java/util/regex/Pattern_CharProperty.hpp>

struct default_init_tag;

class java::util::regex::Pattern_BmpCharProperty
    : public Pattern_CharProperty
{

public:
    typedef Pattern_CharProperty super;

    /*void ctor(); (private) */

public: /* package */
    bool match(Matcher* matcher, int32_t i, ::java::lang::CharSequence* seq) override;

    // Generated

public:
    Pattern_BmpCharProperty();
protected:
    Pattern_BmpCharProperty(const ::default_init_tag&);

public:
    static ::java::lang::Class *class_();

private:
    virtual ::java::lang::Class* getClass0();
};


text:
from .item_meta import ItemMeta
from .page_meta import PageMeta


text:
FOUNDATION_EXPORT double ElixirVersionNumber;

//! Project version string for Elixir.
FOUNDATION_EXPORT const unsigned char ElixirVersionString[];

#import <Elixir/ELXObject.h>


text:
require 'spec_helper'

describe "sys_password_policies", type: :feature, dbscope: :example, js: true do
  context "basic crud" do
    let(:password_limit_days) { rand(1..100) }
    let(:password_warning_days) { rand(1..password_limit_days) }
    let(:password_min_length) { rand(12..20) }
    let(:password_min_upcase_length) { rand(1..3) }
    let(:password_min_downcase_length) { rand(1..3) }
    let(:password_min_digit_length) { rand(1..3) }
    let(:password_min_symbol_length) { rand(1..3) }
    let(:password_prohibited_char) { %w(a b c d e f g h i j k l).sample(3).join }
    let(:password_min_change_char_count) { rand(1..4) }

    before { login_sys_user }

    it do
      visit sys_password_policy_path
      click_on I18n.t("ss.links.edit")

      within "form#item-form" do
        select I18n.t("ss.options.state.enabled"), from: "item[password_limit_use]"
        fill_in "item[password_limit_days]", with: password_limit_days

        select I18n.t("ss.options.state.enabled"), from: "item[password_warning_use]"
        fill_in "item[password_warning_days]", with: password_warning_days

        select I18n.t("ss.options.state.enabled"), from: "item[password_min_use]"
        fill_in "item[password_min_length]", with: password_min_length

        select I18n.t("ss.options.state.enabled"), from: "item[password_min_upcase_use]"
        fill_in "item[password_min_upcase_length]", with: password_min_upcase_length

        select I18n.t("ss.options.state.enabled"), from: "item[password_min_upcase_use]"
        fill_in "item[password_min_upcase_length]", with: password_min_upcase_length

        select I18n.t("ss.options.state.enabled"), from: "item[password_min_downcase_use]"
        fill_in "item[password_min_downcase_length]", with: password_min_downcase_length

        select I18n.t("ss.options.state.enabled"), from: "item[password_min_digit_use]"
        fill_in "item[password_min_digit_length]", with: password_min_digit_length

        select I18n.t("ss.options.state.enabled"), from: "item[password_min_symbol_use]"
        fill_in "item[password_min_symbol_length]", with: password_min_symbol_length

        select I18n.t("ss.options.state.enabled"), from: "item[password_prohibited_char_use]"
        fill_in "item[password_prohibited_char]", with: password_prohibited_char

        select I18n.t("ss.options.state.enabled"), from: "item[password_min_change_char_use]"
        fill_in "item[password_min_change_char_count]", with: password_min_change_char_count

        click_on I18n.t("ss.buttons.save")
      end

      expect(page).to have_css('#notice', text: I18n.t('ss.notice.saved'))

      Sys::Setting.first.tap do |setting|
        expect(setting.password_limit_use).to eq "enabled"
        expect(setting.password_limit_days).to eq password_limit_days

        expect(setting.password_warning_use).to eq "enabled"
        expect(setting.password_warning_days).to eq password_warning_days

        expect(setting.password_min_use).to eq "enabled"
        expect(setting.password_min_length).to eq password_min_length

        expect(setting.password_min_upcase_use).to eq "enabled"
        expect(setting.password_min_upcase_length).to eq password_min_upcase_length

        expect(setting.password_min_downcase_use).to eq "enabled"
        expect(setting.password_min_downcase_length).to eq password_min_downcase_length

        expect(setting.password_min_digit_use).to eq "enabled"
        expect(setting.password_min_digit_length).to eq password_min_digit_length

        expect(setting.password_min_symbol_use).to eq "enabled"
        expect(setting.password_min_symbol_length).to eq password_min_symbol_length

        expect(setting.password_prohibited_char_use).to eq "enabled"
        expect(setting.password_prohibited_char).to eq password_prohibited_char

        expect(setting.password_min_change_char_use).to eq "enabled"
        expect(setting.password_min_change_char_count).to eq password_min_change_char_count
      end
    end
  end

  context "password expiration" do
    let!(:setting) do
      Sys::Setting.create(
        password_limit_use: "enabled", password_limit_days: 10,
        password_warning_use: "enabled", password_warning_days: 5
      )
    end

    before do
      login_sys_user
    end

    context "when password is expired" do
      it do
        sys_user.set(password_changed_at: Time.zone.now.beginning_of_hour - setting.password_limit_days.days)
        visit sns_mypage_path
        within "div.warning" do
          expect(page).to have_link(I18n.t("ss.warning.password_expired"), href: sns_cur_user_account_path)
        end
      end
    end

    context "when password is nearly expired" do
      it do
        sys_user.set(password_changed_at: Time.zone.now.beginning_of_hour - setting.password_warning_days.days)
        visit sns_mypage_path
        within "div.warning" do
          expect(page).to have_link(I18n.t("ss.warning.password_neary_expired"), href: sns_cur_user_account_path)
        end
      end
    end

    context "when password is alived" do
      it do
        visit sns_mypage_path
        expect(page).to have_no_css("div.warning")
      end
    end
  end

  context "password validation with password policy" do
    # at first, you must create a user
    let!(:user) { sys_user }

    let(:chars) { (" ".."~").to_a }
    let(:upcases) { ("A".."Z").to_a }
    let(:downcases) { ("a".."z").to_a }
    let(:digits) { ("0".."9").to_a }
    let(:symbols) { chars - upcases - downcases - digits }
    let(:prohibited_chars) { chars.sample(rand(4..6)).join.strip.split('') }
    let!(:setting) do
      Sys::Setting.create(
        password_min_use: "enabled", password_min_length: rand(16..20),
        password_min_upcase_use: "enabled", password_min_upcase_length: rand(2..4),
        password_min_downcase_use: "enabled", password_min_downcase_length: rand(2..4),
        password_min_digit_use: "enabled", password_min_digit_length: rand(2..4),
        password_min_symbol_use: "enabled", password_min_symbol_length: rand(2..4),
        password_prohibited_char_use: "enabled", password_prohibited_char: prohibited_chars.join,
        password_min_change_char_use: "enabled", password_min_change_char_count: rand(3..5)
      )
    end
    let(:upcase_only_password) { (upcases - prohibited_chars).sample(setting.password_min_length).join }
    let(:downcase_only_password) { (downcases - prohibited_chars).sample(setting.password_min_length).join }
    let(:digit_only_password) { (digits - prohibited_chars).sample(setting.password_min_length).join }
    let(:symbol_only_password) { (symbols - prohibited_chars).sample(setting.password_min_length).join }
    let(:password_contained_prohibited_chars) { prohibited_chars.join }
    let(:password1) do
      etra_length = setting.password_min_length
      - setting.password_min_upcase_length - setting.password_min_downcase_length
      - setting.password_min_digit_length - setting.password_min_symbol_length

      password = ""
      password << (upcases - prohibited_chars).sample(setting.password_min_upcase_length).join
      password << (downcases - prohibited_chars).sample(setting.password_min_downcase_length).join
      password << (digits - prohibited_chars).sample(setting.password_min_digit_length).join
      password << (symbols - prohibited_chars).sample(setting.password_min_symbol_length).join
      password << (chars - prohibited_chars).sample(etra_length).join
      password
    end
    let(:insufficient_password) do
      prev_chars = password1.split("").uniq
      password = ""
      password << prev_chars.sample(setting.password_min_length - setting.password_min_change_char_count + 1).join
      password << (chars - prev_chars - prohibited_chars).sample(setting.password_min_change_char_count - 1).join
      password
    end

    before do
      login_user user
    end

    def fill_password_and_save(password)
      visit sns_cur_user_account_path
      click_on I18n.t("ss.links.edit")

      within "form#item-form" do
        fill_in "item[in_password]", with: password
        click_on I18n.t("ss.buttons.save")
      end
    end

    it do
      fill_password_and_save(upcase_only_password)
      msg = I18n.t("errors.messages.password_short_downcase", count: setting.password_min_downcase_length)
      expect(page).to have_css("div#errorExplanation", text: msg)

      fill_password_and_save(downcase_only_password)
      msg = I18n.t("errors.messages.password_short_digit", count: setting.password_min_digit_length)
      expect(page).to have_css("div#errorExplanation", text: msg)

      fill_password_and_save(digit_only_password)
      msg = I18n.t("errors.messages.password_short_symbol", count: setting.password_min_symbol_length)
      expect(page).to have_css("div#errorExplanation", text: msg)

      fill_password_and_save(symbol_only_password)
      msg = I18n.t("errors.messages.password_short_upcase", count: setting.password_min_upcase_length)
      expect(page).to have_css("div#errorExplanation", text: msg)

      fill_password_and_save(password_contained_prohibited_chars)
      msg = I18n.t("errors.messages.password_contains_prohibited_chars", prohibited_chars: prohibited_chars.join)
      expect(page).to have_css("div#errorExplanation", text: msg)

      fill_password_and_save(password1)
      wait_for_notice I18n.t('ss.notice.saved')

      fill_password_and_save(insufficient_password)
      msg = I18n.t("errors.messages.password_min_change_chars", count: setting.password_min_change_char_count)
      expect(page).to have_css("div#errorExplanation", text: msg)
    end
  end
end


text:
package org.huberb.randompassword;

import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import org.openide.ErrorManager;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;

/**
 * Action which shows RandomPassword component.
 */
public class RandomPasswordAction extends AbstractAction {

    public RandomPasswordAction() {
        putValue(NAME, NbBundle.getMessage(RandomPasswordAction.class, "CTL_RandomPasswordAction"));
//        putValue(SMALL_ICON, new ImageIcon(Utilities.loadImage("SET/PATH/TO/ICON/HERE", true)));
    }

    @Override
    public void actionPerformed(ActionEvent evt) {
        TopComponent win = WindowManager.getDefault().findTopComponent("RandomPasswordTopComponent");
        if (win == null) {
            ErrorManager.getDefault().log(ErrorManager.WARNING, "Cannot find RandomPassword component.");
            return;
        }
        win.open();
        win.requestActive();
    }

}


text:
<?php namespace Delorean\Core\Domain\Repositories;

use Delorean\Core\Domain\Entities\EloquentEntity;
use Delorean\Core\Domain\Repositories\CrudRepository;

abstract class EloquentRepository implements CrudRepository {

    protected $entity;

    public function __construct(EloquentEntity $entity)
    {
        $this->entity = $entity;
    }

    public function all()
    {
        $this->entity->all();
    }

    public function find($id)
    {
        return $this->find($id);
    }

    public function create(array $data)
    {
        return $this->create($data);
    }

    public function update($id, array $data)
    {
        $row = $this->entity->find($id);
        if( !is_null($row) ){
            return $row->update($data);
        }

        return null;
    }

    public function delete($id)
    {
        return $this->entity->delete($id);
    }

    public function search(array $where = array(), array $order = null, array $columns = array('*'))
    {
        $query = $this->entity->select($columns);

        if( is_array($where) ){
            foreach( $order as $column => $direction ) {
                $query->entity->orderBy($column, $direction);
            }
        }

        if( is_array($order) ){
            foreach( $order as $column => $direction ) {
                $query->entity->orderBy($column, $direction);
            }
        }

        return $query->get();
    }
}


text:
package org.pm4j.common.converter.string;

import java.util.Locale;
import java.util.TimeZone;

import org.apache.commons.lang.StringUtils;
import org.pm4j.common.exception.CheckedExceptionWrapper;

/**
 * String converter helper methods.
 *
 * @author Olaf Boede
 */
public class StringConverterUtil {

  /** The default separator string used in case of a multi-format resource string specification. */
  private static String formatSplitString = "|";

  public static void setFormatSplitString(String s) {
    assert s != null && s.length() > 0;
    formatSplitString = s;
  }

  /**
   * Default implementation, may be overridden by implementations:
   * The last format definition returned by {@link #getParseFormats(PmAttr)}.
   *

   * Is used for the method {@link PmAttr#getValueAsString()}.
   *

   * It is also intended to be used by UI help constructs such as calendar
   * popups which provide their data as strings.
   *
   * @return The last item of the result of {@link #getParseFormats(PmAttr)}
   */
  public static String getOutputFormat(StringConverterCtxt ctxt) {
    String[] formats = getParseFormats(ctxt);
    return formats[formats.length-1];
  }

  /**
   * Builds an array of all format strings for the pmAttr.
   * @param pmAttr The pmAttr.
   * @return Format strings.
   */
  public static String[] getParseFormats(StringConverterCtxt ctxt) {
    String allFormatsString = StringUtils.defaultString(ctxt.getConverterCtxtFormatString());
    String[] formats = StringUtils.split(allFormatsString, formatSplitString);
    return formats;
  }

  /**
   * Provides a string for the given value.
   *
   * @param converter The {@link StringConverter} to use.
   * @param value The value to convert.
   * @return the string representation.
   */
  public static <T> String convertToString(StringConverter<T> converter, T value) {
    return converter.valueToString(new StringConverterCtxtImpl(), value);
  }

  /**
   * Provides a string for the given value.
   *
   * @param converter The {@link StringConverter} to use.
   * @param value The value to convert.
   * @param format The format to be used. Is converter specific.
   * @return the string representation.
   */
  public static <T> String convertToString(StringConverter<T> converter, T value, String format) {
    return converter.valueToString(new StringConverterCtxtImpl(format), value);
  }

  /**
   * Provides a string for the given value.
   *
   * @param converter The {@link StringConverter} to use.
   * @param value The value to convert.
   * @param format The format to use. Is converter specific.
   * @param locale The {@link Locale} to use. (Not used by all converters.)
   * @return the string representation.
   */
  public static <T> String convertToString(StringConverter<T> converter, T value, String format, Locale locale) {
    return converter.valueToString(new StringConverterCtxtImpl(format, locale), value);
  }

  /**
   * Provides a string for the given value.
   *
   * @param converter The {@link StringConverter} to use.
   * @param value The value to convert.
   * @param format The format to use. Is converter specific.
   * @param locale The {@link Locale} to use. (Not used by all converters.)
   * @param timeZone The {@link TimeZone} to use. (Not used by all converters.)
   * @return the string representation.
   */
  public static <T> String convertToString(StringConverter<T> converter, T value, String format, Locale locale, TimeZone timeZone) {
    return converter.valueToString(new StringConverterCtxtImpl(format, locale, timeZone), value);
  }

  /**
   * Provides a value for a given string.
   *
   * @param converter The {@link StringConverter} to use.
   * @param string The {@link String} to convert.
   * @return the converted value.
   * @throws RuntimeException if the string can't be converted.
   */
  public static <T> T convertToValue(StringConverter<T> converter, String string) {
    return convertToValue(converter, string, null, null, null);
  }

  /**
   * Provides a value for a given string.
   *
   * @param converter The {@link StringConverter} to use.
   * @param string The {@link String} to convert.
   * @param format The format to use. Is converter specific.
   * @return the converted value.
   * @throws RuntimeException if the string can't be converted.
   */
  public static <T> T convertToValue(StringConverter<T> converter, String string, String format) {
    return convertToValue(converter, string, format, null, null);
  }

  /**
   * Provides a value for a given string.
   *
   * @param converter The {@link StringConverter} to use.
   * @param string The {@link String} to convert.
   * @param format The format to use. Is converter specific.
   * @param locale The {@link Locale} to use. (Not used by all converters.)
   * @return the converted value.
   * @throws RuntimeException if the string can't be converted.
   */
  public static <T> T convertToValue(StringConverter<T> converter, String string, String format, Locale locale) {
    return convertToValue(converter, string, format, locale, null);
  }

  /**
   * Provides a value for a given string.
   *
   * @param converter The {@link StringConverter} to use.
   * @param string The {@link String} to convert.
   * @param format The format to use. Is converter specific.
   * @param locale The {@link Locale} to use. (Not used by all converters.)
   * @param timeZone The {@link TimeZone} to use. (Not used by all converters.)
   * @return the converted value.
   * @throws RuntimeException if the string can't be converted.
   */
  public static <T> T convertToValue(StringConverter<T> converter, String string, String format, Locale locale, TimeZone timeZone) {
    try {
      return converter.stringToValue(new StringConverterCtxtImpl(format, locale, timeZone), string);
    } catch (StringConverterParseException e) {
      throw new CheckedExceptionWrapper(e);
    }
  }

}


text:
define(function (require) {
  'use strict';

  var modules = require('modules');

  modules.get('a4c-metas').factory('orchestratorPropertiesServices', ['$resource',
    function($resource) {
      var orchestratorProperties = $resource('rest/latest/orchestrators/:id/properties', {}, {
        'upsert': {
          method: 'POST',
          isArray: false,
          headers: {
            'Content-Type': 'application/json; charset=UTF-8'
          }
        }
      });

      return {
        'upsertProperty': orchestratorProperties.upsert
      };
    }]
  );
});


text:
This is a simple example of R and Shiny that was created for a talk with the Greater Cleveland R Group on June 24th, 2015.

# Video
For those who are interested, here is the talk itself: https://www.youtube.com/watch?v=QU6J8Z8ue-c

# Slides
Here are the slides: https://docs.google.com/presentation/d/1dnjjEulHSFJdcadGrJ11hvpu1y8BbsaPXaBfu-rfwss/edit?usp=sharing


text:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="HandheldFriendly" content="true" />
  <link rel="shortcut icon" href="https://www.epa.gov/sites/all/themes/epa/favicon.ico" type="image/vnd.microsoft.icon" />
  <meta name="MobileOptimized" content="width" />
  <meta http-equiv="cleartype" content="on" />
  <meta http-equiv="ImageToolbar" content="false" />
  <meta name="viewport" content="width=device-width" />
  <meta name="version" content="20161218" />

  <meta name="DC.description" content="" />
  <meta name="DC.title" content="" />
  <title>
  Components of Riverbed Filtration Enhancement in Urban Stream Restoration Sites|

  Research Project Database | Grantee Research Project | ORD | US EPA</title>

  <meta name="keywords" content="" />
  <link rel="shortlink" href="" />
  <link rel="canonical" href="" />
  <meta name="DC.creator" content="" />
  <meta name="DC.language" content="en" />
  <meta name="DC.Subject.epachannel" content="" />
  <meta name="DC.type" content="" />
  <meta name="DC.date.created" content="" />
  <meta name="DC.date.modified" content="2013-02-01" />

  <link type="text/css" rel="stylesheet" href="https://www.epa.gov/misc/ui/jquery.ui.autocomplete.css" media="all" />
  <link type="text/css" rel="stylesheet" href="https://www.epa.gov/sites/all/themes/epa/css/lib/jquery.ui.theme.css" media="all" />
  <link type="text/css" rel="stylesheet" href="https://www.epa.gov/sites/all/libraries/template2/s.css" media="all" />

	<link rel="alternate" type="application/atom+xml" title="EPA.gov All Press Releases" href="https://www.epa.gov/newsreleases/search/rss" />
	<link rel="alternate" type="application/atom+xml" title="EPA.gov Headquarters Press Releases" href="https://www.epa.gov/newsreleases/search/rss/field_press_office/headquarters" />
	<link rel="alternate" type="application/atom+xml" title="Greenversations, EPA's Blog" href="https://blog.epa.gov/blog/feed/" />

Jump to main content

  <hgroup class="site-name-and-slogan">

US EPA

United States Environmental Protection Agency

  </hgroup>
  <form class="epa-search" method="get" action="https://search.epa.gov/epasearch/epasearch">
    Search
    <input class="form-text" placeholder="Search EPA.gov" name="querytext" id="search-box" value=""/>
    <button class="epa-search-button" id="search-button" type="submit" title="Search">Search</button>
    <input type="hidden" name="fld" value="" />
    <input type="hidden" name="areaname" value="" />
    <input type="hidden" name="areacontacts" value="" />
    <input type="hidden" name="areasearchurl" value="" />
    <input type="hidden" name="typeofsearch" value="epa" />
    <input type="hidden" name="result_template" value="2col.ftl" />
    <input type="hidden" name="filter" value="sample4filt.hts" />
  </form>

Contact Us

Related Information

Research Grants

P3: Student Design Competition

Research Fellowships

Small Business Innovation Research (SBIR)

Grantee Research Project Results Search

      Components of Riverbed Filtration Enhancement in Urban Stream Restoration Sites

    EPA Grant Number: FP917375

    Title: Components of Riverbed Filtration Enhancement in Urban Stream Restoration Sites

    Investigators:
     Robinson, Jesse D

    Institution:

      The State University of New York

    	EPA Project Officer:

           Jones, Brandon

      Project Period:
      September 1, 2011 through
        August 31, 2013

        Project Amount:

          $84,000

      RFA:
      STAR Graduate Fellowships (2011)

        		RFA Text |
          Recipients Lists

      Research Category:

          Fellowship - Water Quality: Hydrogeology and Surface Water
          ,
          Academic Fellowships

Objective:

	Due to the extensive and serious nature of impairment in many urban streams, successful aquatic restoration projects remain a challenge. However, physical alterations to streams resulting from restoration activities may be capable of enhancing hydraulic drivers of riverbed filtration, potentially improving important stream functions. This study will explore relationships between transient storage modeling and stream channel characteristics to identify trends in hyporheic exchange, a driver of riverbed filtration, through examining urban and non-urban degraded, reference condition and restored sites.

Approach:

        Demonstration of improved stream function is
important for determining successful aquatic restoration.
Direct measurement of these functions,
such as nutrient processing, often is complicated
by data intensive methods, site heterogeneity and
temporal variations in environmental factors.
Transient storage modeling (TSM) may represent
one method for achieving rapid assessment
of indicators of improved stream function. TSM
utilizes a mass balance approach to following
a conservative tracer into sub-surface storage
zones within streams, and can provide information
about exchange rates and the residence time
of water moving through these zones. TSM measurements
provide information about the physical
drivers of exchange and the characteristics of
the streambed, which are known to relate to other
important stream functions.

Expected Results:

Transient storage modeling has been used in a
variety of landscapes, and is under exploration
in a network of degraded, reference condition
and restored sites. Post-processing analysis of
the conservative tracer signal provides information
about sub-surface storage zones, but other
processes, such as surface detention areas, must
be carefully isolated. Appropriate characterization
of stream parameters at each site is crucial to
developing scaling relationships between model
output and drivers of exchange. Despite complexities,
physical enhancement through use of
structures in restoration sites has been proven to
alter hydraulic drivers of riverbed filtration. Due
to these enhancements, differentiation between
the transient storage signal in degraded, reference
condition and restored sites is anticipated.
The degree of differentiation in this signal, and
predictive power of direct measurements of
stream characteristics, will provide evidence for
the success of both the methods proposed and
urban stream restoration in general.

Potential to Further Environmental /
Human Health Protection

The impairment seen in urban streams reduces
the ability of these ecosystems to provide important
functions, from support of aquatic life at the
base of the food chain, to the removal of pollutants
from surface waters. This state of impairment
also has the effect of reducing recreational
and quality of life benefits in areas where people
are most likely to live. For citizens in these areas,
developing strategies to repair these ecosystems
requires that they begin with a complete understanding
of the state of efforts in urban environments
to date.

Supplemental Keywords:

      water quality, stream restoration, urban, riverbed filtration, Clean Water Act

Top of Page

 The perspectives, information and conclusions conveyed in research project abstracts, progress reports, final reports, journal abstracts and journal publications convey the viewpoints of the principal investigator and may not represent the views and policies of ORD and EPA.  Conclusions drawn by the principal investigators have not been reviewed by the Agency.

Main menu

Environmental Topics

Laws & Regulations

About EPA

Discover.

Accessibility

EPA Administrator

Budget & Performance

Contracting

Grants

No FEAR Act Data

Privacy and Security

Connect.

Data.gov

Inspector General

Jobs

Newsroom

Open Government

Regulations.gov

Subscribe

USA.gov

White House

Ask.

Contact Us

Hotlines

FOIA Requests

Frequent Questions

Follow.

Facebook

Twitter

YouTube

Flickr

Instagram

Last updated on Friday, February 1, 2013


text:
using System.ComponentModel.DataAnnotations.Schema;

namespace RelationUsingAnnotations
{
    public class Chapter
    {
        public int ChapterId { get; set; }
        public int Number { get; set; }
        public string Title { get; set; }
        public int BookId { get; set; }
        [ForeignKey("BookId")]
        public Book Book { get; set; }
    }
}


text:
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<application xmlns="http://ns.adobe.com/air/application/23.0">
    <!--注意此文件为Demo配置文件,集成主要参考<android>标签下配置内容 -->
    <id>com.teiron.SDKDEMO3</id>
    <filename>ANEDemo</filename>
    <name>ANEDemo</name>
    <versionNumber>0.0.0</versionNumber>
    <initialWindow>
        <content>ANEDemo.swf</content>
        <autoOrients>true</autoOrients>
        <fullScreen>false</fullScreen>
        <visible>true</visible>
        <softKeyboardBehavior>none</softKeyboardBehavior>
    </initialWindow>

<android>
        <colorDepth>16bit</colorDepth>
        <manifestAdditions><![CDATA[
            <manifest android:installLocation="auto">

    <uses-sdk
        android:minSdkVersion="9"
        android:targetSdkVersion="22" />

    <application>

    </application>
            </manifest>

        ]]></manifestAdditions>
    </android>
    <iPhone>
        <InfoAdditions><![CDATA[

            <key>UIDeviceFamily</key>
            <array>
                <string>1</string>
                <string>2</string>
            </array>
            <key>CFBundleURLTypes</key>
            <array>
                <dict>
                    <key>CFBundleURLSchemes</key>
                    <array>
                        <string>teiron5747</string>
                    </array>
                    <key>CFBundleURLName</key>
                    <string></string>
                </dict>
            </array>
            <key>LSApplicationQueriesSchemes</key>
            <array>
                <string>ppappinstall</string>
                <string>pphelperNS</string>
                <string>wechat</string>
                <string>weixin</string>
            </array>
            <key>NSAppTransportSecurity</key>
            <dict>
                <key>NSAllowsArbitraryLoads</key>
                <true/>
            </dict>
            <key>CFBundleAllowMixedLocalizations</key>
            <true/>

        ]]></InfoAdditions>
        <requestedDisplayResolution>high</requestedDisplayResolution>
    </iPhone>
<extensions>
        <extensionID>com.l1fan.ane.pp</extensionID>
    </extensions>
</application>


text:
from meerkat_abacus.pipeline_worker.process_steps import ProcessingStep
from meerkat_abacus import util
from meerkat_abacus.util import data_types

class ToDataType(ProcessingStep):

    def __init__(self, param_config, session):
        self.step_name = "to_data_type"
        self.config = param_config
        self.links_by_type, self.links_by_name = util.get_links(
            param_config.config_directory +
            param_config.country_config["links_file"])
        self.session = session

    def run(self, form, data):
        """
        """
        return_data = []
        # from nose.tools import set_trace; set_trace()
        for data_type in data_types.data_types(param_config=self.config):
            main_form = data_type["form"]
            additional_forms = {}
            for link in self.links_by_type.get(data_type["name"], []):
                additional_forms[link["to_form"]] = link["name"]
            d = {"type": data_type["name"],
                 "original_form": form}
            if form == main_form:
                if check_data_type_condition(data_type, data):
                    d["raw_data"] = data
                else:
                    continue
            elif form in additional_forms.keys():
                d["link_data"] = {additional_forms[form]: [data]}
            else:
                continue
            return_data.append({"form": "data",
                                "data": d})

        return return_data

def check_data_type_condition(data_type, data):
    if data_type["db_column"] and data:
        if data.get(data_type["db_column"]) == data_type["condition"]:
            return True
    else:
        return True
    return False


text:
function modify_file() {
	sed -i "s#^nbs.license_key =.*#nbs.license_key = \"${TINGYUN_LICENSE_KEY}\"#g" $1
    sed -i "s#^nbs.app_name=.*#nbs.app_name = \"${TINGYUN_APP_NAME}\"#g" $1
}

if [ -f /etc/php5/fpm/conf.d/networkbench.ini ]; then
	modify_file /etc/php5/fpm/conf.d/networkbench.ini
	/etc/init.d/php5-fpm start
fi

if [ -f /etc/php5/apache2/conf.d/networkbench.ini ]; then
	modify_file /etc/php5/apache2/conf.d/networkbench.ini
else
	if [ -f /etc/php5/cli/conf.d/networkbench.ini ]; then
		cp /etc/php5/cli/conf.d/networkbench.ini /etc/php5/apache2/conf.d/
		modify_file /etc/php5/apache2/conf.d/networkbench.ini
	else
		echo "The networkbench.ini has not in PHP environment."
	fi
fi


text:
		<title>Demo using dojox.dtl._HtmlTemplated inline in DOM</title>

			{% for item in items %}

{{ item }}

			{% endfor %}

			{% for item in items reversed %}

{{ item }}

			{% endfor %}


text:
package com.yukatan;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;

/**
 * Created by Jesus Barquín on 5/03/16.
 */
@SpringBootApplication
@ComponentScan(basePackages = "org.yukatan.rapid.config")
@EnableConfigurationProperties
public class TestApp {
}


text:
import pyglet
import glooey
import run_demos

window = pyglet.window.Window()
gui = glooey.Gui(window)

# Hmmm, label claims more vertical space than it needs because it calculates
# its claim from its wrapping width, but then flows to fill the whole width
# available to it.  With big pieces of text, this causes problems...

@run_demos.on_space(gui) #
def test_lorem_ipsum():
    lorem = glooey.LoremIpsum(num_paragraphs=1, line_wrap=640)
    gui.clear(); gui.add(lorem)
    yield "Display 1 paragraph of \"lorem ipsum\"."

    lorem = glooey.LoremIpsum(num_paragraphs=2, line_wrap=640)
    gui.clear(); gui.add(lorem)
    yield "Display 2 paragraphs of \"lorem ipsum\"."

    lorem = glooey.LoremIpsum(num_sentences=1, line_wrap=640)
    gui.clear(); gui.add(lorem)
    yield "Display 1 sentence of \"lorem ipsum\"."

    lorem = glooey.LoremIpsum(num_sentences=10, line_wrap=640)
    gui.clear(); gui.add(lorem)
    yield "Display 10 sentences of \"lorem ipsum\"."

pyglet.app.run()