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
24496b610b4f262f85a8b5041fd1d39efd6771be
Fix guest pool inquiry taking
packages/rocketchat-livechat/client/views/sideNav/livechat.js
packages/rocketchat-livechat/client/views/sideNav/livechat.js
/* globals LivechatInquiry, KonchatNotification */ Template.livechat.helpers({ isActive() { const query = { t: 'l', f: { $ne: true }, open: true, rid: Session.get('openedRoom') }; const options = { fields: { _id: 1 } }; if (ChatSubscription.findOne(query, options)) { return 'active'; } }, rooms() { const query = { t: 'l', open: true }; const user = RocketChat.models.Users.findOne(Meteor.userId(), { fields: { 'settings.preferences.unreadRoomsMode': 1 } }); if (user && user.settings && user.settings.preferences && user.settings.preferences.unreadRoomsMode) { query.alert = { $ne: true }; } return ChatSubscription.find(query, { sort: { 't': 1, 'name': 1 }}); }, inquiries() { // get all inquiries of the department const inqs = LivechatInquiry.find({ agents: Meteor.userId(), status: 'open' }, { sort: { 'ts' : 1 } }); // for notification sound inqs.forEach((inq) => { KonchatNotification.newRoom(inq.rid); }); return inqs; }, guestPool() { return RocketChat.settings.get('Livechat_Routing_Method') === 'Guest_Pool'; }, available() { const statusLivechat = Template.instance().statusLivechat.get(); return { status: statusLivechat === 'available' ? 'status-online' : '', icon: statusLivechat === 'available' ? 'icon-toggle-on' : 'icon-toggle-off', hint: statusLivechat === 'available' ? t('Available') : t('Not_Available') }; }, isLivechatAvailable() { return Template.instance().statusLivechat.get() === 'available'; }, showQueueLink() { if (RocketChat.settings.get('Livechat_Routing_Method') !== 'Least_Amount') { return false; } return RocketChat.authz.hasRole(Meteor.userId(), 'livechat-manager') || (Template.instance().statusLivechat.get() === 'available' && RocketChat.settings.get('Livechat_show_queue_list_link')); }, activeLivechatQueue() { FlowRouter.watchPathChange(); if (FlowRouter.current().route.name === 'livechat-queue') { return 'active'; } } }); Template.livechat.events({ 'click .livechat-status'() { Meteor.call('livechat:changeLivechatStatus', (err /*, results*/) => { if (err) { return handleError(err); } }); }, 'click .inquiries .open-room'(event) { event.preventDefault(); event.stopPropagation(); swal({ title: t('Livechat_Take_Confirm'), text: `${ t('Message') }: ${ this.message }`, showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: t('Take_it') }, (isConfirm) => { if (isConfirm) { Meteor.call('livechat:takeInquiry', this._id, (error, result) => { if (!error) { RocketChat.roomTypes.openRouteLink(result.t, result); } }); } }); } }); Template.livechat.onCreated(function() { this.statusLivechat = new ReactiveVar(); this.autorun(() => { if (Meteor.userId()) { const user = RocketChat.models.Users.findOne(Meteor.userId(), { fields: { statusLivechat: 1 } }); this.statusLivechat.set(user.statusLivechat); } else { this.statusLivechat.set(); } }); this.subscribe('livechat:inquiry'); });
JavaScript
0
@@ -2238,16 +2238,19 @@ es . -open-roo +sidebar-ite m'(e
5de40384aaff3f9de3f0fc647451ca5be5b909db
test device
a/d/deviceSets.js
a/d/deviceSets.js
var deviceSets = [ { name : 'Simple Devices', devices : [ { name: 'iPhone 4', w: 320, h:480, type:'phone', rotated: { w:416, h:320} }, { name: 'Small Tablet', w: 600, h: 1000, type:'tablet' }, { name: 'Apple iPad', w: 768, h:1024, type:'tablet' }, { name: '15"', w: 1024, h:768, type:'desktop' }, { name: 'Macbook 13"', w: 1280, h:800, type:'laptop' }, ] }, { name : 'Common Devices', devices : [ { name: 'iPhone 4', w: 320, h:480, type:'phone', rotated: { w:416, h:320} }, { name: 'iPhone 5', w: 320, h:568, type:'phone', rotated: { w:568, h:320} }, { name: 'BlackBerry Curve', w: 480, h:360, type:'phone' }, { name: 'Nexus 4', w: 382, h:592, type:'phone', rotated: { w:416, h:320} }, { name: 'Galaxy S', w: 480, h:800, type:'phone', rotated: { w:800, h:480} }, { name: 'Nexus 7', w: 600, h:960, type:'tablet' }, { name: 'Nexus 10', w: 752, h:1280, type:'tablet' }, { name: 'Apple iPad', w: 768, h:1024, type:'tablet' }, { name: '15"', w: 1024, h:768, type:'desktop' }, { name: 'Macbook 13"', w: 1280, h:800, type:'laptop' }, { name: 'Macbook 15"', w: 1440, h:900, type:'laptop' }, { name: '27" Cinema Display', w: 2560, h:1440, type:'desktop' }, ] }, { name : 'Breakpoints', devices : [ { name: '1', w: 320, h: 480, type:'phone' }, { name: '2', w: 600, h: 1000, type:'tablet' }, { name: '3', w: 760, h: 1024 }, { name: '4', w: 1024, h: 768 }, ] } ];
JavaScript
0.000001
@@ -12,16 +12,182 @@ ets = %5B%0A +/*%0A %7B%0A name : 'One Device',%0A devices : %5B%0A %7B name: 'iPhone 4', w: 320, h:480, type:'phone', rotated: %7B w:416, h:320%7D %7D%0A %5D%0A %7D,%0A*/%0A %7B%0A @@ -591,16 +591,25 @@ ptop' %7D, + %0A
a9fa59c88f28c589bf2f12e31ce67264607de5a6
Add classname to table element
src/main/webapp/components/BuilderDataTable.js
src/main/webapp/components/BuilderDataTable.js
import * as React from 'react'; const HEADERS = ['no', 'text', 'log']; export const BuilderDataTable = props => { return ( <table> <thead> <BuilderRow header={true} data={HEADERS} /> </thead> <tbody> <BuilderRow data={} /> </tbody> </table> ); }
JavaScript
0.000002
@@ -46,16 +46,17 @@ S = %5B'no +. ', 'text @@ -127,24 +127,47 @@ (%0A %3Ctable + className='data-table' %3E%0A %3Cthe
1d8582589e826a2a62aba4f690488c62675a797b
Remove clutter message in Eslint plugin (#434)
lib/ExecutionControlEpic/Plugins/Eslint/Process/lsp.js
lib/ExecutionControlEpic/Plugins/Eslint/Process/lsp.js
/* eslint-disable */ const { createMessageConnection, StreamMessageReader, StreamMessageWriter, } = require("vscode-jsonrpc"); const { exec } = require("child_process"); const connection = createMessageConnection( new StreamMessageReader(process.stdin), new StreamMessageWriter(process.stdout), ); function getDiagnostics(openedPath) { exec( `${process.env.ESLINT_BINARY} ${openedPath} -f json`, { cwd: process.env.ESLINT_CWD }, (err, stdout, stderr) => { // Note: If eslint finds diagnostics in the code, it will return 1, and // err will be non-null; actual execution errors will be tested in stderr if (stderr) { void err; console.error("Error running Eslint: ", stderr.toString()); } else { try { const json = JSON.parse(stdout.toString()); connection.sendNotification("textDocument/publishDiagnostics", { uri: openedPath, diagnostics: json[0].messages.map(message => ({ source: "eslint", severity: message.severity > 1 ? 1 : 2, message: message.message, range: { start: { line: message.line - 1, character: message.column - 1, }, end: { line: message.endLine - 1, character: message.endColumn - 1, }, }, })), }); } catch (e) { console.error("Error in Eslint Language Server: ", e); } } }, ); } connection.onRequest("initialize", async () => { connection.onNotification("textDocument/didOpen", didOpenEvent => { console.error(didOpenEvent.textDocument.uri); getDiagnostics(didOpenEvent.textDocument.uri); }); connection.onNotification("textDocument/didSave", didSaveEvent => { getDiagnostics(didSaveEvent.textDocument.uri); }); }); connection.listen();
JavaScript
0
@@ -486,19 +486,59 @@ -// Note: If +if (stderr) %7B%0A // Note: err is non-null when esl @@ -574,32 +574,57 @@ code -, it will +%0A // (because the executable return +s 1 -, and%0A +)%0A @@ -632,29 +632,20 @@ // -err will be non-null; +To check for act @@ -668,53 +668,32 @@ rors +, w -ill be tested in stderr%0A if ( +e need to read stderr -) %7B %0A @@ -1736,58 +1736,8 @@ %3E %7B%0A - console.error(didOpenEvent.textDocument.uri);%0A
625bb1167d63829a941992d77455cbce650d2abd
Update config.js
bot/config.js
bot/config.js
// The WEBSOCKET server and port the bot should connect to. // Most of the time this isn't the same as the URL, check the `Request URL` of // the websocket. // If you really don't know how to do this... Run `node getserver.js URL`. // Fill in the URL of the client where `URL` is. // For example: `node getserver.js http://example-server.psim.us/` exports.server = 'cbc.pokecommunity.com'; exports.port = 8000; // This is the server id. // To know this one, you should check where the AJAX call 'goes' to when you // log in. // For example, on the Smogon server, it will say somewhere in the URL // ~~showdown, meaning that the server id is 'showdown'. // If you really don't know how to check this... run the said script above. exports.serverid = 'pokecommunity'; // The nick and password to log in with // If no password is required, leave pass empty exports.nick = 'PokeCommBot'; exports.pass = 'filler'; // The rooms that should be joined. // Joining Smogon's Showdown's Lobby is not allowed. exports.rooms = ['lobby']; // Any private rooms that should be joined. // Private rooms will be moderated differently (since /warn doesn't work in them). // The bot will also avoid leaking the private rooms through .seen exports.privaterooms = ['staff']; // The character text should start with to be seen as a command. // Note that using / and ! might be 'dangerous' since these are used in // Showdown itself. // Using only alphanumeric characters and spaces is not allowed. exports.commandcharacter = '.'; // The default rank is the minimum rank that can use a command in a room when // no rank is specified in settings.json exports.defaultrank = '%'; // Whether this file should be watched for changes or not. // If you change this option, the server has to be restarted in order for it to // take effect. exports.watchconfig = true; // Secondary websocket protocols should be defined here, however, Showdown // doesn't support that yet, so it's best to leave this empty. exports.secprotocols = []; // What should be logged? // 0 = error, ok, info, debug, recv, send // 1 = error, ok, info, debug, cmdr, send // 2 = error, ok, info, debug (recommended for development) // 3 = error, ok, info (recommended for production) // 4 = error, ok // 5 = error exports.debuglevel = 3; // Users who can use all commands regardless of their rank. Be very cautious // with this, especially on servers other than main. exports.excepts = []; // Whitelisted users are those who the bot will not enforce moderation for. exports.whitelist = ['PokeCommBot']; // Users in this list can use the regex autoban commands. Only add users who know how to write regular expressions and have your complete trust not to abuse the commands. exports.regexautobanwhitelist = []; // Add a link to the help for the bot here. When there is a link here, .help and .guide // will link to it. exports.botguide = ''; // Add a link to the git repository for the bot here for .git to link to. exports.fork = 'https://github.com/awolffromspace/PC-Battle-Server-Bot'; // This allows the bot to act as an automated moderator. If enabled, the bot will // mute users who send 6 lines or more in 6 or fewer seconds for 7 minutes. NOTE: THIS IS // BY NO MEANS A PERFECT MODERATOR OR SCRIPT. It is a bot and so cannot think for itself or // exercise moderator discretion. In addition, it currently uses a very simple method of // determining who to mute and so may miss people who should be muted, or mute those who // shouldn't. Use with caution. exports.allowmute = true; // The punishment values system allows you to customise how you want the bot to deal with // rulebreakers. Spamming has a points value of 2, all caps has a points value of 1, etc. exports.punishvals = { 1: 'warn', 2: 'mute', 3: 'hourmute', 4: 'hourmute', 5: 'lock' }; //This key is used to deliver requests from Google Spreadsheets. Used by the wifi room. exports.googleapikey = '';
JavaScript
0.000002
@@ -2424,24 +2424,30 @@ .excepts = %5B +'wolf' %5D;%0A%0A// White @@ -2888,16 +2888,77 @@ uide = ' +http://www.pokecommunity.com/showthread.php?t=289012#botguide ';%0A%0A// A
e29e91c0924fe6225fd627da896b2f2b365cda15
Remove requireOptions
AbstractFilter.js
AbstractFilter.js
/* backgrid-filter http://github.com/wyuenho/backgrid Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors Licensed under the MIT @license. */ (function (factory) { // CommonJS if (typeof exports == "object") { module.exports = factory(require("underscore"), require("backbone"), require("backgrid")); } // Browser else if (typeof _ !== "underscore" && typeof Backbone !== "undefined" && typeof Backgrid !== "undefined") { factory(_, Backbone, Backgrid); } }(function (_, Backbone, Backgrid) { "use strict"; /** AbstractFilter is a search form widget whose subclasses filter the current collection. @class Backgrid.Extension.AbstractFilter */ Backgrid.Extension.AbstractFilter = Backbone.View.extend({ /** @property */ tagName: "form", /** @property */ className: "backgrid-filter form-search", /** @property {function(Object, ?Object=): string} template */ template: _.template('<div class="input-prepend input-append"><span class="add-on"><i class="icon-search"></i></span><input class="searchbox" type="text" <% if (placeholder) { %> placeholder="<%- placeholder %>" <% } %> name="<%- name %>" /><span class="add-on"><a class="close" href="#">&times;</a></span></div>'), /** @property */ events: { "click .close": "handleClickClear", "submit": "handleSubmit" }, /** @property [wait=149] The time in milliseconds to wait since for since the last change to the search box's value before searching. This value can be adjusted depending on how often the search box is used and how large the search index is. */ wait: 149, /** @property {string} [name='q'] Query key */ name: "q", /** @property {string} [placeholder] The HTML5 placeholder to appear beneath the search box. */ placeholder: null, /** Debounces the #search and #clear methods. @param {Object} options @param {Backbone.Collection} options.collection @param {string} [options.name] @param {string} [options.placeholder] @param {string} [options.wait=149] */ initialize: function (options) { Backgrid.requireOptions(options, ["collection"]); Backbone.View.prototype.initialize.apply(this, arguments); this.wait = options.wait || this.wait; this.name = options.name || this.name; this.placeholder = options.placeholder || this.placeholder; // These methods should always be debounced }, searchBox: function () { return this.$el.find("input.searchbox"); }, setQuery: function(newValue) { this.searchBox().val(newValue); }, clearQuery: function() { this.searchBox().val(null); }, getQuery: function() { return this.searchBox().val(); }, handleSubmit: function (e) { e.preventDefault(); this.search(); }, handleClickClear: function (e) { e.preventDefault(); this.clear(); }, /** Renders a search form with a text box, optionally with a placeholder and a preset value if supplied during initialization. */ render: function () { this.$el.empty().append(this.template({ name: this.name, placeholder: this.placeholder, value: this.value })); this.delegateEvents(); return this; }, _debounceMethods: function (methodNames) { if (_.isString(methodNames)) methodNames = [methodNames]; this.undelegateEvents(); var methodName, method; for (var i = 0, l = methodNames.length; i < l; i++) { methodName = methodNames[i]; method = this[methodName]; this[methodName] = _.debounce(method, this.wait); } this.delegateEvents(); }, /** * Apply this filter. * @abstract */ search: function() { throw new Error('must be implemented by subclass!'); }, /** * Un-apply this filter. * @abstract */ clear: function() { throw new Error('must be implemented by subclass!'); } }); }));
JavaScript
0.000002
@@ -2315,68 +2315,8 @@ ) %7B%0A - Backgrid.requireOptions(options, %5B%22collection%22%5D);%0A
eb3d2d0423b79478d9d28ab092d4c7d28fd36846
Return in case of no data(no select query)
debug-db/src/main/assets/debugDbHome/js/app.js
debug-db/src/main/assets/debugDbHome/js/app.js
$( document ).ready(function() { getDBList(); $("#query").keypress(function(e){ if(e.which == 13) { queryFunction(); } }); //update currently selected database $( document ).on( "click", "#db-list .list-group-item", function() { $("#db-list .list-group-item").each(function() { $(this).removeClass('selected'); }); $(this).addClass('selected'); }); //update currently table database $( document ).on( "click", "#table-list .list-group-item", function() { $("#table-list .list-group-item").each(function() { $(this).removeClass('selected'); }); $(this).addClass('selected'); }); }); var isDatabaseSelected = true; function getData(tableName) { $.ajax({url: "getAllDataFromTheTable?tableName="+tableName, success: function(result){ result = JSON.parse(result); inflateData(result); }}); } function queryFunction() { var query = $('#query').val(); $.ajax({url: "query?query="+escape(query), success: function(result){ result = JSON.parse(result); inflateData(result); }}); } function downloadDb() { if (isDatabaseSelected) { $.ajax({url: "downloadDb", success: function(){ window.location = 'downloadDb'; }}); } } function getDBList() { $.ajax({url: "getDbList", success: function(result){ result = JSON.parse(result); var dbList = result.rows; $('#db-list').empty(); var isSelectionDone = false; for(var count = 0; count < dbList.length; count++){ if(dbList[count].indexOf("journal") == -1){ $("#db-list").append("<a href='#' id=" +dbList[count] + " class='list-group-item' onClick='openDatabaseAndGetTableList(\""+ dbList[count] + "\");'>" +dbList[count] + "</a>"); if(!isSelectionDone){ isSelectionDone = true; $('#db-list').find('a').trigger('click'); } } } }}); } function openDatabaseAndGetTableList(db) { if("APP_SHARED_PREFERENCES" == db) { $('#run-query').removeClass('active'); $('#run-query').addClass('disabled'); $('#selected-db-info').removeClass('active'); $('#selected-db-info').addClass('disabled'); isDatabaseSelected = false; $("#selected-db-info").text("SharedPreferences"); } else { $('#run-query').removeClass('disabled'); $('#run-query').addClass('active'); $('#selected-db-info').removeClass('disabled'); $('#selected-db-info').addClass('active'); isDatabaseSelected = true; $("#selected-db-info").text("Export Selected Database : "+db); } $.ajax({url: "getTableList?database="+db, success: function(result){ result = JSON.parse(result); var tableList = result.rows; var dbVersion = result.dbVersion; if("APP_SHARED_PREFERENCES" != db) { $("#selected-db-info").text("Export Selected Database : "+db +" Version : "+dbVersion); } $('#table-list').empty() for(var count = 0; count < tableList.length; count++){ var tableName = tableList[count]; $("#table-list").append("<a href='#' data-db-name='"+db+"' data-table-name='"+tableName+"' class='list-group-item' onClick='getData(\""+ tableName + "\");'>" +tableName + "</a>"); } }}); } function inflateData(result){ if(result.isSuccessful){ if(!result.isSelectQuery){ showSuccessInfo("Query Executed Successfully"); } var columnHeader = result.tableInfos; // set function to return cell data for different usages like set, display, filter, search etc.. for(var i = 0; i < columnHeader.length; i++) { columnHeader[i]['targets'] = i; columnHeader[i]['data'] = function(row, type, val, meta) { var dataType = row[meta.col].dataType; if (type == "sort" && dataType == "boolean") { return row[meta.col].value ? 1 : 0; } return row[meta.col].value; } } var columnData = result.rows; var tableId = "#db-data"; if ($.fn.DataTable.isDataTable(tableId) ) { $(tableId).DataTable().destroy(); } $("#db-data-div").remove(); $("#parent-data-div").append('<div id="db-data-div"><table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered display" id="db-data"></table></div>'); $(tableId).dataTable({ "data": columnData, "columnDefs": columnHeader, 'bPaginate': true, 'searching': true, 'bFilter': true, 'bInfo': true, "bSort" : true, "scrollX": true, "iDisplayLength": 10, "dom": "Bfrtip", select: 'single', responsive: true, altEditor: true, // Enable altEditor buttons: [ { extend: 'selected', // Bind to Selected row text: 'Edit', name: 'edit' // do not change name } ] }) //attach row-updated listener $(tableId).on('update-row.dt', function (e, updatedRowData, callback) { var updatedRowDataArray = JSON.parse(updatedRowData); //add value for each column var data = columnHeader; for(var i = 0; i < data.length; i++) { data[i].value = updatedRowDataArray[i].value; data[i].dataType = updatedRowDataArray[i].dataType; } //send update table data request to server updateTableData(data, callback); }); // hack to fix alignment issue when scrollX is enabled $(".dataTables_scrollHeadInner").css({"width":"100%"}); $(".table ").css({"width":"100%"}); }else{ if(!result.isSelectQuery){ showSuccessInfo("Query Execution Failed"); }else { showErrorInfo("Some Error Occurred"); } } } //send update database request to server function updateTableData(updatedData, callback) { //get currently selected element var selectedTableElement = $("#table-list .list-group-item.selected"); var filteredUpdatedData = updatedData.map(function(columnData){ return { title: columnData.title, isPrimary: columnData.isPrimary, value: columnData.value, dataType: columnData.dataType } }); //build request parameters var requestParameters = {}; requestParameters.dbName = selectedTableElement.attr('data-db-name'); requestParameters.tableName = selectedTableElement.attr('data-table-name');; requestParameters.updatedData = encodeURIComponent(JSON.stringify(filteredUpdatedData)); //execute request $.ajax({ url: "updateTableData", type: 'GET', data: requestParameters, success: function(response) { response = JSON.parse(response); if(response.isSuccessful){ console.log("Data updated successfully"); callback(true); showSuccessInfo("Data Updated Successfully"); } else { console.log("Data updated failed"); callback(false); } } }) } function showSuccessInfo(message){ var snackbar = document.getElementById("snackbar") snackbar.className = "show"; snackbar.style.backgroundColor = "#5cb85c"; snackbar.innerHTML = message; setTimeout(function(){ snackbar.className = snackbar.className.replace("show", ""); }, 2000); } function showErrorInfo(message){ var snackbar = document.getElementById("snackbar") snackbar.className = "show"; snackbar.style.backgroundColor = "#d9534f"; snackbar.innerHTML = message; setTimeout(function(){ snackbar.className = snackbar.className.replace("show", ""); }, 2000); }
JavaScript
0.001765
@@ -3683,24 +3683,41 @@ essfully%22);%0A + return;%0A %7D%0A%0A
3ac80b882464c338fe586905a9ddbf7a2cd347d8
Integrate DocSearch (Algolia)
docs/.vuepress/config.js
docs/.vuepress/config.js
module.exports = { title: 'chartjs-plugin-datalabels', description: 'Display labels on data for any type of charts.', ga: 'UA-99068522-2', head: [ ['link', { rel: 'icon', href: `/favicon.png` }], ], themeConfig: { repo: 'chartjs/chartjs-plugin-datalabels', logo: '/favicon.png', lastUpdated: 'Last Updated', editLinks: true, docsDir: 'docs', nav: [ { text: 'Home', link: '/' }, { text: 'Guide', link: '/guide/' }, { text: 'Samples', link: 'https://chartjs-plugin-datalabels.netlify.com/samples/' } ], sidebar: [ '/guide/', '/guide/getting-started', '/guide/options', '/guide/positioning', '/guide/formatting', '/guide/events' ] } }
JavaScript
0.000007
@@ -403,24 +403,161 @@ ir: 'docs',%0A + algolia: %7B%0A apiKey: '7224f458f773f7cf4cbbc4c53621d30c',%0A indexName: 'chartjs-plugin-datalabels'%0A %7D,%0A nav:
427b80bda3c386e70a11e409c4a6b8c2f445d714
configure http client with current selected engine
webapps/client/scripts/api/index.js
webapps/client/scripts/api/index.js
'use strict'; define([ 'angular', 'camunda-bpm-sdk', 'camunda-bpm-sdk-mock' ], function( angular, CamSDK, MockClient ) { var apiModule = angular.module('cam.tasklist.client', []); apiModule.value('HttpClient', CamSDK.Client); apiModule.value('CamForm', CamSDK.Form); apiModule.value('MockHttpClient', MockClient); apiModule.factory('camAPIHttpClient', [ 'MockHttpClient', '$rootScope', '$location', '$translate', 'Notifications', function(MockHttpClient, $rootScope, $location, $translate, Notifications) { function AngularClient(config) { var Client = (config.mock === true ? MockHttpClient : CamSDK.Client.HttpClient); this._wrapped = new Client(config); } angular.forEach(['post', 'get', 'load', 'put', 'del', 'options', 'head'], function(name) { AngularClient.prototype[name] = function(path, options) { if (!options.done) { return; } if (!$rootScope.authentication) { return options.done(new Error('Not authenticated')); } var original = options.done; options.done = function(err, result) { $rootScope.$apply(function() { // in case the session expired if (err && err.status === 401) { // broadcast that the authentication changed $rootScope.$broadcast('authentication.changed', null); // set authentication to null $rootScope.authentication = null; $translate([ 'SESSION_EXPIRED', 'SESSION_EXPIRED_MESSAGE' ]).then(function(translations) { Notifications.addError({ status: translations.SESSION_EXPIRED, message: translations.SESSION_EXPIRED_MESSAGE, exclusive: true }); }); // broadcast event that a login is required // proceeds a redirect to /login $rootScope.$broadcast('authentication.login.required'); return; } original(err, result); }); }; this._wrapped[name](path, options); }; }); angular.forEach(['on', 'once', 'off', 'trigger'], function(name) { AngularClient.prototype[name] = function() { this._wrapped[name].apply(this, arguments); }; }); return AngularClient; }]); apiModule.factory('camAPI', [ 'camAPIHttpClient', function(camAPIHttpClient) { var conf = { apiUri: 'engine-rest/engine', HttpClient: camAPIHttpClient }; if (window.tasklistConf) { for (var c in window.tasklistConf) { conf[c] = window.tasklistConf[c]; } } return new CamSDK.Client(conf); }]); // apiModule.factory('camForm', ['CamForm', function(CamEmbeddedForm) { // return // }]); return apiModule; });
JavaScript
0
@@ -2509,16 +2509,37 @@ lient',%0A + '$window',%0A functi @@ -2557,19 +2557,292 @@ tpClient -) %7B +, $window) %7B%0A%0A function getCurrentEngine() %7B%0A var uri = $window.location.href;%0A%0A var match = uri.match(/%5C/app%5C/tasklist%5C/(%5Cw+)(%7C%5C/)/);%0A if (match) %7B%0A return match%5B1%5D;%0A %7D else %7B%0A throw new Error('no process engine selected');%0A %7D%0A %7D%0A %0A var @@ -2882,16 +2882,20 @@ ne-rest/ +api/ engine', @@ -2929,16 +2929,50 @@ tpClient +,%0A engine: getCurrentEngine() %0A %7D;%0A @@ -2980,16 +2980,17 @@ if ( +$ window.t @@ -3024,16 +3024,17 @@ ar c in +$ window.t @@ -3066,16 +3066,17 @@ nf%5Bc%5D = +$ window.t @@ -3154,107 +3154,8 @@ );%0A%0A - // apiModule.factory('camForm', %5B'CamForm', function(CamEmbeddedForm) %7B%0A // return%0A // %7D%5D);%0A%0A re
7f09678728564e1ac3963f96b27c0cbd79885366
Add upgrading doc in the doc menu
docs/.vuepress/config.js
docs/.vuepress/config.js
var Prism = require('prismjs'); var loadLanguages = require('prismjs/components/'); loadLanguages(['php']); module.exports = { title: 'Sharp', base: '/docs/', themeConfig: { nav: [ { text: 'Home', link: '/' }, { text: 'Documentation', link: '/guide/' }, { text: 'Demo', link: 'http://sharp.code16.fr/sharp/' }, { text: 'Github', link:'https://github.com/code16/sharp' }, { text: 'Medium', link:'https://medium.com/code16/tagged/sharp' }, ], sidebar: { '/guide/': [ { title: 'Introduction', collapsable: false, children: [ '', 'authentication', ] }, { title: 'Entity Lists', collapsable: false, children: [ 'building-entity-list', 'filters', 'commands', 'entity-states', 'reordering-instances', ] }, { title: 'Entity Forms', collapsable: false, children: [ 'building-entity-form', 'entity-authorizations', 'multiforms', 'single-form', 'custom-form-fields' ] }, { title: 'Entity Shows', collapsable: false, children: [ 'building-entity-show', 'single-show', 'custom-show-fields' ] }, { title: 'Dashboards', collapsable: false, children: [ 'dashboard', ...[ 'graph', 'panel', 'ordered-list', ].map(page => `dashboard-widgets/${page}`), ], }, { title: 'Generalities', collapsable: false, children: [ 'building-menu', 'how-to-transform-data', 'context', 'sharp-built-in-solution-for-uploads', 'form-data-localization', 'testing-with-sharp', 'artisan-generators', 'style-visual-theme' ] }, { title: 'Form fields', collapsable: false, children: [ 'text', 'textarea', 'markdown', 'wysiwyg', 'number', 'html', 'check', 'date', 'upload', 'select', 'autocomplete', 'tags', 'list', 'autocomplete-list', 'geolocation', ].map(page => `form-fields/${page}`), }, { title: 'Show fields', collapsable: false, children: [ 'text', 'picture', 'list', 'file', 'embedded-entity-list', ].map(page => `show-fields/${page}`), }, { title: 'Migrations guide', collapsable: false, children: [ 'upgrading/4.2', 'upgrading/4.1.3', 'upgrading/4.1', ], }, ] }, algolia: { apiKey: 'd88cea985d718328d4b892ff6a05dba8', indexName: 'code16_sharp', // debug: true, algoliaOptions: { hitsPerPage: 5, }, } }, markdown: { extendMarkdown: md => { md.renderer.rules['code_inline'] = (tokens, idx, options, env, slf) => { let token = tokens[idx]; return '<code class="inline">' + Prism.highlight(token.content, Prism.languages.php) + '</code>'; }; } }, scss: { implementation: require('sass'), } };
JavaScript
0
@@ -4118,32 +4118,73 @@ children: %5B%0A + 'upgrading/5.0',%0A
ddff29a9b4060e144dbdab2d2757d6e91157b091
fix require in shopper example
example/shopper.js
example/shopper.js
'use strict'; var Monito = require('../lib/index'); let chimp = new Monito({ register: (monito, next) => { next(null, 'getProfile'); }, getProfile: (monito, next) => { next(null, { browse: 4 }, 'shop'); }, browse: (monito, next) => { next(null, { browse: 6 }, 'shop'); }, shop: (monito, next) => { next(null, 'logout'); }, logout: (monito, next) => { // next(null, 'register'); -- Uncomment to have it running forever next(); } }, 'register'); chimp.on('error', function (err) { console.log('An error has occurred'); console.log(err); }); chimp.on('state', function (state) { console.log('New state:', state); }); chimp.on('end', function () { console.log('Ok bye!'); }); chimp.start();
JavaScript
0.000013
@@ -41,13 +41,14 @@ lib/ -index +monito ');%0A
337771fb02274120ca4b584050446a4df84edfa8
build for publish
memoizerific.min.gzip.js
memoizerific.min.gzip.js
JXWM6W>8$Le0LHBRlmEIlm p<K+X$(R4W)%WiJ[X+y੐0u ur#lUE8ၳ?[V Yq~v{bWs:IȃzG4ocR<ݺfP/E*A]܄c '"VZݷ"D"E̙ة_f0:_*v=bp돁;d9)Zi4Il)oKfZ=U_>vǧ?~N˩ۚFǺ]>LX+72mQwv%؊伳A[-X3g ^DunushX-X"@Cqh۲΂/ ϿOxX؆1.c1\+9.)$ )ywz2ʳ-U VL2WYYauF]cV{Vg/Fqj7H6`ǫcsyjF$&cr L6H:p{Ln>%{O=9>tyhh<3ЋzM'7סLւca ck 3 UCBMuR+\#&vkN{Kr4~pl¯p~o) -]oiŎwYgG> 0t3 tU7,w,~ll#KX> dcU|.r]@r9|@b(B\ɘ2 a)Θy34q:^ N/*;^ ]%$\Smq,X, ]~۰'Pq^|ȀqiP K[©zlWUJKiM)<Ψ{Cc5nDt3Զ%-%!@N lt4swd݈ӏ 4gkГ/3ֱSyvz0sT]FP$ K$嫛Xz}vѡ>Nyܺ))j_[&׊/E`LY):_GZmr9 T0f¬ .iQ[mHBi͞Q+_JCY9֐@ _C*nFˇ><LU!`{6ܑl <I>ZU^Y\]M_Ў&04-H!H|Cc#-RVPy.=d!9|Ԅ,g$<'ڵlOr [^p [=Ip$J(moIh2=0O̴:ВUu5 4BXj/v`? @/P$ѦB7Ѕn ? ˥
JavaScript
0
8e315f79565b3e9d69522065554a5f90d1dd6af1
fix default DEVELOPMENT variable on php service
services_conf/php.js
services_conf/php.js
module.exports.prompt = { // use nested prompt "development": [{ name: "AERIAWORK_ENABLED", message: "Do you want to preload AeriaWork?".magenta, type: 'list', pageSize: 2, required: true, choices: [{ name: "yes", value: 1 }, { name: "no", value: '' }] }, { name: "DOMAIN", message: "[DOMAIN] Endpoint to access this container (equals VIRTUAL_HOST by default)".magenta, required: false }, { name: "PHP_MODS", message: "Php modules needed for the project separated by space (ignored in alpine)".magenta, default: "curl", required: false }], "production": [{ name: "AERIAWORK_ENABLED", message: "Do you want to preload AeriaWork?".magenta, type: 'list', pageSize: 2, required: true, choices: [{ name: "yes", value: 1 }, { name: "no", value: '' }] }, { name: "DOMAIN", message: "[DOMAIN] Endpoint to access this container (equals VIRTUAL_HOST by default)".magenta, required: false }] } module.exports.map = { //DOMAIN: ["DOMAIN", "HTTP_HOST"], //PUBLIC_URL: "PUBLIC_URL", AERIAWORK_ENABLED: "AERIAWORK_ENABLED", CORE_ENABLED: "CORE_ENABLED" } module.exports.path = "images/php/php" module.exports.defaults = { dev: { TZ: "Europe/Rome", // Defaults DOCKER: "1", // Defaults ENV: "local", // Defaults WP_POST_REVISIONS: "false", // Defaults WP_USE_THEMES: "false", // Defaults WP_LANG: "it_IT", // Defaults WORKDIR: "/www", DEVELOPMENT: 1, // Defaults DB_HOST: "mysql", DB_NAME: "", // Match with MySQL DB_USER: "", // Match with MySQL DB_PASS: "", // Match with MySQL PROJECT_NAME: "", // Match with main APP_ID: "", // Match with main PORT: "80", // Match with main PHP_MODS: "curl" }, prod: { TZ: "Europe/Rome", // Defaults DOCKER: "1", // Defaults ENV: "local", // Defaults WP_POST_REVISIONS: "false", // Defaults WP_USE_THEMES: "false", // Defaults WP_LANG: "it_IT", // Defaults WORKDIR: "/www", DEVELOPMENT: 0, // Defaults DB_HOST: "mysql", DB_NAME: "", // Match with MySQL DB_USER: "", // Match with MySQL DB_PASS: "", // Match with MySQL PROJECT_NAME: "", // Match with main APP_ID: "", // Match with main PORT: "80", // Match with main PHP_MODS: "curl" } } module.exports.dependencies = [ { PROJECT_NAME: {main: "PROJECT_NAME"} }, { APP_ID: {main: "PROJECT_NAME"} }, { DB_NAME: {main: "PROJECT_NAME"} }, { DB_USER: {mysql: "MYSQL_USER"} }, { DB_PASS: {mysql: "MYSQL_PASSWORD"} }, { DOMAIN: {nginx: "DOMAIN"} }, { PUBLIC_URL: {nginx: "DOMAIN"} } ]
JavaScript
0
@@ -1588,17 +1588,19 @@ OPMENT: -1 +%221%22 , @@ -2253,17 +2253,19 @@ OPMENT: -0 +%220%22 ,
54c789c8eb2a342ac0d0ad809a14dbb21b10c87b
use ES6 class instead of createClass
example/src/app.js
example/src/app.js
/* global google */ import React from 'react'; import ReactDOM from 'react-dom'; import Geosuggest from '../../src/Geosuggest'; var App = React.createClass({ // eslint-disable-line /** * Render the example app * @return {Function} React render function */ render: function() { var fixtures = [ {label: 'New York', location: {lat: 40.7033127, lng: -73.979681}}, {label: 'Rio', location: {lat: -22.066452, lng: -42.9232368}}, {label: 'Tokyo', location: {lat: 35.673343, lng: 139.710388}} ]; return ( // eslint-disable-line <div> <Geosuggest fixtures={fixtures} onFocus={this.onFocus} onBlur={this.onBlur} onChange={this.onChange} onSuggestSelect={this.onSuggestSelect} onSuggestNoResults={this.onSuggestNoResults} location={new google.maps.LatLng(53.558572, 9.9278215)} radius="20" /> </div> ); }, /** * When the input receives focus */ onFocus: function() { console.log('onFocus'); // eslint-disable-line }, /** * When the input loses focus * @param {String} value The user input */ onBlur: function(value) { console.log('onBlur', value); // eslint-disable-line }, /** * When the input got changed * @param {String} value The new value */ onChange: function(value) { console.log('input changes to :' + value); // eslint-disable-line }, /** * When a suggest got selected * @param {Object} suggest The suggest */ onSuggestSelect: function(suggest) { console.log(suggest); // eslint-disable-line }, /** * When there are no suggest results * @param {String} userInput The user input */ onSuggestNoResults: function(userInput) { console.log('onSuggestNoResults for :' + userInput); // eslint-disable-line } }); ReactDOM.render(<App />, document.getElementById('app')); // eslint-disable-line
JavaScript
0.000003
@@ -127,826 +127,43 @@ ';%0A%0A -var App = React.createClass(%7B // eslint-disable-line%0A /**%0A * Render the example app%0A * @return %7BFunction%7D React render function%0A */%0A render: function() %7B%0A var fixtures = %5B%0A %7Blabel: 'New York', location: %7Blat: 40.7033127, lng: -73.979681%7D%7D,%0A %7Blabel: 'Rio', location: %7Blat: -22.066452, lng: -42.9232368%7D%7D,%0A %7Blabel: 'Tokyo', location: %7Blat: 35.673343, lng: 139.710388%7D%7D%0A %5D;%0A%0A return ( // eslint-disable-line%0A %3Cdiv%3E%0A %3CGeosuggest%0A fixtures=%7Bfixtures%7D%0A onFocus=%7Bthis.onFocus%7D%0A onBlur=%7Bthis.onBlur%7D%0A onChange=%7Bthis.onChange%7D%0A onSuggestSelect=%7Bthis.onSuggestSelect%7D%0A onSuggestNoResults=%7Bthis.onSuggestNoResults%7D%0A location=%7Bnew google.maps.LatLng(53.558572, 9.9278215)%7D%0A radius=%2220%22 /%3E%0A %3C/div%3E%0A );%0A %7D,%0A +class App extends React.Component %7B %0A / @@ -215,26 +215,16 @@ onFocus -: function () %7B%0A @@ -266,33 +266,32 @@ disable-line%0A %7D -, %0A%0A /**%0A * Whe @@ -370,26 +370,16 @@ onBlur -: function (value) @@ -432,33 +432,32 @@ disable-line%0A %7D -, %0A%0A /**%0A * Whe @@ -537,26 +537,16 @@ onChange -: function (value) @@ -612,33 +612,32 @@ disable-line%0A %7D -, %0A%0A /**%0A * Whe @@ -726,26 +726,16 @@ stSelect -: function (suggest @@ -790,17 +790,16 @@ line%0A %7D -, %0A%0A /**%0A @@ -913,18 +913,8 @@ ults -: function (use @@ -1011,11 +1011,764 @@ %7D%0A -%7D); +%0A /**%0A * Render the example app%0A * @return %7BFunction%7D React render function%0A */%0A render() %7B%0A var fixtures = %5B%0A %7Blabel: 'New York', location: %7Blat: 40.7033127, lng: -73.979681%7D%7D,%0A %7Blabel: 'Rio', location: %7Blat: -22.066452, lng: -42.9232368%7D%7D,%0A %7Blabel: 'Tokyo', location: %7Blat: 35.673343, lng: 139.710388%7D%7D%0A %5D;%0A%0A return ( // eslint-disable-line%0A %3Cdiv%3E%0A %3CGeosuggest%0A fixtures=%7Bfixtures%7D%0A onFocus=%7Bthis.onFocus%7D%0A onBlur=%7Bthis.onBlur%7D%0A onChange=%7Bthis.onChange%7D%0A onSuggestSelect=%7Bthis.onSuggestSelect%7D%0A onSuggestNoResults=%7Bthis.onSuggestNoResults%7D%0A location=%7Bnew google.maps.LatLng(53.558572, 9.9278215)%7D%0A radius=%2220%22 /%3E%0A %3C/div%3E%0A );%0A %7D%0A%7D %0A%0ARe
4d6fea6551e8d41d01a17ba62757892fd42f37e4
Fix for window variable in compatibility.js
src/main/webapp/js_src/gitana/compatibility.js
src/main/webapp/js_src/gitana/compatibility.js
/** * This gets added into the Gitana Driver to ensure compilation time compatibility with * the Appcelerator Titanium framework. */ /* jQuery Sizzle - these are to fool the Ti compiler into not reporting errors! */ /** * The driver assumes a globally-scoped "window" variable which is a legacy of browser-compatibility. * Frameworks such as Titanium do not have a window root-scoped variable, so we fake one. * * At minimum, the window variable must have a setTimeout variable. */ if (!(typeof window === "undefined")) { window = { "setTimeout": function(func, seconds) { setTimeout(func, seconds); } } }
JavaScript
0
@@ -491,10 +491,8 @@ %0Aif -(! (typ @@ -518,17 +518,16 @@ efined%22) -) %0A%7B%0A w
34aba5d0d74df07e5b905655d2e335cbdbcea246
use TextArea for body
web/js/propilex/models/Document.js
web/js/propilex/models/Document.js
define( [ 'moment', 'backbone' ], function (moment, Backbone) { return Backbone.Model.extend({ dateFormat: 'YYYY-MM-DD HH:mm:ss', defaults: { title: '', body: '' }, schema: { title: { type: 'Text', validators: [ 'required' ] }, body: { type: 'Text', validators: [ 'required' ] } }, url : function() { var base = $('body').data('api-url') + '/documents/'; return this.isNew() ? base : base + this.id; }, parse: function (responseObject) { if (responseObject.document) { return responseObject.document; } return responseObject; }, getHumanizedDate: function () { if (undefined !== this.get('created_at')) { return moment(this.get('created_at').date, this.dateFormat).fromNow(); } return ''; }, toViewJSON: function () { return _.extend(this.toJSON(), { humanized_date: this.getHumanizedDate() }); } }); } );
JavaScript
0
@@ -383,32 +383,36 @@ : %7B type: 'Text +Area ', validators: %5B
5d43409086824f3f5c77adcc3f892c7964f80c2f
Paste HTML content into email templates
src/Oro/Bundle/FormBundle/Resources/public/js/app/views/wysiwig-editor/txt-html-transformer.js
src/Oro/Bundle/FormBundle/Resources/public/js/app/views/wysiwig-editor/txt-html-transformer.js
define(function() { 'use strict'; return { text2html: function(content) { // keep paragraphs at least return '<p>' + String(content).replace(/(\n\r?|\r\n?)/g, '</p><p>') + '</p>'; }, html2text: function(content) { return String(content) .replace(/<head>[^]*<\/head>/, '') .replace(/(<\/?[^>]+>|&[^;]+;)/g, ''); } }; });
JavaScript
0
@@ -411,16 +411,95 @@ )/g, '') +%0A .replace(/%5Cs*%5Cn%7B2,%7D/g, '%5Cn%5Cn')%0A .trim() ;%0A
befdc7e0cd121ddaa60ba656cd60f5d1fc1b7f00
rename some consts
src/store/actions/userSession.actions.js
src/store/actions/userSession.actions.js
import axios from 'axios'; import history from '../configuration/history'; import { getAccessToken, setAccessToken } from '../api'; import { CHECK_LOGGED_STATUS, LOGIN_START, LOGIN_SUCCESS, LOGIN_FAILURE, } from '../constants'; import { requestStart, requestComplete } from './request.actions'; import { getRandomString } from '../../helpers/getRandomString'; const clientId = process.env.REACT_APP_CLIENT_ID; const scope = process.env.REACT_APP_SCOPE; const state = getRandomString(); const URL_EXCHANGE_CODE_ON_TOKEN = process.env.REACT_APP_GITHUB_TOKEN_URL; const URL_GET_ACCESS_TOKEN = process.env.REACT_APP_JANUS_TOKEN_URL; const URL_AUTHORIZE = process.env.REACT_APP_GITHUB_AUTHORIZE_URL; export const getJWTtoken = (hash) => async dispatch => { const getParameterByName = (name, url) => { if (!url) url = window.location.href; name = name.replace(/[\[\]]/g, '\\$&'); const regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'); const results = regex.exec(url); if (!results) return null; if (!results[2]) return ''; return decodeURIComponent(results[2].replace(/\+/g, ' ')); }; const extractToken = (string) => { const param = 'access_token'; const name = param.replace(/[\[\]]/g, '\\$&'); const regex = new RegExp(name + '(=([^&#]*)|&|#|$)'); const results = regex.exec(string); if (!results) return null; if (!results[2]) return ''; return decodeURIComponent(results[2].replace(/\+/g, ' ')); }; const extractParameter = (hash, parameter, url) => getParameterByName(parameter, url); const code = extractParameter(hash, 'code'); try { dispatch(requestStart()); const response = await axios.post( `${URL_EXCHANGE_CODE_ON_TOKEN}?client_id=${clientId}&code=${code}` ); // extract access_token const accessToken = await extractToken(response.data); // set Authorization headers axios.defaults.headers.common['Authorization'] = `Bearer ${accessToken}`; const finalResponse = await axios.post( `${URL_GET_ACCESS_TOKEN}/login?provider=github`, ); // receive JWT token to use Janus-GW const JWTtoken = finalResponse.data.access_token; setAccessToken(JWTtoken); history.push('/'); dispatch(getUserStatus()); dispatch(requestComplete()); } catch (error) { console.log(error); } }; export const checkLoggedStatus = () => ({ type: CHECK_LOGGED_STATUS, }); export const loginRequest = () => ({ type: LOGIN_START, }); export const loginSuccess = () => ({ type: LOGIN_SUCCESS, }); export const loginFailure = () => ({ type: LOGIN_FAILURE, payload: 'The login or password you entered is incorrect.' }); export const authorizeThroughGithub = () => async dispatch => { dispatch(requestStart()); window.location.href = `${URL_AUTHORIZE}?response_type=code&state=${state}&client_id=${clientId}&scope=${scope}`; }; export const getUserStatus = () => dispatch => { dispatch(checkLoggedStatus()); if (getAccessToken()) { dispatch(loginSuccess()); } else { history.push('/login'); } };
JavaScript
0.000164
@@ -507,32 +507,26 @@ nst URL_ -EXCHANGE_CODE_ON +GET_GITHUB _TOKEN = @@ -576,29 +576,28 @@ nst URL_GET_ -ACCES +JANU S_TOKEN = pr @@ -639,24 +639,31 @@ ;%0Aconst URL_ +GITHUB_ AUTHORIZE = @@ -1803,24 +1803,18 @@ URL_ -EXCHANGE_CODE_ON +GET_GITHUB _TOK @@ -2153,13 +2153,12 @@ GET_ -ACCES +JANU S_TO @@ -2924,24 +2924,24 @@ stStart());%0A - window.l @@ -2962,16 +2962,23 @@ %60$%7BURL_ +GITHUB_ AUTHORIZ
fa140a517e4f4ac764f6ff2a9d0730dfca30b938
Work around jsdom TextDecoder limitation
tests/js/setup-globals.js
tests/js/setup-globals.js
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ window.webStoriesEditorSettings = {}; window.webStoriesDashboardSettings = {}; global.wp = { media: { controller: { Library: { prototype: { defaults: { contentUserSetting: jest.fn(), }, }, }, Cropper: { extend: jest.fn(), }, }, View: { extend: jest.fn(), }, view: { Toolbar: { Select: { extend: jest.fn(), }, }, MediaFrame: { Select: { extend: jest.fn(), }, }, }, }, }; global.IntersectionObserver = class IntersectionObserver { observe() {} unobserve() {} disconnect() {} }; // eslint-disable-next-line jest/prefer-spy-on global.matchMedia = jest.fn().mockImplementation((query) => ({ matches: false, media: query, onchange: null, addListener: jest.fn(), // deprecated removeListener: jest.fn(), // deprecated addEventListener: jest.fn(), removeEventListener: jest.fn(), dispatchEvent: jest.fn(), }));
JavaScript
0
@@ -589,22 +589,105 @@ e.%0A */%0A%0A -window +/**%0A * External dependencies%0A */%0Aimport %7B TextEncoder, TextDecoder %7D from 'util';%0A%0Aglobal .webStor @@ -714,14 +714,14 @@ %7B%7D;%0A -window +global .web @@ -1690,8 +1690,234 @@ ),%0A%7D));%0A +%0A// These are not yet available in jsdom environment.%0A// See https://github.com/facebook/jest/issues/9983.%0A// See https://github.com/jsdom/jsdom/issues/2524.%0Aglobal.TextEncoder = TextEncoder;%0Aglobal.TextDecoder = TextDecoder;%0A
d4231b3848adf796e4c2e10108dcd99651823e01
Make "ko.computed" an alias for "ko.dependentObservable"
src/subscribables/dependentObservable.js
src/subscribables/dependentObservable.js
function prepareOptions(evaluatorFunctionOrOptions, evaluatorFunctionTarget, options) { if (evaluatorFunctionOrOptions && typeof evaluatorFunctionOrOptions == "object") { // Single-parameter syntax - everything is on this "options" param options = evaluatorFunctionOrOptions; } else { // Multi-parameter syntax - construct the options according to the params passed options = options || {}; options["read"] = evaluatorFunctionOrOptions || options["read"]; options["owner"] = evaluatorFunctionTarget || options["owner"]; } // By here, "options" is always non-null if (typeof options["read"] != "function") throw "Pass a function that returns the value of the dependentObservable"; return options; } ko.dependentObservable = function (evaluatorFunctionOrOptions, evaluatorFunctionTarget, options) { var _latestValue, _hasBeenEvaluated = false, options = prepareOptions(evaluatorFunctionOrOptions, evaluatorFunctionTarget, options); // Build "disposeWhenNodeIsRemoved" and "disposeWhenNodeIsRemovedCallback" option values // (Note: "disposeWhenNodeIsRemoved" option both proactively disposes as soon as the node is removed using ko.removeNode(), // plus adds a "disposeWhen" callback that, on each evaluation, disposes if the node was removed by some other means.) var disposeWhenNodeIsRemoved = (typeof options["disposeWhenNodeIsRemoved"] == "object") ? options["disposeWhenNodeIsRemoved"] : null; var disposeWhenNodeIsRemovedCallback = null; if (disposeWhenNodeIsRemoved) { disposeWhenNodeIsRemovedCallback = function() { dependentObservable.dispose() }; ko.utils.domNodeDisposal.addDisposeCallback(disposeWhenNodeIsRemoved, disposeWhenNodeIsRemovedCallback); var existingDisposeWhenFunction = options["disposeWhen"]; options["disposeWhen"] = function () { return (!ko.utils.domNodeIsAttachedToDocument(disposeWhenNodeIsRemoved)) || ((typeof existingDisposeWhenFunction == "function") && existingDisposeWhenFunction()); } } var _subscriptionsToDependencies = []; function disposeAllSubscriptionsToDependencies() { ko.utils.arrayForEach(_subscriptionsToDependencies, function (subscription) { subscription.dispose(); }); _subscriptionsToDependencies = []; } function evaluate() { // Don't dispose on first evaluation, because the "disposeWhen" callback might // e.g., dispose when the associated DOM element isn't in the doc, and it's not // going to be in the doc until *after* the first evaluation if ((_hasBeenEvaluated) && typeof options["disposeWhen"] == "function") { if (options["disposeWhen"]()) { dependentObservable.dispose(); return; } } try { disposeAllSubscriptionsToDependencies(); ko.dependencyDetection.begin(function(subscribable) { _subscriptionsToDependencies.push(subscribable.subscribe(evaluate)); }); _latestValue = options["owner"] ? options["read"].call(options["owner"]) : options["read"](); } finally { ko.dependencyDetection.end(); } dependentObservable.notifySubscribers(_latestValue); _hasBeenEvaluated = true; } function dependentObservable() { if (arguments.length > 0) { if (typeof options["write"] === "function") { // Writing a value var valueToWrite = arguments[0]; options["owner"] ? options["write"].call(options["owner"], valueToWrite) : options["write"](valueToWrite); } else { throw "Cannot write a value to a dependentObservable unless you specify a 'write' option. If you wish to read the current value, don't pass any parameters."; } } else { // Reading the value if (!_hasBeenEvaluated) evaluate(); ko.dependencyDetection.registerDependency(dependentObservable); return _latestValue; } } dependentObservable.getDependenciesCount = function () { return _subscriptionsToDependencies.length; } dependentObservable.hasWriteFunction = typeof options["write"] === "function"; dependentObservable.dispose = function () { if (disposeWhenNodeIsRemoved) ko.utils.domNodeDisposal.removeDisposeCallback(disposeWhenNodeIsRemoved, disposeWhenNodeIsRemovedCallback); disposeAllSubscriptionsToDependencies(); }; ko.subscribable.call(dependentObservable); ko.utils.extend(dependentObservable, ko.dependentObservable['fn']); if (options['deferEvaluation'] !== true) evaluate(); ko.exportProperty(dependentObservable, 'dispose', dependentObservable.dispose); ko.exportProperty(dependentObservable, 'getDependenciesCount', dependentObservable.getDependenciesCount); return dependentObservable; }; ko.dependentObservable['fn'] = { __ko_proto__: ko.dependentObservable }; ko.dependentObservable.__ko_proto__ = ko.observable; ko.exportSymbol('ko.dependentObservable', ko.dependentObservable);
JavaScript
0.000297
@@ -5289,28 +5289,143 @@ ', ko.dependentObservable);%0A +ko.exportSymbol('ko.computed', ko.dependentObservable); // Make %22ko.computed%22 an alias for %22ko.dependentObservable%22
cb78789708419259fad7cf3d99f9c485e21f83af
Update card view
src/CardList.js
src/CardList.js
import React, { Component } from 'react'; import styled from 'styled-components'; import NoResults from './NoResults'; import Griddle, { plugins, utils, components } from 'griddle-react'; const { connect } = utils; const CardWrapper = styled.div` margin: 0 10px 0 10px; ` const ListWrapper = styled.div` ` const CenteredPagination = styled.div` width: 100%; text-align: center; margin: 25px 0 25px 0; ` const GriddleWrapper = styled.div` margin-top: 85px; margin-bottom: 120px; .button { margin: 0 10px 0 10px; } `; const TopWrapper = styled.div` display: flex; margin: 10px; @media(max-width: 640px) { button { display: none; } } ` const Left = styled.div` width: 50%; ` const Right = styled.div` width: 50%; text-align: right; padding-right: 20px; ` const CustomRowComponent = connect((state, props) => ({ rowData: plugins.LocalPlugin.selectors.rowDataSelector(state, props) }))(({ rowData }) => ( <CardWrapper className="box"> <h1>{rowData.name}</h1> <ul> <li><strong>State</strong>: {rowData.state}</li> <li><strong>Company</strong>: {rowData.company}</li> </ul> </CardWrapper> )); // HoC for overriding Table component to just render the default TableBody component // We could use this entirely if we wanted and connect and map over visible rows but // Using this + tableBody to take advantange of code that Griddle LocalPlugin already has const CustomTableComponent = OriginalComponent => class CustomTableComponent extends Component { static contextTypes = { components: React.PropTypes.object } render() { return <this.context.components.TableBody /> } } const CustomTableBody = ({ rowIds, Row, className }) => console.log('HERE ', rowIds) || ( <ListWrapper> { (!rowIds || rowIds.size === 0) && <NoResults /> } { rowIds && rowIds.map(r => <Row key={r} griddleKey={r} />) } </ListWrapper> ); const Layout = ({ Table, Pagination, Filter }) => ( <GriddleWrapper> <TopWrapper> <Left> <Filter /> </Left> <Right> <Pagination /> </Right> </TopWrapper> <Table /> <CenteredPagination> <Pagination /> </CenteredPagination> </GriddleWrapper> ); const getRange = (number) => { return Array(number).fill().map((_, i) => i + 1); } class PageDropdown extends Component { setPage = (e) => { this.props.setPage(parseInt(e.target.value)); } render() { const { currentPage, maxPages } = this.props; return ( <div className="select"> <select onChange={this.setPage} value={currentPage} style={this.props.style} className={this.props.className} > {getRange(maxPages) .map(num => ( <option key={num} value={num}>{num}</option> ))} </select> </div> ); } } class Filter extends Component { setFilter = (e) => { this.props.setFilter(e.target.value); } render() { return ( <input type="text" name="filter" placeholder="Filter" onChange={this.setFilter} style={this.props.style} className={this.props.className} /> ) } } export default ({data}) => ( <Griddle data={data} pageProperties={{ pageSize: 5 }} plugins={[plugins.LocalPlugin]} components={{ Row: CustomRowComponent, TableContainer: CustomTableComponent, TableBody: CustomTableBody, SettingsToggle: (props) => null, Layout, PageDropdown, }} styleConfig={{ classNames: { NextButton: 'button', PreviousButton: 'button', Filter: 'input' } }} /> )
JavaScript
0
@@ -262,24 +262,80 @@ 10px 0 10px; +%0A%0A h1 %7B%0A font-weight: bold;%0A font-size: 16px;%0A %7D %0A%60%0A%0Aconst Li @@ -1093,31 +1093,22 @@ %3Cli%3E -%3Cstrong%3EState%3C/strong%3E: +%7BrowData.city%7D %7Bro @@ -1118,16 +1118,24 @@ ta.state +Province %7D%3C/li%3E%0A @@ -1145,34 +1145,8 @@ %3Cli%3E -%3Cstrong%3ECompany%3C/strong%3E: %7Brow @@ -1156,12 +1156,12 @@ a.co -mpan +untr y%7D%3C/ @@ -1173,16 +1173,61 @@ %3C/ul%3E +%0A%0A %3Ca href=%7BrowData.url%7D%3E%7BrowData.url%7D%3C/a%3E %0A %3C/Car
40efcf5ff1db786b9788d6ce7dcbfbbf83ad734e
Fix js tests.
assets/js/googlesitekit/datastore/user/tracking.test.js
assets/js/googlesitekit/datastore/user/tracking.test.js
/** * `core/user` data store: user tracking settings tests. * * Site Kit by Google, Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Internal dependencies */ import API from 'googlesitekit-api'; import { createTestRegistry, subscribeUntil, unsubscribeFromAll } from '../../../../../tests/js/utils'; import { waitFor } from '../../../../../tests/js/test-utils'; import { STORE_NAME } from './constants'; describe( 'core/user tracking settings', () => { let registry; const coreUserTrackingSettingsEndpointRegExp = /^\/google-site-kit\/v1\/core\/user\/data\/tracking/; beforeAll( () => { API.setUsingCache( false ); } ); beforeEach( () => { registry = createTestRegistry(); } ); afterAll( () => { API.setUsingCache( true ); } ); afterEach( () => { unsubscribeFromAll( registry ); } ); describe( 'actions', () => { describe( 'saveUserTracking', () => { it.each( [ [ 'enable', true ], [ 'disable', false ], ] )( 'should %s tracking and add it to the store', async ( status, enabled ) => { fetchMock.postOnce( coreUserTrackingSettingsEndpointRegExp, { status: 200, body: { enabled }, } ); await registry.dispatch( STORE_NAME ).saveUserTracking( enabled ); // Ensure the proper body parameters were sent. expect( fetchMock ).toHaveFetched( coreUserTrackingSettingsEndpointRegExp, { body: { data: { enabled } }, } ); expect( registry.select( STORE_NAME ).isTrackingEnabled() ).toBe( enabled ); expect( fetchMock ).toHaveFetchedTimes( 1 ); } ); it( 'dispatches an error if the request fails ', async () => { const enabled = true; const args = [ enabled ]; const response = { code: 'internal_server_error', message: 'Internal server error', data: { status: 500 }, }; fetchMock.post( coreUserTrackingSettingsEndpointRegExp, { body: response, status: 500 } ); await registry.dispatch( STORE_NAME ).saveUserTracking( ...args ); expect( registry.select( STORE_NAME ).getErrorForAction( 'saveUserTracking', args ) ).toMatchObject( response ); expect( console ).toHaveErrored(); } ); } ); } ); describe( 'selectors', () => { describe( 'isTrackingEnabled', () => { it( 'should use a resolver to make a network request', async () => { const enabled = true; fetchMock.getOnce( coreUserTrackingSettingsEndpointRegExp, { status: 200, body: { enabled }, } ); const { isTrackingEnabled, hasFinishedResolution } = registry.select( STORE_NAME ); expect( isTrackingEnabled() ).toBeUndefined(); await waitFor( () => hasFinishedResolution( 'isTrackingEnabled' ) !== true ); expect( isTrackingEnabled() ).toBe( enabled ); expect( fetchMock ).toHaveFetchedTimes( 1 ); expect( isTrackingEnabled() ).toBe( enabled ); expect( fetchMock ).toHaveFetchedTimes( 1 ); } ); it( 'should not make a network request if data is already in state', async () => { const enabled = true; registry.dispatch( STORE_NAME ).receiveGetTracking( { enabled } ); const tracking = registry.select( STORE_NAME ).isTrackingEnabled(); await subscribeUntil( registry, () => registry.select( STORE_NAME ).hasFinishedResolution( 'isTrackingEnabled' ) ); expect( tracking ).toEqual( enabled ); expect( fetchMock ).not.toHaveFetched(); } ); it( 'should dispatch an error if the request fails', async () => { const response = { code: 'internal_server_error', message: 'Internal server error', data: { status: 500 }, }; fetchMock.getOnce( coreUserTrackingSettingsEndpointRegExp, { status: 500, body: response, } ); registry.select( STORE_NAME ).isTrackingEnabled(); await subscribeUntil( registry, () => registry.select( STORE_NAME ).hasFinishedResolution( 'isTrackingEnabled' ) ); const enabled = registry.select( STORE_NAME ).isTrackingEnabled(); expect( fetchMock ).toHaveFetchedTimes( 1 ); expect( enabled ).toBeUndefined(); expect( console ).toHaveErrored(); } ); } ); } ); } );
JavaScript
0
@@ -1397,31 +1397,26 @@ ribe( 's -aveUser +et Tracking ', () =%3E @@ -1407,16 +1407,23 @@ Tracking +Enabled ', () =%3E @@ -1735,31 +1735,26 @@ NAME ).s -aveUser +et Tracking ( enable @@ -1745,16 +1745,23 @@ Tracking +Enabled ( enable @@ -2491,31 +2491,26 @@ NAME ).s -aveUser +et Tracking ( ...arg @@ -2501,16 +2501,23 @@ Tracking +Enabled ( ...arg @@ -2588,23 +2588,18 @@ ( 's -aveUser +et Tracking ', a @@ -2594,16 +2594,23 @@ Tracking +Enabled ', args
f8d8c8dc086f65d696248daae839e4309986b0c7
Remove unused vars
assets/src/components/editor-carousel/reorderer-item.js
assets/src/components/editor-carousel/reorderer-item.js
/** * WordPress dependencies */ import { compose } from '@wordpress/compose'; import { Draggable, DropZone } from '@wordpress/components'; import { Fragment } from '@wordpress/element'; import { withDispatch, withSelect } from '@wordpress/data'; /** * Internal dependencies */ import BlockPreview from './block-preview'; import { Component } from 'react'; const parseDropEvent = ( event ) => { let result = { srcRootClientId: null, srcClientId: null, srcIndex: null, type: null, }; if ( ! event.dataTransfer ) { return result; } try { result = Object.assign( result, JSON.parse( event.dataTransfer.getData( 'text' ) ) ); } catch ( err ) { return result; } return result; }; class ReordererItem extends Component { constructor() { super( ...arguments ); this.state = { isDragging: false, }; this.onDrop = this.onDrop.bind( this ); } getInsertIndex( position ) { const { index } = this.props; if ( index !== undefined ) { return position.x === 'right' ? index + 1 : index; } } onDrop( event, position ) { const { page: { clientId }, index, movePageToPosition } = this.props; const { srcClientId, type, srcIndex } = parseDropEvent( event ); const isBlockDropType = ( dropType ) => dropType === 'block'; const isSameBlock = ( src, dst ) => src === dst; if ( ! isBlockDropType( type ) || isSameBlock( srcClientId, clientId ) ) { return; } const insertIndex = this.getInsertIndex( position ); movePageToPosition( srcClientId, insertIndex ); } render() { const { page, index } = this.props; const { clientId } = page; const pageElementId = `reorder-page-${ clientId }`; const transferData = { type: 'block', srcIndex: index, srcClientId: clientId, }; return ( <div className="amp-story-reorderer-item"> <Draggable elementId={ pageElementId } transferData={ transferData } onDragStart={ () => this.setState( { isDragging: true } ) } onDragEnd={ () => this.setState( { isDragging: false } ) } > { ( { onDraggableStart, onDraggableEnd } ) => ( <Fragment> <DropZone className={ this.state.isDragging ? 'is-dragging-page' : undefined } onDrop={ this.onDrop } /> <div id={ pageElementId }> <div className="amp-story-page-preview" onDragStart={ onDraggableStart } onDragEnd={ onDraggableEnd } draggable > <BlockPreview { ...page } /> </div> </div> </Fragment> ) } </Draggable> </div> ); } } const applyWithSelect = withSelect( ( select, { page: { clientId } } ) => { const { getBlockIndex } = select( 'amp/story' ); return { index: getBlockIndex( clientId ), }; } ); const applyWithDispatch = withDispatch( ( dispatch ) => { const { movePageToPosition } = dispatch( 'amp/story' ); return { movePageToPosition, }; } ); export default compose( applyWithSelect, applyWithDispatch, )( ReordererItem );
JavaScript
0.000001
@@ -1087,23 +1087,16 @@ entId %7D, - index, movePag @@ -1154,18 +1154,8 @@ type -, srcIndex %7D =
9aac5f79bceedba995b0fe4b6e861a9c0052de2d
Remove unused prop.
assets/src/edit-story/components/canvas/displayLayer.js
assets/src/edit-story/components/canvas/displayLayer.js
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * External dependencies */ import { memo } from 'react'; /** * Internal dependencies */ import { useStory } from '../../app'; import useCanvas from './useCanvas'; import DisplayElement from './displayElement'; import { Layer, PageArea as DisplayPageArea } from './layout'; function DisplayLayer() { const { state: { currentPage }, } = useStory(); const { state: { editingElement }, actions: { setPageContainer, setFullbleedContainer }, } = useCanvas(); return ( <Layer pointerEvents="none"> <DisplayPageArea ref={setPageContainer} fullbleedRef={setFullbleedContainer} background={currentPage?.backgroundColor} overflowAllowed={false} showDangerZone={true} > {currentPage ? currentPage.elements.map(({ id, ...rest }) => { if (editingElement === id) { return null; } return ( <DisplayElement key={id} element={{ id, ...rest }} page={currentPage} /> ); }) : null} </DisplayPageArea> </Layer> ); } export default memo(DisplayLayer);
JavaScript
0
@@ -1270,40 +1270,8 @@ or%7D%0A - overflowAllowed=%7Bfalse%7D%0A
de36e0b13ffcd0d922381fb3d1b8c476091b6008
fix reference error to member
bot/listen.js
bot/listen.js
const refresh = require('./lib/refresh'); const bot = require('./bot.js'); const settings = require('./../settings.json'); const modules = require('./modules.js'); const Message = require('./../orm/Message') const commands = require('./commands'); const request = require('request-promise-native'); const influx = require('./../influx'); let lock = false; bot.on('error', (err) => { /** * Catch errors here */ console.log("Stack Trace: " + err.stack); }) process.on('unhandledRejection', (err) => { console.log("UNHANDLED REJECTION AT " + err.stack); if (err.toString().includes('Request to use token, but token was unavailable to the client')) process.exit();//restart }); process.on('uncaughtException', (err) => console.log("UNHANDLED EXCEPTION AT " + err.stack)); bot.on('message', async function(message) { /** * if locked, reject everything except dm */ influx.writePoints([ { measurement: 'statistics', fields: { tag: member.user.tag, type:'message' }, } ]); new Message({ messageID: message.id, channel: message.channel.id }).save(); if (message.author.bot) return; if (lock) { if (!settings.owners.includes(message.author.id)) // if (message.channel.guild) return;//not DM } /** * Listen to messages and convert into params */ if (message.content.startsWith(settings.identifier)) { /**Extracting params */ let params = message.content.substring(settings.identifier.length).trim(); params = params.split(settings.delimiter || ' '); let cmd = params.shift().trim(); commands.execute(cmd.toLowerCase(), params, message) } else if (message.isMentioned(bot.user)) { /**remove mentions and then get params */ let params = message.cleancontent.trim().replace(bot.user.toString(), "").trim(); params = params.split(settings.delimiter || ' '); let cmd = params.shift.trim(); commands.execute(cmd.toLowerCase(), params, message) } else { //ignore because normal message } }); bot.on('lock', () => { lock = true; }); bot.on('unlock', () => { lock = false; }); bot.on("guildMemberAdd", async function (member) { var user = member.user; if (member.guild.id === "184536578654339072") { influx.writePoints([ { measurement: 'statistics', fields: { tag: member.user.tag, type:'join' }, } ]); if (member.user.bot) return console.log(member.user.tag + " is a bot who joined " + member.guild.name) user.send("Welcome to the Revive Network"); if (! await refresh(user)) { await member.addRole(bot.guilds.get("184536578654339072").roles.get("317854639431221248")); const ma = await bot.channels.get("317859245309689856").send(user.toString() + "Type `accept` to continue. You will be kicked if you don't type `accept` within 10 minutes"); ma.delete(); } } }); bot.on("guildMemberRemove", async function (member) { var user = member.user; if (member.guild.id === "184536578654339072") { influx.writePoints([ { measurement: 'statistics', fields: { tag: member.user.tag, type:'leave' }, } ]); } }); /** bot.on('disconnect', function(event) { if (event.code === 0) return console.error(event); process.exit();//force restart });*/ bot.on('ready', async function() { console.log("ReviveBot Ready"); let dbs = influx.getDatabaseNames(); if(!dbs.includes('discord')) await influx.createDatabase('discord'); influx.writePoints([ { measurement: 'statistics', fields: { tag: bot.user.tag, type:'ready' }, } ]); }); bot.on("guildMemberUpdate", async function (member, newMem) { influx.writePoints([ { measurement: 'statistics', fields: { tag: member.user.tag, type:'update' }, } ]); let user = member.user; if (member.guild && (member.guild.id === "184536578654339072")) { let oldMem = member; if (!oldMem.roles.has("273105185566359562") && newMem.roles.has("273105185566359562")) return; if (!oldMem.roles.has("275317218911322112") && newMem.roles.has("275317218911322112")) return; if (oldMem.roles.has("317854639431221248") && !newMem.roles.has("317854639431221248")) await refresh(user); if ((!oldMem.roles.has("184684916833779712") && newMem.roles.has("184684916833779712")) || (!oldMem.roles.has("200849956796497920") && newMem.roles.has("200849956796497920")) || (!oldMem.roles.has("184676864630063104") && newMem.roles.has("184676864630063104")) || (!oldMem.roles.has("286646245198528523") && newMem.roles.has("286646245198528523"))) { await request('http://revive-bot-discord.revive.systems/v0/discord/reverse_link/' + user.id); } } });
JavaScript
0
@@ -996,32 +996,40 @@ fields: %7B tag: +message. member.user.tag,
6a6d3015334d1027d9087e333057bd71dcefc4fa
add whitespace
wordpress/webpack/entry_HOMEPAGE.js
wordpress/webpack/entry_HOMEPAGE.js
/** * entry_HOMEPAGE.js * * Module for loading styles and scripts related to the home page only * */ var $ = require( "jquery" ); // require jQuery require("./homepage.scss"); // Wait for the DOM to be ready before loading in JSON document.addEventListener( "DOMContentLoaded", function( event ) { /* * ================================================================== * FIND THE FIRST TEN POSTS IN THE WP REST API AND PLACE THEM ON THE * HOME PAGE ON A CERTAIN WAY * ================================================================== */ /* * Grab the first 10 single posts from the WordPress API & sort them * by date. */ var getPostsAPI = "/wp-json/posts?filter[orderby]=date&filter[posts_per_page]=10"; /* * Load in post content with $.getJSON() * Refer to the content as "posts" inside the $.getJSON call */ $.getJSON( getPostsAPI ).done( function( posts ) { // var reference to <section id="all-articles" /> on the home page var articleSection = document.getElementById( "all-articles" ), // Create document fragment to batch-load content onto the page sectionDocFragment = document.createDocumentFragment(); for( var key in posts ) { // jQuery-style single var pattern var postImage, postLink, postTitle, postExcerpt, articlePost = document.createElement( "article" ), articleHeader = document.createElement( "h2" ), articleExcerpt = document.createElement( "p" ), articleLink = document.createElement( "a" ), articleImage = document.createElement( "img" ); imageDiv = document.createElement( "div" ); // Each <article> tag gets the "homepage-post-snippet" class articlePost.setAttribute("class", "homepage-post-snippet"); /* * SET UP SINGLE BLOG POST IMAGES!!!! * The first 10 blog posts MUST have a Featured Image or the site * will crash. */ postImage = posts[key].featured_image["source"]; $( articleImage ).attr({ "src": postImage, "class": "post-pic" }); // Load post image in a <div> imageDiv.appendChild( articleImage ); // Load the <div> with an image in the <article> articlePost.appendChild( imageDiv ); // SET UP SINGLE BLOG LINK & HEADER!!!! // Get post title link postLink = posts[key].link; // Get post title copy postTitle = posts[key].title; // Set the article link's "href" to be the post link articleLink.setAttribute( "href", postLink ); // Load post title copy in the <a> tag articleLink.innerHTML = postTitle; // Load link into the post header articleHeader.appendChild( articleLink ); // Load post header in the <article> articlePost.appendChild( articleHeader ); // SET UP SINGLE BLOG POST EXCERPT!!!! // Get post excerpt copy postExcerpt = posts[key].excerpt; // Load post excerpt copy in the <p> tag articleExcerpt.innerHTML = postExcerpt; // Load post title copy in the <article> articlePost.appendChild( articleExcerpt ); // Load <article> with the title & excerpt into the doc fragment sectionDocFragment.appendChild( articlePost ); var postCategory = posts[key].terms["category"]; for (var key in postCategory) { console.log(postCategory[key].slug); } } // end for...in loop // Exit loop, load the doc fragment into the "all-articles" element articleSection.appendChild( sectionDocFragment ); }); // end $.getJSON() }); // end addEventListener
JavaScript
0.999999
@@ -908,24 +908,28 @@ ( posts ) %7B%0A + %0A // var
e2b36fd78af79410d2cbb498e268d1df82d33285
Remove lazy vs eager confusing behavior
ValidationMixin.js
ValidationMixin.js
"use strict"; require('object.assign').shim(); var ValidationFactory = require('./ValidationFactory'); var ValidationMixin = { /** * Validate single form field against the components state. If no field * is provided, validate entire form. * * @param {?String} field State key to validate * @return {Object} newly updated errors object keyed on state field * names. Missing key or undefined value indicates no error. */ validate: function(field) { var validatorTypes = this.validatorTypes || {}; if (typeof this.validatorTypes === 'function') { validatorTypes = this.validatorTypes(); } var options = { schema: validatorTypes, state: this.state, field: field }; var nextErrors = Object.assign({}, this.state.errors, ValidationFactory.validate(options)); this.setState({ errors: nextErrors }); return nextErrors; }, /** * Convenience method to validate a field via an event handler. Useful for * onBlur, onClick, onChange, etc... * * @param {?String} field State key to validate * @param {?Boolean} preventDefault flag to indicate that this event should be canceled. * default is false. * @return {function} validation event handler */ handleValidation: function(field, preventDefault) { return function(event) { if (preventDefault === true) { event.preventDefault(); } this.validate(field); }.bind(this); }, /** * Returns all validation messages for a single field, or all fields if * no field is provided. * * @param {?String} field State key to validate * @return {Array} all validation messages */ getValidationMessages: function(field) { return ValidationFactory.getValidationMessages(this.state.errors, field); }, /** * Determines if the current components state is valid. This method is lazy * if a field is specified. This allows developers to check if errors have * been reported for this field without forcing a revalidation. If no field * is provided the entire form will be forcefully revalidated. * * @param {?String} field State key to validate * @return {Boolean} returns validity of single field or entire form */ isValid: function(field) { if (field) { //validate single field only; lazy validation return ValidationFactory.isValid(this.state.errors, field); } else { //force full form validation if no field is provided return ValidationFactory.isValid(this.validate(), field); } } }; module.exports = ValidationMixin;
JavaScript
0.000002
@@ -1,9 +1,9 @@ -%22 +' use stri @@ -8,9 +8,9 @@ rict -%22 +' ;%0A%0Ar @@ -41,16 +41,55 @@ shim();%0A +var result = require('lodash.result');%0A var Vali @@ -161,17 +161,16 @@ xin = %7B%0A -%0A /**%0A @@ -176,322 +176,63 @@ * -Validate single form field against the components state. If no field%0A * is provided, validate entire form.%0A *%0A * @param %7B?String%7D field State key to validate%0A * @return %7BObject%7D newly updated errors object keyed on state field%0A * names. Missing key or undefined value indicates no error.%0A */%0A validate +Check for sane configurations%0A */%0A componentDidMount : fu @@ -242,69 +242,12 @@ ion( -field ) %7B%0A - var validatorTypes = this.validatorTypes %7C%7C %7B%7D;%0A @@ -277,17 +277,17 @@ orTypes -= +! == 'func @@ -295,463 +295,197 @@ ion' -) %7B%0A validatorTypes = this.validatorTypes();%0A %7D%0A var options = %7B%0A schema: validatorTypes,%0A state: this.state,%0A field: field%0A %7D;%0A var nextErrors = Object.assign(%7B%7D, this.state.errors, ValidationFactory.validate(options));%0A this.setState(%7B%0A errors: nextErrors%0A %7D);%0A return nextErrors;%0A %7D,%0A%0A /**%0A * Convenience method to validate a field via an event handler. Useful for%0A * onBlur, onClick, onChange, etc.. + && !Array.isArray(this.validatorTypes)) %7B%0A throw Error('invalid %60validatorTypes%60 type');%0A %7D%0A %7D,%0A%0A /**%0A * Validate single form field or entire form against the component's state .%0A @@ -505,35 +505,34 @@ m %7B?String%7D -field State +key. Field key to vali @@ -535,31 +535,59 @@ validate + (entire form if undefined). %0A * @ -param +return %7B -? Boolean%7D @@ -591,357 +591,322 @@ an%7D -preventDefault flag to indicate that this event should be canceled.%0A * default is false.%0A * @return %7Bfunction%7D validation event handler%0A */%0A handleValidation: function(field, preventDefault) %7B%0A return function(event) %7B%0A if (preventDefault === true) %7B%0A event.preventDefault();%0A +Result of %60isValid%60 call after validation.%0A */%0A validate: function(key) %7B%0A var schema = result(this, 'validatorTypes', %7B%7D);%0A var errors = Object.assign(%7B%7D, this.state.errors, ValidationFactory.validate(this.state, schema, key));%0A this.setState(%7B%0A errors: errors%0A - %7D +); %0A - +return this. -v +isV alid -ate(field);%0A %7D.bind(this +(key );%0A @@ -925,19 +925,19 @@ * -Returns all +Get current val @@ -964,164 +964,144 @@ a s -ingle field, or all fields if%0A * no field is provided.%0A *%0A * @param %7B?String%7D field State key to validate%0A * @return %7BArray%7D all validation messages +pecified field or entire form.%0A *%0A * @param %7B?String%7D key. Field key to get messages (entire form if undefined)%0A * @return %7BArray%7D %0A @@ -1129,37 +1129,35 @@ sages: function( -field +key ) %7B%0A return V @@ -1210,29 +1210,27 @@ ate.errors, -field +key );%0A %7D,%0A%0A / @@ -1241,743 +1241,279 @@ * -Determines if the current components state is valid. This method is lazy%0A * if a field is specified. This allows developers to check if errors have%0A * been reported for this field without forcing a revalidation. If no field%0A * is provided the entire form will be forcefully revalidated.%0A *%0A * @param %7B?String%7D field State key to validate%0A * @return %7BBoolean%7D returns validity of single field or entire form%0A */%0A isValid: function(field) %7B%0A if (field) %7B%0A //validate single field only; lazy validation%0A return ValidationFactory.isValid(this.state.errors, field);%0A %7D else %7B%0A //force full form validation if no field is provided%0A return ValidationFactory.isValid(this.validate(), field);%0A %7D%0A %7D%0A +Check current validity for a specified field or entire form.%0A *%0A * @param %7B?String%7D key. Field key to check validity (entire form if undefined).%0A * @return %7BBoolean%7D.%0A */%0A isValid: function(key) %7B%0A return ValidationFactory.isValid(this.state.errors, key);%0A %7D %0A%7D;%0A
5e138d45d282b48616710b0fde5347f885064794
remove photo gallery elements
overloadBrowser.js
overloadBrowser.js
var QUERY = 'lab puppies'; var PAGE = 0; var puppyGenerator = { init: function() { this.requestPuppies(); this.reloadPuppies(); }, _searchOnFlickr: function(page) { return 'https://secure.flickr.com/services/rest/?' + 'method=flickr.photos.search&' + 'api_key=53caa6bf9c68533d9fc34ca096bc6c72&' + 'text=' + encodeURIComponent(QUERY) + '&' + 'safe_search=1&' + 'content_type=1&' + 'sort=interestingness-desc&' + 'per_page=5&' + 'page=' + page.toString(); }, requestPuppies: function() { var req = new XMLHttpRequest(); req.open('GET', this._searchOnFlickr(++PAGE), true); req.onload = this.showPhotos.bind(this); req.send(null); }, showPhotos: function(event) { var puppies = event.target.responseXML.querySelectorAll('photo'); for (var i = 0; i < puppies.length; i++) { var img = document.createElement('img'); img.src = this._constructPuppyURL(puppies[i]); img.setAttribute('alt', puppies[i].getAttribute('title')); this.setPuppyLayout(img); document.body.appendChild(img); } }, _constructPuppyURL: function(photo) { return 'https://farm' + photo.getAttribute('farm') + '.staticflickr.com/' + photo.getAttribute('server') + '/' + photo.getAttribute('id') + '_' + photo.getAttribute('secret') + '_n.jpg'; }, setPuppyLayout: function(photo) { photo.setAttribute('style', 'border: 1px solid black; margin: 5px'); photo.setAttribute('height', '200px'); }, reloadPuppies: function() { document.addEventListener('scroll', function(event) { if (document.body.scrollHeight == document.body.scrollTop + window.innerHeight) { puppyGenerator.requestPuppies(); } }); } }; (function(document) { console.log('Puppy overloadddd...'); puppyGenerator.init(); console.log(window.innerWidth); })(document);
JavaScript
0
@@ -75,24 +75,58 @@ unction() %7B%0A + // document.body.innerHTML();%0A this.req @@ -487,17 +487,19 @@ er_page= -5 +100 &' +%0A @@ -678,24 +678,29 @@ = this.showP +uppyP hotos.bind(t @@ -737,16 +737,21 @@ %0A showP +uppyP hotos: f @@ -1385,17 +1385,17 @@ '_ -n +q .jpg';%0A @@ -1511,51 +1511,8 @@ ');%0A - photo.setAttribute('height', '200px');%0A %7D, @@ -1843,42 +1843,8 @@ ();%0A - console.log(window.innerWidth);%0A %7D)(d
f0e4cdf269ad140f3fc214d586758f50b7bff35a
Move socket creation to method
src/middleware.js
src/middleware.js
import merge from 'deepmerge'; import {SOCKET_DISPATCH, SOCKET_RECEIVE_ACTION, SOCKET_CONNECT, SOCKET_DISCONNECT} from './constants'; const defaultOptions = { actions: [], }; export default function socketMiddleware(options = defaultOptions) { let socket; options = merge(defaultOptions, options); // Determines wether or not an action should be emitted to the socket server. const shouldEmit = action => { return socket // We need a socket server && !action.emitted // If the action was emitted before, we will not emit it again. && options.actions.includes(action.type); // The action type needs to be included }; return store => next => action => { // We first execute the action locally const result = next(action); // We want to intercept a couple of actions related to sockets. switch (action.type) { case SOCKET_CONNECT: if (!socket) { socket = options.resolveSocket(action.url); socket.on(SOCKET_RECEIVE_ACTION, action => { store.dispatch({...action, emitted: true}); }); socket.on('disconnect', () => { store.dispatch({ type: SOCKET_DISCONNECT, }); }); socket.on('reconnect', () => { store.dispatch({ type: SOCKET_CONNECT, }); }); } break; } // If the action should be emitted we do so. if (shouldEmit(action)) { socket.emit(SOCKET_DISPATCH, action); } // Return the result to the next middleware. return result; }; }
JavaScript
0
@@ -646,16 +646,441 @@ d%0A %7D;%0A%0A + const setupSocket = (url) =%3E %7B%0A socket = options.resolveSocket(url);%0A%0A socket.on(SOCKET_RECEIVE_ACTION, action =%3E %7B%0A store.dispatch(%7B...action, emitted: true%7D);%0A %7D);%0A%0A socket.on('disconnect', () =%3E %7B%0A store.dispatch(%7B%0A type: SOCKET_DISCONNECT,%0A %7D);%0A %7D);%0A%0A socket.on('reconnect', () =%3E %7B%0A store.dispatch(%7B%0A type: SOCKET_CONNECT,%0A %7D);%0A %7D);%0A%0A return socket;%0A %7D%0A%0A return @@ -1105,24 +1105,24 @@ action =%3E %7B%0A - // We fi @@ -1308,17 +1308,16 @@ ONNECT:%0A -%0A @@ -1354,444 +1354,30 @@ t = -options.resolveSocket(action.url);%0A socket.on(SOCKET_RECEIVE_ACTION, action =%3E %7B%0A store.dispatch(%7B...action, emitted: true%7D);%0A %7D);%0A%0A%0A socket.on('disconnect', () =%3E %7B%0A store.dispatch(%7B%0A type: SOCKET_DISCONNECT,%0A %7D);%0A %7D);%0A%0A socket.on('reconnect', () =%3E %7B%0A store.dispatch(%7B%0A type: SOCKET_CONNECT,%0A %7D);%0A %7D +setupSocket(action.url );%0A
a9656a6a337266042f30a52b13667867a1f17e2e
add forceArray() function to core lib
share/js/core/lib.js
share/js/core/lib.js
// ************************************************************************* // Copyright (c) 2014, SUSE LLC // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of SUSE LLC nor the names of its contributors may be // used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // ************************************************************************* // // lib.js // "use strict"; define ([ 'jquery', 'current-user', 'prototypes' ], function ( $, currentUser, prototypes ) { var heldObject = null; return { // clear the result line clearResult: function () { $('#result').css('text-align', 'left'); $('#result').html('&nbsp;'); }, // given an object, hold (store) it // if called without argument, just return whatever object we are holding holdObject: function (obj) { if (obj) { console.log("Setting held object to ", obj); heldObject = obj; } return heldObject; }, // give object a "haircut" by throwing out all properties // that do not appear in proplist hairCut: function (obj, proplist) { for (var prop in obj) { if (obj.hasOwnProperty(prop)) { if (proplist.indexOf(prop) !== -1) { continue; } delete obj[prop]; } } return obj; }, // log events to browser JavaScript console logKeyPress: function (evt) { // console.log("WHICH: " + evt.which + ", KEYCODE: " + evt.keyCode); }, // check current employee's privilege against a given ACL profile privCheck: function (p) { var cep = currentUser('priv'), r, yesno; if ( ! cep ) { console.log("Something is wrong: cannot determine priv level of current user!"); return undefined; } if (p === 'passerby' && cep) { r = true; yesno = "Yes."; } else if (p === 'inactive' && (cep === 'inactive' || cep === 'active' || cep === 'admin')) { r = true; yesno = "Yes."; } else if (p === 'active' && (cep === 'active' || cep === 'admin')) { r = true; yesno = "Yes."; } else if (p === 'admin' && cep === 'admin') { r = true; yesno = "Yes."; } else { r = false; yesno = "No."; } console.log("Does " + cep + " user satisfy ACL " + p + "? " + yesno); return r; }, // right pad a string with spaces rightPadSpaces: function (strToPad, padto) { var sp = '&nbsp;', padSpaces = sp.repeat(padto - String(strToPad).length); return strToPad.concat(padSpaces); }, // pause main thread for n milliseconds wait: function (ms) { var start = new Date().getTime(); var end = start; while(end < start + ms) { end = new Date().getTime(); } } }; });
JavaScript
0
@@ -4644,32 +4644,166 @@ ;%0A %7D%0A + %7D,%0A%0A // convert null to empty array%0A forceArray: function (arr) %7B%0A return (arr === null) ? %5B%5D : arr;%0A %7D%0A%0A %7D
805dd1906bdc51f54f29bf8d31a5913248af80e1
Trim return
preload.js
preload.js
(() => { function onMessageCreated(session, store, router) { return (data) => { store.find('message', data.message.id).then((message) => { const isSameId = message.get('senderId') === Number(session.get('user.id')); const byHuman = message.get('senderType') === 'User'; if (isSameId && byHuman) { return; } const room = message.get('room'); const title = `${message.get('senderName')} > ${room.get('organization.slug')} / ${room.get('name')}`; const bodyPlain = ((body) => { let tmp = document.createElement('div'); tmp.innerHTML = body; return tmp.textContent.replace(/ +/g, ' '); })(message.get('body')); const notification = new Notification(title, { body: bodyPlain, icon: message.get('senderIconUrl') }); notification.addEventListener('click', () => { if (!router.isActive('main')) { return }; router.transitionTo('room', room); }); }); }; } window.addEventListener('ready.idobata', (e) => { const container = e.detail.container; const pusher = container.lookup('pusher:main'); const session = container.lookup('service:session'); const store = container.lookup('service:store'); const router = container.lookup('router:main'); pusher.bind('message:created', onMessageCreated(session, store, router)); }); })();
JavaScript
0.000001
@@ -668,16 +668,35 @@ +/g, ' +').replace(/%5Cn/g, ' ');%0A
b69fca4c144988fe5e047601864b0e976e5f23a0
Maintain current protocol, hostname and port when navigating
mirror.js
mirror.js
/*global window, document, Faye */ /*jslint vars: true, indent: 2 */ (function () { 'use strict'; var begin = function (beginControlling, beginMirroring) { var faye = new Faye.Client('/faye'); if (window.location.hostname.indexOf('mirror') === 0) { beginMirroring(faye); } else { beginControlling(faye); } }; var navigateTo = function (url) { if (window.location.href !== url) { window.location.href = url; } }; var beginControlling = function (faye) { window.addEventListener('scroll', function () { faye.publish('/scroll', { x: window.scrollX, y: window.scrollY }); }); window.addEventListener('click', function (event) { var element = event.target; while (element) { if (element.localName === 'a') { event.preventDefault(); faye.publish('/navigate', { url: element.href }); navigateTo(element.href); break; } element = element.parentNode; } }); }; var beginMirroring = function (faye) { faye.subscribe('/scroll', function (message) { window.scrollTo(message.x, message.y); }); faye.subscribe('/navigate', function (message) { navigateTo(message.url); }); }; begin(beginControlling, beginMirroring); }());
JavaScript
0.000001
@@ -372,24 +372,162 @@ ion (url) %7B%0A + var a = document.createElement('a');%0A a.href = url;%0A a.protocol = window.location.protocol;%0A a.host = window.location.host;%0A%0A if (wind @@ -547,19 +547,22 @@ ref !== -url +a.href ) %7B%0A @@ -582,27 +582,30 @@ tion.href = -url +a.href ;%0A %7D%0A %7D;
0879b66e28fcc4f8d5f7051c19d4633868467e1b
Remove accidental double import
examples/cities.js
examples/cities.js
var fs = require('fs'); // Replace with require('pikud-haoref-api') if the package resides in node_modules var pikudHaoref = require('../index'); var pikudHaoref = require('../index'); // Pikud Haoref Google Maps API Key var options = { googleMapsApiKey: 'AIzaSyBYZ7FFqB5U1mP1nAwJ0iScWU5GjDP1KCM' }; // Fetch city metadata from Pikud Haoref's website pikudHaoref.getCityMetadata(function (err, cities) { // Task failed? if (err) { return console.error(err); } // Write cities.json file to disc fs.writeFileSync('cities.json', JSON.stringify(cities, null, 2), 'utf8'); // Output success console.log('Wrote cities.json successfully'); }, options);
JavaScript
0.000002
@@ -143,47 +143,8 @@ x'); -%0Avar pikudHaoref = require('../index'); %0A%0A//
1c2881afadac58327f2e05c73e345a5b8f017ff1
Fix does not notify
preload.js
preload.js
(() => { function onMessageCreated(session, store, router) { return (data) => { store.find('message', data.message.id).then((message) => { const isSameId = message.get('senderId') === Number(session.get('user.id')); const byHuman = message.get('senderType') === 'User'; if (isSameId && byHuman) { return; } const room = message.get('room'); const title = `${message.get('senderName')} > ${room.get('organization.slug')} / ${room.get('name')}`; const bodyPlain = ((body) => { let tmp = document.createElement('div'); tmp.innerHTML = body; return tmp.textContent.replace(/ +/g, ' ').replace(/\n/g, ''); })(message.get('body')); const notification = new Notification(title, { body: bodyPlain, icon: message.get('senderIconUrl') }); notification.addEventListener('click', () => { if (!router.isActive('main')) { return }; router.transitionTo('room', room); }); }); }; } window.addEventListener('ready.idobata', (e) => { const container = e.detail.container; const pusher = container.lookup('pusher:main'); const session = container.lookup('service:session'); const store = container.lookup('service:store'); const router = container.lookup('router:main'); pusher.bind('message:created', onMessageCreated(session, store, router)); }); })();
JavaScript
0
@@ -15,28 +15,27 @@ ction on -MessageCreat +EventReceiv ed(sessi @@ -71,18 +71,136 @@ rn ( -data) =%3E %7B +messageEvent) =%3E %7B%0A const %7Bdata, type%7D = JSON.parse(messageEvent.data);%0A%0A if (type !== 'message:created') %7B return; %7D%0A %0A @@ -1274,22 +1274,22 @@ const -pusher +stream = cont @@ -1306,19 +1306,22 @@ up(' -pusher:main +service:stream ');%0A @@ -1494,53 +1494,228 @@ -pusher.bind('message:created', onMessageCreat +function sleep(millisec) %7B%0A return new Promise((resolve) =%3E %7B%0A setTimeout(() =%3E %7B%0A resolve()%0A %7D, millisec);%0A %7D);%0A %7D%0A%0A sleep(1000).then(() =%3E %7B%0A stream.on('event', onEventReceiv ed(s @@ -1739,16 +1739,24 @@ uter));%0A + %7D);%0A %7D);%0A%7D)
c6005f64c9cb054da3ba64ed4475fd3cf37bd806
Make range properties on the object too
prelude.js
prelude.js
// vim:ts=2:sw=2:expandtab:autoindent: /* Copyright (c) 2008 Aristid Breitkreuz, Ash Berlin, Ruediger Sonderfeld 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. */ Array.from = function from(iterable) { if (!iterable) return []; if (iterable.toArray) return iterable.toArray(); return Array.slice(iterable, 0); }; Object.defineProperty(Array, 'from', {enumerable: false}); function Range(from,to, by) { var i = from; by = by || 1; while (i < to) { yield i; i += by; } } String.prototype.toArray = function toArray() { return this.split(/\s+/); }; Object.defineProperty(String.prototype, 'toArray', {enumerable: false}); Function.prototype.bind = function bind(obj) { var fun = this; return function bound_func() { return fun.apply(obj, arguments); } }; Object.defineProperty(Function.prototype, 'bind', {enumerable: false}); Object.defineProperty(Function, 'bind', { enumerable: false, value: function bind(obj, name) { var fun = obj[name]; if (!fun || !(fun instanceof Function)) throw new Error("Object has no function '" + name + "'"); return fun.bind(obj); } }); (function (g) { var i = new Importer; i.load('io'); g.print = Function.bind(i.IO.stdout, 'print'); g.IO = i.IO; i.load('xml'); g.XML = i.XML; g.$importer = i; })(this); true;
JavaScript
0.000001
@@ -1426,25 +1426,83 @@ ;%0A -while (i %3C to) %7B%0A +var r;%0A function RangeInstance() %7B%0A while (i %3C to) %7B%0A r%5Bi%5D = i;%0A @@ -1514,16 +1514,18 @@ i;%0A + i += by; @@ -1527,17 +1527,110 @@ = by;%0A -%7D + %7D%0A %7D;%0A r = new RangeInstance();%0A r.__itererator__ = function() %7B return r %7D;%0A%0A return r; %0A%7D%0A%0AStri
c31ce504155277a531c39a9c960c276ad831bacb
connect to mysql when initializing the models
server/boot/init-models.js
server/boot/init-models.js
/*eslint-env node */ var async = require('async'); module.exports = function(app) { //data sources var mongodbsvr = app.dataSources.mongodbsvr; //create all models async.parallel({ operators: async.apply(createOperators), schaetzers: async.apply(createSchaetzers), }, function(err, results) { if (err) throw err; console.log('> models created sucessfully'); }); //create operators function createOperators(cb) { mongodbsvr.automigrate('Operator', function(err) { if (err) return cb(err); var Operator = app.models.Operator; Operator.create([ {operatorKey: 'OP1', name: 'Tablet 1'}, {operatorKey: 'OP2', name: 'Tablet 2'} ], cb); }); } //create schaetzer function createSchaetzers(cb) { mongodbsvr.automigrate('Schaetzer', function(err) { if (err) return cb(err); }); } };
JavaScript
0.000001
@@ -143,18 +143,65 @@ godbsvr; +%0A var mysqldbsvr = app.dataSources.mysqldbsvr; %0D%0A - %0D%0A // @@ -513,36 +513,36 @@ ors(cb) %7B%0D%0A m -ongo +ysql dbsvr.automigrat @@ -864,20 +864,20 @@ %7B%0D%0A m -ongo +ysql dbsvr.au
0bdfdfce38a94625e68294beaceac2b1907c0772
Fix definition of payable
model/business-process-new/costs.js
model/business-process-new/costs.js
// BusinessProcess costs resolution 'use strict'; var memoize = require('memoizee/plain') , definePercentage = require('dbjs-ext/number/percentage') , defineCurrency = require('dbjs-ext/number/currency') , defineMultipleProcess = require('../lib/multiple-process') , defineCost = require('../cost') , defineRegistrations = require('./registrations'); module.exports = memoize(function (db/* options */) { var BusinessProcess = defineRegistrations(db, arguments[1]) , Percentage = definePercentage(db) , MultipleProcess = defineMultipleProcess(db) , Currency = defineCurrency(db) , Cost = defineCost(db); BusinessProcess.prototype.defineProperties({ costs: { type: MultipleProcess, nested: true } }); BusinessProcess.prototype.costs.map._descriptorPrototype_.type = Cost; BusinessProcess.prototype.costs.defineProperties({ // Applicable costs resolved out of requested registrations applicable: { type: Cost, value: function (_observe) { var result = []; _observe(this.master.registrations.requested).forEach(function (registration) { _observe(registration.costs).forEach(function (cost) { result.push(cost); }); }); return result; } }, // Payable subset of applicable costs // More directly: all applicable costs that are non 0 payable: { type: Cost, value: function (_observe) { var result = []; this.applicable.forEach(function (cost) { var isPayable = Boolean(cost._get ? _observe(cost._amount) : cost.amount); if (isPayable) result.push(cost); }); return result; } }, // Paid costs paid: { type: Cost, multiple: true, value: function (_observe) { var result = []; this.applicable.forEach(function (cost) { if (_observe(cost._isPaid)) result.push(cost); }); return result; } }, // Payment progress paymentProgress: { type: Percentage, value: function () { if (!this.applicable.size) return 1; return this.paid.size / this.applicable.size; } }, // Payment progress for online payments // We require all online payments to be done in Part A stage. // So having this below 1, doesn't allow submit of application onlinePaymentProgress: { type: Percentage, value: function (_observe) { var valid = 0, total = 0; this.applicable.forEach(function (cost) { if (!cost.isElectronic) return; ++total; if (_observe(cost._isPaid)) ++valid; }); if (!total) return 1; return valid / total; } }, // Total for all applicable costs totalAmount: { type: Currency, value: function (_observe) { var total = 0; this.payable.forEach(function (cost) { var amount = cost._get ? _observe(cost._amount) : cost.amount; total += amount; }); return total; } } }); return BusinessProcess; }, { normalizer: require('memoizee/normalizers/get-1')() });
JavaScript
0.000009
@@ -1335,32 +1335,48 @@ e: %7B type: Cost, + multiple: true, value: function
6ec189330da0591994b9ebb44b699f4bfab780c4
Fix resolver my english in docs
addon/resolver.js
addon/resolver.js
/** @module ember-flexberry */ import Ember from 'ember'; import EmberResolver from 'ember-resolver'; /** Base ember-flexberry application dependencies resolver. Usage: ```javascript import Ember from 'ember'; import Resolver from 'ember-flexberry/resolver'; let App = Ember.Application.extend({ Resolver: Resolver }); export default App; ``` @class Resolver @extends <a href="https://github.com/ember-cli/ember-resolver/blob/master/addon/resolver.js">Ember.Resolver</a> */ export default EmberResolver.extend({ /** Contains names of type for which need lookup class with prefix received through a {{#crossLink "DeviceService"}}{{/crossLink}}. @property resolvingTypes @type Array @default ['component', 'template', 'view'] */ resolvingTypes: [ 'component', 'template', 'view', ], /** Initializes resolver. */ init() { this._super(...arguments); }, /** Checks if template or class with given full name is known and could be resolved. @method isKnown @param {String} fullName Resource full name (with path inside type-related directory). @return {Boolean} Flag: indicates whether given resource is known by application or not. */ isKnown(fullName) { let type = fullName.split(':')[0]; let knownForType = this.knownForType(type) || {}; return knownForType[fullName] === true; }, /** This method is called via the container's resolver method. It parses the provided full name and then looks up and returns the appropriate template or class. First of all it tries to find appropriate template or class in device-related subfolder, if it is possible, otherwise it looks up in default folder related to template or class type. @method resolve @param {String} fullName Resource full name (with path inside type-related directory). @return {Object} The resolved factory. */ resolve(fullName) { let device = this.get('device'); if (Ember.isNone(device)) { return this._super(fullName); } let fullNamePartsArray = fullName.split(':'); let { resolvingType, resolvingPath } = { resolvingType: fullNamePartsArray[0], resolvingPath: fullNamePartsArray[1] }; let resolvingPathParts = resolvingPath.split('/'); if (this._resolveTypeWithDeviceTypeDetection(resolvingType) && !this._resolveResourceWithoutDeviceTypeDetection(fullName)) { let pathPrefixes = device.pathPrefixes(true); for (let i = 0, len = pathPrefixes.length; i < len; i++) { let pathPrefix = pathPrefixes[i]; // Change resolvingPath from 'path/name' to 'pathPrefix/path/name. // For example 'components/my-component' -> 'tablet-portrait/components/my-component'. let newPathParts = Ember.copy(resolvingPathParts); newPathParts.unshift(pathPrefix); let newPath = newPathParts.join('/'); // Change resolvingPath in the given fullName (if resolving resource exists in the new device-related path). let newFullName = resolvingType + ':' + newPath; if (this.isKnown(newFullName)) { fullName = newFullName; break; } } } return this._super(fullName); }, /** Determines if resource should be resolved with origin resolving path. Returns true if full name of resource was specified in 'resolveWithoutDeviceTypeDetection' application setting. @method _resolveResourceWithoutDeviceTypeDetection @param {String} fullName Resource full name (with path inside type-related directory). @return {Boolean} Flag: indicates whether given resource should be resolved with origin resolving path. @private */ _resolveResourceWithoutDeviceTypeDetection(fullName) { if (this.namespace && this.namespace.resolveWithoutDeviceTypeDetection && Ember.isArray(this.namespace.resolveWithoutDeviceTypeDetection)) { let resourceTypesToApplyOriginResolving = this.namespace.resolveWithoutDeviceTypeDetection; return resourceTypesToApplyOriginResolving.indexOf(fullName) > -1; } return false; }, /** Checks `type` need use prefix received through a {{#crossLink "DeviceService"}}{{/crossLink}} to lookup class this `type` or not. @method _resolveTypeWithDeviceTypeDetection @param {String} type @return {Boolean} @private */ _resolveTypeWithDeviceTypeDetection(type) { let resolvingTypes = this.get('resolvingTypes'); return resolvingTypes.indexOf(type) > -1; }, });
JavaScript
0.000002
@@ -553,18 +553,9 @@ -Contains n +N ames @@ -562,20 +562,17 @@ of type - for +s which n @@ -574,29 +574,32 @@ ich need - lookup class +s to be resolved with pr @@ -598,24 +598,26 @@ with prefix +es received th @@ -646,32 +646,46 @@ DeviceService%22%7D%7D +device service %7B%7B/crossLink%7D%7D.%0A @@ -4122,30 +4122,54 @@ cks -%60 +that ' type -%60 +' need - use +s to be resolved with prefix +es rec @@ -4214,16 +4214,30 @@ rvice%22%7D%7D +device service %7B%7B/cross @@ -4246,43 +4246,8 @@ nk%7D%7D - to lookup class this %60type%60 or not .%0A%0A
8aa84298ca34434e6e49fdf82ad7edb036986641
Fix loading cookies with old format
src/app/lib/filestore.js
src/app/lib/filestore.js
const tough = require('tough-cookie'); const { MemoryCookieStore } = require('tough-cookie/lib/memstore'); const fs = require('fs'); function iterateProperties(obj, cb) { for(let elem in obj) { if(obj.hasOwnProperty(elem)) { cb(elem, obj[elem]) } } } class FileStore extends MemoryCookieStore { constructor(file) { super(); this.file = file; this.load(); } createSaveCallback(callback) { return (err) => { if(err) { callback(err); } else { this.save(callback); } }; } putCookie(cookie, callback) { super.putCookie(cookie, this.createSaveCallback(callback)); } removeCookie(domain, path, key, callback) { super.removeCookie(domain, path, key, this.createSaveCallback(callback)); } removeCookies(domain, path, callback) { super.removeCookies(domain, path, this.createSaveCallback(callback)); } load() { const data = fs.readFileSync(this.file, 'utf8'); let json = data ? JSON.parse(data) : {}; iterateProperties(json, (domain, paths) => { iterateProperties(paths, (path, cookies) => { iterateProperties(cookies, (cookieName, cookie) => { json[domain][path][cookieName] = tough.fromJSON(JSON.stringify(cookie)); }); }); }); this.idx = json; } save(callback) { const data = JSON.stringify(this.idx); fs.writeFile(this.file, data, (err) => { if(err) { throw err; } else { callback(); } }); } } module.exports = FileStore;
JavaScript
0
@@ -1082,23 +1082,148 @@ -let json = data +if (data.length %3E= 2) %7B%0A if (data%5B0%5D == '%7B' && data%5Bdata.length - 1%5D == '%7D') %7B%0A let json = data && data.length %3E 0 ? J @@ -1244,16 +1244,24 @@ ) : %7B%7D;%0A + @@ -1309,32 +1309,40 @@ %3E %7B%0A + + iteratePropertie @@ -1379,32 +1379,40 @@ + + iteratePropertie @@ -1444,24 +1444,32 @@ ookie) =%3E %7B%0A + @@ -1557,32 +1557,40 @@ + + %7D);%0A @@ -1581,32 +1581,40 @@ %7D);%0A + + %7D);%0A %7D);%0A @@ -1613,21 +1613,36 @@ + -%7D);%0A%0A + %7D);%0A%0A this @@ -1633,24 +1633,25 @@ + this.idx = j @@ -1655,16 +1655,254 @@ = json;%0A + %7D else %7B%0A LOG.warn(%22Encountered old cookies. Ignoring.%22);%0A this.idx = %7B%7D;%0A this.save(() =%3E %7B%0A %7D);%0A %7D%0A %7D else %7B%0A this.idx = %7B%7D;%0A %7D%0A %7D%0A%0A
880d30bd2907adccd0b623b2ea9df92e0dfabd02
Update HFC Google Maps API Key (from website source code)
examples/cities.js
examples/cities.js
var fs = require('fs'); // Replace with require('pikud-haoref-api') if the package resides in node_modules var pikudHaoref = require('../index'); // Pikud Haoref Google Maps API Key var options = { googleMapsApiKey: 'AIzaSyBYZ7FFqB5U1mP1nAwJ0iScWU5GjDP1KCM' }; // Fetch city metadata from Pikud Haoref's website pikudHaoref.getCityMetadata(function (err, cities) { // Task failed? if (err) { return console.error(err); } // Write cities.json file to disc fs.writeFileSync('cities.json', JSON.stringify(cities, null, 2), 'utf8'); // Output success console.log('Wrote cities.json successfully'); }, options);
JavaScript
0
@@ -226,41 +226,41 @@ zaSy -BYZ7FFqB5U1mP1nAwJ0iScWU5GjDP1KCM +CSeMZ5AxUgSWHy6EedcgeXjRC2irszdUQ '%0A%7D;
7c3cf505456c06d83b1ffc42c54f0b3c4bd0417b
change deleteOldNotifications cronjob time
server/commons/cronjobs.js
server/commons/cronjobs.js
// Cron Jobs // Delete users with scheduledDelete set on profile SyncedCron.add({ name: 'deleteUser', schedule: function(parser) { return parser.text('at 05:30'); }, job: function() { return Bisia.Automator.deleteUsersFromBisia(); } }); // Delete notifications read older than a week SyncedCron.add({ name: 'deleteNotifications', schedule: function(parser) { return parser.text('at 05:00'); }, job: function() { return Bisia.Automator.deleteOldNotifications(); } }); // Send notification email messages SyncedCron.add({ name: 'sendEmail', schedule: function(parser) { // return parser.text('every 2 hours'); return parser.text('at 07:45 and 12:35 and 18:45 and 22:45'); }, job: function() { return Bisia.Automator.emailNotifications(); } }); // Chat Room Ban SyncedCron.add({ name: 'chatRoomBan', schedule: function(parser) { return parser.text('every 3 minutes'); }, job: function() { return Bisia.Automator.chatRoomBanUsers(); } }); // recharge poker credits every day at 00:00:05 except on Monday SyncedCron.add({ name: 'rechargePokerCredits', schedule: function(parser) { return parser.text('at 00:01'); }, job: function() { return Bisia.Poker.rechargeCredits(); } }); // reset poker week SyncedCron.add({ name: 'resetPokerWeek', schedule: function(parser) { return parser.text('on Monday at 00:01'); // return parser.text('every 1 minutes'); }, job: function() { return Bisia.Poker.resetPokerWeek(); } });
JavaScript
0
@@ -393,18 +393,18 @@ ('at 05: -00 +45 ');%0A%09%7D,%0A
7e44b33b4915553f6620b025fa75cea0785f2702
Remove shown tooltips after EPESI loading
modules/Utils/Tooltip/js/tooltip.js
modules/Utils/Tooltip/js/tooltip.js
Utils_Tooltip = { timeout_obj: false, enable_tooltips: function () { jQuery('body').tooltip({selector: '[data-toggle="tooltip"]', html: true, trigger: "hover", container: "body"}) }, load_ajax: function (tooltip_id) { jQuery('[data-ajaxtooltip="' + tooltip_id + '"]').on('shown.bs.tooltip', function () { var el = jq(this); if (el.data('ajaxtooltip')) { jq.ajax({ type: 'POST', url: 'modules/Utils/Tooltip/req.php', data: { tooltip_id: el.data('ajaxtooltip'), cid: Epesi.client_id }, success: function (t) { el .attr('title', t) .tooltip('fixTitle'); el.data('ajaxtooltip', null); if (el.hasClass('lbOn')) { Utils_Tooltip.leightbox_mode(el); if (!jq('#tooltip_leightbox_mode_content').is(':visible')) { el.tooltip('show'); } } else { el.tooltip('show'); } } }); } }); }, leightbox_mode: function (o) { var jo = jq(o); var tip = jo.attr('data-original-title'); jq('#tooltip_leightbox_mode_content').html(tip); } }
JavaScript
0
@@ -188,16 +188,111 @@ %22body%22%7D) +;%0A jQuery(document).on('e:loading', function() %7B jQuery('%5Brole=%22tooltip%22%5D').remove() %7D); %0A %7D,%0A
76b175154b058d35a2dc8c1ce176cde16ea7ab7d
Add favicon
pages/_document.js
pages/_document.js
import React from 'react' import Document, { Head, Main, NextScript } from 'next/document' import stylesheet from './styles.scss' export default class MyDocument extends Document { render () { return ( <html> <Head> <meta charSet='utf-8' /> <meta name='viewport' content='width=device-width, initial-scale=1' /> <style dangerouslySetInnerHTML={{ __html: stylesheet }} /> </Head> <body> <Main /> <NextScript /> </body> </html> ) } }
JavaScript
0.000142
@@ -411,24 +411,342 @@ sheet %7D%7D /%3E%0A + %3Clink rel='icon' type='image/png' href='/static/img/favicon/favicon-16x16.png' sizes='16x16' /%3E%0A %3Clink rel='icon' type='image/png' href='/static/img/favicon/favicon-32x32.png' sizes='32x32' /%3E%0A %3Clink rel='icon' type='image/png' href='/static/img/favicon/favicon-96x96.png' sizes='96x96' /%3E%0A %3C/He
be8f649ddd543350f2cad2d4674338e9f4564d74
Add style prop schema
preview.js
preview.js
import React, { PropTypes, Component } from 'react'; export const getScale = (previewSize, cropArea) => { return previewSize.width / cropArea.width; }; export const getOrigin = (cropArea) => { return { x: cropArea.left + cropArea.width / 2, y: cropArea.top + cropArea.height / 2 }; }; export const getTransformations = (cropArea, containerSize) => { const scale = getScale(containerSize, cropArea); const origin = getOrigin(cropArea); // Move crop area center into container center const translateX = containerSize.width / 2 - origin.x; const translateY = containerSize.height / 2 - origin.y; return { originX: origin.x, originY: origin.y, translateX, translateY, scale }; }; export default class PureCropperPreview extends Component { static propTypes = { originalURL: PropTypes.string.isRequired, cropArea: PropTypes.shape({ top: PropTypes.number.isRequired, left: PropTypes.number.isRequired, width: PropTypes.number.isRequired, height: PropTypes.number.isRequired }), style: PropTypes.object } render() { const { originalURL, cropArea, style = {} } = this.props; const { originX, originY, translateX, translateY, scale } = getTransformations(cropArea, style); const imageStyle = { transform: `translate(${translateX}px, ${translateY}px) scale(${scale})`, transformOrigin: `${originX}px ${originY}px` }; const containerStyle = { ...style, overflow: 'hidden' }; return ( <div style={ containerStyle }> <img src={ originalURL } style={ imageStyle } /> </div> ); } }
JavaScript
0
@@ -1082,14 +1082,106 @@ pes. -object +shape(%7B%0A width: PropTypes.number.isRequired,%0A height: PropTypes.number.isRequired%0A %7D) %0A %7D
dc58df48961c0edb60cd96527fc3e627580ea71a
Update current nsIAlertSerivce implementation
bootstrap.js
bootstrap.js
/* vim: set ts=2 ft=javascript */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ const Cc = Components.classes; const Ci = Components.interfaces; const Cr = Components.results; const Cu = Components.utils; const Cm = Components.manager; Cu.import("resource://gre/modules/XPCOMUtils.jsm"); Cu.import("resource://gre/modules/Services.jsm"); Cu.import("resource://gre/modules/ctypes.jsm"); Cu.import("resource://gre/modules/FileUtils.jsm"); var sLibrary; var sCallbacks = new Array(); function GetBinaryFile() { if (ctypes.voidptr_t.size == 4) { return FileUtils.getFile("ProfD", ["extensions", "toast-alert@wontfix.net", "ToastNotification.dll"]); } return FileUtils.getFile("ProfD", ["extensions", "toast-alert@wontfix.net", "ToastNotification64.dll"]); } function IsSupported() { if (!sLibrary) { sLibrary = ctypes.open(GetBinaryFile().path); } var setAppId = sLibrary.declare("SetAppId", ctypes.winapi_abi, ctypes.bool); return setAppId(); } function ToastAlertService() { } ToastAlertService.prototype = { showAlert: function(aAlert, aListener) { if (!aAlert) { return; } this.showAlertNotification(aAlert.imageURL, aAlert.title, aAlert.text, aAlert.textClickable, aAlert.cookie, aListener, aAlert.name, aAlert.dir, aAlert.lang, aAlert.data, aAlert.principal, aAlert.inPrivateBrowsing); }, showAlertNotification: function(aImageUrl, aTitle, aText, aTextClickable, aCookie, aListener, aName, aDir, aLang, aData, aPrincipal, aInPrivateBrowsing) { var callbackPtr = ctypes.FunctionType(ctypes.stdcall_abi, ctypes.void_t).ptr; var DisplayToastNotification = sLibrary.declare("DisplayToastNotification", ctypes.winapi_abi, ctypes.bool, ctypes.jschar.ptr, ctypes.jschar.ptr, ctypes.jschar.ptr, ctypes.jschar.ptr, callbackPtr, callbackPtr); var callbackClick = null; if (aTextClickable) { callbackClick = callbackPtr(function() { if (this.listener) { this.listener.observe(null, "alertclickcallback", this.cookie); } }, { listener: aListener, cookie: aCookie }); } var callbackClose = callbackPtr(function() { if (this.listener) { this.listener.observe(null, "alertfinished", this.cookie); } sCallbacks.forEach(function(element) { if (element.name === this.name) { sCallbacks.pop(element); } }); }, { listener: aListener, cookie: aCookie, name: aName }); // keep callback objects for GC sCallbacks.push({click: callbackClick, close: callbackClose, name: aName}); if (!DisplayToastNotification(aTitle, aText, aImageUrl, aName, callbackClick, callbackClose)) { throw Cr.NS_ERROR_FAILURE; } if (aListener) { aListener.observe(null, "alertshow", aCookie); } }, closeAlert: function(aName, aPrincipal) { var CloseToastNotification = sLibrary.declare("CloseToastNotification", ctypes.winapi_abi, ctypes.bool, ctypes.jschar.ptr); CloseToastNotification(aName); }, QueryInterface: XPCOMUtils.generateQI([Ci.nsIAlertsService]), classDescription: "alert service using Windows 8 native toast", contractID: "@mozilla.org/system-alerts-service;1", classID: Components.ID("{6270a80b-07e3-481b-804a-644ed6bc991d}"), }; var alertService = new ToastAlertService; var factory = { createInstance: function(aOuter, aIid) { if (aOuter) { throw Cr.NS_ERROR_NO_AGGREGATION; } return alertService.QueryInterface(aIid); }, lockFactory: function(aLock) { throw Cr.NS_ERROR_NOT_IMPLEMENTED; }, QueryInterface: XPCOMUtils.generateQI([Ci.nsIFactory]) }; function registerComponents() { let registrar = Components.manager.QueryInterface(Ci.nsIComponentRegistrar); registrar.registerFactory(alertService.classID, alertService.classDescription, alertService.contractID, factory); } function unregisterComponents() { if (sLibrary) { sLibrary.close(); sLibrary = null; } try { let registrar = Components.manager.QueryInterface(Ci.nsIComponentRegistrar); registrar.unregisterFactory(alertService.classID, factory); } catch (e) { // ignore error } } function install(aData, aReason) { } function uninstall(aData, aReason) { } function startup(aData, aReason) { if (!IsSupported()) { return; } registerComponents(); } function shutdown(aData, aReason) { unregisterComponents(); }
JavaScript
0
@@ -1894,16 +1894,74 @@ Browsing +,%0A aAlert.requireInteraction );%0A %7D,%0A @@ -2182,16 +2182,71 @@ Browsing +,%0A aRequireInteraction ) %7B%0A @@ -4150,16 +4150,142 @@ ;%0A %7D,%0A%0A + showPersistentNofitication: function(aPersistentData, aAlert, aAlertListener) %7B%0A sowAlert(aAlert, aAlertListener);%0A %7D,%0A%0A QueryI
470dfa99032d1d4573117700c0c1b2411cf90aca
Add number regex
src/app/validators/number-validator.directive.js
src/app/validators/number-validator.directive.js
(function() { 'use strict'; var app = angular.module('radar.validators'); // TODO app.directive('numberValidator', function() { return { restrict: 'A' }; }); })();
JavaScript
0.99995
@@ -73,16 +73,66 @@ ors');%0A%0A + var NUMBER_REGEX = /%5E%5B+-%5D?%5B0-9%5D+(%5C.%5B0-9%5D+)?$/;%0A%0A // TOD
fb2db9a29c99a5a6fff14f3bc78bcd933511010d
improve parameter name
src/app/models/client.js
src/app/models/client.js
import { v4 } from "uuid" import { forEach, forEachObjIndexed, isNil, map, reject, zipObj } from "ramda" import Redis from "./redis" import Game from "./game" import Revision from "./revision" import { logger } from "~/app/index" import { BLACK } from "~/share/constants/chess" import { BEFORE, PRIMARY, AFTER } from "~/share/constants/role" import { LEFT, RIGHT } from "~/share/constants/direction" import { POSITION } from "~/share/constants/game_update_types" import { UNIVERSE_CHANNEL } from "./universe" export default class Client { constructor(universe, user, socket) { this.universe = universe this.user = user this.socket = socket this.redis = new Redis() this.redis.on("message", this.messageHandler.bind(this)) this.subscribeUniverse() this.uuid = v4() this.gameUUID = null } async startGame(serializedGame) { this.gameUUID = serializedGame.uuid this.subscribeGame(this.gameUUID) this.socket.send({ action: "start", game: serializedGame }) } // senders sendUniverse(universe) { this.socket.send({ action: "universe", universe }) } sendLogin() { if (isNil(this.user)) { return } this.socket.send({ action: "login", user: this.user.serialize() }) } async sendGame(game, role) { if (isNil(game)) { return } await game.serializePrepare() this.socket.send({ action: "game", role, game: game.serialize() }) } async sendPosition({ uuid, position }) { this.socket.send({ action: POSITION, uuid, position }) } // subscribers subscribeUniverse() { this.redis.subscribe(UNIVERSE_CHANNEL) } subscribeGame(uuid) { this.redis.subscribe(uuid) } // actions async kibitz() { if (await this.universe.games.length() === 0) { return } const first = await this.universe.games.head() const second = await this.universe.games.next(first) const third = await this.universe.games.next(second) const uuids = [first, second, third] const notNilUUIDs = reject(isNil, uuids) const games = await Game.where("uuid", "in", notNilUUIDs).fetchAll() const orderedGames = map((uuid) => { return games.find((game) => { return game.get("uuid") === uuid }) }, uuids) forEach(this.subscribeGame.bind(this), notNilUUIDs) forEachObjIndexed( this.sendGame.bind(this), zipObj([BEFORE, PRIMARY, AFTER], orderedGames) ) } async rotate({ direction, of }) { let uuid, role switch (direction) { case LEFT: uuid = await this.universe.nextGame(of) role = AFTER break case RIGHT: uuid = await this.universe.prevGame(of) role = BEFORE break default: logger.debug(`[rotate] Encountere unexpected direction: ${direction}`) return } this.subscribeGame(uuid) this.sendGame(await Game.where({ uuid: uuid }).fetch(), role) } async play() { this.universe.registerClient(this) } async move(data) { if (isNil(this.gameUUID)) { return } // TODO: authorize user const { revision, moveResult } = await Revision.move(this.gameUUID, data) if (revision) { if (moveResult && moveResult.captured) { // coerce into correct reserve if (moveResult.color === BLACK) { moveResult.captured = moveResult.piece.toUpperCase() } const game = await revision.game().fetch() this.universe.publishCapture(game, moveResult.captured) } // TODO: if revision is a result, publish result, removing from state const position = await revision.position().fetch() this.universe.publishPosition(this.gameUUID, position) } else { this.socket.send({ action: "invalid", data }) } } // handler messageHandler(channel, message) { switch (channel) { case UNIVERSE_CHANNEL: this.sendUniverse(JSON.parse(message)) break default: this.sendGameUpdate(channel, message) } } sendGameUpdate(uuid, message) { const { type, payload } = JSON.parse(message) if (type === POSITION) { this.sendPosition({ uuid, position: payload }) } } }
JavaScript
0.000118
@@ -3015,20 +3015,20 @@ nc move( -data +move ) %7B%0A @@ -3175,20 +3175,20 @@ meUUID, -data +move )%0A%0A i
576f0e28a8eb8f329b9dc827285922d327ec026a
fix redundancy
server/config/db.config.js
server/config/db.config.js
const Sequelize = require('sequelize') const creds = require('./credentials') // grabbing the data from credentials.json /* NOTE: that file is gitignored, add instructions on how to get username and password! */ // creates database connection credentials needed to connect to DB via Sequelize const dburl = `postgres://${creds.username}:${creds.password}@tantor.db.elephantsql.com:5432/sritpzob` // MARK, connect our db here!; const dbConnection = new Sequelize('postgres://sritpzob:inSkiV6E-lydsG8qoAmazy9Zmf9swVL3@tantor.db.elephantsql.com:5432/sritpzob') // Don't delete. May be useful later. // db.on('connected', function () { // console.log('Connected to database successfully.'); // }); // db.on('disconnected', function () { // console.log('Disconnected from database!'); // }); // db.on('error', function (err) { // console.log('Connectioned failed with error:', err); // }); // process.on('SIGINT', function () { // db.close(function () { // console.log('Process terminated. SOME DUDE PRESSED CONTROL+C!?'); // process.exit(0); // }); // }); // process.once('SIGUSR2', function () { // db.close(function () { // console.log('Process terminated by nodemon.'); // process.kill(process.pid, 'SIGUSR2'); // }); // }); module.exports = dbConnection require('../api/poi/poi.model.js') require('../api/users/users.model.js') require('../api/reviews/reviews.model.js')
JavaScript
0.000148
@@ -472,100 +472,13 @@ ze(' -postgres://sritpzob:inSkiV6E-lydsG8qoAmazy9Zmf9swVL3@tantor.db.elephantsql.com:5432/sritpzob +dburl ')%0A%0A
eba1874b624fe0808df5a5c7b4b99a82812b2514
add project creates div
dashboard.js
dashboard.js
$(document).ready(function() { // var header = document.getElementById("dancer_header"); // header.style.visibility='hidden'; document.getElementById("waveform_button").onclick = function () { location.href = document.location.href.replace("dashboard", "index"); }; $("#form_part1").submit(function(e){ var projectTitle = document.forms["form_part1"]["projectTitle"].value; var numDancers = document.forms["form_part1"]["numDancers"].value; var file = document.forms["form_part1"]["music"].value; var filename = $('input[type=file]').val().replace(/C:\\fakepath\\/i, ''); var div = document.createElement('div'); div.className = "pin ui-state-default" var button = document.createElement("button"); button.classname = "project_button"; var p = document.createElement("p"); var node = document.createTextNode(projectTitle + "<br>" + filename + "<br>" + numDancers +" dancers"); p.appendChild(node); div.appendChild(button); div.appendChild(p); var first = document.getElementById("first"); document.getElementById("columns").insertBefore(div, first); }); $("#numDancers").change(function(e){ var value = $("#numDancers").val(); addDancerInfo(value); console.log(value); }) $( ".sortable" ).sortable({ revert: true }); $( ".sortable" ).disableSelection(); function addDancerInfo(numDancers){ for(i = 0; i< numDancers; i++){ var name = document.createElement("fieldset"); var name_label = document.createElement("label"); name_label.innerHTML = "Dancer Name (" + (i+1) + ")"; var name_input = document.createElement("input"); name_input.type = "text"; name_input.className = "form-control name input"; name_input.name = "dancer" + i; name_input.placeholder = "First, Last"; name.appendChild(name_label); name.appendChild(name_input); var info = document.createElement("fieldset"); var info_label = document.createElement("label"); info_label.innerHTML = "Dancer Notes"; var info_text = document.createElement("textarea"); info_text.className = "form-control input"; info_text.name = "dancer_info" + i; info_text.rows = 3; info.appendChild(info_label); info.appendChild(info_text); var submit = document.getElementById("submit_button"); document.getElementById("form_part1").insertBefore(name, submit); document.getElementById("form_part1").insertBefore(info, submit); console.log("success"); } $("input").prop('required',true); }; });
JavaScript
0.000001
@@ -883,19 +883,22 @@ -var node = +p.appendChild( docu @@ -933,91 +933,244 @@ itle - + %22%3Cbr%3E%22 + filename + %22%3Cbr%3E%22 + numDancers +%22 dancers%22);%0A p.appendChild(node +));%0A p.appendChild(document.createElement('br'))%0A p.appendChild(document.createTextNode(filename));%0A p.appendChild(document.createElement('br'))%0A p.appendChild(document.createTextNode(numDancers + %22 dancers%22) );%0A @@ -1349,24 +1349,93 @@ iv, first);%0A + $(%22#new_project_modal%22).modal('hide');%0A return false;%0A %7D);%0A%0A%0A @@ -1517,16 +1517,51 @@ .val();%0A + $(%22.new_dancer%22).remove();%0A @@ -1800,16 +1800,114 @@ i++)%7B%0A%0A + var container = document.createElement('div');%0A container.className = %22new_dancer%22%0A @@ -2386,16 +2386,53 @@ _input); +%0A container.appendChild(name); %0A%0A @@ -2844,16 +2844,53 @@ _text);%0A + container.appendChild(info);%0A %0A%0A @@ -3009,86 +3009,17 @@ ore( -name, submit);%0A document.getElementById(%22form_part1%22). +conta in -s er -tBefore(info , su
ac394a9dc52f9dfaa37d6bbea107953d4c335de2
make sure the promise rejects when it should
packages/api/utils/audio-over-socket.js
packages/api/utils/audio-over-socket.js
/** * This file contains some re-usable parts for websocket audio communication. * * @module api/utils/audio-over-socket */ import autobahn from 'autobahn'; import { getWebsocketConnection, makeWebsocketCall } from '../communication/websocket'; import broadcaster from '../broadcaster'; import { dataToBase64, asyncBlobToArrayBuffer } from './index'; /** * This class allows us to stream audio from the recorder to the backend. * @private */ class StreamRecorderAudio { /** * @param {MediaRecorder} recorder - Recorder to use to capture data from. * @param {string} rpcName - Name of the registered RPC function. */ constructor(recorder, rpcName, websocketConnection) { /** * MediaRecorder to process the stream from. * @type {MediaRecorder} */ this.recorder = recorder; /** * Name of the RPC registered. * This name will be prepended with 'nl.itslanguage' for better consistency. * @type {string} */ this.rpcName = `nl.itslanguage.${rpcName}`; /** * Store a reference to the websocket connection. * @type {autobahn.Connection} */ this.websocketConnection = websocketConnection; /** * The autobahn.Registration object. This is returned when you register * a function through Session.register. * @type {null|autobahn.Registration} */ this.registration = null; this.sendAudioChunks = this.sendAudioChunks.bind(this); this.register = this.register.bind(this); this.unregister = this.unregister.bind(this); } /** * This is the function that will be registered to the autobahn realm that the backend will call * to receive audio on. * * Once called, it will prepare the recorder to allow data transmission trough the progressive * results meganism. * * @see https://github.com/crossbario/autobahn-js/blob/master/doc/reference.md#register * @see https://github.com/crossbario/autobahn-js/blob/master/doc/reference.md#progressive-results * * @private * @param {Array} args - Argument list. * @param {Object} kwargs - Key-valued argument list. * @param {Object} details - Details, just as the progress function. * @returns {Promise} - A promise that can be resolved to end the asynchronous behaviour of this * registered RCP. */ sendAudioChunks(args, kwargs, details) { const defer = new autobahn.when.defer(); // eslint-disable-line new-cap let lastChunk = false; this.recorder.addEventListener('dataavailable', ({ data }) => { asyncBlobToArrayBuffer(data).then((audioData) => { if (details.progress) { const dataToSend = Array.from(new Uint8Array(audioData)); details.progress([dataToSend]); // If the last one ends, closing time! if (lastChunk) { defer.resolve(); this.unregister(); } } }); }); this.recorder.addEventListener('stop', () => { // When stopped, the dataavailableevent will be triggered // one final time, so make sure it will cleanup afterwards lastChunk = true; }); return defer.promise; } /** * register the RPC to the autobahn realm. * @returns {Promise} */ register() { return new Promise((resolve, reject) => { this.websocketConnection.session .register(this.rpcName, this.sendAudioChunks) .then((registration) => { this.registration = registration; resolve(registration); }).catch(reject); }); } /** * unregister the RPC from the autobahn realm. */ unregister() { return new Promise((resolve, reject) => { this.websocketConnection.session .unregister(this.registration) .then(() => { this.registration = null; resolve(); }).catch(reject); }); } } /** * Register a RPC call to the current websocket connection. The backend will call this registered * function once, an then we can send progressive results (the details.progress call) to send audio * chunks to the backend. We will send those chunks as soon as we got audio from the recorder. * * When the recording ends we un-register the rpc. * * @param {MediaRecorder} recorder - Audio recorder instance. * @param {string} rpcName - Name of the RPC to register. This name will be prepended with * nl.itslanguage for better consistency. * @fires broadcaster#websocketserverreadyforaudio * @returns {Promise} - It returns a promise with the service registration as result. */ export function registerStreamForRecorder(recorder, rpcName) { // Start registering a RPC call. As a result, this function will return a promise with the // registration of the RPC as result. return new Promise((resolve, reject) => { getWebsocketConnection().then((websocketConnection) => { const streamingSession = new StreamRecorderAudio(recorder, rpcName, websocketConnection); streamingSession.register() .then((registration) => { /** * Notify that we are ready to process audio. * @event broadcaster#websocketserverreadyforaudio */ broadcaster.emit('websocketserverreadyforaudio'); resolve(registration); }) .catch(reject); }); }); } /** * Encode the audio as base64 and send it to the websocket server. * * @param {string} id - The reserved ID for the audio. * @param {MediaRecorder} recorder - The recorder to use to get the recording. * @param {string} rpc - The RPC to use to store the data. * * @returns {Promise<*>} - The response of the given RPC. */ export function encodeAndSendAudioOnDataAvailable(id, recorder, rpc) { return new Promise((resolve, reject) => { // When data is received from the recorder, it will be in Blob format. // When we read the data from the Blob element, base64 it and send it to // the websocket server and continue with the chain. recorder.addEventListener('dataavailable', ({ data }) => { asyncBlobToArrayBuffer(data).then((audioData) => { const encoded = dataToBase64(audioData); // Send the audio makeWebsocketCall(rpc, { args: [id, encoded, 'base64'] }) .then(resolve, reject); }); }); }); } /** * Send the recorder settings to the websocket server to initialize it. * * The reserved ID (passed in the parameters) is returned once the promise is resolved. * * @param {string} id - The reserved ID for the audio. * @param {MediaRecorder} recorder - The recorder which has been set up to record. * @param {string} rpc - The RPC to use to initialize the websocket server. * * @emits {websocketserverreadyforaudio} - When the websocket server has been prepared for and is * ready to receive the audio. * * @returns {Promise} - The promise which resolves when the websocket server is ready for the audio. */ export function prepareServerForAudio(id, recorder, rpc) { const { audioFormat, audioParameters } = recorder.getAudioSpecs(); return makeWebsocketCall(rpc, { args: [id, audioFormat], kwargs: audioParameters }) .then(() => { // We've prepped the websocket server, now it can receive audio. Broadcast // that it is allowed to record. broadcaster.emit('websocketserverreadyforaudio'); return id; }); }
JavaScript
0.000021
@@ -2866,24 +2866,100 @@ %7D%0A + %7D else %7B%0A defer.reject('no progress function registered');%0A %7D%0A
7ac5a4cf2a50854dbbfc9a68e11edc2dca1a2403
add notes
Algorithms/JS/arrays/matrices/nQueenProblem.js
Algorithms/JS/arrays/matrices/nQueenProblem.js
// Objec­tive : In chess, a queen can move as far as she pleases, hor­i­zon­tally, ver­ti­cally, or diag­o­nally. // A chess board has 8 rows and 8 columns. // The stan­dard 8 by 8 Queen’s prob­lem asks how to place 8 queens on an ordi­nary chess board // so that none of them can hit any other in one move. // Here we are solv­ing it for N queens in NxN chess board. var iterations = 0 var printBoard = function (columns) { var n = columns.length, row = 0, col = 0; while (row < n) { while (col < n) { process.stdout.write(columns[row] === col ? 'Q ' : '# ') col++; } process.stdout.write('\n'); col = 0; row++; } } var hasConflict = function (columns) { var len = columns.length-1, last = columns[len], previous = len - 1; while (previous >= 0) { if (columns[previous] === last) return true; if (last - (len) === columns[previous] - previous) return true; if (last + (len) === columns[previous] + previous) return true; previous--; } return false; } var placeNextQueen = function (total, queens, columns) { if (queens === 0) return columns; columns = columns || []; for (var column = 0; column < total; column++) { columns.push(column); iterations++; if ( !hasConflict(columns) && placeNextQueen(total, queens - 1, columns) ) return columns; columns.pop(column); } return null; } printBoard(placeNextQueen(10, 10)); console.log('\niterations: ', iterations);
JavaScript
0
@@ -856,32 +856,52 @@ st) return true; + // cant be same row %0A if (last - @@ -948,24 +948,74 @@ return true; + // prev cant be one away from current cuz of diag %0A if (las @@ -1107,17 +1107,53 @@ false;%0A - %7D +%0A// 00 01 02%0A// 10 11 12%0A// 20 21 22 %0A%0Avar pl
0d9cc4057ae0322e53d83da21baa36f2f445c671
Refactor code
server/controllers/auth.js
server/controllers/auth.js
import passport from 'passport'; import passportLocal from 'passport-local'; import bcrypt from 'bcrypt'; import user from '../models'; import helpers from '../helpers'; const LocalStrategy = passportLocal.Strategy; passport.serializeUser((sessionUser, done) => { done(null, sessionUser.id); }); passport.deserializeUser((id, done) => { User.findById(id, (err, sessionUser) => done(err, sessionUser)); }); passport.use(new LocalStrategy({ passReqToCallback: true }, (req, username, password, done) => { user.User.findOne({ where: { username } }).then((users) => { if (!users) { return done(null, false, { message: 'Incorrect username' }); } // Compare database salt to the hash of incoming password const reqPasswordHash = bcrypt.hashSync(req.body.password, users.salt); if (users.password === reqPasswordHash) { return done(null, users); } return done(null, false, { message: ' Incorrect password.' }); }).catch(err => done(err)); } )); module.exports = passport;
JavaScript
0.000002
@@ -106,20 +106,22 @@ %0Aimport -user +models from '. @@ -211,16 +211,42 @@ trategy; +%0Aconst User = models.User; %0A%0Apasspo @@ -538,13 +538,8 @@ %7B%0A -user. User
f5f26a771785b94185fb3928adc0cdeae4cdccf4
Update app.js
assets/js/app.js
assets/js/app.js
$( document ).ready(function() { /* Sidebar height set */ $('.sidebar').css('min-height',$(document).height()); /* Secondary contact links */ var scontacts = $('#contact-list-secondary'); var contact_list = $('#contact-list'); scontacts.hide(); contact_list.mouseenter(function(){ scontacts.fadeIn(); }); contact_list.mouseleave(function(){ scontacts.fadeOut(); }); });
JavaScript
0.000002
@@ -375,13 +375,12 @@ (); %7D);%0A -%0A %7D);%0A
931e4ec0cafa5f99b3e7255172eddcc8cbcfd797
Fix ready function.
slyd/media/js/app.js
slyd/media/js/app.js
/*************************** Application **************************/ ASTool = Em.Application.create({ LOG_TRANSITIONS: true, ready: function() { LOG_TRANSITIONS: true, } }); // Leave 'null' for using window.location. Define it to override. var SLYD_URL = null; (function getServerCapabilities(app) { app.deferReadiness(); var hash = {}; hash.type = 'GET'; hash.url = (SLYD_URL || window.location.protocol + '//' + window.location.host) + '/server_capabilities'; ic.ajax(hash).then(function(capabilities) { this.set('serverCapabilities', capabilities); this.advanceReadiness(); }.bind(app)); })(ASTool); Ember.Application.initializer({ name: 'slydApiInitializer', initialize: function(container, application) { container.register('api:slyd', ASTool.SlydApi); application.inject('route', 'slyd', 'api:slyd'); application.inject('adapter', 'slyd', 'api:slyd'); application.inject('controller', 'slyd', 'api:slyd'); } }); Ember.Application.initializer({ name: 'documentViewInitializer', initialize: function(container, application) { container.register('document:view', ASTool.DocumentView); application.inject('controller', 'documentView', 'document:view'); } }); Ember.Application.initializer({ name: 'annotationsStoreInitializer', initialize: function(container, application) { container.register('annotations:store', ASTool.AnnotationsStore); application.inject('route', 'annotationsStore', 'annotations:store'); application.inject('controller', 'annotationsStore', 'annotations:store'); } }); function s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); }; function guid() { return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); } function shortGuid() { return s4() + '.' + s4() + '.' + s4(); } function toType(obj) { return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase() } ASTool.guid = guid; ASTool.shortGuid = shortGuid;
JavaScript
0
@@ -153,47 +153,11 @@ () %7B -%0A LOG_TRANSITIONS: true, %0A %7D - %0A%7D);
f3e16214cb92a6f904ef5438697fe1d5de4d1187
Fix missing comma in LangDic.js
src/LangDic.js
src/LangDic.js
export default { 'cn' : { // Chinese 'january':'一月', 'february':'二月', 'march':'三月', 'april':'四月', 'may':'五月', 'june':'六月', 'july':'七月', 'august':'八月', 'september':'九月', 'october':'十月', 'november':'十一月', 'december':'十二月', 'su':'日', 'mo':'一', 'tu':'二', 'we':'三', 'th':'四', 'fr':'五', 'sa':'六' }, 'jp' : { // Japanese 'january':'1月', 'february':'2月', 'march':'3月', 'april':'4月', 'may':'5月', 'june':'6月', 'july':'7月', 'august':'8月', 'september':'9月', 'october':'10月', 'november':'11月', 'december':'12月', 'su':'日', 'mo':'月', 'tu':'火', 'we':'水', 'th':'木', 'fr':'金', 'sa':'土' }, 'fr' : { // French 'january':'janvier', 'february':'février', 'march':'mars', 'april':'avril', 'may':'mai', 'june':'juin', 'july':'juillet', 'august':'août', 'september':'septembre', 'october':'octobre', 'november':'novembre', 'december':'décembre', 'su':'Dimanche', 'mo':'Lundi', 'tu':'Mardi', 'we':'Mercredi', 'th':'Jeudi', 'fr':'Vendredi', 'sa':'Samedi' }, 'it' : { // Italian 'january':'gennaio', 'february':'febbraio', 'march':'marzo', 'april':'aprile', 'may':'maggio', 'june':'giugno', 'july':'luglio', 'august':'agosto', 'september':'settembre', 'october':'ottobre', 'november':'novembre', 'december':'dicembre', 'su':'Domenica', 'mo':'Lunedì', 'tu':'Mardi', 'we':'Mercoledì', 'th':'Giovedì', 'fr':'Venerdì', 'sa':'Sabato' }, 'de' : { // German 'january':'Januar', 'february':'Februar', 'march':'März', 'april':'April', 'may':'Mai', 'june':'Juni', 'july':'Juli', 'august':'August', 'september':'September', 'october':'Oktober', 'november':'November', 'december':'Dezember', 'su':'Sonntag', 'mo':'Montag', 'tu':'Dienstag', 'we':'Mittwoch', 'th':'Donnerstag', 'fr':'Freitag', 'sa':'Samstag' }, 'ko' : { // Korean 'january':'1월', 'february':'2월', 'march':'3월', 'april':'4월', 'may':'5월', 'june':'6월', 'july':'7월', 'august':'8월', 'september':'9월', 'october':'10월', 'november':'11월', 'december':'12월', 'su':'일', 'mo':'월', 'tu':'화', 'we':'수', 'th':'목', 'fr':'금', 'sa':'토' } 'es' : { // Spanish 'january':'Enero', 'february':'Febrero', 'march':'Marzo', 'april':'Abril', 'may':'Mayo', 'june':'Junio', 'july':'Julio', 'august':'Agosto', 'september':'Septiembre', 'october':'Octubre', 'november':'Noviembre', 'december':'Diciembre', 'su':'Do', 'mo':'Lu', 'tu':'Ma', 'we':'Mi', 'th':'Ju', 'fr':'Vi', 'sa':'Sa' }, 'ru' : { // Russian 'january':'Январь', 'february':'Февраль', 'march':'Март', 'april':'Апрель', 'may':'Май', 'june':'Июнь', 'july':'Июль', 'august':'Август', 'september':'Сентябрь', 'october':'Октябрь', 'november':'Ноябрь', 'december':'Декабрь', 'su':'Вс', 'mo':'Пн', 'tu':'Вт', 'we':'Ср', 'th':'Чт', 'fr':'Пт', 'sa':'Сб' }, 'tr' : { // Turkish 'january':'Ocak', 'february':'Şubat', 'march':'Mart', 'april':'Nisan', 'may':'Mayıs', 'june':'Haziran', 'july':'Temmuz', 'august':'Ağustos', 'september':'Eylül', 'october':'Ekim', 'november':'Kasım', 'december':'Aralık', 'su':'Pz', 'mo':'Pts', 'tu':'Sa', 'we':'Ça', 'th':'Pe', 'fr':'Cu', 'sa':'Cts' }, }
JavaScript
0.999996
@@ -2416,16 +2416,17 @@ :'%ED%86%A0'%0A %7D +, %0A 'es'
55e933e33ec6c1e5ff18d293401ca9f8b1a38aa2
Add use strict
subtitle.js
subtitle.js
/*! * Subtitle.js * Parse and manipulate SRT (SubRip) * https://github.com/gsantiago/subtitle.js * * @version 0.1.1 * @author Guilherme Santiago */ /** * Dependencies */ var extend = require('xtend/immutable') /** * @constructor * @param {String} Optional SRT content to be parsed */ function Subtitle (srt) { this._subtitles = [] if (srt) { this.parse(srt) } } /** * SRT parser * * @public * @param {String} SRT */ Subtitle.prototype.parse = function (srt) { var subs = [] var index var time var text var start var end if (!srt) { throw new Error('No SRT to parse') } srt = srt.trim() srt += '\n' srt = srt.replace(/\r\n/g, '\n').split('\n') srt.forEach(function (line) { line = line.toString() // if we don't have an index, so we should expect an index if (!index) { if (/^\d+$/.test(line)) { index = parseInt(line) return } } // now we have to check for the time if (!time) { var match = line.match(/^(\d{2}:\d{2}:\d{2},\d{3}) --> (\d{2}:\d{2}:\d{2},\d{3})$/) if (match) { start = match[1] end = match[2] time = true return } } // now we get all the strings until we get an empty line if (line.trim() === '') { subs.push({ index: index, start: start, end: end, duration: Subtitle.toMS(end) - Subtitle.toMS(start), text: text }) index = time = start = end = text = null } else { if (!text) { text = line } else { text += '\n' + line } } }) this._subtitles = subs return this } /** * Add a caption * You have to pass an object containing the following data: * start - The start time * end - The end time * text - The caption text * * The start and end time support two patterns: * The SRT: '00:00:24,400' * Or a positive integer representing milliseconds * * @public * @param {Object} Caption data */ Subtitle.prototype.add = function (caption) { if (!caption.start || !caption.end || !caption.text) { throw new Error('Invalid caption data') } for (var prop in caption) { if (!caption.hasOwnProperty(prop) || prop === 'text') { continue } if (prop === 'start' || prop === 'end') { if (/^(\d{2}):(\d{2}):(\d{2}),(\d{3})$/.test(caption[prop])) { continue } if (/^\d+$/.test(caption[prop])) { caption[prop] = Subtitle.toSrtTime(caption[prop]) } else { throw new Error('Invalid caption time format') } } } this._subtitles.push({ index: this._subtitles.length + 1, start: caption.start, end: caption.end, duration: Subtitle.toMS(caption.end) - Subtitle.toMS(caption.start), text: caption.text }) return this } /** * Convert the SRT time format to milliseconds * * @static * @param {String} SRT time format */ Subtitle.toMS = function (time) { var match = time.match(/^(\d{2}):(\d{2}):(\d{2}),(\d{3})$/) if (!match) { throw new Error('Invalid SRT time format') } var hours = parseInt(match[1], 10) var minutes = parseInt(match[2], 10) var seconds = parseInt(match[3], 10) var milliseconds = parseInt(match[4], 10) hours *= 3600000 minutes *= 60000 seconds *= 1000 return hours + minutes + seconds + milliseconds } /** * Convert milliseconds to SRT time format * * @static * @param {Integer} Milleseconds */ Subtitle.toSrtTime = function (time) { if (!/^\d+$/.test(time.toString())) { throw new Error('Time should be an Integer value in milliseconds') } time = parseInt(time) var date = new Date(0, 0, 0, 0, 0, 0, time) var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours() var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes() var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds() var ms = time - ((hours * 3600000) + (minutes * 60000) + (seconds * 1000)) if (ms < 100 && ms >= 10) { ms = '0' + ms } else if (ms < 10) { ms = '00' + ms } var srtTime = hours + ':' + minutes + ':' + seconds + ',' + ms return srtTime } /** * Return the subtitles * * @param {Object} Options * @returns {Array} Subtitles */ Subtitle.prototype.getSubtitles = function (options) { var subtitles = this._subtitles var defaults = { timeFormat: 'srt', duration: false } options = extend(defaults, options) if (options.timeFormat === 'ms') { subtitles = subtitles.map(function (caption) { caption.start = Subtitle.toMS(caption.start) caption.end = Subtitle.toMS(caption.end) return caption }) } if (!options.duration) { subtitles = subtitles.map(function (caption) { delete caption.duration return caption }) } return subtitles } /** * Returns the subtitles in SRT string * @returns {String} srt */ Subtitle.prototype.stringify = function () { var buffer = '' this._subtitles.forEach(function (caption, index) { if (index > 0) { buffer += '\n' } buffer += caption.index buffer += '\n' buffer += caption.start + ' --> ' + caption.end buffer += '\n' buffer += caption.text buffer += '\n' }) return buffer } /** * Resync the captions * @param {Integer} Time in milleseconds */ Subtitle.prototype.resync = function (time) { if (!/(-|\+)?\d+/.test(time.toString())) { throw new Error('Invalid time: ' + time + '.Expected a valid integer') } time = parseInt(time, 10) this._subtitles = this._subtitles.map(function (caption) { var start = Subtitle.toMS(caption.start) var end = Subtitle.toMS(caption.end) start = start + time end = end + time caption.start = start < 0 ? Subtitle.toSrtTime(0) : Subtitle.toSrtTime(start) caption.end = end < 0 ? Subtitle.toSrtTime(0) : Subtitle.toSrtTime(end) return caption }) return this } module.exports = Subtitle
JavaScript
0.000009
@@ -1,8 +1,22 @@ +'use strict'%0A%0A /*!%0A * S @@ -328,16 +328,77 @@ (srt) %7B%0A + if (!(this instanceof Subtitle)) return new Subtitle(srt)%0A%0A this._
09cff33b573d90d87c29895ebb03e3537b6a6dfd
fix off-by-one error—end param in `eagerSlice` is exclusive
src/LazyList.js
src/LazyList.js
import { cloneElement, Component, PropTypes } from 'react' const proxyMethods = [ 'getOffset', 'getScrollParent', 'getScroll', 'setScroll', 'getViewportSize', 'getScrollSize', 'getStartAndEnd', 'getItemSizeAndItemsPerRow', 'getSpaceBefore', 'getSizeOf', 'scrollTo', 'scrollAround', 'getVisibleRange' ] function requestPage (call, page, cb) { let promise = call(page, cb) if (promise && promise.then) { promise .then((res) => cb(null, res)) .then(null, cb) } } /** * Like `.slice`, but doesn't care about array bounds. * * [0, 1].slice(1, 3) === [1] * eagerSlice([0, 1], 1, 3) === [1, undefined, undefined] */ function eagerSlice (list, start, end) { const sliced = [] for (let i = start; i < end; i++) { sliced.push(list[i]) } return sliced } /** * Adds simple lazy loading to react-list. */ export default class LazyList extends Component { static propTypes = { /** * Total amount of items, on all pages. */ length: PropTypes.number.isRequired, /** * Items per page. */ pageSize: PropTypes.number, /** * When to begin loading the next page. */ loadMargin: PropTypes.number, /** * Loaded items. NULLs in this array indicate unloaded items. */ items: PropTypes.array, /** * Callback to begin loading a page. */ onRequestPage: PropTypes.func.isRequired } static defaultProps = { pageSize: 25, loadMargin: 5 } constructor (props) { super(props) this._list = null this._loadingPages = {} this.updateFrame = this.updateFrame.bind(this) } componentDidMount () { this.updateScrollParent() this.updateFrame() } componentDidUpdate () { this.updateScrollParent() this.updateFrame() } updateScrollParent () { const prev = this.scrollParent this.scrollParent = this.getScrollParent() if (prev === this.scrollParent) { return } if (prev) { prev.removeEventListener('scroll', this.updateFrame) } if (this.props.onRequestPage) { this.scrollParent.addEventListener('scroll', this.updateFrame) } } getList () { return this._list } isLoadingPage (page) { return !!this._loadingPages[page] } itemNeedsLoad (idx) { const { items, pageSize } = this.props const page = Math.floor(idx / pageSize) return items[idx] != null || this.isLoadingPage(page) } updateFrame () { const { pageSize, loadMargin, items, length, onRequestPage } = this.props // Item range that should be loaded right about now. let [topItem, bottomItem] = this.getVisibleRange() if (topItem === undefined || bottomItem === undefined) { return } topItem = Math.max(topItem - loadMargin, 0) bottomItem = Math.min(bottomItem + loadMargin, length - 1) const almostVisibleItems = eagerSlice(items, topItem, bottomItem) const unloadedPages = almostVisibleItems.reduce((pages, item, idx) => { if (item == null) { const page = Math.floor((topItem + idx) / pageSize) if (!this.isLoadingPage(page) && pages.indexOf(page) === -1) { return [ ...pages, page ] } } return pages }, []) unloadedPages.forEach((page) => { this._loadingPages[page] = true requestPage(onRequestPage, page, () => { // Always delete after completion. If there was an error, we can retry // later. If there wasn't, we don't need to keep this around :) delete this._loadingPages[page] }) }) } render () { return cloneElement(this.props.children, { ref: (list) => { this._list = list } }) } } proxyMethods.forEach((name) => { LazyList.prototype[name] = function (...args) { return this.getList()[name](...args) } })
JavaScript
0
@@ -2864,12 +2864,8 @@ ngth - - 1 )%0A%0A
4d2a80b4cb26bed3376b3697baaa200bed3ae4c9
Remove Extra Log Statement
src/mockingjay.js
src/mockingjay.js
/** * Core that determines wether to fetch a fresh copy from the source or * fetch a cached copy of the data. */ var CacheClient = require('./cache_client'); var HttpClient = require('./http_client'); var HeaderUtil = require('./header_util'); var Util = require('./util'); var url = require('url'); var Mockingjay = function(options) { this.options = options; this.cacheClient = new CacheClient(options); this.httpClient = new HttpClient(); } /** * Determine if we have request cached. */ Mockingjay.prototype.knows = function(request) { return this.cacheClient.isCached(request); }; /** * Fetch a Request form cache. */ Mockingjay.prototype.repeat = function(request) { console.log("\033[1;33mRepeating:\033[0m: ", JSON.stringify(request)); return this.cacheClient.fetch(request); }; /** * Fetch a Request form the Source. */ Mockingjay.prototype.learnOrPipe = function(request, outputBuffer) { console.log("\033[1;31mLearning:\033[0m: ", JSON.stringify(request)); var self = this; var responsePromise = this.httpClient.fetch(request, outputBuffer); return responsePromise.then(function (response) { if (self._okToCache(response.headers['content-type'])) { return self.cacheClient.record(request, response); } else { return Promise.resolve(response); } }); }; Mockingjay.prototype._okToCache = function (responseType) { // Ok to Cache when the Response Type is not in the ignore list. return !Util.regExArrayContains(this.options.ignoreContentType, responseType); }; /** * Function that echos the response back to the client. * Within this function we determine if we need to learn * or need to fetch a fresh response. */ Mockingjay.prototype.echo = function(request, outputBuffer) { console.log(request); var self = this; var shouldRepeat = this.knows(request) && !this.options.refresh; var responsePromise = shouldRepeat ? this.repeat(request) : this.learnOrPipe(request, outputBuffer); responsePromise.then(function(response) { console.log("\nResponding: ", response.status, response.type); if (!response.piped) { var responseString = typeof(response.data) === 'string' ? response.data : JSON.stringify(response.data); if (HeaderUtil.isText(response.type)) { console.log(responseString); } outputBuffer.writeHead(response.status, {'Content-Type': response.type}); outputBuffer.end(responseString); } }); }; /** * Callback that is called when the server recieves a request. */ Mockingjay.prototype.onRequest = function(request, response) { console.log("\n\033[1;32mRequest Recieved:\033[0m", request.url, request.method); var self = this; var simplifiedRequest = this.simplify(request); var corsHeaders = HeaderUtil.getCorsHeaders(); for (var corsHeader in corsHeaders) { response.setHeader(corsHeader, corsHeaders[corsHeader]); } request.on('data', function(data) { simplifiedRequest.body += data; }); request.on('end', function() { self.echo(simplifiedRequest, response); }); }; Mockingjay.prototype.simplify = function (req) { var self = this; var urlSplit = url.parse(this.options.serverBaseUrl + req.url); var isHttps = urlSplit.protocol === 'https:' var options = { hostname: urlSplit.hostname, port: parseInt(urlSplit.port) || (isHttps ? 443 : 80), path: urlSplit.path, body: '', method: req.method, headers: HeaderUtil.standardize(req.headers) }; return options; }; module.exports = Mockingjay
JavaScript
0
@@ -1755,32 +1755,8 @@ ) %7B%0A - console.log(request);%0A va
3adc27e2a5f97b579800bc324a091e99cb34cbe3
support to get last command through up key in terminal
packages/code/widget/widget_terminal.js
packages/code/widget/widget_terminal.js
/* @author Zakai Hamilton @component WidgetTerminal */ screens.widget.terminal = function WidgetTerminal(me) { me.element = { properties : __json__ }; me.sendInput = function (terminal, message, type) { var window = me.widget.window.get(terminal); var field = me.ui.element.create({ "ui.basic.tag": "input", "ui.class.class": "widget.terminal.field" }, window); terminal.field = field; me.core.property.set(terminal.var.inputLine, "ui.basic.text", ""); me.core.property.set(terminal.var.input, "ui.style.display", "block"); clearTimeout(terminal.cursorTimeout); terminal.cursorTimeout = null; me.core.property.set(terminal, "scroll"); if (message.length) { me.core.property.set(terminal.var.prefix, "ui.basic.text", message); } field.onblur = function () { me.core.property.set(terminal.var.cursor, "ui.style.display", "none"); clearTimeout(terminal.cursorTimeout); terminal.cursorTimeout = null; }; field.onfocus = function () { field.value = me.core.property.get(terminal.var.inputLine, "ui.basic.text"); me.core.property.set(terminal.var.cursor, "ui.style.display", "inline"); me.blinkCursor(terminal, field); }; window.onclick = function () { if (!terminal.cursorTimeout) { setTimeout(() => { field.focus(); }, 1500); } }; field.onkeydown = function (e) { if (e.which === 37 || e.which === 39 || e.which === 38 || e.which === 40 || e.which === 9) { e.preventDefault(); } else if (type === "input" && e.which !== 13) { setTimeout(function () { me.core.property.set(terminal.var.inputLine, "ui.basic.text", field.value); me.core.property.set(terminal, "scroll"); }, 1); } }; field.onkeyup = function (e) { if (e.which === 13) { me.core.property.set(terminal.var.input, "ui.style.display", "none"); if (type === "input") { me.core.property.set(terminal, "print", message + field.value); } me.core.property.set(field, "ui.node.parent"); me.core.property.set(terminal, terminal.response, field.value); } }; if (!terminal.running) { terminal.running = true; setTimeout(function () { field.focus(); }, 500); } else { field.focus(); } }; me.blinkCursor = function (terminal, field) { var cursor = terminal.var.cursor; terminal.cursorTimeout = setTimeout(function () { if (field.parentElement) { var visibility = me.core.property.get(cursor, "ui.style.visibility"); me.core.property.set(cursor, "ui.style.visibility", visibility === "visible" ? "hidden" : "visible"); me.blinkCursor(terminal, field); } else { me.core.property.set(cursor, "ui.style.visibility", "visible"); } }, 500); }; me.clear = { set: function (terminal) { me.core.property.set(terminal.var.output, "ui.basic.text", ""); } }; me.response = { set: function (terminal, response) { terminal.response = response; } }; me.insert = { set: function (terminal, message) { var print = me.ui.node.lastChild(terminal.var.output); if(print) { var text = me.core.property.get(print, "ui.basic.text"); text += message; me.core.property.set(print, "ui.basic.text", text); } else { var print = me.ui.element.create({ "ui.basic.tag": "div", "ui.basic.text": message }, terminal.var.output); } me.core.property.set(terminal, "scroll"); } }; me.print = { set: function (terminal, message) { var print = me.ui.element.create({ "ui.basic.tag": "div", "ui.basic.text": message }, terminal.var.output); me.core.property.set(terminal, "scroll"); } }; me.scroll = { set: function (terminal) { var container = me.ui.node.container(terminal, me.widget.container.id); container.scrollTop = container.scrollHeight; me.core.property.notify(container, "update"); } }; me.input = { set: function (terminal, message) { me.sendInput(terminal, message, "input"); } }; me.password = { set: function (terminal, message) { me.sendInput(terminal, message, "password"); } }; me.focus = { set: function (terminal) { if (terminal.field) { terminal.field.focus(); } } }; };
JavaScript
0
@@ -145,17 +145,16 @@ operties - : __json @@ -1671,26 +1671,8 @@ === - 38 %7C%7C e.which === 40 @@ -1736,24 +1736,335 @@ %7D + else if (e.which === 38) %7B%0A e.preventDefault();%0A if(terminal.lastCommand) %7B%0A me.core.property.set(terminal.var.inputLine, %22ui.basic.text%22, terminal.lastCommand);%0A field.value = terminal.lastCommand;%0A %7D%0A %7D%0A else if (ty @@ -2706,24 +2706,76 @@ e.parent%22);%0A + terminal.lastCommand = field.value;%0A @@ -4080,16 +4080,17 @@ if + (print) @@ -4309,36 +4309,24 @@ - var print = me.ui.eleme @@ -4619,36 +4619,24 @@ %0A - var print = me.ui.eleme
8a8f85ac2e6ff783d7e85ca265a4d2b5ac996545
Make sure that we are only processing messages that are of type request
src/request/repository/message-store-manage.js
src/request/repository/message-store-manage.js
'use strict'; var _ = require('lodash'); var glimpse = require('glimpse'); var processMessages = function(messages) { return { messages: messages, groupedById: _.groupBy(messages, 'context.id') }; }; // republish Found Summary (function () { function republishFoundSummary(messages) { var payload = processMessages(messages); glimpse.emit('data.message.summary.found', payload); } glimpse.on('data.message.summary.found.stream', republishFoundSummary); glimpse.on('data.message.summary.found.remote', republishFoundSummary); })(); // republish Found Details (function () { function republishFoundDetail(messages) { var payload = processMessages(messages); glimpse.emit('data.message.detail.found', payload); } glimpse.on('data.message.detail.found.stream', republishFoundDetail); glimpse.on('data.message.detail.found.remote', republishFoundDetail); })();
JavaScript
0
@@ -114,16 +114,160 @@ ges) %7B %0A + // NOTE: currently filtering out messages that aren't of type %22request%22%0A messages = _.filter(messages, 'context.type', 'request'); %0A %0A retu
b21b09b292dec9ed68c592aaba7faee7f218c2e8
Set default hook selector to `css`
src/model/Hook.js
src/model/Hook.js
var promises = require('q'); /** Mapping from short selector types to WebDriver's fully qualified selector types. * *@see <http://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/element> */ var WATAI_SELECTOR_TYPES_TO_WEBDRIVER_TYPES = { css : 'css selector', xpath : 'xpath', a : 'partial link text', linkText: 'link text', id : 'id', name : 'name', 'class' : 'class name', tag : 'tag name' } /**@class A Hook allows one to target a specific element on a web page. * It is a wrapper around both a selector and its type (css, xpath, id…). * *@param hook A single value-pair hash whose key may be one of `css`, `id`, or any other value of Selenium's `By` class; and whose value must be a string of the matching form. *@param driver The WebDriver instance in which the described elements are to be sought. */ var Hook = function Hook(hook, driver) { this.type = Object.getOwnPropertyNames(hook)[0]; this.selector = hook[this.type]; this.driver = driver; /** Returns the element this hook points to in the given driver, as an object with all WebDriver methods. * *@see http://seleniumhq.org/docs/03_webdriver.html *@private */ this.toSeleniumElement = function toSeleniumElement() { return this.driver.element(WATAI_SELECTOR_TYPES_TO_WEBDRIVER_TYPES[this.type], this.selector); } /** Sends the given sequence of keystrokes to the element pointed by this hook. * *@param input A string that will be sent to this element. *@returns {QPromise} A promise, resolved when keystrokes have been received, rejected in case of a failure. *@see http://seleniumhq.org/docs/03_webdriver.html#sendKeys *@private */ this.handleInput = function handleInput(input) { var element; return this.toSeleniumElement().then(function(elm) { element = elm; return elm.clear(); }).then(function() { return element.type(input); }).then(function() { return element; // allow easier chaining }); } } /** Adds a getter and a setter to the given Object, allowing access to the Selenium element corresponding to the given hook description. * The getter dynamically retrieves the Selenium element pointed at by the given selector description. * The setter will pass the value to the `Hook.handleInput` method. * *@param target The Object to which the getter and setter will be added. *@param key The name of the property to add to the target object. *@param typeAndSelector A hook descriptor, as defined in the Hook constructor. *@param driver The WebDriver instance in which the described elements are to be sought. * *@see Hook *@see Hook#handleInput */ Hook.addHook = function addHook(target, key, typeAndSelector, driver) { var hook = new Hook(typeAndSelector, driver); target.__defineGetter__(key, function() { target.emit('access', key); return hook.toSeleniumElement(hook); }); var inputHandler = function handleInputAndEmit(input) { target.emit('action', key, 'write', [ input ]); return hook.handleInput(input); } target.__defineSetter__(key, inputHandler); // legacy support; works when setting inputs without any need to wait (for example, fails on animated elements) var setterName = 'set' + key.capitalize(); if (! target[setterName]) { // do not overwrite possibly preexisting setters target[setterName] = function(input) { // wrapping to allow call-like syntax in scenarios return inputHandler.bind(null, input); } } } module.exports = Hook; // CommonJS export
JavaScript
0
@@ -427,16 +427,105 @@ ame'%0A%7D%0A%0A +/** Default Watai selector type%0A*%0A*@type%09%7BString%7D%0A*/%0Avar DEFAULT_SELECTOR_TYPE = 'css';%0A%0A /**@clas @@ -970,16 +970,122 @@ iver) %7B%0A +%0A%09if (typeof hook == 'string') %7B%0A%09%09this.type = DEFAULT_SELECTOR_TYPE;%0A%09%09this.selector = hook;%0A%09%7D%0A%09else %7B%0A%09 %09this.ty @@ -1124,18 +1124,18 @@ hook)%5B0%5D -; %0A +%09 %09this.se @@ -1159,16 +1159,19 @@ s.type%5D; +%0A%09%7D %0A%0A%09this.
46081846864bab71b3bbd93d8dd873358efc22c4
Update main.js
data/main.js
data/main.js
var sketchProc=function(processingInstance){ with (processingInstance){ setup = function() { //Setup var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; size(w*0.9,h*0.9); frameRate(60); test; test = loadImage("images/Bootleg2.png"); }; draw = function() { //background(255,250,250); image(test,0,0); }; }};
JavaScript
0.000001
@@ -427,16 +427,22 @@ dImage(%22 +/data/ images/B
bbf40d51f594bf86c65605b4ca70fbfca82b5cbd
Update macSay to use a queue and the new createClient
examples/macSay.js
examples/macSay.js
/* * A fun little BART talker, kinda like the ones on the platform. * Only works on a Mac! */ var exec = require('child_process').exec; var bart = require('../lib/bart'); var speechQueue = []; var say = function(estimates, voice){ //Build two statuses, one for the next train, and one for the one after it. var status1; if(estimates[0].minutes <= 0){ status1 = estimates[0].length + " car " + estimates[0].destination + " train now boarding platform " + estimates[0].platform; }else{ status1 = estimates[0].length + " car " + estimates[0].destination + " train in " + estimates[0].minutes + (estimates[0].minutes > 1 ? " minutes." : " minute."); } var status2; if(estimates[1].minutes <= 0){ status2 = estimates[1].length + " car " + estimates[1].destination + " train now boarding platform " + estimates[1].platform; }else{ status2 = estimates[1].length + " car " + estimates[1].destination + " train in " + estimates[1].minutes + (estimates[1].minutes > 1 ? " minutes." : " minute."); } //Spit out the status lines to the console console.log(status1); console.log(status2); console.log(); exec("say -v "+ voice + " " + status1, function(err, stdout, stderr){ exec("sleep 1", function(e, o, r){ exec("say -v "+ voice + " " + status2); }); }); } //Simulate the platform voices by adding an artificial delay via a queue. var sayInterval = setInterval(function(){ if(speechQueue.length > 0){ item = speechQueue.shift(); say(item.estimates, item.voice); } }, 10000); //Polling the queue every 10 seconds, approx how long it takes for one of the voices to say a message. bart.on('dbrk south', function(estimates){ speechQueue.push({"estimates":estimates, "voice":"Victoria"}); }); bart.on('dbrk north', function(estimates){ speechQueue.push({"estimates":estimates, "voice":"Bruce"}); }); bart.on('error', function(err){ console.error(err); }); console.log("BART talker is now running!");
JavaScript
0
@@ -163,16 +163,31 @@ b/bart') +.createClient() ;%0A%0Avar s @@ -1803,107 +1803,74 @@ -speechQueue.push(%7B%22estimates%22:estimates, %22voice%22:%22Victoria%22%7D);%0A%7D);%0A%0Abart.on('dbrk north', function( +// console.log(estimates)%0A foo = %5Bestimates%5B3%5D, estimates%5B4%5D, esti @@ -1870,26 +1870,28 @@ %5D, estimates -)%7B +%5B5%5D%5D %0A speechQ @@ -1913,25 +1913,19 @@ imates%22: -estimates +foo , %22voice @@ -1931,13 +1931,16 @@ e%22:%22 -Bruce +Victoria %22%7D);
2251e9be7acd7898671597252596ea68e3327412
_ is an allowed first character of mqlkeys
webapp/WEB-INF/js/mjt/src/freebase/mqlkey.js
webapp/WEB-INF/js/mjt/src/freebase/mqlkey.js
(function (mjt) { /** * * routines to quote and unquote javascript strings as valid mql keys * */ var mqlkey_start = 'A-Za-z0-9'; var mqlkey_char = 'A-Za-z0-9_-'; var MQLKEY_VALID = new RegExp('^[' + mqlkey_start + '][' + mqlkey_char + ']*$'); var MQLKEY_CHAR_MUSTQUOTE = new RegExp('([^' + mqlkey_char + '])', 'g'); /** * quote a unicode string to turn it into a valid mql /type/key/value * */ mjt.freebase.mqlkey_quote = function (s) { if (MQLKEY_VALID.exec(s)) // fastpath return s; var convert = function(a, b) { var hex = b.charCodeAt(0).toString(16).toUpperCase(); if (hex.length == 2) hex = '00' + hex; return '$' + hex; }; x = s.replace(MQLKEY_CHAR_MUSTQUOTE, convert); if (x.charAt(0) == '-' || x.charAt(0) == '_') { x = convert(x,x.charAt(0)) + x.substr(1); } // TESTING /* if (mjt.debug && mqlkey_unquote(x) !== s) { mjt.log('failed roundtrip mqlkey quote', s, x); } */ return x; } /** * unquote a /type/key/value string to a javascript string * */ mjt.freebase.mqlkey_unquote = function (x) { x = x.replace(/\$([0-9A-Fa-f]{4})/g, function (a,b) { return String.fromCharCode(parseInt(b, 16)); }); return x; } // convert a mql id to an id suitable for embedding in a url path. // UNTESTED // and DEPRECATED var mqlid_to_mqlurlid = function (id) { if (id.charAt(0) === '~') { return id; } if (id.charAt(0) === '#') { return '%23' + id.substr(1); } if (id.charAt(0) !== '/') { return 'BAD-ID'; } // requote components as keys and rejoin. var segs = id.split('/'); var keys = []; for (var i = 1; i < segs.length; i++) { var seg = segs[i]; // conservative uri encoding for now keys.push(encodeURIComponent(mqlkey_unquote(seg))); } // urlids do not have leading slashes!!! return '/'.join(keys); } })(mjt);
JavaScript
0.998455
@@ -784,30 +784,8 @@ '-' - %7C%7C x.charAt(0) == '_' ) %7B%0A
e02e8158859f2b0d07731f1d21fbbf454c94f831
Refactor Google Analytics logic
src/runtime/google-analytics-event-listener.js
src/runtime/google-analytics-event-listener.js
/** * Copyright 2021 The Subscribe with Google Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import {analyticsEventToGoogleAnalyticsEvent} from './event-type-mapping'; import {isFunction} from '../utils/types'; export class GoogleAnalyticsEventListener { /** * @param {!./deps.DepsDef} deps */ constructor(deps) { /** @private @const {!Window} */ this.win_ = deps.win(); /** @private @const {!./client-event-manager.ClientEventManager} */ this.eventManager_ = deps.eventManager(); } /** * Start listening to client events */ start() { this.eventManager_.registerEventListener( this.handleClientEvent_.bind(this) ); } /** * Listens for new events from the events manager and logs appropriate events to Google Analytics. * @param {!../api/client-event-manager-api.ClientEvent} event * @param {(!../api/client-event-manager-api.ClientEventParams|undefined)=} eventParams */ handleClientEvent_(event, eventParams = undefined) { // Bail immediately if neither ga function (analytics.js) nor gtag function (gtag.js) exists in Window. if ( typeof this.win_.ga !== 'function' && typeof this.win_.gtag !== 'function' ) { return; } let subscriptionFlow = ''; if (event.additionalParameters) { // additionalParameters isn't strongly typed so checking for both object and class notation. subscriptionFlow = event.additionalParameters.subscriptionFlow || event.additionalParameters.getSubscriptionFlow(); } let gaEvent = analyticsEventToGoogleAnalyticsEvent( event.eventType, subscriptionFlow ); if (!gaEvent) { return; } const analyticsParams = eventParams?.googleAnalyticsParameters || {}; gaEvent = { ...gaEvent, eventCategory: analyticsParams.event_category || gaEvent.eventCategory, eventLabel: analyticsParams.event_label || gaEvent.eventLabel, }; // TODO(b/234825847): Remove it once universal analytics is deprecated in 2023. const ga = this.win_.ga || null; if (isFunction(ga)) { ga('send', 'event', gaEvent); } const gtag = this.win_.gtag || null; if (isFunction(gtag)) { const gtagEvent = { 'event_category': gaEvent.eventCategory, 'event_label': gaEvent.eventLabel, 'non_interaction': gaEvent.nonInteraction, ...analyticsParams, }; gtag('event', gaEvent.eventAction, gtagEvent); } } /** * Function to determine whether event is eligible for GA logging. * @param {!./deps.DepsDef} deps * @returns {boolean} */ static isGaEligible(deps) { return isFunction(deps.win().ga || null); } /** * Function to determine whether event is eligible for gTag logging. * @param {!./deps.DepsDef} deps * @returns {boolean} */ static isGtagEligible(deps) { return isFunction(deps.win().gtag || null); } }
JavaScript
0.000934
@@ -754,16 +754,186 @@ ypes';%0A%0A +/** @typedef %7B?function(string, string, Object)%7D */%0Alet AnalyticsMethod;%0A%0A/** @typedef %7B%7Bga: AnalyticsMethod, gtag: AnalyticsMethod%7D%7D */%0Alet WindowWithAnalyticsMethods;%0A%0A export c @@ -1067,15 +1067,28 @@ t %7B! -Window%7D +./deps.DepsDef%7D deps */%0A @@ -1100,19 +1100,20 @@ his. -win +deps _ = deps .win @@ -1108,22 +1108,16 @@ _ = deps -.win() ;%0A%0A / @@ -1730,29 +1730,16 @@ // -Bail immediately if n +Require eith @@ -1768,17 +1768,16 @@ ics.js) -n or gtag @@ -1798,150 +1798,434 @@ .js) - exists in Window.%0A if (%0A typeof this.win_.ga !== 'function' &&%0A typeof this.win_.gtag !== 'function'%0A ) %7B%0A return; +.%0A const gaIsEligible = GoogleAnalyticsEventListener.isGaEligible(this.deps_);%0A const gtagIsEligible = GoogleAnalyticsEventListener.isGtagEligible(%0A this.deps_%0A );%0A const neitherIsEligible = !gaIsEligible && !gtagIsEligible;%0A if (neitherIsEligible) %7B%0A return;%0A %7D%0A%0A // Extract methods from window.%0A const %7Bga, gtag%7D = /** @type %7B!WindowWithAnalyticsMethods%7D */ (%0A this.deps_.win() %0A -%7D +);%0A %0A @@ -2941,24 +2941,25 @@ bel,%0A %7D;%0A +%0A // TODO( @@ -2979,18 +2979,20 @@ Remove -i t +his once un @@ -3040,175 +3040,93 @@ -const ga = this.win_.ga %7C%7C null;%0A if (isFunction(ga)) %7B%0A ga('send', 'event', gaEvent);%0A %7D%0A%0A const gtag = this.win_.gtag %7C%7C null;%0A if (isFunction(gtag) +if (gaIsEligible) %7B%0A ga('send', 'event', gaEvent);%0A %7D%0A%0A if (gtagIsEligible ) %7B%0A @@ -3579,32 +3579,83 @@ turn isFunction( +%0A /** @type %7B!WindowWithAnalyticsMethods%7D */ ( deps.win().ga %7C%7C @@ -3652,19 +3652,17 @@ in() +) .ga - %7C%7C null +%0A );%0A @@ -3861,16 +3861,67 @@ unction( +%0A /** @type %7B!WindowWithAnalyticsMethods%7D */ ( deps.win @@ -3926,21 +3926,19 @@ in() +) .gtag - %7C%7C null +%0A );%0A
dd3c409f7665fb9e812db288d66a5bf31e53ee70
update for reversed dpad on gear vr
webapp/folders/default/scripts/leadvsgold.js
webapp/folders/default/scripts/leadvsgold.js
function updateStats(num) { $.get(flaskServ + '/' + dbname + "/info/" + num, function (data) { splitinfo = data.split(':') $("#curfolder").html(splitinfo[0]); $("#curcreator").html(splitinfo[1]); $("#curindex").html(splitinfo[2]); $("#cursession").html(splitinfo[3]); $("#curremain").html(splitinfo[4]); $("#curdate").html(splitinfo[5]); }); } function changeImage(actionUrl, infoText, infoColor) { var numRand = Math.floor(Math.random() * 100001); $('#mainImg').off("load"); $('#mainImg').fadeTo(350, 0, function() { $('#mainImg').attr('src', flaskServ + '/' + dbname + actionUrl + numRand); }); $('#mainImg').load(function() { $('#mainImg').fadeTo(350, 1, function() { updateStats(numRand); }); // fade in new }); $('#actionbox').html('<p>' + infoText + '</p>'); // change infobox text $('#actionbox').css('background-color', infoColor); // change infobox color $('#actionbox').fadeTo(250, 0.7).delay(1000).fadeTo(250, 0); } var flaskServ = 'http:' + window.location.origin.split(':')[1] + ':5000'; $( document ).ready(function() { $(".floatbox").fadeTo(0,0); var numRand = Math.floor(Math.random() * 100001); updateStats(numRand); $('#mainImg').attr('src', flaskServ + '/' + dbname + '/image/' + numRand); $( ".ui-page" ).swipe( { swipeLeft:function(event, direction, distance, duration, fingerCount) { changeImage('/next/skip/', 'skipped', 'grey'); if (screenfull.enabled) { screenfull.request(); }; }, swipeUp:function(event, direction, distance, duration, fingerCount) { changeImage('/next/up/', upfolder, upcolor); if (screenfull.enabled) { screenfull.request(); }; }, swipeDown:function(event, direction, distance, duration, fingerCount) { changeImage('/next/down/', downfolder, downcolor); if (screenfull.enabled) { screenfull.request(); }; }, swipeRight:function(event, direction, distance, duration, fingerCount) { changeImage('/prev/', 'back', 'grey'); if (screenfull.enabled) { screenfull.request(); }; }, }); $( document ).keydown(function(e) { switch(e.which) { case 37: changeImage('/prev/', 'back', 'grey'); break; case 38: changeImage('/next/up/', upfolder, upcolor); break; case 39: changeImage('/next/skip/', 'skipped', 'grey'); break; case 40: changeImage('/next/down/', downfolder, downcolor); break; case 32: case 35: $.get(flaskServ + '/' + dbname + "/imgtap"); $('#tapbox').html('<p>' + tapfolder + '</p>'); $('#tapbox').css('background-color', tapcolor); $('#tapbox').fadeTo(250, 0.7).delay(1000).fadeTo(250, 0); default: return; } e.preventDefault(); }); $(".ui-page").dblclick(function() { $.get(flaskServ + '/' + dbname + "/imgtap"); $('#tapbox').html('<p>' + tapfolder + '</p>'); $('#tapbox').css('background-color', tapcolor); $('#tapbox').fadeTo(250, 0.7).delay(1000).fadeTo(250, 0); }); $(".cornerbox").click(function() { $.get(flaskServ + '/' + dbname + "/info/reset"); updateStats(78); }) });
JavaScript
0
@@ -428,40 +428,109 @@ ge(a -ctionUrl, infoText, infoColor) %7B +rgsobj) %7B%0A var actionUrl = argsobj%5B0%5D%0A var infoText = argsobj%5B1%5D%0A var infoColor = argsobj%5B2%5D %0A @@ -1214,16 +1214,706 @@ 5000';%0A%0A +upact = '/next/up/', upfolder, upcolor;%0Adownact = '/next/down/', downfolder, downcolor;%0Aleftact = '/next/skip/', 'skipped', 'grey';%0Arightact = '/prev/', 'back', 'grey';%0A%0A// the gear VR's touchpad is logically flipped from UDLR on a screen%0A// if we detect Samsung Internet, flip axes for input%0Aif ((navigator.userAgent.indexOf('SamsungBrowser') != -1)) %7B%0A upaction = downact;%0A downaction = upact;%0A leftaction = rightact;%0A rightaction = leftact;%0A // cataction = dogact;%0A // eastaction = westact;%0A // ukaction = anarchy;%0A console.log('detected Gear VR');%0A%7D%0Aelse %7B%0A upaction = upact;%0A downaction = downact;%0A leftaction = leftact;%0A rightaction = rightact;%0A%7D%0A%0A $( docum @@ -2265,40 +2265,18 @@ age( -'/next/skip/', 'skipped', 'grey' +leftaction );%0A @@ -2481,38 +2481,16 @@ age( -'/next/up/', upfolder, upcolor +upaction );%0A @@ -2697,44 +2697,18 @@ age( -'/next/down/', downfolder, downcolor +downaction );%0A @@ -2916,32 +2916,19 @@ age( -'/prev/', 'back', 'grey' +rightaction );%0A @@ -3154,32 +3154,19 @@ age( -'/prev/', 'back', 'grey' +rightaction );%0A @@ -3240,38 +3240,16 @@ age( -'/next/up/', upfolder, upcolor +upaction );%0A @@ -3323,40 +3323,18 @@ age( -'/next/skip/', 'skipped', 'grey' +leftaction );%0A @@ -3408,44 +3408,18 @@ age( -'/next/down/', downfolder, downcolor +downaction );%0A
3105606fda2e8abd112b2203c204d9fc286ebcda
add pregnancy form to calculate births recorded
mvp_apps/mvp_births/views/child_cases_by_status/map.js
mvp_apps/mvp_births/views/child_cases_by_status/map.js
function (doc) { // !code util/mvp.js if (isChildCase(doc)) { var indicator_entries_open = {}, indicator_entries_closed = {}, indicators_dob = []; var status = (doc.closed) ? "closed" : "open"; if (doc.dob || doc.dob_calc) { var dob_date = doc.dob_calc || doc.dob, weight_at_birth = doc.weight_at_birth, is_delivered = doc.delivered_in_facility === 'yes' || doc.delivered_in_facility === 'no', is_delivered_in_facility = doc.delivered_in_facility === 'yes', opened_on_date = new Date(doc.opened_on); if (is_delivered) { indicators_dob.push("dob delivered"); } if (is_delivered_in_facility) { indicators_dob.push("dob delivered_in_facility"); } indicator_entries_open["opened_on"] = dob_date; indicator_entries_open["opened_on "+status] = dob_date; if (weight_at_birth) { try { var weight = parseFloat(weight_at_birth); if (weight > 0) { indicator_entries_open["opened_on weight_recorded"] = dob_date; } if (weight < 2.5) { indicator_entries_open["opened_on low_birth_weight"] = dob_date; } } catch (e) { // pass } } emit_special(doc, opened_on_date, indicator_entries_open, [doc._id]); try { emit_standard(doc, new Date(dob_date), indicators_dob, [doc._id]); } catch (e) { // just in case the date parsing fails miserably. } if (doc.closed_on) { var closed_on_date = new Date(doc.closed_on); indicator_entries_closed["closed_on"] = dob_date; indicator_entries_closed["closed_on "+status] = dob_date; emit_special(doc, closed_on_date, indicator_entries_closed, [doc._id]); } } } }
JavaScript
0.000001
@@ -60,16 +60,54 @@ se(doc)) + %7C%7C%0A isPregnancyCloseForm(doc)) %7B%0A
5c21395958cf6393d9fc66c6b16a463163532179
Fix missing calculation
www/js/factories/DExOfferFactory.js
www/js/factories/DExOfferFactory.js
angular.module("omniFactories") .factory("DExOffer",["Address", "WHOLE_UNIT",function DExOfferFactory(Address, WHOLE_UNIT){ var DExOffer= function(data,propertydesired,propertyselling,side){ var self = this; self.initialize = function(){ data = data || {}; self.rawdata = data; self.propertyselling = propertyselling; self.propertydesired = propertydesired; self.available_amount = propertyselling.divisible ? new Big(data.available_amount).times(WHOLE_UNIT) : new Big(data.available_amount); self.selling_amount = propertyselling.divisible ? new Big(data.total_amount).times(WHOLE_UNIT) : new Big(data.total_amount); self.desired_amount = propertydesired.divisible ? new Big(data.desired_amount).times(WHOLE_UNIT) : new Big(data.desired_amount); if(side == "ask"){ } else { self.price = self.selling_amount.div(self.desired_amount); } }; self.initialize(); } return DExOffer; }]);
JavaScript
0.999809
@@ -807,16 +807,74 @@ )%7B%0A%09%09%09%09%09 +self.price = self.desired_amount.div(self.selling_amount); %0A%09%09%09%09%7D e
8bf230745c060c6be38466bab46605335581b980
Update rules (#4)
packages/eslint-config-transit/index.js
packages/eslint-config-transit/index.js
'use strict'; module.exports = { extends: 'airbnb-base', parserOptions: { ecmaVersion: 2017, ecmaFeatures: {}, sourceType: 'script', }, rules: { 'no-param-reassign': 'off', 'no-use-before-define': 'off', 'no-continue': 'off', 'radix': 'off', 'max-len': ['error', 120, 2], 'quote-props': ['error', 'consistent'], 'no-restricted-syntax': [ 'error', 'ForInStatement', 'LabeledStatement', 'WithStatement', ], 'comma-dangle': ['error', { arrays: 'always-multiline', objects: 'always-multiline', imports: 'always-multiline', exports: 'always-multiline', functions: 'ignore', }], }, };
JavaScript
0
@@ -681,16 +681,53 @@ %7D%5D,%0A + 'class-methods-use-this': 'off',%0A %7D,%0A%7D;%0A
830bfb248ed78f2df1a19e8b68c8a5cd93ca474f
Make examples/sensor.js more generic
examples/sensor.js
examples/sensor.js
var arduino = require('../'), board, ldr; board = new arduino.Board({ debug: true }); ldr = new arduino.Sensor({ board: board, pin: 'A0' }); ldr.on('read', function(value) { // |value| is reading of the light dependent resistor console.log(value); }); // Tested with: // SoftPot // http://www.spectrasymbol.com/how-it-works-softpot // http://www.sparkfun.com/datasheets/Sensors/Flex/SoftPot-Datasheet.pdf // // LDR // http://www.ladyada.net/learn/sensors/cds.html
JavaScript
0
@@ -34,18 +34,21 @@ board, -ld +senso r;%0A%0Aboar @@ -90,18 +90,21 @@ ue%0A%7D);%0A%0A -ld +senso r = new @@ -157,10 +157,13 @@ );%0A%0A -ld +senso r.on @@ -180,16 +180,21 @@ unction( +err, value) %7B @@ -194,16 +194,33 @@ alue) %7B%0A + value = +value; %0A // %7Cv @@ -228,16 +228,24 @@ lue%7C is +current reading @@ -251,34 +251,12 @@ of -the light dependent resist +sens or%0A @@ -446,11 +446,14 @@ %0A// -LDR +sensor %0A//
1e35f8fbbcdfe380dd77d6d7be6966c742699c8f
Add fn to shorten quarter name
myuw/static/vue/mixins/utils.js
myuw/static/vue/mixins/utils.js
import dayjs from 'dayjs'; export default { methods: { encodeForMaps(s) { if (s) { s = s.replace(/ \(/g, " - "); s = s.replace(/[\)&]/g, ""); s = encodeURIComponent(s); } return s; }, // Phone Number Utils parsePhoneNumber(phNumStr) { let parsed = null; if (phNumStr) { let matches = phNumStr.match(/^(\+(?<country>\d+) )?(?<area>\d{3})[ -\.]?(?<exchange>\d{3})[ -\.]?(?<line>\d{4})$/); if (matches) { parsed = matches.groups; } } return parsed; }, formatPhoneNumberDisaply(phNumStr) { let parsed = this.parsePhoneNumber(phNumStr); if (parsed) { return `(${parsed.area}) ${parsed.exchange}-${parsed.line}`; } return ""; }, formatPhoneNumberLink(phNumStr) { let parsed = this.parsePhoneNumber(phNumStr); if (parsed) { if (parsed.country == undefined) parsed.country = "1"; return `+${parsed.country}-${parsed.area}-${parsed.exchange}-${parsed.line}`; } return ""; }, pageTitleFromTerm(termStr) { let pageTitle = termStr.split(','); let term = pageTitle[1]; pageTitle[1] = pageTitle[0]; pageTitle[0] = term; return pageTitle.map((s) => this.ucfirst(s)).join(' '); }, ucfirst(s) { if (s) { return s.replace(/^([a-z])/, (c) => c.toUpperCase()); } return ""; }, titleCaseName(nameStr) { return nameStr.split(' ').map(function(w) { return w[0].toUpperCase() + w.substr(1).toLowerCase(); }).join(' '); }, toFriendlyDate(date_str) { return (!date_str || date_str.length === 0 ? '' : dayjs(date_str).format("ddd, MMM D")); }, toFriendlyDatetime(date_str) { return (!date_str || date_str.length === 0 ? '' : dayjs(date_str).format("ddd, MMM D, h:mmA")); }, }, }
JavaScript
0.000002
@@ -1906,15 +1906,190 @@ %0A %7D,%0A + quarterAbbr(quarter_str) %7B%0A if (!quarter_str %7C%7C quarter_str.length === 0) %7B%0A return %22%22;%0A %7D%0A return quarter_str.substring(0, 3).toUpperCase();%0A %7D,%0A %7D,%0A%7D%0A
b39dc601b261fbe61b5d6a10b141f7e299a29256
Remove start button
src/MainMenu.js
src/MainMenu.js
/** * * The MainMenu state is used to display the games rules/instructions as well as providing a link to the terms and conditions of the game. * The main menu will provide a start button which upon being pressed will load the Story state. */ var menumusic; Game.MainMenu = function(game) { }; Game.MainMenu.prototype = { create:function(game){ menumusic = game.add.audio('menu_music'); menumusic.play('', 0, 0.5, true); game.Storage = this.game.plugins.add(Phaser.Plugin.Storage); game.Storage.initUnset('Highscore', 0); var highscore = game.Storage.get('Highscore') || 0; var buttonStart = this.add.button(230, this.world.height-380, 'button-start', this.clickStart, this, 1, 0, 2); buttonStart.anchor.set(0); }, clickStart: function() { //Game._playAudio('click'); menumusic.mute=true; this.camera.fade(0, 200, false); this.time.events.add(200, function() { this.state.start('Story'); }, this); } };
JavaScript
0.000004
@@ -353,623 +353,8 @@ e)%7B%0A - menumusic = game.add.audio('menu_music');%0A menumusic.play('', 0, 0.5, true);%0A%0A game.Storage = this.game.plugins.add(Phaser.Plugin.Storage);%0A%0A game.Storage.initUnset('Highscore', 0);%0A var highscore = game.Storage.get('Highscore') %7C%7C 0;%0A%0A var buttonStart = this.add.button(230, this.world.height-380, 'button-start', this.clickStart, this, 1, 0, 2);%0A buttonStart.anchor.set(0);%0A%0A %7D,%0A%0A clickStart: function() %7B%0A //Game._playAudio('click');%0A%09%09menumusic.mute=true;%0A this.camera.fade(0, 200, false);%0A this.time.events.add(200, function() %7B%0A @@ -388,26 +388,8 @@ ');%0A - %7D, this);%0A
7c3adf0d0235eabcf373d5112e3f4e17b6717fb4
Remove confirmation for manually unpinned tabs
Keep-my-Pinned-Tab/src/bg/background.js
Keep-my-Pinned-Tab/src/bg/background.js
chrome.tabs.onCreated.addListener( function(tab){ if(tab.pinned) { chrome.tabs.executeScript(tab.id, {file: "src/js/onbeforeunload.js"}); } } ); chrome.tabs.onUpdated.addListener( function(tabId, changeInfo, tab) { if(changeInfo && changeInfo.pinned) { chrome.tabs.executeScript(tabId, {file: "src/js/onbeforeunload.js"}); } } );
JavaScript
0
@@ -1,20 +1,37 @@ +pinedTabs = %7B%7D;%0A%0A chrome.tabs.onCreate @@ -36,35 +36,32 @@ ted.addListener( -%0A function(tab)%7B%0A @@ -59,18 +59,16 @@ n(tab)%7B%0A - if(tab @@ -72,32 +72,60 @@ tab.pinned) %7B%0A + pinedTabs%5Btab.id%5D = true;%0A chrome.tabs. @@ -143,38 +143,38 @@ pt(tab.id, %7B -fil +cod e: %22 -src/js/ +window. onbeforeunlo @@ -175,34 +175,76 @@ reunload -.js%22%7D);%0A %7D + = function(e) %7B return 'This is a pinned tab'; %7D;%22%7D); %0A %7D%0A +%7D );%0A%0Achro @@ -273,19 +273,16 @@ istener( -%0A function @@ -308,18 +308,16 @@ tab) %7B%0A - if(cha @@ -356,58 +356,480 @@ - chrome.tabs.executeScript(tabId, %7Bfile: %22src/js/ +// Check to see if the tab that got updates wasn't already pinned%0A if(!pinedTabs%5BtabId%5D)%7B%0A pinedTabs%5BtabId%5D = true;%0A chrome.tabs.executeScript(tabId, %7Bcode: %22window.onbeforeunload = function(e) %7B return 'This is a pinned tab'; %7D;%22%7D);%0A %7D%0A %7D else if (changeInfo && !changeInfo.pinned) %7B%0A // Check to see if the tab that got updates was pinned%0A if(pinedTabs%5BtabId%5D)%7B%0A delete pinedTabs%5BtabId%5D;%0A chrome.tabs.executeScript(tabId, %7Bcode: %22window. onbe @@ -842,11 +842,16 @@ load -.js + = null; %22%7D); @@ -861,11 +861,136 @@ %7D%0A %7D%0A +%7D);%0A%0Achrome.tabs.onRemoved.addListener(function(tabId, removeInfo)%7B%0A if(pinedTabs%5BtabId%5D)%7B%0A delete pinedTabs%5BtabId%5D;%0A %7D%0A%7D ); -%0A
4d20443f241d9b08360ba6772f968db363397601
make dewars server side pageable
client/js/collections/dewars.js
client/js/collections/dewars.js
define(['backbone.paginator', 'models/dewar', 'utils/kvcollection'], function(PagableCollection, Dewar, KVCollection) { return PagableCollection.extend(_.extend({}, KVCollection, { mode: 'client', model: Dewar, url: function() { return '/shipment/dewars'+(this.id ? '/sid/'+this.id : '')+(this.fc ? '/fc/'+this.fc : '') }, keyAttribute: 'CODE', valueAttribute: 'DEWARID', initialize: function(models, options) { if (options) { this.id = options.id this.fc = options.FACILITYCODE } }, })) })
JavaScript
0
@@ -117,16 +117,11 @@ ) %7B%0A +%0A - %0A re @@ -185,25 +185,34 @@ %7B%0A -%09 + mode: ' -client',%0A +server',%0A @@ -225,16 +225,20 @@ Dewar,%0A + url: @@ -351,17 +351,80 @@ ,%0A + %0A + state: %7B%0A pageSize: 15,%0A %7D,%0A%0A keyA @@ -445,16 +445,20 @@ E',%0A + + valueAtt @@ -477,16 +477,20 @@ ARID',%0A%0A + init @@ -533,16 +533,20 @@ + if (opti @@ -556,25 +556,32 @@ ) %7B%0A + -%09 + this.id = op @@ -597,17 +597,24 @@ + -%09 + this.fc @@ -645,18 +645,235 @@ -%09%7D%0A %7D, + %7D%0A %7D, %0A%0A parseState: function(r, q, state, options) %7B%0A return %7B totalRecords: r.total %7D%0A %7D,%0A %0A parseRecords: function(r, options) %7B%0A return r.data%0A %7D, @@ -880,10 +880,12 @@ %0A %7D))%0A +%0A %7D) +%0A
574317578b9e5a6299428e32c5a90b9a9b32c8f5
Rename reset to resetColorFg
bundleSize.js
bundleSize.js
const fs = require('fs'); const path = require('path'); const newDistPath = './dist'; const oldDistPath = './dist_old'; const getFileSizes = folderPath => { return fs.readdirSync(folderPath).reduce((res, fileName) => { res[fileName] = fs.readFileSync(path.join(folderPath, fileName)).byteLength; return res; }, {}); }; const oldValues = getFileSizes(oldDistPath); const newValues = getFileSizes(newDistPath); Object.entries(oldValues).forEach(([name, size]) => { const newSize = newValues[name]; const delta = newSize - size; const sizeColorFg = delta <= 0 ? '\x1b[32m' : '\x1b[31m'; const reset = '\x1b[0m'; const nameColorFg = '\x1b[36m'; // eslint-disable-next-line no-console console.log( `${nameColorFg}%s${reset}%s${sizeColorFg}%s${reset}`, `${name}:`, ` ${size} B -> ${newSize} B `, `(${delta >= 0 ? '+' : ''}${delta} B)` ); });
JavaScript
0.000001
@@ -612,16 +612,23 @@ st reset +ColorFg = '%5Cx1b @@ -751,16 +751,23 @@ s$%7Breset +ColorFg %7D%25s$%7Bsiz @@ -784,16 +784,23 @@ s$%7Breset +ColorFg %7D%60,%0A
d6f0ace2239e0bc2e5ea9dd1e774985eed860c40
use optimizeForBuffers in example
examples/server.js
examples/server.js
var http = require('http'), dcache = require('../lib'), //dstore = require('distribucache-redis-store'), dstore = require('distribucache-memory-store'), cacheClient = dcache.createClient(dstore()), server, cache; cache = cacheClient.create('page', { staleIn: '5 sec', populate: generatePage }); server = http.createServer(function (req, res) { cache.get('home', function (err, page) { if (err) { res.writeHead(500); res.end(err.message); return; } res.writeHead(200); res.end(page); }); }); function generatePage(pageId, cb) { console.log('[page] generating...'); setTimeout(function () { cb(null, '<p>Hello world!</p>'); }, 5000); } server.listen(2000, function () { console.log('on :2000'); });
JavaScript
0
@@ -57,10 +57,8 @@ ,%0A -// dsto @@ -98,24 +98,26 @@ -store'),%0A +// dstore = req @@ -298,16 +298,44 @@ ratePage +,%0A optimizeForBuffers: true %0A%7D);%0A%0Ase @@ -684,16 +684,27 @@ b(null, +new Buffer( '%3Cp%3EHell @@ -721,17 +721,17 @@ p%3E') +) ;%0A %7D, -50 +3 00);
2ee060497e732b176e74d33e11a2d309076edf12
Disable button until loaded.
src/devilry_subjectadmin/devilry_subjectadmin/static/devilry_subjectadmin/app/view/period/ListOfRelatedUsers.js
src/devilry_subjectadmin/devilry_subjectadmin/static/devilry_subjectadmin/app/view/period/ListOfRelatedUsers.js
/** * Overview of relatated users on a period. */ Ext.define('devilry_subjectadmin.view.period.ListOfRelatedUsers' ,{ extend: 'Ext.container.Container', alias: 'widget.listofrelatedusers', requires: [ 'devilry_extjsextras.AlertMessageList', 'devilry_extjsextras.DjangoRestframeworkProxyErrorHandler' ], listTemplate: [ '<div class="bootstrap">', '<tpl if="users !== undefined">', '<tpl if="users.length == 0">', '<em>', gettext('None'), '</em>', '</tpl>', '<ul class="relateduserlist">', '<tpl if="users.length &gt; 0">', '<tpl for="users">', '<li relateduserlistitem relateduserlistitem_{data.user.username}>', '{data.user.full_name}', '</li>', '</tpl>', '</tpl>', '</ul>', '</tpl>', '<tpl if="loading">', gettext('Loading ...'), '</tpl>', '</div>' ], /** * @cfg {String} css_suffix * The suffix to add to the css class with. */ /** * @cfg {String} title * The title of the list. */ /** * @cfg {String} buttonText * The text of the "manage" button */ initComponent: function() { var cls = Ext.String.format('devilry_subjectadmin_listofrelatedusers devilry_subjectadmin_listofrelated_{0}', this.css_suffix); Ext.apply(this, { layout: 'border', cls: cls, height: 200, items: [{ xtype: 'panel', ui: 'lookslike-parawitheader-panel', title: this.title, region: 'center', autoScroll: true, items: [{ xtype: 'alertmessagelist' }, { xtype: 'box', itemId: 'userslist', tpl: this.listTemplate, data: { loading: true } }], dockedItems: [{ xtype: 'toolbar', dock: 'bottom', ui: 'footer', items: [{ xtype: 'button', itemId: 'manageButton', scale: 'medium', text: this.buttonText }] }] }] }); this.callParent(arguments); }, _getTplData: function(extra) { var data = { title: this.title }; Ext.apply(data, extra); return data; }, setUserRecords: function(records) { this.down('#userslist').update({ users: records }); }, setFailedToLoad: function(operation) { this.down('#userslist').update({}); var error = Ext.create('devilry_extjsextras.DjangoRestframeworkProxyErrorHandler', operation); error.addErrors(null, operation); this.down('alertmessagelist').addMany(error.errormessages, 'error'); } });
JavaScript
0
@@ -2486,24 +2486,64 @@ : 'medium',%0A + disabled: true,%0A @@ -2963,24 +2963,62 @@ %7D);%0A + this.down('button').enable();%0A %7D,%0A%0A
6fe12c4d7ccc125776b8982a713f4b5a06d045e6
Add scrollMeIntoView JavaScript helper
app/assets/javascripts/ax_window.js
app/assets/javascripts/ax_window.js
Ax.Window = { make: function(url, options) { var window = $.extend({}, Ax.Window.Methods); window.url = url; window.options = options || {}; return window; }, loadFunction: function(target) { target.find("a.popup").click(function() { var link = $(this); var content = link.attr("popup_content"); var url = link.attr("href"); var options = {}; var popup_options = link.attr("popup_options"); if (popup_options) options = $.parseJSON(popup_options); if (content) Ax.Window.launchContent(content, options); else Ax.Window.launch(url, options); return false; } ); } }; Ax.Window.Methods = { _doAjax: function(ajax_options) { ajax_options = ajax_options || {}; var dialog = this.dialog; var error_or_success = function(data) { dialog.html(data.responseText); Ax.loadFunction(dialog); }; var error_handler = error_or_success; var success_handler = error_or_success; if (ajax_options.dataType === "text") { success_handler = function(data) { dialog.html(data); Ax.loadFunction(dialog) }; } $.ajax($.extend({}, { url: this.url, dataType: 'json', success: success_handler, error: error_handler, complete: function() { dialog.dialog("cleanUp"); } }, ajax_options)); } }; Ax.Window.ClassMethods = { defaultEffect: { effect: "fade", duration: 1000 }, _defaultOptions: { modal: true, width: 'auto', autoResize: true, close: function() { $(this).dialog('destroy').remove(); } }, defaultOptions: function() { return $.extend({ maxWidth: $(window).width() - 50, maxHeight: $(window).height() - 50, show: this.defaultEffect, hide: this.defaultEffect }, this._defaultOptions); }, launch: function(url, options) { options = $.extend({}, this.defaultOptions(), options); var window = this.make(url, options); var dialog = $("<div>"); window.dialog = dialog; dialog.html(Ax.loadingP()); if (window._prepDialog) window._prepDialog(); dialog.dialog(options); window._doAjax(options.ajax_options); return window; }, launchContent: function(content, options) { if (!options) { options = {}; } options = $.extend({}, this.defaultOptions(), options); var dialog = $("<div>"); dialog.dialog(options); dialog.html(content); dialog.dialog("cleanUp"); return dialog; } }; $.extend(Ax.Window, Ax.Window.ClassMethods); if ($.ui.dialog.prototype.cleanUp || $.ui.dialog.cleanUp) throw new Error("cleanUp already exists for some reason"); $.ui.dialog.prototype.cleanUp = function() { var dialog = this.element; var widget = dialog.dialog("widget"); var mw = dialog.dialog("option", "maxWidth"); var mh = dialog.dialog("option", "maxHeight"); if (widget.width() > mw) dialog.dialog("option", "width", mw); if (widget.height() > mh) dialog.dialog("option", "height", mh); dialog.dialog("option", "position", "center"); return dialog; }; $(function() { Ax.Window.loadFunction($("body")); Ax.registerLoadable(Ax.Window); });
JavaScript
0
@@ -668,16 +668,559 @@ %7D%0A ); +%0A%0A $.fn.scrollMeIntoView = function () %7B%0A var $container = this.scrollParent(),%0A containerTop = $container.offset().top,%0A containerBottom = containerTop + $container.height(),%0A elemTop = this.offset().top,%0A elemBottom = elemTop + this.height();%0A%0A // if (elemTop %3C containerTop) %7B%0A $container.scrollTop(elemTop);%0A /* %7D else if (elemBottom %3E containerBottom) %7B%0A $container.scrollTop(elemBottom - $container.height());%0A %7D */%0A %7D %0A %7D%0A%7D;%0A
c5cd627df50e73e7b23a806a29b5a47adb068151
Fix syntax
assets/js/dpi.js
assets/js/dpi.js
var hashRegex = /^#(\d+)[x×](\d+)(@(\d*\.?\d+)["″])?|(\d*\.?\d+)["″]$/; var dppx = window.devicePixelRatio || (window.matchMedia && window.matchMedia("(min-resolution: 2dppx), (-webkit-min-device-pixel-ratio: 1.5),(-moz-min-device-pixel-ratio: 1.5),(min-device-pixel-ratio: 1.5)").matches? 2 : 1) || 1; width.value = screen.width * dppx; height.value = screen.height * dppx; var output = $('output'); function calcDpi(w, h, d, opt) { // Calculate PPI/DPI w > 0 || (w = 1); h > 0 || (h = 1); opt || (opt = 'd'); var dpi = (opt == 'd' ? Math.sqrt(w * w + h * h) : opt == 'w' ? w : h) / d; return dp i >0 ? Math.round(dpi) : 0; } function update() { var w = width.value, h = height.value; result.textContent = calcDpi(w, h, physical.value, dimension.value); // Size the output to have the same aspect ratio as the screen var ratio = w / h; output.style.minWidth = result.parentNode.offsetWidth + 'px'; output.style.width = ratio > 1 ? '' : '10em'; output.style.height = output.offsetWidth / ratio + 'px'; } dimension.onchange = update; $$('fieldset input').forEach(function(element) { (element.oninput = function () { this.style.width = this.value.length * .7 + 'em'; this.style.width = this.value.length + 'ch'; update(); }).call(element); }); $$('#resolutions a, #diagonals a').forEach(function(a) { a.href = '#' + a.textContent; }); $u.xhr({ url: 'screens.json', callback: function (xhr) { window.Devices = JSON.parse(xhr.responseText); var fragment = document.createDocumentFragment(); Devices.forEach(function (device) { device.ppi || (device.ppi = calcDpi(device.w, device.h, device.d)); }); window.Devices = Devices.sort(function (device1, device2) { return (device2.ppi - device1.ppi); }); Devices.forEach(function (device) { deviceRow(device, fragment); }); var tbody = $('table tbody', devices); tbody.innerHTML = ''; tbody.appendChild(fragment); } }); function deviceRow(device, fragment) { return $u.element.create('tr', { contents: [ { tag: 'th', contents: { tag: 'a', properties: { href: '#' + device.w + '×' + device.h + '@' + device.d + '″' }, contents: device.name } }, { tag: 'td', contents: device.d + '″' }, { tag: 'td', contents: device.w + '×' + device.h }, { tag: 'td', contents: device.ppi }, { tag: 'td', contents: device.dppx || '?' } ], inside: fragment }); } (window.onhashchange = function() { var hash = decodeURIComponent(location.hash); if (hashRegex.test(hash)) { var matches = hash.match(hashRegex); if (matches[1]) { width.value = matches[1] width.oninput(); } if (matches[2]) { height.value = matches[2]; height.oninput(); } if (matches[3] || matches[5]) { if (matches[3]) { physical.value = matches[4]; } if (matches[5]) { physical.value = matches[5]; } dimension.value = 'd'; physical.oninput(); } } })(); search.oninput = function() { if (!window.Devices) { return; } var term = this.value; var fragment = document.createDocumentFragment(), results = 0; Devices.forEach(function (device) { for (var i in device) { if ((device[i] + '').toLowerCase().indexOf(term.toLowerCase()) > -1) { deviceRow(device, fragment); results++; return; } } }); var tbody = $('table tbody', devices); tbody.innerHTML = results ? '' : '<tr><td colspan="4">No results</td></tr>'; tbody.appendChild(fragment); };
JavaScript
0.509732
@@ -613,12 +613,12 @@ n dp - i %3E + 0 ?
c3e969f11b9efa77ebc12b5595c0bbbf6b465df2
Fix usual breakpoints
src/components/core/breakpoints/getBreakpoint.js
src/components/core/breakpoints/getBreakpoint.js
import { window } from 'ssr-window'; export default function (breakpoints) { // Get breakpoint for window width if (!breakpoints) return undefined; let breakpoint = false; const points = Object.keys(breakpoints).map((point) => { if (typeof point === 'string' && point.startsWith('@')) { const minRatio = parseFloat(point.substr(1)); const value = window.innerHeight * minRatio; return { value, point }; } return point; }); points.sort((a, b) => parseInt(a.value, 10) - parseInt(b.value, 10)); for (let i = 0; i < points.length; i += 1) { const { point, value } = points[i]; if (value <= window.innerWidth) { breakpoint = point; } } return breakpoint || 'max'; }
JavaScript
0.998631
@@ -445,21 +445,39 @@ return -point +%7B value: point, point %7D ;%0A %7D);%0A
fcb554cc20bb98fd9ff1b944dac779242e5ffef0
Improve example server view helpers
examples/server.js
examples/server.js
'use strict'; // // Require some modules // var fs = require('fs'); var jade = require('jade'); var connect = require('connect'); var Mincer = require('..'); // // Get Mincer environment // var environment = require('./environment'); // // Create connect application // var app = connect(); // // Attach assets server // app.use('/assets/', Mincer.createServer(environment)); // // Prepare HTML layout for our dummy application // See `views/layout.jade` for example of `javascript` and `stylesheet` usage. // var view; try { view = fs.readFileSync(__dirname + '/views/layout.jade', 'utf8'); view = jade.compile(view); } catch (err) { console.error("Failed compile view: " + (err.message || err.toString())); process.exit(128); } // // Define some view helpers // var viewHelpers = {}; // returns a list of asset paths function find_asset_paths(logicalPath) { var asset = environment.findAsset(logicalPath), paths = []; if (!asset) { return null; } if ('production' !== process.env.NODE_ENV && asset.isCompiled) { asset.toArray().forEach(function (dep) { paths.push('/assets/' + dep.logicalPath + '?body=1'); }); } else { paths.push('/assets/' + asset.digestPath); } return paths; } viewHelpers.javascript = function javascript(logicalPath) { var paths = find_asset_paths(logicalPath); if (!paths) { // this will help us notify that given logicalPath is not found // without "breaking" view renderer return '<script type="application/javascript">alert("Javascript file ' + JSON.stringify(logicalPath).replace(/"/g, '\\"') + ' not found.")</script>'; } return paths.map(function (path) { return '<script type="application/javascript" src="' + path + '"></script>'; }).join('\n'); }; viewHelpers.stylesheet = function stylesheet(logicalPath) { var paths = find_asset_paths(logicalPath); if (!paths) { // this will help us notify that given logicalPath is not found // without "breaking" view renderer return '<script type="application/javascript">alert("Stylesheet file ' + JSON.stringify(logicalPath).replace(/"/g, '\\"') + ' not found.")</script>'; } return paths.map(function (path) { return '<link rel="stylesheet" type="text/css" href="' + path + '" />'; }).join('\n'); }; // // Attach some dummy handler, that simply renders layout // app.use(function (req, res, next) { // make sure our assets were compiled, so their `digestPath` // will be 100% correct, otherwise first request will produce // wrong digestPath. That's not a big deal, as assets will be // served anyway, but to keep everything correct, we use this // precompilation, which is similar to using manifest, but // without writing files on disk. // // See [[Base#precompile]] for details, environment.precompile(['app.js', 'app.css'], function (err) { if (err) { next(err); return; } res.end(view(viewHelpers)); }); }); // // Start listening // app.listen(3000, function (err) { if (err) { console.error("Failed start server: " + (err.message || err.toString())); process.exit(128); } console.info('Listening on localhost:3000'); });
JavaScript
0
@@ -66,24 +66,55 @@ uire('fs');%0A +var path = require('path');%0A var jade @@ -854,16 +854,199 @@ = %7B%7D;%0A%0A%0A +// dummy helper that injects extension%0Afunction rewrite_extension(source, ext) %7B%0A var source_ext = path.extname(source);%0A return (source_ext === ext) ? source : (source + ext);%0A%7D%0A%0A%0A // retur @@ -1099,32 +1099,37 @@ aths(logicalPath +, ext ) %7B%0A var asset @@ -1365,16 +1365,34 @@ ets/' + +rewrite_extension( dep.logi @@ -1398,16 +1398,17 @@ icalPath +) + '?bod @@ -1461,16 +1461,34 @@ ets/' + +rewrite_extension( asset.di @@ -1496,16 +1496,17 @@ estPath) +) ;%0A %7D%0A%0A @@ -1618,32 +1618,39 @@ aths(logicalPath +, '.js' );%0A%0A if (!paths @@ -2184,16 +2184,24 @@ icalPath +, '.css' );%0A%0A if
e59d133e4dab08a4fbe8d32588dbe8ec18d7776b
remove unused method (#2213)
BackofficeBundle/Resources/public/ecmascript/OpenOrchestra/Application/View/TrashItem/ContentRestoreModalView.js
BackofficeBundle/Resources/public/ecmascript/OpenOrchestra/Application/View/TrashItem/ContentRestoreModalView.js
import AbstractRestoreModalView from './AbstractRestoreModalView' import Content from '../../Model/Content/Content' import Application from '../../Application' /** * @class ContentRestoreModalView */ class ContentRestoreModalView extends AbstractRestoreModalView { /** * @private */ _getEditModelUrl() { new Content({id: this._model.get('entity_id') }).fetch({ success: (content) => { console.log(content); } }); } /** * @private */ _validRestoreAndEdit() { let content = new Content({id: this._model.get('entity_id') }); $.when( this._model.destroy(), content.fetch() ).done( () => { let url = Backbone.history.generateUrl('editContent', { contentTypeId: content.get('content_type'), contentId: content.get('content_id'), language: Application.getContext().user.language.contribution }); Backbone.history.navigate(url, true); this.hide(); }); } } export default ContentRestoreModalView;
JavaScript
0
@@ -295,237 +295,8 @@ w%0A%7B%0A - /**%0A * @private%0A */%0A _getEditModelUrl() %7B%0A new Content(%7Bid: this._model.get('entity_id') %7D).fetch(%7B%0A success: (content) =%3E %7B%0A console.log(content);%0A %7D%0A %7D);%0A %7D%0A%0A
3966a4ea0ce32b7c0c582dc49b035627542263be
move code around
node-modules-installer.js
node-modules-installer.js
'use strict'; var zlib = require('zlib'); var tar = require('tar'); var path = require('path'); var RegistryClient = require('./registry-client.js'); var TarballRepository = require('./tarball-repository.js'); module.exports = NodeModulesInstaller; function NodeModulesInstaller() { this.registryClient = new RegistryClient(); this.tarballRepository = new TarballRepository(); } NodeModulesInstaller.prototype.installModule = function installModule(prefix, moduleName, versionish, cb) { var self = this; self.registryClient.resolveVersionish( moduleName, versionish, onVersion ); function onVersion(err, tarball) { if (err) { return cb(err); } self.tarballRepository.fetchTarball(tarball, onTarball); } function onTarball(err, response) { if (err) { return cb(err); } var location = path.join(prefix, 'node_modules', moduleName); self.installTarballStream(response, location, onInstalled); } function onInstalled(err) { if (err) { return cb(err); } cb(null); } }; NodeModulesInstaller.prototype.installTarballStream = function installTarballStream(stream, location, cb) { stream .on('error', onError) .pipe(zlib.Unzip()) .on('error', onError) .pipe(tar.Extract({ type: 'Directory', path: location, strip: 1 })) .on('error', onError) .on('close', onClose); function onError(err) { cb(err); } function onClose() { cb(null); } };
JavaScript
0.000001
@@ -515,16 +515,333 @@ this;%0A%0A + self.unpackModule(prefix, moduleName, versionish, onUnpackaged);%0A%0A function onUnpackaged(err) %7B%0A if (err) %7B%0A return cb(err);%0A %7D%0A%0A cb(null);%0A %7D%0A%7D;%0A%0ANodeModulesInstaller.prototype.unpackModule =%0Afunction unpackModule(prefix, moduleName, versionish, cb) %7B%0A var self = this;%0A%0A self @@ -1320,134 +1320,10 @@ on, -onInstalled);%0A %7D%0A%0A function onInstalled(err) %7B%0A if (err) %7B%0A return cb(err);%0A %7D%0A%0A cb(null +cb );%0A
2b8c5256a217e9147ec5aa3b3b68d7fb369c3b66
throw new error when path is not defined in file store
src/adapter/store/file.js
src/adapter/store/file.js
'use strict'; import fs from 'fs'; import path from 'path'; /** * file store class */ export default class extends think.adapter.store { /** * init * @param {Object} config [] * @return {} [] */ init(config){ this.config = think.extend({ path: '' }, config); if(!think.isDir(config.path)){ think.mkdir(config.path); } } /** * get data * @param {String} key [] * @return {Promise} [] */ get(key){ let filepath = this.config.path + '/' + key; if(!think.isFile(filepath)){ return Promise.resolve(); } return think.promisify(fs.readFile, fs)(filepath, {encoding: 'utf8'}); } /** * set file content * @param {String} key [] * @param {String} content [] */ set(key, content){ let filepath = this.config.path + '/' + key; think.mkdir(path.dirname(filepath)); let fn = think.promisify(fs.writeFile, fs); return fn(filepath, content).then(() => { think.chmod(filepath); }); } /** * delete file * @param {String} key [] * @return {Promise} [] */ delete(key){ let filepath = this.config.path + '/' + key; if(!think.isFile(filepath)){ return Promise.resolve(); } return think.promisify(fs.unlink, fs)(filepath); } /** * get all files * @return {Promise} [] */ list(){ return Promise.resolve(think.getFiles(this.config.path)); } }
JavaScript
0.000001
@@ -295,16 +295,93 @@ nfig);%0A%0A + if(!config.path)%7B%0A throw new Error('path must be defined.');%0A %7D%0A%0A if(!
fc3b9ead01065ed2a3901211f0da2af2035ba596
Test 123
document/web/template.js
document/web/template.js
var template = []; // template object if(window.Ravel.isLoaded) { var _TEMPLATE = function( url ) { this.url = url; this.load = function( params ) { if (window.XMLHttpRequest) { ajax = new XMLHttpRequest() } if(typeof(params) == "object" ) { p = JSON.stringify(params).replace(/[\"\}\{]/g, ''); param = p.replace(/[\:]/g,"=").replace(/[\,]/g, "&"); ajax.open("GET", "document/web/template/" + this.url + "?" + param, false); ajax.setRequestHeader("Content-Type", "text/html; charset=UTF-8"); ajax.send(null); ajax_response = ajax.responseText; return ajax_response; } else { ajax.open("GET", "document/web/template/" + this.url, false); ajax.setRequestHeader("Content-Type", "text/html; charset=UTF-8"); ajax.send(); ajax_response = ajax.responseText; return ajax_response; } } return this; } }
JavaScript
0.000001
@@ -32,16 +32,20 @@ e object + 123 %0Aif(wind
4905ec521e81f56525dc884ad5a4c3a437b15310
Update example
examples/simple.js
examples/simple.js
"use strict"; const cursor = require('kittik-cursor').Cursor.create().resetTTY(); const Print = require('../lib/Print').default; const shape = require('kittik-shape-rectangle').default.create({ text: 'Good news, everybody!', x: 'center', background: 'white', width: '50%' }); new Print({ easing: 'inOutSine', duration: 5000 }).on('tick', shape => shape.render(cursor) && cursor.flush().eraseScreen()).animate(shape);
JavaScript
0.000001
@@ -52,14 +52,15 @@ r'). -Cursor +default .cre @@ -256,13 +256,39 @@ d: ' -white +yellow_1',%0A foreground: 'black ',%0A
68d558762eb083a68b2b85c9ae376ebcd34ec7b9
inserta arriba
client/route-card-view/index.js
client/route-card-view/index.js
var analytics = require('analytics'); var d3 = require('d3'); var convert = require('convert'); var Feedback = require('feedback-modal'); var mouseenter = require('mouseenter'); var mouseleave = require('mouseleave'); var Calculator = require('route-cost-calculator'); var RouteDirections = require('route-directions-table'); var RouteModal = require('route-modal'); var routeSummarySegments = require('route-summary-segments'); var routeResource = require('route-resource'); var session = require('session'); //var transitive = require('transitive'); var view = require('view'); var showMapView = require('map-view'); /** * Expose `View` */ var View = module.exports = view(require('./template.html'), function(view, model) { mouseenter(view.el, function() { var itineration = JSON.parse(localStorage.getItem('itineration')); console.log("obj itineration 1 ->", itineration.length); var element = []; for (var i=0; i<itineration.length;i++) { var r3 = d3.selectAll(".iteration-"+i); if (i!=model.index){ r3.style("opacity", 1) .transition().duration(500).style("opacity", 0); r3.attr("color","#ffffff"); }else { r3.attr("color","#000000"); } } d3.selectAll(".iteration-200").each(function(e){ var element = d3.select(this); var parent = element.node().parentNode; if (element.attr("color") == "#000000") { d3.select(parent).attr("class", "estaes"); d3.select(parent).attr("color", "#000000"); }else { d3.select(parent).attr("class", "estaes"); d3.select(parent).attr("color", "#ffffff"); } }); d3.selectAll(".estaes")[0].sort(function(a,b){ if(d3.select(a).attr("color") == "#000000") { return 1; }else { return -1; } }); /* showMapView.cleanPolyline(); showMapView.cleanMarkerpoint(); showMapView.cleanMarkerCollision(); showMapView.marker_collision_group = []; var sesion_plan = JSON.parse(localStorage.getItem('dataplan')); sesion_plan = sesion_plan.plan; var index_ = model.index; var stroke; var itineraries = sesion_plan.itineraries; for (var i= 0; i < itineraries.length; i++) { if (i != index_){ stroke = {'stroke':true, 'class_name':true} }else{ stroke = {'stroke':false, 'class_name':false} } for (var j=0; j < itineraries[i].legs.length; j++) { showMapView.drawRouteAmigo(itineraries[i].legs[j], itineraries[i].legs[j].mode, stroke); } } showMapView.drawMakerCollision(); */ }); mouseleave(view.el, function() { var itineration = JSON.parse(localStorage.getItem('itineration')); console.log("obj itineration 2->", itineration.length); for (var i=0; i<itineration.length;i++) { if (i!=model.index){ d3.selectAll(".iteration-"+i) .style("opacity", 0) .transition().duration(500).style("opacity", 1); } } }); }); View.prototype.calculator = function() { return new Calculator(this.model); }; View.prototype.directions = function() { return new RouteDirections(this.model); }; View.prototype.segments = function() { return routeSummarySegments(this.model); }; View.prototype.costSavings = function() { return convert.roundNumberToString(this.model.costSavings()); }; View.prototype.timeSavingsAndNoCostSavings = function() { return this.model.timeSavings() && !this.model.costSavings(); }; /** * Show/hide */ View.prototype.showDetails = function(e) { e.preventDefault(); var el = this.el; var expanded = document.querySelector('.option.expanded'); if (expanded) expanded.classList.remove('expanded'); el.classList.add('expanded'); analytics.track('Expanded Route Details', { plan: session.plan().generateQuery(), route: { modes: this.model.modes(), summary: this.model.summary() } }); var scrollable = document.querySelector('.scrollable'); scrollable.scrollTop = el.offsetTop - 52; }; View.prototype.hideDetails = function(e) { e.preventDefault(); var list = this.el.classList; if (list.contains('expanded')) { list.remove('expanded'); } }; /** * Get the option number for display purposes (1-based) */ View.prototype.optionNumber = function() { return this.model.index + 1; }; /** * View */ View.prototype.feedback = function(e) { e.preventDefault(); Feedback(this.model).show(); }; /** * Select this option */ View.prototype.selectOption = function() { var route = this.model; var plan = session.plan(); var tags = route.tags(plan); analytics.send_ga({ category: 'route-card', action: 'select route', label: JSON.stringify(tags), value: 1 }); routeResource.findByTags(tags, function(err, resources) { var routeModal = new RouteModal(route, null, { context: 'route-card', resources: resources }); routeModal.show(); routeModal.on('next', function() { routeModal.hide(); }); }); };
JavaScript
0.000007
@@ -1841,11 +1841,8 @@ -if( d3.s @@ -1867,109 +1867,42 @@ or%22) - == %22#000000%22) %7B%0A return 1;%0A %7Delse %7B%0A return -1;%0A %7D +.node().parentNode.appendChild(a); %0A
661507e9034296d4592b445601218db2f8ac70db
Update kajmanekTrpaslici.child.js
components/animals/kajmanekTrpaslici.child.js
components/animals/kajmanekTrpaslici.child.js
import React, { Component } from 'react'; import { Text } from 'react-native'; import styles from '../../styles/styles'; import InPageImage from '../inPageImage'; import AnimalText from '../animalText'; import AnimalTemplate from '../animalTemplate'; const IMAGES = [ require('../../images/animals/kajmanekTrpaslici/01.jpg'), require('../../images/animals/kajmanekTrpaslici/02.jpg'), require('../../images/animals/kajmanekTrpaslici/03.jpg'), ]; const THUMBNAILS = [ require('../../images/animals/kajmanekTrpaslici/01-thumb.jpg'), require('../../images/animals/kajmanekTrpaslici/02-thumb.jpg'), require('../../images/animals/kajmanekTrpaslici/03-thumb.jpg'), ]; var AnimalDetail = React.createClass({ render() { return ( <AnimalTemplate firstIndex={[0]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator}> <AnimalText> Vážení a milí, vítám vás u&nbsp;terária kajmánků trpasličích. Jestli si myslíte, že před vámi budou proskakovat obručemi, musím vás zklamat. Když totiž tihle plazi zjistili, jak moc je návštěvníci obdivují, samou radostí strnuli. </AnimalText> <AnimalText> Vypadají skoro jako exponáty v&nbsp;muzeu, viďte? Pojďte si je prohlédnout trochu lépe. Nejprve se podívejte na jejich velikost. Kajmánci trpasličí svojí délkou obyčejně nepřekročí ani 150&nbsp;cm, což z&nbsp;nich dělá jeden z&nbsp;nejmenších druhů krokodýlů. </AnimalText> <InPageImage indexes={[1]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator} /> <AnimalText> Dále se zaměřte na typické rysy kajmánků, kterými jsou hnědé oční duhovky a zkostnatělá oční víčka, jimž podobná nalezli archeologové jen u&nbsp;některých dinosaurů. Krokodýli kdysi opravdu obývali planetu současně s&nbsp;dinosaury, a proto se jim někdy říká živoucí fosilie. Kajmánci mají dokonce ve svém latinském názvu slovo <Text style={styles.italic}>paleosuchus</Text>, které znamená něco jako prastarý krokodýl. </AnimalText> <AnimalText> Stále zoufáte, že se kajmánci moc nehýbou? Buďte rádi, že máte příležitost je vůbec vidět. V&nbsp;rodné Jižní Americe se často schovávají do podzemních doupat v&nbsp;okolí zalesněných řek a jezer. Sotva byste našli jiný druh krokodýla, který by se tak rád zdržoval jinde než ve vodě. </AnimalText> <InPageImage indexes={[2]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator} /> <AnimalText> Prohlídka terária se pomalu chýlí ke konci. Nezbývá než konstatovat, že přes všechny spojitosti s&nbsp;dinosaury nejsou kajmánci žádné vykopávky. Chovat doma je mohou jen ti nejotrlejší. Na zádech i&nbsp;ocasu se kajmánci vyzbrojili kostěnými šupinami. Když se rozhodnou zaútočit, dost to bolí. Kořist, jíž jsou většinou ryby, polykají celou nebo po velkých kusech. Možná se teď ptáte, proč tady v&nbsp;zoo nesežerou kajmánci piraně, které s&nbsp;nimi sdílí terárium. Odpověď je jednoduchá – piraně jsou moc velké, mrštné a kajmánci pravidelně dostávají o&nbsp;dost lepší pochutiny. </AnimalText> </AnimalTemplate> ); } }); module.exports = AnimalDetail;
JavaScript
0.000001
@@ -2659,16 +2659,16 @@ vat +je doma -je moho
f54c0b9ae3888013cf458fe36d7192670d87c78a
fix some css conflicts with boostrap
client/src/components/Header.js
client/src/components/Header.js
import React, { Component } from 'react' import styled from 'styled-components' import logo from '../res/hacker_news_logo.jpg' class Header extends Component { render() { return ( <Nav className="navbar navbar-default"> <div className="container"> <NavBrand className="navbar-brand text-uppercase navbar-link" href="/" > <img src={logo} alt="logo" /> Hacker News </NavBrand> <NavToggle className="navbar-toggle collapsed" data-toggle="collapse" data-target="#navcol-1" > <span className="sr-only">Toggle navigation</span> <IconBar className="icon-bar" /> <IconBar className="icon-bar" /> <IconBar className="icon-bar" /> </NavToggle> <NavCollapsed className="collapse navbar-collapse" id="navcol-1"> <p className="navbar-text navbar-right"> <Action className="navbar-link" href="http://localhost:4000/logout" > Log out </Action> </p> </NavCollapsed> </div> </Nav> ) } } // styles =========== const Nav = styled.nav` background: #324659; padding-top: 10px; padding-bottom: 10px; color: #d0d8e1; border-radius: 0; box-shadow: none; border: none; margin-bottom: 0; ` const NavToggle = styled.button`border: none;` const IconBar = styled.span` background-color: red; :hover, :focus { background: none; } ` const NavCollapsed = styled.div`border-top-color: #3d5368;` const Action = styled.a` margin-right: 7px; text-decoration: none; color: #d0d8e1; ` const NavBrand = styled.a` font-weight: bold; color: inherit; :hover { color: #b4b8be; } > img { height: 100%; display: inline-block; margin-right: 10px; width: auto; } ` // ================== export default Header
JavaScript
0.000002
@@ -283,16 +283,57 @@ avBrand%0A + style=%7B%7B color: '#d0d8e1' %7D%7D%0A @@ -378,20 +378,8 @@ case - navbar-link %22%0A @@ -1377,34 +1377,16 @@ : 10px;%0A - color: #d0d8e1;%0A border @@ -1488,16 +1488,19 @@ .button%60 +%0A border: @@ -1504,16 +1504,76 @@ r: none; +%0A%0A :hover,%0A :focus %7B%0A background: none !important;%0A %7D%0A %60%0A%0Aconst @@ -1595,19 +1595,16 @@ ed.span%60 -%0A backgrou @@ -1617,61 +1617,27 @@ or: -red;%0A%0A :hover,%0A :focus %7B%0A background: none;%0A %7D%0A +#d0d8e1 !important; %60%0A%0Ac @@ -1783,16 +1783,27 @@ #d0d8e1 + !important ;%0A%60%0A%0Acon @@ -1895,16 +1895,27 @@ #b4b8be + !important ;%0A %7D%0A%0A
9a3c9c36ccd2c3e37fabfe0fd576c9670a90de9d
test update
src/api/__tests__/args.js
src/api/__tests__/args.js
import { getArg, getArgs, getEnvironmentVariables, getEnvironmentVariable, getRemainingVariables, getRemainingOptions, flattenOptions, } from '../args'; describe('args test', () => { test('it should return correct arg', () => { process.argv = ['node', '-e', 'MONGO_URL=mongodb://127.0.0.1:27017', '--deps', 'imagemagick']; const arg = getArg('deps'); expect(arg).toBe('imagemagick'); }); test('it should return all default args', () => { process.argv = ['node', '-e', 'MONGO_URL=mongodb://127.0.0.1:27017', '--deps', 'imagemagick']; const args = getArgs(); expect(args).toEqual({ $0: '-e', _: ['node'], help: false, version: false, deps: 'imagemagick', e: 'MONGO_URL=mongodb://127.0.0.1:27017', }); }); test('it should return all args when passed an argv', () => { const args = getArgs([ 'node', '-e', 'MONGO_URL=mongodb://127.0.0.1:27017', '--deps', 'imagemagick', '--public', ]); expect(args).toEqual({ $0: '-e', _: ['node'], help: false, version: false, deps: 'imagemagick', e: 'MONGO_URL=mongodb://127.0.0.1:27017', public: true, }); }); test('it should return correct number of environment variables', () => { process.argv = [ 'node', '-e', 'MONGO_URL=mongodb://127.0.0.1:27017', '-e', 'ROOT_URL=http://localhost:3000', '--deps', 'abc', ]; const environmentVariables = getEnvironmentVariables(); expect(environmentVariables.length).toBe(2); }); test('it should return all environment variables', () => { process.argv = [ 'node', '-e', 'MONGO_URL=mongodb://127.0.0.1:27017', '-e', 'ROOT_URL=http://localhost:3000', '--deps', 'abc', ]; const environmentVariables = getEnvironmentVariables(); expect(environmentVariables).toEqual([ { name: 'MONGO_URL', value: 'mongodb://127.0.0.1:27017' }, { name: 'ROOT_URL', value: 'http://localhost:3000' }, ]); }); test('it should return a environment variable by name', () => { process.argv = [ 'node', '-e', 'MONGO_URL=mongodb://127.0.0.1:27017', '-e', 'ROOT_URL=http://localhost:3000', '--deps', 'abc', ]; const environmentVariables = getEnvironmentVariable('ROOT_URL'); expect(environmentVariables).toBe('http://localhost:3000'); }); test('it should return all custom environment variables', () => { process.argv = [ 'node', '-e', 'MONGO_URL=mongodb://127.0.0.1:27017', '-e', 'ROOT_URL=http://localhost:3000', '-e', 'MY_SPECIAL_VAR=cats', '-e', 'SECRET=litter', '--deps', 'abc', ]; const remainingVariables = getRemainingVariables(); expect(remainingVariables).toEqual([['-e', 'MY_SPECIAL_VAR=cats'], ['-e', 'SECRET=litter']]); }); test('it should return all custom options', () => { process.argv = [ 'node', '-e', 'MONGO_URL=mongodb://127.0.0.1:27017', '-e', 'ROOT_URL=http://localhost:3000', '-e', 'MY_SPECIAL_VAR=cats', '-e', 'SECRET=litter', '--deps', 'abc', '--public', '--alias', 'abc.com', ]; const remainingOptions = getRemainingOptions(); expect(remainingOptions).toEqual([['--public'], ['--alias', 'abc.com']]); }); test('it should correctly flatten options', () => { const flattenedOptions = flattenOptions([ '--public', ['-e', 'MONGO_URL=mongodb://127.0.0.1:27017'], ['--alias', 'abc.com'], ]); expect(flattenedOptions).toEqual([ '--public', '-e', 'MONGO_URL=mongodb://127.0.0.1:27017', '--alias', 'abc.com', ]); }); });
JavaScript
0.000001
@@ -3819,12 +3819,498 @@ ;%0A %7D);%0A +%0A%0A test('it should ignore certain flags', () =%3E %7B%0A process.argv = %5B%0A 'node',%0A '-e',%0A 'MONGO_URL=mongodb://127.0.0.1:27017',%0A '-e',%0A 'ROOT_URL=http://localhost:3000',%0A '-e',%0A 'MY_SPECIAL_VAR=cats',%0A '-e',%0A 'SECRET=litter',%0A '--deps',%0A 'abc',%0A '--nosplit',%0A %5D;%0A const remainingVariables = getRemainingVariables();%0A expect(remainingVariables).toEqual(%5B%5B'-e', 'MY_SPECIAL_VAR=cats'%5D, %5B'-e', 'SECRET=litter'%5D%5D);%0A %7D);%0A %7D);%0A
660c8f63c95bbd2570d519fee661a548f17b4ced
Increase z-index topbar
client/src/components/TopBar.js
client/src/components/TopBar.js
import { resetPages } from "actions" import AppContext from "components/AppContext" import GeneralBanner from "components/GeneralBanner" import Header from "components/Header" import NoPositionBanner from "components/NoPositionBanner" import SecurityBanner from "components/SecurityBanner" import { Person } from "models" import PropTypes from "prop-types" import React, { Component } from "react" import { connect } from "react-redux" const GENERAL_BANNER_LEVEL = "GENERAL_BANNER_LEVEL" const GENERAL_BANNER_TEXT = "GENERAL_BANNER_TEXT" const GENERAL_BANNER_VISIBILITY = "GENERAL_BANNER_VISIBILITY" const GENERAL_BANNER_TITLE = "Announcement" const visible = { USERS: 1, SUPER_USERS: 2, USERS_AND_SUPER_USERS: 3 } class BaseTopBar extends Component { static propTypes = { currentUser: PropTypes.instanceOf(Person), appSettings: PropTypes.object, topbarHeight: PropTypes.func.isRequired, resetPages: PropTypes.func.isRequired, minimalHeader: PropTypes.bool, toggleMenuAction: PropTypes.func } constructor(props) { super(props) this.state = { bannerVisibility: false, height: 0 } this.topbarDiv = React.createRef() } componentDidMount() { this.handleTopbarHeight() this.updateBannerVisibility() window.addEventListener("resize", this.handleTopbarHeight) } componentDidUpdate() { this.handleTopbarHeight() this.updateBannerVisibility() } componentWillUnmount() { window.removeEventListener("resize", this.handleTopbarHeight) } handleTopbarHeight = () => { const height = this.topbarDiv.current.clientHeight if (height !== undefined && height !== this.state.height) { this.setState({ height }, () => this.props.topbarHeight(this.state.height) ) } } handleOnHomeClick = () => { this.props.resetPages() } updateBannerVisibility() { let visibilitySetting = parseInt( this.props.appSettings[GENERAL_BANNER_VISIBILITY], 10 ) let output = false const { currentUser } = this.props if ( visibilitySetting === visible.USERS && currentUser && !currentUser.isSuperUser() ) { output = true } if ( visibilitySetting === visible.SUPER_USERS && currentUser && currentUser.isSuperUser() ) { output = true } if ( visibilitySetting === visible.USERS_AND_SUPER_USERS && (currentUser || currentUser.isSuperUser()) ) { output = true } if (this.state.bannerVisibility !== output) { this.setState({ bannerVisibility: output }) } } bannerOptions() { return ( { level: this.props.appSettings[GENERAL_BANNER_LEVEL], message: this.props.appSettings[GENERAL_BANNER_TEXT], title: GENERAL_BANNER_TITLE, visible: this.state.bannerVisibility } || {} ) } render() { const { currentUser, minimalHeader, toggleMenuAction } = this.props return ( <div style={{ flex: "0 0 auto", zIndex: 100 }} ref={this.topbarDiv}> <div id="topbar"> <GeneralBanner options={this.bannerOptions()} /> <SecurityBanner /> {currentUser && !currentUser.hasActivePosition() && !currentUser.isNewUser() && <NoPositionBanner />} <Header minimalHeader={minimalHeader} toggleMenuAction={toggleMenuAction} onHomeClick={this.handleOnHomeClick} /> </div> </div> ) } } const TopBar = props => ( <AppContext.Consumer> {context => ( <BaseTopBar appSettings={context.appSettings} currentUser={context.currentUser} {...props} /> )} </AppContext.Consumer> ) const mapDispatchToProps = dispatch => ({ resetPages: () => dispatch(resetPages()) }) export default connect(null, mapDispatchToProps)(TopBar)
JavaScript
0
@@ -3018,16 +3018,17 @@ zIndex: +1 100 %7D%7D r
825bced46f17837e1da4a84f3af7b2dd8f29d4c8
add email check
client/src/components/donate.js
client/src/components/donate.js
import React, { Component } from 'react' import * as styles from '../style' import Donation, { KING_BADGE, ANGEL_BADGE } from './donation' import { connect } from 'react-redux' import * as selectors from '../selectors' import * as actions from '../actions' export class Donate extends Component { constructor(props){ super(props) this.state = { pimping: false, activePattern: 0, totalPatterns: 4, amount: 0, email: '' } } onDonateClick() { this.setState({pimping: true }) } onConfirmClick() { const donation = { pattern: this.state.activePattern, amount: this.state.amount, email: this.state.email } this.props.insertDonation(donation) this.setState({pimping: false}) } onAmountInput(event){ this.setState({amount: parseInt(event.target.value) }) } onEmailInput(event){ this.setState({email: event.target.value }) } renderInputAmount(label, placeholder, onChange){ const rowStyle = { display: 'flex', justifyContent: 'space-between', padding: '10px 10px', color: 'lightgray', alignItems: 'center' } const input = { padding: '10px', borderRadius: '5px', border: 'none', width: '64%', } return ( <div style={rowStyle}> <div style={{marginRight: '10px'}}>{label}</div> <input type='number' onChange={onChange.bind(this)} style={input} placeholder={placeholder} min='1' max='500'/> </div> ) } renderInputEmail(label, placeholder, onChange){ const rowStyle = { display: 'flex', justifyContent: 'space-between', padding: '10px 10px', color: 'lightgray', alignItems: 'center' } const input = { padding: '10px', borderRadius: '5px', border: 'none' } return ( <div style={rowStyle}> <div style={{marginRight: '10px'}}>{label}</div> <input onChange={onChange.bind(this)} style={input} placeholder={placeholder} /> </div> ) } onLeftClick(){ if (this.state.activePattern<=0){ this.setState({activePattern: this.state.totalPatterns}) } else { this.setState({activePattern: this.state.activePattern-1}) } } onRightClick(){ if (this.state.activePattern>=this.state.totalPatterns){ this.setState({activePattern: 0}) } else { this.setState({activePattern: this.state.activePattern+1}) } } renderDonateView(column, title, disclaimer, link){ return ( <div style={column}> <p style={title}> Donate </p> <div> { this.renderInputEmail('Email', 'you@example.com', this.onEmailInput) } { this.renderInputAmount('Amount', '€50',this.onAmountInput) } <div onClick={this.onDonateClick.bind(this)} style={{...styles.button, marginTop: '10px'}}>Pay with card</div> <div style={disclaimer}>Untitled Charity Org will charge 15% for daily running costs</div> <div style={link}>Read More</div> </div> </div> ) } render(){ const background = { margin: '0 0 0 50%', backgroundColor: 'rgb(36,36,36)', height: '300px', padding: '0 100px', height: '400px' } const title = { ...styles.text.title } const disclaimer = { fontFamily: 'Times', fontSize: '8pt', color: 'lightgray', marginTop: '10px' } const link = { ...disclaimer, color: 'lightblue', textDecoration: 'underline', margin: '0', cursor: 'pointer' } const column = { width: '250px' } const donationWidth = 100 const donationStyle = { backgroundColor: 'rgb(160, 167, 201)', height: 40, width: donationWidth, borderBottom: '2px solid rgb(204, 226, 255)', margin: '20px' } return( <div style={background}> { !this.state.pimping && this.renderDonateView(column, title, disclaimer, link)} <div style={column}> { this.state.pimping && ( <div> <div style={title}>Style It!</div> <div style={disclaimer}>Your donation has entitled you to choose a custom style for your donation</div> { this.state.amount > KING_BADGE && this.state.amount < ANGEL_BADGE && <div style={disclaimer}>You donated more than €{KING_BADGE} and earned a medal!</div>} { this.state.amount > ANGEL_BADGE && <div style={disclaimer}>You donated more than €{ANGEL_BADGE} and earned a medal!</div>} <div style={{display: 'flex', justifyContent:'space-between', alignItems: 'center' }}> <div onClick={this.onLeftClick.bind(this)} style={{...styles.button, height: '30px', padding: '0 10px'}}> Left </div> <Donation amount={this.state.amount} pattern={this.state.activePattern} donationStyle={donationStyle} /> <div onClick={this.onRightClick.bind(this)} style={{...styles.button, height: '30px', padding: '0 10px'}}> Right </div> </div> <div onClick={this.onConfirmClick.bind(this)} style={{...styles.button, marginTop: '10px'}}>Confirm</div> </div> )} { /* this.props.intertingDonation && <i style={{fontSize: '48px'}} class="fa fa-spinner fa-spin" aria-hidden="true"></i> */ } </div> </div> ) } } const mapStateToProps = state => { return { insertingDonation: state.insertingDonation } } const mapDispatchToProps = dispatch => { return { insertDonation: (donation) => { dispatch(actions.insertDonation(donation)) } } } export default connect(mapStateToProps, mapDispatchToProps)(Donate)
JavaScript
0.000001
@@ -542,24 +542,64 @@ rmClick() %7B%0A + if (this.state.email.length %3E 5)%7B%0A const do @@ -605,24 +605,26 @@ onation = %7B%0A + patter @@ -652,16 +652,18 @@ attern,%0A + am @@ -689,24 +689,26 @@ ount,%0A + email: this. @@ -719,26 +719,30 @@ e.email%0A -%7D%0A + %7D%0A this.pro @@ -769,24 +769,26 @@ nation)%0A + + this.setStat @@ -807,16 +807,22 @@ false%7D)%0A + %7D%0A %7D%0A%0A o
b6e393ccaac3e6ea2d257952d7f27d4dc3f47616
Add Switch to Routes
client/src/containers/Routes.js
client/src/containers/Routes.js
import React, {Component} from 'react' import {Route} from 'react-router-dom' import Home from '../components/Home' export default class Routes extends Component { render() { return ( <div> <Route exact path='/' component={Home}/> </div> ) } }
JavaScript
0.000001
@@ -45,16 +45,24 @@ t %7BRoute +, Switch %7D from ' @@ -200,19 +200,22 @@ %0A %3C -div +Switch %3E%0A @@ -269,11 +269,14 @@ %3C/ -div +Switch %3E%0A
bfa56b43c075e013a03e5f79839089cbf40f323f
save messagesSent locally
www/js/services/microdonation_service.js
www/js/services/microdonation_service.js
angular.module("proBebe.services").factory('Microdonation', function($resource, Constants, storage, $ionicPopup, Profile, DonatedMessage, $q, SmsSender) { return { setProfileType: function(profileType){ storage.set('profileType', profileType); }, getProfileType: function(){ return storage.get('profileType'); }, setSendingMessages: function(value){ storage.set('microdonationSendingMessage', value); }, isSendingMessages: function(){ return storage.get('microdonationSendingMessage'); }, isProfilePossibleDonor: function(){ return this.getProfileType() === Constants.PROFILE_TYPE_POSSIBLE_DONOR; }, isProfileDonor: function(){ return this.getProfileType() === Constants.PROFILE_TYPE_DONOR; }, sendMessages: function(){ var self = this; if(self.isSendingMessages()){ return; } self.setSendingMessages(true); DonatedMessage.get() .$promise.then(function(resp){ return $q.all(resp.donated_messages.map(function(donated_message){ return self._sendMessage(donated_message); })); }) .then(function(resp){ self.setSendingMessages(false); console.log('Terminou de enviar as mensagens'); }).catch(function(){ self.setSendingMessages(false); console.log('Falha'); }); }, _sendMessage: function(donated_message){ var self = this; SmsSender .send(donated_message.message, donated_message.phone_number) .then(function(){ return self._markMessageAsSent(donated_message); }, function(){ return false; }) }, _markMessageAsSent: function(donated_message){ var DonatedMessageMarkAsSent = $resource(Constants.DONATED_MESSAGES_URL + '/mark_as_sent'); DonatedMessageMarkAsSent.save({id: donated_message.id}) .$promise.then(function(){ return true; }) .catch(function(){ return false; }); } } });
JavaScript
0
@@ -1062,24 +1062,142 @@ d_message)%7B%0A + if(self._wasAlreadySent(donated_message))%0A return self._markMessageAsSent(donated_message);%0A%0A @@ -1684,32 +1684,85 @@ hen(function()%7B%0A + self._addInAlreadySentList(donated_message);%0A return s @@ -1904,32 +1904,55 @@ nated_message)%7B%0A + var self = this;%0A var Donate @@ -2031,32 +2031,39 @@ s_sent');%0A +return DonatedMessageMa @@ -2127,32 +2127,90 @@ hen(function()%7B%0A + self._removeFromAlreadySentList(donated_message);%0A return t @@ -2285,17 +2285,826 @@ );%0A %7D -%0A +,%0A _wasAlreadySent: function(donated_message)%7B%0A var messagesSent = storage.get('messagesSent');%0A if(!messagesSent)%0A return false;%0A return messagesSent.indexOf(donated_message.id) %3E= 0%0A %7D,%0A _addInAlreadySentList: function(donated_message)%7B%0A var messagesSent = storage.get('messagesSent');%0A if(!messagesSent)%0A messagesSent = %5B%5D;%0A%0A messagesSent.push(donated_message.id);%0A storage.set('messagesSent', messagesSent)%0A %7D,%0A _removeFromAlreadySentList: function(donated_message)%7B%0A var messagesSent = storage.get('messagesSent');%0A if(!messagesSent)%0A return true;%0A%0A var index = messagesSent.indexOf(donated_message.id)%0A%0A if(index %3E= 0)%0A messagesSent.splice(index, 1);%0A%0A storage.set('messagesSent', messagesSent)%0A %7D %0A %7D%0A%7D);
35d8d1883db558bef869c030586190058fd2b600
Fix syntax
www/js/controllers/DEx/OverviewController.js
www/js/controllers/DEx/OverviewController.js
angular.module("omniControllers") .controller("DExOverviewController", ["$scope","Account","Orderbook","Wallet","PropertyManager","$http" function DExOverviewController($scope,Account,Orderbook,Wallet,PropertyManager,$http){ $scope.isLoggedIn = Account.isLoggedIn; $scope.markets = []; $scope.noMarkets = true; $scope.ecosystem = 1; $scope.setEcosystem = function(ecosystem){ $scope.ecosystem = ecosystem; }; $http.post('/v1/markets/designatingcurrencies',{ecosystem:$scope.ecosystem}).success(function(response) {$scope.designatingcurrencies = response.data.currencies;}); }]);
JavaScript
0.509732
@@ -131,16 +131,17 @@ ,%22$http%22 +, %0A%09%09funct
4f1f585f92e55ce24d9bab0c76eaf9275c39c175
Add this binding to home.js
client/src/modules/home/home.js
client/src/modules/home/home.js
import angular from 'angular'; // components used by this module import PlanCardComponent from './plan-card/plan-card'; import NewPlanButtonComponent from './new-plan-button/new-plan-button'; import PlanService from '../../services/plan/plan.service'; // imports for this component import template from './home.html'; import './home.css'; class HomeController { constructor(PlanService) { this.$inject = ['PlanService']; this.PlanService = PlanService; this.name = 'Your Plans'; this.deletePlan = (planId) => { PlanService.deletePlanById(planId).then( this.PlanService.getAllPlans().then(this.loadPlans) ); }; this.loadPlans = (plans) => { console.log(plans, "plans'"); this.plans = plans; }; this.$onInit = () => { this.PlanService.getAllPlans().then(this.loadPlans); }; } } const HomeComponent = { restrict: 'E', bindings: {}, template: template, controller: HomeController }; const HomeModule = angular.module('app.home', []) .component('home', HomeComponent) .component('planCard', PlanCardComponent) .component('newPlanButton', NewPlanButtonComponent) .service('PlanService', PlanService); export default HomeModule.name;
JavaScript
0
@@ -488,17 +488,16 @@ Plans';%0A -%0A this @@ -501,292 +501,353 @@ his. -delete +load Plan +s = -(planId) =%3E %7B%0A PlanService.deletePlanById(planId).then(%0A this.PlanService.getAllPlans().then(this.loadPlans)%0A );%0A +this.loadPlans.bind(this);%0A this.deletePlan = this.deletePlan.bind(this);%0A this.$onInit = this.$onInit.bind(this);%0A %7D%0A%0A loadPlans(plans) %7B%0A this.plans = plans;%0A %7D -; %0A%0A - - this.loadPlans = (plans) =%3E %7B%0A console.log(plans, %22plans'%22);%0A this.plans = p +deletePlan(planId) %7B%0A this.PlanService.deletePlanById(planId).then(%0A this.PlanService.getAllPlans().then(this.loadP lans -; +) %0A -%7D;%0A%0A this.$onInit = () =%3E %7B%0A +);%0A %7D%0A%0A $onInit() %7B%0A @@ -905,16 +905,10 @@ ;%0A - %7D;%0A %7D +%0A %0A%7D%0A%0A
814affa2fba0caf15e5ad9e6c165c94d43abce7b
Add landed regions to invest requirements form handler
src/apps/investment-projects/middleware/forms/requirements.js
src/apps/investment-projects/middleware/forms/requirements.js
const { assign, flatten, get } = require('lodash') const { updateInvestment } = require('../../repos') const { requirementsFormConfig } = require('../../macros') const { getOptions } = require('../../../../lib/options') const { buildFormWithStateAndErrors } = require('../../../builders') async function getFormOptions (token, createdOn) { return { strategicDrivers: await getOptions(token, 'investment-strategic-driver', { createdOn }), countries: await getOptions(token, 'country', { createdOn }), ukRegions: await getOptions(token, 'uk-region', { createdOn }), } } async function populateForm (req, res, next) { try { const investmentId = req.params.investmentId const investmentData = res.locals.investmentData const createdOn = get(res.locals.investmentData, 'created_on') const options = await getFormOptions(req.session.token, createdOn) const body = res.locals.formattedBody || investmentData res.locals.requirementsForm = assign({}, buildFormWithStateAndErrors(requirementsFormConfig(options), body, res.locals.errors), { returnLink: `/investment-projects/${investmentId}` }, ) } catch (error) { return next(error) } next() } // Strips out empty entries so they are not posted (which result in errors) // and when an error is thrown it doesn't mean yet another is added function cleanArray (values) { return flatten([values]) .filter(item => item) } async function handleFormPost (req, res, next) { try { const investmentId = req.params.investmentId res.locals.formattedBody = assign({}, req.body, { strategic_drivers: cleanArray(req.body.strategic_drivers), competitor_countries: req.body.client_considering_other_countries === 'true' ? cleanArray(req.body.competitor_countries) : [], uk_region_locations: cleanArray(req.body.uk_region_locations), }) // if called with the add item instruction, simply re-render the form and it will add extra fields as needed if (req.body.add_item) { return next() } await updateInvestment(req.session.token, investmentId, res.locals.formattedBody) req.flash('success', 'Investment requirements updated') res.redirect(`/investment-projects/${investmentId}/details`) } catch (err) { if (err.statusCode === 400) { res.locals.errors = err.error next() } else { next(err) } } } module.exports = { populateForm, handleFormPost, }
JavaScript
0
@@ -1857,24 +1857,129 @@ locations),%0A + actual_uk_regions: req.body.site_decided === 'true' ? cleanArray(req.body.actual_uk_regions) : %5B%5D,%0A %7D)%0A%0A
a53f78e35eca4d2a2de68d07108f7c0fbb1eaa3d
update Tab
src/Tab/Tab.js
src/Tab/Tab.js
/** * @file Tab component * @author liangxiaojun(liangxiaojun@derbysoft.com) */ import React, {Component} from 'react'; import PropTypes from 'prop-types'; // Components import Tabs from '../_Tabs'; // Vendors import classNames from 'classnames'; import ComponentUtil from '../_vendors/ComponentUtil'; import Util from '../_vendors/Util'; class Tab extends Component { constructor(props, ...restArgs) { super(props, ...restArgs); this.state = { tabs: props.tabs, activatedIndex: props.activatedIndex, isTabsOverflow: false }; } static getDerivedStateFromProps(props, state) { return { prevProps: props, tabs: ComponentUtil.getDerivedState(props, state, 'tabs'), activatedIndex: ComponentUtil.getDerivedState(props, state, 'activatedIndex') }; } getRenderer = item => { if (!item || !item.tabContentRenderer) { return null; } return typeof item.tabContentRenderer === 'function' ? item.tabContentRenderer(item) : item.tabContentRenderer; }; handleTabClick = (item, activatedIndex, e) => { const {onTabClick} = this.props; onTabClick && onTabClick(item, activatedIndex, e); if (activatedIndex === this.state.activatedIndex) { return; } const {beforeIndexChange} = this.props; if (beforeIndexChange && beforeIndexChange(activatedIndex, item, e) === false) { return; } this.setState({ activatedIndex }, () => { item.onActive && item.onActive(item, activatedIndex, e); const {onIndexChange} = this.props; onIndexChange && onIndexChange(activatedIndex, item, e); }); }; handleTabsOverflowChange = isTabsOverflow => { this.setState({ isTabsOverflow }); }; handleTabButtonDragEnd = result => { if (!result || !('draggableId' in result) || !result.source || !('index' in result.source) || !result.destination || !('index' in result.destination)) { return; } const {tabs} = this.state; Util.reorder(tabs, result.source.index, result.destination.index); const {activatedIndex} = this.state, state = { tabs }; if (activatedIndex === result.source.index) { state.activatedIndex = result.destination.index; } else if (activatedIndex === result.destination.index) { state.activatedIndex = result.source.index; } else if (activatedIndex > result.source.index && activatedIndex < result.destination.index) { state.activatedIndex = activatedIndex - 1; } else if (activatedIndex < result.source.index && activatedIndex > result.destination.index) { state.activatedIndex = activatedIndex + 1; } this.setState(state, () => { const {onTabButtonDragEnd, onTabsSequenceChange} = this.props; onTabButtonDragEnd && onTabButtonDragEnd(result); onTabsSequenceChange && onTabsSequenceChange(tabs); }); }; render() { const {children, tabsChildren, className, style, isAnimated} = this.props, {tabs, activatedIndex, isTabsOverflow} = this.state, tabWidthPerCent = 100 / tabs.length; return ( <div className={classNames('tab', { animated: isAnimated, 'tabs-overflow': isTabsOverflow, [className]: className })} style={style}> <Tabs {...this.props} data={tabs} activatedIndex={activatedIndex} isTabsOverflow={isTabsOverflow} onTabClick={this.handleTabClick} onTabsOverflowChange={this.handleTabsOverflowChange} onTabButtonDragEnd={this.handleTabButtonDragEnd}> {tabsChildren} </Tabs> <div className="tab-content-wrapper"> { isAnimated ? <div className="tab-content-scroller" style={{ width: `${tabs.length * 100}%`, transform: `translate(${-activatedIndex * tabWidthPerCent}%, 0)` }}> { tabs && tabs.map((item, index) => <div key={index} className="tab-content" style={{ width: `${tabWidthPerCent}%` }}> {this.getRenderer(item)} </div> ) } </div> : <div className="tab-content"> {tabs && this.getRenderer(tabs[activatedIndex])} </div> } </div> {children} </div> ); } } Tab.propTypes = { children: PropTypes.any, tabsChildren: PropTypes.any, /** * The CSS class name of the root element. */ className: PropTypes.string, /** * Override the styles of the root element. */ style: PropTypes.object, /** * Children passed into the TabsItem. */ tabs: PropTypes.arrayOf(PropTypes.shape({ /** * The text value of the tab.Type can be string or number. */ value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), /** * If true, the tab will be disabled. */ disabled: PropTypes.bool, /** * If true,the tab will be have loading effect. */ isLoading: PropTypes.bool, /** * If true,the element's ripple effect will be disabled. */ disableTouchRipple: PropTypes.bool, /** * Use this property to display an icon.It will display on the left. */ iconCls: PropTypes.string, /** * The position of the icon. */ iconPosition: PropTypes.string, /** * The render of tab button. */ renderer: PropTypes.any, /** * The render content in tab. */ tabContentRenderer: PropTypes.any, /** * Callback function fired when click onActive tab. */ onActive: PropTypes.func })).isRequired, /** * Activated tab index. */ activatedIndex: PropTypes.number, /** * If true,the tabs is FullWidth. */ isTabFullWidth: PropTypes.bool, isInkBarHidden: PropTypes.bool, isAnimated: PropTypes.bool, draggable: PropTypes.bool, idProp: PropTypes.string, scrollLeftIconCls: PropTypes.string, scrollRightIconCls: PropTypes.string, scrollStep: PropTypes.number, scrollInterval: PropTypes.number, keepScrollingWait: PropTypes.number, beforeIndexChange: PropTypes.func, onIndexChange: PropTypes.func, onTabClick: PropTypes.func, onTabMouseDown: PropTypes.func, onTabMouseUp: PropTypes.func, onTabButtonDragStart: PropTypes.func, onTabButtonDragEnd: PropTypes.func, onTabsSequenceChange: PropTypes.func, onScrollLeftButtonMouseDown: PropTypes.func, onScrollRightButtonMouseDown: PropTypes.func }; Tab.defaultProps = { tabs: [], activatedIndex: 0, isTabFullWidth: true, isInkBarHidden: false, isAnimated: true, draggable: false, scrollLeftIconCls: 'fas fa-chevron-left', scrollRightIconCls: 'fas fa-chevron-right', scrollStep: 100, scrollInterval: 100, keepScrollingWait: 250 }; export default Tab;
JavaScript
0.000001
@@ -3354,16 +3354,30 @@ Animated +, ...restProps %7D = this @@ -3766,22 +3766,21 @@ abs %7B... -this.p +restP rops%7D%0A
c5a20477ac1a8178fe0dfb14b1e166ec98e73b63
Apply bcrypt to passport local strategy
src/api/lib/auth/local.js
src/api/lib/auth/local.js
import { collections } from '../../db/index.js'; export function validatePassword(passport, password) { // TODO: use bcrypt return Promise.resolve(true); } export default function login(username, password, done) { const { User, Passport } = collections; let passport; // Retrieve passport with the username Passport.findOne({ identifier: username, type: 'local' }) .then(gotPassport => { passport = gotPassport; if (passport == null) throw new Error('Passport not found'); // Validate password return validatePassword(passport, password); }) .then(isValid => { if (!isValid) throw new Error('Password incorrect'); return User.findOne(passport.id); }) .then(user => { if (user == null) throw new Error('User not found'); done(null, user); }, error => { done(error); }); }
JavaScript
0
@@ -41,16 +41,142 @@ dex.js'; +%0Aimport bcrypt from 'bcrypt';%0A// Fallback to bcryptjs if not available%0Aif (bcrypt == null) %7B%0A bcrypt = require('bcryptjs');%0A%7D %0A%0Aexport @@ -185,21 +185,21 @@ unction -valid +gener atePassw @@ -210,47 +210,234 @@ pass -port, password) %7B%0A // TODO: use bcrypt +word) %7B%0A return new Promise((resolve, reject) =%3E %7B%0A bcrypt.hash(password, 10, (err, hash) =%3E %7B%0A if (err) return reject(err);%0A resolve(hash);%0A %7D);%0A %7D);%0A%7D%0A%0Aexport function validatePassword(passport, password) %7B %0A r @@ -446,28 +446,169 @@ urn +new Promise -. +(( resolve -(true +, reject) =%3E %7B%0A bcrypt.compare(password, passport.data, (err, res) =%3E %7B%0A if (err) return reject(err);%0A resolve(res);%0A %7D);%0A %7D );%0A%7D
34764acb4cbab9b1c9254f99d2963c9c64c2cb8d
Update data clearing UI's text.
packages/coinstac-ui/app/render/components/settings.js
packages/coinstac-ui/app/render/components/settings.js
import app from 'ampersand-app'; import { Button } from 'react-bootstrap'; import { connect } from 'react-redux'; import React, { Component, PropTypes } from 'react'; class Settings extends Component { constructor(props) { super(props); this.deleteUserData = this.deleteUserData.bind(this); } deleteUserData(event) { event.preventDefault(); app.main.services.clean.userData(this.props.username) .then(() => { app.notify('info', 'Logged out'); // TODO: Figure why `nextTick` is needed process.nextTick(() => this.context.router.push('/login')); }) .catch(error => { app.logger.error(error); app.notify('error', `Could not remove user data: ${error.message}`); }); } render() { return ( <div className="settings"> <div className="page-header"> <h1>Settings</h1> </div> <h2>Remove Data</h2> <form method="post" onSubmit={this.deleteUserData}> <h3 className="h4">Clear user data</h3> <p>Remove stored data for your user:</p> <Button bsStyle="danger" type="submit"> Delete User Data </Button> </form> </div> ); } } Settings.contextTypes = { router: PropTypes.object.isRequired, }; Settings.propTypes = { username: PropTypes.string.isRequired, }; function mapStateToProps(state) { return { username: state.auth.user.username, }; } export default connect(mapStateToProps)(Settings);
JavaScript
0
@@ -1076,17 +1076,85 @@ our user -: +, including your projects. %3Cstrong%3EThis action is permanent.%3C/strong%3E %3C/p%3E%0A