text:
package core

import (
	"bytes"
	"context"
	"fmt"

	"github.com/pingcap/tidb/expression"
	"github.com/pingcap/tidb/planner/util"
	"github.com/pingcap/tidb/util/mathutil"
)

// pushDownTopNOptimizer pushes down the topN or limit. In the future we will remove the limit from `requiredProperty` in CBO phase.
type pushDownTopNOptimizer struct {
}

func (s *pushDownTopNOptimizer) optimize(ctx context.Context, p LogicalPlan, opt *logicalOptimizeOp) (LogicalPlan, error) {
	return p.pushDownTopN(nil, opt), nil
}

func (s *baseLogicalPlan) pushDownTopN(topN *LogicalTopN, opt *logicalOptimizeOp) LogicalPlan {
	p := s.self
	for i, child := range p.Children() {
		p.Children()[i] = child.pushDownTopN(nil, opt)
	}
	if topN != nil {
		return topN.setChild(p, opt)
	}
	return p
}

// setChild set p as topn's child.
func (lt *LogicalTopN) setChild(p LogicalPlan, opt *logicalOptimizeOp) LogicalPlan {
	// Remove this TopN if its child is a TableDual.
	dual, isDual := p.(*LogicalTableDual)
	if isDual {
		numDualRows := uint64(dual.RowCount)
		if numDualRows < lt.Offset {
			dual.RowCount = 0
			return dual
		}
		dual.RowCount = int(mathutil.Min(numDualRows-lt.Offset, lt.Count))
		return dual
	}

	if lt.isLimit() {
		limit := LogicalLimit{
			Count:      lt.Count,
			Offset:     lt.Offset,
			limitHints: lt.limitHints,
		}.Init(lt.ctx, lt.blockOffset)
		limit.SetChildren(p)
		appendTopNPushDownTraceStep(limit, p, opt)
		return limit
	}
	// Then lt must be topN.
	lt.SetChildren(p)
	appendTopNPushDownTraceStep(lt, p, opt)
	return lt
}

func (ls *LogicalSort) pushDownTopN(topN *LogicalTopN, opt *logicalOptimizeOp) LogicalPlan {
	if topN == nil {
		return ls.baseLogicalPlan.pushDownTopN(nil, opt)
	} else if topN.isLimit() {
		topN.ByItems = ls.ByItems
		appendSortPassByItemsTraceStep(ls, topN, opt)
		return ls.children[0].pushDownTopN(topN, opt)
	}
	// If a TopN is pushed down, this sort is useless.
	return ls.children[0].pushDownTopN(topN, opt)
}

func (p *LogicalLimit) convertToTopN(opt *logicalOptimizeOp) *LogicalTopN {
	topn := LogicalTopN{Offset: p.Offset, Count: p.Count, limitHints: p.limitHints}.Init(p.ctx, p.blockOffset)
	appendConvertTopNTraceStep(p, topn, opt)
	return topn
}

func (p *LogicalLimit) pushDownTopN(topN *LogicalTopN, opt *logicalOptimizeOp) LogicalPlan {
	child := p.children[0].pushDownTopN(p.convertToTopN(opt), opt)
	if topN != nil {
		return topN.setChild(child, opt)
	}
	return child
}

func (p *LogicalUnionAll) pushDownTopN(topN *LogicalTopN, opt *logicalOptimizeOp) LogicalPlan {
	for i, child := range p.children {
		var newTopN *LogicalTopN
		if topN != nil {
			newTopN = LogicalTopN{Count: topN.Count + topN.Offset, limitHints: topN.limitHints}.Init(p.ctx, topN.blockOffset)
			for _, by := range topN.ByItems {
				newTopN.ByItems = append(newTopN.ByItems, &util.ByItems{Expr: by.Expr, Desc: by.Desc})
			}
			// newTopN to push down Union's child
			appendNewTopNTraceStep(topN, p, opt)
		}
		p.children[i] = child.pushDownTopN(newTopN, opt)
	}
	if topN != nil {
		return topN.setChild(p, opt)
	}
	return p
}

func (p *LogicalProjection) pushDownTopN(topN *LogicalTopN, opt *logicalOptimizeOp) LogicalPlan {
	for _, expr := range p.Exprs {
		if expression.HasAssignSetVarFunc(expr) {
			return p.baseLogicalPlan.pushDownTopN(topN, opt)
		}
	}
	if topN != nil {
		for _, by := range topN.ByItems {
			by.Expr = expression.FoldConstant(expression.ColumnSubstitute(by.Expr, p.schema, p.Exprs))
		}

		// remove meaningless constant sort items.
		for i := len(topN.ByItems) - 1; i >= 0; i-- {
			switch topN.ByItems[i].Expr.(type) {
			case *expression.Constant, *expression.CorrelatedColumn:
				topN.ByItems = append(topN.ByItems[:i], topN.ByItems[i+1:]...)
			}
		}
	}
	p.children[0] = p.children[0].pushDownTopN(topN, opt)
	return p
}

func (p *LogicalLock) pushDownTopN(topN *LogicalTopN, opt *logicalOptimizeOp) LogicalPlan {
	if topN != nil {
		p.children[0] = p.children[0].pushDownTopN(topN, opt)
	}
	return p.self
}

// pushDownTopNToChild will push a topN to one child of join. The idx stands for join child index. 0 is for left child.
func (p *LogicalJoin) pushDownTopNToChild(topN *LogicalTopN, idx int, opt *logicalOptimizeOp) LogicalPlan {
	if topN == nil {
		return p.children[idx].pushDownTopN(nil, opt)
	}

	for _, by := range topN.ByItems {
		cols := expression.ExtractColumns(by.Expr)
		for _, col := range cols {
			if !p.children[idx].Schema().Contains(col) {
				return p.children[idx].pushDownTopN(nil, opt)
			}
		}
	}

	newTopN := LogicalTopN{
		Count:      topN.Count + topN.Offset,
		ByItems:    make([]*util.ByItems, len(topN.ByItems)),
		limitHints: topN.limitHints,
	}.Init(topN.ctx, topN.blockOffset)
	for i := range topN.ByItems {
		newTopN.ByItems[i] = topN.ByItems[i].Clone()
	}
	appendTopNPushDownJoinTraceStep(p, newTopN, idx, opt)
	return p.children[idx].pushDownTopN(newTopN, opt)
}

func (p *LogicalJoin) pushDownTopN(topN *LogicalTopN, opt *logicalOptimizeOp) LogicalPlan {
	switch p.JoinType {
	case LeftOuterJoin, LeftOuterSemiJoin, AntiLeftOuterSemiJoin:
		p.children[0] = p.pushDownTopNToChild(topN, 0, opt)
		p.children[1] = p.children[1].pushDownTopN(nil, opt)
	case RightOuterJoin:
		p.children[1] = p.pushDownTopNToChild(topN, 1, opt)
		p.children[0] = p.children[0].pushDownTopN(nil, opt)
	default:
		return p.baseLogicalPlan.pushDownTopN(topN, opt)
	}

	// The LogicalJoin may be also a LogicalApply. So we must use self to set parents.
	if topN != nil {
		return topN.setChild(p.self, opt)
	}
	return p.self
}

func (*pushDownTopNOptimizer) name() string {
	return "topn_push_down"
}

func appendTopNPushDownTraceStep(parent LogicalPlan, child LogicalPlan, opt *logicalOptimizeOp) {
	action := func() string {
		return fmt.Sprintf("%v_%v is added as %v_%v's parent", parent.TP(), parent.ID(), child.TP(), child.ID())
	}
	reason := func() string {
		return fmt.Sprintf("%v is pushed down", parent.TP())
	}
	opt.appendStepToCurrent(parent.ID(), parent.TP(), reason, action)
}

func appendTopNPushDownJoinTraceStep(p *LogicalJoin, topN *LogicalTopN, idx int, opt *logicalOptimizeOp) {
	action := func() string {
		buffer := bytes.NewBufferString(fmt.Sprintf("%v_%v is added and pushed into %v_%v's ",
			topN.TP(), topN.ID(), p.TP(), p.ID()))
		if idx == 0 {
			buffer.WriteString("left ")
		} else {
			buffer.WriteString("right ")
		}
		buffer.WriteString("table")
		return buffer.String()
	}
	reason := func() string {
		buffer := bytes.NewBufferString(fmt.Sprintf("%v_%v's joinType is %v, and all ByItems[", p.TP(), p.ID(), p.JoinType.String()))
		for i, item := range topN.ByItems {
			if i > 0 {
				buffer.WriteString(",")
			}
			buffer.WriteString(item.String())
		}
		buffer.WriteString("] contained in ")
		if idx == 0 {
			buffer.WriteString("left ")
		} else {
			buffer.WriteString("right ")
		}
		buffer.WriteString("table")
		return buffer.String()
	}
	opt.appendStepToCurrent(p.ID(), p.TP(), reason, action)
}

func appendSortPassByItemsTraceStep(sort *LogicalSort, topN *LogicalTopN, opt *logicalOptimizeOp) {
	action := func() string {
		buffer := bytes.NewBufferString(fmt.Sprintf("%v_%v passes ByItems[", sort.TP(), sort.ID()))
		for i, item := range sort.ByItems {
			if i > 0 {
				buffer.WriteString(",")
			}
			buffer.WriteString(item.String())
		}
		buffer.WriteString(fmt.Sprintf("] to %v_%v", topN.TP(), topN.ID()))
		return buffer.String()
	}
	reason := func() string {
		return fmt.Sprintf("%v_%v is Limit originally", topN.TP(), topN.ID())
	}
	opt.appendStepToCurrent(sort.ID(), sort.TP(), reason, action)
}

func appendNewTopNTraceStep(topN *LogicalTopN, union *LogicalUnionAll, opt *logicalOptimizeOp) {
	reason := func() string {
		return ""
	}
	action := func() string {
		return fmt.Sprintf("%v_%v is added and pushed down across %v_%v", topN.TP(), topN.ID(), union.TP(), union.ID())
	}
	opt.appendStepToCurrent(topN.ID(), topN.TP(), reason, action)
}

func appendConvertTopNTraceStep(p LogicalPlan, topN *LogicalTopN, opt *logicalOptimizeOp) {
	reason := func() string {
		return ""
	}
	action := func() string {
		return fmt.Sprintf("%v_%v is converted into %v_%v", p.TP(), p.ID(), topN.TP(), topN.ID())
	}
	opt.appendStepToCurrent(topN.ID(), topN.TP(), reason, action)
}


text:
define([
    "yoson"
], function(yOSON){

    var SinglePromise = function(){
        this.callbacks = {
            succeededs:[],
            faileds:[]
        };
        this.status = "pending";
    };

    SinglePromise.prototype.eachCallBackList = function(callbackList, onEveryCallback){
        for(var indexCallback = 0; indexCallback < callbackList.length; indexCallback++){
            onEveryCallback.call(this, callbackList[indexCallback]);
        }
    };

    SinglePromise.prototype.done = function(){
        var that = this;
        this.status = "done";
        this.dataToPass = arguments;
        this.eachCallBackList(this.callbacks.succeededs, function(callbackRegistered){
            callbackRegistered.apply(this, that.dataToPass);
        });
    };

    //When all tasks are successful
    SinglePromise.prototype.then = function(whenItsDone, whenIsFailed){
        var callbacks = this.callbacks;

        var byStatus = {
            "pending": function(){
                callbacks.succeededs.push(whenItsDone);
                if(typeof whenIsFailed === "function"){
                    callbacks.faileds.push(whenIsFailed);
                }

            },
            "done": function(){
                if(typeof whenItsDone === "function"){
                    whenItsDone.call(this);
                }
            },
            "fail": function(){
                whenIsFailed.call(this);
            }
        };
        byStatus[this.status]();
        return this;
    };

    //When the promise is broken
    SinglePromise.prototype.fail = function(objError){
        this.status = "fail";
        this.eachCallBackList(this.callbacks.faileds, function(callbackRegistered){
            callbackRegistered.call(this, objError);
        });
    };

    yOSON.Components.SinglePromise = SinglePromise;
    return SinglePromise;
});

redpajama_set_name: RedPajamaGithub


text:
"""
HTTP version 1.1 partial protocol implementation.

See RFC2616 for the protocol specification:
  http://www.w3.org/Protocols/rfc2616/rfc2616.html

NOTE: This module is for illustration purposes only, and does not implement the
complete, correct protocol.  Do not use in production code.
"""

#-------------------------------------------------------------------------------
# Imports

import collections

#-------------------------------------------------------------------------------
# Constants
#
# These are fixed values used throughout the module.  By convention, we use
# names in ALL_CAPITALS to indicate constants.

# The protocol version implemented in this module.
HTTP_VERSION = 'HTTP/1.1'

# Headers must be encoded with ISO-8859-1 (aka "Latin-1").
HEADER_ENCODING = 'iso-8859-1'

# The end-of-line (EOL) sequence.
EOL = '\r\n'

# For clarity below, we assign names to these single characters.
SPACE = ' '
COLON = ':'

#-------------------------------------------------------------------------------
# Types

# An HTTP request.
Request = collections.namedtuple(
    'Request',
    ('method',  # (str) The request method.
     'path',    # (str) The path to the requested page.
     'header',  # (dict) Dict of field names to field values.
     'body',    # (bytes) Body data.
    ))

# An HTTP response.
Response = collections.namedtuple(
    'Response',
    ('status',  # (int) The status code.
     'reason',  # (str) Description of the reason for the status code.
     'header',  # (dict) Dict of field names to field values.
     'body',    # (bytes) Body data.
    ))

#-------------------------------------------------------------------------------
# Helper functions
#
# These functions are intended for use only in implementing other functions in
# this module, rather than by other people.  They are called "helper functions"
# and in Python by convention are given names starting with an underscore.

def _split_lines(msg):
    """
    Splits a protocol message into lines until the first blank line.

    'msg' is a byte array containing a protocol message.  Divides up the message
    into lines, until it finds a blank line.  These lines have the EOL
    characters removed, and are decoded to strings.  Returns a list of lines,
    and a byte array of the remainder of the message.
    """
    # Find the EOL sequence encoded as bytes.
    eol = EOL.encode(HEADER_ENCODING)

    # The list into which we will collect header lines.
    lines = []
    # Keep going until we find a blank line.
    while True:
        # Look for the EOL sequence.
        index = msg.index(eol)
        # Split off the line, not including the EOL.
        line = msg[: index]
        # In the message, skip over the line, past the EOL.
        msg = msg[index + len(eol) :]
        # Is the line blank?
        if len(line) == 0:
            # Yes.  We're done; return the lines and whatever data is left in
            # the message.
            return lines, msg
        else:
            # No.  Decode the line.
            line = line.decode(HEADER_ENCODING)
            # Store it in the list of lines.
            lines.append(line)
            # Now continue at the top of the loop.

def _format_header(fields):
    """
    Formats a header from fields.

    'fields' is a dict from field names to values.  Returns a list of header
    lines.
    """
    # The list into which we will collect header lines.
    lines = []
    for name, value in fields.items():
        # A header line looks like, "name: value".
        line = name + COLON + SPACE + value
        # Add this line to the list.
        lines.append(line)
    return lines

def _parse_header(lines):
    """
    Parses lines from a header.

    'lines' is a list of strings of header lines.  Parses these into name-value
    pairs, and return a dict from name to value.
    """
    # The dict into which we will store header fields.
    header = {}
    # Loop over lines in the header.
    for line in lines:
        # Find the first colon.
        index = line.index(COLON)
        # Up to the colon is the field name.
        name = line[: index]
        # After the colon is the field value.
        value = line[index + 1 :]
        # The field value may begin or end with extra space, which is not
        # significant.  Remove it.
        value = value.strip()
        # Store the field.
        header[name] = value
    # All done.
    return header

def _format_message(start_line, header, body):
    """
    Formats an HTTP protocol message from a start line, header, and body.

    'start_line' is the start line string; 'header' is a dict from field name
    to value; 'body' is a byte array of the message body.  Returns the message
    as a byte array.
    """
    # The message begins with the start line, terminated with EOL and encoded.
    msg = (start_line + EOL).encode(HEADER_ENCODING)
    # Convert the header to lines.
    header_lines = _format_header(header)
    # Add them to the message, one by one, each terminated with EOL and encoded.
    for line in header_lines:
        msg = msg + (line + EOL).encode(HEADER_ENCODING)
    # A blank line indicates end of headers.
    msg = msg + EOL.encode(HEADER_ENCODING)
    # The rest of the message is the body.
    msg = msg + body
    return msg

def _parse_message(msg):
    """
    Divides an HTTP protocol message into start line, header, and body.

    'msg' is a byte array containing the message.  Returns the start line, with
    the EOL marker removed and decoded into a string; the header, as a dict from
    field name to field value; and the body as a byte array.
    """
    lines, body = _split_lines(msg)
    # The first line is the start line.
    start_line = lines[0]
    # Remaining lines are the header.
    header = _parse_header(lines[1 :])
    return start_line, header, body

def _format_request_line(method, path):
    """
    Formats the request line.

    'method' is the request method; 'path' is the requested path.  Returns
    the request line as a str.
    """
    return method + SPACE + path + SPACE + HTTP_VERSION

def _parse_request_line(line):
    """
    Parses the request line.

    Returns the method and path.
    """
    # Up to the first space is the method.
    index0 = line.index(SPACE)
    method = line[: index0]
    # Starting from the first space, up to the next space is the path.
    index1 = line.index(SPACE, index0 + 1)
    path = line[index0 + 1 : index1]
    # The remainder is the protocol version.
    http_version = line[index1 + 1 :]
    # Make sure it's the protocol version we recognize.
    assert http_version == HTTP_VERSION
    return method, path

def _format_status_line(status, reason):
    """
    Formats the status line.

    'status' is the status code as an integer.  Returns the status line as a
    str.
    """
    return HTTP_VERSION + SPACE + str(status) + SPACE + reason

def _parse_status_line(line):
    """
    Parses the status line.

    Returns the status code and reason.
    """
    # Up to the first space is the protocol version.
    index0 = line.index(SPACE)
    http_version = line[: index0]
    # Make sure it's the protocol version we recognize.
    assert http_version == HTTP_VERSION
    # Starting from the first space, up to the next space is the status code.
    index1 = line.index(SPACE, index0 + 1)
    status = line[index0 + 1 : index1]
    # Convert the status code to an integer.
    status = int(status)
    # The remainder is the reason.
    reason = line[index1 + 1 :]
    return status, reason

def format_request(request):
    """
    Formats a request into a protocol message.

    'request' is a 'Request' object.  Returns a byte array.
    """
    start_line = _format_request_line(request.method, request.path)
    msg = _format_message(start_line, request.header, request.body)
    return msg

def parse_request(msg):
    """
    Parses a request protocol message.

    'msg' is a byte array containing the request message.  Returns a 'Request'
    object.
    """
    start_line, header, body = _parse_message(msg)
    request, path = _parse_request_line(start_line)
    return Request(request, path, header, body)

def format_response(response):
    """
    Formats a response into a protocol message.

    'response' is a 'Response' object.  Returns a byte array.
    """
    start_line = _format_status_line(response.status, response.reason)
    msg = _format_message(start_line, response.header, response.body)
    return msg

def parse_response(msg):
    """
    Parses a response message.

    'msg' is a byte array containing the response message.  Returns a 'Response'
    object.
    """
    start_line, header, body = _parse_message(msg)
    status, reason = _parse_status_line(start_line)
    return Response(status, reason, header, body)


text:
"use strict";

var viewModelBaseModule = require("../../common/view-model-base");

var AmenitiesViewModel = (function (_super) {
    __extends(AmenitiesViewModel, _super);
    function AmenitiesViewModel() {
        _super.call(this);
    }

    return AmenitiesViewModel;

})(viewModelBaseModule.ViewModelBase);

exports.AmenitiesViewModel = AmenitiesViewModel;


text:
/**
 * Autogenerated by Thrift Compiler (0.9.1)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */

namespace LINE.Datatypes
{
  public enum ContactSetting
  {
    CONTACT_SETTING_NOTIFICATION_DISABLE = 1,
    CONTACT_SETTING_DISPLAY_NAME_OVERRIDE = 2,
    CONTACT_SETTING_CONTACT_HIDE = 4,
    CONTACT_SETTING_FAVORITE = 8,
    CONTACT_SETTING_DELETE = 16,
  }
}


text:
NSString * const JJInfiniteTitleBarBtnDidClicked = @"JJInfiniteTitleBarBtnDidClicked";

@interface JJInfiniteTitleBar ()
@property(nonatomic, weak) JJTitleBtn * curPageTitleBtn;
//@property(nonatomic, weak) UIScrollView * scrollView;
@end

@implementation JJInfiniteTitleBar

#pragma mark ------------------------------------------
#pragma mark init methods
- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.bounces = NO;
        self.showsHorizontalScrollIndicator = NO;
        self.showsVerticalScrollIndicator = NO;
    }
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    CGFloat titleBtnH = self.frame.size.height;
    CGFloat titleBtnY = 0;
    NSInteger i = 0;
    for (JJTitleBtn *titleBtn in self.subviews) {
        titleBtn.frame = CGRectMake(self.titleWidth * i, titleBtnY, self.titleWidth, titleBtnH);
        i++;
    }
}

#pragma mark ------------------------------------------
#pragma mark other methods
- (void)titleBtnDidClicked:(UITapGestureRecognizer *)tap
{
    self.currentPage = tap.view.tag;
    // 添加点击通知
    [[NSNotificationCenter defaultCenter] postNotificationName:JJInfiniteTitleBarBtnDidClicked object:nil userInfo:nil];
    JJTitleBtn *clickedBtn = (JJTitleBtn *)tap.view;
    [self setupTitleBtnWithClickedBtn:clickedBtn];
}

- (void)setupTitleBtnWithClickedBtn:(JJTitleBtn *)curPageTitleBtn

{
    self.curPageTitleBtn.textColor = [UIColor blackColor];
    curPageTitleBtn.textColor = [UIColor redColor];
    // 设置居中
    CGFloat offsetX = curPageTitleBtn.center.x - self.frame.size.width * 0.5;
    if (offsetX < 0) {
        offsetX = 0;
    }
    CGFloat maxOffsetX = self.contentSize.width - self.frame.size.width;
    if (offsetX > maxOffsetX) {
        offsetX = maxOffsetX;
    }
    [self setContentOffset:CGPointMake(offsetX, 0) animated:YES];

    self.curPageTitleBtn = curPageTitleBtn;
}

#pragma mark ------------------------------------------
#pragma mark set/get
- (void)setTitles:(NSArray *)titles
{
    _titles = titles;
    self.numberOfPages = titles.count;
    for (int i = 0; i < self.numberOfPages; i++) {
        JJTitleBtn  *titleBtn = [[JJTitleBtn alloc] init];
        titleBtn.tag = i;
        titleBtn.text = self.titles[i];
        titleBtn.textColor = [UIColor blackColor];
        titleBtn.backgroundColor = [UIColor yellowColor];
        [titleBtn addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(titleBtnDidClicked:)]];
        [self addSubview:titleBtn];
    }
    self.contentSize = CGSizeMake(self.titleWidth * _numberOfPages, 0);
}

- (void)setCurrentPage:(NSInteger)currentPage
{
    _currentPage = currentPage;
    JJTitleBtn *curPageTitleBtn = self.subviews[currentPage];
    [self setupTitleBtnWithClickedBtn:curPageTitleBtn];
}
@end


text:
using NUnit.Framework;
using SimpleBase;
using System;

namespace SimpleBaseTest.Base85Test;

class Z85Test
{
    private static readonly TestCaseData[] testVectors = new[]
    {
        new TestCaseData(Array.Empty<byte>(), ""),
        new TestCaseData(new byte[] { 0x86, 0x4F, 0xD2, 0x6F, 0xB5, 0x59, 0xF7, 0x5B }, "HelloWorld"),
        new TestCaseData(new byte[] { 0x11 }, "5D"),
        new TestCaseData(new byte[] { 0x11, 0x22 }, "5H4"),
        new TestCaseData(new byte[] { 0x11, 0x22, 0x33 }, "5H61"),
        new TestCaseData(new byte[] { 0x11, 0x22, 0x33, 0x44 }, "5H620"),
        new TestCaseData(new byte[] { 0x11, 0x22, 0x33, 0x44, 0x55 }, "5H620rr"),
        new TestCaseData(new byte[] { 0x00, 0x00, 0x00, 0x00 }, "00000"),
        new TestCaseData(new byte[] { 0x20, 0x20, 0x20, 0x20 }, "arR^H"),
    };

    [Test]
    [TestCaseSource(nameof(testVectors))]
    public void Encode_TestVectors_ShouldEncodeCorrectly(byte[] input, string expectedOutput)
    {
        var result = Base85.Z85.Encode(input);
        Assert.That(result, Is.EqualTo(expectedOutput));
    }

    [Test]
    public void Encode_NullBuffer_ReturnsEmptyString()
    {
        Assert.That(Base85.Z85.Encode(null), Is.EqualTo(String.Empty));
    }

    [Test]
    [TestCaseSource(nameof(testVectors))]
    public void Decode_TestVectors_ShouldDecodeCorrectly(byte[] expectedOutput, string input)
    {
        var result = Base85.Z85.Decode(input);
        CollectionAssert.AreEqual(expectedOutput, result);
    }
}


text:
<?php

require_once dirname(dirname(dirname(__FILE__))) . DIRECTORY_SEPARATOR . 'TestHelper.php';

if (!defined('PHPUnit_MAIN_METHOD')) {
    define('PHPUnit_MAIN_METHOD', 'Modules_Pages_IndexControllerTest::main');
}

/**
 * @category   Firal
 * @package    Firal_Modules_Pages
 * @subpackage UnitTests
 * @copyright  Copyright (c) 2009-2010 Firal (http://firal.org/)
 * @license    http://firal.org/licenses/new-bsd    New BSD License
 */
class Modules_Pages_IndexControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
{
    public static function main()
    {
        $suite  = new PHPUnit_Framework_TestSuite('Modules_Pages_IndexControllerTest');
        $result = PHPUnit_TextUI_TestRunner::run($suite);
    }

    public function setUp()
    {
        $this->bootstrap = new Zend_Application(
            APPLICATION_ENV,
            APPLICATION_PATH . DIRECTORY_SEPARATOR . 'configs' . DIRECTORY_SEPARATOR . 'config.php'
        );
        parent::setUp();

        Modules_AllTests::setUpDb($this->bootstrap->getBootstrap()->getResource('db'));
    }
}

if (PHPUnit_MAIN_METHOD == 'Modules_Pages_IndexControllerTest::main') {
    Modules_Pages_IndexControllerTest::main();
}


text:
<?xml version="1.0" encoding="utf-8"?>
<geo:GeodesyML gml:id="LILY00AUS" xmlns:gco="http://www.isotc211.org/2005/gco" xmlns:geo="urn:xml-gov-au:icsm:egeodesy:0.4" xmlns:gmd="http://www.isotc211.org/2005/gmd" xmlns:gml="http://www.opengis.net/gml/3.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <geo:siteLog gml:id="lily_20161215.log">
        <geo:formInformation>
            <geo:preparedBy>Ted Zhou</geo:preparedBy>
            <geo:datePrepared>2016-12-15</geo:datePrepared>
            <geo:reportType>UPDATE</geo:reportType>
        </geo:formInformation>
        <geo:siteIdentification>
            <geo:siteName>Lilydale</geo:siteName>
            <geo:fourCharacterID>LILY</geo:fourCharacterID>
            <geo:monumentInscription></geo:monumentInscription>
            <geo:iersDOMESNumber>AUM000426</geo:iersDOMESNumber>
            <geo:cdpNumber>NONE</geo:cdpNumber>
            <geo:monumentDescription codeSpace="urn:ga-gov-au:monument-description-type">316 GRADE STAINLESS STEEL MAST</geo:monumentDescription>
            <geo:heightOfTheMonument>1.2</geo:heightOfTheMonument>
            <geo:monumentFoundation>BRICK WALL</geo:monumentFoundation>
            <geo:foundationDepth>0.5</geo:foundationDepth>
            <geo:markerDescription>250 mm dia Stainless steel plate with centred 5/8" threaded spigot</geo:markerDescription>
            <geo:dateInstalled>2014-11-20T00:00:00Z</geo:dateInstalled>
            <geo:geologicCharacteristic codeSpace="urn:ga-gov-au:geologic-characteristic-type"></geo:geologicCharacteristic>
            <geo:bedrockType></geo:bedrockType>
            <geo:bedrockCondition></geo:bedrockCondition>
            <geo:fractureSpacing></geo:fractureSpacing>
            <geo:faultZonesNearby codeSpace="urn:ga-gov-au:fault-zones-type">(YES/NO/Name of the zone)</geo:faultZonesNearby>
            <geo:notes>The GPS antenna is located on top of a stainless steel mast that is approximately 2.6 metres long, of which 1.2 metres protrudes above the top of the brick parapet wall that it has been secured to, near the corner.</geo:notes>
        </geo:siteIdentification>
        <geo:siteLocation>
            <geo:city>Lilydale</geo:city>
            <geo:state>Tasmania</geo:state>
            <geo:countryCodeISO codeList="http://xml.gov.au/icsm/geodesyml/codelists/country-codes-codelist.xml#GeodesyML_CountryCode" codeListValue="Australia" codeSpace="urn:xml-gov-au:icsm:egeodesy:0.4">AUS</geo:countryCodeISO>
            <geo:tectonicPlate codeSpace="urn:ga-gov-au:plate-type">AUSTRALIAN</geo:tectonicPlate>
            <geo:approximatePositionITRF>
                <geo:cartesianPosition>
                    <gml:Point gml:id="itrf_cartesian" srsName="EPSG:7789">
                        <gml:pos>-4037356.408 2600427.544 -4183584.34</gml:pos>
                    </gml:Point>
                </geo:cartesianPosition>
                <geo:geodeticPosition>
                    <gml:Point gml:id="itrf_geodetic" srsName="EPSG:7912">
                        <gml:pos>-41.2516160056 147.214753225 170.155</gml:pos>
                    </gml:Point>
                </geo:geodeticPosition>
            </geo:approximatePositionITRF>
            <geo:notes>The GPS antenna is located at the south- west corner of the Lilydale District School Science and Arts building, 1947 Main Road Lilydale, Tasmania. It is part of the AuScope GPS in Schools project.</geo:notes>
        </geo:siteLocation>
        <geo:gnssReceiver>
            <geo:GnssReceiver gml:id="gnss-receiver-1">
                <geo:manufacturerSerialNumber>5145K79608</geo:manufacturerSerialNumber>
                <geo:igsModelCode codeList="http://xml.gov.au/icsm/geodesyml/codelists/antenna-receiver-codelists.xml#GeodesyML_GNSSReceiverTypeCode" codeListValue="TRIMBLE NETR9" codeSpace="urn:xml-gov-au:icsm:egeodesy:0.4">TRIMBLE NETR9</geo:igsModelCode>
                <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GPS</geo:satelliteSystem>
                <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GLO</geo:satelliteSystem>
                <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GAL</geo:satelliteSystem>
                <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">BDS</geo:satelliteSystem>
                <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">QZSS</geo:satelliteSystem>
                <geo:firmwareVersion>4.85</geo:firmwareVersion>
                <geo:elevationCutoffSetting>0.0</geo:elevationCutoffSetting>
                <geo:dateInstalled>2015-02-13T00:00:00Z</geo:dateInstalled>
                <geo:dateRemoved>2015-03-23T00:00:00Z</geo:dateRemoved>
                <geo:temperatureStabilization xsi:nil="true"></geo:temperatureStabilization>
            </geo:GnssReceiver>
            <geo:dateInserted>2015-02-13T00:00:00Z</geo:dateInserted>
        </geo:gnssReceiver>
        <geo:gnssReceiver>
            <geo:GnssReceiver gml:id="gnss-receiver-2">
                <geo:manufacturerSerialNumber>5145K79608</geo:manufacturerSerialNumber>
                <geo:igsModelCode codeList="http://xml.gov.au/icsm/geodesyml/codelists/antenna-receiver-codelists.xml#GeodesyML_GNSSReceiverTypeCode" codeListValue="TRIMBLE NETR9" codeSpace="urn:xml-gov-au:icsm:egeodesy:0.4">TRIMBLE NETR9</geo:igsModelCode>
                <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GPS</geo:satelliteSystem>
                <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GLO</geo:satelliteSystem>
                <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GAL</geo:satelliteSystem>
                <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">BDS</geo:satelliteSystem>
                <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">QZSS</geo:satelliteSystem>
                <geo:firmwareVersion>4.93</geo:firmwareVersion>
                <geo:elevationCutoffSetting>0.0</geo:elevationCutoffSetting>
                <geo:dateInstalled>2015-03-23T00:00:00Z</geo:dateInstalled>
                <geo:dateRemoved>2015-06-15T00:00:00Z</geo:dateRemoved>
                <geo:temperatureStabilization xsi:nil="true"></geo:temperatureStabilization>
            </geo:GnssReceiver>
            <geo:dateInserted>2015-03-23T00:00:00Z</geo:dateInserted>
        </geo:gnssReceiver>
        <geo:gnssReceiver>
            <geo:GnssReceiver gml:id="gnss-receiver-3">
                <geo:manufacturerSerialNumber>5145K79608</geo:manufacturerSerialNumber>
                <geo:igsModelCode codeList="http://xml.gov.au/icsm/geodesyml/codelists/antenna-receiver-codelists.xml#GeodesyML_GNSSReceiverTypeCode" codeListValue="TRIMBLE NETR9" codeSpace="urn:xml-gov-au:icsm:egeodesy:0.4">TRIMBLE NETR9</geo:igsModelCode>
                <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GPS</geo:satelliteSystem>
                <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GLO</geo:satelliteSystem>
                <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GAL</geo:satelliteSystem>
                <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">BDS</geo:satelliteSystem>
                <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">QZSS</geo:satelliteSystem>
                <geo:firmwareVersion>5.01</geo:firmwareVersion>
                <geo:elevationCutoffSetting>0.0</geo:elevationCutoffSetting>
                <geo:dateInstalled>2015-06-15T00:00:00Z</geo:dateInstalled>
                <geo:dateRemoved>2016-12-15T00:00:00Z</geo:dateRemoved>
                <geo:temperatureStabilization xsi:nil="true"></geo:temperatureStabilization>
            </geo:GnssReceiver>
            <geo:dateInserted>2015-06-15T00:00:00Z</geo:dateInserted>
        </geo:gnssReceiver>
        <geo:gnssReceiver>
            <geo:GnssReceiver gml:id="gnss-receiver-4">
                <geo:notes>Firmware upgrade only</geo:notes>
                <geo:manufacturerSerialNumber>5145K79608</geo:manufacturerSerialNumber>
                <geo:igsModelCode codeList="http://xml.gov.au/icsm/geodesyml/codelists/antenna-receiver-codelists.xml#GeodesyML_GNSSReceiverTypeCode" codeListValue="TRIMBLE NETR9" codeSpace="urn:xml-gov-au:icsm:egeodesy:0.4">TRIMBLE NETR9</geo:igsModelCode>
                <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GPS</geo:satelliteSystem>
                <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GLO</geo:satelliteSystem>
                <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">GAL</geo:satelliteSystem>
                <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">BDS</geo:satelliteSystem>
                <geo:satelliteSystem codeSpace="urn:ga-gov-au:satellite-system-type">QZSS</geo:satelliteSystem>
                <geo:firmwareVersion>5.15</geo:firmwareVersion>
                <geo:elevationCutoffSetting>0.0</geo:elevationCutoffSetting>
                <geo:dateInstalled>2016-12-15T00:00:00Z</geo:dateInstalled>
                <geo:dateRemoved></geo:dateRemoved>
                <geo:temperatureStabilization xsi:nil="true"></geo:temperatureStabilization>
            </geo:GnssReceiver>
            <geo:dateInserted>2016-12-15T00:00:00Z</geo:dateInserted>
        </geo:gnssReceiver>
        <geo:gnssAntenna>
            <geo:GnssAntenna gml:id="gnss-antenna-1">
                <geo:notes>2mm plus two 0.5mm shims used to ensure correct antenna orientation</geo:notes>
                <geo:manufacturerSerialNumber>5421355007</geo:manufacturerSerialNumber>
                <geo:igsModelCode codeList="http://xml.gov.au/icsm/geodesyml/codelists/antenna-receiver-codelists.xml#GeodesyML_GNSSAntennaTypeCode" codeListValue="TRM59800.00 NONE" codeSpace="urn:xml-gov-au:icsm:egeodesy:0.4">TRM59800.00     NONE</geo:igsModelCode>
                <geo:antennaReferencePoint codeSpace="urn:ga-gov-au:antenna-reference-point-type">BPA</geo:antennaReferencePoint>
                <geo:marker-arpUpEcc.>0.003</geo:marker-arpUpEcc.>
                <geo:marker-arpNorthEcc.>0.0</geo:marker-arpNorthEcc.>
                <geo:marker-arpEastEcc.>0.0</geo:marker-arpEastEcc.>
                <geo:alignmentFromTrueNorth>0.0</geo:alignmentFromTrueNorth>
                <geo:antennaRadomeType codeSpace="urn:igs-org:gnss-radome-model-code">NONE</geo:antennaRadomeType>
                <geo:radomeSerialNumber></geo:radomeSerialNumber>
                <geo:antennaCableType>LMR400</geo:antennaCableType>
                <geo:antennaCableLength>30.0</geo:antennaCableLength>
                <geo:dateInstalled>2015-02-26T00:00:00Z</geo:dateInstalled>
                <geo:dateRemoved></geo:dateRemoved>
            </geo:GnssAntenna>
            <geo:dateInserted>2015-02-26T00:00:00Z</geo:dateInserted>
        </geo:gnssAntenna>
        <geo:frequencyStandard>
            <geo:FrequencyStandard gml:id="frequency-standard-1">
                <geo:standardType codeSpace="urn:ga-gov-au:frequency-standard-type">INTERNAL</geo:standardType>
                <geo:inputFrequency xsi:nil="true"></geo:inputFrequency>
                <gml:validTime>
                    <gml:TimePeriod gml:id="frequency-standard-1--time-period-1">
                        <gml:beginPosition>2015-02-26</gml:beginPosition>
                        <gml:endPosition></gml:endPosition>
                    </gml:TimePeriod>
                </gml:validTime>
                <geo:notes></geo:notes>
            </geo:FrequencyStandard>
            <geo:dateInserted>2015-02-26</geo:dateInserted>
        </geo:frequencyStandard>
        <geo:multipathSource>
            <geo:MultipathSource gml:id="multipath-1">
                <geo:possibleProblemSource>METAL ROOF</geo:possibleProblemSource>
                <gml:validTime>
                    <gml:TimePeriod gml:id="time-period-2">
                        <gml:beginPosition></gml:beginPosition>
                        <gml:endPosition></gml:endPosition>
                    </gml:TimePeriod>
                </gml:validTime>
                <geo:notes>Apex of Hip and Valley rood approximately 14 metres south-east of antenna mast is approximately same elevation as ARP.</geo:notes>
            </geo:MultipathSource>
            <geo:dateInserted></geo:dateInserted>
        </geo:multipathSource>
        <geo:siteContact gml:id="agency-1">
            <gmd:MD_SecurityConstraints>
                <gmd:classification gco:nilReason="missing"/>
            </gmd:MD_SecurityConstraints>
            <gmd:CI_ResponsibleParty>
                <gmd:individualName>
                    <gco:CharacterString>Scott Strong</gco:CharacterString>
                </gmd:individualName>
                <gmd:organisationName>
                    <gco:CharacterString>TAS Department Primary Industries, Parks, Water and Environment</gco:CharacterString>
                </gmd:organisationName>
                <gmd:contactInfo>
                    <gmd:CI_Contact>
                        <gmd:phone>
                            <gmd:CI_Telephone>
                                <gmd:voice>
                                    <gco:CharacterString>+61 3 6165 4175</gco:CharacterString>
                                </gmd:voice>
                                <gmd:voice>
                                    <gco:CharacterString></gco:CharacterString>
                                </gmd:voice>
                                <gmd:facsimile>
                                    <gco:CharacterString></gco:CharacterString>
                                </gmd:facsimile>
                            </gmd:CI_Telephone>
                        </gmd:phone>
                        <gmd:address>
                            <gmd:CI_Address>
                                <gmd:deliveryPoint>
                                    <gco:CharacterString>GPO Box 44 Hobart  TAS  7001 AUSTRALIA</gco:CharacterString>
                                </gmd:deliveryPoint>
                                <gmd:city>
                                    <gco:CharacterString>Hobart</gco:CharacterString>
                                </gmd:city>
                                <gmd:postalCode>
                                    <gco:CharacterString>7001</gco:CharacterString>
                                </gmd:postalCode>
                                <gmd:country>
                                    <gco:CharacterString>Australia</gco:CharacterString>
                                </gmd:country>
                                <gmd:electronicMailAddress>
                                    <gco:CharacterString>scott.strong@dpipwe.tas.gov.au</gco:CharacterString>
                                </gmd:electronicMailAddress>
                            </gmd:CI_Address>
                        </gmd:address>
                    </gmd:CI_Contact>
                </gmd:contactInfo>
                <gmd:role>
                    <gmd:CI_RoleCode codeList="http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#CI_RoleCode" codeListValue="pointOfContact"></gmd:CI_RoleCode>
                </gmd:role>
            </gmd:CI_ResponsibleParty>
        </geo:siteContact>
        <geo:siteContact gml:id="agency-2">
            <gmd:MD_SecurityConstraints>
                <gmd:classification gco:nilReason="missing"/>
            </gmd:MD_SecurityConstraints>
            <gmd:CI_ResponsibleParty>
                <gmd:individualName>
                    <gco:CharacterString></gco:CharacterString>
                </gmd:individualName>
                <gmd:organisationName>
                    <gco:CharacterString>TAS Department Primary Industries, Parks, Water and Environment</gco:CharacterString>
                </gmd:organisationName>
                <gmd:contactInfo>
                    <gmd:CI_Contact>
                        <gmd:phone>
                            <gmd:CI_Telephone>
                                <gmd:voice>
                                    <gco:CharacterString></gco:CharacterString>
                                </gmd:voice>
                                <gmd:voice>
                                    <gco:CharacterString></gco:CharacterString>
                                </gmd:voice>
                                <gmd:facsimile>
                                    <gco:CharacterString></gco:CharacterString>
                                </gmd:facsimile>
                            </gmd:CI_Telephone>
                        </gmd:phone>
                        <gmd:address>
                            <gmd:CI_Address>
                                <gmd:deliveryPoint>
                                    <gco:CharacterString>GPO Box 44 Hobart  TAS  7001 AUSTRALIA</gco:CharacterString>
                                </gmd:deliveryPoint>
                                <gmd:city>
                                    <gco:CharacterString>Hobart</gco:CharacterString>
                                </gmd:city>
                                <gmd:postalCode>
                                    <gco:CharacterString>7001</gco:CharacterString>
                                </gmd:postalCode>
                                <gmd:country>
                                    <gco:CharacterString>Australia</gco:CharacterString>
                                </gmd:country>
                                <gmd:electronicMailAddress>
                                    <gco:CharacterString></gco:CharacterString>
                                </gmd:electronicMailAddress>
                            </gmd:CI_Address>
                        </gmd:address>
                    </gmd:CI_Contact>
                </gmd:contactInfo>
                <gmd:role>
                    <gmd:CI_RoleCode codeList="http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#CI_RoleCode" codeListValue="pointOfContact"></gmd:CI_RoleCode>
                </gmd:role>
            </gmd:CI_ResponsibleParty>
        </geo:siteContact>
        <geo:siteMetadataCustodian gml:id="agency-3">
            <gmd:MD_SecurityConstraints>
                <gmd:classification gco:nilReason="missing"/>
            </gmd:MD_SecurityConstraints>
            <gmd:CI_ResponsibleParty>
                <gmd:individualName>
                    <gco:CharacterString>Ryan Ruddick</gco:CharacterString>
                </gmd:individualName>
                <gmd:organisationName>
                    <gco:CharacterString>Geoscience Australia</gco:CharacterString>
                </gmd:organisationName>
                <gmd:contactInfo>
                    <gmd:CI_Contact>
                        <gmd:phone>
                            <gmd:CI_Telephone>
                                <gmd:voice>
                                    <gco:CharacterString>+61 2 6249 9426</gco:CharacterString>
                                </gmd:voice>
                                <gmd:voice>
                                    <gco:CharacterString>+61 2 6249 9111</gco:CharacterString>
                                </gmd:voice>
                                <gmd:facsimile>
                                    <gco:CharacterString></gco:CharacterString>
                                </gmd:facsimile>
                            </gmd:CI_Telephone>
                        </gmd:phone>
                        <gmd:address>
                            <gmd:CI_Address>
                                <gmd:deliveryPoint>
                                    <gco:CharacterString>GPO Box 378 Canberra  ACT  2601 AUSTRALIA</gco:CharacterString>
                                </gmd:deliveryPoint>
                                <gmd:city>
                                    <gco:CharacterString>Canberra</gco:CharacterString>
                                </gmd:city>
                                <gmd:postalCode>
                                    <gco:CharacterString>2601</gco:CharacterString>
                                </gmd:postalCode>
                                <gmd:country>
                                    <gco:CharacterString>Australia</gco:CharacterString>
                                </gmd:country>
                                <gmd:electronicMailAddress>
                                    <gco:CharacterString>geodesy@ga.gov.au</gco:CharacterString>
                                </gmd:electronicMailAddress>
                            </gmd:CI_Address>
                        </gmd:address>
                    </gmd:CI_Contact>
                </gmd:contactInfo>
                <gmd:role>
                    <gmd:CI_RoleCode codeList="http://www.isotc211.org/2005/resources/Codelist/gmxCodelists.xml#CI_RoleCode" codeListValue="pointOfContact"></gmd:CI_RoleCode>
                </gmd:role>
            </gmd:CI_ResponsibleParty>
        </geo:siteMetadataCustodian>
        <geo:moreInformation>
            <geo:dataCenter>GA</geo:dataCenter>
            <geo:dataCenter>RDSI</geo:dataCenter>
            <geo:urlForMoreInformation>http://www.ga.gov.au</geo:urlForMoreInformation>
            <geo:siteMap>Y</geo:siteMap>
            <geo:siteDiagram>Y</geo:siteDiagram>
            <geo:horizonMask>Y</geo:horizonMask>
            <geo:monumentDescription>Y</geo:monumentDescription>
            <geo:sitePictures>Y</geo:sitePictures>
            <geo:notes></geo:notes>
            <geo:antennaGraphicsWithDimensions></geo:antennaGraphicsWithDimensions>
            <geo:insertTextGraphicFromAntenna></geo:insertTextGraphicFromAntenna>
            <geo:DOI codeSpace="urn:ga-gov-au:self.moreInformation-type">TODO</geo:DOI>
        </geo:moreInformation>
    </geo:siteLog>
</geo:GeodesyML>


text:
<?hh // strict

class :h3 extends :xhp:html-element {
  category %flow;
  children (pcdata | %phrase)*;
  protected string $tagName = 'h3';
}


text:
<Record>
<Term>Fluzoperine</Term>
<SemanticType>Pharmacologic Substance</SemanticType>
<ParentTerm>Antiarrhythmic Agent</ParentTerm>
<ClassificationPath>Chemicals_and_Drugs_Kind/Drug, Food, Chemical or Biomedical Material/Pharmacologic Substance/Adjuvant/Cardiovascular Agent/Antiarrhythmic Agent/Fluzoperine</ClassificationPath>
<BroaderTerm>Fluzoperine</BroaderTerm>
<BroaderTerm>Chemicals_and_Drugs_Kind</BroaderTerm>
<BroaderTerm>Cardiovascular Agent</BroaderTerm>
<BroaderTerm>Pharmacologic Substance</BroaderTerm>
<BroaderTerm>Adjuvant</BroaderTerm>
<BroaderTerm>Drug, Food, Chemical or Biomedical Material</BroaderTerm>
<BroaderTerm>Antiarrhythmic Agent</BroaderTerm>
<Synonym>FLUZOPERINE</Synonym>
<Synonym>Fluzoperine</Synonym>
<Source>NCI Thesaurus</Source>
</Record>


text:
// Targeted by JavaCPP version 1.5.7: DO NOT EDIT THIS FILE

package org.tensorflow.internal.c_api;

import java.nio.*;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;

import static org.tensorflow.internal.c_api.global.tensorflow.*;

@Opaque @Properties(inherit = org.tensorflow.internal.c_api.presets.tensorflow.class)
public class TF_ShapeHandle extends Pointer {
    /** Empty constructor. Calls {@code super((Pointer)null)}. */
    public TF_ShapeHandle() { super((Pointer)null); }
    /** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */
    public TF_ShapeHandle(Pointer p) { super(p); }
}


text:
import os, inspect
import argparse
import subprocess

import sys, urllib, httplib
from datetime import datetime

import math
import numpy, scipy
import scipy.signal

from osgeo import gdal, gdal_array
from osgeo import osr
from osgeo import ogr

from which import *

import mapnik
from mapnik import DatasourceCache as c;

import config

class DEM:

	def __init__( self, tile, zone, force, bbox, target, infile ):
		self.hydroSHEDS_dir		 	= config.SRTM2_DIR
		self.HANDS_DIR		 		= config.SRTM2_DIR
		self.tile					= tile
		self.zone					= zone
		self.force					= force
		self.bbox					= bbox
		self.target					= target

		if zone and tile:
			self.dem_dir 			= os.path.join(self.hydroSHEDS_dir, zone, tile, tile+"_dem_bil")
			self.RasterXSize 		= 5855
			self.RasterYSize 		= 6142

		if bbox and target:
			self.dem_vrt 			= os.path.join(self.HANDS_DIR, config.HANDS_AREA+ "_dem.vrt")
			self.dem_dir 			= target
			self.tile				= "na"
			self.infile				= os.path.join(target, infile)

		print "DEM DIR", self.dem_dir

	def hillshade(self):
		src  = os.path.join(self.dem_dir, self.tile + "_dem_4326.tif")
		dest = os.path.join(self.dem_dir, self.tile + "_dem_hillshade_4326.tif")

		if not os.path.isfile(dest) or self.force:
			cmd = "gdaldem hillshade -co compress=lzw " + src + " " + dest
			print cmd
			err = os.system(cmd)
			if err != 0:
				print('ERROR: hillshade file could not be generated:', err)
				sys.exit(-1)

	def color_relief(self):
		print "Color Relief..."
		color_txt_file 	= "./dem_color_relief.txt"
		src  			= os.path.join(self.dem_dir, self.tile + "_dem_4326.tif")
		dest  			= os.path.join(self.dem_dir, self.tile + "_dem_color_relief_4326.tif")
		legend			= os.path.join(self.dem_dir, "na_dem_legend.png")

		ds = gdal.Open( src )
		if ds is None:
			print('ERROR: file no data:', src)
			sys.exit(-1)

		band 				= ds.GetRasterBand(1)
		self.RasterXSize 	= ds.RasterXSize
		self.RasterYSize 	= ds.RasterYSize

		(minv,maxv,mean, stddev) = band.GetStatistics(1,1)
		print '*** Min=%.3f, Max=%.3f Mean=%.3f Stdev=%.3f' % (minv,maxv,mean,stddev)

		# generate the color_relief.txt file
		mid_lower 	= (minv+mean)/2
		mid_higher 	= (maxv+mean)/2

		str =  "%.2f 110 220 110\n" % (minv)
		str += "%.2f 240 250 160\n" % (mid_lower)
		str += "%.2f 230 220 170\n" % (mean)
		str += "%.2f 220 220 220\n" % (mid_higher)
		str += "%.2f 250 250 250\n" % (maxv)

		if not os.path.isfile(color_txt_file) or self.force:
			f = open(color_txt_file, 'w')
			f.write(str)
			f.close()

		ds 		= None
		band 	= None

		if not os.path.isfile(dest) or self.force:
			cmd ="gdaldem color-relief " + src + " " + color_txt_file + " " + dest
			err = os.system(cmd)
			if err != 0:
				print('ERROR: color_relief file could not be generated:', err)
				sys.exit(-1)

		#if not os.path.isfile(legend) or self.force:
		#	if self.tile == "na":
		#		cmd ="hand_legend.py -l %.0f %.0f %.0f %0.f %0.f --dir %s " % (min, mid_lower, mean, mid_higher, max, self.target)
		#	else:
		#		cmd ="hand_legend.py -l %.0f %.0f %.0f %0.f %0.f -t %s -z %s" % (min, mid_lower, mean, mid_higher, max, self.tile, self.zone)

		#	print cmd
		#	err = os.system(cmd)
		#	if err != 0:
		#		print('ERROR: legend file could not be generated:', err)
		#		sys.exit(-1)

	def slopeshade(self):
		slope_txt_file 	= "./color_slope.txt"
		src  			= os.path.join(self.dem_dir, self.tile + "_dem_4326.tif")
		slope  			= os.path.join(self.dem_dir, self.tile + "_dem_slope_4326.tif")
		slopeshade		= os.path.join(self.dem_dir, self.tile + "_dem_slopeshade_4326.tif")

 		if not os.path.isfile(slope) or self.force:
			cmd = "gdaldem slope " + src + " " + slope
			print cmd
			err = os.system(cmd)
			if err != 0:
				print('ERROR: slope file could not be generated:', err)
				sys.exit(-1)

 		if not os.path.isfile(slope_txt_file):
			print "Creating ", slope_txt_file
			str =  "0 255 255 255\n"
			str += "90 0 0 0"
			f = open(slope_txt_file, 'w')
			f.write(str)
			f.close()

		if not os.path.isfile(slopeshade) or self.force:
			cmd ="gdaldem color-relief " +  slope + " " + slope_txt_file + " " + slopeshade
			print cmd
			err = os.system(cmd)
			if err != 0:
				print('ERROR: slopeshade file could not be generated:', err)
				sys.exit(-1)

	def water_relief(self):
		xml_file 		= os.path.join(self.dem_dir, "na_terrain.xml")
		slopeshade		= os.path.join(self.dem_dir, self.tile + "_dem_slopeshade_4326.tif")
		hillshade		= os.path.join(self.dem_dir, self.tile + "_dem_hillshade_4326.tif")
		color_relief	= os.path.join(self.dem_dir, self.tile + "_dem_color_relief_4326.tif")
		relief			= os.path.join(self.dem_dir, self.tile + "_dem_relief_4326.tif")
		flood			= None

		print "water_relief", color_relief

		if( self.tile == 'na'):
			water			= os.path.join(self.dem_dir, self.tile+"_water_image_transp.tif")
			#flood			= os.path.join(self.dem_dir, "outputfile_4326_hand.tif")
		else:
			water			= os.path.join(self.hydroSHEDS_dir, self.zone, self.tile, self.tile+"_water_image_transp.tif")

 		if not os.path.isfile(relief) or self.force:
			self.compose_relief( xml_file, slopeshade, hillshade, color_relief, relief, flood, water)

	def hand_relief(self):
		xml_file 		= os.path.join(self.dem_dir, "na_terrain.xml")
		slopeshade		= os.path.join(self.dem_dir, self.tile + "_dem_slopeshade_4326.tif")
		hillshade		= os.path.join(self.dem_dir, self.tile + "_dem_hillshade_4326.tif")
		color_relief	= os.path.join(self.dem_dir, self.tile + "_dem_color_relief_4326.tif")
		relief			= os.path.join(self.dem_dir, self.tile + "_dem_hand_relief_4326.tif")
		flood			= None

		if self.tile == 'na':
			water			= os.path.join(self.dem_dir, "hand_4326_transp.tif")
			flood			= os.path.join(self.dem_dir, "outputfile_4326_hand.tif")
		else:
			water			= os.path.join(self.HAND_DIR, self.zone, self.tile + "_hand_transp.tif")

 		if not os.path.isfile(relief) or self.force:
			self.compose_relief( xml_file, slopeshade, hillshade, color_relief, relief, flood, water)

	def compose_relief( self, xml_file, slopeshade, hillshade, color_relief, relief, flood, water):
		xml = "<Map srs='+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs'>\n"
		xml += "<Style name='color relief style'>\n"
		xml += "<Rule>\n"
		xml += "<RasterSymbolizer comp-op='src-over' />\n"
		xml += "</Rule>\n"
		xml += "</Style>\n"

		xml +=  "<Style name='slopeshade style'>\n"
		xml += "<Rule>\n"
		xml += "<RasterSymbolizer opacity='0.4' comp-op='multiply' />\n"
		xml += "</Rule>\n"
		xml += "</Style>\n"

		xml += "<Style name='hillshade style'>\n"
		xml += "<Rule>\n"
		xml += "<RasterSymbolizer opacity='0.6' comp-op='multiply' />\n"
		xml += "</Rule>\n"
		xml += "</Style>\n"

		xml += "<Style name='flood water'>\n"
		xml += "<Rule>\n"
		xml += "<RasterSymbolizer opacity='1'  />\n"
		xml += "</Rule>\n"
		xml += "</Style>\n"

		xml += "<Style name='water'>\n"
		xml += "<Rule>\n"
		xml += "<RasterSymbolizer opacity='1' comp-op='src-over'/>\n"
		xml += "</Rule>\n"
		xml += "</Style>\n"

		xml += "<Layer name='color relief'>\n"
		xml += "<StyleName>color relief style</StyleName>\n"
		xml += "<Datasource>\n"
		xml += "<Parameter name='type'>gdal</Parameter>\n"
		xml += "<Parameter name='file'>" + color_relief +"</Parameter>\n"
		xml += "<Parameter name='format'>tiff</Parameter>\n"
		xml += "</Datasource>\n"
		xml += "</Layer>\n"

		xml += "<Layer name='slopeshade'>\n"
		xml += "<StyleName>slopeshade style</StyleName>\n"
		xml += "<Datasource>\n"
		xml += "<Parameter name='type'>gdal</Parameter>\n"
		xml += "<Parameter name='file'>"+ slopeshade+"</Parameter>\n"
		xml += "<Parameter name='format'>tiff</Parameter>\n"
		xml += "</Datasource>\n"
		xml += "</Layer>\n"

		xml += "<Layer name='hillshade'>\n"
		xml += "<StyleName>hillshade style</StyleName>\n"
		xml += "<Datasource>\n"
		xml += "<Parameter name='type'>gdal</Parameter>\n"
		xml += "<Parameter name='file'>"+ hillshade+"</Parameter>\n"
		xml += "<Parameter name='format'>tiff</Parameter>\n"
		xml += "</Datasource>\n"
		xml += "</Layer>\n"

		if flood:
			xml += "<Layer name='flood water'>\n"
			xml += "<StyleName>flood water</StyleName>\n"
			xml += "<Datasource>\n"
			xml += "<Parameter name='type'>gdal</Parameter>\n"
			xml += "<Parameter name='file'>"+ flood +"</Parameter>\n"
			xml += "<Parameter name='format'>tiff</Parameter>\n"
			xml += "</Datasource>\n"
			xml += "</Layer>\n"

		xml += "<Layer name='water'>\n"
		xml += "<StyleName>water</StyleName>\n"
		xml += "<Datasource>\n"
		xml += "<Parameter name='type'>gdal</Parameter>\n"
		xml += "<Parameter name='file'>"+ water +"</Parameter>\n"
		xml += "<Parameter name='format'>tiff</Parameter>\n"
		xml += "</Datasource>\n"
		xml += "</Layer>\n"

		xml += "</Map>\n"
		f = open(xml_file, 'w')
		f.write(xml)
		f.close()

		print "Generating relief file:", color_relief, xml_file
		print self.RasterXSize, self.RasterYSize

		map = mapnik.Map(self.RasterXSize, self.RasterYSize)
		mapnik.load_map(map, xml_file)
		map.zoom_all()
		mapnik.render_to_file(map, relief)

	def metersToLatLng(self,ds,X,Y):
		srs = osr.SpatialReference()
		srs.ImportFromWkt(ds.GetProjection())
		srsLatLong = srs.CloneGeogCS()
		ct = osr.CoordinateTransformation(srs,srsLatLong)
		return ct.TransformPoint(X,Y)

	# create matching osm water layer
	def create_osm_water_layer(self):
		dem_img							= os.path.join(self.dem_dir, "na_dem_4326.tif")
		osm_surface_water_img 			= os.path.join(self.dem_dir, "na_water_image.tif")
		osm_surface_water_img_tif 		= os.path.join(self.dem_dir, "na_water_image.tif")
		osm_surface_water_transp_img 	= os.path.join(self.dem_dir, "na_water_image_transp.tif")

		ds 								= gdal.Open( dem_img )

		geotransform	 				= ds.GetGeoTransform()

		dx = geotransform[1] * ds.RasterXSize
		dy = geotransform[5] * ds.RasterYSize

		X1 = geotransform[0]
		Y1 = geotransform[3] + dy
		X2 = geotransform[0] + dx
		Y2 = geotransform[3]

		#print "meters", X1,Y1,X2,Y2

		LLC = self.metersToLatLng(ds,X1,Y1)
		URC = self.metersToLatLng(ds,X2,Y2)

 		if not os.path.isfile(osm_surface_water_img) or self.force:
			cmd = "python generate_image.py --mapfile %(map)s --name %(fname)s --bbox %(X1)f %(Y1)f %(X2)f %(Y2)f --img %(dx)d %(dy)d" % \
			{ 	'map': 'water_4326.xml', 'fname':osm_surface_water_img,
				'X1':LLC[0], 'Y1':LLC[1], 'X2':URC[0], 'Y2':URC[1],
				'dx': ds.RasterXSize, 'dy': ds.RasterYSize
			}
			print(cmd)

			err = os.system(cmd)
			if err != 0:
				print('ERROR: water file could not be generated:', err)
				sys.exit(-1)

 		self.transp_water_layer(dem_img, osm_surface_water_img_tif, osm_surface_water_transp_img)

		#print "Water done"
		ds = None

	def water_layer(self):
		water 			= os.path.join(self.hydroSHEDS_dir, self.zone, self.tile, self.tile+"_water_image.tif")
		water_transp	= os.path.join(self.hydroSHEDS_dir, self.zone, self.tile, self.tile+"_water_image_transp.tif")

		src  			= os.path.join(self.dem_dir, self.tile + "_dem_4326.tif")
		self.transp_water_layer(src, water, water_transp)

	def hand_layer(self):
		if self.tile == 'na':
			hand 			= os.path.join(self.dem_dir, "hand_4326.tif")
			hand_transp 	= os.path.join(self.dem_dir, "hand_4326_transp.tif")

		else:
			hand 			= os.path.join(self.HAND_DIR, self.zone, self.tile+"_hand.tif")
			hand_transp 	= os.path.join(self.HAND_DIR, self.zone, self.tile + "_hand_transp.tif")

		src  			= os.path.join(self.dem_dir, self.tile + "_dem_4326.tif")
		self.transp_water_layer(src, hand, hand_transp)

	# Convert to transparent and copy projection
	# Warning: this will fail if convert is not built with tiff delegate
	# PNG Driver will be used to create target tif file and gdalcopyproj will fail
	def transp_water_layer(self, src, water, water_transp):
		if self.force or not os.path.isfile(water_transp):
			cmd = "convert -transparent black " + water + " " + water_transp
			print cmd
			err = os.system(cmd)
			if err != 0:
				print('ERROR: water transparency file could not be generated:', err)
				sys.exit(-1)

			cmd = "gdalcopyproj.py "+ src + " " + water_transp
			print cmd
			err = os.system(cmd)
			if err != 0:
				print('ERROR: gdalcopyproj generated error:', err)
				sys.exit(-1)

	#
	# Subset DEM to bbox area
	#
	def subset(self):
		base_img 		= self.infile	#os.path.join(self.dem_dir, "outputfile_4326.tif")
		in_img 			= self.dem_vrt
		out_img			= os.path.join(self.dem_dir, "na_dem_4326.tif")

		if self.force or not os.path.isfile(out_img):
			cmd = "subset.py "+ base_img + " " + in_img + " " + out_img
			print cmd
			os.system(cmd)

	def water_from_dem(self):
		slope  			= os.path.join(self.dem_dir, self.tile + "_dem_slope_4326.tif")
		slope2  		= os.path.join(self.dem_dir, self.tile + "_dem_slope_4326_2.tif")
		data 			= gdal_array.LoadFile(slope)

		# De-speckle
		data = scipy.signal.medfilt2d(data, kernel_size=3)
		gdal_array.SaveArray(data.astype(numpy.int8), slope2, prototype=gdal.Open(slope))
		print "saved water from dem", slope2

#
# Main
#
if __name__ == '__main__':
	version_num = int(gdal.VersionInfo('VERSION_NUM'))
	if version_num < 1800: # because of GetGeoTransform(can_return_null)
		print('ERROR: Python bindings of GDAL 1.8.0 or later required')
		sys.exit(1)

	# make sure we have ImageMagick convert
	err = which("convert")
	if err == None:
		print "convert missing"
		sys.exit(-1)

	# make sure that mapnik as the gdal plugin
	if not 'gdal' in c.plugin_names():
		print "Missing 'gdal' input plugin in mapnik"
		sys.exit(-1)

	# make sure tiff delegate is present
	output = subprocess.check_output("convert --version | grep Delegates", shell=True)
	err = output.find('tiff')
	if err==-1:
		print "ImageMagick Convert does not have a tiff delegate... rebuild it!", output
		sys.exit(-1)

	parser 		= argparse.ArgumentParser(description='Generate DEM')
	apg_input 	= parser.add_argument_group('Input')
	apg_input.add_argument("-f", "--force", action='store_true', help="HydroSHEDS forces new water image to be generated")
	apg_input.add_argument("-v", "--verbose", action='store_true', help="Verbose")
	apg_input.add_argument("-d", "--scene",  nargs=1, help="Scene")

	options 	= parser.parse_args()

	force		= options.force
	verbose		= options.verbose
	scene		= options.scene[0]

	if scene[0:3] == "EO1":
		target_dir 	= os.path.join(config.EO1_DIR,scene+"_1T")
		fileName	= os.path.join(target_dir, "COMPOSITE_543_dn_4326.tif")
		print fileName
		ds = gdal.Open( fileName )
		if ds is None:
			print('ERROR: file no data:')
			sys.exit(-1)

		geotransform	= ds.GetGeoTransform()
		projection  	= ds.GetProjection()

		minX			= geotransform[0]
		maxY  			= geotransform[3]
		pres			= geotransform[1]

		maxX			= minX + ds.RasterXSize*pres
		minY			= maxY - ds.RasterXSize*pres

		bbox = [minX, minY, maxX, maxY]

		app = DEM( None, None, force, bbox, target_dir, "COMPOSITE_543_dn_4326.tif")
		#app.subset()
		#app.hillshade()
		#app.color_relief()
		#app.slopeshade()
		app.water_from_dem()

	#if tile and zone:
	#	print str(datetime.now()), "Starting processing of tile:"+tile[0]+" zone:"+zone[0]
	#	app = DEM( tile[0], zone[0], force, None, None, None)
	#	app.hillshade()
	#	app.color_relief()
	#	app.slopeshade()
	#	app.water_layer()
	#	app.water_relief()
	##	app.hand_layer()
	##	app.hand_relief()

	#if bbox and target_dir and infile:
	#	print str(datetime.now()), "Starting DEM processing for:", bbox, target_dir[0], infile[0]
	#	app = DEM( None, None, force, bbox, target_dir[0], infile[0])
	#	app.subset()
	#	app.hillshade()
	#	app.color_relief()
	#	app.slopeshade()
	#	app.create_osm_water_layer()
	#	app.water_relief()
		#app.hand_layer()
		#app.hand_relief()

	print str(datetime.now()), "Done."


text:
import { inject } from '../../mixins/registrable'

// Types
import { VNode } from 'vue'
import { ExtractVue } from '../../util/mixins'
import VAppBar from './VAppBar'

// Utilities
import { convertToUnit } from '../../util/helpers'
import { easeInOutCubic } from '../../services/goto/easing-patterns'

const base = inject<'VAppBar', typeof VAppBar>('VAppBar', 'v-app-bar-title', 'v-app-bar')

interface options extends ExtractVue<typeof base> {
  $refs: {
    content: Element
    placeholder: Element
  }
}

export default base.extend<options>().extend({
  name: 'v-app-bar-title',

  data: () => ({
    contentWidth: 0,
    left: 0,
    width: 0,
  }),

  watch: {
    '$vuetify.breakpoint.width': 'updateDimensions',
  },

  computed: {
    styles (): object {
      if (!this.contentWidth) return {}

      const min = this.width
      const max = this.contentWidth
      const ratio = easeInOutCubic(Math.min(1, this.VAppBar.scrollRatio * 1.5))
      return {
        width: convertToUnit(min + (max - min) * ratio),
        visibility: this.VAppBar.scrollRatio ? 'visible' : 'hidden',
      }
    },
  },

  mounted () {
    this.updateDimensions()
  },

  methods: {
    updateDimensions (): void {
      const dimensions = this.$refs.placeholder.getBoundingClientRect()
      this.width = dimensions.width
      this.left = dimensions.left
      this.contentWidth = this.$refs.content.scrollWidth
    },
  },

  render (h): VNode {
    return h('div', {
      class: 'v-toolbar__title v-app-bar-title',
    }, [
      h('div', {
        class: 'v-app-bar-title__content',
        style: this.styles,
        ref: 'content',
      }, [this.$slots.default]),
      h('div', {
        class: 'v-app-bar-title__placeholder',
        style: {
          visibility: this.VAppBar.scrollRatio ? 'hidden' : 'visible',
        },
        ref: 'placeholder',
      }, [this.$slots.default]),
    ])
  },
})


text:
package com.phei.netty.frame.fault;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @author lilinfeng
 * @date 2014年2月14日
 * @version 1.0
 */
public class TimeClient {

    public void connect(int port, String host) throws Exception {
	// 配置客户端NIO线程组
	EventLoopGroup group = new NioEventLoopGroup();
	try {
	    Bootstrap b = new Bootstrap();
	    b.group(group).channel(NioSocketChannel.class)
		    .option(ChannelOption.TCP_NODELAY, true)
		    .handler(new ChannelInitializer<SocketChannel>() {
			@Override
			public void initChannel(SocketChannel ch)
				throws Exception {

			    ch.pipeline().addLast(new TimeClientHandler());
			}
		    });

	    // 发起异步连接操作
	    ChannelFuture f = b.connect(host, port).sync();

	    // 当代客户端链路关闭
	    f.channel().closeFuture().sync();
	} finally {
	    // 优雅退出,释放NIO线程组
	    group.shutdownGracefully();
	}
    }

    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
	int port = 8080;
	if (args != null && args.length > 0) {
	    try {
		port = Integer.valueOf(args[0]);
	    } catch (NumberFormatException e) {
		// 采用默认值
	    }
	}
	new TimeClient().connect(port, "127.0.0.1");
    }
}


text:
package org.iotlabs.dashboard.utils;

import org.iotlabs.dashboard.httpexceptions.BaseHttpException;
import org.iotlabs.dashboard.literals.ContentType;
import spark.Response;

public class ResponseSetter {
    public static void setErrorResponse(Response errorResponse, BaseHttpException e) {
        errorResponse.type(ContentType.HTML);
        errorResponse.status(e.getCode());
        errorResponse.body(e.getBody());
    }
}


text:
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>JabitServer</title>
  <base href="/">

  <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500" rel="stylesheet">
  <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body class="mat-typography">
  <app-root>Loading...</app-root>
</body>
</html>


text:
import api from './api'
import * as m from './model'
import * as A from './actions'

export function stateReducer(state, action) {
  switch(action.type) {
    case A.LOADING:
      return state.withMutations(s => {
        m.setLoading(s, action.payload)
        if(action.payload === true)
          m.setLoadingGif(s)
      })

    case A.SET_GIF:
      return m.setGif(state, action.payload)

    default:
      return state
  }
}

export function taskReducer(dispatch, action, state) {
  switch(action.type) {
    case A.NEW_GIF:
      if( m.isLoading(state) )
        return false
      /* falls through */
    case A.SETUP:
      dispatch( A.loading(true) )

      return api.
        fetchNewGif( m.getTopic(state) ).
        then(src => { dispatch( A.setGif(src) ) }).
        catch(err => { alert(err.message); console.error(err.trace) }).
        complete(() => { dispatch( A.loading(false) ) })
    break

    default:
      return
  }
}


text:
<?php

namespace App\Repository;

use App\Entity\TicketPriority;
use Symfony\Bridge\Doctrine\RegistryInterface;
use Maps_red\TicketingBundle\Repository\TicketPriorityRepository as BaseTicketPriorityRepository;

/**
 * @method TicketPriority|null find($id, $lockMode = null, $lockVersion = null)
 * @method TicketPriority|null findOneBy(array $criteria, array $orderBy = null)
 * @method TicketPriority[]    findAll()
 * @method TicketPriority[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class TicketPriorityRepository extends BaseTicketPriorityRepository
{
    public function __construct(RegistryInterface $registry)
    {
        parent::__construct($registry, TicketPriority::class);
    }
}


text:
import argparse
import os
import sys
import errno

def open_file(output, counter):
    filename = "%s/%s/wiki_%s_sym" % (output, counter/10000, counter % 10000)
    if not os.path.exists(os.path.dirname(filename)):
        try:
            os.makedirs(os.path.dirname(filename))
        except OSError as exc: # Guard against race condition
            if exc.errno != errno.EEXIST:
                raise

    return open(filename, "w")

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-d', '--data_list', type=str, help="Input data list."
                        " and clean up.", required=True)
    parser.add_argument('-o', '--output', type=str, help="Output files."
                        " and clean up.", required=True)

    args = parser.parse_args()
    data_path = args.data_list
    output = args.output

    files = open(data_path).read().split()

    i = 1
    counter = 0
    max = 35
    current_file = open_file(output, counter)
    for f in files:
        current_data = open(f).read().split()
        for w in current_data:
            if i > max:
                current_file.close()
                counter += 1
                i = 1
                current_file = open("%s/wiki_%s_sym" % (output, counter), "w")
            if i != 1:
                current_file.write(" ")
            current_file.write(w)
            i += 1

    current_file.close()


text:
package com.opengamma.livedata.cogda.msg;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotEquals;

import org.fudgemsg.MutableFudgeMsg;
import org.testng.annotations.Test;

import com.opengamma.id.ExternalId;
import com.opengamma.util.fudgemsg.OpenGammaFudgeContext;
import com.opengamma.util.test.TestGroup;

/**
 * Tests for {@link CogdaLiveDataUpdateMessage}.
 */
@Test(groups = TestGroup.UNIT)
public class CogdaLiveDataUpdateMessageTest {
  private static final ExternalId SUBSCRIPTION_ID = ExternalId.of("a", "b");
  private static final String NORMALIZATION_SCHEME = "scheme";
  private static final MutableFudgeMsg MSG = OpenGammaFudgeContext.getInstance().newMessage();
  static {
    MSG.add("field", "value");
  }

  /**
   * Tests that the subscription id cannot be null.
   */
  @Test(expectedExceptions = IllegalArgumentException.class)
  public void testNullId() {
    new CogdaLiveDataUpdateMessage().setSubscriptionId(null);
  }

  /**
   * Tests that the values cannot be null.
   */
  @Test(expectedExceptions = IllegalArgumentException.class)
  public void testNullValues() {
    new CogdaLiveDataUpdateMessage().setValues(null);
  }

  /**
   * Tests the object.
   */
  @Test
  public void testObject() {
    final CogdaLiveDataUpdateMessage message = new CogdaLiveDataUpdateMessage();
    message.setNormalizationScheme(NORMALIZATION_SCHEME);
    message.setSubscriptionId(SUBSCRIPTION_ID);
    message.setValues(MSG);
    assertEquals(message, message);
    assertNotEquals(null, message);
    assertNotEquals(MSG, message);
    assertEquals(message.toString(), "CogdaLiveDataUpdateMessage{subscriptionId=a~b, normalizationScheme=scheme, values=FudgeMsg[field => value]}");
    final CogdaLiveDataUpdateMessage other = new CogdaLiveDataUpdateMessage();
    other.setNormalizationScheme(NORMALIZATION_SCHEME);
    other.setSubscriptionId(SUBSCRIPTION_ID);
    other.setValues(MSG);
    assertEquals(message, other);
    assertEquals(message.hashCode(), other.hashCode());
    other.setNormalizationScheme("scheme1");
    assertNotEquals(message, other);
    other.setNormalizationScheme(NORMALIZATION_SCHEME);
    other.setSubscriptionId(ExternalId.of("b", "c"));
    assertNotEquals(message, other);
    other.setSubscriptionId(SUBSCRIPTION_ID);
    other.setValues(OpenGammaFudgeContext.getInstance().newMessage());
    assertNotEquals(message, other);
  }

  /**
   * Tests the bean.
   */
  @Test
  public void testBean() {
    final CogdaLiveDataUpdateMessage message = new CogdaLiveDataUpdateMessage();
    message.setNormalizationScheme(NORMALIZATION_SCHEME);
    message.setSubscriptionId(SUBSCRIPTION_ID);
    message.setValues(MSG);
    assertEquals(message.metaBean().normalizationScheme().get(message), NORMALIZATION_SCHEME);
    assertEquals(message.metaBean().subscriptionId().get(message), SUBSCRIPTION_ID);
    assertEquals(message.metaBean().values().get(message), MSG);
    assertEquals(message.property("normalizationScheme").get(), NORMALIZATION_SCHEME);
    assertEquals(message.property("subscriptionId").get(), SUBSCRIPTION_ID);
    assertEquals(message.property("values").get(), MSG);
  }
}


text:
img: https://storage.googleapis.com/mail-attachments
subject: "Welcome to Inner Engineering Total program"
preview: https://rawgit.com/ishacrm/emails/master/dist/au/2017/ie-4day-confirmation.html
---
<container>

    {{> spacer }}

    <row class="collapse no-vpad">
        <columns large="2" small="4">
            <wrapper class="logo">

            </wrapper>
        </columns>
        <columns large="10" small="10">
            <wrapper class="header">

Inner Engineering Total (4 Day)

Program Registration

            </wrapper>
        </columns>
    </row>
    {{> drop-shadow }}
    <row>
        <columns>
            <spacer size="16"></spacer>
        </columns>
    </row>
    <row>
        <columns>

Dear {{{{raw}}}}{{FIRST_NAME}}{{{{/raw}}}},

Greetings!

With only one day to go for the Inner Engineering Total program, here is some quick info for your reference.

On Thursday Mar 30, Registrations open from 5pm and program starts at 6pm.  Please make sure to arrive at least 30 minutes before to allow time for registration and settling down. Also include additional time to cater for traffic delays and parking.

        </columns>
    </row>
    <row>
        <columns>

Guest Registration

You can also bring along your family and friends (anyone over the age of 15) to accompany you for first part of the session on 30th March. No registration is required. They can simply walk-in. Post this session,  if they wish they may register for the program if places are still available.

            <callout class="secondary">

Program Details

Session Timings:

Thu 30 Mar: 6:00 PM to 9:15 PM

Fri 31 Mar: 6:00 PM to 9:15 PM

Sat 01 Apr: 8:00 AM to 7:00 PM*

Sun 02 Apr: 7:00 AM to 7:00 PM*

Venue: Brunswick Town Hall
                [MAP]

                Address: 233 Sydney Rd, Brunswick VIC 3056

                Please note that:

Attendance for all the sessions is mandatory.

Doors will close at the session start time and latecomers will be not be allowed inside the hall.

Additional Information

Breakfast and lunch will be provided on Saturday & Sunday.

Please wear loose comfortable clothing and bring a yoga mat or a cushion to sit comfortably on the floor.

            </callout>
        </columns>
    </row>
    {{> drop-shadow }}
    <row class="section-header">
        <columns>
            Preparation for the Program
        </columns>
    </row>
    <row>
        <columns>

                We encourage you to practice Isha Kriya meditation as it will be a supportive tool to prepare you for the program.

                Isha Kriya is a free, simple and powerful meditation, which has been specially designed by Sadhguru and can be
                accessed online at www.ishakriya.com or by downloading the mobile application
                through Google Play / iTunes Store.

                Feel free to share Isha Kriya with family and friends as well.

We look forward to seeing you at the program.

                Pranam,

                Isha Volunteers

        </columns>
    </row>
    {{> drop-shadow }}
    {{> spacer }}

    {{> footer-au }}

    {{> spacer }}

</container>


text:
if ENV['MY_RUBY_HOME'] && ENV['MY_RUBY_HOME'].include?('rvm')
  begin
    require 'rvm'
    RVM.use_from_path! File.dirname(File.dirname(__FILE__))
  rescue LoadError
    raise "RVM gem is currently unavailable."
  end
end

# If you're not using Bundler at all, remove lines bellow
ENV['BUNDLE_GEMFILE'] = File.expand_path('../Gemfile',
                                         File.dirname(__FILE__))
require 'bundler/setup'


text:
<?php

/**
 * Class migration DB CreateTableLeagues
 *
 * For documentation on the methods of migration
 *
 * @see http://blog.phigrate.org/doc/methodsMigrations
 *
 * @category  Rca
 * @package   migrate
 * @author    Manuel Hervo <manuel.hervo@gmail.com>
 * @link      https://github.com/Azema/rc-infosAPI for the canonical source repository
 * @license   https://github.com/Azema/rc-infosAPI/LICENCE New BSD License
 * @copyright Copyright (c) 2013 Manuel Hervo. (https://github.com/Azema)
 */
class CreateTableLeagues extends Phigrate_Migration_Base
{
    /**
     * up
     *
     * @return void
     */
    public function up()
    {
        $this->createTable('leagues', array(
            'options' => 'Engine=InnoDB DEFAULT CHARSET=utf8',
        ))
            ->column('name', 'string')
            ->column('president', 'string')
            ->column('address', 'string')
            ->column('postCode', 'string', array('length' => 10))
            ->column('city', 'string')
            ->column('email', 'string')
            ->column('phone', 'string', array('length' => 15))
            ->column('siteWeb', 'string')
            ->column('createdAt', 'timestamp', array(
                'null' => false,
                'default' => '0000-00-00 00:00',
            ))
            ->column('updatedAt', 'timestamp', array(
                'update'  => 'CURRENT_TIMESTAMP',
                'default' => 'CURRENT_TIMESTAMP',
            ))
            ->finish();
        // Ajout de la relation entre les clubs et les ligues
        $this->addColumn('clubs', 'leagueId', 'integer', array(
            'null'     => false,
            'unsigned' => true,
        ));
        $this->addForeignKey('clubs', 'leagueId', 'leagues', 'id');
    }

    /**
     * down
     *
     * @return void
     */
    public function down()
    {
        $this->removeForeignKey('clubs', 'leagueId', 'leagues', 'id');
        $this->removeColumn('clubs', 'leagueId');
        $this->dropTable('leagues');
    }
}


text:
package com.google.errorprone.bugpatterns.testdata;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Locale;

/** @author alexeagle@google.com (Alex Eagle) */
public class ReturnValueIgnoredPositiveCases {
  String a = "thing";

  // BUG: Diagnostic contains: Return value of 'valueOf' must be used
  private Runnable r = () -> String.valueOf("");

  { // String methods
    // BUG: Diagnostic contains: remove this line
    String.format("%d", 10);
    // BUG: Diagnostic contains: remove this line
    String.format("%d", 10).trim();
    // BUG: Diagnostic contains: remove this line
    java.lang.String.format("%d", 10).trim();
    // BUG: Diagnostic contains: a = a.intern()
    a.intern();
    // BUG: Diagnostic contains: a = a.trim()
    a.trim();
    // BUG: Diagnostic contains: a = a.trim().concat("b")
    a.trim().concat("b");
    // BUG: Diagnostic contains: a = a.concat("append this")
    a.concat("append this");
    // BUG: Diagnostic contains: a = a.replace('t', 'b')
    a.replace('t', 'b');
    // BUG: Diagnostic contains: a = a.replace("thi", "fli")
    a.replace("thi", "fli");
    // BUG: Diagnostic contains: a = a.replaceAll("i", "b")
    a.replaceAll("i", "b");
    // BUG: Diagnostic contains: a = a.replaceFirst("a", "b")
    a.replaceFirst("a", "b");
    // BUG: Diagnostic contains: a = a.toLowerCase()
    a.toLowerCase();
    // BUG: Diagnostic contains: a = a.toLowerCase(Locale.ENGLISH)
    a.toLowerCase(Locale.ENGLISH);
    // BUG: Diagnostic contains: a = a.toUpperCase()
    a.toUpperCase();
    // BUG: Diagnostic contains: a = a.toUpperCase(Locale.ENGLISH)
    a.toUpperCase(Locale.ENGLISH);
    // BUG: Diagnostic contains: a = a.substring(0)
    a.substring(0);
    // BUG: Diagnostic contains: a = a.substring(0, 1)
    a.substring(0, 1);
  }

  StringBuffer sb = new StringBuffer("hello");

  {
    // BUG: Diagnostic contains: remove this line
    sb.toString().trim();
  }

  BigInteger b = new BigInteger("123456789");

  { // BigInteger methods
    // BUG: Diagnostic contains: b = b.add(new BigInteger("3"))
    b.add(new BigInteger("3"));
    // BUG: Diagnostic contains: b = b.abs()
    b.abs();
    // BUG: Diagnostic contains: b = b.shiftLeft(3)
    b.shiftLeft(3);
    // BUG: Diagnostic contains: b = b.subtract(BigInteger.TEN)
    b.subtract(BigInteger.TEN);
  }

  BigDecimal c = new BigDecimal("1234.5678");

  { // BigDecimal methods
    // BUG: Diagnostic contains: c = c.add(new BigDecimal("1.3"))
    c.add(new BigDecimal("1.3"));
    // BUG: Diagnostic contains: c = c.abs()
    c.abs();
    // BUG: Diagnostic contains: c = c.divide(new BigDecimal("4.5"))
    c.divide(new BigDecimal("4.5"));
    // BUG: Diagnostic contains: remove this line
    new BigDecimal("10").add(c);
  }

  Path p = Paths.get("foo/bar/baz");

  { // Path methods
    // BUG: Diagnostic contains: p = p.getFileName();
    p.getFileName();
    // BUG: Diagnostic contains: p = p.getName(0);
    p.getName(0);
    // BUG: Diagnostic contains: p = p.getParent();
    p.getParent();
    // BUG: Diagnostic contains: p = p.getRoot();
    p.getRoot();
    // BUG: Diagnostic contains: p = p.normalize();
    p.normalize();
    // BUG: Diagnostic contains: p = p.relativize(p);
    p.relativize(p);
    // BUG: Diagnostic contains: p = p.resolve(p);
    p.resolve(p);
    // BUG: Diagnostic contains: p = p.resolve("string");
    p.resolve("string");
    // BUG: Diagnostic contains: p = p.resolveSibling(p);
    p.resolveSibling(p);
    // BUG: Diagnostic contains: p = p.resolveSibling("string");
    p.resolveSibling("string");
    // BUG: Diagnostic contains: p = p.subpath(0, 1);
    p.subpath(0, 1);
    // BUG: Diagnostic contains: p = p.toAbsolutePath();
    p.toAbsolutePath();
    try {
      // BUG: Diagnostic contains: p = p.toRealPath();
      p.toRealPath();
    } catch (IOException e) {
    }
  }

  int[] numbers = {5, 4, 3, 2, 1};
  Object[] objects = {new Object(), new Object()};

  { // Arrays methods
    // BUG: Diagnostic contains: Return value of 'asList' must be used
    Arrays.asList(5, 4, 3, 2, 1);
    // BUG: Diagnostic contains: Return value of 'binarySearch' must be used
    Arrays.binarySearch(numbers, 3);
    // BUG: Diagnostic contains: Return value of 'copyOf' must be used
    Arrays.copyOf(numbers, 3);
    // BUG: Diagnostic contains: Return value of 'copyOfRange' must be used
    Arrays.copyOfRange(numbers, 1, 3);
    // BUG: Diagnostic contains: Return value of 'deepEquals' must be used
    Arrays.deepEquals(objects, objects);
    // BUG: Diagnostic contains: Return value of 'deepHashCode' must be used
    Arrays.deepHashCode(objects);
    // BUG: Diagnostic contains: Return value of 'deepToString' must be used
    Arrays.deepToString(objects);
    // BUG: Diagnostic contains: Return value of 'equals' must be used
    Arrays.equals(objects, objects);
    // BUG: Diagnostic contains: Return value of 'hashCode' must be used
    Arrays.hashCode(objects);
    // BUG: Diagnostic contains: Return value of 'toString' must be used
    Arrays.toString(objects);
  }
}


text:
package io.elegie.luchess.pgn.impl.tokens;

import io.elegie.luchess.pgn.api.TokenType;
import io.elegie.luchess.pgn.impl.tokens.helpers.OneMatchTokenTest;

@SuppressWarnings("javadoc")
public class PromotionTokenTest extends OneMatchTokenTest {

    public PromotionTokenTest() {
        super(PromotionToken.class, TokenType.PROMOTION, '=');
    }

}


text:
const dotenv = require('dotenv');
const path = require('path');
const defaultsDeep = require('lodash.defaultsdeep');
const lodashClone = require('lodash.clone');
const lodashMerge = require('lodash.merge');
const CI_Info = require('ci-info');
const Defaults = require('./defaults.js');
const Utils = require('../utils');
const {Logger, isObject} = Utils;

class Settings {

  static get DEFAULT_ENV() {
    return 'default';
  }

  static get DEFAULTS() {
    return Defaults;
  }

  static parse(settings = {}, baseSettings = {}, argv = {}, testEnv = null) {
    let instanceSettings = new Settings(baseSettings, argv);
    instanceSettings.init(testEnv, settings);

    return instanceSettings.settings;
  }

  static setDefaults(settings) {
    defaultsDeep(settings, Settings.DEFAULTS);

    if (!settings.unit_tests_mode) {
      settings.skip_testcases_on_fail = settings.skip_testcases_on_fail ||
        typeof settings.skip_testcases_on_fail == 'undefined';
    }
  }

  get testWorkersEnabled() {
    return this.argv.parallel === true || this.settings.test_workers === true || this.settings.test_workers && this.settings.test_workers.enabled;
  }

  constructor(baseSettings = null, argv = {}) {
    this.baseSettings = baseSettings || {};
    this.argv = argv;
    this.testEnv = '';

    let defaults = lodashClone(Settings.DEFAULTS, true);
    this.settings = Object.assign({}, defaults);

    // copy all other properties outside the "test_settings" environments
    Object.keys(this.baseSettings).forEach(key => {
      if (key === 'test_settings') {
        return;
      }

      let copyVal = lodashClone(this.baseSettings[key], true);

      if (isObject(this.settings[key])) {
        Object.assign(this.settings[key], copyVal);
      } else {
        this.settings[key] = copyVal;
      }
    });
  }

  adaptSettings(settings) {
    lodashMerge(this.settings, settings);

    this.setCliOptions();
    this.setScreenshotsOptions();
    this.setScreenshotsPath();
    this.setUnitTestsMode();
    this.setParallelMode();
    this.setTestRunner();
    this.setWebdriverSettings();

    if (typeof this.settings.src_folders == 'string') {
      this.settings.src_folders = [this.settings.src_folders];
    }

    if (typeof this.settings.skipgroup == 'string' && this.settings.skipgroup.length > 0) {
      this.settings.skipgroup = this.settings.skipgroup.split(',');
    }

    return this;
  }

  setParallelMode() {
    const Concurrency = require('../runner/concurrency/concurrency.js');

    if (Concurrency.isChildProcess()) {
      this.settings.parallel_mode = true;
    }

    const envArray = this.testEnv.split(',');
    if (envArray.length > 1 && this.testWorkersEnabled) {
      if (typeof this.settings.test_workers == 'boolean') {
        this.settings.test_workers = {
          enabled: this.settings.test_workers
        };
        this.baseSettings.test_workers = {
          enabled: this.baseSettings.test_workers
        };
      }

      this.settings.test_workers.enabled = false;
      this.baseSettings.test_workers.enabled = false;
      this.settings.testWorkersEnabled = false;
      Logger.error('Test workers are disabled when running multiple test environments in parallel.\n');
    } else {
      this.settings.testWorkersEnabled = this.testWorkersEnabled;
    }

    return this;
  }

  setTestRunner() {
    if (typeof this.settings.test_runner == 'string') {
      this.settings.test_runner = {
        type: this.settings.test_runner,
        options: {}
      };
    }

    return this;
  }

  setWebdriverSettings() {
    if (this.settings.selenium && this.settings.selenium.start_process) {
      lodashMerge(this.settings.webdriver, this.settings.selenium);
    } else if (this.settings.selenium) {
      defaultsDeep(this.settings.webdriver, this.settings.selenium);
    }

    if (this.settings.start_session === undefined && this.settings.webdriver.start_session !== undefined) {
      this.settings.start_session = this.settings.webdriver.start_session;
    }

    if (this.settings.request_timeout_options) {
      defaultsDeep(this.settings.webdriver.timeout_options, this.settings.request_timeout_options);
    }

    const protocol = this.settings.webdriver.ssl ? 'https' : 'http';

    if (!this.settings.webdriver.host) {
      this.settings.webdriver.host = 'localhost';
    }

    this.setSeleniumPort();
    this.setDefaultPort();

    const {port, host} = this.settings.webdriver;
    this.settings.webdriver.url = `${protocol}://${host}:${port}`;

    if (this.settings.selenium) {
      this.settings.selenium.url = this.settings.webdriver.url;
    }

    return this;
  }

  setSeleniumPort() {
    const seleniumPort = this.settings.selenium_port || this.settings.seleniumPort;
    const {webdriver} = this.settings;

    if (!webdriver.port) {
      this.settings.webdriver.port = seleniumPort;
    }

    return this;
  }

  setDefaultPort() {
    const {webdriver} = this.settings;

    if (webdriver.port !== undefined) {
      return this;
    }

    const WDServer = require('../runner/webdriver-server.js');
    const Driver = WDServer.getWebDriverImpl(this.settings);
    if (Driver) {
      this.settings.webdriver.port = Driver.DEFAULT_PORT;
    }

    return this;
  }

  setUnitTestsMode() {
    if (this.settings.unit_tests_mode) {
      this.settings.webdriver.start_process = false;
      this.settings.webdriver.start_session = false;
      this.settings.start_session = false;
      this.settings.detailed_output = false;
      this.settings.output_timestamp = false;
    }

    return this;
  }

  inheritFromDefaultEnv() {
    if (!this.baseSettings.test_settings) {
      return this;
    }

    const defaultEnvSettings = this.baseSettings.test_settings[Settings.DEFAULT_ENV] || {};
    lodashMerge(this.settings, defaultEnvSettings);

    if (!this.testEnv || this.testEnv === Settings.DEFAULT_ENV) {
      return this;
    }

    const testEnvSettings = this.baseSettings.test_settings[this.testEnv] || {};
    this.inheritFromSuperEnv(testEnvSettings);
    defaultsDeep(testEnvSettings, defaultEnvSettings);
    lodashMerge(this.settings, testEnvSettings);

    return this;
  }

  inheritFromSuperEnv(testEnvSettings) {
    if (testEnvSettings.extends) {
      const superEnv = this.baseSettings.test_settings[testEnvSettings.extends] || {};
      delete testEnvSettings.extends;
      defaultsDeep(testEnvSettings, superEnv);

      return this.inheritFromSuperEnv(testEnvSettings);
    }

    return testEnvSettings;
  }

  /**
   * @deprecated
   * @param settings
   */
  persistGlobals(settings) {
    if (this.settings.persist_globals === true && settings.globals) {
      let globals = settings.globals;
      Object.keys(this.settings.globals).forEach(key => {
        globals[key] = this.settings.globals[key];
      });

      this.settings.globals = globals;
    }
  }

  setScreenshotsOptions() {
    if (isObject(this.settings.screenshots)) {
      this.settings.screenshots.path = path.resolve(this.settings.screenshots.path);
    } else {
      const enabled = this.settings.screenshots === true;
      this.settings.screenshots = Object.assign({}, Defaults.screenshots, {enabled});
    }

    return this;
  }

  setScreenshotsPath() {
    this.settings.screenshotsPath = this.settings.screenshots.path;

    return this;
  }

  setCliOptions() {
    if (this.argv.verbose) {
      this.settings.silent = false;
    }

    const cliOverwrites = {
      output_folder: this.argv.output,
      filename_filter: this.argv.filter,
      tag_filter: this.argv.tag,
      skipgroup: this.argv.skipgroup,
      skiptags: this.argv.skiptags
    };

    Object.keys(cliOverwrites).forEach(key => {
      if (cliOverwrites[key] !== undefined && cliOverwrites[key] !== null) {
        this.settings[key] = cliOverwrites[key];
      }
    });

    // TODO: add support for overwriting any setting

    return this;
  }

  /**
   * Looks for pattern ${VAR_NAME} in settings
   * @param {Object} [target]
   */
  static replaceEnvVariables(target) {
    for (const key in target) {
      switch (typeof target[key]) {
        case 'object':
          Settings.replaceEnvVariables(target[key]);
          break;

        case 'string':
          target[key] = target[key].replace(/\$\{(\w+)\}/g, function(match, varName) {
            return process.env[varName] || '${' + varName + '}';
          });
          break;
      }
    }

    return this;
  }

  sortSettings() {
    const sortedSettings = {};
    Object.keys(this.settings).sort().forEach(key => {
      sortedSettings[key] = this.settings[key];
    });

    this.settings = sortedSettings;
  }

  setColorOutput() {
    const {isCI, CIRCLE, JENKINS, NETLIFY, TRAVIS, GITLAB, BUILDKITE} = CI_Info;
    let coloringSupport = CIRCLE || JENKINS || NETLIFY || TRAVIS || GITLAB || BUILDKITE;

    if (isCI && !coloringSupport) {
      this.settings.disable_colors = true;
    }
  }

  /**
   * Validates and parses the test settings
   *
   * @param {string} [testEnv]
   * @param {object} [settings]
   */
  init(testEnv = null, settings = {}) {
    if (testEnv) {
      this.testEnv = testEnv;
    }

    this.inheritFromDefaultEnv();
    this.adaptSettings(settings);
    this.persistGlobals(settings);

    dotenv.config(this.settings.dotenv);
    Settings.replaceEnvVariables(this.settings);

    this.sortSettings();
    this.setColorOutput();
  }
}

module.exports = Settings;