text:
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"html/template"
	"io/ioutil"
	"net/http"
	"reflect"
	"time"

	"os"

	"github.com/google/gapid/test/robot/web/client/widgets/grid"
)

var (
	traceKind  = item{id: "trace"}
	reportKind = item{id: "report"}
	replayKind = item{id: "replay"}

	packageDisplayTemplate = "{{if .information.tag}}{{.information.tag}}" +
		"{{else if and (isUserType .information.type) (.information.cl)}}{{.information.cl}}" +
		"{{else if  .information.uploader}}{{.information.uploader}} - {{.id}}" +
		"{{else}}unknown - {{.id}}" +
		"{{end}}"

	machineDisplayTemplate = "{{if .information.Name}}{{.information.Name}}" +
		"{{else if .information.Configuration.Hardware.Name}}{{.information.Configuration.Hardware.Name}}" +
		"{{else}}{{.information.Configuration.OS}} - {{.information.id.data}}" +
		"{{end}}"

	kindDimension = &dimension{
		name:     "kind",
		enumData: enum{traceKind, replayKind, reportKind},
		valueOf: func(t *task) Item {
			return t.kind
		},
	}
	subjectDimension = &dimension{
		name: "subject",
		valueOf: func(t *task) Item {
			return t.trace.subject
		},
		enumSrc: func() enum {
			return itemGetter("{{.id}}", "{{.Information.APK.package}}", template.FuncMap{})(queryArray("/subjects/"))
		},
	}
	targetDimension = &dimension{
		name: "traceTarget",
		valueOf: func(t *task) Item {
			return t.trace.target
		},
		enumSrc: func() enum {
			return itemGetter("{{.id}}", machineDisplayTemplate, template.FuncMap{})(queryArray("/devices/"))
		},
	}
	hostDimension = &dimension{
		name: "host",
		valueOf: func(t *task) Item {
			return t.host
		},
		enumSrc: func() enum {
			return itemGetter("{{.id}}", machineDisplayTemplate, template.FuncMap{})(queryArray("/devices/"))
		},
	}
	packageDimension = &dimension{
		name: "package",
		valueOf: func(t *task) Item {
			return t.pkg
		},
		enumSrc: func() enum {
			return itemGetter("{{.id}}", packageDisplayTemplate, template.FuncMap{"isUserType": isUserType})(queryArray("/packages/"))
		},
	}

	dimensions = []*dimension{kindDimension, subjectDimension, targetDimension, hostDimension, packageDimension}
)

func isUserType(t reflect.Value) bool {
	// cannot currently use build.Type_UserType to check the type need to fix that.
	return t.Kind() == reflect.Float64 && t.Float() == float64(2)
}

func itemGetter(idPattern string, displayPattern string, functions template.FuncMap) func([]interface{}) enum {
	mustTemplate := func(s string) *template.Template {
		return template.Must(template.New(fmt.Sprintf("t%d", time.Now().Unix())).Funcs(functions).Parse(s))
	}
	exec := func(t *template.Template, item interface{}) string {
		var b bytes.Buffer
		t.Execute(&b, item)
		return b.String()
	}
	idt := mustTemplate(idPattern)
	dispt := mustTemplate(displayPattern)
	return func(entries []interface{}) enum {
		result := enum{}
		for _, it := range entries {
			result = append(result, item{id: exec(idt, it), display: exec(dispt, it), underlying: it})
		}
		return result
	}
}

func queryRestEndpoint(path string) ([]byte, error) {
	resp, err := http.Get(path)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	return ioutil.ReadAll(resp.Body)
}

func queryArray(path string) []interface{} {
	// TODO: Cache this, as we're using the same path for multiple dimensions.
	body, err := queryRestEndpoint(path)
	if err != nil {
		panic(err)
	}

	arr := []interface{}{}
	if err := json.Unmarshal(body, &arr); err != nil {
		panic(err)
	}
	return arr
}

func queryObject(path string) map[string]interface{} {
	resp, err := http.Get(path)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		panic(err)
	}

	arr := map[string]interface{}{}
	if err := json.Unmarshal(body, &arr); err != nil {
		panic(err)
	}
	return arr
}

func clearDimensionData() {
	for _, d := range dimensions {
		if d.enumSrc != nil {
			d.enumData = nil
		}
		d.itemMap = nil
	}
}

func newTask(entry map[string]interface{}, kind Item) *task {
	t := &task{
		underlying: entry,
		trace:      traceInfo{target: nilItem, subject: nilItem},
		kind:       kind,
		host:       nilItem,
		pkg:        nilItem,
	}

	if st, ok := entry["status"].(float64); ok {
		switch int(st) {
		case 1:
			t.status = grid.InProgress
			t.result = grid.Unknown
		case 2:
			t.status = grid.Current
			t.result = grid.Succeeded
		case 3:
			t.status = grid.Current
			t.result = grid.Failed
		}
	} else {
		t.status = grid.Stale
		t.result = grid.Failed
	}
	return t
}

func robotTasksPerKind(kind Item, path string, fun func(map[string]interface{}, *task)) []*task {
	tasks := []*task{}
	for _, e := range queryArray(path) {
		e := e.(map[string]interface{})
		t := newTask(e, kind)
		fun(e, t)
		tasks = append(tasks, t)
	}
	return tasks
}

func getRobotTasks() []*task {
	traceMap := map[string]*task{}
	tasks := []*task{}

	traceProc := func(e map[string]interface{}, t *task) {
		ei := e["input"].(map[string]interface{})
		t.trace = traceInfo{
			target:  targetDimension.GetItem(e["target"]),
			subject: subjectDimension.GetItem(ei["subject"]),
		}
		t.host = hostDimension.GetItem(e["host"])
		t.pkg = packageDimension.GetItem(ei["package"])
		if eo := e["output"]; eo != nil {
			if traceOutput := eo.(map[string]interface{})["trace"]; traceOutput != nil {
				traceMap[traceOutput.(string)] = t
			}
		}
	}
	tasks = append(tasks, robotTasksPerKind(traceKind, "/traces/", traceProc)...)

	subTaskProc := func(e map[string]interface{}, t *task) {
		ei := (e["input"].(map[string]interface{}))
		id := ei["trace"].(string)
		if traceTask, found := traceMap[id]; found {
			t.trace = traceTask.trace
		} else {
			fmt.Fprintf(os.Stderr, "Trace %s not found when processing action\n", id)
		}
		t.host = hostDimension.GetItem(e["host"])
		t.pkg = packageDimension.GetItem(ei["package"])
	}
	tasks = append(tasks, robotTasksPerKind(replayKind, "/replays/", subTaskProc)...)
	tasks = append(tasks, robotTasksPerKind(reportKind, "/reports/", subTaskProc)...)

	return tasks
}


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

    <!--<name>${project.groupId}:${project.artifactId}</name>-->

    <licenses>
        <license>
            <name>The Apache License, Version 2.0</name>
            <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
        </license>
    </licenses>

    <scm>
        <connection>scm:git:https://github.com/hs-web/hsweb-framework.git</connection>
        <developerConnection>scm:git:https://github.com/hs-web/hsweb-framework.git</developerConnection>
        <url>https://github.com/hs-web/hsweb-framework</url>
        <tag>${project.version}</tag>
    </scm>

    <modules>
        <module>axis-web-dao</module>
        <module>axis-web-service</module>
        <module>axis-web-controller</module>
        <module>axis-web-bean</module>
        <module>axis-web-core</module>
        <module>axis-web-websocket</module>
        <module>axis-web-workflow</module>
        <module>axis-web-concurrent</module>
        <module>axis-web-oauth2</module>
        <module>axis-web-datasource</module>
        <module>axis-web-starter</module>
    </modules>

    <properties>
        <!-- base setting -->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.build.locales>zh_CN</project.build.locales>

        <java.version>1.8</java.version>
        <javassist.version>3.20.0-GA</javassist.version>
        <project.build.jdk>${java.version}</project.build.jdk>

        <spring.boot.version>1.3.7.RELEASE</spring.boot.version>
        <activiti.version>5.19.0.2</activiti.version>

        <fastjson.version>1.2.28</fastjson.version>
        <slf4j.version>1.7.21</slf4j.version>
        <h2.version>1.4.191</h2.version>
        <mysql.version>5.1.39</mysql.version>
        <cglib.version>3.2.2</cglib.version>
        <aspectj.version>1.6.12</aspectj.version>
        <hibernate.validator.version>5.1.1.Final</hibernate.validator.version>
        <axis.ezorm.version>1.1</axis.ezorm.version>
        <axis.expands.version>1.0</axis.expands.version>
        <axis.common.version>1.0</axis.common.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-scm-plugin</artifactId>
                <version>1.8.1</version>
                <configuration>
                    <connectionType>connection</connectionType>
                </configuration>
            </plugin>
            <!-- 要将源码放上去,需要加入这个插件 -->
            <plugin>
                <artifactId>maven-source-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <attach>true</attach>
                </configuration>
                <executions>
                    <execution>
                        <phase>compile</phase>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>${project.build.jdk}</source>
                    <target>${project.build.jdk}</target>
                    <encoding>${project.build.sourceEncoding}</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.4</version>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>${spring.boot.version}</version>
                <configuration>
                    <fork>true</fork>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <!-- test-junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--json-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>${fastjson.version}</version>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
                <version>${slf4j.version}</version>
            </dependency>
            <dependency>
                <groupId>javax.transaction</groupId>
                <artifactId>jta</artifactId>
                <version>1.1</version>
            </dependency>

            <!--oauth2-->
            <dependency>
                <groupId>org.apache.oltu.oauth2</groupId>
                <artifactId>org.apache.oltu.oauth2.authzserver</artifactId>
                <version>1.0.2</version>
            </dependency>

            <dependency>
                <groupId>org.axis</groupId>
                <artifactId>axis-web-datasource</artifactId>
                <version>${project.version}</version>
            </dependency>
            <dependency>
                <groupId>org.axis</groupId>
                <artifactId>axis-web-oauth2-core</artifactId>
                <version>${project.version}</version>
            </dependency>

            <dependency>
                <groupId>org.axis</groupId>
                <artifactId>axis-web-oauth2-mybatis</artifactId>
                <version>${project.version}</version>
            </dependency>

            <dependency>
                <groupId>org.axis</groupId>
                <artifactId>axis-web-oauth2-simple</artifactId>
                <version>${project.version}</version>
            </dependency>

            <dependency>
                <groupId>org.axis</groupId>
                <artifactId>axis-web-oauth2-service-simple</artifactId>
                <version>${project.version}</version>
            </dependency>

            <dependency>
                <groupId>org.axis</groupId>
                <artifactId>axis-web-oauth2-controller</artifactId>
                <version>${project.version}</version>
            </dependency>

            <dependency>
                <groupId>org.axis</groupId>
                <artifactId>axis-common</artifactId>
                <version>${axis.common.version}</version>
                <exclusions>
                    <exclusion>
                        <groupId>org.slf4j</groupId>
                        <artifactId>slf4j-api</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
            <dependency>
                <groupId>org.hsweb</groupId>
                <artifactId>hsweb-expands-script</artifactId>
                <version>${hsweb.expands.version}</version>
            </dependency>
            <dependency>
                <groupId>org.axis</groupId>
                <artifactId>axis-expands-office</artifactId>
                <version>${axis.expands.version}</version>
                <exclusions>
                    <exclusion>
                        <groupId>org.slf4j</groupId>
                        <artifactId>slf4j-api</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
            <dependency>
                <groupId>org.axis</groupId>
                <artifactId>axis-expands-request</artifactId>
                <version>${axis.expands.version}</version>
            </dependency>
            <dependency>
                <groupId>org.axis</groupId>
                <artifactId>axis-expands-shell</artifactId>
                <version>${axis.expands.version}</version>
            </dependency>
            <dependency>
                <groupId>org.axis</groupId>
                <artifactId>axis-expands-compress</artifactId>
                <version>${axis.expands.version}</version>
            </dependency>
            <dependency>
                <groupId>org.axis</groupId>
                <artifactId>axis-expands-template</artifactId>
                <version>${axis.expands.version}</version>
            </dependency>
            <dependency>
                <groupId>org.axis</groupId>
                <artifactId>axis-easy-orm</artifactId>
                <version>${axis.ezorm.version}</version>
                <type>pom</type>
                <scope>import</scope>
                <exclusions>
                    <exclusion>
                        <groupId>org.slf4j</groupId>
                        <artifactId>slf4j-api</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
            <dependency>
                <groupId>org.axis</groupId>
                <artifactId>axis-web-concurrent-cache</artifactId>
                <version>${project.version}</version>
            </dependency>

            <dependency>
                <groupId>org.axis</groupId>
                <artifactId>axis-web-concurrent-lock</artifactId>
                <version>${project.version}</version>
            </dependency>
            <dependency>
                <groupId>org.axis</groupId>
                <artifactId>axis-web-websocket</artifactId>
                <version>${project.version}</version>
            </dependency>
            <dependency>
                <groupId>com.oracle</groupId>
                <artifactId>ojdbc14</artifactId>
                <version>10.2.0.4.0</version>
                <type>pom</type>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>${mysql.version}</version>
            </dependency>
            <dependency>
                <groupId>org.axis</groupId>
                <artifactId>axis-web-bean</artifactId>
                <version>${project.version}</version>
            </dependency>
            <dependency>
                <groupId>org.axis</groupId>
                <artifactId>axis-web-core</artifactId>
                <version>${project.version}</version>
            </dependency>
            <dependency>
                <groupId>org.axis</groupId>
                <artifactId>axis-web-controller</artifactId>
                <version>${project.version}</version>
            </dependency>
            <dependency>
                <groupId>org.axis</groupId>
                <artifactId>axis-web-dao-api</artifactId>
                <version>${project.version}</version>
            </dependency>
            <dependency>
                <groupId>org.axis</groupId>
                <artifactId>axis-web-dao-mybatis</artifactId>
                <version>${project.version}</version>
            </dependency>
            <dependency>
                <groupId>org.axis</groupId>
                <artifactId>axis-web-service-api</artifactId>
                <version>${project.version}</version>
            </dependency>
            <dependency>
                <groupId>org.mockito</groupId>
                <artifactId>mockito-all</artifactId>
                <version>1.8.5</version>
            </dependency>
            <dependency>
                <groupId>org.axis</groupId>
                <artifactId>axis-web-service-simple</artifactId>
                <version>${project.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring.boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--activiti 工作流-->
            <dependency>
                <groupId>org.activiti</groupId>
                <artifactId>activiti-spring-boot-starter-basic</artifactId>
                <version>${activiti.version}</version>
            </dependency>

            <dependency>
                <groupId>org.activiti</groupId>
                <artifactId>activiti-spring-boot-starter-rest-api</artifactId>
                <version>${activiti.version}</version>
            </dependency>

            <dependency>
                <groupId>org.activiti</groupId>
                <artifactId>activiti-spring-boot-starter-actuator</artifactId>
                <version>${activiti.version}</version>
            </dependency>

            <dependency>
                <groupId>org.activiti</groupId>
                <artifactId>activiti-spring-boot-starter-jpa</artifactId>
                <version>${activiti.version}</version>
            </dependency>
            <dependency>
                <groupId>org.axis</groupId>
                <artifactId>axis-web-workflow</artifactId>
                <version>${project.version}</version>
            </dependency>
            <dependency>
                <groupId>org.activiti</groupId>
                <artifactId>activiti-explorer</artifactId>
                <version>${activiti.version}</version>
                <exclusions>
                    <exclusion>
                        <artifactId>vaadin</artifactId>
                        <groupId>com.vaadin</groupId>
                    </exclusion>
                    <exclusion>
                        <artifactId>dcharts-widget</artifactId>
                        <groupId>org.vaadin.addons</groupId>
                    </exclusion>
                    <exclusion>
                        <artifactId>activiti-simple-workflow</artifactId>
                        <groupId>org.activiti</groupId>
                    </exclusion>
                    <exclusion>
                        <groupId>org.slf4j</groupId>
                        <artifactId>slf4j-log4j12</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>

            <dependency>
                <groupId>org.activiti</groupId>
                <artifactId>activiti-modeler</artifactId>
                <version>${activiti.version}</version>
            </dependency>

            <dependency>
                <groupId>org.activiti</groupId>
                <artifactId>activiti-json-converter</artifactId>
                <version>${activiti.version}</version>
            </dependency>

        </dependencies>
    </dependencyManagement>

    <!--<repositories>-->
        <!--<repository>-->
            <!--<id>hsweb-nexus</id>-->
            <!--<name>Nexus Release Repository</name>-->
            <!--<url>http://nexus.hsweb.me/content/groups/public/</url>-->
            <!--<snapshots>-->
                <!--<enabled>true</enabled>-->
            <!--</snapshots>-->
        <!--</repository>-->
    <!--</repositories>-->

</project>

redpajama_set_name: RedPajamaGithub


text:
import compose from 'compose'
import parse from 'string/parse'

// split :: String -> (String -> String)
export default c => compose(s => s.split(c), parse)


text:
import os
import sys
import time
import threading
import json
import errno
import datetime
import pkg_resources
import tendo.singleton
from queue import Queue

from flask import Flask, Response, jsonify, request, abort
#me = tendo.singleton.SingleInstance()
location = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, os.path.join(location, "..", "sptrader"))
sys.path.insert(0, os.path.join(location, ".."))
data_dir = os.path.join(location, "..", "data")

#blacklist backtrader version
btversion = pkg_resources.get_distribution("backtrader").version

if btversion == "1.9.13.102":
    print("WARNING!!!!")
    print("BACKTRADER 1.9.13.102 is BROKEN with sptrader")

from sse import ServerSentEvent
import sptrader
import strategy
import strategy.strategylist

try:
    os.makedirs(data_dir)
except OSError as exception:
    if exception.errno != errno.EEXIST:
        raise

ticker_file = os.path.join(data_dir, "ticker-%s.txt")
VERSION="0.11.1"

def get_ticker(s):
    '''Get ticker file'''
    if "/" in s:
        raise ValueError
    return ticker_file % s

sp = sptrader.SPTrader()
log_subscriptions = []
empty_cache = {"connected": {},
               "account_info": None}
info_cache = empty_cache
ticker_products = set()
app = Flask(__name__,
            static_url_path="/static",
            static_folder=os.path.join(location, "..",
                                       "static"))

@app.route("/")
def hello():
    '''Main application file'''
    return app.send_static_file("sptrader.html")

def send_dict(event_id, msg):
    '''Send dictionary as event'''
    for sub in log_subscriptions[:]:
        sub.put((event_id, msg))

class Config(object):
    '''Load and save config'''
    def __init__(self):
        self.config = {}
        self.config['strategy_data'] = {}
        self.config['backtest_data'] = {}
        try:
            with open(os.path.join(data_dir, "config.json")) as fp:
                self.config.update(json.load(fp))
        except IOError as error:
            pass
        for r in ['strategy_data']:
            for k in self.config[r]:
                self.config[r][k]['status'] = "stopped"
                self.config[r][k]['comment'] = ""
                send_dict("LocalStrategyStatus",
                          {"strategy":  self.config[r][k]['strategy'],
                           "id": self.config[r][k]['id'],
                           "status": "stopped",
                           "comment": ""})

    def save(self):
        with open(os.path.join(data_dir, "config.json"), 'w') as fp:
            json.dump(self.config, fp, indent=4, sort_keys=True)

    def get(self, s):
        return self.config.get(s, None)

    def set(self, s, v, save=True):
        self.config[s] = v
        if save:
            self.save()

    def save_stratdata(self, root, kwargs, save=True):
        sid = kwargs['id']
        self.config[root][sid] = kwargs
        if save:
            self.save()

    def get_stratdata_by_strategy(self, root):
        d = {}
        for k, v in self.config[root].items():
            if v['strategy'] not in d:
                d[v['strategy']] = []
            d[v['strategy']].append(v)
        for k in strategy.strategy_list():
            if k not in d:
                d[k] = []
        return d

my_config = Config()

def send_cdata(event_id, data):
    send_dict(event_id, {"data": sp.cdata_to_py(data[0])})

@app.route("/login-info")
def logininfo():
    d = {"status": "%d" % sp.get_login_status(80)}
    if my_config.get('logininfo') is not None:
        d['info'] = my_config.get('logininfo')
    if info_cache['connected'] is not None:
        d['connected'] = info_cache['connected']
    if info_cache['account_info'] is not None:
        d['account_info'] = info_cache['account_info']
    d['account_fields'] = sp.fields("SPApiAccInfo")
    d['strategy_list'] = strategy.strategy_list()
    d['strategy_headers'] = {}
    for i in strategy.strategy_list():
        d['strategy_headers'][i] = strategy.headers(i)
    d['strategy_data'] = my_config.get_stratdata_by_strategy('strategy_data')
    d['backtest_data'] = my_config.get_stratdata_by_strategy('backtest_data')
    d['versions'] = [
        ["web-backend", VERSION],
        ["backtrader", btversion]
        ]
    return jsonify(d)

@sp.ffi.callback("LoginReplyAddr")
def login_reply(ret_code, ret_msg):
    if ret_code == 0:
        ret_msg = ''
    else:
        ret_msg = sp.ffi.string(ret_msg).decode('utf-8')
    send_dict("LoginReply", {
        "ret_code": ret_code,
        "ret_msg": ret_msg
    })
sp.register_login_reply(login_reply)

@sp.ffi.callback("ConnectedReplyAddr")
def connected_reply(host_type, con_status):
    send_dict("ConnectedReply", {
        "host_type": host_type,
        "con_status": con_status
    })
    info_cache['connected'][host_type] = con_status
    if host_type == 83 and con_status == 2:
        sp.register_ticker_update(ticker_update)
        for p in ticker_products:
            sp.subscribe_ticker(p, 1)
sp.register_connecting_reply(connected_reply)

@sp.ffi.callback("ApiOrderRequestFailedAddr")
def order_request_failed(action, order, error_code, error_msg):
    send_dict("OrderRequestFailed", {
        "action": ord(action),
        "data": sp.cdata_to_py(order[0]),
        "error_code": error_code,
        "error_msg": sp.ffi.string(error_msg).decode('utf-8')})
sp.register_order_request_failed(order_request_failed)

@sp.ffi.callback("ApiOrderReportAddr")
def order_report(rec_no, data):
    send_dict("OrderReport", {
        "rec_no": rec_no,
        "data": sp.cdata_to_py(data[0])
    })
sp.register_order_report(order_report)

@sp.ffi.callback("ApiOrderBeforeSendReportAddr")
def api_order_before_send_report(data):
    send_cdata("OrderBeforeSendReport", data)
sp.register_order_before_send_report(api_order_before_send_report)

@sp.ffi.callback("AccountLoginReplyAddr")
def account_login_reply(accNo, ret_code, ret_msg):
    send_dict("AccountLoginReply", {
        "accNo": accNo,
        "ret_code": ret_code,
        "ret_msg": ret_msg
    })
sp.register_account_login_reply(account_login_reply)

@sp.ffi.callback("AccountLogoutReplyAddr")
def account_logout_reply(ret_code, ret_msg):
    send_dict("AccountLogoutReply", {
        "ret_code": ret_code,
        "ret_msg": ret_msg
    })
sp.register_account_logout_reply(account_logout_reply)

@sp.ffi.callback("AccountInfoPushAddr")
def account_info_push(data):
    info_cache['account_info'] = sp.cdata_to_py(data[0])
    send_cdata("AccountInfoPush", data)
sp.register_account_info_push(account_info_push)

@sp.ffi.callback("AccountPositionPushAddr")
def account_position_push(data):
    send_cdata("AccountPositionPush", data)
sp.register_account_position_push(account_position_push)

@sp.ffi.callback("UpdatedAccountPositionPushAddr")
def updated_account_position_push(data):
    send_cdata("UpdatedAccountPositionPush", data)
sp.register_updated_account_position_push(updated_account_position_push)

@sp.ffi.callback("UpdatedAccountBalancePushAddr")
def updated_account_balance_push(data):
    send_cdata("UpdatedAccountBalancePush", data)
sp.register_updated_account_balance_push(updated_account_balance_push)

@sp.ffi.callback("ApiTradeReportAddr")
def trade_report(rec_no, data):
    send_cdata("TradeReport", data)
sp.register_trade_report(trade_report)

@sp.ffi.callback("ApiPriceUpdateAddr")
def api_price_update(data):
    send_cdata("PriceUpdate", data)
sp.register_price_update(api_price_update)

@sp.ffi.callback("ApiTickerUpdateAddr")
def api_ticker_update(data):
    send_cdata("TickerUpdate", data)
sp.register_ticker_update(api_ticker_update)

@sp.ffi.callback("PswChangeReplyAddr")
def psw_change_reply(ret_code, ret_msg):
    send_cdata("PswChangeReply", {"ret_code": ret_code,
                                  "ret_msg": ret_msg})
sp.register_psw_change_reply(psw_change_reply)

@sp.ffi.callback("ProductListByCodeReplyAddr")
def product_list_by_code(inst_code, is_ready, ret_msg):
    data = {
        "inst_code": inst_code,
        "is_ready": is_ready,
        "ret_msg": ret_msg,
        "data": sp.get_product()}
    send_dict("ProductListByCodeReply", data)
sp.register_product_list_by_code_reply(product_list_by_code)

@sp.ffi.callback("InstrumentListReplyAddr")
def instrument_list_reply(is_ready, ret_msg):
    data = {"is_ready": is_ready,
            "ret_msg": ret_msg,
            "data": sp.get_instrument()}
    send_dict("InstrumentListReply", data)
sp.register_instrument_list_reply(instrument_list_reply)

@sp.ffi.callback("BusinessDateReplyAddr")
def business_date_reply(business_date):
    send_dict("BusinessDateReply", {
        "business_date": business_date
    })
sp.register_business_date_reply(business_date_reply)

@sp.ffi.callback("ApiMMOrderBeforeSendReportAddr")
def api_mm_order_before_send_report(mm_order):
    send_cdata("MMOrderBeforeSendReport", mm_order)
sp.register_mm_order_before_send_report(api_mm_order_before_send_report)

@sp.ffi.callback("ApiMMOrderRequestFailedAddr")
def api_mm_order_request_failed(mm_order, err_code, err_msg):
    send_dict("MMOrderRequestFailed",
              {"data": sp.cdata_to_py(mm_order[0]),
               "err_code": sp.cdata_to_py(err_code),
               "err_msg": sp.cdata_to_py(err_msg)})
sp.register_mm_order_request_failed(api_mm_order_request_failed)

@sp.ffi.callback("ApiQuoteRequestReceivedAddr")
def quote_request_received(product_code, buy_sell, qty):
    send_dict("QuoteRequestReceived",
              {"product_code": product_code,
               "buy_sell": buy_sell,
               "qty": qty})
sp.register_quote_request_received_report(quote_request_received)

def monitor_file(filename, newdata=False):
    try:
        tickerfile = open(filename)
    except FileNotFoundError:
        open(filename, 'a').close()
        tickerfile = open(filename)
    if newdata:
        tickerfile.seek(0, 2)

    def gen():
        try:
            while True:
                line = tickerfile.readline()
                if not line:
                    time.sleep(0.1)
                    continue
                yield line
        except GeneratorExit:  # Or maybe use flask signals
            tickerfile.close()
    return Response(gen(), mimetype="text/plain")

# -------
@app.route("/login", methods=['POST'])
def login():
    if not request.form:
        abort(400)
    sp.set_login_info(request.form["host"],
                      int(request.form["port"]),
                      request.form["license"],
                      request.form["app_id"],
                      request.form["user_id"],
                      request.form["password"])
    my_config.set('logininfo', {
        "host": request.form['host'],
        "port": int(request.form['port']),
        "license": request.form['license'],
        "app_id": request.form['app_id'],
        "user_id": request.form['user_id']
    })

    return jsonify({"retval": sp.login()})

@app.route("/ping")
def ping():
    msg = {
        "msg": "Ping"
    }
    for sub in log_subscriptions[:]:
        sub.put(("ping", msg))
    return "OK"

@app.route("/logout")
def logout():
    global info_cache
    info_cache = empty_cache
    sp.logout()
    return "OK"

# ----------- Ticker code------

@sp.ffi.callback("ApiTickerUpdateAddr")
def ticker_update(data):
    send_cdata("ApiTickerUpdate", data)
    t = sp.cdata_to_py(data[0])
    tickerfile = open(get_ticker(t['ProdCode']), "a")
    dt = datetime.datetime.fromtimestamp(float(t['TickerTime']))
    price = "%.2f" % float(t['Price'])
    tickerfile.write("%s; %s; %s; %s; %s; %d\n" %
                     (dt.strftime("%Y/%m/%d/%H/%M/%S"),
                      price,
                      price,
                      price,
                      price,
                      int(t['Qty'])))
    tickerfile.close()
sp.register_ticker_update(ticker_update)

@app.route("/ticker/subscribe/<string:products>")
def subscribe_ticker(products):
    for p in products.split(","):
        ticker_products.add(p)
        if sp.ready() == 0:
            sp.subscribe_ticker(p, 1)
    if sp.ready() != 0:
        return "NOLOGIN"
    else:
        send_dict("TickerUpdate",
                  {"data": list(ticker_products)})
        return "OK"

@app.route("/ticker/unsubscribe/<string:products>")
def unsubscribe_ticker(products):
    for p in products.split(","):
        ticker_products.discard(p)
        if sp.ready() == 0:
            sp.subscribe_ticker(p, 0)
    if sp.ready() != 0:
        return "NOLOGIN"
    else:
        send_dict("TickerUpdate",
                  {"data": list(ticker_products)})
        return "OK"

@app.route("/ticker/list")
def list_ticker():
    return jsonify({"data": list(ticker_products)})

@app.route("/ticker/view/<string:product>")
def view_ticker(product):
    return monitor_file(get_ticker(product))

@app.route("/ticker/clear/<string:product>")
def clear_ticker(product):
    fo = open(get_ticker(product), "w")
    fo.truncate()
    fo.close()
    return "OK"

@app.route("/account-info-push-send")
def account_info_push_send():
    acc_info = sp.get_acc_info()
    if acc_info is not None:
        info_cache['account_info'] = acc_info
        send_dict("AccountInfoPush", {"data": acc_info})
        return "OK"
    else:
        return "NODATA"

# ----------- Strategy ------

class StrategyList(object):

    def __init__(self):
        self.stratlist = {}

    def start(self, kwargs):
        if id not in self.stratlist or \
                self.stratlist[kwargs['id']][0] is None:
            (p, q) = strategy.run(kwargs)
            self.stratlist[kwargs['id']] = (p, q)
            kwargs['status'] = 'running'
            kwargs['comment'] = ''
            my_config.save_stratdata('strategy_data', kwargs)
            t = threading.Thread(target=strategy_listener, args=(p, q))
            t.daemon = True
            t.start()
            send_dict("LocalStrategyStatus",
                      {"strategy": kwargs['strategy'],
                       "id": kwargs['id'],
                       "status": "running",
                       "comment": ""})
            return "OK"

    def stop(self, info, terminate=False):
        sid = info.get('id', None)
        if sid in self.stratlist:
            (p, q) = self.stratlist[sid]
            cache = my_config.config['strategy_data'][sid]
            cache['status'] = info['status']
            cache['comment'] = info['comment']
            my_config.save_stratdata('strategy_data', cache)
            if q is not None:
                q.close()
            if p is not None and terminate:
                p.terminate()
                p.join()
        self.stratlist.pop(sid)
        send_dict("LocalStrategyStatus",
                  {"strategy": info['strategy'],
                   "id": info['id'],
                   "status": info['status'],
                   "comment": info['comment']})
        return "OK"

    def data(self, stratname):
        retval = []
        for k, v in self.stratlist.items():
            if v[2]['strategy'] == stratname:
                retval.append(v[2])
        return retval

    def terminate_all(self):
        for k, v in self.stratlist.items():
            if v[0] is not None:
                p = v[0]
                p.terminate()
                p.join()

    def pause(self, f):
        raise NotImplementedError

stratlist = StrategyList()

def strategy_listener(p, q):
    try:
        while True:
            (s, sid, status, comment) = q.get()
            info = {"strategy": s,
                    "id": sid,
                    "status": status,
                    "comment": comment}
            if status == "error":
                stratlist.stop(info, terminate=True)
                return
            elif status == "done":
                stratlist.stop(info, terminate=False)
                return
    except GeneratorExit:  # Or maybe use flask signals
        return

@app.route("/strategy/start", methods=['POST'])
def strategy_start():
    if not request.form:
        abort(400)
    return stratlist.start(request.form.to_dict())

@app.route("/strategy/stop", methods=['POST'])
def strategy_stop():
    if not request.form:
        abort(400)
    f = request.form.to_dict()
    f['status'] = "done"
    f['comment'] = ""
    return stratlist.stop(f, terminate=True)

@app.route("/strategy/remove-row/<string:sid>")
def strategy_remove(sid):
    del my_config.config['strategy_data'][sid]
    return "OK"

@app.route("/strategy/log/<string:strategy_id>")
def strategy_log(strategy_id):
    return monitor_file(os.path.join(data_dir,
                                     "log-%s.txt" % strategy_id))

# -----------------------------
@app.route("/backtest", methods=['POST'])
def backtest():
    d = request.form.to_dict()
    my_config.config['backtest_data'][d['id']] = d
    my_config.save()
    return strategy.backtest(d)

@app.route("/backtest/remove-row/<string:sid>")
def backtest_remove(sid):
    del my_config.config['backtest_data'][sid]
    my_config.save()
    return "OK"

# ---------------------------

@app.route("/orders/read")
def orders_read():
    pass

# ---------------------------
@app.route("/trade/list")
def list_trade():
    return jsonify({"data": sp.get_all_trades()})

# -----------------

@app.route("/order/list")
def order_list():
    return jsonify({"data": sp.get_all_orders()})

@app.route("/order/add", methods=['POST'])
def order_add():
    if request.form:
        f = request.form.to_dict()
    elif request.json:
        f = request.json
    else:
        abort(400)
    inactive = bool(int(f.pop("Inactive", 0)))
    if inactive:
        return str(sp.order_add_inactive(f))
    else:
        return str(sp.order_add(f))

@app.route("/order/delete", methods=['POST'])
def order_delete():
    if request.form:
        f = request.form.to_dict()
    elif request.json:
        f = request.json
    else:
        abort(400)
    if 'IntOrderNo' not in f or \
       'ProdCode' not in f or \
       'ClOrderId' not in f:
        orders = sp.get_all_orders()
        found = False
        for o in orders:
            found = True
            for k, v in f.items():
                if str(o[k]) != str(v):
                    found = False
                    break
            if found:
                fin = {}
                fin['IntOrderNo'] = str(o['IntOrderNo'])
                fin['ProdCode'] = str(o['ProdCode'])
                fin['ClOrderId'] = str(o['ClOrderId'])
                return str(sp.order_delete(o))
        abort(400)
    return str(sp.order_delete(f))

@app.route("/order/delete-all", methods=['POST'])
def order_delete_all():
    return str(sp.order_delete_all())

@app.route("/order/activate", methods=['POST'])
def order_activate():
    if request.form:
        f = request.form.to_dict()
    elif request.json:
        f = request.json
    else:
        abort(400)
    if 'IntOrderNo' not in f:
        abort(400)
    return str(sp.order_activate(f))

@app.route("/order/inactivate", methods=['POST'])
def order_inactivate():
    if request.form:
        f = request.form.to_dict()
    elif request.json:
        f = request.json
    else:
        abort(400)
    if 'IntOrderNo' not in f:
        abort(400)
    return str(sp.order_inactivate(f))

@app.route("/price/subscribe/<string:products>")
def subscribe_price(products):
    if sp.ready() != 0:
        return "NOT READY"
    for p in products.split(","):
        sp.subscribe_price(p, 1)
    return "OK"

@app.route("/price/unsubscribe/<string:products>")
def unsubscribe_price(products):
    if sp.ready() != 0:
        return "NOT READY"
    for p in products.split(","):
        sp.subscribe_price(p, 0)
    return "OK"

@app.route("/account-info")
def get_account_info():
    if sp.ready() != 0:
        return "NOT READY"
    sp.get_acc_bal_count()
    return "OK"

# include tag so that different items get different streams
# flask seems set things up so that one subscribe is one stream

@app.route("/log/subscribe/<string:data>")
def subscribe(data):
    def gen():
        q = Queue()
        log_subscriptions.append(q)
        try:
            while True:
                (event_id, result) = q.get()
                ev = ServerSentEvent(result, event_id)
                yield ev.encode()
        except GeneratorExit:  # Or maybe use flask signals
            log_subscriptions.remove(q)
    return Response(gen(), mimetype="text/event-stream")

@app.route("/schema/<string:structure>")
def schema(structure):
    return jsonify({"retval": sp.fields(structure)})

@app.route("/exit")
def exit_done():
    exit()
    return "OK"

if __name__ == "__main__":
    try:
        app.debug = True
        app.run(threaded=True,use_reloader=False)
    except KeyboardInterrupt:
        stratlist.terminate_all()


text:
function ConstTest() {
  /[Cz]/.test("abCdefgzabCdefgzabCdefgzabCdefgzabCdefgzabCdefgzabCdefgzabCdefgz");
}

const cre = /[Cz]/;
function GlobalConstTest() {
  cre.test("abCdefgzabCdefgzabCdefgzabCdefgzabCdefgzabCdefgzabCdefgzabCdefgz");
}

var benchmarks = [ [ConstTest, () => {}],
                   [GlobalConstTest, () => {}],
                 ];
createBenchmarkSuite("InlineTest");


text:
/*
 *file name : logfile.c
 *des :
 *date : 2013-10-23
 *author : liwq (286570361)
 *notes :
 *       2013-10-23   liwq      create files
 */

/**********************************************************/
#include "logfile.h"
#include "file.h"
#include "public.h"

static char * mkLogNm(char *fileName, typeLogFile *pLogFile)
{
  sprintf(fileName, "%s_%8.8s_%s.log", pLogFile->programName, \
          pLogFile->lastDate, pLogFile->procID);

  return fileName;
}

static FILE *openLog(typeLogFile *pLogFile)
{
  char logName[NAMELEN] = {0};
  mkLogNm(logName, pLogFile);
  return pLogFile->fpLog = openFile(pLogFile->logPath, logName, "a+");
}

int initLog(typeLogFile *pLogFile, const char *logPath, const char *programName, \
            const char *sysDate, const char *procID, int logLevel)
{
  memset(pLogFile, 0x00, sizeof(typeLogFile));

  strcpy(pLogFile->logPath, logPath);
  strcpy(pLogFile->programName, programName);
  strcpy(pLogFile->procID, procID);
  strncpy(pLogFile->lastDate, sysDate, 8);
  pLogFile->lastDate[8] = 0;
  pLogFile->logLevel = logLevel;

  pLogFile->fpLog = openLog(pLogFile);
  if (!pLogFile->fpLog)
  {
    perror("initLog open err!");
    return -1;
  }

  return 0;
}

static int getLogLevel(char *levelInfo, int logLevel)
{
  switch(logLevel)
  {
    case DEBUG:
      strcpy(levelInfo, "DEBUG");
      break;
    case INFO:
      strcpy(levelInfo, "INFO");
      break;
    case WARN:
      strcpy(levelInfo, "WARN");
      break;
    case ERROR:
      strcpy(levelInfo, "ERROR");
      break;
    default:
      perror("error log level!");
  }
  return 0;
}

int wrtLog(typeLogFile *pLogFile, const char *file, long line, \
           const char *func, int logLevel, char * fmt, ...)
{
  va_list args;
  char logBuf[STRLEN+2*NAMELEN];
  char logStr[2*NAMELEN];
  char curDate[14+1];
  char logLevelInfo[10];

  if (pLogFile->logLevel > logLevel)
  {
    return 0;
  }

  getSysDate(curDate);

  if (strncmp(curDate,pLogFile->lastDate,8) != 0 )
  {
    fclose(pLogFile->fpLog);

    strncpy(pLogFile->lastDate, curDate, 8);
    pLogFile->lastDate[8]='\0';

    if(openLog(pLogFile) == NULL)
    {
      perror("wrtLog:Can't open log file!");
      return -1;
    }
  }

  memset(logLevelInfo, 0x00, sizeof(logLevelInfo));
  getLogLevel(logLevelInfo, logLevel);

  memset(logBuf,0,sizeof(logBuf));
  sprintf(logBuf,"[%8.8s %2.2s:%2.2s:%2.2s]",curDate, curDate+8, curDate+10, curDate+12);
  if (pLogFile->logLevel <= DEBUG)
  {
    sprintf(logBuf, "%s [%s:%s:%ld]", logBuf, file, func, line);
  }
  sprintf(logBuf, "%s [%9.9s]: ", logBuf, logLevelInfo);

  memset(logStr, 0x00, sizeof(logStr));
  va_start(args,fmt);
  vsprintf(logStr, fmt, args);
  va_end(args);

  strcat(logBuf, logStr);
  strcat(logBuf, "\n");
  putRcd(logBuf,pLogFile->fpLog);
  fflush(pLogFile->fpLog);

  return 0;
}

int closeLog(typeLogFile *pLogFile)
{
  if (0 != closeFile(pLogFile->fpLog))
  {
    perror("close log file err!");
    return -1;
  }
  memset(pLogFile, 0x00, sizeof(typeLogFile));
  return 0;
}


text:
import boto3
import flask
import mimetypes

from .base import AnnexBase

# -----------------------------------------------------------------------------

DEFAULT_EXPIRES_IN = 300

MISSING = object()

# -----------------------------------------------------------------------------

class S3Annex(AnnexBase):
    def __init__(
        self,
        bucket_name,
        *,
        region=None,
        access_key_id=None,
        secret_access_key=None,
        expires_in=DEFAULT_EXPIRES_IN,
        max_content_length=MISSING,
    ):
        self._client = boto3.client(
            "s3",
            region,
            aws_access_key_id=access_key_id,
            aws_secret_access_key=secret_access_key,
        )

        self._bucket_name = bucket_name
        self._expires_in = expires_in
        self._max_content_length = max_content_length

    def delete(self, key):
        self._client.delete_object(Bucket=self._bucket_name, Key=key)

    def delete_many(self, keys):
        # casting to tuple because keys might be iterable
        objects = tuple({"Key": key} for key in keys)
        if not objects:
            # boto fails if the array is empty.
            return

        self._client.delete_objects(
            Bucket=self._bucket_name,
            Delete={"Objects": objects},
        )

    def get_file(self, key, out_file):
        if isinstance(out_file, str):
            self._client.download_file(self._bucket_name, key, out_file)
        else:
            self._client.download_fileobj(self._bucket_name, key, out_file)

    def list_keys(self, prefix):
        response = self._client.list_objects_v2(
            Bucket=self._bucket_name,
            Prefix=prefix,
        )
        if "Contents" not in response:
            return ()
        return tuple(item["Key"] for item in response["Contents"])

    def save_file(self, key, in_file):
        # Get the content type from the key, rather than letting Boto try to
        # figure it out from the file's name, which may be uninformative. It's
        # better to do it here so S3 doesn't have a wrong content type, rather
        # than at read time as with content disposition.
        content_type = mimetypes.guess_type(key)[0]
        if content_type:
            extra_args = {"ContentType": content_type}
        else:
            extra_args = None

        if isinstance(in_file, str):
            self._client.upload_file(
                in_file,
                self._bucket_name,
                key,
                extra_args,
            )
        else:
            self._client.upload_fileobj(
                in_file,
                self._bucket_name,
                key,
                extra_args,
            )

    def send_file(self, key):
        url = self._client.generate_presigned_url(
            ClientMethod="get_object",
            Params={
                "Bucket": self._bucket_name,
                "Key": key,
                # We don't need to specify filename explicitly; the basename
                # of the key is in the URL and is appropriate here.
                "ResponseContentDisposition": "attachment",
            },
            ExpiresIn=self._expires_in,
        )
        return flask.redirect(url)

    def get_upload_info(self, key):
        fields = {}
        conditions = []

        content_type = mimetypes.guess_type(key)[0]
        if content_type:
            fields["Content-Type"] = content_type

        if self._max_content_length is not MISSING:
            max_content_length = self._max_content_length
        else:
            max_content_length = flask.current_app.config["MAX_CONTENT_LENGTH"]
        if max_content_length is not None:
            conditions.append(
                ("content-length-range", 0, max_content_length),
            )

        # Boto doesn't automatically add fields to conditions.
        for field_key, field_value in fields.items():
            conditions.append({field_key: field_value})

        post_info = self._client.generate_presigned_post(
            Bucket=self._bucket_name,
            Key=key,
            Fields=fields,
            Conditions=conditions,
            ExpiresIn=self._expires_in,
        )

        return {
            "method": "POST",
            "url": post_info["url"],
            "post_data": tuple(post_info["fields"].items()),
        }


text:
import pytest

from c3bottles import db

@pytest.fixture(scope="function", autouse=True)
def database(request):
    db.engine.execute("ATTACH ':memory:' AS meta;")
    db.create_all()

    def fin():
        db.drop_all()
        db.engine.execute("DETACH meta;")

    request.addfinalizer(fin)


text:
If you have an issue with Bailador we would love to help you, but there are a few thing we would like to ask you to make it easier for us to help.

First of all, are you on the most recent release of Rakudo? We recommend upgrading and trying again.
Are you using the most recent version of Bailador?

Please include the version number of Rakudo (the output of perl6 -v), the version number of zef (zef info zef) and the Operating System.

If you have an installation problem please include the output of `zef install Bailador`.

Otherwise please describe the problem and include the files you feel we will need to reproduce the problem.

Put command between single backticks ``.
Put output and code snippets betwee tripple-backticks:
```
code or output
```

Oh, and feel free to remove this template text from your issue :)
--------------------


text:
/**
 * @file    chheap.h
 * @brief   Heaps macros and structures.
 *
 * @addtogroup heaps
 * @{
 */

#ifndef CHHEAP_H
#define CHHEAP_H

#if (CH_CFG_USE_HEAP == TRUE) || defined(__DOXYGEN__)

/*===========================================================================*/
/* Module constants.                                                         */
/*===========================================================================*/

/**
 * @brief   Minimum alignment used for heap.
 * @note    Cannot use the sizeof operator in this macro.
 */
#if (SIZEOF_PTR == 4) || defined(__DOXYGEN__)
#define CH_HEAP_ALIGNMENT   8U
#elif (SIZEOF_PTR == 2)
#define CH_HEAP_ALIGNMENT   4U
#else
#error "unsupported pointer size"
#endif

/*===========================================================================*/
/* Module pre-compile time settings.                                         */
/*===========================================================================*/

/*===========================================================================*/
/* Derived constants and error checks.                                       */
/*===========================================================================*/

#if CH_CFG_USE_MEMCORE == FALSE
#error "CH_CFG_USE_HEAP requires CH_CFG_USE_MEMCORE"
#endif

#if (CH_CFG_USE_MUTEXES == FALSE) && (CH_CFG_USE_SEMAPHORES == FALSE)
#error "CH_CFG_USE_HEAP requires CH_CFG_USE_MUTEXES and/or CH_CFG_USE_SEMAPHORES"
#endif

/*===========================================================================*/
/* Module data structures and types.                                         */
/*===========================================================================*/

/**
 * @brief   Type of a memory heap.
 */
typedef struct memory_heap memory_heap_t;

/**
 * @brief   Type of a memory heap header.
 */
typedef union heap_header heap_header_t;

/**
 * @brief   Memory heap block header.
 */
union heap_header {
  stkalign_t align;
  struct {
    heap_header_t       *next;      /**< @brief Next block in free list.    */
    size_t              pages;      /**< @brief Size of the area in pages.  */
  } free;
  struct {
    memory_heap_t       *heap;      /**< @brief Block owner heap.           */
    size_t              size;       /**< @brief Size of the area in bytes.  */
  } used;
};

/**
 * @brief   Structure describing a memory heap.
 */
struct memory_heap {
  memgetfunc2_t         provider;   /**< @brief Memory blocks provider for
                                                this heap.                  */
  heap_header_t         header;     /**< @brief Free blocks list header.    */
#if CH_CFG_USE_MUTEXES == TRUE
  mutex_t               mtx;        /**< @brief Heap access mutex.          */
#else
  semaphore_t           sem;        /**< @brief Heap access semaphore.      */
#endif
};

/*===========================================================================*/
/* Module macros.                                                            */
/*===========================================================================*/

/**
 * @brief   Allocation of an aligned static heap buffer.
 */
#define CH_HEAP_AREA(name, size)                                            \
  ALIGNED_VAR(CH_HEAP_ALIGNMENT)                                            \
  uint8_t name[MEM_ALIGN_NEXT((size), CH_HEAP_ALIGNMENT)]

/*===========================================================================*/
/* External declarations.                                                    */
/*===========================================================================*/

#ifdef __cplusplus
extern "C" {
#endif
  void _heap_init(void);
  void chHeapObjectInit(memory_heap_t *heapp, void *buf, size_t size);
  void *chHeapAllocAligned(memory_heap_t *heapp, size_t size, unsigned align);
  void chHeapFree(void *p);
  size_t chHeapStatus(memory_heap_t *heapp, size_t *totalp, size_t *largestp);
#ifdef __cplusplus
}
#endif

/*===========================================================================*/
/* Module inline functions.                                                  */
/*===========================================================================*/

/**
 * @brief   Allocates a block of memory from the heap by using the first-fit
 *          algorithm.
 * @details The allocated block is guaranteed to be properly aligned for a
 *          pointer data type.
 *
 * @param[in] heapp     pointer to a heap descriptor or @p NULL in order to
 *                      access the default heap.
 * @param[in] size      the size of the block to be allocated. Note that the
 *                      allocated block may be a bit bigger than the requested
 *                      size for alignment and fragmentation reasons.
 * @return              A pointer to the allocated block.
 * @retval NULL         if the block cannot be allocated.
 *
 * @api
 */
static inline void *chHeapAlloc(memory_heap_t *heapp, size_t size) {

  return chHeapAllocAligned(heapp, size, CH_HEAP_ALIGNMENT);
}

/**
 * @brief   Returns the size of an allocated block.
 * @note    The returned value is the requested size, the real size is the
 *          same value aligned to the next @p CH_HEAP_ALIGNMENT multiple.
 *
 * @param[in] p         pointer to the memory block
 * @return              Size of the block.
 *
 * @api
 */
static inline size_t chHeapGetSize(const void *p) {

  return ((heap_header_t *)p)->used.size;
}

#endif /* CH_CFG_USE_HEAP == TRUE */

#endif /* CHHEAP_H */

/** @} */


text:
package com.theisenp.harbor.test;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import lcm.lcm.LCMDataInputStream;
import lcm.lcm.LCMEncodable;

/**
 * A collection of test related static utilities
 *
 * @author patrick.theisen
 */
public class TestUtils {

	/**
	 * @param message
	 * @return An {@link LCMDataInputStream} wrapped around the given
	 * {@link LCMEncodable}
	 * @throws IOException
	 */
	public static LCMDataInputStream wrap(LCMEncodable message) {
		try {
			ByteArrayOutputStream output = new ByteArrayOutputStream();
			message.encode(new DataOutputStream(output));
			return new LCMDataInputStream(output.toByteArray());
		}
		catch(IOException exception) {
			throw new RuntimeException(exception);
		}
	}
}


text:
package com.google.devtools.moe.client.project;

import com.google.devtools.moe.client.translation.editors.Editor;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Configuration for a MOE Translator
 */
public class TranslatorConfig {

  private String fromProjectSpace;
  private String toProjectSpace;
  private List<StepConfig> steps;
  private boolean inverse;

  public TranslatorConfig() {} // Constructed by gson

  public String getFromProjectSpace() {
    return fromProjectSpace;
  }

  public String getToProjectSpace() {
    return toProjectSpace;
  }

  public List<StepConfig> getSteps() {
    return steps;
  }

  public boolean isInverse() {
    return inverse;
  }

  public ScrubberConfig scrubber() {
    if (getSteps() != null) {
      for (StepConfig step : getSteps()) {
        if (step.getEditorConfig().type() == Editor.Type.scrubber) {
          return step.getEditorConfig().scrubberConfig();
        }
      }
    }
    return null;
  }

  public List<ScrubberConfig> scrubbers() {
    if (getSteps() != null) {
      return getSteps().stream()
          .map(StepConfig::getEditorConfig)
          .filter(ec -> ec.type() == Editor.Type.scrubber)
          .map(EditorConfig::scrubberConfig)
          .collect(Collectors.toList());
    }
    return new ArrayList<>(0);
  }

  void validate() throws InvalidProject {
    InvalidProject.assertNotEmpty(fromProjectSpace, "Translator requires from_project_space");
    InvalidProject.assertNotEmpty(toProjectSpace, "Translator requires to_project_space");
    if (inverse) {
      InvalidProject.assertTrue(steps == null, "Inverse translator can't have steps");
    } else {
      InvalidProject.assertTrue(steps != null, "Translator requires steps");
      for (StepConfig s : steps) {
        s.validate();
      }
    }
  }
}


text:
This project uses [README Driven Development so...](http://tom.preston-werner.com/2010/08/23/readme-driven-development.html) there is nothing here yet except for this README!

# Jenny

Jenny generates Java Projects from templates, so that you can get started faster.

# Prerequisites

* Java 8 JRE
* JAVA_HOME environment variable pointing at the installation directory of the JRE

# Installation

* Download Jenny from TODO.
* Unzip and add the extracted directory to your PATH.
* Point the environment variable JENNY_HOME to where you extracted Jenny.
* On a command line, run `jen` to check that installation was successful.

# Usage

Add a new repository of templates. "main" is just a name to refer to a repository. It can be
anything you want but since you'll need to type it every time, it is worth choosing something
short. The url can be any valid git repository containing templates.

    jen add main https://github.com/rupert654/jennyTemplateRepository

See all the templates that are repositories you have added.

    jen list

Create a new project, relative to your current directory, from the specified template.

    jen new main example

You will be prompted if the template requires any more information from you.

# Write Templates

Templates are organised and released as git repositories. To make your repository compatible with
Jenny, it may only contain top-level directories that are templates. The name of the template is
the name of the directory (and is what will need to be typed every time your template is used, so
keep it short!). Your repository may contain any number of other files at the top-level (e.g. a
licence or README) as Jenny will ignore these.

Each template consists of any number of files and directories which will be directly copied when a
new project is created from it.

In addition, you must have a template.xml file at the top-level which allows you to define
meta-data about your template, including any parameters that you want to request when it used. You
will be able to use these parameters in both the names of the files and directories that make up
your template, as well as in the content of those files.


text:
NSString * const kCPPodfileTargetDefinitionsAttributeKey = @"target_definitions";
NSString * const kCPPodfileWorkspaceAttributeKey = @"workspace";
NSString * const kCPPodfileGenerateBridgeSupportAttributeKey = @"generate_bridge_support";
NSString * const kCPPodfileSetArcCompatibilityFlagAttributeKey = @"set_arc_compatibility_flag";

@implementation CPProtoPodfile

- (NSArray*)targetDefinitions; {
  id value = [self backingStoreValueForKey:@"target_definitions"];
  return CPCoherceToArray(value);
}

- (void)setTargetDefinitions:(NSArray*)targetDefinitions; {
  [self setBackingStoreValue:targetDefinitions forKey:@"target_definitions"];
}

- (NSString*)workspace; {
  return [self backingStoreValueForKey:@"workspace"];
}

- (void)setWorkspace:(NSString*)workspace; {
  [self setBackingStoreValue:workspace forKey:@"workspace"];
}

- (BOOL)generateBridgeSupport; {
  id value = [self backingStoreValueForKey:@"generate_bridge_support"];
  return [value boolValue];
}

- (void)setGenerateBridgeSupport:(BOOL)generateBridgeSupport; {
  [self setBackingStoreValue:[NSNumber numberWithBool:generateBridgeSupport] forKey:@"generate_bridge_support"];
}

- (BOOL)setArcCompatibilityFlag; {
  id value = [self backingStoreValueForKey:@"set_arc_compatibility_flag"];
  return [value boolValue];
}

- (void)setSetArcCompatibilityFlag:(BOOL)setArcCompatibilityFlag; {
  [self setBackingStoreValue:[NSNumber numberWithBool:setArcCompatibilityFlag] forKey:@"set_arc_compatibility_flag"];
}

@end


text:
title: Page Statuses
category: page
slug: page-statuses
sortorder: 0704
toc: True
sidebartitle: Page Statuses
meta: Many pages on Full Stack Python are a work-in-progress. This page aggregates the status of each other page.

There are 205 pages on Full Stack Python, not including blog posts. Many
pages are a work-in-progress. This page aggregates the status of each page
on the site.

Each page can be in one of four levels of maturity:

1. Not yet created
2. Starter
3. Intermediate
4. Maintain

Pages are never technically "complete" because there will always be
the possibility of new sections and link maintenance. However, the
aspiration is for all pages to be fully-fleshed out and in the "Maintain"
category where they do not require additional information beyond being
kept up to date with accurate descriptions and resources.

## Chapter 1: Introduction
|Page                                                     | Status       |
|---------------------------------------------------------|--------------|
|[Introduction](/introduction.html)                       | maintain     |
|[Learning Programming](/learning-programming.html)       | maintain     |
|[The Python Language](/python-programming-language.html) | maintain     |
|[Why Use Python?](/why-use-python.html)                  | maintain     |
|[Enterprise Python](/enterprise-python.html)             | maintain     |
|[Python Community](/python-community.html)               | maintain     |
|[Companies Using Python](/companies-using-python.html)   | maintain     |
|[Best Python Resources](/best-python-resources.html)     | maintain     |
|[Must-watch Python Videos](/best-python-videos.html)     | maintain     |
|[Podcasts](/best-python-podcasts.html)                   | maintain     |

## Chapter 2: Development Environments
|Page                                                          | Status       |
|--------------------------------------------------------------|--------------|
|[Development environments](/development-environments.html)    | maintain     |
|[Text Editors and IDEs](/text-editors-ides.html)              | maintain     |
|[Vim](/vim.html)                                              | maintain     |
|[Emacs](/emacs.html)                                          | maintain     |
|[Sublime Text](/sublime-text.html)                            | maintain     |
|[PyCharm](/pycharm.html)                                      | intermediate |
|[Jupyter Notebook](/jupyter-notebook.html)                    | maintain     |
|[Shells](/shells.html)                                        | starter      |
|[Bourne-again shell (Bash)](/bourne-again-shell-bash.html)    | starter      |
|[Zsh](/zsh-shell.html)                                        | starter      |
|[PowerShell](/powershell.html)                                | starter      |
|[Terminal multiplexers](/terminal-multiplexers.html)          | starter      |
|[tmux](/tmux.html)                                            | starter      |
|[Screen](/screen.html)                                        | starter      |
|[Pymux](/pymux.html)                                          | starter      |
|[Environment configuration](/environment-configuration.html)  | starter      |
|[Application dependencies](/application-dependencies.html)    | intermediate |
|[virtualenvs](/virtual-environments-virtualenvs-venvs.html)   | starter      |
|[Environment variables](/environment-variables.html)          | starter      |
|[Localhost tunnels](/localhost-tunnels.html)                  | starter      |
|[Source Control](/source-control.html)                        | intermediate |
|[Git](/git.html)                                              | starter      |
|[Mercurial](/mercurial.html)                                  | starter      |

## Chapter 3: Data
|Page                                                       | Status       |
|-----------------------------------------------------------|--------------|
|[Relational databases](/databases.html)                    | intermediate |
|[PostgreSQL](/postgresql.html)                             | intermediate |
|[MySQL](/mysql.html)                                       | intermediate |
|[SQLite](/sqlite.html)                                     | intermediate |
|[ORMs](/object-relational-mappers-orms.html)               | maintain     |
|[SQLAlchemy](/sqlalchemy.html)                             | intermediate |
|[Peewee](/peewee.html)                                     | starter      |
|[Django ORM](/django-orm.html)                             | starter      |
|[SQLObject](/sqlobject.html)                               | starter      |
|[Pony ORM](/pony-orm.html)                                 | starter      |
|[NoSQL](/no-sql-datastore.html)                            | starter      |
|[Redis](/redis.html)                                       | starter      |
|[MongoDB](/mongodb.html)                                   | starter      |
|[Apache Cassandra](/apache-cassandra.html)                 | starter      |
|[Neo4j](/neo4j.html)                                       | starter      |
|[Data analysis](/data-analysis.html)                       | starter      |
|[pandas](/pandas.html)                                     | starter      |
|[SciPy & NumPy](/scipy-numpy.html)                         | starter      |
|Data visualization                                         | not yet      |
|[Bokeh](/bokeh.html)                                       | starter      |
|[d3.js](d3-js.html)                                        | starter      |
|[Matplotlib](matplotlib.html)                              | starter      |
|Markup Languages                                           | not yet      |
|[Markdown](/markdown.html)                                 | starter      |
|reStructuredText                                           | not yet      |

## Chapter 4: Web Development
|Page                                                       | Status       |
|-----------------------------------------------------------|--------------|
|[Web development](/web-development.html)                   | intermediate |
|[Web frameworks](/web-frameworks.html)                     | maintain     |
|[Django](/django.html)                                     | intermediate |
|[Flask](/flask.html)                                       | maintain     |
|[Bottle](/bottle.html)                                     | intermediate |
|[Pyramid](/pyramid.html)                                   | starter      |
|[Falcon](/falcon.html)                                     | starter      |
|[Morepath](/morepath.html)                                 | starter      |
|[Sanic](/sanic.html)                                       | starter      |
|[Other web frameworks](/other-web-frameworks.html)         | intermediate |
|[Template engines](/template-engines.html)                 | maintain     |
|[Jinja2](/jinja2.html)                                     | intermediate |
|[Mako](/mako.html)                                         | starter      |
|[Django templates](/django-templates.html)                 | starter      |
|[Web design](/web-design.html)                             | starter      |
|[HTML](/hypertext-markup-language-html.html)               | starter      |
|[CSS](/cascading-style-sheets.html)                        | starter      |
|[Responsive design](/responsive-design.html)               | starter      |
|[Minification](/minification.html)                         | starter      |
|[Testing](/testing.html)                                   | starter      |
|[Unit testing](/unit-testing.html)                         | starter      |
|[Integration testing](/integration-testing.html)           | starter      |
|Database testing                                           | not yet      |
|[Code metrics](/code-metrics.html)                         | starter      |
|[Debugging](/debugging.html)                               | starter      |

## Chapter 5: Web App Deployment
|Page                                                        | Status       |
|------------------------------------------------------------|--------------|
|[Deployment](/deployment.html)                              | intermediate |

## Chapter 6: DevOps
|Page                                                        | Status       |
|------------------------------------------------------------|--------------|
|[DevOps](/devops.html)                                      | starter      |
|[Monitoring](/monitoring.html)                              | intermediate |
|Graphite                                                    | not yet      |
|Prometheus                                                  | not yet      |
|Service Canary                                              | not yet      |
|[Rollbar](/rollbar.html)                                    | starter      |
|Sentry                                                      | not yet      |
|Scout                                                       | not yet      |
|Web App Performance                                         | not yet      |
|[Caching](/caching.html)                                    | starter      |
|Load testing                                                | not yet      |
|Scaling                                                     | not yet      |
|[Logging](/logging.html)                                    | intermediate |
|stdlib logging                                              | not yet      |
|DTrace                                                      | not yet      |
|logbook                                                     | not yet      |
|[Web analytics](/web-analytics.html)                        | starter      |
|Google Analytics                                            | not yet      |
|Piwik                                                       | not yet      |


text:
namespace LvEdEngine
{
    class BillboardGob : public PrimitiveShapeGob // note: in the schema, billboard deriveds from game object...but we want to re-use some code from ShapeGob.
    {
    public:
        BillboardGob() : PrimitiveShapeGob( RenderShape::Quad ) {m_intensity=1.0f;}
        virtual const char* ClassName() const {return StaticClassName();}
        static const char* StaticClassName(){return "BillboardGob";}

        // push Renderable nodes
        virtual bool GetRenderables(RenderableNodeCollector* collector, RenderContext* context);
        virtual void SetupRenderable(RenderableNode* r, RenderContext* context);
        void SetIntensity(float intensity){m_intensity = intensity;};
    protected:
        float m_intensity;
    };
}


text:
<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html;charset=utf-8" />
    <meta charset="utf-8">

    <title>Home</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">

    <link rel="shortcut icon" href="favicon.ico">

    <link rel="stylesheet" href="css/grid.css">
    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" href="css/normalize.css">

EN

FR

GM

My Account

My Wishlist

Log In

Sign Up

Jewel Online Store

                        Welcome visitor you can login or create an account.

                                Cart

                    <form class="search">
                        <input type="submit" class="search_button" value="">
                        <input type="text" name="search" class="search_form" value="" placeholder="Search entire store here...">
                    </form>

Home

                            Products

For home

For Garden

For Car

Other spray

Events

Blogs

                            All pages

Home

Login

Shoping cart

Product view

Events

Blog

Contact us

Login or Create an Account

New Customers

By creating an account with our store, you will be able to move through the checkout process faster, store multiple shipping addresses, view and track your orders in your account and more.

			<button class="account" onclick="window.location.href='register.html'">Create An Account</button>

			<form class="registed">

Registed Customers

If you have an account with us, please log in.

				Email Adress:*

				<input type="email" id ="email" name="email" class="ind_cont_input ind_cont_inputioce1" onfocus="if (value =='This field cannot be empty.'){value =''}" onblur="if (value ==''){value='This field cannot be empty.'}" value="This field cannot be empty."  >

				Password:*

				<input type="text" id="password" name="password" class="ind_cont_input ind_cont_inputioce1" onfocus="if (value =='This field cannot be empty.'){value =''}" onblur="if (value ==''){value='This field cannot be empty.'}" value="This field cannot be empty." >

				<input type="submit" onclick="post_login()"  value="Login" />

				*Required Field

			</form>


text:
echo "Creating temp directory..."
tmp_dir=$(mktemp -d)

echo "Getting URL for the latest nix installer..."
latest_installer_url=$(curl -Ls -o /dev/null -w %{url_effective} https://nixos.org/nix/install)

echo "Downloading the lastest installer and signature..."
curl -s -o $tmp_dir/install $latest_installer_url
curl -s -o $tmp_dir/install.asc "${latest_installer_url}.asc"

echo "Importing key and verifying installer script..."
gpg2 --keyserver hkps://keyserver.ubuntu.com --recv-keys B541D55301270E0BCF15CA5D8170B4726D7198DE
gpg2 --verify $tmp_dir/install.asc

echo "Starting nix install!"
sh $tmp_dir/install --daemon


text:
CLI Reference
=============

.. toctree::
   :maxdepth: 1

   freezer-manager-status


text:
import React, {useState} from 'react';
import {observer} from 'mobx-react-lite';
import {useTranslation} from 'react-i18next/hooks';
import {Trans} from 'react-i18next/hooks';
import {navigate} from '@reach/router';
import {makeStyles} from '@material-ui/styles';
import {IconButton} from '@material-ui/core';

import Container from '../ui/Container';
import ProgressButton from '../ui/ProgressButton';
import {SaveIcon} from '../ui/Icons';
import FieldRow from '../form/FieldRow';
import TextField from '../form/TextField';
import cellarsStore, {useCellar} from '../stores/cellarsStore';

export default observer(function CellarForm({id}) {
  const [cellar, ready] = useCellar(id);

  if (!ready) {
    return null;
  }

  const handleSave = () => {
    cellarsStore.save(cellar);
  };

  return (
    <Form
      title={<Trans i18nKey={id ? 'cellar.form.edit' : 'cellar.form.new'} />}
      cellar={cellar}
      onSave={handleSave}
    />
  );
});

const useStyles = makeStyles(theme => ({
  name: {
    flexBasis: '200px',
  },
  description: {
    width: '100%',
  },
}));

const Form = observer(function({title, cellar, onSave}) {
  const [saving, setSaving] = useState(false);
  const errors = {};

  const classes = useStyles();
  const [t] = useTranslation();

  function handleChange(value, name) {
    cellar[name] = value;
  }

  async function handleSubmit(event) {
    event.preventDefault();
    setSaving(true);

    try {
      await onSave();
      setTimeout(() => {
        // Time illusion for feedback
        setSaving(false);
      }, 500);
    } catch (error) {
      setSaving(false);
      console.error(error);
    }
  }

  return (
    <Container
      size="sm"
      title={title}
      actions={
        <ProgressButton
          Component={IconButton}
          loading={saving}
          size={40}
          type="submit"
          color="inherit"
          title={t('label.save')}
          aria-label={t('label.save')}
          onClick={handleSubmit}
        >
          <SaveIcon />
        </ProgressButton>
      }
      component="form"
      onSubmit={handleSubmit}
      noValidate
      autoComplete="off"
    >
      <FieldRow>
        <TextField
          label={<Trans i18nKey="cellar.name" />}
          name="name"
          required={true}
          value={cellar.name}
          onChange={handleChange}
          //error={null !== errors.name}
          helperText={errors.name}
          className={classes.name}
        />
      </FieldRow>
      <FieldRow>
        <TextField
          label={<Trans i18nKey="cellar.description" />}
          name="description"
          value={cellar.description}
          onChange={handleChange}
          className={classes.description}
        />
      </FieldRow>
    </Container>
  );
});


text:
package org.commonvox.hbase_column_manager;

import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.util.Bytes;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import org.junit.Test;

/**
 * Test ColumnDefinition in a standalone (non-persisting) manner. Persistence of ColumnDefinition
 * tested in {@link TestRepositoryAdmin}.
 *
 * @author Daniel Vimont
 */
public class TestColumnDefinition {

  private ColumnDefinition columnDefinition;
  private static final String COLUMN_DEFINITION_FAILURE
          = "FAILURE IN " + ColumnDefinition.class.getSimpleName() + " PROCESSING!! ==>> ";
  private static final String COLUMN_QUALIFIER = "TestColumnQualifier";
  private static final String KEY_STRING = "TestKey";
  private static final String VALUE_STRING = "TestValue";
  private static final ImmutableBytesWritable KEY_IMMUTABLE
          = new ImmutableBytesWritable(Bytes.toBytes(KEY_STRING));
  private static final ImmutableBytesWritable VALUE_IMMUTABLE
          = new ImmutableBytesWritable(Bytes.toBytes(VALUE_STRING));
  private static final long COLUMN_LENGTH = 899999999999993L;

  @Test
  public void testPublicConstructors() {

    columnDefinition = new ColumnDefinition(COLUMN_QUALIFIER);
    assertEquals(COLUMN_DEFINITION_FAILURE
            + "Inconsistency in column qualifier after String constructor invocation",
            COLUMN_QUALIFIER, columnDefinition.getColumnQualifierAsString());

    columnDefinition = new ColumnDefinition(Bytes.toBytes(COLUMN_QUALIFIER));
    assertArrayEquals(COLUMN_DEFINITION_FAILURE
            + "Inconsistency in column qualifier after byte-array constructor invocation",
            Bytes.toBytes(COLUMN_QUALIFIER), columnDefinition.getColumnQualifier());
  }

  @Test
  public void testSetValue() {

    columnDefinition
            = new ColumnDefinition(COLUMN_QUALIFIER).setValue(KEY_STRING, VALUE_STRING);
    assertEquals(COLUMN_DEFINITION_FAILURE
            + "Inconsistency in key/value pairing involved in "
            + "String #setValue and #getValue invocation",
            VALUE_STRING, columnDefinition.getValue(KEY_STRING));

    columnDefinition
            = new ColumnDefinition(COLUMN_QUALIFIER).setValue(
                    Bytes.toBytes(KEY_STRING), Bytes.toBytes(VALUE_STRING));
    assertArrayEquals(COLUMN_DEFINITION_FAILURE
            + "Inconsistency in key/value pairing involved in "
            + "byte-array #setValue and #getValue invocation",
            Bytes.toBytes(VALUE_STRING), columnDefinition.getValue(Bytes.toBytes(KEY_STRING)));

    columnDefinition
            = new ColumnDefinition(COLUMN_QUALIFIER).setValue(KEY_IMMUTABLE, VALUE_IMMUTABLE);
    assertArrayEquals(COLUMN_DEFINITION_FAILURE
            + "Inconsistency in key/value pairing involved in "
            + "ImmutableBytesWritable #setValue and #getValue invocation",
            VALUE_IMMUTABLE.get(), columnDefinition.getValue(KEY_IMMUTABLE.get()));
  }

  @Test
  public void testSetConfiguration() {

    columnDefinition
            = new ColumnDefinition(COLUMN_QUALIFIER).setConfiguration(KEY_STRING, VALUE_STRING);
    assertEquals(COLUMN_DEFINITION_FAILURE
            + "Inconsistency in key/value pairing involved in "
            + "String #setConfiguration and #getConfigurationValue invocation",
            VALUE_STRING, columnDefinition.getConfigurationValue(KEY_STRING));
  }

  @Test
  public void testSetColumnLength() {
    columnDefinition = new ColumnDefinition(COLUMN_QUALIFIER).setColumnLength(COLUMN_LENGTH);
    assertEquals(COLUMN_DEFINITION_FAILURE
            + "Inconsistency in column length in #setColumnLength and #getColumnLength invocation",
            COLUMN_LENGTH, columnDefinition.getColumnLength());
  }

  @Test
  public void testSetColumnValidationRegex() {
    columnDefinition
            = new ColumnDefinition(COLUMN_QUALIFIER).setColumnValidationRegex(VALUE_STRING);
    assertEquals(COLUMN_DEFINITION_FAILURE
            + "Inconsistency in column-validation-regex "
            + "in #setColumnValidationRegex and #getColumnValidationRegex invocation",
            VALUE_STRING, columnDefinition.getColumnValidationRegex());
  }

  public static void main(String[] args) throws Exception {
    new TestColumnDefinition().testPublicConstructors();
    new TestColumnDefinition().testSetValue();
    new TestColumnDefinition().testSetConfiguration();
    new TestColumnDefinition().testSetColumnLength();
    new TestColumnDefinition().testSetColumnValidationRegex();
  }
}


text:
package apple.metalperformanceshadersgraph.enums;

import org.moe.natj.general.ann.Generated;

/**
 * [@typedef] MPSGraphLossReductionType
 *

 * Options to be utilized by the graph
 *

 * [@constant] MPSGraphLossReductionTypeAxis No Reductions
 * [@constant] MPSGraphLossReductionTypeSum ReduceSum down to a scalar
 * [@constant] MPSGraphLossReductionTypeMean ReduceMean down to a scalar
 */
@Generated
public final class MPSGraphLossReductionType {
    @Generated
    private MPSGraphLossReductionType() {
    }

    @Generated public static final long Axis = 0x0000000000000000L;
    @Generated public static final long Sum = 0x0000000000000001L;
    @Generated public static final long Mean = 0x0000000000000002L;
}


text:
var path = require('path');

exports.config = {
	modules: {
		definition: false,
		wrapper: false
	},

	paths: {
		"public": 'public',
		"watched": ['app', 'vendor']
	},

	files: {
		javascripts: {
			joinTo: {
				'javascripts/app.js': /^app/,
				'javascripts/vendor.js': [
					'bower_components/modernizr/modernizr.js',
					'bower_components/jquery/dist/jquery.js',
					'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap.js',
					'bower_components/angular/angular.js',
					'bower_components/angular-route/angular-route.js',
					'bower_components/angular-resource/angular-resource.js',
					'bower_components/angular-sanitize/angular-sanitize.js',
					'bower_components/angular-mocks/angular-mocks.js',
					/^vendor/
				],
				'test/scenarios.js': /^test(\/|\\)e2e/
			},
			order: {
				before: [
					'bower_components/jquery/dist/jquery.js',
					'bower_components/angular/angular.js',
					'bower_components/bootstrap/dist/js/bootstrap.js'
				]
			}
		},
		stylesheets: {
			defaultExtension: 'scss',
			joinTo: {
				'stylesheets/font-awesome.css': 'bower_components/font-awesome/scss/font-awesome.scss',
				'stylesheets/app.css': /^app\/stylesheets\/app/
			}
		}
	},

	plugins: {
		ng_annotate: {
			pattern: /^app/
		},
		sass: {
			options: {
        includePaths: [
					'bower_components/bootstrap-sass-official/assets/stylesheets'
				]
			}
		},
		autoprefixer: {
			browsers: [
				"last 2 version",
				"> 1%", // browsers with > 1% usage
				"ie >= 9"
			],
			cascade: false
		}
	},

	server: {
		port: 3333,
		base: '/backfeeds-client/'
	},

	conventions: {
		assets: /app(\\|\/)assets(\\|\/)/
	},

	sourceMaps: true
};


text:
@echo off
call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat"
SET pathtome=%~dp0
SET SZIP="C:\Program Files\7-Zip\7z.exe"
echo Downloading mediainfo...
call cscript scripts\wget.js http://mediaarea.net/download/source/mediainfo/0.7.86/mediainfo_0.7.86_AllInclusive.7z mediainfo.7z
echo Unzipping mediainfo...
call %SZIP% x %pathtome%mediainfo.7z -o%pathtome%
DEL /F /S /Q /A %pathtome%mediainfo.7z

cd mediainfo_AllInclusive\MediaInfo\Project\MSVC2015
msbuild MediaInfo.sln /target:MediaInfoLib\MediaInfoLib /p:Configuration=Release
msbuild MediaInfo.sln /target:MediaInfoLib\MediaInfoLib /p:Configuration=Debug
cd ../../../..

mkdir %pathtome%mediainfo-build\lib
mkdir %pathtome%mediainfo-build\include\ZenLib
mkdir %pathtome%mediainfo-build\include\MediaInfo

cd mediainfo-build\lib

copy %pathtome%mediainfo_AllInclusive\MediaInfo\Project\MSVC2015\Win32\Debug\ZenLib.lib %pathtome%mediaInfo-build\lib
ren ZenLib.lib zenlibd.lib
copy %pathtome%mediainfo_AllInclusive\MediaInfo\Project\MSVC2015\Win32\Release\ZenLib.lib %pathtome%mediainfo-build\lib
ren ZenLib.lib zenlib.lib

copy %pathtome%mediainfo_AllInclusive\MediaInfo\Project\MSVC2015\Win32\Release\MediaInfo-Static.lib %pathtome%mediainfo-build\lib
ren MediaInfo-Static.lib mediainfo.lib
copy %pathtome%mediainfo_AllInclusive\MediaInfo\Project\MSVC2015\Win32\Debug\MediaInfo-Static.lib %pathtome%mediainfo-build\lib
ren MediaInfo-Static.lib mediainfod.lib

cd ../..

copy %pathtome%mediainfo_AllInclusive\ZenLib\Source\ZenLib\Conf.h %pathtome%mediainfo-build\include\ZenLib
copy %pathtome%mediainfo_AllInclusive\MediaInfoLib\Source\MediaInfo\MediaInfo.h %pathtome%mediainfo-build\include\MediaInfo
copy %pathtome%mediainfo_AllInclusive\MediaInfoLib\Source\MediaInfo\MediaInfo_Config.h %pathtome%mediainfo-build\include\MediaInfo
copy %pathtome%mediainfo_AllInclusive\MediaInfoLib\Source\MediaInfo\MediaInfo_Const.h %pathtome%mediainfo-build\include\MediaInfo

rd /S /Q mediainfo_AllInclusive

SETX MEDIAINFO_LIBRARYDIR %pathtome%mediainfo-build\lib /m
SETX MEDIAINFO_INCLUDEDIR %pathtome%mediainfo-build\include /m


text:
#ifndef GENERIC_READ_WRITE_H
#define GENERIC_READ_WRITE_H

#include "dag_platform.h"
#include "../card.h"
#include "../attribute_types.h"

#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/*
The generic_read_write module defines an object to handle reading and writing 32 bit values using different mechanisms
The most comonly used mechanism is the one over the DRB(Dag Register Bus).
Another is over the SMBus where the reading and writing is more involved.
Regardless this object is designed for use with attributes so they know how to read/write
themselves to the card without having to worry about the mechanics of it.
*/

typedef enum
{
    kGRWNoError,
    kGRWReadError,
    kGRWWriteError,
    kGRWError
} grw_error_t;

/* Sometimes to enable a feature in the framer means setting the bit to 0.
 * This allows the attribute to know which operation to use when enabling/disabling
 * a feature. In most cases enabling a feature means setting the relevant bit to 1, hence the
 * default setting is kGRWSetBit.
 */
typedef enum
{
    kGRWInvalidOperation,
    kGRWClearBit,
    kGRWSetBit,
} grw_on_operation_t;

/* Forward declarations. */
typedef struct GenericReadWriteObject GenericReadWriteObject;
typedef GenericReadWriteObject* GenericReadWritePtr;

/* Method signatures. */
typedef uint32_t (*GenericReadRoutine)(GenericReadWritePtr grw);
typedef void (*GenericWriteRoutine)(GenericReadWritePtr grw, uint32_t value);

void grw_set_address(GenericReadWritePtr grw, uintptr_t address);
uintptr_t grw_get_address(GenericReadWritePtr grw);
void grw_set_read_routine(GenericReadWritePtr grw, GenericReadRoutine routine);
void grw_set_write_routine(GenericReadWritePtr grw, GenericWriteRoutine routine);
uint32_t grw_read(GenericReadWritePtr grw);
void grw_write(GenericReadWritePtr grw, uint32_t value);
GenericReadWritePtr grw_init(DagCardPtr card, uintptr_t address, GenericReadRoutine read, GenericWriteRoutine write);
void grw_dispose(GenericReadWritePtr grw);
DagCardPtr grw_get_card(GenericReadWritePtr grw);
grw_error_t grw_get_last_error(GenericReadWritePtr grw);
void grw_set_last_error(GenericReadWritePtr grw, grw_error_t error);
void grw_set_on_operation(GenericReadWritePtr grw, grw_on_operation_t op);
grw_on_operation_t grw_get_on_operation(GenericReadWritePtr grw);
void grw_set_attribute(GenericReadWritePtr grw, AttributePtr attribute);
AttributePtr grw_get_attribute(GenericReadWritePtr grw);

/* Various functions that define different ways to retrieve and set register values.*/
void grw_iom_write(GenericReadWritePtr grw, uint32_t value);
uint32_t grw_iom_read(GenericReadWritePtr grw);
uint32_t grw_dag71s_phy_read(GenericReadWritePtr grw);
void grw_dag71s_phy_write(GenericReadWritePtr grw, uint32_t val);
uint32_t grw_mini_mac_raw_smbus_read(GenericReadWritePtr grw);

uint32_t grw_vsc8476_raw_smbus_read(GenericReadWritePtr grw);
uint32_t grw_mini_mac_raw_smbus_word_read(GenericReadWritePtr grw);
void grw_mini_mac_raw_smbus_write(GenericReadWritePtr grw, uint32_t val);

uint32_t grw_xfp_sfp_raw_smbus_read(GenericReadWritePtr grw);
void grw_xfp_sfp_raw_smbus_write(GenericReadWritePtr grw, uint32_t val);

void grw_vsc8476_raw_smbus_write(GenericReadWritePtr grw, uint32_t val);
void grw_mini_mac_raw_smbus_word_write(GenericReadWritePtr grw, uint32_t val);
uint32_t grw_drb_smbus_read(GenericReadWritePtr grw);
void grw_drb_smbus_write(GenericReadWritePtr grw, uint32_t val);
uint32_t grw_raw_smbus_read(GenericReadWritePtr grw);
void grw_raw_smbus_write(GenericReadWritePtr grw, uint32_t val);
void grw_dag43s_write(GenericReadWritePtr grw , uint32_t val);
uint32_t grw_dag43s_read(GenericReadWritePtr grw);
void grw_dag62se_write(GenericReadWritePtr grw , uint32_t val);
uint32_t grw_dag62se_read(GenericReadWritePtr grw);
void grw_lm63_smb_write(GenericReadWritePtr grw , uint32_t val);
uint32_t grw_lm63_smb_read(GenericReadWritePtr grw);
void grw_set_capture_hash(GenericReadWritePtr grw, uint32_t val);
void grw_unset_capture_hash(GenericReadWritePtr grw, uint32_t val);
uint32_t grw_rom_read(GenericReadWritePtr grw);
void grw_dag37d_write(GenericReadWritePtr grw , uint32_t val);
uint32_t grw_dag37d_read(GenericReadWritePtr grw);
uint32_t grw_vsc8476_mdio_read(GenericReadWritePtr grw);
void grw_vsc8476_mdio_write(GenericReadWritePtr grw, uint32_t val);
void grw_hlb_component_set_max_range(GenericReadWritePtr grw, uint32_t value);
uint32_t grw_hlb_component_get_max_range(GenericReadWritePtr grw);
uint32_t grw_hlb_component_get_min_range(GenericReadWritePtr grw);
void grw_hlb_component_set_min_range(GenericReadWritePtr grw, uint32_t value);
uint32_t grw_sonic_status_cache_read(GenericReadWritePtr grw);
uint32_t grw_oc48_deframer_status_cache_read(GenericReadWritePtr grw);
uint32_t grw_sonet_pp_b1_cache_read(GenericReadWritePtr grw);
uint32_t grw_sonet_pp_b2_cache_read(GenericReadWritePtr grw);
uint32_t grw_sonet_pp_b3_cache_read(GenericReadWritePtr grw);
uint32_t grw_sonet_pp_rei_cache_read(GenericReadWritePtr grw);
uint32_t grw_drb_optics_smbus_read(GenericReadWritePtr grw);
void grw_drb_optics_smbus_write(GenericReadWritePtr grw, uint32_t val);
uint32_t grw_vsc8486_mdio_read(GenericReadWritePtr grw);
void grw_vsc8486_mdio_write(GenericReadWritePtr grw, uint32_t val);
uint32_t grw_vsc8479_raw_smbus_read(GenericReadWritePtr grw);
void grw_vsc8479_raw_smbus_write(GenericReadWritePtr grw, uint32_t val);

#ifdef __cplusplus
}
#endif /* __cplusplus */

#endif /* ATTRIBUTE_H */


text:
/**
 * @file Ingress-ICE, extra features
 * @license MIT
 */

/*global page */
/*global config */

/**
 * Adds a timestamp to a screenshot
 * @since 2.3.0
 * @param {String} time
 * @param {boolean} iitcz
 */
function addTimestamp(time, iitcz) {
  if (!iitcz) {
    page.evaluate(function(dateTime) {
      var water = document.createElement('p');
      water.id='watermark-ice';
      water.innerHTML = dateTime;
      water.style.position = 'absolute';
      water.style.color = 'orange';
      water.style.top = '0';
      water.style.left = '0';
      water.style.fontSize = '40px';
      water.style.opacity = '0.8';
      water.style.marginTop = '0';
      water.style.paddingTop = '0';
      water.style.fontFamily = 'monospace';
      water.style.textShadow = '2px 2px 5px #111717';
      document.querySelector('#map_canvas').appendChild(water);
    }, time);
  } else {
    page.evaluate(function(dateTime) {
      var water = document.createElement('p');
      water.id='watermark-ice';
      water.innerHTML = dateTime;
      water.style.position = 'absolute';
      water.style.color = '#3A539B';
      water.style.top = '0';
      water.style.zIndex = '4404';
      water.style.marginTop = '0';
      water.style.paddingTop = '0';
      water.style.left = '0';
      water.style.fontSize = '40px';
      water.style.opacity = '0.8';
      water.style.fontFamily = 'monospace';
      water.style.textShadow = '2px 2px 5px #111717';
      document.querySelectorAll('body')[0].appendChild(water);
    }, time);
  }
}

/**
 * Inserts IITC and defines settings
 * @var hideRes
 * @var hideEnl
 * @var hideLink
 * @var hideField
 * @var minlevel
 * @var maxlevel
 * @var plugins
 * @var pluginsConfig
 * @author akileos (https://github.com/akileos)
 * @author Nikitakun
 */
function addIitc() {
  page.evaluate(function(field, link, res, enl, min, max) {
    localStorage['ingress.intelmap.layergroupdisplayed'] = JSON.stringify({
      "Unclaimed Portals":Boolean(min === 1),
      "Level 1 Portals":Boolean(min === 1),
      "Level 2 Portals":Boolean((min <= 2) && (max >= 2)),
      "Level 3 Portals":Boolean((min <= 3) && (max >= 3)),
      "Level 4 Portals":Boolean((min <= 4) && (max >= 4)),
      "Level 5 Portals":Boolean((min <= 5) && (max >= 5)),
      "Level 6 Portals":Boolean((min <= 6) && (max >= 6)),
      "Level 7 Portals":Boolean((min <= 7) && (max >= 7)),
      "Level 8 Portals":Boolean(max === 8),
      "Fields":field,
      "Links":link,
      "Resistance":res,
      "Enlightened":enl,
      "DEBUG Data Tiles":false,
      "Artifacts":true,
      "Ornaments":true
    });
    var script = document.createElement('script');
    script.type='text/javascript';
    script.src='https://secure.jonatkins.com/iitc/release/total-conversion-build.user.js';
    document.head.insertBefore(script, document.head.lastChild);
  }, !config.hideField, !config.hideLink, !config.hideRes, !config.hideEnl, config.minlevel, config.maxlevel);
  setupIitcPlugins(JSON.parse(config.pluginsConfig));
  JSON.parse(config.plugins).forEach(function(plugin) {
    loadIitcPlugin(plugin);
  })
}

/**
 * Loads an IITC plugin
 * @arg src {String}
 */
function loadIitcPlugin(src) {
  page.evaluate(function(src) {
    var script = document.createElement('script');
    script.type='text/javascript';
    script.src=src;
    document.head.insertBefore(script, document.head.lastChild);
  }, src);
}

/**
 * Configures IITC plugins
 * @arg settings {array}
 */
function setupIitcPlugins(settings) {
  page.evaluate(function(settings) {
    settings.forEach(function(param) {
      localStorage[param.key] = param.value;
    });
  }, settings);
}