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
|
|---|---|---|---|---|---|---|---|---|---|
d7070f4e55ba327ccce81de398d8a4ae66e38d06
|
blueprints/ember-cli-react/index.js
|
blueprints/ember-cli-react/index.js
|
/*jshint node:true*/
var pkg = require('../../package.json');
function getPeerDependencyVersion(packageJson, name) {
var peerDependencies = packageJson.peerDependencies;
return peerDependencies[name];
}
module.exports = {
description: 'Install ember-cli-react dependencies into your app.',
normalizeEntityName: function() {},
// Install react into host app
afterInstall: function() {
const packages = [
{
name: 'react',
target: getPeerDependencyVersion(pkg, 'react'),
},
{
name: 'react-dom',
target: getPeerDependencyVersion(pkg, 'react-dom'),
},
];
return this.addPackagesToProject(packages);
},
};
|
/*jshint node:true*/
var pkg = require('../../package.json');
function getDependencyVersion(packageJson, name) {
var dependencies = packageJson.dependencies;
var devDependencies = packageJson.devDependencies;
return dependencies[name] || devDependencies[name];
}
function getPeerDependencyVersion(packageJson, name) {
var peerDependencies = packageJson.peerDependencies;
return peerDependencies[name];
}
module.exports = {
description: 'Install ember-cli-react dependencies into your app.',
normalizeEntityName: function() {},
// Install react into host app
afterInstall: function() {
const packages = [
{
name: 'ember-auto-import',
target: getDependencyVersion(pkg, 'ember-auto-import'),
},
{
name: 'react',
target: getPeerDependencyVersion(pkg, 'react'),
},
{
name: 'react-dom',
target: getPeerDependencyVersion(pkg, 'react-dom'),
},
];
return this.addPackagesToProject(packages);
},
};
|
Install `ember-auto-import` to Ember App during `ember install`
|
Install `ember-auto-import` to Ember App during `ember install`
|
JavaScript
|
mit
|
pswai/ember-cli-react,pswai/ember-cli-react
|
e2367d78b76e73a56ca7e1d04c87d6727a169397
|
lib/build/source-map-support.js
|
lib/build/source-map-support.js
|
/**
* See https://github.com/evanw/node-source-map-support#browser-support
* This is expected to be included in a browserify-module to give proper stack traces, based on browserify's source maps.
*/
require('source-map-support').install();
|
/**
* See https://github.com/evanw/node-source-map-support#browser-support
* This is expected to be included in a browserify-module to give proper stack traces, based on browserify's source maps.
*/
if (window.location.search.indexOf('disablesourcemaps') === -1) {
require('source-map-support').install();
}
|
Add querystring flag to disable sourcemaps
|
Add querystring flag to disable sourcemaps
|
JavaScript
|
bsd-3-clause
|
splashblot/dronedb,codeandtheory/cartodb,splashblot/dronedb,CartoDB/cartodb,CartoDB/cartodb,splashblot/dronedb,splashblot/dronedb,codeandtheory/cartodb,codeandtheory/cartodb,CartoDB/cartodb,splashblot/dronedb,CartoDB/cartodb,codeandtheory/cartodb,codeandtheory/cartodb,CartoDB/cartodb
|
eed6ca7654f6b794eb2d8731838a8998fdd8d9ba
|
tests/config/karma.browserstack.conf.js
|
tests/config/karma.browserstack.conf.js
|
const base = require('./karma.base.conf');
module.exports = function(config) {
config.set(Object.assign(base, {
browserStack: {
username: process.env.BROWSERSTACK_USERNAME,
accessKey: process.env.BROWSERSTACK_ACCESS_KEY
},
customLaunchers: {
bs_safari_mac: {
base: 'BrowserStack',
browser: 'safari',
os: 'OS X',
os_version: 'Sierra'
},
bs_firefox_mac: {
base: 'BrowserStack',
browser: 'firefox',
os: 'OS X',
os_version: 'Sierra'
},
bs_chrome_mac: {
base: 'BrowserStack',
browser: 'chrome',
os: 'OS X',
os_version: 'Sierra'
}
},
browsers: ['bs_safari_mac', 'bs_firefox_mac', 'bs_chrome_mac'],
autoWatch: false,
singleRun: true,
reporters: ['dots', 'BrowserStack']
}));
};
|
const base = require('./karma.base.conf');
module.exports = function(config) {
config.set(Object.assign(base, {
browserStack: {
username: process.env.BROWSERSTACK_USERNAME,
accessKey: process.env.BROWSERSTACK_ACCESS_KEY
},
customLaunchers: {
bs_safari_mac: {
base: 'BrowserStack',
browser: 'safari',
os: 'OS X',
os_version: 'Sierra'
},
bs_firefox_mac: {
base: 'BrowserStack',
browser: 'firefox',
os: 'OS X',
os_version: 'Sierra'
},
bs_chrome_mac: {
base: 'BrowserStack',
browser: 'chrome',
os: 'OS X',
os_version: 'Sierra'
}
},
browsers: ['bs_safari_mac', 'bs_firefox_mac', 'bs_chrome_mac'],
autoWatch: false,
singleRun: true,
reporters: ['dots', 'BrowserStack', 'coverage']
}));
};
|
Add coverage reporter to browserstack build
|
Add coverage reporter to browserstack build
|
JavaScript
|
apache-2.0
|
weepower/wee-core
|
652f9ddc899d89f98c7f45a85ad81e90428cf922
|
packages/whosmysanta-backend/src/data/index.js
|
packages/whosmysanta-backend/src/data/index.js
|
import mongoose from 'mongoose';
const host = process.env.MONGO_HOST;
const database = encodeURIComponent(process.env.MONGO_DATABASE);
const user = encodeURIComponent(process.env.MONGO_USER);
const password = encodeURIComponent(process.env.MONGO_PASS);
export default function connectDatabase() {
// Use node version of Promise for mongoose
mongoose.Promise = global.Promise;
// Connect to mlab database
return mongoose.connect(`mongodb://${user}:${password}@${host}/${database}`);
}
|
import mongoose from 'mongoose';
const host = process.env.MONGO_HOST;
const database = encodeURIComponent(process.env.MONGO_DATABASE);
const user = encodeURIComponent(process.env.MONGO_USER);
const password = encodeURIComponent(process.env.MONGO_PASS);
// Use node version of Promise for mongoose
mongoose.Promise = global.Promise;
export default function connectDatabase() {
// Connect to mlab database
return mongoose.connect(`mongodb://${user}:${password}@${host}/${database}`);
}
|
Move mongoose.Promise reassignment out of function
|
Move mongoose.Promise reassignment out of function
|
JavaScript
|
mit
|
WhosMySanta/app,WhosMySanta/app,WhosMySanta/whosmysanta
|
01c0bc1440fb4c14a8ae49b667fba0ab09accbc8
|
src/components/Navbar/Navbar.js
|
src/components/Navbar/Navbar.js
|
import React from 'react';
import { Link } from 'react-router';
import './Navbar.scss';
export default class Navbar extends React.Component {
render () {
return (
<div className='navigation-items'>
<Link className='links' to='/about'>About me</Link>
<Link className='links' to='http://terakilobyte.com'>Blog</Link>
<Link className='links' to='http://twitter.com/terakilobyte'>Twitter</Link>
<Link className='links' to='http://github.com/terakilobyte'>Github</Link>
<Link className='links' to='/playground'>Playground</Link>
</div>
);
}
}
|
import React from 'react';
import { Link } from 'react-router';
import './Navbar.scss';
export default class Navbar extends React.Component {
render () {
return (
<div className='navigation-items'>
<Link className='links' to='/about'>About me</Link>
<a className='links' to='http://terakilobyte.com'>Blog</a>
<a className='links' to='http://twitter.com/terakilobyte'>Twitter</a>
<a className='links' to='http://github.com/terakilobyte'>Github</a>
<Link className='links' to='/playground'>Playground</Link>
</div>
);
}
}
|
Change external Links to a tags
|
Change external Links to a tags
|
JavaScript
|
mit
|
terakilobyte/terakilobyte.github.io,terakilobyte/terakilobyte.github.io
|
dfc02887804e7c5b2ce1555677cff4cd4910391c
|
templates/base/environment.js
|
templates/base/environment.js
|
var config = {
/*
metrics: {
port: 4001
}
*/
/* // For Passport auth via geddy-passport
, passport: {
twitter: {
consumerKey: 'XXXXX'
, consumerSecret: 'XXXXX'
}
, facebook: {
clientID: 'XXXXX'
, clientSecret: 'XXXXX'
}
}
*/
};
module.exports = config;
|
var config = {
/*
metrics: {
port: 4001
}
*/
/* // For Passport auth via geddy-passport
, passport: {
successRedirect: '/'
, failureRedirect: '/login'
, twitter: {
consumerKey: 'XXXXX'
, consumerSecret: 'XXXXX'
}
, facebook: {
clientID: 'XXXXX'
, clientSecret: 'XXXXX'
}
}
*/
};
module.exports = config;
|
Add success/failure redirects to Passport config
|
Add success/failure redirects to Passport config
|
JavaScript
|
apache-2.0
|
kolonse/ejs,mmis1000/ejs-promise,rpaterson/ejs,cnwhy/ejs,xanxiver/ejs,cnwhy/ejs,mde/ejs,TimothyGu/ejs-tj,TimothyGu/ejs-tj,jtsay362/solveforall-ejs2,operatino/ejs,tyduptyler13/ejs,insidewarehouse/ejs,zensh/ejs,kolonse/ejs,zensh/ejs,insidewarehouse/ejs
|
a5747b9e826d79342b54d08857b57cb523e9225f
|
javascripts/ai.js
|
javascripts/ai.js
|
var AI;
AI = function(baseSpeed) {
this.baseSpeed = baseSpeed;
};
// Simply follows the ball at all times
AI.prototype.easy = function(player, ball) {
'use strict';
var newY;
newY = ball.y - (player.paddle.y + player.paddle.height / 2);
if (newY < 0 && newY < -4) {
newY = -this.baseSpeed;
} else if (newY > 0 && newY > 4) {
newY = this.baseSpeed;
}
return newY;
};
// Follows the ball only when in its half, otherwise stay put
AI.prototype.medium = function(player, ball, canvasWidth, canvasHeight) {
'use strict';
var newY;
// If ball is moving towards computer
if (ball.xSpeed > 0 && ball.x > (canvasWidth / 1.75)) {
// Follow the ball
newY = ball.y - (player.paddle.y + player.paddle.height / 2);
if (newY < 0 && newY < -4) {
newY = -(this.baseSpeed + 0.5);
} else if (newY > 0 && newY > 4) {
newY = this.baseSpeed + 0.5;
}
} else {
newY = 0;
}
return newY;
};
// Predict where the ball is going to land
AI.prototype.hard = function(player, ball, canvasWidth, canvasHeight) {
'use strict';
var newY;
return newY;
};
|
var AI;
AI = function(baseSpeed) {
this.baseSpeed = baseSpeed;
};
// Simply follows the ball at all times
AI.prototype.easy = function(player, ball) {
'use strict';
var newY;
newY = ball.y - (player.paddle.y + player.paddle.height / 2);
if (newY < -4) {
newY = -this.baseSpeed;
} else if (newY > 4) {
newY = this.baseSpeed;
}
return newY;
};
// Follows the ball only when in its half, otherwise stay put
AI.prototype.medium = function(player, ball, canvasWidth, canvasHeight) {
'use strict';
var newY;
// If ball is moving towards computer
if (ball.xSpeed > 0 && ball.x > (canvasWidth / 1.75)) {
// Follow the ball
newY = ball.y - (player.paddle.y + player.paddle.height / 2);
if (newY < -4) {
newY = -(this.baseSpeed + 0.5);
} else if (newY > 4) {
newY = this.baseSpeed + 0.5;
}
} else {
newY = 0;
}
return newY;
};
// Predict where the ball is going to land
AI.prototype.hard = function(player, ball, canvasWidth, canvasHeight) {
'use strict';
var newY;
return newY;
};
|
Remove unnecessary ball speed checks
|
Remove unnecessary ball speed checks
|
JavaScript
|
mit
|
msanatan/pong,msanatan/pong,msanatan/pong
|
4ee7bc82b1282e718f88ba36ca2f7236f0019273
|
server/db/schemas/User.js
|
server/db/schemas/User.js
|
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
_id: { type: Number },
profileImageName: { type: String, default: 'default.png' },
email: { type: String, unique: true },
phoneNumber: { type: String },
name: {
first: { type: String, trim: true },
last: { type: String, trim: true }
},
registeredDate: { type: Date, default: Date.now },
admin: { type: Boolean, default: false },
verified: { type: Boolean, default: false }
}, {
toObject: {
virtuals: true
},
toJSON: {
virtuals: true
}
});
userSchema.methods.findCamps = function() {
return this.model('Camp').find().or([{ ambassador: this._id }, { director: this._id}, { teachers: this._id }]).populate('location').exec();
}
userSchema.virtual('name.full').get(function() {
return this.name.first + ' ' + this.name.last;
});
module.exports = { name: 'User', schema: userSchema };
|
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
_id: { type: Number },
profileImageName: { type: String, default: 'default.png' },
email: { type: String, unique: true },
age: { type: Number, min: 10, max: 100 },
grade: { type: Number, min: 8, max: 12 },
phoneNumber: { type: String },
name: {
first: { type: String, trim: true },
last: { type: String, trim: true }
},
application: {
recommender: { type: Number, ref: 'User' },
why: String,
writingFileName: String
},
registeredDate: { type: Date, default: Date.now },
admin: { type: Boolean, default: false },
verified: { type: Boolean, default: false }
}, {
toObject: {
virtuals: true
},
toJSON: {
virtuals: true
}
});
userSchema.methods.findCamps = function() {
return this.model('Camp').find().or([{ ambassador: this._id }, { director: this._id}, { teachers: this._id }]).populate('location').exec();
}
userSchema.virtual('name.full').get(function() {
return this.name.first + ' ' + this.name.last;
});
module.exports = { name: 'User', schema: userSchema };
|
Update user schema for application merge
|
Update user schema for application merge
|
JavaScript
|
mit
|
KidsTales/kt-web,KidsTales/kt-web
|
d45df4a5745c2bb3f5301f7a0ef587a3c5a73594
|
assets/js/util/is-site-kit-screen.js
|
assets/js/util/is-site-kit-screen.js
|
/**
* Utility function to check whether or not a view-context is a site kit view.
*
* Site Kit by Google, 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* External dependencies
*/
import includes from 'lodash/includes';
/**
* Internal dependencies
*/
import { SITE_KIT_VIEW_CONTEXTS } from '../googlesitekit/constants';
/**
* Checks whether or not the current viewContext is a Site Kit screen.
*
* @since n.e.x.t
*
* @param {string} viewContext THe view-context.
* @return {boolean} TRUE if the passed view-context is a site kit view; otherwise FALSE.
*/
const isSiteKitScreen = ( viewContext ) =>
includes( SITE_KIT_VIEW_CONTEXTS, viewContext );
export default isSiteKitScreen;
|
/**
* Utility function to check whether or not a view-context is a site kit view.
*
* Site Kit by Google, 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Internal dependencies
*/
import { SITE_KIT_VIEW_CONTEXTS } from '../googlesitekit/constants';
/**
* Checks whether or not the current viewContext is a Site Kit screen.
*
* @since n.e.x.t
*
* @param {string} viewContext The view-context.
* @return {boolean} TRUE if the passed view-context is a site kit view; otherwise FALSE.
*/
const isSiteKitScreen = ( viewContext ) =>
SITE_KIT_VIEW_CONTEXTS.includes( viewContext );
export default isSiteKitScreen;
|
Use vanilla includes function. Correct capitalisation.
|
Use vanilla includes function. Correct capitalisation.
|
JavaScript
|
apache-2.0
|
google/site-kit-wp,google/site-kit-wp,google/site-kit-wp,google/site-kit-wp
|
d7cbc2ec2c2e73d9f885ee0de8f395c0fdcbd24b
|
ui/features/lti_collaborations/index.js
|
ui/features/lti_collaborations/index.js
|
/*
* Copyright (C) 2014 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import router from './react/router'
router.start()
|
/*
* Copyright (C) 2014 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import router from './react/router'
import ready from '@instructure/ready'
ready(() => {
router.start()
})
|
Fix lti collaborations page unresponsive on load in chrome
|
Fix lti collaborations page unresponsive on load in chrome
fixes VICE-2440
flag=none
Test Plan:
- follow repro steps in linked ticket
Change-Id: I9b682719ea1e258f98caf90a197167a031995f7b
Reviewed-on: https://gerrit.instructure.com/c/canvas-lms/+/284881
Reviewed-by: Jeffrey Johnson <7a0f98bfe168bc29d5611ba0275e88567b492abc@instructure.com>
Product-Review: Jeffrey Johnson <7a0f98bfe168bc29d5611ba0275e88567b492abc@instructure.com>
QA-Review: Caleb Guanzon <54fa1f30d451e4f3c341a8f3c47c9215fd0be9c6@instructure.com>
Tested-by: Service Cloud Jenkins <9144042a601061f88f1e1d7a1753ea3e2972119d@instructure.com>
|
JavaScript
|
agpl-3.0
|
instructure/canvas-lms,sfu/canvas-lms,instructure/canvas-lms,instructure/canvas-lms,sfu/canvas-lms,sfu/canvas-lms,sfu/canvas-lms,instructure/canvas-lms,instructure/canvas-lms,instructure/canvas-lms,sfu/canvas-lms,sfu/canvas-lms,instructure/canvas-lms,sfu/canvas-lms
|
b25d54624f98726483c25a4f5f25419b1ae42660
|
timeout.js
|
timeout.js
|
'use strict'; /*jslint node: true, es5: true, indent: 2 */
var util = require('util');
var stream = require('stream');
var TimeoutDetector = module.exports = function(opts) {
if (opts === undefined) opts = {};
// opts = {[timeout: 60 (seconds)]}
stream.Transform.call(this, opts);
if (opts.timeout !== undefined) {
// ensure we get something every x seconds.
this.timeout_ms = opts.timeout * 1000;
setInterval(this._check.bind(this), this.timeout_ms);
}
};
util.inherits(TimeoutDetector, stream.Transform);
TimeoutDetector.prototype._check = function() {
// silent_ms: milliseconds since we got some incoming data
var silent_ms = Date.now() - this.last;
if (silent_ms > this.timeout_ms) {
this.emit('error', new Error('Timeout pipe timed out.'));
}
};
TimeoutDetector.prototype._transform = function(chunk, encoding, callback) {
this.last = Date.now();
this.push(chunk);
callback();
};
|
'use strict'; /*jslint node: true, es5: true, indent: 2 */
var util = require('util');
var stream = require('stream');
var TimeoutDetector = module.exports = function(opts) {
if (!opts || !opts.timeout) throw new Error('TimeoutDetector({timeout: ...}) is a required parameter.');
stream.Transform.call(this, opts);
this.timeout_ms = opts.timeout * 1000;
setInterval(this._check.bind(this), this.timeout_ms);
};
util.inherits(TimeoutDetector, stream.Transform);
TimeoutDetector.prototype._check = function() {
// silent_ms: milliseconds since we got some incoming data
var silent_ms = Date.now() - this.last;
if (silent_ms > this.timeout_ms) {
// ensure we get something every x seconds.
this.emit('error', new Error('TimeoutDetector timed out.'));
}
};
TimeoutDetector.prototype._transform = function(chunk, encoding, callback) {
this.last = Date.now();
this.push(chunk);
callback();
};
|
Trim down defaults out of TimeoutDetector.
|
Trim down defaults out of TimeoutDetector.
|
JavaScript
|
mit
|
chbrown/twilight,chbrown/twilight,chbrown/tweetjobs
|
17e1e14851112344b59b366676b3378ae09e798a
|
src/actions/action-creators.js
|
src/actions/action-creators.js
|
import dispatcher from '../dispatcher/dispatcher';
import actionTypes from '../constants/action-types';
import axios from 'axios';
import {
apiConstants
} from '../constants/api-constants';
const {
baseURL,
apiKey,
userName
} = apiConstants;
export function fetchUser() {
let getUserInfo = axios.create({
baseURL,
url: `?format=json&method=user.getinfo&user=${userName}&api_key=${apiKey}`
});
getUserInfo()
.then((response) => {
dispatcher.dispatch({
type: actionTypes.userRetrieved,
user: response.data.user
});
});
}
export function fetchRecentTracks() {
let getRecentTracks = axios.create({
baseURL,
url: `?format=json&method=user.getrecenttracks&user=${userName}&api_key=${apiKey}`
});
getRecentTracks()
.then((response) => {
dispatcher.dispatch({
type: actionTypes.recentTracksRetreived,
recentTracks: response.data.recenttracks.track
});
});
}
export function fetchTopArtists() {
let getTopArtists = axios.create({
baseURL,
url: `?format=json&method=user.gettopartists&user=${userName}&api_key=${apiKey}`
});
getTopArtists()
.then((response) => {
dispatcher.dispatch({
type: actionTypes.topArtistsRetreived,
topArtists: response.data.topartists.artist
});
});
}
|
import dispatcher from '../dispatcher/dispatcher';
import actionTypes from '../constants/action-types';
import axios from 'axios';
import {
apiConstants
} from '../constants/api-constants';
const {
baseURL,
apiKey,
userName
} = apiConstants;
export function fetchUser() {
let getUserInfo = axios.create({
baseURL,
url: `?format=json&method=user.getinfo&user=${userName}&api_key=${apiKey}`
});
getUserInfo()
.then((response) => {
dispatcher.dispatch({
type: actionTypes.userRetrieved,
user: response.data.user
});
});
}
export function fetchRecentTracks(limit) {
let getRecentTracks = axios.create({
baseURL,
url: `?format=json&method=user.getrecenttracks&user=${userName}&limit=${limit}&api_key=${apiKey}`
});
getRecentTracks()
.then((response) => {
dispatcher.dispatch({
type: actionTypes.recentTracksRetreived,
recentTracks: response.data.recenttracks.track
});
});
}
export function fetchTopArtists() {
let getTopArtists = axios.create({
baseURL,
url: `?format=json&method=user.gettopartists&user=${userName}&api_key=${apiKey}`
});
getTopArtists()
.then((response) => {
dispatcher.dispatch({
type: actionTypes.topArtistsRetreived,
topArtists: response.data.topartists.artist
});
});
}
|
Add ‘limit’ parameter to the fetchRecentTracks action to set the number of recent tracks to be retrieved
|
Add ‘limit’ parameter to the fetchRecentTracks action to set the number
of recent tracks to be retrieved
|
JavaScript
|
bsd-3-clause
|
jeromelachaud/Last.fm-Activities-React,jeromelachaud/Last.fm-Activities-React
|
0104841e84a3cdd1019f416678621e7bd9606802
|
src/Oro/Bundle/DataGridBundle/Resources/public/js/datagrid/editor/select-cell-radio-editor.js
|
src/Oro/Bundle/DataGridBundle/Resources/public/js/datagrid/editor/select-cell-radio-editor.js
|
/*global define*/
define([
'underscore',
'backgrid'
], function (_, Backgrid) {
'use strict';
var SelectCellRadioEditor;
SelectCellRadioEditor = Backgrid.SelectCellEditor.extend({
/**
* @inheritDoc
*/
tagName: "div",
/**
* @inheritDoc
*/
events: {
"change": "save",
"blur": "close",
"keydown": "close",
"click": "onClick"
},
/**
* @inheritDoc
*/
template: _.template('<input name="<%- this.model.cid + \'_\' + this.cid %>" type="radio" value="<%- value %>" <%= selected ? checked : "" %>><%- text %>', null, {variable: null}),
/**
* @param {Object} event
*/
onClick: function (event) {
event.stopPropagation();
}
});
return SelectCellRadioEditor;
});
|
/*global define*/
define([
'underscore',
'backgrid'
], function (_, Backgrid) {
'use strict';
var SelectCellRadioEditor;
SelectCellRadioEditor = Backgrid.SelectCellEditor.extend({
/**
* @inheritDoc
*/
tagName: "ul class='icons-ul'",
/**
* @inheritDoc
*/
events: {
"change": "save",
"blur": "close",
"keydown": "close",
"click": "onClick"
},
/**
* @inheritDoc
*/
template: _.template('<li><input id="<%- this.model.cid + \'_\' + this.cid + \'_\' + value %>" name="<%- this.model.cid + \'_\' + this.cid %>" type="radio" value="<%- value %>" <%= selected ? "checked" : "" %>><label for="<%- this.model.cid + \'_\' + this.cid + \'_\' + value %>"><%- text %></label></li>', null, {variable: null}),
/**
* @inheritDoc
*/
save: function () {
var model = this.model;
var column = this.column;
model.set(column.get("name"), this.formatter.toRaw(this.$el.find(':checked').val(), model));
},
/**
* @param {Object} event
*/
onClick: function (event) {
event.stopPropagation();
}
});
return SelectCellRadioEditor;
});
|
Create editor for input=radio, apply it in select-cell - fix radio buttons
|
BB-701: Create editor for input=radio, apply it in select-cell
- fix radio buttons
|
JavaScript
|
mit
|
2ndkauboy/platform,trustify/oroplatform,geoffroycochard/platform,northdakota/platform,ramunasd/platform,Djamy/platform,2ndkauboy/platform,trustify/oroplatform,orocrm/platform,geoffroycochard/platform,hugeval/platform,geoffroycochard/platform,Djamy/platform,hugeval/platform,orocrm/platform,Djamy/platform,northdakota/platform,2ndkauboy/platform,hugeval/platform,orocrm/platform,ramunasd/platform,trustify/oroplatform,northdakota/platform,ramunasd/platform
|
ddd9683976e6c41e6e6e2bd9de58232fabc2197b
|
portal/js/app.js
|
portal/js/app.js
|
var App = Ember.Application.create({
LOG_TRANSITIONS: true,
LOG_TRANSITIONS_INTERNAL: true
});
App.ApplicationAdapter = DS.RESTAdapter.extend({
host: 'https://website-api.withregard.io',
namespace: 'v1'
});
App.ApplicationSerializer = DS.RESTSerializer.extend({
primaryKey: '_id',
serializeHasMany: function (record, json, relationship) {
var key = relationship.key;
var relationshipType = DS.RelationshipChange.determineRelationshipType(record.constructor, relationship);
if (relationshipType === 'manyToNone' || relationshipType === 'manyToMany' || relationshipType === 'manyToOne') {
json[key] = Ember.get(record, key).mapBy('id');
}
}
});
App.ProjectView = Ember.View.extend({
didInsertElement: function() {
$(document).foundation();
}
})
|
var App = Ember.Application.create({
LOG_TRANSITIONS: true,
LOG_TRANSITIONS_INTERNAL: true
});
App.ApplicationAdapter = DS.RESTAdapter.extend({
host: 'https://website-api.withregard.io',
namespace: 'v1',
ajax: function(url, method, hash) {
hash.xhrFields = {withCredentials: true};
return this._super(url, method, hash);
}
});
App.ApplicationSerializer = DS.RESTSerializer.extend({
primaryKey: '_id',
serializeHasMany: function (record, json, relationship) {
var key = relationship.key;
var relationshipType = DS.RelationshipChange.determineRelationshipType(record.constructor, relationship);
if (relationshipType === 'manyToNone' || relationshipType === 'manyToMany' || relationshipType === 'manyToOne') {
json[key] = Ember.get(record, key).mapBy('id');
}
}
});
App.ProjectView = Ember.View.extend({
didInsertElement: function() {
$(document).foundation();
}
})
|
Send cookies with AJAX requests
|
Send cookies with AJAX requests
|
JavaScript
|
apache-2.0
|
with-regard/regard-website
|
f147f649aaad040522d93becb2a7bc845494fc76
|
gemini/index.js
|
gemini/index.js
|
gemini.suite('CSS component', (suite) => {
suite.setUrl('/?selectedKind=CSS%20component&selectedStory=default')
.setCaptureElements('#storybook-preview-iframe')
.capture('plain');
});
gemini.suite('Stateless functional component', (suite) => {
suite.setUrl('/?selectedKind=Stateless%20functional%20component&selectedStory=default')
.setCaptureElements('#storybook-preview-iframe')
.capture('plain');
});
gemini.suite('Web Component', (suite) => {
suite.setUrl('/?selectedKind=Web%20component&selectedStory=default')
.setCaptureElements('#storybook-preview-iframe')
.capture('plain');
});
|
gemini.suite('CSS component', (suite) => {
suite.setUrl('/iframe.html?selectedKind=CSS%20component&selectedStory=default')
.setCaptureElements('body')
.before((actions) => {
actions.setWindowSize(1024, 768);
})
.capture('plain');
});
gemini.suite('Stateless functional component', (suite) => {
suite.setUrl('/iframe.html?selectedKind=Stateless%20functional%20component&selectedStory=default')
.setCaptureElements('body')
.before((actions) => {
actions.setWindowSize(1024, 768);
})
.capture('plain');
});
gemini.suite('Web Component', (suite) => {
suite.setUrl('/iframe.html?selectedKind=Web%20component&selectedStory=default')
.setCaptureElements('body')
.before((actions) => {
actions.setWindowSize(1024, 768);
})
.capture('plain');
});
|
Test the frame contents directly
|
Test the frame contents directly
|
JavaScript
|
mit
|
z-kit/component,z-kit/z-hello,z-kit/component,z-kit/z-hello
|
530467c4840fcd528cd836d1e25fa3174c6b3b9e
|
extension/keysocket-yandex-music.js
|
extension/keysocket-yandex-music.js
|
var playTarget = '.b-jambox__play';
var nextTarget = '.b-jambox__next';
var prevTarget = '.b-jambox__prev';
function onKeyPress(key) {
if (key === PREV) {
simulateClick(document.querySelector(prevTarget));
} else if (key === NEXT) {
simulateClick(document.querySelector(nextTarget));
} else if (key === PLAY) {
simulateClick(document.querySelector(playTarget));
}
}
|
var playTarget = '.player-controls__btn_play';
var nextTarget = '.player-controls__btn_next';
var prevTarget = '.player-controls__btn_prev';
function onKeyPress(key) {
if (key === PREV) {
simulateClick(document.querySelector(prevTarget));
} else if (key === NEXT) {
simulateClick(document.querySelector(nextTarget));
} else if (key === PLAY) {
simulateClick(document.querySelector(playTarget));
}
}
|
Update locators for redesigned Yandex Music
|
Update locators for redesigned Yandex Music
|
JavaScript
|
apache-2.0
|
borismus/keysocket,iver56/keysocket,feedbee/keysocket,vinyldarkscratch/keysocket,feedbee/keysocket,borismus/keysocket,noelmansour/keysocket,kristianj/keysocket,ALiangLiang/keysocket,kristianj/keysocket,chrisdeely/keysocket,legionaryu/keysocket,vladikoff/keysocket,vinyldarkscratch/keysocket,Whoaa512/keysocket
|
b94a452d4030829731047014cefa4f178591f891
|
src/scripts/plugins/Storage.js
|
src/scripts/plugins/Storage.js
|
class Storage extends Phaser.Plugin {
constructor (game, parent) {
super(game, parent);
}
init (name) {
localforage.config({ name });
}
// --------------------------------------------------------------------------
fetch (key, callback = () => {}, context = null) {
localforage.getItem(key, this._wrap(callback, context));
}
store (key, value, callback = () => {}, context = null) {
localforage.setItem(key, value, this._wrap(callback, context));
}
remove (key, callback = () => {}, context = null) {
localforage.removeItem(key, this._wrap(callback, context));
}
clear (callback = () => {}, context = null) {
localforage.clear(this._wrap(callback, context));
}
length (callback = () => {}, context = null) {
localforage.length(this._wrap(callback, context));
}
key (keyIndex, callback = () => {}, context = null) {
localforage.key(keyIndex, this._wrap(callback, context));
}
keys (callback = () => {}, context = null) {
localforage.keys(this._wrap(callback, context));
}
iterate (iterator, iterContext, callback = () => {}, cbContext = null) {
localforage.iterate(
this._wrap(iterator, iterContext),
this._wrap(callback, cbContext));
}
// --------------------------------------------------------------------------
_wrap (callback, context) {
return (... args) => { callback.apply(context, args); };
}
}
export default Storage;
|
class Storage extends Phaser.Plugin {
constructor (game, parent) {
super(game, parent);
}
init (name, version = '1.0') {
localforage.config({ name, version });
}
// --------------------------------------------------------------------------
fetch (key, callback = () => {}, context = null) {
localforage.getItem(key, this._wrap(callback, context));
}
store (key, value, callback = () => {}, context = null) {
localforage.setItem(key, value, this._wrap(callback, context));
}
remove (key, callback = () => {}, context = null) {
localforage.removeItem(key, this._wrap(callback, context));
}
clear (callback = () => {}, context = null) {
localforage.clear(this._wrap(callback, context));
}
length (callback = () => {}, context = null) {
localforage.length(this._wrap(callback, context));
}
key (keyIndex, callback = () => {}, context = null) {
localforage.key(keyIndex, this._wrap(callback, context));
}
keys (callback = () => {}, context = null) {
localforage.keys(this._wrap(callback, context));
}
iterate (iterator, iterContext, callback = () => {}, cbContext = null) {
localforage.iterate(
this._wrap(iterator, iterContext),
this._wrap(callback, cbContext));
}
// --------------------------------------------------------------------------
_wrap (callback, context) {
return (... args) => { callback.apply(context, args); };
}
}
export default Storage;
|
Allow an extra argument to be passed, identifying the storage version in use.
|
Allow an extra argument to be passed, identifying the storage version in use.
|
JavaScript
|
mit
|
rblopes/heart-star,rblopes/heart-star
|
ae78fc5de9f85dd9e13412f626b643314799e487
|
lib/runner/request-helpers-postsend.js
|
lib/runner/request-helpers-postsend.js
|
var AuthLoader = require('../authorizer/index').AuthLoader,
createAuthInterface = require('../authorizer/auth-interface'),
util = require('../authorizer/util');
module.exports = [
// Post authorization.
function (context, run, done) {
// if no response is provided, there's nothing to do, and probably means that the request errored out
// let the actual request command handle whatever needs to be done.
if (!context.response) { return done(); }
// bail out if there is no auth
if (!(context.auth && context.auth.type)) { return done(); }
// bail out if interactive mode is disabled
if (!util.isInteractiveForAuth(run.options, context.auth.type)) { return done(); }
var auth = context.auth,
authHandler = AuthLoader.getHandler(auth.type),
authInterface = createAuthInterface(auth);
// invoke `post` on the Auth
authHandler.post(authInterface, context.response, function (err, success) {
// sync auth state back to item request
_.set(context, 'item.request.auth', auth);
// there was an error in auth post hook
if (err) { return done(err); }
// auth was verified
if (success) { return done(); }
// request a replay of request
done(null, {replay: true});
});
}
];
|
var _ = require('lodash'),
AuthLoader = require('../authorizer/index').AuthLoader,
createAuthInterface = require('../authorizer/auth-interface'),
util = require('../authorizer/util');
module.exports = [
// Post authorization.
function (context, run, done) {
// if no response is provided, there's nothing to do, and probably means that the request errored out
// let the actual request command handle whatever needs to be done.
if (!context.response) { return done(); }
// bail out if there is no auth
if (!(context.auth && context.auth.type)) { return done(); }
// bail out if interactive mode is disabled
if (!util.isInteractiveForAuth(run.options, context.auth.type)) { return done(); }
var auth = context.auth,
authHandler = AuthLoader.getHandler(auth.type),
authInterface = createAuthInterface(auth);
// invoke `post` on the Auth
authHandler.post(authInterface, context.response, function (err, success) {
// sync auth state back to item request
_.set(context, 'item.request.auth', auth);
// there was an error in auth post hook
if (err) { return done(err); }
// auth was verified
if (success) { return done(); }
// request a replay of request
done(null, {replay: true});
});
}
];
|
Fix missing import in merge conflict resolution
|
Fix missing import in merge conflict resolution
|
JavaScript
|
apache-2.0
|
postmanlabs/postman-runtime,postmanlabs/postman-runtime
|
4bac6994b83e1ae64a01bb25e060a3730571df38
|
lib/index.js
|
lib/index.js
|
'use strict';
var child_process = require('child_process');
var fs = require('fs');
var Module = require('module');
var path = require('path');
var _ = require('lodash');
var originalRequire = module.require;
module.require = function(pth) {
if(path.extname(pth) === '.git') return loadGit(pth);
return originalRequire;
};
function loadGit(url) {
var nodeModulesPath = path.join(process.cwd(), 'node_modules');
var oldModules = fs.readdirSync(nodeModulesPath);
child_process.execSync('npm install --save ' + url + ' ');
var newModules = fs.readdirSync(nodeModulesPath);
var added = _.difference(oldModules, newModules)[0];
if(added) return originalRequire(added);
else return undefined;
}
exports = module.exports = loadGit;
console.log(require('git://github.com/yamadapc/mocha-spec-cov-alt.git'));
|
'use strict';
var child_process = require('child_process');
var fs = require('fs');
var Module = require('module');
var path = require('path');
var _ = require('lodash');
require.extensions['.git'] = loadGit;
function loadGit(url, save) {
var nodeModulesPath = path.join(process.cwd(), 'node_modules');
var oldModules = fs.readdirSync(nodeModulesPath);
var command = 'npm install ' + (save ? '--save' : '') + ' ' + url + ' ';
child_process.execSync(command, {
stdio: 'ignore',
});
var newModules = fs.readdirSync(nodeModulesPath);
var added = _.difference(oldModules, newModules)[0];
if(added) return originalRequire(added);
else return undefined;
}
exports = module.exports = loadGit;
|
Make the implementation much more elegant
|
Make the implementation much more elegant
|
JavaScript
|
mit
|
yamadapc/nrequire
|
7fdc72722c0bd39d485382a0df199e933c87b9c0
|
lib/index.js
|
lib/index.js
|
// Dependencies
var Typpy = require("typpy")
, NodeElm = require("./composition/node")
, Composition = require("./composition")
, Enny = require("enny")
;
function Parser(input, appService, moduleInfo, callback) {
// Add the instances
var comp = new Composition({
instances: input
, appService: appService
, moduleInfo: moduleInfo
})
comp.parseFlow();
comp.addConnections();
callback(null, comp);
}
module.exports = Parser;
|
// Dependencies
var Typpy = require("typpy")
, NodeElm = require("./composition/node")
, Composition = require("./composition")
, Enny = require("enny")
;
function Parser(input, appService, moduleInfo, callback) {
// Add the instances
var comp = new Composition({
instances: input
, appService: appService
, moduleInfo: moduleInfo
})
comp.parseFlow();
comp.addConnections();
callback(null, comp);
}
if (typeof window === "object") {
window.EngineParser = Parser;
}
module.exports = Parser;
|
Create a global when running in browser
|
Create a global when running in browser
|
JavaScript
|
mit
|
jillix/engine-builder
|
8290936c560abc56ee43635ff7c90b14ea3042d2
|
lib/redis.js
|
lib/redis.js
|
'use strict';
const async = require('async');
const redis = require('redis').createClient(6379, 'redis');
module.exports = redis;
module.exports.jenkinsChanged = function(nodes, cb) {
async.filter(nodes, function(node, cb) {
const key = `node:${node.displayName}`;
node.offline = !!(node.offline || node.temporarilyOffline) + 0;
redis.hget(key, 'offline', function(err, offline) {
if (err) { return cb(err); }
offline = parseInt(offline || 0, 10);
redis.hset(key, 'offline', node.offline, function(err) {
if (err) { return cb(err); }
cb(!!(node.offline ^ offline));
});
});
}, function(nodes) {
cb(null, nodes);
});
};
|
'use strict';
const async = require('async');
const redis = require('redis').createClient(6379, 'redis');
module.exports = redis;
module.exports.jenkinsChanged = function(nodes, cb) {
async.filter(nodes, function(node, cb) {
const key = `node:${node.name || node.displayName}`;
node.offline = !!(node.offline || node.temporarilyOffline) + 0;
redis.hget(key, 'offline', function(err, offline) {
if (err) { return cb(err); }
offline = parseInt(offline || 0, 10);
redis.hset(key, 'offline', node.offline, function(err) {
if (err) { return cb(err); }
cb(!!(node.offline ^ offline));
});
});
}, function(nodes) {
cb(null, nodes);
});
};
|
Add support for alternative Jenkins node name
|
Add support for alternative Jenkins node name
|
JavaScript
|
mit
|
Starefossen/jenkins-monitor
|
1b73b33858db20c9cfdc171a406d12c1bcfa590f
|
src/util/logger/serializers.js
|
src/util/logger/serializers.js
|
/**
* @param {import('discord.js').Guild} guild
*/
function guild (guild) {
return `${guild.id}, ${guild.name}`
}
/**
* @param {import('discord.js').TextChannel} channel
*/
function channel (channel) {
return `(${channel.guild.id}) ${channel.id}, ${channel.name}`
}
/**
* @param {import('discord.js').User} user
*/
function user (user) {
return `${user.id}, ${user.username}`
}
module.exports = {
guild,
channel,
user
}
|
/**
* @param {import('discord.js').Guild} guild
*/
function guild (guild) {
return `${guild.id}, ${guild.name}`
}
/**
* @param {import('discord.js').TextChannel} channel
*/
function channel (channel) {
return `${channel.id}, ${channel.name}`
}
/**
* @param {import('discord.js').User} user
*/
function user (user) {
return `${user.id}, ${user.username}`
}
module.exports = {
guild,
channel,
user
}
|
Remove dupe info in channel log serializer
|
Remove dupe info in channel log serializer
|
JavaScript
|
mit
|
synzen/Discord.RSS,synzen/Discord.RSS
|
fde26acaffdb416751ff17c391f3a411e8d9207b
|
404/main.js
|
404/main.js
|
// 404 page using mapbox to show cities around the world.
// Helper to generate the kind of coordinate pairs I'm using to store cities
function bounds() {
var center = map.getCenter();
return {lat: center.lat, lng: center.lng, zoom: map.getZoom()};
}
L.mapbox.accessToken = "pk.eyJ1IjoiY29udHJvdmVyc2lhbCIsImEiOiJjaXMwaXEwYjUwM2l6MnpwOHdodTh6Y24xIn0.JOD0uX_n_KXqhJ7ERnK0Lg";
var map = L.mapbox.map("map", "mapbox.pencil", {zoomControl: false});
function go(city) {
var placenames = Object.keys(places);
city = city || placenames[Math.floor(Math.random() * placenames.length)];
var pos = places[city];
map.setView(
[pos.lat, pos.lng],
pos.zoom
);
}
go();
|
// 404 page using mapbox to show cities around the world.
// Helper to generate the kind of coordinate pairs I'm using to store cities
function bounds() {
var center = map.getCenter();
return {lat: center.lat, lng: center.lng, zoom: map.getZoom()};
}
L.mapbox.accessToken = "pk.eyJ1IjoiY29udHJvdmVyc2lhbCIsImEiOiJjaXMwaXEwYjUwM2l6MnpwOHdodTh6Y24xIn0.JOD0uX_n_KXqhJ7ERnK0Lg";
var map = L.mapbox.map("map", "mapbox.pencil", {zoomControl: false});
function go(city) {
var placenames = Object.keys(places);
city = city || placenames[Math.floor(Math.random() * placenames.length)];
var pos = places[city];
map.setView(
[pos.lat, pos.lng],
pos.zoom
);
}
if (places[window.location.search.substring(1)]) {
go(window.location.search.substring(1));
} else {
go();
}
|
Allow direct linking to cities
|
Allow direct linking to cities
|
JavaScript
|
mit
|
controversial/controversial.io,controversial/controversial.io,controversial/controversial.io
|
def7c0fcb0c0c2adbd66d530d0634d6a6e53f0d7
|
virun.js
|
virun.js
|
var virus = document.querySelector("div");
var x = 1;
var y = 0;
var vy = 0;
var ay = 0;
var vx = .1; // px per millisecond
var startTime = Date.now();
var clickTime;
timer = setInterval(function animate() {
var t = Date.now() - startTime;
x = vx * t;
y = vy * t + 400;
virus.style.left = x + "px";
virus.style.top = y + "px";
if ( x > document.body.clientWidth) {
startTime = Date.now();
}
if (ay >= .001) {
var t = Date.now() - clickTime;
vy = ay * t;
}
},20); // ms | 1000/20 = 50 frames per second (50 fps)
virus.addEventListener("click", function onclick(event) {
ay = .001;
clickTime = Date.now();
});
|
var virus = document.querySelector("div");
var x = 1;
var y = 0;
var vy = 0;
var ay = 0;
var vx = .1; // px per millisecond
var startTime = Date.now();
var clickTime;
timer = setInterval(function animate() {
var t = Date.now() - startTime;
x = vx * t;
y = vy * t + 400;
virus.style.left = x + "px";
virus.style.top = y + "px";
if ( x > document.body.clientWidth) {
startTime = Date.now();
}
if (ay >= .001) {
var t = Date.now() - clickTime;
vy = ay * t;
}
//if ( y > document.body.clientHeight && x > document.body.clientWidth) {
// console.log("hello");
// startTime = Date.now();
//}
if (y > screen.height){
console.log("hello");
startTime = Date.now();
vy = 0;
ay = 0;
}
//if ( y > document.body.clientHeight && x > document.body.clientWidth) {
// console.log("second if");
// vy = 0;
// ay = 0;
//}
},20); // ms | 1000/20 = 50 frames per second (50 fps)
virus.addEventListener("click", function onclick(event) {
ay = .001;
clickTime = Date.now();
});
|
Add property screen.height, so that the ufo, once it is shot and falls, returns to start position and flies the same horizontal line like in the beginning
|
Add property screen.height, so that the ufo, once it is shot and falls, returns to start position and flies the same horizontal line like in the beginning
|
JavaScript
|
mit
|
BOZ2323/virun,BOZ2323/virun
|
b834bacb099306bac030b37477fbee0b4a3324de
|
Gulpfile.js
|
Gulpfile.js
|
var gulp = require("gulp"),
util = require("gulp-util"),
minifyHtml = require("gulp-minify-html"),
less = require("gulp-less"),
minifyCss = require("gulp-minify-css"),
minifyJs = require("gulp-uglify");
gulp.task("html", function() {
util.log("Minifying...");
gulp.src("src/html/*.html")
.pipe(minifyHtml({}))
.pipe(gulp.dest("public/"));
util.log("Done!");
});
gulp.task("less", function() {
util.log("Compiling and minifying...");
gulp.src("src/less/*.less")
.pipe(less())
.pipe(minifyCss({cache: false}))
.pipe(gulp.dest("public/css/"));
util.log("Done!");
});
gulp.task("js", function() {
util.log("Minifying...");
gulp.src("src/js/*.js")
.pipe(minifyJs({mangle: false}))
.pipe(gulp.dest("public/js/"));
util.log("Done!");
});
gulp.task("watch", function() {
gulp.watch("src/html/*.html", ["html"]);
gulp.watch("src/less/**/*.less", ["less"]);
gulp.watch("src/js/*.js", ["js"]);
});
gulp.task("default", ["html", "less", "js", "watch"], function() {
util.log("Done!");
});
|
var gulp = require("gulp"),
util = require("gulp-util"),
minifyHtml = require("gulp-minify-html"),
less = require("gulp-less"),
minifyCss = require("gulp-minify-css"),
minifyJs = require("gulp-uglify");
gulp.task("html", function() {
util.log("Minifying...");
gulp.src("src/html/*.html")
.pipe(minifyHtml({}))
.pipe(gulp.dest("public/"));
util.log("Done!");
});
gulp.task("less", function() {
util.log("Compiling and minifying...");
gulp.src("src/less/*.less")
.pipe(less())
.pipe(minifyCss({cache: false}))
.pipe(gulp.dest("public/css/"));
util.log("Done!");
});
gulp.task("js", function() {
util.log("Minifying...");
gulp.src("src/js/*.js")
.pipe(minifyJs({mangle: false, compress: false}))
.pipe(gulp.dest("public/js/"));
util.log("Done!");
});
gulp.task("watch", function() {
gulp.watch("src/html/*.html", ["html"]);
gulp.watch("src/less/**/*.less", ["less"]);
gulp.watch("src/js/*.js", ["js"]);
});
gulp.task("default", ["html", "less", "js", "watch"], function() {
util.log("Done!");
});
|
Add compress: false for proper results.
|
Add compress: false for proper results.
|
JavaScript
|
mit
|
bound1ess/todo-app,bound1ess/todo-app,bound1ess/todo-app
|
a7cde01856ed053477d1edf907f4236ae2dbb23e
|
trex/static/js/controllers.js
|
trex/static/js/controllers.js
|
var trexControllers = angular.module('trexControllers', []);
trexControllers.controller('ProjectListCtrl', ['$scope', '$http',
function($scope, $http) {
$http.get('/api/1/projects/').success(function(data) {
$scope.projects = data;
});
$scope.order = "name";
$scope.orderreverse = false;
$scope.setOrder = function(name) {
if (name == $scope.order) {
$scope.orderreverse = !$scope.orderreverse;
}
$scope.order = name;
};
}
]);
trexControllers.controller('ProjectDetailCtrl',
['$scope', '$routeParams', '$http',
function($scope, $routeParams, $http) {
$http.get('/api/1/projects/' + $routeParams.id).success(function(data) {
$scope.project = data;
});
$http.get('/api/1/projects/' + $routeParams.id + "/entries").success(
function(data) {
$scope.entries = data;
});
$scope.order = "name";
$scope.orderreverse = false;
$scope.setOrder = function(name) {
if (name == $scope.order) {
$scope.orderreverse = !$scope.orderreverse;
}
$scope.order = name;
};
}
]);
|
var trexControllers = angular.module('trexControllers', []);
trexControllers.controller('ProjectListCtrl', ['$scope', 'Project',
function($scope, Project) {
$scope.projects = Project.query();
$scope.order = "name";
$scope.orderreverse = false;
$scope.setOrder = function(name) {
if (name == $scope.order) {
$scope.orderreverse = !$scope.orderreverse;
}
$scope.order = name;
};
}
]);
trexControllers.controller('ProjectDetailCtrl',
['$scope', '$routeParams', 'Project',
function($scope, $routeParams, Project) {
$scope.project = Project.get({projectId: $routeParams.id});
$scope.entries = Project.entries({projectId: $routeParams.id});
// $http.get('/api/1/projects/' + $routeParams.id + "/entries").success(
// function(data) {
// });
$scope.order = "id";
$scope.orderreverse = false;
$scope.setOrder = function(name) {
if (name == $scope.order) {
$scope.orderreverse = !$scope.orderreverse;
}
$scope.order = name;
};
}
]);
|
Use new services for retreiving the Project and Entry
|
Use new services for retreiving the Project and Entry
|
JavaScript
|
mit
|
bjoernricks/trex,bjoernricks/trex
|
dd950e957c2acc4b12160c0d64721506cab0348f
|
Gulpfile.js
|
Gulpfile.js
|
var gulp = require('gulp'),
$ = require('gulp-load-plugins')();
gulp.task('styles', function() {
gulp.src('app/**/*.scss')
.pipe($.watch(function(files) {
files.pipe($.sass())
.pipe($.autoprefixer())
.pipe($.minifyCss())
.pipe(gulp.dest('./dist'))
.pipe($.livereload());
}));
});
gulp.task('copy', function() {
gulp.src('app/**/*.html')
.pipe($.watch())
.pipe($.embedlr())
.pipe(gulp.dest('./dist'))
});
gulp.task('serve', $.serve({
root: ['dist', 'app'],
port: 9000
}));
gulp.task('default', ['styles', 'copy', 'serve']);
|
var gulp = require('gulp'),
$ = require('gulp-load-plugins')(),
browserSync = require('browser-sync'),
reload = browserSync.reload,
config = {
// destinations
tmp: '.tmp',
app: 'app',
dist: 'dist',
// globs
sass: 'app/**/*.scss',
};
gulp.task('copy', function() {
gulp.src('app/**/*.html')
.pipe($.watch())
.pipe(gulp.dest('./dist'))
});
gulp.task('sass', function() {
return gulp.src(config.sass)
.pipe($.plumber())
.pipe($.sass())
.pipe($.autoprefixer())
/*.pipe($.minifyCss())*/
.pipe(gulp.dest(config.tmp))
.pipe(reload({stream: true}));
});
gulp.task('browser-sync', function() {
return browserSync({
server: {
baseDir: [config.tmp, config.app]
}
})
});
gulp.task('watch', function() {
$.watch({glob: config.sass, name: 'Sass'}, ['sass']);
});
gulp.task('default', ['sass', 'copy', 'watch', 'browser-sync']);
|
Update intensely to be much better.
|
Update intensely to be much better.
|
JavaScript
|
mit
|
SevereOverfl0w/generator-buymilk
|
3411cef46121ed8f27468275a6149ee1a55fd717
|
SmartyFace.js
|
SmartyFace.js
|
// ==UserScript==
// @name SmartyFace
// @description Text Prediction on facepunch
// @author benjojo
// @namespace http://facepunch.com
// @include http://facepunch.com/*
// @include http://www.facepunch.com/*
// @include https://facepunch.com/*
// @include https://www.facepunch.com/*
// @version 1
// ==/UserScript==
var endPoint = "http://text.nsa.me.uk/pose";
function findTextBoxes (argument) {
var boxes = $('textarea');
var parent = boxes[2].parentNode;
$(parent).prepend("<i id=\"SmartyFace\" style=\"pointer-events:none; color: #CCC;position: absolute;font: 13px Verdana,Arial,Tahoma,Calibri,Geneva,sans-serif;padding: 0 1px 0 1px;\">This is a test wow. such test</i>");
var textarea = boxes[2];
$(boxes[2]).keypress(function(a) {
var text = $(textarea).val();
$.post( endPoint, { post: text })
.done(function( data ) {
$('#SmartyFace').html($(textarea).val()+data);
});
// $('#SmartyFace').html($(textarea).val());
});
}
findTextBoxes();
|
// ==UserScript==
// @name SmartyFace
// @description Text Prediction on facepunch
// @author benjojo
// @namespace http://facepunch.com
// @include http://facepunch.com/*
// @include http://www.facepunch.com/*
// @include https://facepunch.com/*
// @include https://www.facepunch.com/*
// @version 1
// ==/UserScript==
var endPoint = "http://text.nsa.me.uk/pose";
function findTextBoxes (argument) {
var boxes = $('textarea');
var parent = boxes[2].parentNode;
$(parent).prepend("<i id=\"SmartyFace\" style=\"pointer-events:none; color: #CCC;position: absolute;font: 13px Verdana,Arial,Tahoma,Calibri,Geneva,sans-serif;padding: 0 1px 0 1px;\">Type Reply Here</i>");
var textarea = boxes[2];
$(boxes[2]).keypress(function(a) {
var text = $(textarea).val();
$.post( endPoint, { post: text })
.done(function( data ) {
$('#SmartyFace').html($(textarea).val()+data);
});
// $('#SmartyFace').html($(textarea).val());
});
}
findTextBoxes();
|
Make the starting text more sane
|
Make the starting text more sane
|
JavaScript
|
mit
|
benjojo/SmartyFace
|
f98f6b4660110f1421eae1f484d9242b62b0697d
|
src/swagger/add-model.js
|
src/swagger/add-model.js
|
'use strict';
var _ = require('lodash');
var swagger = require('swagger-spec-express');
var schemaKeys = Object.keys(require('swagger-spec-express/lib/schemas/schema.json').properties);
schemaKeys.push('definitions');
module.exports = function addModel(schema) {
var modelSchema = _.cloneDeep(_.pick(schema, schemaKeys));
stripSpecificProperties(modelSchema);
swagger.common.addModel(modelSchema, {validation: 'warn'});
};
const propertiesToStrip = ['faker', 'chance'];
function stripSpecificProperties(schema) {
if (_.isArray(schema)) {
schema.forEach(function (item) {
stripSpecificProperties(item);
});
return;
}
if (!_.isObject(schema)) {
return;
}
propertiesToStrip.forEach(function (key) {
delete schema[key];
});
_.valuesIn(schema).forEach(stripSpecificProperties);
}
|
'use strict';
var _ = require('lodash');
var swagger = require('swagger-spec-express');
var schemaKeys = Object.keys(require('swagger-spec-express/lib/schemas/schema.json').properties);
schemaKeys.push('definitions');
module.exports = function addModel(schema) {
var modelSchema = _.cloneDeep(_.pick(schema, schemaKeys));
filterProperties(modelSchema.properties);
if (modelSchema.definitions) {
Object.keys(modelSchema.definitions).forEach(function (definitionName) {
var definitionValue = modelSchema.definitions[definitionName];
filterProperties(definitionValue.properties);
});
}
swagger.common.addModel(modelSchema, {validation: 'warn'});
};
function filterProperties(properties) {
Object.keys(properties).forEach(function (propertyName) {
var propertyValue = properties[propertyName];
Object.keys(propertyValue).forEach(function (key) {
if (schemaKeys.indexOf(key) < 0) {
delete propertyValue[key];
}
if (key.toLowerCase() === 'properties') {
filterProperties(propertyValue.properties);
}
});
});
}
|
Fix for stripping properties before adding to swagger.
|
Fix for stripping properties before adding to swagger.
|
JavaScript
|
mit
|
eXigentCoder/node-api-seed,eXigentCoder/node-api-seed
|
e1cfb2e2b4cc186c7d23c47e9d759d54b7571c80
|
src/renderers/canvas/sigma.canvas.nodes.def.js
|
src/renderers/canvas/sigma.canvas.nodes.def.js
|
;(function() {
'use strict';
sigma.utils.pkg('sigma.canvas.nodes');
/**
* The default node renderer. It renders the node as a simple disc.
*
* @param {object} node The node object.
* @param {CanvasRenderingContext2D} context The canvas context.
* @param {configurable} settings The settings function.
*/
sigma.canvas.nodes.def = function(node, context, settings) {
var prefix = settings('prefix') || '';
context.fillStyle = node.color || settings('defaultNodeColor');
context.globalAlpha = node.alpha || settings('defaultNodeAlpha') || 1;
context.beginPath();
context.arc(
node[prefix + 'x'],
node[prefix + 'y'],
node[prefix + 'size'],
0,
Math.PI * 2,
true
);
context.closePath();
context.fill();
};
})();
|
;(function() {
'use strict';
sigma.utils.pkg('sigma.canvas.nodes');
/**
* The default node renderer. It renders the node as a simple disc.
*
* @param {object} node The node object.
* @param {CanvasRenderingContext2D} context The canvas context.
* @param {configurable} settings The settings function.
*/
sigma.canvas.nodes.def = function(node, context, settings) {
var prefix = settings('prefix') || '';
context.fillStyle = node.color || settings('defaultNodeColor');
context.globalAlpha = node.alpha || settings('defaultNodeAlpha') || 1;
context.beginPath();
context.arc(
node[prefix + 'x'],
node[prefix + 'y'],
node[prefix + 'size'],
0,
Math.PI * 2,
true
);
context.closePath();
context.fill();
if (node.hasBorder) {
context.beginPath();
context.strokeStyle = settings('nodeBorderColor') === 'node' ?
(node.color || settings('defaultNodeColor')) :
settings('defaultNodeBorderColor');
context.arc(
node[prefix + 'x'],
node[prefix + 'y'],
node[prefix + 'size'] + settings('borderSize'),
0,
Math.PI * 2,
true
);
context.closePath();
context.stroke();
}
};
})();
|
Add suport for node borders using hasBorder property
|
Add suport for node borders using hasBorder property
|
JavaScript
|
mit
|
wesako/sigma.js,wesako/sigma.js
|
d6f02fe1f7229548de0abf09549786cc9302a315
|
createDatabase.js
|
createDatabase.js
|
var seq = require('seq');
var args = require('yargs').argv;
var Factory = require('./lib/database/Factory');
var config = require('./lib/configuration');
var fileName = args.filename || null;
var dbOptions = config.database;
if (fileName) {
dbOptions.options.filename = fileName;
}
Factory.create(dbOptions, function(error, db) {
if (error) return console.log(error.message);
seq()
.par(function() {
db.query('create table users (id INTEGER PRIMARY KEY AUTOINCREMENT, name text, createDate datetime default current_timestamp)', [], this);
})
.par(function() {
db.query('create table transactions (id INTEGER PRIMARY KEY AUTOINCREMENT, userId INTEGER, createDate datetime default current_timestamp, value REAL)', [], this);
})
.seq(function() {
console.log('database ' + dbOptions.options.filename + ' created');
});
});
|
var seq = require('seq');
var args = require('yargs').argv;
var Factory = require('./lib/database/Factory');
var config = require('./lib/configuration');
var fileName = args.filename || null;
var dbOptions = config.database;
if (fileName) {
dbOptions.options.filename = fileName;
}
Factory.create(dbOptions, function(error, db) {
if (error) return console.log(error.message);
seq()
.par(function() {
db.query('CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, name text, createDate DATETIME DEFAULT current_timestamp)', [], this);
})
.par(function() {
db.query('CREATE TABLE transactions (id INTEGER PRIMARY KEY AUTOINCREMENT, userId INTEGER, createDate DATETIME DEFAULT current_timestamp, value REAL)', [], this);
})
.seq(function() {
db.query('CREATE INDEX userId ON transactions(userId)', [], this);
})
.seq(function() {
console.log('database ' + dbOptions.options.filename + ' created');
});
});
|
Add index on userid to transaction database
|
Add index on userid to transaction database
|
JavaScript
|
mit
|
hackerspace-bootstrap/strichliste
|
9e43aeae0f6ea5333fb41444a7722f5afbd12691
|
src/start/WelcomeScreen.js
|
src/start/WelcomeScreen.js
|
/* @flow */
import React, { PureComponent } from 'react';
import { View, StyleSheet } from 'react-native';
import connectWithActions from '../connectWithActions';
import type { Actions } from '../types';
import { Screen, ZulipButton } from '../common';
const componentStyles = StyleSheet.create({
divider: {
height: 20,
},
});
type Props = {
actions: Actions,
};
class WelcomeScreen extends PureComponent<Props> {
props: Props;
render() {
const { actions } = this.props;
return (
<Screen title="Welcome!" centerContent padding>
<ZulipButton
text="I have a Zulip account"
onPress={() => actions.navigateToAddNewAccount('')}
/>
<View style={componentStyles.divider} />
<ZulipButton text="I am new to Zulip" onPress={() => actions.navigateToWelcomeHelp()} />
</Screen>
);
}
}
export default connectWithActions()(WelcomeScreen);
|
/* @flow */
import React, { PureComponent } from 'react';
import connectWithActions from '../connectWithActions';
import type { Actions } from '../types';
import { Screen, ViewPlaceholder, ZulipButton } from '../common';
type Props = {
actions: Actions,
};
class WelcomeScreen extends PureComponent<Props> {
props: Props;
render() {
const { actions } = this.props;
return (
<Screen title="Welcome!" centerContent padding>
<ZulipButton
text="I have a Zulip account"
onPress={() => actions.navigateToAddNewAccount('')}
/>
<ViewPlaceholder height={20} />
<ZulipButton text="I am new to Zulip" onPress={() => actions.navigateToWelcomeHelp()} />
</Screen>
);
}
}
export default connectWithActions()(WelcomeScreen);
|
Use ViewPlaceholder instead of custom code
|
ui: Use ViewPlaceholder instead of custom code
Instead of using a custom View with custom styles use the
ViewPlaceholder component.
|
JavaScript
|
apache-2.0
|
vishwesh3/zulip-mobile,vishwesh3/zulip-mobile,vishwesh3/zulip-mobile,vishwesh3/zulip-mobile
|
e5afbc0d575605db7c52326e1acb1e0af3186f87
|
application/layout/app-header.js
|
application/layout/app-header.js
|
//Needed components
var Header = require('../header').component;
var Cartridge = require('../cartridge').component;
var ContentBar = require('../content-bar').component;
var Bar = require('../bar').component;
var ContentActions = require('../content-actions').component;
var applicationStore = require('focus').application.builtInStore();
module.exports = React.createClass({
displayName: 'AppHeader',
/** @inheriteddoc */
getInitialState: function getCartridgeInitialState() {
return this._getStateFromStore();
},
/** @inheriteddoc */
componentWillMount: function cartridgeWillMount() {
applicationStore.addModeChangeListener(this._handleModeChange);
},
/** @inheriteddoc */
componentWillUnMount: function cartridgeWillUnMount(){
applicationStore.removeModeChangeListener(this._handleModeChange);
},
_handleModeChange: function(){
this.setState(this._getStateFromStore());
},
_getStateFromStore: function getCartridgeStateFromStore(){
var processMode = applicationStore.getMode();
var mode = 'consult';
if(processMode && processMode.edit && processMode.edit > 0){
mode = 'edit';
}
return {mode: mode};
},
render: function renderApplicationHeader() {
return (
<Header data-focus-mode={this.state.mode}>
<ContentBar>
<Bar appName='FOCUS'/>
<Cartridge />
</ContentBar>
<ContentActions />
</Header>
);
}
});
|
//Needed components
var Header = require('../header').component;
var Cartridge = require('../cartridge').component;
var ContentBar = require('../content-bar').component;
var Bar = require('../bar').component;
var ContentActions = require('../content-actions').component;
module.exports = React.createClass({
displayName: 'AppHeader',
render: function renderApplicationHeader() {
return (
<Header>
<ContentBar>
<Bar appName='FOCUS'/>
<Cartridge />
</ContentBar>
<ContentActions />
</Header>
);
}
});
|
Remove the application mode and route
|
[layout] Remove the application mode and route
|
JavaScript
|
mit
|
JRLK/focus-components,Bernardstanislas/focus-components,Jerom138/focus-components,asimsir/focus-components,Bernardstanislas/focus-components,get-focus/focus-components,sebez/focus-components,sebez/focus-components,JRLK/focus-components,KleeGroup/focus-components,Bernardstanislas/focus-components,anisgh/focus-components,JRLK/focus-components,Ephrame/focus-components,anisgh/focus-components,asimsir/focus-components,KleeGroup/focus-components,JabX/focus-components,JabX/focus-components,Jerom138/focus-components,Ephrame/focus-components,anisgh/focus-components,Ephrame/focus-components,Jerom138/focus-components
|
04e12c573399f08472307d2654a46360dc365986
|
my-frontend/app/routes/application.js
|
my-frontend/app/routes/application.js
|
import Ember from 'ember';
import ApplicationRouteMixin from 'simple-auth/mixins/application-route-mixin';
export default Ember.Route.extend(
ApplicationRouteMixin, {
beforeModel: function () {
return this.csrf.fetchToken();
}
});
|
import Ember from 'ember';
import ApplicationRouteMixin from 'simple-auth/mixins/application-route-mixin';
export default Ember.Route.extend(
ApplicationRouteMixin, {
beforeModel: function () {
this._super.apply(this, arguments);
return this.csrf.fetchToken();
}
});
|
Call super in beforeModel hook
|
Call super in beforeModel hook
Use super to call the application routes beforeModel hook so the
ApplicationRouteMixin works.
|
JavaScript
|
unlicense
|
givanse/ember-cli-simple-auth-devise,bryanwongbh/ember-cli-simple-auth-devise,garth0323/therapy,givanse/ember-cli-simple-auth-devise,garth0323/therapy,givanse/ember-cli-simple-auth-devise,bryanwongbh/ember-cli-simple-auth-devise
|
e503dea58f44ac41fd18cbeaa634c6b373bb5b8d
|
scripts/build.js
|
scripts/build.js
|
const buildBaseCss = require(`./build/base-css.js`);
const buildBaseHtml = require(`./build/base-html.js`);
const buildPackageCss = require(`./build/package-css.js`);
const buildPackageHtml = require(`./build/package-html.js`);
const getDirectories = require(`./lib/get-directories.js`);
const packages = getDirectories(`avalanche/packages`);
const data = {
css: `<link rel="stylesheet" href="/base/css/global.css">`
};
buildBaseHtml(data);
buildBaseCss();
packages.forEach((packageName) => {
data.title = packageName;
data.css = [
`<link rel="stylesheet" href="/base/css/global.css">`,
`<link rel="stylesheet" href="/packages/${packageName}/css/index.css">`
].join(`\n`);
buildPackageHtml(packageName, data);
buildPackageCss(packageName);
});
|
const buildBaseCss = require(`./build/base-css.js`);
const buildBaseHtml = require(`./build/base-html.js`);
const buildPackageCss = require(`./build/package-css.js`);
const buildPackageHtml = require(`./build/package-html.js`);
const getDirectories = require(`./lib/get-directories.js`);
const packages = getDirectories(`avalanche/packages`);
const defaultData = {
css: `<link rel="stylesheet" href="/base/css/global.css">`
};
buildBaseHtml(defaultData);
buildBaseCss();
packages.forEach((packageName) => {
const packageData = JSON.parse(JSON.stringify(defaultData));
packageData.title = packageName;
packageData.css = [
`<link rel="stylesheet" href="/base/css/global.css">`,
`<link rel="stylesheet" href="/packages/${packageName}/css/index.css">`
].join(`\n`);
buildPackageHtml(packageName, packageData);
buildPackageCss(packageName);
});
|
Clone the default page data for every package to prevent problems with async tasks
|
Clone the default page data for every package to prevent problems with async tasks
|
JavaScript
|
mit
|
avalanchesass/avalanche-website,avalanchesass/avalanche-website
|
14f18e750480aeac369015f9e9fc25d475689b31
|
server/routes.js
|
server/routes.js
|
function calcWidth(name) {
return 225 + name.length * 6.305555555555555;
}
WebApp.connectHandlers.use("/package", function(request, response) {
var url = `https://atmospherejs.com/a/packages/findByNames\
?names=${request.url.split('/')[1]}`;
var opts = {headers: {'Accept': 'application/json'}};
HTTP.get(url, opts, function(err, res) {
var name = '', version, pubDate, starCount, installYear;
var pl = res.data[0];
if (res.data.length !== 0) {
name = pl.name;
version = pl.latestVersion.version;
pubDate = moment(pl.latestVersion.published.$date).format('MMM Do YYYY');
starCount = pl.starCount || 0;
installYear = pl['installs-per-year'] || 0;
}
SSR.compileTemplate('icon', Assets.getText('icon.svg'));
var width = calcWidth(name);
var icon = SSR.render('icon', {w: width, totalW: width+2, n: name,
v: version, p: pubDate, s: starCount, i: installYear});
response.writeHead(200, {"Content-Type": "image/svg+xml"});
response.end(icon);
});
});
|
WebApp.connectHandlers.use("/package", function(request, response) {
var url = `https://atmospherejs.com/a/packages/findByNames\
?names=${request.url.split('/')[1]}`;
var opts = {headers: {'Accept': 'application/json'}};
HTTP.get(url, opts, function(err, res) {
var name = '', version, pubDate, starCount, installYear;
var pl = res.data[0];
if (res.data.length !== 0) {
name = pl.name;
version = pl.latestVersion.version;
pubDate = moment(pl.latestVersion.published.$date).format('MMM Do YYYY');
starCount = pl.starCount || 0;
installYear = pl['installs-per-year'] || 0;
}
SSR.compileTemplate('icon', Assets.getText('icon.svg'));
var width = 225 + name.length * 6.305555555555555;
var icon = SSR.render('icon', {w: width, totalW: width+2, n: name,
v: version, p: pubDate, s: starCount, i: installYear});
response.writeHead(200, {"Content-Type": "image/svg+xml"});
response.end(icon);
});
});
|
Delete a function to save LOC
|
Delete a function to save LOC
|
JavaScript
|
mit
|
sungwoncho/meteor-icon,sungwoncho/meteor-icon
|
a8ece3a1f14c850d3eb79c0bb16532a419b91749
|
server/server.js
|
server/server.js
|
var express = require('express');
var mongoose = require('mongoose');
var app = express();
// connect to mongo database named "bolt"
// uncomment this line to use a local database
// mongoose.connect('mongodb://localhost/bolt');
mongoose.connect('mongodb://heroku_l3g4r0kp:61docmam4tnk026c51bhc5hork@ds029605.mongolab.com:29605/heroku_l3g4r0kp');
require('./config/middleware.js')(app, express);
require('./config/routes.js')(app, express);
// start listening to requests on port 8000
var port = Number(process.env.PORT || 8000);
app.listen(port, function () {
console.log(`server listening on port ${port}`);
});
// export our app for testing and flexibility, required by index.js
module.exports = app;
//test
|
var express = require('express');
var mongoose = require('mongoose');
var app = express();
// connect to mongo database named "bolt"
// uncomment this line to use a local database
// be sure to re-comment this line when submitting PR
// mongoose.connect('mongodb://localhost/bolt');
mongoose.connect('mongodb://heroku_l3g4r0kp:61docmam4tnk026c51bhc5hork@ds029605.mongolab.com:29605/heroku_l3g4r0kp');
require('./config/middleware.js')(app, express);
require('./config/routes.js')(app, express);
// start listening to requests on port 8000
var port = Number(process.env.PORT || 8000);
app.listen(port, function () {
console.log(`server listening on port ${port}`);
});
// export our app for testing and flexibility, required by index.js
module.exports = app;
//test
|
Add reccomendation comment to make sure local DB testing changes dont get pulled
|
Add reccomendation comment to make sure local DB testing changes dont get pulled
|
JavaScript
|
mit
|
gm758/Bolt,boisterousSplash/Bolt,thomasRhoffmann/Bolt,elliotaplant/Bolt,elliotaplant/Bolt,boisterousSplash/Bolt,thomasRhoffmann/Bolt,gm758/Bolt
|
72f17e16ab10d8dce678f8eacf1425d4ca8c9733
|
lib/generate.js
|
lib/generate.js
|
var fs = require('fs');
var archiver = require('./archiver');
var createServiceFile = require('./service');
var createSpecFile = require('./spec');
var files = require('./files');
function generateServiceFile(root, pkg) {
var serviceFileContents = createServiceFile(pkg);
var serviceFilePath = files.serviceFile(root, pkg);
fs.writeFileSync(serviceFilePath, serviceFileContents);
}
function generateSpecFile(root, pkg, release) {
var specFileContents = createSpecFile(pkg, release);
var specFilePath = files.specFile(root, pkg);
fs.writeFileSync(specFilePath, specFileContents);
}
function addCustomFieldsToPackage(pkg, customName) {
if (customName) {
return Object.assign({}, pkg, { name: customName });
}
return pkg;
}
module.exports = function (root, pkg, release, customName, cb) {
var customPackage = addCustomFieldsToPackage(pkg, customName);
var specsDirectory = files.specsDirectory(root);
var sourcesDirectory = files.sourcesDirectory(root);
var sourcesArchive = files.sourcesArchive(root, customPackage);
fs.mkdirSync(specsDirectory);
fs.mkdirSync(sourcesDirectory);
generateServiceFile(root, customPackage);
generateSpecFile(specsDirectory, customPackage, release);
archiver.compress(root, sourcesArchive, cb);
};
|
var _ = require('lodash');
var fs = require('fs');
var archiver = require('./archiver');
var createServiceFile = require('./service');
var createSpecFile = require('./spec');
var files = require('./files');
function generateServiceFile(root, pkg) {
var serviceFileContents = createServiceFile(pkg);
var serviceFilePath = files.serviceFile(root, pkg);
fs.writeFileSync(serviceFilePath, serviceFileContents);
}
function generateSpecFile(root, pkg, release) {
var specFileContents = createSpecFile(pkg, release);
var specFilePath = files.specFile(root, pkg);
fs.writeFileSync(specFilePath, specFileContents);
}
function addCustomFieldsToPackage(pkg, customName) {
if (customName) {
return _.extend({}, pkg, { name: customName });
}
return pkg;
}
module.exports = function (root, pkg, release, customName, cb) {
var customPackage = addCustomFieldsToPackage(pkg, customName);
var specsDirectory = files.specsDirectory(root);
var sourcesDirectory = files.sourcesDirectory(root);
var sourcesArchive = files.sourcesArchive(root, customPackage);
fs.mkdirSync(specsDirectory);
fs.mkdirSync(sourcesDirectory);
generateServiceFile(root, customPackage);
generateSpecFile(specsDirectory, customPackage, release);
archiver.compress(root, sourcesArchive, cb);
};
|
Use _.extend instead of Object.assign
|
Use _.extend instead of Object.assign
|
JavaScript
|
mit
|
Limess/speculate,Limess/speculate
|
0b094a233b79ef8b5b7e63c65d167e03ee480cff
|
background.js
|
background.js
|
window.addEventListener("load", detect, false);
document.getElementById("webMessengerRecentMessages").addEventListener('DOMNodeInserted', detect, false);
function detect(evt) {
console.log("hello");
//characters for codeblock
var start = "`~ ";
var stop = " ~`";
//main chat only. small chat splits lines into seperate elements...
var chat = document.getElementsByClassName("_38"); //what is the exact meanning of _38???
for (i = 0; i < chat.length; i++) {
text = chat[i].getElementsByTagName("p")[0];
// console.log( text );
words = chat[i].innerText
// console.log(words + "contains lol? : " + words.indexOf( "lol" ) );
var stop_index = words.indexOf(stop);
var start_index = words.indexOf(start);
if (stop_index > start_index && start_index > -1) {
text.className += " code";
text.innerText = words.substr(start_index + 3, stop_index - start_index - 3);
}
}
}
|
window.addEventListener("load", monospaceInit, false);
function monospaceInit(evt) {
detect(evt);
document.getElementById(
"webMessengerRecentMessages"
).addEventListener('DOMNodeInserted', detect, false);
}
function detect(evt) {
console.log("hello");
//characters for codeblock
var start = "`~ ";
var stop = " ~`";
//main chat only. small chat splits lines into seperate elements...
var chat = document.getElementsByClassName("_38"); //what is the exact meanning of _38???
for (i = 0; i < chat.length; i++) {
text = chat[i].getElementsByTagName("p")[0];
// console.log( text );
words = chat[i].innerText;
// console.log(words + "contains lol? : " + words.indexOf( "lol" ) );
var stop_index = words.indexOf(stop);
var start_index = words.indexOf(start);
if (stop_index > start_index && start_index > -1) {
text.className += " code";
text.innerText = words.substr(start_index + 3, stop_index - start_index - 3);
}
}
}
|
Improve performance: smaller scope, optimization
|
Improve performance: smaller scope, optimization
Change addEventListener to focus only on the large web chat in Facebook
(id = webMessengerRecentMessages). Also add this event listener only
after the entire page has loaded to prevent a flurry of runs.
Conflicts:
background.js
|
JavaScript
|
mit
|
tchen01/monospace
|
b62469ee1103dd69986570ec314be4c2473639ca
|
src/app/utils/AffiliationMap.js
|
src/app/utils/AffiliationMap.js
|
const map = {
//steemit
ned: 'steemit',
justinw: 'steemit',
elipowell: 'steemit',
vandeberg: 'steemit',
birdinc: 'steemit',
gerbino: 'steemit',
andrarchy: 'steemit',
roadscape: 'steemit',
steemitblog: 'steemit',
steemitdev: 'steemit',
/*
//steem monsters
steemmonsters: 'sm',
'steem.monsters': 'sm',
aggroed: 'sm',
yabapmatt: 'sm',
*/
};
export default map;
|
const map = {
//steemit
ned: 'steemit',
justinw: 'steemit',
elipowell: 'steemit',
vandeberg: 'steemit',
gerbino: 'steemit',
andrarchy: 'steemit',
roadscape: 'steemit',
steemitblog: 'steemit',
steemitdev: 'steemit',
/*
//steem monsters
steemmonsters: 'sm',
'steem.monsters': 'sm',
aggroed: 'sm',
yabapmatt: 'sm',
*/
};
export default map;
|
Remove birdinc from team list
|
Remove birdinc from team list
|
JavaScript
|
mit
|
steemit/steemit.com,steemit/steemit.com,TimCliff/steemit.com,TimCliff/steemit.com,TimCliff/steemit.com,steemit/steemit.com
|
bad6e9925b177bb4503a3b03d4afc996be128200
|
src/components/Weapons/index.js
|
src/components/Weapons/index.js
|
import React, { Component } from 'react';
import weapons from './weapons.json';
import './style.css';
class Weapons extends Component {
render() {
return (
<h1>Weapons</h1>
)
}
}
export default Weapons;
|
import React, { Component } from 'react';
import weapons from './weapons.json';
import './style.css';
function WeaponsItems() {
const weaponsItems = weapons.map((item) =>
<div className="content-item">
<p>{item.title}</p>
<ul>
{item.items.map((element) => <li>{element}</li>)}
</ul>
</div>
);
return (
<div className="container">{weaponsItems}</div>
);
}
class Weapons extends Component {
render() {
return (
<WeaponsItems/>
)
}
}
export default Weapons;
|
Add elements to the menu
|
wip(weapons): Add elements to the menu
|
JavaScript
|
mit
|
valsaven/dark-souls-guidebook,valsaven/dark-souls-guidebook
|
2a885f785488efcaa219e8b9c59d457360564f14
|
app/templates/src/gulpfile/tasks/optimize-criticalCss.js
|
app/templates/src/gulpfile/tasks/optimize-criticalCss.js
|
/**
* Critical CSS
* @description Generate Inline CSS for the Above the fold optimization
*/
import kc from '../../config.json'
import gulp from 'gulp'
import critical from 'critical'
import yargs from 'yargs'
const args = yargs.argv
const criticalCss = () => {
// Default Build Variable
var generateCritical = args.critical || false;
if(generateCritical) {
kc.cssabove.sources.forEach(function(item) {
return critical.generate({
inline: kc.cssabove.inline,
base: kc.dist.markup,
src: item,
dest: kc.dist.markup + item,
minify: kc.cssabove.minify,
width: kc.cssabove.width,
height: kc.cssabove.height
})
})
}
}
gulp.task('optimize:criticalCss', criticalCss)
module.exports = criticalCss
|
/**
* Critical CSS
* @description Generate Inline CSS for the Above the fold optimization
*/
import kc from '../../config.json'
import gulp from 'gulp'
import critical from 'critical'
import yargs from 'yargs'
const args = yargs.argv
const criticalCss = () => {
// Default Build Variable
var generateCritical = args.critical || false;
if(generateCritical) {
kc.cssabove.sources.forEach(function(item) {
return critical.generate({
inline: kc.cssabove.inline,
base: kc.dist.markup,
src: item,
dest: item,
minify: kc.cssabove.minify,
width: kc.cssabove.width,
height: kc.cssabove.height
})
})
}
}
gulp.task('optimize:criticalCss', criticalCss)
module.exports = criticalCss
|
Fix Critical CSS Destination Path
|
Fix Critical CSS Destination Path
|
JavaScript
|
mit
|
kittn/generator-kittn,kittn/generator-kittn,kittn/generator-kittn,kittn/generator-kittn
|
49af9443e721cf9e68ca3a17eb01d94f7084cd66
|
src/coercion/generic.js
|
src/coercion/generic.js
|
const getType = require('../typeResolver');
module.exports = {
isCoerced: function(value, typeDescriptor) {
return value instanceof getType(typeDescriptor);
},
coerce(value, typeDescriptor) {
const type = getType(typeDescriptor);
return new type(value);
}
};
|
const getType = require('../typeResolver');
module.exports = {
isCoerced(value, typeDescriptor) {
return value instanceof getType(typeDescriptor);
},
coerce(value, typeDescriptor) {
const type = getType(typeDescriptor);
return new type(value);
}
};
|
Fix eslint shorthand function assignment
|
Fix eslint shorthand function assignment
|
JavaScript
|
mit
|
talyssonoc/structure
|
66e535efbbacef95612fbcfe7c469890edc0e239
|
client/src/character-animations.js
|
client/src/character-animations.js
|
'use strict';
const
Animation = require('./animation'),
eventBus = require('./event-bus');
const
pacmanNormalColor = 0xffff00,
pacmanFrighteningColor = 0xffffff,
ghostFrightenedColor = 0x5555ff;
class CharacterAnimations {
constructor(gfx) {
this._gfx = gfx;
this._animations = [];
}
start() {
this._handlePause = () => {
for (let animation of this._animations) {
animation.pause();
}
};
eventBus.register('event.pause.begin', this._handlePause);
this._handleResume = () => {
for (let animation of this._animations) {
animation.resume();
}
};
eventBus.register('event.pause.end', this._handleResume);
}
stop() {
eventBus.unregister('event.pause.begin', this._handlePause);
eventBus.unregister('event.pause.end', this._handleResume);
}
createPacManAnimations() {
let animation = new Animation(this._gfx, pacmanNormalColor, pacmanFrighteningColor);
this._animations.push(animation);
return animation;
}
createGhostAnimations(ghostNormalColor) {
let animation = new Animation(this._gfx, ghostNormalColor, ghostFrightenedColor);
this._animations.push(animation);
return animation;
}
}
module.exports = CharacterAnimations;
|
'use strict';
const
Animation = require('./animation'),
eventBus = require('./event-bus');
const
pacmanNormalColor = 0xffff00,
pacmanFrighteningColor = 0xffffff,
ghostFrightenedColor = 0x5555ff;
class CharacterAnimations {
constructor(gfx) {
this._gfx = gfx;
this._animations = [];
this._handlePause = () => {
for (let animation of this._animations) {
animation.pause();
}
};
this._handleResume = () => {
for (let animation of this._animations) {
animation.resume();
}
};
}
start() {
eventBus.register('event.pause.begin', this._handlePause);
eventBus.register('event.pause.end', this._handleResume);
}
stop() {
eventBus.unregister('event.pause.begin', this._handlePause);
eventBus.unregister('event.pause.end', this._handleResume);
}
createPacManAnimations() {
let animation = new Animation(this._gfx, pacmanNormalColor, pacmanFrighteningColor);
this._animations.push(animation);
return animation;
}
createGhostAnimations(ghostNormalColor) {
let animation = new Animation(this._gfx, ghostNormalColor, ghostFrightenedColor);
this._animations.push(animation);
return animation;
}
}
module.exports = CharacterAnimations;
|
Refactor private variable declaration to constructor
|
Refactor private variable declaration to constructor
|
JavaScript
|
mit
|
hiddenwaffle/mazing,hiddenwaffle/mazing
|
6cac446d118154a2e9939f32e7f2d2ef628db82b
|
server/index.js
|
server/index.js
|
// To use it create some files under `routes/`
// e.g. `server/routes/ember-hamsters.js`
//
// module.exports = function(app) {
// app.get('/ember-hamsters', function(req, res) {
// res.send('hello');
// });
// };
module.exports = function(app) {
var globSync = require('glob').sync;
var bodyParser = require('body-parser');
var mocks = globSync('./mocks/**/*.js', { cwd: __dirname }).map(require);
var proxies = globSync('./proxies/**/*.js', { cwd: __dirname }).map(require);
var cors = require('cors');
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
// Uncomment to log proxy requests
// var morgan = require('morgan');
// app.use(morgan('dev'));
mocks.forEach(function(route) { route(app); });
proxies.forEach(function(route) { route(app); });
};
|
// To use it create some files under `routes/`
// e.g. `server/routes/ember-hamsters.js`
//
// module.exports = function(app) {
// app.get('/ember-hamsters', function(req, res) {
// res.send('hello');
// });
// };
module.exports = function(app) {
var globSync = require('glob').sync;
var bodyParser = require('body-parser');
var mocks = globSync('./mocks/**/*.js', { cwd: __dirname }).map(require);
var proxies = globSync('./proxies/**/*.js', { cwd: __dirname }).map(require);
var cors = require('cors');
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(function(req,res,next){
setTimeout(next,1000);
});
// Uncomment to log proxy requests
// var morgan = require('morgan');
// app.use(morgan('dev'));
mocks.forEach(function(route) { route(app); });
proxies.forEach(function(route) { route(app); });
};
|
Add some delay to the dev api to better represent reality
|
Add some delay to the dev api to better represent reality
|
JavaScript
|
mit
|
jrjohnson/frontend,gboushey/frontend,ilios/frontend,stopfstedt/frontend,thecoolestguy/frontend,stopfstedt/frontend,djvoa12/frontend,dartajax/frontend,dartajax/frontend,gabycampagna/frontend,djvoa12/frontend,gboushey/frontend,gabycampagna/frontend,ilios/frontend,thecoolestguy/frontend,jrjohnson/frontend
|
14620efc5cea0749966d218989592246001a3ab1
|
app/soc/content/js.min/templates/modules/gsoc/_survey.js
|
app/soc/content/js.min/templates/modules/gsoc/_survey.js
|
(function(){melange.template.survey=function(){};melange.template.survey.prototype=new melange.templates._baseTemplate;melange.template.survey.prototype.constructor=melange.template.survey;melange.template.survey.apply(melange.template.survey,[melange.template.survey,melange.template.survey.prototype.context])})();
|
melange.templates.inherit(function(){});
|
Add minimized version of updated script.
|
Add minimized version of updated script.
|
JavaScript
|
apache-2.0
|
rhyolight/nupic.son,rhyolight/nupic.son,rhyolight/nupic.son
|
f26332123823f9295f50ec62899583c4931e3274
|
src/javascript/app_2/App/app.js
|
src/javascript/app_2/App/app.js
|
import { configure } from 'mobx';
import React from 'react';
import { render } from 'react-dom';
import Client from '_common/base/client_base';
import NetworkMonitor from 'Services/network_monitor';
import RootStore from 'Stores';
import { setStorageEvents } from 'Utils/Events/storage';
import App from './app.jsx';
configure({ enforceActions: true });
const initApp = () => {
Client.init();
setStorageEvents();
const root_store = new RootStore();
NetworkMonitor.init(root_store);
root_store.modules.trade.init();
const app = document.getElementById('binary_app');
if (app) {
render(<App root_store={root_store} />, app);
}
};
export default initApp;
|
import { configure } from 'mobx';
import React from 'react';
import { render } from 'react-dom';
import Client from '_common/base/client_base';
import BinarySocket from '_common/base/socket_base';
import NetworkMonitor from 'Services/network_monitor';
import RootStore from 'Stores';
import { setStorageEvents } from 'Utils/Events/storage';
import App from './app.jsx';
configure({ enforceActions: true });
const initApp = () => {
Client.init();
setStorageEvents();
const root_store = new RootStore();
NetworkMonitor.init(root_store);
BinarySocket.wait('authorize').then(() => {
root_store.modules.trade.init();
const app = document.getElementById('binary_app');
if (app) {
render(<App root_store={root_store} />, app);
}
});
};
export default initApp;
|
Add a wait to get authorize response before initial trade page
|
Add a wait to get authorize response before initial trade page
|
JavaScript
|
apache-2.0
|
4p00rv/binary-static,ashkanx/binary-static,binary-com/binary-static,ashkanx/binary-static,kellybinary/binary-static,binary-com/binary-static,4p00rv/binary-static,kellybinary/binary-static,binary-com/binary-static,binary-static-deployed/binary-static,ashkanx/binary-static,binary-static-deployed/binary-static,kellybinary/binary-static,binary-static-deployed/binary-static,4p00rv/binary-static
|
18dbcfa13ba598b97b3396f90bef0833954eb5bb
|
src/Rectangle.js
|
src/Rectangle.js
|
import Shape from 'kittik-shape-basic';
/**
* Implements rectangle shape with text support.
*
* @since 1.0.0
* @version 1.0.0
*/
export default class Rectangle extends Shape {
render(cursor) {
let text = this.getText();
let width = this.getWidth();
let height = this.getHeight();
let x1 = this.getX();
let y1 = this.getY();
let x2 = x1 + width - 1;
let y2 = y1 + height - 1;
let background = this.getBackground();
let foreground = this.getForeground();
let filler = ' '.repeat(width);
if (typeof background !== 'undefined') cursor.background(background);
if (typeof foreground !== 'undefined') cursor.foreground(foreground);
cursor.moveTo(x1, y1);
while (y1 <= y2) {
cursor.write(filler);
cursor.moveTo(x1, ++y1);
}
cursor.moveTo(x1 + (width / 2 - text.length / 2), this.getY() + (height / 2)).write(text);
return this;
}
}
|
import Shape from 'kittik-shape-basic';
/**
* Implements rectangle shape with text support.
*
* @since 1.0.0
* @version 1.0.0
*/
export default class Rectangle extends Shape {
render(cursor) {
let text = this.getText();
let width = this.getWidth();
let height = this.getHeight();
let x1 = this.getX();
let y1 = this.getY();
let x2 = x1 + width;
let y2 = y1 + height;
let background = this.getBackground();
let foreground = this.getForeground();
let filler = ' '.repeat(width);
if (typeof background !== 'undefined') cursor.background(background);
if (typeof foreground !== 'undefined') cursor.foreground(foreground);
cursor.moveTo(x1, y1);
for (let y = y1; y <= y2; y++) {
cursor.write(filler);
cursor.moveTo(x1, y);
}
cursor.moveTo(x1 + (width / 2 - text.length / 2), y1 + (height / 2)).write(text);
return this;
}
}
|
Simplify logic where calculates coordinates
|
fix(shape): Simplify logic where calculates coordinates
|
JavaScript
|
mit
|
kittikjs/shape-rectangle
|
225b84d3d19c7d4129c13fb7f18c3dd908fefa08
|
constants/data.js
|
constants/data.js
|
export const GAMES = {
'board1': {
'words': ['one', 'two', 'three'],
'board': [
['o', 'n', 'e', '-', '-', '-'],
['t', 'w', 'o', '-', '-', '-'],
['t', 'h', 'r', 'e', 'e', '-'],
['-', '-', '-', '-', '-', '-'],
['-', '-', '-', '-', '-', '-'],
['-', '-', '-', '-', '-', '-']
]
},
'board2': {
'words': ['four', 'five', 'six'],
board: [
['f', 'o', 'u', 'r', '-', '-'],
['f', 'i', 'v', 'e', '-', '-'],
['s', 'i', 'x', '-', '-', '-'],
['-', '-', '-', '-', '-', '-'],
['-', '-', '-', '-', '-', '-'],
['-', '-', '-', '-', '-', '-']
]
}
};
|
export const GAMES = {
'wordSet1': {
'words': ['one', 'two', 'three', 'four','five','six','seven','eight','nine','ten'],
'board': [
['o', 'n', 'e', '-', '-', '-'],
['t', 'w', 'o', '-', '-', '-'],
['t', 'h', 'r', 'e', 'e', '-'],
['-', '-', '-', '-', '-', '-'],
['-', '-', '-', '-', '-', '-'],
['-', '-', '-', '-', '-', '-']
]
},
'wordSet2': {
'words': ['four', 'five', 'six'],
board: [
['f', 'o', 'u', 'r', '-', '-'],
['f', 'i', 'v', 'e', '-', '-'],
['s', 'i', 'x', '-', '-', '-'],
['-', '-', '-', '-', '-', '-'],
['-', '-', '-', '-', '-', '-'],
['-', '-', '-', '-', '-', '-']
]
},
'wordSet3': {
'words': ['seven', 'eight', 'nine'],
board: [
['s', 'e', 'n', '-', '-', '-'],
['e', 'i', 'i', '-', '-', '-'],
['v', 'g', 'n', '-', '-', '-'],
['e', 'h', 'e', '-', '-', '-'],
['n', 't', '-', '-', '-', '-'],
['-', '-', '-', '-', '-', '-']
]
}
};
|
Refactor of bard identifier names
|
Refactor of bard identifier names
|
JavaScript
|
apache-2.0
|
paulbevis/wordsearch,paulbevis/wordsearch
|
85b7bf880a8ecccdd8c732f79fea73db403d237a
|
src/Reporter.js
|
src/Reporter.js
|
const Report = require('./Report');
const Hipchat = require('./Hipchat');
function Reporter( request, reply ) {
console.log(request.query);
return reply({});
}
module.exports = Reporter;
|
const Report = require('./Report');
const Notification = require('./Notification');
async function Reporter( request, reply ) {
const result = await new Report({
k: process.env.WEB_PAGE_TEST_KEY || '',
url: request.query.site,
}).run();
// Set error as default.
let notificationOptions = {
status: 'Error',
description: `There was an error proccesing ${request.query.site}`,
room: request.query.hipchat,
url: request.query.site,
}
// Update notificationOptions if was a success
if ( 'statusCode' in result && result.statusCode === 200 ) {
notificationOptions = Object.assign({}, notificationOptions, {
status: 'Started',
description: 'Your web page performance test has started.',
url: result.data.userUrl,
});
}
const notificationResult = await Notification(notificationOptions);
return reply(notificationResult);
}
module.exports = Reporter;
|
Add reporter and notifications setup
|
Add reporter and notifications setup
|
JavaScript
|
mit
|
wearenolte/lighthouse-reporter
|
a389a4e8807cabced1a08e4ee3c6798dd4e34ea9
|
memory-store.js
|
memory-store.js
|
var SortedArray = require('sorted-array')
var compareTime = require('./compare-time')
function compareCreated (a, b) {
return compareTime(b[1].created, a[1].created)
}
function compareAdded (a, b) {
return b[1].added - a[1].added
}
/**
* Simpliest memory-based events store.
*
* It is good for tests, but not for server or client usage,
* because it doesn’t save events to file or localStorage.
*
* @example
* import { MemoryStore } from 'logux-core'
*
* var log = new Log({
* store: new MemoryStore(),
* timer: createTestTimer()
* })
*
* @class
*/
function MemoryStore () {
this.created = new SortedArray([], compareCreated)
this.added = new SortedArray([], compareAdded)
}
MemoryStore.prototype = {
get: function get (order) {
var data = order === 'added' ? this.added : this.created
return Promise.resolve({ data: data.array })
},
add: function add (entry) {
this.created.insert(entry)
this.added.insert(entry)
},
remove: function remove (entry) {
this.created.remove(entry)
this.added.remove(entry)
}
}
module.exports = MemoryStore
|
var SortedArray = require('sorted-array')
var compareTime = require('./compare-time')
function compareCreated (a, b) {
return compareTime(b[1].created, a[1].created)
}
/**
* Simpliest memory-based events store.
*
* It is good for tests, but not for server or client usage,
* because it doesn’t save events to file or localStorage.
*
* @example
* import { MemoryStore } from 'logux-core'
*
* var log = new Log({
* store: new MemoryStore(),
* timer: createTestTimer()
* })
*
* @class
*/
function MemoryStore () {
this.created = new SortedArray([], compareCreated)
this.added = []
}
MemoryStore.prototype = {
get: function get (order) {
if (order === 'added') {
return Promise.resolve({ data: this.added })
} else {
return Promise.resolve({ data: this.created.array })
}
},
add: function add (entry) {
this.created.insert(entry)
this.added.unshift(entry)
},
remove: function remove (entry) {
this.created.remove(entry)
for (var i = this.added.length - 1; i >= 0; i--) {
if (compareTime(this.added[i][1].created, entry[1].created) === 0) {
this.added.splice(i, 1)
break
}
}
}
}
module.exports = MemoryStore
|
Use simple array for added index in MemoryStore
|
Use simple array for added index in MemoryStore
|
JavaScript
|
mit
|
logux/logux-core
|
c122d6e2a45c90212a2197da2359fdf2bfc5066e
|
index.js
|
index.js
|
'use strict';
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const morgan = require('morgan');
const port = 8080;
const router = express.Router();
const routes = require('./routes');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Use morgan to diplay requests from the client
app.use(morgan('dev'));
// Implement the routes
routes(router);
app.use('/api', router);
app.listen(port, function(){
console.log(`Server started on port ${port}`);
});
module.exports = app;
|
'use strict';
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const morgan = require('morgan');
const port = process.env.PORT || 8080;
const router = express.Router();
const routes = require('./routes');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Use morgan to diplay requests from the client
app.use(morgan('dev'));
// Implement the routes
routes(router);
app.use('/api', router);
app.listen(port, function(){
console.log(`Server started on port ${port}`);
});
module.exports = app;
|
Add the ability for the port to be set by environment variables
|
Add the ability for the port to be set by environment variables
|
JavaScript
|
mit
|
andela-oolutola/document-management-system-api
|
da68f92fdbc2d4512b01ac5985f3d221bcd4a6bb
|
index.js
|
index.js
|
module.exports = {
extends: 'stylelint-config-standard',
plugins: ['stylelint-order', 'stylelint-scss'],
rules: {
'at-rule-empty-line-before': [
'always',
{
except: ['inside-block', 'blockless-after-blockless', 'first-nested'],
ignore: ['after-comment']
}
],
'at-rule-no-unknown': [
true,
{
ignoreAtRules: ['extend', 'content', 'if', 'else', 'mixin', 'function', 'return']
}
],
'block-closing-brace-newline-after': [
'always',
{
ignoreAtRules: ['extend', 'content', 'if', 'else', 'mixin', 'function', 'return']
}
],
'color-hex-case': ['lower', { severity: 'warning' }],
indentation: 4,
'order/order': ['custom-properties', 'declarations'],
'order/properties-alphabetical-order': true,
'number-leading-zero': 'never',
'selector-list-comma-newline-after': null,
'scss/at-rule-no-unknown': true
}
};
|
module.exports = {
extends: 'stylelint-config-standard',
plugins: ['stylelint-order', 'stylelint-scss'],
rules: {
'at-rule-empty-line-before': [
'always',
{
except: ['inside-block', 'blockless-after-blockless', 'first-nested'],
ignore: ['after-comment']
}
],
'at-rule-no-unknown': [
true,
{
ignoreAtRules: ['extend', 'content', 'if', 'else', 'mixin', 'function', 'return', 'include']
}
],
'block-closing-brace-newline-after': [
'always',
{
ignoreAtRules: ['extend', 'content', 'if', 'else', 'mixin', 'function', 'return', 'include']
}
],
'color-hex-case': ['lower', { severity: 'warning' }],
indentation: 4,
'order/order': ['custom-properties', 'declarations'],
'order/properties-alphabetical-order': true,
'number-leading-zero': 'never',
'selector-list-comma-newline-after': null,
'scss/at-rule-no-unknown': true
}
};
|
Add include to be ignored
|
Add include to be ignored
|
JavaScript
|
mit
|
italodr/stylelint-config-runroom
|
b09e4ffc14571cd9679800f1ba02cc7bc728e687
|
index.js
|
index.js
|
'use strict';
var isStream = require('is-stream');
var matchCondition = require('match-condition');
var peekStream = require('peek-stream');
var through = require('through2');
module.exports = function (condition, stream, fn, opts) {
opts = opts || {};
if (fn && !isStream(fn) && typeof fn !== 'function') {
opts = fn;
}
var peek = peekStream(opts, function (data, swap) {
if (!matchCondition(data, condition) && !isStream(fn) && typeof fn !== 'function') {
swap(null, through());
return;
}
if (!matchCondition(data, condition)) {
swap(null, typeof fn === 'function' ? fn() : fn);
return;
}
swap(null, stream());
});
return peek;
};
|
'use strict';
var isStream = require('is-stream');
var matchCondition = require('match-condition');
var peekStream = require('peek-stream');
var through = require('through2');
module.exports = function (condition, stream, fn, opts) {
opts = opts || {};
if (fn && !isStream(fn) && typeof fn !== 'function') {
opts = fn;
}
var peek = peekStream(opts, function (data, swap) {
if (!matchCondition(data, condition) && !isStream(fn) && typeof fn !== 'function') {
swap(null, through());
return;
}
if (!matchCondition(data, condition)) {
swap(null, typeof fn === 'function' ? fn() : fn);
return;
}
swap(null, typeof stream === 'function' ? stream() : stream);
});
return peek;
};
|
Check if `stream` is a function
|
Check if `stream` is a function
|
JavaScript
|
mit
|
kevva/if-stream
|
b1e3a3c32000690495bacc4d11189b15aa740932
|
client/app.js
|
client/app.js
|
(function() {
'use strict';
angular
.module('weatherApp', ['ngRoute'])
.config(config);
function config($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'components/home/home.view.html',
controller: 'HomeCtrl',
controllerAs: 'vm'
})
.when('/forecast', {
templateUrl: 'components/forecast/forecast.view.html',
controller: 'ForecastCtrl',
controllerAs: 'vm'
})
.when('/forecast/:days', {
templateUrl: 'components/forecast/forecast.view.html',
controller: 'ForecastCtrl',
controllerAs: 'vm'
})
.otherwise({redirectTo: '/'});
}
})();
|
(function() {
'use strict';
angular
.module('weatherApp', ['ngRoute'])
.config(['$routeProvider'], config);
function config($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'components/home/home.view.html',
controller: 'HomeCtrl',
controllerAs: 'vm'
})
.when('/forecast', {
templateUrl: 'components/forecast/forecast.view.html',
controller: 'ForecastCtrl',
controllerAs: 'vm'
})
.when('/forecast/:days', {
templateUrl: 'components/forecast/forecast.view.html',
controller: 'ForecastCtrl',
controllerAs: 'vm'
})
.otherwise({redirectTo: '/'});
}
})();
|
Add inline annotation to config
|
Add inline annotation to config
|
JavaScript
|
mit
|
cpanz/Angular_Weather,cpanz/Angular_Weather
|
60e2a7db670003f8f49b786a69be0b16992993a6
|
example/simple.js
|
example/simple.js
|
var zmqbus = require('../lib/index.js');
/* simple quote sender/reader.
Run multiple processes to send/receive cluster-wide.
*/
var node = zmqbus.createNode();
node.on('ready', function() {
// subscribe to equity channel
node.subscribe("equity");
setInterval(fakeEquityQuote, 1000);
// uncomment the following to receive temperature readings
// node.subscribe("temp")
setInterval(fakeTemperatureQuote, 2000);
});
node.on('message', function(msg) {
console.log("received " + msg);
});
function fakeEquityQuote() {
// broadcast some fake stock quotes
var stocks = ['AAPL', 'GOOG', 'IBM', 'FB'];
var symbol = stocks[Math.floor(Math.random() * stocks.length)];
var quote = (Math.random() * 100.0 + 25.0).toFixed(2);
node.publish('equity', symbol, quote);
}
function fakeTemperatureQuote() {
// broadcast some fake stock quotes
var cities = ['New York, NY', 'San Francisco, CA', 'Chicago, IL'];
var city = cities[Math.floor(Math.random() * cities.length)];
var quote = (Math.random() * 50.0 + 30.0).toFixed(2);
node.publish('temp', city, quote);
}
|
var zmqbus = require('zmqbus');
/* simple quote sender/reader.
Run multiple processes to send/receive cluster-wide.
*/
var node = zmqbus.createNode();
node.on('ready', function() {
// subscribe to equity channel
node.subscribe("equity");
setInterval(fakeEquityQuote, 1000);
// uncomment the following to receive temperature readings
// node.subscribe("temp")
setInterval(fakeTemperatureQuote, 2000);
});
node.on('message', function(msg) {
console.log("received " + msg);
});
function fakeEquityQuote() {
// broadcast some fake stock quotes
var stocks = ['AAPL', 'GOOG', 'IBM', 'FB'];
var symbol = stocks[Math.floor(Math.random() * stocks.length)];
var quote = (Math.random() * 100.0 + 25.0).toFixed(2);
node.publish('equity', symbol, quote);
}
function fakeTemperatureQuote() {
// broadcast some fake stock quotes
var cities = ['New York, NY', 'San Francisco, CA', 'Chicago, IL'];
var city = cities[Math.floor(Math.random() * cities.length)];
var quote = (Math.random() * 50.0 + 30.0).toFixed(2);
node.publish('temp', city, quote);
}
|
Fix example to use the right module name
|
Fix example to use the right module name
|
JavaScript
|
mit
|
edwardchoh/zmqbus-node
|
f9df796731fe97fb1c9d6487a25b3dee6a9c7524
|
server/server.js
|
server/server.js
|
'use strict';
const express = require('express');
// Constants
const PORT = 8080;
// App
const app = express();
app.get('/', function (req, res) {
res.send('Hello world\n');
});
app.listen(PORT);
console.log('Running on http://localhost:' + PORT);
|
require('dotenv').config();
const bodyParser = require('body-parser');
const metadata = require('../package.json');
const compression = require('compression');
const express = require('express');
const path = require('path');
const redis = require('redis');
const sharp = require('sharp');
const utils = require('./lib/utilities.js');
const bcrypt = require('bcrypt-nodejs');
const session = require('express-session');
const userController = require('../db/controllers/users.js');
const bookmarkController = require('../db/controllers/bookmarks.js');
const photoController = require('../db/controllers/photos.js');
const likeController = require('../db/controllers/likes.js');
const commentController = require('../db/controllers/comments.js');
const port = process.env.NODE_PORT;
const secret = process.env.SESSION_SECRET;
const AWSaccessKey = process.env.ACCESSKEYID;
const AWSsecretKey = process.env.SECRETACCESSKEY;
// const redisClient = redis.createClient();
const app = express();
app.use(bodyParser.json({limit: '40mb'}));
app.use(compression()); // gzip compress all responses
app.use(session({
secret: secret,
resave: false,
saveUninitialized: true
}));
const routes = ['/'];
for (const route of routes) {
app.get(route, (req, res) => {
if (route === '/') {
res.redirect('/dashboard');
} else {
res.sendFile(path.join(__dirname, '/../client/index.html'));
}
});
}
app.use(express.static(path.join(__dirname, '../client')));
// wildcard route
app.get('*', function(req, res) {
res.status(404).send('Not Found');
});
app.listen(port, () => {
console.log(`🌎 Listening on port ${port} for app ${metadata.name} 🌏`);
});
|
Add npm modules and set up middleware
|
Add npm modules and set up middleware
|
JavaScript
|
mit
|
francoabaroa/happi,francoabaroa/happi
|
e8306057a65889f384caa24933c71f8c8ec71854
|
src/server/boot/root.js
|
src/server/boot/root.js
|
module.exports = function(server) {
// Install a `/` route that returns server status
var router = server.loopback.Router();
router.get('/', server.loopback.status());
server.use(router);
};
|
module.exports = function(server) {
// Install a `/` route that returns server status
var router = server.loopback.Router();
//router.get('/', server.loopback.status()); // loopback default router, change it to do production work
router.get('/', function(req, res) {
res.sendfile('client/public/index.html');
});
server.use(router);
};
|
Change default action of path '/', send index.html file.
|
Change default action of path '/', send index.html file.
|
JavaScript
|
mit
|
agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart
|
49c652b034e8f2c9238282c67e0c3394e6165382
|
public/javascripts/pages/index.js
|
public/javascripts/pages/index.js
|
function proceedSignin() {
'use strict';
event.preventDefault();
var emailField = document.getElementById('email'),
passwordField = document.getElementById('password');
var user = {
username: emailField.value,
password: passwordField.value
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (this.status === 200) {
window.location = '/rooms';
}
if (this.status === 401) {
document.getElementById('signin-message').innerHTML = 'Le mot de passe ou le pseudonyme est incorrect. <br /> Avez-vous confirmé votre inscription ?';
}
}
};
xhr.open('POST', '/signin', true);
xhr.setRequestHeader('content-type', 'application/json; charset=utf-8');
xhr.send(JSON.stringify(user));
}
document.addEventListener('DOMContentLoaded', function () {
'use strict';
var signinSubmit = document.getElementById('signin-submit');
signinSubmit.addEventListener('click', proceedSignin, false);
}, false);
|
function proceedSignin() {
'use strict';
event.preventDefault();
var emailField = document.getElementById('email'),
passwordField = document.getElementById('password');
var user = {
username: emailField.value,
password: passwordField.value
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (this.status === 200) {
window.location = '/rooms';
}
if (this.status === 401) {
document.getElementById('signin-message').innerHTML = 'Le mot de passe ou le pseudonyme est incorrect. <br /> Avez-vous confirmé votre inscription ?';
}
}
};
xhr.open('POST', '/signin', true);
xhr.setRequestHeader('content-type', 'application/json; charset=utf-8');
xhr.setRequestHeader('x-requested-with', 'XMLHttpRequest');
xhr.send(JSON.stringify(user));
}
document.addEventListener('DOMContentLoaded', function () {
'use strict';
var signinSubmit = document.getElementById('signin-submit');
signinSubmit.addEventListener('click', proceedSignin, false);
}, false);
|
Add parameters to /signin (POST) request header
|
Add parameters to /signin (POST) request header
|
JavaScript
|
mit
|
sea-battle/sea-battle,sea-battle/sea-battle
|
859dbe0e2bc5a322633f7323b1ff9fe638624c9f
|
app/assets/javascripts/remote_consoles/vnc.js
|
app/assets/javascripts/remote_consoles/vnc.js
|
//= require jquery
//= require novnc-rails
//= require_tree ../locale
//= require gettext/all
$(function() {
var host = window.location.hostname;
var encrypt = window.location.protocol === 'https:';
var port = encrypt ? 443 : 80;
if (window.location.port) {
port = window.location.port;
}
// noVNC requires an empty canvas item
var canvas = document.createElement('canvas');
$('#remote-console').append(canvas);
var vnc = new RFB({
target: canvas,
encrypt: encrypt,
true_color: true,
local_cursor: true,
shared: true,
view_only: false,
onUpdateState: function(_, state, _, msg) {
if (['normal', 'loaded'].indexOf(state) >= 0) {
$('#connection-status').removeClass('label-danger label-warning').addClass('label-success');
$('#connection-status').text(__('Connected'));
} else if (state === 'disconnected') {
$('#connection-status').removeClass('label-success label-warning').addClass('label-danger');
$('#connection-status').text(__('Disconnected'));
console.error('VNC', msg);
}
},
});
$('#ctrlaltdel').click(vnc.sendCtrlAltDel);
vnc.connect(host, port, $('#remote-console').attr('data-secret'), $('#remote-console').attr('data-url'));
});
|
//= require jquery
//= require novnc-rails
//= require_tree ../locale
//= require gettext/all
$(function() {
var host = window.location.hostname;
var encrypt = window.location.protocol === 'https:';
var port = encrypt ? 443 : 80;
if (window.location.port) {
port = window.location.port;
}
// noVNC requires an empty canvas item
var canvas = document.createElement('canvas');
$('#remote-console').append(canvas);
var vnc = new RFB({
target: canvas,
encrypt: encrypt,
true_color: true,
local_cursor: true,
shared: true,
view_only: false,
onUpdateState: function(_, state, _, msg) {
if (['normal', 'loaded'].indexOf(state) >= 0) {
$('#connection-status').removeClass('label-danger label-warning').addClass('label-success');
$('#connection-status').text(__('Connected'));
} else if (state === 'disconnected') {
$('#connection-status').removeClass('label-success label-warning').addClass('label-danger');
$('#connection-status').text(__('Disconnected'));
console.error('VNC', msg);
}
},
});
vnc.connect(host, port, $('#remote-console').attr('data-secret'), $('#remote-console').attr('data-url'));
$('#ctrlaltdel').on('click', function(){
vnc.sendCtrlAltDel();
});
});
|
Fix VNC console connection to Windows VMs and Ctrl-Alt-Del button
|
Fix VNC console connection to Windows VMs and Ctrl-Alt-Del button
https://bugzilla.redhat.com/show_bug.cgi?id=1464152
|
JavaScript
|
apache-2.0
|
ManageIQ/manageiq-ui-classic,ManageIQ/manageiq-ui-classic,ManageIQ/manageiq-ui-classic,ManageIQ/manageiq-ui-classic
|
0a46deb294a7c093997a4cf2d4d7188e9ef02424
|
sources/openfisca.js
|
sources/openfisca.js
|
<openfisca>
<p>la variable
<input required type="text" name="query" placeholder="al.R1.taux1" value={ opts.value } onchange={ getDescription }>
dans Openfisca ({ description })</p>
<script>
getDescription() {
var url = 'http://api.openfisca.fr/api/1/parameters?name=' + this.query.value;
fetch(url)
.then(function(response) { return response.json() })
.then(function(json) {
this.description = json.parameters[0].description;
this.root.value = url;
this.update();
}.bind(this), console.error.bind(console));
}
</script>
</openfisca>
|
<openfisca>
<p>la variable
<input required type="text" name="query" placeholder="nb_pac" value={ opts.value } onchange={ getDescription }>
dans Openfisca ({ description })</p>
<script>
getDescription() {
var url = 'http://api.openfisca.fr/api/1/variables?name=' + this.query.value;
fetch(url)
.then(function(response) { return response.json() })
.then(function(json) {
this.description = json.variables[0].label;
this.root.value = url;
this.update();
}.bind(this), console.error.bind(console));
}
</script>
</openfisca>
|
Use variables instead of params
|
Use variables instead of params
|
JavaScript
|
agpl-3.0
|
MattiSG/alignements-loi,MattiSG/alignements-loi
|
a0abf6b63572189fe3e3c06cf6c89e621958cb40
|
app/reducers/frontpage.js
|
app/reducers/frontpage.js
|
import moment from 'moment-timezone';
import { Frontpage } from 'app/actions/ActionTypes';
import { fetching } from 'app/utils/createEntityReducer';
import { sortBy } from 'lodash';
import { createSelector } from 'reselect';
import { selectArticles } from './articles';
import { selectEvents } from './events';
export default fetching(Frontpage.FETCH);
export const selectFrontpage = createSelector(
selectArticles,
selectEvents,
(articles, events) => {
articles = articles.map(article => ({
...article,
documentType: 'article'
}));
events = events.map(event => ({ ...event, documentType: 'event' }));
return sortBy(articles.concat(events), [
// Always sort pinned items first:
item => !item.pinned,
item => {
// For events we care about when the event starts, whereas for articles
// we look at when it was written:
const timeField = item.eventType ? item.startTime : item.createdAt;
return Math.abs(moment().diff(timeField));
},
item => item.id
]);
}
);
|
import moment from 'moment-timezone';
import { Frontpage } from 'app/actions/ActionTypes';
import { fetching } from 'app/utils/createEntityReducer';
import { sortBy } from 'lodash';
import { createSelector } from 'reselect';
import { selectArticles } from './articles';
import { selectEvents } from './events';
export default fetching(Frontpage.FETCH);
export const selectFrontpage = createSelector(
selectArticles,
selectEvents,
(articles, events) => {
articles = articles.map(article => ({
...article,
documentType: 'article'
}));
events = events.map(event => ({ ...event, documentType: 'event' }));
const now = moment();
return sortBy(articles.concat(events), [
// Always sort pinned items first:
item => !item.pinned,
item => {
// For events we care about when the event starts, whereas for articles
// we look at when it was written:
const timeField = item.eventType ? item.startTime : item.createdAt;
return Math.abs(now.diff(timeField));
},
item => item.id
]);
}
);
|
Make event sorting stable and deterministic
|
Make event sorting stable and deterministic
|
JavaScript
|
mit
|
webkom/lego-webapp,webkom/lego-webapp,webkom/lego-webapp
|
4b09a703eecc3f5517dc70e51ee7abf8100fee87
|
src/util/update-notification.js
|
src/util/update-notification.js
|
const updateNotification = () => {
document.addEventListener('DOMContentLoaded', () => {
if (Notification.permission !== 'granted') {
Notification.requestPermission()
}
})
if (!Notification) {
alert(
'Desktop notifications not available in your browser. Try Chromium.',
)
return
}
if (Notification.permission !== 'granted') {
Notification.requestPermission()
} else {
const notification = new Notification('NEW FEATURE: Tagging', {
icon: '/img/worldbrain-logo-narrow.png',
body: 'Click for more Information',
})
notification.onclick = () => {
window.open('https://worldbrain.helprace.com/i34-feature-tagging')
}
}
}
export default updateNotification
|
const updateNotification = () => {
browser.notifications.create({
type: 'basic',
title: 'NEW FEATURE: Tagging',
iconUrl: '/img/worldbrain-logo-narrow.png',
message: 'Click for more Information',
buttons: [{ title: 'Click for more Information' }],
})
browser.notifications.onButtonClicked.addListener((id, index) => {
browser.notifications.clear(id)
window.open('https://worldbrain.helprace.com/i34-feature-tagging')
})
}
export default updateNotification
|
Change Notification API when extension updated
|
Change Notification API when extension updated
|
JavaScript
|
mit
|
WorldBrain/WebMemex,WorldBrain/WebMemex
|
8906ef023343ac92cdb7eb0b2835acf1d06fbef2
|
bin/extract_references.js
|
bin/extract_references.js
|
#!/usr/bin/env node
var readline = require('readline');
var bcv_parser = require('bible-passage-reference-parser/js/tr_bcv_parser').bcv_parser;
var bcv = new bcv_parser();
bcv.set_options({
'sequence_combination_strategy': 'separate'
});
bcv.include_apocrypha(true);
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
});
var references = [];
function extract_references (data) {
var res = bcv.parse(data).osis_and_indices();
res.forEach(function(match) {
var ref = {};
ref.original = data.slice(match.indices[0], match.indices[1]);
ref.osis = match.osis;
references.push(ref);
});
}
function output_references () {
var output = JSON.stringify(references, null, ' ');
process.stdout.write(output);
}
rl.on('line', extract_references);
rl.on('close', output_references);
|
#!/usr/bin/env node
var readline = require('readline');
var bcv_parser = require('bible-passage-reference-parser/js/tr_bcv_parser').bcv_parser;
var bcv = new bcv_parser();
var formatter = require('bible-reference-formatter/es6/en');
bcv.set_options({
'sequence_combination_strategy': 'separate'
});
bcv.include_apocrypha(true);
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
});
var references = [];
function extract_references (data) {
var res = bcv.parse(data).osis_and_indices();
res.forEach(function(match) {
var ref = {};
ref.original = data.slice(match.indices[0], match.indices[1]);
ref.osis = match.osis;
ref.reformat = formatter('niv-long', match.osis);
references.push(ref);
});
}
function output_references () {
var output = JSON.stringify(references, null, ' ');
process.stdout.write(output);
}
rl.on('line', extract_references);
rl.on('close', output_references);
|
Add reformatted (EN) verse references to dump
|
Add reformatted (EN) verse references to dump
|
JavaScript
|
agpl-3.0
|
alerque/casile,alerque/casile,alerque/casile,alerque/casile,alerque/casile
|
104b3f4f49f64fa66ef4bb03f0d01bb36013edfa
|
app/components/HomePage/ListView/ListViewport.js
|
app/components/HomePage/ListView/ListViewport.js
|
import {ToolViewport} from '../Tools';
import styled from 'styled-components';
export default styled(ToolViewport)`
background-color: none;
padding: 0 10px 0 50px;
position: relative;
&::before{
content: ' ';
width: 53px;
height: 1px;
border-bottom: 2px solid;
position: absolute;
top: 0px;
${p=>p.theme.isArabic?'right: 9px;':'left: 50px;'};
}
h3 {
padding-top: 5px;
}
`;
|
import {ToolViewport} from '../Tools';
import styled from 'styled-components';
export default styled(ToolViewport)`
background-color: none;
padding: 0;
padding-${props=>props.theme.isArabic?'left':'right'}: 30px;
padding-${props=>props.theme.isArabic?'right':'left'}: 17px;
position: relative;
&::before{
content: ' ';
width: 53px;
height: 1px;
border-bottom: 2px solid;
position: absolute;
top: 0px;
${p=>p.theme.isArabic?'right: 9px;':'left: 17px;'};
}
h3 {
padding-top: 5px;
}
`;
|
Fix on List View issues
|
Fix on List View issues
|
JavaScript
|
mit
|
BeautifulTrouble/beautifulrising-client,BeautifulTrouble/beautifulrising-client
|
1118e45e1a3a9803244eede35f6bf786fa1b65ca
|
blockblockadblock.user.js
|
blockblockadblock.user.js
|
// ==UserScript==
// @name blockblockadblock
// @namespace Mechazawa
// @include https://blockadblock.com/*
// @version 1
// @grant none
// @run-at document-start
// ==/UserScript==
// This is very dirty and should not be used
// I've found a more reliable vuln that I'll be exploiting soon
(function(window) {
var windowKeysDefault = Object.keys(window);
document.addEventListener('DOMContentLoaded', function() {
var windowKeysSuspect = Object.keys(window)
.filter(function(x){return windowKeysDefault.indexOf(x) === -1 && x.length == 12;})
.filter(function(x){return /\D\d\D/.exec(x) !== null;});
for(var i = 0; i < windowKeysSuspect.length; i++) {
delete window[windowKeysSuspect[i]];
}
console.log("Found and deleted suspect keys: " + windowKeysSuspect.join(','));
});
})(window);
|
// ==UserScript==
// @name blockblockadblock
// @namespace Mechazawa
// @include https://blockadblock.com/*
// @include https://mindgamer.com/*
// @version 1
// @grant none
// @run-at document-start
// ==/UserScript==
// This is very dirty and should not be used
// I've found a more reliable vuln that I'll be exploiting soon
(function(window) {
var windowKeysDefault = Object.keys(window);
var suspects = {};
window.getSuspects = function() { return suspects;}
document.addEventListener('DOMContentLoaded', function() {
var windowKeysSuspect = Object.keys(window)
.filter(function(x){return windowKeysDefault.indexOf(x) === -1 && x.length == 12;});
for(var i = 0; i < windowKeysSuspect.length; i++) {
var suspectName = windowKeysSuspect[i];
var suspect = window[suspectName];
var suspectKeys = Object.keys(suspect);
var found = false;
suspects[suspectName] = suspect;
for(var ii in suspectKeys) {
found = suspect[suspectKeys[ii]].toSource().indexOf('aW5zLmFkc2J5Z29vZ2xl') !== -1;
if(found) break;
}
if(found) {
console.log('Found BlockAdBlock with name ' + suspectName);
delete window[suspectName];
}
}
});
})(window);
|
Check for identifier in BlockAdBlock source before deleteing
|
Check for identifier in BlockAdBlock source before deleteing
|
JavaScript
|
unlicense
|
Mechazawa/BlockBlockAdBlock
|
98548f8330696e009a1e81af2d9b234d950c1d3f
|
tasks/htmlmin.js
|
tasks/htmlmin.js
|
/*
* grunt-contrib-htmlmin
* http://gruntjs.com/
*
* Copyright (c) 2012 Sindre Sorhus, contributors
* Licensed under the MIT license.
*/
'use strict';
module.exports = function (grunt) {
var minify = require('html-minifier').minify;
var helper = require('grunt-lib-contrib').init(grunt);
grunt.registerMultiTask('htmlmin', 'Minify HTML', function () {
var options = this.options();
grunt.verbose.writeflags(options, 'Options');
this.files.forEach(function (file) {
var max = file.src.filter(function (filepath) {
// Warn on and remove invalid source files (if nonull was set).
if (!grunt.file.exists(filepath)) {
grunt.log.warn('Source file "' + filepath + '" not found.');
return false;
} else {
return true;
}
})
.map(grunt.file.read)
.join(grunt.util.normalizelf(grunt.util.linefeed));
var min = minify(max, options);
if (min.length < 1) {
grunt.log.warn('Destination not written because minified HTML was empty.');
} else {
grunt.file.write(file.dest, min);
grunt.log.writeln('File ' + file.dest + ' created.');
helper.minMaxInfo(min, max);
}
});
});
};
|
/*
* grunt-contrib-htmlmin
* http://gruntjs.com/
*
* Copyright (c) 2012 Sindre Sorhus, contributors
* Licensed under the MIT license.
*/
'use strict';
module.exports = function (grunt) {
var minify = require('html-minifier').minify;
var helper = require('grunt-lib-contrib').init(grunt);
grunt.registerMultiTask('htmlmin', 'Minify HTML', function () {
var options = this.options();
grunt.verbose.writeflags(options, 'Options');
this.files.forEach(function (file) {
var min;
var max = file.src.filter(function (filepath) {
// Warn on and remove invalid source files (if nonull was set).
if (!grunt.file.exists(filepath)) {
grunt.log.warn('Source file "' + filepath + '" not found.');
return false;
} else {
return true;
}
})
.map(grunt.file.read)
.join(grunt.util.normalizelf(grunt.util.linefeed));
try {
min = minify(max, options);
} catch (err) {
grunt.warn(file.src + '\n' + err);
}
if (min.length < 1) {
grunt.log.warn('Destination not written because minified HTML was empty.');
} else {
grunt.file.write(file.dest, min);
grunt.log.writeln('File ' + file.dest + ' created.');
helper.minMaxInfo(min, max);
}
});
});
};
|
Stop executing when minify throws
|
Stop executing when minify throws
Fixes #16
|
JavaScript
|
mit
|
gruntjs/grunt-contrib-htmlmin,gruntjs/grunt-contrib-htmlmin
|
a7dbce88aceca898c578a7fee62644feb9e07fd2
|
test/examples.js
|
test/examples.js
|
var polyline = require( '..' )
var assert = require( 'assert' )
suite( 'Google Polyline Example', function() {
test( 'encode', function() {
var points = [
[ 38.5, -120.2 ],
[ 40.7, -120.95 ],
[ 43.252, -126.453 ]
]
var encoded = polyline.encode( points )
assert.equal( encoded, '_p~iF~ps|U_ulLnnqC_mqNvxq`@' )
})
test( 'decode' )
})
|
var polyline = require( '..' )
var assert = require( 'assert' )
suite( 'Google Polyline Example', function() {
test( 'encode', function() {
var points = [
[ 38.5, -120.2 ],
[ 40.7, -120.95 ],
[ 43.252, -126.453 ]
]
var encoded = polyline.encode( points )
assert.equal( encoded, '_p~iF~ps|U_ulLnnqC_mqNvxq`@' )
})
test( 'decode', function() {
var points = polyline.decode( '_p~iF~ps|U_ulLnnqC_mqNvxq`@' )
var decoded = [
[ 38.5, -120.2 ],
[ 40.7, -120.95 ],
[ 43.252, -126.453 ]
]
assert.deepEqual( points, decoded )
})
})
|
Update test: Add decoding test
|
Update test: Add decoding test
|
JavaScript
|
mit
|
code42day/google-polyline
|
753359fde8e0868df5a67e79e74c8ea5076c83aa
|
sort-stack.js
|
sort-stack.js
|
"use strict";
// Program that sorts a stack such that smallest items are on top
// create Stack class
function Stack() {
this.top = null;
}
// push value into stack
Stack.prototype.push = function(val) {
this.top = {
data: val,
next: this.top
};
};
// pop value from stack
Stack.prototype.pop = function() {
var top = this.top;
if(top) {
var popData = top.data;
top = top.next;
return popData;
}
return;
};
// sort stack in ascending order (main function in exercise)
Stack.prototype.sort = function() {
var stackTwo = new Stack();
while(this.top) {
var placeHolder = this.pop();
while(stackTwo.top && stackTwo.top.data > placeHolder) {
stackOne.push(stackTwo.pop());
}
stackTwo.push(placeHolder);
}
console.log(stackTwo);
};
|
"use strict";
// Program that sorts a stack such that smallest items are on top
// create Stack class
function Stack() {
this.top = null;
}
// push value into stack
Stack.prototype.push = function(val) {
this.top = {
data: val,
next: this.top
};
};
// pop value from stack
Stack.prototype.pop = function() {
var top = this.top;
if(top) {
var popData = top.data;
top = top.next;
return popData;
}
return;
};
// sort stack in ascending order (main function in exercise)
Stack.prototype.sort = function() {
// create output stack
var stackTwo = new Stack();
while(this.top) {
var placeHolder = this.pop();
while(stackTwo.top && stackTwo.top.data > placeHolder) {
// push the top element in output stack (larger value) into original stack
stackOne.push(stackTwo.pop());
}
// push element in placeholder into output stack
stackTwo.push(placeHolder);
}
console.log(stackTwo);
};
|
Add comments and pseudocode to sort function
|
Add comments and pseudocode to sort function
|
JavaScript
|
mit
|
derekmpham/interview-prep,derekmpham/interview-prep
|
7cfc6ee461d82c5ccc60d59d07daf99c392eb860
|
style.js
|
style.js
|
module.exports = {
plugins: [
"filenames",
"prettier"
],
rules: {
// ERRORS
// No more bikeshedding on style; just use prettier
// https://github.com/not-an-aardvark/eslint-plugin-prettier
"prettier/prettier": ["error", { useTabs: true }],
// enforce lowercase kebab case for filenames
// we have had issues in the past with case sensitivity & module resolution
// https://github.com/selaux/eslint-plugin-filenames
"filenames/match-regex": ["error", "^[a-z\-\.]+$"],
// don't concatenate strings like a n00b
// http://eslint.org/docs/rules/prefer-template
"prefer-template": ["error"],
// =======================================================================================
// WARNINGS
// don't write a whole application in one single js file (default 301 lines is too big)
// http://eslint.org/docs/rules/max-lines
"max-lines": ["warn"],
// don't make ridiculous functions that take billions upon billions of arguments
// http://eslint.org/docs/rules/max-params
"max-params": ["warn", { max: 4 }]
}
};
|
module.exports = {
plugins: [
"filenames",
"prettier"
],
rules: {
// ERRORS
// No more bikeshedding on style; just use prettier
// https://github.com/not-an-aardvark/eslint-plugin-prettier
"prettier/prettier": ["error", { useTabs: true }],
// enforce lowercase kebab case for filenames
// we have had issues in the past with case sensitivity & module resolution
// https://github.com/selaux/eslint-plugin-filenames
"filenames/match-regex": ["error", "^[a-z\-\.]+$"],
// don't concatenate strings like a n00b
// http://eslint.org/docs/rules/prefer-template
"prefer-template": ["error"],
// put a space after the comment slashes
// http://eslint.org/docs/rules/spaced-comment
"spaced-comment": ["error", "always"],
// =======================================================================================
// WARNINGS
// don't write a whole application in one single js file (default 301 lines is too big)
// http://eslint.org/docs/rules/max-lines
"max-lines": ["warn"],
// don't make ridiculous functions that take billions upon billions of arguments
// http://eslint.org/docs/rules/max-params
"max-params": ["warn", { max: 4 }]
}
};
|
Add back missing comment rule
|
Add back missing comment rule
Prettier doesn't enforce anything in regards to comments
|
JavaScript
|
mit
|
civicsource/eslint-config-civicsource
|
b3f0e0245ba31e22d21c42852c79ece24e052597
|
src/text/Text.js
|
src/text/Text.js
|
import React, { PropTypes } from 'react';
import { Text, StyleSheet, Platform } from 'react-native';
import fonts from '../config/fonts';
import normalize from '../helpers/normalizeText';
let styles = {};
const TextElement = ({style, children, h1, h2, h3, h4, fontFamily}) => (
<Text
style={[
styles.text,
h1 && {fontSize: normalize(40)},
h2 && {fontSize: normalize(34)},
h3 && {fontSize: normalize(28)},
h4 && {fontSize: normalize(22)},
h1 && styles.bold,
h2 && styles.bold,
h3 && styles.bold,
h4 && styles.bold,
fontFamily && {fontFamily},
style && style
]}>{children}</Text>
);
TextElement.propTypes = {
style: PropTypes.any,
h1: PropTypes.bool,
h2: PropTypes.bool,
h3: PropTypes.bool,
h4: PropTypes.bool,
fontFamily: PropTypes.string,
children: PropTypes.any,
};
styles = StyleSheet.create({
text: {
...Platform.select({
android: {
...fonts.android.regular
}
})
},
bold: {
...Platform.select({
android: {
...fonts.android.bold
}
})
}
});
export default TextElement;
|
import React, { PropTypes } from 'react';
import { Text, StyleSheet, Platform } from 'react-native';
import fonts from '../config/fonts';
import normalize from '../helpers/normalizeText';
TextElement.propTypes = {
style: PropTypes.any,
h1: PropTypes.bool,
h2: PropTypes.bool,
h3: PropTypes.bool,
h4: PropTypes.bool,
fontFamily: PropTypes.string,
children: PropTypes.any,
};
const styles = StyleSheet.create({
text: {
...Platform.select({
android: {
...fonts.android.regular
}
})
},
bold: {
...Platform.select({
android: {
...fonts.android.bold
}
})
}
});
const TextElement = (props) => {
const {
style,
children,
h1,
h2,
h3,
h4,
fontFamily,
...rest,
} = props;
return (
<Text
style={[
styles.text,
h1 && {fontSize: normalize(40)},
h2 && {fontSize: normalize(34)},
h3 && {fontSize: normalize(28)},
h4 && {fontSize: normalize(22)},
h1 && styles.bold,
h2 && styles.bold,
h3 && styles.bold,
h4 && styles.bold,
fontFamily && {fontFamily},
style && style
]}
{...rest}
>{children}</Text>
);
};
export default TextElement;
|
Use ES6 spread forf rest of the props
|
Use ES6 spread forf rest of the props
In reference to #247
|
JavaScript
|
mit
|
kosiakMD/react-native-elements,martinezguillaume/react-native-elements,react-native-community/React-Native-Elements,kosiakMD/react-native-elements
|
4516a7ced770f11f0febe8aec0615ddbb8f6674b
|
src/modules/ngSharepoint/app.js
|
src/modules/ngSharepoint/app.js
|
angular
.module('ngSharepoint', [])
.run(function($sp, $spLoader) {
if ($sp.getAutoload()) {
if ($sp.getConnectionMode() === 'JSOM') {
$spLoader.loadScripts('SP.Core', ['//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js', 'SP.Runtime.js', 'SP.js']);
}else if ($sp.getConnectionMode() === 'REST' && !$sp.getAccessToken()) {
$spLoader.loadScript('SP.RequestExecutor.js');
}
}
});
|
angular
.module('ngSharepoint', [])
.run(function($sp, $spLoader) {
if ($sp.getAutoload()) {
if ($sp.getConnectionMode() === 'JSOM') {
var scripts = [
'//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js',
'SP.Runtime.js',
'SP.js'
];
$spLoader.loadScripts('SP.Core', scripts);
}else if ($sp.getConnectionMode() === 'REST' && !$sp.getAccessToken()) {
$spLoader.loadScript('SP.RequestExecutor.js');
}
}
});
|
Define scripts in a array instead of inline
|
Define scripts in a array instead of inline
|
JavaScript
|
apache-2.0
|
maxjoehnk/ngSharepoint
|
0168687fb0b9e599e5bf1f25627006531624d114
|
tests/docker.js
|
tests/docker.js
|
var assert = require("assert");
var spawn = require('child_process').spawn;
describe('Start docker container', function () {
it('should show M2 preamble', function (done) {
// ssh localhost
var docker = "docker";
var process = spawn(docker, ["run", "fhinkel/macaulay2", "M2"]);
var encoding = "utf8";
process.stderr.setEncoding(encoding);
process.stderr.on('data', function (data) {
console.log("Preamble: " + data);
assert(data.match(/Macaulay2, version 1\.\d/),
'M2 preamble does not match');
process.kill();
done();
});
process.on('error', function (error) {
assert(false, error);
next();
})
});
});
|
var assert = require("assert");
var spawn = require('child_process').spawn;
describe('Start docker container', function () {
it('should show M2 preamble', function (done) {
// ssh localhost
var docker = "docker";
var process = spawn(docker, ["run", "fhinkel/macaulay2", "M2"]);
var encoding = "utf8";
process.stderr.setEncoding(encoding);
var result = "";
process.stderr.on('data', function (data) {
console.log("Preamble: " + data);
result += data;
});
process.on('error', function (error) {
assert(false, error);
next();
});
process.on('close', function() {
assert(result.match(/Macaulay2, version 1\.\d/),
'M2 preamble does not match');
done();
});
});
});
|
Fix test to wait for output
|
Fix test to wait for output
|
JavaScript
|
mit
|
fhinkel/InteractiveShell,antonleykin/InteractiveShell,antonleykin/InteractiveShell,antonleykin/InteractiveShell,fhinkel/InteractiveShell,fhinkel/InteractiveShell,fhinkel/InteractiveShell
|
4b1dc538fce1baba33efbc9f3b07ae0af3054eb7
|
app/components/query-widget/component.js
|
app/components/query-widget/component.js
|
import Ember from 'ember';
export default Ember.Component.extend({
init () {
this._super(...arguments);
this.set("query", this.get("parameters").query);
},
actions: {
transitionToFacet(parameter) {
let queryParams = {};
queryParams["query"] = parameter;
this.attrs.transitionToFacet(this.get('item.facetDash'), queryParams);
}
}
});
|
import Ember from 'ember';
export default Ember.Component.extend({
init () {
this._super(...arguments);
this.set("query", this.get("parameters").query);
},
actions: {
transitionToFacet(parameter) {
let queryParams = {};
queryParams["query"] = parameter;
queryParams["page"] = undefined;
this.attrs.transitionToFacet(this.get('item.facetDash'), queryParams);
}
}
});
|
Reset query parameter for page when hitting search
|
Reset query parameter for page when hitting search
|
JavaScript
|
apache-2.0
|
caneruguz/share-analytics,caneruguz/share-analytics,caneruguz/share-analytics
|
2885aa520808d944b76387bc4f2dc8c9896c6dcf
|
src/transform/negate.js
|
src/transform/negate.js
|
var es = require("../es");
function Negate(transform, node) {
var expr = transform(node.expr);
if (typeof node.expr.data === "number") {
var literal = es.Literal(node.loc, node.expr.data);
return es.UnaryExpression(node.loc, true, "-", literal);
} else {
var negate = es.Identifier(node.loc, "$negate");
return es.CallExpression(null, negate, [expr]);
}
}
module.exports = Negate;
|
var es = require("../es");
function Negate(transform, node) {
var expr = transform(node.expr);
if (node.expr.type === "Number") {
return es.UnaryExpression(node.loc, true, "-", transform(node.expr));
} else {
var negate = es.Identifier(node.loc, "$negate");
return es.CallExpression(null, negate, [expr]);
}
}
module.exports = Negate;
|
Use proper type checking and transform function
|
Use proper type checking and transform function
As per Brians requests
|
JavaScript
|
mit
|
wavebeem/squiggle,saikobee/expr-lang,squiggle-lang/squiggle-lang,saikobee/expr-lang,squiggle-lang/squiggle-lang,wavebeem/squiggle,squiggle-lang/squiggle-lang,saikobee/squiggle,saikobee/squiggle,saikobee/expr-lang,wavebeem/squiggle,saikobee/squiggle
|
7f0af3ca94e821afe42d0b096c8a7b25d893920a
|
gulpfile.js
|
gulpfile.js
|
'use strict'
var gulp = require('gulp');
var tsc = require('gulp-typescript');
gulp.task('copy', function () {
gulp.src('src/html/**')
.pipe(gulp.dest('dest/html'));
});
gulp.task('build', [
'copy'
]);
gulp.task('test-build', ['build'], function () {
gulp.src('test/src/ts/**/*.ts')
.pipe(tsc())
.pipe(gulp.dest('test/dest/js'));
});
gulp.task('default', ['build']);
|
'use strict'
var gulp = require('gulp');
var tsc = require('gulp-typescript');
gulp.task('copy', function () {
gulp.src('src/html/**')
.pipe(gulp.dest('dest/html'));
});
gulp.task('build', ['copy'], function () {
gulp.src('src/ts/**/*.ts')
.pipe(tsc())
.pipe(gulp.dest('dest/js'));
});
gulp.task('test-build', ['build'], function () {
gulp.src('test/src/ts/**/*.ts')
.pipe(tsc())
.pipe(gulp.dest('test/dest/js'));
});
gulp.task('default', ['build']);
|
Edit task gulp.build: typescript build
|
Edit task gulp.build: typescript build
|
JavaScript
|
mit
|
yajamon/freedomWarsPlantSimulator,yajamon/freedomWarsPlantSimulator
|
9a21a130e2ed9ae44ddf00ac367fdb66de81ce18
|
gulpfile.js
|
gulpfile.js
|
'use strict';
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var rirmaf = require('rimraf');
var lib = 'lib/**/*.js';
gulp.task('coverage', function(){
return gulp.src(lib)
.pipe($.istanbul());
});
gulp.task('coverage:clean', function(callback){
rirmaf('coverage', callback);
});
gulp.task('mocha', ['coverage'], function(){
return gulp.src('test/index.js')
.pipe($.mocha({
reporter: 'spec'
}))
.pipe($.istanbul.writeReports());
});
gulp.task('jshint', function(){
return gulp.src(lib)
.pipe($.jshint())
.pipe($.jshint.reporter('jshint-stylish'))
.pipe($.jshint.reporter('fail'));
});
gulp.task('watch', function(){
gulp.watch(lib, ['mocha', 'jshint']);
gulp.watch(['test/index.js'], ['mocha']);
});
gulp.task('test', ['mocha', 'jshint']);
|
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var rirmaf = require('rimraf');
var lib = 'lib/**/*.js';
gulp.task('coverage', function(){
return gulp.src(lib)
.pipe($.istanbul())
.pipe($.istanbul.hookRequire());
});
gulp.task('coverage:clean', function(callback){
rirmaf('coverage', callback);
});
gulp.task('mocha', ['coverage'], function(){
return gulp.src('test/index.js')
.pipe($.mocha({
reporter: 'spec'
}))
.pipe($.istanbul.writeReports());
});
gulp.task('jshint', function(){
return gulp.src(lib)
.pipe($.jshint())
.pipe($.jshint.reporter('jshint-stylish'))
.pipe($.jshint.reporter('fail'));
});
gulp.task('watch', function(){
gulp.watch(lib, ['mocha', 'jshint']);
gulp.watch(['test/index.js'], ['mocha']);
});
gulp.task('test', ['mocha', 'jshint']);
|
Fix gulp-istanbul 0.5.0 doesn't generate lcov file.
|
Fix gulp-istanbul 0.5.0 doesn't generate lcov file.
|
JavaScript
|
mit
|
hexojs/hexo-fs,hexojs/hexo-fs
|
f125ca538110ffed462a896e639b86e53d4492de
|
gulpfile.js
|
gulpfile.js
|
///
var pkg = require("./package.json")
, gulp = require("gulp")
, plumber = require("gulp-plumber")
///
// Lint JS
///
var jshint = require("gulp-jshint")
, jsonFiles = [".jshintrc", "*.json"]
, jsFiles = ["*.js", "src/**/*.js"]
gulp.task("scripts.lint", function() {
gulp.src([].concat(jsonFiles).concat(jsFiles))
.pipe(plumber())
.pipe(jshint(".jshintrc"))
.pipe(jshint.reporter("jshint-stylish"))
})
var jscs = require("gulp-jscs")
gulp.task("scripts.cs", function() {
gulp.src(jsFiles)
.pipe(plumber())
.pipe(jscs())
})
gulp.task("scripts", ["scripts.lint", "scripts.cs"])
gulp.task("watch", function() {
gulp.watch(jsFiles, ["scripts"])
})
gulp.task("default", ["scripts", "watch"])
var buildBranch = require("buildbranch")
gulp.task("publish", function(cb) {
buildBranch({folder: "src"}
, function(err) {
if (err) {
throw err
}
console.log(pkg.name + " published.")
cb()
})
})
|
///
var pkg = require("./package.json")
, gulp = require("gulp")
, plumber = require("gulp-plumber")
///
// Lint JS
///
var jshint = require("gulp-jshint")
, jsonFiles = [".jshintrc", "*.json"]
, jsFiles = ["*.js", "src/**/*.js"]
gulp.task("scripts.lint", function() {
gulp.src([].concat(jsonFiles).concat(jsFiles))
.pipe(plumber())
.pipe(jshint(".jshintrc"))
.pipe(jshint.reporter("jshint-stylish"))
})
var jscs = require("gulp-jscs")
gulp.task("scripts.cs", function() {
gulp.src(jsFiles)
.pipe(plumber())
.pipe(jscs())
})
gulp.task("scripts", ["scripts.lint", "scripts.cs"])
gulp.task("watch", function() {
gulp.watch(jsFiles, ["scripts"])
})
gulp.task("dist", ["scripts"])
gulp.task("test", ["dist"])
gulp.task("default", ["test", "watch"])
var buildBranch = require("buildbranch")
gulp.task("publish", ["test"], function(cb) {
buildBranch({folder: "src"}
, function(err) {
if (err) {
throw err
}
console.log(pkg.name + " published.")
cb()
})
})
|
Improve build task to run test before
|
Improve build task to run test before
|
JavaScript
|
mit
|
MoOx/parallaxify,MoOx/parallaxify
|
b7fca936a31175610262b51bf618465dd72babbb
|
gulpfile.js
|
gulpfile.js
|
var gulp = require('gulp');
var gulpTypescript = require('gulp-typescript');
var typescript = require('typescript');
var header = require('gulp-header');
var merge = require('merge2');
var pkg = require('./package.json');
var headerTemplate = '// <%= pkg.name %> v<%= pkg.version %>\n';
gulp.task('default', tscTask);
function tscTask() {
var tsResult = gulp
.src([
// this solves the 'cannot resolve Promise' issue
'node_modules/@types/core-js/index.d.ts',
'src/**/*.ts'
])
.pipe(gulpTypescript({
typescript: typescript,
module: 'commonjs',
experimentalDecorators: true,
emitDecoratorMetadata: true,
declarationFiles: true,
target: 'es5',
noImplicitAny: true,
noEmitOnError: false
}));
return merge([
tsResult.dts
.pipe(header(headerTemplate, { pkg : pkg }))
.pipe(gulp.dest('lib')),
tsResult.js
.pipe(header(headerTemplate, { pkg : pkg }))
.pipe(gulp.dest('lib'))
])
}
|
var gulp = require('gulp');
var gulpTypescript = require('gulp-typescript');
var typescript = require('typescript');
var header = require('gulp-header');
var merge = require('merge2');
var pkg = require('./package.json');
var headerTemplate = '// <%= pkg.name %> v<%= pkg.version %>\n';
gulp.task('default', tscTask);
function tscTask() {
var tsResult = gulp
.src([
// this solves the 'cannot resolve Promise' issue
'node_modules/@types/core-js/index.d.ts',
'src/**/*.ts'
])
.pipe(gulpTypescript({
typescript: typescript,
module: 'commonjs',
experimentalDecorators: true,
emitDecoratorMetadata: true,
declarationFiles: true,
target: 'es5',
noImplicitAny: true,
noEmitOnError: false,
lib: ["dom","es2015"]
}));
return merge([
tsResult.dts
.pipe(header(headerTemplate, { pkg : pkg }))
.pipe(gulp.dest('lib')),
tsResult.js
.pipe(header(headerTemplate, { pkg : pkg }))
.pipe(gulp.dest('lib'))
])
}
|
Add "lib" to typescript defs
|
Add "lib" to typescript defs
|
JavaScript
|
mit
|
ceolter/angular-grid,ceolter/ag-grid,ceolter/angular-grid,ceolter/ag-grid
|
2b57e2cf7ac3b3b20253f27c5adc98f58f77b6af
|
gulpfile.js
|
gulpfile.js
|
var gulp = require('gulp');
//var browserify = require('browserify');
var webpack = require('webpack');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var mocha = require('gulp-mocha');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
var ENTRY = './src/build.js';
var DIST = './dist';
var FILE = 'math-light.js';
gulp.task('bundle', function (cb) {
var webpackConfig = {
entry: ENTRY,
output: {
library: 'math-light',
libraryTarget: 'commonjs2',
path: DIST,
filename: FILE
},
externals: [
'crypto' // is referenced by decimal.js
],
cache: false
};
var compiler = webpack(webpackConfig);
compiler.run(function (err, stats) {
if (err) {
console.log(err);
}
console.log('bundled');
cb();
});
});
gulp.task('uglify', ['bundle'], function () {
return gulp.src(DIST + '/' + FILE)
.pipe(uglify({
ie_proof: false
}))
.pipe(rename(function (path) {
path.basename += '.min';
}))
.pipe(gulp.dest(DIST));
});
gulp.task('test', function () {
return gulp.src('test/test.js')
.pipe(mocha());
});
gulp.task('default', ['uglify']);
|
var gulp = require('gulp');
//var browserify = require('browserify');
var webpack = require('webpack');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var mocha = require('gulp-mocha');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
var ENTRY = './src/build.js';
var DIST = './dist';
var FILE = 'math-light.js';
// Could be 'amd'
var MODULE_FORMAT = 'commonjs2';
gulp.task('bundle', function (cb) {
var webpackConfig = {
entry: ENTRY,
output: {
library: 'math-light',
libraryTarget: MODULE_FORMAT,
path: DIST,
filename: FILE
},
externals: [
'crypto' // is referenced by decimal.js
],
cache: false
};
var compiler = webpack(webpackConfig);
compiler.run(function (err, stats) {
if (err) {
console.log(err);
}
console.log('bundled');
cb();
});
});
gulp.task('uglify', ['bundle'], function () {
return gulp.src(DIST + '/' + FILE)
.pipe(uglify({
ie_proof: false
}))
.pipe(rename(function (path) {
path.basename += '.min';
}))
.pipe(gulp.dest(DIST));
});
gulp.task('test', function () {
return gulp.src('test/test.js')
.pipe(mocha());
});
gulp.task('default', ['uglify']);
|
Make it easier to change the output module format
|
Make it easier to change the output module format
|
JavaScript
|
apache-2.0
|
jtsay362/solveforall-custom-mathjs-build
|
ebdefd648d4b5d143a25f2d1861de075f43b4fe1
|
gulpfile.js
|
gulpfile.js
|
'use strict';
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var paths = {
js: ['./gulpfile.js', './test/**/*.js'],
scss: ['./stylesheets/_sass-lib.scss'],
test: ['./test/**/*.js']
};
var plumberOpts = {};
gulp.task('js-lint', function () {
return gulp.src(paths.js)
.pipe($.jshint('.jshintrc'))
.pipe($.plumber(plumberOpts))
.pipe($.jscs())
.pipe($.jshint.reporter('jshint-stylish'));
});
gulp.task('scss-lint', function() {
gulp.src(paths.scss)
.pipe($.scssLint())
.pipe($.plumber(plumberOpts));
});
gulp.task('test', function () {
return gulp.src(paths.test)
.pipe($.plumber(plumberOpts))
.pipe($.mocha());
});
gulp.task('lint', ['scss-lint', 'js-lint']);
gulp.task('test', ['lint']);
gulp.task('watch', ['test'], function () {
gulp.watch(paths.js, ['js-lint']);
gulp.watch(paths.scss, ['scss-lint']);
gulp.watch(paths.test, ['test']);
});
gulp.task('default', ['scss-lint', 'js-lint', 'test']);
|
'use strict';
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var paths = {
js: ['./gulpfile.js', './test/**/*.js'],
scss: ['./stylesheets/_sass-lib.scss'],
test: ['./test/**/*.js']
};
var plumberOpts = {};
gulp.task('js-lint', function () {
return gulp.src(paths.js)
.pipe($.jshint('.jshintrc'))
.pipe($.plumber(plumberOpts))
.pipe($.jscs())
.pipe($.jshint.reporter('jshint-stylish'));
});
gulp.task('scss-lint', function() {
gulp.src(paths.scss)
.pipe($.scssLint())
.pipe($.plumber(plumberOpts));
});
gulp.task('test', function () {
return gulp.src(paths.test, {read: false})
.pipe($.plumber(plumberOpts))
.pipe($.mocha({reporter: 'nyan'}));
});
gulp.task('lint', ['scss-lint', 'js-lint']);
gulp.task('test', ['lint']);
gulp.task('watch', ['test'], function () {
gulp.watch(paths.js, ['js-lint']);
gulp.watch(paths.scss, ['scss-lint']);
gulp.watch(paths.test, ['test']);
});
gulp.task('default', ['scss-lint', 'js-lint', 'test']);
|
Fix mocha implementation in test task
|
Fix mocha implementation in test task
|
JavaScript
|
agpl-3.0
|
Bastly/sass-lib
|
486968a19d4d7f05c33a0039c09f94006f885960
|
src/utilities.js
|
src/utilities.js
|
import R from 'ramda';
import { NpmConfig, httpsGetPromise } from './helpers';
const addVersionProp = (val, key, obj) => obj[key] = { 'version': removeCaret(val) };
const removeCaret = R.replace(/\^/, '');
const isNotPrivate = R.compose(R.not, R.prop('private'));
const filterPrivate = R.filter(isNotPrivate);
const deeplyMerge = (obj1, obj2) => {
return R.keys(obj1).reduce((result, key) => {
result[key] = R.merge(obj1[key], obj2[key]);
return result;
}, {});
};
export const pickDownloads = (obj) => {
return R.keys(obj).reduce((result, key) => {
result[key] = R.pick(['downloads'], obj[key]);
return result;
}, {});
};
export const addNode = (obj) => {
obj.node = {
name : 'Node.js',
url : 'https://nodejs.org',
version : process.versions.node,
description : 'A JavaScript runtime ✨🐢🚀✨',
downloads : 10000000 // A fake number since Node isn't downloaded on npm
};
return obj;
};
export const curriedMerge = R.curry(deeplyMerge);
export const formatVersionsAndFilterPrivate = R.compose(R.mapObjIndexed(addVersionProp), filterPrivate);
export const getNpmData = R.compose(httpsGetPromise, NpmConfig);
|
import R from 'ramda';
import { NpmConfig, httpsGetPromise } from './helpers';
const addVersionProp = (val, key, obj) => obj[key] = { 'version': removeCaret(val) };
const removeCaret = R.replace(/\^/, '');
const isNotPrivate = R.compose(R.not, R.prop('private'));
const filterPrivate = R.filter(isNotPrivate);
const pickProps = R.curry(R.pick);
const deeplyMerge = (obj1, obj2) => {
return R.keys(obj1).reduce((result, key) => {
result[key] = R.merge(obj1[key], obj2[key]);
return result;
}, {});
};
export const addNode = (obj) => {
obj.node = {
name : 'Node.js',
url : 'https://nodejs.org',
version : process.versions.node,
description : 'A JavaScript runtime ✨🐢🚀✨',
downloads : 10000000 // A fake number since Node isn't downloaded on npm
};
return obj;
};
export const pickDownloads = R.map(pickProps(['downloads']));
export const curriedMerge = R.curry(deeplyMerge);
export const formatVersionsAndFilterPrivate = R.compose(R.mapObjIndexed(addVersionProp), filterPrivate);
export const getNpmData = R.compose(httpsGetPromise, NpmConfig);
|
Rewrite pickDownloads as Ramda function
|
refactor: Rewrite pickDownloads as Ramda function
|
JavaScript
|
mit
|
cachilders/backpat,churchie317/backpat
|
196c268ec7913ce0aba8afb6ec0eb27bc3abd325
|
src/promise-array.js
|
src/promise-array.js
|
import {Observable} from 'rx';
export function asyncMap(array, selector, maxConcurrency=4) {
return Observable.from(array)
.map((k) =>
Observable.defer(() =>
Observable.fromPromise(selector(k))
.map((v) => ({ k, v }))))
.merge(maxConcurrency)
.reduce((acc, kvp) => {
acc[kvp.k] = kvp.v;
return acc;
}, {})
.toPromise();
}
|
import {Observable} from 'rx';
const spawnOg = require('child_process').spawn;
export function asyncMap(array, selector, maxConcurrency=4) {
return Observable.from(array)
.map((k) =>
Observable.defer(() =>
Observable.fromPromise(selector(k))
.map((v) => ({ k, v }))))
.merge(maxConcurrency)
.reduce((acc, kvp) => {
acc[kvp.k] = kvp.v;
return acc;
}, {})
.toPromise();
}
export function delay(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
// Public: Maps a process's output into an {Observable}
//
// exe - The program to execute
// params - Arguments passed to the process
// opts - Options that will be passed to child_process.spawn
//
// Returns a {Promise} with a single value, that is the output of the
// spawned process
export function spawn(exe, params, opts=null) {
let spawnObs = Observable.create((subj) => {
let proc = null;
if (!opts) {
proc = spawnOg(exe, params);
} else {
proc = spawnOg(exe, params, opts);
}
let stdout = '';
let bufHandler = (b) => {
let chunk = b.toString();
stdout += chunk;
subj.onNext(chunk);
};
proc.stdout.on('data', bufHandler);
proc.stderr.on('data', bufHandler);
proc.on('error', (e) => subj.onError(e));
proc.on('close', (code) => {
if (code === 0) {
subj.onCompleted();
} else {
subj.onError(new Error(`Failed with exit code: ${code}\nOutput:\n${stdout}`));
}
});
});
return spawnObs.reduce((acc, x) => acc += x, '').toPromise();
}
|
Copy over a promise version of spawn and delay
|
Copy over a promise version of spawn and delay
|
JavaScript
|
mit
|
surf-build/surf,surf-build/surf,surf-build/surf,surf-build/surf
|
accc090267f36417b578d1e3254ae2671599a62c
|
stream-meteor.js
|
stream-meteor.js
|
var apiKey = Meteor.settings.public.streamApiKey,
apiAppId = Meteor.settings.public.streamApiAppId;
var settings = _.clone(Config);
settings['apiKey'] = apiKey;
settings['apiAppId'] = apiAppId;
if (Meteor.isServer) {
Stream.stream = Npm.require('getstream');
settings['apiSecret'] = Meteor.settings.streamApiSecret;
}
Stream.feedManager = new FeedManager(settings);
|
var apiKey = Meteor.settings.public.streamApiKey,
apiAppId = Meteor.settings.public.streamApiAppId;
var settings = _.clone(Config);
if(! apiKey) {
throw new Meteor.Error('misconfig', 'No getstream.io app api key found in your settings.json\n hint: Are you running meteor with --settings settings.json?');
}
if(! apiAppId) {
throw new Meteor.Error('misconfig', 'No getstream.io app id key found in your settings.json\n hint: Are you running meteor with --settings settings.json?');
}
settings['apiKey'] = apiKey;
settings['apiAppId'] = apiAppId;
if (Meteor.isServer) {
Stream.stream = Npm.require('getstream');
if(! Meteor.settings.streamApiSecret) {
throw new Meteor.Error('misconfig', 'No getstream.io private key found in your settings.json\n hint: Are you running meteor with --settings settings.json?');
}
settings['apiSecret'] = Meteor.settings.streamApiSecret;
}
if(Meteor.settings.userFeed) {
settings['userFeed'] = Meteor.settings.userFeed;
}
if(Meteor.settings.notificationFeed) {
settings['notificationFeed'] = Meteor.settings.notificationFeed;
}
if(Meteor.settings.newsFeeds) {
settings['newsFeeds'] = Meteor.settings.newsFeeds;
}
Stream.feedManager = new FeedManager(settings);
|
Check if correct settings are available
|
Check if correct settings are available
|
JavaScript
|
bsd-3-clause
|
GetStream/stream-meteor
|
31bd052a42f825f3dbc4b28fcd6d998db558f91e
|
ui/routes/api.js
|
ui/routes/api.js
|
var express = require('express');
var router = express.Router();
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('/home/pi/homeauto/backend/temp.db');
/* GET home page. */
router.get('/v1/temperature', function(req, res, next) {
var filter = "WHERE sensor_fk = 1";
if(req.query.starttime && req.query.endtime) {
filter += " AND time >= " + req.query.starttime + " AND time <= " + req.query.endtime;
} else if(req.query.starttime) {
filter += " AND time >= " + req.query.starttime;
} else if(req.query.endtime) {
filter += " AND time <= " + req.query.endtime;
}
var stmt = "SELECT * FROM sensorstream " + filter + " ORDER BY time";
console.log(stmt)
db.all(stmt, function(err, rows) {
res.send(rows);
});
});
router.get('/v1/temperature/current', function(req, res, next) {
db.all("SELECT * FROM sensorstream WHERE sensor_fk = 1 ORDER BY time DESC LIMIT 1", function(err, rows) {
res.send(rows);
});
});
router.get('/v1/sensorstream/:id', function(req, res, next) {
var sensor_id = req.params.id;
console.log("sensor id: " + id)
});
module.exports = router;
|
var express = require('express');
var router = express.Router();
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('/home/pi/homeauto/backend/temp.db');
/* GET home page. */
router.get('/v1/temperature', function(req, res, next) {
var filter = "WHERE sensor_fk = 1";
if(req.query.starttime && req.query.endtime) {
filter += " AND time >= " + req.query.starttime + " AND time <= " + req.query.endtime;
} else if(req.query.starttime) {
filter += " AND time >= " + req.query.starttime;
} else if(req.query.endtime) {
filter += " AND time <= " + req.query.endtime;
}
var stmt = "SELECT * FROM sensorstream " + filter + " ORDER BY time";
console.log(stmt)
db.all(stmt, function(err, rows) {
res.send(rows);
});
});
router.get('/v1/temperature/current', function(req, res, next) {
db.all("SELECT * FROM sensorstream WHERE sensor_fk = 1 ORDER BY time DESC LIMIT 1", function(err, rows) {
res.send(rows);
});
});
router.get('/v1/sensorstream/:id', function(req, res, next) {
var sensor_id = req.params.id;
console.log("sensor id: " + id)
res.send({})
});
module.exports = router;
|
Add response to sensor stream API handler
|
Add response to sensor stream API handler
|
JavaScript
|
mit
|
schmidtfx/homeauto,schmidtfx/homeauto,schmidtfx/homeauto
|
fbfb0324b04b8fd3c82f531dea9552abf1509eb9
|
lib/log-writer.js
|
lib/log-writer.js
|
var util = require('util');
var stream = require('stream');
var fs = require('fs');
var generateLogName = require('./logname').generate;
module.exports = LogWriter;
function LogWriter(worker, options) {
if (!(this instanceof LogWriter)) return new LogWriter(worker, options);
stream.PassThrough.call(this);
this.template = options.log;
this.worker = {
id: worker.id || 'supervisor',
pid: worker.pid || worker.process.pid
}
this.name = generateLogName(this.template, this.worker);
this.sink = fs.createWriteStream(this.name, { flags: 'a'});
this.pipe(this.sink);
}
util.inherits(LogWriter, stream.PassThrough);
LogWriter.prototype.reOpen = function LogWriterReOpen() {
if (this.sink instanceof fs.WriteStream) {
this.unpipe(this.sink);
this.sink.end();
// lose our reference to previous stream, but it should clean itself up
this.sink = fs.createWriteStream(this.name, { flags: 'a'});
this.pipe(sink);
}
}
|
var util = require('util');
var stream = require('stream');
var fs = require('fs');
var spawn = require('child_process').spawn;
var generateLogName = require('./logname').generate;
module.exports = LogWriter;
function LogWriter(worker, options) {
if (!(this instanceof LogWriter)) return new LogWriter(worker, options);
stream.PassThrough.call(this);
this.template = options.log;
this.worker = {
id: worker.id || 'supervisor',
pid: worker.pid || worker.process.pid
}
this.name = generateLogName(this.template, this.worker);
if (/^\|[^\|]/.test(this.name)) {
this.cmd = this.name
.slice(1) // strip leading '|'
.trim()
.split(/\s+/);
this.proc = spawn(this.cmd[0], this.cmd.slice(1),
{ stdio: ['pipe', process.stdout, process.stderr] });
this.sink = this.proc.stdin;
} else {
this.sink = fs.createWriteStream(this.name, { flags: 'a'});
}
this.pipe(this.sink);
}
util.inherits(LogWriter, stream.PassThrough);
LogWriter.prototype.reOpen = function LogWriterReOpen() {
if (this.sink instanceof fs.WriteStream) {
this.unpipe(this.sink);
this.sink.end();
// lose our reference to previous stream, but it should clean itself up
this.sink = fs.createWriteStream(this.name, { flags: 'a'});
this.pipe(sink);
}
}
|
Add support for '| cmd' as log name for piping
|
Add support for '| cmd' as log name for piping
Create a child process as described by the log parameter following the
leading '|' and write all log events to that process's stdin stream.
The command name supports %p and %w replacement for per-worker logging.
If per-worker substitutions are made, each worker gets its own logger
process. If the command does not use per-worker substitutions, all
workers and the supervisor share the same logger process.
|
JavaScript
|
artistic-2.0
|
shelbys/strong-supervisor
|
7a0813a41afca49b7fe73367a6707f4379353009
|
test/findAssets.spec.js
|
test/findAssets.spec.js
|
const path = require('path');
const expect = require('chai').expect;
const findAssets = require('../src/config/findAssets');
const mockFs = require('mock-fs');
const dependencies = require('./fixtures/dependencies');
describe('findAssets', () => {
before(() => {
mockFs({ testDir: dependencies });
});
it('should return an array of all files in given folders', () => {
const assets = findAssets(
path.join('testDir', 'withAssets'),
['fonts', 'images']
);
expect(assets).to.be.an('array');
expect(assets.length).to.equal(3);
});
it('should return absoulte paths to assets', () => {
const folder = path.join('testDir', 'withAssets');
const assets = findAssets(
path.join('testDir', 'withAssets'),
['fonts', 'images']
);
assets.forEach(assetPath => expect(assetPath).to.contain(folder));
});
after(() => {
mockFs.restore();
});
});
|
const path = require('path');
const expect = require('chai').expect;
const findAssets = require('../src/config/findAssets');
const mockFs = require('mock-fs');
const dependencies = require('./fixtures/dependencies');
describe('findAssets', () => {
before(() => {
mockFs({ testDir: dependencies.withAssets });
});
it('should return an array of all files in given folders', () => {
const assets = findAssets('testDir', ['fonts', 'images']);
expect(assets).to.be.an('array');
expect(assets.length).to.equal(3);
});
it('should return absoulte paths to assets', () => {
const assets = findAssets('testDir', ['fonts', 'images']);
assets.forEach(assetPath => expect(assetPath).to.contain('testDir'));
});
after(() => {
mockFs.restore();
});
});
|
Use only fixtures we need
|
Use only fixtures we need
|
JavaScript
|
mit
|
rnpm/rnpm
|
b9913a7f583825b76da298d9d2275a5f1565f18e
|
test/reverse_urlSpec.js
|
test/reverse_urlSpec.js
|
(function () {
'use strict';
var reverseUrl, $route;
var routeMock = {};
routeMock.routes = {
'/testRoute1/': {
controller: 'TestController1',
originalPath: '/test-route-1/'
},
'/testRoute1/:params/': {
controller: 'TestController1',
originalPath: '/test-route-1/:param/'
},
'/testRoute2/': {
name: 'TestRoute2',
originalPath: '/test-route-2/'
},
};
describe('Unit: angular-reverse-url', function () {
beforeEach(module('angular-reverse-url', function ($provide) {
$provide.value('$route', routeMock);
}));
describe('reverseUrl filter', function () {
beforeEach(inject(function ($injector) {
$route = $injector.get('$route')
reverseUrl = $injector.get('$filter')('reverseUrl');
}));
it('should correctly match to a basic route by controller', function () {
expect(reverseUrl('TestController1')).toEqual('#/test-route-1/');
});
it('should correctly match to a basic route by name', function () {
expect(reverseUrl('TestRoute2')).toEqual('#/test-route-2/');
});
it('should correctly match to a route with params', function () {
expect(reverseUrl('TestController1', {param: 'foobar'})).toEqual('#/test-route-1/foobar/');
});
});
});
}());
|
(function () {
'use strict';
var reverseUrl, $route;
var routeMock = {};
routeMock.routes = {
'/testRoute1/': {
controller: 'TestController1',
originalPath: '/test-route-1/'
},
'/testRoute1/:params/': {
controller: 'TestController1',
originalPath: '/test-route-1/:param/'
},
'/testRoute2/': {
name: 'TestRoute2',
originalPath: '/test-route-2/'
},
};
describe('Unit: angular-reverse-url', function () {
beforeEach(module('angular-reverse-url', function ($provide) {
$provide.value('$route', routeMock);
}));
describe('reverseUrl filter', function () {
beforeEach(inject(function ($injector) {
$route = $injector.get('$route')
reverseUrl = $injector.get('$filter')('reverseUrl');
}));
it('should correctly match to a basic route by controller', function () {
expect(reverseUrl('TestController1')).toEqual('#/test-route-1/');
});
it('should correctly match to a basic route by name', function () {
expect(reverseUrl('TestRoute2')).toEqual('#/test-route-2/');
});
it('should correctly match to a route with params', function () {
expect(reverseUrl('TestController1', {param: 'foobar'})).toEqual('#/test-route-1/foobar/');
});
it('should log an error if a route is not found');
it('should log an error if params are required and missing');
it('should log an error if params keys are not found');
});
});
}());
|
Add assertions for error logging
|
Add assertions for error logging
|
JavaScript
|
mit
|
incuna/angular-reverse-url
|
b02b438bc187054eaa35d56afc51efdad69a889c
|
fetch-test.js
|
fetch-test.js
|
'use strict'
const test = require('tape')
const proxyquire = require('proxyquire')
test('fetch', function (t) {
t.plan(3)
const fetch = proxyquire('./fetch', {
'simple-get': function (options, callback) {
t.deepEqual(options, {
url: 'https://host.co/path?page=2',
headers: {
foo: 'bar'
}
})
}
})
t.throws(fetch, /app is required/)
t.throws(fetch.bind(null, {}), /path is required/)
fetch({host: 'host.co', headers: {foo: 'bar'}}, '/path?page=2', function noop () {})
})
|
'use strict'
const test = require('tape')
const proxyquire = require('proxyquire')
test('fetch', function (t) {
t.plan(4)
const fetch = proxyquire('./fetch', {
'simple-get': function (options, callback) {
t.deepEqual(options, {
url: 'https://host.co/path?page=2',
headers: {
foo: 'bar'
}
})
callback()
}
})
t.throws(fetch, /app is required/)
t.throws(fetch.bind(null, {}), /path is required/)
fetch({host: 'host.co', headers: {foo: 'bar'}}, '/path?page=2', t.pass)
})
|
Replace noop w/ t.pass to assert call
|
Replace noop w/ t.pass to assert call
|
JavaScript
|
mit
|
bendrucker/http-app-router
|
53f0ee1ff11a92122bd905d587f88abc696b40de
|
test/index.js
|
test/index.js
|
import co from 'co';
import test from 'blue-tape';
import agent from 'promisify-supertest';
import createApplication from '../src';
const setup = () => {
return agent(createApplication().callback());
};
test('GET /', (sub) => {
sub.test('responds with OK status code', co.wrap(function* (assert) {
const app = setup();
yield app
.get('/')
.expect((response) => {
assert.equal(response.statusCode, 200, 'status code should be 200');
})
.end();
}));
});
|
/* eslint-disable func-names, no-use-before-define */
import co from 'co';
import test from 'blue-tape';
import agent from 'promisify-supertest';
import createApplication from '../src';
const setup = () => {
return agent(createApplication().callback());
};
test('GET /', (sub) => {
sub.test('responds with OK status code', co.wrap(function* (assert) {
const app = setup();
yield app
.get('/')
.expect(statusCodeToBeOk)
.end();
function statusCodeToBeOk({statusCode}) {
const okStatusCode = 200;
assert.equal(statusCode, okStatusCode, 'should be status OK');
}
}));
});
|
Refactor root route test for readability.
|
Refactor root route test for readability.
|
JavaScript
|
isc
|
francisbrito/let-go-hold-on-api
|
3052a38676e0c1066dfa145cc29370b762d6ea5b
|
test/rSpec.js
|
test/rSpec.js
|
const
r = require('../'),
expect = require('chai').expect;
describe('RemoveTabs', function(){
it('should have not tabs.', function(){
var tests = [
r` remove
tabs`,
r` remove
tabs
tabs`,
r`
remove
tabs`
];
var expected = [
'remove\ntabs',
'remove\n\ttabs\n\t\ttabs',
'remove\ntabs'
];
for(var i = 0 ; i < tests.length ; i++) {
expect(tests[i]).to.equal(expected[i]);
}
})
})
|
const
r = require('../'),
expect = require('chai').expect;
describe('RemoveTabs', function(){
it('should have not tabs.', function(){
var tests = [
r` remove
tabs`,
r` remove
tabs
tabs`,
r`
remove
tabs`,
r`
remove
remove
tabs
tabs`,
r`remove${'\r\n\t'}tabs${'\r\n\t\t'}tabs`, //window
r`
${'remove'}
${'tabs'}
${'tabs'}`
];
var expected = [
'remove\ntabs',
'remove\n\ttabs\n\t\ttabs',
'remove\ntabs',
'remove\nremove\n\ttabs\n\t\ttabs',
'remove\n\ttabs\n\t\ttabs',
'remove\n\ttabs\n\t\ttabs',
];
for(var i = 0 ; i < tests.length ; i++) {
expect(tests[i]).to.equal(expected[i]);
}
})
})
|
Add test specs for interpolations.
|
Add test specs for interpolations.
|
JavaScript
|
mit
|
Wooooo/remove-tabs
|
fa2a3f0c689a6cedc86452665c338935a5b95574
|
src/javascript/binary/websocket_pages/user/new_account/virtual_acc_opening/virtual_acc_opening.data.js
|
src/javascript/binary/websocket_pages/user/new_account/virtual_acc_opening/virtual_acc_opening.data.js
|
var VirtualAccOpeningData = (function(){
"use strict";
function getDetails(password, residence, verificationCode){
var req = {
new_account_virtual: 1,
client_password: password,
residence: residence,
verification_code: verificationCode
};
if ($.cookie('affiliate_tracking')) {
req.affiliate_token = JSON.parse($.cookie('affiliate_tracking')).t;
}
BinarySocket.send(req);
}
return {
getDetails: getDetails
};
}());
|
var VirtualAccOpeningData = (function(){
"use strict";
function getDetails(password, residence, verificationCode){
var req = {
new_account_virtual: 1,
client_password: password,
residence: residence,
verification_code: verificationCode
};
// Add AdWords parameters
// NOTE: following lines can be uncommented (Re-check property names)
// once these fields added to this ws call
// var utm_data = AdWords.getData();
// req.source = utm_data.utm_source || utm_data.referrer || 'direct';
// if(utm_data.utm_medium) req.medium = utm_data.utm_medium;
// if(utm_data.utm_campaign) req.campaign = utm_data.utm_campaign;
if ($.cookie('affiliate_tracking')) {
req.affiliate_token = JSON.parse($.cookie('affiliate_tracking')).t;
}
BinarySocket.send(req);
}
return {
getDetails: getDetails
};
}());
|
Send source information on virtual account opening
|
Send source information on virtual account opening
|
JavaScript
|
apache-2.0
|
teo-binary/binary-static,binary-com/binary-static,ashkanx/binary-static,binary-static-deployed/binary-static,binary-static-deployed/binary-static,teo-binary/binary-static,binary-com/binary-static,negar-binary/binary-static,kellybinary/binary-static,raunakkathuria/binary-static,fayland/binary-static,teo-binary/binary-static,binary-static-deployed/binary-static,kellybinary/binary-static,fayland/binary-static,4p00rv/binary-static,kellybinary/binary-static,teo-binary/binary-static,negar-binary/binary-static,fayland/binary-static,ashkanx/binary-static,raunakkathuria/binary-static,4p00rv/binary-static,binary-com/binary-static,4p00rv/binary-static,fayland/binary-static,raunakkathuria/binary-static,ashkanx/binary-static,negar-binary/binary-static
|
40bb555785978dcf6ac287aa10d6be6c17cf31e4
|
tests/src/test/javascript/components/basic/propvalidator.spec.js
|
tests/src/test/javascript/components/basic/propvalidator.spec.js
|
import {expect} from 'chai'
import chai from 'chai'
import spies from 'chai-spies'
import {
createAndMountComponent, destroyComponent, onGwtReady,
onNextTick
} from '../../vue-gwt-tests-utils'
describe('@PropValidator', () => {
let component;
beforeEach(() => onGwtReady().then(() => {
chai.use(spies);
chai.spy.on(console, 'error');
component = createAndMountComponent(
'com.axellience.vuegwt.tests.client.components.basic.propvalidator.PropValidatorParentTestComponent');
}));
afterEach(() => {
chai.spy.restore(console);
destroyComponent(component);
});
it('should not fire an error if the value is correct', () => {
component.validatedPropParent = 6;
return onNextTick(() => {
expect(console.error).to.not.have.been.called();
});
});
it('should fire an error if the value is incorrect', () => {
component.validatedPropParent = 106;
return onNextTick(() => {
expect(console.error).to.have.been.called.once;
});
});
});
|
import {expect} from 'chai'
import chai from 'chai'
import spies from 'chai-spies'
import {
createAndMountComponent, destroyComponent, onGwtReady,
onNextTick
} from '../../vue-gwt-tests-utils'
describe('@PropValidator', () => {
let component;
beforeEach(() => onGwtReady().then(() => {
chai.use(spies);
chai.spy.on(console, 'error');
component = createAndMountComponent(
'com.axellience.vuegwt.tests.client.components.basic.propvalidator.PropValidatorParentTestComponent');
}));
afterEach(() => {
chai.spy.restore(console);
destroyComponent(component);
});
it('should not fire an error if the value is correct', () => {
component.validatedPropParent = 6;
return onNextTick(() => {
expect(console.error).to.not.have.been.called();
});
});
it('should fire an error if the value is incorrect in dev mode', () => {
if (Vue.config.productionTip === true) {
component.validatedPropParent = 106;
return onNextTick(() => {
expect(console.error).to.have.been.called.once;
});
}
});
it('should not fire an error if the value is incorrect in production mode', () => {
if (Vue.config.productionTip === false) {
component.validatedPropParent = 106;
return onNextTick(() => {
expect(console.error).to.not.have.been.called();
});
}
});
});
|
Fix PropValidator test to work with Vue in production mode
|
Fix PropValidator test to work with Vue in production mode
PropValidator are only used in dev mode so the test should be ignored
when running Vue in production mode.
|
JavaScript
|
mit
|
Axellience/vue-gwt,Axellience/vue-gwt,Axellience/vue-gwt,Axellience/vue-gwt
|
c218e3ab8e4604b6949ba02deb7a5f1c0b9e32d7
|
fun-script.js
|
fun-script.js
|
#!/usr/bin/env node
var fs = require('fs')
var max = process.argv[2]
playGame()
function playGame() {
var usedNumbers = []
var number = getRandomNumber(max)
while (!isNewNumber(usedNumbers, number)) {
number = getRandomNumber(max)
}
fs.writeFile(process.cwd() + '/_data/numbers/' + number + '.json', '', function done (err) {
if (err) return
console.log(number)
usedNumbers.push(number)
setTimeout(playGame, 5000)
})
function isNewNumber (usedNumbers, number) {
if (usedNumbers.indexOf(number) === -1 && number != 0) {
return true
}
}
function getRandomNumber(max) {
return Math.round(Math.random() * max)
}
}
|
#!/usr/bin/env node
var fs = require('fs')
var max = process.argv[2]
var usedNumbers = []
playGame()
function playGame() {
var number = getRandomNumber(max)
while (!isNewNumber(number)) {
number = getRandomNumber(max)
}
fs.writeFile(process.cwd() + '/_data/numbers/' + number + '.json', '', function done (err) {
if (err) return
console.log(number)
usedNumbers.push(number)
setTimeout(playGame, 5000)
})
function isNewNumber (number) {
if (usedNumbers.indexOf(number) === -1 && number != 0) {
return true
}
}
function getRandomNumber(max) {
return Math.round(Math.random() * max)
}
}
|
Fix usedNumber bring resetted back to empty
|
Fix usedNumber bring resetted back to empty
|
JavaScript
|
mit
|
muan/bingo-board,jlord/bingo-board,muan/bingo-board,jlord/bingo-board
|
879626e9f315dc6069112a82f8b175660e1ff9f7
|
src/setupJest.js
|
src/setupJest.js
|
window.fetch = require('jest-fetch-mock');
// Mock the Date object and allows us to use Date.now() and get a consistent date back
const mockedCurrentDate = new Date("2017-10-06T13:45:28.975Z");
require('jest-mock-now')(mockedCurrentDate);
// Mock document functions (specifically for the CollectionsController component)
const mockedGetElement = () => ({
getBoundingClientRect: () => ({
top: 0
}),
scrollTop: 0
});
Object.defineProperty(document, 'getElementById', {
value: mockedGetElement,
});
|
window.fetch = require('jest-fetch-mock');
// Mock the Date object and allows us to use Date.now() and get a consistent date back
const mockedCurrentDate = new Date("2017-10-06T13:45:28.975Z");
require('jest-mock-now')(mockedCurrentDate);
// Mock document functions (specifically for the CollectionsController component)
const mockedGetElement = () => ({
getBoundingClientRect: () => ({
top: 0
}),
scrollTop: 0,
scrollIntoView: () => {}
});
Object.defineProperty(document, 'getElementById', {
value: mockedGetElement,
});
|
Fix breaking unit tests due to missing mock of scrollIntoView function
|
Fix breaking unit tests due to missing mock of scrollIntoView function
Former-commit-id: fe6fd28df36626f4bb8efab9ba4a8c6c42cb2f5e
Former-commit-id: ddf9c74bc8fa09ec14d3ec518ac7da745cfe3731
Former-commit-id: d14b02918458ccf1d54bb4bcf50faa0b4d487eef
|
JavaScript
|
mit
|
ONSdigital/florence,ONSdigital/florence,ONSdigital/florence,ONSdigital/florence
|
85108314aa89b401d505d047c070f51d5307ccc6
|
test/cli/myrmex-cheers.integ.js
|
test/cli/myrmex-cheers.integ.js
|
/*eslint-env mocha */
'use strict';
const assert = require('assert');
const icli = require('../../packages/cli/src/bin/myrmex');
const showStdout = !!process.env.MYRMEX_SHOW_STDOUT;
describe('The "cheers" sub-command', () => {
before(() => {
process.chdir(__dirname);
});
beforeEach(() => {
return icli.init();
});
it('should display a beer', () => {
icli.catchPrintStart(showStdout);
return icli.parse('node script.js cheers'.split(' '))
.then(res => {
const stdout = icli.catchPrintStop();
assert.ok(stdout.indexOf('language: ') > -1);
assert.ok(stdout.indexOf('font: ') > -1);
});
});
it('should allow to select a language and a font', () => {
icli.catchPrintStart(showStdout);
return icli.parse('node script.js cheers -l french -f Binary'.split(' '))
.then(res => {
const stdout = icli.catchPrintStop();
assert.ok(stdout.indexOf('language: french') > -1);
assert.ok(stdout.indexOf('font: Binary') > -1);
assert.ok(stdout.indexOf('01010011 01100001 01101110 01110100 01100101') > -1);
});
});
});
|
/*eslint-env mocha */
'use strict';
const assert = require('assert');
const icli = require('../../packages/cli/src/bin/myrmex');
const showStdout = !!process.env.MYRMEX_SHOW_STDOUT;
describe('The "cheers" sub-command', () => {
before(() => {
process.chdir(__dirname);
});
beforeEach(() => {
return icli.init();
});
it('should display a beer', () => {
icli.catchPrintStart(showStdout);
return icli.parse('node script.js cheers'.split(' '))
.then(res => {
const stdout = icli.catchPrintStop();
assert.ok(stdout.indexOf('language: ') > -1);
assert.ok(stdout.indexOf('font: ') > -1);
});
});
it('should allow to select a language and a font', () => {
icli.catchPrintStart(showStdout);
return icli.parse('node script.js cheers -l french -f Binary'.split(' '))
.then(res => {
const stdout = icli.catchPrintStop();
assert.ok(stdout.indexOf('language: french') > -1);
assert.ok(stdout.indexOf('font: Binary') > -1);
// Disable assertion because of travis execution context
// assert.ok(stdout.indexOf('01010011 01100001 01101110 01110100 01100101') > -1);
});
});
});
|
Fix test for travis execution context
|
Fix test for travis execution context
|
JavaScript
|
mit
|
myrmex-org/myrmex,myrmex-org/myrmex,lagerjs/lager,myrmex-org/myrmex,myrmx/myrmex,myrmx/myrmex,lagerjs/lager,myrmx/myrmex,myrmx/myrmex,lagerjs/lager,myrmex-org/myrmex,lagerjs/lager
|
2c033eb71202c709bdbd45f4a64909b4b83e28be
|
lib/Avatar.js
|
lib/Avatar.js
|
import React, { Component, PropTypes, View, Image } from 'react-native';
import Icon from './Icon';
import { ICON_NAME } from './config';
export default class Avatar extends Component {
static propTypes = {
icon: PropTypes.string,
src: PropTypes.string,
size: PropTypes.number,
color: PropTypes.string,
backgroundColor: PropTypes.string
};
static defaultProps = {
size: 40,
color: '#ffffff',
backgroundColor: '#bdbdbd'
};
render() {
const { icon, src, size, color, backgroundColor } = this.props;
if (src) {
return (
<Image
style={{ width: size, height: size, borderRadius: size / 2, borderColor: 'rgba(0,0,0,.1)', borderWidth: 1 }}
source={{ uri: src }}
/>
);
}
if (icon) {
return (
<View style={{ flex: 1 }}>
<View style={{ width: size, height: size, borderRadius: size / 2, backgroundColor: backgroundColor, alignItems:'center' }}>
<Icon name={icon} color={color} size={0.6 * size} style={{ position: 'relative', top: -3 }} />
</View>
</View>
);
}
}
}
|
import React, { Component, PropTypes, View, Image } from 'react-native';
import Icon from './Icon';
import { getColor } from './helpers';
export default class Avatar extends Component {
static propTypes = {
icon: PropTypes.string,
src: PropTypes.string,
size: PropTypes.number,
color: PropTypes.string,
backgroundColor: PropTypes.string
};
static defaultProps = {
size: 40,
color: '#ffffff',
backgroundColor: getColor('paperGrey500')
};
render() {
const { icon, src, size, color, backgroundColor } = this.props;
if (src) {
return (
<Image
style={{ width: size, height: size, borderRadius: size / 2, borderColor: 'rgba(0,0,0,.1)', borderWidth: 1 }}
source={{ uri: src }}
/>
);
}
if (icon) {
return (
<View style={{ flex: 1 }}>
<View style={{ width: size, height: size, borderRadius: size / 2, backgroundColor: getColor(backgroundColor), alignItems:'center' }}>
<Icon
name={icon}
color={color}
size={0.6 * size}
style={{
position: 'relative',
top: -3
}}
/>
</View>
</View>
);
}
}
}
|
Update default background color & formatting updates
|
Update default background color & formatting updates
|
JavaScript
|
mit
|
kenma9123/react-native-material-ui,blovato/sca-mobile-components,xotahal/react-native-material-ui,react-native-material-design/react-native-material-design,xvonabur/react-native-material-ui,thomasooo/react-native-material-design,ajaxangular/react-native-material-ui,mobileDevNativeCross/react-native-material-ui
|
6125f7cbbba04208cf4836539ca4f596a6cd6c93
|
test/helpers_test.js
|
test/helpers_test.js
|
/* vim: ts=4:sw=4
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
'use strict';
describe("Helpers", function() {
describe("ArrayBuffer->String conversion", function() {
it('works', function() {
var b = new ArrayBuffer(3);
var a = new Uint8Array(b);
a[0] = 0;
a[1] = 255;
a[2] = 128;
assert.equal(getString(b), "\x00\xff\x80");
});
});
});
|
/* vim: ts=4:sw=4
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
'use strict';
describe("Helpers", function() {
describe("ArrayBuffer->String conversion", function() {
it('works', function() {
var b = new ArrayBuffer(3);
var a = new Uint8Array(b);
a[0] = 0;
a[1] = 255;
a[2] = 128;
assert.equal(getString(b), "\x00\xff\x80");
});
});
describe("toArrayBuffer", function() {
it('returns undefined when passed undefined', function() {
assert.strictEqual(toArrayBuffer(undefined), undefined);
});
it('returns ArrayBuffer when passed ArrayBuffer', function() {
var StaticArrayBufferProto = new ArrayBuffer().__proto__;
var anArrayBuffer = new ArrayBuffer();
assert.strictEqual(toArrayBuffer(anArrayBuffer), anArrayBuffer);
});
it('throws an error when passed a non Stringable thing', function() {
var madeUpObject = function() {};
var notStringable = new madeUpObject();
assert.throw(function() { toArrayBuffer(notStringable) },
Error, /Tried to convert a non-stringable thing/);
});
});
});
|
Add basic test coverage of toArrayBuffer function
|
Add basic test coverage of toArrayBuffer function
|
JavaScript
|
agpl-3.0
|
nrizzio/Signal-Desktop,nrizzio/Signal-Desktop,nrizzio/Signal-Desktop,nrizzio/Signal-Desktop
|
0e7fb78882f5b0e78d3f544857d86717fead0cdb
|
Renderer/canvas-drawer.js
|
Renderer/canvas-drawer.js
|
var CanvasDrawer = (function () {
var CanvasDrawer = function (params) {
};
CanvasDrawer.prototype = {
drawPlayer: {
value: function (player) {
}
},
drawDisc :{
value: function (disc) {
}
}
}
}());
|
var CanvasDrawer = (function () {
var CanvasDrawer = function (params) {
var canvas = document.getElementById("canvas-field");
this.ctx = canvas.getContext("2d");
this.canvasWidth = canvas.width;
this.canvasHeight = canvas.height;
};
CanvasDrawer.prototype = {
drawPlayer: function (player) {
this.ctx.beginPath();
this.ctx.arc(player.x, player.y, player.radius, 0, 2 * Math.PI);
//this.ctx.drawImage(player.image, player.x - player.image.width / 2,
// player.y - player.radius, this.ctx.canvas.height / 15, this.ctx.canvas.height / 15);
this.ctx.fillStyle = 'red';
this.ctx.fill();
},
clear: function () {
this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
},
drawDisc: function (disc) {
this.ctx.beginPath();
this.ctx.arc(disc.x, disc.y, disc.radius, 0, 2 * Math.PI);
this.ctx.fillStyle = 'yellowgreen';
this.ctx.fill();
this.ctx.strokeStyle = 'black';
this.ctx.stroke();
}
};
return CanvasDrawer;
}());
|
Add implement CanvasDrawer witch draw player and disc
|
Add implement CanvasDrawer witch draw player and disc
|
JavaScript
|
mit
|
TeamBarracuda-Telerik/JustDiscBattle,TeamBarracuda-Telerik/JustDiscBattle
|
ff58d6e6788382e2468994f9550bcc1e8d103e49
|
utils/network-timing.js
|
utils/network-timing.js
|
const {hasAdRequestPath, isImplTag} = require('./resource-classification');
const {URL} = require('url');
/**
* Returns end time of tag load (s) relative to system boot.
* @param {LH.Artifacts.NetworkRequest[]} networkRecords
* @return {number}
*/
function getTagEndTime(networkRecords) {
const tagRecord = networkRecords.find(
(record) => isImplTag(new URL(record.url)));
return tagRecord ? tagRecord.endTime : -1;
}
/**
* Returns start time of first ad request (s) relative to system boot.
* @param {LH.Artifacts.NetworkRequest[]} networkRecords
* @return {number}
*/
function getAdStartTime(networkRecords) {
const firstAdRecord = networkRecords.find(
(record) => hasAdRequestPath(new URL(record.url)));
return firstAdRecord ? firstAdRecord.startTime : -1;
}
/**
* Returns start time of page load (s) relative to system boot.
* @param {LH.Artifacts.NetworkRequest[]} networkRecords
* @return {number}
*/
function getPageStartTime(networkRecords) {
const fistSuccessRecord = networkRecords.find(
(record) => record.statusCode == 200);
return fistSuccessRecord ? fistSuccessRecord.startTime : -1;
}
module.exports = {
getTagEndTime,
getAdStartTime,
getPageStartTime,
};
|
const {hasAdRequestPath, isImplTag} = require('./resource-classification');
const {URL} = require('url');
/**
* Returns end time of tag load (s) relative to system boot.
* @param {LH.Artifacts.NetworkRequest[]} networkRecords
* @return {number}
*/
function getTagEndTime(networkRecords) {
const tagRecord = networkRecords.find(
(record) => isImplTag(new URL(record.url)));
return tagRecord ? tagRecord.endTime : -1;
}
/**
* Returns start time of first ad request (s) relative to system boot.
* @param {LH.Artifacts.NetworkRequest[]} networkRecords
* @return {number}
*/
function getAdStartTime(networkRecords) {
const firstAdRecord = networkRecords.find(
(record) => hasAdRequestPath(new URL(record.url)));
return firstAdRecord ? firstAdRecord.startTime : -1;
}
/**
* Returns start time of page load (s) relative to system boot.
* @param {LH.Artifacts.NetworkRequest[]} networkRecords
* @param {number=} defaultValue
* @return {number}
*/
function getPageStartTime(networkRecords, defaultValue = -1) {
const fistSuccessRecord = networkRecords.find(
(record) => record.statusCode == 200);
return fistSuccessRecord ? fistSuccessRecord.startTime : defaultValue;
}
module.exports = {
getTagEndTime,
getAdStartTime,
getPageStartTime,
};
|
Include defaultValue in getPageStartTime function.
|
Include defaultValue in getPageStartTime function.
Change-Id: Ib25db9f76263ffcb907f1c04edb90e1c2c65e4cf
|
JavaScript
|
apache-2.0
|
googleads/publisher-ads-lighthouse-plugin,googleads/publisher-ads-lighthouse-plugin
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.