text:
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
//
//*********************************************************

// The objects defined here demonstrate how to make sure each of the views created remains alive as long as
// the app needs them, but only when they're being used by the app or the user. Many of the scenarios contained in this
// sample use these functions to keep track of the views available and ensure that the view is not closed while
// the scenario is attempting to show it.
//
// As you can see in scenario 1, the ApplicationViewSwitcher.TryShowAsStandaloneAsync and
// ProjectionManager.StartProjectingAsync methods let you show one view next to another. The Consolidated event
// is fired when a view stops being visible separately from other views. Common cases where this will occur
// is when the view falls out of the list of recently used apps, or when the user performs the close gesture on the view.
// This is a good time to close the view, provided the app isn't trying to show the view at the same time. This event
// is fired on the thread of the view that becomes consolidated.
//
// Each view lives on its own thread, so concurrency control is necessary. Also, as you'll see in the sample,
// certain objects may be bound to UI on given threads. Properties of those objects should only be updated
// on that UI thread.

using System;
using System.ComponentModel;
using Windows.UI.Core;
using Windows.UI.ViewManagement;

namespace SecondaryViewsHelpers
{
    // A custom event that fires whenever the secondary view is ready to be closed. You should
    // clean up any state (including deregistering for events) then close the window in this handler
    public delegate void ViewReleasedHandler(Object sender, EventArgs e);

    // A ViewLifetimeControl is instantiated for every secondary view. ViewLifetimeControl's reference count
    // keeps track of when the secondary view thinks it's in usem and when the main view is interacting with the secondary view (about to show
    // it to the user, etc.) When the reference count drops to zero, the secondary view is closed.
    public sealed class ViewLifetimeControl : INotifyPropertyChanged
    {
        // Dispatcher for this view. Kept here for sending messages between this view and the main view.
        CoreDispatcher dispatcher;

        // Window for this particular view. Used to register and unregister for events
        CoreWindow window;

        // The title for the view shown in the list of recently used apps (by setting the title on
        // ApplicationView)
        string title;

        // This class uses references counts to make sure the secondary views isn't closed prematurely.
        // Whenever the main view is about to interact with the secondary view, it should take a reference
        // by calling "StartViewInUse" on this object. When finished interacting, it should release the reference
        // by calling "StopViewInUse". You can see examples of this throughout the sample, especially in
        // scenario 1.
        int refCount = 0;

        // Each view has a unique Id, found using the ApplicationView.Id property or
        // ApplicationView.GetApplicationViewIdForCoreWindow method. This id is used in all of the ApplicationViewSwitcher
        // and ProjectionManager APIs.
        int viewId;

        // Tracks if this ViewLifetimeControl object is still valid. If this is true, then the view is in the process
        // of closing itself down
        bool released = false;

        // Keeps track of if the consolidated event has fired yet. A view is consolidated with other views
        // when there's no way for the user to get to it (it's not in the list of recently used apps, cannot be
        // launched from Start, etc.) A view stops being consolidated when it's visible--at that point
        // the user can interact with it, move it on or off screen, etc.
        bool consolidated = true;

        // Used to store pubicly registered events under the protection of a lock
        event ViewReleasedHandler InternalReleased;

        // Instantiate views using "CreateForCurrentView"
        private ViewLifetimeControl(CoreWindow newWindow)
        {
            dispatcher = newWindow.Dispatcher;
            window = newWindow;
            viewId = ApplicationView.GetApplicationViewIdForWindow(window);

            // This class will automatically tell the view when its time to close
            // or stay alive in a few cases
            RegisterForEvents();
        }

        // Register for events on the current view
        private void RegisterForEvents()
        {
            // A view is consolidated with other views when there's no way for the user to get to it (it's not in the list of recently used apps, cannot be
            // launched from Start, etc.) A view stops being consolidated when it's visible--at that point the user can interact with it, move it on or off screen, etc.
            // It's generally a good idea to close a view after it has been consolidated, but keep it open while it's visible.
            ApplicationView.GetForCurrentView().Consolidated += ViewConsolidated;
        }

        // Unregister for events. Call this method before closing the view to prevent leaks.
        private void UnregisterForEvents()
        {
            ApplicationView.GetForCurrentView().Consolidated -= ViewConsolidated;
        }

        // A view is consolidated with other views hen there's no way for the user to get to it (it's not in the list of recently used apps, cannot be
        // launched from Start, etc.) A view stops being consolidated when it's visible--at that point the user can interact with it, move it on or off screen, etc.
        // It's generally a good idea to close a view after it has been consolidated, but keep it open while it's visible.
        private void ViewConsolidated(ApplicationView sender, ApplicationViewConsolidatedEventArgs e)
        {
            StopViewInUse();
        }

        // Called when a view has been "consolidated" (no longer accessible to the user)
        // and no other view is trying to interact with it. This should only be closed after the reference
        // count goes to 0 (including being consolidated). At the end of this, the view is closed.
        private void FinalizeRelease()
        {
            bool justReleased = false;
            lock (this)
            {
                if (refCount == 0)
                {
                    justReleased = true;
                    released = true;
                }
            }

            // This assumes that released will never be made false after it
            // it has been set to true
            if (justReleased)
            {
                UnregisterForEvents();
                InternalReleased(this, null);
            }
        }

        // Creates ViewLifetimeControl for the particular view.
        // Only do this once per view.
        public static ViewLifetimeControl CreateForCurrentView()
        {
            return new ViewLifetimeControl(CoreWindow.GetForCurrentThread());
        }

        // For purposes of this sample, the collection of views
        // is bound to a UI collection. This property is available for binding
        public string Title
        {
            get
            {
                return title;
            }
            set
            {
                if (title != value)
                {
                    title = value;
                    if (PropertyChanged != null)
                    {
                        PropertyChanged(this, new PropertyChangedEventArgs("Title"));
                    }
                }
            }
        }

        // Necessary to communicate with the window
        public CoreDispatcher Dispatcher
        {
            get
            {
                // This property never changes, so there's no need to lock
                return dispatcher;
            }
        }

        // Each view has a unique Id, found using the ApplicationView.Id property or
        // ApplicationView.GetApplicationViewIdForCoreWindow method. This id is used in all of the ApplicationViewSwitcher
        // and ProjectionManager APIs.
        public int Id
        {
            get
            {
                // This property never changes, so there's no need to lock
                return viewId;
            }
        }

        // Signals that the view is being interacted with by another view,
        // so it shouldn't be closed even if it becomes "consolidated"
        public int StartViewInUse()
        {
            bool releasedCopy = false;
            int refCountCopy = 0;

            // This method is called from several different threads
            // (each view lives on its own thread)
            lock (this)
            {
                releasedCopy = this.released;
                if (!released)
                {
                    refCountCopy = ++refCount;
                }
            }

            if (releasedCopy)
            {
                throw new InvalidOperationException("This view is being disposed");
            }

            return refCountCopy;
        }

        // Should come after any call to StartViewInUse
        // Signals that the another view has finished interacting with the view tracked
        // by this object
        public int StopViewInUse()
        {
            int refCountCopy = 0;
            bool releasedCopy = false;

            lock (this)
            {
                releasedCopy = this.released;
                if (!released)
                {
                    refCountCopy = --refCount;
                    if (refCountCopy == 0)
                    {
                        // If no other view is interacting with this view, and
                        // the view isn't accessible to the user, it's appropriate
                        // to close it
                        //
                        // Before actually closing the view, make sure there are no
                        // other important events waiting in the queue (this low-priority item
                        // will run after other events)
                        var task = dispatcher.RunAsync(CoreDispatcherPriority.Low, FinalizeRelease);
                    }
                }
            }

            if (releasedCopy)
            {
                throw new InvalidOperationException("This view is being disposed");
            }
            return refCountCopy;
        }

        // Signals to consumers that its time to close the view so that
        // they can clean up (including calling Window.Close() when finished)
        public event PropertyChangedEventHandler PropertyChanged;
        public event ViewReleasedHandler Released
        {
            add
            {
                bool releasedCopy = false;
                lock (this)
                {
                    releasedCopy = released;
                    if (!released)
                    {
                        InternalReleased += value;
                    }
                }

                if (releasedCopy)
                {
                    throw new InvalidOperationException("This view is being disposed");
                }
            }

            remove
            {
                lock (this)
                {
                    InternalReleased -= value;
                }
            }
        }
    }
}


text:
import { JobGroup } from '../../api';
import { JobGroupViewModel } from './job-group-view-model';

import { ActivityView } from '../activity-view';
import { JobView } from '../job/job-view';

import Action from '../../global/actions/action';
import Separator from '../../global/actions/separator';

import TEMPLATE from './job-group.tmpl.html';

export class JobGroupView extends ActivityView<JobGroupViewModel> {
    template = TEMPLATE;

    init(dom: js.IDom, viewModel: JobGroupViewModel) {
        super.init(dom, viewModel);
        dom('.js_jobs').observes(viewModel.jobs, JobView);
    }

    composeActions(viewModel: JobGroupViewModel): (Action | Separator)[] {
        return [
            viewModel.pauseAction,
            viewModel.resumeAction,
            new Separator(),
            viewModel.scheduleJobAction,
            new Separator(),
            viewModel.deleteAction
        ];
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.xueqiu.model;

import com.google.gson.annotations.SerializedName;

import java.io.Serializable;

public class Performance implements Serializable {

    private static final long serialVersionUID = -6958813379576812127L;

    private Integer type;// 收益类型
	private Long time;// 收益日期:yyyy-MM-dd
	private String symbol;// 股票收益的股票代码
	private Double principal;// 本金
	private Double cash;// 现金
	private Double assets;// 总资产
    @SerializedName("market_value")
	private Double marketValue;// 持有市值
    @SerializedName("monetary_unit")
	private String monetaryUnit;// 币种 [示例:CNY、USD 等 可参考:http://www.dzkc.net/money.htm]
	private Double shares;// 持股数
	private Double holdpercent;// 持仓占比
	private Double dilutedcost;// 摊薄成本
	private Double holdcost;// 持仓成本
    @SerializedName("accum_amount")
	private Double accumAmount;// 累计盈亏额
    @SerializedName("accum_rate")
	private Double accumRate;// 累计盈亏率
    @SerializedName("float_amount")
	private Double floatAmount;// 浮动盈亏额
    @SerializedName("float_rate")
	private Double floatRate;// 浮动盈亏率
    @SerializedName("day_amount")
	private Double dayAmount;// 当日盈亏额
    @SerializedName("day_rate")
	private Double dayRate;// 当日盈亏率
    @SerializedName("week_amount")
	private Double weekAmount;// 本周盈亏额
    @SerializedName("week_rate")
	private Double weekRate;// 本周盈亏率
    @SerializedName("month_amount")
	private Double monthAmount;// 本月盈亏额
    @SerializedName("month_rate")
	private Double monthRate;// 本月盈亏率

    public Integer getType() {
        return type;
    }

    public void setType(Integer type) {
        this.type = type;
    }

    public Long getTime() {
        return time;
    }

    public void setTime(Long time) {
        this.time = time;
    }

    public String getSymbol() {
        return symbol;
    }

    public void setSymbol(String symbol) {
        this.symbol = symbol;
    }

    public Double getPrincipal() {
        return principal;
    }

    public void setPrincipal(Double principal) {
        this.principal = principal;
    }

    public Double getCash() {
        return cash;
    }

    public void setCash(Double cash) {
        this.cash = cash;
    }

    public Double getAssets() {
        return assets;
    }

    public void setAssets(Double assets) {
        this.assets = assets;
    }

    public Double getMarketValue() {
        return marketValue;
    }

    public void setMarketValue(Double marketValue) {
        this.marketValue = marketValue;
    }

    public String getMonetaryUnit() {
        return monetaryUnit;
    }

    public void setMonetaryUnit(String monetaryUnit) {
        this.monetaryUnit = monetaryUnit;
    }

    public Double getShares() {
        return shares;
    }

    public void setShares(Double shares) {
        this.shares = shares;
    }

    public Double getHoldpercent() {
        return holdpercent;
    }

    public void setHoldpercent(Double holdpercent) {
        this.holdpercent = holdpercent;
    }

    public Double getDilutedcost() {
        return dilutedcost;
    }

    public void setDilutedcost(Double dilutedcost) {
        this.dilutedcost = dilutedcost;
    }

    public Double getHoldcost() {
        return holdcost;
    }

    public void setHoldcost(Double holdcost) {
        this.holdcost = holdcost;
    }

    public Double getAccumAmount() {
        return accumAmount;
    }

    public void setAccumAmount(Double accumAmount) {
        this.accumAmount = accumAmount;
    }

    public Double getAccumRate() {
        return accumRate;
    }

    public void setAccumRate(Double accumRate) {
        this.accumRate = accumRate;
    }

    public Double getFloatAmount() {
        return floatAmount;
    }

    public void setFloatAmount(Double floatAmount) {
        this.floatAmount = floatAmount;
    }

    public Double getFloatRate() {
        return floatRate;
    }

    public void setFloatRate(Double floatRate) {
        this.floatRate = floatRate;
    }

    public Double getDayAmount() {
        return dayAmount;
    }

    public void setDayAmount(Double dayAmount) {
        this.dayAmount = dayAmount;
    }

    public Double getDayRate() {
        return dayRate;
    }

    public void setDayRate(Double dayRate) {
        this.dayRate = dayRate;
    }

    public Double getWeekAmount() {
        return weekAmount;
    }

    public void setWeekAmount(Double weekAmount) {
        this.weekAmount = weekAmount;
    }

    public Double getWeekRate() {
        return weekRate;
    }

    public void setWeekRate(Double weekRate) {
        this.weekRate = weekRate;
    }

    public Double getMonthAmount() {
        return monthAmount;
    }

    public void setMonthAmount(Double monthAmount) {
        this.monthAmount = monthAmount;
    }

    public Double getMonthRate() {
        return monthRate;
    }

    public void setMonthRate(Double monthRate) {
        this.monthRate = monthRate;
    }
}


text:
import {World} from './World';
import {Item} from './Item';
import {Location} from './Location';
import {MersenneTwister} from './MersenneTwister';
import {RandomAssumed} from './filler/RandomAssumed';

export abstract class Filler {
  world: World;
  rng: MersenneTwister;

  constructor(world: World, rng: MersenneTwister) {
    this.world = world;
    this.rng = rng;
  }

  abstract fill(fillItems: Array<Item>): void;

  fastFillItemsInLocations(fillItems: Array<Item>, locations: Array<Location>): void {
    for (const location of locations) {
      if (location.hasItem()) continue;
      const item = fillItems.pop();
      if (!item) break;
      location.setItem(item);
    }
  }

  shuffleItems(items: Array<Item>): Array<Item> {
    return this.shuffleInPlace(items);
  }

  shuffleLocations(locations: Array<Location>): Array<Location> {
    return this.shuffleInPlace(locations);
  }

  shuffleInPlace<T>(array: T[]): T[] {
    // if it's 1 or 0 items, just return
    if (array.length <= 1) return array;

    // For each index in array
    for (let i = 0; i < array.length; i++) {

      // choose a random not-yet-placed item to place there
      // must be an item AFTER the current item, because the stuff
      // before has all already been placed
      const randomChoiceIndex = this.getRandom(i, array.length - 1);

      // place our random choice in the spot by swapping
      [array[i], array[randomChoiceIndex]] = [array[randomChoiceIndex], array[i]];
    }

    return array;
  }

  getRandom(floor: number, ceiling: number) {
    return Math.floor(this.rng.random() * (ceiling - floor + 1)) + floor;
  }
}


text:
package elastigo

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

	hostpool "github.com/bitly/go-hostpool"
)

type Request struct {
	*http.Client
	*http.Request
	hostResponse hostpool.HostPoolResponse
	client       *http.Client
}

func (r *Request) SetBodyJson(data interface{}) error {
	body, err := json.Marshal(data)
	if err != nil {
		return err
	}
	r.SetBodyBytes(body)
	r.Header.Set("Content-Type", "application/json")
	return nil
}

func (r *Request) SetBodyString(body string) {
	r.SetBody(strings.NewReader(body))
}

func (r *Request) SetBodyBytes(body []byte) {
	r.SetBody(bytes.NewReader(body))
}

func (r *Request) SetBody(body io.Reader) {
	rc, ok := body.(io.ReadCloser)
	if !ok && body != nil {
		rc = ioutil.NopCloser(body)
	}
	r.Body = rc
	if body != nil {
		switch v := body.(type) {
		case *strings.Reader:
			r.ContentLength = int64(v.Len())
		case *bytes.Reader:
			r.ContentLength = int64(v.Len())
		case *bytes.Buffer:
			r.ContentLength = int64(v.Len())
		}
	}
}

func (r *Request) Do(v interface{}) (int, []byte, error) {
	response, bodyBytes, err := r.DoResponse(v)
	if err != nil {
		return -1, nil, err
	}
	return response.StatusCode, bodyBytes, err
}

func (r *Request) DoResponse(v interface{}) (*http.Response, []byte, error) {
	var client = r.client
	if client == nil {
		client = http.DefaultClient
	}

	res, err := client.Do(r.Request)
	// Inform the HostPool of what happened to the request and allow it to update
	r.hostResponse.Mark(err)
	if err != nil {
		return nil, nil, err
	}

	defer res.Body.Close()
	bodyBytes, err := ioutil.ReadAll(res.Body)

	if err != nil {
		return nil, nil, err
	}

	if res.StatusCode == 404 {
		return nil, bodyBytes, RecordNotFound
	}

	if res.StatusCode >= 500 {
		return nil, nil, fmt.Errorf("received invalid response code from elasticsearch: %d", res.StatusCode)
	} else if res.StatusCode > 304 && v != nil {
		jsonErr := json.Unmarshal(bodyBytes, v)
		if jsonErr != nil {
			return nil, nil, jsonErr
		}
	}
	return res, bodyBytes, err
}

func Escape(args map[string]interface{}) (s string, err error) {
	vals := url.Values{}
	for key, val := range args {
		switch v := val.(type) {
		case string:
			vals.Add(key, v)
		case bool:
			vals.Add(key, strconv.FormatBool(v))
		case int, int32, int64:
			vals.Add(key, strconv.Itoa(v.(int)))
		case float32, float64:
			vals.Add(key, strconv.FormatFloat(v.(float64), 'f', -1, 64))
		case []string:
			vals.Add(key, strings.Join(v, ","))
		default:
			err = fmt.Errorf("Could not format URL argument: %s", key)
			return
		}
	}
	s = vals.Encode()
	return
}


text:
import pdb
# Add python-bitcoinrpc to module search path:
import os
import sys
import math
import binascii
from binascii import hexlify, unhexlify
from base64 import b64encode
from decimal import Decimal, ROUND_DOWN
import decimal
import json
import random
import shutil
import subprocess
import time
import re
import urllib.parse as urlparse
import errno

from . import coverage
from .authproxy import AuthServiceProxy, JSONRPCException

COVERAGE_DIR = None

# MVF-BU begin read regtest fork params from C files
try:
    _mvf_common_h_fh = open('src/mvf-bu-globals.h', 'rt')
except FileNotFoundError as e:
    _mvf_common_h_fh = open('../src/mvf-bu-globals.h', 'rt')

_mvf_common_h_contents = _mvf_common_h_fh.read()
_mvf_common_h_fh.close()

BTCFORK_CONF_FILENAME = re.search(r'BTCFORK_CONF_FILENAME = "(.*)";', _mvf_common_h_contents).group(1)
HARDFORK_HEIGHT_REGTEST_DEFAULT = int(re.search(r'HARDFORK_HEIGHT_REGTEST = (\d+)', _mvf_common_h_contents).group(1))
HARDFORK_PORT_REGTEST_DEFAULT = int(re.search(r'HARDFORK_PORT_REGTEST = (\d+)', _mvf_common_h_contents).group(1))
HARDFORK_SIGHASH_ID_DEFAULT = int(re.search(r'HARDFORK_SIGHASH_ID = (0x[0-9a-fA-F]+)', _mvf_common_h_contents).group(1), 16)
HARDFORK_DROPFACTOR_REGTEST_DEFAULT = int(re.search(r'HARDFORK_DROPFACTOR_REGTEST = (\d+)', _mvf_common_h_contents).group(1))
# MVF-BU end

DEFAULT_TX_FEE_PER_BYTE = 50
PerfectFractions = True
BTC = 100000000
mBTC = 100000
uBTC = 100

#Set Mocktime default to OFF.
#MOCKTIME is only needed for scripts that use the
#cached version of the blockchain.  If the cached
#version of the blockchain is used without MOCKTIME
#then the mempools will not sync due to IBD.
MOCKTIME = 0

def enable_mocktime():
    #For backwared compatibility of the python scripts
    #with previous versions of the cache, set MOCKTIME
    #to Jan 1, 2014 + (201 * 10 * 60)
    global MOCKTIME
    MOCKTIME = 1388534400 + (201 * 10 * 60)

def disable_mocktime():
    global MOCKTIME
    MOCKTIME = 0

def get_mocktime():
    return MOCKTIME

def enable_coverage(dirname):
    """Maintain a log of which RPC calls are made during testing."""
    global COVERAGE_DIR
    COVERAGE_DIR = dirname

def get_rpc_proxy(url, node_number, timeout=None):
    """
    Args:
        url (str): URL of the RPC server to call
        node_number (int): the node number (or id) that this calls to

    Kwargs:
        timeout (int): HTTP timeout in seconds

    Returns:
        AuthServiceProxy. convenience object for making RPC calls.

    """
    proxy_kwargs = {}
    if timeout is not None:
        proxy_kwargs['timeout'] = timeout

    proxy = AuthServiceProxy(url, **proxy_kwargs)
    proxy.url = url  # store URL on proxy for info

    coverage_logfile = coverage.get_filename(
        COVERAGE_DIR, node_number) if COVERAGE_DIR else None

    return coverage.AuthServiceProxyWrapper(proxy, coverage_logfile)

def p2p_port(n):
    #If port is already defined then return port
    if os.getenv("node" + str(n)):
        return int(os.getenv("node" + str(n)))
    #If no port defined then find an available port
    if n == 0:
        port = 11000 + n + os.getpid()%990
    else:
        port = int(os.getenv("node" + str(n-1))) + 1
    from subprocess import check_output
    netStatOut = check_output(["netstat", "-n"])
    for portInUse in re.findall(b"tcp.*?:(11\d\d\d)",netStatOut.lower()):
        #print portInUse
        if port == int(portInUse):
            port += 1
    os.environ["node" + str(n)] = str(port)

    #print "port node " + str(n) + " is " + str(port)
    return int(port)

def rpc_port(n):
    #If port is already defined then return port
    if os.getenv("rpcnode" + str(n)):
        return int(os.getenv("rpcnode" + str(n)))
    #If no port defined then find an available port
    if n == 0:
        port = 12000 + n + os.getpid()%990
    else:
        port = int(os.getenv("rpcnode" + str(n-1))) + 1
    from subprocess import check_output
    netStatOut = check_output(["netstat", "-n"])
    for portInUse in re.findall(b"tcp.*?:(12\d\d\d)",netStatOut.lower()):
        #print portInUse
        if port == int(portInUse):
            port += 1
    os.environ["rpcnode" + str(n)] = str(port)

    #print "port rpcnode " + str(n) + " is " + str(port)
    return int(port)

def check_json_precision():
    """Make sure json library being used does not lose precision converting BTC values"""
    n = Decimal("20000000.00000003")
    satoshis = int(json.loads(json.dumps(float(n)))*1.0e8)
    if satoshis != 2000000000000003:
        raise RuntimeError("JSON encode/decode loses precision")

def count_bytes(hex_string):
    return len(bytearray.fromhex(hex_string))

def bytes_to_hex_str(byte_str):
    return hexlify(byte_str).decode('ascii')

def hex_str_to_bytes(hex_str):
    return unhexlify(hex_str.encode('ascii'))

def str_to_b64str(string):
    return b64encode(string.encode('utf-8')).decode('ascii')

def sync_blocks(rpc_connections, wait=1):
    """
    Wait until everybody has the same block count
    """
    while True:
        counts = [ x.getblockcount() for x in rpc_connections ]
        print(counts)
        if counts == [ counts[0] ]*len(counts):
            break
        time.sleep(wait)

def sync_mempools(rpc_connections, wait=1):
    """
    Wait until everybody has the same transactions in their memory
    pools
    """
    while True:
        pool = set(rpc_connections[0].getrawmempool())
        num_match = 1
        for i in range(1, len(rpc_connections)):
            if set(rpc_connections[i].getrawmempool()) == pool:
                num_match = num_match+1
        if num_match == len(rpc_connections):
            break
        time.sleep(wait)

bitcoind_processes = {}

def initialize_datadir(dirname, n,bitcoinConfDict=None,wallet=None):
    datadir = os.path.join(dirname, "node"+str(n))
    if not os.path.isdir(datadir):
        os.makedirs(datadir)

    defaults = {"server":1, "discover":0, "regtest":1,"rpcuser":"rt","rpcpassword":"rt",
                "port":p2p_port(n),"rpcport":str(rpc_port(n)),"listenonion":0,"maxlimitertxfee":0}
    if bitcoinConfDict: defaults.update(bitcoinConfDict)

    with open(os.path.join(datadir, "bitcoin.conf"), 'w') as f:
        for (key,val) in defaults.items():
          if type(val) is type([]):
            for v in val:
              f.write("%s=%s\n" % (str(key), str(v)))
          else:
            f.write("%s=%s\n"% (str(key), str(val)))

    if wallet:
      regtestdir = os.path.join(datadir,"regtest")
      if not os.path.isdir(regtestdir):
          os.makedirs(regtestdir)
      print(regtestdir, os.path.join(regtestdir, "wallet.dat"))
      shutil.copyfile(wallet,os.path.join(regtestdir, "wallet.dat"))

    return datadir

def rpc_url(i, rpchost=None):
    return "http://rt:rt@%s:%d" % (rpchost or '127.0.0.1', rpc_port(i))

def wait_for_bitcoind_start(process, url, i):
    '''
    Wait for bitcoind to start. This means that RPC is accessible and fully initialized.
    Raise an exception if bitcoind exits during initialization.
    '''
    while True:
        if process.poll() is not None:
            raise Exception('bitcoind exited with status %i during initialization' % process.returncode)
        try:
            rpc = get_rpc_proxy(url, i)
            blocks = rpc.getblockcount()
            break # break out of loop on success
        except IOError as e:
            if e.errno != errno.ECONNREFUSED: # Port not yet open?
                raise # unknown IO error
        except JSONRPCException as e: # Initialization phase
            if e.error['code'] != -28: # RPC in warmup?
                raise # unkown JSON RPC exception
        time.sleep(0.25)

def initialize_chain(test_dir,bitcoinConfDict=None,wallets=None):
    """
    Create (or copy from cache) a 200-block-long chain and
    4 wallets.
    """

    if (not os.path.isdir(os.path.join("cache","node0"))
        or not os.path.isdir(os.path.join("cache","node1"))
        or not os.path.isdir(os.path.join("cache","node2"))
        or not os.path.isdir(os.path.join("cache","node3"))):

        #find and delete old cache directories if any exist
        for i in range(4):
            if os.path.isdir(os.path.join("cache","node"+str(i))):
                shutil.rmtree(os.path.join("cache","node"+str(i)))

        # Create cache directories, run bitcoinds:
        for i in range(4):
            datadir=initialize_datadir("cache", i,bitcoinConfDict)
            args = [ os.getenv("BITCOIND", "bitcoind"), "-keypool=1", "-datadir="+datadir ]
            if i > 0:
                args.append("-connect=127.0.0.1:"+str(p2p_port(0)))
            bitcoind_processes[i] = subprocess.Popen(args)
            if os.getenv("PYTHON_DEBUG", ""):
                print("initialize_chain: bitcoind started, waiting for RPC to come up")
            wait_for_bitcoind_start(bitcoind_processes[i], rpc_url(i), i)
            if os.getenv("PYTHON_DEBUG", ""):
                print("initialize_chain: RPC succesfully started")

        rpcs = []
        for i in range(4):
            try:
                rpcs.append(get_rpc_proxy(rpc_url(i), i))
            except:
                sys.stderr.write("Error connecting to "+url+"\n")
                sys.exit(1)

        # Create a 200-block-long chain; each of the 4 nodes
        # gets 25 mature blocks and 25 immature.
        # blocks are created with timestamps 10 minutes apart
        # starting from 2010 minutes in the past
        enable_mocktime()
        block_time = get_mocktime() - (201 * 10 * 60)
        for i in range(2):
            for peer in range(4):
                for j in range(25):
                    set_node_times(rpcs, block_time)
                    rpcs[peer].generate(1)
                    block_time += 10*60
                # Must sync before next peer starts generating blocks
                sync_blocks(rpcs)

        # Shut them down, and clean up cache directories:
        stop_nodes(rpcs)
        wait_bitcoinds()
        disable_mocktime()
        for i in range(4):
            os.remove(log_filename("cache", i, "debug.log"))
            os.remove(log_filename("cache", i, "db.log"))
            os.remove(log_filename("cache", i, "peers.dat"))
            os.remove(log_filename("cache", i, "fee_estimates.dat"))

    for i in range(4):
        from_dir = os.path.join("cache", "node"+str(i))
        to_dir = os.path.join(test_dir,  "node"+str(i))
        shutil.copytree(from_dir, to_dir)
        initialize_datadir(test_dir, i,bitcoinConfDict,wallets[i] if wallets else None) # Overwrite port/rpcport in bitcoin.conf

def initialize_chain_clean(test_dir, num_nodes, bitcoinConfDict=None, wallets=None):
    """
    Create an empty blockchain and num_nodes wallets.
    Useful if a test case wants complete control over initialization.
    """
    for i in range(num_nodes):
        datadir=initialize_datadir(test_dir, i, bitcoinConfDict, wallets)

def _rpchost_to_args(rpchost):
    '''Convert optional IP:port spec to rpcconnect/rpcport args'''
    if rpchost is None:
        return []

    match = re.match('(\[[0-9a-fA-f:]+\]|[^:]+)(?::([0-9]+))?$', rpchost)
    if not match:
        raise ValueError('Invalid RPC host spec ' + rpchost)

    rpcconnect = match.group(1)
    rpcport = match.group(2)

    if rpcconnect.startswith('['): # remove IPv6 [...] wrapping
        rpcconnect = rpcconnect[1:-1]

    rv = ['-rpcconnect=' + rpcconnect]
    if rpcport:
        rv += ['-rpcport=' + rpcport]
    return rv

def start_node(i, dirname, extra_args=None, rpchost=None, timewait=None, binary=None):
    """
    Start a bitcoind and return RPC connection to it
    """
    datadir = os.path.join(dirname, "node"+str(i))
    if binary is None:
        binary = os.getenv("BITCOIND", "bitcoind")
    # RPC tests still depend on free transactions
    args = [ binary, "-datadir="+datadir, "-rest", "-mocktime="+str(get_mocktime()) ] # // BU removed, "-keypool=1","-blockprioritysize=50000" ]
    if extra_args is not None: args.extend(extra_args)
    if os.getenv("PYTHON_DEBUG", ""):
        for k in range(len(args)):
            print("bitcoind args: " + args[k])

    bitcoind_processes[i] = subprocess.Popen(args)
    if os.getenv("PYTHON_DEBUG", ""):
        print("start_node: bitcoind started, waiting for RPC to come up")
    url = rpc_url(i, rpchost)
    wait_for_bitcoind_start(bitcoind_processes[i], url, i)
    if os.getenv("PYTHON_DEBUG", ""):
        print("start_node: RPC succesfully started")
    proxy = get_rpc_proxy(url, i, timeout=timewait)

    if COVERAGE_DIR:
        coverage.write_all_rpc_commands(COVERAGE_DIR, proxy)

    return proxy

def start_nodes(num_nodes, dirname, extra_args=None, rpchost=None, binary=None,timewait=None):
    """
    Start multiple bitcoinds, return RPC connections to them
    """
    if extra_args is None: extra_args = [ None for i in range(num_nodes) ]
    if binary is None: binary = [ None for i in range(num_nodes) ]
    rpcs = []
    try:
        for i in range(num_nodes):
            rpcs.append(start_node(i, dirname, extra_args[i], rpchost, binary=binary[i],timewait=timewait))
    except: # If one node failed to start, stop the others
        stop_nodes(rpcs)
        raise
    return rpcs

def log_filename(dirname, n_node, logname):
    return os.path.join(dirname, "node"+str(n_node), "regtest", logname)

# MVHF-BU begin: Function used for searching text files such as debug.log
def search_file(searchfilepath, searchtext):
    """Pass in the file to search and the search text and this returns a list of lines in the file which include the search text. """
    searchfile = open(searchfilepath, "r")
    searchlines=list()
    for line in searchfile:
        if searchtext in line: searchlines.append(line)
    searchfile.close()
    return searchlines
# MVHF-BU end

def stop_node(node, i):
    node.stop()
    bitcoind_processes[i].wait()
    del bitcoind_processes[i]

def stop_nodes(nodes):
    for node in nodes:
        node.stop()
    del nodes[:] # Emptying array closes connections as a side effect

def set_node_times(nodes, t):
    for node in nodes:
        node.setmocktime(t)

def wait_bitcoinds():
    # Wait for all bitcoinds to cleanly exit
    for bitcoind in bitcoind_processes.values():
        bitcoind.wait()
    bitcoind_processes.clear()

def connect_nodes(from_connection, node_num):
    ip_port = "127.0.0.1:"+str(p2p_port(node_num))
    from_connection.addnode(ip_port, "onetry")
    # poll until version handshake complete to avoid race conditions
    # with transaction relaying
    while any(peer['version'] == 0 for peer in from_connection.getpeerinfo()):
        time.sleep(0.1)

def connect_nodes_bi(nodes, a, b):
    connect_nodes(nodes[a], b)
    connect_nodes(nodes[b], a)

def interconnect_nodes(nodes):
    """Connect every node in this list to every other node in the list"""
    for frm in nodes:
      for to in nodes:
        if frm == to: continue
        up = urlparse.urlparse(to.url)
        ip_port = up.hostname + ":" + str(up.port-1000)  # this is the RPC port but we want the p2p port so -1000
        frm.addnode(ip_port, "onetry")

def find_output(node, txid, amount):
    """
    Return index to output of txid with value amount
    Raises exception if there is none.
    """
    txdata = node.getrawtransaction(txid, 1)
    for i in range(len(txdata["vout"])):
        if txdata["vout"][i]["value"] == amount:
            return i
    raise RuntimeError("find_output txid %s : %s not found"%(txid,str(amount)))

def gather_inputs(from_node, amount_needed, confirmations_required=1):
    """
    Return a random set of unspent txouts that are enough to pay amount_needed
    """
    assert(confirmations_required >=0)
    utxo = from_node.listunspent(confirmations_required)
    random.shuffle(utxo)
    inputs = []
    total_in = Decimal("0.00000000")
    while total_in < amount_needed and len(utxo) > 0:
        t = utxo.pop()
        total_in += t["amount"]
        inputs.append({ "txid" : t["txid"], "vout" : t["vout"], "address" : t["address"] } )
    if total_in < amount_needed:
        raise RuntimeError("Insufficient funds: need %d, have %d"%(amount_needed, total_in))
    return (total_in, inputs)

def make_change(from_node, amount_in, amount_out, fee):
    """
    Create change output(s), return them
    """
    outputs = {}
    amount = amount_out+fee
    change = amount_in - amount
    if change > amount*2:
        # Create an extra change output to break up big inputs
        change_address = from_node.getnewaddress()
        # Split change in two, being careful of rounding:
        outputs[change_address] = Decimal(change/2).quantize(Decimal('0.00000001'), rounding=ROUND_DOWN)
        change = amount_in - amount - outputs[change_address]
    if change > 0:
        outputs[from_node.getnewaddress()] = change
    return outputs

def send_zeropri_transaction(from_node, to_node, amount, fee):
    """
    Create&broadcast a zero-priority transaction.
    Returns (txid, hex-encoded-txdata)
    Ensures transaction is zero-priority by first creating a send-to-self,
    then using its output
    """

    # Create a send-to-self with confirmed inputs:
    self_address = from_node.getnewaddress()
    (total_in, inputs) = gather_inputs(from_node, amount+fee*2)
    outputs = make_change(from_node, total_in, amount+fee, fee)
    outputs[self_address] = float(amount+fee)

    self_rawtx = from_node.createrawtransaction(inputs, outputs)
    self_signresult = from_node.signrawtransaction(self_rawtx)
    self_txid = from_node.sendrawtransaction(self_signresult["hex"], True)

    vout = find_output(from_node, self_txid, amount+fee)
    # Now immediately spend the output to create a 1-input, 1-output
    # zero-priority transaction:
    inputs = [ { "txid" : self_txid, "vout" : vout } ]
    outputs = { to_node.getnewaddress() : float(amount) }

    rawtx = from_node.createrawtransaction(inputs, outputs)
    signresult = from_node.signrawtransaction(rawtx)
    txid = from_node.sendrawtransaction(signresult["hex"], True)

    return (txid, signresult["hex"])

def random_zeropri_transaction(nodes, amount, min_fee, fee_increment, fee_variants):
    """
    Create a random zero-priority transaction.
    Returns (txid, hex-encoded-transaction-data, fee)
    """
    from_node = random.choice(nodes)
    to_node = random.choice(nodes)
    fee = min_fee + fee_increment*random.randint(0,fee_variants)
    (txid, txhex) = send_zeropri_transaction(from_node, to_node, amount, fee)
    return (txid, txhex, fee)

def random_transaction(nodes, amount, min_fee, fee_increment, fee_variants):
    """
    Create a random transaction.
    Returns (txid, hex-encoded-transaction-data, fee)
    """
    from_node = random.choice(nodes)
    to_node = random.choice(nodes)
    fee = min_fee + fee_increment*random.randint(0,fee_variants)

    (total_in, inputs) = gather_inputs(from_node, amount+fee)
    outputs = make_change(from_node, total_in, amount, fee)
    outputs[to_node.getnewaddress()] = float(amount)

    rawtx = from_node.createrawtransaction(inputs, outputs)
    signresult = from_node.signrawtransaction(rawtx)
    txid = from_node.sendrawtransaction(signresult["hex"], True)

    return (txid, signresult["hex"], fee)

def split_transaction(node, prevouts, toAddrs, txfeePer=DEFAULT_TX_FEE_PER_BYTE,**kwargs):
    """
      Create a transaction that divides the sum of all the passed utxos into all the destination addresses
      pass:
           node: (node object) where to send the RPC calls
           prevouts: a single UTXO description dictionary, or a list of them
           toAddrs: a list of strings specifying the output addresses
           "sendtx=False" if you don't want to transaction to be submitted.
      Returns (transaction in hex, Vin list, Vout list)
    """
    if type(prevouts) == type({}): prevouts = [prevouts]  # If the user passes just one transaction then put a list around it
    txid = None
    inp = []
    decContext = decimal.getcontext().prec
    try:  # try finally block to put the decimal precision back to what it was prior to this routine
      decimal.getcontext().prec = 8 + 8 # 8 digits to get to 21million, and each bitcoin is 100 million satoshis
      amount = Decimal(0)
      iamount = 0
      count = 0
      for tx in prevouts:
        inp.append({"txid":str(tx["txid"]),"vout":tx["vout"]})
        amount += tx["amount"]*Decimal(BTC)
        iamount += int(tx["amount"]*Decimal(BTC))
        count += 1

      assert(amount == iamount) # make sure Decimal and integer math is consistent
      txLen = (len(prevouts)*100) + (len(toAddrs)*100)  # Guess the tx Size

      while 1:
          outp = {}
          if amount - Decimal(txfeePer*txLen) < 0:  # fee too big, find something smaller
            txfeePer = (float(amount)/txLen)/1.5

          txfee = int(math.ceil(txfeePer*txLen))
          amtPer = (Decimal(amount-txfee)/len(toAddrs)).to_integral_value()
          # print "amount: ", amount, " amount per: ", amtPer, "from :", len(prevouts), "to: ", len(toAddrs), "tx fee: ", txfeePer, txfee

          for a in toAddrs[0:-1]:
            if PerfectFractions:
              outp[str(a)] = str(amtPer/Decimal(BTC))
            else:
              outp[str(a)] = float(amtPer/BTC)

          a = toAddrs[-1]
          amtPer = (amount - ((len(toAddrs)-1)*amtPer)) - txfee
          # print "final amt: ", amtPer
          if PerfectFractions:
              outp[str(a)] = str(amtPer/BTC)
          else:
              outp[str(a)] = float(amtPer/BTC)

          totalOutputs = sum([Decimal(x) for x in outp.values()])
          assert(totalOutputs < amount)
          txn = node.createrawtransaction(inp, outp)
          if kwargs.get("sendtx",True):
              #print time.strftime('%X %x %Z')
              try:
                  s = str(txn)
                  # print "tx len: ", len(binascii.unhexlify(s))
                  signedtxn = node.signrawtransaction(s)
                  txLen = len(binascii.unhexlify(signedtxn["hex"]))  # Get the actual transaction size for better tx fee estimation the next time around
              finally:
                  #print time.strftime('%X %x %Z')
                  pass

              if signedtxn["complete"]:
                  try:
                      txid = node.sendrawtransaction(signedtxn["hex"],True)  # In the unit tests, we'll just allow high fees
                      return (txn,inp,outp,txid)
                  except JSONRPCException as e:
                      tmp = e.error["message"]
                      (code, msg) = tmp.split(":")
                      if code == 64: raise # bad transaction
                      # print tmp
                      if e.error["code"] == -26:  # insufficient priority
                          txfeePer = txfeePer * 2
                          print(str(e))
                          pdb.set_trace()
                          print("Insufficient priority, raising tx fee per byte to: ", txfeePer)
                          continue
                      else:
                          raise
              else:
                  for err in signedtxn["errors"]:
                      print(err["error"])
          else:
              return (txn,inp,outp,txid)
    finally:
      decimal.getcontext().prec = decContext

def assert_not_equal(thing1, thing2):
    if thing1 == thing2:
        raise AssertionError("%s != %s"%(str(thing1),str(thing2)))

def assert_equal(thing1, thing2):
    if thing1 != thing2:
        raise AssertionError("%s != %s"%(str(thing1),str(thing2)))

def assert_greater_than(thing1, thing2):
    if thing1 <= thing2:
        raise AssertionError("%s <= %s"%(str(thing1),str(thing2)))

# MVF-BU begin
def assert_less_than_equal(thing1, thing2):
    if thing1 > thing2:
        raise AssertionError("%s > %s"%(str(thing1),str(thing2)))
# MVF-BU end

def assert_raises(exc, fun, *args, **kwds):
    try:
        fun(*args, **kwds)
    except exc:
        pass
    except Exception as e:
        raise AssertionError("Unexpected exception raised: "+type(e).__name__)
    else:
        raise AssertionError("No exception raised")

def assert_is_hex_string(string):
    try:
        int(string, 16)
    except Exception as e:
        raise AssertionError(
            "Couldn't interpret %r as hexadecimal; raised: %s" % (string, e))

def assert_is_hash_string(string, length=64):
    if not isinstance(string, str):
        raise AssertionError("Expected a string, got type %r" % type(string))
    elif length and len(string) != length:
        raise AssertionError(
            "String of length %d expected; got %d" % (length, len(string)))
    elif not re.match('[abcdef0-9]+$', string):
        raise AssertionError(
            "String %r contains invalid characters for a hash." % string)

def assert_array_result(object_array, to_match, expected, should_not_find = False):
    """
        Pass in array of JSON objects, a dictionary with key/value pairs
        to match against, and another dictionary with expected key/value
        pairs.
        If the should_not_find flag is true, to_match should not be found
        in object_array
        """
    if should_not_find == True:
        assert_equal(expected, { })
    num_matched = 0
    for item in object_array:
        all_match = True
        for key,value in to_match.items():
            if item[key] != value:
                all_match = False
        if not all_match:
            continue
        elif should_not_find == True:
            num_matched = num_matched+1
        for key,value in expected.items():
            if item[key] != value:
                raise AssertionError("%s : expected %s=%s"%(str(item), str(key), str(value)))
            num_matched = num_matched+1
    if num_matched == 0 and should_not_find != True:
        raise AssertionError("No objects matched %s"%(str(to_match)))
    if num_matched > 0 and should_not_find == True:
        raise AssertionError("Objects were found %s"%(str(to_match)))

def satoshi_round(amount):
    return Decimal(amount).quantize(Decimal('0.00000001'), rounding=ROUND_DOWN)

# Helper to create at least "count" utxos
# Pass in a fee that is sufficient for relay and mining new transactions.
def create_confirmed_utxos(fee, node, count):
    node.generate(int(0.5*count)+101)
    utxos = node.listunspent()
    iterations = count - len(utxos)
    addr1 = node.getnewaddress()
    addr2 = node.getnewaddress()
    if iterations <= 0:
        return utxos
    for i in range(iterations):
        t = utxos.pop()
        inputs = []
        inputs.append({ "txid" : t["txid"], "vout" : t["vout"]})
        outputs = {}
        send_value = t['amount'] - fee
        outputs[addr1] = satoshi_round(send_value/2)
        outputs[addr2] = satoshi_round(send_value/2)
        raw_tx = node.createrawtransaction(inputs, outputs)
        signed_tx = node.signrawtransaction(raw_tx)["hex"]
        txid = node.sendrawtransaction(signed_tx)

    while (node.getmempoolinfo()['size'] > 0):
        node.generate(1)

    utxos = node.listunspent()
    assert(len(utxos) >= count)
    return utxos

# Create large OP_RETURN txouts that can be appended to a transaction
# to make it large (helper for constructing large transactions).
def gen_return_txouts():
    # Some pre-processing to create a bunch of OP_RETURN txouts to insert into transactions we create
    # So we have big transactions (and therefore can't fit very many into each block)
    # create one script_pubkey
    script_pubkey = "6a4d0200" #OP_RETURN OP_PUSH2 512 bytes
    for i in range (512):
        script_pubkey = script_pubkey + "01"
    # concatenate 128 txouts of above script_pubkey which we'll insert before the txout for change
    txouts = "81"
    for k in range(128):
        # add txout value
        txouts = txouts + "0000000000000000"
        # add length of script_pubkey
        txouts = txouts + "fd0402"
        # add script_pubkey
        txouts = txouts + script_pubkey
    return txouts

def create_tx(node, coinbase, to_address, amount):
    inputs = [{ "txid" : coinbase, "vout" : 0}]
    outputs = { to_address : amount }
    rawtx = node.createrawtransaction(inputs, outputs)
    signresult = node.signrawtransaction(rawtx)
    assert_equal(signresult["complete"], True)
    return signresult["hex"]

# Create a spend of each passed-in utxo, splicing in "txouts" to each raw
# transaction to make it large.  See gen_return_txouts() above.
def create_lots_of_big_transactions(node, txouts, utxos, fee):
    addr = node.getnewaddress()
    txids = []
    for i in range(len(utxos)):
        t = utxos.pop()
        inputs = []
        inputs.append({ "txid" : t["txid"], "vout" : t["vout"]})
        outputs = {}
        send_value = t['amount'] - fee
        outputs[addr] = satoshi_round(send_value)
        rawtx = node.createrawtransaction(inputs, outputs)
        newtx = rawtx[0:92]
        newtx = newtx + txouts
        newtx = newtx + rawtx[94:]
        signresult = node.signrawtransaction(newtx, None, None, "NONE")
        txid = node.sendrawtransaction(signresult["hex"], True)
        txids.append(txid)
    return txids

def get_bip9_status(node, key):
    info = node.getblockchaininfo()
    return info['bip9_softforks'][key]


text:
module TZInfo
  module Definitions
    module Asia
      module Ujung_Pandang
        include TimezoneDefinition

        linked_timezone 'Asia/Ujung_Pandang', 'Asia/Makassar'
      end
    end
  end
end


text:
from .. import celery

@celery.task
def minus(x, y):
    return x - y


text:
package idemix

import (
	"io"

	math "github.com/IBM/mathlib"
	"github.com/pkg/errors"
)

// NewSignature creates a new idemix pseudonym signature
func (i *Idemix) NewNymSignature(sk *math.Zr, Nym *math.G1, RNym *math.Zr, ipk *IssuerPublicKey, msg []byte, rng io.Reader, tr Translator) (*NymSignature, error) {
	return newNymSignature(sk, Nym, RNym, ipk, msg, rng, i.Curve, tr)
}

func newNymSignature(sk *math.Zr, Nym *math.G1, RNym *math.Zr, ipk *IssuerPublicKey, msg []byte, rng io.Reader, curve *math.Curve, tr Translator) (*NymSignature, error) {
	// Validate inputs
	if sk == nil || Nym == nil || RNym == nil || ipk == nil || rng == nil {
		return nil, errors.Errorf("cannot create NymSignature: received nil input")
	}

	Nonce := curve.NewRandomZr(rng)

	HRand, err := tr.G1FromProto(ipk.HRand)
	if err != nil {
		return nil, err
	}

	HSk, err := tr.G1FromProto(ipk.HSk)
	if err != nil {
		return nil, err
	}

	// The rest of this function constructs the non-interactive zero knowledge proof proving that
	// the signer 'owns' this pseudonym, i.e., it knows the secret key and randomness on which it is based.
	// Recall that (Nym,RNym) is the output of MakeNym. Therefore, Nym = h_{sk}^sk \cdot h_r^r

	// Sample the randomness needed for the proof
	rSk := curve.NewRandomZr(rng)
	rRNym := curve.NewRandomZr(rng)

	// Step 1: First message (t-values)
	t := HSk.Mul2(rSk, HRand, rRNym) // t = h_{sk}^{r_sk} \cdot h_r^{r_{RNym}

	// Step 2: Compute the Fiat-Shamir hash, forming the challenge of the ZKP.
	// proofData will hold the data being hashed, it consists of:
	// - the signature label
	// - 2 elements of G1 each taking 2*math.FieldBytes+1 bytes
	// - one bigint (hash of the issuer public key) of length math.FieldBytes
	// - disclosed attributes
	// - message being signed
	proofData := make([]byte, len([]byte(signLabel))+2*(2*curve.FieldBytes+1)+curve.FieldBytes+len(msg))
	index := 0
	index = appendBytesString(proofData, index, signLabel)
	index = appendBytesG1(proofData, index, t)
	index = appendBytesG1(proofData, index, Nym)
	copy(proofData[index:], ipk.Hash)
	index = index + curve.FieldBytes
	copy(proofData[index:], msg)
	c := curve.HashToZr(proofData)
	// combine the previous hash and the nonce and hash again to compute the final Fiat-Shamir value 'ProofC'
	index = 0
	proofData = proofData[:2*curve.FieldBytes]
	index = appendBytesBig(proofData, index, c)
	index = appendBytesBig(proofData, index, Nonce)
	ProofC := curve.HashToZr(proofData)

	// Step 3: reply to the challenge message (s-values)
	ProofSSk := curve.ModAdd(rSk, curve.ModMul(ProofC, sk, curve.GroupOrder), curve.GroupOrder)       // s_{sk} = r_{sk} + C \cdot sk
	ProofSRNym := curve.ModAdd(rRNym, curve.ModMul(ProofC, RNym, curve.GroupOrder), curve.GroupOrder) // s_{RNym} = r_{RNym} + C \cdot RNym

	// The signature consists of the Fiat-Shamir hash (ProofC), the s-values (ProofSSk, ProofSRNym), and the nonce.
	return &NymSignature{
		ProofC:     ProofC.Bytes(),
		ProofSSk:   ProofSSk.Bytes(),
		ProofSRNym: ProofSRNym.Bytes(),
		Nonce:      Nonce.Bytes()}, nil
}

// Ver verifies an idemix NymSignature
func (sig *NymSignature) Ver(nym *math.G1, ipk *IssuerPublicKey, msg []byte, curve *math.Curve, tr Translator) error {
	ProofC := curve.NewZrFromBytes(sig.GetProofC())
	ProofSSk := curve.NewZrFromBytes(sig.GetProofSSk())
	ProofSRNym := curve.NewZrFromBytes(sig.GetProofSRNym())
	Nonce := curve.NewZrFromBytes(sig.GetNonce())

	HRand, err := tr.G1FromProto(ipk.HRand)
	if err != nil {
		return err
	}

	HSk, err := tr.G1FromProto(ipk.HSk)
	if err != nil {
		return err
	}

	// Verify Proof

	// Recompute t-values using s-values
	t := HSk.Mul2(ProofSSk, HRand, ProofSRNym)
	t.Sub(nym.Mul(ProofC)) // t = h_{sk}^{s_{sk} \ cdot h_r^{s_{RNym}

	// Recompute challenge
	proofData := make([]byte, len([]byte(signLabel))+2*(2*curve.FieldBytes+1)+curve.FieldBytes+len(msg))
	index := 0
	index = appendBytesString(proofData, index, signLabel)
	index = appendBytesG1(proofData, index, t)
	index = appendBytesG1(proofData, index, nym)
	copy(proofData[index:], ipk.Hash)
	index = index + curve.FieldBytes
	copy(proofData[index:], msg)
	c := curve.HashToZr(proofData)
	index = 0
	proofData = proofData[:2*curve.FieldBytes]
	index = appendBytesBig(proofData, index, c)
	index = appendBytesBig(proofData, index, Nonce)

	if !ProofC.Equals(curve.HashToZr(proofData)) {
		return errors.Errorf("pseudonym signature invalid: zero-knowledge proof is invalid")
	}

	return nil
}


text:
package com.mkyong.customer.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.db.MySQLAccessSec;
import com.model.UploadedFile;
import com.utils.FileOperateUtil;

public class FileDownloadController extends SimpleFormController {

	public FileDownloadController(){
		setCommandClass(UploadedFile.class);
		setCommandName("downloadFile");
	}

	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command,
			BindException errors) throws Exception {

			ModelAndView mv = new ModelAndView();
			  UploadedFile downloadFile = (UploadedFile)command;

			  System.out.println("begin downloading.....");
				 String contentType = "application/octet-stream";
				//String type = request.getParameter("type");
				 //String reName = request.getParameter("filename");
				 String type = downloadFile.getType();
				 String reName = downloadFile.getFilename();
				 String realName = reName.substring(reName.indexOf("_")+1,reName.length());

				 System.out.println("type:"+type);
				 System.out.println("reName:"+reName);
				 System.out.println("realName:"+realName);

				 FileOperateUtil.download(request, response, type+"\\"+reName, contentType,realName);

//		        if(type.length()>1){
//		        	mv = new ModelAndView(new RedirectView("activityList.htm"),map);
//					 //strView = "activityList";
//				 }else{
//			        	mv = new ModelAndView(new RedirectView("sharedResources.htm"),map);
//					 //strView = "activityList";
//				 }
				 mv = null;
			     return mv;
		}

		@Override
		protected Map referenceData(HttpServletRequest request, Object command,
				Errors errors) throws Exception {
			Map referenceData = new HashMap();

			 String type = request.getParameter("type");
			 String tempType = type.substring(0,type.indexOf("_")+1);
			// System.out.println((String)request.getParameter("action"));
			 String action = (String)request.getParameter("action");
			// String action = new String(request.getParameter("action").getBytes("iso-8859-1"),"utf-8");
			 List<UploadedFile> uploadedfilelist = new ArrayList<UploadedFile>();

			 MySQLAccessSec mysqlDB = new MySQLAccessSec();
				try {
					uploadedfilelist = mysqlDB.readUploadedFileList(type.substring(type.indexOf("_")+1, type.length()));

				} catch (Exception e) {
					e.printStackTrace();
				}

				if (uploadedfilelist.size()<=0){
					referenceData.put("IsShow", false);
				}else{
					referenceData.put("IsShow", true);
				}
				// request.setAttribute(name, o);
			String strTitle = action ;

			referenceData.put("type", type );
			referenceData.put("tempType", tempType);
			referenceData.put("strTitle", strTitle );
			referenceData.put("uploadedfilelist", uploadedfilelist);

			 //System.out.println("下载type:"+type);
			// mv = new ModelAndView("download");
		    return referenceData;

		}

//		@Override
//		protected ModelAndView onSubmit(HttpServletRequest request,
//				HttpServletResponse response, Object command,
//				BindException errors) throws Exception {
//			 Map<String, Object> map = new HashMap<String, Object>();
//
//		        // 别名
//		        String[] alaises = ServletRequestUtils.getStringParameters(request,
//		                "alais");
//
//		        String[] params = new String[] { "alais" };
//		        Map<String, Object[]> values = new HashMap<String, Object[]>();
//		        values.put("alais", alaises);
//
//		        List<Map<String, Object>> result = FileOperateUtil.upload(request,
//		                params, values);
//
//		        map.put("result", result);
//
//		        return new ModelAndView("upload", map);
//		}

	    /**
	     * 下载

	     */

//	    public ModelAndView download(HttpServletRequest request,
//	            HttpServletResponse response) throws Exception {
//
//	        String storeName = "201205051340364510870879724.zip";
//	        String realName = "Java设计模式.zip";
//	        String contentType = "application/octet-stream";
//
//	        FileOperateUtil.download(request, response, storeName, contentType,
//	                realName);
//
//	        return null;
//	    }
//
}


text:
/*
 * Copyright 2001-2006 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/*
 * $Id: KeyCall.java,v 1.7 2006/06/19 19:49:04 spericas Exp $
 */

package com.sun.org.apache.xalan.internal.xsltc.compiler;

import java.util.Vector;

import com.sun.org.apache.bcel.internal.generic.ALOAD;
import com.sun.org.apache.bcel.internal.generic.ASTORE;
import com.sun.org.apache.bcel.internal.generic.BranchHandle;
import com.sun.org.apache.bcel.internal.generic.ConstantPoolGen;
import com.sun.org.apache.bcel.internal.generic.GOTO;
import com.sun.org.apache.bcel.internal.generic.IFGT;
import com.sun.org.apache.bcel.internal.generic.INVOKEINTERFACE;
import com.sun.org.apache.bcel.internal.generic.INVOKESPECIAL;
import com.sun.org.apache.bcel.internal.generic.INVOKEVIRTUAL;
import com.sun.org.apache.bcel.internal.generic.InstructionHandle;
import com.sun.org.apache.bcel.internal.generic.InstructionList;
import com.sun.org.apache.bcel.internal.generic.LocalVariableGen;
import com.sun.org.apache.bcel.internal.generic.NEW;
import com.sun.org.apache.bcel.internal.generic.PUSH;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.ClassGenerator;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.MethodGenerator;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.StringType;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.Type;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.TypeCheckError;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.Util;

/**
 * @author Morten Jorgensen
 * @author Santiago Pericas-Geertsen
 */
final class KeyCall extends FunctionCall {

    /**
     * The name of the key.
     */
    private Expression _name;

    /**
     * The value to look up in the key/index.
     */
    private Expression _value;

    /**
     * The value's data type.
     */
    private Type _valueType; // The value's data type

    /**
     * Expanded qname when name is literal.
     */
    private QName _resolvedQName = null;

    /**
     * Get the parameters passed to function:
     *   key(String name, String value)
     *   key(String name, NodeSet value)
     * The 'arguments' vector should contain two parameters for key() calls,
     * one holding the key name and one holding the value(s) to look up. The
     * vector has only one parameter for id() calls (the key name is always
     * "##id" for id() calls).
     *
     * @param fname The function name (should be 'key' or 'id')
     * @param arguments A vector containing the arguments the the function
     */
    public KeyCall(QName fname, Vector arguments) {
        super(fname, arguments);
        switch(argumentCount()) {
        case 1:
            _name = null;
            _value = argument(0);
            break;
        case 2:
            _name = argument(0);
            _value = argument(1);
            break;
        default:
            _name = _value = null;
            break;
        }
    }

     /**
     * If this call to key() is in a top-level element like  another variable
     * or param, add a dependency between that top-level element and the
     * referenced key. For example,
     *
     *   <xsl:key name="x" .../>
     *   <xsl:variable name="y" select="key('x', 1)"/>
     *
     * and assuming this class represents "key('x', 1)", add a reference
     * between variable y and key x. Note that if 'x' is unknown statically
     * in key('x', 1), there's nothing we can do at this point.
     */
    public void addParentDependency() {
        // If name unknown statically, there's nothing we can do
        if (_resolvedQName == null) return;

        SyntaxTreeNode node = this;
        while (node != null && node instanceof TopLevelElement == false) {
            node = node.getParent();
        }

        TopLevelElement parent = (TopLevelElement) node;
        if (parent != null) {
            parent.addDependency(getSymbolTable().getKey(_resolvedQName));
        }
    }

   /**
     * Type check the parameters for the id() or key() function.
     * The index name (for key() call only) must be a string or convertable
     * to a string, and the lookup-value must be a string or a node-set.
     * @param stable The parser's symbol table
     * @throws TypeCheckError When the parameters have illegal type
     */
    public Type typeCheck(SymbolTable stable) throws TypeCheckError {
        final Type returnType = super.typeCheck(stable);

        // Run type check on the key name (first argument) - must be a string,
        // and if it is not it must be converted to one using string() rules.
        if (_name != null) {
            final Type nameType = _name.typeCheck(stable);

            if (_name instanceof LiteralExpr) {
                final LiteralExpr literal = (LiteralExpr) _name;
                _resolvedQName =
                    getParser().getQNameIgnoreDefaultNs(literal.getValue());
            }
            else if (nameType instanceof StringType == false) {
                _name = new CastExpr(_name, Type.String);
            }
        }

        // Run type check on the value for this key. This value can be of
        // any data type, so this should never cause any type-check errors.
        // If the value is a reference, then we have to defer the decision
        // of how to process it until run-time.
        // If the value is known not to be a node-set, then it should be
        // converted to a string before the lookup is done. If the value is
        // known to be a node-set then this process (convert to string, then
        // do lookup) should be applied to every node in the set, and the
        // result from all lookups should be added to the resulting node-set.
        _valueType = _value.typeCheck(stable);

        if (_valueType != Type.NodeSet
                && _valueType != Type.Reference
                && _valueType != Type.String) {
            _value = new CastExpr(_value, Type.String);
            _valueType = _value.typeCheck(stable);
        }

        // If in a top-level element, create dependency to the referenced key
        addParentDependency();

        return returnType;
    }

    /**
     * This method is called when the constructor is compiled in
     * Stylesheet.compileConstructor() and not as the syntax tree is traversed.
     * <p>This method will generate byte code that produces an iterator
     * for the nodes in the node set for the key or id function call.
     * @param classGen The Java class generator
     * @param methodGen The method generator
     */
    public void translate(ClassGenerator classGen,
                          MethodGenerator methodGen) {
        final ConstantPoolGen cpg = classGen.getConstantPool();
        final InstructionList il = methodGen.getInstructionList();

        // Returns the KeyIndex object of a given name
        final int getKeyIndex = cpg.addMethodref(TRANSLET_CLASS,
                                                 "getKeyIndex",
                                                 "(Ljava/lang/String;)"+
                                                 KEY_INDEX_SIG);

        // KeyIndex.setDom(Dom, node) => void
        final int keyDom = cpg.addMethodref(KEY_INDEX_CLASS,
                                            "setDom",
                                            "(" + DOM_INTF_SIG + "I)V");

        // Initialises a KeyIndex to return nodes with specific values
        final int getKeyIterator =
                        cpg.addMethodref(KEY_INDEX_CLASS,
                                         "getKeyIndexIterator",
                                         "(" + _valueType.toSignature() + "Z)"
                                             + KEY_INDEX_ITERATOR_SIG);

        // Initialise the index specified in the first parameter of key()
        il.append(classGen.loadTranslet());
        if (_name == null) {
            il.append(new PUSH(cpg,"##id"));
        } else if (_resolvedQName != null) {
            il.append(new PUSH(cpg, _resolvedQName.toString()));
        } else {
            _name.translate(classGen, methodGen);
        }

        // Generate following byte code:
        //
        //   KeyIndex ki = translet.getKeyIndex(_name)
        //   ki.setDom(translet.dom);
        //   ki.getKeyIndexIterator(_value, true)  - for key()
        //        OR
        //   ki.getKeyIndexIterator(_value, false)  - for id()
        il.append(new INVOKEVIRTUAL(getKeyIndex));
        il.append(DUP);
        il.append(methodGen.loadDOM());
        il.append(methodGen.loadCurrentNode());
        il.append(new INVOKEVIRTUAL(keyDom));

        _value.translate(classGen, methodGen);
        il.append((_name != null) ? ICONST_1: ICONST_0);
        il.append(new INVOKEVIRTUAL(getKeyIterator));
    }
}


text:
#include "com/centreon/broker/storage/stream.hh"

#include <cfloat>
#include <cmath>
#include <cstdlib>
#include <cstring>

#include "com/centreon/broker/exceptions/shutdown.hh"
#include "com/centreon/broker/io/events.hh"
#include "com/centreon/broker/log_v2.hh"
#include "com/centreon/broker/multiplexing/publisher.hh"
#include "com/centreon/broker/neb/host.hh"
#include "com/centreon/broker/neb/instance.hh"
#include "com/centreon/broker/neb/internal.hh"
#include "com/centreon/broker/neb/service_status.hh"
#include "com/centreon/broker/storage/conflict_manager.hh"
#include "com/centreon/broker/storage/exceptions/perfdata.hh"
#include "com/centreon/broker/storage/index_mapping.hh"
#include "com/centreon/broker/storage/metric.hh"
#include "com/centreon/broker/storage/parser.hh"
#include "com/centreon/broker/storage/perfdata.hh"
#include "com/centreon/broker/storage/remove_graph.hh"
#include "com/centreon/broker/storage/status.hh"
#include "com/centreon/exceptions/msg_fmt.hh"

using namespace com::centreon::exceptions;
using namespace com::centreon::broker;
using namespace com::centreon::broker::misc;
using namespace com::centreon::broker::storage;

/**
 *  Constructor.
 *
 *  @param[in] db_cfg                  Database configuration.
 *  @param[in] rrd_len                 RRD length.
 *  @param[in] interval_length         Length in seconds of a time unit.
 *  @param[in] rebuild_check_interval  How often the stream must check
 *                                     for graph rebuild.
 *  @param[in] store_in_db             Should we insert data in
 *                                     data_bin ?
 *  @param[in] insert_in_index_data    Create entries in index_data or
 *                                     not.
 */
stream::stream(database_config const& dbcfg,
               uint32_t rrd_len,
               uint32_t interval_length,
               uint32_t rebuild_check_interval,
               bool store_in_db)
    : io::stream("storage"),
      _pending_events(0),
      _rebuilder(dbcfg,
                 rebuild_check_interval,
                 rrd_len ? rrd_len : 15552000,
                 interval_length),
      _stopped(false) {
  log_v2::sql()->debug("storage stream instanciation");
  if (!rrd_len)
    rrd_len = 15552000;

  if (!conflict_manager::init_storage(store_in_db, rrd_len, interval_length,
                                      dbcfg.get_queries_per_transaction())) {
    log_v2::sql()->error("storage stream instanciation failed");
    throw msg_fmt(
        "storage: Unable to initialize the storage connection to the database");
  }
}

int32_t stream::stop() {
  // Stop cleanup thread.
  int32_t retval =
      conflict_manager::instance().unload(conflict_manager::storage);
  log_v2::core()->info("storage stream stopped with {} acknowledged events",
                       retval);
  _stopped = true;
  return retval;
}

/**
 *  Destructor.
 */
stream::~stream() {
  assert(_stopped);
  // Stop cleanup thread.
  log_v2::sql()->debug("storage: stream destruction");
}

/**
 *  Flush the stream.
 *
 *  @return Number of events acknowledged.
 */
int32_t stream::flush() {
  int32_t retval =
      conflict_manager::instance().get_acks(conflict_manager::storage);
  _pending_events -= retval;

  // Event acknowledgement.
  log_v2::perfdata()->debug("storage: {} events have not yet been acknowledged",
                            _pending_events);
  return retval;
}

/**
 *  Read from the datbase.
 *
 *  @param[out] d         Cleared.
 *  @param[in]  deadline  Timeout.
 *
 *  @return This method will throw.
 */
bool stream::read(std::shared_ptr<io::data>& d, time_t deadline) {
  (void)deadline;
  d.reset();
  throw broker::exceptions::shutdown("cannot read from a storage stream");
  return true;
}

/**
 *  Get endpoint statistics.
 *
 *  @param[out] tree Output tree.
 */
void stream::statistics(nlohmann::json& tree) const {
  std::lock_guard<std::mutex> lock(_statusm);
  if (!_status.empty())
    tree["status"] = _status;
  tree["pending events"] = _pending_events;
}

/**
 *  Write an event.
 *
 *  @param[in] data Event pointer.
 *
 *  @return Number of events acknowledged.
 */
int32_t stream::write(std::shared_ptr<io::data> const& data) {
  ++_pending_events;

  assert(data);

  int32_t ack =
      conflict_manager::instance().send_event(conflict_manager::storage, data);
  _pending_events -= ack;
  return ack;
}

/**************************************
 *                                     *
 *           Private Methods           *
 *                                     *
 **************************************/

/**
 *  Update status of endpoint.
 *
 *  @param[in] status New status.
 */
void stream::_update_status(std::string const& status) {
  std::lock_guard<std::mutex> lock(_statusm);
  _status = status;
}


text:
#ifndef _SYS_PROCFS_H
# error "Never include <bits/procfs.h> directly; use <sys/procfs.h> instead."
#endif

#include <sgidefs.h>

/* ELF register definitions */
#define ELF_NGREG	45
#define ELF_NFPREG	33

#if _MIPS_SIM == _ABIN32
__extension__ typedef unsigned long long elf_greg_t;
#else
typedef unsigned long elf_greg_t;
#endif
typedef elf_greg_t elf_gregset_t[ELF_NGREG];

typedef double elf_fpreg_t;
typedef elf_fpreg_t elf_fpregset_t[ELF_NFPREG];


text:
<!DOCTYPE html>
<html lang="en" ng-app="myApp">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <link rel="icon" type="image/png" href="theme/images/favicon.ico" sizes="32x32" />
    <title>My AngularJS App</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="bower_components/html5-boilerplate/dist/css/normalize.css">
    <link rel="stylesheet" href="bower_components/html5-boilerplate/dist/css/main.css">
    <link rel="stylesheet" href="bower_components/ideal-image-slider/ideal-image-slider.css">
    <link rel="stylesheet" href="bower_components/ideal-image-slider/themes/default/default.css">
    <link rel="stylesheet" href="bower_components/sweetalert/dist/sweetalert.css">
    <link rel="stylesheet" href="theme/css/bootstrap.min.css">
    <link rel="stylesheet" href="theme/css/app.css">
    <link rel="stylesheet" href="theme/css/ladda.min.css">
    <link rel="stylesheet" href="theme/css/video-js.css">
</head>

<body>
    <div ng-view></div>
    <script src="bower_components/angular/angular.min.js"></script>
    <script src="bower_components/angular-route/angular-route.min.js"></script>
    <script src="bower_components/ideal-image-slider/ideal-image-slider.min.js"></script>
    <script src="bower_components/angular-base64/angular-base64.min.js"></script>
    <script src="bower_components/ng-file-upload/ng-file-upload.min.js"></script>
    <script src="bower_components/sweetalert/dist/sweetalert.min.js"></script>
    <script src="js/lib/jquery-2.0.1.min.js"></script>
    <script src="js/lib/bootstrap/3.3.4/bootstrap.min.js"></script>
    <script src="js/lib/firebase/2.0.4/firebase.js"></script>
    <script src="js/lib/angularfire/0.9.0/angularfire.min.js"></script>
    <script src="js/lib/simple-login/1.6.2/firebase-simple-login.js"></script>
    <script src="js/lib/spin.min.js"></script>
    <script src="js/lib/ladda.min.js"></script>
    <script src="js/lib/video.js"></script>
    <script src="js/lib/notify.min.js"></script>
    <script src="js/app.js"></script>
    <script src="js/controllers/register.js"></script>
    <script src="js/controllers/forgotPwd.js"></script>
    <script src="js/controllers/home.js"></script>
    <script src="js/controllers/welcome.js"></script>
    <script src="js/controllers/header.js"></script>
    <script src="js/controllers/addPost.js"></script>
    <script src="js/controllers/addImage.js"></script>
    <script src="js/controllers/profile.js"></script>
    <script src="js/controllers/videos.js"></script>
</body>

</html>


text:
package net.chriswareham.mvc;

import java.util.List;

/**
 * This interface provides methods to be implemented by classes that serialise
 * an object to comma separated values.
 *
 * @author Chris Wareham
 * @param <T> the type of objects to serialise
 */
public interface CsvSerialiser<T> {
    /**
     * Get the header for the comma separated values.
     *
     * @return the header for the comma separated values
     */
    List<String> getHeaders();

    /**
     * Serialise an object to comma separated values.
     *
     * @param obj the object to serialise
     * @return comma separated values
     */
    List<String> serialise(T obj);
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:drawable="@color/newhousebuttoncheck" android:state_checked="true"></item>
    <item android:drawable="@color/newhousebuttonuncheck" android:state_checked="false"></item>
</selector>


text:
Different target boards have different layouts for GPIO, LEDs, and more. Often,
this requires that configurations be specified per-target. In this example, we
will be looking at how to configure the LEDs for two different targets. First,
let's start by modifying our `config.exs` to include configs for each target.

```elixir
# config/config.exs

import_config "#{Mix.Project.config[:target]}.exs"
```

This will load a different Mix config for each target. Let's say we plan to
support targets `rpi3` and `bbb`. These target devices have different numbers of
user-controlled LEDs and we want each to blink all of its LEDs. The
configuration files would look like this:

```elixir
# config/rpi3.exs

config :blinky, led_list: [ :green ]
config :nerves_leds, names: [ green: "led0" ]
```

```elixir
# config/bbb.exs

config :blinky, led_list: [ :led0, :led1, :led2, :led3 ]

config :nerves_leds, names: [
  led0: "beaglebone:green:usr0",
  led1: "beaglebone:green:usr1",
  led2: "beaglebone:green:usr2",
  led3: "beaglebone:green:usr3"
]
```

## Root Filesystem Overlays

Sometimes, you want to ship additional files and configurations with your
firmware. This is done by telling the firmware assembler where to find a
directory to use as an overlay on the root mount point:

```elixir
# config/config.exs

config :nerves, :firmware,
  rootfs_overlay: "rootfs_overlay"
```

This declares that the contents of the folder at `rootfs_overlay` in your
project root directory will be merged into the root filesystem when `mix
firmware` is called. You can also specify a different `rootfs_overlay` for each
target, as shown in the previous section.

### Overwriting Files in the Root Filesystem

Any files in the `rootfs_overlay` directory will overwrite those present in the
underlying filesystem. This can be useful if you want to change the contents of
included files in the underlying Nerves system. Let's say, for example, that you
want to change the behavior of `erlinit`. You can include your own
`erlinit.config`:

```bash
# rootfs_overlay/etc/erlinit.config

# Uncomment to hang the board rather than rebooting when Erlang exits
#--hang-on-exit

# Enable UTF-8 filename handling in Erlang and custom inet configuration
-e LANG=en_US.UTF-8;LANGUAGE=en;ERL_INETRC=/etc/erl_inetrc;ERL_CRASH_DUMP=/root/crash.dump

# Mount the application partition
-m /dev/mmcblk0p3:/root:ext4::

# Erlang release search path
-r /srv/erlang

# Hostname
-d "/usr/bin/boardid -b bbb -n 4"
-n nerves-%.4s
```

It is important to note that the entire file is replaced when you apply an
overlay, rather than merging the contents. Therefore, you should first obtain
and modify the original file. A trick for doing this is to expand the
`rootfs.squashfs`. You can do this using `unsquashfs`:

```bash
unsquashfs ~/.nerves/artifacts/<cached_system_name>/images/rootfs.squashfs
```

It will be expanded into the current directory under `squashfs-root`

### Overwriting Files in the Boot Partition

Different targets have different boot partition contents. To overwrite files in
the boot partition, you will need to use your own `fwup.conf` file:

#### Copy `fwup.conf` to Your `config/` Directory

```bash
# Locate the fwup.conf files available in your deps directory
find deps -name fwup.conf
# Copy the one that matches your target to the config directory.
cp deps/nerves_system_rpi0/fwup.conf config/
# Also copy cmdline.txt as you'll need it below.
cp deps/nerves_system_rpi0/cmdline.txt config/
```

#### Configure Your System to Use the Copied `fwup.conf`

```elixir
# config/config.exs

config :nerves, :firmware,
  fwup_conf: "config/fwup.conf"
```

#### Make Your Changes

In your included `fwup.conf` file, you can use absolute paths or environment
variables to point to the location of included files.

Let's say you have a Raspberry Pi and you want to change the contents of the
`cmdline.txt` file. You can do this by editing the `fwup.conf` as follows:

```bash
# fwup.conf

file-resource cmdline.txt {
    host-path = "${NERVES_APP}/config/cmdline.txt"
}
```

You can use the `NERVES_APP` environment variable to point to the root of your
Elixir app. This variable is automatically managed for you by
`nerves_bootstrap`.

### Device Tree Overlays

To add a device tree overlay for your hardware, first define a file-resource for
the dtbo file inside `fwup.conf`. As with other file overlays, you can use
absolute paths or environment variables to point to the file location. For
example, to add support for a Bosch BMP280 I2C sensor on a Raspberry Pi, your new
file resource will be:

```bash
# fwup.conf

file-resource i2c-sensor.dtbo {
    host-path = "${NERVES_SYSTEM}/images/rpi-firmware/overlays/i2c-sensor.dtbo"
}
```

Next you need make sure the dtbo file is written to the destination media on
build and update of your firmware. Add a new `on-resource` declaration for each
of the three firmware tasks:

```bash
# fwup.conf

task complete{
    # ... look for where `on-resource` directives are already defined and add:
    on-resource i2c-sensor.dtbo {
        fat_write(${BOOT_A_PART_OFFSET}, "overlays/i2c-sensor.dtbo")
    }
}

task upgrade.a {
    # ...
    on-resource i2c-sensor.dtbo {
        fat_write(${BOOT_A_PART_OFFSET}, "overlays/i2c-sensor.dtbo")
    }
}

task upgrade.b {
    # ...
    on-resource i2c-sensor.dtbo {
        fat_write(${BOOT_B_PART_OFFSET}, "overlays/i2c-sensor.dtbo")
    }
}
```

Note that the `BOOT_x_PART_OFFSET` variable must match the partition being
written to for each task.

In order to load your new overlay, you will need to create your own
`config.txt` and use it instead of the default. Copy `config.txt` from your
target Nerves system and place it inside your project at `config/config.txt`.

`fwup.conf` now needs to be updated to use this new file. There should already be a
`file-resource` directive for `config.txt`. Find it and change the `host-path`
to point at the new location inside you project:

```bash
# fwup.conf

file-resource config.txt {
    host-path = "${NERVES_APP}/config/config.txt"
}
```

At this point the overlay will be available to load inside `config/config.txt`
on boot. Follow the documentation for your hardware. For the Bosch BMP280 in our
example, the configuration will be:

```bash
# config.txt

dtoverlay=i2c-sensor,bmp280
```

## Partitions

Nerves firmware uses Master Boot Record (MBR) partition layout, which only
supports 4 primary partitions. By default, the root filesystem partition is
mounted in read-only mode. This prevents corruption of the root filesystem due
to "improper shutdowns". With embedded systems, it is assumed that power can be
removed from the device at any time. This could be problematic if you are
performing a write operation on the filesystem. Because the root filesystem is
read-only, we also add a read/write partition by default, called `app_data` and
mounted at `/data` (the `root` user's home directory). These settings are
defined in `etc/erlinit.config`.

```plain
 +----------------------------+
 | MBR                        |
 +----------------------------+
 | Firmware configuration data|
 | (formatted as uboot env)   |
 +----------------------------+
 | p0*: Boot A        (FAT32) |
 | zImage, bootcode.bin,      |
 | config.txt, etc.           |
 +----------------------------+
 | p0*: Boot B        (FAT32) |
 +----------------------------+
 | p1*: Rootfs A   (squashfs) |
 +----------------------------+
 | p1*: Rootfs B   (squashfs) |
 +----------------------------+
 | p2: Application     (EXT4) |
 +----------------------------+
```

More information about how the App Data partition is initialized and mounted can
be found in the documentation for `nerves_runtime` [Filesystem
Initialization](https://hexdocs.pm/nerves_runtime/readme.html#filesystem-initialization)

### Adding a Partition

You can enable and mount an additional read/write partition by modifying the
`fwup.conf` file. This strategy is typically used to define two locations where
data can be written. Let's say you want to persist some infrequently-written
configuration data and some frequently-written log data. These use-cases could
be segmented into separate partitions so that the important,
infrequently-written configuration data is not corrupted due to a loss of power
while writing the more-frequent, but less-critical, log data.

First, define a new space on the disk for the partition:

```bash
# fwup.conf

# (Sizes are in 512 byte blocks)
define(UBOOT_ENV_OFFSET, 16)
define(UBOOT_ENV_COUNT, 16)  # 8 KB

define(BOOT_A_PART_OFFSET, 63)
define(BOOT_A_PART_COUNT, 38630)
define-eval(BOOT_B_PART_OFFSET, "${BOOT_A_PART_OFFSET} + ${BOOT_A_PART_COUNT}")
define(BOOT_B_PART_COUNT, ${BOOT_A_PART_COUNT})

# Let the rootfs have room to grow up to 128 MiB and align it to the nearest 1
# MB boundary
define(ROOTFS_A_PART_OFFSET, 77324)
define(ROOTFS_A_PART_COUNT, 289044)
define-eval(ROOTFS_B_PART_OFFSET, "${ROOTFS_A_PART_OFFSET} + ${ROOTFS_A_PART_COUNT}")
define(ROOTFS_B_PART_COUNT, ${ROOTFS_A_PART_COUNT})

# Configuration partition
define-eval(CONFIG_PART_OFFSET, "${ROOTFS_B_PART_OFFSET} + ${ROOTFS_B_PART_COUNT}")
define(CONFIG_PART_COUNT, 1048576)

# Log partition
define-eval(LOG_PART_OFFSET, "${CONFIG_PART_OFFSET} + ${CONFIG_PART_COUNT}")
define(CONFIG_PART_COUNT, 1048576)

# ...
```

In this example, we are changing the default `APP_PART` data partition to
`CONFIG_PART` and adding `LOG_PART`.

Next, we change the mapping to include these two new partitions:

```bash
# fwup.conf

# ...

mbr mbr-a {
    partition 0 {
        block-offset = ${BOOT_A_PART_OFFSET}
        block-count = ${BOOT_A_PART_COUNT}
        type = 0xc # FAT32
        boot = true
    }
    partition 1 {
        block-offset = ${ROOTFS_A_PART_OFFSET}
        block-count = ${ROOTFS_A_PART_COUNT}
        type = 0x83 # Linux
    }
    partition 2 {
        block-offset = ${CONFIG_PART_OFFSET}
        block-count = ${CONFIG_PART_COUNT}
        type = 0x83 # Linux
    }
    partition 3 {
        block-offset = ${LOG_PART_OFFSET}
        block-count = ${LOG_PART_COUNT}
        type = 0x83 # Linux
    }
}

mbr mbr-b {
    partition 0 {
        block-offset = ${BOOT_B_PART_OFFSET}
        block-count = ${BOOT_B_PART_COUNT}
        type = 0xc # FAT32
        boot = true
    }
    partition 1 {
        block-offset = ${ROOTFS_B_PART_OFFSET}
        block-count = ${ROOTFS_B_PART_COUNT}
        type = 0x83 # Linux
    }
    partition 2 {
        block-offset = ${CONFIG_PART_OFFSET}
        block-count = ${CONFIG_PART_COUNT}
        type = 0x83 # Linux
    }
    partition 3 {
        block-offset = ${LOG_PART_OFFSET}
        block-count = ${LOG_PART_COUNT}
        type = 0x83 # Linux
    }
}

# ...
```

This layout defines our system as follows:

```plain
+----------------------------+
| MBR                        |
+----------------------------+
| Firmware configuration data|
| (formatted as uboot env)   |
+----------------------------+
| p0*: Boot A        (FAT32) |
| zImage, bootcode.bin,      |
| config.txt, etc.           |
+----------------------------+
| p0*: Boot B        (FAT32) |
+----------------------------+
| p1*: Rootfs A   (squashfs) |
+----------------------------+
| p1*: Rootfs B   (squashfs) |
+----------------------------+
| p2: Config          (EXT4) |
+----------------------------+
| p3: Log             (EXT4) |
+----------------------------+
```

### Mounting the Partition

Mounting your new partition can either be handled by `erlinit` or by your Elixir
application. To have `erlinit` mount the partition for you, you will need to
supply your own `erlinit.config` file to set the required `-m` option:

```bash
# Mount the configdata and logdata partitions
-m /dev/mmcblk0p3:/root:ext4::;/dev/mmcblk0p4:/mnt/log:ext4::
```

The other option is to handle it in your Elixir code. This can be useful if you
want to scan the disk for corruption and reformat or seed it. `erlinit` can only
attempt to mount the partition. You may want to see [how `nerves_runtime` does
this for the default application data
partition](https://github.com/nerves-project/nerves_runtime/blob/main/lib/nerves_runtime/init.ex),
extending it to meet your specific needs.

### Overriding erlinit.config from Mix Config

Options specified in the `erlinit.config` file can be overridden through the
project's Mix config. This can be helpful when you want to alter a couple
options without having to maintain a copy of the entire `erlinit.config`
from the system. Here is an example of how you can change the `ctty` option
from the `config/target.exs` file.

```elixir
config :nerves, :erlinit,
  ctty: "ttyAMA0"
```

Options that can only be specified once will overwrite the values specified in
the `erlinit.config` provided by the system. Options that can be specified
multiple times, such as `mount` and `env` will append to the original ones.
If an `erlinit.config` file is provided in the project's `rootfs_overlay` it
will override everything else.

The following is a list of all options that can be specified:

```elixir
[
  boot: Path.t(),
  ctty: String.t(),
  uniqueid_exec: String.t(),
  env: String.t(),
  gid: non_neg_integer(),
  graceful_shutdown_timeout: non_neg_integer(),
  hang_on_exit: boolean(),
  hang_on_fatal: boolean(),
  mount: String.t(),
  hostname_pattern: String.t(),
  pre_run_exec: String.t(),
  poweroff_on_exit: boolean(),
  poweroff_on_fatal: boolean(),
  reboot_on_fatal: boolean(),
  release_path: String.t(),
  run_on_exit: String.t(),
  alternate_exec: binary(),
  print_timing: boolean(),
  uid: non_neg_integer(),
  update_clock: boolean(),
  verbose: boolean(),
  warn_unused_tty: boolean(),
  working_directory: Path.t(),
  shutdown_report: Path.t()
]
```

See [erlinit](https://github.com/nerves-project/erlinit) for more information.

## Kernel Parameters

The `sysctl` command is used to modify kernel parameters at runtime. Nerves
automatically loads settings from `/etc/sysctl.conf` at startup when using
`nerves_runtime` `v0.11.5` or later. The format and content of
`/etc/sysctl.conf` follows that found in other Linux-based systems.

Default settings may be provided in your Nerves system. If a Nerves system uses
a recent enough version of
[`nerves_sytem_br`](https://github.com/nerves-project/nerves_system_br), it will
have a minimal `/etc/sysctl.conf` file.

You can modify the kernel parameters for your application or custom Nerves
system by copying the default `sysctl.conf` file to your `rootfs_overlay/etc`
directory and making the desired changes. Use `System.cmd/3` to run `sysctl` to
change settings after initialization.

Is something wrong?

Edit this page on GitHub


text:
package com.touwolf.mailchimp.data.condiction.types;

import com.google.gson.annotations.SerializedName;

public enum McMemberRatingOpEnum {
    @SerializedName("is")
    IS,
    @SerializedName("not")
    NOT,
    @SerializedName("greater")
    GREATER,
    @SerializedName("less")
    LESS
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>org.qoders.exception.handler</title>
<meta name="date" content="2015-06-18">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

org.qoders.exception.handler

Classes

RestExceptionControllerAdvise


text:
local _, ns = ...
local C = ns.C

if C.objectivetracker.pos_raid then
	print("[sInterface] C.objectivetracker.pos_raid is no longer supported")
end


text:
<?xml version="1.0"  encoding="ISO-8859-1"?>
<!DOCTYPE Configure PUBLIC "-//Mort Bay Consulting//DTD Configure//EN" "http://jetty.eclipse.org/configure.dtd">

<Configure class="org.eclipse.jetty.server.handler.ContextHandler">
  <Set name="contextPath">/</Set>
  <Set name="resourceBase"><SystemProperty name="jetty.home" default="."/>/root/</Set>
  <Set name="handler">
    <New class="org.eclipse.jetty.server.handler.ResourceHandler">
      <Set name="welcomeFiles">
        <Array type="String">
          <Item>index.html</Item>
        </Array>
      </Set>
      <Set name="cacheControl">max-age=3600,public</Set>
    </New>
  </Set>
</Configure>


text:
<fims-layout-card-over title="{{'Cheque clearing' | translate}}" [navigateBackTo]="['../']">

            {{column.label}}

          APPROVE
          CANCEL

            {{column.format ? column.format(row[column.name]) : row[column.name]}}

            <button mat-button mat-raised-button color="primary" [disabled]="row.state !== 'PENDING'" (click)="approveCheque(row)">
              {{ 'APPROVE' | translate}}
            </button>

            <button mat-button mat-raised-button color="warn" [disabled]="row.state !== 'PENDING'" (click)="cancelCheque(row)">
              {{ 'CANCEL' | translate}}
            </button>

</fims-layout-card-over>


text:
namespace Gu.State.Tests.Settings
{
    using System.Reflection;

    using Gu.State.Internals;

    using NUnit.Framework;

    public class MemberComparerTests
    {
        [Test]
        public void CompareSame()
        {
            var nameProperty = typeof(SettingsTypes.ComplexType).GetProperty(nameof(SettingsTypes.ComplexType.Name), BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);

            var comparer = MemberInfoComparer<PropertyInfo>.Default;
            Assert.AreEqual(true, comparer.Equals(nameProperty, nameProperty));
            Assert.AreEqual(comparer.GetHashCode(nameProperty), comparer.GetHashCode(nameProperty));
        }

        [Test]
        public void CompareDerived()
        {
            var complexNameProperty = typeof(SettingsTypes.ComplexType).GetProperty(nameof(SettingsTypes.ComplexType.Name), BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
            var derivedNameProperty = typeof(SettingsTypes.Derived).GetProperty(nameof(SettingsTypes.Derived.Name), BindingFlags.Public | BindingFlags.Instance);

            var comparer = MemberInfoComparer<PropertyInfo>.Default;
            Assert.AreEqual(true, comparer.Equals(complexNameProperty, derivedNameProperty));
            Assert.AreEqual(comparer.GetHashCode(complexNameProperty), comparer.GetHashCode(derivedNameProperty));
        }

        [Test]
        public void CompareDifferent()
        {
            var complexNameProperty = typeof(SettingsTypes.ComplexType).GetProperty(nameof(SettingsTypes.ComplexType.Name), BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
            var complexValueProperty = typeof(SettingsTypes.ComplexType).GetProperty(nameof(SettingsTypes.ComplexType.Value), BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);

            var comparer = MemberInfoComparer<PropertyInfo>.Default;
            Assert.AreEqual(false, comparer.Equals(complexNameProperty, complexValueProperty));
            Assert.AreNotEqual(comparer.GetHashCode(complexNameProperty), comparer.GetHashCode(complexValueProperty));
        }
    }
}


text:
package br.com.codigocerto.controles.sistema;

import br.com.codigocerto.modelos.ArquivoTexto;
import br.com.codigocerto.modelos.sistema.PedidoImpressao;
import br.com.codigocerto.xml.GeradorXML;
import br.com.codigocerto.xml.ParserXML;

/**
 * @author lis
 */
public class RegistroPedidoImpressao {

    String URL_XMl = "etc/impressao.xml";

    /**
     * Gerar nova instancia
     */
    public RegistroPedidoImpressao() {
    }

    /**
     * Salva as configuracoes
     * @param modelo
     * @return verdadeiro para informacoes salvas
     */
    public boolean salvar(PedidoImpressao modelo) {
        boolean salvo = false;

        try {
            GeradorXML xml = new GeradorXML(PedidoImpressao.class);
            String textoXML = xml.object2XML(modelo);
            ArquivoTexto arq = new ArquivoTexto(URL_XMl);
            arq.abrirEdicao();
            arq.setTexto(textoXML);
            arq.fechar();
            salvo = true;
        } catch (Exception e) {
            System.out.println("Problemas ao gerar arquivo de configuracao de impressão!");
        }

        return salvo;
    }

    /**
     * Ler as configuracoes salvas
     * @return configuracao de email
     */
    public PedidoImpressao ler() {
        PedidoImpressao impressao = null;

        try {
            ParserXML parser = new ParserXML();
            parser.setNomeArquivoXml(URL_XMl);
            parser.Iniciar();
            parser.ProcessarArquivoXml();
            impressao = new PedidoImpressao();
            impressao.setImpressora(parser.getValor("impressora"));
            impressao.setVias(parser.getValor("vias"));
        } catch (Exception e) {
            System.out.println(e);
            System.out.println("Problemas ao ler arquivo de configuracao de impressao!");
        }

        return impressao;
    }

}///:~