commit
stringlengths
40
40
subject
stringlengths
1
3.25k
old_file
stringlengths
4
311
new_file
stringlengths
4
311
old_contents
stringlengths
0
26.3k
lang
stringclasses
3 values
proba
float64
0
1
diff
stringlengths
0
7.82k
65be961c47274c0eabcc8f9e303e1cbf5c46fcc3
add controls. more tests.
test/fragment.js
test/fragment.js
function canPlayVideos() { var elem = document.createElement('video'), bool = false; try { bool = !!elem.canPlayType; } catch (e) {} return bool; } jasmine.DEFAULT_TIMEOUT_INTERVAL = 30 * 60 * 1000; describe("", function () { var sources = [ { src: "http://techslides.com/demos/sample-videos/small.webm", type:"video/webm>" }, { src: "http://techslides.com/demos/sample-videos/small.ogv", type:"video/ogg>" }, { src: "http://techslides.com/demos/sample-videos/small.mp4", type:"video/mp4" }, { src: "http://techslides.com/demos/sample-videos/small.3gp", type:"video/3gp" } ]; var listeners = []; function listen(element, type, cb) { element.addEventListener(type, cb); listeners.push({ type: type, element: element, cb: cb }); } var video; beforeEach(function () { video = document.createElement("video"); }); afterEach(function () { video.pause(); video.src = ""; listeners.forEach(function (listener) { listener.element.removeEventListener(listener.type, listener.cb); }); document.body.innerHTML = ""; }); function loadSources(fragment) { sources.forEach(function (source) { var ele = document.createElement("source"); ele.setAttribute("src", source.src + fragment); ele.setAttribute("type", source.type); video.appendChild(ele); }); } it("sanity check", function (done) { expect(canPlayVideos()).toEqual(true); loadSources(""); listen(video, "timeupdate", function (event) { expect(event.target.currentTime).toBeLessThan(3); done(); }); document.body.appendChild(video); video.play(); expect(video.currentTime).toBe(0); }); it("jumps to media fragment automatically", function (done) { expect(canPlayVideos()).toEqual(true); loadSources("#t=4"); listen(video, "timeupdate", function (event) { expect(video.currentTime).toBeGreaterThan(3.9); done(); }); document.body.appendChild(video); video.play(); expect(video.currentTime).toBe(0); }); it("can jump before fragments", function (done) { expect(canPlayVideos()).toEqual(true); loadSources("#t=4"); var firstUpdate = true; listen(video, "timeupdate", function (event) { if (firstUpdate) { video.currentTime = 1; firstUpdate = false; } else { expect(video.currentTime).toBeGreaterThan(0.9); expect(video.currentTime).toBeLessThan(1.5); done(); } }); document.body.appendChild(video); video.play(); expect(video.currentTime).toBe(0); }); });
JavaScript
0
@@ -881,16 +881,56 @@ ideo%22);%0A + video.setAttribute(%22controls%22, %22%22);%0A %7D);%0A%0A @@ -2673,12 +2673,1138 @@ %0A %7D);%0A%0A + it(%22can jump after fragments%22, function (done) %7B%0A expect(canPlayVideos()).toEqual(true);%0A%0A loadSources(%22#t=1,3%22);%0A%0A var firstUpdate = true;%0A%0A listen(video, %22timeupdate%22, function (event) %7B%0A if (firstUpdate) %7B%0A video.currentTime = 4;%0A firstUpdate = false;%0A %7D else %7B%0A expect(video.currentTime).toBeGreaterThan(3.9);%0A expect(video.currentTime).toBeLessThan(4.5);%0A done();%0A %7D%0A %7D);%0A%0A document.body.appendChild(video);%0A video.play();%0A expect(video.currentTime).toBe(0);%0A %7D);%0A%0A it(%22video ended on fragment end%22, function (done) %7B%0A expect(canPlayVideos()).toEqual(true);%0A%0A loadSources(%22#t=1,3%22);%0A%0A var firstUpdate = true;%0A%0A listen(video, %22timeupdate%22, function (event) %7B%0A console.log(video.currentTime);%0A expect(video.currentTime).toBeLessThan(3.5);%0A %7D);%0A%0A listen(video, %22ended%22, function (event) %7B%0A expect(true).toEqual(false);%0A done();%0A %7D);%0A%0A listen(video, %22pause%22, function (event) %7B%0A done();%0A %7D);%0A%0A document.body.appendChild(video);%0A video.play();%0A expect(video.currentTime).toBe(0);%0A %7D);%0A%0A %7D);%0A
385a7c93c7938b34ec134f60322257edff4b3020
Use private variables
Resources/public/js/adapter/fancytree.js
Resources/public/js/adapter/fancytree.js
/** * A tree browser adapter for the Fancytree library. * * @author Wouter J <[email protected]> * @see https://github.com/mar10/fancytree */ var FancytreeAdapter = function (data_url) { if (!window.jQuery || !jQuery.fn.fancytree) { throw 'The FancytreeAdapter requires both jQuery and the FancyTree library.'; } var requestNodeToFancytreeNode = function (requestNode) { var fancytreeNode = { // fixme: remove ugly replacing by just not putting stuff like this in the JSON response title: requestNode.data.replace(' (not editable)', ''), // fixme: also put the current node name in the JSON response, not just the complete path key: requestNode.attr.id.match(/\/([^\/]+)$/)[1] }; // fixme: have more descriptive JSON keys to determine if it has children if (null != requestNode.state) { fancytreeNode.folder = true; } if ('closed' == requestNode.state) { fancytreeNode.lazy = true; } return fancytreeNode; }; return { tree: null, $elem: null, data_url: data_url, bindToElement: function ($elem) { if (!$elem instanceof jQuery) { throw 'FancytreeAdapter can only be adapted to a jQuery object.'; } this.$elem = $elem; var dataUrl = this.data_url; $elem.fancytree({ // the start data (root node + children) source: { url: dataUrl }, // lazy load the children when a node is collapsed lazyLoad: function (event, data) { data.result = { url: dataUrl, data: { root: data.node.getKeyPath() } }; }, // transform the JSON response into a data structure that's supported by FancyTree postProcess: function (event, data) { if (null == data.error) { data.result = [] data.response.forEach(function (node) { var sourceNode = requestNodeToFancytreeNode(node); if (node.children) { sourceNode.children = []; node.children.forEach(function (leaf) { sourceNode.children.push(requestNodeToFancytreeNode(leaf)); }); } data.result.push(sourceNode); }); } else { data.result = { // todo: maybe use a more admin friendly error message in prod? error: 'An error occured while retrieving the nodes: ' + data.error }; } }, // always show the active node activeVisible: true }); this.tree = $elem.fancytree('getTree'); }, bindToInput: function ($input) { // output active node to input field this.$elem.fancytree('option', 'activate', function(event, data) { $input.val(data.node.getKeyPath()); }); // change active node when the value of the input field changed var tree = this.tree; $input.on('change', function (e) { tree.loadKeyPath($(this).val(), function (node, status) { if ('ok' == status) { node.setExpanded(); node.setActive(); } }); }); } }; };
JavaScript
0.000001
@@ -177,18 +177,17 @@ on (data -_u +U rl) %7B%0A @@ -1082,91 +1082,126 @@ %7D;%0A -%0A return %7B + // FancyTree instance %0A - +var tree -: null,%0A $elem: null,%0A data_url: data_url,%0A +;%0A // jQuery instance of the tree output element%0A var $tree;%0A%0A return %7B %0A @@ -1397,67 +1397,21 @@ -this.$elem = $elem;%0A var dataUrl = this.data_url +$tree = $elem ;%0A%0A @@ -1422,20 +1422,20 @@ $ -elem +tree .fancytr @@ -3093,21 +3093,16 @@ -this. tree = $ elem @@ -3097,20 +3097,20 @@ tree = $ -elem +tree .fancytr @@ -3242,18 +3242,13 @@ -this.$elem +$tree .fan
d842c197c774c08816df7b6ab1fc941a4953a317
Fix path in GOL test
test/home/gol.js
test/home/gol.js
// Test the game of life script /* eslint-disable no-console */ const test = require('ava'); const gol = require('../../app/js/home/gol.js'); test('Game of life is properly initialized', (t) => { const g = new gol.Game(15, 15); t.true(g instanceof gol.Game); t.is(g.board.length, 15); t.is(g.board[0].length, 15); }); test('Game of life boardSize works', (t) => { const g = new gol.Game(15, 15); // Check basic boardSize t.deepEqual(g.boardSize, [15, 15]); // Check that boardSize changes when a new row is added g.board.push(new Array(15).fill(false)); t.deepEqual(g.boardSize, [16, 15]); // Check that boardSize changes when a new column is added for (let i = 0; i < g.boardSize[0]; i += 1) { g.board[i].push(false); } t.deepEqual(g.boardSize, [16, 16]); }); test('Game of life logic works', (t) => { // Test game of life with a glider const g = new gol.Game(6, 7); // Create a glider g.turnOn([ [2, 1], [3, 2], [1, 3], [2, 3], [3, 3], ]); // Advance the glider 6 steps g.print(); for (let i = 0; i < 6; i += 1) g.step().print(); t.deepEqual( g.board, [[false, false, false, false, false, false, false], [false, false, false, false, false, false, false], [false, false, false, false, true, false, false], [false, false, false, false, false, true, false], [false, false, false, true, true, true, false], [false, false, false, false, false, false, false]] ); }); test('Game of life helper methods work', (t) => { const g = new gol.Game(2, 2); // test getBlankBoard t.deepEqual(g.getBlankBoard(), [[false, false], [false, false]]); // test getRandomRow t.true(typeof g.getRandomRow() === 'object'); t.is(g.getRandomRow().length, 2); // boardSize is already tested }); test('Game of life manipulation methods work', (t) => { const g = new gol.Game(3, 3); // test turnOn g.turnOn(1, 1); t.deepEqual(g.board, [[false, false, false], [false, true, false], [false, false, false]]); // test turnOff g.turnOff(1, 1); t.deepEqual(g.board, [[false, false, false], [false, false, false], [false, false, false]]); // test clear g.turnOn(1, 1).clear(); t.deepEqual(g.board, [[false, false, false], [false, false, false], [false, false, false]]); // test randomize const board1 = g.randomize().board; const board2 = g.randomize().board; t.notDeepEqual(board1, board2); });
JavaScript
0.000001
@@ -119,18 +119,20 @@ /../app/ -js +main /home/go
905b0488cec446b823f6fc88eaa79aafbbf2f8e4
fix getUserDetails url
dist/backand.min.js
dist/backand.min.js
/* * Angular SDK to use with backand * @version 1.7.2 - 2015-08-02 * @link https://backand.com * @author Itay Herskovits * @license MIT License, http://www.opensource.org/licenses/MIT */ !function(){"use strict";var a=/\?(data|error)=(.+)/,b=a.exec(location.href);if(b&&b[1]&&b[2]){var c={};c[b[1]]=JSON.parse(decodeURI(b[2].replace(/#.*/,""))),window.opener.postMessage(JSON.stringify(c),location.origin)}var d,e,f,g,h,i;angular.module("backand",["ngCookies"]).provider("Backand",function(){function a(a){function b(a,b){var c=l[a],d=b?"up":"in";return"user/socialSign"+d+"?provider="+c.label+"&response_type=token&client_id=self&redirect_uri="+c.url+"&state="}function c(a){if(k.socialAuthWindow.close(),k.socialAuthWindow=null,a.origin===location.origin){var b=JSON.parse(a.data);return b.error?void k.loginPromise.reject({data:b.error.message+" (signing in with "+b.error.provider+")"}):b.data?k.signInWithToken(b.data):void k.loginPromise.reject()}}function j(a){return g.remove(),f.clear(),i({method:"POST",url:e.apiUrl+"/token",headers:{"Content-Type":"application/x-www-form-urlencoded"},transformRequest:function(a){var b=[];return angular.forEach(a,function(a,c){b.push(encodeURIComponent(c)+"="+encodeURIComponent(a))}),b.join("&")},data:a}).success(function(a){angular.isDefined(a)&&null!=a?angular.isDefined(a.access_token)&&(e.token="bearer "+a.access_token,g.set(e.token),f.set(),h.set(a),k.loginPromise.resolve(e.token)):k.loginPromise.reject("token is undefined")}).error(function(a){k.loginPromise.reject(a)}),k.loginPromise.promise}var k=this;k.setAppName=function(a){e.appName=a};var l={github:{name:"github",label:"Github",url:"www.github.com",css:"github",id:1},google:{name:"google",label:"Google",url:"www.google.com",css:"google-plus",id:2},facebook:{name:"facebook",label:"Facebook",url:"www.facebook.com",css:"facebook",id:3}};k.getSocialProviders=function(){return l},k.socialSignIn=function(a){return k.socialAuth(a,!1)},k.socialSignUp=function(a){return k.socialAuth(a,!0)},k.socialAuth=function(d,f){return k.loginPromise=a.defer(),k.socialAuthWindow=window.open(e.apiUrl+"/1/"+b(d,f)+"&appname="+e.appName+"&returnAddress=","id1","left=10, top=10, width=600, height=600"),window.addEventListener("message",c,!1),k.loginPromise.promise},k.signin=function(b,c,d){k.loginPromise=a.defer(),d&&k.setAppName(d);var f={grant_type:"password",username:b,password:c,appname:e.appName};return j(f)},k.signInWithToken=function(a){var b={grant_type:"password",accessToken:a.access_token,appName:e.appName};return j(b)},k.getUserDetails=function(b){var c=a.defer();return b?i({method:"GET",url:e.apiUrl+"/1/account/profile"}).success(function(a){h.set(a),c.resolve(h.get())}):c.resolve(h.get()),c.promise},k.getUsername=function(){var a=d.get(e.userProfileName);return a?a.username:null},k.getUserRole=function(){var a=d.get(e.userProfileName);return a?a.role:null},k.signout=function(){return g.remove(),h.remove(),f.clear(),f.set(),a.when(!0)},k.signup=function(a,b,c,d,f){return i({method:"POST",url:e.apiUrl+"/1/user/signup",headers:{SignUpToken:e.signUpToken},data:{firstName:a,lastName:b,email:c,password:d,confirmPassword:f}})},k.requestResetPassword=function(a,b){return b&&k.setAppName(b),i({method:"POST",url:e.apiUrl+"/1/user/requestResetPassword",data:{appName:e.appName,username:a}})},k.resetPassword=function(a,b){return i({method:"POST",url:e.apiUrl+"/1/user/resetPassword",data:{newPassword:a,resetToken:b}})},k.changePassword=function(a,b){return i({method:"POST",url:e.apiUrl+"/1/user/changePassword",data:{oldPassword:a,newPassword:b}})},k.getToken=function(){return g.get()},k.getTokenName=function(){return e.tokenName},k.getApiUrl=function(){return e.apiUrl}}e={apiUrl:"https://api.backand.com",tokenName:"backand_token",anonymousToken:null,signUpToken:null,isManagingDefaultHeaders:!1,appName:null,userProfileName:"backand_user"},g={get:function(){return d.get(e.tokenName)},set:function(a){d.put(e.tokenName,a)},remove:function(){d.remove(e.tokenName)}},h={get:function(){return d.get(e.userProfileName)},set:function(a){d.put(e.userProfileName,a)},remove:function(){d.remove(e.userProfileName)}},f={set:function(){if(e.isManagingDefaultHeaders){var a=g.get();angular.isDefined(a)&&(i.defaults.headers.common.Authorization=a),e.anonymousToken&&(i.defaults.headers.common.AnonymousToken=e.anonymousToken)}},clear:function(){e.isManagingDefaultHeaders&&(i.defaults.headers.common.Authorization&&delete i.defaults.headers.common.Authorization,i.defaults.headers.common.AnonymousToken&&delete i.defaults.headers.common.AnonymousToken)}},this.getApiUrl=function(){return e.apiUrl},this.setApiUrl=function(a){return e.apiUrl=a,this},this.getTokenName=function(){return e.tokenName},this.setTokenName=function(a){return e.tokenName=a,this},this.setAnonymousToken=function(a){return e.anonymousToken=a,this},this.setSignUpToken=function(a){return e.signUpToken=a,this},this.setAppName=function(a){return e.appName=a,this},this.manageDefaultHeaders=function(a){return void 0==a&&(a=!0),e.isManagingDefaultHeaders=a,this},this.$get=["$q",function(b){return new a(b)}]}).run(["$injector","$location",function(a){a.invoke(["$http","$cookieStore",function(a,b){d=b,i=a}]),f.set()}])}();
JavaScript
0.000078
@@ -2620,17 +2620,19 @@ piUrl+%22/ -1 +api /account @@ -5214,8 +5214,9 @@ )%7D%5D)%7D(); +%0A
6f74159e959fb7b8ed7e90a93a8c46667362c63a
remove logging
test/override.js
test/override.js
require('should'); var _s = require('underscore.string'); var DeDot = require('../dedot.js'); describe("DeDot test:", function () { it("Redefinition should _not_ fail if override is true", function (done) { DeDot.override = true; var obj = { 'some': 'value', 'already': 'set' }; DeDot.str('already.new', 'value', obj); obj.should.eql({ "some": "value", "already": { "new": "value" } }); DeDot.override = false; done(); }); it("Redefinition should _not_ fail if override is true", function (done) { DeDot.override = true; var obj = { 'some': 'value', 'already': 'set' }; DeDot.str('already.new', 'value', obj); DeDot.str('some', 'new_value', obj); obj.should.eql({ "some": "new_value", "already": { "new": "value" } }); DeDot.override = false; done(); }); it("DeDot.object _should_ process non dot notation value with modifier when DeDot.override is true", function (done) { DeDot.override = true; var row = { 'title': 'my page', 'slug': 'My Page' }; var mods = { "title": _s.titleize, "slug": _s.slugify, }; DeDot.object(row, mods); console.log(row); row.should.eql({ "title": "My Page", "slug": "my-page" }); DeDot.override = false; done(); }); });
JavaScript
0.000001
@@ -1226,30 +1226,8 @@ ds); -%0A console.log(row); %0A%0A
9f984def17031bb943b8a753a18c9b517d3dee10
Switch copy name back to 'n'
app/itemIdCopy.js
app/itemIdCopy.js
const logger = require('logger.js'); const $ = jQuery = require('jquery'); require('jquery-toast-plugin'); let mousePositionX; let mousePositionY; $("body").mousemove(function(event) { // When scrolling, need to take viewport in to account mousePositionX = event.pageX - window.pageXOffset; mousePositionY = event.pageY - window.pageYOffset; }); function registerListeners() { $('[data-fate-serial]').not('[data-fate-copy-init]').each(function() { $(this).attr('data-fate-copy-init', true); Mousetrap.bind('s', function() { const $jqElement = $(document.elementFromPoint(mousePositionX, mousePositionY)); let $itemElement = $jqElement; if (!$itemElement.is('[data-fate-serial]')) { $itemElement = $($jqElement.parents('[data-fate-serial]')[0]); } const serialNumber = $itemElement.attr('data-fate-serial'); const weaponName = $itemElement.attr('data-fate-weapon-name'); const armorName = $itemElement.attr('data-fate-armor-name'); const itemName = (weaponName === undefined) ? (armorName) : (weaponName); copyToClipboard(serialNumber); $.toast({ text: '<span style="font-size:16px;"><strong>'+itemName+'</strong> serial number copied to clipboard</span>', }); }, 'keypress'); Mousetrap.bind('m', function() { const $jqElement = $(document.elementFromPoint(mousePositionX, mousePositionY)); let $itemElement = $jqElement; if (!$itemElement.is('[data-fate-serial]')) { $itemElement = $($jqElement.parents('[data-fate-serial]')[0]); } const weaponName = $itemElement.attr('data-fate-weapon-name'); const armorName = $itemElement.attr('data-fate-armor-name'); const itemName = (weaponName === undefined) ? (armorName) : (weaponName); copyToClipboard(itemName); $.toast({ text: '<span style="font-size:16px;"><strong>'+itemName+'</strong> copied to clipboard</span>', }); }, 'keypress'); }); } /* I'd prefer to use clipboard-js, but that only supports click-initiated events and they won't be implementing other event sources. See this Issue for more: https://github.com/zenorocha/clipboard.js/issues/370 That being the case, will implement it ourselves using the guide here: https://hackernoon.com/copying-text-to-clipboard-with-javascript-df4d4988697f */ function copyToClipboard(str) { const el = document.createElement('textarea'); // Create a <textarea> element el.value = str; // Set its value to the string that you want copied el.setAttribute('readonly', ''); // Make it readonly to be tamper-proof el.style.position = 'absolute'; el.style.left = '-9999px'; // Move outside the screen to make it invisible document.body.appendChild(el); // Append the <textarea> element to the HTML document const selected = document.getSelection().rangeCount > 0 // Check if there is any content selected previously ? document.getSelection().getRangeAt(0) // Store selection if found : false; // Mark as false to know no selection existed before el.select(); // Select the <textarea> content document.execCommand('copy'); // Copy - only works as a result of a user action (e.g. click events) document.body.removeChild(el); // Remove the <textarea> element if (selected) { // If a selection existed before copying document.getSelection().removeAllRanges(); // Unselect everything on the HTML document document.getSelection().addRange(selected); // Restore the original selection } } fateBus.subscribe(module, 'fate.refresh', function() { // logger.log('itemIdCopy.js: Registering copy on all weapons'); registerListeners(); });
JavaScript
0.000025
@@ -1297,17 +1297,17 @@ p.bind(' -m +n ', funct
546b58b359a45d3f9dc831026cc07c1973d6a332
Allow url-loader to embed all sort of images
config/webpack-base.js
config/webpack-base.js
const path = require('path'); const paths = require('../config/paths'); // Webpack plugins const StyleLintPlugin = require('stylelint-webpack-plugin'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); module.exports = { entry: paths.indexJs, output: { // Needs to be an absolute path path: paths.build, filename: 'bundle.js', // necessary for HMR to know where to load the hot update chunks publicPath: '/' }, // Loaders module: { rules: [ // Lint all JS files using eslint { test: /\.js$/, enforce: 'pre', exclude: /node_modules/, use: [{ loader: 'eslint-loader', options: { // Point ESLint to our predefined config file (.eslintrc) configFile: path.join(__dirname, './eslint.json'), useEslintrc: false, emitWarning: true, emitError: true, failOnWarning: false, failOnError: true } }] }, // Parse all ES6/JSX files and transpile them to plain old JS { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/, query: { presets: [ // webpack understands the native import syntax, and uses it for tree shaking ['es2015', { modules: false }], // Specifies what level of language features to activate. // Stage 2 is "draft", 4 is finished, 0 is strawman. // See https://tc39.github.io/process-document/ 'stage-2', // Transpile React components to JavaScript 'react' ] } }, // Allow importing CSS modules and extract them to a .css file { test: /\.css$/, use: ExtractTextPlugin.extract({ fallback: 'style-loader', use: [ { loader: 'css-loader', options: { modules: true, importLoaders: 1, localIdentName: '[path][name]__[local]--[hash:base64:5]' } }, { loader: 'postcss-loader', options: { ident: 'postcss', // https://webpack.js.org/guides/migrating/#complex-options plugins: () => [ require('postcss-modules-values'), require('autoprefixer'), require('precss') ] } } ] }) }, // Allow importing SVG files { test: /\.svg$/, use: 'url-loader?limit=10000&mimetype=image/svg+xml' }, // Allow importing PNG files { test: /\.png$/, use: 'url-loader?mimetype=image/png' } ] }, plugins: [ // Lint CSS files using Stylelint new StyleLintPlugin({ context: paths.source, files: '{,**/}*.css', configFile: path.join(__dirname, './stylelint.json') }), // ExtractTextPlugin new ExtractTextPlugin('bundle.css') ], // Avoid complex relative routes when importing modules resolve: { modules: [ paths.source, 'node_modules' ] } };
JavaScript
0
@@ -2553,49 +2553,149 @@ low -importing SVG files%0A %7B%0A test: +embedding assets smaller than specified limit in bytes as data URLs to avoid requests.%0A %7B%0A test: %5B/%5C.gif$/, /%5C.jpe?g$/, /%5C.png$/, /%5C. @@ -2699,16 +2699,17 @@ /%5C.svg$/ +%5D ,%0A @@ -2702,35 +2702,38 @@ svg$/%5D,%0A -use +loader : 'url-loader?li @@ -2733,166 +2733,62 @@ ader -?limit=10000&mimetype=image/svg+xml'%0A %7D,%0A%0A // Allow importing PNG files +',%0A options: %7B %0A -%7B%0A - test: /%5C.png$/,%0A use: 'url-loader?mimetype=image/png' +limit: 10000%0A %7D %0A
781c31452dfbf77f82007b8046d8327a8c285551
use new context API: withStripes()
Pluggable.js
Pluggable.js
import React from 'react'; import PropTypes from 'prop-types'; import { modules } from 'stripes-config'; // eslint-disable-line import/no-unresolved const Pluggable = (props, context) => { const plugins = modules.plugin || []; let best; const wanted = context.stripes.plugins[props.type]; // "@@" is a special case of explicitly chosen "no plugin" if (!wanted || wanted !== '@@') { for (const name of Object.keys(plugins)) { const m = plugins[name]; if (m.pluginType === props.type) { best = m; if (m.module === wanted) break; } } if (best) { const Child = context.stripes.connect(best.getModule()); return <Child {...props} />; } } if (!props.children) return null; if (props.children.length) { console.error(`<Pluggable type="${props.type}"> has ${props.children.length} children, can only return one`); } return props.children; }; Pluggable.contextTypes = { stripes: PropTypes.shape({ hasPerm: PropTypes.func.isRequired, }).isRequired, }; Pluggable.propTypes = { children: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.node), PropTypes.node, ]), type: PropTypes.string.isRequired, }; export default Pluggable;
JavaScript
0.000001
@@ -56,16 +56,86 @@ types';%0A +import %7B withStripes %7D from '@folio/stripes-core/src/StripesContext';%0A import %7B @@ -194,29 +194,8 @@ line - import/no-unresolved %0A%0Aco @@ -220,17 +220,8 @@ rops -, context ) =%3E @@ -289,31 +289,29 @@ st wanted = -context +props .stripes.plu @@ -653,23 +653,21 @@ Child = -context +props .stripes @@ -958,125 +958,8 @@ %7D;%0A%0A -Pluggable.contextTypes = %7B%0A stripes: PropTypes.shape(%7B%0A hasPerm: PropTypes.func.isRequired,%0A %7D).isRequired,%0A%7D;%0A%0A Plug @@ -1077,16 +1077,56 @@ ,%0A %5D),%0A + stripes: PropTypes.object.isRequired,%0A type: @@ -1173,16 +1173,28 @@ default +withStripes( Pluggabl @@ -1194,10 +1194,11 @@ luggable +) ;%0A
40040353cc11aef7a853eef9dd7d3906528d7da2
Update Pong.js
Pong/Pong.js
Pong/Pong.js
var BY, BX, T, BDY, BDX; var Pb, Bot; var PtsA = 0, PtsB = 0; function setup() { background(0); createCanvas(1080, 720); BY = height/2; BX = width/2; BDY = random(-7, 7); BDX = 2; T = random(1, 10); Pb = height/2-15; } function draw() { background(0); textSize(20); fill(255); text("©Javi", width-55, height-10); //puntos textSize(100); fill(255); text(PtsA, width*0.25, height/2); text(PtsB, width*0.75, height/2); //jugadores fill(255); rect(width-15, mouseY, 15, 60); rect(0, Pb, 15, 60); //linea centro rect(width/2-5, 0, 10, height); //pelota fill(150, 0, 0); ellipse(BX, BY, 50, 50); //bot if (BX < width/2 && Pb > width-60 && Pb < 0) { if (Bot == 0) { Pb = BY - 30; } else { if (Pb > BY) { Pb = Pb - T; } if (Pb < BY) { Pb = Pb + T; } if (Pb < BY + 30 && Pb > BY -30) { Bot = 0; } } } //direccion pelota if (BDX == 1) { BX = BX - 3; } if (BDX == 2) { BX = BX +3; } //pelota arriba/abajo BY = BY - BDY; //choque if (BY < 25 || BY > height-25) { BDY = BDY * -1; } if (BX > width-25 && BY < mouseY + 60 && BY > mouseY) { BDX = 1; BDY = random(-7, 7); T = T -1 Bot = 1; } if (BX < 25 && BY < Pb + 60 && BY > Pb) { BDX = 2; T = T - 1; BDY = random(-7, 7); Bot = 1; } //reset if (BX == 0) { PtsB = PtsB + 1; BY = height/2; BX = width/2; BDY = random(-7, 7); BDX = 2; T = random(1, 10); if (Pb < 1) { Pb = Pb + 1; } if (Pb > width) { Pb = Pb - 1; } } if (BX == width) { PtsA = PtsA + 1; BY = height/2; BX = width/2; BDY = random(-7, 7); BDX = 2; T = random(1, 10); if (Pb < 1) { Pb = Pb + 5; } if (Pb > width - 60) { Pb = Pb - 5; } } }
JavaScript
0.000001
@@ -670,17 +670,17 @@ 2 && Pb -%3E +%3C width-6 @@ -687,17 +687,17 @@ 0 && Pb -%3C +%3E 0) %7B%0A
7962e1a571a31ede0e6b04ed820e548676c300d7
Fix a bug in Node.js of WinOS
tests/specs/module/cache/main.js
tests/specs/module/cache/main.js
global.cache_g = 0 // For Node.js var _require = typeof require === 'function' ? require : { cache: {} } define(function(require) { var test = require('../../../test') var a = require('./a') test.assert(a.name === 'a', a.name) test.assert(cache_g === 1, 'cache_g = ' + cache_g) var cache = find('module/cache/a.js') test.assert(cache.length === 1, 'cache.length = ' + cache.length) var m = cache[0] test.assert(m === require.resolve('./a'), m) var url = require.resolve('./a') test.assert(url.indexOf('a.js') > 0, url) // Delete './a' from cache seajs.cache[url].destroy() if (_require && typeof process !== 'undefined' && process.cwd().indexOf('node.exe') > 0) { url = url.replace(/\//g, '\\') } delete _require.cache[url] // Load './a' again require.async('./a', function(a) { test.assert(cache_g === 2, 'cache_g = ' + cache_g) test.assert(a.name === 'a', a.name) // Load from cache require.async('./a', function(a) { test.assert(cache_g === 2, 'cache_g = ' + cache_g) test.assert(a.name === 'a', a.name) test.next() }) }) function find(filename) { var cache = seajs.cache var ret = [] for (var uri in cache) { if (uri.indexOf(filename) > 0) { ret.push(uri) } } return ret } });
JavaScript
0.000031
@@ -674,13 +674,16 @@ ess. -cwd() +execPath .ind
9ddbaca699a7788de5d6f10e46a4cb490034822c
Remove path from io.connect()
game/src/main.js
game/src/main.js
(function(){ 'use strict'; var game = new Phaser.Game(1056, 700, Phaser.AUTO, 'game-container'); // Connect to the socket.io server and add the connection to the current game for future reference: game.state.game.socket = io.connect('http://localhost:3000'); game.state.add('Boot', require('./states/boot')); game.state.add('Preloader', require('./states/preloader')); game.state.add('Menu', require('./states/menu')); game.state.add('Connect', require('./states/connect')); game.state.add('Game', require('./states/game').constructor); game.state.add('Done', require('./states/done')); game.state.start('Boot'); }());
JavaScript
0.000001
@@ -232,31 +232,8 @@ ect( -'http://localhost:3000' );%0A%0A
3a5de0c7f5c6ad58ffee0c07e8e8bb72382598a3
Add testRef assertion to innerRef test
src/test/basic.test.js
src/test/basic.test.js
// @flow import React, { Component } from 'react' import expect from 'expect' import { shallow, mount } from 'enzyme' import jsdom from 'mocha-jsdom' import styleSheet from '../models/StyleSheet' import { resetStyled, expectCSSMatches } from './utils' let styled describe('basic', () => { /** * Make sure the setup is the same for every test */ beforeEach(() => { styled = resetStyled() }) it('should not throw an error when called', () => { styled.div`` }) it('should inject a stylesheet when a component is created', () => { const Comp = styled.div`` shallow(<Comp />) expect(styleSheet.injected).toBe(true) }) it('should generate only component class by default', () => { styled.div`` expectCSSMatches('.sc-a {}') }) it('should generate only component class even if rendered if no styles are passed', () => { const Comp = styled.div`` shallow(<Comp />) expectCSSMatches('.sc-a {}') }) it('should inject styles', () => { const Comp = styled.div` color: blue; ` shallow(<Comp />) expectCSSMatches('.sc-a { } .b { color: blue; }') }) it('should inject only once for a styled component, no matter how often it\'s mounted', () => { const Comp = styled.div` color: blue; ` shallow(<Comp />) shallow(<Comp />) expectCSSMatches('.sc-a {} .b { color: blue; }') }) describe('jsdom tests', () => { jsdom() let Comp let WrapperComp let wrapper beforeEach(() => { Comp = styled.div`` WrapperComp = class extends Component { testRef: any; render() { return <Comp innerRef={(comp) => { this.testRef = comp }} /> } } wrapper = mount(<WrapperComp />) }) it('should pass ref to the component', () => { // $FlowFixMe expect(wrapper.node.testRef).toExist() }) it('should not pass innerRef to the component', () => { // $FlowFixMe expect(wrapper.node.ref).toNotExist() }) it('should not leak the innerRef prop to the wrapped child', () => { const StyledComp = styled.div`` class WrappedStyledComp extends React.Component { render() { return ( <StyledComp {...this.props} /> ) } } const ChildComp = styled(WrappedStyledComp)`` const WrapperComp = class extends Component { testRef: any; render() { return <ChildComp innerRef={(comp) => { this.testRef = comp }} /> } } const wrapper = mount(<WrapperComp />) // $FlowFixMe expect(wrapper.node.testRef).toExist() expect(wrapper.find('WrappedStyledComp').prop('innerRef')).toNotExist() }) }) })
JavaScript
0
@@ -2095,68 +2095,27 @@ c -onst StyledComp = styled.div%60%60%0A class WrappedStyledComp +lass InnerComponent ext @@ -2123,14 +2123,8 @@ nds -React. Comp @@ -2171,22 +2171,21 @@ urn -(%0A +null%0A %3CSty @@ -2184,140 +2184,93 @@ -%3CStyledComp %7B...this.props%7D /%3E%0A )%0A %7D%0A %7D%0A const ChildComp = styled(WrappedStyledComp +%7D%0A %7D%0A%0A const OuterComponent = styled(InnerComponent )%60%60%0A +%0A c -onst +lass Wrapper Comp @@ -2261,36 +2261,24 @@ lass Wrapper -Comp = class extends Com @@ -2300,32 +2300,33 @@ testRef: any;%0A +%0A render() @@ -2350,17 +2350,22 @@ rn %3C -ChildComp +OuterComponent inn @@ -2423,24 +2423,25 @@ %7D%0A %7D%0A +%0A const @@ -2464,23 +2464,85 @@ %3CWrapper -Comp /%3E + /%3E)%0A const innerComponent = wrapper.find(InnerComponent).first( )%0A%0A @@ -2597,62 +2597,59 @@ ).to -Exist()%0A expect(wrapper.find('WrappedStyledComp') +Be(innerComponent.node)%0A expect(innerComponent .pro
9fbac29486954da738c88933ab605ebc64dec690
Correct mocks placement in gql-server
src/test/gql-server.js
src/test/gql-server.js
import graphqlHTTP from "express-graphql" import express from "express" import bodyParser from "body-parser" import { makeExecutableSchema, addMockFunctionsToSchema } from "graphql-tools" export const invokeError = status => (req, res, next) => { const err = new Error() err.status = status next(err) } const exampleSchema = ` type Query { greeting: String }` export const gqlServer = ({ schema = exampleSchema, mocks = {}, middleware = [], }) => { const app = express() const execSchema = makeExecutableSchema({ typeDefs: schema, mocks, }) addMockFunctionsToSchema({ schema: execSchema }) app.use( "/", bodyParser.json(), ...middleware, graphqlHTTP({ schema: execSchema, graphiql: false, }) ) return app } export const app = (...middleware) => gqlServer({ middleware })
JavaScript
0
@@ -559,19 +559,8 @@ ma,%0A - mocks,%0A %7D) @@ -607,16 +607,23 @@ ecSchema +, mocks %7D)%0A ap
017dcb03b86233b32aebefdcc9dff7bb8877b15f
Remove unused code.
src/test/index-spec.js
src/test/index-spec.js
import assert from 'assert'; describe('tests run', function() { it('should', function() { assert.equal(1, 1); }); }); /** x get out all paths out of the JSON x group the katas - sort the kata groups (somehow???) - generate the tddbin link object */ describe('convert github data', function() { it('to a list of kata paths', function() { const githubJson = { items: [ {path: "path1"}, {path: "path2"}, {path: "path3"} ] }; assert.deepEqual(getPathList(githubJson), ['path1', 'path2', 'path3']); }); }); const getPathList = (githubJson) => { return githubJson.items.map((item) => item.path); }; describe('kata groups, from a list of paths', function() { describe('use the last directory as the group name', function() { describe('for one group', function() { var groupName = 'group1'; const inGroup1 = `dir/${groupName}/file.js`; const alsoInGroup1 = `dir/${groupName}/file1.js`; it('one path', () => { const expected = {[groupName]: [inGroup1]}; assert.deepEqual(toKataGroups([inGroup1]), expected) }); it('for two paths', () => { const expected = {[groupName]: [inGroup1, alsoInGroup1]}; assert.deepEqual(toKataGroups([inGroup1, alsoInGroup1]), expected) }); }); describe('for two groups', function() { it('two paths each', () => { const group1Name = 'groupA'; const group2Name = 'groupB'; const paths1 = [`dir/${group1Name}/file.js`, `dir/${group1Name}/file1.js`]; const paths2 = [`dir/${group2Name}/file2.js`, `dir/${group2Name}/file3.js`]; const expected = { [group1Name]: paths1, [group2Name]: paths2 }; assert.deepEqual(toKataGroups([...paths1, ...paths2]), expected) }); }); }); }); const toKataGroups = (paths) => { let groups = {}; paths.forEach((path) => { const groupName = path.split('/').reverse()[1]; if (!groups[groupName]) { groups[groupName] = []; } groups[groupName].push(path); }); return groups; }; describe('generate the kata link from a path', function() { it('do it', function() { const path = 'katas/es6/language/template-strings/basics.js'; const link = { text: 'basics', url: 'http://tddbin.com/#?kata=es6/language/template-strings/basics' }; assert.deepEqual(pathToLink(path), link); }); }); const pathToLink = (path) => { const kata = path.replace(/^katas\//, '').replace(/\.js$/, ''); const text = kata.split('/').reverse()[0]; return { text: text, url: `http://tddbin.com/#?kata=${kata}` }; };
JavaScript
0
@@ -27,106 +27,8 @@ ';%0A%0A -describe('tests run', function() %7B%0A it('should', function() %7B%0A assert.equal(1, 1);%0A %7D);%0A%7D);%0A%0A /**%0A @@ -121,17 +121,17 @@ ow???)%0A -- +x generat
f17f82885d8bb38403f5c155c1733e7d399bb2b6
insert trackingId
gatsby-config.js
gatsby-config.js
module.exports = { siteMetadata: { title: 'Medienformatik Richard Sternagel', domain: 'rsternagel.de' }, plugins: [ { resolve: `gatsby-source-filesystem`, options: { path: `${__dirname}/src/pages`, name: 'pages', }, }, `gatsby-transformer-remark`, `gatsby-transformer-sharp`, { resolve: `gatsby-typegen-remark`, options: { plugins: [ { resolve: `gatsby-typegen-remark-responsive-image`, options: { maxWidth: 590, }, }, { resolve: `gatsby-typegen-remark-responsive-iframe`, options: { wrapperStyle: `margin-bottom: 1.0725rem`, }, }, 'gatsby-typegen-remark-prismjs', 'gatsby-typegen-remark-copy-linked-files', 'gatsby-typegen-remark-smartypants', ], }, }, `gatsby-typegen-filesystem`, `gatsby-typegen-sharp`, `gatsby-plugin-sharp`, { resolve: `gatsby-plugin-google-analytics`, options: { //trackingId: `ADD YOUR TRACKING ID HERE`, }, }, `gatsby-plugin-offline`, ], }
JavaScript
0
@@ -1095,10 +1095,8 @@ -// trac @@ -1107,35 +1107,23 @@ Id: -%60ADD YOUR TRACKING ID HERE%60 +'UA-22466234-1' ,%0A
07a76e878734d2546bdc585173da9d0e42fb89fa
update gatsby-config
gatsby-config.js
gatsby-config.js
const { version, homepage, repository } = require('./package.json'); module.exports = { plugins: [ { resolve: '@antv/gatsby-theme-antv', options: { GATrackingId: 'UA-148148901-4', }, }, ], // Customize your site metadata: siteMetadata: { title: 'G6', description: 'A collection of charts made with the Grammar of Graphics', siteUrl: homepage, githubUrl: repository.url, versions: { [version]: 'https://g6.antv.vision', '3.2.x': 'https://g6-v3-2.antv.vision', }, navs: [ { slug: 'docs/manual/introduction', title: { zh: '使用文档', en: 'Manual', }, }, { slug: 'docs/api/Graph', title: { zh: 'API 文档', en: 'API', }, }, { slug: 'examples', title: { zh: '图表示例', en: 'Examples', }, }, ], docs: [ { slug: 'manual/FAQ', title: { zh: 'FAQ', en: 'FAQ', }, order: 2, }, { slug: 'manual/tutorial', title: { zh: '入门教程', en: 'Tutorial', }, order: 3, }, { slug: 'manual/middle', title: { zh: '核心概念', en: 'Middle', }, order: 4, }, { slug: 'manual/middle/states', title: { zh: '交互与事件', en: 'Behavior & Event', }, order: 4, }, { slug: 'manual/middle/elements', title: { zh: '节点/边/Combo', en: 'Graph Elements', }, }, { slug: 'manual/middle/elements/nodes', title: { zh: '内置节点', en: 'Built-in Node', }, order: 1, }, { slug: 'manual/middle/elements/edges', title: { zh: '内置边', en: 'Built-in Edge', }, order: 2, }, { slug: 'manual/middle/elements/combos', title: { zh: '内置 Combo', en: 'Built-in Combo', }, order: 3, }, { slug: 'manual/advanced', title: { zh: '高级指引', en: 'Advanced', }, order: 5, }, { slug: 'manual/advanced/keyconcept', title: { zh: '概念解释', en: 'Concepts', }, order: 0, }, { slug: 'manual/advanced/theory', title: { zh: '深度原理解析', en: 'Theory Blog', }, order: 1, }, { slug: 'api/nodeEdge', title: { zh: '节点/边/Combo', en: 'Node & Edge & Combo', }, order: 3, }, { slug: 'api/layout', title: { zh: 'Layout', en: 'Layout', }, order: 4, }, ], examples: [ { slug: 'tree', icon: 'tree', // 图标名可以去 https://antv.alipay.com/zh-cn/g2/3.x/demo/index.html 打开控制台查看图标类名 title: { zh: '树图', en: 'Tree Graph', }, }, { slug: 'net', icon: 'net', title: { zh: '一般图', en: 'General Graph', }, }, { slug: 'graphql', icon: 'graphql', title: { zh: '其他表达形式', en: 'Net Charts', }, }, { slug: 'item', icon: 'shape', title: { zh: '元素', en: 'Item', }, }, { slug: 'interaction', icon: 'interaction', title: { zh: '交互', en: 'Interaction', }, }, { slug: 'scatter', icon: 'scatter', title: { zh: '动画', en: 'Animation', }, }, { slug: 'tool', icon: 'tool', title: { zh: '组件', en: 'Component', }, }, { slug: 'case', icon: 'case', title: { zh: '复杂案例', en: 'Case', }, }, ], docsearchOptions: { apiKey: '9d1cd586972bb492b7b41b13a949ef30', indexName: 'antv_g6', }, }, };
JavaScript
0.000001
@@ -216,16 +216,62 @@ %0A %7D,%0A + '@babel/plugin-proposal-class-properties'%0A %5D,%0A /
0a5559f19c21f456704d64411a813ebbb15b7936
Fix location to savegraph.html
app/scripts/edit.js
app/scripts/edit.js
/* jshint devel:true */ /* global ace, cytoscape, saveAs, require */ (function(){'use strict'; var editor; var collector = require('./collectdata'); var graph; var graphPane; var graphStyleP = $.ajax({ url: 'styles/main.cycss', type: 'GET', dataType: 'text' }); editor = ace.edit('jsoneditor'); editor.setTheme('ace/theme/tomorrow_night_eighties'); editor.getSession().setMode('ace/mode/json'); editor.setOption('maxLines', 60); editor.setOption('minLines', 40); editor.getSession().on('changeAnnotation', function() { var annotations = editor.getSession().getAnnotations(); $('#statusbar').toggleClass('failure', annotations.length !== 0); if (annotations.length === 0) { var message = editor.getSession().getLength() < 2 && editor.getSession().getLine(0).length === 0 ? 'No content' : 'Valid'; $('div.status-message').text(message); } else { var firstAnnotation = annotations[0]; $('div.status-message').text(firstAnnotation.text + ' at '+ firstAnnotation.row + ':'+ firstAnnotation.column); } }); var StatusBar = ace.require('ace/ext/statusbar').StatusBar; // create a simple selection status indicator new StatusBar(editor, document.getElementById('statusbar')); editor.commands.addCommand({ name: 'showKeyboardShortcuts', bindKey: {win: 'Ctrl-Alt-h', mac: 'Command-Alt-h'}, exec: function(editor) { ace.config.loadModule('ace/ext/keybinding_menu', function(module) { module.init(editor); editor.showKeyboardShortcuts(); }); } }); var loadTemplate = function(file){ var reader = new FileReader(); reader.onload = function () { var data = reader.result; if(data) { editor.setValue(data); editor.navigateTo(0, 0); } editor.resize(); }; reader.readAsText(file); }; var showCyGraph = function() { var data; try { data = collector.collectCyData(JSON.parse(editor.getValue())); } catch (e) { data = {}; } console.log(data); if (!graphPane) { graphPane = $('div.graph_overlay'); } graph = cytoscape({ container: document.getElementById('graph_area'), elements: data, style: graphStyleP, layout: { name: 'cose', padding: 5 } }); graphPane.fadeIn(300); }; var getTemplateDescription = function() { var description = 'template'; try { description = JSON.parse(editor.getValue(editor.getValue())).Description; } catch (e) {} return description; }; var saveImage = function() { var saveWindow = window.open('/savegraph.html'); saveWindow.onload = function() { saveWindow.document.getElementById('graphPNG').src = graph.png(); }; }; var saveTemplate = function() { var prettyDoc = JSON.stringify(JSON.parse(editor.getValue()), null, 2); var blob = new Blob([prettyDoc], {type: 'text/plain;charset=utf-8'}); saveAs(blob, getTemplateDescription() + '.json'); }; var mainRow = document.getElementById('cfeditor'); mainRow.addEventListener('dragover', function(evt) { evt.stopPropagation(); evt.preventDefault(); evt.dataTransfer.dropEffect = 'copy'; }, false); mainRow.addEventListener('drop', function(evt) { evt.stopPropagation(); evt.preventDefault(); loadTemplate(evt.dataTransfer.files[0]); }, false); $('#open_template').change(function(event){ loadTemplate(event.target.files[0]); }); $('#save_template').click(function(event){ event.preventDefault(); saveTemplate(); return false;}); $('#save_graph').click(function(event){ event.preventDefault(); saveImage(); return false;}); $('#show_graph').click(function(event){ event.preventDefault(); showCyGraph(); return false;}); $('#close_graph').click(function(event){ event.preventDefault(); graphPane.fadeOut(500); return false;}); $('#graph_layout').change(function() { graph.layout( { 'name': $('#graph_layout').val() }); }); })();
JavaScript
0.000001
@@ -2625,17 +2625,16 @@ w.open(' -/ savegrap
da5a1ea6335317d8b82e1ff707c60552ecb988a0
Allow data to be sent back in AJAX response
controllers/helpers.js
controllers/helpers.js
exports.toObjectId = function (str) { var ObjectId = (require('mongoose').Types.ObjectId); return new ObjectId(str); }; exports.respondToAjax = function (res) { return function (err) { var error = null; if (err) { error = err; } res.json({ error: error, }); } };
JavaScript
0
@@ -183,24 +183,30 @@ unction (err +, data ) %7B%0A @@ -322,16 +322,40 @@ error,%0A + data: data,%0A
9fd5c00f9a3ea3934ac4921c40990b3ccc56dcb5
fix the error in autocomplete.js
portality/static/js/autocomplete.js
portality/static/js/autocomplete.js
function autocomplete(selector, doc_field, doc_type, mininput, include_input, allow_clear) { var doc_type = doc_type || "journal"; var mininput = mininput === undefined ? 3 : mininput; var include_input = include_input === undefined ? true : include_input; var allow_clear = allow_clear === undefined ? true : allow_clear; var ajax = { url: current_scheme + "//" + current_domain + "/autocomplete/" + doc_type + "/" + doc_ffunction autocompleteield, dataType: 'json', data: function (term, page) { return { q: term }; }, results: function (data, page) { return { results: data["suggestions"] }; } }; var csc = function(term) {return {"id":term, "text": term};}; var initSel = function (element, callback) { var data = {id: element.val(), text: element.val()}; callback(data); }; if (include_input) { // apply the create search choice $(selector).select2({ minimumInputLength: mininput, ajax: ajax, createSearchChoice: csc, initSelection : initSel, placeholder: "Choose a value", allowClear: allow_clear }); } else { // go without the create search choice option $(selector).select2({ minimumInputLength: mininput, ajax: ajax, initSelection : initSel, placeholder: "Choose a value", allowClear: allow_clear }); } }
JavaScript
0.998523
@@ -450,37 +450,16 @@ + doc_f -function autocomplete ield,%0A
c18a8ff286ed7ea515ca8e5527d525f8860d7410
fix bug
src/toaster/Toaster.js
src/toaster/Toaster.js
import React from 'react'; import cx from 'classnames'; import ReactTransitionGroup from 'react/lib/ReactTransitionGroup'; import cloneWithProps from 'react/lib/cloneWithProps'; import { warn } from '../utils/log'; import TransitionWrapper from '../transition-wrapper/TransitionWrapper'; /** * ### Renders and animates toasts (children) inline or in a portal */ export default class Toaster extends React.Component { static propTypes = { /** * list of toasts (any node with a unique key) */ children: React.PropTypes.node.isRequired, /** * id of the element you want to render the `Toaster` in */ attachTo: React.PropTypes.string, /** * custom settings for `ReactTransitionGroup` */ transitionGroup: React.PropTypes.object, /** * object with style for each transition event (used by `TransitionWrapper`) */ transitionStyles: React.PropTypes.object, /** * duration of enter transition in milliseconds (used by `TransitionWrapper`) */ transitionEnterTimeout: React.PropTypes.number.isRequired, /** * duration of leave transition in milliseconds (used by `TransitionWrapper`) */ transitionLeaveTimeout: React.PropTypes.number.isRequired, id: React.PropTypes.string, className: React.PropTypes.string, style: React.PropTypes.object } static defaultProps = { transitionGroup: {} } componentWillMount() { this.appendToaster(); this.renderToaster(); } componentDidMount() { const node = this.props.attachTo ? this.toaster : this.getDOMNode().parentNode; const { position } = window.getComputedStyle(node); if (position !== 'relative' && position !== 'absolute') { warn(['Toaster\'s parent node should have "position: relative/absolute"', node]); } } componentWillUnmount() { this.removeToaster(); } getTranslationStyle(i) { return { transform: `translateY(${100 * i}%)`, position: 'absolute', top: 0, right: 0 }; } getToasts = () => { const { children, transitionStyles, transitionEnterTimeout, transitionLeaveTimeout } = this.props; return React.Children.map(children, (el, i) => { return ( <TransitionWrapper {...{ transitionStyles, transitionEnterTimeout, transitionLeaveTimeout }} style={this.getTranslationStyle(i)} key={el.key} > {cloneWithProps(el, { uniqueKey: el.key })} </TransitionWrapper> ); }); } appendToaster = () => { if (this.props.attachTo) { this.toaster = document.getElementById(this.props.attachTo); } } removeToaster = () => { if (this.toaster && this.props.attachTo) { this.toaster.innerHTML = ''; // stupid?? } } getToaster = () => { const { style: styleProp, id, className } = this.props; const style = { position: 'absolute', right: 0, top: 0, width: 0, height: 0, ...styleProp }; return ( <div className={cx('toaster', className)} {...{ style, id }}> <ReactTransitionGroup {...this.props.transitionGroup}> {this.getToasts()} </ReactTransitionGroup> </div> ); } renderToaster = () => { if (this.props.attachTo) { React.render(this.getToaster(), this.toaster); } } render() { if (this.props.attachTo) { return null; } else { return this.getToaster(); } } componentDidUpdate() { this.renderToaster(); } componentWillReceiveProps(nextProps) { if (this.props.attachTo !== nextProps.attachTo) { warn('You can\'t change "attachTo" prop after the first render!'); } } }
JavaScript
0.000001
@@ -1571,24 +1571,26 @@ r : -this.get +React.find DOMNode( ).pa @@ -1585,16 +1585,20 @@ DOMNode( +this ).parent
5a42eac8e53cacdb56c5610238dd5167b966f87f
Remove unnecessary declarations
tests/unit/models/custom-test.js
tests/unit/models/custom-test.js
import DS from 'ember-data'; import Ember from 'ember'; import { test, moduleForModel } from 'ember-qunit'; import startApp from '../../helpers/start-app'; import ApplicationSerializer from 'prototype-ember-cli-application/serializers/application'; var CustomModel; var CustomSerializer; var App; // TODO: remove it, it is custom model, not employee. moduleForModel('employee', { //// Specify the other units that are required for this test. // needs: ['model:projected-model'], setup: function(){ App = startApp(); }, teardown: function(){ Ember.run(App, 'destroy'); Ember.$.mockjax.clear(); } }); test('it loads details', function(assert) { // Create custom model. CustomModel = DS.Model.extend({ firstName: DS.attr('string'), reportsTo: DS.belongsTo('custom', { inverse: null, async: true }), tmpChildren: DS.hasMany('custom', { inverse: null, async: true }) }); // Create serializer for custom model. CustomSerializer = ApplicationSerializer.extend({ primaryKey: 'CustomID', // TODO: remove after refactor of similar serializers. normalizePayload: function(payload) { if (payload.value) { payload.customs = payload.value; delete payload.value; } else { payload = { custom: payload }; } return payload; } }); // Register custom structures. App.register('model:custom', CustomModel); App.register('serializer:custom', CustomSerializer); Ember.run(function(){ Ember.$.mockjax({ url: "*Customs(99)", responseText: { "@odata.context": "http://northwindodata.azurewebsites.net/odata/$metadata#Customs(firstName,ReportsTo)/$entity", "CustomID": 99, "FirstName": "TestCustomModel", "ReportsTo": 98, "TmpChildren": [1,2] } }); Ember.$.mockjax({ url: "*Customs(98)", responseText: { "@odata.context": "http://northwindodata.azurewebsites.net/odata/$metadata#Customs(firstName,ReportsTo)/$entity", "CustomID": 98, "FirstName": "TestCustomModelMaster", "ReportsTo": 97 } }); Ember.$.mockjax({ url: "*Customs(1)", responseText: { "@odata.context": "http://northwindodata.azurewebsites.net/odata/$metadata#Customs(firstName,ReportsTo)/$entity", "CustomID": 1, "FirstName": "TestCustomModelDetail1", "ReportsTo": 100 } }); Ember.$.mockjax({ url: "*Customs(2)", responseText: { "@odata.context": "http://northwindodata.azurewebsites.net/odata/$metadata#Customs(firstName,ReportsTo)/$entity", "CustomID": 2, "FirstName": "TestCustomModelDetail2", "ReportsTo": 200 } }); var store = App.__container__.lookup('store:main'); var record = null; store.find('custom', 99).then(function(record) { assert.ok(record); assert.ok(record instanceof DS.Model); assert.equal(record.get('firstName'), "TestCustomModel"); record.get('reportsTo').then(function(masterData) { assert.ok(masterData); assert.ok(masterData instanceof DS.Model); assert.equal(masterData.get('firstName'), "TestCustomModelMaster"); }); record.get('tmpChildren').then(function(detailData) { assert.ok(detailData); var firstDetail = detailData.objectAt(0); assert.ok(firstDetail instanceof DS.Model); assert.equal(firstDetail.get('firstName'), "TestCustomModelDetail1"); var secondDetail = detailData.objectAt(1); assert.ok(firstDetail instanceof DS.Model); assert.equal(secondDetail.get('firstName'), "TestCustomModelDetail2"); }); }); andThen(function(){}); }); });
JavaScript
0.001063
@@ -62,28 +62,20 @@ t %7B -test, moduleForModel +module, test %7D f @@ -79,22 +79,16 @@ %7D from ' -ember- qunit';%0A @@ -282,91 +282,56 @@ p;%0A%0A -// TODO: remove it, it is custom model, not employee.%0AmoduleForModel('employee +module('Test detail load for custom class ', %7B%0A + // @@ -390,16 +390,18 @@ s test.%0A + // ne @@ -440,13 +440,18 @@ -setup +beforeEach : fu @@ -501,16 +501,17 @@ -teardown +afterEach : fu
2a2485e7cdae28cd10155294baaebf7ac6e875a0
Update tooltip.js
src/tooltip/tooltip.js
src/tooltip/tooltip.js
var pk = pk || {}; /** Class used for creating tooltips HTML <span id='tooltip'>Show Tooltip</span> Javascript: pk.tooltip({ element:document.getElementById('tooltip'), content:'Tooltip content', position:'left' }); @class pk.tooltip @constructor @param options {Object} @param options.element {Object} DOM element to apply tooltip to @param [options.content] {String} Tooltip content (`HTML` allowed) @param [options.position=right] {String} Tooltip position (`top`, `right`, `bottom` or `left`) @param [options.delay=500] {Number} Time in `ms` before tooltip is shown @return Object {Object} Returns target element (item `0`) @chainable */ (function(pk) { var ttEl=null; pk.tooltip=function(opt){ if(!ttEl){ ttEl=pk.createEl("<div class='pk-tooltip'></div>"); document.body.appendChild(ttEl); } var delay=opt.delay || 500, timer=null; pk.bindEvent('mouseover', opt.element,function(){ ttEl.innerHTML=opt.content; ttEl.style.display='block'; var tl=pk.layout(ttEl), pl=pk.layout(opt.element), t=0,l=0, o={x:(opt.offset ? (opt.offset.x ? opt.offset.x : 0) : 0),y:(opt.offset ? (opt.offset.y ? opt.offset.y : 0) : 0)}; opt.position=opt.position || 'right'; ttEl.style.display=''; switch(opt.position){ case "top": t=pl.top-tl.height; l=pl.left; break; case "bottom": t=pl.top+pl.height; l=pl.left; break; default: case "right": t=pl.top; l=pl.left + pl.width; break; case "left": t=pl.top; l=pl.left - tl.width; break; } ttEl.style.top=t+o.y+'px'; ttEl.style.left=l+o.x+'px'; pk.addClass(ttEl, 'pk-'+opt.position); if(!timer){ timer = setTimeout(function(){ pk.addClass(ttEl, 'pk-show'); clearTimeout(timer); timer=null; },delay); } }); pk.bindEvent('mouseout', opt.element,function(){ ttEl.innerHTML=''; if(timer){ clearTimeout(timer); timer=null; } pk.removeClass(ttEl, 'pk-show'); pk.removeClass(ttEl, 'pk-'+opt.position); }); return { 0:opt.element }; }; return pk; })(pk);
JavaScript
0.000001
@@ -50,16 +50,312 @@ oltips%0A%0A +%3Cdiv class='info-well'%3E%0AThe value passed to the %60position%60 attribute is added to the tooltip as a CSS class of the format %60pk-*position*%60. Custom positions containing the keywords %60top%60, %60left%60, %60bottom%60 and/or %60right%60 can be applied to assume the relevant attributes, i.e. %60bottomright%60%0A%3C/div%3E%0A%0A HTML%0A%0A @@ -395,16 +395,17 @@ %3C/span%3E%0A +%09 %0AJavascr @@ -1273,16 +1273,19 @@ block';%09 +%09%09%09 %0A%09%09%09var @@ -1466,16 +1466,19 @@ 0)%7D;%0A%09%09%09 +%0A%09%09 %09opt.pos @@ -1509,16 +1509,18 @@ ight';%09%09 +%09%09 %0A%09%09%09ttEl @@ -1537,24 +1537,27 @@ play=''; +%09%09%09 %0A%09%09%09%0A%09%09%09 switch(o @@ -1552,115 +1552,136 @@ %0A%09%09%09 -switch(opt.position)%7B%0A%09%09%09%09case %22top%22:%0A%09%09%09%09%09t=pl.top-tl.height;%0A%09%09%09%09%09l=pl.left;%0A%09%09%09%09break;%0A%09%09%09%09case +t=pl.top;%0A%09%09%09l=pl.left;%0A%09%09%09if(opt.position.indexOf(%22top%22)%3E-1)%7B%0A%09%09%09%09t=pl.top-tl.height;%0A%09%09%09%7Delse if(opt.position.indexOf( %22bottom%22 :%0A%09%09 @@ -1676,19 +1676,23 @@ %22bottom%22 -:%0A%09 +)%3E-1)%7B%0A %09%09%09%09t=pl @@ -1714,154 +1714,124 @@ %0A%09%09%09 -%09%09l=pl.left;%0A%09%09%09%09break;%0A%09%09%09%09default:%0A%09%09%09%09case %22right%22:%0A%09%09%09%09%09t=pl.top;%0A%09%09%09%09%09l=pl.left + pl.width;%0A%09%09%09%09break;%09%09%09%09%0A%09%09%09%09case %22left%22: %0A%09%09%09%09%09t=pl.top;%0A%09 +%7Delse if(opt.position.indexOf(%22right%22)%3E-1)%7B%0A%09%09%09%09l=pl.left + pl.width;%0A%09%09%09%7Delse if(opt.position.indexOf(%22left%22)%3E-1)%7B%0A %09%09%09%09 @@ -1859,21 +1859,13 @@ %0A%09%09%09 -%09break; +%7D %0A%09%09%09 -%7D %0A%09%09%09
57aa0f63361ec95c1ec871162ccf681ff833b6dc
Include the huntgroup for first request
the-graph/the-graph-clipboard.js
the-graph/the-graph-clipboard.js
/** * Created by mpricope on 05.09.14. */ (function (context) { "use strict"; var TheGraph = context.TheGraph; TheGraph.Clipboard = {}; var clipboardContent = {}; var cloneObject = function (obj) { return JSON.parse(JSON.stringify(obj)); }; var makeNewId = function (label) { var num = 60466176; // 36^5 num = Math.floor(Math.random() * num); var id = label + '_' + num.toString(36); return id; }; TheGraph.Clipboard.copy = function (graph, keys) { clipboardContent = {nodes:[], edges:[]}; var map = {}; var i, len; for (i = 0, len = keys.length; i < len; i++) { var node = graph.getNode(keys[i]); var newNode = cloneObject(node); newNode.id = makeNewId(node.component); clipboardContent.nodes.push(newNode); map[node.id] = newNode.id; } for (i = 0, len = graph.edges.length; i < len; i++) { var edge = graph.edges[i]; var fromNode = edge.from.node; var toNode = edge.to.node; if (map.hasOwnProperty(fromNode) && map.hasOwnProperty(toNode)) { var newEdge = cloneObject(edge); newEdge.from.node = map[fromNode]; newEdge.to.node = map[toNode]; clipboardContent.edges.push(newEdge); } } }; TheGraph.Clipboard.paste = function (graph) { var map = {}; var pasted = {nodes:[], edges:[]}; var i, len; for (i = 0, len = clipboardContent.nodes.length; i < len; i++) { var node = clipboardContent.nodes[i]; var meta = cloneObject(node.metadata); meta.x += 36; meta.y += 36; var newNode = graph.addNode(makeNewId(node.component), node.component, meta); map[node.id] = newNode.id; pasted.nodes.push(newNode); } for (i = 0, len = clipboardContent.edges.length; i < len; i++) { var edge = clipboardContent.edges[i]; var newEdgeMeta = cloneObject(edge.metadata); var newEdge; if (edge.from.hasOwnProperty('index') || edge.to.hasOwnProperty('index')) { // One or both ports are addressable var fromIndex = edge.from.index || null; var toIndex = edge.to.index || null; newEdge = graph.addEdgeIndex(map[edge.from.node], edge.from.port, fromIndex, map[edge.to.node], edge.to.port, toIndex, newEdgeMeta); } else { newEdge = graph.addEdge(map[edge.from.node], edge.from.port, map[edge.to.node], edge.to.port, newEdgeMeta); } pasted.edges.push(newEdge); } return pasted; }; TheGraph.Clipboard.displayMenu = function(graph, node) { var editor = document.getElementById('editor'); $('#modalForm').empty(); if ( isNaN(node.component.substring(node.component.length-2,node.component.length)) ) { name = node.component; } else { name = node.component.substring(0,node.component.length-2); }; var requireAjaxRequest = [ "ddi", "schedule", "ivr", "device", "user", "queue", "voicemail", "playback", "script", "conference", ]; if (requireAjaxRequest.indexOf(name)>= 0) { $.ajax({ url: "/webadmin/inroutes/components/"+name+"s/", type : "GET", dataType: "json", data : { csrfmiddlewaretoken: $.cookie('csrftoken'), current_tenant: localStorage.getItem("current_tenant"), } }) .done(function( data, textStatus, jqXHR){ var panel = createForm(node, data, editor); $('#modalTitle').html(panel.title); $('#modalForm').append(panel.content); activateEvents(node, data); $('#myModal').modal('toggle'); $('#saveNode').off(); $('#saveNode').click(function() { var result = saveForm(node, editor); editor.rerender(); if (result) { $('#myModal').modal('toggle'); }; }); }) .fail(function( jqXHR, textStatus, errorThrown){ console.log('ERROR'); }); } else { var panel = createForm(node, null, editor); $('#modalTitle').html(panel.title); $('#modalForm').append(panel.content); activateEvents(node, null); $('#myModal').modal('toggle'); $('#saveNode').off(); $('#saveNode').click(function() { var result = saveForm(node, editor); editor.rerender(); if (result) { $('#myModal').modal('toggle'); }; }); }; }; })(this);
JavaScript
0
@@ -2534,20 +2534,16 @@ node) %7B%0A - %0A var @@ -2973,16 +2973,32 @@ rence%22,%0A + %22huntgrp%22%0A %5D;%0A%0A
f71dff316ec06e8dcd65f54c7b65cfa95bad4eca
update timeout bumped to 48 hours
src/utils/constants.js
src/utils/constants.js
#!/usr/bin/env node 'use strict'; const homedir = require('homedir'); const Chalk = require('chalk'); const HIVE_GITHUB_URL = 'https://github.com/cesarferreira/drone-hive'; const DRONE_HOME_DIR = `${homedir()}/.drone`; const HIVE_HOME_DIR = `${DRONE_HOME_DIR}/drone-hive`; const HIVE_LIBS_DIR = `${HIVE_HOME_DIR}/hive`; const HIVE_SUMMARY_FILE = `${DRONE_HOME_DIR}/hive_summary.json`; const DRONE_CONFIG_FILE = `${DRONE_HOME_DIR}/config.json`; const UPDATE_TIMOUT = 60 * 60; // 1 hour in seconds const JCENTER_URL_TEMPLATE = `https://jcenter.bintray.com/PLACEHOLDER/maven-metadata.xml`; const MAVEN_URL_TEMPLATE = `http://repo1.maven.org/maven2/PLACEHOLDER/maven-metadata.xml`; const JITPACK_URL_TEMPLATE = `https://jitpack.io/PLACEHOLDER/maven-metadata.xml`; const MAVEN_CUSTOM_URL_TEMPLATE = `URL/PLACEHOLDER/maven-metadata.xml`; const ALL_PROJECTS_TEMPLATE = ` allprojects { repositories { SERVER { url 'SERVER_URL' } } } }` const ALL_PROJECTS_EMPTY_TEMPLATE = ` allprojects { repositories { jcenter() } }` // Main code // module.exports = Object.freeze({ HIVE_GITHUB_URL, HIVE_HOME_DIR, HIVE_LIBS_DIR, DRONE_HOME_DIR, HIVE_SUMMARY_FILE, MAVEN_URL_TEMPLATE, JCENTER_URL_TEMPLATE, JITPACK_URL_TEMPLATE, MAVEN_CUSTOM_URL_TEMPLATE, DRONE_CONFIG_FILE, ALL_PROJECTS_TEMPLATE, UPDATE_TIMOUT, ALL_PROJECTS_EMPTY_TEMPLATE });
JavaScript
0
@@ -473,19 +473,26 @@ * 60 + * 48 ; // -1 +48 hour +s in
35a3bb7023433f17555fdeb1e966e7816d9e8f60
Fix early return for cached `false` values in `importLocalName` (#234)
src/utils/detectors.js
src/utils/detectors.js
const VALID_TOP_LEVEL_IMPORT_PATHS = [ 'styled-components', 'styled-components/no-tags', 'styled-components/native', 'styled-components/primitives', ] export const isValidTopLevelImport = x => VALID_TOP_LEVEL_IMPORT_PATHS.includes(x) const localNameCache = {} export const importLocalName = (name, state, bypassCache = false) => { const cacheKey = name + state.file.opts.filename if (!bypassCache && localNameCache[cacheKey]) { return localNameCache[cacheKey] } let localName = state.styledRequired ? name === 'default' ? 'styled' : name : false state.file.path.traverse({ ImportDeclaration: { exit(path) { const { node } = path if (isValidTopLevelImport(node.source.value)) { for (const specifier of path.get('specifiers')) { if (specifier.isImportDefaultSpecifier()) { localName = specifier.node.local.name } if ( specifier.isImportSpecifier() && specifier.node.imported.name === name ) { localName = specifier.node.local.name } if (specifier.isImportNamespaceSpecifier()) { localName = specifier.node.local.name } } } }, }, }) localNameCache[cacheKey] = localName return localName } export const isStyled = t => (tag, state) => { if ( t.isCallExpression(tag) && t.isMemberExpression(tag.callee) && tag.callee.property.name !== 'default' /** ignore default for #93 below */ ) { // styled.something() return isStyled(t)(tag.callee.object, state) } else { return ( (t.isMemberExpression(tag) && tag.object.name === importLocalName('default', state)) || (t.isCallExpression(tag) && tag.callee.name === importLocalName('default', state)) || /** * #93 Support require() * styled-components might be imported using a require() * call and assigned to a variable of any name. * - styled.default.div`` * - styled.default.something() */ (state.styledRequired && t.isMemberExpression(tag) && t.isMemberExpression(tag.object) && tag.object.property.name === 'default' && tag.object.object.name === state.styledRequired) || (state.styledRequired && t.isCallExpression(tag) && t.isMemberExpression(tag.callee) && tag.callee.property.name === 'default' && tag.callee.object.name === state.styledRequired) ) } } export const isCSSHelper = t => (tag, state) => t.isIdentifier(tag) && tag.name === importLocalName('css', state) export const isCreateGlobalStyleHelper = t => (tag, state) => t.isIdentifier(tag) && tag.name === importLocalName('createGlobalStyle', state) export const isInjectGlobalHelper = t => (tag, state) => t.isIdentifier(tag) && tag.name === importLocalName('injectGlobal', state) export const isKeyframesHelper = t => (tag, state) => t.isIdentifier(tag) && tag.name === importLocalName('keyframes', state) export const isHelper = t => (tag, state) => isCSSHelper(t)(tag, state) || isKeyframesHelper(t)(tag, state) export const isPureHelper = t => (tag, state) => isCSSHelper(t)(tag, state) || isKeyframesHelper(t)(tag, state) || isCreateGlobalStyleHelper(t)(tag, state)
JavaScript
0.000008
@@ -410,16 +410,28 @@ Cache && + cacheKey in localNa @@ -437,26 +437,16 @@ ameCache -%5BcacheKey%5D ) %7B%0A
3bc38971d405b07e8a0a847fd35623bb7e280d33
Rename `assert` to `okay`.
prolific.collector/t/collector.t.js
prolific.collector/t/collector.t.js
require('proof')(15, prove) function prove (assert) { var Chunk = require('prolific.chunk') var Collector = require('../collector') var collector = new Collector(false) collector.scan(Buffer.from('x\n')) assert(collector.stderr.shift().toString(), 'x\n', 'stdout not header') collector.scan(Buffer.from('0 00000000 00000000 0\n')) assert(collector.stderr.shift().toString(), '0 00000000 00000000 0\n', 'stdout not valid') var chunk chunk = new Chunk(1, 0, Buffer.from(''), 1) var header = chunk.header('aaaaaaaa') collector.scan(header.slice(0, 4)) collector.scan(header.slice(4)) collector.scan(chunk.buffer) assert(collector.chunks.length, 0, 'no chunks after header chunk') var previousChecksum = chunk.checksum assert(collector.chunkNumber[1], 1, 'next chunk number stderr initialization') chunk = new Chunk(1, 1, Buffer.from('a\n'), 2) collector.scan(chunk.header(previousChecksum)) collector.scan(chunk.buffer) previousChecksum = chunk.checksum assert(collector.chunkNumber[1], 2, 'next chunk number') chunk = new Chunk(1, 0, Buffer.from(''), 2) collector.scan(chunk.header('aaaaaaaa')) collector.scan(chunk.buffer) assert({ number: collector.chunkNumber[1], stderr: collector.stderr.shift().toString(), }, { number: 2, stderr: '% 1 0 aaaaaaaa 811c9dc5 2\n' }, 'already initialized') chunk = new Chunk(1, 0, Buffer.from(''), 2) collector.scan(chunk.header('00000000')) collector.scan(chunk.buffer) assert({ number: collector.chunkNumber[1], stderr: collector.stderr.shift().toString(), }, { number: 2, stderr: '% 1 0 00000000 811c9dc5 2\n' }, 'initial entry wrong checksum') var buffer = Buffer.from('b\n') chunk = new Chunk(1, 1, buffer, buffer.length) collector.scan(chunk.header(previousChecksum)) collector.scan(chunk.buffer) assert({ number: collector.chunkNumber[1], stderr: [ collector.stderr.shift().toString(), collector.stderr.shift().toString() ] }, { number: 2, stderr: [ '% 1 1 2524c6d2 a72c4f3d 2\n', 'b\n' ] }, 'wrong chunk number') chunk = new Chunk(1, 2, buffer, buffer.length) collector.scan(chunk.header(previousChecksum)) collector.scan(chunk.buffer) previousChecksum = chunk.checksum assert(collector.chunks.shift().buffer.toString(), 'a\n', 'chunk a') assert(collector.chunks.shift().buffer.toString(), 'b\n', 'chunk b') collector.scan(chunk.header('00000000')) assert({ number: collector.chunkNumber[1], stderr: collector.stderr.shift().toString(), }, { number: 3, stderr: '% 1 2 00000000 a72c4f3d 2\n' }, 'wrong previous checksum') chunk = new Chunk(1, 3, Buffer.from(''), 0) chunk.checksum = 'aaaaaaaa' collector.scan(Buffer.concat([ chunk.header(previousChecksum), Buffer.from('hello, world') ])) assert(collector.chunks.shift().eos, 'end of stream') collector.exit() assert({ stderr: collector.stderr.shift().toString(), }, { stderr: 'hello, world' }, 'exit') var collector = new Collector(true) chunk = new Chunk(1, 0, Buffer.from(''), 1) collector.scan(chunk.header('aaaaaaaa')) collector.scan(chunk.buffer) previousChecksum = chunk.checksum assert(collector.chunks.length, 0, 'async header chunk') chunk = new Chunk(1, 1, Buffer.from(''), 0) chunk.checksum = 'aaaaaaaa' collector.scan(chunk.header(previousChecksum)) assert(collector.chunks.shift().eos, 'async end of stream') }
JavaScript
0.000779
@@ -38,22 +38,20 @@ prove ( -assert +okay ) %7B%0A @@ -209,38 +209,36 @@ rom('x%5Cn'))%0A -assert +okay (collector.stder @@ -346,30 +346,28 @@ 0%5Cn'))%0A -assert +okay (collector.s @@ -654,30 +654,28 @@ uffer)%0A%0A -assert +okay (collector.c @@ -763,38 +763,36 @@ k.checksum%0A%0A -assert +okay (collector.chunk @@ -1020,38 +1020,36 @@ k.checksum%0A%0A -assert +okay (collector.chunk @@ -1207,38 +1207,36 @@ nk.buffer)%0A%0A -assert +okay (%7B%0A numbe @@ -1545,38 +1545,36 @@ nk.buffer)%0A%0A -assert +okay (%7B%0A numbe @@ -1941,30 +1941,28 @@ uffer)%0A%0A -assert +okay (%7B%0A n @@ -2405,38 +2405,36 @@ k.checksum%0A%0A -assert +okay (collector.chunk @@ -2480,30 +2480,28 @@ unk a')%0A -assert +okay (collector.c @@ -2598,30 +2598,28 @@ 000'))%0A%0A -assert +okay (%7B%0A n @@ -3001,38 +3001,36 @@ ')%0A %5D))%0A%0A -assert +okay (collector.chunk @@ -3088,22 +3088,20 @@ ()%0A%0A -assert +okay (%7B%0A @@ -3411,30 +3411,28 @@ ecksum%0A%0A -assert +okay (collector.c @@ -3611,14 +3611,12 @@ -assert +okay (col
696422ec6ae32ca09a8f8f6f32720bef199ea894
Add error handling on travis reporting
ci/report.js
ci/report.js
#!/usr/bin/env node /** * Send reports. */ 'use strict' process.chdir(`${__dirname}/..`) const apeTasking = require('ape-tasking') const apeReporting = require('ape-reporting') apeTasking.runTasks('report', [ () => apeReporting.sendToCodeclimate('coverage/lcov.info', {}) ], true)
JavaScript
0
@@ -273,16 +273,59 @@ fo', %7B%7D) +.catch(%0A (err) =%3E console.error(err)%0A ) %0A%5D, true
f7578fec797d8d3ac99b40f083d615d2c4cca9c9
Make links from @login in posts and comments
public/js/app/helpers/Handlebars.js
public/js/app/helpers/Handlebars.js
define(["app/app", "ember"], function(App, Ember) { Ember.Handlebars.registerBoundHelper('prettifyText', function(content) { var text = $('<span/>').text(content) // wrap anchor tags around links in post text text.anchorTextUrls() // please read // https://github.com/kswedberg/jquery-expander/issues/24 // text.expander({ // slicePoint: 350, // expandPrefix: '&hellip; ', // preserveWords: true, // expandText: 'more&hellip;', // userCollapseText: '', // collapseTimer: 0, // expandEffect: 'fadeIn', // collapseEffect: 'fadeOut' // }) return new Ember.Handlebars.SafeString(text.html()) }) Ember.Handlebars.registerBoundHelper('ifpositive', function(property, options) { var context = (options.contexts && options.contexts[0]) || this var val = Ember.get(context, property) if (val > 0) return options.fn(this) return options.inverse(this) }) Ember.Handlebars.registerBoundHelper('isLast', function(index, options) { return index === options.hash.length - 1 }); Ember.Handlebars.registerBoundHelper('isFirst', function(index) { return index === 0 }); })
JavaScript
0
@@ -610,16 +610,331 @@ // %7D)%0A%0A + var html = text.html()%0A%0A // make links from @login%0A var parts = html.split(/(%3C.*?%3E)/g), i%0A for (i = 0; i %3C parts.length; i += 4) %7B%0A parts%5Bi%5D = parts%5Bi%5D.replace(/%5CB@(%5Ba-z0-9%5D+)/g, function(u) %7B%0A return '%3Ca href=%22/' + u.substr(1) + '%22%3E' + u + '%3C/a%3E'%0A %7D)%0A %7D%0A html = parts.join(%22%22)%0A%0A retu @@ -968,27 +968,20 @@ eString( -text. html -() )%0A %7D)%0A%0A
624b6a3ce307d2410ace18343a7a4c6c5237b219
修复 avalon 执行 bug
static/src/js/build.js
static/src/js/build.js
({ // RequireJS 通过一个相对的路径 baseUrl来加载所有代码。baseUrl通常被设置成data-main属性指定脚本的同级目录。 baseUrl: "./js", // 第三方脚本模块的别名,jquery比libs/jquery-1.11.1.min.js简洁明了; paths: { jquery: "empty:", avalon: "lib/avalon/avalon", editor: "utils/editor", uploader: "utils/uploader", formValidation: "utils/formValidation", codeMirror: "utils/codeMirror", bsAlert: "utils/bsAlert", problem: "app/oj/problem/problem", contest: "app/admin/contest/contest", csrfToken: "utils/csrfToken", admin: "app/admin/admin", chart: "lib/chart/Chart", tagEditor: "lib/tagEditor/jquery.tag-editor.min", jqueryUI: "lib/jqueryUI/jquery-ui", bootstrap: "lib/bootstrap/bootstrap", datetimePicker: "lib/datetime_picker/bootstrap-datetimepicker", validator: "lib/validator/validator", ZeroClipboard: "lib/ZeroClipboard/ZeroClipboard", // ------ 下面写的都不要直接用,而是使用上面的封装版本 ------ //富文本编辑器simditor -> editor simditor: "lib/simditor/simditor", "simple-module": "lib/simditor/module", "simple-hotkeys": "lib/simditor/hotkeys", "simple-uploader": "lib/simditor/uploader", //code mirror 代码编辑器 ->codeMirror _codeMirror: "lib/codeMirror/codemirror", codeMirrorClang: "lib/codeMirror/language/clike", // bootstrap组件 modal: "lib/bootstrap/modal", dropdown: "lib/bootstrap/dropdown", transition: "lib/bootstrap/transition", //百度webuploader -> uploader webUploader: "lib/webuploader/webuploader", //"_datetimePicker": "lib/datetime_picker/bootstrap-datetimepicker", //以下都是页面 script 标签引用的js addProblem_0_pack: "app/admin/problem/addProblem", addContest_1_pack: "app/admin/contest/addContest", problem_2_pack: "app/admin/problem/problem", register_3_pack: "app/oj/account/register", contestList_4_pack: "app/admin/contest/contestList", group_5_pack: "app/oj/group/group", editProblem_6_pack: "app/admin/problem/editProblem", announcement_7_pack: "app/admin/announcement/announcement", monitor_8_pack: "app/admin/monitor/monitor", groupDetail_9_pack: "app/admin/group/groupDetail", admin_10_pack: "app/admin/admin", problem_11_pack: "app/oj/problem/problem", submissionList_12_pack: "app/admin/problem/submissionList", editProblem_13_pack: "app/admin/contest/editProblem", joinGroupRequestList_14_pack: "app/admin/group/joinGroupRequestList", changePassword_15_pack: "app/oj/account/changePassword", group_16_pack: "app/admin/group/group", submissionList_17_pack: "app/admin/contest/submissionList", login_18_pack: "app/oj/account/login", contestPassword_19_pack: "app/oj/contest/contestPassword", userList_20_pack: "app/admin/user/userList" }, findNestedDependencies: true, appDir: "../", dir: "../../release/", modules: [ { name: "addContest_1_pack" } ], optimizeCss: "standard", })
JavaScript
0
@@ -201,25 +201,14 @@ n: %22 -lib/avalon/avalon +empty: %22,%0A @@ -3019,50 +3019,1241 @@ : %5B%0A -%0A %7B%0A name: %22addContest_1 + %7B%0A name: %22addProblem_0_pack%22%0A %7D,%0A %7B%0A name: %22addContest_1_pack%22%0A %7D,%0A %7B%0A name: %22problem_2_pack%22%0A %7D,%0A %7B%0A name: %22register_3_pack%22%0A %7D,%0A %7B%0A name: %22contestList_4_pack%22%0A %7D,%0A %7B%0A name: %22group_5_pack%22%0A %7D,%0A %7B%0A name: %22editProblem_6_pack%22%0A %7D,%0A %7B%0A name: %22announcement_7_pack%22%0A %7D,%0A %7B%0A name: %22monitor_8_pack%22%0A %7D,%0A %7B%0A name: %22groupDetail_9_pack%22%0A %7D,%0A %7B%0A name: %22admin_10_pack%22%0A %7D,%0A %7B%0A name: %22problem_11_pack%22%0A %7D,%0A %7B%0A name: %22submissionList_12_pack%22%0A %7D,%0A %7B%0A name: %22editProblem_13_pack%22%0A %7D,%0A %7B%0A name: %22joinGroupRequestList_14_pack%22%0A %7D,%0A %7B%0A name: %22changePassword_15_pack%22%0A %7D,%0A %7B%0A name: %22group_16_pack%22%0A %7D,%0A %7B%0A name: %22submissionList_17_pack%22%0A %7D,%0A %7B%0A name: %22login_18_pack%22%0A %7D,%0A %7B%0A name: %22contestPassword_19_pack%22%0A %7D,%0A %7B%0A name: %22userList_20 _pac
e9b9bbc46b93c62cfbb4daede055f362211db007
Update DIG wallet balance fetch error
SBSE.meta.js
SBSE.meta.js
// ==UserScript== // @version 1.13.0 // ==/UserScript==
JavaScript
0
@@ -32,9 +32,9 @@ .13. -0 +1 %0A//
7630fc97636c27244cd65bd93152f0489e145a03
Update templates to add a key and length of all templates in collection
Templates.js
Templates.js
/** * TEMPLATES * Template parsing with jQuery and Hogan * * Hogan: http://twitter.github.io/hogan.js/ * Mustache: http://mustache.github.io/ * * Templates with `x-template` get indexed by their name and injected into the * DOM where `x-template-inject` matches the template's name. * * To inject a specific template you can call * `Templates.inject(templatename, data)` while `templatename` is the value of * `x-template` and data is the object that holds the data to be passed to * the Hogan template. */ void function (global) { var $; var Hogan; var Templates = {}; /** * All templates on a page * @return {jQuery Object} All templates on a page */ Templates.getTemplates = function () { return $('[x-template]'); }; /** * Get a specific template * @param {String} page * @return {jQuery Object} Template */ Templates.get = function (page) { return Templates.getTemplates().filter('[x-template~="' + page + '"]').html(); }; /** * Parse templates and render them with data * @param {Sting} template HTML of template * @param {Object} data Data to inject into template * @return {String} Parsed template */ Templates.parse = function (template, data) { var parsedTemplate = Hogan.compile(template); return parsedTemplate.render(data); }; /** * Generate UUID * @return {String} */ Templates.generateId = function () { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1) + Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); }; /** * Inject templates where they are needed * @param {String} templateName Name of template * @param {Object} data Data to inject into template * @param {Function} callback Callback function for each element * @return {void} */ Templates.inject = function (templateName, data, callback) { var template = Templates.get(templateName); var html = ''; var i = 0; var length = 0; callback = callback || function () {}; // If data is not provided as an array if (!$.isArray(data)) { data = [data]; } length = data.length; for (; i < length; i++) { data[i].__name = data[i].__name || Templates.generateId(); data[i].id = templateName + '__' + data[i].__name; html += '<div x-template-id="' + data[i].id + '">' + Templates.parse(template, data[i]) + '</div>'; } $('[x-template-inject~="' + templateName + '"]').html(html); for (i = 0; i < length; i++) { callback(data[i]); } }; /** * Update a given template * @param {String} templateName Name of template * @param {String} name ID of element to update * @param {Object} data Data to inject into template * @return {void} */ Templates.update = function (templateName, name, data) { var template = Templates.get(templateName); var html = Templates.parse(template, data); // Replace element with new element $('[x-template-id="' + templateName + '__' + name + '"]') .after(html) .remove(); }; /** * Initialize with jQuery and Hogan * @param {Obejct} imports Holds possible imports * @return {void} */ Templates.init = function (imports) { $ = imports.jQuery; Hogan = imports.Hogan; return Templates; }; /* * AMD, module loader, global registration */ // Expose loaders that implement the Node module pattern. if (typeof module === 'object' && module && typeof module.exports === 'object') { module.exports = Templates.init({ jQuery: require('jquery'), Hogan: require('hogan.js') }); // Register as an AMD module } else if (typeof define === 'function' && define.amd) { define('Templates', ['jquery', 'hogan.js'], function (jQuery, Hogan) { return Templates.init({ jQuery: jQuery, Hogan: Hogan }); }); // Export into global space } else if (typeof global === 'object' && typeof global.document === 'object') { global.Templates = Templates.init({ jQuery: global.jQuery, Hogan: global.Hogan }); } }(this);
JavaScript
0
@@ -2437,16 +2437,73 @@ .__name; +%0A data%5Bi%5D%5B'@key'%5D = i;%0A data%5Bi%5D.count = length; %0A%0A
1d9f52e765786b9f545a8348200ec8f326667667
Use jquery instead of jQuery with AMD
Templates.js
Templates.js
/** * TEMPLATES * Template parsing with jQuery and Hogan * * Hogan: http://twitter.github.io/hogan.js/ * Mustache: http://mustache.github.io/ * * Templates with `x-template` get indexed by their name and injected into the * DOM where `x-template-inject` matches the template's name. * * To inject a specific template you can call * `Templates.inject(templatename, data)` while `templatename` is the value of * `x-template` and data is the object that holds the data to be passed to * the Hogan template. */ void function (global) { var $; var Hogan; var Templates = {}; /** * All templates on a page * @return {jQuery Object} All templates on a page */ Templates.getTemplates = function () { return $('[x-template]'); }; /** * Get a specific template * @param {String} page * @return {jQuery Object} Template */ Templates.get = function (page) { return Templates.getTemplates().filter('[x-template~="' + page + '"]').html(); }; /** * Parse templates and render them with data * @param {Sting} template HTML of template * @param {Object} data Data to inject into template * @return {String} Parsed template */ Templates.parse = function (template, data) { var parsedTemplate = Hogan.compile(template); return parsedTemplate.render(data); }; /** * Generate UUID * @return {String} */ Templates.generateId = function () { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1) + Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); }; /** * Inject templates where they are needed * @param {String} templateName Name of template * @param {Object} data Data to inject into template * @param {Function} callback Callback function for each element * @return {void} */ Templates.inject = function (templateName, data, callback) { var template = Templates.get(templateName); var html = ''; var i = 0; var length = 0; callback = callback || function () {}; // If data is not provided as an array if (!$.isArray(data)) { data = [data]; } length = data.length; for (; i < length; i++) { data[i].__name = data[i].__name || Templates.generateId(); data[i].id = templateName + '__' + data[i].__name; html += '<div x-template-id="' + data[i].id + '">' + Templates.parse(template, data[i]) + '</div>'; } $('[x-template-inject~="' + templateName + '"]').html(html); for (i = 0; i < length; i++) { callback(data[i]); } }; /** * Update a given template * @param {String} templateName Name of template * @param {String} name ID of element to update * @param {Object} data Data to inject into template * @return {void} */ Templates.update = function (templateName, name, data) { var template = Templates.get(templateName); var html = Templates.parse(template, data); // Replace element with new element $('[x-template-id="' + templateName + '__' + name + '"]') .after(html) .remove(); }; /** * Initialize with jQuery and Hogan * @param {Obejct} imports Holds possible imports * @return {void} */ Templates.init = function (imports) { $ = imports.jQuery; Hogan = imports.Hogan; return Templates; }; /* * AMD, module loader, global registration */ // Expose loaders that implement the Node module pattern. if (typeof module === 'object' && module && typeof module.exports === 'object') { module.exports = Templates.init({ jQuery: require('jquery'), Hogan: require('hogan.js') }); // Register as an AMD module } else if (typeof define === 'function' && define.amd) { define('Templates', ['jQuery', 'hogan.js'], function (jQuery, Hogan) { return Templates.init({ jQuery: jQuery, Hogan: Hogan }); }); // Export into global space } else if (typeof global === 'object' && typeof global.document === 'object') { global.Templates = Templates.init({ jQuery: global.jQuery, Hogan: global.Hogan }); } }(this);
JavaScript
0.000001
@@ -3900,17 +3900,17 @@ es', %5B'j -Q +q uery', '
0542d4bc2b4113b9d9e374f252b237b2dcd76426
Check & warn if pools use SQLite3 :memory: databases (#46)
any-db/index.js
any-db/index.js
var ConnectionPool = require('any-db-pool') var parseDbUrl = require('./lib/parse-url') var Transaction = require('./lib/transaction') Object.defineProperty(exports, 'adapters', { get: function () { throw new Error( "Replace require('any-db').adapters.<blah> with require('any-db-<blah>')" ) } }) // Re-export Transaction for adapters exports.Transaction = Transaction exports.createConnection = function connect (dbUrl, callback) { var adapterConfig = parseDbUrl(dbUrl) var adapter = getAdapter(adapterConfig.adapter) return adapter.createConnection(adapterConfig, callback) } exports.createPool = function getPool (dbUrl, poolConfig) { poolConfig = poolConfig || {} if (poolConfig.create || poolConfig.destroy) { throw new Error( "Use onConnect/reset options instead of create/destroy." ) } var adapterConfig = parseDbUrl(dbUrl); var adapter = getAdapter(adapterConfig.adapter); var pool = new ConnectionPool(adapter, adapterConfig, poolConfig) pool.begin = function (stmt, callback) { if (stmt && typeof stmt == 'function') { callback = stmt stmt = undefined } var t = new Transaction(adapter.createQuery) // Proxy query events from the transaction to the pool t.on('query', pool.emit.bind(this, 'query')) pool.acquire(function (err, conn) { if (err) return callback ? callback(err) : t.emit('error', err) t.begin(conn, stmt, callback) var release = pool.release.bind(pool, conn) t.once('rollback:complete', release) t.once('commit:complete', release) }.bind(pool)) return t } return pool } function getAdapter (protocol) { var name = protocol.replace(':', '').split('+').shift() return require('any-db-' + name); }
JavaScript
0
@@ -882,16 +882,447 @@ dbUrl);%0A + %0A if (adapterConfig.adapter === 'sqlite3' && /:memory:$/i.test(adapterConfig.database)) %7B%0A if (poolConfig.min %3E 1 %7C%7C poolConfig.max %3E 1) %7B%0A console.warn(%0A %22Pools of more than 1 connection do not work for in-memory SQLite3 databases%5Cn%22 +%0A %22The specified minimum (%25d) and maximum (%25d) connections have been overridden%22%0A )%0A %7D%0A if (poolConfig.min) poolConfig.min = 1;%0A poolConfig.max = 1;%0A %7D%0A %0A var ad
6e7eaa5b9a21e1f0e3511d7fe3f7d9ad89a0554b
Redefine method calls to use this
jasmine/src/invertedIndex.js
jasmine/src/invertedIndex.js
/* This file require running it on HTTP Server for the JQuery AJAX file reading functionality to work */ // uncomment the variable and equate it to the file path to load file contents //var dataSource = 'books.json'; //main get index function var Index = function(source, searchKeys) {}; //function to read file contents Index.prototype.readTexts = function(files) { //check file type if its an array, variable or file path var bookData; if (typeof files === typeof '') { //syncronous ajax request to read file if it is a file path $.ajax({ url: files, async: false, dataType: 'json', success: function(json) { bookData = json; } }); } else { bookData = files; } //iterate trough JSON properties and push sentences to holding array var k = 0, holder = []; do { var grab = []; for (var j in bookData[k]) { var collector = bookData[k]; grab.push(collector[j].toLowerCase()); } holder.push(grab.join(' ')); k += 1; } while (k < bookData.length); return holder; }; //function for creating index Index.prototype.createIndex = function(sourceFile) { //call the readTexts function to read contents var holder = Index.prototype.readTexts(sourceFile); var result = {}, i, index = []; //iterate through holder, split by all punctuations and push words to result for (i = 0; i < holder.length; i++) { var words = holder[i].split(/[\s\W\d]+/g); var temp = []; // push words to index array for (var j = 0; j < words.length; j++) { temp.push(words[j]); } index.push(temp); } //assign the array of words in each document to a variable for (var k = 0; k < index.length; k++) { var pass = index[k]; //take each word and locate them in the entire document for (var a = 0; a < pass.length; a++) { var holdArr = []; for (var b = 0; b < index.length; b++) { if (index[b].indexOf(pass[a]) >= 0) { //push the index of the documents they belong the holding array holdArr.push(index.indexOf(index[b])); } //assign words to their index in the result object result[pass[a]] = holdArr; } } } //store the results this.index = result; }; // this is the main search function it takes two arguement, data source // and keywords to be searched, //returns two results, all indexes and indexes of search keys Index.prototype.searchIndex = function(dataSource, searchKeys) { //check if keys is an array of strings or a string if (typeof searchKeys === typeof []) { //join if its an array searchKeys = searchKeys.join(); } //convert string to lowercase and split searchKeys = searchKeys.toLowerCase(); var keys = searchKeys.split(/[\s\W\d]+/g); //call the getIndex function //var allIndex = new Index.prototype.createIndex(dataSource); var index = this.index; var keyIndexes = {}; //check if the keys are in the index list; for (var i = 0; i < keys.length; i++) if (index.hasOwnProperty(keys[i]) === true) { keyIndexes[keys[i]] = index[keys[i]]; } //log all indexes to the console console.log(index); //log search keyresults to the console console.log(keyIndexes); //return for test purpose return keyIndexes; }; //the function below should be called on to run the creation and search // search keys can take a single word, sentences and an array of words //Index.prototype.searchIndex(dataSource, 'search keys');
JavaScript
0.000006
@@ -89,17 +89,16 @@ ality to - %0Awork */ @@ -379,16 +379,17 @@ eck file +s type if @@ -710,25 +710,199 @@ -bookData = files; +if (typeof files === typeof JSON && files !== null && files !== %7B%7D) %7B%0A bookData = files;%0A %7D else %7B%0A console.log('cannot read data, please provide a file path or JSON data')%0A %7D %0A %7D @@ -1019,20 +1019,25 @@ var -grab +bookTexts = %5B%5D;%0A @@ -1110,20 +1110,25 @@ ;%0A -grab +bookTexts .push(co @@ -1180,12 +1180,17 @@ ush( -grab +bookTexts .joi @@ -1415,31 +1415,20 @@ older = -Index.prototype +this .readTex @@ -1997,17 +1997,16 @@ document - %0A for @@ -2561,19 +2561,16 @@ arched, -%0A// returns @@ -2593,16 +2593,19 @@ indexes +%0A// and ind @@ -2781,16 +2781,60 @@ ypeof %5B%5D + && searchKeys !== null && searchKeys !== %7B%7D ) %7B%0A @@ -2889,16 +2889,18 @@ ys.join( +'' );%0A %7D%0A @@ -3035,77 +3035,97 @@ // -call +use the -getIndex function %0A //var allIndex = new %0A Index.prototype +create index property to create the indexes of words%0A //in the dataSource%0A this .cre @@ -3391,135 +3391,8 @@ %0A%0A - //log all indexes to the console%0A console.log(index);%0A%0A //log search keyresults to the console%0A console.log(keyIndexes);%0A%0A // @@ -3584,17 +3584,16 @@ of words - %0A//Index
dc3cdd726868647c198c05083030170ccbdd2442
Enable grok the docs ssl
media/javascript/rtd.js
media/javascript/rtd.js
(function () { var checkVersion = function (slug, version) { var versionURL = ["//readthedocs.org/api/v1/version/", slug, "/highest/", version, "/?callback=?"].join(""); $.getJSON(versionURL, onData); function onData (data) { if (data.is_highest) { return; } var currentURL = window.location.pathname.replace(version, data.slug), warning = $('<div class="admonition note"> <p class="first \ admonition-title">Note</p> <p class="last"> \ You are not using the most up to date version \ of the library. <a href="#"></a> is the newest version.</p>\ </div>'); warning .find('a') .attr('href', currentURL) .text(data.version); $("div.body").prepend(warning); } }; var getVersions = function (slug, version) { var versionsURL = ["//readthedocs.org/api/v1/version/", slug, "/?active=True&callback=?"].join(""); return $.getJSON(versionsURL, gotData); function gotData (data) { var items = $('<ul />') , currentURL , versionItem , object for (var key in data.objects) { object = data.objects[key] currentURL = window.location.pathname.replace(version, object.slug) versionItem = $('<a href="#"></a>') .attr('href', currentURL) .text(object.slug) .appendTo($('<li />').appendTo(items)) } // update widget and sidebar $('#version_menu, .version-listing, #sidebar_versions').html(items.html()) } }; function logHashChange(project, version, page, id, hash) { $.ajax({ type: 'POST', url: 'http://api.grokthedocs.com/api/v1/actions/', crossDomain: true, data: { project: project, version: version, page: page, object_slug: id, hash: hash, url: window.location.href, type: "hashchange" }, success: function(data, textStatus, request) { console.log("Sent hash change data") }, error: function(request, textStatus, error) { console.log("Error sending hash change data") } }); } $(function () { // Code executed on load var slug = window.doc_slug, version = window.doc_version; // Show action on hover $(".module-item-menu").hover( function () { $(".hidden-child", this).show(); }, function () { $(".hidden-child", this).hide(); } ); checkVersion(slug, version); getVersions(slug, version); // Click tracking code window.onhashchange = function(ev) { var element = document.getElementById((window.location.hash || '').slice(1)) var project = doc_slug var version = doc_version var page = page_name var id = element.id if (typeof element.hash != "undefined") { var hash = element.hash } else { var hash = null } logHashChange(project, version, page, id, hash); } }); })();
JavaScript
0.000001
@@ -1760,13 +1760,8 @@ l: ' -http: //ap @@ -2871,53 +2871,149 @@ var -page = page_name%0A var id = element.id%0A +id = element.id%0A if (typeof page_name != %22undefined%22) %7B%0A var page = page_name%0A %7D else %7B%0A var page = null%0A %7D%0A @@ -3058,34 +3058,32 @@ d%22) %7B%0A - - var hash = eleme @@ -3092,26 +3092,24 @@ .hash%0A - %7D else %7B%0A @@ -3105,34 +3105,32 @@ else %7B%0A - - var hash = null%0A @@ -3125,26 +3125,24 @@ hash = null%0A - %7D%0A
96a9d809d24a626e28970a6e90fef05bdfedb2f6
Update dom.js
javascript/dom.js
javascript/dom.js
function id(x) {return document.getElementById(x);} function cls(x) {return document.getElementsByClassName(x);} function value(x) {return id(x).value;}
JavaScript
0.000001
@@ -146,8 +146,68 @@ value;%7D%0A +function setHTML(to, from) %7Bto.innerHTML = from.innerHTML;%7D%0A
2cd77cd04691b38d593b009366f420877a3d3534
Update tests to use .type() instead of .a()
test/profiles.js
test/profiles.js
var should = require('should'); var profiler = require('../'); describe('profiles', function () { var test; function validateNode (node) { var numbers = [ 'childrenCount' , 'callUid' , 'selfSamplesCount' , 'totalSamplesCount' , 'selfTime' , 'totalTime' , 'lineNumber' ]; numbers.forEach(function (num) { node[num].should.be.a('number'); }); node.scriptName.should.be.a('string'); node.functionName.should.be.a('string'); if (Array.isArray(node.children)) { node.children.forEach(validateNode); } } it('should export profiling methods', function () { should.exist(profiler.startProfiling); profiler.startProfiling.should.be.a('function'); should.exist(profiler.startProfiling); profiler.stopProfiling.should.be.a('function'); }); it('create a profile result', function (next) { profiler.startProfiling('test'); setTimeout(function () { test = profiler.stopProfiling('test'); test.title.should.equal('test'); test.uid.should.be.above(0); next(); }, 100); }); it('should contain delete method', function () { should.exist(test.delete); test.delete.should.be.a('function'); }); it('should contain bottom and top roots', function () { should.exist(test.bottomRoot); should.exist(test.topRoot); }); it('should have correct root contents', function () { ['bottomRoot','topRoot'].forEach(function (type) { validateNode(test[type]); }); }); it('should have a getChild method for each root', function () { ['bottomRoot','topRoot'].forEach(function (type) { should.exist(test[type].getChild); test[type].getChild.should.be.a('function'); }); }); it('should getChild correctly', function () { ['bottomRoot','topRoot'].forEach(function (type) { var child = test[type].getChild(0); validateNode(child); }); }); it('should getTopDownRoot and getBottomUpRoot correctly', function () { ['getTopDownRoot','getBottomUpRoot'].forEach(function (call) { var tree = test[call](); validateNode(tree); }); }); });
JavaScript
0
@@ -383,17 +383,20 @@ ould.be. -a +type ('number @@ -429,33 +429,36 @@ tName.should.be. -a +type ('string');%0A @@ -485,17 +485,20 @@ ould.be. -a +type ('string @@ -723,33 +723,36 @@ iling.should.be. -a +type ('function');%0A%0A @@ -822,33 +822,36 @@ iling.should.be. -a +type ('function');%0A @@ -1224,33 +1224,36 @@ elete.should.be. -a +type ('function');%0A @@ -1745,17 +1745,20 @@ ould.be. -a +type ('functi
6c7fc1284e7506e45f9b489bc032c01da132b73b
Connect and Config
fruit.js
fruit.js
/* بسم الله الرحمن الرحيم */ module.exports = (function () { var defer = require('./lib/defer') , modelFactory = require('./lib/model-factory') function Fruit (adapter) { var _adapter = adapter; this.adapterType = adapter.type function getResponseHandler (deferred, formatResults) { return function (err, result) { if(err) deferred.reject(err); else deferred.resolve(formatResults ? formatResults(result) : result); } } this.insert = function (data, multipleIds) { var fruitReference = this; return { into : function (tocName) { var deferred = defer(); _adapter.insert(tocName, data, getResponseHandler(deferred), multipleIds); return deferred.getPromise(); } } } this.find = function (condition) { var fruitReference = this; return { from : function (tocName) { function formatResults (results) { for(var index in results) { var Model = modelFactory(); results[index] = new Model(results[index], tocName, fruitReference); } return results; } var deferred = defer(); _adapter.find(tocName, condition, getResponseHandler(deferred, formatResults)); return deferred.getPromise(); } } } this.findOne = function (condition) { var fruitReference = this; return { from : function (tocName) { var Model = modelFactory(); function formatResult (result) { return new Model(result, tocName, fruitReference) } var deferred = defer(); _adapter.findOne(tocName, condition, getResponseHandler(deferred, formatResult)); return deferred.getPromise(); } } } this.findAll = function (tocName) { var fruitReference = this; function formatResults (results) { for(var index in results) { var Model = modelFactory(); results[index] = new Model(results[index], tocName, fruitReference); } return results; } var deferred = defer(); _adapter.findAll(tocName, getResponseHandler(deferred, formatResults)); return deferred.getPromise(); } this.update = function (tocName) { return { set : function (data) { function _update (condition) { var deferred = defer(); _adapter.update(tocName, data, condition, getResponseHandler(deferred)); return deferred.getPromise(); } return { where : _update, success : function (callBack) { return _update({}).success(callBack); }, error : function (callBack) { return _update({}).error(callBack); } } } } } this.updateAll = function (tocName) { return { set : function (data) { function _update (condition) { var deferred = defer(); _adapter.updateAll(tocName, data, condition, getResponseHandler(deferred)); return deferred.getPromise(); } return { where : _update, success : function (callBack) { return _update({}).success(callBack); }, error : function (callBack) { return _update({}).error(callBack); } } } } } this.delete = function (tocName) { function _delete (condition) { var deferred = defer(); _adapter.delete(tocName, condition, getResponseHandler(deferred)); return deferred.getPromise(); } return { where : _delete, success : function (callBack) { return _delete({}).success(callBack); }, error : function (callBack) { return _delete({}).error(callBack); } } } this.deleteAll = function (tocName) { function _delete (condition) { var deferred = defer(); _adapter.deleteAll(tocName, condition, getResponseHandler(deferred)); return deferred.getPromise(); } return { where : _delete, success : function (callBack) { return _delete({}).success(callBack); }, error : function (callBack) { return _delete({}).error(callBack); } } } this.count = function (tocName) { function _count (condition) { var deferred = defer(); _adapter.count(tocName, condition, getResponseHandler(deferred)); return deferred.getPromise(); } return { where : _count, success : function (callBack) { return _count({}).success(callBack); }, error : function (callBack) { return _count({}).error(callBack); } } } } return Fruit; }());
JavaScript
0
@@ -491,32 +491,376 @@ %7D%0A %7D%0A %0A + this.connect = function (config) %7B%0A var deferred = defer();%0A _adapter.connect(config, function(err) %7B%0A if(err) deferred.reject(err);%0A else deferred.resolve();%0A %7D);%0A return deferred.getPromise();%0A %7D%0A %0A this.config = function (config) %7B%0A _adapter.config(config);%0A return this;%0A %7D%0A %0A this.insert
6cbdb65f6e21f96dd32826bf377aeacf70bbe030
Add tests ensuring correct escaping of ANSI chars on line refresh
test/readline.js
test/readline.js
var assert = require("assert"); var rawReadline = require("readline"); var readline2 = require(".."); var _ = require("lodash"); var through2 = require("through2"); var chalk = require("chalk"); var sinon = require("sinon"); /** * Assert an Object implements an interface * @param {Object} subject - subject implementing the façade * @param {Object|Array} methods - a façace, hash or array of keys to be implemented */ assert.implement = function (subject, methods) { methods = _.isArray(methods) ? methods : Object.keys(methods).filter(function (method) { return _.isFunction(methods[method]); }); var pass = methods.filter(function (method) { assert(_.isFunction(subject[method]), "expected subject to implement `" + method + "`"); return !_.isFunction(subject[method]); }); assert.ok(pass.length === 0, "expected object to implement the complete interface"); }; describe("Readline2", function() { beforeEach(function() { this.rl = readline2.createInterface(); }); it("returns an interface", function() { var opt = { input: process.stdin, output: process.stdout }; var interface2 = readline2.createInterface(opt); var interface = rawReadline.createInterface(opt); assert.implement( interface2, interface ); }); it("transform interface.output as a MuteStream", function( done ) { var expected = [ "foo", "lab" ]; this.rl.output.on("data", function( chunk ) { assert.equal( chunk, expected.shift() ); }); this.rl.output.on("end", function() { done(); }); this.rl.write("foo"); this.rl.output.mute(); this.rl.write("bar"); this.rl.output.unmute(); this.rl.write("lab"); this.rl.output.end(); }); // FIXME: When line is refreshed, ANSI deleted char are printed, we'd need to get // rid of those to compare the result xit("escape ANSI character in prompt", function() { var content = ""; this.rl.output.on("data", function( chunk ) { content += chunk.toString(); }); this.rl.setPrompt(chalk.red("readline2> ")); this.rl.output.emit("resize"); this.rl.write("answer"); assert.equal( content, "\x1b[31mreadline2> \x1b[39manswer" ); }); it("doesn\'t write up and down arrow", function() { this.rl._historyPrev = sinon.spy(); this.rl._historyNext = sinon.spy(); process.stdin.emit("keypress", null, { name: "up" }); process.stdin.emit("keypress", null, { name: "down" }); assert( this.rl._historyPrev.notCalled ); assert( this.rl._historyNext.notCalled ); }); });
JavaScript
0
@@ -1716,298 +1716,118 @@ %0A%0A -// FIXME: When line is refreshed, ANSI deleted char are printed, we'd need to get%0A // rid of those to compare the result%0A xit(%22escape ANSI character in prompt%22, function() %7B%0A var content = %22%22;%0A this.rl.output.on(%22data%22, function( chunk ) %7B%0A content += chunk.toString();%0A %7D); +it(%22position the cursor at the expected emplacement when the prompt contains ANSI control chars%22, function() %7B %0A @@ -1958,52 +1958,40 @@ al( -content, %22%5Cx1b%5B31mreadline2%3E %5Cx1b%5B39manswer%22 +this.rl._getCursorPos().cols, 17 );%0A
3cf845ce6b2527911c1eb94f779d0506914b7d2c
Update package dependencies. Temporarily use appworkshop:push to use latest cordova plugins.
package.js
package.js
Package.describe({ name: 'appworkshop:raix-push-config', version: '1.0.0', // Brief, one-line summary of the package. summary: 'Configure raix:push with sensible defaults for both client and server', // URL to the Git repository containing the source code for this package. git: 'https://github.com/AppWorkshop/meteor-raix-push-config', // By default, Meteor will default to using README.md for documentation. // To avoid submitting documentation, set this field to null. documentation: 'README.md' }); Package.onUse(function(api) { api.versionsFrom('1.3.2.4'); api.use('ecmascript'); api.use([ 'standard-app-packages', "appworkshop:[email protected]", "raix:[email protected]", "alanning:[email protected]" ], ['client', 'server']); api.imply([ 'raix:push', 'alanning:roles' ],['client','server']); // let other packages use Push. var path = Npm.require('path'); api.addFiles(path.join('client', 'push-config-client.js'), ['client']); api.addFiles([ path.join('server', 'push-config-server.js'), path.join('server', 'push-methods.js') ],['server']); });
JavaScript
0
@@ -68,17 +68,17 @@ n: '1.0. -0 +1 ',%0A // @@ -571,13 +571,13 @@ ('1. -3.2.4 +4.1.1 ');%0A @@ -694,17 +694,17 @@ 1.0. -2 +5 %22,%0A %22 raix @@ -699,20 +699,27 @@ %22,%0A %22 -raix +appworkshop :push@3. @@ -725,17 +725,17 @@ .0.3-rc. -5 +8 %22,%0A %22 @@ -804,25 +804,43 @@ (%5B%0A ' -raix:push +appworkshop:[email protected] ',%0A '
6ae60a98ea48100d9f69e1371b2065cde7aaf013
Fix issue with multiple PluginInstance plugins
core/PluginInstance.js
core/PluginInstance.js
var fs = require('fs'); function PluginCreateInstance(pluginInst) { var inst = new PluginInstance(); inst.prototype = pluginInst; return inst; } var PluginInstance = function () { this.pinst = this; this.files = []; }; PluginInstance.prototype.events = {}; PluginInstance.prototype.events.onLoad = function (_plugin) { this.plugin = _plugin; this.manager = _plugin.manager; this.core = this.manager.core; this.config = _plugin.getConfig(); if (this.init) this.init(); }; PluginInstance.prototype.loadDir = function (path) { var files = fs.readdirSync(path); for (var i in files) { var file = path + "/" + files[i]; var name = require.resolve(file); this.files.push(name); //small hack, try unloading before loading // in case of error/plugin not unloading properly try { delete require.cache[name]; } catch (e) { } require(file)(this); } }; PluginInstance.prototype.onUnload = function () { for (var i in this.files) { var name = this.files[i]; try { delete require.cache[name]; } catch (e) { } } }; module.exports = PluginInstance;
JavaScript
0
@@ -18,16 +18,34 @@ 'fs');%0A%0A +var events = %7B%7D;%0A%0A function @@ -253,288 +253,136 @@ %5B%5D;%0A -%7D;%0A%0APluginInstance.prototype.events = %7B%7D;%0A%0APluginInstance.prototype.events.onLoad = function (_plugin) %7B%0A this.plugin = _plugin;%0A this.manager = _plugin.manager;%0A this.core = this.manager.core;%0A this.config = _plugin.getConfig();%0A%0A if (this.init)%0A this.init( +%0A this.events = %7B%7D;%0A for(var k in events) %7B%0A this.events%5Bk%5D = events%5Bk%5D;%0A %7D%0A%0A console.log(events, this.events );%0A%7D @@ -866,32 +866,233 @@ %7D;%0A%0A -PluginInstance.prototype +events.onLoad = function (_plugin) %7B%0A this.plugin = _plugin;%0A this.manager = _plugin.manager;%0A this.core = this.manager.core;%0A this.config = _plugin.getConfig();%0A%0A if (this.init)%0A this.init();%0A%7D;%0A%0Aevents .onU
5ef533c0897a2813a0dc0697e393e3d0ea2252c7
Add missing GamePad supporting function
Web/Siv3D.js
Web/Siv3D.js
mergeInto(LibraryManager.library, { glfwGetKeysSiv3D: function (windowid) { const window = GLFW.WindowFromId(windowid); if (!window) return 0; if (!window.keysBuffer) { window.keysBuffer = Module._malloc(349 /* GLFW_KEY_LAST + 1 */) } Module.HEAPU8.set(window.keys, window.keysBuffer); return window.keysBuffer; }, glfwGetKeysSiv3D__sig: "ii", glfwGetMonitorInfo_Siv3D: function(handle, displayID, xpos, ypos, w, h) { setValue(displayID, 1, 'i32'); setValue(xpos, 0, 'i32'); setValue(ypos, 0, 'i32'); setValue(w, 0, 'i32'); setValue(h, 0, 'i32'); }, glfwGetMonitorInfo_Siv3D__sig: "viiiiiiiiiii", glfwGetMonitorWorkarea: function(handle, wx, wy, ww, wh) { setValue(wx, 0, 'i32'); setValue(wy, 0, 'i32'); setValue(ww, 1280, 'i32'); setValue(wh, 720, 'i32'); }, glfwGetMonitorWorkarea__sig: "viiiii", glfwGetMonitorContentScale: function(handle, xscale, yscale) { setValue(xscale, 1, 'float'); setValue(yscale, 1, 'float'); }, glfwGetMonitorContentScale__sig: "viii", siv3dSetCursorStyle: function(style) { const styleText = UTF8ToString(style); Module["canvas"].style.cursor = styleText; }, siv3dSetCursorStyle__sig: "vi", // // MessageBox // siv3dShowMessageBox: function(messagePtr, type) { const message = UTF8ToString(messagePtr); if (type === 0) { /* MessageBoxButtons.OK */ window.alert(message); return 0; /* MessageBoxResult.OK */ } else if (type === 1) { /* MessageBoxButtons.OKCancel */ return window.confirm(message) ? 0 /* MessageBoxResult.OK */ : 1 /* MessageBoxResult.Cancel */; } return 4; /* MessageBoxSelection.None */ }, siv3dShowMessageBox__sig: "iii", // // DragDrop Support // siv3dRegisterDragEnter: function(ptr) { Module["canvas"].ondragenter = function (e) { e.preventDefault(); const types = e.dataTransfer.types; if (types.length > 0) { {{{ makeDynCall('vi', 'ptr') }}}(types[0] === 'Files' ? 1 : 0); } }; }, siv3dRegisterDragEnter__sig: "vi", siv3dRegisterDragUpdate: function(ptr) { Module["canvas"].ondragover = function (e) { e.preventDefault(); {{{ makeDynCall('v', 'ptr') }}}(); }; }, siv3dRegisterDragUpdate__sig: "vi", siv3dRegisterDragExit: function(ptr) { Module["canvas"].ondragexit = function (e) { e.preventDefault(); {{{ makeDynCall('v', 'ptr') }}}(); }; }, siv3dRegisterDragExit__sig: "vi", $s3dDragDropFileReader: null, siv3dRegisterDragDrop: function(ptr) { Module["canvas"].ondrop = function (e) { e.preventDefault(); const items = e.dataTransfer.items; if (items.length == 0) { return; } if (items[0].kind === 'text') { items[0].getAsString(function(str) { const strPtr = allocate(intArrayFromString(str), ALLOC_NORMAL); {{{ makeDynCall('vi', 'ptr') }}}(strPtr); Module["_free"](strPtr); }) } else if (items[0].kind === 'file') { const file = items[0].getAsFile(); if (!s3dDragDropFileReader) { s3dDragDropFileReader = new FileReader(); } const filePath = `/tmp/${file.name}`; s3dDragDropFileReader.addEventListener("load", function onLoaded() { FS.writeFile(filePath, new Uint8Array(s3dDragDropFileReader.result)); const namePtr = allocate(intArrayFromString(filePath), ALLOC_NORMAL); {{{ makeDynCall('vi', 'ptr') }}}(namePtr); s3dDragDropFileReader.removeEventListener("load", onLoaded); }); s3dDragDropFileReader.readAsArrayBuffer(file); } }; }, siv3dRegisterDragDrop__sig: "vi", siv3dRegisterDragDrop__deps: [ "$s3dDragDropFileReader", "$FS" ], })
JavaScript
0
@@ -29,16 +29,312 @@ rary, %7B%0A + //%0A // GamePads%0A //%0A siv3dGetJoystickInfo: function(joystickId) %7B%0A return GLFW.joys%5BjoystickId%5D.id;%0A %7D,%0A siv3dGetJoystickInfo__sig: %22iiiii%22,%0A%0A glfwGetJoystickHats: function () %7B%0A // Not supported.%0A return 0;%0A %7D,%0A glfwGetJoystickHats__sig: %22iii%22,%0A%0A glfw @@ -702,24 +702,54 @@ sig: %22ii%22,%0A%0A + //%0A // Monitors%0A //%0A glfwGetM @@ -3135,16 +3135,18 @@ %0A%0A $s +iv 3dDragDr @@ -3859,16 +3859,18 @@ if (!s +iv 3dDragDr @@ -3898,32 +3898,34 @@ s +iv 3dDragDropFileRe @@ -4032,32 +4032,34 @@ s +iv 3dDragDropFileRe @@ -4169,16 +4169,18 @@ 8Array(s +iv 3dDragDr @@ -4370,32 +4370,34 @@ s +iv 3dDragDropFileRe @@ -4478,16 +4478,18 @@ s +iv 3dDragDr @@ -4648,16 +4648,18 @@ s: %5B %22$s +iv 3dDragDr
0c2b06d337e8f667434be69c2faddadc5e8a2bc0
remove useless line
jest.config.js
jest.config.js
module.exports = { browser: true, verbose: false, collectCoverage: true, collectCoverageFrom: [ 'src/app/**/*.js', ], setupFiles: [ 'jest-localstorage-mock', 'jest-mock-console', ], moduleNameMapper: { '\\.scss$': '<rootDir>/test/mocks/style.js', '@/(.*)$': '<rootDir>/src/app/$1', 'Mocks(.*)$': '<rootDir>/test/mocks$1', }, };
JavaScript
0.000026
@@ -360,12 +360,11 @@ ',%0A %7D,%0A -%0A %7D;%0A
a11cf7f5adc87446df1fe74a5d628bd7b373a785
Add missing tests
test/test-url.js
test/test-url.js
var url = require("./url"); var targetClean = "http://redirection.target.com/?some=parameter&some-other=parameter;yet-another=parameter#some-fragment"; var targetEncoded = encodeURIComponent(targetClean); var tests = [ [targetClean, undefined], ["http://some.website.com/?target=" + targetEncoded, targetClean], ["http://some.website.com/?target=" + targetEncoded + "&some=parameter", targetClean], ["http://some.website.com/?target=" + targetEncoded + ";some=parameter", targetClean], ["http://some.website.com/?target=" + targetEncoded + "#some-fragment", targetClean], ["http://some.website.com/login?continue=" + targetEncoded + "#some-fragment", undefined], ]; exports["test no redirect"] = function(assert) { for (var index = 0; index < tests.length; index++) { var from = tests[index][0]; var to = tests[index][1]; assert.equal( url.getRedirectTarget(from), to, "Wrong redirection target for " + from ); } }; require("sdk/test").run(exports);
JavaScript
0.00007
@@ -199,16 +199,77 @@ tClean); +%0Avar targetDoubleEncoded = encodeURIComponent(targetEncoded); %0A%0Avar te @@ -744,16 +744,484 @@ fined%5D,%0A + %5B%22http://some.website.com/?target=%22 + targetDoubleEncoded, targetClean%5D,%0A %5B%22http://some.website.com/?target=%22 + targetDoubleEncoded + %22&some=parameter%22, targetClean%5D,%0A %5B%22http://some.website.com/?target=%22 + targetDoubleEncoded + %22;some=parameter%22, targetClean%5D,%0A %5B%22http://some.website.com/?target=%22 + targetDoubleEncoded + %22#some-fragment%22, targetClean%5D,%0A %5B%22http://some.website.com/login?continue=%22 + targetDoubleEncoded + %22#some-fragment%22, undefined%5D,%0A %5D;%0A%0Aexpo
be7d4c2f2dc4e39af8c863ba7604688c4a1c4d93
remove unused import
addon/utils/update.js
addon/utils/update.js
import Ember from 'ember'; const { get, set, assign } = Ember; // Usage: update(person, 'name', (name) => name.toUpperCase()) export default function update(obj, key, updateFn) { let property = get(obj, key); let newValue = updateFn(property); set(obj, key, newValue); }
JavaScript
0.000001
@@ -41,16 +41,8 @@ set -, assign %7D =
007761b1e7b413b9dce3d97ac267028189ec2293
add csrf capabilities to form register header using axios.
web/project/dashboard/src/actions/authActions.js
web/project/dashboard/src/actions/authActions.js
import axios from 'axios'; import setAuthorizationToken from '../utils/setAuthorizationToken'; export function login(data){ var headers = { 'Content-Type':'application/json' } return dispatch => { return axios.post('api/login', data, headers).then( res => { const is_staff = res.data.is_staff; if (is_staff){ const token = res.data.token; localStorage.setItem('jwtToken', token); localStorage.setItem('is_staff', is_staff); setAuthorizationToken(token); } } ) }}
JavaScript
0
@@ -89,16 +89,109 @@ oken';%0A%0A +axios.defaults.xsrfCookieName = 'csrftoken';%0Aaxios.defaults.xsrfHeaderName = 'X-CSRFToken';%0A%0A export f @@ -233,16 +233,18 @@ = %7B%0A + 'Content @@ -272,16 +272,17 @@ son'%0A %7D +; %0A retur @@ -669,8 +669,9 @@ )%0A%7D%7D%0A +%0A
c06d516cfdf072c8e7b020328034aabf76eb9f16
add link to export format docs
ui/app/components/ChooseFormats.js
ui/app/components/ChooseFormats.js
import React from "react"; import { FormattedMessage } from "react-intl"; import { Row } from "react-bootstrap"; import { Link } from "react-router-dom"; import { Field } from "redux-form"; import { AVAILABLE_EXPORT_FORMATS, getFormatCheckboxes, renderCheckboxes } from "./utils"; export default ({ next }) => <Row> <Field name="export_formats" label="File Formats" component={renderCheckboxes} > {getFormatCheckboxes(AVAILABLE_EXPORT_FORMATS)} </Field> <Link className="btn btn-primary pull-right" to={next}> <FormattedMessage id="nav.next" defaultMessage="Next" /> </Link> </Row>;
JavaScript
0
@@ -426,16 +426,146 @@ %7D%0A %3E%0A + &nbsp; See %3CLink to=%22/learn/export_formats%22 target=%22_blank%22%3ELearn (Export Formats)%3C/Link%3E for details on each file format.%0A %7Bg
77661282202f25c6bafa9afc0047e0306d1427aa
add time to twitter endpoint
jobs/social.js
jobs/social.js
//get username keys from config file var config = require('../config.js'); //save.js to save json var save = require('../save.js'); //request for simple http calls var request = require('request'); // async to make batch HTTP easy var async = require('async'); // twitter for ... twitter var Twitter = require('twitter'); if (!config.social) return; job('hn', function(done) { social = new Object; if (config.social.hackernews.id) { request('https://hacker-news.firebaseio.com/v0/user/'+ config.social.hackernews.id + '.json', function (error, response, data) { data = JSON.parse(data); social.hn = new Object; social.hn.karma = data.karma; social.hn.id = data.id; // determine amount of items to fetch if (data.submitted.length >= config.social.hackernews.recentItems) { items = config.social.hackernews.recentItems; } else { items = data.submitted.length; } social.hn.recent = []; // start an async queue for http requests var queue = async.queue(function (task, done) { request('https://hacker-news.firebaseio.com/v0/item/'+ task.item + '.json', function (error, response, data) { // remove username & kids from data data = JSON.parse(data); delete data.by; delete data.kids; if (data.deleted) { done(); } else { // add item url data.url = "http://news.ycombinator.com/item?id=" + task.item; social.hn.recent[task.order] = data; done(); } }); }, items); for (var i = 0; i < items; i++) { item = data.submitted[i]; queue.push({item: item, order: i}); }; // when all are finished, save json queue.drain = function() { save.file("hn", social); console.log("Hacker News data updated."); } }); } }).every('1h'); job('twitter', function(done) { if(!config.social.twitter) return; var client = new Twitter({ consumer_key: config.social.twitter.consumer_key, consumer_secret: config.social.twitter.consumer_secret, access_token_key: config.social.twitter.access_token_key, access_token_secret: config.social.twitter.access_token_secret }); client.get('statuses/user_timeline', function(error, data, response){ if (!error) { tweets = new Object; tweets.username = config.social.twitter.username; tweets.url = "https://twitter.com/" + tweets.username; tweets.recent = []; for (var i = 0; i < data.length; i++) { tweet = new Object; tweet.text = data[i].text; tweet.favorite_count = data[i].favorite_count; tweet.retweet_count = data[i].retweet_count; // URL is different for retweets if (data[i].retweeted_status) { tweet.is_retweet = true; // find original user to create url user = data[i].retweeted_status.user.screen_name; } else { tweet.is_retweet = false user = tweets.username; } tweet.url = "https://twitter.com/" + user + "/status/" + data[i].id_str; tweets.recent[i] = tweet; }; save.file("twitter", tweets); console.log("Twitter data updated."); } }); }).every("5m");
JavaScript
0.000016
@@ -2568,16 +2568,54 @@ t_count; +%0A%09 %09tweet.time = data%5Bi%5D.created_at; %0A%0A%09 %09/
d11bfa5a4d165f70eb0864ca7ded1fd34f219cbb
Remove default prefix.
jquery.thar.js
jquery.thar.js
/*! * thar - Automatic content anchors * https://github.com/gocom/jquery.thar * * Copyright (C) 2013 Jukka Svahn * * 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 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * 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. */ /** * thar * * A content anchor links plugin for jQuery. * * @param {Object} options Options * @param {String} options.prefix A prefix added to the generated links * @param {String|Boolean} options.anchor The anchor link text * @return {Object} this * @author Jukka Svahn * @package thar */ ;(function (factory) { if (typeof define === 'function' && define.amd) { define(['jquery'], factory); } else { factory(jQuery); } }(function ($) { var hash = window.location.hash.substr(1), occurrences = {'' : 0}, methods = { scrollTo : function () { var $this = $(this), id = $this.attr('id'); $('html, body').animate({ scrollTop : $this.offset().top }, 1000, 'swing', function () { if (id) { window.location.hash = '#' + id; } }); } }; $.fn.thar = function (options) { options = $.extend({ 'prefix' : 'thar-', 'anchor' : '&#167;' }, options); var ul = $('<ul />'); return this.each(function () { var _this = this, $this = $(this), id = '', anchor; if ($this.hasClass('jquery-thar')) { return; } if ($this.attr('id')) { id = $this.attr('id'); } else { id = options.prefix + encodeURIComponent($this.text().replace(/\s/g, '-')) .replace(/[^A-Z0-9\-]/gi, '-') .substr(0, 255) .replace(/^[\d\-]|-$/g, '') .replace(/-{2,}/g, '-') .toLowerCase(); if ($.type(occurrences[id]) !== 'undefined') { occurrences[id]++; id += '_' + occurrences[id]; } else { occurrences[id] = 1; } } $this.attr('id', id).addClass('jquery-thar').trigger('anchorcreate.thar'); if (id === hash) { methods.scrollTo.apply(this); $this.trigger('anchorload.thar', { 'id' : id }); hash = false; } ul.append( $('<li />') .addClass('jquery-thar-to-' + id) .html( $('<a />') .attr('href', '#' + id) .text($this.text()) .on('click.thar', function (e) { e.preventDefault(); methods.scrollTo.apply(_this); }) ) ); if (options.anchor !== false) { anchor = $('<a class="jquery-thar-anchor" />') .attr('href', '#' + id) .on('click.thar', function (e) { e.preventDefault(); methods.scrollTo.apply(_this); }); if (options.anchor === true) { $this.wrapInner(anchor); } else { $this.prepend(anchor.html(options.anchor)).prepend(' '); } } }) .extend({ tharResults : { 'ul' : ul } }); }; }));
JavaScript
0
@@ -2097,21 +2097,16 @@ fix' : ' -thar- ',%0A%09%09%09'a
dde1d80cc3d98a35f0e9e058a225dd87c54694dc
Fix one off error in broken test
test/time-ago.js
test/time-ago.js
suite('time-ago', function() { let dateNow function freezeTime(expected) { dateNow = Date function MockDate(...args) { if (args.length) { return new dateNow(...args) } return new dateNow(expected) } MockDate.UTC = dateNow.UTC MockDate.parse = dateNow.parse MockDate.now = () => expected.getTime() MockDate.prototype = dateNow.prototype // eslint-disable-next-line no-global-assign Date = MockDate } teardown(function() { if (dateNow) { // eslint-disable-next-line no-global-assign Date = dateNow dateNow = null } }) test('always uses relative dates', function() { const now = new Date(Date.now() - 10 * 365 * 24 * 60 * 60 * 1000).toISOString() const time = document.createElement('time-ago') time.setAttribute('datetime', now) assert.equal(time.textContent, '10 years ago') }) test('rewrites from now past datetime to minutes ago', function() { const now = new Date(Date.now() - 3 * 60 * 1000).toISOString() const time = document.createElement('time-ago') time.setAttribute('datetime', now) assert.equal(time.textContent, '3 minutes ago') }) test('rewrites a few seconds ago to now', function() { const now = new Date().toISOString() const time = document.createElement('time-ago') time.setAttribute('datetime', now) assert.equal(time.textContent, 'now') }) test('displays future times as now', function() { const now = new Date(Date.now() + 3 * 1000).toISOString() const time = document.createElement('time-ago') time.setAttribute('datetime', now) assert.equal(time.textContent, 'now') }) test('sets relative contents when parsed element is upgraded', function() { const now = new Date().toISOString() const root = document.createElement('div') root.innerHTML = `<time-ago datetime="${now}"></time-ago>` if ('CustomElements' in window) { window.CustomElements.upgradeSubtree(root) } assert.equal(root.children[0].textContent, 'now') }) test('rewrites from now past datetime to months ago', function() { const now = new Date(Date.now() - 3 * 30 * 24 * 60 * 60 * 1000).toISOString() const time = document.createElement('time-ago') time.setAttribute('datetime', now) assert.equal(time.textContent, '3 months ago') }) test('rewrites time-ago datetimes < 18months as "months ago"', function() { freezeTime(new Date(2020, 0, 1)) const then = new Date(2018, 10, 1).toISOString() const timeElement = document.createElement('time-ago') timeElement.setAttribute('datetime', then) assert.equal(timeElement.textContent, '15 months ago') }) test('rewrites time-ago datetimes >= 18 months as "years ago"', function() { freezeTime(new Date(2020, 0, 1)) const then = new Date(2018, 6, 1).toISOString() const timeElement = document.createElement('time-ago') timeElement.setAttribute('datetime', then) assert.equal(timeElement.textContent, '2 years ago') }) test('micro formats years', function() { const now = new Date(Date.now() - 10 * 365 * 24 * 60 * 60 * 1000).toISOString() const time = document.createElement('time-ago') time.setAttribute('datetime', now) time.setAttribute('format', 'micro') assert.equal(time.textContent, '10y') }) test('micro formats future times', function() { const now = new Date(Date.now() + 3 * 1000).toISOString() const time = document.createElement('time-ago') time.setAttribute('datetime', now) time.setAttribute('format', 'micro') assert.equal(time.textContent, '1m') }) test('micro formats hours', function() { const now = new Date(Date.now() - 60 * 60 * 1000).toISOString() const time = document.createElement('time-ago') time.setAttribute('datetime', now) time.setAttribute('format', 'micro') assert.equal(time.textContent, '1h') }) test('micro formats days', function() { const now = new Date(Date.now() - 25 * 60 * 60 * 1000).toISOString() const time = document.createElement('time-ago') time.setAttribute('datetime', now) time.setAttribute('format', 'micro') assert.equal(time.textContent, '1d') }) })
JavaScript
0.000575
@@ -2499,18 +2499,17 @@ e(2018, -10 +9 , 1).toI
68fc23983985f691d40e40d87cdf54d3cc154319
Clean up tests a little bit. Clarify problems with IE in comments next to tests that ensure their behaviour.
test/unit/dom.js
test/unit/dom.js
import helpers from '../lib/helpers'; import skate from '../../src/skate'; describe('DOM', function () { describe('General DOM node interaction.', function () { it('Modules should pick up nodes already in the DOM.', function (done) { var calls = 0; helpers.fixture('<div><my-element-1></my-element-1></div>'); skate.init(helpers.fixture()); skate('my-element-1', { insert: function () { ++calls; } }); helpers.afterMutations(function () { expect(calls).to.equal(1); done(); }); }); it('Modules should pick up nodes inserted into the DOM after they are defined.', function (done) { var calls = 0; skate('my-element-2', { insert: function () { ++calls; } }); helpers.fixture('<div><my-element-2></my-element-2></div>'); skate.init(helpers.fixture()); helpers.afterMutations(function () { expect(calls).to.equal(1); done(); }); }); it('should pick up descendants that are inserted as part of an HTML block.', function (done) { var calls = 0; skate('my-element-3', { insert: function () { ++calls; } }); helpers.fixture('<div><my-element-3></my-element-3></div>'); skate.init(helpers.fixture()); helpers.afterMutations(function () { expect(calls).to.equal(1); done(); }); }); // IE 11 has a bug: https://connect.microsoft.com/IE/feedback/details/817132/ie-11-childnodes-are-missing-from-mutationobserver-mutations-removednodes-after-setting-innerhtml. // IE 9 and 10 also have the same bug with Mutation Events. it('should pick up descendants that are removed if an ancestor\'s innerHTML is set.', function (done) { var calls = 0; skate('my-element-4', { remove: function () { ++calls; } }); helpers.fixture('<div id="removing"><child><my-element-4</my-element-4></child></div>'); skate.init(helpers.fixture()); helpers.fixture(''); helpers.afterMutations(function () { expect(calls).to.equal(1); done(); }); }); // IE 9 / 10 have issues with this. This is also to ensure IE 11 doesn't. it('should pick up descendants that are removed if an ancestor is removed.', function (done) { var calls = 0; skate('my-element-5', { remove: function () { ++calls; } }); helpers.fixture('<div id="removing"><child><my-element-5></my-element-5></child></div>'); skate.init(helpers.fixture()); helpers.fixture().removeChild(document.getElementById('removing')); helpers.afterMutations(function () { expect(calls).to.equal(1); done(); }); }); }); describe('SVG', function () { it('should work for any SVG element', function () { var div = document.createElement('div'); div.innerHTML = '<svg width="100" height="100">' + '<circle my-circle="true" cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />' + '<circle my-circle="true" class="my-circle" cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />' + '</svg>'; skate('my-circle', { ready: function (element) { element.getAttribute('my-circle').should.equal('true'); } }); skate.init(div); }); }); });
JavaScript
0
@@ -254,32 +254,43 @@ lls = 0;%0A%0A +skate.init( helpers.fixture( @@ -336,48 +336,11 @@ v%3E') -;%0A skate.init(helpers.fixture() );%0A -%0A @@ -771,32 +771,43 @@ %7D);%0A%0A +skate.init( helpers.fixture( @@ -853,44 +853,8 @@ v%3E') -;%0A skate.init(helpers.fixture() );%0A @@ -1184,32 +1184,43 @@ %7D);%0A%0A +skate.init( helpers.fixture( @@ -1266,44 +1266,8 @@ v%3E') -;%0A skate.init(helpers.fixture() );%0A @@ -1562,72 +1562,8 @@ ml.%0A - // IE 9 and 10 also have the same bug with Mutation Events.%0A @@ -1786,32 +1786,43 @@ %7D);%0A%0A +skate.init( helpers.fixture( @@ -1896,44 +1896,8 @@ v%3E') -;%0A skate.init(helpers.fixture() );%0A @@ -2061,62 +2061,68 @@ ave -issues with this. This is also to ensure IE 11 doesn't +the same bug with removeChild() as IE 11 does with innerHTML .%0A @@ -2338,32 +2338,43 @@ %7D);%0A%0A +skate.init( helpers.fixture( @@ -2449,44 +2449,8 @@ v%3E') -;%0A skate.init(helpers.fixture() );%0A
49b126c78ae10b18d73631b5ad739f275b98c72b
Update AllSites.js
js/AllSites.js
js/AllSites.js
/* How this works: this takes what you write and change it into HTML code (see Sites.js for more info) How to use: NedTool("Name", "Link to site", "Link to image"); <-- This has been replaced (for the most part) with DNedTool DNedTool("Name", "Link to image"); <-- This is a direct version of NedTool where the name is taken and the site is set to nedhome.ml/tools/name OutherSite("Name", "Link to site", "Link to image"); <-- Link to outsite site thats not part of the Ned sites SocialMedia("Name", "Link to site", "Link to image"); <-- Facebook, Twitter, ex... All of the stuff above is a shortcut to Button() ex NedTool() whould be this: Button("Name", "url", "NedTool", "image"); */ function AllNedTools() { DNedTool("google", "goo.gl/b274CE"); NedTool("Yahoo", "nedhome.ml/tools/google?yahoo", "goo.gl/Tu73C3"); DNedTool("Calculator", "www.free-icons-download.net/images/calculator-logo-73002.png"); //DNedTool("Calendar", "goo.gl/hGkTvi"); DNedTool("Calendar", "pixabay.com/static/uploads/photo/2016/01/20/10/52/maintenance-1151312_960_720.png"); DNedTool("Clock", "goo.gl/V4Zwrh"); NedTool("$ Converter", "nedhome.ml/tools/moneyconverter", "goo.gl/g0vTnM"); DNedTool("Holidays", "nedhome.ml/imgs/tree.png"); //pixabay.com/static/uploads/photo/2015/12/10/17/46/fir-1086772_960_720.png DNedTool("Radio", "upload.wikimedia.org/wikipedia/commons/thumb/8/8f/Icon_sound_radio.svg/1259px-Icon_sound_radio.svg.png"); DNedTool("Tv", "nedhome.ml/imgs/LAPTOP.png"); //pixabay.com/static/uploads/photo/2013/07/13/01/20/monitor-155565_960_720.png NedGames(); } function AllOutherSites() { OutherSite("SUSEStudio", "susestudio.com", "goo.gl/64ozgA"); OutherSite("Weebly", "weebly.com", "upload.wikimedia.org/wikipedia/commons/4/43/Weebly_logo_2013.png"); OutherSite("Youtube", "youtube.com", "t2.gstatic.com/images?q=tbn:ANd9GcQDfL7X2SHlu_A9qhVi4HhJFMFqkX4VBAZL9LS81bJm_RatOoM71KJX9nv3"); OutherSite("Linux", "linux.com", "upload.wikimedia.org/wikipedia/commons/thumb/3/35/Tux.svg/1000px-Tux.svg.png"); OutherSite("CCleaner", "ccleaner.com", "upload.wikimedia.org/wikipedia/en/4/4a/CCleaner_logo_2013.png"); OutherSite("Microsoft", "microsoft.com", "img05.deviantart.net/e1f7/i/2011/251/e/4/microsoft_windows_logo_3000px_by_davidm147-d3hax3m.png"); OutherSite("Wikipedia", "wikipedia.org", "upload.wikimedia.org/wikipedia/commons/7/7a/Nohat-wiki-logo.png"); OutherSite("W3 Schools", "w3schools.com", "w3schools.com/favicon.ico"); } function AllSocialMedia() { SocialMedia("Facebook", "facebook.com", "upload.wikimedia.org/wikipedia/commons/thumb/c/c2/F_icon.svg/2000px-F_icon.svg.png"); SocialMedia("Twitter", "twitter.com", "upload.wikimedia.org/wikipedia/en/thumb/9/9f/Twitter_bird_logo_2012.svg/220px-Twitter_bird_logo_2012.svg.png"); SocialMedia("Flickr", "flickr.com", "upload.wikimedia.org/wikipedia/commons/9/9b/Flickr_logo.png"); SocialMedia("Google+", "plus.google.com", "upload.wikimedia.org/wikipedia/commons/1/13/Google%2Bapp_icon.png"); SocialMedia("Imgur", "imgur.com", "upload.wikimedia.org/wikipedia/commons/thumb/e/e9/Imgur_logo.svg/2000px-Imgur_logo.svg.png"); } function AllKids() { Kids("Disney", "disney.com", "upload.wikimedia.org/wikipedia/commons/4/4c/Walt_Disney_Pictures.png"); Kids("Nick", "nick.com", "upload.wikimedia.org/wikipedia/commons/8/85/Nick_(Logo).png"); Kids("CN", "cartoonnetwork.com", "bit.ly/CNLogo"); //The image is from Wikipedia just shortened Kids("Safe Google", "nedhome.ml/tools/google?kids", "www.edu.pe.ca/lmmontgomery/Links/images/kid_rex.jpg"); Kids("GamesFreak", "gamesfreak.net", "static.gamepilot.com/i/c75_themes/gamesfreak/fast-freddy-blue-pale.jpg"); Kids("Minecraft", "minecraft.net", "alice.violympic.vn/assets/uploads/member/icon_minecraft.png"); Kids("PBS Kids", "pbskids.org", "grundycenter.lib.ia.us/images/icons/pbskids-logo.png"); } function AllSites() { AllNedTools(); NewLine("br"); AllOutherSites(); NewLine("br"); AllKids(); NewLine("br"); AllSocialMedia(); }
JavaScript
0
@@ -716,16 +716,101 @@ %22);%0A*/%0A%0A +// All the images are found on Google with usage rights set to 'Labeled for reuse'.%0A%0A function @@ -1087,118 +1087,20 @@ i%22); -%0A DNedTool(%22Calendar%22, %22pixabay.com/static/uploads/photo/2016/01/20/10/52/maintenance-1151312_960_720.png%22); + Not working %0A @@ -1619,24 +1619,126 @@ 720.png%0A %0A + DNedTool(%22Piano%22, %22http://www.publicdomainpictures.net/pictures/30000/velka/piano-notes.jpg%22);%0A %0A NedGames(
e95bf23b70d78e91e22b26eaaa60a7e1f96d875a
add test
test/unittest.js
test/unittest.js
/*jslint node: true */ "use strict"; var assert = require("assert"); var PDCP = require("../lib/pdcp"); var e_key = new Buffer([0xb0, 0x8c, 0x70, 0xcf, 0xbc, 0xb0, 0xeb, 0x6c, 0xab, 0x7e, 0x82, 0xc6, 0xb7, 0x5d, 0xa5, 0x20, 0x72, 0xae, 0x62, 0xb2, 0xbf, 0x4b, 0x99, 0x0b, 0xb8, 0x0a, 0x48, 0xd8, 0x14, 0x1e, 0xec, 0x07]); var i_key = new Buffer([0xbf, 0x77, 0xec, 0x55, 0xc3, 0x01, 0x30, 0xc1, 0xd8, 0xcd, 0x18, 0x62, 0xed, 0x2a, 0x4c, 0xd2, 0xc7, 0x6a, 0xc3, 0x3b, 0xc0, 0xc4, 0xce, 0x8a, 0x3d, 0x3b, 0xbd, 0x3a, 0xd5, 0x68, 0x77, 0x92]); describe('PDCP', function() { it('shoud decrypt the google code example', function(done) { var enc_price = 'SjpvRwAB4kB7jEpgW5IA8p73ew9ic6VZpFsPnA'; var dec_price = PDCP.decrypt(e_key, i_key, enc_price); assert.equal(709959680, dec_price); done(); }); it('shoud crypt the google code example with different result', function(done) { var price = 709959680; var enc_price = PDCP.crypt(e_key, i_key, price); assert.notEqual('SjpvRwAB4kB7jEpgW5IA8p73ew9ic6VZpFsPnA', enc_price); done(); }); it('shoud crypt/decrypt properly', function(done) { var price = 709959680; var enc_price = PDCP.crypt(e_key, i_key, price); var dec_price = PDCP.decrypt(e_key, i_key, enc_price); assert.equal(price, dec_price); done(); }); it('crypt same price twice provide diferent result', function(done) { var price = 10000000; var enc_price1 = PDCP.crypt(e_key, i_key, price); var enc_price2 = PDCP.crypt(e_key, i_key, price); assert.notEqual(enc_price1, enc_price2); done(); }); it('crypt/decrypt 1000 random number', function(done) { var price; for(var i=0; i< 1000; i++){ price = Math.floor(Math.random()*1000000000); var enc_price = PDCP.crypt(e_key, i_key, price); var dec_price = PDCP.decrypt(e_key, i_key, enc_price); assert.equal(price, dec_price); } done(); }); });
JavaScript
0.000002
@@ -1546,24 +1546,427 @@ e();%0A%09%7D);%0A%0A%0A +%09it('crypt same price twice with same iv provide diferent result', function(done) %7B%0A%09%09var price = 10000000;%0A%09%09var iv = new Buffer(%5B0x00, 0x8c, 0x70, 0xcf, 0xbc, 0xb0, 0xeb, 0x6c, 0xab, 0x7e, 0x82, 0xc6, 0xb7, 0x5d, 0xa5, 0x21%5D);%0A%09%09var enc_price1 = PDCP.crypt(e_key, i_key, price, iv);%0A%09%09var enc_price2 = PDCP.crypt(e_key, i_key, price, iv);%0A%09%09assert.notEqual(enc_price1, enc_price2);%0A%09%09done();%0A%09%7D);%0A%0A%0A %09it('crypt/d @@ -2002,32 +2002,32 @@ unction(done) %7B%0A - %09%09var price;%0A%09%09f @@ -2214,17 +2214,16 @@ price);%0A -%0A %09%09%09asser @@ -2249,17 +2249,16 @@ price);%0A -%0A %09%09%7D%0A%09%09do
9c3dd9d7c6c9843aa4e17e67bc7172e77f59a483
Make ShowCard a clickable link to show details page.
js/ShowCard.js
js/ShowCard.js
import React from 'react' const { shape, string } = React.PropTypes const ShowCard = React.createClass({ // propTypes are things I expect to get from my parent. propTypes: { show: shape({ poster: string, title: string, year: string, description: string }) }, render () { const { poster, title, year, description } = this.props.show return ( <div className='show-card'> <img src={`/public/img/posters/${poster}`} /> <div> <h3>{title}</h3> <h4>({year})</h4> <p>{description}</p> </div> </div> ) } }) export default ShowCard
JavaScript
0
@@ -19,16 +19,53 @@ 'react'%0A +import %7B Link %7D from 'react-router'%0A%0A const %7B @@ -309,16 +309,38 @@ ription: + string,%0A imdbID: string%0A @@ -410,16 +410,24 @@ cription +, imdbID %7D = thi @@ -452,16 +452,57 @@ eturn (%0A + %3CLink to=%7B%60/details/$%7BimdbID%7D%60%7D%3E%0A %3Cd @@ -527,16 +527,18 @@ -card'%3E%0A + @@ -595,14 +595,18 @@ + + %3Cdiv%3E%0A + @@ -638,16 +638,18 @@ + %3Ch4%3E(%7Bye @@ -668,16 +668,18 @@ + + %3Cp%3E%7Bdesc @@ -691,16 +691,33 @@ on%7D%3C/p%3E%0A + %3C/div%3E%0A @@ -727,27 +727,28 @@ iv%3E%0A %3C/ -div +Link %3E%0A )%0A %7D%0A
655bfda8ff9e9b0e15abe52c164945761c7d1b81
Add defualt grunt task -> `tdd`
grunt/aliases.js
grunt/aliases.js
module.exports = { // Linting // ------------------------- lint: ['jshint:all'], // Testing // ------------------------- test: ['karma:unit'], coverage: ['karma:coverage'], tdd: ['karma:tdd'] };
JavaScript
0.000026
@@ -195,13 +195,76 @@ ma:tdd'%5D +,%0A%0A%0A%09// Default%0A%09// -------------------------%0A%09default: %5B'tdd'%5D %0A%0A%7D;%0A
e940fa22df15dcb59f44fff0e8e7b56bac1d528a
Update 'query' key to 'influxql'
ui/src/dashboards/actions/index.js
ui/src/dashboards/actions/index.js
import { getDashboards as getDashboardsAJAX, updateDashboard as updateDashboardAJAX, deleteDashboard as deleteDashboardAJAX, updateDashboardCell as updateDashboardCellAJAX, addDashboardCell as addDashboardCellAJAX, deleteDashboardCell as deleteDashboardCellAJAX, } from 'src/dashboards/apis' import {publishNotification} from 'shared/actions/notifications' import {publishAutoDismissingNotification} from 'shared/dispatchers' import {NEW_DEFAULT_DASHBOARD_CELL} from 'src/dashboards/constants' import { TEMPLATE_VARIABLE_SELECTED, } from 'shared/constants/actionTypes' export const loadDashboards = (dashboards, dashboardID) => ({ type: 'LOAD_DASHBOARDS', payload: { dashboards, dashboardID, }, }) export const setTimeRange = timeRange => ({ type: 'SET_DASHBOARD_TIME_RANGE', payload: { timeRange, }, }) export const updateDashboard = dashboard => ({ type: 'UPDATE_DASHBOARD', payload: { dashboard, }, }) export const deleteDashboard = dashboard => ({ type: 'DELETE_DASHBOARD', payload: { dashboard, }, }) export const deleteDashboardFailed = dashboard => ({ type: 'DELETE_DASHBOARD_FAILED', payload: { dashboard, }, }) export const updateDashboardCells = (dashboard, cells) => ({ type: 'UPDATE_DASHBOARD_CELLS', payload: { dashboard, cells, }, }) export const syncDashboardCell = (dashboard, cell) => ({ type: 'SYNC_DASHBOARD_CELL', payload: { dashboard, cell, }, }) export const addDashboardCell = (dashboard, cell) => ({ type: 'ADD_DASHBOARD_CELL', payload: { dashboard, cell, }, }) export const editDashboardCell = (dashboard, x, y, isEditing) => ({ type: 'EDIT_DASHBOARD_CELL', // x and y coords are used as a alternative to cell ids, which are not // universally unique, and cannot be because React depends on a // quasi-predictable ID for keys. Since cells cannot overlap, coordinates act // as a suitable id payload: { dashboard, x, // x-coord of the cell to be edited y, // y-coord of the cell to be edited isEditing, }, }) export const renameDashboardCell = (dashboard, x, y, name) => ({ type: 'RENAME_DASHBOARD_CELL', payload: { dashboard, x, // x-coord of the cell to be renamed y, // y-coord of the cell to be renamed name, }, }) export const deleteDashboardCell = cell => ({ type: 'DELETE_DASHBOARD_CELL', payload: { cell, }, }) export const editCellQueryStatus = (queryID, status) => ({ type: 'EDIT_CELL_QUERY_STATUS', payload: { queryID, status, }, }) export const templateSelected = (dashboardID, templateID, values) => ({ type: TEMPLATE_VARIABLE_SELECTED, payload: { dashboardID, templateID, values, }, }) export const editTemplate = (dashboardID, templateID, updates) => ({ type: 'EDIT_TEMPLATE', payload: { dashboardID, templateID, updates, }, }) // Stub Template Variables Data const templates = [ { id: '1', type: 'query', label: 'test query', code: '$REGION', query: { db: 'db1', rp: 'rp1', measurement: 'm1', query: 'SHOW TAGS WHERE HUNTER = "coo"', }, values: [ {value: 'us-west', type: 'tagKey', selected: false}, {value: 'us-east', type: 'tagKey', selected: true}, {value: 'us-mount', type: 'tagKey', selected: false}, ], }, { id: '2', type: 'csv', label: 'test csv', code: '$TEMPERATURE', values: [ {value: '98.7', type: 'measurement', selected: false}, {value: '99.1', type: 'measurement', selected: false}, {value: '101.3', type: 'measurement', selected: true}, ], }, ] // Async Action Creators export const getDashboardsAsync = dashboardID => async dispatch => { try { const {data: {dashboards}} = await getDashboardsAJAX() const stubbedDashboards = dashboards.map(d => ({...d, templates})) dispatch(loadDashboards(stubbedDashboards, dashboardID)) } catch (error) { console.error(error) throw error } } export const putDashboard = dashboard => dispatch => { updateDashboardAJAX(dashboard).then(({data}) => { dispatch(updateDashboard({...data, templates})) }) } export const updateDashboardCell = (dashboard, cell) => dispatch => { return updateDashboardCellAJAX(cell).then(({data}) => { dispatch(syncDashboardCell(dashboard, data)) }) } export const deleteDashboardAsync = dashboard => async dispatch => { dispatch(deleteDashboard(dashboard)) try { await deleteDashboardAJAX(dashboard) dispatch( publishAutoDismissingNotification( 'success', 'Dashboard deleted successfully.' ) ) } catch (error) { dispatch(deleteDashboardFailed(dashboard)) dispatch( publishNotification( 'error', `Failed to delete dashboard: ${error.data.message}.` ) ) } } export const addDashboardCellAsync = dashboard => async dispatch => { try { const {data} = await addDashboardCellAJAX( dashboard, NEW_DEFAULT_DASHBOARD_CELL ) dispatch(addDashboardCell(dashboard, data)) } catch (error) { console.error(error) throw error } } export const deleteDashboardCellAsync = cell => async dispatch => { try { await deleteDashboardCellAJAX(cell) dispatch(deleteDashboardCell(cell)) } catch (error) { console.error(error) throw error } }
JavaScript
0
@@ -3113,21 +3113,24 @@ ,%0A -query +influxql : 'SHOW
c64ac0a237b29cf8315a042db8a3536ca9e857ab
Add a condition for the end of a subreddit.
js/behavior.js
js/behavior.js
document.getElementById( 'settings' ).onclick = function( e ) { $( '.bubble' ).toggle(); e.stopPropagation(); return false; }; document.onclick = function() { $( '.bubble' ).hide(); }; $( '.bubble' ).click( function( e ) { e.stopPropagation(); } ); var items = [], current = -1, downloading = false; var subreddit = document.body.id.split( '_' )[ 1 ]; var first = -1; function loadPost( name ) { if ( downloading ) { return; } console.log( 'Loading post ' + name ); downloading = true; $.get( 'post.php', { name: name }, function( post ) { downloading = false; items.splice( current + 1, 0, post.data.children[ 0 ] ); ++current; localRead[ name ] = undefined; process( next ); }, 'json' ); } function download( after, limit, callback ) { if ( downloading ) { return; } console.log( 'Loading new page after ' + after ); downloading = true; $.get( 'feed.php', { r: subreddit, after: after, limit: limit }, function( feed ) { downloading = false; items.push.apply( items, feed.data.children ); callback(); }, 'json' ); } function next() { if ( downloading ) { return; } ++current; update( next ); } function prev() { --current; if ( current < first ) { current = first; } update( prev ); } String.prototype.beginsWith = function( str ) { return this.substr( 0, str.length ) == str; }; function getImage( url ) { switch ( url.substr( -4 ).toLowerCase() ) { case '.gif': case '.jpg': case '.png': return url; } if ( url.beginsWith( 'http://imgur.com' ) || url.beginsWith( 'http://quickmeme.com' ) || url.beginsWith( 'http://qkme.me' ) ) { console.log( 'Converted to image: ' + url ); return 'imgur.php?url=' + encodeURIComponent( url ) + '&type=.jpg'; } return false; } function process( direction ) { var url = getImage( items[ current ].data.url ); var args = window.location.href.split( '#' ); if ( url === false ) { console.log( 'Skipping non-image ' + items[ current ].data.url ); return direction(); } else { items[ current ].data.url = url; } if ( isRead( items[ current ].data.name ) ) { console.log( 'Skipping read item ' + items[ current ].data.url ); return direction(); } if ( first == -1 ) { first = current; } if ( args.length > 1 ) { args[ 1 ] = items[ current ].data.name; window.location.href = args.join( '#' ); } else { window.location.href += '#' + items[ current ].data.name; } return render(); } function update( direction ) { if ( items.length <= current ) { var after = ''; if ( items.length ) { after = items[ items.length - 1 ].data.name; } download( after, 25, function () { process( direction ); } ); } else { process( direction ); } } var loadWait = false; function render() { var item = items[ current ].data; $( '#img' ).hide(); $( '#img' )[ 0 ].src = item.url; // this intentionally left unescaped; reddit sends this including HTML entities that must be rendered correctly // we trust reddit to do the escaping correctly $( 'h2' ).html( item.title ); $( '.reddit' )[ 0 ].href = 'http://reddit.com' + item.permalink; loadWait = setTimeout( function() { $( '#loading' ).fadeIn(); }, 500 ); } $( '#img' ).load( function() { clearTimeout( loadWait ); $( '#loading' ).hide(); $( '#img' ).show(); markAsRead( items[ current ].data.name ); } ); loadStorage(); var args = window.location.href.split( '#' ); if ( args.length > 1 ) { loadPost( args[ 1 ] ); } else { next(); } $( window ).keydown( function( e ) { switch ( e.keyCode ) { case 74: // j $( '.instructions' ).fadeOut(); localStorage.instructions = 'read'; next(); break; case 75: // k prev(); break; } } ); $( '#img' ).click( next ); if ( localStorage.instructions == 'read' ) { $( '.instructions' ).hide(); } $( '.instructions' ).click( function() { $( this ).fadeOut(); localStorage.instructions = 'read'; } ); var read, localRead; function isRead( name ) { // console.log( 'Checking if "' + name + '" is read' ); // console.log( read ); return typeof localRead[ name ] !== 'undefined'; } function markAsRead( name ) { // console.log( 'Marking ' + name + ' as read.' ); read[ name ] = true; saveStorage(); } function saveStorage() { if ( typeof( localStorage ) !== 'undefined' ) { // console.log( 'Saving to storage.' ); localStorage.read = JSON.stringify( read ); } } function loadStorage() { if ( typeof( localStorage ) !== 'undefined' ) { console.log( 'Local storage is supported' ); } else { console.log( 'Local storage is not supported' ); return; } if ( typeof localStorage.read === 'undefined' ) { console.log( 'Storage is empty.' ); localStorage.read = '{}'; } else { console.log( 'Loading from storage: ' ); } read = JSON.parse( localStorage.read ); localRead = JSON.parse( localStorage.read ); console.log( read ); }
JavaScript
0.000031
@@ -1109,16 +1109,55 @@ false;%0A + var prevlength = items.length;%0A @@ -1199,24 +1199,326 @@ children );%0A + var newlength = items.length;%0A%0A if ( prevlength == newlength ) %7B%0A // we ran out of pages%0A console.log( 'End of subreddit.' );%0A $( '#img' ).hide();%0A $( 'h2' ).html( '%3Cem%3EThis subreddit has no more content.%3C/em%3E' );%0A %7D%0A else %7B%0A call @@ -1521,24 +1521,34 @@ callback();%0A + %7D%0A %7D, 'json
b41bda569d96a516cf1374509e51ff2ea03070ae
Change method for check if pass dev parameter
js/electron.js
js/electron.js
/* jshint esversion: 6 */ "use strict"; const Server = require(__dirname + "/server.js"); const electron = require("electron"); const core = require(__dirname + "/app.js"); // Config var config = {}; // Module to control application life. const app = electron.app; // Module to create native browser window. const BrowserWindow = electron.BrowserWindow; // Keep a global reference of the window object, if you don't, the window will // be closed automatically when the JavaScript object is garbage collected. let mainWindow; function createWindow() { var electronOptionsDefaults = { width: 800, height: 600, x: 0, y: 0, darkTheme: true, webPreferences: { nodeIntegration: false, zoomFactor: config.zoom }, backgroundColor: "#000000" } // DEPRECATED: "kioskmode" backwards compatibility, to be removed // settings these options directly instead provides cleaner interface if (config.kioskmode) { electronOptionsDefaults.kiosk = true; } else { electronOptionsDefaults.fullscreen = true; electronOptionsDefaults.autoHideMenuBar = true; } var electronOptions = Object.assign({}, electronOptionsDefaults, config.electronOptions); // Create the browser window. mainWindow = new BrowserWindow(electronOptions); // and load the index.html of the app. //mainWindow.loadURL('file://' + __dirname + '../../index.html'); mainWindow.loadURL("http://localhost:" + config.port); // Open the DevTools if run with "npm start dev" if(process.argv[2] == "dev") { mainWindow.webContents.openDevTools(); } // Set responders for window events. mainWindow.on("closed", function() { mainWindow = null; }); if (config.kioskmode) { mainWindow.on("blur", function() { mainWindow.focus(); }); mainWindow.on("leave-full-screen", function() { mainWindow.setFullScreen(true); }); mainWindow.on("resize", function() { setTimeout(function() { mainWindow.reload(); }, 1000); }); } } // This method will be called when Electron has finished // initialization and is ready to create browser windows. app.on("ready", function() { console.log("Launching application."); createWindow(); }); // Quit when all windows are closed. app.on("window-all-closed", function() { createWindow(); }); app.on("activate", function() { // On OS X it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (mainWindow === null) { createWindow(); } }); // Start the core application. // This starts all node helpers and starts the webserver. core.start(function(c) { config = c; });
JavaScript
0
@@ -1462,16 +1462,17 @@ dev%22%0A%09if + (process @@ -1480,21 +1480,25 @@ argv -%5B2%5D == +.includes( %22dev%22) +) %7B%0A%09
6c201e3999a0062a11bc613365a113512223be6b
Disable menu bar completely
js/electron.js
js/electron.js
import {app, BrowserWindow, Menu} from "electron"; // Keep a global reference of the window object, if you don't, the window will // be closed automatically when the JavaScript object is garbage collected. let mainWindow; function createWindow () { // This sets the initial window size. // If Sozi has been opened before, the size and location will be // loaded from local storage in backend/Electron.js. mainWindow = new BrowserWindow({ width: 800, height: 600, autoHideMenuBar: true, // Temporary fix for the non-removable menu bar. webPreferences: { nodeIntegration: true } }); if (process.env.SOZI_DEVTOOLS) { mainWindow.webContents.openDevTools(); } // Electron 6 provides a default menu bar that cannot be removed. // We keep it for a few default actions. const template = [ { label: "Sozi", submenu: [ {role: "quit"} ] } ]; Menu.setApplicationMenu(Menu.buildFromTemplate(template)); mainWindow.loadURL(`file://${__dirname}/../index.html`); // Emitted when the window is closed. mainWindow.on("closed", function () { // Dereference the window object, usually you would store windows // in an array if your app supports multi windows, this is the time // when you should delete the corresponding element. mainWindow = null; }); } // This method will be called when Electron has finished // initialization and is ready to create browser windows. // Some APIs can only be used after this event occurs. app.on("ready", createWindow); // Quit when all windows are closed. app.on("window-all-closed", function () { // On OS X it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== "darwin") { app.quit(); } }); app.on("activate", function () { // On OS X it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (mainWindow === null) { createWindow(); } });
JavaScript
0
@@ -495,88 +495,8 @@ 00,%0A - autoHideMenuBar: true, // Temporary fix for the non-removable menu bar.%0A @@ -517,16 +517,16 @@ nces: %7B%0A + @@ -566,24 +566,69 @@ %7D%0A %7D);%0A%0A + mainWindow.setMenuBarVisibility(false);%0A%0A if (proc @@ -703,339 +703,15 @@ ();%0A + %7D%0A%0A - // Electron 6 provides a default menu bar that cannot be removed.%0A // We keep it for a few default actions.%0A const template = %5B%0A %7B%0A label: %22Sozi%22,%0A submenu: %5B%0A %7Brole: %22quit%22%7D%0A %5D%0A %7D%0A %5D;%0A Menu.setApplicationMenu(Menu.buildFromTemplate(template));%0A%0A
5c443285c890162e9c9654bad8e9d116654a12d5
fix a warning
js/extended.js
js/extended.js
var extended = {}; // the object that contains the function to make the extended views extended.make = {} extended.make.response = function(context, json) { var key = responseCollectionName(json); var objs = key ? json[key] : []; var type = getType(key); if (! type) { return 'Unknown request type'; } var result = $('<div class="list"/>'); if ('links' in json) { result.append(render(context, json.links, 'links', 'links')); } objs.forEach(function(obj, i) { result.append(render(context, obj, type, key, i)); }); return result; } extended.make.journey = function(context, json) { if (! ('sections' in json)) { return $('No extended view for isochron'); } var result = $('<div class="list"/>'); json.sections.forEach(function(section, i) { result.append(render(context, section, 'section', 'sections', i)); }); return result; } extended.make.stop_schedule = function(context, json) { var result = $('<div class="list"/>'); json.date_times.forEach(function(stop_schedule, i) { result.append(render(context, stop_schedule, 'date_time', 'date_times', i)); }); return result; } extended.make.route_schedule = function(context, json) { var result = $('<div class="table"/>'); var table = $('<table/>'); // Add the data rows json.table.rows.forEach(function(route_schedule, i) { row = $(table[0].insertRow(-1)); var cellName = $("<td />").addClass("stop-point"); cellName.html(summary.run(context, 'stop_point', route_schedule.stop_point)); row.append(cellName); route_schedule.date_times.forEach(function(route_schedule, i) { var cellValue = $("<td />").addClass("time"); cellValue.html(summary.formatTime(route_schedule.date_time)); row.append(cellValue); }); }); result.append(table); return result; } // add your extended view by addind: // extended.make.{type} = function(context, json) { ... } extended.defaultExtended = function(context, type, json) { var noExt = 'No extended view yet!'; if (! (json instanceof Object)) { return noExt; } var empty = true; var result = $('<div class="list"/>'); for (var key in context.links) { if (! (key in json)) { continue; } empty = false; var type = getType(key); if ($.isArray(json[key])) { json[key].forEach(function(obj, i) { result.append(render(context, obj, type, key, i)); }); } else { result.append(render(context, json[key], type, key)); } } if (empty) { return noExt; } else { return result; } } // main method extended.run = function(context, type, json) { if (type in this.make) { return this.make[type](context, json); } return extended.defaultExtended(context, type, json); }
JavaScript
0.999951
@@ -2357,41 +2357,8 @@ se;%0A - var type = getType(key);%0A @@ -2481,36 +2481,44 @@ r(context, obj, -type +getType(key) , key, i));%0A @@ -2599,20 +2599,28 @@ n%5Bkey%5D, -type +getType(key) , key));
a53a94b87b066dfde5723a1a7fb8f2ae27f015f9
add image lazyload
js/get_data.js
js/get_data.js
$(function() { $.getJSON("https://mywebservice.info/beautyUniversity/data_out.php", function(data) { var str = ""; for (var i = data.length - 1; i >= 0; i--) { str += "<p><img data-src='"+"https://graph.facebook.com/"+ data[i]["object_id"] + "/picture"+ "' width='300' height='200'></p>"; } $("#main-content").append(str); }); });
JavaScript
0.000002
@@ -8,16 +8,60 @@ ion() %7B%0A +%09$('#marker').on('lazyshow', function () %7B%0A%09 %09$.getJS @@ -141,16 +141,17 @@ ta) %7B%0A%09%09 +%09 var str @@ -156,16 +156,17 @@ r = %22%22;%0A +%09 %09%09for (v @@ -204,16 +204,17 @@ i--) %7B%0A +%09 %09%09%09str + @@ -343,11 +343,13 @@ ;%0A%09%09 +%09 %7D%0A%0A +%09 %09%09$( @@ -379,15 +379,166 @@ (str);%0A%09 +%09%09$(window).lazyLoadXT();%0A %09%09%09$('#marker').lazyLoadXT(%7BvisibleOnly: false, checkDuplicates: false%7D);%0A%09%09%7D);%0A%09 %7D).lazyLoadXT(%7BvisibleOnly: false %7D);%0A%7D);
4265cd00928484fa67ced8d79dda64a1f3d78bc8
Fix humanized editor injection time. Update humanized editor value after image insert dialog background is closed.
js/humanize.js
js/humanize.js
(function () { var originalEditorSelector = '#postingHtmlBox'; function switchToHtmlMode() { var composeModeButtonSelector = 'span.tabs button:first-of-type()'; var composeModeIsOn = $(composeModeButtonSelector).attr('aria-selected') === 'true'; if (composeModeIsOn) { var htmlModeButtonSelector = 'span.tabs button:last-of-type()'; $(htmlModeButtonSelector).trigger('click'); } // Turn off original editor mode switching. $('span.tabs').hide(); } function createHumanizedEditor() { // Copy original post wrapper and put new editor there. // TODO: replace with .after(). $('.boxes').append('<div id="humanizedEditorWrapper" class="editor htmlBoxWrapper"></div>'); var humanizedEditor = ace.edit('humanizedEditorWrapper'); return humanizedEditor; } function configureHumanizedEditor(humanizedEditor) { // TODO: Check and fix html-worker loading issue. humanizedEditor.getSession().setUseWorker(false); humanizedEditor.getSession().setMode('ace/mode/html'); humanizedEditor.setTheme('ace/theme/monokai'); humanizedEditor.getSession().setUseWrapMode(true); humanizedEditor.setFontSize(13); humanizedEditor.setShowPrintMargin(false); humanizedEditor.on('change', function () { // Update original textarea value, which will be posted on post Update. var humanhumanizedEditorValue = humanizedEditor.getValue(); $(originalEditorSelector).val(humanhumanizedEditorValue); }); } function updateHumanizedEditorValue(humanizedEditor) { var originalEditorValue = $(originalEditorSelector).val(); var humanizedEditorValue = humanizedEditor.getValue(); if (originalEditorValue.length > 0 && originalEditorValue !== humanizedEditorValue) { //originalEditorValue = vkbeautify.xml(originalEditorValue); humanizedEditor.setValue(originalEditorValue, 1); } } // TODO: Intercept image add function humanizeHtmlEditor() { // TODO: Fix. Button attributes do not exist at this moment. // switchToHtmlMode(); var humanizedEditor = createHumanizedEditor(); configureHumanizedEditor(humanizedEditor); updateHumanizedEditorValue(humanizedEditor); var originalEditorContainerSelector = 'div.GCUXF0KCL5'; // TODO: Replace with observer. $(document).on('DOMSubtreeModified', originalEditorContainerSelector, function () { updateHumanizedEditorValue(humanizedEditor) }); } function isMutatedNodeContainsOriginalEditor(node) { return node.className === 'postsNew'; } var bloggerObserver = new MutationObserver(function (mutations) { mutations.forEach(function (mutation) { if (mutation.addedNodes.length > 0 && isMutatedNodeContainsOriginalEditor(mutation.addedNodes[0])) { // At this moment all data needed for humanized editor creation presented on the page. humanizeHtmlEditor(); bloggerObserver.disconnect(); } }); }); var configuration = { childList: true, subtree: true }; bloggerObserver.observe(document.body, configuration); })();
JavaScript
0
@@ -2053,41 +2053,8 @@ %7D%0A%0A - // TODO: Intercept image add%0A @@ -2375,177 +2375,414 @@ itor -ContainerSelector = 'div.GCUXF0KCL5';%0A // TODO: Replace with observer.%0A $(document).on('DOMSubtreeModified', originalEditorContainerSelector, function () %7B +Observer = new MutationObserver(function (mutations) %7B%0A mutations.forEach(function (mutation) %7B%0A // Posts switch.%0A var originalEditorID = 'postingHtmlBox';%0A if (mutation.target.id === originalEditorID &&%0A mutation.attributeName === 'disabled' &&%0A mutation.target.disabled === false) %7B%0A upd @@ -2825,121 +2825,702 @@ tor) - %7D) ;%0A -%7D%0A%0A function isMutatedNodeC + %7D%0A%0A // Image insert.%0A var imageUploadDialogBackgroundClass = 'modal-dialog-bg';%0A if (mutation.target.className === imageUploadDialogBackgroundClass &&%0A mutati on +. ta -insOriginalEditor(node) %7B%0A return node.className === 'postsNew' +rget.nodeName === 'DIV' &&%0A mutation.attributeName === 'style' &&%0A mutation.target.style.display === 'none') %7B%0A console.log(mutation);%0A updateHumanizedEditorValue(humanizedEditor);%0A %7D%0A %7D);%0A%0A %7D);%0A var configuration = %7B attributes: true, subtree: true %7D;%0A originalEditorObserver.observe(document.body, configuration) ;%0A @@ -3658,68 +3658,89 @@ -if (mutation.addedNodes.length %3E 0 && isMutatedNodeC +var originalEditorID = %22postingHtmlBox%22;%0A if (mutati on +. ta -insO +rget.id === o rigi @@ -3748,17 +3748,22 @@ alEditor -( +ID && mutation @@ -3768,21 +3768,73 @@ on.a -ddedNodes%5B0%5D) +ttributeName === %22disabled%22 && mutation.target.disabled === false ) %7B%0A @@ -4051,24 +4051,59 @@ );%0A %7D);%0A%0A + // TODO: Add attribute filter.%0A var conf @@ -4120,17 +4120,18 @@ = %7B -childList +attributes : tr
1c4fcdaf7c8a3ff1af3c1e59ced0f3b6a251f3a5
add click event for wind tap
js/mod/wind.js
js/mod/wind.js
window.Wind = (function (undefined) { 'use strict'; function _calculateRotate (p_touch_x, p_touch_y, p_target_x, p_target_y) { var _PI = Math.atan2(p_touch_x - p_target_x, p_touch_y - p_target_y); return (2 - (_PI/Math.PI + 1))*180; } return function (opt) { var options = { rotate: function () {}, tap: function () {}, panel: document.querySelector('.time-panel'), plate: document.querySelector('.upside'), main: document.querySelector('.main'), alarmPointer: document.querySelector('.time-alarm') }; if (typeof opt === 'function') { options.tap = opt; } else { for (var key in opt) { options[key] = opt[key]; } } var touch = false; options.main.addEventListener('touchmove', rotate, false); options.main.addEventListener('touchend', touchUp, false); options.main.addEventListener('touchcancel', touchUp, false); // to rotate the alarm pointer on move touch. function rotate (p_event) { p_event.preventDefault(); touch = true; options.alarmPointer.style.display = 'block'; var touchPos = p_event.touches[0]; var rotate = _calculateRotate(touchPos.pageX, touchPos.pageY, options.plate.clientWidth*0.5, options.plate.clientHeight*0.5); _setRotateStyle(rotate); } function touchUp (p_event) { p_event.preventDefault(); if (touch) { _touch(p_event); } else { _tap(p_event); } } function _touch (p_event) { touch = false; options.alarmPointer.style.display = 'none'; var _transform = options.alarmPointer.style.transform; var _rotate = /(rotate[\s]*\()([\d.]+)/.exec(_transform); if (_rotate && _rotate[2]) { var angle = _rotate[2]; options.rotate(angle); } } function _tap (p_event) { options.tap(p_event); } function _setRotateStyle (p_rotate) { var _prefix = ['webkit', 'moz', 'ms', 'o', '']; for (var i = 0; i < _prefix.length; i++) { if (_prefix[i].length > 0) { _prefix[i] = '-' + _prefix[i] + '-'; } options.alarmPointer.style[_prefix[i] + 'transform'] = 'rotate(' + p_rotate + 'deg)'; } } function _setAlarm (angle) { var ALARM_NAME = 'only_alarm'; var _alarmTime = new Date(); var _alarmSeconds = (angle/360 + 1)*12*60*60*1000; _alarmTime.setHours(0); _alarmTime.setMinutes(0); _alarmTime.setSeconds(0); _alarmTime.setMilliseconds(_alarmSeconds); if (_alarmTime.getTime() < (new Date()).getTime()) {// past time _alarmTime.setHours(_alarmTime.getHours() + 12); } var _addAlarm = navigator.mozAlarms.add(_alarmTime, ALARM_NAME); _addAlarm.onsuccess = function () { this.result.forEach(function (p_alarm) { alert(p_alarm.date); }); }; } } })();
JavaScript
0
@@ -1070,24 +1070,89 @@ Up, false);%0D +%0A options.main.addEventListener('click', touchUp, false);%0D %0A%0D%0A /
455c44730fec831837d2ec29551d09e442b8e401
Increase the pipe gap to deal with clunky hit boxes
js/obstacle.js
js/obstacle.js
function createObstacle(obstacleId, scoreManager) { return { /** * Internal properties, DO NOT write directly to them, used to maintain internal state. **/ props: { id: obstacleId, upperPipe: null, lowerPipe: null, randomChunk: -1, position: -300, hasPassed: false }, init: function() { var minChunk = Math.ceil(2); var maxChunk = Math.floor(8); this.props.randomChunk = Math.floor(Math.random() * (maxChunk - minChunk + 1)) + minChunk; this.rescale(); return this; }, /** * Updates the location of the obstacle on the x-axis from right to left. * The renderer calls this method every tick to create a forward moving animation. */ applyMovement: function() { var CHARACTER_BODY_OFFSET = 75; // Transform scale offset in px. if (!this.props.hasPassed && (window.innerWidth / 2) + CHARACTER_BODY_OFFSET <= this.props.position) { scoreManager.incrementScore(); this.props.hasPassed = true; } this.props.position = (this.props.position += 2); this.props.lowerPipe.x = this.props.position; this.props.upperPipe.x = this.props.position; var elArr = document.querySelectorAll(`#game #obstacle-${this.props.id} #pipe-${this.props.id}`); elArr[0].style.right = this.props.position + "px"; elArr[1].style.right = this.props.position + "px"; }, /** * Inserts the obstacle (parent div and children) into the DOM. **/ insert: function() { var obstacleDiv = document.createElement('div'); obstacleDiv.id = `obstacle-${this.props.id}`; // TODO: Consolidate this into just one DOM write. document.getElementById('game').appendChild(obstacleDiv); document.getElementById(obstacleDiv.id).insertAdjacentHTML('beforeend', this.props.lowerPipe.svg); document.getElementById(obstacleDiv.id).insertAdjacentHTML('beforeend', this.props.upperPipe.svg); }, /** * Removes the obstacle (parent div and children) from the DOM. **/ remove: function() { var el = document.querySelector(`#obstacle-${this.props.id}`); el.parentNode.removeChild(el); }, /** * Utility method that rescales the pipe length based on any changes to the viewport height. * For example, if the user scales their viewport down and the pipes now overlap and need rescaled. **/ rescale: function() { var PIPE_GAP_OFFSET = 320; // Accounts for pipe header, and gap. var PIPE_SCALE_BY = 0.75; // Scale constant, must change if SVG transform changes. var totalPipeHeight = window.innerHeight - PIPE_GAP_OFFSET; var firstPipeHeight = (totalPipeHeight / 10) * this.props.randomChunk; var secondPipeHeight = totalPipeHeight - firstPipeHeight; if (this.props.randomChunk % 2 == 0) { this.props.lowerPipe = { x: -300, y: window.innerHeight, height: ((firstPipeHeight + 40) * PIPE_SCALE_BY), width: 208 * PIPE_SCALE_BY, svg: this.createObstacleSVG(firstPipeHeight, false) }; this.props.upperPipe = { x: -300, y: 0, height: ((secondPipeHeight + 40) * PIPE_SCALE_BY), width: 208 * PIPE_SCALE_BY, svg: this.createObstacleSVG(secondPipeHeight, true) }; } else { this.props.upperPipe = { x: -300, y: 0, height: ((firstPipeHeight + 40) * PIPE_SCALE_BY), width: 208 * PIPE_SCALE_BY, svg: this.createObstacleSVG(firstPipeHeight, true) }; this.props.lowerPipe = { x: -300, y: window.innerHeight, height: ((secondPipeHeight + 40) * PIPE_SCALE_BY), width: 208 * PIPE_SCALE_BY, svg: this.createObstacleSVG(secondPipeHeight, false) }; } }, /** * Utility method that dynamically generates the obstacle (pipe) SVG given some information. * For example, if we want to generate an upside down pipe, or maybe we want to rescale a pipe. **/ createObstacleSVG: function(pipeHeight, isUpper) { return ` <svg id="pipe-${this.props.id}" width="208" height="${pipeHeight + 40}" viewBox="0 0 208 ${pipeHeight + 40}" class="${isUpper == true ? "upper-pipe" : "lower-pipe"}"> <g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"> <g id="pipe" transform="translate(8.000000, 56.000000)"> <g id="pipe-border" fill="#333333"> <rect x="0" y="0" width="8" height="${pipeHeight}"></rect> <rect x="184" y="0" width="8" height="${pipeHeight}"></rect> <rect x="8" y="0" width="176" height="8"></rect> </g> <rect fill="#3399FF" x="32" y="8" width="8" height="${pipeHeight}"></rect> <rect fill="#3399FF" x="48" y="8" width="96" height="${pipeHeight}"></rect> <rect fill="#3399FF" x="152" y="8" width="8" height="${pipeHeight}"></rect> <rect fill="#59ACFF" x="8" y="8" width="24" height="${pipeHeight}"></rect> <rect fill="#59ACFF" x="40" y="8" width="8" height="${pipeHeight}"></rect> <rect fill="#0066CC" x="160" y="8" width="24" height="${pipeHeight}"></rect> <rect fill="#0066CC" x="144" y="8" width="8" height="${pipeHeight}"></rect> </g> <g id="pipe-wider"> <path d="M0,0 L208,0 L208,56 L0,56 L0,0 Z M8,8 L200,8 L200,48 L8,48 L8,8 Z" id="pipe-border-wider" fill="#333333"></path> <rect fill="#59ACFF" x="8" y="8" width="24" height="40"></rect> <rect fill="#59ACFF" x="40" y="8" width="8" height="40"></rect> <rect fill="#3399FF" x="48" y="8" width="112" height="40"></rect> <rect fill="#3399FF" x="168" y="8" width="8" height="40"></rect> <rect fill="#3399FF" x="32" y="8" width="8" height="40"></rect> <rect fill="#0066CC" x="176" y="8" width="24" height="40"></rect> <rect fill="#0066CC" x="160" y="8" width="8" height="40"></rect> </g> </g> </svg>`; } }; }
JavaScript
0
@@ -2476,17 +2476,17 @@ FSET = 3 -2 +6 0; // Ac
755b0d9ad5e7a433b06b1107b86fb265f13e489a
修改 ChapterObj parse相關方法.
js/readfile.js
js/readfile.js
// 定義 TextContent function TextContent(content){ this.content = content || ""; } TextContent.prototype = { isEmpty : function () { return (this.content == "" || this.content == null); }, AddContent : function (content) { this.content += content; } } // 定義 ChapterObj function ChapterObj(title, content){ this.title = title || ""; this.originContent = new TextContent(content || ""); this.parsedContent = ""; this.parse = function () {}; } ChapterObj.prototype = { isEmpty : function () { return (this.isTitleEmpty() && this.isContentEmpty()); }, isTitleEmpty : function () { return (this.title == "" || this.title == null); }, isContentEmpty : function () { return (this.originContent.isEmpty()); }, print : function () { return this.title + "\n" + this.originContent.content + "\n"; }, AddContent : function (content) { this.originContent.AddContent(content); }, setParseFun : function (parseFunction) { this.parse = parseFunction; }, runParse : function () { this.parse(); } } function readFile() { var files = document.getElementById('datafile').files; if (!files.length) { alert('Please select a file!'); return; } var file = files[0]; var reader = new FileReader(); reader.onloadend = function(evt) { if (evt.target.readyState == FileReader.DONE) { // DONE == 2 var contentArea = document.getElementById('file_content'); var FileContens = evt.target.result; var resContent = parseFile(FileContens); contentArea.innerHTML = resContent.originalContent; contentArea.hidden = false; var parseArea = document.getElementById('parse_content'); parseArea.textContent = resContent.parseContent; parseArea.hidden = false; // 顯示 存檔按鈕 $("#button_save").show(); } }; reader.readAsText(file); } function saveFile() { var textToWrite = document.getElementById("parse_content").textContent; var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'}); var fileNameToSaveAs = "NewFile" // var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value; var downloadLink = document.createElement("a"); downloadLink.download = fileNameToSaveAs; downloadLink.innerHTML = "Download File"; if (window.webkitURL != null) { // Chrome allows the link to be clicked // without actually adding it to the DOM. downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob); } else { // Firefox requires the link to be added to the DOM // before it can be clicked. downloadLink.href = window.URL.createObjectURL(textFileAsBlob); downloadLink.onclick = destroyClickedElement; downloadLink.style.display = "none"; document.body.appendChild(downloadLink); } downloadLink.click(); } function destroyClickedElement(event) { document.body.removeChild(event.target); } function parseFile(FileContens) { var resultContent = { originalContent : "", parseContent : "" }; // 將檔案內容以行為單位儲存 var lines = FileContens.split('\n'); // 處理每一行的內容 for(var i = 0; i < lines.length; i++) { var line = lines[i]; var originalResult, parseResult; var start = '<font color="red">'; var end = '</font>'; if (isChapter(line)) { originalResult = start + line + end; parseResult = "<chapter> " + line; } else { originalResult = line; parseResult = line; } resultContent.originalContent = (resultContent.originalContent || "") + originalResult; resultContent.parseContent = (resultContent.parseContent || "") + parseResult + '\n'; } return resultContent; } function isChapter(str) { var patt = /(第?([0-9]|[零一二三四五六七八九十百千零壹貳參肆伍陸柒捌玖拾佰仟初兩])+章)|楔子/i; if(str.search(patt) != -1) { return true; } else { return false; } }
JavaScript
0
@@ -398,16 +398,41 @@ %7C%7C %22%22);%0A + this.parsedTitle = %22%22;%0A this.p @@ -463,16 +463,67 @@ is.parse +AllTitles = function () %7B%7D;%0A this.parseAllContents = funct @@ -1005,16 +1005,21 @@ %7D,%0A set +Title ParseFun @@ -1062,16 +1062,123 @@ is.parse +AllTitles = parseFunction;%0A %7D,%0A setContentParseFun : function (parseFunction) %7B%0A this.parseAllContents = parse @@ -1233,16 +1233,54 @@ is.parse +AllTitles();%0A this.parseAllContents ();%0A %7D%0A
078c32e3b8caf277ded636b9b772ae2baa8ae7d2
Remove cosole.log
js/services.js
js/services.js
var Service = function() {}; Service.prototype.get = function(options) { options = $.extend({ cache: true }, options); options.data = $.extend({}, this.defaults, options.data); var method = options.queue ? $.ajaxQueue : $.ajax; return method(options); }; var PubMed = function(options) { this.defaults = $.extend({}, options); this.url = $("link[rel='service.pubmed']").attr("href"); this.search = function(input) { var parts = [input.term]; $.each(input.filters, function(index, value) { if (value.enabled) { parts.push(index); } }); var data = { tool: "hubmed", email: "[email protected]", db: "pubmed", //sort: "pub date", usehistory: "y", retmax: 0, term: parts.join(" AND ") }; if (input.days) { data.reldate = input.days; data.dateType = "pdat"; } return this.get({ url: this.url + "esearch.fcgi", data: data }); }; this.related = function(input) { var parts = []; $.each(input.filters, function(index, value) { if (value.enabled) { parts.push(index); } }); var data = { tool: "hubmed", email: "[email protected]", db: "pubmed", cmd: "neighbor_history", linkname: "pubmed_pubmed", id: input.term.replace(/^related:/, ""), term: parts.join(" AND ") }; if (input.days) { data.reldate = input.days; data.dateType = "pdat"; } return this.get({ url: this.url + "elink.fcgi", data: data }); }; this.history = function(query, offset, limit) { var data = { tool: "hubmed", email: "[email protected]", db: "pubmed", rettype: "xml", webenv: query.webEnv, query_key: query.queryKey, retstart: offset, retmax: limit }; return this.get({ url: this.url + "efetch.fcgi", data: data }); }; }; PubMed.prototype = new Service(); var Altmetric = function(options) { this.defaults = $.extend({}, options); var node = $("link[rel='service.altmetric']"); this.url = node.attr("href"); this.key = node.data("key"); this.path = function(identifiers) { if (identifiers.doi) return "doi/" + identifiers.doi; if (identifiers.pmid) return "pmid/" + identifiers.pmid; return false; }; this.fetch = function(path){ var data = { key: this.key }; return this.get({ url: this.url + path, data: data, queue: false }); }; this.parse = function(data){ var id = encodeURIComponent(data.altmetric_id), items = [], mendeley_url; if (data.cited_by_blogs_count) { items.push({ url: "http://altmetric.com/details.php?citation_id=" + id, text: data.cited_by_blogs_count, image: "altmetric.png" }); } if (data.cited_by_tweeters_count){ items.push({ url: "http://altmetric.com/details.php?citation_id=" + id, text: data.cited_by_tweeters_count, image: "twitter.png" }); } data.readers.mendeley = Number(data.readers.mendeley); if (data.readers.mendeley) { if (data.pmid) mendeley_url = "http://www.mendeley.com/openURL?id=pmid:" + encodeURIComponent(data.pmid); else if (data.doi) mendeley_url = "http://www.mendeley.com/openURL?id=doi:" + encodeURIComponent(data.doi); else mendeley_url = "http://altmetric.com/details.php?citation_id=" + id; items.push({ url: mendeley_url, text: data.readers.mendeley, image: "mendeley.png" }); } return items; }; }; Altmetric.prototype = new Service(); var Scopus = function(options) { this.defaults = $.extend({}, options); var node = $("link[rel='service.scopus']"); this.url = node.attr("href"); this.key = node.data("key"); this.fetch = function(doi){ var data = { apiKey: this.key, search: "DOI(" + doi + ")" }; return this.get({ url: this.url + "documentSearch.url", data: data, dataType: "jsonp", queue: true }); }; this.parse = function(data) { if(!data.OK || !data.OK.results || !data.OK.results.length) return; var item = data.OK.results[0]; var citedbycount = Number(item.citedbycount); if(!citedbycount) return; return { url: item.inwardurl, text: citedbycount, image: "sciverse.png" }; }; }; Scopus.prototype = new Service(); var PMC = function(options) { this.defaults = $.extend({}, options); this.url = $("link[rel='service.pubmed']").attr("href"); this.fetch = function(doi){ var data = { tool: "hubmed", email: "[email protected]", db: "pmc", //sort: "pub date", usehistory: "n", retmax: 1, term: doi + "[DOI]" }; return this.get({ url: this.url + "esearch.fcgi", data: data }); }; this.parse = function(doc) { var template = { count: "/eSearchResult/Count", id: "/eSearchResult/IdList/Id" }; var data = Jath.parse(template, doc); console.log(data); if (!data.count || !data.id) return; return { url: "http://www.ncbi.nlm.nih.gov/pmc/articles/PMC" + data.id + "/", text: "", image: "oa.png" }; }; }; PMC.prototype = new Service();
JavaScript
0.000001
@@ -5630,35 +5630,8 @@ oc); -%0A console.log(data); %0A%0A
3b6bd3d6c1ed6640b0837577ac40846c35d8e7f7
Update spoilers.js
js/spoilers.js
js/spoilers.js
(function($) { 'use strict'; function init() { $('.spoilers-button').each(function() { var $this = $(this), $parent = $this.parent(), showMsg = $parent.attr('data-showtext') || mw.msg('spoilers_show_default'), hideMsg = $parent.attr('data-hidetext') || mw.msg('spoilers_hide_default'); $this .text($parent.children('.spolers-body:visible').length ? showMsg : hideMsg) .click(function() { $parent.children('.spoilers-button').text($parent.children('.spolers-body:visible').length ? hideMsg : showMsg); $parent.children('.spoilers-body').slideToggle(); }); }); } $(init); }(this.jQuery));
JavaScript
0
@@ -332,32 +332,33 @@ t.children('.spo +i lers-body:visibl
cc2ea98859556ebf1489f92b77fcf7e0dd390c0f
Simplify get
jsonpointer.js
jsonpointer.js
var console = require("console"); var traverse = function(obj, pointer, value) { // assert(isArray(pointer)) var part = unescape(pointer.shift()); if(typeof obj[part] === "undefined") { throw("Value for pointer '" + pointer + "' not found."); return; } if(pointer.length != 0) { // keep traversin! return traverse(obj[part], pointer, value); } // we're done if(typeof value === "undefined") { // just reading return obj[part]; } // set new value, return old value var old_value = obj[part]; if(value === null) { delete obj[part]; } else { obj[part] = value; } return old_value; } var validate_input = function(obj, pointer) { if(typeof obj !== "object") { throw("Invalid input object."); } if(!pointer) { throw("Invalid JSON pointer."); } } var get = function(obj, pointer) { validate_input(obj, pointer); if (pointer === "/") { return obj; } else { pointer = pointer.split("/").slice(1); return traverse(obj, pointer); } } var set = function(obj, pointer, value) { validate_input(obj, pointer); if (pointer === "/") { return obj; } else { pointer = pointer.split("/").slice(1); return traverse(obj, pointer, value); } } exports.get = get exports.set = set
JavaScript
0.000005
@@ -919,36 +919,27 @@ urn obj;%0A %7D - else %7B%0A +%0A - pointer = po @@ -957,34 +957,32 @@ (%22/%22).slice(1);%0A - return travers @@ -998,20 +998,16 @@ inter);%0A - %7D%0A %7D%0A%0Avar s
8ff339f08e827a4db4c856c40f09bd3342cecc5b
Add use strict directive
vendor/assets/javascripts/scrollinity.js
vendor/assets/javascripts/scrollinity.js
$(document).ready(function(){ function load_new_items(){ var sign = load_path.indexOf('?') >= 0 ? '&' : '?' $.get(load_path + sign + 'page=' + (++page_num), function(data, e) { if(data.length < 5) { var page_num = 0; return false; } data_container.append(data); }).complete(function() { loading_pic.hide(); }); } function loading_hidden(){ return !loading_pic.is(':visible'); } function near_bottom(){ return $(window).scrollTop() > $(document).height() - $(window).height() - bottom_px_limit; } if($('*[data-scrollinity-path]').length > 0) { var page_num = 1 var load_path = $('*[data-scrollinity-path]').data('scrollinity-path'); var loading_pic = $('*[data-scrollinity-loading-pic]'); var data_container = $('#' + $('*[data-scrollinity-data-container]').data('scrollinity-data-container')); var bottom_px_limit = $('*[data-scrollinity-bottom-px-limit]').data('scrollinity-bottom-px-limit'); $(window).on('scroll', function(){ if(loading_hidden() && near_bottom()) { if(page_num > 0) { loading_pic.show(); load_new_items(); } } }); } });
JavaScript
0.000004
@@ -24,16 +24,33 @@ ion()%7B%0A%0A + 'use strict';%0A%0A functi
11b8856af3fae78f548b88ce2f2f7ed59f9f313e
Add function cart_get_orders
public/app.js
public/app.js
function something() { // получаем значение из LocalStorage var x = window.localStorage.getItem('aaa'); //увеличиваем значение на 1 x = x*1 + 1; //устанавливаем значение ключа равному переменной window.localStorage.setItem('aaa',x); alert(x); } function add_to_cart(id) { var key = 'product_' + id; var x = window.localStorage.getItem(key); x = x * 1 + 1; window.localStorage.setItem(key, x); //вывод количества айтемов show_items(); } function show_items() { var total = 0; for (var i = 0; i < localStorage.length; i++){ var key = window.localStorage.key(i) // получаем ключ if (key.indexOf('product_')==0) //проверяем ключ на совпадение с нужным product_, если входжение с начала (0 позиция), то ключ наш. { total = total + window.localStorage.getItem(key)*1; //получаем значение их хеша по ключу и наращиваем total } } document.getElementById("cart").innerHTML = "Your cart contains " + total + " items"; }
JavaScript
0.000009
@@ -973,8 +973,467 @@ tems%22;%0A%7D +%0A%0Afunction cart_get_orders()%0A%7B%0A%09var orders = '';%0A%09for (var i = 0; i %3C localStorage.length; i++)%7B%0A %09var key = window.localStorage.key(i) // %D0%BF%D0%BE%D0%BB%D1%83%D1%87%D0%B0%D0%B5%D0%BC %D0%BA%D0%BB%D1%8E%D1%87%0A %09var value = window.localStorage.getItem(key); //%D0%BF%D0%BE%D0%BB%D1%83%D1%87%D0%B0%D0%B5%D0%BC %D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%0A %09if (key.indexOf('product_') == 0) //%D0%BF%D1%80%D0%BE%D0%B2%D0%B5%D1%80%D1%8F%D0%B5%D0%BC %D0%BA%D0%BB%D1%8E%D1%87 %D0%BD%D0%B0 %D1%81%D0%BE%D0%B2%D0%BF%D0%B0%D0%B4%D0%B5%D0%BD%D0%B8%D0%B5 %D1%81 %D0%BD%D1%83%D0%B6%D0%BD%D1%8B%D0%BC product_, %D0%B5%D1%81%D0%BB%D0%B8 %D0%B2%D1%85%D0%BE%D0%B4%D0%B6%D0%B5%D0%BD%D0%B8%D0%B5 %D1%81 %D0%BD%D0%B0%D1%87%D0%B0%D0%BB%D0%B0 (0 %D0%BF%D0%BE%D0%B7%D0%B8%D1%86%D0%B8%D1%8F), %D1%82%D0%BE %D0%BA%D0%BB%D1%8E%D1%87 %D0%BD%D0%B0%D1%88.%0A %09%7B%0A %09%09orders = orders + key + '=' + value + ','%0A %09%7D%0A%09%7D%0A%09return orders%0A%7D
aea72ac2517eb65f8c7e78f6f56a5167da19a912
Use element name for vulcanize
gulpfile.babel.js
gulpfile.babel.js
import gulp from 'gulp'; import del from 'del'; import webpack from 'webpack-stream'; import named from 'vinyl-named'; import csswring from 'csswring'; import autoprefixer from 'autoprefixer'; import wct from 'web-component-tester'; import notify from 'gulp-notify'; import vulcanize from 'gulp-vulcanize'; import gulpif from 'gulp-if'; import eslint from 'gulp-eslint'; import postcss from 'gulp-postcss'; import plumber from 'gulp-plumber'; import browserSync from 'browser-sync'; import { simplaImports, name as ELEMENT_NAME } from './bower.json'; import path from 'path'; const name = 'simpla-img', imports = simplaImports.map(dep => `../${dep}`), bs = browserSync.create(); // Get WCT going wct.gulp.init(gulp); const options = { webpack: { module: { loaders: [ { test: /\.js$/, loader: 'babel-loader' } ] } }, postcss: [ csswring(), autoprefixer() ], vulcanize: { inlineCss: true, inlineScripts: true, addedImports: imports }, browserSync: { server: { baseDir: './', index: 'demo/index.html', routes: { '/': './bower_components', [`/${ELEMENT_NAME}.html`]: `./${ELEMENT_NAME}.html` } }, open: false } }, errorNotifier = () => plumber({ errorHandler: notify.onError('Error: <%= error.message %>') }); gulp.task('process', () => { return gulp.src(['src/*/*.{html,js,css}', 'src/*.{html,js,css}']) .pipe(errorNotifier()) .pipe(gulpif('*.js', named(file => { let name = path.basename(file.path, path.extname(file.path)), parent = path.basename(path.dirname(file.path)); return parent === 'src' ? name : path.join(parent, name); }))) .pipe(gulpif('*.css', postcss(options.postcss))) .pipe(gulpif('*.js', eslint())) .pipe(gulpif('*.js', eslint.format())) .pipe(gulpif('*.js', eslint.failAfterError())) .pipe(gulpif('*.js', webpack(options.webpack))) .pipe(gulp.dest('.tmp')); }); gulp.task('build', ['process'], () => { return gulp.src([`.tmp/${name}/${name}.html`,`.tmp/${name}.html`]) .pipe(errorNotifier()) .pipe(vulcanize(options.vulcanize)) .pipe(gulp.dest('.')); }); gulp.task('clean', () => { return del([ '.tmp' ]); }); gulp.task('demo', (callback) => { gulp.watch('./*.{html,js}').on('change', bs.reload); return bs.init(options.browserSync); }); gulp.task('test', ['build', 'test:local']); gulp.task('watch', () => gulp.watch(['src/**/*'], ['build'])); gulp.task('default', ['build', 'demo', 'watch']);
JavaScript
0.000003
@@ -581,35 +581,8 @@ nst -name = 'simpla-img',%0A impo @@ -2253,20 +2253,36 @@ p/$%7B -name%7D/$%7Bname +ELEMENT_NAME%7D/$%7BELEMENT_NAME %7D.ht @@ -2293,20 +2293,28 @@ %60.tmp/$%7B -name +ELEMENT_NAME %7D.html%60%5D
c4be18dfea2e57c0dc9a904bc25b8ae6471c6e23
not not not not
public/js/main.js
public/js/main.js
var $ = require('jquery'); var Webrtc2images = require('webrtc2images'); var Fingerprint = require('fingerprintjs'); var crypto = require('crypto'); var music = require('./music'); var services = require('./services'); var socket = io(); var rtc = false; var mp4Support = false; rtc = new Webrtc2images({ width: 200, height: 150, frames: 10, type: 'image/png', interval: 200 }); var profile = { ip: false, fingerprint: new Fingerprint({ canvas: true }).get(), md5: false }; var testVideo = $('<video></video>')[0]; if (testVideo.canPlayType('video/mp4; codecs="avc1.42E01E"') || testVideo.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2')) { mp4Support = true; } var messages = $('#messages'); var body = $('body'); var doc = $(document); var messagesFiltered = $('#messages-filtered'); var filtered = $('#filtered'); var unmute = $('#unmute'); var invisible = $('#invisible'); var invisibleMode = $('#invisible-mode'); var form = $('form'); var sadBrowser = $('#sad-browser'); var active = $('#active'); var mutedFP = {}; var filteredFP = {}; try { mutedFP = JSON.parse(localStorage.getItem('muted')) || {}; } catch (err) { } try { filteredFP = JSON.parse(localStorage.getItem('filtered')) || {}; } catch (err) { } rtc.startVideo(function (err) { if (err) { rtc = false; } }); $('#music').click(music.toggle); filtered.click(function () { messagesFiltered.slideToggle('fast', function () { if (filtered.hasClass('on')) { filtered.removeClass('on'); } else { filtered.addClass('on'); } }); }); invisible.click(function () { if (!invisible.hasClass('on')) { invisibleMode.slideDown('fast'); invisible.addClass('on'); } else { invisibleMode.slideUp('fast'); invisible.removeClass('on'); } }); unmute.click(function (ev) { mutedFP = {}; localStorage.setItem('muted', JSON.stringify(mutedFP)); }); invisibleMode.on('click', 'button', function () { invisibleMode.slideUp('fast'); }); var submitting = false; if (!rtc && !mp4Support) { sadBrowser.show(); form.remove(); $('#video-preview').remove(); } form.submit(function (ev) { ev.preventDefault(); if (rtc && !submitting) { submitting = true; services.sendMessage(profile, rtc, function (submitted) { submitting = submitted; }); } }); messages.on('click', '.mute', function (ev) { ev.preventDefault(); var fp = $(this).closest('li').data('fp'); if (!mutedFP[fp]) { mutedFP[fp] = true; localStorage.setItem('muted', JSON.stringify(mutedFP)); body.find('li[data-fp="' + fp + '"]').remove(); } }); body.on('click', '.filter', function (ev) { ev.preventDefault(); var fp = $(this).closest('li').data('fp'); filteredFP[fp] = true; messages.find('li[data-fp="' + fp + '"] .filter').removeClass('filter') .addClass('unfilter') .text('unfilter'); localStorage.setItem('filtered', JSON.stringify(filteredFP)); }); body.on('click', '.unfilter', function (ev) { ev.preventDefault(); var fp = $(this).closest('li').data('fp'); delete filteredFP[fp]; localStorage.setItem('filtered', JSON.stringify(filteredFP)); messagesFiltered.find('li[data-fp="' + fp + '"]').remove(); messages.find('li[data-fp="' + fp + '"] .unfilter').removeClass('unfilter') .addClass('filter') .text('filter'); }); doc.on('visibilitychange', function (ev) { var hidden = document.hidden; $('video').each(function () { if (!hidden) { this.pause(); } else { this.play(); } }); }); socket.on('ip', function (data) { profile.ip = data; profile.md5 = crypto.createHash('md5').update(profile.fingerprint + data).digest('hex'); }); socket.on('active', function (data) { active.text(data); }); socket.on('message', function (data) { services.getMessage(data, mutedFP, filteredFP, profile, messages); });
JavaScript
0.998931
@@ -3635,17 +3635,16 @@ if ( -! hidden)
402146360112ecd5e3773d809a94b8aa1f5eef1b
test query strings
tests/inf_cli.js
tests/inf_cli.js
/* informix cli using nodejs-db-informix */ var readline = require('readline'), rl = readline.createInterface(process.stdin, process.stdout); /* * Connection configurations */ // var settings = JSON.parse(require('fs').readFileSync('./tests/db_conf.json','utf8')); var settings = { "host": "" , "user": "" , "password": "" , "database": "sysmaster" , "charset": "" // , "port": "" // , "compress": "" // , "initCommand": "" // , "readTimeout": "" // , "reconnect": "" // , "socket": "" // , "sslVerifyServer": "" // , "timeout": "" // , "writeTimeout": "" }; /* * Create a new Informix database bindings. Setup event callbacks. Connect to * the database. * c - connection */ function connect(settings) { if (!settings || typeof(settings) !== 'object') { throw new Error("No settings provided"); } /* * Create an Informix database nodejs object */ var bindings = require("../nodejs-db-informix"); console.log(bindings); var c = new bindings.Informix(settings); c.on('error', function(error) { console.log("Error: "); console.log(error); }).on('ready', function(server) { console.log("Connection ready to "); console.log(server); }).connect(function(err) { if (err) { throw new Error('Could not connect to DB'); } console.log('Connected to db with '); console.log(settings); console.log("isConnected() == " + c.isConnected()); this .on('each', function(e, idx, more) { console.log('each'); console.log(arguments); }) .on('success', function() { console.log('success'); console.log(arguments); }); /* var rs = this.query("select first 10 * from systables", function(s,r) { console.log(s); console.log(r); }).execute(); */ var rs = this .query( "select first 1 * from systables" , [] , function (status, results) { console.log('CALLBACK:'); // console.log(arguments); console.log("status:" + status); console.log(results); } , { start: function(q) { console.log('Query:'); console.log(q); } , finish: function(f) { console.log('Finish:'); console.log(f); } , async: true , cast: true } ) .execute(); }); return c; } function execQuery(conn,qry) { if (!conn || conn == undefined || conn == null) { throw Error("_main: connection is not valid"); } var rs = conn .query( qry , [] , function (status, results) { console.log('CALLBACK:'); // console.log(arguments); console.log("status:" + status); console.log(results); } , { start: function(q) { console.log('Query:'); console.log(q); } , finish: function(f) { console.log('Finish:'); console.log(f); } , async: true , cast: true } ) .execute(); return rs; } function _main () { var conn = connect(settings); if (!conn || conn == undefined || conn == null) { throw Error("_main: connection is not valid"); } console.log('connection:'); console.log(conn); rl.setPrompt('inf> '); rl.prompt(); rl.on('line', function(line) { var cmd = line.trim(); if (cmd == '' || cmd == undefined || cmd == null) { rl.prompt(); return; } var c_reg = /^\s*connect\s+(\w+)/; if (c_reg.test(cmd)) { var m = cmd.match(c_reg); var db = m[1]; if (db == null || db == undefined || db.trim() == '') { console.log("Invalid command: " + cmd); rl.prompt(); return; } conn.disconnect(); settings.database = db; conn = connect(settings); } else { execQuery(conn, cmd); } rl.prompt(); }).on('close', function() { console.log('Exit.'); }); } _main();
JavaScript
0.000723
@@ -2045,29 +2045,30 @@ %22 -select first +SELECT FIRST 1 +0 * -from +FROM sys @@ -2844,32 +2844,32 @@ )%0A - @@ -2877,24 +2877,1021 @@ execute();%0A%0A + /*%0A var rs = this%0A .query(%0A %22%22%0A , %5B%5D%0A , function (status, results) %7B%0A console.log('CALLBACK:');%0A // console.log(arguments);%0A console.log(%22status:%22 + status);%0A console.log(results);%0A %7D%0A , %7B%0A start: function(q) %7B%0A console.log('Query:');%0A console.log(q);%0A %7D%0A , finish: function(f) %7B%0A console.log('Finish:');%0A console.log(f);%0A %7D%0A , async: true%0A , cast: true%0A %7D%0A )%0A .select(%22*%22)%0A .first(10)%0A .from(%22systables%22, false)%0A .execute();%0A */%0A%0A %7D);%0A%0A
cd8b30435e2221e0cf35523eceafcfb7245dfec1
Print actual error message instead of generic type
site/Home.js
site/Home.js
/* global JSZip saveAs */ let haikunate = require('haikunator'); let url = require('url'); let base64url = require('base64-url'); import React from 'react'; import ReactDOM from 'react-dom'; import {isArray, forOwn, clone} from 'lodash'; import { createHistory, useQueries } from 'history'; import Header from './Header'; import Footer from './Footer'; import Platform from './sections/Platform'; import Framework from './sections/Framework'; import TemplateEngine from './sections/TemplateEngine'; import CssFramework from './sections/CssFramework'; import CssPreprocessor from './sections/CssPreprocessor'; import BuildTool from './sections/BuildTool'; import Database from './sections/Database'; import Authentication from './sections/Authentication'; import JsFramework from './sections/JsFramework'; import Theme from './sections/Theme'; import Deployment from './sections/Deployment'; class Home extends React.Component { constructor(props) { super(props); this.state = {}; this.handleChange = this.handleChange.bind(this); this.clickDownload = this.clickDownload.bind(this); } clickDownload() { let state = this.state; let downloadBtn = this.refs.downloadBtn; // Google Analytics event //ga("send","event","Customize","Download","Customize and Download") let data = clone(state); data.appName = haikunate({ tokenLength: 0 }); if (data.authentication) { data.authentication = Array.from(data.authentication); } $.ajax({ url: '/download', method: 'POST', contentType: 'application/json; charset=utf-8', data: JSON.stringify(data) }) .done((response, status, request) => { $(downloadBtn).removeAttr('disabled'); var disp = request.getResponseHeader('Content-Disposition'); if (disp && disp.search('attachment') != -1) { var form = $('<form method="POST" action="/download">'); $.each(data, function(k, v) { form.append($('<input type="hidden" name="' + k + '" value="' + v + '">')); }); $('body').append(form); form.submit(); } }) .fail(function(jqXHR) { window.notie.alert(3, jqXHR.statusText, 2.5); }); } handleChange(e) { let name = e.target.name; let value = e.target.value; let isChecked = e.target.checked; let state = clone(this.state); let refs = this.refs; switch (name) { case 'platformRadios': // Reset everything for (let key in state) { if (state.hasOwnProperty(key) ) { state[key] = null; } } state.platform = value; window.smoothScroll(refs.framework); break; case 'frameworkRadios': if (!state.framework) { window.smoothScroll(refs.templateEngine); } state.framework = value; break; case 'templateEngineRadios': if (!state.templateEngine) { window.smoothScroll(refs.cssFramework); } state.templateEngine = value; break; case 'cssFrameworkRadios': if (!state.cssFramework) { window.smoothScroll(refs.cssPreprocessor); } state.cssPreprocessor = null; state.cssFramework = value; break; case 'cssPreprocessorRadios': if (!state.cssPreprocessor) { window.smoothScroll(refs.jsFramework); } state.cssPreprocessor = value; break; case 'jsFrameworkRadios': if (!state.jsFramework) { window.smoothScroll(refs.buildTool); } state.jsFramework = value; break; case 'reactOptionsCheckboxes': state.reactOptions = state.reactOptions || new Set(); if (isChecked) { state.reactOptions.add(value); } else { state.reactOptions.delete(value); } break; case 'reactBuildSystemRadios': state.reactBuildSystem = value; break; case 'buildToolRadios': if (!state.buildTool) { window.smoothScroll(refs.database); } state.buildTool = value; break; case 'databaseRadios': if (!state.database) { window.smoothScroll(refs.authentication); } if (value === 'none' && state.authentication) { state.authentication.clear(); state.authentication.add('none'); } state.database = value; break; case 'authenticationCheckboxes': state.authentication = state.authentication || new Set(); if (isChecked) { if (value === 'none') { state.authentication.clear(); } else { state.authentication.add(value); } } else { state.authentication.delete(value); } break; case 'deploymentRadios': if (!state.deployment) { window.smoothScroll(refs.download); } state.deployment = value; break; } this.setState(state); } render() { let state = this.state; let platform = <Platform platform={state.platform} handleChange={this.handleChange} />; let framework = state.platform ? ( <Framework platform={state.platform} framework={state.framework} handleChange={this.handleChange} /> ) : null; let templateEngine = state.framework ? ( <TemplateEngine platform={state.platform} templateEngine={state.templateEngine} handleChange={this.handleChange} /> ) : null; let cssFramework = state.templateEngine ? ( <CssFramework cssFramework={state.cssFramework} handleChange={this.handleChange} /> ) : null; let cssPreprocessor = state.cssFramework ? ( <CssPreprocessor cssPreprocessor={state.cssPreprocessor} cssFramework={state.cssFramework} handleChange={this.handleChange} /> ) : null; let jsFramework = state.cssPreprocessor ? ( <JsFramework jsFramework={state.jsFramework} reactOptions={state.reactOptions} handleChange={this.handleChange} /> ) : null; let buildTool = state.jsFramework ? ( <BuildTool buildTool={state.buildTool} jsFramework={state.jsFramework} cssPreprocessor={state.cssPreprocessor} handleChange={this.handleChange} /> ) : null; let database = state.buildTool ? ( <Database database={state.database} handleChange={this.handleChange} /> ) : null; let authentication = state.database ? ( <Authentication database={state.database} authentication={state.authentication} handleChange={this.handleChange} /> ) : null; let deployment = (state.authentication || state.database === 'none')? ( <Deployment deployment={state.deployment} handleChange={this.handleChange} /> ) : null; let download = state.deployment ? ( <button ref="downloadBtn" className="btn btn-block btn-mega" onClick={this.clickDownload}>Compile and Download</button> ) : null; return ( <main> <Header /> <div className="container"> <br/> <div ref="platform">{platform}</div> <div ref="framework">{framework}</div> <div ref="templateEngine">{templateEngine}</div> <div ref="cssFramework">{cssFramework}</div> <div ref="cssPreprocessor">{cssPreprocessor}</div> <div ref="jsFramework">{jsFramework}</div> <div ref="buildTool">{buildTool}</div> <div ref="database">{database}</div> <div ref="authentication">{authentication}</div> <div ref="deployment">{deployment}</div> <div ref="download">{download}</div> <button ref="downloadBtn" className="btn btn-block btn-mega" onClick={this.clickDownload}>Compile and Download</button> </div> <Footer /> </main> ); } } export default Home;
JavaScript
0.000063
@@ -2225,22 +2225,24 @@ , jqXHR. -status +response Text, 2.
7d78d07abee797a1df77397624d211a9109aac80
add {max,min}{Width,Height}
src/Block.js
src/Block.js
/** * @copyright 2016-present, Prometheus Research, LLC * @flow */ import * as React from 'react'; import {wrapWithStylesheet} from './stylesheet'; import {chooseValue} from './Utils'; import * as theme from './theme'; type Props = { inline?: boolean; noWrap?: boolean; position?: 'relative' | 'absolute' | 'fixed', width?: number; height?: number; top?: number; left?: number; bottom?: number; right?: number; padding?: string | number; paddingV?: string | number; paddingH?: string | number; paddingLeft?: string | number; paddingRight?: string | number; paddingTop?: string | number; paddingBottom?: string | number; margin?: string | number; marginV?: string | number; marginH?: string | number; marginLeft?: string | number; marginRight?: string | number; marginTop?: string | number; marginBottom?: string | number; textAlign?: 'left' | 'right' | 'center', verticalAlign?: string; style?: Object; }; export default function Block({ inline, noWrap, position = 'relative', width, height, top, left, bottom, right, padding, paddingV, paddingH, paddingLeft, paddingRight, paddingTop, paddingBottom, margin, marginV, marginH, marginLeft, marginRight, marginTop, marginBottom, textAlign, verticalAlign, style, ...props }: Props) { style = { paddingLeft: chooseValue(theme.padding, paddingLeft, paddingH, padding), paddingRight: chooseValue(theme.padding, paddingRight, paddingH, padding), paddingTop: chooseValue(theme.padding, paddingTop, paddingV, padding), paddingBottom: chooseValue(theme.padding, paddingBottom, paddingV, padding), marginLeft: chooseValue(theme.margin, marginLeft, marginH, margin), marginRight: chooseValue(theme.margin, marginRight, marginH, margin), marginTop: chooseValue(theme.margin, marginTop, marginV, margin), marginBottom: chooseValue(theme.margin, marginBottom, marginV, margin), display: inline ? 'inline-block' : undefined, whiteSpace: noWrap ? 'nowrap' : undefined, position, width, height, top, left, bottom, right, textAlign, verticalAlign, ...style, }; return <div {...props} style={style} />; } Block.style = function style(stylesheet, displayName) { return wrapWithStylesheet(Block, stylesheet, displayName || 'Block'); };
JavaScript
0.999961
@@ -340,17 +340,103 @@ mber;%0A -h +maxWidth?: number;%0A minWidth?: number;%0A height?: number;%0A maxHeight?: number;%0A minH eight?: @@ -1121,39 +1121,85 @@ tive',%0A width, -height, +maxWidth, minWidth,%0A height, maxHeight, minHeight,%0A top, left, bott @@ -2181,23 +2181,73 @@ width, -height, +minWidth, maxWidth,%0A height, minHeight, maxHeight,%0A top, le
fe4f2c92faf6cbff247570220380bb6551b7e54f
add filter condition for text and select filter
src/Const.js
src/Const.js
export default { SORT_DESC: 'desc', SORT_ASC: 'asc', SIZE_PER_PAGE: 10, NEXT_PAGE: '>', LAST_PAGE: '>>', PRE_PAGE: '<', FIRST_PAGE: '<<', PAGE_START_INDEX: 1, ROW_SELECT_BG_COLOR: '', ROW_SELECT_NONE: 'none', ROW_SELECT_SINGLE: 'radio', ROW_SELECT_MULTI: 'checkbox', CELL_EDIT_NONE: 'none', CELL_EDIT_CLICK: 'click', CELL_EDIT_DBCLICK: 'dbclick', SIZE_PER_PAGE_LIST: [ 10, 25, 30, 50 ], PAGINATION_SIZE: 5, NO_DATA_TEXT: 'There is no data to display', SHOW_ONLY_SELECT: 'Show Selected Only', SHOW_ALL: 'Show All', EXPORT_CSV_TEXT: 'Export to CSV', INSERT_BTN_TEXT: 'New', DELETE_BTN_TEXT: 'Delete', SAVE_BTN_TEXT: 'Save', CLOSE_BTN_TEXT: 'Close', FILTER_DELAY: 500, SCROLL_TOP: 'Top', SCROLL_BOTTOM: 'Bottom', FILTER_TYPE: { TEXT: 'TextFilter', REGEX: 'RegexFilter', SELECT: 'SelectFilter', NUMBER: 'NumberFilter', DATE: 'DateFilter', CUSTOM: 'CustomFilter' }, EXPAND_BY_ROW: 'row', EXPAND_BY_COL: 'column' };
JavaScript
0
@@ -938,16 +938,54 @@ r'%0A %7D,%0A + FILTER_CONDITION: %5B 'eq', 'like' %5D,%0A EXPAND
9cd12f6ad120e9e9ea5a266e29c006e54ad35525
add #getData
src/Index.js
src/Index.js
var Component = require('yacomponent'), inheritClass = require('inherit-class'), Item = Collection.Item = require('./Item'); function Collection() { this.items = []; this.fakeItem = undefined; } Collection.defaults = { dName: 'list', parent: null, Item: Item }; inheritClass(Collection, Component, 'component'); Collection.prototype = $.extend({}, Collection.prototype, { init: function() { this.items = []; this.defineParentName(); Component.prototype.init.call(this); this.makeFakeItem(); this.defineItems(); this.defineEvents(); }, makeFakeItem: function() { this.fakeItem = this.initItem({$el: $([]), fake: true, instance: false}); }, defineParentName: function() { if (this.options.parent) return; this.options.parent = this; }, defineEvents: function() { var self = this; this.$el.on('click', this.elDel('makeSelector', 'remove'), function(e) { e.preventDefault(); self.onRemove(e); }); $('.' + this.options.dName + 'Add').on('click', function(e) { e.preventDefault(); self.clickAdd(); }); }, elDel: function(method, arg) { var args = [this.getItemDName()]; args.push(arg); return this.options.parent[method].call(this.options.parent, args); }, onRemove: function(event) { var item = this.getByEl(event.currentTarget); this.remove(item); }, getByEl: function(el) { return this.items.filter(function(item) { return item.$el[0] === el || item.$el.find(el).length; })[0]; }, getItemDName: function() { return this.options.Item.defaults.dName; }, defineItems: function() { var self = this; this.options.parent.find(this.getItemDName()).each(function() { var $el = $(this); var data = $el.data(self.options.parent.dName + '-' + self.options.Item.defaults.dName); var item = self.initItem({$el: $el, data: data}); self.add(item); }); }, add: function(item, insert) { insert = typeof insert == 'undefined' ? false : insert; this.items.push(item); if (insert) this.$el.append(item.$el); }, addByData: function(data) { var html = this.fakeItem.template(data); var item = this.initItem({$el: $(html), data: data}); this.add(item, true); }, addPatchByData: function(data) { var self = this; data.forEach(function(i) { self.addByData(i); }); }, clickAdd: function() { var data = this.getClickAddData(); this.addByData(data); }, getClickAddData: function() { return {}; }, remove: function(item) { var index = this.items.indexOf(item); item.$el.remove(); this.items.splice(index, 1); }, initItem: function(options) { options = $.extend({ dName: this.options.parent.makeName(this.getItemDName()), template: this.options.itemTemplate }, options, this.getItemOptions()); return this.options.Item.init(options); }, getItemOptions: function() { return {}; }, clear: function() { this.items.forEach(function(i) { i.$el.remove(); }); this.items = []; }, }); Collection.prototype.constructor = Collection; module.exports = Collection;
JavaScript
0
@@ -3062,16 +3062,112 @@ %5D;%0D%0A%09%7D,%0D +%0A%0D%0A%09getData: function() %7B%0D%0A%09%09return this.items.map(function(i) %7B%0D%0A%09%09%09return i.data;%0D%0A%09%09%7D);%0D%0A%09%7D,%0D %0A%7D);%0D%0ACo
843bdb4e675be37c19a902dbe5c3ae4bca081b0e
change React Router to hash router when deploying on ghpages
web-app/src/index.js
web-app/src/index.js
/* global document, window */ import React from 'react'; import { render } from 'react-dom'; import { BrowserRouter as Router, Switch, Route, Redirect } from 'react-router-dom'; import { createStore, applyMiddleware } from 'redux'; import { Provider } from 'react-redux'; import thunk from 'redux-thunk'; import rootReducer from './reducers'; import App from './components/App'; import Login from './components/Login'; import LoginCallback from './components/Login/LoginCallback'; import StartScreen from './components/StartScreen'; import SignUp from './components/SignUp'; import OnBoard from './components/OnBoard'; import RequestResetPassword from './components/RequestResetPassword'; import ResetPassword from './components/ResetPassword'; import './index.css'; const configureStore = () => { if (process.env.NODE_ENV === 'production') { return createStore(rootReducer, applyMiddleware(thunk)); } return createStore( rootReducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(), // eslint-disable-line applyMiddleware(thunk), ); }; const isAuthenticated = () => { const token = window.localStorage.getItem('jwt.token'); if (token === null || token === undefined) { return <Redirect to="/app" />; } return <App />; }; // TODO: need to think about the onboarding url's const Root = () => ( <Provider store={configureStore()}> <Router> <Switch> <Route exact path="/app" component={StartScreen} /> <Route exact path="/login" component={Login} /> <Route exact path="/login/callback/facebook/:token" component={LoginCallback} /> <Route exact path="/reset-password" component={RequestResetPassword} /> <Route exact path="/reset-password/:token" component={ResetPassword} /> <Route exact path="/sign-up" component={SignUp} /> <Route exact path="/start" component={OnBoard} /> {isAuthenticated()} </Switch> </Router> </Provider> ); render(<Root />, document.getElementById('root'));
JavaScript
0
@@ -112,12 +112,14 @@ uter - as +, Hash Rout @@ -1295,57 +1295,90 @@ %7D;%0A%0A -// TODO: need to think about the onboarding url's +const Router = process.env.NODE_ENV === 'github'%0A ? HashRouter%0A : BrowserRouter; %0A%0Aco
23118f088d7b0ee0c418f058194d429eaee489d6
Handle null cohort.
js/AppControls.js
js/AppControls.js
/*global require: false, module: false */ 'use strict'; var React = require('react'); var CohortSelect = require('./views/CohortSelect'); var DatasetSelect = require('./views/DatasetSelect'); var Button = require('react-bootstrap/lib/Button'); var Tooltip = require('react-bootstrap/lib/Tooltip'); var OverlayTrigger = require('react-bootstrap/lib/OverlayTrigger'); var pdf = require('./pdfSpreadsheet'); var modeButton = { chart: 'Visual Spreadsheet', heatmap: 'Chart' }; var modeEvent = { chart: 'heatmap', heatmap: 'chart' }; // XXX drop this.props.style? Not sure it's used. var AppControls = React.createClass({ onMode: function () { var {callback, appState: {mode}} = this.props; callback([modeEvent[mode]]); }, onRefresh: function () { var {callback} = this.props; callback(['refresh-cohorts']); }, onPdf: function () { pdf(this.props.appState); }, onSamplesSelect: function (value) { this.props.callback(['samplesFrom', 0 /* index into composite cohorts */, value]); }, onCohortSelect: function (value) { this.props.callback(['cohort', 0 /* index into composite cohorts */, value]); }, render: function () { var {appState: {cohort: [{name: cohort, samplesFrom}], cohorts, datasets, mode}} = this.props, hasCohort = !!cohort, noshow = (mode !== "heatmap"); const tooltip = <Tooltip id='reload-cohorts'>Reload cohorts from all hubs.</Tooltip>; return ( <form className='form-inline'> <OverlayTrigger placement="top" overlay={tooltip}> <Button onClick={this.onRefresh} bsSize='sm' style={{marginRight: 5}}> <span className="glyphicon glyphicon-refresh" aria-hidden="true"/> </Button> </OverlayTrigger> {noshow ? null : <CohortSelect cohort={cohort} cohorts={cohorts} onSelect={this.onCohortSelect}/>} {' '} {hasCohort && !noshow ? <div className='form-group' style={this.props.style}> <label> Samples in </label> {' '} <DatasetSelect onSelect={this.onSamplesSelect} nullOpt="Any Datasets (i.e. show all samples)" style={{display: hasCohort ? 'inline' : 'none'}} datasets={datasets} cohort={cohort} value={samplesFrom} /> </div> : null} {' '} <Button onClick={this.onMode} bsStyle='primary'>{modeButton[mode]}</Button> {' '} {noshow ? null : <Button onClick={this.onPdf}>PDF</Button>} </form> ); } }); module.exports = AppControls;
JavaScript
0
@@ -399,16 +399,53 @@ sheet'); +%0Avar _ = require('./underscore_ext'); %0A%0Avar mo @@ -1210,37 +1210,21 @@ rt: -%5B%7Bname: cohort, samplesFrom%7D%5D +activeCohorts , co @@ -1261,16 +1261,126 @@ .props,%0A +%09%09%09cohort = _.getIn(activeCohorts, %5B0, 'name'%5D),%0A%09%09%09samplesFrom = _.getIn(activeCohorts, %5B0, 'samplesFrom'%5D),%0A %09%09%09hasCo
ebfb17acfef4eae6478a071afdecd14c9bf5dee9
clear tiles
web/script/canvas.js
web/script/canvas.js
function CanvasLayer (map) { var me = {}; var minZoom = 4; var maxZoom = 20; var radius = 3; var updateFunctions = []; var markers = []; me.setPoints = function (list) { markers = list; layoutLevels(); me.redraw(); } me.redraw = function () { updateFunctions.forEach(function (update) { update() }); } var canvasTiles = L.tileLayer.canvas(); canvasTiles.drawTile = function (canvas, tilePoint, zoom) { var size = canvas.width; var ctx = canvas.getContext('2d'); var zoomExp = Math.pow(2, zoom); var x0 = tilePoint.x*size; var y0 = tilePoint.y*size; var x1 = x0 + size; var y1 = y0 + size; var levelZoom = Math.min(maxZoom, Math.max(zoom, minZoom)); var scale = Math.pow(2, zoom-levelZoom); var r = radius*scale; function drawTile () { markers.forEach(function (marker) { var point = marker.levelPosition[levelZoom]; var x = point.x*scale; var y = point.y*scale; if (x + r < x0) return; if (x - r > x1) return; if (y + r < y0) return; if (y - r > y1) return; ctx.beginPath(); ctx.arc( x - x0, y - y0, r, 0, Math.PI*2, false); ctx.fillStyle = marker.fillColor; ctx.fill(); ctx.lineWidth = scale; ctx.strokeStyle = marker.strokeColor; ctx.stroke(); }) } drawTile(); updateFunctions.push(drawTile); } function layoutLevels() { markers.forEach(function (marker) { marker.levelPosition = []; }); markers.forEach(function (marker) { var p = map.project([marker.latitude, marker.longitude], maxZoom); marker.levelPosition[maxZoom] = { x0:p.x, y0:p.y, x:p.x, y:p.y } }) layout(maxZoom); for (var zoom = maxZoom-1; zoom >= minZoom; zoom--) { markers.forEach(function (marker) { var p0 = map.project([marker.latitude, marker.longitude], zoom); var p = marker.levelPosition[zoom+1]; marker.levelPosition[zoom] = { x0:p.x0/2, y0:p.y0/2, x: p0.x, y: p0.y }; }) layout(zoom); } function layout(zoom) { } } canvasTiles.addTo(map); return me; }
JavaScript
0.000001
@@ -782,24 +782,58 @@ awTile () %7B%0A +%09%09%09ctx.clearRect(0,0,size,size);%0A%0A %09%09%09markers.f
4489d680cb9e04bbc3e000363d8d45747c2613d6
refactor array interation
scripts-available/disk-usage/process.js
scripts-available/disk-usage/process.js
module.exports = function (data) { var lines = data.chunk.split ("\n"), statuses = []; data.mysql_connection.connect(); for (var linesIndex = 0; linesIndex < lines.length; linesIndex++) { var this_line = lines[linesIndex].replace(/\s+/g, ' ').split(" "), path = this_line[0], percent = this_line[4], usage = percent.substring(0, percent.length - 1), message = path + " is at " + percent; usage > 90 ? statuses.push ({ "status":"ALERT", "message":message }) : usage > 50 ? statuses.push ({ "status":"Warning", "message":message }) : statuses.push ({ "status":"OK", "message":message }); var sql = "INSERT INTO `big_brother`.`disk_usage` (`host`, `path`, `percent`) VALUES ('" + data.host + "', '" + path + "', '" + percent + "')"; data.mysql_connection.query(sql, function(err, rows, fields) { if (err) throw err; }); } data.mysql_connection.end(); return statuses; }
JavaScript
0.000196
@@ -130,111 +130,64 @@ ;%0A%0A%09 -for (var linesIndex = 0; linesIndex %3C lines.length; linesIndex++) %7B%0A%09%09var this_line = lines%5BlinesIndex%5D +lines.forEach (function (line) %7B%0A%09%09var line_split = line .rep @@ -232,27 +232,29 @@ th + = -this_line +line_split %5B0%5D,%0A%09%09 @@ -270,19 +270,21 @@ t + = -this_line +line_split %5B4%5D, @@ -300,16 +300,17 @@ age + = percen @@ -361,16 +361,17 @@ ssage + = path + @@ -867,18 +867,19 @@ %09%09%7D);%0A%09%7D +); %0A -%09 %0A%09data.m
965d72b5691a4f403069fe54dc9b1e9c793881a4
Fix link to Github
js/application.js
js/application.js
$(document).ready(function() { $('.content a').click(function(e) { e.preventDefault(); $('body').toggleClass('sidebar-open'); }); });
JavaScript
0.000006
@@ -40,16 +40,23 @@ ontent a +.switch ').click
9fec6e9fdd4cfaafefe33af83a782b0e2cbd518c
Fix id ref
angular-collection.js
angular-collection.js
(function(angular, _){ 'use strict'; // Create local references to array methods we'll want to use later. var array = []; var push = array.push; var slice = array.slice; var splice = array.splice; angular.module('ngCollection', ['ngResource']) .factory('$model', ['$resource', '$q', function($resource, $q){ var Model = function(url, model){ // Remove leading slash if provided url = (url[0] == '/') ? url.slice(1) : url; // Instantiate resource var defaultParams = (model && model.id) ? {id: model.id} : {}; var resource = $resource('/' + url + '/:id', defaultParams, { // Add PUT method since it's not available by default update: { method: 'PUT' } }); // Store the model this.model = model || {}; // Expose resource promise and resolved this.$resolved = true; this.$promise = null; this.get = function(id){ id = id || this.id; var get = resource.get({id: id}); var that = this; // Update exposed promise and resolution indication this.$resolved = false; this.$promise = get.$promise; get.$promise.then(function(model){ // Update model data _.extend(that.model, model); // Update resolution indicator that.$resolved = true; }); return this; }; this.save = function(){ var save = (this.model.id) ? resource.update(this.model) : resource.save(this.model); var that = this; // Update exposed promise and resolution indication this.$resolved = false; this.$promise = save.$promise; save.$promise.then(function(model){ _.extend(that.model, model); that.resolved = true; }); return this; }; this.remove = this.del = function(){ var remove = resource.remove(this.model); var that = this; // Remove model from collection if it's in one if (this.$collection) { this.$collection.models.splice(this.$collection.indexOf(this), 1); } // Update exposed promise and resolution indication this.$resolved = false; this.$promise = remove.$promise; remove.$promise.then(function(model){ that.resolved = true; }); return this; }; }; // Return the constructor return function(url, model){ return new Model(url, model); }; }]) .factory('$collection', ['$resource', '$q', '$model', function($resource, $q, $model){ // Collection constructor var Collection = function(url, defaultParams){ // Remove leading slash if provided url = (url[0] == '/') ? url.slice(1) : url; // Instantiate resource var resource = $resource('/' + url + '/:id', defaultParams, { // Add PUT method since it's not available by default update: { method: 'PUT' } }); // Store models for manipulation and display this.models = []; // Store length so we can look it up faster/more easily this.length = 0; // Expose resource promise and resolved this.$resolved = true; this.$promise = null; var updateLength = function(){ this.length = this.models.length; }; // Expose method for querying collection of models this.query = function(params){ params = params || {}; var that = this; var query = resource.query(params); this.models = []; // Update exposed promise and resolution indication this.$resolved = false; this.$promise = query.$promise; // Update models this.$promise.then(function(models){ // Loop through models _.each(models, function(model){ // Push new model that.push(model); }); // Update length property updateLength.apply(that); that.$resolved = true; }); return this; }; // Get an individual model by id this.get = function(id){ var model = _.find(this.models, {id: id}); return model; }; this.push = this.add = function(model){ if (model && model.model) { var existingModel = _.find(this.models, {id: model.model.id}); // Add the model if it doesn't exist if (this.indexOf(model) < 0) { // Add collection reference model.$collection = this; // Push it to the models this.models.push(model); } } else if (model) { // Instantiate new model model = $model(url, model); // Add this collection reference to it model.$collection = this; // Push it to the models this.models.push(model); } // Update length property updateLength.apply(this); return model; }; // Save all models this.save = function(){ var that = this; var defer = $q.defer(); var counter = 0; // Update promise and resolved indicator this.$resolved = false; this.$promise = defer.promise; // Save each model individually _.each(this.models, function(model){ model.save().$promise.then(function(){ // Increment counter counter++; // If all saves have finished, resolve the promise if (counter === that.length) { that.$resolved = true; defer.resolve(that.models); } }); }); return this; }; return this; }; // Stolen straight from Backbone // NOTE - The current included methods have been selected arbitrarily based on // what I've actually used in my application var methods = ['forEach', 'each', 'map', 'find', 'pluck', 'last', 'indexOf']; _.each(methods, function(method) { Collection.prototype[method] = function() { // Slice returns arguments as an array var args = slice.call(arguments); // Add the models as the first value in args args.unshift(this.models); // Return the _ method with appropriate context and arguments return _[method].apply(_, args); }; }); // Return the constructor return function(url, defaultParams){ return new Collection(url, defaultParams); }; }]); })(window.angular, window._);
JavaScript
0.000001
@@ -946,16 +946,22 @@ %7C%7C this. +model. id;%0A
2da62d284dd7375768cff3966f9056d77e716aec
add heart.graphics.get{Width,Height}
heart.js
heart.js
/* heart.js v0.0.1 copyright (c) 2012 darkf licensed under the terms of the MIT license, see LICENSE for details A Canvas-based graphics library inspired by (i.e. cloned from) Love 2D (https://love2d.org/) It's currently in its pre-alpha development stage, so don't expect anything to work, and feel free to send pull requests / file issues! Thank you for using heart.js! :-) */ var heart = { _lastTick: new Date().getTime(), /* time of the last tick */ _dt: 0, /* time since last tick in seconds */ _fps: 0, /* frames per second */ _targetFPS: 30, /* the target FPS cap */ bg: {r: 127, g: 127, b: 127}, /* background color */ _size: {w: 800, h: 600}, /* size of viewport */ _syncLoading: [] /* for synchronous image loading */ }; var love = heart; /* for interoperability with the love API */ var HeartImage = function(img) { this.img = img; }; HeartImage.prototype.getWidth = function() { return this.img.width; }; HeartImage.prototype.getHeight = function() { return this.img.height; }; heart.graphics = { rectangle: function(mode, x, y, w, h) { if(mode === "fill") heart.ctx.fillRect(x, y, w, h); else heart.ctx.strokeRect(x, y, w, h); }, print: function(text, x, y) { heart.ctx.fillText(text, x, y); }, setColor: function(r, g, b) { heart.ctx.fillStyle = heart.ctx.strokeStyle = "rgb("+r+","+g+","+b+")"; }, newImage: function(src) { /* synchronously load image */ /* XXX: does not handle errors */ var img = new Image(); var i = heart._syncLoading.length; heart._syncLoading.push(img); img.onload = function() { heart._syncLoading.splice(i, 1); /* remove img from the loading sequence\ */ }; img.src = src; return new HeartImage(img); }, draw: function(drawable, x, y) { if(drawable.img !== undefined) { heart.ctx.drawImage(drawable.img, x, y); } } }; heart.timer = { getFPS: function() { return heart._fps; } }; heart._init = function() { if(heart.load !== undefined) heart.load(); if(heart.canvas === undefined || heart.ctx === undefined) alert("no canvas"); }; heart._tick = function() { /* if we're waiting on images to load, skip the frame */ if(heart._syncLoading.length === 0) { var time = new Date().getTime(); heart._dt = time - heart._lastTick; heart._lastTick = time; heart._fps = Math.floor(1000 / heart._dt); if(heart.update) heart.update(heart._dt / 1000); heart.ctx.fillStyle = "rgb("+heart.bg.r+","+heart.bg.g+","+heart.bg.b+")"; heart.ctx.fillRect(0, 0, heart._size.w, heart._size.h); if(heart.draw) heart.draw(); } setTimeout(heart._tick, 1000 / heart._targetFPS); } heart.attach = function(canvas) { var el = document.getElementById(canvas); if(!el) return false; heart.canvas = el; heart.ctx = heart.canvas.getContext("2d"); if(!heart.ctx) alert("couldn't get canvas context") }; window.onload = function() { heart._init(); heart._tick(); };
JavaScript
0.99965
@@ -1399,16 +1399,123 @@ %22;%0A%09%7D,%0A%0A +%09getWidth: function() %7B%0A%09%09return heart._size.w;%0A%09%7D,%0A%0A%09getHeight: function() %7B%0A%09%09return heart._size.h;%0A%09%7D,%0A%0A %09newImag
9a4894a328468807e422a768f17a98d99d45cbc5
Fix walkthrough
js/id/ui/intro.js
js/id/ui/intro.js
iD.ui.intro = function(context) { var step; function intro(selection) { context.enter(iD.modes.Browse(context)); // Save current map state var history = context.history().toJSON(), hash = window.location.hash, background = context.background().baseLayerSource(), opacity = d3.select('.background-layer').style('opacity'), loadedTiles = context.connection().loadedTiles(), baseEntities = context.history().graph().base().entities; // Load semi-real data used in intro context.connection().toggle(false).flush(); context.history().save().reset(); context.history().merge(iD.Graph().load(JSON.parse(iD.introGraph)).entities); context.background().bing(); // Block saving var savebutton = d3.select('#bar button.save'), save = savebutton.on('click'); savebutton.on('click', null); var beforeunload = window.onbeforeunload; window.onbeforeunload = null; d3.select('.background-layer').style('opacity', 1); var curtain = d3.curtain(); selection.call(curtain); function reveal(box, text, options) { options = options || {}; if (text) curtain.reveal(box, text, options.tooltipClass, options.duration); else curtain.reveal(box, '', '', options.duration); } var steps = ['navigation', 'point', 'area', 'line', 'startEditing'].map(function(step, i) { var s = iD.ui.intro[step](context, reveal) .on('done', function() { entered.filter(function(d) { return d.title === s.title; }).classed('finished', true); enter(steps[i + 1]); }); return s; }); steps[steps.length - 1].on('startEditing', function() { curtain.remove(); navwrap.remove(); d3.select('.background-layer').style('opacity', opacity); context.connection().toggle(true).flush().loadedTiles(loadedTiles); context.history().reset().merge(baseEntities); context.background().baseLayerSource(background); if (history) context.history().fromJSON(history); window.location.replace(hash); window.onbeforeunload = beforeunload; d3.select('#bar button.save').on('click', save); }); var navwrap = selection.append('div').attr('class', 'intro-nav-wrap fillD'); var buttonwrap = navwrap.append('div') .attr('class', 'joined') .selectAll('button.step'); var entered = buttonwrap.data(steps) .enter().append('button') .attr('class', 'step') .on('click', enter); entered.append('div').attr('class','icon icon-pre-text apply'); entered.append('label').text(function(d) { return t(d.title); }); enter(steps[0]); function enter (newStep) { if (step) { step.exit(); } context.enter(iD.modes.Browse(context)); step = newStep; step.enter(); entered.classed('active', function(d) { return d.title === step.title; }); } } return intro; }; iD.ui.intro.pointBox = function(point, context) { var rect = context.surface().node().getBoundingClientRect(); point = context.projection(point); return { left: point[0] + rect.left - 30, top: point[1] + rect.top - 50, width: 60, height: 70 }; }; iD.ui.intro.pad = function(box, padding, context) { if (box instanceof Array) { var rect = context.surface().node().getBoundingClientRect(); box = context.projection(box); box = { left: box[0] + rect.left, top: box[1] + rect.top }; } return { left: box.left - padding, top: box.top - padding, width: (box.width || 0) + 2 * padding, height: (box.width || 0) + 2 * padding }; };
JavaScript
0.000003
@@ -517,18 +517,42 @@ entities +,%0A introGraph ;%0A - %0A @@ -679,24 +679,187 @@ ().reset();%0A + %0A introGraph = JSON.parse(iD.introGraph);%0A for (var key in introGraph) %7B%0A introGraph%5Bkey%5D = iD.Entity(introGraph%5Bkey%5D);%0A %7D%0A cont @@ -894,30 +894,16 @@ ().load( -JSON.parse(iD. introGra @@ -905,17 +905,16 @@ roGraph) -) .entitie
cc52563d9cef8e4c2ab251cf1576ade001fdbd18
Update tp-link-prettifier.user.js
tp-link-prettifier.user.js
tp-link-prettifier.user.js
// ==UserScript== // @name TP-LINK Prettifier // @author Giuseppe Bertone, Brainmote s.r.l.s. // @namespace http://www.brainmote.com // @version 1.1 // @updateURL https://raw.githubusercontent.com/Brainmote/TP-Link-Prettifier/master/tp-link-prettifier.user.js // @downloadURL https://raw.githubusercontent.com/Brainmote/TP-Link-Prettifier/1.1-release/tp-link-prettifier.user.js // @description This script is used to prettify the "Wireless Station Status" page for TP-Link TD-W8970 router. In particular, with this script you can see the description near the MAC address for devices you already registered in the Wireless MAC Filtering page. (you can see a snapshot here https://goo.gl/pBjoLY). Tested on Firmware version: 0.6.0 2.8 v000c.0 Build 130828 Rel.38099n and Hardware version: TD-W8970 v1 00000000 // @match http://192.168.1.1/* // @copyright 2014+, Brainmote s.r.l.s. // @license Apache License Version 2.0 // @require https://s3-eu-west-1.amazonaws.com/public.brainmote.com/userscripts/jquery-2.1.1.min.js // @grant unsafeWindow // ==/UserScript== $(document).ready( function() { //Modify the original ajax function so I can call the prettify when needed unsafeWindow.$.ajaxOriginal = unsafeWindow.$.ajax; unsafeWindow.$.ajax = function( s ) { if ( "/cgi?7" == s.url ){ $.when( unsafeWindow.$.ajaxOriginal( s ) ).done( function(){ //Use a little timeout to let the list to be loaded setTimeout( function() { //Native call to the router to get the registered mac list and description unsafeWindow.$.io( "./cgi?5", false, function( response ) { //Read the response and prepare a clean MAC list (key = mac address, value = description) response = response.replace( /X_TPLINK_Description=/g, "" ); response = response.replace( /X_TPLINK_MACAddress=/g, "" ); var responseArray = response.split( '\n' ); var descList = {}, descListSize = 0; for( var i = 2; i < responseArray.length; i+=4 ){ descList[responseArray[i]] = responseArray[i+1]; } //Native call to the router to get IP and hostname associated to the mac unsafeWindow.$.io( "./cgi?5", false, function( response ) { //Read the response and prepare a clean MAC list (key = mac address, value = description) response = response.replace( /MACAddress=/g, "" ); response = response.replace( /hostName=/g, "" ); response = response.replace( /IPAddress=/g, "" ); var responseArray = response.split( '\n' ); var hostnameList = {}, ipList = {}; for( var i = 2; i < responseArray.length; i+=5 ){ hostnameList[responseArray[i]] = responseArray[i+1]; ipList[responseArray[i]] = responseArray[i+2]; } //Prepare data for the prettify function hostList = {}; Object.keys(ipList). forEach(function(element, index, array){ hostList[element] = {}; hostList[element]["IP"] = ipList[element]; hostList[element]["HOSTNAME"] = hostnameList[element]; hostList[element]["DESC"] = descList[element]; }); //List all MAC addresses and insert detailed info $( "td[width='20%']" ).each( function( index, element ) { var jqElement = $(element); var mac = jqElement.text(); var hostData = hostList[mac]; if ( hostData ) { console.log(hostData["MAC"] + hostData["HOSTNAME"] + hostData["DESC"] + hostData["IP"]); jqElement.after($("<td>").text(mac)); jqElement.after($("<td>").text(hostData["HOSTNAME"])); jqElement.text(hostData["DESC"]) .after($("<td>").text(hostData["IP"])); } }); $( "#tlbHead" ).remove(); $( "th[width='5%']" ).remove(); $( "td[width='5%']" ).remove(); $( "#staTbl" ).css("border", "1px solid #999"); $( "#staTbl td" ).removeAttr("width"); $( "#staTbl tbody" ).prepend("<tr style='font-weight:bold;'><td>Description</td><td>IP</td><td>Hostname</td><td>MAC address</td><td>Current status</td><td>Received packets</td><td>Sent packets</td></tr>"); }, "[LAN_HOST_ENTRY#0,0,0,0,0,0#0,0,0,0,0,0]0,4\r\nleaseTimeRemaining\r\nMACAddress\r\nhostName\r\nIPAddress\r\n", false ); }, "[LAN_WLAN_MACTABLEENTRY#0,0,0,0,0,0#1,1,0,0,0,0]0,3\r\nX_TPLINK_Enabled\r\nX_TPLINK_MACAddress\r\nX_TPLINK_Description\r\n", false ); }, 250 );}); } else { unsafeWindow.$.ajaxOriginal( s ); } } });
JavaScript
0
@@ -4504,141 +4504,8 @@ ) %7B%0A - console.log(hostData%5B%22MAC%22%5D + hostData%5B%22HOSTNAME%22%5D + hostData%5B%22DESC%22%5D + hostData%5B%22IP%22%5D);%0A
b3eee12d267565537f02fe41b4acbb910941e528
Disable the Nagle algorithm
transformers/uws/server.js
transformers/uws/server.js
'use strict'; var parse = require('url').parse , http = require('http'); /** * Server of µWebSockets transformer. * * @runat server * @api private */ module.exports = function server() { var uws = require('uws').uws , Spark = this.Spark; var service = this.service = new uws.Server(); service.onMessage(function message(socket, msg, binary, spark) { spark.emit('incoming::data', binary ? msg : msg.toString()); }); service.onDisconnection(function close(socket, code, msg, spark) { service.setData(socket); spark.ultron.remove('outgoing::end'); spark.emit('incoming::end'); }); // // Listen to upgrade requests. // this.on('upgrade', function upgrade(req, soc, head) { var secKey = req.headers['sec-websocket-key'] , ticket; if (secKey && secKey.length === 24) { ticket = service.transfer(soc._handle.fd, soc.ssl ? soc.ssl._external : null); soc.on('close', function destroy() { service.onConnection(function create(socket) { var spark = new Spark( req.headers // HTTP request headers. , req // IP address location. , parse(req.url).query // Optional query string. , null // We don't have an unique id. , req // Reference to the HTTP req. ); service.setData(socket, spark); spark.ultron.on('outgoing::end', function end() { service.close(socket); }).on('outgoing::data', function write(data) { service.send(socket, data, Buffer.isBuffer(data)); }); }); service.upgrade(ticket, secKey); }); } soc.destroy(); }); // // Listen to non-upgrade requests. // this.on('request', function request(req, res) { res.writeHead(426, { 'content-type': 'text/plain' }); res.end(http.STATUS_CODES[426]); }); this.on('close', function close() { service.close(); }); };
JavaScript
0.000023
@@ -820,24 +820,52 @@ h === 24) %7B%0A + soc.setNoDelay(true);%0A ticket
2ec221850888fe6a66af389186d3f0b93bd2854e
Fix on month change firstDay issue
tiny-calendar.js
tiny-calendar.js
'use strict'; angular.module('angular-tiny-calendar', []).directive('tinyCalendar', [ function() { function removeTime(date) { return date.startOf('day'); } function firstSelected(month, date) { var s = null; for (var i = 0; i < month.length; i++) { if (date && month[i].date === date) { s = month[i]; break; } else if (!date && month[i].isToday) { s = month[i]; break; } } return s; } function buildMonth(start, events, firstDay) { if(!firstDay || isNaN(firstDay)){ firstDay = 0; } var days = []; var date = removeTime(start.clone().date(0).day(firstDay)); for (var i = 0; i < 42; i++) { days.push({ number: date.date(), isCurrentMonth: date.month() === start.month(), isToday: date.isSame(moment().format(), 'day'), date: date.format(), }); date = date.clone(); date.add(1, 'd'); } return addEvents(days, events); } function addEvents(month, events) { if(!events){ return month; } return month.map(function(day) { var ev = []; var d = moment(day.date); events.forEach(function(event) { var s = removeTime(moment(event.startDate)); var e = event.endDate ? removeTime(moment(event.endDate)) : s.clone(); if (moment().range(s, e).contains(d)) { ev.push(event); } }); if (ev.length > 0) { day.events = ev; } return day; }); } return { restrict: 'A', scope: { events: '=' }, // replace: true, template: function(element, attrs) { var defaultsAttrs = { weekDays : 'SMTWTFS', today: 'today', allDayLabel : 'All day', firstDay: 0 }; for (var xx in defaultsAttrs) { if (attrs[xx] === undefined) { attrs[xx] = defaultsAttrs[xx]; } } attrs.weekDays = attrs.weekDays.split('').slice(0,7); if(attrs.firstDay){ attrs.weekDays = attrs.weekDays.slice(attrs.firstDay).concat(attrs.weekDays.slice(0, attrs.firstDay)); } attrs.weekDays = '[' + attrs.weekDays.map(function(day){ return '"'+day+'"'; }).join(',').replace('"', '&quot;') + ']'; var html = "<div class='tc-container'>"; html+= "<div class='tc-header'>{{currentMonth.format('MMMM YYYY')}}"; html+= "<div class='tc-navigation'>"; html+= "<button ng-click='previous()'>«</button>"; html+= "<button ng-click='today()'>"+attrs.today+"</button>"; html+= "<button ng-click='next()'>»</button>"; html+= "</div>"; html+= "</div>"; html+= "<div class='tc-days-name'>"; html+= "<div class='tc-day-name' ng-repeat='wd in "+attrs.weekDays+" track by $index'>{{wd}}</div>"; html+= "</div>"; html+= "<div class='tc-days'>"; html+= "<div ng-repeat='day in month' class='tc-day' ng-class='{ today: day.isToday, differentMonth: !day.isCurrentMonth, selected: day.date === selected.date, hasEvents: day.events.length > 0}' ng-click='select(day)'>{{day.number}}</div>"; html+= "</div>"; html+= "<div class='tc-focus' ng-show='selected.events'>"; html+= "<ul>"; html+= "<li ng-repeat='e in selected.events | orderBy:&quot;date&quot;'><span class='tc-time' ng-show='e.time'>{{e.time}}</span><span class='tc-time' ng-hide='e.time'>"+attrs.allDayLabel+"</span><span class='tc-title' ng-bind-html='e.title'></span></li>"; html+= "</ul>"; html+= "</div>"; html+= "</div>"; return html; }, link: function(scope, el, attrs) { var today = moment().format(); scope.currentMonth = moment(); var start = scope.currentMonth.clone(); scope.month = buildMonth((start), scope.events, attrs.firstDay); scope.selected = firstSelected(scope.month); scope.select = function(day) { if (day.isCurrentMonth) { scope.selected = day; } else { scope.currentMonth = moment(day.date); scope.month = buildMonth(scope.currentMonth, scope.events); scope.selected = firstSelected(scope.month, day.date); } }; scope.today = function() { scope.currentMonth = moment(today); scope.month = buildMonth(scope.currentMonth, scope.events); scope.selected = firstSelected(scope.month, removeTime(scope.currentMonth).format()); }; scope.previous = function() { scope.selected = null; scope.currentMonth.subtract(1, 'months'); scope.month = buildMonth(scope.currentMonth, scope.events); }; scope.next = function() { scope.selected = null; scope.currentMonth.add(1, 'months'); scope.month = buildMonth(scope.currentMonth, scope.events); }; } }; }]);
JavaScript
0
@@ -5160,36 +5160,52 @@ th, scope.events +, attrs.firstDay );%0D%0A - @@ -5487,32 +5487,48 @@ th, scope.events +, attrs.firstDay );%0D%0A @@ -5871,24 +5871,40 @@ scope.events +, attrs.firstDay );%0D%0A%0D%0A @@ -6056,32 +6056,32 @@ (1, 'months');%0D%0A - @@ -6137,24 +6137,40 @@ scope.events +, attrs.firstDay );%0D%0A
434fca1b246a4b2ffc7e6b0a2bf875f94fa6c17d
read bug from removed id.
read/index.js
read/index.js
var Survey = require('./survey'); var Question = require('./question'); var Option = require('./option'); module.exports = function(Obj, cb){ if(Obj){ var search = Obj; if(Obj.id){ search._id = Obj.id; delete search.id; } Survey(search, function(err, survey){ if(err) return cb(err, Obj); else { Question({survey:Obj.id}, function(err, questions){ if(err) return cb(err, Obj); else { if(questions[0]){ survey.questions = questions; Option({survey:Obj.id}, function(err, options){ if(err) return cb(err, Obj); else { if(options[0]){ survey.options = options; return cb(null, survey); } else return cb(null, survey); } }); } else return cb(null, survey); } }); } }); } else { return cb({type:'!No READ Item'}, Obj); } }; module.exports.survey = Survey; module.exports.question = Question; module.exports.option = Option;
JavaScript
0
@@ -326,36 +326,40 @@ uestion(%7Bsurvey: -Obj. +search._ id%7D, function(er @@ -502,20 +502,24 @@ %7Bsurvey: -Obj. +search._ id%7D, fun
c6cba9f82ee843d793a4bc2a9b341cddfbf84411
Add rejectOnNull to ttl()
src/cache.js
src/cache.js
'use strict'; import extend from 'extend'; const DEFAULT_OPTIONS = { 'expire': 60 * 60, // 1hr 'json': true, 'rejectOnNull': false, 'prefix': null }; export class RedisCache { constructor(client, options = {}) { if(!client) throw new Error('redis client required'); this._client = client; this._options = extend({}, DEFAULT_OPTIONS, options); } /** * Try to parse a JSON value or return the original value **/ _parseJSON(value) { try { value = JSON.parse(value); } catch(e) { } return value; } /** * Try to stringify a JSON value or return the original value **/ _stringifyJSON(value) { try { value = JSON.stringify(value); } catch(e) { } return value; } /** * Prefixes the key **/ _prefix(key, prefix = this._options.prefix) { if(prefix !== null) key = prefix + key; return key; } /** * Fetch a key from the cache **/ fetch(key, options = {}) { options = extend({}, this._options, options); key = this._prefix(key, options.prefix); return new Promise((resolve, reject) => { this._client.get(key, (err, reply) => { if(err) return reject(err); if(options.rejectOnNull && reply === null) return reject(new Error('reply is null')); if(options.json) reply = this._parseJSON(reply); return resolve(reply); }); }); } /** * Convenience method for fetch() **/ get(key, options = {}) { return this.fetch(key, options); } /** * Set a key in the cache **/ set(key, value, options = {}) { options = extend({}, this._options, options); key = this._prefix(key, options.prefix); return new Promise((resolve, reject) => { if(options.json) value = this._stringifyJSON(value); this._client.set(key, value, (err, reply) => { if(err) return reject(err); if(options.expire) this._client.expire(key, options.expire); return resolve((reply === 'OK') ? true : false); }); }); } /** * Delete a key from the cache **/ del(key) { key = this._prefix(key); return new Promise((resolve, reject) => { this._client.del(key, (err, reply) => { if(err) return reject(err); return resolve(reply); }); }); } /** * Get the Time-To-Live (TTL) for a key **/ ttl(key) { key = this._prefix(key); return new Promise((resolve, reject) => { this._client.ttl(key, (err, reply) => { if(err) return reject(err); return resolve(reply); }); }); } /** * Check if a key exists **/ exists(key) { key = this._prefix(key); return new Promise((resolve, reject) => { this._client.exists(key, (err, reply) => { if(err) return reject(err); return resolve((reply === 1) ? true : false); }); }); } /** * Set expiry time on a key **/ expire(key, expire = this._options.expire) { key = this._prefix(key); return new Promise((resolve, reject) => { this._client.expire(key, expire, (err, reply) => { if(err) return reject(err); return resolve((reply === 1) ? true : false); }); }); } /** * Remove expiry on a key **/ persist(key) { key = this._prefix(key); return new Promise((resolve, reject) => { this._client.persist(key, (err, reply) => { if(err) return reject(err); return resolve((reply == 1) ? true : false); }); }); } /** * Split the class into a new instance using the same Redis client **/ split(options = {}, useDefaultOptions = false) { options = extend({}, (useDefaultOptions) ? DEFAULT_OPTIONS : this._options, options); return new RedisCache(this._client, options); } }
JavaScript
0
@@ -2376,16 +2376,120 @@ t(err);%0A +%09%09%09%09if(this._options.rejectOnNull && reply === -2)%0A%09%09%09%09%09return reject(new Error('key does not exist'));%0A
fe2cc155059cb64f169d4aa86237200252c250f5
fix defect
routes/melody.js
routes/melody.js
var MelodyDao = require("../dao/MelodyDao"); var MelodyModel = require("../models").Melody; var TrackDao = require("../dao/TrackDao"); var TrackModel = require("../models").Track; var mongoose = require('mongoose'); var fs = require('fs'); var utils = require("../libs/util"); exports.getMelodyCollection=function(req,res){ }; exports.getMelodyList = function(req, res){ var query = MelodyModel.find(); query.exec(function(err,_data){ console.log(_data); if(err){ return res.json({state:1, err:err}); } return res.json(_data); }); } exports.getMelody= function (req, res) { var melody_id = req.params['id']; console.log("Get Melody by ID:"+ melody_id); try{ var _melody_id = mongoose.Types.ObjectId(melody_id); }catch(e){ return res.json({err:'invalid melody id'}); }; MelodyModel.findOne({_id:_melody_id},function(err,_melody){ if (err) return res.json({err:err}); if (!_melody) { return res.json({err:'Melody does not exists'}); } return res.json(_melody); }); }; exports.putMelody=function(req,res){ var track_id = req.body.track_id; var track = new TrackModel(); var melody = req.body; melody.track = new Array(); TrackModel.findOne({_id: mongoose.Types.ObjectId(track_id)}, function(err,_track){ if(err){ return res.json({state:1,err:err}); } if(_track==null){ return res.json({state:1,err:"Can not find the track"}); } melody.track.push( _track); var new_melody = new MelodyModel(melody); new_melody.save(function(err,data){ if(err){ return res.json({state:1,err:err}); } console.log(data); return res.json({state:0,guid,data._id}); }); }); }; exports.putComment=function(req, res){ var comment = req.body; var melody_id =req.body.melody_id; //console.log({ _id: mongoose.Types.ObjectId(melody_id)}); MelodyModel.findOne({ _id: mongoose.Types.ObjectId(melody_id)}, function(err, _melody){ if(err){ return res.json({state:1,err:err}); } if(_melody==null){ return res.json({state:1,err:"Can not find the melody"}); } if(_melody.comment==undefined){ _melody.comment = new Array(); } _melody.comment.push(comment); console.log(_melody); MelodyModel.update({ _id: mongoose.Types.ObjectId(melody_id)}, {comment:_melody.comment},function(err, _data){ if(err){ return res.json({state:1,err:err}); } return res.json({state:0}); }); }) return res.json({state:1,err:"unexpected error"}); }; exports.putTrack=function(req, res){ var tmp_path = req.files.track.path; var file_ext = req.body.ext; var track_id = utils.guid(); var target_path = './Tracks/' + track_id; console.log("Copy to target_path: "+ target_path); fs.readFile(tmp_path, function (err, data) { if(err){ console.log(err); return res.json({state:1,err:err}); } fs.writeFile(target_path, data, function (err) { if(err){ console.log(err); return res.json({state:1,err:err}); } fs.unlink(tmp_path); // ignore callback var track = new TrackModel({track_location:target_path,ext:file_ext}); track.save(function(err, user){ if (err) { return res.json({err:err}); } }); return res.json({state:0, guid:track._id}); }); }); }; exports.getTrackList=function(req,res){ var query = TrackModel.find(); query.exec(function(err,_data){ console.log(_data); if(err){ return res.json({state:1, err:err}); } return res.json(_data); }); } exports.getTrack = function(req,res){ var track_id = req.params['id']; console.log("Get Track by ID:"+ track_id); try{ var _track_id = mongoose.Types.ObjectId(track_id); }catch(e){ return res.json({err:'invalid Track id'}); }; TrackModel.findOne({_id:_track_id},function(err,_track){ if (err) return res.json({state:1, err:err}); if (!_track) { return res.json({state:1, err:'Melody does not exists'}); } filename = "temp."+_track.ext; return res.download(_track.track_location,filename); }); }
JavaScript
0.000001
@@ -1674,17 +1674,17 @@ e:0,guid -, +: data._id
6069976b56a7cf1d365da8b9d5e19bb498fea3bf
Fix seeder.
seeders/20161204173948-default-admin.js
seeders/20161204173948-default-admin.js
'use strict'; var passwordHash = require('password-hash'); module.exports = { up: function (queryInterface, Sequelize) { return queryInterface.create('Admin', { username: process.env.SEED_ADMIN_USERNAME, passwordHash.generate(process.env.SEED_ADMIN_PASSWORD) }); }, down: function (queryInterface, Sequelize) { return queryInterface.destroy({ where: { username: process.env.SEED_ADMIN_USERNAME } }); } };
JavaScript
0
@@ -148,24 +148,30 @@ ace. -create +bulkInsert ('Admin +s ', +%5B %7B us @@ -210,16 +210,26 @@ SERNAME, + password: passwor @@ -275,17 +275,60 @@ ASSWORD) - +, createdAt: Date(), updatedAt: Date() %7D%5D, %7B %7D);%0A %7D,
80da3b031a7649474e9fdf7b2ad70a5e296f9b98
Add comments on section/update server method.
server/admin/forum/section/update.js
server/admin/forum/section/update.js
// Update a set of basic fields on section. 'use strict'; var _ = require('lodash'); var async = require('async'); var updateInheritedSectionData = require('nodeca.forum/lib/admin/update_inherited_section_data'); module.exports = function (N, apiPath) { N.validate(apiPath, { _id: { type: 'string', required: true } , parent: { type: ['null', 'string'], required: false } , display_order: { type: 'number', required: false } , title: { type: 'string', required: false } , description: { type: 'string', required: false } , is_category: { type: 'boolean', required: false } , is_enabled: { type: 'boolean', required: false } , is_writeble: { type: 'boolean', required: false } , is_searcheable: { type: 'boolean', required: false } , is_voteable: { type: 'boolean', required: false } , is_counted: { type: 'boolean', required: false } , is_excludable: { type: 'boolean', required: false } }); N.wire.on(apiPath, function section_update(env, callback) { var ForumUsergroupStore = N.settings.getStore('forum_usergroup'); if (!ForumUsergroupStore) { callback({ code: N.io.APP_ERROR, message: 'Settings store `forum_usergroup` is not registered.' }); return; } N.models.forum.Section.findById(env.params._id, function (err, section) { if (err) { callback(err); return; } // Update specified fields. _(env.params).keys().without('_id').forEach(function (key) { section.set(key, env.params[key]); }); async.series([ // // If section's `parent` is changed, but new `display_order` is not // specified, find free `display_order`. // function (next) { if (!section.isModified('parent') || _.has(env.params, 'display_order')) { next(); return; } // This is the most simple way to find max value of a field in Mongo. N.models.forum.Section .find({ parent: section.parent }) .select('display_order') .sort('-display_order') .limit(1) .setOptions({ lean: true }) .exec(function (err, result) { if (err) { next(err); return; } section.display_order = _.isEmpty(result) ? 1 : result[0].display_order + 1; next(); }); } // // Save changes at section. // , function (next) { section.save(next); } // // Recompute parent-dependent data for descendant sections. // , async.apply(updateInheritedSectionData, N) ], callback); }); }); };
JavaScript
0
@@ -37,16 +37,166 @@ ection.%0A +//%0A// NOTE: This method is used for both:%0A// - section/index page for section reordering.%0A// - section/edit page for changing certain section fields.%0A %0A%0A'use s @@ -1981,32 +1981,113 @@ er%60.%0A //%0A + // NOTE: Used when user changes %60parent%60 field via edit page.%0A //%0A function
d3e66faff0009fcbf8e23c266938fc4671ace211
Fix incorrect array construction for class catgs, closes #17
server/graph/helpers/pwPropParser.js
server/graph/helpers/pwPropParser.js
'use strict'; const _ = require('lodash'); class PWPropParser { constructor({smwDataArbitrator}) { this._smwDataArbitrator = smwDataArbitrator; this._rgx = { /* durations */ range_dur: /(.*?)_(.*?)_(.*?)_time$/i, /* doses */ range_dose: /(.*?)_(.*?)_(.*?)_dose$/i, def_dose: /(.*?)_(.*?)_dose$/i, /* bioavailability */ def_bioavailability: /(.*?)_(.*?)_bioavailability$/i, /* units */ dose_units: /(.*?)_dose_units$/i, roa_time_units: /(.*?)_(.*?)_time_units$/i, /* meta: tolerance */ meta_tolerance_time: /Time_to_(.*?)_tolerance$/i, /* misc */ wt_prop_glob: /\[\[(.*?)]]/g, wt_prop: /\[\[(.*?)]]/, /* misc sanitization */ wt_link: /(\[\[.*?]])/ig, wt_named_link: /(\[\[.*?\|.*?]])/ig, wt_sub_sup: /<su[bp]>(.*?)<\/su[bp]>/ig, }; this._flatMetaProps = new Map([ ['addiction_potential', 'addictionPotential'], ['uncertaininteraction', 'uncertainInteractions'], ['unsafeinteraction', 'unsafeInteractions'], ['dangerousinteraction', 'dangerousInteractions'], ['effect', 'effects'] ]); this._mappedMetaProps = new Map([ ['cross-tolerance', prop => { const propTarget = 'crossTolerances'; if (!this._rgx.wt_prop_glob.test(prop)) { return [propTarget, []]; } const mappedCrossTolerance = Array.prototype.slice .call(prop.match(this._rgx.wt_prop_glob)) .map(item => this._rgx.wt_prop.exec(item)[1] ); return [propTarget, mappedCrossTolerance]; }], ['featured', prop => ['featured', prop === 't']], ['toxicity', prop => (['toxicity', [].concat(prop)])], [ 'psychoactive_class', prop => ([ 'class.psychoactive', [].concat(prop && String(prop).replace(/#$/, '')), ]), ], [ 'chemical_class', prop => ([ 'class.chemical', [].concat(prop && String(prop).replace(/#$/, '')), ]), ], ]); this._sanitizers = new Map([ [ 'addictionPotential', val => this._sanitizeText(val) ], [ 'toxicity', val => val.map(item => this._sanitizeText(item)) ], ]); } _sanitizeText(propValue) { let tmpVal = propValue; if (!tmpVal) { return tmpVal; } // Links if (this._rgx.wt_link.test(tmpVal)) { // handle [[link|name]] { const matches = tmpVal.match(this._rgx.wt_named_link) || []; for (let i = 0; i < matches.length; ++i) { const match = matches[i]; tmpVal = tmpVal.replace( match, match .slice(2, -2) // get rid of [[ and ]] .split('|') // split by delimiter .pop() // get right side xx|yy -> yy ); } } // handle [[link]] { const matches = tmpVal.match(this._rgx.wt_link) || []; for (let i = 0; i < matches.length; ++i) { const match = matches[i]; tmpVal = tmpVal.replace( match, match.slice(2, -2) // get rid of [[ and ]] ); } } } // <sub>, <sup> tmpVal = tmpVal.replace(this._rgx.wt_sub_sup, '$1'); return tmpVal; } _sanitizedIfNeeded(propName, propValue) { if (!propValue) { return propValue; } if (this._sanitizers.has(propName)) { return this._sanitizers.get(propName)(propValue); } return propValue; } parse(propSet) { const procPropMap = {}; propSet[1].map(([_propName, {prop}]) => { const propName = _propName.toLowerCase(); let rx; switch (true) { /* durations */ case this._rgx.range_dur.test(propName): rx = this._rgx.range_dur.exec(propName); _.set( procPropMap, `roa.${rx[1]}.duration.${rx[3]}.${rx[2]}`, prop ); break; /* doses */ case this._rgx.range_dose.test(propName): rx = this._rgx.range_dose.exec(propName); _.set( procPropMap, `roa.${rx[1]}.dose.${rx[3]}.${rx[2]}`, prop ); break; case this._rgx.def_dose.test(propName): rx = this._rgx.def_dose.exec(propName); _.set( procPropMap, `roa.${rx[1]}.dose.${rx[2]}`, prop ); break; case this._rgx.def_bioavailability.test(propName): rx = this._rgx.def_bioavailability.exec(propName); _.set( procPropMap, `roa.${rx[1]}.bioavailability.${rx[2]}`, prop ); break; /* units */ case this._rgx.dose_units.test(propName): rx = this._rgx.dose_units.exec(propName); _.set( procPropMap, `roa.${rx[1]}.dose.units`, prop ); break; case this._rgx.roa_time_units.test(propName): rx = this._rgx.roa_time_units.exec(propName); _.set( procPropMap, `roa.${rx[1]}.duration.${rx[2]}.units`, prop ); break; /* meta */ case this._rgx.meta_tolerance_time.test(propName): rx = this._rgx.meta_tolerance_time.exec(propName); _.set( procPropMap, `tolerance.${rx[1]}`, prop ); break; } if (this._flatMetaProps.has(propName)) { const mappedPropName = this._flatMetaProps.get(propName); _.set( procPropMap, mappedPropName, this._sanitizedIfNeeded(mappedPropName, prop) ); } if (this._mappedMetaProps.has(propName)) { rx = this._mappedMetaProps.get(propName)(prop); _.set( procPropMap, rx[0], this._sanitizedIfNeeded(rx[0], rx[1]) ); } }); // new ROA interface const rawROAMap = _.get(procPropMap, 'roa', {}); const mappedROAs = _.chain(rawROAMap) .keys() .map(key => _.merge(_.get(rawROAMap, key), {name: key})) .value(); _.assign(procPropMap, { roas: mappedROAs }); return procPropMap; } parseFromSMW(obj) { return this.parse(this._smwDataArbitrator.parse(obj)); } } module.exports = PWPropParser;
JavaScript
0.000022
@@ -2181,32 +2181,34 @@ cat(prop - && String( +).map(prop =%3E prop -) .replace @@ -2406,24 +2406,26 @@ prop - && String( +).map(prop =%3E prop -) .rep
c87411687ec4eeb0940da734e5d48b12d594ffc3
Fix minor typo that would cause crashes
imports/api/families/methods.js
imports/api/families/methods.js
import {Families} from './families'; import Schemas from '../../modules/schemas'; import {Meteor} from 'meteor/meteor'; import {SimpleSchema} from 'meteor/aldeed:simple-schema'; import {ValidateMethod} from 'meteor/mdg:validated-method'; const insertFamily = new ValidatedMethod({ name: 'families.insert', validate: Schemas.Family.validator(), run(family){ Families.insert(family); } }); const updateFamily = new ValidatedMethod({ name: 'families.update', validate: new SimpleSchema({ _id: { type: String }, 'update.ids': { type: Array, optional: true, defaultValue: [] }, 'update.familyName': { type: String, optional: true, defaultValue: null } }).validator(), run({_id, newIds, familyName}) { Families.update(_id, { $addToSet: { userIds: { $each: newIds } } }); if(familyName !== null) Families.update(_id, {$set: {familyName: familyName}}); } }); const deleteFamily = new ValidatedMethod({ name: 'families.remove.user', rvalidate: new SimpleSchema({ _id: {type: String} }).validator(), run({_id}) { Meteor.users.update({familyIds: _id}, {$pull: {familyIds: _id}}, {multi: true}); } }); const removeUserFromFamily = new ValidatedMethod({ name: 'families.remove.user', validate: new SimpleSchema({ _id: {type: String}, 'update.userId': {type: String} }).validator(), run({_id, userId}){ Meteor.users.update(userId, {$pull: {familyIds: _id}}); } }); export {removeUserFromFamily, deleteFamily, updateFamily, insertFamily};
JavaScript
0.000269
@@ -188,16 +188,17 @@ Validate +d Method%7D
95bd9b72c774c12d4f119b6d42b4c9de4e4a7cdb
update export to improve commonjs exp
src/index.js
src/index.js
// dist :: String, Int, String, Int -> Int function dist(s, sLen, t, tLen) { if (sLen === 0) { return tLen; } else if(tLen === 0) { return sLen; } const cost = (s[sLen -1] === t[tLen - 1]) ? 0 : 1; return Math.min( dist(s, sLen - 1, t, tLen) + 1, dist(s, sLen, t, tLen - 1) + 1, dist(s, sLen - 1, t, tLen - 1) + cost, ); } // findClosest :: String, [String] -> String function findMostSimilar(source, targets) { const sLen = source.length; // scoreStruct :: { score: Int, target: String } const { target } = targets.reduce((acc, target) => { const score = dist(source, sLen, target, target.length); return score > acc.score ? acc : ({ score, target}); }); return target; } export default findMostSimilar;
JavaScript
0
@@ -398,16 +398,23 @@ String%0A +export function
0ab8dfa363e5f114207f504c9979995c0c8b6a51
Remove redirect
imports/startup/client/index.js
imports/startup/client/index.js
import './router.js'; import './i18n.js'; import './lib/accountUI.js'; import './moment.js'; window.location.href = "http://eklore.fr/";
JavaScript
0.000001
@@ -90,49 +90,4 @@ s';%0A -%0Awindow.location.href = %22http://eklore.fr/%22;%0A
614bb73ea682f25705536fa11a5c7ee0ae92d0de
update log for multiple insatnces
src/index.js
src/index.js
import ControllerModel from './controller/controller-model'; import RouteModel from './route/route-model'; import DirectiveModel from './directive/directive-model'; import FactoryModel from './factory/factory-model'; var local = { storage: Symbol('storage') }; var version = '0.0.96'; class Manager { constructor() { this.version = version; this.clear(); } addController(contoller) { if (!(contoller instanceof ControllerModel)) { throw new Error('Wrong controller model instance'); } this[local.storage].controllers.add(contoller); } removeController(controller) { this[local.storage].controllers.remove(controller); } clearControllers() { this[local.storage].controllers.clear(); } // -------------------- addFactory(factory) { if (!(factory instanceof FactoryModel)) { throw new Error('Wrong factory model instance'); } this[local.storage].factories.add(factory); } removeFactory(factory) { this[local.storage].factories.remove(factory); } clearFactories() { this[local.storage].factories.clear(); } // -------------------- addDirective(directive) { if (!(directive instanceof DirectiveModel)) { throw new Error('Wrong directive model instance'); } this[local.storage].directives.add(directive); } removeDirective(directive) { this[local.storage].directives.remove(directive); } clearDirectives() { this[local.storage].directives.clear(); } // -------------------- addRoute(route) { if (!(route instanceof RouteModel)) { throw new Error('Wrong route model instance'); } this[local.storage].routes.add(route); } removeRoute(route) { this[local.storage].routes.remove(route); } clearRoutes() { this[local.storage].routes.clear(); } getModels() { return this[local.storage]; } clear() { this[local.storage] = {}; /** * Better to se WeakSet storage but polyfill for WeakSet is not iterable */ this[local.storage].controllers = new Set(); this[local.storage].factories = new Set(); this[local.storage].directives = new Set(); this[local.storage].routes = new Set(); } } var manager = null; var context = window ? window : global; if (context.valent) { manager = context.valent; console.error('Seems there is multiple installations of Valent'); } else { manager = new Manager(); context.valent = manager; } export default manager; export { Manager };
JavaScript
0
@@ -2331,13 +2331,12 @@ ole. -error +info ('Se @@ -2384,17 +2384,16 @@ lent');%0A -%0A %7D else %7B
03d4ff09677e369258e52e929b0d9f37360ef20f
create attach: add public function for models attaching
src/index.js
src/index.js
const ld = require('lodash'); const debug = require('debug')('restify-utils'); const glob = require('glob'); const path = require('path'); const { METHODS } = require('http'); /** * Load module, separate it's name and pushed to container * @param {Object} container */ function loadModule(container) { return function loader(file) { debug('loaded file %s', file); const parts = file.split('/'); const name = path.basename(parts.pop(), '.js'); container[name] = require(file); }; } /** * Tells where endpoints reside * @param {String} dir * @return {Function} */ exports.attach = function createAttach(config, endpointsDir, middlewareDir) { // load files const files = {}; glob.sync(`${endpointsDir}/*.js`).forEach(loadModule(files)); // load middleware const middleware = {}; glob.sync(`${middlewareDir}/*.js`).forEach(loadModule(middleware)); // export shared models const models = {}; glob.sync('./models/*.js', { cwd: __dirname }).forEach(loadModule(models)); /** * Accepts restify server instance and attaches handlers * @param {RestifyServer} server * @param {String} family */ function attach(server, family, prefix = '/api') { config[family].attachPoint = ld.compact([prefix, family]).join('/'); debug('attaching with family %s and prefix %s', family, prefix); ld.forOwn(files, function attachRoute(file, name) { debug('attaching file %s', name); ld.forOwn(file, function iterateOverProperties(props, method) { if (METHODS.indexOf(method.toUpperCase()) === -1 && method.toUpperCase() !== 'DEL') { return; } debug(' attaching method %s', method); ld.forOwn(props.handlers, function iterateOverVersionedHandler(handler, versionString) { debug(' attaching handler for version %s', versionString); ld([props.paths, props.path]) .flattenDeep() .compact() .forEach(function attachPath(uriPath, idx, arr) { debug(' attaching handler for path %s', uriPath); const args = [ { name: `${family}.${name}.${method}`, path: `${prefix}/${family + uriPath}`, version: versionString.split(','), }, ]; // if we actually have a regexp in place - modify it if (props.regexp) { args[0].path = props.regexp(prefix, family, uriPath); } // we need to make sure that name is unique if (arr.length > 1) { args[0].name += `.${idx}`; } if (props.middleware) { props.middleware.forEach(function attachMiddleware(middlewareName) { debug(' pushed middleware %s', middlewareName); args.push(middleware[middlewareName]); }); } args.push(handler); const attached = server[method].apply(server, args); if (!attached) { console.error('route %s with path %s could not be attached', args[0].name, args[0].path); // eslint-disable-line } }); }); }); }); config.models = ld.mapValues(models, generator => { return generator(config); }); } attach.files = files; attach.middleware = middleware; return attach; };
JavaScript
0.000001
@@ -3215,24 +3215,93 @@ );%0A %7D);%0A%0A + attach.attachModels();%0A %7D%0A%0A attach.attachModels = function() %7B%0A config.m @@ -3383,24 +3383,25 @@ %0A %7D);%0A %7D +; %0A%0A attach.f
daa46254fe75be01410615ed0aa51ff1c7a19019
Fix grid to support single child
src/index.js
src/index.js
import React, { Component } from 'react'; import upperFirst from 'lodash.upperfirst'; import contrib from 'blessed-contrib'; import ReactBlessedComponent from 'react-blessed/dist/ReactBlessedComponent'; import solveClass from 'react-blessed/dist/solveClass'; const blacklist = [ 'OutputBuffer', 'InputBuffer', 'createScreen', 'serverError', 'grid' ]; export function createBlessedComponent(blessedElement, tag='') { return class extends ReactBlessedComponent { constructor() { super(tag); } mountNode(parent, element) { const {props} = element, {children, ...options} = props; const node = blessedElement(solveClass(options)); node.on('event', this._eventListener); parent.append(node); return node; } } } function Grid(props) { const grid = new contrib.grid({...props, screen: { append: () => {} }}); return React.createElement('element', {}, props.children.map(child => { const props = child.props; const options = grid.set(props.row, props.col, props.rowSpan, props.colSpan, x => x, props.options); return React.cloneElement(child, options); })); } class GridItem extends Component { getItem() { return this._reactInternalInstance._instance.refs.item; } render() { const props = this.props; return React.createElement(props.component, {...props, ref: 'item'}, props.children); } } class Carousel extends Component { constructor(props) { super(props); this.state = { page: 0 }; } componentDidMount() { this.carousel = new contrib.carousel(this.props.children, this.props); this.carousel.move = () => { this.setState({ page: this.carousel.currPage }); } this.carousel.start(); } render() { return this.props.children[this.state.page]; } } Object.keys(contrib).forEach(key => { // todo check prototype if (contrib.hasOwnProperty(key) && blacklist.indexOf(key) === -1) { exports[upperFirst(key)] = createBlessedComponent(contrib[key], 'contrib-' + key); } exports.Grid = Grid; exports.GridItem = GridItem; exports.Carousel = Carousel; });
JavaScript
0
@@ -892,16 +892,104 @@ %7B%7D %7D%7D);%0A + const children = props.children instanceof Array ? props.children : %5Bprops.children%5D;%0A return @@ -1024,22 +1024,16 @@ t', %7B%7D, -props. children