commit
stringlengths
40
40
old_file
stringlengths
4
264
new_file
stringlengths
4
264
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
624
message
stringlengths
15
4.7k
lang
stringclasses
3 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
d70cfc735c3fdaf9c65c6bd6fa27f9ec6f9ea2de
test/package.js
test/package.js
import fs from 'fs'; import test from 'ava'; import pify from 'pify'; import index from '../'; test('Every rule is defined in index file', async t => { const files = await pify(fs.readdir, Promise)('../rules/'); const rules = files.filter(file => file.indexOf('.js') === file.length - 3); rules.forEach(file => { const name = file.slice(0, -3); t.truthy(index.rules[name], `'${name}' is not exported in 'index.js'`); t.truthy(index.configs.recommended.rules[`fp/${name}`], `'${name}' is not set in the recommended config`); }); t.is(Object.keys(index.rules).length, rules.length, 'There are more exported rules than rule files.'); });
import fs from 'fs'; import test from 'ava'; import pify from 'pify'; import index from '../'; test('every rule should defined in the index file and recommended settings', async t => { const files = await pify(fs.readdir, Promise)('../rules/'); const rules = files.filter(file => file.indexOf('.js') === file.length - 3); rules.forEach(file => { const name = file.slice(0, -3); t.truthy(index.rules[name], `'${name}' is not exported in 'index.js'`); t.truthy(index.configs.recommended.rules[`fp/${name}`], `'${name}' is not set in the recommended config`); }); t.is(Object.keys(index.rules).length, rules.length, 'There are more exported rules than rule files.'); }); test('no-var should be turned on in the recommended settings', async t => { t.true(index.configs.recommended.rules['no-var'] === 'error'); });
Add test to make sure `no-var` is in the recommended config
Add test to make sure `no-var` is in the recommended config
JavaScript
mit
eslint-plugin-cleanjs/eslint-plugin-cleanjs,jfmengels/eslint-plugin-fp
4af27a810903abd4ec127f9b0799f9dc02674a91
source/demo/demo.js
source/demo/demo.js
import React from 'react' import { render } from 'react-dom' import FlexTableExample from '../FlexTable/FlexTable.example' import VirtualScrollExample from '../VirtualScroll/VirtualScroll.example' require('./demo.less') render(( <div className='demo__row'> <VirtualScrollExample/> <FlexTableExample/> </div> ), document.getElementById('root') )
import React from 'react' import { render } from 'react-dom' import FlexTableExample from '../FlexTable/FlexTable.example' import VirtualScrollExample from '../VirtualScroll/VirtualScroll.example' import './demo.less' render(( <div className='demo__row'> <VirtualScrollExample/> <FlexTableExample/> </div> ), document.getElementById('root') )
Use ES6 style modules for consistency
Use ES6 style modules for consistency
JavaScript
mit
bvaughn/react-virtualized,nicholasrq/react-virtualized,cesarandreu/react-virtualized,edulan/react-virtualized,cesarandreu/react-virtualized,nicholasrq/react-virtualized,edulan/react-virtualized,bvaughn/react-virtualized
1012fb705859f61eb097f34a258050b837a593df
core/cb.project/parse/index.js
core/cb.project/parse/index.js
var path = require("path"); module.exports = { id: "parse", name: "Parse", sample: path.resolve(__dirname, "sample"), detector: path.resolve(__dirname, "detector.sh"), runner: [ { id: "run", script: path.resolve(__dirname, "run.sh") } ] };
var path = require("path"); module.exports = { id: "parse", name: "Parse", otherIds: ["mobile"], sample: path.resolve(__dirname, "sample"), detector: path.resolve(__dirname, "detector.sh"), runner: [ { id: "run", script: path.resolve(__dirname, "run.sh") } ] };
Add id of mobile stack to parse sample
Add id of mobile stack to parse sample
JavaScript
apache-2.0
kustomzone/codebox,CodeboxIDE/codebox,rodrigues-daniel/codebox,smallbal/codebox,ronoaldo/codebox,Ckai1991/codebox,lcamilo15/codebox,LogeshEswar/codebox,quietdog/codebox,Ckai1991/codebox,blubrackets/codebox,rajthilakmca/codebox,blubrackets/codebox,ronoaldo/codebox,nobutakaoshiro/codebox,smallbal/codebox,listepo/codebox,listepo/codebox,code-box/codebox,lcamilo15/codebox,ahmadassaf/Codebox,kustomzone/codebox,fly19890211/codebox,fly19890211/codebox,indykish/codebox,quietdog/codebox,indykish/codebox,etopian/codebox,CodeboxIDE/codebox,rodrigues-daniel/codebox,code-box/codebox,ahmadassaf/Codebox,nobutakaoshiro/codebox,etopian/codebox,LogeshEswar/codebox,rajthilakmca/codebox
c8fa6d7743e990f9b943ec045cada74403944d72
lib/webhook.js
lib/webhook.js
/* * Copyright (c) 2014-2020 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ const request = require('request') const colors = require('colors/safe') const logger = require('../lib/logger') const utils = require('../lib/utils') const os = require('os') const config = require('config') exports.notify = (challenge) => { request.post(process.env.SOLUTIONS_WEBHOOK, { json: { solution: { issuer: `owasp_juiceshop-${utils.version()}@${os.hostname()}`, challenge: challenge.key, evidence: null, issuedOn: new Date().toISOString() } } }, (error, res) => { if (error) { console.error(error) return } logger.info(`Webhook ${colors.bold(process.env.SOLUTIONS_WEBHOOK)} notified about ${colors.cyan(challenge.key)} being solved: ${res.statusCode < 400 ? colors.green(res.statusCode) : colors.red(res.statusCode)}`) }) }
/* * Copyright (c) 2014-2020 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ const request = require('request') const colors = require('colors/safe') const logger = require('../lib/logger') const utils = require('../lib/utils') const os = require('os') exports.notify = (challenge) => { request.post(process.env.SOLUTIONS_WEBHOOK, { json: { solution: { issuer: `owasp_juiceshop-${utils.version()}@${os.hostname()}`, challenge: challenge.key, evidence: null, issuedOn: new Date().toISOString() } } }, (error, res) => { if (error) { console.error(error) return } logger.info(`Webhook ${colors.bold(process.env.SOLUTIONS_WEBHOOK)} notified about ${colors.cyan(challenge.key)} being solved: ${res.statusCode < 400 ? colors.green(res.statusCode) : colors.red(res.statusCode)}`) }) }
Remove unused config module import
Remove unused config module import
JavaScript
mit
bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop
f182bb037d49003a42cc8fefa10d849b1145b15a
src/app/components/msp/application/personal-info/i18n/data/en/index.js
src/app/components/msp/application/personal-info/i18n/data/en/index.js
module.exports = { pageTitle: 'Tell us a bit about who is applying for health care coverage', addSpouseButton: 'Add Spouse/Common-Law Partner', addChildUnder19Button: 'Add Child (0-18)', addChild19To24Button: 'Add Child (19-24)', continueButton: 'Continue' }
module.exports = { pageTitle: 'Tell us a bit about who is applying for health care coverage', addSpouseButton: 'Add Spouse/Common-Law Partner', addChildUnder19Button: 'Add Child (0-18)', addChild19To24Button: 'Add Child (19-24) who is a full-time student', continueButton: 'Continue' }
Clarify student status of older children
Clarify student status of older children Re: MoH legal feedback
JavaScript
apache-2.0
bcgov/MyGovBC-MSP,bcgov/MyGovBC-MSP,bcgov/MyGovBC-MSP,bcgov/MyGovBC-MSP
62513397441fd0af5614a18e4cb6037479b744f2
models/User.js
models/User.js
'use strict'; var bcrypt = require('bcrypt'); var mongoose = require('mongoose'); var Schema = mongoose.Schema; // export a mongoose model var userSchema = new Schema({ userName : String, passwordDigest : String }); userSchema.virtual('password').set(function(password) { var self = this; var saltPromise = new Promise(function saltExec(res, rej) { bcrypt.genSalt(16, function(err, salt) { if(err) { rej(err); return; } res(salt); }); }); var returnedPromise = saltPromise.then(function(salt) { return new Promise(function hashExec(res, rej) { bcrypt.hash(password, salt, function(err, digest) { if(err) { rej(err); return; } res(digest); }); }); }).then(function(digest) { self.passwordDigest = digest; }); return returnedPromise; }); module.exports = userSchema;
'use strict'; var bcrypt = require('bcrypt'); var mongoose = require('mongoose'); var Schema = mongoose.Schema; // export a mongoose model var userSchema = new Schema({ userName : String, passwordDigest : String }); userSchema.methods.setPassword = function(password) { var self = this; var saltPromise = new Promise(function saltExec(res, rej) { bcrypt.genSalt(16, function(err, salt) { if(err) { rej(err); return; } res(salt); }); }); var returnedPromise = saltPromise.then(function(salt) { return new Promise(function hashExec(res, rej) { bcrypt.hash(password, salt, function(err, digest) { if(err) { rej(err); return; } res(digest); }); }); }).then(function(digest) { self.passwordDigest = digest; return self.save(); }); return returnedPromise; }; module.exports = userSchema;
Change virtual prop to an instance method
Change virtual prop to an instance method
JavaScript
mit
dhuddell/teachers-lounge-back-end
1810afeeeb0f678d6968f8849a1932a547e966eb
test/test_ss.js
test/test_ss.js
/*global seqJS:true */ (function() { /* ======== A Handy Little QUnit Reference ======== http://api.qunitjs.com/ Test methods: module(name, {[setup][ ,teardown]}) test(name, callback) expect(numberOfequalions) stop(increment) start(decrement) Test equalions: ok(value, [message]) equal(actual, expected, [message]) notEqual(actual, expected, [message]) deepEqual(actual, expected, [message]) notDeepEqual(actual, expected, [message]) strictEqual(actual, expected, [message]) notStrictEqual(actual, expected, [message]) throws(block, [expected], [message]) */ module('seqJS.ss'); test('Test ss', function(){ equal(seqJS.ss.predict('GGGAAATCC'), '.(((..)))', 'secondary structure incorrect'); }); }());
/*global seqJS:true */ (function() { /* ======== A Handy Little QUnit Reference ======== http://api.qunitjs.com/ Test methods: module(name, {[setup][ ,teardown]}) test(name, callback) expect(numberOfequalions) stop(increment) start(decrement) Test equalions: ok(value, [message]) equal(actual, expected, [message]) notEqual(actual, expected, [message]) deepEqual(actual, expected, [message]) notDeepEqual(actual, expected, [message]) strictEqual(actual, expected, [message]) notStrictEqual(actual, expected, [message]) throws(block, [expected], [message]) */ module('seqJS.ss'); test('Test ss', function(){ var s = new seqJS.Seq('GGGAAATCC', 'DNA'); equal(seqJS.ss.predict(s), '.(((..)))', 'secondary structure incorrect'); }); }());
Test passes a seqJS.Seq, not String
Test passes a seqJS.Seq, not String
JavaScript
mit
haydnKing/seqJS,haydnKing/seqJS
86b1e11b31c57bf51dd779c8ffc7e8ad5803de9a
client/src/views/member.js
client/src/views/member.js
_kiwi.view.Member = Backbone.View.extend({ tagName: "li", initialize: function (options) { this.model.bind('change', this.render, this); this.render(); }, render: function () { var $this = this.$el, prefix_css_class = (this.model.get('modes') || []).join(' '), max_prefix = (this.model.get('modes') || [])[0]; $this.attr('class', 'mode ' + prefix_css_class + ' member member-' + max_prefix); $this.html('<a class="nick"><span class="prefix prefix-' + max_prefix + '">' + this.model.get("prefix") + '</span>' + this.model.get("nick") + '</a>'); return this; } });
_kiwi.view.Member = Backbone.View.extend({ tagName: "li", initialize: function (options) { this.model.bind('change', this.render, this); this.render(); }, render: function () { var $this = this.$el, max_prefix = (this.model.get('modes') || [])[0]; $this.attr('class', 'member member-' + max_prefix); $this.html('<a class="nick"><span class="prefix prefix-' + max_prefix + '">' + this.model.get("prefix") + '</span>' + this.model.get("nick") + '</a>'); return this; } });
Remove old CSS classes (breaks stuff)
Remove old CSS classes (breaks stuff)
JavaScript
agpl-3.0
MDTech-us-MAN/KiwiIRC,MDTech-us-MAN/KiwiIRC,MDTech-us-MAN/KiwiIRC
53cf51e0c7671750985ee2b88ddf51905897d9c7
node/server.js
node/server.js
var mongo = require('mongodb').MongoClient; mongo.connect('mongodb://localhost:27017/akkavsnode', function(err, db) { var http = require('http'); http.createServer(function (req, res) { if (req.url === '/api/user') { var i = Math.ceil(Math.random() * 10000); db.collection('users').findOne({ name: 'user-' + i }, function (err, user) { res.writeHead(200, {'Content-Type': 'application/json'}); res.end(JSON.stringify(user)); }); } else { res.writeHead(404, {'Content-Type': 'application/json'}); res.end(); } }).listen(8081, '0.0.0.0'); });
var mongo = require('mongodb').MongoClient; mongo.connect('mongodb://localhost:27017/akkavsnode', function(err, db) { var http = require('http'); http.createServer(function (req, res) { if (req.url === '/api/user') { var i = Math.ceil(Math.random() * 10000); db.collection('users').findOne({ name: 'user-' + i }, function (err, user) { res.writeHead(200, {'Content-Type': 'application/json'}); res.end(JSON.stringify(user, true, 2)); }); } else { res.writeHead(404, {'Content-Type': 'application/json'}); res.end(); } }).listen(8081, '0.0.0.0'); });
Make node also response with pretty JSON
Make node also response with pretty JSON
JavaScript
mit
choffmeister/akka-vs-node,choffmeister/akka-vs-node
e01ceaf62d2ee3dbdb7cce9988a55742c348bd31
client/karma.conf.js
client/karma.conf.js
// Karma configuration file, see link for more information // https://karma-runner.github.io/1.0/config/configuration-file.html module.exports = function (config) { var configuration = { basePath: '', frameworks: ['jasmine', '@angular/cli'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage-istanbul-reporter'), require('@angular/cli/plugins/karma') ], client:{ clearContext: false // leave Jasmine Spec Runner output visible in browser }, coverageIstanbulReporter: { reports: [ 'html', 'lcovonly' ], fixWebpackSourcePaths: true }, angularCli: { environment: 'dev' }, reporters: ['progress', 'kjhtml'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, customLaunchers: { ChromeHeadless: { base: 'Chrome', flags: [ '--headless', '--disable-gpu', '--remote-debugging-port=9222', '--no-sandbox' ] } }, browsers: ['Chrome'], singleRun: false }; if (process.env.TRAVIS) { configuration.autoWatch = false; configuration.browsers = ['ChromeHeadless']; } config.set(configuration); };
// Karma configuration file, see link for more information // https://karma-runner.github.io/1.0/config/configuration-file.html module.exports = function (config) { var configuration = { basePath: '', frameworks: ['jasmine', '@angular/cli'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage-istanbul-reporter'), require('@angular/cli/plugins/karma') ], client:{ clearContext: false // leave Jasmine Spec Runner output visible in browser }, coverageIstanbulReporter: { reports: [ 'html', 'lcovonly' ], fixWebpackSourcePaths: true }, angularCli: { environment: 'dev' }, reporters: ['progress', 'kjhtml'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, customLaunchers: { ChromeHeadless: { base: 'Chrome', flags: [ '--headless', '--disable-gpu', '--remote-debugging-port=9222', '--no-sandbox' ] } }, browsers: ['Chrome'], singleRun: false }; if (process.env.TRAVIS) { configuration.singleRun = true; configuration.browsers = ['ChromeHeadless']; } config.set(configuration); };
Set up Travis test environment (cont. 3)
Set up Travis test environment (cont. 3) Autowatch didn't help. Seeing if `singleRun = true` causes it to stop after running the tests.
JavaScript
mit
UMM-CSci-3601/3601-lab4_mongo,UMM-CSci-3601-F17/interation-1-drop-table-teams,UMM-CSci-3601/3601-lab4_mongo,UMM-CSci-3601-F17/interation-1-drop-table-teams,UMM-CSci-3601-F17/interation-1-drop-table-teams,UMM-CSci-3601/3601-lab4_mongo,UMM-CSci-3601-F17/interation-1-drop-table-teams,UMM-CSci-3601-F17/interation-1-drop-table-teams,UMM-CSci-3601/3601-lab4_mongo
b5efd8cd8eeab78442e210ab7d51d4a310a1678d
src/jquery.clone_form_template.js
src/jquery.clone_form_template.js
(function ($) { $.fn.clone_form_template = function (options) { if (!options) { options = {}; } return $(this).map(function () { return update($(this).clone(), options)[0]; }); }; // updates a template clone according to conventions function update($clone, options) { var index = new Date().getTime(); $clone.find('label,input,textarea,select').each(function (i, obj) { update_attrs($(obj), index, options); }); return $clone.removeClass('template').show(); } function update_attrs($element, identifier, options) { if ($element.attr('id')) { $element.attr('id', $element.attr('id').replace(/_-?\d+_/, '_' + identifier + '_') ); } if ($element.attr('for')) { $element.attr('for', $element.attr('for').replace(/_-?\d+_/, '_' + identifier + '_') ); } if ($element.attr('name')) { if (options.copy_values) { $element.val($('[name="' + $element.attr('name') + '"]').val()); } $element.attr('name', $element.attr('name').replace(/\[-?\d+\]/, '[' + identifier + ']') ); } } }(jQuery));
(function ($) { var DEFAULT_PATTERN = '-1'; $.fn.clone_form_template = function (options, cb) { if (!options) { options = {}; } return $(this).map(function () { return update($(this).clone(), options, cb)[0]; }); }; // updates a template clone according to conventions function update($clone, options, cb) { var index = new Date().getTime(); $clone.find('label,input,textarea,select').each(function (i, obj) { update_attrs($(obj), index, options, cb); }); return $clone.removeClass('template').show(); } function update_attrs($element, identifier, options, cb) { var pattern = options.pattern || DEFAULT_PATTERN, underscore_pattern = new RegExp('_' + pattern + '_'), bracket_pattern = new RegExp('\\[' + pattern + '\\]'); if ($element.attr('id')) { $element.attr('id', $element.attr('id').replace(underscore_pattern, '_' + identifier + '_') ); } if ($element.attr('for')) { $element.attr('for', $element.attr('for').replace(underscore_pattern, '_' + identifier + '_') ); } if ($element.attr('name')) { if (options.copy_values) { $element.val($('[name="' + $element.attr('name') + '"]').val()); } $element.attr('name', $element.attr('name').replace(bracket_pattern, '[' + identifier + ']') ); } if (typeof cb === 'function') { cb.apply($element, $element); } } }(jQuery));
Allow customizable pattern and callback
Allow customizable pattern and callback
JavaScript
mit
samuelcole/jquery-livesearch,samuelcole/jquery-livesearch
a8f98d8df125bbfaade27e606d5e75f72b158228
commons/CitationModal.js
commons/CitationModal.js
import { $$ } from '../dom' import { Form, FormRow, Modal, MultiSelect } from '../ui' export default function CitationModal (props) { const { document, node, mode } = props const confirmLabel = mode === 'edit' ? 'Update' : 'Create' const title = mode === 'edit' ? 'Edit Citation' : 'Create Citation' const value = mode === 'edit' ? node.target : [] const root = document.root const referencesList = root.resolve('references') const modalProps = { title, cancelLabel: 'Cancel', confirmLabel, size: 'large' } return $$(Modal, modalProps, $$(Form, {}, $$(FormRow, {}, $$(MultiSelect, { options: referencesList.map(ref => { return { value: ref.id, label: ref.content } }), value, label: 'Add Reference', placeholder: 'Please select one or more references' }).ref('references') ) ) ) }
import { $$, Component } from '../dom' import { Form, FormRow, Modal, MultiSelect } from '../ui' export default class CitationModal extends Component { getInitialState () { const { mode, node } = this.props const value = mode === 'edit' ? node.target : [] return { value } } render () { const { document, mode } = this.props const { value } = this.state const confirmLabel = mode === 'edit' ? 'Update' : 'Create' const title = mode === 'edit' ? 'Edit Citation' : 'Create Citation' const root = document.root const referencesList = root.resolve('references') const disableConfirm = value.length === 0 const modalProps = { title, cancelLabel: 'Cancel', confirmLabel, disableConfirm, size: 'large' } return $$(Modal, modalProps, $$(Form, {}, $$(FormRow, {}, $$(MultiSelect, { options: referencesList.map(ref => { return { value: ref.id, label: ref.content } }), value, label: 'Add Reference', placeholder: 'Please select one or more references', onchange: this._updateReferencess }).ref('references') ) ) ) } _updateReferencess () { const value = this.refs.references.val() this.extendState({ value }) } }
Disable modal confirmation without values.
Disable modal confirmation without values.
JavaScript
mit
michael/substance-1,substance/substance,substance/substance,michael/substance-1
76842f742608a29d5bd1460aeb983265e807d197
src/build/supportedFolders.js
src/build/supportedFolders.js
/* eslint-disable max-len */ exports.extensions = { supported: [ { icon: 'dist', extensions: ['dist', 'out'] }, { icon: 'git', extensions: ['git', 'github'] }, { icon: 'node', extensions: ['node_modules'] }, { icon: 'meteor', extensions: ['meteor'] }, { icon: 'src', extensions: ['src'] }, { icon: 'test', extensions: ['tests', 'test', '__tests__', '__test__'] }, { icon: 'typings', extensions: ['typings'] }, { icon: 'vscode', extensions: ['vscode'] } ], parse: function () { var s = this.replace(/\./g, '_'); if ((/^\d/).test(s)) return 'n' + s; return s; } };
/* eslint-disable max-len */ exports.extensions = { supported: [ { icon: 'dist', extensions: ['dist', 'out'] }, { icon: 'git', extensions: ['git', 'github'] }, { icon: 'node', extensions: ['node_modules'] }, { icon: 'meteor', extensions: ['meteor'] }, { icon: 'src', extensions: ['src', 'source'] }, { icon: 'test', extensions: ['tests', 'test', '__tests__', '__test__'] }, { icon: 'typings', extensions: ['typings'] }, { icon: 'vscode', extensions: ['vscode'] } ], parse: function () { var s = this.replace(/\./g, '_'); if ((/^\d/).test(s)) return 'n' + s; return s; } };
Support "source" as a src folder
Support "source" as a src folder
JavaScript
mit
robertohuertasm/vscode-icons,jens1o/vscode-icons,JimiC/vscode-icons,vscode-icons/vscode-icons,vscode-icons/vscode-icons,JimiC/vscode-icons,olzaragoza/vscode-icons
2717beda255cb4f474ef141397cadf1592d2246a
blueprints/flexberry-model-init/files/__root__/models/__name__.js
blueprints/flexberry-model-init/files/__root__/models/__name__.js
import { Model as <%= className %>Mixin<%if (projections) {%>, defineProjections<%}%> } from '../mixins/regenerated/models/<%= name %>'; import <%if(parentModelName) {%><%= parentClassName %>Model from './<%= parentModelName %>';<%}else{%>__Projection from 'ember-flexberry-data';<%}%> let Model = <%if(parentModelName) {%><%= parentClassName %>Model.extend<%}else{%>__Projection.Model.extend<%}%>(<%= className %>Mixin, { }); <%if(projections) {%>defineProjections(Model);<%}%> export default Model;
import { Model as <%= className %>Mixin<%if (projections) {%>, defineProjections<%}%> } from '../mixins/regenerated/models/<%= name %>'; import <%if(parentModelName) {%><%= parentClassName %>Model from './<%= parentModelName %>';<%}else{%>{ __Projection } from 'ember-flexberry-data';<%}%> let Model = <%if(parentModelName) {%><%= parentClassName %>Model.extend<%}else{%>__Projection.Model.extend<%}%>(<%= className %>Mixin, { }); <%if(projections) {%>defineProjections(Model);<%}%> export default Model;
Rollback blueprints for base model
Rollback blueprints for base model tfs #116013
JavaScript
mit
Flexberry/ember-flexberry,Flexberry/ember-flexberry,Flexberry/ember-flexberry,Flexberry/ember-flexberry
d9f7edd951b7c69db4623ade722f71b751a65143
connectors/v2/pitchfork.js
connectors/v2/pitchfork.js
'use strict'; /* global Connector */ Connector.artistSelector = '.track-title .artist'; Connector.trackSelector = '.track-title .title'; Connector.isPlaying = function () { return $('.playback-button > div').attr('title') == 'Pause Track'; }; (function() { var playerObserver = new MutationObserver(function() { var playerElement = document.querySelector('#player-container'); if (playerElement !== null) { playerObserver.disconnect(); var actualObserver = new MutationObserver(Connector.onStateChanged); actualObserver.observe(playerElement, { childList: true, subtree: true, attributes: true, characterData: true }); } }); playerObserver.observe(document.body, { childList: true, subtree: true, attributes: false, characterData: false, }); })();
'use strict'; /* global Connector */ Connector.artistSelector = '.track-title .artist'; Connector.trackSelector = '.track-title .title'; Connector.isPlaying = function () { return $('.playback-button > div').attr('title') === 'Pause Track'; }; (function() { var playerObserver = new MutationObserver(function() { var playerElement = document.querySelector('#player-container'); if (playerElement !== null) { playerObserver.disconnect(); var actualObserver = new MutationObserver(Connector.onStateChanged); actualObserver.observe(playerElement, { childList: true, subtree: true, attributes: true, characterData: true }); } }); playerObserver.observe(document.body, { childList: true, subtree: true, attributes: false, characterData: false, }); })();
Use strict equality in Pitchfork connector
Use strict equality in Pitchfork connector
JavaScript
mit
alexesprit/web-scrobbler,inverse/web-scrobbler,usdivad/web-scrobbler,fakelbst/Chrome-Last.fm-Scrobbler,ex47/web-scrobbler,galeksandrp/web-scrobbler,ex47/web-scrobbler,carpet-berlin/web-scrobbler,alexesprit/web-scrobbler,Paszt/web-scrobbler,carpet-berlin/web-scrobbler,inverse/web-scrobbler,david-sabata/web-scrobbler,galeksandrp/web-scrobbler,usdivad/web-scrobbler,david-sabata/web-scrobbler,fakelbst/Chrome-Last.fm-Scrobbler,Paszt/web-scrobbler
f2fd025793df508f7980c5c4f21bfc5745cf9d08
src/fs/__tests__/test-base.js
src/fs/__tests__/test-base.js
jest.autoMockOff(); jest.unmock('../base.js'); const base = require('../base.js'); describe('Base', () => { it('does a lot of cool stuff', () => { }); });
jest.autoMockOff(); jest.unmock('../base.js'); const base = require('../base.js'); jest.unmock('node-fetch'); const fetch = require('node-fetch'); global.Response = fetch.Response; describe('Base', () => { it('constructs correctly', () => { let path = Object.create(null); let name = Object.create(null); let options = Object.create(null); expect(path).not.toBe(name); expect(path).not.toBe(options); expect(name).not.toBe(options); let bfs = new base.Base(name, path, options); expect(bfs).toBeDefined(); expect(bfs.path).toBe(path); expect(bfs.name).toBe(name); expect(bfs.options).toBe(options); }); it('does not stat paths', () => { let path = Object.create(null); let name = Object.create(null); let options = Object.create(null); let bfs = new base.Base(name, path, options); let ret = Object.create(null); spyOn(Promise, 'resolve').and.returnValue(ret); let val = bfs.stat(''); expect(Promise.resolve).toHaveBeenCalledWith(new Response(null, {status: 405})); expect(val).toBe(ret); }); it('does not read paths', () => { let path = Object.create(null); let name = Object.create(null); let options = Object.create(null); let bfs = new base.Base(name, path, options); let ret = Object.create(null); spyOn(Promise, 'resolve').and.returnValue(ret); let val = bfs.read(''); expect(Promise.resolve).toHaveBeenCalledWith(new Response(null, {status: 405})); expect(val).toBe(ret); }); it('does not write paths', () => { let path = Object.create(null); let name = Object.create(null); let options = Object.create(null); let bfs = new base.Base(name, path, options); let ret = Object.create(null); spyOn(Promise, 'resolve').and.returnValue(ret); let val = bfs.write('', ''); expect(Promise.resolve).toHaveBeenCalledWith(new Response(null, {status: 405})); expect(val).toBe(ret); }); });
Add tests for Base fs
Add tests for Base fs
JavaScript
mit
LivelyKernel/lively4-core,LivelyKernel/lively4-core
af85171d2c488bbaa851815ffd8a8aafb0e52f8e
.eleventy.js
.eleventy.js
const CleanCSS = require("clean-css"); module.exports = function (eleventyConfig) { eleventyConfig.addPassthroughCopy("src/img"); eleventyConfig.addPassthroughCopy("src/webfonts"); eleventyConfig.addFilter("cssmin", function (code) { return new CleanCSS({}).minify(code).styles; }); eleventyConfig.addPairedShortcode("cssPostProcess", function (code) { return `${code}`; }); return { dir: { data: "data", input: "src", output: "dist", }, }; };
const CleanCSS = require("clean-css"); module.exports = function (eleventyConfig) { eleventyConfig.addPassthroughCopy("src/img"); eleventyConfig.addPassthroughCopy("src/webfonts"); eleventyConfig.addFilter("cssmin", function (code) { return new CleanCSS({}).minify(code).styles; }); eleventyConfig.addPairedShortcode("cssPostProcess", function (code) { return code; }); return { dir: { data: "data", input: "src", output: "dist", }, }; };
Remove template literal as it isn't necessary
Remove template literal as it isn't necessary
JavaScript
mit
stevecochrane/stevecochrane.com,stevecochrane/stevecochrane.com
8831374a514314c64f52822c1be393f396bc415f
.eslintrc.js
.eslintrc.js
module.exports = { root: true, parser: "@typescript-eslint/parser", parserOptions: { tsconfigRootDir: __dirname, project: ["./tsconfig.json"] }, plugins: ["@typescript-eslint"], extends: [ "eslint:recommended", "plugin:@typescript-eslint/recommended", "plugin:@typescript-eslint/recommended-requiring-type-checking", "prettier", "prettier/@typescript-eslint" ], rules: { "@typescript-eslint/no-non-null-assertion": 0 } };
module.exports = { root: true, parser: "@typescript-eslint/parser", parserOptions: { tsconfigRootDir: __dirname, project: ["./tsconfig.json"] }, plugins: ["@typescript-eslint"], extends: [ "eslint:recommended", "plugin:@typescript-eslint/recommended", "plugin:@typescript-eslint/recommended-requiring-type-checking", "prettier", "prettier/@typescript-eslint" ], rules: { "@typescript-eslint/no-explicit-any": 0, "@typescript-eslint/no-non-null-assertion": 0, "@typescript-eslint/no-unsafe-assignment": 0, "@typescript-eslint/no-unsafe-call": 0, "@typescript-eslint/no-unsafe-member-access": 0, "@typescript-eslint/no-unsafe-return": 0, } };
Disable eslint rules disallowing `any` to be used
Disable eslint rules disallowing `any` to be used
JavaScript
lgpl-2.1
SoftCreatR/WCF,WoltLab/WCF,SoftCreatR/WCF,Cyperghost/WCF,Cyperghost/WCF,SoftCreatR/WCF,Cyperghost/WCF,SoftCreatR/WCF,WoltLab/WCF,Cyperghost/WCF,WoltLab/WCF,WoltLab/WCF,Cyperghost/WCF
f1992db7234513a86b07e53b30a160342e0bb9fc
docs/_book/gitbook/gitbook-plugin-sharing/buttons.js
docs/_book/gitbook/gitbook-plugin-sharing/buttons.js
require(['gitbook', 'jquery'], function(gitbook, $) { var SITES = { 'facebook': { 'label': 'Facebook', 'icon': 'fa fa-facebook', 'onClick': function(e) { e.preventDefault(); window.open('http://www.facebook.com/sharer/sharer.php?s=100&p[url]='+encodeURIComponent(location.href)); } }, 'twitter': { 'label': 'Twitter', 'icon': 'fa fa-twitter', 'onClick': function(e) { e.preventDefault(); window.open('http://twitter.com/home?status='+encodeURIComponent(document.title+' '+location.href)); } }, 'google': { 'label': 'Google+', 'icon': 'fa fa-google-plus', 'onClick': function(e) { e.preventDefault(); window.open('https://plus.google.com/share?url='+encodeURIComponent(location.href)); } }, 'weibo': { 'label': 'Weibo', 'icon': 'fa fa-weibo', 'onClick': function(e) { e.preventDefault(); window.open('http://service.weibo.com/share/share.php?content=utf-8&url='+encodeURIComponent(location.href)+'&title='+encodeURIComponent(document.title)); } }, 'instapaper': { 'label': 'Instapaper', 'icon': 'fa fa-instapaper', 'onClick': function(e) { e.preventDefault(); window.open('http://www.instapaper.com/text?u='+encodeURIComponent(location.href)); } }, 'vk': { 'label': 'VK', 'icon': 'fa fa-vk', 'onClick': function(e) { e.preventDefault(); window.open('http://vkontakte.ru/share.php?url='+encodeURIComponent(location.href)); } } }; gitbook.events.bind('start', function(e, config) { var opts = config.sharing; // Create dropdown menu var menu = $.map(opts.all, function(id) { var site = SITES[id]; return { text: site.label, onClick: site.onClick }; }); // Create main button with dropdown if (menu.length > 0) { gitbook.toolbar.createButton({ icon: 'fa fa-share-alt', label: 'Share', position: 'right', dropdown: [menu] }); } // Direct actions to share $.each(SITES, function(sideId, site) { if (!opts[sideId]) return; gitbook.toolbar.createButton({ icon: site.icon, label: site.text, position: 'right', onClick: site.onClick }); }); }); });
Update HTML files with the updates.
Update HTML files with the updates.
JavaScript
mit
HIT2GAP-EU-PROJECT/HIT2GAPOnt
c09772fb4d1523f2171ddfe0858605e79d4516a3
src/js/controller/Contacts.js
src/js/controller/Contacts.js
var ContactModel = require('../model/Contacts'); var ContactView = require('../view/Contact'); var AddContactForm = require('../view/AddContactForm'); /** * Controller Object to dispatch actions to view/Contact and model/Contacts. * @constructor */ var ContactsController = function() { this.init(); }; ContactsController.remove = function(id) { console.log('Controller Remove'); //ContactModel.remove(id); //ContactView.remove(id); }; ContactsController.prototype = { init: function() { console.log('new controller'); }, setup: function() { var addContact = new AddContactForm(); }, /** * @description Fetches all existing contacts from LocalStorage. */ fetchAll: function() { var contacts = []; var total = localStorage.length; for (i = 0; i < total; i++) { var contact = {}; var key = localStorage.key(i); if (key !== 'debug') { contact.key = key; contact.value = JSON.parse(localStorage.getItem((i + 1).toString())); contacts.push(contact); } } return contacts; }, /** * @description Adds all existing contacts to table. Intended for use * on startup. */ renderAll: function() { var contacts = this.fetchAll(); contacts.forEach(function(currentValue) { var contact = new ContactView(currentValue.key, currentValue.value); }); } }; module.exports = ContactsController;
var ContactModel = require('../model/Contacts'); var ContactView = require('../view/Contact'); var AddContactForm = require('../view/AddContactForm'); /** * Controller Object to dispatch actions to view/Contact and model/Contacts. * @constructor */ var ContactsController = function() { }; ContactsController.remove = function(id) { console.log('Controller Remove'); //ContactModel.remove(id); //ContactView.remove(id); }; ContactsController.render = function(id, contact) { var contactView = new ContactView(id, contact); }; ContactsController.prototype = { setup: function() { var addContact = new AddContactForm(); }, /** * @description Fetches all existing contacts from LocalStorage. */ fetchAll: function() { var contacts = []; var total = localStorage.length; for (i = 0; i < total; i++) { var contact = {}; var key = localStorage.key(i); if (key !== 'debug') { contact.key = key; contact.value = JSON.parse(localStorage.getItem((i + 1).toString())); contacts.push(contact); } } return contacts; }, /** * @description Adds all existing contacts to table. Intended for use * on startup. */ renderAll: function() { var contacts = this.fetchAll(); contacts.forEach(function(currentValue) { var contact = new ContactView(currentValue.key, currentValue.value); }); } }; module.exports = ContactsController;
Remove unused init() add render() method
Remove unused init() add render() method
JavaScript
isc
bitfyre/contacts
be8ed28b34bcd1b9a7666b9dc9ec0da64ff28a30
js/locales/bootstrap-datepicker.mk.js
js/locales/bootstrap-datepicker.mk.js
/** * Macedonian translation for bootstrap-datepicker * Marko Aleksic <psybaron@gmail.com> */ ;(function($){ $.fn.datepicker.dates['mk'] = { days: ["Недела", "Понеделник", "Вторник", "Среда", "Четврток", "Петок", "Сабота", "Недела"], daysShort: ["Нед", "Пон", "Вто", "Сре", "Чет", "Пет", "Саб", "Нед"], daysMin: ["Не", "По", "Вт", "Ср", "Че", "Пе", "Са", "Не"], months: ["Јануари", "Февруари", "Март", "Април", "Мај", "Јуни", "Јули", "Август", "Септември", "Октомври", "Ноември", "Декември"], monthsShort: ["Јан", "Фев", "Мар", "Апр", "Мај", "Јун", "Јул", "Авг", "Сеп", "Окт", "Ное", "Дек"], today: "Денес" }; }(jQuery));
/** * Macedonian translation for bootstrap-datepicker * Marko Aleksic <psybaron@gmail.com> */ ;(function($){ $.fn.datepicker.dates['mk'] = { days: ["Недела", "Понеделник", "Вторник", "Среда", "Четврток", "Петок", "Сабота", "Недела"], daysShort: ["Нед", "Пон", "Вто", "Сре", "Чет", "Пет", "Саб", "Нед"], daysMin: ["Не", "По", "Вт", "Ср", "Че", "Пе", "Са", "Не"], months: ["Јануари", "Февруари", "Март", "Април", "Мај", "Јуни", "Јули", "Август", "Септември", "Октомври", "Ноември", "Декември"], monthsShort: ["Јан", "Фев", "Мар", "Апр", "Мај", "Јун", "Јул", "Авг", "Сеп", "Окт", "Ное", "Дек"], today: "Денес", format: "dd.MM.yyyy" }; }(jQuery));
Add Macedonian date format (with leading zero).
Add Macedonian date format (with leading zero).
JavaScript
apache-2.0
bitzesty/bootstrap-datepicker,HNygard/bootstrap-datepicker,gn0st1k4m/bootstrap-datepicker,aldano/bootstrap-datepicker,zhaoyan158567/bootstrap-datepicker,acrobat/bootstrap-datepicker,TheJumpCloud/bootstrap-datepicker,cherylyan/bootstrap-datepicker,huang-x-h/bootstrap-datepicker,cherylyan/bootstrap-datepicker,defrian8/bootstrap-datepicker,mreiden/bootstrap-datepicker,xutongtong/bootstrap-datepicker,daniyel/bootstrap-datepicker,Tekzenit/bootstrap-datepicker,vegardok/bootstrap-datepicker,parkeugene/bootstrap-datepicker,Youraiseme/bootstrap-datepicker,Azaret/bootstrap-datepicker,Doublemedia/bootstrap-datepicker,saurabh27125/bootstrap-datepicker,tcrossland/bootstrap-datepicker,hemp/bootstrap-datepicker,Mteuahasan/bootstrap-datepicker,NFC-DITO/bootstrap-datepicker,riyan8250/bootstrap-datepicker,CherryDT/bootstrap-datepicker,josegomezr/bootstrap-datepicker,otnavle/bootstrap-datepicker,jesperronn/bootstrap-datepicker,WebbyLab/bootstrap-datepicker,otnavle/bootstrap-datepicker,Invulner/bootstrap-datepicker,Mteuahasan/bootstrap-datepicker,inukshuk/bootstrap-datepicker,mfunkie/bootstrap-datepicker,dckesler/bootstrap-datepicker,1000hz/bootstrap-datepicker,hebbet/bootstrap-datepicker,osama9/bootstrap-datepicker,keiwerkgvr/bootstrap-datepicker,MartijnDwars/bootstrap-datepicker,kiwiupover/bootstrap-datepicker,jhalak/bootstrap-datepicker,HuBandiT/bootstrap-datepicker,1000hz/bootstrap-datepicker,dswitzer/bootstrap-datepicker,inspur-tobacco/bootstrap-datepicker,stenmuchow/bootstrap-datepicker,christophercaburog/bootstrap-datepicker,CheapSk8/bootstrap-datepicker,chengky/bootstrap-datepicker,bitzesty/bootstrap-datepicker,pacozaa/bootstrap-datepicker,abnovak/bootstrap-sass-datepicker,uxsolutions/bootstrap-datepicker,steffendietz/bootstrap-datepicker,Doublemedia/bootstrap-datepicker,mfunkie/bootstrap-datepicker,nerionavea/bootstrap-datepicker,ashleymcdonald/bootstrap-datepicker,NFC-DITO/bootstrap-datepicker,oller/foundation-datepicker-sass,huang-x-h/bootstrap-datepicker,wetet2/bootstrap-datepicker,jhalak/bootstrap-datepicker,rocLv/bootstrap-datepicker,acrobat/bootstrap-datepicker,champierre/bootstrap-datepicker,inway/bootstrap-datepicker,WebbyLab/bootstrap-datepicker,janusnic/bootstrap-datepicker,parkeugene/bootstrap-datepicker,CheapSk8/bootstrap-datepicker,inway/bootstrap-datepicker,yangyichen/bootstrap-datepicker,rocLv/bootstrap-datepicker,ashleymcdonald/bootstrap-datepicker,dswitzer/bootstrap-datepicker,WeiLend/bootstrap-datepicker,Invulner/bootstrap-datepicker,HNygard/bootstrap-datepicker,inspur-tobacco/bootstrap-datepicker,tcrossland/bootstrap-datepicker,kevintvh/bootstrap-datepicker,TheJumpCloud/bootstrap-datepicker,hemp/bootstrap-datepicker,abnovak/bootstrap-sass-datepicker,martinRjs/bootstrap-datepicker,mfunkie/bootstrap-datepicker,inukshuk/bootstrap-datepicker,menatoric59/bootstrap-datepicker,darluc/bootstrap-datepicker,janusnic/bootstrap-datepicker,Youraiseme/bootstrap-datepicker,oller/foundation-datepicker-sass,thetimbanks/bootstrap-datepicker,cbryer/bootstrap-datepicker,champierre/bootstrap-datepicker,thetimbanks/bootstrap-datepicker,christophercaburog/bootstrap-datepicker,Sprinkle7/bootstrap-datepicker,josegomezr/bootstrap-datepicker,nilbus/bootstrap-datepicker,chengky/bootstrap-datepicker,gn0st1k4m/bootstrap-datepicker,uxsolutions/bootstrap-datepicker,Azaret/bootstrap-datepicker,osama9/bootstrap-datepicker,rstone770/bootstrap-datepicker,defrian8/bootstrap-datepicker,nilbus/bootstrap-datepicker,stenmuchow/bootstrap-datepicker,wulinmengzhu/bootstrap-datepicker,Sprinkle7/bootstrap-datepicker,daniyel/bootstrap-datepicker,joubertredrat/bootstrap-datepicker,xutongtong/bootstrap-datepicker,wetet2/bootstrap-datepicker,hebbet/bootstrap-datepicker,riyan8250/bootstrap-datepicker,zhaoyan158567/bootstrap-datepicker,WebbyLab/bootstrap-datepicker,mreiden/bootstrap-datepicker,i-am-kenny/bootstrap-datepicker,wulinmengzhu/bootstrap-datepicker,Tekzenit/bootstrap-datepicker,oller/foundation-datepicker-sass,vgrish/bootstrap-datepicker,kevintvh/bootstrap-datepicker,joubertredrat/bootstrap-datepicker,vegardok/bootstrap-datepicker,aldano/bootstrap-datepicker,cbryer/bootstrap-datepicker,SimpleUpdates/bootstrap-datepicker,ibcooley/bootstrap-datepicker,steffendietz/bootstrap-datepicker,WeiLend/bootstrap-datepicker,eternicode/bootstrap-datepicker,ibcooley/bootstrap-datepicker,vsn4ik/bootstrap-datepicker,darluc/bootstrap-datepicker,pacozaa/bootstrap-datepicker,eternicode/bootstrap-datepicker,CherryDT/bootstrap-datepicker,wearespindle/datepicker-js,josegomezr/bootstrap-datepicker,dckesler/bootstrap-datepicker,menatoric59/bootstrap-datepicker,i-am-kenny/bootstrap-datepicker,yangyichen/bootstrap-datepicker,rstone770/bootstrap-datepicker,kiwiupover/bootstrap-datepicker,jesperronn/bootstrap-datepicker,nerionavea/bootstrap-datepicker,martinRjs/bootstrap-datepicker,SimpleUpdates/bootstrap-datepicker,vgrish/bootstrap-datepicker,vsn4ik/bootstrap-datepicker,1000hz/bootstrap-datepicker,saurabh27125/bootstrap-datepicker,keiwerkgvr/bootstrap-datepicker,HuBandiT/bootstrap-datepicker,MartijnDwars/bootstrap-datepicker
6c504b7a54518d498d256caa3801df0df49a4a87
server/tests/seed/auth_seed.js
server/tests/seed/auth_seed.js
// auth_seed.js const User = require('./../../database/models').User; module.exports = { emptyDB(done) { User.destroy({ truncate: true }) .then((rows) => { console.log(rows); return done(); }) .catch(err => done(err)); }, setData(fullname, username, email, mobile, password, confirmPassword) { return { fullname, username, email, mobile, password, confirm_password: confirmPassword }; }, addUserToDb(done) { User.create({ fullname: 'jimoh hadi', username: 'ovenje', email: 'ovenje@yahoo.com', mobile: '8163041269', password: '11223344' }) .then((user) => { done(); }) .catch((err) => { done(err); }); } };
// auth_seed.js const User = require('./../../database/models').User; module.exports = { emptyDB(done) { User.destroy({ truncate: true }) .then(() => done()) .catch(err => done(err)); }, setData(fullname, username, email, mobile, password, confirmPassword) { return { fullname, username, email, mobile, password, confirm_password: confirmPassword }; }, addUserToDb(done) { User.create({ fullname: 'jimoh hadi', username: 'ovenje', email: 'ovenje@yahoo.com', mobile: '8163041269', password: '11223344' }) .then((user) => { done(); }) .catch((err) => { done(err); }); } };
Remove unnecessary argument from seeder file
Remove unnecessary argument from seeder file
JavaScript
mit
johadi10/PostIt,johadi10/PostIt
890bdbb025bcf7ec6121c58d6b6882cdbd6dd6ee
src/handlers.js
src/handlers.js
const pkg = require('../package.json'); const Identify = require('./identifyPeople.js'); function handlers() { function index(req, reply) { reply.view('index', { users: [ 'hello' ] }); } function version(req, reply) { reply({version: pkg.version}).code(200); } function identifyPeople(req, reply) { if (!req.payload || !req.payload.url) { reply("Expected 'url' parameter").code(400); return; } let imageUrl = req.payload.url; Identify.findFace(imageUrl) .then((names) => { reply({"Identification results: " : JSON.stringify(names)}).code(200); }) .catch((err) => { console.log(JSON.stringify(err, null, 2)); reply({"Identification results" : []}).code(500); }); } return { index, version, identifyPeople }; } module.exports = handlers;
const pkg = require('../package.json'); const Identify = require('./identifyPeople.js'); function handlers() { function index(req, reply) { reply.view('index', { users: [ 'hello' ] }); } function version(req, reply) { reply({version: pkg.version}).code(200); } function identifyPeople(req, reply) { if (!req.payload || !req.payload.url) { reply("Expected 'url' parameter").code(400); return; } let imageUrl = req.payload.url; Identify.findFace(imageUrl) .then((names) => { reply({"identities" : names}).code(200); }) .catch((err) => { console.log(JSON.stringify(err, null, 2)); reply({"identities" : []}).code(500); }); } return { index, version, identifyPeople }; } module.exports = handlers;
Return names as json array
Return names as json array Now the identify results are returned as json.
JavaScript
mit
alsalo1/walls-have-ears,alsalo1/walls-have-ears
76b57bed027fb3cb16bd24f9bb6fef4011fd9ebd
src/routes/product-group.routes.js
src/routes/product-group.routes.js
import express from 'express'; import * as controller from '../controllers/product-group.controller'; import { createAuthMiddleware } from '../auth'; import { MODERATOR } from '../auth/constants'; const router = express.Router(); router.use(createAuthMiddleware(MODERATOR)); router.get('/', controller.list); router.post('/', controller.create); router.put('/:id', controller.update); router.delete('/:id', controller.destroy); export default router;
import express from 'express'; import * as controller from '../controllers/product-group.controller'; import { createAuthMiddleware } from '../auth'; import { MODERATOR, TOKEN } from '../auth/constants'; const router = express.Router(); router.get('/', createAuthMiddleware(TOKEN), controller.list); router.post('/', createAuthMiddleware(MODERATOR), controller.create); router.put('/:id', createAuthMiddleware(MODERATOR), controller.update); router.delete('/:id', createAuthMiddleware(MODERATOR), controller.destroy); export default router;
Change product group api authentication
Change product group api authentication
JavaScript
mit
abakusbackup/abacash-api,abakusbackup/abacash-api
da2614a96f6e78133ae6e7441557a470dc27fde0
src/components/Editor/index.js
src/components/Editor/index.js
import './index.css'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Viewer from '../Viewer'; class Editor extends Component { render() { const { presId } = this.props; return ( <div className="editor-wrapper"> <Viewer presId={presId}/> </div> ) } } Editor.propTypes = { presId: PropTypes.string.isRequired }; export default Editor;
import './index.css'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Viewer from '../Viewer'; import presentations from '../../data/presentations'; import PreviewPanel from './components/PreviewPanel'; class Editor extends Component { constructor(props) { super(props); this.state = { presentation: null, loading: true, activeSlideIndex: 0, error: null, }; } componentDidMount() { const { presId } = this.props; presentations.get(presId) .then(presentation => { this.setState({ presentation, loading: false, activeSlideIndex: 0, }) }) .catch(err => { this.setState({ error: err, loading: false, }) }) } render() { const { presId } = this.props; const { loading, error, presentation } = this.state; return ( <div className="editor-wrapper"> <Viewer presId={presId}/> </div> ) } } Editor.propTypes = { presId: PropTypes.string.isRequired }; export default Editor;
Add logic to getting the presentation to the editor
Add logic to getting the presentation to the editor
JavaScript
mit
jacobwindsor/pathway-presenter,jacobwindsor/pathway-presenter
c13e26870627291988d144ff9d77f1b1b05ec264
src/config/app-config.index.js
src/config/app-config.index.js
import Config from './app-config.module'; import './base.config'; /** * Optionally include a file */ ((_require) => { if (_require.keys().find(x => x.indexOf('local.config.js') > -1)) { _require('./local.config.js'); } })(require.context('./', false, /local\.config\.js$/)); export default Config;
import Config from './app-config.module'; import './base.config'; /** * Optionally include a file */ ((_require) => { if (_require.keys().indexOf('./local.config.js') > -1) { _require('./local.config.js'); } })(require.context('./', false, /local\.config\.js$/)); export default Config;
Simplify check for local.config.js file
Simplify check for local.config.js file
JavaScript
mit
tijhaart/webpack-foundation,tijhaart/webpack-foundation
f1cd45736986db9362750ac3061ee4113c8ba3f2
test/unit/vdom/incremental-dom.js
test/unit/vdom/incremental-dom.js
import * as IncrementalDOM from 'incremental-dom'; import { vdom } from '../../../src/index'; describe('IncrementalDOM', function () { it('should export all the same members as the incremental-dom we consume', function () { // Ensure we export the element functions. expect(vdom.attr).to.be.a('function'); expect(vdom.elementClose).to.be.a('function'); expect(vdom.elementOpenEnd).to.be.a('function'); expect(vdom.elementOpenStart).to.be.a('function'); expect(vdom.elementVoid).to.be.a('function'); expect(vdom.text).to.be.a('function'); // Ensure they're not the same as Incremental DOM's implementation. expect(vdom.attr).not.to.equal(IncrementalDOM.attr); expect(vdom.elementClose).not.to.equal(IncrementalDOM.elementClose); expect(vdom.elementOpenEnd).not.to.equal(IncrementalDOM.elementOpenEnd); expect(vdom.elementOpenStart).not.to.equal(IncrementalDOM.elementOpenStart); expect(vdom.elementVoid).not.to.equal(IncrementalDOM.elementVoid); expect(vdom.text).not.to.equal(IncrementalDOM.text); }); });
import * as IncrementalDOM from 'incremental-dom'; import { vdom } from '../../../src/index'; function testBasicApi (name) { it('should be a function', () => expect(vdom[name]).to.be.a('function')); it('should not be the same one as in Incremental DOM', () => expect(vdom[name]).not.to.equal(IncrementalDOM[name])); } describe('IncrementalDOM', function () { describe('attr', () => { testBasicApi('attr'); }); describe('elementClose', () => { testBasicApi('elementClose'); }); describe('elementOpen', () => { testBasicApi('elementOpen'); }); describe('elementOpenEnd', () => { testBasicApi('elementOpenEnd'); }); describe('elementOpenStart', () => { testBasicApi('elementOpenStart'); }); describe('elementVoid', () => { testBasicApi('elementVoid'); }); describe('text', () => { testBasicApi('text'); }); });
Add basic tests for all api points that override Incremental DOM.
test(vdom): Add basic tests for all api points that override Incremental DOM.
JavaScript
mit
chrisdarroch/skatejs,skatejs/skatejs,skatejs/skatejs,chrisdarroch/skatejs,skatejs/skatejs
933d14bd3764d570477af932604f8243ff406aa3
index-browser.js
index-browser.js
const assert = require('assert') function createGL (opts) { assert(!opts || (typeof opts === 'object'), 'pex-gl: createGL requires opts argument to be null or an object') if (!opts) opts = {} let canvas = opts.canvas if (!canvas) { canvas = document.createElement('canvas') canvas.width = opts.width || window.innerWidth canvas.height = opts.height || window.innerHeight if (!opts.width && !opts.height) { // fullscreen document.body.style.margin = '0px' } if (document.body) { document.body.appendChild(canvas) } else { // just in case our script is included above <body> document.addEventListener('DOMContentLoaded', () => { document.body.appendChild(canvas) }) } } const gl = canvas.getContext('webgl', opts) return gl } module.exports = createGL
const assert = require('assert') function createGL (opts) { assert(!opts || (typeof opts === 'object'), 'pex-gl: createGL requires opts argument to be null or an object') if (!opts) opts = {} let canvas = opts.canvas if (!canvas) { canvas = document.createElement('canvas') canvas.width = opts.width || window.innerWidth canvas.height = opts.height || window.innerHeight const appendCanvas = () => { if (!opts.width && !opts.height) { // fullscreen document.body.style.margin = '0px' } document.body.appendChild(canvas) } if (document.body) { appendCanvas() } else { // just in case our script is included above <body> document.addEventListener('DOMContentLoaded', appendCanvas) } } const gl = canvas.getContext('webgl', opts) return gl } module.exports = createGL
Change the way properties on document.body are set while loading canvas.
Change the way properties on document.body are set while loading canvas. In the default setup, when no width and height options are passed and `createGL` is called on page load, it throws an error if the script is included before the body element, since `document.body.style` is null. The function already accounts for this fact while appending the canvas to the page, but not while setting `style.margin = '0px'`. This PR changes that.
JavaScript
mit
pex-gl/pex-gl
cc43c6c9e5be06cd77a26015e519f72ae4f3e918
test/replace.js
test/replace.js
var replace = require( "../src/str-replace" ); module.exports = { replaceAll: function( assert ) { var actual = replace.all( "/" ).from( "/home/dir" ).to( "\\" ); var expected = "\\home\\dir"; assert.strictEqual( actual, expected ); assert.done(); } };
var replace = require( "../src/str-replace" ); module.exports = { replace_all: function( assert ) { var actual = replace.all( "/" ).from( "/home/dir" ).to( "\\" ); var expected = "\\home\\dir"; assert.strictEqual( actual, expected ); assert.done(); } };
Use dash pattern in tests for better console visibility
Use dash pattern in tests for better console visibility
JavaScript
mit
FagnerMartinsBrack/str-replace
16479fe5e89eb332f015eaba6344140142a5959f
lib/endpoint/UploadEndpoint.js
lib/endpoint/UploadEndpoint.js
var loadTemplate = require('../loadTemplate') var getRepository = require('./getRepository') function UploadEndpoint(req, res, next) { var repo = getRepository(req) repo.post(req.body, 'application/rdf+xml', (err, callback) => { if(err) { return next(err) } res.status(200).send('ok') }) } module.exports = UploadEndpoint
var loadTemplate = require('../loadTemplate') var getRepository = require('./getRepository') function UploadEndpoint(req, res, next) { var repo = getRepository(req) repo.post(req.body, req.headers['content-type'], (err, callback) => { if(err) { return next(err) } res.status(200).send('ok') }) } module.exports = UploadEndpoint
Use content-type header in upload endpoint
Use content-type header in upload endpoint
JavaScript
bsd-2-clause
ICO2S/sbolstack-api,ICO2S/sbolstack-api,ICO2S/sbolstack-api
d6761e50b6285b3ba0d7371a61be6712cdc6fac3
src/SumoCoders/FrameworkCoreBundle/Resources/assets/js/Framework/Tabs.js
src/SumoCoders/FrameworkCoreBundle/Resources/assets/js/Framework/Tabs.js
export class Tabs { initEventListeners () { this.loadTab() $('.nav-tabs a').on('click', $.proxy(this.changeTab, this)) } changeTab (event) { let $current = $(event.currentTarget) /* if the browser supports history.pushState(), use it to update the URL with the fragment identifier, without triggering a scroll/jump */ if (window.history && window.history.pushState) { /* an empty state object for now — either we implement a proper popstate handler ourselves, or wait for jQuery UI upstream */ window.history.pushState({}, document.title, $current.href) } else { let scrolled = $(window).scrollTop() window.location.hash = '#' + $current.href.split('#')[1] $(window).scrollTop(scrolled) } $current.tab('show') } loadTab () { let url = document.location.toString() if (url.match('#')) { let anchor = '#' + url.split('#')[1] if ($('.nav-tabs a[href=' + anchor + ']').length > 0) { $('.nav-tabs a[href=' + anchor + ']').tab('show') } } } }
export class Tabs { initEventListeners () { this.loadTab() $('.nav-tabs a').on('click', $.proxy(this.changeTab, this)) } changeTab (event) { let $current = $(event.currentTarget) /* if the browser supports history.pushState(), use it to update the URL with the fragment identifier, without triggering a scroll/jump */ if (window.history && window.history.pushState) { /* an empty state object for now — either we implement a proper popstate handler ourselves, or wait for jQuery UI upstream */ window.history.pushState({}, document.title, $current.attr('href')) } else { let scrolled = $(window).scrollTop() window.location.hash = '#' + $current.attr('href').split('#')[1] $(window).scrollTop(scrolled) } $current.tab('show') } loadTab () { let url = document.location.toString() if (url.match('#')) { let anchor = '#' + url.split('#')[1] if ($('.nav-tabs a[href=' + anchor + ']').length > 0) { $('.nav-tabs a[href=' + anchor + ']').tab('show') } } } }
Fix url hash when changing tabs
Fix url hash when changing tabs
JavaScript
mit
sumocoders/Framework,jonasdekeukelaere/Framework,sumocoders/Framework,jonasdekeukelaere/Framework,jonasdekeukelaere/Framework,sumocoders/Framework,sumocoders/Framework,jonasdekeukelaere/Framework
6bce932ca8d3b10cfa00231f0719c92262282dc9
Gruntfile.js
Gruntfile.js
'use strict'; module.exports = function (grunt) { // Show elapsed time at the end require('time-grunt')(grunt); // Load all grunt tasks require('load-grunt-tasks')(grunt); grunt.initConfig({ jshint: { options: { jshintrc: '.jshintrc', reporter: require('jshint-stylish') }, gruntfile: { src: ['Gruntfile.js'] }, js: { src: ['*.js'] }, test: { src: ['test/**/*.js'] } }, mochacli: { options: { reporter: 'nyan', bail: true }, all: ['test/*.js'] }, watch: { gruntfile: { files: '<%= jshint.gruntfile.src %>', tasks: ['jshint:gruntfile'] }, js: { files: '<%= jshint.js.src %>', tasks: ['jshint:js', 'mochacli'] }, test: { files: '<%= jshint.test.src %>', tasks: ['jshint:test', 'mochacli'] } } }); grunt.registerTask('default', ['jshint', 'mochacli']); };
'use strict'; module.exports = function (grunt) { // Show elapsed time at the end require('time-grunt')(grunt); // Load all grunt tasks require('load-grunt-tasks')(grunt); grunt.initConfig({ jshint: { options: { jshintrc: '.jshintrc', reporter: require('jshint-stylish'), ignores: 'browser.js' }, gruntfile: { src: ['Gruntfile.js'] }, js: { src: ['*.js'] }, test: { src: ['test/**/*.js'] } }, mochacli: { options: { reporter: 'nyan', bail: true }, all: ['test/*.js'] }, watch: { gruntfile: { files: '<%= jshint.gruntfile.src %>', tasks: ['jshint:gruntfile'] }, js: { files: '<%= jshint.js.src %>', tasks: ['jshint:js', 'mochacli'] }, test: { files: '<%= jshint.test.src %>', tasks: ['jshint:test', 'mochacli'] } } }); grunt.registerTask('default', ['jshint', 'mochacli']); };
Make ignore browser.js from jshint
Make ignore browser.js from jshint
JavaScript
mit
hakatashi/japanese.js,hakatashi/japanese.js
1d16098e3bba07210d0e561124a67a0c1c2b139c
src/reducers/index.js
src/reducers/index.js
import { combineReducers } from 'redux' import counter from './counter' const reducer = combineReducers({ counter }) export default reducer
import { combineReducers } from 'redux' import counter from './counter' import todos from './todos' const reducer = combineReducers({ counter, todos }) export default reducer
Put the todos reducer into the root reducer
Put the todos reducer into the root reducer
JavaScript
mit
RSS-Dev/live-html,epicsharp/react-boilerplate,epicsharp/react-boilerplate,RSS-Dev/live-html
abec1e3b7b21eb8a7fc4ca301050f5703c3b61d7
src/DefaultSpecimens.js
src/DefaultSpecimens.js
import Audio from './specimens/Audio'; import Code from './specimens/Code'; import Color from './specimens/Color'; import Html from './specimens/Html'; import Hint from './specimens/Hint'; import Image from './specimens/Image'; import Type from './specimens/Type'; import Download from './specimens/Download'; import Video from './specimens/Video'; export default { audio: Audio, code: Code, color: Color, html: Html, hint: Hint, image: Image, type: Type, download: Download, video: Video };
import Audio from './specimens/Audio'; import Code from './specimens/Code'; import Color from './specimens/Color'; import Html from './specimens/Html'; import Hint from './specimens/Hint'; import Image from './specimens/Image'; import Type from './specimens/Type'; import Download from './specimens/Download'; import Video from './specimens/Video'; export default { audio: Audio, code: Code, // color: Color, // html: Html, hint: Hint, // image: Image, // type: Type, // download: Download, // video: Video };
Disable specimens which are not upgraded yet
Disable specimens which are not upgraded yet
JavaScript
bsd-3-clause
interactivethings/catalog,interactivethings/catalog,interactivethings/catalog,interactivethings/catalog
59195df3b093746478e0077bddbc913ebb63cb45
pre-build.js
pre-build.js
'use strict'; var Mocha = require('mocha'); var colors = require('colors'); var build = require('./build.js'); var mocha = new Mocha({ui: 'bdd', reporter: 'list'}); mocha.addFile('test/test-optipng-path.js'); mocha.run(function (failures) { if (failures > 0) { build(); } else { console.log('pre-build test passed successfully, skipping build'.green); } });
'use strict'; var Mocha = require('mocha'); var colors = require('colors'); var build = require('./build.js'); var mocha = new Mocha({ui: 'bdd', reporter: 'min'}); mocha.addFile('test/test-optipng-path.js'); mocha.run(function (failures) { if (failures > 0) { console.log('pre-build test failed, compiling from source...'.red); build(); } else { console.log('pre-build test passed successfully, skipping build...'.green); } });
Improve message on prebuild test failure
Improve message on prebuild test failure
JavaScript
mit
jmnarloch/optipng-bin,imagemin/optipng-bin,inversion/optipng-bin
2bbe6c91c53b871e6c2aad0b3c26508db3a0cf3f
Gruntfile.js
Gruntfile.js
module.exports = function(grunt) { 'use strict'; // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), // Task configuration. aws: grunt.file.readJSON('.aws-deploy.json'), s3: { options: { accessKeyId: '<%= aws.accessKeyId %>', secretAccessKey: '<%= aws.secretAccessKey %>', bucket: 'gamekeller', region: 'eu-central-1', gzip: false, overwrite: false }, assets: { cwd: 'public/', src: ['assets/**', '!assets/manifest.json'] } } }) // Load local grunt tasks. grunt.loadTasks('grunt') // Load necessary plugins. grunt.loadNpmTasks('grunt-aws') // Production simulating task. grunt.registerTask('prod', ['revupdate', 'precompile']) // Database operation tasks. grunt.registerTask('db', ['dropDB', 'seedDB']) grunt.registerTask('db.drop', ['dropDB']) grunt.registerTask('db.seed', ['seedDB']) // Deploy task. grunt.registerTask('deploy', ['bower', 'precompile', 's3', 'revupdate']) }
module.exports = function(grunt) { 'use strict'; // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), // Task configuration. aws: grunt.file.readJSON('.aws-deploy.json'), s3: { options: { accessKeyId: '<%= aws.accessKeyId %>', secretAccessKey: '<%= aws.secretAccessKey %>', bucket: 'gamekeller', region: 'eu-central-1', gzip: false, overwrite: false, access: 'private' }, assets: { cwd: 'public/', src: ['assets/**', '!assets/manifest.json'] } } }) // Load local grunt tasks. grunt.loadTasks('grunt') // Load necessary plugins. grunt.loadNpmTasks('grunt-aws') // Production simulating task. grunt.registerTask('prod', ['revupdate', 'precompile']) // Database operation tasks. grunt.registerTask('db', ['dropDB', 'seedDB']) grunt.registerTask('db.drop', ['dropDB']) grunt.registerTask('db.seed', ['seedDB']) // Deploy task. grunt.registerTask('deploy', ['bower', 'precompile', 's3', 'revupdate']) }
Use private ACL for S3
Grunt/deploy: Use private ACL for S3
JavaScript
mit
gamekeller/next,gamekeller/next
56abe6dc632ece6f1cb2518f654c6da499798a28
Gruntfile.js
Gruntfile.js
/** * Copyright (c) Ajay Sreedhar. All rights reserved. * * Licensed under the MIT License. * Please see LICENSE file located in the project root for more information. */ 'use strict'; const loadTasks = require('load-grunt-tasks'); const {copyConfig, babelConfig} = require('./build/grunt-config'); const {cleanBuild, startRenderer, makeRelease} = require('./build/grunt-task'); module.exports = function (grunt) { loadTasks(grunt, {pattern: ['grunt-contrib-copy', 'grunt-babel']}); grunt.initConfig({ copy: copyConfig, babel: babelConfig }); grunt.registerTask('clean', 'Cleans up the output files.', cleanBuild); grunt.registerTask('render', 'Starts the electron renderer.', startRenderer); grunt.registerTask('release', 'Makes an app release.', makeRelease); grunt.registerTask('dist', ['clean', 'babel', 'copy']); grunt.registerTask('start', ['dist', 'render']); };
/** * Copyright (c) Ajay Sreedhar. All rights reserved. * * Licensed under the MIT License. * Please see LICENSE file located in the project root for more information. */ 'use strict'; const loadTasks = require('load-grunt-tasks'); const {copyConfig, babelConfig} = require('./build/grunt-config'); const {cleanBuild, startRenderer, makeRelease} = require('./build/grunt-task'); module.exports = function (grunt) { loadTasks(grunt, {pattern: ['grunt-contrib-copy', 'grunt-babel']}); grunt.initConfig({ copy: copyConfig, babel: babelConfig }); grunt.registerTask('clean', 'Cleans up the output files.', cleanBuild); grunt.registerTask('render', 'Starts the electron renderer.', startRenderer); grunt.registerTask('dist', 'Makes a distributable release.', makeRelease); grunt.registerTask('compile', ['clean', 'babel', 'copy']); grunt.registerTask('start', ['compile', 'render']); };
Rename dist script as compile
change: Rename dist script as compile
JavaScript
mit
ajaysreedhar/kongdash,ajaysreedhar/kongdash,ajaysreedhar/kongdash
3ab63bdd39ba71a9ad8a7cd0dbb768dc26daec64
Gruntfile.js
Gruntfile.js
module.exports = function (grunt) { require('load-grunt-tasks')(grunt); grunt.initConfig({ handlebars: { compile: { options: { amd: ['handlebars', 'handlebars.helpers'], namespace: 'templates', partialRegex: /.*/, partialsPathRegex: /\/partials\//, processName: function (path) { return path.match(/([\w]+)\.hbs/)[1]; } }, files: { 'static/templates/compiled.js': ['src/views/**/*.hbs'] } } }, jshint: { server: { options: { jshintrc: true }, src: ['src/**/*.js'] }, client: { options: { jshintrc: true }, src: ['static/js/**/*.js'] }, tests: { options: { jshintrc: true }, src: ['test/**/*.js'] } }, sass: { dist: { files: { 'static/css/styles.css': 'static/css/styles.scss' } } }, watch: { handlebars: { files: ['src/views/**/*.hbs'], tasks: ['handlebars'] }, jshint: { files: ['src/**/*.js', 'static/js/**/*.js', 'test/**/*.js'], tasks: ['jshint'] }, sass: { files: ['static/css/**/*.scss'], tasks: ['sass'] } } }); grunt.registerTask('default', ['handlebars', 'jshint', 'sass']); };
module.exports = function (grunt) { require('load-grunt-tasks')(grunt); grunt.initConfig({ handlebars: { compile: { options: { amd: ['handlebars', 'handlebars.helpers'], namespace: 'templates', partialRegex: /.*/, partialsPathRegex: /\/partials\//, processName: function (path) { return path.match(/([\w]+)\.hbs/)[1]; } }, files: { 'static/templates/compiled.js': ['src/views/**/*.hbs'] } } }, jshint: { server: { options: { jshintrc: true }, src: ['src/**/*.js'] }, client: { options: { jshintrc: true, ignores: ['static/js/**/*.min.js'] }, src: ['static/js/**/*.js'] }, tests: { options: { jshintrc: true }, src: ['test/**/*.js'] } }, sass: { dist: { files: { 'static/css/styles.css': 'static/css/styles.scss' } } }, watch: { handlebars: { files: ['src/views/**/*.hbs'], tasks: ['handlebars'] }, jshint: { files: ['src/**/*.js', 'static/js/**/*.js', 'test/**/*.js'], tasks: ['jshint'] }, sass: { files: ['static/css/**/*.scss'], tasks: ['sass'] } } }); grunt.registerTask('default', ['handlebars', 'jshint', 'sass']); };
Set jshint to ignore minified files.
Set jshint to ignore minified files.
JavaScript
mit
neogeek/nodejs-starter-kit
0cfe946a2394d1f3def3c55763b856c15ab29892
Gruntfile.js
Gruntfile.js
const zipFileName = 'extension.zip'; module.exports = function (grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), webstoreUpload: { accounts: { default: { cli_auth: true, // eslint-disable-line publish: true, client_id: process.env.CLIENT_ID, // eslint-disable-line client_secret: process.env.CLIENT_SECRET, // eslint-disable-line refresh_token: process.env.REFRESH_TOKEN // eslint-disable-line } }, extensions: { refinedGitHub: { appID: 'hlepfoohegkhhmjieoechaddaejaokhf', // App ID from chrome webstore publish: true, zip: zipFileName } } } }); grunt.loadNpmTasks('grunt-webstore-upload'); grunt.registerTask('default', ['webstoreUpload']); };
const zipFileName = 'extension.zip'; module.exports = function (grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), webstore_upload: { // eslint-disable-line accounts: { default: { cli_auth: true, // eslint-disable-line publish: true, client_id: process.env.CLIENT_ID, // eslint-disable-line client_secret: process.env.CLIENT_SECRET, // eslint-disable-line refresh_token: process.env.REFRESH_TOKEN // eslint-disable-line } }, extensions: { refinedGitHub: { appID: 'hlepfoohegkhhmjieoechaddaejaokhf', // App ID from chrome webstore publish: true, zip: zipFileName } } } }); grunt.loadNpmTasks('grunt-webstore-upload'); grunt.registerTask('default', ['webstore_upload']); };
Change deploy Grunt taskname to snake case
Change deploy Grunt taskname to snake case
JavaScript
mit
sindresorhus/refined-github,busches/refined-github,jgierer12/refined-github,busches/refined-github,sindresorhus/refined-github,jgierer12/refined-github
1d7088cfae8aa64ff834e1d20911df15af06f745
Gruntfile.js
Gruntfile.js
module.exports = function(grunt) { // load grunt tasks from package.json require('load-grunt-tasks')(grunt); // Project configuration. grunt.initConfig({ clean: { dist: [ 'dist', 'robert/**/*.pyc', ] }, compass: { dist: { options: { sassDir: 'robert/static/sass/', cssDir: 'robert/static/css/', outputStyle: 'compressed', } } }, concurrent: { server: { options: { logConcurrentOutput: true, }, tasks: ['watch', 'shell:devserver'] } }, shell: { options: { stdout: true, stderr: true, }, devserver: { command: 'python run_devserver.py', }, freeze: { command: 'python freeze.py', } }, watch: { options: { livereload: true, }, python: { files: ['robert/**/*.py'], tasks: [] }, sass: { files: ['robert/static/sass/*.scss'], tasks: ['compass'], }, templates: { files: ['robert/templates/*.html'], tasks: [], }, articles: { files: ['articles/*.md'], tasks: [], }, }, }); grunt.registerTask('default', [ 'build', 'concurrent:server', ]); grunt.registerTask('build', [ 'clean', 'compass', 'shell:freeze', ]); };
module.exports = function(grunt) { // load grunt tasks from package.json require('load-grunt-tasks')(grunt); // Project configuration. grunt.initConfig({ clean: { dist: [ 'dist', 'robert/**/*.pyc', ], postbuild: [ 'dist/static/sass', ], }, compass: { dist: { options: { sassDir: 'robert/static/sass/', cssDir: 'robert/static/css/', outputStyle: 'compressed', } } }, concurrent: { server: { options: { logConcurrentOutput: true, }, tasks: ['watch', 'shell:devserver'] } }, shell: { options: { stdout: true, stderr: true, }, devserver: { command: 'python run_devserver.py', }, freeze: { command: 'python freeze.py', } }, watch: { options: { livereload: true, }, python: { files: ['robert/**/*.py'], tasks: [] }, sass: { files: ['robert/static/sass/*.scss'], tasks: ['compass'], }, templates: { files: ['robert/templates/*.html'], tasks: [], }, articles: { files: ['articles/*.md'], tasks: [], }, }, }); grunt.registerTask('default', [ 'build', 'concurrent:server', ]); grunt.registerTask('build', [ 'clean:dist', 'compass', 'shell:freeze', 'clean:postbuild', ]); };
Add a postbuild task to grunt to remove unnecessary build artifacts
Add a postbuild task to grunt to remove unnecessary build artifacts
JavaScript
mit
thusoy/robertblag,thusoy/robertblag,thusoy/robertblag
1e421c03fce6c4b1e167c232838b3273249f0fc9
api/models/rat.js
api/models/rat.js
var mongoose, RatSchema, Schema; mongoose = require( 'mongoose' ); Schema = mongoose.Schema; RatSchema = new Schema({ 'archive': { default: false, type: Boolean }, 'CMDRname': { type: String }, 'createdAt': { type: Date }, 'drilled': { default: false, type: Boolean }, 'gamertag': { type: String }, 'lastModified': { type: Date }, 'joined': { default: Date.now(), type: Date }, 'netlog': { type: { 'commanderId': { type: String }, 'data': { type: Schema.Types.Mixed }, 'userId': { type: String } } }, 'nickname': { type: String } }); RatSchema.index({ 'CMDRname': 'text', 'gamertag': 'text', 'nickname': 'text' }); RatSchema.pre( 'save', function ( next ) { var timestamp; timestamp = Date.now(); this.createdAt = this.createdAt || timestamp; this.lastModified = timestamp; next(); }); RatSchema.set( 'toJSON', { virtuals: true, transform: function ( document, ret, options ) { ret.id = ret._id; delete ret._id; } }); module.exports = mongoose.model( 'Rat', RatSchema );
var mongoose, RatSchema, Schema; mongoose = require( 'mongoose' ); Schema = mongoose.Schema; RatSchema = new Schema({ 'archive': { default: false, type: Boolean }, 'CMDRname': { type: String }, 'createdAt': { type: Date }, 'drilled': { default: false, type: Boolean }, 'gamertag': { type: String }, 'lastModified': { type: Date }, 'joined': { default: Date.now(), type: Date }, 'netlog': { type: { 'commanderId': { type: String }, 'data': { type: Schema.Types.Mixed }, 'userId': { type: String } } }, 'nickname': { type: [String] } }); RatSchema.index({ 'CMDRname': 'text', 'gamertag': 'text', 'nickname': 'text' }); RatSchema.pre( 'save', function ( next ) { var timestamp; timestamp = Date.now(); this.createdAt = this.createdAt || timestamp; this.lastModified = timestamp; next(); }); RatSchema.set( 'toJSON', { virtuals: true, transform: function ( document, ret, options ) { ret.id = ret._id; delete ret._id; } }); module.exports = mongoose.model( 'Rat', RatSchema );
Add rescue field to store client's messages
Add rescue field to store client's messages
JavaScript
bsd-3-clause
FuelRats/api.fuelrats.com,FuelRats/api.fuelrats.com,FuelRats/api.fuelrats.com
0e854b660501e3bcdf01071392b9ab0ec8b9a5f0
src/components/Iframe/index.js
src/components/Iframe/index.js
import React, {PropTypes} from 'react' import injectSheet from '../../utils/jss' function Iframe({src, sheet: {classes}}) { return <iframe src={src} className={classes.iframe} /> } Iframe.propTypes = { src: PropTypes.string.isRequired, sheet: PropTypes.object.isRequired } const styles = { iframe: { width: '100%', height: '100%', border: 0 } } export default injectSheet(styles)(Iframe)
import React, {PropTypes} from 'react' import injectSheet from '../../utils/jss' function Iframe({src, sheet: {classes}}) { return <iframe src={src} className={classes.iframe} /> } Iframe.propTypes = { src: PropTypes.string.isRequired, sheet: PropTypes.object.isRequired } const styles = { iframe: { width: '100%', height: '100vh', minHeight: 50, border: 0, display: 'block' } } export default injectSheet(styles)(Iframe)
Fix iframe height after migration to vh
Fix iframe height after migration to vh
JavaScript
mit
cssinjs/cssinjs
b0fc06384fcddaf293c5c9f66b4a49b8f2f7c56b
app/index.js
app/index.js
import React from 'react' import ReactDOM from 'react-dom' import { Provider } from 'react-redux' import Routes from './routes' import Store from './store' ReactDOM.render( <Provider store={Store}> <Routes /> </Provider>, document.getElementById('root') )
import React from 'react' import ReactDOM from 'react-dom' import { Provider } from 'react-redux' import Routes from './routes' import Store from './store' ReactDOM.render( <Provider store={Store}> <Routes /> </Provider>, document.getElementById('application') )
Fix the root component id.
Fix the root component id.
JavaScript
mit
rhberro/the-react-client,rhberro/the-react-client
ccc12a7dae4b01674f9bc76efaefef5f901852e2
src/components/preview/Code.js
src/components/preview/Code.js
// @flow import { PureComponent } from 'react' import Lowlight from 'react-lowlight' import js from 'highlight.js/lib/languages/javascript' import type { Children } from 'react' type Props = { className:string, children: Children, } Lowlight.registerLanguage('js', js) export default class Code extends PureComponent<void, Props, void> { static languageClassNamePattern = /\s*language-([\w-]+)\s*/ // for lint props: Props get language (): string { const match = (this.props.className || '').match(Code.languageClassNamePattern) const lang = (match && match[1]) || '' return Lowlight.hasLanguage(lang) ? lang : '' } get value (): string { return this.props.children[0] } render () { return ( <Lowlight language={this.language} value={this.value} inline /> ) } }
// @flow import { PureComponent } from 'react' import Lowlight from 'react-lowlight' import type { Children } from 'react' import langMap from 'settings/languageNameMap' type Props = { className:string, children: Children, } type State = { language: string, } export default class Code extends PureComponent<void, Props, State> { static languageClassNamePattern = /\s*language-([\w-]+)\s*/ constructor (props: Props) { super(props) this.state = { language: '', } } state: State componentWillMount () { this.registerLanguage(this.props.className) } componentWillReceiveProps ({ className }: Props) { this.registerLanguage(className) } async registerLanguage (className: string) { const match = (className || '').match(Code.languageClassNamePattern) const langName = (match && match[1]) || '' const lang = langMap[langName] if (lang == null) { this.setState({ language: '' }) } else if (Lowlight.hasLanguage(langName)) { this.setState({ language: langName }) } else { Lowlight.registerLanguage(langName, await lang.load()) this.setState({ language: langName }) } } get value (): string { return this.props.children[0] } render () { return ( <Lowlight language={this.state.language} value={this.value} inline /> ) } }
Load language config for highlight.js dynamically
Load language config for highlight.js dynamically
JavaScript
mit
izumin5210/OHP,izumin5210/OHP
1433d3379014c115636cf0d472fb085c5397b4a7
test/mocha/github-2xx-76.js
test/mocha/github-2xx-76.js
"use strict"; var Promise = require("../../js/debug/bluebird.js"); Promise.longStackTraces(); var assert = require("assert"); describe("github276 - stack trace cleaner", function(){ specify("message with newline and a$_b should not be removed", function(done){ Promise.resolve(1).then(function() { throw new Error("Blah\n a$_b"); }).catch(function(e) { var msg = e.stack.split('\n')[1] assert(msg.indexOf('a$_b') >= 0, 'message should contain a$_b'); }).done(done, done); }); });
"use strict"; var Promise = require("../../js/debug/bluebird.js"); Promise.longStackTraces(); var assert = require("assert"); var isNodeJS = typeof process !== "undefined" && typeof process.execPath === "string"; if (isNodeJS) { describe("github276 - stack trace cleaner", function(){ specify("message with newline and a$_b should not be removed", function(done){ Promise.resolve(1).then(function() { throw new Error("Blah\n a$_b"); }).caught(function(e) { var msg = e.stack.split('\n')[1] assert(msg.indexOf('a$_b') >= 0, 'message should contain a$_b'); }).done(done, done); }); }); }
Add nodejs guard for nodejs test
Add nodejs guard for nodejs test
JavaScript
mit
tpphu/bluebird,joemcelroy/bluebird,lindenle/bluebird,BigDSK/bluebird,cwhatley/bluebird,avinoamr/bluebird,Wanderfalke/bluebird,tesfaldet/bluebird,paulcbetts/bluebird,timnew/bluebird,techniq/bluebird,robertn702/bluebird,atom-morgan/bluebird,Scientifik/bluebird,perfecting/bluebird,javraindawn/bluebird,RobinQu/bluebird,vladikoff/bluebird,StefanoDeVuono/bluebird,matklad/bluebird,perfecting/bluebird,alubbe/bluebird,impy88/bluebird,ryanwholey/bluebird,rrpod/bluebird,ziad-saab/bluebird,n1kolas/bluebird,ajitsy/bluebird,alubbe/bluebird,a25patel/bluebird,tpphu/bluebird,lo1tuma/bluebird,starkwang/bluebird,kidaa/bluebird,impy88/bluebird,codevlabs/bluebird,henryqdineen/bluebird,tesfaldet/bluebird,kidaa/bluebird,HBOCodeLabs/bluebird,petkaantonov/bluebird,linalu1/bluebird,ryanwholey/bluebird,ankushg/bluebird,avinoamr/bluebird,peterKaleta/bluebird,codevlabs/bluebird,reggi/bluebird,code-monkeys/bluebird,arenaonline/bluebird,code-monkeys/bluebird,janzal/bluebird,wainage/bluebird,cgvarela/bluebird,kjvalencik/bluebird,akinsella/bluebird,BridgeAR/bluebird,naoufal/bluebird,garysye/bluebird,davyengone/bluebird,rrpod/bluebird,ryanwholey/bluebird,esco/bluebird,janmeier/bluebird,mdarveau/bluebird,briandela/bluebird,gillesdemey/bluebird,TechnicalPursuit/bluebird,javraindawn/bluebird,Scientifik/bluebird,whatupdave/bluebird,abhishekgahlot/bluebird,justsml/bluebird,a25patel/bluebird,djchie/bluebird,tesfaldet/bluebird,bjonica/bluebird,DeX3/bluebird,moretti/bluebird,matklad/bluebird,BridgeAR/bluebird,yonjah/bluebird,abhishekgahlot/bluebird,DrewVartanian/bluebird,naoufal/bluebird,angelxmoreno/bluebird,jozanza/bluebird,cwhatley/bluebird,migclark/bluebird,fmoliveira/bluebird,moretti/bluebird,code-monkeys/bluebird,akinsella/bluebird,lo1tuma/bluebird,jozanza/bluebird,soyuka/bluebird,perfecting/bluebird,goopscoop/bluebird,a25patel/bluebird,StefanoDeVuono/bluebird,bjonica/bluebird,spion/bluebird,briandela/bluebird,ricardo-hdz/bluebird,peterKaleta/bluebird,javraindawn/bluebird,haohui/bluebird,DrewVartanian/bluebird,amelon/bluebird,Zeratul5/bluebird,fadzlan/bluebird,gillesdemey/bluebird,STRML/bluebird,ydaniv/bluebird,gillesdemey/bluebird,DrewVartanian/bluebird,xbenjii/bluebird,tpphu/bluebird,janzal/bluebird,fadzlan/bluebird,justsml/bluebird,P-Seebauer/bluebird,sandrinodimattia/bluebird,janmeier/bluebird,goofiw/bluebird,satyadeepk/bluebird,Scientifik/bluebird,TechnicalPursuit/bluebird,petkaantonov/bluebird,alubbe/bluebird,goofiw/bluebird,goopscoop/bluebird,matklad/bluebird,starkwang/bluebird,xdevelsistemas/bluebird,techniq/bluebird,timnew/bluebird,ydaniv/bluebird,cgvarela/bluebird,HBOCodeLabs/bluebird,bsiddiqui/bluebird,developmentstudio/bluebird,atom-morgan/bluebird,impy88/bluebird,lindenle/bluebird,paulcbetts/bluebird,illahi0/bluebird,goopscoop/bluebird,whatupdave/bluebird,briandela/bluebird,fadzlan/bluebird,cusspvz/bluebird,ydaniv/bluebird,haohui/bluebird,garysye/bluebird,yonjah/bluebird,ricardo-hdz/bluebird,djchie/bluebird,xbenjii/bluebird,amelon/bluebird,ScheerMT/bluebird,reggi/bluebird,johnculviner/bluebird,rrpod/bluebird,henryqdineen/bluebird,wainage/bluebird,ronaldbaltus/bluebird,Zeratul5/bluebird,dantheuber/bluebird,kidaa/bluebird,robertn702/bluebird,xdevelsistemas/bluebird,mcanthony/bluebird,mcanthony/bluebird,spion/bluebird,bjonica/bluebird,lo1tuma/bluebird,ronaldbaltus/bluebird,RobinQu/bluebird,BigDSK/bluebird,joemcelroy/bluebird,JaKXz/bluebird,henryqdineen/bluebird,esco/bluebird,RobinQu/bluebird,developmentstudio/bluebird,cgvarela/bluebird,davyengone/bluebird,dantheuber/bluebird,peterKaleta/bluebird,JaKXz/bluebird,migclark/bluebird,jozanza/bluebird,kjvalencik/bluebird,JaKXz/bluebird,illahi0/bluebird,mdarveau/bluebird,ajitsy/bluebird,bsiddiqui/bluebird,migclark/bluebird,atom-morgan/bluebird,BridgeAR/bluebird,codevlabs/bluebird,justsml/bluebird,amelon/bluebird,developmentstudio/bluebird,HBOCodeLabs/bluebird,enicolasWebs/bluebird,bsiddiqui/bluebird,linalu1/bluebird,linalu1/bluebird,STRML/bluebird,robertn702/bluebird,ajitsy/bluebird,soyuka/bluebird,cusspvz/bluebird,haohui/bluebird,STRML/bluebird,Wanderfalke/bluebird,cusspvz/bluebird,DeX3/bluebird,StefanoDeVuono/bluebird,avinoamr/bluebird,angelxmoreno/bluebird,esco/bluebird,joemcelroy/bluebird,timnew/bluebird,n1kolas/bluebird,ziad-saab/bluebird,arenaonline/bluebird,illahi0/bluebird,yonjah/bluebird,TechnicalPursuit/bluebird,P-Seebauer/bluebird,Zeratul5/bluebird,P-Seebauer/bluebird,enicolasWebs/bluebird,whatupdave/bluebird,ScheerMT/bluebird,ankushg/bluebird,fmoliveira/bluebird,kjvalencik/bluebird,ScheerMT/bluebird,dantheuber/bluebird,moretti/bluebird,vladikoff/bluebird,sandrinodimattia/bluebird,soyuka/bluebird,DeX3/bluebird,lindenle/bluebird,abhishekgahlot/bluebird,djchie/bluebird,vladikoff/bluebird,reggi/bluebird,cwhatley/bluebird,naoufal/bluebird,goofiw/bluebird,angelxmoreno/bluebird,garysye/bluebird,johnculviner/bluebird,satyadeepk/bluebird,mdarveau/bluebird,petkaantonov/bluebird,wainage/bluebird,sandrinodimattia/bluebird,mcanthony/bluebird,davyengone/bluebird,johnculviner/bluebird,xbenjii/bluebird,paulcbetts/bluebird,janzal/bluebird,ricardo-hdz/bluebird,fmoliveira/bluebird,satyadeepk/bluebird,n1kolas/bluebird,Wanderfalke/bluebird,xdevelsistemas/bluebird,techniq/bluebird,ronaldbaltus/bluebird,arenaonline/bluebird,ankushg/bluebird,ziad-saab/bluebird,enicolasWebs/bluebird,janmeier/bluebird,starkwang/bluebird,BigDSK/bluebird,akinsella/bluebird
92334651e178d2760434e8e1923ba691c69f448c
src/events/mouse-dispatcher.js
src/events/mouse-dispatcher.js
var slice = [].slice exports = function mouseDispatcher(name, fn) { return function(x, y) { var target = document.elementFromPoint(x, y) || document var event = new MouseEvent(name, { bubbles: true, clientX: x, clientY: y }) fn.apply(event, slice.call(arguments, 2)) target.dispatchEvent(event) } }
var slice = [].slice exports = function mouseDispatcher(name, fn) { return function(clientX, clientY, shiftKey, ctrlKey, altKey, metaKey) { var target = document.elementFromPoint(clientX, clientY) || document var event = new MouseEvent(name, { bubbles: true, clientX: clientX, clientY: clientY, shiftKey: shiftKey, ctrlKey: ctrlKey, altKey: altKey, metaKey: metaKey }) fn.apply(event, slice.call(arguments, 6)) target.dispatchEvent(event) } }
Handle modifier keys in mouse dispatcher
Handle modifier keys in mouse dispatcher
JavaScript
unlicense
freedraw/core,freedraw/core
112f786717f405f0b2b708fe67d4b6df780386ea
models/Author.js
models/Author.js
var keystone = require('keystone'); var Types = keystone.Field.Types; /** * Author Model * ========== */ var Author = new keystone.List('Author'); Author.add({ firstName: { type: Types.Text, initial: true, required: true, index: true }, lastName: { type: Types.Text, initial: true, required: true, index: true }, email: { type: Types.Email }, affiliations: { type: Types.Relationship, ref: 'Organization', many: true }, }); /** * Registration */ Author.defaultColumns = 'firstName, lastName'; Author.register();
var keystone = require('keystone'); var Types = keystone.Field.Types; /** * Author Model * ========== */ var Author = new keystone.List('Author'); Author.add({ name: { type: Types.Name, initial: true, required: true, index: true }, email: { type: Types.Email }, affiliations: { type: Types.Relationship, ref: 'Organization', many: true }, }); /** * Registration */ Author.defaultColumns = 'name, affiliations'; Author.register();
Use single name field for authors
Use single name field for authors
JavaScript
mit
zharley/papers,zharley/papers
f768f26e0b1da687a04da7256047d12d34b11f1c
examples/example2.js
examples/example2.js
var ping = require("../index"); var hosts = ['192.168.1.1', 'google.com', 'yahoo.com']; hosts.forEach(function (host) { ping.promise.probe(host) .then(function (res) { console.log(res); }) .done(); }); hosts.forEach(function (host) { ping.promise.probe(host, { timeout: 10, extra: ["-i 2"] }) .then(function (res) { console.log(res); }) .done(); });
var ping = require("../index"); var hosts = ['192.168.1.1', 'google.com', 'yahoo.com']; hosts.forEach(function (host) { ping.promise.probe(host) .then(function (res) { console.log(res); }) .done(); }); hosts.forEach(function (host) { ping.promise.probe(host, { timeout: 10, extra: ["-i", "2"] }) .then(function (res) { console.log(res); }) .done(); });
Fix bug on window platform
Fix bug on window platform --Overview 1. Window's ping command treat '-i 2' as an invalid option. Therefore, we must split them up. IE using ['-i', '2'] instead of ['-i 2']
JavaScript
mit
alexgervais/node-ping,danielzzz/node-ping
2ba85374c28132da84e6f7679bb1bb4f487db14d
webpack.config.js
webpack.config.js
var path = require('path'); var webpack = require('webpack'); var Clean = require('clean-webpack-plugin'); var webpackConfig = require("./webpack-base-config"); webpackConfig.entry = path.resolve(__dirname, 'src/main.js'); if (process.env.npm_lifecycle_event === 'release') { webpackConfig.plugins.push(new webpack.optimize.UglifyJsPlugin({ compress: {warnings: false}, output: {comments: false} })); } else { webpackConfig.plugins.push(new Clean(['dist'])); } webpackConfig.output = { path: path.resolve(__dirname, 'dist'), publicPath: '<%=baseUrl%>/', filename: 'clappr.js', library: 'Clappr', libraryTarget: 'umd', }; module.exports = webpackConfig;
var path = require('path'); var webpack = require('webpack'); var Clean = require('clean-webpack-plugin'); var webpackConfig = require("./webpack-base-config"); webpackConfig.entry = path.resolve(__dirname, 'src/main.js'); if (process.env.npm_lifecycle_event === 'release') { webpackConfig.plugins.push(new webpack.optimize.UglifyJsPlugin({ compress: {warnings: false}, output: {comments: false} })); } else { webpackConfig.plugins.push(new Clean(['dist'], {verbose: false})); } webpackConfig.output = { path: path.resolve(__dirname, 'dist'), publicPath: '<%=baseUrl%>/', filename: 'clappr.js', library: 'Clappr', libraryTarget: 'umd', }; module.exports = webpackConfig;
Set verbose to false in webpack clean plugin
Set verbose to false in webpack clean plugin
JavaScript
bsd-3-clause
flavioribeiro/clappr,clappr/clappr,flavioribeiro/clappr,clappr/clappr,clappr/clappr,flavioribeiro/clappr
d341843ff99eeb5b3371e8e13420363366f2d8bf
js/components/games/DeployButton.react.js
js/components/games/DeployButton.react.js
"use strict"; var _ = require('mori'); var Router = require('react-router'); var React = require('react'); var mori = require("mori"); var UnitCell = require('../board/UnitCell.react.js'); var GameStore = require('../../stores/GameStore.js'); var ProfileLink = require('../common/ProfileLink.react.js'); var GameActions = require('../../actions/GameActions.js'); module.exports = React.createClass({ render: function () { var game = this.props.game; var state = _.getIn(game, ["board", "state"]); var stash = _.getIn(game, ["board", "stash", this.props.playerCode]); var originalStash = _.getIn(this.props.originalGame, ["board", "stash", this.props.playerCode]); var css = "btn btn-info"; if("deploy" === state) { if(_.isEmpty(originalStash)) { css = "hide"; } else if(!_.isEmpty(stash)) { css = "btn btn-default disabled"; } } else { css = "hide"; } return ( <a onClick={this.click} className={css}>Deploy</a> ); }, click: function click(ev) { GameActions.deployGame(this.props.game); } });
"use strict"; var _ = require('mori'); var Router = require('react-router'); var React = require('react'); var mori = require("mori"); var UnitCell = require('../board/UnitCell.react.js'); var GameStore = require('../../stores/GameStore.js'); var ProfileLink = require('../common/ProfileLink.react.js'); var GameActions = require('../../actions/GameActions.js'); module.exports = React.createClass({ render: function () { var game = this.props.game; var stash = _.getIn(game, ["board", "stash", this.props.playerCode]); var originalGame = this.props.originalGame; var state = _.getIn(originalGame, ["board", "state"]); var originalStash = _.getIn(originalGame, ["board", "stash", this.props.playerCode]); console.log(state) var css = "btn btn-info"; if("deploy" === state) { if(_.isEmpty(originalStash)) { css = "hide"; } else if(!_.isEmpty(stash)) { css = "btn btn-default disabled"; } } else { css = "hide"; } return ( <a onClick={this.click} className={css}>Deploy</a> ); }, click: function click(ev) { GameActions.deployGame(this.props.game); } });
Fix deploy button for second player
Fix deploy button for second player
JavaScript
mit
orionsbelt-battlegrounds/frontend,orionsbelt-battlegrounds/frontend,orionsbelt-battlegrounds/frontend
4012357932dc0d9acb17076cd321affa6d94cb81
src/ggrc/assets/javascripts/components/assessment/info-pane/info-pane.js
src/ggrc/assets/javascripts/components/assessment/info-pane/info-pane.js
/*! Copyright (C) 2017 Google Inc., authors, and contributors Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> */ (function (can, GGRC) { 'use strict'; var tpl = can.view(GGRC.mustache_path + '/components/assessment/info-pane/info-pane.mustache'); /** * Assessment Specific Info Pane View Component */ GGRC.Components('assessmentInfoPane', { tag: 'assessment-info-pane', template: tpl, viewModel: { define: { isLocked: { type: 'htmlbool', value: false } }, instance: {} } }); })(window.can, window.GGRC);
/*! Copyright (C) 2017 Google Inc., authors, and contributors Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> */ (function (can, GGRC) { 'use strict'; var tpl = can.view(GGRC.mustache_path + '/components/assessment/info-pane/info-pane.mustache'); /** * Assessment Specific Info Pane View Component */ GGRC.Components('assessmentInfoPane', { tag: 'assessment-info-pane', template: tpl, viewModel: { define: { mappedSnapshots: { value: function () { return []; } }, controls: { get: function () { return this.attr('mappedSnapshots') .filter(function (item) { return item.child_type === 'Control'; }); } }, relatedInformation: { get: function () { return this.attr('mappedSnapshots') .filter(function (item) { return item.child_type !== 'Control'; }); } } }, instance: null, getSnapshotQuery: function () { var relevantFilters = [{ type: this.attr('instance.type'), id: this.attr('instance.id'), operation: 'relevant' }]; return GGRC.Utils.QueryAPI .buildParam('Snapshot', {}, relevantFilters, [], []); }, requestQuery: function (query) { var dfd = can.Deferred(); this.attr('isLoading', true); GGRC.Utils.QueryAPI .batchRequests(query) .done(function (response) { var type = Object.keys(response)[0]; var values = response[type].values; dfd.resolve(values); }) .fail(function () { dfd.resolve([]); }) .always(function () { this.attr('isLoading', false); }.bind(this)); return dfd; }, loadSnapshots: function () { var query = this.getSnapshotQuery(); return this.requestQuery(query); } }, init: function () { this.viewModel.attr('mappedSnapshots') .replace(this.viewModel.loadSnapshots()); }, events: { '{viewModel.instance} related_destinations': function () { console.info('Was related_destinations called!!!!', arguments); } } }); })(window.can, window.GGRC);
Add Extra Loading Logic to Assessment Info Pane Component
Add Extra Loading Logic to Assessment Info Pane Component
JavaScript
apache-2.0
AleksNeStu/ggrc-core,AleksNeStu/ggrc-core,AleksNeStu/ggrc-core,AleksNeStu/ggrc-core
e2fb55b5ff165df0f58e4cdeffeb1c34f49fe382
angular-toggle-switch.js
angular-toggle-switch.js
angular.module('toggle-switch', ['ng']).directive('toggleSwitch', function() { return { restrict: 'EA', replace: true, scope: { model: '=' }, template: '<div class="switch" ng-click="toggle()"><div class="switch-animate switch-off" ng-class="{\'switch-off\': !model, \'switch-on\': model}"><span class="switch-left">On</span><span class="knob">&nbsp;</span><span class="switch-right">Off</span></div></div>', link: function($scope, element, attrs) { if ($scope.model == null) { $scope.model = false; } return $scope.toggle = function() { return $scope.model = !$scope.model; }; } }; });
angular.module('toggle-switch', ['ng']).directive('toggleSwitch', function() { return { restrict: 'EA', replace: true, scope: { model: '=' }, template: '<div class="switch" ng-click="toggle()"><div class="switch-animate" ng-class="{\'switch-off\': !model, \'switch-on\': model}"><span class="switch-left">On</span><span class="knob">&nbsp;</span><span class="switch-right">Off</span></div></div>', link: function($scope, element, attrs) { if ($scope.model == null) { $scope.model = false; } return $scope.toggle = function() { return $scope.model = !$scope.model; }; } }; });
Remove default class switch-off (fix css bug when a switcher is set to true by default)
Remove default class switch-off (fix css bug when a switcher is set to true by default)
JavaScript
mit
JeromeSadou/angular-toggle-switch,cgarvis/angular-toggle-switch,JumpLink/angular-toggle-switch,nilpath/angular-toggle-switch,razvanz/angular-toggle-switch,zachlysobey/angular-toggle-switch,ProtonMail/angular-toggle-switch,nilpath/angular-toggle-switch,JeromeSadou/angular-toggle-switch,chris110408/angular-toggle-switch,JumpLink/angular-toggle-switch
56733b29e6b79dd0b7b00f7a9fe778b209ceaa73
backend/server/apikey.js
backend/server/apikey.js
// apikey module validates the apikey argument used in the call. It // caches the list of users to make lookups faster. module.exports = function(users) { 'use strict'; let apikeyCache = require('./apikey-cache')(users); let httpStatus = require('http-status'); // whiteList contains paths that don't require // a valid apikey. let whiteList = { "/login": true, "/socket.io/socket.io.js": true, "/socket.io/": true }; // validateAPIKey Looks up the apikey. If none is specified, or a // bad key is passed then abort the calls and send back an 401. return function *validateAPIKey(next) { if (!(this.path in whiteList)) { let UNAUTHORIZED = httpStatus.UNAUTHORIZED; let apikey = this.query.apikey || this.throw(UNAUTHORIZED, 'Not authorized'); let user = yield apikeyCache.find(apikey); if (! user) { this.throw(UNAUTHORIZED, 'Not authorized'); } this.reqctx = { user: user }; } yield next; }; };
// apikey module validates the apikey argument used in the call. It // caches the list of users to make lookups faster. module.exports = function(users) { 'use strict'; let apikeyCache = require('./apikey-cache')(users); let httpStatus = require('http-status'); // whiteList contains paths that don't require // a valid apikey. let whiteList = { "/login": true }; // validateAPIKey Looks up the apikey. If none is specified, or a // bad key is passed then abort the calls and send back an 401. return function *validateAPIKey(next) { if (!(this.path in whiteList)) { let UNAUTHORIZED = httpStatus.UNAUTHORIZED; let apikey = this.query.apikey || this.throw(UNAUTHORIZED, 'Not authorized'); let user = yield apikeyCache.find(apikey); if (! user) { this.throw(UNAUTHORIZED, 'Not authorized'); } this.reqctx = { user: user }; } yield next; }; };
Remove console statement. Cleanup whitelist since socket.io paths will never been seen in route mount point.
Remove console statement. Cleanup whitelist since socket.io paths will never been seen in route mount point.
JavaScript
mit
materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org
0222a20e870c475b0d3c979ad3d09d0c0ea69706
lib/assets/javascripts/dashboard/data/authenticated-user-model.js
lib/assets/javascripts/dashboard/data/authenticated-user-model.js
var Backbone = require('backbone'); module.exports = Backbone.Model.extend({ defaults: { username: '', avatar_url: '' }, url: function () { return '//' + this.getHost() + '/api/v3/me'; }, getHost: function () { var currentHost = window.location.host; return this.get('host') ? this.get('host') : currentHost; } });
var Backbone = require('backbone'); module.exports = Backbone.Model.extend({ defaults: { username: '', avatar_url: '' }, url: function () { return `//${this.getHost()}/api/v1/get_authenticated_users`; }, getHost: function () { var currentHost = window.location.host; return this.get('host') ? this.get('host') : currentHost; } });
Change AuthenticatedUser URL to query /v1/get_authenticated_users instead of /v3/me
Change AuthenticatedUser URL to query /v1/get_authenticated_users instead of /v3/me
JavaScript
bsd-3-clause
CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb
a939f2794cac08ee94baf53c3fe5587b3f122725
rollup.config.js
rollup.config.js
/** * NOTE: This file must only use node v0.12 features + ES modules. */ import babel from 'rollup-plugin-babel'; import json from 'rollup-plugin-json'; import babelrc from 'babelrc-rollup'; const pkg = require('./package.json'); const external = Object.keys(pkg.dependencies).concat(['path', 'fs']); export default { entry: 'src/index.js', plugins: [ json(), babel(babelrc()) ], external: external, targets: [ { format: 'cjs', dest: pkg['main'] }, { format: 'es6', dest: pkg['jsnext:main'] } ] };
/** * NOTE: This file must only use node v0.12 features + ES modules. */ import babel from 'rollup-plugin-babel'; import json from 'rollup-plugin-json'; import babelrc from 'babelrc-rollup'; var pkg = require('./package.json'); var external = Object.keys(pkg.dependencies).concat(['path', 'fs']); export default { entry: 'src/index.js', plugins: [ json(), babel(babelrc()) ], external: external, targets: [ { format: 'cjs', dest: pkg['main'] }, { format: 'es6', dest: pkg['jsnext:main'] } ] };
Use `var` instead of `const` for node 0.12 support.
Use `var` instead of `const` for node 0.12 support.
JavaScript
mit
alangpierce/decaffeinate,decaffeinate/decaffeinate,alangpierce/decaffeinate,eventualbuddha/decaffeinate,decaffeinate/decaffeinate,alangpierce/decaffeinate,eventualbuddha/decaffeinate
df4079541ec0ca698bbabedf176b164f25833551
rollup.config.js
rollup.config.js
import commonjs from 'rollup-plugin-commonjs'; import babel from 'rollup-plugin-babel'; import uglify from 'rollup-plugin-uglify'; import replace from 'rollup-plugin-replace'; import resolve from 'rollup-plugin-node-resolve'; const env = process.env.NODE_ENV; const config = { output: { name: 'react-uncontrolled-form', format: 'umd', globals: {react: 'React'} }, external: ['react'], plugins: [ resolve({jsnext: true}), commonjs({include: 'node_modules/**'}), babel({exclude: 'node_modules/**'}), replace({'process.env.NODE_ENV': JSON.stringify(env)}) ] }; if (env === 'production') { config.plugins.push( uglify({ compress: { pure_getters: true, unsafe: true, unsafe_proto: true, passes: 2, } }) ); } export default config;
import commonjs from 'rollup-plugin-commonjs'; import babel from 'rollup-plugin-babel'; import uglify from 'rollup-plugin-uglify'; import replace from 'rollup-plugin-replace'; import resolve from 'rollup-plugin-node-resolve'; const env = process.env.NODE_ENV; const config = { output: { name: 'react-uncontrolled-form', format: 'umd', globals: {react: 'React'} }, external: ['react'], plugins: [ resolve({jsnext: true}), commonjs({include: 'node_modules/**'}), babel({exclude: 'node_modules/**'}), replace({'process.env.NODE_ENV': JSON.stringify(env)}) ] }; if (env === 'production') { config.plugins.push( uglify({ compress: { pure_getters: true, unsafe: true, unsafe_proto: true } }) ); } export default config;
Remove unnecessary uglify `passes` property
Remove unnecessary uglify `passes` property
JavaScript
mit
ericvaladas/formwood
cc6731b13b26a56aa705a8835605009f3e11f36c
routes/signup.js
routes/signup.js
var bcrypt = require('bcrypt'); var crypto = require('crypto'); var passport = require('passport'); var request = require('request'); var SALT = process.env.SALT; var SIGNUP_URL = process.env.LANDLINE_API + '/teams'; module.exports = function(router) { router.get('/signup', function(req, res) { res.render('signup', { title: 'Landline | Signup' }); }); router.post('/signup', function(req, res) { if (!req.body.email || !req.body.password || !req.body.name || !req.body.url) { return res.render('signup', { title: 'Landline | Signup', error: 'All fields are required' }); } var password = req.body.password; req.body.name = req.body.name.toLowerCase(); req.body.password = bcrypt.hashSync(password, SALT); req.body.secret = crypto.randomBytes(48).toString('hex'); request.post({ url: SIGNUP_URL, json: true, body: req.body }, function(err, response) { if (err) { return res.render('signup', { title: 'Landline | Signup', error: err.message }); } req.session.teamName = req.body.name; req.session.jwt = response.body.token; passport.authenticate('local')(req, res, function () { res.redirect('/settings'); }); }); }); };
var bcrypt = require('bcrypt'); var crypto = require('crypto'); var passport = require('passport'); var request = require('request'); var SALT = process.env.SALT; var SIGNUP_URL = process.env.LANDLINE_API + '/teams'; module.exports = function(router) { router.get('/signup', function(req, res) { res.render('signup', { title: 'Landline | Signup' }); }); router.post('/signup', function(req, res) { if (!req.body.email || !req.body.password || !req.body.name || !req.body.url) { return res.render('signup', { title: 'Landline | Signup', error: 'All fields are required' }); } var password = req.body.password; req.body.name = req.body.name.toLowerCase(); req.body.password = bcrypt.hashSync(password, SALT); req.body.secret = crypto.randomBytes(24).toString('hex'); request.post({ url: SIGNUP_URL, json: true, body: req.body }, function(err, response) { if (err) { return res.render('signup', { title: 'Landline | Signup', error: err.message }); } req.session.teamName = req.body.name; req.session.jwt = response.body.token; passport.authenticate('local')(req, res, function () { res.redirect('/settings'); }); }); }); };
Make the initial shared secret less obnoxiously long
Make the initial shared secret less obnoxiously long
JavaScript
agpl-3.0
asm-products/landline.io,asm-products/landline.io
80e664a171286279828e2bb62781a8d5b3c8e881
server/config.js
server/config.js
/* eslint-disable no-process-env */ export const NODE_ENV = process.env.NODE_ENV || 'development'; export const isDevelopment = () => NODE_ENV === 'development'; export const isProduction = () => NODE_ENV === 'production'; export const PORT = process.env.PORT || 3000;
/* eslint-disable no-process-env */ export const NODE_ENV = process.env.NODE_ENV || 'development'; export const isDevelopment = () => NODE_ENV === 'development'; export const isProduction = () => NODE_ENV === 'production'; export const PORT = process.env.PORT || 3010;
Update server to be from port 3010
Update server to be from port 3010
JavaScript
mit
golmansax/my-site-in-express,golmansax/my-site-in-express
3b07035c1790c787899044c44c89b84e048deadd
server/server.js
server/server.js
var assert = require('assert'); var config = require('config'); var express = require('express'); var mongoose = require('mongoose'); var db = mongoose.connection; var locationSchema = new mongoose.Schema({ 'category': String, 'location': { 'latitude': Number, 'longitude': Number } }); var Location = mongoose.model('Location', locationSchema); mongoose.connect(config.get('mongo').url); var app = express(); // For debugging in development app.set('json spaces', 2); app.get('/', function(req, res) { res.json({}); }); app.get('/locations', function(req, res) { Location.find(function(_err, locations) { return res.json(locations); }); }); var server = app.listen(8080, function() { console.log('Server up'); });
var assert = require('assert'); var config = require('config'); var express = require('express'); var mongoose = require('mongoose'); var db = mongoose.connection; var locationSchema = new mongoose.Schema({ 'category': String, 'location': { 'latitude': Number, 'longitude': Number } }); var Location = mongoose.model('Location', locationSchema); mongoose.connect(config.get('mongo').url); var app = express(); // For debugging in development app.set('json spaces', 2); app.get('/', function(req, res) { res.json({}); }); app.get('/locations', function(req, res) { Location.find({'category': req.query.category}, function(_err, locations) { return res.json(locations); }); }); var server = app.listen(8080, function() { console.log('Server up'); });
Add filtering /locations by category
Add filtering /locations by category
JavaScript
mit
volontario/volontario-server
124e478cf6849a523910e2bd58d98b8d645bcd43
src/index.js
src/index.js
#!/usr/bin/env node --harmony var inquirer = require("inquirer"); var makeLicense = require("./make-license.js") console.log("make-license"); var questions = [ { type: "list", name: "license", message: "Choose a License", choices: [ "MIT", "ISC", "BSD 3", "UNLICENSE", "NO LICENSE" ] } ]; inquirer.prompt(questions, function( answers ) { makeLicense(answers); });
#!/usr/bin/env node --harmony var inquirer = require("inquirer"); var makeLicense = require("./make-license.js") console.log("make-license"); var questions = [ { type: "list", name: "license", message: "Choose a License", choices: [ "MIT", "ISC", "BSD 2", "BSD 3", "UNLICENSE", "NO LICENSE" ] } ]; inquirer.prompt(questions, function( answers ) { makeLicense(answers); });
Add bsd 2 to menu
Add bsd 2 to menu
JavaScript
mit
accraze/make-license,accraze/make-license
e2ce6b77eabc0cfabe06e443298734e8629ad8c2
src/index.js
src/index.js
define([ "text!src/welcome.md" ], function(welcomeMessage) { var commands = codebox.require("core/commands"); var dialogs = codebox.require("utils/dialogs"); var File = codebox.require("models/file"); // About dialog commands.register({ id: "about.show", title: "Application: About", shortcuts: [ "mod+shift+a" ], run: function() { return dialogs.alert("About Codebox"); } }); // Welcome message commands.register({ id: "about.welcome", title: "Application: Welcome", run: function() { return commands.run("file.open", { file: File.buffer("welcome.md", welcomeMessage) }) } }); });a
define([ "text!src/welcome.md" ], function(welcomeMessage) { var commands = codebox.require("core/commands"); var dialogs = codebox.require("utils/dialogs"); var File = codebox.require("models/file"); // About dialog commands.register({ id: "about.show", title: "Application: About", run: function() { return dialogs.alert("About Codebox"); } }); // Welcome message commands.register({ id: "about.welcome", title: "Application: Welcome", run: function() { return commands.run("file.open", { file: File.buffer("welcome.md", welcomeMessage) }) } }); });a
Remove shortcut for about dialog
Remove shortcut for about dialog
JavaScript
apache-2.0
etopian/codebox-package-about,etopian/codebox-package-about,CodeboxIDE/package-about,CodeboxIDE/package-about
22bab20dd6ef60c7a372257c41d8a026c73b477a
src/index.js
src/index.js
/* @flow */ import './vendor'; import ReactDOM from 'react-dom'; import routes from './routes'; setTimeout(() => { ReactDOM.render(routes, document.querySelector('#webedit')); }, 500);
/* @flow */ import './vendor'; import ReactDOM from 'react-dom'; import routes from './routes'; document.addEventListener('DOMContentLoaded', () => { ReactDOM.render(routes, document.querySelector('#webedit')); });
Use a dom ready event instead of timeout speculations
Use a dom ready event instead of timeout speculations
JavaScript
mit
blinkenrocket/webedit-react,blinkenrocket/webedit-react
f3f41884b55ed4b039f30b1604c6d69be2f6c739
src/index.js
src/index.js
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import YTSearch from 'youtube-api-search'; import SearchBar from './components/SearchBar'; import VideoList from './components/VideoList'; const YT_API = 'AIzaSyDqL_re6cE8YhtNr_O7GvX1SX3aQo1clyg'; class App extends Component { constructor(props) { super(props); this.state = { videos: [] }; YTSearch({ key: YT_API, term: 'coc'}, (videos) => { this.setState({ videos }); }); } render() { return ( <div> <SearchBar /> <VideoList videos={this.state.videos} /> </div> ); } } ReactDOM.render(<App />, document.querySelector('.container'));
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import YTSearch from 'youtube-api-search'; import SearchBar from './components/SearchBar'; import VideoList from './components/VideoList'; const YT_API = 'AIzaSyDqL_re6cE8YhtNr_O7GvX1SX3aQo1clyg'; class App extends Component { constructor(props) { super(props); this.state = { videos: undefined }; YTSearch({ key: YT_API, term: 'coc'}, (videos) => { this.setState({ videos }); }); } render() { return ( <div> <SearchBar /> <VideoList videos={this.state.videos} /> </div> ); } } ReactDOM.render(<App />, document.querySelector('.container'));
Set state.video value to undefined
Set state.video value to undefined
JavaScript
mit
mimukit/react-youtube-app,mimukit/react-youtube-app
aabdea65e3187b6b267896464b86333dcc3233d5
src/index.js
src/index.js
import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter, Route } from 'react-router-dom'; import './styles/index.css'; import Background from './components/Background'; import Footer from './components/Footer'; import Header from './components/Header'; import ScrollToTop from './components/ScrollToTop'; import Home from './scenes/Home'; import Store from './scenes/Store'; import registerServiceWorker from './registerServiceWorker'; import './i18n'; if (process.env.NODE_ENV === 'production') { window.Raven .config('https://0ddfcefcf922465488c2dde443f9c9d5@sentry.io/230876') .install(); } ReactDOM.render( <BrowserRouter> <ScrollToTop> <Background /> <Header /> <Route exact path="/" component={Home} /> <Route path="/store" component={Store} /> <Footer /> </ScrollToTop> </BrowserRouter>, document.getElementById('root'), ); registerServiceWorker();
import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter as Router, Redirect, Route, Switch, } from 'react-router-dom'; import './styles/index.css'; import Background from './components/Background'; import Footer from './components/Footer'; import Header from './components/Header'; import ScrollToTop from './components/ScrollToTop'; import Home from './scenes/Home'; import Store from './scenes/Store'; import registerServiceWorker from './registerServiceWorker'; import './i18n'; if (process.env.NODE_ENV === 'production') { window.Raven .config('https://0ddfcefcf922465488c2dde443f9c9d5@sentry.io/230876') .install(); } ReactDOM.render( <Router> <ScrollToTop> <Background /> <Header /> <Switch> <Route exact path="/" component={Home} /> <Route path="/store" component={Store} /> <Redirect from="*" to="/" /> </Switch> <Footer /> </ScrollToTop> </Router>, document.getElementById('root'), ); registerServiceWorker();
Add Switch and Redirect for Router
Add Switch and Redirect for Router
JavaScript
mit
ELTCOIN/website
ee50f51a89fc140102d3b6d576762d453443299e
src/index.js
src/index.js
// Return Promise const imageMerge = (sources = []) => new Promise(resolve => { // Load sources const images = sources.map(source => new Promise(resolve => { const img = new Image(); img.onload = () => resolve(Object.assign({}, source, {img})); img.src = source.src; })); // Create canvas const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); // When sources have loaded Promise.all(images) .then(images => { // Set canvas dimensions canvas.width = Math.max(...images.map(image => image.img.width)); canvas.height = Math.max(...images.map(image => image.img.height)); // Draw images to canvas images.forEach(image => ctx.drawImage(image.img, image.x || 0, image.y || 0)); // Resolve data uri resolve(canvas.toDataURL()); }); }); module.exports = imageMerge;
// Return Promise const imageMerge = (sources = []) => new Promise(resolve => { // Load sources const images = sources.map(source => new Promise(resolve => { // Convert strings to objects if (typeof source === 'string') { source = {src: source}; } // Resolve source and img when loaded const img = new Image(); img.onload = () => resolve(Object.assign({}, source, {img})); img.src = source.src; })); // Create canvas const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); // When sources have loaded Promise.all(images) .then(images => { // Set canvas dimensions canvas.width = Math.max(...images.map(image => image.img.width)); canvas.height = Math.max(...images.map(image => image.img.height)); // Draw images to canvas images.forEach(image => ctx.drawImage(image.img, image.x || 0, image.y || 0)); // Resolve data uri resolve(canvas.toDataURL()); }); }); module.exports = imageMerge;
Allow array of src strings to be passed in
Allow array of src strings to be passed in
JavaScript
mit
lukechilds/merge-images
5e86a4ba2ebe27b0971d8cb1b569c27dbe3fba37
src/index.js
src/index.js
import { certificates, certificatesAsync } from './certificates'; import { sign, signAsync } from './sign'; import { paramsForDetachedSignature, paramsForDetachedSignatureAsync, } from './params_for_detached_signature'; import { digestValue, digestValueAsync } from './digest_value'; import { cadesplugin } from './constants'; console.log('----', cadesplugin); /** * @class * @name CryptoProProvider * @description Module provide methods for signing requests with Crypto Pro * @author Vitaly Mashanov <vvmashanov@yandex.ru> */ /** * @function * @name isAsync * @description Checking, which method used by browser (Async or NPAPI) * @return {boolean} */ const isAsync = () => (cadesplugin.CreateObjectAsync || false); export default { certificates: isAsync() ? certificatesAsync : certificates, sign: isAsync() ? signAsync : sign, paramsForDetachedSignature: isAsync() ? paramsForDetachedSignatureAsync : paramsForDetachedSignature, digestValue: isAsync() ? digestValueAsync : digestValue, };
import { certificates, certificatesAsync } from './certificates'; import { sign, signAsync } from './sign'; import { paramsForDetachedSignature, paramsForDetachedSignatureAsync, } from './params_for_detached_signature'; import { digestValue, digestValueAsync } from './digest_value'; import { cadesplugin } from './constants'; /** * @class * @name CryptoProProvider * @description Module provide methods for signing requests with Crypto Pro * @author Vitaly Mashanov <vvmashanov@yandex.ru> */ /** * @function * @name isAsync * @description Checking, which method used by browser (Async or NPAPI) * @return {boolean} */ const isAsync = () => (cadesplugin.CreateObjectAsync || false); export default { certificates: isAsync() ? certificatesAsync : certificates, sign: isAsync() ? signAsync : sign, paramsForDetachedSignature: isAsync() ? paramsForDetachedSignatureAsync : paramsForDetachedSignature, digestValue: isAsync() ? digestValueAsync : digestValue, };
Call of console was deleted
Call of console was deleted
JavaScript
mit
VMashanov/crypto-pro-provider,VMashanov/crypto-pro-provider
7d299640acbdb594561f493bd78868a5281e7e4d
app/angular/services/friend_service.js
app/angular/services/friend_service.js
'use strict'; module.exports = function(app) { app.service('FriendService', ['$rootScope', '$http', function($rs, $http) { let allFriends = {}; let getAllFriends = function(emailOrUsername) { return new Promise((resolve, reject) => { let userData = { emailOrUsername: emailOrUsername, }; $http.post(`${$rs.baseUrl}/friends/all`, userData) .then((friends) => { allFriends.friends = friends.data; resolve(); }) .catch((err) => { console.log('error getting all friends'); }); }); } let addFriend = function(friendId) { let friendData = { _id: friendId, }; $http.post(`${$rs.baseUrl}/friends/add`, friendData) .then((res) => { console.log(res.data); }) .catch((err) => { console.log(err.data); }); }; return { getAllFriends: getAllFriends, addFriend: addFriend, data: { allFriends: allFriends, }, } }]); }
'use strict'; module.exports = function(app) { app.service('FriendService', ['$rootScope', '$http', function($rs, $http) { let data = { allFriends: {}, }; let getAllFriends = function(emailOrUsername) { let userData = { emailOrUsername: emailOrUsername, }; return $http.post(`${$rs.baseUrl}/friends/all`, userData) .then((friends) => { data.allFriends.friends = friends.data; }) .catch((err) => { console.log('error getting all friends'); }); } let addFriend = function(friendId) { let friendData = { _id: friendId, }; return $http.post(`${$rs.baseUrl}/friends/add`, friendData) .then((res) => { console.log(res.data); }) .catch((err) => { console.log(err.data); }); }; return { getAllFriends: getAllFriends, addFriend: addFriend, data: data, } }]); }
Remove promises returning data from Friend Service. Unused.
Remove promises returning data from Friend Service. Unused.
JavaScript
mit
sendjmoon/GolfFourFriends,sendjmoon/GolfFourFriends
7059a9d40f27b2ff3bd1acb0d9b3a7a0e72bdd8a
examples/main-page/main.js
examples/main-page/main.js
window.onload = function() { d3.json("../examples/data/gitstats.json", function(data) { data.forEach(function(d) { d.date = new Date(d.date); d.name = d.name === "ashwinraman9" ? "aramaswamy" : d.name; }); var dataset = {data: data, metadata: {}}; var commitSVG = d3.select("#intro-chart"); sizeSVG(commitSVG); commitChart(commitSVG, dataset); var scatterFullSVG = d3.select("#scatter-full"); sizeSVG(scatterFullSVG); scatterFull(scatterFullSVG, dataset); var lineSVG = d3.select("#line-chart"); sizeSVG(lineSVG); lineChart(lineSVG, dataset); }); } function sizeSVG(svg) { var width = svg.node().clientWidth; var height = Math.min(width*.75, 600); svg.attr("height", height); }
window.onload = function() { d3.json("examples/data/gitstats.json", function(data) { data.forEach(function(d) { d.date = new Date(d.date); d.name = d.name === "ashwinraman9" ? "aramaswamy" : d.name; }); var dataset = {data: data, metadata: {}}; var commitSVG = d3.select("#intro-chart"); sizeSVG(commitSVG); commitChart(commitSVG, dataset); var scatterFullSVG = d3.select("#scatter-full"); sizeSVG(scatterFullSVG); scatterFull(scatterFullSVG, dataset); var lineSVG = d3.select("#line-chart"); sizeSVG(lineSVG); lineChart(lineSVG, dataset); }); } function sizeSVG(svg) { var width = svg.node().clientWidth; var height = Math.min(width*.75, 600); svg.attr("height", height); }
Fix it gau! oh godgp
Fix it gau! oh godgp
JavaScript
mit
gdseller/plottable,alyssaq/plottable,jacqt/plottable,softwords/plottable,palantir/plottable,iobeam/plottable,palantir/plottable,NextTuesday/plottable,palantir/plottable,gdseller/plottable,iobeam/plottable,danmane/plottable,softwords/plottable,jacqt/plottable,jacqt/plottable,danmane/plottable,onaio/plottable,palantir/plottable,onaio/plottable,RobertoMalatesta/plottable,onaio/plottable,RobertoMalatesta/plottable,NextTuesday/plottable,NextTuesday/plottable,gdseller/plottable,softwords/plottable,danmane/plottable,alyssaq/plottable,RobertoMalatesta/plottable,alyssaq/plottable,iobeam/plottable
6e712d8ded370fea4b7f1a8df6d896a3ae4472c4
src/authentication/sessions.js
src/authentication/sessions.js
'use strict'; export default { setup, }; /** * Module dependencies. */ import SequelizeStore from 'koa-generic-session-sequelize'; // import convert from 'koa-convert'; import session from 'koa-generic-session'; /** * Prepares session middleware and methods without attaching to the stack * * @param {Object} settings * @param {Object} database * @param {Object} [store] Store for `koa-generic-sessions`. Uses the database if a store is not provided * @return {Object} */ function setup(settings, database, store) { return { // session middleware session: session({ key: 'identityDesk.sid', store: store || new SequelizeStore(database), }), sessionMethods: function(ctx, next) { // set the secret keys for Keygrip ctx.app.keys = settings.session.keys; // attach session methods ctx.identityDesk = { get(key) { if (ctx.session && ctx.session.identityDesk && ctx.session.identityDesk[key] !== undefined) { return ctx.session.identityDesk[key]; } else { return undefined; } }, set(values) { ctx.session = ctx.session || { identityDesk: { values } }; ctx.session.identityDesk = ctx.session.identityDesk || { values }; Object.assign(ctx.session.identityDesk, values); }, }; return next(); }, }; }
'use strict'; export default { setup, }; /** * Module dependencies. */ import SequelizeStore from 'koa-generic-session-sequelize'; // import convert from 'koa-convert'; import session from 'koa-generic-session'; /** * Prepares session middleware and methods without attaching to the stack * * @param {Object} settings * @param {Object} database * @param {Object} [store] Store for `koa-generic-sessions`. Uses the database if a store is not provided * @return {Object} */ function setup(settings, database, store) { return { // session middleware session: session({ key: 'identityDesk.sid', store: store || new SequelizeStore(database), }), sessionMethods: function(ctx, next) { // set the secret keys for Keygrip ctx.app.keys = settings.session.keys; // attach session methods ctx.identityDesk = { get(key) { if (ctx.session && ctx.session.identityDesk && ctx.session.identityDesk[key] !== undefined) { return ctx.session.identityDesk[key]; } else { return undefined; } }, set(values) { ctx.session = ctx.session || { identityDesk: values }; ctx.session.identityDesk = ctx.session.identityDesk || values; Object.assign(ctx.session.identityDesk, values); }, }; return next(); }, }; }
Fix bug of session data being stored with an extra `values` key
Fix bug of session data being stored with an extra `values` key
JavaScript
mit
HiFaraz/identity-desk
db8294dc10fb9240bacbdc65e724d884d81b74c7
src/components/GlobalSearch.js
src/components/GlobalSearch.js
import React, { Component, findDOMNode } from 'react'; import styles from './GlobalSearch.scss'; export default class GlobalSearch extends Component { render () { return ( <input ref='searchBox' placeholder={this.props.placeholder} className={styles['gs-input']} onChange={this.props.onChange} onKeyUp={this.props.onKeyUp} onFocus={this.props.onFocus} onClick={() => { findDOMNode(this).select(); }} /> ); }; }; GlobalSearch.propTypes = { placeholder: React.PropTypes.string, onFocus: React.PropTypes.func.isRequired, onChange: React.PropTypes.func.isRequired, onKeyUp: React.PropTypes.func.isRequired, styles: React.PropTypes.object };
import React, { Component } from 'react'; import { findDOMNode } from 'react-dom'; import styles from './GlobalSearch.scss'; export default class GlobalSearch extends Component { render () { return ( <input ref='searchBox' placeholder={this.props.placeholder} className={styles['gs-input']} onChange={this.props.onChange} onKeyUp={this.props.onKeyUp} onFocus={this.props.onFocus} onClick={() => { findDOMNode(this).select(); }} /> ); }; }; GlobalSearch.propTypes = { placeholder: React.PropTypes.string, onFocus: React.PropTypes.func.isRequired, onChange: React.PropTypes.func.isRequired, onKeyUp: React.PropTypes.func.isRequired, styles: React.PropTypes.object };
Swap deprecated findDOMNode to the version from the react-dom module.
Swap deprecated findDOMNode to the version from the react-dom module.
JavaScript
bsd-3-clause
FiviumAustralia/RNSH-Pilot,FiviumAustralia/RNSH-Pilot,FiviumAustralia/RNSH-Pilot
13351bc9c4dc36a27251ed9147ab35b7c771fce5
packages/shared/lib/keys/keyImport.js
packages/shared/lib/keys/keyImport.js
import { getKeys } from 'pmcrypto'; import { readFileAsString } from '../helpers/file'; const PRIVATE_KEY_EXPR = /-----BEGIN PGP PRIVATE KEY BLOCK-----(?:(?!-----)[\s\S])*-----END PGP PRIVATE KEY BLOCK-----/g; export const parseArmoredKeys = (fileString) => { return fileString.match(PRIVATE_KEY_EXPR) || []; }; export const parseKeys = (filesAsStrings = []) => { const armoredKeys = parseArmoredKeys(filesAsStrings.join('\n')); if (!armoredKeys.length) { return []; } return Promise.all(armoredKeys.map(async (armoredPrivateKey) => { try { const [key] = await getKeys(armoredPrivateKey); return key; } catch (e) { // ignore errors } })).then((result) => result.filter(Boolean)); }; export const parseKeyFiles = async (files = []) => { const filesAsStrings = await Promise.all(files.map(readFileAsString)).catch(() => []); return parseKeys(filesAsStrings); };
import { getKeys } from 'pmcrypto'; import { readFileAsString } from '../helpers/file'; const PRIVATE_KEY_EXPR = /-----BEGIN PGP (PRIVATE|PUBLIC) KEY BLOCK-----(?:(?!-----)[\s\S])*-----END PGP (PRIVATE|PUBLIC) KEY BLOCK-----/g; export const parseArmoredKeys = (fileString) => { return fileString.match(PRIVATE_KEY_EXPR) || []; }; export const parseKeys = (filesAsStrings = []) => { const armoredKeys = parseArmoredKeys(filesAsStrings.join('\n')); if (!armoredKeys.length) { return []; } return Promise.all( armoredKeys.map(async (armoredPrivateKey) => { try { const [key] = await getKeys(armoredPrivateKey); return key; } catch (e) { // ignore errors } }) ).then((result) => result.filter(Boolean)); }; export const parseKeyFiles = async (files = []) => { const filesAsStrings = await Promise.all(files.map(readFileAsString)).catch(() => []); return parseKeys(filesAsStrings); };
Update REGEX to accept also public keys
Update REGEX to accept also public keys
JavaScript
mit
ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient
31488615c3bd0a3b9ae1399c479dee95d503273e
client/app/validators/messages.js
client/app/validators/messages.js
import Messages from 'ember-cp-validations/validators/messages'; export default Messages.extend({ blank: 'Поле не может быть пустым', email: 'Значение должно быть адресом электронной почты', emailNotFound: 'Адрес не найден', notANumber: 'Значение должно быть числом', notAnInteger: 'Значение должно быть целым числом', positive: 'Значение должно быть положительным числом', invalid: 'Поле заполнено неверно' });
import Messages from 'ember-cp-validations/validators/messages'; export default Messages.extend({ blank: 'Поле не может быть пустым', email: 'Значение должно быть адресом электронной почты', emailNotFound: 'Адрес не найден', notANumber: 'Значение должно быть числом', notAnInteger: 'Значение должно быть целым числом', positive: 'Значение должно быть положительным числом', invalid: 'Поле заполнено неверно', url: 'Значение не является ссылкой' });
Add custom message for invalid url
Add custom message for invalid url
JavaScript
mit
yandex-shri-minsk-2016/yummy-time,yandex-shri-minsk-2016/yummy-time,yandex-shri-minsk-2016/yummy-time
fa117ab8cfa2a82fd20ee9312a8719d604dc010b
test/util/string.js
test/util/string.js
var assert = require('chai').assert; var string = require('../../util/string'); describe('util/string', function () { describe('#isEmpty', function () { it('should return true', function () { assert(true, string.isEmpty()); assert(true, string.isEmpty('')); assert(true, string.isEmpty(' ')); }); it('should return false', function () { assert.isFalse(string.isEmpty('myString')); }); }); });
var assert = require('chai').assert; var string = require('../../util/string'); describe('util/string', function () { describe('#isEmpty', function () { it('should return true', function () { assert.isTrue(string.isEmpty()); assert.isTrue(string.isEmpty('')); assert.isTrue(string.isEmpty(' ')); }); it('should return false', function () { assert.isFalse(string.isEmpty('myString')); }); }); });
Change assert style: use method isTrue
Change assert style: use method isTrue
JavaScript
mit
pmu-tech/grunt-erb
69d8e29ba6c802699c38bec0c9ec65ccdbfa0d95
src/client/StatusBar.js
src/client/StatusBar.js
import React, {Component} from 'react'; import Mousetrap from 'mousetrap'; class StatusBar extends Component { componentDidMount() { Mousetrap.bind(['alt+a'], this.toggleSearchAllWindows); } render() { return ( /* jshint ignore:start */ <label className='status'> <input type='checkbox' checked={this.props.searchAllWindows} onChange={this.onChange} /> <span>Show tabs from <u>a</u>ll windows</span> </label> /* jshint ignore:end */ ); } toggleSearchAllWindows() { this.props.changeSearchAllWindows(!this.props.searchAllWindows); } onChange(evt) { this.props.changeSearchAllWindows(evt.target.checked); } } export default StatusBar;
import React, {Component} from 'react'; import Mousetrap from 'mousetrap'; class StatusBar extends Component { constructor(props) { super(props); this.toggleSearchAllWindows = this.toggleSearchAllWindows.bind(this); this.onChange = this.onChange.bind(this); } componentDidMount() { Mousetrap.bind(['alt+a'], this.toggleSearchAllWindows); } render() { return ( /* jshint ignore:start */ <label className='status'> <input type='checkbox' checked={this.props.searchAllWindows} onChange={this.onChange} /> <span>Show tabs from <u>a</u>ll windows</span> </label> /* jshint ignore:end */ ); } toggleSearchAllWindows() { this.props.changeSearchAllWindows(!this.props.searchAllWindows); } onChange(evt) { this.props.changeSearchAllWindows(evt.target.checked); } } export default StatusBar;
Fix for toggle all windows
Fix for toggle all windows
JavaScript
mit
fewhnhouse/chrome-tab-switcher
b791de38894ffa04c66a8c8c7164da1bb3cb4dc6
src/main/resources/static/js/autocomplete-lecturer-for-subject.js
src/main/resources/static/js/autocomplete-lecturer-for-subject.js
export default class AutoCompleteSubjects { constructor(wrapper) { this.wrapper = wrapper; } initialize(selector) { const $input = this.wrapper.find('input[type=text]'); const $realInput = this.wrapper.find('input[type=hidden]'); const jsonUrl = this.wrapper.data("url"); $input.materialize_autocomplete({ multiple: { enable: false }, dropdown: { el: '.dropdown-content', itemTemplate: '<li class="ac-item" data-id="<%= item.id %>" data-text=\'<%= item.name %>\'><a href="javascript:void(0)"><%= item.name %></a></li>', }, getData: function (value, callback) { const url = jsonUrl + `?filter=${value}`; $.ajax({ url: url, }) .then(data => { callback(value, data); }); }, onSelect: function (item) { $realInput.val(item.id); }, }); } }
export default class AutoCompleteSubjects { constructor(wrapper) { this.wrapper = wrapper; } initialize(selector) { const $input = this.wrapper.find('input[type=text]'); const $realInput = this.wrapper.find('input[type=hidden]'); const jsonUrl = this.wrapper.data("url"); $input.materialize_autocomplete({ multiple: { enable: false }, dropdown: { el: '.dropdown-content', itemTemplate: '<li class="ac-item" data-id="<%= item.id %>" data-text=\'<%= item.name %>\'><a href="javascript:void(0)"><%= item.name %></a></li>', }, getData: function (value, callback) { const url = jsonUrl + `?search=${value}`; $.ajax({ url: url, }) .then(data => { callback(value, data); }); }, onSelect: function (item) { $realInput.val(item.id); }, }); } }
Rename GET parameter from ?filter to ?search
Rename GET parameter from ?filter to ?search
JavaScript
mit
university-information-system/uis,university-information-system/uis,university-information-system/uis,university-information-system/uis
878b9eeb01b579bf30ab30d5d8f1e76f34aa4aee
gruntfile.js
gruntfile.js
"use strict"; /*jshint node: true*/ /*eslint-env node*/ module.exports = function (grunt) { require("time-grunt")(grunt); // Since the tasks are split using load-grunt-config, a global object contains the configuration /*global configFile, configuration*/ var ConfigFile = require("./make/configFile.js"); global.configFile = new ConfigFile(); global.configuration = configFile.content; if (configFile.isNew()) { grunt.registerTask("default", function () { var done = this.async(); //eslint-disable-line no-invalid-this grunt.util.spawn({ cmd: "node", args: ["make/config"], opts: { stdio: "inherit" } }, function (error) { if (error) { done(); return; } grunt.util.spawn({ grunt: true, args: ["check", "jsdoc", "default"], opts: { stdio: "inherit" } }, done); }); }); return; } configFile.readSourceFiles(); // Amend the configuration with internal settings configuration.pkg = grunt.file.readJSON("./package.json"); require("load-grunt-config")(grunt); grunt.task.loadTasks("grunt/tasks"); };
"use strict"; /*jshint node: true*/ /*eslint-env node*/ module.exports = function (grunt) { require("time-grunt")(grunt); // Since the tasks are split using load-grunt-config, a global object contains the configuration /*global configFile, configuration*/ var ConfigFile = require("./make/configFile.js"); global.configFile = new ConfigFile(); global.configuration = Object.create(configFile.content); if (configFile.isNew()) { grunt.registerTask("default", function () { var done = this.async(); //eslint-disable-line no-invalid-this grunt.util.spawn({ cmd: "node", args: ["make/config"], opts: { stdio: "inherit" } }, function (error) { if (error) { done(); return; } grunt.util.spawn({ grunt: true, args: ["check", "jsdoc", "default"], opts: { stdio: "inherit" } }, done); }); }); return; } configFile.readSourceFiles(); // Amend the configuration with internal settings configuration.pkg = grunt.file.readJSON("./package.json"); require("load-grunt-config")(grunt); grunt.task.loadTasks("grunt/tasks"); };
Secure content that must not be altered by grunt
Secure content that must not be altered by grunt
JavaScript
mit
ArnaudBuchholz/gpf-js,ArnaudBuchholz/gpf-js
5d973ab69edbf2618020bab1b764838f4d17ef47
src/plugins/configure/index.js
src/plugins/configure/index.js
const { next, hookStart, hookEnd } = require('hooter/effects') const assignDefaults = require('./assignDefaults') const validateConfig = require('./validateConfig') const EVENTS_WITH_CONFIG = ['start', 'execute', 'process', 'handle', 'error'] module.exports = function* configurePlugin() { let schema, config function* provideConfig(...args) { let event = this.type if (!config && event !== 'error') { throw new Error( `The config must already be defined at the beginning of "${event}"` ) } return yield next(config, ...args) } yield hookEnd('schema', function* (_schema) { schema = yield next(_schema).or(_schema) return schema }) yield hookStart('configure', function* (_config) { return yield next(schema, _config) }) yield hookStart('configure', function* (_schema, _config) { _config = assignDefaults(_schema, _config) return yield next(_schema, _config) }) yield hookEnd('configure', function* (_schema, _config) { validateConfig(_schema, _config) config = yield next(_schema, _config).or(_config) return config }) for (let event of EVENTS_WITH_CONFIG) { yield hookStart(event, provideConfig) } }
const { next, hookStart, hookEnd } = require('hooter/effects') const assignDefaults = require('./assignDefaults') const validateConfig = require('./validateConfig') const EVENTS_WITH_CONFIG = ['start', 'execute', 'process', 'handle', 'error'] module.exports = function* configurePlugin() { let schema, config function* provideConfig(...args) { let event = this.name if (!config && event !== 'error') { throw new Error( `The config must already be defined at the beginning of "${event}"` ) } return yield next(config, ...args) } yield hookEnd('schema', function* (_schema) { schema = yield next(_schema).or(_schema) return schema }) yield hookStart('configure', function* (_config) { return yield next(schema, _config) }) yield hookStart('configure', function* (_schema, _config) { _config = assignDefaults(_schema, _config) return yield next(_schema, _config) }) yield hookEnd('configure', function* (_schema, _config) { validateConfig(_schema, _config) config = yield next(_schema, _config).or(_config) return config }) for (let event of EVENTS_WITH_CONFIG) { yield hookStart(event, provideConfig) } }
Fix provideConfig() in configure using event.type instead of event.name
Fix provideConfig() in configure using event.type instead of event.name
JavaScript
isc
alex-shnayder/comanche
59bdb85cdaa72829024108e3fc1fb71777e389f6
persistance.js
persistance.js
const models = require('./models') const Course = models.Course const path = require('path') const url = require('url') const uri = url.format({ pathname: path.join(__dirname, 'data.db'), protocol: 'nedb:', slashes: true }) const init = function(cb){ models.init(uri, function(err){ if(err){ console.log("Models initialization failed") cb(err) }else{ console.log("Models initialized..") cb() } }) } const saveCourse = function(course, cb){ let c = Course.create(course) c.save().then(function(doc){ cb(null, doc._id) }, function(err){ cb(err) }) } const getCourse = function(course, cb){ Course.findOne(course).then(function(doc){ cb(null, doc) }, function(err){ cb(err) }) } const getCourses = function(course, cb){ Course.find(course).then(function(docs){ cb(null, docs) }, function(err){ cb(err) }) } module.exports = { init, saveCourse, getCourse, getCourses }
const models = require('./models') const Course = models.Course const path = require('path') const url = require('url') const uri = url.format({ pathname: path.join(__dirname, 'data.db'), protocol: 'nedb:', slashes: true }) const init = function(cb){ models.init(uri, function(err){ if(err){ console.log("Models initialization failed") cb(err) }else{ console.log("Models initialized..") cb() } }) } const saveCourse = function(course, cb){ let c = Course.create(course) c.save().then(function(doc){ cb(null, doc._id) }, function(err){ cb(err) }) } const getCourse = function(course, cb){ Course.findOne(course).then(function(doc){ cb(null, doc) }, function(err){ cb(err) }) } const getCourses = function(course, cb){ Course.find(course, {sort: '-startDate'}).then(function(docs){ cb(null, docs) }, function(err){ cb(err) }) } module.exports = { init, saveCourse, getCourse, getCourses }
Sort courses based on startDate
Sort courses based on startDate
JavaScript
mit
nilenso/dhobi-seva-electron,nilenso/dhobi-seva-electron
445300182d2217a85dbb16ca2cee9522ce2c43a0
templates/react-class/index.js
templates/react-class/index.js
import React, { Component } from 'react' class {{file}} extends Component { render () { return ( <div className="{{file}}"> </div> ) } } export default {{file}}
import React, { Component } from 'react' import './{{file}}.css' class {{file}} extends Component { render () { return ( <div className="{{file}}"> </div> ) } } export default {{file}}
Add CSS import to react-class template
Add CSS import to react-class template
JavaScript
isc
tu4mo/teg
8b153821c3a8348a4a54442af453fd61b6e3d51f
app/assets/javascripts/ruby_prof_rails/home.js
app/assets/javascripts/ruby_prof_rails/home.js
$(function() { $('form').preventDoubleSubmission(); $('form').on('submit', function(e){ $(this).find('button').text('Processing...') }); select_profiles_tab_from_url_hash(); disable_modal_links(); }); function disable_modal_links(){ if( !bootstrap_enabled() ){ $("a[data-toggle='modal'").hide(); } } function bootstrap_enabled(){ return (typeof $().modal == 'function'); } function select_profiles_tab_from_url_hash(){ if( window.location.hash == '#profiles' ){ $('#profiles-tab a').tab('show'); } } // jQuery plugin to prevent double submission of forms jQuery.fn.preventDoubleSubmission = function() { $(this).on('submit',function(e){ var $form = $(this); if ($form.data('submitted') === true) { // Previously submitted - don't submit again e.preventDefault(); } else { // Mark it so that the next submit can be ignored $form.data('submitted', true); } }); // Keep chainability return this; };
$(function() { $('form').preventDoubleSubmission(); $('form').on('submit', function(e){ $(this).find('button').text('Processing...') }); select_profiles_tab_from_url_hash(); disable_modal_links(); }); function disable_modal_links(){ if( !bootstrap_enabled() ){ $("a[data-toggle='modal'").hide(); } } function bootstrap_enabled(){ return (typeof $().modal == 'function'); } function select_profiles_tab_from_url_hash(){ if( window.location.hash == '#profiles' ){ $('#my-profiles-tab a').tab('show'); } } // jQuery plugin to prevent double submission of forms jQuery.fn.preventDoubleSubmission = function() { $(this).on('submit',function(e){ var $form = $(this); if ($form.data('submitted') === true) { // Previously submitted - don't submit again e.preventDefault(); } else { // Mark it so that the next submit can be ignored $form.data('submitted', true); } }); // Keep chainability return this; };
Add Exclude Formats to skip
Add Exclude Formats to skip
JavaScript
mit
tleish/ruby-prof-rails,tleish/ruby-prof-rails,tleish/ruby-prof-rails
5a0f409a488a4a5d3fed358fda6f71cd7dc66676
rollup.config.js
rollup.config.js
import resolve from 'rollup-plugin-node-resolve' import minify from 'rollup-plugin-minify-es' import license from 'rollup-plugin-license' export default { input: 'src/micro-panel-all.js', output: [ { format: 'iife', name: 'codeflask_element', file: 'dist/micro-panel-all.bundle.min.js', sourcemap: true, } ], plugins: [ resolve(), minify(), license({ banner: `@license micro-panel is public domain or available under the Unlicense. lit-element/lit-html/etc. (c) The Polymer Authors under BSD 3-Clause.` }), ], }
import resolve from 'rollup-plugin-node-resolve' import minify from 'rollup-plugin-minify-es' import license from 'rollup-plugin-license' export default { input: 'src/micro-panel-all.js', output: [ { format: 'iife', name: 'codeflask_element', file: 'dist/micro-panel-all.bundle.min.js', sourcemap: true, } ], plugins: [ resolve(), minify(), license({ banner: `@license micro-panel | Unlicense. lit-element/lit-html (c) The Polymer Authors | BSD 3-Clause. CodeFlask (c) Claudio Holanda | MIT. Prism (c) Lea Verou | MIT.` }), ], }
Add codeflask/prism to license banner
Add codeflask/prism to license banner
JavaScript
unlicense
myfreeweb/micro-panel,myfreeweb/micro-panel
c3ebe5ba281de674c18c47130df3aabfac1cd0c8
lib/index.js
lib/index.js
var native = require('../build/Release/dhcurve'), common = require('./common.js'), Promise = require('es6-promises'), _ = require('goal'); function generateKeyPair() { } module.exports = _.mixin({ generateKeyPair: generateKeyPair }, common);
var global = function() { return this; }(); var native = require('../build/Release/dhcurve'), common = require('./common.js'), Promise = global.Promise || require('es6-promises'), _ = require('goal'); function generateKeyPair() { } module.exports = _.mixin({ generateKeyPair: generateKeyPair }, common);
Use Promises in node.js if found.
Use Promises in node.js if found.
JavaScript
mit
mbullington/dhcurve
6e69926de990faac1132b2f434c493750766b101
src/grid-interaction.js
src/grid-interaction.js
import gtr from './global-translation.js' import GraphicsHandler from './graphics-handler.js' import MouseHandler from './mouse-handler.js' import {getIsometricCoordinate} from './isometric-math.js' const CONTAINER = document.querySelector('.graphics-wrapper') export default class GridInteraction { constructor () { this.gh = new GraphicsHandler(CONTAINER) } clear () { this.gh.clearCanvas() } render () { const x = MouseHandler.position().x const y = MouseHandler.position().y if (x !== this.oldX && y !== this.oldY) { this.oldX = x this.oldY = y const gPos = gtr.toGlobal(x, y) const isoCoord = getIsometricCoordinate(gPos.x, gPos.y) this.gh.clearCanvas() this.gh.fillStyle = 'rgba(0, 0, 0, 0.2)' this.gh.drawTriangle(isoCoord.a1, isoCoord.a2, isoCoord.right) } } }
import gtr from './global-translation.js' import GraphicsHandler from './graphics-handler.js' import MouseHandler from './mouse-handler.js' import {getIsometricCoordinate} from './isometric-math.js' const CONTAINER = document.querySelector('.graphics-wrapper') export default class GridInteraction { constructor () { this.gh = new GraphicsHandler(CONTAINER) this.isTouchDevice = 'ontouchstart' in window || navigator.maxTouchPoints }; } clear () { this.gh.clearCanvas() } render () { const x = MouseHandler.position().x const y = MouseHandler.position().y if (!isTouchDevice && x !== this.oldX && y !== this.oldY) { this.oldX = x this.oldY = y const gPos = gtr.toGlobal(x, y) const isoCoord = getIsometricCoordinate(gPos.x, gPos.y) this.gh.clearCanvas() this.gh.fillStyle = 'rgba(0, 0, 0, 0.2)' this.gh.drawTriangle(isoCoord.a1, isoCoord.a2, isoCoord.right) } } }
Fix that removes hover effect on touch devices
Fix that removes hover effect on touch devices
JavaScript
apache-2.0
drpentagon/isometric-paint,drpentagon/isometric-paint
ac64d509ed40712a7c10c265b642560c0a8a0b6e
scripts/chris.js
scripts/chris.js
var audio = document.getElementById("chris"); function pauseChris() { if (audio.currentTime >= 331000) { audio.pause(); alert(interval); } } function playChris() { audio.currentTime = 952; audio.play(); var interval = setInterval(pauseChris, 1000); } function addChrisButton() { var div = document.getElementById("audioContainer"); var button = document.createElement("BUTTON"); button.setAttribute("type", "button"); button.addEventListener("click", playChris); button.innerText = "Escuchar a Chris"; div.insertBefore(button, audio); } addChrisButton();
var audio = document.getElementById("chris"); function pauseChris() { if (audio.currentTime >= 331000) { audio.pause(); alert(audio.currentTime); } } function playChris() { audio.currentTime = 952; audio.play(); var interval = setInterval(pauseChris, 1000); } function addChrisButton() { var div = document.getElementById("audioContainer"); var button = document.createElement("BUTTON"); button.setAttribute("type", "button"); button.addEventListener("click", playChris); button.innerText = "Escuchar a Chris"; div.insertBefore(button, audio); } addChrisButton();
Check current time after pause
Check current time after pause
JavaScript
mit
nvdaes/nvdaes.github.io,nvdaes/nvdaes.github.io
9adb52b6fd343ca01b4d706a0b87be7fe09b3e7b
src/content_scripts/pivotal_tracker/view/toggle_feature_notifier.js
src/content_scripts/pivotal_tracker/view/toggle_feature_notifier.js
import $ from 'jquery'; export default class ToggleFeatureNotifier { constructor({chromeWrapper}) { this._chromeWrapper = chromeWrapper; this.notify = this.notify.bind(this); } notify() { const optionsUrl = this._chromeWrapper.getURL('src/options/index.html'); prependElementAsChildOf('#tracker', ` <div class="ui message"> <i class="close icon"></i> <div class="header"> WWLTW Extension Update </div> <p>You can enable and disable the WWLTW chrome extension for individual backlogs from the <a href="${optionsUrl}" target="_blank">bottom of the options page.</a></p> </div> `); $('.message .close').on('click', function () { $(this) .closest('.message') .transition('fade') ; }); } } const prependElementAsChildOf = function (parent, html) { let elementContainer = document.createElement('div'); elementContainer.innerHTML = html; $(parent).prepend(elementContainer); };
import $ from 'jquery'; export default class ToggleFeatureNotifier { constructor({chromeWrapper}) { this._chromeWrapper = chromeWrapper; this.notify = this.notify.bind(this); } notify() { const optionsUrl = this._chromeWrapper.getURL('src/options/index.html'); prependElementAsChildOf('#tracker', ` <div class="ui message"> <i class="close icon"></i> <div class="header"> WWLTW Extension Update </div> <p>The WWLTW chrome extension is now disabled by default for all backlogs. You can enable it for any of your backlogs from the <a href="${optionsUrl}" target="_blank">bottom of the options page.</a></p> </div> `); $('.message .close').on('click', function () { $(this) .closest('.message') .transition('fade') ; }); } } const prependElementAsChildOf = function (parent, html) { let elementContainer = document.createElement('div'); elementContainer.innerHTML = html; $(parent).prepend(elementContainer); };
Update copy for toggle feature notification
Update copy for toggle feature notification
JavaScript
isc
oliverswitzer/wwltw-for-pivotal-tracker,oliverswitzer/wwltw-for-pivotal-tracker
931fa47355cb7f5d5bce4d77affb7313211ac043
base.js
base.js
var util = require('util'); module.exports = function (name, defaultMessage, status) { util.inherits(Constructor, Error); return Constructor; function Constructor (message, code) { Error.call(this); Error.captureStackTrace(this, arguments.callee); this.name = name; this.message = message || defaultMessage; this.status = status; this.expose = true; if (code !== undefined) this.code = code; } };
var util = require('util'); module.exports = function (name, defaultMessage, status) { util.inherits(Constructor, Error); return Constructor; function Constructor (message, code) { Error.call(this, message || defaultMessage); Error.captureStackTrace(this, arguments.callee); this.name = name; this.status = status; this.expose = true; if (code !== undefined) this.code = code; } };
Set error message using constructor
Set error message using constructor
JavaScript
mit
aantthony/errors
8436bfbd641fd92d85116a4f6683d18fc23282a7
app/common/resourceCache/reducer.js
app/common/resourceCache/reducer.js
import { SET_RESOURCE, MARK_DASHBOARD_DIRTY, RESET_RESOURCE_CACHE } from './actions'; const markAllDirty = (keys, state) => { const dirty = {}; keys.forEach((key) => { dirty[key] = { ...state[key], dirty: true }; }); return dirty; }; const resourceReducer = (state = {}, action) => { switch (action.type) { case MARK_DASHBOARD_DIRTY: return { ...state, ...markAllDirty(action.payload, state), }; case SET_RESOURCE: return { ...state, [action.payload.key]: action.payload.resource, }; case RESET_RESOURCE_CACHE: return {}; default: return state; } }; export default resourceReducer;
import { SET_RESOURCE, MARK_DASHBOARD_DIRTY, RESET_RESOURCE_CACHE } from './actions'; const markAllDirty = (keys, state) => { const dirty = {}; keys.forEach((key) => { if (state[key]) { dirty[key] = { ...state[key], dirty: true }; } }); return dirty; }; const resourceReducer = (state = {}, action) => { switch (action.type) { case MARK_DASHBOARD_DIRTY: return { ...state, ...markAllDirty(action.payload, state), }; case SET_RESOURCE: return { ...state, [action.payload.key]: action.payload.resource, }; case RESET_RESOURCE_CACHE: return {}; default: return state; } }; export default resourceReducer;
Check for the existence of the resource cache key before attempting to make dirty
Check for the existence of the resource cache key before attempting to make dirty
JavaScript
mit
nathanhood/mmdb,nathanhood/mmdb
aea4582982e586365f788ed0d886262da7ab325f
server/controllers/students.js
server/controllers/students.js
//var Teachers = require('../models/teachers'); //var TeacherClasses = require('../models/Teacher_classes'); //var Classes = require('../models/classes'); //var ClassLessons = require('../models/class_lessons'); // var Lessons = require('../models/lessons'); //var RequestedResponses = require('../models/requested_responses'); module.exports = { readyStage : function(io, req, res, next) { // io.on('connection', function(client){ // console.log('Hey, server! A student is ready to learn!'); // client.emit('greeting', 'Hello, student!'); // client.on('responseRecorded', function(data){ // io.sockets.emit('responseRecordedFromStudent', data); // }); // }); res.status(200).send('Hello from the other side'); } };
//var Teachers = require('../models/teachers'); //var TeacherClasses = require('../models/Teacher_classes'); //var Classes = require('../models/classes'); //var ClassLessons = require('../models/class_lessons'); // var Lessons = require('../models/lessons'); //var RequestedResponses = require('../models/requested_responses'); module.exports = { readyStage : function(io, req, res, next) { //var studentInformation = req.body.studentData var pollResponse = { responseId: 1, type: 'thumbs', datetime: new Date(), lessonId: 13, }; io.on('connection', function(student){ student.emit('studentStandby', studentInformation); student.on('teacherConnect', function() { student.emit('teacherConnect'); }); student.on('newPoll', function(data) { student.emit(data); }); setTimeout(function(){ io.sockets.emit('responseFromStudent', pollResponse); }, 5000); }); res.status(200).send('Hello from the other side'); } };
Add student information to connection socket event
Add student information to connection socket event
JavaScript
mit
Jakeyrob/thumbroll,shanemcgraw/thumbroll,Jakeyrob/thumbroll,absurdSquid/thumbroll,shanemcgraw/thumbroll,shanemcgraw/thumbroll,absurdSquid/thumbroll,Jakeyrob/thumbroll
c2c520b16f46f94d9b82251b344f0ef7de158903
app/assets/javascripts/sprangular.js
app/assets/javascripts/sprangular.js
// // General // //= require underscore //= require underscore.string //= require jquery //= require angular //= require angularytics //= require bootstrap-sass-official //= require validity // // Angular specific // //= require angular-translate //= require angular-strap/angular-strap.js //= require angular-strap/angular-strap.tpl.js //= require angular-route //= require angular-sanitize //= require angular-animate //= require sprangular/app
// // General // //= require underscore //= require underscore.string //= require angular //= require angularytics //= require bootstrap-sass-official //= require validity // // Angular specific // //= require angular-translate //= require angular-strap/angular-strap.js //= require angular-strap/angular-strap.tpl.js //= require angular-route //= require angular-sanitize //= require angular-animate //= require sprangular/app
Remove include of jquery, it should be included by host app
Remove include of jquery, it should be included by host app
JavaScript
mit
sprangular/sprangular,sprangular/sprangular,sprangular/sprangular
bee4589cdd421a33aad2d5f25fbd97f777bf2e58
app/assets/javascripts/application.js
app/assets/javascripts/application.js
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require tinymce-jquery //= require_tree . //= require_tree ../../../vendor/assets/javascripts/.
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require tinymce-jquery //= require_tree ../../../vendor/assets/javascripts/. //= require_tree .
Move vender js files in manifest so the tree can access them
Move vender js files in manifest so the tree can access them
JavaScript
mit
timmykat/openeffects.org,timmykat/openeffects.org,timmykat/openeffects.org,ofxa/openeffects.org,timmykat/openeffects.org,ofxa/openeffects.org,ofxa/openeffects.org,ofxa/openeffects.org
cbeaf1c062caa2262ab7dc0553069f8708a0d472
app/assets/javascripts/application.js
app/assets/javascripts/application.js
// This is a manifest file that'll be compiled into including all the files listed below. // Add new JavaScript/Coffee code in separate files in this directory and they'll automatically // be included in the compiled file accessible from http://example.com/assets/application.js // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // //= require jquery //= require jquery_ujs //= require jquery.cookie //= require jquery.tools.min //= require knockout //= require superbly-tagfield.min //= require maps //= require map_display //= require map_edit //= require map_popup //= require map_style //= require openlayers_pz //= require ui //= require tags //= require supercool //= require library_message
// This is a manifest file that'll be compiled into including all the files listed below. // Add new JavaScript/Coffee code in separate files in this directory and they'll automatically // be included in the compiled file accessible from http://example.com/assets/application.js // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // //= require jquery //= require jquery_ujs //= require jquery.cookie //= require jquery.tools.min //= require knockout //= require superbly-tagfield.min //= require maps //= require map_display //= require map_edit //= require map_popup //= require map_style //= require openlayers_pz //= require ui //= require tags //= require library_message
Remove supercool.js from manifest as tag plugin causes errors in IE8.
Remove supercool.js from manifest as tag plugin causes errors in IE8. Looks like the plugin does not support empty jQuery sets for when the field isn't present.
JavaScript
mit
cyclestreets/cyclescape,auto-mat/toolkit,cyclestreets/cyclescape,auto-mat/toolkit,cyclestreets/cyclescape
7db436acaad26f648be77abea89f726e2677434f
app/assets/javascripts/application.js
app/assets/javascripts/application.js
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // // WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD // GO AFTER THE REQUIRES BELOW. // //= require jquery //= require jquery_ujs //= require bootstrap //= require_tree .
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // // WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD // GO AFTER THE REQUIRES BELOW. // //= require jquery //= require jquery_ujs //= require bootstrap //= require namespace //= require_tree .
Load namespace javascript file before all others
Load namespace javascript file before all others
JavaScript
mit
joshmcarthur/inquest,joshmcarthur/inquest
ae50e4f695c7f68ce839332cc548696d1692e5c0
app/assets/javascripts/districts/controllers/district_modal_controller.js
app/assets/javascripts/districts/controllers/district_modal_controller.js
VtTracker.DistrictModalController = Ember.ObjectController.extend({ needs: ['index'], modalTitle: function() { if (this.get('isNew')) { return 'New District'; } else { return 'Edit District'; } }.property('isNew'), actions: { save: function() { var _self = this; var isNew = _self.get('model.isNew'); _self.get('model').save().then(function() { if (isNew) { _self.set('controllers.index.newDistrict', _self.store.createRecord('district')); } }); } } });
VtTracker.DistrictModalController = Ember.ObjectController.extend({ needs: ['index'], modalTitle: function() { if (this.get('isNew')) { return 'New District'; } else { return 'Edit District'; } }.property('isNew'), actions: { removeModal: function() { this.get('model').rollback(); return true; }, save: function() { var _self = this; var isNew = _self.get('model.isNew'); _self.get('model').save().then(function() { if (isNew) { _self.set('controllers.index.newDistrict', _self.store.createRecord('district')); } }); } } });
Rollback district edit model when modal is closed
Rollback district edit model when modal is closed
JavaScript
mit
bfcoder/vt-ht-tracker,bfcoder/vt-ht-tracker,bfcoder/vt-ht-tracker
b28a11df9533f9fa91945264bb34e51ea977c417
javascripts/extension.js
javascripts/extension.js
$("div.entry").live('click', function( e ) { var item = $(e.target).closest('.entry'); if (!item.find('.entry-actions span.google-plus').length) { item.find(".entry-actions span.tag").after($('<span class="link google-plus">Share to Google+</span>')); } }); $(".entry-actions span.google-plus").live('click', function( e ) { var entry = $(e.target).closest('.entry'); var link = entry.find('a.entry-original').attr('href'); $("#gbg3").trigger('click'); });
$("div.entry").live('click', function( e ) { var link, href, item = $(e.target).closest('.entry'); if (!item.find('.entry-actions span.google-plus').length) { href = 'https://plus.google.com/?status=' + item.find('a.entry-title-link').attr('href'); link = $('<a target="_blank">Share to Google+</a>').attr('href', href); item.find(".entry-actions span.tag").after($('<span class="link google-plus"></span>').html(link)); } });
Create a share link with ?status
Create a share link with ?status
JavaScript
mit
felipeelias/reader_to_plus
3af0ea079e7710f16599de9565c9c9f07f666d4c
lib/ui/views/targetSelector.js
lib/ui/views/targetSelector.js
/* * Copyright 2014 BlackBerry Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var TargetSelectorView, targetSelectorTemplate; TargetSelectorView = Backbone.View.extend({ initialize: function () { // Find the template and save it $.get("pages/targetSelector.html", function (data) { targetSelectorTemplate = data; }); }, render: function () { // Use the template to create the html to display var view = this, showDevices = view.model.get("buildSettings").device, template; if (typeof showDevices === "undefined") { showDevices = true; } this.model.targetFilter(showDevices, function (filteredTargets) { template = _.template(targetSelectorTemplate, { targetNameList: Object.keys(filteredTargets) }); // Put the new html inside of the assigned element view.$el.html(template); }); }, events: { }, display: function (model) { this.model = model; this.render(); } }); module.exports = TargetSelectorView;
/* * Copyright 2014 BlackBerry Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var TargetSelectorView, targetSelectorTemplate; TargetSelectorView = Backbone.View.extend({ initialize: function () { // Find the template and save it $.get("pages/targetSelector.html", function (data) { targetSelectorTemplate = data; }); }, render: function () { // Use the template to create the html to display var view = this, buildSettings = view.model.get("buildSettings"), showDevices = !buildSettings || typeof buildSettings.device === "undefined" || buildSettings.device, template; this.model.targetFilter(showDevices, function (filteredTargets) { template = _.template(targetSelectorTemplate, { targetNameList: Object.keys(filteredTargets) }); // Put the new html inside of the assigned element view.$el.html(template); }); }, events: { }, display: function (model) { this.model = model; this.render(); } }); module.exports = TargetSelectorView;
Fix target selector for imported projects
Fix target selector for imported projects
JavaScript
apache-2.0
blackberry/webworks-gui,blackberry-webworks/webworks-gui,blackberry/webworks-gui,blackberry-webworks/webworks-gui
994654819859ddb726b92d0f4d571bb75bbcbe91
test/support/logger-factory.js
test/support/logger-factory.js
var _ = require('lodash') var assert = require('assert') module.exports = function () { var log = [] return { write: function () { log.push(_(arguments).toArray().join(' ')) }, read: function () { return log }, toString: function () { return log.join('\n') }, assert: function () { var lines = _.toArray(arguments) _.each(lines, function (line, i) { if (line instanceof RegExp) { assert(line.test(log[i]), line.toString() + ' did not match: "' + log[i] + '"') } else { assert.equal(log[i], line) } }) } } }
var _ = require('lodash') var assert = require('assert') module.exports = function () { var log = [] return { write: function () { log.push(_(arguments).toArray().join(' ')) }, read: function () { return log }, toString: function () { return log.join('\n') }, assert: function () { var lines = _.toArray(arguments) try { _.each(lines, function (line, i) { if (line instanceof RegExp) { assert(line.test(log[i]), line.toString() + ' did not match: "' + log[i] + '"') } else { assert.equal(log[i], line) } }) } catch (e) { console.error('Error asserting the log. Full log follows:') console.log(log) throw e } } } }
Make debugging easier by always printing the log
Make debugging easier by always printing the log
JavaScript
mit
testdouble/teenytest,testdouble/teenytest
ed2c390f30ceeb1f5e0ff5618006fb9f1bc778ef
app/users/edit/responsibilities/controller.js
app/users/edit/responsibilities/controller.js
import Controller from '@ember/controller' import { task } from 'ember-concurrency' import QueryParams from 'ember-parachute' import moment from 'moment' const UsersEditResponsibilitiesQueryParams = new QueryParams({}) export default Controller.extend(UsersEditResponsibilitiesQueryParams.Mixin, { setup() { this.get('projects').perform() this.get('supervisees').perform() }, projects: task(function*() { return yield this.store.query('project', { reviewer: this.get('model.id'), include: 'customer', ordering: 'customer__name,name' }) }), supervisees: task(function*() { let supervisor = this.get('model.id') yield this.store.query('worktime-balance', { supervisor, date: moment().format('YYYY-MM-DD') }) return yield this.store.query('user', { supervisor, ordering: 'username' }) }) })
import Controller from '@ember/controller' import { task } from 'ember-concurrency' import QueryParams from 'ember-parachute' import moment from 'moment' const UsersEditResponsibilitiesQueryParams = new QueryParams({}) export default Controller.extend(UsersEditResponsibilitiesQueryParams.Mixin, { setup() { this.get('projects').perform() this.get('supervisees').perform() }, projects: task(function*() { return yield this.store.query('project', { reviewer: this.get('model.id'), include: 'customer', ordering: 'customer__name,name' }) }), supervisees: task(function*() { let supervisor = this.get('model.id') let balances = yield this.store.query('worktime-balance', { supervisor, date: moment().format('YYYY-MM-DD'), include: 'user' }) return balances.mapBy('user') }) })
Use included to fetch supervisees
Use included to fetch supervisees
JavaScript
agpl-3.0
anehx/timed-frontend,adfinis-sygroup/timed-frontend,adfinis-sygroup/timed-frontend,anehx/timed-frontend,adfinis-sygroup/timed-frontend
faa007e535289ee435df9ec4a92f3b229bbd9227
app_server/app/controllers/AdminController.js
app_server/app/controllers/AdminController.js
/** * Admin Controller * @module AdminController */ var rfr = require('rfr'); var Joi = require('joi'); var Boom = require('boom'); var Utility = rfr('app/util/Utility'); var Service = rfr('app/services/Service'); var logger = Utility.createLogger(__filename); function AdminController(server, options) { this.server = server; this.options = options; } var Class = AdminController.prototype; Class.registerRoutes = function () { this.server.route({ method: 'POST', path: '/', config: { auth: false }, handler: this.createAdmin }); }; /* Routes handlers */ Class.createAdmin = function (request, reply) { }; exports.register = function (server, options, next) { var adminController = new AdminController(server, options); server.bind(adminController); adminController.registerRoutes(); next(); }; exports.register.attributes = { name: 'AdminController' };
/** * Admin Controller * @module AdminController */ var rfr = require('rfr'); var Joi = require('joi'); var Boom = require('boom'); var bcrypt = require('bcryptjs'); var Utility = rfr('app/util/Utility'); var Authenticator = rfr('app/policies/Authenticator'); var Service = rfr('app/services/Service'); var logger = Utility.createLogger(__filename); function AdminController(server, options) { this.server = server; this.options = options; } var Class = AdminController.prototype; Class.registerRoutes = function () { this.server.route({ method: 'POST', path: '/', config: { auth: {scope: Authenticator.SCOPE.ADMIN} }, handler: this.createAdmin }); }; /* Routes handlers */ Class.createAdmin = function (request, reply) { var credentials = { username: request.payload.username, password: encrypt(request.payload.password) }; Service.createNewAdmin(credentials) .then(function (admin) { if (!admin || admin instanceof Error) { return reply(Boom.badRequest('Unable to create admin ' + credentials)); } // overwrite with unencrypted password admin.password = request.payload.password; reply(admin).created(); }); }; /* Helpers for everything above */ var encrypt = function (password) { var salt = bcrypt.genSaltSync(10); return bcrypt.hashSync(password, salt); }; exports.register = function (server, options, next) { var adminController = new AdminController(server, options); server.bind(adminController); adminController.registerRoutes(); next(); }; exports.register.attributes = { name: 'AdminController' };
Implement basic create admin with username / password only
Implement basic create admin with username / password only
JavaScript
mit
nus-mtp/worldscope,nus-mtp/worldscope,nus-mtp/worldscope,nus-mtp/worldscope
d01f5941fa4a017d3b4434ba2a4f58b98364ba43
lib/node/nodes/source.js
lib/node/nodes/source.js
'use strict'; var Node = require('../node'); var TYPE = 'source'; var PARAMS = { query: Node.PARAM.STRING() }; var Source = Node.create(TYPE, PARAMS); module.exports = Source; module.exports.TYPE = TYPE; module.exports.PARAMS = PARAMS; Source.prototype.sql = function() { return this.query; }; Source.prototype.setColumnsNames = function(columns) { this.columns = columns; // Makes columns affecting Node.id(). // When a `select * from table` might end in a different set of columns // we want to have a different node. this.setAttributeToModifyId('columns'); }; /** * Source nodes are ready by definition * * @returns {Node.STATUS} */ Source.prototype.getStatus = function() { return Node.STATUS.READY; }; Source.prototype.getAndSetUpdatedAt = function(databaseService, callback) { if (this.updatedAt !== null) { return callback(null, this.updatedAt); } databaseService.getLastUpdatedTimeFromAffectedTables(this.sql(), function(err, lastUpdatedAt) { if (err) { return callback(err); } this.updatedAt = lastUpdatedAt; return callback(null, this.updatedAt); }.bind(this)); };
'use strict'; var Node = require('../node'); var TYPE = 'source'; var PARAMS = { query: Node.PARAM.STRING() }; var Source = Node.create(TYPE, PARAMS, { beforeCreate: function(node) { // Last updated time in source node means data changed so it has to modify node.id node.setAttributeToModifyId('updatedAt'); } }); module.exports = Source; module.exports.TYPE = TYPE; module.exports.PARAMS = PARAMS; Source.prototype.sql = function() { return this.query; }; Source.prototype.setColumnsNames = function(columns) { this.columns = columns; // Makes columns affecting Node.id(). // When a `select * from table` might end in a different set of columns // we want to have a different node. this.setAttributeToModifyId('columns'); }; /** * Source nodes are ready by definition * * @returns {Node.STATUS} */ Source.prototype.getStatus = function() { return Node.STATUS.READY; }; Source.prototype.getAndSetUpdatedAt = function(databaseService, callback) { if (this.updatedAt !== null) { return callback(null, this.updatedAt); } databaseService.getLastUpdatedTimeFromAffectedTables(this.sql(), function(err, lastUpdatedAt) { if (err) { return callback(err); } this.updatedAt = lastUpdatedAt; return callback(null, this.updatedAt); }.bind(this)); };
Make updatedAt modifying node.id in Source nodes
Make updatedAt modifying node.id in Source nodes
JavaScript
bsd-3-clause
CartoDB/camshaft
21cd7291094b7b03a5571287bf3673db3b13006e
lib/panes/output-area.js
lib/panes/output-area.js
/* @flow */ import { CompositeDisposable } from "atom"; import ResizeObserver from "resize-observer-polyfill"; import React from "react"; import { reactFactory, OUTPUT_AREA_URI } from "./../utils"; import typeof store from "../store"; import OutputArea from "./../components/output-area"; export default class OutputPane { element = document.createElement("div"); disposer = new CompositeDisposable(); constructor(store: store) { this.element.classList.add("hydrogen", "watch-sidebar"); // HACK: Dispatch a window resize Event for the slider history to recompute // We should use native ResizeObserver once Atom ships with a newer version of Electron // Or fork react-rangeslider to fix https://github.com/whoisandie/react-rangeslider/issues/62 const resizeObserver = new ResizeObserver(this.resize); resizeObserver.observe(this.element); reactFactory( <OutputArea store={store} />, this.element, null, this.disposer ); } resize = () => { window.dispatchEvent(new Event("resize")); }; getTitle = () => "Hydrogen Output Area"; getURI = () => OUTPUT_AREA_URI; getDefaultLocation = () => "right"; getAllowedLocations = () => ["left", "right", "bottom"]; destroy() { this.disposer.dispose(); this.element.remove(); } }
/* @flow */ import { CompositeDisposable, Disposable } from "atom"; import ResizeObserver from "resize-observer-polyfill"; import React from "react"; import { reactFactory, OUTPUT_AREA_URI } from "./../utils"; import typeof store from "../store"; import OutputArea from "./../components/output-area"; export default class OutputPane { element = document.createElement("div"); disposer = new CompositeDisposable(); constructor(store: store) { this.element.classList.add("hydrogen", "watch-sidebar"); // HACK: Dispatch a window resize Event for the slider history to recompute // We should use native ResizeObserver once Atom ships with a newer version of Electron // Or fork react-rangeslider to fix https://github.com/whoisandie/react-rangeslider/issues/62 const resizeObserver = new ResizeObserver(this.resize); resizeObserver.observe(this.element); this.disposer.add( new Disposable(() => { if (store.kernel) store.kernel.outputStore.clear(); }) ); reactFactory( <OutputArea store={store} />, this.element, null, this.disposer ); } resize = () => { window.dispatchEvent(new Event("resize")); }; getTitle = () => "Hydrogen Output Area"; getURI = () => OUTPUT_AREA_URI; getDefaultLocation = () => "right"; getAllowedLocations = () => ["left", "right", "bottom"]; destroy() { this.disposer.dispose(); this.element.remove(); } }
Reset output store if pane is closed
Reset output store if pane is closed
JavaScript
mit
nteract/hydrogen,nteract/hydrogen,xanecs/hydrogen,rgbkrk/hydrogen