text:
package com.dev9.crash.bad;

import com.dev9.crash.AbstractBadThing;
import org.springframework.stereotype.Service;

@Service
public class ExecuteBadSql extends AbstractBadThing {

    public String getBadThingDescription() {
        String result = "Looks for a valid driver (" + DatabaseMislocator.driver
                + ") and connection string (" + DatabaseMislocator.url
                + ") using username/password (" + DatabaseMislocator.username + ","
                + DatabaseMislocator.password + ") and execute meaningless SQL. ";
        return result;
    }

    @Override
    public String getBadThingId() {
        return "bad-sql";
    }

    @Override
    public String getBadThingName() {
        return "Execute Meaningless SQL (SELECT asdf)";
    }

    @Override
    public String doBadThing() throws Exception {
        new DatabaseMislocator().nonsensicalSQL();
        return null;
    }
}


text:
namespace {

int g_export_call_count = 0;

}  // namespace

extern "C" __declspec(dllexport) void ExportedApi() {
  g_export_call_count++;
}

extern "C" __declspec(dllexport) int ExportedApiCallCount() {
  return g_export_call_count;
}

BOOL APIENTRY DllMain(HMODULE module, DWORD reason, LPVOID reserved) {
  return TRUE;
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.flink.table.client.cli;

import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.table.client.gateway.ResultDescriptor;
import org.apache.flink.table.client.gateway.SqlExecutionException;
import org.apache.flink.table.client.gateway.TypedResult;
import org.apache.flink.types.Row;

import org.jline.keymap.KeyMap;
import org.jline.utils.AttributedString;
import org.jline.utils.AttributedStringBuilder;
import org.jline.utils.AttributedStyle;
import org.jline.utils.InfoCmp.Capability;

import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import static org.apache.flink.table.client.cli.CliUtils.TIME_FORMATTER;
import static org.apache.flink.table.client.cli.CliUtils.formatTwoLineHelpOptions;
import static org.apache.flink.table.client.cli.CliUtils.normalizeColumn;
import static org.apache.flink.table.client.cli.CliUtils.repeatChar;
import static org.jline.keymap.KeyMap.ctrl;
import static org.jline.keymap.KeyMap.esc;
import static org.jline.keymap.KeyMap.key;

/**
 * CLI view for retrieving and displaying a table.
 */
public class CliTableResultView extends CliResultView<CliTableResultView.ResultTableOperation> {

	private int pageCount;
	private int page;
	private LocalTime lastRetrieval;
	private int previousResultsPage;

	private static final int DEFAULT_REFRESH_INTERVAL = 3; // every 1s
	private static final int MIN_REFRESH_INTERVAL = 1; // every 100ms
	private static final int LAST_PAGE = 0;

	public CliTableResultView(CliClient client, ResultDescriptor resultDescriptor) {
		super(client, resultDescriptor);

		refreshInterval = DEFAULT_REFRESH_INTERVAL;
		pageCount = 1;
		page = LAST_PAGE;

		previousResults = Collections.emptyList();
		previousResultsPage = 1;
		results = Collections.emptyList();
	}

	// --------------------------------------------------------------------------------------------

	@Override
	protected String[] getRow(String[] resultRow) {
		return resultRow;
	}

	@Override
	protected int computeColumnWidth(int idx) {
		return MAX_COLUMN_WIDTH;
	}

	@Override
	protected void refresh() {
		// take snapshot
		TypedResult<Integer> result;
		try {
			result = client.getExecutor().snapshotResult(client.getContext(), resultDescriptor.getResultId(), getVisibleMainHeight());
		} catch (SqlExecutionException e) {
			close(e);
			return;
		}

		// stop retrieval if job is done
		if (result.getType() == TypedResult.ResultType.EOS) {
			stopRetrieval();
		}
		// update page
		else if (result.getType() == TypedResult.ResultType.PAYLOAD) {
			int newPageCount = result.getPayload();
			pageCount = newPageCount;
			if (page > newPageCount) {
				page = LAST_PAGE;
			}
			updatePage();
		}

		lastRetrieval = LocalTime.now();

		// reset view
		resetAllParts();
	}

	@Override
	protected KeyMap<ResultTableOperation> getKeys() {
		final KeyMap<ResultTableOperation> keys = new KeyMap<>();
		keys.setAmbiguousTimeout(200); // make ESC quicker
		keys.bind(ResultTableOperation.QUIT, "q", "Q", esc(), ctrl('c'));
		keys.bind(ResultTableOperation.REFRESH, "r", "R", key(client.getTerminal(), Capability.key_f5));
		keys.bind(ResultTableOperation.UP, "w", "W", key(client.getTerminal(), Capability.key_up));
		keys.bind(ResultTableOperation.DOWN, "s", "S", key(client.getTerminal(), Capability.key_down));
		keys.bind(ResultTableOperation.LEFT, "a", "A", key(client.getTerminal(), Capability.key_left));
		keys.bind(ResultTableOperation.RIGHT, "d", "D", key(client.getTerminal(), Capability.key_right));
		keys.bind(ResultTableOperation.OPEN, "o", "O", "\r");
		keys.bind(ResultTableOperation.GOTO, "g", "G");
		keys.bind(ResultTableOperation.NEXT, "n", "N");
		keys.bind(ResultTableOperation.PREV, "p", "P");
		keys.bind(ResultTableOperation.LAST, "l", "L", key(client.getTerminal(), Capability.key_end));
		keys.bind(ResultTableOperation.INC_REFRESH, "+");
		keys.bind(ResultTableOperation.DEC_REFRESH, "-");
		return keys;
	}

	@Override
	protected void evaluate(ResultTableOperation operation, String binding) {
		switch (operation) {
			case QUIT:
				close();
				break;
			case REFRESH:
				refresh();
				break;
			case UP:
				selectRowUp();
				break;
			case DOWN:
				selectRowDown();
				break;
			case OPEN:
				openRow();
				break;
			case GOTO:
				gotoPage();
				break;
			case NEXT:
				gotoNextPage();
				break;
			case PREV:
				gotoPreviousPage();
				break;
			case LAST:
				gotoLastPage();
				break;
			case LEFT:
				scrollLeft();
				break;
			case RIGHT:
				scrollRight();
				break;
			case INC_REFRESH:
				increaseRefreshInterval();
				break;
			case DEC_REFRESH:
				decreaseRefreshInterval(MIN_REFRESH_INTERVAL);
				break;
		}
	}

	@Override
	protected String getTitle() {
		return CliStrings.RESULT_TITLE + " (" + CliStrings.RESULT_TABLE + ")";
	}

	@Override
	protected List<AttributedString> computeHeaderLines() {
		final AttributedStringBuilder statusLine = new AttributedStringBuilder();
		statusLine.style(AttributedStyle.INVERSE);
		// left
		final String left;
		if (isRetrieving()) {
			left = CliStrings.DEFAULT_MARGIN + CliStrings.RESULT_REFRESH_INTERVAL + ' ' + REFRESH_INTERVALS.get(refreshInterval).f0;
		} else {
			left = CliStrings.DEFAULT_MARGIN + CliStrings.RESULT_STOPPED;
		}
		// middle
		final StringBuilder middleBuilder = new StringBuilder();
		middleBuilder.append(CliStrings.RESULT_PAGE);
		middleBuilder.append(' ');
		if (page == LAST_PAGE) {
			middleBuilder.append(CliStrings.RESULT_LAST_PAGE);
		} else {
			middleBuilder.append(page);
		}
		middleBuilder.append(CliStrings.RESULT_PAGE_OF);
		middleBuilder.append(pageCount);
		final String middle = middleBuilder.toString();
		// right
		final String right;
		if (lastRetrieval == null) {
			right = CliStrings.RESULT_LAST_REFRESH + ' ' + CliStrings.RESULT_REFRESH_UNKNOWN + CliStrings.DEFAULT_MARGIN;
		} else {
			right = CliStrings.RESULT_LAST_REFRESH + ' ' + lastRetrieval.format(TIME_FORMATTER) + CliStrings.DEFAULT_MARGIN;
		}
		// all together
		final int totalLeftSpace = getWidth() - middle.length();
		final int leftSpace = totalLeftSpace / 2 - left.length();
		statusLine.append(left);
		repeatChar(statusLine, ' ', leftSpace);
		statusLine.append(middle);
		final int rightSpacing = getWidth() - statusLine.length() - right.length();
		repeatChar(statusLine, ' ', rightSpacing);
		statusLine.append(right);

		return Arrays.asList(statusLine.toAttributedString(), AttributedString.EMPTY);
	}

	@Override
	protected List<AttributedString> computeMainHeaderLines() {
		final AttributedStringBuilder schemaHeader = new AttributedStringBuilder();

		Arrays.stream(resultDescriptor.getResultSchema().getFieldNames()).forEach(s -> {
			schemaHeader.append(' ');
			schemaHeader.style(AttributedStyle.DEFAULT.underline());
			normalizeColumn(schemaHeader, s, MAX_COLUMN_WIDTH);
			schemaHeader.style(AttributedStyle.DEFAULT);
		});

		return Collections.singletonList(schemaHeader.toAttributedString());
	}

	@Override
	protected List<AttributedString> computeFooterLines() {
		return formatTwoLineHelpOptions(getWidth(), getHelpOptions());
	}

	// --------------------------------------------------------------------------------------------

	private void updatePage() {
		// retrieve page
		final int retrievalPage = page == LAST_PAGE ? pageCount : page;
		final List<Row> rows;
		try {
			rows = client.getExecutor().retrieveResultPage(resultDescriptor.getResultId(), retrievalPage);
		} catch (SqlExecutionException e) {
			close(e);
			return;
		}

		// convert page
		final List<String[]> stringRows = rows
				.stream()
				.map(CliUtils::rowToString)
				.collect(Collectors.toList());

		// update results
		if (previousResultsPage == retrievalPage) {
			// only use the previous results if the current page number has not changed
			// this allows for updated results when the key space remains constant
			previousResults = results;
		} else {
			previousResults = null;
			previousResultsPage = retrievalPage;
		}

		results = stringRows;

		// check if selected row is still valid
		if (selectedRow != NO_ROW_SELECTED) {
			if (selectedRow >= results.size()) {
				selectedRow = NO_ROW_SELECTED;
			}
		}

		// reset view
		resetAllParts();
	}

	private List<Tuple2<String, String>> getHelpOptions() {
		final List<Tuple2<String, String>> options = new ArrayList<>();

		options.add(Tuple2.of("Q", CliStrings.RESULT_QUIT));
		options.add(Tuple2.of("R", CliStrings.RESULT_REFRESH));

		options.add(Tuple2.of("+", CliStrings.RESULT_INC_REFRESH));
		options.add(Tuple2.of("-", CliStrings.RESULT_DEC_REFRESH));

		options.add(Tuple2.of("G", CliStrings.RESULT_GOTO));
		options.add(Tuple2.of("L", CliStrings.RESULT_LAST));

		options.add(Tuple2.of("N", CliStrings.RESULT_NEXT));
		options.add(Tuple2.of("P", CliStrings.RESULT_PREV));

		options.add(Tuple2.of("O", CliStrings.RESULT_OPEN));

		return options;
	}

	private void gotoPage() {
		final CliInputView view = new CliInputView(
			client,
			CliStrings.INPUT_ENTER_PAGE + " [1 to " + pageCount + "]",
			(s) -> {
				// validate input
				final int newPage;
				try {
					newPage = Integer.parseInt(s);
				} catch (NumberFormatException e) {
					return false;
				}
				return newPage > 0 && newPage <= pageCount;
			});
		view.open(); // enter view
		if (view.getResult() != null) {
			page = Integer.parseInt(view.getResult());
			updatePage();
		}
	}

	private void gotoNextPage() {
		final int curPageIndex = page == LAST_PAGE ? pageCount : page;
		if (curPageIndex < pageCount) {
			page = curPageIndex + 1;
		}
		updatePage();
	}

	private void gotoPreviousPage() {
		final int curPageIndex = page == LAST_PAGE ? pageCount : page;
		if (curPageIndex > 1) {
			page = curPageIndex - 1;
		}
		updatePage();
	}

	private void gotoLastPage() {
		page = LAST_PAGE;
		updatePage();
	}

	// --------------------------------------------------------------------------------------------

	/**
	 * Available operations for this view.
	 */
	public enum ResultTableOperation {
		QUIT, // leave view
		REFRESH, // refresh current table page
		UP, // row selection up
		DOWN, // row selection down
		OPEN, // shows a full row
		GOTO, // enter table page number
		NEXT, // next table page
		PREV, // previous table page
		LAST, // last table page
		LEFT, // scroll left if row is large
		RIGHT, // scroll right if row is large
		INC_REFRESH, // increase refresh rate
		DEC_REFRESH, // decrease refresh rate
	}
}


text:
katsu-static
============

assets pipeline module for katsu


text:
'use strict';

define(['knockout', 'onefold-js', './streams/mapped-stream'], function (ko, js, MappedResource) {
    /**
     * @constructor
     * @template I, V, O
     * @extends {de.benshu.ko.dataSource.DataSource<I, V, O>}
     *
     * @param {!de.benshu.ko.dataSource.ObservableEntries<I, V, O>} observableEntries
     * @param {!function(I):V} getValueById
     */
    function AbstractDataSource(observableEntries, getValueById) {
        this.__observableEntries = observableEntries;
        this.__getValueById = getValueById;
    }

    AbstractDataSource.prototype = {
        openEntryView: function (entryId) {
            return new DefaultEntryView(this.openOptionalEntryView(entryId));
        },

        openOptionalEntryView: function (entryId) {
            return new DefaultOptionalEntryView(this.__observableEntries, this.__getValueById, entryId);
        },

        streamObservables: function (queryConfiguration) {
            return this.streamValues(queryConfiguration).then(values => {
                return new MappedResource(values,
                    this.__observableEntries.addReference.bind(this.__observableEntries),
                    this.__observableEntries.releaseReference.bind(this.__observableEntries));
            });
        },

        openView: function () { throw new Error('`' + this.constructor + '` does not implement `openView`.'); },
        streamValues: function () { throw new Error('`' + this.constructor + '` does not implement `streamValues`.'); },
        dispose: function () { throw new Error('`' + this.constructor + '` does not implement `dispose`.'); }
    };

    AbstractDataSource.prototype = js.objects.extend({}, {
        'openEntryView': AbstractDataSource.prototype.openEntryView,
        'openOptionalEntryView': AbstractDataSource.prototype.openOptionalEntryView,
        'streamObservables': AbstractDataSource.prototype.streamObservables
    }, AbstractDataSource.prototype);

    /**
     * @constructor
     * @template V, O
     * @extends {de.benshu.ko.dataSource.EntryView<V, O>}
     *
     * @param {de.benshu.ko.dataSource.OptionalEntryView<V, O>} optionalEntryView
     */
    function DefaultEntryView(optionalEntryView) {
        this.__optionalEntryView = optionalEntryView;
        this.__subscription = optionalEntryView.optionalObservable.subscribe(function () {
            throw new Error('Illegal state: A non-optional view for this entry is still open.');
        });
    }

    DefaultEntryView.prototype = {
        get value() { return this.__optionalEntryView.value; },
        get observable() { return this.__optionalEntryView.observable; },
        dispose: function () {
            if (this.__subscription)
                this.__subscription.dispose();
            this.__optionalEntryView.dispose();
        }
    };

    DefaultEntryView.prototype = js.objects.extend({}, {
        get 'value'() { return this.value; },
        get 'observable'() { return this.observable; },
        'dispose': DefaultEntryView.prototype.dispose
    }, DefaultEntryView.prototype);

    /**
     * @constructor
     * @template I, V, O
     * @extends {de.benshu.ko.dataSource.OptionalEntryView<V, O>}
     *
     * @param {de.benshu.ko.dataSource.ObservableEntries<I, V, O>} observableEntries
     * @param {function(V):I} getValueById
     * @param {I} entryId
     */
    function DefaultOptionalEntryView(observableEntries, getValueById, entryId) {
        this.__observableEntries = observableEntries;
        this.__getValueById = getValueById;
        this.__entryId = entryId;

        this.__disposed = false;
        this.__lastKnownValue = getValueById(entryId);

        var sharedObservable = observableEntries.addOptionalReference(this.value);
        this.__observable = sharedObservable();
        this.__optionalObservable = ko.observable({
            'present': true,
            'observable': this.__observable
        });
        this.__subscription = sharedObservable.subscribe(observable => {
            this.__optionalObservable({
                'present': !!observable,
                'observable': observable
            });
        });
    }

    DefaultOptionalEntryView.prototype = {
        __assertNotDisposed: function () {
            if (this.__disposed)
                throw new Error('Illegal state: Entry view was already disposed.');
        },
        get value() {
            this.__assertNotDisposed();
            return (this.__lastKnownValue = this.__getValueById(this.__entryId));
        },
        get observable() {
            this.__assertNotDisposed();
            return this.__observable;
        },
        get optionalObservable() {
            this.__assertNotDisposed();
            return this.__optionalObservable;
        },
        dispose: function () {
            this.__assertNotDisposed();
            this.__disposed = true;

            if (this.__subscription) {
                this.__subscription.dispose();
                this.__observableEntries.releaseReference(this.__lastKnownValue);
                this.__lastKnownValue = this.__observable = this.__optionalObservable = this.__subscription = null;
            }
        }
    };

    DefaultOptionalEntryView.prototype = js.objects.extend({}, {
        get 'value'() { return this.value; },
        get 'observable'() { return this.observable; },
        get 'optionalObservable'() { return this.optionalObservable; },
        'dispose': DefaultOptionalEntryView.prototype.dispose
    }, DefaultOptionalEntryView.prototype);

    var TRUE = function () {return true; };
    var ZERO = function () {return 0; };

    /**
     * @constructor
     * @template V
     *
     * @param {(function(V):boolean|ko.Subscribable<function(V):boolean>)=} predicate
     * @param {(function(V, V):number|ko.Subscribable<function(V, V):number>)=} comparator
     * @param {(number|ko.Subscribable<number>)=} offset
     * @param {(number|ko.Subscribable<number>)=} limit
     */
    function OpenViewKey(predicate, comparator, offset, limit) {
        this.predicate = predicate || TRUE;
        this.comparator = comparator || ZERO;
        this.offset = offset || 0;
        this.limit = limit || limit === 0 ? limit : Number.POSITIVE_INFINITY;

        this.rank = Math.max(
            this.predicate === TRUE ? OpenViewKey.RANK_ROOT : OpenViewKey.RANK_FILTERED,
            this.comparator === ZERO ? OpenViewKey.RANK_ROOT : OpenViewKey.RANK_SORTED,
            this.offset === 0 && this.limit === Number.POSITIVE_INFINITY ? OpenViewKey.RANK_ROOT : OpenViewKey.RANK_CLIPPED
        );
    }

    OpenViewKey.RANK_ROOT = 0;
    OpenViewKey.RANK_FILTERED = 1;
    OpenViewKey.RANK_SORTED = 2;
    OpenViewKey.RANK_CLIPPED = 3;
    OpenViewKey.fromQuery = function (query) {
        return new OpenViewKey(query.predicate, query.comparator, query.offset, query.limit);
    };

    OpenViewKey.prototype = {
        equals: function (other) {
            return this.rank === other.rank
                && this.predicate === other.predicate
                && this.comparator === other.comparator
                && this.offset === other.offset
                && this.limit === other.limit;
        },
        reduceRank: function () {
            if (this.rank <= 0)
                throw new Error('Unsupported operation.');

            var args = [null, this.predicate, this.comparator].slice(0, this.rank);
            /** @type {function(new:OpenViewKey<V>)} */
            var ReducedRankKeyConstructor = OpenViewKey.bind.apply(OpenViewKey, args);
            return new ReducedRankKeyConstructor();
        },
        allRanks: function () {
            return this.rank === 0 ? [this] : this.reduceRank().allRanks().concat([this]);
        },
        applyPrimaryTransformation: function (view) {
            var accessor = [v => v.filteredBy, v => v.sortedBy, v => v.clipped][this.rank - 1];
            var args = [[this.predicate], [this.comparator], [this.offset, this.limit]][this.rank - 1];

            return accessor(view).apply(view, args);
        }
    };

    /**
     * @constructor
     *
     * @param key
     * @param view
     * @param disposer
     */
    function OpenViewReference(key, view, disposer) {
        this.key = key;
        this.view = view;
        this.referenceCount = 1;
        this.disposer = disposer;
    }

    OpenViewReference.prototype = {
        addReference: function () {
            if (this.referenceCount <= 0)
                throw new Error('Assertion error: Reference count at `' + this.referenceCount + '`.');
            ++this.referenceCount;
            return this;
        },
        releaseReference: function () {
            if (--this.referenceCount === 0) {
                this.disposer();
            }
            return this;
        }
    };

    AbstractDataSource.OpenViewKey = OpenViewKey;
    AbstractDataSource.OpenViewReference = OpenViewReference;

    return AbstractDataSource;
});


text:
<!DOCTYPE html>

  <title>
But Why Mars though?
  </title>

  <link type="text/css" rel="stylesheet" href="../stylesheets/blog-stylesheet.css"/>

    Too Smart by Half

Projects

Curricula Vitae

Contact

Blog and Ruminations

Friends and Collaborators

 But Why Mars though?

 It's not the only game in town.

2020-07-17

  A few nights ago I went out into the farm fields of Iowa to get a dark enough sky to look at NEOWISE. Looking at a 5 kilometer wide ball of ice so close got me thinking about somethings. We're in the midst of a space renaissance and the idea of humans going out and space faring is more attainable than ever before. New vistas and opportunities unlike anything we'd ever have on Earth seem to be just over the horizon. So why does it feel like so many people are obsessed with Mars?

  This may be slightly correlated with one of the flashiest figures in the space, Elon Musk and how Mars is his cause célèbre, but he's  far from alone. A couple of arguments get brought up by different people. Economic opportunity of a new planet, increasing the durability of the human race, inexorable allure of exploration, development of new technologies, bragging rights, they all make the list depending on who you ask. I'm feeling like pursuing any of these goals with settling Mars is a failure of imagination.

Economic Opportunity

  An economic opportunity is, in almost all cases, a situation where you have some comparative advantage over other participants in the market. This could be any kind of thing. A few examples might be a physical resource like coal being more easily accessible. Or technological like having better handle on steel working, allowing you to use the resource more efficiently. Or it might be sociological like having fewer stigmas about what kinds of people can work, making your community appealing to ambitious people being oppressed in other regions.


text:
A collection of CakePHP utility components, behaviors, datasources, models, helpers and more all packaged into a single plugin.

## Requirements ##

* PHP 5.3.0
    * Multibyte
* CakePHP 2
* Composer

## Dependencies ##

* `Decoda` - https://github.com/milesj/decoda (DecodaHelper)
* `TypeConverter` - https://github.com/milesj/type-converter (AjaxHandlerComponent, FeedSource)

## Libraries ##

**Components**
* `AjaxHandler` - Provides support for AJAX request and response
* `AutoLogin` - An auth auto-login and persistent remember me

**Controllers**
* `Sitemap` - Generates a sitemap.xml for search engines

**Models**
* `Aggregator` - Convenience model that uses the FeedSource

**Behaviors**
* `Cacheable` - Automatic database query caching
* `Convertable` - Converts between types before and after database queries
* `Enumerable` - Provides enumerable support for database columns
* `Filterable` - Apply automatic filters and escaping to fields
* `Sluggable` - Generate a slug based off another field
* `SpamBlocker` - Validates comments against a point system and flags as spam
* `Validateable` - Allows for multiple sets of validation rules as well as message translation

**Datasources**
* `Feed` - RSS, RDF, Atom and XML parser through the model layer

**Helpers**
* `Breadcrumb` - Basic breadcrumb and sitemap generation
* `OpenGraph` - Generate meta tags for the OpenGraph protocol
* `Decoda` - BBcode markup parsing with the Decoda library
* `Utility` - Provides utility helper methods that integrate with the plugins other classes

**Shells**
* `CacheKill` - Clear cache from the command line
* `BaseInstall` - An abstract shell that provides installation functionality for plugins
* `BaseUpgrade` - An abstract shell that provides version upgrade migration functionality for plugins

## Documentation ##

Thorough documentation can be found here: http://milesj.me/code/cakephp/utility


text:
This is a gui project which can be implemented on Respberry Pi,
It can automatically download the weather infomation.

###目录结构
---KReminder
   |-Sources
      |-bgp
        |- 1.bgp
        |- 2.bgp
        |- ...
      |-wicon
        |- 1.png
        |- 2.png
        |- ...
   fetchnote.py
   fetchweather.py
   city.py
   main.py


text:
args=("$@")

NODEJS="node-v0.10.32"
MONGODB="mongodb-linux-x86_64-2.6.4"
REDIS="redis-2.8.17"

if [ $1 == "-h" ] || [ $1 == "--help" ]; then
    echo "Usage: ./setup.sh <Arguments>"
    echo "Arguments:"
    echo "-n : don't install nodejs"
    echo "-m : don't install mongodb"
    echo "-r : don't install redis"
    exit
fi

#TODO how to check linux distribution name?

#get your machine ready for work
#sudo apt-get update
#sudo apt-get -y install build-essential
yum install -y gcc-c++ make
yum install -y wget

#install nodejs
if [[ "${args[*]}" != *"-n"* ]]; then
    echo "[NODEJS] installing ..."
    wget http://nodejs.org/dist/v0.10.32/${NODEJS}.tar.gz
    tar xzf ${NODEJS}.tar.gz
    cd ${NODEJS}
    ./configure
    make
    make install
    cd ..
fi
npm install -g forever

#install mongodb
if [[ "${args[*]}" != *"-m"* ]]; then
    echo "[MONGODB] installing ..."
    wget https://fastdl.mongodb.org/linux/${MONGODB}.tgz
    tar -zxvf ${MONGODB}.tgz
    mkdir -p mongodb
    cp -R -n ${MONGODB}/ mongodb
    #export PATH=<mongodb-install-directory>/bin:$PATH
    mkdir -p /data/db
fi

#install redis and start as daemon
if [[ "${args[*]}" != *"-r"* ]]; then
    echo "[REDIS] installing ..."
    wget http://download.redis.io/releases/${REDIS}.tar.gz
    tar xzf ${REDIS}.tar.gz
    cd ${REDIS}
    make
    sed -i.bak s/"daemonize no"/"daemonize yes"/ redis.conf
    ./src/redis-server redis.conf
    cd ..
fi

#TODO config redis as daemon
#TODO test node and mongodb and redis


text:
<?php
namespace HXPHP\System\Helpers\Menu;

class Menu
{
    /**
     * Dependências
     * @var object
     */
    private $render = null;

    /**
     * Dados do módulo de configuração
     * @var array
     */
    private $configs = [];

    /**
     * URL ATUAL
     * @var string
     */
    private $current_URL = null;

    /**
     * Nível de acesso
     * @var string
     */
    private $role;

    /**
     * @param \HXPHP\System\Http\Request   $request Objeto Request
     * @param \HXPHP\System\Configs\Config $configs Configurações do framework
     * @param string                       $role    Nível de acesso
     */
    public function __construct(\HXPHP\System\Http\Request $request, \HXPHP\System\Configs\Config $configs, $role = 'default')
    {
        $this->role = $role;

        $this->setConfigs($configs)
                ->setCurrentURL($request, $configs);

        $realLink = new RealLink($configs->site->url, $configs->baseURI);
        $checkActive = new CheckActive($realLink, $this->current_URL);

        $this->render = new Render(
                $realLink, $checkActive, $this->configs->menu->itens, $this->configs->menu->configs
        );
    }

    /**
     * Dados do módulo de configuração do MenuHelper
     * @param array $configs
     */
    private function setConfigs($configs)
    {
        $this->configs = $configs;

        return $this;
    }

    /**
     * Define a URL atual
     */
    private function setCurrentURL($request, $configs)
    {
        $parseURL = parse_url($request->server('REQUEST_URI'));

        $this->current_URL = $configs->site->url . $parseURL['path'];

        return $this;
    }

    /**
     * Exibe o HTML com o menu renderizado
     * @return string
     */
    public function getMenu()
    {
        return $this->render->getHTML($this->role);
    }

    /**
     * Exibe o HTML com o menu renderizado
     * @return string
     */
    public function __toString()
    {
        return $this->getMenu();
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>PlausibleInstruments: Enumerations</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

Main Page

Modules

Classes

Files

Enumerations

[Constants Reference]

Collaboration diagram for Enumerations:

<map name="group____enums_map">
<area shape="rect" href="group__constants.html" title="Constants Reference" alt="" coords="5,5,120,32"></map>

<address style="text-align: right;">Generated on Wed Dec 31 18:55:34 2008 for PlausibleInstruments by

 1.5.5 </address>


text:
package io.wcm.caravan.io.http.impl.servletclient;

import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentSkipListMap;

import javax.servlet.Servlet;
import javax.servlet.ServletException;

import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.ReferencePolicy;
import org.apache.felix.scr.annotations.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Sets;

import io.wcm.caravan.io.http.CaravanHttpClient;
import io.wcm.caravan.io.http.IllegalResponseRuntimeException;
import io.wcm.caravan.io.http.RequestFailedRuntimeException;
import io.wcm.caravan.io.http.impl.CaravanHttpServiceConfigValidator;
import io.wcm.caravan.io.http.request.CaravanHttpRequest;
import io.wcm.caravan.io.http.response.CaravanHttpResponse;
import rx.Observable;

/**
 * Client which executes {@link Servlet}s registered in the same server directly without HTTP. Ignores fallbacks.
 */
@Component
@Service(ServletHttpClient.class)
public class ServletHttpClient implements CaravanHttpClient {

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

  @Reference(referenceInterface = Servlet.class, cardinality = ReferenceCardinality.OPTIONAL_MULTIPLE, policy = ReferencePolicy.DYNAMIC)
  private final ConcurrentMap<String, Servlet> servlets = new ConcurrentSkipListMap<>();

  private final Set<String> failedServices = Sets.newHashSet();
  protected void bindServlet(Servlet servlet, Map<String, Object> config) {
    String serviceId = (String)config.get("alias");
    if (serviceId != null) {
      servlets.put(serviceId, servlet);
    }
  }

  protected void unbindServlet(Servlet servle, Map<String, Object> config) {
    String serviceId = (String)config.get("alias");
    if (serviceId != null) {
      servlets.remove(serviceId);
    }
  }

  @Override
  public Observable<CaravanHttpResponse> execute(CaravanHttpRequest request) {
    return Observable.just(request.getServiceId())
        .map(serviceId -> getServlet(serviceId))
        .map(servlet -> executeServlet(servlet, request));
  }

  @Override
  public Observable<CaravanHttpResponse> execute(CaravanHttpRequest request, Observable<CaravanHttpResponse> fallback) {
    return execute(request);
  }

  @Override
  public boolean hasValidConfiguration(String serviceId) {
    return servlets.containsKey(serviceId) && !failedServices.contains(serviceId);
  }

  private Servlet getServlet(String serviceId) {

    Servlet servlet = servlets.get(serviceId);
    if (servlet == null) {
      throw new IllegalStateException("No local servlet registered for " + serviceId);
    }
    return servlet;

  }

  private CaravanHttpResponse executeServlet(Servlet servlet, CaravanHttpRequest request) {

    LOG.debug("Execute: {},\n{}", request.toString(), request.getCorrelationId());
    HttpServletRequestMapper requestMapper = new HttpServletRequestMapper(request);
    HttpServletResponseMapper responseMapper = new HttpServletResponseMapper();
    try {
      servlet.service(requestMapper, responseMapper);
      CaravanHttpResponse response = responseMapper.getResponse();

      int status = response.status();
      boolean throwExceptionForStatus500 = CaravanHttpServiceConfigValidator.throwExceptionForStatus500(request.getServiceId());
      if (status >= 500 && throwExceptionForStatus500) {
        String requestUrl = request.getUrl();
        String responseBody = response.body().asString();
        throw new IllegalResponseRuntimeException(request, requestUrl, status, responseBody,
          "Executing '" + requestUrl + "' failed: " + responseBody);
      }
      return response;
    }
    catch (NotSupportedByRequestMapperException ex) {
      failedServices.add(request.getServiceId());
      throw ex;
    }
    catch (ServletException | IOException ex) {
      throw new RequestFailedRuntimeException(request, ex.getMessage(), ex);
    }

  }

}


text:
/**
 * Packages management storage implementation with bookkeeper.
 */
package org.apache.pulsar.packages.management.storage.bookkeeper;


text:
package org.broadleafcommerce.openadmin.server.service.persistence.module.provider;

import org.apache.commons.lang.ArrayUtils;
import org.broadleafcommerce.openadmin.dto.Property;
import org.broadleafcommerce.openadmin.server.dao.FieldInfo;
import org.broadleafcommerce.openadmin.server.service.persistence.PersistenceManager;
import org.broadleafcommerce.openadmin.server.service.persistence.module.FieldManager;

import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;

/**
 * @author Jeff Fischer
 */
public abstract class AbstractFieldPersistenceProvider implements FieldPersistenceProvider {

    protected Class<?> getListFieldType(Serializable instance, FieldManager fieldManager, Property property, PersistenceManager persistenceManager) {
        Class<?> returnType = null;
        Field field = fieldManager.getField(instance.getClass(), property.getName());
        java.lang.reflect.Type type = field.getGenericType();
        if (type instanceof ParameterizedType) {
            ParameterizedType pType = (ParameterizedType) type;
            Class<?> clazz = (Class<?>) pType.getActualTypeArguments()[0];
            Class<?>[] entities = persistenceManager.getDynamicEntityDao().getAllPolymorphicEntitiesFromCeiling(clazz);
            if (!ArrayUtils.isEmpty(entities)) {
                returnType = entities[entities.length-1];
            }
        }
        return returnType;
    }

    protected Class<?> getMapFieldType(Serializable instance, FieldManager fieldManager, Property property, PersistenceManager persistenceManager) {
        Class<?> returnType = null;
        Field field = fieldManager.getField(instance.getClass(), property.getName().substring(0, property.getName().indexOf(FieldManager.MAPFIELDSEPARATOR)));
        java.lang.reflect.Type type = field.getGenericType();
        if (type instanceof ParameterizedType) {
            ParameterizedType pType = (ParameterizedType) type;
            Class<?> clazz = (Class<?>) pType.getActualTypeArguments()[1];
            Class<?>[] entities = persistenceManager.getDynamicEntityDao().getAllPolymorphicEntitiesFromCeiling(clazz);
            if (!ArrayUtils.isEmpty(entities)) {
                returnType = entities[entities.length-1];
            }
        }
        return returnType;
    }

    protected FieldInfo buildFieldInfo(Field field) {
        FieldInfo info = new FieldInfo();
        info.setName(field.getName());
        info.setGenericType(field.getGenericType());
        ManyToMany manyToMany = field.getAnnotation(ManyToMany.class);
        if (manyToMany != null) {
            info.setManyToManyMappedBy(manyToMany.mappedBy());
            info.setManyToManyTargetEntity(manyToMany.targetEntity().getName());
        }
        OneToMany oneToMany = field.getAnnotation(OneToMany.class);
        if (oneToMany != null) {
            info.setOneToManyMappedBy(oneToMany.mappedBy());
            info.setOneToManyTargetEntity(oneToMany.targetEntity().getName());
        }
        return info;
    }
}


text:
		<button class="navbar-toggle" type="button" data-ng-click="toggleSidebar()">
			Toggle navigation

		</button>


text:
/**
 * @ngdoc function
 * @name <%= moduleName %>.controller:<%= classedName %>Ctrl
 * @description
 * # <%= classedName %>Ctrl
 * Controller of the <%= moduleName %>
 */

(function() {
    'use strict';

    angular
        .module('<%= moduleName %>')
        .controller('<%= classedName %><%= nameSuffix %>', <%= classedName %><%= nameSuffix %>);

    /* @ngInject */
    function <%= classedName %><%= nameSuffix %>($state, ngToast, aaalToSchemaForm, <%= modelServiceName %>) {
        var vm = this;
        var ModelService = <%= modelServiceName %>;
        vm.modelName = '<%= modelName %>';

        //form and schema definition
        vm.schema = aaalToSchemaForm(vm.modelName);
        vm.form = [
            '*',
            {
                type: 'submit',
                title: 'Save'
            }
        ];

        // load or create new instance
        if ($state.params.id) {
            ModelService.findById({id: $state.params.id})
                .$promise
                .then(function(model) {
                    vm.model = model;
                }, function() {
                    ngToast.danger('Could not load model #' + $state.params.id);
                    $state.go('<%= overviewStateFull %>');
                });
        } else {
            vm.model = {};
        }

        function postSave() {
            ngToast.create('Saved');
            $state.go('<%= overviewStateFull %>');
        }

        vm.createOrUpdate = function() {
            // update
            if (vm.model.id) {
                var modelInstance = new ModelService(vm.model);
                vm.submitPromise = modelInstance.$save()
                    .then(postSave);
            }
            // create
            else {
                vm.submitPromise = ModelService.create(vm.model)
                    .$promise
                    .then(postSave);
            }
        };
    }
})();


text:
@implementation MBABaseSearchBar
-(instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        self.autocorrectionType = UITextAutocorrectionTypeNo;
        self.autocapitalizationType = UITextAutocapitalizationTypeNone;
        self.keyboardType = UIKeyboardTypeDefault;
    }
    return self;
}

-(void)updateColor{
    NSInteger themeStyle = [MBAThemeManager readThemeStyle];
    [self setBarStyle: themeStyle];
}

-(void)updateLanguage{

}

-(void)updateUI{

}

@end


text:
<?php
require_once 'functions.php';
require_once 'functions.omat.php';
$section = 6;
$load_menu = 2;
$sub_page = 5;

$id = (int)$_GET['id'];

if ($_POST) {
  $post = array(
    'multiscale_as_proxy' => (int)$_POST['multiscale_as_proxy'],
  );
  $db->update("mfa_dataset",$post,"id = $id");
  $print = "Option has been saved";
}

$info = $db->record("SELECT * FROM mfa_dataset WHERE id = $id");

if ($_GET['delete']) {
  $delete = (int)$_GET['delete'];
  $check = $db->query("SELECT * FROM mfa_data WHERE scale = $delete");
  if (count($check)) {
    die("Sorry, we could not delete this scale type because there are data points for this scale already logged!");
  }
  $db->query("DELETE FROM mfa_scales WHERE id = $delete AND dataset = $id LIMIT 1");
  $print = "Scale was deleted";
}

$list = $db->query("SELECT * FROM mfa_scales WHERE dataset = $id ORDER BY name");
?>
<!DOCTYPE html>

    <?php echo $header ?>
    <link rel="stylesheet" href="css/sidebar.css" />
    <title>Types of Scales | <?php echo $info->name ?> | OMAT | <?php echo SITENAME ?></title>

<?php require_once 'include.header.php'; ?>
<?php require_once 'include.omatheader.php'; ?>

Types of Scales

<a href="omat/<?php echo $project ?>/dashboard">Dashboard

Types of Scales

  <?php if ($print) { echo "
$print
"; } ?>

Use of scales

    How should the scales be used? One option is that scales are used for
    comparison.  You should use this if you intend to get full
    datasets for each of the scales and to contrast the different results. An
    example of this multi-scale approach is Barles'
    study on Paris, Paris and its suburbs, and the entire region.
    Alternatively, you can use several scales because you want to use data from
    different scales as proxies if data is not available for your scale of
    choice. For instance, if you are studying the City of Cape Town but you
    sometimes have to make do with data from the province (the Western Cape),
    then you can enter this data and OMAT will convert it for you (using
    parameters that you can set).

  <form method="post">

     <input type="radio" name="multiscale_as_proxy" value="0" <?php echo !$info->multiscale_as_proxy ? 'checked="checked"' : ''; ?> />
      Use scales to compare different systems (each scale will be an individual dataset)

     <input type="radio" name="multiscale_as_proxy" value="1" <?php echo $info->multiscale_as_proxy ? 'checked="checked"' : ''; ?> />
      Use scales as proxies (all scales will form one single dataset)

      <button type="submit" class="btn btn-primary">Save</button>

  </form>

  <?php if (!count($list)) { ?>

    In this section you can define scale levels for your project. In the data points you can save values
    for each scale that you define. Scales could include for instance 'urban core', 'city-wide region', and 'province'.

  <?php } else { ?>

        Name
        <?php if ($info->multiscale_as_proxy) { ?>
          Standard Multiplier
        <?php } ?>
        Edit
        Delete

    <?php foreach ($list as $row) { ?>

        <?php echo $row['name'] ?>
        <?php if ($info->multiscale_as_proxy) { ?>
          <?php echo $row['standard_multiplier'] ?>
        <?php } ?>
        <a href="omat/<?php echo $project ?>/maintenance-scale/<?php echo $row['id'] ?>" class="btn btn-primary">Edit
        <a href="omat/<?php echo $project ?>/maintenance-scales/<?php echo $row['id'] ?>/delete" class="btn btn-danger" onclick="javascript:return confirm('Are you sure?')">Delete

    <?php } ?>

  <?php } ?>

<a href="omat/<?php echo $project ?>/maintenance-scale/0" class="btn btn-success">Add scale

<?php require_once 'include.omatfooter.php'; ?>
<?php require_once 'include.footer.php'; ?>


text:
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

//! APIs for memory profiling.

#![deny(missing_docs)]

use ipc_channel::ipc::{self, IpcSender};
use ipc_channel::router::ROUTER;
use std::marker::Send;
use std::sync::mpsc::Sender;

/// A trait to abstract away the various kinds of message senders we use.
pub trait OpaqueSender<T> {
    /// Send a message.
    fn send(&self, message: T);
}

impl<T> OpaqueSender<T> for Sender<T> {
    fn send(&self, message: T) {
        if let Err(e) = Sender::send(self, message) {
            warn!("Error communicating with the target thread from the profiler: {}", e);
        }
    }
}

/// Front-end representation of the profiler used to communicate with the
/// profiler.
#[derive(Clone, Deserialize, Serialize)]
pub struct ProfilerChan(pub IpcSender<ProfilerMsg>);

impl ProfilerChan {
    /// Send `msg` on this `IpcSender`.
    ///
    /// Warns if the send fails.
    pub fn send(&self, msg: ProfilerMsg) {
        if let Err(e) = self.0.send(msg) {
            warn!("Error communicating with the memory profiler thread: {}", e);
        }
    }

    /// Runs `f()` with memory profiling.
    pub fn run_with_memory_reporting<F, M, T, C>(&self, f: F,
                                                 reporter_name: String,
                                                 channel_for_reporter: C,
                                                 msg: M)
        where F: FnOnce(),
              M: Fn(ReportsChan) -> T + Send + 'static,
              T: Send + 'static,
              C: OpaqueSender<T> + Send + 'static
    {
        // Register the memory reporter.
        let (reporter_sender, reporter_receiver) = ipc::channel().unwrap();
        ROUTER.add_route(reporter_receiver.to_opaque(), box move |message| {
            // Just injects an appropriate event into the paint thread's queue.
            let request: ReporterRequest = message.to().unwrap();
            channel_for_reporter.send(msg(request.reports_channel));
        });
        self.send(ProfilerMsg::RegisterReporter(reporter_name.clone(),
                                                Reporter(reporter_sender)));

        f();

        self.send(ProfilerMsg::UnregisterReporter(reporter_name));
    }
}

/// The various kinds of memory measurement.
///
/// Here "explicit" means explicit memory allocations done by the application. It includes
/// allocations made at the OS level (via functions such as VirtualAlloc, vm_allocate, and mmap),
/// allocations made at the heap allocation level (via functions such as malloc, calloc, realloc,
/// memalign, operator new, and operator new[]) and where possible, the overhead of the heap
/// allocator itself. It excludes memory that is mapped implicitly such as code and data segments,
/// and thread stacks. "explicit" is not guaranteed to cover every explicit allocation, but it does
/// cover most (including the entire heap), and therefore it is the single best number to focus on
/// when trying to reduce memory usage.
#[derive(Deserialize, Serialize)]
pub enum ReportKind {
    /// A size measurement for an explicit allocation on the jemalloc heap. This should be used
    /// for any measurements done via the `HeapSizeOf` trait.
    ExplicitJemallocHeapSize,

    /// A size measurement for an explicit allocation on the system heap. Only likely to be used
    /// for external C or C++ libraries that don't use jemalloc.
    ExplicitSystemHeapSize,

    /// A size measurement for an explicit allocation not on the heap, e.g. via mmap().
    ExplicitNonHeapSize,

    /// A size measurement for an explicit allocation whose location is unknown or uncertain.
    ExplicitUnknownLocationSize,

    /// A size measurement for a non-explicit allocation. This kind is used for global
    /// measurements such as "resident" and "vsize", and also for measurements that cross-cut the
    /// measurements grouped under "explicit", e.g. by grouping those measurements in a way that's
    /// different to how they are grouped under "explicit".
    NonExplicitSize,
}

/// A single memory-related measurement.
#[derive(Deserialize, Serialize)]
pub struct Report {
    /// The identifying path for this report.
    pub path: Vec<String>,

    /// The report kind.
    pub kind: ReportKind,

    /// The size, in bytes.
    pub size: usize,
}

/// A channel through which memory reports can be sent.
#[derive(Clone, Deserialize, Serialize)]
pub struct ReportsChan(pub IpcSender<Vec<Report>>);

impl ReportsChan {
    /// Send `report` on this `IpcSender`.
    ///
    /// Panics if the send fails.
    pub fn send(&self, report: Vec<Report>) {
        self.0.send(report).unwrap();
    }
}

/// The protocol used to send reporter requests.
#[derive(Deserialize, Serialize)]
pub struct ReporterRequest {
    /// The channel on which reports are to be sent.
    pub reports_channel: ReportsChan,
}

/// A memory reporter is capable of measuring some data structure of interest. It's structured as
/// an IPC sender that a `ReporterRequest` in transmitted over. `ReporterRequest` objects in turn
/// encapsulate the channel on which the memory profiling information is to be sent.
///
/// In many cases, clients construct `Reporter` objects by creating an IPC sender/receiver pair and
/// registering the receiving end with the router so that messages from the memory profiler end up
/// injected into the client's event loop.
#[derive(Deserialize, Serialize)]
pub struct Reporter(pub IpcSender<ReporterRequest>);

impl Reporter {
    /// Collect one or more memory reports. Returns true on success, and false on failure.
    pub fn collect_reports(&self, reports_chan: ReportsChan) {
        self.0.send(ReporterRequest {
            reports_channel: reports_chan,
        }).unwrap()
    }
}

/// An easy way to build a path for a report.
#[macro_export]
macro_rules! path {
    ($($x:expr),*) => {{
        use std::borrow::ToOwned;
        vec![$( $x.to_owned() ),*]
    }}
}

/// Messages that can be sent to the memory profiler thread.
#[derive(Deserialize, Serialize)]
pub enum ProfilerMsg {
    /// Register a Reporter with the memory profiler. The String is only used to identify the
    /// reporter so it can be unregistered later. The String must be distinct from that used by any
    /// other registered reporter otherwise a panic will occur.
    RegisterReporter(String, Reporter),

    /// Unregister a Reporter with the memory profiler. The String must match the name given when
    /// the reporter was registered. If the String does not match the name of a registered reporter
    /// a panic will occur.
    UnregisterReporter(String),

    /// Triggers printing of the memory profiling metrics.
    Print,

    /// Tells the memory profiler to shut down.
    Exit,
}


text:
import React, {Component, PropTypes} from 'react';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';

export default class Questions extends Component {
  static propTypes = {
      questionObj: PropTypes.array.isRequired
    };

  render() {
   const styles = require('./Questions.scss');
    return (

 Question 1:

 It is this?

              This!

 Question 2:

 Or that?

          That!

    );
  }
}


text:
package org.cloudfoundry.autosleep.access.dao.repositories;

import lombok.extern.slf4j.Slf4j;
import org.cloudfoundry.autosleep.access.dao.config.RepositoryConfig;
import org.cloudfoundry.autosleep.access.dao.model.Binding;
import org.cloudfoundry.autosleep.access.dao.model.Binding.ResourceType;
import org.cloudfoundry.autosleep.util.ApplicationConfiguration;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

@Slf4j
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {ApplicationConfiguration.class, RepositoryConfig.class, EnableJpaConfiguration.class})
public abstract class BindingRepositoryTest extends CrudRepositoryTest<Binding> {

    private static final String APP_GUID = "2F5A0947-6468-401B-B12A-963405121937";

    @Autowired
    private BindingRepository bindingRepository;

    @Override
    protected Binding build(String id) {
        return Binding.builder()
                .resourceId(APP_GUID)
                .resourceType(ResourceType.Application)
                .serviceInstanceId("service")
                .serviceBindingId(id)
                .build();
    }

    @Override
    protected void compareReloaded(Binding original, Binding reloaded) {
        assertThat(reloaded.getServiceInstanceId(), is(equalTo(original.getServiceInstanceId())));
        assertThat(reloaded.getResourceId(), is(equalTo(original.getResourceId())));
        assertThat(reloaded, is(equalTo(original)));
    }

    /**
     * Init DAO with test data.
     */
    @Before
    @After
    public void setAndClearDao() {
        setDao(bindingRepository);
        bindingRepository.deleteAll();
    }

    @Test
    public void test_find_by_resource_id_and_type_on_existing_type() {
        //Given there is some entity in database
        List<String> ids = Arrays.asList("testFind1", "testFind2");
        ids.forEach(id -> bindingRepository.save(build(id)));
        //When we count element by resource and type that were inserted
        int count = bindingRepository.findByResourceIdAndType(Arrays.asList(APP_GUID, APP_GUID),
                ResourceType.Application).size();
        //then the count is equal to the one inserted
        assertTrue("Retrieving all elements should return the same quantity", count == ids.size());
    }

    @Test
    public void test_find_by_resource_id_and_type_on_non_existing_type() {
        //Given there is some entity in database
        List<String> ids = Arrays.asList("testFind1", "testFind2");
        ids.forEach(id -> bindingRepository.save(build(id)));
        //When we count element by resource and type that were not inserted
        int count = bindingRepository.findByResourceIdAndType(Collections.singletonList(APP_GUID),
                ResourceType.Route).size();
        //then the count is equal to zero
        assertTrue("No route binding should be found", count == 0);
    }

}


text:
jvm.SVGCanvasElement = function(container, width, height){
  this.classPrefix = 'SVG';
  jvm.SVGCanvasElement.parentClass.call(this, 'svg');

  this.defsElement = new jvm.SVGElement('defs');
  this.node.appendChild( this.defsElement.node );

  jvm.AbstractCanvasElement.apply(this, arguments);
}

jvm.inherits(jvm.SVGCanvasElement, jvm.SVGElement);
jvm.mixin(jvm.SVGCanvasElement, jvm.AbstractCanvasElement);

jvm.SVGCanvasElement.prototype.setSize = function(width, height){
  this.width = width;
  this.height = height;
  this.node.setAttribute('width', width);
  this.node.setAttribute('height', height);
};

jvm.SVGCanvasElement.prototype.applyTransformParams = function(scale, transX, transY) {
  this.scale = scale;
  this.transX = transX;
  this.transY = transY;
  this.rootElement.node.setAttribute('transform', 'scale('+scale+') translate('+transX+', '+transY+')');
};


text:
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use core::cmp::{Ord, Eq};
use ops::{Add, Div, Modulo, Mul, Neg, Sub};
use option::{None, Option, Some};
use char;
use str;
use kinds::Copy;
use vec;
use num::{NumCast, Zero, One, cast, pow_with_uint};
use f64;

pub enum ExponentFormat {
    ExpNone,
    ExpDec,
    ExpBin
}

pub enum SignificantDigits {
    DigAll,
    DigMax(uint),
    DigExact(uint)
}

pub enum SignFormat {
    SignNone,
    SignNeg,
    SignAll
}

#[inline(always)]
fn is_NaN<T:Eq>(num: &T) -> bool {
    *num != *num
}

#[inline(always)]
fn is_inf<T:Eq+NumStrConv>(num: &T) -> bool {
    match NumStrConv::inf() {
        None    => false,
        Some(n) => *num == n
    }
}

#[inline(always)]
fn is_neg_inf<T:Eq+NumStrConv>(num: &T) -> bool {
    match NumStrConv::neg_inf() {
        None    => false,
        Some(n) => *num == n
    }
}

#[inline(always)]
fn is_neg_zero<T:Eq+One+Zero+NumStrConv+Div<T,T>>(num: &T) -> bool {
    let _0: T = Zero::zero();
    let _1: T = One::one();

    *num == _0 && is_neg_inf(&(_1 / *num))
}

pub trait NumStrConv {
    fn NaN()      -> Option<Self>;
    fn inf()      -> Option<Self>;
    fn neg_inf()  -> Option<Self>;
    fn neg_zero() -> Option<Self>;

    fn round_to_zero(&self)   -> Self;
    fn fractional_part(&self) -> Self;
}

macro_rules! impl_NumStrConv_Floating (($t:ty) => (
    impl NumStrConv for $t {
        #[inline(always)]
        fn NaN()      -> Option<$t> { Some( 0.0 / 0.0) }
        #[inline(always)]
        fn inf()      -> Option<$t> { Some( 1.0 / 0.0) }
        #[inline(always)]
        fn neg_inf()  -> Option<$t> { Some(-1.0 / 0.0) }
        #[inline(always)]
        fn neg_zero() -> Option<$t> { Some(-0.0      ) }

        #[inline(always)]
        fn round_to_zero(&self) -> $t {
            ( if *self < 0.0 { f64::ceil(*self as f64)  }
              else           { f64::floor(*self as f64) }
            ) as $t
        }

        #[inline(always)]
        fn fractional_part(&self) -> $t {
            *self - self.round_to_zero()
        }
    }
))

macro_rules! impl_NumStrConv_Integer (($t:ty) => (
    impl NumStrConv for $t {
        #[inline(always)] fn NaN()      -> Option<$t> { None }
        #[inline(always)] fn inf()      -> Option<$t> { None }
        #[inline(always)] fn neg_inf()  -> Option<$t> { None }
        #[inline(always)] fn neg_zero() -> Option<$t> { None }

        #[inline(always)] fn round_to_zero(&self)   -> $t { *self }
        #[inline(always)] fn fractional_part(&self) -> $t {     0 }
    }
))

// FIXME: #4955
// Replace by two generic impls for traits 'Integral' and 'Floating'
impl_NumStrConv_Floating!(float)
impl_NumStrConv_Floating!(f32)
impl_NumStrConv_Floating!(f64)

impl_NumStrConv_Integer!(int)
impl_NumStrConv_Integer!(i8)
impl_NumStrConv_Integer!(i16)
impl_NumStrConv_Integer!(i32)
impl_NumStrConv_Integer!(i64)

impl_NumStrConv_Integer!(uint)
impl_NumStrConv_Integer!(u8)
impl_NumStrConv_Integer!(u16)
impl_NumStrConv_Integer!(u32)
impl_NumStrConv_Integer!(u64)

// Special value strings as [u8] consts.
static inf_buf:          [u8, ..3] = ['i' as u8, 'n' as u8, 'f' as u8];
static positive_inf_buf: [u8, ..4] = ['+' as u8, 'i' as u8, 'n' as u8,
                                      'f' as u8];
static negative_inf_buf: [u8, ..4] = ['-' as u8, 'i' as u8, 'n' as u8,
                                      'f' as u8];
static nan_buf:          [u8, ..3] = ['N' as u8, 'a' as u8, 'N' as u8];

/**
 * Converts a number to its string representation as a byte vector.
 * This is meant to be a common base implementation for all numeric string
 * conversion functions like `to_str()` or `to_str_radix()`.
 *
 * # Arguments
 * - `num`           - The number to convert. Accepts any number that
 *                     implements the numeric traits.
 * - `radix`         - Base to use. Accepts only the values 2-36.
 * - `negative_zero` - Whether to treat the special value `-0` as
 *                     `-0` or as `+0`.
 * - `sign`          - How to emit the sign. Options are:
 *     - `SignNone`: No sign at all. Basically emits `abs(num)`.
 *     - `SignNeg`:  Only `-` on negative values.
 *     - `SignAll`:  Both `+` on positive, and `-` on negative numbers.
 * - `digits`        - The amount of digits to use for emitting the
 *                     fractional part, if any. Options are:
 *     - `DigAll`:         All calculatable digits. Beware of bignums or
 *                         fractions!
 *     - `DigMax(uint)`:   Maximum N digits, truncating any trailing zeros.
 *     - `DigExact(uint)`: Exactly N digits.
 *
 * # Return value
 * A tuple containing the byte vector, and a boolean flag indicating
 * whether it represents a special value like `inf`, `-inf`, `NaN` or not.
 * It returns a tuple because there can be ambiguity between a special value
 * and a number representation at higher bases.
 *
 * # Failure
 * - Fails if `radix` < 2 or `radix` > 36.
 */
pub fn to_str_bytes_common<T:NumCast+Zero+One+Eq+Ord+NumStrConv+Copy+
                                  Div<T,T>+Neg<T>+Modulo<T,T>+Mul<T,T>>(
        num: &T, radix: uint, negative_zero: bool,
        sign: SignFormat, digits: SignificantDigits) -> (~[u8], bool) {
    if (radix as int) < 2 {
        fail!(fmt!("to_str_bytes_common: radix %? to low, \
                   must lie in the range [2, 36]", radix));
    } else if radix as int > 36 {
        fail!(fmt!("to_str_bytes_common: radix %? to high, \
                   must lie in the range [2, 36]", radix));
    }

    let _0: T = Zero::zero();
    let _1: T = One::one();

    if is_NaN(num) {
        return (str::to_bytes("NaN"), true);
    }
    else if is_inf(num){
        return match sign {
            SignAll => (str::to_bytes("+inf"), true),
            _       => (str::to_bytes("inf"), true)
        }
    }
    else if is_neg_inf(num) {
        return match sign {
            SignNone => (str::to_bytes("inf"), true),
            _        => (str::to_bytes("-inf"), true),
        }
    }

    let neg = *num < _0 || (negative_zero && is_neg_zero(num));
    let mut buf: ~[u8] = ~[];
    let radix_gen: T   = cast(radix as int);

    let mut deccum;

    // First emit the non-fractional part, looping at least once to make
    // sure at least a `0` gets emitted.
    deccum = num.round_to_zero();
    loop {
        // Calculate the absolute value of each digit instead of only
        // doing it once for the whole number because a
        // representable negative number doesn't necessary have an
        // representable additive inverse of the same type
        // (See twos complement). But we assume that for the
        // numbers [-35 .. 0] we always have [0 .. 35].
        let current_digit_signed = deccum % radix_gen;
        let current_digit = if current_digit_signed < _0 {
            -current_digit_signed
        } else {
            current_digit_signed
        };

        // Decrease the deccumulator one digit at a time
        deccum /= radix_gen;
        deccum = deccum.round_to_zero();

        unsafe { // FIXME: Pureness workaround (#4568)
            buf.push(char::from_digit(current_digit.to_int() as uint, radix)
                 .unwrap() as u8);
        }

        // No more digits to calculate for the non-fractional part -> break
        if deccum == _0 { break; }
    }

    // If limited digits, calculate one digit more for rounding.
    let (limit_digits, digit_count, exact) = match digits {
        DigAll          => (false, 0u,      false),
        DigMax(count)   => (true,  count+1, false),
        DigExact(count) => (true,  count+1, true)
    };

    // Decide what sign to put in front
    match sign {
        SignNeg | SignAll if neg => {
            unsafe { // FIXME: Pureness workaround (#4568)
                buf.push('-' as u8);
            }
        }
        SignAll => {
            unsafe { // FIXME: Pureness workaround (#4568)
                buf.push('+' as u8);
            }
        }
        _ => ()
    }

    unsafe { // FIXME: Pureness workaround (#4568)
        vec::reverse(buf);
    }

    // Remember start of the fractional digits.
    // Points one beyond end of buf if none get generated,
    // or at the '.' otherwise.
    let start_fractional_digits = buf.len();

    // Now emit the fractional part, if any
    deccum = num.fractional_part();
    if deccum != _0 || (limit_digits && exact && digit_count > 0) {
        unsafe { // FIXME: Pureness workaround (#4568)
            buf.push('.' as u8);
        }
        let mut dig = 0u;

        // calculate new digits while
        // - there is no limit and there are digits left
        // - or there is a limit, it's not reached yet and
        //   - it's exact
        //   - or it's a maximum, and there are still digits left
        while (!limit_digits && deccum != _0)
           || (limit_digits && dig < digit_count && (
                   exact
                || (!exact && deccum != _0)
              )
        ) {
            // Shift first fractional digit into the integer part
            deccum *= radix_gen;

            // Calculate the absolute value of each digit.
            // See note in first loop.
            let current_digit_signed = deccum.round_to_zero();
            let current_digit = if current_digit_signed < _0 {
                -current_digit_signed
            } else {
                current_digit_signed
            };

            unsafe { // FIXME: Pureness workaround (#4568)
                buf.push(char::from_digit(
                    current_digit.to_int() as uint, radix).unwrap() as u8);
            }

            // Decrease the deccumulator one fractional digit at a time
            deccum = deccum.fractional_part();
            dig += 1u;
        }

        // If digits are limited, and that limit has been reached,
        // cut off the one extra digit, and depending on its value
        // round the remaining ones.
        if limit_digits && dig == digit_count {
            let ascii2value = |chr: u8| {
                char::to_digit(chr as char, radix).unwrap() as uint
            };
            let value2ascii = |val: uint| {
                char::from_digit(val, radix).unwrap() as u8
            };

            unsafe { // FIXME: Pureness workaround (#4568)
                let extra_digit = ascii2value(buf.pop());
                if extra_digit >= radix / 2 { // -> need to round
                    let mut i: int = buf.len() as int - 1;
                    loop {
                        // If reached left end of number, have to
                        // insert additional digit:
                        if i < 0
                        || buf[i] == '-' as u8
                        || buf[i] == '+' as u8 {
                            buf.insert((i + 1) as uint, value2ascii(1));
                            break;
                        }

                        // Skip the '.'
                        if buf[i] == '.' as u8 { i -= 1; loop; }

                        // Either increment the digit,
                        // or set to 0 if max and carry the 1.
                        let current_digit = ascii2value(buf[i]);
                        if current_digit < (radix - 1) {
                            buf[i] = value2ascii(current_digit+1);
                            break;
                        } else {
                            buf[i] = value2ascii(0);
                            i -= 1;
                        }
                    }
                }
            }
        }
    }

    // if number of digits is not exact, remove all trailing '0's up to
    // and including the '.'
    if !exact {
        let buf_max_i = buf.len() - 1;

        // index to truncate from
        let mut i = buf_max_i;

        // discover trailing zeros of fractional part
        while i > start_fractional_digits && buf[i] == '0' as u8 {
            i -= 1;
        }

        // Only attempt to truncate digits if buf has fractional digits
        if i >= start_fractional_digits {
            // If buf ends with '.', cut that too.
            if buf[i] == '.' as u8 { i -= 1 }

            // only resize buf if we actually remove digits
            if i < buf_max_i {
                buf = buf.slice(0, i + 1).to_owned();
            }
        }
    } // If exact and trailing '.', just cut that
    else {
        let max_i = buf.len() - 1;
        if buf[max_i] == '.' as u8 {
            buf = buf.slice(0, max_i).to_owned();
        }
    }

    (buf, false)
}

/**
 * Converts a number to its string representation. This is a wrapper for
 * `to_str_bytes_common()`, for details see there.
 */
#[inline(always)]
pub fn to_str_common<T:NumCast+Zero+One+Eq+Ord+NumStrConv+Copy+
                            Div<T,T>+Neg<T>+Modulo<T,T>+Mul<T,T>>(
        num: &T, radix: uint, negative_zero: bool,
        sign: SignFormat, digits: SignificantDigits) -> (~str, bool) {
    let (bytes, special) = to_str_bytes_common(num, radix,
                               negative_zero, sign, digits);
    (str::from_bytes(bytes), special)
}

// Some constants for from_str_bytes_common's input validation,
// they define minimum radix values for which the character is a valid digit.
priv static DIGIT_P_RADIX: uint = ('p' as uint) - ('a' as uint) + 11u;
priv static DIGIT_I_RADIX: uint = ('i' as uint) - ('a' as uint) + 11u;
priv static DIGIT_E_RADIX: uint = ('e' as uint) - ('a' as uint) + 11u;

/**
 * Parses a byte slice as a number. This is meant to
 * be a common base implementation for all numeric string conversion
 * functions like `from_str()` or `from_str_radix()`.
 *
 * # Arguments
 * - `buf`        - The byte slice to parse.
 * - `radix`      - Which base to parse the number as. Accepts 2-36.
 * - `negative`   - Whether to accept negative numbers.
 * - `fractional` - Whether to accept numbers with fractional parts.
 * - `special`    - Whether to accept special values like `inf`
 *                  and `NaN`. Can conflict with `radix`, see Failure.
 * - `exponent`   - Which exponent format to accept. Options are:
 *     - `ExpNone`: No Exponent, accepts just plain numbers like `42` or
 *                  `-8.2`.
 *     - `ExpDec`:  Accepts numbers with a decimal exponent like `42e5` or
 *                  `8.2E-2`. The exponent string itself is always base 10.
 *                  Can conflict with `radix`, see Failure.
 *     - `ExpBin`:  Accepts numbers with a binary exponent like `42P-8` or
 *                  `FFp128`. The exponent string itself is always base 10.
 *                  Can conflict with `radix`, see Failure.
 * - `empty_zero` - Whether to accept a empty `buf` as a 0 or not.
 *
 * # Return value
 * Returns `Some(n)` if `buf` parses to a number n without overflowing, and
 * `None` otherwise, depending on the constraints set by the remaining
 * arguments.
 *
 * # Failure
 * - Fails if `radix` < 2 or `radix` > 36.
 * - Fails if `radix` > 14 and `exponent` is `ExpDec` due to conflict
 *   between digit and exponent sign `'e'`.
 * - Fails if `radix` > 25 and `exponent` is `ExpBin` due to conflict
 *   between digit and exponent sign `'p'`.
 * - Fails if `radix` > 18 and `special == true` due to conflict
 *   between digit and lowest first character in `inf` and `NaN`, the `'i'`.
 *
 * # Possible improvements
 * - Could accept option to allow ignoring underscores, allowing for numbers
 *   formated like `FF_AE_FF_FF`.
 */
pub fn from_str_bytes_common<T:NumCast+Zero+One+Ord+Copy+Div<T,T>+
                                    Mul<T,T>+Sub<T,T>+Neg<T>+Add<T,T>+
                                    NumStrConv>(
        buf: &[u8], radix: uint, negative: bool, fractional: bool,
        special: bool, exponent: ExponentFormat, empty_zero: bool
        ) -> Option<T> {
    match exponent {
        ExpDec if radix >= DIGIT_E_RADIX       // decimal exponent 'e'
          => fail!(fmt!("from_str_bytes_common: radix %? incompatible with \
                        use of 'e' as decimal exponent", radix)),
        ExpBin if radix >= DIGIT_P_RADIX       // binary exponent 'p'
          => fail!(fmt!("from_str_bytes_common: radix %? incompatible with \
                        use of 'p' as binary exponent", radix)),
        _ if special && radix >= DIGIT_I_RADIX // first digit of 'inf'
          => fail!(fmt!("from_str_bytes_common: radix %? incompatible with \
                        special values 'inf' and 'NaN'", radix)),
        _ if (radix as int) < 2
          => fail!(fmt!("from_str_bytes_common: radix %? to low, \
                        must lie in the range [2, 36]", radix)),
        _ if (radix as int) > 36
          => fail!(fmt!("from_str_bytes_common: radix %? to high, \
                        must lie in the range [2, 36]", radix)),
        _ => ()
    }

    let _0: T = Zero::zero();
    let _1: T = One::one();
    let radix_gen: T = cast(radix as int);

    let len = buf.len();

    if len == 0 {
        if empty_zero {
            return Some(_0);
        } else {
            return None;
        }
    }

    if special {
        if buf == inf_buf || buf == positive_inf_buf {
            return NumStrConv::inf();
        } else if buf == negative_inf_buf {
            if negative {
                return NumStrConv::neg_inf();
            } else {
                return None;
            }
        } else if buf == nan_buf {
            return NumStrConv::NaN();
        }
    }

    let (start, accum_positive) = match buf[0] {
      '-' as u8 if !negative => return None,
      '-' as u8 => (1u, false),
      '+' as u8 => (1u, true),
       _        => (0u, true)
    };

    // Initialize accumulator with signed zero for floating point parsing to
    // work
    let mut accum      = if accum_positive { _0 } else { -_1 * _0};
    let mut last_accum = accum; // Necessary to detect overflow
    let mut i          = start;
    let mut exp_found  = false;

    // Parse integer part of number
    while i < len {
        let c = buf[i] as char;

        match char::to_digit(c, radix) {
            Some(digit) => {
                // shift accum one digit left
                accum *= radix_gen;

                // add/subtract current digit depending on sign
                if accum_positive {
                    accum += cast(digit as int);
                } else {
                    accum -= cast(digit as int);
                }

                // Detect overflow by comparing to last value
                if accum_positive && accum < last_accum { return None; }
                if !accum_positive && accum > last_accum { return None; }
                last_accum = accum;
            }
            None => match c {
                'e' | 'E' | 'p' | 'P' => {
                    exp_found = true;
                    break;                       // start of exponent
                }
                '.' if fractional => {
                    i += 1u;                     // skip the '.'
                    break;                       // start of fractional part
                }
                _ => return None                 // invalid number
            }
        }

        i += 1u;
    }

    // Parse fractional part of number
    // Skip if already reached start of exponent
    if !exp_found {
        let mut power = _1;

        while i < len {
            let c = buf[i] as char;

            match char::to_digit(c, radix) {
                Some(digit) => {
                    // Decrease power one order of magnitude
                    power /= radix_gen;

                    let digit_t: T = cast(digit);

                    // add/subtract current digit depending on sign
                    if accum_positive {
                        accum += digit_t * power;
                    } else {
                        accum -= digit_t * power;
                    }

                    // Detect overflow by comparing to last value
                    if accum_positive && accum < last_accum { return None; }
                    if !accum_positive && accum > last_accum { return None; }
                    last_accum = accum;
                }
                None => match c {
                    'e' | 'E' | 'p' | 'P' => {
                        exp_found = true;
                        break;                   // start of exponent
                    }
                    _ => return None             // invalid number
                }
            }

            i += 1u;
        }
    }

    // Special case: buf not empty, but does not contain any digit in front
    // of the exponent sign -> number is empty string
    if i == start {
        if empty_zero {
            return Some(_0);
        } else {
            return None;
        }
    }

    let mut multiplier = _1;

    if exp_found {
        let c = buf[i] as char;
        let base = match (c, exponent) {
            ('e', ExpDec) | ('E', ExpDec) => 10u,
            ('p', ExpBin) | ('P', ExpBin) => 2u,
            _ => return None // char doesn't fit given exponent format
        };

        // parse remaining bytes as decimal integer,
        // skipping the exponent char
        let exp: Option<int> = from_str_bytes_common(
            buf.slice(i+1, len), 10, true, false, false, ExpNone, false);

        match exp {
            Some(exp_pow) => {
                multiplier = if exp_pow < 0 {
                    _1 / pow_with_uint::<T>(base, (-exp_pow.to_int()) as uint)
                } else {
                    pow_with_uint::<T>(base, exp_pow.to_int() as uint)
                }
            }
            None => return None // invalid exponent -> invalid number
        }
    }

    Some(accum * multiplier)
}

/**
 * Parses a string as a number. This is a wrapper for
 * `from_str_bytes_common()`, for details see there.
 */
#[inline(always)]
pub fn from_str_common<T:NumCast+Zero+One+Ord+Copy+Div<T,T>+Mul<T,T>+
                              Sub<T,T>+Neg<T>+Add<T,T>+NumStrConv>(
        buf: &str, radix: uint, negative: bool, fractional: bool,
        special: bool, exponent: ExponentFormat, empty_zero: bool
        ) -> Option<T> {
    from_str_bytes_common(str::to_bytes(buf), radix, negative,
                            fractional, special, exponent, empty_zero)
}


text:
package ru.spbstu.icc.kspt.kuznetsov.fpf4mir.core.facts.request;

import ru.spbstu.icc.kspt.kuznetsov.fpf4mir.core.facts.activity.ActivityRelatedFact;

public interface Request extends ActivityRelatedFact{
	public long getRefId();
	public void setRefId(long refId);
}


text:
System.register(["github:aurelia/http-client@0.9.1/index"], function($__export) {
  return {  setters: [function(m) { for (var p in m) $__export(p, m[p]); }],  execute: function() {}  };
});


text:
const path = require("path");

/** @type {import("../../../../").Configuration} */
module.exports = {
	target: `browserslist:${path.join(__dirname, ".browserslistrc")}`,
	plugins: [
		compiler => {
			compiler.hooks.compilation.tap("Test", compilation => {
				expect(compilation.outputOptions.environment).toMatchInlineSnapshot(`
			Object {
			  "arrowFunction": false,
			  "bigIntLiteral": false,
			  "const": false,
			  "destructuring": false,
			  "dynamicImport": false,
			  "forOf": false,
			  "module": false,
			}
		`);
				expect(compilation.options.externalsPresets).toMatchInlineSnapshot(`
			Object {
			  "electron": false,
			  "electronMain": false,
			  "electronPreload": false,
			  "electronRenderer": false,
			  "node": false,
			  "nwjs": false,
			  "web": true,
			}
		`);
			});
		}
	]
};


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Podospora filiformis Cailleux

### Remarks
null


text:
using Newtonsoft.Json;

namespace ByteSharp.Entities.Auth
{

    public class Data
    {

        [JsonProperty("token")]
        public string Token { get; set; }

        [JsonProperty("user")]
        public User User { get; set; }
    }

}


text:
<?php

namespace Ongoing;

class ArticleClass
{

    /**
     * @var int $SystemId
     */
    protected $SystemId = null;

    /**
     * @var string $Name
     */
    protected $Name = null;

    /**
     * @var string $ArticleNumber
     */
    protected $ArticleNumber = null;

    /**
     * @var string $ProductCode
     */
    protected $ProductCode = null;

    /**
     * @var string $BarCode
     */
    protected $BarCode = null;

    /**
     * @var string $Description
     */
    protected $Description = null;

    /**
     * @var string $SupplierArticleNumber
     */
    protected $SupplierArticleNumber = null;

    /**
     * @var string $StatisticsNumber
     */
    protected $StatisticsNumber = null;

    /**
     * @var string $ArticleGroupName
     */
    protected $ArticleGroupName = null;

    /**
     * @var string $ArticleGroupCode
     */
    protected $ArticleGroupCode = null;

    /**
     * @var string $MainSupplierName
     */
    protected $MainSupplierName = null;

    /**
     * @var string $MainSupplierNumber
     */
    protected $MainSupplierNumber = null;

    /**
     * @var string $ArticleCategoryName
     */
    protected $ArticleCategoryName = null;

    /**
     * @var string $ArticleCategoryCode
     */
    protected $ArticleCategoryCode = null;

    /**
     * @var string $CountryOfOriginCode
     */
    protected $CountryOfOriginCode = null;

    /**
     * @var boolean $IsStockArticle
     */
    protected $IsStockArticle = null;

    /**
     * @var string $ArticleUnitCode
     */
    protected $ArticleUnitCode = null;

    /**
     * @var string $VatCode
     */
    protected $VatCode = null;

    /**
     * @var float $VatPercent
     */
    protected $VatPercent = null;

    /**
     * @var float $Length
     */
    protected $Length = null;

    /**
     * @var float $Width
     */
    protected $Width = null;

    /**
     * @var float $Height
     */
    protected $Height = null;

    /**
     * @var float $Price
     */
    protected $Price = null;

    /**
     * @var float $CustomerPrice
     */
    protected $CustomerPrice = null;

    /**
     * @var float $PurchasePrice
     */
    protected $PurchasePrice = null;

    /**
     * @var float $Weight
     */
    protected $Weight = null;

    /**
     * @var float $NetWeight
     */
    protected $NetWeight = null;

    /**
     * @var float $Volume
     */
    protected $Volume = null;

    /**
     * @var float $QuantityPerPallet
     */
    protected $QuantityPerPallet = null;

    /**
     * @var float $QuantityPerPackage
     */
    protected $QuantityPerPackage = null;

    /**
     * @var DangerousGoods[] $DangerousGoods
     */
    protected $DangerousGoods = null;

    /**
     * @var string $PurchaseCurrencyCode
     */
    protected $PurchaseCurrencyCode = null;

    /**
     * @var string $PurchaseCurrencyName
     */
    protected $PurchaseCurrencyName = null;

    /**
     * @param boolean $IsStockArticle
     */
    public function __construct($IsStockArticle)
    {
      $this->IsStockArticle = $IsStockArticle;
    }

    /**
     * @return int
     */
    public function getSystemId()
    {
      return $this->SystemId;
    }

    /**
     * @param int $SystemId
     * @return \Ongoing\ArticleClass
     */
    public function setSystemId($SystemId)
    {
      $this->SystemId = $SystemId;
      return $this;
    }

    /**
     * @return string
     */
    public function getName()
    {
      return $this->Name;
    }

    /**
     * @param string $Name
     * @return \Ongoing\ArticleClass
     */
    public function setName($Name)
    {
      $this->Name = $Name;
      return $this;
    }

    /**
     * @return string
     */
    public function getArticleNumber()
    {
      return $this->ArticleNumber;
    }

    /**
     * @param string $ArticleNumber
     * @return \Ongoing\ArticleClass
     */
    public function setArticleNumber($ArticleNumber)
    {
      $this->ArticleNumber = $ArticleNumber;
      return $this;
    }

    /**
     * @return string
     */
    public function getProductCode()
    {
      return $this->ProductCode;
    }

    /**
     * @param string $ProductCode
     * @return \Ongoing\ArticleClass
     */
    public function setProductCode($ProductCode)
    {
      $this->ProductCode = $ProductCode;
      return $this;
    }

    /**
     * @return string
     */
    public function getBarCode()
    {
      return $this->BarCode;
    }

    /**
     * @param string $BarCode
     * @return \Ongoing\ArticleClass
     */
    public function setBarCode($BarCode)
    {
      $this->BarCode = $BarCode;
      return $this;
    }

    /**
     * @return string
     */
    public function getDescription()
    {
      return $this->Description;
    }

    /**
     * @param string $Description
     * @return \Ongoing\ArticleClass
     */
    public function setDescription($Description)
    {
      $this->Description = $Description;
      return $this;
    }

    /**
     * @return string
     */
    public function getSupplierArticleNumber()
    {
      return $this->SupplierArticleNumber;
    }

    /**
     * @param string $SupplierArticleNumber
     * @return \Ongoing\ArticleClass
     */
    public function setSupplierArticleNumber($SupplierArticleNumber)
    {
      $this->SupplierArticleNumber = $SupplierArticleNumber;
      return $this;
    }

    /**
     * @return string
     */
    public function getStatisticsNumber()
    {
      return $this->StatisticsNumber;
    }

    /**
     * @param string $StatisticsNumber
     * @return \Ongoing\ArticleClass
     */
    public function setStatisticsNumber($StatisticsNumber)
    {
      $this->StatisticsNumber = $StatisticsNumber;
      return $this;
    }

    /**
     * @return string
     */
    public function getArticleGroupName()
    {
      return $this->ArticleGroupName;
    }

    /**
     * @param string $ArticleGroupName
     * @return \Ongoing\ArticleClass
     */
    public function setArticleGroupName($ArticleGroupName)
    {
      $this->ArticleGroupName = $ArticleGroupName;
      return $this;
    }

    /**
     * @return string
     */
    public function getArticleGroupCode()
    {
      return $this->ArticleGroupCode;
    }

    /**
     * @param string $ArticleGroupCode
     * @return \Ongoing\ArticleClass
     */
    public function setArticleGroupCode($ArticleGroupCode)
    {
      $this->ArticleGroupCode = $ArticleGroupCode;
      return $this;
    }

    /**
     * @return string
     */
    public function getMainSupplierName()
    {
      return $this->MainSupplierName;
    }

    /**
     * @param string $MainSupplierName
     * @return \Ongoing\ArticleClass
     */
    public function setMainSupplierName($MainSupplierName)
    {
      $this->MainSupplierName = $MainSupplierName;
      return $this;
    }

    /**
     * @return string
     */
    public function getMainSupplierNumber()
    {
      return $this->MainSupplierNumber;
    }

    /**
     * @param string $MainSupplierNumber
     * @return \Ongoing\ArticleClass
     */
    public function setMainSupplierNumber($MainSupplierNumber)
    {
      $this->MainSupplierNumber = $MainSupplierNumber;
      return $this;
    }

    /**
     * @return string
     */
    public function getArticleCategoryName()
    {
      return $this->ArticleCategoryName;
    }

    /**
     * @param string $ArticleCategoryName
     * @return \Ongoing\ArticleClass
     */
    public function setArticleCategoryName($ArticleCategoryName)
    {
      $this->ArticleCategoryName = $ArticleCategoryName;
      return $this;
    }

    /**
     * @return string
     */
    public function getArticleCategoryCode()
    {
      return $this->ArticleCategoryCode;
    }

    /**
     * @param string $ArticleCategoryCode
     * @return \Ongoing\ArticleClass
     */
    public function setArticleCategoryCode($ArticleCategoryCode)
    {
      $this->ArticleCategoryCode = $ArticleCategoryCode;
      return $this;
    }

    /**
     * @return string
     */
    public function getCountryOfOriginCode()
    {
      return $this->CountryOfOriginCode;
    }

    /**
     * @param string $CountryOfOriginCode
     * @return \Ongoing\ArticleClass
     */
    public function setCountryOfOriginCode($CountryOfOriginCode)
    {
      $this->CountryOfOriginCode = $CountryOfOriginCode;
      return $this;
    }

    /**
     * @return boolean
     */
    public function getIsStockArticle()
    {
      return $this->IsStockArticle;
    }

    /**
     * @param boolean $IsStockArticle
     * @return \Ongoing\ArticleClass
     */
    public function setIsStockArticle($IsStockArticle)
    {
      $this->IsStockArticle = $IsStockArticle;
      return $this;
    }

    /**
     * @return string
     */
    public function getArticleUnitCode()
    {
      return $this->ArticleUnitCode;
    }

    /**
     * @param string $ArticleUnitCode
     * @return \Ongoing\ArticleClass
     */
    public function setArticleUnitCode($ArticleUnitCode)
    {
      $this->ArticleUnitCode = $ArticleUnitCode;
      return $this;
    }

    /**
     * @return string
     */
    public function getVatCode()
    {
      return $this->VatCode;
    }

    /**
     * @param string $VatCode
     * @return \Ongoing\ArticleClass
     */
    public function setVatCode($VatCode)
    {
      $this->VatCode = $VatCode;
      return $this;
    }

    /**
     * @return float
     */
    public function getVatPercent()
    {
      return $this->VatPercent;
    }

    /**
     * @param float $VatPercent
     * @return \Ongoing\ArticleClass
     */
    public function setVatPercent($VatPercent)
    {
      $this->VatPercent = $VatPercent;
      return $this;
    }

    /**
     * @return float
     */
    public function getLength()
    {
      return $this->Length;
    }

    /**
     * @param float $Length
     * @return \Ongoing\ArticleClass
     */
    public function setLength($Length)
    {
      $this->Length = $Length;
      return $this;
    }

    /**
     * @return float
     */
    public function getWidth()
    {
      return $this->Width;
    }

    /**
     * @param float $Width
     * @return \Ongoing\ArticleClass
     */
    public function setWidth($Width)
    {
      $this->Width = $Width;
      return $this;
    }

    /**
     * @return float
     */
    public function getHeight()
    {
      return $this->Height;
    }

    /**
     * @param float $Height
     * @return \Ongoing\ArticleClass
     */
    public function setHeight($Height)
    {
      $this->Height = $Height;
      return $this;
    }

    /**
     * @return float
     */
    public function getPrice()
    {
      return $this->Price;
    }

    /**
     * @param float $Price
     * @return \Ongoing\ArticleClass
     */
    public function setPrice($Price)
    {
      $this->Price = $Price;
      return $this;
    }

    /**
     * @return float
     */
    public function getCustomerPrice()
    {
      return $this->CustomerPrice;
    }

    /**
     * @param float $CustomerPrice
     * @return \Ongoing\ArticleClass
     */
    public function setCustomerPrice($CustomerPrice)
    {
      $this->CustomerPrice = $CustomerPrice;
      return $this;
    }

    /**
     * @return float
     */
    public function getPurchasePrice()
    {
      return $this->PurchasePrice;
    }

    /**
     * @param float $PurchasePrice
     * @return \Ongoing\ArticleClass
     */
    public function setPurchasePrice($PurchasePrice)
    {
      $this->PurchasePrice = $PurchasePrice;
      return $this;
    }

    /**
     * @return float
     */
    public function getWeight()
    {
      return $this->Weight;
    }

    /**
     * @param float $Weight
     * @return \Ongoing\ArticleClass
     */
    public function setWeight($Weight)
    {
      $this->Weight = $Weight;
      return $this;
    }

    /**
     * @return float
     */
    public function getNetWeight()
    {
      return $this->NetWeight;
    }

    /**
     * @param float $NetWeight
     * @return \Ongoing\ArticleClass
     */
    public function setNetWeight($NetWeight)
    {
      $this->NetWeight = $NetWeight;
      return $this;
    }

    /**
     * @return float
     */
    public function getVolume()
    {
      return $this->Volume;
    }

    /**
     * @param float $Volume
     * @return \Ongoing\ArticleClass
     */
    public function setVolume($Volume)
    {
      $this->Volume = $Volume;
      return $this;
    }

    /**
     * @return float
     */
    public function getQuantityPerPallet()
    {
      return $this->QuantityPerPallet;
    }

    /**
     * @param float $QuantityPerPallet
     * @return \Ongoing\ArticleClass
     */
    public function setQuantityPerPallet($QuantityPerPallet)
    {
      $this->QuantityPerPallet = $QuantityPerPallet;
      return $this;
    }

    /**
     * @return float
     */
    public function getQuantityPerPackage()
    {
      return $this->QuantityPerPackage;
    }

    /**
     * @param float $QuantityPerPackage
     * @return \Ongoing\ArticleClass
     */
    public function setQuantityPerPackage($QuantityPerPackage)
    {
      $this->QuantityPerPackage = $QuantityPerPackage;
      return $this;
    }

    /**
     * @return DangerousGoods[]
     */
    public function getDangerousGoods()
    {
      return $this->DangerousGoods;
    }

    /**
     * @param DangerousGoods[] $DangerousGoods
     * @return \Ongoing\ArticleClass
     */
    public function setDangerousGoods(array $DangerousGoods = null)
    {
      $this->DangerousGoods = $DangerousGoods;
      return $this;
    }

    /**
     * @return string
     */
    public function getPurchaseCurrencyCode()
    {
      return $this->PurchaseCurrencyCode;
    }

    /**
     * @param string $PurchaseCurrencyCode
     * @return \Ongoing\ArticleClass
     */
    public function setPurchaseCurrencyCode($PurchaseCurrencyCode)
    {
      $this->PurchaseCurrencyCode = $PurchaseCurrencyCode;
      return $this;
    }

    /**
     * @return string
     */
    public function getPurchaseCurrencyName()
    {
      return $this->PurchaseCurrencyName;
    }

    /**
     * @param string $PurchaseCurrencyName
     * @return \Ongoing\ArticleClass
     */
    public function setPurchaseCurrencyName($PurchaseCurrencyName)
    {
      $this->PurchaseCurrencyName = $PurchaseCurrencyName;
      return $this;
    }

}


text:
<?xml version='1.0' encoding='UTF-8'?>
<project>
  <actions/>
  <description>Stream Analysis - Runs Simson Garfinkel's bulk_Extractor against both Memory and Disk Image</description>
  <keepDependencies>false</keepDependencies>
  <properties>
    <hudson.model.ParametersDefinitionProperty>
      <parameterDefinitions>
        <hudson.model.StringParameterDefinition>
          <name>MEMORY_IMAGE_FILE</name>
          <description>Location of the raw memory image</description>
          <defaultValue>/cases/xp-tdungan-10.3.58.7/xp-tdungan-memory/xp-tdungan-memory-raw.001</defaultValue>
        </hudson.model.StringParameterDefinition>
        <hudson.model.StringParameterDefinition>
          <name>DISK_IMAGE_FILE</name>
          <description>Location of the raw disk image</description>
          <defaultValue>/cases/xp-tdungan-10.3.58.7/xp-tdungan-c-drive/xp-tdungan-c-drive.E01</defaultValue>
        </hudson.model.StringParameterDefinition>
        <hudson.model.StringParameterDefinition>
          <name>DISK_ARTIFACTS</name>
          <description></description>
          <defaultValue>/artifacts/xp-tdungan-10.3.58.7/bulk_extractor_disk</defaultValue>
        </hudson.model.StringParameterDefinition>
        <hudson.model.StringParameterDefinition>
          <name>MEMORY_ARTIFACTS</name>
          <description></description>
          <defaultValue>/artifacts/xp-tdungan-10.3.58.7/bulk_extractor_memory</defaultValue>
        </hudson.model.StringParameterDefinition>
      </parameterDefinitions>
    </hudson.model.ParametersDefinitionProperty>
  </properties>
  <scm class="hudson.scm.NullSCM"/>
  <canRoam>true</canRoam>
  <disabled>false</disabled>
  <blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
  <blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
  <triggers/>
  <concurrentBuild>true</concurrentBuild>
  <builders>
    <hudson.plugins.parameterizedtrigger.TriggerBuilder plugin="parameterized-trigger@2.25">
      <configs>
        <hudson.plugins.parameterizedtrigger.BlockableBuildTriggerConfig>
          <configs>
            <hudson.plugins.parameterizedtrigger.CurrentBuildParameters/>
          </configs>
          <projects>bulk_extractor_memory,bulk_extractor_disk</projects>
          <condition>ALWAYS</condition>
          <triggerWithNoParameters>false</triggerWithNoParameters>
          <block>
            <buildStepFailureThreshold>
              <name>FAILURE</name>
              <ordinal>2</ordinal>
              <color>RED</color>
              <completeBuild>true</completeBuild>
            </buildStepFailureThreshold>
            <unstableThreshold>
              <name>UNSTABLE</name>
              <ordinal>1</ordinal>
              <color>YELLOW</color>
              <completeBuild>true</completeBuild>
            </unstableThreshold>
            <failureThreshold>
              <name>FAILURE</name>
              <ordinal>2</ordinal>
              <color>RED</color>
              <completeBuild>true</completeBuild>
            </failureThreshold>
          </block>
          <buildAllNodesWithLabel>false</buildAllNodesWithLabel>
        </hudson.plugins.parameterizedtrigger.BlockableBuildTriggerConfig>
      </configs>
    </hudson.plugins.parameterizedtrigger.TriggerBuilder>
  </builders>
  <publishers/>
  <buildWrappers/>
</project>


text:
{% load bootstrap3 %}
<form method="POST" novalidate="" enctype="multipart/form-data">
    {% csrf_token %}
    {% bootstrap_form form %}
    {% buttons %}
    <button type="submit" class="btn btn-primary">
      Guardar
    </button>
    <a href="{% url 'paciente_list' %}">
        <input type="button" class="btn btn.primary" value="Volver" />
    </a>
    {% endbuttons %}
</form>