commit stringlengths 40 40 | old_file stringlengths 4 150 | new_file stringlengths 4 150 | old_contents stringlengths 0 3.26k | new_contents stringlengths 1 4.43k | subject stringlengths 15 501 | message stringlengths 15 4.06k | lang stringclasses 4 values | license stringclasses 13 values | repos stringlengths 5 91.5k | diff stringlengths 0 4.35k |
|---|---|---|---|---|---|---|---|---|---|---|
e2fac6bb350ac744eb8ea66f8ff227e3d09ecaf7 | test/groupexists.js | test/groupexists.js | var assert = require('assert');
var ActiveDirectory = require('../index');
var config = require('./config');
describe('ActiveDirectory', function() {
describe('#groupExists()', function() {
var ad;
var settings = require('./settings').groupExists;
beforeEach(function() {
ad = new ActiveDirectory(config);
});
it('should return true if the groupName (commonName) exists', function(done) {
ad.groupExists(settings.sAMAccountName, settings.groupName.cn, function(err, exists) {
if (err) return(done(err));
assert(exists);
done();
});
});
it('should return true if the groupName (distinguishedName) exists', function(done) {
ad.groupExists(settings.sAMAccountName, settings.groupName.dn, function(err, exists) {
if (err) return(done(err));
assert(exists);
done();
});
});
it('should return false if the groupName doesn\'t exist', function(done) {
ad.groupExists(settings.sAMAccountName, '!!!NON-EXISTENT GROUP!!!', function(err, exists) {
if (err) return(done(err));
assert(! exists);
done();
});
});
});
});
| Add unit tests for groupExists() method call. | Add unit tests for groupExists() method call.
| JavaScript | mit | jsumners/node-activedirectory,BenPaster/node-activedirectory,gheeres/node-activedirectory,kattsushi/node-activedirectory | ---
+++
@@ -0,0 +1,37 @@
+var assert = require('assert');
+var ActiveDirectory = require('../index');
+var config = require('./config');
+
+describe('ActiveDirectory', function() {
+ describe('#groupExists()', function() {
+ var ad;
+ var settings = require('./settings').groupExists;
+
+ beforeEach(function() {
+ ad = new ActiveDirectory(config);
+ });
+
+ it('should return true if the groupName (commonName) exists', function(done) {
+ ad.groupExists(settings.sAMAccountName, settings.groupName.cn, function(err, exists) {
+ if (err) return(done(err));
+ assert(exists);
+ done();
+ });
+ });
+ it('should return true if the groupName (distinguishedName) exists', function(done) {
+ ad.groupExists(settings.sAMAccountName, settings.groupName.dn, function(err, exists) {
+ if (err) return(done(err));
+ assert(exists);
+ done();
+ });
+ });
+ it('should return false if the groupName doesn\'t exist', function(done) {
+ ad.groupExists(settings.sAMAccountName, '!!!NON-EXISTENT GROUP!!!', function(err, exists) {
+ if (err) return(done(err));
+ assert(! exists);
+ done();
+ });
+ });
+ });
+});
+ | |
18dd550415a86928b8a5bd1ddc0c6963d57172ad | app/app.js | app/app.js | (function(){
angular.module('MeanSocial', ['ui.router'])
.config(function ($stateProvider) {
$stateProvider
.state('signUp', {
url: '/signup',
templateUrl: "app/signup/signup.html",
controller: 'SignUpController'
});
});
}());
| Add signup state; inject ui-router | Add signup state; inject ui-router
| JavaScript | mit | DavidMax/mean-social,DavidMax/mean-social | ---
+++
@@ -0,0 +1,12 @@
+(function(){
+ angular.module('MeanSocial', ['ui.router'])
+ .config(function ($stateProvider) {
+
+ $stateProvider
+ .state('signUp', {
+ url: '/signup',
+ templateUrl: "app/signup/signup.html",
+ controller: 'SignUpController'
+ });
+ });
+}()); | |
c70d24c5f3492c85734a1975a51af96c3f5c18e9 | test/functional/realtime-session.js | test/functional/realtime-session.js | import SocketIO from 'socket.io-client';
const eventTimeout = 2000;
const silenceTimeout = 500;
/**
* Session is a helper class
* for the realtime testing
*/
export default class Session {
socket = null;
name = '';
static create(port, name = '') {
const options = {
transports: ['websocket'],
'force new connection': true,
};
return new Promise((resolve, reject) => {
const socket = SocketIO.connect(`http://localhost:${port}/`, options);
socket.on('error', reject);
socket.on('connect_error', reject);
socket.on('connect', () => resolve(new Session(socket, name)));
});
}
constructor(socket, name = '') {
this.socket = socket;
this.name = name;
}
send(event, data) {
this.socket.emit(event, data);
}
disconnect() {
this.socket.disconnect();
}
receive(event) {
return new Promise((resolve, reject) => {
const success = (data) => {
this.socket.off(event, success);
clearTimeout(timer);
resolve(data);
};
this.socket.on(event, success);
const timer = setTimeout(() => reject(new Error(`${this.name ? `${this.name}: ` : ''}Expecting '${event}' event, got timeout`)), eventTimeout);
});
}
notReceive(event) {
return new Promise((resolve, reject) => {
const fail = () => {
this.socket.off(event, fail);
clearTimeout(timer);
reject(new Error(`${this.name ? `${this.name}: ` : ''}Expecting silence, got '${event}' event`));
};
this.socket.on(event, fail);
const timer = setTimeout(() => resolve(null), silenceTimeout);
});
}
}
| Add a helper class for simplyfy realtime testing | Add a helper class for simplyfy realtime testing
| JavaScript | mit | FreeFeed/freefeed-server,FreeFeed/freefeed-server | ---
+++
@@ -0,0 +1,63 @@
+import SocketIO from 'socket.io-client';
+
+const eventTimeout = 2000;
+const silenceTimeout = 500;
+
+/**
+ * Session is a helper class
+ * for the realtime testing
+ */
+export default class Session {
+ socket = null;
+ name = '';
+
+ static create(port, name = '') {
+ const options = {
+ transports: ['websocket'],
+ 'force new connection': true,
+ };
+ return new Promise((resolve, reject) => {
+ const socket = SocketIO.connect(`http://localhost:${port}/`, options);
+ socket.on('error', reject);
+ socket.on('connect_error', reject);
+ socket.on('connect', () => resolve(new Session(socket, name)));
+ });
+ }
+
+ constructor(socket, name = '') {
+ this.socket = socket;
+ this.name = name;
+ }
+
+ send(event, data) {
+ this.socket.emit(event, data);
+ }
+
+ disconnect() {
+ this.socket.disconnect();
+ }
+
+ receive(event) {
+ return new Promise((resolve, reject) => {
+ const success = (data) => {
+ this.socket.off(event, success);
+ clearTimeout(timer);
+ resolve(data);
+ };
+ this.socket.on(event, success);
+ const timer = setTimeout(() => reject(new Error(`${this.name ? `${this.name}: ` : ''}Expecting '${event}' event, got timeout`)), eventTimeout);
+ });
+ }
+
+ notReceive(event) {
+ return new Promise((resolve, reject) => {
+ const fail = () => {
+ this.socket.off(event, fail);
+ clearTimeout(timer);
+ reject(new Error(`${this.name ? `${this.name}: ` : ''}Expecting silence, got '${event}' event`));
+ };
+ this.socket.on(event, fail);
+ const timer = setTimeout(() => resolve(null), silenceTimeout);
+ });
+ }
+} | |
1e1b0f3563c758f583cb3f00eaf1b2b7fcf0bff9 | tests/e2e/matchers/to-be-checked.js | tests/e2e/matchers/to-be-checked.js | /**
* Custom matcher for testing if a checkbox is checked or not.
*
* Site Kit by Google, Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* External dependencies
*/
import { getDefaultOptions } from 'expect-puppeteer';
/**
* Asserts the given selector is checked.
*
* @since n.e.x.t
*
* @param {string} selector Selector for element with value.
* @param {Object} [options] Matcher options.
* @param {number} [options.timeout] Maximum time to wait for selector in milliseconds.
* @return {Object} Object with `pass` and `message` keys.
*/
export async function toBeChecked( selector, { timeout } = getDefaultOptions() ) {
let pass, message;
await page.waitForSelector( selector, { timeout } );
const actualValue = await page.$eval( selector, ( { checked } ) => checked );
if ( this.equals( true, actualValue ) ) {
pass = true;
message = `Expected "${ selector }" to be checked.`;
} else {
pass = false;
message = `Expected ${ selector } not to be checked.`;
}
return { pass, message };
}
| Add toBeChecked custom matcher for E2E. | Add toBeChecked custom matcher for E2E.
| JavaScript | apache-2.0 | google/site-kit-wp,google/site-kit-wp,google/site-kit-wp,google/site-kit-wp | ---
+++
@@ -0,0 +1,49 @@
+/**
+ * Custom matcher for testing if a checkbox is checked or not.
+ *
+ * Site Kit by Google, Copyright 2020 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * External dependencies
+ */
+import { getDefaultOptions } from 'expect-puppeteer';
+
+/**
+ * Asserts the given selector is checked.
+ *
+ * @since n.e.x.t
+ *
+ * @param {string} selector Selector for element with value.
+ * @param {Object} [options] Matcher options.
+ * @param {number} [options.timeout] Maximum time to wait for selector in milliseconds.
+ * @return {Object} Object with `pass` and `message` keys.
+ */
+export async function toBeChecked( selector, { timeout } = getDefaultOptions() ) {
+ let pass, message;
+
+ await page.waitForSelector( selector, { timeout } );
+ const actualValue = await page.$eval( selector, ( { checked } ) => checked );
+
+ if ( this.equals( true, actualValue ) ) {
+ pass = true;
+ message = `Expected "${ selector }" to be checked.`;
+ } else {
+ pass = false;
+ message = `Expected ${ selector } not to be checked.`;
+ }
+
+ return { pass, message };
+} | |
533d1dd6f31fc174d9620ae935f19d0311c261db | js/Utilities/BackAndroid.windows.js | js/Utilities/BackAndroid.windows.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule BackAndroid
*/
'use strict';
var DeviceEventManager = require('NativeModules').DeviceEventManager;
var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter');
var DEVICE_BACK_EVENT = 'hardwareBackPress';
type BackPressEventName = $Enum<{
backPress: string;
}>;
var _backPressSubscriptions = new Set();
RCTDeviceEventEmitter.addListener(DEVICE_BACK_EVENT, function() {
var backPressSubscriptions = new Set(_backPressSubscriptions);
var invokeDefault = true;
backPressSubscriptions.forEach((subscription) => {
if (subscription()) {
invokeDefault = false;
}
});
if (invokeDefault) {
BackAndroid.exitApp();
}
});
/**
* Detect hardware back button presses, and programmatically invoke the default back button
* functionality to exit the app if there are no listeners or if none of the listeners return true.
*
* Example:
*
* ```js
* BackAndroid.addEventListener('hardwareBackPress', function() {
* if (!this.onMainScreen()) {
* this.goBack();
* return true;
* }
* return false;
* });
* ```
*/
var BackAndroid = {
exitApp: function() {
DeviceEventManager.invokeDefaultBackPressHandler();
},
addEventListener: function (
eventName: BackPressEventName,
handler: Function
): {remove: () => void} {
_backPressSubscriptions.add(handler);
return {
remove: () => BackAndroid.removeEventListener(eventName, handler),
};
},
removeEventListener: function(
eventName: BackPressEventName,
handler: Function
): void {
_backPressSubscriptions.delete(handler);
},
};
module.exports = BackAndroid; | Add BackAndroid JS module for Windows platform | feat(BackAndroid): Add BackAndroid JS module for Windows platform
The BackAndroid module provides a JS API for the native DeviceEventEmitter module to hook into back-button presses. This is needed, e.g., for Navigator.
Fixes #246
| JavaScript | mit | lbochenek/react-native-windows,lbochenek/react-native-windows,lbochenek/react-native-windows,lbochenek/react-native-windows | ---
+++
@@ -0,0 +1,79 @@
+/**
+ * Copyright (c) 2015-present, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule BackAndroid
+ */
+
+'use strict';
+
+var DeviceEventManager = require('NativeModules').DeviceEventManager;
+var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter');
+
+var DEVICE_BACK_EVENT = 'hardwareBackPress';
+
+type BackPressEventName = $Enum<{
+ backPress: string;
+}>;
+
+var _backPressSubscriptions = new Set();
+
+RCTDeviceEventEmitter.addListener(DEVICE_BACK_EVENT, function() {
+ var backPressSubscriptions = new Set(_backPressSubscriptions);
+ var invokeDefault = true;
+ backPressSubscriptions.forEach((subscription) => {
+ if (subscription()) {
+ invokeDefault = false;
+ }
+ });
+ if (invokeDefault) {
+ BackAndroid.exitApp();
+ }
+});
+
+/**
+ * Detect hardware back button presses, and programmatically invoke the default back button
+ * functionality to exit the app if there are no listeners or if none of the listeners return true.
+ *
+ * Example:
+ *
+ * ```js
+ * BackAndroid.addEventListener('hardwareBackPress', function() {
+ * if (!this.onMainScreen()) {
+ * this.goBack();
+ * return true;
+ * }
+ * return false;
+ * });
+ * ```
+ */
+var BackAndroid = {
+
+ exitApp: function() {
+ DeviceEventManager.invokeDefaultBackPressHandler();
+ },
+
+ addEventListener: function (
+ eventName: BackPressEventName,
+ handler: Function
+ ): {remove: () => void} {
+ _backPressSubscriptions.add(handler);
+ return {
+ remove: () => BackAndroid.removeEventListener(eventName, handler),
+ };
+ },
+
+ removeEventListener: function(
+ eventName: BackPressEventName,
+ handler: Function
+ ): void {
+ _backPressSubscriptions.delete(handler);
+ },
+
+};
+
+module.exports = BackAndroid; | |
651cd79f2ae92afeff6c519cdf30472b82c1a830 | webpack-hot-only-dev-server.js | webpack-hot-only-dev-server.js | // Modified copy of https://github.com/webpack/webpack/blob/v1.11.0/hot/only-dev-server.js
// (Added window.instrumentCodeGroupAsyncTopLevel)
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
/*globals window __webpack_hash__ */
if(module.hot) {
var lastData;
var upToDate = function upToDate() {
return lastData.indexOf(__webpack_hash__) >= 0;
};
var check = function check() {
module.hot.check(function(err, updatedModules) {
if(err) {
if(module.hot.status() in {
abort: 1,
fail: 1
}) {
console.warn("[HMR] Cannot check for update. Need to do a full reload!");
console.warn("[HMR] " + err.stack || err.message);
} else {
console.warn("[HMR] Update check failed: " + err.stack || err.message);
}
return;
}
if(!updatedModules) {
console.warn("[HMR] Cannot find update. Need to do a full reload!");
console.warn("[HMR] (Probably because of restarting the webpack-dev-server)");
return;
}
window.instrumentCodeGroupAsyncTopLevel('Webpack HMR', 'Webpack Hot Module Replacement', function() {
module.hot.apply({
ignoreUnaccepted: true
}, function(err, renewedModules) {
if(err) {
if(module.hot.status() in {
abort: 1,
fail: 1
}) {
console.warn("[HMR] Cannot apply update. Need to do a full reload!");
console.warn("[HMR] " + err.stack || err.message);
} else {
console.warn("[HMR] Update failed: " + err.stack || err.message);
}
return;
}
if(!upToDate()) {
check();
}
require("webpack/hot/log-apply-result")(updatedModules, renewedModules);
if(upToDate()) {
console.log("[HMR] App is up to date.");
}
});
});
});
};
var addEventListener = window.addEventListener ? function(eventName, listener) {
window.addEventListener(eventName, listener, false);
} : function(eventName, listener) {
window.attachEvent("on" + eventName, listener);
};
addEventListener("message", function(event) {
if(typeof event.data === "string" && event.data.indexOf("webpackHotUpdate") === 0) {
lastData = event.data;
if(!upToDate() && module.hot.status() === "idle") {
console.log("[HMR] Checking for updates on the server...");
check();
}
}
});
console.log("[HMR] Waiting for update signal from WDS...");
} else {
throw new Error("[HMR] Hot Module Replacement is disabled.");
}
| Add modified version of a Webpack hot loading file | Add modified version of a Webpack hot loading file
Which makes use of grouping calls, so you don’t get a crazy amount of
top-level calls when re-rendering React components. | JavaScript | mit | janpaul123/omniscient-debugging,Tug/omniscient-debugging | ---
+++
@@ -0,0 +1,82 @@
+// Modified copy of https://github.com/webpack/webpack/blob/v1.11.0/hot/only-dev-server.js
+// (Added window.instrumentCodeGroupAsyncTopLevel)
+
+/*
+ MIT License http://www.opensource.org/licenses/mit-license.php
+ Author Tobias Koppers @sokra
+*/
+/*globals window __webpack_hash__ */
+if(module.hot) {
+ var lastData;
+ var upToDate = function upToDate() {
+ return lastData.indexOf(__webpack_hash__) >= 0;
+ };
+ var check = function check() {
+ module.hot.check(function(err, updatedModules) {
+ if(err) {
+ if(module.hot.status() in {
+ abort: 1,
+ fail: 1
+ }) {
+ console.warn("[HMR] Cannot check for update. Need to do a full reload!");
+ console.warn("[HMR] " + err.stack || err.message);
+ } else {
+ console.warn("[HMR] Update check failed: " + err.stack || err.message);
+ }
+ return;
+ }
+
+ if(!updatedModules) {
+ console.warn("[HMR] Cannot find update. Need to do a full reload!");
+ console.warn("[HMR] (Probably because of restarting the webpack-dev-server)");
+ return;
+ }
+
+ window.instrumentCodeGroupAsyncTopLevel('Webpack HMR', 'Webpack Hot Module Replacement', function() {
+ module.hot.apply({
+ ignoreUnaccepted: true
+ }, function(err, renewedModules) {
+ if(err) {
+ if(module.hot.status() in {
+ abort: 1,
+ fail: 1
+ }) {
+ console.warn("[HMR] Cannot apply update. Need to do a full reload!");
+ console.warn("[HMR] " + err.stack || err.message);
+ } else {
+ console.warn("[HMR] Update failed: " + err.stack || err.message);
+ }
+ return;
+ }
+
+ if(!upToDate()) {
+ check();
+ }
+
+ require("webpack/hot/log-apply-result")(updatedModules, renewedModules);
+
+ if(upToDate()) {
+ console.log("[HMR] App is up to date.");
+ }
+ });
+ });
+ });
+ };
+ var addEventListener = window.addEventListener ? function(eventName, listener) {
+ window.addEventListener(eventName, listener, false);
+ } : function(eventName, listener) {
+ window.attachEvent("on" + eventName, listener);
+ };
+ addEventListener("message", function(event) {
+ if(typeof event.data === "string" && event.data.indexOf("webpackHotUpdate") === 0) {
+ lastData = event.data;
+ if(!upToDate() && module.hot.status() === "idle") {
+ console.log("[HMR] Checking for updates on the server...");
+ check();
+ }
+ }
+ });
+ console.log("[HMR] Waiting for update signal from WDS...");
+} else {
+ throw new Error("[HMR] Hot Module Replacement is disabled.");
+} | |
a4f50092575e1037d2bff0f992df836de797bb2e | src/mpayrollAPI.js | src/mpayrollAPI.js | const Hapi = require("hapi");
let port = 3000;
let ip = 'localhost';
const server = new Hapi.Server();
server.connection({
host: ip,
port: port
});
//Add Routes
server.route({
method: 'POST',
path: '/api_mpayroll/employees',
handler: function(request, reply){
//Stub out sending the employee payload to the employee service
console.log('headers: ',request.headers);
console.log('pathname: ',request.url.pathname);
console.log('payload: ',request.payload);
//Inform requester of success
return reply('1234').code(201);
}
});
server.start((err)=> {
if(err){
console.log(error);
throw err;
}
console.log(`mPayroll API is running at: ${server.info.uri}`)
}); | ADD - Minimal code for mPayroll API | ADD - Minimal code for mPayroll API
| JavaScript | mit | Bill-A/Correctness-DrivenDevelopment | ---
+++
@@ -0,0 +1,36 @@
+const Hapi = require("hapi");
+
+let port = 3000;
+let ip = 'localhost';
+
+const server = new Hapi.Server();
+
+server.connection({
+ host: ip,
+ port: port
+});
+
+//Add Routes
+server.route({
+ method: 'POST',
+ path: '/api_mpayroll/employees',
+ handler: function(request, reply){
+ //Stub out sending the employee payload to the employee service
+ console.log('headers: ',request.headers);
+ console.log('pathname: ',request.url.pathname);
+ console.log('payload: ',request.payload);
+
+
+ //Inform requester of success
+ return reply('1234').code(201);
+ }
+
+});
+
+server.start((err)=> {
+ if(err){
+ console.log(error);
+ throw err;
+ }
+ console.log(`mPayroll API is running at: ${server.info.uri}`)
+}); | |
1e50ee02fb2e7ff80e62e6701fc9f8aa7e35c391 | lib/collections/questionsGroupsCollection.js | lib/collections/questionsGroupsCollection.js | QuestionsGroups = new Mongo.Collection('questionsGroups');
var Schemas = {};
Schemas.QuestionsGroups = new SimpleSchema({
level: {
type: Number,
label: 'Question group level'
},
version: {
type: Number,
label: 'Question group version'
},
deprecated: {
type: Boolean,
label: 'Is the question group deprecated or not'
},
title: {
type: String,
label: 'Question group title'
},
label: {
type: String,
label: 'Question group label',
optional: true
}
});
QuestionsGroups.attachSchema(Schemas.QuestionsGroups);
Meteor.methods({
addAQuestionsGroup: function(questionsGroupData) {
check(questionsGroupData.title, String);
check(questionsGroupData.label, String);
check(questionsGroupData.level, Number);
questionsGroupData.version = 1;
questionsGroupData.deprecated = false;
return QuestionsGroups.insert(questionsGroupData);
},
updateAQuestionsGroup: function(questionsGroupData) {
check(questionsGroupData.questionsGroupId, String);
check(questionsGroupData.title, String);
check(questionsGroupData.label, String);
check(questionsGroupData.level, Number);
check(questionsGroupData.deprecated, Boolean);
return QuestionsGroups.update({ _id: questionsGroupData.questionsGroupId }, {
$set: {
title: questionsGroupData.title,
label: questionsGroupData.label,
level: questionsGroupData.level,
deprecated: questionsGroupData.deprecated
},
$inc: {
version: 1
}
});
}
});
| Add collection managment for the questionsGroup | Add collection managment for the questionsGroup
| JavaScript | mit | EKlore/EKlore,EKlore/EKlore | ---
+++
@@ -0,0 +1,58 @@
+QuestionsGroups = new Mongo.Collection('questionsGroups');
+
+var Schemas = {};
+
+Schemas.QuestionsGroups = new SimpleSchema({
+ level: {
+ type: Number,
+ label: 'Question group level'
+ },
+ version: {
+ type: Number,
+ label: 'Question group version'
+ },
+ deprecated: {
+ type: Boolean,
+ label: 'Is the question group deprecated or not'
+ },
+ title: {
+ type: String,
+ label: 'Question group title'
+ },
+ label: {
+ type: String,
+ label: 'Question group label',
+ optional: true
+ }
+});
+
+QuestionsGroups.attachSchema(Schemas.QuestionsGroups);
+
+Meteor.methods({
+ addAQuestionsGroup: function(questionsGroupData) {
+ check(questionsGroupData.title, String);
+ check(questionsGroupData.label, String);
+ check(questionsGroupData.level, Number);
+ questionsGroupData.version = 1;
+ questionsGroupData.deprecated = false;
+ return QuestionsGroups.insert(questionsGroupData);
+ },
+ updateAQuestionsGroup: function(questionsGroupData) {
+ check(questionsGroupData.questionsGroupId, String);
+ check(questionsGroupData.title, String);
+ check(questionsGroupData.label, String);
+ check(questionsGroupData.level, Number);
+ check(questionsGroupData.deprecated, Boolean);
+ return QuestionsGroups.update({ _id: questionsGroupData.questionsGroupId }, {
+ $set: {
+ title: questionsGroupData.title,
+ label: questionsGroupData.label,
+ level: questionsGroupData.level,
+ deprecated: questionsGroupData.deprecated
+ },
+ $inc: {
+ version: 1
+ }
+ });
+ }
+}); | |
c1ddf25cfecccf75c006f79a38c45c380bb7e65f | bin/run-simple-global-site-test.js | bin/run-simple-global-site-test.js | //
// Ref) https://www.browserstack.com/automate/node#getting-started
//
var webdriver = require('browserstack-webdriver');
var browserstackConf = require('../browserstack-conf.json');
// Input capabilities
var capabilities = {
'browserName' : 'firefox',
'browserstack.user' : browserstackConf['browserstack.user'],
'browserstack.key' : browserstackConf['browserstack.key']
}
var driver = new webdriver.Builder().
usingServer('http://hub.browserstack.com/wd/hub').
withCapabilities(capabilities).
build();
driver.get('http://www.google.com/ncr');
driver.findElement(webdriver.By.name('q')).sendKeys('BrowserStack');
driver.findElement(webdriver.By.name('btnG')).click();
driver.getTitle().then(function(title) {
console.log(title);
});
driver.quit();
| Add a simple global test | Add a simple global test
| JavaScript | mit | kjirou/browserstack-with-express | ---
+++
@@ -0,0 +1,29 @@
+//
+// Ref) https://www.browserstack.com/automate/node#getting-started
+//
+
+var webdriver = require('browserstack-webdriver');
+
+var browserstackConf = require('../browserstack-conf.json');
+
+// Input capabilities
+var capabilities = {
+ 'browserName' : 'firefox',
+ 'browserstack.user' : browserstackConf['browserstack.user'],
+ 'browserstack.key' : browserstackConf['browserstack.key']
+}
+
+var driver = new webdriver.Builder().
+ usingServer('http://hub.browserstack.com/wd/hub').
+ withCapabilities(capabilities).
+ build();
+
+driver.get('http://www.google.com/ncr');
+driver.findElement(webdriver.By.name('q')).sendKeys('BrowserStack');
+driver.findElement(webdriver.By.name('btnG')).click();
+
+driver.getTitle().then(function(title) {
+ console.log(title);
+});
+
+driver.quit(); | |
0fdd3fd1f0df888cf13e1e13e2418307bca407ae | week-7/game.js | week-7/game.js | // Design Basic Game Solo Challenge
// This is a solo challenge
// Your mission description:
// Overall mission:
//You're an astronaut and you need to get back to the spaceship. There is a martian trying to stop you so you have to shoot at him as you make your way back to safety.
// Goals:
//Get back to spaceship while avoiding the martian
//Shoot the martian
// Characters:
//Astronaut
//Martian
// Objects:
//Astronaut
//Properties: x coordinate, y coordinate, shoot, move
//Martian
//Properties: x coordinate, y coordinate
//Spaceship
//Properties: x coordinate, y coordinate
//Raygun
//Properties: x coordinate, y coordinate
// Functions:
//Move astronaut
//This will change his coordinates
//If his coordiantes are the same as the martian, he dies
//If his coordinates are the same as the sapceship, he wins
//Shoot raygun
//This changes the raygun coordinates
//If the raygun coordinates are the same as the martian you win
//Move martial
//This will change his coordinates
// Pseudocode
//Create the astronaut object
//Add properties:
//Add x and y coordinates as propeties set to 0
//shoot: a function that changes the x and y coordinates of the raygun
//IF the raygun coordinates are the same as the martian - you win
//move: a function that changes x and y coordinates of the astronaut and the martian
//IF the coordinates are the same as the martians - you lose
//IF the coordinates are the same as the spaceship - you win
//Create the martian object
//Add x and y coordinates as propeties set to 0
//Create the spaceship object
//Add x and y coordinates as propeties set to 0
//Create the raygun object
//Add x and y coordinates as propeties set to 0
// Initial Code
// Refactored Code
// Reflection
//
//
//
//
//
//
//
// | Add mission outline and pseudocode | Add mission outline and pseudocode
| JavaScript | mit | cstallings1/phase-0,cstallings1/phase-0,cstallings1/phase-0 | ---
+++
@@ -0,0 +1,73 @@
+// Design Basic Game Solo Challenge
+
+// This is a solo challenge
+
+// Your mission description:
+// Overall mission:
+ //You're an astronaut and you need to get back to the spaceship. There is a martian trying to stop you so you have to shoot at him as you make your way back to safety.
+// Goals:
+ //Get back to spaceship while avoiding the martian
+ //Shoot the martian
+// Characters:
+ //Astronaut
+ //Martian
+// Objects:
+ //Astronaut
+ //Properties: x coordinate, y coordinate, shoot, move
+ //Martian
+ //Properties: x coordinate, y coordinate
+ //Spaceship
+ //Properties: x coordinate, y coordinate
+ //Raygun
+ //Properties: x coordinate, y coordinate
+// Functions:
+ //Move astronaut
+ //This will change his coordinates
+ //If his coordiantes are the same as the martian, he dies
+ //If his coordinates are the same as the sapceship, he wins
+ //Shoot raygun
+ //This changes the raygun coordinates
+ //If the raygun coordinates are the same as the martian you win
+ //Move martial
+ //This will change his coordinates
+
+// Pseudocode
+//Create the astronaut object
+ //Add properties:
+ //Add x and y coordinates as propeties set to 0
+ //shoot: a function that changes the x and y coordinates of the raygun
+ //IF the raygun coordinates are the same as the martian - you win
+ //move: a function that changes x and y coordinates of the astronaut and the martian
+ //IF the coordinates are the same as the martians - you lose
+ //IF the coordinates are the same as the spaceship - you win
+//Create the martian object
+ //Add x and y coordinates as propeties set to 0
+//Create the spaceship object
+ //Add x and y coordinates as propeties set to 0
+//Create the raygun object
+ //Add x and y coordinates as propeties set to 0
+
+
+// Initial Code
+
+
+
+
+
+
+// Refactored Code
+
+
+
+
+
+
+// Reflection
+//
+//
+//
+//
+//
+//
+//
+// | |
a2748c414a629b1b909de14bd927428055f30adc | migrations/1.3.0.js | migrations/1.3.0.js | 'use strict';
var async = require('async');
var openVeoAPI = require('@openveo/api');
var db = openVeoAPI.applicationStorage.getDatabase();
module.exports.update = function(callback) {
process.logger.info('Publish 1.3.0 migration launched.');
db.get('videos', {}, null, null, function(error, value) {
if (error) {
callback(error);
return;
}
// No need to change anything
if (!value || !value.length) callback();
else {
var series = [];
value.forEach(function(video) {
if (video.files) {
// backup files property in sources property
if (!video.sources) {
series.push(function(callback) {
db.update('videos', {id: video.id}, {sources: {files: video.files}}, function(error) {
callback(error);
});
});
}
// delete files property
if (video.files) {
series.push(function(callback) {
db.removeProp('videos', 'files', {id: video.id}, function(error) {
callback(error);
});
});
}
}
});
async.series(series, function(error) {
if (error) {
callback(error);
return;
}
process.logger.info('Publish 1.3.0 migration done.');
callback();
});
}
});
};
| Add migration script to rewrite files property into sources property | Add migration script to rewrite files property into sources property
| JavaScript | agpl-3.0 | veo-labs/openveo-publish,veo-labs/openveo-publish,veo-labs/openveo-publish | ---
+++
@@ -0,0 +1,55 @@
+'use strict';
+
+var async = require('async');
+var openVeoAPI = require('@openveo/api');
+var db = openVeoAPI.applicationStorage.getDatabase();
+
+
+module.exports.update = function(callback) {
+ process.logger.info('Publish 1.3.0 migration launched.');
+ db.get('videos', {}, null, null, function(error, value) {
+ if (error) {
+ callback(error);
+ return;
+ }
+
+ // No need to change anything
+ if (!value || !value.length) callback();
+
+ else {
+ var series = [];
+
+ value.forEach(function(video) {
+ if (video.files) {
+
+ // backup files property in sources property
+ if (!video.sources) {
+ series.push(function(callback) {
+ db.update('videos', {id: video.id}, {sources: {files: video.files}}, function(error) {
+ callback(error);
+ });
+ });
+ }
+
+ // delete files property
+ if (video.files) {
+ series.push(function(callback) {
+ db.removeProp('videos', 'files', {id: video.id}, function(error) {
+ callback(error);
+ });
+ });
+ }
+ }
+ });
+
+ async.series(series, function(error) {
+ if (error) {
+ callback(error);
+ return;
+ }
+ process.logger.info('Publish 1.3.0 migration done.');
+ callback();
+ });
+ }
+ });
+}; | |
4736c2be21a62e675ff895a0201416c6b660a019 | experiments/GitHubGistUserCreator.js | experiments/GitHubGistUserCreator.js | const bcrypt = require('bcrypt');
const github = require('github-api');
const { User } = require('../models');
const { email } = require('../utils');
const GITHUB_API_TOKEN = process.env.GITHUB_TOKEN;
const GITHUB_GIST_ID = process.env.GITHUB_GIST_ID;
// Authenticate using a GitHub Token
const ghClient = new github({
token: GITHUB_API_TOKEN
});
const gist = ghClient.getGist(GITHUB_GIST_ID);
gist.read(function (err, gist, xhr) {
Promise.all(JSON.parse(gist['files']['users.json']['content']).map((user) => {
user.password = bcrypt.hashSync(e[6], bcrypt.genSaltSync(1)); // eslint-disable-line no-sync
return User.create(user.name, user.nameNumber, user.instrument, user.part, user.role, user.spotId, user.email, user.password)
.then(() => { email.sendUserCreateEmail(user.email, user.nameNumber, user.password); });
}))
.then(console.log('success!')
.catch(console.error);
});
| Create users from static data | Create users from static data
This pulls down a given GitHub Gist that contains a JSON file.
It then parses the data, creates a new password, creates a User, and
then it emails the user with their new password.
| JavaScript | mit | osumb/challenges,osumb/challenges,osumb/challenges,osumb/challenges | ---
+++
@@ -0,0 +1,25 @@
+const bcrypt = require('bcrypt');
+const github = require('github-api');
+
+const { User } = require('../models');
+const { email } = require('../utils');
+
+const GITHUB_API_TOKEN = process.env.GITHUB_TOKEN;
+const GITHUB_GIST_ID = process.env.GITHUB_GIST_ID;
+
+// Authenticate using a GitHub Token
+const ghClient = new github({
+ token: GITHUB_API_TOKEN
+});
+
+const gist = ghClient.getGist(GITHUB_GIST_ID);
+
+gist.read(function (err, gist, xhr) {
+ Promise.all(JSON.parse(gist['files']['users.json']['content']).map((user) => {
+ user.password = bcrypt.hashSync(e[6], bcrypt.genSaltSync(1)); // eslint-disable-line no-sync
+ return User.create(user.name, user.nameNumber, user.instrument, user.part, user.role, user.spotId, user.email, user.password)
+ .then(() => { email.sendUserCreateEmail(user.email, user.nameNumber, user.password); });
+ }))
+ .then(console.log('success!')
+ .catch(console.error);
+}); | |
53e25a15e0444f525166ed04305dcd6889815b2d | magnum_ui/static/dashboard/container-infra/cluster-templates/create/cluster-template-model.spec.js | magnum_ui/static/dashboard/container-infra/cluster-templates/create/cluster-template-model.spec.js | /**
* (c) Copyright 2016 NEC Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
(function() {
'use strict';
describe('horizon.dashboard.container-infra.cluster-templates.model', function() {
var template, specModel;
specModel = {
name: null,
coe: "",
public: null,
registry_enabled: null,
tls_disabled: null,
image_id: "",
flavor_id: "",
master_flavor_id: "",
docker_volume_size: null,
docker_storage_driver: "devicemapper",
keypair_id: "",
network_driver: "",
volume_driver: "",
http_proxy: null,
https_proxy: null,
no_proxy: null,
external_network_id: "",
fixed_network: "",
fixed_subnet: "",
dns_nameserver: null,
master_lb_enabled: "",
floating_ip_enabled: true,
labels: null,
network_drivers : [{name: "", label: gettext("Choose a Network Driver")},
{name: "docker", label: gettext("Docker")},
{name: "flannel", label: gettext("Flannel")}],
volume_drivers : [{name: "", label: gettext("Choose a Volume Driver")},
{name: "cinder", label: gettext("Cinder")},
{name: "rexray", label: gettext("Rexray")}],
docker_storage_drivers: [{name: "devicemapper", label: gettext("Device Mapper")},
{name: "overlay", label: gettext("Overley")}]
};
beforeEach(module('horizon.dashboard.container-infra.cluster-templates'));
beforeEach(inject(function($injector) {
template = $injector.get('horizon.dashboard.container-infra.cluster-templates.model');
}));
it('newClusterTemplateSpec', testTemplatemodel);
function testTemplatemodel() {
template.init();
expect(specModel).toEqual(template.newClusterTemplateSpec);
}
it('createClusterTemplate', inject(function($q, $injector) {
var magnum = $injector.get('horizon.app.core.openstack-service-api.magnum');
var deferred = $q.defer();
spyOn(magnum, 'createClusterTemplate').and.returnValue(deferred.promise);
template.init();
template.createClusterTemplate();
expect(magnum.createClusterTemplate).toHaveBeenCalled();
}));
});
})();
| Add javascript tests for ClusterTemplateModel | Add javascript tests for ClusterTemplateModel
This patch adds javascript tests for the following modules.
- horizon.dashboard.container-infra.cluster-templates.model
Change-Id: I7f7b720ef8d8e69ecf8ea7994db77f74baba4cd2
| JavaScript | apache-2.0 | openstack/magnum-ui,openstack/magnum-ui,openstack/magnum-ui,openstack/magnum-ui | ---
+++
@@ -0,0 +1,83 @@
+/**
+ * (c) Copyright 2016 NEC Corporation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ */
+
+(function() {
+ 'use strict';
+
+ describe('horizon.dashboard.container-infra.cluster-templates.model', function() {
+ var template, specModel;
+
+ specModel = {
+ name: null,
+ coe: "",
+ public: null,
+ registry_enabled: null,
+ tls_disabled: null,
+ image_id: "",
+ flavor_id: "",
+ master_flavor_id: "",
+ docker_volume_size: null,
+ docker_storage_driver: "devicemapper",
+ keypair_id: "",
+ network_driver: "",
+ volume_driver: "",
+ http_proxy: null,
+ https_proxy: null,
+ no_proxy: null,
+ external_network_id: "",
+ fixed_network: "",
+ fixed_subnet: "",
+ dns_nameserver: null,
+ master_lb_enabled: "",
+ floating_ip_enabled: true,
+ labels: null,
+ network_drivers : [{name: "", label: gettext("Choose a Network Driver")},
+ {name: "docker", label: gettext("Docker")},
+ {name: "flannel", label: gettext("Flannel")}],
+ volume_drivers : [{name: "", label: gettext("Choose a Volume Driver")},
+ {name: "cinder", label: gettext("Cinder")},
+ {name: "rexray", label: gettext("Rexray")}],
+ docker_storage_drivers: [{name: "devicemapper", label: gettext("Device Mapper")},
+ {name: "overlay", label: gettext("Overley")}]
+ };
+
+ beforeEach(module('horizon.dashboard.container-infra.cluster-templates'));
+ beforeEach(inject(function($injector) {
+ template = $injector.get('horizon.dashboard.container-infra.cluster-templates.model');
+ }));
+
+ it('newClusterTemplateSpec', testTemplatemodel);
+
+ function testTemplatemodel() {
+ template.init();
+ expect(specModel).toEqual(template.newClusterTemplateSpec);
+ }
+
+ it('createClusterTemplate', inject(function($q, $injector) {
+ var magnum = $injector.get('horizon.app.core.openstack-service-api.magnum');
+ var deferred = $q.defer();
+ spyOn(magnum, 'createClusterTemplate').and.returnValue(deferred.promise);
+
+ template.init();
+ template.createClusterTemplate();
+
+ expect(magnum.createClusterTemplate).toHaveBeenCalled();
+
+ }));
+
+ });
+
+})(); | |
722e50efcd1d64f36472f0722cf5e95933ed2767 | js/util.js | js/util.js | // 使い方
// getCurrentLocation()
// .done(function(location) {
// // success
// })
// .fail(function() {
// // faile
// });
function getCurrentLocation() {
var dfd = $.Deferred();
if(!navigator.geolocation) {
alert('Geolocation API is unavalable.');
dfd.reject();
}
navigator.geolocation.getCurrentPosition(function(position) {
var location = {"latitude" : position.coords.latitude,
"longitude": position.coords.longitude};
dfd.resolve(location);
}, function(error) {
alert('ERROR(' + error.code + '): ' + error.message);
dfd.reject();
});
return dfd.promise();
} | Implement function getting current location by using jQuery.Defferred | Implement function getting current location by using jQuery.Defferred
| JavaScript | mit | otknoy/michishiki | ---
+++
@@ -0,0 +1,28 @@
+// 使い方
+// getCurrentLocation()
+// .done(function(location) {
+// // success
+// })
+// .fail(function() {
+// // faile
+// });
+
+function getCurrentLocation() {
+ var dfd = $.Deferred();
+
+ if(!navigator.geolocation) {
+ alert('Geolocation API is unavalable.');
+ dfd.reject();
+ }
+
+ navigator.geolocation.getCurrentPosition(function(position) {
+ var location = {"latitude" : position.coords.latitude,
+ "longitude": position.coords.longitude};
+ dfd.resolve(location);
+ }, function(error) {
+ alert('ERROR(' + error.code + '): ' + error.message);
+ dfd.reject();
+ });
+
+ return dfd.promise();
+} | |
366c22009a3bda07c84790c91f567f57d8fa381c | src/reducers/r.spec.js | src/reducers/r.spec.js | import reducer from './r'
describe('r', () => {
it('Should return the initial state', () => {
expect(
reducer(undefined, {})
)
.toEqual(null)
})
it('Should handle LOGIN_SUCCESS', () => {
expect(
reducer(
// State,
null,
// Action
{
type: 'LOGIN_SUCCESS',
client: { foo: 'bar' }
}
)
)
.toEqual({ foo: 'bar' })
})
it('Should handle LOGOUT', () => {
expect(
reducer(
// State
{ accessToken: 'some-token' },
// Action
{ type: 'LOGOUT' }
)
)
.toEqual(null)
})
}) | Add reddit client reducer tests | Add reddit client reducer tests
| JavaScript | mit | antoinechalifour/Reddix,antoinechalifour/Reddix | ---
+++
@@ -0,0 +1,37 @@
+import reducer from './r'
+
+describe('r', () => {
+ it('Should return the initial state', () => {
+ expect(
+ reducer(undefined, {})
+ )
+ .toEqual(null)
+ })
+
+ it('Should handle LOGIN_SUCCESS', () => {
+ expect(
+ reducer(
+ // State,
+ null,
+ // Action
+ {
+ type: 'LOGIN_SUCCESS',
+ client: { foo: 'bar' }
+ }
+ )
+ )
+ .toEqual({ foo: 'bar' })
+ })
+
+ it('Should handle LOGOUT', () => {
+ expect(
+ reducer(
+ // State
+ { accessToken: 'some-token' },
+ // Action
+ { type: 'LOGOUT' }
+ )
+ )
+ .toEqual(null)
+ })
+}) | |
69d5639b0e71f598a2830f01195adb6628aec744 | src/app/controllers/MainController.js | src/app/controllers/MainController.js | (function(){
angular
.module('app')
.controller('MainController', [
'navService', '$mdSidenav', '$mdBottomSheet', '$log', '$q', '$state', '$mdToast',
MainController
]);
function MainController(navService, $mdSidenav, $mdBottomSheet, $log, $q, $state, $mdToast) {
var vm = this;
vm.menuItems = [ ];
vm.selectItem = selectItem;
vm.toggleItemsList = toggleItemsList;
vm.showActions = showActions;
vm.title = $state.current.data.title;
vm.showSimpleToast = showSimpleToast;
vm.toggleRightSidebar = toggleRightSidebar;
navService
.loadAllItems()
.then(function(menuItems) {
vm.menuItems = [].concat(menuItems);
});
function toggleRightSidebar() {
$mdSidenav('right').toggle();
}
function toggleItemsList() {
var pending = $mdBottomSheet.hide() || $q.when(true);
pending.then(function(){
$mdSidenav('left').toggle();
});
}
function selectItem (item) {
vm.title = item.name;
vm.toggleItemsList();
vm.showSimpleToast(vm.title);
}
function showActions($event) {
$mdBottomSheet.show({
parent: angular.element(document.getElementById('content')),
templateUrl: 'app/views/partials/bottomSheet.html',
controller: [ '$mdBottomSheet', SheetController],
controllerAs: "vm",
bindToController : true,
targetEvent: $event
}).then(function(clickedItem) {
clickedItem && $log.debug( clickedItem.name + ' clicked!');
});
function SheetController( $mdBottomSheet ) {
var vm = this;
vm.actions = [
{ name: 'Share', icon: 'share', url: 'https://twitter.com/intent/tweet?text=Angular%20Material%20Dashboard%20https://github.com/flatlogic/angular-material-dashboard%20via%20@flatlogicinc' },
{ name: 'Star', icon: 'star', url: 'https://github.com/flatlogic/angular-material-dashboard/stargazers' }
];
vm.performAction = function(action) {
$mdBottomSheet.hide(action);
};
}
}
function showSimpleToast(title) {
$mdToast.show(
$mdToast.simple()
.content(title)
.hideDelay(2000)
.position('bottom right')
);
}
}
})();
| Build a main layout for home page and customize layout sizes. | Build a main layout for home page and customize layout sizes.
| JavaScript | mit | happyboy171/DailyReportDashboard-Angluar-,happyboy171/DailyReportDashboard-Angluar- | ---
+++
@@ -0,0 +1,81 @@
+(function(){
+
+ angular
+ .module('app')
+ .controller('MainController', [
+ 'navService', '$mdSidenav', '$mdBottomSheet', '$log', '$q', '$state', '$mdToast',
+ MainController
+ ]);
+
+ function MainController(navService, $mdSidenav, $mdBottomSheet, $log, $q, $state, $mdToast) {
+ var vm = this;
+
+ vm.menuItems = [ ];
+ vm.selectItem = selectItem;
+ vm.toggleItemsList = toggleItemsList;
+ vm.showActions = showActions;
+ vm.title = $state.current.data.title;
+ vm.showSimpleToast = showSimpleToast;
+ vm.toggleRightSidebar = toggleRightSidebar;
+
+ navService
+ .loadAllItems()
+ .then(function(menuItems) {
+ vm.menuItems = [].concat(menuItems);
+ });
+
+ function toggleRightSidebar() {
+ $mdSidenav('right').toggle();
+ }
+
+ function toggleItemsList() {
+ var pending = $mdBottomSheet.hide() || $q.when(true);
+
+ pending.then(function(){
+ $mdSidenav('left').toggle();
+ });
+ }
+
+ function selectItem (item) {
+ vm.title = item.name;
+ vm.toggleItemsList();
+ vm.showSimpleToast(vm.title);
+ }
+
+ function showActions($event) {
+ $mdBottomSheet.show({
+ parent: angular.element(document.getElementById('content')),
+ templateUrl: 'app/views/partials/bottomSheet.html',
+ controller: [ '$mdBottomSheet', SheetController],
+ controllerAs: "vm",
+ bindToController : true,
+ targetEvent: $event
+ }).then(function(clickedItem) {
+ clickedItem && $log.debug( clickedItem.name + ' clicked!');
+ });
+
+ function SheetController( $mdBottomSheet ) {
+ var vm = this;
+
+ vm.actions = [
+ { name: 'Share', icon: 'share', url: 'https://twitter.com/intent/tweet?text=Angular%20Material%20Dashboard%20https://github.com/flatlogic/angular-material-dashboard%20via%20@flatlogicinc' },
+ { name: 'Star', icon: 'star', url: 'https://github.com/flatlogic/angular-material-dashboard/stargazers' }
+ ];
+
+ vm.performAction = function(action) {
+ $mdBottomSheet.hide(action);
+ };
+ }
+ }
+
+ function showSimpleToast(title) {
+ $mdToast.show(
+ $mdToast.simple()
+ .content(title)
+ .hideDelay(2000)
+ .position('bottom right')
+ );
+ }
+ }
+
+})(); | |
201eecdca92ac97ed3f84717d1fa69f4155a09de | gulpfile.js | gulpfile.js | var gulp = require('gulp');
var psi = require('psi');
var site = 'http://www.html5rocks.com';
var key = '';
// Please feel free to use the `nokey` option to try out PageSpeed
// Insights as part of your build process. For more frequent use,
// we recommend registering for your own API key. For more info:
// https://developers.google.com/speed/docs/insights/v1/getting_started
gulp.task('mobile', function (cb) {
psi({
// key: key
nokey: 'true',
url: site,
strategy: 'mobile',
}, cb);
});
gulp.task('desktop', function (cb) {
psi({
// key: key,
nokey: 'true',
url: site,
strategy: 'desktop',
}, cb);
});
gulp.task('default', ['mobile']);
| var gulp = require('gulp');
var psi = require('psi');
var site = 'http://www.html5rocks.com';
var key = '';
// Please feel free to use the `nokey` option to try out PageSpeed
// Insights as part of your build process. For more frequent use,
// we recommend registering for your own API key. For more info:
// https://developers.google.com/speed/docs/insights/v1/getting_started
gulp.task('mobile', function (cb) {
psi({
// key: key
nokey: 'true',
url: site,
strategy: 'mobile',
}, cb);
});
gulp.task('desktop', function (cb) {
psi({
// key: key,
nokey: 'true',
url: site,
strategy: 'desktop',
}, cb);
});
gulp.task('default', ['mobile']);
| Use tabs rather as psi is using tabs | Use tabs rather as psi is using tabs | JavaScript | mit | Jazz-Man/psi-gulp-sample,addyosmani/psi-gulp-sample | ---
+++
@@ -9,21 +9,21 @@
// https://developers.google.com/speed/docs/insights/v1/getting_started
gulp.task('mobile', function (cb) {
- psi({
- // key: key
- nokey: 'true',
- url: site,
- strategy: 'mobile',
- }, cb);
+ psi({
+ // key: key
+ nokey: 'true',
+ url: site,
+ strategy: 'mobile',
+ }, cb);
});
gulp.task('desktop', function (cb) {
- psi({
- // key: key,
- nokey: 'true',
- url: site,
- strategy: 'desktop',
- }, cb);
+ psi({
+ // key: key,
+ nokey: 'true',
+ url: site,
+ strategy: 'desktop',
+ }, cb);
});
gulp.task('default', ['mobile']); |
9e3d376c072775c93f456402786871c1f7060cdf | spec/helpers-spec.js | spec/helpers-spec.js | const path = require('path')
const helpers = require('../lib/helpers')
describe('Helpers', () => {
describe('getFullExtension', () => {
it('returns the extension for a simple file', () => {
expect(helpers.getFullExtension('filename.txt')).toBe('.txt')
})
it('returns the extension for a path', () => {
expect(helpers.getFullExtension(path.join('path', 'to', 'filename.txt'))).toBe('.txt')
})
it('returns the full extension for a filename with more than one extension', () => {
expect(helpers.getFullExtension('index.html.php')).toBe('.html.php')
expect(helpers.getFullExtension('archive.tar.gz.bak')).toBe('.tar.gz.bak')
})
it('returns no extension when the filename begins with a period', () => {
expect(helpers.getFullExtension('.gitconfig')).toBe('')
expect(helpers.getFullExtension(path.join('path', 'to', '.gitconfig'))).toBe('')
})
})
})
| Add dedicated specs for getFullExtension | Add dedicated specs for getFullExtension
| JavaScript | mit | jarig/tree-view,atom/tree-view | ---
+++
@@ -0,0 +1,25 @@
+const path = require('path')
+
+const helpers = require('../lib/helpers')
+
+describe('Helpers', () => {
+ describe('getFullExtension', () => {
+ it('returns the extension for a simple file', () => {
+ expect(helpers.getFullExtension('filename.txt')).toBe('.txt')
+ })
+
+ it('returns the extension for a path', () => {
+ expect(helpers.getFullExtension(path.join('path', 'to', 'filename.txt'))).toBe('.txt')
+ })
+
+ it('returns the full extension for a filename with more than one extension', () => {
+ expect(helpers.getFullExtension('index.html.php')).toBe('.html.php')
+ expect(helpers.getFullExtension('archive.tar.gz.bak')).toBe('.tar.gz.bak')
+ })
+
+ it('returns no extension when the filename begins with a period', () => {
+ expect(helpers.getFullExtension('.gitconfig')).toBe('')
+ expect(helpers.getFullExtension(path.join('path', 'to', '.gitconfig'))).toBe('')
+ })
+ })
+}) | |
c4be15ab7481215f39571fd7ec4c6ccff75457a6 | spec/all-spec.js | spec/all-spec.js | var FS = require("q-io/fs");
var PATH = require("path");
var RELATIVE_LIB = PATH.join("..", "lib");
var ABSOLUTE_LIB = PATH.join(__dirname, RELATIVE_LIB);
FS.listTree(ABSOLUTE_LIB, function (path, stat) {
return !!path.match(/.js$/);
})
.then(function (tree) {
tree.forEach(function (path) {
require(path.replace(ABSOLUTE_LIB, RELATIVE_LIB));
});
});
| Add "spec" to load all lib files | Add "spec" to load all lib files
To get true code coverage
| JavaScript | bsd-3-clause | pchaussalet/mop,thibaultzanini/mop | ---
+++
@@ -0,0 +1,15 @@
+var FS = require("q-io/fs");
+var PATH = require("path");
+
+var RELATIVE_LIB = PATH.join("..", "lib");
+var ABSOLUTE_LIB = PATH.join(__dirname, RELATIVE_LIB);
+
+
+FS.listTree(ABSOLUTE_LIB, function (path, stat) {
+ return !!path.match(/.js$/);
+})
+.then(function (tree) {
+ tree.forEach(function (path) {
+ require(path.replace(ABSOLUTE_LIB, RELATIVE_LIB));
+ });
+}); | |
a65eafa20a6862ddea627cf1dde438e680fa3fc1 | addon/-private/apollo/setup-hooks.js | addon/-private/apollo/setup-hooks.js | import Component from '@ember/component';
import Route from '@ember/routing/route';
const hooks = {
willDestroyElement() {
this.unsubscribeAll(false);
},
beforeModel() {
this.markSubscriptionsStale();
},
resetController(_, isExiting) {
this.unsubscribeAll(!isExiting);
},
willDestroy() {
if (this.unsubscribeAll) {
this.unsubscribeAll(false);
}
},
};
function installHook(queryManager, context, hookName) {
let hook = hooks[hookName].bind(queryManager);
let originalHook = context[hookName];
context[hookName] = function() {
if (typeof originalHook === 'function') {
originalHook.call(this, ...arguments);
}
hook.call(queryManager, ...arguments);
};
}
export default function setupHooks(queryManager, context) {
if (context instanceof Component) {
installHook(queryManager, context, 'willDestroyElement');
} else if (context instanceof Route) {
installHook(queryManager, context, 'beforeModel');
installHook(queryManager, context, 'resetController');
installHook(queryManager, context, 'willDestroy');
} else {
installHook(queryManager, context, 'willDestroy');
}
}
| Add setup hooks thanks @tchak | Add setup hooks thanks @tchak
The original idea here came from @tchak in his branch https://github.com/tchak/ember-apollo-client/tree/drop-mixins.
The only difference is that I default to willDestroy hook, not only for ember objects. This is to add support for Glimmer Components, in which they don't extend EmberObject, but they do implement willDestroy hook.
| JavaScript | mit | bgentry/ember-apollo-client,bgentry/ember-apollo-client | ---
+++
@@ -0,0 +1,46 @@
+import Component from '@ember/component';
+import Route from '@ember/routing/route';
+
+const hooks = {
+ willDestroyElement() {
+ this.unsubscribeAll(false);
+ },
+
+ beforeModel() {
+ this.markSubscriptionsStale();
+ },
+
+ resetController(_, isExiting) {
+ this.unsubscribeAll(!isExiting);
+ },
+
+ willDestroy() {
+ if (this.unsubscribeAll) {
+ this.unsubscribeAll(false);
+ }
+ },
+};
+
+function installHook(queryManager, context, hookName) {
+ let hook = hooks[hookName].bind(queryManager);
+ let originalHook = context[hookName];
+
+ context[hookName] = function() {
+ if (typeof originalHook === 'function') {
+ originalHook.call(this, ...arguments);
+ }
+ hook.call(queryManager, ...arguments);
+ };
+}
+
+export default function setupHooks(queryManager, context) {
+ if (context instanceof Component) {
+ installHook(queryManager, context, 'willDestroyElement');
+ } else if (context instanceof Route) {
+ installHook(queryManager, context, 'beforeModel');
+ installHook(queryManager, context, 'resetController');
+ installHook(queryManager, context, 'willDestroy');
+ } else {
+ installHook(queryManager, context, 'willDestroy');
+ }
+} | |
b1f3cbd648ab6245ce13219f83173e2c2619fa5d | Specs/Scene/PrimitivePipelineSpec.js | Specs/Scene/PrimitivePipelineSpec.js | /*global defineSuite*/
defineSuite([
'Scene/PrimitivePipeline',
'Core/BoundingSphere',
'Core/BoxGeometry',
'Core/Cartesian3',
'Core/ComponentDatatype',
'Core/Geometry',
'Core/GeometryAttribute',
'Core/GeometryAttributes',
'Core/PrimitiveType'
], function(
PrimitivePipeline,
BoundingSphere,
BoxGeometry,
Cartesian3,
ComponentDatatype,
Geometry,
GeometryAttribute,
GeometryAttributes,
PrimitiveType) {
"use strict";
/*global jasmine,describe,xdescribe,it,xit,expect,beforeEach,afterEach,beforeAll,afterAll,spyOn,runs,waits,waitsFor*/
it('can pack and unpack geometry', function() {
var boxGeometry = BoxGeometry.createGeometry(BoxGeometry.fromDimensions({
dimensions : new Cartesian3(1, 2, 3)
}));
var boxGeometry2 = BoxGeometry.createGeometry(BoxGeometry.fromDimensions({
dimensions : new Cartesian3(3, 4, 7)
}));
var geometryToPack = [boxGeometry, boxGeometry2];
var transferableObjects = [];
var results = PrimitivePipeline.packCreateGeometryResults(geometryToPack, transferableObjects);
var unpackedGeometry = PrimitivePipeline.unpackCreateGeometryResults(results);
expect(transferableObjects.length).toBe(1);
expect(geometryToPack).toEqual(unpackedGeometry);
});
it('can pack and unpack geometry without indices', function() {
var attributes = new GeometryAttributes();
attributes.position = new GeometryAttribute({
componentDatatype : ComponentDatatype.DOUBLE,
componentsPerAttribute : 3,
values : new Float32Array([1, 2, 3, 4, 5, 6])
});
var geometry = new Geometry({
attributes : attributes,
indices : undefined,
primitiveType : PrimitiveType.POINTS,
boundingSphere : BoundingSphere.fromVertices(attributes.position.values)
});
var geometryToPack = [geometry];
var transferableObjects = [];
var results = PrimitivePipeline.packCreateGeometryResults(geometryToPack, transferableObjects);
var unpackedGeometry = PrimitivePipeline.unpackCreateGeometryResults(results);
expect(transferableObjects.length).toBe(1);
expect(geometryToPack).toEqual(unpackedGeometry);
});
}, 'WebGL'); | Add specs for PrimitivePipline geometry packing. | Add specs for PrimitivePipline geometry packing.
| JavaScript | apache-2.0 | omh1280/cesium,aelatgt/cesium,kiselev-dv/cesium,kiselev-dv/cesium,jason-crow/cesium,emackey/cesium,hodbauer/cesium,soceur/cesium,AnimatedRNG/cesium,denverpierce/cesium,AnimatedRNG/cesium,emackey/cesium,CesiumGS/cesium,likangning93/cesium,wallw-bits/cesium,AnalyticalGraphicsInc/cesium,geoscan/cesium,denverpierce/cesium,ggetz/cesium,hodbauer/cesium,josh-bernstein/cesium,jason-crow/cesium,NaderCHASER/cesium,YonatanKra/cesium,esraerik/cesium,jason-crow/cesium,emackey/cesium,omh1280/cesium,progsung/cesium,NaderCHASER/cesium,soceur/cesium,likangning93/cesium,emackey/cesium,CesiumGS/cesium,geoscan/cesium,jasonbeverage/cesium,CesiumGS/cesium,wallw-bits/cesium,AnimatedRNG/cesium,ggetz/cesium,NaderCHASER/cesium,oterral/cesium,wallw-bits/cesium,kaktus40/cesium,hodbauer/cesium,denverpierce/cesium,esraerik/cesium,progsung/cesium,wallw-bits/cesium,oterral/cesium,YonatanKra/cesium,likangning93/cesium,AnalyticalGraphicsInc/cesium,CesiumGS/cesium,YonatanKra/cesium,omh1280/cesium,josh-bernstein/cesium,YonatanKra/cesium,esraerik/cesium,aelatgt/cesium,aelatgt/cesium,likangning93/cesium,aelatgt/cesium,AnimatedRNG/cesium,kiselev-dv/cesium,denverpierce/cesium,omh1280/cesium,likangning93/cesium,jasonbeverage/cesium,kiselev-dv/cesium,esraerik/cesium,ggetz/cesium,oterral/cesium,soceur/cesium,jason-crow/cesium,kaktus40/cesium,CesiumGS/cesium,ggetz/cesium | ---
+++
@@ -0,0 +1,67 @@
+/*global defineSuite*/
+defineSuite([
+ 'Scene/PrimitivePipeline',
+ 'Core/BoundingSphere',
+ 'Core/BoxGeometry',
+ 'Core/Cartesian3',
+ 'Core/ComponentDatatype',
+ 'Core/Geometry',
+ 'Core/GeometryAttribute',
+ 'Core/GeometryAttributes',
+ 'Core/PrimitiveType'
+ ], function(
+ PrimitivePipeline,
+ BoundingSphere,
+ BoxGeometry,
+ Cartesian3,
+ ComponentDatatype,
+ Geometry,
+ GeometryAttribute,
+ GeometryAttributes,
+ PrimitiveType) {
+ "use strict";
+ /*global jasmine,describe,xdescribe,it,xit,expect,beforeEach,afterEach,beforeAll,afterAll,spyOn,runs,waits,waitsFor*/
+
+ it('can pack and unpack geometry', function() {
+ var boxGeometry = BoxGeometry.createGeometry(BoxGeometry.fromDimensions({
+ dimensions : new Cartesian3(1, 2, 3)
+ }));
+
+ var boxGeometry2 = BoxGeometry.createGeometry(BoxGeometry.fromDimensions({
+ dimensions : new Cartesian3(3, 4, 7)
+ }));
+
+ var geometryToPack = [boxGeometry, boxGeometry2];
+ var transferableObjects = [];
+ var results = PrimitivePipeline.packCreateGeometryResults(geometryToPack, transferableObjects);
+ var unpackedGeometry = PrimitivePipeline.unpackCreateGeometryResults(results);
+
+ expect(transferableObjects.length).toBe(1);
+ expect(geometryToPack).toEqual(unpackedGeometry);
+ });
+
+ it('can pack and unpack geometry without indices', function() {
+ var attributes = new GeometryAttributes();
+ attributes.position = new GeometryAttribute({
+ componentDatatype : ComponentDatatype.DOUBLE,
+ componentsPerAttribute : 3,
+ values : new Float32Array([1, 2, 3, 4, 5, 6])
+ });
+
+ var geometry = new Geometry({
+ attributes : attributes,
+ indices : undefined,
+ primitiveType : PrimitiveType.POINTS,
+ boundingSphere : BoundingSphere.fromVertices(attributes.position.values)
+ });
+
+ var geometryToPack = [geometry];
+ var transferableObjects = [];
+ var results = PrimitivePipeline.packCreateGeometryResults(geometryToPack, transferableObjects);
+ var unpackedGeometry = PrimitivePipeline.unpackCreateGeometryResults(results);
+
+ expect(transferableObjects.length).toBe(1);
+ expect(geometryToPack).toEqual(unpackedGeometry);
+ });
+
+}, 'WebGL'); | |
599b32f2b2c0c29337a053a6b6a28d61f92c1241 | karma.conf.js | karma.conf.js | module.exports = function (config) {
config.set({
frameworks: ['mocha'],
exclude: ['build/test/external.spec.js'],
files: [
'vendor/rsvp.js',
'vendor/unexpected-magicpen.min.js',
'build/test/promisePolyfill.js',
'unexpected.js',
'build/test/common.js',
'build/test/**/*.spec.js',
],
browsers: ['ChromeHeadlessNoSandbox', 'ie11'],
browserDisconnectTimeout: '60000',
browserNoActivityTimeout: '60000',
client: {
mocha: {
reporter: 'html',
timeout: 60000,
},
},
browserStack: {
video: false,
project:
process.env.TRAVIS_BRANCH === 'master' &&
!process.env.TRAVIS_PULL_REQUEST_BRANCH // Catch Travis "PR" builds
? 'unexpected'
: 'unexpected-dev',
},
customLaunchers: {
ChromeHeadlessNoSandbox: {
base: 'ChromeHeadless',
flags: ['--no-sandbox'],
},
ie11: {
base: 'BrowserStack',
browser: 'IE',
browser_version: '11',
os: 'Windows',
os_version: '7',
},
},
reporters: ['dots', 'BrowserStack'],
});
};
| module.exports = function (config) {
config.set({
frameworks: ['mocha'],
exclude: ['build/test/external.spec.js'],
files: [
'vendor/rsvp.js',
'vendor/unexpected-magicpen.min.js',
'build/test/promisePolyfill.js',
'unexpected.js',
'build/test/common.js',
'build/test/**/*.spec.js',
],
browsers: ['ChromeHeadlessNoSandbox', 'ie11'],
browserDisconnectTimeout: '60000',
browserNoActivityTimeout: '60000',
client: {
mocha: {
reporter: 'html',
timeout: 60000,
},
},
browserStack: {
video: false,
project:
process.env.TRAVIS_BRANCH === 'master' &&
!process.env.TRAVIS_PULL_REQUEST_BRANCH // Catch Travis "PR" builds
? 'unexpected'
: 'unexpected-dev',
// Attempt to fix timeouts on CI:
// https://github.com/karma-runner/karma-browserstack-launcher/pull/168#issuecomment-582373514
timeout: 1800,
},
customLaunchers: {
ChromeHeadlessNoSandbox: {
base: 'ChromeHeadless',
flags: ['--no-sandbox'],
},
ie11: {
base: 'BrowserStack',
browser: 'IE',
browser_version: '11',
os: 'Windows',
os_version: '7',
},
},
reporters: ['dots', 'BrowserStack'],
});
};
| Set browserStack timeout in an attempt to fix failing CI builds | Set browserStack timeout in an attempt to fix failing CI builds
| JavaScript | mit | unexpectedjs/unexpected | ---
+++
@@ -32,6 +32,9 @@
!process.env.TRAVIS_PULL_REQUEST_BRANCH // Catch Travis "PR" builds
? 'unexpected'
: 'unexpected-dev',
+ // Attempt to fix timeouts on CI:
+ // https://github.com/karma-runner/karma-browserstack-launcher/pull/168#issuecomment-582373514
+ timeout: 1800,
},
customLaunchers: { |
4f76060e328e0ef864bde3a138bce7c3135d60a2 | lib/moment.js | lib/moment.js | moment.locale('fr', {
months : "janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre".split("_"),
monthsShort : "janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.".split("_"),
weekdays : "dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi".split("_"),
weekdaysShort : "dim._lun._mar._mer._jeu._ven._sam.".split("_"),
weekdaysMin : "Di_Lu_Ma_Me_Je_Ve_Sa".split("_"),
longDateFormat : {
LT : "HH:mm",
LTS : "HH:mm:ss",
L : "DD/MM/YYYY",
LL : "D MMMM YYYY",
LLL : "D MMMM YYYY LT",
LLLL : "dddd D MMMM YYYY LT"
},
calendar : {
sameDay: "[Aujourd'hui à] LT",
nextDay: '[Demain à] LT',
nextWeek: 'dddd [à] LT',
lastDay: '[Hier à] LT',
lastWeek: 'dddd [dernier à] LT',
sameElse: 'L'
},
relativeTime : {
future : "dans %s",
past : "il y a %s",
s : "quelques secondes",
m : "une minute",
mm : "%d minutes",
h : "une heure",
hh : "%d heures",
d : "un jour",
dd : "%d jours",
M : "un mois",
MM : "%d mois",
y : "une année",
yy : "%d années"
},
ordinalParse : /\d{1,2}(er|ème)/,
ordinal : function (number) {
return number + (number === 1 ? 'er' : 'ème');
},
meridiemParse: /PD|MD/,
isPM: function (input) {
return input.charAt(0) === 'M';
},
// in case the meridiem units are not separated around 12, then implement
// this function (look at locale/id.js for an example)
// meridiemHour : function (hour, meridiem) {
// return /* 0-23 hour, given meridiem token and hour 1-12 */
// },
meridiem : function (hours, minutes, isLower) {
return hours < 12 ? 'PD' : 'MD';
},
week : {
dow : 1, // Monday is the first day of the week.
doy : 4 // The week that contains Jan 4th is the first week of the year.
}
}); | Add config to display date in french | Add config to display date in french
| JavaScript | mit | dexterneo/mangatek,dexterneo/mangatek,dexterneo/mangas,dexterneo/mangas | ---
+++
@@ -0,0 +1,58 @@
+moment.locale('fr', {
+ months : "janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre".split("_"),
+ monthsShort : "janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.".split("_"),
+ weekdays : "dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi".split("_"),
+ weekdaysShort : "dim._lun._mar._mer._jeu._ven._sam.".split("_"),
+ weekdaysMin : "Di_Lu_Ma_Me_Je_Ve_Sa".split("_"),
+ longDateFormat : {
+ LT : "HH:mm",
+ LTS : "HH:mm:ss",
+ L : "DD/MM/YYYY",
+ LL : "D MMMM YYYY",
+ LLL : "D MMMM YYYY LT",
+ LLLL : "dddd D MMMM YYYY LT"
+ },
+ calendar : {
+ sameDay: "[Aujourd'hui à] LT",
+ nextDay: '[Demain à] LT',
+ nextWeek: 'dddd [à] LT',
+ lastDay: '[Hier à] LT',
+ lastWeek: 'dddd [dernier à] LT',
+ sameElse: 'L'
+ },
+ relativeTime : {
+ future : "dans %s",
+ past : "il y a %s",
+ s : "quelques secondes",
+ m : "une minute",
+ mm : "%d minutes",
+ h : "une heure",
+ hh : "%d heures",
+ d : "un jour",
+ dd : "%d jours",
+ M : "un mois",
+ MM : "%d mois",
+ y : "une année",
+ yy : "%d années"
+ },
+ ordinalParse : /\d{1,2}(er|ème)/,
+ ordinal : function (number) {
+ return number + (number === 1 ? 'er' : 'ème');
+ },
+ meridiemParse: /PD|MD/,
+ isPM: function (input) {
+ return input.charAt(0) === 'M';
+ },
+ // in case the meridiem units are not separated around 12, then implement
+ // this function (look at locale/id.js for an example)
+ // meridiemHour : function (hour, meridiem) {
+ // return /* 0-23 hour, given meridiem token and hour 1-12 */
+ // },
+ meridiem : function (hours, minutes, isLower) {
+ return hours < 12 ? 'PD' : 'MD';
+ },
+ week : {
+ dow : 1, // Monday is the first day of the week.
+ doy : 4 // The week that contains Jan 4th is the first week of the year.
+ }
+}); | |
a3519ec3e332e9825645cf02e614c724c30c8a46 | src/dsp/DiscontinuityDetector.js | src/dsp/DiscontinuityDetector.js | /**
* @depends ../core/AudioletNode.js
*/
var DiscontinuityDetector = new Class({
Extends: PassThroughNode,
initialize: function(audiolet, threshold, callback) {
PassThroughNode.prototype.initialize.apply(this, [audiolet, 1, 1]);
this.linkNumberOfOutputChannels(0, 0);
this.threshold = threshold || 0.2;
if (callback) {
this.callback = callback;
}
this.lastValues = [];
},
// Override me
callback: function() {
},
generate: function(inputBuffers, outputBuffers) {
var inputBuffer = inputBuffers[0];
var lastValues = this.lastValues;
var threshold = this.threshold;
var numberOfChannels = inputBuffer.numberOfChannels;
for (var i = 0; i < numberOfChannels; i++) {
var channel = inputBuffer.getChannelData(i);
if (i >= lastValues.length) {
lastValues.push(null);
}
var lastValue = lastValues[i];
var bufferLength = inputBuffer.length;
for (var j = 0; j < bufferLength; j++) {
var value = channel[j];
if (lastValue != null) {
if (Math.abs(lastValue - value) > threshold) {
this.callback();
}
}
lastValue = value;
}
lastValues[i] = lastValue;
}
},
toString: function() {
return 'Discontinuity Detector';
}
});
| Add discontinuity detector - a debugging tool for my crappy dsp | Add discontinuity detector - a debugging tool for my crappy dsp
| JavaScript | apache-2.0 | kn0ll/Audiolet,mcanthony/Audiolet,kn0ll/Audiolet,oampo/Audiolet,Kosar79/Audiolet,oampo/Audiolet,Kosar79/Audiolet,mcanthony/Audiolet,Kosar79/Audiolet,bobby-brennan/Audiolet,bobby-brennan/Audiolet | ---
+++
@@ -0,0 +1,57 @@
+/**
+ * @depends ../core/AudioletNode.js
+ */
+
+var DiscontinuityDetector = new Class({
+ Extends: PassThroughNode,
+ initialize: function(audiolet, threshold, callback) {
+ PassThroughNode.prototype.initialize.apply(this, [audiolet, 1, 1]);
+ this.linkNumberOfOutputChannels(0, 0);
+
+ this.threshold = threshold || 0.2;
+ if (callback) {
+ this.callback = callback;
+ }
+ this.lastValues = [];
+
+ },
+
+ // Override me
+ callback: function() {
+ },
+
+ generate: function(inputBuffers, outputBuffers) {
+ var inputBuffer = inputBuffers[0];
+
+ var lastValues = this.lastValues;
+ var threshold = this.threshold;
+
+ var numberOfChannels = inputBuffer.numberOfChannels;
+ for (var i = 0; i < numberOfChannels; i++) {
+ var channel = inputBuffer.getChannelData(i);
+
+ if (i >= lastValues.length) {
+ lastValues.push(null);
+ }
+ var lastValue = lastValues[i];
+
+ var bufferLength = inputBuffer.length;
+ for (var j = 0; j < bufferLength; j++) {
+ var value = channel[j];
+ if (lastValue != null) {
+ if (Math.abs(lastValue - value) > threshold) {
+ this.callback();
+ }
+ }
+ lastValue = value;
+ }
+
+ lastValues[i] = lastValue;
+ }
+ },
+
+ toString: function() {
+ return 'Discontinuity Detector';
+ }
+});
+ | |
dc76f34b8688ecaab77e43d3c74521c640f70971 | support/find_urls.js | support/find_urls.js | // Find urls within selected domain in posts
//
'use strict';
const _ = require('lodash');
const argparse = require('argparse');
const Promise = require('bluebird');
const mongoose = require('mongoose');
const pump = require('pump');
const stream = require('stream');
const URL = require('url');
let parser = new argparse.ArgumentParser();
parser.addArgument(
[ '-d', '--db' ],
{
help: 'database name',
defaultValue: 'nodeca'
}
);
parser.addArgument(
[ '-c', '--cutoff' ],
{
help: 'cutoff (days)',
type: 'int'
}
);
parser.addArgument(
'domain',
{
help: 'domain name'
}
);
let args = parser.parseArgs();
mongoose.Promise = Promise;
Promise.coroutine(function* () {
yield mongoose.connect('mongodb://localhost/' + args.db);
let Post = mongoose.model('forum.Post', new mongoose.Schema());
let regexp_search = new RegExp('href="https?:\\/\\/[^\\/]*' + _.escapeRegExp(args.domain));
let query = { html: regexp_search };
if (args.cutoff) {
let ts = Date.now() / 1000 - args.cutoff * 24 * 60 * 60;
let min_objectid = new mongoose.Types.ObjectId(Math.floor(ts).toString(16) + '0000000000000000');
query._id = { $gt: min_objectid };
}
yield Promise.fromCallback(callback => pump(
Post.find(query).lean(true).cursor(),
new stream.Writable({
objectMode: true,
write(post, encoding, callback) {
let urls = post.html.match(/href="[^"]+"/g)
.map(href => _.unescape(href.replace(/^href="|"$/g, '')));
urls.forEach(url => {
let parsed = URL.parse(url);
if (parsed.host && parsed.host.includes(args.domain)) {
/* eslint-disable no-console */
console.log(url);
}
});
callback();
}
}),
callback
));
yield mongoose.disconnect();
})();
| Add script to dump links from a particular domain | Add script to dump links from a particular domain
| JavaScript | mit | rcdesign/rcd-nodeca,rcdesign/rcd-nodeca | ---
+++
@@ -0,0 +1,88 @@
+// Find urls within selected domain in posts
+//
+
+'use strict';
+
+
+const _ = require('lodash');
+const argparse = require('argparse');
+const Promise = require('bluebird');
+const mongoose = require('mongoose');
+const pump = require('pump');
+const stream = require('stream');
+const URL = require('url');
+
+
+let parser = new argparse.ArgumentParser();
+
+parser.addArgument(
+ [ '-d', '--db' ],
+ {
+ help: 'database name',
+ defaultValue: 'nodeca'
+ }
+);
+
+parser.addArgument(
+ [ '-c', '--cutoff' ],
+ {
+ help: 'cutoff (days)',
+ type: 'int'
+ }
+);
+
+parser.addArgument(
+ 'domain',
+ {
+ help: 'domain name'
+ }
+);
+
+let args = parser.parseArgs();
+
+
+mongoose.Promise = Promise;
+
+Promise.coroutine(function* () {
+ yield mongoose.connect('mongodb://localhost/' + args.db);
+
+ let Post = mongoose.model('forum.Post', new mongoose.Schema());
+
+ let regexp_search = new RegExp('href="https?:\\/\\/[^\\/]*' + _.escapeRegExp(args.domain));
+
+ let query = { html: regexp_search };
+
+ if (args.cutoff) {
+ let ts = Date.now() / 1000 - args.cutoff * 24 * 60 * 60;
+ let min_objectid = new mongoose.Types.ObjectId(Math.floor(ts).toString(16) + '0000000000000000');
+
+ query._id = { $gt: min_objectid };
+ }
+
+ yield Promise.fromCallback(callback => pump(
+ Post.find(query).lean(true).cursor(),
+
+ new stream.Writable({
+ objectMode: true,
+ write(post, encoding, callback) {
+ let urls = post.html.match(/href="[^"]+"/g)
+ .map(href => _.unescape(href.replace(/^href="|"$/g, '')));
+
+ urls.forEach(url => {
+ let parsed = URL.parse(url);
+
+ if (parsed.host && parsed.host.includes(args.domain)) {
+ /* eslint-disable no-console */
+ console.log(url);
+ }
+ });
+
+ callback();
+ }
+ }),
+
+ callback
+ ));
+
+ yield mongoose.disconnect();
+})(); | |
bb1a00d28bb36c0919968bb1ee02510dccd3caf0 | test/virtual-loopback-test.js | test/virtual-loopback-test.js | var midi = require("../build/default/midi.node");
var output = new midi.output();
var input = new midi.input();
output.openVirtualPort("node-midi Virtual Output");
input.on('message', function(deltaTime, message) {
console.log('m:' + message + ' d:' + deltaTime);
output.sendMessage([
message[0],
message[1] + 10,
message[2]
]);
});
input.openVirtualPort("node-midi Virtual Input");
setTimeout(function() {
input.closePort();
output.closePort();
}, 60000); | Add a test that uses a virtual input and virtual output to make a loopback. | Add a test that uses a virtual input and virtual output to make a loopback.
| JavaScript | mit | Cycling74/node-midi,drewish/node-midi,Cycling74/node-midi,brandly/node-midi,brandly/node-midi,szymonkaliski/node-midi,drewish/node-midi,Cycling74/node-midi,Cycling74/node-midi,drewish/node-midi,brandly/node-midi,justinlatimer/node-midi,brandly/node-midi,julianduque/node-midi,drewish/node-midi,julianduque/node-midi,Cycling74/node-midi,julianduque/node-midi,Cycling74/node-midi,julianduque/node-midi,drewish/node-midi,szymonkaliski/node-midi,szymonkaliski/node-midi,justinlatimer/node-midi,julianduque/node-midi,brandly/node-midi,szymonkaliski/node-midi,szymonkaliski/node-midi,justinlatimer/node-midi | ---
+++
@@ -0,0 +1,19 @@
+var midi = require("../build/default/midi.node");
+
+var output = new midi.output();
+var input = new midi.input();
+
+output.openVirtualPort("node-midi Virtual Output");
+input.on('message', function(deltaTime, message) {
+ console.log('m:' + message + ' d:' + deltaTime);
+ output.sendMessage([
+ message[0],
+ message[1] + 10,
+ message[2]
+ ]);
+});
+input.openVirtualPort("node-midi Virtual Input");
+setTimeout(function() {
+ input.closePort();
+ output.closePort();
+}, 60000); | |
a6f899f06258ca0b01eb33d965b10cfcde74a92a | test/unit/traderTickerTest.js | test/unit/traderTickerTest.js | 'use strict';
var assert = require('chai').assert;
var hock = require('hock');
var uuid = require('node-uuid').v4;
var Trader = require('../../lib/trader.js');
var PostgresqlInterface = require('../../lib/protocol/db/postgresql_interface.js');
var db = 'psql://lamassu:lamassu@localhost/lamassu-test';
var psqlInterface = new PostgresqlInterface(db);
var CURRENCY = 'USD';
describe('trader/send', function () {
var trader = new Trader(psqlInterface);
trader.config = {
exchanges: {
settings: { currency: CURRENCY }
}
};
it('should call `balance` on the transfer exchange', function (done) {
trader.transferExchange = {
balance: function (callback) {
callback(null, 100);
}
};
trader.pollBalance(function (err, balance) {
assert.notOk(err);
assert.equal(trader.balance.transferBalance, 100);
assert.ok(trader.balance.timestamp);
done();
});
});
it('should call `ticker` on the ticker exchange', function (done) {
trader.tickerExchange = {
ticker: function (currency, callback) {
assert.equal(currency, CURRENCY);
callback(null, 100);
}
};
trader.pollRate(function (err, rate) {
var rate;
assert.notOk(err);
rate = trader.rate(CURRENCY);
assert.equal(rate.rate, 100);
assert.ok(rate.timestamp);
done();
});
});
});
| Add a unit test for ticker | Add a unit test for ticker
| JavaScript | unlicense | lamassu/lamassu-server,joshmh/lamassu-server,naconner/lamassu-server,naconner/lamassu-server,joshmh/lamassu-server,joshmh/lamassu-server,naconner/lamassu-server,joshmh/lamassu-server,lamassu/lamassu-server,evan82/lamassu-server,lamassu/lamassu-server | ---
+++
@@ -0,0 +1,55 @@
+'use strict';
+
+var assert = require('chai').assert;
+var hock = require('hock');
+var uuid = require('node-uuid').v4;
+var Trader = require('../../lib/trader.js');
+var PostgresqlInterface = require('../../lib/protocol/db/postgresql_interface.js');
+
+var db = 'psql://lamassu:lamassu@localhost/lamassu-test';
+var psqlInterface = new PostgresqlInterface(db);
+
+var CURRENCY = 'USD';
+
+describe('trader/send', function () {
+ var trader = new Trader(psqlInterface);
+ trader.config = {
+ exchanges: {
+ settings: { currency: CURRENCY }
+ }
+ };
+
+ it('should call `balance` on the transfer exchange', function (done) {
+ trader.transferExchange = {
+ balance: function (callback) {
+ callback(null, 100);
+ }
+ };
+
+ trader.pollBalance(function (err, balance) {
+ assert.notOk(err);
+ assert.equal(trader.balance.transferBalance, 100);
+ assert.ok(trader.balance.timestamp);
+ done();
+ });
+ });
+
+ it('should call `ticker` on the ticker exchange', function (done) {
+ trader.tickerExchange = {
+ ticker: function (currency, callback) {
+ assert.equal(currency, CURRENCY);
+ callback(null, 100);
+ }
+ };
+
+ trader.pollRate(function (err, rate) {
+ var rate;
+
+ assert.notOk(err);
+ rate = trader.rate(CURRENCY);
+ assert.equal(rate.rate, 100);
+ assert.ok(rate.timestamp);
+ done();
+ });
+ });
+}); | |
ae753386502263230e7616e9436a41dd43c07e21 | direct-demo/direct-demo.js | direct-demo/direct-demo.js | /**
* Copyright (C) 2009-2013 Akiban Technologies, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
function _register(registrar) {
registrar.register(JSON.stringify(
{"method":"GET","name":"totalComp","function":"computeTotalCompensation",
"pathParams":"/<empno>", "queryParams":"start","in":"empno int required, start Date default `2000-01-01`","out":"String"}));
}
/*
* Compute the total amount of compensation paid
* to the specified employee by computing
* rate * duration for each period of employment.
*/
function computeTotalCompensation(empno, start) {
var emp = com.akiban.direct.Direct.context.extent.getEmployee(empno);
var total = 0;
var today = new Date();
var summary = {from: today, to: today, total: total};
for (var salary in Iterator(emp.salaries.sort("to_date"),where("to_date > " + start))) {
var from = salary.fromDate;
var to = salary.toDate.time < 0
? today : salary.toDate;
if (from <summary > summary.to) {
summary.to = to;
}
var duration = (to.getTime() - from.getTime()) / 86400000 / 365;
summary.total += salary.salary * duration;
}
return JSON.stringify(summary);
} | Add a small demo file | Add a small demo file | JavaScript | agpl-3.0 | ngaut/sql-layer,jaytaylor/sql-layer,qiuyesuifeng/sql-layer,relateiq/sql-layer,jaytaylor/sql-layer,relateiq/sql-layer,relateiq/sql-layer,shunwang/sql-layer-1,jaytaylor/sql-layer,shunwang/sql-layer-1,wfxiang08/sql-layer-1,qiuyesuifeng/sql-layer,ngaut/sql-layer,shunwang/sql-layer-1,wfxiang08/sql-layer-1,relateiq/sql-layer,shunwang/sql-layer-1,ngaut/sql-layer,ngaut/sql-layer,qiuyesuifeng/sql-layer,qiuyesuifeng/sql-layer,wfxiang08/sql-layer-1,wfxiang08/sql-layer-1,jaytaylor/sql-layer | ---
+++
@@ -0,0 +1,47 @@
+/**
+ * Copyright (C) 2009-2013 Akiban Technologies, Inc.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+function _register(registrar) {
+ registrar.register(JSON.stringify(
+ {"method":"GET","name":"totalComp","function":"computeTotalCompensation",
+ "pathParams":"/<empno>", "queryParams":"start","in":"empno int required, start Date default `2000-01-01`","out":"String"}));
+}
+
+/*
+ * Compute the total amount of compensation paid
+ * to the specified employee by computing
+ * rate * duration for each period of employment.
+ */
+function computeTotalCompensation(empno, start) {
+ var emp = com.akiban.direct.Direct.context.extent.getEmployee(empno);
+
+ var total = 0;
+ var today = new Date();
+ var summary = {from: today, to: today, total: total};
+
+ for (var salary in Iterator(emp.salaries.sort("to_date"),where("to_date > " + start))) {
+ var from = salary.fromDate;
+ var to = salary.toDate.time < 0
+ ? today : salary.toDate;
+ if (from <summary > summary.to) {
+ summary.to = to;
+ }
+ var duration = (to.getTime() - from.getTime()) / 86400000 / 365;
+ summary.total += salary.salary * duration;
+ }
+ return JSON.stringify(summary);
+} | |
17a2a18e5c7cf0b52059ef70a28dccfd66de6c1b | packages/activemodel-adapter/tests/integration/active-model-adapter-serializer-test.js | packages/activemodel-adapter/tests/integration/active-model-adapter-serializer-test.js | var env, store, adapter, User;
var originalAjax;
module("integration/active_model_adapter_serializer - AMS Adapter and Serializer", {
setup: function() {
originalAjax = Ember.$.ajax;
User = DS.Model.extend({
firstName: DS.attr()
});
env = setupStore({
user: User,
adapter: DS.ActiveModelAdapter
});
store = env.store;
adapter = env.adapter;
env.registry.register('serializer:application', DS.ActiveModelSerializer);
},
teardown: function() {
Ember.$.ajax = originalAjax;
}
});
test('errors are camelCased and are expected under the `errors` property of the payload', function() {
var jqXHR = {
status: 422,
responseText: JSON.stringify({
errors: {
first_name: ["firstName error"]
}
})
};
Ember.$.ajax = function(hash) {
hash.error(jqXHR);
};
var user;
Ember.run(function() {
user = store.push('user', { id: 1 });
});
Ember.run(function() {
user.save().then(null, function() {
var errors = user.get('errors');
ok(errors.has('firstName'), "there are errors for the firstName attribute");
deepEqual(errors.errorsFor('firstName').getEach('message'), ['firstName error']);
});
});
});
| Test that active model adapter passes errors to serializer | Test that active model adapter passes errors to serializer
Thanks to @pangratz for putting this test together. Currently we only have tests
for the adapter and serializer correctly behaving in isolation.
| JavaScript | mit | HeroicEric/data,simaob/data,PrecisionNutrition/data,yaymukund/data,minasmart/data,danmcclain/data,splattne/data,yaymukund/data,tonywok/data,H1D/data,offirgolan/data,Eric-Guo/data,duggiefresh/data,intuitivepixel/data,gabriel-letarte/data,webPapaya/data,dustinfarris/data,greyhwndz/data,fsmanuel/data,kappiah/data,dustinfarris/data,gabriel-letarte/data,nickiaconis/data,faizaanshamsi/data,H1D/data,wecc/data,webPapaya/data,fsmanuel/data,ryanpatrickcook/data,Robdel12/data,usecanvas/data,tstirrat/ember-data,nickiaconis/data,topaxi/data,vikram7/data,sebweaver/data,gniquil/data,yaymukund/data,tarzan/data,nickiaconis/data,wecc/data,Eric-Guo/data,hibariya/data,simaob/data,usecanvas/data,eriktrom/data,pdud/data,offirgolan/data,lostinpatterns/data,seanpdoyle/data,sammcgrail/data,davidpett/data,whatthewhat/data,tstirrat/ember-data,EmberSherpa/data,Turbo87/ember-data,Eric-Guo/data,Turbo87/ember-data,lostinpatterns/data,courajs/data,offirgolan/data,danmcclain/data,sebastianseilund/data,sammcgrail/data,hibariya/data,intuitivepixel/data,duggiefresh/data,splattne/data,bf4/data,tarzan/data,tonywok/data,topaxi/data,HeroicEric/data,arenoir/data,PrecisionNutrition/data,whatthewhat/data,EmberSherpa/data,thaume/data,tonywok/data,XrXr/data,HeroicEric/data,davidpett/data,fpauser/data,thaume/data,ryanpatrickcook/data,InboxHealth/data,InboxHealth/data,splattne/data,bf4/data,jgwhite/data,bcardarella/data,funtusov/data,BookingSync/data,EmberSherpa/data,sebweaver/data,Kuzirashi/data,flowjzh/data,swarmbox/data,thaume/data,intuitivepixel/data,gniquil/data,vikram7/data,greyhwndz/data,workmanw/data,zoeesilcock/data,simaob/data,Turbo87/ember-data,workmanw/data,greyhwndz/data,heathharrelson/data,gkaran/data,funtusov/data,faizaanshamsi/data,whatthewhat/data,ryanpatrickcook/data,andrejunges/data,pdud/data,danmcclain/data,stefanpenner/data,seanpdoyle/data,gniquil/data,thaume/data,Robdel12/data,minasmart/data,courajs/data,danmcclain/data,swarmbox/data,gkaran/data,minasmart/data,andrejunges/data,vikram7/data,heathharrelson/data,workmanw/data,sebastianseilund/data,hibariya/data,acburdine/data,rtablada/data,heathharrelson/data,mphasize/data,fpauser/data,rtablada/data,simaob/data,H1D/data,minasmart/data,fpauser/data,HeroicEric/data,arenoir/data,sebweaver/data,gabriel-letarte/data,heathharrelson/data,flowjzh/data,sebweaver/data,Kuzirashi/data,davidpett/data,faizaanshamsi/data,jgwhite/data,flowjzh/data,XrXr/data,duggiefresh/data,arenoir/data,acburdine/data,swarmbox/data,zoeesilcock/data,Robdel12/data,InboxHealth/data,stefanpenner/data,whatthewhat/data,mphasize/data,gkaran/data,intuitivepixel/data,arenoir/data,mphasize/data,PrecisionNutrition/data,duggiefresh/data,greyhwndz/data,kappiah/data,zoeesilcock/data,ryanpatrickcook/data,kappiah/data,webPapaya/data,workmanw/data,eriktrom/data,lostinpatterns/data,Turbo87/ember-data,tstirrat/ember-data,stefanpenner/data,nickiaconis/data,zoeesilcock/data,BookingSync/data,pdud/data,andrejunges/data,Kuzirashi/data,acburdine/data,gniquil/data,bcardarella/data,eriktrom/data,sebastianseilund/data,usecanvas/data,bcardarella/data,rtablada/data,InboxHealth/data,webPapaya/data,yaymukund/data,gkaran/data,davidpett/data,topaxi/data,bf4/data,pdud/data,XrXr/data,splattne/data,andrejunges/data,mphasize/data,Eric-Guo/data,Kuzirashi/data,seanpdoyle/data,BookingSync/data,hibariya/data,jgwhite/data,kappiah/data,rtablada/data,seanpdoyle/data,fsmanuel/data,eriktrom/data,sammcgrail/data,BookingSync/data,tarzan/data,bcardarella/data,sammcgrail/data,courajs/data,sebastianseilund/data,faizaanshamsi/data,vikram7/data,tstirrat/ember-data,dustinfarris/data,offirgolan/data,PrecisionNutrition/data,fsmanuel/data,H1D/data,acburdine/data,tonywok/data,bf4/data,gabriel-letarte/data,funtusov/data,EmberSherpa/data,wecc/data,topaxi/data,XrXr/data,Robdel12/data,tarzan/data,dustinfarris/data,swarmbox/data,stefanpenner/data,fpauser/data,lostinpatterns/data,wecc/data,usecanvas/data,courajs/data,funtusov/data,jgwhite/data,flowjzh/data | ---
+++
@@ -0,0 +1,54 @@
+var env, store, adapter, User;
+var originalAjax;
+
+module("integration/active_model_adapter_serializer - AMS Adapter and Serializer", {
+ setup: function() {
+ originalAjax = Ember.$.ajax;
+
+ User = DS.Model.extend({
+ firstName: DS.attr()
+ });
+
+ env = setupStore({
+ user: User,
+ adapter: DS.ActiveModelAdapter
+ });
+
+ store = env.store;
+ adapter = env.adapter;
+
+ env.registry.register('serializer:application', DS.ActiveModelSerializer);
+ },
+
+ teardown: function() {
+ Ember.$.ajax = originalAjax;
+ }
+});
+
+test('errors are camelCased and are expected under the `errors` property of the payload', function() {
+ var jqXHR = {
+ status: 422,
+ responseText: JSON.stringify({
+ errors: {
+ first_name: ["firstName error"]
+ }
+ })
+ };
+
+ Ember.$.ajax = function(hash) {
+ hash.error(jqXHR);
+ };
+
+ var user;
+ Ember.run(function() {
+ user = store.push('user', { id: 1 });
+ });
+
+ Ember.run(function() {
+ user.save().then(null, function() {
+ var errors = user.get('errors');
+ ok(errors.has('firstName'), "there are errors for the firstName attribute");
+ deepEqual(errors.errorsFor('firstName').getEach('message'), ['firstName error']);
+ });
+ });
+}); | |
dbe09fc00bb05ada08a0497e7242199e0935f464 | solutions/uri/1006/1006.js | solutions/uri/1006/1006.js | const input = require('fs').readFileSync('/dev/stdin', 'utf8')
const [a, b, c] = input
.trim()
.split('\n')
.map(x => parseFloat(x))
console.log(`MEDIA = ${((a * 2.0 + b * 3.0 + c * 5.0) / 10.0).toFixed(1)}`)
| Solve Average 2 in javascript | Solve Average 2 in javascript
| JavaScript | mit | deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground | ---
+++
@@ -0,0 +1,8 @@
+const input = require('fs').readFileSync('/dev/stdin', 'utf8')
+
+const [a, b, c] = input
+ .trim()
+ .split('\n')
+ .map(x => parseFloat(x))
+
+console.log(`MEDIA = ${((a * 2.0 + b * 3.0 + c * 5.0) / 10.0).toFixed(1)}`) | |
352ab0a798ed1529f30563cfec997b24569a81a9 | src/framework/framework_pack.js | src/framework/framework_pack.js | pc.extend(pc, function () {
var Pack = function (data) {
this.hierarchy = data.hierarchy;
this.settings = data.settings;
};
Pack.prototype = {
};
return {
Pack: Pack,
/**
* @function
* @name pc.loadPack
* @description Load and initialise a new Pack. The Pack is loaded, added to the root of the hierarchy and any new scripts are initialized.
* @param {String} guid The GUID of the Pack to load
* @param {pc.ApplicationContext} context The ApplicationContext containing the root hierarchy and the ScriptComponentSystem
* @param {Function} success Callback fired when the Pack is loaded and initialized, passed the new Entity that was created
* @param {Function} error Callback fired if there are problems, passed a list of error messages
* @param {Function} progress Callback fired on each progress event, usually when a file or Entity is loaded, passed a percentage complete value
*/
// loadPack: function (guid, context, success, error, progress) {
// var request = new pc.resources.PackRequest(guid);
// context.loader.request(request, function (resources) {
// var pack = resources[guid];
// // add to hierarchy
// context.root.addChild(pack.hierarchy);
// // Initialise any systems with an initialize() method after pack is loaded
// pc.ComponentSystem.initialize(pack.hierarchy);
// // callback
// if (success) {
// success(pack);
// }
// }.bind(this), function (errors) {
// // error
// if (error) {
// error(errors);
// }
// }.bind(this), function (value) {
// // progress
// if (progress) {
// progress(value);
// }
// }.bind(this));
// }
};
}()); | pc.extend(pc, function () {
var Pack = function (data) {
this.hierarchy = data.hierarchy;
this.settings = data.settings;
};
return {
Pack: Pack
};
}()); | Remove pc.loadPack from the docs since the function doesn't actually exist - it's commented out in the sourcebase. | Remove pc.loadPack from the docs since the function doesn't actually exist - it's commented out in the sourcebase.
| JavaScript | mit | SuperStarPL/engine,nizihabi/engine,MicroWorldwide/PlayCanvas,RainsSoft/engine,horryq/engine-1,shinate/engine,guycalledfrank/engine,aidinabedi/playcanvas-engine,horryq/engine-1,sanyaade-teachings/engine,sanyaade-teachings/engine,sereepap2029/playcanvas,H1Gdev/engine,guycalledfrank/engine,playcanvas/engine,nizihabi/engine,sanyaade-teachings/engine,maxwellalive/engine,sereepap2029/playcanvas,nizihabi/engine,sereepap2029/playcanvas,RainsSoft/engine,playcanvas/engine,SuperStarPL/engine,RainsSoft/engine,MicroWorldwide/PlayCanvas,3DGEOM/engine,maxwellalive/engine,horryq/engine-1,maxwellalive/engine,aidinabedi/playcanvas-engine,3DGEOM/engine,shinate/engine,SuperStarPL/engine,H1Gdev/engine,3DGEOM/engine,shinate/engine | ---
+++
@@ -4,48 +4,7 @@
this.settings = data.settings;
};
- Pack.prototype = {
-
- };
-
return {
- Pack: Pack,
- /**
- * @function
- * @name pc.loadPack
- * @description Load and initialise a new Pack. The Pack is loaded, added to the root of the hierarchy and any new scripts are initialized.
- * @param {String} guid The GUID of the Pack to load
- * @param {pc.ApplicationContext} context The ApplicationContext containing the root hierarchy and the ScriptComponentSystem
- * @param {Function} success Callback fired when the Pack is loaded and initialized, passed the new Entity that was created
- * @param {Function} error Callback fired if there are problems, passed a list of error messages
- * @param {Function} progress Callback fired on each progress event, usually when a file or Entity is loaded, passed a percentage complete value
- */
- // loadPack: function (guid, context, success, error, progress) {
- // var request = new pc.resources.PackRequest(guid);
- // context.loader.request(request, function (resources) {
- // var pack = resources[guid];
-
- // // add to hierarchy
- // context.root.addChild(pack.hierarchy);
-
- // // Initialise any systems with an initialize() method after pack is loaded
- // pc.ComponentSystem.initialize(pack.hierarchy);
-
- // // callback
- // if (success) {
- // success(pack);
- // }
- // }.bind(this), function (errors) {
- // // error
- // if (error) {
- // error(errors);
- // }
- // }.bind(this), function (value) {
- // // progress
- // if (progress) {
- // progress(value);
- // }
- // }.bind(this));
- // }
+ Pack: Pack
};
}()); |
3dc57d08a8944ebc3b4a60622118e10ceaeca116 | lib/bramqp.js | lib/bramqp.js | var specification = require('./specification');
var ConnectionHandle = require('./connectionHandle');
exports.initialize = function(socket, spec, callback) {
socket.on('error', callback);
socket.on('connect', function() {
var handle = new ConnectionHandle(socket, spec);
handle.once('init', function() {
callback(null, handle);
});
});
};
| var specification = require('./specification');
var ConnectionHandle = require('./connectionHandle');
exports.initialize = function(socket, spec, callback) {
socket.once('connect', function() {
var handle = new ConnectionHandle(socket, spec);
handle.once('init', function() {
callback(null, handle);
});
});
};
| Fix initialize running callback multiple times | Fix initialize running callback multiple times
| JavaScript | mit | bakkerthehacker/bramqp,sega-yarkin/bramqp | ---
+++
@@ -3,8 +3,7 @@
var ConnectionHandle = require('./connectionHandle');
exports.initialize = function(socket, spec, callback) {
- socket.on('error', callback);
- socket.on('connect', function() {
+ socket.once('connect', function() {
var handle = new ConnectionHandle(socket, spec);
handle.once('init', function() {
callback(null, handle); |
40d3b9d9bd8657769d9ea162dc0a41b4322f4af2 | lib/withdrawal_payments_queue.js | lib/withdrawal_payments_queue.js | var gateway = require('./gateway');
var EventEmitter = require("events").EventEmitter;
var util = require('util');
var queue = new EventEmitter;
function pollIncoming(fn) {
gateway.payments.listIncoming(function(err, payments) {
if (err) {
console.log('error:', err);
} else {
if (payments[0]) {
queue.emit('payment:withdrawal', payments[0]);
}
}
setTimeout(function() {
fn(pollIncoming);
},500);
});
}
queue.work = function() {
pollIncoming(pollIncoming);
}
module.exports = queue;
| Add withdrawal payments queue event emitter. | [FEATURE] Add withdrawal payments queue event emitter.
| JavaScript | isc | whotooktwarden/gatewayd,xdv/gatewayd,Parkjeahwan/awegeeks,crazyquark/gatewayd,zealord/gatewayd,xdv/gatewayd,crazyquark/gatewayd,Parkjeahwan/awegeeks,zealord/gatewayd,whotooktwarden/gatewayd | ---
+++
@@ -0,0 +1,27 @@
+var gateway = require('./gateway');
+var EventEmitter = require("events").EventEmitter;
+var util = require('util');
+
+var queue = new EventEmitter;
+
+function pollIncoming(fn) {
+ gateway.payments.listIncoming(function(err, payments) {
+ if (err) {
+ console.log('error:', err);
+ } else {
+ if (payments[0]) {
+ queue.emit('payment:withdrawal', payments[0]);
+ }
+ }
+ setTimeout(function() {
+ fn(pollIncoming);
+ },500);
+ });
+}
+
+queue.work = function() {
+ pollIncoming(pollIncoming);
+}
+
+module.exports = queue;
+ | |
a7642fe014cf295e43d65435879b96789c6509dd | cli/main.js | cli/main.js | #!/usr/bin/env node
'use strict'
require('debug').enable('UCompiler:*')
const UCompiler = require('..')
const knownCommands = ['go', 'watch']
const parameters = process.argv.slice(2)
if (!parameters.length || knownCommands.indexOf(parameters[0]) === -1) {
console.log('Usage: ucompiler go|watch [path]')
process.exit(0)
}
if (parameters[0] === 'go') {
// TODO: Compile only those by default that are in rules
UCompiler.compile(parameters[1] || '.', {defaultRoot: process.cwd()})
}
| Add a basic cli script | :new: Add a basic cli script
| JavaScript | mit | steelbrain/UCompiler | ---
+++
@@ -0,0 +1,17 @@
+#!/usr/bin/env node
+'use strict'
+
+require('debug').enable('UCompiler:*')
+const UCompiler = require('..')
+const knownCommands = ['go', 'watch']
+const parameters = process.argv.slice(2)
+
+if (!parameters.length || knownCommands.indexOf(parameters[0]) === -1) {
+ console.log('Usage: ucompiler go|watch [path]')
+ process.exit(0)
+}
+
+if (parameters[0] === 'go') {
+ // TODO: Compile only those by default that are in rules
+ UCompiler.compile(parameters[1] || '.', {defaultRoot: process.cwd()})
+} | |
d5f135f198a4855564c381e375f4c3a8fad97a63 | Native/Test/Fabric/fixed-array-member-access.js | Native/Test/Fabric/fixed-array-member-access.js |
FABRIC = wrapFabricClient(createFabricClient());
node = FABRIC.DependencyGraph.createNode("foo");
node.addMember( "foo", "Integer[5]" );
node.setData( "foo", [6,4,7,2,1] );
print( node.getDataSize( "foo", 0 ) );
print( node.getDataElement( "foo", 0, 3 ) );
| FC = createFabricClient();
FABRIC = wrapFabricClient(FC);
node = FABRIC.DependencyGraph.createNode("foo");
node.addMember( "foo", "Integer[5]" );
node.setData( "foo", [6,4,7,2,1] );
print( node.getDataSize( "foo", 0 ) );
print( node.getDataElement( "foo", 0, 3 ) );
FABRIC.flush();
FC.dispose();
| Verify no memory leaks in test | Verify no memory leaks in test
| JavaScript | agpl-3.0 | chbfiv/fabric-engine-old,chbfiv/fabric-engine-old,chbfiv/fabric-engine-old,errordeveloper/fe-devel,errordeveloper/fe-devel,chbfiv/fabric-engine-old,chbfiv/fabric-engine-old,errordeveloper/fe-devel,chbfiv/fabric-engine-old,errordeveloper/fe-devel,errordeveloper/fe-devel,chbfiv/fabric-engine-old,errordeveloper/fe-devel,errordeveloper/fe-devel | ---
+++
@@ -1,8 +1,11 @@
-
-FABRIC = wrapFabricClient(createFabricClient());
+FC = createFabricClient();
+FABRIC = wrapFabricClient(FC);
node = FABRIC.DependencyGraph.createNode("foo");
node.addMember( "foo", "Integer[5]" );
node.setData( "foo", [6,4,7,2,1] );
print( node.getDataSize( "foo", 0 ) );
print( node.getDataElement( "foo", 0, 3 ) );
+
+FABRIC.flush();
+FC.dispose(); |
cbd87c2bff4d9c03d21853079734e7ed3efdd58a | app/mixins/tooltip-enabled.js | app/mixins/tooltip-enabled.js | import Ember from 'ember';
export default Ember.Mixin.create({
/**
* Attribute bindings for mixin's component element
* @property {array} attributeBindings
*/
attributeBindings: [ 'data-placement', 'title' ],
/**
* Enables the tooltip functionality, based on a passed-in `title` attribute
* @method enableTooltip
*/
enableTooltip: function () {
if ( this.get( 'title' )) {
this.$().tooltip();
}
}.on( 'didInsertElement' )
}); | Add TooltipEnabled mixin for title-based tooltips | Add TooltipEnabled mixin for title-based tooltips
| JavaScript | mit | juwara0/sl-ember-components,Suven/sl-ember-components,alxyuu/sl-ember-components,theoshu/sl-ember-components,azizpunjani/sl-ember-components,jonathandavidson/sl-ember-components,softlayer/sl-ember-components,Suven/sl-ember-components,notmessenger/sl-ember-components,alxyuu/sl-ember-components,notmessenger/sl-ember-components,erangeles/sl-ember-components,theoshu/sl-ember-components,SpikedKira/sl-ember-components,softlayer/sl-ember-components,azizpunjani/sl-ember-components,SpikedKira/sl-ember-components,juwara0/sl-ember-components,erangeles/sl-ember-components | ---
+++
@@ -0,0 +1,20 @@
+import Ember from 'ember';
+
+export default Ember.Mixin.create({
+
+ /**
+ * Attribute bindings for mixin's component element
+ * @property {array} attributeBindings
+ */
+ attributeBindings: [ 'data-placement', 'title' ],
+
+ /**
+ * Enables the tooltip functionality, based on a passed-in `title` attribute
+ * @method enableTooltip
+ */
+ enableTooltip: function () {
+ if ( this.get( 'title' )) {
+ this.$().tooltip();
+ }
+ }.on( 'didInsertElement' )
+}); | |
4201b52166149eba80a446731517e7ef4532fdd7 | src/store/configureStore.dev.js | src/store/configureStore.dev.js | // This file merely configures the store for hot reloading.
// This boilerplate file is likely to be the same for each project that uses Redux.
// With Redux, the actual stores are in /reducers.
import {createStore, compose, applyMiddleware} from 'redux';
import reduxImmutableStateInvariant from 'redux-immutable-state-invariant';
import thunkMiddleware from 'redux-thunk';
import rootReducer from '../reducers';
export default function configureStore(initialState) {
const middlewares = [
// Add other middleware on this line...
// Redux middleware that spits an error on you when you try to mutate your state either inside a dispatch or between dispatches.
reduxImmutableStateInvariant(),
// thunk middleware can also accept an extra argument to be passed to each thunk action
// https://github.com/gaearon/redux-thunk#injecting-a-custom-argument
thunkMiddleware,
];
const store = createStore(rootReducer, initialState, compose(
applyMiddleware(...middlewares),
window.devToolsExtension ? window.devToolsExtension() : f => f // add support for Redux dev tools
)
);
if (module.hot) {
// Enable Webpack hot module replacement for reducers
module.hot.accept('../reducers', () => {
const nextReducer = require('../reducers').default; // eslint-disable-line global-require
store.replaceReducer(nextReducer);
});
}
return store;
}
| // This file merely configures the store for hot reloading.
// This boilerplate file is likely to be the same for each project that uses Redux.
// With Redux, the actual stores are in /reducers.
import {createStore, compose, applyMiddleware} from 'redux';
import reduxImmutableStateInvariant from 'redux-immutable-state-invariant';
import thunkMiddleware from 'redux-thunk';
import rootReducer from '../reducers';
export default function configureStore(initialState) {
const middlewares = [
// Add other middleware on this line...
// Redux middleware that spits an error on you when you try to mutate your state either inside a dispatch or between dispatches.
reduxImmutableStateInvariant(),
// thunk middleware can also accept an extra argument to be passed to each thunk action
// https://github.com/gaearon/redux-thunk#injecting-a-custom-argument
thunkMiddleware,
];
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; // add support for Redux dev tools
const store = createStore(rootReducer, initialState, composeEnhancers(
applyMiddleware(...middlewares)
)
);
if (module.hot) {
// Enable Webpack hot module replacement for reducers
module.hot.accept('../reducers', () => {
const nextReducer = require('../reducers').default; // eslint-disable-line global-require
store.replaceReducer(nextReducer);
});
}
return store;
}
| Upgrade for the Redux DevTools extension. | Upgrade for the Redux DevTools extension.
| JavaScript | mit | danpersa/remindmetolive-react,svitekpavel/chatbot-website,coryhouse/react-slingshot,flibertigibet/react-redux-starter-kit-custom,akataz/theSite,barbel840113/testapp,garusis/up-designer,aaronholmes/yelp-clone,barbel840113/testapp,luanatsainsburys/road-runner,danpersa/remindmetolive-react,svitekpavel/Conway-s-Game-of-Life,kpuno/survey-app,MouseZero/nightlife-frontend,garusis/up-designer,git-okuzenko/react-redux,flibertigibet/react-redux-starter-kit-custom,svitekpavel/chatbot-website,danpersa/remindmetolive-react,oded-soffrin/gkm_viewer,lisavogtsf/canned-react-slingshot-app,AurimasSk/DemoStore,AurimasSk/DemoStore,aaronholmes/yelp-clone,svitekpavel/Conway-s-Game-of-Life,coryhouse/react-slingshot,BenMGilman/react-lunch-and-learn,kpuno/survey-app,oshalygin/react-slingshot,git-okuzenko/react-redux,lisavogtsf/canned-react-slingshot-app,oded-soffrin/gkm_viewer,BenMGilman/react-lunch-and-learn,akataz/theSite,MouseZero/nightlife-frontend,oshalygin/react-slingshot,luanatsainsburys/road-runner | ---
+++
@@ -19,9 +19,9 @@
thunkMiddleware,
];
- const store = createStore(rootReducer, initialState, compose(
- applyMiddleware(...middlewares),
- window.devToolsExtension ? window.devToolsExtension() : f => f // add support for Redux dev tools
+ const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; // add support for Redux dev tools
+ const store = createStore(rootReducer, initialState, composeEnhancers(
+ applyMiddleware(...middlewares)
)
);
|
c1a1cdd460d1057be1ea1ca322950640d2823944 | src/components/InfiniteList.react.js | src/components/InfiniteList.react.js | import React, { Component, PropTypes } from 'react';
class InfiniteList extends Component {
constructor(props, context) {
super(props, context);
}
render() {
return null;
}
}
export default InfiniteList;
| Add in an infinite list component. | Add in an infinite list component.
| JavaScript | mit | mareksuscak/surfing-gallery,mareksuscak/surfing-gallery | ---
+++
@@ -0,0 +1,13 @@
+import React, { Component, PropTypes } from 'react';
+
+class InfiniteList extends Component {
+ constructor(props, context) {
+ super(props, context);
+ }
+
+ render() {
+ return null;
+ }
+}
+
+export default InfiniteList; | |
d8eb90edcf34e1c15cf862eece8fef831f10c105 | packages/core/src/contexts/listSpacing.js | packages/core/src/contexts/listSpacing.js | // #FIXME: use React navive context API when upgraded to v16+
import createReactContext from 'create-react-context';
const ListSpacingContext = createReactContext(true);
export default ListSpacingContext;
| Create a context for configuring vertical spacing of <List> | Create a context for configuring vertical spacing of <List>
| JavaScript | apache-2.0 | iCHEF/gypcrete,iCHEF/gypcrete | ---
+++
@@ -0,0 +1,6 @@
+// #FIXME: use React navive context API when upgraded to v16+
+import createReactContext from 'create-react-context';
+
+const ListSpacingContext = createReactContext(true);
+
+export default ListSpacingContext; | |
5135bd1a50894c11f09cc982f0f140222fe0d691 | backend/servers/mcapi/db/model/sample-common.js | backend/servers/mcapi/db/model/sample-common.js | module.exports = function(r) {
return {
removeUnusedSamples
};
function* removeUnusedSamples(sampleIds) {
for (let i = 0; i < sampleIds.length; i++) {
let sampleId = sampleIds[i];
let p2s = yield r.table('process2sample').getAll(sampleId, {index: 'sample_id'});
if (!p2s.length) {
// Sample is not used anywhere
yield removeSample(sampleId);
}
}
}
function* removeSample(sampleId) {
yield r.table('project2sample').getAll(sampleId, {index: 'sample_id'}).delete();
yield r.table('experiment2sample').getAll(sampleId, {index: 'sample_id'}).delete();
// TODO: How to delete property sets associated with non-existent samples?
// let propertySets = yield r.table('sample2propertyset').getAll(sampleId, {index: 'sample_id'});
yield r.table('sample2propertyset').getAll(sampleId, {index: 'sample_id'}).delete();
yield r.table('sample2datafile').getAll(sampleId, {index: 'sample_id'}).delete();
}
};
| Create a module for commonly needed sample functionality. | Create a module for commonly needed sample functionality.
| JavaScript | mit | materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org | ---
+++
@@ -0,0 +1,28 @@
+module.exports = function(r) {
+ return {
+ removeUnusedSamples
+ };
+
+ function* removeUnusedSamples(sampleIds) {
+ for (let i = 0; i < sampleIds.length; i++) {
+ let sampleId = sampleIds[i];
+ let p2s = yield r.table('process2sample').getAll(sampleId, {index: 'sample_id'});
+ if (!p2s.length) {
+ // Sample is not used anywhere
+ yield removeSample(sampleId);
+ }
+ }
+ }
+
+ function* removeSample(sampleId) {
+ yield r.table('project2sample').getAll(sampleId, {index: 'sample_id'}).delete();
+ yield r.table('experiment2sample').getAll(sampleId, {index: 'sample_id'}).delete();
+
+ // TODO: How to delete property sets associated with non-existent samples?
+ // let propertySets = yield r.table('sample2propertyset').getAll(sampleId, {index: 'sample_id'});
+ yield r.table('sample2propertyset').getAll(sampleId, {index: 'sample_id'}).delete();
+
+
+ yield r.table('sample2datafile').getAll(sampleId, {index: 'sample_id'}).delete();
+ }
+}; | |
894ca9adcb73e6f799aa6e1ca4bb59ba3ea45166 | src/create-schedule.js | src/create-schedule.js | const fs = require('fs');
const PDFDocument = require('pdfkit');
var doc = new PDFDocument();
doc.pipe(fs.createWriteStream('templates/resources/pdf/schedule.pdf'));
doc
.moveTo(0,0)
.lineTo(100, 100)
.stroke();
doc.end();
| Create a skeletal pdf generation file | Create a skeletal pdf generation file
| JavaScript | mit | Balletboetiek/website,Balletboetiek/website,Balletboetiek/website | ---
+++
@@ -0,0 +1,13 @@
+const fs = require('fs');
+
+const PDFDocument = require('pdfkit');
+
+var doc = new PDFDocument();
+doc.pipe(fs.createWriteStream('templates/resources/pdf/schedule.pdf'));
+
+doc
+ .moveTo(0,0)
+ .lineTo(100, 100)
+ .stroke();
+
+doc.end(); | |
6dc3d5db2efcd632b0a46f86394408aefe868967 | test/pem_as_hmac_key_spec.js | test/pem_as_hmac_key_spec.js |
describe('pem-as-hmac-key', function ()
{
var token;
before(function ()
{
// generate HS256 token using public PEM string as key
var expires = new Date();
expires.setSeconds(expires.getSeconds() + 60);
token = new jsjws.JWT().generateJWTByKey({ alg: 'HS256' }, payload, expires, pub_pem);
});
it('should verify token using public PEM string as public key when no algorithm is specified', function ()
{
// verify token using public PEM string as public key
new jsjws.JWT().verifyJWTByKey(token, pub_pem);
});
it('should fail to verify token using public PEM string as public key when algorithm is specified', function ()
{
// specify expected algorithm this time
expect(function ()
{
new jsjws.JWT().verifyJWTByKey(token,
{
allowed_algs: ['RS256']
}, pub_pem);
}).to.throw('algorithm not allowed: HS256');
});
it('should fail to verify token using public key', function ()
{
expect(function ()
{
new jsjws.JWT().verifyJWTByKey(token, pub_keys['RS256'].fast);
}).to.throw();
expect(function ()
{
new jsjws.JWT().verifyJWTByKey(token, pub_keys['RS256'].slow);
}).to.throw();
});
});
| Add test to check we can restrict alg when PEM is used | Add test to check we can restrict alg when PEM is used
| JavaScript | mit | davedoesdev/node-jsjws,davedoesdev/node-jsjws,davedoesdev/node-jsjws | ---
+++
@@ -0,0 +1,46 @@
+
+
+describe('pem-as-hmac-key', function ()
+{
+ var token;
+
+ before(function ()
+ {
+ // generate HS256 token using public PEM string as key
+ var expires = new Date();
+ expires.setSeconds(expires.getSeconds() + 60);
+ token = new jsjws.JWT().generateJWTByKey({ alg: 'HS256' }, payload, expires, pub_pem);
+ });
+
+ it('should verify token using public PEM string as public key when no algorithm is specified', function ()
+ {
+ // verify token using public PEM string as public key
+ new jsjws.JWT().verifyJWTByKey(token, pub_pem);
+ });
+
+ it('should fail to verify token using public PEM string as public key when algorithm is specified', function ()
+ {
+ // specify expected algorithm this time
+ expect(function ()
+ {
+ new jsjws.JWT().verifyJWTByKey(token,
+ {
+ allowed_algs: ['RS256']
+ }, pub_pem);
+ }).to.throw('algorithm not allowed: HS256');
+ });
+
+ it('should fail to verify token using public key', function ()
+ {
+ expect(function ()
+ {
+ new jsjws.JWT().verifyJWTByKey(token, pub_keys['RS256'].fast);
+ }).to.throw();
+
+ expect(function ()
+ {
+ new jsjws.JWT().verifyJWTByKey(token, pub_keys['RS256'].slow);
+ }).to.throw();
+ });
+});
+ | |
058ec9922c74ee76837b0a91bf5e4b85a7ac07e2 | test/exception-bad-this.js | test/exception-bad-this.js | // Copyright (C) 2014 Domenic Denicola. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
description: Array.prototype.includes should fail if used on a null or undefined this
---*/
assert.throws(TypeError, function () {
Array.prototype.includes.call(null, 'a');
});
assert.throws(TypeError, function () {
Array.prototype.includes.call(undefined, 'a');
});
| Add test for throwing on bad `this` | Add test for throwing on bad `this`
Fixes @caitp's review comment at https://codereview.chromium.org/771863002/diff/60001/test/mjsunit/harmony/array-includes-to-object.js.
| JavaScript | bsd-2-clause | tc39/Array.prototype.includes,tc39/Array.prototype.includes,tc39/Array.prototype.includes | ---
+++
@@ -0,0 +1,14 @@
+// Copyright (C) 2014 Domenic Denicola. All rights reserved.
+// This code is governed by the BSD license found in the LICENSE file.
+
+/*---
+description: Array.prototype.includes should fail if used on a null or undefined this
+---*/
+
+assert.throws(TypeError, function () {
+ Array.prototype.includes.call(null, 'a');
+});
+
+assert.throws(TypeError, function () {
+ Array.prototype.includes.call(undefined, 'a');
+}); | |
4295d68d536a8f9597cae00f932170523e4b89c0 | static/script/devices/exit/openclosewindow.js | static/script/devices/exit/openclosewindow.js | /**
* @fileOverview Requirejs module for openclosewindow exit strategy.
* Uses a workaround to make the browser think the current window
* was opened by JavaScript, allowing window.close() to close it.
*
* @preserve Copyright (c) 2013 British Broadcasting Corporation
* (http://www.bbc.co.uk) and TAL Contributors (1)
*
* (1) TAL Contributors are listed in the AUTHORS file and at
* https://github.com/fmtvp/TAL/AUTHORS - please extend this file,
* not this notice.
*
* @license 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.
*
* All rights reserved
* Please contact us for an alternative licence
*/
require.def(
'antie/devices/exit/openclosewindow',
['antie/devices/browserdevice'],
function(Device) {
/**
* Exits the application by invoking window.open() on the current window,
* then window.close().
*/
Device.prototype.exit = function() {
// Workaround to make the browser think this window was opened via script
window.open('', '_self');
// Close the current window
window.close();
};
}
);
| Add a new exit strategy, calling window.open() before window.close(), as a workaround for LG devices that do not currently allow window.close() if the current window was not opened by a script. | Add a new exit strategy, calling window.open() before window.close(), as a workaround for LG devices that do not currently allow window.close() if the current window was not opened by a script.
| JavaScript | apache-2.0 | ZeboFranklin/tal,joeyjojo/tal,ZeboFranklin/tal,joeyjojo/tal,joeyjojo/tal,ZeboFranklin/tal,ZeboFranklin/tal,joeyjojo/tal,joeyjojo/tal,ZeboFranklin/tal | ---
+++
@@ -0,0 +1,46 @@
+/**
+ * @fileOverview Requirejs module for openclosewindow exit strategy.
+ * Uses a workaround to make the browser think the current window
+ * was opened by JavaScript, allowing window.close() to close it.
+ *
+ * @preserve Copyright (c) 2013 British Broadcasting Corporation
+ * (http://www.bbc.co.uk) and TAL Contributors (1)
+ *
+ * (1) TAL Contributors are listed in the AUTHORS file and at
+ * https://github.com/fmtvp/TAL/AUTHORS - please extend this file,
+ * not this notice.
+ *
+ * @license 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.
+ *
+ * All rights reserved
+ * Please contact us for an alternative licence
+ */
+
+require.def(
+ 'antie/devices/exit/openclosewindow',
+ ['antie/devices/browserdevice'],
+ function(Device) {
+
+ /**
+ * Exits the application by invoking window.open() on the current window,
+ * then window.close().
+ */
+ Device.prototype.exit = function() {
+ // Workaround to make the browser think this window was opened via script
+ window.open('', '_self');
+
+ // Close the current window
+ window.close();
+ };
+ }
+); | |
823b15e51314bf335a50d775d0e5399f489c5066 | examples/_mac-terminal-app/index.js | examples/_mac-terminal-app/index.js | #!/usr/bin/env node
//
// Can Terminal.app (Mac OS X) accept mouse events?
//
// * click needs "Option" pressing
//
console.log('Start');
process.stdin.setRawMode(true);
process.stdin.resume();
var onData = function onData(aInput) {
console.log(aInput, aInput.toString());
if (aInput.toString() === 'q') {
process.stdin.removeListener('data', onData);
process.stdin.pause()
process.exit(0);
}
};
process.stdin.addListener('data', onData);
| Add a sample of Terminail.app mouse events | Add a sample of Terminail.app mouse events
| JavaScript | mit | kjirou/nodejs-codes | ---
+++
@@ -0,0 +1,23 @@
+#!/usr/bin/env node
+
+//
+// Can Terminal.app (Mac OS X) accept mouse events?
+//
+// * click needs "Option" pressing
+//
+
+console.log('Start');
+
+process.stdin.setRawMode(true);
+process.stdin.resume();
+
+var onData = function onData(aInput) {
+ console.log(aInput, aInput.toString());
+ if (aInput.toString() === 'q') {
+ process.stdin.removeListener('data', onData);
+ process.stdin.pause()
+ process.exit(0);
+ }
+};
+
+process.stdin.addListener('data', onData); | |
bbfd9a2a613d55a16a7db5ef1e6b572137861cb4 | web/src/js/components/General/AuthUserComponent.js | web/src/js/components/General/AuthUserComponent.js | import React from 'react';
import FullScreenProgress from 'general/FullScreenProgress';
import { getCurrentUser } from '../../utils/cognito-auth';
import { goToLogin } from 'navigation/navigation';
class AuthUserComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
userId: null,
}
}
componentWillMount() {
getCurrentUser((user) => {
if (!user) {
goToLogin();
return;
}
this.setState({
userId: user.sub,
});
});
}
render() {
if(!this.state.userId){
return (<FullScreenProgress />);
}
const root = {
height: '100%',
width: '100%',
};
const childrenWithProps = React.Children.map(this.props.children,
(child) => React.cloneElement(child, {
variables: Object.assign({}, this.props.variables, {
userId: this.state.userId
})
})
);
return (
<div style={root}>
{childrenWithProps}
</div>
);
}
}
AuthUserComponent.propTypes = {
variables: React.PropTypes.object,
}
AuthUserComponent.defaultProps = {
variables: {}
}
export default AuthUserComponent;
| Add a wrapper component for the queryrenders that requiere the userId. Pass any extra variables to the wrapper instead. | Add a wrapper component for the queryrenders that requiere the userId. Pass any extra variables to the wrapper instead.
| JavaScript | mpl-2.0 | gladly-team/tab,gladly-team/tab,gladly-team/tab | ---
+++
@@ -0,0 +1,63 @@
+import React from 'react';
+import FullScreenProgress from 'general/FullScreenProgress';
+import { getCurrentUser } from '../../utils/cognito-auth';
+import { goToLogin } from 'navigation/navigation';
+
+class AuthUserComponent extends React.Component {
+
+ constructor(props) {
+ super(props);
+ this.state = {
+ userId: null,
+ }
+ }
+
+ componentWillMount() {
+ getCurrentUser((user) => {
+ if (!user) {
+ goToLogin();
+ return;
+ }
+
+ this.setState({
+ userId: user.sub,
+ });
+ });
+ }
+
+ render() {
+
+ if(!this.state.userId){
+ return (<FullScreenProgress />);
+ }
+
+ const root = {
+ height: '100%',
+ width: '100%',
+ };
+
+ const childrenWithProps = React.Children.map(this.props.children,
+ (child) => React.cloneElement(child, {
+ variables: Object.assign({}, this.props.variables, {
+ userId: this.state.userId
+ })
+ })
+ );
+
+ return (
+ <div style={root}>
+ {childrenWithProps}
+ </div>
+ );
+ }
+}
+
+AuthUserComponent.propTypes = {
+ variables: React.PropTypes.object,
+}
+
+AuthUserComponent.defaultProps = {
+ variables: {}
+}
+
+export default AuthUserComponent; | |
8dcdaa48cf23a5fec53013b4af63a29fc4d786d2 | app/assets/javascripts/sencha_base/placeholder_fallback.js | app/assets/javascripts/sencha_base/placeholder_fallback.js | // Placeholder fallback for browsers that don't support it.
//
// Requirements:
// Modernizr
//
// Instructions:
// 1. Require sencha_base/placeholder_fallback after Modernizr and before any
// other on submit events are binded, so the placeholder attribute is reset and
// not posted as the field value.
//
// 2. Add 'placeholder' class to elements with placeholders.
//
// Thanks to UniqueMethod.com
Ext.onReady(function() {
// check placeholder browser support
if (!Modernizr.input.placeholder)
{
// set placeholder values
Ext.select("*[placeholder]").each(function() {
field = Ext.get(this);
if(field.getValue() == '') {
field.set({value: field.getAttribute('placeholder')});
}
});
// focus and blur of placeholders
Ext.select("*[placeholder]").on('focus', function() {
field = Ext.get(this);
if(field.getValue() == field.getAttribute('placeholder')) {
field.set({value: ''});
field.removeClass('placeholder');
}
}).on('blur', function() {
field = Ext.get(this);
if(field.getValue() == '' || field.getValue() == field.getAttribute('placeholder')) {
field.set({value: field.getAttribute('placeholder')});
field.addClass('placeholder');
}
});
// remove placeholders on submit
Ext.select("form").on('submit', function() {
Ext.get(this).select('*[placeholder]').each(function()
{
field = Ext.get(this);
if(field.getValue() == field.getAttribute('placeholder')) {
field.set({value: ''});
}
});
return false;
});
}
});
| Add placeholder fallback for older browsers. | Add placeholder fallback for older browsers.
| JavaScript | mit | jvcanote/SenchaBase,hypertiny/SenchaBase,hypertiny/SenchaBase,jvcanote/SenchaBase,hypertiny/SenchaBase,jvcanote/SenchaBase | ---
+++
@@ -0,0 +1,56 @@
+// Placeholder fallback for browsers that don't support it.
+//
+// Requirements:
+// Modernizr
+//
+// Instructions:
+// 1. Require sencha_base/placeholder_fallback after Modernizr and before any
+// other on submit events are binded, so the placeholder attribute is reset and
+// not posted as the field value.
+//
+// 2. Add 'placeholder' class to elements with placeholders.
+//
+// Thanks to UniqueMethod.com
+
+Ext.onReady(function() {
+
+ // check placeholder browser support
+ if (!Modernizr.input.placeholder)
+ {
+
+ // set placeholder values
+ Ext.select("*[placeholder]").each(function() {
+ field = Ext.get(this);
+ if(field.getValue() == '') {
+ field.set({value: field.getAttribute('placeholder')});
+ }
+ });
+
+ // focus and blur of placeholders
+ Ext.select("*[placeholder]").on('focus', function() {
+ field = Ext.get(this);
+ if(field.getValue() == field.getAttribute('placeholder')) {
+ field.set({value: ''});
+ field.removeClass('placeholder');
+ }
+ }).on('blur', function() {
+ field = Ext.get(this);
+ if(field.getValue() == '' || field.getValue() == field.getAttribute('placeholder')) {
+ field.set({value: field.getAttribute('placeholder')});
+ field.addClass('placeholder');
+ }
+ });
+
+ // remove placeholders on submit
+ Ext.select("form").on('submit', function() {
+ Ext.get(this).select('*[placeholder]').each(function()
+ {
+ field = Ext.get(this);
+ if(field.getValue() == field.getAttribute('placeholder')) {
+ field.set({value: ''});
+ }
+ });
+ return false;
+ });
+ }
+}); | |
c86b7b6126ce716d8ff685c1dd105ed660054ac9 | client/components/lists/ManageSubscribersTable.js | client/components/lists/ManageSubscribersTable.js | import React, { PropTypes } from 'react';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
import BSTyle from 'react-bootstrap-table/dist/react-bootstrap-table.min.css';
export default class ManageSubscribersTable extends React.Component {
constructor(props) {
super(props);
this.state = {
data: this.props.data
};
}
static propTypes = {
data: PropTypes.array.isRequired
}
componentWillReceiveProps(newProps) {
this.setState({
data: newProps.data
})
}
formatFieldSubscribed(subscribed) {
// this is a placeholder for now, since we are not yet handling
// user subscription state
return '<span class="label label-success">Subscribed</span>'
}
render() {
return (
<BootstrapTable data={this.props.data}
pagination={true}
hover={true}>
<TableHeaderColumn dataField="id" hidden={true} isKey={true}>id</TableHeaderColumn>
<TableHeaderColumn dataField="email">email</TableHeaderColumn>
<TableHeaderColumn dataField="subscribed" dataFormat={this.formatFieldSubscribed}>status</TableHeaderColumn>
</BootstrapTable>
);
}
}
| import React, { PropTypes } from 'react';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
import BSTyle from 'react-bootstrap-table/dist/react-bootstrap-table.min.css';
export default class ManageSubscribersTable extends React.Component {
constructor(props) {
super(props);
this.state = {
data: this.props.data || []
};
}
static propTypes = {
data: PropTypes.array.isRequired
}
componentWillReceiveProps(newProps) {
this.setState({
data: newProps.data
})
}
formatFieldSubscribed(subscribed) {
// this is a placeholder for now, since we are not yet handling
// user subscription state
return '<span class="label label-success">Subscribed</span>'
}
render() {
return (
<BootstrapTable data={this.state.data}
pagination={true}
hover={true}>
<TableHeaderColumn dataField="id" hidden={true} isKey={true}>id</TableHeaderColumn>
<TableHeaderColumn dataField="email">email</TableHeaderColumn>
<TableHeaderColumn dataField="subscribed" dataFormat={this.formatFieldSubscribed}>status</TableHeaderColumn>
</BootstrapTable>
);
}
}
| Fix initial state of list subscribers table | Fix initial state of list subscribers table
| JavaScript | bsd-3-clause | zhakkarn/Mail-for-Good,zhakkarn/Mail-for-Good,karuppiah7890/Mail-for-Good,zhakkarn/Mail-for-Good,karuppiah7890/Mail-for-Good,karuppiah7890/Mail-for-Good | ---
+++
@@ -7,7 +7,7 @@
super(props);
this.state = {
- data: this.props.data
+ data: this.props.data || []
};
}
@@ -30,7 +30,7 @@
render() {
return (
- <BootstrapTable data={this.props.data}
+ <BootstrapTable data={this.state.data}
pagination={true}
hover={true}>
<TableHeaderColumn dataField="id" hidden={true} isKey={true}>id</TableHeaderColumn> |
86ab0e203fb62f1d3b1e13445966f72567f6cbd8 | bin/cliHelper.js | bin/cliHelper.js | var q = require('q');
var childProcess = require('child_process');
var CLI_PATH = 'node /Users/andresdom/dev/protractor/lib/cli.js ' +
'--elementExplorer true ' +
'--debuggerServerPort 6969';
var startProtractor = function() {
var deferred = q.defer();
console.log('Starting protractor with command: [%s]', CLI_PATH);
var ptor = childProcess.exec(CLI_PATH, function(error, stdout, stderr) {
if (error) {
console.log('Error starting protractor', error);
//console.log(error.stack);
//console.log('Error code:', error.code);
//console.log('Signal received:', error.signal);
return deferred.reject(error);
}
console.log('Child Process STDOUT:', stdout);
console.log('Child Process STDERR:', stderr);
deferred.resolve();
});
ptor.on('exit', function(code) {
console.log('Protractor process exited with exit code', code);
});
return deferred.promise;
};
module.exports = {
startProtractor: startProtractor
};
| Add helper to start protractor | Add helper to start protractor
| JavaScript | mit | andresdominguez/elementor,andresdominguez/elementor | ---
+++
@@ -0,0 +1,35 @@
+var q = require('q');
+var childProcess = require('child_process');
+
+var CLI_PATH = 'node /Users/andresdom/dev/protractor/lib/cli.js ' +
+ '--elementExplorer true ' +
+ '--debuggerServerPort 6969';
+
+var startProtractor = function() {
+ var deferred = q.defer();
+
+ console.log('Starting protractor with command: [%s]', CLI_PATH);
+ var ptor = childProcess.exec(CLI_PATH, function(error, stdout, stderr) {
+ if (error) {
+ console.log('Error starting protractor', error);
+
+ //console.log(error.stack);
+ //console.log('Error code:', error.code);
+ //console.log('Signal received:', error.signal);
+ return deferred.reject(error);
+ }
+ console.log('Child Process STDOUT:', stdout);
+ console.log('Child Process STDERR:', stderr);
+ deferred.resolve();
+ });
+
+ ptor.on('exit', function(code) {
+ console.log('Protractor process exited with exit code', code);
+ });
+
+ return deferred.promise;
+};
+
+module.exports = {
+ startProtractor: startProtractor
+}; | |
5acf747c9025491ab5198dc80a5b0c13c2e568ac | projectSlug.js | projectSlug.js | var rest = require('./rest');
/**
* Fetches a project by project id, then fetches its project slug for use
* when working with tasks.
*
* @param {int} projectid - AC project id
* @param {Function} cb - function to be called once project slug has
* been fetched and calculated
*/
module.exports = function (projectid, cb) {
rest.fetch(process.env.API_URL, '/projects/' + projectid, process.env.API_KEY, function (project) {
console.log(project.name);
var slug = project.name.replace(/ /g, '-');
slug = slug.toLowerCase();
console.log(slug);
cb(slug);
});
}; | Add module 2 work out project slug from project id | Add module 2 work out project slug from project id
| JavaScript | mit | mediasuitenz/node-activecollab | ---
+++
@@ -0,0 +1,19 @@
+var rest = require('./rest');
+
+/**
+ * Fetches a project by project id, then fetches its project slug for use
+ * when working with tasks.
+ *
+ * @param {int} projectid - AC project id
+ * @param {Function} cb - function to be called once project slug has
+ * been fetched and calculated
+ */
+module.exports = function (projectid, cb) {
+ rest.fetch(process.env.API_URL, '/projects/' + projectid, process.env.API_KEY, function (project) {
+ console.log(project.name);
+ var slug = project.name.replace(/ /g, '-');
+ slug = slug.toLowerCase();
+ console.log(slug);
+ cb(slug);
+ });
+}; | |
8f4d41cecdeb357cdc1ebb6ca2bc3a3a1661467b | BakinBaconApi.js | BakinBaconApi.js | 'use strict';
import React, {
AsyncStorage,
AlertIOS
} from 'react-native';
var SERVER_URL = 'https://ziiwfyoc40.execute-api.us-east-2.amazonaws.com/prod
var BACON_URL = SERVER_URL + '/bacon-bit';
export class BakinBaconApi
{
constructor() {
}
postBaconBit(baconBit, onBaconing) {
try {
fetch(BACON_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic ' + session.toString('base64')
},
body: JSON.stringify({
user_id: poll.userId,
duration: poll.duration,
timestamp: poll.timestamp,
bsi: poll.bsi
})
})
.then((response) => response.json())
.then((responseData) => {
if(responseData == '🥓'){
onBaconing();
}
})
.done();
} catch (err) {
AlertIOS.alert(
"PUT Poll ERROR",
"[" + err + "]"
)
}
}
} | Add initial client API with bacon bit post | Add initial client API with bacon bit post
| JavaScript | mit | bakin-bacon/app | ---
+++
@@ -0,0 +1,46 @@
+'use strict';
+import React, {
+ AsyncStorage,
+ AlertIOS
+} from 'react-native';
+
+var SERVER_URL = 'https://ziiwfyoc40.execute-api.us-east-2.amazonaws.com/prod
+var BACON_URL = SERVER_URL + '/bacon-bit';
+
+export class BakinBaconApi
+{
+ constructor() {
+
+ }
+
+ postBaconBit(baconBit, onBaconing) {
+ try {
+ fetch(BACON_URL, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Authorization': 'Basic ' + session.toString('base64')
+ },
+ body: JSON.stringify({
+ user_id: poll.userId,
+ duration: poll.duration,
+ timestamp: poll.timestamp,
+ bsi: poll.bsi
+ })
+ })
+ .then((response) => response.json())
+ .then((responseData) => {
+ if(responseData == '🥓'){
+ onBaconing();
+ }
+ })
+ .done();
+
+ } catch (err) {
+ AlertIOS.alert(
+ "PUT Poll ERROR",
+ "[" + err + "]"
+ )
+ }
+ }
+} | |
111688be26d8647ca3c2a42633007f9e298ff2d7 | website/static/js/fileRevisions.js | website/static/js/fileRevisions.js | 'use strict';
var ko = require('knockout');
require('knockout-punches');
var $ = require('jquery');
var $osf = require('osfHelpers');
var bootbox = require('bootbox');
var waterbutler = require('waterbutler');
ko.punches.enableAll();
var Revision = function(data) {
var self = this;
$.extend(self, data);
self.date = new $osf.FormattableDate(data.modified);
self.displayDate = self.date.local !== 'Invalid date' ?
self.date.local :
data.date;
};
var RevisionsViewModel = function(node, file, editable) {
var self = this;
self.node = node;
self.file = file;
self.editable = editable;
self.urls = {
delete: waterbutler.buildDeleteUrl(file.path, file.provider, node.id),
download: waterbutler.buildDownloadUrl(file.path, file.provider, node.id),
revisions: waterbutler.buildRevisionsUrl(file.path, file.provider, node.id),
};
self.page = 0;
self.more = ko.observable(false);
self.revisions = ko.observableArray([]);
};
RevisionsViewModel.prototype.fetch = function() {
var self = this;
$.getJSON(
self.urls.revisions,
{page: self.page}
).done(function(response) {
// self.more(response.more);
var revisions = ko.utils.arrayMap(response.data, function(item) {
return new Revision(item);
});
self.revisions(self.revisions().concat(revisions));
self.page += 1;
});
};
RevisionsViewModel.prototype.delete = function() {
var self = this;
$.ajax({
type: 'DELETE',
url: self.urls.delete,
}).done(function() {
window.location = self.node.urls.files;
}).fail(function() {
$osf.growl('Error', 'Could not delete file.');
});
};
RevisionsViewModel.prototype.askDelete = function() {
var self = this;
bootbox.confirm({
title: 'Delete file?',
message: '<p class="overflow">' +
'Are you sure you want to delete <strong>' +
self.name + '</strong>?' +
'</p>',
callback: function(confirm) {
if (confirm) {
self.delete();
}
}
});
};
var RevisionTable = function(selector, node, file, editable) {
var self = this;
self.viewModel = new RevisionsViewModel(node, file, editable);
self.viewModel.fetch();
$osf.applyBindings(self.viewModel, selector);
};
module.exports = RevisionTable;
| Add @jmcarp filerevision ko model from osfstorage | Add @jmcarp filerevision ko model from osfstorage
| JavaScript | apache-2.0 | felliott/osf.io,pattisdr/osf.io,lyndsysimon/osf.io,kushG/osf.io,lamdnhan/osf.io,kushG/osf.io,bdyetton/prettychart,DanielSBrown/osf.io,barbour-em/osf.io,caseyrollins/osf.io,GaryKriebel/osf.io,doublebits/osf.io,cslzchen/osf.io,abought/osf.io,cldershem/osf.io,amyshi188/osf.io,dplorimer/osf,RomanZWang/osf.io,zachjanicki/osf.io,revanthkolli/osf.io,acshi/osf.io,CenterForOpenScience/osf.io,sloria/osf.io,CenterForOpenScience/osf.io,barbour-em/osf.io,zkraime/osf.io,ZobairAlijan/osf.io,kushG/osf.io,jeffreyliu3230/osf.io,himanshuo/osf.io,cosenal/osf.io,crcresearch/osf.io,binoculars/osf.io,TomHeatwole/osf.io,KAsante95/osf.io,barbour-em/osf.io,jnayak1/osf.io,doublebits/osf.io,mfraezz/osf.io,fabianvf/osf.io,leb2dg/osf.io,kch8qx/osf.io,baylee-d/osf.io,petermalcolm/osf.io,sbt9uc/osf.io,caseyrollins/osf.io,brianjgeiger/osf.io,alexschiller/osf.io,njantrania/osf.io,billyhunt/osf.io,chrisseto/osf.io,KAsante95/osf.io,acshi/osf.io,chrisseto/osf.io,chennan47/osf.io,abought/osf.io,jeffreyliu3230/osf.io,amyshi188/osf.io,ckc6cz/osf.io,mluo613/osf.io,himanshuo/osf.io,wearpants/osf.io,ckc6cz/osf.io,jolene-esposito/osf.io,arpitar/osf.io,TomBaxter/osf.io,samchrisinger/osf.io,lamdnhan/osf.io,chennan47/osf.io,emetsger/osf.io,kch8qx/osf.io,abought/osf.io,GaryKriebel/osf.io,laurenrevere/osf.io,fabianvf/osf.io,samchrisinger/osf.io,erinspace/osf.io,kch8qx/osf.io,alexschiller/osf.io,asanfilippo7/osf.io,laurenrevere/osf.io,aaxelb/osf.io,revanthkolli/osf.io,petermalcolm/osf.io,amyshi188/osf.io,wearpants/osf.io,Nesiehr/osf.io,mluo613/osf.io,sbt9uc/osf.io,brandonPurvis/osf.io,danielneis/osf.io,doublebits/osf.io,RomanZWang/osf.io,samanehsan/osf.io,cosenal/osf.io,petermalcolm/osf.io,cwisecarver/osf.io,TomHeatwole/osf.io,mluke93/osf.io,rdhyee/osf.io,HalcyonChimera/osf.io,zkraime/osf.io,himanshuo/osf.io,haoyuchen1992/osf.io,zachjanicki/osf.io,zamattiac/osf.io,jolene-esposito/osf.io,chrisseto/osf.io,erinspace/osf.io,monikagrabowska/osf.io,reinaH/osf.io,reinaH/osf.io,cldershem/osf.io,haoyuchen1992/osf.io,revanthkolli/osf.io,rdhyee/osf.io,saradbowman/osf.io,Johnetordoff/osf.io,cslzchen/osf.io,jnayak1/osf.io,HarryRybacki/osf.io,samchrisinger/osf.io,mfraezz/osf.io,cldershem/osf.io,acshi/osf.io,samchrisinger/osf.io,emetsger/osf.io,jnayak1/osf.io,icereval/osf.io,lyndsysimon/osf.io,asanfilippo7/osf.io,Nesiehr/osf.io,baylee-d/osf.io,revanthkolli/osf.io,brandonPurvis/osf.io,mattclark/osf.io,caseyrygt/osf.io,danielneis/osf.io,GaryKriebel/osf.io,sloria/osf.io,alexschiller/osf.io,TomBaxter/osf.io,GageGaskins/osf.io,alexschiller/osf.io,leb2dg/osf.io,acshi/osf.io,HarryRybacki/osf.io,monikagrabowska/osf.io,dplorimer/osf,Ghalko/osf.io,asanfilippo7/osf.io,brianjgeiger/osf.io,bdyetton/prettychart,Johnetordoff/osf.io,caseyrollins/osf.io,TomBaxter/osf.io,samanehsan/osf.io,icereval/osf.io,arpitar/osf.io,zamattiac/osf.io,billyhunt/osf.io,HalcyonChimera/osf.io,ticklemepierce/osf.io,jmcarp/osf.io,fabianvf/osf.io,hmoco/osf.io,himanshuo/osf.io,zachjanicki/osf.io,MerlinZhang/osf.io,HalcyonChimera/osf.io,arpitar/osf.io,jmcarp/osf.io,Nesiehr/osf.io,wearpants/osf.io,caseyrygt/osf.io,GageGaskins/osf.io,SSJohns/osf.io,binoculars/osf.io,bdyetton/prettychart,ckc6cz/osf.io,KAsante95/osf.io,lamdnhan/osf.io,HarryRybacki/osf.io,cwisecarver/osf.io,MerlinZhang/osf.io,kushG/osf.io,KAsante95/osf.io,Johnetordoff/osf.io,Ghalko/osf.io,DanielSBrown/osf.io,barbour-em/osf.io,caneruguz/osf.io,njantrania/osf.io,mattclark/osf.io,rdhyee/osf.io,binoculars/osf.io,HalcyonChimera/osf.io,ticklemepierce/osf.io,monikagrabowska/osf.io,emetsger/osf.io,felliott/osf.io,SSJohns/osf.io,crcresearch/osf.io,felliott/osf.io,SSJohns/osf.io,leb2dg/osf.io,dplorimer/osf,mluo613/osf.io,doublebits/osf.io,ckc6cz/osf.io,hmoco/osf.io,amyshi188/osf.io,aaxelb/osf.io,ticklemepierce/osf.io,jinluyuan/osf.io,ZobairAlijan/osf.io,acshi/osf.io,caneruguz/osf.io,njantrania/osf.io,chrisseto/osf.io,zamattiac/osf.io,lyndsysimon/osf.io,fabianvf/osf.io,chennan47/osf.io,GageGaskins/osf.io,mfraezz/osf.io,SSJohns/osf.io,danielneis/osf.io,brandonPurvis/osf.io,brianjgeiger/osf.io,jeffreyliu3230/osf.io,brianjgeiger/osf.io,adlius/osf.io,jmcarp/osf.io,TomHeatwole/osf.io,crcresearch/osf.io,laurenrevere/osf.io,billyhunt/osf.io,hmoco/osf.io,RomanZWang/osf.io,hmoco/osf.io,GageGaskins/osf.io,adlius/osf.io,cslzchen/osf.io,aaxelb/osf.io,jinluyuan/osf.io,cwisecarver/osf.io,ticklemepierce/osf.io,icereval/osf.io,alexschiller/osf.io,petermalcolm/osf.io,cldershem/osf.io,cwisecarver/osf.io,jinluyuan/osf.io,mluke93/osf.io,zkraime/osf.io,adlius/osf.io,erinspace/osf.io,CenterForOpenScience/osf.io,arpitar/osf.io,haoyuchen1992/osf.io,doublebits/osf.io,ZobairAlijan/osf.io,saradbowman/osf.io,Ghalko/osf.io,billyhunt/osf.io,dplorimer/osf,jeffreyliu3230/osf.io,zachjanicki/osf.io,jinluyuan/osf.io,haoyuchen1992/osf.io,brandonPurvis/osf.io,adlius/osf.io,njantrania/osf.io,samanehsan/osf.io,abought/osf.io,zamattiac/osf.io,baylee-d/osf.io,ZobairAlijan/osf.io,RomanZWang/osf.io,caseyrygt/osf.io,kwierman/osf.io,sloria/osf.io,pattisdr/osf.io,sbt9uc/osf.io,emetsger/osf.io,MerlinZhang/osf.io,asanfilippo7/osf.io,kwierman/osf.io,samanehsan/osf.io,aaxelb/osf.io,sbt9uc/osf.io,mluke93/osf.io,mattclark/osf.io,CenterForOpenScience/osf.io,rdhyee/osf.io,HarryRybacki/osf.io,caseyrygt/osf.io,jnayak1/osf.io,Ghalko/osf.io,monikagrabowska/osf.io,leb2dg/osf.io,kwierman/osf.io,Nesiehr/osf.io,caneruguz/osf.io,RomanZWang/osf.io,lamdnhan/osf.io,brandonPurvis/osf.io,cosenal/osf.io,GaryKriebel/osf.io,monikagrabowska/osf.io,DanielSBrown/osf.io,MerlinZhang/osf.io,jmcarp/osf.io,billyhunt/osf.io,KAsante95/osf.io,mluke93/osf.io,mfraezz/osf.io,mluo613/osf.io,felliott/osf.io,TomHeatwole/osf.io,kwierman/osf.io,Johnetordoff/osf.io,mluo613/osf.io,wearpants/osf.io,danielneis/osf.io,lyndsysimon/osf.io,bdyetton/prettychart,GageGaskins/osf.io,jolene-esposito/osf.io,kch8qx/osf.io,reinaH/osf.io,pattisdr/osf.io,kch8qx/osf.io,DanielSBrown/osf.io,cosenal/osf.io,jolene-esposito/osf.io,reinaH/osf.io,cslzchen/osf.io,caneruguz/osf.io,zkraime/osf.io | ---
+++
@@ -0,0 +1,95 @@
+'use strict';
+
+var ko = require('knockout');
+require('knockout-punches');
+var $ = require('jquery');
+var $osf = require('osfHelpers');
+var bootbox = require('bootbox');
+var waterbutler = require('waterbutler');
+
+ko.punches.enableAll();
+
+var Revision = function(data) {
+
+ var self = this;
+
+ $.extend(self, data);
+ self.date = new $osf.FormattableDate(data.modified);
+ self.displayDate = self.date.local !== 'Invalid date' ?
+ self.date.local :
+ data.date;
+
+};
+
+var RevisionsViewModel = function(node, file, editable) {
+
+ var self = this;
+
+ self.node = node;
+ self.file = file;
+ self.editable = editable;
+ self.urls = {
+ delete: waterbutler.buildDeleteUrl(file.path, file.provider, node.id),
+ download: waterbutler.buildDownloadUrl(file.path, file.provider, node.id),
+ revisions: waterbutler.buildRevisionsUrl(file.path, file.provider, node.id),
+ };
+ self.page = 0;
+ self.more = ko.observable(false);
+ self.revisions = ko.observableArray([]);
+
+};
+
+RevisionsViewModel.prototype.fetch = function() {
+ var self = this;
+ $.getJSON(
+ self.urls.revisions,
+ {page: self.page}
+ ).done(function(response) {
+ // self.more(response.more);
+ var revisions = ko.utils.arrayMap(response.data, function(item) {
+ return new Revision(item);
+ });
+ self.revisions(self.revisions().concat(revisions));
+ self.page += 1;
+ });
+};
+
+RevisionsViewModel.prototype.delete = function() {
+ var self = this;
+ $.ajax({
+ type: 'DELETE',
+ url: self.urls.delete,
+ }).done(function() {
+ window.location = self.node.urls.files;
+ }).fail(function() {
+ $osf.growl('Error', 'Could not delete file.');
+ });
+};
+
+RevisionsViewModel.prototype.askDelete = function() {
+ var self = this;
+ bootbox.confirm({
+ title: 'Delete file?',
+ message: '<p class="overflow">' +
+ 'Are you sure you want to delete <strong>' +
+ self.name + '</strong>?' +
+ '</p>',
+ callback: function(confirm) {
+ if (confirm) {
+ self.delete();
+ }
+ }
+ });
+};
+
+var RevisionTable = function(selector, node, file, editable) {
+
+ var self = this;
+
+ self.viewModel = new RevisionsViewModel(node, file, editable);
+ self.viewModel.fetch();
+ $osf.applyBindings(self.viewModel, selector);
+
+};
+
+module.exports = RevisionTable; | |
eaa48afb8c904527c71a7953d037133b92e90015 | i18n/jquery.spectrum-fr.js | i18n/jquery.spectrum-fr.js | // Spectrum Colorpicker
// French (fr) localization
// https://github.com/bgrins/spectrum
(function ( $ ) {
var localization = $.spectrum.localization["fr"] = {
cancelText: "Annuler",
chooseText: "Valider",
clearText: "Effacer couleur sélectionnée",
noColorSelectedText: "Aucune couleur sélectionnée",
togglePaletteMoreText: "plus",
togglePaletteLessText: "moins"
};
$.extend($.fn.spectrum.defaults, localization);
})( jQuery );
| // Spectrum Colorpicker
// French (fr) localization
// https://github.com/bgrins/spectrum
(function ( $ ) {
var localization = $.spectrum.localization["fr"] = {
cancelText: "Annuler",
chooseText: "Valider",
clearText: "Effacer couleur sélectionnée",
noColorSelectedText: "Aucune couleur sélectionnée",
togglePaletteMoreText: "Plus",
togglePaletteLessText: "Moins"
};
$.extend($.fn.spectrum.defaults, localization);
})( jQuery );
| Fix capitalization in French language file. | Fix capitalization in French language file.
| JavaScript | mit | bgrins/spectrum,ajssd/spectrum,bgrins/spectrum,ginlime/spectrum,GerHobbelt/spectrum,safareli/spectrum,armanforghani/spectrum,kotmatpockuh/spectrum,shawinder/spectrum,GerHobbelt/spectrum,maurojs25/spectrum,kotmatpockuh/spectrum,liitii/spectrum,safareli/spectrum,maurojs25/spectrum,c9s/spectrum,armanforghani/spectrum,ginlime/spectrum,ajssd/spectrum,liitii/spectrum,shawinder/spectrum | ---
+++
@@ -9,8 +9,8 @@
chooseText: "Valider",
clearText: "Effacer couleur sélectionnée",
noColorSelectedText: "Aucune couleur sélectionnée",
- togglePaletteMoreText: "plus",
- togglePaletteLessText: "moins"
+ togglePaletteMoreText: "Plus",
+ togglePaletteLessText: "Moins"
};
$.extend($.fn.spectrum.defaults, localization); |
1c8dd493e796d7b576e4b1b09e8415306a6ab1b6 | src/lib/convertInventorySlotId.js | src/lib/convertInventorySlotId.js | module.exports = { fromNBT, toNBT };
const replace = {
"100": 8, "101": 7, "102": 6, "103": 5, "-106": 45
}
function fromNBT(slotId) {
let slot;
if (slotId >= 0 && slotId < 9) {
slot = 36 + slotId
}
return replace[String(slotId)] || slot;
}
function toNBT(slotId) {
let slot;
const invertReplace = Object.assign({}, ...Object.entries(replace).map(([a, b]) => ({ [b]: a })));
if (slotId >= 36 && slotId < 44) {
slot = slotId - 36
}
return invertReplace[String(slotId)] || slot;
} | Add library for converting slot IDs from/to NBT format | Add library for converting slot IDs from/to NBT format
| JavaScript | mit | mhsjlw/flying-squid,demipixel/flying-squid,PrismarineJS/flying-squid | ---
+++
@@ -0,0 +1,22 @@
+module.exports = { fromNBT, toNBT };
+
+const replace = {
+ "100": 8, "101": 7, "102": 6, "103": 5, "-106": 45
+}
+
+function fromNBT(slotId) {
+ let slot;
+ if (slotId >= 0 && slotId < 9) {
+ slot = 36 + slotId
+ }
+ return replace[String(slotId)] || slot;
+}
+
+function toNBT(slotId) {
+ let slot;
+ const invertReplace = Object.assign({}, ...Object.entries(replace).map(([a, b]) => ({ [b]: a })));
+ if (slotId >= 36 && slotId < 44) {
+ slot = slotId - 36
+ }
+ return invertReplace[String(slotId)] || slot;
+} | |
80ad17a9ce1223e19fd0be5cbfa5bd901a40ecb8 | 3/moment-setfulltime_utc.js | 3/moment-setfulltime_utc.js | var moment = require('moment');
console.log(moment("2014-12-11 21+0800").format());
console.log(moment("2014-W50-4 21+08:00").format());
console.log(moment("2014-12-11 21Z").format());
| Add the example to use moment to set a full time with utc. | Add the example to use moment to set a full time with utc.
| JavaScript | mit | nicebook/Node.js-Reference,nicebook/Node.js-Reference,nicebook/Node.js-Reference | ---
+++
@@ -0,0 +1,5 @@
+var moment = require('moment');
+
+console.log(moment("2014-12-11 21+0800").format());
+console.log(moment("2014-W50-4 21+08:00").format());
+console.log(moment("2014-12-11 21Z").format()); | |
e1fa882726ce18c9a9fb4092d8663d33b75ad96a | app/marked/Dedicated/script.js | app/marked/Dedicated/script.js | const input = document.getElementById("input-message");
const output = document.getElementById("output-message");
let worker;
function onMessageReceived(event) {
// progressively display worker's messages
console.log("OUTSIDE::received MessageEvent", event, "\ndata:", event.data);
output.value += (output.value ? "\n> " : "> ") + event.data;
// autoscroll to bottom
output.scrollTop = output.scrollHeight;
}
function onErrorReceived(event) {
console.log("OUTSIDE::caught ErrorEvent", event);
// progressively display worker's messages
output.value += (output.value ? "\n! " : "! ") + event.message;
// autoscroll to bottom
output.scrollTop = output.scrollHeight;
// the error can be prevented from displaying in the console with
event.preventDefault();
}
function sendInput() {
let command;
// create worker if needed
if(!worker) {
console.log("OUTSIDE::creating worker");
worker = new Worker('/js/worker.js');
worker.onmessage = onMessageReceived;
worker.onerror = onErrorReceived;
// indicate that it is the initial message
command = "FIRST";
} else {
command = "PROCESS";
}
console.log(`OUTSIDE::posting message with {command: ${command}}`);
// post the message
worker.postMessage({command, message: input.value});
}
function causeError() {
if(!worker) {
console.warn("FIRST CREATE A WORKER");
return;
}
console.log("OUTSIDE::posting message with {command: ERROR}");
worker.postMessage({command: "ERROR"});
}
function closeWorker() {
if(!worker) {
console.warn("FIRST CREATE A WORKER");
return;
}
console.log("OUTSIDE::posting message with {command: CLOSE}");
worker.postMessage({command: "CLOSE"});
// allow it to be garbage collected
worker = null;
}
function terminateWorker() {
if(!worker) {
console.warn("FIRST CREATE A WORKER");
return;
}
console.log("OUTSIDE::terminating worker");
worker.terminate();
// allow it to be garbage collected
worker = null;
}
function clearOutput() {
output.value = "";
}
| Add code to run on the main thread for Dedicated Worker example | feat(worker-example): Add code to run on the main thread for Dedicated Worker example
| JavaScript | mit | Velenir/workers-journey,Velenir/workers-journey | ---
+++
@@ -0,0 +1,79 @@
+const input = document.getElementById("input-message");
+const output = document.getElementById("output-message");
+
+let worker;
+
+function onMessageReceived(event) {
+ // progressively display worker's messages
+ console.log("OUTSIDE::received MessageEvent", event, "\ndata:", event.data);
+
+ output.value += (output.value ? "\n> " : "> ") + event.data;
+
+ // autoscroll to bottom
+ output.scrollTop = output.scrollHeight;
+}
+
+function onErrorReceived(event) {
+ console.log("OUTSIDE::caught ErrorEvent", event);
+ // progressively display worker's messages
+ output.value += (output.value ? "\n! " : "! ") + event.message;
+
+ // autoscroll to bottom
+ output.scrollTop = output.scrollHeight;
+
+ // the error can be prevented from displaying in the console with
+ event.preventDefault();
+}
+
+function sendInput() {
+ let command;
+ // create worker if needed
+ if(!worker) {
+ console.log("OUTSIDE::creating worker");
+ worker = new Worker('/js/worker.js');
+ worker.onmessage = onMessageReceived;
+ worker.onerror = onErrorReceived;
+ // indicate that it is the initial message
+ command = "FIRST";
+ } else {
+ command = "PROCESS";
+ }
+ console.log(`OUTSIDE::posting message with {command: ${command}}`);
+ // post the message
+ worker.postMessage({command, message: input.value});
+}
+
+function causeError() {
+ if(!worker) {
+ console.warn("FIRST CREATE A WORKER");
+ return;
+ }
+ console.log("OUTSIDE::posting message with {command: ERROR}");
+ worker.postMessage({command: "ERROR"});
+}
+
+function closeWorker() {
+ if(!worker) {
+ console.warn("FIRST CREATE A WORKER");
+ return;
+ }
+ console.log("OUTSIDE::posting message with {command: CLOSE}");
+ worker.postMessage({command: "CLOSE"});
+ // allow it to be garbage collected
+ worker = null;
+}
+
+function terminateWorker() {
+ if(!worker) {
+ console.warn("FIRST CREATE A WORKER");
+ return;
+ }
+ console.log("OUTSIDE::terminating worker");
+ worker.terminate();
+ // allow it to be garbage collected
+ worker = null;
+}
+
+function clearOutput() {
+ output.value = "";
+} | |
a9227099dc30d67315ba7a6075c0243fc9b87504 | blueprints/app/files/config/environment.js | blueprints/app/files/config/environment.js | /* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: '<%= modulePrefix %>',
environment: environment,
baseURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
| /* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: '<%= modulePrefix %>',
environment: environment,
baseURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
| Disable default lookup & active generation logging | Disable default lookup & active generation logging | JavaScript | mit | airportyh/ember-cli,aceofspades/ember-cli,tsing80/ember-cli,HeroicEric/ember-cli,dosco/ember-cli,slindberg/ember-cli,beatle/ember-cli,kanongil/ember-cli,scalus/ember-cli,pzuraq/ember-cli,trabus/ember-cli,samselikoff/ember-cli,alefteris/ember-cli,acorncom/ember-cli,searls/ember-cli,eoinkelly/ember-cli,michael-k/ember-cli,seanpdoyle/ember-cli,williamsbdev/ember-cli,noslouch/ember-cli,xtian/ember-cli,eccegordo/ember-cli,jcope2013/ember-cli,fpauser/ember-cli,nruth/ember-cli,ember-cli/ember-cli,Restuta/ember-cli,pangratz/ember-cli,xiujunma/ember-cli,ianstarz/ember-cli,joaohornburg/ember-cli,joaohornburg/ember-cli,lazybensch/ember-cli,airportyh/ember-cli,ef4/ember-cli,igorT/ember-cli,tsing80/ember-cli,jasonmit/ember-cli,asakusuma/ember-cli,dukex/ember-cli,martndemus/ember-cli,code0100fun/ember-cli,quaertym/ember-cli,oss-practice/ember-cli,ianstarz/ember-cli,xcambar/ember-cli,alexdiliberto/ember-cli,rot26/ember-cli,jonathanKingston/ember-cli,josemarluedke/ember-cli,johnotander/ember-cli,csantero/ember-cli,olegdovger/ember-cli,mixonic/ember-cli,tobymarsden/ember-cli,szines/ember-cli,scalus/ember-cli,williamsbdev/ember-cli,ballPointPenguin/ember-cli,DanielOchoa/ember-cli,typeoneerror/ember-cli,EricSchank/ember-cli,romulomachado/ember-cli,DanielOchoa/ember-cli,jayphelps/ember-cli,givanse/ember-cli,rodyhaddad/ember-cli,greyhwndz/ember-cli,seawatts/ember-cli,makepanic/ember-cli,ef4/ember-cli,ro0gr/ember-cli,akatov/ember-cli,joliss/ember-cli,BrianSipple/ember-cli,nathanhammond/ember-cli,quaertym/ember-cli,pixelhandler/ember-cli,dosco/ember-cli,dukex/ember-cli,jasonmit/ember-cli,rodyhaddad/ember-cli,eoinkelly/ember-cli,joliss/ember-cli,trentmwillis/ember-cli,pangratz/ember-cli,gmurphey/ember-cli,eccegordo/ember-cli,code0100fun/ember-cli,DanielOchoa/ember-cli,rot26/ember-cli,pzuraq/ember-cli,mohlek/ember-cli,sivakumar-kailasam/ember-cli,ballPointPenguin/ember-cli,makepanic/ember-cli,cibernox/ember-cli,joostdevries/ember-cli,gmurphey/ember-cli,mixonic/ember-cli,xcambar/ember-cli,marcioj/ember-cli,ro0gr/ember-cli,blimmer/ember-cli,mschinis/ember-cli,eliotsykes/ember-cli,mixonic/ember-cli,jrjohnson/ember-cli,trabus/ember-cli,calderas/ember-cli,ServiceTo/ember-cli,fpauser/ember-cli,tsing80/ember-cli,makepanic/ember-cli,rodyhaddad/ember-cli,joaohornburg/ember-cli,josemarluedke/ember-cli,rtablada/ember-cli,olegdovger/ember-cli,ef4/ember-cli,seawatts/ember-cli,gfvcastro/ember-cli,mschinis/ember-cli,jgwhite/ember-cli,olegdovger/ember-cli,givanse/ember-cli,nathanhammond/ember-cli,princeofdarkness76/ember-cli,beatle/ember-cli,princeofdarkness76/ember-cli,sivakumar-kailasam/ember-cli,cibernox/ember-cli,sivakumar-kailasam/ember-cli,blimmer/ember-cli,ember-cli/ember-cli,joostdevries/ember-cli,oss-practice/ember-cli,alefteris/ember-cli,lazybensch/ember-cli,xiujunma/ember-cli,kellyselden/ember-cli,ServiceTo/ember-cli,EricSchank/ember-cli,seawatts/ember-cli,fpauser/ember-cli,eoinkelly/ember-cli,mschinis/ember-cli,yaymukund/ember-cli,rot26/ember-cli,typeoneerror/ember-cli,jayphelps/ember-cli,samselikoff/ember-cli,rtablada/ember-cli,patocallaghan/ember-cli,Turbo87/ember-cli,cibernox/ember-cli,akatov/ember-cli,Turbo87/ember-cli,maxcal/ember-cli,givanse/ember-cli,rondale-sc/ember-cli,trentmwillis/ember-cli,romulomachado/ember-cli,airportyh/ember-cli,mohlek/ember-cli,kamalaknn/ember-cli,ef4/ember-cli,runspired/ember-cli,joliss/ember-cli,romulomachado/ember-cli,mike-north/ember-cli,kamalaknn/ember-cli,calderas/ember-cli,EricSchank/ember-cli,nruth/ember-cli,quaertym/ember-cli,johnotander/ember-cli,acorncom/ember-cli,EricSchank/ember-cli,comlaterra/ember-cli,abuiles/ember-cli,BrianSipple/ember-cli,csantero/ember-cli,Restuta/ember-cli,yaymukund/ember-cli,searls/ember-cli,jcope2013/ember-cli,tobymarsden/ember-cli,jonathanKingston/ember-cli,ballPointPenguin/ember-cli,Restuta/ember-cli,mohlek/ember-cli,BrianSipple/ember-cli,samselikoff/ember-cli,gfvcastro/ember-cli,code0100fun/ember-cli,michael-k/ember-cli,calderas/ember-cli,fpauser/ember-cli,maxcal/ember-cli,blimmer/ember-cli,bevacqua/ember-cli,Restuta/ember-cli,kategengler/ember-cli,tsing80/ember-cli,gmurphey/ember-cli,trabus/ember-cli,calderas/ember-cli,zanemayo/ember-cli,quaertym/ember-cli,elwayman02/ember-cli,eliotsykes/ember-cli,mike-north/ember-cli,bevacqua/ember-cli,greyhwndz/ember-cli,jayphelps/ember-cli,cibernox/ember-cli,lancedikson/ember-cli,marcioj/ember-cli,raycohen/ember-cli,noslouch/ember-cli,jgwhite/ember-cli,selvagsz/ember-cli,taras/ember-cli,jgwhite/ember-cli,asakusuma/ember-cli,szines/ember-cli,jasonmit/ember-cli,jcope2013/ember-cli,lancedikson/ember-cli,scalus/ember-cli,maxcal/ember-cli,eccegordo/ember-cli,seanpdoyle/ember-cli,nruth/ember-cli,igorT/ember-cli,greyhwndz/ember-cli,kellyselden/ember-cli,akatov/ember-cli,trentmwillis/ember-cli,akatov/ember-cli,bmac/ember-cli,patocallaghan/ember-cli,joliss/ember-cli,felixrieseberg/ember-cli,gmurphey/ember-cli,princeofdarkness76/ember-cli,josemarluedke/ember-cli,jcope2013/ember-cli,bmac/ember-cli,buschtoens/ember-cli,searls/ember-cli,twokul/ember-cli,HeroicEric/ember-cli,beatle/ember-cli,ember-cli/ember-cli,HeroicEric/ember-cli,seanpdoyle/ember-cli,eliotsykes/ember-cli,romulomachado/ember-cli,mattmarcum/ember-cli,elwayman02/ember-cli,jgwhite/ember-cli,acorncom/ember-cli,josemarluedke/ember-cli,martypenner/ember-cli,pangratz/ember-cli,code0100fun/ember-cli,ro0gr/ember-cli,kanongil/ember-cli,johanneswuerbach/ember-cli,ballPointPenguin/ember-cli,dosco/ember-cli,joaohornburg/ember-cli,runspired/ember-cli,blimmer/ember-cli,martypenner/ember-cli,pixelhandler/ember-cli,sivakumar-kailasam/ember-cli,alexdiliberto/ember-cli,joostdevries/ember-cli,csantero/ember-cli,zanemayo/ember-cli,chadhietala/ember-cli,martndemus/ember-cli,selvagsz/ember-cli,joostdevries/ember-cli,raytiley/ember-cli,dosco/ember-cli,ianstarz/ember-cli,seanpdoyle/ember-cli,maxcal/ember-cli,lazybensch/ember-cli,jrjohnson/ember-cli,HeroicEric/ember-cli,michael-k/ember-cli,airportyh/ember-cli,balinterdi/ember-cli,johanneswuerbach/ember-cli,samselikoff/ember-cli,abuiles/ember-cli,DanielOchoa/ember-cli,johnotander/ember-cli,raytiley/ember-cli,thoov/ember-cli,marcioj/ember-cli,xtian/ember-cli,martypenner/ember-cli,szines/ember-cli,searls/ember-cli,szines/ember-cli,kriswill/ember-cli,kanongil/ember-cli,xcambar/ember-cli,noslouch/ember-cli,mschinis/ember-cli,raytiley/ember-cli,dukex/ember-cli,taras/ember-cli,martndemus/ember-cli,bevacqua/ember-cli,mike-north/ember-cli,michael-k/ember-cli,jonathanKingston/ember-cli,martndemus/ember-cli,BrianSipple/ember-cli,johnotander/ember-cli,comlaterra/ember-cli,pixelhandler/ember-cli,ro0gr/ember-cli,mike-north/ember-cli,thoov/ember-cli,kellyselden/ember-cli,Turbo87/ember-cli,ServiceTo/ember-cli,typeoneerror/ember-cli,xiujunma/ember-cli,felixrieseberg/ember-cli,jonathanKingston/ember-cli,comlaterra/ember-cli,runspired/ember-cli,yaymukund/ember-cli,raycohen/ember-cli,felixrieseberg/ember-cli,greyhwndz/ember-cli,mattmarcum/ember-cli,xcambar/ember-cli,slindberg/ember-cli,williamsbdev/ember-cli,selvagsz/ember-cli,lazybensch/ember-cli,alefteris/ember-cli,pzuraq/ember-cli,jasonmit/ember-cli,aceofspades/ember-cli,zanemayo/ember-cli,gfvcastro/ember-cli,twokul/ember-cli,trentmwillis/ember-cli,chadhietala/ember-cli,bevacqua/ember-cli,kamalaknn/ember-cli,thoov/ember-cli,yaymukund/ember-cli,kellyselden/ember-cli,ServiceTo/ember-cli,kriswill/ember-cli,johanneswuerbach/ember-cli,abuiles/ember-cli,trabus/ember-cli,nruth/ember-cli,eliotsykes/ember-cli,princeofdarkness76/ember-cli,martypenner/ember-cli,pangratz/ember-cli,rtablada/ember-cli,selvagsz/ember-cli,taras/ember-cli,xtian/ember-cli,twokul/ember-cli,alexdiliberto/ember-cli,acorncom/ember-cli,Turbo87/ember-cli,taras/ember-cli,coderly/ember-cli,pzuraq/ember-cli,csantero/ember-cli,beatle/ember-cli,rondale-sc/ember-cli,xiujunma/ember-cli,mixonic/ember-cli,zanemayo/ember-cli,nathanhammond/ember-cli,seawatts/ember-cli,makepanic/ember-cli,lancedikson/ember-cli,alefteris/ember-cli,runspired/ember-cli,pixelhandler/ember-cli,comlaterra/ember-cli,patocallaghan/ember-cli,raytiley/ember-cli,kriswill/ember-cli,williamsbdev/ember-cli,abuiles/ember-cli,eoinkelly/ember-cli,ianstarz/ember-cli,alexdiliberto/ember-cli,mohlek/ember-cli,lancedikson/ember-cli,dukex/ember-cli,kanongil/ember-cli,nathanhammond/ember-cli,kriswill/ember-cli,balinterdi/ember-cli,coderly/ember-cli,olegdovger/ember-cli,kategengler/ember-cli,gfvcastro/ember-cli,rot26/ember-cli,rodyhaddad/ember-cli,tobymarsden/ember-cli,kamalaknn/ember-cli,buschtoens/ember-cli,patocallaghan/ember-cli,jayphelps/ember-cli,rtablada/ember-cli,marcioj/ember-cli,johanneswuerbach/ember-cli,thoov/ember-cli,coderly/ember-cli,coderly/ember-cli,twokul/ember-cli,typeoneerror/ember-cli,xtian/ember-cli,tobymarsden/ember-cli,givanse/ember-cli,eccegordo/ember-cli,noslouch/ember-cli,scalus/ember-cli | ---
+++
@@ -21,10 +21,10 @@
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
- ENV.APP.LOG_ACTIVE_GENERATION = true;
+ // ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
- ENV.APP.LOG_VIEW_LOOKUPS = true;
+ // ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') { |
91564336b9e0dc02bf0025b90e15c34801b20fbe | frontend/src/components/ViewTrips/change-collaborator-type-button.js | frontend/src/components/ViewTrips/change-collaborator-type-button.js | import React from 'react';
import app from '../Firebase';
import Button from 'react-bootstrap/Button';
import authUtils from '../AuthUtils';
import * as DB from '../../constants/database.js';
const db = app.firestore();
/**
* {@link TripData} defined originally in `ViewTrips/trip.js`.
*/
/**
* Component that opens the edit trip modal upon click.
*
* @property {Object} props These are the props for this component:
* @property {string} props.tripId The document id associated with the trip.
* @property {TripData} props.tripData The current trip document data.
* @property {string} props.curCollabType The current collaborator type of the
* user for the trip specified by `props.tripId`.
* @property {string} props.newCollabType The collaborator type that the user
* is changed to (for the trip) once the button is pressed.
* @property {string} props.text The inner text of the button.
*/
const ChangeCollabTypeButton = (props) => {
/**
*
*/
function getNewCollabUidArrObj() {
const curUserUid = authUtils.getCurUserUid();
let curCollabUidSet = new Set(props.tripData[props.curCollabType]);
curCollabUidSet.delete(curUserUid);
let curCollabUidArr = Array.from(curCollabUidSet);
let newCollabUidArr = props.tripData[props.newCollabType].push(curUserUid);
return { [props.curCollabType]: curCollabUidArr,
[props.newCollabType]: newCollabUidArr
};
}
/**
*
*/
function changeUserCollabType() {
const collabData = getNewCollabUidArrObj();
db.collection(DB.COLLECTION_TRIPS)
.doc(props.tripId)
.set(collabData, { merge: true })
.then(() => {
console.log('Collaborators updated for trip with ID: ', props.tripId);
})
.catch(error => {
console.error('Error updated collaborators for trip: ', error);
});
}
return (
<Button
type='button'
variant='primary'
onClick={changeUserCollabType}
>
{props.text}
</Button>
);
}
export default ChangeCollabTypeButton;
| Add button that moves the collaborator from one collaborator type (uid arr) to the other. | Add button that moves the collaborator from one collaborator type (uid arr) to the other.
| JavaScript | apache-2.0 | googleinterns/SLURP,googleinterns/SLURP,googleinterns/SLURP | ---
+++
@@ -0,0 +1,73 @@
+import React from 'react';
+
+import app from '../Firebase';
+import Button from 'react-bootstrap/Button';
+
+import authUtils from '../AuthUtils';
+import * as DB from '../../constants/database.js';
+
+const db = app.firestore();
+
+/**
+ * {@link TripData} defined originally in `ViewTrips/trip.js`.
+ */
+
+/**
+ * Component that opens the edit trip modal upon click.
+ *
+ * @property {Object} props These are the props for this component:
+ * @property {string} props.tripId The document id associated with the trip.
+ * @property {TripData} props.tripData The current trip document data.
+ * @property {string} props.curCollabType The current collaborator type of the
+ * user for the trip specified by `props.tripId`.
+ * @property {string} props.newCollabType The collaborator type that the user
+ * is changed to (for the trip) once the button is pressed.
+ * @property {string} props.text The inner text of the button.
+ */
+const ChangeCollabTypeButton = (props) => {
+ /**
+ *
+ */
+ function getNewCollabUidArrObj() {
+ const curUserUid = authUtils.getCurUserUid();
+ let curCollabUidSet = new Set(props.tripData[props.curCollabType]);
+ curCollabUidSet.delete(curUserUid);
+ let curCollabUidArr = Array.from(curCollabUidSet);
+
+ let newCollabUidArr = props.tripData[props.newCollabType].push(curUserUid);
+
+ return { [props.curCollabType]: curCollabUidArr,
+ [props.newCollabType]: newCollabUidArr
+ };
+ }
+
+ /**
+ *
+ */
+ function changeUserCollabType() {
+ const collabData = getNewCollabUidArrObj();
+
+ db.collection(DB.COLLECTION_TRIPS)
+ .doc(props.tripId)
+ .set(collabData, { merge: true })
+ .then(() => {
+ console.log('Collaborators updated for trip with ID: ', props.tripId);
+ })
+ .catch(error => {
+ console.error('Error updated collaborators for trip: ', error);
+ });
+ }
+
+ return (
+ <Button
+ type='button'
+ variant='primary'
+ onClick={changeUserCollabType}
+ >
+ {props.text}
+ </Button>
+ );
+}
+
+export default ChangeCollabTypeButton;
+ | |
99dd1d8abc174cb8682958ad1bd9138989c8a6c4 | examples/getting-started.js | examples/getting-started.js |
/* Outside of this project, change to:
*
* const SBOLDocument = require('sboljs')
*/
const SBOLDocument = require('../lib/SBOLDocument')
/* prefix string for example purposes
*/
const prefix = 'http://sbolstandard.org/example/'
/* create a new empty SBOL doc
*/
const doc = new SBOLDocument()
/* create component definitions for our promoter, rbs, coding site, and terminator
*/
const promoterDef = doc.componentDefinition(prefix + 'promoter')
const rbsDef = doc.componentDefinition(prefix + 'rbs')
const cdsDef = doc.componentDefinition(prefix + 'cds')
const terminatorDef = doc.componentDefinition(prefix + 'terminator')
/* add relevant role URIs to the component definitions
*/
promoterDef.addRole(SBOLDocument.terms.promoter)
rbsDef.addRole(SBOLDocument.terms.ribosomeBindingSite)
cdsDef.addRole(SBOLDocument.terms.cds)
terminatorDef.addRole(SBOLDocument.terms.terminator)
/* create an example component definition that will contain all of the components
* we just created.
*/
const componentDefinition = doc.componentDefinition(prefix + 'exampleComponentDefinition')
/* we have component definitions for the various components. now we need to
* create components to instantiate them.
*/
const promoter = doc.component(componentDefinition.uri + '/promoter')
const rbs = doc.component(componentDefinition.uri + '/rbs')
const cds = doc.component(componentDefinition.uri + '/cds')
const terminator = doc.component(componentDefinition.uri + '/terminator')
/* hook up our new component instances with their definitions
*/
promoter.definition = promoterDef
rbs.definition = rbsDef
cds.definition = cdsDef
terminator.definition = terminatorDef
/* add them to the example component definition
*/
componentDefinition.addComponent(promoter)
componentDefinition.addComponent(rbs)
componentDefinition.addComponent(cds)
componentDefinition.addComponent(terminator)
/* serialize the newly created document as RDF/XML and print it to the console
*/
console.log(doc.serializeXML())
| Add getting started example to the repo | Add getting started example to the repo
| JavaScript | bsd-2-clause | ICO2S/sboljs,ICO2S/sboljs | ---
+++
@@ -0,0 +1,62 @@
+
+
+/* Outside of this project, change to:
+ *
+ * const SBOLDocument = require('sboljs')
+ */
+const SBOLDocument = require('../lib/SBOLDocument')
+
+/* prefix string for example purposes
+ */
+const prefix = 'http://sbolstandard.org/example/'
+
+/* create a new empty SBOL doc
+ */
+const doc = new SBOLDocument()
+
+/* create component definitions for our promoter, rbs, coding site, and terminator
+ */
+const promoterDef = doc.componentDefinition(prefix + 'promoter')
+const rbsDef = doc.componentDefinition(prefix + 'rbs')
+const cdsDef = doc.componentDefinition(prefix + 'cds')
+const terminatorDef = doc.componentDefinition(prefix + 'terminator')
+
+/* add relevant role URIs to the component definitions
+ */
+promoterDef.addRole(SBOLDocument.terms.promoter)
+rbsDef.addRole(SBOLDocument.terms.ribosomeBindingSite)
+cdsDef.addRole(SBOLDocument.terms.cds)
+terminatorDef.addRole(SBOLDocument.terms.terminator)
+
+/* create an example component definition that will contain all of the components
+ * we just created.
+ */
+const componentDefinition = doc.componentDefinition(prefix + 'exampleComponentDefinition')
+
+/* we have component definitions for the various components. now we need to
+ * create components to instantiate them.
+ */
+const promoter = doc.component(componentDefinition.uri + '/promoter')
+const rbs = doc.component(componentDefinition.uri + '/rbs')
+const cds = doc.component(componentDefinition.uri + '/cds')
+const terminator = doc.component(componentDefinition.uri + '/terminator')
+
+/* hook up our new component instances with their definitions
+ */
+promoter.definition = promoterDef
+rbs.definition = rbsDef
+cds.definition = cdsDef
+terminator.definition = terminatorDef
+
+/* add them to the example component definition
+ */
+componentDefinition.addComponent(promoter)
+componentDefinition.addComponent(rbs)
+componentDefinition.addComponent(cds)
+componentDefinition.addComponent(terminator)
+
+/* serialize the newly created document as RDF/XML and print it to the console
+ */
+console.log(doc.serializeXML())
+
+ | |
76ae0e7258d2a952f2a187c2abd574dadd87ef21 | spec/store/markers-spec.js | spec/store/markers-spec.js | "use babel";
import { Range } from "atom";
import MarkerStore from "../../lib/store/markers";
describe("MarkerStore", () => {
let store;
beforeEach(() => {
store = new MarkerStore();
});
it("correctly initializes MarkerStore", () => {
expect(store.markers).toEqual(new Map());
});
it("clears markers", () => {
const bubble1 = jasmine.createSpyObj("bubble1", ["destroy"]);
const bubble2 = jasmine.createSpyObj("bubble2", ["destroy"]);
store.markers.set(1, bubble1);
store.markers.set(2, bubble2);
expect(store.markers.size).toEqual(2);
store.clear();
expect(bubble1.destroy).toHaveBeenCalled();
expect(bubble2.destroy).toHaveBeenCalled();
expect(store.markers.size).toEqual(0);
});
it("stores a new marker", () => {
const bubble = { marker: { id: 42 } };
store.new(bubble);
expect(store.markers.size).toEqual(1);
expect(store.markers.get(42)).toEqual(bubble);
});
it("deletes a marker", () => {
const bubble1 = jasmine.createSpyObj("bubble1", ["destroy"]);
const bubble2 = jasmine.createSpyObj("bubble2", ["destroy"]);
store.markers.set(1, bubble1);
store.markers.set(2, bubble2);
expect(store.markers.size).toEqual(2);
store.delete(2);
expect(bubble1.destroy).not.toHaveBeenCalled();
expect(bubble2.destroy).toHaveBeenCalled();
expect(store.markers.size).toEqual(1);
expect(store.markers.get(1)).toEqual(bubble1);
});
it("clears bubble on row", () => {
const bubble = {
marker: { getBufferRange: () => new Range([5, 1], [5, 3]) }
};
spyOn(store, "delete");
store.markers.set(1, bubble);
expect(store.markers.size).toEqual(1);
expect(store.clearOnRow(20)).toEqual(false);
expect(store.delete).not.toHaveBeenCalled();
expect(store.clearOnRow(5)).toEqual(true);
expect(store.delete).toHaveBeenCalledWith(1);
});
});
| Add tests for marker store | Add tests for marker store
| JavaScript | mit | nteract/hydrogen,nteract/hydrogen,xanecs/hydrogen,rgbkrk/hydrogen | ---
+++
@@ -0,0 +1,73 @@
+"use babel";
+
+import { Range } from "atom";
+
+import MarkerStore from "../../lib/store/markers";
+
+describe("MarkerStore", () => {
+ let store;
+ beforeEach(() => {
+ store = new MarkerStore();
+ });
+
+ it("correctly initializes MarkerStore", () => {
+ expect(store.markers).toEqual(new Map());
+ });
+
+ it("clears markers", () => {
+ const bubble1 = jasmine.createSpyObj("bubble1", ["destroy"]);
+ const bubble2 = jasmine.createSpyObj("bubble2", ["destroy"]);
+
+ store.markers.set(1, bubble1);
+ store.markers.set(2, bubble2);
+ expect(store.markers.size).toEqual(2);
+
+ store.clear();
+
+ expect(bubble1.destroy).toHaveBeenCalled();
+ expect(bubble2.destroy).toHaveBeenCalled();
+ expect(store.markers.size).toEqual(0);
+ });
+
+ it("stores a new marker", () => {
+ const bubble = { marker: { id: 42 } };
+
+ store.new(bubble);
+
+ expect(store.markers.size).toEqual(1);
+ expect(store.markers.get(42)).toEqual(bubble);
+ });
+
+ it("deletes a marker", () => {
+ const bubble1 = jasmine.createSpyObj("bubble1", ["destroy"]);
+ const bubble2 = jasmine.createSpyObj("bubble2", ["destroy"]);
+
+ store.markers.set(1, bubble1);
+ store.markers.set(2, bubble2);
+ expect(store.markers.size).toEqual(2);
+
+ store.delete(2);
+
+ expect(bubble1.destroy).not.toHaveBeenCalled();
+ expect(bubble2.destroy).toHaveBeenCalled();
+ expect(store.markers.size).toEqual(1);
+ expect(store.markers.get(1)).toEqual(bubble1);
+ });
+
+ it("clears bubble on row", () => {
+ const bubble = {
+ marker: { getBufferRange: () => new Range([5, 1], [5, 3]) }
+ };
+
+ spyOn(store, "delete");
+
+ store.markers.set(1, bubble);
+ expect(store.markers.size).toEqual(1);
+
+ expect(store.clearOnRow(20)).toEqual(false);
+ expect(store.delete).not.toHaveBeenCalled();
+
+ expect(store.clearOnRow(5)).toEqual(true);
+ expect(store.delete).toHaveBeenCalledWith(1);
+ });
+}); | |
9f88221838c29374d8845e5dd7c5895953ba37af | test/RowSpec.js | test/RowSpec.js | import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import Row from '../src/Row';
describe('Row', function () {
it('uses "div" by default', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Row />
);
assert.equal(React.findDOMNode(instance).nodeName, 'DIV');
});
it('has "row" class', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Row>Row content</Row>
);
assert.equal(React.findDOMNode(instance).className, 'row');
});
it('Should merge additional classes passed in', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Row className="bob"/>
);
assert.ok(React.findDOMNode(instance).className.match(/\bbob\b/));
assert.ok(React.findDOMNode(instance).className.match(/\brow\b/));
});
it('allows custom elements instead of "div"', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Row componentClass='section' />
);
assert.equal(React.findDOMNode(instance).nodeName, 'SECTION');
});
});
| Add missing tests for 'Row' | Add missing tests for 'Row'
| JavaScript | mit | dongtong/react-bootstrap,egauci/react-bootstrap,gianpaj/react-bootstrap,JimiHFord/react-bootstrap,HorizonXP/react-bootstrap,react-bootstrap/react-bootstrap,jakubsikora/react-bootstrap,Sipree/react-bootstrap,Terminux/react-bootstrap,chrishoage/react-bootstrap,xuorig/react-bootstrap,azmenak/react-bootstrap,mmarcant/react-bootstrap,jesenko/react-bootstrap,Lucifier129/react-bootstrap,pivotal-cf/react-bootstrap,Lucifier129/react-bootstrap,coderstudy/react-bootstrap,victorzhang17/react-bootstrap,pombredanne/react-bootstrap,pieter-lazzaro/react-bootstrap,zanjs/react-bootstrap,tannewt/react-bootstrap,nickuraltsev/react-bootstrap,kwnccc/react-bootstrap,herojobs/react-bootstrap,deerawan/react-bootstrap,xiaoking/react-bootstrap,westonplatter/react-bootstrap,adampickeral/react-bootstrap,aparticka/react-bootstrap,mengmenglv/react-bootstrap,justinanastos/react-bootstrap,dozoisch/react-bootstrap,zerkms/react-bootstrap,brentertz/react-bootstrap,natlownes/react-bootstrap,AlexKVal/react-bootstrap,andrew-d/react-bootstrap,mxc/react-bootstrap,jontewks/react-bootstrap,erictherobot/react-bootstrap,react-bootstrap/react-bootstrap,pandoraui/react-bootstrap,wjb12/react-bootstrap,react-bootstrap/react-bootstrap,PeterDaveHello/react-bootstrap,insionng/react-bootstrap,HPate-Riptide/react-bootstrap,xsistens/react-bootstrap,chilts/react-bootstrap,asiniy/react-bootstrap,albertojacini/react-bootstrap,omerts/react-bootstrap,apisandipas/react-bootstrap,laran/react-bootstrap,tonylinyy/react-bootstrap,BespokeInsights/react-bootstrap,brynjagr/react-bootstrap,glenjamin/react-bootstrap,bbc/react-bootstrap,glenjamin/react-bootstrap,roderickwang/react-bootstrap,blue68/react-bootstrap,apkiernan/react-bootstrap,bvasko/react-bootstrap,roadmanfong/react-bootstrap,thealjey/react-bootstrap,snadn/react-bootstrap,cgvarela/react-bootstrap,IveWong/react-bootstrap,sheep902/react-bootstrap | ---
+++
@@ -0,0 +1,36 @@
+import React from 'react';
+import ReactTestUtils from 'react/lib/ReactTestUtils';
+import Row from '../src/Row';
+
+describe('Row', function () {
+ it('uses "div" by default', function () {
+ let instance = ReactTestUtils.renderIntoDocument(
+ <Row />
+ );
+
+ assert.equal(React.findDOMNode(instance).nodeName, 'DIV');
+ });
+
+ it('has "row" class', function () {
+ let instance = ReactTestUtils.renderIntoDocument(
+ <Row>Row content</Row>
+ );
+ assert.equal(React.findDOMNode(instance).className, 'row');
+ });
+
+ it('Should merge additional classes passed in', function () {
+ let instance = ReactTestUtils.renderIntoDocument(
+ <Row className="bob"/>
+ );
+ assert.ok(React.findDOMNode(instance).className.match(/\bbob\b/));
+ assert.ok(React.findDOMNode(instance).className.match(/\brow\b/));
+ });
+
+ it('allows custom elements instead of "div"', function () {
+ let instance = ReactTestUtils.renderIntoDocument(
+ <Row componentClass='section' />
+ );
+
+ assert.equal(React.findDOMNode(instance).nodeName, 'SECTION');
+ });
+}); | |
a07c46d7cc3861ac98c98bcf0a179f8285dc9182 | app/assets/javascripts/autosave.js | app/assets/javascripts/autosave.js | function autosaveSnippet () {
var $url = $('.edit_snippet')[0].action;
var $data = $('.edit_snippet').serialize();
$.ajax({
type: "PATCH",
url: $url,
data: $data,
dataType: "text"
}).done(function(response){
console.log(response);
$(".autosave").html(response);
});
}
function autosaveStory () {
var $url = $('.edit_story')[0].action;
var $data = $('.edit_story').serialize();
$.ajax({
type: "PATCH",
url: $url,
data: $data,
dataType: "text"
}).done(function(response){
console.log(response);
$(".autosave").html(response);
});
}
$(document).ready(function (){
var autosaveOnFocus;
$('.redactor_editor').focus(function() {
if ($('.edit_snippet').length !== 0) {
autosaveOnFocus = setInterval(autosaveSnippet, 5000);
}
else {
autosaveOnFocus = setInterval(autosaveStory, 5000);
}
});
$('.redactor_editor').blur(function() {
console.log(autosaveOnFocus);
clearInterval(autosaveOnFocus);
console.log(autosaveOnFocus);
})
});
| function autosaveSnippet () {
var $url = $('.edit_snippet')[0].action;
var $data = $('.edit_snippet').serialize();
$.ajax({
type: "PATCH",
url: $url,
data: $data,
dataType: "text"
}).done(function(response){
console.log(response);
$(".autosave").html(response);
});
}
function autosaveStory () {
var $url = $('.edit_story')[0].action;
var $data = $('.edit_story').serialize();
$.ajax({
type: "PATCH",
url: $url,
data: $data,
dataType: "text"
}).done(function(response){
console.log(response);
$(".autosave").html(response);
});
}
$(document).ready(function (){
var autosaveOnFocus;
$('.redactor_editor').focus(function() {
if ($('.edit_snippet').length !== 0) {
autosaveOnFocus = setInterval(autosaveSnippet, 5000);
}
else {
autosaveOnFocus = setInterval(autosaveStory, 5000);
}
});
$('.redactor_editor').blur(function() {
console.log(autosaveOnFocus);
clearInterval(autosaveOnFocus);
console.log(autosaveOnFocus);
})
});
| Add an extra blank line | Add an extra blank line
| JavaScript | mit | pearlshin/StoryVine,mxngyn/StoryVine,mxngyn/StoryVine,SputterPuttRedux/storyvine_clone,SputterPuttRedux/storyvine_clone,mxngyn/StoryVine,pearlshin/StoryVine,pearlshin/StoryVine,SputterPuttRedux/storyvine_clone | ---
+++
@@ -44,4 +44,5 @@
clearInterval(autosaveOnFocus);
console.log(autosaveOnFocus);
})
+
}); |
daa98b6991b4997deb5202ae4e5dbc307d720226 | src/main/webapp/resources/marketplace/js/AlertManager.js | src/main/webapp/resources/marketplace/js/AlertManager.js | /**
* Copyright (c) 2015, CoNWeT Lab., Universidad Politécnica de Madrid
* Code licensed under BSD 3-Clause (https://github.com/conwetlab/WMarket/blob/master/LICENSE)
*/
WMarket.alerts = (function () {
"use strict";
var AlertManager = {
'info': function info(messageContent, extraClass) {
var defaultIcon = $('<span>').addClass("fa fa-info-circle");
return createAlert('info', defaultIcon, messageContent, extraClass);
},
'warning': function warning(messageContent, extraClass) {
var defaultIcon = $('<span>').addClass("fa fa-exclamation-circle");
return createAlert('warning', defaultIcon, messageContent, extraClass);
}
};
var createAlert = function createAlert(type, icon, content, extraClass) {
var alert = $('<div>').addClass('alert alert-' + type);
return alert.addClass(extraClass).append(icon, " ", content);
};
return AlertManager;
})();
| Add module JS to manage alerts | Add module JS to manage alerts
Signed-off-by: Aitor Magán García <a93a7d273b830b2e8a26461c1a80328a1d7ad27a@conwet.com>
| JavaScript | bsd-3-clause | Fiware/apps.WMarket,conwetlab/WMarket,conwetlab/WMarket,Fiware/apps.WMarket,Fiware/apps.WMarket,conwetlab/WMarket,Fiware/apps.WMarket,conwetlab/WMarket | ---
+++
@@ -0,0 +1,34 @@
+/**
+ * Copyright (c) 2015, CoNWeT Lab., Universidad Politécnica de Madrid
+ * Code licensed under BSD 3-Clause (https://github.com/conwetlab/WMarket/blob/master/LICENSE)
+ */
+
+WMarket.alerts = (function () {
+
+ "use strict";
+
+ var AlertManager = {
+
+ 'info': function info(messageContent, extraClass) {
+ var defaultIcon = $('<span>').addClass("fa fa-info-circle");
+
+ return createAlert('info', defaultIcon, messageContent, extraClass);
+ },
+
+ 'warning': function warning(messageContent, extraClass) {
+ var defaultIcon = $('<span>').addClass("fa fa-exclamation-circle");
+
+ return createAlert('warning', defaultIcon, messageContent, extraClass);
+ }
+
+ };
+
+ var createAlert = function createAlert(type, icon, content, extraClass) {
+ var alert = $('<div>').addClass('alert alert-' + type);
+
+ return alert.addClass(extraClass).append(icon, " ", content);
+ };
+
+ return AlertManager;
+
+})(); | |
f0fff4fe4f8e5fffa984b55d90c0a70d6e302fe2 | openstack_dashboard/static/app/core/images/details/details.module.spec.js | openstack_dashboard/static/app/core/images/details/details.module.spec.js | /**
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
(function() {
'use strict';
describe('images details module', function() {
var registry, resource;
beforeEach(module('horizon.app.core.images.details'));
beforeEach(inject(function($injector) {
registry = $injector.get('horizon.framework.conf.resource-type-registry.service');
}));
it('should be loaded', function() {
resource = registry.getResourceType('OS::Glance::Image');
expect(resource.detailsViews[0].id).toBe('imageDetailsOverview');
});
});
})();
| Add unit test for image detail | Add unit test for image detail
Change-Id: I8ae82e37be53b8b7642534e4f6772cb1e52ef3d6
| JavaScript | apache-2.0 | openstack/horizon,openstack/horizon,NeCTAR-RC/horizon,openstack/horizon,NeCTAR-RC/horizon,ChameleonCloud/horizon,ChameleonCloud/horizon,NeCTAR-RC/horizon,ChameleonCloud/horizon,openstack/horizon,ChameleonCloud/horizon,NeCTAR-RC/horizon | ---
+++
@@ -0,0 +1,31 @@
+/**
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ */
+
+(function() {
+ 'use strict';
+
+ describe('images details module', function() {
+ var registry, resource;
+ beforeEach(module('horizon.app.core.images.details'));
+ beforeEach(inject(function($injector) {
+ registry = $injector.get('horizon.framework.conf.resource-type-registry.service');
+ }));
+
+ it('should be loaded', function() {
+ resource = registry.getResourceType('OS::Glance::Image');
+ expect(resource.detailsViews[0].id).toBe('imageDetailsOverview');
+ });
+ });
+})(); | |
41667f629da4f51769d8849df9465ef9da75ea47 | gulpfile.babel.js | gulpfile.babel.js | const gulp = require('gulp'),
bs = require('browser-sync').create(),
nunjucks = require('gulp-nunjucks-render'),
sass = require('gulp-sass'),
sourcemaps = require('gulp-sourcemaps');
function html() {
return gulp.src('src/index.njk')
.pipe(nunjucks({
path: 'src/'
}))
.pipe(gulp.dest('./dist'))
.pipe(bs.stream());
}
function css() {
return gulp.src('src/sass/main.scss')
.pipe(sourcemaps.init())
.pipe(sass())
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('./dist/css'))
.pipe(bs.stream());
}
function js() {
return gulp.src('src/**/*.js')
.pipe(sourcemaps.init())
.pipe(babel())
.pipe(concat('all.js'))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('./dist/js'))
.pipe(bs.stream());
}
function dev() {
bs.init({
server: "./dist"
})
gulp.watch('src/**/*.njk', html).on('end', bs.reload);
gulp.watch('src/sass/**/*.scss', css).on('end', bs.reload);
}
gulp.task(
'default',
gulp.series(
gulp.parallel(html, css),
dev
)
);
| Rename Gulpfile to use Babel. | Rename Gulpfile to use Babel.
| JavaScript | mit | majtom2grndctrl/design-guide-scaffold,majtom2grndctrl/design-guide-scaffold | ---
+++
@@ -0,0 +1,49 @@
+const gulp = require('gulp'),
+ bs = require('browser-sync').create(),
+ nunjucks = require('gulp-nunjucks-render'),
+ sass = require('gulp-sass'),
+ sourcemaps = require('gulp-sourcemaps');
+
+function html() {
+ return gulp.src('src/index.njk')
+ .pipe(nunjucks({
+ path: 'src/'
+ }))
+ .pipe(gulp.dest('./dist'))
+ .pipe(bs.stream());
+}
+
+function css() {
+ return gulp.src('src/sass/main.scss')
+ .pipe(sourcemaps.init())
+ .pipe(sass())
+ .pipe(sourcemaps.write('./'))
+ .pipe(gulp.dest('./dist/css'))
+ .pipe(bs.stream());
+}
+
+function js() {
+ return gulp.src('src/**/*.js')
+ .pipe(sourcemaps.init())
+ .pipe(babel())
+ .pipe(concat('all.js'))
+ .pipe(sourcemaps.write('.'))
+ .pipe(gulp.dest('./dist/js'))
+ .pipe(bs.stream());
+}
+
+function dev() {
+ bs.init({
+ server: "./dist"
+ })
+ gulp.watch('src/**/*.njk', html).on('end', bs.reload);
+ gulp.watch('src/sass/**/*.scss', css).on('end', bs.reload);
+}
+
+gulp.task(
+ 'default',
+ gulp.series(
+ gulp.parallel(html, css),
+ dev
+ )
+); | |
a2f4e0a23386678a46fceaa4efd8802d8dd5d6bd | 17/amqp-server-worker.js | 17/amqp-server-worker.js | var amqp = require('amqp');
var connection = amqp.createConnection({
host: 'localhost'
});
connection.on('ready', function () {
connection.queue('task-queue', { autoDelete: false, durable: true }, function(q) {
q.bind('#');
q.subscribe({ ack: true, prefetchCount: 1 }, function(message) {
console.log(message);
q.shift();
});
});
});
| Add the example to the worker for RabbitMG server. | Add the example to the worker for RabbitMG server.
| JavaScript | mit | nicebook/Node.js-Reference,nicebook/Node.js-Reference,nicebook/Node.js-Reference | ---
+++
@@ -0,0 +1,15 @@
+var amqp = require('amqp');
+
+var connection = amqp.createConnection({
+ host: 'localhost'
+});
+
+connection.on('ready', function () {
+ connection.queue('task-queue', { autoDelete: false, durable: true }, function(q) {
+ q.bind('#');
+ q.subscribe({ ack: true, prefetchCount: 1 }, function(message) {
+ console.log(message);
+ q.shift();
+ });
+ });
+}); | |
d11e67d241fd12daff2ec7ea2c2ad5ef1d8bb166 | index.js | index.js | "use strict";
// Export the most important modules
global[ "ResourceBundle" ] = require( "./lib/resource-bundle" );
global[ "Locale" ] = require( "./lib/locale" );
global[ "Currency" ] = require( "./lib/currency" );
global[ "Format" ] = require( "./lib/format" );
global[ "FieldPosition" ] = require( "./lib/field-position" );
global[ "ParsePosition" ] = require( "./lib/parse-position" );
global[ "DateFormatSymbols" ] = require( "./lib/date-format-symbols" );
global[ "DecimalFormatSymbols" ] = require( "./lib/decimal-format-symbols" );
global[ "NumberFormat" ] = require( "./lib/number-format" );
global[ "DecimalFormat" ] = require( "./lib/decimal-format" );
global[ "ChoiceFormat" ] = require( "./lib/choice-format" );
global[ "DateFormat" ] = require( "./lib/date-format" );
global[ "SimpleDateFormat" ] = require( "./lib/simple-date-format" );
global[ "MessageFormat" ] = require( "./lib/message-format" );
| Add the package main file | Add the package main file
| JavaScript | mit | yannickebongue/text-formatjs,yannickebongue/text-formatjs | ---
+++
@@ -0,0 +1,18 @@
+"use strict";
+
+// Export the most important modules
+
+global[ "ResourceBundle" ] = require( "./lib/resource-bundle" );
+global[ "Locale" ] = require( "./lib/locale" );
+global[ "Currency" ] = require( "./lib/currency" );
+global[ "Format" ] = require( "./lib/format" );
+global[ "FieldPosition" ] = require( "./lib/field-position" );
+global[ "ParsePosition" ] = require( "./lib/parse-position" );
+global[ "DateFormatSymbols" ] = require( "./lib/date-format-symbols" );
+global[ "DecimalFormatSymbols" ] = require( "./lib/decimal-format-symbols" );
+global[ "NumberFormat" ] = require( "./lib/number-format" );
+global[ "DecimalFormat" ] = require( "./lib/decimal-format" );
+global[ "ChoiceFormat" ] = require( "./lib/choice-format" );
+global[ "DateFormat" ] = require( "./lib/date-format" );
+global[ "SimpleDateFormat" ] = require( "./lib/simple-date-format" );
+global[ "MessageFormat" ] = require( "./lib/message-format" ); | |
1ab91d4923ece874474ae08934452b35609c4124 | metashare/media/js/jsi18n.js | metashare/media/js/jsi18n.js | /* gettext library */
// This function is copied from django admin path
var catalog = new Array();
function pluralidx(count) { return (count == 1) ? 0 : 1; }
function gettext(msgid) {
var value = catalog[msgid];
if (typeof(value) == 'undefined') {
return msgid;
} else {
return (typeof(value) == 'string') ? value : value[0];
}
}
function ngettext(singular, plural, count) {
value = catalog[singular];
if (typeof(value) == 'undefined') {
return (count == 1) ? singular : plural;
} else {
return value[pluralidx(count)];
}
}
function gettext_noop(msgid) { return msgid; }
function interpolate(fmt, obj, named) {
if (named) {
return fmt.replace(/%\(\w+\)s/g, function(match){return String(obj[match.slice(2,-2)])});
} else {
return fmt.replace(/%s/g, function(match){return String(obj.shift())});
}
}
| Manage default editor group on a single page | Manage default editor group on a single page
| JavaScript | bsd-3-clause | MiltosD/CEF-ELRC,MiltosD/CEF-ELRC,zeehio/META-SHARE,MiltosD/CEFELRC,JuliBakagianni/META-SHARE,JuliBakagianni/CEF-ELRC,zeehio/META-SHARE,MiltosD/CEFELRC,JuliBakagianni/CEF-ELRC,JuliBakagianni/META-SHARE,MiltosD/CEF-ELRC,MiltosD/CEFELRC,JuliBakagianni/META-SHARE,JuliBakagianni/CEF-ELRC,zeehio/META-SHARE,zeehio/META-SHARE,MiltosD/CEF-ELRC,MiltosD/CEF-ELRC,JuliBakagianni/CEF-ELRC,MiltosD/CEF-ELRC,JuliBakagianni/CEF-ELRC,JuliBakagianni/META-SHARE,MiltosD/CEF-ELRC,zeehio/META-SHARE,JuliBakagianni/CEF-ELRC,zeehio/META-SHARE,zeehio/META-SHARE,MiltosD/CEFELRC,JuliBakagianni/META-SHARE,JuliBakagianni/META-SHARE,MiltosD/CEFELRC,JuliBakagianni/CEF-ELRC,JuliBakagianni/META-SHARE,MiltosD/CEFELRC,MiltosD/CEFELRC | ---
+++
@@ -0,0 +1,35 @@
+/* gettext library */
+// This function is copied from django admin path
+
+var catalog = new Array();
+
+function pluralidx(count) { return (count == 1) ? 0 : 1; }
+
+
+function gettext(msgid) {
+var value = catalog[msgid];
+if (typeof(value) == 'undefined') {
+return msgid;
+} else {
+return (typeof(value) == 'string') ? value : value[0];
+}
+}
+
+function ngettext(singular, plural, count) {
+value = catalog[singular];
+if (typeof(value) == 'undefined') {
+return (count == 1) ? singular : plural;
+} else {
+return value[pluralidx(count)];
+}
+}
+
+function gettext_noop(msgid) { return msgid; }
+
+function interpolate(fmt, obj, named) {
+if (named) {
+return fmt.replace(/%\(\w+\)s/g, function(match){return String(obj[match.slice(2,-2)])});
+} else {
+return fmt.replace(/%s/g, function(match){return String(obj.shift())});
+}
+} | |
54a5a217282470916cbc97c08209f39f89296f19 | test/mecab_test.js | test/mecab_test.js | 'use strict';
const assert = require('assert');
const Mecab = require('../lib/mecab');
describe('Mecab', () => {
const tests = [
{argv: '本日は晴天なり', expected: ['本日', 'は', '晴天', 'なり']},
{argv: '\r\n 本日は晴天なり \r\n \r\n', expected: ['本日', 'は', '晴天', 'なり']},
];
tests.forEach(test => {
it(`should return a valid array of words: "${test.argv}"`, () =>{
Mecab.parse(test.argv, (res, err) => {
assert.equals(res, test.expected);
});
});
});
});
| Add test cases of mecab.js | Add test cases of mecab.js
| JavaScript | mit | tanikawa04/kyrica | ---
+++
@@ -0,0 +1,20 @@
+'use strict';
+
+const assert = require('assert');
+
+const Mecab = require('../lib/mecab');
+
+describe('Mecab', () => {
+ const tests = [
+ {argv: '本日は晴天なり', expected: ['本日', 'は', '晴天', 'なり']},
+ {argv: '\r\n 本日は晴天なり \r\n \r\n', expected: ['本日', 'は', '晴天', 'なり']},
+ ];
+
+ tests.forEach(test => {
+ it(`should return a valid array of words: "${test.argv}"`, () =>{
+ Mecab.parse(test.argv, (res, err) => {
+ assert.equals(res, test.expected);
+ });
+ });
+ });
+}); | |
a3b279660d21b9e4453a68f9cbfaae7d0cef1ef0 | public/modules/core/directives/focusOn.js | public/modules/core/directives/focusOn.js | /*global angular*/
(function () {
'use strict';
angular.module('core').directive('focusOn', ["$timeout", "$parse", function ($timeout, $parse) {
return {
link: function (scope, element, attrs) {
var expr = $parse(attrs.focusOn);
scope.$watch(expr, function (value) {
if (value) {
$timeout(function () {
element.focus();
}, 0, false);
}
});
}
};
}]);
}());
| Add directive to focus an element based on an expression (useful for search inputs). | Add directive to focus an element based on an expression (useful for search inputs).
| JavaScript | mit | tmol/iQSlideShow,tmol/iQSlideShow,tmol/iQSlideShow | ---
+++
@@ -0,0 +1,20 @@
+/*global angular*/
+(function () {
+ 'use strict';
+
+ angular.module('core').directive('focusOn', ["$timeout", "$parse", function ($timeout, $parse) {
+ return {
+ link: function (scope, element, attrs) {
+ var expr = $parse(attrs.focusOn);
+
+ scope.$watch(expr, function (value) {
+ if (value) {
+ $timeout(function () {
+ element.focus();
+ }, 0, false);
+ }
+ });
+ }
+ };
+ }]);
+}()); | |
043fec02cb4d1ad6c90422701079f12d80662811 | app/assets/javascripts/unit_toggler.js | app/assets/javascripts/unit_toggler.js | $(function() {
$('.toggleDeadlineUnitDate').on('click', function(e) {
e.preventDefault();
$(this).replaceWith("<label for='project_goal_deadline_date'>Goal Deadline Date</label><input type='date' name='project[goal_deadline_date]' id='project_goal_deadline_date'></input>");
$('.toggleDeadlineUnitHours').remove();
});
$('.toggleDeadlineUnitHours').on('click', function(e) {
e.preventDefault();
$(this).replaceWith("<label for='project_goal_time_limit'>Goal Time Limit</label><input type='text' name='project[goal_time_limit]' id='project_goal_time_limit'></input>");
$('.toggleDeadlineUnitDate').remove();
});
}); | Add JS date toggle file and functionality. | Add JS date toggle file and functionality.
| JavaScript | mit | tiger-swallowtails-2014/write-now,tiger-swallowtails-2014/write-now | ---
+++
@@ -0,0 +1,14 @@
+$(function() {
+ $('.toggleDeadlineUnitDate').on('click', function(e) {
+ e.preventDefault();
+ $(this).replaceWith("<label for='project_goal_deadline_date'>Goal Deadline Date</label><input type='date' name='project[goal_deadline_date]' id='project_goal_deadline_date'></input>");
+ $('.toggleDeadlineUnitHours').remove();
+ });
+
+ $('.toggleDeadlineUnitHours').on('click', function(e) {
+ e.preventDefault();
+ $(this).replaceWith("<label for='project_goal_time_limit'>Goal Time Limit</label><input type='text' name='project[goal_time_limit]' id='project_goal_time_limit'></input>");
+ $('.toggleDeadlineUnitDate').remove();
+ });
+
+}); | |
45e9577cad2e3955edc60e3acb831ef1445c38e6 | lib/middleware/timeout.js | lib/middleware/timeout.js | /*!
* Connect - timeout
* Ported from https://github.com/LearnBoost/connect-timeout
* MIT Licensed
*/
/**
* Module dependencies.
*/
var debug = require('debug')('connect:timeout');
/**
* Timeout:
*
* Times out the request in `ms`, defaulting to `5000`. The
* method `req.clearTimeout()` is added to revert this behaviour
* programmatically within your application's middleware, routes, etc.
*
* The timeout error is passed to `next()` so that you may customize
* the response behaviour. This error has the `.timeout` property as
* well as `.status == 408`.
*
* @param {Number} ms
* @return {Function}
* @api public
*/
module.exports = function timeout(ms) {
ms = ms || 5000;
return function(req, res, next) {
var id = setTimeout(function(){
req.emit('timeout', ms);
}, ms);
req.on('timeout', function(){
if (res.headerSent) return debug('response started, cannot timeout');
var err = new Error('Response timeout');
err.timeout = ms;
err.status = 503;
next(err);
});
req.clearTimeout = function(){
clearTimeout(id);
};
res.on('header', function(){
clearTimeout(id);
});
next();
};
};
| /*!
* Connect - timeout
* Ported from https://github.com/LearnBoost/connect-timeout
* MIT Licensed
*/
/**
* Module dependencies.
*/
var debug = require('debug')('connect:timeout');
/**
* Timeout:
*
* Times out the request in `ms`, defaulting to `5000`. The
* method `req.clearTimeout()` is added to revert this behaviour
* programmatically within your application's middleware, routes, etc.
*
* The timeout error is passed to `next()` so that you may customize
* the response behaviour. This error has the `.timeout` property as
* well as `.status == 503`.
*
* @param {Number} ms
* @return {Function}
* @api public
*/
module.exports = function timeout(ms) {
ms = ms || 5000;
return function(req, res, next) {
var id = setTimeout(function(){
req.emit('timeout', ms);
}, ms);
req.on('timeout', function(){
if (res.headerSent) return debug('response started, cannot timeout');
var err = new Error('Response timeout');
err.timeout = ms;
err.status = 503;
next(err);
});
req.clearTimeout = function(){
clearTimeout(id);
};
res.on('header', function(){
clearTimeout(id);
});
next();
};
};
| Fix status code in documentation | Fix status code in documentation
Fix a mismatch between the documented status code (408) and the one set by the middleware | JavaScript | mit | behind2/connect,chinazhaghai/connect,liuwei9413/connect,khirayama/connect,austincitylimits/connect,RoseTHERESA/connect,lian774739140/connect,davehorton/drachtio,tanveer12332/connect,khalerc/connect,qitianchan/connect,gtomitsuka/connect,RickyDan/connect,dkfiresky/connect,mi2oon/connect,keenwon/connect,llwanghong/connect,senchalabs/connect,mi2oon/connect,wghust/connect | ---
+++
@@ -19,7 +19,7 @@
*
* The timeout error is passed to `next()` so that you may customize
* the response behaviour. This error has the `.timeout` property as
- * well as `.status == 408`.
+ * well as `.status == 503`.
*
* @param {Number} ms
* @return {Function} |
bd532c391431ab5f097fbf15e36a5db9b4e8415a | src/utils/config.js | src/utils/config.js | // node modules
import fs from 'fs';
// npm modules
import homedir from 'homedir';
const configFilePath = `${homedir()}/.urcli/config.json`;
export class Config {
constructor() {
try {
const config = JSON.parse(fs.readFileSync(configFilePath));
Object.assign(this, config);
} catch (e) {
// We can ignore ENOENT and throw on everything else.
if (e.code !== 'ENOENT') {
console.error('Error reading from filesystem.');
throw new Error(e);
}
}
}
save(configValues) {
Object.assign(this, configValues);
const config = JSON.stringify(this, null, 2);
try {
fs.writeFileSync(configFilePath, config);
} catch (e) {
// We can create both the config folder and file on ENOENT and throw on
// everything else.
if (e.code !== 'ENOENT') {
console.error('Error while saving the config file.');
throw new Error(e);
}
fs.mkdirSync(`${homedir()}/.urcli`);
fs.writeFileSync(configFilePath, config);
}
return this;
}
}
| // node modules
import fs from 'fs';
// npm modules
import homedir from 'homedir';
const configFilePath = `${homedir()}/.urcli/config.json`;
export class Config {
constructor() {
try {
const config = JSON.parse(fs.readFileSync(configFilePath));
Object.assign(this, config);
} catch (e) {
// We can ignore ENOENT and throw on everything else.
if (e.code !== 'ENOENT') {
console.error('Error reading from filesystem.');
throw new Error(e);
}
}
}
save() {
const newConfigs = JSON.stringify(this, null, 2);
try {
fs.writeFileSync(configFilePath, newConfigs);
} catch (e) {
// We can create both the config folder and file on ENOENT and throw on
// everything else.
if (e.code !== 'ENOENT') {
console.error('Error while saving the config file.');
throw new Error(e);
}
fs.mkdirSync(`${homedir()}/.urcli`);
fs.writeFileSync(configFilePath, newConfigs);
}
return this;
}
}
| Save the object itself, rather than a list of arguments | Save the object itself, rather than a list of arguments
| JavaScript | mit | trolster/urcli,gabraganca/ur-cli,trolster/ur-cli | ---
+++
@@ -18,11 +18,10 @@
}
}
}
- save(configValues) {
- Object.assign(this, configValues);
- const config = JSON.stringify(this, null, 2);
+ save() {
+ const newConfigs = JSON.stringify(this, null, 2);
try {
- fs.writeFileSync(configFilePath, config);
+ fs.writeFileSync(configFilePath, newConfigs);
} catch (e) {
// We can create both the config folder and file on ENOENT and throw on
// everything else.
@@ -31,7 +30,7 @@
throw new Error(e);
}
fs.mkdirSync(`${homedir()}/.urcli`);
- fs.writeFileSync(configFilePath, config);
+ fs.writeFileSync(configFilePath, newConfigs);
}
return this;
} |
a7c95c5cdccf0ec21ce2da6d71e4fb756059dc5b | tools/distServer.js | tools/distServer.js | // This file configures a web server for testing the production build
// on your local machine.
import browserSync from 'browser-sync';
import historyApiFallback from 'connect-history-api-fallback';
// Run Browsersync
browserSync({
port: 3000,
ui: {
port: 3001
},
server: {
baseDir: 'dist'
},
files: [
'src/*.html'
],
middleware: [historyApiFallback()]
});
| // This file configures a web server for testing the production build
// on your local machine.
import browserSync from 'browser-sync';
import historyApiFallback from 'connect-history-api-fallback';
import {chalkProcessing} from './chalkConfig';
/* eslint-disable no-console */
console.log(chalkProcessing('Opening production build...'));
// Run Browsersync
browserSync({
port: 3000,
ui: {
port: 3001
},
server: {
baseDir: 'dist'
},
files: [
'src/*.html'
],
middleware: [historyApiFallback()]
});
| Add message when opening prod build | Add message when opening prod build
| JavaScript | mit | svitekpavel/Conway-s-Game-of-Life,danpersa/remindmetolive-react,svitekpavel/chatbot-website,waneka/codenames,PatrickHai/react-client-changers,danpersa/remindmetolive-react,lisavogtsf/canned-react-slingshot-app,aaronholmes/yelp-clone,oded-soffrin/gkm_viewer,kpuno/survey-app,akataz/theSite,oshalygin/react-slingshot,oshalygin/react-slingshot,coryhouse/react-slingshot,BenMGilman/react-lunch-and-learn,PatrickHai/react-client-changers,Nevraeka/cfx-prerender,aaronholmes/yelp-clone,seantcoyote/react-slingshot-bones,luanatsainsburys/road-runner,flibertigibet/react-redux-starter-kit-custom,danpersa/remindmetolive-react,garusis/up-designer,AurimasSk/DemoStore,waneka/codenames,seantcoyote/react-slingshot-bones,sadasystems/react-slingshot,lisavogtsf/canned-react-slingshot-app,barbel840113/testapp,garusis/up-designer,kpuno/survey-app,oded-soffrin/gkm_viewer,barbel840113/testapp,ronstarcool/pf,svitekpavel/Conway-s-Game-of-Life,ronstarcool/pf,MouseZero/nightlife-frontend,coryhouse/react-slingshot,sadasystems/react-slingshot,AurimasSk/DemoStore,codenamekt/reactive-boiler,svitekpavel/chatbot-website,MouseZero/nightlife-frontend,git-okuzenko/react-redux,flibertigibet/react-redux-starter-kit-custom,waneka/codenames,git-okuzenko/react-redux,codenamekt/reactive-boiler,BenMGilman/react-lunch-and-learn,akataz/theSite,Nevraeka/cfx-prerender,luanatsainsburys/road-runner | ---
+++
@@ -3,6 +3,11 @@
import browserSync from 'browser-sync';
import historyApiFallback from 'connect-history-api-fallback';
+import {chalkProcessing} from './chalkConfig';
+
+/* eslint-disable no-console */
+
+console.log(chalkProcessing('Opening production build...'));
// Run Browsersync
browserSync({ |
82d1b94903536e70edf56faa5011246be9c67be3 | scripts/bugs/math_pow.js | scripts/bugs/math_pow.js | 'use strict';
var x = 10;
var y = 308;
var actual = Math.pow( x, y );
var expected = 1e308;
console.log( 'pow(%d,%d) = %d. Expected: %d.', x, y, actual, expected );
actual = pow( x, y );
console.log( 'pow(%d,%d) = %d. Expected: %d.', x, y, actual, expected );
// See https://bugs.chromium.org/p/v8/issues/detail?id=3599
function pow( x, y ) {
var m = x;
var n = y;
var p = 1;
while ( n !== 0 ) {
if ( ( n & 1 ) !== 0 ) {
p *= m;
}
m *= m;
if ( ( n & 2 ) !== 0 ) {
p *= m;
}
m *= m;
n >>= 2;
}
return p;
}
| Add script showing Math.pow bug | Add script showing Math.pow bug
| JavaScript | mit | kgryte/talks-nodejs-interactive-2016,kgryte/talks-nodejs-interactive-2016 | ---
+++
@@ -0,0 +1,30 @@
+'use strict';
+
+var x = 10;
+var y = 308;
+var actual = Math.pow( x, y );
+var expected = 1e308;
+
+console.log( 'pow(%d,%d) = %d. Expected: %d.', x, y, actual, expected );
+
+actual = pow( x, y );
+console.log( 'pow(%d,%d) = %d. Expected: %d.', x, y, actual, expected );
+
+// See https://bugs.chromium.org/p/v8/issues/detail?id=3599
+function pow( x, y ) {
+ var m = x;
+ var n = y;
+ var p = 1;
+ while ( n !== 0 ) {
+ if ( ( n & 1 ) !== 0 ) {
+ p *= m;
+ }
+ m *= m;
+ if ( ( n & 2 ) !== 0 ) {
+ p *= m;
+ }
+ m *= m;
+ n >>= 2;
+ }
+ return p;
+} | |
8f141dc580a0168927441745c824a7e98382e805 | boxcharter/common/status_types.js | boxcharter/common/status_types.js | /*
* Copyright (c) 2017 Bonnie Schulkin. All Rights Reserved.
*
* This file is part of BoxCharter.
*
* BoxCharter is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version.
*
* BoxCharter is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License
* for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with BoxCharter. If not, see <http://www.gnu.org/licenses/>.
*
*/
/* for status consistency from express to angular */
const statusTypes = {
success: 'success',
warning: 'warning',
danger: 'danger'
}
module.exports = { statusTypes: statusTypes } | Add status type object for consistent use across client / server. | Add status type object for consistent use across client / server.
| JavaScript | agpl-3.0 | flyrightsister/boxcharter,flyrightsister/boxcharter | ---
+++
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2017 Bonnie Schulkin. All Rights Reserved.
+ *
+ * This file is part of BoxCharter.
+ *
+ * BoxCharter is free software: you can redistribute it and/or modify it under
+ * the terms of the GNU Affero General Public License as published by the Free
+ * Software Foundation, either version 3 of the License, or (at your option)
+ * any later version.
+ *
+ * BoxCharter is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with BoxCharter. If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+/* for status consistency from express to angular */
+
+const statusTypes = {
+ success: 'success',
+ warning: 'warning',
+ danger: 'danger'
+}
+
+module.exports = { statusTypes: statusTypes } | |
24136b649067029c3d0f8be4254accc50a68c455 | Medium/073_Set_Matrix_Zeroes.js | Medium/073_Set_Matrix_Zeroes.js | /**
* @param {number[][]} matrix
* @return {void} Do not return anything, modify matrix in-place instead.
*/
var setZeroes = function(matrix) {
var zeroes = [];
for (var i = 0; i < matrix.length; i++) {
for (var j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] === 0) {
zeroes.push([i, j]);
}
}
}
zeroes.forEach(function(axis) {
for (var j = 0; j < matrix[axis[0]].length; j++) {
matrix[axis[0]][j] = 0;
}
for (var i = 0; i < matrix.length; i++) {
matrix[i][axis[1]] = 0;
}
});
};
| Add solution to question 73 | Add solution to question 73
| JavaScript | mit | Rhadow/leetcode,Rhadow/leetcode,Rhadow/leetcode,Rhadow/leetcode | ---
+++
@@ -0,0 +1,23 @@
+/**
+ * @param {number[][]} matrix
+ * @return {void} Do not return anything, modify matrix in-place instead.
+ */
+var setZeroes = function(matrix) {
+ var zeroes = [];
+
+ for (var i = 0; i < matrix.length; i++) {
+ for (var j = 0; j < matrix[i].length; j++) {
+ if (matrix[i][j] === 0) {
+ zeroes.push([i, j]);
+ }
+ }
+ }
+ zeroes.forEach(function(axis) {
+ for (var j = 0; j < matrix[axis[0]].length; j++) {
+ matrix[axis[0]][j] = 0;
+ }
+ for (var i = 0; i < matrix.length; i++) {
+ matrix[i][axis[1]] = 0;
+ }
+ });
+}; | |
1067669be2af48b5f8f55411c0c7d35438535438 | src/common.js | src/common.js | const symbols = {
'~': 'tilde',
'`': 'backtick',
'!': 'exclamation',
'@': 'at',
'#': 'pound',
$: 'dollar',
'%': 'percent',
'^': 'carat',
'&': 'ampersand',
'*': 'asterisk',
'(': 'paren-open',
')': 'paren-close',
'-': 'hyphen',
_: 'underscore',
'=': 'equals',
'+': 'plus',
'[': 'square-open',
']': 'square-close',
'{': 'curly-open',
'}': 'curly-close',
'\\': 'backslash',
'|': 'pipe',
';': 'semicolon',
':': 'colon',
"'": 'single-quote',
'"': 'double-quote',
',': 'comma',
'.': 'period',
'<': 'less',
'>': 'greater',
'/': 'slash',
'?': 'question-mark',
}
export const matchers = {
word: {
name: 'word',
match: /[a-zA-Z]+/,
},
whitespace: {
name: 'whitespace',
match: /\s+/,
},
identifier: {
name: 'identifier',
match: /[\w.]+/,
},
sentence: {
name: 'sentence',
match: /[\w\s]+\./,
},
paragraph: {
name: 'paragraph',
match: /^.*$/m,
},
newline: {
name: 'newline',
match: /\n/,
},
integer: {
name: 'integer',
match: /\d+/,
},
float: {
name: 'float',
match: /\d*\.\d+/,
},
number: {
name: 'number',
match: /\d*\.\d+|\d+/,
},
call: {
name: 'call',
match: /([\w.]+)\((.*)\)/,
},
comment: {
name: 'comment',
match: /(?:(?:\/\/|#).*$|\/\*(.|\n)*?\*\/)/,
},
symbol: {
name: 'symbol',
match: /[^\w\s]/,
},
'symbol-map': {
name: 'symbol',
match: /^[^\w\s]/,
handler: context => {
const symbol = symbols[context.token[1]]
if (symbol) context.tokens.push([symbol, context.token[1]])
},
},
string: {
name: 'string',
match: /(?:"[^"\n]*"|'[^'\n]*')/,
},
unknown: {
name: 'unknown',
match: /[\s\S]/,
},
terminator: {
name: 'terminator',
match: /[\n;]+/,
},
}
| Add a list of useful regex. | Add a list of useful regex.
| JavaScript | mit | kroogs/scanty | ---
+++
@@ -0,0 +1,120 @@
+const symbols = {
+ '~': 'tilde',
+ '`': 'backtick',
+ '!': 'exclamation',
+ '@': 'at',
+ '#': 'pound',
+ $: 'dollar',
+ '%': 'percent',
+ '^': 'carat',
+ '&': 'ampersand',
+ '*': 'asterisk',
+ '(': 'paren-open',
+ ')': 'paren-close',
+ '-': 'hyphen',
+ _: 'underscore',
+ '=': 'equals',
+ '+': 'plus',
+ '[': 'square-open',
+ ']': 'square-close',
+ '{': 'curly-open',
+ '}': 'curly-close',
+ '\\': 'backslash',
+ '|': 'pipe',
+ ';': 'semicolon',
+ ':': 'colon',
+ "'": 'single-quote',
+ '"': 'double-quote',
+ ',': 'comma',
+ '.': 'period',
+ '<': 'less',
+ '>': 'greater',
+ '/': 'slash',
+ '?': 'question-mark',
+}
+
+export const matchers = {
+ word: {
+ name: 'word',
+ match: /[a-zA-Z]+/,
+ },
+
+ whitespace: {
+ name: 'whitespace',
+ match: /\s+/,
+ },
+
+ identifier: {
+ name: 'identifier',
+ match: /[\w.]+/,
+ },
+
+ sentence: {
+ name: 'sentence',
+ match: /[\w\s]+\./,
+ },
+
+ paragraph: {
+ name: 'paragraph',
+ match: /^.*$/m,
+ },
+
+ newline: {
+ name: 'newline',
+ match: /\n/,
+ },
+
+ integer: {
+ name: 'integer',
+ match: /\d+/,
+ },
+
+ float: {
+ name: 'float',
+ match: /\d*\.\d+/,
+ },
+
+ number: {
+ name: 'number',
+ match: /\d*\.\d+|\d+/,
+ },
+
+ call: {
+ name: 'call',
+ match: /([\w.]+)\((.*)\)/,
+ },
+
+ comment: {
+ name: 'comment',
+ match: /(?:(?:\/\/|#).*$|\/\*(.|\n)*?\*\/)/,
+ },
+
+ symbol: {
+ name: 'symbol',
+ match: /[^\w\s]/,
+ },
+
+ 'symbol-map': {
+ name: 'symbol',
+ match: /^[^\w\s]/,
+ handler: context => {
+ const symbol = symbols[context.token[1]]
+ if (symbol) context.tokens.push([symbol, context.token[1]])
+ },
+ },
+
+ string: {
+ name: 'string',
+ match: /(?:"[^"\n]*"|'[^'\n]*')/,
+ },
+
+ unknown: {
+ name: 'unknown',
+ match: /[\s\S]/,
+ },
+
+ terminator: {
+ name: 'terminator',
+ match: /[\n;]+/,
+ },
+} | |
faa58cbd818d4bfcdc2861301d5cd2415b432ac5 | js/nav_menu.js | js/nav_menu.js | /**
* Handle the custom post type nav menu meta box
*/
jQuery( document ).ready( function($) {
$( '#submit-mlp_language' ).click( function( event ) {
event.preventDefault();
var items = $( '#' + mlp_nav_menu.metabox_list_id + ' li :checked' ),
submit = $( '#submit-mlp_language' ),
languages = [],
post_data = { action: mlp_nav_menu.action },
menu_id = $( '#menu' ).val();
items.each( function() {
languages.push( $( this ).val() );
} );
// Show spinner
$( '#' + mlp_nav_menu.metabox_id ).find('.spinner').show();
// Disable button
submit.prop( 'disabled', true );
post_data[ "mlp_sites" ] = languages;
post_data[ mlp_nav_menu.nonce_name ] = mlp_nav_menu.nonce;
post_data[ "menu" ] = menu_id;
// Send checked post types with our action, and nonce
$.post( mlp_nav_menu.ajaxurl, post_data,
// AJAX returns html to add to the menu, hide spinner, remove checks
function( response ) {
$( '#menu-to-edit' ).append( response );
$( '#' + mlp_nav_menu.metabox_id ).find('.spinner').hide();
items.prop( "checked", false);
submit.prop( "disabled", false );
}
);
});
});
| Add missing nav menu js | Add missing nav menu js
| JavaScript | mit | inpsyde/multilingual-press,inpsyde/multilingual-press | ---
+++
@@ -0,0 +1,40 @@
+/**
+ * Handle the custom post type nav menu meta box
+ */
+jQuery( document ).ready( function($) {
+ $( '#submit-mlp_language' ).click( function( event ) {
+ event.preventDefault();
+
+ var items = $( '#' + mlp_nav_menu.metabox_list_id + ' li :checked' ),
+ submit = $( '#submit-mlp_language' ),
+ languages = [],
+ post_data = { action: mlp_nav_menu.action },
+ menu_id = $( '#menu' ).val();
+
+ items.each( function() {
+ languages.push( $( this ).val() );
+ } );
+
+ // Show spinner
+ $( '#' + mlp_nav_menu.metabox_id ).find('.spinner').show();
+
+ // Disable button
+ submit.prop( 'disabled', true );
+
+ post_data[ "mlp_sites" ] = languages;
+ post_data[ mlp_nav_menu.nonce_name ] = mlp_nav_menu.nonce;
+ post_data[ "menu" ] = menu_id;
+
+ // Send checked post types with our action, and nonce
+ $.post( mlp_nav_menu.ajaxurl, post_data,
+
+ // AJAX returns html to add to the menu, hide spinner, remove checks
+ function( response ) {
+ $( '#menu-to-edit' ).append( response );
+ $( '#' + mlp_nav_menu.metabox_id ).find('.spinner').hide();
+ items.prop( "checked", false);
+ submit.prop( "disabled", false );
+ }
+ );
+ });
+}); | |
d2b3e46f9f58b3b47dcec1032401885b2ea139cf | JS-Fundamentals-Homeworks/Operators-and-Expressions/02.Divide-by-7-and-5.js | JS-Fundamentals-Homeworks/Operators-and-Expressions/02.Divide-by-7-and-5.js | function solve(argument) {
var n = parseInt(argument[0]);
if (n % 7 === 0 && n % 5 === 0) {
console.log("true " + n);
} else {
console.log("false " + n);
}
} | Solve problem 02. Divide by 7 and 5 | Solve problem 02. Divide by 7 and 5
| JavaScript | mit | Gyokay/Telerik-Academy-Homeworks,Gyokay/Telerik-Homeworks,Gyokay/Telerik-Academy-Homeworks,Gyokay/Telerik-Homeworks,Gyokay/Telerik-Academy-Homeworks | ---
+++
@@ -0,0 +1,9 @@
+function solve(argument) {
+ var n = parseInt(argument[0]);
+
+ if (n % 7 === 0 && n % 5 === 0) {
+ console.log("true " + n);
+ } else {
+ console.log("false " + n);
+ }
+} | |
f4b135a3897e708a6332aebc307cc0d6602cef3b | app/js/GameOfLife.js | app/js/GameOfLife.js | var GameOfLife = (function () {
var ALIVE = "alive", DEAD = "dead";
function Cell(initialState) {
var state = initialState || DEAD;
function getNumberOfAlive(neighbours) {
var nbAliveCells = 0;
neighbours.forEach(function (neighbor) {
if (neighbor.isAlive()) {
nbAliveCells += 1;
}
});
return nbAliveCells;
}
return {
calculateState: function (neighbours) {
var liveCellNumber = getNumberOfAlive(neighbours);
if (liveCellNumber < 2 || liveCellNumber > 3) {
state = DEAD;
}
if(liveCellNumber === 3) {
state = ALIVE;
}
},
isAlive: function () {
return state === ALIVE;
}
};
}
function AliveCell() {
return new Cell(ALIVE);
}
function DeadCell() {
return new Cell(DEAD);
}
return {
AliveCell: AliveCell,
DeadCell: DeadCell
};
})(); | Move game of life module to its own file | Move game of life module to its own file
| JavaScript | mit | velcrin/GameOfLife | ---
+++
@@ -0,0 +1,45 @@
+var GameOfLife = (function () {
+ var ALIVE = "alive", DEAD = "dead";
+
+ function Cell(initialState) {
+ var state = initialState || DEAD;
+
+ function getNumberOfAlive(neighbours) {
+ var nbAliveCells = 0;
+ neighbours.forEach(function (neighbor) {
+ if (neighbor.isAlive()) {
+ nbAliveCells += 1;
+ }
+ });
+ return nbAliveCells;
+ }
+
+ return {
+ calculateState: function (neighbours) {
+ var liveCellNumber = getNumberOfAlive(neighbours);
+ if (liveCellNumber < 2 || liveCellNumber > 3) {
+ state = DEAD;
+ }
+ if(liveCellNumber === 3) {
+ state = ALIVE;
+ }
+ },
+ isAlive: function () {
+ return state === ALIVE;
+ }
+ };
+ }
+
+ function AliveCell() {
+ return new Cell(ALIVE);
+ }
+
+ function DeadCell() {
+ return new Cell(DEAD);
+ }
+
+ return {
+ AliveCell: AliveCell,
+ DeadCell: DeadCell
+ };
+})(); | |
102429aa5b8f3c56f2aa64ab5cc09b4c6bb1e7de | src/components/PreviewPane.js | src/components/PreviewPane.js | import React, { PropTypes } from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import Widgets from './Widgets';
export default class PreviewPane extends React.Component {
previewFor(field) {
const { entry, getMedia } = this.props;
const widget = Widgets[field.get('widget')] || Widgets._unknown;
return React.createElement(widget.Preview, {
field: field,
value: entry.getIn(['data', field.get('name')]),
getMedia: getMedia,
});
}
render() {
const { collection } = this.props;
if (!collection) { return null; }
return <div>
{collection.get('fields').map((field) => <div key={field.get('name')}>{this.previewFor(field)}</div>)}
</div>;
}
}
PreviewPane.propTypes = {
collection: ImmutablePropTypes.map.isRequired,
entry: ImmutablePropTypes.map.isRequired,
getMedia: PropTypes.func.isRequired,
};
| import React, { PropTypes } from 'react';
import { render } from 'react-dom';
import ImmutablePropTypes from 'react-immutable-proptypes';
import Widgets from './Widgets';
class Preview extends React.Component {
previewFor(field) {
const { entry, getMedia } = this.props;
const widget = Widgets[field.get('widget')] || Widgets._unknown;
return React.createElement(widget.Preview, {
field: field,
value: entry.getIn(['data', field.get('name')]),
getMedia: getMedia,
});
}
render() {
const { collection } = this.props;
if (!collection) { return null; }
return <div>
{collection.get('fields').map((field) => <div key={field.get('name')}>{this.previewFor(field)}</div>)}
</div>;
}
}
export default class PreviewPane extends React.Component {
constructor(props) {
super(props);
this.handleIframeRef = this.handleIframeRef.bind(this);
}
componentDidUpdate() {
this.renderPreview();
}
renderPreview() {
const props = this.props;
render(<Preview {...props}/>, this.previewEl);
}
handleIframeRef(ref) {
if (ref) {
this.previewEl = document.createElement('div');
ref.contentDocument.body.appendChild(this.previewEl);
this.renderPreview();
}
}
render() {
const { collection } = this.props;
if (!collection) { return null; }
return <iframe style={{width: "100%", height: "100%", border: "none"}} ref={this.handleIframeRef}></iframe>
}
}
PreviewPane.propTypes = {
collection: ImmutablePropTypes.map.isRequired,
entry: ImmutablePropTypes.map.isRequired,
getMedia: PropTypes.func.isRequired,
};
| Make preview pane render to an iframe | Make preview pane render to an iframe
| JavaScript | mit | dopry/netlify-cms,netlify/netlify-cms,Aloomaio/netlify-cms,netlify/netlify-cms,Aloomaio/netlify-cms,netlify/netlify-cms,netlify/netlify-cms,dopry/netlify-cms | ---
+++
@@ -1,8 +1,9 @@
import React, { PropTypes } from 'react';
+import { render } from 'react-dom';
import ImmutablePropTypes from 'react-immutable-proptypes';
import Widgets from './Widgets';
-export default class PreviewPane extends React.Component {
+class Preview extends React.Component {
previewFor(field) {
const { entry, getMedia } = this.props;
const widget = Widgets[field.get('widget')] || Widgets._unknown;
@@ -17,10 +18,40 @@
const { collection } = this.props;
if (!collection) { return null; }
-
return <div>
{collection.get('fields').map((field) => <div key={field.get('name')}>{this.previewFor(field)}</div>)}
</div>;
+ }
+}
+
+export default class PreviewPane extends React.Component {
+ constructor(props) {
+ super(props);
+ this.handleIframeRef = this.handleIframeRef.bind(this);
+ }
+
+ componentDidUpdate() {
+ this.renderPreview();
+ }
+
+ renderPreview() {
+ const props = this.props;
+ render(<Preview {...props}/>, this.previewEl);
+ }
+
+ handleIframeRef(ref) {
+ if (ref) {
+ this.previewEl = document.createElement('div');
+ ref.contentDocument.body.appendChild(this.previewEl);
+ this.renderPreview();
+ }
+ }
+
+ render() {
+ const { collection } = this.props;
+ if (!collection) { return null; }
+
+ return <iframe style={{width: "100%", height: "100%", border: "none"}} ref={this.handleIframeRef}></iframe>
}
}
|
1a2b5a507dbfd75fdaf8630f6b29907d813c3bb9 | scripts/points-url-data-to-new-bucket.js | scripts/points-url-data-to-new-bucket.js | const promise = require("bluebird");
const options = {
// Initialization Options
promiseLib: promise, // use bluebird as promise library
capSQL: true, // when building SQL queries dynamically, capitalize SQL keywords
};
const pgp = require("pg-promise")(options);
const connectionString = process.env.DATABASE_URL;
const parse = require("pg-connection-string").parse;
const oldS3Url = 'uploads.participedia.xyz';
const newS3Url = 'participedia.stage';
let config;
try {
config = parse(connectionString);
if (process.env.NODE_ENV === "test" || config.host === "localhost") {
config.ssl = false;
} else {
config.ssl = true;
}
} catch (e) {
console.error("# Error parsing DATABASE_URL environment variable");
}
let db = pgp(config);
getPhotos('cases');
getPhotos('methods');
getPhotos('organizations');
function getPhotos(table) {
db.any(`SELECT id, photos FROM ${table}`)
.then(function(data) {
data.forEach(data => {
var photo = data.photos;
if (photo.search(oldS3Url) >= 0) {
var newPhoto = photo.replace(oldS3Url, newS3Url);
updatePhoto(data.id, newPhoto, table);
} else {
console.log(`Row ${data.id} doesn't have the URL we are looking for.`);
}
});
})
.catch(function(error) {
console.log(error);
});
}
function updatePhoto(id, value, table) {
const dataSingle = {photos: value};
const condition = pgp.as.format(` WHERE id = ${id}`, dataSingle);
const update = pgp.helpers.update(dataSingle, null, table) + condition;
db.none(update)
.then(function(data) {
console.log(`Table: ${table}; ID: ${id} updated`);
})
.catch(function(error) {
console.log(error);
});
} | Create a script to update old photo URL to new URL | Create a script to update old photo URL to new URL
| JavaScript | mit | participedia/api,participedia/api,participedia/api,participedia/api | ---
+++
@@ -0,0 +1,60 @@
+const promise = require("bluebird");
+const options = {
+ // Initialization Options
+ promiseLib: promise, // use bluebird as promise library
+ capSQL: true, // when building SQL queries dynamically, capitalize SQL keywords
+};
+const pgp = require("pg-promise")(options);
+const connectionString = process.env.DATABASE_URL;
+const parse = require("pg-connection-string").parse;
+const oldS3Url = 'uploads.participedia.xyz';
+const newS3Url = 'participedia.stage';
+
+let config;
+try {
+ config = parse(connectionString);
+ if (process.env.NODE_ENV === "test" || config.host === "localhost") {
+ config.ssl = false;
+ } else {
+ config.ssl = true;
+ }
+} catch (e) {
+ console.error("# Error parsing DATABASE_URL environment variable");
+}
+
+let db = pgp(config);
+getPhotos('cases');
+getPhotos('methods');
+getPhotos('organizations');
+
+function getPhotos(table) {
+ db.any(`SELECT id, photos FROM ${table}`)
+ .then(function(data) {
+ data.forEach(data => {
+ var photo = data.photos;
+ if (photo.search(oldS3Url) >= 0) {
+ var newPhoto = photo.replace(oldS3Url, newS3Url);
+ updatePhoto(data.id, newPhoto, table);
+ } else {
+ console.log(`Row ${data.id} doesn't have the URL we are looking for.`);
+ }
+ });
+ })
+ .catch(function(error) {
+ console.log(error);
+ });
+}
+
+function updatePhoto(id, value, table) {
+ const dataSingle = {photos: value};
+ const condition = pgp.as.format(` WHERE id = ${id}`, dataSingle);
+ const update = pgp.helpers.update(dataSingle, null, table) + condition;
+
+ db.none(update)
+ .then(function(data) {
+ console.log(`Table: ${table}; ID: ${id} updated`);
+ })
+ .catch(function(error) {
+ console.log(error);
+ });
+} | |
4ce36f3443a3385468fd6fde0ae9f27d54ea1d37 | spec/frontend/notes/stores/utils_spec.js | spec/frontend/notes/stores/utils_spec.js | import { hasQuickActions } from '~/notes/stores/utils';
describe('hasQuickActions', () => {
it.each`
input | expected
${'some comment'} | ${false}
${'/quickaction'} | ${true}
${'some comment with\n/quickaction'} | ${true}
`('returns $expected for $input', ({ input, expected }) => {
expect(hasQuickActions(input)).toBe(expected);
});
it('is stateless', () => {
expect(hasQuickActions('some comment')).toBe(hasQuickActions('some comment'));
expect(hasQuickActions('/quickaction')).toBe(hasQuickActions('/quickaction'));
});
});
| Add failing test for hasQuickActions | Add failing test for hasQuickActions
| JavaScript | mit | stoplightio/gitlabhq,stoplightio/gitlabhq,stoplightio/gitlabhq,mmkassem/gitlabhq,mmkassem/gitlabhq,mmkassem/gitlabhq,stoplightio/gitlabhq,mmkassem/gitlabhq | ---
+++
@@ -0,0 +1,17 @@
+import { hasQuickActions } from '~/notes/stores/utils';
+
+describe('hasQuickActions', () => {
+ it.each`
+ input | expected
+ ${'some comment'} | ${false}
+ ${'/quickaction'} | ${true}
+ ${'some comment with\n/quickaction'} | ${true}
+ `('returns $expected for $input', ({ input, expected }) => {
+ expect(hasQuickActions(input)).toBe(expected);
+ });
+
+ it('is stateless', () => {
+ expect(hasQuickActions('some comment')).toBe(hasQuickActions('some comment'));
+ expect(hasQuickActions('/quickaction')).toBe(hasQuickActions('/quickaction'));
+ });
+}); | |
fecd3b971f6536a7ef289640168d33d981ac5c66 | tests/commands/cenTests.js | tests/commands/cenTests.js | var cen = require("__buttercup/classes/commands/command.cen.js");
module.exports = {
setUp: function(cb) {
this.command = new cen();
(cb)();
},
errors: {
groupNotFoundThrowsError: function (test) {
var fakeSearching = {
findGroupByID: function (a, b) {
return false;
}
};
this.command.injectSearching(fakeSearching);
test.throws(function() {
this.command.execute({ }, 1, 1);
}.bind(this), 'Invalid group ID', 'An error was thrown when no group found');
test.done();
}
},
};
| Test error for cen command | Test error for cen command
| JavaScript | mit | buttercup/buttercup-core,buttercup/buttercup-core,buttercup/buttercup-core,perry-mitchell/buttercup-core,buttercup-pw/buttercup-core,perry-mitchell/buttercup-core,buttercup-pw/buttercup-core | ---
+++
@@ -0,0 +1,25 @@
+var cen = require("__buttercup/classes/commands/command.cen.js");
+
+module.exports = {
+ setUp: function(cb) {
+ this.command = new cen();
+ (cb)();
+ },
+
+ errors: {
+ groupNotFoundThrowsError: function (test) {
+ var fakeSearching = {
+ findGroupByID: function (a, b) {
+ return false;
+ }
+ };
+
+ this.command.injectSearching(fakeSearching);
+
+ test.throws(function() {
+ this.command.execute({ }, 1, 1);
+ }.bind(this), 'Invalid group ID', 'An error was thrown when no group found');
+ test.done();
+ }
+ },
+}; | |
ad3e5c3f9a4529819b26ebeef3ba2ec94eaecf83 | string-truncate.js | string-truncate.js | const stringTruncate = (str, lgt) => {
if (str.length > lgt) {
return str.substring(0, lgt) + "...";
}
return str;
};
stringTruncate("hello mortal world", 13);
| Truncate a string with a specific length | Truncate a string with a specific length
| JavaScript | mit | divyanshu-rawat/Basic-JS-Algorithms | ---
+++
@@ -0,0 +1,8 @@
+const stringTruncate = (str, lgt) => {
+ if (str.length > lgt) {
+ return str.substring(0, lgt) + "...";
+ }
+ return str;
+};
+
+stringTruncate("hello mortal world", 13); | |
7a45e111d37b899432e191e439f7c843e74b3455 | router.js | router.js | var Router = (function() {
var routes = [],
redirects = [];
/**
* Add a set of routes and their callbacks to the Router
* Params: alternating RegExp objects and functions are expected
*/
function setRoutes() {
if (arguments.length % 2 != 0) {
throw new Error("Even number of arguments required");
}
for (var i=0, len=arguments.length; i<len; i+=2) {
if (!(arguments[i] instanceof RegExp)) {
throw new Error("Expected a RegExp expression in odd position");
}
if (typeof arguments[i+1] !== "function") {
throw new Error("Expected a function in even position");
}
routes.push([arguments[i], arguments[i+1]]);
}
}
/**
* Add a set of routes and their redirect targets to the Router
* Params: alternating RegExp objects and strings are expected
*/
function setRedirects() {
if (arguments.length % 2 != 0) {
throw new Error("Even number of arguments required");
}
for (var i=0, len=arguments.length; i<len; i+=2) {
if (!(arguments[i] instanceof RegExp)) {
throw new Error("Expected a RegExp expression in odd position");
}
if (typeof arguments[i+1] !== "string") {
throw new Error("Expected url as string in even position");
}
redirects.push([arguments[i], arguments[i+1]]);
}
}
/**
* Navigate to a specific URL (hash, in fact)
*/
function navigate(url) {
window.location.hash = url;
}
/**
* Check if an URL matches routes or redirects
*/
function dispatch(url) {
/* First check routes */
for (var i=0, len=routes.length; i<len; i++) {
var exp = routes[i][0],
func = routes[i][1],
vals = url.match(exp);
if (vals) {
vals.shift();
func.apply(window, vals);
return;
}
}
/* Check redirects */
for (var i=0, len=redirects.length; i<len; i++) {
var exp = redirects[i][0],
target = redirects[i][1];
if (exp.test(url)) {
navigate(target);
return;
}
}
throw new Error("No matching routes or redirects!");
}
/**
* Convenience slot to call on "load" and "hashchange" events
*/
function urlUpdated() {
dispatch(window.location.hash);
}
/**
* Connect events to the dispatcher
*/
window.addEventListener("load", urlUpdated);
window.addEventListener("hashchange", urlUpdated);
/**
* Return a public API
*/
return {
"routes": setRoutes,
"redirects": setRedirects,
"navigate": navigate
}
})();
| Add initial version of routes.js | Add initial version of routes.js
| JavaScript | mit | AndreiDuma/router.js | ---
+++
@@ -0,0 +1,100 @@
+var Router = (function() {
+ var routes = [],
+ redirects = [];
+
+ /**
+ * Add a set of routes and their callbacks to the Router
+ * Params: alternating RegExp objects and functions are expected
+ */
+ function setRoutes() {
+ if (arguments.length % 2 != 0) {
+ throw new Error("Even number of arguments required");
+ }
+ for (var i=0, len=arguments.length; i<len; i+=2) {
+ if (!(arguments[i] instanceof RegExp)) {
+ throw new Error("Expected a RegExp expression in odd position");
+ }
+ if (typeof arguments[i+1] !== "function") {
+ throw new Error("Expected a function in even position");
+ }
+ routes.push([arguments[i], arguments[i+1]]);
+ }
+ }
+
+ /**
+ * Add a set of routes and their redirect targets to the Router
+ * Params: alternating RegExp objects and strings are expected
+ */
+ function setRedirects() {
+ if (arguments.length % 2 != 0) {
+ throw new Error("Even number of arguments required");
+ }
+ for (var i=0, len=arguments.length; i<len; i+=2) {
+ if (!(arguments[i] instanceof RegExp)) {
+ throw new Error("Expected a RegExp expression in odd position");
+ }
+ if (typeof arguments[i+1] !== "string") {
+ throw new Error("Expected url as string in even position");
+ }
+ redirects.push([arguments[i], arguments[i+1]]);
+ }
+ }
+
+ /**
+ * Navigate to a specific URL (hash, in fact)
+ */
+ function navigate(url) {
+ window.location.hash = url;
+ }
+
+ /**
+ * Check if an URL matches routes or redirects
+ */
+ function dispatch(url) {
+ /* First check routes */
+ for (var i=0, len=routes.length; i<len; i++) {
+ var exp = routes[i][0],
+ func = routes[i][1],
+ vals = url.match(exp);
+
+ if (vals) {
+ vals.shift();
+ func.apply(window, vals);
+ return;
+ }
+ }
+ /* Check redirects */
+ for (var i=0, len=redirects.length; i<len; i++) {
+ var exp = redirects[i][0],
+ target = redirects[i][1];
+
+ if (exp.test(url)) {
+ navigate(target);
+ return;
+ }
+ }
+ throw new Error("No matching routes or redirects!");
+ }
+
+ /**
+ * Convenience slot to call on "load" and "hashchange" events
+ */
+ function urlUpdated() {
+ dispatch(window.location.hash);
+ }
+
+ /**
+ * Connect events to the dispatcher
+ */
+ window.addEventListener("load", urlUpdated);
+ window.addEventListener("hashchange", urlUpdated);
+
+ /**
+ * Return a public API
+ */
+ return {
+ "routes": setRoutes,
+ "redirects": setRedirects,
+ "navigate": navigate
+ }
+})(); | |
cb14823f8fb538a662e7220740aa46af93b36bc1 | replaceHtml.js | replaceHtml.js | function replaceHtml(htmlString, hashObject) {
const filesArray = Object.keys(hashObject)
let newHtmlString = htmlString
function replaceSrc(file) {
const srcAttributeDblQuote = `src="${file}"`
const srcAttributeSingQuote = `src='${file}'`
const hash = hashObject[file]
const classAttribute = `class='${hash}'`
while (newHtmlString.includes(srcAttributeDblQuote)) {
newHtmlString = newHtmlString.replace(srcAttributeDblQuote, classAttribute)
}
while (newHtmlString.includes(srcAttributeSingQuote)) {
newHtmlString = newHtmlString.replace(srcAttributeSingQuote, classAttribute)
}
}
filesArray.forEach(replaceSrc)
return newHtmlString
}
module.exports = replaceHtml | Replace src in html with class=hash | Replace src in html with class=hash
| JavaScript | mit | CarolAG/WebFlight,coryc5/WebFlight | ---
+++
@@ -0,0 +1,24 @@
+function replaceHtml(htmlString, hashObject) {
+ const filesArray = Object.keys(hashObject)
+ let newHtmlString = htmlString
+
+ function replaceSrc(file) {
+ const srcAttributeDblQuote = `src="${file}"`
+ const srcAttributeSingQuote = `src='${file}'`
+ const hash = hashObject[file]
+ const classAttribute = `class='${hash}'`
+
+ while (newHtmlString.includes(srcAttributeDblQuote)) {
+ newHtmlString = newHtmlString.replace(srcAttributeDblQuote, classAttribute)
+ }
+ while (newHtmlString.includes(srcAttributeSingQuote)) {
+ newHtmlString = newHtmlString.replace(srcAttributeSingQuote, classAttribute)
+ }
+ }
+
+ filesArray.forEach(replaceSrc)
+
+ return newHtmlString
+}
+
+module.exports = replaceHtml | |
e308516a1407f64f9642fadf0ca51707340a56bc | test/bin.js | test/bin.js | var expect = require('chai').expect;
var fs = require("fs");
var exec = require('child_process').exec;
describe('Smoke test for the executable script', function () {
beforeEach(function () {
fs.writeFileSync(
"test/test-data.js",
'var foo = 10;\n' +
'[1, 2, 3].map(function(x) { return x*x });'
);
});
afterEach(function () {
fs.unlinkSync("test/test-data.js");
if (fs.existsSync("test/output.js")) {
fs.unlinkSync("test/output.js");
}
});
describe('when valid input and output file given', function() {
it('transforms input file to output file', function (done) {
exec('node ./bin/index.js test/test-data.js -o test/output.js', function (error, stdout, stderr) {
expect(error).to.equal(null);
expect(stderr).to.equal('');
expect(stdout).to.equal('The file "test/output.js" has been written.\n');
expect(fs.readFileSync('test/output.js').toString()).to.equal(
'const foo = 10;\n' +
'[1, 2, 3].map(x => x*x);'
);
done();
});
});
});
describe('when no input file given', function () {
it('exits with error message', function (done) {
exec('node ./bin/index.js', function (error, stdout, stderr) {
expect(error).not.to.equal(null);
expect(stderr).to.equal('Input file name is required.\n');
expect(stdout).to.equal('');
expect(fs.existsSync('test/output.js')).to.equal(false);
done();
});
});
});
});
| Add smoke test for running the executable script | Add smoke test for running the executable script
It's slow, but we only need a few of these just to ensure that
everything has been wired together correctly.
| JavaScript | mit | lebab/lebab,mohebifar/xto6,mohebifar/lebab | ---
+++
@@ -0,0 +1,50 @@
+var expect = require('chai').expect;
+var fs = require("fs");
+var exec = require('child_process').exec;
+
+describe('Smoke test for the executable script', function () {
+ beforeEach(function () {
+ fs.writeFileSync(
+ "test/test-data.js",
+ 'var foo = 10;\n' +
+ '[1, 2, 3].map(function(x) { return x*x });'
+ );
+ });
+
+ afterEach(function () {
+ fs.unlinkSync("test/test-data.js");
+ if (fs.existsSync("test/output.js")) {
+ fs.unlinkSync("test/output.js");
+ }
+ });
+
+ describe('when valid input and output file given', function() {
+ it('transforms input file to output file', function (done) {
+ exec('node ./bin/index.js test/test-data.js -o test/output.js', function (error, stdout, stderr) {
+ expect(error).to.equal(null);
+ expect(stderr).to.equal('');
+ expect(stdout).to.equal('The file "test/output.js" has been written.\n');
+
+ expect(fs.readFileSync('test/output.js').toString()).to.equal(
+ 'const foo = 10;\n' +
+ '[1, 2, 3].map(x => x*x);'
+ );
+ done();
+ });
+ });
+ });
+
+ describe('when no input file given', function () {
+ it('exits with error message', function (done) {
+ exec('node ./bin/index.js', function (error, stdout, stderr) {
+ expect(error).not.to.equal(null);
+ expect(stderr).to.equal('Input file name is required.\n');
+ expect(stdout).to.equal('');
+
+ expect(fs.existsSync('test/output.js')).to.equal(false);
+ done();
+ });
+ });
+ });
+
+}); | |
fa12c52231dd91e2485433cbd9df2161b8839c7a | migrations/3_deploy_crowdsale_contract.js | migrations/3_deploy_crowdsale_contract.js | var NeufundTestToken = artifacts.require("./NeufundTestToken.sol");
var Crowdsale = artifacts.require("./Crowdsale.sol");
module.exports = function (deployer) {
/**
* address ifSuccessfulSendTo,
* uint fundingGoalInEthers,
* uint durationInMinutes,
* uint etherCostOfEachToken,
* Token addressOfTokenUsedAsReward
*/
NeufundTestToken.deployed().then((instance)=> {
console.log(instance.address);
var ifSuccessfulSendTo = "0xb67fb67eb9e4700c90f2ab65c8ecbb3b687d49c7";
var fundingGoalInEthers = 1;
var durationInMinutes = 1;
var etherCostOfEachToken = 1;
var addressOfTokenUsedAsReward = instance.address;
deployer.deploy(Crowdsale,
ifSuccessfulSendTo,
fundingGoalInEthers,
durationInMinutes,
etherCostOfEachToken,
addressOfTokenUsedAsReward);
});
};
| Add migration for a crowdsale contract | Add migration for a crowdsale contract
| JavaScript | mit | Neufund/Contracts | ---
+++
@@ -0,0 +1,26 @@
+var NeufundTestToken = artifacts.require("./NeufundTestToken.sol");
+var Crowdsale = artifacts.require("./Crowdsale.sol");
+
+module.exports = function (deployer) {
+ /**
+ * address ifSuccessfulSendTo,
+ * uint fundingGoalInEthers,
+ * uint durationInMinutes,
+ * uint etherCostOfEachToken,
+ * Token addressOfTokenUsedAsReward
+ */
+ NeufundTestToken.deployed().then((instance)=> {
+ console.log(instance.address);
+ var ifSuccessfulSendTo = "0xb67fb67eb9e4700c90f2ab65c8ecbb3b687d49c7";
+ var fundingGoalInEthers = 1;
+ var durationInMinutes = 1;
+ var etherCostOfEachToken = 1;
+ var addressOfTokenUsedAsReward = instance.address;
+ deployer.deploy(Crowdsale,
+ ifSuccessfulSendTo,
+ fundingGoalInEthers,
+ durationInMinutes,
+ etherCostOfEachToken,
+ addressOfTokenUsedAsReward);
+ });
+}; | |
adf64a16d81e5c2968b4d572d9cb649b48d92910 | scripts/mocha.js | scripts/mocha.js | var system = require('system')
, webpage = require('webpage');
var page = webpage.create()
, passes = 0
, failures = 0
, total;
page.onAlert = function(msg) {
var a = JSON.parse(msg)
switch(a.event) {
case 'start':
total = a.params.total;
break;
case 'pass':
console.log('[ ok ] ' + a.params.title)
passes++;
break;
case 'fail':
console.log('[ FAIL ] ' + a.params.title)
failures++;
break;
case 'end':
console.log('');
if (failures) {
console.log(failures + ' of ' + total + ' tests failed');
phantom.exit(-1);
} else {
console.log(total + ' tests complete');
phantom.exit();
}
break;
}
}
page.onConsoleMessage = function(msg) {
console.log(msg);
};
page.onError = function(msg, trace) {
console.log(msg);
trace.forEach(function(item) {
console.log(' at ' + (item.function || '<anonymous>') + ' (' + item.file + ':' + item.line + ')');
})
phantom.exit(-1);
}
if (system.args.length === 1) {
console.log('Usage: ' + system.args[0] + ' page.html');
phantom.exit(-1);
} else {
var file = system.args[1];
page.open(file, function (status) {
if (status !== 'success') {
console.log('Failed to load file: ' + file);
phantom.exit(-1);
} else {
// tests will be run, with events delivered from the PhantomJS reporter
// to page.onAlert
}
});
}
| Add PhantomJS script to report test results. | Add PhantomJS script to report test results.
| JavaScript | mit | jaredhanson/phantomjs-mocha | ---
+++
@@ -0,0 +1,62 @@
+var system = require('system')
+ , webpage = require('webpage');
+
+var page = webpage.create()
+ , passes = 0
+ , failures = 0
+ , total;
+
+page.onAlert = function(msg) {
+ var a = JSON.parse(msg)
+ switch(a.event) {
+ case 'start':
+ total = a.params.total;
+ break;
+ case 'pass':
+ console.log('[ ok ] ' + a.params.title)
+ passes++;
+ break;
+ case 'fail':
+ console.log('[ FAIL ] ' + a.params.title)
+ failures++;
+ break;
+ case 'end':
+ console.log('');
+ if (failures) {
+ console.log(failures + ' of ' + total + ' tests failed');
+ phantom.exit(-1);
+ } else {
+ console.log(total + ' tests complete');
+ phantom.exit();
+ }
+ break;
+ }
+}
+
+page.onConsoleMessage = function(msg) {
+ console.log(msg);
+};
+
+page.onError = function(msg, trace) {
+ console.log(msg);
+ trace.forEach(function(item) {
+ console.log(' at ' + (item.function || '<anonymous>') + ' (' + item.file + ':' + item.line + ')');
+ })
+ phantom.exit(-1);
+}
+
+if (system.args.length === 1) {
+ console.log('Usage: ' + system.args[0] + ' page.html');
+ phantom.exit(-1);
+} else {
+ var file = system.args[1];
+ page.open(file, function (status) {
+ if (status !== 'success') {
+ console.log('Failed to load file: ' + file);
+ phantom.exit(-1);
+ } else {
+ // tests will be run, with events delivered from the PhantomJS reporter
+ // to page.onAlert
+ }
+ });
+} | |
4b051356414093bcee39a46d0ab727261e6d4a54 | maintenance/recompute-indexed-geometry.js | maintenance/recompute-indexed-geometry.js | #!/usr/bin/env node
/*jslint node: true */
/*
* Compute a new indexedGeometry field for every Response document.
* We should run this if we significantly change our algorithm for computing
* the indexedGeometry field.
*
* Usage:
* $ envrun -e my-deployment.env --path recompute-indexed-geometry.js
*
* Or run on Heroku to mitigate network latency.
*/
'use strict';
var _ = require('lodash');
var async = require('async');
var mongo = require('../lib/mongo');
var Response = require('../lib/models/Response');
var db;
function log(data) {
if (Object.prototype.toString.call(data) === '[object Error]' ||
(data.name && data.message)) {
console.log('Error: ' + data.name + '. ' + data.message);
console.log(data);
console.log(data.stack);
if (Object.prototype.toString.call(data.errors) === '[object Array]') {
data.errors.forEach(log);
} else if (data.errors) {
log(data.errors);
}
return;
}
console.log(Object.keys(data).map(function (key) {
return key + '=' + data[key];
}).join(' '));
}
var count = 0;
function task(doc, done) {
var geom = Response.createIndexedGeometry(doc.geometry);
Response.update({ _id: doc._id}, {
$set: {
indexedGeometry: geom
}
}, function (error) {
count += 1;
if (count % 100 === 0) {
process.stdout.write('\rProcessed ' + count + ' documents.');
}
done(error);
});
}
function run(done) {
var stream = Response.find({})
.select({ geometry: 1 })
.snapshot()
.lean()
.stream();
var queue = async.queue(task, 20);
queue.saturated = function () {
stream.pause();
};
queue.empty = function () {
stream.resume();
};
stream.on('data', function (doc) {
queue.push(doc);
})
.on('error', done)
.on('close', function () {
queue.drain = function () {
process.stdout.write('\rProcessed ' + count + ' documents.');
console.log('\nDone.');
done();
};
});
}
db = mongo.connect(function () {
run(function (error) {
if (error) { log(error); }
db.close();
});
});
db.on('error', log);
| Add maintenance script for recomputing indexed geometries | Add maintenance script for recomputing indexed geometries
| JavaScript | bsd-3-clause | LocalData/localdata-api,LocalData/localdata-api,LocalData/localdata-api | ---
+++
@@ -0,0 +1,95 @@
+#!/usr/bin/env node
+/*jslint node: true */
+
+/*
+ * Compute a new indexedGeometry field for every Response document.
+ * We should run this if we significantly change our algorithm for computing
+ * the indexedGeometry field.
+ *
+ * Usage:
+ * $ envrun -e my-deployment.env --path recompute-indexed-geometry.js
+ *
+ * Or run on Heroku to mitigate network latency.
+ */
+'use strict';
+
+var _ = require('lodash');
+var async = require('async');
+
+var mongo = require('../lib/mongo');
+var Response = require('../lib/models/Response');
+
+var db;
+
+function log(data) {
+ if (Object.prototype.toString.call(data) === '[object Error]' ||
+ (data.name && data.message)) {
+ console.log('Error: ' + data.name + '. ' + data.message);
+ console.log(data);
+ console.log(data.stack);
+ if (Object.prototype.toString.call(data.errors) === '[object Array]') {
+ data.errors.forEach(log);
+ } else if (data.errors) {
+ log(data.errors);
+ }
+ return;
+ }
+ console.log(Object.keys(data).map(function (key) {
+ return key + '=' + data[key];
+ }).join(' '));
+}
+
+var count = 0;
+function task(doc, done) {
+ var geom = Response.createIndexedGeometry(doc.geometry);
+ Response.update({ _id: doc._id}, {
+ $set: {
+ indexedGeometry: geom
+ }
+ }, function (error) {
+ count += 1;
+ if (count % 100 === 0) {
+ process.stdout.write('\rProcessed ' + count + ' documents.');
+ }
+ done(error);
+ });
+}
+
+function run(done) {
+ var stream = Response.find({})
+ .select({ geometry: 1 })
+ .snapshot()
+ .lean()
+ .stream();
+
+ var queue = async.queue(task, 20);
+
+ queue.saturated = function () {
+ stream.pause();
+ };
+
+ queue.empty = function () {
+ stream.resume();
+ };
+
+ stream.on('data', function (doc) {
+ queue.push(doc);
+ })
+ .on('error', done)
+ .on('close', function () {
+ queue.drain = function () {
+ process.stdout.write('\rProcessed ' + count + ' documents.');
+ console.log('\nDone.');
+ done();
+ };
+ });
+}
+
+db = mongo.connect(function () {
+ run(function (error) {
+ if (error) { log(error); }
+ db.close();
+ });
+});
+
+db.on('error', log); | |
b395f02cf30a64bd21af14bfd0883467962b4902 | 16/sharp-toFormat.js | 16/sharp-toFormat.js | var sharp = require('sharp');
var dirpath = 'images/';
var imgname = 'download-logo.png';
var tmppath = 'tmp/'
sharp(dirpath + imgname)
.jpeg()
.toFile(tmppath + 'New_' + 'output.jpeg', function (err, info) {
if (err)
throw err;
console.log('done');
});
sharp(dirpath + imgname)
.webp()
.toFile(tmppath + 'New_' + 'output.webp', function (err, info) {
if (err)
throw err;
console.log('done');
}); | Add the example to change format of image via sharp. | Add the example to change format of image via sharp.
| JavaScript | mit | nicebook/Node.js-Reference,nicebook/Node.js-Reference,nicebook/Node.js-Reference | ---
+++
@@ -0,0 +1,21 @@
+var sharp = require('sharp');
+
+var dirpath = 'images/';
+var imgname = 'download-logo.png';
+var tmppath = 'tmp/'
+
+sharp(dirpath + imgname)
+ .jpeg()
+ .toFile(tmppath + 'New_' + 'output.jpeg', function (err, info) {
+ if (err)
+ throw err;
+ console.log('done');
+ });
+
+sharp(dirpath + imgname)
+ .webp()
+ .toFile(tmppath + 'New_' + 'output.webp', function (err, info) {
+ if (err)
+ throw err;
+ console.log('done');
+ }); | |
f9c48d88a67fed97610ba82106df668abca53698 | scripts/opendata_manual_update.js | scripts/opendata_manual_update.js | 'use strict';
const co = require('co');
const logger = require('../modules').logger;
const mongooseHelper = require('../modules').mongooseHelper;
const opendata = require('../worker').opendata;
const rollbarHelper = require('../modules').rollbarHelper;
mongooseHelper.connect()
.then(() => rollbarHelper.init())
.then(() => {
logger.info('[SCRIPT.opendata_manual_update] Updating Paris...');
return co(opendata.paris.update);
})
.then(() => {
logger.info('[SCRIPT.opendata_manual_update] Ended');
process.exit(0);
})
.catch(err => {
logger.error(err, '[SCRIPT.opendata_manual_update] Uncaught error');
rollbarHelper.rollbar.handleError(err, '[SCRIPT.opendata_manual_update] Uncaught exception');
process.exit(1);
});
| Add script to execute manually to update parkings | Add script to execute manually to update parkings
| JavaScript | mit | carparker/carparker-server | ---
+++
@@ -0,0 +1,23 @@
+'use strict';
+
+const co = require('co');
+const logger = require('../modules').logger;
+const mongooseHelper = require('../modules').mongooseHelper;
+const opendata = require('../worker').opendata;
+const rollbarHelper = require('../modules').rollbarHelper;
+
+mongooseHelper.connect()
+ .then(() => rollbarHelper.init())
+ .then(() => {
+ logger.info('[SCRIPT.opendata_manual_update] Updating Paris...');
+ return co(opendata.paris.update);
+ })
+ .then(() => {
+ logger.info('[SCRIPT.opendata_manual_update] Ended');
+ process.exit(0);
+ })
+ .catch(err => {
+ logger.error(err, '[SCRIPT.opendata_manual_update] Uncaught error');
+ rollbarHelper.rollbar.handleError(err, '[SCRIPT.opendata_manual_update] Uncaught exception');
+ process.exit(1);
+ }); | |
2f234f6ce007a625382f597af0cd017d8ca044ac | server/startup/migrations/v095.js | server/startup/migrations/v095.js | RocketChat.Migrations.add({
version: 95,
up() {
if (RocketChat && RocketChat.models && RocketChat.models.Settings) {
const emailHeader = RocketChat.models.Settings.findOne({ _id: 'Email_Header' });
const emailFooter = RocketChat.models.Settings.findOne({ _id: 'Email_Footer' });
const startWithHTML = emailHeader.value.match(/^<html>/);
const endsWithHTML = emailFooter.value.match(/<\/hmtl>$/);
if (!startWithHTML) {
RocketChat.models.Settings.update(
{ _id: 'Email_Header' },
{ $set: { value: `<html>${ emailHeader.value }`} }
);
}
if (!endsWithHTML) {
RocketChat.models.Settings.update(
{ _id: 'Email_Footer' },
{ $set: { value: `${ emailFooter.value }</hmtl>`} }
);
}
}
}
});
| Add <html> tags to email header and footer | Add <html> tags to email header and footer
| JavaScript | mit | mrinaldhar/Rocket.Chat,fatihwk/Rocket.Chat,mrsimpson/Rocket.Chat,galrotem1993/Rocket.Chat,inoio/Rocket.Chat,danielbressan/Rocket.Chat,k0nsl/Rocket.Chat,Sing-Li/Rocket.Chat,4thParty/Rocket.Chat,cnash/Rocket.Chat,4thParty/Rocket.Chat,k0nsl/Rocket.Chat,Sing-Li/Rocket.Chat,4thParty/Rocket.Chat,nishimaki10/Rocket.Chat,VoiSmart/Rocket.Chat,pitamar/Rocket.Chat,Achaikos/Rocket.Chat,pitamar/Rocket.Chat,subesokun/Rocket.Chat,flaviogrossi/Rocket.Chat,Sing-Li/Rocket.Chat,fatihwk/Rocket.Chat,subesokun/Rocket.Chat,danielbressan/Rocket.Chat,trt15-ssci-organization/Rocket.Chat,pkgodara/Rocket.Chat,danielbressan/Rocket.Chat,Achaikos/Rocket.Chat,mrsimpson/Rocket.Chat,galrotem1993/Rocket.Chat,k0nsl/Rocket.Chat,pachox/Rocket.Chat,k0nsl/Rocket.Chat,fatihwk/Rocket.Chat,mrsimpson/Rocket.Chat,pkgodara/Rocket.Chat,Kiran-Rao/Rocket.Chat,Kiran-Rao/Rocket.Chat,Kiran-Rao/Rocket.Chat,VoiSmart/Rocket.Chat,danielbressan/Rocket.Chat,cnash/Rocket.Chat,fatihwk/Rocket.Chat,nishimaki10/Rocket.Chat,4thParty/Rocket.Chat,Achaikos/Rocket.Chat,Sing-Li/Rocket.Chat,trt15-ssci-organization/Rocket.Chat,pkgodara/Rocket.Chat,trt15-ssci-organization/Rocket.Chat,mrinaldhar/Rocket.Chat,flaviogrossi/Rocket.Chat,nishimaki10/Rocket.Chat,nishimaki10/Rocket.Chat,galrotem1993/Rocket.Chat,galrotem1993/Rocket.Chat,pachox/Rocket.Chat,flaviogrossi/Rocket.Chat,inoio/Rocket.Chat,pitamar/Rocket.Chat,inoio/Rocket.Chat,pitamar/Rocket.Chat,pachox/Rocket.Chat,subesokun/Rocket.Chat,cnash/Rocket.Chat,VoiSmart/Rocket.Chat,mrsimpson/Rocket.Chat,pkgodara/Rocket.Chat,Kiran-Rao/Rocket.Chat,mrinaldhar/Rocket.Chat,mrinaldhar/Rocket.Chat,trt15-ssci-organization/Rocket.Chat,cnash/Rocket.Chat,Achaikos/Rocket.Chat,subesokun/Rocket.Chat,pachox/Rocket.Chat,flaviogrossi/Rocket.Chat | ---
+++
@@ -0,0 +1,25 @@
+RocketChat.Migrations.add({
+ version: 95,
+ up() {
+ if (RocketChat && RocketChat.models && RocketChat.models.Settings) {
+ const emailHeader = RocketChat.models.Settings.findOne({ _id: 'Email_Header' });
+ const emailFooter = RocketChat.models.Settings.findOne({ _id: 'Email_Footer' });
+ const startWithHTML = emailHeader.value.match(/^<html>/);
+ const endsWithHTML = emailFooter.value.match(/<\/hmtl>$/);
+
+ if (!startWithHTML) {
+ RocketChat.models.Settings.update(
+ { _id: 'Email_Header' },
+ { $set: { value: `<html>${ emailHeader.value }`} }
+ );
+ }
+
+ if (!endsWithHTML) {
+ RocketChat.models.Settings.update(
+ { _id: 'Email_Footer' },
+ { $set: { value: `${ emailFooter.value }</hmtl>`} }
+ );
+ }
+ }
+ }
+}); | |
73a91ee247e43d67fb586b5b0c7b8e2694c14345 | src/modules/gallery-lazy-load.js | src/modules/gallery-lazy-load.js | import axios from 'axios';
function Loader(options = {}) {
this.page = options.page || 0;
this.limit = options.limit || 1;
this.url = options.url || '';
this.nextPage = () => {
this.page += 1;
return axios.get(this.url, {
params: {
page: this.page,
limit: this.limit,
},
responseType: 'text',
});
};
}
function observeLastPost(observer) {
const posts = document.querySelectorAll('.gallery-post');
const lastPost = posts[posts.length - 1];
observer.observe(lastPost);
return lastPost;
}
export default (options) => {
let observer;
const galleryContainer = document.querySelector('.gallery-posts');
const loader = new Loader({
url: '/api/gallery',
page: 2,
limit: 1,
});
const handler = (entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
observer.unobserve(entry.target);
loader.nextPage()
.then(({ data: postHtml }) => {
galleryContainer.insertAdjacentHTML('beforeend', postHtml);
const lastPost = observeLastPost(observer);
if (options.afterInsert && typeof options.afterInsert === 'function') {
options.afterInsert(lastPost);
}
}).catch(() => {
// No more posts
});
}
});
};
observer = new IntersectionObserver(handler, {
threshold: 0,
});
observeLastPost(observer);
}
| Add lazy loader client script | Add lazy loader client script
| JavaScript | mit | tuelsch/bolg,tuelsch/bolg | ---
+++
@@ -0,0 +1,59 @@
+import axios from 'axios';
+
+function Loader(options = {}) {
+ this.page = options.page || 0;
+ this.limit = options.limit || 1;
+ this.url = options.url || '';
+
+ this.nextPage = () => {
+ this.page += 1;
+ return axios.get(this.url, {
+ params: {
+ page: this.page,
+ limit: this.limit,
+ },
+ responseType: 'text',
+ });
+ };
+}
+
+function observeLastPost(observer) {
+ const posts = document.querySelectorAll('.gallery-post');
+ const lastPost = posts[posts.length - 1];
+ observer.observe(lastPost);
+ return lastPost;
+}
+
+export default (options) => {
+ let observer;
+ const galleryContainer = document.querySelector('.gallery-posts');
+ const loader = new Loader({
+ url: '/api/gallery',
+ page: 2,
+ limit: 1,
+ });
+
+ const handler = (entries) => {
+ entries.forEach((entry) => {
+ if (entry.isIntersecting) {
+ observer.unobserve(entry.target);
+ loader.nextPage()
+ .then(({ data: postHtml }) => {
+ galleryContainer.insertAdjacentHTML('beforeend', postHtml);
+ const lastPost = observeLastPost(observer);
+ if (options.afterInsert && typeof options.afterInsert === 'function') {
+ options.afterInsert(lastPost);
+ }
+ }).catch(() => {
+ // No more posts
+ });
+ }
+ });
+ };
+
+ observer = new IntersectionObserver(handler, {
+ threshold: 0,
+ });
+
+ observeLastPost(observer);
+} | |
9f495fe9c7edb89cdf9226007715b55a6f5fb15f | tests/record.js | tests/record.js | var expect = require('chai').expect,
models = require('../models'),
Record = require('../models/record'),
connection = require('../lib/datastore').connection;
describe('Record retrieved from database', function () {
var wantid
var rec;
before(function (done) {
connection.query('SELECT id FROM records LIMIT 1', function (err, results, fields) {
wantid = results[0].id;
rec = new Record(wantid);
rec.with(function (val) {
rec = val;
done();
});
});
});
it('has desired id', function () {
expect(rec.id).to.equal(wantid);
});
it('has data', function () {
expect(rec.data).to.exist;
});
});
| Add simple unit test for Record model | Add simple unit test for Record model
| JavaScript | agpl-3.0 | jcamins/biblionarrator,jcamins/biblionarrator | ---
+++
@@ -0,0 +1,25 @@
+var expect = require('chai').expect,
+ models = require('../models'),
+ Record = require('../models/record'),
+ connection = require('../lib/datastore').connection;
+
+describe('Record retrieved from database', function () {
+ var wantid
+ var rec;
+ before(function (done) {
+ connection.query('SELECT id FROM records LIMIT 1', function (err, results, fields) {
+ wantid = results[0].id;
+ rec = new Record(wantid);
+ rec.with(function (val) {
+ rec = val;
+ done();
+ });
+ });
+ });
+ it('has desired id', function () {
+ expect(rec.id).to.equal(wantid);
+ });
+ it('has data', function () {
+ expect(rec.data).to.exist;
+ });
+}); | |
05131a5eaf5c4bdab431a8de4d86f3ce726fc7e4 | server/labyrinthdb.js | server/labyrinthdb.js | 'use strict';
var r = require('rethinkdb');
export class LabyrinthDB {
constructor (conn, dbName) {
this.conn = conn;
this.dbName = dbName;
this.tableList = ['chat'];
this.checkDB();
}
checkDB () {
const _this = this;
r.dbList().run(this.conn, function (err, dbList) {
if (err) throw err;
if (!dbList.find(function (e) {
return e === _this.dbName
})) _this.createDB();
});
}
createDB () {
const _this = this;
r.dbCreate(this.dbName).run(this.conn, function (err, res) {
if (err) throw err;
_this.tableList.forEach(function (tableName) {
_this.createTable(tableName);
});
});
}
createTable (tableName) {
r.db(this.dbName).tableCreate(tableName).run(this.conn, function (err, res) {
if (err) throw err;
});
}
}
| Add first prototype of LabyrinthDB. | Add first prototype of LabyrinthDB.
| JavaScript | mit | nobus/Labyrinth,nobus/Labyrinth | ---
+++
@@ -0,0 +1,46 @@
+'use strict';
+
+var r = require('rethinkdb');
+
+
+export class LabyrinthDB {
+ constructor (conn, dbName) {
+ this.conn = conn;
+ this.dbName = dbName;
+
+ this.tableList = ['chat'];
+
+ this.checkDB();
+ }
+
+ checkDB () {
+ const _this = this;
+
+ r.dbList().run(this.conn, function (err, dbList) {
+ if (err) throw err;
+
+ if (!dbList.find(function (e) {
+ return e === _this.dbName
+ })) _this.createDB();
+ });
+ }
+
+ createDB () {
+ const _this = this;
+
+ r.dbCreate(this.dbName).run(this.conn, function (err, res) {
+ if (err) throw err;
+
+ _this.tableList.forEach(function (tableName) {
+ _this.createTable(tableName);
+ });
+
+ });
+ }
+
+ createTable (tableName) {
+ r.db(this.dbName).tableCreate(tableName).run(this.conn, function (err, res) {
+ if (err) throw err;
+ });
+ }
+} | |
e8bebebe19e64d664069f23e534b173ca50e4d2f | ui/src/status/apis/index.js | ui/src/status/apis/index.js | import {get} from 'utils/ajax'
export const getJSONFeed = url => get(url)
| import {get} from 'utils/ajax'
import {fixtureJSONFeed} from 'src/status/fixtures'
// TODO: remove async/await & object return, uncomment get(url) when proxy route implemented
export const getJSONFeed = async url => {
return await {data: fixtureJSONFeed}
// get(url)
}
| Return fixture data until json feed proxy implemented | Return fixture data until json feed proxy implemented
| JavaScript | mit | li-ang/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,nooproblem/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,influxdb/influxdb,li-ang/influxdb,influxdb/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,influxdata/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,nooproblem/influxdb,influxdata/influxdb | ---
+++
@@ -1,3 +1,8 @@
import {get} from 'utils/ajax'
-export const getJSONFeed = url => get(url)
+import {fixtureJSONFeed} from 'src/status/fixtures'
+// TODO: remove async/await & object return, uncomment get(url) when proxy route implemented
+export const getJSONFeed = async url => {
+ return await {data: fixtureJSONFeed}
+ // get(url)
+} |
d2b27174c997b0bda5836ade508511fd3a21c9cf | js/api-server.js | js/api-server.js | var lightResource,
sensor = require( "./mock-sensor" )(),
iotivity = require( "iotivity" ),
device = iotivity.OicDevice(),
settings = {
role: "server",
connectionMode: "acked",
info: {
uuid: "INTEL"
}
};
device.configure( settings );
sensor.on( "change", function( newData ) {
var index,
updates = [];
if ( !lightResource ) {
return;
}
for ( index in newData ) {
if ( newData[ index ] !== lightResource.properties[ index ] ) {
lightResource.properties[ index ] = newData[ index ];
updates.push( index );
}
}
if ( updates.length > 0 ) {
device._server.notify( lightResource.id, "update", updates );
}
} );
if ( device._settings.info.uuid ) {
device._server.registerResource( {
url: "/light/ambience/blue",
deviceId: device._settings.info.uuid,
connectionMode: device._settings.connectionMode,
resourceTypes: [ "Light" ],
interfaces: [ "/oic/if/rw" ],
discoverable: true,
observable: true,
properties: { someValue: 0, someOtherValue: "Helsinki" }
} ).then(
function( resource ) {
lightResource = resource;
},
function( error ) {
throw error;
} );
}
| Add API observable server example | Examples: Add API observable server example
| JavaScript | mit | zqzhang/iotivity-node,zolkis/iotivity-node,zqzhang/iotivity-node,zolkis/iotivity-node,zqzhang/iotivity-node,zolkis/iotivity-node,zqzhang/iotivity-node,zolkis/iotivity-node,zolkis/iotivity-node,zqzhang/iotivity-node | ---
+++
@@ -0,0 +1,51 @@
+var lightResource,
+ sensor = require( "./mock-sensor" )(),
+ iotivity = require( "iotivity" ),
+ device = iotivity.OicDevice(),
+ settings = {
+ role: "server",
+ connectionMode: "acked",
+ info: {
+ uuid: "INTEL"
+ }
+ };
+
+device.configure( settings );
+
+sensor.on( "change", function( newData ) {
+ var index,
+ updates = [];
+
+ if ( !lightResource ) {
+ return;
+ }
+
+ for ( index in newData ) {
+ if ( newData[ index ] !== lightResource.properties[ index ] ) {
+ lightResource.properties[ index ] = newData[ index ];
+ updates.push( index );
+ }
+ }
+ if ( updates.length > 0 ) {
+ device._server.notify( lightResource.id, "update", updates );
+ }
+} );
+
+if ( device._settings.info.uuid ) {
+ device._server.registerResource( {
+ url: "/light/ambience/blue",
+ deviceId: device._settings.info.uuid,
+ connectionMode: device._settings.connectionMode,
+ resourceTypes: [ "Light" ],
+ interfaces: [ "/oic/if/rw" ],
+ discoverable: true,
+ observable: true,
+ properties: { someValue: 0, someOtherValue: "Helsinki" }
+ } ).then(
+ function( resource ) {
+ lightResource = resource;
+ },
+ function( error ) {
+ throw error;
+ } );
+} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.