<commit_before>/*

    Confirm that we can consistently choose to persist or reset data between runs.

 */
/* eslint-env node */
"use strict";
var fluid  = require("infusion");
var gpii   = fluid.registerNamespace("gpii");

require("../../../");
gpii.pouch.loadTestingSupport();

fluid.defaults("gpii.tests.pouch.persistent.request", {
    gradeNames: ["gpii.test.pouch.request"],
    path:   "/persistence/new",
    method: "GET"
});

fluid.defaults("gpii.tests.pouch.persistent.request.view", {
    gradeNames: ["gpii.tests.pouch.persistent.request"],
    path: "/persistence/_design/persistence/_view/byId?startKey=%22new%22"
});

fluid.defaults("gpii.tests.pouch.persistent.caseHolder", {
    gradeNames: ["gpii.test.pouch.caseHolder.base"],
    persistenceRecord: { _id: "new", foo: "bar"},
    rawModules: [{
        name: "Testing persistence within a single restart...",
        tests: [
            {
                name: "Confirm that we have no indexed records in the view on startup...",
                type: "test",
                sequence: [
                    {
                        func: "{getViewBeforeInsertRequest}.send",
                        args: []
                    },
                    {
                        event:    "{getViewBeforeInsertRequest}.events.onComplete",
                        listener: "jqUnit.assertLeftHand",
                        args:     ["The status code should be as expected...", { total_rows: 0 }, "@expand:JSON.parse({arguments}.0)"]
                    },
                    {
                        func: "jqUnit.assertEquals",
                        args:     ["The status code should be as expected...", 200, "{getViewBeforeInsertRequest}.nativeResponse.statusCode"]
                    }
                ]
            },
            {
                name: "Set a record and confirm that it's there...",
                type: "test",
                sequence: [
                    {
                        func: "{insertRequest}.send",
                        args: ["{that}.options.persistenceRecord"]
                    },
                    {
                        event:    "{insertRequest}.events.onComplete",
                        listener: "jqUnit.assertEquals",
                        args:     ["The status code should be as expected...", 201, "{insertRequest}.nativeResponse.statusCode"]
                    },
                    {
                        func: "{getAfterInsertRequest}.send",
                        args: []
                    },
                    {
                        event:    "{getAfterInsertRequest}.events.onComplete",
                        listener: "jqUnit.assertLeftHand",
                        args:     ["The record should be readable", "{that}.options.persistenceRecord", "@expand:JSON.parse({arguments}.0)"]
                    }
                ]
            },
            {
                name: "Confirm that we have indexed records after adding one...",
                type: "test",
                sequence: [
                    {
                        func: "{getViewAfterInsertRequest}.send",
                        args: []
                    },
                    {
                        event:    "{getViewAfterInsertRequest}.events.onComplete",
                        listener: "jqUnit.assertLeftHand",
                        args:     ["The status code should be as expected...", { total_rows: 1 }, "@expand:JSON.parse({arguments}.0)"]
                    },
                    {
                        func: "jqUnit.assertEquals",
                        args:     ["The status code should be as expected...", 200, "{getViewAfterInsertRequest}.nativeResponse.statusCode"]
                    }
                ]
            },
            {
                name: "Confirm that the record is still there after a restart...",
                type: "test",
                sequence: [
                    {
                        func: "{getAfterRestartRequest}.send",
                        args:     []
                    },
                    {
                        event:    "{getAfterRestartRequest}.events.onComplete",
                        listener: "jqUnit.assertLeftHand",
                        args:     ["The record should still be found.", "{that}.options.persistenceRecord", "@expand:JSON.parse({arguments}.0)"]
                    }
                ]
            },
            {
                name: "Confirm that we have indexed records after a restart...",
                type: "test",
                sequence: [
                    {
                        func: "{getViewAfterRestartRequest}.send",
                        args: []
                    },
                    {
                        event:    "{getViewAfterRestartRequest}.events.onComplete",
                        listener: "jqUnit.assertLeftHand",
                        args:     ["The status code should be as expected...", { total_rows: 1 }, "@expand:JSON.parse({arguments}.0)"]
                    },
                    {
                        func: "jqUnit.assertEquals",
                        args:     ["The status code should be as expected...", 200, "{getViewAfterRestartRequest}.nativeResponse.statusCode"]
                    }
                ]
            },
            {
                name: "Confirm that the record is no longer there after cleaning up the data and recreating express-pouchdb...",
                type: "test",
                sequence: [
                    {
                        task:        "{harness}.cleanup",
                        resolve:     "{getAfterResetRequest}.send",
                        resolveArgs: []
                    },
                    {
                        event:    "{getAfterResetRequest}.events.onComplete",
                        listener: "jqUnit.assertEquals",
                        args:     ["There should no longer be a record.", 404, "{getAfterResetRequest}.nativeResponse.statusCode"]
                    }
                ]
            },
            {
                name: "Confirm that we have no indexed records after a reset...",
                type: "test",
                sequence: [
                    {
                        func: "{getViewAfterResetRequest}.send",
                        args: []
                    },
                    {
                        event:    "{getViewAfterResetRequest}.events.onComplete",
                        listener: "jqUnit.assertLeftHand",
                        args:     ["The status code should be as expected...", { total_rows: 0 }, "@expand:JSON.parse({arguments}.0)"]
                    },
                    {
                        func: "jqUnit.assertEquals",
                        args:     ["The status code should be as expected...", 200, "{getViewAfterResetRequest}.nativeResponse.statusCode"]
                    }
                ]
            },
            {
                name: "Clean up at the end of the run...",
                type: "test",
                sequence: [
                    {
                        task:        "{harness}.cleanup",
                        resolve:     "jqUnit.assert",
                        resolveArgs: ["The final cleanup should complete as expexted"]
                    }
                ]
            }
        ]
    }],
    components: {
        getViewBeforeInsertRequest: {
            type: "gpii.tests.pouch.persistent.request.view"
        },
        insertRequest: {
            type: "gpii.tests.pouch.persistent.request",
            options: {
                method: "PUT"
            }
        },
        getAfterInsertRequest: {
            type: "gpii.tests.pouch.persistent.request"
        },
        getViewAfterInsertRequest: {
            type: "gpii.tests.pouch.persistent.request.view"
        },
        getAfterRestartRequest: {
            type: "gpii.tests.pouch.persistent.request"
        },
        getViewAfterRestartRequest: {
            type: "gpii.tests.pouch.persistent.request.view"
        },
        getAfterResetRequest: {
            type: "gpii.tests.pouch.persistent.request"
        },
        getViewAfterResetRequest: {
            type: "gpii.tests.pouch.persistent.request.view"
        }
    }
});

fluid.defaults("gpii.tests.pouch.persistent.environment", {
    gradeNames: ["gpii.test.pouch.environment"],
    components: {
        harness: {
            type: "gpii.pouch.harness.persistent"
        },
        caseHolder: {
            type: "gpii.tests.pouch.persistent.caseHolder"
        }
    },
    port:       6798,
    pouchConfig: {
        databases: {
            persistence: { data: ["%gpii-pouchdb/tests/data/persistence"]},
            _replicator: {},
            _users: {},
            pouch__all_dbs__: {}
        }
    },
    // We cannot use the normal logic to determine whether to delete the test directory, as we intentionally persist it
    // between runs.  Manually setting the following option will ensure that when we do eventually call cleanup, it will
    // be aggressive enough.
    distributeOptions: [
        {
            record: true,
            target: "{that gpii.pouch.express.base}.options.members.baseDirBelongsToUs"
        }
    ]
});

fluid.test.runTests("gpii.tests.pouch.persistent.environment");
<commit_msg>GPII-2179: Increased `hangWait` for persistence tests to allow time for directory removal.<commit_after>/*

    Confirm that we can consistently choose to persist or reset data between runs.

 */
/* eslint-env node */
"use strict";
var fluid  = require("infusion");
var gpii   = fluid.registerNamespace("gpii");

require("../../../");
gpii.pouch.loadTestingSupport();

fluid.defaults("gpii.tests.pouch.persistent.request", {
    gradeNames: ["gpii.test.pouch.request"],
    path:   "/persistence/new",
    method: "GET"
});

fluid.defaults("gpii.tests.pouch.persistent.request.view", {
    gradeNames: ["gpii.tests.pouch.persistent.request"],
    path: "/persistence/_design/persistence/_view/byId?startKey=%22new%22"
});

fluid.defaults("gpii.tests.pouch.persistent.caseHolder", {
    gradeNames: ["gpii.test.pouch.caseHolder.base"],
    persistenceRecord: { _id: "new", foo: "bar"},
    rawModules: [{
        name: "Testing persistence within a single restart...",
        tests: [
            {
                name: "Confirm that we have no indexed records in the view on startup...",
                type: "test",
                sequence: [
                    {
                        func: "{getViewBeforeInsertRequest}.send",
                        args: []
                    },
                    {
                        event:    "{getViewBeforeInsertRequest}.events.onComplete",
                        listener: "jqUnit.assertLeftHand",
                        args:     ["The status code should be as expected...", { total_rows: 0 }, "@expand:JSON.parse({arguments}.0)"]
                    },
                    {
                        func: "jqUnit.assertEquals",
                        args:     ["The status code should be as expected...", 200, "{getViewBeforeInsertRequest}.nativeResponse.statusCode"]
                    }
                ]
            },
            {
                name: "Set a record and confirm that it's there...",
                type: "test",
                sequence: [
                    {
                        func: "{insertRequest}.send",
                        args: ["{that}.options.persistenceRecord"]
                    },
                    {
                        event:    "{insertRequest}.events.onComplete",
                        listener: "jqUnit.assertEquals",
                        args:     ["The status code should be as expected...", 201, "{insertRequest}.nativeResponse.statusCode"]
                    },
                    {
                        func: "{getAfterInsertRequest}.send",
                        args: []
                    },
                    {
                        event:    "{getAfterInsertRequest}.events.onComplete",
                        listener: "jqUnit.assertLeftHand",
                        args:     ["The record should be readable", "{that}.options.persistenceRecord", "@expand:JSON.parse({arguments}.0)"]
                    }
                ]
            },
            {
                name: "Confirm that we have indexed records after adding one...",
                type: "test",
                sequence: [
                    {
                        func: "{getViewAfterInsertRequest}.send",
                        args: []
                    },
                    {
                        event:    "{getViewAfterInsertRequest}.events.onComplete",
                        listener: "jqUnit.assertLeftHand",
                        args:     ["The status code should be as expected...", { total_rows: 1 }, "@expand:JSON.parse({arguments}.0)"]
                    },
                    {
                        func: "jqUnit.assertEquals",
                        args:     ["The status code should be as expected...", 200, "{getViewAfterInsertRequest}.nativeResponse.statusCode"]
                    }
                ]
            },
            {
                name: "Confirm that the record is still there after a restart...",
                type: "test",
                sequence: [
                    {
                        func: "{getAfterRestartRequest}.send",
                        args:     []
                    },
                    {
                        event:    "{getAfterRestartRequest}.events.onComplete",
                        listener: "jqUnit.assertLeftHand",
                        args:     ["The record should still be found.", "{that}.options.persistenceRecord", "@expand:JSON.parse({arguments}.0)"]
                    }
                ]
            },
            {
                name: "Confirm that we have indexed records after a restart...",
                type: "test",
                sequence: [
                    {
                        func: "{getViewAfterRestartRequest}.send",
                        args: []
                    },
                    {
                        event:    "{getViewAfterRestartRequest}.events.onComplete",
                        listener: "jqUnit.assertLeftHand",
                        args:     ["The status code should be as expected...", { total_rows: 1 }, "@expand:JSON.parse({arguments}.0)"]
                    },
                    {
                        func: "jqUnit.assertEquals",
                        args:     ["The status code should be as expected...", 200, "{getViewAfterRestartRequest}.nativeResponse.statusCode"]
                    }
                ]
            },
            {
                name: "Confirm that the record is no longer there after cleaning up the data and recreating express-pouchdb...",
                type: "test",
                sequence: [
                    {
                        task:        "{harness}.cleanup",
                        resolve:     "{getAfterResetRequest}.send",
                        resolveArgs: []
                    },
                    {
                        event:    "{getAfterResetRequest}.events.onComplete",
                        listener: "jqUnit.assertEquals",
                        args:     ["There should no longer be a record.", 404, "{getAfterResetRequest}.nativeResponse.statusCode"]
                    }
                ]
            },
            {
                name: "Confirm that we have no indexed records after a reset...",
                type: "test",
                sequence: [
                    {
                        func: "{getViewAfterResetRequest}.send",
                        args: []
                    },
                    {
                        event:    "{getViewAfterResetRequest}.events.onComplete",
                        listener: "jqUnit.assertLeftHand",
                        args:     ["The status code should be as expected...", { total_rows: 0 }, "@expand:JSON.parse({arguments}.0)"]
                    },
                    {
                        func: "jqUnit.assertEquals",
                        args:     ["The status code should be as expected...", 200, "{getViewAfterResetRequest}.nativeResponse.statusCode"]
                    }
                ]
            },
            {
                name: "Clean up at the end of the run...",
                type: "test",
                sequence: [
                    {
                        task:        "{harness}.cleanup",
                        resolve:     "jqUnit.assert",
                        resolveArgs: ["The final cleanup should complete as expexted"]
                    }
                ]
            }
        ]
    }],
    components: {
        getViewBeforeInsertRequest: {
            type: "gpii.tests.pouch.persistent.request.view"
        },
        insertRequest: {
            type: "gpii.tests.pouch.persistent.request",
            options: {
                method: "PUT"
            }
        },
        getAfterInsertRequest: {
            type: "gpii.tests.pouch.persistent.request"
        },
        getViewAfterInsertRequest: {
            type: "gpii.tests.pouch.persistent.request.view"
        },
        getAfterRestartRequest: {
            type: "gpii.tests.pouch.persistent.request"
        },
        getViewAfterRestartRequest: {
            type: "gpii.tests.pouch.persistent.request.view"
        },
        getAfterResetRequest: {
            type: "gpii.tests.pouch.persistent.request"
        },
        getViewAfterResetRequest: {
            type: "gpii.tests.pouch.persistent.request.view"
        }
    }
});

fluid.defaults("gpii.tests.pouch.persistent.environment", {
    gradeNames: ["gpii.test.pouch.environment"],
    components: {
        harness: {
            type: "gpii.pouch.harness.persistent"
        },
        caseHolder: {
            type: "gpii.tests.pouch.persistent.caseHolder"
        }
    },
    port:       6798,
    hangWait:   15000,
    pouchConfig: {
        databases: {
            persistence: { data: ["%gpii-pouchdb/tests/data/persistence"]},
            _replicator: {},
            _users: {},
            pouch__all_dbs__: {}
        }
    },
    // We cannot use the normal logic to determine whether to delete the test directory, as we intentionally persist it
    // between runs.  Manually setting the following option will ensure that when we do eventually call cleanup, it will
    // be aggressive enough.
    distributeOptions: [
        {
            record: true,
            target: "{that gpii.pouch.express.base}.options.members.baseDirBelongsToUs"
        }
    ]
});

fluid.test.runTests("gpii.tests.pouch.persistent.environment");
<|endoftext|>


<commit_before>/**
 **
 ** paste.js
 **
 ** description :
 **  pastebin is a script to paste clipboard's content
 **  in a new pastebin. Its URL is yanked.
 **
 **
 **
 * @author Yoann Lamouroux (spamonsophia@gmail.com) (legreffier@freenode)
 * @version 1.0 now exhaustive.
 *
 **/
var INFO =
<plugin name="paste" version="1.0"
		href="http://www.overthewire.org/"
		summary="Pastebin wrapper"
		xmlns="http://vimperator.org/namespaces/liberator">
	<author email="spamonsophia@gmail.com">Yoann Lamouroux</author>
	<license href="http://www.opensource.org/licenses/mit-license.html">MIT</license>
	<project name="Vimperator" minVersion="2.0" />

		This plugin allow you to fill pastebins with clipboard's content.

	<item>
		<tags>:past :pastebin</tags>
		<spec>:past[ebin] <oa>-name=author</oa> <oa>-language=language</oa> <oa>-private</oa> <oa>-mail=you@lolcat.org</oa> <oa>-subdomain=subdom</oa></spec>
		<description>

Paste the clipboard's content in a new pastebin, yanks its URL.

You can use several options :

-name your_name (or -n) : to give your pastes an author

-language syntax_hilight (or -l) : to enable syntax hilighting

-private (or -p) : to make your pastebin private (sort of)

-mail login@mail.tld (or -m) : add a mail address

-subdomain subdom (or -s) : send the buffer to subdom.pastebin.com

		</description>
	</item>
</plugin>;

function pasteBin(arg) {
	var url = "http://pastebin.com/api_public.php";
	var http = new XMLHttpRequest();
	var params = arg + "paste_code=";
	var paste = util.readFromClipboard();
	if(!paste) {
		liberator.echoerr("The clipboard is empty.\n");
		return;
	} else {
		params += paste;
	}
	http.open("POST", url, true);

	//Send the proper header information along with the request
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http.setRequestHeader("Content-length", params.length);
	http.setRequestHeader("Connection", "close");

	http.send(params);
	http.onreadystatechange = function() {
		if(http.readyState == 4 && http.status == 200) {
			util.copyToClipboard(http.responseText);
			liberator.echo("Yanked " + http.responseText);
		}
	}
}

var expilist = [['N', 'Never'], ['10M', 'Ten minutes'], ['1H', 'One hour'], ['1D', 'One day'], ['1M', 'One month']];

var langlist = [    // looooooongcat, he's rather long.
	['abap', 'ABAP'],
	['actionscript', 'ActionScript'],
	['actionscript3', 'ActionScript3'],
	['ada', 'Ada'],
	['apache', 'Apache'],
	['applescript', 'AppleScript'],
	['apt_sources', 'APT Sources'],
	['asm', 'Assembler'],
	['asp', 'ASP'],
	['autoit', 'AutoIt'],
	['avisynth', 'Avisynth'],
	['bash', 'Bash script'],
	['basic4gl', 'Basic4GL'],
	['bibtex', 'BibTeXgi'],
	['blitzbasic', 'Blitz Basic'],
	['bnf', 'BNF'],
	['boo', 'Boo'],
	['bf', 'BrainFuck'],
	['c', 'C'],
	['c_mac', 'C for Macs'],
	['cill', 'C Intermediate Language'],
	['csharp', 'C#'],
	['cpp', 'C++'],
	['caddcl', 'CAD DCL'],
	['cadlisp', 'CAD Lisp'],
	['cfdg', 'CFDG'],
	['klonec', 'Clone C'],
	['klonecpp', 'Clone C++'],
	['cmake', 'CMake'],
	['cobol', 'Cobol'],
	['cfm', 'ColdFusion'],
	['css', 'CSS'],
	['d', 'D'],
	['dcs', 'DCS'],
	['delphi', 'Delphi'],
	['dff', 'Diff'],
	['div', 'DIV'],
	['dos', 'DOS'],
	['dot', 'DOT'],
	['eiffel', 'Eiffel'],
	['email', 'E-mail'],
	['erlang', 'Erlang'],
	['fo', 'FO Language'],
	['fortran', 'Fortran'],
	['freebasic', 'FreeBasic'],
	['gml', 'Game Maker'],
	['genero', 'Genero'],
	['gettext', 'GetText'],
	['groovy', 'Groovy'],
	['haskell', 'Haskell'],
	['hq9plus', 'HQ9 Plus'],
	['html4strict', 'HTML4 strict'],
	['idl', 'IDL'],
	['ini', 'INI configuration file'],
	['inno', 'Inno script'],
	['intercal', 'INTERCAL'],
	['io', 'IO'],
	['java', 'Java'],
	['java5', 'Java5'],
	['javascript', 'JavaScript'],
	['kixtart', 'KiXtart'],
	['latex', 'Latex'],
	['lsl2', 'Linden Scripting'],
	['lisp', 'Lisp'],
	['locobasic', 'Loco Basic'],
	['lolcode', 'LOL Code'],
	['lotusformulas', 'Lotus Formulas'],
	['lotusscript', 'Lotus Script'],
	['lscript', 'LScript'],
	['lua', 'Lua'],
	['m68k', 'M68000 Assembler'],
	['make', 'Makefile'],
	['matlab', 'MatLab'],
	['matlab', 'MatLab'],
	['mirc', 'mIRC'],
	['modula3', 'Modula 3'],
	['mpasm', 'MPASM'],
	['mxml', 'MXML'],
	['mysql', 'MySQL'],
	['nsis', 'NullSoft Installer'],
	['oberon2', 'Oberon 2'],
	['objc', 'Objective C'],
	['ocaml-brief', 'OCaml Brief'],
	['ocaml', 'OCaml'],
	['glsl', 'OpenGL Shading'],
	['oobas', 'OpenOffice Basic'],
	['oracle11', 'Oracle 11'],
	['oracle8', 'Oracle 8'],
	['pascal', 'Pascal'],
	['pawn', 'PAWN'],
	['per', 'Per'],
	['perl', 'Perl'],
	['php', 'PHP'],
	['php-brief', 'PHP Brief'],
	['pic16', 'Pic 16'],
	['pixelbender', 'Pixel Bender'],
	['plsql', 'PL/SQL'],
	['povray', 'POV-Ray'],
	['powershell', 'PowerShell'],
	['progress', 'Progress'],
	['prolog', 'Prolog'],
	['properties', 'Properties'],
	['providex', 'ProvideX'],
	['python', 'Python'],
	['qbasic', 'Quick Basic'],
	['rails', 'Rails'],
	['rebol', 'REBOL'],
	['reg', 'REG'],
	['robots', 'Robots'],
	['ruby', 'Ruby'],
	['gnuplot', 'Ruby Gnuplot'],
	['sas', 'SAS'],
	['scala', 'Scala'],
	['scheme', 'Scheme'],
	['scilab', 'Scilab'],
	['sdlbasic', 'SDL Basic'],
	['smalltalk', 'SmallTalk'],
	['smarty', 'Smarty'],
	['sql', 'SQL'],
	['tsql', 'T-SQL'],
	['tcl', 'TCL'],
	['tcl', 'tcl'],
	['teraterm', 'Tera Term'],
	['thinbasic', 'thinBasic'],
	['typoscript', 'TypoScript'],
	['unreal', 'unrealScript'],
	['vbnet', 'VB.NET'],
	['verilog', 'VeriLog'],
	['vhdl', 'VHDL'],
	['vim', 'Vim'],
	['visualprolog', 'Visual Pro Log'],
	['vb', 'Visual Basic'],
	['visualfoxpro', 'VisualFoxPro'],
	['whitespace', 'WhiteSpace'],
	['whois', 'WHOIS'],
	['winbatch', 'Win Batch'],
	['xml', 'XML'],
	['xorg_conf', 'xorg.conf'],
	['xpp', 'XPP'],
	['z80', 'z80 Assembler']];

commands.addUserCommand(
	"past[ebin]",
	"pastebin the clipboard, store the address in clipboard",
	function(args) {
		var prefix = "";
		if(args["-name"]) {
			prefix += "paste_name=" + args["-name"] + "&";
		}
		if(args["-language"]) {
			var ok = 0;
			for each (l in langlist) {
				if(args["-language"] === l[0]) {
					prefix += "paste_format=" + args["-language"] + "&";
					ok++;
					break;
				}
			}
			if(ok == 0) liberator.echo("language argument not recognized, defaulting to none");
		}
		if(args["-expire"]) {
			var ok = 0;
			for each (l in expilist) {
				if(args["-expire"] === l[0]) {
					prefix += "paste_expire_date=" + args["-expire"] + "&";
					ok++;
					break;
				}
			}
			if(ok == 0) {
				liberator.echo("expire argument not recognized, defaulting to minutes");
				prefix += "paste_expire_date=10M&";
			}
		}
		if(args["-mail"]) {
			prefix += "paste_email=" + args["-mail"] + "&";
		}
		if(args["-subdomain"]) {
			prefix += "paste_subdomain=" + args["-subdomain"] + "&";
		}
		if(args["-private"]) {
			prefix += "paste_private=1&"
		}
		pasteBin(prefix);
	}, {
		options: [
			[["-name", "-n"], commands.OPTION_STRING, function(arg) /\w+/.test(arg)],
			[["-language", "-l"], commands.OPTION_STRING, null, langlist],
			[["-expire", "-e"], commands.OPTION_STRING , null, expilist],
			[["-mail", "-m"], commands.OPTION_STRING, function(arg) /^.+\@.+\.\w+$/.test(arg)],
			[["-subdomain", "-s"], commands.OPTION_STRING, function(arg) /\w+/.test(arg)],
			[["-private", "-p"], commands.OPTION_NOARG]
		] }
);
<commit_msg>pentadactyl: fix pastebin plugin for Penta<commit_after>/**
 **
 ** paste.js
 **
 ** description :
 **  pastebin is a script to paste clipboard's content
 **  in a new pastebin. Its URL is yanked.
 **
 **
 **
 * @author Yoann Lamouroux (spamonsophia@gmail.com) (legreffier@freenode)
 * @version 1.0 now exhaustive.
 *
 **/
var INFO =
<plugin name="paste" version="1.0"
		href="http://www.overthewire.org/"
		summary="Pastebin wrapper"
		xmlns="http://vimperator.org/namespaces/liberator">
	<author email="spamonsophia@gmail.com">Yoann Lamouroux</author>
	<license href="http://www.opensource.org/licenses/mit-license.html">MIT</license>
	<project name="Vimperator" minVersion="2.0" />

		This plugin allow you to fill pastebins with clipboard's content.

	<item>
		<tags>:past :pastebin</tags>
		<spec>:past[ebin] <oa>-name=author</oa> <oa>-language=language</oa> <oa>-private</oa> <oa>-mail=you@lolcat.org</oa> <oa>-subdomain=subdom</oa></spec>
		<description>

Paste the clipboard's content in a new pastebin, yanks its URL.

You can use several options :

-name your_name (or -n) : to give your pastes an author

-language syntax_hilight (or -l) : to enable syntax hilighting

-private (or -p) : to make your pastebin private (sort of)

-mail login@mail.tld (or -m) : add a mail address

-subdomain subdom (or -s) : send the buffer to subdom.pastebin.com

		</description>
	</item>
</plugin>;

function pasteBin(arg) {
	var url = "http://pastebin.com/api_public.php";
	var http = new XMLHttpRequest();
	var params = arg + "paste_code=";
	var paste = dactyl.clipboardRead();
	if(!paste) {
		dactyl.echoerr("The clipboard is empty.\n");
		return;
	} else {
		params += paste;
	}
	http.open("POST", url, true);

	//Send the proper header information along with the request
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http.setRequestHeader("Content-length", params.length);
	http.setRequestHeader("Connection", "close");

	http.send(params);
	http.onreadystatechange = function() {
		if(http.readyState == 4 && http.status == 200) {
			dactyl.clipboardWrite(http.responseText);
			dactyl.echo("Yanked " + http.responseText);
		}
	}
}

var expilist = [['N', 'Never'], ['10M', 'Ten minutes'], ['1H', 'One hour'], ['1D', 'One day'], ['1M', 'One month']];

var langlist = [    // looooooongcat, he's rather long.
	['abap', 'ABAP'],
	['actionscript', 'ActionScript'],
	['actionscript3', 'ActionScript3'],
	['ada', 'Ada'],
	['apache', 'Apache'],
	['applescript', 'AppleScript'],
	['apt_sources', 'APT Sources'],
	['asm', 'Assembler'],
	['asp', 'ASP'],
	['autoit', 'AutoIt'],
	['avisynth', 'Avisynth'],
	['bash', 'Bash script'],
	['basic4gl', 'Basic4GL'],
	['bibtex', 'BibTeXgi'],
	['blitzbasic', 'Blitz Basic'],
	['bnf', 'BNF'],
	['boo', 'Boo'],
	['bf', 'BrainFuck'],
	['c', 'C'],
	['c_mac', 'C for Macs'],
	['cill', 'C Intermediate Language'],
	['csharp', 'C#'],
	['cpp', 'C++'],
	['caddcl', 'CAD DCL'],
	['cadlisp', 'CAD Lisp'],
	['cfdg', 'CFDG'],
	['klonec', 'Clone C'],
	['klonecpp', 'Clone C++'],
	['cmake', 'CMake'],
	['cobol', 'Cobol'],
	['cfm', 'ColdFusion'],
	['css', 'CSS'],
	['d', 'D'],
	['dcs', 'DCS'],
	['delphi', 'Delphi'],
	['dff', 'Diff'],
	['div', 'DIV'],
	['dos', 'DOS'],
	['dot', 'DOT'],
	['eiffel', 'Eiffel'],
	['email', 'E-mail'],
	['erlang', 'Erlang'],
	['fo', 'FO Language'],
	['fortran', 'Fortran'],
	['freebasic', 'FreeBasic'],
	['gml', 'Game Maker'],
	['genero', 'Genero'],
	['gettext', 'GetText'],
	['groovy', 'Groovy'],
	['haskell', 'Haskell'],
	['hq9plus', 'HQ9 Plus'],
	['html4strict', 'HTML4 strict'],
	['idl', 'IDL'],
	['ini', 'INI configuration file'],
	['inno', 'Inno script'],
	['intercal', 'INTERCAL'],
	['io', 'IO'],
	['java', 'Java'],
	['java5', 'Java5'],
	['javascript', 'JavaScript'],
	['kixtart', 'KiXtart'],
	['latex', 'Latex'],
	['lsl2', 'Linden Scripting'],
	['lisp', 'Lisp'],
	['locobasic', 'Loco Basic'],
	['lolcode', 'LOL Code'],
	['lotusformulas', 'Lotus Formulas'],
	['lotusscript', 'Lotus Script'],
	['lscript', 'LScript'],
	['lua', 'Lua'],
	['m68k', 'M68000 Assembler'],
	['make', 'Makefile'],
	['matlab', 'MatLab'],
	['matlab', 'MatLab'],
	['mirc', 'mIRC'],
	['modula3', 'Modula 3'],
	['mpasm', 'MPASM'],
	['mxml', 'MXML'],
	['mysql', 'MySQL'],
	['nsis', 'NullSoft Installer'],
	['oberon2', 'Oberon 2'],
	['objc', 'Objective C'],
	['ocaml-brief', 'OCaml Brief'],
	['ocaml', 'OCaml'],
	['glsl', 'OpenGL Shading'],
	['oobas', 'OpenOffice Basic'],
	['oracle11', 'Oracle 11'],
	['oracle8', 'Oracle 8'],
	['pascal', 'Pascal'],
	['pawn', 'PAWN'],
	['per', 'Per'],
	['perl', 'Perl'],
	['php', 'PHP'],
	['php-brief', 'PHP Brief'],
	['pic16', 'Pic 16'],
	['pixelbender', 'Pixel Bender'],
	['plsql', 'PL/SQL'],
	['povray', 'POV-Ray'],
	['powershell', 'PowerShell'],
	['progress', 'Progress'],
	['prolog', 'Prolog'],
	['properties', 'Properties'],
	['providex', 'ProvideX'],
	['python', 'Python'],
	['qbasic', 'Quick Basic'],
	['rails', 'Rails'],
	['rebol', 'REBOL'],
	['reg', 'REG'],
	['robots', 'Robots'],
	['ruby', 'Ruby'],
	['gnuplot', 'Ruby Gnuplot'],
	['sas', 'SAS'],
	['scala', 'Scala'],
	['scheme', 'Scheme'],
	['scilab', 'Scilab'],
	['sdlbasic', 'SDL Basic'],
	['smalltalk', 'SmallTalk'],
	['smarty', 'Smarty'],
	['sql', 'SQL'],
	['tsql', 'T-SQL'],
	['tcl', 'TCL'],
	['tcl', 'tcl'],
	['teraterm', 'Tera Term'],
	['thinbasic', 'thinBasic'],
	['typoscript', 'TypoScript'],
	['unreal', 'unrealScript'],
	['vbnet', 'VB.NET'],
	['verilog', 'VeriLog'],
	['vhdl', 'VHDL'],
	['vim', 'Vim'],
	['visualprolog', 'Visual Pro Log'],
	['vb', 'Visual Basic'],
	['visualfoxpro', 'VisualFoxPro'],
	['whitespace', 'WhiteSpace'],
	['whois', 'WHOIS'],
	['winbatch', 'Win Batch'],
	['xml', 'XML'],
	['xorg_conf', 'xorg.conf'],
	['xpp', 'XPP'],
	['z80', 'z80 Assembler']];

commands.addUserCommand(
	["past[ebin]"],
	"pastebin the clipboard, store the address in clipboard",
	function(args) {
		var prefix = "";
		if(args["-name"]) {
			prefix += "paste_name=" + args["-name"] + "&";
		}
		if(args["-language"]) {
			var ok = 0;
			for each (l in langlist) {
				if(args["-language"] === l[0]) {
					prefix += "paste_format=" + args["-language"] + "&";
					ok++;
					break;
				}
			}
			if(ok == 0) dactyl.echo("language argument not recognized, defaulting to none");
		}
		if(args["-expire"]) {
			var ok = 0;
			for each (l in expilist) {
				if(args["-expire"] === l[0]) {
					prefix += "paste_expire_date=" + args["-expire"] + "&";
					ok++;
					break;
				}
			}
			if(ok == 0) {
				dactyl.echo("expire argument not recognized, defaulting to minutes");
				prefix += "paste_expire_date=10M&";
			}
		}
		if(args["-mail"]) {
			prefix += "paste_email=" + args["-mail"] + "&";
		}
		if(args["-subdomain"]) {
			prefix += "paste_subdomain=" + args["-subdomain"] + "&";
		}
		if(args["-private"]) {
			prefix += "paste_private=1&"
		}
		pasteBin(prefix);
	}, {
		options: [
			[["-name", "-n"], commands.OPTION_STRING, function(arg) /\w+/.test(arg)],
			[["-language", "-l"], commands.OPTION_STRING, null, langlist],
			[["-expire", "-e"], commands.OPTION_STRING , null, expilist],
			[["-mail", "-m"], commands.OPTION_STRING, function(arg) /^.+\@.+\.\w+$/.test(arg)],
			[["-subdomain", "-s"], commands.OPTION_STRING, function(arg) /\w+/.test(arg)],
			[["-private", "-p"], commands.OPTION_NOARG]
		] }
);
<|endoftext|>


<commit_before>import debounce                          from 'lodash.debounce';
import {
    action,
    observable,
    runInAction,
    reaction }                           from 'mobx';
import Client                            from '_common/base/client_base';
import {
    getMinPayout,
    isCryptocurrency  }                  from '_common/base/currency_base';
import BinarySocket                      from '_common/base/socket_base';
import { cloneObject, isEmptyObject }    from '_common/utility';
import { WS }                            from 'Services';
import GTM                               from 'Utils/gtm';
import URLHelper                         from 'Utils/URL/url_helper';
import { processPurchase }               from './Actions/purchase';
import * as Symbol                       from './Actions/symbol';
import {
    allowed_query_string_variables,
    non_proposal_query_string_variable } from './Constants/query_string';
import getValidationRules                from './Constants/validation_rules';
import { setChartBarrier }               from './Helpers/chart';
import ContractType                      from './Helpers/contract_type';
import { convertDurationLimit }          from './Helpers/duration';
import { processTradeParams }            from './Helpers/process';
import {
    createProposalRequests,
    getProposalInfo,
    getProposalParametersName }          from './Helpers/proposal';
import { pickDefaultSymbol }             from './Helpers/symbol';
import BaseStore                         from '../../base_store';

export default class TradeStore extends BaseStore {
    // Control values
    @observable is_trade_component_mounted = false;
    @observable is_purchase_enabled        = false;
    @observable is_trade_enabled           = false;

    // Underlying
    @observable symbol;

    // Contract Type
    @observable contract_expiry_type = '';
    @observable contract_start_type  = '';
    @observable contract_type        = '';
    @observable contract_types_list  = {};
    @observable form_components      = [];
    @observable trade_types          = {};

    // Amount
    @observable amount          = 10;
    @observable basis           = '';
    @observable basis_list      = [];
    @observable currencies_list = {};
    @observable currency        = Client.get('currency');

    // Duration
    @observable duration            = 5;
    @observable duration_unit       = '';
    @observable duration_units_list = [];
    @observable duration_min_max    = {};
    @observable expiry_date         = '';
    @observable expiry_time         = '09:40';
    @observable expiry_type         = 'duration';

    // Barrier
    @observable barrier_1     = '';
    @observable barrier_2     = '';
    @observable barrier_count = 0;

    // Start Time
    @observable start_date       = Number(0); // Number(0) refers to 'now'
    @observable start_dates_list = [];
    @observable start_time       = '12:30';
    @observable sessions         = [];

    // Last Digit
    @observable last_digit = 5;

    // Purchase
    @observable proposal_info = {};
    @observable purchase_info = {};

    // Chart
    chart_id = 1;

    debouncedProposal = debounce(this.requestProposal, 500);

    constructor({ root_store }) {
        URLHelper.pruneQueryString(allowed_query_string_variables);

        super({
            root_store,
            session_storage_properties: allowed_query_string_variables,
            validation_rules          : getValidationRules(),
        });

        Object.defineProperty(
            this,
            'is_query_string_applied',
            {
                enumerable: false,
                value     : false,
                writable  : true,
            }
        );

        if (Client.isLoggedIn) {
            this.processNewValuesAsync({ currency: Client.get('currency') });
        }

        // Adds intercept to change min_max value of duration validation
        reaction(
            ()=> [this.contract_expiry_type, this.duration_min_max, this.duration_unit, this.expiry_type],
            () => {
                this.changeDurationValidationRules();
            }
        );
    }

    @action.bound
    async prepareTradeStore() {
        let query_string_values = this.updateQueryString();
        this.smart_chart = this.root_store.modules.smart_chart;
        const active_symbols = await WS.activeSymbols();

        // Checks for finding out that the current account has access to the defined symbol in quersy string or not.
        const is_invalid_symbol = !!query_string_values.symbol &&
            !active_symbols.active_symbols.find(s => s.symbol === query_string_values.symbol);

        // Changes the symbol in query string to default symbol since the account doesn't have access to the defined symbol.
        if (is_invalid_symbol) {
            this.root_store.ui.addToastMessage({
                message: 'Fusce vehicula dolor arcu, sit amet blandit dolor mollis nec. Donec viverra eleifend lacus. Fusce vehicula dolor arcu, sit amet blandit dolor mollis nec. Donec viverra eleifend lacus.',
                delay  : 100000,
                type   : 'info',
            });
            this.root_store.ui.addToastMessage({
                message: 'The specific broker is not availbe for your account2',
                delay  : 100000,
                type   : 'error',
            });
            this.root_store.ui.addToastMessage({
                message: 'The specific broker is not availbe for your account2',
                delay  : 100000,
                type   : 'success',
            });
            this.root_store.ui.addToastMessage({
                message: 'The specific broker is not availbe for your account2',
                delay  : 100000,
                type   : 'warning',
            });
            URLHelper.setQueryParam({ 'symbol': pickDefaultSymbol(active_symbols.active_symbols) });
            query_string_values = this.updateQueryString();
        }

        if (!this.symbol) {

            await this.processNewValuesAsync({
                symbol: pickDefaultSymbol(active_symbols.active_symbols),
                ...query_string_values,
            });
        }

        if (this.symbol) {
            ContractType.buildContractTypesConfig(query_string_values.symbol || this.symbol).then(action(async () => {
                await this.processNewValuesAsync({
                    ...ContractType.getContractValues(this),
                    ...ContractType.getContractCategories(),
                    ...query_string_values,
                });
            }));
        }
    }

    @action.bound
    async init() {
         // To be sure that the website_status response has been received before processing trading page.
         await BinarySocket.wait('website_status');
     };

    @action.bound
    onChange(e) {
        const { name, value } = e.target;
        if (!(name in this)) {
            throw new Error(`Invalid Argument: ${name}`);
        }

        this.processNewValuesAsync({ [name]: value }, true);
    }

    @action.bound
    onHoverPurchase(is_over, contract_type) {
        this.smart_chart.updateBarrierShade(is_over, contract_type);
    }

    @action.bound
    onPurchase(proposal_id, price, type) {
        if (proposal_id) {
            processPurchase(proposal_id, price).then(action((response) => {
                if (this.proposal_info[type].id !== proposal_id) {
                    throw new Error('Proposal ID does not match.');
                }
                if (response.buy && !Client.get('is_virtual')) {
                    const contract_data = {
                        ...this.proposal_requests[type],
                        ...this.proposal_info[type],
                        buy_price: response.buy.buy_price,
                    };
                    GTM.pushPurchaseData(contract_data, this.root_store);
                }
                WS.forgetAll('proposal');
                this.purchase_info = response;
            }));
        }
    }

    @action.bound
    onClickNewTrade(e) {
        this.requestProposal();
        e.preventDefault();
    }

    /**
     * Updates the store with new values
     * @param  {Object} new_state - new values to update the store with
     * @return {Object} returns the object having only those values that are updated
     */
    @action.bound
    updateStore(new_state) {
        Object.keys(cloneObject(new_state)).forEach((key) => {
            if (key === 'root_store' || ['validation_rules', 'validation_errors'].indexOf(key) > -1) return;
            if (JSON.stringify(this[key]) === JSON.stringify(new_state[key])) {
                delete new_state[key];
            } else {
                if (key === 'symbol') {
                    this.is_purchase_enabled = false;
                    this.is_trade_enabled    = false;
                }

                // Add changes to queryString of the url
                if (
                    allowed_query_string_variables.indexOf(key) !== -1 &&
                    this.is_trade_component_mounted
                ) {
                    URLHelper.setQueryParam({ [key]: new_state[key] });
                }

                this[key] = new_state[key];

                // validation is done in mobx intercept (base_store.js)
                // when barrier_1 is set, it is compared with store.barrier_2 (which is not updated yet)
                if (key === 'barrier_2' && new_state.barrier_1) {
                    this.barrier_1 = new_state.barrier_1; // set it again, after barrier_2 is updated in store
                }
            }
        });

        return new_state;
    }

    async processNewValuesAsync(obj_new_values = {}, is_changed_by_user = false) {
        // Sets the default value to Amount when Currency has changed from Fiat to Crypto and vice versa.
        // The source of default values is the website_status response.
        if (is_changed_by_user && /\bcurrency\b/.test(Object.keys(obj_new_values)) &&
            isCryptocurrency(obj_new_values.currency) !== isCryptocurrency(this.currency)) {
            obj_new_values.amount = obj_new_values.amount || getMinPayout(obj_new_values.currency);
        }

        const new_state = this.updateStore(cloneObject(obj_new_values));

        if (is_changed_by_user || /\b(symbol|contract_types_list)\b/.test(Object.keys(new_state))) {
            if ('symbol' in new_state) {
                await Symbol.onChangeSymbolAsync(new_state.symbol);
            }

            this.updateStore({ // disable purchase button(s), clear contract info
                is_purchase_enabled: false,
                proposal_info      : {},
            });

            if (!this.smart_chart.is_contract_mode) {
                const is_barrier_changed = 'barrier_1' in new_state || 'barrier_2' in new_state;
                if (is_barrier_changed) {
                    this.smart_chart.updateBarriers(this.barrier_1, this.barrier_2);
                } else {
                    this.smart_chart.removeBarriers();
                }
            }

            const snapshot = await processTradeParams(this, new_state);
            const query_string_values = this.updateQueryString();
            snapshot.is_trade_enabled = true;

            this.updateStore({
                ...snapshot,
                ...(this.is_query_string_applied ? {} : query_string_values), // Applies the query string values again to set barriers.
            });

            this.is_query_string_applied = true;

            if (/\bcontract_type\b/.test(Object.keys(new_state))) {
                this.validateAllProperties();
            }

            this.debouncedProposal();
        }
    }

    proposal_requests = {};

    @action.bound
    requestProposal() {
        const requests = createProposalRequests(this);

        if (Object.values(this.validation_errors).some(e => e.length)) {
            this.proposal_info     = {};
            this.purchase_info     = {};
            WS.forgetAll('proposal');
            return;
        }

        if (!isEmptyObject(requests)) {
            const proper_proposal_params_for_query_string = getProposalParametersName(requests);

            URLHelper.pruneQueryString(
                [
                    ...proper_proposal_params_for_query_string,
                    ...non_proposal_query_string_variable,
                ]
            );

            this.proposal_requests = requests;
            this.proposal_info     = {};
            this.purchase_info     = {};

            WS.forgetAll('proposal').then(() => {
                Object.keys(this.proposal_requests).forEach((type) => {
                    WS.subscribeProposal(this.proposal_requests[type], this.onProposalResponse);
                });
            });
        }
    }

    @action.bound
    onProposalResponse(response) {
        const contract_type = response.echo_req.contract_type;
        this.proposal_info = {
            ...this.proposal_info,
            [contract_type]: getProposalInfo(this, response),
        };

        if (!this.smart_chart.is_contract_mode) {
            setChartBarrier(this.smart_chart, response, this.onChartBarrierChange);
        }

        this.is_purchase_enabled = true;
    }

    @action.bound
    onChartBarrierChange(barrier_1, barrier_2) {
        this.processNewValuesAsync({ barrier_1, barrier_2 }, true);
    }

    @action.bound
    updateQueryString() {

        // Update the url's query string by default values of the store
        const query_params = URLHelper.updateQueryString(
            this,
            allowed_query_string_variables,
            this.is_trade_component_mounted
        );

        // update state values from query string
        const config = {};
        [...query_params].forEach(param => config[param[0]] = param[1]);
        return config;
    }

    @action.bound
    changeDurationValidationRules() {
        if (this.expiry_type === 'endtime') {
            this.validation_errors.duration = [];
            return;
        }

        const index = this.validation_rules.duration.findIndex(item => item[0] === 'number');
        const limits = this.duration_min_max[this.contract_expiry_type] || false;

        if (limits) {
            const duration_options = {
                min: convertDurationLimit(+limits.min, this.duration_unit),
                max: convertDurationLimit(+limits.max, this.duration_unit),
            };

            if (index > -1) {
                this.validation_rules.duration[index][1] = duration_options;
            } else {
                this.validation_rules.duration.push(['number', duration_options]);
            }
            this.validateProperty('duration', this.duration);
        }
    }

    @action.bound
    async onMount() {
        await this.prepareTradeStore();
        this.debouncedProposal();
        runInAction(() => {
            this.is_trade_component_mounted = true;
        });
        this.updateQueryString();
    }

    @action.bound
    onUnmount() {
        WS.forgetAll('proposal');
        this.is_trade_component_mounted = false;
    }
}
<commit_msg>Added the message of toast<commit_after>import debounce                          from 'lodash.debounce';
import {
    action,
    observable,
    runInAction,
    reaction }                           from 'mobx';
import Client                            from '_common/base/client_base';
import {
    getMinPayout,
    isCryptocurrency  }                  from '_common/base/currency_base';
import BinarySocket                      from '_common/base/socket_base';
import { localize }                      from '_common/localize';
import { cloneObject, isEmptyObject }    from '_common/utility';
import { WS }                            from 'Services';
import GTM                               from 'Utils/gtm';
import URLHelper                         from 'Utils/URL/url_helper';
import { processPurchase }               from './Actions/purchase';
import * as Symbol                       from './Actions/symbol';
import {
    allowed_query_string_variables,
    non_proposal_query_string_variable } from './Constants/query_string';
import getValidationRules                from './Constants/validation_rules';
import { setChartBarrier }               from './Helpers/chart';
import ContractType                      from './Helpers/contract_type';
import { convertDurationLimit }          from './Helpers/duration';
import { processTradeParams }            from './Helpers/process';
import {
    createProposalRequests,
    getProposalInfo,
    getProposalParametersName }          from './Helpers/proposal';
import { pickDefaultSymbol }             from './Helpers/symbol';
import BaseStore                         from '../../base_store';

export default class TradeStore extends BaseStore {
    // Control values
    @observable is_trade_component_mounted = false;
    @observable is_purchase_enabled        = false;
    @observable is_trade_enabled           = false;

    // Underlying
    @observable symbol;

    // Contract Type
    @observable contract_expiry_type = '';
    @observable contract_start_type  = '';
    @observable contract_type        = '';
    @observable contract_types_list  = {};
    @observable form_components      = [];
    @observable trade_types          = {};

    // Amount
    @observable amount          = 10;
    @observable basis           = '';
    @observable basis_list      = [];
    @observable currencies_list = {};
    @observable currency        = Client.get('currency');

    // Duration
    @observable duration            = 5;
    @observable duration_unit       = '';
    @observable duration_units_list = [];
    @observable duration_min_max    = {};
    @observable expiry_date         = '';
    @observable expiry_time         = '09:40';
    @observable expiry_type         = 'duration';

    // Barrier
    @observable barrier_1     = '';
    @observable barrier_2     = '';
    @observable barrier_count = 0;

    // Start Time
    @observable start_date       = Number(0); // Number(0) refers to 'now'
    @observable start_dates_list = [];
    @observable start_time       = '12:30';
    @observable sessions         = [];

    // Last Digit
    @observable last_digit = 5;

    // Purchase
    @observable proposal_info = {};
    @observable purchase_info = {};

    // Chart
    chart_id = 1;

    debouncedProposal = debounce(this.requestProposal, 500);

    constructor({ root_store }) {
        URLHelper.pruneQueryString(allowed_query_string_variables);

        super({
            root_store,
            session_storage_properties: allowed_query_string_variables,
            validation_rules          : getValidationRules(),
        });

        Object.defineProperty(
            this,
            'is_query_string_applied',
            {
                enumerable: false,
                value     : false,
                writable  : true,
            }
        );

        if (Client.isLoggedIn) {
            this.processNewValuesAsync({ currency: Client.get('currency') });
        }

        // Adds intercept to change min_max value of duration validation
        reaction(
            ()=> [this.contract_expiry_type, this.duration_min_max, this.duration_unit, this.expiry_type],
            () => {
                this.changeDurationValidationRules();
            }
        );
    }

    @action.bound
    async prepareTradeStore() {
        let query_string_values = this.updateQueryString();
        this.smart_chart = this.root_store.modules.smart_chart;
        const active_symbols = await WS.activeSymbols();

        // Checks for finding out that the current account has access to the defined symbol in quersy string or not.
        const is_invalid_symbol = !!query_string_values.symbol &&
            !active_symbols.active_symbols.find(s => s.symbol === query_string_values.symbol);

        // Changes the symbol in query string to default symbol since the account doesn't have access to the defined symbol.
        if (is_invalid_symbol) {
            this.root_store.ui.addToastMessage({
                message: localize('Certain trade parameters have been changed due to your account settings.'),
                type   : 'info',
            });
            URLHelper.setQueryParam({ 'symbol': pickDefaultSymbol(active_symbols.active_symbols) });
            query_string_values = this.updateQueryString();
        }

        if (!this.symbol) {

            await this.processNewValuesAsync({
                symbol: pickDefaultSymbol(active_symbols.active_symbols),
                ...query_string_values,
            });
        }

        if (this.symbol) {
            ContractType.buildContractTypesConfig(query_string_values.symbol || this.symbol).then(action(async () => {
                await this.processNewValuesAsync({
                    ...ContractType.getContractValues(this),
                    ...ContractType.getContractCategories(),
                    ...query_string_values,
                });
            }));
        }
    }

    @action.bound
    init  = async () => {
        // To be sure that the website_status response has been received before processing trading page.
        await BinarySocket.wait('website_status');
    };

    @action.bound
    onChange(e) {
        const { name, value } = e.target;
        if (!(name in this)) {
            throw new Error(`Invalid Argument: ${name}`);
        }

        this.processNewValuesAsync({ [name]: value }, true);
    }

    @action.bound
    onHoverPurchase(is_over, contract_type) {
        this.smart_chart.updateBarrierShade(is_over, contract_type);
    }

    @action.bound
    onPurchase(proposal_id, price, type) {
        if (proposal_id) {
            processPurchase(proposal_id, price).then(action((response) => {
                if (this.proposal_info[type].id !== proposal_id) {
                    throw new Error('Proposal ID does not match.');
                }
                if (response.buy && !Client.get('is_virtual')) {
                    const contract_data = {
                        ...this.proposal_requests[type],
                        ...this.proposal_info[type],
                        buy_price: response.buy.buy_price,
                    };
                    GTM.pushPurchaseData(contract_data, this.root_store);
                }
                WS.forgetAll('proposal');
                this.purchase_info = response;
            }));
        }
    }

    @action.bound
    onClickNewTrade(e) {
        this.requestProposal();
        e.preventDefault();
    }

    /**
     * Updates the store with new values
     * @param  {Object} new_state - new values to update the store with
     * @return {Object} returns the object having only those values that are updated
     */
    @action.bound
    updateStore(new_state) {
        Object.keys(cloneObject(new_state)).forEach((key) => {
            if (key === 'root_store' || ['validation_rules', 'validation_errors'].indexOf(key) > -1) return;
            if (JSON.stringify(this[key]) === JSON.stringify(new_state[key])) {
                delete new_state[key];
            } else {
                if (key === 'symbol') {
                    this.is_purchase_enabled = false;
                    this.is_trade_enabled    = false;
                }

                // Add changes to queryString of the url
                if (
                    allowed_query_string_variables.indexOf(key) !== -1 &&
                    this.is_trade_component_mounted
                ) {
                    URLHelper.setQueryParam({ [key]: new_state[key] });
                }

                this[key] = new_state[key];

                // validation is done in mobx intercept (base_store.js)
                // when barrier_1 is set, it is compared with store.barrier_2 (which is not updated yet)
                if (key === 'barrier_2' && new_state.barrier_1) {
                    this.barrier_1 = new_state.barrier_1; // set it again, after barrier_2 is updated in store
                }
            }
        });

        return new_state;
    }

    async processNewValuesAsync(obj_new_values = {}, is_changed_by_user = false) {
        // Sets the default value to Amount when Currency has changed from Fiat to Crypto and vice versa.
        // The source of default values is the website_status response.
        if (is_changed_by_user && /\bcurrency\b/.test(Object.keys(obj_new_values)) &&
            isCryptocurrency(obj_new_values.currency) !== isCryptocurrency(this.currency)) {
            obj_new_values.amount = obj_new_values.amount || getMinPayout(obj_new_values.currency);
        }

        const new_state = this.updateStore(cloneObject(obj_new_values));

        if (is_changed_by_user || /\b(symbol|contract_types_list)\b/.test(Object.keys(new_state))) {
            if ('symbol' in new_state) {
                await Symbol.onChangeSymbolAsync(new_state.symbol);
            }

            this.updateStore({ // disable purchase button(s), clear contract info
                is_purchase_enabled: false,
                proposal_info      : {},
            });

            if (!this.smart_chart.is_contract_mode) {
                const is_barrier_changed = 'barrier_1' in new_state || 'barrier_2' in new_state;
                if (is_barrier_changed) {
                    this.smart_chart.updateBarriers(this.barrier_1, this.barrier_2);
                } else {
                    this.smart_chart.removeBarriers();
                }
            }

            const snapshot = await processTradeParams(this, new_state);
            const query_string_values = this.updateQueryString();
            snapshot.is_trade_enabled = true;

            this.updateStore({
                ...snapshot,
                ...(this.is_query_string_applied ? {} : query_string_values), // Applies the query string values again to set barriers.
            });

            this.is_query_string_applied = true;

            if (/\bcontract_type\b/.test(Object.keys(new_state))) {
                this.validateAllProperties();
            }

            this.debouncedProposal();
        }
    }

    proposal_requests = {};

    @action.bound
    requestProposal() {
        const requests = createProposalRequests(this);

        if (Object.values(this.validation_errors).some(e => e.length)) {
            this.proposal_info     = {};
            this.purchase_info     = {};
            WS.forgetAll('proposal');
            return;
        }

        if (!isEmptyObject(requests)) {
            const proper_proposal_params_for_query_string = getProposalParametersName(requests);

            URLHelper.pruneQueryString(
                [
                    ...proper_proposal_params_for_query_string,
                    ...non_proposal_query_string_variable,
                ]
            );

            this.proposal_requests = requests;
            this.proposal_info     = {};
            this.purchase_info     = {};

            WS.forgetAll('proposal').then(() => {
                Object.keys(this.proposal_requests).forEach((type) => {
                    WS.subscribeProposal(this.proposal_requests[type], this.onProposalResponse);
                });
            });
        }
    }

    @action.bound
    onProposalResponse(response) {
        const contract_type = response.echo_req.contract_type;
        this.proposal_info = {
            ...this.proposal_info,
            [contract_type]: getProposalInfo(this, response),
        };

        if (!this.smart_chart.is_contract_mode) {
            setChartBarrier(this.smart_chart, response, this.onChartBarrierChange);
        }

        this.is_purchase_enabled = true;
    }

    @action.bound
    onChartBarrierChange(barrier_1, barrier_2) {
        this.processNewValuesAsync({ barrier_1, barrier_2 }, true);
    }

    @action.bound
    updateQueryString() {

        // Update the url's query string by default values of the store
        const query_params = URLHelper.updateQueryString(
            this,
            allowed_query_string_variables,
            this.is_trade_component_mounted
        );

        // update state values from query string
        const config = {};
        [...query_params].forEach(param => config[param[0]] = param[1]);
        return config;
    }

    @action.bound
    changeDurationValidationRules() {
        if (this.expiry_type === 'endtime') {
            this.validation_errors.duration = [];
            return;
        }

        const index = this.validation_rules.duration.findIndex(item => item[0] === 'number');
        const limits = this.duration_min_max[this.contract_expiry_type] || false;

        if (limits) {
            const duration_options = {
                min: convertDurationLimit(+limits.min, this.duration_unit),
                max: convertDurationLimit(+limits.max, this.duration_unit),
            };

            if (index > -1) {
                this.validation_rules.duration[index][1] = duration_options;
            } else {
                this.validation_rules.duration.push(['number', duration_options]);
            }
            this.validateProperty('duration', this.duration);
        }
    }

    @action.bound
    async onMount() {
        await this.prepareTradeStore();
        this.debouncedProposal();
        runInAction(() => {
            this.is_trade_component_mounted = true;
        });
        this.updateQueryString();
    }

    @action.bound
    onUnmount() {
        WS.forgetAll('proposal');
        this.is_trade_component_mounted = false;
    }
}
<|endoftext|>


<commit_before>(function () {
  "use strict";

  var connect = require('connect')
    , pathname = process.cwd()
    , fs = require('fs')
    , path = require('path')
    , app
    , version = JSON.parse(fs.readFileSync(path.join(__dirname, '/../package.json'), 'utf8')).version
    ;

  app = connect()
    .use(connect.static(pathname))
    .use(connect.directory(pathname))
    .use('/version', function (req, res, next) {
      res.end(version);
    })
    ;

  module.exports = app;
  module.exports.path = pathname;
}());
<commit_msg>Now handles POSTing files (but not to directories)<commit_after>/*jshint strict:true node:true es5:true onevar:true laxcomma:true laxbreak:true eqeqeq:true immed:true latedef:true*/
(function () {
  "use strict";

  // TODO receive files
  var connect = require('connect')
    , pathname = process.cwd()
    , util = require('util')
    , fs = require('fs')
    , url = require('url')
    , path = require('path')
    , app
    , version = JSON.parse(fs.readFileSync(path.join(__dirname, '/../package.json'), 'utf8')).version
    ;

  app = connect()
    .use(connect.static(pathname))
    .use(connect.directory(pathname))
    .use(function (req, res, next) {
        var filename = url.parse(req.url).pathname.replace(/.*\//, '')
          , ws
          , err
          ;

        filename = filename || 'served-stream.bin';

        if (!/^POST$/i.exec(req.method)) {
          next();
        }

        util.print('Receiving ' + filename + ' ');

        try {
          // forgive me, for I have sinned
          fs.statSync(filename);
        } catch(e) {
          err = e;
        }

        if (!err) {
          console.log('hmm... that file exists, cancelling');
          res.end();
          return;
        }

        ws = fs.createWriteStream(filename);
        ws.on('error', function (err) {
          console.log('Had some problem... cancelling');
          console.error(err.message);
          res.end(err.message, 500);
        });
        req.on('data', function (chunk) {
          ws.write(chunk);
          util.print('.');
        });
        req.on('end', function () {
          ws.end();
          res.end();
          util.print(' done!');
          console.log();
        });
      })
    .use('/version', function (req, res, next) {
        res.end(version);
      })
    ;

  module.exports = app;
  module.exports.path = pathname;
}());
<|endoftext|>


<commit_before>/*!
 * VIZABI BUBBLE COLOR LEGEND COMPONENT
 */

(function() {

    "use strict";

    var Vizabi = this.Vizabi;
    var utils = Vizabi.utils;
    var INDICATOR = "which";

    if (!Vizabi._require('d3')) return;

    Vizabi.Component.extend('gapminder-colorlegend', {

        init: function(config, context) {
            var _this = this;
            this.template = '

';

            this.model_expects = [{
                name: "color",
                type: "color"
            },{
                name: "entities",
                type: "entities"
            },{
                name: "language",
                type: "language"
            }];

            this.needsUpdate = false;
            this.which_1 = false;
            this.scaleType_1 = false;

            this.model_binds = {
                "change:color": function(evt) {
                    if(_this.model.color.which != _this.which_1
                       || _this.model.color.scaleType != _this.scaleType_1 ) {
                        _this.needsUpdate = true;
                        _this.which_1 = _this.model.color.which;
                        _this.scaleType_1 = _this.model.color.scaleType;
                    }
                },
                "change:language": function(evt) {
                    _this.updateView();
                },
                "ready": function(evt) {
                    if(!_this._readyOnce) return;
                    if(_this.needsUpdate){
                        _this.updateView();
                        _this.needsUpdate = false;
                    }
                }
            }

            //contructor is the same as any component
            this._super(config, context);
        },

        readyOnce: function() {
            var _this = this;
            this.element = d3.select(this.element);
            this.listColorsEl = this.element.append("div").attr("class", "vzb-cl-colorList");
            this.rainbowEl = this.listColorsEl.append("div").attr("class", "vzb-cl-rainbow");
            this.worldmapEl = this.listColorsEl.append("div").attr("class", "vzb-cl-worldmap");

            this.colorPicker = d3.svg.colorPicker();
            this.element.call(this.colorPicker);

            this.worldMap = d3.svg.worldMap();
            this.worldmapEl.call(this.worldMap);

            this.updateView();
        },

        updateView: function(){
            var _this = this;
            this.translator = this.model.language.getTFunction();

            var palette = this.model.color.palette;

            var whichPalette = "_default";
            if(Object.keys(this.model.color.getPalettes()).indexOf(this.model.color[INDICATOR]) > -1) {
                whichPalette = this.model.color[INDICATOR];
            }

            var paletteDefault = this.model.color.getPalettes()[whichPalette];

            var colors = this.listColorsEl
                .selectAll(".vzb-cl-option")
                .data(utils.keys(paletteDefault), function(d){return d});

            colors.exit().remove();

            colors.enter().append("div").attr("class", "vzb-cl-option")
                .each(function(){
                    d3.select(this).append("div").attr("class", "vzb-cl-color-sample");
                    d3.select(this).append("div").attr("class", "vzb-cl-color-legend");
                })
                .on("mouseover", function(){
                    //disable interaction if so stated in metadata
                    if(!_this.model.color.isUserSelectable(whichPalette)) return;

                    var sample = d3.select(this).select(".vzb-cl-color-sample");
                    sample.style("border-width", "5px");
                    sample.style("background-color", "transparent");

                })
                .on("mouseout", function(d){
                    //disable interaction if so stated in metadata
                    if(!_this.model.color.isUserSelectable(whichPalette)) return;

                    var sample = d3.select(this).select(".vzb-cl-color-sample");
                    sample.style("border-width", "0px");
                    sample.style("background-color", _this.model.color.palette[d]);
                })
                .on("click", function(d){
                    //disable interaction if so stated in metadata
                    if(!_this.model.color.isUserSelectable(whichPalette)) return;

                    _this.colorPicker
                        .colorOld(palette[d])
                        .colorDef(paletteDefault[d])
                        .callback(function(value){_this.model.color.setColor(value, d)})
                        .show(true);
                })

            if(this.model.color.use == "indicator"){
                this.rainbowEl.classed("vzb-hidden", false)
                    .style("height", (utils.keys(paletteDefault).length * 25 + 5) + "px")
                    .style("background", "linear-gradient(" + utils.values(palette._data).join(", ") +")");
            }else{
                this.rainbowEl.classed("vzb-hidden", true);
            }

            if(this.model.color[INDICATOR] == "geo.region"){
                var regions = this.worldmapEl.classed("vzb-hidden", false)
                    .select("svg").selectAll("g");
                regions.each(function(){
                    var view = d3.select(this);
                    var color = palette[view.attr("id")];
                    view.selectAll("path").style("fill",color);
                })
                .style("opacity", 0.8)
                .on("mouseover", function(){
                    var view = d3.select(this);
                    var region = view.attr("id");
                    regions.selectAll("path").style("opacity",0.5);
                    view.selectAll("path").style("opacity",1);

                    //TODO: accessing _filtered is an ugly hack. should be optimised later
                    var highlight = utils.values(_this.model.color._filtered)
                        //returns a function over time. pick the last time-value
                        .map(function(d){return d[d.length-1]})
                        //filter so that only countries of the correct region remain
                        .filter(function(f){return f["geo.region"]==region})
                        //fish out the "geo" field, leave the rest behind
                        .map(function(d){return {geo: d.geo}});

                    _this.model.entities.setHighlighted(highlight);
                })
                .on("mouseout", function(){
                    regions.selectAll("path").style("opacity",0.8);
                    _this.model.entities.clearHighlighted();
                })
                .on("click", function(d){
                    //disable interaction if so stated in metadata
                    if(!_this.model.color.isUserSelectable(whichPalette)) return;
                    var view = d3.select(this);
                    var region = view.attr("id")

                    _this.colorPicker
                        .colorOld(palette[region])
                        .colorDef(paletteDefault[region])
                        .callback(function(value){_this.model.color.setColor(value, region)})
                        .show(true);
                })
                colors.classed("vzb-hidden", true);
            }else{
                this.worldmapEl.classed("vzb-hidden", true);
                colors.classed("vzb-hidden", false);
            }

            colors.each(function(d, index){
                d3.select(this).select(".vzb-cl-color-sample")
                    .style("background-color", palette[d])
                    .style("border", "1px solid " + palette[d]);

                if(_this.model.color.use == "indicator"){
                    var domain = _this.model.color.getScale().domain();
                    d3.select(this).select(".vzb-cl-color-legend")
                        .text(_this.model.color.tickFormatter(domain[index]))
                }else{

                    d3.select(this).select(".vzb-cl-color-legend")
                        .text(_this.translator("color/" + _this.model.color[INDICATOR] + "/" + d));
                }
            });
        }

    });

}).call(this);<commit_msg>Fix Changed an indicator, color legend didn't update. Fix Change color: wrong stuff updates in legend. Closes #144<commit_after>/*!
 * VIZABI BUBBLE COLOR LEGEND COMPONENT
 */

(function() {

    "use strict";

    var Vizabi = this.Vizabi;
    var utils = Vizabi.utils;
    var INDICATOR = "which";

    if (!Vizabi._require('d3')) return;

    Vizabi.Component.extend('gapminder-colorlegend', {

        init: function(config, context) {
            var _this = this;
            this.template = '

';

            this.model_expects = [{
                name: "color",
                type: "color"
            },{
                name: "entities",
                type: "entities"
            },{
                name: "language",
                type: "language"
            }];

            this.needsUpdate = false;
            this.which_1 = false;
            this.scaleType_1 = false;

            this.model_binds = {
                "change:color": function(evt) {
                    _this.updateView();
                },
                "change:language": function(evt) {
                    _this.updateView();
                },
                "ready": function(evt) {
                    if(!_this._readyOnce) return;
                     _this.updateView();
                }
            }

            //contructor is the same as any component
            this._super(config, context);
        },

        readyOnce: function() {
            var _this = this;
            this.element = d3.select(this.element);
            this.listColorsEl = this.element.append("div").attr("class", "vzb-cl-colorList");
            this.rainbowEl = this.listColorsEl.append("div").attr("class", "vzb-cl-rainbow");
            this.worldmapEl = this.listColorsEl.append("div").attr("class", "vzb-cl-worldmap");

            this.colorPicker = d3.svg.colorPicker();
            this.element.call(this.colorPicker);

            this.worldMap = d3.svg.worldMap();
            this.worldmapEl.call(this.worldMap);

            this.updateView();
        },

        updateView: function(){
            var _this = this;
            this.translator = this.model.language.getTFunction();

            var palette = this.model.color.palette;

            var whichPalette = "_default";
            if(Object.keys(this.model.color.getPalettes()).indexOf(this.model.color[INDICATOR]) > -1) {
                whichPalette = this.model.color[INDICATOR];
            }

            var paletteDefault = this.model.color.getPalettes()[whichPalette];

            var colors = this.listColorsEl
                .selectAll(".vzb-cl-option")
                .data(utils.keys(paletteDefault), function(d){return d});

            colors.exit().remove();

            colors.enter().append("div").attr("class", "vzb-cl-option")
                .each(function(){
                    d3.select(this).append("div").attr("class", "vzb-cl-color-sample");
                    d3.select(this).append("div").attr("class", "vzb-cl-color-legend");
                })
                .on("mouseover", function(){
                    //disable interaction if so stated in metadata
                    if(!_this.model.color.isUserSelectable(whichPalette)) return;

                    var sample = d3.select(this).select(".vzb-cl-color-sample");
                    sample.style("border-width", "5px");
                    sample.style("background-color", "transparent");

                })
                .on("mouseout", function(d){
                    //disable interaction if so stated in metadata
                    if(!_this.model.color.isUserSelectable(whichPalette)) return;

                    var sample = d3.select(this).select(".vzb-cl-color-sample");
                    sample.style("border-width", "0px");
                    sample.style("background-color", _this.model.color.palette[d]);
                })
                .on("click", function(d){
                    //disable interaction if so stated in metadata
                    if(!_this.model.color.isUserSelectable(whichPalette)) return;

                    _this.colorPicker
                        .colorOld(palette[d])
                        .colorDef(paletteDefault[d])
                        .callback(function(value){_this.model.color.setColor(value, d)})
                        .show(true);
                })

            if(this.model.color.use == "indicator"){
                this.rainbowEl.classed("vzb-hidden", false)
                    .style("height", (utils.keys(paletteDefault).length * 25 + 5) + "px")
                    .style("background", "linear-gradient(" + utils.values(palette._data).join(", ") +")");
            }else{
                this.rainbowEl.classed("vzb-hidden", true);
            }

            if(this.model.color[INDICATOR] == "geo.region"){
                var regions = this.worldmapEl.classed("vzb-hidden", false)
                    .select("svg").selectAll("g");
                regions.each(function(){
                    var view = d3.select(this);
                    var color = palette[view.attr("id")];
                    view.selectAll("path").style("fill",color);
                })
                .style("opacity", 0.8)
                .on("mouseover", function(){
                    var view = d3.select(this);
                    var region = view.attr("id");
                    regions.selectAll("path").style("opacity",0.5);
                    view.selectAll("path").style("opacity",1);

                    //TODO: accessing _filtered is an ugly hack. should be optimised later
                    var highlight = utils.values(_this.model.color._filtered)
                        //returns a function over time. pick the last time-value
                        .map(function(d){return d[d.length-1]})
                        //filter so that only countries of the correct region remain
                        .filter(function(f){return f["geo.region"]==region})
                        //fish out the "geo" field, leave the rest behind
                        .map(function(d){return {geo: d.geo}});

                    _this.model.entities.setHighlighted(highlight);
                })
                .on("mouseout", function(){
                    regions.selectAll("path").style("opacity",0.8);
                    _this.model.entities.clearHighlighted();
                })
                .on("click", function(d){
                    //disable interaction if so stated in metadata
                    if(!_this.model.color.isUserSelectable(whichPalette)) return;
                    var view = d3.select(this);
                    var region = view.attr("id")

                    _this.colorPicker
                        .colorOld(palette[region])
                        .colorDef(paletteDefault[region])
                        .callback(function(value){_this.model.color.setColor(value, region)})
                        .show(true);
                })
                colors.classed("vzb-hidden", true);
            }else{
                this.worldmapEl.classed("vzb-hidden", true);
                colors.classed("vzb-hidden", false);
            }

            colors.each(function(d, index){
                d3.select(this).select(".vzb-cl-color-sample")
                    .style("background-color", palette[d])
                    .style("border", "1px solid " + palette[d]);

                if(_this.model.color.use == "indicator"){
                    var domain = _this.model.color.getScale().domain();
                    d3.select(this).select(".vzb-cl-color-legend")
                        .text(_this.model.color.tickFormatter(domain[index]))
                }else{

                    d3.select(this).select(".vzb-cl-color-legend")
                        .text(_this.translator("color/" + _this.model.color[INDICATOR] + "/" + d));
                }
            });
        }

    });

}).call(this);<|endoftext|>