working on it ...

Filters

Explore Public Snippets

Sort by

Found 128k snippets

    public by JKCPR modified Apr 25, 2018  164  0  4  0

    unit testing - mocking server responses with sinonjs

    {
        setUp: function () {
            this.server = sinon.fakeServer.create();
        },
    
        tearDown: function () {
            this.server.restore();
        },
    
        "test should fetch comments from server" : function () {
            this.server.respondWith("GET", "/some/article/comments.json",
                                    [200, { "Content-Type": "application/json" },
                                     '[{ "id": 12, "comment": "Hey there" }]']);
    
            var callback = sinon.spy();
            myLib.getCommentsFor("/some/article", callback);
            this.server.respond();
    
            sinon.assert.calledWith(callback, [{ id: 12, comment: "Hey there" }]));
        }
    }		

    public by tomsim modified Jan 21, 2018  1212  1  6  0

    Simple RPC call

    Simple function to call RPC (only 1k uncompressed). Use this instead of JQuery. Alternatively, use zepto.min.js from zeptojs.com if you have 26K to spare.
    /* 
    Addapted from Paolo Manna git pmanna/mongoose_os_playground browser_rpc_service.js
    */
    
    var platform = '';
    var host = '';
    
    var defCallBack = function(response) {
      if ((response) && (response.error)) {
    	  alert(response.message);
      }
    };
    
    // Common call to RPC services on the board
    function callRPCService(cmd, params, callback) {
      if (!callback) {
    	  callback = defCallBack;
      }
      var xhttp = new XMLHttpRequest();
      
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          callback(this.response);
        }
      };
      
      xhttp.open('POST', 'rpc/' + cmd + '?' + new Date().getTime(), true);
      xhttp.responseType = 'json';
      xhttp.send(JSON.stringify(params));
    }
    
    // Discover which platform we're using, to enable/disable features
    function startup() {
      callRPCService('Config.Get',{}, function(response) {
        if (response) {
          platform = response.device.id;
          console.log('Platform is: ' + platform);
    
          var mac_id = (response.device.id.split("_"))[1];
    
          host = mac_id + '.local';
          document.getElementById("hostname").innerHTML = host;
        }
      });
    }
    
    // Reboots the microcontroller
    function rebootDevice() {
      callRPCService('Sys.Reboot',{delay_ms:500});
    }
    
    						

    public by Tech_JA modified Oct 26, 2017  199  1  5  0

    sqlite-sync.js

    
    var sqlite = require('sqlite-sync'); //requiring 
     
    //Connecting - if the file does not exist it will be created 
    sqlite.connect('test/test.db'); 
     
    //Creating table - you can run any command 
    sqlite.run("CREATE TABLE COMPANYS(ID  INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL);");
     
    //Inserting - this function can be sync to, look the wiki 
    sqlite.insert("COMPANYS",{NAME:"My COMPANY"}, function(inserid){
    	console.log(inserid);
    });
     
    //Updating - returns the number of rows modified - can be async too 
    var rows_modified = sqlite.update("COMPANYS",{NAME:"TESTING UPDATE"},{ID:1});
     
    //Create your function 
    function test(a,b){
    	return a+b;
    }
     
    //Add your function to connection 
    sqlite.create_function(test);
     
    // Use your function in the SQL 
    console.log(sqlite.run("SELECT ID, test(NAME, ' Inc') as NAME FROM COMPANYS"));
     
    // Closing connection  
    sqlite.close();
    
    					

    public by Tech_JA modified Oct 26, 2017  207  0  5  0

    Get the current date and time

    Get the current date and time
    var datetime = "";
    
    function getdate() {
        var currentdate = new Date();
        datetime = currentdate.getFullYear();
        datetime += "/";
        if (currentdate.getMonth() < 10) {
            datetime += "0" + currentdate.getMonth();
        } else {
            datetime = currentdate.getMonth();
        }
        datetime += "/";
        if (currentdate.getDate() < 10) {
            datetime += "0" + currentdate.getDate();
        } else {
            datetime += currentdate.getDate();
        }
        datetime += " ";
        if (currentdate.getHours() < 10) {
            datetime += " " + currentdate.getHours();
        } else {
            datetime += currentdate.getHours();
        }
        datetime += ":";
        if (currentdate.getMinutes() < 10) {
            datetime += "0" + currentdate.getMinutes();
        } else {
            datetime += currentdate.getMinutes();
        }
        datetime += ":";
        if (currentdate.getSeconds() < 10) {
            datetime += "0" + currentdate.getSeconds();
        } else {
            datetime += currentdate.getSeconds();
        }
    }
    
    getdate();
    console.log("data e hora actuais: " + datetime);						

    public by electron modified Oct 18, 2017  259  0  4  0

    es6 async function

    template for async function es6 javascript js
    async function GetData() {
    	const resp = await axios.get('/url')
    	console.log(resp)
    }
    
    GetaData()

    public by teppeis modified Sep 18, 2017  88  0  1  0

    Safari 10.1 `nomodule` support

    Safari 10.1 `nomodule` support: safari-nomodule.js
    /**
     * Safari 10.1 supports modules, but does not support the `nomodule` attribute - it will
     * load <script nomodule> anyway. This snippet solve this problem, but only for script
     * tags that load external code, e.g.: <script nomodule src="nomodule.js"></script>
     *
     * Again: this will **not** prevent inline script, e.g.:
     * <script nomodule>alert('no modules');</script>.
     *
     * This workaround is possible because Safari supports the non-standard 'beforeload' event.
     * This allows us to trap the module and nomodule load.
     *
     * Note also that `nomodule` is supported in later versions of Safari - it's just 10.1 that
     * omits this attribute.
     */
    (function() {
      var check = document.createElement('script');
      if (!('noModule' in check) && 'onbeforeload' in check) {
        var supportModule = false;
        document.addEventListener('beforeload', function(e) {
          if (e.target === check) {
            supportModule = true;
          } else if (e.target.hasAttribute('nomodule') && supportModule) {
            e.preventDefault();
          }
        }, true);
    
        check.type = 'module';
        check.src = '.';
        document.head.appendChild(check);
        check.remove();
      }
    }());
    
    

    public by szmerek modified Sep 6, 2017  418  7  5  0

    OnClick without setting an attribute of the link

    //<div id="dog" >Woow woow</div>
    
    
        (function() {
            document.getElementById("dog").onclick = function() { 
                alert('fuf fuf'); 
            };
        })();																								

    public by tttttttttt modified Aug 30, 2017  234  1  3  0

    ttttttttttttttttt

    tttt
    // ==UserScript==
    // @name         MicroScatter Cheater Script
    // @namespace    http://qsysmine.tk/
    // @version      0.1
    // @description  Press C on microscatter to win
    // @author       qsysmine
    // @match        https://quizlet.com/*/microscatter
    // @grant        none
    // ==/UserScript==
    
    (function() {
        var $ = window.jQuery;
        var cheat = function() {
            var ids = [];
            var checkhasid = function(id) {
                for(var i in ids) {
                    if(ids[i] == id) {
                        return true;
                    }
                }
                return false;
            };
            $('.cell').each(function(index){
    
                if(checkhasid($(this).attr("data-id"))) $('[data-id="' + $(this).attr("data-id") + '"]').trigger("click")
                if(!checkhasid($(this).attr("data-id"))) ids.push($(this).attr("data-id"));
    
            });
        };
        var z = 0;
        $('*').keyup(function(e) {
            if(e.keyCode == 67 && z == 0) {z = 1; cheat();}
        });
    })();
    
    

    public by tttttttttt modified Aug 30, 2017  254  0  3  0

    ttttttttttt

    ttttttttttttttt
    // ==UserScript==
    // @name         MicroScatter Cheater Script
    // @namespace    http://qsysmine.tk/
    // @version      0.1
    // @description  Press C on microscatter to win
    // @author       qsysmine
    // @match        https://quizlet.com/*/microscatter
    // @grant        none
    // ==/UserScript==
    
    (function() {
        var $ = window.jQuery;
        var cheat = function() {
            var ids = [];
            var checkhasid = function(id) {
                for(var i in ids) {
                    if(ids[i] == id) {
                        return true;
                    }
                }
                return false;
            };
            $('.cell').each(function(index){
    
                if(checkhasid($(this).attr("data-id"))) $('[data-id="' + $(this).attr("data-id") + '"]').trigger("click")
                if(!checkhasid($(this).attr("data-id"))) ids.push($(this).attr("data-id"));
    
            });
        };
        var z = 0;
        $('*').keyup(function(e) {
            if(e.keyCode == 67 && z === 0) {z = 1; cheat();}
        });
    })();
    
    

    public by szmerek modified Aug 20, 2017  311  0  4  0

    Remove part of a string before specified character

    //remove string before '&' if want to include character '&' then 'indexOf("&") + 0'
    var str = "black&white";
    str = str.substring(str.indexOf("&") + 1);
    
    //or use regex
    var str = "black&white";
    str = /&(.+)/.exec(str)[1];
    
    // or use .split() and .pop() 
    var str = "black&white";
    str = str.split("&").pop();						
    • Public Snippets
    • Channels Snippets