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 |
|---|---|---|---|---|---|---|---|---|---|---|
5e7ee92ba760f0a014852b44ca603de0cf33103b | lib/router.js | lib/router.js |
;(function(riot, evt) {
// browsers only
if (!this.top) return
var loc = location,
fns = riot.observable(),
win = window,
current
function hash() {
return loc.hash.slice(1)
}
function parser(path) {
return path.split('/')
}
function emit(path) {
if (path.type) path = hash()
if (path != current) {
fns.trigger.apply(null, ['H'].concat(parser(path)))
current = path
}
}
var r = riot.route = function(arg) {
// string
if (arg[0]) {
loc.hash = arg
emit(arg)
// function
} else {
fns.on('H', arg)
}
}
r.exec = function(fn) {
fn.apply(null, parser(hash()))
}
r.parser = function(fn) {
parser = fn
}
win.addEventListener ? win.addEventListener(evt, emit, false) : win.attachEvent('on' + evt, emit)
})(riot, 'hashchange')
|
;(function(riot, evt) {
// browsers only
if (!this.top) return
var loc = location,
fns = riot.observable(),
win = window,
current
function hash() {
return loc.href.split('#')[1] || ''
}
function parser(path) {
return path.split('/')
}
function emit(path) {
if (path.type) path = hash()
if (path != current) {
fns.trigger.apply(null, ['H'].concat(parser(path)))
current = path
}
}
var r = riot.route = function(arg) {
// string
if (arg[0]) {
loc.hash = arg
emit(arg)
// function
} else {
fns.on('H', arg)
}
}
r.exec = function(fn) {
fn.apply(null, parser(hash()))
}
r.parser = function(fn) {
parser = fn
}
win.addEventListener ? win.addEventListener(evt, emit, false) : win.attachEvent('on' + evt, emit)
})(riot, 'hashchange')
| Use location.href to extract hash | Use location.href to extract hash
There is a bug in firefox which means that location.hash contains the decoded URL. e.g
if the url is
xxx.com/#link/http%3A%2Fwhy.com
Then:
location.hash will be: #link/http://why.com
and
location.href will be: xxx.com/#link/http%3A%2Fwhy.com
So location.href contains the correct value but location.hash does not since it contains the decoded value. The fix is to use location.href to extract the hash.
More details on this page:
http://stackoverflow.com/questions/1703552/encoding-of-window-location-hash | JavaScript | mit | laomu1988/riot,davidmarkclements/riot,davidmarkclements/riot,dschnare/riot,marcioj/riot,xieyu33333/riot,xieyu33333/riot,GerHobbelt/riotjs,marciojcoelho/riotjs,ListnPlay/riotjs,scalabl3/riot,ListnPlay/riotjs,dp-lewis/riot,xtity/riot,tao-zeng/riot,scalabl3/riot,duongphuhiep/riot,rsbondi/riotjs,muut/riotjs,ttamminen/riotjs,mike-ward/riot,rsbondi/riotjs,madlordory/riot,tao-zeng/riot,seedtigo/riot,crisward/riot,AndrewSwerlick/riot,qrb/riotjs,AndrewSwerlick/riot,qrb/riotjs,antonheryanto/riot,marciojcoelho/riotjs,sylvainpolletvillard/riot,sylvainpolletvillard/riot,joshcartme/riot,muut/riotjs,noodle-learns-programming/riot,marcioj/riot,madlordory/riot,joshcartme/riot,dschnare/riot,a-moses/riot,dp-lewis/riot,xtity/riot,stonexer/riot,laomu1988/riot,daemonchen/riotjs,zawsx/js-lib-webcomponents-react-riot,rasata/riot,rthbound/riot,baysao/riot,thepian/riot,txchen/riotjs,chetanism/riot,stonexer/riot,txchen/riotjs,beni55/riot,ttamminen/riotjs,GerHobbelt/riotjs,mike-ward/riot,zawsx/js-lib-webcomponents-react-riot,crisward/riot,a-moses/riot,duongphuhiep/riot,rasata/riot,chetanism/riot,rthbound/riot,thepian/riot,noodle-learns-programming/riot,daemonchen/riotjs,seedtigo/riot,beni55/riot,antonheryanto/riot,baysao/riot | ---
+++
@@ -10,7 +10,7 @@
current
function hash() {
- return loc.hash.slice(1)
+ return loc.href.split('#')[1] || ''
}
function parser(path) { |
9120504c07a69506831f3264dd3b244411fd2ebd | Queue/index.js | Queue/index.js | function Queue() {
this._oldestIndex = 1;
this._newestIndex = 1;
this._storage = {};
}
Queue.prototype.size = function() {
return this._newestIndex - this._oldestIndex;
};
Queue.prototype.enqueue = function(data) {
this._storage[this._newestIndex] = data;
this._newestIndex++;
};
Queue.prototype.dequeue = function() {
var oldestIndex = this._oldestIndex,
newestIndex = this._newestIndex,
deletedData;
if (oldestIndex !== newestIndex) {
deletedData = this._storage[oldestIndex];
delete this._storage[oldestIndex];
this._oldestIndex++;
return deletedData;
}
};
export default Queue;
| Add Queue, and rename files | Add Queue, and rename files
| JavaScript | mit | jazlalli/data-structure-playground | ---
+++
@@ -0,0 +1,30 @@
+function Queue() {
+ this._oldestIndex = 1;
+ this._newestIndex = 1;
+ this._storage = {};
+}
+
+Queue.prototype.size = function() {
+ return this._newestIndex - this._oldestIndex;
+};
+
+Queue.prototype.enqueue = function(data) {
+ this._storage[this._newestIndex] = data;
+ this._newestIndex++;
+};
+
+Queue.prototype.dequeue = function() {
+ var oldestIndex = this._oldestIndex,
+ newestIndex = this._newestIndex,
+ deletedData;
+
+ if (oldestIndex !== newestIndex) {
+ deletedData = this._storage[oldestIndex];
+ delete this._storage[oldestIndex];
+ this._oldestIndex++;
+
+ return deletedData;
+ }
+};
+
+export default Queue; | |
cfb735bf738443de1d868435e55758e6a1cf3c62 | udata/migrations/2019-07-23-reversed-date-range.js | udata/migrations/2019-07-23-reversed-date-range.js | /**
* Swap reversed DateRange values
*/
var updated = 0;
// Match all Dataset having temporal_coverage.start > temporal_coverage.end
const pipeline = [
{$project: {
cmp: {$cmp: ['$temporal_coverage.start', '$temporal_coverage.end']},
obj: '$$ROOT'
}},
{$match: {cmp: {$gt: 0}}},
{$replaceRoot: {newRoot: '$obj'}}
];
db.dataset.aggregate(pipeline).forEach(dataset => {
db.dataset.update(
{_id: dataset._id},
{'$set': {
'temporal_coverage.start': dataset.temporal_coverage.end,
'temporal_coverage.end': dataset.temporal_coverage.start,
}}
);
updated++;
});
print(`Updated ${updated} datasets with reversed temporal coverage.`);
| Fix existing dataset with reversed temporal coverage (migration) | Fix existing dataset with reversed temporal coverage (migration)
| JavaScript | agpl-3.0 | opendatateam/udata,etalab/udata,etalab/udata,etalab/udata,opendatateam/udata,opendatateam/udata | ---
+++
@@ -0,0 +1,29 @@
+/**
+ * Swap reversed DateRange values
+ */
+
+var updated = 0;
+
+// Match all Dataset having temporal_coverage.start > temporal_coverage.end
+const pipeline = [
+ {$project: {
+ cmp: {$cmp: ['$temporal_coverage.start', '$temporal_coverage.end']},
+ obj: '$$ROOT'
+ }},
+ {$match: {cmp: {$gt: 0}}},
+ {$replaceRoot: {newRoot: '$obj'}}
+];
+
+
+db.dataset.aggregate(pipeline).forEach(dataset => {
+ db.dataset.update(
+ {_id: dataset._id},
+ {'$set': {
+ 'temporal_coverage.start': dataset.temporal_coverage.end,
+ 'temporal_coverage.end': dataset.temporal_coverage.start,
+ }}
+ );
+ updated++;
+});
+
+print(`Updated ${updated} datasets with reversed temporal coverage.`); | |
7613c87332c207db7cfd0809c1695ed991a89fc5 | file-system/watcher-spawn.js | file-system/watcher-spawn.js | 'use strict';
// In the curernt version of JavaScript, one **cannot** 'use strict' with const
// declarations
// Import the fs (file system) module.
// "Require" returns an object: the module being required.
// By declaring it
const fs = require('fs');
// Import the child_process module; however, only get a single function, spawn.
const spawn = require('child_process').spawn
// Get the filename to watch from the command line arguments.
const filename = process.argv[2];
if (! filename) {
throw Error("No file to watch.");
}
// Watch the specified target for changes. When the file changes, invoke the
// anonymous function.
fs.watch(filename, function() {
// The anonymous function runs the command `ls -lh filename` in a shell and
// pipes its output to the standard output of the node process.
let ls = spawn('ls', ['-lh', filename]);
ls.stdout.pipe(process.stdout);
});
// Remember that this message will print *before* other messoges.
console.log('Now watching ' + filename + ' for changes...');
| Add file watcher that spawns a new process. | Add file watcher that spawns a new process.
Add a file watcher process that spawns an operating system process,
captures its output and pipes that output to the standard output of the
node process running the file watcher script.
| JavaScript | mit | mrwizard82d1/node-js-the-right-way | ---
+++
@@ -0,0 +1,30 @@
+'use strict';
+
+// In the curernt version of JavaScript, one **cannot** 'use strict' with const
+// declarations
+
+// Import the fs (file system) module.
+// "Require" returns an object: the module being required.
+// By declaring it
+const fs = require('fs');
+
+// Import the child_process module; however, only get a single function, spawn.
+const spawn = require('child_process').spawn
+
+// Get the filename to watch from the command line arguments.
+const filename = process.argv[2];
+if (! filename) {
+ throw Error("No file to watch.");
+}
+
+// Watch the specified target for changes. When the file changes, invoke the
+// anonymous function.
+fs.watch(filename, function() {
+ // The anonymous function runs the command `ls -lh filename` in a shell and
+ // pipes its output to the standard output of the node process.
+ let ls = spawn('ls', ['-lh', filename]);
+ ls.stdout.pipe(process.stdout);
+});
+
+// Remember that this message will print *before* other messoges.
+console.log('Now watching ' + filename + ' for changes...'); | |
5826f84bf22d136fa4eede515b7511f4e566fd4a | child_process/handle_error.js | child_process/handle_error.js | /*
If the child process fails, print the error.
*/
const {exec} = require('child_process')
proc = exec('python count.py abc', (error, stdout, stderr) => {
if (error) {
console.log('Error:', error)
}
console.log(stdout)
})
| Add example that prints the error from a child process | Add example that prints the error from a child process
| JavaScript | apache-2.0 | feihong/node-examples,feihong/node-examples | ---
+++
@@ -0,0 +1,14 @@
+/*
+
+If the child process fails, print the error.
+
+*/
+
+const {exec} = require('child_process')
+
+proc = exec('python count.py abc', (error, stdout, stderr) => {
+ if (error) {
+ console.log('Error:', error)
+ }
+ console.log(stdout)
+}) | |
3245e5defcce51139b0d30cc4956b5520708d068 | week-7/variables-objects.js | week-7/variables-objects.js | // JavaScript Variables and Objects
// I paired [by myself] on this challenge.
// __________________________________________
// Write your code below.
var secretNumber = 7;
var password = "just open the door";
var allowedIn = false;
var members = ["John", "Kate", "Joe", "Mary"];
// __________________________________________
// Test Code: Do not alter code below this line.
function assert(test, message, test_number) {
if (!test) {
console.log(test_number + "false");
throw "ERROR: " + message;
}
console.log(test_number + "true");
return true;
}
assert(
(typeof secretNumber === 'number'),
"The value of secretNumber should be a number.",
"1. "
)
assert(
secretNumber === 7,
"The value of secretNumber should be 7.",
"2. "
)
assert(
typeof password === 'string',
"The value of password should be a string.",
"3. "
)
assert(
password === "just open the door",
"The value of password should be 'just open the door'.",
"4. "
)
assert(
typeof allowedIn === 'boolean',
"The value of allowedIn should be a boolean.",
"5. "
)
assert(
allowedIn === false,
"The value of allowedIn should be false.",
"6. "
)
assert(
members instanceof Array,
"The value of members should be an array",
"7. "
)
assert(
members[0] === "John",
"The first element in the value of members should be 'John'.",
"8. "
)
assert(
members[3] === "Mary",
"The fourth element in the value of members should be 'Mary'.",
"9. "
) | Add variables objects solution to match test code | Add variables objects solution to match test code
| JavaScript | mit | michaelzwang/phase-0,michaelzwang/phase-0,michaelzwang/phase-0 | ---
+++
@@ -0,0 +1,79 @@
+// JavaScript Variables and Objects
+
+// I paired [by myself] on this challenge.
+
+// __________________________________________
+// Write your code below.
+
+var secretNumber = 7;
+var password = "just open the door";
+var allowedIn = false;
+var members = ["John", "Kate", "Joe", "Mary"];
+
+
+// __________________________________________
+
+// Test Code: Do not alter code below this line.
+
+function assert(test, message, test_number) {
+ if (!test) {
+ console.log(test_number + "false");
+ throw "ERROR: " + message;
+ }
+ console.log(test_number + "true");
+ return true;
+}
+
+assert(
+ (typeof secretNumber === 'number'),
+ "The value of secretNumber should be a number.",
+ "1. "
+)
+
+assert(
+ secretNumber === 7,
+ "The value of secretNumber should be 7.",
+ "2. "
+)
+
+assert(
+ typeof password === 'string',
+ "The value of password should be a string.",
+ "3. "
+)
+
+assert(
+ password === "just open the door",
+ "The value of password should be 'just open the door'.",
+ "4. "
+)
+
+assert(
+ typeof allowedIn === 'boolean',
+ "The value of allowedIn should be a boolean.",
+ "5. "
+)
+
+assert(
+ allowedIn === false,
+ "The value of allowedIn should be false.",
+ "6. "
+)
+
+assert(
+ members instanceof Array,
+ "The value of members should be an array",
+ "7. "
+)
+
+assert(
+ members[0] === "John",
+ "The first element in the value of members should be 'John'.",
+ "8. "
+)
+
+assert(
+ members[3] === "Mary",
+ "The fourth element in the value of members should be 'Mary'.",
+ "9. "
+) | |
7041c7958b3b8a8354300b76ef1e5716d67de2d4 | src/lib/SpreadSheet.spec.js | src/lib/SpreadSheet.spec.js | import { SpreadSheet } from './SpreadSheet';
import { Row, Cell } from './models';
import { parseCommand } from './models';
describe('SpreadSheet', () => {
const cells = [
new Cell(0, 'A', 0),
new Cell(1, 'A', 5),
new Cell(2, 'A', 10)
];
const rows = [
new Row('A', cells)
];
const spreadSheet = new SpreadSheet(rows);
describe('eval', () => {
const ast = parseCommand('A0 = A1 + A2');
it('raises exception if AST Type is unknown', () => {
const astWithUnknownType = {
type: 'something that is unknown'
};
expect(() => {
spreadSheet.eval(astWithUnknownType)
}).toThrow();
});
it('evals a valid AST', () => {
spreadSheet.eval(ast);
expect(spreadSheet.rows[0].cells[0].value).toEqual(15);
});
});
}); | Add tests for SpreadSheet eval | Add tests for SpreadSheet eval
| JavaScript | mit | schultyy/spreadsheet,schultyy/spreadsheet | ---
+++
@@ -0,0 +1,34 @@
+import { SpreadSheet } from './SpreadSheet';
+import { Row, Cell } from './models';
+import { parseCommand } from './models';
+
+describe('SpreadSheet', () => {
+ const cells = [
+ new Cell(0, 'A', 0),
+ new Cell(1, 'A', 5),
+ new Cell(2, 'A', 10)
+ ];
+ const rows = [
+ new Row('A', cells)
+ ];
+
+ const spreadSheet = new SpreadSheet(rows);
+ describe('eval', () => {
+ const ast = parseCommand('A0 = A1 + A2');
+
+ it('raises exception if AST Type is unknown', () => {
+ const astWithUnknownType = {
+ type: 'something that is unknown'
+ };
+
+ expect(() => {
+ spreadSheet.eval(astWithUnknownType)
+ }).toThrow();
+ });
+
+ it('evals a valid AST', () => {
+ spreadSheet.eval(ast);
+ expect(spreadSheet.rows[0].cells[0].value).toEqual(15);
+ });
+ });
+}); | |
a66bd438086607e141616769368eae3c799d70a5 | lib/utilities.js | lib/utilities.js | 'use strict';
/**
* Convert a string to camel case.
*
* @param {String} string - The string.
* @return {String}
*/
function camelCase(string) {
if (typeof string !== 'string') {
throw new Error('`camelCase`: first argument must be a string.');
}
// hyphen found after first character
if (string.indexOf('-') > 0) {
var strings = string.toLowerCase().split('-');
// capitalize starting from the second string item
for (var i = 1, len = strings.length; i < len; i++) {
strings[i] = strings[i].charAt(0).toUpperCase() + strings[i].slice(1);
}
return strings.join('');
}
return string;
}
/**
* Export utilties.
*/
module.exports = {
camelCase: camelCase
};
| Create utility helper for camel casing text with hyphens | Create utility helper for camel casing text with hyphens
This helper will be used when converting CSS styles to JS objects.
Then the `style` object will be consistent in the React props.
| JavaScript | mit | remarkablemark/html-react-parser,remarkablemark/html-react-parser,remarkablemark/html-react-parser | ---
+++
@@ -0,0 +1,34 @@
+'use strict';
+
+/**
+ * Convert a string to camel case.
+ *
+ * @param {String} string - The string.
+ * @return {String}
+ */
+function camelCase(string) {
+ if (typeof string !== 'string') {
+ throw new Error('`camelCase`: first argument must be a string.');
+ }
+
+ // hyphen found after first character
+ if (string.indexOf('-') > 0) {
+ var strings = string.toLowerCase().split('-');
+
+ // capitalize starting from the second string item
+ for (var i = 1, len = strings.length; i < len; i++) {
+ strings[i] = strings[i].charAt(0).toUpperCase() + strings[i].slice(1);
+ }
+
+ return strings.join('');
+ }
+
+ return string;
+}
+
+/**
+ * Export utilties.
+ */
+module.exports = {
+ camelCase: camelCase
+}; | |
70fc48b39ea70654f230899629da2339c63606d4 | src/concat/index.js | src/concat/index.js | var FileType = require('../file').type;
/**
* @param {Array<Object>} files
* @param {string} fileType
*/
function concat(files, fileType) {
var code = [];
files.forEach(function(file) {
switch (fileType) {
case FileType.CSS:
code.push(file.code);
code.push('\n');
break;
case FileType.JS:
code.push(';');
code.push(file.code);
code.push('\n');
break;
}
});
return code.join('');
}
module.exports = concat; | Add simple module for concatting code. | Add simple module for concatting code.
| JavaScript | bsd-3-clause | ZocDoc/Bundler,ZocDoc/Bundler | ---
+++
@@ -0,0 +1,34 @@
+var FileType = require('../file').type;
+
+/**
+ * @param {Array<Object>} files
+ * @param {string} fileType
+ */
+function concat(files, fileType) {
+
+ var code = [];
+
+ files.forEach(function(file) {
+
+ switch (fileType) {
+
+ case FileType.CSS:
+ code.push(file.code);
+ code.push('\n');
+ break;
+
+ case FileType.JS:
+ code.push(';');
+ code.push(file.code);
+ code.push('\n');
+ break;
+
+ }
+
+ });
+
+ return code.join('');
+
+}
+
+module.exports = concat; | |
5ae4b4f4b0fbef750a0f897c05c3dca5c1d8454f | src/tasks/load-model-files.js | src/tasks/load-model-files.js | var path = require('path'),
vow = require('vow'),
inherit = require('inherit'),
fsExtra = require('fs-extra'),
Base = require('./base');
module.exports = inherit(Base, {
logger: undefined,
__constructor: function (baseConfig, taskConfig) {
this.__base(baseConfig, taskConfig);
this.logger = this.createLogger(module);
this.logger.info('Initialize "%s" task successfully', this.getName());
},
/**
* Returns name of current task
* @returns {string} - name of task
*/
getName: function () {
return 'load model files';
},
/**
* Performs task
* @returns {Promise}
*/
run: function () {
var newModelFilePath = path.resolve(this.getBaseConfig().getModelFilePath()),
oldModelFilePath = path.resolve(this.getBaseConfig().getDestinationDirPath(), 'model.json'),
newModel,
oldModel;
try {
newModel = fsExtra.readJSONSync(newModelFilePath);
} catch (error) {
this.logger.error('Can\'t read or parse model file "%s"', newModelFilePath);
throw error;
}
try {
oldModel = fsExtra.readJSONSync(oldModelFilePath);
} catch (error) {
this.logger.warn('Can\'t read or parse model file "%s". New model will be created', newModelFilePath);
oldModel = [];
}
return vow.resolve({ newModel: newModel, oldModel: oldModel });
}
});
| Implement task for loading model files | Implement task for loading model files
| JavaScript | mpl-2.0 | bem-site/builder-core,bem-site/gorshochek | ---
+++
@@ -0,0 +1,51 @@
+var path = require('path'),
+ vow = require('vow'),
+ inherit = require('inherit'),
+ fsExtra = require('fs-extra'),
+ Base = require('./base');
+
+module.exports = inherit(Base, {
+
+ logger: undefined,
+
+ __constructor: function (baseConfig, taskConfig) {
+ this.__base(baseConfig, taskConfig);
+ this.logger = this.createLogger(module);
+ this.logger.info('Initialize "%s" task successfully', this.getName());
+ },
+
+ /**
+ * Returns name of current task
+ * @returns {string} - name of task
+ */
+ getName: function () {
+ return 'load model files';
+ },
+
+ /**
+ * Performs task
+ * @returns {Promise}
+ */
+ run: function () {
+ var newModelFilePath = path.resolve(this.getBaseConfig().getModelFilePath()),
+ oldModelFilePath = path.resolve(this.getBaseConfig().getDestinationDirPath(), 'model.json'),
+ newModel,
+ oldModel;
+
+ try {
+ newModel = fsExtra.readJSONSync(newModelFilePath);
+ } catch (error) {
+ this.logger.error('Can\'t read or parse model file "%s"', newModelFilePath);
+ throw error;
+ }
+
+ try {
+ oldModel = fsExtra.readJSONSync(oldModelFilePath);
+ } catch (error) {
+ this.logger.warn('Can\'t read or parse model file "%s". New model will be created', newModelFilePath);
+ oldModel = [];
+ }
+
+ return vow.resolve({ newModel: newModel, oldModel: oldModel });
+ }
+}); | |
630e5319af9242035b66df3dba9714604f7a058f | scripts/process-all-records.js | scripts/process-all-records.js | var jobs = require('../server/kue').jobs;
var mongoose = require('../server/mongoose');
var Record = mongoose.model('Record');
var count = 0;
Record
.find()
.select({ identifier: 1, parentCatalog: 1 })
.lean()
.stream()
.on('data', function (record) {
count++;
jobs
.create('process-record', {
recordId: record.identifier,
catalogId: record.parentCatalog
})
.removeOnComplete(true)
.attempts(5)
.save();
})
.on('error', function (err) {
console.trace(err);
})
.on('close', function () {
console.log(count);
process.exit();
});
| Add script to process all records again | Add script to process all records again
| JavaScript | agpl-3.0 | jdesboeufs/geogw,inspireteam/geogw | ---
+++
@@ -0,0 +1,30 @@
+var jobs = require('../server/kue').jobs;
+var mongoose = require('../server/mongoose');
+
+var Record = mongoose.model('Record');
+
+var count = 0;
+
+Record
+ .find()
+ .select({ identifier: 1, parentCatalog: 1 })
+ .lean()
+ .stream()
+ .on('data', function (record) {
+ count++;
+ jobs
+ .create('process-record', {
+ recordId: record.identifier,
+ catalogId: record.parentCatalog
+ })
+ .removeOnComplete(true)
+ .attempts(5)
+ .save();
+ })
+ .on('error', function (err) {
+ console.trace(err);
+ })
+ .on('close', function () {
+ console.log(count);
+ process.exit();
+ }); | |
5ce37602b361f4ed79d4354b998f0ae1d99a18bf | test/functional/ios/testapp/keyboard-specs.js | test/functional/ios/testapp/keyboard-specs.js | "use strict";
var setup = require("../../common/setup-base")
, desired = require('./desired')
, _ = require('underscore');
describe("testapp - keyboard stability @skip-ci", function () {
var runs = 10
, text = 'Delhi is New @@@ QA-BREAKFAST-FOOD-0001';
var driver;
setup(this, _.defaults({
deviceName: 'iPad Simulator',
}, desired)).then(function (d) { driver = d; });
var test = function () {
it("should send keys to a text field", function (done) {
driver
.elementByClassName('UIATextField')
.sendKeys(text)
.text().should.become(text)
.nodeify(done);
});
};
for (var n = 0; n < runs; n++) {
describe('sendKeys test ' + (n + 1), test);
}
});
| Add stability test for iOS keyboard | Add stability test for iOS keyboard
| JavaScript | apache-2.0 | appium/appium,appium/appium,appium/appium,appium/appium,appium/appium,Sw0rdstream/appium,appium/appium | ---
+++
@@ -0,0 +1,30 @@
+"use strict";
+
+var setup = require("../../common/setup-base")
+ , desired = require('./desired')
+ , _ = require('underscore');
+
+
+describe("testapp - keyboard stability @skip-ci", function () {
+ var runs = 10
+ , text = 'Delhi is New @@@ QA-BREAKFAST-FOOD-0001';
+
+ var driver;
+ setup(this, _.defaults({
+ deviceName: 'iPad Simulator',
+ }, desired)).then(function (d) { driver = d; });
+
+ var test = function () {
+ it("should send keys to a text field", function (done) {
+ driver
+ .elementByClassName('UIATextField')
+ .sendKeys(text)
+ .text().should.become(text)
+ .nodeify(done);
+ });
+ };
+
+ for (var n = 0; n < runs; n++) {
+ describe('sendKeys test ' + (n + 1), test);
+ }
+}); | |
71b4aecaabd67943c58a2fa62f03f10b21bc9b63 | index.js | index.js | const http = require('http')
const parseString = require('xml2js').parseString
const nfl = {
hostname: 'www.nfl.com',
path: '/liveupdate/scorestrip/ss.xml',
method: 'GET'
}
const getGames = function getGames(xml) {
let games
parseString(xml.join(''), (err, data) => {
if (err) return console.error(err)
return games = data.ss.gms[0].g
})
return games
}
const pickTeam = function pickTeam(games) {
const gameNumber = getRandomInt(0, 15)
const side = getRandomInt(0, 1) ? 'hnn' : 'vnn'
return games[gameNumber]['$'][side]
}
const getRandomInt = function getRandomInt(min, max) {
min = Math.ceil(min) //inclusive min
max = Math.floor(max + 1) //inclusive max
return Math.floor(Math.random() * (max - min)) + min
}
const req = http.request(nfl, (res) => {
let xml = []
res.setEncoding('utf8')
res.on('data', body => xml.push(body))
res.on('end', () => {
const games = getGames(xml)
console.log(`For this week, your pick is: ${pickTeam(games)}`)
console.log(`Don't lose :)`)
})
})
req.on('error', (err) => {
console.log(`Error: ${err.message}`)
})
req.end()
| Add random team select script | Add random team select script
This script will randomly select a team from the current season's,
week's set of matches.
Not sure if the XML will get updated as the
season goes along. Will update if changes are needed.
| JavaScript | mit | yuleugim/nfld16 | ---
+++
@@ -0,0 +1,50 @@
+const http = require('http')
+const parseString = require('xml2js').parseString
+
+const nfl = {
+ hostname: 'www.nfl.com',
+ path: '/liveupdate/scorestrip/ss.xml',
+ method: 'GET'
+}
+
+const getGames = function getGames(xml) {
+ let games
+
+ parseString(xml.join(''), (err, data) => {
+ if (err) return console.error(err)
+ return games = data.ss.gms[0].g
+ })
+
+ return games
+}
+
+const pickTeam = function pickTeam(games) {
+ const gameNumber = getRandomInt(0, 15)
+ const side = getRandomInt(0, 1) ? 'hnn' : 'vnn'
+ return games[gameNumber]['$'][side]
+}
+
+const getRandomInt = function getRandomInt(min, max) {
+ min = Math.ceil(min) //inclusive min
+ max = Math.floor(max + 1) //inclusive max
+ return Math.floor(Math.random() * (max - min)) + min
+}
+
+const req = http.request(nfl, (res) => {
+ let xml = []
+
+ res.setEncoding('utf8')
+ res.on('data', body => xml.push(body))
+ res.on('end', () => {
+ const games = getGames(xml)
+
+ console.log(`For this week, your pick is: ${pickTeam(games)}`)
+ console.log(`Don't lose :)`)
+ })
+})
+
+req.on('error', (err) => {
+ console.log(`Error: ${err.message}`)
+})
+
+req.end() | |
3c6bec39f84dd8aa6424483a2d819420d0e2e785 | bundle.js | bundle.js | (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
module.exports = {
init: function init(size) {
this.size = size;
this.stick = []
for(var i = 0; i < size * size; i++) {
this.stick.push(0);
}
},
getTile: function getTile(x, y) {
var tileIdx = y * this.size + x;
return this.stick[tileIdx];
},
setTile: function getTile(x, y, val) {
var tileIdx = y * this.size + x;
return this.stick[tileIdx] = val;
}
};
},{}]},{},[1]);
| Create a dist file with browserify | Create a dist file with browserify
| JavaScript | mit | jollyra/tiles,jollyra/tiles | ---
+++
@@ -0,0 +1,20 @@
+(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
+module.exports = {
+ init: function init(size) {
+ this.size = size;
+ this.stick = []
+ for(var i = 0; i < size * size; i++) {
+ this.stick.push(0);
+ }
+ },
+ getTile: function getTile(x, y) {
+ var tileIdx = y * this.size + x;
+ return this.stick[tileIdx];
+ },
+ setTile: function getTile(x, y, val) {
+ var tileIdx = y * this.size + x;
+ return this.stick[tileIdx] = val;
+ }
+};
+
+},{}]},{},[1]); | |
429fa904d86ee4c6963a331b6a73ca70d15c4605 | bin/tap-reader.js | bin/tap-reader.js | #!/usr/bin/env node
// read a tap stream from stdin.
var TapConsumer = require("../lib/tap-consumer")
, TapStream = require("../lib/tap-stream")
var tc = new TapConsumer
, ts = new TapStream(!process.env.nodiag)
//process.stdin.pipe(tc)
process.stdin.on("data", function (c) {
c = c + ""
// console.error(JSON.stringify(c).substr(0, 100))
tc.write(c)
})
process.stdin.on("end", function () { tc.end() })
process.stdin.resume()
//tc.pipe(ts)
tc.on("data", function (c) {
ts.write(c)
})
tc.on("end", function () { ts.end() })
ts.on("data", function (c) {
console.error(["output write", c])
process.stdout.write(c)
})
ts.on("end", function (er, total, ok) {
if (er) throw er
process.exit(total - ok)
})
| Read tap output from stdin, to test parsing | Read tap output from stdin, to test parsing
| JavaScript | isc | iarna/node-tap,tapjs/node-tap,isaacs/node-tap,myndzi/node-tap,evanlucas/node-tap,myndzi/node-tap,jkrems/node-tap,Raynos/node-tap,Dignifiedquire/node-tap-core,evanlucas/node-tap,strongloop-forks/node-tap,iarna/node-tap,jondlm/node-tap,isaacs/node-tap,tapjs/node-tap,strongloop-forks/node-tap,jinivo/marhert,jondlm/node-tap,chbrown/node-tap,substack/node-tap,chbrown/node-tap,Dignifiedquire/node-tap-core,othiym23/node-tap,jkrems/node-tap,dominictarr/node-tap,othiym23/node-tap | ---
+++
@@ -0,0 +1,33 @@
+#!/usr/bin/env node
+
+// read a tap stream from stdin.
+
+var TapConsumer = require("../lib/tap-consumer")
+ , TapStream = require("../lib/tap-stream")
+
+var tc = new TapConsumer
+ , ts = new TapStream(!process.env.nodiag)
+
+//process.stdin.pipe(tc)
+process.stdin.on("data", function (c) {
+ c = c + ""
+ // console.error(JSON.stringify(c).substr(0, 100))
+ tc.write(c)
+})
+process.stdin.on("end", function () { tc.end() })
+process.stdin.resume()
+//tc.pipe(ts)
+tc.on("data", function (c) {
+ ts.write(c)
+})
+tc.on("end", function () { ts.end() })
+
+ts.on("data", function (c) {
+ console.error(["output write", c])
+ process.stdout.write(c)
+})
+
+ts.on("end", function (er, total, ok) {
+ if (er) throw er
+ process.exit(total - ok)
+}) | |
25c32481177b8055a7c746b38d094efd5ab8e3a7 | test/test-util.js | test/test-util.js | /*globals suite, test, setup, teardown */
var sutil = require('sake/util');
suite('sake.util', function () {
test('fileFromStackTrace', function () {
sutil.fileFromStackTrace().should.equal(__filename);
});
test('directoryFromStackTrace', function () {
sutil.directoryFromStackTrace().should.equal(__dirname);
});
}); | Add test file for stack trace functions. | Add test file for stack trace functions.
| JavaScript | mit | jhamlet/node-sake | ---
+++
@@ -0,0 +1,15 @@
+/*globals suite, test, setup, teardown */
+
+var sutil = require('sake/util');
+
+suite('sake.util', function () {
+
+ test('fileFromStackTrace', function () {
+ sutil.fileFromStackTrace().should.equal(__filename);
+ });
+
+ test('directoryFromStackTrace', function () {
+ sutil.directoryFromStackTrace().should.equal(__dirname);
+ });
+
+}); | |
b31d1b6e1e0eb033d9b7165e2c476fdfdadf7591 | scripts/managedb/swap_coords.js | scripts/managedb/swap_coords.js | /*
# Copyright 2014 Telefonica Investigacion y Desarrollo, S.A.U
#
# This file is part of Orion Context Broker.
#
# Orion Context Broker 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.
#
# Orion Context Broker 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 Orion Context Broker. If not, see http://www.gnu.org/licenses/.
#
# For those usages not covered by this license please contact with
# fermin at tid dot es
*/
/*
IT IS HIGHLY ADVISABLE TO PERFORM A DATABASE BACKUP BEFORE USING THIS SCRIPT. AS
STATED IN THE LICENSE TEST ABOVE, THIS SCRIPT IS PROVIDED IN THE HOPE IT WILL BE
USEFUL BUT WITHOUT ANY WARRANTY.
This script is aimed to swap the position of the coords in the location.coords field in the
entities collection. It is needed during the 0.14.0 (or before) to 0.14.1 upgrage
procedure in the case you have geo-tagged information in your Orion database.
Usage: mongo <db> swap_coords.js
where <db> is the name of the database in which you want to perform the operation.
The script prints to standard output the entities being processed.
*/
cursor = db.entities.find();
while ( cursor.hasNext() ) {
doc = cursor.next();
entity = '<id=' + doc._id.id + ', type=' + doc._id.type + '>';
if (doc.location) {
old0 = doc.location.coords[0];
old1 = doc.location.coords[1];
doc.location.coords[0] = old1;
doc.location.coords[1] = old0;
print (entity + ' swapping [ ' + old0 + ' , ' + old1 + ' ] -> [ ' + doc.location.coords[0] + ' , ' + doc.location.coords[1] + ' ]');
db.entities.save(doc);
}
else {
print (entity + ' skipped (no location)');
}
}
| ADD script for swapping coordinates in entities collection | ADD script for swapping coordinates in entities collection
| JavaScript | agpl-3.0 | McMutton/fiware-orion,gavioto/fiware-orion,fortizc/fiware-orion,gavioto/fiware-orion,telefonicaid/fiware-orion,j1fig/fiware-orion,Fiware/data.Orion,j1fig/fiware-orion,jmcanterafonseca/fiware-orion,pacificIT/fiware-orion,jmcanterafonseca/fiware-orion,fiwareulpgcmirror/fiware-orion,Fiware/data.Orion,telefonicaid/fiware-orion,Fiware/data.Orion,fortizc/fiware-orion,fortizc/fiware-orion,guerrerocarlos/fiware-orion,McMutton/fiware-orion,McMutton/fiware-orion,jmcanterafonseca/fiware-orion,Fiware/data.Orion,fiwareulpgcmirror/fiware-orion,pacificIT/fiware-orion,Fiware/data.Orion,j1fig/fiware-orion,Fiware/context.Orion,Fiware/context.Orion,Fiware/context.Orion,fiwareulpgcmirror/fiware-orion,jmcanterafonseca/fiware-orion,McMutton/fiware-orion,telefonicaid/fiware-orion,guerrerocarlos/fiware-orion,McMutton/fiware-orion,jmcanterafonseca/fiware-orion,guerrerocarlos/fiware-orion,j1fig/fiware-orion,pacificIT/fiware-orion,fiwareulpgcmirror/fiware-orion,telefonicaid/fiware-orion,pacificIT/fiware-orion,guerrerocarlos/fiware-orion,fiwareulpgcmirror/fiware-orion,Fiware/context.Orion,McMutton/fiware-orion,guerrerocarlos/fiware-orion,j1fig/fiware-orion,Fiware/context.Orion,McMutton/fiware-orion,telefonicaid/fiware-orion,fortizc/fiware-orion,Fiware/context.Orion,yalp/fiware-orion,yalp/fiware-orion,gavioto/fiware-orion,telefonicaid/fiware-orion,Fiware/data.Orion,gavioto/fiware-orion,yalp/fiware-orion,fiwareulpgcmirror/fiware-orion,yalp/fiware-orion,fortizc/fiware-orion,jmcanterafonseca/fiware-orion,pacificIT/fiware-orion,gavioto/fiware-orion,yalp/fiware-orion,fortizc/fiware-orion | ---
+++
@@ -0,0 +1,56 @@
+/*
+ # Copyright 2014 Telefonica Investigacion y Desarrollo, S.A.U
+ #
+ # This file is part of Orion Context Broker.
+ #
+ # Orion Context Broker 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.
+ #
+ # Orion Context Broker 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 Orion Context Broker. If not, see http://www.gnu.org/licenses/.
+ #
+ # For those usages not covered by this license please contact with
+ # fermin at tid dot es
+ */
+
+/*
+
+IT IS HIGHLY ADVISABLE TO PERFORM A DATABASE BACKUP BEFORE USING THIS SCRIPT. AS
+STATED IN THE LICENSE TEST ABOVE, THIS SCRIPT IS PROVIDED IN THE HOPE IT WILL BE
+USEFUL BUT WITHOUT ANY WARRANTY.
+
+This script is aimed to swap the position of the coords in the location.coords field in the
+entities collection. It is needed during the 0.14.0 (or before) to 0.14.1 upgrage
+procedure in the case you have geo-tagged information in your Orion database.
+
+Usage: mongo <db> swap_coords.js
+
+where <db> is the name of the database in which you want to perform the operation.
+
+The script prints to standard output the entities being processed.
+
+*/
+
+cursor = db.entities.find();
+while ( cursor.hasNext() ) {
+ doc = cursor.next();
+ entity = '<id=' + doc._id.id + ', type=' + doc._id.type + '>';
+ if (doc.location) {
+ old0 = doc.location.coords[0];
+ old1 = doc.location.coords[1];
+ doc.location.coords[0] = old1;
+ doc.location.coords[1] = old0;
+ print (entity + ' swapping [ ' + old0 + ' , ' + old1 + ' ] -> [ ' + doc.location.coords[0] + ' , ' + doc.location.coords[1] + ' ]');
+ db.entities.save(doc);
+ }
+ else {
+ print (entity + ' skipped (no location)');
+ }
+} | |
a1f23b243a855a9cae37edaaa5ed2a2c62c50072 | webpack.config.js | webpack.config.js | const path = require('path');
module.exports = {
resolve: {
modules: [
__dirname + '/scripts',
path.resolve(__dirname, "./node_modules")
]
}
}; | Resolve import for modules in ‘scripts’ directory | Resolve import for modules in ‘scripts’ directory
| JavaScript | apache-2.0 | weepower/wee-core | ---
+++
@@ -0,0 +1,10 @@
+const path = require('path');
+
+module.exports = {
+ resolve: {
+ modules: [
+ __dirname + '/scripts',
+ path.resolve(__dirname, "./node_modules")
+ ]
+ }
+}; | |
8adde8004e6986a919fc26e1df2c72bddc55077b | test/actions/editor_test.js | test/actions/editor_test.js | import { expect, isFSA, isFSAName } from '../spec_helper'
import * as subject from '../../src/actions/editor'
describe('editor actions', () => {
context('#setIsCompleterActive', () => {
const action = subject.setIsCompleterActive({ isActive: true })
it('is an FSA compliant action', () => {
expect(isFSA(action)).to.be.true
})
it('has similar action.name and action.type', () => {
expect(isFSAName(action, subject.setIsCompleterActive)).to.be.true
})
it('has a payload with the correct keys', () => {
expect(action.payload).to.have.keys('isCompleterActive')
})
it('sets the appropriate payload', () => {
expect(action.payload.isCompleterActive).to.be.true
})
})
context('#setIsTextToolsActive', () => {
const action = subject.setIsTextToolsActive({
isActive: true,
textToolsStates: { isLinkActive: false, isBoldActive: true, isItalicActive: false },
})
it('is an FSA compliant action', () => {
expect(isFSA(action)).to.be.true
})
it('has similar action.name and action.type', () => {
expect(isFSAName(action, subject.setIsTextToolsActive)).to.be.true
})
it('has a payload with the correct keys', () => {
expect(action.payload).to.have.keys('isTextToolsActive', 'textToolsStates')
})
it('sets the appropriate payload for isTextToolsActive', () => {
expect(action.payload.isTextToolsActive).to.be.true
})
it('sets the appropriate payload for textToolsStates', () => {
expect(action.payload.textToolsStates.isLinkActive).to.be.false
expect(action.payload.textToolsStates.isBoldActive).to.be.true
expect(action.payload.textToolsStates.isItalicActive).to.be.false
})
})
context('#setTextToolsCoordinates', () => {
const action = subject.setTextToolsCoordinates({
textToolsCoordinates: { top: -867, left: -666 },
})
it('is an FSA compliant action', () => {
expect(isFSA(action)).to.be.true
})
it('has similar action.name and action.type', () => {
expect(isFSAName(action, subject.setTextToolsCoordinates)).to.be.true
})
it('sets the appropriate payload for textToolsStates', () => {
expect(action.payload.textToolsCoordinates.top).to.equal(-867)
expect(action.payload.textToolsCoordinates.left).to.equal(-666)
})
})
})
| Add tests around the new updated editor actions | Add tests around the new updated editor actions | JavaScript | mit | ello/webapp,ello/webapp,ello/webapp | ---
+++
@@ -0,0 +1,73 @@
+import { expect, isFSA, isFSAName } from '../spec_helper'
+import * as subject from '../../src/actions/editor'
+
+describe('editor actions', () => {
+ context('#setIsCompleterActive', () => {
+ const action = subject.setIsCompleterActive({ isActive: true })
+
+ it('is an FSA compliant action', () => {
+ expect(isFSA(action)).to.be.true
+ })
+
+ it('has similar action.name and action.type', () => {
+ expect(isFSAName(action, subject.setIsCompleterActive)).to.be.true
+ })
+
+ it('has a payload with the correct keys', () => {
+ expect(action.payload).to.have.keys('isCompleterActive')
+ })
+
+ it('sets the appropriate payload', () => {
+ expect(action.payload.isCompleterActive).to.be.true
+ })
+ })
+
+ context('#setIsTextToolsActive', () => {
+ const action = subject.setIsTextToolsActive({
+ isActive: true,
+ textToolsStates: { isLinkActive: false, isBoldActive: true, isItalicActive: false },
+ })
+
+ it('is an FSA compliant action', () => {
+ expect(isFSA(action)).to.be.true
+ })
+
+ it('has similar action.name and action.type', () => {
+ expect(isFSAName(action, subject.setIsTextToolsActive)).to.be.true
+ })
+
+ it('has a payload with the correct keys', () => {
+ expect(action.payload).to.have.keys('isTextToolsActive', 'textToolsStates')
+ })
+
+ it('sets the appropriate payload for isTextToolsActive', () => {
+ expect(action.payload.isTextToolsActive).to.be.true
+ })
+
+ it('sets the appropriate payload for textToolsStates', () => {
+ expect(action.payload.textToolsStates.isLinkActive).to.be.false
+ expect(action.payload.textToolsStates.isBoldActive).to.be.true
+ expect(action.payload.textToolsStates.isItalicActive).to.be.false
+ })
+ })
+
+ context('#setTextToolsCoordinates', () => {
+ const action = subject.setTextToolsCoordinates({
+ textToolsCoordinates: { top: -867, left: -666 },
+ })
+
+ it('is an FSA compliant action', () => {
+ expect(isFSA(action)).to.be.true
+ })
+
+ it('has similar action.name and action.type', () => {
+ expect(isFSAName(action, subject.setTextToolsCoordinates)).to.be.true
+ })
+
+ it('sets the appropriate payload for textToolsStates', () => {
+ expect(action.payload.textToolsCoordinates.top).to.equal(-867)
+ expect(action.payload.textToolsCoordinates.left).to.equal(-666)
+ })
+ })
+})
+ | |
a19c5e3daf7cc6b81f410c5780b9eff24df70b00 | test/unit/ngGravatarTest.js | test/unit/ngGravatarTest.js | var chai = require('chai');
var sinon = require('sinon');
var sinonChai = require("sinon-chai");
var ngGravatar = require('../../src/ngGravatar');
chai.should();
chai.use(sinonChai);
describe('ngGravatar', function() {
var gravatarDirective;
beforeEach(function() {
gravatarDirective = ngGravatar();
});
it('should return a directive definition object', function() {
gravatarDirective.should.be.an('object');
});
});
| Add simple test for gravatar directive | Add simple test for gravatar directive
| JavaScript | mit | Spidy88/ngGravatar | ---
+++
@@ -0,0 +1,20 @@
+var chai = require('chai');
+var sinon = require('sinon');
+var sinonChai = require("sinon-chai");
+
+var ngGravatar = require('../../src/ngGravatar');
+
+chai.should();
+chai.use(sinonChai);
+
+describe('ngGravatar', function() {
+ var gravatarDirective;
+
+ beforeEach(function() {
+ gravatarDirective = ngGravatar();
+ });
+
+ it('should return a directive definition object', function() {
+ gravatarDirective.should.be.an('object');
+ });
+}); | |
eb2454acd11b656a16813a1bdbc7e6257d5d486f | core/model/formats/bibtexmisc.js | core/model/formats/bibtexmisc.js | 'use strict';
require('../../../utils/array');
/**
* @module bibTex Misc Entry Formatter
* Module for formatting source data into a bibTeX misc type entry
*/
module.exports = {
/**
* Formats a source data object to a citation
* @param {SourceData} sourceData - The SourceData object to generate the citation string from
* @return {string} - The bibTeX Misc Entry
*/
format : (sourceData){
return "";
}
}
| Set up initial bibtex misc style formatter | Set up initial bibtex misc style formatter
| JavaScript | mit | nokeeo/software-citation-tools,faokryn/software-citation-tools | ---
+++
@@ -0,0 +1,19 @@
+'use strict';
+require('../../../utils/array');
+
+/**
+ * @module bibTex Misc Entry Formatter
+ * Module for formatting source data into a bibTeX misc type entry
+ */
+
+module.exports = {
+ /**
+ * Formats a source data object to a citation
+ * @param {SourceData} sourceData - The SourceData object to generate the citation string from
+ * @return {string} - The bibTeX Misc Entry
+ */
+ format : (sourceData){
+ return "";
+ }
+}
+ | |
fb969ac6c3ebd2dd62897c3cbb34222a08e09655 | src/io.js | src/io.js | /* IO monad taken from monet.js */
/*
The MIT License (MIT)
Copyright (c) 2016 Chris Myers
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/* eslint-disable fp/no-this, fp/no-nil, fp/no-mutation, fp/no-throw */
export const IO = (effectFn) => {
return new IO.fn.init(effectFn)
};
IO.of = (a) => {
return IO(() => {
return a;
})
};
IO.fn = IO.prototype = {
init: (effectFn) => {
if (!isFunction(effectFn))
throw 'IO requires a function';
this.effectFn = effectFn;
},
map: (fn) => {
return IO(function() {
return fn(this.effectFn());
})
},
bind: (fn) => {
return IO(() => {
return fn(this.effectFn())
.run();
})
},
ap: (ioWithFn) => {
return ioWithFn.map((fn) => fn(this.effectFn()));
},
run: () => this.effectFn()
}
IO.fn.init.prototype = IO.fn
IO.prototype.perform = IO.prototype.performUnsafeIO = IO.prototype.run
| Add IO monad from monet.js | Add IO monad from monet.js
but make it more es6-like
| JavaScript | mit | memee/reactive-charts | ---
+++
@@ -0,0 +1,62 @@
+/* IO monad taken from monet.js */
+/*
+The MIT License (MIT)
+
+Copyright (c) 2016 Chris Myers
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+*/
+/* eslint-disable fp/no-this, fp/no-nil, fp/no-mutation, fp/no-throw */
+export const IO = (effectFn) => {
+ return new IO.fn.init(effectFn)
+};
+
+IO.of = (a) => {
+ return IO(() => {
+ return a;
+ })
+};
+
+IO.fn = IO.prototype = {
+ init: (effectFn) => {
+ if (!isFunction(effectFn))
+ throw 'IO requires a function';
+ this.effectFn = effectFn;
+ },
+ map: (fn) => {
+ return IO(function() {
+ return fn(this.effectFn());
+ })
+ },
+ bind: (fn) => {
+ return IO(() => {
+ return fn(this.effectFn())
+ .run();
+ })
+ },
+ ap: (ioWithFn) => {
+ return ioWithFn.map((fn) => fn(this.effectFn()));
+ },
+ run: () => this.effectFn()
+}
+
+IO.fn.init.prototype = IO.fn
+
+IO.prototype.perform = IO.prototype.performUnsafeIO = IO.prototype.run | |
5dbd7c1c09c05fa122d53ca3060b565af75b54d7 | lib/properties.es6.js | lib/properties.es6.js | /**
* @license
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
foam.CLASS({
package: 'tools.web.strict',
name: 'MethodProperty',
extends: 'FObjectProperty',
documentation: `
Property that may be set to a function, a Method object, or data
specification of a method object, and assume the function value.
`,
requires: ['Method'],
properties: [
{
name: 'of',
value: 'Method',
},
{
name: 'adapt',
value: function(_, o, self) {
if (!o) return o;
if (typeof o === 'function')
return self.Method.create({code: o}).code;
if (!self.Method.isInstance(o))
return self.Method.create(o).code;
return o.code;
},
},
{
name: 'factory',
value: function(self) {
return self.adapt(
undefined,
Object.assign({}, self.value, {name: self.name}),
self
);
},
}
],
});
foam.CLASS({
package: 'foam.core',
name: 'FObjectArray',
extends: 'FObjectProperty',
documentation: 'Similar to FObjectProperty, but for arrays of FObjects',
properties: [
{
name: 'of',
value: 'FObject',
},
{
name: 'fromJSON',
value: function(json, ctx, prop) {
return foam.json.parse(json, prop.of, ctx);
},
},
{
name: 'adapt',
value: function(_, v, prop) {
const of = foam.lookup(prop.of);
return v.map(
o => of.isInstance(o) ? o :
(o.class ? foam.lookup(o.class) : of).create(o, this.__subContext__)
);
},
},
{
name: 'factory',
value: function() {
return [];
},
},
],
});
| Add missing properties module (required by Hook and PubHook) | Add missing properties module (required by Hook and PubHook)
| JavaScript | apache-2.0 | mdittmer/smw,mdittmer/smw,mdittmer/smw | ---
+++
@@ -0,0 +1,97 @@
+/**
+ * @license
+ * Copyright 2016 Google Inc. All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+'use strict';
+
+foam.CLASS({
+ package: 'tools.web.strict',
+ name: 'MethodProperty',
+ extends: 'FObjectProperty',
+
+ documentation: `
+ Property that may be set to a function, a Method object, or data
+ specification of a method object, and assume the function value.
+ `,
+
+ requires: ['Method'],
+
+ properties: [
+ {
+ name: 'of',
+ value: 'Method',
+ },
+ {
+ name: 'adapt',
+ value: function(_, o, self) {
+ if (!o) return o;
+
+ if (typeof o === 'function')
+ return self.Method.create({code: o}).code;
+ if (!self.Method.isInstance(o))
+ return self.Method.create(o).code;
+ return o.code;
+ },
+ },
+ {
+ name: 'factory',
+ value: function(self) {
+ return self.adapt(
+ undefined,
+ Object.assign({}, self.value, {name: self.name}),
+ self
+ );
+ },
+ }
+ ],
+});
+
+foam.CLASS({
+ package: 'foam.core',
+ name: 'FObjectArray',
+ extends: 'FObjectProperty',
+
+ documentation: 'Similar to FObjectProperty, but for arrays of FObjects',
+
+ properties: [
+ {
+ name: 'of',
+ value: 'FObject',
+ },
+ {
+ name: 'fromJSON',
+ value: function(json, ctx, prop) {
+ return foam.json.parse(json, prop.of, ctx);
+ },
+ },
+ {
+ name: 'adapt',
+ value: function(_, v, prop) {
+ const of = foam.lookup(prop.of);
+
+ return v.map(
+ o => of.isInstance(o) ? o :
+ (o.class ? foam.lookup(o.class) : of).create(o, this.__subContext__)
+ );
+ },
+ },
+ {
+ name: 'factory',
+ value: function() {
+ return [];
+ },
+ },
+ ],
+}); | |
d0d1827193fbcb37d9315adddf3000f4d0037a75 | controllers/helpers/docHelper.js | controllers/helpers/docHelper.js | const docHelper = {
checkDocDetails: (req, res) => {
let document = req.body;
if (!(document.title && document.content && document.access)) {
res.status(400)
.json({
success: false,
message: 'All fields must be filled'
});
res.end();
return true;
}
}
};
module.exports = docHelper;
| Add document helper file for document controller | Add document helper file for document controller
| JavaScript | mit | andela-oolutola/document-management-system-api | ---
+++
@@ -0,0 +1,16 @@
+const docHelper = {
+ checkDocDetails: (req, res) => {
+ let document = req.body;
+ if (!(document.title && document.content && document.access)) {
+ res.status(400)
+ .json({
+ success: false,
+ message: 'All fields must be filled'
+ });
+ res.end();
+ return true;
+ }
+ }
+};
+
+module.exports = docHelper; | |
25955ef55a3086c37c8e6fa6590abb4b3bd80da6 | Workspace/Project/utility.js | Workspace/Project/utility.js | module.exports = {
move: function(arr, old_index, new_index)
{
while (old_index < 0)
old_index += arr.length;
while (new_index < 0)
new_index += arr.length
if (new_index >= arr.length)
{
var k = new_index - arr.length
while ((k--) + 1)
arr.push(undefined)
}
arr.splice(new_index, 0, arr.splice(old_index, 1)[0])
return arr
},
objectCompare: function (obj1, obj2) {
//Loop through properties in object 1
for (var p in obj1) {
//Check property exists on both objects
if (obj1.hasOwnProperty(p) !== obj2.hasOwnProperty(p)) return false;
switch (typeof (obj1[p])) {
//Deep compare objects
case 'object':
if (!this.objectCompare(obj1[p], obj2[p])) return false;
break;
//Compare function code
case 'function':
if (typeof (obj2[p]) == 'undefined' || (p != 'compare' && obj1[p].toString() != obj2[p].toString())) return false;
break;
//Compare values
default:
if (obj1[p] != obj2[p]) return false;
}
}
//Check object 2 for any extra properties
for (var p in obj2) {
if (typeof (obj1[p]) == 'undefined') return false;
}
return true;
}
}
| Add Object Compare Check and Element Change Position in Array | Add Object Compare Check and Element Change Position in Array
| JavaScript | mit | MrWooJ/WJChipDesign,MrWooJ/WJChipDesign | ---
+++
@@ -0,0 +1,46 @@
+module.exports = {
+ move: function(arr, old_index, new_index)
+ {
+ while (old_index < 0)
+ old_index += arr.length;
+ while (new_index < 0)
+ new_index += arr.length
+ if (new_index >= arr.length)
+ {
+ var k = new_index - arr.length
+ while ((k--) + 1)
+ arr.push(undefined)
+ }
+ arr.splice(new_index, 0, arr.splice(old_index, 1)[0])
+ return arr
+ },
+
+ objectCompare: function (obj1, obj2) {
+ //Loop through properties in object 1
+ for (var p in obj1) {
+ //Check property exists on both objects
+ if (obj1.hasOwnProperty(p) !== obj2.hasOwnProperty(p)) return false;
+
+ switch (typeof (obj1[p])) {
+ //Deep compare objects
+ case 'object':
+ if (!this.objectCompare(obj1[p], obj2[p])) return false;
+ break;
+ //Compare function code
+ case 'function':
+ if (typeof (obj2[p]) == 'undefined' || (p != 'compare' && obj1[p].toString() != obj2[p].toString())) return false;
+ break;
+ //Compare values
+ default:
+ if (obj1[p] != obj2[p]) return false;
+ }
+ }
+
+ //Check object 2 for any extra properties
+ for (var p in obj2) {
+ if (typeof (obj1[p]) == 'undefined') return false;
+ }
+ return true;
+ }
+
+} | |
c99512ea8181d4020de2d1adc45612a70ddce91d | files/bootstrap.hover-dropdown/2.1.3/bootstrap-hover-dropdown.min.js | files/bootstrap.hover-dropdown/2.1.3/bootstrap-hover-dropdown.min.js | /**
* @preserve
* Project: Bootstrap Hover Dropdown
* Author: Cameron Spear
* Version: v2.1.3
* Contributors: Mattia Larentis
* Dependencies: Bootstrap's Dropdown plugin, jQuery
* Description: A simple plugin to enable Bootstrap dropdowns to active on hover and provide a nice user experience.
* License: MIT
* Homepage: http://cameronspear.com/blog/bootstrap-dropdown-on-hover-plugin/
*/
!function(e,n){var o=e();e.fn.dropdownHover=function(t){return"ontouchstart"in document?this:(o=o.add(this.parent()),this.each(function(){function r(){n.clearTimeout(a),n.clearTimeout(i),i=n.setTimeout(function(){o.find(":focus").blur(),f.instantlyCloseOthers===!0&&o.removeClass("open"),n.clearTimeout(i),d.attr("aria-expanded","true"),s.addClass("open"),d.trigger(l)},f.hoverDelay)}var a,i,d=e(this),s=d.parent(),u={delay:500,hoverDelay:0,instantlyCloseOthers:!0},h={delay:e(this).data("delay"),hoverDelay:e(this).data("hover-delay"),instantlyCloseOthers:e(this).data("close-others")},l="show.bs.dropdown",c="hide.bs.dropdown",f=e.extend(!0,{},u,t,h);s.hover(function(e){return s.hasClass("open")||d.is(e.target)?void r(e):!0},function(){n.clearTimeout(i),a=n.setTimeout(function(){d.attr("aria-expanded","false"),s.removeClass("open"),d.trigger(c)},f.delay)}),d.hover(function(e){return s.hasClass("open")||s.is(e.target)?void r(e):!0}),s.find(".dropdown-submenu").each(function(){var o,t=e(this);t.hover(function(){n.clearTimeout(o),t.children(".dropdown-menu").show(),t.siblings().children(".dropdown-menu").hide()},function(){var e=t.children(".dropdown-menu");o=n.setTimeout(function(){e.hide()},f.delay)})})}))},e(document).ready(function(){e('[data-hover="dropdown"]').dropdownHover()})}(jQuery,window); | Update project bootstrap-hover-dropdown to v2.1.3 | Update project bootstrap-hover-dropdown to v2.1.3
| JavaScript | mit | anilanar/jsdelivr,MenZil/jsdelivr,dnbard/jsdelivr,siscia/jsdelivr,tunnckoCore/jsdelivr,Swatinem/jsdelivr,photonstorm/jsdelivr,cognitom/jsdelivr,anilanar/jsdelivr,yyx990803/jsdelivr,vousk/jsdelivr,garrypolley/jsdelivr,labsvisual/jsdelivr,dpellier/jsdelivr,siscia/jsdelivr,anilanar/jsdelivr,Sneezry/jsdelivr,ajibolam/jsdelivr,alexmojaki/jsdelivr,vvo/jsdelivr,korusdipl/jsdelivr,markcarver/jsdelivr,moay/jsdelivr,fchasen/jsdelivr,bdukes/jsdelivr,gregorypratt/jsdelivr,ajkj/jsdelivr,spud2451/jsdelivr,bonbon197/jsdelivr,RoberMac/jsdelivr,AdityaManohar/jsdelivr,vousk/jsdelivr,vvo/jsdelivr,ndamofli/jsdelivr,dpellier/jsdelivr,stevelacy/jsdelivr,towerz/jsdelivr,l3dlp/jsdelivr,cesarmarinhorj/jsdelivr,Valve/jsdelivr,Sneezry/jsdelivr,oller/jsdelivr,yaplas/jsdelivr,CTres/jsdelivr,ManrajGrover/jsdelivr,Valve/jsdelivr,markcarver/jsdelivr,ndamofli/jsdelivr,markcarver/jsdelivr,yyx990803/jsdelivr,towerz/jsdelivr,evilangelmd/jsdelivr,walkermatt/jsdelivr,cesarmarinhorj/jsdelivr,MenZil/jsdelivr,cake654326/jsdelivr,afghanistanyn/jsdelivr,cake654326/jsdelivr,MenZil/jsdelivr,Third9/jsdelivr,dpellier/jsdelivr,spud2451/jsdelivr,labsvisual/jsdelivr,dandv/jsdelivr,Heark/jsdelivr,asimihsan/jsdelivr,oller/jsdelivr,leebyron/jsdelivr,AdityaManohar/jsdelivr,Swatinem/jsdelivr,AdityaManohar/jsdelivr,anilanar/jsdelivr,yyx990803/jsdelivr,CTres/jsdelivr,yaplas/jsdelivr,afghanistanyn/jsdelivr,korusdipl/jsdelivr,Third9/jsdelivr,walkermatt/jsdelivr,CTres/jsdelivr,megawac/jsdelivr,asimihsan/jsdelivr,bdukes/jsdelivr,siscia/jsdelivr,l3dlp/jsdelivr,AdityaManohar/jsdelivr,walkermatt/jsdelivr,rtenshi/jsdelivr,gregorypratt/jsdelivr,ndamofli/jsdelivr,ManrajGrover/jsdelivr,firulais/jsdelivr,fchasen/jsdelivr,justincy/jsdelivr,MenZil/jsdelivr,dnbard/jsdelivr,siscia/jsdelivr,photonstorm/jsdelivr,Swatinem/jsdelivr,ajibolam/jsdelivr,cognitom/jsdelivr,RoberMac/jsdelivr,Kingside/jsdelivr,firulais/jsdelivr,asimihsan/jsdelivr,Valve/jsdelivr,l3dlp/jsdelivr,megawac/jsdelivr,fchasen/jsdelivr,leebyron/jsdelivr,towerz/jsdelivr,evilangelmd/jsdelivr,bonbon197/jsdelivr,bonbon197/jsdelivr,Heark/jsdelivr,ajibolam/jsdelivr,Metrakit/jsdelivr,oller/jsdelivr,gregorypratt/jsdelivr,hubdotcom/jsdelivr,yaplas/jsdelivr,Valve/jsdelivr,Kingside/jsdelivr,tunnckoCore/jsdelivr,afghanistanyn/jsdelivr,tunnckoCore/jsdelivr,korusdipl/jsdelivr,oller/jsdelivr,oller/jsdelivr,vousk/jsdelivr,yyx990803/jsdelivr,ntd/jsdelivr,photonstorm/jsdelivr,garrypolley/jsdelivr,ManrajGrover/jsdelivr,cedricbousmanne/jsdelivr,Metrakit/jsdelivr,ntd/jsdelivr,ajibolam/jsdelivr,korusdipl/jsdelivr,dnbard/jsdelivr,Heark/jsdelivr,ntd/jsdelivr,cedricbousmanne/jsdelivr,yyx990803/jsdelivr,cognitom/jsdelivr,ajkj/jsdelivr,ndamofli/jsdelivr,bonbon197/jsdelivr,wallin/jsdelivr,labsvisual/jsdelivr,firulais/jsdelivr,evilangelmd/jsdelivr,rtenshi/jsdelivr,MichaelSL/jsdelivr,cedricbousmanne/jsdelivr,dandv/jsdelivr,vebin/jsdelivr,ajkj/jsdelivr,jtblin/jsdelivr,stevelacy/jsdelivr,moay/jsdelivr,siscia/jsdelivr,Metrakit/jsdelivr,royswastik/jsdelivr,megawac/jsdelivr,royswastik/jsdelivr,alexmojaki/jsdelivr,cake654326/jsdelivr,leebyron/jsdelivr,bdukes/jsdelivr,MichaelSL/jsdelivr,Kingside/jsdelivr,Heark/jsdelivr,spud2451/jsdelivr,ManrajGrover/jsdelivr,Metrakit/jsdelivr,royswastik/jsdelivr,vvo/jsdelivr,asimihsan/jsdelivr,justincy/jsdelivr,CTres/jsdelivr,justincy/jsdelivr,ManrajGrover/jsdelivr,fchasen/jsdelivr,MichaelSL/jsdelivr,hubdotcom/jsdelivr,hubdotcom/jsdelivr,ntd/jsdelivr,dandv/jsdelivr,photonstorm/jsdelivr,CTres/jsdelivr,jtblin/jsdelivr,l3dlp/jsdelivr,rtenshi/jsdelivr,garrypolley/jsdelivr,vvo/jsdelivr,Sneezry/jsdelivr,moay/jsdelivr,gregorypratt/jsdelivr,markcarver/jsdelivr,MenZil/jsdelivr,cesarmarinhorj/jsdelivr,towerz/jsdelivr,spud2451/jsdelivr,ntd/jsdelivr,stevelacy/jsdelivr,towerz/jsdelivr,dnbard/jsdelivr,Kingside/jsdelivr,cake654326/jsdelivr,Sneezry/jsdelivr,ajibolam/jsdelivr,MichaelSL/jsdelivr,bonbon197/jsdelivr,wallin/jsdelivr,ndamofli/jsdelivr,rtenshi/jsdelivr,cesarmarinhorj/jsdelivr,walkermatt/jsdelivr,AdityaManohar/jsdelivr,yaplas/jsdelivr,jtblin/jsdelivr,RoberMac/jsdelivr,dpellier/jsdelivr,gregorypratt/jsdelivr,RoberMac/jsdelivr,RoberMac/jsdelivr,Kingside/jsdelivr,ajkj/jsdelivr,rtenshi/jsdelivr,cedricbousmanne/jsdelivr,Metrakit/jsdelivr,stevelacy/jsdelivr,moay/jsdelivr,Valve/jsdelivr,bdukes/jsdelivr,cedricbousmanne/jsdelivr,fchasen/jsdelivr,MichaelSL/jsdelivr,leebyron/jsdelivr,royswastik/jsdelivr,alexmojaki/jsdelivr,tunnckoCore/jsdelivr,firulais/jsdelivr,jtblin/jsdelivr,Heark/jsdelivr,hubdotcom/jsdelivr,dandv/jsdelivr,Third9/jsdelivr,garrypolley/jsdelivr,Swatinem/jsdelivr,labsvisual/jsdelivr,wallin/jsdelivr,jtblin/jsdelivr,hubdotcom/jsdelivr,vvo/jsdelivr,ajkj/jsdelivr,cognitom/jsdelivr,vebin/jsdelivr,dpellier/jsdelivr,afghanistanyn/jsdelivr,evilangelmd/jsdelivr,firulais/jsdelivr,cesarmarinhorj/jsdelivr,vousk/jsdelivr,stevelacy/jsdelivr,Swatinem/jsdelivr,royswastik/jsdelivr,anilanar/jsdelivr,wallin/jsdelivr,evilangelmd/jsdelivr,garrypolley/jsdelivr,justincy/jsdelivr,Third9/jsdelivr,megawac/jsdelivr,korusdipl/jsdelivr,dandv/jsdelivr,spud2451/jsdelivr,asimihsan/jsdelivr,moay/jsdelivr,vebin/jsdelivr,leebyron/jsdelivr,justincy/jsdelivr,dnbard/jsdelivr,yaplas/jsdelivr,walkermatt/jsdelivr,alexmojaki/jsdelivr,Third9/jsdelivr,Sneezry/jsdelivr,tunnckoCore/jsdelivr,alexmojaki/jsdelivr,labsvisual/jsdelivr,megawac/jsdelivr,l3dlp/jsdelivr,vebin/jsdelivr,markcarver/jsdelivr,vebin/jsdelivr,cake654326/jsdelivr,wallin/jsdelivr,vousk/jsdelivr,cognitom/jsdelivr,afghanistanyn/jsdelivr | ---
+++
@@ -0,0 +1,12 @@
+/**
+ * @preserve
+ * Project: Bootstrap Hover Dropdown
+ * Author: Cameron Spear
+ * Version: v2.1.3
+ * Contributors: Mattia Larentis
+ * Dependencies: Bootstrap's Dropdown plugin, jQuery
+ * Description: A simple plugin to enable Bootstrap dropdowns to active on hover and provide a nice user experience.
+ * License: MIT
+ * Homepage: http://cameronspear.com/blog/bootstrap-dropdown-on-hover-plugin/
+ */
+!function(e,n){var o=e();e.fn.dropdownHover=function(t){return"ontouchstart"in document?this:(o=o.add(this.parent()),this.each(function(){function r(){n.clearTimeout(a),n.clearTimeout(i),i=n.setTimeout(function(){o.find(":focus").blur(),f.instantlyCloseOthers===!0&&o.removeClass("open"),n.clearTimeout(i),d.attr("aria-expanded","true"),s.addClass("open"),d.trigger(l)},f.hoverDelay)}var a,i,d=e(this),s=d.parent(),u={delay:500,hoverDelay:0,instantlyCloseOthers:!0},h={delay:e(this).data("delay"),hoverDelay:e(this).data("hover-delay"),instantlyCloseOthers:e(this).data("close-others")},l="show.bs.dropdown",c="hide.bs.dropdown",f=e.extend(!0,{},u,t,h);s.hover(function(e){return s.hasClass("open")||d.is(e.target)?void r(e):!0},function(){n.clearTimeout(i),a=n.setTimeout(function(){d.attr("aria-expanded","false"),s.removeClass("open"),d.trigger(c)},f.delay)}),d.hover(function(e){return s.hasClass("open")||s.is(e.target)?void r(e):!0}),s.find(".dropdown-submenu").each(function(){var o,t=e(this);t.hover(function(){n.clearTimeout(o),t.children(".dropdown-menu").show(),t.siblings().children(".dropdown-menu").hide()},function(){var e=t.children(".dropdown-menu");o=n.setTimeout(function(){e.hide()},f.delay)})})}))},e(document).ready(function(){e('[data-hover="dropdown"]').dropdownHover()})}(jQuery,window); | |
185f131d51470073e4656122276c7d8a561ef3a5 | src/utils/get-scripts.js | src/utils/get-scripts.js | import fs from 'fs';
import path from 'path';
import yaml from 'js-yaml';
const scriptCache = {};
function getCacheOrFile(key, fn) {
if (scriptCache[key]) {
return scriptCache[key];
}
const value = fn();
scriptCache[key] = value;
return value;
}
const travisCommands = [
// Reference: http://docs.travis-ci.com/user/customizing-the-build/#The-Build-Lifecycle
'before_install',
'install',
'before_script',
'script',
'after_success or after_failure',
'before_deploy',
'deploy',
'after_deploy',
'after_script',
];
function concat(array, item) {
return array.concat(item);
}
function getObjectValues(object) {
return Object.keys(object).map(key => object[key]);
}
export default function getScripts(filepath, content = null) {
return getCacheOrFile(filepath, () => {
const basename = path.basename(filepath);
const fileContent = content !== null ? content : fs.readFileSync(filepath, 'utf-8');
if (basename === 'package.json') {
return getObjectValues(JSON.parse(fileContent).scripts || {});
} else if (basename === '.travis.yml') {
const metadata = yaml.safeLoad(content) || {};
return travisCommands.map(cmd => metadata[cmd] || []).reduce(concat, []);
}
return [];
});
}
| import fs from 'fs';
import path from 'path';
import yaml from 'js-yaml';
const scriptCache = {};
function getCacheOrFile(key, fn) {
if (scriptCache[key]) {
return scriptCache[key];
}
const value = fn();
scriptCache[key] = value;
return value;
}
const travisCommands = [
// Reference: http://docs.travis-ci.com/user/customizing-the-build/#The-Build-Lifecycle
'before_install',
'install',
'before_script',
'script',
'after_success or after_failure',
'before_deploy',
'after_deploy',
'after_script',
];
function concat(array, item) {
return array.concat(item);
}
function getObjectValues(object) {
return Object.keys(object).map(key => object[key]);
}
export default function getScripts(filepath, content = null) {
return getCacheOrFile(filepath, () => {
const basename = path.basename(filepath);
const fileContent = content !== null ? content : fs.readFileSync(filepath, 'utf-8');
if (basename === 'package.json') {
return getObjectValues(JSON.parse(fileContent).scripts || {});
} else if (basename === '.travis.yml') {
const metadata = yaml.safeLoad(content) || {};
return travisCommands.map(cmd => metadata[cmd] || []).reduce(concat, []);
}
return [];
});
}
| Fix a bug in getScript utility. | Fix a bug in getScript utility.
- Should not extract script from deploy section.
| JavaScript | mit | depcheck/depcheck,depcheck/depcheck | ---
+++
@@ -23,7 +23,6 @@
'script',
'after_success or after_failure',
'before_deploy',
- 'deploy',
'after_deploy',
'after_script',
]; |
7d5d37e7477c4a41e264d583158d759ad851b201 | patchDedupe.js | patchDedupe.js | var through = require("through2");
exports.patch = function (Browserify) {
Browserify.prototype._dedupe = function () {
return through.obj(function (row, enc, next) {
if (!row.dedupeIndex && row.dedupe) {
// PATCH IS AS SIMPLE AS NOT DOING THE FOLLOWING:
/*
row.source = 'module.exports=require('
+ JSON.stringify(row.dedupe)
+ ')'
;
row.deps = {};
row.deps[row.dedupe] = row.dedupe;
row.nomap = true;
*/
// AND JUST MOVING ON :)
return next();
}
if (row.dedupeIndex && row.sameDeps) {
row.source = 'module.exports=require('
+ JSON.stringify(row.dedupeIndex)
+ ')'
;
row.deps = {};
row.nomap = true;
}
else if (row.dedupeIndex) {
row.source = 'arguments[4]['
+ JSON.stringify(row.dedupeIndex)
+ '][0].apply(exports,arguments)'
;
row.nomap = true;
}
if (row.dedupeIndex && row.dedupe && row.indexDeps) {
row.indexDeps[row.dedupe] = row.dedupeIndex;
}
this.push(row);
next();
});
};
};
| Add monkey patch for _dedupe. | Add monkey patch for _dedupe.
| JavaScript | mit | YuzuJS/browserify-dedupe-patch | ---
+++
@@ -0,0 +1,42 @@
+var through = require("through2");
+
+exports.patch = function (Browserify) {
+ Browserify.prototype._dedupe = function () {
+ return through.obj(function (row, enc, next) {
+ if (!row.dedupeIndex && row.dedupe) {
+ // PATCH IS AS SIMPLE AS NOT DOING THE FOLLOWING:
+ /*
+ row.source = 'module.exports=require('
+ + JSON.stringify(row.dedupe)
+ + ')'
+ ;
+ row.deps = {};
+ row.deps[row.dedupe] = row.dedupe;
+ row.nomap = true;
+ */
+ // AND JUST MOVING ON :)
+ return next();
+ }
+ if (row.dedupeIndex && row.sameDeps) {
+ row.source = 'module.exports=require('
+ + JSON.stringify(row.dedupeIndex)
+ + ')'
+ ;
+ row.deps = {};
+ row.nomap = true;
+ }
+ else if (row.dedupeIndex) {
+ row.source = 'arguments[4]['
+ + JSON.stringify(row.dedupeIndex)
+ + '][0].apply(exports,arguments)'
+ ;
+ row.nomap = true;
+ }
+ if (row.dedupeIndex && row.dedupe && row.indexDeps) {
+ row.indexDeps[row.dedupe] = row.dedupeIndex;
+ }
+ this.push(row);
+ next();
+ });
+ };
+}; | |
6793f01abdbd91e6b8918504145e616ffa05f727 | week-7/group_project_solution.js | week-7/group_project_solution.js | // PERSON 5
// Refactored code:
// Simplified variable names and sum.
function sum(array){
// This works thanks to ECMAScript 6!
var total = array.reduce((a, b) => a + b, 0);
return total;
}
// Got rid of total_sum variable.
function mean(array){
var average = sum(array) / array.length;
return average;
}
// Cleaned up some variables that weren't necessary and reduced steps by altering calculations and rearranging if statement.
function median(array) {
array.sort(function(a,b){return a-b});
var half = Math.floor(array.length / 2)
// This is equivalent to "if (array.length % 2 != 0)" because 0 evaluates to 'false' in JS.
if (array.length % 2){
return array[half];
}else{
return (array[half - 1] + array[half]) / 2;
}
}
//Driver Code:
// var nums = [-1, 0, 1, 2, 3, 3.5, -3]
// console.log(sum(nums))
// console.log(mean(nums))
// console.log(median(nums))
// User Stories:
/*
1. As a user, I want a function that takes a set of
numbers and gives me the sum of all the numbers.
2. As a user, I want a function that takes a set of
numbers and calculates the mean for all the numbers.
3. As a user, I want a function that takes a set of
numbers and calculates the median of all the numbers.
If the amount of numbers is odd, it should give me
the middle number. If the amount of numbers is even,
it should average the two middle numbers and give me
that number.
*/
| Add 7.8 JS Telephone file | Add 7.8 JS Telephone file
| JavaScript | mit | Rinthm/phase-0,Rinthm/phase-0,Rinthm/phase-0 | ---
+++
@@ -0,0 +1,54 @@
+// PERSON 5
+
+// Refactored code:
+
+// Simplified variable names and sum.
+function sum(array){
+ // This works thanks to ECMAScript 6!
+ var total = array.reduce((a, b) => a + b, 0);
+ return total;
+}
+
+// Got rid of total_sum variable.
+function mean(array){
+ var average = sum(array) / array.length;
+ return average;
+}
+
+// Cleaned up some variables that weren't necessary and reduced steps by altering calculations and rearranging if statement.
+function median(array) {
+ array.sort(function(a,b){return a-b});
+ var half = Math.floor(array.length / 2)
+ // This is equivalent to "if (array.length % 2 != 0)" because 0 evaluates to 'false' in JS.
+ if (array.length % 2){
+ return array[half];
+ }else{
+ return (array[half - 1] + array[half]) / 2;
+ }
+}
+
+//Driver Code:
+
+// var nums = [-1, 0, 1, 2, 3, 3.5, -3]
+// console.log(sum(nums))
+// console.log(mean(nums))
+// console.log(median(nums))
+
+// User Stories:
+
+/*
+1. As a user, I want a function that takes a set of
+numbers and gives me the sum of all the numbers.
+
+2. As a user, I want a function that takes a set of
+numbers and calculates the mean for all the numbers.
+
+3. As a user, I want a function that takes a set of
+numbers and calculates the median of all the numbers.
+If the amount of numbers is odd, it should give me
+the middle number. If the amount of numbers is even,
+it should average the two middle numbers and give me
+that number.
+*/
+
+ | |
fb9ac1e15ab745af5cc79ad5c06a91be49760ed7 | src/components/events/DetailSpec.js | src/components/events/DetailSpec.js | import { shallow, createLocalVue } from '@vue/test-utils';
import Vuex from 'vuex';
import Detail from './Detail.vue';
const localVue = createLocalVue();
localVue.use(Vuex);
describe('Event Detail.vue', () => {
let wrapper, getters, store;
beforeEach(() => {
getters = {
isAdmin: () => true
}
store = new Vuex.Store({
getters
});
wrapper = shallow(Detail, {
localVue,
store,
propsData: {
event: {}
}
});
});
it('should create', () => {
expect(wrapper.isVueInstance()).to.be.true;
});
});
| Test to catch compile issues | Test to catch compile issues
| JavaScript | mit | dmurtari/mbu-frontend,dmurtari/mbu-frontend | ---
+++
@@ -0,0 +1,34 @@
+import { shallow, createLocalVue } from '@vue/test-utils';
+import Vuex from 'vuex';
+
+import Detail from './Detail.vue';
+
+const localVue = createLocalVue();
+localVue.use(Vuex);
+
+describe('Event Detail.vue', () => {
+ let wrapper, getters, store;
+
+ beforeEach(() => {
+ getters = {
+ isAdmin: () => true
+ }
+
+ store = new Vuex.Store({
+ getters
+ });
+
+ wrapper = shallow(Detail, {
+ localVue,
+ store,
+ propsData: {
+ event: {}
+ }
+ });
+ });
+
+ it('should create', () => {
+ expect(wrapper.isVueInstance()).to.be.true;
+ });
+
+}); | |
9ef27994b8fab189390e473ccd8ed59ca15281c1 | server/startup/migrations/v060.js | server/startup/migrations/v060.js | RocketChat.Migrations.add({
version: 60,
up: function() {
let subscriptions = RocketChat.models.Subscriptions.find({ $or: [ { name: { $exists: 0 } }, { name: { $not: { $type: 2 } } } ] }).fetch();
if (subscriptions && subscriptions.length > 0) {
RocketChat.models.Subscriptions.remove({ _id: { $in: _.pluck(subscriptions, '_id') } });
}
subscriptions = RocketChat.models.Subscriptions.find().forEach(function(subscription) {
let user = RocketChat.models.Users.findOne({ _id: subscription && subscription.u && subscription.u._id });
if (!user) {
RocketChat.models.Subscriptions.remove({ _id: subscription._id });
}
});
}
});
| Add migration to remove invalid subscriptions | Add migration to remove invalid subscriptions
| JavaScript | mit | Achaikos/Rocket.Chat,ahmadassaf/Rocket.Chat,Gyubin/Rocket.Chat,4thParty/Rocket.Chat,BorntraegerMarc/Rocket.Chat,alexbrazier/Rocket.Chat,abduljanjua/TheHub,snaiperskaya96/Rocket.Chat,mwharrison/Rocket.Chat,ealbers/Rocket.Chat,NMandapaty/Rocket.Chat,ealbers/Rocket.Chat,Movile/Rocket.Chat,matthewshirley/Rocket.Chat,AlecTroemel/Rocket.Chat,mrsimpson/Rocket.Chat,galrotem1993/Rocket.Chat,fatihwk/Rocket.Chat,igorstajic/Rocket.Chat,pitamar/Rocket.Chat,ziedmahdi/Rocket.Chat,pachox/Rocket.Chat,AimenJoe/Rocket.Chat,galrotem1993/Rocket.Chat,Sing-Li/Rocket.Chat,flaviogrossi/Rocket.Chat,trt15-ssci-organization/Rocket.Chat,yuyixg/Rocket.Chat,LearnersGuild/Rocket.Chat,trt15-ssci-organization/Rocket.Chat,Gyubin/Rocket.Chat,ggazzo/Rocket.Chat,mwharrison/Rocket.Chat,yuyixg/Rocket.Chat,k0nsl/Rocket.Chat,nishimaki10/Rocket.Chat,igorstajic/Rocket.Chat,JamesHGreen/Rocket.Chat,JamesHGreen/Rocket.Chat,Achaikos/Rocket.Chat,fatihwk/Rocket.Chat,intelradoux/Rocket.Chat,inoio/Rocket.Chat,galrotem1993/Rocket.Chat,AimenJoe/Rocket.Chat,wtsarchive/Rocket.Chat,ahmadassaf/Rocket.Chat,tntobias/Rocket.Chat,pkgodara/Rocket.Chat,wtsarchive/Rocket.Chat,ealbers/Rocket.Chat,VoiSmart/Rocket.Chat,NMandapaty/Rocket.Chat,fatihwk/Rocket.Chat,igorstajic/Rocket.Chat,matthewshirley/Rocket.Chat,danielbressan/Rocket.Chat,mwharrison/Rocket.Chat,ziedmahdi/Rocket.Chat,karlprieb/Rocket.Chat,flaviogrossi/Rocket.Chat,mrsimpson/Rocket.Chat,LearnersGuild/Rocket.Chat,Gudii/Rocket.Chat,pitamar/Rocket.Chat,JamesHGreen/Rocket_API,Achaikos/Rocket.Chat,karlprieb/Rocket.Chat,JamesHGreen/Rocket.Chat,AlecTroemel/Rocket.Chat,snaiperskaya96/Rocket.Chat,mrsimpson/Rocket.Chat,mrsimpson/Rocket.Chat,k0nsl/Rocket.Chat,pitamar/Rocket.Chat,Gudii/Rocket.Chat,ggazzo/Rocket.Chat,Sing-Li/Rocket.Chat,snaiperskaya96/Rocket.Chat,ggazzo/Rocket.Chat,alexbrazier/Rocket.Chat,mrinaldhar/Rocket.Chat,k0nsl/Rocket.Chat,LearnersGuild/echo-chat,mrinaldhar/Rocket.Chat,yuyixg/Rocket.Chat,marzieh312/Rocket.Chat,subesokun/Rocket.Chat,abduljanjua/TheHub,alexbrazier/Rocket.Chat,xasx/Rocket.Chat,LearnersGuild/Rocket.Chat,AimenJoe/Rocket.Chat,wtsarchive/Rocket.Chat,ahmadassaf/Rocket.Chat,4thParty/Rocket.Chat,inoio/Rocket.Chat,subesokun/Rocket.Chat,LearnersGuild/Rocket.Chat,LearnersGuild/echo-chat,xasx/Rocket.Chat,pkgodara/Rocket.Chat,cnash/Rocket.Chat,ahmadassaf/Rocket.Chat,xasx/Rocket.Chat,tntobias/Rocket.Chat,subesokun/Rocket.Chat,intelradoux/Rocket.Chat,NMandapaty/Rocket.Chat,mrinaldhar/Rocket.Chat,cnash/Rocket.Chat,NMandapaty/Rocket.Chat,matthewshirley/Rocket.Chat,BorntraegerMarc/Rocket.Chat,galrotem1993/Rocket.Chat,Movile/Rocket.Chat,snaiperskaya96/Rocket.Chat,intelradoux/Rocket.Chat,Kiran-Rao/Rocket.Chat,pkgodara/Rocket.Chat,JamesHGreen/Rocket_API,BorntraegerMarc/Rocket.Chat,flaviogrossi/Rocket.Chat,matthewshirley/Rocket.Chat,wtsarchive/Rocket.Chat,Gudii/Rocket.Chat,LearnersGuild/echo-chat,Gyubin/Rocket.Chat,pachox/Rocket.Chat,danielbressan/Rocket.Chat,VoiSmart/Rocket.Chat,abduljanjua/TheHub,marzieh312/Rocket.Chat,karlprieb/Rocket.Chat,subesokun/Rocket.Chat,danielbressan/Rocket.Chat,pitamar/Rocket.Chat,trt15-ssci-organization/Rocket.Chat,tntobias/Rocket.Chat,abduljanjua/TheHub,intelradoux/Rocket.Chat,karlprieb/Rocket.Chat,Kiran-Rao/Rocket.Chat,Gudii/Rocket.Chat,JamesHGreen/Rocket_API,inoio/Rocket.Chat,trt15-ssci-organization/Rocket.Chat,Kiran-Rao/Rocket.Chat,Gyubin/Rocket.Chat,xasx/Rocket.Chat,Achaikos/Rocket.Chat,ziedmahdi/Rocket.Chat,JamesHGreen/Rocket.Chat,mwharrison/Rocket.Chat,k0nsl/Rocket.Chat,LearnersGuild/echo-chat,alexbrazier/Rocket.Chat,JamesHGreen/Rocket_API,inoxth/Rocket.Chat,mrinaldhar/Rocket.Chat,pkgodara/Rocket.Chat,Movile/Rocket.Chat,AimenJoe/Rocket.Chat,danielbressan/Rocket.Chat,pachox/Rocket.Chat,4thParty/Rocket.Chat,ealbers/Rocket.Chat,inoxth/Rocket.Chat,inoxth/Rocket.Chat,Kiran-Rao/Rocket.Chat,cnash/Rocket.Chat,marzieh312/Rocket.Chat,Sing-Li/Rocket.Chat,flaviogrossi/Rocket.Chat,tntobias/Rocket.Chat,fatihwk/Rocket.Chat,4thParty/Rocket.Chat,igorstajic/Rocket.Chat,Movile/Rocket.Chat,VoiSmart/Rocket.Chat,ziedmahdi/Rocket.Chat,marzieh312/Rocket.Chat,cnash/Rocket.Chat,AlecTroemel/Rocket.Chat,pachox/Rocket.Chat,nishimaki10/Rocket.Chat,nishimaki10/Rocket.Chat,Sing-Li/Rocket.Chat,inoxth/Rocket.Chat,nishimaki10/Rocket.Chat,yuyixg/Rocket.Chat,BorntraegerMarc/Rocket.Chat,ggazzo/Rocket.Chat,AlecTroemel/Rocket.Chat | ---
+++
@@ -0,0 +1,16 @@
+RocketChat.Migrations.add({
+ version: 60,
+ up: function() {
+ let subscriptions = RocketChat.models.Subscriptions.find({ $or: [ { name: { $exists: 0 } }, { name: { $not: { $type: 2 } } } ] }).fetch();
+ if (subscriptions && subscriptions.length > 0) {
+ RocketChat.models.Subscriptions.remove({ _id: { $in: _.pluck(subscriptions, '_id') } });
+ }
+
+ subscriptions = RocketChat.models.Subscriptions.find().forEach(function(subscription) {
+ let user = RocketChat.models.Users.findOne({ _id: subscription && subscription.u && subscription.u._id });
+ if (!user) {
+ RocketChat.models.Subscriptions.remove({ _id: subscription._id });
+ }
+ });
+ }
+}); | |
ea67a765efd1145cc6f9df34ce7d7b6a0c0f12a5 | models/county.js | models/county.js | 'use strict';
module.exports = (sequelize, DataTypes) => {
const county = sequelize.define('county', {
name: DataTypes.STRING(64) // eslint-disable-line no-magic-numbers
}, {
timestamps: false,
classMethods: {
associate: (models) => {
county.hasMany(models.temp);
}
}
});
return county;
};
| Rename of the area model | Rename of the area model
| JavaScript | mit | NewEvolution/thermostats,NewEvolution/thermostats | ---
+++
@@ -0,0 +1,15 @@
+'use strict';
+
+module.exports = (sequelize, DataTypes) => {
+ const county = sequelize.define('county', {
+ name: DataTypes.STRING(64) // eslint-disable-line no-magic-numbers
+ }, {
+ timestamps: false,
+ classMethods: {
+ associate: (models) => {
+ county.hasMany(models.temp);
+ }
+ }
+ });
+ return county;
+}; | |
2472cec57936a2d8820f5e047b7f9520a7cf5d3c | components/ClickablePath.js | components/ClickablePath.js | import React, { Component } from 'react';
import { TouchableOpacity, Image, View } from 'react-native';
import styles from './styles/ClickablePathStyle';
import PropTypes from 'prop-types';
import { StackNagivator } from 'react-navigation';
export default class ClickablePath extends Component {
static propTypes = {
onPress: PropTypes.func,
text: PropTypes.object,
children: PropTypes.object,
navigation: PropTypes.object
}
render() {
return (
<View>
<TouchableOpacity style={styles.touchableSize} activeOpacity={.85} onPress={this.props.onPress}>
<Image style={styles.image} source={this.props.text} resizeMode='contain' />
</TouchableOpacity>
</View>
)
}
}
| Add separate clickable image for paths | Add separate clickable image for paths
| JavaScript | mit | fridl8/cold-bacon-client,fridl8/cold-bacon-client,fridl8/cold-bacon-client | ---
+++
@@ -0,0 +1,24 @@
+import React, { Component } from 'react';
+import { TouchableOpacity, Image, View } from 'react-native';
+import styles from './styles/ClickablePathStyle';
+import PropTypes from 'prop-types';
+import { StackNagivator } from 'react-navigation';
+
+export default class ClickablePath extends Component {
+ static propTypes = {
+ onPress: PropTypes.func,
+ text: PropTypes.object,
+ children: PropTypes.object,
+ navigation: PropTypes.object
+ }
+
+ render() {
+ return (
+ <View>
+ <TouchableOpacity style={styles.touchableSize} activeOpacity={.85} onPress={this.props.onPress}>
+ <Image style={styles.image} source={this.props.text} resizeMode='contain' />
+ </TouchableOpacity>
+ </View>
+ )
+ }
+} | |
52a9aa355a2c931d96f3f3d9a5ad483e94a95cf4 | geoportailv3/static/js/statemanagerservice.js | geoportailv3/static/js/statemanagerservice.js | /**
* @fileoverview This files provides a service for managing application
* states. States are written to both the URL (through the ngeoLocation
* service) and the local storage.
*/
goog.provide('app.StateManager');
goog.require('app');
goog.require('goog.asserts');
goog.require('goog.math');
goog.require('goog.storage.mechanism.HTML5LocalStorage');
goog.require('ngeo.Location');
/**
* @constructor
* @param {ngeo.Location} ngeoLocation ngeo location service.
* @ngInject
*/
app.StateManager = function(ngeoLocation) {
/**
* @type {ngeo.Location}
* @private
*/
this.ngeoLocation_ = ngeoLocation;
var version = ngeoLocation.getParam('version');
/**
* @type {number}
* @private
*/
this.version_ = goog.isDef(version) ? goog.math.clamp(+version, 2, 3) : 2;
this.ngeoLocation_.updateParams({'version': 3});
/**
* @type {goog.storage.mechanism.HTML5LocalStorage}
* @private
*/
this.localStorage_ = new goog.storage.mechanism.HTML5LocalStorage();
goog.asserts.assert(this.localStorage_.isAvailable());
};
/**
* Return the version as set in the initial URL (the URL that user
* used to load the application in the browser).
* @return {number} Version.
*/
app.StateManager.prototype.getVersion = function() {
return this.version_;
};
/**
* @param {string} key Param key.
* @return {string|undefined} Param value.
*/
app.StateManager.prototype.getParam = function(key) {
var value = this.ngeoLocation_.getParam(key);
if (!goog.isDef(value)) {
value = this.localStorage_.get(key);
if (goog.isNull(value)) {
value = undefined;
}
}
return value;
};
/**
* @param {Object.<string, string>} params Params to update.
*/
app.StateManager.prototype.updateParams = function(params) {
this.ngeoLocation_.updateParams(params);
var param;
for (param in params) {
this.localStorage_.set(param, params[param]);
}
};
app.module.service('appStateManager', app.StateManager);
| Add a state manager service | Add a state manager service
| JavaScript | mit | Geoportail-Luxembourg/geoportailv3,Geoportail-Luxembourg/geoportailv3,geoportallux/geoportailv3-gisgr,Geoportail-Luxembourg/geoportailv3,Geoportail-Luxembourg/geoportailv3,Geoportail-Luxembourg/geoportailv3,geoportallux/geoportailv3-gisgr,geoportallux/geoportailv3-gisgr,geoportallux/geoportailv3-gisgr | ---
+++
@@ -0,0 +1,87 @@
+/**
+ * @fileoverview This files provides a service for managing application
+ * states. States are written to both the URL (through the ngeoLocation
+ * service) and the local storage.
+ */
+goog.provide('app.StateManager');
+
+goog.require('app');
+goog.require('goog.asserts');
+goog.require('goog.math');
+goog.require('goog.storage.mechanism.HTML5LocalStorage');
+goog.require('ngeo.Location');
+
+
+
+/**
+ * @constructor
+ * @param {ngeo.Location} ngeoLocation ngeo location service.
+ * @ngInject
+ */
+app.StateManager = function(ngeoLocation) {
+
+ /**
+ * @type {ngeo.Location}
+ * @private
+ */
+ this.ngeoLocation_ = ngeoLocation;
+
+ var version = ngeoLocation.getParam('version');
+
+ /**
+ * @type {number}
+ * @private
+ */
+ this.version_ = goog.isDef(version) ? goog.math.clamp(+version, 2, 3) : 2;
+
+ this.ngeoLocation_.updateParams({'version': 3});
+
+ /**
+ * @type {goog.storage.mechanism.HTML5LocalStorage}
+ * @private
+ */
+ this.localStorage_ = new goog.storage.mechanism.HTML5LocalStorage();
+
+ goog.asserts.assert(this.localStorage_.isAvailable());
+};
+
+
+/**
+ * Return the version as set in the initial URL (the URL that user
+ * used to load the application in the browser).
+ * @return {number} Version.
+ */
+app.StateManager.prototype.getVersion = function() {
+ return this.version_;
+};
+
+
+/**
+ * @param {string} key Param key.
+ * @return {string|undefined} Param value.
+ */
+app.StateManager.prototype.getParam = function(key) {
+ var value = this.ngeoLocation_.getParam(key);
+ if (!goog.isDef(value)) {
+ value = this.localStorage_.get(key);
+ if (goog.isNull(value)) {
+ value = undefined;
+ }
+ }
+ return value;
+};
+
+
+/**
+ * @param {Object.<string, string>} params Params to update.
+ */
+app.StateManager.prototype.updateParams = function(params) {
+ this.ngeoLocation_.updateParams(params);
+ var param;
+ for (param in params) {
+ this.localStorage_.set(param, params[param]);
+ }
+};
+
+
+app.module.service('appStateManager', app.StateManager); | |
40ae6817fa0314ebd3f249965876c9a7b18056a9 | static/js/loadall.js | static/js/loadall.js | // ready() functions executed after everything else.
// Mainly for widget layout
$(function() {
$(window).resize(function(event) {
layoutWidgets();
});
layoutWidgets();
$(window).trigger("resize");
$("#workspace").invalidateLayout = function(event) {
layoutWidgets();
}
});
| Add specific JS to run after everything else has loaded, mainly for widget layout. | Add specific JS to run after everything else has loaded, mainly for widget layout.
| JavaScript | apache-2.0 | vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium | ---
+++
@@ -0,0 +1,15 @@
+// ready() functions executed after everything else.
+// Mainly for widget layout
+
+$(function() {
+ $(window).resize(function(event) {
+ layoutWidgets();
+ });
+ layoutWidgets();
+ $(window).trigger("resize");
+
+ $("#workspace").invalidateLayout = function(event) {
+ layoutWidgets();
+ }
+});
+ | |
c5a39025eb85c99f3a14e522b7e3411e3336ce7d | lib/rules/split-platform-components.js | lib/rules/split-platform-components.js | /**
* @fileoverview Android and IOS components should be
* used in platform specific React Native components.
* @author Tom Hastjarjanto
*/
'use strict';
module.exports = function(context) {
var reactComponents = [];
var androidMessage = 'Android components should be placed in android files';
var iosMessage = 'IOS components should be placed in ios files';
var conflictMessage = 'IOS and Android components can\'t be mixed';
function getKeyValue(node) {
var key = node.key || node.argument;
return key.type === 'Identifier' ? key.name : key.value;
}
function hasNodeWithName(node, name) {
return node.some(function(node) {
var nodeName = getKeyValue(node)
return nodeName && nodeName.includes(name);
})
}
function reportErrors(components, filename) {
var containsAndroidAndIOS = (
hasNodeWithName(components, 'IOS') &&
hasNodeWithName(components, 'Android')
);
for(var i = 0; i < components.length; i++) {
var node = components[i];
var propName = getKeyValue(node);
if (propName.includes('IOS') && !filename.endsWith('.ios.js')) {
context.report(node, containsAndroidAndIOS ? conflictMessage : iosMessage)
}
if (propName.includes('Android') && !filename.endsWith('.android.js')) {
context.report(node, containsAndroidAndIOS ? conflictMessage : androidMessage)
}
}
}
return {
VariableDeclarator: function(node) {
var destructuring = node.init && node.id && node.id.type === 'ObjectPattern';
var statelessDestructuring = destructuring && node.init.name === 'React';
if (destructuring && statelessDestructuring) {
reactComponents = reactComponents.concat(node.id.properties);
}
},
'Program:exit': function() {
var filename = context.getFilename();
reportErrors(reactComponents, filename);
}
};
};
module.exports.schema = [];
| Add initial implementation to force seperation of platform specific components | Add initial implementation to force seperation of platform specific components
| JavaScript | mit | Intellicode/eslint-plugin-react-native | ---
+++
@@ -0,0 +1,61 @@
+/**
+ * @fileoverview Android and IOS components should be
+ * used in platform specific React Native components.
+ * @author Tom Hastjarjanto
+ */
+'use strict';
+
+module.exports = function(context) {
+ var reactComponents = [];
+ var androidMessage = 'Android components should be placed in android files';
+ var iosMessage = 'IOS components should be placed in ios files';
+ var conflictMessage = 'IOS and Android components can\'t be mixed';
+
+ function getKeyValue(node) {
+ var key = node.key || node.argument;
+ return key.type === 'Identifier' ? key.name : key.value;
+ }
+
+ function hasNodeWithName(node, name) {
+ return node.some(function(node) {
+ var nodeName = getKeyValue(node)
+ return nodeName && nodeName.includes(name);
+ })
+ }
+
+ function reportErrors(components, filename) {
+ var containsAndroidAndIOS = (
+ hasNodeWithName(components, 'IOS') &&
+ hasNodeWithName(components, 'Android')
+ );
+
+ for(var i = 0; i < components.length; i++) {
+ var node = components[i];
+ var propName = getKeyValue(node);
+
+ if (propName.includes('IOS') && !filename.endsWith('.ios.js')) {
+ context.report(node, containsAndroidAndIOS ? conflictMessage : iosMessage)
+ }
+
+ if (propName.includes('Android') && !filename.endsWith('.android.js')) {
+ context.report(node, containsAndroidAndIOS ? conflictMessage : androidMessage)
+ }
+ }
+ }
+
+ return {
+ VariableDeclarator: function(node) {
+ var destructuring = node.init && node.id && node.id.type === 'ObjectPattern';
+ var statelessDestructuring = destructuring && node.init.name === 'React';
+ if (destructuring && statelessDestructuring) {
+ reactComponents = reactComponents.concat(node.id.properties);
+ }
+ },
+ 'Program:exit': function() {
+ var filename = context.getFilename();
+ reportErrors(reactComponents, filename);
+ }
+ };
+};
+
+module.exports.schema = []; | |
c51db7e3983d631228cd39f2ee6ac1d840104e28 | doubly-linked-list.js | doubly-linked-list.js | "use strict";
// DOUBLY-LINKED LIST
// define constructor
function Node(val) {
this.data = val;
this.previous = null;
this.next = null;
}
| Define constructor for doubly linked list | Define constructor for doubly linked list
| JavaScript | mit | derekmpham/interview-prep,derekmpham/interview-prep | ---
+++
@@ -0,0 +1,10 @@
+"use strict";
+
+// DOUBLY-LINKED LIST
+
+// define constructor
+function Node(val) {
+ this.data = val;
+ this.previous = null;
+ this.next = null;
+} | |
988347f27393de2cd643c29aad772d13df170189 | shared/util/typed-connect.js | shared/util/typed-connect.js | // @flow
import {Component} from 'react'
import {connect} from 'react-redux'
type TypedMergeProps<State, Dispatch, OwnProps, Props> = (state: State, dispatch: Dispatch, ownProps: OwnProps) => Props
export class ConnectedComponent<OwnProps> extends Component<void, OwnProps, void> {}
export default function typedConnect<State, Dispatch, OwnProps, Props> (mergeProps: TypedMergeProps<State, Dispatch, OwnProps, Props>): (smartComponent: ReactClass<Props>) => Class<ConnectedComponent<OwnProps>> {
return connect(
state => ({state}),
dispatch => ({dispatch}),
({state}, {dispatch}, ownProps) => {
return mergeProps(state, dispatch, ownProps)
}
)
}
| Add typedConnect to let smart components in on the action | Add typedConnect to let smart components in on the action
| JavaScript | bsd-3-clause | keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client | ---
+++
@@ -0,0 +1,18 @@
+// @flow
+
+import {Component} from 'react'
+import {connect} from 'react-redux'
+
+type TypedMergeProps<State, Dispatch, OwnProps, Props> = (state: State, dispatch: Dispatch, ownProps: OwnProps) => Props
+
+export class ConnectedComponent<OwnProps> extends Component<void, OwnProps, void> {}
+
+export default function typedConnect<State, Dispatch, OwnProps, Props> (mergeProps: TypedMergeProps<State, Dispatch, OwnProps, Props>): (smartComponent: ReactClass<Props>) => Class<ConnectedComponent<OwnProps>> {
+ return connect(
+ state => ({state}),
+ dispatch => ({dispatch}),
+ ({state}, {dispatch}, ownProps) => {
+ return mergeProps(state, dispatch, ownProps)
+ }
+ )
+} | |
ec3dc4a2824e31bcb526d7873045efaa638b7f5f | migrations/20141007112548-uniqueromvariants.js | migrations/20141007112548-uniqueromvariants.js | module.exports = {
up: function(migration, DataTypes, done) {
migration.removeIndex('Incrementals', 'Incrementals_UniqueFilePerDirectory');
migration.addIndex(
'Incrementals',
[ 'RomVariantId', 'filename' ],
{
indexName: 'Incrementals_UniqueFilePerRomVariant',
indicesType: 'UNIQUE',
}
);
done();
},
down: function(migration, DataTypes, done) {
migration.removeIndex('Incrementals', 'Incrementals_UniqueFilePerRomVariant');
migration.addIndex(
'Incrementals',
[ 'subdirectory', 'filename' ],
{
indexName: 'Incrementals_UniqueFilePerDirectory',
indicesType: 'UNIQUE',
}
);
done()
}
}
| Add a unique index for the rom variant. | Add a unique index for the rom variant.
| JavaScript | mit | xdarklight/cm-update-server,xdarklight/cm-update-server,TheNameIsNigel/cm-update-server,TheNameIsNigel/cm-update-server | ---
+++
@@ -0,0 +1,31 @@
+module.exports = {
+ up: function(migration, DataTypes, done) {
+ migration.removeIndex('Incrementals', 'Incrementals_UniqueFilePerDirectory');
+
+ migration.addIndex(
+ 'Incrementals',
+ [ 'RomVariantId', 'filename' ],
+ {
+ indexName: 'Incrementals_UniqueFilePerRomVariant',
+ indicesType: 'UNIQUE',
+ }
+ );
+
+ done();
+ },
+
+ down: function(migration, DataTypes, done) {
+ migration.removeIndex('Incrementals', 'Incrementals_UniqueFilePerRomVariant');
+
+ migration.addIndex(
+ 'Incrementals',
+ [ 'subdirectory', 'filename' ],
+ {
+ indexName: 'Incrementals_UniqueFilePerDirectory',
+ indicesType: 'UNIQUE',
+ }
+ );
+
+ done()
+ }
+} | |
68d195f515efc4aab1fa9bcc69f4df151c886d17 | generators/REACT_SCRIPTS/template/.storybook/config.js | generators/REACT_SCRIPTS/template/.storybook/config.js | import { configure } from '@kadira/storybook';
import '../src/index.css';
function loadStories() {
require('../src/stories');
}
configure(loadStories, module);
| import { configure } from '@kadira/storybook';
function loadStories() {
require('../src/stories');
}
configure(loadStories, module);
| Remove index.css import for CRA based apps. | Remove index.css import for CRA based apps.
| JavaScript | mit | enjoylife/storybook,rhalff/storybook,enjoylife/storybook,storybooks/react-storybook,nfl/react-storybook,shilman/storybook,storybooks/storybook,nfl/react-storybook,jribeiro/storybook,kadirahq/react-storybook,bigassdragon/storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook,jribeiro/storybook,bigassdragon/storybook,storybooks/react-storybook,enjoylife/storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,rhalff/storybook,shilman/storybook,storybooks/react-storybook,storybooks/storybook,bigassdragon/storybook,nfl/react-storybook,enjoylife/storybook,rhalff/storybook,shilman/storybook,shilman/storybook,nfl/react-storybook,jribeiro/storybook,rhalff/storybook,rhalff/storybook,jribeiro/storybook,kadirahq/react-storybook,rhalff/storybook,bigassdragon/storybook | ---
+++
@@ -1,5 +1,4 @@
import { configure } from '@kadira/storybook';
-import '../src/index.css';
function loadStories() {
require('../src/stories'); |
945a11ece943e8d4bde889b297905a88150eef78 | utils/seed_test_cases.js | utils/seed_test_cases.js | var str = "[";
for (var seedVal = 0; seedVal < 256; seedVal++) {
var a = -3969392806;
var b = -1780940711;
var c = -1021952437;
var d = 255990488;
var e = -651539848;
var f = -1525007287;
var g = -990909925;
var h = 811634969;
var results = [];
for (var i = 0; i < 256; i++) {
results[i] = seedVal;
}
var memory = [];
for (var i = 0; i < 256; i += 8) {
a += results[i];
b += results[i + 1];
c += results[i + 2];
d += results[i + 3];
e += results[i + 4];
f += results[i + 5];
g += results[i + 6];
h += results[i + 7];
a ^= b << 11;
d += a;
b += c;
b ^= c >>> 2;
e += b;
c += d;
c ^= d << 8;
f += c;
d += e;
d ^= e >>> 16;
g += d;
e += f;
e ^= f << 10;
h += e;
f += g;
f ^= g >>> 4;
a += f;
g += h;
g ^= h << 8;
b += g;
h += a;
h ^= a >>> 9;
c += h;
a += b;
memory[i] = a;
memory[i + 1] = b;
memory[i + 2] = c;
memory[i + 3] = d;
memory[i + 4] = e;
memory[i + 5] = f;
memory[i + 6] = g;
memory[i + 7] = h;
}
for (var i in memory) {
str += "[" + i + ", " + seedVal + ", " + memory[i] + ", ";
}
}
str += "]";
console.log(str);
| Create script for getting seed test cases | Create script for getting seed test cases
| JavaScript | mit | Jameskmonger/isaac-crypto | ---
+++
@@ -0,0 +1,72 @@
+var str = "[";
+
+for (var seedVal = 0; seedVal < 256; seedVal++) {
+ var a = -3969392806;
+ var b = -1780940711;
+ var c = -1021952437;
+ var d = 255990488;
+ var e = -651539848;
+ var f = -1525007287;
+ var g = -990909925;
+ var h = 811634969;
+
+ var results = [];
+
+ for (var i = 0; i < 256; i++) {
+ results[i] = seedVal;
+ }
+
+ var memory = [];
+
+ for (var i = 0; i < 256; i += 8) {
+ a += results[i];
+ b += results[i + 1];
+ c += results[i + 2];
+ d += results[i + 3];
+ e += results[i + 4];
+ f += results[i + 5];
+ g += results[i + 6];
+ h += results[i + 7];
+
+ a ^= b << 11;
+ d += a;
+ b += c;
+ b ^= c >>> 2;
+ e += b;
+ c += d;
+ c ^= d << 8;
+ f += c;
+ d += e;
+ d ^= e >>> 16;
+ g += d;
+ e += f;
+ e ^= f << 10;
+ h += e;
+ f += g;
+ f ^= g >>> 4;
+ a += f;
+ g += h;
+ g ^= h << 8;
+ b += g;
+ h += a;
+ h ^= a >>> 9;
+ c += h;
+ a += b;
+
+ memory[i] = a;
+ memory[i + 1] = b;
+ memory[i + 2] = c;
+ memory[i + 3] = d;
+ memory[i + 4] = e;
+ memory[i + 5] = f;
+ memory[i + 6] = g;
+ memory[i + 7] = h;
+ }
+
+ for (var i in memory) {
+ str += "[" + i + ", " + seedVal + ", " + memory[i] + ", ";
+ }
+}
+str += "]";
+
+console.log(str); | |
e99435374eb3b53bf5e1e88226976a0aacefc7f8 | remove-the-minimum.js | remove-the-minimum.js | // https://www.codewars.com/kata/remove-the-minimum
const removeSmallest = numbers => {
const smallest = Math.min(...numbers);
const smallestIndex = numbers.findIndex(number => number === smallest);
const result = [...numbers];
result.splice(smallestIndex, 1);
return result;
};
| Add solution for "remove the minimum" | Add solution for "remove the minimum"
| JavaScript | mit | jonathanweiss/codewars | ---
+++
@@ -0,0 +1,11 @@
+// https://www.codewars.com/kata/remove-the-minimum
+
+const removeSmallest = numbers => {
+ const smallest = Math.min(...numbers);
+ const smallestIndex = numbers.findIndex(number => number === smallest);
+ const result = [...numbers];
+
+ result.splice(smallestIndex, 1);
+
+ return result;
+}; | |
cb0bea819f71afa4f01e8856e252c17aa177c1d9 | 17/amqp-broadcast-bind.js | 17/amqp-broadcast-bind.js | var amqp = require('amqp');
var connection = amqp.createConnection({
host: 'localhost'
});
connection.on('ready', function () {
connection.exchange('broadcast', { type: 'fanout', autoDelete: false },
function(exchange) {
connection.queue('tmp-' + Math.random, { exclusive: true }, function(q) {
q.bind(exchange, '');
q.subscribe(function(message) {
console.log(message);
});
});
});
}); | Add the example to subscribe the broadcast via amqp. | Add the example to subscribe the broadcast via amqp.
| JavaScript | mit | nicebook/Node.js-Reference,nicebook/Node.js-Reference,nicebook/Node.js-Reference | ---
+++
@@ -0,0 +1,18 @@
+var amqp = require('amqp');
+
+var connection = amqp.createConnection({
+ host: 'localhost'
+});
+
+connection.on('ready', function () {
+ connection.exchange('broadcast', { type: 'fanout', autoDelete: false },
+ function(exchange) {
+ connection.queue('tmp-' + Math.random, { exclusive: true }, function(q) {
+ q.bind(exchange, '');
+ q.subscribe(function(message) {
+ console.log(message);
+ });
+
+ });
+ });
+}); | |
0ee01508243586e88b56b32f7089a00ce8eca4cc | app/assets/javascripts/factoid.js | app/assets/javascripts/factoid.js | $(document).ready(function(){
$("body").on("click", "#new-facts button", function(event){
event.preventDefault();
$.ajax({
url: "/factoids",
type: "get"
}).done(function(resp){
$("#factoid-display").empty().append(resp);
}).fail(function(respo){
console.log(Error("Couldn't reload facts"));
});
});
}); | Write ajax call for new facts. | Write ajax call for new facts.
| JavaScript | mit | lukert33/about_luke_thomas,lukert33/about_luke_thomas,lukert33/about_luke_thomas | ---
+++
@@ -0,0 +1,16 @@
+$(document).ready(function(){
+
+ $("body").on("click", "#new-facts button", function(event){
+ event.preventDefault();
+
+ $.ajax({
+ url: "/factoids",
+ type: "get"
+ }).done(function(resp){
+ $("#factoid-display").empty().append(resp);
+ }).fail(function(respo){
+ console.log(Error("Couldn't reload facts"));
+ });
+ });
+
+}); | |
92fafb2e0ee21222aba97084998ac1ca8ef38c6f | server/node-server.js | server/node-server.js | var express = require('express');
var app = express();
var path = __dirname + '';
var port = 8080;
app.use(express.static(path));
app.get('*', function(req, res) {
res.sendFile(path + '/index.html');
});
app.listen(port);
| Add custom Node.js server written with Express. | Add custom Node.js server written with Express.
| JavaScript | mit | emc-mongoose/console,emc-mongoose/console,emc-mongoose/console | ---
+++
@@ -0,0 +1,11 @@
+var express = require('express');
+var app = express();
+
+var path = __dirname + '';
+var port = 8080;
+
+app.use(express.static(path));
+app.get('*', function(req, res) {
+ res.sendFile(path + '/index.html');
+});
+app.listen(port); | |
60b69b21c56edffe45e60e9cb8ab4d1bff7f1726 | 7/archiver-zip-bulk.js | 7/archiver-zip-bulk.js | var fs = require('fs');
var archiver = require('archiver');
var output = fs.createWriteStream('output.zip');
output.on('close', function() {
console.log('Done');
});
var archive = archiver('zip');
archive.on('error', function(err) {
throw err;
});
archive.pipe(output);
archive.bulk([
{ expand: true, cwd: 'dir/', src: ['*.txt'] }
]);
archive.finalize();
| Add the example to create a zip file with multiple files by archiver. | Add the example to create a zip file with multiple files by archiver.
| JavaScript | mit | nicebook/Node.js-Reference,nicebook/Node.js-Reference,nicebook/Node.js-Reference | ---
+++
@@ -0,0 +1,20 @@
+var fs = require('fs');
+var archiver = require('archiver');
+
+var output = fs.createWriteStream('output.zip');
+output.on('close', function() {
+ console.log('Done');
+});
+
+var archive = archiver('zip');
+archive.on('error', function(err) {
+ throw err;
+});
+
+archive.pipe(output);
+
+archive.bulk([
+ { expand: true, cwd: 'dir/', src: ['*.txt'] }
+]);
+
+archive.finalize(); | |
39d080cfca62991c5f57de38a77bd30c61bbabb0 | corehq/couchapps/exports_forms/views/attachments/map.js | corehq/couchapps/exports_forms/views/attachments/map.js | function (doc) {
var media = 0, attachments = {}, value;
if (doc.doc_type === "XFormInstance") {
if (doc.xmlns) {
for (var key in doc._attachments) {
if (doc._attachments.hasOwnProperty(key) &&
doc._attachments[key].content_type !== "text/xml") {
media += 1;
attachments[key] = doc._attachments[key];
}
}
if (media > 0) {
value = {
xmlns: doc.xmlns,
attachments: attachments,
date: doc.received_on
};
emit([doc.domain, doc.app_id, doc.xmlns, doc.received_on], value);
}
}
}
}
| Add couch view for attachments | Add couch view for attachments
| JavaScript | bsd-3-clause | qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,puttarajubr/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq | ---
+++
@@ -0,0 +1,23 @@
+function (doc) {
+ var media = 0, attachments = {}, value;
+
+ if (doc.doc_type === "XFormInstance") {
+ if (doc.xmlns) {
+ for (var key in doc._attachments) {
+ if (doc._attachments.hasOwnProperty(key) &&
+ doc._attachments[key].content_type !== "text/xml") {
+ media += 1;
+ attachments[key] = doc._attachments[key];
+ }
+ }
+ if (media > 0) {
+ value = {
+ xmlns: doc.xmlns,
+ attachments: attachments,
+ date: doc.received_on
+ };
+ emit([doc.domain, doc.app_id, doc.xmlns, doc.received_on], value);
+ }
+ }
+ }
+} | |
70b7c22e48a21079a379ced7d895d489fc96e65d | Greasemonkey/apple-documentation.user.js | Greasemonkey/apple-documentation.user.js | // ==UserScript==
// @name Apple documentation class link
// @namespace https://franklinyu.github.io/
// @version 0.1
// @description create link for classes in code segments
// @author Franklin Yu
// @include https://developer.apple.com/reference/*
// @grant none
// ==/UserScript==
for (let span of document.getElementsByClassName('syntax-type')) {
let className = span.textContent;
let xhr = new XMLHttpRequest();
if (! /^\w+$/.test(className)) {
console.warn("class name not recognized in", span);
continue;
}
xhr.open('GET', '/search/search_data.php?&q=' + className);
xhr.onreadystatechange = function() {
if (this.readyState != 4)
return;
if (this.status == 200) {
let result = JSON.parse(this.responseText).results[0];
if (result.title === className) {
let anchor = document.createElement('A'); // HTMLAnchorElement
anchor.href = result.url;
span.replaceWith(anchor);
anchor.appendChild(span);
} else {
console.warn("can't find %s in search results.", className);
console.info('request:', this);
}
} else {
console.error("get %s when searching class %s", this.statusText, className);
console.info('request:', this);
}
};
xhr.send();
}
| Add script to help finding Apple documentation | Add script to help finding Apple documentation
| JavaScript | mit | franklinyu/snippets,franklinyu/snippets,franklinyu/snippets | ---
+++
@@ -0,0 +1,39 @@
+// ==UserScript==
+// @name Apple documentation class link
+// @namespace https://franklinyu.github.io/
+// @version 0.1
+// @description create link for classes in code segments
+// @author Franklin Yu
+// @include https://developer.apple.com/reference/*
+// @grant none
+// ==/UserScript==
+
+for (let span of document.getElementsByClassName('syntax-type')) {
+ let className = span.textContent;
+ let xhr = new XMLHttpRequest();
+ if (! /^\w+$/.test(className)) {
+ console.warn("class name not recognized in", span);
+ continue;
+ }
+ xhr.open('GET', '/search/search_data.php?&q=' + className);
+ xhr.onreadystatechange = function() {
+ if (this.readyState != 4)
+ return;
+ if (this.status == 200) {
+ let result = JSON.parse(this.responseText).results[0];
+ if (result.title === className) {
+ let anchor = document.createElement('A'); // HTMLAnchorElement
+ anchor.href = result.url;
+ span.replaceWith(anchor);
+ anchor.appendChild(span);
+ } else {
+ console.warn("can't find %s in search results.", className);
+ console.info('request:', this);
+ }
+ } else {
+ console.error("get %s when searching class %s", this.statusText, className);
+ console.info('request:', this);
+ }
+ };
+ xhr.send();
+} | |
60995e57bc9e1b417693231f1818faf80feff641 | src/es5.js | src/es5.js | var isES5 = (function(){
"use strict";
return this === void 0;
})();
if (isES5) {
module.exports = {
freeze: Object.freeze,
defineProperty: Object.defineProperty,
keys: Object.keys,
getPrototypeOf: Object.getPrototypeOf,
isArray: Array.isArray,
isES5: isES5
};
}
else {
var has = {}.hasOwnProperty;
var str = {}.toString;
var proto = {}.constructor.prototype;
function ObjectKeys(o) {
var ret = [];
for (var key in o) {
if (has.call(o, key)) {
ret.push(key);
}
}
return ret;
}
function ObjectDefineProperty(o, key, desc) {
o[key] = desc.value;
return o;
}
function ObjectFreeze(obj) {
return obj;
}
function ObjectGetPrototypeOf(obj) {
try {
return Object(obj).constructor.prototype;
}
catch (e) {
return proto;
}
}
function ArrayIsArray(obj) {
try {
return str.call(obj) === "[object Array]";
}
catch(e) {
return false;
}
}
module.exports = {
isArray: ArrayIsArray,
keys: ObjectKeys,
defineProperty: ObjectDefineProperty,
freeze: ObjectFreeze,
getPrototypeOf: ObjectGetPrototypeOf,
isES5: isES5
};
}
| var isES5 = (function(){
"use strict";
return this === void 0;
})();
if (isES5) {
module.exports = {
freeze: Object.freeze,
defineProperty: Object.defineProperty,
keys: Object.keys,
getPrototypeOf: Object.getPrototypeOf,
isArray: Array.isArray,
isES5: isES5
};
}
else {
var has = {}.hasOwnProperty;
var str = {}.toString;
var proto = {}.constructor.prototype;
var ObjectKeys = function ObjectKeys(o) {
var ret = [];
for (var key in o) {
if (has.call(o, key)) {
ret.push(key);
}
}
return ret;
}
var ObjectDefineProperty = function ObjectDefineProperty(o, key, desc) {
o[key] = desc.value;
return o;
}
var ObjectFreeze = function ObjectFreeze(obj) {
return obj;
}
var ObjectGetPrototypeOf = function ObjectGetPrototypeOf(obj) {
try {
return Object(obj).constructor.prototype;
}
catch (e) {
return proto;
}
}
var ArrayIsArray = function ArrayIsArray(obj) {
try {
return str.call(obj) === "[object Array]";
}
catch(e) {
return false;
}
}
module.exports = {
isArray: ArrayIsArray,
keys: ObjectKeys,
defineProperty: ObjectDefineProperty,
freeze: ObjectFreeze,
getPrototypeOf: ObjectGetPrototypeOf,
isES5: isES5
};
}
| Change function defs to variable defs in block scope. | Change function defs to variable defs in block scope.
Function definitions in blocks cause chrome to throw syntax error in
strict mode.
| JavaScript | mit | alubbe/bluebird,xbenjii/bluebird,bjonica/bluebird,peterKaleta/bluebird,vladikoff/bluebird,code-monkeys/bluebird,sequelize/bluebird,davyengone/bluebird,kidaa/bluebird,janmeier/bluebird,timnew/bluebird,mdarveau/bluebird,bsiddiqui/bluebird,STRML/bluebird,code-monkeys/bluebird,wainage/bluebird,xdevelsistemas/bluebird,Wanderfalke/bluebird,goofiw/bluebird,djchie/bluebird,goofiw/bluebird,iarna/promisable-bluebird,angelxmoreno/bluebird,whatupdave/bluebird,DeX3/bluebird,impy88/bluebird,lindenle/bluebird,BigDSK/bluebird,tesfaldet/bluebird,sandrinodimattia/bluebird,Zeratul5/bluebird,soyuka/bluebird,developmentstudio/bluebird,goopscoop/bluebird,BigDSK/bluebird,cwhatley/bluebird,RobinQu/bluebird,TechnicalPursuit/bluebird,JaKXz/bluebird,tesfaldet/bluebird,atom-morgan/bluebird,garysye/bluebird,rrpod/bluebird,briandela/bluebird,whatupdave/bluebird,P-Seebauer/bluebird,jozanza/bluebird,soyuka/bluebird,ryanwholey/bluebird,ryanwholey/bluebird,paulcbetts/bluebird,joemcelroy/bluebird,satyadeepk/bluebird,illahi0/bluebird,moretti/bluebird,Scientifik/bluebird,ajitsy/bluebird,kidaa/bluebird,angelxmoreno/bluebird,robertn702/bluebird,henryqdineen/bluebird,gillesdemey/bluebird,javraindawn/bluebird,P-Seebauer/bluebird,ricardo-hdz/bluebird,ziad-saab/bluebird,reggi/bluebird,migclark/bluebird,perfecting/bluebird,TechnicalPursuit/bluebird,yonjah/bluebird,yonjah/bluebird,ScheerMT/bluebird,javraindawn/bluebird,goopscoop/bluebird,ricardo-hdz/bluebird,cwhatley/bluebird,akinsella/bluebird,DeX3/bluebird,Zeratul5/bluebird,kjvalencik/bluebird,DrewVartanian/bluebird,fadzlan/bluebird,impy88/bluebird,moretti/bluebird,yonjah/bluebird,matklad/bluebird,esco/bluebird,justsml/bluebird,lo1tuma/bluebird,xbenjii/bluebird,naoufal/bluebird,whatupdave/bluebird,ronaldbaltus/bluebird,amelon/bluebird,jozanza/bluebird,spion/bluebird,soyuka/bluebird,TechnicalPursuit/bluebird,xbenjii/bluebird,JaKXz/bluebird,abhishekgahlot/bluebird,justsml/bluebird,RobinQu/bluebird,JaKXz/bluebird,vladikoff/bluebird,StefanoDeVuono/bluebird,cusspvz/bluebird,BridgeAR/bluebird,developmentstudio/bluebird,naoufal/bluebird,johnculviner/bluebird,petkaantonov/bluebird,techniq/bluebird,wainage/bluebird,perfecting/bluebird,perfecting/bluebird,n1kolas/bluebird,janzal/bluebird,djchie/bluebird,cgvarela/bluebird,gillesdemey/bluebird,enicolasWebs/bluebird,robertn702/bluebird,wainage/bluebird,ankushg/bluebird,HBOCodeLabs/bluebird,mcanthony/bluebird,johnculviner/bluebird,petkaantonov/bluebird,ronaldbaltus/bluebird,fadzlan/bluebird,bsiddiqui/bluebird,satyadeepk/bluebird,xdevelsistemas/bluebird,cgvarela/bluebird,codevlabs/bluebird,developmentstudio/bluebird,linalu1/bluebird,codevlabs/bluebird,impy88/bluebird,naoufal/bluebird,janzal/bluebird,starkwang/bluebird,avinoamr/bluebird,tpphu/bluebird,n1kolas/bluebird,DrewVartanian/bluebird,Wanderfalke/bluebird,kjvalencik/bluebird,P-Seebauer/bluebird,BigDSK/bluebird,angelxmoreno/bluebird,dantheuber/bluebird,janzal/bluebird,reggi/bluebird,a25patel/bluebird,StefanoDeVuono/bluebird,lindenle/bluebird,paulcbetts/bluebird,StefanoDeVuono/bluebird,reggi/bluebird,amelon/bluebird,mcanthony/bluebird,migclark/bluebird,timnew/bluebird,garysye/bluebird,codevlabs/bluebird,xdevelsistemas/bluebird,ziad-saab/bluebird,a25patel/bluebird,akinsella/bluebird,davyengone/bluebird,ankushg/bluebird,haohui/bluebird,techniq/bluebird,satyadeepk/bluebird,goopscoop/bluebird,STRML/bluebird,johnculviner/bluebird,BridgeAR/bluebird,DeX3/bluebird,henryqdineen/bluebird,ronaldbaltus/bluebird,mdarveau/bluebird,starkwang/bluebird,ScheerMT/bluebird,javraindawn/bluebird,BridgeAR/bluebird,moretti/bluebird,matklad/bluebird,sandrinodimattia/bluebird,peterKaleta/bluebird,avinoamr/bluebird,haohui/bluebird,atom-morgan/bluebird,paulcbetts/bluebird,illahi0/bluebird,fmoliveira/bluebird,cwhatley/bluebird,fadzlan/bluebird,briandela/bluebird,peterKaleta/bluebird,abhishekgahlot/bluebird,janmeier/bluebird,bjonica/bluebird,tpphu/bluebird,linalu1/bluebird,sequelize/bluebird,arenaonline/bluebird,bjonica/bluebird,briandela/bluebird,cgvarela/bluebird,jozanza/bluebird,ajitsy/bluebird,joemcelroy/bluebird,enicolasWebs/bluebird,mcanthony/bluebird,fmoliveira/bluebird,arenaonline/bluebird,avinoamr/bluebird,goofiw/bluebird,RobinQu/bluebird,bsiddiqui/bluebird,ricardo-hdz/bluebird,janmeier/bluebird,starkwang/bluebird,justsml/bluebird,fmoliveira/bluebird,gillesdemey/bluebird,robertn702/bluebird,ajitsy/bluebird,esco/bluebird,atom-morgan/bluebird,alubbe/bluebird,cusspvz/bluebird,kidaa/bluebird,alubbe/bluebird,mdarveau/bluebird,lindenle/bluebird,sequelize/bluebird,esco/bluebird,amelon/bluebird,timnew/bluebird,ydaniv/bluebird,akinsella/bluebird,rrpod/bluebird,ryanwholey/bluebird,HBOCodeLabs/bluebird,Scientifik/bluebird,rrpod/bluebird,linalu1/bluebird,ScheerMT/bluebird,migclark/bluebird,haohui/bluebird,arenaonline/bluebird,spion/bluebird,cusspvz/bluebird,n1kolas/bluebird,HBOCodeLabs/bluebird,techniq/bluebird,DrewVartanian/bluebird,joemcelroy/bluebird,ankushg/bluebird,kjvalencik/bluebird,tesfaldet/bluebird,enicolasWebs/bluebird,ziad-saab/bluebird,matklad/bluebird,Scientifik/bluebird,djchie/bluebird,abhishekgahlot/bluebird,lo1tuma/bluebird,a25patel/bluebird,garysye/bluebird,code-monkeys/bluebird,petkaantonov/bluebird,dantheuber/bluebird,lo1tuma/bluebird,davyengone/bluebird,tpphu/bluebird,Wanderfalke/bluebird,vladikoff/bluebird,dantheuber/bluebird,henryqdineen/bluebird,sandrinodimattia/bluebird,ydaniv/bluebird,ydaniv/bluebird,Zeratul5/bluebird,illahi0/bluebird,STRML/bluebird | ---
+++
@@ -19,7 +19,7 @@
var str = {}.toString;
var proto = {}.constructor.prototype;
- function ObjectKeys(o) {
+ var ObjectKeys = function ObjectKeys(o) {
var ret = [];
for (var key in o) {
if (has.call(o, key)) {
@@ -29,16 +29,16 @@
return ret;
}
- function ObjectDefineProperty(o, key, desc) {
+ var ObjectDefineProperty = function ObjectDefineProperty(o, key, desc) {
o[key] = desc.value;
return o;
}
- function ObjectFreeze(obj) {
+ var ObjectFreeze = function ObjectFreeze(obj) {
return obj;
}
- function ObjectGetPrototypeOf(obj) {
+ var ObjectGetPrototypeOf = function ObjectGetPrototypeOf(obj) {
try {
return Object(obj).constructor.prototype;
}
@@ -47,7 +47,7 @@
}
}
- function ArrayIsArray(obj) {
+ var ArrayIsArray = function ArrayIsArray(obj) {
try {
return str.call(obj) === "[object Array]";
} |
86f58920fea9f9773c64fb598139a795ba4bc2cc | client/src/reducers/reducer_broadcast.js | client/src/reducers/reducer_broadcast.js | import {SAVE_BROADCAST} from '../actions/index';
export default function (state=[], action) {
switch (action.type){
case SAVE_BROADCAST:
return state.concat([action.payload.data]);
}
return state;
} | Create reducer that listens to SAVE_BROADCAST actions. | Create reducer that listens to SAVE_BROADCAST actions.
| JavaScript | mit | TeamDreamStream/GigRTC,AuggieH/GigRTC,kat09kat09/GigRTC,AuggieH/GigRTC,TeamDreamStream/GigRTC,kat09kat09/GigRTC | ---
+++
@@ -0,0 +1,9 @@
+import {SAVE_BROADCAST} from '../actions/index';
+
+export default function (state=[], action) {
+ switch (action.type){
+ case SAVE_BROADCAST:
+ return state.concat([action.payload.data]);
+ }
+ return state;
+} | |
11a8b02e97884f77c8c1f9720acc64dd9026e503 | test/util/content-disposition.js | test/util/content-disposition.js | var assert = require('assert');
var contentDisposition = require('../../lib/util/content-disposition');
describe('contentDisposition', function() {
it('returns attachment for no file name', function() {
assert.equal(contentDisposition(), 'attachment');
});
it('returns file name', function() {
assert.equal(contentDisposition('test.txt'),
'attachment; filename="test.txt"');
});
it('returns utf-8 encoded for non-ASCII files', function() {
var file = 'fañcy.txt';
assert.equal(contentDisposition(file),
'attachment; filename="' + encodeURI(file) +'";'
+ ' filename*=UTF-8\'\'' + encodeURI(file));
});
});
| Add full coverage for contentDisposition utility | Add full coverage for contentDisposition utility
| JavaScript | mit | itsananderson/molded | ---
+++
@@ -0,0 +1,18 @@
+var assert = require('assert');
+var contentDisposition = require('../../lib/util/content-disposition');
+
+describe('contentDisposition', function() {
+ it('returns attachment for no file name', function() {
+ assert.equal(contentDisposition(), 'attachment');
+ });
+ it('returns file name', function() {
+ assert.equal(contentDisposition('test.txt'),
+ 'attachment; filename="test.txt"');
+ });
+ it('returns utf-8 encoded for non-ASCII files', function() {
+ var file = 'fañcy.txt';
+ assert.equal(contentDisposition(file),
+ 'attachment; filename="' + encodeURI(file) +'";'
+ + ' filename*=UTF-8\'\'' + encodeURI(file));
+ });
+}); | |
bbe6a5c7fd28324bf5ce8df345ac97e2182db570 | packages/gatsby/src/cache-dir/register-service-worker.js | packages/gatsby/src/cache-dir/register-service-worker.js | import emitter from "./emitter"
if (`serviceWorker` in navigator) {
navigator.serviceWorker
.register(`sw.js`)
.then(function(reg) {
reg.addEventListener(`updatefound`, () => {
// The updatefound event implies that reg.installing is set; see
// https://w3c.github.io/ServiceWorker/#service-worker-registration-updatefound-event
const installingWorker = reg.installing
console.log(`installingWorker`, installingWorker)
installingWorker.addEventListener(`statechange`, () => {
switch (installingWorker.state) {
case `installed`:
if (navigator.serviceWorker.controller) {
// At this point, the old content will have been purged and the fresh content will
// have been added to the cache.
// We reload immediately so the user sees the new content.
// This could/should be made configurable in the future.
window.location.reload()
} else {
// At this point, everything has been precached.
// It's the perfect time to display a "Content is cached for offline use." message.
console.log(`Content is now available offline!`)
emitter.emit(`sw:installed`)
}
break
case `redundant`:
console.error(`The installing service worker became redundant.`)
break
}
})
})
})
.catch(function(e) {
console.error(`Error during service worker registration:`, e)
})
}
| import emitter from "./emitter"
let pathPrefix = `/`
if (__PREFIX_PATHS__) {
pathPrefix = __PATH_PREFIX__
}
if (`serviceWorker` in navigator) {
navigator.serviceWorker
.register(`${pathPrefix}sw.js`)
.then(function(reg) {
reg.addEventListener(`updatefound`, () => {
// The updatefound event implies that reg.installing is set; see
// https://w3c.github.io/ServiceWorker/#service-worker-registration-updatefound-event
const installingWorker = reg.installing
console.log(`installingWorker`, installingWorker)
installingWorker.addEventListener(`statechange`, () => {
switch (installingWorker.state) {
case `installed`:
if (navigator.serviceWorker.controller) {
// At this point, the old content will have been purged and the fresh content will
// have been added to the cache.
// We reload immediately so the user sees the new content.
// This could/should be made configurable in the future.
window.location.reload()
} else {
// At this point, everything has been precached.
// It's the perfect time to display a "Content is cached for offline use." message.
console.log(`Content is now available offline!`)
emitter.emit(`sw:installed`)
}
break
case `redundant`:
console.error(`The installing service worker became redundant.`)
break
}
})
})
})
.catch(function(e) {
console.error(`Error during service worker registration:`, e)
})
}
| Support path prefixes for service workers | Support path prefixes for service workers
| JavaScript | mit | 0x80/gatsby,gatsbyjs/gatsby,chiedo/gatsby,okcoker/gatsby,danielfarrell/gatsby,mingaldrichgan/gatsby,ChristopherBiscardi/gatsby,danielfarrell/gatsby,0x80/gatsby,gatsbyjs/gatsby,mingaldrichgan/gatsby,chiedo/gatsby,gatsbyjs/gatsby,ChristopherBiscardi/gatsby,mingaldrichgan/gatsby,ChristopherBiscardi/gatsby,fk/gatsby,danielfarrell/gatsby,Khaledgarbaya/gatsby,chiedo/gatsby,gatsbyjs/gatsby,mickeyreiss/gatsby,fk/gatsby,okcoker/gatsby,mickeyreiss/gatsby,mickeyreiss/gatsby,0x80/gatsby,fabrictech/gatsby,ChristopherBiscardi/gatsby,gatsbyjs/gatsby,Khaledgarbaya/gatsby,fabrictech/gatsby,okcoker/gatsby,fabrictech/gatsby,Khaledgarbaya/gatsby,gatsbyjs/gatsby,fk/gatsby | ---
+++
@@ -1,8 +1,13 @@
import emitter from "./emitter"
+
+let pathPrefix = `/`
+if (__PREFIX_PATHS__) {
+ pathPrefix = __PATH_PREFIX__
+}
if (`serviceWorker` in navigator) {
navigator.serviceWorker
- .register(`sw.js`)
+ .register(`${pathPrefix}sw.js`)
.then(function(reg) {
reg.addEventListener(`updatefound`, () => {
// The updatefound event implies that reg.installing is set; see |
956a4c76ff90d4169d21f90b4ef6f1a33ed787bf | test/renderer/components/cell/cell_spec.js | test/renderer/components/cell/cell_spec.js | import React from 'react';
import {renderIntoDocument} from 'react-addons-test-utils';
import {expect} from 'chai';
import Cell from '../../../../src/notebook/components/cell/cell';
import * as commutable from 'commutable';
describe('Cell', () => {
it('should be able to render a markdown cell', () => {
const cell = renderIntoDocument(
<Cell cell={commutable.emptyMarkdownCell}/>
);
expect(cell).to.not.be.null;
});
});
| Add tests for cell component | Add tests for cell component
| JavaScript | bsd-3-clause | jdetle/nteract,nteract/nteract,jdfreder/nteract,temogen/nteract,jdetle/nteract,jdfreder/nteract,nteract/composition,rgbkrk/nteract,jdfreder/nteract,temogen/nteract,0u812/nteract,temogen/nteract,captainsafia/nteract,rgbkrk/nteract,nteract/nteract,nteract/nteract,nteract/composition,nteract/nteract,jdfreder/nteract,0u812/nteract,nteract/composition,nteract/nteract,jdetle/nteract,rgbkrk/nteract,0u812/nteract,rgbkrk/nteract,captainsafia/nteract,captainsafia/nteract,jdetle/nteract,rgbkrk/nteract,0u812/nteract,captainsafia/nteract | ---
+++
@@ -0,0 +1,16 @@
+import React from 'react';
+
+import {renderIntoDocument} from 'react-addons-test-utils';
+import {expect} from 'chai';
+
+import Cell from '../../../../src/notebook/components/cell/cell';
+import * as commutable from 'commutable';
+
+describe('Cell', () => {
+ it('should be able to render a markdown cell', () => {
+ const cell = renderIntoDocument(
+ <Cell cell={commutable.emptyMarkdownCell}/>
+ );
+ expect(cell).to.not.be.null;
+ });
+}); | |
21efb579e9ed5d925296dfa030afa487d4ce6fd2 | spec/helpers/consolereporter.js | spec/helpers/consolereporter.js | var util = require('util');
var options = {
showColors: true,
print: function () {
process.stdout.write(util.format.apply(this, arguments));
}
};
jasmine.getEnv().addReporter(new jasmine.ConsoleReporter(options)); | Fix jasmine has no output | Fix jasmine has no output
| JavaScript | mit | jean343/Node-OpenMAX,jean343/Node-OMX,jean343/Node-OpenMAX,jean343/Node-OpenMAX,jean343/Node-OMX,jean343/Node-OpenMAX,jean343/Node-OMX,jean343/Node-OMX,jean343/Node-OMX,jean343/Node-OpenMAX,jean343/Node-OMX,jean343/Node-OpenMAX | ---
+++
@@ -0,0 +1,9 @@
+var util = require('util');
+var options = {
+ showColors: true,
+ print: function () {
+ process.stdout.write(util.format.apply(this, arguments));
+ }
+};
+
+jasmine.getEnv().addReporter(new jasmine.ConsoleReporter(options)); | |
a3b1e4c08b61db7cfb09ee82a085621ec19da8d1 | modules/errors/errors.js | modules/errors/errors.js | /**
* Meters the number of page errors, and provides traces after notices.
*/
exports.version = '0.1';
exports.module = function(phantomas) {
var errors = [];
phantomas.on('pageerror', function(msg, trace) {
errors.push({"msg":msg, "trace":trace});
});
phantomas.on('report', function() {
var len = errors.length || 0;
phantomas.setMetric('errors', len);
if (len > 0) {
errors.forEach(function(e) {
phantomas.addError(e.msg);
e.trace.forEach(function(item) {
var fn = item.function || '(anonymous function)';
phantomas.addError(' ' + fn + ' ' + item.file + ':' + item.line);
});
phantomas.addError();
});
}
});
};
| Add a basic error reporting module. | Add a basic error reporting module.
| JavaScript | bsd-2-clause | gmetais/phantomas,ingoclaro/phantomas,macbre/phantomas,william-p/phantomas,macbre/phantomas,ingoclaro/phantomas,gmetais/phantomas,ingoclaro/phantomas,william-p/phantomas,gmetais/phantomas,macbre/phantomas,william-p/phantomas | ---
+++
@@ -0,0 +1,29 @@
+/**
+ * Meters the number of page errors, and provides traces after notices.
+ */
+
+exports.version = '0.1';
+
+exports.module = function(phantomas) {
+ var errors = [];
+
+ phantomas.on('pageerror', function(msg, trace) {
+ errors.push({"msg":msg, "trace":trace});
+ });
+
+ phantomas.on('report', function() {
+ var len = errors.length || 0;
+ phantomas.setMetric('errors', len);
+
+ if (len > 0) {
+ errors.forEach(function(e) {
+ phantomas.addError(e.msg);
+ e.trace.forEach(function(item) {
+ var fn = item.function || '(anonymous function)';
+ phantomas.addError(' ' + fn + ' ' + item.file + ':' + item.line);
+ });
+ phantomas.addError();
+ });
+ }
+ });
+}; | |
6ba99cb38f453499eb2cf84d0300f96f13584fd0 | code/js/controllers/HoferLifeMusicController.js | code/js/controllers/HoferLifeMusicController.js | ;(function() {
"use strict";
var BaseController = require("BaseController");
new BaseController({
siteName: "LifeStoreFlat",
play: ".player-play-button .icon-play-button",
pause: ".player-play-button .icon-pause2",
playNext: ".player-advance-button",
playPrev: ".player-rewind-button",
like: ".like-button",
dislike: ".dislike-button",
buttonSwitch: true,
song: ".player-track",
artist: ".player-artist"
});
})();
| ;(function() {
"use strict";
var BaseController = require("BaseController");
new BaseController({
siteName: "Hofer life music",
play: ".player-play-button .icon-play-button",
pause: ".player-play-button .icon-pause2",
playNext: ".player-advance-button",
playPrev: ".player-rewind-button",
like: ".like-button",
dislike: ".dislike-button",
buttonSwitch: true,
song: ".player-track",
artist: ".player-artist"
});
})();
| Fix hofer life music Controller name | Fix hofer life music Controller name
| JavaScript | mit | nemchik/streamkeys,nemchik/streamkeys,alexesprit/streamkeys,berrberr/streamkeys,ovcharik/streamkeys,berrberr/streamkeys,alexesprit/streamkeys,nemchik/streamkeys,ovcharik/streamkeys,berrberr/streamkeys | ---
+++
@@ -4,7 +4,7 @@
var BaseController = require("BaseController");
new BaseController({
- siteName: "LifeStoreFlat",
+ siteName: "Hofer life music",
play: ".player-play-button .icon-play-button",
pause: ".player-play-button .icon-pause2",
playNext: ".player-advance-button", |
9de6aaaf8f14e1e91497a34012e8e46de519d7f4 | Sources/Proxy/Core/LookupTableProxy/index.js | Sources/Proxy/Core/LookupTableProxy/index.js | import macro from 'vtk.js/Sources/macro';
import vtkColorMaps from 'vtk.js/Sources/Rendering/Core/ColorTransferFunction/ColorMaps';
import vtkColorTransferFunction from 'vtk.js/Sources/Rendering/Core/ColorTransferFunction';
const DEFAULT_PRESET_NAME = 'Cool to Warm';
// ----------------------------------------------------------------------------
// vtkLookupTableProxy methods
// ----------------------------------------------------------------------------
function vtkLookupTableProxy(publicAPI, model) {
// Set our className
model.classHierarchy.push('vtkLookupTableProxy');
model.lookupTable =
model.lookupTable || vtkColorTransferFunction.newInstance();
// Initialize lookup table
model.presetName = model.presetName || DEFAULT_PRESET_NAME;
model.lookupTable.setVectorModeToMagnitude();
model.lookupTable.applyColorMap(
vtkColorMaps.getPresetByName(model.presetName)
);
model.lookupTable.setMappingRange(model.dataRange[0], model.dataRange[1]);
model.lookupTable.updateRange();
publicAPI.setPresetName = (presetName) => {
if (model.presetName !== presetName) {
model.presetName = presetName;
model.lookupTable.applyColorMap(vtkColorMaps.getPresetByName(presetName));
model.lookupTable.setMappingRange(model.dataRange[0], model.dataRange[1]);
model.lookupTable.updateRange();
publicAPI.modified();
}
};
publicAPI.setDataRange = (min, max) => {
if (model.dataRange[0] !== min || model.dataRange[1] !== max) {
model.dataRange[0] = min;
model.dataRange[1] = max;
model.lookupTable.setMappingRange(model.dataRange[0], model.dataRange[1]);
model.lookupTable.updateRange();
publicAPI.modified();
}
};
}
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
const DEFAULT_VALUES = {
arrayName: 'No array associated',
arrayLocation: 'pointData',
dataRange: [0, 1],
};
// ----------------------------------------------------------------------------
function extend(publicAPI, model, initialValues = {}) {
Object.assign(model, DEFAULT_VALUES, initialValues);
macro.obj(publicAPI, model);
macro.setGet(publicAPI, model, ['arrayName']);
macro.get(publicAPI, model, ['lookupTable', 'presetName', 'dataRange']);
// Object specific methods
vtkLookupTableProxy(publicAPI, model);
// Proxy handling
macro.proxy(publicAPI, model);
}
// ----------------------------------------------------------------------------
export const newInstance = macro.newInstance(extend, 'vtkLookupTableProxy');
// ----------------------------------------------------------------------------
export default { newInstance, extend };
| Add proxy to manage LoookupTable with preset | fix(LookupTableProxy): Add proxy to manage LoookupTable with preset
| JavaScript | bsd-3-clause | Kitware/vtk-js,Kitware/vtk-js,Kitware/vtk-js,Kitware/vtk-js | ---
+++
@@ -0,0 +1,83 @@
+import macro from 'vtk.js/Sources/macro';
+
+import vtkColorMaps from 'vtk.js/Sources/Rendering/Core/ColorTransferFunction/ColorMaps';
+import vtkColorTransferFunction from 'vtk.js/Sources/Rendering/Core/ColorTransferFunction';
+
+const DEFAULT_PRESET_NAME = 'Cool to Warm';
+
+// ----------------------------------------------------------------------------
+// vtkLookupTableProxy methods
+// ----------------------------------------------------------------------------
+
+function vtkLookupTableProxy(publicAPI, model) {
+ // Set our className
+ model.classHierarchy.push('vtkLookupTableProxy');
+
+ model.lookupTable =
+ model.lookupTable || vtkColorTransferFunction.newInstance();
+
+ // Initialize lookup table
+ model.presetName = model.presetName || DEFAULT_PRESET_NAME;
+ model.lookupTable.setVectorModeToMagnitude();
+ model.lookupTable.applyColorMap(
+ vtkColorMaps.getPresetByName(model.presetName)
+ );
+ model.lookupTable.setMappingRange(model.dataRange[0], model.dataRange[1]);
+ model.lookupTable.updateRange();
+
+ publicAPI.setPresetName = (presetName) => {
+ if (model.presetName !== presetName) {
+ model.presetName = presetName;
+ model.lookupTable.applyColorMap(vtkColorMaps.getPresetByName(presetName));
+ model.lookupTable.setMappingRange(model.dataRange[0], model.dataRange[1]);
+ model.lookupTable.updateRange();
+ publicAPI.modified();
+ }
+ };
+
+ publicAPI.setDataRange = (min, max) => {
+ if (model.dataRange[0] !== min || model.dataRange[1] !== max) {
+ model.dataRange[0] = min;
+ model.dataRange[1] = max;
+
+ model.lookupTable.setMappingRange(model.dataRange[0], model.dataRange[1]);
+ model.lookupTable.updateRange();
+
+ publicAPI.modified();
+ }
+ };
+}
+
+// ----------------------------------------------------------------------------
+// Object factory
+// ----------------------------------------------------------------------------
+
+const DEFAULT_VALUES = {
+ arrayName: 'No array associated',
+ arrayLocation: 'pointData',
+ dataRange: [0, 1],
+};
+
+// ----------------------------------------------------------------------------
+
+function extend(publicAPI, model, initialValues = {}) {
+ Object.assign(model, DEFAULT_VALUES, initialValues);
+
+ macro.obj(publicAPI, model);
+ macro.setGet(publicAPI, model, ['arrayName']);
+ macro.get(publicAPI, model, ['lookupTable', 'presetName', 'dataRange']);
+
+ // Object specific methods
+ vtkLookupTableProxy(publicAPI, model);
+
+ // Proxy handling
+ macro.proxy(publicAPI, model);
+}
+
+// ----------------------------------------------------------------------------
+
+export const newInstance = macro.newInstance(extend, 'vtkLookupTableProxy');
+
+// ----------------------------------------------------------------------------
+
+export default { newInstance, extend }; | |
ccfc1237400f0f719e6e17f4372cce18cc0d7692 | utils/streamHandler.js | utils/streamHandler.js | var Tweet = require('../models/Tweet');
var StreamHandler = function(stream, io) {
// Whenever the stream handler passes new tweets...
stream.on('data', function(data) {
var tweet = {
twid: data['id'],
active: false,
author: data['user']['name'],
avatar: data['user']['profile_image_url'],
body: data['text'],
date: data['created_at'],
screenname: data['user']['screen_name']
};
var tweetModel = new Tweet(tweet);
// Save the new tweet to the database
tweetModel.save(function(err) {
if (!err) {
// Notify client app of new tweet
io.emit('tweet', tweet);
}
});
});
};
module.exports = StreamHandler;
| Add stream handler for saving new tweets and emitting data to the client | Add stream handler for saving new tweets and emitting data to the client
| JavaScript | mit | thinkswan/react-twitter-stream,thinkswan/react-twitter-stream | ---
+++
@@ -0,0 +1,28 @@
+var Tweet = require('../models/Tweet');
+
+var StreamHandler = function(stream, io) {
+ // Whenever the stream handler passes new tweets...
+ stream.on('data', function(data) {
+ var tweet = {
+ twid: data['id'],
+ active: false,
+ author: data['user']['name'],
+ avatar: data['user']['profile_image_url'],
+ body: data['text'],
+ date: data['created_at'],
+ screenname: data['user']['screen_name']
+ };
+
+ var tweetModel = new Tweet(tweet);
+
+ // Save the new tweet to the database
+ tweetModel.save(function(err) {
+ if (!err) {
+ // Notify client app of new tweet
+ io.emit('tweet', tweet);
+ }
+ });
+ });
+};
+
+module.exports = StreamHandler; | |
b4aeabeeb81f14505416e0b0c4a5001f422044d2 | test/tap/00-check-mock-dep.js | test/tap/00-check-mock-dep.js | console.log("TAP Version 13")
process.on("uncaughtException", function(er) {
console.log("not ok - Failed checking mock registry dep. Expect much fail!")
console.log("1..1")
process.exit(1)
})
var assert = require("assert")
var semver = require("semver")
var mock = require("npm-registry-mock/package.json").version
var req = require("../../package.json").devDependencies["npm-registry-mock"]
assert(semver.satisfies(mock, req))
console.log("ok")
console.log("1..1")
| Add test to verify npm-registry-mock version | test: Add test to verify npm-registry-mock version
I keep getting myself into weird cases where I have an outdated copy of
npm-registry-mock, and so tests fail, and I spend several minutes digging
only to find that it's because I didn't update after the package.json dep
changed.
Add a test to alert to this situation, which will run BEFORE all the other
tests start failing horribly.
| JavaScript | artistic-2.0 | cchamberlain/npm,yibn2008/npm,lxe/npm,thomblake/npm,rsp/npm,thomblake/npm,Volune/npm,kimshinelove/naver-npm,TimeToogo/npm,DaveEmmerson/npm,segrey/npm,yodeyer/npm,Volune/npm,DIREKTSPEED-LTD/npm,misterbyrne/npm,cchamberlain/npm-msys2,haggholm/npm,ekmartin/npm,yibn2008/npm,yibn2008/npm,lxe/npm,cchamberlain/npm,kimshinelove/naver-npm,xalopp/npm,kimshinelove/naver-npm,segrey/npm,xalopp/npm,rsp/npm,evocateur/npm,evocateur/npm,kemitchell/npm,haggholm/npm,segrey/npm,ekmartin/npm,kemitchell/npm,thomblake/npm,yyx990803/npm,evanlucas/npm,yodeyer/npm,evanlucas/npm,evocateur/npm,chadnickbok/npm,DIREKTSPEED-LTD/npm,yyx990803/npm,misterbyrne/npm,Volune/npm,misterbyrne/npm,cchamberlain/npm,chadnickbok/npm,haggholm/npm,DaveEmmerson/npm,rsp/npm,DIREKTSPEED-LTD/npm,xalopp/npm,ekmartin/npm,cchamberlain/npm-msys2,midniteio/npm,cchamberlain/npm-msys2,yyx990803/npm,midniteio/npm,TimeToogo/npm,yodeyer/npm,DaveEmmerson/npm,princeofdarkness76/npm,midniteio/npm,chadnickbok/npm,TimeToogo/npm,kemitchell/npm,princeofdarkness76/npm,princeofdarkness76/npm,lxe/npm,evanlucas/npm | ---
+++
@@ -0,0 +1,15 @@
+console.log("TAP Version 13")
+
+process.on("uncaughtException", function(er) {
+ console.log("not ok - Failed checking mock registry dep. Expect much fail!")
+ console.log("1..1")
+ process.exit(1)
+})
+
+var assert = require("assert")
+var semver = require("semver")
+var mock = require("npm-registry-mock/package.json").version
+var req = require("../../package.json").devDependencies["npm-registry-mock"]
+assert(semver.satisfies(mock, req))
+console.log("ok")
+console.log("1..1") | |
edd9a17fd5d08514b54ce0450d82dbe055ba762b | mp3-stream.js | mp3-stream.js | var express = require('express');
var app = express();
var fs = require('fs');
app.listen(3000, function() {
console.log("[NodeJS] Application Listening on Port 3000");
});
app.get('/api/play/:key', function(req, res) {
var key = req.params.key;
var music = 'music/' + key + '.mp3';
var stat = fs.statSync(music);
range = req.headers.range;
var readStream;
if (range !== undefined) {
var parts = range.replace(/bytes=/, "").split("-");
var partial_start = parts[0];
var partial_end = parts[1];
if ((isNaN(partial_start) && partial_start.length > 1) || (isNaN(partial_end) && partial_end.length > 1)) {
return res.sendStatus(500); //ERR_INCOMPLETE_CHUNKED_ENCODING
}
var start = parseInt(partial_start, 10);
var end = partial_end ? parseInt(partial_end, 10) : stat.size - 1;
var content_length = (end - start) + 1;
res.status(206).header({
'Content-Type': 'audio/mpeg',
'Content-Length': content_length,
'Content-Range': "bytes " + start + "-" + end + "/" + stat.size
});
readStream = fs.createReadStream(music, {start: start, end: end});
} else {
res.header({
'Content-Type': 'audio/mpeg',
'Content-Length': stat.size
});
readStream = fs.createReadStream(music);
}
readStream.pipe(res);
});
| Add mp3 file streaming example | Add mp3 file streaming example | JavaScript | mit | voidabhi/node-scripts,voidabhi/node-scripts,voidabhi/node-scripts | ---
+++
@@ -0,0 +1,47 @@
+var express = require('express');
+var app = express();
+var fs = require('fs');
+
+app.listen(3000, function() {
+ console.log("[NodeJS] Application Listening on Port 3000");
+});
+
+app.get('/api/play/:key', function(req, res) {
+ var key = req.params.key;
+
+ var music = 'music/' + key + '.mp3';
+
+ var stat = fs.statSync(music);
+ range = req.headers.range;
+ var readStream;
+
+ if (range !== undefined) {
+ var parts = range.replace(/bytes=/, "").split("-");
+
+ var partial_start = parts[0];
+ var partial_end = parts[1];
+
+ if ((isNaN(partial_start) && partial_start.length > 1) || (isNaN(partial_end) && partial_end.length > 1)) {
+ return res.sendStatus(500); //ERR_INCOMPLETE_CHUNKED_ENCODING
+ }
+
+ var start = parseInt(partial_start, 10);
+ var end = partial_end ? parseInt(partial_end, 10) : stat.size - 1;
+ var content_length = (end - start) + 1;
+
+ res.status(206).header({
+ 'Content-Type': 'audio/mpeg',
+ 'Content-Length': content_length,
+ 'Content-Range': "bytes " + start + "-" + end + "/" + stat.size
+ });
+
+ readStream = fs.createReadStream(music, {start: start, end: end});
+ } else {
+ res.header({
+ 'Content-Type': 'audio/mpeg',
+ 'Content-Length': stat.size
+ });
+ readStream = fs.createReadStream(music);
+ }
+ readStream.pipe(res);
+}); | |
fd644a2e6881833fdbbc56c0451235f22b5f8aeb | test/karma.conf.js | test/karma.conf.js | module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath : '',
// frameworks to use
frameworks : [ 'mocha', 'sinon', 'chai-jquery', 'jquery-2.1.0', 'chai' ],
// list of files / patterns to load in the browser
files: [
{
pattern : 'bower_components/underscore/underscore.js',
included: true,
served: true
},
{
pattern : 'bower_components/backbone/backbone.js',
included: true,
served: true
},
{
pattern : '../src/**/*.js',
included: true,
served: true
},
{
pattern : 'specs/**/*.js',
included: true,
served: true
},
{
pattern : 'specs/fixtures/*.html',
included: true,
served: true
},
{
pattern : 'specRunner.js',
included: true,
served: true
}
],
// list of files to exclude
exclude : [],
// test results reporter to use
// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
reporters : [ 'dots', 'coverage' ] ,
preprocessors : {
'../src/**/*.js' : [ 'coverage' ],
'specs/fixtures/*.html' : [ 'html2js' ]
},
coverageReporter : {
type : 'html',
dir : '../coverage/browser/'
},
// web server port
port : 9876,
// enable / disable colors in the output (reporters and logs)
colors : true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel : config.LOG_WARN,
// enable / disable watching file and executing tests whenever any file changes
autoWatch : false,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera (has to be installed with `npm install karma-opera-launcher`)
// - Safari (only Mac; has to be installed with `npm install karma-safari-launcher`)
// - PhantomJS
// - IE (only Windows; has to be installed with `npm install karma-ie-launcher`)
browsers : [ 'Chrome' , 'ChromeCanary', 'Firefox', 'Opera', 'Safari' ],
// If browser does not capture in given timeout [ms], kill it
captureTimeout: 60000,
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun : true
});
};
| Add karma file for browser tests | Add karma file for browser tests
| JavaScript | mit | uplift/ExoSuit,uplift/ExoSuit | ---
+++
@@ -0,0 +1,90 @@
+module.exports = function(config) {
+ config.set({
+ // base path, that will be used to resolve files and exclude
+ basePath : '',
+
+ // frameworks to use
+ frameworks : [ 'mocha', 'sinon', 'chai-jquery', 'jquery-2.1.0', 'chai' ],
+
+ // list of files / patterns to load in the browser
+ files: [
+ {
+ pattern : 'bower_components/underscore/underscore.js',
+ included: true,
+ served: true
+ },
+ {
+ pattern : 'bower_components/backbone/backbone.js',
+ included: true,
+ served: true
+ },
+ {
+ pattern : '../src/**/*.js',
+ included: true,
+ served: true
+ },
+ {
+ pattern : 'specs/**/*.js',
+ included: true,
+ served: true
+ },
+ {
+ pattern : 'specs/fixtures/*.html',
+ included: true,
+ served: true
+ },
+ {
+ pattern : 'specRunner.js',
+ included: true,
+ served: true
+ }
+ ],
+
+ // list of files to exclude
+ exclude : [],
+
+ // test results reporter to use
+ // possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
+ reporters : [ 'dots', 'coverage' ] ,
+
+ preprocessors : {
+ '../src/**/*.js' : [ 'coverage' ],
+ 'specs/fixtures/*.html' : [ 'html2js' ]
+ },
+
+ coverageReporter : {
+ type : 'html',
+ dir : '../coverage/browser/'
+ },
+
+ // web server port
+ port : 9876,
+
+ // enable / disable colors in the output (reporters and logs)
+ colors : true,
+
+ // level of logging
+ // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
+ logLevel : config.LOG_WARN,
+
+ // enable / disable watching file and executing tests whenever any file changes
+ autoWatch : false,
+
+ // Start these browsers, currently available:
+ // - Chrome
+ // - ChromeCanary
+ // - Firefox
+ // - Opera (has to be installed with `npm install karma-opera-launcher`)
+ // - Safari (only Mac; has to be installed with `npm install karma-safari-launcher`)
+ // - PhantomJS
+ // - IE (only Windows; has to be installed with `npm install karma-ie-launcher`)
+ browsers : [ 'Chrome' , 'ChromeCanary', 'Firefox', 'Opera', 'Safari' ],
+
+ // If browser does not capture in given timeout [ms], kill it
+ captureTimeout: 60000,
+
+ // Continuous Integration mode
+ // if true, it capture browsers, run tests and exit
+ singleRun : true
+ });
+}; | |
9dd1afd6966c5b53dcc7f98ab7caf92d328fdd29 | test/index.js | test/index.js | const expect = require('expect');
const createProbot = require('..');
describe('Probot', () => {
let probot;
let event;
beforeEach(() => {
probot = createProbot();
probot.robot.auth = () => Promise.resolve({});
event = {
event: 'push',
payload: require('./fixtures/webhook/push')
};
});
describe('receive', () => {
it('delivers the event', async () => {
spy = expect.createSpy();
probot.load(robot => robot.on('push', spy));
await probot.receive(event);
expect(spy).toHaveBeenCalled();
});
it('raises errors thrown in plugins', async () => {
spy = expect.createSpy();
probot.load(robot => robot.on('push', () => {
throw new Error('something happened');
}));
expect(async () => {
await probot.receive(event);
}).toThrow();
});
});
});
| Test for manually delivering events | Test for manually delivering events
| JavaScript | isc | pholleran-org/probot,pholleran-org/probot,bkeepers/PRobot,probot/probot,pholleran-org/probot,probot/probot,probot/probot,bkeepers/PRobot | ---
+++
@@ -0,0 +1,40 @@
+const expect = require('expect');
+const createProbot = require('..');
+
+describe('Probot', () => {
+ let probot;
+ let event;
+
+ beforeEach(() => {
+ probot = createProbot();
+ probot.robot.auth = () => Promise.resolve({});
+
+ event = {
+ event: 'push',
+ payload: require('./fixtures/webhook/push')
+ };
+ });
+
+ describe('receive', () => {
+ it('delivers the event', async () => {
+ spy = expect.createSpy();
+ probot.load(robot => robot.on('push', spy));
+
+ await probot.receive(event);
+
+ expect(spy).toHaveBeenCalled();
+ });
+
+ it('raises errors thrown in plugins', async () => {
+ spy = expect.createSpy();
+
+ probot.load(robot => robot.on('push', () => {
+ throw new Error('something happened');
+ }));
+
+ expect(async () => {
+ await probot.receive(event);
+ }).toThrow();
+ });
+ });
+}); | |
71156875e3af065137a620c918f042b9719a5aa9 | mods/inverse/abilities.js | mods/inverse/abilities.js | exports.BattleAbilities = {
arenatrap: {
inherit: true,
onFoeModifyPokemon: function(pokemon) {
if (!pokemon.hasType('Flying') && pokemon.runImmunity('Ground', false)) {
pokemon.tryTrap();
}
},
onFoeMaybeTrapPokemon: function(pokemon) {
if (!pokemon.hasType('Flying') && pokemon.runImmunity('Ground', false)) {
pokemon.maybeTrapped = true;
}
}
}
};
| Fix Arena Trap on Inverse Battle Arena Trap still does not trap Flying-types on Inverse Battle. | Fix Arena Trap on Inverse Battle
Arena Trap still does not trap Flying-types on Inverse Battle.
| JavaScript | mit | yashagl/pokemon,Irraquated/Pokemon-Showdown,lFernanl/Pokemon-Showdown,gustavo515/batata,JennyPRO/Jenny,BlazingAura/Showdown-Boilerplate,SSJGVegito007/Vegito-s-Server,lAlejandro22/lolipoop,hayleysworld/serenityc9,DalleTest/Pokemon-Showdown,Elveman/RPCShowdownServer,Syurra/Pokemon-Showdown,comedianchameleon/servertest1,lAlejandro22/lolipoop,jumbowhales/Pokemon-Showdown,danpantry/Pokemon-Showdown,Ecuacion/Pokemon-Showdown,hayleysworld/Pokemon-Showdown,lFernanl/Zero-Pokemon-Showdown,DarkSuicune/Pokemon-Showdown,kotarou3/Krister-Pokemon-Showdown,AbsolitoSweep/Absol-server,PrimalGallade45/Dropp-Pokemon-Showdown,TheManwithskills/Server---Thermal,TheManwithskills/COC,svivian/Pokemon-Showdown,Kill-The-Noise/BlakJack-Boilerplate,Atwar/server-epilogueleague.rhcloud.com,Atwar/ServerClassroom,jumbowhales/Pokemon-Showdown,lFernanl/Mudkip-Server,sirDonovan/Pokemon-Showdown,Adithya4Uberz/The-Tsunami-League,Atwar/ServerClassroom,Pokemon-Devs/Pokemon-Showdown,JellalTheMage/PS-,catanatron/pokemon-rebalance,KewlStatics/Shit,Ecuacion/Lumen-Pokemon-Showdown,Breakfastqueen/advanced,k3naan/Pokemon-Showdown,miahjennatills/Pokemon-Showdown,hayleysworld/asdfasdf,Pablo000/aaa,AbsolitoSweep/Absol-server,psnsVGC/Wish-Server,zek7rom/SpacialGaze,comedianchameleon/test,MayukhKundu/Flame-Savior,Extradeath/psserver,Enigami/Pokemon-Showdown,CreaturePhil/Showdown-Boilerplate,abulechu/Dropp-Pokemon-Showdown,MayukhKundu/Mudkip-Server,lFernanl/Mudkip-Server,PrimalGallade45/Dropp-Pokemon-Showdown,Flareninja/Pokemon-Showdown,Legit99/Lightning-Storm-Server,Hopenub/Pokemon-Showdown,PrimalGallade45/Lumen-Pokemon-Showdown,abrulochp/Dropp-Pokemon-Showdown,Tesarand/Pokemon-Showdown,AnaRitaTorres/Pokemon-Showdown,Wando94/Pokemon-Showdown,Gold-Solox/Pokemon-Showdown,Flareninja/Sora,HoeenCoder/SpacialGaze,JellalTheMage/Jellals-Server,kuroscafe/Paradox,JellalTheMage/Jellals-Server,Mystifi/Exiled,Irraquated/Showdown-Boilerplate,Articuno-I/Pokemon-Showdown,Extradeath/psserver,gustavo515/batata,FakeSloth/wulu,panpawn/Pokemon-Showdown,gustavo515/gashoro,Irraquated/Pokemon-Showdown,SilverTactic/Dragotica-Pokemon-Showdown,Vacate/Pokemon-Showdown,kuroscafe/Showdown-Boilerplate,ehk12/bigbangtempclone,sama2/Universe-Pokemon-Showdown,DarkSuicune/Pokemon-Showdown,PS-Spectral/Spectral,TheManwithskills/New-boiler-test,SerperiorBae/Bae-Showdown-2,Atwar/server-epilogueleague.rhcloud.com,LegendBorned/PS-Boilerplate,CreaturePhil/Pokemon-Showdown,Checkinator/Pokemon-Showdown,Lauc1an/Perulink-Showdown,Psyientist/Showdown-Boilerplate,forbiddennightmare/Pokemon-Showdown-1,AWailOfATail/Pokemon-Showdown,Sora-League/Sora,ZeroParadox/BlastBurners,Oiawesome/DPPtServ2,JennyPRO/Jenny,Flareninja/Sora,Werfin96/Ultimate,panpawn/Gold-Server,Neosweiss/Pokemon-Showdown,Ridukuo/Test,EmmaKitty/Pokemon-Showdown,Articuno-I/Pokemon-Showdown,Oiawesome/DPPtServ2,Tesarand/Pokemon-Showdown,BuzzyOG/Pokemon-Showdown,javi501/Lumen-Pokemon-Showdown,LightningStormServer/Lightning-Storm,jumbowhales/Pokemon-Showdown,k3naan/Pokemon-Showdown,SerperiorBae/Bae-Showdown,Alpha-Devs/OmegaRuby-Server,RustServer/Pokemon-Showdown,AWailOfATail/awoat,Kokonoe-san/Glacia-PS,Parukia/Pokemon-Showdown,xfix/Pokemon-Showdown,hayleysworld/serenityc9,DesoGit/TsunamiPS,Volcos/SpacialGaze,Pikachuun/Joimmon-Showdown,Irraquated/EOS-Master,BadSteel/Pokemon-Showdown,AustinXII/Pokemon-Showdown,UniversalMan12/Universe-Server,Enigami/Pokemon-Showdown,Syurra/Pokemon-Showdown,Flareninja/Lumen-Pokemon-Showdown,Evil-kun/Pokemon-Showdown,ZestOfLife/FestiveLife,AnaRitaTorres/Pokemon-Showdown,superman8900/Pokemon-Showdown,LustyAsh/EOS-Master,Lord-Haji/SpacialGaze,EienSeiryuu/Pokemon-Showdown,piiiikachuuu/Pokemon-Showdown,DesoGit/Tsunami_PS,AWailOfATail/Pokemon-Showdown,DesoGit/Tsunami_PS,Kevinxzllz/PS-Openshift-Server,Celecitia/Plux-Pokemon-Showdown,Pikachuun/Pokemon-Showdown-SMCMDM,aakashrajput/Pokemon-Showdown,arkanox/MistShowdown,Ridukuo/Test2,KaitoV4X/Showdown,ankailou/Pokemon-Showdown,svivian/Pokemon-Showdown,abulechu/Lumen-Pokemon-Showdown,kupochu/Pokemon-Showdown,kuroscafe/Showdown-Boilerplate,LustyAsh/EOS-Master,Irraquated/Showdown-Boilerplate,UniversalMan12/Universe-Server,anubhabsen/Pokemon-Showdown,Alpha-Devs/Alpha-Server,svivian/Pokemon-Showdown,SkyeTheFemaleSylveon/Mudkip-Server,Raina4uberz/Light-server,HoeenCoder/SpacialGaze,Ecuacion/Lumen-Pokemon-Showdown,sama2/Universe-Pokemon-Showdown,sama2/Viridian-Pokemon-Showdown,Sora-Server/Sora,BuzzyOG/Pokemon-Showdown,Git-Worm/City-PS,ScottehMax/Pokemon-Showdown,sama2/Dropp-Pokemon-Showdown,hayleysworld/serenityserver,TheManwithskills/Server-2,SkyeTheFemaleSylveon/Pokemon-Showdown,Flareninja/Pokemon-Showdown-1,Flareninja/Sora,UniversalMan12/Universe-Server,KewlStatics/Shit,Gold-Solox/Pokemon-Showdown,BadSteel/Omega-Pokemon-Showdown,lFernanl/Zero-Pokemon-Showdown,cadaeic/Pokemon-Showdown,TheManwithskills/DS,Kevinxzllz/PS-Openshift-Server,Parukia/Pokemon-Showdown,Firestatics/omega,Irraquated/Pokemon-Showdown,Alpha-Devs/Alpha-Server,lFernanl/Lumen-Pokemon-Showdown,MeliodasBH/boarhat,hayleysworld/serenity,gustavo515/final,xCrystal/Pokemon-Showdown,anubhabsen/Pokemon-Showdown,SerperiorBae/Pokemon-Showdown,CreaturePhil/Pokemon-Showdown,ScottehMax/Pokemon-Showdown,svivian/Pokemon-Showdown,yashagl/yash-showdown,hayleysworld/serenity,panpawn/Pokemon-Showdown,gustavo515/final,Sora-Server/Sora,DarkSuicune/Kakuja-2.0,CrestfallPS/Pokemon-Showdown,Checkinator/Pokemon-Showdown,brettjbush/Pokemon-Showdown,MayukhKundu/Technogear-Final,aakashrajput/Pokemon-Showdown,iFaZe/SliverX,urkerab/Pokemon-Showdown,LegendBorned/PS-Boilerplate,comedianchameleon/test,urkerab/Pokemon-Showdown,BasedGod7/PH,megaslowbro1/Pokemon-Showdown,KewlStatics/Alliance,MasterFloat/LQP-Server-Showdown,kotarou3/Krister-Pokemon-Showdown,SilverTactic/Pokemon-Showdown,SubZeroo99/Pokemon-Showdown,Wando94/Spite,asdfghjklohhnhn/Pokemon-Showdown,CharizardtheFireMage/Showdown-Boilerplate,TheManwithskills/COC,Celecitia/Plux-Pokemon-Showdown,ShowdownHelper/Saffron,BlazingAura/Showdown-Boilerplate,SerperiorBae/Pokemon-Showdown-1,sama2/Lumen-Pokemon-Showdown,xfix/Pokemon-Showdown,forbiddennightmare/Pokemon-Showdown-1,panpawn/Gold-Server,MeliodasBH/boarhat,Nineage/Showdown-Boilerplate,DB898/theregalias,kuroscafe/Paradox,psnsVGC/Wish-Server,Flareninja/Hispano-Pokemon-Showdown,Wando94/Spite,SilverTactic/Showdown-Boilerplate,Zarel/Pokemon-Showdown,Ransei1/Alt,scotchkorean27/Pokemon-Showdown,gustavo515/test,SerperiorBae/BaeShowdown,RustServer/Pokemon-Showdown,AWailOfATail/Pokemon-Showdown,kubetz/Pokemon-Showdown,MayukhKundu/Pokemon-Domain,TheManwithskills/Server---Thermal,Nineage/Origin,Pikachuun/Pokemon-Showdown,SerperiorBae/Pokemon-Showdown,lFernanl/Pokemon-Showdown,TheManwithskills/Dusk--Showdown,SolarisFox/Pokemon-Showdown,Darkshadow6/git-remote-add-scalingo-git-scalingo.com-pokemoonforums,SubZeroo99/Pokemon-Showdown,Flareninja/Showdown-Boilerplate,sama2/Lumen-Pokemon-Showdown,AvinashSwaminathan/lotus-v2,MayukhKundu/Technogear-Final,LightningStormServer/Lightning-Storm,ZeroParadox/BlastBurners,KewlStatics/Pokeindia-Codes,TheManwithskills/Server-2,Firestatics/Omega-Alpha,theodelhay/test,Darkshadow6/git-remote-add-scalingo-git-scalingo.com-pokemoonforums,HoeenKid/Pokemon-Showdown-Johto,AustinXII/Pokemon-Showdown,MayukhKundu/Mudkip-Server,PauLucario/LQP-Server-Showdown,SerperiorBae/Pokemon-Showdown,TheManwithskills/New-boiler-test,Breakfastqueen/advanced,ehk12/clone,Zipzapadam/Server,Darkshadow6/PokeMoon-Creation,HoeenCoder/SpacialGaze,bai2/Dropp,Hidden-Mia/Roleplay-PS,SerperiorBae/Bae-Showdown-2,svivian/Pokemon-Showdown,iFaZe/SilverZ,catanatron/pokemon-rebalance,CreaturePhil/Showdown-Boilerplate,AustinXII/Pokemon-Showdown,TheManwithskills/Dusk--Showdown,DalleTest/Pokemon-Showdown,AWailOfATail/awoat,SerperiorBae/Bae-Showdown,Sora-Server/Sora,Elveman/RPCShowdownServer,SerperiorBae/Pokemon-Showdown-1,TheDiabolicGift/Showdown-Boilerplate,Enigami/Pokemon-Showdown,Adithya4Uberz/The-Tsunami-League,DesoGit/Tsunami_PS,yashagl/pokemon-showdown,xfix/Pokemon-Showdown,TogeSR/Lumen-Pokemon-Showdown,Disaster-Area/Pokemon-Showdown,Hidden-Mia/Roleplay-PS,javi501/Lumen-Pokemon-Showdown,Alpha-Devs/OmegaRuby-Server,Disaster-Area/Pokemon-Showdown,abrulochp/Lumen-Pokemon-Showdown,Vacate/Pokemon-Showdown,Darkshadow6/git-remote-add-scalingo-git-scalingo.com-pokemoonforums,MayukhKundu/Technogear,SerperiorBae/BaeShowdown,TheManwithskills/serenity,FakeSloth/Infinite,SilverTactic/Pokemon-Showdown,Mystifi/Exiled,Sora-League/Sora,hayleysworld/Pokemon-Showdown,MeliodasBH/Articuno-Land,CreaturePhil/Showdown-Boilerplate,Nineage/Origin,Flareninja/Pokemon-Showdown-1,xCrystal/Pokemon-Showdown,jd4564/Pokemon-Showdown,kubetz/Pokemon-Showdown,xfix/Pokemon-Showdown,comedianchameleon/servertest1,Raina4uberz/Light-server,Kill-The-Noise/BlakJack-Boilerplate,JellalTheMage/PS-,Extradeath/advanced,DesoGit/TsunamiPS,Johto-Serverr/Werfin-Boilerplate,TheDiabolicGift/Lumen-Pokemon-Showdown,Guernouille/Pokemon-Showdown,yashagl/yash-showdown,SerperiorBae/Bae-Showdown,yashagl/pokecommunity,TbirdClanWish/Pokemon-Showdown,InvalidDN/Pokemon-Showdown,Flareninja/Showdown-Boilerplate,Psyientist/Showdown-Boilerplate,TheManwithskills/Server,SerperiorBae/PokemonShowdown2,Legit99/Lightning-Storm-Server,ZestOfLife/FestiveLife,Pikachuun/Pokemon-Showdown-SMCMDM,Fusxfaranto/Pokemon-Showdown,Luobata/Pokemon-Showdown,NoahVSGamingYT/Pokemon-Showdown,gustavo515/gashoro,urkerab/Pokemon-Showdown,SSJGVegito007/Vegito-s-Server,VoltStorm/Server-pokemon-showdown,Zarel/Pokemon-Showdown,piiiikachuuu/Pokemon-Showdown,ehk12/coregit,Guernouille/Pokemon-Showdown,Parukia/Pokemon-Showdown,TbirdClanWish/Pokemon-Showdown,PrimalGallade45/Lumen-Pokemon-Showdown,danpantry/Pokemon-Showdown,jd4564/Pokemon-Showdown,Pikachuun/Touhoumon-Showdown,abrulochp/Lumen-Pokemon-Showdown,ShowdownHelper/Saffron,TheManwithskills/Creature-phil-boiler,AvinashSwaminathan/lotus-v3,BuzzyOG/Pokemon-Showdown,zek7rom/SpacialGaze,ZeroParadox/ugh,Thiediev/Pokemon-Showdown,megaslowbro1/Pokemon-Showdown-Server-for-megaslowbro1,SerperiorBae/Bae-Showdown-2,Firestatics/Firestatics46,Git-Worm/City-PS,SilverTactic/Showdown-Boilerplate,Yggdrasil-League/Yggdrasil,arkanox/MistShowdown,Stroke123/POKEMON,PauLucario/LQP-Server-Showdown,TheFenderStory/Pokemon-Showdown,Flareninja/Lumen-Pokemon-Showdown,TheManwithskills/serenity,SkyeTheFemaleSylveon/Pokemon-Showdown,hayleysworld/harmonia,megaslowbro1/Pokemon-Showdown,NoahVSGamingYT/Pokemon-Showdown,Ridukuo/Test2,Zarel/Pokemon-Showdown,KewlStatics/Alliance,SerperiorBae/PokemonShowdown2,Flareninja/Pokemon-Showdown,aakashrajput/Pokemon-Showdown,azum4roll/Pokemon-Showdown,megaslowbro1/Showdown-Server-again,Kenny-/Pokemon-Showdown,AvinashSwaminathan/Pokelegends,TheFenderStory/Pokemon-Showdown,Enigami/Pokemon-Showdown,gustavo515/test,MayukhKundu/Flame-Savior,Bryan-0/Pokemon-Showdown,Pablo000/aaa,AvinashSwaminathan/lotus,hayleysworld/harmonia,Flareninja/Hispano-Pokemon-Showdown,TheDiabolicGift/Showdown-Boilerplate,Neosweiss/Pokemon-Showdown,brettjbush/Pokemon-Showdown,Ransei1/Alt,kupochu/Pokemon-Showdown,Atwar/http-server-femalehq.rhcloud.com-80.psim.us-,bai2/Dropp,QuiteQuiet/Pokemon-Showdown,Pokemon-Devs/Pokemon-Showdown,ehk12/coregit,Kokonoe-san/Glacia-PS,TheManwithskills/Server,Sora-League/Sora,FakeSloth/Infinite,hayleysworld/asdfasdf,zczd/enculer,sama2/Viridian-Pokemon-Showdown,hayleysworld/Showdown-Boilerplate,Adithya4Uberz/KTN,Ecuacion/Pokemon-Showdown,Tesarand/Pokemon-Showdown,yashagl/pokemon-showdown,KewlStatics/Showdown-Template,abulechu/Dropp-Pokemon-Showdown,xCrystal/Pokemon-Showdown,SolarisFox/Pokemon-Showdown,theodelhay/test,sama2/Dropp-Pokemon-Showdown,Ridukuo/Test,Irraquated/EOS-Master,Firestatics/omega,MayukhKundu/Technogear,hayleysworld/Showdown-Boilerplate,abrulochp/Dropp-Pokemon-Showdown,Darkshadow6/PokeMoon-Creation,sirDonovan/Pokemon-Showdown,johtooo/PS,Extradeath/advanced,InvalidDN/Pokemon-Showdown,MayukhKundu/Pokemon-Domain,QuiteQuiet/Pokemon-Showdown,TheManwithskills/DS,BlakJack/Kill-The-Noise,comedianchameleon/test,TogeSR/Lumen-Pokemon-Showdown,Volcos/SpacialGaze,KewlStatics/Pokeindia-Codes,Stroke123/POKEMON,scotchkorean27/Pokemon-Showdown,Lord-Haji/SpacialGaze,SerperiorBae/Pokemon-Showdown-1,QuiteQuiet/Pokemon-Showdown,Pikachuun/Pokemon-Showdown,Wando94/Pokemon-Showdown,asdfghjklohhnhn/Pokemon-Showdown,MasterFloat/Pokemon-Showdown,panpawn/Gold-Server,PS-Spectral/Spectral,Zipzapadam/Server,Atwar/http-server-femalehq.rhcloud.com-80.psim.us-,TheFenderStory/Showdown-Boilerplate,Legendaryhades/Oblivion,ShowdownHelper/Saffron,yashagl/pokemon,megaslowbro1/Pokemon-Showdown-Server-for-megaslowbro1,Firestatics/Omega-Alpha,Pikachuun/Joimmon-Showdown,megaslowbro1/Showdown-Server-again,hayleysworld/serenityserver,ZeroParadox/ugh,LightningStormServer/Lightning-Storm,Bryan-0/Pokemon-Showdown,cadaeic/Pokemon-Showdown,Evil-kun/Pokemon-Showdown,Breakfastqueen/advanced,SilverTactic/Dragotica-Pokemon-Showdown,PS-Spectral/Spectral,yashagl/pokecommunity,MasterFloat/LQP-Server-Showdown,Chespin14/Custom-Platform-Pokemon-Showdown,ankailou/Pokemon-Showdown,sirDonovan/Pokemon-Showdown,TheFenderStory/Showdown-Boilerplate,TheManwithskills/Creature-phil-boiler,Yggdrasil-League/Yggdrasil,ZestOfLife/PSserver,johtooo/PS,ZestOfLife/PSserver,MasterFloat/Pokemon-Showdown,MeliodasBH/Articuno-Land,KewlStatics/Showdown-Template,EienSeiryuu/Pokemon-Showdown,HoeenCoder/SpacialGaze,ehk12/bigbangtempclone,zczd/enculer,superman8900/Pokemon-Showdown,EmmaKitty/Pokemon-Showdown,xfix/Pokemon-Showdown,abulechu/Lumen-Pokemon-Showdown,ehk12/clone,Lauc1an/Perulink-Showdown,Darkshadow6/PokeMoon-Creation,TheDiabolicGift/Lumen-Pokemon-Showdown,Kill-The-Noise/BlakJack-Boilerplate,DarkSuicune/Kakuja-2.0,lFernanl/Lumen-Pokemon-Showdown,SkyeTheFemaleSylveon/Mudkip-Server,Firestatics/Firestatics46,SerperiorBae/BaeShowdown,azum4roll/Pokemon-Showdown,KaitoV4X/Showdown,TheManwithskills/Server-2,Lord-Haji/SpacialGaze,Mystifi/Exiled,CharizardtheFireMage/Showdown-Boilerplate,DB898/theregalias,miahjennatills/Pokemon-Showdown | ---
+++
@@ -0,0 +1,15 @@
+exports.BattleAbilities = {
+ arenatrap: {
+ inherit: true,
+ onFoeModifyPokemon: function(pokemon) {
+ if (!pokemon.hasType('Flying') && pokemon.runImmunity('Ground', false)) {
+ pokemon.tryTrap();
+ }
+ },
+ onFoeMaybeTrapPokemon: function(pokemon) {
+ if (!pokemon.hasType('Flying') && pokemon.runImmunity('Ground', false)) {
+ pokemon.maybeTrapped = true;
+ }
+ }
+ }
+}; | |
1e84ec991a9d161f1e5d4fa4351d8a0d2562ec42 | test/api-compiler-tests.js | test/api-compiler-tests.js | 'use strict';
require('./patch-module');
require('marko/node-require').install();
var chai = require('chai');
chai.config.includeStack = true;
var expect = require('chai').expect;
var nodePath = require('path');
require('../compiler');
var autotest = require('./autotest');
var marko = require('../');
var markoCompiler = require('../compiler');
describe('api' , function() {
var autoTestDir = nodePath.join(__dirname, 'autotests/api-compiler');
autotest.scanDir(autoTestDir, function run(dir, helpers, done) {
var test = require(nodePath.join(dir, 'test.js'));
test.check(marko, markoCompiler, expect, done);
});
});
| Test runner for `api-compiler` tests | Test runner for `api-compiler` tests
| JavaScript | mit | marko-js/marko,marko-js/marko | ---
+++
@@ -0,0 +1,22 @@
+'use strict';
+require('./patch-module');
+require('marko/node-require').install();
+
+var chai = require('chai');
+chai.config.includeStack = true;
+
+var expect = require('chai').expect;
+var nodePath = require('path');
+require('../compiler');
+var autotest = require('./autotest');
+var marko = require('../');
+var markoCompiler = require('../compiler');
+
+describe('api' , function() {
+ var autoTestDir = nodePath.join(__dirname, 'autotests/api-compiler');
+
+ autotest.scanDir(autoTestDir, function run(dir, helpers, done) {
+ var test = require(nodePath.join(dir, 'test.js'));
+ test.check(marko, markoCompiler, expect, done);
+ });
+}); | |
a0811c7c3b685dbd94b8ad2cb463fdad97b67620 | 06/jjhampton-ch6-sequence-interface.js | 06/jjhampton-ch6-sequence-interface.js | // Design an interface that abstracts iteration over a collection of values. An object that provides this interface represents a sequence, and the interface must somehow make it possible for code that uses such an object to iterate over the sequence, looking at the element values it is made up of and having some way to find out when the end of the sequence is reached.
// When you have specified your interface, try to write a function logFive that takes a sequence object and calls console.log on its first five elements—or fewer, if the sequence has fewer than five elements.
// Then implement an object type ArraySeq that wraps an array and allows iteration over the array using the interface you designed. Implement another object type RangeSeq that iterates over a range of integers (taking from and to arguments to its constructor) instead.
function Sequence(collection) {
this.collection = collection;
this.length = collection.length;
}
Sequence.prototype.getCurrentElement = function(index) {
return this.collection[index];
}
Sequence.prototype.getRemainingSequence = function(index) {
var remainingElements = this.collection.slice(index + 1);
if (remainingElements.length === 0)
return null;
else return new Sequence(remainingElements);
}
function logFive(sequence) {
if (sequence.length === 0)
return;
for (var i = 0; i < 5; i++) {
console.log(sequence.getCurrentElement(i));
if (!sequence.getRemainingSequence(i)) {
break;
}
}
console.log(); // empty line to mark end of sequence
}
function ArraySeq(array) {
return new Sequence(array);
}
logFive(new ArraySeq([1, 2]));
logFive(new ArraySeq([1, 2, 3, 4, 5]));
logFive(new ArraySeq([1, 2, 3, 4, 5, 6, 7]));
logFive(new ArraySeq([]));
//logFive(new RangeSeq(100, 1000));
// → 100
// → 101
// → 102
// → 103
// → 104
| Add partial solution to sequence-interface exercise | Add partial solution to sequence-interface exercise
Specify Sequence interface - define constructor, instance properties, and prototype
methods. Also implement ArraySeq constructor that uses the Sequence
interface.
| JavaScript | mit | OperationCode/eloquent-js | ---
+++
@@ -0,0 +1,56 @@
+// Design an interface that abstracts iteration over a collection of values. An object that provides this interface represents a sequence, and the interface must somehow make it possible for code that uses such an object to iterate over the sequence, looking at the element values it is made up of and having some way to find out when the end of the sequence is reached.
+
+// When you have specified your interface, try to write a function logFive that takes a sequence object and calls console.log on its first five elements—or fewer, if the sequence has fewer than five elements.
+
+// Then implement an object type ArraySeq that wraps an array and allows iteration over the array using the interface you designed. Implement another object type RangeSeq that iterates over a range of integers (taking from and to arguments to its constructor) instead.
+
+function Sequence(collection) {
+ this.collection = collection;
+ this.length = collection.length;
+}
+
+Sequence.prototype.getCurrentElement = function(index) {
+ return this.collection[index];
+}
+
+Sequence.prototype.getRemainingSequence = function(index) {
+ var remainingElements = this.collection.slice(index + 1);
+ if (remainingElements.length === 0)
+ return null;
+ else return new Sequence(remainingElements);
+}
+
+function logFive(sequence) {
+ if (sequence.length === 0)
+ return;
+ for (var i = 0; i < 5; i++) {
+ console.log(sequence.getCurrentElement(i));
+ if (!sequence.getRemainingSequence(i)) {
+ break;
+ }
+ }
+ console.log(); // empty line to mark end of sequence
+}
+
+function ArraySeq(array) {
+ return new Sequence(array);
+}
+
+
+logFive(new ArraySeq([1, 2]));
+logFive(new ArraySeq([1, 2, 3, 4, 5]));
+logFive(new ArraySeq([1, 2, 3, 4, 5, 6, 7]));
+logFive(new ArraySeq([]));
+
+//logFive(new RangeSeq(100, 1000));
+// → 100
+// → 101
+// → 102
+// → 103
+// → 104
+
+
+
+
+
+ | |
8bb4599170ecfb99af9a3e1029d30093bb83e7ef | popup-view.js | popup-view.js | PinPoint.View = function(){
//Steven's storeListDOMRoot is equivalent to our noteList
this.noteListDOMRoot = document.getElementsByTagName('table');
}
//the 'notes' argument will be an array of parsed JSON note objects
PinPoint.View.prototype = {
loadNotesFromDatabase: function(notes) {
// this.noteList.appendChild(newNode)
controller = new PinPoint.NoteController(notes);
//At this point you can call 'controller.notes' and get an array of all the note objects.
for (i=0, i <= controller.length, i++) {
}
}
}
//Steven's code that we definitely need:
//dataSource is the controller
populateNoteList: function(dataSource) {
var noteListParent = this.noteListDOMRoot;
while (noteListParent.firstChild) {
noteListParent.removeChild(noteListParent.firstChild);
}
dataSource.noteList.forEach(function(note) {
var newNode = new PinPointApp.NotePresenter(note).present();
noteListParent.appendChild(newNode);
});
}
| Create view file for popup. | Create view file for popup.
| JavaScript | mit | ospreys-2014/PinPoint,jbouzi12/PinPoint,jbouzi12/PinPoint | ---
+++
@@ -0,0 +1,35 @@
+PinPoint.View = function(){
+ //Steven's storeListDOMRoot is equivalent to our noteList
+ this.noteListDOMRoot = document.getElementsByTagName('table');
+
+}
+
+//the 'notes' argument will be an array of parsed JSON note objects
+PinPoint.View.prototype = {
+ loadNotesFromDatabase: function(notes) {
+ // this.noteList.appendChild(newNode)
+ controller = new PinPoint.NoteController(notes);
+ //At this point you can call 'controller.notes' and get an array of all the note objects.
+ for (i=0, i <= controller.length, i++) {
+
+ }
+
+ }
+
+}
+
+
+
+//Steven's code that we definitely need:
+//dataSource is the controller
+populateNoteList: function(dataSource) {
+ var noteListParent = this.noteListDOMRoot;
+
+ while (noteListParent.firstChild) {
+ noteListParent.removeChild(noteListParent.firstChild);
+ }
+ dataSource.noteList.forEach(function(note) {
+ var newNode = new PinPointApp.NotePresenter(note).present();
+ noteListParent.appendChild(newNode);
+ });
+} | |
8fd28d35f51c40088a834eaa4bbfb01dc86385f9 | web/js/swToolboxAdmin.js | web/js/swToolboxAdmin.js | /*
* $Id$
*
* (c) 2008 Thomas Rabaix <thomas.rabaix@soleoweb.com>
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see
* <http://www.soleoweb.com>.
*/
jQuery(window).bind('load', function(){
jQuery("ul.ui-tabs-nav").tabs();
})
| Add admin backend js helper | Add admin backend js helper
git-svn-id: c69874b65fc60996824a336b7ccbc1d3cf663ce3@12655 ee427ae8-e902-0410-961c-c3ed070cd9f9
| JavaScript | mit | rande/swToolboxPlugin | ---
+++
@@ -0,0 +1,25 @@
+/*
+ * $Id$
+ *
+ * (c) 2008 Thomas Rabaix <thomas.rabaix@soleoweb.com>
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * This software consists of voluntary contributions made by many individuals
+ * and is licensed under the LGPL. For more information, see
+ * <http://www.soleoweb.com>.
+ */
+
+jQuery(window).bind('load', function(){
+ jQuery("ul.ui-tabs-nav").tabs();
+}) | |
8cbf3e2469e4e6a157d7916817bfaf939e89007d | app/helpers/functions.js | app/helpers/functions.js | module.exports = {
capitalizeFirstLetter: function (str) {
if (str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
return '';
}
}; | Create a place for function helpers | Create a place for function helpers
Add first function, capitalizeFirstLetter
| JavaScript | mit | hacksu/kenthackenough,hacksu/kenthackenough | ---
+++
@@ -0,0 +1,10 @@
+module.exports = {
+
+ capitalizeFirstLetter: function (str) {
+ if (str) {
+ return str.charAt(0).toUpperCase() + str.slice(1);
+ }
+ return '';
+ }
+
+}; | |
edef73dce067d18c3dab643e2c454f992a06e13f | test/api/lambdas/:organizationName/:lambdaName/get.js | test/api/lambdas/:organizationName/:lambdaName/get.js | import express from "express";
import request from "supertest-as-promised";
import {sign} from "jsonwebtoken";
import api from "api";
import * as config from "config";
import dynamodb from "services/dynamodb";
describe("GET /lambdas/:organizationName/:lambdaName", () => {
const server = express().use(api);
const token = sign(
{aud: config.AUTH0_CLIENT_ID, sub: "userId"},
config.AUTH0_CLIENT_SECRET
);
beforeEach(async () => {
await dynamodb.putAsync({
TableName: config.DYNAMODB_ORGANIZATIONS,
Item: {
name: "organizationName",
ownerId: "userId"
}
});
await dynamodb.putAsync({
TableName: config.DYNAMODB_LAMBDAS,
Item: {
organizationName: "organizationName",
name: "lambdaName",
sourceRepository: "gh/org/repo"
}
});
});
afterEach(async () => {
await dynamodb.deleteAsync({
TableName: config.DYNAMODB_ORGANIZATIONS,
Key: {name: "organizationName"}
});
await dynamodb.deleteAsync({
TableName: config.DYNAMODB_LAMBDAS,
Key: {
organizationName: "organizationName",
name: "lambdaName"
}
});
});
it("404 on lambda not found [CASE 0: non existing organization]", () => {
return request(server)
.get("/lambdas/nonExistingOrganizationName/lambdaName")
.set("Authorization", `Bearer ${token}`)
.expect(404)
.expect(/Lambda nonExistingOrganizationName\/lambdaName not found/);
});
it("404 on lambda not found [CASE 0: non existing lambda]", () => {
return request(server)
.get("/lambdas/organizationName/nonExistingLambdaName")
.set("Authorization", `Bearer ${token}`)
.expect(404)
.expect(/Lambda organizationName\/nonExistingLambdaName not found/);
});
it("200 and returns the requested lambda", () => {
return request(server)
.get("/lambdas/organizationName/lambdaName")
.set("Authorization", `Bearer ${token}`)
.expect(200)
.expect({
organizationName: "organizationName",
name: "lambdaName",
sourceRepository: "gh/org/repo"
});
});
});
| Add tests for GET /lambdas/:organizationName/:lambdaName | Add tests for GET /lambdas/:organizationName/:lambdaName
| JavaScript | mit | lk-architecture/lh-api | ---
+++
@@ -0,0 +1,76 @@
+import express from "express";
+import request from "supertest-as-promised";
+import {sign} from "jsonwebtoken";
+
+import api from "api";
+import * as config from "config";
+import dynamodb from "services/dynamodb";
+
+describe("GET /lambdas/:organizationName/:lambdaName", () => {
+
+ const server = express().use(api);
+ const token = sign(
+ {aud: config.AUTH0_CLIENT_ID, sub: "userId"},
+ config.AUTH0_CLIENT_SECRET
+ );
+
+ beforeEach(async () => {
+ await dynamodb.putAsync({
+ TableName: config.DYNAMODB_ORGANIZATIONS,
+ Item: {
+ name: "organizationName",
+ ownerId: "userId"
+ }
+ });
+ await dynamodb.putAsync({
+ TableName: config.DYNAMODB_LAMBDAS,
+ Item: {
+ organizationName: "organizationName",
+ name: "lambdaName",
+ sourceRepository: "gh/org/repo"
+ }
+ });
+ });
+ afterEach(async () => {
+ await dynamodb.deleteAsync({
+ TableName: config.DYNAMODB_ORGANIZATIONS,
+ Key: {name: "organizationName"}
+ });
+ await dynamodb.deleteAsync({
+ TableName: config.DYNAMODB_LAMBDAS,
+ Key: {
+ organizationName: "organizationName",
+ name: "lambdaName"
+ }
+ });
+ });
+
+ it("404 on lambda not found [CASE 0: non existing organization]", () => {
+ return request(server)
+ .get("/lambdas/nonExistingOrganizationName/lambdaName")
+ .set("Authorization", `Bearer ${token}`)
+ .expect(404)
+ .expect(/Lambda nonExistingOrganizationName\/lambdaName not found/);
+ });
+
+ it("404 on lambda not found [CASE 0: non existing lambda]", () => {
+ return request(server)
+ .get("/lambdas/organizationName/nonExistingLambdaName")
+ .set("Authorization", `Bearer ${token}`)
+ .expect(404)
+ .expect(/Lambda organizationName\/nonExistingLambdaName not found/);
+ });
+
+ it("200 and returns the requested lambda", () => {
+ return request(server)
+ .get("/lambdas/organizationName/lambdaName")
+ .set("Authorization", `Bearer ${token}`)
+ .expect(200)
+ .expect({
+ organizationName: "organizationName",
+ name: "lambdaName",
+ sourceRepository: "gh/org/repo"
+ });
+ });
+
+}); | |
b1f87ed9f07f24154e86be7d3a1df8ed54f1883a | updates/0.0.1-locales.js | updates/0.0.1-locales.js | var fs = require('fs');
var namespaces = [
'app','home','form','services',
'footer','portfolio','terms',
'contact'
],
lngs = ['fr', 'en'],
resources = [];
function loadResource($ns,$lng) {
var data = fs.readFileSync('./locales/' + $lng +'/' + $ns + '.json', 'utf8');
return {
_id: $ns + '_' + $lng,
ns: $ns,
lng: $lng,
resource: JSON.stringify(JSON.parse(data))
}
}
var tuples = [];
// create tuples of ns, lng
namespaces.forEach(function(ns) {
lngs.forEach(function(lng) {
resources.push(loadResource(ns,lng));
});
});
console.log(resources);
exports.create = {
LocaleResource: resources
};
| Add localeResource model and update | Add localeResource model and update
| JavaScript | mit | infocinc/homepage,infocinc/homepage,infocinc/homepage | ---
+++
@@ -0,0 +1,38 @@
+var fs = require('fs');
+
+var namespaces = [
+ 'app','home','form','services',
+ 'footer','portfolio','terms',
+ 'contact'
+ ],
+ lngs = ['fr', 'en'],
+ resources = [];
+
+
+function loadResource($ns,$lng) {
+ var data = fs.readFileSync('./locales/' + $lng +'/' + $ns + '.json', 'utf8');
+ return {
+ _id: $ns + '_' + $lng,
+ ns: $ns,
+ lng: $lng,
+ resource: JSON.stringify(JSON.parse(data))
+ }
+}
+
+
+var tuples = [];
+// create tuples of ns, lng
+namespaces.forEach(function(ns) {
+ lngs.forEach(function(lng) {
+ resources.push(loadResource(ns,lng));
+ });
+});
+
+console.log(resources);
+
+exports.create = {
+ LocaleResource: resources
+};
+
+
+ | |
c099debbc24fb8576cdddfe31b9391996a6aad21 | server/models/listsubscriber.js | server/models/listsubscriber.js | 'use strict';
module.exports = function(sequelize, DataTypes) {
var listsubscriber = sequelize.define('listsubscriber', {
email: DataTypes.STRING,
subscribed: { type: DataTypes.BOOLEAN, defaultValue: true },
unsubscribeKey: { type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4 },
mostRecentStatus: { type: DataTypes.STRING, defaultValue: 'unconfirmed' }, // bounce:permanent, bounce:transient, complaint
additionalData: { type: DataTypes.JSONB, defaultValue: {} }
}, {
classMethods: {
associate: function(models) {
// associations can be defined here
listsubscriber.belongsTo(models.list);
listsubscriber.hasMany(models.campaignanalyticslink);
listsubscriber.hasMany(models.campaignanalyticsopen);
listsubscriber.hasMany(models.campaignsubscriber);
}
},
indexes: [
{
unique: true,
fields:['email']
}
]
});
return listsubscriber;
};
| 'use strict';
module.exports = function(sequelize, DataTypes) {
var listsubscriber = sequelize.define('listsubscriber', {
email: DataTypes.STRING,
subscribed: { type: DataTypes.BOOLEAN, defaultValue: true },
unsubscribeKey: { type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4 },
mostRecentStatus: { type: DataTypes.STRING, defaultValue: 'unconfirmed' }, // bounce:permanent, bounce:transient, complaint
additionalData: { type: DataTypes.JSONB, defaultValue: {} }
}, {
classMethods: {
associate: function(models) {
// associations can be defined here
listsubscriber.belongsTo(models.list);
listsubscriber.hasMany(models.campaignanalyticslink);
listsubscriber.hasMany(models.campaignanalyticsopen);
listsubscriber.hasMany(models.campaignsubscriber);
}
},
indexes: [
{
fields:['email']
}
]
});
return listsubscriber;
};
| Remove unique constraint for ListSubscribers table | Remove unique constraint for ListSubscribers table
| JavaScript | bsd-3-clause | karuppiah7890/Mail-for-Good,zhakkarn/Mail-for-Good,karuppiah7890/Mail-for-Good,karuppiah7890/Mail-for-Good,zhakkarn/Mail-for-Good,zhakkarn/Mail-for-Good | ---
+++
@@ -18,7 +18,6 @@
},
indexes: [
{
- unique: true,
fields:['email']
}
] |
9858889189d3516b62bd0b78ae76cb9dbb9b837c | lib/core-components/famous-demos/config-panel/config-panel.js | lib/core-components/famous-demos/config-panel/config-panel.js | FamousFramework.component('famous-demos:config-panel', {
tree: `
<famous:ui:config-panel:controller id="controller">
<famous-demos:clickable-square id="square" class="configurable"></famous-demos:clickable-square>
</famous:ui:config-panel:controller>
`
});
| Add config panel demo with everyone's favorite, clickable-square | feat: Add config panel demo with everyone's favorite, clickable-square
| JavaScript | mit | jeremykenedy/framework,Famous/framework,SvitlanaShepitsena/framework,infamous/framework,KraigWalker/framework,ildarsamit/framework,SvitlanaShepitsena/framework,tbossert/framework,infamous/famous-framework,woltemade/framework,colllin/famous-framework,KraigWalker/framework,woltemade/framework,SvitlanaShepitsena/remax-banner,jeremykenedy/framework,SvitlanaShepitsena/framework-1,SvitlanaShepitsena/shakou,infamous/framework,colllin/famous-framework,SvitlanaShepitsena/remax-banner,tbossert/framework,SvitlanaShepitsena/shakou,SvitlanaShepitsena/framework-1,ildarsamit/framework,infamous/famous-framework,Famous/framework | ---
+++
@@ -0,0 +1,8 @@
+FamousFramework.component('famous-demos:config-panel', {
+
+ tree: `
+ <famous:ui:config-panel:controller id="controller">
+ <famous-demos:clickable-square id="square" class="configurable"></famous-demos:clickable-square>
+ </famous:ui:config-panel:controller>
+ `
+}); | |
6df052468b535b54f208207a44f42ef4791c89c4 | settings/OwnerSettings.js | settings/OwnerSettings.js | import React from 'react';
import PropTypes from 'prop-types';
import ControlledVocab from '@folio/stripes-smart-components/lib/ControlledVocab';
class OwnerSettings extends React.Component {
static propTypes = {
stripes: PropTypes.shape({
connect: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
}).isRequired,
};
constructor(props) {
super(props);
this.connectedControlledVocab = props.stripes.connect(ControlledVocab);
}
render() {
return (
<this.connectedControlledVocab
{...this.props}
baseUrl="owners"
records="owners"
label={this.props.stripes.intl.formatMessage({ id: 'ui-users.owners.label' })}
labelSingular={this.props.stripes.intl.formatMessage({ id: 'ui-users.owners.singular' })}
objectLabel=""
hiddenFields={['numberOfObjects']}
visibleFields={['owner', 'desc']}
columnMapping={{
owner: this.props.stripes.intl.formatMessage({ id: 'ui-users.owners.columns.owner' }),
desc: this.props.stripes.intl.formatMessage({ id: 'ui-users.owners.columns.desc' })
}}
nameKey="ownerType"
id="ownerstypes"
/>
);
}
}
export default OwnerSettings;
| Add settings for UIU-193 CRUD Fee/Fine Owners | Add settings for UIU-193 CRUD Fee/Fine Owners
| JavaScript | apache-2.0 | folio-org/ui-users,folio-org/ui-users | ---
+++
@@ -0,0 +1,40 @@
+import React from 'react';
+import PropTypes from 'prop-types';
+import ControlledVocab from '@folio/stripes-smart-components/lib/ControlledVocab';
+
+class OwnerSettings extends React.Component {
+ static propTypes = {
+ stripes: PropTypes.shape({
+ connect: PropTypes.func.isRequired,
+ intl: PropTypes.object.isRequired,
+ }).isRequired,
+ };
+
+ constructor(props) {
+ super(props);
+ this.connectedControlledVocab = props.stripes.connect(ControlledVocab);
+ }
+
+ render() {
+ return (
+ <this.connectedControlledVocab
+ {...this.props}
+ baseUrl="owners"
+ records="owners"
+ label={this.props.stripes.intl.formatMessage({ id: 'ui-users.owners.label' })}
+ labelSingular={this.props.stripes.intl.formatMessage({ id: 'ui-users.owners.singular' })}
+ objectLabel=""
+ hiddenFields={['numberOfObjects']}
+ visibleFields={['owner', 'desc']}
+ columnMapping={{
+ owner: this.props.stripes.intl.formatMessage({ id: 'ui-users.owners.columns.owner' }),
+ desc: this.props.stripes.intl.formatMessage({ id: 'ui-users.owners.columns.desc' })
+ }}
+ nameKey="ownerType"
+ id="ownerstypes"
+ />
+ );
+ }
+}
+
+export default OwnerSettings; | |
bc239931777d170dc8ab1737746fcaeb6465e1b1 | src/data/migrations/20170728095755-removeLevelsFieldsFromPools.js | src/data/migrations/20170728095755-removeLevelsFieldsFromPools.js | export async function up(r) {
return r.table('pools').replace(r.row.without('levels'))
}
export async function down() {
// irreversible; cannot recover data
}
| Remove "level" fields from pools table in database. | Remove "level" fields from pools table in database.
| JavaScript | mit | sdweber422/echo,LearnersGuild/echo | ---
+++
@@ -0,0 +1,7 @@
+export async function up(r) {
+ return r.table('pools').replace(r.row.without('levels'))
+}
+
+export async function down() {
+ // irreversible; cannot recover data
+} | |
23f2f179f298e435b49375edb7516e9b67dc0622 | database_connection.js | database_connection.js | var mysqlConnection = function(credentials) {
var mysql = require('mysql');
this.connection = mysql.createConnection(credentials);
return this;
}
mysqlConnection.prototype.getUsers = function(callback, errCallback) {
this.connection.query('SELECT username, password_hash, token FROM users', function(err, rows, fields) {
if (err) {
if (errCallback) {
errCallback(err);
}
else {
throw err;
}
}
callback(rows);
});
};
mysqlConnection.prototype.createUser = function(fields, callback, errCallback) {
this.connection.query('INSERT INTO users SET ?', fields, function(err, results, fields) {
if (err) {
if (errCallback) {
errCallback(err);
}
else {
throw err;
}
}
else {
callback();
}
});
};
mysqlConnection.prototype.loginUser = function(token, username, callback, errCallback) {
this.connection.query('UPDATE users SET token = ? WHERE username = ?', [token, username], function(err, results, fields) {
if (err) {
if (errCallback) {
errCallback(err);
}
else {
throw err;
}
}
else {
callback();
}
});
};
mysqlConnection.prototype.signoutUser = function(username, callback, errCallback) {
this.connection.query('UPDATE users SET token = NULL WHERE username = ?', username, function(err, results, fields) {
if (err) {
if (errCallback) {
errCallback(err);
}
else {
throw err;
}
}
else {
callback();
}
});
};
module.exports = (credentials, type) => {
switch (type) {
case 'mysql':
return new mysqlConnection(credentials);
break;
default:
return new mysqlConnection(credentials);
}
};
| Add database connection script with mysql option | Add database connection script with mysql option
| JavaScript | mit | peternatewood/socket-battle,peternatewood/socket-battle | ---
+++
@@ -0,0 +1,75 @@
+var mysqlConnection = function(credentials) {
+ var mysql = require('mysql');
+
+ this.connection = mysql.createConnection(credentials);
+ return this;
+}
+mysqlConnection.prototype.getUsers = function(callback, errCallback) {
+ this.connection.query('SELECT username, password_hash, token FROM users', function(err, rows, fields) {
+ if (err) {
+ if (errCallback) {
+ errCallback(err);
+ }
+ else {
+ throw err;
+ }
+ }
+
+ callback(rows);
+ });
+};
+mysqlConnection.prototype.createUser = function(fields, callback, errCallback) {
+ this.connection.query('INSERT INTO users SET ?', fields, function(err, results, fields) {
+ if (err) {
+ if (errCallback) {
+ errCallback(err);
+ }
+ else {
+ throw err;
+ }
+ }
+ else {
+ callback();
+ }
+ });
+};
+mysqlConnection.prototype.loginUser = function(token, username, callback, errCallback) {
+ this.connection.query('UPDATE users SET token = ? WHERE username = ?', [token, username], function(err, results, fields) {
+ if (err) {
+ if (errCallback) {
+ errCallback(err);
+ }
+ else {
+ throw err;
+ }
+ }
+ else {
+ callback();
+ }
+ });
+};
+mysqlConnection.prototype.signoutUser = function(username, callback, errCallback) {
+ this.connection.query('UPDATE users SET token = NULL WHERE username = ?', username, function(err, results, fields) {
+ if (err) {
+ if (errCallback) {
+ errCallback(err);
+ }
+ else {
+ throw err;
+ }
+ }
+ else {
+ callback();
+ }
+ });
+};
+
+module.exports = (credentials, type) => {
+ switch (type) {
+ case 'mysql':
+ return new mysqlConnection(credentials);
+ break;
+ default:
+ return new mysqlConnection(credentials);
+ }
+}; | |
b7ef5c2df3c76bd20691036ee20d00350538d403 | test/frontend/editController.spec.js | test/frontend/editController.spec.js | describe('editController', function(){
var scope; // use this scope in our tests
// mock Application to allow us to inject our own dependencies
beforeEach(angular.mock.module('zoomableApp'));
// mock the controller for the same reason and include $rootScope and $controller
beforeEach(angular.mock.inject(function($rootScope, $controller){
// create an empty scope
scope = $rootScope.$new();
// declare the controller and inject our empty scope
$controller('editController', {$scope: scope});
}));
// tests start here
describe('#setPrivacy', function() {
it('sets privacy to public and updates form state', function() {
scope.videoForm = {
$setDirty: jasmine.createSpy('$setDirty')
};
scope.video.privacy = 0;
scope.updatePrivacy(1);
expect(scope.video.privacy).toEqual(1);
expect(scope.videoForm.$setDirty).toHaveBeenCalled();
});
it('sets privacy to private and updates form state', function() {
scope.videoForm = {
$setDirty: jasmine.createSpy('$setDirty')
};
scope.video.privacy = 1;
scope.updatePrivacy(0);
expect(scope.video.privacy).toEqual(0);
expect(scope.videoForm.$setDirty).toHaveBeenCalled();
});
});
});
| Add unit test for editController.js | Add unit test for editController.js
| JavaScript | mit | nus-mtp/zoomable.js,nus-mtp/zoomable.js,nus-mtp/zoomable.js | ---
+++
@@ -0,0 +1,38 @@
+describe('editController', function(){
+ var scope; // use this scope in our tests
+
+ // mock Application to allow us to inject our own dependencies
+ beforeEach(angular.mock.module('zoomableApp'));
+
+ // mock the controller for the same reason and include $rootScope and $controller
+ beforeEach(angular.mock.inject(function($rootScope, $controller){
+ // create an empty scope
+ scope = $rootScope.$new();
+ // declare the controller and inject our empty scope
+ $controller('editController', {$scope: scope});
+ }));
+
+ // tests start here
+ describe('#setPrivacy', function() {
+ it('sets privacy to public and updates form state', function() {
+ scope.videoForm = {
+ $setDirty: jasmine.createSpy('$setDirty')
+ };
+ scope.video.privacy = 0;
+
+ scope.updatePrivacy(1);
+ expect(scope.video.privacy).toEqual(1);
+ expect(scope.videoForm.$setDirty).toHaveBeenCalled();
+ });
+ it('sets privacy to private and updates form state', function() {
+ scope.videoForm = {
+ $setDirty: jasmine.createSpy('$setDirty')
+ };
+ scope.video.privacy = 1;
+
+ scope.updatePrivacy(0);
+ expect(scope.video.privacy).toEqual(0);
+ expect(scope.videoForm.$setDirty).toHaveBeenCalled();
+ });
+ });
+}); | |
ee6cd9202c7a55798085d07a4c0682eade4dd1ce | app/filters/commonFilters.js | app/filters/commonFilters.js | define(['app','lodash', ], function (app,_) { 'use strict';
//##################################################################
app.filter('filterByLetter', function () {
return function (arr, letter) {
if (!arr)
return null;
if(!letter || letter==='ALL' )
return arr;
return _.filter(arr,function(item) {
//
return item.name.charAt(0) === letter;
});
};
});
}); //define
| Add common filters file. filter created to filter by first char | Add common filters file. filter created to filter by first char
| JavaScript | mit | scbd/chm.cbd.int,scbd/chm.cbd.int,scbd/chm.cbd.int | ---
+++
@@ -0,0 +1,21 @@
+define(['app','lodash', ], function (app,_) { 'use strict';
+
+ //##################################################################
+ app.filter('filterByLetter', function () {
+ return function (arr, letter) {
+ if (!arr)
+ return null;
+
+
+ if(!letter || letter==='ALL' )
+ return arr;
+
+ return _.filter(arr,function(item) {
+//
+ return item.name.charAt(0) === letter;
+ });
+ };
+ });
+
+
+}); //define | |
b51858e4e24ed5f919532724b44ea96fddf8ea61 | lib/sentient.js | lib/sentient.js | "use strict";
var Level2Compiler = require("./sentient/compiler/level2Compiler");
var Level2Runtime = require("./sentient/runtime/level2Runtime");
var Level1Compiler = require("./sentient/compiler/level1Compiler");
var Level1Runtime = require("./sentient/runtime/level1Runtime");
var Machine = require("./sentient/machine");
var MiniSatAdapter = require("./sentient/machine/miniSatAdapter");
var Sentient = function () {
var self = this;
self.compile = function (input) {
var level1Code = Level2Compiler.compile(input);
var program = Level1Compiler.compile(level1Code);
return program;
};
self.run = function (program, assignments) {
assignments = Level2Runtime.encode(program, assignments);
assignments = Level1Runtime.encode(program, assignments);
var machine = new Machine(MiniSatAdapter);
var result = machine.run(program, assignments);
result = Level1Runtime.decode(program, result);
result = Level2Runtime.decode(program, result);
return result;
};
};
Sentient.compile = function (input) {
return new Sentient().compile(input);
};
Sentient.run = function (program, assignments) {
return new Sentient().run(program, assignments);
};
module.exports = Sentient;
if (typeof window !== "undefined") {
window.Sentient = module.exports;
}
| Add a top-level Sentient module… | Add a top-level Sentient module…
This will probably be re-written to use dedicated
compiler / runtime so that they can be packaged
separately, but this will do for now. | JavaScript | bsd-3-clause | sentient-lang/sentient-lang,sentient-lang/sentient-lang | ---
+++
@@ -0,0 +1,48 @@
+"use strict";
+
+var Level2Compiler = require("./sentient/compiler/level2Compiler");
+var Level2Runtime = require("./sentient/runtime/level2Runtime");
+
+var Level1Compiler = require("./sentient/compiler/level1Compiler");
+var Level1Runtime = require("./sentient/runtime/level1Runtime");
+
+var Machine = require("./sentient/machine");
+var MiniSatAdapter = require("./sentient/machine/miniSatAdapter");
+
+var Sentient = function () {
+ var self = this;
+
+ self.compile = function (input) {
+ var level1Code = Level2Compiler.compile(input);
+ var program = Level1Compiler.compile(level1Code);
+
+ return program;
+ };
+
+ self.run = function (program, assignments) {
+ assignments = Level2Runtime.encode(program, assignments);
+ assignments = Level1Runtime.encode(program, assignments);
+
+ var machine = new Machine(MiniSatAdapter);
+ var result = machine.run(program, assignments);
+
+ result = Level1Runtime.decode(program, result);
+ result = Level2Runtime.decode(program, result);
+
+ return result;
+ };
+};
+
+Sentient.compile = function (input) {
+ return new Sentient().compile(input);
+};
+
+Sentient.run = function (program, assignments) {
+ return new Sentient().run(program, assignments);
+};
+
+module.exports = Sentient;
+
+if (typeof window !== "undefined") {
+ window.Sentient = module.exports;
+} | |
46c63ae49ee4f2b9e66dd440f2a4acc3e245f8de | src/shared/components/boardCard/boardCard.js | src/shared/components/boardCard/boardCard.js | import React from 'react';
import PropTypes from 'prop-types';
import styles from './boardCard.css';
const BoardCard = ({
alt,
name,
role,
src,
description
}) => (
<div className={styles.boardCard}>
<img className={styles.img} src={src} alt={alt} />
<span className={styles.name}>
{name}
</span>
<hr className={styles.hr} />
<span className={styles.item}>
<span className={styles.upper}>Role: </span> {role}
{description !== null && <p>{description}</p>}
</span>
</div>
);
BoardCard.propTypes = {
name: PropTypes.string.isRequired,
src: PropTypes.string.isRequired,
alt: PropTypes.string.isRequired,
role: PropTypes.string.isRequired,
description: PropTypes.string
};
BoardCard.defaultProps = {
description: null
};
export default BoardCard;
| import React from 'react';
import PropTypes from 'prop-types';
import styles from './boardCard.css';
const BoardCard = ({
alt,
name,
role,
src,
description
}) => (
<div className={styles.boardCard}>
<img className={styles.img} src={src} alt={alt} />
<span className={styles.name}>
{name}
</span>
<hr className={styles.hr} />
<span className={styles.item}>
<span className={styles.upper}>Role: </span> {role}
{description && <p>{description}</p>}
</span>
</div>
);
BoardCard.propTypes = {
name: PropTypes.string.isRequired,
src: PropTypes.string.isRequired,
alt: PropTypes.string.isRequired,
role: PropTypes.string.isRequired,
description: PropTypes.string
};
BoardCard.defaultProps = {
description: null
};
export default BoardCard;
| Make conditional rendering even shorter syntax | Make conditional rendering even shorter syntax | JavaScript | mit | hollomancer/operationcode_frontend,tskuse/operationcode_frontend,NestorSegura/operationcode_frontend,tal87/operationcode_frontend,tskuse/operationcode_frontend,tskuse/operationcode_frontend,sethbergman/operationcode_frontend,tal87/operationcode_frontend,tal87/operationcode_frontend,hollomancer/operationcode_frontend,hollomancer/operationcode_frontend,NestorSegura/operationcode_frontend,NestorSegura/operationcode_frontend,OperationCode/operationcode_frontend,OperationCode/operationcode_frontend,sethbergman/operationcode_frontend,OperationCode/operationcode_frontend,sethbergman/operationcode_frontend | ---
+++
@@ -17,7 +17,7 @@
<hr className={styles.hr} />
<span className={styles.item}>
<span className={styles.upper}>Role: </span> {role}
- {description !== null && <p>{description}</p>}
+ {description && <p>{description}</p>}
</span>
</div>
); |
92abd614459c4e702a7b786ccd285c240a758243 | app/lib/collections/flows.js | app/lib/collections/flows.js | import { Mongo } from 'meteor/mongo';
import SimpleSchema from 'simpl-schema';
import { FlowSchema } from './projects';
Flows = new Mongo.Collection('flows');
if (Meteor.isServer) {
Flows.allow({
insert: function(userId, doc) {
return false;
},
update: function(userId, doc, fieldNames, modifier) {
return false;
},
remove: function(userId, doc) {
return false;
}
});
}
if (Meteor.isClient) {
Flows.allow({
insert: function(userId, doc) {
return true;
},
update: function(userId, doc, fieldNames, modifier) {
return true;
},
remove: function(userId, doc) {
return true;
}
});
}
// A schema for flows
FlowsSeparateSchema = new SimpleSchema({
projectId: {
type: String,
},
flowId: {
type: String,
},
flowData: {
type: FlowSchema
}
});
// Attach the FlowSeparateSchema to the Flows collection
Flows.attachSchema(FlowsSeparateSchema);
| Create a separate Flows collection | Create a separate Flows collection
| JavaScript | agpl-3.0 | openp2pdesign/OpenMetaDesign,openp2pdesign/OpenMetaDesign,openp2pdesign/OpenMetaDesign | ---
+++
@@ -0,0 +1,54 @@
+import { Mongo } from 'meteor/mongo';
+import SimpleSchema from 'simpl-schema';
+import { FlowSchema } from './projects';
+
+Flows = new Mongo.Collection('flows');
+
+
+if (Meteor.isServer) {
+ Flows.allow({
+ insert: function(userId, doc) {
+ return false;
+ },
+
+ update: function(userId, doc, fieldNames, modifier) {
+ return false;
+ },
+
+ remove: function(userId, doc) {
+ return false;
+ }
+ });
+}
+
+if (Meteor.isClient) {
+ Flows.allow({
+ insert: function(userId, doc) {
+ return true;
+ },
+
+ update: function(userId, doc, fieldNames, modifier) {
+ return true;
+ },
+
+ remove: function(userId, doc) {
+ return true;
+ }
+ });
+}
+
+// A schema for flows
+FlowsSeparateSchema = new SimpleSchema({
+ projectId: {
+ type: String,
+ },
+ flowId: {
+ type: String,
+ },
+ flowData: {
+ type: FlowSchema
+ }
+});
+
+// Attach the FlowSeparateSchema to the Flows collection
+Flows.attachSchema(FlowsSeparateSchema); | |
273c67b0d7cfee84adb181ca10e80f69e8b69d27 | test/unit/server/util/adjust-resource-quantity.js | test/unit/server/util/adjust-resource-quantity.js | const adjustResourceQuantity = require('../../../../server/util/adjust-resource-quantity');
adjustResourceQuantity.setResources([
{name: 'cat', plural_form: 'cats'},
{name: 'person', plural_form: 'people'},
]);
describe('adjustResourceQuantity', function() {
describe('when requesting singular', () => {
it('should return the plural form', () => {
assert.equal(adjustResourceQuantity.getPluralName('cat'), 'cats');
});
});
describe('when requesting plural', () => {
it('should return the single form', () => {
assert.equal(adjustResourceQuantity.getSingularName('people'), 'person');
});
});
});
| Add unit tests for adjustResourceQuantity | Add unit tests for adjustResourceQuantity
| JavaScript | mit | jmeas/api-pls | ---
+++
@@ -0,0 +1,20 @@
+const adjustResourceQuantity = require('../../../../server/util/adjust-resource-quantity');
+
+adjustResourceQuantity.setResources([
+ {name: 'cat', plural_form: 'cats'},
+ {name: 'person', plural_form: 'people'},
+]);
+
+describe('adjustResourceQuantity', function() {
+ describe('when requesting singular', () => {
+ it('should return the plural form', () => {
+ assert.equal(adjustResourceQuantity.getPluralName('cat'), 'cats');
+ });
+ });
+
+ describe('when requesting plural', () => {
+ it('should return the single form', () => {
+ assert.equal(adjustResourceQuantity.getSingularName('people'), 'person');
+ });
+ });
+}); | |
f82f69de8cc08ac27b9948264582bffda635027c | Gruntfile.js | Gruntfile.js | module.exports = function(grunt) {
grunt.initConfig({
less: {
production: {
options: {
paths: [ "bower_components/bootstrap/less" ],
cleancss: true
},
files: {
"css/application.min.css": "_less/application.less"
}
}
},
uglify: {
jquery: {
files: {
"js/jquery.min.js": "bower_components/jquery/jquery.js"
}
},
bootstrap: {
files: {
"js/bootstrap.min.js": [
"bower_components/bootstrap/js/transition.js",
"bower_components/bootstrap/js/alert.js",
"bower_components/bootstrap/js/button.js",
"bower_components/bootstrap/js/carousel.js",
"bower_components/bootstrap/js/collapse.js",
"bower_components/bootstrap/js/dropdown.js",
"bower_components/bootstrap/js/modal.js",
"bower_components/bootstrap/js/tooltip.js",
"bower_components/bootstrap/js/popover.js",
"bower_components/bootstrap/js/scrollspy.js",
"bower_components/bootstrap/js/tab.js",
"bower_components/bootstrap/js/affix.js"
]
}
}
},
copy: {
bootstrap: {
files: [
{
expand: true,
cwd: "bower_components/bootstrap/img/",
src: ["**"],
dest: "assets/img/"
}
]
}
},
shell: {
jekyllBuild: {
command: "jekyll build"
},
jekyllServe: {
command: "jekyll serve"
}
}
});
grunt.loadNpmTasks("grunt-contrib-less");
grunt.loadNpmTasks("grunt-contrib-uglify");
grunt.loadNpmTasks("grunt-contrib-copy");
grunt.loadNpmTasks("grunt-shell");
grunt.registerTask("default", [ "less", "uglify", "copy", "shell:jekyllBuild" ]);
};
| Build and serve via Grunt. | Build and serve via Grunt.
| JavaScript | bsd-3-clause | nfloersch/codeforbtv.github.com,nfloersch/codeforbtv.github.com,nfloersch/codeforbtv.github.com | ---
+++
@@ -0,0 +1,69 @@
+module.exports = function(grunt) {
+
+ grunt.initConfig({
+ less: {
+ production: {
+ options: {
+ paths: [ "bower_components/bootstrap/less" ],
+ cleancss: true
+ },
+ files: {
+ "css/application.min.css": "_less/application.less"
+ }
+ }
+ },
+ uglify: {
+ jquery: {
+ files: {
+ "js/jquery.min.js": "bower_components/jquery/jquery.js"
+ }
+ },
+ bootstrap: {
+ files: {
+ "js/bootstrap.min.js": [
+ "bower_components/bootstrap/js/transition.js",
+ "bower_components/bootstrap/js/alert.js",
+ "bower_components/bootstrap/js/button.js",
+ "bower_components/bootstrap/js/carousel.js",
+ "bower_components/bootstrap/js/collapse.js",
+ "bower_components/bootstrap/js/dropdown.js",
+ "bower_components/bootstrap/js/modal.js",
+ "bower_components/bootstrap/js/tooltip.js",
+ "bower_components/bootstrap/js/popover.js",
+ "bower_components/bootstrap/js/scrollspy.js",
+ "bower_components/bootstrap/js/tab.js",
+ "bower_components/bootstrap/js/affix.js"
+ ]
+ }
+ }
+ },
+ copy: {
+ bootstrap: {
+ files: [
+ {
+ expand: true,
+ cwd: "bower_components/bootstrap/img/",
+ src: ["**"],
+ dest: "assets/img/"
+ }
+ ]
+ }
+ },
+ shell: {
+ jekyllBuild: {
+ command: "jekyll build"
+ },
+ jekyllServe: {
+ command: "jekyll serve"
+ }
+ }
+ });
+
+ grunt.loadNpmTasks("grunt-contrib-less");
+ grunt.loadNpmTasks("grunt-contrib-uglify");
+ grunt.loadNpmTasks("grunt-contrib-copy");
+ grunt.loadNpmTasks("grunt-shell");
+
+ grunt.registerTask("default", [ "less", "uglify", "copy", "shell:jekyllBuild" ]);
+
+}; | |
6e48690e84b3b9411b8fe5872941dd0ed1e40da0 | app/js/arethusa.relation/directives/nested_menu.js | app/js/arethusa.relation/directives/nested_menu.js | "use strict";
angular.module('arethusa.relation').directive('nestedMenu', [
'$compile',
function($compile) {
return {
restrict: 'A',
scope: {
relation: '=',
values: '=',
label: '='
},
link: function(scope, element, attrs) {
//var nestedHtml = '<ul nested-menu relation="relation" labels="labels"></ul>';
//angular.forEach(scope.labels, function(obj, label) {
//if (obj.nested) {
//var li = angular.element('#' + label);
//var childScope = scope.$new();
//childScope.labels = obj.nested;
//console.log(li);
//console.log($compile(nestedHtml)(childScope));
//li.append($compile(nestedHtml)(childScope));
//}
//});
//console.log('1');
var html = '<ul><li ng-repeat="(k, v) in values.nested" nested-menu relation="relation" label="k" values="v"></li></ul>';
if (scope.values.nested) {
element.append($compile(html)(scope));
}
},
template: '{{ label }}'
};
}
]);
| Add nesteMenu directive in relation | Add nesteMenu directive in relation
| JavaScript | mit | alpheios-project/arethusa,fbaumgardt/arethusa,fbaumgardt/arethusa,Masoumeh/arethusa,fbaumgardt/arethusa,PonteIneptique/arethusa,alpheios-project/arethusa,latin-language-toolkit/arethusa,PonteIneptique/arethusa,Masoumeh/arethusa,alpheios-project/arethusa,latin-language-toolkit/arethusa | ---
+++
@@ -0,0 +1,35 @@
+"use strict";
+
+angular.module('arethusa.relation').directive('nestedMenu', [
+ '$compile',
+ function($compile) {
+ return {
+ restrict: 'A',
+ scope: {
+ relation: '=',
+ values: '=',
+ label: '='
+ },
+ link: function(scope, element, attrs) {
+ //var nestedHtml = '<ul nested-menu relation="relation" labels="labels"></ul>';
+
+ //angular.forEach(scope.labels, function(obj, label) {
+ //if (obj.nested) {
+ //var li = angular.element('#' + label);
+ //var childScope = scope.$new();
+ //childScope.labels = obj.nested;
+ //console.log(li);
+ //console.log($compile(nestedHtml)(childScope));
+ //li.append($compile(nestedHtml)(childScope));
+ //}
+ //});
+ //console.log('1');
+ var html = '<ul><li ng-repeat="(k, v) in values.nested" nested-menu relation="relation" label="k" values="v"></li></ul>';
+ if (scope.values.nested) {
+ element.append($compile(html)(scope));
+ }
+ },
+ template: '{{ label }}'
+ };
+ }
+]); | |
243f86b8177d59647b60db50f2961cec431badf7 | chapter_06/load_crawl_urls.js | chapter_06/load_crawl_urls.js | const AWS = require('aws-sdk');
const async = require('async');
const argv = require('minimist')(process.argv.slice(2));
const config = require('./config');
const helpers = require('./helpers');
AWS.config.update({ region: 'us-east-1' });
const urls = argv._;
if (urls.length === 0) {
console.error('Usage: node load_crawl_urls.js <URL...>');
process.exit(1);
}
const sqs = new AWS.SQS();
helpers.findQueueURL(sqs, config.URL_QUEUE, (err, queueURL) => {
async.each(urls, (url, cb) => {
const message = {
origin: 'load_crawl_urls.js',
data: url,
history: [`Posted by load_crawl_urls.js on ${(new Date()).toISOString()}`]
};
sqs.sendMessage({
QueueUrl: queueURL,
MessageBody: JSON.stringify(message)
}, (err) => {
if (!err) {
console.log(`Posted '${JSON.stringify(message)}' to '${queueURL}'.`);
}
cb(err);
});
}, (err) => {
if (err) console.log(err);
});
});
| Add script to add URL to queue | Add script to add URL to queue
| JavaScript | mit | colinking/host_your_website_jeff_barr,colinking/host_your_website_jeff_barr | ---
+++
@@ -0,0 +1,36 @@
+const AWS = require('aws-sdk');
+const async = require('async');
+const argv = require('minimist')(process.argv.slice(2));
+const config = require('./config');
+const helpers = require('./helpers');
+
+AWS.config.update({ region: 'us-east-1' });
+
+const urls = argv._;
+
+if (urls.length === 0) {
+ console.error('Usage: node load_crawl_urls.js <URL...>');
+ process.exit(1);
+}
+
+const sqs = new AWS.SQS();
+helpers.findQueueURL(sqs, config.URL_QUEUE, (err, queueURL) => {
+ async.each(urls, (url, cb) => {
+ const message = {
+ origin: 'load_crawl_urls.js',
+ data: url,
+ history: [`Posted by load_crawl_urls.js on ${(new Date()).toISOString()}`]
+ };
+ sqs.sendMessage({
+ QueueUrl: queueURL,
+ MessageBody: JSON.stringify(message)
+ }, (err) => {
+ if (!err) {
+ console.log(`Posted '${JSON.stringify(message)}' to '${queueURL}'.`);
+ }
+ cb(err);
+ });
+ }, (err) => {
+ if (err) console.log(err);
+ });
+}); | |
20fa1dc0a4a870e54b361af453e6a112130e1a99 | app/index.js | app/index.js | "use strict";
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var favicon = require('serve-favicon');
var routes = require('./routes');
var cachebuster = require('./routes/cachebuster');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(favicon(__dirname + '/public/favicon.ico'));
// static files
var publicPath = path.join(__dirname, 'public');
app.use(express.static(publicPath));
app.get(cachebuster.path, cachebuster.remove, express.static(publicPath), cachebuster.restore);
// use react routes
app.use('/', routes);
module.exports = app; | "use strict";
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var favicon = require('serve-favicon');
var routes = require('./routes');
var cachebuster = require('./routes/cachebuster');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger(app.get('env') === 'production' ? 'combined' : 'dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(favicon(__dirname + '/public/favicon.ico'));
// static files
var publicPath = path.join(__dirname, 'public');
app.use(express.static(publicPath));
app.get(cachebuster.path, cachebuster.remove, express.static(publicPath), cachebuster.restore);
// use react routes
app.use('/', routes);
module.exports = app; | Print combined logs in production | Print combined logs in production
| JavaScript | mit | pheadra/isomorphic500,devypt/isomorphic500,jonathanconway/MovieBrowser,gpbl/isomorphic500,veeracs/isomorphic500,jeffhandley/oredev-sessions,beeva-davidgarcia/isomorphic500,geekyme/isomorphic-react-template,fustic/isomorphic500,jmfurlott/isomorphic500,ryankanno/isomorphic500,davedx/isomorphic-react-template,dmitrif/isomorphic500,geekyme/isomorphic-react-template,elfinxx/isomorphic500,saitodisse/isomorphic500,jxnblk/isomorphic500,w01fgang/isomorphic500,davedx/isomorphic-react-template | ---
+++
@@ -14,7 +14,7 @@
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
-app.use(logger('dev'));
+app.use(logger(app.get('env') === 'production' ? 'combined' : 'dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser()); |
a88b98ac08d8918dbb8ae2c274ff6d88fa983694 | tests/unit/controllers/tasks.js | tests/unit/controllers/tasks.js | const TaskController = require('../../../controllers/tasks');
describe('Controllers: Tasks', () => {
describe('Get all tasks from a tasklist: getAll()', () => {
it('should return all tasks', () => {
const Task = {
getAll: td.function(),
}
const owner = {
id: 1,
name: 'Tasklist owner',
description: 'Someother desc here',
created_at: '2016-10-08T19:03:02.923Z',
}
const expectedResponse = [{
id: 2,
name: 'Test Task 1',
created_at: '2016-10-08T19:03:02.923Z',
description: 'Some desc here',
belongs: owner
}];
td.when(Task.getAll(owner)).thenResolve(expectedResponse);
const taskCtrl = TaskController(Task);
return taskCtrl.getAll(owner)
.then((response) => expect(response).to.be.eql(expectedResponse));
});
});
});
| Create unit test to task controller (getAll) | Create unit test to task controller (getAll)
| JavaScript | mit | jonatasleon/neo4j-tutorial,jonatasleon/neo4j-tutorial | ---
+++
@@ -0,0 +1,33 @@
+const TaskController = require('../../../controllers/tasks');
+
+describe('Controllers: Tasks', () => {
+
+ describe('Get all tasks from a tasklist: getAll()', () => {
+ it('should return all tasks', () => {
+ const Task = {
+ getAll: td.function(),
+ }
+
+ const owner = {
+ id: 1,
+ name: 'Tasklist owner',
+ description: 'Someother desc here',
+ created_at: '2016-10-08T19:03:02.923Z',
+ }
+
+ const expectedResponse = [{
+ id: 2,
+ name: 'Test Task 1',
+ created_at: '2016-10-08T19:03:02.923Z',
+ description: 'Some desc here',
+ belongs: owner
+ }];
+
+ td.when(Task.getAll(owner)).thenResolve(expectedResponse);
+
+ const taskCtrl = TaskController(Task);
+ return taskCtrl.getAll(owner)
+ .then((response) => expect(response).to.be.eql(expectedResponse));
+ });
+ });
+}); | |
6fccdf744ff88a14ee0cd3a7334bd215ff59d791 | test/jsxtest.js | test/jsxtest.js | import { Component, Render, RasterManager, View, Text } from '../index';
const assert = require('assert');
describe('JSX', function() {
describe('Comments', function() {
it('should not include comments in children', function() {
class MyComponent extends Component {
render() {
return <View>
{/*These are comments*/}
<View/>
{/*These are comments*/}
<Text> Hello </Text>
{/*These are comments*/}
</View>;
}
}
const mycomponent = new MyComponent();
const rendering = mycomponent.render();
assert.equal(typeof rendering.elementName, 'function');
assert.equal(typeof rendering.attributes, 'object');
assert.equal(rendering.children instanceof Array, true);
assert.equal(rendering.children.length, 2);
assert.equal(typeof rendering.guid, 'string');
});
});
});
| Test to check JSX does not pass comments as children. | Test to check JSX does not pass comments as children.
| JavaScript | mit | dmikey/syr,dmikey/syr,dmikey/syr,dmikey/syr | ---
+++
@@ -0,0 +1,29 @@
+import { Component, Render, RasterManager, View, Text } from '../index';
+const assert = require('assert');
+
+describe('JSX', function() {
+ describe('Comments', function() {
+ it('should not include comments in children', function() {
+ class MyComponent extends Component {
+ render() {
+ return <View>
+ {/*These are comments*/}
+ <View/>
+ {/*These are comments*/}
+ <Text> Hello </Text>
+ {/*These are comments*/}
+ </View>;
+ }
+ }
+
+ const mycomponent = new MyComponent();
+ const rendering = mycomponent.render();
+
+ assert.equal(typeof rendering.elementName, 'function');
+ assert.equal(typeof rendering.attributes, 'object');
+ assert.equal(rendering.children instanceof Array, true);
+ assert.equal(rendering.children.length, 2);
+ assert.equal(typeof rendering.guid, 'string');
+ });
+ });
+}); | |
cb5f8e7d25388849d4caed72d839253f7d94a56c | test/queries.js | test/queries.js | import test from 'ava'
import nock from 'nock'
import data from './fixtures/data'
import Onionoo from '../'
test('Query string is built correctly', async t => {
const onionoo = new Onionoo()
const defaultEndpoint = data.defaultEndpoints[0]
const scope = nock(data.defaultBaseUrl)
.get(`/${defaultEndpoint}?foo=bar`)
.reply(200, data.dummyResponse)
const response = await onionoo[defaultEndpoint]({ foo: 'bar' })
t.deepEqual(response.body, data.dummyResponse)
t.truthy(scope.isDone())
})
| Test query string is built correctly | Test query string is built correctly
| JavaScript | mit | lukechilds/onionoo-node-client | ---
+++
@@ -0,0 +1,18 @@
+import test from 'ava'
+import nock from 'nock'
+import data from './fixtures/data'
+import Onionoo from '../'
+
+test('Query string is built correctly', async t => {
+ const onionoo = new Onionoo()
+
+ const defaultEndpoint = data.defaultEndpoints[0]
+ const scope = nock(data.defaultBaseUrl)
+ .get(`/${defaultEndpoint}?foo=bar`)
+ .reply(200, data.dummyResponse)
+
+ const response = await onionoo[defaultEndpoint]({ foo: 'bar' })
+
+ t.deepEqual(response.body, data.dummyResponse)
+ t.truthy(scope.isDone())
+}) | |
7944212d6c2ad4b7d4bd8141f2918d4f08b1b90e | tests/server.js | tests/server.js | "use strict";
var Server = require("../server");
exports.testMissingBasicHeader = function (test) {
var parser = Server.prototype._basicAuthentication({
"headers": {}
});
parser().fail(function (err) {
test.equal(401, err.statusCode);
test.done();
});
};
exports.testValidBasicHeader = function (test) {
var parser = Server.prototype._basicAuthentication({
"headers": { "authorization": "Basic Zm9vOmJhcg==" }
});
parser().then(function (result) {
test.deepEqual(["foo", "bar"], result);
test.done();
});
};
exports.testInvalidBasicHeader = function (test) {
var parser = Server.prototype._basicAuthentication({
"headers": { "authorization": "What the heck is this" }
});
parser().fail(function (err) {
test.equal(400, err.statusCode);
test.done();
});
};
| Add tests for basic auth header parser | Add tests for basic auth header parser
| JavaScript | isc | whymarrh/mattress | ---
+++
@@ -0,0 +1,33 @@
+"use strict";
+
+var Server = require("../server");
+
+exports.testMissingBasicHeader = function (test) {
+ var parser = Server.prototype._basicAuthentication({
+ "headers": {}
+ });
+ parser().fail(function (err) {
+ test.equal(401, err.statusCode);
+ test.done();
+ });
+};
+
+exports.testValidBasicHeader = function (test) {
+ var parser = Server.prototype._basicAuthentication({
+ "headers": { "authorization": "Basic Zm9vOmJhcg==" }
+ });
+ parser().then(function (result) {
+ test.deepEqual(["foo", "bar"], result);
+ test.done();
+ });
+};
+
+exports.testInvalidBasicHeader = function (test) {
+ var parser = Server.prototype._basicAuthentication({
+ "headers": { "authorization": "What the heck is this" }
+ });
+ parser().fail(function (err) {
+ test.equal(400, err.statusCode);
+ test.done();
+ });
+}; | |
6c40337f6b32f1ace131ab2e2238cceebefa9cfe | test/index.js | test/index.js | const koa = require('koa'),
expect = require('expect'),
uncapitalize = require('../'),
app = koa();
app.use(uncapitalize);
app.use(function *(next) {
if (this.path.toLowerCase() != '/test') {
return yield next;
}
this.body = "OK";
});
const request = require('supertest').agent(app.listen());
describe('koa uncapitalize', function() {
describe('lowercase routes', function() {
it('should not redirect', function(done) {
request.get('/test').expect(200, done);
});
});
describe('uppercase routes', function() {
it('should redirect', function(done) {
request.get('/TEST').expect(301, done);
});
});
});
| Add simple tests to detect redirect behavior | Add simple tests to detect redirect behavior
| JavaScript | mit | mfinelli/koa-uncapitalize | ---
+++
@@ -0,0 +1,29 @@
+const koa = require('koa'),
+ expect = require('expect'),
+ uncapitalize = require('../'),
+ app = koa();
+
+app.use(uncapitalize);
+app.use(function *(next) {
+ if (this.path.toLowerCase() != '/test') {
+ return yield next;
+ }
+
+ this.body = "OK";
+});
+
+const request = require('supertest').agent(app.listen());
+
+describe('koa uncapitalize', function() {
+ describe('lowercase routes', function() {
+ it('should not redirect', function(done) {
+ request.get('/test').expect(200, done);
+ });
+ });
+
+ describe('uppercase routes', function() {
+ it('should redirect', function(done) {
+ request.get('/TEST').expect(301, done);
+ });
+ });
+}); | |
49a9a81570b45f3d024035fb1e31fc1d775edeb0 | src/test/js/scryptSpeed.js | src/test/js/scryptSpeed.js | /**
* Example command for running this testing utility:
*
* <pre>
* jjs -cp ~/.m2/repository/commons-codec/commons-codec/1.10/commons-codec-1.10.jar:target/scrypt-1.4.0.jar scryptTimer.js
* </pre>
*
* If you don't have commons-codec, use the following command to download with Maven:
*
* <pre>
* mvn dependency:get -Dartifact=commons-codec:commons-codec:1.10
* </pre>
*
*/
var SCrypt = com.lambdaworks.crypto.SCrypt;
var System = java.lang.System;
var Hex = org.apache.commons.codec.binary.Hex;
var f = Hex.class.getClassLoader().loadClass("com.lambdaworks.crypto.SCrypt").getDeclaredField("native_library_loaded");
f.setAccessible(true);
var native = f.get(null);
System.out.println("Using " + (native ? "Native" : "Java") + " scrypt implementation." );
var startTs = System.currentTimeMillis();
var P, S, N, r, p, dkLen;
var expected, actual;
P = "pleaseletmein".getBytes("UTF-8");
S = "SodiumChloride".getBytes("UTF-8");
N = 1048576;
r = 8;
p = 1;
dkLen = 64;
expected = "2101cb9b6a511aaeaddbbe09cf70f881ec568d574a2ffd4dabe5ee9820adaa478e56fd8f4ba5d09ffa1c6d927c40f4c337304049e8a952fbcbf45c6fa77a41a4";
actual = SCrypt.scrypt(P, S, N, r, p, dkLen);
actual = Hex.encodeHexString(actual);
var endTs = System.currentTimeMillis();
System.out.println("expect: " + expected);
System.out.println("actual: " + actual);
System.out.println("Time: " + (endTs - startTs) / 1000 + " sec");
| Add a jjs runnable JavaScript test script to ease testing whether native library is loaded on a specific platform. | Add a jjs runnable JavaScript test script to ease testing whether native
library is loaded on a specific platform.
Signed-off-by: Haochen Xie <6cdef7921402f78bb75e2821c6818c66fb01ab31@xie.name>
| JavaScript | apache-2.0 | haochenx/scrypt,haochenx/scrypt,haochenx/scrypt | ---
+++
@@ -0,0 +1,45 @@
+/**
+ * Example command for running this testing utility:
+ *
+ * <pre>
+ * jjs -cp ~/.m2/repository/commons-codec/commons-codec/1.10/commons-codec-1.10.jar:target/scrypt-1.4.0.jar scryptTimer.js
+ * </pre>
+ *
+ * If you don't have commons-codec, use the following command to download with Maven:
+ *
+ * <pre>
+ * mvn dependency:get -Dartifact=commons-codec:commons-codec:1.10
+ * </pre>
+ *
+ */
+
+var SCrypt = com.lambdaworks.crypto.SCrypt;
+var System = java.lang.System;
+var Hex = org.apache.commons.codec.binary.Hex;
+
+var f = Hex.class.getClassLoader().loadClass("com.lambdaworks.crypto.SCrypt").getDeclaredField("native_library_loaded");
+f.setAccessible(true);
+var native = f.get(null);
+System.out.println("Using " + (native ? "Native" : "Java") + " scrypt implementation." );
+
+var startTs = System.currentTimeMillis();
+
+var P, S, N, r, p, dkLen;
+var expected, actual;
+
+P = "pleaseletmein".getBytes("UTF-8");
+S = "SodiumChloride".getBytes("UTF-8");
+N = 1048576;
+r = 8;
+p = 1;
+dkLen = 64;
+expected = "2101cb9b6a511aaeaddbbe09cf70f881ec568d574a2ffd4dabe5ee9820adaa478e56fd8f4ba5d09ffa1c6d927c40f4c337304049e8a952fbcbf45c6fa77a41a4";
+
+actual = SCrypt.scrypt(P, S, N, r, p, dkLen);
+actual = Hex.encodeHexString(actual);
+
+var endTs = System.currentTimeMillis();
+
+System.out.println("expect: " + expected);
+System.out.println("actual: " + actual);
+System.out.println("Time: " + (endTs - startTs) / 1000 + " sec"); | |
7be879358cc4b91d4fafb504641d652133d48c86 | lib/remixes/floodgap.js | lib/remixes/floodgap.js | 'use strict';
// Generate image link
var SERVICE_FLOODGAP = /(((www.floodgap\.com))\/\w\/\w+)/i;
exports.process = function(media, remix) {
if (!remix.isMatched && media.link.match(SERVICE_FLOODGAP)) {
var parts = media.link.split('/');
var shortcode = parts[parts.length - 2];
remix.isMatched = true;
remix.result = (media.text != media.url) ? media.text + ' ' : '';
remix.result += '<div class="image-wrapper"><a href="' + media.link + '">' +
'<img src="http://http://www.floodgap.com/iv-store/' + shortcode + '.jpg"/></a></div><a href="' + media.link +
'" target="_blank" class="media-off">' + media.text + '</a>';
}
return remix;
};
| Add an image remix for Cameron Kaiser’s (@doctorlinguist) image posts. | Add an image remix for Cameron Kaiser’s (@doctorlinguist) image posts.
| JavaScript | bsd-3-clause | 33mhz/noodleapp | ---
+++
@@ -0,0 +1,20 @@
+'use strict';
+
+// Generate image link
+var SERVICE_FLOODGAP = /(((www.floodgap\.com))\/\w\/\w+)/i;
+
+exports.process = function(media, remix) {
+ if (!remix.isMatched && media.link.match(SERVICE_FLOODGAP)) {
+ var parts = media.link.split('/');
+ var shortcode = parts[parts.length - 2];
+
+ remix.isMatched = true;
+
+ remix.result = (media.text != media.url) ? media.text + ' ' : '';
+ remix.result += '<div class="image-wrapper"><a href="' + media.link + '">' +
+ '<img src="http://http://www.floodgap.com/iv-store/' + shortcode + '.jpg"/></a></div><a href="' + media.link +
+ '" target="_blank" class="media-off">' + media.text + '</a>';
+ }
+
+ return remix;
+}; | |
b9415f91b0b25ae6b0ea21e2cccd6bf5f6ad4f60 | Easy/155_Min_Stack.js | Easy/155_Min_Stack.js | /**
* @constructor
*/
var MinStack = function() {
this.stack = [];
this.minStack = [];
};
/**
* @param {number} x
* @returns {void}
*/
MinStack.prototype.push = function(x) {
this.stack.push(x);
if (this.minStack.length === 0 || x <= this.minStack[this.minStack.length - 1]) {
this.minStack.push(x);
}
};
/**
* @returns {void}
*/
MinStack.prototype.pop = function() {
var poped = this.stack.pop();
if (poped === this.minStack[this.minStack.length - 1]) {
this.minStack.pop();
}
};
/**
* @returns {number}
*/
MinStack.prototype.top = function() {
return this.stack[this.stack.length - 1];
};
/**
* @returns {number}
*/
MinStack.prototype.getMin = function() {
return this.minStack[this.minStack.length - 1];
};
| Add solution to question 155 | Add solution to question 155
| JavaScript | mit | Rhadow/leetcode,Rhadow/leetcode,Rhadow/leetcode,Rhadow/leetcode | ---
+++
@@ -0,0 +1,42 @@
+/**
+ * @constructor
+ */
+var MinStack = function() {
+ this.stack = [];
+ this.minStack = [];
+};
+
+/**
+ * @param {number} x
+ * @returns {void}
+ */
+MinStack.prototype.push = function(x) {
+ this.stack.push(x);
+ if (this.minStack.length === 0 || x <= this.minStack[this.minStack.length - 1]) {
+ this.minStack.push(x);
+ }
+};
+
+/**
+ * @returns {void}
+ */
+MinStack.prototype.pop = function() {
+ var poped = this.stack.pop();
+ if (poped === this.minStack[this.minStack.length - 1]) {
+ this.minStack.pop();
+ }
+};
+
+/**
+ * @returns {number}
+ */
+MinStack.prototype.top = function() {
+ return this.stack[this.stack.length - 1];
+};
+
+/**
+ * @returns {number}
+ */
+MinStack.prototype.getMin = function() {
+ return this.minStack[this.minStack.length - 1];
+}; | |
dd36e9af22d3a522e449e47abc0143475fd24b82 | tests/node/sourcemap-test.js | tests/node/sourcemap-test.js | var fs = require('fs');
QUnit.module('sourcemap validation', function() {
var assets = ['ember.debug', 'ember.prod', 'ember.min'];
assets.forEach(asset => {
QUnit.test(`${asset} has only a single sourcemaps comment`, function(assert) {
var jsPath = `dist/${asset}.js`;
assert.ok(fs.existsSync(jsPath));
var contents = fs.readFileSync(jsPath, 'utf-8');
var num = count(contents, '//# sourceMappingURL=');
assert.equal(num, 1);
});
});
});
function count(source, find) {
var num = 0;
var i = -1;
while ((i = source.indexOf(find, i + 1)) !== -1) {
num += 1;
}
return num;
}
| Add Node.js test asserting on the number of sourcemap comments in final assets | Add Node.js test asserting on the number of sourcemap comments in final assets
| JavaScript | mit | asakusuma/ember.js,givanse/ember.js,kellyselden/ember.js,Turbo87/ember.js,GavinJoyce/ember.js,qaiken/ember.js,qaiken/ember.js,intercom/ember.js,givanse/ember.js,jaswilli/ember.js,qaiken/ember.js,jaswilli/ember.js,mixonic/ember.js,bekzod/ember.js,kellyselden/ember.js,bekzod/ember.js,sly7-7/ember.js,miguelcobain/ember.js,Turbo87/ember.js,GavinJoyce/ember.js,cibernox/ember.js,knownasilya/ember.js,knownasilya/ember.js,emberjs/ember.js,asakusuma/ember.js,bekzod/ember.js,jaswilli/ember.js,asakusuma/ember.js,cibernox/ember.js,knownasilya/ember.js,tildeio/ember.js,givanse/ember.js,jaswilli/ember.js,kellyselden/ember.js,mfeckie/ember.js,elwayman02/ember.js,miguelcobain/ember.js,emberjs/ember.js,mixonic/ember.js,miguelcobain/ember.js,fpauser/ember.js,cibernox/ember.js,Turbo87/ember.js,givanse/ember.js,tildeio/ember.js,stefanpenner/ember.js,sandstrom/ember.js,intercom/ember.js,mfeckie/ember.js,Turbo87/ember.js,fpauser/ember.js,fpauser/ember.js,intercom/ember.js,asakusuma/ember.js,emberjs/ember.js,mfeckie/ember.js,qaiken/ember.js,GavinJoyce/ember.js,mixonic/ember.js,elwayman02/ember.js,fpauser/ember.js,elwayman02/ember.js,sly7-7/ember.js,elwayman02/ember.js,GavinJoyce/ember.js,mfeckie/ember.js,tildeio/ember.js,sandstrom/ember.js,miguelcobain/ember.js,bekzod/ember.js,kellyselden/ember.js,sly7-7/ember.js,stefanpenner/ember.js,sandstrom/ember.js,cibernox/ember.js,stefanpenner/ember.js,intercom/ember.js | ---
+++
@@ -0,0 +1,27 @@
+var fs = require('fs');
+
+QUnit.module('sourcemap validation', function() {
+ var assets = ['ember.debug', 'ember.prod', 'ember.min'];
+
+ assets.forEach(asset => {
+ QUnit.test(`${asset} has only a single sourcemaps comment`, function(assert) {
+ var jsPath = `dist/${asset}.js`;
+ assert.ok(fs.existsSync(jsPath));
+
+ var contents = fs.readFileSync(jsPath, 'utf-8');
+ var num = count(contents, '//# sourceMappingURL=');
+ assert.equal(num, 1);
+ });
+ });
+});
+
+function count(source, find) {
+ var num = 0;
+
+ var i = -1;
+ while ((i = source.indexOf(find, i + 1)) !== -1) {
+ num += 1;
+ }
+
+ return num;
+} | |
234e5503df070b34f220a2cc483921aa754d2ac3 | lib/resources/hook/attemptToRequireUntrustedHook.js | lib/resources/hook/attemptToRequireUntrustedHook.js | var config = require('../../../config');
var fs = require("fs");
module['exports'] = function attemptToRequireUntrustedHook (opts, callback) {
var username = opts.username,
script = opts.script;
var untrustedHook;
var isStreamingHook;
var untrustedTemplate;
var err = null;
// At this stage, the hook source code is untrusted ( and should be validated )
try {
var _script = require.resolve(__dirname + '/../../../temp/' + username + "/" + opts.req.hook.name + "/" + script + '.js');
delete require.cache[_script];
untrustedHook = require(_script);
opts.req.hook = opts.req.hook || {};
untrustedHook.schema = untrustedHook.schema || {};
untrustedHook.theme = untrustedHook.theme || opts.req.hook.theme || config.defaultTheme;
untrustedHook.presenter = untrustedHook.presenter || opts.req.hook.presenter || config.defaultPresenter;
} catch (e) {
err = e;
}
if (err) {
return fs.readFile(__dirname + '/../../../temp/' + username + "/" + script + '.js', function(_err, _source){
if (_err) {
throw _err;
return callback(_err);
}
// unable to require Hook as commonjs module,
// the Hook is invalid
return callback(err, _source);
});
}
return callback(null, untrustedHook)
};
| var config = require('../../../config');
var fs = require("fs");
module['exports'] = function attemptToRequireUntrustedHook (opts, callback) {
var username = opts.username,
script = opts.script;
var untrustedHook;
var isStreamingHook;
var untrustedTemplate;
var err = null;
// At this stage, the hook source code is untrusted ( and should be validated )
try {
var _script = require.resolve(__dirname + '/../../../temp/' + username + "/" + opts.req.hook.name + "/" + script + '.js');
delete require.cache[_script];
untrustedHook = require(_script);
opts.req.hook = opts.req.hook || {};
untrustedHook.schema = untrustedHook.schema || {};
untrustedHook.theme = opts.req.hook.theme || untrustedHook.theme || config.defaultTheme;
untrustedHook.presenter = opts.req.hook.presenter || untrustedHook.presenter || config.defaultPresenter;
} catch (e) {
err = e;
}
if (err) {
return fs.readFile(__dirname + '/../../../temp/' + username + "/" + script + '.js', function(_err, _source){
if (_err) {
throw _err;
return callback(_err);
}
// unable to require Hook as commonjs module,
// the Hook is invalid
return callback(err, _source);
});
}
return callback(null, untrustedHook)
};
| Set param theme precedence over hook theme module scope ( for now ) | [api] Set param theme precedence over hook theme module scope ( for now ) | JavaScript | agpl-3.0 | ljharb/hook.io,ljharb/hook.io,ajnsit/hook.io,joshgillies/hook.io,joshgillies/hook.io,ljharb/hook.io,joshgillies/hook.io,joshgillies/hook.io,joshgillies/hook.io,ajnsit/hook.io,joshgillies/hook.io,ajnsit/hook.io,joshgillies/hook.io | ---
+++
@@ -18,8 +18,8 @@
untrustedHook = require(_script);
opts.req.hook = opts.req.hook || {};
untrustedHook.schema = untrustedHook.schema || {};
- untrustedHook.theme = untrustedHook.theme || opts.req.hook.theme || config.defaultTheme;
- untrustedHook.presenter = untrustedHook.presenter || opts.req.hook.presenter || config.defaultPresenter;
+ untrustedHook.theme = opts.req.hook.theme || untrustedHook.theme || config.defaultTheme;
+ untrustedHook.presenter = opts.req.hook.presenter || untrustedHook.presenter || config.defaultPresenter;
} catch (e) {
err = e;
} |
f7e0be860842febbe2d7b327a34cda2dba72bbde | app/utils/replayEvents.js | app/utils/replayEvents.js | export function replayEvents(events, currentTime) {
const head = events[0];
const tail = events.slice(1);
// Exit condition, no events
if (head === undefined) return;
if (head.timestamp > currentTime) {
const delay = head.timestamp - currentTime;
setTimeout(() => {
head.replay();
replayEvents(tail, head.timestamp);
}, delay);
} else {
replayEvents(tail, currentTime);
}
}
| Add helper method to replay events | Add helper method to replay events
| JavaScript | mit | UniSiegenCSCW/remotino,UniSiegenCSCW/remotino,UniSiegenCSCW/remotino | ---
+++
@@ -0,0 +1,17 @@
+export function replayEvents(events, currentTime) {
+ const head = events[0];
+ const tail = events.slice(1);
+
+ // Exit condition, no events
+ if (head === undefined) return;
+
+ if (head.timestamp > currentTime) {
+ const delay = head.timestamp - currentTime;
+ setTimeout(() => {
+ head.replay();
+ replayEvents(tail, head.timestamp);
+ }, delay);
+ } else {
+ replayEvents(tail, currentTime);
+ }
+} | |
77a86d9a5180a1586d9a61eb87b4408d107ab3c3 | nin/dasBoot/Random.js | nin/dasBoot/Random.js | function Random(seed){
var m_w = seed || 123456791;
var m_z = 987654321;
var mask = 0xffffffff;
return function random() {
m_z = (36969 * (m_z & 65535) + (m_z >> 16)) & mask;
m_w = (18000 * (m_w & 65535) + (m_w >> 16)) & mask;
var result = ((m_z << 16) + m_w) & mask;
result /= 4294967296;
return result + 0.5;
}
}
| Add better seeded random function | Add better seeded random function
Instead of using
`Math.seedrandom(seed)` which affects the global Math object, use
`var rand = Random(seed)` which returns a unique random object for you
to use. This does not affect the global random method or other instances
of random.
| JavaScript | apache-2.0 | ninjadev/nin,ninjadev/nin,ninjadev/nin | ---
+++
@@ -0,0 +1,13 @@
+function Random(seed){
+ var m_w = seed || 123456791;
+ var m_z = 987654321;
+ var mask = 0xffffffff;
+
+ return function random() {
+ m_z = (36969 * (m_z & 65535) + (m_z >> 16)) & mask;
+ m_w = (18000 * (m_w & 65535) + (m_w >> 16)) & mask;
+ var result = ((m_z << 16) + m_w) & mask;
+ result /= 4294967296;
+ return result + 0.5;
+ }
+} | |
c223b150921943c2b5ba178863ed7c22a585be91 | migrations/20160324195635_add_ip_for_actions.js | migrations/20160324195635_add_ip_for_actions.js |
exports.up = function(knex, Promise) {
return knex.schema.table('actions', function(table) {
table.string('ip', 15);
});
};
exports.down = function(knex, Promise) {
return knex.schema.table('actions', function(table) {
table.dropColumn('ip');
});
};
| Add ip column for actions table | Add ip column for actions table
| JavaScript | mit | futurice/wappuapp-backend,kaupunki-apina/prahapp-backend,kaupunki-apina/prahapp-backend,futurice/wappuapp-backend | ---
+++
@@ -0,0 +1,13 @@
+
+exports.up = function(knex, Promise) {
+ return knex.schema.table('actions', function(table) {
+ table.string('ip', 15);
+ });
+};
+
+exports.down = function(knex, Promise) {
+ return knex.schema.table('actions', function(table) {
+ table.dropColumn('ip');
+ });
+};
+ | |
cd267b8d836ac79980106bbbe2f9851f45a938fa | hooks/opencps-hook/docroot/META-INF/custom_jsps/html/extensions/hex2base.js | hooks/opencps-hook/docroot/META-INF/custom_jsps/html/extensions/hex2base.js | // FIXME: origin unknown
if (!window.atob) {
var tableStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var table = tableStr.split("");
window.atob = function (base64) {
if (/(=[^=]+|={3,})$/.test(base64)) throw new Error("String contains an invalid character");
base64 = base64.replace(/=/g, "");
var n = base64.length & 3;
if (n === 1) throw new Error("String contains an invalid character");
for (var i = 0, j = 0, len = base64.length / 4, bin = []; i < len; ++i) {
var a = tableStr.indexOf(base64[j++] || "A"), b = tableStr.indexOf(base64[j++] || "A");
var c = tableStr.indexOf(base64[j++] || "A"), d = tableStr.indexOf(base64[j++] || "A");
if ((a | b | c | d) < 0) throw new Error("String contains an invalid character");
bin[bin.length] = ((a << 2) | (b >> 4)) & 255;
bin[bin.length] = ((b << 4) | (c >> 2)) & 255;
bin[bin.length] = ((c << 6) | d) & 255;
};
return String.fromCharCode.apply(null, bin).substr(0, bin.length + n - 4);
};
window.btoa = function (bin) {
for (var i = 0, j = 0, len = bin.length / 3, base64 = []; i < len; ++i) {
var a = bin.charCodeAt(j++), b = bin.charCodeAt(j++), c = bin.charCodeAt(j++);
if ((a | b | c) > 255) throw new Error("String contains an invalid character");
base64[base64.length] = table[a >> 2] + table[((a << 4) & 63) | (b >> 4)] +
(isNaN(b) ? "=" : table[((b << 2) & 63) | (c >> 6)]) +
(isNaN(b + c) ? "=" : table[c & 63]);
}
return base64.join("");
};
}
function hexToBase64(str) {
return btoa(String.fromCharCode.apply(null,
str.replace(/\r|\n/g, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" "))
);
}
function hexToPem(s) {
var b = hexToBase64(s);
var pem = b.match(/.{1,64}/g).join("\n");
return "-----BEGIN CERTIFICATE-----\n" + pem + "\n-----END CERTIFICATE-----";
} | Add lib js for signature | Add lib js for signature | JavaScript | agpl-3.0 | hltn/opencps,VietOpenCPS/opencps,hltn/opencps,VietOpenCPS/opencps,VietOpenCPS/opencps,hltn/opencps | ---
+++
@@ -0,0 +1,45 @@
+// FIXME: origin unknown
+if (!window.atob) {
+ var tableStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+ var table = tableStr.split("");
+
+ window.atob = function (base64) {
+ if (/(=[^=]+|={3,})$/.test(base64)) throw new Error("String contains an invalid character");
+ base64 = base64.replace(/=/g, "");
+ var n = base64.length & 3;
+ if (n === 1) throw new Error("String contains an invalid character");
+ for (var i = 0, j = 0, len = base64.length / 4, bin = []; i < len; ++i) {
+ var a = tableStr.indexOf(base64[j++] || "A"), b = tableStr.indexOf(base64[j++] || "A");
+ var c = tableStr.indexOf(base64[j++] || "A"), d = tableStr.indexOf(base64[j++] || "A");
+ if ((a | b | c | d) < 0) throw new Error("String contains an invalid character");
+ bin[bin.length] = ((a << 2) | (b >> 4)) & 255;
+ bin[bin.length] = ((b << 4) | (c >> 2)) & 255;
+ bin[bin.length] = ((c << 6) | d) & 255;
+ };
+ return String.fromCharCode.apply(null, bin).substr(0, bin.length + n - 4);
+ };
+
+ window.btoa = function (bin) {
+ for (var i = 0, j = 0, len = bin.length / 3, base64 = []; i < len; ++i) {
+ var a = bin.charCodeAt(j++), b = bin.charCodeAt(j++), c = bin.charCodeAt(j++);
+ if ((a | b | c) > 255) throw new Error("String contains an invalid character");
+ base64[base64.length] = table[a >> 2] + table[((a << 4) & 63) | (b >> 4)] +
+ (isNaN(b) ? "=" : table[((b << 2) & 63) | (c >> 6)]) +
+ (isNaN(b + c) ? "=" : table[c & 63]);
+ }
+ return base64.join("");
+ };
+
+}
+
+function hexToBase64(str) {
+ return btoa(String.fromCharCode.apply(null,
+ str.replace(/\r|\n/g, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" "))
+ );
+}
+
+function hexToPem(s) {
+ var b = hexToBase64(s);
+ var pem = b.match(/.{1,64}/g).join("\n");
+ return "-----BEGIN CERTIFICATE-----\n" + pem + "\n-----END CERTIFICATE-----";
+} | |
68868f156ce62400c9148c4cdd80dd0f562f6c37 | problem-009/problem-009.0.js | problem-009/problem-009.0.js | /*
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
*/
var euler9 = function() {
//Euclid's Formula: https://en.wikipedia.org/wiki/Pythagorean_triple#Generating_a_triple
var max = 100;
var a, b, c, m, n;
var triples = [[3,4,5]];
var answerTriple = [];
var product;
for(m=1; m<max; m++) {
for(n=1; n<max; n++) {
a = Math.pow(m,2) - Math.pow(n,2);
b = 2 * m * n;
c = Math.pow(m,2) + Math.pow(n,2);
triples.push([a, b, c]);
}
}
triples.forEach(function(triple) {
if(triple[0] + triple[1] + triple[2] == 1000) {
answerTriple = triple;
}
});
product = answerTriple.reduce(function (previousValue, currentValue) {
return previousValue * currentValue;
});
console.log(product);
};
var start = Date.now();
euler9();
console.log('Time elapsed: ' + (Date.now() - start) + 'ms');
| Add problem 9 solution :tada: | Add problem 9 solution :tada:
| JavaScript | mit | ItsASine/Project-Euler | ---
+++
@@ -0,0 +1,44 @@
+/*
+ A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
+
+ a^2 + b^2 = c^2
+ For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
+
+ There exists exactly one Pythagorean triplet for which a + b + c = 1000.
+ Find the product abc.
+ */
+
+var euler9 = function() {
+ //Euclid's Formula: https://en.wikipedia.org/wiki/Pythagorean_triple#Generating_a_triple
+ var max = 100;
+ var a, b, c, m, n;
+ var triples = [[3,4,5]];
+ var answerTriple = [];
+ var product;
+
+ for(m=1; m<max; m++) {
+ for(n=1; n<max; n++) {
+ a = Math.pow(m,2) - Math.pow(n,2);
+ b = 2 * m * n;
+ c = Math.pow(m,2) + Math.pow(n,2);
+
+ triples.push([a, b, c]);
+ }
+ }
+
+ triples.forEach(function(triple) {
+ if(triple[0] + triple[1] + triple[2] == 1000) {
+ answerTriple = triple;
+ }
+ });
+
+ product = answerTriple.reduce(function (previousValue, currentValue) {
+ return previousValue * currentValue;
+ });
+
+ console.log(product);
+};
+
+var start = Date.now();
+euler9();
+console.log('Time elapsed: ' + (Date.now() - start) + 'ms'); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.