text:
// Copyright (c) 2011-2013 Turbulenz Limited
/*global VMath*/
/*global WebGLGraphicsDevice*/
/*global WebGLInputDevice*/
/*global WebGLSoundDevice*/
/*global WebGLPhysicsDevice*/
/*global WebGLNetworkDevice*/
/*global Float32Array*/
/*global console*/
/*global window*/
"use strict";
;
;
;
;
var WebGLTurbulenzEngine = (function () {
    function WebGLTurbulenzEngine() {
        this.version = '0.28.0.0';
    }
    WebGLTurbulenzEngine.prototype.setInterval = function (f, t) {
        var that = this;
        return window.setInterval(function () {
            that.updateTime();
            f();
        }, t);
    };
    WebGLTurbulenzEngine.prototype.clearInterval = function (i) {
        window.clearInterval(i);
    };
    WebGLTurbulenzEngine.prototype.createGraphicsDevice = function (params) {
        if (this.graphicsDevice) {
            this.callOnError('GraphicsDevice already created');
            return null;
        }
        else {
            var graphicsDevice = WebGLGraphicsDevice.create(this.canvas, params);
            this.graphicsDevice = graphicsDevice;
            return graphicsDevice;
        }
    };
    WebGLTurbulenzEngine.prototype.createPhysicsDevice = function (params) {
        if (this.physicsDevice) {
            this.callOnError('PhysicsDevice already created');
            return null;
        }
        else {
            var physicsDevice;
            var plugin = this.getPluginObject();
            if (plugin) {
                physicsDevice = plugin.createPhysicsDevice(params);
            }
            else {
                physicsDevice = WebGLPhysicsDevice.create();
            }
            this.physicsDevice = physicsDevice;
            return physicsDevice;
        }
    };
    WebGLTurbulenzEngine.prototype.createSoundDevice = function (params) {
        if (this.soundDevice) {
            this.callOnError('SoundDevice already created');
            return null;
        }
        else {
            var soundDevice;
            var plugin = this.getPluginObject();
            if (plugin) {
                soundDevice = plugin.createSoundDevice(params);
            }
            else {
                soundDevice = WebGLSoundDevice.create(params);
            }
            this.soundDevice = soundDevice;
            return soundDevice;
        }
    };
    WebGLTurbulenzEngine.prototype.createInputDevice = function (params) {
        if (this.inputDevice) {
            this.callOnError('InputDevice already created');
            return null;
        }
        else {
            var inputDevice = WebGLInputDevice.create(this.canvas);
            this.inputDevice = inputDevice;
            return inputDevice;
        }
    };
    WebGLTurbulenzEngine.prototype.createNetworkDevice = function (params) {
        if (this.networkDevice) {
            throw 'NetworkDevice already created';
        }
        else {
            var networkDevice = WebGLNetworkDevice.create(params);
            this.networkDevice = networkDevice;
            return networkDevice;
        }
    };
    WebGLTurbulenzEngine.prototype.createMathDevice = function (params) {
        try {
            var testVector = new Float32Array([1, 2, 3]);
            VMath.v3Build.apply(VMath, testVector);
            testVector[0] = VMath.FLOAT_MAX;
            VMath.FLOAT_MAX = testVector[0];
        }
        catch (e) {
        }
        return WebGLMathDevice;
    };
    WebGLTurbulenzEngine.prototype.createNativeMathDevice = function (params) {
        return WebGLMathDevice;
    };
    WebGLTurbulenzEngine.prototype.getGraphicsDevice = function () {
        var graphicsDevice = this.graphicsDevice;
        if (graphicsDevice === null) {
            this.callOnError("GraphicsDevice not created yet.");
        }
        return graphicsDevice;
    };
    WebGLTurbulenzEngine.prototype.getPhysicsDevice = function () {
        return this.physicsDevice;
    };
    WebGLTurbulenzEngine.prototype.getSoundDevice = function () {
        return this.soundDevice;
    };
    WebGLTurbulenzEngine.prototype.getInputDevice = function () {
        return this.inputDevice;
    };
    WebGLTurbulenzEngine.prototype.getNetworkDevice = function () {
        return this.networkDevice;
    };
    WebGLTurbulenzEngine.prototype.getMathDevice = function () {
        return WebGLMathDevice;
    };
    WebGLTurbulenzEngine.prototype.getNativeMathDevice = function () {
        return WebGLMathDevice;
    };
    WebGLTurbulenzEngine.prototype.getObjectStats = function () {
        return null;
    };
    WebGLTurbulenzEngine.prototype.flush = function () {
    };
    WebGLTurbulenzEngine.prototype.run = function () {
    };
    WebGLTurbulenzEngine.prototype.encrypt = function (msg) {
        return msg;
    };
    WebGLTurbulenzEngine.prototype.decrypt = function (msg) {
        return msg;
    };
    WebGLTurbulenzEngine.prototype.generateSignature = function (msg) {
        return null;
    };
    WebGLTurbulenzEngine.prototype.verifySignature = function (msg, sig) {
        return true;
    };
    WebGLTurbulenzEngine.prototype.onerror = function (msg) {
        console.error(msg);
    };
    WebGLTurbulenzEngine.prototype.onwarning = function (msg) {
        console.warn(msg);
    };
    WebGLTurbulenzEngine.prototype.onperformancewarning = function (msg) {
    };
    WebGLTurbulenzEngine.prototype.getSystemInfo = function () {
        return this.systemInfo;
    };
    WebGLTurbulenzEngine.prototype.request = function (url, callback) {
        var that = this;
        var xhr;
        if (window.XMLHttpRequest) {
            xhr = new window.XMLHttpRequest();
        }
        else if (window.ActiveXObject) {
            xhr = new window.ActiveXObject("Microsoft.XMLHTTP");
        }
        else {
            that.callOnError("No XMLHTTPRequest object could be created");
            return;
        }
        var httpRequestCallback = function httpRequestCallbackFn() {
            if (xhr.readyState === 4) {
                if (!that.isUnloading()) {
                    var xhrResponseText = xhr.responseText;
                    var xhrStatus = xhr.status;
                    if ("" === xhrResponseText) {
                        xhrResponseText = null;
                    }
                    if (xhrStatus === 0 && xhrResponseText && window.location.protocol === "file:") {
                        xhrStatus = 200;
                    }
                    else if (null === xhr.getResponseHeader("Content-Type") &&
                        "" === xhr.getAllResponseHeaders()) {
                        callback(null, 0);
                        return;
                    }
                    if (xhrStatus !== 0) {
                        if (404 === xhrStatus) {
                            xhrResponseText = null;
                        }
                        callback(xhrResponseText, xhrStatus);
                    }
                    else {
                        callback(xhrResponseText, 0);
                    }
                }
                xhr.onreadystatechange = null;
                xhr = null;
                callback = null;
            }
        };
        xhr.open('GET', url, true);
        if (callback) {
            xhr.onreadystatechange = httpRequestCallback;
        }
        xhr.send();
    };
    WebGLTurbulenzEngine.prototype.destroy = function () {
        if (this.networkDevice) {
            delete this.networkDevice;
        }
        if (this.inputDevice) {
            this.inputDevice.destroy();
            delete this.inputDevice;
        }
        if (this.physicsDevice) {
            delete this.physicsDevice;
        }
        if (this.soundDevice) {
            if (this.soundDevice.destroy) {
                this.soundDevice.destroy();
            }
            delete this.soundDevice;
        }
        if (this.graphicsDevice) {
            this.graphicsDevice.destroy();
            delete this.graphicsDevice;
        }
        if (this.canvas) {
            delete this.canvas;
        }
        if (this.resizeCanvas) {
            window.removeEventListener('resize', this.resizeCanvas, false);
            delete this.resizeCanvas;
        }
        if (this.handleZeroTimeoutMessages) {
            window.removeEventListener("message", this.handleZeroTimeoutMessages, true);
            delete this.handleZeroTimeoutMessages;
        }
    };
    WebGLTurbulenzEngine.prototype.getPluginObject = function () {
        if (!this.plugin &&
            this.pluginId) {
            this.plugin = document.getElementById(this.pluginId);
        }
        return this.plugin;
    };
    WebGLTurbulenzEngine.prototype.unload = function () {
        if (!this.unloading) {
            this.unloading = true;
            if (this.onunload) {
                this.onunload();
            }
            if (this.destroy) {
                this.destroy();
            }
        }
    };
    WebGLTurbulenzEngine.prototype.isUnloading = function () {
        return this.unloading;
    };
    WebGLTurbulenzEngine.prototype.enableProfiling = function () {
    };
    WebGLTurbulenzEngine.prototype.startProfiling = function () {
        if (console && console.profile && console.profileEnd) {
            console.profile("turbulenz");
        }
    };
    WebGLTurbulenzEngine.prototype.stopProfiling = function () {
        var result;
        if (console && console.profile && console.profileEnd) {
            console.profileEnd();
            if (console.profiles) {
                result = console.profiles[console.profiles.length - 1];
            }
        }
        return result;
    };
    WebGLTurbulenzEngine.prototype.callOnError = function (msg) {
        var onerror = this.onerror;
        if (onerror) {
            onerror(msg);
        }
    };
    WebGLTurbulenzEngine.create = function (params) {
        var tz = new WebGLTurbulenzEngine();
        var canvas = params.canvas;
        var fillParent = params.fillParent;
        window.TurbulenzEngineCanvas = tz;
        tz.pluginId = params.pluginId;
        tz.plugin = null;
        var getTime = Date.now;
        var performance = window.performance;
        if (performance) {
            if (performance.now) {
                getTime = function getTimeFn() {
                    return performance.now();
                };
            }
            else if (performance.webkitNow) {
                getTime = function getTimeFn() {
                    return performance.webkitNow();
                };
            }
        }
        tz.getTime = getTime;
        var baseTime = getTime();
        var canUseDefineProperty = true;
        var navStr = navigator.userAgent;
        var navVersionIdx = navStr.indexOf("Version/6.0");
        if (-1 !== navVersionIdx) {
            if (-1 !== navStr.substring(navVersionIdx).indexOf("Safari/")) {
                canUseDefineProperty = false;
            }
        }
        if (canUseDefineProperty && Object.defineProperty) {
            Object.defineProperty(tz, "time", {
                get: function () {
                    return ((getTime() - baseTime) * 0.001);
                },
                set: function (newValue) {
                    if (typeof newValue === 'number') {
                        baseTime = (getTime() - (newValue * 1000));
                    }
                    else {
                        tz.callOnError("Must set 'time' attribute to a number");
                    }
                },
                enumerable: false,
                configurable: false
            });
            tz.updateTime = function () {
            };
        }
        else {
            tz.updateTime = function () {
                this.time = ((getTime() - baseTime) * 0.001);
            };
        }
        if (window.postMessage) {
            var zeroTimeoutMessageName = "0-timeout-message";
            var timeouts = [];
            var timeId = 0;
            var setZeroTimeout = function setZeroTimeoutFn(fn) {
                timeId += 1;
                var timeout = {
                    id: timeId,
                    fn: fn
                };
                timeouts.push(timeout);
                window.postMessage(zeroTimeoutMessageName, "*");
                return timeout;
            };
            var clearZeroTimeout = function clearZeroTimeoutFn(timeout) {
                var id = timeout.id;
                var numTimeouts = timeouts.length;
                for (var n = 0; n < numTimeouts; n += 1) {
                    if (timeouts[n].id === id) {
                        timeouts.splice(n, 1);
                        return;
                    }
                }
            };
            var handleZeroTimeoutMessages = function handleZeroTimeoutMessagesFn(event) {
                if (event.source === window &&
                    event.data === zeroTimeoutMessageName) {
                    event.stopPropagation();
                    if (timeouts.length && !tz.isUnloading()) {
                        var timeout = timeouts.shift();
                        var fn = timeout.fn;
                        fn();
                    }
                }
            };
            tz.handleZeroTimeoutMessages = handleZeroTimeoutMessages;
            window.addEventListener("message", handleZeroTimeoutMessages, true);
            tz.setTimeout = function (f, t) {
                if (t < 1) {
                    return (setZeroTimeout(f));
                }
                else {
                    var that = this;
                    return window.setTimeout(function () {
                        that.updateTime();
                        if (!that.isUnloading()) {
                            f();
                        }
                    }, t);
                }
            };
            tz.clearTimeout = function (i) {
                if (typeof i === 'object') {
                    return clearZeroTimeout(i);
                }
                else {
                    return window.clearTimeout(i);
                }
            };
        }
        else {
            tz.setTimeout = function (f, t) {
                var that = this;
                return window.setTimeout(function () {
                    that.updateTime();
                    if (!that.isUnloading()) {
                        f();
                    }
                }, t);
            };
            tz.clearTimeout = function (i) {
                return window.clearTimeout(i);
            };
        }
        var requestAnimationFrame = (window.requestAnimationFrame ||
            window.webkitRequestAnimationFrame ||
            window.oRequestAnimationFrame ||
            window.msRequestAnimationFrame ||
            window.mozRequestAnimationFrame);
        if (requestAnimationFrame) {
            tz.setInterval = function (f, t) {
                var that = this;
                if (Math.abs(t - (1000 / 60)) <= 1) {
                    var interval = {
                        enabled: true
                    };
                    var nextFrameTime = (getTime() + 16.6);
                    var wrap1 = function wrap1() {
                        if (interval.enabled) {
                            var currentTime = getTime();
                            var diff = (currentTime - nextFrameTime);
                            if (0 <= diff) {
                                if (diff > 50) {
                                    nextFrameTime = (currentTime + 16.6);
                                }
                                else {
                                    nextFrameTime += 16.6;
                                }
                                that.updateTime();
                                if (!that.isUnloading()) {
                                    f();
                                }
                            }
                            requestAnimationFrame(wrap1, that.canvas);
                        }
                    };
                    requestAnimationFrame(wrap1, that.canvas);
                    return interval;
                }
                else {
                    var wrap2 = function wrap2() {
                        that.updateTime();
                        if (!that.isUnloading()) {
                            f();
                        }
                    };
                    return window.setInterval(wrap2, t);
                }
            };
            tz.clearInterval = function (i) {
                if (typeof i === 'object') {
                    i.enabled = false;
                }
                else {
                    window.clearInterval(i);
                }
            };
        }
        tz.canvas = canvas;
        tz.networkDevice = null;
        tz.inputDevice = null;
        tz.physicsDevice = null;
        tz.soundDevice = null;
        tz.graphicsDevice = null;
        if (fillParent) {
            tz.resizeCanvas = function () {
                if (document.fullscreenElement === canvas ||
                    document.mozFullScreenElement === canvas ||
                    document.webkitFullscreenElement === canvas ||
                    document.msFullscreenElement === canvas) {
                    canvas.width = window.innerWidth;
                    canvas.height = window.innerHeight;
                }
                else {
                    var parentNode = canvas.parentNode;
                    canvas.width = parentNode.clientWidth;
                    canvas.height = parentNode.clientHeight;
                }
            };
            tz.resizeCanvas();
            window.addEventListener('resize', tz.resizeCanvas, false);
        }
        try {
            var previousOnBeforeUnload = window.onbeforeunload;
            window.onbeforeunload = function () {
                tz.unload();
                if (previousOnBeforeUnload) {
                    previousOnBeforeUnload.call(this);
                }
            };
        }
        catch (e) {
        }
        ;
        tz.time = 0;
        var systemInfo = {
            architecture: '',
            cpuDescription: '',
            cpuVendor: '',
            numPhysicalCores: 1,
            numLogicalCores: 1,
            ramInMegabytes: 0,
            frequencyInMegaHZ: 0,
            osVersionMajor: 0,
            osVersionMinor: 0,
            osVersionBuild: 0,
            osName: navigator.platform,
            platformProfile: "desktop",
            userLocale: (navigator.language || navigator.userLanguage).replace('-', '_')
        };
        var looksLikeNetbook = function looksLikeNetbookFn() {
            var minScreenDim = Math.min(window.screen.height, window.screen.width);
            return minScreenDim < 900;
        };
        var userAgent = navigator.userAgent;
        var osIndex = userAgent.indexOf('Windows');
        if (osIndex !== -1) {
            systemInfo.osName = 'Windows';
            if (navigator.platform === 'Win64') {
                systemInfo.architecture = 'x86_64';
            }
            else if (navigator.platform === 'Win32') {
                systemInfo.architecture = 'x86';
            }
            osIndex += 7;
            if (userAgent.slice(osIndex, (osIndex + 4)) === ' NT ') {
                osIndex += 4;
                systemInfo.osVersionMajor = parseInt(userAgent.slice(osIndex, (osIndex + 1)), 10);
                systemInfo.osVersionMinor = parseInt(userAgent.slice((osIndex + 2), (osIndex + 4)), 10);
            }
            if (looksLikeNetbook()) {
                systemInfo.platformProfile = "tablet";
                if (debug) {
                    debug.log("Setting platformProfile to 'tablet'");
                }
            }
        }
        else {
            osIndex = userAgent.indexOf('Mac OS X');
            if (osIndex !== -1) {
                systemInfo.osName = 'Darwin';
                if (navigator.platform.indexOf('Intel') !== -1) {
                    systemInfo.architecture = 'x86';
                }
                osIndex += 9;
                systemInfo.osVersionMajor = parseInt(userAgent.slice(osIndex, (osIndex + 2)), 10);
                systemInfo.osVersionMinor = parseInt(userAgent.slice((osIndex + 3), (osIndex + 4)), 10);
                systemInfo.osVersionBuild = (parseInt(userAgent.slice((osIndex + 5), (osIndex + 6)), 10) || 0);
            }
            else {
                osIndex = userAgent.indexOf('Linux');
                if (osIndex !== -1) {
                    systemInfo.osName = 'Linux';
                    if (navigator.platform.indexOf('64') !== -1) {
                        systemInfo.architecture = 'x86_64';
                    }
                    else if (navigator.platform.indexOf('x86') !== -1) {
                        systemInfo.architecture = 'x86';
                    }
                    if (looksLikeNetbook()) {
                        systemInfo.platformProfile = "tablet";
                        if (debug) {
                            debug.log("Setting platformProfile to 'tablet'");
                        }
                    }
                }
                else {
                    osIndex = userAgent.indexOf('Android');
                    if (-1 !== osIndex) {
                        systemInfo.osName = 'Android';
                        if (navigator.platform.indexOf('arm')) {
                            systemInfo.architecture = 'arm';
                        }
                        else if (navigator.platform.indexOf('x86')) {
                            systemInfo.architecture = 'x86';
                        }
                        if (-1 !== userAgent.indexOf('Mobile')) {
                            systemInfo.platformProfile = "smartphone";
                        }
                        else {
                            systemInfo.platformProfile = "tablet";
                        }
                    }
                    else {
                        if (-1 !== userAgent.indexOf("iPhone") ||
                            -1 !== userAgent.indexOf("iPod")) {
                            systemInfo.osName = 'iOS';
                            systemInfo.architecture = 'arm';
                            systemInfo.platformProfile = 'smartphone';
                        }
                        else if (-1 !== userAgent.indexOf("iPad")) {
                            systemInfo.osName = 'iOS';
                            systemInfo.architecture = 'arm';
                            systemInfo.platformProfile = 'tablet';
                        }
                    }
                }
            }
        }
        tz.systemInfo = systemInfo;
        var b64ConversionTable = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".split('');
        tz.base64Encode = function base64EncodeFn(bytes) {
            var output = "";
            var numBytes = bytes.length;
            var valueToChar = b64ConversionTable;
            var n, chr1, chr2, chr3, enc1, enc2, enc3, enc4;
            n = 0;
            while (n < numBytes) {
                chr1 = bytes[n];
                n += 1;
                enc1 = (chr1 >> 2);
                if (n < numBytes) {
                    chr2 = bytes[n];
                    n += 1;
                    if (n < numBytes) {
                        chr3 = bytes[n];
                        n += 1;
                        enc2 = (((chr1 & 3) << 4) | (chr2 >> 4));
                        enc3 = (((chr2 & 15) << 2) | (chr3 >> 6));
                        enc4 = (chr3 & 63);
                    }
                    else {
                        enc2 = (((chr1 & 3) << 4) | (chr2 >> 4));
                        enc3 = ((chr2 & 15) << 2);
                        enc4 = 64;
                    }
                }
                else {
                    enc2 = ((chr1 & 3) << 4);
                    enc3 = 64;
                    enc4 = 64;
                }
                output += valueToChar[enc1];
                output += valueToChar[enc2];
                output += valueToChar[enc3];
                output += valueToChar[enc4];
            }
            return output;
        };
        return tz;
    };
    return WebGLTurbulenzEngine;
})();
window.WebGLTurbulenzEngine = WebGLTurbulenzEngine;


text:
package mock;

import org.jitsi.jicofo.xmpp.*;
import org.osgi.framework.*;

/**
 * Activator does the job of "main" method - executed during normal program
 * flow.
 *
 * @author Pawel Domas
 */
public class MockMainMethodActivator
    implements BundleActivator
{
    private static boolean started;

    private static FocusComponent focusComponent;

    @Override
    public void start(BundleContext context)
        throws Exception
    {
        focusComponent = new FocusComponent(true, "focus@testserver");

        focusComponent.init();

        synchronized (MockMainMethodActivator.class)
        {
            started = true;
            MockMainMethodActivator.class.notifyAll();
        }
    }

    @Override
    public void stop(BundleContext context)
        throws Exception
    {
        focusComponent.dispose();
    }

    public static FocusComponent getFocusComponent()
    {
        return focusComponent;
    }

    public static void waitUntilStarted(long timeout)
    {
        synchronized (MockMainMethodActivator.class)
        {
            if (!started)
            {
                try
                {
                    MockMainMethodActivator.class.wait(timeout);
                    if (!started)
                    {
                        throw new RuntimeException(
                            "Failed to wait for activator to get started");
                    }
                }
                catch (InterruptedException e)
                {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace AppliedAlgebra.GfAlgorithms.Tests.TestCases.BiVariablePolynomial
{
    using BiVariablePolynomials;

    public class DivideByXDegreeTestCase
    {
        public BiVariablePolynomial Polynomial { get; set; }

        public BiVariablePolynomial Expected { get; set; }
    }
}


text:
<!--
@license
Copyright (c) 2017 The expand.js authors. All rights reserved.
This code may only be used under the BSD style license found at https://expandjs.github.io/LICENSE.txt
The complete set of authors may be found at https://expandjs.github.io/AUTHORS.txt
The complete set of contributors may be found at https://expandjs.github.io/CONTRIBUTORS.txt
-->

<!--
A behavior used to add tab capabilities on a web component.

@behavior xp-tabs-behavior
@since 1.0.0
@category behaviors
@description A behavior used to add tab capabilities on a web component
@keywords expandjs, web components

@homepage https://expandjs.com/components/xp-tabs-behavior
@repository https://github.com/expandjs/xp-elements
@source https://github.com/expandjs/xp-elements/blob/master/xp-tabs-behavior.html

@behavior xp-master-slave-behavior /bower_components/xp-elements/xp-master-slave-behavior.html
-->

<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="../expandjs/expandjs.html">
<link rel="import" href="xp-master-slave-behavior.html">

<script>

    /**
     * @polymerBehavior Polymer.XPTabBehaviorImp
     */
    Polymer.XPTabBehaviorImp = {

        // CLASSES
        classes: ['tab'],

        /*********************************************************************/

        // OBSERVERS
        observers: [
            '__handleCompare(data.*, memento.*)'
        ],

        // PROPERTIES
        properties: {

            /**
             * The `tagName` of the element to inject into the tab's page.
             *
             * @attribute content
             * @type string
             */
            content: {
                observer: '__contentChanged',
                reflectToAttribute: true,
                type: String
            },

            /**
             * The tab's data.
             *
             * @attribute data
             * @type *
             * @notifies
             */
            data: {
                notify: true
            },

            /**
             * The tab's label.
             *
             * @attribute label
             * @type string
             */
            label: {
                reflectToAttribute: true,
                type: String
            },

            /**
             * The memento, used to know when the tab's data changes.
             *
             * @attribute memento
             * @type Object
             */
            memento: {
                type: Object
            },

            /**
             * If set to true, the tab's data ant its memento are not equivalent.
             *
             * @attribute modified
             * @type boolean
             * @default false
             * @notifies
             * @readonly
             */
            modified: {
                notify: true,
                readOnly: true,
                reflectToAttribute: true,
                type: Boolean,
                value: false
            },

            /**
             * The tab's targeted page.
             *
             * @attribute page
             * @type Element
             */
            page: {
                observer: '__pageChanged'
            },

            /**
             * The master selector.
             *
             * @attribute selector
             * @type Element
             * @readonly
             */
            selector: {
                master: '.tabs',
                readOnly: true,
                value: null
            }
        },

        /*********************************************************************/

        // OBSERVER
        __contentChanged() {

            // Let
            let target = this.findTarget();

            // Setting
            if (target) { target.content = this.content; }
        },

        // OBSERVER
        __pageChanged(post, pre) {

            // Linking
            if (pre) { this.unlinkProperties('data', 'data', pre); }
            if (post) { this.linkProperties('data', 'data', post); }
        },

        /*********************************************************************/

        // HANDLER
        __handleCompare() {

            // Ensuring
            this.ensure('modified', !XP.isVoid(this.memento) && !XP.isEquivalent(this.data, this.memento));
        }
    };

    /**
     * @polymerBehavior Polymer.XPTabBehavior
     */
    Polymer.XPTabBehavior = [
        Polymer.XPMasterSlaveBehavior,
        Polymer.XPTabBehaviorImp
    ];
</script>


text:
.class public Lcom/android/internal/midi/MidiEventScheduler$MidiEvent;
.super Lcom/android/internal/midi/EventScheduler$SchedulableEvent;
.source "MidiEventScheduler.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/internal/midi/MidiEventScheduler;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x9
    name = "MidiEvent"
.end annotation

# instance fields
.field public count:I

.field public data:[B

# direct methods
.method private constructor <init>(I)V
    .locals 2
    .param p1, "count"    # I

    .prologue
    .line 58
    const-wide/16 v0, 0x0

    invoke-direct {p0, v0, v1}, Lcom/android/internal/midi/EventScheduler$SchedulableEvent;-><init>(J)V

    .line 54
    const/4 v0, 0x0

    iput v0, p0, Lcom/android/internal/midi/MidiEventScheduler$MidiEvent;->count:I

    .line 59
    new-array v0, p1, [B

    iput-object v0, p0, Lcom/android/internal/midi/MidiEventScheduler$MidiEvent;->data:[B

    .line 57
    return-void
.end method

.method synthetic constructor <init>(ILcom/android/internal/midi/MidiEventScheduler$MidiEvent;)V
    .locals 0
    .param p1, "count"    # I

    .prologue
    invoke-direct {p0, p1}, Lcom/android/internal/midi/MidiEventScheduler$MidiEvent;-><init>(I)V

    return-void
.end method

.method private constructor <init>([BIIJ)V
    .locals 2
    .param p1, "msg"    # [B
    .param p2, "offset"    # I
    .param p3, "count"    # I
    .param p4, "timestamp"    # J

    .prologue
    const/4 v1, 0x0

    .line 63
    invoke-direct {p0, p4, p5}, Lcom/android/internal/midi/EventScheduler$SchedulableEvent;-><init>(J)V

    .line 54
    iput v1, p0, Lcom/android/internal/midi/MidiEventScheduler$MidiEvent;->count:I

    .line 64
    new-array v0, p3, [B

    iput-object v0, p0, Lcom/android/internal/midi/MidiEventScheduler$MidiEvent;->data:[B

    .line 65
    iget-object v0, p0, Lcom/android/internal/midi/MidiEventScheduler$MidiEvent;->data:[B

    invoke-static {p1, p2, v0, v1, p3}, Ljava/lang/System;->arraycopy([BI[BII)V

    .line 66
    iput p3, p0, Lcom/android/internal/midi/MidiEventScheduler$MidiEvent;->count:I

    .line 62
    return-void
.end method

.method synthetic constructor <init>([BIIJLcom/android/internal/midi/MidiEventScheduler$MidiEvent;)V
    .locals 0
    .param p1, "msg"    # [B
    .param p2, "offset"    # I
    .param p3, "count"    # I
    .param p4, "timestamp"    # J

    .prologue
    invoke-direct/range {p0 .. p5}, Lcom/android/internal/midi/MidiEventScheduler$MidiEvent;-><init>([BIIJ)V

    return-void
.end method

# virtual methods
.method public toString()Ljava/lang/String;
    .locals 4

    .prologue
    .line 71
    const-string/jumbo v1, "Event: "

    .line 72
    .local v1, "text":Ljava/lang/String;
    const/4 v0, 0x0

    .local v0, "i":I
    :goto_0
    iget v2, p0, Lcom/android/internal/midi/MidiEventScheduler$MidiEvent;->count:I

    if-ge v0, v2, :cond_0

    .line 73
    new-instance v2, Ljava/lang/StringBuilder;

    invoke-direct {v2}, Ljava/lang/StringBuilder;-><init>()V

    invoke-virtual {v2, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v2

    iget-object v3, p0, Lcom/android/internal/midi/MidiEventScheduler$MidiEvent;->data:[B

    aget-byte v3, v3, v0

    invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v2

    const-string/jumbo v3, ", "

    invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v2

    invoke-virtual {v2}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    .line 72
    add-int/lit8 v0, v0, 0x1

    goto :goto_0

    .line 75
    :cond_0
    return-object v1
.end method


text:
package com.gtm.cpims.log.service;

import java.util.List;

import net.sweet.dao.generic.support.Page;

import com.gtm.cpims.model.BsLog;

/**
 * 日志业务处理类
 *
 * @author Sweet
 *
 */
@SuppressWarnings("unchecked")
public interface LogService {
    public Page findLog4jList(String loginUser, String message, String begin, String end,
            String priority, int pageNo, int pageSize);

    public BsLog Loginfo(String id);

    public int countLog4j(String message, String begin, String end, String priority);

    public List getAllLogs();

    public List getAboveGoodLogs();
}


text:
<?php
/**
 * 用于多个域名之间的切换逻辑
 * Created by PhpStorm.
 * User: zhangdali
 * Date: 2016/12/5
 * Time: 下午4:29
 */

namespace Sdclub\MiPush\XmPush;

class ServerSwitch {
    /**
     * 存储message的server
     * @var array Server
     */
    private $servers;
    private $feedback;
    private $sandbox;
    private $specified;
    private $emq;
    private $defaultServer;
    private $inited = false;
    private $lastRefreshTime;
    static $REFRESH_SERVER_HOST_INTERVAL = 300000; // 5 * 60 * 1000

    /**
     * @var ServerSwitch reference to singleton instance
     */
    private static $instance;

    /**
     * 通过延迟加载(用到时才加载)获取实例
     *
     * @return self
     */
    public static function getInstance() {
        if (!isset(self::$instance)) {
            $class = __CLASS__;
            self::$instance = new $class;
        }

        return self::$instance;
    }

    /**
     * 是否需要刷新host列表
     * @return bool
     */
    public function needRefreshHostList() {
        return !$this->inited ||
            $this->currentTimeMillis() - $this->lastRefreshTime >= self::$REFRESH_SERVER_HOST_INTERVAL;
    }

    /**
     * @param String $serverListStr : host:min:max:step,host:min:max:step,...
     */
    public function initialize($serverListStr) {
        if (!$this->needRefreshHostList()) {
            return;
        }
        $serverStrArr = explode(',', $serverListStr);
        $servers = array();
        $i = 0;
        foreach ($serverStrArr as $serverStr) {
            $sp = explode(":", $serverStr);
            if (count($sp) < 5) {
                $servers[$i] = $this->defaultServer;
                continue;
            }
            $servers[$i] = new Server($sp[0], intval($sp[1]), intval($sp[2]), intval($sp[3]), intval($sp[4]));
            if (!empty($this->servers)) {
                foreach ($this->servers as $server) {
                    if (strcmp($server->getHost(), $servers[$i]->getHost())) {
                        $servers[$i]->setPriority($server->getPriority());
                    }
                }
            }
            $i++;
        }
        $this->inited = true;
        $this->lastRefreshTime = $this->currentTimeMillis();
        $this->servers = $servers;
    }

    /**
     * @param PushRequestPath $requestPath
     */
    /**
     * @param PushRequestPath $requestPath
     * @return Server
     */
    public function &selectServer($requestPath) {
        if (isset(Constants::$host)) {
            $this->specified->setHost(Constants::$host);
            return $this->specified;
        }
        if (Constants::$sandbox) {
            return $this->sandbox;
        }

        switch ($requestPath->getRequestType()) {
            case PushRequestType::FEEDBACK:
                return $this->feedback;
            case PushRequestType::EMQ:
                return $this->emq;
            default:
                return $this->selectMsgServer();
        }

    }

    /**
     * @return mixed|Server
     */
    private function &selectMsgServer() {
        if (!Constants::$autoSwitchHost || !$this->inited) {
            return $this->defaultServer;
        }
        $allPriority = 0;
        $priorities = array();
        foreach ($this->servers as $server) {
            $priorities[] = $server->getPriority();
            $allPriority += $server->getPriority();
        }
        $randomPoint = mt_rand(0, $allPriority);
        $sum = 0;
        for ($i = 0; $i < count($priorities); $i++) {
            $sum += $priorities[$i];
            if ($randomPoint <= $sum) {
                return $this->servers[$i];
            }
        }
        return $this->defaultServer;
    }

    /**
     * 构造函数私有,不允许在外部实例化
     */
    private function __construct() {
        $this->feedback = new Server(Constants::HOST_PRODUCTION_FEEDBACK, 100, 100, 0, 0);
        $this->sandbox = new Server(Constants::HOST_SANDBOX, 100, 100, 0, 0);
        $this->specified = new Server(Constants::$host, 100, 100, 0, 0);
        $this->emq = new Server(Constants::HOST_EMQ, 100, 100, 0, 0);
        $this->defaultServer = new Server(Constants::HOST_PRODUCTION, 1, 90, 10, 5);
        $this->lastRefreshTime = $this->currentTimeMillis();
    }

    /**
     * 防止对象实例被克隆
     *
     * @return void
     */
    private function __clone() {
    }

    /**
     * 防止被反序列化
     *
     * @return void
     */
    private function __wakeup() {
    }

    /**
     * 获取当前时间(毫秒)
     * @return int
     */
    private function currentTimeMillis() {
        return ceil(microtime(true) * 1000);
    }
}


text:
"""
This example illustrates how the computation can notify of advancing progress:
it simply uses the :meth:`notify_progress` method. This method expects a real
number between 0 and 1, 1 meaning 100% completion.

Monitoring progress is best done with the Clustertools utility `clustertools`.
Prepare two terminals. In the first one, run this experiment with
`python 008_monitoring_progress.py front-end`. In the second one do
`clustertools count BasicUsageMonitoring` several times. You should see the
progress evolves.

Instead of using the `clustertools` utility, you enter a python console and
use the :cls:`Monitor` class to track your computations.
"""

from clustertools import Computation, CTParser, ParameterSet, \
    Experiment, set_stdout_logging

class MyComputation(Computation):
    """
    Inherit from `Computation` and redefine the `run` method as you which.

    This computation will perform 100 steps of the bisection method to find a
    root for x^3 - x - 2 on [a, b]
    """

    def run(self, result, a, b, **parameters):
        import time

        # The polynome for which we are trying to find the roots
        def P(x):
            return x**3 - x - 2

        # Bisection algorithm
        m = 0
        for i in range(100):
            m = (a+b)/2.
            if P(a)*P(m) < 0:
                b = m
            else:
                a = m

            # Notify the progression of the task. `notify_progress` takes as
            # input a float between 0 and 1
            self.notify_progress((i+1)/100.)

            # Wait some time to be able to see the update with
            # `clustertools count`
            time.sleep(1)

        result["root"] = m

if __name__ == "__main__":
    set_stdout_logging()

    parser = CTParser()

    environment, _ = parser.parse()

    param_set = ParameterSet()
    param_set.add_parameters(a=1, b=2)

    experiment = Experiment("BasicUsageMonitoring", param_set, MyComputation)
    environment.run(experiment)


text:
import * as asn1js from "asn1js";
import { getParametersValue, clearProps } from "pvutils";
import RecipientEncryptedKey from "./RecipientEncryptedKey.js";
//**************************************************************************************
/**
 * Class from RFC5652
 */
export default class RecipientEncryptedKeys
{
	//**********************************************************************************
	/**
	 * Constructor for RecipientEncryptedKeys class
	 * @param {Object} [parameters={}]
	 * @param {Object} [parameters.schema] asn1js parsed value to initialize the class from
	 */
	constructor(parameters = {})
	{
		//region Internal properties of the object
		/**
		 * @type {Array.<RecipientEncryptedKey>}
		 * @desc encryptedKeys
		 */
		this.encryptedKeys = getParametersValue(parameters, "encryptedKeys", RecipientEncryptedKeys.defaultValues("encryptedKeys"));
		//endregion

		//region If input argument array contains "schema" for this object
		if("schema" in parameters)
			this.fromSchema(parameters.schema);
		//endregion
	}
	//**********************************************************************************
	/**
	 * Return default values for all class members
	 * @param {string} memberName String name for a class member
	 */
	static defaultValues(memberName)
	{
		switch(memberName)
		{
			case "encryptedKeys":
				return [];
			default:
				throw new Error(`Invalid member name for RecipientEncryptedKeys class: ${memberName}`);
		}
	}
	//**********************************************************************************
	/**
	 * Compare values with default values for all class members
	 * @param {string} memberName String name for a class member
	 * @param {*} memberValue Value to compare with default value
	 */
	static compareWithDefault(memberName, memberValue)
	{
		switch(memberName)
		{
			case "encryptedKeys":
				return (memberValue.length === 0);
			default:
				throw new Error(`Invalid member name for RecipientEncryptedKeys class: ${memberName}`);
		}
	}
	//**********************************************************************************
	/**
	 * Return value of pre-defined ASN.1 schema for current class
	 *
	 * ASN.1 schema:
	 * ```asn1
	 * RecipientEncryptedKeys ::= SEQUENCE OF RecipientEncryptedKey
	 * ```
	 *
	 * @param {Object} parameters Input parameters for the schema
	 * @returns {Object} asn1js schema object
	 */
	static schema(parameters = {})
	{
		/**
		 * @type {Object}
		 * @property {string} [blockName]
		 * @property {string} [RecipientEncryptedKeys]
		 */
		const names = getParametersValue(parameters, "names", {});

		return (new asn1js.Sequence({
			name: (names.blockName || ""),
			value: [
				new asn1js.Repeated({
					name: (names.RecipientEncryptedKeys || ""),
					value: RecipientEncryptedKey.schema()
				})
			]
		}));
	}
	//**********************************************************************************
	/**
	 * Convert parsed asn1js object into current class
	 * @param {!Object} schema
	 */
	fromSchema(schema)
	{
		//region Clear input data first
		clearProps(schema, [
			"RecipientEncryptedKeys"
		]);
		//endregion

		//region Check the schema is valid
		const asn1 = asn1js.compareSchema(schema,
			schema,
			RecipientEncryptedKeys.schema({
				names: {
					RecipientEncryptedKeys: "RecipientEncryptedKeys"
				}
			})
		);

		if(asn1.verified === false)
			throw new Error("Object's schema was not verified against input data for RecipientEncryptedKeys");
		//endregion

		//region Get internal properties from parsed schema
		this.encryptedKeys = Array.from(asn1.result.RecipientEncryptedKeys, element => new RecipientEncryptedKey({ schema: element }));
		//endregion
	}
	//**********************************************************************************
	/**
	 * Convert current object to asn1js object and set correct values
	 * @returns {Object} asn1js object
	 */
	toSchema()
	{
		//region Construct and return new ASN.1 schema for this object
		return (new asn1js.Sequence({
			value: Array.from(this.encryptedKeys, element => element.toSchema())
		}));
		//endregion
	}
	//**********************************************************************************
	/**
	 * Convertion for the class to JSON object
	 * @returns {Object}
	 */
	toJSON()
	{
		return {
			encryptedKeys: Array.from(this.encryptedKeys, element => element.toJSON())
		};
	}
	//**********************************************************************************
}
//**************************************************************************************


text:
import * as React from 'react';
import { Sizes } from 'react-bootstrap';

declare namespace ModalDialog {
    export interface ModalDialogProps extends React.HTMLProps<ModalDialog> {
        // TODO: these props are not correct https://github.com/react-bootstrap/react-bootstrap/blob/v0.31.1/src/ModalDialog.js#L9
        onHide?: Function | undefined;
        onEnter?: Function | undefined;
        onEntered?: Function | undefined;
        onEntering?: Function | undefined;
        onExit?: Function | undefined;
        onExited?: Function | undefined;
        onExiting?: Function | undefined;
        bsSize?: Sizes | undefined;
        bsClass?: string | undefined;
    }
}
declare class ModalDialog extends React.Component<ModalDialog.ModalDialogProps> { }
export = ModalDialog;


text:
import React, { Component, PropTypes } from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import { Col, Alert } from 'react-bootstrap';
import SigninComp from '../../components/Signin';
import connectComponent from '../../utils/connectComponent';
import history from '../../core/history';

const title = '登陆';

class Signin extends Component {
  static contextTypes = {
    setTitle: PropTypes.func.isRequired,
  };

  constructor() {
    super();
    this.state = {
      signinButNotActive: false
    };
  }

  componentWillMount() {
    this.context.setTitle(title);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.secret && nextProps.secret._id) {
      console.log(nextProps.secret);
      if (nextProps.active) {
        history.push('/');
      } else {
        this.setState({signinButNotActive: true});
      }
    }
  }

  _onSubmit(name, password) {
    const { actions } = this.props;
    this.props.actions.onSignin(name, password);
  }

  render() {
    if (this.state.signinButNotActive) {
      return (
        <Col md={4} mdOffset={4}>
          <Alert bsStyle="warning">
            您好,{this.props.secret.loginname}

            您的账号未激活,请登录你的注册邮箱 {this.props.secret.email} 激活账号。
          </Alert>
        </Col>
      );
    } else {
      return (
        <Col md={4} mdOffset={4}>
          <SigninComp onSubmit={this._onSubmit.bind(this)} />
        </Col>
      );
    }
  }
}

const LayoutComponent = Signin;

function mapStateToProps(state) {
  return {
    active: state.auth.active || false,
    secret: state.auth.secret || {}
  }
}

export default connectComponent({LayoutComponent, mapStateToProps});


text:
<?php
namespace Everyman\Neo4j;

/**
 * Represents a relationship between two nodes
 */
class Relationship extends PropertyContainer
{
	const DirectionAll       = 'all';
	const DirectionIn        = 'in';
	const DirectionOut       = 'out';

	protected $start = null;
	protected $end = null;
	protected $type = null;

	/**
	 * Delete this relationship
	 *
	 * @return PropertyContainer
	 * @throws Exception on failure
	 */
	public function delete()
	{
		$this->client->deleteRelationship($this);
		return $this;
	}

	/**
	 * Get the end node
	 *
	 * @return Node
	 */
	public function getEndNode()
	{
		$this->loadProperties();
		return $this->end;
	}

	/**
	 * Get the start node
	 *
	 * @return Node
	 */
	public function getStartNode()
	{
		$this->loadProperties();
		return $this->start;
	}

	/**
	 * Get the relationship type
	 *
	 * @return string
	 */
	public function getType()
	{
		$this->loadProperties();
		return $this->type;
	}

	/**
	 * Load this relationship
	 *
	 * @return PropertyContainer
	 * @throws Exception on failure
	 */
	public function load()
	{
		$this->client->loadRelationship($this);
		return $this;
	}

	/**
	 * Save this node
	 *
	 * @return PropertyContainer
	 * @throws Exception on failure
	 */
	public function save()
	{
		$this->client->saveRelationship($this);
		return $this;
	}

	/**
	 * Set the end node
	 *
	 * @param Node $end
	 * @return Relationship
	 */
	public function setEndNode(Node $end)
	{
		$this->end = $end;
		return $this;
	}

	/**
	 * Set the start node
	 *
	 * @param Node $start
	 * @return Relationship
	 */
	public function setStartNode(Node $start)
	{
		$this->start = $start;
		return $this;
	}

	/**
	 * Set the type
	 *
	 * @param string $type
	 * @return Relationship
	 */
	public function setType($type)
	{
		$this->type = $type;
		return $this;
	}
}


text:
package edu.mit.simile.babel.tsv;

import java.util.Locale;

import edu.mit.simile.babel.SerializationFormat;

/**
 * @author dfhuynh
 *
 */
public class TSVFormat implements SerializationFormat {
	final static public TSVFormat s_singleton = new TSVFormat();

	protected TSVFormat() {
		// nothing
	}

	/* (non-Javadoc)
	 * @see edu.mit.simile.babel.format.SerializationFormat#getLabel(java.util.Locale)
	 */
	public String getLabel(Locale locale) {
		return "Tab-Separated Values";
	}

	/* (non-Javadoc)
	 * @see edu.mit.simile.babel.format.SerializationFormat#getDescription(java.util.Locale)
	 */
	public String getDescription(Locale locale) {
		return "Tab-Separated Values";
	}

	/* (non-Javadoc)
	 * @see edu.mit.simile.babel.format.SerializationFormat#getMimetype()
	 */
	public String getMimetype() {
		return "text/plain";
	}
}


text:
layout: page
title: Experience
---

{% assign experience_list = site.experiences %}
{% for experience in experience_list%}

              {% for org in experience.organizations %}

              {% endfor %}

              {{ experience.content }}

{% unless forloop.last %}

{% endunless %}
{% endfor %}

Not enough? Look at some of some different projects of mine.


text:
function [um] = cm2um(cm)
% Convert length from centimeters to micrometers or microns.
% Chad A. Greene 2012
um = cm*10000;


text:
Rails.application.routes.draw do

  ActiveAdmin.routes(self)
  devise_for :admin_users, :class_name => 'Kinney::AdminUser'
  mount Kinney::Engine => "/kinney", :as => 'kinney'
  root :to => 'kinney/pages#home'
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.sonatype.oss</groupId>
        <artifactId>oss-parent</artifactId>
        <version>9</version>
    </parent>
    <groupId>org.cthul</groupId>
    <artifactId>cthul</artifactId>
    <packaging>pom</packaging>
    <version>1.2.0-SNAPSHOT</version>
    <name>Cthul POM</name>
    <url>http://cthul.org/</url>
    <description>
        Common Tools, Helpers, and Utils Library
    </description>
    <modules>
        <module>matchers</module>
        <module>monad</module>
        <!--<module>strings</module>
        <module>log</module>
        <module>log-cal10n</module>-->
        <module>objects</module>
        <module>xml</module>
        <!--<module>parser</module>
        <module>parser-lib</module>-->
    </modules>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.dependencies.hamcrest.version>1.3</project.dependencies.hamcrest.version>
        <project.url.docs>${project.url}/docs/mvn/</project.url.docs>
    </properties>
    <licenses>
        <license>
            <name>The MIT License</name>
            <url>http://opensource.org/licenses/MIT</url>
            <distribution>repo</distribution>
        </license>
    </licenses>
    <scm>
        <url>https://github.com/derari/cthul.git</url>
        <connection>scm:git:git://github.com/derari/cthul.git</connection>
    </scm>
    <distributionManagement>
        <site>
            <id>cthul-maven-docs</id>
            <url>${project.url.docs}</url>
        </site>
    </distributionManagement>
    <developers>
        <developer>
            <id>at</id>
            <name>Arian Treffer</name>
            <email>derari@web.de</email>
        </developer>
    </developers>
    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.1</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                        <encoding>${project.build.sourceEncoding}</encoding>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.1.0</version>
                    <configuration>
                        <encoding>${project.build.sourceEncoding}</encoding>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-site-plugin</artifactId>
                    <version>3.9.0</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-source-plugin</artifactId>
                    <version>3.2.1</version>
                    <executions>
                        <execution>
                            <goals>
                                <goal>jar</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-javadoc-plugin</artifactId>
                    <version>3.1.1</version>
                    <executions>
                        <execution>
                            <goals>
                                <goal>jar</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-assembly-plugin</artifactId>
                    <version>3.2.0</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-gpg-plugin</artifactId>
                    <version>1.6</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-jar-plugin</artifactId>
                    <version>3.2.0</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
    <profiles>
        <profile>
            <id>xlint</id>
            <build>
                <pluginManagement>
                    <plugins>
                        <plugin>
                            <groupId>org.apache.maven.plugins</groupId>
                            <artifactId>maven-compiler-plugin</artifactId>
                            <configuration>
                                <compilerArgument>-Xlint</compilerArgument>
                            </configuration>
                        </plugin>
                    </plugins>
                </pluginManagement>
            </build>
        </profile>
        <profile>
            <id>site</id>
            <properties>
                <generateSite>true</generateSite>
            </properties>
            <reporting>
                <excludeDefaults>true</excludeDefaults>
                <outputDirectory>${project.build.directory}/site</outputDirectory>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-project-info-reports-plugin</artifactId>
                        <version>3.0.0</version>
                        <configuration>
                            <dependencyDetailsEnabled>false</dependencyDetailsEnabled>
                            <dependencyLocationsEnabled>false</dependencyLocationsEnabled>
                            <linkOnly>true</linkOnly>
                        </configuration>
                        <reportSets>
                            <reportSet>
                                <inherited>false</inherited>
                                <reports>
                                    <report>index</report>
                                    <report>dependencies</report>
                                    <report>dependency-management</report>
                                    <report>license</report>
                                    <report>modules</report>
                                    <report>scm</report>
                                    <report>summary</report>
                                </reports>
                            </reportSet>
                            <reportSet>
                                <reports>
                                    <report>index</report>
                                    <report>dependencies</report>
                                    <report>license</report>
                                    <report>modules</report>
                                    <report>scm</report>
                                    <report>summary</report>
                                </reports>
                            </reportSet>
                        </reportSets>
                    </plugin>
                    <plugin>
                        <artifactId>maven-javadoc-plugin</artifactId>
                        <version>3.1.1</version>
                    </plugin>
                    <plugin>
                        <artifactId>maven-jxr-plugin</artifactId>
                        <version>3.0.0</version>
                    </plugin>
                    <plugin>
                        <artifactId>maven-surefire-report-plugin</artifactId>
                        <version>3.0.0-M4</version>
                    </plugin>
                </plugins>
            </reporting>
        </profile>
        <profile>
            <id>release-sign-artifacts</id>
            <activation>
                <property>
                    <name>performRelease</name>
                    <value>true</value>
                </property>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-gpg-plugin</artifactId>
                        <executions>
                            <execution>
                                <id>sign-artifacts</id>
                                <phase>verify</phase>
                                <goals>
                                    <goal>sign</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.hamcrest</groupId>
                <artifactId>hamcrest-core</artifactId>
                <version>${project.dependencies.hamcrest.version}</version>
            </dependency>
            <dependency>
                <groupId>org.hamcrest</groupId>
                <artifactId>hamcrest-library</artifactId>
                <version>${project.dependencies.hamcrest.version}</version>
            </dependency>
            <dependency>
                <groupId>org.hamcrest</groupId>
                <artifactId>hamcrest-generator</artifactId>
                <version>${project.dependencies.hamcrest.version}</version>
            </dependency>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.13.1</version>
            </dependency>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.13.1</version>
            </dependency>
            <dependency>
                <groupId>net.sf.twip</groupId>
                <artifactId>twip</artifactId>
                <version>3.3</version>
            </dependency>
            <dependency>
                <groupId>org.mockito</groupId>
                <artifactId>mockito-core</artifactId>
                <version>1.9.0</version>
            </dependency>
            <dependency>
                <groupId>org.codehaus.plexus</groupId>
                <artifactId>plexus-compiler-eclipse</artifactId>
                <version>2.3</version>
            </dependency>
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
                <version>1.7.2</version>
            </dependency>
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-ext</artifactId>
                <version>1.7.26</version>
            </dependency>
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-jdk14</artifactId>
                <version>1.7.2</version>
            </dependency>
            <dependency>
                <groupId>org.cthul</groupId>
                <artifactId>cthul-matchers</artifactId>
                <version>1.1.0</version>
            </dependency>
            <dependency>
                <groupId>org.cthul</groupId>
                <artifactId>cthul-objects</artifactId>
                <version>1.2</version>
            </dependency>
            <dependency>
                <groupId>org.cthul</groupId>
                <artifactId>cthul-strings</artifactId>
                <version>1.0</version>
            </dependency>
            <dependency>
                <groupId>org.cthul</groupId>
                <artifactId>cthul-log</artifactId>
                <version>1.0</version>
            </dependency>
        </dependencies>
    </dependencyManagement>
</project>


text:
#region MIT.
//
// Gorgon.
// Copyright (C) 2012 Michael Winsor
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Created: Tuesday, September 18, 2012 8:00:02 PM
//
#endregion

using System;
using System.Drawing;
using System.Windows.Forms;
using Gorgon.Core;
using Gorgon.Diagnostics;
using Gorgon.Timing;
using Gorgon.UI;

namespace Gorgon.Examples
{
    ///
    /// Entry point class.
    ///
    /// <remarks>
    /// This example is tiny bit more advanced.  It'll show how to use an application context with Gorgon and how to dynamically switch idle loops on the fly.
    ///
    /// It will also demonstrate the use of the Console log.
    /// </remarks>
    internal static class Program
    {
        #region Variables.
        // Random number generator.
        private static readonly Random _rnd = new();
        // Last horizontal coordinate.
        private static int _lastX;
        // Last vertical coordinate.
        private static int _lastY;
        // Last time we drew.
        private static float _lastTime;
        // Color for the bars.
        private static int _color;
        // Color component.
        private static int _component;
        // The debug logging interface.
        private static IGorgonLog _log;
        // The current idle method.
        private static Func<bool> _currentIdle;
        #endregion

        #region Methods.
        ///
        /// Function that's called during idle time.
        ///
        /// <returns>true to continue execution, false to stop.</returns>
        /// <remarks>This is the secondary default idle loop.</remarks>
        public static bool NewIdle()
        {
            if (_currentIdle != NewIdle)
            {
                _currentIdle = NewIdle;
                _log.Print("In new idle loop.", LoggingLevel.All);
            }

            var form = (FormMain)GorgonApplication.ApplicationContext.MainForm;     // Get our main form from the context.

            // Draw some bars every 16 ms.
            if ((GorgonTiming.MillisecondsSinceStart - _lastTime) >= 16.6f)
            {
                Color newColor = Color.Transparent;

                switch (_component)
                {
                    case 0:
                        newColor = Color.FromArgb(_color, 0, 0);
                        break;
                    case 1:
                        newColor = Color.FromArgb(0, _color, 0);
                        break;
                    case 2:
                        newColor = Color.FromArgb(0, 0, _color);
                        break;
                }

                _lastTime = GorgonTiming.MillisecondsSinceStart;

                form.Draw(_lastX, _lastY, _lastX, (form.GraphicsSize.Height - 1) - (_lastY), newColor);

                _color += 3;
                _lastX++;

                if (_color >= 255)
                {
                    _color = 0;
                    _component++;
                    if (_component > 2)
                    {
                        _component = 0;
                    }
                }

                if (_lastX >= form.GraphicsSize.Width)
                {
                    _lastX = 0;
                }

                _lastY = _rnd.Next(0, form.GraphicsSize.Height / 4);
            }

            form.Flip();

            form.DrawFPS("Secondary Idle Loop - FPS: " + GorgonTiming.FPS.ToString("0.0"));

            return true;
        }

        ///
        /// Function that's called during idle time.
        ///
        /// <returns>true to continue execution, false to stop.</returns>
        /// <remarks>This is the default idle loop.</remarks>
        public static bool Idle()
        {
            if (_currentIdle != Idle)
            {
                _currentIdle = Idle;
                _log.Print("In primary idle loop.", LoggingLevel.All);
            }

            var form = (FormMain)GorgonApplication.ApplicationContext.MainForm;     // Get our main form from the context.

            int x = _rnd.Next(0, form.GraphicsSize.Width - 1);
            int y = _rnd.Next(0, form.GraphicsSize.Height - 1);

            // Draw a connected line on the form every 256 milliseconds.
            // This will run continously until the application has ended.
            if ((GorgonTiming.MillisecondsSinceStart - _lastTime) >= 256)
            {
                _lastTime = GorgonTiming.MillisecondsSinceStart;
                form.Draw(_lastX, _lastY, x, y, Color.FromArgb(_rnd.Next(0, 255), _rnd.Next(0, 255), _rnd.Next(0, 255)));
                _lastX = x;
                _lastY = y;
            }
            else
            {
                form.Draw(x, y, x, y, Color.FromArgb(_rnd.Next(0, 255), _rnd.Next(0, 255), _rnd.Next(0, 255)));
            }

            // Flip the buffer.
            form.Flip();

            form.DrawFPS("Primary Idle Loop - FPS: " + GorgonTiming.FPS.ToString("0.0"));

            return true;
        }

        ///
        /// The main entry point for the application.
        ///
        [STAThread]
        private static void Main()
        {
            try
            {
#if NET6_0_OR_GREATER
                Application.SetHighDpiMode(HighDpiMode.PerMonitorV2);
#endif
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                // Get the initial time.
                _lastTime = GorgonTiming.MillisecondsSinceStart;

                // Here we will override the log to use a console log.
                GorgonApplication.Log = _log = new GorgonLogConsole(Application.ProductName, typeof(Program).Assembly.GetName().Version);

                // Run the application context with an idle loop.
                //
                // Here we specify that we want to run an application context and an idle loop.  The idle loop
                // will kick in after the main form displays.
                GorgonApplication.Run(new Context(), Idle);
            }
            catch (Exception ex)
            {
                ex.Catch(_ => GorgonDialogs.ErrorBox(null, _), GorgonApplication.Log);
            }
        }
        #endregion
    }
}


text:
package main

import (
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestVersionString(t *testing.T) {
	GitVersion = ""
	assert.Equal(t, Version, VersionString())

	GitVersion = "some-git-version"
	assert.Equal(t, GitVersion, VersionString())
}


text:
package com.foo.persistence;

public interface StoreMapper {
	String getStorenameByCode(String code);
}


text:
package br.odb.derelict2d;

import android.app.DialogFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.Button;
import br.odb.gamelib.android.AndroidUtils;
import br.odb.gamelib.android.GameView;

public class ShowGameIntroDialogFragment extends DialogFragment implements
		OnClickListener {

	private WebView wvStory;
	private GameView gvIntroComics;
	private Button btNextFinish;
	String [] storyBits;
	String [] buttonTitles = { "Next", "Next", "Dismiss" };
	String [] imagePath = { "intro-comics0", "intro-comics1", "intro-comics2" };
	int currentStoryPoint = 0;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View view = inflater.inflate(R.layout.show_game_intro,
				container, true);

		btNextFinish = (Button) view.findViewById(R.id.btnDismissStory);
		btNextFinish.setOnClickListener(this);

		wvStory = (WebView) view.findViewById(R.id.wvStory);
		gvIntroComics = (GameView) view.findViewById(R.id.gvIntroComics);
		Bundle args = getArguments();

		getDialog().setTitle( "..And so, here we go..." );
		storyBits = args.getString("desc").split( "\n\n\n"  );
		updateDescription( 0 );

		return view;
	}

	private void updateDescription( final int storyPoint ) {

		wvStory.getSettings().setJavaScriptEnabled(false);
		wvStory.loadDataWithBaseURL(null, ""
				+ storyBits[ storyPoint ].replaceAll("\n", "
") + "", "text/html", "utf-8", null);

		if ( imagePath[ storyPoint ] != null ) {

			gvIntroComics.setVisibility( View.VISIBLE );
			AndroidUtils.initImage(gvIntroComics, imagePath[ storyPoint ], ((Derelict2DApplication) getActivity()
					.getApplication()).getAssetManager());
		} else {
			gvIntroComics.setVisibility( View.INVISIBLE );
		}

		((ExploreStationActivity) getActivity()).stopTalking();
		((ExploreStationActivity) getActivity()).say( storyBits[ storyPoint ] );

		btNextFinish.setText( buttonTitles[ storyPoint ] );
	}

	@Override
	public void onClick(View v) {
		((ExploreStationActivity) getActivity()).stopTalking();

		if ( ++currentStoryPoint >= storyBits.length ) {

			dismiss();
		} else {
			updateDescription( currentStoryPoint );
		}
	}
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="../stylesheets/default.css">
    <link rel="stylesheet" type="text/css" href="../stylesheets/blog-stylesheet.css">
    <title>Erin's Home</title>

Erin

Hyejin Kim

A journey from an education major to a software engineer

How do I feel about DBC experience?

After watching the fireside chat

Dec 13, 2014

        After watching the video, I realized that I should be more active and self-motivated than I expected at DBC. Without any experience, I somewhat expected that DBC will work as a traditional school. However, it was more like building something by ourselves. Rather than being a consumer, I need to be more passionate, grab my experience, and take control of my program.

        Going through the first week, I felt everyone was smarter than me and they seemed to go through the curriculum so fast and smooth. I wanted to give up, doubting my ability to survive in this program. However, after chatting with some members of my cohort and watching the video, I found that I was not the only one who felt like this. Though it is somewhat competitive environment, we have each other who is willing to help and work together.

        I decided not to worry about my ignorance and keep in mind that the knowledge difference between me and other people is not that big. I will expose my ignorance, ask helps, and enjoy the process of learning itself. With humble attitude, I will focus on learning new things and overcoming each challenge.


text:
<?xml version="1.0" encoding="utf-8"?>
<selector
	xmlns:android="http://schemas.android.com/apk/res/android">

	<!-- pressed -->
	<item
		android:state_pressed="true">
		<shape
			xmlns:android="http://schemas.android.com/apk/res/android"
			android:shape="rectangle">
			<gradient
				android:startColor="#b4d17a"
				android:centerColor="#9fc455"
				android:endColor="#b4d17a"
				android:angle="270" />
			<stroke
				android:width="2dp"
				android:color="#fff" />
			<corners
				android:radius="2dp" />

		</shape>
	</item>

	<!-- focused -->
	<item
		android:state_focused="true">
		<shape
			xmlns:android="http://schemas.android.com/apk/res/android"
			android:shape="rectangle">
			<gradient
				android:startColor="#b4d17a"
				android:centerColor="#9fc455"
				android:endColor="#b4d17a"
				android:angle="270" />
			<stroke
				android:width="2dp"
				android:color="#fff" />
			<corners
				android:radius="2dp" />

		</shape>
	</item>

	<!-- disabled -->
	<item
		android:state_enabled="false">
		<shape
			xmlns:android="http://schemas.android.com/apk/res/android"
			android:shape="rectangle">
			<gradient
				android:startColor="#b4d17a"
				android:centerColor="#9fc455"
				android:endColor="#b4d17a"
				android:angle="270" />
			<stroke
				android:width="2dp"
				android:color="#fff" />
			<corners
				android:radius="2dp" />

		</shape>
	</item>

	<!-- default -->
	<item>
		<shape
			xmlns:android="http://schemas.android.com/apk/res/android"
			android:shape="rectangle">

			<gradient
				android:startColor="#b4d17a"
				android:centerColor="#9fc455"
				android:endColor="#b4d17a"
				android:angle="270" />
			<stroke
				android:width="2dp"
				android:color="@color/lightBlue" />
			<corners
				android:radius="2dp" />

		</shape>
	</item>

</selector>


text:
package com.slack.api.methods.response.reminders;

import com.slack.api.methods.SlackApiResponse;
import com.slack.api.model.Reminder;
import lombok.Data;

@Data
public class RemindersAddResponse implements SlackApiResponse {

    private boolean ok;
    private String warning;
    private String error;
    private String needed;
    private String provided;

    private Reminder reminder;
}


text:
title: Elliptic Curve Cryptography (ECC)
category: Sécurité, Cryptographie
---

## Pourquoi les courbes elliptiques

* Les algorithmes de cryptographie à clé assymétrique se basent sur des opérations mathématiques faciles à traiter dans un sens mais difficile à résoudre dans l'autre sens. Par exemple, dans le cas de RSA, il est facile de multiplier deux nombres premiers (multiplier est une opération facile) mais il est difficile de retrouver les deux nombres premiers utilisés à partir du produit (factoriser est une opération difficile). Ainsi, on peut facilement calculer une clé publique mais on peut difficilement retrouver la clé privée.

  Les algorithmes ayant cette caractéristiques, facile dans un sens mais difficile dans l'autre, sont connus sous le nom de fonctions *trap door*. Plus l'écart est grand entre la difficulté d'aller dans un sens et celle d'aller dans l'autre sens, plus l'algorithme sera sûr.

* Les algorithmes se basant sur la factorisation (comme RSA) sont d'autant plus efficaces que la taille des nombres utilisés est importante. La taille des clés doit augmenter à mesure que les ressources disponibles pour décrypter les nombres augmentent. Pour pallier à ce problème, il faut trouver une meilleure *trap door*. C'est en 1985, que l'utilisation des courbes elliptiques à été proposé.

## Une courbe elliptique, c'est quoi

L'équation d'une courbe elliptique est comme suit:

```
y² = x³ + ax + b
```

La représentation graphique d'une telle courbe est présentée ci-dessous.
Elle sera plus ou moins alongée selon les paramètres (a, b) utilisés.

![](https://i.imgur.com/jk9Dk7r.png)

Les types de données utilisés doivent avoir certaines caractéristiques:
* l'addition et la multiplication doivent être associatives: `a + (b + c) = (a + b) + c`
* l'addition et la multiplication doivent être commutatives: `a + b = b + a`
* l'addition doit avoir une identité: `a + 0 = a`
* la multiplication doit avoir une identité: `a * 1 = a`
* il doit exister un inverse additif: `a + (-a) = 0`
* il doit exister un inverse multiplicatif: `a * (1/a) = 1`
* la multiplication doit se distribuer sur l'addition: `a * (b + c) = ab + ac`

On peut par exemple utiliser les courbes elliptiques avec des entiers et non des matrices.

En cryptographie, on limite *x*, *y*, *a* et *b* a un champ fini: on ne va donc pas utiliser l'ensemble des entiers (-∞ ; +∞) mais un sous-ensemble (0 ; *p*):

```
y² = x³ + ax + b  mod p
```

---

## Caractéristiques

Une courbe elliptique a des caractéristiques intéressantes:
* la symmétrie horizontale: tout point de la courbe peut être réfléchi sur l'axe des *x* et le résultat sera sur la courbe.
* toute ligne non verticale coupera la courbe en 3 endroits.

En utilisant les points de notre courbe, on peut définir certaines opérations: l'*addition de point* (*point addition* en anglais) et la *multiplication de point* (*point multiplication*).

## Addition de point (⊕)

* Les points sur une courbe sont donnés en fonction de leurs coordonées (x, y). L'addition de points consiste à prendre deux points donnés — (x1, y1) et (x2, y2) — et à les relier entre eux: cette ligne coupera la courbe en un 3ème point (x3, y3), le résultat de l'addition de point est le point réfléchi par l'axe *x* (x3', y3').

  ![](https://i.imgur.com/7F9EAC5.png)

* Pour additionner un point avec lui-même, on prend la tangente du point.

  ![](https://i.imgur.com/p4AoCgn.png)

* Dans le cas où il n'y a pas de 3ème point (ligne verticale), le résultat est l'infini (𝓞).

  P + 𝓞 = 𝓞 + P = P
  P + (−P) = 𝓞

  ![](https://i.imgur.com/bocHEe3.png)

### Exemple

Soit la courbe elliptique `E: y² = x³ + 5x + 7` et les points `P: (2,5)` et `Q: (3,7)`

* On calcule la ligne qui relie P et Q:

  y = ax + b

  # Calcul de a:
  a = (y2 - y1) / (x2 - x1)
    = (7-5) / (3-2)
    = 2

  # Calcul de b — avec P(2,5):
  5 = 2*2 + b
  1 = b

  # Résultat:
  y = 2x + 1

* On résout x

  (2x + 1)²    = x³ + 5x + 7
  4x² + 4x + 1 = x³ + 5x + 7
             0 = x³ -4x² + x + 6
               = (x - 3)(x - 2)(x + 1)

  • x = 3
    y = 2*3 + 1 = 7

  • x = 2
    y = 2*2 + 1 = 5

  • x = -1
    y = -2 + 1 = -1

  La droite coupe la courbe elliptique en 3 points:
  (x,y) = (3,7), (2,5), (-1,-1)

  On connait déjà (3,7) et (2,5), le point d'intersection qu'on cherchait est donc (-1,-1).

* On prend la réflection du point trouvé par l'axe x et on obtient P + Q = (-1,1)

### Formule

Plutôt que de calculer la ligne / les points d'intersection / la réflection du point, on peut utiliser une formule:

* Si P1 = P2,

  * Si *y1 = 0* alors P1 + P2 = 𝓞
  * Si *y1 ≠ 0* alors

    λ = (3x² + a) / 2y

    x3 = λ² - x1 - x2
    y3 = λ * (x1 - x3) - y1

* Si P1 ≠ P2,

  * Si *x1 = x2* alors P1 + P2 = 𝓞
  * Si *x1 ≠ x2* alors

    λ = (y2 - y1) / (x2 - x1)

    x3 = λ² - x1 - x2
    y3 = λ * (x1 - x3) - y1

Soit la courbe elliptique `E: y² = x³ + 5x + 7` et les points `P: (2,5)` et `Q: (3,7)`:

λ = (7-5) / (3-2) = 2

x3 = 2² - 2 - 3 = -1
y3 = 2 * (2 - (-1)) - 5 = 1

P + Q = (-1, 1)

## Multiplication de point

* La multiplication de point consiste à prendre un point et à répéter les opérations d'addition:

      0g = 𝓞
      1g = g
      2g = g ⊕ g
      3g = g ⊕ g ⊕ g (ou 2g ⊕ g)
      ...

* En continuant à additioner le point *g* à lui-même, arrive un moment où *ng* = 𝓞. *n* est ce qu'on appelle l'*ordre* de *g*.

  Il est possible que *g* n'ai pas d'ordre (avec une courbe et un point qui font qu'on finit par visiter tous les points possibles de la courbe) mais ce n'est généralement pas le cas.

* Si on cherche à multiplier *g* par une valeur *m* très grande (mais inférieure à l'ordre de *g*), on peut calculer *mg* en *log m* étapes —  et donc réduire drastiquement le temps de calcul nécessaire — avec la méthode *double-and-add*:

  m = m0 + m1⋅2 + m2⋅2² + ... + mr⋅2r
    où m0 .. mr ∈ {0,1}, r = log2m

  mg = m0⋅g + m1⋅2g + m2⋅2²g + ... + mr⋅2rg

  En JavaScript, on pourrait l'implémenter comme ça:

  ``` js
  function point_multiply(P, d){
     if(d == 0) {
        return 0;

     } else if(d == 1) {
         return P;

     } else if(d % 2 == 1) {
        return point_add(P, point_multiply(P, d - 1));

     } else {
        return point_multiply(point_double(P), d/2);
      }
  }
  point_multiply(P, 100);
  ```

  Cela prend approximativement *log2(m)* doubles et *1/2log2(m)* additions pour calculer *mg*. On peut donc calculer la multiplication très rapidement, beaucoup plus rapidement que si on cherchait à additionner *g* *m* fois.

  ![](https://i.imgur.com/RfsqnaA.png)

  Exemple:

  ```
  100P = 2(2[P + 2(2[2(P + 2P)])])
  ```

  = 6 opérations 2P + 2 opérations P+Q

## Intérêt pour la cryptographie

* Il est facile de multiplier le point, mais si quelqu'un voit la position du point obtenu, même en connaissant la position du point d'origine, il ne peut pas deviner de combien il a été multiplié.

  * Il peut essayer d'additionner *g* encore et encore jusqu'à tomber sur la valeur *mg* obtenue (approche brute force). Si *m* est un grand nombre, cette approche sera extrêmement lente.

  * Il peut essayer d'inverser la multiplication, c'est à dire trouver un entier *x* tel que *XB = P*, soit *x = logBP*. Il s'agit d'un problème de logarithme discret, lequel est considéré comme infaisable — aucun algorithme en logn n'est connu pour le problème du logarithme discret de la courbe elliptique.

* En bref, la multiplication de point est une excellente *trap door*.
  À l'heure actuelle, les seuls algorithmes ECC qu'OpenSSL supporte sont ECDH (Elliptic Curve Diffie Hellman) pour la négociation des clés et ECDSA (Elliptic Curve Digital Signature Algorithm) pour la signature/vérification.

  Dans les algorithmes ECDH et ECDSA, le point *mg* serait la clé publique et *m* serait la clé privée. La clé privée et la clé publique ne sont pas interchangeables (contrairement à RSA): la clé privée est un entier tandis que la clé publique est un point sur la courbe.

---

## Elliptic Curve Diffie Hellman (ECDH)

Diffie Hellman permet de négocier une clé partagée.
Diffie Hellman utilise en général [des clés RSA](https://a-mt.github.io/dev-roadmap/ssl.html#n%C3%A9gociation-de-la-cl%C3%A9-partag%C3%A9e) en se basant sur le fait que pour les clés RSA `Message = Clé_privée(Clé_publique(Message))`. ECDH se base sur une courbe elliptique comme suit:

1. Alice et Bob se mettent d'accord sur une courbe elliptique *E mod p*, où *p* est un nombre premier.

2. Ils se mettent d'accord, publiquement, sur un point G sur la courbe.

3. Alice génère un nombre aléatoire *a*, calcule *aG*, et envoie le résultat à Bob.
   Un tiers connaissant *G* n'est pas capable de déduire *a* puisqu'il s'agit d'une multiplication de point sur une courbe elliptique.

4. Bob génère un nombre aléatoire *b*, calcule *bG*, et envoie le résultat à Bob.
   Un tiers ne peut pas déduire *b*, pas plus qu'il ne peut déduire *a*.

5. Alice calcule *a * bG* et Bob calcule *b * aG*.
   Ils ont désormais un secret partagé, qui sera utilisé pour crypter/décrypter les futures communications.

## Elliptic Curve Digital Signature Algorithm (ECDSA)

On suppose ici que les paramètres de ECDSA sont connus par tous: la courbe utilisée (E mod p), le point générateur (G) et l'ordre de ce dernier (n). Bitcoin utilise la courbe `secp256k1` (Standards for Efficient Cryptography, *p* sur 256bits) — qui a environ 2256 (1077) clés possibles:

   | Paramètre      | Valeur
   |---             |---
   | Équation (E)   | y2 = x3 + 7
   | Max (p)        | 2256 - 232 - 977
   | Générateur (G) | (79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798, 483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8)
   | Ordre (n)      | FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141

### Signer

Bob dispose de la paire de clé *priv* (*m*) et *Pub* (*mG*) et veut signer un message pour prouver que lui seul peut avoir émis ce message — qu'il possède bien la clé privée.

1. Il calcule le *digest* du message. Par exemple en utilisant l'algorithme SHA-1:

   ```
   digest = sha1(message)
   ```

2. Il choisit aléatoirement un nombre *k*, inférieur à l'ordre de G, et multiplie G avec ce nombre.

   ```
   R = (x, y) = k G
   ```

   Notons qu'il s'agit du même processus que la génération de clé privée/publique. Raison pour laquelle les valeurs (k, R) sont appelées dans certains documents des clés éphèmères ou temporaires.

3. Il récupère la coordonnée x du point trouvé, modulo n — pour s'assurer que la valeur est toujours inférieure à l'ordre de G.

   ```
   r = x mod n
   ```

   Si r vaut 0, un nouveau nombre aléatoire (*k*) doit être choisit.

4. Il calcule *s* comme suit:

   s = ((digest + r ⋅ priv) / k) mod n

   Si s vaut 0, un nouveau nombre aléatoire (*k*) doit être choisit.

5. Sinon, alors il signe avec la paire *(r, s)*.
   *(r, -s mod n)* est également une signature valide.

   ```
   signature = (r, s)
   ```

### Vérifier la signature

Alice a reçu le message de Bob, sa signature *(r, s)*, et elle connaît sa clé publique *Pub*. Elle veut vérifier que l'émetteur du message possède bien la clé privée *priv*.

1. Elle vérifie que les valeurs *r* et *s* sont plausibles, elles sont inférieures à l'ordre de G.

   ```
   0 < r < n
   0 < s < n
   ```

2. Elle génère le *digest* du message

   ```
   digest = sha1(message)
   ```

3. Elle calcule R:

   w  = 1/s mod n
   u1 = (digest ⋅ w) mod n
   u2 = (r ⋅ w) mod n

   R  = (x, y) = u1 G + u2 Pub

6. Elle vérifie que le *r* de la signature vaut bien la coordonnée *x* qu'elle a trouvé:

   ```
   r == x mod n
   ```

Démonstration:

R = (u1 G) + (u2 Pub)
  = (digest s-1 G) + (r s-1 Pub)
  = (digest s-1 G) + (r s-1 priv G)
  = (digest + r priv) s-1 G
  = (digest + r priv) ((digest + r priv)/k)-1 G
  = (digest + r priv) (digest + r priv)-1 (1/k)-1 G
  = k G

Seule une personne possédant la clé privée associée à la clé publique aurait pu générer le couple *(r, s)*.

### Récupérer la clé publique à partir de la signature

Il est possible de récupérer la clé publique à partir de la signature:

1. Calculer un point *R = (x, y)* où *x* vaut *r* (ou *r + n*, *r + 2n*, etc) et *y* une valeur telle que *(x, y)* est sur la courbe.

   ```
   R = (r, y)
   ```

2. Générer le *digest* du message

   ```
   digest = sha1(message)
   ```

3. Calculer la clé publique:

   u1 = (-digest / r) mod n
   u2 = (s / r) mod n

   Pub = u1 G + u2 R

### Générateur de nombres aléatoires

* Il est important de ne pas divulguer la valeur de *k* utilisée lors de la signature ECDSA, et d'utiliser différents *k* pour différentes signatures, sinon la valeur de la clé privée peut être calculée.

  Si on a deux signatures employant le même *k* — *(r, s)* et *(r, s2)* — alors on peut calculer la clé privée comme suit:

  ``` python
  # Calculer les digests
  digest  = sha1(message)
  digest2 = sha1(message2)

  # Calculer la valeur de k
  # s - s2 = (digest - digest2) / k
  k = (digest - digest2) / (s - s2)

  # Calculer la valeur de la clé privée
  # s = (digest + r priv) / k
  priv   = (sk - digest) / r
  ```

* En décembre 2010, cette faille de sécurité a été exploité pour extraire la clé privée ECDSA utilisée par la console de jeu PlayStation 3 pour signer les logiciels. Cette attaque n'était possible que parce que la valeur de *k* utilisée par Sony était statique et non aléatoire.

* La signature ECDSA peut faire fuiter des clés privées lorsque *k* est généré par un générateur de nombres aléatoires défectueux. C'est ce qui s'est passé en août 2013, certaines implémentations de la classe java SecureRandom (utilisée par les applications Android, notamment Android Bitcoin Wallet) ont permis le même exploit que la PS3.

  Il est possible d'éviter ce problème en générant *k* de manière déterministe, comme décrit dans le [RFC 6979](https://tools.ietf.org/html/rfc6979).

---

## Sources

* [cloudflare](https://blog.cloudflare.com/a-relatively-easy-to-understand-primer-on-elliptic-curve-cryptography/)
* [openssl](https://wiki.openssl.org/index.php/Elliptic_Curve_Cryptography)
* [wikipedia EC Point Multiplication](https://en.wikipedia.org/wiki/Elliptic_curve_point_multiplication)
* [wikipedia ECDSA](https://en.wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm)
* [johannes-bauer.com](https://www.johannes-bauer.com/compsci/ecc/)
* [paxos.com](https://eng.paxos.com/blockchain-101-elliptic-curve-cryptography)
* [wizardforcel.gitbooks.io](https://wizardforcel.gitbooks.io/practical-cryptography-for-developers-book/digital-signatures/ecdsa-sign-verify-messages.html)

Pour aller plus loin:
[Weak Curves in ECC](http://web.archive.org/web/20120713221339/http://modular.math.washington.edu/edu/2010/414/projects/novotney.pdf)
[Review of Cryptanalysis of ECC](https://vdocuments.mx/reader/full/review-of-cryptanalysis-of-elliptic-curve-review-of-cryptanalysis-of-elliptic)
[Dual_EC_DRBG](https://en.wikipedia.org/wiki/Dual_EC_DRBG)


text:
.class public interface abstract Landroid/view/ViewDebug$HierarchyHandler;
.super Ljava/lang/Object;
.source "ViewDebug.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/view/ViewDebug;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x609
    name = "HierarchyHandler"
.end annotation

# virtual methods
.method public abstract dumpViewHierarchyWithProperties(Ljava/io/BufferedWriter;I)V
.end method

.method public abstract findHierarchyView(Ljava/lang/String;I)Landroid/view/View;
.end method


text:
package org.spongepowered.common.mixin.api.minecraft.world.level.levelgen;

import net.minecraft.world.level.levelgen.NoiseSamplingSettings;
import net.minecraft.world.level.levelgen.NoiseSettings;
import org.spongepowered.api.world.generation.config.noise.NoiseConfig;
import org.spongepowered.api.world.generation.config.noise.SamplingConfig;
import org.spongepowered.api.world.generation.config.noise.SlideConfig;
import org.spongepowered.asm.mixin.Implements;
import org.spongepowered.asm.mixin.Interface;
import org.spongepowered.asm.mixin.Interface.Remap;
import org.spongepowered.asm.mixin.Intrinsic;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;

@Mixin(NoiseSettings.class)
@Implements(@Interface(iface = NoiseConfig.class, prefix = "noiseConfig$", remap = Remap.NONE))
public abstract class NoiseSettingsMixin_API implements NoiseConfig {

    // @formatter:off
    @Shadow public abstract int shadow$height();
    @Shadow public abstract NoiseSamplingSettings shadow$noiseSamplingSettings();
    @Shadow public abstract net.minecraft.world.level.levelgen.NoiseSlideSettings shadow$topSlideSettings();
    @Shadow public abstract net.minecraft.world.level.levelgen.NoiseSlideSettings shadow$bottomSlideSettings();
    @Shadow public abstract int shadow$noiseSizeHorizontal();
    @Shadow public abstract int shadow$noiseSizeVertical();
    @Shadow public abstract double shadow$densityFactor();
    @Shadow public abstract double shadow$densityOffset();
    @Shadow @Deprecated public abstract boolean shadow$useSimplexSurfaceNoise();
    @Shadow @Deprecated public abstract boolean shadow$randomDensityOffset();
    @Shadow @Deprecated public abstract boolean shadow$isAmplified();
    // @formatter:on

    @Intrinsic
    public int noiseConfig$height() {
        return this.shadow$height();
    }

    @Override
    public SamplingConfig samplingConfig() {
        return (SamplingConfig) this.shadow$noiseSamplingSettings();
    }

    @Override
    public SlideConfig topConfig() {
        return (SlideConfig) this.shadow$topSlideSettings();
    }

    @Override
    public SlideConfig bottomConfig() {
        return (SlideConfig) this.shadow$bottomSlideSettings();
    }

    @Override
    public int horizontalSize() {
        return this.shadow$noiseSizeHorizontal();
    }

    @Override
    public int verticalSize() {
        return this.shadow$noiseSizeVertical();
    }

    @Intrinsic
    public double noiseConfig$densityFactor() {
        return this.shadow$densityFactor();
    }

    @Intrinsic
    public double noiseConfig$densityOffset() {
        return this.shadow$densityOffset();
    }

    @Override
    public boolean simplexForSurface() {
        return this.shadow$useSimplexSurfaceNoise();
    }

    @Override
    public boolean randomizeDensityOffset() {
        return this.shadow$randomDensityOffset();
    }

    @Override
    public boolean amplified() {
        return this.shadow$isAmplified();
    }
}


text:
' MODE 0x13: http://www.brackeen.com/vga/basics.html

Public Class RenderCtrl
    Public Sub New()
        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        Me.SetStyle(ControlStyles.AllPaintingInWmPaint, True)
        Me.SetStyle(ControlStyles.OptimizedDoubleBuffer, True)
        Me.SetStyle(ControlStyles.ResizeRedraw, True)
        Me.SetStyle(ControlStyles.Selectable, True)
        Me.SetStyle(ControlStyles.UserPaint, True)

        ' This is used to force the arrows keys to generate a KeyDown event
        ' It also allows us to capture the Alt key
        AddHandler PreviewKeyDown, Sub(sender As Object, e As PreviewKeyDownEventArgs) e.IsInputKey = True
    End Sub

    Protected Overrides Sub OnPaintBackground(e As System.Windows.Forms.PaintEventArgs)
        'MyBase.OnPaintBackground(e)
    End Sub

    ' This method also works
    'Protected Overrides Function ProcessCmdKey(ByRef msg As Message, keyData As Keys) As Boolean
    '    Select Case keyData
    '        Case Keys.Up, Keys.Down, Keys.Left, Keys.Right
    '            OnKeyDown(New KeyEventArgs(keyData))
    '    End Select
    '    Return MyBase.ProcessCmdKey(msg, keyData)
    'End Function
End Class


text:
FILES = \
	../../utils/hdl/utils_pkg.vhd \
	../../utils/hdl/edge_detect.vhd \
	../../spislave/hdl/bus_pkg.vhd \
	../../peripheral_register/hdl/reg_file_pkg.vhd

# Testbench-specific files
ifeq ($(TESTBENCH), peripheral_register_tb)
FILES += \
	../hdl/peripheral_register.vhd
else ifeq ($(TESTBENCH), reg_file_tb)
FILES += \
	../hdl/reg_file.vhd
else ifeq ($(TESTBENCH), reg_file_bram_tb)
FILES += \
	../../ram/hdl/xilinx_block_ram_pkg.vhd\
	../../ram/hdl/xilinx_block_ram.vhd\
	../hdl/reg_file_bram.vhd
else ifeq ($(TESTBENCH), reg_file_bram_double_buffered_tb)
FILES += \
	../../ram/hdl/xilinx_block_ram_pkg.vhd \
	../../ram/hdl/xilinx_block_ram.vhd \
	../hdl/double_buffering.vhd \
	../hdl/reg_file_bram_double_buffered.vhd
else ifeq ($(TESTBENCH), double_buffering_tb)
FILES += \
	../hdl/double_buffering.vhd
endif

# Default settings for gtkwave (visable signal etc.)
#  use gtkwave > File > Write Save File (Strg + S) to generate the file
WAVEFORM_SETTINGS = $(TESTBENCH).sav

# Simulation break condition
#GHDL_SIM_OPT = --assert-level=error
GHDL_SIM_OPT = --stop-time=200us --disp-tree=inst

# Load default options for GHDL.
# Defines make [all|compile|run|view|clean]
include ../../makefile.ghdl.mk