commit
stringlengths 40
40
| old_file
stringlengths 4
236
| new_file
stringlengths 4
236
| old_contents
stringlengths 1
3.26k
| new_contents
stringlengths 16
4.43k
| subject
stringlengths 16
624
| message
stringlengths 17
3.29k
| lang
stringclasses 5
values | license
stringclasses 13
values | repos
stringlengths 5
91.5k
|
|---|---|---|---|---|---|---|---|---|---|
d40bead054b0883ff59ae6ddd311bf93c5da6de3
|
public/js/scripts.js
|
public/js/scripts.js
|
$(document).ready(function(){
$('.datepicker').pickadate({
onSet: function (ele) {
if(ele.select){
this.close();
}
}
});
$('.timepicker').pickatime({
min: [7,30],
max: [19,0],
interval: 15,
onSet: function (ele) {
if(ele.select){
this.close();
}
}
});
$('select').material_select();
});
|
$(document).ready(function(){
$('.datepicker').pickadate({
onSet: function (ele) {
if(ele.select){
this.close();
}
},
min: true
});
$('.timepicker').pickatime({
min: [7,30],
max: [19,0],
interval: 15,
onSet: function (ele) {
if(ele.select){
this.close();
}
}
});
$('select').material_select();
});
|
Disable the selection of past dates
|
Disable the selection of past dates
|
JavaScript
|
mit
|
warrenca/silid,warrenca/silid,warrenca/silid,warrenca/silid
|
e5b67dcf51ee97b6890b06a5d17b890bbf616081
|
bin/index.js
|
bin/index.js
|
#!/usr/bin/env node
const fs = require('fs')
const path = require('path')
const concise = require('../src/index')
const command = {
name: process.argv[2],
input: process.argv[3],
output: process.argv[4]
}
const build = (input, output) => {
concise.process(fs.readFileSync(input, 'utf8'), { from: input }).then(css => {
// Create all the parent directories if required
fs.mkdirSync(path.dirname(output), { recursive: true })
// Write the CSS
fs.writeFile(output, css, err => {
if (err) throw err
console.log(`File written: ${output}\nFrom: ${input}`);
})
});
};
const watch = path => {
console.log(`Currently watching for changes in: ${path}`);
fs.watch(path, {recursive: true}, (eventType, filename) => {
console.log(`${eventType.charAt(0).toUpperCase() + eventType.slice(1)} in: ${filename}`);
build();
});
};
switch (command.name) {
case 'compile':
build(command.input, command.output);
break
case 'watch':
build(command.input, command.output);
watch(path.dirname(command.input));
break
default:
console.log('Unknown command')
break
}
|
#!/usr/bin/env node
const fs = require('fs')
const path = require('path')
const concise = require('../src/index')
const command = {
name: process.argv[2],
input: process.argv[3],
output: process.argv[4]
}
const build = (input, output) => {
concise.process(fs.readFileSync(input, 'utf8'), { from: input }).then(result => {
// Create all the parent directories if required
fs.mkdirSync(path.dirname(output), { recursive: true })
// Write the CSS
fs.writeFile(output, result.css, err => {
if (err) throw err
console.log(`File written: ${output}\nFrom: ${input}`);
})
});
};
const watch = path => {
console.log(`Currently watching for changes in: ${path}`);
fs.watch(path, {recursive: true}, (eventType, filename) => {
console.log(`${eventType.charAt(0).toUpperCase() + eventType.slice(1)} in: ${filename}`);
build();
});
};
switch (command.name) {
case 'compile':
build(command.input, command.output);
break
case 'watch':
build(command.input, command.output);
watch(path.dirname(command.input));
break
default:
console.log('Unknown command')
break
}
|
Use the `css` property of `Result`
|
Use the `css` property of `Result`
|
JavaScript
|
mit
|
ConciseCSS/concise.css
|
a00a62f147489141cfb7d3fb2d10e08e8f161e01
|
demo/js/components/workbench-new.js
|
demo/js/components/workbench-new.js
|
angular.module('yds').directive('ydsWorkbenchNew', ['$ocLazyLoad', '$timeout', '$window', 'Data', 'Basket', 'Workbench',
function ($ocLazyLoad, $timeout, $window, Data, Basket, Workbench) {
return {
restrict: 'E',
scope: {
lang: '@',
userId: '@'
},
templateUrl: ((typeof Drupal != 'undefined') ? Drupal.settings.basePath + Drupal.settings.yds_project.modulePath + '/' : '') + 'templates/workbench-new.html',
link: function (scope, element) {
scope.ydsAlert = "";
var editorContainer = angular.element(element[0].querySelector('.highcharts-editor-container'));
//if userId is undefined or empty, stop the execution of the directive
if (_.isUndefined(scope.userId) || scope.userId.trim().length == 0) {
scope.ydsAlert = "The YDS component is not properly configured." +
"Please check the corresponding documentation section";
return false;
}
//check if the language attr is defined, else assign default value
if (_.isUndefined(scope.lang) || scope.lang.trim() == "")
scope.lang = "en";
// Load the required CSS & JS files for the Editor
$ocLazyLoad.load([
"css/highcharts-editor.min.css",
"lib/highcharts-editor.js"
]).then(function () {
// Start the Highcharts Editor
highed.ready(function () {
highed.Editor(editorContainer[0]);
});
});
}
}
}
]);
|
angular.module('yds').directive('ydsWorkbenchNew', ['$ocLazyLoad', '$timeout', '$window', 'Data', 'Basket', 'Workbench',
function ($ocLazyLoad, $timeout, $window, Data, Basket, Workbench) {
return {
restrict: 'E',
scope: {
lang: '@',
userId: '@'
},
templateUrl: ((typeof Drupal != 'undefined') ? Drupal.settings.basePath + Drupal.settings.yds_project.modulePath + '/' : '') + 'templates/workbench-new.html',
link: function (scope, element) {
scope.ydsAlert = "";
var editorContainer = angular.element(element[0].querySelector('.highcharts-editor-container'));
//if userId is undefined or empty, stop the execution of the directive
if (_.isUndefined(scope.userId) || scope.userId.trim().length == 0) {
scope.ydsAlert = "The YDS component is not properly configured." +
"Please check the corresponding documentation section";
return false;
}
//check if the language attr is defined, else assign default value
if (_.isUndefined(scope.lang) || scope.lang.trim() == "")
scope.lang = "en";
var editorOptions = {
features: "import templates customize export"
};
// Load the required CSS & JS files for the Editor
$ocLazyLoad.load([
"css/highcharts-editor.min.css",
"lib/highcharts-editor.js"
]).then(function () {
// Start the Highcharts Editor
highed.ready(function () {
highed.Editor(editorContainer[0], editorOptions);
});
});
}
}
}
]);
|
Disable steps that are not needed in Highcharts Editor
|
Disable steps that are not needed in Highcharts Editor
|
JavaScript
|
apache-2.0
|
YourDataStories/components-visualisation,YourDataStories/components-visualisation,YourDataStories/components-visualisation
|
7b1ee57b1fc73b6bf75818561a2f5bba39b50344
|
src/scripts/main.js
|
src/scripts/main.js
|
console.log('main.js');
// Load Css async w LoadCSS & +1 polyfill / https://www.npmjs.com/package/fg-loadcss?notice=MIvGLZ2qXNAEF8AM1kvyFWL8p-1MwaU7UpJd8jcG
var stylesheet = loadCSS( "styles/main.css" );
onloadCSS( stylesheet, function() {
console.log( "LoadCSS > Stylesheet has loaded. Yay !" );
$('.no-fouc').fadeIn(); // Jquery animation
});
// Load Hyphenopoly plugins, manage font césure & text FOUC
// Need to be loaded beofre HyphenopolyLoader, cf. gulpfile paths.scripts.src
var Hyphenopoly = {
require: {
"en-us": "hyphenation"
},
paths: {
patterndir: 'assets/hyphenopoly/patterns/',
maindir: 'assets/hyphenopoly/'
},
setup: {
classnames: {
"hyphenate": {}
}
}
};
|
console.log('main.js');
// Load Css async w LoadCSS & +1 polyfill / https://www.npmjs.com/package/fg-loadcss?notice=MIvGLZ2qXNAEF8AM1kvyFWL8p-1MwaU7UpJd8jcG
var stylesheet = loadCSS( "styles/main.css" );
onloadCSS( stylesheet, function() {
console.log( "LoadCSS > Stylesheet has loaded. Yay !" );
// + No Fouc management
$('.no-fouc').fadeIn(); // Lovely Jquery animation on load
// Fouc out management
$('a').click(function(e) {
e.preventDefault();
newLocation = this.href;
$('body').fadeOut(200, function() {
window.location = newLocation;
});
});
});
// Load Hyphenopoly plugins, manage font césure & text FOUC
// Need to be loaded beofre HyphenopolyLoader, cf. gulpfile paths.scripts.src
var Hyphenopoly = {
require: {
"en-us": "hyphenation"
},
paths: {
patterndir: 'assets/hyphenopoly/patterns/',
maindir: 'assets/hyphenopoly/'
},
setup: {
classnames: {
"hyphenate": {}
}
}
};
|
Add / Fouc out (on link clic)
|
Add / Fouc out (on link clic)
|
JavaScript
|
mit
|
youpiwaza/chaos-boilerplate,youpiwaza/chaos-boilerplate
|
3908db4cabd5193aa3798a48277369b86b786f73
|
tests/nock.js
|
tests/nock.js
|
/**
* Copyright (c) 2015 IBM Cloudant, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
function noop() {
return this;
}
function nock_noop() {
// Return a completely inert nock-compatible object.
return {head:noop, get:noop, post:noop, put:noop, 'delete':noop, reply:noop, filteringPath:noop, done:noop};
}
if (process.env.NOCK_OFF) {
var nock = nock_noop;
} else {
var nock = require('nock');
}
module.exports = nock;
|
/**
* Copyright (c) 2015 IBM Cloudant, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
function noop() {
return this;
}
function nock_noop() {
// Return a completely inert nock-compatible object.
return {head:noop, get:noop, post:noop, put:noop, 'delete':noop, reply:noop, filteringPath:noop, done:noop, query:noop};
}
if (process.env.NOCK_OFF) {
var nock = nock_noop;
} else {
var nock = require('nock');
}
module.exports = nock;
|
Add the .query() method to the Nock noop
|
Add the .query() method to the Nock noop
|
JavaScript
|
apache-2.0
|
KimStebel/nodejs-cloudant,cloudant/nodejs-cloudant,cloudant/nodejs-cloudant
|
ae166fa6cd8ef9c8a73ff1b9e7a1e64503e6061e
|
src/js/portfolio.js
|
src/js/portfolio.js
|
var observer = lozad(".lazy", {
rootMargin: "25%",
threshold: 0
});
observer.observe();
|
import IntersectionObserver from 'intersection-observer';
import Lozad from 'lozad';
let observer = Lozad('.lazy', {
rootMargin: '25%',
threshold: 0
});
observer.observe();
|
Use ES6 import for Portfolio JS dependencies
|
Use ES6 import for Portfolio JS dependencies
|
JavaScript
|
mit
|
stevecochrane/stevecochrane.com,stevecochrane/stevecochrane.com
|
a7a88cac0976c49e05fa9ea278320749f6ef1ba0
|
rollup.config-dev.js
|
rollup.config-dev.js
|
"use strict";
const baseConfig = require("./rollup.config");
const plugin = require("./plugin");
const path = require("path");
module.exports = baseConfig.map((config, index) => {
config.plugins.push(plugin({
open: true,
filename: `stats.${index}.html`,
template: getTemplateType(config)
}));
return config;
});
function getTemplateType({ input }) {
const filename = path.basename(input, path.extname(input));
const [, templateType] = filename.split("-");
return templateType;
}
|
"use strict";
const baseConfig = require("./rollup.config");
const plugin = require("./plugin");
const path = require("path");
module.exports = baseConfig.map(config => {
const templateType = getTemplateType(config);
config.plugins.push(
plugin({
open: true,
filename: `stats.${templateType}.html`,
template: templateType
})
);
return config;
});
function getTemplateType({ input }) {
const filename = path.basename(input, path.extname(input));
const [, templateType] = filename.split("-");
return templateType;
}
|
Use template name for statts file name
|
Use template name for statts file name
|
JavaScript
|
mit
|
btd/rollup-plugin-visualizer,btd/rollup-plugin-visualizer
|
0d58435c37ad66fa5bea391672cb490c13e455f7
|
website/mcapp.projects/src/app/models/project.model.js
|
website/mcapp.projects/src/app/models/project.model.js
|
/*@ngInject*/
function ProjectModelService(projectsAPI) {
class Project {
constructor(id, name, owner) {
this.id = id;
this.name = name;
this.owner = owner;
this.samples_count = 0;
this.processes_count = 0;
this.experiments_count = 0;
this.files_count = 0;
this.description = "";
this.birthtime = 0;
this.mtime = 0;
}
static fromJSON(data) {
let p = new Project(data.id, data.name, data.owner);
p.samples_count = data.samples;
p.processes_count = data.processes;
p.experiments_count = data.experiments;
p.files_counts = data.files;
p.description = data.description;
p.birthtime = new Date(data.birthtime * 1000);
p.mtime = new Date(data.mtime * 1000);
p.users = data.users;
p.owner_details = data.owner_details;
return p;
}
static get(id) {
}
static getProjectsForCurrentUser() {
return projectsAPI.getAllProjects().then(
(projects) => projects.map(p => Project.fromJSON(p))
);
}
save() {
}
update() {
}
}
return Project;
}
angular.module('materialscommons').factory('ProjectModel', ProjectModelService);
|
/*@ngInject*/
function ProjectModelService(projectsAPI) {
class Project {
constructor(id, name, owner) {
this.id = id;
this.name = name;
this.owner = owner;
this.samples_count = 0;
this.processes_count = 0;
this.experiments_count = 0;
this.files_count = 0;
this.description = "";
this.birthtime = 0;
this.owner_details = {};
this.mtime = 0;
}
static fromJSON(data) {
let p = new Project(data.id, data.name, data.owner);
p.samples_count = data.samples;
p.processes_count = data.processes;
p.experiments_count = data.experiments;
p.files_counts = data.files;
p.description = data.description;
p.birthtime = new Date(data.birthtime * 1000);
p.mtime = new Date(data.mtime * 1000);
p.users = data.users;
p.owner_details = data.owner_details;
return p;
}
static get(id) {
}
static getProjectsForCurrentUser() {
return projectsAPI.getAllProjects().then(
(projects) => projects.map(p => Project.fromJSON(p))
);
}
save() {
}
update() {
}
}
return Project;
}
angular.module('materialscommons').factory('ProjectModel', ProjectModelService);
|
Add default value for owner_details.
|
Add default value for owner_details.
|
JavaScript
|
mit
|
materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org
|
0f9b5317e5a9ce68372d62c814dfbd260b748169
|
JavaScriptUI-DOM-TeamWork-Kinetic/Scripts/GameEngine.js
|
JavaScriptUI-DOM-TeamWork-Kinetic/Scripts/GameEngine.js
|
var GameEngine = ( function () {
function start(){
var x,
y,
color,
i,
j,
lengthBoard,
lengthField;
var players = [];
players.push( Object.create( GameObjects.Player ).init( 'First', 'white' ) );
players.push( Object.create( GameObjects.Player ).init( 'Second', 'black' ) );
var board = GameObjects.Board.init( players );
GameDraw.background();
lengthBoard = board.length;
for ( i = 0; i < lengthBoard; i += 1 ) {
lengthField = board[i].length;
for ( j = 0; j < lengthField; j += 1 ) {
x = i;
y = j;
color = board[i][j].color;
GameDraw.createCircle( x, y, color );
}
}
GameDraw.playGround();
}
return{
start: start,
}
}() )
|
var GameEngine = ( function () {
function start() {
var x,
y,
color,
i,
j,
lengthBoard,
lengthField;
var players = [];
players.push(Object.create(GameObjects.Player).init('First', 'white'));
players.push(Object.create(GameObjects.Player).init('Second', 'black'));
var board = GameObjects.Board.init(players);
GameDraw.background();
lengthBoard = board.length;
for (i = 0; i < lengthBoard; i += 1) {
lengthField = board[i].length;
for (j = 0; j < lengthField; j += 1) {
x = i;
y = j;
color = board[i][j].color;
GameDraw.createCircle(x, y, color);
}
}
GameDraw.playGround();
}
function update(){
// currentPlayer = GetCurrentPlayer - depending on player.isOnTurn or isFirstPlayerOnTurn
// flag hasThrownDice -> if not - throw dice(allowedMoves = diceResult, currentPlayerMoves = 0); else - continue
// if (currentPlayer.hasHitPiece) -> Call function(s) to deal with this situation.
// if can't put piece -> playerMoves = allowedMoves
// if ((currentPlayerMoves < allowedMoves) && hasMovedPiece (sets to true when called from onDrag event on piece)
// Subcases: move from position to position/ collect piece
// Call function(s) to deal with this situation. -> hasMovedPiece = false, currentPlayerMoves++;
// Missed logic?
// if current player has no pieces on the board -> He wins.
// if (playerMoves === allowedMoves) -> change player, hasThrownDice = false
}
return {
start: start,
update: update
};
}());
// All events will call GameEngine.Update() and GameDraw.Update().
|
Add pseudo code for game update according to game state.
|
Add pseudo code for game update according to game state.
|
JavaScript
|
mit
|
Vesper-Team/JavaScriptUI-DOM-TeamWork,Vesper-Team/JavaScriptUI-DOM-TeamWork
|
5390da989457ecff7dbfa94637c042e2d63f2841
|
examples/Node.js/exportTadpoles.js
|
examples/Node.js/exportTadpoles.js
|
require('../../index.js');
var scope = require('./Tadpoles');
scope.view.exportFrames({
amount: 200,
directory: __dirname,
onComplete: function() {
console.log('Done exporting.');
},
onProgress: function(event) {
console.log(event.percentage + '% complete, frame took: ' + event.delta);
}
});
|
require('../../node.js/');
var paper = require('./Tadpoles');
paper.view.exportFrames({
amount: 400,
directory: __dirname,
onComplete: function() {
console.log('Done exporting.');
},
onProgress: function(event) {
console.log(event.percentage + '% complete, frame took: ' + event.delta);
}
});
|
Clean up Node.js tadpoles example.
|
Clean up Node.js tadpoles example.
|
JavaScript
|
mit
|
0/paper.js,0/paper.js
|
8c1899b772a1083ce739e237990652b73b41a48d
|
src/apps/investment-projects/constants.js
|
src/apps/investment-projects/constants.js
|
const { concat } = require('lodash')
const currentYear = (new Date()).getFullYear()
const GLOBAL_NAV_ITEM = {
path: '/investment-projects',
label: 'Investment projects',
permissions: [
'investment.read_associated_investmentproject',
'investment.read_all_investmentproject',
],
order: 5,
}
const LOCAL_NAV = [
{
path: 'details',
label: 'Project details',
},
{
path: 'team',
label: 'Project team',
},
{
path: 'interactions',
label: 'Interactions',
permissions: [
'interaction.read_associated_investmentproject_interaction',
'interaction.read_all_interaction',
],
},
{
path: 'evaluation',
label: 'Evaluations',
},
{
path: 'audit',
label: 'Audit history',
},
{
path: 'documents',
label: 'Documents',
permissions: [
'investment.read_investmentproject_document',
],
},
]
const DEFAULT_COLLECTION_QUERY = {
estimated_land_date_after: `${currentYear}-04-05`,
estimated_land_date_before: `${currentYear + 1}-04-06`,
sortby: 'estimated_land_date:asc',
}
const APP_PERMISSIONS = concat(LOCAL_NAV, GLOBAL_NAV_ITEM)
module.exports = {
GLOBAL_NAV_ITEM,
LOCAL_NAV,
DEFAULT_COLLECTION_QUERY,
APP_PERMISSIONS,
}
|
const { concat } = require('lodash')
const GLOBAL_NAV_ITEM = {
path: '/investment-projects',
label: 'Investment projects',
permissions: [
'investment.read_associated_investmentproject',
'investment.read_all_investmentproject',
],
order: 5,
}
const LOCAL_NAV = [
{
path: 'details',
label: 'Project details',
},
{
path: 'team',
label: 'Project team',
},
{
path: 'interactions',
label: 'Interactions',
permissions: [
'interaction.read_associated_investmentproject_interaction',
'interaction.read_all_interaction',
],
},
{
path: 'evaluation',
label: 'Evaluations',
},
{
path: 'audit',
label: 'Audit history',
},
{
path: 'documents',
label: 'Documents',
permissions: [
'investment.read_investmentproject_document',
],
},
]
const DEFAULT_COLLECTION_QUERY = {
sortby: 'estimated_land_date:asc',
}
const APP_PERMISSIONS = concat(LOCAL_NAV, GLOBAL_NAV_ITEM)
module.exports = {
GLOBAL_NAV_ITEM,
LOCAL_NAV,
DEFAULT_COLLECTION_QUERY,
APP_PERMISSIONS,
}
|
Remove preset date filters in investment collection
|
Remove preset date filters in investment collection
|
JavaScript
|
mit
|
uktrade/data-hub-frontend,uktrade/data-hub-frontend,uktrade/data-hub-fe-beta2,uktrade/data-hub-fe-beta2,uktrade/data-hub-frontend
|
ec0c70f94319a898453252d4c4a7d8020e40081b
|
take_screenshots.js
|
take_screenshots.js
|
var target = UIATarget.localTarget();
function captureLocalizedScreenshot(name) {
var target = UIATarget.localTarget();
var model = target.model();
var rect = target.rect();
if (model.match(/iPhone/)) {
if (rect.size.height > 480) model = "iphone5";
else model = "iphone";
} else {
model = "ipad";
}
var orientation = "portrait";
if (rect.size.height < rect.size.width) orientation = "landscape";
var language = target.frontMostApp().
preferencesValueForKey("AppleLanguages")[0];
var parts = [model, orientation, language, name];
target.captureScreenWithName(parts.join("-"));
}
var window = target.frontMostApp().mainWindow();
captureLocalizedScreenshot("screen1");
window.buttons()[0].tap();
target.delay(0.5);
captureLocalizedScreenshot("screen2");
|
var target = UIATarget.localTarget();
function captureLocalizedScreenshot(name) {
var target = UIATarget.localTarget();
var model = target.model();
var rect = target.rect();
if (model.match(/iPhone/)) {
if (rect.size.height > 480) model = "iphone5";
else model = "iphone";
} else {
model = "ipad";
}
var orientation = "portrait";
if (rect.size.height < rect.size.width) orientation = "landscape";
var language = target.frontMostApp().
preferencesValueForKey("AppleLanguages")[0];
var parts = [language, model, orientation, name];
target.captureScreenWithName(parts.join("-"));
}
var window = target.frontMostApp().mainWindow();
captureLocalizedScreenshot("screen1");
window.buttons()[0].tap();
target.delay(0.5);
captureLocalizedScreenshot("screen2");
|
Put the language first in the screen shot generation
|
Put the language first in the screen shot generation
|
JavaScript
|
mit
|
wordpress-mobile/ui-screen-shooter,myhanhtran1999/UIScreenShot,jonathanpenn/ui-screen-shooter,duk42111/ui-screen-shooter,myhanhtran1999/UIScreenShot,wordpress-mobile/ui-screen-shooter,jonathanpenn/ui-screen-shooter,duk42111/ui-screen-shooter,myhanhtran1999/UIScreenShot
|
e771602c05add371bdb1d8d7082f87ae02715cae
|
app/commands.js
|
app/commands.js
|
var _ = require('underscore');
var util = require('util');
exports.setup = function() {
global.commands = {};
};
exports.handle = function(evt, msg) {
if(msg.slice(0, 1) != "!")
return;
var m = msg.match(/^!([A-Za-z0-9]+)(?: (.+))?$/);
if(!m)
return;
if(global.commands[m[1].lower()])
global.commands[m[1].lower()](evt, m[2]);
else
console.log("[commands.js] unknown command: '!%s'", m[1]);
};
|
var _ = require('underscore');
var util = require('util');
exports.setup = function() {
global.commands = {};
};
exports.handle = function(evt, msg) {
if(msg.slice(0, 1) != "!")
return;
var m = msg.match(/^!([A-Za-z0-9]+)(?: (.+))?$/);
if(!m)
return;
if(global.commands[m[1].toLowerCase()])
global.commands[m[1].toLowerCase()](evt, m[2]);
else
console.log("[commands.js] unknown command: '!%s'", m[1]);
};
|
Fix error. Thought this was Python for a second xD
|
Fix error. Thought this was Python for a second xD
|
JavaScript
|
mit
|
ircah/cah-js,ircah/cah-js
|
e50a7eec7a8d1cb130da08cdae8c022b82af0e35
|
app/controllers/sessionobjective.js
|
app/controllers/sessionobjective.js
|
import Ember from 'ember';
export default Ember.ObjectController.extend(Ember.I18n.TranslateableProperties, {
proxiedObjectives: [],
session: null,
course: null,
actions: {
addParent: function(parentProxy){
var newParent = parentProxy.get('content');
var self = this;
var sessionObjective = this.get('model');
sessionObjective.get('parents').then(function(ourParents){
newParent.get('children').then(function(newParentChildren){
newParentChildren.addObject(sessionObjective);
newParent.save().then(function(newParent){
ourParents.addObject(newParent);
sessionObjective.save().then(function(sessionObjective){
self.set('model', sessionObjective);
});
});
});
});
},
removeParent: function(parentProxy){
var self = this;
var removingParent = parentProxy.get('content');
var sessionObjective = this.get('model');
sessionObjective.get('parents').then(function(ourParents){
ourParents.removeObject(removingParent);
removingParent.get('children').then(function(children){
children.addObject(sessionObjective);
sessionObjective.save().then(function(sessionObjective){
self.set('model', sessionObjective);
removingParent.save();
});
});
});
}
}
});
|
import Ember from 'ember';
export default Ember.ObjectController.extend(Ember.I18n.TranslateableProperties, {
proxiedObjectives: [],
session: null,
course: null,
actions: {
addParent: function(parentProxy){
var newParent = parentProxy.get('content');
var sessionObjective = this.get('model');
sessionObjective.get('parents').then(function(ourParents){
ourParents.addObject(newParent);
newParent.get('children').then(function(newParentChildren){
newParentChildren.addObject(sessionObjective);
newParent.save();
sessionObjective.save();
});
});
},
removeParent: function(parentProxy){
var removingParent = parentProxy.get('content');
var sessionObjective = this.get('model');
sessionObjective.get('parents').then(function(ourParents){
ourParents.removeObject(removingParent);
removingParent.get('children').then(function(children){
children.removeObject(sessionObjective);
removingParent.save();
sessionObjective.save();
});
});
}
}
});
|
Fix issue with removing parent and speed up the process
|
Fix issue with removing parent and speed up the process
|
JavaScript
|
mit
|
stopfstedt/frontend,stopfstedt/frontend,jrjohnson/frontend,thecoolestguy/frontend,gabycampagna/frontend,thecoolestguy/frontend,jrjohnson/frontend,ilios/frontend,djvoa12/frontend,gboushey/frontend,djvoa12/frontend,gboushey/frontend,ilios/frontend,dartajax/frontend,dartajax/frontend,gabycampagna/frontend
|
6be5d442638239436104e48cd8977a7742c86c38
|
bin/repl.js
|
bin/repl.js
|
#!/usr/bin/env node
var repl = require('repl');
var Chrome = require('../');
Chrome(function (chrome) {
var chromeRepl = repl.start({
'prompt': 'chrome> '
});
chromeRepl.on('exit', function () {
chrome.close();
});
for (var domain in chrome) {
chromeRepl.context[domain] = chrome[domain];
}
});
|
#!/usr/bin/env node
var repl = require('repl');
var protocol = require('../lib/Inspector.json');
var Chrome = require('../');
Chrome(function (chrome) {
var chromeRepl = repl.start({
'prompt': 'chrome> '
});
chromeRepl.on('exit', function () {
chrome.close();
});
for (var domainIdx in protocol.domains) {
var domainName = protocol.domains[domainIdx].domain;
chromeRepl.context[domainName] = chrome[domainName];
}
});
|
Add protocol API only to the REPL context
|
Add protocol API only to the REPL context
|
JavaScript
|
mit
|
valaxy/chrome-remote-interface,cyrus-and/chrome-remote-interface,washtubs/chrome-remote-interface,cyrus-and/chrome-remote-interface
|
c4d7ea7e74d0f81b6b38a6623e47ccfee3a0fab1
|
src/locale/index.js
|
src/locale/index.js
|
import React from 'react'
import * as ReactIntl from 'react-intl'
import languageResolver from './languageResolver'
import messagesFetcher from './messagesFetcher'
function wrappedReactIntlProvider(language, localizedMessages) {
return function SanityIntlProvider(props) {
return <ReactIntl.IntlProvider locale={language} messages={localizedMessages} {...props} />
}
}
const SanityIntlProviderPromise = languageResolver.then(language => {
return messagesFetcher.fetchLocalizedMessages(language).then(localizedMessages => {
// TODO: ReactIntl.addLocaleData()
return {
ReactIntl,
SanityIntlProvider: wrappedReactIntlProvider(language, localizedMessages)
}
})
})
module.exports = SanityIntlProviderPromise
|
import React from 'react'
import * as ReactIntl from 'react-intl'
import languageResolver from './languageResolver'
import messagesFetcher from './messagesFetcher'
function wrappedReactIntlProvider(language, localizedMessages) {
return function SanityIntlProvider(props) {
return <ReactIntl.IntlProvider locale={language} messages={localizedMessages} {...props} />
}
}
const SanityIntlPromise = languageResolver.then(language => {
return messagesFetcher.fetchLocalizedMessages(language).then(localizedMessages => {
const languagePrexif = language.split('-')[0]
const localeData = require(`react-intl/locale-data/${languagePrexif}`)
ReactIntl.addLocaleData(localeData)
return {
ReactIntl,
SanityIntlProvider: wrappedReactIntlProvider(language, localizedMessages)
}
})
})
module.exports = SanityIntlPromise
|
Add localeData for requested lanuage
|
Add localeData for requested lanuage
|
JavaScript
|
mit
|
sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity
|
fd5937050f8f97301d909beadfa3e87ef9f4aa13
|
src/components/forms/LinksControl.js
|
src/components/forms/LinksControl.js
|
import React, { Component, PropTypes } from 'react'
import FormControl from './FormControl'
/* eslint-disable react/prefer-stateless-function */
class LinksControl extends Component {
static propTypes = {
text: PropTypes.oneOfType([
PropTypes.string,
PropTypes.array,
]),
}
static defaultProps = {
className: 'LinksControl',
id: 'external_links',
label: 'Links',
name: 'user[links]',
placeholder: 'Links (optional)',
}
getLinks() {
const { text } = this.props
const links = text || ''
if (typeof links === 'string') {
return links
}
return links.map((link) => link.text).join(', ')
}
render() {
return (
<FormControl
{ ...this.props }
autoCapitalize="off"
autoCorrect="off"
maxLength="50"
text={ this.getLinks() }
type="text"
/>
)
}
}
export default LinksControl
|
import React, { Component, PropTypes } from 'react'
import FormControl from './FormControl'
/* eslint-disable react/prefer-stateless-function */
class LinksControl extends Component {
static propTypes = {
text: PropTypes.oneOfType([
PropTypes.string,
PropTypes.array,
]),
}
static defaultProps = {
className: 'LinksControl',
id: 'external_links',
label: 'Links',
name: 'user[links]',
placeholder: 'Links (optional)',
}
getLinks() {
const { text } = this.props
const links = text || ''
if (typeof links === 'string') {
return links
}
return links.map((link) => link.text).join(', ')
}
render() {
return (
<FormControl
{ ...this.props }
autoCapitalize="off"
autoCorrect="off"
text={ this.getLinks() }
type="text"
/>
)
}
}
export default LinksControl
|
Remove max-length on links control
|
Remove max-length on links control
The `max-length` attribute was inadvertently added.
[Finishes: #119027729](https://www.pivotaltracker.com/story/show/119027729)
[#119014219](https://www.pivotaltracker.com/story/show/119014219)
|
JavaScript
|
mit
|
ello/webapp,ello/webapp,ello/webapp
|
17bcd21bf30b3baabbacb1e45b59c7103b3cdbd3
|
webpack/webpack.common.config.js
|
webpack/webpack.common.config.js
|
// Common webpack configuration used by webpack.hot.config and webpack.rails.config.
var path = require("path");
module.exports = {
context: __dirname, // the project dir
entry: [ "./assets/javascripts/example" ],
// In case you wanted to load jQuery from the CDN, this is how you would do it:
// externals: {
// jquery: "var jQuery"
// },
resolve: {
root: [path.join(__dirname, "scripts"),
path.join(__dirname, "assets/javascripts"),
path.join(__dirname, "assets/stylesheets")],
extensions: ["", ".webpack.js", ".web.js", ".js", ".jsx", ".scss", ".css", "config.js"]
},
module: {
loaders: [
{ test: require.resolve("react"), loader: "expose?React" }
]
}
};
|
// Common webpack configuration used by webpack.hot.config and webpack.rails.config.
var path = require("path");
module.exports = {
context: __dirname, // the project dir
entry: [ "./assets/javascripts/example" ],
// In case you wanted to load jQuery from the CDN, this is how you would do it:
// externals: {
// jquery: "var jQuery"
// },
resolve: {
root: [path.join(__dirname, "scripts"),
path.join(__dirname, "assets/javascripts"),
path.join(__dirname, "assets/stylesheets")],
extensions: ["", ".webpack.js", ".web.js", ".js", ".jsx", ".scss", ".css", "config.js"]
},
module: {
loaders: []
}
};
|
Remove exposing React as that was fixed in the React update
|
Remove exposing React as that was fixed in the React update
|
JavaScript
|
mit
|
mscienski/stpauls,szyablitsky/react-webpack-rails-tutorial,RomanovRoman/react-webpack-rails-tutorial,crmaxx/react-webpack-rails-tutorial,roxolan/react-webpack-rails-tutorial,Rvor/react-webpack-rails-tutorial,phosphene/react-on-rails-cherrypick,jeffthemaximum/Teachers-Dont-Pay-Jeff,shakacode/react-webpack-rails-tutorial,skv-headless/react-webpack-rails-tutorial,skv-headless/react-webpack-rails-tutorial,michaelgruber/react-webpack-rails-tutorial,janklimo/react-webpack-rails-tutorial,stevecj/term_palette_maker,shakacode/react-webpack-rails-tutorial,BadAllOff/react-webpack-rails-tutorial,RomanovRoman/react-webpack-rails-tutorial,jeffthemaximum/jeffline,michaelgruber/react-webpack-rails-tutorial,CerebralStorm/workout_logger,hoffmanc/react-webpack-rails-tutorial,justin808/react-webpack-rails-tutorial,BadAllOff/react-webpack-rails-tutorial,phosphene/react-on-rails-cherrypick,csmalin/react-webpack-rails-tutorial,skv-headless/react-webpack-rails-tutorial,shilu89757/react-webpack-rails-tutorial,bronson/react-webpack-rails-tutorial,shakacode/react-webpack-rails-tutorial,jeffthemaximum/jeffline,janklimo/react-webpack-rails-tutorial,cacheflow/react-webpack-rails-tutorial,cacheflow/react-webpack-rails-tutorial,michaelgruber/react-webpack-rails-tutorial,csterritt/react-webpack-rails-tutorial,janklimo/react-webpack-rails-tutorial,szyablitsky/react-webpack-rails-tutorial,Johnnycus/react-webpack-rails-tutorial,justin808/react-webpack-rails-tutorial,BadAllOff/react-webpack-rails-tutorial,StanBoyet/react-webpack-rails-tutorial,jeffthemaximum/Teachers-Dont-Pay-Jeff,jeffthemaximum/Teachers-Dont-Pay-Jeff,thiagoc7/react-webpack-rails-tutorial,yakovenkodenis/react-webpack-rails-tutorial,CerebralStorm/workout_logger,roxolan/react-webpack-rails-tutorial,thiagoc7/react-webpack-rails-tutorial,crmaxx/react-webpack-rails-tutorial,StanBoyet/react-webpack-rails-tutorial,CerebralStorm/workout_logger,kentwilliam/react-webpack-rails-tutorial,phosphene/react-on-rails-cherrypick,csterritt/react-webpack-rails-tutorial,crmaxx/react-webpack-rails-tutorial,kentwilliam/react-webpack-rails-tutorial,shilu89757/react-webpack-rails-tutorial,roxolan/react-webpack-rails-tutorial,bsy/react-webpack-rails-tutorial,BadAllOff/react-webpack-rails-tutorial,Rvor/react-webpack-rails-tutorial,bsy/react-webpack-rails-tutorial,suzukaze/react-webpack-rails-tutorial,hoffmanc/react-webpack-rails-tutorial,Johnnycus/react-webpack-rails-tutorial,shilu89757/react-webpack-rails-tutorial,kentwilliam/react-webpack-rails-tutorial,bronson/react-webpack-rails-tutorial,stevecj/term_palette_maker,StanBoyet/react-webpack-rails-tutorial,bsy/react-webpack-rails-tutorial,shunwen/react-webpack-rails-tutorial,phosphene/react-on-rails-cherrypick,bsy/react-webpack-rails-tutorial,jeffthemaximum/jeffline,stevecj/term_palette_maker,RomanovRoman/react-webpack-rails-tutorial,StanBoyet/react-webpack-rails-tutorial,shunwen/react-webpack-rails-tutorial,csterritt/react-webpack-rails-tutorial,CerebralStorm/workout_logger,bronson/react-webpack-rails-tutorial,cacheflow/react-webpack-rails-tutorial,jeffthemaximum/Teachers-Dont-Pay-Jeff,csmalin/react-webpack-rails-tutorial,szyablitsky/react-webpack-rails-tutorial,jeffthemaximum/jeffline,suzukaze/react-webpack-rails-tutorial,thiagoc7/react-webpack-rails-tutorial,shunwen/react-webpack-rails-tutorial,Rvor/react-webpack-rails-tutorial,cacheflow/react-webpack-rails-tutorial,crmaxx/react-webpack-rails-tutorial,suzukaze/react-webpack-rails-tutorial,janklimo/react-webpack-rails-tutorial,Johnnycus/react-webpack-rails-tutorial,michaelgruber/react-webpack-rails-tutorial,yakovenkodenis/react-webpack-rails-tutorial,RomanovRoman/react-webpack-rails-tutorial,justin808/react-webpack-rails-tutorial,hoffmanc/react-webpack-rails-tutorial,shilu89757/react-webpack-rails-tutorial,yakovenkodenis/react-webpack-rails-tutorial,yakovenkodenis/react-webpack-rails-tutorial,shunwen/react-webpack-rails-tutorial,szyablitsky/react-webpack-rails-tutorial,suzukaze/react-webpack-rails-tutorial,jeffthemaximum/Teachers-Dont-Pay-Jeff,stevecj/term_palette_maker,csmalin/react-webpack-rails-tutorial,justin808/react-webpack-rails-tutorial,shakacode/react-webpack-rails-tutorial,bronson/react-webpack-rails-tutorial,hoffmanc/react-webpack-rails-tutorial,jeffthemaximum/jeffline,skv-headless/react-webpack-rails-tutorial,thiagoc7/react-webpack-rails-tutorial,Johnnycus/react-webpack-rails-tutorial,csmalin/react-webpack-rails-tutorial,roxolan/react-webpack-rails-tutorial,csterritt/react-webpack-rails-tutorial,Rvor/react-webpack-rails-tutorial,kentwilliam/react-webpack-rails-tutorial,mscienski/stpauls
|
255c7b47e7686650f5712fb2632d3b4c0e863d64
|
src/lib/substituteVariantsAtRules.js
|
src/lib/substituteVariantsAtRules.js
|
import _ from 'lodash'
import postcss from 'postcss'
const variantGenerators = {
hover: (container, config) => {
const cloned = container.clone()
cloned.walkRules(rule => {
rule.selector = `.hover${config.options.separator}${rule.selector.slice(1)}:hover`
})
return cloned.nodes
},
focus: (container, config) => {
const cloned = container.clone()
cloned.walkRules(rule => {
rule.selector = `.focus${config.options.separator}${rule.selector.slice(1)}:focus`
})
return cloned.nodes
},
}
export default function(config) {
return function(css) {
const unwrappedConfig = config()
css.walkAtRules('variants', atRule => {
const variants = postcss.list.comma(atRule.params)
if (variants.includes('responsive')) {
const responsiveParent = postcss.atRule({ name: 'responsive' })
atRule.before(responsiveParent)
responsiveParent.append(atRule)
}
atRule.before(atRule.clone().nodes)
_.forEach(['focus', 'hover'], variant => {
if (variants.includes(variant)) {
atRule.before(variantGenerators[variant](atRule, unwrappedConfig))
}
})
atRule.remove()
})
}
}
|
import _ from 'lodash'
import postcss from 'postcss'
const variantGenerators = {
hover: (container, config) => {
const cloned = container.clone()
cloned.walkRules(rule => {
rule.selector = `.hover${config.options.separator}${rule.selector.slice(1)}:hover`
})
container.before(cloned.nodes)
},
focus: (container, config) => {
const cloned = container.clone()
cloned.walkRules(rule => {
rule.selector = `.focus${config.options.separator}${rule.selector.slice(1)}:focus`
})
container.before(cloned.nodes)
},
}
export default function(config) {
return function(css) {
const unwrappedConfig = config()
css.walkAtRules('variants', atRule => {
const variants = postcss.list.comma(atRule.params)
if (variants.includes('responsive')) {
const responsiveParent = postcss.atRule({ name: 'responsive' })
atRule.before(responsiveParent)
responsiveParent.append(atRule)
}
atRule.before(atRule.clone().nodes)
_.forEach(['focus', 'hover'], variant => {
if (variants.includes(variant)) {
variantGenerators[variant](atRule, unwrappedConfig)
}
})
atRule.remove()
})
}
}
|
Move responsibility for appending nodes into variant generators themselves
|
Move responsibility for appending nodes into variant generators themselves
|
JavaScript
|
mit
|
tailwindlabs/tailwindcss,tailwindlabs/tailwindcss,tailwindlabs/tailwindcss,tailwindcss/tailwindcss
|
fcb2a9ecda9fe5dfb9484531ab697ef4c26ae608
|
test/create-test.js
|
test/create-test.js
|
var tape = require("tape"),
jsdom = require("jsdom"),
d3 = Object.assign(require("../"), require("d3-selection"));
/*************************************
************ Components *************
*************************************/
// Leveraging create hook with selection as first argument.
var checkboxHTML = `
<label class="form-check-label">
<input type="checkbox" class="form-check-input">
<span class="checkbox-label-span"></span>
</label>
`,
checkbox = d3.component("div", "form-check")
.create(function (selection){
selection.html(checkboxHTML);
})
.render(function (selection, props){
if(props && props.label){
selection.select(".checkbox-label-span")
.text(props.label);
}
});
/*************************************
************** Tests ****************
*************************************/
tape("Create hook should pass selection on enter.", function(test) {
var div = d3.select(jsdom.jsdom().body).append("div");
div.call(checkbox);
test.equal(div.html(), `<div class="form-check">${checkboxHTML}</div>`);
test.end();
});
tape("Render should have access to selection content from create hook.", function(test) {
var div = d3.select(jsdom.jsdom().body).append("div");
div.call(checkbox, { label: "My Checkbox"});
test.equal(div.select(".checkbox-label-span").text(), "My Checkbox");
test.end();
});
|
var tape = require("tape"),
jsdom = require("jsdom"),
d3 = Object.assign(require("../"), require("d3-selection"));
/*************************************
************ Components *************
*************************************/
// Leveraging create hook with selection as first argument.
var card = d3.component("div", "card")
.create(function (selection){
selection
.append("div").attr("class", "card-block")
.append("div").attr("class", "card-text");
})
.render(function (selection, props){
selection
.select(".card-text")
.text(props.text);
});
/*************************************
************** Tests ****************
*************************************/
tape("Create hook should pass selection on enter.", function(test) {
var div = d3.select(jsdom.jsdom().body).append("div");
div.call(card, { text: "I'm in a card." });
test.equal(div.html(), [
'<div class="card">',
'<div class="card-block">',
'<div class="card-text">',
"I\'m in a card.",
"</div>",
"</div>",
"</div>"
].join(""));
test.end();
});
|
Change test to use card concept
|
Change test to use card concept
|
JavaScript
|
bsd-3-clause
|
curran/d3-component
|
3500fe09fd8aba9d9d789f1308d57955aaeacd5d
|
public/javascripts/page.js
|
public/javascripts/page.js
|
$(function() {
var socket = new WebSocket("ws://" + window.location.host + "/");
socket.onmessage = function(message){
console.log('got a message: ')
console.log(message)
}
});
|
$(function() {
var socket = new WebSocket("ws://" + window.location.host + "/");
socket.addEventListener('message', function(message){
console.log('got a message: ')
console.log(message)
});
});
|
Use addEventListener rather than onmessage
|
Use addEventListener rather than onmessage
|
JavaScript
|
mit
|
portlandcodeschool-jsi/barebones-chat,portlandcodeschool-jsi/barebones-chat
|
1a8ad6d06e5b465ee331cbc5c4957862edf31950
|
test/fixtures/output_server.js
|
test/fixtures/output_server.js
|
/*
* grunt-external-daemon
* https://github.com/jlindsey/grunt-external-daemon
*
* Copyright (c) 2013 Joshua Lindsey
* Licensed under the MIT license.
*/
'use strict';
process.stdout.write("STDOUT Message");
process.stderr.write("STDERR Message");
|
/*
* grunt-external-daemon
* https://github.com/jlindsey/grunt-external-daemon
*
* Copyright (c) 2013 Joshua Lindsey
* Licensed under the MIT license.
*/
'use strict';
process.stdout.setEncoding('utf-8');
process.stderr.setEncoding('utf-8');
process.stdout.write("STDOUT Message");
process.stderr.write("STDERR Message");
|
Add encoding to output server streams
|
Add encoding to output server streams
|
JavaScript
|
mit
|
jlindsey/grunt-external-daemon
|
ea850baf397ae98a78222691e1f38571d66d029c
|
db/config.js
|
db/config.js
|
//For Heroku Deployment
var URI = require('urijs');
var config = URI.parse(process.env.DATABASE_URL);
config['ssl'] = true;
module.exports = config;
// module.exports = {
// database: 'sonder',
// user: 'postgres',
// //password: 'postgres',
// port: 32769,
// host: '192.168.99.100'
// };
|
//For Heroku Deployment
var URI = require('urijs');
// var config = URI.parse(process.env.DATABASE_URL);
// config['ssl'] = true;
var config = process.env.DATABASE_URL;
module.exports = config;
// module.exports = {
// database: 'sonder',
// user: 'postgres',
// //password: 'postgres',
// port: 32769,
// host: '192.168.99.100'
// };
|
Connect to PG via ENV string
|
Connect to PG via ENV string
|
JavaScript
|
mit
|
aarontrank/SonderServer,MapReactor/SonderServer,MapReactor/SonderServer,aarontrank/SonderServer
|
588a552ce9750a70f0c80ed574c139f563d5ffcc
|
optimize/index.js
|
optimize/index.js
|
var eng = require('./node/engine');
var index = module.exports = {
localMinimize: function(func, options, callback) {
eng.runPython('local', func, options, callback);
},
globalMinimize: function(func, options, callback) {
eng.runPython('global', func, options, callback);
},
nonNegLeastSquares: function(A, b, callback) {
eng.runPython('nnls', A, b, callback);
},
fitCurve: function(func, xData, yData, options, callback) {
eng.runPython('fit', func, options, callback, xData, yData);
},
findRoot: function(func, lower, upper, options, callback) {
eng.runPython('root', func, options, callback, lower, upper);
}
};
index.fitCurve.linear = function(xData, yData, callback) {
eng.runPython('fit', 'a * x + b', { variables: ['x', 'a', 'b'] }, callback, xData, yData);
};
index.fitCurve.quadratic = function(xData, yData, callback) {
eng.runPython('fit', 'a * (x**2) + b * x + c', { variables: ['x', 'a', 'b', 'c'] }, callback, xData, yData);
};
|
var eng = require('./node/engine');
var index = module.exports = {
localMinimize: function(func, options, callback) {
eng.runPython('local', func, options, callback);
},
globalMinimize: function(func, options, callback) {
eng.runPython('global', func, options, callback);
},
minimizeEuclideanNorm: function(A, b, callback) {
eng.runPython('nnls', A, b, callback);
},
fitCurve: function(func, xData, yData, options, callback) {
eng.runPython('fit', func, options, callback, xData, yData);
},
findRoot: function(func, lower, upper, options, callback) {
eng.runPython('root', func, options, callback, lower, upper);
},
findVectorRoot: function(func, guess, options, callback) {
eng.runPython('vectorRoot', func, options, callback, guess);
},
calcDerivatives: function(func, point, options, callback) {
eng.runPython('derivative', func, options, callback, point);
}
};
index.fitCurve.linear = function(xData, yData, callback) {
eng.runPython('fit', 'a * x + b', { variables: ['x', 'a', 'b'] }, callback, xData, yData);
};
index.fitCurve.quadratic = function(xData, yData, callback) {
eng.runPython('fit', 'a * (x**2) + b * x + c', { variables: ['x', 'a', 'b', 'c'] }, callback, xData, yData);
};
|
Add API for derivative, vector root
|
Add API for derivative, vector root
|
JavaScript
|
mit
|
acjones617/scipy-node,acjones617/scipy-node
|
94396993d1a0552559cb5b822f797adee09ea2b1
|
test/com/spinal/ioc/plugins/theme-test.js
|
test/com/spinal/ioc/plugins/theme-test.js
|
/**
* com.spinal.ioc.plugins.ThemePlugin Class Tests
* @author Patricio Ferreira <3dimentionar@gmail.com>
**/
define(['ioc/plugins/theme'], function(ThemePlugin) {
describe('com.spinal.ioc.plugins.ThemePlugin', function() {
before(function() {
});
after(function() {
});
describe('#new()', function() {
});
});
});
|
/**
* com.spinal.ioc.plugins.ThemePlugin Class Tests
* @author Patricio Ferreira <3dimentionar@gmail.com>
**/
define(['ioc/plugins/theme'], function(ThemePlugin) {
describe('com.spinal.ioc.plugins.ThemePlugin', function() {
before(function() {
this.plugin = null;
});
after(function() {
delete this.plugin;
});
describe('#new()', function() {
it('Should return an instance of ThemePlugin');
});
describe('#parse()', function() {
it('Should parse themes from specified on a given spec');
});
describe('#currentTheme()', function() {
it('Should return the current theme');
});
describe('#useBootstrap()', function() {
it('Should inject bootstrap-core and bootstrap-theme');
it('Should inject only bootstrap-core');
it('Should inject only bootstrap-theme');
});
describe('#useDefault()', function() {
it('Should inject theme flagged as default');
});
describe('#validate()', function() {
it('Should return false: theme name is not a String');
it('Should return false: theme is not registered');
it('Should return false: current theme is the same as the one being validated');
});
describe('#applyTheme()', function() {
it('Should inject a given theme');
});
describe('#removeTheme()', function() {
it('Should remove all themes except for bootstrap core and theme');
});
describe('#resolveURI()', function() {
it('Should resolve theme URI for a given theme path');
});
describe('#getTheme()', function() {
it('Should retrieve a theme object registered given a theme name');
it('Should NOT retrieve a theme object registered given a theme name');
});
describe('#changeTheme()', function() {
it('Should change the current theme with another one given a theme name');
});
describe('#run()', function() {
it('Should executes plugin logic');
});
});
});
|
Test cases for ThemePlugin Class added to the unit test file.
|
Test cases for ThemePlugin Class added to the unit test file.
|
JavaScript
|
mit
|
nahuelio/boneyard,3dimention/spinal,3dimention/boneyard
|
27b391f8bdf57b9c3215ef99a29351ba55db65f5
|
public/main.js
|
public/main.js
|
$(function() {
var formatted_string = 'hoge';
// $('#text_output').text(formatted_string);
$('#text_input').bind('keyup', function(e) {
var text = $('#text_input').val();
console.log(text);
$.ajax({
url: 'http://localhost:9292/parse/',
method: 'POST',
crossDomain: true,
data: {'text': text}
}).error(function() {
console.log('Error');
}).done(function(text) {
console.log(text);
update(text);
});
});
});
function update(formatted_string) {
$('#text_output').html(formatted_string);
}
|
$(function() {
var formatted_string = 'hoge';
// $('#text_output').text(formatted_string);
$('#text_input').bind('keyup', function(e) {
var text = $('#text_input').val();
console.log(text);
parse(text);
});
});
function update(formatted_string) {
$('#text_output').html(formatted_string);
}
function parse(text) {
$.ajax({
url: 'http://localhost:9292/parse/',
method: 'POST',
crossDomain: true,
data: {'text': text}
}).error(function() {
console.log('Error');
}).done(function(text) {
console.log(text);
update(text);
});
}
|
Split out to parse function
|
Split out to parse function
|
JavaScript
|
mit
|
gouf/test_sinatra_markdown_preview,gouf/test_sinatra_markdown_preview
|
512ebaf12ea76d3613c2742d4ea5b61a257e5e04
|
test/templateLayout.wefTest.js
|
test/templateLayout.wefTest.js
|
/*!
* templateLayout tests
* Copyright (c) 2011 Pablo Escalada
* MIT Licensed
*/
TestCase("templateLayout", {
"test templateLayout registration":function () {
assertNotUndefined(wef.plugins.registered.templateLayout);
assertEquals("templateLayout", wef.plugins.registered["templateLayout"].name);
},
"test templateLayout namespace":function () {
assertNotUndefined(wef.plugins.templateLayout);
assertEquals("templateLayout", wef.plugins.templateLayout.name);
}
});
AsyncTestCase("templateLayoutAsync", {
"test templateLayout listen cssParser events":function (queue) {
//requires cssParser
var text = "body {display-model: \"a (intrinsic), b (intrinsic)\";} div#uno {situated: a; display-model: \"123 (intrinsic)\";}";
queue.call(function (callbacks) {
var myCallback = callbacks.add(function () {
wef.plugins.registered.templateLayout.templateLayout();
wef.plugins.registered.cssParser.cssParser().parse(text);
});
window.setTimeout(myCallback, 5000);
});
queue.call(function () {
var result = wef.plugins.registered.templateLayout.getLastEvent().property;
//console.log(result);
assertEquals("display-model", result);
})
}
})
|
/*!
* templateLayout tests
* Copyright (c) 2011 Pablo Escalada
* MIT Licensed
*/
TestCase("templateLayout", {
"test templateLayout registration":function () {
assertNotUndefined(wef.plugins.registered.templateLayout);
assertEquals("templateLayout", wef.plugins.registered.templateLayout.name);
},
"test templateLayout namespace":function () {
assertNotUndefined(wef.fn.templateLayout);
assertEquals("templateLayout", wef.fn.templateLayout.name);
}
});
AsyncTestCase("templateLayoutAsync", {
"test templateLayout listen cssParser events":function (queue) {
//requires cssParser
var text = "body {display-model: \"a (intrinsic), b (intrinsic)\";} div#uno {situated: a; display-model: \"123 (intrinsic)\";}";
queue.call(function (callbacks) {
var myCallback = callbacks.add(function () {
wef.fn.templateLayout.init();
wef.fn.cssParser.init().parse(text);
});
window.setTimeout(myCallback, 5000);
});
queue.call(function () {
var result = wef.fn.templateLayout.getLastEvent().property;
//console.log(result);
assertEquals("display-model", result);
})
}
})
|
Update code to pass tests
|
Update code to pass tests
|
JavaScript
|
mit
|
diesire/cssTemplateLayout,diesire/cssTemplateLayout,diesire/cssTemplateLayout
|
302c3434a44b3e51d84b70e801a72e9119f106f4
|
src/scripts/main.js
|
src/scripts/main.js
|
// ES2015 polyfill
import 'babel-polyfill';
// Modernizr
import './modernizr';
// Components
import './components/example';
|
// Polyfills
// Only use the polyfills you need e.g
// import 'core-js/object';
// import 'js-polyfills/html';
// Modernizr
import './modernizr';
// Components
import './components/example';
|
Use core-js and js-polyfills instead of babel-polyfill
|
Use core-js and js-polyfills instead of babel-polyfill
|
JavaScript
|
mit
|
strt/strt-boilerplate,strt/strt-boilerplate
|
940f4f4da198335f51c2f8e76fc1c0caffb7736c
|
__tests__/index.js
|
__tests__/index.js
|
import config from "../"
import postcss from "postcss"
import stylelint from "stylelint"
import test from "tape"
test("basic properties of config", t => {
t.ok(isObject(config.rules), "rules is object")
t.end()
})
function isObject(obj) {
return typeof obj === "object" && obj !== null
}
const css = (
`a {
\ttop: .2em;
}
`)
postcss()
.use(stylelint(config))
.process(css)
.then(checkResult)
.catch(e => console.log(e.stack))
function checkResult(result) {
const { messages } = result
test("expected warnings", t => {
t.equal(messages.length, 1, "flags one warning")
t.ok(messages.every(m => m.type === "warning"), "message of type warning")
t.ok(messages.every(m => m.plugin === "stylelint"), "message of plugin stylelint")
t.equal(messages[0].text, "Expected a leading zero (number-leading-zero)", "correct warning text")
t.end()
})
}
|
import config from "../"
import stylelint from "stylelint"
import test from "tape"
test("basic properties of config", t => {
t.ok(isObject(config.rules), "rules is object")
t.end()
})
function isObject(obj) {
return typeof obj === "object" && obj !== null
}
const css = (
`a {
\ttop: .2em;
}
`)
stylelint.lint({
code: css,
config: config,
})
.then(checkResult)
.catch(function (err) {
console.error(err.stack)
})
function checkResult(data) {
const { errored, results } = data
const { warnings } = results[0]
test("expected warnings", t => {
t.ok(errored, "errored")
t.equal(warnings.length, 1, "flags one warning")
t.equal(warnings[0].text, "Expected a leading zero (number-leading-zero)", "correct warning text")
t.end()
})
}
|
Use stylelint standalone API in test
|
Use stylelint standalone API in test
|
JavaScript
|
mit
|
ntwb/stylelint-config-wordpress,WordPress-Coding-Standards/stylelint-config-wordpress,GaryJones/stylelint-config-wordpress,stylelint/stylelint-config-wordpress
|
fd7dda54d0586906ccd07726352ba8566176ef71
|
app/scripts/app.js
|
app/scripts/app.js
|
(function () {
'use strict';
/**
* ngInject
*/
function StateConfig($urlRouterProvider) {
$urlRouterProvider.otherwise('/');
}
// color ramp for sectors
var sectorColors = {
'School (K-12)': '#A6CEE3',
'Office': '#1F78B4',
'Warehouse': '#B2DF8A',
'College/ University': '#33A02C',
'Other': '#FB9A99',
'Retail': '#E31A1C',
'Municipal': '#FDBF6F',
'Multifamily': '#FF7F00',
'Hotel': '#CAB2D6',
'Industrial': '#6A3D9A',
'Unknown': '#DDDDDD'
};
/**
* @ngdoc overview
* @name mos
* @description
* # mos
*
* Main module of the application.
*/
angular
.module('mos', [
'mos.views.charts',
'mos.views.map',
'mos.views.info',
'mos.views.detail',
'mos.views.compare',
'headroom'
]).config(StateConfig);
angular.module('mos').constant('MOSColors', sectorColors);
})();
|
(function () {
'use strict';
/**
* ngInject
*/
function StateConfig($urlRouterProvider) {
$urlRouterProvider.otherwise('/');
}
// color ramp for sectors
var sectorColors = {
'School (K-12)': '#A6CEE3',
'Office': '#1F78B4',
'Medical Office': '#52A634',
'Warehouse': '#B2DF8A',
'College/ University': '#33A02C',
'Other': '#FB9A99',
'Retail': '#E31A1C',
'Municipal': '#FDBF6F',
'Multifamily': '#FF7F00',
'Hotel': '#CAB2D6',
'Industrial': '#6A3D9A',
'Worship': '#9C90C4',
'Supermarket': '#E8AE6C',
'Parking': '#C9DBE6',
'Laboratory': '#3AA3FF',
'Hospital': '#C6B4FF',
'Data Center': '#B8FFA8',
'Unknown': '#DDDDDD'
};
/**
* @ngdoc overview
* @name mos
* @description
* # mos
*
* Main module of the application.
*/
angular
.module('mos', [
'mos.views.charts',
'mos.views.map',
'mos.views.info',
'mos.views.detail',
'mos.views.compare',
'headroom'
]).config(StateConfig);
angular.module('mos').constant('MOSColors', sectorColors);
})();
|
Add remaining building types to MOSColors
|
Add remaining building types to MOSColors
|
JavaScript
|
mit
|
azavea/mos-energy-benchmark,azavea/mos-energy-benchmark,azavea/mos-energy-benchmark
|
202941769bd594e31719303882df16ee6ece95c9
|
react/index.js
|
react/index.js
|
var deps = [
'/stdlib/tag.js',
'/stdlib/observable.js'
];
function increment(x) {
return String(parseInt(x, 10) + 1);
}
function onReady(tag, observable) {
var value = observable.observe("0");
function onChange(evt) {
value.set(evt.target.value);
}
var input = tag.tag({
name: 'input',
attributes: {type: 'number', value: value},
handlers: {keyup: onChange, change: onChange}
});
var inc = observable.lift(increment);
var output = tag.tag({
name: 'input',
attributes: {type: 'number', value: inc(value), readOnly: true}
});
var div = tag.tag({name: 'div', contents: [input, output]});
yoink.define(div);
}
yoink.require(deps, onReady);
|
var deps = [
'/stdlib/tag.js',
'/stdlib/observable.js'
];
function increment(x) {
return String(parseInt(x, 10) + 1);
}
function onReady(tag, observable) {
var value = observable.observe("0");
var input = tag.tag({
name: 'input',
attributes: {type: 'number', value: value},
});
var inc = observable.lift(increment);
var output = tag.tag({
name: 'input',
attributes: {type: 'number', value: inc(value), readOnly: true}
});
var div = tag.tag({name: 'div', contents: [input, output]});
yoink.define(div);
}
yoink.require(deps, onReady);
|
Add 'change' event handler if tag attribute is an observable.
|
Add 'change' event handler if tag attribute is an observable.
|
JavaScript
|
bsd-3-clause
|
garious/poochie-examples,garious/yoink-examples,garious/poochie-examples,garious/yoink-examples
|
e37ab30622a50614f226dc746d7e7b68b2afd792
|
lib/index.js
|
lib/index.js
|
var Keen = require('keen-tracking');
var extend = require('keen-tracking/lib/utils/extend');
// Accessor methods
function readKey(str){
if (!arguments.length) return this.config.readKey;
this.config.readKey = (str ? String(str) : null);
return this;
}
function queryPath(str){
if (!arguments.length) return this.config.readPath;
if (!this.projectId()) {
this.emit('error', 'Keen is missing a projectId property');
return;
}
this.config.readPath = (str ? String(str) : ('/3.0/projects/' + this.projectId() + '/queries'));
return this;
}
// Query method
function query(){}
// HTTP methods
function get(){}
function post(){}
function put(){}
function del(){}
// Extend client instance
extend(Keen.prototype, {
'readKey' : readKey,
'queryPath' : queryPath,
'query' : query,
'get' : get,
'post' : post,
'put' : put,
'del' : del
});
module.exports = Keen;
|
var Keen = require('keen-tracking');
var extend = require('keen-tracking/lib/utils/extend');
// Accessor methods
function readKey(str){
if (!arguments.length) return this.config.readKey;
this.config.readKey = str ? String(str) : null;
return this;
}
function queryPath(str){
if (!arguments.length) return this.config.queryPath;
if (!this.projectId()) {
this.emit('error', 'Keen is missing a projectId property');
return;
}
this.config.queryPath = str ? String(str) : ('/3.0/projects/' + this.projectId() + '/queries');
return this;
}
// Query method
function query(){}
// HTTP methods
function get(){}
function post(){}
function put(){}
function del(){}
// Extend client instance
extend(Keen.prototype, {
'readKey' : readKey,
'queryPath' : queryPath,
'query' : query,
'get' : get,
'post' : post,
'put' : put,
'del' : del
});
// console.log(new Keen({ projectId: '123' }).queryPath('test').queryPath());
module.exports = Keen;
|
Clean up method names and internals
|
Clean up method names and internals
|
JavaScript
|
mit
|
keen/keen-analysis.js,keen/keen-analysis.js
|
ecb93921a112556a307505aec1d249b9fcc27f1d
|
lib/track.js
|
lib/track.js
|
var Util = require('./util.js');
module.exports = Track = function(vid, info) {
this.vid = vid;
this.title = info.title;
this.author = info.author;
this.viewCount = info.viewCount || info.view_count;
this.lengthSeconds = info.lengthSeconds || info.length_seconds;
};
Track.prototype.formatViewCount = function() {
return this.viewCount ? this.viewCount.replace(/\B(?=(\d{3})+(?!\d))/g, ',') : 'unknown';
};
Track.prototype.formatTime = function() {
return Util.formatTime(this.lengthSeconds);
};
Track.prototype.prettyPrint = function() {
return `**${this.title}** by **${this.author}** *(${this.formatViewCount()} views)* [${this.formatTime()}]`;
};
Track.prototype.fullPrint = function() {
return `${this.prettyPrint()}, added by <@${this.userId}>`;
};
Track.prototype.saveable = function() {
return {
vid: this.vid,
title: this.title,
author: this.author,
viewCount: this.viewCount,
lengthSeconds: this.lengthSeconds,
};
};
|
var Util = require('./util.js');
module.exports = Track = function(vid, info) {
this.vid = vid;
this.title = info.title;
this.author = info.author;
this.viewCount = info.viewCount || info.view_count;
this.lengthSeconds = info.lengthSeconds || info.length_seconds;
};
Track.prototype.formatViewCount = function() {
return this.viewCount ? this.viewCount.replace(/\B(?=(\d{3})+(?!\d))/g, ',') : 'unknown';
};
Track.prototype.formatTime = function() {
return Util.formatTime(this.lengthSeconds);
};
Track.prototype.prettyPrint = function() {
return `**${this.title}** by **${this.author}** *(${this.formatViewCount()} views)* [${this.formatTime()}]`;
};
Track.prototype.fullPrint = function() {
return `${this.prettyPrint()}, added by <@${this.userId}>`;
};
Track.prototype.saveable = function() {
return {
vid: this.vid,
title: this.title,
author: this.author,
viewCount: this.viewCount,
lengthSeconds: this.lengthSeconds,
};
};
Track.prototype.getTime = function() {
return this.lengthSeconds;
};
|
Add getTime function to get remaining time
|
Add getTime function to get remaining time
|
JavaScript
|
mit
|
meew0/Lethe
|
5e41bab44fe3cdd1d160198cbe9ec3aeebf1fdcc
|
jupyter-js-widgets/src/embed-webpack.js
|
jupyter-js-widgets/src/embed-webpack.js
|
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
// This file must be webpacked because it contains .css imports
// Load jquery and jquery-ui
var $ = require('jquery');
require('jquery-ui');
window.$ = window.jQuery = $;
require('jquery-ui');
// Load styling
require('jquery-ui/themes/smoothness/jquery-ui.min.css');
require('../css/widgets.min.css');
const widgets = require('./index');
console.info('jupyter-js-widgets loaded successfully');
const manager = new widgets.EmbedManager();
// Magic global widget rendering function:
function renderInlineWidgets(element) {
var element = element || document;
var tags = element.querySelectorAll('script.jupyter-widgets');
for (var i=0; i!=tags.length; ++i) {
var tag = tags[i];
var widgetStateObject = JSON.parse(tag.innerHTML);
var widgetContainer = document.createElement('div');
widgetContainer.className = 'widget-area';
manager.display_widget_state(widgetStateObject, widgetContainer).then(function() {
tag.parentElement.insertBefore(widgetContainer, tag);
});
}
}
// Module exports
exports.manager = manager;
exports.renderInlineWidgets = renderInlineWidgets;
// Set window globals
window.manager = manager;
window.onload = renderInlineWidgets;
|
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
// This file must be webpacked because it contains .css imports
// Load jquery and jquery-ui
var $ = require('jquery');
require('jquery-ui');
window.$ = window.jQuery = $;
require('jquery-ui');
// Load styling
require('jquery-ui/themes/smoothness/jquery-ui.min.css');
require('../css/widgets.min.css');
const widgets = require('./index');
console.info('jupyter-js-widgets loaded successfully');
const manager = new widgets.EmbedManager();
// Magic global widget rendering function:
function renderInlineWidgets(event) {
var element = event.target || document;
var tags = element.querySelectorAll('script.jupyter-widgets');
for (var i=0; i!=tags.length; ++i) {
var tag = tags[i];
var widgetStateObject = JSON.parse(tag.innerHTML);
var widgetContainer = document.createElement('div');
widgetContainer.className = 'widget-area';
manager.display_widget_state(widgetStateObject, widgetContainer).then(function() {
tag.parentElement.insertBefore(widgetContainer, tag);
});
}
}
// Module exports
exports.manager = manager;
exports.renderInlineWidgets = renderInlineWidgets;
// Set window globals
window.manager = manager;
window.addEventListener('load', renderInlineWidgets);
|
Use addEventListener('load' instead of onload
|
Use addEventListener('load' instead of onload
|
JavaScript
|
bsd-3-clause
|
cornhundred/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,cornhundred/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,ipython/ipywidgets,cornhundred/ipywidgets,cornhundred/ipywidgets,jupyter-widgets/ipywidgets,SylvainCorlay/ipywidgets,jupyter-widgets/ipywidgets,SylvainCorlay/ipywidgets,cornhundred/ipywidgets,ipython/ipywidgets
|
18d33de0c54e64693274bc17afb1a08b9fec5ad8
|
app/public/panel/controllers/DashCtrl.js
|
app/public/panel/controllers/DashCtrl.js
|
var angular = require('angular');
angular.module('DashCtrl', ['chart.js']).controller('DashController', ['$scope', $scope => {
const colorScheme = ['#2a9fd6'];
let weekDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
for(let i = 0; i < 6 - (new Date()).getDay(); i++) {
const back = weekDays.pop();
weekDays.unshift(back);
}
$scope.uploadColors = colorScheme;
$scope.uploadLabels = weekDays;
$scope.uploadSeries = ['Uploads'];
$scope.uploadData = [[10, 20, 30, 20, 15, 20, 45]];
$scope.uploadOptions = {
title: {
display: true,
text: 'Historical Uploads'
},
};
$scope.viewColors = colorScheme;
$scope.viewLabels = weekDays;
$scope.viewSeries = ['Views'];
$scope.viewData = [[5, 11, 4, 3, 7, 9, 21]];
$scope.viewOptions = {
title: {
display: true,
text: 'Historical Views'
}
};
}]);
{
}
|
var angular = require('angular');
angular.module('DashCtrl', ['chart.js']).controller('DashController', ['$scope', $scope => {
const colorScheme = ['#2a9fd6'];
// Calculate and format descending dates back one week
const currentDate = new Date();
const oneDay = 1000 * 60 * 60 * 24;
let dates = Array.from({length: 7}, (date, i) => new Date(currentDate - oneDay * (6 - i)));
let labels = dates.map(date => date.toISOString().substr(5, 5));
$scope.uploadColors = colorScheme;
$scope.uploadLabels = labels;
$scope.uploadSeries = ['Uploads'];
$scope.uploadData = [[10, 20, 30, 20, 15, 20, 45]];
$scope.uploadOptions = {
title: {
display: true,
text: 'Historical Uploads'
},
};
$scope.viewColors = colorScheme;
$scope.viewLabels = labels;
$scope.viewSeries = ['Views'];
$scope.viewData = [[5, 11, 4, 3, 7, 9, 21]];
$scope.viewOptions = {
title: {
display: true,
text: 'Historical Views'
}
};
}]);
{
}
|
Fix date and label calculation
|
Fix date and label calculation
|
JavaScript
|
mit
|
Foltik/Shimapan,Foltik/Shimapan
|
323b195642bab258001da6b0a85ca998e8697d3d
|
static/js/submit.js
|
static/js/submit.js
|
$(document).ready(function()
{
$("#invite-form").on('submit', function()
{
var inviteeEmail = $("#email").val();
console.log(inviteeEmail)
if (!inviteeEmail || !inviteeEmail.length) {
alert('Please enter an email');
return false;
}
$.ajax({
type: "POST",
url: "/",
headers: {
'X-CSRFToken': csrfToken,
},
data: { email: inviteeEmail},
success: function(data) {
handleResponse(data);
}
});
return false;
});
});
function handleResponse(data) {
document.data = data
if (data.status === 'success') {
console.log('success')
}
if (data.status === 'fail') {
console.log('failed')
}
}
|
$(document).ready(function()
{
$("#invite-form").on('submit', function()
{
var inviteeEmail = $("#email").val();
console.log(inviteeEmail)
if (!inviteeEmail || !inviteeEmail.length) {
alert('Please enter an email');
return false;
}
$.ajax({
type: "POST",
url: "/",
headers: {
'X-CSRFToken': csrfToken,
},
data: { email: inviteeEmail},
success: function(data) {
handleResponse(data);
}
});
return false;
});
});
function handleResponse(data) {
document.data = data
if (data.status === 'success') {
console.log('success')
Materialize.toast('Success!', 4000)
}
if (data.status === 'fail') {
Materialize.toast(data.error, 4000)
}
}
|
Use Materialize toasts to show the status
|
Use Materialize toasts to show the status
|
JavaScript
|
mit
|
avinassh/slackipy,avinassh/slackipy,avinassh/slackipy
|
63618d2180dfc52c922857eb6aabb2e195b637da
|
lib/helpers/redirect-to-organization.js
|
lib/helpers/redirect-to-organization.js
|
'use strict';
var url = require('url');
var getHost = require('./get-host');
module.exports = function redirectToOrganization(req, res, organization) {
res.redirect(req.protocol + '://' + organization.nameKey + '.' + getHost(req) + url.parse(req.url).pathname);
};
|
'use strict';
var url = require('url');
var getHost = require('./get-host');
module.exports = function redirectToOrganization(req, res, organization) {
var uri = req.protocol
+ '://' + organization.nameKey
+ '.'
+ getHost(req)
+ url.parse(req.url).pathname;
var queryParams = Object.keys(req.query);
if (queryParams.length > 0) {
uri += '?' + queryParams.map(function (param) {
return encodeURIComponent(param)
+ '='
+ encodeURIComponent(req.query[param]);
}).join('&');
}
res.redirect(uri);
};
|
Fix behaviour for redirect with query params
|
Fix behaviour for redirect with query params
|
JavaScript
|
apache-2.0
|
stormpath/express-stormpath,stormpath/express-stormpath,stormpath/express-stormpath
|
1c42a6e807b644a246b62c43f1494a906c130447
|
spec/server-pure/spec.render_png.js
|
spec/server-pure/spec.render_png.js
|
var renderPng = require('../../app/render_png');
describe('renderPng', function () {
describe('getScreenshotPath', function () {
it('creates the URL for the screenshot service call', function () {
renderPng.screenshotServiceUrl = 'http://screenshotservice';
renderPng.screenshotTargetUrl = 'http://spotlight';
var url = '/test/path.png';
var screenshotPath = renderPng.getScreenshotPath(url);
expect(screenshotPath).toEqual('http://screenshotservice?readyExpression=!!document.querySelector(".loaded")&forwardCacheHeaders=true&clipSelector=.visualisation&url=http://spotlight/test/path?raw');
});
});
});
|
var renderPng = require('../../app/render_png');
describe('renderPng', function () {
describe('getScreenshotPath', function () {
it('creates the URL for the screenshot service call', function () {
renderPng.screenshotServiceUrl = 'http://screenshotservice';
renderPng.screenshotTargetUrl = 'http://spotlight';
var url = '/test/path.png';
var screenshotPath = renderPng.getScreenshotPath({
url: url,
query: {}
});
expect(screenshotPath).toEqual('http://screenshotservice?readyExpression=!!document.querySelector(".loaded")&forwardCacheHeaders=true&clipSelector=.visualisation-inner figure&url=http://spotlight/test/path');
});
});
});
|
Fix qs params in screenshot url tests
|
Fix qs params in screenshot url tests
|
JavaScript
|
mit
|
keithiopia/spotlight,alphagov/spotlight,alphagov/spotlight,keithiopia/spotlight,alphagov/spotlight,tijmenb/spotlight,keithiopia/spotlight,tijmenb/spotlight,tijmenb/spotlight
|
8ffe7ba8783c85de062299f709a4a8d8a68eeef5
|
packages/@sanity/base/src/preview/ReferencePreview.js
|
packages/@sanity/base/src/preview/ReferencePreview.js
|
import React, {PropTypes} from 'react'
import resolveRefType from './resolveRefType'
import {resolver as previewResolver} from 'part:@sanity/base/preview'
export default class SanityPreview extends React.PureComponent {
static propTypes = {
value: PropTypes.object,
type: PropTypes.object.isRequired
};
state = {
loading: true,
materialized: null,
refType: null
}
resolveRefType(value, type) {
resolveRefType(value, type).then(refType => {
this.setState({
refType
})
})
}
componentDidMount() {
const {type, value} = this.props
this.resolveRefType(value, type)
}
componentWillReceiveProps(nextProps) {
if (this.props.type !== nextProps.type || this.props.value !== nextProps.value) {
this.resolveRefType(nextProps.value, nextProps.type)
}
}
render() {
const {refType} = this.state
if (!refType) {
return null
}
const Preview = previewResolver(refType)
return (
<Preview {...this.props} type={refType} />
)
}
}
|
import React, {PropTypes} from 'react'
import resolveRefType from './resolveRefType'
import {resolver as previewResolver} from 'part:@sanity/base/preview'
export default class SanityPreview extends React.PureComponent {
static propTypes = {
value: PropTypes.object,
type: PropTypes.object.isRequired
};
state = {
loading: true,
materialized: null,
refType: null
}
componentDidMount() {
const {type, value} = this.props
this.subscribeRefType(value, type)
}
componentWillUnmount() {
this.unsubscribe()
}
subscribeRefType(value, type) {
this.unsubscribe()
this.subscription = resolveRefType(value, type)
.subscribe(refType => {
this.setState({refType})
})
}
unsubscribe() {
if (this.subscription) {
this.subscription.unsubscribe()
this.subscription = null
}
}
componentWillReceiveProps(nextProps) {
if (this.props.type !== nextProps.type || this.props.value !== nextProps.value) {
this.subscribeRefType(nextProps.value, nextProps.type)
}
}
render() {
const {refType} = this.state
if (!refType) {
return null
}
const Preview = previewResolver(refType)
return (
<Preview {...this.props} type={refType} />
)
}
}
|
Fix wrong resolving of referenced type
|
[previews] Fix wrong resolving of referenced type
|
JavaScript
|
mit
|
sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity
|
abfd3076f555807bd43fc2733573056afda9d089
|
settings/index.js
|
settings/index.js
|
import _ from 'lodash';
import React from 'react';
import Settings from '@folio/stripes-components/lib/Settings';
import PermissionSets from './permissions/PermissionSets';
import PatronGroupsSettings from './PatronGroupsSettings';
import AddressTypesSettings from './AddressTypesSettings';
const pages = [
{
route: 'perms',
label: 'Permission sets',
component: PermissionSets,
perm: 'ui-users.editpermsets',
},
{
route: 'groups',
label: 'Patron groups',
component: PatronGroupsSettings,
// No perm needed yet
},
{
route: 'addresstypes',
label: 'Address Types',
component: AddressTypesSettings,
// No perm needed yet
},
];
export default props => <Settings {...props} pages={_.sortBy(pages, ['label'])} paneTitle="Users" />;
|
import _ from 'lodash';
import React from 'react';
import Settings from '@folio/stripes-components/lib/Settings';
import PermissionSets from './permissions/PermissionSets';
import PatronGroupsSettings from './PatronGroupsSettings';
import AddressTypesSettings from './AddressTypesSettings';
const pages = [
{
route: 'perms',
label: 'Permission sets',
component: PermissionSets,
perm: 'ui-users.editpermsets',
},
{
route: 'groups',
label: 'Patron groups',
component: PatronGroupsSettings,
// perm: 'settings.usergroups.all',
},
{
route: 'addresstypes',
label: 'Address Types',
component: AddressTypesSettings,
// perm: 'settings.addresstypes.all',
},
];
export default props => <Settings {...props} pages={_.sortBy(pages, ['label'])} paneTitle="Users" />;
|
Add commented-out permission guards. Part of UIU-197.
|
Add commented-out permission guards. Part of UIU-197.
|
JavaScript
|
apache-2.0
|
folio-org/ui-users,folio-org/ui-users
|
6c3cd606ff1dd948a8a1b51eb5525da4881945d1
|
www/Gruntfile.js
|
www/Gruntfile.js
|
module.exports = function (grunt) {
var allJSFilesInJSFolder = "js/**/*.js";
var distFolder = '../wikipedia/assets/';
grunt.loadNpmTasks( 'grunt-browserify' );
grunt.loadNpmTasks( 'gruntify-eslint' );
grunt.loadNpmTasks( 'grunt-contrib-copy' );
grunt.loadNpmTasks( 'grunt-contrib-less' );
grunt.initConfig( {
browserify: {
distMain: {
src: ["index-main.js", allJSFilesInJSFolder, "!preview-main.js"],
dest: distFolder + "index.js"
},
distPreview: {
src: ["preview-main.js", "js/utilities.js"],
dest: distFolder + "preview.js"
}
},
less: {
all: {
options: {
compress: true,
yuicompress: true,
optimization: 2
},
files: [
{ src: ["less/**/*.less", "node_modules/wikimedia-page-library/build/wikimedia-page-library-transform.css"], dest: distFolder + "styleoverrides.css"}
]
}
},
eslint: {
src: [allJSFilesInJSFolder]
},
copy: {
main: {
files: [{
src: ["*.html",
"*.css",
"ios.json",
"languages.json",
"mainpages.json",
"*.png"],
dest: distFolder
}]
}
}
} );
grunt.registerTask('default', ['eslint', 'browserify', 'less', 'copy']);
};
|
module.exports = function (grunt) {
var allJSFilesInJSFolder = "js/**/*.js";
var distFolder = '../wikipedia/assets/';
grunt.loadNpmTasks( 'grunt-browserify' );
grunt.loadNpmTasks( 'gruntify-eslint' );
grunt.loadNpmTasks( 'grunt-contrib-copy' );
grunt.loadNpmTasks( 'grunt-contrib-less' );
grunt.initConfig( {
browserify: {
distMain: {
src: ["index-main.js", allJSFilesInJSFolder, "!preview-main.js"],
dest: distFolder + "index.js"
},
distPreview: {
src: ["preview-main.js", "js/utilities.js"],
dest: distFolder + "preview.js"
}
},
less: {
all: {
options: {
compress: true,
yuicompress: true,
optimization: 2
},
files: [
{ src: ["less/**/*.less", "node_modules/wikimedia-page-library/build/wikimedia-page-library-transform.css"], dest: distFolder + "styleoverrides.css"}
]
}
},
eslint: {
src: [allJSFilesInJSFolder],
options: {
fix: false
}
},
copy: {
main: {
files: [{
src: ["*.html",
"*.css",
"ios.json",
"languages.json",
"mainpages.json",
"*.png"],
dest: distFolder
}]
}
}
} );
grunt.registerTask('default', ['eslint', 'browserify', 'less', 'copy']);
};
|
Add eslint 'fix' flag to config.
|
Add eslint 'fix' flag to config.
Can be flipped to 'true' to auto-fix linting violations!
|
JavaScript
|
mit
|
wikimedia/apps-ios-wikipedia,josve05a/wikipedia-ios,julienbodet/wikipedia-ios,montehurd/apps-ios-wikipedia,josve05a/wikipedia-ios,wikimedia/wikipedia-ios,julienbodet/wikipedia-ios,josve05a/wikipedia-ios,wikimedia/apps-ios-wikipedia,josve05a/wikipedia-ios,wikimedia/apps-ios-wikipedia,julienbodet/wikipedia-ios,josve05a/wikipedia-ios,josve05a/wikipedia-ios,wikimedia/wikipedia-ios,montehurd/apps-ios-wikipedia,wikimedia/wikipedia-ios,montehurd/apps-ios-wikipedia,wikimedia/wikipedia-ios,julienbodet/wikipedia-ios,julienbodet/wikipedia-ios,julienbodet/wikipedia-ios,wikimedia/apps-ios-wikipedia,montehurd/apps-ios-wikipedia,josve05a/wikipedia-ios,montehurd/apps-ios-wikipedia,wikimedia/wikipedia-ios,wikimedia/wikipedia-ios,montehurd/apps-ios-wikipedia,wikimedia/apps-ios-wikipedia,julienbodet/wikipedia-ios,montehurd/apps-ios-wikipedia,wikimedia/wikipedia-ios,josve05a/wikipedia-ios,wikimedia/apps-ios-wikipedia,wikimedia/apps-ios-wikipedia,wikimedia/apps-ios-wikipedia,julienbodet/wikipedia-ios,montehurd/apps-ios-wikipedia
|
5eb4b643651673dac89f53b5cc016b47ff852157
|
src/generator-bin.js
|
src/generator-bin.js
|
#!/usr/bin/env node
const generate = require('./generator')
const program = require('commander')
program
.version('1.0.0')
.option('-w, --words [num]', 'number of words [2]', 2)
.option('-n, --numbers', 'use numbers')
.option('-a, --alliterative', 'use alliterative')
.option('-o --output [output]', 'output type', /^(raw|dashed|spaced)$/i)
.parse(process.argv)
let project_name = generate({words: program.words, number: program.numbers, alliterative: program.alliterative});
if (program.output == "dashed"){
console.log(project_name.dashed);
} else if (program.output == "raw") {
console.log(project_name.raw);
} else if (program.output == "spaced") {
console.log(project_name.spaced);
} else {
console.log(project_name);
}
|
#!/usr/bin/env node
const generate = require('./generator')
const program = require('commander')
program
.version('1.0.0')
.option('-w, --words [num]', 'number of words [2]', 2)
.option('-n, --numbers', 'use numbers')
.option('-a, --alliterative', 'use alliterative')
.option('-o, --output [output]', 'output type [raw|dashed|spaced]', /^(raw|dashed|spaced)$/i)
.parse(process.argv)
let project_name = generate({words: program.words, number: program.numbers, alliterative: program.alliterative});
if (program.output == "dashed"){
console.log(project_name.dashed);
} else if (program.output == "raw") {
console.log(project_name.raw);
} else if (program.output == "spaced") {
console.log(project_name.spaced);
} else {
console.log(project_name);
}
|
Update README for CLI options.
|
Update README for CLI options.
|
JavaScript
|
isc
|
aceakash/project-name-generator
|
9e77430c1f309444c1990877d237cdf991d36d72
|
src/dform.js
|
src/dform.js
|
function dform(formElement) {
var eventEmitter = {
on: function (name, handler) {
this[name] = this[name] || [];
this[name].push(handler);
return this;
},
trigger: function (name, event) {
if (this[name]) {
this[name].map(function (handler) {
handler(event);
});
}
return this;
}
};
var submitElement = formElement.find('[type=submit]');
var inputElements = formElement.find('input, select');
formElement.submit(function (event) {
event.preventDefault();
var formData = {};
$.each(inputElements, function (_, element) {
element = $(element);
var name = element.attr('name');
if (name) {
formData[name] = element.val();
}
});
submitElement.attr('disabled', 'disabled');
eventEmitter.trigger('submit');
$[formElement.attr('method')](formElement.attr('action'), formData)
.always(function () {
submitElement.removeAttr('disabled', 'disabled');
})
.done(function (data) {
eventEmitter.trigger('done', data);
})
.fail(function (jqXHR) {
eventEmitter.trigger('fail', jqXHR);
});
});
submitElement.removeAttr('disabled', 'disabled');
return eventEmitter;
}
|
function dform(formElement) {
var eventEmitter = {
on: function (name, handler) {
this[name] = this[name] || [];
this[name].push(handler);
return this;
},
trigger: function (name, event) {
if (this[name]) {
this[name].map(function (handler) {
handler(event);
});
}
return this;
}
};
var submitElement = formElement.find('[type=submit]');
var inputElements = formElement.find('input, select');
formElement.submit(function (event) {
event.preventDefault();
submitElement.attr('disabled', 'disabled');
var formData = {};
$.each(inputElements, function (_, element) {
element = $(element);
var name = element.attr('name');
if (name) {
formData[name] = element.val();
}
});
eventEmitter.trigger('submit');
$[formElement.attr('method')](formElement.attr('action'), formData)
.always(function () {
submitElement.removeAttr('disabled', 'disabled');
})
.done(function (responseData) {
eventEmitter.trigger('done', responseData);
})
.fail(function (jqXHR) {
eventEmitter.trigger('fail', jqXHR);
});
});
submitElement.removeAttr('disabled', 'disabled');
return eventEmitter;
}
|
Disable button should be the first thing to do
|
Disable button should be the first thing to do
|
JavaScript
|
mit
|
dnode/dform,dnode/dform
|
fc617bc90f25c5e7102c0e76c71d4790599ff23b
|
data-demo/person_udf.js
|
data-demo/person_udf.js
|
function transform(line) {
var values = line.split(',');
var obj = new Object();
obj.name = values[0];
obj.surname = values[1];
obj.timestamp = values[2];
var jsonString = JSON.stringify(obj);
return jsonString;
}
|
/*
Copyright 2022 Google LLC.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
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.
*/
function transform(line) {
var values = line.split(',');
var obj = new Object();
obj.name = values[0];
obj.surname = values[1];
obj.timestamp = values[2];
var jsonString = JSON.stringify(obj);
return jsonString;
}
|
Add a license header on code files
|
Add a license header on code files
Signed-off-by: Laurent Grangeau <919068a1571bc1b5deaaf9ac4d631597f8dd629f@gmail.com>
|
JavaScript
|
apache-2.0
|
GoogleCloudPlatform/deploystack-gcs-to-bq-with-least-privileges
|
f7d9d0a57f691a4d9104ab00c75e1cca8cb2142f
|
src/history.js
|
src/history.js
|
const timetrack = require('./timetrack');
const calculateDuration = require('./calculateDuration');
module.exports = (pluginContext) => {
return (project, env = {}) => {
return new Promise((resolve, reject) => {
timetrack.loadData();
resolve(timetrack.getHistory().map(entry => {
// get the duration of the entry
let duration = 'Running';
if ('stop' in entry) {
duration = calculateDuration(entry.start, entry.stop);
}
// get the project name
const project = entry.project || 'No project';
return {
icon: 'fa-clock-o',
title: `[${duration}] ${project}`,
subtitle: `Nice work bro!`
}
}));
});
}
}
|
const timetrack = require('./timetrack');
const Sugar = require('sugar-date');
const calculateDuration = require('./calculateDuration');
module.exports = (pluginContext) => {
return (project, env = {}) => {
return new Promise((resolve, reject) => {
timetrack.loadData();
resolve(timetrack.getHistory().map(entry => {
try {
// get the duration of the entry
let duration = 'Running';
if ('stop' in entry) {
// sugarjs sets it auto on 1 hour, so i'll just subtract 3600000 for now, fix this later
duration = Sugar.Date.format(Sugar.Date.create(entry.stop - entry.start - 3600000), '%H:%M:%S');
}
// get the project name
const project = entry.project || 'No project';
// get the start date
const startDate = Sugar.Date.format(Sugar.Date.create(entry.start), '%c')
return {
icon: 'fa-clock-o',
title: `[${duration}] ${project}`,
subtitle: `started on ${startDate}`
}
} catch (e) {
alert('fount: ' + e);
}
}));
});
}
}
|
Use sugarjs for date parsing
|
Use sugarjs for date parsing
|
JavaScript
|
mit
|
jnstr/zazu-timetracker
|
a39453fdbfcc397839583d1b695e0476962f9879
|
src/index.js
|
src/index.js
|
'use strict';
import bunyan from 'bunyan';
import http from 'http';
import { createApp } from './app.js';
const logger = bunyan.createLogger({name: "Graphql-Swapi"});
logger.info('Server initialisation...');
createApp()
.then((app) => {
logger.info('Starting HTTP server');
const server = http.createServer(app);
server.listen(8000, ()=> { logger.info('Server is up and running'); });
})
.catch((err) => { logger.error(err); });
|
'use strict';
import bunyan from 'bunyan';
import http from 'http';
import { createApp } from './app.js';
import eventsToAnyPromise from 'events-to-any-promise';
const logger = bunyan.createLogger({name: "Graphql-Swapi"});
function startServer(port, app) {
logger.info('Starting HTTP server');
const server = http.createServer(app);
server.listen(port);
return eventsToAnyPromise(server, 'listening').then(() => {
logger.info('Server is up and running');
return server;
});
}
logger.info('Server initialisation...');
createApp()
.then((app) => startServer(8000, app))
.catch((err) => { logger.error(err); });
|
Use my new lib events-to-any-promise
|
Use my new lib events-to-any-promise
|
JavaScript
|
mit
|
franckLdx/GraphqlSwapi,franckLdx/GraphqlSwapi
|
c6bb66a01539a85c6011eb1c6bd92fb4b7253ca4
|
src/index.js
|
src/index.js
|
'use strict';
const childProcess = require('child-process-promise');
const express = require('express');
const path = require('path');
const fs = require('fs');
const configPath = path.resolve(process.cwd(), process.argv.slice().pop());
const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
const app = express();
async function build (target, args) {
const commands = args.commands;
const options = {
cwd: args.path,
};
console.log(`Deploying ${ target }...`);
for (let i = 0; i < commands.length; i++) {
const date = (new Date()).toLocaleDateString('sv-SE', {
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
});
console.log(`${ date } Running ${ commands[i] }...`);
await childProcess.exec(commands[i], options);
console.log('Done');
}
}
app.post('/', (req, res) => {
const target = req.query.target;
if (config.repos[target]) {
if(req.get('HTTP_X_GITHUB_EVENT') && req.get('HTTP_X_GITHUB_EVENT') === 'push'){
build(target, config.repos[target]);
res.status(200).send();
} else {
res.status(401).send();
}
} else {
res.status(400).send();
}
});
app.listen(config.port, config.host);
|
'use strict';
const childProcess = require('child-process-promise');
const express = require('express');
const path = require('path');
const fs = require('fs');
const configPath = path.resolve(process.cwd(), process.argv.slice().pop());
const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
const app = express();
async function build (target, args) {
const commands = args.commands;
const options = {
cwd: args.path,
};
console.log(`Deploying ${ target }...`);
for (let i = 0; i < commands.length; i++) {
const date = (new Date()).toLocaleDateString('sv-SE', {
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
});
console.log(`${ date } Running ${ commands[i] }...`);
await childProcess.exec(commands[i], options);
console.log('Done');
}
}
app.post('/', (req, res) => {
const target = req.query.target;
if (config.repos[target]) {
if (req.get('x-github-event') && req.get('x-github-event') === 'push') {
build(target, config.repos[target]);
res.status(200).send();
} else {
res.status(401).send();
}
} else {
res.status(400).send();
}
});
app.listen(config.port, config.host);
|
Use correct GitHub header name when checking requests
|
Use correct GitHub header name when checking requests
|
JavaScript
|
mit
|
jwilsson/deployy-mcdeployface
|
85b926b56baa0f29b71b5edea3e83479d1252f69
|
saleor/static/js/components/categoryPage/ProductItem.js
|
saleor/static/js/components/categoryPage/ProductItem.js
|
import React, { Component, PropTypes } from 'react';
import Relay from 'react-relay';
import ProductPrice from './ProductPrice';
class ProductItem extends Component {
static propTypes = {
product: PropTypes.object
};
render() {
const { product } = this.props;
return (
<div className="col-6 col-md-4 product-list" itemScope itemType="https://schema.org/Product">
<a itemProp="url" href={product.url}>
<div className="text-center">
<div>
<img itemProp="image" className="img-responsive" src={product.thumbnailUrl} alt="" />
<span className="product-list-item-name" itemProp="name" title={product.name}>{product.name}</span>
</div>
<div className="panel-footer">
<ProductPrice price={product.price} availability={product.availability} />
</div>
</div>
</a>
</div>
);
}
}
export default Relay.createContainer(ProductItem, {
fragments: {
product: () => Relay.QL`
fragment on ProductType {
id
name
price {
currency
gross
net
}
availability {
${ProductPrice.getFragment('availability')}
}
thumbnailUrl
url
}
`
}
});
|
import React, { Component, PropTypes } from 'react';
import Relay from 'react-relay';
import ProductPrice from './ProductPrice';
class ProductItem extends Component {
static propTypes = {
product: PropTypes.object
};
render() {
const { product } = this.props;
return (
<div className="col-6 col-md-4 product-list" itemScope itemType="https://schema.org/Product">
<a itemProp="url" href={product.url}>
<div className="text-center">
<div>
<img itemProp="image" className="img-responsive" src={product.thumbnailUrl} alt="" />
<span className="product-list-item-name" itemProp="name" title={product.name}>{product.name}</span>
</div>
<div className="panel-footer">
<ProductPrice price={product.price} availability={product.availability} />
</div>
</div>
</a>
</div>
);
}
}
export default Relay.createContainer(ProductItem, {
fragments: {
product: () => Relay.QL`
fragment on ProductType {
id
name
price {
currency
gross
grossLocalized
net
}
availability {
${ProductPrice.getFragment('availability')}
}
thumbnailUrl
url
}
`
}
});
|
Add missing field to query
|
Add missing field to query
|
JavaScript
|
bsd-3-clause
|
jreigel/saleor,UITools/saleor,tfroehlich82/saleor,UITools/saleor,KenMutemi/saleor,UITools/saleor,tfroehlich82/saleor,HyperManTT/ECommerceSaleor,HyperManTT/ECommerceSaleor,jreigel/saleor,mociepka/saleor,KenMutemi/saleor,mociepka/saleor,maferelo/saleor,car3oon/saleor,maferelo/saleor,mociepka/saleor,maferelo/saleor,UITools/saleor,HyperManTT/ECommerceSaleor,itbabu/saleor,UITools/saleor,car3oon/saleor,jreigel/saleor,itbabu/saleor,tfroehlich82/saleor,itbabu/saleor,car3oon/saleor,KenMutemi/saleor
|
5927b98e608128152adafed5435fd2ec47a04237
|
src/slide.js
|
src/slide.js
|
const DEFAULT_IN = 'fadeIn'
const DEFAULT_OUT = 'fadeOut'
class Slide extends BaseElement {
static get observedAttributes () {
return ['active', 'in', 'out']
}
get active () {
return this.hasAttribute('active')
}
set active (value) {
value ? this.setAttribute('active', '')
: this.removeAttribute('active')
}
get in () {
return this.getAttribute('in') || DEFAULT_IN
}
get out () {
return this.getAttribute('out') || DEFAULT_OUT
}
onConnect() {
this.style.cssText = `
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
`
this.classList.add('animated')
}
renderCallback () {
if (this.active) {
this.classList.add(this.in)
this.classList.remove(this.out)
} else {
this.classList.add(this.out)
this.classList.remove(this.in)
}
}
}
customElements.define('x-slide', Slide)
|
const DEFAULT_IN = 'fadeIn'
const DEFAULT_OUT = 'fadeOut'
class Slide extends BaseElement {
static get observedAttributes () {
return ['active', 'in', 'out']
}
get active () {
return this.hasAttribute('active')
}
set active (value) {
value ? this.setAttribute('active', '')
: this.removeAttribute('active')
}
get in () {
return this.getAttribute('in') || DEFAULT_IN
}
get out () {
return this.getAttribute('out') || DEFAULT_OUT
}
onConnect() {
this.classList.add('animated')
Object.assign(this.style, this.inlineCSS())
}
renderCallback () {
if (this.active) {
this.classList.add(this.in)
this.classList.remove(this.out)
} else {
this.classList.add(this.out)
this.classList.remove(this.in)
}
}
inlineCSS() {
return {
position: 'fixed',
top: 0,
left: 0,
display: 'flex',
width: '100%',
height: '100%',
background: 'black',
fontFamily: 'BlinkMacSystemFont, sans-serif',
borderWidth: '30px',
borderStyle: 'solid',
padding: '100px'
}
}
}
customElements.define('x-slide', Slide)
|
Simplify inline styles for inheritance
|
Simplify inline styles for inheritance
|
JavaScript
|
mit
|
ricardocasares/using-custom-elements,ricardocasares/using-custom-elements
|
b47017282e23be837d469378e5d1ac307f8d99c1
|
client/app/scripts/directive/projectQuickView.js
|
client/app/scripts/directive/projectQuickView.js
|
angular
.module('app')
.directive('projectQuickView', function() {
return {
restrict: 'EA',
replace: false,
templateUrl: 'app/templates/partials/projectQuickView.html',
link: function(scope, element, attrs) {
scope.completed = attrs.completed;
scope.hasDate = function() {
return scope.item.end_date && scope.item.end_date !== null;
};
scope.isContentFromOldSite = function(item) {
return scope.item.end_date == "2012-10-20T04:00:00.000Z";
};
scope.completedStamp = function(item) {
return scope.completed && !scope.isContentFromOldSite(item);
};
}
};
});
|
angular
.module('app')
.directive('projectQuickView', function() {
return {
restrict: 'EA',
replace: false,
templateUrl: 'app/templates/partials/projectQuickView.html',
link: function(scope, element, attrs) {
scope.completed = attrs.completed;
scope.hasDate = function() {
return scope.item && scope.item.end_date && scope.item.end_date !== null;
};
scope.isContentFromOldSite = function(item) {
return item && item.end_date == "2012-10-20T04:00:00.000Z";
};
scope.completedStamp = function(item) {
return scope.completed && !scope.isContentFromOldSite(item);
};
}
};
});
|
Make a check if end_date exists on the project in the hasDate function
|
Make a check if end_date exists on the project in the hasDate function
|
JavaScript
|
mit
|
brettshollenberger/rootstrikers,brettshollenberger/rootstrikers
|
ae93a807f90a0b59101443d28a88cf934e536e4e
|
src/Calibrator.js
|
src/Calibrator.js
|
import {VM} from 'vm2'
import SensorData from './SensorData'
export default class Calibrator {
calibrate (data, cb) {
if ( ! (data instanceof SensorData)) return cb('Invalid SensorData given.')
var meta = data.getMetadata()
meta.getAttributes().forEach(function (attr) {
attr.getProperties().forEach(function (prop) {
if (prop.name !== 'calibrate') return
var vm = new VM({
timeout: 1000,
sandbox: {
val: data.getValue(attr.getName())
},
})
var value = vm.run('(' + decodeURI(prop.value) + ')(val)')
data.setValue(attr.getName(), value)
})
})
cb()
}
}
|
import {VM} from 'vm2'
import SensorData from './SensorData'
export default class Calibrator {
calibrate (data, cb) {
if ( ! (data instanceof SensorData)) return cb('Invalid SensorData given.')
var meta = data.getMetadata()
meta.getAttributes().forEach(function (attr) {
attr.getProperties().forEach(function (prop) {
if (prop.name !== 'calibrate') return
var vm = new VM({
timeout: 1000,
sandbox: {
Math: Math,
val: data.getValue(attr.getName())
},
})
var value = vm.run('(' + decodeURI(prop.value.toString()) + ')(val)')
data.setValue(attr.getName(), value)
})
})
cb()
}
}
|
Add Math to calibrator VM and allow use of functions (not only function strings).
|
Add Math to calibrator VM and allow use of functions (not only function strings).
|
JavaScript
|
mit
|
kukua/concava
|
769ceb537eec6642fd039ea7ad0fa074029759b1
|
share/spice/arxiv/arxiv.js
|
share/spice/arxiv/arxiv.js
|
(function (env) {
"use strict";
env.ddg_spice_arxiv = function(api_result){
if (!api_result) {
return Spice.failed('arxiv');
}
Spice.add({
id: "arxiv",
name: "Reference",
data: api_result,
meta: {
sourceName: "arxiv.org",
sourceUrl: api_result.feed.entry.link[0].href
},
normalize: function(item) {
return {
title: item.feed.entry.title.text,
url: item.feed.entry.link[0].href,
subtitle: item.feed.entry.author.map( function(e) {
return e.name.text;
} ).join(', '),
description: item.feed.entry.summary.text
};
},
templates: {
group: 'info',
options: {
moreAt: true
}
}
});
};
}(this));
|
(function (env) {
"use strict";
env.ddg_spice_arxiv = function(api_result){
if (!api_result) {
return Spice.failed('arxiv');
}
Spice.add({
id: "arxiv",
name: "Reference",
data: api_result,
meta: {
sourceName: "arxiv.org",
sourceUrl: api_result.feed.entry.link[0].href
},
normalize: function(item) {
return {
title: sprintf( "%s (%s)",
item.feed.entry.title.text,
item.feed.entry.published.text.replace( /^(\d{4}).*/, "$1" )
),
url: item.feed.entry.link[0].href,
subtitle: item.feed.entry.author.map( function(e) {
return e.name.text;
} ).join(', '),
description: item.feed.entry.summary.text
};
},
templates: {
group: 'info',
options: {
moreAt: true
}
}
});
};
}(this));
|
Add published year to title
|
Add published year to title
|
JavaScript
|
apache-2.0
|
bigcurl/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,levaly/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,imwally/zeroclickinfo-spice,soleo/zeroclickinfo-spice,P71/zeroclickinfo-spice,soleo/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,lerna/zeroclickinfo-spice,imwally/zeroclickinfo-spice,lernae/zeroclickinfo-spice,deserted/zeroclickinfo-spice,soleo/zeroclickinfo-spice,lerna/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,lernae/zeroclickinfo-spice,soleo/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,lerna/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,soleo/zeroclickinfo-spice,levaly/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,levaly/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,P71/zeroclickinfo-spice,imwally/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,levaly/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,deserted/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,deserted/zeroclickinfo-spice,soleo/zeroclickinfo-spice,P71/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,imwally/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,deserted/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,P71/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,lerna/zeroclickinfo-spice,imwally/zeroclickinfo-spice,lernae/zeroclickinfo-spice,lerna/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,lernae/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,levaly/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,lernae/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,lernae/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,levaly/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,deserted/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,deserted/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice
|
2897631e9330289d95ddbab0aa3b13f5d24d1d81
|
web/js/calendar-template.js
|
web/js/calendar-template.js
|
function cookieValueHandler() {
Cookies.set(this.name, this.value, 365)
window.location.reload()
}
function registerSpecialInputs() {
$$("input").each(function(input) {
if (input.getAttribute("special") == "cookie") {
Event.observe(input, "click", cookieValueHandler)
if (input.type == "radio" && Cookies.get(input.name) == input.value) {
input.checked = true
}
}
});
}
Event.observe(window, 'load', registerSpecialInputs)
|
function cookieValueHandler(event) {
var src = Event.element(event)
Cookies.set(src.name, src.value, 365)
window.location.reload()
}
function registerSpecialInputs() {
$$("input").each(function(input) {
if (input.getAttribute("special") == "cookie") {
Event.observe(input, "click", cookieValueHandler)
if (input.type == "radio" && Cookies.get(input.name) == input.value) {
input.checked = true
}
}
});
}
Event.observe(window, 'load', registerSpecialInputs)
|
Fix cookieValueHandler to work with IE
|
Fix cookieValueHandler to work with IE
git-svn-id: 4b387fe5ada7764508e2ca96c335714e4c1692c6@406 0d517254-b314-0410-acde-c619094fa49f
|
JavaScript
|
bsd-3-clause
|
NUBIC/psc-mirror,NUBIC/psc-mirror,NUBIC/psc-mirror,NUBIC/psc-mirror
|
3ee8995af1835156d7c94a3f6480d48396884f5c
|
dashboard/src/store/store.js
|
dashboard/src/store/store.js
|
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export default new Vuex.Store({
state: {},
mutations: {},
actions: {},
modules: {}
});
|
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export default new Vuex.Store({
strict: process.env.NODE_ENV !== "production", //see https://vuex.vuejs.org/guide/strict.html
state: {},
mutations: {},
actions: {},
modules: {}
});
|
Enable VueX strict mode in dev
|
Enable VueX strict mode in dev
|
JavaScript
|
agpl-3.0
|
napstr/wolfia,napstr/wolfia,napstr/wolfia
|
1bc6d05e92432dbf503483e3f74d8a3fd456b4a6
|
gulpfile.js
|
gulpfile.js
|
var gulp = require('gulp');
var $ = require('gulp-load-plugins')({ lazy: false });
var source = require('vinyl-source-stream2');
var browserify = require('browserify');
var path = require('path');
var pkg = require('./package.json');
var banner = ['/**',
' * <%= pkg.name %> - <%= pkg.description %>',
' * @version v<%= pkg.version %>',
' * @author <%= pkg.author %>',
' * @link <%= pkg.homepage %>',
' * @license <%= pkg.license %>',
' */',
''].join('\n');
gulp.task('test', function() {
return gulp.src('test/**/*.test.js', { read: false })
.pipe($.mocha({
reporter: 'mocha-better-spec-reporter'
}));
});
gulp.task('script', function () {
var bundleStream = browserify({
entries: './lib/should.js',
builtins: ['util', 'assert']
})
.bundle({
insertGlobals: false,
detectGlobals: false,
standalone: 'Should'
});
return bundleStream
.pipe(source('should.js'))
.pipe($.header(banner, { pkg : pkg } ))
.pipe(gulp.dest('./'))
.pipe($.uglify())
.pipe($.header(banner, { pkg : pkg } ))
.pipe($.rename('should.min.js'))
.pipe(gulp.dest('./'));
});
|
var gulp = require('gulp');
var $ = require('gulp-load-plugins')({ lazy: false });
var source = require('vinyl-source-stream2');
var browserify = require('browserify');
var path = require('path');
var pkg = require('./package.json');
var banner = ['/**',
' * <%= pkg.name %> - <%= pkg.description %>',
' * @version v<%= pkg.version %>',
' * @author <%= pkg.author %>',
' * @link <%= pkg.homepage %>',
' * @license <%= pkg.license %>',
' */',
''].join('\n');
gulp.task('test', function() {
return gulp.src('test/**/*.test.js', { read: false })
.pipe($.mocha({
reporter: 'mocha-better-spec-reporter'
}));
});
gulp.task('script', function () {
var bundleStream = browserify({
entries: './lib/should.js',
builtins: ['util', 'assert'],
insertGlobals: false,
detectGlobals: false,
standalone: 'Should'
})
.bundle();
return bundleStream
.pipe(source('should.js'))
.pipe($.header(banner, { pkg : pkg } ))
.pipe(gulp.dest('./'))
.pipe($.uglify())
.pipe($.header(banner, { pkg : pkg } ))
.pipe($.rename('should.min.js'))
.pipe(gulp.dest('./'));
});
|
Fix bundle arguments for latest browserify
|
Fix bundle arguments for latest browserify
|
JavaScript
|
mit
|
ngot/should.js,Lucifier129/should.js,Qix-/should.js,shouldjs/should.js,shouldjs/should.js,hakatashi/wa.js,enicholson/should.js
|
4156b07d63af7e23ac8138bc233747727310d407
|
gulpfile.js
|
gulpfile.js
|
'use strict';
var gulp = require('gulp');
var shell = require('gulp-shell')
var sass = require('gulp-sass');
var electron = require('electron-connect').server.create();
gulp.task('serve', function () {
// Compile the sass
gulp.start('sass');
// Start browser process
electron.start();
// Restart browser process
gulp.watch('main.js', electron.restart);
// Reload renderer process
gulp.watch(['index.js', 'index.html', 'index.scss'], function(){
gulp.start('sass');
electron.reload()
});
});
gulp.task('build', shell.task([
'electron-packager . --overwrite --platform=darwin --icon=assets/icons/mac/icon.icns --arch=x64 --prune=true --out=release_builds'
]))
gulp.task('sass', function () {
return gulp.src('./*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./'));
});
|
'use strict';
var gulp = require('gulp');
var shell = require('gulp-shell')
var sass = require('gulp-sass');
var electron = require('electron-connect').server.create();
var package_info = require('./package.json')
gulp.task('serve', function () {
// Compile the sass
gulp.start('sass');
// Start browser process
electron.start();
// Restart browser process
gulp.watch('main.js', electron.restart);
// Reload renderer process
gulp.watch(['index.js', 'index.html', 'index.scss'], function(){
gulp.start('sass');
electron.reload()
});
});
gulp.task('build-all', shell.task([
'electron-packager . --overwrite --platform=all --arch=all --prune=true --out=release_builds'
]));
gulp.task('build-mac', shell.task([
'electron-packager . --overwrite --platform=darwin --icon=assets/icons/mac/icon.icns --arch=x64 --prune=true --out=release_builds'
]));
gulp.task('zip', shell.task([
`zip -FSr release_builds/opsdroid-desktop-darwin-x64/opsdroid-desktop-${package_info.version}-macos-x64.zip release_builds/opsdroid-desktop-darwin-x64/opsdroid-desktop.app`
]));
gulp.task('sass', function () {
return gulp.src('./*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./'));
});
|
Make builds platform specific and add zipping
|
Make builds platform specific and add zipping
|
JavaScript
|
apache-2.0
|
opsdroid/opsdroid-desktop,opsdroid/opsdroid-desktop
|
f7bd0b4865f0dadc77a33c1168c5239916b05614
|
gulpfile.js
|
gulpfile.js
|
var gulp = require('gulp'),
coffee = require('gulp-coffee'),
concat = require('gulp-concat'),
uglify = require('gulp-uglify'),
sourcemaps = require('gulp-sourcemaps'),
del = require('del');
var paths = {
scripts: ['source/**/*.coffee']
};
gulp.task('clean', function (cb) {
del(['build'], cb);
});
// Compiles coffee to js
gulp.task('scripts', ['clean'], function () {
return gulp.src(paths.scripts)
.pipe(sourcemaps.init())
.pipe(coffee({bare: true}))
//.pipe(uglify())
.pipe(concat('all.min.js'))
.pipe(sourcemaps.write())
.pipe(gulp.dest('build'));
});
gulp.task('watch', function () {
gulp.watch(paths.scripts, ['scripts']);
});
gulp.task('default', ['watch', 'scripts']);
|
var gulp = require('gulp'),
coffee = require('gulp-coffee'),
concat = require('gulp-concat'),
uglify = require('gulp-uglify'),
sourcemaps = require('gulp-sourcemaps'),
del = require('del'),
karma = require('karma').server;
var paths = {
scripts: ['source/**/*.coffee']
};
gulp.task('clean', function (cb) {
del(['build'], cb);
});
// Compiles coffee to js
gulp.task('scripts', ['clean'], function () {
return gulp.src(paths.scripts)
.pipe(sourcemaps.init())
.pipe(coffee({bare: true}))
//.pipe(uglify())
.pipe(concat('all.min.js'))
.pipe(sourcemaps.write())
.pipe(gulp.dest('build'));
});
gulp.task('watch', function () {
gulp.watch(paths.scripts, ['scripts']);
});
// Run test once and exit
gulp.task('test', function (done) {
karma.start({
configFile: __dirname + '/karma.conf.js',
singleRun: true
}, done);
});
// Watch for file changes and re-run tests on each change
gulp.task('tdd', function (done) {
karma.start({
configFile: __dirname + '/karma.conf.js'
}, done);
});
gulp.task('default', ['tdd']);
|
Add tasks test and tdd
|
Add tasks test and tdd
|
JavaScript
|
mit
|
mkawalec/latte-art
|
b7d67f8a8581df15bf526f0e493b9ab626cab924
|
Resources/public/js/select24entity.js
|
Resources/public/js/select24entity.js
|
$(document).ready(function () {
$.fn.select24entity = function (action) {
// Create the parameters array with basic values
var select24entityParam = {
ajax: {
data: function (params) {
return {
q: params.term
};
},
processResults: function (data) {
return {
results: data
};
},
cache: true,
tags: false
}
};
// Extend the parameters array with the one in arguments
$.extend(select24entityParam, action);
// Activate the select2 field
this.select2(select24entityParam);
// If we have tag support activated, add a listener to add "new_" in front of new entries.
if (select24entityParam.tags === true) {
this.on('select2:selecting', function (e) {
if (e.params.args.data.id === e.params.args.data.text) {
e.params.args.data.id = 'new_' + e.params.args.data.id;
}
});
}
// Return current field
return this;
};
});
|
$(document).ready(function () {
$.fn.select24entity = function (action) {
// Create the parameters array with basic values
var select24entityParam = {
ajax: {
data: function (params) {
return {
q: params.term
};
},
processResults: function (data) {
return {
results: data
};
},
cache: true
},
tags: false
};
// Extend the parameters array with the one in arguments
$.extend(select24entityParam, action);
// Activate the select2 field
this.select2(select24entityParam);
// If we have tag support activated, add a listener to add "new_" in front of new entries.
if (select24entityParam.tags === true) {
this.on('select2:selecting', function (e) {
if (e.params.args.data.id === e.params.args.data.text) {
e.params.args.data.id = 'new_' + e.params.args.data.id;
}
});
}
// Return current field
return this;
};
});
|
Fix place of "tags" option in the default options
|
Fix place of "tags" option in the default options
|
JavaScript
|
mit
|
sharky98/select24entity-bundle,sharky98/select24entity-bundle,sharky98/select24entity-bundle
|
b46ae05b9622867dfdbfe30402f2848b2770fee8
|
test/DOM/main.js
|
test/DOM/main.js
|
// This is a simple test that is meant to demonstrate the ability
// interact with the 'document' instance from the global scope.
//
// Thus, the line: `exports.document = document;`
// or something similar should be done in your main module.
module.load('./DOM', function(DOM) {
// A wrapper for 'document.createElement()'
var foo = new (DOM.Element)('h1');
// Sets the 'innerHTML'
foo.update('It Works! <a href="..">Go Back</a>');
// Appends to the <body> tag
DOM.insert(foo);
});
|
// This is a simple test that is meant to demonstrate the ability
// interact with the 'document' instance from the global scope.
//
// Thus, the line: `exports.document = document;`
// or something similar should be done in your main module.
module.load('./DOM', function(DOM) {
// A wrapper for 'document.createElement()'
var foo = new (DOM.Element)('h1');
// Sets the 'innerHTML'
foo.update('It Works! <a href="../index.html">Go Back</a>');
// Appends to the <body> tag
DOM.insert(foo);
});
|
Make the link work from a "file://" URI.
|
Make the link work from a "file://" URI.
|
JavaScript
|
mit
|
TooTallNate/ModuleJS
|
5f8631362875b2cafe042c7121cc293615cfffe0
|
test/test-app.js
|
test/test-app.js
|
/*global describe, beforeEach, it*/
'use strict';
var path = require('path');
var assert = require('yeoman-generator').assert;
var helpers = require('yeoman-generator').test;
var os = require('os');
describe('hubot:app', function () {
before(function (done) {
helpers.run(path.join(__dirname, '../app'))
.inDir(path.join(os.tmpdir(), './temp-test'))
.withOptions({ 'skip-install': true })
.withPrompt({
someOption: true
})
.on('end', done);
});
it('creates files', function () {
assert.file([
'bower.json',
'package.json',
'.editorconfig',
'.jshintrc'
]);
});
});
|
/*global describe, beforeEach, it*/
'use strict';
var path = require('path');
var assert = require('yeoman-generator').assert;
var helpers = require('yeoman-generator').test;
var os = require('os');
describe('hubot:app', function () {
before(function (done) {
helpers.run(path.join(__dirname, '../app'))
.inDir(path.join(os.tmpdir(), './temp-test'))
.withOptions({ 'skip-install': true })
.withPrompt({
someOption: true
})
.on('end', done);
});
it('creates files', function () {
assert.file([
'bin/hubot',
'bin/hubot.cmd',
'Procfile',
'README.md',
'external-scripts.json',
'hubot-scripts.json',
'.gitignore',
'package.json',
'scripts/example.coffee',
'.editorconfig',
]);
});
});
|
Fix assertion for not existing files
|
Fix assertion for not existing files
|
JavaScript
|
mit
|
ArLEquiN64/generator-hubot-gulp,m-seldin/generator-hubot-enterprise,eedevops/generator-hubot-enterprise,eedevops/generator-hubot-enterprise,ArLEquiN64/generator-hubot-gulp,zarqin/generator-hubot,github/generator-hubot,mal/generator-hubot,zarqin/generator-hubot,mal/generator-hubot,m-seldin/generator-hubot-enterprise,ClaudeBot/generator-hubot,ClaudeBot/generator-hubot,github/generator-hubot
|
66b15d29269455a5cf24164bd1982f7f01c323f3
|
src/parse/expr.js
|
src/parse/expr.js
|
var expr = require('vega-expression'),
args = ['datum', 'event', 'signals'];
module.exports = expr.compiler(args, {
idWhiteList: args,
fieldVar: args[0],
globalVar: args[2],
functions: function(codegen) {
var fn = expr.functions(codegen);
fn.item = function() { return 'event.vg.item'; };
fn.group = 'event.vg.getGroup';
fn.mouseX = 'event.vg.getX';
fn.mouseY = 'event.vg.getY';
fn.mouse = 'event.vg.getXY';
return fn;
}
});
|
var expr = require('vega-expression'),
args = ['datum', 'event', 'signals'];
module.exports = expr.compiler(args, {
idWhiteList: args,
fieldVar: args[0],
globalVar: args[2],
functions: function(codegen) {
var fn = expr.functions(codegen);
fn.eventItem = function() { return 'event.vg.item'; };
fn.eventGroup = 'event.vg.getGroup';
fn.eventX = 'event.vg.getX';
fn.eventY = 'event.vg.getY';
return fn;
}
});
|
Update to revised event methods.
|
Update to revised event methods.
|
JavaScript
|
bsd-3-clause
|
chiu/vega,smclements/vega,seyfert/vega,mathisonian/vega-browserify,carabina/vega,mcanthony/vega,shaunstanislaus/vega,Jerrythafast/vega,Jerrythafast/vega,cesine/vega,shaunstanislaus/vega,lgrammel/vega,Applied-Duality/vega,smclements/vega,smartpcr/vega,smartpcr/vega,mcanthony/vega,mathisonian/vega-browserify,pingjiang/vega,timelyportfolio/vega,jsanch/vega,uwdata/vega,smclements/vega,nyurik/vega,pingjiang/vega,nyurik/vega,gdseller/vega,jsanch/vega,carabina/vega,gdseller/vega,cesine/vega,Jerrythafast/vega,cesine/vega,mcanthony/vega,gdseller/vega,Applied-Duality/vega,seyfert/vega,shaunstanislaus/vega,uwdata/vega,vega/vega,smartpcr/vega,carabina/vega,pingjiang/vega,timelyportfolio/vega,linearregression/vega,nyurik/vega,mathisonian/vega-browserify,jsanch/vega,vega/vega,linearregression/vega,linearregression/vega,chiu/vega,seyfert/vega,Applied-Duality/vega,vega/vega,vega/vega,chiu/vega
|
02475ac2b8ca9832733bbf01fbf49c80c8f5c66a
|
src/lang-proto.js
|
src/lang-proto.js
|
// Copyright (C) 2006 Google Inc.
//
// 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.
/**
* @fileoverview
* Registers a language handler for Protocol Buffers as described at
* http://code.google.com/p/protobuf/.
*
* Based on the lexical grammar at
* http://research.microsoft.com/fsharp/manual/spec2.aspx#_Toc202383715
*
* @author mikesamuel@gmail.com
*/
PR['registerLangHandler'](PR['sourceDecorator']({
keywords: (
'bool bytes default double enum extend extensions false fixed32 '
+ 'fixed64 float group import int32 int64 max message option '
+ 'optional package repeated required returns rpc service '
+ 'sfixed32 sfixed64 sint32 sint64 string syntax to true uint32 '
+ 'uint64'),
cStyleComments: true
}), ['proto']);
|
// Copyright (C) 2006 Google Inc.
//
// 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.
/**
* @fileoverview
* Registers a language handler for Protocol Buffers as described at
* http://code.google.com/p/protobuf/.
*
* Based on the lexical grammar at
* http://research.microsoft.com/fsharp/manual/spec2.aspx#_Toc202383715
*
* @author mikesamuel@gmail.com
*/
PR['registerLangHandler'](PR['sourceDecorator']({
'keywords': (
'bytes,default,double,enum,extend,extensions,false,'
+ 'group,import,max,message,option,'
+ 'optional,package,repeated,required,returns,rpc,service,'
+ 'syntax,to,true'),
'types': /^(bool|(double|s?fixed|[su]?int)(32|64)|float|string)\b/,
'cStyleComments': true
}), ['proto']);
|
Fix proto lang handler to work minified and to use the type style for types like uint32.
|
Fix proto lang handler to work minified and to use the type style for types like uint32.
|
JavaScript
|
apache-2.0
|
ebidel/google-code-prettify,tcollard/google-code-prettify,tcollard/google-code-prettify,ebidel/google-code-prettify,tcollard/google-code-prettify
|
e89d777b928d212b95ce639256de4e38c1788a77
|
src/routes/api.js
|
src/routes/api.js
|
// Api Routes --
// RESTful API cheat sheet : http://ricostacruz.com/cheatsheets/rest-api.html
var express = require('express'),
router = express.Router(),
db = require('../modules/database');
/* GET users listing. */
router.get('/', function(req, res, next) {
res.json({
message: 'Hello world!'
});
});
router.get('/users', function(req, res, next) {
db.select('first_name', 'last_name', 'username').from('User').where({active: true}).all()
.then(function (users) {
res.json({
users
});
});
});
module.exports = router;
|
// Api Routes --
// RESTful API cheat sheet : http://ricostacruz.com/cheatsheets/rest-api.html
var express = require('express'),
router = express.Router(),
db = require('../modules/database');
/* GET users listing. */
router.get('/', function(req, res, next) {
res.json({
message: 'Hello world!'
});
});
router.get('/users', function(req, res, next) {
db.select('first_name', 'last_name', 'username').from('User').where({active: true}).all()
.then(function (users) {
res.json({
users
});
});
});
router.get('/users/:username', function (req, res) {
db.select().from('User').where({active: true, 'username': req.param('username')}).all()
.then(function (user) {
res.json({
user
});
});
});
module.exports = router;
|
Add get one user in API
|
Add get one user in API
|
JavaScript
|
mit
|
AnimalTracker/AnimalTracker,AnimalTracker/AnimalTracker
|
53a27ad98440fb40c5d13f0415ee0ac348289ca1
|
app/extension-scripts/main.js
|
app/extension-scripts/main.js
|
(function() {
chrome.browserAction.onClicked.addListener(function() {
var newURL = "chrome-extension://" + chrome.runtime.id + "/index.html";
chrome.tabs.create({ url: newURL });
});
})();
|
(function() {
chrome.browserAction.onClicked.addListener(function() {
var appUrl = chrome.extension.getURL('index.html');
chrome.tabs.create({ url: appUrl });
});
})();
|
Use builtin to build url
|
Use builtin to build url
|
JavaScript
|
mit
|
chrisfried/DIM,bhollis/DIM,DestinyItemManager/DIM,48klocs/DIM,bhollis/DIM,delphiactual/DIM,chrisfried/DIM,bhollis/DIM,DestinyItemManager/DIM,LouisFettet/DIM,48klocs/DIM,delphiactual/DIM,bhollis/DIM,LouisFettet/DIM,DestinyItemManager/DIM,chrisfried/DIM,48klocs/DIM,delphiactual/DIM,chrisfried/DIM,delphiactual/DIM,DestinyItemManager/DIM
|
b7f05eeb90ceeb53ce14d2a23ee73300cce61f92
|
lib/querystring.js
|
lib/querystring.js
|
// based on the qs module, but handles null objects as expected
// fixes by Tomas Pollak.
function stringify(obj, prefix) {
if (prefix && (obj === null || typeof obj == 'undefined')) {
return prefix + '=';
} else if (obj.constructor == Array) {
return stringifyArray(obj, prefix);
} else if (obj !== null && typeof obj == 'object') {
return stringifyObject(obj, prefix);
} else if (prefix) { // string inside array or hash
return prefix + '=' + encodeURIComponent(String(obj));
} else if (String(obj).indexOf('=') !== -1) { // string with equal sign
return String(obj);
} else {
throw new TypeError('Cannot build a querystring out of: ' + obj);
}
};
function stringifyArray(arr, prefix) {
var ret = [];
for (var i = 0, len = arr.length; i < len; i++) {
if (prefix)
ret.push(stringify(arr[i], prefix + '[' + i + ']'));
else
ret.push(stringify(arr[i]));
}
return ret.join('&');
}
function stringifyObject(obj, prefix) {
var ret = [];
Object.keys(obj).forEach(function(key) {
ret.push(stringify(obj[key], prefix
? prefix + '[' + encodeURIComponent(key) + ']'
: encodeURIComponent(key)));
})
return ret.join('&');
}
exports.build = stringify;
|
// based on the qs module, but handles null objects as expected
// fixes by Tomas Pollak.
var toString = Object.prototype.toString;
function stringify(obj, prefix) {
if (prefix && (obj === null || typeof obj == 'undefined')) {
return prefix + '=';
} else if (toString.call(obj) == '[object Array]') {
return stringifyArray(obj, prefix);
} else if (toString.call(obj) == '[object Object]') {
return stringifyObject(obj, prefix);
} else if (toString.call(obj) == '[object Date]') {
return obj.toISOString();
} else if (prefix) { // string inside array or hash
return prefix + '=' + encodeURIComponent(String(obj));
} else if (String(obj).indexOf('=') !== -1) { // string with equal sign
return String(obj);
} else {
throw new TypeError('Cannot build a querystring out of: ' + obj);
}
};
function stringifyArray(arr, prefix) {
var ret = [];
for (var i = 0, len = arr.length; i < len; i++) {
if (prefix)
ret.push(stringify(arr[i], prefix + '[' + i + ']'));
else
ret.push(stringify(arr[i]));
}
return ret.join('&');
}
function stringifyObject(obj, prefix) {
var ret = [];
Object.keys(obj).forEach(function(key) {
ret.push(stringify(obj[key], prefix
? prefix + '[' + encodeURIComponent(key) + ']'
: encodeURIComponent(key)));
})
return ret.join('&');
}
exports.build = stringify;
|
Add support for Dates to stringify, also improve stringify Object and Array
|
Add support for Dates to stringify, also improve stringify Object and Array
|
JavaScript
|
mit
|
tomas/needle,tomas/needle
|
7b6f45b5970766e1ce85c51c0e3d471b41f6a7d6
|
app/helpers/takeScreenshot.js
|
app/helpers/takeScreenshot.js
|
import { remote } from 'electron'
export default async function takeScreenshot (html, deviceWidth) {
return new Promise(resolve => {
const win = new remote.BrowserWindow({
width: deviceWidth,
show: false,
})
win.loadURL(`data:text/html, ${html}`)
win.webContents.on('did-finish-load', () => {
// Window is not fully loaded after this event, hence setTimeout()...
win.webContents.executeJavaScript('document.querySelector(\'body\').getBoundingClientRect().height', (height) => {
win.setSize(deviceWidth, height)
setTimeout(() => {
win.webContents.capturePage((img) => { // eslint-disable-line
win.close()
resolve(img.toPng())
})
}, 500)
})
})
})
}
|
import { remote } from 'electron'
import path from 'path'
import os from 'os'
import { fsWriteFile } from 'helpers/fs'
const TMP_DIR = os.tmpdir()
export default async function takeScreenshot (html, deviceWidth) {
return new Promise(async resolve => {
const win = new remote.BrowserWindow({
width: deviceWidth,
show: false,
})
const tmpFileName = path.join(TMP_DIR, 'tpm-mjml-preview.html')
await fsWriteFile(tmpFileName, html)
win.loadURL(`file://${tmpFileName}`)
win.webContents.on('did-finish-load', () => {
// Window is not fully loaded after this event, hence setTimeout()...
win.webContents.executeJavaScript('document.querySelector(\'body\').getBoundingClientRect().height', (height) => {
win.setSize(deviceWidth, height)
setTimeout(() => {
win.webContents.capturePage((img) => { // eslint-disable-line
win.close()
resolve(img.toPng())
})
}, 500)
})
})
})
}
|
Use file to generate screenshot
|
Use file to generate screenshot
|
JavaScript
|
mit
|
mjmlio/mjml-app,mjmlio/mjml-app,mjmlio/mjml-app
|
2106cfa5b5905945ae2899441995c6c6451717ab
|
src/apps/interactions/macros/kind-form.js
|
src/apps/interactions/macros/kind-form.js
|
module.exports = function ({
returnLink,
errors = [],
}) {
return {
buttonText: 'Continue',
errors,
children: [
{
macroName: 'MultipleChoiceField',
type: 'radio',
label: 'What would you like to record?',
name: 'kind',
options: [{
value: 'interaction',
label: 'A standard interaction',
hint: 'For example, an email, phone call or meeting',
}, {
value: 'service_delivery',
label: 'A service that you have provided',
hint: 'For example, account management, a significant assist or an event',
},
/*, {
value: 'policy_feedback',
label: 'Policy feedback',
hint: 'For example, when a company wants to give UK government policy feedback',
} */
],
},
],
}
}
|
module.exports = function ({
returnLink,
errors = [],
}) {
return {
buttonText: 'Continue',
errors,
children: [{
macroName: 'MultipleChoiceField',
type: 'radio',
label: 'What would you like to record?',
name: 'kind',
options: [{
value: 'interaction',
label: 'A standard interaction',
hint: 'For example, an email, phone call or meeting',
}, {
value: 'service_delivery',
label: 'A service that you have provided',
hint: 'For example, account management, a significant assist or an event',
},
{
value: 'policy_feedback',
label: 'Capture policy feedback',
hint: 'For example, and issue or comment on government policy from a company',
}],
}],
}
}
|
Enable policy feedback in interaction creation selection
|
Enable policy feedback in interaction creation selection
|
JavaScript
|
mit
|
uktrade/data-hub-fe-beta2,uktrade/data-hub-frontend,uktrade/data-hub-frontend,uktrade/data-hub-fe-beta2,uktrade/data-hub-frontend
|
0734e87bfa82d268366a46b29d3f54f14754d09d
|
js/swipe.js
|
js/swipe.js
|
$(document).ready(function(){
$('.swipeGal').each(function(i, obj){
});
});
|
flickrParser = function(json){
var imageList = []
$(json.items).each(function(i, image){
imageList.push({
'title':image.title,
'artist':image.author,
'url':image.link,
'image':image.media.m});
})
return imageList;
}
$(document).ready(function(){
$('.swipeGal').each(function(i, obj){
var feedid = $(obj).data('feed-id');
var url = 'http://ycpi.api.flickr.com/services/feeds/groups_pool.gne?id='+feedid+'&jsoncallback=?';
$.getJSON(url, {format: "json"})
.done(function(data){
parsedImages = flickrParser(data);
//console.log(parsedImages);
});
});
});
|
Make request to flickr for group images and parse results into a standard json format.
|
Make request to flickr for group images and parse results into a standard json format.
|
JavaScript
|
mit
|
neilvallon/Swipe-Gallery,neilvallon/Swipe-Gallery
|
0ceb155aad0bad3d343194227b82fa8e074f7b07
|
src/js/collections/pool.js
|
src/js/collections/pool.js
|
define(['backbone', '../models/dataset/connection'],
function(Backbone, Connection) {
'use strict';
var ConnectionPool = Backbone.Collection.extend({
model: Connection,
initialize: function(models, options) {
this.dataset = options['dataset'];
this.defaultCut = options['defaultCut'];
},
getConnection: function(opts) {
var id = this.getConnectionId(opts),
conn = this.get(id);
if (_.isUndefined(conn)) {
var defaults = {
id: id,
dataset: this.dataset,
cut: this.defaultCut
};
conn = new Connection(_.extend(defaults, opts));
this.add(conn);
}
return conn;
},
getConnectionId: function(opts) {
switch(opts['type']) {
case 'dimensions':
return opts['type'] + ':' + opts['dimension'];
case 'observations':
return opts['type'] + ':' + opts['dimension'] + ':' + opts['measure'];
default:
return _.uniqueId('conn_');
}
}
});
return ConnectionPool;
});
|
define(['backbone', '../models/dataset/connection'],
function(Backbone, Connection) {
'use strict';
var ConnectionPool = Backbone.Collection.extend({
model: Connection,
initialize: function(models, options) {
this.dataset = options['dataset'];
this.defaultCut = options['defaultCut'];
},
getConnection: function(opts) {
var id = this.getConnectionId(opts),
conn = this.get(id);
if (_.isUndefined(conn)) {
var defaults = {
id: id,
dataset: this.dataset,
cut: this.defaultCut
};
conn = new Connection(_.extend(defaults, opts));
this.add(conn);
}
return conn;
},
getConnectionId: function(opts) {
switch(opts['type']) {
case 'dimensions':
return opts['type'] + ':' + opts['dimension'];
case 'observations':
return opts['type'] + ':' + opts['dimension'] + ':' + opts['measure'] + ':' + opts['aggregation'];
default:
return _.uniqueId('conn_');
}
}
});
return ConnectionPool;
});
|
Use aggregation to namespace the connection id
|
Use aggregation to namespace the connection id
re #506
|
JavaScript
|
agpl-3.0
|
dataseed/dataseed-visualisation.js,dataseed/dataseed-visualisation.js
|
a0501d86dcee4ef1ddad9e7e65db93b7e0b8b10b
|
src/events.js
|
src/events.js
|
var domElementValue = require('dom-element-value');
var EventManager = require('dom-event-manager');
var eventManager;
function eventHandler(name, e) {
var element = e.delegateTarget, eventName = 'on' + name;
if (!element.domLayerNode || !element.domLayerNode.events || !element.domLayerNode.events[eventName]) {
return;
}
var value;
if (/^(?:input|select|textarea|button)$/i.test(element.tagName)) {
value = domElementValue(element);
}
return element.domLayerNode.events[eventName](e, value, element.domLayerNode);
}
function getManager() {
if (eventManager) {
return eventManager;
}
return eventManager = new EventManager(eventHandler);
}
function init() {
var em = getManager();
em.bindDefaultEvents();
return em;
}
module.exports = {
EventManager: EventManager,
getManager: getManager,
init: init
};
|
var domElementValue = require('dom-element-value');
var EventManager = require('dom-event-manager');
var eventManager;
function eventHandler(name, e) {
var element = e.delegateTarget;
if (!element.domLayerNode || !element.domLayerNode.events) {
return;
}
var events = []
var mouseClickEventName;
var bail = false;
if (name.substr(name.length - 5) === 'click') {
mouseClickEventName = 'onmouse' + name;
if (element.domLayerNode.events[mouseClickEventName]) {
events.push(mouseClickEventName);
}
// Do not call the `click` handler if it's not a left click.
if (e.button !== 0) {
bail = true;
}
}
var eventName;
if (!bail) {
eventName = 'on' + name;
if (element.domLayerNode.events[eventName]) {
events.push(eventName);
}
}
if (!events.length) {
return;
}
var value;
if (/^(?:input|select|textarea|button)$/i.test(element.tagName)) {
value = domElementValue(element);
}
for (var i = 0, len = events.length; i < len ; i++) {
element.domLayerNode.events[events[i]](e, value, element.domLayerNode);
}
}
function getManager() {
if (eventManager) {
return eventManager;
}
return eventManager = new EventManager(eventHandler);
}
function init() {
var em = getManager();
em.bindDefaultEvents();
return em;
}
module.exports = {
EventManager: EventManager,
getManager: getManager,
init: init
};
|
Change the event handler, the `click` handler is only called on left clicks, use the fake `mouseclick` event to catch any kind of click.
|
Change the event handler, the `click` handler is only called on left clicks, use the fake `mouseclick` event to catch any kind of click.
|
JavaScript
|
mit
|
crysalead-js/dom-layer,crysalead-js/dom-layer
|
b9e61516e633e79909371d6c185818e3579085d2
|
languages.js
|
languages.js
|
module.exports = [
{name:'C++', mode:'c_cpp'},
{name:'CSS', mode:'css'},
{name:'HTML', mode:'html'},
{name:'JavaScript', mode:'javascript'},
{name:'Perl', mode:'perl'},
{name:'Python', mode:'python'},
{name:'Ruby', mode:'ruby'},
{name:'Shell', mode:'sh'},
{name:'SQL', mode:'sql'},
{name:'Text', mode:'text'}
];
|
module.exports = [
{name:'C++', mode:'c_cpp'},
{name:'CSS', mode:'css'},
{name:'HTML', mode:'html'},
{name:'JavaScript', mode:'javascript'},
{name:'JSON', mode:'json'},
{name:'Perl', mode:'perl'},
{name:'Python', mode:'python'},
{name:'Ruby', mode:'ruby'},
{name:'Shell', mode:'sh'},
{name:'SQL', mode:'sql'},
{name:'Text', mode:'text'},
{name:'XML', mode:'xml'}
];
|
Add XML and JSON modes
|
Add XML and JSON modes
|
JavaScript
|
unlicense
|
briangreenery/gist
|
94a0a48971adbd1583707bd4ed9f874db0b82385
|
test/dispose.js
|
test/dispose.js
|
describe('asking if a visible div scrolled', function() {
require('./fixtures/bootstrap.js');
beforeEach(h.clean);
afterEach(h.clean);
var visible = false;
var element;
var watcher;
beforeEach(function(done) {
element = h.createTest({
style: {
top: '10000px'
}
});
h.insertTest(element);
watcher = inViewport(element, function() {
scrolled = true;
done();
});
});
describe('when the watcher is not active', function() {
beforeEach(watcher.dispose());
beforeEach(h.scroller(0, 10000));
beforeEach(h.scroller(0, 0));
it('cb not called', function() {
assert.strictEqual(calls.length, 0);
});
});
describe('when the watcher is active', function() {
beforeEach(watcher.watch());
beforeEach(h.scroller(0, 10000));
beforeEach(h.scroller(0, 0));
it('cb called', function() {
assert.strictEqual(calls.length, 1);
});
});
});
|
describe('using the watcher API to dispose and watch again', function() {
require('./fixtures/bootstrap.js');
beforeEach(h.clean);
afterEach(h.clean);
var visible = false;
var element;
var watcher;
beforeEach(function(done) {
element = h.createTest({
style: {
top: '10000px'
}
});
h.insertTest(element);
watcher = inViewport(element, function() {
scrolled = true;
done();
});
});
describe('when the watcher is not active', function() {
beforeEach(watcher.dispose());
beforeEach(h.scroller(0, 10000));
beforeEach(h.scroller(0, 0));
it('cb not called', function() {
assert.strictEqual(calls.length, 0);
});
});
describe('when the watcher is active', function() {
beforeEach(watcher.watch());
beforeEach(h.scroller(0, 10000));
beforeEach(h.scroller(0, 0));
it('cb called', function() {
assert.strictEqual(calls.length, 1);
});
});
});
|
Rename the test on watcher API to have something more specific
|
Rename the test on watcher API to have something more specific
|
JavaScript
|
mit
|
tzi/in-viewport,tzi/in-viewport,vvo/in-viewport,vvo/in-viewport,fasterize/in-viewport,fasterize/in-viewport,ipy/in-viewport,ipy/in-viewport
|
5cb52c0c7d5149048fdc0f36c18e033a48f33fad
|
src/scripts/browser/components/auto-launcher/impl-win32.js
|
src/scripts/browser/components/auto-launcher/impl-win32.js
|
import manifest from '../../../../package.json';
import filePaths from '../../utils/file-paths';
import Winreg from 'winreg';
import BaseAutoLauncher from './base';
class Win32AutoLauncher extends BaseAutoLauncher {
static REG_KEY = new Winreg({
hive: Winreg.HKCU,
key: '\\Software\\Microsoft\\Windows\\CurrentVersion\\Run'
});
enable(callback) {
const updateExePath = filePaths.getSquirrelUpdateExe();
const cmd = `"${updateExePath}" --processStart ` +
`"${manifest.productName}.exe" --process-start-args "--os-startup"`;
log('setting registry key for', manifest.productName, 'value', cmd);
Win32AutoLauncher.REG_KEY.set(manifest.productName, Winreg.REG_SZ, cmd, callback);
}
disable(callback) {
log('removing registry key for', manifest.productName);
Win32AutoLauncher.REG_KEY.remove(manifest.productName, callback);
}
isEnabled(callback) {
log('querying registry key for', manifest.productName);
Win32AutoLauncher.REG_KEY.get(manifest.productName, function(err, item) {
const enabled = !!item;
log('registry value for', manifest.productName, 'is', enabled);
callback(err, enabled);
});
}
}
export default Win32AutoLauncher;
|
import manifest from '../../../../package.json';
import filePaths from '../../utils/file-paths';
import Winreg from 'winreg';
import BaseAutoLauncher from './base';
class Win32AutoLauncher extends BaseAutoLauncher {
static REG_KEY = new Winreg({
hive: Winreg.HKCU,
key: '\\Software\\Microsoft\\Windows\\CurrentVersion\\Run'
});
enable(callback) {
const updateExePath = filePaths.getSquirrelUpdateExe();
const cmd = `"${updateExePath}" --processStart ` +
`"${manifest.productName}.exe" --process-start-args "--os-startup"`;
log('setting registry key for', manifest.productName, 'value', cmd);
Win32AutoLauncher.REG_KEY.set(manifest.productName, Winreg.REG_SZ, cmd, callback);
}
disable(callback) {
log('removing registry key for', manifest.productName);
Win32AutoLauncher.REG_KEY.remove(manifest.productName, (err) => {
const notFound = err.message == 'The system was unable to find the specified registry key or value.';
if (notFound) {
callback();
} else {
callback(err);
}
});
}
isEnabled(callback) {
log('querying registry key for', manifest.productName);
Win32AutoLauncher.REG_KEY.get(manifest.productName, function(err, item) {
const enabled = !!item;
log('registry value for', manifest.productName, 'is', enabled);
callback(err, enabled);
});
}
}
export default Win32AutoLauncher;
|
Handle not found error in win32 auto launcher
|
Handle not found error in win32 auto launcher
|
JavaScript
|
mit
|
Hadisaeed/test-build,Aluxian/Messenger-for-Desktop,Aluxian/Facebook-Messenger-Desktop,Aluxian/Facebook-Messenger-Desktop,Aluxian/Messenger-for-Desktop,Aluxian/Facebook-Messenger-Desktop,Hadisaeed/test-build,Hadisaeed/test-build,rafael-neri/whatsapp-webapp,rafael-neri/whatsapp-webapp,rafael-neri/whatsapp-webapp,Aluxian/Messenger-for-Desktop
|
3e89abf57c2242f8bef493eb0dc8fa053bec9e48
|
lib/index.js
|
lib/index.js
|
/**
* Comma number formatter
* @param {Number} number Number to format
* @param {String} [separator=','] Value used to separate numbers
* @returns {String} Comma formatted number
*/
module.exports = function commaNumber (number, separator) {
separator = typeof separator === 'undefined' ? ',' : ('' + separator)
// Convert to number if it's a non-numeric value
if (typeof number !== 'number')
number = Number(number)
// NaN => 0
if (isNaN(number))
number = 0
// Return Infinity immediately
if (!isFinite(number))
return '' + number
var stringNumber = ('' + Math.abs(number))
.split('')
.reverse()
var result = []
for (var i = 0; i < stringNumber.length; i++) {
if (i && i % 3 === 0)
result.push(separator)
result.push(stringNumber[i])
}
// Handle negative numbers
if (number < 0)
result.push('-')
return result
.reverse()
.join('')
}
|
/**
* Comma number formatter
* @param {Number} number Number to format
* @param {String} [separator=','] Value used to separate numbers
* @returns {String} Comma formatted number
*/
module.exports = function commaNumber (number, separator) {
separator = typeof separator === 'undefined' ? ',' : ('' + separator)
// Convert to number if it's a non-numeric value
if (typeof number !== 'number') {
number = Number(number)
}
// NaN => 0
if (isNaN(number)) {
number = 0
}
// Return Infinity immediately
if (!isFinite(number)) {
return '' + number
}
var stringNumber = ('' + Math.abs(number))
.split('')
.reverse()
var result = []
for (var i = 0; i < stringNumber.length; i++) {
if (i && i % 3 === 0) {
result.push(separator)
}
result.push(stringNumber[i])
}
// Handle negative numbers
if (number < 0) {
result.push('-')
}
return result
.reverse()
.join('')
}
|
Update code to follow standard style
|
Update code to follow standard style
|
JavaScript
|
mit
|
cesarandreu/comma-number
|
2a1121c856f387c164e5239e6a7dacf2d2f29330
|
test/test-main.js
|
test/test-main.js
|
'use strict';
if (!Function.prototype.bind) {
// PhantomJS doesn't support bind yet
Function.prototype.bind = Function.prototype.bind || function(thisp) {
var fn = this;
return function() {
return fn.apply(thisp, arguments);
};
};
}
var tests = Object.keys(window.__karma__.files).filter(function(file) {
return /-spec\.js$/.test(file);
});
requirejs.config({
// Karma serves files from '/base'
baseUrl: '/base/src',
paths: {
'jquery': '../lib/jquery/jquery',
'extend': '../lib/gextend/extend'
},
// ask Require.js to load these files (all our tests)
deps: tests,
// start test run, once Require.js is done
callback: window.__karma__.start
});
|
'use strict';
if (!Function.prototype.bind) {
// PhantomJS doesn't support bind yet
Function.prototype.bind = Function.prototype.bind || function(thisp) {
var fn = this;
return function() {
return fn.apply(thisp, arguments);
};
};
}
var tests = Object.keys(window.__karma__.files).filter(function(file) {
return /-spec\.js$/.test(file);
});
requirejs.config({
// Karma serves files from '/base'
baseUrl: '/base/src',
paths: {
'extend': '../lib/gextend/extend'
},
// ask Require.js to load these files (all our tests)
deps: tests,
// start test run, once Require.js is done
callback: window.__karma__.start
});
|
Remove jQuery dependency, not used
|
TEST: Remove jQuery dependency, not used
|
JavaScript
|
mit
|
goliatone/gsocket
|
7e71970b1cb76c8a916e365491ca07252a61a208
|
src/server.js
|
src/server.js
|
import express from 'express';
import ReactDOMServer from 'react-dom/server'
import {Router} from 'react-router';
import MemoryHistory from 'react-router/lib/MemoryHistory';
import React from 'react';
import routes from './routing';
let app = express();
//app.engine('html', require('ejs').renderFile);
//app.set('view engine', 'html');
app.use(function (req, res, next) {
let history = new MemoryHistory([req.url]);
let html = ReactDOMServer.renderToString(
<Router history={history}>
{routes}
</Router>
);
return res.send(html);
/*var router = Router.create({location: req.url, routes: routes})
router.run(function(Handler, state) {
var html = ReactDOMServer.renderToString(<Handler/>)
return res.render('react_page', {html: html})
})*/
});
let server = app.listen(8000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
|
import express from 'express';
import ReactDOMServer from 'react-dom/server'
import {Router} from 'react-router';
import MemoryHistory from 'react-router/lib/MemoryHistory';
import React from 'react';
import routes from './routing';
let app = express();
//app.engine('html', require('ejs').renderFile);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.static('../public'));
app.use(function (req, res, next) {
let history = new MemoryHistory([req.url]);
let html = ReactDOMServer.renderToString(
<Router history={history}>
{routes}
</Router>
);
return res.render('index', {html: html});
});
let server = app.listen(8000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
|
Handle initial page laod via express
|
Handle initial page laod via express
|
JavaScript
|
agpl-3.0
|
voidxnull/libertysoil-site,Lokiedu/libertysoil-site,voidxnull/libertysoil-site,Lokiedu/libertysoil-site
|
14e97545ba507765cd186b549981e0ebc55f1dff
|
javascript/NocaptchaField.js
|
javascript/NocaptchaField.js
|
var _noCaptchaFields=_noCaptchaFields || [];
function noCaptchaFieldRender() {
for(var i=0;i<_noCaptchaFields.length;i++) {
var field=document.getElementById('Nocaptcha-'+_noCaptchaFields[i]);
var options={
'sitekey': field.getAttribute('data-sitekey'),
'theme': field.getAttribute('data-theme'),
'type': field.getAttribute('data-type'),
'size': field.getAttribute('data-size'),
'callback': (field.getAttribute('data-callback') ? verifyCallback : undefined )
};
grecaptcha.render(field, options);
}
}
|
var _noCaptchaFields=_noCaptchaFields || [];
function noCaptchaFieldRender() {
for(var i=0;i<_noCaptchaFields.length;i++) {
var field=document.getElementById('Nocaptcha-'+_noCaptchaFields[i]);
var options={
'sitekey': field.getAttribute('data-sitekey'),
'theme': field.getAttribute('data-theme'),
'type': field.getAttribute('data-type'),
'size': field.getAttribute('data-size'),
'callback': (field.getAttribute('data-callback') ? verifyCallback : undefined )
};
var widget_id = grecaptcha.render(field, options);
field.setAttribute("data-widgetid", widget_id);
}
}
|
Store widget_id on field element
|
Store widget_id on field element
This allows the captcha element to be targeted via the js api in situations where there is more than one nocaptcha widget on the page. See examples referencing `opt_widget_id` here https://developers.google.com/recaptcha/docs/display#js_api
|
JavaScript
|
bsd-3-clause
|
UndefinedOffset/silverstripe-nocaptcha,UndefinedOffset/silverstripe-nocaptcha
|
2ebe898d9f2284ee0f25d8ac927bef4e7bb730de
|
lib/store.js
|
lib/store.js
|
var Store = module.exports = function () {
};
Store.prototype.hit = function (req, configuration, callback) {
var self = this;
var ip = req.ip;
var path;
if (configuration.pathLimiter) {
path = (req.baseUrl) ? req.baseUrl.replace(req.path, '') : '';
ip += configuration.path || path;
}
var now = Date.now();
self.get(ip, function (err, limit) {
if (err) {
callback(err, undefined, now);
return;
};
if (limit) {
//Existing user
var limitDate = limit.date;
var timeLimit = limitDate + configuration.innerTimeLimit;
var resetInner = now > timeLimit;
limit.date = now;
self.decreaseLimits(ip, limit, resetInner, configuration, function (error, result) {
callback(error, result, limitDate);
});
} else {
//New User
var outerReset = Math.floor((now + configuration.outerTimeLimit) / 1000);
limit = {
date: now,
inner: configuration.innerLimit,
outer: configuration.outerLimit,
firstDate: now,
outerReset: outerReset
};
self.create(ip, limit, configuration, function (error, result) {
callback(error, result, now);
});
}
}, configuration);
}
|
var Store = module.exports = function () {
};
Store.prototype.hit = function (req, configuration, callback) {
var self = this;
var ip = req.ip;
var path;
if (configuration.pathLimiter) {
path = (req.baseUrl) ? req.baseUrl.replace(req.path, '') : '';
ip += configuration.path || path;
}
var now = Date.now();
self.get(ip, function (err, limit) {
if (err) {
callback(err, undefined, now);
return;
};
if (limit) {
//Existing user
var limitDate = limit.date;
var timeLimit = limitDate + configuration.innerTimeLimit;
var resetInner = now > timeLimit;
if (resetInner) {
limit.date = now;
}
self.decreaseLimits(ip, limit, resetInner, configuration, function (error, result) {
callback(error, result, limitDate);
});
} else {
//New User
var outerReset = Math.floor((now + configuration.outerTimeLimit) / 1000);
limit = {
date: now,
inner: configuration.innerLimit,
outer: configuration.outerLimit,
firstDate: now,
outerReset: outerReset
};
self.create(ip, limit, configuration, function (error, result) {
callback(error, result, now);
});
}
}, configuration);
}
|
Fix bug with inner reset time
|
Fix bug with inner reset time
|
JavaScript
|
mit
|
StevenThuriot/express-rate-limiter
|
df1807f823332d076a0dff7e6ec0b49b8a42e8ad
|
config-SAMPLE.js
|
config-SAMPLE.js
|
/* Magic Mirror Config Sample
*
* By Michael Teeuw http://michaelteeuw.nl
* MIT Licensed.
*/
var config = {
port: 8080,
language: 'en',
timeFormat: 12,
units: 'imperial',
modules: [
{
module: 'clock',
position: 'top_left',
config: {
displaySeconds: false
}
},
{
module: 'hurst/weather',
position: 'top_right',
config: {
}
}
]
};
/*************** DO NOT EDIT THE LINE BELOW ***************/
if (typeof module !== 'undefined') {module.exports = config;}
|
/* Magic Mirror Config Sample
*
* By Michael Teeuw http://michaelteeuw.nl
* MIT Licensed.
*/
var config = {
port: 8080,
language: 'en',
timeFormat: 12,
units: 'imperial',
modules: [
{
module: 'clock',
position: 'top_left',
config: {
displaySeconds: false
}
},
{
module: 'hurst/muni',
position: 'top_left',
config: {
stops: ['48|3463']
}
},
{
module: 'hurst/weather',
position: 'top_right',
config: {
apiKey: 'MUST_PUT_KEY_HERE',
latLng: '37.700000,-122.400000'
}
}
]
};
/*************** DO NOT EDIT THE LINE BELOW ***************/
if (typeof module !== 'undefined') {module.exports = config;}
|
Update sample config for new modules.
|
Update sample config for new modules.
|
JavaScript
|
apache-2.0
|
jhurstus/mirror,jhurstus/mirror
|
761977b9c98bd5f92d6c90981fff16fec2df4893
|
src/components/svg/SVGComponents.js
|
src/components/svg/SVGComponents.js
|
import React, { PropTypes } from 'react'
import classNames from 'classnames'
export const SVGComponent = ({ children, ...rest }) =>
<svg {...rest}>
{children}
</svg>
SVGComponent.propTypes = {
children: PropTypes.node.isRequired,
}
export const SVGIcon = ({ children, className, onClick }) =>
<SVGComponent
className={classNames(className, 'SVGIcon')}
onClick={onClick}
width="20"
height="20"
>
{children}
</SVGComponent>
SVGIcon.propTypes = {
children: PropTypes.node.isRequired,
className: PropTypes.string.isRequired,
onClick: PropTypes.func,
}
SVGIcon.defaultProps = {
onClick: null,
}
export const SVGBox = ({ children, className, size = '40' }) =>
<SVGComponent
className={classNames(className, 'SVGBox')}
width={size}
height={size}
>
{children}
</SVGComponent>
SVGBox.propTypes = {
children: PropTypes.node.isRequired,
className: PropTypes.string.isRequired,
size: PropTypes.string,
}
SVGBox.defaultProps = {
size: null,
}
|
import React, { PropTypes } from 'react'
import classNames from 'classnames'
export const SVGComponent = ({ children, ...rest }) =>
<svg {...rest}>
{children}
</svg>
SVGComponent.propTypes = {
children: PropTypes.node.isRequired,
}
export const SVGIcon = ({ children, className, onClick }) =>
<SVGComponent
className={classNames(className, 'SVGIcon')}
onClick={onClick}
width="20"
height="20"
>
{children}
</SVGComponent>
SVGIcon.propTypes = {
children: PropTypes.node.isRequired,
className: PropTypes.string.isRequired,
onClick: PropTypes.func,
}
SVGIcon.defaultProps = {
onClick: null,
}
export const SVGBox = ({ children, className, size }) =>
<SVGComponent
className={classNames(className, 'SVGBox')}
width={size}
height={size}
>
{children}
</SVGComponent>
SVGBox.propTypes = {
children: PropTypes.node.isRequired,
className: PropTypes.string.isRequired,
size: PropTypes.string,
}
SVGBox.defaultProps = {
size: 40,
}
|
Set the default size to 40 on SVGBoxes
|
Set the default size to 40 on SVGBoxes
The null value was causing some weird rendering issues on a few icons
|
JavaScript
|
mit
|
ello/webapp,ello/webapp,ello/webapp
|
904ec5fd379bf47f66794af36ffcd5ecbf5d3ec5
|
blueprints/ember-flexberry/index.js
|
blueprints/ember-flexberry/index.js
|
/* globals module */
module.exports = {
afterInstall: function () {
this.addBowerPackageToProject('git://github.com/BreadMaker/semantic-ui-daterangepicker.git#5d46ed2e6e5a0bf398bb6a5df82e06036dfc46be');
this.addBowerPackageToProject('datatables');
},
normalizeEntityName: function () {}
};
|
/* globals module */
module.exports = {
afterInstall: function () {
return this.addBowerPackagesToProject([
{ name: 'semantic-ui-daterangepicker', target: '5d46ed2e6e5a0bf398bb6a5df82e06036dfc46be' },
{ name: 'datatables', target: '~1.10.8' }
]);
},
normalizeEntityName: function () {}
};
|
Fix bower packages installation for addon
|
Fix bower packages installation for addon
|
JavaScript
|
mit
|
Flexberry/ember-flexberry,Flexberry/ember-flexberry,Flexberry/ember-flexberry,Flexberry/ember-flexberry
|
ae5d7724d279e3d1feb1c696d70f6a030407053e
|
test/patch.js
|
test/patch.js
|
var patch = require("../lib/patch")
, net = require("net")
, https = require("https")
, fs = require("fs");
// This is probably THE most ugliest code I've ever written
var responseRegExp = /^([0-9a-z-]{36}) (.*)$/i;
var host = net.createServer(function(socket) {
var i = 0;
socket.setEncoding("utf8");
socket.on("data", function(data) {
switch(i) {
case 0: socket.write("SUCCESS"); break;
default: socket.write(data.match(responseRegExp)[1] + " " + JSON.stringify({
peername: { address: "peer-address", port: 1234 },
sockname: { address: "sock-address", port: 1234 }
}));
}
i++;
});
}).listen(0).address().port;
var ssl = {
cert: fs.readFileSync(__dirname + "/ssl/cert.pem"),
key: fs.readFileSync(__dirname + "/ssl/key.pem")
};
// The utlimate test: HTTPS (and therefore SPDY too)
var server = https.createServer(ssl, function(req, res) {
console.log(req.socket.remoteAddress + ":" + req.socket.remotePort);
res.end("Fuck yeah!");
});
patch(host, server, true).listen("address");
|
var patch = require("../lib/patch")
, net = require("net")
, https = require("https")
, fs = require("fs");
// This is probably THE most ugliest code I've ever written
var responseRegExp = /^([0-9a-z-]{36}) (.*)$/i;
var host = net.createServer(function(socket) {
var i = 0;
socket.setEncoding("utf8");
socket.on("data", function(data) {
switch(i) {
case 0: socket.write("SUCCESS"); break;
default: socket.write(data.match(responseRegExp)[1] + " " + JSON.stringify({
peername: { address: "peer-address", port: 1234 },
sockname: { address: "sock-address", port: 1234 }
}));
}
i++;
});
}).listen(0).address().port;
var ssl = {
cert: fs.readFileSync(__dirname + "/ssl/cert.pem"),
key: fs.readFileSync(__dirname + "/ssl/key.pem")
};
// The utlimate test: HTTPS (and therefore SPDY too)
var server = https.createServer(ssl, function(req, res) {
console.log(req.socket.remoteAddress + ":" + req.socket.remotePort);
res.end("Fuck yeah!");
}).on("error", console.log);
patch(host, server, true).listen("address");
|
Add error listener to test
|
Add error listener to test
|
JavaScript
|
mit
|
buschtoens/distroy
|
a7b3e2edaa8f1f2791f3cf8c88d210ca7f3b06c1
|
webpack.config.js
|
webpack.config.js
|
'use strict';
const path = require('path');
const webpack = require('webpack');
module.exports = {
cache: true,
devtool: '#source-map',
entry: [
path.resolve(__dirname, 'src', 'index.js')
],
module: {
rules: [
{
enforce: 'pre',
include: [
path.resolve(__dirname, 'src')
],
loader: 'eslint-loader',
options: {
configFile: '.eslintrc',
failOnError: true,
failOnWarning: false,
formatter: require('eslint-friendly-formatter')
},
test: /\.js$/
}, {
include: [
path.resolve(__dirname, 'src')
],
options: {
babelrc: false,
plugins: [
'syntax-flow',
'transform-flow-strip-types'
],
presets: [
['env', {
loose: true,
modules: false
}],
'stage-2'
]
},
test: /\.js$/,
loader: 'babel-loader'
}
]
},
output: {
filename: 'moize.js',
library: 'moize',
libraryTarget: 'umd',
path: path.resolve(__dirname, 'dist'),
umdNamedDefine: true
},
plugins: [
new webpack.EnvironmentPlugin([
'NODE_ENV'
])
],
resolve: {
modules: [
path.join(__dirname, 'src'),
'node_modules'
]
}
};
|
'use strict';
const path = require('path');
const webpack = require('webpack');
module.exports = {
cache: true,
devtool: '#source-map',
entry: [
path.resolve(__dirname, 'src', 'index.js')
],
module: {
rules: [
{
enforce: 'pre',
include: [
path.resolve(__dirname, 'src')
],
loader: 'eslint-loader',
options: {
cache: true,
configFile: '.eslintrc',
failOnError: true,
failOnWarning: false,
fix: true,
formatter: require('eslint-friendly-formatter')
},
test: /\.js$/
}, {
include: [
path.resolve(__dirname, 'src')
],
options: {
babelrc: false,
plugins: [
'syntax-flow',
'transform-flow-strip-types'
],
presets: [
['env', {
loose: true,
modules: false
}],
'stage-2'
]
},
test: /\.js$/,
loader: 'babel-loader'
}
]
},
output: {
filename: 'moize.js',
library: 'moize',
libraryTarget: 'umd',
path: path.resolve(__dirname, 'dist'),
umdNamedDefine: true
},
plugins: [
new webpack.EnvironmentPlugin([
'NODE_ENV'
])
],
resolve: {
modules: [
path.join(__dirname, 'src'),
'node_modules'
]
}
};
|
Improve ESLint options for Webpack
|
Improve ESLint options for Webpack
|
JavaScript
|
mit
|
planttheidea/moize,planttheidea/moize
|
349bad1afc06c0af44ff42ab7358e393f3ec4fd9
|
lib/ipc-helpers/dump-node.js
|
lib/ipc-helpers/dump-node.js
|
#!/usr/bin/env node
process.on('exit', function sendCoverage() {
process.send({'coverage': global.__coverage__});
});
|
#!/usr/bin/env node
process.on('beforeExit', function sendCovereageBeforeExit() {
process.send({'coverage': global.__coverage__});
});
|
Use beforeExit event to send coverage
|
Use beforeExit event to send coverage
|
JavaScript
|
mit
|
rtsao/unitest
|
7d8145fce09a92004fbf302953d37863d2bc202b
|
lib/matrices.js
|
lib/matrices.js
|
function Matrix(options) {
options = options || {};
var values;
if (options.values)
values = options.values;
if (options.rows && options.columns && !values) {
values = [];
for (var k = 0; k < options.rows; k++) {
var row = [];
for (var j = 0; j < options.columns; j++)
row[j] = 0;
values.push(row);
}
}
this.nrows = function () {
if (!values)
return 0;
return values.length;
};
this.ncolumns = function () {
if (!values)
return 0;
return values[0].length;
};
this.element = function (r, c) {
if (!values) return 0;
var row = values[r];
if (!row) return 0;
var element = values[r][c];
return element == null ? 0 : element;
};
}
Matrix.prototype.isMatrix = function () { return true; }
Matrix.prototype.isVector = function () { return false; }
function createMatrix(options) {
return new Matrix(options);
}
module.exports = {
createMatrix: createMatrix
}
|
function Matrix(options) {
options = options || {};
var values;
if (options.values) {
values = options.values.slice();
for (var k = 0; k < values.length; k++)
values[k] = values[k].slice();
}
if (options.rows && options.columns && !values) {
values = [];
for (var k = 0; k < options.rows; k++) {
var row = [];
for (var j = 0; j < options.columns; j++)
row[j] = 0;
values.push(row);
}
}
this.nrows = function () {
if (!values)
return 0;
return values.length;
};
this.ncolumns = function () {
if (!values)
return 0;
return values[0].length;
};
this.element = function (r, c) {
if (!values) return 0;
var row = values[r];
if (!row) return 0;
var element = values[r][c];
return element == null ? 0 : element;
};
}
Matrix.prototype.isMatrix = function () { return true; }
Matrix.prototype.isVector = function () { return false; }
function createMatrix(options) {
return new Matrix(options);
}
module.exports = {
createMatrix: createMatrix
}
|
Refactor matrix creation to use values slice
|
Refactor matrix creation to use values slice
|
JavaScript
|
mit
|
ajlopez/MathelJS
|
c29d3a670722b2f4d0a394e6a72ecb647687893a
|
.storybook/main.js
|
.storybook/main.js
|
module.exports = {
addons: ['@storybook/addon-backgrounds', '@storybook/addon-knobs'],
};
|
module.exports = {
stories: ['../**/*.stories.js'],
addons: ['@storybook/addon-backgrounds', '@storybook/addon-knobs'],
};
|
Define where to find the component stories
|
Define where to find the component stories
|
JavaScript
|
mit
|
teamleadercrm/teamleader-ui
|
ade0cebb2c7edcacb2f0e83a103e55529fa024cc
|
lib/user-data.js
|
lib/user-data.js
|
//
// This file talks to the main process by fetching the path to the user data.
// It also writes updates to the user-data file.
//
var ipc = require('electron').ipcRenderer
var fs = require('fs')
var getData = function () {
var data = {}
data.path = ipc.sendSync('getUserDataPath', null)
data.contents = JSON.parse(fs.readFileSync(data.path))
return data
}
var getSavedDir = function () {
var savedDir = {}
data.path = ipc.sendSync('getUserSavedDir', null)
data.contents = JSON.parse(fs.readFileSync(data.path))
return savedDir
}
var writeData = function (data) {
fs.writeFile(data.path, JSON.stringify(data.contents, null, ' '), function updatedUserData (err) {
if (err) return console.log(err)
})
}
// this could take in a boolean on compelte status
// and be named better in re: to updating ONE challenge, not all
var updateData = function (challenge) {
var data = getData()
data.contents[challenge].completed = true
writeData(data)
}
var updateCurrentDirectory = function (path) {
var data = getSavedDir()
data.contents.savedDir = path
writeData(data)
}
module.exports.getData = getData
module.exports.updateData = updateData
module.exports.updateCurrentDirectory = updateCurrentDirectory
|
//
// This file talks to the main process by fetching the path to the user data.
// It also writes updates to the user-data file.
//
var ipc = require('electron').ipcRenderer
var fs = require('fs')
var getData = function () {
var data = {}
data.path = ipc.sendSync('getUserDataPath', null)
data.contents = JSON.parse(fs.readFileSync(data.path))
return data
}
var getSavedDir = function () {
var savedDir = {}
savedDir.path = ipc.sendSync('getUserSavedDir', null)
savedDir.contents = JSON.parse(fs.readFileSync(savedDir.path))
return savedDir
}
var writeData = function (data) {
fs.writeFile(data.path, JSON.stringify(data.contents, null, ' '), function updatedUserData (err) {
if (err) return console.log(err)
})
}
// this could take in a boolean on compelte status
// and be named better in re: to updating ONE challenge, not all
var updateData = function (challenge) {
var data = getData()
data.contents[challenge].completed = true
writeData(data)
}
var updateCurrentDirectory = function (path) {
var data = getSavedDir()
data.contents.savedDir = path
writeData(data)
}
module.exports.getData = getData
module.exports.getSavedDir = getSavedDir
module.exports.updateData = updateData
module.exports.updateCurrentDirectory = updateCurrentDirectory
|
Fix having not set this up correctly
|
Fix having not set this up correctly
|
JavaScript
|
bsd-2-clause
|
jlord/git-it-electron,jlord/git-it-electron,shiftkey/git-it-electron,vongola12324/git-it-electron,vongola12324/git-it-electron,shiftkey/git-it-electron,shiftkey/git-it-electron,vongola12324/git-it-electron,vongola12324/git-it-electron,vongola12324/git-it-electron,vongola12324/git-it-electron,shiftkey/git-it-electron,jlord/git-it-electron,shiftkey/git-it-electron,shiftkey/git-it-electron,jlord/git-it-electron,shiftkey/git-it-electron,jlord/git-it-electron,vongola12324/git-it-electron,jlord/git-it-electron
|
b1da47403f4871313e0759a21091ace04151cb84
|
src/renderer/actions/connections.js
|
src/renderer/actions/connections.js
|
import { sqlectron } from '../../browser/remote';
export const CONNECTION_REQUEST = 'CONNECTION_REQUEST';
export const CONNECTION_SUCCESS = 'CONNECTION_SUCCESS';
export const CONNECTION_FAILURE = 'CONNECTION_FAILURE';
export const dbSession = sqlectron.db.createSession();
export function connect (id, database) {
return async (dispatch, getState) => {
const { servers } = getState();
const [ server, config ] = await* [
servers.items.find(srv => srv.id === id),
sqlectron.config.get(),
];
dispatch({ type: CONNECTION_REQUEST, server, database });
try {
await dbSession.connect(server, database);
dispatch({ type: CONNECTION_SUCCESS, server, database, config });
} catch (error) {
dispatch({ type: CONNECTION_FAILURE, server, database, error });
}
};
}
|
import { sqlectron } from '../../browser/remote';
export const CONNECTION_REQUEST = 'CONNECTION_REQUEST';
export const CONNECTION_SUCCESS = 'CONNECTION_SUCCESS';
export const CONNECTION_FAILURE = 'CONNECTION_FAILURE';
export const dbSession = sqlectron.db.createSession();
export function connect (id, database) {
return async (dispatch, getState) => {
const { servers } = getState();
const server = servers.items.find(srv => srv.id === id);
dispatch({ type: CONNECTION_REQUEST, server, database });
try {
const [, config ] = await Promise.all([
dbSession.connect(server, database),
sqlectron.config.get(),
]);
dispatch({ type: CONNECTION_SUCCESS, server, database, config });
} catch (error) {
dispatch({ type: CONNECTION_FAILURE, server, database, error });
}
};
}
|
Use promise all at the right place in the server connecting action
|
Use promise all at the right place in the server connecting action
|
JavaScript
|
mit
|
sqlectron/sqlectron-gui,sqlectron/sqlectron-gui,sqlectron/sqlectron-gui,sqlectron/sqlectron-gui
|
0ebb23201bc8364368cb77c5b502a345d3144f0e
|
www/pg-plugin-fb-connect.js
|
www/pg-plugin-fb-connect.js
|
PG = ( typeof PG == 'undefined' ? {} : PG );
PG.FB = {
init: function(apiKey) {
PhoneGap.exec(function(e) {
console.log("init: " + e);
}, null, 'com.facebook.phonegap.Connect', 'init', [apiKey]);
},
login: function(a, b) {
try {
b = b || { perms: '' };
PhoneGap.exec(function(e) { // login
//FB.Auth.setSession(e.session, 'connected'); // never gets called because the plugin spawns Mobile Safari/Facebook app
if (a) a(e);
}, null, 'com.facebook.phonegap.Connect', 'login', b.perms.split(',') );
} catch (e) {
alert(e);
}
},
logout: function(cb) {
try {
PhoneGap.exec(function(e) {
FB.Auth.setSession(null, 'notConnected');
if (cb) cb(e);
}, null, 'com.facebook.phonegap.Connect', 'logout', []);
} catch (e) {
alert(e);
}
},
getLoginStatus: function(cb) {
try {
PhoneGap.exec(function(e) {
if (cb) cb(e);
console.log("getLoginStatus: " + e);
}, null, 'com.facebook.phonegap.Connect', 'getLoginStatus', []);
} catch (e) {
alert(e);
}
}
};
|
PG = ( typeof PG == 'undefined' ? {} : PG );
PG.FB = {
init: function(apiKey) {
PhoneGap.exec(null, null, 'com.facebook.phonegap.Connect', 'init', [apiKey]);
},
login: function(a, b) {
b = b || { perms: '' };
PhoneGap.exec(function(e) { // login
FB.Auth.setSession(e.session, 'connected');
if (a) a(e);
}, null, 'com.facebook.phonegap.Connect', 'login', b.perms.split(',') );
},
logout: function(cb) {
PhoneGap.exec(function(e) {
FB.Auth.setSession(null, 'notConnected');
if (cb) cb(e);
}, null, 'com.facebook.phonegap.Connect', 'logout', []);
},
getLoginStatus: function(cb) {
PhoneGap.exec(function(e) {
if (cb) cb(e);
}, null, 'com.facebook.phonegap.Connect', 'getLoginStatus', []);
}
};
|
Update the JS to remove alerts etc and login now has to have its success method called
|
Update the JS to remove alerts etc and login now has to have its success method called
|
JavaScript
|
mit
|
barfight/phonegap-plugin-facebook-connect,irnc/phonegap-plugin-facebook-connect,AntonDobrev/phonegap-plugin-facebook-connect,totoo74/phonegap-plugin-facebook-connect,AntonDobrev/phonegap-plugin-facebook-connect,irnc/phonegap-plugin-facebook-connect,totoo74/phonegap-plugin-facebook-connect,barfight/phonegap-plugin-facebook-connect,MingxuanLi/phonegap-plugin-facebook-connect,MingxuanLi/phonegap-plugin-facebook-connect,barfight/phonegap-plugin-facebook-connect,irnc/phonegap-plugin-facebook-connect,AntonDobrev/phonegap-plugin-facebook-connect,barfight/phonegap-plugin-facebook-connect,MingxuanLi/phonegap-plugin-facebook-connect,AntonDobrev/phonegap-plugin-facebook-connect,totoo74/phonegap-plugin-facebook-connect,MingxuanLi/phonegap-plugin-facebook-connect,barfight/phonegap-plugin-facebook-connect,totoo74/phonegap-plugin-facebook-connect,AntonDobrev/phonegap-plugin-facebook-connect
|
a7dd9961d9350fc38ad2ad679c6e6b1d1e85e6e9
|
packages/core/lib/commands/help.js
|
packages/core/lib/commands/help.js
|
var command = {
command: "help",
description:
"List all commands or provide information about a specific command",
help: {
usage: "truffle help [<command>]",
options: [
{
option: "<command>",
description: "Name of the command to display information for."
}
]
},
builder: {},
run: function(options, callback) {
var commands = require("./index");
if (options._.length === 0) {
this.displayCommandHelp("help");
return callback();
}
var selectedCommand = options._[0];
if (commands[selectedCommand]) {
this.displayCommandHelp(selectedCommand);
return callback();
} else {
console.log(`\n Cannot find the given command '${selectedCommand}'`);
console.log(" Please ensure your command is one of the following: ");
Object.keys(commands)
.sort()
.forEach(command => console.log(` ${command}`));
console.log("");
return callback();
}
},
displayCommandHelp: function(selectedCommand) {
var commands = require("./index");
var commandHelp = commands[selectedCommand].help;
console.log(`\n Usage: ${commandHelp.usage}`);
console.log(` Description: ${commands[selectedCommand].description}`);
if (commandHelp.options.length > 0) {
console.log(` Options: `);
commandHelp.options.forEach(option => {
console.log(` ${option.option}`);
console.log(` ${option.description}`);
});
}
console.log("");
}
};
module.exports = command;
|
var command = {
command: "help",
description:
"List all commands or provide information about a specific command",
help: {
usage: "truffle help [<command>]",
options: [
{
option: "<command>",
description: "Name of the command to display information for."
}
]
},
builder: {},
run: function (options, callback) {
var commands = require("./index");
if (options._.length === 0) {
this.displayCommandHelp("help");
return callback();
}
var selectedCommand = options._[0];
if (commands[selectedCommand]) {
this.displayCommandHelp(selectedCommand);
return callback();
} else {
console.log(`\n Cannot find the given command '${selectedCommand}'`);
console.log(" Please ensure your command is one of the following: ");
Object.keys(commands)
.sort()
.forEach(command => console.log(` ${command}`));
console.log("");
return callback();
}
},
displayCommandHelp: function (selectedCommand) {
var commands = require("./index");
var commandHelp = commands[selectedCommand].help;
console.log(`\n Usage: ${commandHelp.usage}`);
console.log(` Description: ${commands[selectedCommand].description}`);
if (commandHelp.options.length > 0) {
console.log(` Options: `);
for (const option of commandHelp.options) {
if (option.internal) {
continue;
}
console.log(` ${option.option}`);
console.log(` ${option.description}`);
}
}
console.log("");
}
};
module.exports = command;
|
Allow commands to define internal options
|
Allow commands to define internal options
So those options don't appear in the help output
|
JavaScript
|
mit
|
ConsenSys/truffle
|
d2eeb477b2925e6e83e63f75b497cc2b24d5e9d5
|
webpack.config.js
|
webpack.config.js
|
const path = require('path')
module.exports = {
context: __dirname,
entry: './js/ClientApp.js',
devtool: 'source-map',
output: {
path: path.join(__dirname, '/public'),
filename: 'bundle.js'
},
resolve: {
extensions: ['.js', '.json']
},
stats: {
colors: true,
reasons: true,
chunks: false
},
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader'
}
]
}
}
|
const path = require('path')
module.exports = {
context: __dirname,
entry: './js/ClientApp.js',
devtool: 'source-map',
output: {
path: path.join(__dirname, '/public'),
filename: 'bundle.js'
},
resolve: {
extensions: ['.js', '.json']
},
stats: {
colors: true,
reasons: true,
chunks: false
},
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader'
},
{
test: /\.css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
url: false
}
}
]
}
]
}
}
|
Add style to Webpack rules.
|
Add style to Webpack rules.
|
JavaScript
|
mit
|
sheamunion/fem_intro_react_code_along,sheamunion/fem_intro_react_code_along
|
e1495b4a57c88e50ad1cb817372502f59c51b596
|
lib/MultiSelection/OptionsListWrapper.js
|
lib/MultiSelection/OptionsListWrapper.js
|
import React from 'react';
import PropTypes from 'prop-types';
import Popper from '../Popper';
const OptionsListWrapper = React.forwardRef(({
useLegacy,
children,
controlRef,
isOpen,
renderToOverlay,
menuPropGetter,
modifiers,
...props
}, ref) => {
if (useLegacy) {
return <div {...menuPropGetter()} {...props} ref={ref} hidden={!isOpen}>{children}</div>;
}
const {
overlayRef,
...menuRest
} = menuPropGetter({ ref, refKey: 'overlayRef' });
let portal;
if (renderToOverlay) {
portal = document.getElementById('OverlayContainer');
}
return (
<Popper
anchorRef={controlRef}
overlayProps={{ ...menuRest, ...props }}
overlayRef={overlayRef}
isOpen={isOpen}
portal={portal}
placement="bottom-start"
modifiers={modifiers}
hideIfClosed
>
{children}
</Popper>
);
});
OptionsListWrapper.displayName = 'OptionsListWrapper';
OptionsListWrapper.propTypes = {
children: PropTypes.node,
controlRef: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
isOpen: PropTypes.bool,
menuPropGetter: PropTypes.func,
modifiers: PropTypes.object,
renderToOverlay: PropTypes.bool,
useLegacy: PropTypes.bool,
};
export default OptionsListWrapper;
|
import React from 'react';
import PropTypes from 'prop-types';
import Popper from '../Popper';
const OptionsListWrapper = React.forwardRef(({
useLegacy,
children,
controlRef,
isOpen,
renderToOverlay,
menuPropGetter,
modifiers,
...props
}, ref) => {
if (useLegacy) {
return <div {...menuPropGetter({ ref })} {...props} hidden={!isOpen}>{children}</div>;
}
const {
overlayRef,
...menuRest
} = menuPropGetter({ ref, refKey: 'overlayRef' });
let portal;
if (renderToOverlay) {
portal = document.getElementById('OverlayContainer');
}
return (
<Popper
anchorRef={controlRef}
overlayProps={{ ...menuRest, ...props }}
overlayRef={overlayRef}
isOpen={isOpen}
portal={portal}
placement="bottom-start"
modifiers={modifiers}
hideIfClosed
>
{children}
</Popper>
);
});
OptionsListWrapper.displayName = 'OptionsListWrapper';
OptionsListWrapper.propTypes = {
children: PropTypes.node,
controlRef: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
isOpen: PropTypes.bool,
menuPropGetter: PropTypes.func,
modifiers: PropTypes.object,
renderToOverlay: PropTypes.bool,
useLegacy: PropTypes.bool,
};
export default OptionsListWrapper;
|
Fix ref on downshift element
|
Fix ref on downshift element
|
JavaScript
|
apache-2.0
|
folio-org/stripes-components,folio-org/stripes-components
|
3b4ee7102882f6e629828ac1e3e44d8f343d4012
|
src/features/home/redux/initialState.js
|
src/features/home/redux/initialState.js
|
const initialState = {
count: 0,
redditReactjsList: [],
// navTreeData: null,
// projectData: null,
elementById: {},
fileContentById: {},
features: null,
projectDataNeedReload: false,
projectFileChanged: false,
fetchProjectDataPending: false,
fetchProjectDataError: null,
fetchFileContentPending: false,
fetchFileContentError: null,
demoAlertVisible: true,
};
export default initialState;
|
const initialState = {
count: 0,
redditReactjsList: [],
elementById: {},
fileContentById: {},
features: null,
projectDataNeedReload: false,
projectFileChanged: false,
fetchProjectDataPending: false,
fetchProjectDataError: null,
fetchFileContentPending: false,
fetchFileContentError: null,
demoAlertVisible: false,
};
export default initialState;
|
Hide demo alert by default.
|
Hide demo alert by default.
|
JavaScript
|
mit
|
supnate/rekit-portal,supnate/rekit-portal
|
35c3457c31087a85103c9729279343775511c7e4
|
packages/lesswrong/lib/reactRouterWrapper.js
|
packages/lesswrong/lib/reactRouterWrapper.js
|
/*import * as reactRouter3 from 'react-router';
export const Link = reactRouter3.Link;
export const withRouter = reactRouter3.withRouter;*/
import React from 'react';
import * as reactRouter from 'react-router';
import * as reactRouterDom from 'react-router-dom';
import { parseQuery } from './routeUtil'
import qs from 'qs'
export const withRouter = (WrappedComponent) => {
const WithRouterWrapper = (props) => {
return <WrappedComponent
routes={[]}
location={{pathname:""}}
router={{location: {query:"", pathname:""}}}
{...props}
/>
}
return reactRouter.withRouter(WithRouterWrapper);
}
export const Link = (props) => {
if (!(typeof props.to === "string" || typeof props.to === "function")) {
// eslint-disable-next-line no-console
console.error("Props 'to' for Link components only accepts strings or functions, passed type: ", typeof props.to)
return <span>Broken Link</span>
}
return <reactRouterDom.Link {...props}/>
}
export const QueryLink = reactRouter.withRouter(({query, location, staticContext, merge=false, ...rest}) => {
// Merge determines whether we do a shallow merge with the existing query parameters, or replace them completely
const newSearchString = merge ? qs.stringify({...parseQuery(location), ...query}) : qs.stringify(query)
return <reactRouterDom.Link
{...rest}
to={{search: newSearchString}}
/>
})
|
/*import * as reactRouter3 from 'react-router';
export const Link = reactRouter3.Link;
export const withRouter = reactRouter3.withRouter;*/
import React from 'react';
import * as reactRouter from 'react-router';
import * as reactRouterDom from 'react-router-dom';
import { parseQuery } from './routeUtil'
import qs from 'qs'
export const withRouter = (WrappedComponent) => {
const WithRouterWrapper = (props) => {
return <WrappedComponent
routes={[]}
location={{pathname:""}}
router={{location: {query:"", pathname:""}}}
{...props}
/>
}
return reactRouter.withRouter(WithRouterWrapper);
}
export const Link = (props) => {
if (!(typeof props.to === "string" || typeof props.to === "object")) {
// eslint-disable-next-line no-console
console.error("Props 'to' for Link components only accepts strings or objects, passed type: ", typeof props.to)
return <span>Broken Link</span>
}
return <reactRouterDom.Link {...props}/>
}
export const QueryLink = reactRouter.withRouter(({query, location, staticContext, merge=false, ...rest}) => {
// Merge determines whether we do a shallow merge with the existing query parameters, or replace them completely
const newSearchString = merge ? qs.stringify({...parseQuery(location), ...query}) : qs.stringify(query)
return <reactRouterDom.Link
{...rest}
to={{search: newSearchString}}
/>
})
|
Fix dumb bug in link-props handling
|
Fix dumb bug in link-props handling
|
JavaScript
|
mit
|
Discordius/Telescope,Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Telescope,Discordius/Telescope,Discordius/Lesswrong2,Discordius/Telescope,Discordius/Lesswrong2
|
0e1e23a2754c56869c9abf1ec058f69ac047905b
|
FrontEndCreator/questions.js
|
FrontEndCreator/questions.js
|
//must have a blank option one for question of type dropdown
standard('qTypes',["","Drop Down", "Multidrop-down", "Number Fillin", "Essay", "Code"]);
standard('qTypes2',["","dropdowns", "multidropdowns", "numfillins", "essays", "codes"]);
standard('correct',["Correct","Incorrect"]);
standard('incorrect',["Incorrect","Correct"]);
quiz([
question("dropdown","Type of Question:",choices['qTypes'],'Choose a type...',choices['qTypes2']),
question("essay","Question Text:",3,30,'Your text here...'),
questionSet("dropdowns multidropdowns",[
question("essay","Placeholder Text:",3,30,'Your text here...'),
question("multiquestion","",[
question("essay","Answer Choice 1:",3,30,'Your text here...'),
question("dropdown","",choices['correct'])
]),
question("multiquestion","",[
question("essay","Answer Choice 2:",3,30,'Your text here...'),
question("dropdown","",choices['incorrect'])
]),
question("multiquestion","",[
question("essay","Answer Choice 3:",3,30,'Your text here...'),
question("dropdown","",choices['incorrect'])
])
]),
questionSet("codes",[
question("essay","Base Code:",3,30,'Your base code here...')
]),
questionSet("numfillins essays",[
question("essay","Placeholder Text:",3,30,'Your placeholder text here...')
])
]);
|
var config = {
'.chosen-select' : {},
};
for (var selector in config) {
$(selector).chosen(config[selector]);
}
for(var k = 0; k < showHideList.length; k++){
// alert(showHide);
var showHide=showHideList[k];
for(var i = 0; i < showHide.length; i++){
// alert(showHide[i]);
if(showHide[i].length>0)
$("."+showHide[i]).hide();
}
}
function SUBMIT_ONE_QUIZ(quiz){
var i = 0;
var allSend = "";
$(quiz).find(".question").each(function(){
if(!$(this).hasClass("nonquestion")){
if(i>0)
allSend+=",\n";
var val = $(this).val();
if(val==null){
val = "No Answer";
}
if(val.length < 1){
val = "No Answer";
}
//BTW we will escape the val of each answer so that students can't mess server parsing up
allSend+=("{q"+i+": "+val+"}");
i++;
}
});
alert(allSend);
}
/*Will send all quizes if need be
$("#sendAll").on("click",function(){
var i = 0;
$(".quiz").find(".question").each(function(){
var val = $(this).val();
if(val==null){
val = "No Answer";
}
if(val.length < 1){
val = "No Answer";
}
alert("q"+i+": "+val);
i++;
});
});
*/
|
Update methods to send object params
|
Update methods to send object params
|
JavaScript
|
mit
|
stephenjoro/QuizEngine
|
fa48474a1860ab76a38cb0de737e48262dcd1bef
|
api/routes/auth.js
|
api/routes/auth.js
|
const url = require('url');
const express = require('express');
const router = express.Router();
module.exports = (app, auth) => {
router.post('/', auth.authenticate('saml', {
failureFlash: true,
failureRedirect: app.get('configureUrl'),
}), (req, res) => {
const arns = req.user['https://aws.amazon.com/SAML/Attributes/Role'].split(',');
/* eslint-disable no-param-reassign */
req.session.passport.samlResponse = req.body.SAMLResponse;
req.session.passport.roleArn = arns[0];
req.session.passport.principalArn = arns[1];
req.session.passport.accountId = arns[0].split(':')[4]; // eslint-disable-line rapid7/static-magic-numbers
/* eslint-enable no-param-reassign */
let frontend = process.env.ELECTRON_START_URL || app.get('baseUrl');
frontend = new url.URL(frontend);
frontend.searchParams.set('auth', 'true');
res.redirect(frontend);
});
return router;
};
|
const url = require('url');
const express = require('express');
const router = express.Router();
module.exports = (app, auth) => {
router.post('/', auth.authenticate('saml', {
failureFlash: true,
failureRedirect: app.get('configureUrl'),
}), (req, res) => {
roles = req.user['https://aws.amazon.com/SAML/Attributes/Role']
if (!Array.isArray(roles)) {
roles = [roles]
}
const arns = roles[0].split(',');
/* eslint-disable no-param-reassign */
req.session.passport.samlResponse = req.body.SAMLResponse;
req.session.passport.roleArn = arns[0];
req.session.passport.principalArn = arns[1];
req.session.passport.accountId = arns[0].split(':')[4]; // eslint-disable-line rapid7/static-magic-numbers
/* eslint-enable no-param-reassign */
let frontend = process.env.ELECTRON_START_URL || app.get('baseUrl');
frontend = new url.URL(frontend);
frontend.searchParams.set('auth', 'true');
res.redirect(frontend);
});
return router;
};
|
Add support for multiple role assertions
|
Add support for multiple role assertions
The `https://aws.amazon.com/SAML/Attributes/Role` attribute supports
single or multiple values. This fixes Awsaml to work when a
multiple-value attribute is passed.
Currently, the first role is always used. Support for selecting from
the roles may be added later.
GH-105
|
JavaScript
|
mit
|
rapid7/awsaml,rapid7/awsaml,rapid7/awsaml
|
37822557c035ca41a6e9243f77d03a69351fc65c
|
examples/simple.js
|
examples/simple.js
|
var jerk = require( '../lib/jerk' ), sys=require('sys');
var options =
{ server: 'localhost'
, port: 6667
, nick: 'Bot9121'
, channels: [ '#jerkbot' ]
};
jerk( function( j ) {
j.watch_for( 'soup', function( message ) {
message.say( message.user + ': soup is good food!' )
});
j.watch_for( /^(.+) are silly$/, function( message ) {
message.say( message.user + ': ' + message.match_data[1] + ' are NOT SILLY. Don\'t joke!' )
});
j.user_join(function(message) {
message.say(message.user + ": Hey, welcome!");
});
j.user_leave(function(message) {
sys.puts("User: " + message.user + " has left");
});
}).connect( options );
|
var jerk = require( '../lib/jerk' ), util = require('util');
var options =
{ server: 'localhost'
, port: 6667
, nick: 'Bot9121'
, channels: [ '#jerkbot' ]
};
jerk( function( j ) {
j.watch_for( 'soup', function( message ) {
message.say( message.user + ': soup is good food!' )
});
j.watch_for( /^(.+) are silly$/, function( message ) {
message.say( message.user + ': ' + message.match_data[1] + ' are NOT SILLY. Don\'t joke!' )
});
j.user_join(function(message) {
message.say(message.user + ": Hey, welcome!");
});
j.user_leave(function(message) {
util.puts("User: " + message.user + " has left");
});
}).connect( options );
|
Use util instead of sys in example.
|
Use util instead of sys in example.
Make sure the example Jerk script continues to work in future node.js
releases. The node.js `sys` library has been a pointer to `util` since
0.3 and has now been removed completely in the node.js development
branch.
|
JavaScript
|
unlicense
|
gf3/Jerk
|
c671f90b3877273d18ba22351e1e8b9a63a925c3
|
shp/concat.js
|
shp/concat.js
|
export default function(a, b) {
var ab = new a.constructor(a.length + b.length);
ab.set(a, 0);
ab.set(b, a.length);
return ab;
}
|
export default function(a, b) {
var ab = new Uint8Array(a.length + b.length);
ab.set(a, 0);
ab.set(b, a.length);
return ab;
}
|
Fix for older versions of Node.
|
Fix for older versions of Node.
Older versions of Node had a conflicting implementation of buffer.set.
|
JavaScript
|
bsd-3-clause
|
mbostock/shapefile
|
1dfde5055467da45665db268a68e72866aef60e2
|
lib/networking/ws/BaseSocket.js
|
lib/networking/ws/BaseSocket.js
|
"use strict";
const WebSocket = require("ws");
const Constants = require("../../Constants");
const heartbeat = new WeakMap();
class BaseSocket extends WebSocket {
constructor(url) {
super(url);
this.readyState = Constants.ReadyState.CONNECTING;
this.on("open", () => this.readyState = Constants.ReadyState.OPEN);
const close = () => {
heartbeat.delete(this);
this.readyState = Constants.ReadyState.CLOSED;
};
this.on("close", close);
this.on("error", close);
}
get connected() {
return this.readyState == Constants.ReadyState.OPEN;
}
get connecting() {
return this.readyState == Constants.ReadyState.CONNECTING;
}
send(op, data) {
let m = {op: op, d: data};
try {
super.send(JSON.stringify(m));
} catch (e) { console.error(e.stack); }
}
setHeartbeat(opcode, msec) {
if (!this.connected)
return;
heartbeat.set(this, setInterval(() => {
if (!this.connected)
return this.close();
this.send(opcode, new Date().getTime());
}, msec));
}
}
module.exports = BaseSocket;
|
"use strict";
const WebSocket = require("ws");
const Constants = require("../../Constants");
const heartbeat = new WeakMap();
class BaseSocket extends WebSocket {
constructor(url) {
super(url);
this.readyState = Constants.ReadyState.CONNECTING;
this.on("open", () => this.readyState = Constants.ReadyState.OPEN);
const close = () => {
this.unsetHeartbeat();
this.readyState = Constants.ReadyState.CLOSED;
};
this.on("close", close);
this.on("error", close);
}
get connected() {
return this.readyState == Constants.ReadyState.OPEN;
}
get connecting() {
return this.readyState == Constants.ReadyState.CONNECTING;
}
send(op, data) {
let m = {op: op, d: data};
try {
super.send(JSON.stringify(m));
} catch (e) { console.error(e.stack); }
}
setHeartbeat(opcode, msec) {
if (!this.connected)
return;
heartbeat.set(this, setInterval(() => {
if (!this.connected)
return this.close();
this.send(opcode, new Date().getTime());
}, msec));
}
unsetHeartbeat() {
var handle = heartbeat.get(this);
if (handle !== undefined) clearInterval(handle);
heartbeat.delete(this);
}
close() {
super.close();
this.unsetHeartbeat();
// release websocket resources without waiting for close frame from Discord
if (this._closeTimer && this._closeTimer._onTimeout)
this._closeTimer._onTimeout();
clearTimeout(this._closeTimer);
}
}
module.exports = BaseSocket;
|
Fix heartbeat sender timer handle cleanup
|
Fix heartbeat sender timer handle cleanup
|
JavaScript
|
bsd-2-clause
|
qeled/discordie
|
e1c49c2c2c1e8e8661a079b6e7acd598bd6123d3
|
pliers-npm-security-check.js
|
pliers-npm-security-check.js
|
var fs = require('fs')
, request = require('request')
module.exports = function (pliers) {
pliers('npmSecurityCheck', function (done) {
fs.createReadStream('./npm-shrinkwrap.json').pipe(
request.post('https://nodesecurity.io/validate/shrinkwrap', function (error, res) {
if (error) done(new Error('Problem contacting nodesecurity.io web service'))
if (JSON.parse(res.body).length !== 0) {
pliers.logger.error('NPM packages with security warnings found')
JSON.parse(res.body).forEach(function (module) {
pliers.logger.error('module:', module.dependencyOf.join(' -> '), '->', module.module + '@' + module.version
, 'https://nodesecurity.io/advisories/' + module.advisory.url)
})
}
}))
})
}
|
var fs = require('fs')
, request = require('request')
module.exports = function (pliers, name) {
pliers(name || 'npmSecurityCheck', function (done) {
fs.createReadStream('./npm-shrinkwrap.json').pipe(
request.post('https://nodesecurity.io/validate/shrinkwrap', function (error, res) {
if (error) done(new Error('Problem contacting nodesecurity.io web service'))
if (JSON.parse(res.body).length !== 0) {
pliers.logger.error('NPM packages with security warnings found')
JSON.parse(res.body).forEach(function (module) {
pliers.logger.error('module:', module.dependencyOf.join(' -> '), '->', module.module + '@' + module.version
, 'https://nodesecurity.io/advisories/' + module.advisory.url)
})
}
}))
})
}
|
Add task name override functionality
|
Add task name override functionality
|
JavaScript
|
bsd-3-clause
|
pliersjs/pliers-npm-security-check
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.