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
|
---|---|---|---|---|---|---|---|---|---|
f0299893c99537b1d23c54fbdbd04b463a6eed26
|
Gruntfile.js
|
Gruntfile.js
|
module.exports = function(grunt) {
'use strict';
grunt.initConfig({
benchmark: {
all: {
src: ['benchmarks/*.js'],
options: { times: 10 }
}
},
nodeunit: {
files: ['test/*_test.js'],
},
jshint: {
options: {
jshintrc: '.jshintrc'
},
gruntfile: {
src: 'Gruntfile.js'
},
lib: {
src: ['lib/**/*.js']
},
test: {
src: ['test/**/*_test.js']
},
}
});
grunt.loadNpmTasks('grunt-benchmark');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
grunt.registerTask('default', ['jshint', 'nodeunit']);
};
|
module.exports = function(grunt) {
'use strict';
grunt.initConfig({
benchmark: {
all: {
src: ['benchmarks/*.js'],
options: { times: 10 }
}
},
nodeunit: {
files: ['test/*_test.js'],
},
jshint: {
options: {
jshintrc: '.jshintrc'
},
gruntfile: {
src: 'Gruntfile.js'
},
lib: {
src: ['lib/**/*.js']
},
test: {
src: ['test/**/*_test.js']
},
},
});
// Dynamic alias task to nodeunit. Run individual tests with: grunt test:events
grunt.registerTask('test', function(file) {
grunt.config('nodeunit.files', String(grunt.config('nodeunit.files')).replace('*', file || '*'));
grunt.task.run('nodeunit');
});
grunt.loadNpmTasks('grunt-benchmark');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
grunt.registerTask('default', ['jshint', 'nodeunit']);
};
|
Add dynamic alias task for running individual tests
|
Add dynamic alias task for running individual tests
|
JavaScript
|
mit
|
modulexcite/gaze,prodatakey/gaze,prodatakey/gaze,shama/gaze,modulexcite/gaze,chebum/gaze,bevacqua/gaze,bevacqua/gaze,modulexcite/gaze,bevacqua/gaze,prodatakey/gaze
|
34080a9b4d3835b0cde39503ab2c1ab48e7c06ab
|
src/components/logger/logger.js
|
src/components/logger/logger.js
|
import intelLogger from 'intel'
import joi from 'joi'
import { validateObject } from '../../core'
/**
* Returns config data and its schema
* @param {Object} env
* @returns {SchemedData}
*/
function getConfig(env) {
/**
* Log level compatible with intel module
* Valid values: ALL, TRACE, VERBOSE, DEBUG, INFO, WARN, ERROR, CRITICAL, NONE
* @enum {string}
*/
const { LOG_LEVEL = 'INFO' } = env
return {
data: {
logLevel: LOG_LEVEL,
},
schema: {
logLevel: joi.string()
.only([ 'ALL', 'TRACE', 'VERBOSE', 'DEBUG', 'INFO', 'WARN', 'ERROR', 'CRITICAL', 'NONE' ])
}
}
}
/**
* Returns logger service
* @param {Object} deps Appi dependencies
* @param {Object} deps.env Env dependency
* @returns {Logger} Configured intel logger
*/
export function logger(deps) {
const config = validateObject(getConfig(deps.env))
intelLogger.setLevel(config.logLevel)
intelLogger.addHandler(new intelLogger.handlers.Console({
formatter: new intelLogger.Formatter({
format: '[%(date)s] %(name)s.%(levelname)s: %(message)s',
datefmt: '%Y-%m-%d %H:%M-%S',
colorize: true,
})
}))
return intelLogger
}
logger.isAppiComponent = true
|
import intelLogger from 'intel'
import joi from 'joi'
import { validateObject } from '../../core'
/**
* Returns config data and its schema
* @param {Object} env
* @returns {SchemedData}
*/
function getConfig(env) {
/**
* Log level compatible with intel module
* Valid values: ALL, TRACE, VERBOSE, DEBUG, INFO, WARN, ERROR, CRITICAL, NONE
* @enum {string}
*/
const { LOG_LEVEL = 'INFO' } = env
return {
data: {
logLevel: LOG_LEVEL,
},
schema: {
logLevel: joi.string()
.only([ 'ALL', 'TRACE', 'VERBOSE', 'DEBUG', 'INFO', 'WARN', 'ERROR', 'CRITICAL', 'NONE' ])
}
}
}
/**
* Returns logger service
* @param {Object} deps Appi dependencies
* @param {Object} deps.env Env dependency
* @returns {Logger} Configured intel logger
*/
export function logger(deps) {
const config = validateObject(getConfig(deps.env))
intelLogger.setLevel(config.logLevel)
intelLogger.addHandler(new intelLogger.handlers.Console({
formatter: new intelLogger.Formatter({
format: '[%(date)s] %(name)s.%(levelname)s: %(message)s',
datefmt: '%Y-%m-%d %H:%M-%S',
colorize: true,
})
}))
return intelLogger
}
logger.componentName = 'logger'
|
Align Logger component with new AppiComponent api
|
Align Logger component with new AppiComponent api
|
JavaScript
|
apache-2.0
|
labs42/appi
|
26e8ca7ae9a2e4123886c5cbbb549c76219473d0
|
src/popper/utils/findCommonOffsetParent.js
|
src/popper/utils/findCommonOffsetParent.js
|
import isOffsetContainer from './isOffsetContainer';
export default function findCommonOffsetParent(element1, element2) {
const range = document.createRange();
if (element1.compareDocumentPosition(element2) & Node.DOCUMENT_POSITION_FOLLOWING) {
range.setStart(element1, 0);
range.setEnd(element2, 0);
} else {
range.setStart(element2, 0);
range.setEnd(element1, 0);
}
const { commonAncestorContainer } = range;
if (isOffsetContainer(commonAncestorContainer)) {
return commonAncestorContainer;
}
// This is probably very stupid, fix me please
if (!commonAncestorContainer) {
return window.document.documentElement;
}
const offsetParent = commonAncestorContainer.offsetParent;
return offsetParent.nodeName === 'BODY' ? document.documentElement : offsetParent;
}
|
import isOffsetContainer from './isOffsetContainer';
export default function findCommonOffsetParent(element1, element2) {
const range = document.createRange();
if (element1.compareDocumentPosition(element2) & Node.DOCUMENT_POSITION_FOLLOWING) {
range.setStart(element1, 0);
range.setEnd(element2, 0);
} else {
range.setStart(element2, 0);
range.setEnd(element1, 0);
}
const { commonAncestorContainer } = range;
if (isOffsetContainer(commonAncestorContainer)) {
return commonAncestorContainer;
}
// This is probably very stupid, fix me please
if (!commonAncestorContainer) {
return window.document.documentElement;
}
const offsetParent = commonAncestorContainer.offsetParent;
if (!offsetParent || offsetParent && offsetParent.nodeName === 'BODY') {
return document.documentElement;
}
return offsetParent;
}
|
Return document if offsetParent is null
|
Return document if offsetParent is null
This because `.offsetParent` null is returned by documentElement
|
JavaScript
|
mit
|
imkremen/popper.js,imkremen/popper.js
|
795bdb81899bff86df89174ceeaa5173999a7de2
|
hypem-resolver.js
|
hypem-resolver.js
|
// Copyright 2015 Fabian Dietenberger
'use-strict'
var q = require('q'),
request = require('request');
var hypemResolver = {};
hypemResolver.getUrl = function (hypemUrl) {
var resultUrl = "";
return resultUrl;
};
module.exports = hypemResolver;
|
// Copyright 2015 Fabian Dietenberger
'use-strict'
var q = require('q'),
request = require('request');
var hypemResolver = {};
hypemResolver.getByUrl = function (hypemUrl) {
var resultUrl = "";
return resultUrl;
};
hypemResolver.getById = function (hypemId) {
return this.getByUrl("http://hypem.com/track/" + hypemId);
};
module.exports = hypemResolver;
|
Split get method into 2 single methods for url and id
|
Split get method into 2 single methods for url and id
|
JavaScript
|
mit
|
feedm3/hypem-resolver
|
fe74c923958c21f8706fbca6e4da8a9cfb1b6a1d
|
src/server/migrations/0.3.0-0.4.0/index.js
|
src/server/migrations/0.3.0-0.4.0/index.js
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const database = require('../../models/database');
const sqlFile = database.sqlFile;
module.exports = {
fromVersion: '0.3.0',
toVersion: '0.4.0',
up: async db => {
try {
await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/preferences/create_language_types_enum.sql'));
await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/preferences/add_language_column.sql'));
await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/logemail/create_log_table.sql'));
await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/baseline/create_baseline_table.sql'));
await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/baseline/create_function_get_average_reading.sql'));
} catch (err) {
throw new Error('Error while migrating each sql file');
}
}
};
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const database = require('../../models/database');
const sqlFile = database.sqlFile;
module.exports = {
fromVersion: '0.3.0',
toVersion: '0.4.0',
up: async db => {
try {
await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/preferences/create_language_types_enum.sql'));
await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/preferences/add_language_column.sql'));
await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/logemail/create_log_table.sql'));
await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/baseline/create_baseline_table.sql'));
await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/baseline/create_function_get_average_reading.sql'));
await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/compareReadings/create_function_get_compare_readings.sql'));
} catch (err) {
throw new Error('Error while migrating each sql file');
}
}
};
|
Set migration for compare_readings/group_compare_readings sql functions
|
Set migration for compare_readings/group_compare_readings sql functions
|
JavaScript
|
mpl-2.0
|
OpenEnergyDashboard/OED,OpenEnergyDashboard/OED,OpenEnergyDashboard/OED,OpenEnergyDashboard/OED
|
1f71f06920d43c2c8ff3b670e9355033eaed7f11
|
src/telemetry.js
|
src/telemetry.js
|
// Copyright (c) Martin Costello, 2017. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
"use strict";
var appInsights = require("applicationinsights");
const telemetry = {
appInsights: appInsights,
trackEvent: function () {
},
trackException: function () {
}
};
telemetry.instrumentationKey = "";
telemetry.createClient = function () {
var client = new appInsights.TelemetryClient(telemetry.instrumentationKey);
client.config.maxBatchIntervalMs = 0;
return client;
};
/**
* Sets up collection of telemetry.
* @param {String} [instrumentationKey=null] - The optional instrumentation key to use.
*/
telemetry.setup = function (instrumentationKey) {
if (instrumentationKey) {
telemetry.instrumentationKey = instrumentationKey;
telemetry.appInsights.setup(instrumentationKey).start();
telemetry.trackEvent = function (name, properties) {
telemetry.createClient().trackEvent({
name: name,
properties: properties
});
};
telemetry.trackException = function (exception, properties) {
telemetry.createClient().trackException({
exception: exception,
properties: properties
});
};
}
};
module.exports = telemetry;
|
// Copyright (c) Martin Costello, 2017. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
"use strict";
var appInsights = require("applicationinsights");
const telemetry = {
appInsights: appInsights,
trackEvent: function () {
},
trackException: function () {
}
};
telemetry.instrumentationKey = "";
telemetry.createClient = function () {
var client = new appInsights.TelemetryClient(telemetry.instrumentationKey);
// Prevent Lambda function from hanging and timing out.
// See https://github.com/martincostello/alexa-london-travel/issues/45.
client.config.maxBatchIntervalMs = 0;
client.config.maxBatchSize = 1;
return client;
};
/**
* Sets up collection of telemetry.
* @param {String} [instrumentationKey=null] - The optional instrumentation key to use.
*/
telemetry.setup = function (instrumentationKey) {
if (instrumentationKey) {
telemetry.instrumentationKey = instrumentationKey;
telemetry.appInsights.setup(instrumentationKey).start();
telemetry.trackEvent = function (name, properties) {
telemetry.createClient().trackEvent({
name: name,
properties: properties
});
};
telemetry.trackException = function (exception, properties) {
telemetry.createClient().trackException({
exception: exception,
properties: properties
});
};
}
};
module.exports = telemetry;
|
Set ApplicationInsights batch size to 1
|
Set ApplicationInsights batch size to 1
Set the batch size for ApplicationInsights to 1 to try and prevent setTimeout() ever being called and causing the lambda function to timeout from hanging.
Relates to #45.
|
JavaScript
|
apache-2.0
|
martincostello/alexa-london-travel
|
9ba3095bdc0a81a1546634160f2a20c3a0196d51
|
src/time_slot.js
|
src/time_slot.js
|
Occasion.Modules.push(function(library) {
library.TimeSlot = class TimeSlot extends library.Base {};
library.TimeSlot.className = 'TimeSlot';
library.TimeSlot.queryName = 'time_slots';
library.TimeSlot.belongsTo('product');
library.TimeSlot.belongsTo('venue');
library.TimeSlot.afterRequest(function() {
if(this.product().merchant()) {
this.startsAt = moment.tz(this.startsAt, this.product().merchant().timeZone);
} else {
throw 'Must use includes({ product: \'merchant\' }) in timeSlot request';
}
this.duration = moment.duration(this.duration, 'minutes');
});
});
|
Occasion.Modules.push(function(library) {
library.TimeSlot = class TimeSlot extends library.Base {};
library.TimeSlot.className = 'TimeSlot';
library.TimeSlot.queryName = 'time_slots';
library.TimeSlot.belongsTo('order');
library.TimeSlot.belongsTo('product');
library.TimeSlot.belongsTo('venue');
library.TimeSlot.afterRequest(function() {
if(this.product().merchant()) {
this.startsAt = moment.tz(this.startsAt, this.product().merchant().timeZone);
} else {
throw 'Must use includes({ product: \'merchant\' }) in timeSlot request';
}
this.duration = moment.duration(this.duration, 'minutes');
});
});
|
Add TimeSlot belongsTo order relationship
|
Add TimeSlot belongsTo order relationship
|
JavaScript
|
mit
|
nicklandgrebe/occasion-sdk-js
|
b447e585b0c77739315677deb367140184d24a17
|
src/models/reminder.js
|
src/models/reminder.js
|
const mongoose = require('mongoose');
const reminderSchema = new mongoose.Schema({
user_address: { type: Object, required: true, index: true },
value: { type: String, required: true },
expiration: { type: Date, required: true }
});
module.exports = mongoose.model('Reminder', reminderSchema);
|
const mongoose = require('mongoose');
const reminderSchema = new mongoose.Schema({
user_address: {
useAuth: Boolean,
serviceUrl: String,
bot: {
name: String,
id: String
},
conversation: {
id: String,
isGroup: Boolean
},
user: {
name: { type: String, index: true },
id: String
},
channelId: String,
id: String
},
value: { type: String, required: true },
expiration: { type: Date, required: true }
});
module.exports = mongoose.model('Reminder', reminderSchema);
|
Improve mongoose schema, index user.name
|
Improve mongoose schema, index user.name
|
JavaScript
|
mit
|
sebsylvester/reminder-bot
|
26fa40b50deee67a1ce8711ef5f35a7cd977c18d
|
src/openpoliticians.js
|
src/openpoliticians.js
|
"use strict";
var cors = require('cors');
var originWhitelist = [
'http://openpoliticians.org',
'http://localhost:4000',
];
var openPoliticiansCors = cors({
origin: function(origin, callback) {
var originIsWhitelisted = originWhitelist.indexOf(origin) !== -1;
callback(null, originIsWhitelisted);
},
credentials: true,
});
module.exports = openPoliticiansCors;
|
"use strict";
var cors = require('cors');
var originWhitelist = [
'http://openpoliticians.org',
'http://everypolitician.org',
'http://localhost:4000',
];
var openPoliticiansCors = cors({
origin: function(origin, callback) {
var originIsWhitelisted = originWhitelist.indexOf(origin) !== -1;
callback(null, originIsWhitelisted);
},
credentials: true,
});
module.exports = openPoliticiansCors;
|
Add everypolitician.org to allowed CORS addresses
|
Add everypolitician.org to allowed CORS addresses
|
JavaScript
|
agpl-3.0
|
Sinar/popit-api,mysociety/popit-api,mysociety/popit-api,Sinar/popit-api
|
9fad0a8e69069226f4d7efeec98410e453044ba8
|
realtime/index.js
|
realtime/index.js
|
const io = require('socket.io'),
winston = require('winston');
winston.remove(winston.transports.Console);
winston.add(winston.transports.Console, {'timestamp': true});
const PORT = 3031;
winston.info('Rupture real-time service starting');
winston.info('Listening on port ' + PORT);
var socket = io.listen(PORT);
socket.on('connection', function(client) {
winston.info('New connection from client ' + client.id);
client.on('get-work', function() {
winston.info('get-work from client ' + client.id);
client.emit('do-work', {
url: 'https://facebook.com/?breach-test',
amount: 3,
timeout: 0
});
});
client.on('disconnect', function() {
winston.info('Client ' + client.id + ' disconnected');
});
});
|
const io = require('socket.io'),
winston = require('winston');
winston.remove(winston.transports.Console);
winston.add(winston.transports.Console, {'timestamp': true});
const PORT = 3031;
winston.info('Rupture real-time service starting');
winston.info('Listening on port ' + PORT);
var socket = io.listen(PORT);
socket.on('connection', function(client) {
winston.info('New connection from client ' + client.id);
client.on('get-work', function() {
winston.info('get-work from client ' + client.id);
client.emit('do-work', {
url: 'https://facebook.com/?breach-test',
amount: 1000,
timeout: 0
});
});
client.on('disconnect', function() {
winston.info('Client ' + client.id + ' disconnected');
});
});
|
Switch experiment to performing 1000 parallel requests
|
Switch experiment to performing 1000 parallel requests
|
JavaScript
|
mit
|
dimriou/rupture,esarafianou/rupture,dionyziz/rupture,dimriou/rupture,dionyziz/rupture,dimriou/rupture,esarafianou/rupture,esarafianou/rupture,dimkarakostas/rupture,dionyziz/rupture,esarafianou/rupture,dionyziz/rupture,dimriou/rupture,dimkarakostas/rupture,dimkarakostas/rupture,dimkarakostas/rupture,dimkarakostas/rupture,dimriou/rupture,dionyziz/rupture
|
0edf973af2efff8614ddae037eb28d5f2b178599
|
ext/codecast/7.1/codecast-loader.js
|
ext/codecast/7.1/codecast-loader.js
|
$(document).ready(function() {
if (window.taskData) {
var taskInstructionsHtml = $('#taskIntro').html();
var hints = $('#taskHints > div').toArray().map(elm => {
return {
content: elm.innerHTML.trim()
};
});
var additionalOptions = window.taskData.codecastParameters ? window.taskData.codecastParameters : {};
if (window.codecastPreload) {
additionalOptions.preload = true;
}
var codecastParameters = $.extend(true, {
start: 'task',
showStepper: true,
showStack: true,
showViews: true,
showIO: true,
showDocumentation: true,
showFullScreen: true,
showMenu: true,
canRecord: false,
platform: 'python',
canChangePlatform: true,
canChangeLanguage: true,
controls: {},
// audioWorkerUrl: modulesPath + "ext/codecast/7.0/index.worker.worker.js",
baseUrl: "https://codecast.france-ioi.org/v7",
authProviders: ["algorea", "guest"],
task: window.taskData,
taskInstructions: taskInstructionsHtml,
taskHints: hints,
}, additionalOptions, window.codecastPreload ? window.codecastPreload : {});
Codecast.start(codecastParameters);
}
});
|
$(document).ready(function() {
if (window.taskData) {
var taskInstructionsHtml = $('#taskIntro').html();
var hints = $('#taskHints > div').toArray().map(elm => {
return {
content: elm.innerHTML.trim()
};
});
var additionalOptions = window.taskData.codecastParameters ? window.taskData.codecastParameters : {};
if (window.codecastPreload) {
additionalOptions.preload = true;
}
if (!additionalOptions.language && window.stringsLanguage) {
additionalOptions.language = window.stringsLanguage;
}
var codecastParameters = $.extend(true, {
start: 'task',
showStepper: true,
showStack: true,
showViews: true,
showIO: true,
showDocumentation: true,
showFullScreen: true,
showMenu: true,
canRecord: false,
platform: 'python',
canChangePlatform: true,
canChangeLanguage: true,
controls: {},
// audioWorkerUrl: modulesPath + "ext/codecast/7.0/index.worker.worker.js",
baseUrl: "https://codecast.france-ioi.org/v7",
authProviders: ["algorea", "guest"],
task: window.taskData,
taskInstructions: taskInstructionsHtml,
taskHints: hints,
}, additionalOptions, window.codecastPreload ? window.codecastPreload : {});
Codecast.start(codecastParameters);
}
});
|
Revert "Revert "Use window.stringsLanguage by default if fulfilled""
|
Revert "Revert "Use window.stringsLanguage by default if fulfilled""
This reverts commit 6c738f09b3c930a90847440c564d65179417c469.
|
JavaScript
|
mit
|
France-ioi/bebras-modules,France-ioi/bebras-modules
|
09bff03f5f74939ef6551625f2c453419f845c61
|
request-logger.js
|
request-logger.js
|
var util = require('util');
var log = require('minilog')('http');
module.exports = function requestLogger(req, res, next) {
//
// Pretty much copypasta from
// https://github.com/senchalabs/connect/blob/master/lib/middleware/logger.js#L168-L174
//
// Monkey punching res.end. It's dirty but, maan I wanna log my status
// codes!
//
var end = res.end;
res.end = function (chunk, encoding) {
res.end = end;
res.end(chunk, encoding);
var remoteAddr = (function () {
if (req.ip) return req.ip;
var sock = req.socket;
if (sock.socket) return sock.socket.remoteAddress;
return sock.remoteAddress;
})(),
date = new Date().toUTCString(), // DEFINITELY not CLF-compatible.
method = req.method,
url = req.originalUrl || req.url,
httpVersion = req.httpVersionMajor + '.' + req.httpVersionMinor,
status = res.statusCode;
// Similar to, but not anywhere near compatible with, CLF. So don't try
// parsing it as CLF.
//
log.info(util.format(
'%s - - [%s] "%s %s HTTP/%s" %s',
remoteAddr,
date,
method,
url,
httpVersion,
status
));
};
next();
};
|
var util = require('util');
var log = require('minilog')('http');
module.exports = function requestLogger(req, res, next) {
//
// Pretty much copypasta from
// https://github.com/senchalabs/connect/blob/master/lib/middleware/logger.js#L135-L158
//
// Monkey punching res.end. It's dirty but, maan I wanna log my status
// codes!
//
var end = res.end;
res.end = function (chunk, encoding) {
res.end = end;
res.end(chunk, encoding);
var remoteAddr = (function () {
if (req.ip) return req.ip;
var sock = req.socket;
if (sock.socket) return sock.socket.remoteAddress;
return sock.remoteAddress;
})(),
date = new Date().toUTCString(), // DEFINITELY not CLF-compatible.
method = req.method,
url = req.originalUrl || req.url,
httpVersion = req.httpVersionMajor + '.' + req.httpVersionMinor,
status = res.statusCode;
// Similar to, but not anywhere near compatible with, CLF. So don't try
// parsing it as CLF.
//
log.info(util.format(
'%s - - [%s] "%s %s HTTP/%s" %s',
remoteAddr,
date,
method,
url,
httpVersion,
status
));
};
next();
};
|
Correct link in code comment
|
[minor] Correct link in code comment
|
JavaScript
|
mit
|
chrismoulton/wzrd.in,rstr74/wzrd.in,jfhbrook/wzrd.in,jfhbrook/browserify-cdn,rstr74/wzrd.in,jfhbrook/wzrd.in,jfhbrook/browserify-cdn,tsatse/browserify-cdn,wraithgar/wzrd.in,tsatse/browserify-cdn,chrismoulton/wzrd.in,wraithgar/wzrd.in
|
f3f2ed4622828fdce9ca809e32939548267cf406
|
lib/node_modules/@stdlib/types/ndarray/ctor/lib/get2d.js
|
lib/node_modules/@stdlib/types/ndarray/ctor/lib/get2d.js
|
'use strict';
// MODULES //
var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive;
// FUNCTIONS //
/**
* Returns an array element.
*
* @private
* @param {integer} i - index for first dimension
* @param {integer} j - index for second dimension
* @throws {TypeError} index for first dimension must be an integer value
* @throws {TypeError} index for second dimension must be an integer value
* @returns {*} array element
*/
function get( i, j ) {
/* eslint-disable no-invalid-this */
var idx;
if ( !isInteger( i ) ) {
throw new TypeError( 'invalid input argument. Index for first dimension must be an integer value. Value: `'+i+'`.' );
}
if ( !isInteger( j ) ) {
throw new TypeError( 'invalid input argument. Index for second dimension must be an integer value. Value: `'+j+'`.' );
}
// TODO: support index modes
idx = this._offset + ( this._strides[0]*i ) + ( this._strides[1]*j );
return this._buffer[ idx ];
} // end FUNCTION get()
// EXPORTS //
module.exports = get;
|
'use strict';
// MODULES //
var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive;
var getIndex = require( './get_index.js' );
// FUNCTIONS //
/**
* Returns an array element.
*
* @private
* @param {integer} i - index for first dimension
* @param {integer} j - index for second dimension
* @throws {TypeError} index for first dimension must be an integer value
* @throws {TypeError} index for second dimension must be an integer value
* @returns {*} array element
*/
function get( i, j ) {
/* eslint-disable no-invalid-this */
var idx;
if ( !isInteger( i ) ) {
throw new TypeError( 'invalid input argument. Index for first dimension must be an integer value. Value: `'+i+'`.' );
}
if ( !isInteger( j ) ) {
throw new TypeError( 'invalid input argument. Index for second dimension must be an integer value. Value: `'+j+'`.' );
}
i = getIndex( i, this._shape[ 0 ], this._mode );
j = getIndex( j, this._shape[ 1 ], this._mode );
idx = this._offset + ( this._strides[0]*i ) + ( this._strides[1]*j );
return this._buffer[ idx ];
} // end FUNCTION get()
// EXPORTS //
module.exports = get;
|
Add support for an index mode
|
Add support for an index mode
|
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
|
5620dd2921b534e1328c9305c66c254d04131797
|
app/index.js
|
app/index.js
|
'use strict';
var util = require('util');
var yeoman = require('yeoman-generator');
var Generator = module.exports = function () {
var cb = this.async();
var ignores = [
'.git',
'CHANGELOG.md',
'CONTRIBUTING.md',
'LICENSE.md',
'README.md'
];
this.prompt([{
type: 'confirm',
name: 'docs',
message: 'Would you like docs included?',
default: false
}], function (props) {
if (props.docs) {
this.directory('doc');
}
this.directory('css');
this.directory('img');
this.directory('js');
this.expandFiles('*', {
cwd: this.sourceRoot(),
dot: true
}).forEach(function (el) {
if (ignores.indexOf(el) === -1) {
this.copy(el, el);
}
}, this);
cb();
}.bind(this));
};
util.inherits(Generator, yeoman.generators.Base);
Generator.name = 'HTML5 Boilerplate';
|
'use strict';
var util = require('util');
var yeoman = require('yeoman-generator');
var Generator = module.exports = function Generator () {
yeoman.generators.Base.apply(this, arguments);
};
util.inherits(Generator, yeoman.generators.NamedBase);
Generator.prototype.copyFiles = function () {
var cb = this.async();
var ignores = [
'.git',
'CHANGELOG.md',
'CONTRIBUTING.md',
'LICENSE.md',
'README.md'
];
this.prompt([{
type: 'confirm',
name: 'docs',
message: 'Would you like docs included?',
default: false
}], function (props) {
if (props.docs) {
this.directory('doc');
}
this.directory('css');
this.directory('img');
this.directory('js');
this.expandFiles('*', {
cwd: this.sourceRoot(),
dot: true
}).forEach(function (el) {
if (ignores.indexOf(el) === -1) {
this.copy(el, el);
}
}, this);
cb();
}.bind(this));
};
Generator.name = 'HTML5 Boilerplate';
|
Make generator work with `yo` v1.0.5
|
Make generator work with `yo` v1.0.5
Ref #12.
Fix #11.
|
JavaScript
|
mit
|
h5bp/generator-h5bp
|
7aee442d3b12698bb027c747a11719a075d9c586
|
lib/autoprefix-processor.js
|
lib/autoprefix-processor.js
|
var autoprefixer = require('autoprefixer-core');
module.exports = function(less) {
function AutoprefixProcessor(options) {
this.options = options || {};
};
AutoprefixProcessor.prototype = {
process: function (css, extra) {
var options = this.options;
var sourceMap = extra.sourceMap;
var sourceMapInline, processOptions = {};
if (sourceMap) {
processOptions.map = {};
processOptions.to = sourceMap.getOutputFilename();
processOptions.from = sourceMap.getInputFilename();
sourceMapInline = sourceMap.isInline();
if (sourceMapInline) {
processOptions.map.inline = true;
} else {
processOptions.map.prev = sourceMap.getExternalSourceMap();
processOptions.map.annotation = sourceMap.getSourceMapURL();
}
}
var processed = autoprefixer(options).process(css, processOptions);
if (sourceMap && !sourceMapInline) {
sourceMap.setExternalSourceMap(processed.map);
}
return processed.css;
}
};
return AutoprefixProcessor;
};
|
var autoprefixer = require('autoprefixer-core');
module.exports = function(less) {
function AutoprefixProcessor(options) {
this.options = options || {};
};
AutoprefixProcessor.prototype = {
process: function (css, extra) {
var options = this.options;
var sourceMap = extra.sourceMap;
var sourceMapInline, processOptions = {};
if (sourceMap) {
processOptions.map = {};
processOptions.to = sourceMap.getOutputFilename();
// setting from = input filename works unless there is a directory,
// then autoprefixer adds the directory onto the source filename twice.
// setting to to anything else causes an un-necessary extra file to be
// added to the map, but its better than it failing
processOptions.from = sourceMap.getOutputFilename();
sourceMapInline = sourceMap.isInline();
if (sourceMapInline) {
processOptions.map.inline = true;
} else {
processOptions.map.prev = sourceMap.getExternalSourceMap();
processOptions.map.annotation = sourceMap.getSourceMapURL();
}
}
var processed = autoprefixer(options).process(css, processOptions);
if (sourceMap && !sourceMapInline) {
sourceMap.setExternalSourceMap(processed.map);
}
return processed.css;
}
};
return AutoprefixProcessor;
};
|
Fix sourcemaps when in a directory
|
Fix sourcemaps when in a directory
|
JavaScript
|
apache-2.0
|
less/less-plugin-autoprefix,PixnBits/less-plugin-autoprefix
|
7df02298180fcd94019506f363392c48e0fe21cf
|
app.js
|
app.js
|
function Person(name)
{
this.name = name;
this.parent = null;
this.children = [];
this.siblings = [];
this.getChildren = function ()
{
return this.children;
}
};
var Nancy = new Person("Nancy")
var Adam = new Person("Adam")
var Jill = new Person("Jill")
var Carl = new Person("Carl")
Nancy.children.push(Adam, Jill, Carl)
console.log(Nancy.getChildren());
|
var familyTree = [];
function Person(name)
{
this.name = name;
this.parent = null;
this.children = [];
this.siblings = [];
this.addChild = function(name)
{
var child = new Person(name)
child.parent = this
this.children.push(child);
};
this.init();
};
Person.prototype.init = function(){
familyTree.push(this)
};
//Driver test
console.log(familyTree);
var nancy = new Person("Nancy");
nancy.addChild("Adam")
console.log(familyTree);
|
Restructure Person prototype and add family array
|
Restructure Person prototype and add family array
|
JavaScript
|
mit
|
Nilaco/Family-Tree,Nilaco/Family-Tree
|
cf73385957d54ef0c808aa69e261fe57b87cb7f9
|
ukelonn.web.frontend/src/main/frontend/reducers/passwordReducer.js
|
ukelonn.web.frontend/src/main/frontend/reducers/passwordReducer.js
|
import { createReducer } from 'redux-starter-kit';
import {
UPDATE,
} from '../actiontypes';
const passwordReducer = createReducer(null, {
[UPDATE]: (state, action) => {
if (!(action.payload && action.payload.password)) {
return state;
}
return action.payload.password;
},
});
export default passwordReducer;
|
import { createReducer } from 'redux-starter-kit';
import {
UPDATE,
LOGIN_RECEIVE,
INITIAL_LOGIN_STATE_RECEIVE,
} from '../actiontypes';
const passwordReducer = createReducer(null, {
[UPDATE]: (state, action) => {
if (!(action.payload && action.payload.password)) {
return state;
}
return action.payload.password;
},
[LOGIN_RECEIVE]: (state, action) => '',
[INITIAL_LOGIN_STATE_RECEIVE]: (state, action) => '',
});
export default passwordReducer;
|
Set password in redux to empty string on successful login
|
Set password in redux to empty string on successful login
|
JavaScript
|
apache-2.0
|
steinarb/ukelonn,steinarb/ukelonn,steinarb/ukelonn
|
2eb63b132d4ecd0c78998c716139298862319460
|
public/js/identify.js
|
public/js/identify.js
|
(function(){
function close() {
$('.md-show .md-close').click();
}
function clean() {
$('.md-show input[name="name"]').val(''),
$('.md-show input[name="email"]').val(''),
$('.md-show input[name="phone"]').val('');
}
$('.btn-modal').click(function() {
var name = $('.md-show input[name="name"]').val(),
email = $('.md-show input[name="email"]').val(),
phone = $('.md-show input[name="phone"]').val();
if (name.trim().length == 0 || email.trim().length == 0 || phone.trim().length == 0) {
return;
}
dito.identify({
id: dito.generateID(email),
name: name,
email: email,
data: {
phone: phone,
}
});
clean();
close();
});
})();
|
(function(){
function close() {
$('.md-show .md-close').click();
}
function clean() {
$('.md-show input[name="name"]').val(''),
$('.md-show input[name="email"]').val(''),
$('.md-show input[name="phone"]').val('');
}
$('.btn-modal').click(function() {
var name = $('.md-show input[name="name"]').val(),
email = $('.md-show input[name="email"]').val(),
phone = $('.md-show input[name="phone"]').val();
if (name.trim().length == 0 || email.trim().length == 0 || phone.trim().length == 0) {
return;
}
dito.identify({
id: dito.generateID(email),
name: name,
email: email,
data: {
telefone: phone
}
});
clean();
close();
});
})();
|
Modify key "phone" to "telefone"
|
Modify key "phone" to "telefone"
|
JavaScript
|
apache-2.0
|
arthurbailao/gama-demo,arthurbailao/gama-demo
|
ea015fcb266ab4287e583bed76bf5fbbb62205e5
|
database/index.js
|
database/index.js
|
let pgp = require('pg-promise')({ssl: true});
// let databaseUrl = process.env.DATABASE_URL || require('./config');
// module.exports = pgp(databaseUrl);
|
let pgp = require('pg-promise')(); // initialization option was {ssl: true}, sorry for deleting, but wasn't working for me with it
let connection = process.env.DATABASE_URL || require('./config');
module.exports = pgp(connection);
|
Delete initialization options and change variable name
|
Delete initialization options and change variable name
|
JavaScript
|
mit
|
SentinelsOfMagic/SentinelsOfMagic
|
62188e803684cb8b7cf965a895da23bc583b83a5
|
postcss.config.js
|
postcss.config.js
|
"use strict";
const {media_breakpoints} = require("./static/js/css_variables");
module.exports = {
plugins: {
// Warning: despite appearances, order is significant
"postcss-nested": {},
"postcss-extend-rule": {},
"postcss-simple-vars": {
variables: media_breakpoints,
},
"postcss-calc": {},
"postcss-media-minmax": {},
autoprefixer: {},
},
};
|
"use strict";
const {media_breakpoints} = require("./static/js/css_variables");
module.exports = {
plugins: [
require("postcss-nested"),
require("postcss-extend-rule"),
require("postcss-simple-vars")({variables: media_breakpoints}),
require("postcss-calc"),
require("postcss-media-minmax"),
require("autoprefixer"),
],
};
|
Convert plugins object to an array.
|
postcss: Convert plugins object to an array.
Since order matters for plugins, its better to use the Array syntax
to pass plugins to the PostCSS instead of Object.
This also allows us to reliably add more plugins programatically if
we so choose.
[[email protected]: Adjust to work with postcss-cli.]
Co-authored-by: Anders Kaseorg <[email protected]>
Signed-off-by: Anders Kaseorg <[email protected]>
|
JavaScript
|
apache-2.0
|
eeshangarg/zulip,kou/zulip,kou/zulip,kou/zulip,andersk/zulip,zulip/zulip,rht/zulip,kou/zulip,andersk/zulip,eeshangarg/zulip,rht/zulip,rht/zulip,rht/zulip,zulip/zulip,zulip/zulip,eeshangarg/zulip,eeshangarg/zulip,rht/zulip,zulip/zulip,andersk/zulip,rht/zulip,andersk/zulip,zulip/zulip,rht/zulip,zulip/zulip,zulip/zulip,kou/zulip,eeshangarg/zulip,eeshangarg/zulip,kou/zulip,andersk/zulip,eeshangarg/zulip,kou/zulip,andersk/zulip,andersk/zulip
|
55a531708dfcf895433ce9abaf2c11fe9635df14
|
public/js/read.js
|
public/js/read.js
|
var imgWidth = new Array();
function imageWidth()
{
var width = $(window).width() - fixedPadding;
$(".img_flex").each(function(index)
{
if (width != $(this).width())
{
if (width < imgWidth[index])
{
$(this).width(width);
}
else
{
$(this).width(imgWidth[index]);
}
}
});
}
$(document).ready(function() {
$(document).keyup(function(e) {
if (e.keyCode === 37) window.location.href = prevPage;
if (e.keyCode === 39) window.location.href = nextPage;
});
$(".jump").on('change', function() {
window.location.href = baseUrl + this.value;
});
$(".img_flex").each(function(index)
{
imgWidth.push($(this).width());
});
imageWidth();
$(window).resize(function(){
imageWidth();
});
});
|
var imgWidth = new Array();
var imagePadding = 100;
function imageWidth()
{
var width = $(window).width() - imagePadding;
$(".img_flex").each(function(index)
{
if (width != $(this).width())
{
if (width < imgWidth[index])
{
$(this).width(width);
}
else
{
$(this).width(imgWidth[index]);
}
}
});
}
$(document).ready(function() {
$(document).keyup(function(e) {
if (e.keyCode === 37) window.location.href = prevPage;
if (e.keyCode === 39) window.location.href = nextPage;
});
$(".jump").on('change', function() {
window.location.href = baseUrl + this.value;
});
$(".img_flex").each(function(index)
{
imgWidth.push($(this).width());
});
imageWidth();
$(window).resize(function(){
imageWidth();
});
});
|
Change padding depend on window width (the bigger the more big the width is)
|
Change padding depend on window width (the bigger the more big the width is)
|
JavaScript
|
mit
|
hernantas/MangaReader,hernantas/MangaReader,hernantas/MangaReader
|
8be4bc9543ba1f23019d619c822bc7e4769e22da
|
stories/Autocomplete.stories.js
|
stories/Autocomplete.stories.js
|
import React from 'react';
import { storiesOf } from '@storybook/react';
import Autocomplete from '../src/Autocomplete';
const stories = storiesOf('javascript/Autocomplete', module);
stories.addParameters({
info: {
text: `Add an autocomplete dropdown below your input
to suggest possible values in your form. You can
populate the list of autocomplete options dynamically as well.`
}
});
stories.add('Default', () => (
<Autocomplete
options={{
data: {
['Gus Fring']: null,
['Saul Goodman']: null,
['Tuco Salamanca']: 'https://placehold.it/250x250'
}
}}
placeholder="Insert here"
/>
));
|
import React from 'react';
import { storiesOf } from '@storybook/react';
import Autocomplete from '../src/Autocomplete';
const stories = storiesOf('javascript/Autocomplete', module);
stories.addParameters({
info: {
text: `Add an autocomplete dropdown below your input
to suggest possible values in your form. You can
populate the list of autocomplete options dynamically as well.`
}
});
stories.add('Default', () => (
<Autocomplete
options={{
data: {
['Gus Fring']: null,
['Saul Goodman']: null,
['Tuco Salamanca']: 'https://placehold.it/250x250'
}
}}
placeholder="Insert here"
/>
));
stories.add('With icon', () => (
<Autocomplete
options={{
data: {
['Gus Fring']: null,
['Saul Goodman']: null,
['Tuco Salamanca']: 'https://placehold.it/250x250'
}
}}
placeholder="Insert here"
icon="textsms"
/>
));
|
Add autocomplete with icon story
|
Add autocomplete with icon story
|
JavaScript
|
mit
|
react-materialize/react-materialize,react-materialize/react-materialize,react-materialize/react-materialize
|
ef090c4c1b819b2df89ec50a855260decdf5ace0
|
app/tradeapi/tradeapi.js
|
app/tradeapi/tradeapi.js
|
/**
This Angular module provide interface to VNDIRECT API, include:
- Auth API
- Trade API
*/
angular.module('myApp.tradeapi', [])
.factory('tradeapi', ['$http', function($http) {
var AUTH_URL = 'https://auth-api.vndirect.com.vn/auth';
var token = null;
return {
login: function(username, password) {
$http({
method: 'POST',
url: AUTH_URL,
data: {
username: username,
password: password
}
})
.then(function(response) {
console.log('Login success', response);
})
},
};
});
|
/**
This Angular module provide interface to VNDIRECT API, include:
- Auth API
- Trade API
*/
angular.module('myApp.tradeapi', [])
.factory('tradeapi', ['$http', '$q', function($http, $q) {
var AUTH_URL = 'https://auth-api.vndirect.com.vn/auth';
var CUSOMTER_URL = 'https://trade-api.vndirect.com.vn/customer';
var token = null;
return {
login: function(username, password) {
var deferred = $q.defer();
$http({
method: 'POST',
url: AUTH_URL,
data: {
username: username,
password: password
}
})
.then(function(response) {
deferred.resolve(response.data);
token = response.data.token;
}, function(response) {
deferred.reject(response.data.message);
});
return deferred.promise;
},
/**
Retrieve customer information such as cusid, name, accou
*/
retrieve_customer: function() {
var deferred = $q.defer();
if(token) {
$http({
method: 'GET',
url: CUSOMTER_URL,
headers: {
'X-AUTH-TOKEN': token
}
})
.then(function(response) {
deferred.resolve(response.data);
}, function(response) {
deferred.reject(response.data.message);
});
return deferred.promise;
}
else{
throw 'You are not logged in';
}
}
};
}]);
|
Integrate login & retrieve customer with Trade API
|
Integrate login & retrieve customer with Trade API
|
JavaScript
|
mit
|
VNDIRECT/SmartP,VNDIRECT/SmartP
|
b5a460ecc35dc5609339317337d467368d7593bb
|
frontend/src/utils/createWebSocketConnection.js
|
frontend/src/utils/createWebSocketConnection.js
|
import SockJS from 'sockjs-client'
import Stomp from 'webstomp-client'
const wsURL = 'http://localhost:8080/seven-wonders-websocket'
const createConnection = (headers = {}) => new Promise((resolve, reject) => {
let socket = Stomp.over(new SockJS(wsURL), {
debug: process.env.NODE_ENV !== "production"
})
socket.connect(headers, (frame) => {
return resolve({ frame, socket })
}, reject)
})
export default createConnection
|
import SockJS from 'sockjs-client'
import Stomp from 'webstomp-client'
const wsURL = '/seven-wonders-websocket'
const createConnection = (headers = {}) => new Promise((resolve, reject) => {
let socket = Stomp.over(new SockJS(wsURL), {
debug: process.env.NODE_ENV !== "production"
})
socket.connect(headers, (frame) => {
return resolve({ frame, socket })
}, reject)
})
export default createConnection
|
Remove absolute ws link in frontend
|
Remove absolute ws link in frontend
|
JavaScript
|
mit
|
luxons/seven-wonders,luxons/seven-wonders,luxons/seven-wonders
|
d299ceac7d3d115266a8f45a14f1fd9f42cea883
|
tests/test-simple.js
|
tests/test-simple.js
|
/*
* Copyright 2011 Rackspace
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
var et = require('elementtree');
exports['test_error_type'] = function(test, assert) {
/* Ported from <https://github.com/lxml/lxml/blob/master/src/lxml/tests/test_elementtree.py> */
var Element = et.Element
var root = Element('root');
root.append(Element('one'));
root.append(Element('two'));
root.append(Element('three'));
assert.equal(3, root.len())
assert.equal('one', root.getItem(0).tag)
assert.equal('two', root.getItem(1).tag)
assert.equal('three', root.getItem(2).tag)
test.finish();
};
|
/*
* Copyright 2011 Rackspace
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
var et = require('elementtree');
exports['test_simplest'] = function(test, assert) {
/* Ported from <https://github.com/lxml/lxml/blob/master/src/lxml/tests/test_elementtree.py> */
var Element = et.Element
var root = Element('root');
root.append(Element('one'));
root.append(Element('two'));
root.append(Element('three'));
assert.equal(3, root.len())
assert.equal('one', root.getItem(0).tag)
assert.equal('two', root.getItem(1).tag)
assert.equal('three', root.getItem(2).tag)
test.finish();
};
exports['test_attribute_values'] = function(test, assert) {
var XML = et.XML;
var root = XML('<doc alpha="Alpha" beta="Beta" gamma="Gamma"/>');
assert.equal('Alpha', root.attrib['alpha']);
assert.equal('Beta', root.attrib['beta']);
assert.equal('Gamma', root.attrib['gamma']);
test.finish();
};
|
Add simple attributes test case
|
Add simple attributes test case
|
JavaScript
|
apache-2.0
|
racker/node-elementtree
|
f8c3893888e1cd5d8b31e4621fe6c04b3343bfce
|
src/app/UI/lib/managers/statistics/client/components/routes.js
|
src/app/UI/lib/managers/statistics/client/components/routes.js
|
import React from "react";
import { Route } from "react-router";
import {
View as TAView
} from "ui-components/type_admin";
import Item from "./Item";
import List from "./List";
const routes = [
<Route
key="charts"
path="charts"
component={TAView}
List={List}
type="stat.chart"
label="Statistics"
>
<Route
key="stat"
path=":_id"
component={TAView}
Item={Item}
type="stat.chart"
/>
</Route>
];
export default routes;
|
import React from "react";
import { Route } from "react-router";
import {
View as TAView,
EditTags as TAEditTags
} from "ui-components/type_admin";
import Item from "./Item";
import List from "./List";
const routes = [
<Route
key="charts"
path="charts"
component={TAView}
List={List}
type="stat.chart"
label="Statistics"
>
<Route
path=":_id"
component={TAView}
Item={Item}
type="stat.chart"
>
<Route
path="tags"
component={TAView}
Action={TAEditTags}
type="stat.chart"
/>
</Route>
</Route>
];
export default routes;
|
Add edit tags to statistics chart
|
UI: Add edit tags to statistics chart
|
JavaScript
|
mit
|
Combitech/codefarm,Combitech/codefarm,Combitech/codefarm
|
2162a6463b14f8cf4f78c964aca248828bed5faf
|
packages/components/containers/labels/FoldersSection.js
|
packages/components/containers/labels/FoldersSection.js
|
import React from 'react';
import { c } from 'ttag';
import { Loader, Alert, PrimaryButton, useFolders, useModals } from 'react-components';
import FolderTreeViewList from './FolderTreeViewList';
import EditLabelModal from './modals/Edit';
function LabelsSection() {
const [folders, loadingFolders] = useFolders();
const { createModal } = useModals();
if (loadingFolders) {
return <Loader />;
}
return (
<>
<Alert
type="info"
className="mt1 mb1"
learnMore="https://protonmail.com/support/knowledge-base/creating-folders/"
>
{c('LabelSettings').t`A message can only be in filed in a single Folder at a time.`}
</Alert>
<div className="mb1">
<PrimaryButton onClick={() => createModal(<EditLabelModal type="folder" />)}>
{c('Action').t`Add folder`}
</PrimaryButton>
</div>
{folders.length ? (
<FolderTreeViewList items={folders} />
) : (
<Alert>{c('LabelSettings').t`No folders available`}</Alert>
)}
</>
);
}
export default LabelsSection;
|
import React from 'react';
import { c } from 'ttag';
import { Loader, Alert, PrimaryButton, useFolders, useModals } from 'react-components';
import FolderTreeViewList from './FolderTreeViewList';
import EditLabelModal from './modals/Edit';
function LabelsSection() {
const [folders, loadingFolders] = useFolders();
const { createModal } = useModals();
if (loadingFolders) {
return <Loader />;
}
return (
<>
<Alert
type="info"
className="mt1 mb1"
learnMore="https://protonmail.com/support/knowledge-base/creating-folders/"
>
{c('LabelSettings').t`A message can only be filed in a single Folder at a time.`}
</Alert>
<div className="mb1">
<PrimaryButton onClick={() => createModal(<EditLabelModal type="folder" />)}>
{c('Action').t`Add folder`}
</PrimaryButton>
</div>
{folders.length ? (
<FolderTreeViewList items={folders} />
) : (
<Alert>{c('LabelSettings').t`No folders available`}</Alert>
)}
</>
);
}
export default LabelsSection;
|
Fix translation typo message info folders
|
Fix translation typo message info folders
|
JavaScript
|
mit
|
ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient
|
6e72bc8a412b0ba8dc648d80a6d433c282496f16
|
client/app/common/navbar/navbar.controller.js
|
client/app/common/navbar/navbar.controller.js
|
import moment from 'moment';
class NavbarController {
constructor() {
this.name = 'navbar';
}
$onInit(){
this.moment = moment().format('dddd HH:mm');
this.updateDate();
this.user =
{
name: 'Jesus Garcia',
mail: '[email protected]',
picture: '//icons.iconarchive.com/icons/graphicloads/flat-finance/256/person-icon.png',
lists: [
{
name: 'Study',
timers: [
{
name: 'Timer 1',
time: '1500'
},
{
name: 'Timer 2',
time: '1500'
},
{
name: 'Timer 3',
time: '1500'
}
]
},
{
name: 'Piano',
timers: [
{
name: 'Timer 4',
time: '1500'
},
{
name: 'Timer 5',
time: '1500'
}
]
}
]
};
}
updateDate () {
setTimeout(() => {
this.moment = moment().format('dddd HH:mm');
this.updateDate();
}, 1000);
}
}
export default NavbarController;
|
import moment from 'moment';
class NavbarController {
constructor() {
this.name = 'navbar';
}
$onInit(){
this.moment = moment().format('dddd HH:mm');
this.updateDate();
this.user =
{
name: 'Jesus Garcia',
mail: '[email protected]',
picture: '//icons.iconarchive.com/icons/graphicloads/flat-finance/256/person-icon.png',
lists: [
{
name: 'Study',
timers: [
{
name: 'Timer 1',
time: '1500'
},
{
name: 'Timer 2',
time: '1500'
},
{
name: 'Timer 3',
time: '1500'
}
]
},
{
name: 'Piano',
timers: [
{
name: 'Timer 4',
time: '1500'
},
{
name: 'Timer 5',
time: '1500'
}
]
}
]
};
}
updateDate () {
setTimeout(() => {
this.moment = moment().format('dddd HH:mm');
this.updateDate();
}, 60000);
}
}
export default NavbarController;
|
Update local Date automatically each 60s
|
Update local Date automatically each 60s
|
JavaScript
|
apache-2.0
|
ctwhome/studylist,ctwhome/studylist
|
33450086e8ada4f7d73e93da99a61b1b007e7c75
|
client/scripts/controllers/UsersController.js
|
client/scripts/controllers/UsersController.js
|
/**
* Created by groupsky on 18.11.15.
*/
require('../app').controller('UsersController', /* @ngInject */function ($filter, $scope, User) {
var controller = this
var filter = $filter('filter')
$scope.rows = User.query({
limit: 1000
})
controller.filterRows = function (config) {
return function (row) {
if (config && config.role) {
if (config.role !== row.role) {
return false
}
}
if (config && config.search) {
if (!filter([row], config.search).length) {
return false
}
}
return true
}
}
})
|
/**
* Created by groupsky on 18.11.15.
*/
require('../app').controller('UsersController', /* @ngInject */function ($filter, $scope, User) {
var controller = this
var filter = $filter('filter')
$scope.rows = User.query({
limit: 5000
})
controller.filterRows = function (config) {
return function (row) {
if (config && config.role) {
if (config.role !== row.role) {
return false
}
}
if (config && config.search) {
if (!filter([row], config.search).length) {
return false
}
}
return true
}
}
})
|
Increase limit for fetching users in UI
|
Increase limit for fetching users in UI
|
JavaScript
|
agpl-3.0
|
BspbOrg/smartbirds-server,BspbOrg/smartbirds-server,BspbOrg/smartbirds-server
|
be284e8f6e0a72ae58d861a26f8bd748dfbad156
|
tasks/register/cron.js
|
tasks/register/cron.js
|
"use strict";
const path = require('path');
const Sails = require('sails');
const _ = require('lodash');
module.exports = function (grunt) {
grunt.registerTask('cron', async function (...args) {
const done = this.async();
Sails.load({ hooks: { grunt: false } }, async () => {
try {
const filePath = path.resolve('config', 'scientilla.js');
const config = require(filePath);
const crons = config.scientilla.crons.filter(cron => cron.name === args[0]);
if (crons.length > 0) {
for (const cron of crons) {
for (const job of cron.jobs) {
try {
await _.get(global, job.fn)(...job.params);
} catch (e) {
throw e;
}
}
}
} else {
throw 'Cron not found!';
}
done();
} catch(err) {
sails.log.debug(err);
done();
return 1;
}
});
});
};
|
"use strict";
const Sails = require('sails');
const _ = require('lodash');
module.exports = function (grunt) {
grunt.registerTask('cron', async function (...args) {
const done = this.async();
Sails.load({ hooks: { grunt: false } }, async () => {
try {
const crons = sails.config.scientilla.crons.filter(cron => cron.name === args[0]);
if (crons.length > 0) {
for (const cron of crons) {
for (const job of cron.jobs) {
try {
await _.get(global, job.fn)(...job.params);
} catch (e) {
throw e;
}
}
}
} else {
throw 'Cron not found!';
}
done();
} catch(err) {
sails.log.debug(err);
done();
return 1;
}
});
});
};
|
Remove reading config from file
|
Remove reading config from file
|
JavaScript
|
mit
|
scientilla/scientilla,scientilla/scientilla,scientilla/scientilla
|
16ae1fcedba350a023ed866413cea05d2a3cd8c5
|
src/js/middle_level/elements/gizmos/M_DirectionalLightGizmo.js
|
src/js/middle_level/elements/gizmos/M_DirectionalLightGizmo.js
|
import M_Gizmo from './M_Gizmo';
import Arrow from '../../../low_level/primitives/Arrow';
import ClassicMaterial from '../../../low_level/materials/ClassicMaterial';
import M_Mesh from '../meshes/M_Mesh';
import Vector4 from '../../../low_level/math/Vector4';
export default class M_DirectionalLightGizmo extends M_Gizmo {
constructor(glBoostContext, length) {
super(glBoostContext, null, null);
this._init(glBoostContext, length);
// this.isVisible = false;
this.baseColor = new Vector4(0.8, 0.8, 0, 1);
}
_init(glBoostContext, length) {
this._material = new ClassicMaterial(this._glBoostContext);
this._mesh = new M_Mesh(glBoostContext,
new Arrow(this._glBoostContext, length, 3),
this._material);
this.addChild(this._mesh);
}
set rotate(rotateVec3) {
this._mesh.rotate = rotateVec3;
}
get rotate() {
return this._mesh.rotate;
}
set baseColor(colorVec) {
this._material.baseColor = colorVec;
}
get baseColor() {
return this._material.baseColor;
}
}
|
import M_Gizmo from './M_Gizmo';
import Arrow from '../../../low_level/primitives/Arrow';
import ClassicMaterial from '../../../low_level/materials/ClassicMaterial';
import M_Mesh from '../meshes/M_Mesh';
import Vector4 from '../../../low_level/math/Vector4';
export default class M_DirectionalLightGizmo extends M_Gizmo {
constructor(glBoostContext, length) {
super(glBoostContext, null, null);
this._init(glBoostContext, length);
this.isVisible = false;
this.baseColor = new Vector4(0.8, 0.8, 0, 1);
}
_init(glBoostContext, length) {
this._material = new ClassicMaterial(this._glBoostContext);
this._mesh = new M_Mesh(glBoostContext,
new Arrow(this._glBoostContext, length, 3),
this._material);
this.addChild(this._mesh);
}
set rotate(rotateVec3) {
this._mesh.rotate = rotateVec3;
}
get rotate() {
return this._mesh.rotate;
}
set baseColor(colorVec) {
this._material.baseColor = colorVec;
}
get baseColor() {
return this._material.baseColor;
}
}
|
Make directional light gizmo invisible
|
Make directional light gizmo invisible
|
JavaScript
|
mit
|
emadurandal/GLBoost,emadurandal/GLBoost,cx20/GLBoost,cx20/GLBoost,emadurandal/GLBoost,cx20/GLBoost
|
d6ab81e3e201e08004aee6ec30d4cf0d85678886
|
src/D3TopoJson.js
|
src/D3TopoJson.js
|
po.d3TopoJson = function(fetch) {
if (!arguments.length) fetch = po.queue.json;
var topoToGeo = function(url, callback) {
function convert(topology, object, layer, features) {
if (object.type == "GeometryCollection" && !object.properties) {
object.geometries.forEach(function(g) {
convert(topology, g, layer, features);
});
}
else {
var feature = topojson.feature(topology, object);
feature.properties = { layer: layer };
if (object.properties) {
Object.keys(object.properties).forEach(function(property) {
feature.properties[property] = object.properties[property];
});
}
features.push(feature);
}
}
return fetch(url, function(topology) {
var features = [];
for (var o in topology.objects) {
convert(topology, topology.objects[o], o, features);
}
callback({
type: "FeatureCollection",
features: features
});
});
};
var d3TopoJson = po.d3GeoJson(topoToGeo);
return d3TopoJson;
};
|
po.d3TopoJson = function(fetch) {
if (!arguments.length) fetch = po.queue.json;
var topologyFeatures = function(topology) {
function convert(topology, object, layer, features) {
if (object.type == "GeometryCollection" && !object.properties) {
object.geometries.forEach(function(g) {
convert(topology, g, layer, features);
});
}
else {
var feature = topojson.feature(topology, object);
feature.properties = { layer: layer };
if (object.properties) {
Object.keys(object.properties).forEach(function(property) {
feature.properties[property] = object.properties[property];
});
}
features.push(feature);
}
}
var features = [];
for (var o in topology.objects) {
convert(topology, topology.objects[o], o, features);
}
return features;
};
var topoToGeo = function(url, callback) {
return fetch(url, function(topology) {
callback({
type: "FeatureCollection",
features: topologyFeatures(topology)
});
});
};
var d3TopoJson = po.d3GeoJson(topoToGeo);
d3TopoJson.topologyFeatures = function(x) {
if (!arguments.length) return topologyFeatures;
topologyFeatures = x;
return d3TopoJson;
};
return d3TopoJson;
};
|
Allow changing the function used to extract GeoJSON features from TopoJSON.
|
Allow changing the function used to extract GeoJSON features from TopoJSON.
|
JavaScript
|
bsd-3-clause
|
dillan/mapsense.js,RavishankarDuMCA10/mapsense.js,sfchronicle/mapsense.js,manueltimita/mapsense.js,cksachdev/mapsense.js,mapsense/mapsense.js,shkfnly/mapsense.js,Laurian/mapsense.js,gimlids/mapsense.js
|
97e1d783d9a09dca204dff19bf046fc0af198643
|
test/js/thumbs_test.js
|
test/js/thumbs_test.js
|
window.addEventListener('load', function(){
// touchstart
module('touchstart', environment);
test('should respond to touchstart', 1, function() {
listen('touchstart').trigger('mousedown');
});
// touchend
module('touchend', environment);
test('should respond to touchend', 1, function() {
listen('touchend').trigger('mouseup');
});
// touchmove
module('touchmove', environment);
test('should respond to touchmove', 1, function() {
listen('touchmove').trigger('mousemove');
});
});
|
window.addEventListener('load', function(){
// mousedown
module('mousedown', environment);
test('should respond to mousedown', 1, function() {
listen('mousedown').trigger('mousedown');
});
// mouseup
module('mouseup', environment);
test('should respond to mouseup', 1, function() {
listen('mouseup').trigger('mouseup');
});
// mousemove
module('mousemove', environment);
test('should respond to mousemove', 1, function() {
listen('mousemove').trigger('mousemove');
});
// touchstart
module('touchstart', environment);
test('should respond to touchstart', 1, function() {
listen('touchstart').trigger('mousedown');
});
// touchend
module('touchend', environment);
test('should respond to touchend', 1, function() {
listen('touchend').trigger('mouseup');
});
// touchmove
module('touchmove', environment);
test('should respond to touchmove', 1, function() {
listen('touchmove').trigger('mousemove');
});
});
|
Add mousedown/mouseup/mousemove to test suite.
|
Add mousedown/mouseup/mousemove to test suite.
To make sure that we do not clobber those events.
|
JavaScript
|
mit
|
mwbrooks/thumbs.js,pyrinelaw/thumbs.js,pyrinelaw/thumbs.js
|
fbc38523508db2201e6f1c136640f560a77b7282
|
lib/utils/copy.js
|
lib/utils/copy.js
|
'use strict';
const Promise = require('bluebird');
const glob = Promise.promisify(require('glob'));
const mkdirp = Promise.promisify(require('mkdirp'));
const path = require('path');
const fs = require('fs');
const mu = require('mu2');
function compile(src, dest, settings) {
settings = settings || {};
return mkdirp(path.dirname(dest))
.then(() => {
return new Promise((resolve, reject) => {
let stream;
if (path.basename(src).match(/\.tpl\./)) {
dest = dest.replace('.tpl', '');
stream = mu.compileAndRender(src, settings);
} else {
stream = fs.createReadStream(src);
}
stream.pipe(fs.createWriteStream(dest));
stream.on('end', resolve);
stream.on('error', reject);
});
});
}
function copy(src, dest, settings) {
const pattern = path.resolve(src, '**/*');
return glob(pattern, { nodir: true, dot: true })
.then((files) => {
return Promise.map(files, (file) => {
const target = path.resolve(dest, path.relative(src, file));
return compile(file, target, settings);
}, {concurrency: 1});
});
}
module.exports = copy;
|
'use strict';
const Promise = require('bluebird');
const glob = Promise.promisify(require('glob'));
const mkdirp = Promise.promisify(require('mkdirp'));
const path = require('path');
const fs = require('fs');
const mu = require('mu2');
function compile(src, dest, settings) {
settings = settings || {};
return mkdirp(path.dirname(dest))
.then(() => {
return new Promise((resolve, reject) => {
let stream;
if (path.basename(src).match(/\.tpl(\.|$)/)) {
dest = dest.replace('.tpl', '');
stream = mu.compileAndRender(src, settings);
} else {
stream = fs.createReadStream(src);
}
stream.pipe(fs.createWriteStream(dest));
stream.on('end', resolve);
stream.on('error', reject);
});
});
}
function copy(src, dest, settings) {
const pattern = path.resolve(src, '**/*');
return glob(pattern, { nodir: true, dot: true })
.then((files) => {
return Promise.map(files, (file) => {
const target = path.resolve(dest, path.relative(src, file));
return compile(file, target, settings);
}, {concurrency: 1});
});
}
module.exports = copy;
|
Fix regex for template files
|
Fix regex for template files
The regex wasn't matching dotfiles with no file extension so modify it to also include .tpl files with no additional extension.
|
JavaScript
|
mit
|
UKHomeOfficeForms/hof-generator,UKHomeOfficeForms/hof-generator
|
5f3d0240de0f8dcc5abfc8962e4a1ce9ab629b83
|
lib/and.js
|
lib/and.js
|
'use strict';
var R = require('ramda');
/**
* Output a block (or its inverse) based on whether or not both of the suppied
* arguments are truthy.
*
* @since v0.0.1
* @param {*} left
* @param {*} right
* @param {Object} options
* @throws {Error} An error is thrown when the `right` argument is missing.
* @return {String}
* @example
*
* var a = true;
* var b = 1;
* var c = false;
*
* {{#and a b}}✔︎{{else}}✘{{/and}} //=> ✔︎
* {{#and b c}}✔︎{{else}}✘{{/and}} //=> ✘
*/
module.exports = function and (left, right, options) {
if (arguments.length < 3) {
throw new Error('The "or" helper needs two arguments.');
}
return R.and(left, right) ?
options.fn(this) : options.inverse(this);
}
|
'use strict';
var R = require('ramda');
/**
* Output a block (or its inverse) based on whether or not both of the suppied
* arguments are truthy.
*
* @since v0.0.1
* @param {*} left
* @param {*} right
* @param {Object} options
* @throws {Error} An error is thrown when the `right` argument is missing.
* @return {String}
* @example
*
* var a = true;
* var b = 1;
* var c = false;
*
* {{#and a b}}✔︎{{else}}✘{{/and}} //=> ✔︎
* {{#and b c}}✔︎{{else}}✘{{/and}} //=> ✘
*/
module.exports = function and (left, right, options) {
if (arguments.length < 3) {
throw new Error('The "and" helper needs two arguments.');
}
return R.and(left, right) ?
options.fn(this) : options.inverse(this);
}
|
Fix typo in error message
|
Fix typo in error message
|
JavaScript
|
mit
|
cloudfour/core-hbs-helpers
|
670a5e6d50f69def9444b179dc62c18689463f6e
|
test/user-container.js
|
test/user-container.js
|
var _ = require('underscore');
var UserContainer = require('../lib/authentication/user-container');
var assert = require('chai').assert;
describe('tests of garbage collecting of outdated cookies', function() {
var responseMock = {
cookies: {
set: function() {
}
}
};
it('', function(done) {
//for the sake of the test
UserContainer._collectorIntervalMs = 100;
UserContainer._oudatedTimeMs = UserContainer._collectorIntervalMs + 1;
var userContainer = new UserContainer();
userContainer.saveUser(responseMock, 'token');
assert(_.size(userContainer._userList) == 1);
var user = userContainer._userList[0];
setTimeout(function() {
assert(userContainer.hasUserByCookie(user.cookie), 'Cookie should be presented');
assert(userContainer.hasUserByToken(user.token), 'Token should be presented');
setTimeout(function() {
assert(!userContainer.hasUserByCookie(user), 'User should be deleted');
assert(!userContainer.hasUserByToken(user), 'User should be deleted');
done();
}, (UserContainer._oudatedTimeMs + 2 * UserContainer._collectorIntervalMs));
}, UserContainer._collectorIntervalMs);
});
});
|
var _ = require('underscore');
var UserContainer = require('../lib/authentication/user-container');
var assert = require('chai').assert;
describe('tests of garbage collecting of outdated cookies', function() {
var responseMock = {
cookies: {
set: function() {
}
}
};
it('', function(done) {
//for the sake of the test
UserContainer._collectorIntervalMs = 100;
UserContainer._oudatedTimeMs = UserContainer._collectorIntervalMs + 10;
var userContainer = new UserContainer();
userContainer.saveUser(responseMock, 'token');
assert(_.size(userContainer._userList) == 1);
var user = userContainer._userList[0];
setTimeout(function() {
assert(userContainer.hasUserByCookie(user.cookie), 'Cookie should be presented');
assert(userContainer.hasUserByToken(user.token), 'Token should be presented');
setTimeout(function() {
assert(!userContainer.hasUserByCookie(user), 'User should be deleted');
assert(!userContainer.hasUserByToken(user), 'User should be deleted');
done();
}, (UserContainer._oudatedTimeMs + 2 * UserContainer._collectorIntervalMs));
}, UserContainer._collectorIntervalMs);
});
});
|
Fix timeout error in UserContainer test.
|
Fix timeout error in UserContainer test.
|
JavaScript
|
mit
|
cargomedia/pulsar-rest-api,njam/pulsar-rest-api,cargomedia/pulsar-rest-api,vogdb/pulsar-rest-api,njam/pulsar-rest-api,njam/pulsar-rest-api,vogdb/pulsar-rest-api,cargomedia/pulsar-rest-api,njam/pulsar-rest-api,vogdb/pulsar-rest-api,cargomedia/pulsar-rest-api
|
11ec2067d683564efe69793ee2345e05d8264e94
|
lib/flux_mixin.js
|
lib/flux_mixin.js
|
var React = require("react");
module.exports = {
propTypes: {
flux: React.PropTypes.object
},
childContextTypes: {
flux: React.PropTypes.object
},
contextTypes: {
flux: React.PropTypes.object
},
getChildContext: function() {
return {
flux: this.context.flux || this.props.flux
};
}
};
|
var React = require("react");
module.exports = {
propTypes: {
flux: React.PropTypes.object.isRequired
},
childContextTypes: {
flux: React.PropTypes.object
},
getChildContext: function() {
return {
flux: this.props.flux
};
}
};
|
Make Fluxbox.Mixin only for the top-level components
|
Make Fluxbox.Mixin only for the top-level components
|
JavaScript
|
mit
|
alcedo/fluxxor,dantman/fluxxor,chimpinano/fluxxor,nagyistoce/fluxxor,VincentHoang/fluxxor,vsakaria/fluxxor,dantman/fluxxor,nagyistoce/fluxxor,davesag/fluxxor,hoanglamhuynh/fluxxor,demiazz/fluxxor,davesag/fluxxor,BinaryMuse/fluxxor,dantman/fluxxor,davesag/fluxxor,VincentHoang/fluxxor,hoanglamhuynh/fluxxor,STRML/fluxxor,chimpinano/fluxxor,webcoding/fluxxor,chimpinano/fluxxor,SqREL/fluxxor,hoanglamhuynh/fluxxor,nagyistoce/fluxxor,STRML/fluxxor,andrewslater/fluxxor,thomasboyt/fluxxor
|
cb840a02a3485054642364742bc157b0c02d5c59
|
lib/irc.js
|
lib/irc.js
|
/* eslint no-console: 0 */
'use strict';
const irc = require('irc');
const server = process.env.IRC_SERVER;
const user = process.env.IRC_USER;
const channel = process.env.IRC_CHANNEL;
const client = module.exports.client = new irc.Client(server, user, {
channels: [channel],
});
if (process.env.NODE_ENV !== 'testing') {
client.on('registered', function clientOnRegisterd(message) {
console.log(new Date(), '[IRC]', message.args[1]);
});
}
client.on('error', function clientOnError(error) {
console.error(error);
console.error('Shutting Down...');
process.exit(1);
});
module.exports.notify = function ircPost(nodes, callback) {
nodes.forEach(function nodesForEach(node) {
// let name = `[${node.name}](${jenkins}/computer/${node.name})`;
if (node.offline) {
client.say(channel, `Jenkins slave ${node.name} is offline`);
} else {
client.say(channel, `Jenkins slave ${node.name} is online`);
}
});
callback(null);
};
|
/* eslint no-console: 0 */
'use strict';
const irc = require('irc');
const server = process.env.IRC_SERVER;
const user = process.env.IRC_USER;
const channel = process.env.IRC_CHANNEL;
const client = module.exports.client = new irc.Client(server, user, {
debug: true,
autoConnect: false,
autoRejoin: true,
channels: [channel],
showErrors: true,
});
client.connect(5, function() {
console.log(arguments);
});
if (process.env.NODE_ENV !== 'testing') {
client.on('registered', function clientOnRegisterd(message) {
console.log(new Date(), '[IRC]', message.args[1]);
});
}
client.on('error', function clientOnError(error) {
console.error(error);
console.error('Shutting Down...');
process.exit(1);
});
module.exports.notify = function ircPost(nodes, callback) {
nodes.forEach(function nodesForEach(node) {
// let name = `[${node.name}](${jenkins}/computer/${node.name})`;
if (node.offline) {
client.say(channel, `Jenkins slave ${node.name} is offline`);
} else {
client.say(channel, `Jenkins slave ${node.name} is online`);
}
});
callback(null);
};
|
Add debug information to IRC handler
|
Add debug information to IRC handler
|
JavaScript
|
mit
|
Starefossen/jenkins-monitor
|
7d566b878a58ec91c2f88e3bd58ff5d7ec9b41df
|
lib/orbit/main.js
|
lib/orbit/main.js
|
/**
Contains core methods and classes for Orbit.js
@module orbit
@main orbit
*/
// Prototype extensions
if (!Array.prototype.forEach) {
Array.prototype.forEach = function (fn, scope) {
var i, len;
for (i = 0, len = this.length; i < len; ++i) {
if (i in this) {
fn.call(scope, this[i], i, this);
}
}
};
}
/**
Namespace for core Orbit methods and classes.
@class Orbit
@static
*/
var Orbit = {};
export default Orbit;
|
/**
Contains core methods and classes for Orbit.js
@module orbit
@main orbit
*/
/**
Namespace for core Orbit methods and classes.
@class Orbit
@static
*/
var Orbit = {};
export default Orbit;
|
Remove prototype extensions. ES5.1 now required.
|
Remove prototype extensions. ES5.1 now required.
|
JavaScript
|
mit
|
greyhwndz/orbit.js,orbitjs/orbit.js,orbitjs/orbit-core,lytbulb/orbit.js,opsb/orbit.js,opsb/orbit.js,rollokb/orbit.js,lytbulb/orbit.js,ProlificLab/orbit.js,SmuliS/orbit.js,orbitjs/orbit.js,rollokb/orbit.js,jpvanhal/orbit.js,greyhwndz/orbit.js,beni55/orbit.js,jpvanhal/orbit.js,ProlificLab/orbit.js,SmuliS/orbit.js,beni55/orbit.js,jpvanhal/orbit-core,jpvanhal/orbit-core
|
b344ff88babd7ef982d54e46c969b2420026621d
|
hall/index.js
|
hall/index.js
|
const program = require('commander');
program
.version('1.0.0')
.option('-p, --port <port>', 'specify the websocket port to listen to [9870]', 9870)
.parse(process.argv);
const io = require('socket.io'),
winston = require('winston');
winston.level = 'debug';
winston.remove(winston.transports.Console);
winston.add(winston.transports.Console, {'timestamp': true});
const PORT = program.port;
winston.info('Unichat hall service');
winston.info('Listening on port ' + PORT);
const socket = io.listen(PORT);
socket.on('connection', (client) => {
winston.debug('New connection from client ' + client.id);
});
|
const program = require('commander');
program
.version('1.0.0')
.option('-p, --port <port>', 'specify the websocket port to listen to [9870]', 9870)
.parse(process.argv);
const io = require('socket.io'),
winston = require('winston');
winston.level = 'debug';
winston.remove(winston.transports.Console);
winston.add(winston.transports.Console, {'timestamp': true});
const PORT = program.port;
winston.info('Unichat hall service');
winston.info('Listening on port ' + PORT);
const socket = io.listen(PORT);
const ROOMID = 'room1';
socket.on('connection', (client) => {
winston.debug('New connection from client ' + client.id);
client.on('client-get-partner', () => {
winston.debug('Client ' + client.id + ' wants partner.');
client.emit('server-join-room', ROOMID);
winston.debug('Sending client ' + client.id + ' to room ' + ROOMID);
});
});
|
Add client-get-partner listener to hall server
|
Add client-get-partner listener to hall server
|
JavaScript
|
mit
|
dimkarakostas/unimeet,dimkarakostas/unimeet,dimkarakostas/unimeet,dimkarakostas/unimeet
|
49adc111cd02ea1d1d22281f172fda0819876970
|
main.js
|
main.js
|
var game = new Phaser.Game(600, 800, Phaser.AUTO, '', {preload: preload, create: create, update: update});
function preload() {
game.load.image('player', 'assets/player.png');
}
var player;
function create() {
player = game.add.sprite(game.world.width / 2 - 50, game.world.height - 76, 'player');
}
function update() {
}
|
var game = new Phaser.Game(600, 800, Phaser.AUTO, '', {preload: preload, create: create, update: update});
function preload() {
game.load.image('player', 'assets/player.png');
}
var player;
var cursors;
function create() {
game.physics.startSystem(Phaser.Physics.ARCADE);
player = game.add.sprite(game.world.width / 2 - 50, game.world.height - 76, 'player');
game.physics.arcade.enable(player);
player.body.collideWorldBounds = true;
cursors = game.input.keyboard.createCursorKeys();
}
function update() {
player.body.velocity.x = 0;
player.body.velocity.y = 0;
if (cursors.left.isDown) {
player.body.velocity.x = -200;
}
else if (cursors.right.isDown) {
player.body.velocity.x = 200;
}
if (cursors.up.isDown) {
player.body.velocity.y = -200;
}
else if (cursors.down.isDown) {
player.body.velocity.y = 200;
}
}
|
Allow player to move up/down/right/left
|
Allow player to move up/down/right/left
|
JavaScript
|
mit
|
Acaki/WWW_project,Acaki/WWW_project,Acaki/WWW_project
|
bf53c204ee379a7e4d2c289f6db4848d23a79aca
|
tv-bridge/lib/relay.js
|
tv-bridge/lib/relay.js
|
var WebSocket = require('faye-websocket'),
http = require('http'),
reject = require('lodash/collection/reject'),
without = require('lodash/array/without');
module.exports = function (config) {
var server = http.createServer(),
connections = [];
// Send to everyone except sender
function broadcastMessageFrom(sender, data) {
var sockets = reject(connections, function (c) { return c === sender; });
console.log('Broadcast to %s of %s connections', sockets.length, connections.length);
sockets.forEach(function (s) {
s.send(data);
});
}
server.on('upgrade', function(request, socket, body) {
if (WebSocket.isWebSocket(request)) {
var ws = new WebSocket(request, socket, body);
// Keep track of new WebSocket connection
connections.push(ws);
ws.on('message', function(event) {
console.log('New message', event.data);
broadcastMessageFrom(ws, event.data);
});
// Remove from connections
ws.on('close', function(event) {
console.log('close', event.code, event.reason);
connections = without(connections, ws);
ws = null;
});
}
});
console.log('Listening on ', config.port);
server.listen(config.port);
}
|
var WebSocket = require('faye-websocket'),
http = require('http'),
reject = require('lodash/collection/reject'),
without = require('lodash/array/without');
module.exports = function (config) {
var server = http.createServer(),
connections = [];
// Send to everyone except sender
function broadcastMessageFrom(sender, data) {
var sockets = reject(connections, function (c) { return c === sender; });
console.log('Broadcast to %s of %s connections', sockets.length, connections.length);
sockets.forEach(function (s) {
s.send(data);
});
}
server.on('upgrade', function(request, socket, body) {
if (WebSocket.isWebSocket(request)) {
var ws = new WebSocket(request, socket, body);
// Keep track of new WebSocket connection
connections.push(ws);
ws.on('message', function(event) {
console.log('New message', event.data);
broadcastMessageFrom(ws, event.data);
});
// Remove from connections
ws.on('close', function(event) {
console.log('close', event.code, event.reason);
connections = without(connections, ws);
ws = null;
});
}
});
console.log('Listening on port', config.port);
server.listen(config.port);
}
|
Add consistancy to port logging
|
Add consistancy to port logging
|
JavaScript
|
apache-2.0
|
mediascape/euromeme,mediascape/euromeme,mediascape/euromeme,mediascape/euromeme,mediascape/euromeme,mediascape/euromeme
|
3f32dd2bede0cb23f5453891d7b92a83e90c2d71
|
routes/apiRoot.js
|
routes/apiRoot.js
|
var contentType = require('../middleware/contentType'),
config = require('../config');
function apiRoot(req, res) {
var root = config.get('apiEndpoint');
var answer = {
motd: 'Welcome to the NGP VAN OSDI Service!',
max_pagesize: 200,
vendor_name: 'NGP VAN, Inc.',
product_name: 'VAN',
osdi_version: '1.0',
_links: {
self: {
href: root,
title: 'NGP VAN OSDI Service Entry Point'
},
'osdi:tags': {
'href': root + 'tags',
'title': 'The collection of tags in the system'
},
'osdi:questions': {
'href': root + 'questions',
'title': 'The collection of questions in the system'
},
'osdi:people': {
'href': root + 'people',
'title': 'The collection of people in the system'
}
}
};
return res.status(200).send(answer);
}
module.exports = function (app) {
app.get('/api/v1/', contentType, apiRoot);
};
|
var contentType = require('../middleware/contentType'),
config = require('../config');
function apiRoot(req, res) {
var root = config.get('apiEndpoint');
var answer = {
motd: 'Welcome to the NGP VAN OSDI Service!',
max_pagesize: 200,
vendor_name: 'NGP VAN, Inc.',
product_name: 'VAN',
osdi_version: '1.0',
_links: {
self: {
href: root,
title: 'NGP VAN OSDI Service Entry Point'
},
'osdi:tags': {
'href': root + 'tags',
'title': 'The collection of tags in the system'
},
'osdi:questions': {
'href': root + 'questions',
'title': 'The collection of questions in the system'
},
"osdi:person_signup_helper": {
"href": root + 'people/person_signup',
"title": "The person signup helper for the system"
}
}
};
return res.status(200).send(answer);
}
module.exports = function (app) {
app.get('/api/v1/', contentType, apiRoot);
};
|
Correct AEP resource for person signup helper
|
Correct AEP resource for person signup helper
Signed-off-by: shaisachs <[email protected]>
|
JavaScript
|
apache-2.0
|
NGPVAN/osdi-service,joshco/osdi-service
|
929e85200848bb9974eb480efa9945c6af3250f4
|
resource-router-middleware.js
|
resource-router-middleware.js
|
var Router = require('express').Router;
var keyed = ['get', 'read', 'put', 'patch', 'update', 'del', 'delete'],
map = { index:'get', list:'get', read:'get', create:'post', update:'put', modify:'patch' };
module.exports = function ResourceRouter(route) {
route.mergeParams = route.mergeParams ? true : false;
var router = Router({mergeParams: route.mergeParams}),
key, fn, url;
if (route.middleware) router.use(route.middleware);
if (route.load) {
router.param(route.id, function(req, res, next, id) {
route.load(req, id, function(err, data) {
if (err) return res.status(404).send(err);
req[route.id] = data;
next();
});
});
}
for (key in route) {
fn = map[key] || key;
if (typeof router[fn]==='function') {
url = ~keyed.indexOf(key) ? ('/:'+route.id) : '/';
router[fn](url, route[key]);
}
}
return router;
};
module.exports.keyed = keyed;
|
var Router = require('express').Router;
var keyed = ['get', 'read', 'put', 'update', 'patch', 'modify', 'del', 'delete'],
map = { index:'get', list:'get', read:'get', create:'post', update:'put', modify:'patch' };
module.exports = function ResourceRouter(route) {
route.mergeParams = route.mergeParams ? true : false;
var router = Router({mergeParams: route.mergeParams}),
key, fn, url;
if (route.middleware) router.use(route.middleware);
if (route.load) {
router.param(route.id, function(req, res, next, id) {
route.load(req, id, function(err, data) {
if (err) return res.status(404).send(err);
req[route.id] = data;
next();
});
});
}
for (key in route) {
fn = map[key] || key;
if (typeof router[fn]==='function') {
url = ~keyed.indexOf(key) ? ('/:'+route.id) : '/';
router[fn](url, route[key]);
}
}
return router;
};
module.exports.keyed = keyed;
|
Add modify to keyed methods to enable patch with id
|
Add modify to keyed methods to enable patch with id
|
JavaScript
|
bsd-3-clause
|
developit/resource-router-middleware
|
4383d7d3f566e33e5d4dc86e64fb1539ddad1642
|
src/compressor.js
|
src/compressor.js
|
'use strict';
var es = require('event-stream'),
path = require('path'),
zlib = require('zlib');
var compressibles = [
'.js',
'.json',
'.css',
'.html'
];
function isCompressibleFile( file ) {
var ext = path.extname( file.path ).toLowerCase();
return ( compressibles.indexOf( ext ) > -1 );
}
module.exports = function() {
return es.map( function( file, cb ) {
if( !isCompressibleFile( file ) ) {
cb( null, file );
return;
}
zlib.gzip( file.contents, function( err, result ) {
if( err ) {
cb( err, null );
return;
}
file.path += '.gz';
file.contents = result;
cb( null, file );
} );
} );
};
module.exports._isCompressibleFile = isCompressibleFile;
|
'use strict';
var es = require('event-stream'),
path = require('path'),
zlib = require('zlib');
var compressibles = [
'.js',
'.css',
'.html'
];
function isCompressibleFile( file ) {
var ext = path.extname( file.path ).toLowerCase();
return ( compressibles.indexOf( ext ) > -1 );
}
module.exports = function() {
return es.map( function( file, cb ) {
if( !isCompressibleFile( file ) ) {
cb( null, file );
return;
}
zlib.gzip( file.contents, function( err, result ) {
if( err ) {
cb( err, null );
return;
}
file.path += '.gz';
file.contents = result;
cb( null, file );
} );
} );
};
module.exports._isCompressibleFile = isCompressibleFile;
|
Revert "adding JSON to the list of extensions that should be compressed"
|
Revert "adding JSON to the list of extensions that should be compressed"
This reverts commit c90513519febf8feeea78b06da6a467bb1085948.
|
JavaScript
|
apache-2.0
|
Brightspace/gulp-frau-publisher,Brightspace/gulp-frau-publisher,Brightspace/frau-publisher,Brightspace/frau-publisher
|
fbf98e6125a702a63857688cfa07fefa6791a909
|
src/stages/main/patchers/SoakedMemberAccessOpPatcher.js
|
src/stages/main/patchers/SoakedMemberAccessOpPatcher.js
|
import NodePatcher from './../../../patchers/NodePatcher.js';
export default class SoakedMemberAccessOpPatcher extends NodePatcher {
patchAsExpression() {
}
patchAsStatement() {
this.patchAsExpression();
}
}
|
import NodePatcher from './../../../patchers/NodePatcher.js';
export default class SoakedMemberAccessOpPatcher extends NodePatcher {
patchAsExpression() {
throw this.error('cannot patch soaked member access (e.g. `a?.b`) yet');
}
}
|
Throw when encountering a SoakedMemberAccessOp.
|
Throw when encountering a SoakedMemberAccessOp.
|
JavaScript
|
mit
|
decaffeinate/decaffeinate,alangpierce/decaffeinate,decaffeinate/decaffeinate,eventualbuddha/decaffeinate,alangpierce/decaffeinate,eventualbuddha/decaffeinate,alangpierce/decaffeinate
|
666e5e1efa16941ac7ded51444b566a0d5faedd1
|
move-plugins/moveplugins.js
|
move-plugins/moveplugins.js
|
module.exports.movePlugins = function (src, dest) {
var exec = require('child_process').exec
console.log(`Copying ${src} to ${dest}`)
exec(`rm -rf ${dest}${src}`, function (error) {
if (error) {
console.error(`exec error: ${error}`)
} else {
exec(`cp -r ${src} ${dest}`, function (error, stdout, stderr) {
if (error) {
console.error(`exec error: ${error}`)
}
})
}
})
}
|
module.exports.movePlugins = function (src, dest) {
var exec = require('child_process').exec
exec(`rm ${dest}${src} -rf`, function (error) {
if (error) console.error(`exec error: ${error}`)
exec(`cp -r ${src} ${dest}`, function (error, stdout, stderr) {
if (error) console.error(`exec error: ${error}`)
})
})
}
|
Revert "fixed possible bug & Mac OSX compatibility issue with rm"
|
Revert "fixed possible bug & Mac OSX compatibility issue with rm"
This reverts commit b4ed13e1cd70025d4b8bb4b29e98334b00bfdbed.
|
JavaScript
|
mit
|
Lamassau/PiTrol,Lamassau/PiTrol,AlhasanIQ/PiTrol,fadeenk/PiTrol,fadeenk/PiTrol,AlhasanIQ/PiTrol
|
2a7e347e4f2f08faf84ce745ae8e611ced216421
|
webapp/src/main/frontend/app/scripts/components/doctorProfile.js
|
webapp/src/main/frontend/app/scripts/components/doctorProfile.js
|
'use strict';
define(['ChoPidoTurnos'], function(ChoPidoTurnos) {
function DoctorProfileCtrl(doctorsService) {
return {
'$onInit': function () {
var _this = this;
doctorsService
.getUserRating(this.doctor.id)
.then(function (result) {
_this.userRating = result.data.value;
});
doctorsService
.getRatingSummary(this.doctor.id)
.then(function (result) {
var data = result.data;
_this.ratingAverage = Math.round(data.average);
_this.ratingSummary = data.valuesCount;
});
},
onDoctorRated: function (ev) {
doctorsService
.rate(this.doctor.id, ev.rating)
.then(function (result) {
// TODO
});
}
};
}
DoctorProfileCtrl.$inject = ['doctorsService'];
ChoPidoTurnos
.component('doctorProfile', {
bindings: {
doctor: '<'
},
controller: DoctorProfileCtrl,
templateUrl: 'views/doctorProfile.html'
});
});
|
'use strict';
define(['ChoPidoTurnos'], function(ChoPidoTurnos) {
function DoctorProfileCtrl(doctorsService, sessionService) {
return {
'$onInit': function () {
var _this = this;
if (sessionService.getLoggedUser()) {
doctorsService
.getUserRating(this.doctor.id)
.then(function (result) {
_this.userRating = result.data.value;
});
}
doctorsService
.getRatingSummary(this.doctor.id)
.then(function (result) {
var data = result.data;
_this.ratingAverage = Math.round(data.average);
_this.ratingSummary = data.valuesCount;
});
},
onDoctorRated: function (ev) {
doctorsService
.rate(this.doctor.id, ev.rating)
.then(function (result) {
// TODO
});
}
};
}
DoctorProfileCtrl.$inject = ['doctorsService', 'sessionService'];
ChoPidoTurnos
.component('doctorProfile', {
bindings: {
doctor: '<'
},
controller: DoctorProfileCtrl,
templateUrl: 'views/doctorProfile.html'
});
});
|
Remove failing request when user is not logged in
|
Remove failing request when user is not logged in
|
JavaScript
|
mit
|
jsuarezb/paw-2016-4,jsuarezb/paw-2016-4,jsuarezb/paw-2016-4,jsuarezb/paw-2016-4
|
eaf69c1a63c41db025a65d87e104390deb6db591
|
components/CopyButton.js
|
components/CopyButton.js
|
import React from 'react';
import ClipboardJS from 'clipboard';
export default class CopyButton extends React.PureComponent {
constructor(props) {
super(props);
this.btnRef = React.createRef();
this.clipboardRef = React.createRef();
}
static defaultProps = {
content: '',
};
componentDidMount() {
this.clipboardRef.current = new ClipboardJS(this.btnRef.current, {
text: () => this.props.content,
});
}
render() {
return (
<button
ref={this.btnRef}
key="copy"
onClick={() => {}}
className="btn-copy"
data-clipboard-target="#testCopyTarget"
>
複製到剪貼簿
<style jsx>{`
.btn-copy {
margin-left: 10px;
}
`}</style>
</button>
);
}
}
|
import React from 'react';
import ClipboardJS from 'clipboard';
export default class CopyButton extends React.PureComponent {
constructor(props) {
super(props);
this.btnRef = React.createRef();
this.clipboardRef = React.createRef();
}
static defaultProps = {
content: '',
};
componentDidMount() {
this.clipboardRef.current = new ClipboardJS(this.btnRef.current, {
text: () => this.props.content,
});
}
render() {
return (
<button
ref={this.btnRef}
key="copy"
onClick={() => {}}
className="btn-copy"
>
複製到剪貼簿
<style jsx>{`
.btn-copy {
margin-left: 10px;
}
`}</style>
</button>
);
}
}
|
Solve 'invalid target element' error
|
Solve 'invalid target element' error
|
JavaScript
|
mit
|
cofacts/rumors-site,cofacts/rumors-site
|
f0d2f99dbdd764915efd138361f815e86a3d2210
|
app/assets/javascripts/angular/services/annotation_refresher.js
|
app/assets/javascripts/angular/services/annotation_refresher.js
|
angular.module("Prometheus.services").factory('AnnotationRefresher', ["$http", function($http) {
return function(graph, scope) {
var tags = graph.tags.map(function(e) {
if (e.name) {
return e.name.split(",").map(function(s) { return s.trim(); });
} else {
return "";
}
})
if (tags.length) {
var range = Prometheus.Graph.parseDuration(graph.range);
var until = Math.floor(graph.endTime || Date.now()) / 1000;
tags.forEach(function(t) {
$http.get('/annotations', {
params: {
tags: t.join(","),
until: until,
range: range
}
})
.then(function(payload) {
scope.$broadcast('annotateGraph', payload.data.posts);
}, function(response) {
scope.errorMessages.push("Error " + response.status + ": Error occurred fetching annotations.");
});
});
}
};
}]);
|
angular.module("Prometheus.services").factory('AnnotationRefresher', ["$http", function($http) {
return function(graph, scope) {
var tags = graph.tags.map(function(e) {
if (e.name) {
return e.name.split(",").map(function(s) { return s.trim(); });
} else {
return "";
}
})
if (tags.length) {
var range = Prometheus.Graph.parseDuration(graph.range);
var until = Math.floor(graph.endTime || Date.now()) / 1000;
tags.forEach(function(t) {
$http.get('/annotations', {
params: {
'tags[]': t,
until: until,
range: range
}
})
.then(function(payload) {
scope.$broadcast('annotateGraph', payload.data.posts);
}, function(response) {
scope.errorMessages.push("Error " + response.status + ": Error occurred fetching annotations.");
});
});
}
};
}]);
|
Send annotation tags as array.
|
Send annotation tags as array.
|
JavaScript
|
apache-2.0
|
alonpeer/promdash,lborguetti/promdash,jonnenauha/promdash,lborguetti/promdash,lborguetti/promdash,jonnenauha/promdash,jmptrader/promdash,alonpeer/promdash,thooams/promdash,jonnenauha/promdash,prometheus/promdash,prometheus/promdash,juliusv/promdash,juliusv/promdash,jmptrader/promdash,juliusv/promdash,jmptrader/promdash,jonnenauha/promdash,thooams/promdash,alonpeer/promdash,lborguetti/promdash,thooams/promdash,thooams/promdash,prometheus/promdash,juliusv/promdash,alonpeer/promdash,jmptrader/promdash,prometheus/promdash
|
1896a56db306f7cadfc004373839887ce6b3c5cd
|
app/assets/javascripts/angular/services/annotation_refresher.js
|
app/assets/javascripts/angular/services/annotation_refresher.js
|
angular.module("Prometheus.services").factory('AnnotationRefresher', ["$http", function($http) {
return function(graph, scope) {
var tags = graph.tags.map(function(e) {
if (e.name) {
return e.name.split(",").map(function(s) { return s.trim(); });
} else {
return "";
}
})
if (tags.length) {
var range = Prometheus.Graph.parseDuration(graph.range);
var until = Math.floor(graph.endTime || Date.now()) / 1000;
tags.forEach(function(t) {
$http.get('/annotations', {
params: {
'tags[]': t,
until: until,
range: range
}
})
.then(function(payload) {
scope.$broadcast('annotateGraph', payload.data.posts);
}, function(response) {
scope.errorMessages.push("Error " + response.status + ": Error occurred fetching annotations.");
});
});
}
};
}]);
|
angular.module("Prometheus.services").factory('AnnotationRefresher', ["$http", "VariableInterpolator", function($http, VariableInterpolator) {
return function(graph, scope) {
var tags = graph.tags.map(function(e) {
if (e.name) {
var n = VariableInterpolator(e.name, scope.vars);
return n.split(",").map(function(s) { return s.trim(); });
} else {
return "";
}
})
if (tags.length) {
var range = Prometheus.Graph.parseDuration(graph.range);
var until = Math.floor(graph.endTime || Date.now()) / 1000;
tags.forEach(function(t) {
$http.get('/annotations', {
params: {
'tags[]': t,
until: until,
range: range
}
})
.then(function(payload) {
scope.$broadcast('annotateGraph', payload.data.posts);
}, function(response) {
scope.errorMessages.push("Error " + response.status + ": Error occurred fetching annotations.");
});
});
}
};
}]);
|
Allow for tags to be interpolated variables.
|
Allow for tags to be interpolated variables.
|
JavaScript
|
apache-2.0
|
prometheus/promdash,prometheus/promdash,thooams/promdash,lborguetti/promdash,jmptrader/promdash,juliusv/promdash,jonnenauha/promdash,lborguetti/promdash,lborguetti/promdash,jmptrader/promdash,prometheus/promdash,jmptrader/promdash,juliusv/promdash,juliusv/promdash,thooams/promdash,jonnenauha/promdash,lborguetti/promdash,jmptrader/promdash,alonpeer/promdash,juliusv/promdash,alonpeer/promdash,alonpeer/promdash,thooams/promdash,jonnenauha/promdash,thooams/promdash,jonnenauha/promdash,prometheus/promdash,alonpeer/promdash
|
ce79d7a652564fed3b86000e9c295f00f28e5223
|
examples/myShellExtension.js
|
examples/myShellExtension.js
|
'use strict';
exports.register = function (callback) {
var commands = [{
name : 'hello',
desc : 'print Hello, John',
options : {
wizard : false,
params : {
required: 'name',
optional: 'etc...'
}
},
handler : function (callback, args) {
console.log ('Hello, ' + args.join (' '));
callback ();
}
}, {
name : 'wizard',
desc : 'begins a wizard',
options : {
wizard : true
},
handler : function (callback, args) {
var wizard = [{
/* Inquirer definition... */
type: 'input',
name: 'zog',
message: 'tell zog'
}];
callback (wizard, function (answers) {
/* stuff on answers */
if (answers.zog === 'zog') {
console.log ('zog zog');
} else {
console.log ('lokthar?');
}
/*
* You can return false if you must provide several wizard with only
* one call to this command handler.
* You can call callback () without argument in order to return to the
* prompt instead of returning true.
*/
return true;
});
}
}];
callback (null, commands);
};
exports.unregister = function (callback) {
/* internal stuff */
callback ();
};
|
'use strict';
var cmd = {};
cmd.hello = function (callback, args) {
console.log ('Hello, ' + args.join (' '));
callback ();
};
cmd.wizard = function (callback) {
var wizard = [{
/* Inquirer definition... */
type: 'input',
name: 'zog',
message: 'tell zog'
}];
callback (wizard, function (answers) {
/* stuff on answers */
if (answers.zog === 'zog') {
console.log ('zog zog');
} else {
console.log ('lokthar?');
}
/*
* You can return false if you must provide several wizard with only
* one call to this command handler.
* You can call callback () without argument in order to return to the
* prompt instead of returning true.
*/
return true;
});
};
exports.register = function (callback) {
var commands = [{
name : 'hello',
desc : 'print Hello, John',
options : {
wizard : false,
params : {
required: 'name',
optional: 'etc...'
}
},
handler : cmd.hello
}, {
name : 'wizard',
desc : 'begins a wizard',
options : {
wizard : true
},
handler : cmd.wizard
}];
callback (null, commands);
};
exports.unregister = function (callback) {
/* internal stuff */
callback ();
};
|
Split the register function for the readability.
|
Split the register function for the readability.
|
JavaScript
|
mit
|
Xcraft-Inc/shellcraft.js
|
efda627489ccfa3bc6e3f64a40623da2d62ee316
|
gatsby-browser.js
|
gatsby-browser.js
|
exports.onClientEntry = () => {
(() => {
function OptanonWrapper() { } // eslint-disable-line no-unused-vars
})();
};
|
exports.onClientEntry = () => {
(() => {
function OptanonWrapper() {} // eslint-disable-line no-unused-vars
})();
};
// Always start at the top of the page on a route change.
exports.onInitialClientRender = () => {
if (!window.location.hash) {
window.scrollTo(0, 0);
} else {
window.location = window.location.hash;
}
};
|
Add function to start at top of new page unless window.location has a hash
|
[MARKENG-156] Add function to start at top of new page unless window.location has a hash
|
JavaScript
|
apache-2.0
|
postmanlabs/postman-docs,postmanlabs/postman-docs
|
65a50b9a92299366e37a412d99b1b31a4f15b3d9
|
lib/cape/mixins/propagator_methods.js
|
lib/cape/mixins/propagator_methods.js
|
'use strict';
var PropagatorMethods = {
attach: function(component) {
var target = component;
for (var i = 0, len = this._.components.length; i < len; i++) {
if (this._.components[i] === component) return;
}
this._.components.push(component);
},
detach: function(component) {
for (var i = 0, len = this._.components.length; i < len; i++) {
if (this._.components[i] === component) {
this._.components.splice(i, 1);
break;
}
}
},
propagate: function() {
for (var i = this._.components.length; i--;)
this._.components[i].refresh();
}
}
module.exports = PropagatorMethods;
|
'use strict'
let PropagatorMethods = {
attach: function(component) {
let target = component
for (let i = 0, len = this._.components.length; i < len; i++) {
if (this._.components[i] === component) return
}
this._.components.push(component)
},
detach: function(component) {
for (let i = 0, len = this._.components.length; i < len; i++) {
if (this._.components[i] === component) {
this._.components.splice(i, 1)
break
}
}
},
propagate: function() {
for (let i = this._.components.length; i--;)
this._.components[i].refresh()
}
}
module.exports = PropagatorMethods
|
Rewrite PropagatorMethods module with ES6 syntax
|
Rewrite PropagatorMethods module with ES6 syntax
|
JavaScript
|
mit
|
capejs/capejs,capejs/capejs
|
ced84f283761f38156960f2d8e001ba6f3cd2b08
|
src/hook/index.js
|
src/hook/index.js
|
import { Base } from 'yeoman-generator';
import generatorArguments from './arguments';
import generatorOptions from './options';
import generatorSteps from './steps';
export default class HookGenerator 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 HookGenerator 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]));
this.description = 'Scaffold a custom hook in api/hooks';
}
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;
}
}
|
Add description to hook generator
|
Add description to hook generator
|
JavaScript
|
mit
|
tnunes/generator-trails,IncoCode/generator-sails-rest-api,ghaiklor/generator-sails-rest-api,jaumard/generator-trails,konstantinzolotarev/generator-trails,italoag/generator-sails-rest-api,italoag/generator-sails-rest-api,ghaiklor/generator-sails-rest-api
|
88135630eeee214e6a6777b325970084305a3028
|
src/i18n/index.js
|
src/i18n/index.js
|
/**
* You can customize the initial state of the module from the editor initialization
* ```js
* const editor = grapesjs.init({
* i18n: {
* locale: 'en',
* messages: {
* en: {
* hello: 'Hello',
* },
* ...
* }
* }
* })
* ```
*
* Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance
*
* ```js
* const i18n = editor.I18n;
* ```
*
* @module I18n
*/
import messages from './messages';
export default () => {
let em;
let config;
const { language } = window.navigator || {};
const localeDef = language ? language.split('-')[0] : 'en';
const configDef = {
locale: localeDef,
localeFallback: 'en',
counter: 'n',
messages
};
return {
name: 'I18n',
/**
* Get module configurations
* @returns {Object} Configuration object
*/
getConfig() {
return config;
},
/**
* Initialize module
* @param {Object} config Configurations
* @private
*/
init(opts = {}) {
config = { ...configDef, ...opts };
em = opts.em;
this.em = em;
return this;
}
};
};
|
/**
* You can customize the initial state of the module from the editor initialization
* ```js
* const editor = grapesjs.init({
* i18n: {
* locale: 'en',
* messages: {
* en: {
* hello: 'Hello',
* },
* ...
* }
* }
* })
* ```
*
* Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance
*
* ```js
* const i18n = editor.I18n;
* ```
*
* @module I18n
*/
import messages from './messages';
export default () => {
const { language } = window.navigator || {};
const localeDef = language ? language.split('-')[0] : 'en';
const config = {
locale: localeDef,
localeFallback: 'en',
counter: 'n',
messages
};
return {
name: 'I18n',
config,
/**
* Get module configurations
* @returns {Object} Configuration object
*/
getConfig() {
return this.config;
},
/**
* Update current locale
* @param {String} locale Locale value
* @returns {this}
* @example
* i18n.setLocale('it');
*/
setLocale(locale) {
this.config.locale = locale;
return this;
},
/**
* Get current locale
* @returns {String} Current locale value
*/
getLocale() {
return this.config.locale;
},
/**
* Initialize module
* @param {Object} config Configurations
* @private
*/
init(opts = {}) {
this.em = opts.em;
return this;
}
};
};
|
Add locales methods to i18n
|
Add locales methods to i18n
|
JavaScript
|
bsd-3-clause
|
artf/grapesjs,QuorumDMS/grapesjs,artf/grapesjs,artf/grapesjs,QuorumDMS/grapesjs
|
9963a7f7e6f161fa6b9b0085ae3f48df33c2fb20
|
package.js
|
package.js
|
var path = Npm.require("path");
Package.describe({
summary: "JavaScript.next-to-JavaScript-of-today compiler",
version: "1.0.3+0.0.42"
});
Package._transitional_registerBuildPlugin({
name: "compileHarmony",
use: [],
sources: [
"plugin/compile-harmony.js"
],
npmDependencies: {
"traceur": "0.0.42"
}
});
Package.on_use(function (api) {
// The location of this runtime file is not supposed to change:
// http://git.io/B2s0Tg
var dir = ".npm/plugin/compileHarmony/node_modules/traceur/bin/";
api.add_files(path.join(dir, "traceur-runtime.js"));
// Export `module.exports` and `exports` down the package pipeline
api.use('exports');
api.export(['module', 'exports']);
});
Package.on_test(function (api) {
api.use(['harmony', 'tinytest']);
api.add_files([
'harmony_test_setup.js',
'harmony_tests.js',
'tests/harmony_test_setup.next.js',
'tests/harmony_tests.next.js'
], ["client", "server"]);
});
|
var path = Npm.require("path");
Package.describe({
summary: "JavaScript.next-to-JavaScript-of-today compiler",
version: "1.0.3+0.0.42"
});
Package._transitional_registerBuildPlugin({
name: "compileHarmony",
use: [],
sources: [
"plugin/compile-harmony.js"
],
npmDependencies: {
"traceur": "0.0.42"
}
});
Package.on_use(function (api) {
// The location of this runtime file is not supposed to change:
// http://git.io/B2s0Tg
var dir = ".npm/plugin/compileHarmony/node_modules/traceur/bin/";
api.add_files(path.join(dir, "traceur-runtime.js"));
// Export `module.exports` and `exports` down the package pipeline
api.imply('exports');
});
Package.on_test(function (api) {
api.use(['harmony', 'tinytest']);
api.add_files([
'harmony_test_setup.js',
'harmony_tests.js',
'tests/harmony_test_setup.next.js',
'tests/harmony_tests.next.js'
], ["client", "server"]);
});
|
Use `imply` instead of `use` and `export` together
|
Use `imply` instead of `use` and `export` together
This commit uses the `api.imply` shorthand to use a package and export its exports.
|
JavaScript
|
mit
|
mquandalle/meteor-harmony
|
92e4e867c02ab0d55ad54539568ac29692f01733
|
src/index.node.js
|
src/index.node.js
|
/* eslint-env node */
const Canvas = require('canvas');
const fs = require('fs');
const { Image } = Canvas;
/**
* Create a new canvas object with height and width
* set to the given values.
*
* @param width {number} The width of the canvas.
* @param height {number} The height of the canvas.
*
* @return {Canvas} A canvas object with
* height and width set to the given values.
*/
function createCanvas(width, height) {
return new Canvas(width, height);
}
/**
* Load the image given by the file path, returning
* a promise to the image represented by the given path.
*
* @parm path {string} The path to the image.
*
* @return {Image} An image element referring to
* the given path.
*/
function loadImage(path) {
return new Promise((resolve, reject) => {
fs.readFile(path, (err, data) => {
if (err) {
return reject(err);
}
const image = new Image();
image.src = data;
return resolve(image);
});
});
}
module.exports = {
createCanvas,
loadImage,
};
|
/* eslint-env node */
const Canvas = require('canvas');
const fs = require('fs');
const { Image } = Canvas;
/**
* Create a new canvas object with height and width
* set to the given values.
*
* @param width {number} The width of the canvas.
* @param height {number} The height of the canvas.
*
* @return {Canvas} A canvas object with
* height and width set to the given values.
*/
function createCanvas(width, height) {
return new Canvas(width, height);
}
/**
* Load the image given by the file path, returning
* a promise to the image represented by the given path.
*
* @parm path {string} The path to the image.
*
* @return {Image} An image element referring to
* the given path.
*/
function loadImage(path) {
return new Promise((resolve, reject) => {
fs.readFile(path, (err, data) => {
if (err) {
reject(err);
return;
}
const image = new Image();
image.onload = () => resolve(image);
image.onerror = err => reject(err);
image.src = data;
return resolve(image);
});
});
}
module.exports = {
createCanvas,
loadImage,
};
|
Use image onload and onerror
|
Use image onload and onerror
|
JavaScript
|
mit
|
bschlenk/canvas-everywhere
|
053ce99dec181fa886818c69fe80507257dffd56
|
src/Views/PickList.js
|
src/Views/PickList.js
|
/*
* Copyright (c) 1997-2013, SalesLogix, NA., LLC. All rights reserved.
*/
/**
* @class Mobile.SalesLogix.Views.PickList
*
*
* @extends Sage.Platform.Mobile.List
*
*/
define('Mobile/SalesLogix/Views/PickList', [
'dojo/_base/declare',
'dojo/string',
'Sage/Platform/Mobile/List'
], function(
declare,
string,
List
) {
return declare('Mobile.SalesLogix.Views.PickList', [List], {
//Templates
itemTemplate: new Simplate([
'<h3>{%: $.text %}</h3>'
]),
//View Properties
id: 'pick_list',
expose: false,
resourceKind: 'picklists',
resourceProperty: 'items',
contractName: 'system',
activateEntry: function(params) {
if (this.options.keyProperty === 'text' && !this.options.singleSelect) {
params.key = params.descriptor;
}
this.inherited(arguments);
},
show: function(options) {
this.set('title', options && options.title || this.title);
this.inherited(arguments);
},
formatSearchQuery: function(searchQuery) {
return string.substitute('upper(text) like "${0}%"', [this.escapeSearchQuery(searchQuery.toUpperCase())]);
}
});
});
|
/*
* Copyright (c) 1997-2013, SalesLogix, NA., LLC. All rights reserved.
*/
/**
* @class Mobile.SalesLogix.Views.PickList
*
*
* @extends Sage.Platform.Mobile.List
*
*/
define('Mobile/SalesLogix/Views/PickList', [
'dojo/_base/declare',
'dojo/string',
'Sage/Platform/Mobile/List'
], function(
declare,
string,
List
) {
return declare('Mobile.SalesLogix.Views.PickList', [List], {
//Templates
itemTemplate: new Simplate([
'<h3>{%: $.text %}</h3>'
]),
//View Properties
id: 'pick_list',
expose: false,
resourceKind: 'picklists',
resourceProperty: 'items',
contractName: 'system',
activateEntry: function(params) {
if (this.options.keyProperty === 'text' && !this.options.singleSelect) {
params.key = params.descriptor;
}
this.inherited(arguments);
},
show: function(options) {
this.set('title', options && options.title || this.title);
if (options.keyProperty) {
this.idProperty = options.keyProperty;
}
if (options.textProperty) {
this.labelProperty = options.textProperty;
}
this.inherited(arguments);
},
formatSearchQuery: function(searchQuery) {
return string.substitute('upper(text) like "${0}%"', [this.escapeSearchQuery(searchQuery.toUpperCase())]);
}
});
});
|
Update the idProperty and labelProperty of the store properly based on what the picklist is using.
|
Update the idProperty and labelProperty of the store properly based on what the picklist is using.
|
JavaScript
|
apache-2.0
|
Saleslogix/argos-saleslogix,Saleslogix/argos-saleslogix,Saleslogix/argos-saleslogix,Saleslogix/argos-saleslogix
|
433541eee8c71f67265240dcd35323cfb0790e2b
|
src/about.js
|
src/about.js
|
import h from 'hyperscript';
import fetch from 'unfetch';
import audio from './audio';
import aboutSrc from './content/about.md';
let visible = false;
let fetched = false;
const toggle = () => {
visible = !visible;
document.body.classList[visible ? 'remove' : 'add']('mod-overflow-hidden');
about.classList[visible ? 'remove' : 'add']('mod-hidden');
audio[visible ? 'pause' : 'play']();
if (!fetched) {
fetched = true;
fetch(aboutSrc)
.then(response => response.text())
.then(data => {
about.innerHTML = data;
about.appendChild(closeButton);
});
}
};
const about = h('div.about.mod-hidden')
const closeButton = h('div.about-close-button', { onclick: toggle }, '×');
document.body.appendChild(about);
export default { toggle };
|
import h from 'hyperscript';
import fetch from 'unfetch';
import audio from './audio';
import aboutSrc from './content/about.md';
let visible = false;
let fetched = false;
const toggle = async () => {
visible = !visible;
document.body.classList[visible ? 'remove' : 'add']('mod-overflow-hidden');
about.classList[visible ? 'remove' : 'add']('mod-hidden');
audio[visible ? 'pause' : 'play']();
if (!fetched) {
fetched = true;
const response = await fetch(aboutSrc);
const data = await response.text();
about.innerHTML = data;
about.appendChild(closeButton);
}
};
const about = h('div.about.mod-hidden');
const closeButton = h('div.about-close-button', { onclick: toggle }, '×');
document.body.appendChild(about);
export default { toggle };
|
Switch markdown loading to fetch/async/await
|
Switch markdown loading to fetch/async/await
|
JavaScript
|
apache-2.0
|
puckey/dance-tonite,puckey/dance-tonite
|
eb59950038a363baca64593379739fcb4eeea22f
|
src/lib/server.js
|
src/lib/server.js
|
import express from 'express';
import path from 'path';
import bodyParser from 'body-parser';
import api from './api';
let server = null;
function start(port) {
return new Promise((resolve, reject) => {
if (server !== null) {
reject(new Error('The server is already running.'));
}
let app = express();
app.use(express.static(path.join(__dirname, '../public')));
app.use(bodyParser.json({ limit: '1MB' }));
app.use('/api', api);
server = app.listen(port, () => {
resolve();
});
});
}
function stop() {
return new Promise((resolve, reject) => {
if (server === null) {
reject(new Error('The server is not running.'));
}
server.close(() => {
server = null;
resolve();
});
});
}
export default {
start,
stop
};
|
import express from 'express';
import path from 'path';
import bodyParser from 'body-parser';
import api from './api';
let server = null;
function start(port) {
return new Promise((resolve, reject) => {
if (server !== null) {
reject(new Error('The server is already running.'));
}
let app = express();
app.use(express.static(path.join(__dirname, '../public')));
app.use(bodyParser.json({ limit: '1.5MB' }));
app.use('/api', api);
server = app.listen(port, () => {
resolve();
});
});
}
function stop() {
return new Promise((resolve, reject) => {
if (server === null) {
reject(new Error('The server is not running.'));
}
server.close(() => {
server = null;
resolve();
});
});
}
export default {
start,
stop
};
|
Increase payload limit to 1.5MB
|
Increase payload limit to 1.5MB
When editing a model, this allow the user to upload a 1MB file, rather
than something like a 925.3kB file, along with about 500kB of
description text.
|
JavaScript
|
unlicense
|
TheFourFifths/consus,TheFourFifths/consus
|
6dbe686652f6e642000b183a4063d68f27c8b6e0
|
karma.conf.js
|
karma.conf.js
|
module.exports = (config) => {
config.set({
frameworks: ['mocha', 'karma-typescript'],
browsers: ['ChromeHeadless'],
singleRun: true,
concurrency: Infinity,
reporters: ['mocha'],
port: 9876,
colors: true,
logLevel: config.LOG_WARN,
files: [
'src/*.ts',
'test/*.ts',
],
preprocessors: {
'**/*.ts': ['karma-typescript'],
},
karmaTypescriptConfig: {
compilerOptions: {
target: 'es6',
baseUrl: __dirname,
},
},
})
};
|
module.exports = (config) => {
config.set({
frameworks: ['mocha', 'karma-typescript'],
browsers: ['ChromeHeadless'],
singleRun: true,
concurrency: Infinity,
reporters: ['mocha'],
port: 9876,
colors: true,
logLevel: config.LOG_WARN,
files: [
'src/*.ts',
'test/*.ts',
{
pattern: 'test/*.html',
watched: false,
included: false,
served: true,
},
],
preprocessors: {
'**/*.ts': ['karma-typescript'],
},
karmaTypescriptConfig: {
compilerOptions: {
target: 'es6',
baseUrl: __dirname,
},
},
});
};
|
Add file rule for test template file
|
Add file rule for test template file
|
JavaScript
|
mit
|
marcoms/make-element,marcoms/make-element,marcoms/make-element
|
a7eef3262e571e51f2f8a0403dbfbd7b51b1946a
|
src/tools/courseraSampleToArray.js
|
src/tools/courseraSampleToArray.js
|
var http = require('http');
/*
* Convert from coursera sample format to javascript array.
* e.g :
*
* a.txt :
*
* 111
* 222
* 333
* 444
*
* converts to
*
* [111,222,333,444]
* */
var strToArray = function(str) {
return str.trim().split('\r\n').map(function (elStr) {
return parseInt(elStr);
})
}
function simpleHttpHandler(url, callback) {
http.get(url, function(response) {
var str = '';
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
callback( str )
});
});
}
exports.getNumberArray = function (url, callback) {
simpleHttpHandler(url, function (str) {
var numberArry = str.trim().split('\r\n').map(function (elStr) {
return parseInt(elStr);
})
callback(numberArry);
});
};
|
var http = require('http');
var courseraHttpHandler = function(url, processor, callback) {
http.get(url, function(response) {
var str = '';
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
var processedStr = str.trim().split('\r\n').map( processor );
callback( processedStr );
});
});
}
var strToInt = function (str) {
return parseInt(str);
}
/*
* Convert from coursera sample format to javascript array.
* e.g :
*
* a.txt :
*
* 111
* 222
* 333
* 444
*
* converts to
*
* [111,222,333,444]
* */
exports.getNumberArray = function (url, callback) {
courseraHttpHandler(url, strToInt, callback);
};
exports.getAdjacencylist = function (url, callback) {
courseraHttpHandler(url, function (str) {
return str.trim().split('\t').map( strToInt );
}, callback);
}
|
Refactor coursera tool. Add getAdjacencylist function.
|
Refactor coursera tool. Add getAdjacencylist function.
lzhoucs|G580|Win8|WebStorm9
|
JavaScript
|
apache-2.0
|
lzhoucs/cs-algorithms
|
b43e6f2a5fdbb355369d82a2c5ff65f5b0e42a23
|
webroot/rsrc/js/application/repository/repository-crossreference.js
|
webroot/rsrc/js/application/repository/repository-crossreference.js
|
/**
* @provides javelin-behavior-repository-crossreference
* @requires javelin-behavior
* javelin-dom
* javelin-uri
*/
JX.behavior('repository-crossreference', function(config) {
// NOTE: Pretty much everything in this file is a worst practice. We're
// constrained by the markup generated by the syntax highlighters.
var container = JX.$(config.container);
JX.DOM.alterClass(container, 'repository-crossreference', true);
JX.DOM.listen(
container,
'click',
'tag:span',
function(e) {
var target = e.getTarget();
var map = {nc : 'class', nf : 'function'};
if (JX.DOM.isNode(target, 'span') && (target.className in map)) {
var symbol = target.textContent || target.innerText;
var uri = JX.$U('/diffusion/symbol/' + symbol + '/');
uri.addQueryParams({
type : map[target.className],
lang : config.lang,
projects : config.projects.join(','),
jump : true
});
window.open(uri);
e.kill();
}
});
});
|
/**
* @provides javelin-behavior-repository-crossreference
* @requires javelin-behavior
* javelin-dom
* javelin-uri
*/
JX.behavior('repository-crossreference', function(config) {
// NOTE: Pretty much everything in this file is a worst practice. We're
// constrained by the markup generated by the syntax highlighters.
var container = JX.$(config.container);
JX.DOM.alterClass(container, 'repository-crossreference', true);
JX.DOM.listen(
container,
'click',
'tag:span',
function(e) {
var target = e.getTarget();
var map = {nc : 'class', nf : 'function'};
while (target !== document.body) {
if (JX.DOM.isNode(target, 'span') && (target.className in map)) {
var symbol = target.textContent || target.innerText;
var uri = JX.$U('/diffusion/symbol/' + symbol + '/');
uri.addQueryParams({
type : map[target.className],
lang : config.lang,
projects : config.projects.join(','),
jump : true
});
window.open(uri);
e.kill();
break;
}
target = target.parentNode;
}
});
});
|
Make symbol linking more lenient.
|
Make symbol linking more lenient.
Summary:
Sometimes a symbol has a nested <span> in it. Clicks on that
should count as clicks on the symbol. So keep looking for symbols among
the ancestors of the click target.
This is a silly method because I don't know if there's a more idiomatic
way to do it in Javelin.
Test Plan:
Open a Differential revision where part of a symbol is
highlighted. Click on the highlighted part. Symbol search opens.
Reviewers: epriestley
Reviewed By: epriestley
CC: aran, epriestley
Maniphest Tasks: T1577
Differential Revision: https://secure.phabricator.com/D3113
|
JavaScript
|
apache-2.0
|
parksangkil/phabricator,hach-que/unearth-phabricator,freebsd/phabricator,phacility/phabricator,dannysu/phabricator,wxstars/phabricator,schlaile/phabricator,apexstudios/phabricator,optimizely/phabricator,Soluis/phabricator,MicroWorldwide/phabricator,Drooids/phabricator,devurandom/phabricator,wikimedia/phabricator-phabricator,kanarip/phabricator,coursera/phabricator,kwoun1982/phabricator,freebsd/phabricator,wangjun/phabricator,eSpark/phabricator,huangjimmy/phabricator-1,eSpark/phabricator,benchling/phabricator,optimizely/phabricator,UNCC-OpenProjects/Phabricator,UNCC-OpenProjects/Phabricator,huaban/phabricator,devurandom/phabricator,ide/phabricator,shrimpma/phabricator,cjxgm/p.cjprods.org,vuamitom/phabricator,devurandom/phabricator,vuamitom/phabricator,Automatic/phabricator,zhihu/phabricator,gsinkovskiy/phabricator,devurandom/phabricator,hshackathons/phabricator-deprecated,Automatic/phabricator,kalbasit/phabricator,optimizely/phabricator,r4nt/phabricator,matthewrez/phabricator,benchling/phabricator,vinzent/phabricator,matthewrez/phabricator,hshackathons/phabricator-deprecated,wikimedia/phabricator-phabricator,ide/phabricator,huangjimmy/phabricator-1,christopher-johnson/phabricator,hach-que/phabricator,tanglu-org/tracker-phabricator,aik099/phabricator,wusuoyongxin/phabricator,librewiki/phabricator,parksangkil/phabricator,gsinkovskiy/phabricator,WuJiahu/phabricator,uhd-urz/phabricator,librewiki/phabricator,NigelGreenway/phabricator,Automatic/phabricator,folsom-labs/phabricator,Khan/phabricator,shl3807/phabricator,leolujuyi/phabricator,akkakks/phabricator,tanglu-org/tracker-phabricator,uhd-urz/phabricator,memsql/phabricator,huaban/phabricator,aswanderley/phabricator,Automattic/phabricator,jwdeitch/phabricator,a20012251/phabricator,wxstars/phabricator,optimizely/phabricator,kwoun1982/phabricator,wangjun/phabricator,hach-que/unearth-phabricator,coursera/phabricator,tanglu-org/tracker-phabricator,Drooids/phabricator,kanarip/phabricator,sharpwhisper/phabricator,ryancford/phabricator,Khan/phabricator,UNCC-OpenProjects/Phabricator,memsql/phabricator,shrimpma/phabricator,wusuoyongxin/phabricator,memsql/phabricator,leolujuyi/phabricator,shrimpma/phabricator,hshackathons/phabricator-deprecated,cjxgm/p.cjprods.org,gsinkovskiy/phabricator,wikimedia/phabricator-phabricator,huaban/phabricator,Soluis/phabricator,phacility/phabricator,wangjun/phabricator,hach-que/phabricator,parksangkil/phabricator,zhihu/phabricator,benchling/phabricator,WuJiahu/phabricator,coursera/phabricator,Soluis/phabricator,huaban/phabricator,folsom-labs/phabricator,Automattic/phabricator,aik099/phabricator,a20012251/phabricator,NigelGreenway/phabricator,schlaile/phabricator,akkakks/phabricator,codevlabs/phabricator,wxstars/phabricator,huangjimmy/phabricator-1,Khan/phabricator,folsom-labs/phabricator,matthewrez/phabricator,denisdeejay/phabricator,a20012251/phabricator,Drooids/phabricator,Soluis/phabricator,phacility/phabricator,WuJiahu/phabricator,r4nt/phabricator,shl3807/phabricator,r4nt/phabricator,NigelGreenway/phabricator,kalbasit/phabricator,vinzent/phabricator,sharpwhisper/phabricator,devurandom/phabricator,kwoun1982/phabricator,NigelGreenway/phabricator,Symplicity/phabricator,denisdeejay/phabricator,apexstudios/phabricator,schlaile/phabricator,shrimpma/phabricator,Symplicity/phabricator,wangjun/phabricator,christopher-johnson/phabricator,codevlabs/phabricator,cjxgm/p.cjprods.org,MicroWorldwide/phabricator,eSpark/phabricator,librewiki/phabricator,apexstudios/phabricator,wikimedia/phabricator,UNCC-OpenProjects/Phabricator,kanarip/phabricator,denisdeejay/phabricator,kanarip/phabricator,jwdeitch/phabricator,zhihu/phabricator,codevlabs/phabricator,huangjimmy/phabricator-1,tanglu-org/tracker-phabricator,telerik/phabricator,benchling/phabricator,gsinkovskiy/phabricator,matthewrez/phabricator,optimizely/phabricator,kanarip/phabricator,ryancford/phabricator,ryancford/phabricator,dannysu/phabricator,hach-que/phabricator,jwdeitch/phabricator,WuJiahu/phabricator,kwoun1982/phabricator,kalbasit/phabricator,uhd-urz/phabricator,akkakks/phabricator,uhd-urz/phabricator,vinzent/phabricator,kalbasit/phabricator,vinzent/phabricator,NigelGreenway/phabricator,wusuoyongxin/phabricator,codevlabs/phabricator,Symplicity/phabricator,Automattic/phabricator,sharpwhisper/phabricator,Drooids/phabricator,jwdeitch/phabricator,aswanderley/phabricator,dannysu/phabricator,akkakks/phabricator,hshackathons/phabricator-deprecated,memsql/phabricator,denisdeejay/phabricator,leolujuyi/phabricator,gsinkovskiy/phabricator,devurandom/phabricator,kwoun1982/phabricator,wikimedia/phabricator,eSpark/phabricator,christopher-johnson/phabricator,freebsd/phabricator,MicroWorldwide/phabricator,leolujuyi/phabricator,r4nt/phabricator,shl3807/phabricator,wikimedia/phabricator,hach-que/unearth-phabricator,huangjimmy/phabricator-1,parksangkil/phabricator,ide/phabricator,wikimedia/phabricator-phabricator,aswanderley/phabricator,aik099/phabricator,wxstars/phabricator,zhihu/phabricator,vuamitom/phabricator,Symplicity/phabricator,hach-que/phabricator,vinzent/phabricator,folsom-labs/phabricator,hach-que/unearth-phabricator,zhihu/phabricator,wusuoyongxin/phabricator,wikimedia/phabricator,christopher-johnson/phabricator,a20012251/phabricator,ide/phabricator,memsql/phabricator,MicroWorldwide/phabricator,vuamitom/phabricator,telerik/phabricator,shl3807/phabricator,hach-que/unearth-phabricator,hach-que/phabricator,aswanderley/phabricator,uhd-urz/phabricator,phacility/phabricator,a20012251/phabricator,dannysu/phabricator,telerik/phabricator,christopher-johnson/phabricator,freebsd/phabricator,Soluis/phabricator,ryancford/phabricator,sharpwhisper/phabricator,eSpark/phabricator,librewiki/phabricator,cjxgm/p.cjprods.org,akkakks/phabricator,vuamitom/phabricator,r4nt/phabricator,schlaile/phabricator,tanglu-org/tracker-phabricator,aswanderley/phabricator,dannysu/phabricator,librewiki/phabricator,Khan/phabricator,zhihu/phabricator,Automatic/phabricator,hshackathons/phabricator-deprecated,folsom-labs/phabricator,coursera/phabricator,codevlabs/phabricator,cjxgm/p.cjprods.org,sharpwhisper/phabricator,wikimedia/phabricator-phabricator,aik099/phabricator
|
48c94504fce5b6ccbdd84dec3e676a6867c0125f
|
lib/convoy.js
|
lib/convoy.js
|
var Queue = require('./queue');
var Job = require('./job');
var Worker = require('./worker');
var redis = require('./redis');
exports.redis = redis;
exports.createQueue = function(name){
var q = new Queue(name);
q.client = exports.redis.createClient();
q.workerClient = exports.redis.createClient();
return q;
};
exports.Job = Job;
exports.Worker = Worker;
|
var Queue = require('./queue');
var Job = require('./job');
var Worker = require('./worker');
var redis = require('./redis');
exports.redis = redis;
exports.createQueue = function(name, opts){
if(!opts)
opts = {};
if(typeof opts.redis == 'undefined'){
opts.redis = redis;
}
var q = new Queue(name, opts);
return q;
};
exports.Job = Job;
exports.Worker = Worker;
|
Send redis library to queue via opts
|
Send redis library to queue via opts
|
JavaScript
|
mit
|
gosquared/convoy,intertwine/convoy
|
67ffd189c4717ff78dc04fdc7268d60e4840eebf
|
lib/linter.js
|
lib/linter.js
|
var JSLINT = require("../lib/nodelint");
function addDefaults(options) {
'use strict';
['node', 'es5'].forEach(function (opt) {
if (!options.hasOwnProperty(opt)) {
options[opt] = true;
}
});
return options;
}
exports.lint = function (script, options) {
'use strict';
// remove shebang
/*jslint regexp: true*/
script = script.replace(/^\#\!.*/, "");
options = options || {};
delete options.argv;
options = addDefaults(options);
var ok = JSLINT(script, options),
result = {
ok: true,
errors: []
};
if (!ok) {
result = JSLINT.data();
result.errors = (result.errors || []).filter(function (error) {
return !(/\/\/.*bypass/).test(error.evidence);
});
result.ok = !result.errors.length;
}
result.options = options;
return result;
};
|
var JSLINT = require("../lib/nodelint");
function addDefaults(options) {
'use strict';
['node', 'es5'].forEach(function (opt) {
if (!options.hasOwnProperty(opt)) {
options[opt] = true;
}
});
return options;
}
exports.lint = function (script, options) {
'use strict';
// remove shebang
/*jslint regexp: true*/
script = script.replace(/^\#\!.*/, "");
options = options || {};
delete options.argv;
options = addDefaults(options);
var ok = JSLINT(script, options),
result = {
ok: true,
errors: []
};
if (!ok) {
result = JSLINT.data();
result.errors = (result.errors || []).filter(function (error) {
return !error.evidence || !(/\/\/.*bypass/).test(error.evidence);
});
result.ok = !result.errors.length;
}
result.options = options;
return result;
};
|
Fix unexpected error when there is no context in an error
|
Fix unexpected error when there is no context in an error
|
JavaScript
|
bsd-3-clause
|
BenoitZugmeyer/node-jslint-extractor,BenoitZugmeyer/node-jslint-extractor
|
35631043b65738731b8dc51dcf6df818b454acfd
|
app/js/arethusa.artificial_token/directives/artificial_token_list.js
|
app/js/arethusa.artificial_token/directives/artificial_token_list.js
|
"use strict";
angular.module('arethusa.artificialToken').directive('artificialTokenList', [
'artificialToken',
'idHandler',
function(artificialToken, idHandler) {
return {
restrict: 'A',
scope: true,
link: function(scope, element, attrs) {
scope.aT = artificialToken;
scope.formatId = function(id) {
return idHandler.formatId(id, '%w');
};
},
templateUrl: 'templates/arethusa.artificial_token/artificial_token_list.html'
};
}
]);
|
"use strict";
angular.module('arethusa.artificialToken').directive('artificialTokenList', [
'artificialToken',
'idHandler',
function(artificialToken, idHandler) {
return {
restrict: 'A',
scope: true,
link: function(scope, element, attrs) {
scope.aT = artificialToken;
scope.formatId = function(id) {
return idHandler.formatId(id, '%s-%w');
};
},
templateUrl: 'templates/arethusa.artificial_token/artificial_token_list.html'
};
}
]);
|
Fix id formatting in artificialTokenList
|
Fix id formatting in artificialTokenList
|
JavaScript
|
mit
|
latin-language-toolkit/arethusa,PonteIneptique/arethusa,fbaumgardt/arethusa,Masoumeh/arethusa,Masoumeh/arethusa,PonteIneptique/arethusa,fbaumgardt/arethusa,alpheios-project/arethusa,latin-language-toolkit/arethusa,fbaumgardt/arethusa,alpheios-project/arethusa,alpheios-project/arethusa
|
3650f297790e9c53fe609e72c65771b70e1af6ab
|
app/scripts/directives/radioQuestion.js
|
app/scripts/directives/radioQuestion.js
|
'use strict';
angular.module('confRegistrationWebApp')
.directive('radioQuestion', function () {
return {
templateUrl: 'views/radioQuestion.html',
restrict: 'E',
controller: function ($scope) {
$scope.answer = {};
}
};
});
|
'use strict';
angular.module('confRegistrationWebApp')
.directive('radioQuestion', function () {
return {
templateUrl: 'views/radioQuestion.html',
restrict: 'E',
controller: function ($scope) {
$scope.updateAnswer = function (answer) {
console.log('block ' + $scope.block.id + ' answer changed to ' + answer);
};
$scope.answer = {};
}
};
});
|
Add the previously removed updateAnswer function
|
Add the previously removed updateAnswer function
|
JavaScript
|
mit
|
CruGlobal/conf-registration-web,CruGlobal/conf-registration-web,CruGlobal/conf-registration-web,CruGlobal/conf-registration-web
|
201376a144a28953616f6412d544ee7585808b53
|
lib/marked.js
|
lib/marked.js
|
var escape = require('./util/escape')
var format = require('string-template');
var hljs = require('highlight.js');
var heading = require('./util/writeHeading');
var marked = require('marked');
var multiline = require('multiline');
var mdRenderer = new marked.Renderer();
var HTML_EXAMPLE_TEMPLATE = multiline(function() {/*
<div class="docs-code" data-docs-code>
<pre>
<code class="{0}">{1}</code>
</pre>
</div>
*/});
// Adds an anchor link to each heading created
mdRenderer.heading = heading;
// Adds special formatting to each code block created
// If the language is suffixed with "_example", the raw HTML is printed after the code sample, creating a live example.
mdRenderer.code = function(code, language) {
var extraOutput = '';
if (language === 'inky') {
return require('./buildInkySample')(code);
}
if (typeof language === 'undefined') language = 'html';
// If the language is *_example, live code will print out along with the sample
if (language.match(/_example$/)) {
extraOutput = format('\n\n<div class="docs-code-live">{0}</div>', [code]);
language = language.replace(/_example$/, '');
}
var renderedCode = hljs.highlight(language, code).value;
var output = format(HTML_EXAMPLE_TEMPLATE, [language, renderedCode]);
return output + extraOutput;
}
module.exports = mdRenderer;
|
var escape = require('./util/escape')
var format = require('string-template');
var hljs = require('highlight.js');
var heading = require('./util/writeHeading');
var marked = require('marked');
var multiline = require('multiline');
var mdRenderer = new marked.Renderer();
var HTML_EXAMPLE_TEMPLATE = multiline(function() {/*
<div class="docs-code" data-docs-code>
<pre>
<code class="{0}">{1}</code>
</pre>
</div>
*/});
// Adds an anchor link to each heading created
mdRenderer.heading = heading;
// Adds special formatting to each code block created
// If the language is suffixed with "_example", the raw HTML is printed after the code sample, creating a live example.
mdRenderer.code = function(code, language) {
var extraOutput = '';
if (language === 'inky') {
return require('./util/buildInkySample')(code);
}
if (typeof language === 'undefined') language = 'html';
// If the language is *_example, live code will print out along with the sample
if (language.match(/_example$/)) {
extraOutput = format('\n\n<div class="docs-code-live">{0}</div>', [code]);
language = language.replace(/_example$/, '');
}
var renderedCode = hljs.highlight(language, code).value;
var output = format(HTML_EXAMPLE_TEMPLATE, [language, renderedCode]);
return output + extraOutput;
}
module.exports = mdRenderer;
|
Fix incorrect require() path in Marked renderer
|
Fix incorrect require() path in Marked renderer
|
JavaScript
|
mit
|
zurb/foundation-docs,zurb/foundation-docs
|
a1e8fb35145d772c9766b0e279b75969a2192491
|
src/index.js
|
src/index.js
|
export function search(select, queryString, callback) {
select.find('input').simulate('change', { target: { value: queryString } });
setTimeout(() => { callback(); }, 0);
}
export function chooseOption(select, optionText) {
const options = select.find('.Select-option span');
const matchingOptions = options.findWhere((option) => {
return option.text() === optionText;
});
matchingOptions.simulate('mouseDown');
}
export function chooseOptionBySearching(select, queryString, optionText, callback) {
search(select, queryString, () => {
chooseOption(select, optionText);
callback();
});
}
export default {
search,
chooseOption,
chooseOptionBySearching
};
|
import Select from 'react-select';
function findSelect(wrapper) {
const plainSelect = wrapper.find(Select);
if (plainSelect.length > 0) {
return plainSelect;
}
const asyncSelect = wrapper.find(Select.Async);
if (asyncSelect.length > 0) {
return asyncSelect;
}
throw "Couldn't find Select or Select.Async in wrapper";
}
export function search(wrapper, queryString, callback) {
findSelect(wrapper).find('.Select-input input').simulate('change', { target: { value: queryString } });
setTimeout(callback, 0);
}
export function chooseOption(wrapper, optionText) {
const options = findSelect(wrapper).find('.Select-option');
const matchingOptions = options.findWhere((option) => {
return option.text() === optionText;
});
matchingOptions.simulate('mouseDown');
}
export function chooseOptionBySearching(wrapper, queryString, optionText, callback) {
search(wrapper, queryString, () => {
chooseOption(wrapper, optionText);
callback();
});
}
export default {
search,
chooseOption,
chooseOptionBySearching
};
|
Make helpers a little more robust by searching specifically for Select or Select.Async components
|
Make helpers a little more robust by searching specifically for Select or Select.Async components
|
JavaScript
|
mit
|
patientslikeme/react-select-test-utils
|
903a944fd035f558f862dc7e8fa86d45625a6a9d
|
src/index.js
|
src/index.js
|
import {StreamTransformer} from './stream.transformer';
import {TracebackTransformer} from './traceback.transformer';
import {LaTeXTransformer} from './latex.transformer';
import {MarkdownTransformer} from 'transformime-commonmark';
import {PDFTransformer} from './pdf.transformer';
export default {StreamTransformer, TracebackTransformer, MarkdownTransformer};
|
import {StreamTransformer} from './stream.transformer';
import {TracebackTransformer} from './traceback.transformer';
import {LaTeXTransformer} from './latex.transformer';
import {MarkdownTransformer} from 'transformime-commonmark';
import {PDFTransformer} from './pdf.transformer';
export default {
StreamTransformer,
TracebackTransformer,
MarkdownTransformer,
LaTeXTransformer,
PDFTransformer
};
|
Include the PDF and LaTeX Transformers
|
Include the PDF and LaTeX Transformers
|
JavaScript
|
bsd-3-clause
|
rgbkrk/transformime-jupyter-transformers,jdfreder/transformime-jupyter-transformers,nteract/transformime-jupyter-transformers,nteract/transformime-jupyter-renderers
|
fd91b33f7fb3538a11c5a1096fbef0155a24afe0
|
lib/routes.js
|
lib/routes.js
|
Router.configure({
layoutTemplate: 'layout'
});
Router.route('/votes', {name: 'votesList'});
Router.route('/iframe', {name: 'iFrame'});
Router.route('/submitvote', {name: 'submitVote'});
Router.route('/signup', {name: 'signup'});
Router.route('/scores', {name: 'scoreCard'});
Router.route('/login', {name: 'loginpage'});
var requireLogin = function() { if (! Meteor.user()) {
if (Meteor.loggingIn()) { this.render(this.loadingTemplate);
} this.render('accessDenied');
} else {
this.next(); }
}
Router.onBeforeAction(requireLogin, {only: 'submitVote'});
Router.route('/votes/:_id', {
name: 'voteInfoPage',
data: function() { return VotesCollection.findOne(this.params._id); }
});
Router.route('/votes/comments/:_id', {
name: 'commentList',
data: function() { return VotesCollection.findOne(this.params._id); }
});
|
Router.configure({
layoutTemplate: 'layout'
});
Router.route('/', {name: 'votesList'});
Router.route('/iframe', {name: 'iFrame'});
Router.route('/submitvote', {name: 'submitVote'});
Router.route('/signup', {name: 'signup'});
Router.route('/scores', {name: 'scoreCard'});
Router.route('/login', {name: 'loginpage'});
var requireLogin = function() { if (! Meteor.user()) {
if (Meteor.loggingIn()) { this.render(this.loadingTemplate);
} this.render('accessDenied');
} else {
this.next(); }
}
Router.onBeforeAction(requireLogin, {only: 'submitVote'});
Router.route('/votes/:_id', {
name: 'voteInfoPage',
data: function() { return VotesCollection.findOne(this.params._id); }
});
Router.route('/votes/comments/:_id', {
name: 'commentList',
data: function() { return VotesCollection.findOne(this.params._id); }
});
|
Change votes route to /
|
Change votes route to /
|
JavaScript
|
agpl-3.0
|
gazhayes/Popvote-Australia,gazhayes/popvote,gazhayes/Popvote-Australia,gazhayes/popvote
|
ec8a6e644a68f05da723bf5f463bda662ad0dde1
|
lib/router.js
|
lib/router.js
|
Router.configure({
layoutTemplate: 'layout',
loadingTemplate: 'loading',
notFoundTemplate: 'notFound',
waitOn: function() {
return [Meteor.subscribe('posts'), Meteor.subscribe('notifications')];
}
});
Router.route('/', { name: 'postsList'});
Router.route('/posts/:_id', {
name: 'postPage',
waitOn: function() {
return Meteor.subscribe('comments', this.params._id);
},
data: function() {
return Posts.findOne(this.params._id);
}
});
Router.route('posts/:_id/edit', {
name: 'postEdit',
data: function() {
return Posts.findOne(this.params._id);
}
});
Router.route('/submit', { name: 'postSubmit' });
var requireLogin = function() {
if (!Meteor.user()) {
if (Meteor.loggingIn()) {
this.render(this.loadingTemplate);
} else {
this.render('accessDenied');
}
} else {
this.next();
}
}
Router.onBeforeAction('dataNotFound', { only: 'postPage' });
Router.onBeforeAction(requireLogin, { only: 'postSubmit' });
|
Router.configure({
layoutTemplate: 'layout',
loadingTemplate: 'loading',
notFoundTemplate: 'notFound',
waitOn: function() {
return Meteor.subscribe('notifications');
}
});
Router.route('/', { name: 'postsList'});
Router.route('/posts/:_id', {
name: 'postPage',
waitOn: function() {
return Meteor.subscribe('comments', this.params._id);
},
data: function() {
return Posts.findOne(this.params._id);
}
});
Router.route('posts/:_id/edit', {
name: 'postEdit',
data: function() {
return Posts.findOne(this.params._id);
}
});
Router.route('/submit', { name: 'postSubmit' });
Router.route('/:postsLimit?', {
name: 'postsList',
waitOn: function() {
var limit = parseInt(this.params.postsLimit) || 5;
return Meteor.subscribe('posts', { sort: { submitted: -1 }, limit: limit });
}
});
var requireLogin = function() {
if (!Meteor.user()) {
if (Meteor.loggingIn()) {
this.render(this.loadingTemplate);
} else {
this.render('accessDenied');
}
} else {
this.next();
}
}
Router.onBeforeAction('dataNotFound', { only: 'postPage' });
Router.onBeforeAction(requireLogin, { only: 'postSubmit' });
|
Add route to limit posts
|
Add route to limit posts
|
JavaScript
|
mit
|
Bennyz/microscope,Bennyz/microscope
|
c11be7a5d0e635699f079e4d4151a0ffaeec4603
|
src/candela/components/index.js
|
src/candela/components/index.js
|
import BarChart from './BarChart';
import BoxPlot from './BoxPlot';
import BulletChart from './BulletChart';
import GanttChart from './GanttChart';
import Geo from './Geo';
import Heatmap from './Heatmap';
import Histogram from './Histogram';
import LineChart from './LineChart';
import LineUp from './LineUp';
import ParallelCoordinates from './ParallelCoordinates';
import ScatterPlot from './ScatterPlot';
import ScatterPlotMatrix from './ScatterPlotMatrix';
import UpSet from './UpSet';
export default {
BarChart,
BoxPlot,
BulletChart,
GanttChart,
Geo,
Heatmap,
Histogram,
LineChart,
LineUp,
ParallelCoordinates,
UpSet
};
|
import BarChart from './BarChart';
import BoxPlot from './BoxPlot';
import BulletChart from './BulletChart';
import GanttChart from './GanttChart';
import Geo from './Geo';
import Heatmap from './Heatmap';
import Histogram from './Histogram';
import LineChart from './LineChart';
import LineUp from './LineUp';
import ParallelCoordinates from './ParallelCoordinates';
import ScatterPlot from './ScatterPlot';
import ScatterPlotMatrix from './ScatterPlotMatrix';
import UpSet from './UpSet';
export default {
BarChart,
BoxPlot,
BulletChart,
GanttChart,
Geo,
Heatmap,
Histogram,
LineChart,
LineUp,
ParallelCoordinates,
ScatterPlot,
ScatterPlotMatrix,
UpSet
};
|
Replace lost classes in components list
|
Replace lost classes in components list
|
JavaScript
|
apache-2.0
|
Kitware/candela,Kitware/candela,Kitware/candela,Kitware/candela,Kitware/candela
|
f9ea9934ee9cfc21d9b1642452977c4f30474491
|
src/client/app/trades/trades.js
|
src/client/app/trades/trades.js
|
"use strict";
(function () {
angular
.module("argo")
.controller("Trades", Trades);
Trades.$inject = ["toastService", "tradesService"];
function Trades(toastService, tradesService) {
var vm = this;
vm.getTrades = getTrades;
vm.closeTrade = closeTrade;
tradesService.getTrades().then(getTrades);
function getTrades(trades) {
vm.trades = trades;
}
function closeTrade(id) {
tradesService.closeTrade(id).then(function (trade) {
var message = "Closed " +
trade.side + " " +
trade.instrument +
" #" + trade.id +
" @" + trade.price +
" P&L " + trade.profit;
toastService.show(message);
tradesService.getTrades().then(getTrades);
});
}
}
}());
|
"use strict";
(function () {
angular
.module("argo")
.controller("Trades", Trades);
Trades.$inject = ["$mdDialog", "toastService", "tradesService"];
function Trades($mdDialog, toastService, tradesService) {
var vm = this;
vm.getTrades = getTrades;
vm.closeTrade = closeTrade;
tradesService.getTrades().then(getTrades);
function getTrades(trades) {
vm.trades = trades;
}
function closeTrade(event, id) {
var confirm = $mdDialog.confirm()
.content("Are you sure to close the trade?")
.ariaLabel("Trade closing confirmation")
.ok("Ok")
.cancel("Cancel")
.targetEvent(event);
$mdDialog.show(confirm).then(function () {
tradesService.closeTrade(id).then(function (trade) {
var message = "Closed " +
trade.side + " " +
trade.instrument +
" #" + trade.id +
" @" + trade.price +
" P&L " + trade.profit;
toastService.show(message);
tradesService.getTrades().then(getTrades);
});
});
}
}
}());
|
Add confirmation dialog to close trade.
|
Add confirmation dialog to close trade.
|
JavaScript
|
mit
|
albertosantini/argo,albertosantini/argo
|
637339c263e278e99b4bec3eb1b48d3c721ab57b
|
src/index.js
|
src/index.js
|
var Transmitter = function (config) {
var router = require('./router.js');
router(config);
var io = require('socket.io')(router.server);
// Socket.io connection handling
io.on('connection', function(socket){
console.log('PULSAR: client connected');
socket.on('disconnect', function() {
console.log('PULSAR: client disconnected');
});
});
var Processor = require('@dermah/pulsar-input-keyboard');
var processor = new Processor(io, config);
}
module.exports = Transmitter;
|
var Transmitter = function (config) {
var router = require('./router.js');
router(config);
var io = require('socket.io')(router.server);
// Socket.io connection handling
io.on('connection', function(socket){
console.log('PULSAR: client connected');
socket.on('disconnect', function() {
console.log('PULSAR: client disconnected');
});
});
var Processor = require('@dermah/pulsar-input-keyboard');
var processor = new Processor(config);
processor.on('pulse', pulse => {
io.emit('pulse', pulse)
});
processor.on('pulsar control', pulse => {
io.emit('pulsar control', pulse)
});
processor.on('pulse update', pulse => {
io.emit('pulse update', pulse);
});
}
module.exports = Transmitter;
|
Use the new EventEmitter input by passing its events to socket.io
|
Use the new EventEmitter input by passing its events to socket.io
|
JavaScript
|
mit
|
Dermah/pulsar-transmitter
|
0ee8baa8d70d20502f8c3134f6feea475646fbca
|
src/index.js
|
src/index.js
|
"use strict";
const http = require('http');
const mongoose = require('mongoose');
const requireAll = require('require-all');
const TelegramBot = require('node-telegram-bot-api');
const GitHubNotifications = require('./common/GitHubNotifications');
const User = require('./models/User');
const BOT_COMMANDS = requireAll({dirname: `${__dirname}/commands`});
const TELEGRAM_BOT_TOKEN = process.env['TELEGRAM_BOT_TOKEN'];
if (!TELEGRAM_BOT_TOKEN) throw new Error('You must provide telegram bot token');
const bot = new TelegramBot(TELEGRAM_BOT_TOKEN, {polling: true});
Object.keys(BOT_COMMANDS).forEach(command => BOT_COMMANDS[command](bot));
mongoose.connect(process.env['MONGODB_URI']);
User.find({}, (error, users) => {
if (error) throw new Error(error);
users.forEach(user => {
new GitHubNotifications(user.username, user.token).on('notification', data => {
bot.sendMessage(user.telegramId, `You have unread notification - ${data}`);
});
});
});
http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Bot is working\n');
}).listen(process.env['PORT']);
|
"use strict";
const http = require('http');
const mongoose = require('mongoose');
const requireAll = require('require-all');
const TelegramBot = require('node-telegram-bot-api');
const GitHubNotifications = require('./services/GitHubNotifications');
const User = require('./models/User');
const BOT_COMMANDS = requireAll({dirname: `${__dirname}/commands`});
const TELEGRAM_BOT_TOKEN = process.env['TELEGRAM_BOT_TOKEN'];
if (!TELEGRAM_BOT_TOKEN) throw new Error('You must provide telegram bot token');
const telegramBotConfig = process.env.NODE_ENV === 'production' ? {webHook: true} : {polling: true};
const bot = new TelegramBot(TELEGRAM_BOT_TOKEN, telegramBotConfig);
Object.keys(BOT_COMMANDS).forEach(command => BOT_COMMANDS[command](bot));
mongoose.connect(process.env['MONGODB_URI']);
User.find({}, (error, users) => {
if (error) throw new Error(error);
users.forEach(user => {
new GitHubNotifications(user.username, user.token).on('notification', data => {
bot.sendMessage(user.telegramId, `You have unread notification - ${data}`);
});
});
});
http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Bot is working\n');
}).listen(process.env['PORT']);
|
Implement switching to webhooks in production
|
feat(bot): Implement switching to webhooks in production
|
JavaScript
|
mit
|
ghaiklor/telegram-bot-github
|
d8e2ceeb05de3c2fda22ef00486d50ef7fe9379c
|
src/index.js
|
src/index.js
|
'use strict';
require('foundation-sites/scss/foundation.scss')
require('./styles.scss');
require('font-awesome/css/font-awesome.css');
// Require index.html so it gets copied to dist
require('./index.html');
var Elm = require('./Main.elm');
var mountNode = document.getElementById('main');
// The third value on embed are the initial values for incomming ports into Elm
var app = Elm.Main.embed(mountNode);
|
'use strict';
require('./styles.scss');
require('font-awesome/css/font-awesome.css');
// Require index.html so it gets copied to dist
require('./index.html');
var Elm = require('./Main.elm');
var mountNode = document.getElementById('main');
// The third value on embed are the initial values for incomming ports into Elm
var app = Elm.Main.embed(mountNode);
|
Remove foundation-sites require as foundation is not used anymore.
|
Remove foundation-sites require as foundation is not used anymore.
Signed-off-by: Snorre Magnus Davøen <[email protected]>
|
JavaScript
|
mit
|
Snorremd/builds-dashboard-gitlab,Snorremd/builds-dashboard-gitlab
|
bb40f82aaa28cfef7b362f97bbc0ef332b925fe0
|
sandbox-react-redux/src/enhancer.js
|
sandbox-react-redux/src/enhancer.js
|
export default function enhancer() {
return (next) => (reducer, preloadedState) => {
const initialState = Object.assign({}, preloadedState, loadState(restoreState));
const store = next(reducer, initialState);
store.subscribe(() => saveState(store.getState()));
return store;
}
}
const restoreState = (state) => {
return {
misc: state
};
}
const loadState = (transform) => {
const state = {
locked: true
};
return transform(state);
}
const saveState = (state) => {
if (state.misc) {
console.log(state.misc);
}
}
|
export default function enhancer() {
return (next) => (reducer, preloadedState) => {
const initialState = Object.assign({}, preloadedState, loadState(restoreState));
const store = next(reducer, initialState);
store.subscribe(() => saveState(store.getState(), filterState));
return store;
}
}
const restoreState = (state) => {
return {
misc: state
};
}
const filterState = (state) => {
return state.misc;
}
const storageKey = 'sample';
const loadState = (transform) => {
const saved = window.localStorage.getItem(storageKey);
if (saved) {
return transform(JSON.parse(saved));
}
}
const saveState = (state, transform) => {
const saving = transform(state);
if (saving) {
window.localStorage.setItem(storageKey, JSON.stringify(saving));
}
}
|
Tweak sample for react-redux in order to use local storage
|
Tweak sample for react-redux in order to use local storage
|
JavaScript
|
mit
|
ohtomi/sandbox,ohtomi/sandbox,ohtomi/sandbox,ohtomi/sandbox,ohtomi/sandbox,ohtomi/sandbox,ohtomi/sandbox,ohtomi/sandbox,ohtomi/sandbox
|
8b9af7220cc36962794a953525505bb57d8f426e
|
public/assets/wee/build/tasks/legacy-convert.js
|
public/assets/wee/build/tasks/legacy-convert.js
|
/* global legacyConvert, module, project */
module.exports = function(grunt) {
grunt.registerTask('convertLegacy', function(task) {
var dest = legacyConvert[task],
content = grunt.file.read(dest),
rootSize = project.style.legacy.rootSize,
rootValue = 10;
// Determine root value for unit conversion
if (rootSize.indexOf('%') !== -1) {
rootValue = (rootSize.replace('%', '') / 100) * 16;
} else if (rootSize.indexOf('px') !== -1) {
rootValue = rootSize.replace('px', '');
} else if (rootSize.indexOf('em') !== -1) {
rootValue = rootSize.replace('em', '');
} else if (rootSize.indexOf('pt') !== -1) {
rootValue = rootSize.replace('pt', '');
}
content = content.replace(/(-?[.\d]+)rem/gi, function(str, match) {
return (match * rootValue) + 'px';
}).replace(/opacity:([.\d]+)/gi, function(str, match) {
return 'filter:alpha(opacity=' + Math.round((match * 100) * 100 / 100) + ');';
});
grunt.file.write(dest, content);
});
};
|
/* global legacyConvert, module, project */
module.exports = function(grunt) {
grunt.registerTask('convertLegacy', function(task) {
var dest = legacyConvert[task],
content = grunt.file.read(dest),
rootSize = project.style.legacy.rootSize,
rootValue = 10;
// Determine root value for unit conversion
if (rootSize.indexOf('%') !== -1) {
rootValue = (rootSize.replace('%', '') / 100) * 16;
} else if (rootSize.indexOf('px') !== -1) {
rootValue = rootSize.replace('px', '');
} else if (rootSize.indexOf('em') !== -1) {
rootValue = rootSize.replace('em', '');
} else if (rootSize.indexOf('pt') !== -1) {
rootValue = rootSize.replace('pt', '');
}
content = content.replace(/(-?[.\d]+)rem/gi, function(str, match) {
return (match * rootValue) + 'px';
}).replace(/opacity:([.\d]+)/gi, function(str, match) {
return 'filter:alpha(opacity=' + Math.round((match * 100) * 100 / 100) + ');';
}).replace(/::/g, ':');
grunt.file.write(dest, content);
});
};
|
Replace :: with : in IE8 for backward compatibility with element pseudo selectors
|
Replace :: with : in IE8 for backward compatibility with element pseudo selectors
|
JavaScript
|
apache-2.0
|
weepower/wee,janusnic/wee,weepower/wee,janusnic/wee
|
729fb1c904ca57b39110894b85e8439a11cab554
|
src/widgets/Wizard.js
|
src/widgets/Wizard.js
|
/* eslint-disable import/no-named-as-default */
/* eslint-disable react/forbid-prop-types */
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Stepper } from './Stepper';
import { TabNavigator } from './TabNavigator';
import DataTablePageView from './DataTablePageView';
import { WizardActions } from '../actions/WizardActions';
import { selectCurrentTab } from '../selectors/wizard';
/**
* Layout component for a Tracker and TabNavigator, displaying steps
* to completion for completion. See TabNavigator and StepsTracker
* for individual component implementation.
*/
const WizardComponent = ({ tabs, titles, currentTab, nextTab }) => (
<DataTablePageView>
<Stepper
numberOfSteps={tabs.length}
currentStep={currentTab}
onPress={nextTab}
titles={titles}
/>
<TabNavigator tabs={tabs} currentTabIndex={currentTab} />
</DataTablePageView>
);
WizardComponent.propTypes = {
tabs: PropTypes.array.isRequired,
titles: PropTypes.array.isRequired,
nextTab: PropTypes.func.isRequired,
currentTab: PropTypes.number.isRequired,
};
const mapStateToProps = state => {
const currentTab = selectCurrentTab(state);
return { currentTab };
};
const mapDispatchToProps = dispatch => ({
nextTab: tab => dispatch(WizardActions.switchTab(tab)),
});
export const Wizard = connect(mapStateToProps, mapDispatchToProps)(WizardComponent);
|
/* eslint-disable import/no-named-as-default */
/* eslint-disable react/forbid-prop-types */
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Stepper } from './Stepper';
import { TabNavigator } from './TabNavigator';
import DataTablePageView from './DataTablePageView';
import { WizardActions } from '../actions/WizardActions';
import { selectCurrentTab } from '../selectors/wizard';
/**
* Layout component for a Tracker and TabNavigator, displaying steps
* to completion for completion. See TabNavigator and StepsTracker
* for individual component implementation.
*/
const WizardComponent = ({ tabs, titles, currentTab, switchTab }) => (
<DataTablePageView>
<Stepper
numberOfSteps={tabs.length}
currentStep={currentTab}
onPress={switchTab}
titles={titles}
/>
<TabNavigator tabs={tabs} currentTabIndex={currentTab} />
</DataTablePageView>
);
WizardComponent.propTypes = {
tabs: PropTypes.array.isRequired,
titles: PropTypes.array.isRequired,
switchTab: PropTypes.func.isRequired,
currentTab: PropTypes.number.isRequired,
};
const mapStateToProps = state => {
const currentTab = selectCurrentTab(state);
return { currentTab };
};
const mapDispatchToProps = dispatch => ({
switchTab: tab => dispatch(WizardActions.switchTab(tab)),
});
export const Wizard = connect(mapStateToProps, mapDispatchToProps)(WizardComponent);
|
Add renaming of nextTab -> switchTab
|
Add renaming of nextTab -> switchTab
|
JavaScript
|
mit
|
sussol/mobile,sussol/mobile,sussol/mobile,sussol/mobile
|
04b32b2c6f6bc92f9fbe6cc994c137968f4b522c
|
lib/i18n/dicts.js
|
lib/i18n/dicts.js
|
module.exports = {
'ar': require('../../i18n/ar.json'),
'da': require('../../i18n/da.json'),
'de': require('../../i18n/de.json'),
'en': require('../../i18n/en.json'),
'es': require('../../i18n/es.json'),
'fr': require('../../i18n/fr-FR.json'),
'fr-FR': require('../../i18n/fr-FR.json'),
'he': require('../../i18n/he.json'),
'it': require('../../i18n/it.json'),
'ja': require('../../i18n/ja.json'),
'ko': require('../../i18n/ko.json'),
'nb-NO': require('../../i18n/nb-NO.json'),
'nl': require('../../i18n/nl-NL.json'),
'nl-NL': require('../../i18n/nl-NL.json'),
'pt': require('../../i18n/pt.json'),
'pt-BR': require('../../i18n/pt-BR.json'),
'ru': require('../../i18n/ru.json'),
'sv': require('../../i18n/sv.json'),
'tlh': require('../../i18n/tlh.json'),
'tr': require('../../i18n/tr.json'),
'zh': require('../../i18n/zh.json'),
'zh-TW': require('../../i18n/zh-TW.json')
}
|
module.exports = {
'ar': require('../../i18n/ar.json'),
'da': require('../../i18n/da.json'),
'de': require('../../i18n/de.json'),
'en': require('../../i18n/en.json'),
'es': require('../../i18n/es.json'),
'fr': require('../../i18n/fr-FR.json'),
'fr-FR': require('../../i18n/fr-FR.json'),
'he': require('../../i18n/he.json'),
'it': require('../../i18n/it.json'),
'ja': require('../../i18n/ja.json'),
'ko': require('../../i18n/ko.json'),
'nb-NO': require('../../i18n/nb-NO.json'),
'nl': require('../../i18n/nl-NL.json'),
'nl-NL': require('../../i18n/nl-NL.json'),
'pl': require('../../i18n/pl.json'),
'pt': require('../../i18n/pt.json'),
'pt-BR': require('../../i18n/pt-BR.json'),
'ru': require('../../i18n/ru.json'),
'sv': require('../../i18n/sv.json'),
'tlh': require('../../i18n/tlh.json'),
'tr': require('../../i18n/tr.json'),
'zh': require('../../i18n/zh.json'),
'zh-TW': require('../../i18n/zh-TW.json')
}
|
Add polish dict to base code
|
Add polish dict to base code
|
JavaScript
|
mit
|
cwilgenhoff/lock,cwilgenhoff/lock,adam2314/lock,cwilgenhoff/lock,adam2314/lock,adam2314/lock
|
28b05e832339fafe433e5970b00466f5a915b895
|
website/app/application/core/projects/project/processes/process-list-controller.js
|
website/app/application/core/projects/project/processes/process-list-controller.js
|
(function (module) {
module.controller('projectListProcess', projectListProcess);
projectListProcess.$inject = ["processes", "project", "$state", "mcmodal", "$filter"];
function projectListProcess(processes, project, $state, mcmodal, $filter) {
console.log('projectListProcess');
var ctrl = this;
ctrl.viewProcess = viewProcess;
ctrl.chooseTemplate = chooseTemplate;
ctrl.processes = processes;
ctrl.project = project;
if (ctrl.processes.length !== 0) {
console.log(' ctrl.processes.length !== 0');
ctrl.processes = $filter('orderBy')(ctrl.processes, 'name');
ctrl.current = ctrl.processes[0];
//$state.go('projects.project.processes.list.view', {process_id: ctrl.current.id});
}
///////////////////////////////////
function viewProcess(process) {
ctrl.current = process;
$state.go('projects.project.processes.list.view', {process_id: ctrl.current.id});
}
function chooseTemplate() {
mcmodal.chooseTemplate(ctrl.project);
}
}
}(angular.module('materialscommons')));
|
(function (module) {
module.controller('projectListProcess', projectListProcess);
projectListProcess.$inject = ["processes", "project", "$state", "mcmodal", "$filter"];
function projectListProcess(processes, project, $state, mcmodal, $filter) {
var ctrl = this;
ctrl.viewProcess = viewProcess;
ctrl.chooseTemplate = chooseTemplate;
ctrl.processes = processes;
ctrl.project = project;
if (ctrl.processes.length !== 0) {
ctrl.processes = $filter('orderBy')(ctrl.processes, 'name');
ctrl.current = ctrl.processes[0];
$state.go('projects.project.processes.list.view', {process_id: ctrl.current.id});
}
///////////////////////////////////
function viewProcess(process) {
ctrl.current = process;
$state.go('projects.project.processes.list.view', {process_id: ctrl.current.id});
}
function chooseTemplate() {
mcmodal.chooseTemplate(ctrl.project);
}
}
}(angular.module('materialscommons')));
|
Remove debug of ui router state changes.
|
Remove debug of ui router state changes.
|
JavaScript
|
mit
|
materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org
|
e022dd7bd62f4f088a9d943adfc5258fbfc91006
|
app/components/Pit/index.js
|
app/components/Pit/index.js
|
import React, { PropTypes } from 'react';
import './index.css';
const Pit = React.createClass({
propTypes: {
pit: PropTypes.object.isRequired,
},
render() {
const { pit } = this.props;
return (
<div className="Pit">
<div className="Pit-name">{pit.name}</div>
<div className="Pit-type">{pit.type}</div>
<div className="Pit-dataset">{pit.dataset}</div>
<div className="Pit-id">{pit.id}</div>
<table>
{Object.keys(pit.data).map((key) =>
<tr>
<td>{key}</td>
<td>{pit.data[key]}</td>
</tr>
)}
</table>
</div>
);
},
});
export default Pit;
|
import React, { PropTypes } from 'react';
import './index.css';
const Pit = React.createClass({
propTypes: {
pit: PropTypes.object.isRequired,
},
render() {
const { pit } = this.props;
return (
<div className="Pit">
<div className="Pit-name">{pit.name}</div>
<div className="Pit-type">{pit.type}</div>
<div className="Pit-dataset">{pit.dataset}</div>
<div className="Pit-id">{pit.id}</div>
<table>
<tbody>
{Object.keys(pit.data).map((key) =>
<tr key={key}>
<td>{key}</td>
<td>{pit.data[key]}</td>
</tr>
)}
</tbody>
</table>
</div>
);
},
});
export default Pit;
|
Add keys to table loop
|
Add keys to table loop
|
JavaScript
|
mit
|
transparantnederland/browser,waagsociety/tnl-relationizer,transparantnederland/browser,transparantnederland/relationizer,waagsociety/tnl-relationizer,transparantnederland/relationizer
|
885f50a52c41cbc50f8de0d46ef57fc62fce1c17
|
src/actions/socketActionsFactory.js
|
src/actions/socketActionsFactory.js
|
import {
SOCKET_SET_OPENING, SOCKET_SET_CLOSING, SOCKET_SEND_MESSAGE
} from "../constants/ActionTypes";
export default (socketClient) => ({
open: url => {
const action = { type: SOCKET_SET_OPENING };
try {
socketClient.open(url);
action.payload = url;
} catch (err) {
action.error = true;
action.payload = err;
}
return action;
},
close: () => {
const action = { type: SOCKET_SET_CLOSING };
try {
socketClient.close();
} catch (err) {
action.error = true;
action.payload = err;
}
return action;
},
send: message => {
const action = { type: SOCKET_SEND_MESSAGE };
try {
socketClient.send(JSON.stringify(message));
} catch (err) {
action.error = true;
action.payload = err;
}
return action;
}
});
|
import {
SOCKET_SET_OPENING, SOCKET_SET_CLOSING, SOCKET_SEND_MESSAGE
} from "../constants/ActionTypes";
export default (socketClient) => ({
open: url => {
const action = { type: SOCKET_SET_OPENING };
try {
socketClient.open(url);
action.payload = url;
} catch (err) {
action.error = true;
action.payload = err;
}
return action;
},
close: () => {
const action = { type: SOCKET_SET_CLOSING };
try {
socketClient.close();
} catch (err) {
action.error = true;
action.payload = err;
}
return action;
},
send: message => {
const action = { type: SOCKET_SEND_MESSAGE };
try {
socketClient.send(JSON.stringify(message));
action.payload = message;
} catch (err) {
action.error = true;
action.payload = err;
}
return action;
}
});
|
Add message to SEND_MESSAGE action for debugging.
|
Add message to SEND_MESSAGE action for debugging.
|
JavaScript
|
mit
|
letitz/solstice-web,letitz/solstice-web
|
f9efd3ba4b435a46a47aec284a30abe83efb9e6a
|
src/reducers/FridgeReducer.js
|
src/reducers/FridgeReducer.js
|
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2020
*/
import moment from 'moment';
import { UIDatabase } from '../database';
import { FRIDGE_ACTIONS } from '../actions/FridgeActions';
const initialState = () => {
const fridges = UIDatabase.objects('Location');
return {
fridges,
selectedFridge: fridges[0],
fromDate: moment(new Date())
.subtract(30, 'd')
.toDate(),
toDate: new Date(),
};
};
export const FridgeReducer = (state = initialState(), action) => {
const { type } = action;
switch (type) {
case FRIDGE_ACTIONS.SELECT: {
const { payload } = action;
const { fridge } = payload;
return { ...state, selectedFridge: fridge };
}
case FRIDGE_ACTIONS.CHANGE_FROM_DATE: {
const { payload } = action;
const { date } = payload;
return { ...state, fromDate: date };
}
case FRIDGE_ACTIONS.CHANGE_TO_DATE: {
const { payload } = action;
const { date } = payload;
return { ...state, toDate: date };
}
default:
return state;
}
};
|
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2020
*/
import moment from 'moment';
import { UIDatabase } from '../database';
import { FRIDGE_ACTIONS } from '../actions/FridgeActions';
const initialState = () => {
const fridges = UIDatabase.objects('Location');
return {
fridges,
selectedFridge: fridges[0],
fromDate: moment(new Date())
.subtract(30, 'd')
.toDate(),
toDate: new Date(),
};
};
export const FridgeReducer = (state = initialState(), action) => {
const { type } = action;
switch (type) {
case FRIDGE_ACTIONS.SELECT: {
const { payload } = action;
const { fridge } = payload;
return { ...state, selectedFridge: fridge };
}
case FRIDGE_ACTIONS.CHANGE_FROM_DATE: {
const { payload } = action;
const { date } = payload;
const fromDate = new Date(date);
fromDate.setUTCHours(0, 0, 0, 0);
return { ...state, fromDate };
}
case FRIDGE_ACTIONS.CHANGE_TO_DATE: {
const { payload } = action;
const { date } = payload;
const toDate = new Date(date);
toDate.setUTCHours(23, 59, 59, 999);
return { ...state, toDate };
}
default:
return state;
}
};
|
Add UTC manipulation of dates for to and froms
|
Add UTC manipulation of dates for to and froms
|
JavaScript
|
mit
|
sussol/mobile,sussol/mobile,sussol/mobile,sussol/mobile
|
d3c58065a12e493e0a30bcdb9d19dcfebebff83e
|
src/misterT/skills/warnAboutMissingTimesheet.js
|
src/misterT/skills/warnAboutMissingTimesheet.js
|
'use strict';
const moment = require('moment')
const _ = require('lodash')
const lastBusinessDay = require('../../businessDays').last
module.exports = ({ getChatUsers, getWorkEntries }) => {
return async function warnAboutMissingTimesheet () {
const day = lastBusinessDay(moment()).format('YYYY-MM-DD');
const users = await getChatUsers()
const workEntries = users.map(slackId => {
return (async function () {
const workEntries = await getWorkEntries(slackId, day, day)
const hours = _.reduce(workEntries, function (sum, entry) {
return sum + entry[ 'hours' ]
}, 0);
if (hours < 8) {
return {
text: `Ieri ha segnato solo ${hours} ore\n, non è che ti sei dimenticato di qualcosa?`,
channel: slackId
}
}
}())
})
return _.filter(await Promise.all(workEntries))
}
}
|
'use strict';
const moment = require('moment')
const _ = require('lodash')
const lastBusinessDay = require('../../businessDays').last
module.exports = ({ getChatUsers, getWorkEntries }) => {
return async function warnAboutMissingTimesheet () {
const day = lastBusinessDay(moment()).format('YYYY-MM-DD');
const users = await getChatUsers()
const workEntries = users.map(slackId => {
return (async function () {
const workEntries = await getWorkEntries(slackId, day, day)
const hours = _.reduce(workEntries, function (sum, entry) {
return sum + entry[ 'hours' ]
}, 0);
if (hours < 8) {
return {
text: `Ieri ha segnato solo ${hours} ore, non è che ti sei dimenticato di qualcosa?\n Puoi <https://report.ideato.it/|aggiornare il timesheet>`,
channel: slackId
}
}
}())
})
return _.filter(await Promise.all(workEntries))
}
}
|
Add link to report from hell
|
Add link to report from hell
|
JavaScript
|
mit
|
ideatosrl/mister-t
|
fe0a75812fd1e26ad45cf2457230641ed12af605
|
static/js/base.js
|
static/js/base.js
|
'use strict';
if (!waitlist) {
var waitlist = {};
}
waitlist.base = (function(){
function getMetaData (name) {
return $('meta[name="'+name+'"]').attr('content');
}
function displayMessage(message, type, html=false) {
var alertHTML = $($.parseHTML(`<div class="alert alert-dismissible alert-${type}" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<p class="text-xs-center"></p>
</div>`));
var textContainer = $('.text-xs-center', alertHTML);
if (html === true) {
textContainer.html(message);
} else {
textContainer.text(message);
}
var alertArea = $('#alert-area-base');
alertArea.append(alertHTML);
}
return {
getMetaData: getMetaData,
displayMessage: displayMessage
};
})();
|
'use strict';
if (!waitlist) {
var waitlist = {};
}
waitlist.base = (function(){
function getMetaData (name) {
return $('meta[name="'+name+'"]').attr('content');
}
function displayMessage(message, type, html=false, id=false) {
var alertHTML = $($.parseHTML(`<div class="alert alert-dismissible alert-${type}" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<p class="text-xs-center"></p>
</div>`));
var textContainer = $('.text-xs-center', alertHTML);
if (id !== false) {
alertHTML.attr("id", id);
}
if (html === true) {
textContainer.html(message);
} else {
textContainer.text(message);
}
var alertArea = $('#alert-area-base');
alertArea.append(alertHTML);
}
return {
getMetaData: getMetaData,
displayMessage: displayMessage
};
})();
|
Update alert to allow for setting an id.
|
Update alert to allow for setting an id.
|
JavaScript
|
mit
|
SpeedProg/eve-inc-waitlist,SpeedProg/eve-inc-waitlist,SpeedProg/eve-inc-waitlist,SpeedProg/eve-inc-waitlist
|
d34f4ef6b96090913839b158423d912bd18a585f
|
release.js
|
release.js
|
var shell = require('shelljs');
if (exec('git status --porcelain').output != '') {
console.error('Git working directory not clean.');
process.exit(2);
}
var versionIncrement = process.argv[process.argv.length -1];
if (versionIncrement != 'major' && versionIncrement != 'minor' && versionIncrement != 'patch') {
console.error('Usage: node release.js major|minor|patch');
process.exit(1);
}
exec('npm version ' + versionIncrement);
exec('npm test');
exec('git push');
exec('git push --tags');
exec('npm publish');
function exec(cmd) {
var ret = shell.exec(cmd, { silent : true });
if (ret.code != 0) {
console.error(ret.output);
process.exit(1);
}
return ret;
}
|
var shell = require('shelljs');
if (exec('git status --porcelain').stdout != '') {
console.error('Git working directory not clean.');
process.exit(2);
}
var versionIncrement = process.argv[process.argv.length -1];
if (versionIncrement != 'major' && versionIncrement != 'minor' && versionIncrement != 'patch') {
console.error('Usage: node release.js major|minor|patch');
process.exit(1);
}
exec('npm version ' + versionIncrement);
exec('npm test');
exec('git push');
exec('git push --tags');
exec('npm publish');
function exec(cmd) {
var ret = shell.exec(cmd, { silent : true });
if (ret.code != 0) {
console.error(ret.output);
process.exit(1);
}
return ret;
}
|
Fix checking of exec output
|
Fix checking of exec output
|
JavaScript
|
isc
|
saintedlama/git-visit
|
d4673dcb8a1b07edec917c390311b20b22fd91c7
|
app/javascript/app/components/scroll-to-highlight-index/scroll-to-highlight-index.js
|
app/javascript/app/components/scroll-to-highlight-index/scroll-to-highlight-index.js
|
import { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { scrollIt } from 'utils/scroll';
class ScrollToHighlightIndex extends PureComponent {
// eslint-disable-line react/prefer-stateless-function
componentDidMount() {
setTimeout(this.handleScroll, 150);
}
componentWillReceiveProps(nextProps) {
if (nextProps.content.html !== this.props.content.html) {
setTimeout(this.handleScroll, 150);
}
}
handleScroll = () => {
const { idx, targetElementsSelector } = this.props;
const e = idx
? document.querySelectorAll(targetElementsSelector)[idx]
: document.querySelectorAll(targetElementsSelector)[0];
if (e) {
scrollIt(document.querySelector(targetElementsSelector), 300, 'smooth');
}
};
render() {
return null;
}
}
ScrollToHighlightIndex.propTypes = {
idx: PropTypes.string,
targetElementsSelector: PropTypes.string,
content: PropTypes.object
};
export default ScrollToHighlightIndex;
|
import { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { scrollIt } from 'utils/scroll';
class ScrollToHighlightIndex extends PureComponent {
// eslint-disable-line react/prefer-stateless-function
componentDidMount() {
setTimeout(this.handleScroll, 150);
}
componentWillReceiveProps(nextProps) {
if (nextProps.content.html !== this.props.content.html) {
setTimeout(this.handleScroll, 150);
}
}
handleScroll = () => {
const { idx, targetElementsSelector } = this.props;
const target = idx
? document.querySelectorAll(targetElementsSelector)[idx]
: document.querySelectorAll(targetElementsSelector)[0];
if (target) {
scrollIt(target, 300, 'smooth');
}
};
render() {
return null;
}
}
ScrollToHighlightIndex.propTypes = {
idx: PropTypes.string,
targetElementsSelector: PropTypes.string,
content: PropTypes.object
};
export default ScrollToHighlightIndex;
|
Use index to scroll to desired target
|
Use index to scroll to desired target
|
JavaScript
|
mit
|
Vizzuality/climate-watch,Vizzuality/climate-watch,Vizzuality/climate-watch,Vizzuality/climate-watch
|
98cb394af2d4244c85ddaf2e5ef02fa4e1c9c2c1
|
templates/localise.js
|
templates/localise.js
|
function localizeHtmlPage() {
//Localize by replacing __MSG_***__ meta tags
var objects = document.querySelectorAll('.message');
for (var j = 0; j < objects.length; j++) {
var obj = objects[j];
var valStrH = obj.innerHTML.toString();
var valNewH = valStrH.replace(/__MSG_(\w+)__/g, function (match, v1) {
return v1 ? browser.i18n.getMessage(v1) : "";
});
if (valNewH != valStrH) {
obj.innerHTML = valNewH;
}
}
}
localizeHtmlPage();
|
function localizeHtmlPage() {
//Localize by replacing __MSG_***__ meta tags
var objects = document.querySelectorAll('.message');
for (var j = 0; j < objects.length; j++) {
var obj = objects[j];
var valStrH = obj.innerHTML.toString();
var valNewH = valStrH.replace(/__MSG_(\w+)__/g, function (match, v1) {
return v1 ? browser.i18n.getMessage(v1) : "";
});
if (valNewH != valStrH) {
obj.textContent = valNewH;
}
}
}
localizeHtmlPage();
|
Change to using textContent instead of innerHTML
|
Change to using textContent instead of innerHTML
|
JavaScript
|
mit
|
codefisher/mozbutton_sdk,codefisher/mozbutton_sdk
|
1a43f902beb82336e9f66dc75b1768721dc419c0
|
frontend/app/components/modal-dialog.js
|
frontend/app/components/modal-dialog.js
|
import Ember from "ember";
export default Ember.Component.extend({
didInsertElement: function() {
// show the dialog
this.$('.modal').modal('show');
// send the according action after it has been hidden again
var _this = this;
this.$('.modal').one('hidden.bs.modal', function() {
Ember.run(function() {
// send the according action after it has been hidden
_this.sendAction("dismiss");
});
});
},
showDoNotAccept: Ember.computed.notEmpty('doNotAcceptText'),
actions: {
accept: function() {
this.sendAction("accept");
},
doNotAccept: function() {
this.sendAction("doNotAccept");
},
cancel: function() {
this.sendAction("cancel");
}
}
});
|
import Ember from "ember";
export default Ember.Component.extend({
didInsertElement: function() {
// show the dialog
this.$('.modal').modal('show');
// send the according action after it has been hidden again
var _this = this;
this.$('.modal').one('hidden.bs.modal', function() {
Ember.run(function() {
// send the according action after it has been hidden
_this.sendAction("dismiss");
});
});
},
willDestroyElement: function() {
this.$('.modal').modal('hide');
},
showDoNotAccept: Ember.computed.notEmpty('doNotAcceptText'),
actions: {
accept: function() {
this.sendAction("accept");
},
doNotAccept: function() {
this.sendAction("doNotAccept");
},
cancel: function() {
this.sendAction("cancel");
}
}
});
|
Hide dialog when leaving route
|
Hide dialog when leaving route
|
JavaScript
|
apache-2.0
|
uboot/stromx-web,uboot/stromx-web,uboot/stromx-web
|
717f919a0ddc00e989889ac1957209f758d3ce96
|
test/banterbot.js
|
test/banterbot.js
|
//
// Copyright (c) 2016-2017 DrSmugleaf
//
"use strict"
require("dotenv").config({ path: __dirname + "/../.env" })
const constants = require("../libs/util/constants")
const client = require("../banterbot").client
before(function(done) {
global.constants = constants
global.client = client
client.on("dbReady", () => {
global.guild = client.guilds.get("260158980343463937")
global.guild.createChannel("mocha-tests", "text").then((channel) => {
global.channel = channel
done()
})
})
})
beforeEach(function(done) {
setTimeout(done, 2000)
})
after(function() {
return global.channel.delete()
})
|
//
// Copyright (c) 2016-2017 DrSmugleaf
//
"use strict"
require("dotenv").config({ path: __dirname + "/../.env" })
const constants = require("../libs/util/constants")
const client = require("../banterbot").client
before(function(done) {
global.constants = constants
global.client = client
client.on("dbReady", () => {
global.guild = client.guilds.get("260158980343463937")
global.guild.createChannel("test", "text").then((channel) => {
global.channel = channel
done()
})
})
})
beforeEach(function(done) {
setTimeout(done, 2000)
})
after(function() {
return global.channel.delete()
})
|
Change mocha tests discord channel name to test
|
Change mocha tests discord channel name to test
|
JavaScript
|
apache-2.0
|
DrSmugleaf/Banter-Bot,DrSmugleaf/Banter-Bot
|
6bfdb7fc09ad70b20fa4864fdde18db311fa3db9
|
src/main/web/florence/js/functions/_environment.js
|
src/main/web/florence/js/functions/_environment.js
|
function isDevOrSandpit () {
var hostname = window.location.hostname;
var env = {};
if(hostname.indexOf('develop') > -1) {
env.name = 'develop'
}
if(hostname.indexOf('sandpit') > -1) {
env.name = 'sandpit'
}
// if((hostname.indexOf('127') > -1) || (hostname.indexOf('localhost'))) {
// env.name = 'localhost'
// }
return env;
}
|
function isDevOrSandpit () {
var hostname = window.location.hostname;
var env = {};
if(hostname.indexOf('develop') > -1) {
env.name = 'develop'
}
if(hostname.indexOf('sandpit') > -1) {
env.name = 'sandpit'
}
// if((hostname.indexOf('127') > -1) || (hostname.indexOf('localhost')) > -1) {
// env.name = 'localhost'
// }
return env;
}
|
Check localhost domain to set env notification
|
Check localhost domain to set env notification
|
JavaScript
|
mit
|
ONSdigital/florence,ONSdigital/florence,ONSdigital/florence,ONSdigital/florence
|
1389db463184fcccbded21eec2ba2c61c6d16d91
|
tools/utils/gc.js
|
tools/utils/gc.js
|
import { throttle } from "underscore";
export const requestGarbageCollection =
// For this global function to be defined, the --expose-gc flag must
// have been passed to node at the bottom of the ../../meteor script,
// probably via the TOOL_NODE_FLAGS environment variable.
typeof global.gc === "function"
// Restrict actual garbage collections to once per 500ms.
? throttle(global.gc, 500)
: function () {};
|
import { throttle } from "underscore";
export const requestGarbageCollection =
// For this global function to be defined, the --expose-gc flag must
// have been passed to node at the bottom of the ../../meteor script,
// probably via the TOOL_NODE_FLAGS environment variable.
typeof global.gc === "function"
// Restrict actual garbage collections to once per second.
? throttle(global.gc, 1000)
: function () {};
|
Increase garbage collection throttling delay.
|
Increase garbage collection throttling delay.
May help with this problem, which seems to stem from too much GC:
https://github.com/meteor/meteor/pull/8728#issuecomment-337636773
If this isn't enough, we could include this commit in 1.6.1:
https://github.com/meteor/meteor/commit/5d212926e795bba714abc9ca2b86429eff2831dd
|
JavaScript
|
mit
|
Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor
|
e3389659239731bb5bb367061cc0dd113998097f
|
src/containers/NewsFeedContainer.js
|
src/containers/NewsFeedContainer.js
|
/* NewsFeedContainer.js
* Container for our NewsFeed as a view
* Dependencies: ActionTypes
* Modules: NewsActions, and NewsFeed
* Author: Tiffany Tse
* Created: July 29, 2017
*/
//import dependencie
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
//import modules
import { loadNews } from '../actions/NewsActions.js';
import NewsFeed from '../component/NewsFeed.js';
import { reshapeNewsData } from '../util/DataTransformations.js';
import { allNewsSelector } from '../selectors/NewsSelectors.js';
//create state for mapStateToProps which exposes state tree's news property as a prop
//to NewsFeed called news
const mapStateToProps = state ({
news: reshapeNewsData(state.news);
});
//create the dispatcher for actions as a prop
const mapDispatchToProps = dispatch => (
bindActionCreators({ loadNews}, dispatch)
);
//export mapStateToProps and mapDispatchToProps as props to to newsFeed
export default connect(mapStateToProps, mapDispatchToProps)(NewsFeed);
|
/* NewsFeedContainer.js
* Container for our NewsFeed as a view
* Dependencies: ActionTypes
* Modules: NewsActions, and NewsFeed
* Author: Tiffany Tse
* Created: July 29, 2017
*/
//import dependencie
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
//import modules
import { loadNews } from '../actions/NewsActions.js';
import NewsFeed from '../component/NewsFeed.js';
import { reshapeNewsData } from '../util/DataTransformations.js';
import { allNewsSelector } from '../selectors/NewsSelectors.js';
//create state for mapStateToProps which exposes state tree's news property as a prop
//to NewsFeed called news
const mapStateToProps = state ({
news: allNewsSelector(state);
});
//create the dispatcher for actions as a prop
const mapDispatchToProps = dispatch => (
bindActionCreators({ loadNews}, dispatch)
);
//export mapStateToProps and mapDispatchToProps as props to to newsFeed
export default connect(mapStateToProps, mapDispatchToProps)(NewsFeed);
|
Update reshapeNewsData to use allNewsSelector and pass state to it
|
Update reshapeNewsData to use allNewsSelector and pass state to it
|
JavaScript
|
mit
|
titse/NYTimes-Clone,titse/NYTimes-Clone,titse/NYTimes-Clone
|
68f46c73a0de920803aebb9db5b78a28e458ea9e
|
lib/api/reddit.js
|
lib/api/reddit.js
|
/*jshint node:true */
"use strict";
var request = require('request');
var reddit = {
top: function (subreddit, callback) {
var url = "http://www.reddit.com/r/" + subreddit + "/top.json";
var currentTime = (new Date()).getTime();
request
.get({url: url + "?bust=" + currentTime, json: true}, function (error, response, body) {
if (!error && response.statusCode == 200) {
body.url = url;
body.timestamp = currentTime;
if (callback) {
callback(body);
}
}
});
}
};
module.exports = reddit;
|
/*jshint node:true */
"use strict";
var request = require('request');
var reddit = {
top: function (subreddit, callback) {
var url = "http://www.reddit.com/r/" + subreddit + "/top.json";
var currentTime = new Date();
request
.get({url: url + "?bust=" + currentTime, json: true}, function (error, response, body) {
if (!error && response.statusCode == 200) {
body.url = url;
body.date = {
"timestamp": currentTime.getTime(),
"year": currentTime.getUTCFullYear(),
"month": currentTime.getUTCMonth() + 1, // Date.getUTCMonth is 0 indexed... wtf?
"day": currentTime.getUTCDate(),
"hour": currentTime.getUTCHours(),
"minute": currentTime.getUTCMinutes()
};
if (callback) {
callback(body);
}
}
});
}
};
module.exports = reddit;
|
Expand timestamp json for db indicies
|
Expand timestamp json for db indicies
|
JavaScript
|
mit
|
netherwarhead/netherwarhead,netherwarhead/baconytics2,netherwarhead/netherwarhead,netherwarhead/baconytics2,netherwarhead/baconytics2,netherwarhead/netherwarhead
|
701feebf107a55a5720aca2ee52d40d421647cbc
|
js/app/app.js
|
js/app/app.js
|
App = Ember.Application.create();
// Add routes here
App.Router.map(function() {
// Atoms (Components)
this.resource('atoms', function() {
// Sub-routes here
this.route('hs-button');
});
// Molecules (Modules)
this.resource('molecules', function() {
// Sub-routes here
});
// Organisms (Layouts)
this.resource('organisms', function() {
// Sub-routes here
});
// Templates
this.resource('templates', function() {
// Sub-routes here
});
});
// Use this mixin for high-level atomic routes
App.AtomicRouteMixin = Ember.Mixin.create({
renderTemplate: function() {
this.render('atomic');
}
});
// Modify high-level routes to use the same template
App.AtomsRoute = Ember.Route.extend(App.AtomicRouteMixin);
App.MoleculesRoute = Ember.Route.extend(App.AtomicRouteMixin);
App.OrganismsRoute = Ember.Route.extend(App.AtomicRouteMixin);
App.TemplatesRoute = Ember.Route.extend(App.AtomicRouteMixin);
|
Ember.Route.reopen({
beforeModel: function(transition) {
if (transition) {
transition.then(function() {
Ember.run.scheduleOnce('afterRender', this, function() {
$(document).foundation();
});
});
}
}
});
App = Ember.Application.create();
// Add routes here
App.Router.map(function() {
// Atoms (Components)
this.resource('atoms', function() {
// Sub-routes here
this.route('hs-button');
});
// Molecules (Modules)
this.resource('molecules', function() {
// Sub-routes here
});
// Organisms (Layouts)
this.resource('organisms', function() {
// Sub-routes here
});
// Templates
this.resource('templates', function() {
// Sub-routes here
});
});
// Use this mixin for high-level atomic routes
App.AtomicRouteMixin = Ember.Mixin.create({
renderTemplate: function() {
this.render('atomic');
}
});
// Modify high-level routes to use the same template
App.AtomsRoute = Ember.Route.extend(App.AtomicRouteMixin);
App.MoleculesRoute = Ember.Route.extend(App.AtomicRouteMixin);
App.OrganismsRoute = Ember.Route.extend(App.AtomicRouteMixin);
App.TemplatesRoute = Ember.Route.extend(App.AtomicRouteMixin);
|
Initialize Foundation after every route transition
|
Initialize Foundation after every route transition
|
JavaScript
|
mit
|
jneurock/pattern-lib
|
f7108b212c596ba5c3f2bbf0184d186714130e93
|
app/assets/javascripts/ng-app/services/control-panel-service.js
|
app/assets/javascripts/ng-app/services/control-panel-service.js
|
angular.module('myApp')
.factory('ctrlPanelService', ['$rootScope', 'userService', 'locationService','transactionService',
function($rootScope, $userService, locationService, transactionService) {
var settings = { users: null, userId: null };
settings.updateUsers = function(users) {
settings.users = users;
$rootScope.$broadcast('updateUsers');
}
settings.setUserId = function(userId) {
settings.userId = userId;
$rootScope.$broadcast('updateUserId');
}
// define generic submit event for other controllers to use
settings.submit = function() { $rootScope.$broadcast('submit') };
return settings;
}]);
|
angular.module('myApp')
.factory('ctrlPanelService', ['$rootScope', 'userService', 'locationService','transactionService',
function($rootScope, $userService, locationService, transactionService) {
// this service is responsible for storing and broadcasting changes
// to any of the control panel's settings. These settings are intended
// to be available to the entire app to be synced with whatever portion
// uses them. For example, transactions tab in charts will react to a
// selected userId via 'updateUserId' event on the $rootScope.
var settings = { users: null, userId: null };
settings.updateUsers = function(users) {
settings.users = users;
$rootScope.$broadcast('updateUsers');
}
settings.setUserId = function(userId) {
settings.userId = userId;
$rootScope.$broadcast('updateUserId');
}
// define generic submit event for other controllers to use
settings.submit = function() { $rootScope.$broadcast('submit') };
return settings;
}]);
|
Add comments for ctrlPanelService and its role
|
Add comments for ctrlPanelService and its role
|
JavaScript
|
mit
|
godspeedyoo/Breeze-Mapper,godspeedyoo/Breeze-Mapper,godspeedyoo/Breeze-Mapper
|
8a60c3bd25bd166d3e4c8a1bf6beb825bd84df81
|
gulp/psk-config.js
|
gulp/psk-config.js
|
module.exports = {
// Autoprefixer
autoprefixer: {
// https://github.com/postcss/autoprefixer#browsers
browsers: [
'Explorer >= 10',
'ExplorerMobile >= 10',
'Firefox >= 30',
'Chrome >= 34',
'Safari >= 7',
'Opera >= 23',
'iOS >= 7',
'Android >= 4.4',
'BlackBerry >= 10'
]
},
// BrowserSync
browserSync: {
browser: 'default', // or ["google chrome", "firefox"]
https: false, // Enable https for localhost development.
notify: false, // The small pop-over notifications in the browser.
port: 9000
},
// GitHub Pages
ghPages: {
branch: 'gh-pages',
domain: 'polymer-starter-kit.startpolymer.org', // change it!
origin: 'origin'
},
// PageSpeed Insights
// Please feel free to use the `nokey` option to try out PageSpeed
// Insights as part of your build process. For more frequent use,
// we recommend registering for your own API key. For more info:
// https://developers.google.com/speed/docs/insights/v1/getting_started
pageSpeed: {
key: '', // need uncomment in task
nokey: true,
site: 'http://polymer-starter-kit.startpolymer.org', // change it!
strategy: 'mobile' // or desktop
}
};
|
module.exports = {
// Autoprefixer
autoprefixer: {
// https://github.com/postcss/autoprefixer#browsers
browsers: [
'Explorer >= 10',
'ExplorerMobile >= 10',
'Firefox >= 30',
'Chrome >= 34',
'Safari >= 7',
'Opera >= 23',
'iOS >= 7',
'Android >= 4.4',
'BlackBerry >= 10'
]
},
// BrowserSync
browserSync: {
browser: 'default', // or ["google chrome", "firefox"]
https: false, // Enable https for localhost development.
notify: false, // The small pop-over notifications in the browser.
port: 9000
},
// GitHub Pages
ghPages: {
branch: 'gh-pages',
domain: 'polymer-starter-kit.startpolymer.org', // change it!
origin: 'origin'
},
// Metalsmith
metalsmith: {
configFile: './psa-config.yaml'
},
// PageSpeed Insights
// Please feel free to use the `nokey` option to try out PageSpeed
// Insights as part of your build process. For more frequent use,
// we recommend registering for your own API key. For more info:
// https://developers.google.com/speed/docs/insights/v1/getting_started
pageSpeed: {
key: '', // need uncomment in task
nokey: true,
site: 'http://polymer-starter-kit.startpolymer.org', // change it!
strategy: 'mobile' // or desktop
}
};
|
Add metalsmith config to gulp config
|
Add metalsmith config to gulp config
|
JavaScript
|
mit
|
StartPolymer/polymer-static-app,StartPolymer/polymer-static-app
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.