commit
stringlengths 40
40
| old_file
stringlengths 4
264
| new_file
stringlengths 4
264
| old_contents
stringlengths 0
3.26k
| new_contents
stringlengths 1
4.43k
| subject
stringlengths 15
624
| message
stringlengths 15
4.7k
| lang
stringclasses 3
values | license
stringclasses 13
values | repos
stringlengths 5
91.5k
|
---|---|---|---|---|---|---|---|---|---|
97be40abed9993dae673799fbc002fa3cad4f77a
|
server/server.js
|
server/server.js
|
'use strict';
require('newrelic');
const common = require('../common/common');
const db = require('./db');
const logger = require('./logger');
const httpServer = require('./staticHttpServer');
const createWsServer = require('./createWsServer');
const PORT = Number(process.env.PORT || common.PORT);
process.title = 'jcm2018-server';
db.connect();
httpServer.listen(PORT, () => {
logger.info(`Server is listening on port ${PORT}.`);
});
const requestAllowed = wsRequest => {
/* webSocketRequest.origin is only advisory and Same origin policy cannot rely on it.
Rather, we disallow http in production and employ authentication-protected API. */
if (process.env.NODE_ENV && process.env.NODE_ENV === 'production') {
const proto = wsRequest.httpRequest.headers['x-forwarded-proto'];
if (proto === 'https') {
logger.debug(`Allowing originating protocol '${proto}' in production.`);
return true;
}
logger.debug(`Disallowing originating protocol '${proto}' in production.`);
logger.silly(JSON.stringify(wsRequest.httpRequest.headers));
return false;
}
logger.debug('Allowing any access, not in production.');
return true;
};
createWsServer({ httpServer, requestAllowed });
|
'use strict';
const common = require('../common/common');
const db = require('./db');
const logger = require('./logger');
const httpServer = require('./staticHttpServer');
const createWsServer = require('./createWsServer');
const PORT = Number(process.env.PORT || common.PORT);
process.title = 'jcm2018-server';
db.connect();
httpServer.listen(PORT, () => {
logger.info(`Server is listening on port ${PORT}.`);
});
const requestAllowed = wsRequest => {
/* webSocketRequest.origin is only advisory and Same origin policy cannot rely on it.
Rather, we disallow http in production and employ authentication-protected API. */
if (process.env.NODE_ENV && process.env.NODE_ENV === 'production') {
const proto = wsRequest.httpRequest.headers['x-forwarded-proto'];
if (proto === 'https') {
logger.debug(`Allowing originating protocol '${proto}' in production.`);
return true;
}
logger.debug(`Disallowing originating protocol '${proto}' in production.`);
logger.silly(JSON.stringify(wsRequest.httpRequest.headers));
return false;
}
logger.debug('Allowing any access, not in production.');
return true;
};
createWsServer({ httpServer, requestAllowed });
|
Remove newrelic from the project.
|
Remove newrelic from the project.
|
JavaScript
|
mit
|
ivosh/jcm2018,ivosh/jcm2018,ivosh/jcm2018
|
bd25f30c0bed4a02a165f6741e338f552af23cb0
|
js/router.js
|
js/router.js
|
define(['jquery', 'underscore', 'backbone', 'views'],
function($ , _ , Backbone , View ) {
var AppRouter = Backbone.Router.extend({
routes: {
'': 'showHome',
'about': 'showAbout',
'projects': 'showProjects',
'resume': 'showResume',
':string': 'showError'
},
showHome: function() {
var homeView = new View['home'];
homeView.render();
},
showAbout: function() {
var aboutView = new View['about'];
aboutView.render();
},
showProjects: function() {
var projectsView = new View['projects'];
projectsView.render();
},
showResume: function() {
var resumeView = new View['resume'];
resumeView.render();
},
showError: function(string) {
var errorView = new View['error'];
errorView.render();
}
});
function initialize() {
var appRouter = new AppRouter;
Backbone.history.start({ pushstate: true });
$('#toggle-menu').click(function() {
$('.navbar-content').toggleClass('expanded');
});
$(document).on('click', 'a', function(evt) {
if (this.host == location.host) {
evt.preventDefault();
var href = $(this).attr('href');
$('.navbar-content').removeClass('animate expanded');
Backbone.history.navigate(href, true);
_.delay(function() {
$('.navbar-content').addClass('animate');
}, 50);
}
});
return appRouter;
}
return {
initialize: initialize
};
});
|
define(['jquery', 'underscore', 'backbone', 'views'],
function($ , _ , Backbone , View ) {
var AppRouter = Backbone.Router.extend({
routes: {
'': 'showHome',
'about': 'showAbout',
'projects': 'showProjects',
'resume': 'showResume',
':string': 'showError'
},
showHome: function() {
var homeView = new View['home'];
homeView.render();
},
showAbout: function() {
var aboutView = new View['about'];
aboutView.render();
},
showProjects: function() {
var projectsView = new View['projects'];
projectsView.render();
},
showResume: function() {
var resumeView = new View['resume'];
resumeView.render();
},
showError: function(string) {
var errorView = new View['error'];
errorView.render();
}
});
function initialize() {
var appRouter = new AppRouter;
Backbone.history.start({ pushstate: true });
$('#toggle-menu').click(function() {
$('.navbar-content').toggleClass('expanded');
});
$(document).on('click', 'a', function(evt) {
if (this.host == location.host) {
evt.preventDefault();
var href = $(this).attr('href');
$('.navbar-content').removeClass('animate expanded');
Backbone.history.navigate(href, { trigger: true });
_.delay(function() {
$('.navbar-content').addClass('animate');
}, 50);
}
});
return appRouter;
}
return {
initialize: initialize
};
});
|
Add trigger to navigate() calls
|
Add trigger to navigate() calls
|
JavaScript
|
mit
|
jonlai/personal-website,jonlai/personal-website,jonlai/personal-website
|
e0181d13dd3e42ee3bbda2aa270848e06f50fe4e
|
app/js/controllers/data-controller.js
|
app/js/controllers/data-controller.js
|
'use strict';
module.exports = function(app) {
app.controller('dataController',
[ '$scope', 'HttpService', '$http', '$cookies',
function($scope, HttpService, $http, $cookies) {
$http.defaults.headers.common.jwt = $cookies.jwt;
$scope.selectedDomain = false;
var domainService = new HttpService('domains');
$scope.getDomains = function(){
domainService.get()
.success(function(domains){
$scope.domains = domains;
});
};
$scope.getDomains(); // run on view load
var visitService = new HttpService('visits');
$scope.getVisits = function(domain_id){
$scope.selectedDomain = domain_id;
visitService.get(domain_id.toString())
.success(function(visits){
$scope.visits = visits;
});
};
} ]);
};
|
'use strict';
module.exports = function(app) {
app.controller('dataController',
[ '$scope', 'HttpService', '$http', '$cookies',
function($scope, HttpService, $http, $cookies) {
$http.defaults.headers.common.jwt = $cookies.jwt;
$scope.selectedDomain = false;
var domainService = new HttpService('domains');
$scope.getDomains = function(){
domainService.get()
.success(function(domains){
$scope.domains = domains;
});
};
$scope.getDomains(); // run on view load
var visitService = new HttpService('visits');
$scope.getVisits = function(domain_id){
$scope.selectedDomain = domain_id;
visitService.get(domain_id.toString())
.success(function(visits){
$scope.visits = visits;
});
};
/**
* Add domains
*/
$scope.addDomain = function() {
domainService.post($scope.newDomain, {});
$scope.newDomain = '';
};
} ]);
};
|
Add function for adding domains
|
Add function for adding domains
|
JavaScript
|
mit
|
Sextant-WDB/sextant-ng
|
f1f4f9e1afbb331ed3eb679d4b2cebf930a21824
|
js/script.js
|
js/script.js
|
(function () {
'use strict';
var worker = null,
$output = null;
$output = $('#worker-output');
/**
worker = new Worker('/js/example-worker.js');
worker.addEventListener('message', function (event) {
$output.text(event.data);
return;
})
//worker.postMessage();
/**/
worker = new WebWorker('/js/example-worker.js');
worker.on('message', function (event) {
$output.text(event.data);
return;
});
worker.load().on(WebWorker.Event.WORKER_LOADED, function () {
worker.start();
return;
});
return;
})();
|
(function () {
'use strict';
var worker = null,
$output = null;
$output = $('#worker-output');
/**
worker = new Worker('/js/example-worker.js');
worker.addEventListener('message', function (event) {
$output.text(event.data);
return;
})
//worker.postMessage();
/**/
worker = new WebWorker('/js/example-worker.js');
worker.on('message', function (event) {
$output.text(event.data);
return;
});
worker.load().on(WebWorker.Event.WORKER_LOADED, function () {
console.log('has loaded');
worker.start();
return;
});
return;
})();
|
Add temporary console.log for debugging.
|
Add temporary console.log for debugging.
|
JavaScript
|
mit
|
tanzeelkazi/web-worker,tanzeelkazi/webworker,tanzeelkazi/webworker,tanzeelkazi/web-worker,tanzeelkazi/web-worker,tanzeelkazi/webworker
|
b555d4c3922ed5ccb2a2affa58c566cce7b9b1f6
|
handlers/users.js
|
handlers/users.js
|
'use strict';
const Boom = require('boom');
const Errors = require('../lib/errors');
const Formatters = require('../lib/formatters');
const EXISTING_USER = Boom.conflict('User already exist');
exports.listUsers = function({ headers }, reply) {
let authParts = [];
if (headers.authorization) {
authParts = headers.authorization.split(' ');
}
const token = (authParts.length === 2) ? authParts[1] : '';
return this.helpers.verifyJWT(token)
.then(({ sub }) => this.models.User.getUser(sub))
.then((user) => {
const options = {};
if (!user) {
options.onlyViewPublic = true;
} else if (!user.isAdministrator()) {
options.selfId = user.id;
}
return this.models.User.listUsers(options);
})
.then((users) => {
return reply(Formatters.users(users)).code(200);
})
.catch(this.helpers.errorHandler.bind(this, reply));
};
exports.createUser = function({ payload }, reply) {
return this.models.User.createUser(payload)
.then((user) => {
return reply(Formatters.user(user)).code(201);
})
.catch(Errors.ExistingUserError, () => reply(EXISTING_USER))
.catch(this.helpers.errorHandler.bind(this, reply));
};
|
'use strict';
const Boom = require('boom');
const Errors = require('../lib/errors');
const Formatters = require('../lib/formatters');
exports.listUsers = function({ headers }, reply) {
let authParts = [];
if (headers.authorization) {
authParts = headers.authorization.split(' ');
}
const token = (authParts.length === 2) ? authParts[1] : '';
return this.helpers.verifyJWT(token)
.then(({ sub }) => this.models.User.getUser(sub))
.then((user) => {
const options = {};
if (!user) {
options.onlyViewPublic = true;
} else if (!user.isAdministrator()) {
options.selfId = user.id;
}
return this.models.User.listUsers(options);
})
.then((users) => {
return reply(Formatters.users(users)).code(200);
})
.catch(this.helpers.errorHandler.bind(this, reply));
};
exports.createUser = function({ payload }, reply) {
return this.models.User.createUser(payload)
.then((user) => {
return reply(Formatters.user(user)).code(201);
})
.catch(Errors.ExistingUserError, () => {
return reply(Boom.conflict('User already exist'));
})
.catch(this.helpers.errorHandler.bind(this, reply));
};
|
Replace Boom variable in createUser()
|
Replace Boom variable in createUser()
|
JavaScript
|
mit
|
cjduncana/adevav-back-end,cjduncana/adevav-back-end,creativo-pty/adevav-back-end,creativo-pty/adevav-back-end
|
46cf5c9a5c56c6abcf0ee50c9492a96588b925dc
|
app/renderer/js/utils/config-util.js
|
app/renderer/js/utils/config-util.js
|
'use strict';
const {app} = require('electron').remote;
const JsonDB = require('node-json-db');
let instance = null;
class ConfigUtil {
constructor() {
if (instance) {
return instance;
} else {
instance = this;
}
this.db = new JsonDB(app.getPath('userData') + '/config.json', true, true);
return instance;
}
getConfigItem(key, defaultValue = null) {
const value = this.db.getData('/')[key];
if (value === undefined) {
this.setConfigItem(key, value);
return defaultValue;
} else {
return value;
}
}
setConfigItem(key, value) {
this.db.push(`/${key}`, value, true);
}
removeConfigItem(key) {
this.db.delete(`/${key}`);
}
}
module.exports = new ConfigUtil();
|
'use strict';
const process = require('process');
const JsonDB = require('node-json-db');
let instance = null;
let app = null;
/* To make the util runnable in both main and renderer process */
if (process.type === 'renderer') {
app = require('electron').remote.app;
} else {
app = require('electron').app;
}
class ConfigUtil {
constructor() {
if (instance) {
return instance;
} else {
instance = this;
}
this.db = new JsonDB(app.getPath('userData') + '/config.json', true, true);
return instance;
}
getConfigItem(key, defaultValue = null) {
const value = this.db.getData('/')[key];
if (value === undefined) {
this.setConfigItem(key, value);
return defaultValue;
} else {
return value;
}
}
setConfigItem(key, value) {
this.db.push(`/${key}`, value, true);
}
removeConfigItem(key) {
this.db.delete(`/${key}`);
}
}
module.exports = new ConfigUtil();
|
Make ConfigUtil runnable in both processes.
|
Make ConfigUtil runnable in both processes.
|
JavaScript
|
apache-2.0
|
zulip/zulip-desktop,zulip/zulip-desktop,zulip/zulip-desktop,zulip/zulip-desktop,zulip/zulip-electron,zulip/zulip-electron,zulip/zulip-electron
|
9c117026f141ef68e06571afb5bffc90a29d22ee
|
app/scripts/services/eventservice.js
|
app/scripts/services/eventservice.js
|
'use strict';
/**
* @ngdoc service
* @name barteguidenMarkedsWebApp.eventService
* @description
* # eventService
* Factory in the barteguidenMarkedsWebApp.
*/
angular.module('barteguidenMarkedsWebApp.services')
.factory('Event', function ($resource) {
return $resource('http://barteguiden.no/v2/events/:id', { id: '@_id' }, {
update: {
method: 'PUT'
},
query: {
method: 'GET',
isArray: false
}
});
});
|
'use strict';
/**
* @ngdoc service
* @name barteguidenMarkedsWebApp.eventService
* @description
* # eventService
* Factory in the barteguidenMarkedsWebApp.
*/
angular.module('barteguidenMarkedsWebApp.services')
.factory('Event', function ($resource) {
return $resource('http://localhost:4004/api/events/:id', { id: '@_id' }, {
update: {
method: 'PUT'
},
query: {
method: 'GET',
isArray: true
}
});
});
|
Update the EventService to use the local server. The event response is now an array
|
Update the EventService to use the local server. The event response is now an array
|
JavaScript
|
apache-2.0
|
Studentmediene/Barteguiden,Studentmediene/Barteguiden
|
e418a810e6b20efceb472c3165a750894afc75f0
|
src/__tests__/server.device.js
|
src/__tests__/server.device.js
|
/**
* Copyright 2018-present Facebook.
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* @format
*/
import Server from '../server.js';
import LogManager from '../fb-stubs/Logger';
import reducers from '../reducers/index.js';
import configureStore from 'redux-mock-store';
import path from 'path';
import os from 'os';
import fs from 'fs';
let server;
const mockStore = configureStore([])(reducers(undefined, {type: 'INIT'}));
beforeAll(() => {
// create config directory, which is usually created by static/index.js
const flipperDir = path.join(os.homedir(), '.flipper');
if (!fs.existsSync(flipperDir)) {
fs.mkdirSync(flipperDir);
}
server = new Server(new LogManager(), mockStore);
return server.init();
});
test.skip(
'Device can connect successfully',
done => {
var testFinished = false;
server.addListener('new-client', (client: Client) => {
console.debug('new-client ' + new Date().toString());
setTimeout(() => {
testFinished = true;
done();
}, 5000);
});
server.addListener('removed-client', (id: string) => {
console.debug('removed-client ' + new Date().toString());
if (!testFinished) {
done.fail('client disconnected too early');
}
});
},
20000,
);
afterAll(() => {
return server.close();
});
|
/**
* Copyright 2018-present Facebook.
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* @format
*/
import Server from '../server.js';
import LogManager from '../fb-stubs/Logger';
import reducers from '../reducers/index.js';
import configureStore from 'redux-mock-store';
import path from 'path';
import os from 'os';
import fs from 'fs';
let server;
const mockStore = configureStore([])(reducers(undefined, {type: 'INIT'}));
beforeAll(() => {
// create config directory, which is usually created by static/index.js
const flipperDir = path.join(os.homedir(), '.flipper');
if (!fs.existsSync(flipperDir)) {
fs.mkdirSync(flipperDir);
}
server = new Server(new LogManager(), mockStore);
return server.init();
});
test(
'Device can connect successfully',
done => {
var testFinished = false;
server.addListener('new-client', (client: Client) => {
console.debug('new-client ' + new Date().toString());
setTimeout(() => {
testFinished = true;
done();
}, 5000);
});
server.addListener('removed-client', (id: string) => {
console.debug('removed-client ' + new Date().toString());
if (!testFinished) {
done.fail('client disconnected too early');
}
});
},
20000,
);
afterAll(() => {
return server.close();
});
|
Apply oneworld-fix patch before testing connectivity
|
Apply oneworld-fix patch before testing connectivity
Summary:
Making the runner apply the necessary oneworld fix patch before running the tests.
This can't be a long term solution, but at least means not getting that breaking change landed doesn't stop our tests from running.
Since that change is only necessary for the tests, maybe we'll get away with fixing the update process before having to land it.
Reviewed By: priteshrnandgaonkar
Differential Revision: D10852110
fbshipit-source-id: b53a6d0ae9cb51e62cafc0c0f2cfe359ee6aff46
|
JavaScript
|
mit
|
facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper
|
fe59cb4ecf7371f775f793f72bb64e5fc7203c8a
|
transformers/engine.io/server.js
|
transformers/engine.io/server.js
|
'use strict';
/**
* Minimum viable WebSocket server for Node.js that works through the primus
* interface.
*
* @runat server
* @api private
*/
module.exports = function server() {
var Engine = require('engine.io').Server
, Spark = this.Spark
, primus = this.primus;
this.service = new Engine();
//
// We've received a new connection, create a new Spark. The Spark will
// automatically announce it self as a new connection once it's created (after
// the next tick).
//
this.service.on('connection', function connection(socket) {
var spark = new Spark(
socket.request.headers
, socket.request.connection.address()
, socket.id
);
spark.on('ougoing::end', function end() {
socket.end();
}).on('outgoing::data', function write(data) {
socket.write(data);
});
socket.on('end', spark.emits('end'));
socket.on('data', spark.emits('data'));
});
//
// Listen to upgrade requests.
//
this.on('upgrade', function upgrade(req, socket, head) {
this.service.handleUpgrade(req, socket, head);
}).on('request', function request(req, res) {
this.service.handleRequest(req, res);
});
};
|
'use strict';
/**
* Minimum viable WebSocket server for Node.js that works through the primus
* interface.
*
* @runat server
* @api private
*/
module.exports = function server() {
var Engine = require('engine.io').Server
, Spark = this.Spark
, primus = this.primus;
this.service = new Engine();
//
// We've received a new connection, create a new Spark. The Spark will
// automatically announce it self as a new connection once it's created (after
// the next tick).
//
this.service.on('connection', function connection(socket) {
var spark = new Spark(
socket.request.headers
, socket.request.connection.address()
, socket.id
);
spark.on('ougoing::end', function end() {
socket.end();
}).on('outgoing::data', function write(data) {
socket.write(data);
});
socket.on('close', spark.emits('end'));
socket.on('data', spark.emits('data'));
});
//
// Listen to upgrade requests.
//
this.on('upgrade', function upgrade(req, socket, head) {
this.service.handleUpgrade(req, socket, head);
}).on('request', function request(req, res) {
this.service.handleRequest(req, res);
});
};
|
Make sure we're listing to the right event
|
[minor] Make sure we're listing to the right event
|
JavaScript
|
mit
|
modulexcite/primus,primus/primus,primus/primus,basarat/primus,clanwqq/primus,STRML/primus,colinbate/primus,dercodebearer/primus,colinbate/primus,dercodebearer/primus,primus/primus,clanwqq/primus,dercodebearer/primus,colinbate/primus,modulexcite/primus,basarat/primus,STRML/primus,modulexcite/primus,beni55/primus,STRML/primus,beni55/primus,beni55/primus,clanwqq/primus,basarat/primus
|
18a8ea8eaac3b0ec2f1868d1b9961f3befd6df78
|
v3/buildUtils/webpack.plugins.js
|
v3/buildUtils/webpack.plugins.js
|
// webpack.plugins.js
"use strict";
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const UglifyJsWebpackPlugin = require("uglifyjs-webpack-plugin");
const config = {
plugins: [
new ExtractTextPlugin({
filename: "[name].css"
}),
new UglifyJsWebpackPlugin({
uglifyOptions: {
compress: {
drop_console: true,
},
output: {
comments: false,
beautify: false
}
}
})
]
};
module.exports = config;
|
// webpack.plugins.js
"use strict";
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const UglifyJsWebpackPlugin = require("uglifyjs-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CleanWebpackPlugin = require("clean-webpack-plugin");
const commonPaths = require("./commonPaths");
const config = {
plugins: [
new ExtractTextPlugin({
filename: "[name].bundle.css"
}),
/* new UglifyJsWebpackPlugin({
uglifyOptions: {
compress: {
drop_console: true,
},
output: {
comments: false,
beautify: false
}
}
}) */
new HtmlWebpackPlugin({
title: "test HtmlWebpackPlugin"
}),
new CleanWebpackPlugin([commonPaths.outputPath], {
root: commonPaths.webpackConfigPath
})
]
};
module.exports = config;
|
Edit filename for ExtractTextPlugin. Added HtmlWebpackPlugin, CleanWebpackPlugin
|
Edit filename for ExtractTextPlugin. Added HtmlWebpackPlugin, CleanWebpackPlugin
|
JavaScript
|
mit
|
var-bin/webpack-training,var-bin/webpack-training,var-bin/webpack-training,var-bin/webpack-training
|
9130da003fb1623b8fc1eb6eeb8bb1573ac8dece
|
lib/World.js
|
lib/World.js
|
let path = require('path'),
utils = require('./utils'),
Region = require('./Region');
module.exports = class World {
constructor(worldPath) {
this.worldPath = worldPath;
this.regionPath = path.join(worldPath, "region");
this.playerPath = path.join(worldPath, "playerdata");
this.regions = {};
}
getRegion(position) {
let regionFilename = utils.regionFilenameFromPosition(position);
if (regionFilename in this.regions === false) {
let fullpath = path.join(this.regionPath, regionFilename);
this.regions[regionFilename] = Region.fromFile(fullpath, utils.regionXZFromPosition(position));
}
return this.regions[regionFilename];
}
};
|
let fs = require('fs'),
path = require('path'),
utils = require('./utils'),
Region = require('./Region');
module.exports = class World {
constructor(worldPath) {
this.worldPath = worldPath;
this.regionPath = path.join(worldPath, "region");
this.playerPath = path.join(worldPath, "playerdata");
this.regions = {};
}
getRegion(position) {
let regionFilename = utils.regionFilenameFromPosition(position);
if (regionFilename in this.regions === false) {
let fullpath = path.join(this.regionPath, regionFilename);
this.regions[regionFilename] = Region.fromFile(fullpath, utils.regionXZFromPosition(position));
}
return this.regions[regionFilename];
}
getRegions() {
return fs.readdirSync(this.regionPath)
.filter(file => /^r\.-?\d+\.-?\d+\.mca$/.test(file))
.map(file => {
let fullPath = path.join(this.regionPath, file);
let parts = file.split(".");
let x = parseInt(parts[1], 10);
let z = parseInt(parts[2], 10);
// TODO: use regions cache
return Region.fromFile(fullPath, {x: x, z: z});
});
}
};
|
Add ability to return all regions
|
Add ability to return all regions
This walks the region’s directory and returns a Region instance for each .mca file in that directory.
|
JavaScript
|
bsd-3-clause
|
thelonious/kld-mc-world
|
722bd5f6636d448c7b95d636e99726a4c21d9c9f
|
src/components/datagrid.js
|
src/components/datagrid.js
|
var fs = require('fs');
module.exports = function (app) {
app.config([
'formioComponentsProvider',
function(formioComponentsProvider) {
formioComponentsProvider.register('datagrid', {
title: 'Data Grid',
template: 'formio/components/datagrid.html',
settings: {
input: true,
components: [],
tableView: true,
label: '',
key: 'datagrid',
protected: false,
persistent: true
}
});
}
]);
app.controller('formioDataGrid', [
'$scope',
function($scope) {
$scope.data[$scope.component.key] = $scope.data[$scope.component.key] || [{}];
$scope.addRow = function() {
$scope.data[$scope.component.key].push({});
};
$scope.removeRow = function(index) {
$scope.data[$scope.component.key].splice(index, 1);
};
}
]);
app.run([
'$templateCache',
'FormioUtils',
function($templateCache, FormioUtils) {
$templateCache.put('formio/components/datagrid.html', FormioUtils.fieldWrap(
fs.readFileSync(__dirname + '/../templates/components/datagrid.html', 'utf8')
));
}
]);
};
|
var fs = require('fs');
module.exports = function (app) {
app.config([
'formioComponentsProvider',
function(formioComponentsProvider) {
formioComponentsProvider.register('datagrid', {
title: 'Data Grid',
template: 'formio/components/datagrid.html',
settings: {
input: true,
tree: true,
components: [],
tableView: true,
label: '',
key: 'datagrid',
protected: false,
persistent: true
}
});
}
]);
app.controller('formioDataGrid', [
'$scope',
function($scope) {
$scope.data[$scope.component.key] = $scope.data[$scope.component.key] || [{}];
$scope.addRow = function() {
$scope.data[$scope.component.key].push({});
};
$scope.removeRow = function(index) {
$scope.data[$scope.component.key].splice(index, 1);
};
}
]);
app.run([
'$templateCache',
'FormioUtils',
function($templateCache, FormioUtils) {
$templateCache.put('formio/components/datagrid.html', FormioUtils.fieldWrap(
fs.readFileSync(__dirname + '/../templates/components/datagrid.html', 'utf8')
));
}
]);
};
|
Add tree to fix formio-util dependency.
|
Add tree to fix formio-util dependency.
|
JavaScript
|
mit
|
formio/ngFormio,Kelsus/ngFormio,Kelsus/ngFormio
|
12eede4a14e74957d1ad86a9a83807442f90fdd4
|
lib/measure-avenir.js
|
lib/measure-avenir.js
|
var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var cssstats = require('cssstats')
var module = require('tachyons-typography/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-typography/tachyons-typography.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)
var srcCSS = fs.readFileSync('./src/_typography.css', 'utf8')
var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8')
var template = fs.readFileSync('./templates/docs/measure/avenir-next/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
moduleVersion: module.version,
moduleSize: moduleSize,
moduleObj: moduleObj,
srcCSS: srcCSS,
navDocs: navDocs
})
fs.writeFileSync('./docs/typography/measure/avenir-next/index.html', html)
|
var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var cssstats = require('cssstats')
var module = require('tachyons-typography/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-typography/tachyons-typography.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)
var srcCSS = fs.readFileSync('./src/_typography.css', 'utf8')
var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8')
var siteFooter = fs.readFileSync('./templates/footer.html', 'utf8')
var template = fs.readFileSync('./templates/docs/measure/avenir-next/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
moduleVersion: module.version,
moduleSize: moduleSize,
moduleObj: moduleObj,
srcCSS: srcCSS,
navDocs: navDocs,
siteFooter: siteFooter
})
fs.writeFileSync('./docs/typography/measure/avenir-next/index.html', html)
|
Add site footer to each documentation generator
|
Add site footer to each documentation generator
|
JavaScript
|
mit
|
fenderdigital/css-utilities,fenderdigital/css-utilities,pietgeursen/pietgeursen.github.io,tachyons-css/tachyons,topherauyeung/portfolio,topherauyeung/portfolio,getfrank/tachyons,topherauyeung/portfolio,cwonrails/tachyons,matyikriszta/moonlit-landing-page
|
501491a520c617e3a9f759f31cdfc479f7e5fe96
|
hardware/index.js
|
hardware/index.js
|
var EventEmitter = require('events').EventEmitter;
var hardware = module.exports = new EventEmitter();
//var e = nobleEmitter.connect(peripheralUuid, serviceUuid, characteristicUuid);
var e = (process.env.DEVICE) ?
require('./serial')(process.env.DEVICE) :
require('./stdin-mock');
var commands = {
0: function () {
emitScore('a'); // single click
},
1: function () {
emitScore('b'); // single click
},
2: function () {
emitUndo('a'); // double click
},
3: function () {
emitUndo('b'); // double click
},
4: function () {
hardware.emit('restart'); // long press
},
5: function () {
hardware.emit('restart'); // long press
}
};
e.on('connected', function () {
console.log('ble connected');
hardware.emit('connected');
});
e.on('data', function (data) {
console.log('data: ', data);
if(commands[data])
commands[data]();
else
console.log('unknown command "' + data + '"');
});
e.on('disconnected', function () {
console.log('ble disconnected');
hardware.emit('disconnected');
});
function emitScore (side) {
hardware.emit('score', { side: side });
}
function emitUndo (side) {
hardware.emit('undo', { side: side });
}
|
var EventEmitter = require('events').EventEmitter;
var hardware = module.exports = new EventEmitter();
var e = (process.env.DEVICE) ?
require('./serial')(process.env.DEVICE) :
require('./stdin-mock');
var commands = {
0: function () {
emitScore('a'); // single click
},
1: function () {
emitScore('b'); // single click
},
2: function () {
emitUndo('a'); // double click
},
3: function () {
emitUndo('b'); // double click
},
4: function () {
hardware.emit('restart'); // long press
},
5: function () {
hardware.emit('restart'); // long press
}
};
e.on('connected', function () {
console.log('ble connected');
hardware.emit('connected');
});
e.on('data', function (data) {
console.log('data: ', data);
if(commands[data])
commands[data]();
else
console.log('unknown command "' + data + '"');
});
e.on('disconnected', function () {
console.log('ble disconnected');
hardware.emit('disconnected');
});
function emitScore (side) {
hardware.emit('score', { side: side });
}
function emitUndo (side) {
hardware.emit('undo', { side: side });
}
|
Remove unused noble emitter code
|
Remove unused noble emitter code
|
JavaScript
|
mit
|
bekk/bekkboard,bekk/bekkboard,bekk/bekkboard,bekk/bekkboard
|
9d5975acddb3dcf1851ea2c5bb2fc38ce7e42a5b
|
src/PublicApi.js
|
src/PublicApi.js
|
'use strict';
const Engine = require('./Engine');
const PublicSelect = require('./public/PublicSelect');
const PublicApiOptions = require('./PublicApiOptions');
const Explainer = require('./Explainer');
class PublicApi
{
/**
*
* @param {PublicApiOptions} options
*/
constructor(options = new PublicApiOptions)
{
if (options instanceof PublicApiOptions) {
this.options = options;
} else {
this.options = new PublicApiOptions(options);
}
this.engine = new Engine();
}
/**
*
* @param {string} sql
* @returns {PublicSelect}
*/
query(sql)
{
return new PublicSelect(this.engine.createQuery(sql, this.options), this.options.dataSourceResolvers);
}
explain(select)
{
const e = new Explainer();
return e.createExplain(select);
}
}
PublicApi.DataSourceResolver = require('./DataSourceResolver');
PublicApi.exceptions = {
JlException: require('./error/JlException'),
SqlFunctionArgumentError: require('./error/SqlFunctionArgumentError'),
SqlLogicError: require('./error/SqlLogicError'),
SqlNotSupported: require('./error/SqlNotSupported'),
JsonParsingError: require('./error/JsonParsingError'),
DataSourceNotFound: require('./error/DataSourceNotFound')
};
module.exports = PublicApi;
|
'use strict';
const Engine = require('./Engine');
const PublicSelect = require('./public/PublicSelect');
const PublicApiOptions = require('./PublicApiOptions');
const Explainer = require('./Explainer');
class PublicApi
{
/**
*
* @param {PublicApiOptions} options
*/
constructor(options = new PublicApiOptions)
{
if (options instanceof PublicApiOptions) {
this.options = options;
} else {
this.options = new PublicApiOptions(options);
}
this.engine = new Engine();
}
/**
*
* @param {string} sql
* @returns {PublicSelect}
*/
query(sql)
{
return new PublicSelect(this.engine.createQuery(sql, this.options), this.options.dataSourceResolvers);
}
explain(select)
{
const e = new Explainer();
return e.createExplain(select);
}
}
PublicApi.DataSourceResolver = require('./DataSourceResolver');
PublicApi.exceptions = {
JlException: require('./error/JlException'),
SqlFunctionArgumentError: require('./error/SqlFunctionArgumentError'),
SqlLogicError: require('./error/SqlLogicError'),
SqlNotSupported: require('./error/SqlNotSupported'),
JsonParsingError: require('./error/JsonParsingError'),
DataSourceNotFound: require('./error/DataSourceNotFound')
};
PublicApi.version = require('../package.json').version;
module.exports = PublicApi;
|
Add `version` field in exports
|
Add `version` field in exports
|
JavaScript
|
mit
|
avz/node-jl-sql-api
|
30aa7fc0d67a049d0ce3c14856226a1c25d376e9
|
lib/http/endpoints/announce.js
|
lib/http/endpoints/announce.js
|
/**
* Based on specs at: http://wiki.theory.org/BitTorrent_Tracker_Protocol
*/
function announceHandler(req, res) {
console.log(req);
res.end('stub');
}
function register(server) {
server.get('/announce', announceHandler);
}
exports.register = register;
|
/**
* Based on specs at: http://wiki.theory.org/BitTorrent_Tracker_Protocol
*/
var async = require('async');
var httpUtil = require('util/http');
var flowCtrl = require('util/flow-ctrl');
var log = require('logmagic').local('bittorrent-tracker.lib.http.endpoints.announce');
function announceHandler(req, res) {
if (req.method !== 'GET') {
httpUtil.returnError(res, 100, null);
}
res.end('stub');
}
function register(server) {
server.all('/announce', async.apply(flowCtrl.captureAndLogError,
log, announceHandler, null));
}
exports.register = register;
|
Return error if the method is not GET.
|
Return error if the method is not GET.
|
JavaScript
|
bsd-3-clause
|
Kami/node-bittorrent-tracker,Kami/node-bittorrent-tracker
|
1623531764f7b044f9593f74e0c344c833ceac99
|
src/credit-card.js
|
src/credit-card.js
|
const { GraphQLScalarType } = require('graphql')
const cc = require('credit-card')
function parse (value) {
const {
card,
validCardNumber,
validCvv: validCVV,
validExpiryMonth,
validExpiryYear,
isExpired
} = cc.validate(getPayload())
if (validCardNumber) {
return Object.assign(card, {
validCVV,
validExpiryMonth,
validExpiryYear,
isExpired
})
}
function getPayload () {
switch (typeof value) {
case 'string':
case 'number': {
const cardType = cc.determineCardType(value.toString())
return {
number: value.toString(),
cardType
}
}
default: return Object.assign({ cardType: value.cardType || value.type }, value)
}
}
}
module.exports = new GraphQLScalarType({
name: 'CreditCard',
serialize: parse,
parseValue: parse,
parseLiteral (ast) {
return parse(ast.value)
}
})
|
const { GraphQLScalarType } = require('graphql')
const cc = require('credit-card')
function parse (value) {
const {
card,
validCardNumber,
validCvv: validCVV,
validExpiryMonth,
validExpiryYear,
isExpired
} = cc.validate(getPayload())
if (validCardNumber) {
return Object.assign(card, {
validCVV,
validExpiryMonth,
validExpiryYear,
isExpired
})
}
function getPayload () {
switch (typeof value) {
case 'string':
case 'number': {
const number = value.toString().replace(/\D/g, '')
const cardType = cc.determineCardType(number)
return {
number,
cardType
}
}
default: return Object.assign({}, value, {
number: value.number.toString().replace(/\D/g, ''),
cardType: value.cardType || value.type
})
}
}
}
module.exports = new GraphQLScalarType({
name: 'CreditCard',
serialize: parse,
parseValue: parse,
parseLiteral (ast) {
return parse(ast.value)
}
})
|
Remove spaces from credit card
|
Remove spaces from credit card
|
JavaScript
|
mit
|
mfix22/gnt
|
cd998cac866f0e0e820099534f2ecfaf1038468c
|
app/assets/javascripts/nail_polish/utils/subview_manager.js
|
app/assets/javascripts/nail_polish/utils/subview_manager.js
|
NailPolish.SubviewManager = {
renderEach: function (subviews) {
this._subviews = subviews;
_.each(subviews, function (view) {
view.parent = view.parent || this.defaultParent();
view.repository = view.repository || this.repository;
view.render();
}.bind(this));
},
remove: function() {
this.removeSelf();
_.each(this._subviews, function(subview) {
subview.remove();
});
},
removeSelf: function() { /* override me */ },
defaultParent: function() { return this },
};
|
NailPolish.SubviewManager = {
renderEach: function (subviews) {
this._subviews = subviews;
_.each(subviews, function (view) {
if(view) {
view.parent = view.parent || this.defaultParent();
view.repository = view.repository || this.repository;
view.render();
}
}.bind(this));
},
remove: function() {
this.removeSelf();
_.each(this._subviews, function(subview) {
if (subview){
subview.remove();
}
});
},
removeSelf: function() { /* override me */ },
defaultParent: function() {
return this;
}
};
|
Add a gaurd clause for IE8 compatibility in subview rendering
|
Add a gaurd clause for IE8 compatibility in subview rendering
|
JavaScript
|
mit
|
socialchorus/nail_polish,socialchorus/nail_polish,socialchorus/nail_polish
|
587386215a25ebd49761d336f97ab9b04b8dd1dc
|
lib/node_modules/@stdlib/math/base/special/dirchlet-eta/lib/index.js
|
lib/node_modules/@stdlib/math/base/special/dirchlet-eta/lib/index.js
|
'use strict';
// MODULES //
var powm1 = require( '@stdlib/math/base/special/powm1' );
var zeta = require( '@stdlib/math/base/special/riemann-zeta' );
var LN2 = require( '@stdlib/math/constants/float64-ln2' );
// ETA //
/**
* FUNCTION: eta( s )
* Evaluates the Dirichlet eta function.
*
* @param {Number} s - input value
* @returns {Number} function value
*/
function eta( s ) {
if ( s !== s ) {
return NaN;
}
if ( s === 1 ) {
// Alternating harmonic series...
return LN2;
}
return -powm1( 2, 1-s ) * zeta( s );
} // end FUNCTION eta()
// EXPORTS //
module.exports = eta;
|
'use strict';
// MODULES //
var isnan = require( '@stdlib/math/base/utils/is-nan' );
var powm1 = require( '@stdlib/math/base/special/powm1' );
var zeta = require( '@stdlib/math/base/special/riemann-zeta' );
var LN2 = require( '@stdlib/math/constants/float64-ln2' );
// ETA //
/**
* FUNCTION: eta( s )
* Evaluates the Dirichlet eta function.
*
* @param {Number} s - input value
* @returns {Number} function value
*/
function eta( s ) {
if ( isnan( s ) ) {
return NaN;
}
if ( s === 1 ) {
// Alternating harmonic series...
return LN2;
}
return -powm1( 2, 1-s ) * zeta( s );
} // end FUNCTION eta()
// EXPORTS //
module.exports = eta;
|
Use base util is-nan to check for NaN value
|
Use base util is-nan to check for NaN value
|
JavaScript
|
apache-2.0
|
stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib
|
858675611a4bffd130eea17cba35a698a093cb43
|
src/app/index.js
|
src/app/index.js
|
import { Base } from 'yeoman-generator';
import generatorArguments from './arguments';
import generatorOptions from './options';
import generatorSteps from './steps';
export default class ServicesGenerator extends Base {
constructor(...args) {
super(...args);
Object.keys(generatorArguments).forEach(key => this.argument(key, generatorArguments[key]));
Object.keys(generatorOptions).forEach(key => this.option(key, generatorOptions[key]));
}
get configuring() {
return generatorSteps.configuring;
}
get conflicts() {
return generatorSteps.conflicts;
}
get default() {
return generatorSteps.default;
}
get end() {
return generatorSteps.end;
}
get initializing() {
return generatorSteps.initializing
}
get install() {
return generatorSteps.install;
}
get prompting() {
return generatorSteps.prompting
}
get writing() {
return generatorSteps.writing;
}
}
|
import { Base } from 'yeoman-generator';
import generatorArguments from './arguments';
import generatorOptions from './options';
import generatorSteps from './steps';
export default class AppGenerator extends Base {
constructor(...args) {
super(...args);
Object.keys(generatorArguments).forEach(key => this.argument(key, generatorArguments[key]));
Object.keys(generatorOptions).forEach(key => this.option(key, generatorOptions[key]));
}
get configuring() {
return generatorSteps.configuring;
}
get conflicts() {
return generatorSteps.conflicts;
}
get default() {
return generatorSteps.default;
}
get end() {
return generatorSteps.end;
}
get initializing() {
return generatorSteps.initializing
}
get install() {
return generatorSteps.install;
}
get prompting() {
return generatorSteps.prompting
}
get writing() {
return generatorSteps.writing;
}
}
|
Rename export class for app generator
|
Rename export class for app generator
|
JavaScript
|
mit
|
italoag/generator-sails-rest-api,ghaiklor/generator-sails-rest-api,konstantinzolotarev/generator-trails,IncoCode/generator-sails-rest-api,ghaiklor/generator-sails-rest-api,italoag/generator-sails-rest-api,tnunes/generator-trails,jaumard/generator-trails
|
9ab94feb518c518816bd64a4e0e811dfedb3c428
|
katas/libraries/hamjest/assertThat.js
|
katas/libraries/hamjest/assertThat.js
|
// 1: assertThat
// To do: make all tests pass, leave the assert lines unchanged!
import {
assertThat, equalTo,
containsString, throws, returns,
} from 'hamjest';
describe('The core function, `assertThat()`', () => {
it('is a function', () => {
const typeOfAssertThat = typeof assertThat;
assertThat(typeOfAssertThat, equalTo('function'));
});
describe('requires at least two params', () => {
it('1st: the actual value', () => {
const expected = equalTo('actual');
assertThat('actual', expected);
});
it('2nd: a matcher for the expected value', () => {
const matcher = equalTo('expected');
assertThat('expected', matcher);
});
describe('the optional 3rd param', () => {
it('goes first(!), and is the assertion reason', () => {
const reason = 'This is the reason, the first `assertThat()` throws as part of its message.';
try {
assertThat(reason, true, equalTo(false));
} catch (e) {
assertThat(e.message, containsString(reason));
}
});
});
});
describe('under the hood, it does', () => {
it('nothing, WHEN actual and expected match (using the given matcher)', () => {
const passingTest = () => assertThat(true, equalTo(true));
assertThat(passingTest, returns());
});
it('throw an assertion, WHEN actual and expected don`t match', () => {
const failingTest = () => assertThat(false, equalTo(true));
assertThat(failingTest, throws());
});
});
});
|
// 1: assertThat
// To do: make all tests pass, leave the assert lines unchanged!
import {
assertThat, equalTo,
containsString, throws, returns,
} from 'hamjest';
describe('The core function, `assertThat()`', () => {
it('is a function', () => {
const typeOfAssertThat = typeof assertThat;
assertThat(typeOfAssertThat, equalTo('function'));
});
describe('requires at least two params', () => {
it('1st: the actual value', () => {
const actual = 'actual';
const expected = equalTo('actual');
assertThat(actual, expected);
});
it('2nd: a matcher for the expected value', () => {
const matcher = equalTo('expected');
assertThat('expected', matcher);
});
describe('the optional 3rd param', () => {
it('goes first(!), and is the assertion reason', () => {
let caughtError;
const reason = 'This is the reason, the first `assertThat()` throws as part of its message.';
try {
assertThat(reason, true, equalTo(false));
} catch (e) {
caughtError = e;
}
assertThat(caughtError.message, containsString(reason));
});
});
});
describe('under the hood, it does', () => {
it('nothing, WHEN actual and expected match (using the given matcher)', () => {
const passingTest = () => assertThat(true, equalTo(true));
assertThat(passingTest, returns());
});
it('throw an assertion, WHEN actual and expected don`t match', () => {
const failingTest = () => assertThat(false, equalTo(true));
assertThat(failingTest, throws());
});
});
});
|
Prepare for making it a kata.
|
Prepare for making it a kata.
|
JavaScript
|
mit
|
tddbin/katas,tddbin/katas,tddbin/katas
|
9e01d0685c4299920360389c255c14c3a59477ce
|
public/javascripts/application.js
|
public/javascripts/application.js
|
// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
|
// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
if (!Date.now) {
Date.now = function() {
return (new Date()).getTime();
};
}
function updateClock() {
var el = $("uhr");
var time = new Date();
var hours = time.getHours(),
minutes = time.getMinutes(),
seconds = time.getSeconds();
if (hours < 10)
hours = "0" + hours;
if (minutes < 10)
minutes = "0" + minutes;
if (seconds < 10)
seconds = "0" + seconds;
el.update("<p>" + hours + ":" + minutes + ":" + seconds + "</p>");
}
document.observe("dom:loaded", function(ev) {
if ($("uhr")) {
window.setInterval(updateClock, 1000);
}
})
|
Make the clock on the frontpage work.
|
Make the clock on the frontpage work.
|
JavaScript
|
mit
|
bt4y/bulletin_board,bt4y/bulletin_board
|
7cd25460f396d904fecb0c877f8ea06619994c38
|
blueprints/ember-websockets/index.js
|
blueprints/ember-websockets/index.js
|
module.exports = {
normalizeEntityName: function() {},
afterInstall: function() {
return this.addBowerPackageToProject('uri.js');
}
};
|
module.exports = {
normalizeEntityName: function() {},
afterInstall: function() {
var installContext = this;
return this.addPackageToProject('mock-socket').then(function() {
return installContext.addBowerPackageToProject('urijs');
});
}
};
|
Fix install issue with ember install ember-websockets
|
Fix install issue with ember install ember-websockets
|
JavaScript
|
mit
|
thoov/ember-websockets,thoov/ember-websockets
|
21ec0674ea25ea1d3df33fec7b825644162f1b58
|
src/components/EditActivityForm.js
|
src/components/EditActivityForm.js
|
import React, { Component, PropTypes } from 'react';
class EditActivityForm extends Component {
componentDidMount() {
this.description.focus();
}
updateActivity(e) {
e.preventDefault();
const activity = {
description: this.description.value,
timestamp: this.props.timestamp,
}
this.props.updateActivity(activity);
this.props.cancelEdit();
}
render() {
return (
<div className="row row--middle row--start">
<form
className="col--12"
onSubmit={(e) => this.updateActivity(e)}
ref={(input) => this.activityForm = input}
>
<div className="row row--middle">
<div className="col--6">
<input
type="text"
className="w--100 pv- ph-"
ref={(node) => this.description = node}
defaultValue={this.props.activity.description}
placeholder="went to the park"
/>
</div>
<div className="col--2">
<button type="submit">Update</button>
</div>
<div className="col--2">
<div onClick={this.props.cancelEdit}>cancel</div>
</div>
</div>
</form>
</div>
);
}
}
EditActivityForm.propTypes = {
updateActivity: PropTypes.func.isRequired,
cancelEdit: PropTypes.func.isRequired,
activity: PropTypes.object.isRequired,
};
export default EditActivityForm;
|
import React, { Component, PropTypes } from 'react';
import { getDescriptionAndTags, buildDescriptionAndTags } from '../helpers';
class EditActivityForm extends Component {
componentDidMount() {
this.description.focus();
}
updateActivity(e) {
e.preventDefault();
const { description, tags } = getDescriptionAndTags(this.description.value);
const activity = {
description,
tags,
timestamp: this.props.timestamp,
}
this.props.updateActivity(activity);
this.props.cancelEdit();
}
render() {
const { activity } = this.props;
const { description, tags } = activity;
return (
<div className="row row--middle row--start">
<form
className="col--12"
onSubmit={(e) => this.updateActivity(e)}
ref={(input) => this.activityForm = input}
>
<div className="row row--middle">
<div className="col--6">
<input
type="text"
className="w--100 pv- ph-"
ref={(node) => this.description = node}
defaultValue={buildDescriptionAndTags(description, tags)}
placeholder="went to the park"
/>
</div>
<div className="col--2">
<button type="submit">Update</button>
</div>
<div className="col--2">
<div onClick={this.props.cancelEdit}>cancel</div>
</div>
</div>
</form>
</div>
);
}
}
EditActivityForm.propTypes = {
updateActivity: PropTypes.func.isRequired,
cancelEdit: PropTypes.func.isRequired,
activity: PropTypes.object.isRequired,
};
export default EditActivityForm;
|
Edit tags in edit form input
|
Edit tags in edit form input
|
JavaScript
|
mit
|
mknudsen01/today,mknudsen01/today
|
cb33b14464bf23b36f0d1499c7a4cfde95f85f80
|
src/actions/Placeholder.js
|
src/actions/Placeholder.js
|
import { Action } from './../lib/Action';
import { Util } from '@aegis-framework/artemis';
export class Placeholder extends Action {
static matchString ([ action ]) {
return action === '$';
}
constructor ([action, name]) {
super ();
this.name = name;
this.action = this.engine.$ (name);
}
willApply () {
if (this.name.indexOf ('_') === 0) {
return Util.callAsync (this.action, this.engine).then ((action) => {
this.action = action;
return Promise.resolve ();
});
}
return Promise.resolve ();
}
apply () {
return this.engine.run (this.action);
}
revert () {
return this.engine.revert (this.action);
}
}
Placeholder.id = 'Placeholder';
export default Placeholder;
|
import { Action } from './../lib/Action';
import { Util } from '@aegis-framework/artemis';
export class Placeholder extends Action {
static matchString ([ action ]) {
return action === '$';
}
constructor ([action, name, ...args]) {
super ();
this.name = name;
this.action = this.engine.$ (name);
this.arguments = args;
}
willApply () {
if (this.name.indexOf ('_') === 0) {
return Util.callAsync (this.action, this.engine, ...this.arguments).then ((action) => {
this.action = action;
return Promise.resolve ();
});
}
return Promise.resolve ();
}
apply () {
return this.engine.run (this.action);
}
revert () {
return this.engine.revert (this.action);
}
}
Placeholder.id = 'Placeholder';
export default Placeholder;
|
Allow passing arguments to dynamic placeholders
|
Allow passing arguments to dynamic placeholders
|
JavaScript
|
mit
|
MonogatariVN/Monogatari,MonogatariVN/Monogatari,Monogatari/Monogatari
|
e3c1f2162caf735f6ba8324d698445929ecac248
|
js/application.js
|
js/application.js
|
/*global document, Reveal, carousel*/
(function(document, Reveal, carousel){
'use strict';
Reveal.addEventListener('carousel', function(){
var container = document.getElementById('carousel');
carousel.show(['aap', 'noot', 'mies'], container);
});
})(document, Reveal, carousel);
|
/*global document, Reveal, carousel*/
(function(document, Reveal, carousel){
'use strict';
Reveal.addEventListener('carousel', function(){
var container = document.getElementById('carousel');
var languages = [
'Ada',
'BBx',
'C',
'CFML',
'Clojure',
'Common Lisp',
'Groovy',
'JavaScript',
'Oberon',
'Oxygene',
'Pascal',
'Perl',
'Prolog',
'Python',
'REXX',
'Ruby',
'Scala',
'Scheme',
'Tcl',
];
carousel.show(languages, container);
});
})(document, Reveal, carousel);
|
Use JVM languages for carousel
|
Use JVM languages for carousel
|
JavaScript
|
mit
|
dvberkel/polyglot-programming-on-jvm,dvberkel/polyglot-programming-on-jvm
|
d30faa1e9f1e76715fec1f026d712ea11576af58
|
src/component.js
|
src/component.js
|
import { select, local } from "d3-selection";
var componentLocal = local(),
noop = function (){};
export default function (tagName, className){
var create,
render = noop,
destroy = noop,
selector = className ? "." + className : tagName;
function component(selection, props){
var update = selection.selectAll(selector)
.data(Array.isArray(props) ? props : [props]),
exit = update.exit(),
enter = update.enter().append(tagName).attr("class", className);
enter.each(function (){
componentLocal.set(this, {
selection: select(this)
});
});
if(create){
enter.each(function (){
var local = componentLocal.get(this);
local.state = {};
local.render = noop;
create(function setState(state){
Object.assign(local.state, state);
local.render();
});
});
enter.merge(update).each(function (props){
var local = componentLocal.get(this);
if(local.render === noop){
local.render = function (){
render(local.selection, local.props, local.state);
};
}
local.props = props;
local.render();
});
exit.each(function (){
destroy(componentLocal.get(this).state);
});
} else {
enter.merge(update).each(function (props){
render(componentLocal.get(this).selection, props);
});
}
exit.remove();
}
component.render = function(_) { return (render = _, component); };
component.create = function(_) { return (create = _, component); };
component.destroy = function(_) { return (destroy = _, component); };
return component;
};
|
import { select, local } from "d3-selection";
var componentLocal = local(),
noop = function (){};
export default function (tagName, className){
var create,
render = noop,
destroy = noop,
selector = className ? "." + className : tagName;
function component(selection, props){
var update = selection.selectAll(selector)
.data(Array.isArray(props) ? props : [props]),
exit = update.exit(),
enter = update.enter().append(tagName).attr("class", className);
enter.each(function (){
var local = componentLocal.set(this, {
selection: select(this),
state: {},
render: noop
});
if(create){
create(function setState(state){
Object.assign(local.state, state);
local.render();
});
}
});
enter.merge(update).each(function (props){
var local = componentLocal.get(this);
if(local.render === noop){
local.render = function (){
render(local.selection, local.props, local.state);
};
}
local.props = props;
local.render();
});
exit.each(function (){
destroy(componentLocal.get(this).state);
});
exit.remove();
}
component.render = function(_) { return (render = _, component); };
component.create = function(_) { return (create = _, component); };
component.destroy = function(_) { return (destroy = _, component); };
return component;
};
|
Unify cases of create and no create
|
Unify cases of create and no create
|
JavaScript
|
bsd-3-clause
|
curran/d3-component
|
f49a0fb3b6271061be2808495cbbb180770fff60
|
app/renderer/components/libraries/channel-request.js
|
app/renderer/components/libraries/channel-request.js
|
var ChannelRequest, Promise, refreshProviderObject, stopLongPolling, timeoutID;
Promise = require('bluebird');
refreshProviderObject = null;
ChannelRequest = (function() {
function ChannelRequest(channelName1, callback1) {
this.channelName = channelName1;
this.callback = callback1;
this.stopLongPolling = false;
if (this.channelName == null) {
throw new Error('Channel request needs of a channelName');
}
if (typeof this.callback !== 'function') {
throw new Error('Channel request needs of a callback function');
}
}
var startRefreshProvider = function(channelName, callback) {
return new Promise(function(resolve, reject) {
return callback(channelName, function(err) {
if (err) {
reject(err);
}
return resolve();
});
});
};
ChannelRequest.prototype.startLongPolling = function(miliseconds) {
if (!!this.stopLongPolling) {
clearTimeout(timeoutID);
return;
}
var self = this;
refreshProviderObject = startRefreshProvider(this.channelName, this.callback);
return refreshProviderObject.then(function() {
timeoutID = setTimeout(function() {
return self.startLongPolling(miliseconds);
}, miliseconds);
if (!!self.stopLongPolling) {
clearTimeout(timeoutID);
return;
}
}).catch(function(err) {
return console.error(err);
});
};
return ChannelRequest;
})();
export default ChannelRequest;
|
var ChannelRequest, Promise, refreshProviderObject, stopLongPolling, timeoutID;
Promise = require('bluebird');
refreshProviderObject = null;
ChannelRequest = (function() {
function ChannelRequest(channelName1, callback1) {
this.channelName = channelName1;
this.callback = callback1;
this.stopLongPolling = false;
if (this.channelName == null) {
throw new Error('Channel request needs of a channelName');
}
if (typeof this.callback !== 'function') {
throw new Error('Channel request needs of a callback function');
}
}
var startRefreshProvider = function(channelName, callback) {
return new Promise(function(resolve, reject) {
return callback(channelName, function(err) {
if (err) {
reject(new Error(err));
}
return resolve();
});
});
};
ChannelRequest.prototype.startLongPolling = function(miliseconds) {
if (!!this.stopLongPolling) {
clearTimeout(timeoutID);
return;
}
var self = this;
refreshProviderObject = startRefreshProvider(this.channelName, this.callback);
return refreshProviderObject.then(function() {
timeoutID = setTimeout(function() {
return self.startLongPolling(miliseconds);
}, miliseconds);
if (!!self.stopLongPolling) {
clearTimeout(timeoutID);
return;
}
}).catch(function(err) {
return err;
});
};
return ChannelRequest;
})();
export default ChannelRequest;
|
Return an error in ChannelRequest library
|
Return an error in ChannelRequest library
|
JavaScript
|
mit
|
willmendesneto/build-checker-app,willmendesneto/build-checker-app
|
62bf3607a8191925a2eb3b4a71693234dcaf5646
|
src/Oro/Bundle/UserBundle/Resources/public/js/models/role/access-levels-collection.js
|
src/Oro/Bundle/UserBundle/Resources/public/js/models/role/access-levels-collection.js
|
define(function(require) {
'use strict';
var AccessLevelsCollection;
var _ = require('underscore');
var RoutingCollection = require('oroui/js/app/models/base/routing-collection');
AccessLevelsCollection = RoutingCollection.extend({
routeDefaults: {
routeName: 'oro_security_access_levels'
},
parse: function(resp, options) {
return _.map(_.pairs(resp), function(item) {
return {access_level: item[0], access_level_label: item[1]};
});
}
});
return AccessLevelsCollection;
});
|
define(function(require) {
'use strict';
var AccessLevelsCollection;
var _ = require('underscore');
var RoutingCollection = require('oroui/js/app/models/base/routing-collection');
AccessLevelsCollection = RoutingCollection.extend({
routeDefaults: {
routeName: 'oro_security_access_levels'
},
parse: function(resp, options) {
return _.map(_.pairs(resp), function(item) {
return {access_level: parseInt(item[0], 10), access_level_label: item[1]};
});
}
});
return AccessLevelsCollection;
});
|
Fix issues found on demo
|
BAP-10897: Fix issues found on demo
|
JavaScript
|
mit
|
geoffroycochard/platform,orocrm/platform,trustify/oroplatform,geoffroycochard/platform,trustify/oroplatform,orocrm/platform,Djamy/platform,orocrm/platform,trustify/oroplatform,geoffroycochard/platform,Djamy/platform,Djamy/platform
|
07279ef62b8c745f7d6d5e57f6166cd6125ee1c1
|
server/discord/cogs/ping/index.js
|
server/discord/cogs/ping/index.js
|
const client = require('./../../');
module.exports.info = {
aliases: [
'ping',
'pong'
]
};
module.exports.command = message =>
message.channel.createMessage(`\`\`\`\n${client.shards.map(shard => `Shard ${shard.id} | ${shard.latency}ms`).join('\n')}\n\`\`\``);
|
const client = require('./../../');
module.exports.info = {
aliases: [
'ping',
'pong'
]
};
module.exports.command = (message) => {
let s = 0;
if (message.channel.guild) {
s = client.guildShardMap[message.channel.guild.id];
}
message.channel.createMessage(`\`\`\`\n${client.shards.map(shard => `${s === shard.id ? '>' : ' '}Shard ${shard.id} | ${shard.latency}ms`).join('\n')}\n\`\`\``);
};
|
Add an arrow next to what shard the bot is on
|
Add an arrow next to what shard the bot is on
|
JavaScript
|
mit
|
moustacheminer/discordmail,moustacheminer/discordmail
|
56b40b666ecedb2c4df37e67b8216682582e77e7
|
src/components/Resource.js
|
src/components/Resource.js
|
import React, { PropTypes } from 'react'
import SVG from 'svg-inline-react'
const Resource = ({ icon, value }) =>
<li>
<SVG src={icon}/>
<span>{value}</span>
</li>
Resource.propTypes = {
icon: PropTypes.object.isRequired,
value: PropTypes.string.isRequired,
}
export default Resource
|
import React, { PropTypes } from 'react'
import SVG from 'svg-inline-react'
const Resource = ({ icon, value }) =>
<li>
<SVG src={icon}/>
<span>{value}</span>
</li>
Resource.propTypes = {
icon: PropTypes.string.isRequired,
value: PropTypes.number.isRequired,
}
export default Resource
|
Fix warnings with wrong PropTypes
|
Fix warnings with wrong PropTypes
|
JavaScript
|
mit
|
albertoblaz/lord-commander,albertoblaz/lord-commander
|
08bdcfbbb82e1c6dd0fc6e41d17f6211a2adc1bf
|
app/components/browser/Browser.js
|
app/components/browser/Browser.js
|
import React from 'react'
import ErrorMessage from './ErrorMessage'
import Header from './Header'
import BrowserStack from './BrowserStack'
import BrowserTabs from './BrowserTabs'
import CorpusStatusWatcher from '../CorpusStatusWatcher'
class Browser extends React.Component {
render () {
return (
<CorpusStatusWatcher className="window browser-window">
<Header />
<BrowserStack />
<BrowserTabs />
<ErrorMessage />
</CorpusStatusWatcher>
)
}
}
export default Browser
|
import React from 'react'
import { connect } from 'react-redux'
import ErrorMessage from './ErrorMessage'
import Header from './Header'
import BrowserStack from './BrowserStack'
import BrowserTabs from './BrowserTabs'
import CorpusStatusWatcher from '../CorpusStatusWatcher'
import Spinner from '../Spinner'
class Browser extends React.Component {
render () {
if (!this.props.corpus) {
// Corpus not yet selected
return <Spinner />
}
return (
<CorpusStatusWatcher className="window browser-window">
<Header />
<BrowserStack />
<BrowserTabs />
<ErrorMessage />
</CorpusStatusWatcher>
)
}
}
Browser.propTypes = {
corpus: React.PropTypes.object
}
const mapStateToProps = ({ corpora }) => ({
corpus: corpora.selected
})
const mapDispatchToProps = {
}
export default connect(mapStateToProps, mapDispatchToProps)(Browser)
|
Fix proptypes error when rendering too soon after corpus is selected
|
fix(browser): Fix proptypes error when rendering too soon after corpus is selected
|
JavaScript
|
agpl-3.0
|
medialab/hyphe-browser,medialab/hyphe-browser
|
667625bff0a81ee0d420f9ada44d7d95bfbffa10
|
lib/directives.js
|
lib/directives.js
|
var directives = {
TOC: function(text) {
var toc = require('markdown-toc');
return toc(text).content;
}
};
module.exports = {
directiveMap: directives
};
|
var directives = {
TOC: function(text) {
var toc = require('markdown-toc');
text = text.split('\n').slice(1).join('\n');
return toc(text, {slugify: function(str) {
return str.toLowerCase().replace(/[^\w]+/g, '-');
}}).content;
}
};
module.exports = {
directiveMap: directives
};
|
Fix TOC anchor tags bug
|
Fix TOC anchor tags bug
|
JavaScript
|
mit
|
claudioc/jingo,claudioc/jingo
|
87b3e5b3a0ac04537237208a7535a937109e1d13
|
src/hmac.js
|
src/hmac.js
|
// HMAC - keyed-Hash Message Authentication Code
function hmac(hash, size, digest, data, hkey, block) {
var i, akey, ipad, opad;
data = self.Encoder(data).trunc();
hkey = self.Encoder(hkey).trunc();
if (hkey.length > block) {
akey = hash(digest, hkey).trunc();
} else {
akey = self.Encoder(hkey).trunc();
}
for (i = 0, ipad = [], opad = []; i < block; i += 1) {
ipad[i] = (akey[i] || 0x00) ^ 0x36;
opad[i] = (akey[i] || 0x00) ^ 0x5c;
}
return hash(size, opad.concat(hash(digest, ipad.concat(data)).trunc()));
}
|
// HMAC - keyed-Hash Message Authentication Code
function hmac(hash, size, digest, data, hkey, block) {
var i, akey, ipad, opad;
if (hkey.length > block) {
akey = hash(digest, hkey).trunc();
} else {
akey = self.Encoder(hkey).trunc();
}
for (i = 0, ipad = [], opad = []; i < block; i += 1) {
ipad[i] = (akey[i] || 0x00) ^ 0x36;
opad[i] = (akey[i] || 0x00) ^ 0x5c;
}
return hash(size, opad.concat(hash(digest, ipad.concat(data)).trunc()));
}
|
Remove excessive Encoder calls in HMAC -- 'ready' should already have been applied.
|
Remove excessive Encoder calls in HMAC -- 'ready' should already have been applied.
|
JavaScript
|
mit
|
coiscir/jsdigest,coiscir/jsdigest
|
a832aeea3b219b2e40cfa6065c0a94dc19b76a3b
|
js/components/layouts/Header.react.js
|
js/components/layouts/Header.react.js
|
var React = require('react');
var title = "Orion's Belt BattleGrounds";
var Router = require('react-router');
var Route = Router.Route, DefaultRoute = Router.DefaultRoute,
Link=Router.Link, RouteHandler = Router.RouteHandler;
var CurrentUserMenu = require('../users/CurrentUserMenu.react.js');
var Header = React.createClass({
render: function () {
return (
<div className="navbar navbar-default navbar-fixed-top">
<div className="container">
<div className="navbar-header">
<a href="/" className="navbar-brand">{title}</a>
<button className="navbar-toggle" type="button" data-toggle="collapse" data-target="#navbar-main">
<span className="icon-bar"></span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
</button>
</div>
<div className="navbar-collapse collapse" id="navbar-main">
{/*<ul className="nav navbar-nav">
<li><a href="../help/">Help</a></li>
</ul>*/}
<ul className="nav navbar-nav navbar-right">
<CurrentUserMenu />
</ul>
</div>
</div>
</div>
);
}
});
module.exports = Header;
|
var React = require('react');
var title = "Orion's Belt BattleGrounds";
var Router = require('react-router');
var Route = Router.Route, DefaultRoute = Router.DefaultRoute,
Link=Router.Link, RouteHandler = Router.RouteHandler;
var CurrentUserMenu = require('../users/CurrentUserMenu.react.js');
var Header = React.createClass({
render: function () {
return (
<div className="navbar navbar-default navbar-fixed-top">
<div className="container">
<div className="navbar-header">
<Link to="root" className="navbar-brand">{title}</Link>
<button className="navbar-toggle" type="button" data-toggle="collapse" data-target="#navbar-main">
<span className="icon-bar"></span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
</button>
</div>
<div className="navbar-collapse collapse" id="navbar-main">
{/*<ul className="nav navbar-nav">
<li><a href="../help/">Help</a></li>
</ul>*/}
<ul className="nav navbar-nav navbar-right">
<CurrentUserMenu />
</ul>
</div>
</div>
</div>
);
}
});
module.exports = Header;
|
Make brand link a router link
|
Make brand link a router link
|
JavaScript
|
mit
|
orionsbelt-battlegrounds/frontend,orionsbelt-battlegrounds/frontend,orionsbelt-battlegrounds/frontend
|
f555d3422ada1c77e7c36d88b6b96d962b8b5f76
|
ckanext/nhm/theme/public/scripts/modules/iframe-resize.js
|
ckanext/nhm/theme/public/scripts/modules/iframe-resize.js
|
// Track iframe content height changes and resize element accordingly
this.ckan.module('iframe-resize', function(jQuery, _) {
return {
initialize: function() {
var $iframe = this.el;
var i_window = $iframe.get(0).contentWindow;
var i_doc = i_window.document;
jQuery(i_window).resize(function(){
$iframe.height(jQuery(i_doc).height);
});
}
}
});
|
// Track iframe content height changes and resize element accordingly
this.ckan.module('iframe-resize', function(jQuery, _) {
return {
initialize: function() {
var $iframe = this.el;
$iframe.ready(function(){
var i_window = $iframe.get(0).contentWindow;
var set_height = function(){
// body is not always available on some browsers. True even if we did a jQuery(i_window.document).ready(...)
if (i_window.document && i_window.document.body){
var current = $iframe.height();
var target = jQuery(i_window.document).height();
if (current != target){
$iframe.height(target);
}
}
};
set_height();
// This is, unfortunately, the only reliable cross browser way to track iframe size changes.
jQuery(i_window).resize(set_height);
window.setInterval(set_height, 250);
});
}
}
});
|
Improve iframe height change tracking
|
Improve iframe height change tracking
|
JavaScript
|
mit
|
NaturalHistoryMuseum/ckanext-nhm,NaturalHistoryMuseum/ckanext-nhm,NaturalHistoryMuseum/ckanext-nhm
|
5d7866930a492909ea703ba5343b8f028a5763b5
|
app/utils/i18n/missing-message.js
|
app/utils/i18n/missing-message.js
|
import Ember from 'ember';
import Locale from 'ember-i18n/utils/locale';
import config from '../../config/environment';
const DEFAULT_LOCALE = config.i18n.defaultLocale;
let missingMessage = function(locale, key, data) {
console.log(locale)
if (locale === DEFAULT_LOCALE || window.env === 'development') {
return `Missing translation: ${key}`;
} else {
Ember.Logger.warn("Missing translation: " + key);
// NOTE This relies on internal APIs and is brittle.
// Emulating the internals of ember-i18n's translate method
const i18n = this;
const count = Ember.get(data, 'count');
const defaults = Ember.makeArray(Ember.get(data, 'default'));
defaults.unshift(key);
const localeObj = new Locale(DEFAULT_LOCALE, Ember.getOwner(i18n));
const template = localeObj.getCompiledTemplate(defaults, count);
return template(data);
}
};
export default missingMessage;
|
import Ember from 'ember';
import Locale from 'ember-i18n/utils/locale';
import config from '../../config/environment';
const DEFAULT_LOCALE = config.i18n.defaultLocale;
let missingMessage = function(locale, key, data) {
if (locale === DEFAULT_LOCALE || window.env === 'development') {
return `Missing translation: ${key}`;
} else {
Ember.Logger.warn(`Missing translation: ${key}`);
// NOTE This relies on internal APIs and is brittle.
// Emulating the internals of ember-i18n's translate method
let i18n = this;
let count = Ember.get(data, 'count');
let defaults = Ember.makeArray(Ember.get(data, 'default'));
defaults.unshift(key);
let localeObj = new Locale(DEFAULT_LOCALE, Ember.getOwner(i18n));
let template = localeObj.getCompiledTemplate(defaults, count);
return template(data);
}
};
export default missingMessage;
|
Tidy up missing message util linting issues
|
Tidy up missing message util linting issues
|
JavaScript
|
mit
|
HospitalRun/hospitalrun-frontend,HospitalRun/hospitalrun-frontend,HospitalRun/hospitalrun-frontend,HospitalRun/hospitalrun-frontend
|
bbb30eace3a304a423b1b1fe47c8f0130e216865
|
app/modules/clock/clock.js
|
app/modules/clock/clock.js
|
export default class Clock {
getTime() {
var date = new Date();
return date.getTime();
}
}
|
export default class {
getTime() {
var date = new Date();
return date.getTime();
}
}
|
Remove redundant class name from export
|
Remove redundant class name from export
|
JavaScript
|
mit
|
Voles/es2015-modules,Voles/es2015-modules
|
529c57c39a28bb6343230c52345cac29aa1c2226
|
app/src/js/modules/buic.js
|
app/src/js/modules/buic.js
|
/**
* Main mixin for the Bolt buic module.
*
* @mixin
* @namespace Bolt.buic
*
* @param {Object} bolt - The Bolt module.
* @param {Object} $ - jQuery.
*/
(function (bolt, $) {
'use strict';
/**
* Bolt.buic mixin container.
*
* @private
* @type {Object}
*/
var buic = {};
/**
* Initializes the fields, optionally based on a context.
*
* @function init
* @memberof Bolt.buic
* @param context
*/
buic.init = function (context) {
if (typeof context === 'undefined') {
context = $(document.documentElement);
}
// Widgets initialisations
$('[data-widget]', context).each(function () {
$(this)[$(this).data('widget')]();
});
};
// Add placeholder for buic.
bolt.buic = buic;
})(Bolt || {}, jQuery);
|
/**
* Main mixin for the Bolt buic module.
*
* @mixin
* @namespace Bolt.buic
*
* @param {Object} bolt - The Bolt module.
* @param {Object} $ - jQuery.
*/
(function (bolt, $) {
'use strict';
/**
* Bolt.buic mixin container.
*
* @private
* @type {Object}
*/
var buic = {};
/**
* Initializes the fields, optionally based on a context.
*
* @function init
* @memberof Bolt.buic
* @param context
*/
buic.init = function (context) {
if (typeof context === 'undefined') {
context = $(document.documentElement);
}
// Widgets initialisations
$('[data-widget]', context).each(function () {
$(this)[$(this).data('widget')]()
.removeAttr('data-widget')
.removeData('widget');
});
};
// Add placeholder for buic.
bolt.buic = buic;
})(Bolt || {}, jQuery);
|
Make sure the widget is initialized only once (although the widget factory does something similar)
|
Make sure the widget is initialized only once (although the widget factory does something similar)
|
JavaScript
|
mit
|
joshuan/bolt,one988/cm,rossriley/bolt,Raistlfiren/bolt,bolt/bolt,joshuan/bolt,electrolinux/bolt,romulo1984/bolt,HonzaMikula/masivnipostele,cdowdy/bolt,lenvanessen/bolt,rossriley/bolt,one988/cm,nantunes/bolt,bolt/bolt,romulo1984/bolt,Raistlfiren/bolt,CarsonF/bolt,electrolinux/bolt,nikgo/bolt,rarila/bolt,electrolinux/bolt,nikgo/bolt,cdowdy/bolt,GawainLynch/bolt,CarsonF/bolt,Raistlfiren/bolt,HonzaMikula/masivnipostele,GawainLynch/bolt,nantunes/bolt,romulo1984/bolt,nikgo/bolt,HonzaMikula/masivnipostele,lenvanessen/bolt,rarila/bolt,bolt/bolt,joshuan/bolt,Intendit/bolt,Raistlfiren/bolt,Intendit/bolt,Intendit/bolt,joshuan/bolt,lenvanessen/bolt,GawainLynch/bolt,lenvanessen/bolt,nantunes/bolt,CarsonF/bolt,GawainLynch/bolt,rarila/bolt,cdowdy/bolt,rossriley/bolt,one988/cm,HonzaMikula/masivnipostele,rossriley/bolt,electrolinux/bolt,Intendit/bolt,one988/cm,rarila/bolt,CarsonF/bolt,cdowdy/bolt,nikgo/bolt,nantunes/bolt,romulo1984/bolt,bolt/bolt
|
11ce50309b409bb9003adc82a0c4785a35d04b67
|
src/js/inject.js
|
src/js/inject.js
|
(() => {
'use strict';
chrome.storage.sync.get(function(storage) {
let execFlag = true;
for (var i = 0; i < storage.excludeURL.length; i++) {
if (parseURL(location.href).match(RegExp(parseURL(storage.excludeURL[i])))) {
execFlag = false;
}
}
if (execFlag) {
disableReferrer();
}
});
function disableReferrer() {
let meta = document.createElement('meta');
meta.name = "referrer";
meta.content = "no-referrer";
document.head.appendChild(meta);
}
function parseURL(url) {
// cut 'http' or 'https'
// http://www.example.com => www.example.com
// https://www.example.com => www.example.com
url = url.replace(/^https?:\/\//g, '');
// cut trailing slash
// example.com/foo/bar/ => example.com/foo/bar
url = (url[url.length-1] === '/') ? url.substr(0, url.length-1) : url;
return url;
}
chrome.runtime.sendMessage({referrer: document.referrer}, function(response) {});
})();
|
(() => {
'use strict';
chrome.storage.sync.get(function(storage) {
let execFlag = true;
if (storage.excludeURL !== undefined) {
for (var i = 0; i < storage.excludeURL.length; i++) {
if (parseURL(location.href).match(RegExp(parseURL(storage.excludeURL[i])))) {
execFlag = false;
}
}
}
if (execFlag) {
disableReferrer();
}
});
function disableReferrer() {
let meta = document.createElement('meta');
meta.name = "referrer";
meta.content = "no-referrer";
document.head.appendChild(meta);
}
function parseURL(url) {
// cut 'http' or 'https'
// http://www.example.com => www.example.com
// https://www.example.com => www.example.com
url = url.replace(/^https?:\/\//g, '');
// cut trailing slash
// example.com/foo/bar/ => example.com/foo/bar
url = (url[url.length-1] === '/') ? url.substr(0, url.length-1) : url;
return url;
}
chrome.runtime.sendMessage({referrer: document.referrer}, function(response) {});
})();
|
Fix error when never load options page
|
:bug: Fix error when never load options page
|
JavaScript
|
mit
|
noraworld/no-more-referrer,noraworld/no-more-referrer
|
440d1c9fd5833bca5c746b9f6787eaa9993643dc
|
test/spec/windshaft/map-serializer/anonymous-map-serializer/dataviews-serializer.spec.js
|
test/spec/windshaft/map-serializer/anonymous-map-serializer/dataviews-serializer.spec.js
|
// var Backbone = require('backbone');
// var DataviewsSerializer = require('../../../../../src/windshaft/map-serializer/anonymous-map-serializer/dataviews-serializer');
// var HistogramDataviewModel = require('../../../../../src/dataviews/histogram-dataview-model');
fdescribe('dataviews-serializer', function () {
it('.serialize', function () {
pending('TODO: create dataviews using the new v4 api and check the serialization');
});
});
|
Add pending tests for dataviews-serializer
|
Add pending tests for dataviews-serializer
|
JavaScript
|
bsd-3-clause
|
splashblot/cartodb.js,splashblot/cartodb.js,splashblot/cartodb.js,splashblot/cartodb.js
|
|
31b86c877b4a8a6f61d3dd096d3d6967a00154a5
|
lib/util/index.js
|
lib/util/index.js
|
import * as distance from './distance'
import * as geocode from './geocode'
import * as itinerary from './itinerary'
import * as map from './map'
import * as profile from './profile'
import * as query from './query'
import * as reverse from './reverse'
import * as state from './state'
import * as time from './time'
import * as ui from './ui'
const OtpUtils = {
distance,
geocode,
itinerary,
map,
profile,
query,
reverse,
state,
time,
ui
}
export default OtpUtils
|
import * as distance from './distance'
import * as geocoder from './geocoder'
import * as itinerary from './itinerary'
import * as map from './map'
import * as profile from './profile'
import * as query from './query'
import * as reverse from './reverse'
import * as state from './state'
import * as time from './time'
import * as ui from './ui'
const OtpUtils = {
distance,
geocoder,
itinerary,
map,
profile,
query,
reverse,
state,
time,
ui
}
export default OtpUtils
|
Fix error with bundling geocoder utils for export as part of api
|
fix(api): Fix error with bundling geocoder utils for export as part of api
|
JavaScript
|
mit
|
opentripplanner/otp-react-redux,opentripplanner/otp-react-redux,opentripplanner/otp-react-redux,opentripplanner/otp-react-redux
|
37771b1cb803e09c51f20305d52fd4df246172a0
|
packages/@sanity/core/src/actions/graphql/listApisAction.js
|
packages/@sanity/core/src/actions/graphql/listApisAction.js
|
module.exports = async function listApisAction(args, context) {
const {apiClient, output, chalk} = context
const client = apiClient({
requireUser: true,
requireProject: true
})
let endpoints
try {
endpoints = await client.request({
url: `/apis/graphql`,
method: 'GET'
})
} catch (err) {
if (err.statusCode === 404) {
endpoints = []
} else {
throw err
}
}
endpoints = [{
dataset: 'production',
tag: 'default',
generation: 'gen1',
playgroundEnabled: false
}, {
dataset: 'staging',
tag: 'next',
generation: 'gen2',
playgroundEnabled: true
}]
if (endpoints && endpoints.length > 0) {
output.print('Here are the GraphQL endpoints deployed for this project:')
endpoints.forEach((endpoint, index) => {
output.print(`${index + 1}. ${chalk.bold('Dataset:')} ${endpoint.dataset}`)
output.print(` ${chalk.bold('Tag:')} ${endpoint.tag}`)
output.print(` ${chalk.bold('Generation:')} ${endpoint.generation}`)
output.print(` ${chalk.bold('Playground:')} ${endpoint.playgroundEnabled}\n`)
})
}
output.print("This project doesn't have any GraphQL endpoints deployed.")
}
|
module.exports = async function listApisAction(args, context) {
const {apiClient, output, chalk} = context
const client = apiClient({
requireUser: true,
requireProject: true
})
let endpoints
try {
endpoints = await client.request({
url: `/apis/graphql`,
method: 'GET'
})
} catch (err) {
if (err.statusCode === 404) {
endpoints = []
} else {
throw err
}
}
if (endpoints && endpoints.length > 0) {
output.print('Here are the GraphQL endpoints deployed for this project:')
endpoints.forEach((endpoint, index) => {
output.print(`${index + 1}. ${chalk.bold('Dataset:')} ${endpoint.dataset}`)
output.print(` ${chalk.bold('Tag:')} ${endpoint.tag}`)
output.print(` ${chalk.bold('Generation:')} ${endpoint.generation}`)
output.print(` ${chalk.bold('Playground:')} ${endpoint.playgroundEnabled}\n`)
})
}
output.print("This project doesn't have any GraphQL endpoints deployed.")
}
|
Remove in-line mock data when testing graphql list CLI command
|
[core] GraphQL: Remove in-line mock data when testing graphql list CLI command
|
JavaScript
|
mit
|
sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity
|
59c2a76434297f7d6ae2389f693a3b4fd484a5f5
|
api/src/lib/logger.js
|
api/src/lib/logger.js
|
const winston = require('winston');
const util = require('util');
const transports = [new winston.transports.Console()];
const Rollbar = require('rollbar');
const rollbar = new Rollbar('ff3ef8cca74244eabffb17dc2365e7bb');
const rollbarLogger = winston.transports.CustomLogger = function () {
this.name = 'rollbarLogger';
this.level = 'error';
};
util.inherits(rollbarLogger, winston.Transport);
rollbarLogger.prototype.log = function (level, msg, meta, callback) {
rollbar.error(meta.message, meta);
callback(null, true);
};
const Raven = require('raven');
const sentryLogger = winston.transports.CustomLogger = function () {
this.name = 'sentryLogger';
this.level = 'error';
};
util.inherits(sentryLogger, winston.Transport);
sentryLogger.prototype.log = function (level, msg, meta, callback) {
Raven.captureMessage(msg);
callback(null, true);
};
transports.push(new sentryLogger());
transports.push(new rollbarLogger());
module.exports = new winston.Logger({
transports: transports,
filters: [
(level, msg, meta) => msg.trim(), // shouldn't be necessary, but good-winston is adding \n
],
});
|
const winston = require('winston');
const util = require('util');
const transports = [new winston.transports.Console()];
if (process.env.SENTRY_DSN) {
const Raven = require('raven');
const sentryLogger = winston.transports.CustomLogger = function () {
this.name = 'sentryLogger';
this.level = 'error';
};
util.inherits(sentryLogger, winston.Transport);
sentryLogger.prototype.log = function (level, msg, meta, callback) {
Raven.captureException(meta);
callback(null, true);
};
transports.push(new sentryLogger());
}
if (process.env.ROLLBAR_ACCESS_TOKEN) {
const Rollbar = require('rollbar');
const rollbar = new Rollbar(process.env.ROLLBAR_ACCESS_TOKEN);
const rollbarLogger = winston.transports.CustomLogger = function () {
this.name = 'rollbarLogger';
this.level = 'error';
};
util.inherits(rollbarLogger, winston.Transport);
rollbarLogger.prototype.log = function (level, msg, meta, callback) {
rollbar.error(meta.message, meta);
callback(null, true);
};
transports.push(new rollbarLogger());
}
module.exports = new winston.Logger({
transports: transports,
filters: [
(level, msg, meta) => msg.trim(), // shouldn't be necessary, but good-winston is adding \n
],
});
|
Change rollbarLogger & sentryLogger to be conditionally used
|
Change rollbarLogger & sentryLogger to be conditionally used
|
JavaScript
|
mit
|
synapsestudios/oidc-platform,synapsestudios/oidc-platform,synapsestudios/oidc-platform,synapsestudios/oidc-platform
|
9f720da6aa6d4f72e9c3a6f26389f95eadf30cf6
|
src/dom-utils/getWindow.js
|
src/dom-utils/getWindow.js
|
// @flow
/*:: import type { Window } from '../types'; */
/*:: declare function getWindow(node: Node | Window): Window; */
export default function getWindow(node) {
if (node.toString() !== '[object Window]') {
const ownerDocument = node.ownerDocument;
return ownerDocument ? ownerDocument.defaultView : window;
}
return node;
}
|
// @flow
/*:: import type { Window } from '../types'; */
/*:: declare function getWindow(node: Node | Window): Window; */
export default function getWindow(node) {
if (node.toString() !== '[object Window]') {
const ownerDocument = node.ownerDocument;
return ownerDocument ? ownerDocument.defaultView || window : window;
}
return node;
}
|
Fix errors when iFrames are destroyed
|
Fix errors when iFrames are destroyed
Errors are thrown when an iFrame is destroyed because the popper's reference node's document no longer has a `defaultView`. The errors being thrown are:
> Cannot read property 'Element' of null
and
> Cannot read property 'HTMLElement' of null
from within `update`.
|
JavaScript
|
mit
|
FezVrasta/popper.js,floating-ui/floating-ui,floating-ui/floating-ui,FezVrasta/popper.js,floating-ui/floating-ui,FezVrasta/popper.js,FezVrasta/popper.js
|
f535468595a036df443c95a84e9a182fd572115c
|
reverse-words.js
|
reverse-words.js
|
// Reverse Words
/*RULES:
Function takes a string parameter
Reverse every word in the string
Return new string
NOTE:
Order of words shouldn't change
Can't use the array.reverse() method
*/
/*PSEUDOCODE
1) Split array by words
2) For each word,
2a) Push last letter of each individual element into a new array
2b) When done, push new array into new empty str array
2c) Continue doing this for all words
3) Join new array
4) Return new string
*/
function reverseWords(str){
var strArr = str.split(" ");
var emptyWordArr = [];
var emptyStrArr = [];
var index = 0;
strArr.forEach(function(word){
word = word.split('');
index = (word.length);
while (index > -1){
emptyWordArr.push(word[index])
index--;
}
emptyStrArr.push(emptyWordArr.join(''));
emptyWordArr = [];
});
return emptyStrArr.join(' ');
}
|
// Reverse Words
/*RULES:
Function takes a string parameter
Reverse every word in the string
Return new string
NOTE:
Order of words shouldn't change
Can't use the array.reverse() method
*/
/*PSEUDOCODE
1) Split array by words
2) For each word,
2a) Push last letter of each individual element into a new array
2b) When done, push new array into new empty str array
2c) Continue doing this for all words
3) Join new array
4) Return new string
*/
// This was my initial response, and it works fine! But could be slightly refactored for cleaner code.
// function reverseWords(str){
// var strArr = str.split(" ");
// var emptyWordArr = [];
// var emptyStrArr = [];
// var index = 0;
// strArr.forEach(function(word){
// word = word.split('');
// index = (word.length);
// while (index > -1){
// emptyWordArr.push(word[index])
// index--;
// }
// emptyStrArr.push(emptyWordArr.join(''));
// emptyWordArr = [];
// });
// return emptyStrArr.join(' ');
// }
|
Comment out initial response to include refactored answer
|
Comment out initial response to include refactored answer
|
JavaScript
|
mit
|
benjaminhyw/javascript_algorithms
|
bf33bafd03eb1265a7b10468b4a9a74f80d5adca
|
rollup.config.js
|
rollup.config.js
|
import commonjs from '@rollup/plugin-commonjs';
import resolve from '@rollup/plugin-node-resolve';
import json from '@rollup/plugin-json';
import { terser } from 'rollup-plugin-terser';
import peggy from 'rollup-plugin-peggy';
import copy from 'rollup-plugin-copy';
import scss from 'rollup-plugin-scss';
import serve from 'rollup-plugin-serve';
export default {
input: 'src/scripts/index.js',
output: {
file: 'dist/index.js',
sourcemap: true,
exports: 'auto'
},
plugins: [
copy({
targets: [
{ src: 'public/*', dest: 'dist/' }
]
}),
resolve({
browser: true,
preferBuiltins: true
}),
scss(),
commonjs(),
json(),
peggy({ cache: true }),
process.env.NODE_ENV === 'production' ? terser() : null,
process.env.SERVE_APP ? serve({
contentBase: 'dist',
port: 8080
}) : null
]
};
|
import path from 'path';
import glob from 'glob';
import commonjs from '@rollup/plugin-commonjs';
import resolve from '@rollup/plugin-node-resolve';
import json from '@rollup/plugin-json';
import { terser } from 'rollup-plugin-terser';
import peggy from 'rollup-plugin-peggy';
import copy from 'rollup-plugin-copy';
import scss from 'rollup-plugin-scss';
import serve from 'rollup-plugin-serve';
// Watch additional files outside of the module graph (e.g. SCSS or static
// assets); see <https://github.com/rollup/rollup/issues/3414>
function watcher(globs) {
return {
buildStart() {
for (const item of globs) {
glob.sync(path.resolve(__dirname, item)).forEach((filename) => {
this.addWatchFile(filename);
});
}
}
};
}
export default {
input: 'src/scripts/index.js',
output: {
file: 'dist/index.js',
sourcemap: true,
exports: 'auto'
},
plugins: [
watcher(['src/styles/*.*', 'public/**/*.*']),
copy({
targets: [
{ src: 'public/*', dest: 'dist/' }
]
}),
resolve({
browser: true,
preferBuiltins: true
}),
scss(),
commonjs(),
json(),
peggy({ cache: true }),
process.env.NODE_ENV === 'production' ? terser() : null,
process.env.SERVE_APP ? serve({
contentBase: 'dist',
port: 8080
}) : null
]
};
|
Fix watching of stylesheets and static assets
|
Fix watching of stylesheets and static assets
|
JavaScript
|
mit
|
caleb531/truthy,caleb531/truthy
|
f3d336e625f576c47c4803051e63934f10e9b3ff
|
packages/machinomy/migrations/sqlite/20180325060555-add-created-at.js
|
packages/machinomy/migrations/sqlite/20180325060555-add-created-at.js
|
'use strict';
var dbm;
var type;
var seed;
/**
* We receive the dbmigrate dependency from dbmigrate initially.
* This enables us to not have to rely on NODE_PATH.
*/
exports.setup = function(options, seedLink) {
dbm = options.dbmigrate;
type = dbm.dataType;
seed = seedLink;
};
exports.up = function(db) {
return db.addColumn('payment', 'createdAt', {
type: 'bigint'
});
};
exports.down = function(db) {
return db.removeColumn('payment', 'createdAt');
};
exports._meta = {
"version": 1
};
|
'use strict';
var dbm;
var type;
var seed;
/**
* We receive the dbmigrate dependency from dbmigrate initially.
* This enables us to not have to rely on NODE_PATH.
*/
exports.setup = function(options, seedLink) {
dbm = options.dbmigrate;
type = dbm.dataType;
seed = seedLink;
};
exports.up = function(db) {
return db.addColumn('payment', 'createdAt', {
type: 'bigint'
});
};
exports.down = function(db) {
};
exports._meta = {
"version": 1
};
|
Remove call of not implemented method removeColumn in SQLite migration.
|
Remove call of not implemented method removeColumn in SQLite migration.
|
JavaScript
|
apache-2.0
|
machinomy/machinomy,machinomy/machinomy,machinomy/machinomy
|
77f9ca109a9b9f84d8d9837b8dc743b902115392
|
packages/rekit-core/templates/jest/ConnectedComponent.test.js
|
packages/rekit-core/templates/jest/ConnectedComponent.test.js
|
import React from 'react';
import { shallow } from 'enzyme';
import { ${_.pascalCase(component)} } from '../../../src/features/${_.kebabCase(feature)}/${_.pascalCase(component)}';
describe('${_.kebabCase(feature)}/${_.pascalCase(component)}', () => {
it('renders node with correct class name', () => {
const props = {
${_.camelCase(feature)}: {},
actions: {},
};
const renderedComponent = shallow(
<${_.pascalCase(component)} {...props} />
);
expect(
renderedComponent.find('.${_.kebabCase(feature)}-${_.kebabCase(component)}')
).toHaveLength(1);
});
});
|
Add connected component tpl for jest.
|
Add connected component tpl for jest.
|
JavaScript
|
mit
|
supnate/rekit
|
|
89a27fac6b191459d63d90a63b29da691f823879
|
rollup.config.js
|
rollup.config.js
|
import buble from 'rollup-plugin-buble'
import inject from 'rollup-plugin-inject'
import resolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs'
import builtins from 'builtin-modules'
const pkg = require('./package.json')
export default {
input: 'src/index.js',
output: [
{ format: 'cjs', file: pkg.main, sourcemap: true, exports: 'default' },
{ format: 'es', file: pkg.module, sourcemap: true }
],
external: builtins.concat(Object.keys(pkg.dependencies)),
plugins: [
buble({
include: 'src/**',
target: {
node: 4
}
}),
resolve({
module: true,
jsnext: true,
main: true,
browser: false,
preferBuiltins: true
}),
commonjs(),
inject({
include: 'src/**',
Promise: 'bluebirdish'
})
]
}
|
import buble from 'rollup-plugin-buble'
import inject from 'rollup-plugin-inject'
import resolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs'
import builtins from 'builtin-modules'
const pkg = require('./package.json')
export default {
input: 'src/index.js',
output: [
{ format: 'cjs', file: pkg.main, sourcemap: true, exports: 'default', interop: false },
{ format: 'es', file: pkg.module, sourcemap: true }
],
external: builtins.concat(Object.keys(pkg.dependencies)),
plugins: [
buble({
include: 'src/**',
target: {
node: 4
}
}),
resolve({
module: true,
jsnext: true,
main: true,
browser: false,
preferBuiltins: true
}),
commonjs(),
inject({
include: 'src/**',
Promise: 'bluebirdish'
})
]
}
|
Disable CJS→ES interop in CommonJS build.
|
Disable CJS→ES interop in CommonJS build.
|
JavaScript
|
mit
|
goto-bus-stop/miniplug
|
19878840876fc3d85b169b3a02fff412d7d80b95
|
rollup.config.js
|
rollup.config.js
|
export default [
{
input: './src/index.js',
treeshake: false,
external: p => /^three/.test( p ),
output: {
name: 'MeshBVHLib',
extend: true,
format: 'umd',
file: './umd/index.js',
sourcemap: true,
globals: p => /^three/.test( p ) ? 'THREE' : null,
},
},
{
input: './src/index.js',
treeshake: false,
external: p => /^three/.test( p ),
output: {
name: 'MeshBVHLib',
extend: true,
format: 'esm',
file: './esm/index.js',
sourcemap: true,
globals: p => /^three/.test( p ) ? 'THREE' : null,
},
}
];
|
export default [
{
input: './src/index.js',
treeshake: false,
external: p => /^three/.test( p ),
output: {
name: 'MeshBVHLib',
extend: true,
format: 'umd',
file: './umd/index.js',
sourcemap: true,
globals: p => /^three/.test( p ) ? 'THREE' : null,
},
},
{
input: './src/index.js',
treeshake: false,
external: p => /^three/.test( p ),
output: {
format: 'esm',
file: './esm/index.js',
sourcemap: true,
},
}
];
|
Remove `name`, `extend` and `globals` options.
|
Remove `name`, `extend` and `globals` options.
|
JavaScript
|
mit
|
gkjohnson/three-mesh-bvh,gkjohnson/three-mesh-bvh,gkjohnson/three-mesh-bvh
|
4a991cfec283699e1c10070b89fc797c6e6320a5
|
js/components/DropTarget.js
|
js/components/DropTarget.js
|
import React from "react";
import { connect } from "react-redux";
import { loadFilesFromReferences } from "../actionCreators";
export class DropTarget extends React.Component {
constructor(props) {
super(props);
this.handleDrop = this.handleDrop.bind(this);
}
supress(e) {
e.stopPropagation();
e.preventDefault();
}
handleDrop(e) {
this.supress(e);
const { files } = e.dataTransfer;
this.props.loadFilesFromReferences(files);
}
render() {
// eslint-disable-next-line no-shadow, no-unused-vars
const { loadFilesFromReferences, ...passThroughProps } = this.props;
return (
<div
{...passThroughProps}
onDragEnter={this.supress}
onDragOver={this.supress}
onDrop={this.handleDrop}
/>
);
}
}
export default connect(null, { loadFilesFromReferences })(DropTarget);
|
import React from "react";
export default class DropTarget extends React.Component {
constructor(props) {
super(props);
this.handleDrop = this.handleDrop.bind(this);
this._ref = this._ref.bind(this);
}
supress(e) {
e.stopPropagation();
e.preventDefault();
}
handleDrop(e) {
this.supress(e);
if (!this._node) {
return;
}
const { x, y } = this._node.getBoundingClientRect();
this.props.handleDrop(e, { x, y });
}
_ref(node) {
this._node = node;
}
render() {
const {
// eslint-disable-next-line no-shadow, no-unused-vars
loadFilesFromReferences,
// eslint-disable-next-line no-shadow, no-unused-vars
handleDrop,
...passThroughProps
} = this.props;
return (
<div
{...passThroughProps}
onDragEnter={this.supress}
onDragOver={this.supress}
onDrop={this.handleDrop}
ref={this._ref}
/>
);
}
}
|
Add coords to drop handle call
|
Add coords to drop handle call
|
JavaScript
|
mit
|
captbaritone/winamp2-js,captbaritone/winamp2-js,captbaritone/winamp2-js
|
90effe78be49943827057b60ee6dc0b6c4ce086a
|
app/js/controllers.js
|
app/js/controllers.js
|
'use strict';
/* Controllers */
var cvAppControllers = angular.module('cvAppControllers', []);
cvAppControllers.controller('HomeController', ['$scope', function($scope) {
$scope.name = 'Elias';
}]);
cvAppControllers.controller('AboutController', ['$scope', function($scope) {
$scope.name = 'Elias';
}]);
|
'use strict';
/* Controllers */
var cvAppControllers = angular.module('cvAppControllers', []);
cvAppControllers.controller('HomeController', ['$scope', function($scope) {
$scope.name = 'Elias';
}]);
cvAppControllers.controller('AboutController', ['$scope', function($scope) {
$scope.name = 'Elias';
}]);
/*
phonecatApp.controller('PhoneListCtrl', function ($scope, $http) {
$http.get('phones/phones.json').success(function(data) {
$scope.phones = data;
});
$scope.orderProp = 'age';
});
*/
|
Add tutorial http controller for reference (commented)
|
Add tutorial http controller for reference (commented)
|
JavaScript
|
mit
|
RegularSvensson/cvApp,RegularSvensson/cvApp
|
4a704fb65343f43945ac623abf6706b24ed5b9ea
|
brunch-config.js
|
brunch-config.js
|
'use strict';
module.exports = {
files: {
javascripts: {
joinTo: {
'app.js': /^app\//,
'vendor.js': /^node_modules\//
}
},
stylesheets: {
joinTo: {
'app.css': /^app\//
}
}
},
plugins: {
babel: {
presets: ['es2015', 'react']
}
},
server: {
port: 8000
}
};
|
'use strict';
module.exports = {
files: {
javascripts: {
joinTo: {
'app.js': /^app\//,
'vendor.js': /^node_modules\//
}
},
stylesheets: {
joinTo: {
'app.css': /^app\//
}
}
},
plugins: {
babel: {
presets: ['es2015', 'react']
}
},
server: {
port: Number.parseInt(process.env.PORT) || 8000
}
};
|
Allow PORT env variable to specify server port number
|
Allow PORT env variable to specify server port number
|
JavaScript
|
mit
|
ryansobol/with-react,ryansobol/with-react
|
7a6fb64b30513b987e59965a948a681037f406e9
|
src/utils/index.js
|
src/utils/index.js
|
const { parse } = require('url')
const UrlPattern = require('url-pattern')
const patternOpts = {
segmentNameCharset: 'a-zA-Z0-9_-',
}
const isPattern = pattern => pattern instanceof UrlPattern
const getParamsAndQuery = (pattern, url) => {
const { query, pathname } = parse(url, true)
const route = isPattern(pattern)
? pattern
: new UrlPattern(pattern, patternOpts)
const params = route.match(pathname)
return { query, params }
}
module.exports = {
getParamsAndQuery,
isPattern,
patternOpts,
}
|
const { parse } = require('url')
const UrlPattern = require('url-pattern')
const patternOpts = {
segmentNameCharset: 'a-zA-Z0-9_-',,
segmentValueCharset: 'a-zA-Z0-9@\.\+\-\_'
}
const isPattern = pattern => pattern instanceof UrlPattern
const getParamsAndQuery = (pattern, url) => {
const { query, pathname } = parse(url, true)
const route = isPattern(pattern)
? pattern
: new UrlPattern(pattern, patternOpts)
const params = route.match(pathname)
return { query, params }
}
module.exports = {
getParamsAndQuery,
isPattern,
patternOpts,
}
|
Allow some more chars in url as pattern value
|
Allow some more chars in url as pattern value
Allow character @, dot, +, _ and - as url pattern value, so email address can be passed as url parameter.
|
JavaScript
|
mit
|
pedronauck/micro-router
|
943a6c173c366dad1207b53d79b35e4f97ed0062
|
src/server/handlers/badge.js
|
src/server/handlers/badge.js
|
import path from 'path';
import logging from '../logging';
const logger = logging.getLogger('express');
import {
internalFindSnap,
internalGetSnapBuilds
} from './launchpad';
import { getGitHubRepoUrl } from '../../common/helpers/github-url';
import { snapBuildFromAPI } from '../../common/helpers/snap-builds';
const BADGES_PATH = path.join(__dirname, '../../common/images/badges');
export const badge = async (req, res) => {
const repoUrl = getGitHubRepoUrl(req.params.owner, req.params.name);
try {
const snap = await internalFindSnap(repoUrl);
const builds = await internalGetSnapBuilds(snap);
let badgeName = 'never_built';
if (builds.length) {
const latestBuild = snapBuildFromAPI(builds[0]);
if (latestBuild.badge) {
badgeName = latestBuild.badge;
}
}
res.setHeader('Cache-Control', 'no-cache');
return res.sendFile(path.join(BADGES_PATH, `${badgeName}.svg`));
} catch (err) {
logger.error(`Error generating badge for repo ${repoUrl}`, err);
res.status(404).send('Not found');
}
};
|
import path from 'path';
import logging from '../logging';
const logger = logging.getLogger('express');
import {
internalFindSnap,
internalGetSnapBuilds
} from './launchpad';
import { getGitHubRepoUrl } from '../../common/helpers/github-url';
import { snapBuildFromAPI } from '../../common/helpers/snap-builds';
const BADGES_PATH = path.join(__dirname, '../../common/images/badges');
export const badge = async (req, res) => {
const repoUrl = getGitHubRepoUrl(req.params.owner, req.params.name);
try {
const snap = await internalFindSnap(repoUrl);
const builds = await internalGetSnapBuilds(snap);
let badgeName = 'never_built';
if (builds.length) {
const latestBuild = snapBuildFromAPI(builds[0]);
if (latestBuild.badge) {
badgeName = latestBuild.badge;
}
}
res.setHeader('Cache-Control', 'no-cache, no-store, max-age=0, must-revalidate, value');
res.setHeader('Expires', 'Thu, 01 Jan 1970 00:00:00 GMT');
res.setHeader('Pragma', 'no-cache');
return res.sendFile(path.join(BADGES_PATH, `${badgeName}.svg`));
} catch (err) {
logger.error(`Error generating badge for repo ${repoUrl}`, err);
res.status(404).send('Not found');
}
};
|
Add Extra Cache Headers To Build Badge Response
|
Add Extra Cache Headers To Build Badge Response
Add extra cache prevention headers to the build badge response. This should help
reduce caching on GitHub README's.
|
JavaScript
|
agpl-3.0
|
canonical-ols/build.snapcraft.io,canonical-ols/build.snapcraft.io,canonical-ols/build.snapcraft.io
|
6d9d315ca741f5472902c0f961591fdff9bbf946
|
src/js/utils/time.js
|
src/js/utils/time.js
|
// ==========================================================================
// Time utils
// ==========================================================================
import is from './is';
// Time helpers
export const getHours = value => parseInt((value / 60 / 60) % 60, 10);
export const getMinutes = value => parseInt((value / 60) % 60, 10);
export const getSeconds = value => parseInt(value % 60, 10);
// Format time to UI friendly string
export function formatTime(time = 0, displayHours = false, inverted = false) {
// Bail if the value isn't a number
if (!is.number(time)) {
return formatTime(null, displayHours, inverted);
}
// Format time component to add leading zero
const format = value => `0${value}`.slice(-2);
// Breakdown to hours, mins, secs
let hours = getHours(time);
const mins = getMinutes(time);
const secs = getSeconds(time);
// Do we need to display hours?
if (displayHours || hours > 0) {
hours = `${hours}:`;
} else {
hours = '';
}
// Render
return `${inverted && time > 0 ? '-' : ''}${hours}${format(mins)}:${format(secs)}`;
}
|
// ==========================================================================
// Time utils
// ==========================================================================
import is from './is';
// Time helpers
export const getHours = value => Math.trunc((value / 60 / 60) % 60, 10);
export const getMinutes = value => Math.trunc((value / 60) % 60, 10);
export const getSeconds = value => Math.trunc(value % 60, 10);
// Format time to UI friendly string
export function formatTime(time = 0, displayHours = false, inverted = false) {
// Bail if the value isn't a number
if (!is.number(time)) {
return formatTime(null, displayHours, inverted);
}
// Format time component to add leading zero
const format = value => `0${value}`.slice(-2);
// Breakdown to hours, mins, secs
let hours = getHours(time);
const mins = getMinutes(time);
const secs = getSeconds(time);
// Do we need to display hours?
if (displayHours || hours > 0) {
hours = `${hours}:`;
} else {
hours = '';
}
// Render
return `${inverted && time > 0 ? '-' : ''}${hours}${format(mins)}:${format(secs)}`;
}
|
Use Math.trunc instead of parseInt
|
fix: Use Math.trunc instead of parseInt
|
JavaScript
|
mit
|
dacostafilipe/plyr,dacostafilipe/plyr,sampotts/plyr,Selz/plyr
|
5ea305a1fa5591bb50d1b180546ce1e8efa4b258
|
scripts/chris.js
|
scripts/chris.js
|
var audio = document.getElementById("chris");
function pauseChris() {
if (audio.currentTime >= 331000) {
audio.pause();
}
}
function playChris() {
audio.currentTime = 952;
audio.play();
var interval = setInterval(pauseChris, 1000);
alert(interval);
}
function addChrisButton() {
var div = document.getElementById("audioContainer");
var button = document.createElement("BUTTON");
button.setAttribute("type", "button");
button.addEventListener("click", playChris);
button.innerText = "Escuchar a Chris";
div.insertBefore(button, audio);
}
addChrisButton();
|
var audio = document.getElementById("chris");
function pauseChris() {
if (audio.currentTime >= 331000) {
audio.pause();
alert(interval);
}
}
function playChris() {
audio.currentTime = 952;
audio.play();
var interval = setInterval(pauseChris, 1000);
}
function addChrisButton() {
var div = document.getElementById("audioContainer");
var button = document.createElement("BUTTON");
button.setAttribute("type", "button");
button.addEventListener("click", playChris);
button.innerText = "Escuchar a Chris";
div.insertBefore(button, audio);
}
addChrisButton();
|
Test with alert in pause
|
Test with alert in pause
|
JavaScript
|
mit
|
nvdaes/nvdaes.github.io,nvdaes/nvdaes.github.io
|
ae8d93f223107d6fde7c1426187ac36e4747b010
|
src/utils/isReactModuleName.js
|
src/utils/isReactModuleName.js
|
/*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
*
*/
var reactModules = ['react', 'react/addons'];
/**
* Takes a module name (string) and returns true if it refers to a root react
* module name.
*/
export default function isReactModuleName(moduleName: string): boolean {
return reactModules.some(function(reactModuleName) {
return reactModuleName === moduleName.toLowerCase();
});
}
|
/*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
*
*/
var reactModules = ['react', 'react/addons', 'react-native'];
/**
* Takes a module name (string) and returns true if it refers to a root react
* module name.
*/
export default function isReactModuleName(moduleName: string): boolean {
return reactModules.some(function(reactModuleName) {
return reactModuleName === moduleName.toLowerCase();
});
}
|
Add support for PropTypes import from react-native
|
Add support for PropTypes import from react-native
See issue #43
|
JavaScript
|
mit
|
fkling/react-docgen,reactjs/react-docgen,janicduplessis/react-docgen,reactjs/react-docgen,reactjs/react-docgen
|
453c689050e6cb8277f47eed16035b7cd608f262
|
server/server.js
|
server/server.js
|
'use strict';
var loopback = require('loopback');
var boot = require('loopback-boot');
var path = require('path');
var bodyParser = require('body-parser');
var app = module.exports = loopback();
// configure view handler
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// configure body parser
app.use(bodyParser.urlencoded({extended: true}));
app.use(loopback.token());
app.start = function() {
// start the web server
return app.listen(function() {
app.emit('started');
var baseUrl = app.get('url').replace(/\/$/, '');
console.log('Web server listening at: %s', baseUrl);
if (app.get('loopback-component-explorer')) {
var explorerPath = app.get('loopback-component-explorer').mountPath;
console.log('Browse your REST API at %s%s', baseUrl, explorerPath);
}
});
};
// Bootstrap the application, configure models, datasources and middleware.
// Sub-apps like REST API are mounted via boot scripts.
boot(app, __dirname, function(err) {
if (err) throw err;
// start the server if `$ node server.js`
if (require.main === module)
app.start();
});
|
'use strict'
var loopback = require('loopback')
var boot = require('loopback-boot')
var path = require('path')
var bodyParser = require('body-parser')
var app = module.exports = loopback()
// configure body parser
app.use(bodyParser.urlencoded({extended: true}))
app.use(loopback.token({
model: app.models.accessToken,
currentUserLiteral: 'me'
}))
app.start = function() {
// start the web server
return app.listen(function() {
app.emit('started')
var baseUrl = app.get('url').replace(/\/$/, '')
console.log('Web server listening at: %s', baseUrl)
if (app.get('loopback-component-explorer')) {
var explorerPath = app.get('loopback-component-explorer').mountPath
console.log('Browse your REST API at %s%s', baseUrl, explorerPath)
}
})
}
// Bootstrap the application, configure models, datasources and middleware.
// Sub-apps like REST API are mounted via boot scripts.
boot(app, __dirname, function(err) {
if (err) throw err
// start the server if `$ node server.js`
if (require.main === module)
app.start()
})
|
Remove Extra EJS Routes Handler and Add Caching Process to AccessToken
|
Remove Extra EJS Routes Handler and Add Caching Process to AccessToken
|
JavaScript
|
mit
|
Flieral/Publisher-Service,Flieral/Publisher-Service
|
5db936da218aafcb5480119c655fbb9dc4071b94
|
lib/text-align.js
|
lib/text-align.js
|
var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var cssstats = require('cssstats')
var module = require('tachyons-text-align/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-text-align/tachyons-text-align.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)
var srcCSS = fs.readFileSync('./src/_text-align.css', 'utf8')
var template = fs.readFileSync('./templates/docs/text-align/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
moduleVersion: module.version,
moduleSize: moduleSize,
moduleObj: moduleObj,
srcCSS: srcCSS
})
fs.writeFileSync('./docs/typography/text-align/index.html', html)
|
var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var cssstats = require('cssstats')
var module = require('tachyons-text-align/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-text-align/tachyons-text-align.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)
var srcCSS = fs.readFileSync('./src/_text-align.css', 'utf8')
var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8')
var template = fs.readFileSync('./templates/docs/text-align/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
moduleVersion: module.version,
moduleSize: moduleSize,
moduleObj: moduleObj,
srcCSS: srcCSS,
navDocs: navDocs
})
fs.writeFileSync('./docs/typography/text-align/index.html', html)
|
Update with reference to global nav partial
|
Update with reference to global nav partial
|
JavaScript
|
mit
|
getfrank/tachyons,topherauyeung/portfolio,topherauyeung/portfolio,matyikriszta/moonlit-landing-page,fenderdigital/css-utilities,tachyons-css/tachyons,fenderdigital/css-utilities,cwonrails/tachyons,pietgeursen/pietgeursen.github.io,topherauyeung/portfolio
|
d4f7822658f0c67952bc861f8efc10431c481cb1
|
put_comma.js
|
put_comma.js
|
var num;
var num_str;
var result = '';
// check args
if (process.argv.length < 3) { // sample value
num = Math.floor(Math.random() * 1000000000) + 1;
} else {
num = process.argv[2];
}
num_str = num.toString();
console.log('input: ' + num_str);
while (num_str.length > 0) {
var three_digits = num_str.slice(-3); // get 3 digits
result = three_digits + result;
num_str = num_str.slice(0, -3); // remove 3 digits
if (num_str.length >= 1) {
result = ',' + result;
}
}
console.log(result);
|
var num;
var num_str;
var result = '';
// check args
if (process.argv.length < 3) { // sample value
num = Math.floor(Math.random() * 1000000000) + 1;
} else {
num = process.argv[2];
}
console.log('input: ' + num);
num_str = Number(num).toString();
while (num_str.length > 0) {
var three_digits = num_str.slice(-3); // get 3 digits
result = three_digits + result;
num_str = num_str.slice(0, -3); // remove 3 digits
if (num_str.length >= 1) {
result = ',' + result;
}
}
console.log(result);
|
Deal with a case starting 0, e.g. input: 01234, output: 1,234
|
Deal with a case starting 0, e.g. input: 01234, output: 1,234
|
JavaScript
|
mit
|
moji29nabe/quiz
|
020d181694878a374fa1ae8606942a0b77d40ae7
|
app/js/pointer-lock.js
|
app/js/pointer-lock.js
|
import THREE from 'three';
export default function pointerLock( controls ) {
const hasPointerLock = 'pointerLockElement' in document ||
'mozPointerLockElement' in document ||
'webkitPointerLockElement' in document;
if ( !hasPointerLock ) {
return;
}
const element = document.body;
const dispatcher = new THREE.EventDispatcher();
function onPointerLockChange() {
if ( document.pointerLockElement === element ||
document.mozPointerLockElement === element ||
document.webkitPointerLockElement === element ) {
controls.enabled = true;
} else {
controls.enabled = false;
}
dispatcher.dispatchEvent({
type: 'change',
enabled: controls.enabled
});
}
function onPointerLockError() {
dispatcher.dispatchEvent({ type: 'error' });
}
document.addEventListener( 'pointerlockchange', onPointerLockChange );
document.addEventListener( 'mozpointerlockchange', onPointerLockChange );
document.addEventListener( 'webkitpointerlockchange', onPointerLockChange );
document.addEventListener( 'pointerlockerror', onPointerLockError );
document.addEventListener( 'mozpointerlockerror', onPointerLockError );
document.addEventListener( 'webkitpointerlockerror', onPointerLockError );
element.requestPointerLock = element.requestPointerLock ||
element.mozRequestPointerLock ||
element.webkitRequestPointerLock;
document.addEventListener( 'click', () => element.requestPointerLock() );
return dispatcher;
}
|
import THREE from 'three';
export default function pointerLock( controls, element = document.body ) {
const hasPointerLock = (
'pointerLockElement' in document ||
'mozPointerLockElement' in document ||
'webkitPointerLockElement' in document
);
if ( !hasPointerLock ) {
return;
}
const dispatcher = new THREE.EventDispatcher();
function onPointerLockChange() {
controls.enabled = (
element === document.pointerLockElement ||
element === document.mozPointerLockElement ||
element === document.webkitPointerLockElement
);
dispatcher.dispatchEvent({
type: 'change',
enabled: controls.enabled
});
}
function onPointerLockError() {
dispatcher.dispatchEvent({ type: 'error' });
}
document.addEventListener( 'pointerlockchange', onPointerLockChange );
document.addEventListener( 'mozpointerlockchange', onPointerLockChange );
document.addEventListener( 'webkitpointerlockchange', onPointerLockChange );
document.addEventListener( 'pointerlockerror', onPointerLockError );
document.addEventListener( 'mozpointerlockerror', onPointerLockError );
document.addEventListener( 'webkitpointerlockerror', onPointerLockError );
element.requestPointerLock = (
element.requestPointerLock ||
element.mozRequestPointerLock ||
element.webkitRequestPointerLock
);
document.addEventListener( 'click', () => element.requestPointerLock() );
return dispatcher;
}
|
Add pointerLock() custom element support.
|
Add pointerLock() custom element support.
Increase readability.
|
JavaScript
|
mit
|
razh/third-person-camera-tests,razh/third-person-camera-tests
|
e215805c984d8f3da9e5b4380ddf20ea76a88e9e
|
app/routes/accounts.js
|
app/routes/accounts.js
|
import Ember from 'ember';
export default Ember.Route.extend({
model: function(params) {
return this.store.find('namespace', btoa(params.namespace));
}
});
|
import Ember from 'ember';
export default Ember.Route.extend({
setupController: function(controller, model) {
// Model Hook is called only when the page is accessed via direct
// navigation
var namespace = this.store.fetch('namespace', btoa(model.namespace));
controller.set('model', namespace);
},
});
|
Fix model hook not being called when performing 'transitionToRoute'
|
Fix model hook not being called when performing 'transitionToRoute'
|
JavaScript
|
mit
|
nihey/firehon,nihey/firehon
|
833e6dc23b1d9d2b6d81cd0c68654a904f045578
|
src/modules/gallery-lazy-load.js
|
src/modules/gallery-lazy-load.js
|
import axios from 'axios';
function Loader(options = {}) {
this.page = options.page || 0;
this.limit = options.limit || 1;
this.url = options.url || '';
this.nextPage = () => {
this.page += 1;
return axios.get(this.url, {
params: {
page: this.page,
limit: this.limit,
},
responseType: 'text',
});
};
}
function observeLastPost(observer) {
const posts = document.querySelectorAll('.gallery-post');
const lastPost = posts[posts.length - 1];
observer.observe(lastPost);
return lastPost;
}
export default (options) => {
let observer;
const galleryContainer = document.querySelector('.gallery-posts');
const loader = new Loader({
url: '/api/gallery',
page: 2,
limit: 1,
});
const handler = (entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
observer.unobserve(entry.target);
loader.nextPage()
.then(({ data: postHtml }) => {
galleryContainer.insertAdjacentHTML('beforeend', postHtml);
const lastPost = observeLastPost(observer);
if (options.afterInsert && typeof options.afterInsert === 'function') {
options.afterInsert(lastPost);
}
}).catch(() => {
// No more posts
});
}
});
};
observer = new IntersectionObserver(handler, {
threshold: 0,
});
observeLastPost(observer);
}
|
import Loader from 'src/modules/lazy-loader';
let observer;
let galleryContainer;
const loader = new Loader({
url: '/api/gallery',
page: 2,
limit: 1,
});
function lastPost() {
const posts = document.querySelectorAll('.gallery-post');
return posts[posts.length - 1];
}
function observeLastPost() {
if (!observer) return false;
observer.observe(lastPost());
return lastPost;
}
export default (options) => {
galleryContainer = document.querySelector('.gallery-posts');
const next = () => {
loader.nextPage()
.then(({ data: html }) => {
galleryContainer.insertAdjacentHTML('beforeend', html);
if (observer) observeLastPost();
if (options.afterInsert && typeof options.afterInsert === 'function') {
options.afterInsert(lastPost());
}
})
.catch(() => {
// No more posts
});
}
const observerHandler = (entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
if (observer) observer.unobserve(entry.target);
next();
}
});
};
if (!('IntersectionObserver' in window)) {
// Alternative routine
document.body.classList.add('no-intersection-observer');
document
.querySelector('button.compat-int-obs')
.addEventListener('click', next);
} else {
// Modern browser
observer = new IntersectionObserver(observerHandler, {
threshold: 0,
});
observeLastPost();
}
}
|
Add old browser compat routine for loading pictures
|
Add old browser compat routine for loading pictures
|
JavaScript
|
mit
|
tuelsch/bolg,tuelsch/bolg
|
616cfb178b1af953a73e01febef0bc8aac6017f3
|
templates/footer.handlebars.js
|
templates/footer.handlebars.js
|
let tpl = `
</body>
</html>
`;
exports.tpl = () => tpl;
|
let tpl = `
<hr />
<address>MirrorJson version 0.90. Idea, design and implementation by Arne Bakkebø, Making Waves in 2017.</address>
</body>
</html>
`;
exports.tpl = () => tpl;
|
Add footer info and version number
|
Add footer info and version number
|
JavaScript
|
mit
|
makingwaves/mirrorjson,makingwaves/mirrorjson
|
4f6b6937c7f67aa02898478e34506ed80c9e33a4
|
resources/public/js/monitor.js
|
resources/public/js/monitor.js
|
var maxColumns = 3
var buildStatusPadding = 10
var fontResizeFactor = 1.6
function buildStatusCount() {
return $('li').size()
}
function numberOfColumns() {
return Math.min(maxColumns, buildStatusCount())
}
function numberOfRows() {
return Math.ceil(buildStatusCount() / maxColumns)
}
function buildStatusWidth() {
return window.innerWidth / numberOfColumns() - buildStatusPadding
}
function buildStatusHeight() {
return window.innerHeight / numberOfRows() - buildStatusPadding
}
function scaleFontToContainerSize() {
$(".outerContainer").fitText(fontResizeFactor)
}
function styleListItems() {
$('.outerContainer').height(buildStatusHeight()).width(buildStatusWidth())
scaleFontToContainerSize()
}
function addBuildStatusToScreen(project) {
var buildStatus = project.lastBuildStatus
if(buildStatus !== "Success"){
$('#projects').append("<li><div class=outerContainer><div class=innerContainer>" +
project.name + "</div></div></li>")
}
}
function addListItems(data) {
$('#projects').empty()
data.body.forEach(addBuildStatusToScreen)
}
function updateBuildMonitor() {
$.getJSON("/projects").then(function(data){
addListItems(data)
styleListItems()
})
}
updateBuildMonitor() // run immediately
setInterval(updateBuildMonitor, 5000)
|
function Styler() {
this.maxColumns = 3
this.buildStatusPadding = 10
this.fontResizeFactor = 1.6
function buildStatusCount() {
return $('li').size()
}
function numberOfColumns() {
return Math.min(maxColumns, buildStatusCount())
}
function numberOfRows() {
return Math.ceil(buildStatusCount() / maxColumns)
}
function buildStatusWidth() {
return window.innerWidth / numberOfColumns() - buildStatusPadding
}
function buildStatusHeight() {
return window.innerHeight / numberOfRows() - buildStatusPadding
}
function scaleFontToContainerSize() {
$(".outerContainer").fitText(fontResizeFactor)
}
this.styleListItems = function () {
$('.outerContainer').height(buildStatusHeight()).width(buildStatusWidth())
scaleFontToContainerSize()
}
}
function StatusAppender(projects) {
this.projects = projects
function addBuildStatusToScreen(project) {
var buildStatus = project.lastBuildStatus
if(buildStatus !== "Success"){
$('#projects').append("<li><div class=outerContainer><div class=innerContainer>" +
project.name + "</div></div></li>")
}
}
this.addListItems = function() {
$('#projects').empty()
projects.forEach(addBuildStatusToScreen)
}
}
function updateBuildMonitor() {
$.getJSON("/projects").then(function(data){
new StatusAppender(data.body).addListItems()
new Styler().styleListItems()
})
}
updateBuildMonitor() // run immediately
setInterval(updateBuildMonitor, 5000)
|
Introduce JS enclosing functions to separate Styling from DOM manipulation
|
Introduce JS enclosing functions to separate Styling from DOM manipulation
|
JavaScript
|
epl-1.0
|
antoniou/nevergreen-standalone,cburgmer/nevergreen,darrenhaken/nevergreen,darrenhaken/nevergreen,cburgmer/nevergreen,darrenhaken/nevergreen,antoniou/nevergreen-standalone,build-canaries/nevergreen,build-canaries/nevergreen,cburgmer/nevergreen,antoniou/nevergreen-standalone,build-canaries/nevergreen,build-canaries/nevergreen
|
4d3fd2b55084f8033cad20ee5e939b0bdbac25a5
|
blob-feature-check.js
|
blob-feature-check.js
|
var svg = new Blob(
["<svg xmlns='http://www.w3.org/2000/svg'></svg>"],
{type: "image/svg+xml;charset=utf-8"}
);
var img = new Image();
var featureDiv = document.getElementById("blob-urls");
img.onload = function() {
featureDiv.className += " feature-supported";
};
img.onerror = function() {
featureDiv.className += " feature-unsupported";
};
img.src = URL.createObjectURL(svg);
|
var svg = new Blob(
["<svg xmlns='http://www.w3.org/2000/svg'></svg>"],
{type: "image/svg+xml;charset=utf-8"}
);
var img = new Image();
var featureDiv = document.getElementById("blob-urls");
img.onload = function() {
featureDiv.className += " feature-supported";
};
img.onerror = function() {
featureDiv.className += " feature-unsupported";
};
// Safari 6 uses "webkitURL".
var url = window.webkitURL || window.URL;
img.src = url.createObjectURL(svg);
|
Use webkitURL for Safari 6
|
Use webkitURL for Safari 6
Other browsers use window.URL, but Safari 6 namespaced it to "webkit".
|
JavaScript
|
mit
|
ssorallen/blob-feature-check,ssorallen/blob-feature-check
|
8c03d3e088db12b410cdc6d7e301a05b6ebd8745
|
js/views/conversation_list_view.js
|
js/views/conversation_list_view.js
|
/*
* vim: ts=4:sw=4:expandtab
*/
(function () {
'use strict';
window.Whisper = window.Whisper || {};
Whisper.ConversationListView = Whisper.ListView.extend({
tagName: 'div',
itemView: Whisper.ConversationListItemView,
sort: function(conversation) {
console.log('sorting conversation', conversation.id);
var $el = this.$('.' + conversation.cid);
if ($el && $el.length > 0) {
var index = getInboxCollection().indexOf(conversation);
if (index > 0) {
$el.insertBefore(this.$('.conversation-list-item')[index+1]);
} else {
this.$el.prepend($el);
}
}
}
});
})();
|
/*
* vim: ts=4:sw=4:expandtab
*/
(function () {
'use strict';
window.Whisper = window.Whisper || {};
Whisper.ConversationListView = Whisper.ListView.extend({
tagName: 'div',
itemView: Whisper.ConversationListItemView,
sort: function(conversation) {
console.log('sorting conversation', conversation.id);
var $el = this.$('.' + conversation.cid);
if ($el && $el.length > 0) {
var index = getInboxCollection().indexOf(conversation);
if (index === 0) {
this.$el.prepend($el);
} else if (index === this.collection.length - 1) {
this.$el.append($el);
} else {
$el.insertBefore(this.$('.conversation-list-item')[index+1]);
}
}
}
});
})();
|
Fix sorting of the last element
|
Fix sorting of the last element
// FREEBIE
|
JavaScript
|
agpl-3.0
|
nrizzio/Signal-Desktop,nrizzio/Signal-Desktop,nrizzio/Signal-Desktop,nrizzio/Signal-Desktop
|
589baa87b799e86d070c3c446e32c21e193b9c61
|
test/app.js
|
test/app.js
|
/**
* @license
* Copyright (c) 2016 The IBM Research Emergent Solutions authors. All rights reserved.
* This code may only be used under the MIT style license found at https://ibmresearch.github.io/LICENSE.txt
* The complete set of authors may be found at https://ibmresearch.github.io/AUTHORS.txt
* The complete set of contributors may be found at https://ibmresearch.github.io/CONTRIBUTORS.txt
*/
'use strict';
var path = require('path');
var assert = require('yeoman-assert');
var helpers = require('yeoman-test');
describe('generator-polymer-init-ibm-element:app', function() {
before(function() {
return helpers.run(path.join(__dirname, '../generators/app'))
.withPrompts({
elementName: 'ibm-element',
elementDescription: 'IBM element description',
githubOrganization: 'IBMResearch'
})
.toPromise();
});
it('creates files', function() {
assert.file([
'demo/index.html',
'test/ibm-element.html',
'test/index.html',
'.gitignore',
'ibm-element.html',
'bower.json',
'index.html',
'LICENSE',
'README.md'
]);
});
});
|
/**
* @license
* Copyright (c) 2016 The IBM Research Emergent Solutions authors. All rights reserved.
* This code may only be used under the MIT style license found at https://ibmresearch.github.io/LICENSE.txt
* The complete set of authors may be found at https://ibmresearch.github.io/AUTHORS.txt
* The complete set of contributors may be found at https://ibmresearch.github.io/CONTRIBUTORS.txt
*/
'use strict';
var path = require('path');
var assert = require('yeoman-assert');
var helpers = require('yeoman-test');
describe('generator-polymer-init-ibm-element:app', function() {
before(function() {
return helpers.run(path.join(__dirname, '../generators/app'))
.withPrompts({
elementName: 'ibm-element',
elementDescription: 'IBM element description',
githubOrganization: 'IBMResearch'
})
.toPromise();
});
it('creates files', function() {
assert.file([
'demo/index.html',
'test/ibm-element.html',
'test/index.html',
'.gitignore',
'.eslintrc.json',
'bower.json',
'ibm-element.html',
'index.html',
'LICENSE',
'README.md'
]);
});
});
|
Add missed file to the test
|
Add missed file to the test
|
JavaScript
|
mit
|
IBMResearch/generator-polymer-init-ibm-element,IBMResearch/generator-polymer-init-ibm-element
|
681d637a01145bb623f035b9dec7a1fe5a1d7255
|
lib/matchers/hashmap.js
|
lib/matchers/hashmap.js
|
var _ = require('lodash');
var Matcher = require('../matcher');
var factory = require('../factory');
var compile = require('../compile');
var s = require('../strummer');
module.exports = factory({
initialize: function(opts) {
var matchers = { keys: null, values: null };
if (opts instanceof Matcher) {
matchers.values = opts;
} else if (typeof opts === 'object') {
matchers.keys = opts.keys ? compile.spec(opts.keys) : null;
matchers.values = opts.values ? compile.spec(opts.values) : null;
} else if (opts) {
matchers.values = compile.spec(opts);
}
this.matchers = matchers;
},
match: function(path, obj) {
if (obj == null || typeof obj !== 'object') {
return [{path: path, value: obj, message: 'should be a hashmap'}];
}
var errors = [];
if (this.matchers.keys) {
var keyErrors = s.array({of: this.matchers.keys}).match(path + '.keys', Object.keys(obj));
errors.push(keyErrors);
}
if (this.matchers.values) {
errors.push(_.map(obj, function(val, key) {
return this.matchers.values.match(path + '[' + key + ']', val);
}, this));
}
return _.compact(_.flattenDeep(errors));
}
});
|
var _ = require('lodash');
var Matcher = require('../matcher');
var factory = require('../factory');
var compile = require('../compile');
var s = require('../strummer');
module.exports = factory({
initialize: function(opts) {
var matchers = { keys: null, values: null };
if (opts instanceof Matcher) {
matchers.values = opts;
} else if (typeof opts === 'object') {
matchers.keys = opts.keys ? compile.spec(opts.keys) : null;
matchers.values = opts.values ? compile.spec(opts.values) : null;
} else if (opts) {
matchers.values = compile.spec(opts);
}
this.matchers = matchers;
},
match: function(path, obj) {
if (obj == null || typeof obj !== 'object') {
return [{path: path, value: obj, message: 'should be a hashmap'}];
}
var errors = [];
if (this.matchers.keys) {
var keyErrors = s.array({of: this.matchers.keys}).match(path + '.keys', Object.keys(obj));
errors.push(keyErrors);
}
if (this.matchers.values) {
var self = this;
errors.push(_.map(obj, function(val, key) {
return self.matchers.values.match(path + '[' + key + ']', val);
}));
}
return _.compact(_.flattenDeep(errors));
}
});
|
Fix error with lodash map
|
Fix error with lodash map
|
JavaScript
|
mit
|
TabDigital/strummer
|
aa5fe28d4a40438849c88ff067b072cb78ae7940
|
src/server/routes.js
|
src/server/routes.js
|
'use strict';
const router = require('express').Router();
const authRouter = require('./auth/authRouter');
const trackRouter = require('./track/trackRouter');
router.get('/', function(req, res) {
res.send('Scrawble dat track j0!');
});
router.use('/auth', authRouter);
router.use('/scrobbles', trackRouter);
module.exports = router;
|
'use strict';
const router = require('express').Router();
const authRouter = require('./auth/authRouter');
const trackRouter = require('./track/trackRouter');
router.get('/', function(req, res) {
res.send(`Your token is ${req.query.token}. Scrawble dat track j0!`);
});
router.use('/auth', authRouter);
router.use('/scrobbles', trackRouter);
module.exports = router;
|
Send back token as part of response
|
Send back token as part of response
|
JavaScript
|
mit
|
FTLam11/Audio-Station-Scrobbler,FTLam11/Audio-Station-Scrobbler
|
49c6c49ad5934b45de95571a6ecb31223cda589a
|
run/index.js
|
run/index.js
|
var path = require('path')
var command = process.argv[2]
var restArguments = process.argv.slice(2)
var root = path.join(__dirname, '..')
var execute = require('./execute')({
BIN: path.join(root, 'node_modules', '.bin'),
JS_INPUT: path.join(root, 'src', 'app.js'),
JS_OUTPUT: path.join(root, 'dist', 'bundle.js')
})
var formattedOutput = require('./formatted_output')
function run(task) {
formattedOutput.start({ taskname: task })
return execute(task)
.then(formattedOutput.success)
.catch(formattedOutput.fail)
}
var tasks = {
js() {
run('browserify')
},
watch_js() {
run('watchify')
}
}
if (command in tasks) {
tasks[command](restArguments)
} else {
console.error(`The task ${command} doesn't exist.`)
process.exit(1)
}
module.exports = run
|
var path = require('path')
var [ command, ...restArguments ] = process.argv.slice(2)
var root = path.join(__dirname, '..')
var execute = require('./execute')({
BIN: path.join(root, 'node_modules', '.bin'),
JS_INPUT: path.join(root, 'src', 'app.js'),
JS_OUTPUT: path.join(root, 'dist', 'bundle.js')
})
var formattedOutput = require('./formatted_output')
function run(task) {
formattedOutput.start({ taskname: task })
return execute(task)
.then(formattedOutput.success)
.catch(formattedOutput.fail)
}
var tasks = {
js() {
run('browserify')
},
watch_js() {
run('watchify')
}
}
if (command in tasks) {
tasks[command](restArguments)
} else {
console.error(`The task ${command} doesn't exist.`)
process.exit(1)
}
module.exports = run
|
Improve parsing of cli arguments
|
Improve parsing of cli arguments
|
JavaScript
|
mit
|
scriptype/salinger,scriptype/salinger
|
b865cafc14bf29b97b5fea9484f3730c2772d0ec
|
mix/lib/stream.js
|
mix/lib/stream.js
|
'use strict';
var Kefir = require('kefir');
module.exports = Stream;
function Stream(value) {
if (typeof value === 'function') {
var subscribe = value;
this._observable = Kefir.fromBinder(function (sink) {
return subscribe({
push: sink,
close: function (value) {
if (typeof value !== 'undefined') {
sink(value);
}
sink(Kefir.END);
}
});
}, this);
} else {
this._observable = value;
}
this._consumers = 0;
process.nextTick(function () {
if (this._consumers === 0) {
this._consumers++;
this._observable.onValue(function () {});
}
}.bind(this));
}
Stream.prototype.pipe = function (sink) {
this._consumers++;
return new Stream(this._observable.flatMap(function (input) {
output = sink(input);
if (output instanceof Stream) {
return output._observable;
} else {
return Kefir.once(output);
}
}));
};
|
'use strict';
var Kefir = require('kefir');
module.exports = Stream;
function Stream(value) {
if (typeof value === 'function') {
var subscribe = value;
this._observable = Kefir.fromBinder(function (sink) {
return subscribe({
push: sink,
close: function (value) {
if (typeof value !== 'undefined') {
sink(value);
}
sink(Kefir.END);
}
});
}, this);
} else {
this._observable = value;
}
this._consumers = 0;
process.nextTick(function () {
if (this._consumers === 0) {
this._consumers++;
this._observable.onValue(function () {});
}
}.bind(this));
}
Stream.prototype.pipe = function (sink) {
this._consumers++;
return new Stream(this._observable.flatMap(function (input) {
var output = sink(input);
if (output instanceof Stream) {
return output._observable;
} else {
return Kefir.once(output);
}
}));
};
|
Fix accidental global variable assignment
|
Fix accidental global variable assignment
|
JavaScript
|
mit
|
byggjs/bygg-plugins,byggjs/bygg
|
f8b68dae34c8f3308531bb2c28a3ff7047c0f4e1
|
tests/bind.spec.js
|
tests/bind.spec.js
|
import { Vue, firebase, firestore, VueTick, randomString } from './TestCase'
let vm, collection, doc
let collectionName = randomString()
let documentName = randomString()
describe('Manual binding', () => {
beforeEach(async () => {
collection = firestore.collection('items')
doc = firestore.doc('collectionOfDocs/doc')
vm = new Vue({
data: () => ({
//
})
})
await VueTick()
})
test('Bind collection manually', async () => {
await vm.$binding(collectionName, firestore.collection(collectionName))
expect(vm[collectionName]).toEqual([])
await vm.$firestore[collectionName].add({name: 'item'})
expect(vm[collectionName].length).toEqual(1)
expect(vm[collectionName][0].name).toEqual('item')
})
test('Bind document manually', async () => {
await vm.$binding(documentName, doc)
expect(vm.$firestore[documentName]).toBe(doc)
expect(vm[documentName]).toEqual({'.key': 'doc', 'name': 'docName'})
})
test('Binding collection returns promise', async () => {
expect(vm.$binding('someCollections', collection) instanceof Promise).toBe(true)
})
test('Binding document returns promise', async () => {
expect(vm.$binding('someCollections', doc) instanceof Promise).toBe(true)
})
})
|
import { Vue, firebase, firestore, VueTick, randomString } from './TestCase'
let vm, collection, doc
let collectionName = randomString()
let documentName = randomString()
describe('Manual binding', () => {
beforeEach(async () => {
collection = firestore.collection('items')
doc = firestore.doc('collectionOfDocs/doc')
vm = new Vue({
data: () => ({
//
})
})
await VueTick()
})
test('Bind collection manually', async () => {
await vm.$binding(collectionName, firestore.collection(collectionName))
expect(vm[collectionName]).toEqual([])
await vm.$firestore[collectionName].add({name: 'item'})
expect(vm[collectionName].length).toEqual(1)
expect(vm[collectionName][0].name).toEqual('item')
let updatedItem = vm[collectionName][0]
await vm.$firestore[collectionName].doc(updatedItem['.key']).update({name: 'item2'})
expect(vm[collectionName].length).toEqual(1)
expect(vm[collectionName][0].name).toEqual('item2')
})
test('Bind document manually', async () => {
await vm.$binding(documentName, doc)
expect(vm.$firestore[documentName]).toBe(doc)
expect(vm[documentName]).toEqual({'.key': 'doc', 'name': 'docName'})
})
test('Binding collection returns promise', async () => {
expect(vm.$binding('someCollections', collection) instanceof Promise).toBe(true)
})
test('Binding document returns promise', async () => {
expect(vm.$binding('someCollections', doc) instanceof Promise).toBe(true)
})
})
|
Add tests for update doc in collection
|
Add tests for update doc in collection
|
JavaScript
|
mit
|
gdg-tangier/vue-firestore
|
49006a90b6ed3184f706a2688b3a51fa34de8d8f
|
routerpwn.js
|
routerpwn.js
|
var csv = require('./lib/csv.js');
//Object to hold all the data
var vendors = {};
var init = function(callback) {
csv.each(__dirname + '/macVendor/vendors.csv').on('data', function(data) {
vendors[data[1]] = {
'prefix': data[1],
'manufacturer': data[2],
'manufacturerAdress': data[3]
};
}).on('end', function() {
console.log('Finished');
if(callback) {
callback(vendors);
}
});
};
var getVendorForMac = function(macAddress) {
for(var macPrefix in vendors) {
if(macAddress.startsWith(macPrefix)) {
return vendors[macPrefix];
}
}
};
var pwn = function(macAddress) {
var vendor = getVendorForMac(macAddress);
switch (vendor.manufacturer) {
case 'Arcadyan Technology Corporation':
return require(__dirname + '/exploits/easybox.js')(macAddress);
break;
}
}
module.exports = {
init: init,
getVendorForMac: getVendorForMac,
pwn: pwn
};
|
var csv = require('./lib/csv.js');
//Object to hold all the data
var vendors = {};
var init = function(callback) {
csv.each(__dirname + '/macVendor/vendors.csv').on('data', function(data) {
vendors[data[1]] = {
'prefix': data[1],
'manufacturer': data[2],
'manufacturerAdress': data[3]
};
}).on('end', function() {
console.log('Finished');
if(callback) {
callback(vendors);
}
});
};
var getVendorForMac = function(macAddress) {
for(var macPrefix in vendors) {
if(macAddress.startsWith(macPrefix)) {
return vendors[macPrefix];
}
}
};
var pwn = function(macAddress) {
var vendor = getVendorForMac(macAddress.replace(/:/g, '').replace(/-/g, ''));
switch (vendor.manufacturer) {
case 'Arcadyan Technology Corporation':
return require(__dirname + '/exploits/easybox.js')(macAddress);
break;
}
}
module.exports = {
init: init,
getVendorForMac: getVendorForMac,
pwn: pwn
};
|
Replace ':' and '-' to check the MAC-prefix
|
Replace ':' and '-' to check the MAC-prefix
|
JavaScript
|
mit
|
jannickfahlbusch/node-routerpwn
|
3be1f95dcaafb09e8836979d79b02aeede891487
|
routes/index.js
|
routes/index.js
|
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index');
});
/* Mode selection page. */
router.get('/select', function(req, res, next) {
res.render('select');
});
/* Page to start a new room with friends. */
router.get('/start-room', function(req, res, next) {
res.render('start-room');
});
/* Page to join a room of friends. */
router.get('/join-room', function(req, res, next) {
res.render('join-room');
});
/* Page to join a random room. */
router.get('/join-random', function(req, res, next) {
res.render('join-random');
});
/* Gameplay page components. Should be called with AJAX. */
router.post('/game', function(req, res, next) {
res.render('game', { playerId: req.body.playerId});
});
/* If people directly try to access /play, redirect them home.
* This URL is displayed when playing the game. */
router.get('/play', function(req, res, next) {
res.redirect('/');
});
module.exports = router;
|
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index');
});
/* Mode selection page. */
router.get('/select', function(req, res, next) {
res.render('select');
});
/* Page to start a new room with friends. */
router.get('/start-room', function(req, res, next) {
res.render('start-room');
});
/* Page to join a room of friends. */
router.get('/join-room', function(req, res, next) {
res.render('join-room');
});
/* Page to join a random room. */
router.get('/join-random', function(req, res, next) {
res.render('join-random');
});
/* Gameplay page components. Should be called with AJAX. */
router.post('/game', function(req, res, next) {
res.render('game', { playerId: req.body.playerId});
});
/* If people directly try to access /play, redirect them home.
* This URL is displayed when playing the game. */
router.get('/play', function(req, res, next) {
res.redirect('/');
});
module.exports = router;
|
Fix indentation on routes page.
|
Fix indentation on routes page.
|
JavaScript
|
mit
|
nashkevin/Turing-Party,nashkevin/Turing-Party
|
5c110374d1c75c8892f074a9ea15dbb73744924e
|
.eslintrc.js
|
.eslintrc.js
|
module.exports = {
env: {
browser: true,
es2021: true,
},
extends: [
'standard',
],
parserOptions: {
ecmaVersion: 12,
sourceType: 'module',
},
plugins: [
'svelte3',
],
overrides: [
{
files: ['**/*.svelte'],
processor: 'svelte3/svelte3',
rules: {
'import/first': ['off', 'always'],
'no-multiple-empty-lines': ['error', { max: 1, maxBOF: 2, maxEOF: 0 }],
},
},
],
rules: {
indent: ['error', 4],
}
}
|
module.exports = {
env: {
browser: true,
es2021: true,
},
extends: [
'standard',
],
parserOptions: {
ecmaVersion: 12,
sourceType: 'module',
},
plugins: [
'svelte3',
],
overrides: [
{
files: ['**/*.svelte'],
processor: 'svelte3/svelte3',
rules: {
'import/first': ['off', 'always'],
'no-multiple-empty-lines': ['error', { max: 1, maxBOF: 2, maxEOF: 0 }],
},
},
],
rules: {
'comma-dangle': ['off', 'always'],
'indent': ['error', 4],
'no-console': ['warn', {}],
}
}
|
Allow dangling commas and warn about console statements
|
eslint: Allow dangling commas and warn about console statements
|
JavaScript
|
mit
|
peterhil/ninhursag,peterhil/ninhursag,peterhil/ninhursag,peterhil/ninhursag
|
87b264835136852a5aa0832d1ea75a04a0172817
|
app/assets/javascripts/alchemy/alchemy.page_sorter.js
|
app/assets/javascripts/alchemy/alchemy.page_sorter.js
|
Alchemy.PageSorter = function () {
var $sortables = $("ul#sitemap").find("ul.level_1_children")
$sortables.nestedSortable({
disableNesting: "no-nest",
forcePlaceholderSize: true,
handle: ".handle",
items: "li",
listType: "ul",
opacity: 0.5,
placeholder: "placeholder",
tabSize: 16,
tolerance: "pointer",
toleranceElement: "> div"
})
$("#save_page_order").click(function (e) {
e.preventDefault()
Alchemy.Buttons.disable(this)
$.post(Alchemy.routes.order_admin_pages_path, {
set: JSON.stringify($sortables.nestedSortable("toHierarchy"))
})
})
}
|
Alchemy.PageSorter = function () {
var $sortables = $("ul#sitemap").find("ul.level_0_children")
$sortables.nestedSortable({
disableNesting: "no-nest",
forcePlaceholderSize: true,
handle: ".handle",
items: "li",
listType: "ul",
opacity: 0.5,
placeholder: "placeholder",
tabSize: 16,
tolerance: "pointer",
toleranceElement: "> div"
})
$("#save_page_order").click(function (e) {
e.preventDefault()
Alchemy.Buttons.disable(this)
$.post(Alchemy.routes.order_admin_pages_path, {
set: JSON.stringify($sortables.nestedSortable("toHierarchy"))
})
})
}
|
Fix page sorting after root page removal
|
Fix page sorting after root page removal
Since we removed the root page we need to adjust the sortable items
class.
|
JavaScript
|
bsd-3-clause
|
mamhoff/alchemy_cms,robinboening/alchemy_cms,AlchemyCMS/alchemy_cms,robinboening/alchemy_cms,AlchemyCMS/alchemy_cms,robinboening/alchemy_cms,AlchemyCMS/alchemy_cms,mamhoff/alchemy_cms,mamhoff/alchemy_cms
|
da6a95170c50d33180da30775d460ce160f2101b
|
app/assets/javascripts/views/dashboard_report_view.js
|
app/assets/javascripts/views/dashboard_report_view.js
|
// ELMO.Views.DashboardReport
//
// View model for the dashboard report
ELMO.Views.DashboardReportView = class DashboardReportView extends ELMO.Views.ApplicationView {
get el() {
return '.report';
}
get events() {
return {
'change .report-chooser': 'handleReportChange',
'click .action-link-close': 'handleReportClose',
};
}
handleReportChange(e) {
const id = $(e.target).val();
if (id) {
this.changeReport(id, $(e.target).find('option:selected').text());
}
}
handleReportClose(e) {
e.preventDefault();
this.changeReport(null, I18n.t('activerecord.models.report/report.one'));
}
changeReport(id, name) {
this.toggleLoader(true);
this.$('.report-title-text').html(name);
this.$('.report-chooser').find('option').attr('selected', false);
this.$('.report-output-and-modal').empty();
this.$('.action-link').hide();
this.$el.load(ELMO.app.url_builder.build(`dashboard/report?id=${id || ''}`));
}
toggleLoader(bool) {
$('.report-pane-header .inline-load-ind img').toggle(bool);
}
};
|
// ELMO.Views.DashboardReport
//
// View model for the dashboard report
ELMO.Views.DashboardReportView = class DashboardReportView extends ELMO.Views.ApplicationView {
get el() {
return '.report';
}
get events() {
return {
'change .report-chooser': 'handleReportChange',
'click .action-link-close': 'handleReportClose',
};
}
handleReportChange(e) {
const id = $(e.target).val();
if (id) {
this.changeReport(id, $(e.target).find('option:selected').text());
}
}
handleReportClose(e) {
e.preventDefault();
this.changeReport(null, I18n.t('activerecord.models.report/report.one'));
}
changeReport(id, name) {
if (this.request) {
this.request.abort();
}
this.toggleLoader(true);
this.$('.report-title-text').html(name);
this.$('.report-chooser').find('option').attr('selected', false);
this.$('.report-output-and-modal').empty();
this.$('.action-link').hide();
const url = ELMO.app.url_builder.build(`dashboard/report?id=${id || ''}`);
this.request = $.get(url, this.handleReportLoaded.bind(this));
}
handleReportLoaded(html) {
this.request = null;
this.$el.html(html);
}
toggleLoader(bool) {
$('.report-pane-header .inline-load-ind img').toggle(bool);
}
};
|
Abort running request if new one fired
|
11239: Abort running request if new one fired
|
JavaScript
|
apache-2.0
|
thecartercenter/elmo,thecartercenter/elmo,thecartercenter/elmo
|
d88889401bf3f1532ee55eb3cf3f157fb4a47719
|
BikeMates/BikeMates.Web/Scripts/App_Scripts/ProfileScript.js
|
BikeMates/BikeMates.Web/Scripts/App_Scripts/ProfileScript.js
|
$(document).ready(function () {
function AppViewModel() {
var self = this;
self.FirstName = ko.observable("");
self.SecondName = ko.observable("");
self.About = ko.observable("");
self.Picture = ko.observable("");
self.fullName = ko.computed(function () {
return self.FirstName() + " " + self.SecondName();
}, this);
$.ajax({
url: "http://localhost:51952/api/profile",
contentType: "application/json",
type: "GET",
header:{"Authorization" : "Bearer "+ sessionStorage.getItem(tokenKey) },
success: function (data) {
self.FirstName(data.firstName);
self.SecondName(data.secondName);
self.About(data.about);
self.Picture(data.picture);
},
error: function (data) {
alert("error occured");
}
});
}
// Activates knockout.js
// bind view model to referring view
ko.applyBindings(new AppViewModel());
});
|
$(document).ready(function () {
var tokenKey = sessionStorage.getItem()
function AppViewModel() {
var self = this;
self.FirstName = ko.observable("");
self.SecondName = ko.observable("");
self.About = ko.observable("");
self.Picture = ko.observable("");
self.fullName = ko.computed(function () {
return self.FirstName() + " " + self.SecondName();
}, this);
$.ajax({
url: "api/profile",
contentType: "application/json",
type: "GET",
header: {"Authorization " : " Bearer " + sessionStorage.getItem(tokenKey) }, // + sessionStorage.getItem(tokenKey)
success: function (data) {
self.FirstName(data.firstName);
self.SecondName(data.secondName);
self.About(data.about);
self.Picture(data.picture);
},
error: function (data) {
alert("error occured");
}
});
}
// Activates knockout.js
// bind view model to referring view
ko.applyBindings(new AppViewModel());
});
|
Create BLL for profile - edit js files
|
Create BLL for profile - edit js files
|
JavaScript
|
mit
|
BikeMates/bike-mates,BikeMates/bike-mates,BikeMates/bike-mates
|
bdeeb9cc823025cfed65340caeb69ae6cde91e22
|
server/index.js
|
server/index.js
|
var gpio = require('pi-gpio');
gpio.open(7, "in");
setInterval(function () {
gpio.read(7, function (err, value) {
if(err) {
console.log(err);
}
else {
console.log(value);
}
});
}, 5000);
process.on('SIGINT', function() {
console.log('Shutting down GPIO');
gpio.close(7);
});
|
var gpio = require('pi-gpio');
gpio.open(7, "in");
setInterval(function () {
gpio.read(7, function (err, value) {
if(err) {
console.log(err);
}
else {
console.log(value);
}
});
}, 5000);
process.on('SIGINT', function() {
console.log('Shutting down GPIO');
gpio.close(7);
process.exit();
});
|
Add missing process exit call
|
Add missing process exit call
|
JavaScript
|
mit
|
Sephizor/openboiler,Sephizor/openboiler,Sephizor/openboiler
|
f696511e83678c4fcc7fd78b8590ef859c61f8ac
|
src/js/_fontawesome-collection.js
|
src/js/_fontawesome-collection.js
|
import fontawesome from '@fortawesome/fontawesome'
import faCustomIcons from './_fontawesome-harrix-icons.js'
//import fontawesomeFreeRegular from '@fortawesome/fontawesome-free-regular'
import faSearch from '@fortawesome/fontawesome-free-solid/faSearch'
import faGithub from '@fortawesome/fontawesome-free-brands/faGithub'
fontawesome.library.add(faSearch);
fontawesome.library.add(faGithub);
|
import fontawesome from '@fortawesome/fontawesome'
import faCustomIcons from './_fontawesome-harrix-icons.js'
import faSearch from '@fortawesome/fontawesome-free-solid/faSearch'
import faGithub from '@fortawesome/fontawesome-free-brands/faGithub'
fontawesome.library.add(faSearch);
fontawesome.library.add(faGithub);
|
Delete unnecessary lines in the code
|
Delete unnecessary lines in the code
|
JavaScript
|
mit
|
Harrix/Harrix-Html-Template
|
db872fe4b98311d5ee3e459268e9d2ec133871b5
|
tasks/check_clean.js
|
tasks/check_clean.js
|
/*
* grunt-check-clean
* https://github.com/the-software-factory/grunt-check-clean
*
* Copyright (c) 2015 Stéphane Bisinger
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Please see the Grunt documentation for more information regarding task
// creation: http://gruntjs.com/creating-tasks
grunt.registerTask('check_clean', 'Ensure the git index is clean and that there are no untracked files or directories.', function() {
var done = this.async();
grunt.util.spawn({
cmd: 'git',
args: ['status', '--porcelain']
}, function(error, result) {
var ret = 0;
if (error !== 0 || result.stdout.length > 0) {
ret = new Error("The git index is not clean. Ensure there are no uncommitted changes or untracked files.");
}
done(ret);
});
});
};
|
/*
* grunt-check-clean
* https://github.com/the-software-factory/grunt-check-clean
*
* Copyright (c) 2015 Stéphane Bisinger
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Please see the Grunt documentation for more information regarding task
// creation: http://gruntjs.com/creating-tasks
grunt.registerTask('check_clean', 'Ensure the git index is clean and that there are no untracked files or directories.', function() {
var done = this.async();
grunt.util.spawn({
cmd: 'git',
args: ['status', '--porcelain']
}, function(error, result) {
var ret = 0;
if (error || result.stdout.length > 0) {
console.log(error);
console.log(result.stdout);
ret = new Error("The git index is not clean. Ensure there are no uncommitted changes or untracked files.");
}
done(ret);
});
});
};
|
Fix check on error messages.
|
Fix check on error messages.
|
JavaScript
|
mit
|
the-software-factory/grunt-check-clean
|
6306c7760de7e15a3e32143e19c0662d554d2091
|
test/ios/findProject.spec.js
|
test/ios/findProject.spec.js
|
jest.autoMockOff();
const findProject = require('../../src/config/ios/findProject');
const mockFs = require('mock-fs');
const projects = require('../fixtures/projects');
describe('ios::findProject', () => {
beforeEach(() => {
mockFs({ testDir: projects });
});
it('should return path to xcodeproj if found', () => {
const userConfig = {};
mockFs(projects.flat);
expect(findProject('')).toContain('.xcodeproj');
});
it('should ignore xcodeproj from example folders', () => {
const userConfig = {};
mockFs({
examples: projects.flat,
Examples: projects.flat,
example: projects.flat,
KeychainExample: projects.flat,
Zpp: projects.flat,
});
expect(findProject('').toLowerCase()).not.toContain('example');
});
it('should ignore xcodeproj from test folders at any level', () => {
const userConfig = {};
mockFs({
test: projects.flat,
IntegrationTests: projects.flat,
tests: projects.flat,
Zpp: {
tests: projects.flat,
src: projects.flat,
},
});
expect(findProject('').toLowerCase()).not.toContain('test');
});
afterEach(mockFs.restore);
});
|
jest.autoMockOff();
const findProject = require('../../src/config/ios/findProject');
const mockFs = require('mock-fs');
const projects = require('../fixtures/projects');
const userConfig = {};
describe('ios::findProject', () => {
beforeEach(() => {
mockFs({ testDir: projects });
});
it('should return path to xcodeproj if found', () => {
mockFs(projects.flat);
expect(findProject('')).toContain('.xcodeproj');
});
it('should return null if there\'re no projects', () => {
expect(findProject('')).toBe(null);
});
it('should ignore xcodeproj from example folders', () => {
mockFs({
examples: projects.flat,
Examples: projects.flat,
example: projects.flat,
KeychainExample: projects.flat,
Zpp: projects.flat,
});
expect(findProject('').toLowerCase()).not.toContain('example');
});
it('should ignore xcodeproj from test folders at any level', () => {
mockFs({
test: projects.flat,
IntegrationTests: projects.flat,
tests: projects.flat,
Zpp: {
tests: projects.flat,
src: projects.flat,
},
});
expect(findProject('').toLowerCase()).not.toContain('test');
});
afterEach(mockFs.restore);
});
|
Cover null case in ios/findProject
|
Cover null case in ios/findProject
|
JavaScript
|
mit
|
rnpm/rnpm
|
82c8799e9ae313c00e042d9943855bea9ee3e5c2
|
src/index.js
|
src/index.js
|
try {
require('external:electron-react-devtools').install();
} catch (e) {}
import React from 'react';
import ReactDOM from 'react-dom';
import RecorderUI from './ui/RecorderUI';
ReactDOM.render(
<div>
<RecorderUI />
</div>,
document.querySelector('main')
);
|
if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
try {
require('external:electron-react-devtools').install();
} catch (e) {
console.error(e);
}
}
import React from 'react';
import ReactDOM from 'react-dom';
import RecorderUI from './ui/RecorderUI';
ReactDOM.render(
<div>
<RecorderUI />
</div>,
document.querySelector('main')
);
|
Fix for noisy console warning
|
Fix for noisy console warning
|
JavaScript
|
mit
|
mattbasta/pinecast-studio,mattbasta/pinecast-studio
|
117753105085c46615ff9de6ed273df200abb8fa
|
src/index.js
|
src/index.js
|
import fetch from 'isomorphic-fetch'
export default function fetchDispatch(url, action) {
return (dispatch) => {
return fetch(url, {
credentials: 'include'
})
.then( (response) => {
return response.json()
})
.then( (json) => {
dispatch(action(json))
})
.catch( (error) => {
console.log(error)
})
}
}
|
import fetch from 'isomorphic-fetch'
export default function fetchDispatch(url, options = {}, actions = {}) {
return (dispatch) => {
if (typeof actions.request === 'function') {
actions.request()
}
return fetch(url, options)
.then( (response) => {
return response.json()
})
.then( (json) => {
if (typeof actions.success === 'function') {
dispatch(action(json))
}
return json
})
.catch( (err) => {
if (typeof actions.fail === 'function') {
dispatch(actions.fail(err))
}
})
}
}
|
Add options and actions to fetchDispatch
|
Add options and actions to fetchDispatch
|
JavaScript
|
mit
|
KaleoSoftware/redux-fetch-dispatch
|
90af5bbbf68e061030a8b671978d7999f9088c4c
|
src/Index.js
|
src/Index.js
|
module.exports = {
BarChart: require('./components/BarChart'),
Button: require('./components/Button'),
ButtonGroup: require('./components/ButtonGroup'),
Calendar: require('./components/Calendar'),
Column: require('./components/grid/Column'),
DatePicker: require('./components/DatePicker'),
DatePickerFullScreen: require('./components/DatePickerFullScreen'),
DateRangePicker: require('./components/DateRangePicker'),
DateTimePicker: require('./components/DateTimePicker'),
DisplayInput: require('./components/DisplayInput'),
DonutChart: require('./components/DonutChart'),
Drawer: require('./components/Drawer'),
FileUpload: require('./components/FileUpload'),
Icon: require('./components/Icon'),
Loader: require('./components/Loader'),
Modal: require('./components/Modal'),
PageIndicator: require('./components/PageIndicator'),
ProgressBar: require('./components/ProgressBar'),
RadioButton: require('./components/RadioButton'),
RajaIcon: require('./components/RajaIcon'),
Row: require('./components/grid/Row'),
RangeSelector: require('./components/RangeSelector'),
SearchInput: require('./components/SearchInput'),
Select: require('./components/Select'),
SelectFullScreen: require('./components/SelectFullScreen'),
SimpleInput: require('./components/SimpleInput'),
SimpleSelect: require('./components/SimpleSelect'),
Spin: require('./components/Spin'),
TimeBasedLineChart: require('./components/TimeBasedLineChart'),
ToggleSwitch: require('./components/ToggleSwitch'),
Tooltip: require('./components/Tooltip'),
TypeAhead: require('./components/TypeAhead'),
AppConstants: require('./constants/App'),
Styles: require('./constants/Style')
};
|
module.exports = {
BarChart: require('./components/BarChart'),
Button: require('./components/Button'),
ButtonGroup: require('./components/ButtonGroup'),
Calendar: require('./components/Calendar'),
Column: require('./components/grid/Column'),
DatePicker: require('./components/DatePicker'),
DatePickerFullScreen: require('./components/DatePickerFullScreen'),
DateRangePicker: require('./components/DateRangePicker'),
DateTimePicker: require('./components/DateTimePicker'),
DisplayInput: require('./components/DisplayInput'),
DonutChart: require('./components/DonutChart'),
Drawer: require('./components/Drawer'),
FileUpload: require('./components/FileUpload'),
Gauge: require('./components/Gauge'),
Icon: require('./components/Icon'),
Loader: require('./components/Loader'),
Modal: require('./components/Modal'),
PageIndicator: require('./components/PageIndicator'),
ProgressBar: require('./components/ProgressBar'),
RadioButton: require('./components/RadioButton'),
RajaIcon: require('./components/RajaIcon'),
Row: require('./components/grid/Row'),
RangeSelector: require('./components/RangeSelector'),
SearchInput: require('./components/SearchInput'),
Select: require('./components/Select'),
SelectFullScreen: require('./components/SelectFullScreen'),
SimpleInput: require('./components/SimpleInput'),
SimpleSelect: require('./components/SimpleSelect'),
Spin: require('./components/Spin'),
TimeBasedLineChart: require('./components/TimeBasedLineChart'),
ToggleSwitch: require('./components/ToggleSwitch'),
Tooltip: require('./components/Tooltip'),
TypeAhead: require('./components/TypeAhead'),
AppConstants: require('./constants/App'),
Styles: require('./constants/Style')
};
|
Add Gauge component to src/index
|
Add Gauge component to src/index
|
JavaScript
|
mit
|
mxenabled/mx-react-components,derek-boman/mx-react-components
|
e024d3c5e62e12ee6c6081280188ad73b9144da2
|
src/js/helpers/keyboard_navigation.js
|
src/js/helpers/keyboard_navigation.js
|
(function() {
var $body = $('body'),
$document = $(document);
$body.on('keydown', function(e) {
var keyCode = (window.event) ? e.which : e.keyCode;
if (!$body.attr('data-state')) {
if (keyCode === 9 || keyCode === 13 || keyCode === 37 || keyCode === 38 || keyCode === 39 || keyCode === 40) {
$body.attr('data-state', 'keyboard');
$document.trigger('keyboardnavigation');
}
}
});
$body.on('mousemove.LibeoDataState', function(e) {
if ($body.attr('data-state')) {
$body.removeAttr('data-state');
}
$body.off('mousemove.LibeoDataState');
});
}());
|
(function() {
var $body = $('body'),
$document = $(document);
$body.on('keydown', function(e) {
var keyCode = (window.event) ? e.which : e.keyCode;
if (!$body.attr('data-state')) {
if (keyCode === 9 || keyCode === 13 || keyCode === 37 || keyCode === 38 || keyCode === 39 || keyCode === 40) {
$body.attr('data-state', 'keyboard');
$document.trigger('keyboardnavigation');
}
}
});
$body.on('mousemove.LibeoDataState', function() {
if ($body.attr('data-state')) {
$body.removeAttr('data-state');
}
$body.off('mousemove.LibeoDataState');
});
}());
|
Fix eslint warning 'e' is defined but never used
|
Fix eslint warning 'e' is defined but never used
|
JavaScript
|
agpl-3.0
|
libeo-vtt/vtt,libeo-vtt/vtt
|
56c7c34c64b3fac897c02e583562f2472319dadb
|
src/matchNode.js
|
src/matchNode.js
|
/*
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var hasOwn =
Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty);
/**
* Checks whether needle is a strict subset of haystack.
*
* @param {Object} haystack The object to test
* @param {Object} needle The properties to look for in test
* @return {bool}
*/
function matchNode(haystack, needle) {
var props = Object.keys(needle);
return props.every(function(prop) {
if (!hasOwn(haystack, prop)) {
return false;
}
if (haystack[prop] &&
typeof haystack[prop] === 'object' &&
typeof needle[prop] === 'object') {
return matchNode(haystack[prop], needle[prop]);
}
return haystack[prop] === needle[prop];
});
}
module.exports = matchNode;
|
/*
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var hasOwn =
Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty);
/**
* Checks whether needle is a strict subset of haystack.
*
* @param {Object} haystack The object to test
* @param {Object|Function} needle The properties to look for in test
* @return {bool}
*/
function matchNode(haystack, needle) {
if (typeof needle === 'function') {
return needle(haystack);
}
var props = Object.keys(needle);
return props.every(function(prop) {
if (!hasOwn(haystack, prop)) {
return false;
}
if (haystack[prop] &&
typeof haystack[prop] === 'object' &&
typeof needle[prop] === 'object') {
return matchNode(haystack[prop], needle[prop]);
}
return haystack[prop] === needle[prop];
});
}
module.exports = matchNode;
|
Allow matching nodes with a function
|
Allow matching nodes with a function
|
JavaScript
|
mit
|
fkling/jscodeshift,facebook/jscodeshift
|
49f59fea35e8753ebeca12b88ab2cf5d54bc8cfc
|
test/helpers/auth.js
|
test/helpers/auth.js
|
module.exports.getUser = function(name) {
return {
username: name,
password: name,
};
};
module.exports.login = function(user) {
browser.driver.manage().window().setSize(1600, 900);
browser.get('/#/login/');
element(by.css('div.login-form a[data-role="switch-login-form"]')).click();
element(by.model('auth.user.username')).sendKeys(user.username);
element(by.model('auth.user.password')).sendKeys(user.password);
element(by.css('div.inputs-box input[type=submit]')).click();
};
module.exports.logout = function(user) {
browser.get('/#/dashboard/');
element(by.css('ul.nav-list.context > li:nth-child(3) > a')).click();
element(by.cssContainingText('ul.nav-list.context > li:nth-child(3) > ul > li > a', 'Logout')).click();
};
|
module.exports.getUser = function(name) {
return {
username: name,
password: name,
};
};
module.exports.login = function(user) {
browser.driver.manage().window().setSize(1600, 900);
browser.get('/#/login/');
element(by.model('auth.user.username')).sendKeys(user.username);
element(by.model('auth.user.password')).sendKeys(user.password);
element(by.css('.button-login')).click();
};
module.exports.logout = function(user) {
browser.get('/#/dashboard/');
element(by.css('ul.nav-list.context > li:nth-child(3) > a')).click();
element(by.cssContainingText('ul.nav-list.context > li:nth-child(3) > ul > li > a', 'Logout')).click();
};
|
Fix test after changed of login page (SAAS-256)
|
Fix test after changed of login page (SAAS-256)
Upgrated css paths in auth helper.
|
JavaScript
|
mit
|
opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport
|
cffe6c5880fec9e421bd2d9cc654ae91b1536d16
|
src/outro.js
|
src/outro.js
|
// get at whatever the global object is, like window in browsers
}( (function() {return this;}.call()) ));
|
// Get a reference to the global object, like window in browsers
}( (function() {
return this;
}.call()) ));
|
Fix formatting and improve the comment
|
Outro: Fix formatting and improve the comment
|
JavaScript
|
mit
|
qunitjs/qunit,qunitjs/qunit,danielgindi/qunit
|
c3d816f009b81291a93d3d3c8d976c37e537d67a
|
test/writeNewHtml.js
|
test/writeNewHtml.js
|
var assert = require('assert')
var fs = require('fs')
var writeNewHtml = require('./../writeNewHtml')
describe('writeNewHtml', () => {
it('should write html file to wf/',done => {
var html = `<!DOCTYPE>
<html>
<body>
<script class="923ad49f0ca1962716d34bd60433de8a207570f7"></script>
</body>
</html>`
fs.mkdir(__dirname + '/wf', err => {
writeNewHtml(html, 'test/wf/index');
setTimeout(() => {
var wroteHtml = fs.statSync(__dirname + '/wt/index.html').isFile()
fs.unlink(__dirname + '/wf/index.html', err => {
console.log('unlinking...')
fs.rmdir(__dirname + '/wf', err => {
assert.equal(true, wroteHtml)
done()
})
})
}, 1500)
})
})
})
|
var assert = require('assert')
var fs = require('fs')
var writeNewHtml = require('./../writeNewHtml')
describe('writeNewHtml', () => {
it('should write html file to wf/',done => {
var html = `<!DOCTYPE>
<html>
<body>
<script class="923ad49f0ca1962716d34bd60433de8a207570f7"></script>
</body>
</html>`
fs.mkdir(__dirname + '/wf', err => {
writeNewHtml(html, 'test/wf/index');
var wroteHtml = fs.statSync(__dirname + '/wf/index.html').isFile()
fs.unlink(__dirname + '/wf/index.html', err => {
fs.rmdir(__dirname + '/wf', err => {
assert.equal(true, wroteHtml)
done()
})
})
})
})
})
|
Test for write new html
|
Test for write new html
|
JavaScript
|
mit
|
CarolAG/WebFlight,coryc5/WebFlight
|
cf2487ba7929bf33695a16aebdc98f5e0ee412d0
|
src/pages/App.js
|
src/pages/App.js
|
import React, { Component, PropTypes } from 'react'
import { Link } from 'react-router'
import 'normalize.css/normalize.css'
import '../styles/defaults.scss'
import classNames from './App.scss'
import { trackTiming } from '../analytics'
import { APP_NAME, AUTHOR_URL, SOURCE_URL, SEPARATOR } from '../config'
export default class App extends Component {
static propTypes = {
children: PropTypes.node
};
componentDidMount () {
if (window.performance) {
trackTiming('react', 'firstrender', Math.round(window.performance.now()))
}
}
render () {
return (
<div className={classNames.app}>
<header className={classNames.header}>
<h1 className={classNames.title}>
<Link to='/'>
{APP_NAME}
</Link>
</h1>
{SEPARATOR}
<a href={SOURCE_URL} target='_blank'>Source</a>
{SEPARATOR}
by <a href={AUTHOR_URL} target='_blank'>CookPete</a>
</header>
{ this.props.children }
</div>
)
}
}
|
import React, { Component, PropTypes } from 'react'
import { Link } from 'react-router'
import 'normalize.css/normalize.css'
import '../styles/defaults.scss'
import classNames from './App.scss'
import { trackTiming } from '../analytics'
import { APP_NAME, AUTHOR_URL, SOURCE_URL, SEPARATOR } from '../config'
export default class App extends Component {
static propTypes = {
children: PropTypes.node
};
componentDidMount () {
if (window.performance) {
trackTiming('react', 'firstrender', Math.round(window.performance.now()))
}
}
render () {
return (
<div className={classNames.app}>
<header className={classNames.header}>
<h1 className={classNames.title}>
<Link to='/'>
{APP_NAME}
</Link>
</h1>
{SEPARATOR}
by <a href={AUTHOR_URL} target='_blank'>CookPete</a>
{SEPARATOR}
<a href={SOURCE_URL} target='_blank'>Source</a>
</header>
{ this.props.children }
</div>
)
}
}
|
Reorder source and author links
|
Reorder source and author links
|
JavaScript
|
cc0-1.0
|
CookPete/reddit-player,CookPete/rplayr,CookPete/rplayr,CookPete/reddit-player
|
d24f4d335470d664a019763e9f3780f339120de2
|
packages/example-usecase/webpack.config.js
|
packages/example-usecase/webpack.config.js
|
const path = require('path')
const webpack = require('webpack')
module.exports = {
entry: './src/index.js',
output: {
filename: './bundle.js',
path: path.resolve('public')
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
}
]
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
new webpack.IgnorePlugin(/(languageData|compile).*\.dev$/)
],
devServer: {
hot: true,
inline: true,
contentBase: path.resolve('public')
}
}
|
const path = require('path')
const webpack = require('webpack')
module.exports = {
entry: './src/index.js',
output: {
filename: './bundle.js',
path: path.resolve('public')
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
}
]
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
new webpack.optimize.UglifyJsPlugin(),
new webpack.IgnorePlugin(/\.dev$/, /lingui-i18n/)
],
devServer: {
hot: true,
inline: true,
contentBase: path.resolve('public')
}
}
|
Remove dev code in production
|
feat(example): Remove dev code in production
|
JavaScript
|
mit
|
lingui/js-lingui,lingui/js-lingui
|
007c357d7f3fe9a8e14e495fab5f166ac4c9b84a
|
packages/vega-scenegraph/src/Scenegraph.js
|
packages/vega-scenegraph/src/Scenegraph.js
|
import Bounds from './Bounds';
import GroupItem from './GroupItem';
export default function Scenegraph() {
this.root = createMark({
marktype: 'group',
interactive: false
});
this.root.items = [new GroupItem(this.root)];
}
var prototype = Scenegraph.prototype;
prototype.select = function(path, markdef) {
var items = this.root.items[0],
node, i, n;
for (i=0, n=path.length-1; i<n; ++i) {
items = items.items[path[i]];
if (!items) error('Invalid scenegraph path: ' + path);
}
items = items.items;
if (!(node = items[path[n]])) {
if (markdef) items[path[n]] = node = createMark(markdef);
else error('Invalid scenegraph path: ' + path);
}
return node;
};
function error(msg) {
throw Error(msg);
}
function createMark(def) {
return {
bounds: new Bounds(),
clip: !!def.clip,
interactive: def.interactive === false ? false : true,
items: [],
marktype: def.marktype,
name: def.name || undefined,
role: def.role || undefined
};
}
|
import Bounds from './Bounds';
import GroupItem from './GroupItem';
export default function Scenegraph() {
this.root = createMark({
marktype: 'group',
interactive: false
});
this.root.items = [new GroupItem(this.root)];
}
var prototype = Scenegraph.prototype;
prototype.select = function(path, markdef) {
var group = this.root.items[0],
mark = group.items[path[0]],
i, n;
try {
for (i=1, n=path.length-1; i<n; ++i) {
group = mark.items[path[i++]];
mark = group.items[path[i]];
}
if (!mark && !markdef) throw n;
if (markdef) {
mark = createMark(markdef, group);
group.items[path[n]] = mark;
}
return mark;
} catch (err) {
error('Invalid scenegraph path: ' + path);
}
};
function error(msg) {
throw Error(msg);
}
function createMark(def, group) {
return {
bounds: new Bounds(),
clip: !!def.clip,
group: group,
interactive: def.interactive === false ? false : true,
items: [],
marktype: def.marktype,
name: def.name || undefined,
role: def.role || undefined
};
}
|
Add group reference to new mark instances.
|
Add group reference to new mark instances.
|
JavaScript
|
bsd-3-clause
|
vega/vega,vega/vega,vega/vega,lgrammel/vega,vega/vega
|
b2fd712c21080cd38d367ee856f3212a21aa7340
|
src/store.js
|
src/store.js
|
import { createStore, applyMiddleware, compose } from 'redux'
import createSagaMiddleware from 'redux-saga'
import reducer from './reducers'
// create the saga middleware
export const sagaMiddleware = createSagaMiddleware()
const composeEnhancers =
process.env.NODE_ENV !== 'production' &&
typeof window === 'object' &&
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__()
: compose
// mount it on the Store
const store = createStore(
reducer,
composeEnhancers(
applyMiddleware(sagaMiddleware)
)
)
export default store
|
import { createStore, applyMiddleware, compose } from 'redux'
import createSagaMiddleware from 'redux-saga'
import reducer from './reducers'
// create the saga middleware
export const sagaMiddleware = createSagaMiddleware()
const composeEnhancers =
process.env.NODE_ENV !== 'production' &&
typeof window === 'object' &&
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
: compose
// mount it on the Store
const store = createStore(
reducer,
composeEnhancers(
applyMiddleware(sagaMiddleware)
)
)
export default store
|
Remove brackets for correct function of devel mode
|
Remove brackets for correct function of devel mode
|
JavaScript
|
apache-2.0
|
mkrajnak/ovirt-web-ui,mareklibra/userportal,oVirt/ovirt-web-ui,oVirt/ovirt-web-ui,matobet/userportal,matobet/userportal,mkrajnak/ovirt-web-ui,mkrajnak/ovirt-web-ui,mareklibra/userportal,matobet/userportal,mkrajnak/ovirt-web-ui,oVirt/ovirt-web-ui,mareklibra/userportal,matobet/userportal,mareklibra/userportal
|
14d6537cd2000ae28320366934d769846f3610cf
|
src/index.js
|
src/index.js
|
import React, { Component, PropTypes } from 'react'
import ReactDOM from 'react-dom'
import ReactDOMServer from 'react-dom/server'
import SVGInjector from 'svg-injector'
export default class ReactSVG extends Component {
static defaultProps = {
callback: () => {},
className: '',
evalScripts: 'once',
style: {}
}
static propTypes = {
callback: PropTypes.func,
className: PropTypes.string,
evalScripts: PropTypes.oneOf([ 'always', 'once', 'never' ]),
path: PropTypes.string.isRequired,
style: PropTypes.object
}
renderSVG(props = this.props) {
const {
callback: each,
className,
evalScripts,
path,
style
} = props
this.container = this.container || ReactDOM.findDOMNode(this)
const div = document.createElement('div')
div.innerHTML = ReactDOMServer.renderToStaticMarkup(
<img
className={className}
data-src={path}
style={style}
/>
)
const img = this.container.appendChild(div.firstChild)
SVGInjector(img, {
evalScripts,
each
})
}
removeSVG() {
this.container.removeChild(this.container.firstChild)
}
componentDidMount() {
this.renderSVG()
}
componentWillReceiveProps(nextProps) {
this.removeSVG()
this.renderSVG(nextProps)
}
shouldComponentUpdate() {
return false
}
componentWillUnmount() {
this.removeSVG()
}
render() {
return <div />
}
}
|
import React, { Component, PropTypes } from 'react'
import ReactDOMServer from 'react-dom/server'
import SVGInjector from 'svg-injector'
export default class ReactSVG extends Component {
static defaultProps = {
callback: () => {},
className: '',
evalScripts: 'once',
style: {}
}
static propTypes = {
callback: PropTypes.func,
className: PropTypes.string,
evalScripts: PropTypes.oneOf([ 'always', 'once', 'never' ]),
path: PropTypes.string.isRequired,
style: PropTypes.object
}
refCallback = (container) => {
if (!container) {
this.removeSVG()
return
}
this.container = container
this.renderSVG()
}
renderSVG(props = this.props) {
const {
callback: each,
className,
evalScripts,
path,
style
} = props
const div = document.createElement('div')
div.innerHTML = ReactDOMServer.renderToStaticMarkup(
<img
className={className}
data-src={path}
style={style}
/>
)
const img = this.container.appendChild(div.firstChild)
SVGInjector(img, {
evalScripts,
each
})
}
removeSVG() {
this.container.removeChild(this.container.firstChild)
}
componentWillReceiveProps(nextProps) {
this.removeSVG()
this.renderSVG(nextProps)
}
shouldComponentUpdate() {
return false
}
render() {
return <div ref={this.refCallback} />
}
}
|
Handle mounting and unmounting via ref callback
|
Handle mounting and unmounting via ref callback
|
JavaScript
|
mit
|
atomic-app/react-svg
|
d8aac8b081f5df7c7c331d78d25e25958cfe5676
|
src/index.js
|
src/index.js
|
/**
* External imports
*/
import koa from 'koa';
import route from 'koa-route';
import libdebug from 'debug';
// create debug logger
const debug = libdebug('lgho:root');
/**
* Routes
*/
function* root() {
this.response.status = 200;
}
export default function create(options = {}) {
debug('options %j', options);
return koa()
.use(route.get('/', root));
}
|
/**
* External imports
*/
import route from 'koa-route';
import createDebugLogger from 'debug';
import createKoaApplication from 'koa';
// create debug logger
const log = createDebugLogger('lgho:root');
/**
* Routes
*/
function* root() {
this.response.body = {
'let go': null,
'hold on': null,
};
this.response.status = 200;
}
export default function create(options = {}) {
log('options %j', options);
return createKoaApplication()
.use(route.get('/', root));
}
|
Update root route to respond with hold-on/let-go object.
|
Update root route to respond with hold-on/let-go object.
|
JavaScript
|
isc
|
francisbrito/let-go-hold-on-api
|
5ce278078201707cd8f308e06475f55c7793c8fd
|
src/index.js
|
src/index.js
|
import pluralize, { singular } from 'pluralize';
function normalize(slug: string): string {
return singular(slug.toLowerCase()).replace(/(-|_|\.|\s)+/g, '_');
}
function urlify(slug: string): string {
return pluralize(slug).replace('_', '-');
}
const formats = {
pascal(slug: string): string {
return slug
.split('_')
.map(word => `${word.charAt(0).toUpperCase()}${word.substr(1)}`)
.join(' ');
},
camel(slug: string): string {
const splitSlug = slug.split('_');
return [
splitSlug[0],
formats.pascal(splitSlug.slice(1).join('_')).replace(' ', ''),
].join('');
},
};
export default function slugizoid(slug: string = ''): string {
const _original = slug;
const _normalized = normalize(slug);
return {
toString(options: { format: 'pascal' | 'camel', plural: boolean }): string {
const { format, plural } = Object.assign(
{ format: 'pascal', plural: false },
options
);
return (plural ? pluralize : singular)(formats[format](_normalized));
},
equals(slug: string): boolean {
return normalize(slug) === _normalized;
},
slugify(): string {
return _normalized;
},
urlify(): string {
return urlify(_normalized);
},
};
}
|
import pluralize, { singular } from 'pluralize';
function normalize(slug: string): string {
return singular(slug.toLowerCase()).replace(/(-|_)+/g, '_');
}
function urlify(slug: string): string {
return pluralize(slug).replace('_', '-');
}
const formats = {
pascal(slug: string): string {
return slug
.split('_')
.map(word => `${word.charAt(0).toUpperCase()}${word.substr(1)}`)
.join(' ');
},
camel(slug: string): string {
const splitSlug = slug.split('_');
return [
splitSlug[0],
formats.pascal(splitSlug.slice(1).join('_')).replace(' ', ''),
].join('');
},
};
export default function slugizoid(slug: string = ''): string {
const _original = slug;
const _normalized = normalize(slug);
return {
toString(options: { format: 'pascal' | 'camel', plural: boolean }): string {
const { format, plural } = Object.assign(
{ format: 'pascal', plural: false },
options
);
return (plural ? pluralize : singular)(formats[format](_normalized));
},
equals(slug: string): boolean {
return normalize(slug) === _normalized;
},
slugify(): string {
return _normalized;
},
urlify(): string {
return urlify(_normalized);
},
};
}
|
Remove whitespace and '.' delims
|
refactor(src): Remove whitespace and '.' delims
|
JavaScript
|
mit
|
mb3online/slugizoid
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.