commit
stringlengths 40
40
| old_file
stringlengths 4
236
| new_file
stringlengths 4
236
| old_contents
stringlengths 1
3.26k
| new_contents
stringlengths 16
4.43k
| subject
stringlengths 16
624
| message
stringlengths 17
3.29k
| lang
stringclasses 5
values | license
stringclasses 13
values | repos
stringlengths 5
91.5k
|
|---|---|---|---|---|---|---|---|---|---|
ef93b58cecc433382f125702934e3ed30d995eb3
|
www/android/FileSystem.js
|
www/android/FileSystem.js
|
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*
*/
FILESYSTEM_PROTOCOL = "cdvfile";
module.exports = {
__format__: function(fullPath, nativeUrl) {
var path = '/' + this.name + '/' + encodeURI(fullPath);
path = path.replace('//','/');
var ret = FILESYSTEM_PROTOCOL + '://localhost' + path;
var m = /\?.*/.exec(nativeUrl);
if (m) {
ret += m[0];
}
return ret;
}
};
|
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*
*/
FILESYSTEM_PROTOCOL = "cdvfile";
module.exports = {
__format__: function(fullPath, nativeUrl) {
var path;
var contentUrlMatch = /^content:\/\//.exec(nativeUrl);
if (contentUrlMatch) {
// When available, use the path from a native content URL, which was already encoded by Android.
// This is necessary because JavaScript's encodeURI() does not encode as many characters as
// Android, which can result in permission exceptions when the encoding of a content URI
// doesn't match the string for which permission was originally granted.
path = nativeUrl.substring(contentUrlMatch[0].length - 1);
} else {
path = encodeURI(fullPath);
if (!/^\//.test(path)) {
path = '/' + path;
}
var m = /\?.*/.exec(nativeUrl);
if (m) {
path += m[0];
}
}
return FILESYSTEM_PROTOCOL + '://localhost/' + this.name + path;
}
};
|
Fix permission errors due to URI encoding inconsistency on Android
|
CB-9891: Fix permission errors due to URI encoding inconsistency on Android
|
JavaScript
|
apache-2.0
|
tripodsan/cordova-plugin-file,cadenasgmbh/cordova-plugin-file,tripodsan/cordova-plugin-file,macdonst/cordova-plugin-file,apache/cordova-plugin-file,macdonst/cordova-plugin-file,mnill/cordova-plugin-file,sanmeranam/cordova-file,cadenasgmbh/cordova-plugin-file,mnill/cordova-plugin-file,GenusAS/cordova-plugin-file,purplecabbage/cordova-plugin-file,purplecabbage/cordova-plugin-file,cadenasgmbh/cordova-plugin-file,macdonst/cordova-plugin-file,purplecabbage/cordova-plugin-file,cadenasgmbh/cordova-plugin-file,sanmeranam/cordova-file,mnill/cordova-plugin-file,starquake/cordova-plugin-file,sanmeranam/cordova-file,tripodsan/cordova-plugin-file,purplecabbage/cordova-plugin-file,GenusAS/cordova-plugin-file,GenusAS/cordova-plugin-file,tripodsan/cordova-plugin-file,sanmeranam/cordova-file,GenusAS/cordova-plugin-file,mnill/cordova-plugin-file,starquake/cordova-plugin-file,apache/cordova-plugin-file,macdonst/cordova-plugin-file
|
204053d95ffa1429288def46fa1e13941834e045
|
addon-test-support/-private/is-focusable.js
|
addon-test-support/-private/is-focusable.js
|
export default function isFocusable(el) {
let focusableTags = ['INPUT', 'BUTTON', 'LINK', 'SELECT', 'A', 'TEXTAREA'];
let { tagName, type } = el;
if (type === 'hidden') {
return false;
}
return focusableTags.includes(tagName) || el.contentEditable;
}
|
export default function isFocusable(el) {
let focusableTags = ['INPUT', 'BUTTON', 'LINK', 'SELECT', 'A', 'TEXTAREA'];
let { tagName, type } = el;
if (type === 'hidden') {
return false;
}
return focusableTags.indexOf(tagName) > -1 || el.contentEditable;
}
|
Use indexOf instead of includes
|
Use indexOf instead of includes
|
JavaScript
|
mit
|
cibernox/ember-native-dom-helpers,cibernox/ember-native-dom-helpers
|
ccb8732f686b578c9f1d09c21f5498769f15bf01
|
src/core/sfx.js
|
src/core/sfx.js
|
var Sfx = {
sounds: { },
preload: function() {
// Note to self: Do not preload "burning tomato". It doesn't work due to timing issues and just causes overhead.
},
load: function(fileName) {
if (typeof Sfx.sounds[fileName] != 'undefined') {
return Sfx.sounds[fileName];
}
Sfx.sounds[fileName] = new Audio('assets/sfx/' + fileName);
Sfx.sounds[fileName].load();
return Sfx.sounds[fileName];
},
play: function(soundId, volume) {
if (volume == null) {
volume = 0.8;
}
if (typeof Sfx.sounds[soundId] == 'undefined') {
Sfx.load(soundId);
} else {
// Call load() every time to fix Chrome issue where sound only plays first time
Sfx.sounds[soundId].load();
}
Sfx.sounds[soundId].volume = volume;
Sfx.sounds[soundId].play();
}
};
|
var Sfx = {
sounds: { },
preload: function() {
// Note to self: Do not preload "burning tomato". It doesn't work due to timing issues and just causes overhead.
this.load('dialogue_tick.wav');
this.load('footstep_snow_1.wav');
this.load('footstep_snow_2.wav');
this.load('footstep_snow_3.wav');
this.load('footstep_snow_4.wav');
this.load('boom.wav');
this.load('knock.wav');
},
load: function(fileName) {
if (typeof Sfx.sounds[fileName] != 'undefined') {
return Sfx.sounds[fileName];
}
Sfx.sounds[fileName] = new Audio('assets/sfx/' + fileName);
Sfx.sounds[fileName].load();
return Sfx.sounds[fileName];
},
play: function(soundId, volume) {
if (volume == null) {
volume = 0.8;
}
if (typeof Sfx.sounds[soundId] == 'undefined') {
Sfx.load(soundId);
} else {
// Call load() every time to fix Chrome issue where sound only plays first time
Sfx.sounds[soundId].load();
}
Sfx.sounds[soundId].volume = volume;
Sfx.sounds[soundId].play();
}
};
|
Update the preload list. Fixes issue with the first dialogue message glitching up with the ticking sound.
|
[SFX] Update the preload list. Fixes issue with the first dialogue message glitching up with the ticking sound.
|
JavaScript
|
mit
|
burningtomatoes/CabinInTheSnow
|
c4a345314585cd23d965d0e52441a275ae53f356
|
test/lib/rules/disallow-objectcontroller.js
|
test/lib/rules/disallow-objectcontroller.js
|
describe('lib/rules/disallow-objectcontroller', function () {
var checker = global.checker({
plugins: ['./lib/index']
});
describe('not configured', function() {
it('should report with undefined', function() {
global.expect(function() {
checker.configure({disallowObjectController: undefined});
}).to.throws(/requires a true value/i);
});
it('should report with an object', function() {
global.expect(function() {
checker.configure({disallowObjectController: {}});
}).to.throws(/requires a true value/i);
});
});
describe('with true', function() {
checker.rules({disallowObjectController: true});
checker.cases([
/* jshint ignore:start */
{
it: 'should not report',
code: function() {
Ember.Controller.extend({
});
}
}, {
it: 'should not report',
code: function() {
var foo = Ember.ObjectController;
}
}, {
it: 'should report deprecated use',
errors: 1,
code: function() {
Ember.ObjectController.extend({
});
}
}, {
it: 'should report deprecated use',
errors: 1,
code: function() {
var foo = Ember.ObjectController.create({
});
}
}
/* jshint ignore:end */
]);
});
});
|
describe('lib/rules/disallow-objectcontroller', function () {
var checker = global.checker({
plugins: ['./lib/index']
});
describe('not configured', function() {
it('should report with undefined', function() {
global.expect(function() {
checker.configure({disallowObjectController: undefined});
}).to.throws(/requires a true value/i);
});
it('should report with an object', function() {
global.expect(function() {
checker.configure({disallowObjectController: {}});
}).to.throws(/requires a true value/i);
});
});
describe('with true', function() {
checker.rules({disallowObjectController: true});
checker.cases([
/* jshint ignore:start */
{
it: 'should not report',
code: function() {
Ember.Controller.extend({
});
}
}, {
it: 'should not report',
code: function() {
var foo = Ember.ObjectController;
}
}, {
it: 'should report deprecated use',
errors: 1,
code: function() {
Ember.ObjectController.extend({
});
},
errors: [{
column: 6, line: 1, filename: 'input', rule: 'disallowObjectController', fixed: undefined,
message: 'ObjectController is deprecated in Ember 1.11'
}]
}, {
it: 'should report deprecated use',
errors: 1,
code: function() {
var foo = Ember.ObjectController.create({
});
},
errors: [{
column: 16, line: 1, filename: 'input', rule: 'disallowObjectController', fixed: undefined,
message: 'ObjectController is deprecated in Ember 1.11'
}]
}
/* jshint ignore:end */
]);
});
});
|
Add additional assertions around objectcontroller errors
|
Add additional assertions around objectcontroller errors
|
JavaScript
|
mit
|
minichate/jscs-ember-deprecations,minichate/jscs-ember-deprecations
|
9fd9751f875e2800672c12e66889234375deeb51
|
__tests__/assets/js/util.spec.js
|
__tests__/assets/js/util.spec.js
|
import * as util from '~/assets/js/util'
describe('util', () => {
test('getRSSLink', () => {
expect(util.getRSSLink('foo')).toEqual({
hid: 'rss',
rel: 'alternate',
type: 'application/rss+xml',
href: 'foo'
})
})
})
|
import * as util from '~/assets/js/util'
describe('util', () => {
test('getRSSLink', () => {
expect(util.getRSSLink('foo')).toEqual({
hid: 'rss',
rel: 'alternate',
type: 'application/rss+xml',
href: 'foo'
})
})
describe('getImageURLs', () => {
it('get from link', () => {
expect(
util.getImageURLs({
content: {
entities: {
links: [
{
link: 'photo.jpeg'
}
]
}
}
})
).toEqual([
{
thumb: 'photo.jpeg',
original: 'photo.jpeg'
}
])
})
it('get from raw', () => {
expect(
util.getImageURLs(
{
content: {},
raw: [
{
type: 'io.pnut.core.oembed',
value: {
type: 'photo',
url: 'original.png',
thumbnail_url: 'thumbnail.png'
}
}
]
},
true
)
).toMatchObject([
{
thumb: 'thumbnail.png',
original: 'original.png'
}
])
})
it('Remove duplicate', () => {
expect(
util.getImageURLs({
content: {
entities: {
links: [
{
link: 'original.png'
}
]
}
},
raw: [
{
type: 'io.pnut.core.oembed',
value: {
type: 'photo',
url: 'original.png',
thumbnail_url: 'thumbnail.png'
}
}
]
})
).toMatchObject([
{
thumb: 'thumbnail.png',
original: 'original.png'
}
])
})
})
})
|
Add the getImageURLs test case
|
Add the getImageURLs test case
|
JavaScript
|
mit
|
sunya9/beta,sunya9/beta,sunya9/beta
|
7adc1e15da0b0e0c11b383758322e2ed3412486a
|
addon/components/object-list-view-input-cell.js
|
addon/components/object-list-view-input-cell.js
|
import BaseComponent from './flexberry-base';
export default BaseComponent.extend({
tagName: 'td',
classNames: [],
column: null,
record: null,
didInsertElement: function() {
var _this = this;
this.$('input').change(function() {
_this.record.set(_this.column.propName, _this.$(this).val());
});
}
});
|
import BaseComponent from './flexberry-base';
export default BaseComponent.extend({
tagName: 'td',
classNames: [],
column: null,
record: null,
didInsertElement: function() {
var _this = this;
this.$('input').change(function() {
_this._setValue();
});
this.$('input').keyup(function() {
_this._setValue();
});
},
_setValue: function() {
var currentModelValue = this.record.get(this.column.propName);
var currentInputValue = this.$('input').val();
if (currentModelValue !== currentInputValue) {
this.record.set(this.column.propName, currentInputValue);
}
}
});
|
Modify the way of two way binding
|
Modify the way of two way binding
in object-list-view-input-cell component. Add binding input value with
model on key press.
|
JavaScript
|
mit
|
Flexberry/ember-flexberry,Flexberry/ember-flexberry,Flexberry/ember-flexberry,Flexberry/ember-flexberry
|
420cda51273dd81b2d5eeff07400d23d31cc21c6
|
src/store/api/playlists.js
|
src/store/api/playlists.js
|
import client from './client'
export default {
getPlaylists (production, callback) {
client.get(`/api/data/projects/${production.id}/playlists`, callback)
},
newPlaylist (playlist, callback) {
const data = {
name: playlist.name,
project_id: playlist.production_id
}
client.post('/api/data/playlists/', data, callback)
},
updatePlaylist (playlist, callback) {
const data = {
name: playlist.name
}
client.put(`/api/data/playlists/${playlist.id}`, data, callback)
},
deletePlaylist (playlist, callback) {
client.del(`/api/data/playlists/${playlist.id}`, callback)
}
}
|
import client from './client'
export default {
getPlaylists (production, callback) {
client.get(`/api/data/projects/${production.id}/playlists`, callback)
},
getPlaylist (production, playlist, callback) {
const path = `/api/data/projects/${production.id}/playlists/${playlist.id}`
client.get(path, callback)
},
getShotPreviewFiles (shot, callback) {
const path = `/api/data/shots/${shot.id}/preview-files`
client.get(path, callback)
},
newPlaylist (playlist, callback) {
const data = {
name: playlist.name,
project_id: playlist.production_id
}
client.post('/api/data/playlists/', data, callback)
},
updatePlaylist (playlist, callback) {
const data = {
name: playlist.name
}
if (playlist.shots) {
data.shots = playlist.shots
}
client.put(`/api/data/playlists/${playlist.id}`, data, callback)
},
deletePlaylist (playlist, callback) {
client.del(`/api/data/playlists/${playlist.id}`, callback)
}
}
|
Add functions to get details about preview files
|
Add functions to get details about preview files
|
JavaScript
|
agpl-3.0
|
cgwire/kitsu,cgwire/kitsu
|
f0295c57ad4b607c0922ddfbfc1ee6f694d8a97c
|
src/legacy/js/functions/_loadEmbedIframe.js
|
src/legacy/js/functions/_loadEmbedIframe.js
|
/**
* Created by crispin on 10/12/2015.
*/
function loadEmbedIframe(onSave) {
// add modal window
$('.workspace-menu').append(templates.embedIframe());
// variables
var modal = $(".modal");
// modal functions
function closeModal() {
modal.remove();
}
function saveUrl() {
var embedUrl = $('input#embed-url').val();
var fullWidth = $('input#full-width-checkbox').is(':checked');
if (!embedUrl) {
console.log("No url added");
sweetAlert('URL field is empty', 'Please add a url and save again');
return;
}
var parsedEmbedUrl = new URL(embedUrl);
if (parsedEmbedUrl.hostname === window.location.hostname) {
embedUrl = parsedEmbedUrl.pathname;
}
onSave('<ons-interactive url="' + embedUrl + '" full-width="' + fullWidth + '"/>');
modal.remove();
}
// bind events
$('.btn-embed-cancel').click(function() {
closeModal();
});
$('.btn-embed-save').click(function() {
saveUrl();
});
modal.keyup(function(e) {
if (e.keyCode == 27) { //close on esc key
closeModal()
}
if (e.keyCode == 13) { //save on enter key
saveUrl();
}
});
}
|
/**
* Created by crispin on 10/12/2015.
*/
function loadEmbedIframe(onSave) {
// add modal window
$('.workspace-menu').append(templates.embedIframe());
// variables
var modal = $(".modal");
// modal functions
function closeModal() {
modal.remove();
}
function saveUrl() {
var embedUrl = $('input#embed-url').val();
var fullWidth = $('input#full-width-checkbox').is(':checked');
if (!embedUrl) {
console.log("No url added");
sweetAlert('URL field is empty', 'Please add a url and save again');
return;
}
var parsedEmbedUrl = new URL(embedUrl);
console.log(parsedEmbedUrl);
console.log(window.location);
if (parsedEmbedUrl.host === window.location.host) {
embedUrl = parsedEmbedUrl.pathname;
}
onSave('<ons-interactive url="' + embedUrl + '" full-width="' + fullWidth + '"/>');
modal.remove();
}
// bind events
$('.btn-embed-cancel').click(function() {
closeModal();
});
$('.btn-embed-save').click(function() {
saveUrl();
});
modal.keyup(function(e) {
if (e.keyCode == 27) { //close on esc key
closeModal()
}
if (e.keyCode == 13) { //save on enter key
saveUrl();
}
});
}
|
Use host instead of hostname
|
Use host instead of hostname
|
JavaScript
|
mit
|
ONSdigital/florence,ONSdigital/florence,ONSdigital/florence,ONSdigital/florence
|
361b2f3c3d871da640431e8cd24baeedda15707d
|
lib/github.js
|
lib/github.js
|
'use strict';
var GitHubApi = require('github');
var githubapi = new GitHubApi({
// required
version: "3.0.0",
// optional
timeout: 3000
});
exports.getPackageJson = function (user, repo, callback) {
if (!user) {
callback('GitHub user not valid.');
return;
}
if (!repo) {
callback('GitHub repo not valid.');
return;
}
githubapi.repos.getContent({
user: user,
repo: repo,
path: 'package.json'
}, function(error, result) {
if (error) {
callback(error.message || error.defaultMessage || error);
return;
}
var jsonString = new Buffer(result.content, result.encoding).toString();
var json = JSON.parse(jsonString);
callback(null, json);
});
};
exports.getUserFromUrl = function(url) {
var user = url.substr('https://github.com/'.length);
user = user.substr(0, user.indexOf('/'));
return user;
};
exports.getRepoFromUrl = function(url) {
var repo = url.substr(url.lastIndexOf('/')+1);
repo = repo.substr(0, repo.indexOf('.'));
return repo;
}
|
'use strict';
var GitHubApi = require('github');
var githubapi = new GitHubApi({
// required
version: "3.0.0",
// optional
timeout: 3000
});
exports.getPackageJson = function (user, repo, callback) {
if (!user) {
callback('GitHub user not valid.');
return;
}
if (!repo) {
callback('GitHub repo not valid.');
return;
}
githubapi.repos.getContent({
user: user,
repo: repo,
path: 'package.json'
}, function(error, result) {
if (error) {
callback(error.message || error.defaultMessage || error);
return;
}
var jsonString = new Buffer(result.content, result.encoding).toString();
var json = JSON.parse(jsonString);
callback(null, json);
});
};
exports.getUserFromUrl = function(url) {
if (!url) {
return url;
}
var user = url.substr('https://github.com/'.length);
return user && user.substr(0, user.indexOf('/'));
};
exports.getRepoFromUrl = function(url) {
if (!url) {
return url;
}
var repo = url.substr(url.lastIndexOf('/')+1);
return repo && repo.substr(0, repo.indexOf('.'));
}
|
Add protection for empty GitHub url.
|
Add protection for empty GitHub url.
|
JavaScript
|
mit
|
seriema/npmalerts,creationix/npmalerts
|
c3ff50a7013280fdc3686e9ca676882ceddeef7b
|
app/assets/javascripts/admin/application.js
|
app/assets/javascripts/admin/application.js
|
//= require trix
//= require jquery.geocomplete
//= require cleave
//= require ./trix_events
//= require ./trix_toolbar
//= require ./app/init
//= require_tree ./app
$(document).on('turbolinks:load', function() {
// Datepicker
$('.air-datepicker').datepicker({
autoClose: true,
onSelect: function onSelect(_, _, instance) {
$(instance.el).trigger("datepicker-change");
}
});
});
|
//= require trix
//= require jquery.geocomplete
//= require cleave
//= require ./trix_events
//= require ./trix_toolbar
//= require ./app/init
//= require_tree ./app
$(document).on('turbolinks:load', function() {
// Datepicker
$('.air-datepicker').datepicker({
autoClose: true,
minutesStep: 5,
onSelect: function onSelect(_, _, instance) {
$(instance.el).trigger("datepicker-change");
}
});
});
|
Allow only 5 minute increments for date picker so we reduce the number of steps
|
Allow only 5 minute increments for date picker so we reduce the number of steps
|
JavaScript
|
agpl-3.0
|
PopulateTools/gobierto,PopulateTools/gobierto,PopulateTools/gobierto,PopulateTools/gobierto-dev,PopulateTools/gobierto,PopulateTools/gobierto-dev,PopulateTools/gobierto-dev,PopulateTools/gobierto-dev
|
c2abeaf62c7a8ec5b2435a579cc192a1edc58ceb
|
app/index-create-script.js
|
app/index-create-script.js
|
const bravePort = process.env.BRAVE_PORT || 8080
const createScript = function (scriptPath) {
return new Promise(function (resolve, reject) {
var script = document.createElement('script')
script.type = 'text/javascript'
script.src = scriptPath.replace(/\{port\}/, bravePort)
script.async = true
script.onload = resolve
script.onerror = reject
document.body.appendChild(script)
})
}
createScript('http://localhost:{port}/webpack-dev-server.js').catch(function () {
document.querySelector('#setupError').style.display = 'block'
}).then(function () {
createScript('http://localhost:{port}/built/app.entry.js')
})
|
const bravePort = process.env.BRAVE_PORT || 8080
const createScript = function (scriptPath) {
return new Promise(function (resolve, reject) {
var script = document.createElement('script')
script.type = 'text/javascript'
script.src = scriptPath.replace(/\{port\}/, bravePort)
script.async = true
script.onload = resolve
script.onerror = reject
document.body.appendChild(script)
})
}
createScript('http://localhost:{port}/built/app.entry.js')
createScript('http://localhost:{port}/webpack-dev-server.js').catch(function () {
document.querySelector('#setupError').style.display = 'block'
})
|
Fix dev app init for Windows
|
Fix dev app init for Windows
Having it load entry.js only after the other script is loading is
causing problems in init on slow machines (or my Windows VM).
The devserver doesn't need to be included first, it's just for live
realoading.
Auditors: da39a3ee5e6b4b0d3255bfef95601890afd80709@diracdeltas
|
JavaScript
|
mpl-2.0
|
MKuenzi/browser-laptop,Sh1d0w/browser-laptop,MKuenzi/browser-laptop,jonathansampson/browser-laptop,darkdh/browser-laptop,manninglucas/browser-laptop,manninglucas/browser-laptop,pmkary/braver,diasdavid/browser-laptop,MKuenzi/browser-laptop,Sh1d0w/browser-laptop,darkdh/browser-laptop,luixxiul/browser-laptop,pmkary/braver,Sh1d0w/browser-laptop,jonathansampson/browser-laptop,diasdavid/browser-laptop,willy-b/browser-laptop,darkdh/browser-laptop,diasdavid/browser-laptop,willy-b/browser-laptop,jonathansampson/browser-laptop,luixxiul/browser-laptop,jonathansampson/browser-laptop,luixxiul/browser-laptop,dcposch/browser-laptop,willy-b/browser-laptop,timborden/browser-laptop,timborden/browser-laptop,diasdavid/browser-laptop,manninglucas/browser-laptop,darkdh/browser-laptop,timborden/browser-laptop,dcposch/browser-laptop,dcposch/browser-laptop,Sh1d0w/browser-laptop,dcposch/browser-laptop,MKuenzi/browser-laptop,timborden/browser-laptop,manninglucas/browser-laptop,pmkary/braver,pmkary/braver,luixxiul/browser-laptop,willy-b/browser-laptop
|
061d5ff56ea10b8b1b6441bdfe6dd4c0751ce6b6
|
app/updateChannel.js
|
app/updateChannel.js
|
'use strict'
const TelegramBot = require('node-telegram-bot-api');
const config = require('../config');
const utils = require('./utils');
const Kinospartak = require('./Kinospartak/Kinospartak');
const bot = new TelegramBot(config.TOKEN);
const kinospartak = new Kinospartak();
/**
* updateSchedule - update schedule and push updates to Telegram channel
*
* @return {Promise}
*/
function updateSchedule() {
return kinospartak.getChanges()
.then(changes =>
changes.length ?
utils.formatSchedule(changes) : Promise.reject('No changes'))
.then(messages => utils.sendInOrder(bot, config.CHANNEL, messages))
.then(() => kinospartak.commitChanges())
};
/**
* updateNews - update news and push updates to Telegram channel
*
* @return {Promise}
*/
function updateNews() {
return kinospartak.getLatestNews()
.then(news =>
news.length ?
utils.formatNews(news) : Promise.reject('No news'))
.then(messages => utils.sendInOrder(bot, config.CHANNEL, messages))
.then(() => kinospartak.setNewsOffset(new Date().toString()))
};
updateSchedule()
.then(() => updateNews())
|
'use strict'
const TelegramBot = require('node-telegram-bot-api');
const config = require('../config');
const utils = require('./utils');
const Kinospartak = require('./Kinospartak/Kinospartak');
const bot = new TelegramBot(config.TOKEN);
const kinospartak = new Kinospartak();
/**
* updateSchedule - update schedule and push updates to Telegram channel
*
* @return {Promise}
*/
function updateSchedule() {
return kinospartak.getChanges()
.then(changes =>
changes.length
? utils.formatSchedule(changes)
: undefined)
.then(messages =>
messages
? utils.sendInOrder(bot, config.CHANNEL, messages)
: undefined)
.then(() => kinospartak.commitChanges())
};
/**
* updateNews - update news and push updates to Telegram channel
*
* @return {Promise}
*/
function updateNews() {
return kinospartak.getLatestNews()
.then(news =>
news.length
? utils.formatNews(news)
: undefined)
.then(messages =>
messages
? utils.sendInOrder(bot, config.CHANNEL, messages)
: undefined)
.then(() => kinospartak.setNewsOffset(new Date().toString()))
};
function update() {
return Promise.all([
updateSchedule,
updateNews
]).catch((err) => {
setTimeout(() => {
update();
}, 60 * 5);
})
}
update();
|
Add error handling for channel updates
|
Add error handling for channel updates
|
JavaScript
|
mit
|
TheBeastOfCaerbannog/kinospartak-bot
|
8646b63a22e82765743b102c1665d5e97e831e75
|
src/schema/defaultsetup.js
|
src/schema/defaultsetup.js
|
const {Plugin} = require("../edit")
const {menuBar} = require("../menu/menubar")
const {inputRules, allInputRules} = require("../inputrules")
const {defaultRules} = require("./inputrules")
const {defaultMenuItems} = require("./menu")
const {defaultSchemaKeymapPlugin} = require("./keymap")
const {defaultSchemaStyle} = require("./style")
// :: Plugin
// A convenience plugin that bundles together a simple menubar, the
// default input rules, default key bindings, and default styling.
// Probably only useful for quickly setting up a passable
// editor—you'll need more control over your settings in most
// real-world situations.
const defaultSetup = new Plugin(class DefaultSetup {
constructor(pm, options) {
let menu = defaultMenuItems(pm.schema).fullMenu
if (options.updateMenu) menu = options.updateMenu(menu)
this.plugins = (menu ? [menuBar.config({float: true, content: menu})] : []).concat([
inputRules.config({rules: allInputRules.concat(defaultRules(pm.schema))}),
defaultSchemaKeymapPlugin,
defaultSchemaStyle
])
this.plugins.forEach(plugin => plugin.attach(pm))
}
detach(pm) {
this.plugins.forEach(plugin => plugin.detach(pm))
}
})
exports.defaultSetup = defaultSetup
|
const {Plugin} = require("../edit")
const {menuBar} = require("../menu/menubar")
const {inputRules, allInputRules} = require("../inputrules")
const {defaultRules} = require("./inputrules")
const {defaultMenuItems} = require("./menu")
const {defaultSchemaKeymapPlugin} = require("./keymap")
const {defaultSchemaStyle} = require("./style")
// :: Plugin
// A convenience plugin that bundles together a simple menubar, the
// default input rules, default key bindings, and default styling.
// Probably only useful for quickly setting up a passable
// editor—you'll need more control over your settings in most
// real-world situations.
const defaultSetup = new Plugin(class DefaultSetup {
constructor(pm, options) {
let menu = options.menu
if (menu == null)
menu = defaultMenuItems(pm.schema).fullMenu
this.plugins = (menu ? [menuBar.config({float: true, content: menu})] : []).concat([
inputRules.config({rules: allInputRules.concat(defaultRules(pm.schema))}),
defaultSchemaKeymapPlugin,
defaultSchemaStyle
])
this.plugins.forEach(plugin => plugin.attach(pm))
}
detach(pm) {
this.plugins.forEach(plugin => plugin.detach(pm))
}
})
exports.defaultSetup = defaultSetup
|
Replace the updateMenu option to defaultSetup with a menu option
|
Replace the updateMenu option to defaultSetup with a menu option
Much cleaner
|
JavaScript
|
mit
|
kiejo/prosemirror,tzuhsiulin/prosemirror,tzuhsiulin/prosemirror,kiejo/prosemirror,kiejo/prosemirror,salzhrani/prosemirror,tzuhsiulin/prosemirror,salzhrani/prosemirror,salzhrani/prosemirror
|
08289ce0e335bffcb0126fc940660c465cf13d98
|
addon/initializers/responsive.js
|
addon/initializers/responsive.js
|
import Media from 'ember-responsive/media';
/**
* An initializer that sets up `ember-responsive`.
*
* Refer to {{#crossLink "Ember.Application.responsive"}}{{/crossLink}}
* for examples of how to configure this library before the initializer
* before it's run by Ember.
*
* @static
* @constructor
* @module ember-responsive
* @namespace Ember.Application
* @class initializer
*/
export default {
/**
* @property name
* @type string
* @default responsive
*/
name: 'responsive',
/**
* @method initialize
* @param Ember.Container container
* @param Ember.Application app
*/
initialize: function(container, app) {
var breakpoints = container.lookupFactory('breakpoints:main');
var media = Media.create();
if (breakpoints) {
for (var name in breakpoints) {
if (media.hasOwnProperty(name)) {
media.match(name, breakpoints[name]);
}
}
}
app.register('responsive:media', media, { instantiate: false });
app.inject('controller', 'media', 'responsive:media');
app.inject('component', 'media', 'responsive:media');
app.inject('route', 'media', 'responsive:media');
app.inject('view', 'media', 'responsive:media');
}
};
|
import Media from 'ember-responsive/media';
/**
* An initializer that sets up `ember-responsive`.
*
* Refer to {{#crossLink "Ember.Application.responsive"}}{{/crossLink}}
* for examples of how to configure this library before the initializer
* before it's run by Ember.
*
* @static
* @constructor
* @module ember-responsive
* @namespace Ember.Application
* @class initializer
*/
export default {
/**
* @property name
* @type string
* @default responsive
*/
name: 'responsive',
/**
* @method initialize
* @param Ember.Container container
* @param Ember.Application app
*/
initialize: function(container, app) {
if (app.responsive) {
Ember.warn('Your breakpoints should be defined in /app/breakpoints.js');
}
var breakpoints = container.lookupFactory('breakpoints:main');
var media = Media.create();
if (breakpoints) {
for (var name in breakpoints) {
if (media.hasOwnProperty(name)) {
media.match(name, breakpoints[name]);
}
}
}
app.register('responsive:media', media, { instantiate: false });
app.inject('controller', 'media', 'responsive:media');
app.inject('component', 'media', 'responsive:media');
app.inject('route', 'media', 'responsive:media');
app.inject('view', 'media', 'responsive:media');
}
};
|
Add a warning if breakpoints are still define in app.js
|
Add a warning if breakpoints are still define in app.js
|
JavaScript
|
mit
|
topaxi/ember-responsive,jasonmit/ember-responsive,jasonmit/ember-responsive,jherdman/ember-responsive,topaxi/ember-responsive,freshbooks/ember-responsive,salzhrani/ember-responsive,salzhrani/ember-responsive,elwayman02/ember-responsive,f3ndot/ember-responsive,freshbooks/ember-responsive,f3ndot/ember-responsive,jherdman/ember-responsive,elwayman02/ember-responsive
|
8094fb5d78b8fecc3a45a0bd7771b034888bd41a
|
app/server/server.js
|
app/server/server.js
|
import path from 'path';
import renderApp from './renderApp.js';
import express from 'express';
import compression from 'compression';
const server = express();
const port = process.env.PORT || 80;
server.use(compression());
server.use(express.static('public'));
server.use('/fireball-js', express.static(path.resolve(__dirname, '../../node_modules/fireball-js')));
server.get('*', renderApp);
server.listen(port, () => {
console.log('Node running on port', port); // eslint-disable-line no-console
});
if (process.env.NODE_ENV !== 'production') {
require('../../buildTools/webpackDevServer.js');
}
|
import path from 'path';
import renderApp from './renderApp.js';
import express from 'express';
import compression from 'compression';
const server = express();
const port = process.env.PORT || 80;
server.use(compression());
server.use(express.static('public', {maxAge: 31536000})); // 31536000 = one year
server.use('/fireball-js', express.static(path.resolve(__dirname, '../../node_modules/fireball-js')));
server.get('*', renderApp);
server.listen(port, () => {
console.log('Node running on port', port); // eslint-disable-line no-console
});
if (process.env.NODE_ENV !== 'production') {
require('../../buildTools/webpackDevServer.js');
}
|
Add cache-control max age to static content
|
Add cache-control max age to static content
|
JavaScript
|
mit
|
davidgilbertson/davidg-site,davidgilbertson/davidg-site
|
f9639831d2d01cfad745f9355f76bd6bd305e932
|
addon/components/file-renderer/component.js
|
addon/components/file-renderer/component.js
|
import Ember from 'ember';
import layout from './template';
import config from 'ember-get-config';
export default Ember.Component.extend({
layout,
download: null,
mfrUrl: Ember.computed('download', function() {
var base = config.OSF.renderUrl;
var download = this.get('download');
var renderUrl = base + '?url=' + encodeURIComponent(download + '?direct&mode=render&initialWidth=766');
return renderUrl;
})
});
|
import Ember from 'ember';
import layout from './template';
import config from 'ember-get-config';
export default Ember.Component.extend({
layout,
download: null,
width: '100%',
height: '100%',
mfrUrl: Ember.computed('download', function() {
var base = config.OSF.renderUrl;
var download = this.get('download');
var renderUrl = base + '?url=' + encodeURIComponent(download + '?direct&mode=render&initialWidth=766');
return renderUrl;
})
});
|
Add height and width defaults for mfr renderer
|
Add height and width defaults for mfr renderer
|
JavaScript
|
apache-2.0
|
jamescdavis/ember-osf,crcresearch/ember-osf,CenterForOpenScience/ember-osf,samchrisinger/ember-osf,baylee-d/ember-osf,crcresearch/ember-osf,binoculars/ember-osf,hmoco/ember-osf,pattisdr/ember-osf,binoculars/ember-osf,hmoco/ember-osf,CenterForOpenScience/ember-osf,chrisseto/ember-osf,cwilli34/ember-osf,jamescdavis/ember-osf,chrisseto/ember-osf,pattisdr/ember-osf,samchrisinger/ember-osf,cwilli34/ember-osf,baylee-d/ember-osf
|
725165d485e127498f934e63e0498614dd7d4072
|
Nope.safariextension/rules/custom/css_rules.js
|
Nope.safariextension/rules/custom/css_rules.js
|
var advertisingCSSRules = [{
"trigger": {
"url-filter": ".*"
},
"action": {
"type": "css-display-none",
"selector":
".ad-promotions-container,\
.ad-wide,\
.ad-top,\
#bottomads"
}
}];
|
var advertisingCSSRules = [{
"trigger": {
"url-filter": ".*"
},
"action": {
"type": "css-display-none",
"selector":
".ad-promotions-container,\
.ad-wide,\
.ad-top,\
#bottomads,\
#tads"
}
}];
|
Hide Google search top ads
|
[Rules] Hide Google search top ads
|
JavaScript
|
mit
|
kaishin/Nope,kaishin/Nope,kaishin/Nope
|
a13ed5a7f9a50ecd2e5c9341d37dfe795c374c02
|
tests/extend.js
|
tests/extend.js
|
var $ = require('../')
, assert = require('assert')
$.import('Foundation')
$.NSAutoreleasePool('alloc')('init')
// Subclass 'NSObject', creating a new class named 'NRTest'
var NRTest = $.NSObject.extend('NRTest')
, counter = 0
// Add a new method to the NRTest class responding to the "description" selector
NRTest.addMethod('description', '@@:', function (self, _cmd) {
counter++
console.log(_cmd)
return $.NSString('stringWithUTF8String', 'test')
})
// Finalize the class so the we can make instances of it
NRTest.register()
// Create an instance
var instance = NRTest('alloc')('init')
// call [instance description] in a variety of ways (via toString())
console.log(instance('description')+'')
console.log(instance.toString())
//console.log(String(instance)) // now this one segfaults? WTF!?!?!
console.log(''+instance)
console.log(instance+'')
console.log(instance)
assert.equal(counter, 5)
|
var $ = require('../')
, assert = require('assert')
$.import('Foundation')
$.NSAutoreleasePool('alloc')('init')
// Subclass 'NSObject', creating a new class named 'NRTest'
var NRTest = $.NSObject.extend('NRTest')
, counter = 0
// Add a new method to the NRTest class responding to the "description" selector
assert.ok(NRTest.addMethod('description', '@@:', function (self, _cmd) {
counter++
console.log(_cmd)
console.log(self.ivar('name'))
return $.NSString('stringWithUTF8String', 'test')
}))
// Add an instance variable, an NSString* instance.
assert.ok(NRTest.addIvar('name', '@'))
// Finalize the class so the we can make instances of it
NRTest.register()
// Create an instance
var instance = NRTest('alloc')('init')
// call [instance description] in a variety of ways (via toString())
console.log(instance('description')+'')
console.log(instance.toString())
instance.ivar('name', $._('NodObjC Rules!'))
console.log(String(instance))
console.log(''+instance)
console.log(instance+'')
console.log(instance)
assert.equal(counter, 6)
|
Add test for single addIvar call. For some reason this fixes the segfault from before... WTF...
|
Add test for single addIvar call. For some reason this fixes the segfault from before... WTF...
|
JavaScript
|
mit
|
mralexgray/NodObjC,TooTallNate/NodObjC,TooTallNate/NodObjC,mralexgray/NodObjC,telerik/NodObjC,telerik/NodObjC,jerson/NodObjC,jerson/NodObjC,jerson/NodObjC
|
21c5f97e898b8f02ff38445536481151affdf077
|
src/Oro/Bundle/UIBundle/Resources/public/js/extend/bootstrap/bootstrap-typeahead.js
|
src/Oro/Bundle/UIBundle/Resources/public/js/extend/bootstrap/bootstrap-typeahead.js
|
define(function(require) {
'use strict';
var $ = require('jquery');
require('bootstrap');
/**
* This customization allows to define own click, render, show functions for Typeahead
*/
var Typeahead;
var origTypeahead = $.fn.typeahead.Constructor;
var origFnTypeahead = $.fn.typeahead;
Typeahead = function(element, options) {
var opts = $.extend({}, $.fn.typeahead.defaults, options);
this.click = opts.click || this.click;
this.render = opts.render || this.render;
this.show = opts.show || this.show;
origTypeahead.apply(this, arguments);
};
Typeahead.prototype = origTypeahead.prototype;
Typeahead.prototype.constructor = Typeahead;
$.fn.typeahead = function(option) {
return this.each(function() {
var $this = $(this);
var data = $this.data('typeahead');
var options = typeof option === 'object' && option;
if (!data) {
$this.data('typeahead', (data = new Typeahead(this, options)));
}
if (typeof option === 'string') {
data[option]();
}
});
};
$.fn.typeahead.defaults = origFnTypeahead.defaults;
$.fn.typeahead.Constructor = Typeahead;
$.fn.typeahead.noConflict = origFnTypeahead.noConflict;
});
|
define(function(require) {
'use strict';
var $ = require('jquery');
require('bootstrap');
/**
* This customization allows to define own focus, click, render, show, lookup functions for Typeahead
*/
var Typeahead;
var origTypeahead = $.fn.typeahead.Constructor;
var origFnTypeahead = $.fn.typeahead;
Typeahead = function(element, options) {
var opts = $.extend({}, $.fn.typeahead.defaults, options);
this.focus = opts.focus || this.focus;
this.render = opts.render || this.render;
this.show = opts.show || this.show;
this.lookup = opts.lookup || this.lookup;
origTypeahead.apply(this, arguments);
};
Typeahead.prototype = origTypeahead.prototype;
Typeahead.prototype.constructor = Typeahead;
$.fn.typeahead = function(option) {
return this.each(function() {
var $this = $(this);
var data = $this.data('typeahead');
var options = typeof option === 'object' && option;
if (!data) {
$this.data('typeahead', (data = new Typeahead(this, options)));
}
if (typeof option === 'string') {
data[option]();
}
});
};
$.fn.typeahead.defaults = origFnTypeahead.defaults;
$.fn.typeahead.Constructor = Typeahead;
$.fn.typeahead.noConflict = origFnTypeahead.noConflict;
});
|
Add validation functionality to RuleEditorComponent - extended typeahead plugin; - changed autocomplete init script; - added typeahead behavior ащк empty value;
|
BB-4210: Add validation functionality to RuleEditorComponent
- extended typeahead plugin;
- changed autocomplete init script;
- added typeahead behavior ащк empty value;
|
JavaScript
|
mit
|
orocrm/platform,orocrm/platform,orocrm/platform
|
6637f4982ba917abdc1123f8cf1b6f615ecc9b73
|
addon/controllers/sub-row-array.js
|
addon/controllers/sub-row-array.js
|
import Ember from 'ember';
var SubRowArray = Ember.ArrayController.extend({
init: function() {
this._super();
var oldObject = this.get('oldObject');
if (oldObject) {
var content = this.get('content');
var oldControllers = oldObject.get('_subControllers');
oldControllers.forEach(function(item) {
if (item) {
var index = content.indexOf(Ember.get(item, 'content'));
this.setControllerAt(item, index);
}
}.bind(this));
}
},
objectAt: function (idx) {
return this._subControllers[idx];
},
setControllerAt: function (controller, idx) {
this._subControllers[idx] = controller;
this.incrementProperty('definedControllersCount', 1);
},
objectAtContent: function (idx) {
var content = this.get('content');
return content.objectAt(idx);
},
definedControllersCount: 0,
definedControllers: function () {
return this._subControllers.filter(function (item) {
return !!item;
});
}
});
export default SubRowArray;
|
import Ember from 'ember';
var SubRowArray = Ember.ArrayController.extend({
init: function() {
this._super();
var self = this;
var oldObject = this.get('oldObject');
if (oldObject) {
var content = this.get('content');
var oldControllers = oldObject.get('_subControllers');
oldControllers.forEach(function(item) {
if (item) {
var index = content.indexOf(Ember.get(item, 'content'));
self.setControllerAt(item, index);
}
});
}
},
objectAt: function (idx) {
return this._subControllers[idx];
},
setControllerAt: function (controller, idx) {
this._subControllers[idx] = controller;
this.incrementProperty('definedControllersCount', 1);
},
objectAtContent: function (idx) {
var content = this.get('content');
return content.objectAt(idx);
},
definedControllersCount: 0,
definedControllers: function () {
return this._subControllers.filter(function (item) {
return !!item;
});
}
});
export default SubRowArray;
|
Fix ember test and remove bind syntax
|
Fix ember test and remove bind syntax
|
JavaScript
|
bsd-3-clause
|
Gaurav0/ember-table,Gaurav0/ember-table,Cuiyansong/ember-table,nomadop/ember-table,nomadop/ember-table,hedgeserv/ember-table,hedgeserv/ember-table,phoebusliang/ember-table,Cuiyansong/ember-table,phoebusliang/ember-table
|
ab85db461e34bae17b7510204bc405736af26e05
|
app/soc/content/js/datetimepicker-090825.js
|
app/soc/content/js/datetimepicker-090825.js
|
jQuery(
function () {
jQuery('.datetime-pick').datetimepicker();
jQuery('.date-pick').datetimepicker({
'pickDateOnly': true,
'defaultDate': new Date('01/01/1974'),
'timeFormat': '',
'yearRange': '1900:2008'
});
}
);
|
jQuery(
function () {
var cur_year = new Date().getFullYear();
jQuery('.datetime-pick').datetimepicker();
jQuery('.date-pick').datetimepicker({
'pickDateOnly': true,
'defaultDate': new Date('01/01/1974'),
'timeFormat': '',
'yearRange': '1900:' + (cur_year + 1)
});
}
);
|
Fix the date picker to show the year till the current year plus one.
|
Fix the date picker to show the year till the current year plus one.
--HG--
extra : rebase_source : 251155a2af486272154e6eb5e993859fc4fd0650
|
JavaScript
|
apache-2.0
|
SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange
|
b4d0577e3734b979a204b44989ec615191b7b632
|
test/serialization_test.js
|
test/serialization_test.js
|
suite('serialization', function () {
setup(function () {
var documents = [{
id: 'a',
title: 'Mr. Green kills Colonel Mustard',
body: 'Mr. Green killed Colonel Mustard in the study with the candlestick. Mr. Green is not a very nice fellow.',
wordCount: 19
},{
id: 'b',
title: 'Plumb waters plant',
body: 'Professor Plumb has a green plant in his study',
wordCount: 9
},{
id: 'c',
title: 'Scarlett helps Professor',
body: 'Miss Scarlett watered Professor Plumbs green plant while he was away from his office last week.',
wordCount: 16
}]
this.idx = lunr(function () {
this.ref('id')
this.field('title')
this.field('body')
documents.forEach(function (document) {
this.add(document)
}, this)
})
this.serializedIdx = JSON.stringify(this.idx)
this.loadedIdx = lunr.Index.load(JSON.parse(this.serializedIdx))
})
test('search', function () {
var idxResults = this.idx.search('green'),
serializedResults = this.loadedIdx.search('green')
assert.deepEqual(idxResults, serializedResults)
})
})
|
suite('serialization', function () {
setup(function () {
var documents = [{
id: 'a',
title: 'Mr. Green kills Colonel Mustard',
body: 'Mr. Green killed Colonel Mustard in the study with the candlestick. Mr. Green is not a very nice fellow.',
wordCount: 19
},{
id: 'b',
title: 'Plumb waters plant',
body: 'Professor Plumb has a green plant in his study',
wordCount: 9
},{
id: 'c',
title: 'Scarlett helps Professor',
body: 'Miss Scarlett watered Professor Plumbs green plant while he was away from his office last week.',
wordCount: 16
},{
id: 'd',
title: 'All about JavaScript',
body: 'JavaScript objects have a special __proto__ property',
wordCount: 7
}]
this.idx = lunr(function () {
this.ref('id')
this.field('title')
this.field('body')
documents.forEach(function (document) {
this.add(document)
}, this)
})
this.serializedIdx = JSON.stringify(this.idx)
this.loadedIdx = lunr.Index.load(JSON.parse(this.serializedIdx))
})
test('search', function () {
var idxResults = this.idx.search('green'),
serializedResults = this.loadedIdx.search('green')
assert.deepEqual(idxResults, serializedResults)
})
test('__proto__ double serialization', function () {
var doubleLoadedIdx = lunr.Index.load(JSON.parse(JSON.stringify(this.loadedIdx))),
idxResults = this.idx.search('__proto__'),
doubleSerializedResults = doubleLoadedIdx.search('__proto__')
assert.deepEqual(idxResults, doubleSerializedResults)
})
})
|
Test that __proto__ is indexed across two serializations
|
Test that __proto__ is indexed across two serializations
I found while using lunr that __proto__ can slip through the
serialization process if you're serializing an index that was
itself loaded from a serialized index - it might not be a bad idea
to make sure that serializing an index loaded from a JSON blob
serializes to the exact same JSON blob (well, forgiving things like
a change in the order of the keys)
|
JavaScript
|
mit
|
olivernn/lunr.js,olivernn/lunr.js,olivernn/lunr.js
|
fbed3b71609ec1354bf5140d2bc3d28681d54709
|
redirectToUpToDateDocumentation.user.js
|
redirectToUpToDateDocumentation.user.js
|
// ==UserScript==
// @name Redirect to up to date documentation
// @namespace sieradzki.it
// @description Detects if currently viewed online documentation page is the most recent version available, and if not, redirects user to the latest version.
// @version 1.0.0
// @match *://*/*
// ==/UserScript==
(function () {
'use strict';
var DocumentationRedirect = function () {
};
DocumentationRedirect.prototype.ifPageExists = function (url, callback) {
var request = new XMLHttpRequest();
request.open('HEAD', url, true);
request.timeout = 15000; // 15 seconds
request.onload = function () {
if (request.status < 400) {
callback();
}
};
request.send();
};
window.DocumentationRedirect = new DocumentationRedirect();
})();
|
// ==UserScript==
// @name Redirect to up to date documentation
// @namespace sieradzki.it
// @description Detects if currently viewed online documentation page is the most recent version available, and if not, redirects user to the latest version.
// @version 1.0.0
// @match *://docs.oracle.com/javase/*
// ==/UserScript==
(function () {
'use strict';
var documentations = {
javaSE: {
currentVersion: '8',
isOutdatedDocumentationPage: function (url) {
var matches = url.match(/^http(s)?:\/\/docs\.oracle\.com\/javase\/([0-9\.]+)\/docs\/api\//);
return matches !== null && matches[2] !== this.currentVersion;
},
rewriteUrl: function (url) {
return url.replace(/\/javase\/([0-9\.]+)\/docs\/api\//, '/javase/'+ this.currentVersion + '/docs/api/');
}
}
};
var DocumentationRedirect = function () {
for (var key in documentations) {
if (documentations[key].isOutdatedDocumentationPage(window.location.href)) {
var rewrittenUrl = documentations[key].rewriteUrl(window.location.href);
this.ifPageExists(rewrittenUrl, function (url) {
window.location.replace(url);
});
break;
}
}
};
DocumentationRedirect.prototype.ifPageExists = function (url, callback) {
var request = new XMLHttpRequest();
request.open('HEAD', url, true);
request.timeout = 15000; // 15 seconds
request.onload = function () {
if (request.status < 400) {
callback(url);
}
};
request.send();
};
window.DocumentationRedirect = new DocumentationRedirect();
})();
|
Add working redirection for Java SE documentation
|
Add working redirection for Java SE documentation
|
JavaScript
|
mit
|
kuc/Redirect-to-up-to-date-documentation
|
4c8392797d795261187a29d84f714cf9b116fcbc
|
client/components/ImageUpload.js
|
client/components/ImageUpload.js
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import actions from '../actions/index.js';
import { fetchFPKey } from '../utils/utils';
const filepicker = require('filepicker-js');
import '../scss/_createRecipe.scss';
class ImageUpload extends Component {
render() {
const { recipe, uploadPicture } = this.props;
return (
<div>
<button
className="btn btn-add"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
uploadPicture(recipe);
}}>Add Pics</button>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
recipe: state.recipe,
};
};
const mapDispatchToProps = (dispatch) => {
return {
uploadPicture: (recipe) => {
fetchFPKey((key) => {
filepicker.setKey(key);
filepicker.pick(
{
mimetype: 'image/*',
container: 'window',
},
(data) => {
const newSet = { images: recipe.images };
newSet.images.push(data.url);
dispatch(actions.editRecipe(newSet));
},
(error) => console.log(error)
);
});
},
};
};
export default connect(mapStateToProps, mapDispatchToProps)(ImageUpload);
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import actions from '../actions/index.js';
import { fetchFPKey } from '../utils/utils';
const filepicker = require('filepicker-js');
// import '../scss/_createRecipe.scss';
class ImageUpload extends Component {
render() {
const { recipe, uploadPicture } = this.props;
return (
<button
className="btn btn-default"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
uploadPicture(recipe);
}}>Upload</button>
);
}
}
const mapStateToProps = (state) => {
return {
recipe: state.recipe,
};
};
const mapDispatchToProps = (dispatch) => {
return {
uploadPicture: (recipe) => {
fetchFPKey((key) => {
filepicker.setKey(key);
filepicker.pick(
{
mimetype: 'image/*',
container: 'window',
},
(data) => {
const newSet = { images: recipe.images };
newSet.images.push(data.url);
dispatch(actions.editRecipe(newSet));
},
(error) => console.log(error)
);
});
},
};
};
export default connect(mapStateToProps, mapDispatchToProps)(ImageUpload);
|
Update image upload button styling
|
Update image upload button styling
|
JavaScript
|
mit
|
forkful/forkful,forkful/forkful,rompingstalactite/rompingstalactite,rompingstalactite/rompingstalactite,rompingstalactite/rompingstalactite,forkful/forkful
|
5aa417475b32f75560c994fb7cff850e7663d4ca
|
static/script/user/view.js
|
static/script/user/view.js
|
$( document ).ready( function() {
function showUploadedImage( source ) {
$( "#userImage" ).attr( "src", source );
}
$( "#image-form" ).submit( function() {
var image = document.getElementById( "image" ).files[ 0 ];
var token = $( "input[type=hidden]" ).val();
var formdata = new FormData();
var reader = new FileReader();
$( "#imageSubmit" ).hide();
$( "#uploading" ).show();
reader.onloadend = function ( e ) {
showUploadedImage( e.target.result );
}
reader.readAsDataURL( image );
formdata.append( "image", image );
formdata.append( "token", token );
$.ajax( {
url: "image/create",
type: "POST",
data: formdata,
cache: false,
dataType: "json",
processData: false,
contentType: false,
success: function( res ) {
$( "#imageSubmit" ).show();
$( "#uploading" ).hide();
},
error: function( res ) {
console.log( res );
$( "#imageSubmit" ).show();
$( "#uploading" ).hide();
}
} );
return false;
} );
} );
|
$( document ).ready( function() {
function showUploadedImage( source ) {
$( "#userImage" ).attr( "src", source );
}
$( "#image-form" ).submit( function() {
var image = document.getElementById( "image" ).files[ 0 ];
var token = $( "input[type=hidden]" ).val();
var formdata = new FormData();
var reader = new FileReader();
$( "#imageSubmit" ).hide();
$( "#uploading" ).show();
reader.onloadend = function ( e ) {
showUploadedImage( e.target.result );
}
reader.readAsDataURL( image );
formdata.append( "image", image );
formdata.append( "token", token );
$.ajax( {
url: "image/create",
type: "POST",
data: formdata,
cache: false,
dataType: false,
processData: false,
contentType: false,
success: function( res ) {
$( "#imageSubmit" ).show();
$( "#uploading" ).hide();
},
error: function( res ) {
$( "#imageSubmit" ).show();
$( "#uploading" ).hide();
}
} );
return false;
} );
} );
|
Make it not expect json
|
Make it not expect json
|
JavaScript
|
mit
|
VitSalis/endofcodes,VitSalis/endofcodes,VitSalis/endofcodes,dionyziz/endofcodes,dionyziz/endofcodes,dionyziz/endofcodes,VitSalis/endofcodes
|
3a8ebb82e964b2deadfe5f216e6a54c0a847f482
|
both/collections/groups.js
|
both/collections/groups.js
|
Groups = new Mongo.Collection('groups');
var GroupsSchema = new SimpleSchema({
name: {
type: String
}
});
// Add i18n tags
GroupsSchema.i18n("groups");
Groups.attachSchema(GroupsSchema);
Groups.helpers({
'homes': function () {
// Get group ID
var groupId = this._id;
// Get all homes assigned to group
var homes = Homes.find({'groupId': groupId}).fetch();
return homes;
}
});
Groups.allow({
insert: function () {
return true;
}
});
|
Groups = new Mongo.Collection('groups');
var GroupsSchema = new SimpleSchema({
name: {
type: String
}
});
// Add i18n tags
GroupsSchema.i18n("groups");
Groups.attachSchema(GroupsSchema);
Groups.helpers({
'homes': function () {
// Get group ID
var groupId = this._id;
// Get all homes assigned to group
var homes = Homes.find({'groupId': groupId}).fetch();
return homes;
}
});
Groups.allow({
insert () {
// Get user ID
const userId = Meteor.userId();
// Check if user is administrator
const userIsAdmin = Roles.userIsInRole(userId, ['admin']);
if (userIsAdmin) {
// admin user can insert
return true;
}
},
update () {
// Get user ID
const userId = Meteor.userId();
// Check if user is administrator
const userIsAdmin = Roles.userIsInRole(userId, ['admin']);
if (userIsAdmin) {
// admin user can update
return true;
}
}
});
|
Add update allow rule; refactor insert rule
|
Add update allow rule; refactor insert rule
|
JavaScript
|
agpl-3.0
|
GeriLife/wellbeing,brylie/juhani-wellbeing,GeriLife/wellbeing,brylie/juhani-wellbeing,GeriLife/wellbeing,GeriLife/wellbeing,brylie/juhani-wellbeing,brylie/juhani-wellbeing
|
be716adc76382618e44836f17b37a76a380b2094
|
src/utils/hotfixes/DisableTextSelection.js
|
src/utils/hotfixes/DisableTextSelection.js
|
/**
* Created by tom on 08/07/16.
*/
let location = window.location;
let isWebsite = location.protocol.indexOf('http') !== -1 && location.host.indexOf('localhost') === -1;
if(!isWebsite) {
/* Source: https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule */
var styleElement = document.createElement('style'),
styleSheet;
/* Append style element to head */
document.head.appendChild(styleElement);
/* Grab style sheet */
styleSheet = styleElement.sheet;
styleSheet.insertRule('*{-webkit-touch-callout: none; -webkit-user-select: none; -moz-user-select: none; -o-user-select: none; user-select: none;}', 0);
}
|
/**
* Created by tom on 08/07/16.
*/
var currentLocation = window.location;
var isWebsite = currentLocation.protocol.indexOf('http') !== -1 && currentLocation.host.indexOf('localhost') === -1;
if(!isWebsite) {
/* Source: https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule */
var styleElement = document.createElement('style'),
styleSheet;
/* Append style element to head */
document.head.appendChild(styleElement);
console.log("Appending");
/* Grab style sheet */
styleSheet = styleElement.sheet;
styleSheet.insertRule('*{-webkit-touch-callout: none; -webkit-user-select: none; -moz-user-select: none; -o-user-select: none; user-select: none;}', 0);
}
|
Patch hot fix to work on mobile
|
Patch hot fix to work on mobile
|
JavaScript
|
mit
|
Bizboard/arva-mvc
|
7ce1ab4d5b06b93e73276638e9a91086bb54463a
|
public/js/custom.layout.js
|
public/js/custom.layout.js
|
// Midas Server. Copyright Kitware SAS. Licensed under the Apache License 2.0.
$(document).ready(function () {
'use strict';
var hideDownloadsForAnon = function () {
if (json.global.logged !== "1") {
$('.downloadObject').hide();
}
};
// Go to the landing page.
$('div.HeaderLogo').unbind('click').click(function () {
window.location = json.global.webroot;
});
// Remove download links if the user is not logged into the system.
hideDownloadsForAnon();
midas.registerCallback('CALLBACK_CORE_RESOURCE_HIGHLIGHTED',
'rsnabranding', hideDownloadsForAnon);
// Change upload button to "Request Upload"
$('.uploadFile-top')
.empty()
.unbind()
.html("<div style=\"color: white; font-size: 14pt; padding-top: 2px;\">Request Upload</div>")
.click(function (evt) {
if (evt.originalEvent) {
window.location = "https://www.rsna.org/QIDW-Contributor-Request/";
}
});
// Hide the users and feed links
$('#menuUsers').hide();
$('#menuFeed').hide();
});
|
// Midas Server. Copyright Kitware SAS. Licensed under the Apache License 2.0.
$(document).ready(function () {
'use strict';
var hideDownloadsForAnon = function () {
if (json.global.logged !== "1") {
$('.downloadObject').hide();
}
};
// Go to the landing page.
$('div.HeaderLogo').unbind('click').click(function () {
window.location = json.global.webroot;
});
// Remove download links if the user is not logged into the system.
hideDownloadsForAnon();
midas.registerCallback('CALLBACK_CORE_RESOURCE_HIGHLIGHTED',
'rsnabranding', hideDownloadsForAnon);
// Change upload button to "Request Upload"
$('.uploadFile-top')
.empty()
.unbind()
.html("<div style=\"color: white; font-size: 14pt; padding-top: 2px;\">Request Upload</div>")
.click(function (evt) {
if (evt.originalEvent) {
window.location = "https://www.rsna.org/QIDW-Contributor-Request/";
}
});
// Hide the users and feed links
$('#menuUsers').hide();
$('#menuFeed').hide();
// Hide user deletion for non admins
$('#userDeleteActionNonAdmin').hide();
});
|
Hide user deletion for non-admins.
|
Hide user deletion for non-admins.
|
JavaScript
|
apache-2.0
|
midasplatform/rsnabranding,midasplatform/rsnabranding,midasplatform/rsnabranding
|
b8142700dbe5c9f4031c866cd6ac2d4dba2c55ee
|
app/js/models/key_pair.js
|
app/js/models/key_pair.js
|
(function(bitcoinWorker, Models) {
function KeyPair() {
self = this;
self.isGenerated = false;
// self.bitcoin_worker = new Worker('/js/workers/bitcoin_worker.js');
// self.bitcoin_worker.postMessage();
// self.bitcoin_worker.currentMessageId = 0;
// self.bitcoin_worker.callbacks = {};
// self.bitcoin_worker.onmessage = function(e) {
// var message = e.data;
// self.bitcoin_worker.callbacks[message.id].apply(null, [message.result]);
// delete self.bitcoin_worker.callbacks[message.id];
// };
// self.bitcoin_worker.async = function(functionName, params, hollaback) {
// var message = {
// id: self.bitcoin_worker.currentMessageId,
// functionName: functionName,
// params: params,
// };
// self.bitcoin_worker.callbacks[message.id] = hollaback;
// self.bitcoin_worker.postMessage(message);
// self.bitcoin_worker.currentMessageId++;
// };
}
KeyPair.prototype.generate = function(password, hollaback) {
var self = this;
var params = [
Models.entropy.randomWords(32),
password
];
bitcoinWorker.async("seedGenerateAndEncryptKeys", params, function(keyPair) {
self.isGenerated = true;
self.encryptedPrivateKeyExponent = keyPair.encryptedPrivateKeyExponent;
self.publicKeyX = keyPair.publicKeyX;
self.publicKeyY = keyPair.publicKeyY;
// self.bitcoinAddress = keyPair.bitcoinAddress;
self.bitcoinAddress = "1GyqJhgVYkjBgEy8wf2iApwx4EvU3LvEtR";
if (typeof hollaback === "function") {
hollaback(keyPair);
}
self.trigger('keyPair.generate', keyPair);
});
};
MicroEvent.mixin(KeyPair);
Models.keyPair = new KeyPair();
})(CoinPocketApp.Models.bitcoinWorker, CoinPocketApp.Models);
|
(function(bitcoinWorker, Models) {
function KeyPair() {
self = this;
self.isGenerated = false;
}
KeyPair.prototype.generate = function(password, hollaback) {
var self = this;
var params = [
Models.entropy.randomWords(32),
password
];
bitcoinWorker.async("seedGenerateAndEncryptKeys", params, function(keyPair) {
self.isGenerated = true;
self.encryptedPrivateKeyExponent = keyPair.encryptedPrivateKeyExponent;
self.publicKeyX = keyPair.publicKeyX;
self.publicKeyY = keyPair.publicKeyY;
self.bitcoinAddress = keyPair.bitcoinAddress;
if (typeof hollaback === "function") {
hollaback(keyPair);
}
self.trigger('keyPair.generate', keyPair);
});
};
MicroEvent.mixin(KeyPair);
Models.keyPair = new KeyPair();
})(CoinPocketApp.Models.bitcoinWorker, CoinPocketApp.Models);
|
Clean up and remove stub
|
Clean up and remove stub
|
JavaScript
|
mit
|
MrBluePotato/Dogepocket,enriquez/coinpocketapp.com,MrBluePotato/Dogepocket,enriquez/coinpocketapp.com,enriquez/coinpocketapp.com
|
d4fe86d1e075e35c7e4a0181c12b147f22f0b418
|
GraphiQL/webpack.config.js
|
GraphiQL/webpack.config.js
|
const path = require("path");
module.exports = {
entry: "./src/index.js",
output: {
filename: "bundle.js",
path: path.resolve(__dirname, "dist")
},
module: {
rules: [
{
test: /\.css$/,
use: ["css-loader", "style-loader"]
}
]
}
};
|
const path = require("path");
module.exports = {
entry: "./src/index.js",
output: {
filename: "bundle.js",
path: path.resolve(__dirname, "dist")
},
module: {
rules: [
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
}
]
}
};
|
Correct the order of css loaders.
|
Correct the order of css loaders.
|
JavaScript
|
mit
|
dadish/ProcessGraphQL,dadish/ProcessGraphQL
|
edd3ee4cbe2ad7f0ac3a3b975a4f9c2d573ce013
|
tasks-gulp/config/watch.js
|
tasks-gulp/config/watch.js
|
/**
* Run predefined tasks whenever watched file patterns are added, changed or deleted.
*
* ---------------------------------------------------------------
*
* Watch for changes on
* - files in the `assets` folder
* - the `tasks/pipeline.js` file
* and re-run the appropriate tasks.
*
*
*/
module.exports = function(gulp, plugins, growl) {
var server = plugins.livereload();
gulp.task('watch:api', function() {
// Watch Style files
return gulp.watch('api/**/*', ['syncAssets'])
.on('change', function(file) {
server.changed(file.path);
});
});
gulp.task('watch:assets', function() {
// Watch assets
return gulp.watch(['assets/**/*', 'tasks/pipeline.js'], ['syncAssets'])
.on('change', function(file) {
server.changed(file.path);
});
});
};
|
/**
* Run predefined tasks whenever watched file patterns are added, changed or deleted.
*
* ---------------------------------------------------------------
*
* Watch for changes on
* - files in the `assets` folder
* - the `tasks/pipeline.js` file
* and re-run the appropriate tasks.
*
*
*/
var server = require('gulp-livereload');
module.exports = function(gulp, plugins, growl) {
gulp.task('watch:api', function() {
// Watch Style files
return gulp.watch('api/**/*', ['syncAssets'])
.on('change', function(file) {
server.changed(file.path);
});
});
gulp.task('watch:assets', function() {
// Watch assets
return gulp.watch(['assets/**/*', 'tasks/pipeline.js'], ['syncAssets'])
.on('change', function(file) {
server.changed(file.path);
});
});
};
|
Change to prevent livereload from dying on certain file changes.
|
Change to prevent livereload from dying on certain file changes.
|
JavaScript
|
mit
|
JoshDobbin/CrispyAdmin,JoshDobbin/CrispyAdmin,JoshDobbin/CrispyAdmin
|
d44749756d41329802e332658105640aa5aa2ea8
|
app/assets/javascripts/blogelator/routes/posts_new_route.js
|
app/assets/javascripts/blogelator/routes/posts_new_route.js
|
(function() {
"use strict";
App.PostsNewRoute = Ember.Route.extend({
actions: {
willTransition: function(transition) {
var record = this.get('controller.content');
// Allow transition if nothing is entered
if (Ember.isEmpty(record.get('title')) &&
Ember.isEmpty(record.get('bodyMarkdown'))
) {
return true;
}
// Confirm transition if there are unsaved changes
if (record.get('isNew')) {
if (confirm("Are you sure you want to lose unsaved changes?")) {
record.deleteRecord();
return true;
} else {
transition.abort();
}
} else {
if (record.get('isDirty')) {
if (confirm("Are you sure you want to lose unsaved changes?")) {
record.rollback();
return true;
} else {
transition.abort();
}
} else {
return true;
}
}
}
},
model: function() {
return App.Post.createRecord();
},
renderTemplate: function() {
this.render();
this.render('posts/_form_action_bar', {
into: 'application',
outlet: 'footer'
});
}
});
})();
|
(function() {
"use strict";
App.PostsNewRoute = Ember.Route.extend({
actions: {
willTransition: function(transition) {
var record = this.get('controller.content');
// Allow transition if nothing is entered
if (Ember.isEmpty(record.get('title')) &&
Ember.isEmpty(record.get('bodyMarkdown'))
) {
record.destroyRecord();
return true;
}
// Confirm transition if there are unsaved changes
if (record.get('isNew')) {
if (confirm("Are you sure you want to lose unsaved changes?")) {
record.destroyRecord();
return true;
} else {
transition.abort();
}
} else {
if (record.get('isDirty')) {
if (confirm("Are you sure you want to lose unsaved changes?")) {
record.rollback();
return true;
} else {
transition.abort();
}
} else {
return true;
}
}
}
},
model: function() {
return this.store.createRecord('post');
},
renderTemplate: function() {
this.render();
this.render('posts/_form_action_bar', {
into: 'application',
outlet: 'footer'
});
}
});
})();
|
Fix new route after new ember-data
|
Fix new route after new ember-data
|
JavaScript
|
mit
|
codelation/blogelator,codelation/blogelator,codelation/blogelator
|
d4ec5ba0c60c0ab81f7b8945bbafff578e59ff20
|
app/scripts.babel/contentscript.js
|
app/scripts.babel/contentscript.js
|
'use strict';
console.log('\'Allo \'Allo! Content script');
// https://gist.github.com/dkniffin/b6f5dd4e1bde716e7b32#gistcomment-1980578
function toggle_visibility(data_id) {
var matches = document.querySelectorAll(data_id);
[].forEach.call(matches, function(e) {
if(e.style.display == 'none') {
e.style.display = 'table-cell';
} else {
e.style.display = 'none';
}
});
}
window.addEventListener ('load', myMain, false);
function myMain (evt) {
var jsInitChecktimer = setInterval (checkForDomReady, 111);
function checkForDomReady () {
var selector = jQuery('#ghx-column-headers > li.ghx-column');
if (selector) {
selector.append(function() {
return jQuery('<a href="#" class="column-header-hider"><i class="aui-icon aui-icon-small aui-iconfont-remove-label ghx-iconfont"></i></a>')
.click(function() {
var col = jQuery(this).parent().data('id');
toggle_visibility('[data-id="'+col+'"]');
toggle_visibility('[data-column-id="'+col+'"]');
});
});
clearInterval(jsInitChecktimer);
}
}
}
|
'use strict';
console.log('\'Allo \'Allo! Content script');
// https://gist.github.com/dkniffin/b6f5dd4e1bde716e7b32#gistcomment-1980578
function toggle_visibility(data_id) {
var matches = document.querySelectorAll(data_id);
[].forEach.call(matches, function(e) {
if(e.style.display == 'none') {
e.style.display = 'table-cell';
} else {
e.style.display = 'none';
}
});
}
window.addEventListener ('load', myMain, false);
function myMain (evt) {
var jsInitChecktimer = setInterval (checkForDomReady, 111);
function checkForDomReady () {
var selector = jQuery('#ghx-column-headers > li.ghx-column');
if (selector) {
selector.append(function() {
return jQuery('<a href="#" class="column-header-hider"><i class="aui-icon aui-icon-small aui-iconfont-remove-label ghx-iconfont"></i></a>')
.click(function() {
var col = jQuery(this).parent().data('id');
toggle_visibility('[data-id="'+col+'"]');
toggle_visibility('[data-column-id="'+col+'"]');
});
});
clearInterval(jsInitChecktimer);
}
var somePadding = jQuery('.ghx-wrap-issue');
if(somePadding){
somePadding.css('padding-top','20px');
}
}
}
|
Add CSS for moving cards down a little
|
Add CSS for moving cards down a little
|
JavaScript
|
mit
|
GabLeRoux/hide-jira-board-columns,GabLeRoux/hide-jira-board-columns
|
7ed647f025681828dee8295b3a0976354f3f2162
|
configs/grunt/mochaTest.js
|
configs/grunt/mochaTest.js
|
module.exports = {
options: { reporter: 'spec' },
all: { src: 'test/*-test.js' },
app: { src: 'test/app-test.js' },
node: { src: 'test/node-test.js' },
nodeServer: { src: 'test/node-server-test.js' }
};
|
module.exports = {
options: { reporter: 'spec' },
all: {
src: [
'test/app-test.js',
'test/node-test.js',
'test/node-server-test.js'
]
},
app: { src: 'test/app-test.js' },
node: { src: 'test/node-test.js' },
nodeServer: { src: 'test/node-server-test.js' }
};
|
Enforce order of tests when running all.
|
Enforce order of tests when running all.
|
JavaScript
|
bsd-2-clause
|
KK578/generator-kk578,KK578/generator-kk578
|
397ed5a09edd16cac35ea6f30173b10841a46c7a
|
gulp/scripts.js
|
gulp/scripts.js
|
'use strict';
var gulp = require('gulp');
var env = require('node-env-file');
env(".env");
var paths = gulp.paths;
var $ = require('gulp-load-plugins')();
gulp.task('scripts', function () {
return gulp.src(paths.src + '/{app,components}/**/*.coffee')
.pipe($.replace('PUSHER_APP_KEY', process.env.PUSHER_APP_KEY))
.pipe($.coffeelint())
.pipe($.coffeelint.reporter())
.pipe($.coffee())
.on('error', function handleError(err) {
console.error(err.toString());
this.emit('end');
})
.pipe(gulp.dest(paths.tmp + '/serve/'))
.pipe($.size())
});
|
'use strict';
var gulp = require('gulp');
var env = require('node-env-file');
try {
env(__dirname + "/.env");
} catch (_error) {
console.log(_error);
}
var paths = gulp.paths;
var $ = require('gulp-load-plugins')();
gulp.task('scripts', function () {
return gulp.src(paths.src + '/{app,components}/**/*.coffee')
.pipe($.replace('PUSHER_APP_KEY', process.env.PUSHER_APP_KEY))
.pipe($.coffeelint())
.pipe($.coffeelint.reporter())
.pipe($.coffee())
.on('error', function handleError(err) {
console.error(err.toString());
this.emit('end');
})
.pipe(gulp.dest(paths.tmp + '/serve/'))
.pipe($.size())
});
|
Allow build with no env file
|
Allow build with no env file
|
JavaScript
|
mit
|
adambutler/geo-pusher,adambutler/geo-pusher,adambutler/geo-pusher
|
3df8a507d11831c60cf0bef33d6e0872ef167117
|
resources/public/common/dataSource.js
|
resources/public/common/dataSource.js
|
var dataSource = function () {
var module = {};
module.load = function (url, callback) {
d3.json(url, function (_, data) {
callback(data);
});
};
module.loadCSV = function (url, callback) {
d3.csv(url, function (_, data) {
callback(data);
});
};
return module;
}();
|
var dataSource = function () {
var module = {};
module.load = function (url, callback) {
d3.json(url, function (error, data) {
if (error) return console.warn(error);
callback(data);
});
};
module.loadCSV = function (url, callback) {
d3.csv(url, function (error, data) {
if (error) return console.warn(error);
callback(data);
});
};
return module;
}();
|
Handle ajax errors, don't show 'no content'
|
Handle ajax errors, don't show 'no content'
|
JavaScript
|
bsd-2-clause
|
cburgmer/buildviz,cburgmer/buildviz,cburgmer/buildviz
|
1e7176484d41769d04d46b2f8877764a87e17851
|
puzzles/99_Bottles/javascript/99bottles.js
|
puzzles/99_Bottles/javascript/99bottles.js
|
let bottles = 99;
while (bottles != 0)
{
console.log(`${bottles} bottles of beer on the wall, ${bottles} bottles of beer.`);
--bottles;
console.log(`Take one down and pass it around, ${bottles} bottles of beer on the wall.`);
}
console.log('No more bottles of beer on the wall, no more bottles of beer.');
console.log('Go to the store and buy some more, 99 bottles of beer on the wall.');
|
let bottles = 99;
while (bottles != 0)
{
if (bottles === 1) {
console.log(`${bottles} bottle of beer on the wall, ${bottles} bottles of beer.`);
} else {
console.log(`${bottles} bottles of beer on the wall, ${bottles} bottles of beer.`);
}
--bottles;
if (bottles === 1) {
console.log(`Take one down and pass it around, ${bottles} bottle of beer on the wall.`);
} else if (bottles === 0) {
console.log(`Take one down and pass it around, no more bottles of beer on the wall.`);
} else {
console.log(`Take one down and pass it around, ${bottles} bottles of beer on the wall.`);
}
}
console.log('No more bottles of beer on the wall, no more bottles of beer.');
console.log('Go to the store and buy some more, 99 bottles of beer on the wall.');
|
Add condition for one bottle
|
Add condition for one bottle
It will now print -
"2 bottles of beer on the wall, 2 bottles of beer.
Take one down and pass it around, 1 bottle of beer on the wall.
1 bottle of beer on the wall, 1 bottle of beer."
instead of -
"2 bottles of beer on the wall, 2 bottles of beer.
Take one down and pass it around, 1 bottle(s) of beer on the wall.
1 bottle(s) of beer on the wall, 1 bottle(s) of beer."
|
JavaScript
|
cc0-1.0
|
ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms
|
d034c23af62b0b007471ce7d178f1878e695243b
|
app/assets/javascripts/delete_open_session.js
|
app/assets/javascripts/delete_open_session.js
|
var deleteOpenSession = function(timeslot_id){
event.preventDefault();
$("#modal_remote").modal('hide');
swal({
title: "Are you sure you wish to cancel?",
text: "This will delete your mentoring timeslot.",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#EF5350",
confirmButtonText: "Yes, cancel this mentoring timeslot.",
cancelButtonText: "No, I've changed my mind.",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm){
if (isConfirm) {
$.ajax({
type: "DELETE",
url: "/api/timeslots/" + timeslot_id
}).done(function(){
swal({
title: "Deleted!",
text: "Your mentoring availabilty has been removed.",
confirmButtonColor: "#66BB6A",
type: "info"
});
$('#tutor-cal').fullCalendar('refetchEvents');
}).fail(function() {
swal({
title: "Oops...",
text: "Something went wrong!",
confirmButtonColor: "#EF5350",
type: "error"
});
});
}
else {
swal({
title: "Cancelled",
text: "Your availabilty is still scheduled.",
confirmButtonColor: "#2196F3",
type: "error"
});
}
});
}
|
var deleteOpenSession = function(timeslot_id){
event.preventDefault();
$("#modal_remote").modal('hide');
swal({
title: "Are you sure you wish to cancel?",
text: "This will delete your mentoring timeslot.",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#EF5350",
confirmButtonText: "Yes, cancel this mentoring timeslot.",
cancelButtonText: "No, I've changed my mind.",
closeOnConfirm: false,
closeOnCancel: true
},
function(isConfirm){
if (isConfirm) {
$.ajax({
type: "DELETE",
url: "/api/timeslots/" + timeslot_id
}).done(function(){
swal({
title: "Deleted!",
text: "Your mentoring availabilty has been removed.",
confirmButtonColor: "#FFFFFF",
showConfirmButton: false,
allowOutsideClick: true,
timer: 1500,
type: "info"
});
$('#tutor-cal').fullCalendar('refetchEvents');
}).fail(function() {
swal({
title: "Oops...",
text: "Something went wrong!",
confirmButtonColor: "#EF5350",
type: "error"
});
});
}
});
}
|
Add timer and remove confirm buttonk, overall cleanup for better ux
|
Add timer and remove confirm buttonk, overall cleanup for better ux
|
JavaScript
|
mit
|
theresaboard/theres-a-board,theresaboard/theres-a-board,theresaboard/theres-a-board
|
99939b68695d1b8b6ff9f765abe7a742c6017845
|
background.js
|
background.js
|
chrome.webRequest.onBeforeSendHeaders.addListener(
function(details) {
details.requestHeaders.push({
name: "X-Molotov-Agent",
value: "{\"app_id\":\"electron_app\",\"app_build\":1,\"app_version_name\":\"0.9.6\",\"type\":\"desktop\",\"os\":\"\",\"os_version\":\"\",\"manufacturer\":\"\",\"serial\":\"\",\"model\":\"\",\"brand\":\"\"}"
});
return {requestHeaders: details.requestHeaders};
},
{
urls: [
"https://fapi.molotov.tv/v2/auth/login"
],
types: ["xmlhttprequest"]
},
["blocking", "requestHeaders"]
);
|
chrome.webRequest.onBeforeSendHeaders.addListener(
function(details) {
details.requestHeaders.push({
name: "X-Molotov-Agent",
value: "{\"app_id\":\"electron_app\",\"app_build\":1,\"app_version_name\":\"0.9.6\",\"type\":\"desktop\",\"os\":\"\",\"os_version\":\"\",\"manufacturer\":\"\",\"serial\":\"\",\"model\":\"\",\"brand\":\"\"}"
});
return {requestHeaders: details.requestHeaders};
},
{
urls: [
"https://fapi.molotov.tv/v2/auth/login",
"https://fapi.molotov.tv/v2/auth/refresh/*"
],
types: ["xmlhttprequest"]
},
["blocking", "requestHeaders"]
);
|
Add "X-Molotov-Agent" header on authentication token refresh requests.
|
Add "X-Molotov-Agent" header on authentication token refresh requests.
|
JavaScript
|
bsd-2-clause
|
jleroy/MoloChrome,jleroy/MoloChrome
|
11cbb36d19865113636b291e207e5dd587bbd1e2
|
deserializers/resource.js
|
deserializers/resource.js
|
'use strict';
var _ = require('lodash');
var P = require('bluebird');
var humps = require('humps');
var Schemas = require('../generators/schemas');
function ResourceDeserializer(model, params) {
var schema = Schemas.schemas[model.collection.name];
function extractAttributes() {
return new P(function (resolve) {
var attributes = params.data.attributes;
attributes._id = params.data.id;
resolve(attributes);
});
}
function extractRelationships() {
return new P(function (resolve) {
var relationships = {};
_.each(schema.fields, function (field) {
if (field.reference && params.data.relationships[field.field]) {
if (params.data.relationships[field.field].data === null) {
// Remove the relationships
relationships[field.field] = null;
} else if (params.data.relationships[field.field].data) {
// Set the relationship
relationships[field.field] = params.data.relationships[field.field]
.data.id;
} // Else ignore the relationship
}
});
resolve(relationships);
});
}
this.perform = function () {
return P.all([extractAttributes(), extractRelationships()])
.spread(function (attributes, relationships) {
return humps.camelizeKeys(_.extend(attributes, relationships));
});
};
}
module.exports = ResourceDeserializer;
|
'use strict';
var _ = require('lodash');
var P = require('bluebird');
var humps = require('humps');
var Schemas = require('../generators/schemas');
function ResourceDeserializer(model, params) {
var schema = Schemas.schemas[model.collection.name];
function extractAttributes() {
return new P(function (resolve) {
var attributes = params.data.attributes;
attributes._id = params.data.id;
resolve(attributes);
});
}
function extractRelationships() {
return new P(function (resolve) {
var relationships = {};
_.each(schema.fields, function (field) {
if (field.reference && params.data.relationships &&
params.data.relationships[field.field]) {
if (params.data.relationships[field.field].data === null) {
// Remove the relationships
relationships[field.field] = null;
} else if (params.data.relationships[field.field].data) {
// Set the relationship
relationships[field.field] = params.data.relationships[field.field]
.data.id;
} // Else ignore the relationship
}
});
resolve(relationships);
});
}
this.perform = function () {
return P.all([extractAttributes(), extractRelationships()])
.spread(function (attributes, relationships) {
return humps.camelizeKeys(_.extend(attributes, relationships));
});
};
}
module.exports = ResourceDeserializer;
|
Fix the deserializer when no relationships is present.
|
Fix the deserializer when no relationships is present.
|
JavaScript
|
mit
|
SeyZ/forest-express-mongoose
|
ba44e3a48b9e383c9d8ad573f920d8f3a665e483
|
src/components/home/HomePage.js
|
src/components/home/HomePage.js
|
import React from 'react';
import GithubAPI from '../../api/githubAPI';
class HomePage extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
showResult: "l"
};
this.invokeGitHubAPI = this.invokeGitHubAPI.bind(this);
}
invokeGitHubAPI(){
GithubAPI.testOctokat().then(testResult => {
let parsedTestResult = testResult.pushedAt.toTimeString();
console.log(testResult);
console.log(parsedTestResult);
this.setState({showResult: parsedTestResult});
}).catch(error => {
throw(error);
});
}
render() {
return (
<div>
<h1>GitHub Status API GUI</h1>
<h3>Open browser console to see JSON data returned from GitHub API</h3>
<div className="row">
<div className="col-sm-3">
<button type="button" className="btn btn-primary" onClick={this.invokeGitHubAPI}>Test GitHub API Call</button>
</div>
</div>
<div className="row">
<div className="col-sm-6">
<span>{this.state.showResult}</span>
</div>
</div>
</div>
);
}
}
export default HomePage;
|
import React from 'react';
import GithubAPI from '../../api/githubAPI';
class HomePage extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
showResult: "NO DATA - Click button above to fetch data."
};
this.invokeGitHubAPI = this.invokeGitHubAPI.bind(this);
}
invokeGitHubAPI(){
GithubAPI.testOctokat().then(testResult => {
let parsedTestResult = testResult.pushedAt.toTimeString();
console.log(testResult);
console.log(parsedTestResult);
this.setState({showResult: parsedTestResult});
}).catch(error => {
throw(error);
});
}
render() {
return (
<div>
<h1>GitHub Status API GUI</h1>
<h3>Open browser console to see JSON data returned from GitHub API</h3>
<div className="row">
<div className="col-sm-3">
<button type="button" className="btn btn-primary" onClick={this.invokeGitHubAPI}>Test GitHub API Call</button>
</div>
</div>
<div className="row">
<div className="col-sm-6">
<span>{this.state.showResult}</span>
</div>
</div>
</div>
);
}
}
export default HomePage;
|
Change initial default showResult value to 'NO DATA' message
|
Change initial default showResult value to 'NO DATA' message
|
JavaScript
|
mit
|
compumike08/GitHub_Status_API_GUI,compumike08/GitHub_Status_API_GUI
|
9f32a721ee065f0a031e766c58a71b74976140f7
|
e2e/ComplexLayout.test.js
|
e2e/ComplexLayout.test.js
|
const Utils = require('./Utils');
const testIDs = require('../playground/src/testIDs');
const { elementByLabel, elementById } = Utils;
describe('complex layout', () => {
beforeEach(async () => {
await device.relaunchApp();
});
test(':ios: shows external component in stack in modal', async () => {
await elementById(testIDs.COMPLEX_LAYOUT_BUTTON).tap();
await elementById(testIDs.EXTERNAL_COMPONENT_IN_STACK).tap();
await expect(elementByLabel('External component in stack')).toBeVisible();
});
test(':ios: shows external component in deep stack in modal', async () => {
await elementById(testIDs.COMPLEX_LAYOUT_BUTTON).tap();
await elementById(testIDs.EXTERNAL_COMPONENT_IN_DEEP_STACK).tap();
await expect(elementByLabel('External component in deep stack')).toBeVisible();
});
});
|
const Utils = require('./Utils');
const testIDs = require('../playground/src/testIDs');
const { elementByLabel, elementById } = Utils;
describe('complex layout', () => {
beforeEach(async () => {
await device.relaunchApp();
});
test('shows external component in stack in modal', async () => {
await elementById(testIDs.COMPLEX_LAYOUT_BUTTON).tap();
await elementById(testIDs.EXTERNAL_COMPONENT_IN_STACK).tap();
await expect(elementByLabel('External component in stack')).toBeVisible();
});
test('shows external component in deep stack in modal', async () => {
await elementById(testIDs.COMPLEX_LAYOUT_BUTTON).tap();
await elementById(testIDs.EXTERNAL_COMPONENT_IN_DEEP_STACK).tap();
await expect(elementByLabel('External component in deep stack')).toBeVisible();
});
});
|
Enable external component e2e on Android
|
Enable external component e2e on Android
|
JavaScript
|
mit
|
ceyhuno/react-native-navigation,wix/react-native-navigation,thanhzusu/react-native-navigation,Jpoliachik/react-native-navigation,3sidedcube/react-native-navigation,ceyhuno/react-native-navigation,ceyhuno/react-native-navigation,chicojasl/react-native-navigation,guyca/react-native-navigation,chicojasl/react-native-navigation,chicojasl/react-native-navigation,Jpoliachik/react-native-navigation,guyca/react-native-navigation,Jpoliachik/react-native-navigation,3sidedcube/react-native-navigation,thanhzusu/react-native-navigation,ceyhuno/react-native-navigation,thanhzusu/react-native-navigation,3sidedcube/react-native-navigation,thanhzusu/react-native-navigation,chicojasl/react-native-navigation,ceyhuno/react-native-navigation,ceyhuno/react-native-navigation,wix/react-native-navigation,chicojasl/react-native-navigation,thanhzusu/react-native-navigation,thanhzusu/react-native-navigation,3sidedcube/react-native-navigation,wix/react-native-navigation,guyca/react-native-navigation,Jpoliachik/react-native-navigation,Jpoliachik/react-native-navigation,wix/react-native-navigation,wix/react-native-navigation,guyca/react-native-navigation,wix/react-native-navigation,chicojasl/react-native-navigation,Jpoliachik/react-native-navigation
|
aee94ef6667fdd0d267a2cd1e718756b1c2bb9de
|
exercises/class_extend/solution/solution.js
|
exercises/class_extend/solution/solution.js
|
'use strict';
class Character {
constructor(x, y) {
this.x = x;
this.y = y;
this.health_ = 100;
}
damage() {
this.health_ -= 10;
}
getHealth() {
return this.health_;
}
toString() {
return "x: " + this.x + " y: " + this.y + " health: " + this.health_;
}
}
class Player extends Character {
constructor(x, y, name) {
super(x, y);
this.name = name;
}
move(dx, dy) {
this.x += dx;
this.y += dy;
}
toString() {
return "name: " + this.name + " " + super.toString();
}
}
var x = process.argv[2];
var y = process.argv[3];
var name = process.argv[4];
var character = new Character(+x, +y);
character.damage();
console.log(character.toString());
var player = new Player(+x, +y, name);
player.damage();
player.move(7, 8);
console.log(player.toString());
|
'use strict';
class Character {
constructor(x, y) {
this.x = x;
this.y = y;
this.health_ = 100;
}
damage() {
this.health_ -= 10;
}
getHealth() {
return this.health_;
}
toString() {
return `x: ${this.x} y: ${this.y} health: ${this.health_}`
}
}
class Player extends Character {
constructor(x, y, name) {
super(x, y);
this.name = name;
}
move(dx, dy) {
this.x += dx;
this.y += dy;
}
toString() {
return `name: ${this.name} ${super.toString()}`;
}
}
var x = process.argv[2];
var y = process.argv[3];
var name = process.argv[4];
var character = new Character(+x, +y);
character.damage();
console.log(character.toString());
var player = new Player(+x, +y, name);
player.damage();
player.move(7, 8);
console.log(player.toString());
|
Use string interpolation in toString functions
|
Use string interpolation in toString functions
|
JavaScript
|
mit
|
yosuke-furukawa/tower-of-babel
|
75aaf57ec8e76f4be3347831693557e9185c4f01
|
frontend/admin/ticket/AdminTicketRevokeController.js
|
frontend/admin/ticket/AdminTicketRevokeController.js
|
angular.module('billett.admin').controller('AdminTicketRevokeController', function ($http, $modalInstance, order, ticket) {
var ctrl = this;
ctrl.order = order;
ctrl.ticket = ticket;
ctrl.revoke = function () {
ctrl.sending = true;
$http.post('api/ticket/' + ticket.id + '/revoke', {
'paymentgroup_id': ctrl.active_paymentgroup.id
}).then(function () {
$modalInstance.close();
}, function () {
alert("Ukjent feil oppsto");
delete ctrl.sending;
});
};
ctrl.cancel = function () {
$modalInstance.dismiss('cancel');
};
});
|
angular.module('billett.admin').controller('AdminTicketRevokeController', function ($http, $modalInstance, order, ticket) {
var ctrl = this;
ctrl.order = order;
ctrl.ticket = ticket;
ctrl.revoke = function () {
ctrl.sending = true;
$http.post('api/ticket/' + ctrl.ticket.id + '/revoke', {
'paymentgroup_id': ctrl.paymentgroup.id
}).then(function () {
$modalInstance.close();
}, function () {
alert("Ukjent feil oppsto");
delete ctrl.sending;
});
};
ctrl.cancel = function () {
$modalInstance.dismiss('cancel');
};
});
|
Fix bug in ticket revoke controller.
|
Fix bug in ticket revoke controller.
|
JavaScript
|
mit
|
blindernuka/billett,blindernuka/billett
|
40e46880557d770952e6081978dac7413dd2cc37
|
server/public/javascripts/frontpage.js
|
server/public/javascripts/frontpage.js
|
//
// Copyright 2014 Ilkka Oksanen <iao@iki.fi>
//
// 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.
//
'use strict';
$(function() {
$('input[name="username"]').focus();
$('#login-form').submit(function() {
$('.login-error').empty();
$.post('/login',
$('#login-form').serialize(),
function(data) {
if (data.success === true) {
$.cookie('ProjectEvergreen', data.userId + '-' + data.secret + '-n', {
path: '/',
expires: new Date(data.expires)
});
window.location.pathname = '/app/';
} else {
$('.login-error').text(data.msg);
}
});
return false;
});
});
|
//
// Copyright 2014 Ilkka Oksanen <iao@iki.fi>
//
// 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.
//
'use strict';
$(function() {
$('input[name="username"]').focus();
$('#login-form').submit(function() {
$('.login-error').empty();
$('input').keypress(function() {
$('.login-error').empty();
});
$.post('/login',
$('#login-form').serialize(),
function(data) {
if (data.success === true) {
$.cookie('ProjectEvergreen', data.userId + '-' + data.secret + '-n', {
path: '/',
expires: new Date(data.expires)
});
window.location.pathname = '/app/';
} else {
$('.login-error').text(data.msg);
$('input[name="username"]').val('').focus();
$('input[name="password"]').val('');
}
});
return false;
});
});
|
Improve login page when wrong password is entered
|
Improve login page when wrong password is entered
|
JavaScript
|
apache-2.0
|
ilkkao/mas,ilkkao/mas,ilkkao/mas,ilkkao/mas
|
1262480306ea633f4a9b4c56e4131113341a896c
|
src/app/shared/api/baseApi.service.js
|
src/app/shared/api/baseApi.service.js
|
export default class BaseApiService {
constructor($http, $log, appConfig, path) {
'ngInject';
this.$http = $http;
this.$log = $log;
this._ = _;
this.host = `${appConfig.host}:3000`;
this.url = `//${this.host}/api/${path}`;
this.$log.info('constructor()', this);
}
create(data) {
this.$log.info('api:create()', data, this);
return this.$http.post(`${this.url}`, data);
}
get(query = '') {
this.$log.info('api:get()', query, this);
return this.$http.get(`${this.url}/${query}`);
}
remove(id) {
this.$log.info('api:remove()', id, this);
return this.$http.delete(`${this.url}/${id}`);
}
update(id, data) {
this.$log.info('api:update()', id, data, this);
return this.$http.post(`${this.url}/${id}`, data);
}
}
|
export default class BaseApiService {
constructor($http, $log, appConfig, path) {
'ngInject';
this.$http = $http;
this.$log = $log;
this._ = _;
this.host = `${appConfig.host}:3000`;
this.path = path;
this.url = `//${this.host}/api/${path}`;
this.$log.info('constructor()', this);
}
create(data) {
this.$log.info('api:create()', data, this);
return this.$http.post(`${this.url}`, data);
}
get(query = '') {
let httpObj = {
method: 'GET',
url: `${this.url}/${query}`,
cache: this.path === 'cards' ? true : false
}
this.$log.info('api:get()', query, this);
return this.$http(httpObj);
}
remove(id) {
this.$log.info('api:remove()', id, this);
return this.$http.delete(`${this.url}/${id}`);
}
update(id, data) {
this.$log.info('api:update()', id, data, this);
return this.$http.post(`${this.url}/${id}`, data);
}
}
|
Enable cache for 'get' API call to /cards
|
Enable cache for 'get' API call to /cards
|
JavaScript
|
unlicense
|
ejwaibel/squarrels,ejwaibel/squarrels
|
4052b15906f82214e20782676479141976bfe9e4
|
src/foam/swift/refines/AbstractDAO.js
|
src/foam/swift/refines/AbstractDAO.js
|
/**
* @license
* Copyright 2017 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
refines: 'foam.dao.AbstractDAO',
methods: [
// Here to finish implementing the interface.
{ name: 'select_' },
{ name: 'put_' },
{ name: 'remove_' },
{ name: 'find_' },
{ name: 'removeAll_' },
],
})
foam.CLASS({
refines: 'foam.dao.DAOProperty',
properties: [
{
name: 'swiftType',
value: 'DAO',
},
],
});
|
/**
* @license
* Copyright 2017 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
refines: 'foam.dao.AbstractDAO',
methods: [
// Here to finish implementing the interface.
{ name: 'select_' },
{ name: 'put_' },
{ name: 'remove_' },
{ name: 'find_' },
{ name: 'removeAll_' },
],
})
foam.CLASS({
refines: 'foam.dao.DAOProperty',
properties: [
{
name: 'swiftType',
expression: function(required) {
return '(DAO & FObject)' + (required ? '' : '?');
},
},
],
});
|
Make swift DAOProperties be of type (DAO & FObject)
|
Make swift DAOProperties be of type (DAO & FObject)
|
JavaScript
|
apache-2.0
|
foam-framework/foam2,jacksonic/vjlofvhjfgm,foam-framework/foam2,jacksonic/vjlofvhjfgm,jacksonic/vjlofvhjfgm,foam-framework/foam2,foam-framework/foam2,foam-framework/foam2
|
5ef9ad42974de745d63fd64b16e9c4709964a270
|
app/client/lib/config.js
|
app/client/lib/config.js
|
// Configure Accounts UI for our specific user schema
import { Accounts } from 'meteor/accounts-base';
Accounts.ui.config({
requestPermissions: {},
extraSignupFields: [{
fieldName: 'username',
fieldLabel: 'Username',
inputType: 'text',
visible: true,
validate: function(value, errorFunction) {
if (!value) {
errorFunction("Please write your username");
return false;
} else {
return true;
}
}
}, {
fieldName: 'first-name',
fieldLabel: 'First name',
inputType: 'text',
visible: true,
validate: function(value, errorFunction) {
if (!value) {
errorFunction("Please write your first name");
return false;
} else {
return true;
}
}
}, {
fieldName: 'last-name',
fieldLabel: 'Last name',
inputType: 'text',
visible: true,
}, {
fieldName: 'terms',
fieldLabel: 'I accept the terms and conditions <span class="compulsory">*</span>',
inputType: 'checkbox',
visible: true,
saveToProfile: false,
validate: function(value, errorFunction) {
if (value) {
return true;
} else {
errorFunction('You must accept the terms and conditions.');
return false;
}
}
}]
});
|
// Configure Accounts UI for our specific user schema
import { Accounts } from 'meteor/accounts-base';
Accounts.ui.config({
forceEmailLowercase: true,
forceUsernameLowercase: true,
requestPermissions: {},
extraSignupFields: [{
fieldName: 'username',
fieldLabel: 'Username',
inputType: 'text',
visible: true,
validate: function(value, errorFunction) {
if (!value) {
errorFunction("Please write your username");
return false;
} else {
return true;
}
}
}, {
fieldName: 'first-name',
fieldLabel: 'First name',
inputType: 'text',
visible: true,
validate: function(value, errorFunction) {
if (!value) {
errorFunction("Please write your first name");
return false;
} else {
return true;
}
}
}, {
fieldName: 'last-name',
fieldLabel: 'Last name',
inputType: 'text',
visible: true,
}, {
fieldName: 'terms',
fieldLabel: 'I accept the terms and conditions <span class="compulsory">*</span>',
inputType: 'checkbox',
visible: true,
saveToProfile: false,
validate: function(value, errorFunction) {
if (value) {
return true;
} else {
errorFunction('You must accept the terms and conditions.');
return false;
}
}
}]
});
|
Fix settings for username and email
|
Fix settings for username and email
|
JavaScript
|
agpl-3.0
|
openp2pdesign/OpenMetaDesign,openp2pdesign/OpenMetaDesign,openp2pdesign/OpenMetaDesign
|
669a5e8b19a97fd63d3288ee0754c3fbca1c65ab
|
app/services/intercom.js
|
app/services/intercom.js
|
import { getWithDefault } from '@ember/object';
import IntercomService from 'ember-intercom-io/services/intercom';
import cfg from '../config/environment';
export default IntercomService.extend({
config: getWithDefault(cfg, 'intercom', {})
});
|
import { get } from '@ember/object';
import IntercomService from 'ember-intercom-io/services/intercom';
import cfg from '../config/environment';
export default IntercomService.extend({
config: get(cfg, 'intercom') ?? {}
});
|
Remove use of deprecated getWithDefault
|
Remove use of deprecated getWithDefault
|
JavaScript
|
mit
|
mike-north/ember-intercom-io,mike-north/ember-intercom-io
|
6a7cb14be69d2776f45f79afd7099398ecede329
|
src/client/modules/lib/knockout-plus.js
|
src/client/modules/lib/knockout-plus.js
|
define([
'knockout',
'knockout-mapping',
'knockout-arraytransforms',
'knockout-validation'
], function(ko) {
return ko;
})
|
define([
'knockout',
'knockout-mapping',
'knockout-arraytransforms',
'knockout-validation'
], function (ko) {
ko.extenders.dirty = function (target, startDirty) {
var cleanValue = ko.observable(ko.mapping.toJSON(target));
var dirtyOverride = ko.observable(ko.utils.unwrapObservable(startDirty));
target.isDirty = ko.computed(function () {
return dirtyOverride() || ko.mapping.toJSON(target) !== cleanValue();
});
target.markClean = function () {
cleanValue(ko.mapping.toJSON(target));
dirtyOverride(false);
};
target.markDirty = function () {
dirtyOverride(true);
};
return target;
};
return ko;
});
|
Add dirty-flag extension for knockout
|
Add dirty-flag extension for knockout
|
JavaScript
|
mit
|
eapearson/kbase-ui,eapearson/kbase-ui,kbase/kbase-ui,eapearson/kbase-ui,kbase/kbase-ui,kbase/kbase-ui,briehl/kbase-ui,briehl/kbase-ui,kbase/kbase-ui,kbase/kbase-ui,briehl/kbase-ui,eapearson/kbase-ui,eapearson/kbase-ui
|
cef546a8bb537e5ca976045f67d372ccddc36f0b
|
js/respuesta.js
|
js/respuesta.js
|
function createMenuItem(parentSelector,menuData){
var menuListItem=document.createElement('li');
$(menuListItem).addClass(menuData.class).appendTo(parentSelector);
var menuLink=document.createElement('a');
$(menuLink).attr({"href":menuData.link}).html(menuData.name);
$(menuLink).appendTo(menuListItem);
}
function generateJSONMenu(url,menuListSelector) {
$.getJSON(url,function(data) {
for(var dataI=0;dataI<data.length;dataI++) {
createMenuItem(menuListSelector,data[dataI]);
}});
}
function init() {
generateJSONMenu('js/menu.json',".main-list");
}
|
function createMenuItem(parentSelector,menuData){
var menuListItem=document.createElement('li');
$(menuListItem).addClass(menuData.class).appendTo(parentSelector);
var menuLink=document.createElement('a');
$(menuLink).attr({"href":menuData.link}).html(menuData.name);
$(menuLink).appendTo(menuListItem);
}
function generateJSONMenu(url,menuListSelector) {
$.getJSON(url,function(data) {
for(var dataI=0;dataI<data.length;dataI++) {
createMenuItem(menuListSelector,data[dataI]);
}});
}
function initialAnimation() {
$("div>div").fadeTo(1,30);
$(".left , .right").animate({"margin-left":0},5000);
}
function init() {
generateJSONMenu('js/menu.json',".main-list");
initialAnimation();
}
|
Add layers animation and fadeIn
|
Add layers animation and fadeIn
|
JavaScript
|
mit
|
edysanchez/test_json
|
15f20685ed79148e5f7273287923f2b97dceef50
|
lib/at-login.js
|
lib/at-login.js
|
'use babel';
import {component} from './polymer-es6';
import _ from 'lodash';
console.log("AT LOGIN");
@component('at-login')
export class AtomTwitchLogin {
static properties() {
return { };
}
ready() {
const query = {
'response_type': 'token',
'client_id': 'akeo37esgle8e0r3w7r4f6fpt7prj21',
'redirect_uri': 'https://paulcbetts.github.io/atom-twitch/oauth.html',
'scope': 'user_read channel_editor channel_commercial channel_subscriptions user_subscriptions chat_login'
};
let queryString = _.map(Object.keys(query), (x) => `${x}=${encodeURIComponent(query[x])}`).join('&');
this.$.login.src = `https://api.twitch.tv/kraken/oauth2/authorize?${queryString}`;
}
}
|
'use babel';
import {component} from './polymer-es6';
import _ from 'lodash';
import url from 'url';
console.log("AT LOGIN");
@component('at-login')
export class AtomTwitchLogin {
static properties() {
return {
accessToken: {
type: String,
notify: true,
readOnly: true,
reflectToAttribute: true
}
};
}
ready() {
const query = {
'response_type': 'token',
'client_id': 'akeo37esgle8e0r3w7r4f6fpt7prj21',
'redirect_uri': 'https://paulcbetts.github.io/atom-twitch/oauth.html',
'scope': 'user_read channel_editor channel_commercial channel_subscriptions user_subscriptions chat_login'
};
let queryString = _.map(Object.keys(query), (x) => `${x}=${encodeURIComponent(query[x])}`).join('&');
this.$.login.preload = require.resolve('./at-login-preload');
this.$.login.src = `https://api.twitch.tv/kraken/oauth2/authorize?${queryString}`;
this.$.login.addEventListener('ipc-message', (e) => {
let query = url.parse(e.args[0]).hash;
let dict = _.reduce(query.slice(1).split('&'), (acc,part) => {
let [k,v] = part.split('=');
acc[decodeURIComponent(k)] = decodeURIComponent(v);
return acc;
}, {});
this._setAccessToken(dict['access_token']);
this.$.login.style.display = 'none';
});
}
}
|
Save off the access token in our property
|
Save off the access token in our property
|
JavaScript
|
mit
|
paulcbetts/atom-twitch,paulcbetts/atom-twitch
|
42318849244779b3513ffd32dc69d54f179a5d55
|
source/assets/js/utils/fef-keycodes.js
|
source/assets/js/utils/fef-keycodes.js
|
export const KEYCODES = {
'enter': 13,
'tab': 9,
'space': 32,
'escape': 27,
'up': 38,
'down': 40
};
|
export const KEYCODES = {
'enter': 13,
'tab': 9,
'space': 32,
'escape': 27,
'up': 38,
'down': 40,
'left': 37,
'right': 39,
'home': 36,
'end': 35
};
|
Add more keycodes used in cms
|
Add more keycodes used in cms
SRFCMSAL-2597
|
JavaScript
|
mit
|
mmz-srf/srf-frontend-framework,mmz-srf/srf-frontend-framework,mmz-srf/srf-frontend-framework,mmz-srf/srf-frontend-framework
|
405e806514889bbcece5cf44266885c7e50615c2
|
phjs-main.js
|
phjs-main.js
|
/* eslint-env phantomjs */
var system = require('system');
var webpage = require('webpage');
var page = webpage.create();
var ua = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) ' +
'AppleWebKit/537.36 (KHTML, like Gecko) ' +
'Chrome/56.0.2924.87 Safari/537.36';
var args = JSON.parse(system.args[1]);
var url = args.url;
var viewSize = args.viewSize;
function complete(msg) {
system.stdout.write(JSON.stringify(msg));
phantom.exit();
}
function uponWindowLoad() {
var render = page.renderBase64('PNG');
var msg = {
status: 'ok',
body: render,
};
complete(msg);
}
function uponPageOpen(status) {
if (status !== 'success') {
var msg = {
status: 'error',
body: status,
};
complete(msg);
return;
}
// Wait an extra second for anything else to load
window.setTimeout(uponWindowLoad, 1000);
}
page.settings.userAgent = ua;
page.viewportSize = viewSize;
page.open(url, uponPageOpen);
|
/* eslint-env phantomjs */
var system = require('system');
var webpage = require('webpage');
var page = webpage.create();
var ua = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) ' +
'AppleWebKit/537.36 (KHTML, like Gecko) ' +
'Chrome/56.0.2924.87 Safari/537.36';
var args = JSON.parse(system.args[1]);
var url = args.url;
var viewSize = args.viewSize;
function complete(msg) {
system.stdout.write(JSON.stringify(msg));
phantom.exit();
}
function renderComplete() {
var render = page.renderBase64('PNG');
var msg = {
status: 'ok',
body: render,
};
complete(msg);
}
function uponPageOpen(status) {
if (status !== 'success') {
var msg = {
status: 'error',
body: status,
};
complete(msg);
return;
}
renderComplete();
}
page.settings.userAgent = ua;
page.viewportSize = viewSize;
page.open(url, uponPageOpen);
|
Remove 1000ms wait for page load
|
Remove 1000ms wait for page load
|
JavaScript
|
mit
|
tkmcc/stylish
|
6650d1b9ee9afa29c5316646292cc1227e975f23
|
src/index.js
|
src/index.js
|
import React from 'react';
import ReactDom from 'react-dom';
import { Route, Router, browserHistory } from 'react-router';
import "./vendor/css/skeleton_css/normalize.css"
import "./vendor/css/skeleton_css/skeleton_css.css"
import Main from './components/Main/Main';
ReactDom.render(
<Router history={browserHistory}>
<Route path="/" component={Main} />
</Router>,
document.getElementById('app'));
|
import React from 'react';
import ReactDom from 'react-dom';
import { Route, Router, browserHistory } from 'react-router';
import "./styles/style.css"
import "./vendor/css/skeleton_css/normalize.css"
import "./vendor/css/skeleton_css/skeleton_css.css"
import Main from './components/Main/Main';
ReactDom.render(
<Router history={browserHistory}>
<Route path="/" component={Main} />
</Router>,
document.getElementById('app'));
|
Set up skeleton and style css
|
Set up skeleton and style css
|
JavaScript
|
mit
|
Decidr/react-decidr,Decidr/react-decidr,Decidr/react-decidr
|
cdd3bbde2eb51db584f67530836a754284de3d7c
|
src/index.js
|
src/index.js
|
import React from 'react';
import ReactDOM from 'react-dom';
import Root from 'components/Root';
import configureStore from './stores';
import createBrowserHistory from 'history/lib/createBrowserHistory';
import initialState from './stores/initial-state';
import {resetAnimation} from './action-creators';
const target = document.getElementById('root');
const store = configureStore(initialState);
store.dispatch(resetAnimation());
const node = <Root routerHistory={createBrowserHistory()} store={store}/>;
ReactDOM.render(node, target);
|
import React from 'react';
import ReactDOM from 'react-dom';
import Root from 'components/Root';
import configureStore from './stores';
// import createBrowserHistory from 'history/lib/createBrowserHistory';
import initialState from './stores/initial-state';
import {resetAnimation} from './action-creators';
const target = document.getElementById('root');
const store = configureStore(initialState);
store.dispatch(resetAnimation());
// const node = <Root routerHistory={createBrowserHistory()} store={store}/>;
const node = <Root store={store}/>;
ReactDOM.render(node, target);
|
Disable browser history for static site
|
Disable browser history for static site
|
JavaScript
|
mit
|
rossta/pathfinder,rossta/pathfinder
|
f4143bc419b4cca0d26bbfde5908043fbe8732be
|
src/index.js
|
src/index.js
|
/**
* 24.05.2017
* TCP Chat using NodeJS
* https://github.com/PatrikValkovic/TCPChat
* Created by patri
*/
'use strict'
const net = require('net')
const log = require('./logger')
const config = require('../config.json')
const GroupManager = require('./groupManager')
const Parser = require('./Parser')
const Client = require('./Client')
if (require.main === module) {
GroupManager.createGroup(config.defaultGroups)
const parser = new Parser()
const server = net.createServer()
server.on('connection', (socket) => {
const client = new Client(socket)
log.info('Client connected')
socket.on('close', () => {
log.info('Socket ended')
client.disconnect()
})
socket.once('data', (name) => {
client.name = name.toString().trim()
socket.write('Welcome to chat, type /help for more help\n')
socket.on('data',(content) => {
parser.parse(client, content.toString())
})
})
socket.on('error', () => {
log.warning('Error with socket')
client.disconnect()
})
socket.write('Please enter your name: ')
})
server.listen(config.port, config.host, () => {
const address = server.address()
log.info(`Server running on ${address.address}:${address.port}`)
})
}
|
/**
* 24.05.2017
* TCP Chat using NodeJS
* https://github.com/PatrikValkovic/TCPChat
* Created by patri
*/
'use strict'
const net = require('net')
const log = require('./logger')
const config = require('../config.json')
const GroupManager = require('./groupManager')
const Parser = require('./Parser')
const Client = require('./Client')
if (require.main === module) {
GroupManager.createGroup(config.defaultGroups)
const parser = new Parser()
const server = net.createServer()
server.on('connection', (socket) => {
const client = new Client(socket)
log.info('Client connected')
socket.on('close', () => {
log.info('Socket ended')
client.disconnect()
})
socket.once('data', (name) => {
let obtainedName = name.toString().trim()
client.name = obtainedName === '' ? 'anonymous' : obtainedName
socket.write('Welcome to chat, type /help for more help\n')
socket.on('data',(content) => {
parser.parse(client, content.toString())
})
})
socket.on('error', () => {
log.warning('Error with socket')
client.disconnect()
})
socket.write('Please enter your name: ')
})
server.listen(config.port, config.host, () => {
const address = server.address()
log.info(`Server running on ${address.address}:${address.port}`)
})
}
|
Set user's name as anonymous if no name is specified
|
Set user's name as anonymous if no name is specified
|
JavaScript
|
mit
|
PatrikValkovic/TCPChat
|
2cb6e1e59632bbce7ead7b78b29c0c4bd5592bb6
|
lib/webpack/vue-loader.config.js
|
lib/webpack/vue-loader.config.js
|
'use strict'
import { defaults } from 'lodash'
import { extractStyles, styleLoader } from './helpers'
export default function ({ isClient }) {
let babelOptions = JSON.stringify(defaults(this.options.build.babel, {
presets: ['vue-app'],
babelrc: false,
cacheDirectory: !!this.dev
}))
// https://github.com/vuejs/vue-loader/blob/master/docs/en/configurations
let config = {
postcss: this.options.build.postcss,
loaders: {
'js': 'babel-loader?' + babelOptions,
'css': styleLoader.call(this, 'css'),
'less': styleLoader.call(this, 'less', 'less-loader'),
'sass': styleLoader.call(this, 'sass', 'sass-loader?indentedSyntax'),
'scss': styleLoader.call(this, 'sass', 'sass-loader?sourceMap'),
'stylus': styleLoader.call(this, 'stylus', 'stylus-loader'),
'styl': styleLoader.call(this, 'stylus', 'stylus-loader')
},
preserveWhitespace: false,
extractCSS: extractStyles.call(this)
}
// Return the config
return config
}
|
'use strict'
import { defaults } from 'lodash'
import { extractStyles, styleLoader } from './helpers'
export default function ({ isClient }) {
let babelOptions = JSON.stringify(defaults(this.options.build.babel, {
presets: ['vue-app'],
babelrc: false,
cacheDirectory: !!this.dev
}))
// https://github.com/vuejs/vue-loader/blob/master/docs/en/configurations
let config = {
postcss: this.options.build.postcss,
loaders: {
'js': 'babel-loader?' + babelOptions,
'css': styleLoader.call(this, 'css'),
'less': styleLoader.call(this, 'less', 'less-loader'),
'sass': styleLoader.call(this, 'sass', 'sass-loader?indentedSyntax&?sourceMap'),
'scss': styleLoader.call(this, 'sass', 'sass-loader?sourceMap'),
'stylus': styleLoader.call(this, 'stylus', 'stylus-loader'),
'styl': styleLoader.call(this, 'stylus', 'stylus-loader')
},
preserveWhitespace: false,
extractCSS: extractStyles.call(this)
}
// Return the config
return config
}
|
Add source map for SASS
|
Add source map for SASS
|
JavaScript
|
mit
|
jfroffice/nuxt.js,mgesmundo/nuxt.js,jfroffice/nuxt.js,mgesmundo/nuxt.js
|
ca68678fc52b5a4b46ed1b8e207a827c6b5c07b8
|
src/store.js
|
src/store.js
|
import {
applyMiddleware,
combineReducers,
compose,
createStore as createReduxStore
} from 'redux'
const makeRootReducer = (reducers, asyncReducers) => {
// Redux + combineReducers always expect at least one reducer, if reducers
// and asyncReducers are empty, we define an useless reducer function
// returning the state
if (!reducers && !asyncReducers) { return (state) => state }
return combineReducers({
...reducers,
...asyncReducers
})
}
export const injectReducer = (store, { key, reducer }) => {
store.asyncReducers[key] = reducer
store.replaceReducer(makeRootReducer(store.reducers, store.asyncReducers))
}
export const createStore = (initialState = {}, reducers = {}, middlewares = {}, enhancers = {}) => {
const store = createReduxStore(
makeRootReducer(reducers),
initialState,
compose(
applyMiddleware(...middlewares),
...enhancers
)
)
store.reducers = reducers
store.asyncReducers = {}
return store
}
|
import {
applyMiddleware,
combineReducers,
compose,
createStore as createReduxStore
} from 'redux'
const makeRootReducer = (reducers, asyncReducers) => {
// Redux + combineReducers always expect at least one reducer, if reducers
// and asyncReducers are empty, we define an useless reducer function
// returning the state
if (!reducers && !asyncReducers) { return (state) => state }
return combineReducers({
...reducers,
...asyncReducers
})
}
export const injectReducer = (store, { key, reducer }) => {
store.asyncReducers[key] = reducer
store.replaceReducer(makeRootReducer(store.reducers, store.asyncReducers))
}
export const createStore = (initialState = {}, reducers = {}, middlewares = {}, enhancers = {}) => {
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose
const store = createReduxStore(
makeRootReducer(reducers),
initialState,
composeEnhancers(
applyMiddleware(...middlewares),
...enhancers
)
)
store.reducers = reducers
store.asyncReducers = {}
return store
}
|
Support for Redux DevTools Extension
|
Support for Redux DevTools Extension
|
JavaScript
|
mit
|
tseho/react-redux-app-container
|
0e0f29f6d7f816cda8caf647abbe20f04d0b4607
|
src/utils.js
|
src/utils.js
|
module.exports = {
// Tools for client side
addStyleSheet: function(url) {
if (document) {
var link = document.createElement("link");
link.type = "text/css";
link.rel = "stylesheet";
link.href = url;
document.getElementsByTagName("head")[0].appendChild(link);
}
},
existsStyleSheet: function(resourceName) {
if (document) {
var styles = document.styleSheets;
for (var i = 0, len = styles.length; i < len; i++) {
if (styles[i].href.endsWith(resourceName + ".css") || styles[i].href.endsWith(resourceName + ".min.css"))
return true;
}
}
return false;
}
}
|
module.exports = {
// Tools for client side
addStyleSheet: function(url) {
if (document) {
var link = document.createElement("link");
link.type = "text/css";
link.rel = "stylesheet";
link.href = url;
document.getElementsByTagName("head")[0].appendChild(link);
}
},
existsStyleSheet: function(resourceName) {
if (document) {
var href, styles = document.styleSheets;
for (var i = 0, len = styles.length; i < len; i++) {
href = styles[i].href; // not all style tags have external reference : some are inline !
if (href && href.indexOf(resourceName) !== -1) {
return true;
}
}
}
return false;
}
}
|
FIX bug on stylesheets without href
|
FIX bug on stylesheets without href
|
JavaScript
|
mit
|
zipang/markdown-bundle,zipang/markdown-bundle
|
a4e460b40855d689c90b570ba66b6280f924b2a4
|
src/utils.js
|
src/utils.js
|
import VNode from 'snabbdom/vnode';
export function createTextVNode(text) {
return VNode(undefined, undefined, undefined, unescape(text));
}
export function transformName(name) {
// Replace -a with A to help camel case style property names.
name = name.replace( /-(\w)/g, function _replace( $1, $2 ) {
return $2.toUpperCase();
});
// Handle properties that start with a -.
const firstChar = name.charAt(0).toLowerCase();
return `${firstChar}${name.substring(1)}`;
}
// Regex for matching HTML entities.
const entityRegex = new RegExp('&[a-z0-9]+;', 'gi')
// Element for setting innerHTML for transforming entities.
const el = document.createElement('div');
function unescape(text) {
return text.replace(entityRegex, (entity) => {
el.innerHTML = entity;
return el.textContent;
});
}
|
import VNode from 'snabbdom/vnode';
export function createTextVNode(text, context) {
return VNode(undefined, undefined, undefined, unescape(text, context));
}
export function transformName(name) {
// Replace -a with A to help camel case style property names.
name = name.replace( /-(\w)/g, function _replace( $1, $2 ) {
return $2.toUpperCase();
});
// Handle properties that start with a -.
const firstChar = name.charAt(0).toLowerCase();
return `${firstChar}${name.substring(1)}`;
}
// Regex for matching HTML entities.
const entityRegex = new RegExp('&[a-z0-9]+;', 'gi')
// Element for setting innerHTML for transforming entities.
let el = null;
function unescape(text, context) {
// Create the element using the context if it doesn't exist.
if (!el) {
el = context.createElement('div');
}
return text.replace(entityRegex, (entity) => {
el.innerHTML = entity;
return el.textContent;
});
}
|
Add a 'context' parameter to util functions, so we don't rely on a global 'document'.
|
Add a 'context' parameter to util functions, so we don't rely on a global 'document'.
|
JavaScript
|
mit
|
appcues/snabbdom-virtualize
|
f9cf1298e8d1e924167648be8279a01488a989d4
|
javascripts/application.js
|
javascripts/application.js
|
$(function () {
VS.init({
remainder : null,
container : $('.visual_search'),
query : '',
unquotable: ['day', 'date'],
callbacks : {
facetMatches: function(callback) {
callback(['day', 'date'])
},
valueMatches: function(facet, searchTerm, callback) {
if (facet == 'day')
callback(['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], { preserveOrder: true })
else if (facet == 'date')
callback([searchTerm])
}
}
})
})
|
$(function () {
var displayDatepicker = function (callback) {
var input = $('.search_facet.is_editing input.search_facet_input')
var removeDatepicker = function () {
input.datepicker("destroy")
}
// Put a selected date into the VS autocomplete and trigger click
var setVisualSearch = function (date) {
removeDatepicker()
callback([date])
$("ul.VS-interface:visible li.ui-menu-item a:first").click()
}
input.datepicker({
dateFormat: 'yy-mm-dd',
onSelect: setVisualSearch,
onClose: removeDatepicker
})
input.datepicker('show')
}
VS.init({
remainder : null,
container : $('.visual_search'),
query : '',
unquotable: ['day', 'date'],
callbacks : {
facetMatches: function(callback) {
callback(['day', 'date'])
},
valueMatches: function(facet, searchTerm, callback) {
if (facet == 'day')
callback(['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], { preserveOrder: true })
else if (facet == 'date')
setTimeout(function () { displayDatepicker(callback) }, 0)
}
}
})
})
|
Integrate UI Datepicker into VisualSearch.js
|
Integrate UI Datepicker into VisualSearch.js
|
JavaScript
|
mit
|
Djo/visualsearch-with-datepicker
|
debc7bf35201daa1e0223c0ab37ee496c635406a
|
app/notes/notes.service.js
|
app/notes/notes.service.js
|
(function() {
angular.module('marvelousnote.notes')
.service('NotesService', NotesService);
NotesService.$inject = ['$http'];
function NotesService($http) {
var service = this;
service.getNotes = function() {
$http.get('https://meganote.herokuapp.com/notes')
.success(function(notes) {
console.log(notes);
});
};
}
})();
|
(function() {
angular.module('marvelousnote.notes')
.service('NotesService', NotesService);
NotesService.$inject = ['$http'];
function NotesService($http) {
var service = this;
service.getNotes = function() {
$http.get('https://meganote.herokuapp.com/notes')
.then(function(res) {
console.log(res.data);
});
};
}
})();
|
Use then instead of success on promise.
|
Use then instead of success on promise.
|
JavaScript
|
mit
|
patriciachunk/MarvelousNote,patriciachunk/MarvelousNote
|
ff7bd17fac5efd1b80d6b36bcbceba9f71b4f154
|
src/index.js
|
src/index.js
|
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
(function() {
var include = function(path) {
document.write('<script src="' + path + '"></script>');
};
include("/chrome/tracing/overlay.js");
include("/chrome/tracing/timeline_model.js");
include("/chrome/tracing/sorted_array_utils.js");
include("/chrome/tracing/timeline.js");
include("/chrome/tracing/timeline_track.js");
include("/chrome/tracing/fast_rect_renderer.js");
include("/chrome/tracing/timeline_view.js");
var timelineView;
function onDOMContentLoaded() {
timelineView = $('timeline-view');
cr.ui.decorate(timelineView, tracing.TimelineView);
chrome.send('ready');
}
function loadTrace(trace) {
if (timelineView == undefined)
throw Error('timelineview is null');
// some old traces were just arrays without an outer object
if (!trace.traceEvents) {
if (trace instanceof Array)
timelineView.traceEvents = trace;
else
throw Error('trace does not have an events array');
} else {
timelineView.traceEvents = trace.traceEvents;
}
return true;
}
window.loadTrace = loadTrace;
document.addEventListener('DOMContentLoaded', onDOMContentLoaded);
})();
|
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
var g_timelineView;
(function() {
var include = function(path) {
document.write('<script src="' + path + '"></script>');
};
include("/chrome/tracing/overlay.js");
include("/chrome/tracing/timeline_model.js");
include("/chrome/tracing/sorted_array_utils.js");
include("/chrome/tracing/timeline.js");
include("/chrome/tracing/timeline_track.js");
include("/chrome/tracing/fast_rect_renderer.js");
include("/chrome/tracing/timeline_view.js");
var timelineView;
function onDOMContentLoaded() {
timelineView = $('timeline-view');
g_timelineView = timelineView;
cr.ui.decorate(timelineView, tracing.TimelineView);
chrome.send('ready');
}
function loadTrace(trace) {
if (timelineView == undefined)
throw Error('timelineview is null');
// some old traces were just arrays without an outer object
if (!trace.traceEvents) {
if (trace instanceof Array)
timelineView.traceEvents = trace;
else
throw Error('trace does not have an events array');
} else {
timelineView.traceEvents = trace.traceEvents;
}
return true;
}
window.loadTrace = loadTrace;
document.addEventListener('DOMContentLoaded', onDOMContentLoaded);
})();
|
Make timeline view a global for debugging.
|
Make timeline view a global for debugging.
|
JavaScript
|
apache-2.0
|
natduca/trace_event_viewer,natduca/trace_event_viewer,natduca/trace_event_viewer
|
4d09b36b71853100eda128b4ef50376c3376cd49
|
src/index.js
|
src/index.js
|
require('dotenv').config()
import {version} from '../package.json'
import path from 'path'
import Koa from 'koa'
import Route from 'koa-route'
import Serve from 'koa-static'
import Octokat from 'octokat'
import Badge from './Badge'
const app = new Koa()
app.context.github = new Octokat({
token: process.env.GITHUB_TOKEN
})
Badge.$app = app.context
Badge.$env = process.env
app.use(Serve(path.join(__dirname, '../public'), {
maxage: 31536000000
}))
app.use(Route.get('/', function * () {
this.body = 'Hireable v' + version
}))
app.use(Route.get('/:user/:repo?', function * show (id, repo) {
yield Badge.show(id, repo).then(src => {
this.redirect(src)
})
}))
app.listen(process.env.APP_PORT)
console.log('Listening on :' + process.env.APP_PORT)
console.log('Visit http://localhost:' + process.env.APP_PORT)
|
require('dotenv').config()
import {version} from '../package.json'
import path from 'path'
import Koa from 'koa'
import Route from 'koa-route'
import Serve from 'koa-static'
import Octokat from 'octokat'
import Badge from './Badge'
const app = new Koa()
app.context.github = new Octokat({
token: process.env.GITHUB_TOKEN
})
Badge.$app = app.context
Badge.$env = process.env
app.use(Serve(path.join(__dirname, '../public'), {
maxage: 31536000000
}))
app.use(Route.get('/', function * () {
this.body = 'Hireable v' + version
}))
app.use(Route.get('/p/:user', function * (user) {
this.redirect('https://github.com/' + user)
}))
app.use(Route.get('/:user/:repo?', function * show (id, repo) {
yield Badge.show(id, repo).then(src => {
this.redirect(src)
})
}))
app.listen(process.env.APP_PORT)
console.log('Listening on :' + process.env.APP_PORT)
console.log('Visit http://localhost:' + process.env.APP_PORT)
|
Add a profile link which allow users to control the redirection
|
Add a profile link which allow users to control the redirection
|
JavaScript
|
mit
|
hiendv/hireable
|
423bd167163010b89a00f871cce83d76f6e52f4e
|
inst/htmlwidgets/sigma.js
|
inst/htmlwidgets/sigma.js
|
HTMLWidgets.widget({
name: "sigma",
type: "output",
initialize: function(el, width, height) {
// create our sigma object and bind it to the element
var sig = new sigma(el.id);
// return it as part of our instance data
return {
sig: sig
};
},
renderValue: function(el, x, instance) {
// parse gexf data
var parser = new DOMParser();
var data = parser.parseFromString(x.data, "application/xml");
// apply settings
for (var name in x.settings)
instance.sig.settings(name, x.settings[name]);
// update the sigma instance
sigma.parsers.gexf(
data, // parsed gexf data
instance.sig, // sigma instance we created in initialize
function() {
// need to call refresh to reflect new settings and data
instance.sig.refresh();
}
);
},
resize: function(el, width, height, instance) {
// forward resize on to sigma renderers
for (var name in instance.sig.renderers)
instance.sig.renderers[name].resize(width, height);
}
});
|
HTMLWidgets.widget({
name: "sigma",
type: "output",
initialize: function(el, width, height) {
// create our sigma object and bind it to the element
// force to use canvas - webgl not rendering opacity
// properly consistently
var sig = new sigma({
renderers: [{
container: document.getElementById(el.id),
type: 'canvas'
}]
});
// return it as part of our instance data
return {
sig: sig
};
},
renderValue: function(el, x, instance) {
// parse gexf data
var parser = new DOMParser();
var data = parser.parseFromString(x.data, "application/xml");
// apply settings
for (var name in x.settings)
instance.sig.settings(name, x.settings[name]);
// update the sigma instance
sigma.parsers.gexf(
data, // parsed gexf data
instance.sig, // sigma instance we created in initialize
function() {
// need to call refresh to reflect new settings and data
instance.sig.refresh();
}
);
},
resize: function(el, width, height, instance) {
// forward resize on to sigma renderers
for (var name in instance.sig.renderers)
instance.sig.renderers[name].resize(width, height);
}
});
|
Fix for opacity issues on browsers
|
Fix for opacity issues on browsers
|
JavaScript
|
mit
|
iankloo/sigma,iankloo/sigma
|
498a81fee3dc30432d25fa79bc455bdeeee08b10
|
tests/unit/serializers/course-test.js
|
tests/unit/serializers/course-test.js
|
import { moduleForModel, test } from 'ember-qunit';
import {a as testgroup} from 'ilios/tests/helpers/test-groups';
moduleForModel('course', 'Unit | Serializer | course ' + testgroup, {
// Specify the other units that are required for this test.
needs: [
'serializer:course',
'model:publish-event',
'model:school',
'model:user',
'model:course',
'model:course-clerkship-type',
'model:session',
'model:offering',
'model:topic',
'model:objective',
'model:cohort',
'model:mesh-descriptor',
'model:course-learning-material'
]
});
test('it serializes records', function(assert) {
var record = this.subject();
var serializedRecord = record.serialize();
assert.ok(serializedRecord);
});
|
import { moduleForModel, test } from 'ember-qunit';
import {a as testgroup} from 'ilios/tests/helpers/test-groups';
moduleForModel('course', 'Unit | Serializer | course ' + testgroup, {
// Specify the other units that are required for this test.
needs: [
'serializer:course',
'model:school',
'model:user',
'model:course',
'model:course-clerkship-type',
'model:session',
'model:offering',
'model:topic',
'model:objective',
'model:cohort',
'model:mesh-descriptor',
'model:course-learning-material'
]
});
test('it serializes records', function(assert) {
var record = this.subject();
var serializedRecord = record.serialize();
assert.ok(serializedRecord);
});
|
Remove publish-event from course serializer
|
Remove publish-event from course serializer
|
JavaScript
|
mit
|
gboushey/frontend,ilios/frontend,dartajax/frontend,djvoa12/frontend,jrjohnson/frontend,stopfstedt/frontend,ilios/frontend,thecoolestguy/frontend,thecoolestguy/frontend,stopfstedt/frontend,gboushey/frontend,gabycampagna/frontend,gabycampagna/frontend,dartajax/frontend,jrjohnson/frontend,djvoa12/frontend
|
77b1c897a9e23e06006a034a46b18dd3c605e1da
|
eloquent_js/chapter07/ch07_ex02.js
|
eloquent_js/chapter07/ch07_ex02.js
|
function getTurnCount(state, robot, memory) {
for (let turn = 0;; turn++) {
if (state.parcels.length == 0 || turn > 50) {
return turn;
}
let action = robot(state, memory);
state = state.move(action.direction);
memory = action.memory;
}
}
function compareRobots(robot1, memory1, robot2, memory2) {
let total1 = 0, total2 = 0, reps = 10000;
for (let i = 0; i < reps; ++i) {
let initState = VillageState.random();
total1 += getTurnCount(initState, robot1, memory1);
total2 += getTurnCount(initState, robot2, memory2);
}
console.log(`${robot1.name}: ${total1 / reps}\n` +
`${robot2.name}: ${total2 / reps}`);
}
function myRobot({place, parcels}, route) {
if (route.length == 0) {
// Select locations of parcels we current don't carry
let places = parcels.filter(p => p.place != place).map(p => p.place);
// Select addresses of parcels we currently carry
let addresses = parcels.filter(p => p.place == place).map(p => p.address);
let minLen = Infinity;
// Loop over destinations; checking parcels to pick up first guarantees
// that for multiple routes with same length, we'll prefer the one that
// picks up a parcel
for (let destination of places.concat(addresses)) {
parcelRoute = findRoute(roadGraph, place, destination);
if (parcelRoute.length < minLen) {
route = parcelRoute;
minLen = route.length;
}
}
}
return {direction: route[0], memory: route.slice(1)};
}
compareRobots(goalOrientedRobot, [], myRobot, []);
runRobotAnimation(VillageState.random(), myRobot, []);
|
function myRobot({place, parcels}, route) {
if (route.length == 0) {
let routes = parcels.map(p => {
if (p.place != place) return {
pickup: true,
route: findRoute(roadGraph, place, p.place)
};
return {
pickup: false,
route: findRoute(roadGraph, place, p.adress)
};
});
route = routes.reduce((prev, cur) => {
if (prev.route.length > cur.route.length) return cur;
if (prev.route.length < cur.route.length) return prev;
return cur.pickup ? cur : prev;
}).route;
}
return {direction: route[0], memory: route.slice(1)};
}
|
Add chapter 7, exercise 2
|
Add chapter 7, exercise 2
|
JavaScript
|
mit
|
bewuethr/ctci
|
cb292522bfaff42b453bf8b1ed7b2dd5fd233e0e
|
jobs/calc-site-views.js
|
jobs/calc-site-views.js
|
'use strict'
const AV = require('leancloud-storage')
const schedule = require('node-schedule')
const APP_ID = 'yzbpXQpXf1rWVRfAAM8Durgh-gzGzoHsz'
const APP_KEY = '020bjTvbiVinVQ21YtWAJ9t8'
const INTERVAL = 10 * 60 * 1000;
AV.init({
appId: APP_ID,
appKey: APP_KEY
})
const Site = AV.Object.extend('Site')
var j = schedule.scheduleJob('20 * * * *', calc); // every 20 minutes
function calc() {
let counter = {}
let query = new AV.Query('Page')
query.each((page) => {
let d = page.get('domain')
if (counter[d]) counter[d] += page.get('count')
else counter[d] = page.get('count')
}).then(() => {
console.log('Collect all pages.')
for (let domain in counter) {
if (counter.hasOwnProperty(domain)) {
let siteView = counter[domain]
let siteQ = new AV.Query('Site')
siteQ.equalTo('domain', domain)
siteQ.first().then(site => {
if (!site) {
site = new Site()
site.set('domain', domain)
}
site.set('count', siteView).save()
})
}
}
console.log('Done.');
})
}
|
'use strict'
const AV = require('leancloud-storage')
const schedule = require('node-schedule')
const APP_ID = 'yzbpXQpXf1rWVRfAAM8Durgh-gzGzoHsz'
const APP_KEY = '020bjTvbiVinVQ21YtWAJ9t8'
AV.init({
appId: APP_ID,
appKey: APP_KEY
})
const Site = AV.Object.extend('Site')
let j = schedule.scheduleJob('*/20 * * * *', calc); // every 20 minutes
function calc() {
let counter = {}
let query = new AV.Query('Page')
query.each((page) => {
let d = page.get('domain')
if (counter[d]) counter[d] += page.get('count')
else counter[d] = page.get('count')
}).then(() => {
console.log('Collect all pages.')
for (let domain in counter) {
if (counter.hasOwnProperty(domain)) {
let siteView = counter[domain]
let siteQ = new AV.Query('Site')
siteQ.equalTo('domain', domain)
siteQ.first().then(site => {
if (!site) {
site = new Site()
site.set('domain', domain)
}
site.set('count', siteView).save()
})
}
}
console.log('Done.');
})
}
|
Fix a mistake about cron jobs
|
Fix a mistake about cron jobs
|
JavaScript
|
mit
|
zry656565/Hit-Kounter-LC,zry656565/Hit-Kounter-LC
|
ba70a80ee9870d2185734f55349f67ac691a2f20
|
app/templates/extension.js
|
app/templates/extension.js
|
/*global
define,
require,
window,
console,
_
*/
/*jslint devel:true,
white: true
*/
define([
'jquery',
'underscore',
'./properties',
'./initialproperties',
'./lib/js/extensionUtils',
'text!./lib/css/style.css'
],
function ($, _, props, initProps, extensionUtils, cssContent) {
'use strict';
extensionUtils.addStyleToHeader(cssContent);
return {
definition: props,
initialProperties: initProps,
snapshot: { canTakeSnapshot: true },
resize : function( $element, layout ) {
//do nothing
},
// clearSelectedValues : function($element) {
//
// },
// Angular Template
//template: '',
// (Angular Template)
// Angular Controller
controller: ['$scope', function ($scope) {
}],
// (Angular Controller)
// Paint Method
paint: function ( $element, layout ) {
console.groupCollapsed('Basic Objects');
console.info('$element:');
console.log($element);
console.info('layout:');
console.log(layout);
console.groupEnd();
$element.empty();
var $helloWorld = $(document.createElement('div'));
$helloWorld.addClass('hello-world');
$helloWorld.html('Hello World from the extension "<%= extensionName%>"');
$element.append($helloWorld);
}
// (Paint Method)
};
});
|
/*global
define,
require,
window,
console,
_
*/
/*jslint devel:true,
white: true
*/
define([
'jquery',
'underscore',
'./properties',
'./initialproperties',
'./lib/js/extensionUtils',
'text!./lib/css/style.css'
],
function ($, _, props, initProps, extensionUtils, cssContent) {
'use strict';
extensionUtils.addStyleToHeader(cssContent);
return {
definition: props,
initialProperties: initProps,
snapshot: { canTakeSnapshot: true },
resize : function( $element, layout ) {
//do nothing
},
// clearSelectedValues : function($element) {
//
// },
// Angular Support (uncomment to use)
//template: '',
// Angular Controller
//controller: ['$scope', function ($scope) {
//
//}],
// (Angular Controller)
paint: function ( $element, layout ) {
console.groupCollapsed('Basic Objects');
console.info('$element:');
console.log($element);
console.info('layout:');
console.log(layout);
console.groupEnd();
$element.empty();
var $helloWorld = $(document.createElement('div'));
$helloWorld.addClass('hello-world');
$helloWorld.html('Hello World from the extension "<%= extensionName%>"');
$element.append($helloWorld);
}
};
});
|
Optimize formatting of main file
|
Optimize formatting of main file
|
JavaScript
|
mit
|
cloud9UG/generator-qsExtension,cloud9UG/generator-qsExtension
|
2f1eec32b35cdb0c379ece2837edb95fca13e009
|
test/util.js
|
test/util.js
|
var EventEmitter = require("events").EventEmitter;
var util = require("util");
var _ = require("lodash");
var express = require("express");
var Network = require("../src/models/network");
function MockClient(opts) {
this.user = {nick: "test-user"};
for (var k in opts) {
this[k] = opts[k];
}
}
util.inherits(MockClient, EventEmitter);
MockClient.prototype.createMessage = function(opts) {
var message = _.extend({
message: "dummy message",
nick: "test-user",
target: "#test-channel"
}, opts);
this.emit("privmsg", message);
};
module.exports = {
createClient: function() {
return new MockClient();
},
createNetwork: function() {
return new Network({
host: "example.com",
channels: [{
name: "#test-channel",
messages: []
}]
});
},
createWebserver: function() {
return express();
}
};
|
var EventEmitter = require("events").EventEmitter;
var util = require("util");
var _ = require("lodash");
var express = require("express");
var Network = require("../src/models/network");
var Chan = require("../src/models/chan");
function MockClient(opts) {
this.user = {nick: "test-user"};
for (var k in opts) {
this[k] = opts[k];
}
}
util.inherits(MockClient, EventEmitter);
MockClient.prototype.createMessage = function(opts) {
var message = _.extend({
message: "dummy message",
nick: "test-user",
target: "#test-channel"
}, opts);
this.emit("privmsg", message);
};
module.exports = {
createClient: function() {
return new MockClient();
},
createNetwork: function() {
return new Network({
host: "example.com",
channels: [new Chan({
name: "#test-channel"
})]
});
},
createWebserver: function() {
return express();
}
};
|
Create real channel object in tests
|
Create real channel object in tests
|
JavaScript
|
mit
|
FryDay/lounge,rockhouse/lounge,libertysoft3/lounge-autoconnect,MaxLeiter/lounge,libertysoft3/lounge-autoconnect,libertysoft3/lounge-autoconnect,metsjeesus/lounge,realies/lounge,rockhouse/lounge,MaxLeiter/lounge,MaxLeiter/lounge,williamboman/lounge,ScoutLink/lounge,ScoutLink/lounge,ScoutLink/lounge,sebastiencs/lounge,williamboman/lounge,realies/lounge,sebastiencs/lounge,williamboman/lounge,metsjeesus/lounge,FryDay/lounge,thelounge/lounge,metsjeesus/lounge,rockhouse/lounge,realies/lounge,FryDay/lounge,sebastiencs/lounge,thelounge/lounge
|
5cc35c18b5b3eeb5cc78ffb74f4fc893dc39646b
|
src/controllers/version.js
|
src/controllers/version.js
|
const slaveService = require('../services/slave');
const versionService = require('../services/version');
const version = {
currentVersion(req, res) {
const {slaveUID, slaveVersion} = req.params,
remoteAddress = req.headers['x-forwarded-for'] || req.connection.remoteAddress,
tag = versionService.getCurrent();
const respondWithTag = () => {
res.json(200, {tag});
};
slaveService.updateSlave(slaveUID, slaveVersion, remoteAddress)
.then(respondWithTag)
.catch(error => {
console.error(`An error occurred when updating ${slaveUID}: ${error}`);
// send back current version regardless
respondWithTag();
});
}
}
module.exports = version;
|
const slaveService = require('../services/slave');
const versionService = require('../services/version');
const version = {
currentVersion(req, res) {
const {slaveUID, slaveVersion} = req.params,
remoteAddress = req.headers['x-forwarded-for'] || req.connection.remoteAddress,
tag = versionService.getCurrent();
const respondWithTag = () => {
res.json(200, {tag});
};
slaveService.updateSlave(slaveUID, slaveVersion, remoteAddress)
.catch(error => {
console.error(`An error occurred when updating ${slaveUID}: ${error}`);
});
// send back current version regardless of success or failure of db entry
respondWithTag();
}
}
module.exports = version;
|
Send response while database is still updating
|
Send response while database is still updating
|
JavaScript
|
mit
|
4minitz/version-check
|
30c6ae39b53d26eca08ff42e37b58f383d965240
|
language_switcher_for_microsoft_docs.user.js
|
language_switcher_for_microsoft_docs.user.js
|
// ==UserScript==
// @name Language switcher for Microsoft Docs
// @namespace curipha
// @description Add language menu
// @include https://docs.microsoft.com/*
// @version 0.0.1
// @grant none
// @noframes
// ==/UserScript==
(function() {
'use strict';
const nav = document.getElementById('affixed-left-container');
if (nav) {
const [tolang, label] = location.pathname.substring(0,7) === '/en-us/' ? ['ja-jp', '日本語'] : ['en-us', 'English'];
const anchor = document.createElement('a');
anchor.href = location.pathname.replace(/(?<=^\/)[A-Za-z0-9-]+(?=\/)/, tolang);
anchor.className = 'button is-small is-text has-inner-focus has-margin-bottom-small has-border-top has-border-bottom';
const icon = document.createElement('span');
icon.className = 'icon is-size-8 has-text-subtle';
const iconinner = document.createElement('span');
iconinner.className = 'docon docon-locale-globe';
const text = document.createElement('span');
text.textContent = label;
icon.appendChild(iconinner);
anchor.appendChild(icon);
anchor.appendChild(text);
nav.appendChild(anchor);
const makehref = function() { this.href += location.hash; };
anchor.addEventListener('mousedown', makehref, false);
anchor.addEventListener('keydown', makehref, false);
}
})();
|
// ==UserScript==
// @name Language switcher for Microsoft Docs
// @namespace curipha
// @description Add language menu
// @include https://docs.microsoft.com/*
// @version 0.0.1
// @grant none
// @noframes
// ==/UserScript==
(function() {
'use strict';
const nav = document.getElementById('affixed-left-container');
if (nav) {
const [tolang, label] = location.pathname.substring(0,7) === '/en-us/' ? ['ja-jp', '日本語'] : ['en-us', 'English'];
const anchor = document.createElement('a');
anchor.href = location.pathname.replace(/(?<=^\/)[A-Za-z0-9-]+(?=\/)/, tolang) + location.search;
anchor.className = 'button is-small is-text has-inner-focus has-margin-bottom-small has-border-top has-border-bottom';
const icon = document.createElement('span');
icon.className = 'icon is-size-8 has-text-subtle';
const iconinner = document.createElement('span');
iconinner.className = 'docon docon-locale-globe';
const text = document.createElement('span');
text.textContent = label;
icon.appendChild(iconinner);
anchor.appendChild(icon);
anchor.appendChild(text);
nav.appendChild(anchor);
const makehref = function() { this.href += location.hash; };
anchor.addEventListener('mousedown', makehref, false);
anchor.addEventListener('keydown', makehref, false);
}
})();
|
Add query strings to the anchor
|
Add query strings to the anchor
|
JavaScript
|
unlicense
|
curipha/userscripts,curipha/userscripts
|
e3503e8cbd9ea13f93b1b40f746ce512e988c60b
|
extensions/no_right_click/apply.js
|
extensions/no_right_click/apply.js
|
window.oncontextmenu = function() {return false;};
|
/**
* Disables context menus, including those initiated by a right click.
*/
function disableRightClick() {
window.addEventListener('oncontextmenu', function() {
return false;
}, true);
}
disableRightClick();
|
Add JSDoc and use addEventListener
|
no_right_click: Add JSDoc and use addEventListener
|
JavaScript
|
apache-2.0
|
EndPointCorp/appctl,EndPointCorp/appctl
|
edba00314d922c1a308c77a5da308f1d522aecd3
|
src/js/app/models/trade.js
|
src/js/app/models/trade.js
|
define([
'app/models/base',
'app/validations/trade'
], function (BaseModel, validation) {
return BaseModel.extend({
defaults: {
'executionOn': null,
'isBtcSell': false,
'isBtcBuy': false,
'currencyIsoCode': 'usd',
'btcPrice': 0.0,
'btcAmount': 0.0,
'xxxAmount': 0.0,
'btcFee': 0.0,
'xxxFee': 0.0,
'isIgnored': false,
'isDeleted': false,
'serviceName': '',
'serviceIdentifier': null,
'tags': []
},
validation: validation
});
});
|
define([
'app/models/base',
'app/validations/trade',
'moment',
'underscore'
], function (BaseModel, validation, moment, _) {
return BaseModel.extend({
validation: validation,
defaults: {
'executionOn': null,
'isBtcSell': false,
'isBtcBuy': false,
'currencyIsoCode': 'usd',
'btcPrice': 0.0,
'btcAmount': 0.0,
'xxxAmount': 0.0,
'btcFee': 0.0,
'xxxFee': 0.0,
'isIgnored': false,
'isDeleted': false,
'serviceName': '',
'serviceIdentifier': null,
'tags': []
},
executionOn: function () {
var setValue, getValue;
if (arguments.length > 0) {
// setter
setValue = arguments[0];
if (_.isNull(setValue))
return this.set('executionOn', null);
if (!_.isNull(setValue) && !moment.isMoment(setValue))
throw new Error('No moment object provided!');
return this.set('executionOn', newValue);
} else {
// getter
getValue = this.get('executionOn');
return moment(getValue);
}
}
});
});
|
Add high level getter/setter for executionOn attr
|
Add high level getter/setter for executionOn attr
|
JavaScript
|
mit
|
davidknezic/bitcoin-trade-guard
|
0970c167a6df5f48664295cddb6f5f5effaaf8c2
|
app/lib/fg/import-web-apis.js
|
app/lib/fg/import-web-apis.js
|
import { ipcRenderer } from 'electron'
import rpc from 'pauls-electron-rpc'
// it would be better to import this from package.json
const BEAKER_VERSION = '0.0.1'
// method which will populate window.beaker with the APIs deemed appropriate for the protocol
export default function () {
window.beaker = { version: BEAKER_VERSION }
var webAPIs = ipcRenderer.sendSync('get-web-api-manifests', window.location.protocol)
for (var k in webAPIs) {
window[k] = rpc.importAPI(k, webAPIs[k], { timeout: false })
}
}
|
import { ipcRenderer, webFrame } from 'electron'
import rpc from 'pauls-electron-rpc'
// it would be better to import this from package.json
const BEAKER_VERSION = '0.0.1'
// method which will populate window.beaker with the APIs deemed appropriate for the protocol
export default function () {
// mark the safe protocol as 'secure' to enable all DOM APIs
webFrame.registerURLSchemeAsSecure('safe');
window.beaker = { version: BEAKER_VERSION }
var webAPIs = ipcRenderer.sendSync('get-web-api-manifests', window.location.protocol)
for (var k in webAPIs) {
window[k] = rpc.importAPI(k, webAPIs[k], { timeout: false })
}
}
|
Mark safe as a secure protocol
|
feat/webview: Mark safe as a secure protocol
Chrom(e|ium) exposes many newer DOM APIs and HTML5 features (like User Media or Geolocation)
only over secure connections – primarily https – in order to prevent the user from
accidentially exposing themselves to third parties. For any webpage deliver over an unsecure
protocol those APIs will be flat out denied.
This patch registers our own `safe`-protocol as a secure one, in order to enable said
DOM APIs and HTML5 features.
|
JavaScript
|
mit
|
joshuef/beaker,joshuef/beaker,joshuef/beaker
|
b02b385adb60e13249e3ae11811100c5ad4a4118
|
src/event.js
|
src/event.js
|
/**
* Event
*
* @author Rakume Hayashi<i@fake.moe>
*/
Faiash.ise.extend({
on: function() {
if (typeof arguments[0] === 'string') {
for (var i = 0; i < this.length; i++) {
this[i].addEventListener(arguments[0], arguments[1], arguments[2]);
}
} else {
for (var i = 0; i < this.length; i++) {
for (var event in this[i]) {
if (object.hasOwnProperty(event)) {
this[i].addEventListener(event, this[i][event]);
}
}
}
}
}
});
|
/**
* Event
*
* @author Rakume Hayashi<i@fake.moe>
*/
Faiash.ise.extend({
bind: function() {
if (typeof arguments[0] === 'string') {
for (var i = 0; i < this.length; i++) {
this[i].addEventListener(arguments[0], arguments[1], arguments[2]);
}
} else {
for (var i = 0; i < this.length; i++) {
for (var event in this[i]) {
if (object.hasOwnProperty(event)) {
this[i].addEventListener(event, this[i][event]);
}
}
}
}
},
unbind: function() {
if (typeof arguments[0] === 'string') {
for (var i = 0; i < this.length; i++) {
this[i].removeEventListener(arguments[0], arguments[1], arguments[2]);
}
} else {
for (var i = 0; i < this.length; i++) {
for (var event in this[i]) {
if (object.hasOwnProperty(event)) {
this[i].removeEventListener(event, this[i][event]);
}
}
}
}
}
});
|
Rename on to bind, add unbind
|
Rename on to bind, add unbind
|
JavaScript
|
mit
|
Kunr/Faiash
|
eb8a252ffd5923e328603f0c7c61048a1a2d2e72
|
src/index.js
|
src/index.js
|
import {Stream} from 'most'
import MulticastSource from './MulticastSource'
function multicast (stream) {
const source = stream.source
return source instanceof MulticastSource
? stream
: new Stream(new MulticastSource(source))
}
export {multicast as default, MulticastSource}
|
import MulticastSource from './MulticastSource'
function multicast (stream) {
const source = stream.source
return source instanceof MulticastSource
? stream
: new stream.constructor(new MulticastSource(source))
}
export {multicast as default, MulticastSource}
|
Break dep cycle, allow most to use mostjs/multicast
|
Break dep cycle, allow most to use mostjs/multicast
|
JavaScript
|
mit
|
mostjs/multicast
|
3231c6bffcffad290e7a900e7a51d5b889f796bf
|
src/index.js
|
src/index.js
|
// Configuration
export {default as configure} from './configure';
export {default as configureRoutes} from './configureRoutes';
// Components
export {default as Card} from './components/Card/Card';
export {default as Span} from './components/Specimen/Span';
// Higher-order component for creating specimens
export {default as Specimen} from './components/Specimen/Specimen';
// Specimens
export {default as AudioSpecimen} from './specimens/Audio';
export {default as ButtonSpecimen} from './specimens/Button';
export {default as CodeSpecimen} from './specimens/Code';
export {default as ColorSpecimen} from './specimens/Color';
export {default as HtmlSpecimen} from './specimens/Html';
export {default as HintSpecimen} from './specimens/Hint';
export {default as ImageSpecimen} from './specimens/Image';
export {default as TypeSpecimen} from './specimens/Type';
export {default as ProjectSpecimen} from './specimens/Project/Project';
export {default as DownloadSpecimen} from './specimens/Download';
export {default as ReactSpecimen} from './specimens/ReactSpecimen/ReactSpecimen';
export {default as VideoSpecimen} from './specimens/Video';
|
// Configuration
export {default as render} from './render';
export {default as configure} from './configure';
export {default as configureRoutes} from './configureRoutes';
// Components
export {default as Card} from './components/Card/Card';
export {default as Span} from './components/Specimen/Span';
// Higher-order component for creating specimens
export {default as Specimen} from './components/Specimen/Specimen';
// Specimens
export {default as AudioSpecimen} from './specimens/Audio';
export {default as ButtonSpecimen} from './specimens/Button';
export {default as CodeSpecimen} from './specimens/Code';
export {default as ColorSpecimen} from './specimens/Color';
export {default as HtmlSpecimen} from './specimens/Html';
export {default as HintSpecimen} from './specimens/Hint';
export {default as ImageSpecimen} from './specimens/Image';
export {default as TypeSpecimen} from './specimens/Type';
export {default as ProjectSpecimen} from './specimens/Project/Project';
export {default as DownloadSpecimen} from './specimens/Download';
export {default as ReactSpecimen} from './specimens/ReactSpecimen/ReactSpecimen';
export {default as VideoSpecimen} from './specimens/Video';
|
Bring back `render` to module
|
Bring back `render` to module
|
JavaScript
|
bsd-3-clause
|
interactivethings/catalog,interactivethings/catalog,interactivethings/catalog,interactivethings/catalog
|
b5fb9cadc7ac30f291f7db9e5a692271cc58e2d4
|
src/index.js
|
src/index.js
|
import React from 'react'
import ReactDOM from 'react-dom'
import {Router, browserHistory} from 'react-router'
import configureStore from './store'
import {Provider} from 'react-redux'
import {syncHistoryWithStore} from 'react-router-redux'
import APIUtils from './utils/APIUtils'
import { AppContainer } from 'react-hot-loader'
import {makeRoutes} from './routes'
// styles are stored separately in production
if (__DEV__)
require('../stylus/index.styl')
// require('bootstrap/dist/css/bootstrap.css')
class Root extends React.Component {
render() {
return (
<Provider store={this.props.store}>
<Router history={browserHistory}>
{this.props.routes}
</Router>
</Provider>
)
}
}
const api = new APIUtils()
const store = configureStore(api)
const history = syncHistoryWithStore(browserHistory, store)
function render(routes) {
console.log('render')
ReactDOM.render(
<AppContainer>
<Provider store={store}>
<Router history={history}>
{routes}
</Router>
</Provider>
</AppContainer>,
document.getElementById('app')
)
}
render(makeRoutes())
if (module.hot)
module.hot.accept('./routes', () => render(makeRoutes()))
|
import React from 'react'
import ReactDOM from 'react-dom'
import {Router, browserHistory} from 'react-router'
import configureStore from './store'
import {Provider} from 'react-redux'
import {syncHistoryWithStore} from 'react-router-redux'
import APIUtils from './utils/APIUtils'
import { AppContainer } from 'react-hot-loader'
import {makeRoutes} from './routes'
import '../stylus/index.styl'
class Root extends React.Component {
render() {
return (
<Provider store={this.props.store}>
<Router history={browserHistory}>
{this.props.routes}
</Router>
</Provider>
)
}
}
const api = new APIUtils()
const store = configureStore(api)
const history = syncHistoryWithStore(browserHistory, store)
function render(routes) {
console.log('render')
ReactDOM.render(
<AppContainer>
<Provider store={store}>
<Router history={history}>
{routes}
</Router>
</Provider>
</AppContainer>,
document.getElementById('app')
)
}
render(makeRoutes())
if (module.hot)
module.hot.accept('./routes', () => render(makeRoutes()))
|
Fix style loading in production.
|
Fix style loading in production.
|
JavaScript
|
mit
|
jsza/tempus-website,jsza/tempus-website
|
b85745c284cbf29372b9caf2d2ea8010d1129ac2
|
test/node.js
|
test/node.js
|
"use strict";
var assert = require('assert');
var CryptoApi = require('../lib/crypto-api');
var hex = require('../lib/enc.hex');
var md2 = require('../lib/hasher.md2');
var md4 = require('../lib/hasher.md4');
var md5 = require('../lib/hasher.md5');
var sha0 = require('../lib/hasher.sha0');
var sha1 = require('../lib/hasher.sha1');
var sha256 = require('../lib/hasher.sha256');
var TestVectors = require('../test-vectors');
Object.keys(TestVectors).forEach(function(hash) {
describe('Tests for hash ' + hash, function () {
Object.keys(TestVectors[hash]).forEach(function(msg) {
it(msg, function () {
assert.equal(CryptoApi.hash(hash, TestVectors[hash][msg].message, {}).stringify('hex'), TestVectors[hash][msg].hash);
});
});
});
});
|
"use strict";
var assert = require('assert');
var CryptoApi = require('../lib/crypto-api');
var hex = require('../lib/enc.hex');
var md2 = require('../lib/hasher.md2');
var md4 = require('../lib/hasher.md4');
var md5 = require('../lib/hasher.md5');
var sha0 = require('../lib/hasher.sha0');
var sha1 = require('../lib/hasher.sha1');
var sha256 = require('../lib/hasher.sha256');
var TestVectors = require('../test-vectors');
Object.keys(TestVectors).forEach(function(hash) {
describe('Tests for hash ' + hash, function () {
Object.keys(TestVectors[hash]).forEach(function(msg) {
it(msg, function () {
assert.equal(CryptoApi.hash(hash, TestVectors[hash][msg].message, {}).stringify('hex'), TestVectors[hash][msg].hash);
});
});
});
});
describe('Test Error handling', function () {
it("CryptoApi.hash('no-hasher')", function () {
var error = '';
try {
CryptoApi.hash('no-hasher', '', {});
} catch(e) {
error = e;
}
assert.equal(error instanceof Error, true);
});
it("CryptoApi.hash('md2').stringify('no-encode')", function () {
var error = '';
try {
CryptoApi.hash('md2', '', {}).stringify('no-encode');
} catch(e) {
error = e;
}
assert.equal(error instanceof Error, true);
});
it("CryptoApi.Hashers.add('undefined', undefined", function () {
var error = '';
try {
CryptoApi.Hashers.add('undefined', undefined);
} catch(e) {
error = e;
}
assert.equal(error instanceof Error, true);
});
it("CryptoApi.Encodes.add('undefined', undefined)", function () {
var error = '';
try {
CryptoApi.Encodes.add('undefined', undefined);
} catch(e) {
error = e;
}
assert.equal(error instanceof Error, true);
});
});
|
Add tests for error handling
|
Add tests for error handling
|
JavaScript
|
mit
|
nf404/crypto-api,nf404/crypto-api
|
cdb29356d47db83b517e053165ef78cfd81ff918
|
db/models/beacons.js
|
db/models/beacons.js
|
const Sequelize = require('sequelize');
const db = require('../db.js');
const beacon = db.define('beacon', {
currentLocation: {
type: Sequelize.ARRAY(Sequelize.FLOAT),
},
})
module.exports = beacon;
|
const Sequelize = require('sequelize');
const db = require('../db.js');
const beacon = db.define('beacon', {
currentLocation: {
type: Sequelize.ARRAY(Sequelize.FLOAT),
},
OS: {
type: Sequelize.STRING,
},
token: {
type: Sequelize.STRING,
},
lastNotification: {
type: Sequelize.DATE,
},
device: {
type: Sequelize.STRING,
}
})
module.exports = beacon;
|
Add device info to beacon
|
refactor(database): Add device info to beacon
Add device info to beacon
|
JavaScript
|
mit
|
LintLions/Respondr,LintLions/Respondr
|
3e231f8ada23d4c166facae27933f2f2c9024aea
|
addon/mixin.js
|
addon/mixin.js
|
import Ember from 'ember';
export default Ember.Mixin.create({
init: function() {
this._super();
if(!this.hasAnalytics()) {
Ember.Logger.warn('Segment.io is not loaded yet (window.analytics)');
}
},
hasAnalytics: function() {
return !!(window.analytics && typeof window.analytics === "object");
},
log: function() {
if(this.config && this.config.segment && this.config.segment.LOG_EVENT_TRACKING) {
Ember.Logger.info('[Segment.io] ', arguments);
}
},
trackPageView: function(page) {
if(this.hasAnalytics()) {
window.analytics.page(page);
this.log('trackPageView', page);
}
},
trackEvent: function(event, properties, options, callback) {
if(this.hasAnalytics()) {
window.analytics.track(event, properties, options, callback);
this.log(event, properties, options);
}
},
identifyUser: function(userId, traits, options, callback) {
if(this.hasAnalytics()) {
window.analytics.identify(userId, traits, options, callback);
this.log('identifyUser', traits, options);
}
},
aliasUser: function(userId, previousId, options, callback) {
if(this.hasAnalytics()) {
window.analytics.alias(userId, previousId, options, callback);
this.log('aliasUser', previousId, options);
}
}
});
|
import Ember from 'ember';
export default Ember.Mixin.create({
init: function() {
this._super();
if(!this.hasAnalytics()) {
Ember.Logger.warn('Segment.io is not loaded yet (window.analytics)');
}
},
hasAnalytics: function() {
return !!(window.analytics && typeof window.analytics === "object");
},
log: function() {
if(this.config && this.config.segment && this.config.segment.LOG_EVENT_TRACKING) {
Ember.Logger.info('[Segment.io] ', arguments);
}
},
trackPageView: function() {
if(this.hasAnalytics()) {
window.analytics.page.apply(this, arguments);
this.log('trackPageView', arguments);
}
},
trackEvent: function(event, properties, options, callback) {
if(this.hasAnalytics()) {
window.analytics.track(event, properties, options, callback);
this.log(event, properties, options);
}
},
identifyUser: function(userId, traits, options, callback) {
if(this.hasAnalytics()) {
window.analytics.identify(userId, traits, options, callback);
this.log('identifyUser', traits, options);
}
},
aliasUser: function(userId, previousId, options, callback) {
if(this.hasAnalytics()) {
window.analytics.alias(userId, previousId, options, callback);
this.log('aliasUser', previousId, options);
}
}
});
|
Allow passing more params to trackPageView
|
Allow passing more params to trackPageView
|
JavaScript
|
mit
|
cepko33/ember-cli-analytics,cepko33/ember-cli-analytics,josemarluedke/ember-cli-segment,kmiyashiro/ember-cli-segment,josemarluedke/ember-cli-segment,kmiyashiro/ember-cli-segment
|
8380f2753ac96953a141e6f393f2829335255dba
|
lib/services/route53.js
|
lib/services/route53.js
|
/**
* Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You
* may not use this file except in compliance with the License. A copy of
* the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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 AWS = require('../core');
AWS.Route53 = AWS.Service.defineService('route53', ['2012-12-12'], {
setupRequestListeners: function setupRequestListeners(request) {
request.on('build', this.sanitizeUrl);
},
sanitizeUrl: function sanitizeUrl(request) {
var path = request.httpRequest.path;
request.httpRequest.path = path.replace(/\/%2F\w+%2F/, '/');
},
setEndpoint: function setEndpoint(endpoint) {
if (endpoint) {
AWS.Service.prototype.setEndpoint(endpoint);
} else {
var opts = {sslEnabled: true}; // SSL is always enabled for Route53
this.endpoint = new AWS.Endpoint(this.api.globalEndpoint, opts);
}
}
});
module.exports = AWS.Route53;
|
/**
* Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You
* may not use this file except in compliance with the License. A copy of
* the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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 AWS = require('../core');
AWS.Route53 = AWS.Service.defineService('route53', ['2012-12-12'], {
/**
* @api private
*/
setupRequestListeners: function setupRequestListeners(request) {
request.on('build', this.sanitizeUrl);
},
/**
* @api private
*/
sanitizeUrl: function sanitizeUrl(request) {
var path = request.httpRequest.path;
request.httpRequest.path = path.replace(/\/%2F\w+%2F/, '/');
},
/**
* @api private
*/
setEndpoint: function setEndpoint(endpoint) {
if (endpoint) {
AWS.Service.prototype.setEndpoint(endpoint);
} else {
var opts = {sslEnabled: true}; // SSL is always enabled for Route53
this.endpoint = new AWS.Endpoint(this.api.globalEndpoint, opts);
}
}
});
module.exports = AWS.Route53;
|
Update documentation for Route53 service
|
Update documentation for Route53 service
|
JavaScript
|
apache-2.0
|
jeskew/aws-sdk-js,chrisradek/aws-sdk-js,Blufe/aws-sdk-js,guymguym/aws-sdk-js,odeke-em/aws-sdk-js,chrisradek/aws-sdk-js,beni55/aws-sdk-js,Blufe/aws-sdk-js,prembasumatary/aws-sdk-js,grimurjonsson/aws-sdk-js,MitocGroup/aws-sdk-js,beni55/aws-sdk-js,dconnolly/aws-sdk-js,grimurjonsson/aws-sdk-js,jmswhll/aws-sdk-js,dconnolly/aws-sdk-js,prestomation/aws-sdk-js,GlideMe/aws-sdk-js,jippeholwerda/aws-sdk-js,prestomation/aws-sdk-js,jmswhll/aws-sdk-js,MitocGroup/aws-sdk-js,aws/aws-sdk-js,mohamed-kamal/aws-sdk-js,AdityaManohar/aws-sdk-js,jeskew/aws-sdk-js,misfitdavidl/aws-sdk-js,j3tm0t0/aws-sdk-js,misfitdavidl/aws-sdk-js,ugie/aws-sdk-js,mohamed-kamal/aws-sdk-js,MitocGroup/aws-sdk-js,j3tm0t0/aws-sdk-js,aws/aws-sdk-js,AdityaManohar/aws-sdk-js,LiuJoyceC/aws-sdk-js,odeke-em/aws-sdk-js,misfitdavidl/aws-sdk-js,LiuJoyceC/aws-sdk-js,jmswhll/aws-sdk-js,AdityaManohar/aws-sdk-js,jeskew/aws-sdk-js,odeke-em/aws-sdk-js,guymguym/aws-sdk-js,michael-donat/aws-sdk-js,mapbox/aws-sdk-js,Blufe/aws-sdk-js,grimurjonsson/aws-sdk-js,jippeholwerda/aws-sdk-js,mapbox/aws-sdk-js,mohamed-kamal/aws-sdk-js,michael-donat/aws-sdk-js,GlideMe/aws-sdk-js,j3tm0t0/aws-sdk-js,jippeholwerda/aws-sdk-js,guymguym/aws-sdk-js,prembasumatary/aws-sdk-js,GlideMe/aws-sdk-js,GlideMe/aws-sdk-js,mapbox/aws-sdk-js,jeskew/aws-sdk-js,dconnolly/aws-sdk-js,chrisradek/aws-sdk-js,chrisradek/aws-sdk-js,guymguym/aws-sdk-js,aws/aws-sdk-js,LiuJoyceC/aws-sdk-js,michael-donat/aws-sdk-js,aws/aws-sdk-js,ugie/aws-sdk-js,prembasumatary/aws-sdk-js,ugie/aws-sdk-js,beni55/aws-sdk-js,prestomation/aws-sdk-js
|
b6c04907f80c9942358dfbaf5bd9d5d40afdb120
|
lib/utils/leap-mockhand.js
|
lib/utils/leap-mockhand.js
|
'use strict'
const path = require('path')
const { config } = require(path.join(__dirname, '..', '..', 'main.config.js'))
module.exports = class MockHand {
constructor (normalizedPosition) {
this.normalizedPosition = [...normalizedPosition]
this.target = [...normalizedPosition]
}
update (box) {
this.normalizedPosition.forEach((_, index) => {
const d = this.target[index] - this.normalizedPosition[index]
this.normalizedPosition[index] += d * config.leap.mockHandEasing
})
return {
x: this.normalizedPosition[0] * box[0],
y: this.normalizedPosition[2] * box[1],
z: this.normalizedPosition[1] * box[2]
}
}
}
|
'use strict'
const path = require('path')
const { config } = require(path.join(__dirname, '..', '..', 'main.config.js'))
module.exports = class MockHand {
constructor (normalizedPosition) {
this.normalizedPosition = [...normalizedPosition]
this.target = [...normalizedPosition]
}
update (box) {
this.normalizedPosition.forEach((_, index) => {
const d = this.target[index] - this.normalizedPosition[index]
this.normalizedPosition[index] += d * config.leap.mockHandEasing
})
return {
isMockHand: true,
x: this.normalizedPosition[0] * box[0],
y: this.normalizedPosition[2] * box[1],
z: this.normalizedPosition[1] * box[2]
}
}
}
|
Add method to determine if hand is mocked
|
[leap] Add method to determine if hand is mocked
|
JavaScript
|
mit
|
chevalvert/stratum,chevalvert/stratum
|
91c3c0a352c46c885b5dd169ea6c59ce6863337a
|
app/bundles.js
|
app/bundles.js
|
var fs = require('fs'),
_ = require('lodash'),
yaml = require('js-yaml'),
bundles = yaml.safeLoad(fs.readFileSync('bundles.yml', 'utf8')),
settings = require('./config');
function getTag(key, asset) {
if (key.indexOf('_js') > -1) {
return '<script type="text/javascript" src="' + asset + '"></script>';
} else {
return '<link rel="stylesheet" type="text/css" href="' + asset + '" />';
}
}
function production(value, key) {
return [key, getTag(key, value.dest)];
}
function development(value, key) {
var tags = value.src.map(function(asset) {
return getTag(key, asset);
});
return [key, tags.join('')];
}
var map = settings.env === 'production' ? production : development;
module.exports = _.object(_.map(bundles, map));
|
var fs = require('fs'),
_ = require('lodash'),
yaml = require('js-yaml'),
bundles = yaml.safeLoad(fs.readFileSync('bundles.yml', 'utf8')),
settings = require('./config');
function getTag(key, asset) {
if (key.indexOf('_js') > -1) {
return '<script type="text/javascript" src="' + asset + '"></script>';
} else {
return '<link rel="stylesheet" type="text/css" href="' + asset + '" />';
}
}
function production(value, key) {
return [key, getTag(key, value.dest)];
}
function development(value, key) {
var tags = value.src.map(function(asset) {
if (asset.indexOf('socket.io.js') > -1) {
asset ='socket.io/socket.io.js';
}
return getTag(key, asset);
});
return [key, tags.join('')];
}
var map = settings.env === 'production' ? production : development;
module.exports = _.object(_.map(bundles, map));
|
Fix loading of socket.io.js when in development mode
|
Fix loading of socket.io.js when in development mode
|
JavaScript
|
mit
|
cesarmarinhorj/lets-chat,ashwini-angular/lets-chat,nickrobinson/lets-chat,evdevgit/lets-chat,disappearedgod/lets-chat,rlightner/lets-chat,KillianKemps/lets-chat,saitodisse/lets-chat,hzruandd/lets-chat,sdelements/lets-chat,webkaz/lets-chat,aaryn101/lets-chat,e-green/eduChat,jparyani/lets-chat,damoguyan8844/lets-chat,damoguyan8844/lets-chat,linhmtran168/lets-chat,fabianschwarzfritz/lets-chat,cloudnautique/lets-chat,alexisaperez/lets-chat,eetuuuu/lets-chat,robin1liu/lets-chat,neynah/lets-chat,Drooids/lets-chat,fhchina/lets-chat,webbab/lets-chat,ycaihua/lets-chat,heitortsergent/lets-chat,leolujuyi/lets-chat,glomb226/lets-chat,e-green/eduChat,gvmatera/lets-chat,udacity/lets-chat,Stackato-Apps/lets-chat,saranrapjs/lets-chat,nickrobinson/lets-chat,saitodisse/lets-chat,fhchina/lets-chat,CodesScripts/lets-chat,hrwebasst/lets-chat,kaushik94/ama,fabric8io/lets-chat,yangchaogit/lets-chat,qitianchan/lets-chat,galal-hussein/lets-chat,fabianschwarzfritz/lets-chat,cloudnautique/lets-chat,akira1908jp/tachikawapm,eetuuuu/lets-chat,dcode/lets-chat,xdevelsistemas/lets-chat,jparyani/lets-chat,eiriklv/lets-chat,webbab/lets-chat,MOZGIII/lets-chat,beni55/lets-chat,praveenscience/lets-chat,leohmoraes/lets-chat,ashwini-angular/lets-chat,iooly/lets-chat,sitexa/lets-chat,lihuanghai/lets-chat,galal-hussein/lets-chat,lumeet/lets-chat,hzruandd/lets-chat,akira1908jp/tachikawapm,beijinglug/lets-chat,Stackato-Apps/lets-chat,kaushik94/ama,neynah/lets-chat,lumeet/lets-chat,ycaihua/lets-chat,manland/lets-chat,8bitjeremy/velochat,sunnipaul/lets-chat,jparyani/lets-chat,replicat0r/tkcomm,gvmatera/lets-chat,galal-hussein/lets-chat,praveenscience/lets-chat,madnanbashir/stitch1,hrwebasst/lets-chat,ga-wdi-boston/lets-chat,ibuildthecloud/lets-chat,CodesScripts/lets-chat,sdelements/lets-chat,ibuildthecloud/lets-chat,cloudnautique/lets-chat,ga-wdi-boston/lets-chat,gamedevtech/lets-chat,alexisaperez/lets-chat,xdevelsistemas/lets-chat,Tepira/lets-chat,fallacy321/lets-chat,dmbrown/lets-chat,dmbrown/lets-chat,MenZil/lets-chat,stonegithubs/lets-chat,fallacy321/lets-chat,sploadie/lets-chat,madnanbashir/stitch1,manland/lets-chat,cesarmarinhorj/lets-chat,askmeanything-app/askmeanything,MOZGIII/lets-chat,tart/lets-chat,glomb226/lets-chat,hcxiong/lets-chat,rlightner/lets-chat,linhmtran168/lets-chat,heitortsergent/lets-chat,yangchaogit/lets-chat,fabric8io/lets-chat,ibuildthecloud/lets-chat,neynah/lets-chat,gautamkrishnar/lets-chat,thollingsheadesri/lets-chat,jjz/lets-chat,iooly/lets-chat,beni55/lets-chat,sploadie/lets-chat,Drooids/lets-chat,thollingsheadesri/lets-chat,jjz/lets-chat,webkaz/lets-chat,evdevgit/lets-chat,replicat0r/tkcomm,sitexa/lets-chat,hcxiong/lets-chat,leohmoraes/lets-chat,qitianchan/lets-chat,saranrapjs/lets-chat,udacity/lets-chat,adam-nnl/lets-chat,disappearedgod/lets-chat,askmeanything-app/askmeanything,dcode/lets-chat,leolujuyi/lets-chat,MenZil/lets-chat,gamedevtech/lets-chat,Tepira/lets-chat,adam-nnl/lets-chat,aaryn101/lets-chat,sunnipaul/lets-chat,lihuanghai/lets-chat,KillianKemps/lets-chat,ashwini-angular/lets-chat,8bitjeremy/velochat,alawnchen/lets-chat,beijinglug/lets-chat,galal-hussein/lets-chat,gautamkrishnar/lets-chat,alawnchen/lets-chat,stonegithubs/lets-chat,joyhuang-web/lets-chat,robin1liu/lets-chat
|
b406c7cfd16c1054d2e3d3ccb054990f2d1679e1
|
src/index.js
|
src/index.js
|
import React from 'react';
import ReactDOM from 'react-dom';
import { setComponentsNames, globalizeComponents, promoteInlineExamples, flattenChildren } from './utils/utils';
import StyleGuide from 'rsg-components/StyleGuide';
import 'highlight.js/styles/tomorrow.css';
import './styles.css';
global.React = React;
if (module.hot) {
module.hot.accept();
}
// Load style guide
let { config, components, sections } = require('styleguide!');
function processComponents(cs) {
cs = flattenChildren(cs);
cs = promoteInlineExamples(cs);
cs = setComponentsNames(cs);
globalizeComponents(cs);
return cs;
}
function processSections(ss) {
return ss.map(section => {
section.components = processComponents(section.components || []);
section.sections = processSections(section.sections || []);
return section;
});
}
// Components are required unless sections are provided
if (sections) {
sections = processSections(sections)
components = []
} else {
components = processComponents(components)
sections = []
}
components = components ? processComponents(components) : [];
sections = sections ? processSections(sections) : [];
ReactDOM.render(<StyleGuide config={config} components={components} sections={sections} />, document.getElementById('app'));
|
import React from 'react';
import ReactDOM from 'react-dom';
import { setComponentsNames, globalizeComponents, promoteInlineExamples, flattenChildren } from './utils/utils';
import StyleGuide from 'rsg-components/StyleGuide';
import 'highlight.js/styles/tomorrow.css';
import './styles.css';
global.React = React;
if (module.hot) {
module.hot.accept();
}
// Load style guide
let { config, components, sections } = require('styleguide!');
function processComponents(cs) {
cs = flattenChildren(cs);
cs = promoteInlineExamples(cs);
cs = setComponentsNames(cs);
globalizeComponents(cs);
return cs;
}
function processSections(ss) {
return ss.map(section => {
section.components = processComponents(section.components || []);
section.sections = processSections(section.sections || []);
return section;
});
}
// Components are required unless sections are provided
if (sections) {
sections = processSections(sections);
components = [];
}
else {
components = processComponents(components);
sections = [];
}
ReactDOM.render(<StyleGuide config={config} components={components} sections={sections} />, document.getElementById('app'));
|
Fix linting issues and duplicate check for components and sections
|
Fix linting issues and duplicate check for components and sections
|
JavaScript
|
mit
|
bluetidepro/react-styleguidist,sapegin/react-styleguidist,sapegin/react-styleguidist,styleguidist/react-styleguidist,styleguidist/react-styleguidist,styleguidist/react-styleguidist
|
069c586ba2a6a33ce830b383931ce32a958498f0
|
src/index.js
|
src/index.js
|
import functionalText from "functional-text";
window.addEventListener("DOMContentLoaded", function () {
let inputNode = document.querySelector("#input");
let outputHtmlNode = document.querySelector("#output-html");
let str = `Sample Text for parsing`.trim();
inputNode.value = str;
inputNode.style.height = '200px';
inputNode.style.width = '100%';
function runParser() {
let parsedHtml = functionalText(inputNode.value);
outputHtmlNode.innerHTML = parsedHtml.replace(/</g, "<").replace(/>/g, ">");
}
inputNode.addEventListener("input", runParser, 200);
try {
runParser();
} catch (err) {
console.error(err);
}
});
|
import functionalText from "functional-text";
window.addEventListener("DOMContentLoaded", function () {
let inputNode = document.querySelector("#input");
let outputHtmlNode = document.querySelector("#output-html");
let str = `Sample Text for parsing`.trim();
inputNode.value = str;
inputNode.style.height = '200px';
inputNode.style.width = '100%';
function runParser() {
try {
let parsedHtml = functionalText(inputNode.value);
outputHtmlNode.style.borderColor = "black";
outputHtmlNode.innerHTML = parsedHtml.replace(/</g, "<").replace(/>/g, ">");
} catch (error) {
outputHtmlNode.style.borderColor = "red";
outputHtmlNode.innerHTML = error;
}
}
inputNode.addEventListener("input", runParser, 200);
runParser();
});
|
Move try-catch into the parsing logic, and display errors into the output.
|
Move try-catch into the parsing logic, and display errors into the
output.
|
JavaScript
|
mit
|
measurement-factory/functional-text-sandbox,measurement-factory/functional-text-sandbox,measurement-factory/functional-text-sandbox
|
ec8cc8b69d872fbaf6898e30aa03f96cccbaef92
|
src/index.js
|
src/index.js
|
import React from 'react';
import { render } from 'react-dom';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import App from './components/app';
import rootReducer from './reducers'
const store = createStore(rootReducer);
render(
<Provider store={store}>
<App />
</Provider>, document.getElementById('app'));
|
import React from 'react';
import { render } from 'react-dom';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';
import App from './components/app';
import rootReducer from './reducers'
const createStoreWithMiddleware = applyMiddleware(thunk)(createStore);
render(
<Provider store={createStoreWithMiddleware(rootReducer)}>
<App />
</Provider>, document.getElementById('app'));
|
Update React app entry point: Add middleware to the project Use redux-thunk lib Applies middleware and use it as store
|
Update React app entry point:
Add middleware to the project
Use redux-thunk lib
Applies middleware and use it as store
|
JavaScript
|
mit
|
Jesus-Gonzalez/ReactReduxTestNumberTwo,Jesus-Gonzalez/ReactReduxTestNumberTwo
|
61f4570bd931d2318489661ecf32dd482e008980
|
src/index.js
|
src/index.js
|
import React from 'react';
import App from './app/App';
React.render(<App />, document.body);
|
import React from 'react';
import ReactDOM from 'react-dom';
import App from './app/App';
const appRoot = document.createElement('div');
appRoot.id = 'app';
document.body.appendChild(appRoot);
ReactDOM.render(<App />, appRoot);
|
Update App rendering to comply with React 0.14
|
Update App rendering to comply with React 0.14
|
JavaScript
|
mit
|
nkbt/esnext-quickstart,halhenke/life-letters
|
980fbb4f7f5ca3613a01182d5338d6eae7a98e04
|
src/index.js
|
src/index.js
|
import glob from 'glob'
import path from 'path'
import Dns from './dns'
import { name as packageName } from '../package.json'
export default () => {
const dns = new Dns()
// Load Plugins
glob(
`./node_modules/${packageName}-plugin-*`,
( err, files ) => {
files
.forEach(
( plugin ) => {
plugin = path.basename( plugin )
const instance = eval('require')( plugin )
if ( instance && instance.default )
new instance.default( dns )
else if ( instance ) {
new instance( dns )
}
}
)
// Finally start the DNS daemon
dns.start()
}
)
}
|
import { exec } from 'child_process'
import glob from 'glob'
import path from 'path'
import Dns from './dns'
import { name as packageName } from '../package.json'
const dns = new Dns()
function getNodeModulesPath( isGlobal ) {
return new Promise (
( resolve, reject ) => {
if ( isGlobal )
exec(
`npm config get prefix -g`,
( err, stdout, stderr ) => {
if ( err ) reject( err )
else if ( stderr ) reject ( stderr )
else resolve( stdout )
}
)
else
resolve(
`${path.resolve()}/node_modules`
)
}
)
}
function loadPlugins( pluginPath ) {
return new Promise (
( resolve, reject ) => {
// Load Plugins
glob(
`${pluginPath}/${packageName}-plugin-*`,
( err, files ) => {
if ( err ) reject( err )
else {
files
.forEach(
( plugin ) => {
plugin = path.basename( plugin )
const instance = eval('require')( plugin )
if ( instance && instance.default )
new instance.default( dns )
else if ( instance ) {
new instance( dns )
}
}
)
// Finally resolve
resolve()
}
}
)
}
)
}
export default () => {
Promise.resolve()
.catch( err => console.log( err ) )
// Load global plugins
.then( () => getNodeModulesPath( true ) )
.then( path => loadPlugins( path ) )
// Load local plugins
.then( () => getNodeModulesPath() )
.then( path => loadPlugins( path ) )
// Start the DNS
.then( () => dns.start() )
}
|
Allow loading of local and global plugins
|
Allow loading of local and global plugins
|
JavaScript
|
mit
|
dynsdjs/dynsdjs,julianxhokaxhiu/zeroads
|
68d25860580b56f20ed8902917b3a10591d3462d
|
src/index.js
|
src/index.js
|
import R from 'ramda';
import And from './and';
import Or from './or';
import Conjunction from './conjunction';
/**
* Check if the given object is an object-like `And` conjunction.
* @param {Object} obj
* @param {String} obj.type
* @returns {Boolean}
*/
const objectIsAndConjunction = R.compose(
R.equals(And.type()),
R.prop('type')
);
/**
* Check if the given object is an object-like `Or` conjunction.
* @param {Object} obj
* @param {String} obj.type
* @returns {Boolean}
*/
const objectIsOrConjunction = R.compose(
R.equals(Or.type()),
R.prop('type')
);
const create = obj => {
if (objectIsOrConjunction(obj)) {
return new Or(obj.mappings);
} else if (objectIsAndConjunction(obj)) {
return new And(obj.mappings);
} else {
var message = 'Cannot create conjunction based on ' + obj;
throw new Error(message);
}
}
export default {
create,
And,
Or,
Conjunction
};
|
import R from 'ramda';
import And from './and';
import Or from './or';
import Conjunction from './conjunction';
/**
* Check if the given object is an object-like `And` conjunction.
* @param {Object} obj
* @param {String} obj.type
* @returns {Boolean}
*/
const objectIsAndConjunction = R.compose(
R.equals(And.type()),
R.prop('type')
);
/**
* Check if the given object is an object-like `Or` conjunction.
* @param {Object} obj
* @param {String} obj.type
* @returns {Boolean}
*/
const objectIsOrConjunction = R.compose(
R.equals(Or.type()),
R.prop('type')
);
const create = obj => {
if (objectIsOrConjunction(obj)) {
return new Or(obj.mappings);
} else if (objectIsAndConjunction(obj)) {
return new And(obj.mappings);
} else {
var message = 'Cannot create conjunction based on ' + obj;
throw new Error(message);
}
}
module.exports = {
create,
And,
Or,
Conjunction
};
export default module.exports
|
Add support to old module.exports (webpack has issue with it)
|
Add support to old module.exports (webpack has issue with it)
|
JavaScript
|
mit
|
sendyhalim/noes
|
080e9f84d5bc7c1b476b2c41cc3b84fafb9451ca
|
src/index.js
|
src/index.js
|
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, browserHistory } from 'react-router';
import App from './App';
import Board from './Board';
import './styles/index.css';
ReactDOM.render(
<Router history={browserHistory}>
<Route path="/" component={App}>
<Route path="boards/:abbreviation/" component={Board}>
{/*<Route path="boards/:abbreviation/" component={ThreadList} />*/}
<Route path=":thread/" />
</Route>
</Route>
</Router>,
document.getElementById('root')
);
|
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, browserHistory } from 'react-router';
import App from './App';
import Board from './Board';
import './styles/index.css';
ReactDOM.render(
<Router history={browserHistory}>
<Route path="/" component={App}>
<Route path="boards/:abbreviation/" component={Board}>
<Route path=":threadId" />
</Route>
</Route>
</Router>,
document.getElementById('root')
);
|
Fix bug with Board not realizing it's in a thread view
|
Fix bug with Board not realizing it's in a thread view
|
JavaScript
|
mit
|
drop-table-ryhmatyo/tekislauta-front,drop-table-ryhmatyo/tekislauta-front
|
558f6a65dac8908376dabaee78e3c590af0d59b8
|
exercises/mock-box-view.js
|
exercises/mock-box-view.js
|
var extend = require('extend')
var bv, createClient
module.exports.mock = function (mocks) {
var boxview = 'box-view'
bv = require(boxview)
createClient = bv.createClient
bv.createClient = function (token) {
if (token === 'your api token') {
throw new Error('(HINT) remember to replace "your api token" with your Box View token!')
}
var client = createClient(token)
, mock = extend(true, {}, client, mocks)
mock.documents.__ = client.documents
mock.sessions.__ = client.sessions
return mock
}
}
module.exports.restore = function () {
if (bv) {
bv.createClient = createClient
}
}
|
var extend = require('extend')
var bv, createClient
module.exports.mock = function (mocks, creator) {
var boxview = 'box-view'
bv = require(boxview)
createClient = bv.createClient
bv.createClient = function (token) {
if (token === 'your api token') {
throw new Error('(HINT) remember to replace "your api token" with your Box View token!')
}
var client = createClient(token)
, mock = extend(true, {}, client, mocks)
mock.documents.__ = client.documents
mock.sessions.__ = client.sessions
client.token = token
mock.documents.__client = client
mock.sessions.__client = client
return creator(mock, token)
}
}
module.exports.restore = function () {
if (bv) {
bv.createClient = createClient
}
}
|
Add token and client reference to box-view mock
|
Add token and client reference to box-view mock
|
JavaScript
|
mit
|
lakenen/view-school,lakenen/view-school
|
1d6341af12b86001732d0cc06af7bf2880049676
|
test/trie.js
|
test/trie.js
|
var Trie = require('../app/trie');
describe('Trie', function() {
var trie;
beforeEach(function() {
trie = new Trie();
});
it('should be an object', function() {
expect(trie).to.be.ok;
});
it('should have add method', function() {
expect(trie.add).to.be.an.instanceof(Function);
});
it('should have search method', function() {
expect(trie.search).to.be.an.instanceof(Function);
});
it('should have find method', function() {
expect(trie.find).to.be.an.instanceof(Function);
});
});
|
var Trie = require('../app/trie');
describe('Trie', function() {
var trie;
beforeEach(function() {
trie = new Trie();
});
it('should be an object', function() {
expect(trie).to.be.ok;
});
it('should have a root', function() {
expect(trie.root).to.be.ok;
});
it('should have add method', function() {
expect(trie.add).to.be.an.instanceof(Function);
});
it('should have search method', function() {
expect(trie.search).to.be.an.instanceof(Function);
});
it('should have find method', function() {
expect(trie.find).to.be.an.instanceof(Function);
});
});
|
Add check for root variable in Trie
|
Add check for root variable in Trie
|
JavaScript
|
mit
|
mgarbacz/nordrassil,mgarbacz/nordrassil
|
71af45da5cdceb6e8e377ab2c3641b40dfb8c441
|
src/utils.js
|
src/utils.js
|
export function extractAttributes(el) {
const map = el.hasAttributes() ? el.attributes : []
const attrs = {}
for (let i = 0; i < map.length; i++) {
const attr = map[i]
if (attr.value) {
attrs[attr.name] = attr.value === '' ? true : attr.value
}
}
let klass, style
if (attrs.class) {
klass = attrs.class
delete attrs.class
}
if (attrs.style) {
style = attrs.style
delete attrs.style
}
const data = {
attrs,
class: klass,
style,
}
return data
}
export function freeze(item) {
if (Array.isArray(item) || typeof item === 'object') {
return Object.freeze(item)
}
return item
}
export function combinePassengers(transports, slotProps = {}) {
return transports.reduce((passengers, transport) => {
let newPassengers = transport.passengers[0]
newPassengers =
typeof newPassengers === 'function'
? newPassengers(slotProps)
: newPassengers
return passengers.concat(newPassengers)
}, [])
}
|
export function extractAttributes(el) {
const map = el.hasAttributes() ? el.attributes : []
const attrs = {}
for (let i = 0; i < map.length; i++) {
const attr = map[i]
if (attr.value) {
attrs[attr.name] = attr.value === '' ? true : attr.value
}
}
let klass, style
if (attrs.class) {
klass = attrs.class
delete attrs.class
}
if (attrs.style) {
style = attrs.style
delete attrs.style
}
const data = {
attrs,
class: klass,
style,
}
return data
}
export function freeze(item) {
if (Array.isArray(item) || typeof item === 'object') {
return Object.freeze(item)
}
return item
}
export function combinePassengers(transports, slotProps = {}) {
return transports.reduce((passengers, transport) => {
let newPassengers = transport.passengers[0]
newPassengers =
typeof newPassengers === 'function'
? newPassengers(slotProps)
: transport.passengers
return passengers.concat(newPassengers)
}, [])
}
|
Fix bug wher only one element was returned
|
Fix bug wher only one element was returned
|
JavaScript
|
mit
|
LinusBorg/portal-vue,LinusBorg/portal-vue,LinusBorg/portal-vue
|
636863f5b8fcff8e7cfc000349f5167b51b9544c
|
public/app/routes/application.js
|
public/app/routes/application.js
|
/*
Copyright, 2013, by Tomas Korcak. <korczis@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
(function (global) {
require
(
["ember", "app"], function (Ember, App) {
App.ApplicationRoute = Ember.Route.extend({
title: "Microscratch",
model: function() {
},
setupController: function(controller, model) {
}
});
App.ApplicationController = Ember.Controller.extend({
});
App.ApplicationView = Ember.View.extend({
classNames: ['app-view'],
templateName: "application",
/**
* Called when inserted to DOM.
* @memberof Application.ApplicationView
* @instance
*/
didInsertElement: function () {
console.log("App.ApplicationView.didInsertElement()");
}
});
}
);
})(this);
|
/*
Copyright, 2013, by Tomas Korcak. <korczis@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
(function (global) {
require
(
["ember", "app"], function (Ember, App) {
App.ApplicationView = Ember.View.extend({
classNames: ['app-view'],
templateName: "application",
/**
* Called when inserted to DOM.
* @memberof Application.ApplicationView
* @instance
*/
didInsertElement: function () {
console.log("App.ApplicationView.didInsertElement()");
}
});
}
);
})(this);
|
Remove empty route and controller
|
Remove empty route and controller
|
JavaScript
|
mit
|
pavelbinar/craftsmen,zadr007/BLUEjs,pavelbinar/craftsmen,zadr007/BLUEjs
|
3844217c602b329d9a98a620de6576124f94c21b
|
test/init.js
|
test/init.js
|
global.assert = require('assert');
global.chai = require("chai");
global.chaiAsPromised = require("chai-as-promised");
global.jsf = require('json-schema-faker');
global.should = require('should');
global.sinon = require('sinon');
// Load schemas
global.mocks = require('./mocks');
// Run the tests
require('./unit');
|
global.assert = require('assert');
global.chai = require("chai");
global.chaiAsPromised = require("chai-as-promised");
global.jsf = require('json-schema-faker');
global.should = require('should');
global.sinon = require('sinon');
global._ = require('lodash');
// Load schemas
global.mocks = require('./mocks');
// Run the tests
require('./unit');
|
Add lodash access in global scope
|
Add lodash access in global scope
|
JavaScript
|
mit
|
facundovictor/mocha-testing
|
945adf03719a67d7fe65b9dafcd6a1aa1fe31dcb
|
app/assets/javascripts/roots/application.js
|
app/assets/javascripts/roots/application.js
|
function clearAndHideResultTable() {
var header = $('table.matching-term .header');
$('table.matching-term').html(header);
$('table.matching-term').hide();
}
function hideNoResults() {
$('.no-results').hide();
}
function showNoResults() {
$('.no-results').show();
}
function showResultTable() {
hideNoResults();
$('table.matching-term').show();
}
function searchResults(query) {
clearAndHideResultTable();
var found = $('[data-search*=' + query).parent('tr');
return found;
}
function addToResultTable(result){
showResultTable();
var table = $('.matching-term');
var lastChild = table.find('tr:last');
if(lastChild.length == 0) {
table.html(result);
}
else {
lastChild.after(result);
}
}
$(document).on('ready', function(){
$('input[name=search]').keyup(function(event){
var searchTerm = event.target.value;
if(searchTerm.length > 0) {
hideNoResults();
var results = searchResults(searchTerm.toLowerCase());
if (results.length > 0) {
$.each(results, function(index, value){
addToResultTable($(value).clone());
});
}
else {
showNoResults();
}
}
else {
hideNoResults();
clearAndHideResultTable();
}
});
});
|
DomElements = {
matchingTerm: 'table.matching-term'
};
function clearAndHideResultTable() {
var header = $('table.matching-term .header');
$(DomElements.matchingTerm).html(header);
$(DomElements.matchingTerm).hide();
}
function hideNoResults() {
$('.no-results').hide();
}
function showNoResults() {
$('.no-results').show();
}
function showResultTable() {
hideNoResults();
$(DomElements.matchingTerm).show();
}
function searchResults(query) {
clearAndHideResultTable();
var found = $('[data-search*=' + query).parent('tr');
return found;
}
function addToResultTable(result){
showResultTable();
var table = $('.matching-term');
var lastChild = table.find('tr:last');
if(lastChild.length == 0) {
table.html(result);
}
else {
lastChild.after(result);
}
}
$(document).on('ready', function(){
$('input[name=search]').keyup(function(event){
var searchTerm = event.target.value;
if(searchTerm.length > 0) {
hideNoResults();
var results = searchResults(searchTerm.toLowerCase());
if (results.length > 0) {
$.each(results, function(index, value){
addToResultTable($(value).clone());
});
}
else {
showNoResults();
}
}
else {
hideNoResults();
clearAndHideResultTable();
}
});
});
|
Add JS lookup to object
|
Add JS lookup to object
|
JavaScript
|
mit
|
yez/roots,yez/passages,yez/roots,yez/passages,yez/passages,yez/roots
|
4d685b2ffe124c2b3e5b3a8187c4b31a56518c13
|
packages/mendel-config/src/variation-config.js
|
packages/mendel-config/src/variation-config.js
|
const parseVariations = require('../variations');
const createValidator = require('./validator');
const validate = createValidator({
variations: {type: 'array', minLen: 1},
// There can be a user of Mendel who does not want variation but faster build.
allVariationDirs: {type: 'array', minLen: 0},
allDirs: {type: 'array', minLen: 1},
});
function VariationConfig(config) {
const variations = parseVariations(config);
const allVariationDirs = getAllDirs(variations);
const baseVariation = {
id: config.baseConfig.id,
chain: [config.baseConfig.dir],
};
variations.push(baseVariation);
const allDirs = getAllDirs(variations);
const variationConfig = {
variations,
baseVariation,
allDirs,
allVariationDirs,
};
validate(variationConfig);
return variationConfig;
}
function getAllDirs(variationArray) {
return variationArray.reduce((allDirs, variation) => {
variation.chain.forEach(dir => {
if (!allDirs.includes(dir)) allDirs.push(dir);
});
return allDirs;
}, []);
}
module.exports = VariationConfig;
|
const parseVariations = require('../variations');
const createValidator = require('./validator');
const validate = createValidator({
variations: {type: 'array', minLen: 1},
// There can be a user of Mendel who does not want variation but faster build.
allVariationDirs: {type: 'array', minLen: 0},
allDirs: {type: 'array', minLen: 1},
});
function VariationConfig(config) {
const variations = parseVariations(config);
const allVariationDirs = getAllDirs(variations);
const baseVariation = {
id: config.baseConfig.id,
chain: [config.baseConfig.dir],
};
// base variation must come first in order to variationMatches to work
variations.unshift(baseVariation);
const allDirs = getAllDirs(variations);
const variationConfig = {
variations,
baseVariation,
allDirs,
allVariationDirs,
};
validate(variationConfig);
return variationConfig;
}
function getAllDirs(variationArray) {
return variationArray.reduce((allDirs, variation) => {
variation.chain.forEach(dir => {
if (!allDirs.includes(dir)) allDirs.push(dir);
});
return allDirs;
}, []);
}
module.exports = VariationConfig;
|
Fix base files identified as wrong variation
|
Fix base files identified as wrong variation
|
JavaScript
|
mit
|
stephanwlee/mendel,yahoo/mendel,stephanwlee/mendel,yahoo/mendel
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.