commit
stringlengths 40
40
| subject
stringlengths 1
3.25k
| old_file
stringlengths 4
311
| new_file
stringlengths 4
311
| old_contents
stringlengths 0
26.3k
| lang
stringclasses 3
values | proba
float64 0
1
| diff
stringlengths 0
7.82k
|
---|---|---|---|---|---|---|---|
ac00259e45c078caa79fcf60c7105844e64a0ff4
|
Make Compass plugin a separate object, lazy init options, make output file name to be configurable
|
index.js
|
index.js
|
var path = require('path');
var merge = require('lodash-node/modern/objects/merge');
var compileCompass = require('broccoli-compass-compiler');
var renameFiles = require('broccoli-rename-files');
module.exports = {
name: 'ember-cli-compass-compiler',
included: function(app) {
this._super.included.apply(this, arguments);
var projectName = app.project.name();
app.registry.add('css', {
name: 'ember-cli-compass-compiler',
ext: ['scss', 'sass'],
toTree: function(tree, inputPath, outputPath) {
if (inputPath[0] === '/') {
inputPath = inputPath.slice(1);
}
if (outputPath[0] === '/') {
outputPath = outputPath.slice(1);
}
var options = app.options.compassOptions || {};
var defaultOptions = {
outputStyle: 'compressed',
compassCommand: 'compass',
importPath: [],
getCssDir: function(outputDir) {
return path.join(outputDir, outputPath);
}
};
var compassOptions = merge(defaultOptions, options);
var inputTrees = [inputPath];
if (compassOptions.importPath.length > 0) {
inputTrees = inputTrees.concat(compassOptions.importPath);
}
var compassTree = compileCompass(inputTrees, compassOptions);
var outputTree = renameFiles(compassTree, {
transformFilename: function(filename, basename, extname) {
if (basename === 'app' && extname === '.css') {
return filename.replace(basename, projectName);
}
return filename;
}
});
return outputTree;
}
});
}
};
|
JavaScript
| 0 |
@@ -194,226 +194,191 @@
);%0A%0A
-module.exports = %7B%0A name: 'ember-cli-compass-compiler',%0A included: function(app) %7B%0A this._super.included.apply(this, arguments);%0A var projectName = app.project.name();%0A%0A app.registry.add('css', %7B%0A
+var removeLeadingSlash = function(string) %7B%0A return (string.length %3E 0 && string%5B0%5D === '/') ? string.slice(1) : string;%0A%7D;%0A%0Afunction CompassCompilerPlugin(optionsFn) %7B%0A this.
name
-:
+ =
'em
@@ -406,20 +406,22 @@
ler'
-,%0A ext:
+;%0A this.ext =
%5B's
@@ -437,23 +437,83 @@
ss'%5D
-,%0A
+;%0A this.optionsFn = optionsFn;%0A%7D%0A%0ACompassCompilerPlugin.prototype.
toTree
-:
+ =
fun
@@ -549,255 +549,190 @@
Path
-) %7B%0A if (inputPath%5B0%5D === '/'
+, inputOptions
) %7B%0A
+%0A
- inputPath = inputPath.slice(1);%0A %7D%0A%0A if (outputPath%5B0%5D === '/') %7B%0A outputPath = outputPath.slice(1);%0A %7D%0A%0A var options = app.options.compassOptions %7C%7C %7B%7D;%0A
+// Normalize paths%0A inputPath = removeLeadingSlash(inputPath);%0A outputPath = removeLeadingSlash(outputPath);%0A%0A // Merge default options with supplied options%0A
va
@@ -752,22 +752,16 @@
ons = %7B%0A
-
outp
@@ -787,22 +787,16 @@
d',%0A
-
compassC
@@ -814,22 +814,16 @@
mpass',%0A
-
impo
@@ -834,22 +834,16 @@
th: %5B%5D,%0A
-
getC
@@ -867,30 +867,24 @@
utputDir) %7B%0A
-
return
@@ -926,33 +926,15 @@
- %7D%0A %7D;%0A
+%7D%0A %7D;%0A
va
@@ -958,16 +958,20 @@
= merge(
+%7B%7D,
defaultO
@@ -982,25 +982,159 @@
ns,
+this.
options
-);%0A%0A
+Fn(), inputOptions);%0A var projectName = compassOptions.outputFile;%0A delete compassOptions.outputFile;%0A%0A // Watch importPath directories%0A
va
@@ -1161,22 +1161,16 @@
tPath%5D;%0A
-
if (co
@@ -1203,30 +1203,24 @@
ngth %3E 0) %7B%0A
-
inputTre
@@ -1276,23 +1276,64 @@
;%0A
- %7D%0A%0A
+%7D%0A%0A // Compile and rename app.css =%3E project-name.scss%0A
va
@@ -1392,22 +1392,16 @@
tions);%0A
-
var ou
@@ -1438,22 +1438,16 @@
Tree, %7B%0A
-
tran
@@ -1507,22 +1507,16 @@
%7B%0A
-
if (base
@@ -1555,22 +1555,16 @@
css') %7B%0A
-
@@ -1621,111 +1621,518 @@
+%7D%0A
-%7D%0A return filename;%0A %7D%0A %7D);%0A%0A return outputTree;%0A %7D%0A %7D)
+return filename;%0A %7D%0A %7D);%0A%0A return outputTree;%0A%7D;%0A%0Amodule.exports = %7B%0A name: 'Ember CLI Compass Compiler',%0A%0A included: function(app) %7B%0A this.app = app;%0A this._super.included.apply(this, arguments);%0A app.registry.add('css', new CompassCompilerPlugin(this.compassOptions.bind(this)));%0A %7D,%0A%0A compassOptions: function () %7B%0A var options = (this.app && this.app.options.compassOptions) %7C%7C %7B%7D;%0A options.outputFile = options.outputFile %7C%7C this.project.name() + '.css';%0A return options
;%0A
|
937ae76e2c49dba674b2332ab7145d3cd784aa01
|
Update formatting of index.js
|
index.js
|
index.js
|
import React from 'react';
import {NativeModules, Platform} from 'react-native';
const invariant = require('invariant');
const RNCookieManagerIOS = NativeModules.RNCookieManagerIOS;
const RNCookieManagerAndroid = NativeModules.RNCookieManagerAndroid;
let CookieManager;
if (Platform.OS === 'ios') {
invariant(RNCookieManagerIOS,
'Add RNCookieMangerIOS.h and RNCookieManagerIOS.m to your Xcode project');
CookieManager = RNCookieManagerIOS;
} else if (Platform.OS === 'android') {
invariant(RNCookieManagerAndroid,
'Import libraries to android "rnpm link"');
CookieManager = RNCookieManagerAndroid;
} else {
invariant(CookieManager, 'Invalid platform. This library only supports Android and iOS.');
}
var functions = [
'set',
'setFromResponse',
'getFromResponse',
'get',
'getAll',
'clearAll',
'clearByName'
];
module.exports = {}
for (var i=0; i < functions.length; i++) {
module.exports[functions[i]] = CookieManager[functions[i]];
}
|
JavaScript
| 0.000001 |
@@ -28,16 +28,17 @@
import %7B
+
NativeMo
@@ -52,16 +52,17 @@
Platform
+
%7D from '
@@ -339,16 +339,38 @@
'
+react-native-cookies:
Add RNCo
@@ -552,17 +552,16 @@
Android,
-
%0A
@@ -562,16 +562,38 @@
'
+react-native-cookies:
Import l
@@ -618,16 +618,45 @@
d %22r
-npm link
+eact-native link react-native-cookies
%22');
@@ -739,16 +739,38 @@
nager, '
+react-native-cookies:
Invalid
@@ -829,19 +829,21 @@
.');%0A%7D%0A%0A
-var
+const
functio
@@ -999,17 +999,19 @@
r (var i
-=
+ =
0; i %3C f
@@ -1099,9 +1099,8 @@
s%5Bi%5D%5D;%0A%7D
-%0A
|
5b937cf51861d8e702a76aa320d39880b1a2afc0
|
disable colored output
|
index.js
|
index.js
|
var cp = require('child_process');
var fs = require('fs');
var path = require('path');
var async = require('async');
var request = require('request');
var nodemailer = require('nodemailer');
var nl2br = require('nl2br');
var date = new Date();
fs.readFile(process.argv[2], 'utf8', onFile); // takes "third" argument which should be file
function onFile (err, data) {
if (err) {
console.error(err);
return;
}
var urls = data.split('\n');
scanSites(urls);
}
function scanSites (urls) {
var filteredUrls = urls.filter(function (url){return url;});
async.map(filteredUrls, onUrl, onResults);
}
function onUrl (url, next) {
var cmd = [
'cd /usr/bin/wpscan;',
'echo ' + url + ';',
'./wpscan.rb --url=' + url + ' --batch |',
'php ' + path.join(__dirname, 'wp_check_for_vulnerabilities.php') + ';',
'echo ---------\n'
];
cp.exec(cmd.join(' '), function (err, stdout, stderr) {
if (err) {
next(err);
return;
}
if (stderr) {
next(stderr);
return;
}
if (stdout) {
next(null, stdout);
}
});
}
function onResults (err, results) {
if (err) {
console.error(err);
return;
}
results = results.join('\n');
process.stdout.write(results);
var transporter = nodemailer.createTransport('direct:?name=server.example.com');
var mailOptions = {
from: 'Server <[email protected]>',
to: '[email protected]',
subject: 'WPSCAN Results ' + padZero(date.getDate()) + padZero(date.getMonth() + 1) + padZero(date.getFullYear()),
text: results, // plaintext body
html: nl2br(results) // html body
};
transporter.sendMail(mailOptions, function(err, info){
if (err) {
console.log(err);
return;
}
console.log('Message sent: ' + info.response);
});
}
function padZero (num) {
return ('0' + num).slice(-2);
}
|
JavaScript
| 0.000001 |
@@ -750,16 +750,27 @@
--batch
+--no-color
%7C',%0A
|
ee53960c116468a6a9f19ca20b74ca635bf2af09
|
create public api
|
index.js
|
index.js
|
'use strict';
function parse(argv) {
if (!(argv && argv.length)) {
return [];
}
const args = argv.slice(2);
const components = args.reduce((components, arg) => {
components.push(...componentsFromArg(arg));
return components;
}, []);
return components;
}
function componentsFromArg(arg) {
for (let i = 0, len = matchers.length; i < len; i++) {
const matcher = matchers[i];
const components = matcher(arg);
if (components.length > 0) {
return components;
}
}
}
const matchers = [
parseLongOption,
parseShortOptionSet,
parseShortOption,
// TODO
// parseOptionTerminator
parseValue
];
function parseLongOption(arg) {
let results = [];
const match = /^--([^=]+)(=(.*))?/.exec(arg);
if (match) {
results.push({
type: 'long',
value: match[1],
raw: arg
});
if (match[3]) {
results.push({
type: 'value',
value: match[3],
raw: match[3]
});
}
}
return results;
}
function parseShortOptionSet(arg) {
const match = /^-([^\-\s]{2,})/.exec(arg);
if (match) {
return match[1].split('').map(char => {
return {
type: 'short',
value: char,
raw: `-${char}`
};
});
}
return [];
}
function parseShortOption(arg) {
const match = /^-([^\-\s])/.exec(arg);
if (match) {
return [{
type: 'short',
value: match[1],
raw: arg
}];
}
return [];
}
function parseValue(arg) {
return [{
type: 'value',
value: arg,
raw: arg
}];
}
function processComponents(components, schema) {
function findScheme(component) {
return schema.find(scheme => {
const name = scheme[component.type];
return name && name === component.value;
});
}
let result = {};
const consumers = {
string: function(component, scheme) {
const next = components.shift();
if (!(next && next.type === 'value')) {
// throw new usage error
throw new Error(`Argument ${component.raw} requires a string value`);
}
result[scheme.name] = next.value;
},
boolean: function(component, scheme) {
result[scheme.name] = !result[scheme.name];
},
value: function(component, scheme) {
// TODO
}
};
while (components.length > 0) {
const component = components.shift();
const scheme = findScheme(component);
if (!scheme) {
console.error("component:", component);
throw new Error("Unrecognized argument: " + component.raw);
// throw unrecognized argument exception: component.raw
}
const consume = consumers[scheme.type];
consume(component, scheme);
}
return result;
}
console.log("process.argv:", process.argv);
const components = parse(process.argv);
const schema = [
{
name: 'firstName',
long: 'first-name',
short: 'f',
type: 'string'
},
{
name: 'lastName',
long: 'last-name',
short: 'l',
type: 'string'
},
{
name: 'florped',
long: 'florped',
short: 'P',
type: 'boolean'
}
];
console.log("parsed components:", components);
const result = processComponents(components, schema);
console.log("result:", result);
|
JavaScript
| 0 |
@@ -17,21 +17,1170 @@
unction
-parse
+createParser(schemaDefinitions) %7B%0A const schema = createSchema(schemaDefinitions);%0A%0A function parse(argv) %7B%0A const components = parseComponents(argv);%0A return processComponents(components, schema);%0A %7D%0A%0A // TODO: public API docs%0A return %7B parse %7D;%0A%7D%0A%0Afunction createSchema(definitions) %7B%0A const supportedTypes = %5B 'string', 'boolean' %5D;%0A%0A const schema = %5B%5D;%0A Object.keys(definitions).forEach(key =%3E %7B%0A const definition = definitions%5Bkey%5D;%0A const scheme = %7B%0A name: key,%0A type: definition.type,%0A description: definition.description,%0A long: key,%0A short: definition.short%0A %7D;%0A%0A const type = definition.type %7C%7C 'boolean';%0A if (!supportedTypes.includes(type)) %7B%0A throw new Error(%60Argument type for $%7Bkey%7D must be one of: $%7BsupportedTypes.join(', ')%7D%60);%0A %7D%0A%0A if (definition.short && schema.some(s =%3E s.short === definition.short)) %7B%0A throw new Error(%60Short option $%7Bdefinition.short%7D specified twice%60);%0A %7D%0A%0A schema.push(scheme);%0A %7D);%0A%0A return schema;%0A%7D%0A%0Afunction parseComponents
(argv) %7B
@@ -4235,568 +4235,97 @@
%0A%7D%0A%0A
-console.log(%22process.argv:%22, process.argv);%0Aconst components = parse(process.argv);%0Aconst schema = %5B%0A %7B%0A name: 'firstName',%0A long: 'first-name',%0A short: 'f',%0A type: 'string'%0A %7D,%0A %7B%0A name: 'lastName',%0A long: 'last-name',%0A short: 'l',%0A type: 'string'%0A %7D,%0A %7B%0A name: 'florped',%0A long: 'florped',%0A short: 'P',%0A type: 'boolean'%0A %7D%0A%5D;%0Aconsole.log(%22parsed components:%22, components);%0Aconst result = processComponents(components, schema);%0A%0Aconsole.log(%22result:%22, result)
+// TODO:, set banner/usage%0A%0Amodule.exports = %7B%0A // TODO: docs%0A schema: createParser%0A%7D
;%0A
|
7155868d8fe735ec4e47c840d2ed94ff8b943979
|
Fix LinearRing error for multiple LinearRings
|
index.js
|
index.js
|
/**
* Generates a new GeoJSON Polygon feature, given an array of coordinates
* and list of properties.
*
* @module turf/polygon
* @param {number[][]} rings - an array of LinearRings
* @param {Object} properties - an optional properties object
* @return {GeoJSONPolygon} output
* @example
* var poly1 = turf.polygon([[[20.0,0.0],[101.0,0.0],[101.0,1.0],[100.0,1.0],[100.0,0.0]]])
* var poly2 = turf.polygon([[[20.0,0.0],[101.0,0.0],[101.0,1.0],[100.0,1.0],[100.0,0.0]]],
* {name: 'line 1', distance: 145})
* console.log(poly1)
* console.log(poly2)
*/
module.exports = function(coordinates, properties){
if(coordinates === null) return new Error('No coordinates passed');
if ((coordinates[coordinates.length - 1].length !== coordinates[0].length || !coordinates[coordinates.length - 1].every(function(position, index) {
return coordinates[0][index] === position;
}))) {
return new Error('First and last coordinate pair are not equivalent');
};
var polygon = {
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": coordinates
},
"properties": properties
};
if(!polygon.properties){
polygon.properties = {};
}
return polygon;
}
|
JavaScript
| 0.000076 |
@@ -685,223 +685,201 @@
');%0A
+%0A
-if ((coordinates%5Bcoordinates.length - 1%5D.length !== coordinates%5B0%5D.length %7C%7C !coordinates%5Bcoordinates.length - 1%5D.every(function(position, index) %7B%0A return coordinates%5B0%5D%5Bindex%5D === position;%0A %7D))) %7B%0A
+for (var i = 0; i %3C coordinates.length; i++) %7B%0A var ring = coordinates%5Bi%5D;%0A%0A for (var j = 0; j %3C ring%5Bring.length - 1%5D.length; j++) %7B%0A if (ring%5Bring.length - 1%5D%5Bj%5D !== ring%5B0%5D%5Bj%5D)
ret
@@ -948,15 +948,21 @@
nt')
-;
+%0A %7D
%0A %7D;%0A
+%0A
va
|
4b854da35114896105939ab786f22a2ca27f8049
|
Add qplus.series function
|
index.js
|
index.js
|
// Requires
var Q = require('q');
// Retry a function a maximum of N times
// the function must use promises and will always be executed once
function retry(fn, N, retryTimeout) {
// Default args
N = ((N === undefined || N < 0) ? 0 : N - 1);
retryTimeout = (retryTimeout === undefined ? 0 : retryTimeout);
return function wrapper() {
// Actual arguments (passed first time)
var args = arguments;
var d = Q.defer();
// Our failure counter (decounter by decrementing)
var remainingTries = N;
// The function with the try logic
var _try = function _try() {
// Call function
fn.apply(null, args)
.then(function(result) {
// Success
d.resolve(result);
}, function(err) {
// Failure
// Decrement
remainingTries -= 1;
// No tries left, so reject promise with last error
if(remainingTries < 0) {
// Total failure
d.reject(err);
return;
} else {
// We have some retries left, so retry
setTimeout(_try, retryTimeout);
}
}).done();
};
// Start trying
_try();
// Give promise
return d.promise;
};
}
// Exports
exports.retry = retry;
|
JavaScript
| 0.00004 |
@@ -1409,16 +1409,81 @@
%7D;%0A%7D%0A%0A
+function series(funcs) %7B%0A return funcs.reduce(Q.when, Q());%0A%7D%0A
%0A// Expo
@@ -1509,8 +1509,33 @@
retry;%0A
+exports.series = series;%0A
|
e6db61f615d08568d3c08eb71e5762dfe6504be5
|
add test for species()
|
index.js
|
index.js
|
'use strict';
var binsPromise = require('gramene-bins-client').binsPromise;
var treesPromise = require('gramene-trees-client').promise;
var Q = require('q');
var _ = require('lodash');
function addGenomesToTaxonomy(taxonomy, genomes) {
taxonomy.leafNodes().forEach(function (speciesNode) {
var species = speciesNode.model,
taxonId = species.id,
genome = genomes.get(taxonId);
if (!genome) {
console.warn('No genome found for', species);
}
species.genome = genome;
});
taxonomy.results = function () { return genomes.results; };
taxonomy.binCount = genomes.binCount.bind(genomes);
taxonomy.setResults = genomes.setResults.bind(genomes);
function getNodesAndReturnModel(predicate) {
return function () {
return taxonomy.all(predicate)
.map(function (node) {
return node.model;
});
}
}
taxonomy.species = getNodesAndReturnModel(function (node) {
return node.model.genome;
});
taxonomy.speciesWithResults = getNodesAndReturnModel(function (node) {
return node.model.genome &&
node.model.genome.results &&
node.model.genome.results.count;
});
}
function removeGenomesFromTaxonomy(taxonomy) {
taxonomy.leafNodes().forEach(function (speciesNode) {
delete speciesNode.model.genome;
});
['results', 'binCount', 'setResults', 'species'].map(function (fnName) {
delete taxonomy[fnName];
})
}
function addGeneratorToTaxonomy(binsGenerator, taxonomy) {
taxonomy.binParams = {};
taxonomy.setBinType = function (methodName, param) {
var newParams = methodName ? {method: methodName, param: param} : {};
if (_.isEqual(this.binParams, newParams)) {
return false;
}
var binFn = binsGenerator[methodName + 'BinMapper'];
if (!binFn) {
removeGenomesFromTaxonomy(taxonomy);
if (_.isEqual(this.binParams, {})) {
return false;
}
this.binParams = {};
return true;
}
var genomes = binFn(param).binnedGenomes();
this.binParams = {
method: methodName,
param: param
};
addGenomesToTaxonomy(taxonomy, genomes);
return true;
};
taxonomy.removeBins = function () { return taxonomy.setBinType() };
return taxonomy;
}
module.exports = {
get: function (local) {
return Q.all([
binsPromise.get(local),
treesPromise.get(local)
]).spread(addGeneratorToTaxonomy);
}
};
|
JavaScript
| 0.000001 |
@@ -328,36 +328,8 @@
el,%0A
- taxonId = species.id,%0A
@@ -355,14 +355,17 @@
get(
-taxonI
+species.i
d);%0A
|
3489b6adca3ebed1a86f73f56956e295567d8d4d
|
Fix jsc errors
|
index.js
|
index.js
|
var debug = require('debug')('loopback-ds-computed-mixin');
var _ = require('lodash');
function computed(Model, options) {
'use strict';
// Trigger a warning and remove the property from the watchlist when one of
// the property is not found on the model or the defined callback is not found
_.mapKeys(options.properties, function (callback, property) {
var removeProperty = false;
if (_.isUndefined(Model.definition.properties[property])) {
console.warn('Property %s on %s is undefined', property, Model.modelName);
removeProperty = true;
}
if (typeof Model[callback] !== 'function') {
console.warn('Callback %s for %s is not a model function', callback, property);
removeProperty = true;
}
if (removeProperty) {
debug('Remove Changed %s for %s ', property, Model.modelName);
delete options.properties[property];
}
});
debug('Computed mixin for Model %s with options %o', Model.modelName, options);
// The loaded observer is triggered when an item is loaded
Model.observe('loaded', function (ctx, next) {
// We don't act on new instances
if (ctx.instance === undefined) {
return next();
}
//
_.keys(options.properties).map(function (property) {
var callback = options.properties[property];
if (typeof Model[callback] !== 'function') {
console.warn('Function %s not found on Model', callback);
return false;
}
debug('Computing property %s with callback %s', property, callback);
ctx.instance[property] = Model[callback](ctx.instance);
});
next();
})
}
module.exports = function mixin(app) {
app.loopback.modelBuilder.mixins.define('Computed', computed);
};
|
JavaScript
| 0.001045 |
@@ -333,17 +333,16 @@
function
-
(callbac
@@ -1069,17 +1069,16 @@
function
-
(ctx, ne
@@ -1236,17 +1236,16 @@
function
-
(propert
@@ -1611,16 +1611,17 @@
();%0A %7D)
+;
%0A%7D%0A%0Amodu
|
90988cf181d642c57a02c9b802b0f6c3899505d7
|
Optimize content type detection
|
index.js
|
index.js
|
#!/usr/bin/env node
'use strict'
var fs = require('fs')
var pump = require('pump')
var menu = require('appendable-cli-menu')
var log = require('single-line-log').stdout
var chalk = require('chalk')
var bonjour = require('bonjour')()
var spy = require('ipp-spy')
var gunzip = require('gunzip-maybe')
var peek = require('peek-stream')
var isPostScript = require('is-postscript')
var isPjl = require('is-pjl')
var isPdf = require('is-pdf')
var C = require('ipp-encoder/constants')
var printers = menu('Select a printer', function (printer) {
browser.stop()
hijack(printer)
})
var browser = bonjour.find({ type: 'ipp' }, function (printer) {
printers.add({ name: printer.name, value: printer })
})
function hijack (printer) {
var state = { ops: 0, docs: [] }
render(state)
var opts = {
port: 3001,
forwardHost: printer.host,
forwardPort: printer.port
}
spy(opts, function (operation, doc) {
state.ops++
render(state)
if (operation.operationId !== C.PRINT_JOB) return
var file = toFile('job-' + Date.now())
pump(doc, gunzip(), file, function (err) {
if (err) throw err
state.docs.push(file.name)
render(state)
})
})
bonjour.publish({ type: printer.type, name: printer.name, port: 3001, txt: printer.txt, probe: false })
}
function toFile (name) {
var stream = peek({ maxBuffer: 10 }, function (data, swap) {
if (isPostScript(data)) name += '.ps'
else if (isPjl(data)) name += '.ps' // Preview.app on OS X will be able to read PJL documents if opened as .ps
else if (isPdf(data)) name += '.pdf'
else name += '.bin'
stream.name = name
swap(null, fs.createWriteStream(name))
})
return stream
}
function render (state) {
var len = state.docs.length
log('\n' +
'Requests intercepted: ' + chalk.green(state.ops) + '\n' +
'Documents printed: ' + chalk.green(len) + '\n' +
'Latest document: ' + (len ? chalk.cyan(state.docs[len - 1]) : chalk.grey('waiting...')) + '\n')
}
|
JavaScript
| 0.000005 |
@@ -1338,16 +1338,32 @@
= peek(%7B
+ newline: false,
maxBuff
|
5cce31e533ec4a97144280ea613a71a7302a7ec3
|
add support for homebrew
|
index.js
|
index.js
|
module.exports = null
if (process.platform === 'darwin')
return module.exports = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
if (process.platform !== 'win32')
return module.exports = require('which').sync('google-chrome')
var fs = require('fs')
var suffix = '\\Google\\Chrome\\Application\\chrome.exe';
var prefixes = [
process.env.LOCALAPPDATA
, process.env.PROGRAMFILES
, process.env['PROGRAMFILES(X86)']
]
for (var i = 0; i < prefixes.length; i++) {
var exe = prefixes[i] + suffix
if (fs.existsSync(exe)) {
return module.exports = exe
}
}
|
JavaScript
| 0 |
@@ -1,24 +1,48 @@
+var fs = require('fs')%0A%0A
module.exports = null%0A%0Ai
@@ -78,32 +78,24 @@
in')
+ %7B
%0A
-return module.exports
+var regPath
= '
@@ -155,16 +155,129 @@
Chrome'
+;%0A var altPath = '~' + regPath;%0A%0A return module.exports = fs.existsSync(regPath)%0A ? regPath%0A : altPath%0A%7D%0A
%0A%0Aif (pr
@@ -370,39 +370,16 @@
rome')%0A%0A
-var fs = require('fs')%0A
%0Avar suf
|
e83d80a50d3d762fc75d68034134fa045c38279a
|
create the module
|
index.js
|
index.js
|
/*
* __proto__
* Node Schema Abstraction
* https://github.com/thanpolas/__proto__
*
* Copyright (c) 2014 Thanasis Polychronakis
* Licensed under the MIT license.
*/
/**
* @fileOverview __proto__ bootstrap module.
*/
module.exports = require('./lib/__proto__');
|
JavaScript
| 0.000001 |
@@ -3,44 +3,96 @@
%0A *
-__proto__%0A * Node Schema Abstraction
+ffmpeg-binary-linux-64bit%0A * Provides staticly compiled binaries for linux environments.
%0A *
@@ -120,25 +120,41 @@
anpolas/
-__proto__
+ffmpeg-binary-linux-64bit
%0A *%0A * C
@@ -233,16 +233,17 @@
se.%0A */%0A
+%0A
/**%0A * @
@@ -259,81 +259,542 @@
iew
-__proto__ bootstrap module.%0A */%0Amodule.exports = require('./lib/__proto__
+ffmpeg-binary-linux-64bit bootstrap module.%0A */%0A%0Avar path = require('path');%0A%0Avar ffmpegPath = path.join(__dirname, '/ffmpeg');%0A%0A/**%0A * Returns the full path to the %22ffmpeg%22 binary.%0A *%0A * @return %7Bstring%7D The full path to the %22ffmpeg%22 binary.%0A */%0Avar ffmpegBin = module.exports = function() %7B%0A return path.join(ffmpegPath, 'ffmpeg');%0A%7D;%0A%0A/**%0A * Returns the full path to the %22ffprobe%22 binary.%0A *%0A * @return %7Bstring%7D The full path to the %22ffprobe%22 binary.%0A */%0AffmpegBin.ffprobe = function() %7B%0A return path.join(ffmpegPath, 'ffprobe
');%0A
+%7D;%0A
|
9a4a65cbfec8ffb8e8b577178f210dd7b5fc30d8
|
throw error for non existing queue
|
index.js
|
index.js
|
// const cluster = require('cluster')
global.Promise = require('bluebird')
Promise.config({
longStackTraces: true
})
const _ = require('lodash')
const Queue = require('promise-queue')
const env = require('./lib/env')
const dbs = require('./lib/dbs')
const statsd = require('./lib/statsd')
require('./lib/rollbar')
// if (cluster.isMaster && env.NODE_ENV !== 'development') {
// for (let i = 0; i++ < env.WORKER_SIZE;) cluster.fork()
// cluster.on('exit', (worker, code, signal) => {
// console.log('worker %d died (%s). restarting...', worker.process.pid, signal || code)
// cluster.fork()
// })
// } else {
;(async () => {
const amqp = require('amqplib')
const conn = await amqp.connect(env.AMQP_URL)
const channel = await conn.createChannel()
// 5 different prios because order matters
// e.g. always sync before everything else
// or always uninstall integrations before installing
await channel.assertQueue(env.EVENTS_QUEUE_NAME, {
maxPriority: 5
})
await channel.assertExchange(`${env.JOBS_QUEUE_NAME}-exchange`, 'x-delayed-message', {
arguments: {
'x-delayed-type': 'direct'
}
})
// one prio for free, support and paid plans each
const jobsQueue = await channel.assertQueue(env.JOBS_QUEUE_NAME, {
maxPriority: 3
})
await channel.bindQueue(jobsQueue.queue, `${env.JOBS_QUEUE_NAME}-exchange`, env.JOBS_QUEUE_NAME)
const scheduleJob = channel.publish.bind(channel, `${env.JOBS_QUEUE_NAME}-exchange`, env.JOBS_QUEUE_NAME)
const worker = require('./lib/worker').bind(null, scheduleJob, channel)
const queues = {
'registry-change': new Queue(1, Infinity),
'stripe-event': new Queue(1, Infinity),
'reset': new Queue(1, Infinity)
}
channel.consume(env.EVENTS_QUEUE_NAME, consume)
channel.consume(env.JOBS_QUEUE_NAME, consume)
if (env.NODE_ENV !== 'testing') {
setInterval(function collectAccountQueueStats () {
statsd.gauge('queues.account-jobs', Object.keys(queues).length)
}, 5000)
}
const scheduleRemindersJobData = Buffer.from(JSON.stringify({name: 'schedule-stale-initial-pr-reminders'}))
async function scheduleReminders () {
try {
await scheduleJob(scheduleRemindersJobData, {priority: 1})
} catch (e) {
console.log(e)
}
}
setTimeout(scheduleReminders, 5000)
setInterval(scheduleReminders, 24 * 60 * 60 * 1000)
async function consume (job) {
const data = JSON.parse(job.content.toString())
const jobsWithoutOwners = ['registry-change', 'stripe-event', 'schedule-stale-initial-pr-reminders', 'reset']
if (jobsWithoutOwners.includes(data.name)) {
return queues[data.name].add(() => worker(job))
}
let queueId = Number(data.accountId) ||
_.get(data, 'repository.owner.id') ||
_.get(data, 'installation.account.id') ||
_.get(data, 'organization.id')
if (!queueId) {
const login = _.get(data, 'repository.owner.name')
try {
if (!login) throw new Error(`can not identify job owner of ${data.name}`)
const {installations} = await dbs()
queueId = _.get(await installations.query('by_login', {
key: login
}), 'rows[0].id')
if (!queueId) throw new Error('totally can not identify job owner')
} catch (e) {
channel.nack(job, false, false)
throw e
}
}
const q = queues[queueId] = queues[queueId] || new Queue(1, Infinity)
q.add(() => worker(job))
}
})()
// }
|
JavaScript
| 0.000019 |
@@ -2611,24 +2611,57 @@
ta.name)) %7B%0A
+ if (queues%5Bdata.name%5D) %7B%0A
return
@@ -2702,16 +2702,82 @@
r(job))%0A
+ %7D%0A throw new Error(%60Unknown queue name: $%7Bdata.name%7D%60)%0A
%7D%0A%0A
|
c52188d7e9e1a1ea379137b921e8ac70b2c0f8eb
|
clean up
|
index.js
|
index.js
|
var colors = require('colors');
var package = require('./package.json');
var JSON5 = require('json5');
var glob = require('glob');
var path = require('path');
var fs = require('fs');
function start() {
var cwd = path.resolve(__dirname, '../../');
console.log('files', process.argv.slice(2));
process.argv.slice(2).forEach(function(pattern) {
glob.sync(pattern, {
cwd: cwd,
ignore: ['node_modules/**/*', 'build/**/*', 'build.js']
}).forEach(function (filename) {
var content = fs.readFileSync(path.join(cwd, filename), 'utf-8');
try {
filename.endsWith('.json') ? JSON5.parse(content) : require(path.join(cwd, filename));
} catch (err) {
handleError(filename, err);
}
});
});
}
function handleError(filename, err) {
console.error(colors.yellow.underline(filename) + '\n' + colors.red(err.message) + '\n');
}
start();
|
JavaScript
| 0.000001 |
@@ -253,57 +253,8 @@
');%0A
- console.log('files', process.argv.slice(2));%0A
|
9485903cbf96e0f05bf187b924e7040ee554ab09
|
Remove null charakter byte from model
|
index.js
|
index.js
|
const http = require('http');
const execSync = require('child_process').execSync;
const fs = require('fs');
const os = require("os");
const diskspace = require('fd-diskspace');
const port = 9360;
console.log('started raspberry-status-server at port ' + port);
console.log(getOperatingSystem());
http.createServer(function(request, response) {
response.setHeader('Content-Type', 'application/json');
response.end(JSON.stringify(
{
hostname: os.hostname(),
model: getModel(),
operatingsystem: getOperatingSystem(),
uptime: parseInt(os.uptime() / (60 * 60 * 24)),
load: parseFloat(os.loadavg()[1].toFixed(2)),
processes: parseInt(getNumberOfProcesses()),
temperature: parseFloat(getTemperature()),
cpu: {
cores: os.cpus().length,
speed: os.cpus()[0].speed
},
memory: {
total: inMegabyte(os.totalmem()),
used: inMegabyte(os.totalmem() - os.freemem()),
free: inMegabyte(os.freemem()),
percent: (100 - parseFloat((os.freemem() * 100) / os.totalmem()).toFixed(2))
},
disks: diskspace.diskSpaceSync().disks
}
));
}).listen(port);
function inMegabyte(bytes) {
return parseInt(bytes / 1000 / 1000);
}
function getNumberOfProcesses() {
return execSync('ps aux | wc -l').toString().replace('\n', '');
}
function getModel() {
const filename = '/proc/device-tree/model';
if (! fs.existsSync(filename)) {
return 'unknown';
}
return fs.readFileSync(filename, 'utf8');
}
function getOperatingSystem() {
const filename = '/etc/os-release';
if (! fs.existsSync(filename)) {
return 'unknown';
}
const content = fs.readFileSync(filename, 'utf8');
const regexp = /PRETTY_NAME="(.*)"/g;
return regexp.exec(content)[1];
}
function getTemperature() {
const filename = '/sys/class/thermal/thermal_zone0/temp';
if (! fs.existsSync(filename)) {
return 'not found';
}
var temperature = fs.readFileSync(filename, 'utf8');
temperature = temperature.replace(/\n$/, '');
return parseFloat(temperature / 1000).toFixed(2);
}
|
JavaScript
| 0.000001 |
@@ -1532,22 +1532,23 @@
%7D%0A%0A
-return
+model =
fs.read
@@ -1571,24 +1571,73 @@
e, 'utf8');%0A
+ model.replace(/%5C0/g, '');%0A%0A return model;%0A
%7D%0A%0Afunction
|
e6a020e8dd6a63caae376938af0acd6eb01782b3
|
Add jasmine-core
|
index.js
|
index.js
|
#!/usr/bin/env node
'use strict';
const fs = require('fs');
const path = require('path');
const package_json = path.resolve('./package.json');
const tsconfig_json = path.resolve('./tsconfig.json');
const webpack_config_js = path.resolve('./webpack.config.js');
const karma_config_js = path.resolve('./karma.config.js');
const git_ignore_file = path.resolve('./.gitignore');
const execSync = require('child_process').execSync;
// webpack 2.x
const webpack_config = `module.exports = {
entry: './index.ts',
output: {
filename: './app.[hash].js'
},
resolve: {
extensions: ['.ts', '.tsx', '.js']
},
module: {
rules: [
{ test: /\.tsx?$/, loader: 'ts-loader' }
]
}
}`;
// karma config
const karma_config = `var webpackConfig = require('./webpack.config');
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ["jasmine"],
files: [
{ pattern: "tests/*.spec.ts" }
],
exclude: [
],
preprocessors: {
'tests/*.spec.*': ['webpack'],
},
webpack: webpackConfig,
reporters: ["progress"],
colors: true,
logLevel: config.LOG_INFO,
browsers: ['Chrome'],
mime: {
'text/x-typescript': ['ts','tsx']
}
})
}`;
const git_ignore = `
.DS_Store
node_modules
*.log
`;
if (!fs.existsSync(package_json)) {
console.log('Initializing package.json');
execSync('npm init -y');
}
console.log('Installing packages. This might take a couple minutes.');
execSync('npm install webpack webpack-dev-server ts-loader typescript --save-dev');
execSync('npm install @types/jasmine karma karma-jasmine karma-webpack karma-chrome-launcher --save-dev');
if (!fs.existsSync(tsconfig_json)) {
console.log('Creating tsconfig.json');
execSync('tsc --init');
}
const tsconfig = require(tsconfig_json);
if (!tsconfig.compilerOptions || ! tsconfig.compilerOptions.lib) {
tsconfig["compilerOptions"]["lib"] = ["dom", "es2015.promise", "es5"];
}
console.log('Updating tsconfig.json');
fs.writeFileSync(
tsconfig_json,
JSON.stringify(tsconfig, null, 2)
);
RegExp.prototype.toJSON = RegExp.prototype.toString;
if (!fs.existsSync(webpack_config_js)) {
console.log('Creating webpack.config.js');
fs.writeFileSync(
webpack_config_js,
webpack_config
);
}
if (!fs.existsSync(karma_config_js)) {
console.log('Creating karma.config.js');
fs.writeFileSync(
karma_config_js,
karma_config
);
}
console.log('Initializing git');
execSync('git init');
if (!fs.existsSync(git_ignore_file)) {
console.log('Creating .gitignore');
fs.writeFileSync(
git_ignore_file,
git_ignore
);
}
console.log('Adding npm scripts');
const package_info = require(package_json);
if (!package_info.scripts || ! package_info.scripts['dev']) {
package_info["scripts"]["dev"] = 'webpack-dev-server --inline --hot';
}
if (!package_info.scripts || ! package_info.scripts['build:prod']) {
package_info["scripts"]["build:prod"] = 'webpack -p';
}
if (package_info.scripts) {
package_info["scripts"]["test"] = 'karma start';
}
fs.writeFileSync(
package_json,
JSON.stringify(package_info, null, 2)
);
|
JavaScript
| 0.998811 |
@@ -1577,24 +1577,37 @@
pes/jasmine
+jasmine-core
karma karma-
|
f420a11a431679a6b8be1ba1634eff4efb5fc935
|
return response
|
index.js
|
index.js
|
module.exports = function (options) {
return {
available: function (callback) {
if (typeof navigator === 'undefined') return callback(false);
return callback(!!navigator.mimeTypes['application/x-shockwave-flash']);
},
permission: function (callback) {
this.rec = {};
Wami.setup({
id: options.elementId,
onReady: callback,
swfUrl: options.swfUrl
});
},
send: function (url, callback) {
callback(null, this.rec.url);
},
start: function (callback) {
var self = this;
var error = Wami.nameCallback(function (err) {
self.rec.callback(err[0]);
});
var stop = Wami.nameCallback(function (data) {
self.rec.url = data[0].url;
self.rec.callback();
});
Wami.startRecording(options.uploadUrl, null, stop, error);
return callback();
},
stop: function (callback) {
this.rec.callback = callback;
Wami.stopRecording();
}
};
};
|
JavaScript
| 0.999999 |
@@ -483,20 +483,16 @@
this.rec
-.url
);%0A %7D
|
8b104f38c0dddc5e5bba386c802a21ecc22e1b74
|
fix example typo
|
index.js
|
index.js
|
'use strict';
/**
* Module dependencies.
*/
var logger = require('mm-node-logger')(module),
mongoose = require('mongoose');
/**
* This module follow best practice for creating, maintaining and using a Mongoose connection like:
* - open the connection when the app process start
* - start the app server when the connection is open (optional)
* - monitor the connection events (`connected`, `error` and `disconnected`)
* - close the connection when the app process terminates
*
* @example
* ```js
* var mongodb = require('mm-mongoose-connection');
* var config = {
* dbURI: 'mongodb://127.0.0.1:27017/connectionDemo',
* dbOptions: {user: '', pass: ''}
* }
* // start mongo db
* mongodb(config, function() {
* // start up the server
* app.listen(3000, function () {
* console.info('app started on port: 3000');
* });
* });
* ```
*
* @param {Object} config - the mongo config connection options
* @param {*=} cb - the callback that start server
*/
module.exports = function(config, cb) {
// create the database connection
mongoose.connect(config.dbURI, config.dbOptions);
// when successfully connected
mongoose.connection.on('connected', function () {
logger.info('Mongoose connected to ' + config.dbURI);
});
// if the connection throws an error
mongoose.connection.on('error', function (err) {
logger.error('Mongoose connection error: ' + err);
});
// when the connection is disconnected
mongoose.connection.on('disconnected', function () {
logger.info('Mongoose disconnected');
});
// when the connection is open
mongoose.connection.once('open', function () {
if(cb && typeof(cb) === 'function') cb();
});
// if the Node process ends, close the Mongoose connection
process.on('SIGINT', function() {
mongoose.connection.close(function () {
logger.info('Mongoose disconnected through app termination');
process.exit(0);
});
});
};
// TODO: test
// http://www.scotchmedia.com/tutorials/express/authentication/1/06
// https://github.com/elliotf/mocha-mongoose
|
JavaScript
| 0.003131 |
@@ -312,26 +312,41 @@
server when
-th
+after the databas
e connection
@@ -342,25 +342,26 @@
connection
-i
+wa
s open (opti
|
cccf536090800cbce4cdf7e8b84d8f2fcbc1b868
|
fix nam export
|
index.js
|
index.js
|
module.exports.Sortable = require('./src/Sortable.js');
module.exports.SortableNested = require('./src/SortableNested.js');
|
JavaScript
| 0.000001 |
@@ -42,16 +42,27 @@
Sortable
+Composition
.js');%0Am
|
19ca2d84a6b7a20a8cf53edcb899b4f871e07301
|
Create person with last seen
|
api/missing/create.js
|
api/missing/create.js
|
var MissingPerson = require('../../app/models/missingPerson');
exports.create = function (req, res) {
var firstname = req.body.firstname;
var surname = req.body.surname;
var missingPerson = new MissingPerson();
if (firstname) {
missingPerson.forenames = firstname;
}
if (surname) {
missingPerson.surname = surname;
}
missingPerson.gender = 'M';
missingPerson.status = 'Missing';
missingPerson.category = 'Missing';
missingPerson.birthYear = req.body.birthYear;
missingPerson.borough = req.body.town;
missingPerson.latitude = req.body.latitude;
missingPerson.longitude = req.body.longitude;
missingPerson.wentMissing = new Date();
missingPerson.created = new Date();
missingPerson.updated = new Date();
missingPerson.id = generateGUID();
missingPerson.save(function (err) {
if (err) {
console.log(err);
res.json({ message: 'Error' });
}
else {
res.json(missingPerson);
}
});
}
generateGUID = function() {
var _sym = 'ABCDEF1234567890';
var str = '';
var count = 20;
for (var i = 0; i < count; i++) {
str += _sym[parseInt(Math.random() * (_sym.length))];
}
return str;
}
|
JavaScript
| 0 |
@@ -822,24 +822,287 @@
ateGUID();%0A%0A
+ var lastSeen = %7B%7D;%0A lastSeen.date = new Date();%0A lastSeen.longitude = req.body.longitude;%0A lastSeen.latitude = req.body.latitude;%0A lastSeen.accountId = req.body.accountId;%0A lastSeen.description = '';%0A missingPerson.lastSeen.push(lastSeen);%0A%0A
missingP
|
7f3a6beb7fc99fc6a8761edaba5d398614dd2a20
|
Move back to Streams1
|
index.js
|
index.js
|
'use strict';
module.exports = function read(stream, options, cb) {
if (!stream) {
throw new Error('stream argument is required');
}
if (typeof options === 'function') {
cb = options;
options = {};
}
if (typeof options === 'string' || options === undefined || options === null) {
options = { encoding: options };
}
if (!cb) {
throw new Error('callback argument is required');
}
var chunks = [];
var len = 0;
var err = null;
stream.on('readable', function () {
var chunk;
while (chunk = stream.read()) {
chunks.push(chunk);
len += chunk.length;
}
});
stream.once('error', function (error) {
err = error;
});
stream.once('end', function () {
var data = Buffer.concat(chunks, len);
if (options.encoding !== null) {
data = data.toString(options.encoding || 'utf-8');
}
cb(err, data);
});
};
|
JavaScript
| 0.000003 |
@@ -460,16 +460,12 @@
on('
-readable
+data
', f
@@ -477,60 +477,17 @@
on (
-) %7B%0A%09%09var chunk;%0A%09%09while (chunk = stream.read()
+chunk
) %7B%0A
-%09
%09%09ch
@@ -506,17 +506,16 @@
unk);%0A%09%09
-%09
len += c
@@ -527,20 +527,16 @@
length;%0A
-%09%09%7D%0A
%09%7D);%0A%0A%09s
|
b65e558127c14197dbc5cb416b04e71c48f23a6b
|
remove underline
|
index.js
|
index.js
|
const { deploy } = require('sftp-sync-deploy');
hexo.extend.deployer.register("sftp", function(args, callback) {
if (!args.host || !args.user) {
const help = [
"You should argsure deployment settings in _config.yml first!",
"",
"Example:",
" deploy:",
" type: sftp",
" host: <host>",
" port: [port] # Default is 21",
" user: <user>",
" pass: <pass> # leave blank for paswordless connections",
" privateKey: [path/to/privateKey] # Optional",
" passphrase: [passphrase] # Optional",
" agent: [path/to/agent/socket] # Optional, defaults to $SSH_AUTH_SOCK",
" remotePath: [remotePath] # Default is `/`",
" forceUpload: [boolean] # default is false",
"",
"For more help, you can check the docs: " +
"https://hexo.io/docs/one-command-deployment".underline
];
console.log(help.join("\n"));
return callback();
}
const config = {
host: args.host,
port: args.port || 22,
username: args.user,
password: args.pass,
privateKey: args.privateKey,
passphrase: args.passphrase,
agent: args.agent || process.env.SSH_AUTH_SOCK,
localDir: hexo.public_dir,
remoteDir: args.remotePath || "/"
};
const options = {
dryRun: !!args.dryrun,
forceUpload: args.forceUpload,
excludeMode: 'remove',
concurrency: 100
// exclude: [ // exclude patterns (glob)
// 'node_modules',
// 'src/**/*.spec.ts'
// ]
};
deploy(config, options).then(() => {
callback();
}).catch(err => {
callback(err);
});
});
|
JavaScript
| 0.0003 |
@@ -20,17 +20,17 @@
require(
-'
+%22
sftp-syn
@@ -37,17 +37,17 @@
c-deploy
-'
+%22
);%0A%0Ahexo
@@ -878,18 +878,8 @@
ent%22
-.underline
%0A
@@ -1358,16 +1358,16 @@
de:
-'
+%22
remove
-'
+%22
,%0A
@@ -1544,16 +1544,21 @@
options)
+%0A
.then(()
@@ -1559,32 +1559,34 @@
hen(() =%3E %7B%0A
+
callback();%0A %7D)
@@ -1581,20 +1581,27 @@
back();%0A
+
%7D)
+%0A
.catch(e
@@ -1608,24 +1608,26 @@
rr =%3E %7B%0A
+
callback(err
@@ -1629,16 +1629,18 @@
k(err);%0A
+
%7D);%0A%7D)
|
d917d1d90f3781c27c1504f29d0cc2963a7341ad
|
refactor - remove unnecessary code
|
index.js
|
index.js
|
(function(){
var Traverse = require('traverse');
module.exports = datify;
function datify(raw){
if (typeof raw === 'string'){
return datifyString(raw);
}
else {
return Traverse.map(raw, function(value){
if (typeof value === 'string'){
this.update(datifyString(value));
}
});
}
};
function datifyString(raw){
var parsedDate = Date.parse(raw);
if (parsedDate) {
return new Date(parsedDate);
}
else {
return raw;
}
}
})()
|
JavaScript
| 0.000001 |
@@ -98,83 +98,8 @@
w)%7B%0A
-%09%09if (typeof raw === 'string')%7B%0A%09%09%09return datifyString(raw);%0A%09%09%7D%0A%09%09else %7B%0A%09
%09%09re
@@ -138,17 +138,16 @@
value)%7B%0A
-%09
%09%09%09if (t
@@ -177,17 +177,16 @@
')%7B%0A%09%09%09%09
-%09
this.upd
@@ -215,25 +215,19 @@
));%0A
-%09
%09%09%09%7D%0A%09%09
-%09
%7D);%0A
-%09%09%7D%0A
%09%7D;%09
|
af6c08aa60e9cca984e81be9f07fcdf8bc7e0ca5
|
add two missing let for err
|
index.js
|
index.js
|
'use strict';
const util = require('util');
const events = require('events');
const crypto = require('crypto');
const extend = require('util-extend');
const requestPromise = require('request-promise-native');
const querystring = require('querystring');
/**
* BitcoindeClient connects to the bitcoin.de API
* @param {object} settings Object required keys "key" and "secret"
*/
function BitcoindeClient(settings) {
var self = this;
let config_default = {
url: 'https://api.bitcoin.de',
version: 'v2',
agent: 'Bitcoin.de NodeJS API Client',
timeoutMS: 20000
};
let config = extend(config_default, settings);
if (!config.key) self.emit('error', new Error('required settings "key" is missing'));
if (!config.secret) self.emit('error', new Error('required settings "secret" is missing'));
/**
* Initialize necessary properties from EventEmitter
*/
events.EventEmitter.call(self);
/**
* Perform GET API request
* @param {String} method API method
* @param {Object} params Arguments to pass to the api call
* @return {Object} The request object
*/
self.get = function(method, params) {
var url = config.url+'/'+config.version+'/'+method;
return rawRequest('get', url, params);
};
/**
* Perform POST API request
* @param {String} method API method
* @param {Object} params Arguments to pass to the api call
* @return {Object} The request object
*/
self.post = function(method, params) {
var url = config.url+'/'+config.version+'/'+method;
return rawRequest('post', url, params);
};
/**
* Perform DELETE API request
* @param {String} method API method
* @param {Object} params Arguments to pass to the api call
* @return {Object} The request object
*/
self.delete = function(method, params) {
var url = config.url+'/'+config.version+'/'+method;
return rawRequest('delete', url, params);
};
/**
* Send the actual HTTP request
* @param {String} method HTTP method
* @param {String} url URL to request
* @param {Object} params POST body
* @return {Object} The request object
*/
var rawRequest = function(method, url, params) {
let nonce = noncer.generate();
let md5Query = 'd41d8cd98f00b204e9800998ecf8427e'; // empty string hash
let options = {
url: url,
timeout: config.timeoutMS,
json: true
};
if (params) {
switch(method) {
case 'post':
var queryParams = {};
Object.keys(params).sort().forEach(function(idx) { queryParams[idx] = params[idx]; });
md5Query = crypto.createHash('md5')
.update(querystring.stringify(queryParams))
.digest('hex');
options.form = queryParams;
options.method = 'POST';
break;
case 'get':
options.url += '?'+querystring.stringify(params);
break;
case 'delete':
options.url += '?'+querystring.stringify(params);
options.method = 'DELETE';
break;
default:
return new Promise((resolve, reject) => {
let err = new Error('Method ' + method + ' not defined');
self.emit('error', err);
reject(err)
});
}
}
var signature = crypto.createHmac('sha256', config.secret)
.update([method.toUpperCase(), options.url, config.key, nonce, md5Query].join('#'))
.digest('hex');
options.headers = {
'User-Agent' : config.agent,
'X-API-KEY' : config.key,
'X-API-NONCE' : nonce,
'X-API-SIGNATURE': signature
};
return new Promise((resolve, reject) => {
requestPromise(options)
.then((data) => {
if(data.errors && data.errors.length) {
// can we do something better with data.errors?
err = new Error('Bitcoin.de API returned error: '+data.errors[0].message);
self.emit('error', err);
reject(err)
} else {
resolve(data)
}
})
.catch((error) => {
err = new Error('Error in server response: '+JSON.stringify(error));
self.emit('error', err);
reject(err)
});
});
}; // rawRequest
/**
* Nonce generator
*/
var noncer = new (function() {
// if you call Date.now() too fast it will generate
// the same ms, helper to make sure the nonce is
// truly unique (supports up to 999 calls per ms).
this.generate = function() {
var now = Date.now();
this.counter = (now === this.last? this.counter + 1 : 0);
this.last = now;
// add padding to nonce
var padding =
this.counter < 10 ? '000' :
this.counter < 100 ? '00' :
this.counter < 1000 ? '0' : '';
return now + padding + this.counter;
};
})();
};
util.inherits(BitcoindeClient, events.EventEmitter);
module.exports = BitcoindeClient;
|
JavaScript
| 0.006444 |
@@ -3153,24 +3153,25 @@
%09reject(err)
+;
%0A%09%09%09%09%09%7D);%0A%09%09
@@ -3699,24 +3699,28 @@
rors?%0A%09%09%09%09%09%09
+let
err = new Er
@@ -3724,17 +3724,17 @@
Error('
-B
+b
itcoin.d
@@ -3756,17 +3756,19 @@
error: '
-+
+ +
data.err
@@ -3828,24 +3828,25 @@
%09reject(err)
+;
%0A%09%09%09%09%09%7D else
@@ -3867,16 +3867,17 @@
ve(data)
+;
%0A%09%09%09%09%09%7D%0A
@@ -3912,16 +3912,20 @@
%7B%0A%09%09%09%09%09
+let
err = ne
@@ -3960,17 +3960,19 @@
ponse: '
-+
+ +
JSON.str
@@ -4033,16 +4033,17 @@
ect(err)
+;
%0A%09%09%09%09%7D);
@@ -4635,17 +4635,16 @@
%09%7D)();%0A%7D
-;
%0A%0Autil.i
|
c69a0859d50bbc77d41e61073a43efcea1205827
|
add all pass cases
|
regression.js
|
regression.js
|
[
/********************************
* STEP 1 PASS
* ******************************/
{
code: "<p><span class='first-sentence'>Groupers are others</span></p> <p><span class='first-sentence'>Groupers are things</span></p>",
steps: ["pass"]
},
/********************************
* STEP 1 FAIL
* ******************************/
/********************************
* STEP 2 PASS
* ******************************/
{
code: "<style>.first-sentence { font-weight: bold; }</style><p><span class='first-sentence'>Groupers are others</span></p> <p><span class='first-sentence'>Groupers are things</span></p>",
steps: ["pass", "pass"]
},
{
code: "<style>.first-sentence { font-weight: 400; }</style><p><span class='first-sentence'>Groupers are others</span></p> <p><span class='first-sentence'>Groupers are things</span></p>",
steps: ["pass", "pass"]
},
{
code: "<style>.first-sentence { text-decoration: underline; }</style><p><span class='first-sentence'>Groupers are others</span></p> <p><span class='first-sentence'>Groupers are things</span></p>",
steps: ["pass", "pass"]
},
/********************************
* STEP 2 FAIL
* ******************************/
/********************************
* STEP 3 PASS
* ******************************/
{
code: "<style>.first-sentence { text-decoration: underline; }</style><div class='info'><p><span class='first-sentence'>Groupers are others</span></p> <p><span class='first-sentence'>Groupers are things</span></p></div>",
steps: ["pass", "pass", "pass"]
},
/********************************
* STEP 3 FAIL
* ******************************/
/********************************
* STEP 4 PASS
* ******************************/
{
code: "<style>.first-sentence { text-decoration: underline; } .info { background: red; }</style><div class='info'><p><span class='first-sentence'>Groupers are others</span></p> <p><span class='first-sentence'>Groupers are things</span></p></div>",
steps: ["pass", "pass", "pass", "pass"]
},
{
code: "<style>.first-sentence { text-decoration: underline; } .info { background-color: red; }</style><div class='info'><p><span class='first-sentence'>Groupers are others</span></p> <p><span class='first-sentence'>Groupers are things</span></p></div>",
steps: ["pass", "pass", "pass", "pass"]
}
/********************************
* STEP 4 FAIL
* ******************************/
]
// [{
// code: "<p><span>Groupers</span></p>",
// steps: ["Looks like you added 1 <span>, make sure you add another <span> to the first sentence of the second paragraph."]
// }, {
// code: "<p><span>Groupers are others</span></p> <p><span>Groupers are things</span></p>",
// steps: ["Looks like you added <span>s. Make sure you also add the 'first-sentence' class to each span too."]
// },{
// code: "<p><span id='first-sentence'>Groupers are others</span></p> <p><span>Groupers are things</span></p>",
// steps: ["Remember, we want to use classes for this challenge, not ids. That means you should use the `class` attribute on your HTML tag, and the '.' before the class name in your CSS selector."]
// },
// {
// code: "<p><span class='first-sentence'>Groupers are others</span></p> <p><span class='first-sentence'>Groupers are things</span></p>",
// steps: ["Once you've added the <span>s, add a style for the 'first-sentence' class that makes them bold or underline."]
// },
// {
// code: "<style>.first-sentence { font-style:underline; }</style> <p><span class='first-sentence'>Groupers are others</span></p> <p><span class='first-sentence'>Groupers are things</span></p>",
// steps: ["To make text bold, use the `font-weight` property. To make text underline, use the `text-decoration` property. If you forget those properties in the future, you can always search the web."]
// },
// {
// code: "<style>.first-sentence { text-decoration:underline; }</style> <p><span class='first-sentence'>Groupers are others</span></p> <p><span class='first-sentence'>Groupers are things</span></p>",
// steps: ["pass"]
// },
// {
// code: "<style>.first-sentence { font-weight:bold; }</style> <p><span class='first-sentence'>Groupers are others</span></p> <p><span class='first-sentence'>Groupers are things</span></p>",
// steps: ["pass"]
// },
// {
// code: "<style>.first-sentence { font-weight:bold; }</style> <div><p><span class='first-sentence'>Groupers are others</span></p> <p><span class='first-sentence'>Groupers are things</span></p></div>",
// steps: ["pass", "Looks like you added a <div>. Make sure you also add the 'info' class to the div."]
// },
// {
// code: "<style>.first-sentence { font-weight:bold; }</style> <div class='info'><p><span class='first-sentence'>Groupers are others</span></p> <p><span class='first-sentence'>Groupers are things</span></p></div>",
// steps: ["pass", "Once you've added the <div>, add a style for the 'info' class that gives it a background color."]
// },
// {
// code: "<style>.first-sentence { font-weight:bold;} .info { background: grey; }</style> <div id='info'><p><span class='first-sentence'>Groupers are others</span></p> <p><span class='first-sentence'>Groupers are things</span></p></div>",
// steps: ["pass", "Add a class of 'info', not an id."]
// },
// {
// code: "<style>.first-sentence { font-weight:bold;} .info { background: grey; }</style> <div class='info'><p><span class='first-sentence'>Groupers are others</span></p> <p><span class='first-sentence'>Groupers are things</span></p></div>",
// steps: ["pass", "pass"]
// },
// {
// code: "<style>.first-sentence { font-weight:900;} .info { background: grey; }</style> <div class='info'><p><span class='first-sentence'>Groupers are others</span></p> <p><span class='first-sentence'>Groupers are things</span></p></div>",
// steps: ["pass", "pass"]
// }
// ]
|
JavaScript
| 0.000009 |
@@ -430,17 +430,16 @@
****/%0A %0A
-
%7B%0A co
|
dc107d1199887914b9fba8f68fd3408b773a490b
|
remove css extension that never used
|
webpack/isomorphic.tools.config.js
|
webpack/isomorphic.tools.config.js
|
import WebpackIsomorphicToolsPlugin from 'webpack-isomorphic-tools/plugin'
import _debug from 'debug'
import projectConfig from '../config'
const debug = _debug('app:webpack:isomorphic:tools:config')
debug('Create configuration.')
// https://github.com/halt-hammerzeit/webpack-isomorphic-tools#configuration
// https://github.com/halt-hammerzeit/webpack-isomorphic-tools#style-loader-css-stylesheets-with-css-modules-feature
export default {
debug: projectConfig.__DEBUG__,
assets: {
images: {
extensions: ['png', 'jpg', 'jpeg', 'gif', 'ico', 'svg']
},
styles: {
extensions: ['css', 'scss'],
filter (module, regex, options, log) {
if (options.development) {
return WebpackIsomorphicToolsPlugin.style_loader_filter(module, regex, options, log)
}
// in production mode there's no webpack "style-loader",
// so the module.name will be equal to the asset path
return regex.test(module.name)
},
path (module, options, log) {
if (options.development) {
return WebpackIsomorphicToolsPlugin.style_loader_path_extractor(module, options, log);
}
// in production mode there's no Webpack "style-loader",
// so `module.name`s will be equal to correct asset paths
return module.name
},
parser (module, options, log) {
if (options.development) {
return WebpackIsomorphicToolsPlugin.css_modules_loader_parser(module, options, log);
}
// In production mode there's Webpack Extract Text Plugin
// which extracts all CSS text away, so there's
// only CSS style class name map left.
return module.source
}
}
}
}
|
JavaScript
| 0 |
@@ -605,15 +605,8 @@
s: %5B
-'css',
'scs
|
4557823f8e9bfe7623ef9602ca311f509fcd806a
|
Allow arbitrary java args to be passed
|
index.js
|
index.js
|
var Buffer = require('buffer').Buffer;
var child_process = require('child_process');
var fs = require('fs');
var gutil = require('gulp-util');
var path = require('path');
var tempWrite = require('temp-write');
var through = require('through');
const PLUGIN_NAME = 'gulp-closure-library';
module.exports = function(opt, execFile_opt) {
opt = opt || {};
opt.maxBuffer = opt.maxBuffer || 1000;
var files = [];
var execFile = execFile_opt || child_process.execFile;
if (!opt.compilerPath)
throw new gutil.PluginError(PLUGIN_NAME, 'Missing compilerPath option.');
if (!opt.fileName)
throw new gutil.PluginError(PLUGIN_NAME, 'Missing fileName option.');
var getFlagFilePath = function(files) {
var src = files.map(function(file) {
var relativePath = path.relative(file.cwd, file.path);
var tempPath = tempWrite.sync(file.contents.toString(), relativePath);
return '--js=' + tempPath;
}).join('\n');
return tempWrite.sync(src);
};
// Can't use sindresorhus/dargs, compiler requires own syntax.
var flagsToArgs = function(flags) {
var args = [];
for (var flag in flags || {}) {
var values = flags[flag];
if (!Array.isArray(values)) values = [values];
values.forEach(function(value) {
args.push('--' + flag + (value === null ? '' : '=' + value));
});
}
return args;
};
function bufferContents(file) {
if (file.isNull()) return;
if (file.isStream()) {
return this.emit('error',
new gutil.PluginError(PLUGIN_NAME, 'Streaming not supported'));
}
files.push(file);
}
function endStream() {
if (!files.length) return this.emit('end');
var firstFile = files[0];
var outputFilePath = tempWrite.sync('');
var args = [
'-jar',
// For faster compilation. It's supported everywhere from Java 1.7+.
'-XX:+TieredCompilation',
opt.compilerPath,
// To prevent maximum length of command line string exceeded error.
'--flagfile=' + getFlagFilePath(files)
].concat(flagsToArgs(opt.compilerFlags));
// Force --js_output_file to prevent [Error: stdout maxBuffer exceeded.]
args.push('--js_output_file=' + outputFilePath);
// Enable custom max buffer to fix "stderr maxBuffer exceeded" error. Default is 200*1024.
var jar = execFile('java', args, { maxBuffer: opt.maxBuffer*1024 }, function(error, stdout, stderr) {
if (error || stderr) {
this.emit('error', new gutil.PluginError(PLUGIN_NAME, error || stderr));
return;
}
var outputFileSrc = fs.readFile(outputFilePath, function(err, data) {
if (err) {
this.emit('error', new gutil.PluginError(PLUGIN_NAME, err));
return;
}
var outputFile = new gutil.File({
base: firstFile.base,
contents: new Buffer(data),
cwd: firstFile.cwd,
path: path.join(firstFile.base, opt.fileName)
});
this.emit('data', outputFile);
this.emit('end');
}.bind(this));
}.bind(this));
}
return through(bufferContents, endStream);
};
|
JavaScript
| 0 |
@@ -2068,24 +2068,101 @@
erFlags));%0A%0A
+ var javaFlags = opt.javaFlags %7C%7C %5B%5D;%0A args = javaFlags.concat(args);%0A%0A
// Force
|
382393e1f2adbd8db9390930a66d3a422505bc2a
|
fix challenge ordering Now challenges are ordered on map first by top order value of json file second by index of array
|
index.js
|
index.js
|
/* eslint-disable no-process-exit */
require('babel/register');
require('dotenv').load();
var fs = require('fs'),
_ = require('lodash'),
path = require('path'),
app = require('../server/server'),
nonprofits = require('./nonprofits.json'),
jobs = require('./jobs.json');
function getFilesFor(dir) {
return fs.readdirSync(path.join(__dirname, '/' + dir));
}
var Challenge = app.models.Challenge;
var Nonprofit = app.models.Nonprofit;
var Job = app.models.Job;
var counter = 0;
var challenges = getFilesFor('challenges');
// plus two accounts for nonprofits and jobs seed.
var numberToSave = challenges.length + 1;
function completionMonitor() {
// Increment counter
counter++;
// Exit if all challenges have been checked
if (counter >= numberToSave) {
process.exit(0);
}
// Log where in the seed order we're currently at
console.log('Call: ' + counter + '/' + numberToSave);
}
Challenge.destroyAll(function(err, info) {
if (err) {
throw err;
} else {
console.log('Deleted ', info);
}
challenges.forEach(function(file) {
var challengeSpec = require('./challenges/' + file);
var order = challengeSpec.order;
var block = challengeSpec.name;
// challenge file has no challenges...
if (challengeSpec.challenges.length === 0) {
console.log('file %s has no challenges', file);
completionMonitor();
return;
}
var challenges = challengeSpec.challenges
.map(function(challenge, index) {
// NOTE(berks): add title for displaying in views
challenge.name =
_.capitalize(challenge.type) +
': ' +
challenge.title.replace(/[^a-zA-Z0-9\s]/g, '');
challenge.dashedName = challenge.name
.toLowerCase()
.replace(/\:/g, '')
.replace(/\s/g, '-');
challenge.order = +('' + order + (index + 1));
challenge.block = block;
return challenge;
});
Challenge.create(
challenges,
function(err) {
if (err) {
throw err;
} else {
console.log('Successfully parsed %s', file);
completionMonitor(err);
}
}
);
});
});
Nonprofit.destroyAll(function(err, info) {
if (err) {
console.error(err);
} else {
console.log('Deleted ', info);
}
Nonprofit.create(nonprofits, function(err, data) {
if (err) {
throw err;
} else {
console.log('Saved ', data);
}
completionMonitor(err);
console.log('nonprofits');
});
});
Job.destroyAll(function(err, info) {
if (err) {
throw err;
} else {
console.log('Deleted ', info);
}
Job.create(jobs, function(err, data) {
if (err) {
console.log('error: ', err);
} else {
console.log('Saved ', data);
}
console.log('jobs');
completionMonitor(err);
});
});
|
JavaScript
| 0 |
@@ -1847,24 +1847,44 @@
r =
-+('' +
+order;%0A challenge.sub
order
-+ (
+=
inde
@@ -1888,18 +1888,16 @@
ndex + 1
-))
;%0A
|
9e057b8c7ffcce74d7c8392521518d351888c27b
|
Update index
|
index.js
|
index.js
|
'use strict';
const express = require('express');
const bodyParser = require('body-parser');
const restService = express();
restService.use(bodyParser.json());
restService.post('/hook', function (req, res) {
console.log('hook request');
try {
var speech = 'empty speech';
if (req.body) {
var requestBody = req.body;
if (requestBody.result) {
speech = '';
if (requestBody.result.fulfillment) {
speech += requestBody.result.fulfillment.speech;
speech += ' ';
}
if (requestBody.result.action) {
speech += 'action: ' + requestBody.result.action;
}
}
}
console.log('result: ', speech);
return res.json({
speech: speech,
displayText: speech,
source: 'apiai-webhook-sample'
});
} catch (err) {
console.error("Can't process request", err);
return res.status(400).json({
status: {
code: 400,
errorType: err.message
}
});
}
});
restService.listen((process.env.PORT || 5000), function () {
console.log("Server listening");
});
|
JavaScript
| 0.000001 |
@@ -88,16 +88,43 @@
ser');%0A%0A
+var time = require('time');
%0Aconst r
@@ -314,16 +314,172 @@
peech';%0A
+ var now = new time.Date();%0A var hour = now.setTimezone(%22America/Chicago%22).getHours();%0A var action = %5B'coverage.speedingTickets'%5D;%0A
%0A
|
be706fc097e91710473656f322c000a077207494
|
remove var proto pattern
|
index.js
|
index.js
|
'use strict';
var TypedError = require('error/typed');
var LogMessage = require('./log-message.js');
var DebugLogBackend = require('./backends/debug-log-backend.js');
var LEVELS = require('./levels.js').LEVELS_BY_NAME;
var validNamespaceRegex = /^[a-zA-Z0-9]+$/;
var InvalidNamespaceError = TypedError({
type: 'debug-logtron.invalid-argument.namespace',
message: 'Unexpected characters in the `namespace` arg.\n' +
'Expected the namespace to be a bare word but instead ' +
'found {badChar} character.\n' +
'SUGGESTED FIX: Use just alphanum in the namespace.\n',
badChar: null,
reason: null,
namespace: null
});
module.exports = DebugLogtron;
function DebugLogtron(namespace, opts) {
if (!(this instanceof DebugLogtron)) {
return new DebugLogtron(namespace, opts);
}
var isValid = validNamespaceRegex.test(namespace);
if (!isValid) {
var hasHypen = namespace.indexOf('-') >= 0;
var hasSpace = namespace.indexOf(' ') >= 0;
throw InvalidNamespaceError({
namespace: namespace,
badChar: hasHypen ? '-' : hasSpace ? 'space' : 'bad',
reason: hasHypen ? 'hypen' :
hasSpace ? 'space' : 'unknown'
});
}
opts = opts || {};
this.name = namespace;
this._backend = DebugLogBackend(namespace, opts);
this._stream = this._backend.createStream();
}
var proto = DebugLogtron.prototype;
proto._log = function _log(level, msg, meta, cb) {
var logMessage = new LogMessage(level, msg, meta);
LogMessage.isValid(logMessage);
this._stream.write(logMessage, cb);
};
proto.whitelist = function whitelist(level, msg) {
this._backend.whitelist(level, msg);
};
proto.items = function items() {
return this._backend.records;
};
proto.trace = function trace(msg, meta, cb) {
this._log(LEVELS.trace, msg, meta, cb);
};
proto.debug = function debug(msg, meta, cb) {
this._log(LEVELS.debug, msg, meta, cb);
};
proto.info = function info(msg, meta, cb) {
this._log(LEVELS.info, msg, meta, cb);
};
proto.access = function access(msg, meta, cb) {
this._log(LEVELS.access, msg, meta, cb);
};
proto.warn = function warn(msg, meta, cb) {
this._log(LEVELS.warn, msg, meta, cb);
};
proto.error = function error(msg, meta, cb) {
this._log(LEVELS.error, msg, meta, cb);
};
proto.fatal = function fatal(msg, meta, cb) {
this._log(LEVELS.fatal, msg, meta, cb);
};
|
JavaScript
| 0.000002 |
@@ -1416,20 +1416,8 @@
%0A%7D%0A%0A
-var proto =
Debu
@@ -1434,24 +1434,16 @@
rototype
-;%0A%0Aproto
._log =
@@ -1620,180 +1620,30 @@
%7D;%0A%0A
-proto.whitelist = function whitelist(level, msg) %7B%0A this._backend.whitelist(level, msg);%0A%7D;%0A%0Aproto.items = function items() %7B%0A return this._backend.records;%0A%7D;%0A%0Aproto
+DebugLogtron.prototype
.tra
@@ -1727,21 +1727,38 @@
b);%0A%7D;%0A%0A
+DebugLogtron.
proto
+type
.debug =
@@ -1838,21 +1838,38 @@
b);%0A%7D;%0A%0A
+DebugLogtron.
proto
+type
.info =
@@ -1946,21 +1946,38 @@
b);%0A%7D;%0A%0A
+DebugLogtron.
proto
+type
.access
@@ -2060,21 +2060,38 @@
b);%0A%7D;%0A%0A
+DebugLogtron.
proto
+type
.warn =
@@ -2168,21 +2168,38 @@
b);%0A%7D;%0A%0A
+DebugLogtron.
proto
+type
.error =
@@ -2279,21 +2279,38 @@
b);%0A%7D;%0A%0A
+DebugLogtron.
proto
+type
.fatal =
@@ -2369,28 +2369,229 @@
S.fatal, msg, meta, cb);%0A%7D;%0A
+%0ADebugLogtron.prototype.whitelist = function whitelist(level, msg) %7B%0A this._backend.whitelist(level, msg);%0A%7D;%0A%0ADebugLogtron.prototype.items = function items() %7B%0A return this._backend.records;%0A%7D;%0A
|
b4724a0df1c9a710bace85e7cb51565042d9d6eb
|
allow for null characters
|
index.js
|
index.js
|
var spaceCode = ' '.charCodeAt(0)
function stringToBits(str) {
var bits = []
for (var i = 0, l = str.length; i < l; i += 1) {
var character = str[i]
, number = str.charCodeAt(i) || spaceCode
// Non-standard characters are treated as spaces
if (number > 255) number = spaceCode
// Split the character code into bits
for (var j = 7; j >= 0; j -= 1) {
bits[i * 8 + 7 - j] = (number >> j) & 1
}
}
return bits
}
function bitsToString(bits) {
var str = ''
, character
for (var i = 0, l = bits.length; i < l; i += 8) {
character = 0
for (var j = 7; j >= 0; j -= 1) {
character += bits[i + 7 - j] << j
}
str += String.fromCharCode(character)
}
return str
}
function encode(channel, stegotext, fn) {
fn = fn || function index(n) { return n }
var i = 0
, channelLength = channel.length
, stegoLength
, textLength
, index
textLength = stegotext.length
stegotext = stringToBits(stegotext)
stegoLength = stegotext.length
// Encode length into the first 4 bytes
channel[fn(0)] = (textLength >> 32) & 255
channel[fn(1)] = (textLength >> 24) & 255
channel[fn(2)] = (textLength >> 16) & 255
channel[fn(3)] = (textLength >> 8) & 255
while (i < channelLength && i < stegoLength) {
index = fn(i + 4)
if (index < 0) break
channel[index] = (channel[index] & 254) + (stegotext[i] ? 1 : 0)
i += 1
}
return channel
}
function decode(channel, fn) {
fn = fn || function index(n) { return n }
var i = 0
, l = 0
, stegotext = []
, index
for (var n = 0; n < 4; n += 1) {
l += channel[fn(n)] << n * 8
}
l = Math.min(l * 8, channel.length)
while (i < l) {
index = fn(i + 4)
if (index < 0) break
stegotext[i] = (channel[index] & 1) ? 1 : 0
i += 1
}
return bitsToString(stegotext)
}
module.exports = {
encode: encode
, decode: decode
, bitsToString: bitsToString
, stringToBits: stringToBits
}
|
JavaScript
| 0.00001 |
@@ -190,21 +190,8 @@
t(i)
- %7C%7C spaceCode
%0A%0A
|
9c6d73c94ef8d91015581af1101f32f9fb25a48f
|
Fix typo
|
app/client/js/fink.js
|
app/client/js/fink.js
|
'use strict'
;(function (Fink, fetch, _isURI, parseURI) {
Fink.isURI = function (uri) {
return _isURI(uri, window.location.hostname)
}
Fink.register = function (uri) {
return fetch(Fink.endpoint, {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
uri: uri
})
}).then(function (response) {
return response.json()
})
}
Fink.buzz = function () {
var elem = document.getElementById('fink-logo')
elem.classList.add('toggleBuzz')
setTimeout(function () {
elem.classList.remove('toggleBuzz')
}, 750)
}
})(window.Fink, window.fetch, require('fink-is-uri')); // eslint-disable-line
|
JavaScript
| 0.999999 |
@@ -42,18 +42,8 @@
sURI
-, parseURI
) %7B%0A
@@ -694,30 +694,20 @@
ch,
-require('fink-is-uri')
+window.isURI
); /
|
7da2af251e8e57a3ad9fb9074fe3250b2e4ac37c
|
Fix Proxy.set return value to match ES6 specifications
|
index.js
|
index.js
|
var deasync = require("deasync");
module.exports = function Rebridge(client) {
if (!client) {
var redis = require("redis");
client = redis.createClient();
}
return _Rebridge(client);
};
function _Rebridge(client, base = {}, inTree = []) {
// Yeah, that's a bit weird, but it works.
// "inTree" is the list of ancestors, with the generating ancestor as the first
// element and the immediate parent as the last.
return new Proxy(
base,
{
get: function(obj, key) {
// Avoid all the weird mess with symbols.
// After all, any key you can possibly read is a string.
// Not sure this is needed tho.
if (typeof key !== typeof "a") return obj[key];
// Forward the obvious cases
if (key in obj && !obj.hasOwnProperty(key)) return obj[key];
// Array cloning
var tree = inTree.slice(0);
var value;
var done = false;
tree.push(key); // Add self to descendants
if (tree.length === 1) {
// Key is parent
client.get(key, function(err, reply) {
done = true;
if (err) throw err;
value = JSON.parse(reply);
});
} else {
var parent = tree.shift();
client.get(parent, function(err, reply) {
done = true;
if (err) throw err;
value = JSON.parse(reply);
value = tree.reduce(
(x, d) => d in x ? x[d] : undefined,
value
);
tree.unshift(parent); // Fix the array
});
}
while (!done) deasync.runLoopOnce();
if (value === undefined) return undefined;
try {
return _Rebridge(client, value, tree);
} catch (e) {
return value;
}
},
set: function(obj, key, val) {
// Array cloning
var tree = inTree.slice(0);
var value;
var done = false;
tree.push(key); // Add self to descendants
if (tree.length === 1) {
client.set(key, JSON.stringify(val), function(err) {
done = true;
if (err) throw err;
value = val;
});
} else {
var parent = tree.shift();
client.get(parent, function(err, reply) {
if (err) throw err;
value = JSON.parse(reply);
editTree(value, tree, val);
client.set(
parent,
JSON.stringify(value),
function(err) {
done = true;
if (err) throw err;
}
);
tree.unshift(parent); // Fix the array
});
}
while (!done) deasync.runLoopOnce();
try {
return _Rebridge(client, value, tree);
} catch (e) {
return value;
}
},
deleteProperty: function(obj, key, val) {
// Array cloning
var tree = inTree.slice(0);
var value;
var done = false;
tree.push(key); // Add self to descendants
if (tree.length === 1) {
client.del(key, function(err) {
done = true;
if (err) throw err;
value = val;
});
} else {
var parent = tree.shift();
client.get(parent, function(err, reply) {
if (err) throw err;
value = JSON.parse(reply);
deleteFromTree(value, tree);
client.set(
parent,
JSON.stringify(value),
function(err) {
done = true;
if (err) throw err;
}
);
tree.unshift(parent); // Fix the array
});
}
while (!done) deasync.runLoopOnce();
try {
return _Rebridge(client, value, tree);
} catch (e) {
return value;
}
}
}
);
}
function editTree(tree, path, newValue) {
if (path.length === 0) return newValue;
let key = path.shift();
if (tree[key])
tree[key] = editTree(tree[key], path, newValue);
else
tree[key] = newValue;
return tree;
}
function deleteFromTree(tree, path) {
let key = path.shift();
if (tree[key] && path.length > 0)
tree[key] = deleteFromTree(tree[key], path);
else
delete tree[key];
return tree;
}
|
JavaScript
| 0 |
@@ -2388,100 +2388,20 @@
%09%09%09%09
-try %7B%0A%09%09%09%09%09return _Rebridge(client, value, tree);%0A%09%09%09%09%7D catch (e) %7B%0A%09%09%09%09%09return value;%0A%09%09%09%09%7D
+return true;
%0A%09%09%09
|
afa9d03b029b51101af8340151a2b408932d02d4
|
Replace native Promises with Bluebird Promises
|
index.js
|
index.js
|
require('babel-core/register');
require('./server.js');
|
JavaScript
| 0.999999 |
@@ -1,16 +1,55 @@
+global.Promise = require('bluebird');%0A%0A
require('babel-c
|
cdbdcd6b95983599b223b5e9ff21e9399e18add8
|
Remove obsolete comment.
|
webpack/devserver.js
|
webpack/devserver.js
|
/* @flow weak */
"use strict"
var gutil = require('gulp-util')
var path = require('path')
var webpack = require('webpack')
var webpackDevServer = require('webpack-dev-server')
module.exports = function(webpackConfig) {
return function(callback) {
// It seems webpackDevServer doesn't emit errors, so we can't use gulp-notify.
// Webpack callback does not work with webpackDevServer as well.
new webpackDevServer(webpack(webpackConfig), {
contentBase: 'http://localhost:8888',
hot: true,
publicPath: webpackConfig.output.publicPath,
// Unfortunately quiet swallows everything even error so it can't be used.
quiet: false,
// No info filters only initial compilation it seems.
noInfo: true,
// Remove console.log mess during watch.
stats: {
assets: false,
colors: true,
version: false,
hash: false,
timings: false,
chunks: false,
chunkModules: false
}
}).listen(8888, 'localhost', function(err) {
// Callback is called only once, can't be used to catch compilation errors.
if (err)
throw new gutil.PluginError('webpack-dev-server', err)
gutil.log('[webpack-dev-server]', 'localhost:8888/build/client.js')
callback()
})
}
}
|
JavaScript
| 0 |
@@ -249,160 +249,8 @@
) %7B%0A
- // It seems webpackDevServer doesn't emit errors, so we can't use gulp-notify.%0A // Webpack callback does not work with webpackDevServer as well.%0A
|
ab77dc7791728414c75545a05cae6f22321bac3c
|
throw a type error if `bubbleErrors` option is not Boolean
|
index.js
|
index.js
|
var stream = require("readable-stream");
var duplex2 = module.exports = function duplex2(options, writable, readable) {
return new DuplexWrapper(options, writable, readable);
};
var DuplexWrapper = exports.DuplexWrapper = function DuplexWrapper(options, writable, readable) {
if (typeof readable === "undefined") {
readable = writable;
writable = options;
options = null;
}
options = options || {};
stream.Duplex.call(this, options);
this._bubbleErrors = (typeof options.bubbleErrors === "undefined") || !!options.bubbleErrors;
this._shouldRead = false;
if (typeof readable.read !== 'function')
readable = stream.Readable().wrap(readable)
this._writable = writable;
this._readable = readable;
var self = this;
writable.once("finish", function() {
self.end();
});
this.once("finish", function() {
writable.end();
});
readable.on("readable", function() {
self._forwardRead();
});
readable.once("end", function() {
return self.push(null);
});
if (this._bubbleErrors) {
writable.on("error", function(err) {
return self.emit("error", err);
});
readable.on("error", function(err) {
return self.emit("error", err);
});
}
};
DuplexWrapper.prototype = Object.create(stream.Duplex.prototype, {constructor: {value: DuplexWrapper}});
DuplexWrapper.prototype._write = function _write(input, encoding, done) {
this._writable.write(input, encoding, done);
};
DuplexWrapper.prototype._read = function _read() {
if (this._shouldRead) return;
this._shouldRead = true;
this._forwardRead();
};
DuplexWrapper.prototype._forwardRead = function _forwardRead() {
if (!this._shouldRead) return;
var data;
var shouldRead = true;
while ((data = this._readable.read()) !== null) {
shouldRead = false;
this.push(data);
}
this._shouldRead = shouldRead;
};
|
JavaScript
| 0.012111 |
@@ -1,12 +1,27 @@
+%22use strict%22;%0A%0A
var stream =
@@ -50,16 +50,77 @@
eam%22);%0A%0A
+var Duplex = stream.Duplex;%0Avar Readable = stream.Readable;%0A%0A
var dupl
@@ -351,31 +351,24 @@
le) %7B%0A if (
-typeof
readable ===
@@ -364,25 +364,24 @@
eadable ===
-%22
undefined%22)
@@ -377,17 +377,16 @@
ndefined
-%22
) %7B%0A
@@ -448,19 +448,25 @@
s =
-null
+%7B%7D
;%0A %7D
-%0A%0A
+ else %7B%0A
op
@@ -492,18 +492,15 @@
%7B%7D;%0A
-%0A stream.
+ %7D%0A%0A
Dupl
@@ -530,28 +530,98 @@
%0A%0A
-this._bubbleErrors =
+if (options.bubbleErrors === undefined) %7B%0A this._bubbleErrors = true;%0A %7D else %7B%0A if
(ty
@@ -650,30 +650,238 @@
ors
+!
==
-= %22undefined%22) %7C%7C !!
+ %22boolean%22) %7B%0A throw new TypeError(%0A String(options.bubbleErrors) +%0A %22 is not a Boolean value. %60bubbleErrors%60 option of duplexer2 must be Boolean (%60true%60 by default).%22%0A );%0A %7D%0A this._bubbleErrors =
opti
@@ -898,16 +898,20 @@
Errors;%0A
+ %7D%0A
this._
@@ -973,16 +973,18 @@
nction')
+ %7B
%0A rea
@@ -983,39 +983,37 @@
%0A readable =
-stream.
+(new
Readable().wrap(
@@ -1006,16 +1006,17 @@
adable()
+)
.wrap(re
@@ -1022,16 +1022,21 @@
eadable)
+;%0A %7D
%0A%0A this
@@ -1881,32 +1881,38 @@
his._shouldRead)
+ %7B%0A
return;%0A this.
@@ -1904,16 +1904,21 @@
return;%0A
+ %7D%0A%0A
this._
@@ -2052,16 +2052,22 @@
uldRead)
+ %7B%0A
return;
@@ -2067,16 +2067,21 @@
return;%0A
+ %7D%0A%0A
var da
@@ -2082,16 +2082,40 @@
var data
+ = this._readable.read()
;%0A var
@@ -2145,39 +2145,13 @@
ile
-(
(data
- = this._readable.read())
!==
@@ -2204,16 +2204,50 @@
(data);%0A
+ data = this._readable.read();%0A
%7D%0A th
|
d315a21d8b9b3874b1d52e8e2e0d579a82f2b708
|
Fix crashing on viewing, add proper db gets
|
index.js
|
index.js
|
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var databaseUrl = "data";
var collections = ["publicChores", "privateChores", "users"];
var db = require("mongojs").connect(databaseUrl, collections);
app.use(require('express').static(__dirname +'/public'));
app.get('/', function(req, res){
res.sendfile('index.html');
});
io.on('connection', function(socket){
console.log('user connection');
socket.on('login', function(user, pass){login(user, pass);});
socket.on('viewJobs', function(isPublic){viewJobs(isPublic);});
socket.on('viewLeaderboard', function(){viewLeaderboard();});
socket.on('movePrivate', function(job, bounty){movePrivate(job, bounty);});
socket.on('submitBidJob', function(name, description, points){submitBidJob(name, description, points);});
socket.on('transferPoints', function(user, points){transferPoints(user, points);});
socket.on('bid', function(job, points){bid(job, points);});
socket.on('complete', function(job){complete(job);});
socket.on('verify', function(job){verify(job);});
});
//TODO: THESE FUNCTIONS
//use the following to send things back to the index
//io.emit('<functionname>', '<information>');
function login(user, pass) {
//login/register [add user to db]
console.log('login ' + user + ',' + pass);
}
function viewJobs(isPublic) {
//view jobs (special | chores) [get jobs from db]
io.emit('clearList');
io.emit('setSection', isPublic ? 'Public' : 'Private');
//Determines which collection to look at
var p;
if (isPublic)
p = db.publicChores[0];
else
p = db.privateChores[0];
//Displays at most 4 of either job.
var i;
for (i = 0; p.hasNext() && i < 4; i++) {
io.emit('addList', p.next()); //TODO: Strip JSON
p = p.next();
}
console.log('view jobs public/private ' + isPublic);
}
function viewLeaderboard() {
//view leaderboard [get users from db]
io.emit('clearList');
io.emit('setSection', 'Leaderboard');
var i;
while (db.users.hasNext) {//i < users.length
io.emit('addList', 'ayy lmao x' + i);//user: points
}
console.log('view leaderboard');
}
function movePrivate(job, bounty) {
//move chores to special at a cost of points [set job.isSpecial, job.points, user.points]
console.log('move private ' + job + ',' + bounty);
}
function submitBidJob(name, description, points) {
//submit special jobs (?) [add special job to db]
console.log('submit bid job ' + name + ',' + description + ',' + points);
}
function transferPoints(user, points) {
//transfer points [set user.points, target.points]
//remove own points [set user.points]
//allow transfer to "null" user for point removal
console.log('transfer ' + points + ' points to ' + user);
}
function bid(job, points) {
//bid to special job
console.log('bid ' + points + ' points to ' + job);
}
function complete(job) {
//complete special jobs [set job.isVerifying]
console.log('complete ' + job);
}
function verify(job) {
//verify that a user did a special job [set job.isDone, job.isVerifying]
console.log('verify ' + job);
}
//function nudge(user) {
//nudge another user [set target.nudges, user.points]
//}
http.listen(3000, function(){
console.log('listening on *:3000');
});
|
JavaScript
| 0 |
@@ -361,21 +361,20 @@
ndfile('
-index
+list
.html');
@@ -1482,72 +1482,25 @@
');%0A
-%0A%09//Determines which collection to look at%0A%09var p;%0A%09if (
+%09var p =
isPublic
)%0A%09%09
@@ -1499,15 +1499,10 @@
blic
-)%0A%09%09p =
+ ?
db.
@@ -1517,24 +1517,10 @@
ores
-%5B0%5D;%0A%09else%0A%09%09p =
+ :
db.
@@ -1536,101 +1536,191 @@
ores
-%5B0%5D;%0A%0A%09//Displays at most 4 of either job.%0A%09var i;%0A%09for (i = 0; p.hasNext() && i %3C 4; i++
+;%0A%09p.find(%7B%7D, function(err, chores) %7B%0A%09%09if( err %7C%7C !chores) %7B%0A%09%09%09io.emit('addList', %22No chores found%22);%0A%09%09%09console.log(%22No chores found%22);%0A%09%09%7D else chores.forEach( function(chore
) %7B%0A
+%09
%09%09io
@@ -1740,56 +1740,113 @@
t',
-p.next()); //TODO: Strip JSON%0A%09%09p = p.next();%0A%09%7D
+chore.name + ': ' + chore.description);%0A%09%09%09console.log(chore.name + ': ' + chore.description);%0A%09%09%7D);%0A%09%7D);
%0A%09co
@@ -2035,117 +2035,301 @@
);%0A%09
-var i;%0A%09while (db.users.hasNext) %7B//i %3C users.length%0A%09%09io.emit('addList', 'ayy lmao x' + i);//user: points
+db.users.find(%7B%7D, function(err, users) %7B%0A%09%09if( err %7C%7C !users) %7B%0A%09%09%09io.emit('addList', %22No users found%22);%0A%09%09%09console.log(%22No users found%22);%0A%09%09%7D else users.forEach( function(user) %7B%0A%09%09%09io.emit('addList', user.name + ': ' + user.points);%0A%09%09%09console.log(user.name + ': ' + user.points);%0A%09%09%7D);
%0A%09%7D
+);
%0A%09co
|
9a23afadf30c4626b89099d102a7ec7d2714e3f0
|
remove debug logging
|
webui/src/media_size_controller.js
|
webui/src/media_size_controller.js
|
import mapValues from 'lodash/mapValues'
import objectValues from 'lodash/values'
import SettingsModel, { FontSize, MediaSize, MediaSizeIndex } from './settings_model'
const MediaSizes = Object.freeze({
small: 0,
medium: 29,
large: 43,
});
const FontScale = Object.freeze({
small: 0.875,
medium: 1.0,
large: 1.125,
});
function queryMinWidth(em)
{
return window.matchMedia(`(min-width: ${em}em)`);
}
class MediaSizeQuery
{
constructor(scale)
{
this.entries = [];
for (let size of Object.keys(MediaSize))
{
const query = queryMinWidth(MediaSizes[size] * scale);
this.entries[MediaSizeIndex[size]] = { size, query };
}
this.entries.reverse();
}
getMediaSize()
{
for (let entry of this.entries)
{
if (entry.query.matches)
return entry.size;
}
throw Error("Internal error: unable to select any media size");
}
addListener(callback)
{
for (let entry of this.entries)
entry.query.addListener(callback);
}
removeListener(callback)
{
for (let entry of this.entries)
entry.query.removeListener(callback);
}
}
export default class MediaSizeController
{
constructor(settingsModel)
{
this.settingsModel = settingsModel;
this.mediaQueries = mapValues(FontScale, scale => new MediaSizeQuery(scale));
this.update = this.update.bind(this);
}
start()
{
this.settingsModel.on('fontSizeChange', this.update);
for (let query of objectValues(this.mediaQueries))
query.addListener(this.update);
this.update();
}
update()
{
const query = this.mediaQueries[this.settingsModel.fontSize];
console.log(this.settingsModel.mediaSize);
console.log(query.getMediaSize());
this.settingsModel.mediaSize = query.getMediaSize();
}
}
|
JavaScript
| 0.000002 |
@@ -1818,103 +1818,8 @@
%5D;%0A%0A
- console.log(this.settingsModel.mediaSize);%0A console.log(query.getMediaSize());%0A%0A
|
c47fe3734bc19be10ec557adf124afc1f993b552
|
Add callback wrapper test
|
test/add-subtask-spec.js
|
test/add-subtask-spec.js
|
var _ = require( 'lodash' );
var should = require( 'should' );
var sinon = require( 'sinon' );
var pequire = require( 'proxyquire' );
var tutil = require( './test-util' );
var HAPPY_PROXY_DEPS = {
path: { dirname: _.noop },
'./hub-util': { isValidHubFile: function (){ return true } }
};
var getAddSubtask = function ( proxyDeps ) {
return pequire( '../lib/add-subtask', _.assign( {}, HAPPY_PROXY_DEPS, proxyDeps ) );
};
describe.only( 'add-subtask', function () {
it( 'errors if subfile is not a valid Gulp Hub file', function () {
var addSubtask = getAddSubtask( {
'./hub-util': { isValidHubFile: function () { return false } }
} );
addSubtask.should.throw( '`subfile` must be a valid Gulp Hub file object.' );
} );
it( 'errors if the task registry is not a plain object', function () {
var addSubtask = getAddSubtask();
tutil.getTypeExamples( _.isPlainObject ).forEach( function ( type ) {
addSubtask.bind( null, undefined, type )
.should.throw('`tasks` must be a plain object.');
} );
} );
it( 'errors if name is not a string', function () {
var addSubtask = getAddSubtask();
tutil.getTypeExamples( _.isString ).forEach( function ( type ) {
addSubtask.bind( null, undefined, {}, type )
.should.throw('`name` must be a string.');
} );
} );
it( 'errors if param1 is not an array or function', function () {
var addSubtask = getAddSubtask();
var excludeFunc = function ( el ) {
return _.isArray( el ) || _.isFunction( el );
};
tutil.getTypeExamples( excludeFunc ).forEach( function ( type ) {
addSubtask.bind( null, undefined, {}, 'string', type )
.should.throw('`param1` must be an array or function.');
} );
} );
it( 'errors if param2 is not a or function or undefined', function () {
var addSubtask = getAddSubtask();
var excludeFunc = function ( el ) {
return _.isFunction( el ) || _.isUndefined( el );
};
tutil.getTypeExamples( excludeFunc ).forEach( function ( type ) {
addSubtask.bind( null, undefined, {}, 'string', [], type )
.should.throw('`param2` must be a function or undefined.');
} );
} );
it( 'registers a master task with `name` if it doesn\'t already exist', function () {
var testTasks = {};
var addSubtask = getAddSubtask();
addSubtask( { uniqueName: 'unique-name' }, testTasks, 'task-name', [] );
var taskObj = testTasks[ 'task-name' ];
_.isPlainObject( taskObj ).should.be.true;
taskObj.name = 'task-name';
_.isArray( taskObj.subtasks ).should.be.true;
} );
it( 'registers the subfile\'s tasks prefixed with its unique name under the master task name', function () {
var testTasks = {};
var addSubtask = getAddSubtask();
addSubtask( { uniqueName: 'unique-name' }, testTasks, 'task-name', [] );
testTasks[ 'task-name' ].subtasks[ 0 ].name.should.eql( 'unique-name-task-name' );
} );
it( 'prefixes the subfile\'s task dependencies with its unique name', function () {
var testTasks = {};
var addSubtask = getAddSubtask();
addSubtask(
{ uniqueName: 'subfile-unique-name' }, testTasks, 'task-name',
[ 'task-dep-1', 'task-dep-2' ]
);
var subtaskDeps = testTasks[ 'task-name' ].subtasks[ 0 ].param1;
subtaskDeps[ 0 ].should.eql( 'subfile-unique-name-task-dep-1' );
subtaskDeps[ 1 ].should.eql( 'subfile-unique-name-task-dep-2' );
} );
it( 'changes the working directory to the subfile\'s dirname' );
it( 'executes the subfile task\'s callback' );
it( 'registers each subfile task in the task registry' );
} );
|
JavaScript
| 0.000001 |
@@ -3741,64 +3741,234 @@
t( '
-changes the working directory to the subfile%5C's dirname'
+wraps the subtask%5C's callbacks in a function that corrects the working directory', function () %7B%0A var testTasks = %7B%7D;%0A var callbackSpy = sinon.spy();%0A var dirnameSpy = sinon.spy( function () %7B return '.' %7D
);%0A
@@ -3976,60 +3976,292 @@
+
-it( 'executes the subfile task%5C's callback'
+ var addSubtask = getAddSubtask( %7B path: %7B dirname: dirnameSpy %7D %7D );%0A addSubtask(%0A %7B uniqueName: 'subfile-unique-name', absolutePath: '.' %7D,%0A testTasks, 'task-name', callbackSpy%0A );%0A testTasks%5B 'task-name' %5D.subtasks%5B 0 %5D.param1(
);%0A%0A
it(
@@ -4260,62 +4260,577 @@
+
-it( 'registers each subfile task in the task registry'
+ dirnameSpy.calledOnce.should.be.true;%0A dirnameSpy.calledWith( '.' ).should.be.true;%0A callbackSpy.calledOnce.should.be.true;%0A%0A dirnameSpy.reset();%0A callbackSpy.reset();%0A%0A addSubtask(%0A %7B uniqueName: 'subfile-unique-name-2', absolutePath: '.' %7D,%0A testTasks, 'task-name-2', %5B%5D, callbackSpy%0A );%0A testTasks%5B 'task-name-2' %5D.subtasks%5B 0 %5D.param2();%0A%0A dirnameSpy.calledOnce.should.be.true;%0A dirnameSpy.calledWith( '.' ).should.be.true;%0A callbackSpy.calledOnce.should.be.true;%0A %7D
);%0A
|
fa67204eb8e3e5e2b5b1e018cf9a43809774d47f
|
Fix incorrect paths
|
index.js
|
index.js
|
/* jshint node: true */
'use strict';
module.exports = {
name: 'ember-trix-editor',
included: function (app) {
this._super.included(app);
app.import(app.vendorDirectory + '/trix.js');
app.import(app.vendorDirectory + '/trix.css');
}
};
|
JavaScript
| 0.999979 |
@@ -157,39 +157,23 @@
.import(
-app.
+'
vendor
-Directory + '
/trix.js
@@ -195,31 +195,15 @@
ort(
-app.
+'
vendor
-Directory + '
/tri
|
2eba0709215996883f953b45c4ae844f2b91e3d2
|
Add missing unit test for auth_hdr.
|
test/auth_header-test.js
|
test/auth_header-test.js
|
var auth_hdr = require('../lib/auth_header')
describe('Parsing Auth Header field-value', function() {
it('Should handle single space separated values', function() {
var res = auth_hdr.parse("SCHEME VALUE");
expect(res).to.deep.equal({scheme: "SCHEME", value: "VALUE"});
});
it('Should handle CRLF separator', function() {
var res = auth_hdr.parse("SCHEME\nVALUE");
expect(res).to.deep.equal({scheme: "SCHEME", value: "VALUE"});
});
it('Should handle malformed authentication headers with no scheme', function() {
var res = auth_hdr.parse("malformed");
expect(res).to.not.be.ok;
});
});
|
JavaScript
| 0 |
@@ -656,12 +656,169 @@
%7D);%0A%0A%0A
+ it('Should return null when the auth header is not a string', function() %7B%0A var res = auth_hdr.parse(%7B%7D);%0A expect(res).to.be.null;%0A %7D);%0A
%7D);%0A
|
2f66115ad0a6b082e9771b947523457cc228cc4d
|
add fs require for linux
|
index.js
|
index.js
|
var ReadStream = require('tty').ReadStream;
var _fs = process.binding('fs');
var _constants = process.binding('constants');
var _TTY = process.binding('tty_wrap').TTY;
module.exports = openTTY;
function openTTY() {
var fd;
if (process.platform === 'win32') {
fd = _fs.open('CONIN$', _constants.O_RDWR, 438);
} else {
fd = fs.openSync('/dev/tty', 'r');
}
if (!fd) {
throw new Error('Cannot access console input buffer');
}
var tty = new _TTY(fd, true);
tty.setRawMode(true);
if (process.stdin.isTTY) {
return process.stdin;
} else {
return new ReadStream(fd);
}
}
|
JavaScript
| 0.000001 |
@@ -1,12 +1,36 @@
+var fs = require('fs');%0A
var ReadStre
|
dfa6917606eea85337b1f9a51451715df122f16a
|
update for swf.create,用例有编译错误
|
test/baidu/swf/create.js
|
test/baidu/swf/create.js
|
module("baidu.swf.create");
// 1、normal
test("test ver", function() {
stop();
var div = document.body.appendChild(document.createElement('div'));
div.id = "div_id";
baidu.swf.create({
id : 'test1',
url : "short1.swf",
width:'100',
height:'100',
ver:'6.0.0'
}, div);
ok(true, "flash对象创建成功");
setTimeout(function(){
document.body.removeChild(div);
},2000);
start();
});
// 2、 There is no flash player or the version of existed flash is lower
// than
// needed&&errorMessage
test("ver errorMessage", function() {
stop();
var div = document.body.appendChild(document.createElement('div'));
baidu.swf.create({
id : 'test1',
url : "short1.swf",
ver:'11.0.0',
width:'200',
height:'100',
errorMessage:"There is no flash player or the version is too low"
}, div);
equal(div.innerHTML,"There is no flash player or the version is too low","test option errorMessage successfully");
setTimeout(function(){
document.body.removeChild(div);
},2000);
start();
});
// 3、There is no flash player or the version of existed flash is lower
// than
// needed&&!errorMessage
test("ver no errorMessage", function() {
stop();
var div = document.body.appendChild(document.createElement('div'));
div.id="div_id";
baidu.swf.create({
id : 'test1',
url : "short1.swf",
width:'100',
height:'100',
ver:'11.0.0',
}, 'div_id');
equal(div.innerHTML,'',"flash 对象没有创建成功");
setTimeout(function(){
document.body.removeChild(div);
},2000);
start();
});
// 4、There is no container(target)
// test("options&&!container", function() {
// stop();
// baidu.swf.create({
// id : 'test1',
// url : "short1.swf",
// width : 100,
// height : 100
// });
// setTimeout(function(){
// document.body.innerHTML="";
// },200);
// start();
// });
|
JavaScript
| 0.000001 |
@@ -310,24 +310,54 @@
ash%E5%AF%B9%E8%B1%A1%E5%88%9B%E5%BB%BA%E6%88%90%E5%8A%9F%22);
+//%E8%BF%99%E4%B8%AA%E8%B2%8C%E4%BC%BC%E4%B9%9F%E6%B2%A1%E6%9C%89%E6%A0%A1%E9%AA%8C%E3%80%82%E3%80%82%E5%9B%9E%E5%A4%B4%E7%A1%AE%E8%AE%A4%EF%BC%8C%E7%A1%AE%E8%AE%A4%E5%AE%8C%E6%AF%95%E8%AF%B7%E7%A7%BB%E9%99%A4%E6%AD%A4%E5%A4%84%E7%9A%84%E8%AF%B4%E6%98%8E
%0D%0A%09setTimeou
@@ -1410,17 +1410,37 @@
'11.0.0'
-,
+//,%E6%9D%A8%E6%90%8F%E5%A4%84%E7%90%86%EF%BC%8C%E6%AD%A4%E5%A4%84%E5%A4%9A%E4%B8%80%E4%B8%AA,%EF%BC%8C%E9%BA%BB%E7%83%A6%E6%B5%B7%E5%85%88%E6%B3%A8%E6%84%8F
%0D%0A%09%7D, 'd
|
7c158605187303ed7476a4ee48ed0978c043c12c
|
Update `cursorTo` to use `SEP` constant (#28)
|
index.js
|
index.js
|
const ESC = '\u001B[';
const OSC = '\u001B]';
const BEL = '\u0007';
const SEP = ';';
const isTerminalApp = process.env.TERM_PROGRAM === 'Apple_Terminal';
const ansiEscapes = {};
ansiEscapes.cursorTo = (x, y) => {
if (typeof x !== 'number') {
throw new TypeError('The `x` argument is required');
}
if (typeof y !== 'number') {
return ESC + (x + 1) + 'G';
}
return ESC + (y + 1) + ';' + (x + 1) + 'H';
};
ansiEscapes.cursorMove = (x, y) => {
if (typeof x !== 'number') {
throw new TypeError('The `x` argument is required');
}
let returnValue = '';
if (x < 0) {
returnValue += ESC + (-x) + 'D';
} else if (x > 0) {
returnValue += ESC + x + 'C';
}
if (y < 0) {
returnValue += ESC + (-y) + 'A';
} else if (y > 0) {
returnValue += ESC + y + 'B';
}
return returnValue;
};
ansiEscapes.cursorUp = (count = 1) => ESC + count + 'A';
ansiEscapes.cursorDown = (count = 1) => ESC + count + 'B';
ansiEscapes.cursorForward = (count = 1) => ESC + count + 'C';
ansiEscapes.cursorBackward = (count = 1) => ESC + count + 'D';
ansiEscapes.cursorLeft = ESC + 'G';
ansiEscapes.cursorSavePosition = isTerminalApp ? '\u001B7' : ESC + 's';
ansiEscapes.cursorRestorePosition = isTerminalApp ? '\u001B8' : ESC + 'u';
ansiEscapes.cursorGetPosition = ESC + '6n';
ansiEscapes.cursorNextLine = ESC + 'E';
ansiEscapes.cursorPrevLine = ESC + 'F';
ansiEscapes.cursorHide = ESC + '?25l';
ansiEscapes.cursorShow = ESC + '?25h';
ansiEscapes.eraseLines = count => {
let clear = '';
for (let i = 0; i < count; i++) {
clear += ansiEscapes.eraseLine + (i < count - 1 ? ansiEscapes.cursorUp() : '');
}
if (count) {
clear += ansiEscapes.cursorLeft;
}
return clear;
};
ansiEscapes.eraseEndLine = ESC + 'K';
ansiEscapes.eraseStartLine = ESC + '1K';
ansiEscapes.eraseLine = ESC + '2K';
ansiEscapes.eraseDown = ESC + 'J';
ansiEscapes.eraseUp = ESC + '1J';
ansiEscapes.eraseScreen = ESC + '2J';
ansiEscapes.scrollUp = ESC + 'S';
ansiEscapes.scrollDown = ESC + 'T';
ansiEscapes.clearScreen = '\u001Bc';
ansiEscapes.clearTerminal = process.platform === 'win32' ?
`${ansiEscapes.eraseScreen}${ESC}0f` :
// 1. Erases the screen (Only done in case `2` is not supported)
// 2. Erases the whole screen including scrollback buffer
// 3. Moves cursor to the top-left position
// More info: https://www.real-world-systems.com/docs/ANSIcode.html
`${ansiEscapes.eraseScreen}${ESC}3J${ESC}H`;
ansiEscapes.beep = BEL;
ansiEscapes.link = (text, url) => {
return [
OSC,
'8',
SEP,
SEP,
url,
BEL,
text,
OSC,
'8',
SEP,
SEP,
BEL
].join('');
};
ansiEscapes.image = (buffer, options = {}) => {
let returnValue = `${OSC}1337;File=inline=1`;
if (options.width) {
returnValue += `;width=${options.width}`;
}
if (options.height) {
returnValue += `;height=${options.height}`;
}
if (options.preserveAspectRatio === false) {
returnValue += ';preserveAspectRatio=0';
}
return returnValue + ':' + buffer.toString('base64') + BEL;
};
ansiEscapes.iTerm = {
setCwd: (cwd = process.cwd()) => `${OSC}50;CurrentDir=${cwd}${BEL}`,
annotation: (message, options = {}) => {
let returnValue = `${OSC}1337;`;
const hasX = typeof options.x !== 'undefined';
const hasY = typeof options.y !== 'undefined';
if ((hasX || hasY) && !(hasX && hasY && typeof options.length !== 'undefined')) {
throw new Error('`x`, `y` and `length` must be defined when `x` or `y` is defined');
}
message = message.replace(/\|/g, '');
returnValue += options.isHidden ? 'AddHiddenAnnotation=' : 'AddAnnotation=';
if (options.length > 0) {
returnValue +=
(hasX ?
[message, options.length, options.x, options.y] :
[options.length, message]).join('|');
} else {
returnValue += message;
}
return returnValue + BEL;
}
};
export default ansiEscapes;
|
JavaScript
| 0 |
@@ -385,19 +385,19 @@
+ 1) +
-';'
+SEP
+ (x +
|
9bf4cfce1bab6dbe2e9055f48b790e459afb9a0d
|
remove usage of replace at city names
|
index.js
|
index.js
|
const request = require('request');
const APP_ID = '59f807307ebf813df0c1dd3647242945';
const BASE_URL = 'http://api.openweathermap.org/data/2.5/weather?q=';
const getRequestOptions = city => ({
url: `${BASE_URL}${city}&APPID=${APP_ID}`,
headers: {
'User-Agent': 'agentWeatherrApi'
}
})
const getWordWithoutSomething = (str, find, replace) =>
str.replace(new RegExp(find, 'g'), replace);
// Get maximum temperature
exports.getMaximumTemp = (city, callback) => {
city = getWordWithoutSomething(city.trim(), ' ', '-');
const options = getRequestOptions(city)
request(options, (error, response, body) => {
let data = JSON.parse(body);
if(data['message'] != undefined) {
return callback('City not found');
} else {
return callback(null, parseInt(data['main']['temp_max'] - 273));
}
});
};
// Get minimum temperature
exports.getMinimumTemp = (city, callback) => {
city = getWordWithoutSomething(city.trim(), ' ', '-');
const options = getRequestOptions(city)
request(options, (error, response, body) => {
let data = JSON.parse(body);
if(data['message'] != undefined) {
return callback('City not found');
} else {
return callback(null, parseInt(data['main']['temp_min'] - 273));
}
});
};
// Get actual temperature
exports.getActualTemp = (city, callback) => {
city = getWordWithoutSomething(city.trim(), ' ', '-');
const options = getRequestOptions(city)
request(options, (error, response, body) => {
let data = JSON.parse(body);
if(data['message'] != undefined) {
return callback('City not found');
} else {
return callback(null, parseInt(data['main']['temp'] - 273));
}
});
};
// Get climate description
exports.getClimateDescription = (city, callback) => {
city = getWordWithoutSomething(city.trim(), ' ', '-');
const options = getRequestOptions(city)
request(options, (error, response, body) => {
let data = JSON.parse(body);
if(data['message'] != undefined) {
return callback('City not found');
} else {
return callback(null, data['weather'][0]['description']);
}
});
};
// Get wind speed
exports.getWindSpeed = (city, callback) => {
city = getWordWithoutSomething(city.trim(), ' ', '-');
const options = getRequestOptions(city)
request(options, (error, response, body) => {
let data = JSON.parse(body);
if(data['message'] != undefined) {
return callback('City not found');
} else {
return callback(null, data['wind']['speed']);
}
});
};
|
JavaScript
| 0.002747 |
@@ -294,111 +294,8 @@
%7D%0A%7D)
-%0A%0Aconst getWordWithoutSomething = (str, find, replace) =%3E%0A str.replace(new RegExp(find, 'g'), replace)
;%0A%0A/
@@ -371,66 +371,8 @@
%3E %7B%0A
- city = getWordWithoutSomething(city.trim(), ' ', '-');%0A%0A
co
@@ -399,33 +399,41 @@
uestOptions(city
-)
+.trim());
%0A%0A request(opti
@@ -758,66 +758,8 @@
%3E %7B%0A
- city = getWordWithoutSomething(city.trim(), ' ', '-');%0A%0A
co
@@ -786,33 +786,41 @@
uestOptions(city
-)
+.trim());
%0A%0A request(opti
@@ -1144,66 +1144,8 @@
%3E %7B%0A
- city = getWordWithoutSomething(city.trim(), ' ', '-');%0A%0A
co
@@ -1172,33 +1172,41 @@
uestOptions(city
-)
+.trim());
%0A%0A request(opti
@@ -1534,66 +1534,8 @@
%3E %7B%0A
- city = getWordWithoutSomething(city.trim(), ' ', '-');%0A%0A
co
@@ -1562,33 +1562,41 @@
uestOptions(city
-)
+.trim());
%0A%0A request(opti
@@ -1903,66 +1903,8 @@
%3E %7B%0A
- city = getWordWithoutSomething(city.trim(), ' ', '-');%0A%0A
co
@@ -1939,17 +1939,25 @@
ons(city
-)
+.trim());
%0A%0A requ
|
043444775be67ef475defd117c72d3cd530cabf2
|
change default mysql host to match docker-compose
|
test/dbconfig.example.js
|
test/dbconfig.example.js
|
'use strict'
module.exports = {
name: 'senecatest',
host: 'localhost',
user: 'senecatest',
password: 'senecatest',
port: 3306
}
|
JavaScript
| 0.000001 |
@@ -61,17 +61,13 @@
t: '
-localhost
+mysql
',%0A
|
4dd0b830c489df352236b6e6974701a94706f915
|
Reset debug preference when resetting VTR options
|
index.js
|
index.js
|
/* ***** BEGIN LICENSE BLOCK *****
*
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* ***** END LICENSE BLOCK ***** */
"use strict";
// SDK
var simplePrefs = require("sdk/simple-prefs");
var preferences = simplePrefs.prefs;
var preferencesService = require("sdk/preferences/service");
var windows = require("sdk/windows");
var windowUtils = require("sdk/window/utils");
var hotkey = require("sdk/hotkeys").Hotkey;
var { viewFor } = require("sdk/view/core");
var { Services } = require("resource://gre/modules/Services.jsm");
// Modules
var { unload } = require("./lib/unload.js");
var { VerticalTabsReloaded } = require("./lib/verticaltabs.js");
let packageJSON = require("./package.json");
const PREF_BRANCH = "extensions."+packageJSON['preferences-branch']+".";
// Reset the preferences
function setDefaultPrefs()
{
for (let aPreference of preferencesService.keys(PREF_BRANCH))
{
preferencesService.reset(aPreference);
}
}
simplePrefs.on("setDefaultPrefs", setDefaultPrefs);
// Toggle function of browser.tabs.drawInTitlebar for preference page
function toggleDrawInTitlebar() {
if(preferencesService.get("browser.tabs.drawInTitlebar", true))
{
preferencesService.set("browser.tabs.drawInTitlebar", false);
}
else
{
preferencesService.set("browser.tabs.drawInTitlebar", true);
}
}
simplePrefs.on("toggleDrawInTitlebar", toggleDrawInTitlebar);
unload(function() {
simplePrefs.off("setDefaultPrefs", setDefaultPrefs);
simplePrefs.off("toggleDrawInTitlebar", toggleDrawInTitlebar);
});
// Hotkeys
var GLOBAL_SCOPE = this;
function initHotkeys() {
var objectScope = GLOBAL_SCOPE;
let toggleKey = preferences["toggleDisplayHotkey"];
let windowUtilsx = windowUtils;
GLOBAL_SCOPE.vtToggleDisplayHotkey = hotkey({
combo: toggleKey,
onPress: function() {
let windowID = windowUtilsx.getOuterId(windowUtilsx.getToplevelWindow(windowUtilsx.getFocusedWindow()));
objectScope["vt"+windowID].toggleDisplayState();
}
});
}
function destroyHotkey() {
GLOBAL_SCOPE.vtToggleDisplayHotkey.destroy();
}
function changeHotkey() {
destroyHotkey();
initHotkeys();
}
// Entry point
exports.main = function (options, callbacks) {
//debugOutput(options.loadReason);
if (options.loadReason == "install") {
preferencesService.set("browser.tabs.drawInTitlebar", false);
}
else if (options.loadReason == "upgrade") {
// v0.4.0 -> v0.5.0, remove when most use >= v0.5.0
if(preferences["theme"] == "winnt") {
preferences["theme"] = "windows";
}
}
// Back up 'browser.tabs.animate' pref before overwriting it
preferences["animate"] = preferencesService.get("browser.tabs.animate");
preferencesService.set("browser.tabs.animate", false);
unload(function () {
preferencesService.set("browser.tabs.animate", preferences["animate"]);
});
// Initialize VerticalTabsReloaded object for each window.
for (let window of windows.browserWindows) {
let lowLevelWindow = viewFor(window);
let windowID = windowUtils.getOuterId(lowLevelWindow);
GLOBAL_SCOPE["vt"+windowID] = new VerticalTabsReloaded(lowLevelWindow);
unload(GLOBAL_SCOPE["vt" + windowID].unload.bind(GLOBAL_SCOPE["vt"+windowID]), lowLevelWindow);
}
windows.browserWindows.on('open', function(window) {
let lowLevelWindow = viewFor(window);
let windowID = windowUtils.getOuterId(lowLevelWindow);
GLOBAL_SCOPE["vt"+windowID] = new VerticalTabsReloaded(lowLevelWindow);
unload(GLOBAL_SCOPE["vt" + windowID].unload.bind(GLOBAL_SCOPE["vt"+windowID]), lowLevelWindow);
});
windows.browserWindows.on('close', function(window) {
let lowLevelWindow = viewFor(window);
let windowID = windowUtils.getOuterId(lowLevelWindow);
GLOBAL_SCOPE["vt"+windowID].unload();
delete GLOBAL_SCOPE["vt"+windowID];
});
initHotkeys();
simplePrefs.on("toggleDisplayHotkey", changeHotkey);
unload(function() {
destroyHotkey();
simplePrefs.off("toggleDisplayHotkey", changeHotkey);
});
};
exports.onUnload = function (reason) {
//debugOutput("onUnload:" + reason);
if(reason == "disable")
{
debugOutput("VTR disabled");
}
unload();
// Unloaders might want access to prefs, so do this last
if (reason == "uninstall") {
// Delete all settings
Services.prefs.getDefaultBranch(PREF_BRANCH).deleteBranch("");
debugOutput("VTR uninstalled");
}
}
function debugOutput(output) {
if (preferences["debug"] == true) {
console.log(output);
}
}
|
JavaScript
| 0 |
@@ -1087,16 +1087,147 @@
ce);%0A%09%7D%0A
+%09%0A%09// Reset hidden preferences not inited in package.json%0A%09if (preferences%5B%22debug%22%5D == true)%0A%09%7B%0A%09%09preferences%5B%22debug%22%5D = false;%0A%09%7D%0A
%7D%0Asimple
|
f0e4922ae87fb862ce81bad9b7be5f607a2c8c76
|
Change to new Artifact property from serverless 1.18.0 (#35)
|
index.js
|
index.js
|
'use strict';
const bluebird = require('bluebird');
const _ = require('lodash');
const path = require('path');
const jszip = require('jszip');
const fs = require('fs');
const minimatch = require('minimatch');
const munge = require('./serverless-cljs-plugin/munge');
const mkdirp = bluebird.promisify(require('mkdirp'));
const exec = bluebird.promisify(require('child_process').exec,
{multiArgs: true});
jszip.external.Promise = bluebird;
const DEFAULT_EXCLUDE = ['node_modules/serverless-cljs-plugin/**', '.lumo_cache/**'];
function isLumo(serverless, opts) {
const compiler = _.get(serverless.service, 'custom.cljsCompiler');
const lumo = _.get(compiler, 'lumo', {});
return (compiler == "lumo" || opts.lumo || _.some(lumo));
}
function setCljsLambdaFnMap(serverless, opts) {
return _.mapValues(
serverless.service.functions,
fn => {
if(fn.cljs) {
fn.handler = `index.${munge.munge(fn.cljs)}`;
if(!isLumo(serverless, opts)) {
_.set(fn, 'package.artifact', serverless.service.__cljsArtifact);
}
}
return fn;
});
}
function setCljsLambdaExclude(serverless) {
return _.update(serverless.service, 'package.exclude', v => _.concat(v || [], DEFAULT_EXCLUDE));
}
function edn(v) {
if (_.isArray(v)) {
return '[' + v.map(edn).join(' ') + ']';
}
if (_.isPlainObject(v)) {
return '{' + _.map(v, (v, k) => ':' + k + ' ' + edn(v)).join(' ') + '}';
}
return v;
}
function slsToCljsLambda(functions, opts) {
return _(functions)
.pickBy((v, k) => v.cljs && (opts.function ? k === opts.function : true))
.values()
.map (m => {
return {name: `"${m.name}"`, invoke: m.cljs};
})
.thru (edn)
.value ();
}
function basepath(config, service, opts) {
return `${config.servicePath}/.serverless/${opts.function || service.service}`;
}
const readFile = bluebird.promisify(fs.readFile);
const writeFile = bluebird.promisify(fs.writeFile);
const applyZipExclude = bluebird.coroutine(
function*(serverless, opts) {
// TODO respect exclude/include on individual functions
const exclude = _.uniq(_.get(serverless.service.package, "exclude", []));
if (!_.isEmpty(exclude)) {
const data = yield readFile(serverless.service.__cljsArtifact);
const oldZip = yield jszip.loadAsync(data);
const newZip = jszip();
oldZip
.filter((path, file) => !_.some(exclude, pattern => minimatch(path, pattern)))
.forEach(entry => newZip.file(entry.name,
entry.nodeStream("nodebuffer"),
_.pick(entry, ["unixPermissions", "dosPermissions", "comment", "date"])));
const buffer = yield newZip.generateAsync({
type: "nodebuffer",
platform: process.platform,
compression: "DEFLATE",
comment: `Generated by serverless-cljs-plugin on ${new Date().toISOString()}`});
yield writeFile(serverless.service.__cljsArtifact, buffer);
}
});
function lumoClasspath(lumo) {
let cp = path.resolve(__dirname, 'serverless-cljs-plugin');
if(lumo.classpath) {
cp = _.isString(lumo.classpath) ? `${cp}:${lumo.classpath}` : `${cp}:${lumo.classpath.join(':')}`;
}
return `--classpath ${cp}`;
}
function lumoDependencies(lumo) {
if(lumo.dependencies) {
const d = _.isString(lumo.dependencies) ? lumo.dependencies : lumo.dependencies.join(',');
return `--dependencies ${d}`;
}
}
function lumoLocalRepo(lumo) {
if(lumo.localRepo) {
return `--local-repo ${lumo.localRepo}`;
}
}
function lumoCache(lumo) {
if(!lumo.cache) {
return "--auto-cache";
} else {
if(lumo.cache != "none") {
return `--cache ${lumo.cache}`;
}
}
}
function cljsLambdaBuild(serverless, opts) {
const fns = slsToCljsLambda(serverless.service.functions, opts);
const compiler = _.get(serverless.service, 'custom.cljsCompiler');
const lumo = _.get(compiler, 'lumo', {});
const exitOnWg = _.get(lumo, 'exitOnWarning');
const index = _.get(lumo, 'index');
let cmd;
if(isLumo(serverless, opts)) {
const args = _.filter([lumoClasspath(lumo),
lumoDependencies(lumo),
lumoLocalRepo(lumo),
lumoCache(lumo)]);
cmd = (`lumo ${args.join(' ')} ` +
`--main serverless-lumo.build ` +
`--service-path ${serverless.config.servicePath} ` +
`--functions '${fns}' ` +
`--index ${_.defaultTo(opts.index || index, false)} ` +
`--warning-exit ${_.defaultTo(opts.exitOnWarning || exitOnWg, false)}`);
} else {
cmd = (`lein update-in :cljs-lambda assoc :functions '${fns}' ` +
`-- cljs-lambda build :output ${serverless.service.__cljsArtifact} ` +
`:quiet`);
}
serverless.cli.log(`Executing "${cmd}"`);
return exec(cmd);
}
const after_createDeploymentArtifacts = bluebird.coroutine(
function*(serverless, opts) {
yield mkdirp(`${serverless.config.servicePath}/.serverless`);
yield cljsLambdaBuild(serverless, opts);
if(!isLumo(serverless, opts)) {
yield applyZipExclude(serverless, opts);
}
serverless.cli.log(`Returning artifact path ${serverless.service.__cljsArtifact}`);
return serverless.service.__cljsArtifact;
});
class ServerlessPlugin {
constructor(serverless, opts) {
opts.function = (opts.f || opts.function);
serverless.service.__cljsBasePath = (
`${basepath(serverless.config, serverless.service, opts)}`);
serverless.service.__cljsArtifact= `${serverless.service.__cljsBasePath}.zip`;
serverless.cli.log(`Targeting ${serverless.service.__cljsArtifact}`);
setCljsLambdaFnMap(serverless, opts);
setCljsLambdaExclude(serverless);
const buildAndMerge = after_createDeploymentArtifacts.bind(
null, serverless, opts);
const when = isLumo(serverless, opts) ? 'before' : 'after';
// Using the same hooks as in graphcool/serverless-plugin-typescript:
// https://github.com/graphcool/serverless-plugin-typescript/blob/master/src/index.ts#L39
this.hooks = {
[`${when}:package:createDeploymentArtifacts`]: buildAndMerge,
[`${when}:deploy:function:packageFunction`]: buildAndMerge
};
}
}
module.exports = ServerlessPlugin;
|
JavaScript
| 0.000001 |
@@ -1044,26 +1044,10 @@
-_.set(fn, 'package
+fn
.art
@@ -1051,18 +1051,18 @@
artifact
-',
+ =
serverl
@@ -1079,33 +1079,32 @@
e.__cljsArtifact
-)
;%0A %7D%0A
|
b628361ea495d252924b32a2ac857f4a81606982
|
Add type and id to script tag
|
index.js
|
index.js
|
/* jshint node: true */
'use strict';
module.exports = {
name: 'ember-cli-inspectlet',
contentFor: function(type, config) {
var wid = config.APP.INSPECTLET_WID;
if (wid != null && type === 'head') {
return "<script>\n" +
"window.__insp = window.__insp || [];\n" +
"__insp.push(['wid', " + wid + "]);\n" +
"(function() {\n" +
"function ldinsp(){if(typeof window.__inspld != 'undefined') return; window.__inspld = 1; var insp = document.createElement('script'); insp.type = 'text/javascript'; insp.async = true; insp.id = 'inspsync'; insp.src = ('https:' == document.location.protocol ? 'https' : 'http') + '://cdn.inspectlet.com/inspectlet.js'; var x = document.getElementsByTagName('script')[0]; x.parentNode.insertBefore(insp, x); };\n" +
" setTimeout(ldinsp, 500); document.readyState != 'complete' ? (window.attachEvent ? window.attachEvent('onload', ldinsp) : window.addEventListener('load', ldinsp, false)) : ldinsp();\n" +
"})();" +
"</script>"
}
}
};
|
JavaScript
| 0.000009 |
@@ -228,16 +228,57 @@
%22%3Cscript
+ type='text/javascript' id='inspectletjs'
%3E%5Cn%22 +%0A
|
d290fc36c3002c8c9e35eba80053dba86272a7b1
|
Remove timestamp
|
index.js
|
index.js
|
var express = require('express');
var pg = require('pg');
var receiver = require('./receiver');
var crud = require('./crud');
var app = express();
app.use(express.static(__dirname + '/public'));
app.set('port', (process.env.PORT || 5000));
app.post('/receiver', function (request, response) {
var body = '';
request.on('data', function (data) {
body += data;
});
request.on('end', function () {
var data = JSON.parse(body);
function cb(a, b){
response.send(a || b);
}
pg.connect(process.env.DATABASE_URL, function (err, client, done) {
client.query("INSERT INTO results VALUES ($1, $2, $3, $4)",
[data.guid, data.username, data.video, JSON.stringify(data.score), +new Date()],
function (err, result) {
done();
if (err) {
cb(err, null);
} else {
cb(null, result.rows);
}
});
});
});
});
app.get('/data', function (request, response) {
pg.connect(process.env.DATABASE_URL, function (err, client, done) {
client.query('TABLE results;', function (err, result) {
done();
if (err) {
console.error(err);
response.send("Error " + err);
} else {
response.send(result.rows);
}
});
});
})
app.listen(app.get('port'), function () {
console.log("Node app is running at localhost:" + app.get('port'));
});
|
JavaScript
| 0.999758 |
@@ -686,21 +686,8 @@
ore)
-, +new Date()
%5D,%0A%09
|
e53ea9b8c9cafd8d53175665435ebe3f1273f6a6
|
Fix path to optimist-config-file import
|
index.js
|
index.js
|
module.exports = require('lib/optimist-config-file');
|
JavaScript
| 0.000062 |
@@ -20,16 +20,18 @@
equire('
+./
lib/opti
@@ -49,8 +49,9 @@
-file');
+%0A
|
a53cfa19f0ea7828c9c84ada7e7eef5787e7622f
|
allow for anonymous map generation using boolean outSorceMap flag
|
index.js
|
index.js
|
var UglifyJS = require("uglify-js");
var loaderUtils = require('loader-utils');
module.exports = function(source, inputSourceMap) {
var callback = this.async();
if (this.cacheable) {
this.cacheable();
}
var opts = this.options['uglify-loader'] || {};
// just an indicator to generate source maps, the output result.map will be modified anyway
opts.outSourceMap = "out.map.js";
opts.fromString = true;
var result = UglifyJS.minify(source, opts);
var sourceFilename = loaderUtils.getRemainingRequest(this);
var current = loaderUtils.getCurrentRequest(this);
var sourceMap = JSON.parse(result.map);
sourceMap.sources = [sourceFilename];
sourceMap.file = current;
sourceMap.sourcesContent = [source];
callback(null, result.code, sourceMap);
};
|
JavaScript
| 0 |
@@ -375,40 +375,110 @@
-opts.outSourceMap = %22out.map.js%22
+// tell UglifyJS2 not to emit a name by just setting outSourceMap to true%0A opts.outSourceMap = true
;%0A
|
9763f69c70aa11fe63e15d22010778b3d8e059e8
|
Remove unnecessary argument.
|
index.js
|
index.js
|
var scuttleup = require('scuttleup');
var crypto = require('crypto');
var events = require('events');
var sublevel = require('level-sublevel');
var pump = require('pump');
var through = require('through2');
var cas = function(db, opts) {
var subs = sublevel(db)
var log = scuttleup(subs.sublevel('log'), {id: opts.id});
var store = subs.sublevel('store');
var that = new events.EventEmitter();
var cbs = {};
var head = 0;
var changeStream = through.obj(function(dta, enc, cb) {
var onbatch = function(err) {
if (err) that.emit('error', err);
if (dta.peer === log.id) {
head = dta.seq;
if (cbs[dta.seq]) {
cbs[dta.seq]();
delete cbs[dta.seq];
}
}
cb();
};
var onget = function(err, heads) {
if (err && !err.notFound) return that.emit('error', err);
heads = heads? JSON.parse(heads) : {};
heads[dta.peer] = {peer: dta.peer, seq: dta.seq};
store.batch([
JSON.parse(dta.entry.toString()),
{type: 'put', key: 'heads', value: JSON.stringify(heads)}
], onbatch);
};
store.get('heads', onget);
});
store.get('heads', function(err, heads) {
if (err && !err.notFound) return that.emit('error', err);
if (!heads) return pump(log.createReadStream({live: true, since: hds}), changeStream);
heads = JSON.parse(heads);
var hds = Object.keys(heads).map(function(key) {
return heads[key];
});
pump(log.createReadStream({live: true, since: hds}), changeStream);
});
that.syncStream = function() {
return log.createReplicationStream();
};
that.put = function(content, cb) {
cb = cb || function() {};
var key = crypto.createHash('sha256').update(content).digest('base64');
log.append(JSON.stringify({type:'put', key: key, value: content}), function(err, change) {
if (err) return cb(err);
if (head >= change.seq) return cb(null, key);
cbs[change.seq] = function() { cb(null, key) };
});
};
that.del = function(key, cb) {
log.append(JSON.stringify({type:'del', key: key}), function(err, change) {
if (err) return cb(err);
if (head >= change.seq) return cb(null);
cbs[change.seq] = function() { cb(null) };
});
};
that.get = store.get;
that.createValueStream = store.createValueStream;
that.createKeyStream = store.createKeyStream;
that.createReadStream = store.createReadStream;
return that;
};
module.exports = cas;
|
JavaScript
| 0.000129 |
@@ -2184,20 +2184,16 @@
turn cb(
-null
);%0A
@@ -2227,20 +2227,16 @@
() %7B cb(
-null
) %7D;%0A
|
855729d903aaaaaaa8b597f77eccb1d13cef7d96
|
fix file
|
index.js
|
index.js
|
var jst = require('jst_compiler');
var through = require('through');
var gutil = require('gulp-util');
var PluginError = gutil.PluginError;
var path = require('path');
var File = gutil.File;
module.exports = function (fileName, options) {
if (!fileName) {
throw new PluginError('gulp-jst_compiler', 'Missing fileName option for gulp-jst_compiler');
}
if (!options) {
options = {};
}
var buffer = [];
var firstFile = null;
function bufferContents(file) {
if (file.isNull()) {
return;
}
if (file.isStream()) {
return this.emit('error', new PluginError('gulp-jst_compiler', 'Streaming not supported'));
}
buffer.push(file.contents);
}
function endStream() {
if (!buffer.length) {
return this.emit('end');
}
var tmpl = jst.compileText(buffer.join('\n'), options);
var joinedContents = new Buffer(tmpl, 'utf8');
var joinedPath = path.join(firstFile.base, fileName);
var joinedFile = new File({
cwd: firstFile.cwd,
base: firstFile.base,
path: joinedPath,
contents: joinedContents
});
this.emit('data', joinedFile);
this.emit('end');
}
return through(bufferContents, endStream);
};
|
JavaScript
| 0.000001 |
@@ -697,32 +697,107 @@
ed'));%0A %7D
+%0A %0A if (!firstFile) %7B%0A firstFile = file;%0A %7D
%0A%0A buffer
|
eac40f08bedee5cb8db8f8f46d97b4d25cb8c716
|
add photoCtrl. bind simple search result and implement tagging and untagging prototype.
|
app/js/controllers.js
|
app/js/controllers.js
|
'use strict';
/* Controllers */
angular.module('flickrDupFinder.controllers', [])
.controller('MyCtrl1', [function() {
}])
.controller('MyCtrl2', [function() {
}]);
|
JavaScript
| 0 |
@@ -12,27 +12,8 @@
';%0A%0A
-/* Controllers */%0A%0A
angu
@@ -39,18 +39,17 @@
upFinder
-.c
+C
ontrolle
@@ -52,18 +52,72 @@
ollers',
- %5B
+%0A %5B'flickrDupFinderServices', 'underscore'
%5D)%0A .co
@@ -129,66 +129,608 @@
ler(
-'My
+%0A 'photo
Ctrl
-1
',
- %5Bfunction() %7B%0A%0A %7D%5D)%0A .controller('MyCtrl2'
+%0A %5B'$scope', '$log', 'Flickr', '_',%0A function($scope, $log, Flickr, _) %7B%0A Flickr.get(%7Btags: %22screens%22%7D, function(result)%7B%0A $scope.results = result.photos.photo;%0A %7D);%0A Flickr.get(%7Btags: %22flickrdupfinder%22%7D, function(result)%7B%0A $scope.specials = result.photos.photo;%0A %7D);%0A%0A $scope.toggleTag = function(photo) %7B%0A if (_.contains(photo.tags.split(%22 %22), 'flickrdupfinder')) %7B%0A Flickr.get(%7B%0A method: 'flickr.photos.getInfo',%0A photo_id: photo.id,%0A tags: 'flickrdupfinder'%0A %7D
,
-%5B
func
@@ -738,13 +738,587 @@
ion(
-) %7B%0A%0A
+info) %7B%0A var tag = _.find(info.photo.tags.tag,%0A function(tag) %7B%0A return tag.raw === 'flickrdupfinder';%0A %7D);%0A Flickr.get(%7B%0A method: 'flickr.photos.removeTag',%0A photo_id: photo.id,%0A tag_id: tag.id%0A %7D);%0A %7D);%0A %7D else %7B%0A Flickr.get(%7B%0A photo_id: photo.id,%0A method: 'flickr.photos.addTags',%0A tags: 'flickrdupfinder'%0A %7D);%0A %7D%0A %7D;%0A
%7D%5D
|
a13edbf13b605663214757f622508a6adf0b3e13
|
Make faces() and attr() calls order-independent
|
index.js
|
index.js
|
var normalize = require('./normalize')
var glType = require('gl-to-dtype')
var createVAO = require('gl-vao')
var dtype = require('dtype')
module.exports = GLGeometry
function GLGeometry(gl) {
if (!(this instanceof GLGeometry))
return new GLGeometry(gl)
this._elementsType = 5123
this._elementsBytes = 2
this._attributes = []
this._dirty = true
this._length = 0
this._index = null
this._vao = null
this._keys = []
this.gl = gl
}
GLGeometry.prototype.dispose = function() {
for (var i = 0; i < this._attributes.length; i++) {
this._attributes[i].buffer.dispose()
}
this._attributes = []
this._keys = []
this._length = 0
this._dirty = true
if (this._index) {
this._index.dispose()
this._index = null
}
if (this._vao) {
this._vao.dispose()
this._vao = null
}
}
GLGeometry.prototype.faces = function faces(attr, opts) {
var size = opts && opts.size || 3
attr = attr.cells ? attr.cells : attr
this._dirty = true
if (this._index) {
this._index.dispose()
}
this._index = normalize(this.gl
, attr
, size
, this.gl.ELEMENT_ARRAY_BUFFER
, 'uint16'
)
this._length = this._index.length * size
this._index = this._index.buffer
return this
}
GLGeometry.prototype.attr = function attr(name, attr, opts) {
opts = opts || {}
this._dirty = true
var gl = this.gl
var first = !this._attributes.length
var size = opts.size || 3
var attribute = normalize(gl, attr, size, gl.ARRAY_BUFFER, 'float32')
if (!attribute) {
throw new Error(
'Unexpected attribute format: needs an ndarray, array, typed array, '
+ 'gl-buffer or simplicial complex'
)
}
var buffer = attribute.buffer
var length = attribute.length
var index = attribute.index
this._keys.push(name)
this._attributes.push({
size: size
, buffer: buffer
})
if (first) {
this._length = length
}
if (first && index) {
this._index = index
}
return this
}
GLGeometry.prototype.bind = function bind(shader) {
this.update()
this._vao.bind()
if (!this._keys) return
for (var i = 0; i < this._keys.length; i++) {
var attr = shader.attributes[this._keys[i]]
if (attr) attr.location = i
}
if (!shader) return
shader.bind()
}
GLGeometry.prototype.draw = function draw(mode, start, stop) {
start = typeof start === 'undefined' ? 0 : start
stop = typeof stop === 'undefined' ? this._length : stop
mode = typeof mode === 'undefined' ? this.gl.TRIANGLES : mode
this.update()
if (this._vao._useElements) {
this.gl.drawElements(mode, stop - start, this._elementsType, start * this._elementsBytes) // "2" is sizeof(uint16)
} else {
this.gl.drawArrays(mode, start, stop - start)
}
}
GLGeometry.prototype.unbind = function unbind() {
this.update()
this._vao.unbind()
}
GLGeometry.prototype.update = function update() {
if (!this._dirty) return
this._dirty = false
if (this._vao) this._vao.dispose()
this._vao = createVAO(
this.gl
, this._attributes
, this._index
)
this._elementsType = this._vao._elementsType
this._elementsBytes = dtype(
glType(this._elementsType) || 'array'
).BYTES_PER_ELEMENT || 2
}
|
JavaScript
| 0.000007 |
@@ -354,33 +354,61 @@
= true%0A this._
-l
+attrLength = 0%0A this._facesL
ength = 0%0A this
@@ -663,33 +663,37 @@
ys = %5B%5D%0A this._
-l
+attrL
ength = 0%0A this
@@ -677,32 +677,166 @@
._attrLength = 0
+ // Length of this attribute (the number of vertices it feeds)%0A this._facesLength = 0 // Number of vertices needed to draw all faces
%0A this._dirty =
@@ -1308,33 +1308,38 @@
6'%0A )%0A%0A this._
-l
+facesL
ength = this._in
@@ -2034,16 +2034,132 @@
r%0A %7D)%0A%0A
+ var isSimplicialComplex = Boolean(index)%0A var attrLength = isSimplicialComplex ? attr.positions.length : length%0A%0A
if (fi
@@ -2175,25 +2175,29 @@
this._
-l
+attrL
ength =
length%0A
@@ -2192,38 +2192,45 @@
h =
-l
+attrL
ength%0A
+%0A
-%7D%0A%0A
if (
-first && ind
+isSimplicialCompl
ex)
@@ -2227,32 +2227,34 @@
lComplex) %7B%0A
+
+
this._index = in
@@ -2257,16 +2257,241 @@
= index%0A
+ this._facesLength = length%0A %7D%0A%0A %7D else if (this._attrLength != attrLength) %7B%0A throw new Error(%0A 'Unexpected discrepancy in attributes size (was ' + this_attrLength%0A + ', now ' + attrLength+ ')'%0A )%0A
%7D%0A%0A r
@@ -2910,69 +2910,8 @@
art%0A
- stop = typeof stop === 'undefined' ? this._length : stop%0A
mo
@@ -3018,24 +3018,92 @@
Elements) %7B%0A
+ stop = typeof stop === 'undefined' ? this._facesLength : stop%0A
this.gl.
@@ -3187,44 +3187,86 @@
tes)
- // %222%22 is sizeof(uint16)%0A %7D else %7B
+%0A %7D else %7B%0A stop = typeof stop === 'undefined' ? this._attrLength : stop
%0A
|
a8146f3112c05db457caa496c5193c3a96ca9fe5
|
Add units to y-axis - closes #20
|
app/js/controllers.js
|
app/js/controllers.js
|
'use strict';
/* Controllers */
angular.module('quixrWebview.controllers', []).
controller('WrapperCtrl1', function($scope, $location, $routeParams) {
$scope.isActive = function (viewLocation) {
return $location.path().indexOf(viewLocation) != -1;
};
$scope.searchDisabled = function() {
return !(typeof($routeParams.vhost) === 'undefined');
}
})
.controller('TrafficCtrl1', function($scope, $http) {
$http.get('data/quixr.json').success(function(data) {
$scope.vhosts = data;
});
})
.controller('MonthviewCtrl1', function($scope, $routeParams, $http, $filter) {
$scope.vhost = $routeParams.vhost;
$scope.month = $routeParams.month;
$scope.year = $routeParams.year;
$scope.display = $routeParams.display;
$http.get('data/quixr.json').success(function(data) {
$scope.data = data[$routeParams.vhost][$routeParams.display][$routeParams.year][$routeParams.month];
var chartObject = {
type: 'LineChart'
};
chartObject.options = {
legend: {
position: 'none'
}
}
chartObject.data = {"cols": [
{id: "m", label: "Month", type: "string"},
{id: "b", label: "Traffic", type: "number"}
], "rows": {}
};
$scope.chartObject = function(unit) {
chartObject.data.rows = getFormattedData($scope.data, unit);
return chartObject;
};
});
function getFormattedData(tmpData, unit) {
var data = [];
angular.forEach(tmpData, function (value, key) {
data.push({c:[
{v: key},
{v: $filter('formatBytes')(value, unit).toFixed(2)}
]});
});
return data;
}
})
.controller('DiskspaceCtrl1', function($scope, $http) {
$http.get('data/quixr.json').success(function(data) {
$scope.vhosts = data;
});
});
|
JavaScript
| 0 |
@@ -1464,32 +1464,108 @@
unction(unit) %7B%0A
+ chartObject.options = %7BvAxis: %7Btitle: unit.toUpperCase()%7D%7D;%0A
|
6730b53b09b473c3a00725950377287b610d551e
|
Set Mac prompt to feature ⌘
|
index.js
|
index.js
|
var deselectCurrent = require('toggle-selection');
function copy(text, options) {
var debug, message, cb, reselectPrevious, range, selection, mark;
if (!options) { options = {}; }
debug = options.debug || false;
message = options.message || 'Copy to clipboard: Ctrl+C, Enter';
cb = options.cb || Function.prototype;
try {
reselectPrevious = deselectCurrent();
range = document.createRange();
selection = document.getSelection();
mark = document.createElement('mark');
mark.textContent = text;
// used to conserve newline, etc
mark.style.whiteSpace = 'pre';
document.body.appendChild(mark);
range.selectNode(mark);
selection.addRange(range);
var successful = document.execCommand('copy');
if (!successful) {
throw new Error('copy command was unsuccessful');
}
} catch (err) {
debug && console.error('unable to copy, trying IE specific stuff');
try {
window.clipboardData.setData('text', text);
} catch (err) {
debug && console.error('unable to copy, falling back to prompt');
window.prompt(message, text);
}
} finally {
cb(null);
if (selection) {
if (typeof selection.removeRange == 'function') {
selection.removeRange(range);
} else {
selection.removeAllRanges();
}
}
if (mark) {
document.body.removeChild(mark);
}
reselectPrevious();
}
}
module.exports = copy;
|
JavaScript
| 0 |
@@ -88,16 +88,25 @@
r debug,
+ copyKey,
message
@@ -153,16 +153,16 @@
, mark;%0A
-
if (!o
@@ -221,16 +221,82 @@
false;%0A
+ copyKey = /mac os x/i.test(navigator.userAgent) ? '%E2%8C%98' : 'Ctrl';%0A
messag
@@ -338,20 +338,31 @@
pboard:
-Ctrl
+' + copyKey + '
+C, Ente
|
4b631a264a7c80f17dac3ad12ccf1472337e1409
|
Remove unused if
|
index.js
|
index.js
|
'use strict'
var Primus = require('primus')
var config = require('config')
var workflowHandler = require('./lib/eventHandlers/workflow.js')
var jobSourceCorePoller = require('./lib/jobSources/corePoller.js')
var EventEmitter = require('eventemitter3')
var pollingInterval = 1000
if (!(config.coreAPIToken)) {
if (config.coreAPIToken.length === 0) {
process.exit(1)
}
}
var socket = new Primus.createSocket() // eslint-disable-line new-cap
var client = socket(config.coreUrl + '?token=' + config.coreAPIToken)
var emitter = new EventEmitter()
workflowHandler(emitter)
jobSourceCorePoller(emitter, pollingInterval)
var plugins = require('./lib/plugins')
plugins(emitter, client)
console.log('this drone runs on: ', process.platform)
console.log('using token', config.coreAPIToken)
// TODO: periodic token refresh (in corePoller)?
emitter.emit('auth.token', config.coreAPIToken)
if (!module.parent) {
}
|
JavaScript
| 0.000002 |
@@ -890,29 +890,4 @@
en)%0A
-%0Aif (!module.parent) %7B%0A%7D%0A
|
be67e80697647837d6c1271eaaae1a4edd80e1fe
|
fix ga expression
|
app/js/controllers.js
|
app/js/controllers.js
|
'use strict';
angular.module('SecretSantaApp.controllers', [])
.controller('eventController', function($scope, emailAPIService, _) {
$scope.event = {
title: null,
cashAmount: 15,
cashCurrency: 'eur',
date: new Date("2013-12-25T00:00:00.000Z"),
message: '',
valid: false
}
$scope.people = [];
$scope.newPerson = {};
$scope.slider = {
options: {
orientation: 'horizontal',
min: '0',
max: '100',
range: 'min'
}
}
$scope.errors = {
'title': 'Please provide an event title.',
'people': 'Please add at least 3 people',
'exists': 'Already on the list',
'noexist': 'One of the addresses does not exist',
'checking': 'The elves are verifying the addresses',
'ok': 'Send to santa!'
}
$scope.currentError = $scope.errors.title;
$scope.checkErrors = function(detailsForm, people) {
if(! $scope.event.title) {
$scope.currentError = $scope.errors.title;
$scope.valid = false;
} else if($scope.people.length < 3) {
$scope.currentError = $scope.errors.people;
$scope.valid = false;
} else if(detailsForm.$valid && people.length >= 3) {
var valid = true;
for(var i = 0; i < people.length; i++) {
if(people[i].valid == false) {
valid = false;
} else if(people[i].valid == null) {
$scope.currentError = $scope.errors.checking;
valid = false;
} else {
valid = true;
}
}
$scope.valid = valid;
if($scope.valid) {
$scope.currentError = $scope.errors.ok;
}
}
return $scope.valid;
};
$scope.alreadyAdded = function(email) {
var alreadyAdded = false;
if($scope.people.length >= 1) {
for(var idx in $scope.people) {
if(_.contains($scope.people[idx], email)) {
alreadyAdded = true;
}
}
}
return alreadyAdded;
}
$scope.checkEmail = function(email, idx) {
emailAPIService.checkEmail(email, function(data) {
if(data.success != true) {
$scope.people[idx].valid = false;
} else {
$scope.people[idx].valid = true;
}
});
};
$scope.addPerson = function(person) {
var emailExists = null,
person = $scope.newPerson;
if($scope.alreadyAdded(person.email)) {
$scope.currentError = $scope.errors.exists;
$scope.newPerson = {};
} else {
$scope.people.push(person);
$scope.newPerson = {};
var idx = $scope.people.indexOf(person);
$scope.checkEmail(person.email, idx);
}
};
$scope.removePerson = function(index) {
$scope.people.splice(index, 1);
$scope.checkErrors();
};
$scope.validateEvent = function(detailsForm, people) {
return $scope.checkErrors(detailsForm, people);
};
// $scope.submitEvent = function() {
// var postData = {};
// window._gaq.push(['_trackEvent', 'sendNames', 'clickSubmit']);
// _.extend(postData, { event: $scope.event }, { people: $scope.people });
// emailAPIService.postEmails(postData, function(data) {
// console.log(data.success);
// if(data.success) {
// $scope.people = [];
// $scope.newPerson = {};
// $scope.event = {
// title: null,
// cashAmount: 15,
// cashCurrency: 'eur',
// date: new Date("2013-12-25T00:00:00.000Z"),
// message: ''
// };
// }
// });
// };
/* TODO: figure out where to put this */
$('#github').on('click', function() {
window._gaq.push(['_trackEvent', 'link', 'github-fork']);
});
$('a[class^="seeger-"], a[class^=joris-').on('click', function() {
window._gaq.push(['_trackEvent', 'link', $(this).attr('class')]);
});
var body = document.body,
timer;
window.addEventListener('scroll', function() {
clearTimeout(timer);
if(!body.classList.contains('disable-hover')) {
body.classList.add('disable-hover')
}
var timer = setTimeout(function(){
body.classList.remove('disable-hover')
},500);
}, false);
$('.slider').slider();
/* /TODO */
});
|
JavaScript
| 0.999996 |
@@ -3631,14 +3631,17 @@
ss%5E=
+%22
joris-
+%22%5D
').o
|
74094fe0e72280f1275979abeb0079e75aa4f386
|
disable rotation, confused the noobs
|
app/js/modules/map.js
|
app/js/modules/map.js
|
import mapboxgl from 'mapbox-gl';
let Map = class {
constructor(mapOptions, geoJSON, breaks, colors, bounds = [], selected = []) {
this.mapOptions = mapOptions;
this.geoJSON = geoJSON;
this.breaks = breaks;
this.colors = colors;
this.selected = selected;
this.bounds = bounds;
}
// initialize the map
createMap() {
this.map = new mapboxgl.Map(this.mapOptions);
let map = this.map;
let component = this;
let bounds = this.bounds;
// send new bounds to parent on move end
if (window!=window.top) {
map.on('moveend', function() {
let bounds = map.getBounds();
parent.postMessage({"bounds": `${bounds._sw.lng.toFixed(4)},${bounds._sw.lat.toFixed(4)},${bounds._ne.lng.toFixed(4)},${bounds._ne.lat.toFixed(4)}`},"*");
});
}
// after map initiated, intiate and style neighborhoods and zoom to bounds
map.on('load', function () {
component.neighborhoodInit(component.geoJSON);
component.neighborhoodStyle(component.breaks, component.colors);
component.neighborhoodSelected(component.selected);
if (bounds.length === 4) {
map.fitBounds([[bounds[0],bounds[1]],[bounds[2],bounds[3]]]);
}
});
}
// create neighborhood layers (choropleth, regular outline, highlight outline)
neighborhoodInit(geoJSON) {
let map = this.map;
this.choroplethSource = new mapboxgl.GeoJSONSource({
data: geoJSON
});
let choroplethSource = this.choroplethSource;
map.addSource('neighborhoods', choroplethSource);
// neighborhood boundaries
map.addLayer({
'id': 'neighborhoods-line',
'type': 'line',
'source': 'neighborhoods',
'layout': {},
'paint': {
'line-color': '#ffffff',
'line-width': 0.8
}
}, 'building');
// neighborhood boundaries highlight
map.addLayer({
'id': 'neighborhoods-line-selected',
'type': 'line',
'source': 'neighborhoods',
'layout': {},
"filter": ["in", "id", "-999999"],
'paint': {
'line-color': '#ba00e4',
'line-width': {
"base": 2,
"stops": [
[
7,
2
],
[
13,
5
],
[
16,
8
]
]
}
}
}, 'water_label');
// neighborhoods choropleth
map.addLayer({
'id': 'neighborhoods-fill',
'type': 'fill',
'source': 'neighborhoods',
'layout': {},
'filter': ['!=', 'choropleth', 'null'],
'paint': {
'fill-opacity': 1
}
}, 'neighborhoods-line');
}
// filter the neighborhood line highlights
neighborhoodSelected(selected) {
let map = this.map;
let filter;
if (selected.length > 0) {
filter = ["in", "id"];
for (let i = 0; i < selected.length; i++) {
filter.push(selected[i]);
}
} else {
filter = ["in", "id", "-999999"];
}
map.setFilter("neighborhoods-line-selected", filter);
}
// style the neighborhood polygons
neighborhoodStyle(breaks, colors) {
let map = this.map;
let fillColor = {
property: 'choropleth',
stops: [
[breaks[1], colors[0]],
[breaks[2], colors[1]],
[breaks[3], colors[2]],
[breaks[4], colors[3]],
[breaks[5], colors[4]]
]
};
map.setPaintProperty("neighborhoods-fill", 'fill-color', fillColor);
}
// change the mapped data
updateChrolopleth(geoJSON, breaks) {
this.choroplethSource.setData(geoJSON);
this.neighborhoodStyle(breaks, this.colors);
this.neighborhoodSelected(this.selected);
}
};
export default Map;
|
JavaScript
| 0 |
@@ -521,16 +521,165 @@
ounds;%0A%0A
+ // disable map rotation using right click + drag and touch%0A map.dragRotate.disable();%0A map.touchZoomRotate.disableRotation();%0A%0A
|
331fc1b613ea90bae7c9e266ff1619a1691cdb68
|
Make the configuration from HtmlWebpackplugin (options.favicons) work (#54)
|
index.js
|
index.js
|
'use strict';
var childCompiler = require('./lib/compiler.js');
var assert = require('assert');
var _ = require('lodash');
var fs = require('fs');
var path = require('path');
function FaviconsWebpackPlugin (options) {
if (typeof options === 'string') {
options = {logo: options};
}
assert(typeof options === 'object', 'FaviconsWebpackPlugin options are required');
assert(options.logo, 'An input file is required');
this.options = _.extend({
prefix: 'icons-[hash]/',
emitStats: false,
statsFilename: 'iconstats-[hash].json',
persistentCache: true,
inject: true,
background: '#fff'
}, options);
this.options.icons = _.extend({
android: true,
appleIcon: true,
appleStartup: true,
coast: false,
favicons: true,
firefox: true,
opengraph: false,
twitter: false,
yandex: false,
windows: false
}, this.options.icons);
}
FaviconsWebpackPlugin.prototype.apply = function (compiler) {
var self = this;
if (!self.options.title) {
self.options.title = guessAppName(compiler.context);
}
// Generate the favicons
var compilationResult;
compiler.plugin('make', function (compilation, callback) {
childCompiler.compileTemplate(self.options, compiler.context, compilation)
.then(function (result) {
compilationResult = result;
callback();
})
.catch(callback);
});
// Hook into the html-webpack-plugin processing
// and add the html
if (self.options.inject) {
compiler.plugin('compilation', function (compilation) {
compilation.plugin('html-webpack-plugin-before-html-processing', function (htmlPluginData, callback) {
if (htmlPluginData.plugin.options.favicons !== false) {
htmlPluginData.html = htmlPluginData.html.replace(
/(<\/head>)/i, compilationResult.stats.html.join('') + '$&');
callback(null, htmlPluginData);
}
});
});
}
// Remove the stats from the output if they are not required
if (!self.options.emitStats) {
compiler.plugin('emit', function (compilation, callback) {
delete compilation.assets[compilationResult.outputName];
callback();
});
}
};
/**
* Tries to guess the name from the package.json
*/
function guessAppName (compilerWorkingDirectory) {
var packageJson = path.resolve(compilerWorkingDirectory, 'package.json');
if (!fs.existsSync(packageJson)) {
packageJson = path.resolve(compilerWorkingDirectory, '../package.json');
if (!fs.existsSync(packageJson)) {
return 'Webpack App';
}
}
return JSON.parse(fs.readFileSync(packageJson)).name;
}
module.exports = FaviconsWebpackPlugin;
|
JavaScript
| 0.001477 |
@@ -1851,24 +1851,32 @@
+ '$&');%0A
+ %7D%0A
call
@@ -1903,26 +1903,16 @@
nData);%0A
- %7D%0A
%7D)
|
6abc43730b85f9bbd6ce149209b79483b3e58a0e
|
change Tags in profileCtrl.js
|
app/js/profileCtrl.js
|
app/js/profileCtrl.js
|
app.controller("profileCtrl",
function($scope, Auth, $firebaseArray, $firebaseObject,$window, $stateParams) {
Auth.$onAuthStateChanged(function(authData){
//initialize
if (authData) {
$scope.authData = authData;
ref = firebase.database().ref("users/"+$scope.authData.uid+"/readOnly/info");
$scope.profile_info = $firebaseObject(ref);
$scope.profile_readOnly = true;
$scope.profile_readOnly_checkbox = "return false;"
//$scope.profile_info.tag.c++=false;
var id = $stateParams.uid;
if (id != $scope.authData.uid) $scope.button_visible = false;
else $scope.button_visible = true;
console.log(authData);
}
else {
console.log("signed out");
}
});
$scope.button_name = "EDIT";
$scope.edit = function(){
if($scope.profile_readOnly) {
$scope.profile_readOnly=false;
$scope.button_name = "SAVE";
}
else{
$scope.profile_info.$save().then(function(){
console.log($scope.profile_info);
});
$scope.profile_readOnly=true;
$scope.button_name = "EDIT";
}
};
}
);
|
JavaScript
| 0.000001 |
@@ -102,16 +102,23 @@
teParams
+,Helper
) %7B%09%0A%09%09A
@@ -417,43 +417,32 @@
ile_
-readOnly_checkbox = %22return false;%22
+info.tags = Helper.tags;
%0A%09%09%09
|
6a66368a647a18b390f172baf004a8465abb8898
|
Need to return the value in the set function
|
index.js
|
index.js
|
module.exports = lookup;
function lookup() {
if( !( this instanceof lookup ) ) {
var newObj = Object.create(lookup.prototype);
lookup.apply(newObj, arguments);
return newObj;
}
if( arguments.length % 2 != 0 ) {
throw new Error( 'Incorrect key value amount. You should pass in arguments as key, value, key, value, ...' );
}
this._dataStr = {}; // structure for strings
this._dataNum = {}; // structure for numbers
this._dataOther = []; // structure for everything else
for( var i = 0, len = arguments.length; i < len; i += 2 ) {
this.set( arguments[ i ], arguments[ i + 1 ] );
}
}
lookup.prototype = {
set: function( key, value ) {
var keyType = typeof key;
if( keyType === "string" ) {
this._dataStr[ key ] = value;
}
else if( keyType === "number" ) {
this._dataNum[ key ] = value;
}
else {
var i = getIdx( this, key );
i = i == -1 ? this._dataOther.length : i;
this._dataOther[ i ] = key;
this._dataOther[ i + 1 ] = value;
return value;
}
},
remove: function( key ) {
var keyType = typeof key,
rVal = undefined;
if( keyType === "string" ) {
rVal = this._dataStr[ key ];
delete this._dataStr[ key ];
}
else if( keyType === "number" ) {
rVal = this._dataNum[ key ];
delete this._dataNum[ key ];
}
else {
var i = getIdx( this, key );
if( i != -1 ) {
rVal = this._dataOther[ i + 1 ];
this._dataOther.splice( i, 2 );
}
}
return rVal;
},
get: function( key ) {
var keyType = typeof key;
if( keyType === "string" ) {
return this._dataStr[ key ];
}
else if( keyType === "number" ) {
return this._dataNum[ key ];
}
else {
var i = getIdx( this, key )
if( i != -1 ) {
return this._dataOther[ i + 1 ];
}
else {
return undefined;
}
}
}
};
function getIdx( lookup, key ) {
var rVal = -1;
for( var i = 0, len = lookup._dataOther.length; i < len; i += 2 ) {
if( lookup._dataOther[ i ] === key ) {
rVal = i;
break;
}
}
return rVal;
}
|
JavaScript
| 0.999996 |
@@ -1042,19 +1042,27 @@
value;%0A
-%0A
+ %7D%0A %0A
retu
@@ -1071,22 +1071,16 @@
value;%0A
- %7D%0A
%7D,%0A%0A
|
cead7d3f89d6f483285952006bfc66465ade81df
|
allow binding css width to elements
|
index.js
|
index.js
|
var Vec2 = require('vec2')
var Rec2 = require('rec2')
var mouse, scroll, screen
var element =
exports.element = function (el, bind) {
var rec = el.getBoundingClientRect()
var rec2 = new Rec2
var style = getComputedStyle(el)
console.log(style.left, style.right)
rec2.set(rec.left - parseFloat(style['margin-left'])
, rec.top - parseFloat(style['margin-top']))
//check if it's actually a Rec2 - if it's a vec2
//skip this step.
if(rec2.size)
rec2.size.set(rec.width, rec.height)
return rec2
}
exports.mouseEvent = mouseEvent
//function (ev) {
// return new Vec2(ev.clientX, ev.clientY)
//}
//var style = getComputedStyle(el)
// + parseFloat(style['margin-top'])
// + parseFloat(style['margin-left'])
var elementRec2 = function (el) {
var rec = el.getBoundingClientRect()
var style = getComputedStyle(el)
return new Rec2(
rec.left - parseFloat(style.left),
rec.top - parseFloat(style.top),
rec.width, rec.height
)
}
function mouseEvent (ev) {
var vec = new Vec2()
return vec.set(ev.clientX, ev.clientY)
}
exports.mouse = function () {
if(mouse) return mouse
mouse = new Vec2()
window.addEventListener('mousemove', function (e) {
mouse.set(e.clientX, e.clientY)
})
return mouse
}
exports.scroll = function () {
if(scroll) return scroll
scroll = new Vec2()
scroll.set(e.clientX, e.clientY)
window.addEventListener('scroll', function (e) {
scroll.set(window.scrollX, window.scrollY)
})
}
exports.screenSize = function () {
if(size) return size
size = new Vec2()
window.addEventListener('resize', function (e) {
size.set(window.innerWidth, window.innerHeight)
})
}
//if bind=true this will make the element
//track the position of the Vec2,
//and will work around the DOM qwerk that
exports.absolute = function (el, bind) {
var absolute =
element(el).subtract(element(el.parentElement))
if(bind) {
el.style.position = 'absolute'
function place () {
el.style.left = absolute.x + 'px'
el.style.top = absolute.y + 'px'
}
absolute.change(place)
el.style.bottom = ''
el.style.right = ''
}
return absolute
}
exports.size = function (el, bind) {
}
|
JavaScript
| 0 |
@@ -73,17 +73,23 @@
, screen
+, size
%0A
-
%0Avar ele
@@ -242,47 +242,9 @@
el)%0A
- console.log(style.left, style.right)
%0A
+
re
@@ -430,16 +430,16 @@
2.size)%0A
-
rec2
@@ -472,16 +472,196 @@
eight)%0A%0A
+ if(bind) %7B%0A rec2.size.change(function (size) %7B%0A console.log('wh', size.x, size.y)%0A el.style.width = size.x + 'px'%0A el.style.height = size.y + 'px'%0A %7D)%0A %7D%0A%0A
return
@@ -1810,16 +1810,80 @@
t)%0A %7D)%0A
+ size.set(window.innerWidth, window.innerHeight)%0A return size%0A
%7D%0A%0A%0A//if
@@ -2372,46 +2372,4 @@
%0A%7D%0A%0A
-exports.size = function (el, bind) %7B%0A %0A%7D%0A
|
95574fb7bdc67bf8de704f9be86a1a352895c102
|
Update to use lazypipe style calling
|
index.js
|
index.js
|
var gulp = require('gulp');
var Elixir = require('laravel-elixir');
var inky = require('inky');
var prettify = require('gulp-prettify');
var fs = require('fs');
var siphon = require('siphon-media-query');
var lazypipe = require('lazypipe');
var inlineCss = require('gulp-inline-css');
var htmlmin = require('gulp-htmlmin');
var injectString = require('gulp-inject-string');
var Task = Elixir.Task;
Elixir.extend('processEmails', function(options) {
new Task('processEmails', function() {
return gulp
.src('resources/emails/**/*.blade.php')
.pipe(inky())
.pipe(prettify({ indent_size: 2 }))
.pipe(injectString.replace('->', '->'))
.pipe(injectString.replace('=>', '=>'))
.pipe(injectString.replace('"', '"'))
.pipe(injectString.replace(''', '\''))
.pipe(inliner('node_modules/laravel-elixir-mail-processor/foundation-emails.min.css'))
.pipe(gulp.dest('resources/views/emails'));
})
.watch('./resources/emails/**');
function inliner(css) {
var css = fs.readFileSync(css).toString();
var pipe = lazypipe()
.pipe(injectString.replace, '<!-- <style> -->', '<style>'+css+'</style>')
.pipe(inlineCss({ preserveMediaQueries: true }))
.pipe(htmlmin, {
collapseWhitespace: true,
minifyCSS: true
});
return pipe();
}
});
|
JavaScript
| 0 |
@@ -1278,17 +1278,18 @@
nlineCss
-(
+,
%7B preser
@@ -1311,17 +1311,16 @@
true %7D)
-)
%0A
|
5098ad1f09f7d04aba7f5f8883ddbafa70cc65ae
|
Add check for remaining queue items
|
app/libs/queue/add.js
|
app/libs/queue/add.js
|
'use strict';
// Load requirements
const assign = require('deep-assign');
// Load libraries
const logger = require('../log');
// Variables
let queueCache = [];
// Send back the function
module.exports = function(task) {
return new Promise((resolve, reject) => {
// Variables
let added = [],
promises = [],
options = {};
// Exit without a task
if ( ! task || typeof task !== 'object' ) {
return reject('Missing or invalid task argument');
}
// Loop through and assign the available jobs to the queue
task.jobs.forEach((job) => {
// Skip if already in queue
if ( queueCache.includes(job.file) ) {
return false;
}
// Add to cache to stop additional runs
queueCache.push(job.file);
this.total = queueCache.length;
// Track files being added with this task
added.push(job.basename);
// Merge options for this task
job.options = assign(options, job.options);
// Add to the queue
promises.push(this.items.add(() => {
// Update queue length
this.length = ( this.items.getQueueLength() + this.items.getPendingLength() );
// Update current task position
this.current++;
// Update overall counter
task.overall = {total: this.total, current: this.current};
// DEBUG
logger.info('Starting task {cyan:%s} of {green:%s}', this.current, this.total);
// Queue data test
if ( this.current < this.total ) {
let next = this.items.queue[0].job;
logger.info('Next task {green:' + next.basename + '}');
}
// Send to conversion for processing
return require('../conversion').run(job);
}));
// Add data to queue for lookup later
this.items.queue[( this.items.queue.length - 1)].job = job;
});
// DEBUG
logger.info('Added:\n {green:' + added.join('\n ').trim() + '}');
// Unpause the queue
this.items.maxPendingPromises = 1;
this.items._dequeue();
// Wait for this task to complete to resolve
Promise.all(promises).then((result) => {
return resolve(result);
}).catch((err) => {
return reject(err);
});
});
};
|
JavaScript
| 0 |
@@ -1495,28 +1495,22 @@
his.
-current %3C this.total
+items.queue%5B0%5D
) %7B
|
6a9e72c1f230a0d92a74e2cfc3c0b0627cfc88f7
|
Update index.js
|
index.js
|
index.js
|
const Discord = require('discord.js');
const config = require('./settings.json');
const client = new Discord.Client();
const ddiff = require('return-deep-diff');
const path = require('path');
//Events
client.on('ready', () =>{
console.log('This is Margarine speaking!');
console.log('Online and awaiting orders!');
client.user.setGame('Being Useless...');
});
client.on('guildDelete', guild =>{
console.log(`I have stopped providing for ${guild.name} at ${new Date()}`);
});
client.on('guildCreate', guild =>{
console.log(`I have started working for ${guild.name} at ${new Date()}`);
guild.defaultChannel.sendMessage('Hello! I am Margarine and I will be a bot on here!');
guild.defaultChannel.sendMessage('Please do m~help for more information!'); //Not a command yet. Final command before 0.2 release.
});
client.on('guildMemberAdd', (member) =>{
console.log(`New User: ${member.user.username}`);
let guild = member.guild;
member.guild.defaultChannel.sendMessage(`${member.user.username} has joined for the first time!`);
});
client.on('guildMemberRemove', (member) => {
console.log(`User left: ${member.user.username}`);
let guild = member.guild;
member.guild.defaultChannel.sendMessage(`${member.user.username} has left the server.`);
});
client.on('guildMemberUpdate', (oMember, nMember) => {
console.log(ddiff(oMember, nMember));
});
client.on('guildBanAdd', (guild, user) => {
guild.defaultChannel.sendMessage(`${user.username} was banned!`);
guild.defaultChannel.sendMessage('Glory to the hammer!');
});
client.on('guildBanRemove', (guild, user) => {
guild.defaultChannel.sendMessage(`${user.username} fought the ban hammer and won!`);
});
//Bot Failure Safety net
client.on('error', (e) => console.error(e));
client.on('warn', (e) => console.warn(e));
client.on('debug', (e) => console.debug(e));
client.on('message', message => {
if (message.author === client.user) return;
if (message.content.startsWith(config.prefix + 'ping')) { //Possible to move command to different file and still work?
console.log('Ping command executed.');
message.channel.send('Pong');
}
if (message.content.startsWith(config.prefix + 'version')){
console.log('Version command executed.');
message.channel.send(`Margarine is on version: ${package.version}`);
}
});
client.login(config.token); //See settings.json for edits.
|
JavaScript
| 0 |
@@ -1933,24 +1933,12 @@
thor
- === client.user
+.bot
) re
@@ -1943,16 +1943,18 @@
return;%0A
+%09%0A
%09if (mes
@@ -2147,16 +2147,198 @@
ng');%0A%09%7D
+ else%0A%09%0A%09if (message.content.startWith(config.prefix + 'send'))%7B%0A%09%09console.log('Trans-channel message sent!');%0A%09%09client.channel.get('304129722999373825').sendMessage('Hello!');%0A%09%7D%0A%09%09
%0A%09if (me
|
20ad858a60c9d1c4e46db1c14e2f7c9a4443fd8f
|
fix `cascade` option
|
index.js
|
index.js
|
'use strict';
var autoprefixer = require('autoprefixer');
var plugin = module.exports;
function prefix() {
var browsers = atom.config.get('autoprefixer.browsers');
var editor = atom.workspace.getActiveEditor();
var isCSS = editor.getGrammar().name === 'CSS';
if (!editor) {
return;
}
// process the selected text only when not CSS
var text = isCSS ? editor.getText() : editor.getSelectedText();
var prefixed = '';
try {
prefixed = autoprefixer(browsers).process(text, {
safe: true,
cascade: atom.config.get('autoprefixer.cascade')
}).css;
} catch (err) {
console.error(err);
atom.beep();
return;
}
var cursorPosition = editor.getCursorBufferPosition();
if (isCSS) {
editor.setText(prefixed);
} else {
editor.setTextInBufferRange(editor.getSelectedBufferRange(), prefixed);
}
editor.setCursorBufferPosition(cursorPosition);
}
plugin.configDefaults = {
browsers: ['> 1%', 'last 2 versions', 'Firefox ESR', 'Opera 12.1'],
cascade: true
};
plugin.activate = function () {
return atom.workspaceView.command('autoprefixer', prefix);
};
|
JavaScript
| 0.000221 |
@@ -466,40 +466,11 @@
sers
-).process(text, %7B%0A%09%09%09safe: true,
+, %7B
%0A%09%09%09
@@ -518,16 +518,51 @@
scade')%0A
+%09%09%7D).process(text, %7B%0A%09%09%09safe: true%0A
%09%09%7D).css
|
9b74ef0002fd915d67842d320d3c86b87aa913f3
|
Call transport through domain reference
|
index.js
|
index.js
|
/*
index.js - "tart-marshal": Send messages between memory domains (tart module)
The MIT License (MIT)
Copyright (c) 2013 Dale Schumacher
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.
*/
"use strict";
var marshal = module.exports;
marshal.router = function router(sponsor, defaultRoute) { // table-based routing transport
var self = {};
self.sponsor = sponsor;
self.defaultRoute = defaultRoute || function route(message) {
throw Error('No route for ' + message.address);
};
self.routingTable = {}; // mapping from domains to transports
self.transport = function transport(message) {
// { address:<token>, content:<json> }
var remote = message.address;
var parsed = remote.split('#');
if (parsed.length != 2) { throw Error('Bad address format: ' + remote); }
var domain = parsed[0];
var route = self.routingTable[domain];
if (!route) {
route = self.defaultRoute;
}
route(message);
};
self.domain = function domain(name, sponsor) {
sponsor = sponsor || self.sponsor;
var dom = marshal.domain(name, sponsor, self.transport);
self.routingTable[name] = function route(message) {
dom.receptionist(message); // call domain endpoint
};
return dom;
};
return self;
};
marshal.domain = function domain(name, sponsor, transport) {
var self = {};
var tokenMap = {};
self.name = name;
self.sponsor = sponsor;
self.transport = transport;
self.receptionist = function endpoint(message) {
// { address:<token>, content:<json> }
var local = tokenMap[message.address];
if (!local) { throw Error('Unknown address: ' + message.address); }
local(decode(message.content));
};
var bindLocal = function bindLocal(remote, local) {
tokenMap[remote] = local;
};
var localToRemote = function localToRemote(local) {
var remote;
for (remote in tokenMap) {
if (tokenMap[remote] === local) {
return remote;
}
}
/* not found, create a new entry */
remote = name + '#' + generateCapability();
bindLocal(remote, local);
return remote;
};
var generateCapability = function generateCapability() {
try {
return require('crypto').randomBytes(42).toString('base64');
} catch (exception) {
// FIXME: if the system runs out of entropy, an exception will be thrown;
// we need to define system behavior when we are out of entropy,
// remembering that the entire OS crypto activity
// (including any encrypted network traffic)
// will grind to a halt while waiting for entropy to be available
throw exception;
}
};
var remoteToLocal = function remoteToLocal(remote) {
var local = tokenMap[remote];
if (local === undefined) {
local = sponsor(proxy(remote)); // create new proxy
bindLocal(remote, local);
}
return local;
};
var proxy = function proxy(remote) {
return function proxyBeh(message) {
transport({
address: remote,
content: encode(message)
});
};
};
var encode = function encode(message) {
var json;
json = JSON.stringify(message, replacer);
return json;
};
var replacer = function replacer(key, value) {
if (typeof value === 'function') {
return localToRemote(value);
}
if (typeof value === 'string') {
return encodeString(value);
}
if (value instanceof Error) {
return {
message: value.message,
stack: value.stack
};
}
return value;
};
var encodeString = function encodeString(value) {
return ":" + value;
};
var decode = function decode(json) {
var message;
message = JSON.parse(json, reviver);
return message;
};
var reviver = function reviver(key, value) {
if (typeof value === 'string') {
if (isString(value)) {
return decodeString(value);
} else {
return remoteToLocal(value);
}
}
return value;
};
var isString = function isString(value) {
return (value.charAt(0) === ":");
};
var decodeString = function decodeString(value) {
return value.slice(1);
};
self.encode = encode;
self.decode = decode;
self.localToRemote = localToRemote;
self.remoteToLocal = remoteToLocal;
self.bindLocal = bindLocal;
return self;
};
|
JavaScript
| 0 |
@@ -4243,16 +4243,21 @@
+self.
transpor
|
6a1e55db514da3ea2f39e6fb68eeed965791b85f
|
Remove superfluous routes
|
index.js
|
index.js
|
var _, app, badge, bodyParser, config, cookieParser, cors, docket, docs, express, expressSession, fs, http, httpServer, io, LocalStrategy, logger, login, mongoose, notAllowed, options, passport, path, port, Rat, rat, register, Rescue, rescue, router, socket, winston, ws
// IMPORT
// =============================================================================
// Import libraries
_ = require( 'underscore' )
bodyParser = require( 'body-parser' )
cors = require( 'cors' )
cookieParser = require( 'cookie-parser' )
// docket = require( './docket.js' )
docs = require( 'express-mongoose-docs' )
express = require( 'express' )
expressSession = require( 'express-session' )
fs = require( 'fs' )
http = require( 'http' )
mongoose = require( 'mongoose' )
passport = require( 'passport' )
path = require( 'path' )
LocalStrategy = require( 'passport-local' ).Strategy
winston = require( 'winston' )
ws = require( 'ws' ).Server
// Import config
if ( fs.existsSync( './config.json' ) ) {
config = require( './config' )
} else {
config = require( './config-example' )
}
// Import models
Rat = require( './api/models/rat' )
Rescue = require( './api/models/rescue' )
User = require( './api/models/user' )
// Import controllers
badge = require( './api/controllers/badge' )
login = require( './api/controllers/login' )
rat = require( './api/controllers/rat' )
register = require( './api/controllers/register' )
rescue = require( './api/controllers/rescue' )
// Connect to MongoDB
mongoose.connect( 'mongodb://localhost/fuelrats' )
options = {
logging: true,
test: false
}
// SHARED METHODS
// =============================================================================
// Function for disallowed methods
notAllowed = function notAllowed ( request, response ) {
response.status( 405 )
response.send()
}
// Add a broadcast method for websockets
ws.prototype.broadcast = function ( data ) {
var clients
clients = this.clients
for ( var i = 0; i < clients.length; i++ ) {
clients[i].send( data )
}
}
// Parse command line arguments
// =============================================================================
if ( process.argv ) {
for ( var i = 0; i < process.argv.length; i++ ) {
var arg
arg = process.argv[i]
switch ( arg ) {
case '--no-log':
options.logging = false
break
case '--test':
options.test = true
break
}
}
}
// MIDDLEWARE
// =============================================================================
app = express()
app.use( cors() )
app.use( bodyParser.urlencoded( { extended: true } ) )
app.use( bodyParser.json() )
app.use( cookieParser() )
app.use( expressSession({
secret: config.secretSauce,
resave: false,
saveUninitialized: false
}))
app.use( passport.initialize() )
app.use( passport.session() )
app.set( 'json spaces', 2 )
app.set( 'x-powered-by', false )
httpServer = http.Server( app )
port = process.env.PORT || config.port
passport.use( User.createStrategy() )
passport.serializeUser( User.serializeUser() )
passport.deserializeUser( User.deserializeUser() )
app.use( expressSession({
secret: 'foobarbazdiddlydingdongsdf]08st0agf/b',
resave: false,
saveUninitialized: false
}))
app.use( passport.initialize() )
app.use( passport.session() )
docs( app, mongoose )
// docket( app, mongoose )
// Combine query parameters with the request body, prioritizing the body
app.use( function ( request, response, next ) {
request.body = _.extend( request.query, request.body )
next()
})
// Add logging
if ( options.logging || options.test ) {
app.use( function ( request, response, next ) {
winston.info( '' )
winston.info( 'TIMESTAMP:', Date.now() )
winston.info( 'ENDPOINT:', request.originalUrl )
winston.info( 'METHOD:', request.method )
winston.info( 'DATA:', request.body )
next()
})
}
// ROUTER
// =============================================================================
// Create router
router = express.Router()
// ROUTES
// =============================================================================
app.get( '/badge/:rat', badge.get )
app.get( '/register', register.get )
app.post( '/register', register.post )
app.get( '/login', login.get )
app.post( '/login', passport.authenticate( 'local' ), login.post )
router.get( '/rats/:id', rat.get )
router.post( '/rats/:id', rat.post )
router.put( '/rats/:id', rat.put )
router.delete( '/rats/:id', notAllowed )
router.get( '/rats', rat.get )
router.post( '/rats', rat.post )
router.put( '/rescues', notAllowed )
router.delete( '/rescues', notAllowed )
router.get( '/rescues/:id', rescue.get )
router.post( '/rescues/:id', rescue.post )
router.put( '/rescues/:id', rescue.put )
router.delete( '/rescues/:id', notAllowed )
router.get( '/rescues', rescue.get )
router.post( '/rescues', rescue.post )
router.put( '/rescues', notAllowed )
router.delete( '/rescues', notAllowed )
router.get( '/search/rescues', rescue.get )
router.get( '/search/rats', rat.get )
// Register routes
app.use( express.static( __dirname + '/static' ) )
app.use( '/', router )
app.use( '/api', router )
// SOCKET
// =============================================================================
socket = new ws({ server: httpServer })
socket.on( 'connection', function ( client ) {
client.send( JSON.stringify({
data: 'Welcome to the Fuel Rats API. You can check out the docs at absolutely fucking nowhere because Trezy is lazy.',
type: 'welcome'
}))
client.on( 'message', function ( data ) {
data = JSON.parse( data )
winston.info( data )
})
})
// START THE SERVER
// =============================================================================
module.exports = httpServer.listen( port )
if ( !module.parent ) {
winston.info( 'Listening for requests on port ' + port + '...' )
}
|
JavaScript
| 0.999975 |
@@ -4146,45 +4146,8 @@
)%0A%0A
-app.get( '/register', register.get )%0A
app.
@@ -4186,39 +4186,8 @@
)%0A%0A
-app.get( '/login', login.get )%0A
app.
|
87db0af964ea1fa827a41b34f9b5bccfc9efba06
|
allow top-level http
|
index.js
|
index.js
|
var npa = require('npm-package-arg');
var guessVersion = require('./lib/guessVersion.js');
var Promise = require('bluebird');
module.exports = buildGraph;
module.exports.isRemote = isRemote;
function buildGraph(http, url) {
url = url || 'http://registry.npmjs.org/';
if (url[url.length - 1] !== '/') {
throw new Error('registry url is supposed to end with /');
}
var progress;
var cache = Object.create(null);
return {
createNpmDependenciesGraph: createNpmDependenciesGraph,
notifyProgress: function (cb) {
progress = cb;
}
};
function createNpmDependenciesGraph(packageName, graph, version) {
if (!packageName) throw new Error('Initial package name is required');
if (!graph) throw new Error('Graph data structure is required');
if (!version) version = 'latest';
var queue = [];
var processed = Object.create(null);
queue.push({
name: packageName,
version: version,
parent: null
});
return processQueue(graph);
function processQueue(graph) {
if (typeof progress === 'function') {
progress(queue.length);
}
var work = queue.pop();
var cached = cache[getCacheKey(work)];
if (cached) {
return new Promise(function(resolve) {
resolve(processRegistryResponse(cached));
});
}
if (isRemote(work.version)) {
// TODO: This will not download remote dependnecies (e.g. git-based)
return new Promise(function(resolve) {
resolve(processRegistryResponse({data: {}}));
});
}
var escapedName = npa(work.name).escapedName;
if (!escapedName) {
throw new Error('TODO: Escaped name is missing for ' + work.name);
}
return http(url + escapedName).then(processRegistryResponse);
function processRegistryResponse(res) {
cache[getCacheKey(work)] = res;
traverseDependencies(work, res.data);
if (queue.length) {
// continue building the graph
return processQueue(graph);
}
return graph;
}
}
function getCacheKey(work) {
var packageIsRemote = isRemote(work.version);
var cacheKey = work.name;
return packageIsRemote ? cacheKey + work.version : cacheKey
}
function traverseDependencies(work, packageJson) {
var version, pkg, id;
if (isRemote(work.version)) {
version = '';
pkg = packageJson;
id = work.version;
} else {
version = guessVersion(work.version, packageJson);
pkg = packageJson.versions[version];
id = pkg._id;
}
// TODO: here is a good place to address https://github.com/anvaka/npmgraph.an/issues/4
var dependencies = pkg.dependencies;
graph.beginUpdate();
graph.addNode(id, pkg);
if (work.parent && !graph.hasLink(work.parent, id)) {
graph.addLink(work.parent, id);
}
graph.endUpdate();
if (processed[id]) {
// no need to enqueue this package again - we already downladed it before
return;
}
processed[id] = true;
if (dependencies) {
Object.keys(dependencies).forEach(addToQueue);
}
function addToQueue(name) {
queue.push({
name: name,
version: dependencies[name],
parent: id
})
}
}
}
}
function isRemote(version) {
return typeof version === 'string' && (
(version.indexOf('git') === 0) ||
(version.indexOf('http') === 0) ||
(version.indexOf('file') === 0)
);
}
|
JavaScript
| 0.000001 |
@@ -1426,18 +1426,18 @@
e depend
-n
e
+n
cies (e.
@@ -1566,32 +1566,32 @@
%7D);%0A %7D%0A%0A
-
var escape
@@ -1622,24 +1622,567 @@
scapedName;%0A
+ if (!escapedName && isHttp(work.name)) %7B%0A return http(work.name).then(res =%3E %7B%0A if (res.data) %7B%0A // TODO: Validate pkg json%0A var pkgJSON = res.data;%0A pkgJSON._id = pkgJSON.name + '@' + pkgJSON.version;%0A var versions = %7B%7D;%0A versions%5BpkgJSON.version%5D = pkgJSON;%0A%0A return processRegistryResponse(%7B%0A data: Object.assign(%7B%7D, %7B versions: versions %7D)%0A %7D);%0A %7D%0A throw new Error('Unexpected response');%0A %7D);%0A %7D%0A
if (!e
@@ -3597,16 +3597,17 @@
dy downl
+o
aded it
@@ -3937,16 +3937,117 @@
%0A %7D%0A%7D%0A%0A
+function isHttp(version) %7B%0A return typeof version === 'string' && version.match(/%5Ehttps?:%5C/%5C//);%0A%7D%0A%0A
function
|
8fc81855575b3962d35fabcbebe289b8ced9ef40
|
Add headers option to request().
|
index.js
|
index.js
|
/*!
* Pact
* Copyright 2011 Yahoo! Inc.
* Licensed under the BSD license.
*/
/**
* Dependencies.
*/
var assert = require('assert');
var http = require('./lib/http');
var STATUS_CODES = require('http').STATUS_CODES;
/**
* A starting server port number.
*/
var _port = 8099;
/**
* Factory for server port numbers.
*
* @return {Number} port A new port number.
*/
function getPort() {
return _port++;
}
/**
* Return a function that makes an HTTP request
* according to what's specified in the provided `req`
* object.
*
* Relative 302 redirects will be followed.
*
* You can specify:
*
* - url: The path to request. Defaults to a path as the second word of
* a context.
* - method: Defaults to GET.
* - data: Request body for POST.
*
* Instead of specifying `url` in `req`, you can make it the second word of
* your context. This lets you omit `req` completely, for example:
*
* "when /foo/bar/baz is requested" : {
* topic : request(),
* "should succeed" : code(200)
* }
*
* Your test functions will recieve an object containing:
*
* - body: The response body, which is an object if the response was
* application/json.
* - status: HTTP status code.
* - headers: HTTP headers as an object, with headers in lowercase.
*
* A topic function.
*
* For an example test function, {@see code}.
*
* @param {Object} req Request object.
* @return {Function} Topic function that makes the request.
*/
function request(req) {
var path, options = {
host: 'localhost',
method: 'GET'
};
if (req) {
if ('url' in req) path = options.path = req.url;
if ('data' in req) options.body = req.data;
if ('method' in req) options.method = req.method;
}
return function(lastTopic) {
var vow = this;
// try to find port number
var port = Array.prototype.slice.call(arguments, -1)[0];
if (!isNaN(port))
options.port = port;
else throw new Error('Unable to determine port from topic.');
if ('function' === typeof path)
options.path = path(lastTopic);
else if (!path)
options.path = vow.context.name.split(/ +/)[1];
http.request(
options
).on('response', function X(res, results) {
var err = null;
if (res.statusCode === 302) { // handle redirects
if (options._302) {
err = 'Redirect loop';
} else {
var location = res.headers.location;
if (location.indexOf('/') === 0) {
// relative path, don't handle absolute
options.path = location;
options._302 = true;
return http.request(options).on('response', X);
}
}
}
vow.callback(err, {
body: results,
status: res.statusCode,
headers: res.headers
});
});
}
}
/**
* Return a function that starts a `http.Server` listening on 127.0.0.1.
*
* Your test functions will recieve the port the server is listening on.
*
* A topic function.
*
* @param {Object} server `http.Server` instance.
* @param {Number} port Optional. Port to listen on.
* @return {Function} Topic function that starts the server.
*/
function httpify(server, port) {
port = port || getPort();
return function() {
var vows = this;
server.listen(port, '127.0.0.1', function(err) {
vows.callback(err, port);
});
};
}
/**
* Return a function that asserts that `status` matches httpify's status.
*
* A test function.
*
* @see httpify
* @param {Number} status Expected HTTP status code.
* @return {Function} Test function that checks the status.
*/
function code(status) {
return function(lastTopic) {
assert.strictEqual(lastTopic.status, status,
'Expected ' + status +
' ' + STATUS_CODES[status] +
', received: ' + lastTopic.status +
' ' + STATUS_CODES[lastTopic.status] +
'.\n' + lastTopic.body
);
};
}
/**
* Export these functions.
*/
module.exports = {
code: code,
request: request,
httpify: httpify
};
|
JavaScript
| 0 |
@@ -756,16 +756,89 @@
r POST.%0A
+ * - headers: HTTP request headers object.%0A *%0A * These are all optional.%0A
*%0A * In
@@ -1830,16 +1830,77 @@
method;%0A
+ if ('headers' in req) options.headers = req.headers;%0A
%7D%0A
|
e4bfb406d4bcbee2a130c2a0fe5ba7ec1186c602
|
remove console.log
|
index.js
|
index.js
|
module.exports = function blacklist (src) {
var copy = {}, filter = arguments[1]
if (typeof filter === 'string') {
filter = {}
for (var i = 1; i < arguments.length; i++) {
filter[arguments[i]] = true
}
} console.log(filter, arguments)
for (var key in src) {
// blacklist?
if (filter[key]) continue
copy[key] = src[key]
}
return copy
}
|
JavaScript
| 0.000004 |
@@ -225,39 +225,8 @@
%0A %7D
- console.log(filter, arguments)
%0A%0A
|
14d7fea999c608cea41e9e001ce60f93d887f8cc
|
Fix index function
|
index.js
|
index.js
|
var debug = require('debug');
module.exports = function (app) {
return new Connectr(app);
};
var merge = function(a, b){
if (a && b) {
for (var key in b) {
a[key] = b[key];
}
}
return a;
};
module.exports.patch = function (app) {
if (app._use)
throw new Error('This app is already patched by Connectr.');
app._use = app.use;
app.app = app;
app = merge(app, Connectr.prototype);
return app;
};
var Connectr = function (app) {
this.app = app;
};
Connectr.prototype.use = function (route, fn) {
//this.currentFn = fn
//
//forward call to connect.use
//lookup connect.stack if there is a fn with before or after properties
//and move it at right place
//once it is moved at right position, remove the before/after property
//clear this.before and this.after
if ('string' != typeof route) {
fn = route;
}
// save currentFn in case there is a .as call after .use
this.currentFn = fn;
// save before/after as properties attached to the fn
if (this._first)
fn._first = true;
if (this._before)
fn._before = this._before;
if (this._after)
fn._after = this._after;
delete this._first;
delete this._before;
delete this._after;
// forward call to app.use
if (this.app._use)
this.app._use.apply(this.app, arguments);
else
this.app.use.apply(this.app, arguments);
// lookup connect.stack if there is a fn with before or after properties
// and move it at right place
// @todo: optimize
function order_stack (stack) {
// Find a handle with a before or after property
for (var i = 0; i < stack.length; i++) {
var handle = stack[i].handle;
if (handle._first) {
// remove handle from current position
var mid = stack.splice(i, 1)[0];
// insert it at begining of stack
stack.unshift(mid);
// remove property so we don't order it again later
delete handle._first;
// for debugging
handle['_moved_first'] = true;
// Continue ordering for remaining handles
return order_stack (stack);
}
else if (handle._before || handle._after) {
if (handle._before) {
var position = '_before';
}
else if (handle._after) {
var position = '_after';
}
var label = handle[position];
//console.log(label);
for (var j = 0; j < stack.length; j++) {
if (stack[j].handle.label === label) {
// insert before index = j
// insert after index = j + 1
var new_index = j;
if (position == '_after') new_index++;
// move handle in new position
// http://stackoverflow.com/questions/5306680/move-an-array-element-from-one-array-position-to-another
stack.splice(new_index, 0, stack.splice(i, 1)[0]);
// remove _before/_after property so we don't order ad infinitum
handle['_moved' + position] = handle[position]; // for debugging
break;
}
}
delete handle[position];
// Continue ordering for remaining handles
return order_stack (stack);
}
}
// didn't find any handle with a before/after property => done ordering
return true;
}
order_stack(this.app.stack);
return this;
};
/**
* Removes middleware labeled `label`
*
* @param {String} label
*/
Connectr.prototype.remove = function (label) {
for (var i = 0; i < this.app.stack.length; i++) {
if (this.app.stack[i].handle.label === label) {
this.app.stack.splice(i, 1);
}
}
return this;
};
Connectr.prototype.index = function (index) {
this.currentFn = this.app.stack[i].handle;
return this;
};
Connectr.prototype.as = function (label) {
try {
this.currentFn.label = label;
return this;
}
catch (e) {
throw new Error('.as() must be used after a .use() call.');
}
};
/**
* Adds a middleware at the beginning of the stack
*/
Connectr.prototype.first = function () {
this._first = true;
return this;
};
Connectr.prototype.before = function (label) {
this._before = label;
return this;
};
Connectr.prototype.after = function (label) {
this._after = label;
return this;
};
|
JavaScript
| 0.000084 |
@@ -3691,32 +3691,36 @@
this.app.stack%5Bi
+ndex
%5D.handle;%0A retu
|
a7f9fddf54706c4de899a3e1a28c95f918e7afa5
|
Support math block
|
index.js
|
index.js
|
#! /usr/bin/env node
const fetch = require("node-fetch");
const url = "http://qiita.com/api/v2/items/";
const item_id = process.argv[2];
const template = {
ipynb: {
"cells": null,
"metadata": {
"kernelspec": {
"display_name": "Python 2",
"language": "python",
"name": "python2"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.10"
}
},
"nbformat": 4,
"nbformat_minor": 1
},
markdownCell: {
"cell_type": "markdown",
"metadata": {},
"source": null
},
codeCell: {
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": null
}
};
fetch(url + item_id)
.then(res => {
return res.json();
})
.then(json => {
const markdown = json.body;
const ipynb = md2ipynb(markdown);
console.log(JSON.stringify(ipynb, null, " "));
})
.catch(err => console.error(err));
/**
* @param {String} markdown
* @return {Object}
*/
function md2ipynb(markdown) {
const lines = markdown.split("\n");
const ipynb = Object.assign({}, template.ipynb);
let isCodeBlock = false;
let cell = Object.assign({}, template.markdownCell);
ipynb.cells = [];
cell.source = [];
lines.forEach(line => {
// starting line of code block
if (line.match(/^```py/)) {
ipynb.cells.push(cell);
cell = Object.assign({}, template.codeCell);
cell.source = [];
isCodeBlock = true;
// ending line of code block
} else if (isCodeBlock && line.match(/^```$/)) {
ipynb.cells.push(cell);
cell = Object.assign({}, template.markdownCell);
cell.source = [];
isCodeBlock = false;
// inside code block
} else if (isCodeBlock) {
cell.source.push(line + "\n");
// normal block
} else {
cell.source.push(line + "\n");
}
});
ipynb.cells.push(cell);
return ipynb;
}
exports.md2ipynb = md2ipynb;
|
JavaScript
| 0.000001 |
@@ -1290,16 +1290,42 @@
false;%0A
+%09let isMathBlock = false;%0A
%09let cel
@@ -1370,16 +1370,16 @@
nCell);%0A
-
%0A%09ipynb.
@@ -1616,16 +1616,40 @@
= true;
+%0A%09%09%09isMathBlock = false;
%0A%0A%09%09// e
@@ -1843,24 +1843,48 @@
ock = false;
+%0A%09%09%09isMathBlock = false;
%0A%0A%09%09// insid
@@ -1924,16 +1924,16 @@
lock) %7B%0A
-
%09%09%09cell.
@@ -1959,16 +1959,564 @@
%22%5Cn%22);%0A%0A
+%09%09// starting line of math block%0A%09%09%7D else if (line.match(/%5E%60%60%60math/)) %7B%0A%09%09%09ipynb.cells.push(cell);%0A%09%09%09cell = Object.assign(%7B%7D, template.markdownCell);%0A%09%09%09cell.source = %5B%5D;%0A%09%09%09isCodeBlock = false;%0A%09%09%09isMathBlock = true;%0A%0A%09%09// ending line of math block%0A%09%09%7D else if (isMathBlock && line.match(/%5E%60%60%60$/)) %7B%0A%09%09%09ipynb.cells.push(cell);%0A%09%09%09cell = Object.assign(%7B%7D, template.markdownCell);%0A%09%09%09cell.source = %5B%5D;%0A%09%09%09isCodeBlock = false;%0A%09%09%09isMathBlock = false;%0A%0A%09%09// inside math block%0A%09%09%7D else if (isMathBlock) %7B%0A%09%09%09cell.source.push(%22$$ %22 + line + %22 $$%5Cn%22);%0A%0A
%09%09// nor
|
ad82bea368ebe49fec3eeac9e04dee0fb43155df
|
fix performance.timing check
|
index.js
|
index.js
|
/**
* Initialize the environment
*/
var envs = require('envs');
if (window.env) envs.set(window.env);
/**
* Module dependencies
*/
var angular = require('angular');
var hyper = require('ng-hyper');
var feature = require('ng-feature');
var logger = require('./lib/logger');
var hyperagent = require('hyperagent');
var token = require('access-token');
var each = require('each');
var featureUI = require('feature-ui');
/**
* Expose creating an app
*/
exports = module.exports = function(mod, deps) {
if (!deps) return angular.module(mod);
deps.push(hyper.name);
deps.push(feature.name);
var app = angular.module(mod, deps);
app.name = mod;
return app;
};
/**
* Start an app with options
*/
exports.run = function(app, options, loadPartial) {
// initialize the logger
var log = window.metric = logger(app.name, {
collector: options.collector || envs('SYSLOG_COLLECTOR'),
context: options.context || {}
});
// initialize the hyperagent client
hyperagent.set(token.auth());
hyperagent.profile = log.profile.bind(log);
// TODO initialize in-progress
// TODO initialize subscriptions
// set the default routes
var routes = options.routes || {'/': 'index'};
// initialize the routes
loadPartial = options.loader || loadPartial;
var routeConfig = {};
each(routes, function(path, opts) {
if (typeof opts === 'string') opts = {templateUrl: opts, _route: opts};
// load the template
if (loadPartial && opts.templateUrl) opts.templateUrl = loadPartial(opts.templateUrl);
routeConfig[path] = opts;
});
app.config([
'$routeProvider',
'$locationProvider',
function($routeProvider, $locationProvider) {
each(routeConfig, function(path, opts) {
// Handle a catch all here
if (path === '_') return $routeProvider.otherwise(opts);
$routeProvider.when(path, opts);
});
$locationProvider.html5Mode(true).hashPrefix('!');
}
]);
app.run([
'$rootScope',
'$location',
function($rootScope, $location) {
var done;
$rootScope.$on('$routeChangeStart', function() {
done = log.profile('route_time');
});
$rootScope.$on('$routeChangeSuccess', function(currentRoute, conf) {
if (options.analytics) analytics.pageview();
if (currentRoute.title) $rootScope.title = currentRoute.title;
if (conf.$$route._route) $rootScope._route = conf.$$route._route;
done({path: $location.path()});
});
}
]);
/**
* Show the feature UI
*/
setTimeout(function() {
featureUI(options.feature);
if (!window.performance && !window.performance.timing) return;
var t = performance.timing;
var timing = {
'measure#performance.connect': t.connectEnd - t.connectStart + 'ms',
'measure#performance.domain': t.domainLookupEnd - t.domainLookupStart + 'ms',
'measure#performance.response': t.responseEnd - t.requestStart + 'ms',
'measure#performance.dom': t.domComplete - t.domLoading + 'ms'
};
log(timing);
}, 0);
}
|
JavaScript
| 0.000001 |
@@ -2594,16 +2594,17 @@
ature);%0A
+%0A
if (
@@ -2623,18 +2623,18 @@
ormance
-&&
+%7C%7C
!window
|
048332b15cbb3f501ec9a88fece3e4ffaeee950f
|
fix winning
|
app/models/auction.js
|
app/models/auction.js
|
var couch = require('../couch.js');
var userModel = require('../models/user.js');
var uuid = require('node-uuid');
var fs = require('fs');
var auctionModel = {
create: function(prop) {
this._id = uuid.v4();
this.auctioneer_id = prop.auctioneer_id;
this.auction_name = prop.auction_name;
this.date_created = new Date();
this.end_date = this.calculateEndDate(prop.end_date);
this.start_bid = prop.start_bid;
this.step = prop.step;
this.image_path = prop.image_path;
this.bid_count = 0;
},
toJSON: function() {
return {
_id: this._id,
auctioneer_id: this.auctioneer_id,
auction_name: this.auction_name,
date_created: this.date_created.toISOString(),
end_date: this.end_date.toISOString(),
start_bid: this.start_bid,
step: this.step,
image_path: this.image_path,
bid_count: this.bid_count
};
},
save: function(callback) {
couch.save('auction', this.toJSON(), function(err, data) {
if (err) {
return false
}
callback(data._id);
return true;
});
},
validateBid: function(auction_id, user_id, callback) {
// Fetch the record from the DB before updating it
couch.id('auction', auction_id, function(err, data) {
if (err) {
callback(err);
} else if (user_id === data.auctioneer_id) {
callback('You are not allowed to participate in your own auction!', data);
} else if (new Date() > new Date(data.end_date)) {
callback('This auction has ended!', data);
} else {
callback(null, data);
}
});
},
saveBid: function(auction_data, revision, user_id, callback) {
auction_data._rev = revision;
auction_data.current_bidder = user_id;
auction_data.current_bid =
auction_data.current_bid ?
parseInt(auction_data.current_bid) + parseInt(auction_data.step) :
auction_data.start_bid;
auction_data.bid_count += 1;
couch.save('auction', auction_data, function(err, doc) {
if (err) {
console.log('WAAHHH');
console.log(err);
callback(err)
}
callback(null, auction_data);
});
},
// helper date function
// it expects time in 24 hour format "HH:MM"
calculateEndDate: function (endTimeString) {
var hour = parseInt(endTimeString.slice(0,2));
var minute = parseInt(endTimeString.slice(3,5));
var x = new Date();
return new Date(x.getFullYear(), x.getMonth(), (((x.getHours()<=hour&&x.getMinutes()<minute)||x.getHours()<hour)?x.getDate():x.getDate()+1), hour, minute);
},
// helper date function
// format TZ to human readable
formatDate: function(tz) {
var date = new Date(tz);
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
};
module.exports = auctionModel;
|
JavaScript
| 0.000004 |
@@ -1956,16 +1956,196 @@
t += 1;%0A
+ // TODO: remove this property from ever being set in the auction model, it should be in app level model for auction details (once extant)%0A auction_data.winning = undefined;%0A
couc
|
763172ac8bac1c2f57e7fc3e4d2848fb2a24db34
|
fix watch mode in webpack 4
|
index.js
|
index.js
|
/**
* @author Eoin Hennessy
* @author Erik Desjardins
* See LICENSE file in root directory for full license.
*/
'use strict';
var path = require('path');
var loaderUtils = require('loader-utils');
var SingleEntryPlugin = require('webpack').SingleEntryPlugin;
var InertEntryPlugin = require('inert-entry-webpack-plugin');
module.exports = function() {};
module.exports.pitch = function(request) {
var callback = this.async();
var options = loaderUtils.getOptions(this) || {};
var context = options.context || this.rootContext;
var name = options.name || path.basename(this.resourcePath);
var filename = loaderUtils.interpolateName(this, name, { context: context });
var outputDir = options.path || '.';
var plugins = options.plugins || [];
if (options.inert) {
plugins = [new InertEntryPlugin()].concat(plugins);
}
// name of the entry and compiler (in logs)
var debugName = loaderUtils.interpolateName(this, '[name]', {});
// create a child compiler (hacky)
var compiler = this._compilation.createChildCompiler(debugName, { filename: filename }, plugins);
new SingleEntryPlugin(this.context, '!!' + request, debugName).apply(compiler);
// add a dependency on the entry point of the child compiler, so watch mode works
this.addDependency(this.resourcePath);
// like compiler.runAsChild(), but remaps paths if necessary
// https://github.com/webpack/webpack/blob/f6e366b4be1cfe2770251a890d93081824789209/lib/Compiler.js#L206
compiler.compile(function(err, compilation) {
if (err) return callback(err);
this.parentCompilation.children.push(compilation);
for (const name of Object.keys(compilation.assets)) {
this.parentCompilation.assets[path.join(outputDir, name)] = compilation.assets[name];
}
// the first file in the first chunk of the first (should only be one) entry point is the real file
// see https://github.com/webpack/webpack/blob/f6e366b4be1cfe2770251a890d93081824789209/lib/Compiler.js#L215
var outputFilename = compilation.entrypoints.values().next().value.chunks[0].files[0];
callback(null, 'module.exports = __webpack_public_path__ + ' + JSON.stringify(path.join(outputDir, outputFilename)) + ';')
}.bind(compiler));
};
|
JavaScript
| 0 |
@@ -1240,16 +1240,140 @@
e works%0A
+%09// ...this format is required for webpack 4%0A%09this.addDependency(request);%0A%09// ...and this format is required for webpack 5%0A
%09this.ad
|
228623231192377e310f313c83649424513fd6a9
|
Fix handling of non-paragraphs on selection edges.
|
index.js
|
index.js
|
import AbstractCommand from 'abstract-command';
class PaddingCommand extends AbstractCommand {
constructor({ direction = 'auto', delta = 50, max = 200, min = 0 } = {}, root = document.documentElement, doc: Document = root.ownerDocument) {
super(doc);
this.direction = direction;
this.delta = delta;
this.max = max;
this.min = min;
this.root = root;
this.document = doc;
}
_getProp(paragraph) {
let direction = this.direction;
// TODO: properly handle LTR here
if (direction == 'auto') {
direction = 'left';
}
return `padding-${direction}`;
}
_setPadding(paragraph, padding) {
let value = `${padding}px`;
let prop = this._getProp(paragraph);
// attempt to clear padding in inline style and check if the computed
// value matches the desired padding. If it does, keep it blank, since
// the padding specified on the stylesheet is the correct one.
paragraph.style[prop] = '';
let style = window.getComputedStyle(paragraph);
if (style[prop] == value) return;
paragraph.style[prop] = value;
}
_getPadding(paragraph) {
let prop = this._getProp(paragraph);
let padding = paragraph.style[prop];
if (padding && padding.match('[0-9\.]+px')) return parseInt(padding);
let style = window.getComputedStyle(paragraph);
return parseInt(style[prop]) || 0;
}
_isParagraph(node) {
return node.nodeName == 'P';
}
_findParagraph(node) {
while (node && node != this.root) {
if (this._isParagraph(node)) return node;
node = node.parentNode;
}
return null;
}
_findParagraphs(range) {
let firstParagraph = this._findParagraph(range.startContainer);
let lastParagraph = this._findParagraph(range.endContainer);
if (firstParagraph.parentNode != lastParagraph.parentNode) {
// we don't handle this case yet
return [];
}
let result = [];
for (let node = firstParagraph; node != lastParagraph; node = node.nextSibling) {
if (this._isParagraph(node)) {
result.push(node);
}
}
result.push(lastParagraph);
return result;
}
_execute(range) {
if (!range) return;
let paragraphs = this._findParagraphs(range);
for (let paragraph of paragraphs) {
let padding = this._getPadding(paragraph)
this._setPadding(paragraph, Math.min(Math.max(padding + this.delta, this.min), this.max));
}
}
_queryEnabled(range) {
if (!range) return false;
let paragraphs = this._findParagraphs(range);
if (paragraphs.length == 0) return false;
let values = paragraphs.map((paragraph) => this._getPadding(paragraph) + this.delta);
return values.some((value) => value >= this.min && value <= this.max);
}
_queryState(range) {
return false;
}
}
export default PaddingCommand;
|
JavaScript
| 0 |
@@ -1439,25 +1439,32 @@
%0A _find
-Paragraph
+ClosestOrTopmost
(node) %7B
@@ -1548,24 +1548,77 @@
eturn node;%0A
+ if (node.parentNode == this.root) return node;%0A
node =
@@ -1703,25 +1703,20 @@
et first
-Paragraph
+Node
= this.
@@ -1716,33 +1716,40 @@
= this._find
-Paragraph
+ClosestOrTopmost
(range.start
@@ -1772,25 +1772,20 @@
let last
-Paragraph
+Node
= this.
@@ -1789,25 +1789,32 @@
is._find
-Paragraph
+ClosestOrTopmost
(range.e
@@ -1840,25 +1840,20 @@
f (first
-Paragraph
+Node
.parentN
@@ -1863,25 +1863,20 @@
!= last
-Paragraph
+Node
.parentN
@@ -1990,25 +1990,20 @@
= first
-Paragraph
+Node
; node !
@@ -2008,25 +2008,20 @@
!= last
-Paragraph
+Node
; node =
@@ -2115,24 +2115,65 @@
%7D%0A %7D%0A
+ if (this._isParagraph(lastNode)) %7B%0A
result.p
@@ -2184,19 +2184,20 @@
last
-Paragraph);
+Node);%0A %7D
%0A
|
e43415c6ce8db8bf42f0608eef61b6304eb9ac31
|
Refactor exports
|
index.js
|
index.js
|
import strings from './src/i18n/strings';
export { default as Validator } from './src/validator';
export function load(app) {
if (app.i18n()) {
app.i18n().strings(strings);
}
}
|
JavaScript
| 0.000001 |
@@ -1,22 +1,24 @@
import
-strings
+Validator
from '.
@@ -26,88 +26,63 @@
src/
-i18n/strings';%0A%0Aexport %7B default as Validator %7D from './src/validator';%0A%0Aexport
+validator';%0Aimport strings from './src/i18n/strings';%0A%0A
func
@@ -157,8 +157,41 @@
;%0A %7D%0A%7D%0A
+%0Aexport %7B%0A Validator,%0A load%0A%7D;%0A
|
9fc473a9161af61027173da7ea008a991c0e345b
|
Replace opaque 0, 1, 2 with transparent "off", "warn", "error" (#23)
|
index.js
|
index.js
|
'use strict';
module.exports = {
env: {
es6: true,
},
extends: ['eslint:recommended', require.resolve('eslint-config-prettier')],
parserOptions: {
ecmaVersion: 2017,
sourceType: 'module',
},
plugins: ['liferayportal', 'no-only-tests'],
rules: {
'liferayportal/arrowfunction-newline': 0,
'no-console': 0,
'no-constant-condition': 0,
'no-empty': 0,
'no-only-tests/no-only-tests': 'error',
'no-unused-expressions': 'error',
'no-process-env': 0,
'comma-spacing': 0,
indent: ['error', 'tab'],
'keyword-spacing': 1,
'max-len': [
2,
{
code: 80,
comments: 120,
ignoreRegExpLiterals: true,
ignoreStrings: true,
ignoreTemplateLiterals: true,
ignoreUrls: true,
tabWidth: 4,
},
],
'no-tabs': 0,
'arrow-parens': 0, // Setting for Prettier
},
};
|
JavaScript
| 0.000072 |
@@ -289,25 +289,29 @@
n-newline':
-0
+'off'
,%0A%09%09'no-cons
@@ -316,17 +316,21 @@
nsole':
-0
+'off'
,%0A%09%09'no-
@@ -350,17 +350,21 @@
ition':
-0
+'off'
,%0A%09%09'no-
@@ -371,17 +371,21 @@
empty':
-0
+'off'
,%0A%09%09'no-
@@ -476,17 +476,21 @@
s-env':
-0
+'off'
,%0A%09%09'com
@@ -502,17 +502,21 @@
acing':
-0
+'off'
,%0A%09%09inde
@@ -558,17 +558,22 @@
acing':
-1
+'warn'
,%0A%09%09'max
@@ -584,17 +584,23 @@
': %5B%0A%09%09%09
-2
+'error'
,%0A%09%09%09%7B%0A%09
@@ -785,17 +785,21 @@
-tabs':
-0
+'off'
,%0A%09%09'arr
@@ -810,17 +810,21 @@
arens':
-0
+'off'
, // Set
|
071ad1e281590d30698dadf2ec07520d2099b0fa
|
use this.field and this.log
|
index.js
|
index.js
|
'use strict';
var _ = require('lodash');
var nex = require('nex-api');
var rimraf = require('rimraf');
var path = require('path');
var fs = require('fs');
var proc = require('child_process');
var color = require('colors');
var handler = module.exports = new nex.Handler('linkDependencies');
/**
* @override
*/
handler.do = function (pkg) {
_.each(pkg.linkDependencies, function (dir, name) {
process.chdir(dir);
this.log.info('npm install', name, 'in'.magenta, dir);
proc.spawnSync('npm',[ 'install' ], { cwd: dir });
process.chdir(global.cwd);
let linkName = path.resolve(process.cwd(), 'node_modules', name);
this.log.info('link', path.relative(process.cwd(), linkName), '->', dir);
rimraf.sync(linkName);
fs.symlinkSync(path.resolve(dir), linkName);
}, this);
};
/**
* @override
*/
handler.undo = function (pkg) {
_.each(pkg.linkDependencies, function (dir, name) {
process.chdir(dir);
rimraf.sync('node_modules');
process.chdir(global.cwd);
rimraf.sync(path.resolve(process.cwd(), 'node_modules', name));
});
};
|
JavaScript
| 0 |
@@ -218,17 +218,16 @@
ors');%0A%0A
-%0A
var hand
@@ -350,33 +350,28 @@
each(pkg
-.linkDependencies
+%5Bthis.field%5D
, functi
@@ -867,25 +867,20 @@
(pkg
-.linkDependencies
+%5Bthis.field%5D
, fu
@@ -1060,14 +1060,20 @@
e));%0A %7D
+, this
);%0A%7D;%0A
|
b0d75e5be09e14fd69957192725c0eed51ac2744
|
add once function
|
index.js
|
index.js
|
var http = require('http')
var request = require('request')
var omit = require('lodash.omit')
var parseUrl = require('url').parse
var decamelize = require('decamelize')
var PORT = 8488
var REDIRECT_URI = 'http://localhost:' + PORT
var BASE_URL = 'https://accounts.google.com/o/oauth2/auth'
var GOOGLE_OAUTH2_TOKEN_URL = 'https://accounts.google.com/o/oauth2/token'
var getCode = exports.getCode = function (params, callback) {
var url = buildUrl(params)
return function (nightmare) {
startCallbackServer(callback)
nightmare
.viewport(800, 1600)
.goto(url)
.wait('input[type=email]')
.type('input[type=email]', params.email)
.type('input[type=password]', params.password)
.click('input[type=submit]')
.wait()
.goto(url)
.wait()
.exists('#signin-action', handleAccess)
function handleAccess(exists) {
var account = params.useAccount || ''
if (exists) {
nightmare
.wait(500)
.click('#account-' + account + ' > a')
}
nightmare
.wait('#submit_approve_access')
.wait(1500)
.click('#submit_approve_access')
.wait()
}
}
}
var getToken = exports.getToken = function (params, callback) {
return getCode(params, function (err, code) {
if (err) return callback(err)
if (!params.clientSecret) {
throw missingParam('clientSecret')
}
var values = {
code: code,
client_id: params.clientId,
client_secret: params.clientSecret,
redirect_uri: REDIRECT_URI,
grant_type: 'authorization_code'
}
request({
method: 'POST',
uri: GOOGLE_OAUTH2_TOKEN_URL,
form: values,
json: true
}, handler)
function handler(err, res, tokens) {
if (!err && tokens && tokens.expires_in) {
tokens.expiry_date = ((new Date()).getTime() + (tokens.expires_in * 1000))
tokens = omit(tokens, 'expires_in')
}
if (!err && tokens.error) {
err = new Error(tokens.error_description)
err.code = tokens.error
tokens = null
}
callback(err, tokens)
}
})
}
function startCallbackServer(callback) {
var server = http.createServer(function (req, res) {
res.writeHead(200)
res.end()
server.close()
server = null
var query = parseUrl(req.url, true).query
if (!query || !query.code) {
return callback(new Error('Missing OAuth2 code in callback'))
}
callback(null, query.code)
})
server.listen(PORT, function (err) {
if (err) return callback(err)
// be sure we kill the server in case of timeout/error
setTimeout(function () {
if (server) {
server.close()
}
}, 20 * 1000)
})
}
function buildUrl(options) {
var params = defineDefaultParams(options)
var query = Object.keys(params).map(function (key) {
return key + '=' + encodeURIComponent(params[key])
}).join('&')
return BASE_URL + '?' + query
}
function defineDefaultParams(params) {
params = validate(normalize(params))
if (!params.redirect_uri) {
params.redirect_uri = REDIRECT_URI
}
if (!params.access_type) {
params.access_type = 'offline'
}
params.response_type = 'code'
return omitPrivateParams(params)
}
function omitPrivateParams(params) {
return omit(params, 'email', 'password', 'client_secret', 'use_account')
}
function validate(params) {
['email', 'password', 'scope', 'client_id'].forEach(function (name) {
if (!params[name]) {
throw missingParam(name)
}
})
return params
}
function normalize(params) {
var buf = {}
Object.keys(params).forEach(function (key) {
return buf[decamelize(key)] = params[key]
})
return buf
}
function missingParam(name) {
return new TypeError('Missing required param: ' + name)
}
|
JavaScript
| 0.000017 |
@@ -3814,12 +3814,153 @@
' + name)%0A%7D%0A
+%0Afunction once(fn) %7B%0A var one = true%0A return function () %7B%0A if (call) %7B%0A call = false%0A fn.apply(null, arguments)%0A %7D%0A %7D%0A%7D%0A%0A
|
5474277f6b10911a2776c979631b88b05b776cdf
|
Declare `i` before using in `optimizeFunction`
|
index.js
|
index.js
|
var estraverse = require('estraverse'),
escope = require('escope'),
tcoLabel = {
type: 'Identifier',
name: 'tco'
};
function equals(a, b, s) {
var equal,
k;
if(typeof a != typeof b)
return false;
if(typeof a == 'object' || typeof a == 'array') {
equal = true;
for(k in a) {
equal = equal && equals(a[k], b[k], s);
}
for(k in b) {
equal = equal && equals(a[k], b[k], s);
}
return equal;
}
return a === b;
}
function nodeAncestry(f, ast) {
var ancestry = [],
result;
estraverse.traverse(ast, {
enter: function(n) {
if(n == f) result = ancestry.slice();
if(result) return;
ancestry.push(n);
},
leave: function() {
ancestry.pop();
}
});
return result;
}
function returnValue(r, resultIdentifier) {
return {
type: 'BlockStatement',
body: [{
type: 'ExpressionStatement',
expression: {
type: 'AssignmentExpression',
operator: '=',
left: resultIdentifier,
right: r.argument
}
}, {
type: 'BreakStatement',
label: tcoLabel
}]
};
}
function isFunctionNode(n) {
return ['FunctionDeclaration', 'FunctionExpression'].indexOf(n.type) != -1;
}
function tailCall(f, r, scope) {
var tmpVars = [],
assignments = [],
i,
identifier;
for(i = 0; i < f.params.length; i++) {
identifier = {
type: 'Identifier',
name: freshNameWhile('__' + f.params[i].name, function(name){ return !inScope(scope, name); })
};
tmpVars.push({
type: 'VariableDeclarator',
id: identifier,
init: r.argument['arguments'][i]
});
assignments.push({
type: 'ExpressionStatement',
expression: {
type: 'AssignmentExpression',
operator: '=',
left: f.params[i],
right: identifier
}
});
}
return {
type: 'BlockStatement',
body: [{
type: 'VariableDeclaration',
declarations: tmpVars,
kind: 'var'
}].concat(assignments).concat({
type: 'ContinueStatement',
label: tcoLabel
})
};
}
function inScope(scope, name){
if(scope.set.has(name)) return true;
for (var i = 0, iz = scope.through.length; i < iz; ++i) {
if (scope.through[i].identifier.name === name) {
return true;
}
}
return false;
};
function freshNameWhile(prefix, test){
name = prefix;
// TODO: the size of this name can be optimised with a smarter algorithm
while(!test(name)) name += "$";
return name;
}
function optimizeFunction(f, ast, scope) {
var id = functionId(f, ast),
block = f.body,
ancestry = [];
var resultIdentifier = {
type: 'Identifier',
name: freshNameWhile('__tcor', function(name) {
return !inScope(scope, name);
})
};
estraverse.replace(block, {
enter: function(n) {
ancestry.push(n);
if(!n || n.type != 'ReturnStatement')
return n;
for(i = ancestry.length - 1; i >= 0; i--) {
if(isFunctionNode(ancestry[i]))
return;
}
if(n.argument.type == 'CallExpression' && equals(n.argument.callee, id)) {
return tailCall(f, n, scope);
} else {
return returnValue(n, resultIdentifier);
}
},
leave: function(n) {
ancestry.pop();
}
});
block.body = [{
type: 'VariableDeclaration',
declarations: [{
type: 'VariableDeclarator',
id: resultIdentifier
}],
kind: 'var'
}, {
type: 'LabeledStatement',
label: tcoLabel,
body: {
type: 'WhileStatement',
test: {
type: 'Literal',
value: true
},
body: {
type: 'BlockStatement',
body: block.body
}
}
}, {
type: 'ReturnStatement',
argument: resultIdentifier
}];
}
function topLevel(n, ast) {
var ancestry = nodeAncestry(n, ast),
node,
i;
for(i = ancestry.length - 1; i >= 0; --i) {
node = ancestry[i];
if(isFunctionNode(node)) {
return equals(functionId(node, ast), n.argument.callee);
}
}
return false;
}
function functionId(f, ast) {
var ancestry,
parent;
if(f.id) {
return f.id;
}
ancestry = nodeAncestry(f, ast);
parent = ancestry[ancestry.length - 1];
if(parent.type == 'VariableDeclarator') {
return parent.id;
} else if(parent.type == 'AssignmentExpression') {
return parent.left;
}
}
function hasOnlyTailCalls(f, ast) {
var accum = {
any: false,
all: true
},
ancestry = [];
estraverse.traverse(f, {
enter: function(n) {
var id;
ancestry.push(n);
if(!accum.all) return;
if(n.type != 'ReturnStatement') return;
if(!n.argument) return;
if(n.argument.type != 'CallExpression') return;
id = functionId(f, ast);
if(!id || !equals(n.argument.callee, id)) return;
accum = {
any: true,
all: accum.all && topLevel(n, ast)
};
},
leave: function(n) {
ancestry.pop();
}
});
return accum.any && accum.all;
}
function mutateAST(ast) {
var scopeManager = escope.analyze(ast);
scopeManager.attach();
estraverse.traverse(ast, {
enter: function(n) {
if(!isFunctionNode(n) || !hasOnlyTailCalls(n, ast))
return;
optimizeFunction(n, ast, scopeManager.acquire(n));
}
});
scopeManager.detach();
}
function tco(content) {
var esprima = require('esprima'),
escodegen = require('escodegen'),
ast = esprima.parse(content);
mutateAST(ast);
return escodegen.generate(ast);
}
(function(exports) {
exports.optimizeFunction = optimizeFunction;
exports.mutateAST = mutateAST;
exports.tco = tco;
})(typeof exports == 'undefined' ? this.brushtail = {} : exports);
|
JavaScript
| 0.000016 |
@@ -3279,32 +3279,52 @@
: function(n) %7B%0A
+ var i;%0A%0A
ance
|
0fc21a2f8296e86458f2cacc13e7b8f1d64008c1
|
Fix WireframeHelper deprecation
|
index.js
|
index.js
|
/* global AFRAME, THREE */
if (typeof AFRAME === 'undefined') {
throw new Error('Component attempted to register before AFRAME was available.');
}
require('./lib/terrainloader.js');
/**
* Terrain model component for A-Frame.
*/
AFRAME.registerComponent('terrain-model', {
schema: {
DEM: {
type: 'asset'
},
texture: {
type: 'asset'
},
alphaMap: {
type: 'asset'
},
planeHeight: {
type: 'number'
},
planeWidth: {
type: 'number'
},
segmentsHeight: {
type: 'number',
default: 199
},
segmentsWidth: {
type: 'number',
default: 199
},
zPosition: {
type: 'number',
default: 1.5
},
transparent: {
type: 'boolean',
default: false
},
// If true, enable wireframe
debug: { default: false }
},
/**
* Set if component needs multiple instancing.
*/
multiple: true,
/**
* Called when component is attached and when component data changes.
* Generally modifies the entity based on the data.
*/
update: function (oldData) {
var el = this.el;
var data = this.data;
var debug = data.debug;
var transparentMaterial = data.transparent;
var surface;
// Texture and terrain URLs
var terrainURL = data.DEM;
var textureURL = data.texture;
var alphaMapURL = data.alphaMap;
// Utility to load the DEM data
var terrainLoader = new THREE.TerrainLoader();
// Create the plane geometry
var geometry = new THREE.PlaneBufferGeometry(data.planeWidth, data.planeHeight, data.segmentsWidth, data.segmentsHeight);
// z-scaling factor
var zPosition = data.zPosition;
// The terrainLoader loads the DEM file and defines a function to be called when the file is successfully downloaded.
terrainLoader.load(terrainURL, function (data) {
var verts = geometry.attributes.position;
/**
* Adjust each vertex in the plane to correspond to the height value in the DEM file.
* vi = The index of the current vertex's Z position in the plane geometry's position attribute array.
* di = The index of the current data value.
* tv = The total number of vertices in the plane geometry.
*/
for (var vi = 2, di = 0, tv = verts.count*3; vi < tv; vi+=3, di++) {
verts.array[vi] = data[di] / 65535 * zPosition;
}
geometry.attributes.position.needsUpdate = true;
// Load texture, apply maximum anisotropy
var textureLoader = new THREE.TextureLoader();
var texture = textureLoader.load(textureURL);
texture.anisotropy = 16;
// Load alphaMap
var alphaMap = alphaMapURL==="" ? null : new THREE.TextureLoader().load(alphaMapURL);
// Create material
var material = new THREE.MeshLambertMaterial({
map: texture,
alphaMap: alphaMap,
transparent: transparentMaterial || (alphaMap!=null)
});
// Create the surface mesh and register it under entity's object3DMap
surface = new THREE.Mesh(geometry, material);
surface.rotation.x = -90 * Math.PI / 180;
el.setObject3D('terrain', surface);
// Wireframe debug mode
if (debug) {
wireframe = new THREE.WireframeHelper( surface, 0x4caf50 );
el.setObject3D('terrain-wireframe', wireframe);
}
});
},
/**
* Called when a component is removed (e.g., via removeAttribute).
* Generally undoes all modifications to the entity.
*/
remove: function () {
this.el.removeObject3D('terrain-wireframe');
this.el.removeObject3D('terrain');
}
});
|
JavaScript
| 0.000003 |
@@ -3222,25 +3222,32 @@
-wireframe
+var wireGeometry
= new T
@@ -3264,90 +3264,220 @@
rame
-Helper( surface, 0x4caf50 );%0A el.setObject3D('terrain-wireframe', wireframe
+Geometry(geometry);%0A var wireMaterial = new THREE.LineBasicMaterial(%7Bcolor: 0x4caf50, linewidth: 2%7D);%0A var wireMesh = new THREE.LineSegments(wireGeometry, wireMaterial);%0A surface.add(wireMesh
);%0A
|
9ce804ddb9e96222d22a6fa1e69e4be490719014
|
Switch isHttpOnly to false
|
index.js
|
index.js
|
/* jshint -W064 */
'use strict';
const composer = require('./server/composer');
const cleanUp = require('./server/cleaner').cleanUp;
composer((err, server) => {
if (err) {
throw err;
}
server.state('Hawk-Session-Token', {
ttl: 24 * 60 * 60 * 1000,
path: '/',
isSecure: true,
isHttpOnly: true,
encoding: 'base64json',
clearInvalid: true
});
cleanUp(server.app.redis, (err) => {
server.log(['error', 'database', 'delete'], err);
});
server.start((err) => {
if (err) {
throw err;
}
server.log([], 'Server started at ' + server.info.uri);
});
});
|
JavaScript
| 0.99963 |
@@ -336,19 +336,20 @@
tpOnly:
-tru
+fals
e,%0A
|
24341076e667b849cca4fa5f3f63f558b900ab4a
|
Use database...
|
index.js
|
index.js
|
const express = require('express');
const https = require('https');
const http = require('http');
const fs = require('fs');
const url = require('url');
const app = express();
const mongoose = new (require('mongoose').Mongoose)();
mongoose.connect(process.env.N_DB);
const db = mongoose.connection;
db.on('error', function (err) {
console.error(err);
console.error('Faild to connect to db. Exiting...');
process.exit(1);
});
db.on('open', function() {
// HTTP Redirect to HTTPS
app.use(function(req, res, next) {
if(!req.secure) {
res.redirect(302, 'https://' + req.hostname + req.originalUrl);
} else {
res.set('Strict-Transport-Security', 'max-age=10886400; includeSubdomains; preload');
next();
}
});
app.use(function(req, res, next) {
var prasedUrl = url.parse(req.originalUrl, false);
if(req.method == 'GET' && prasedUrl.pathname.substr(-1) != '/'
&& req.hostname != 'static.maowtm.org') {
prasedUrl.pathname += '/';
res.redirect(302, url.format(prasedUrl));
} else {
next();
}
});
app.use(function(req, res, next) {
req.db = db;
next();
});
app.use(require('./subs/main'));
app.use(require('./subs/static'));
http.createServer(app).listen(80, process.env.N_LISTEN);
const httpsopts = {
key: fs.readFileSync(process.env.N_SSLKEY),
cert: fs.readFileSync(process.env.N_SSLCERT),
ciphers: [
"ECDHE-RSA-AES256-SHA384",
"DHE-RSA-AES256-SHA384",
"ECDHE-RSA-AES256-SHA256",
"DHE-RSA-AES256-SHA256",
"ECDHE-RSA-AES128-SHA256",
"DHE-RSA-AES128-SHA256",
"HIGH",
"!aNULL", "!eNULL", "!EXPORT", "!DES", "!RC4", "!MD5", "!PSK", "!SRP", "!CAMELLIA"
].join(':'),
honorCipherOrder: true
};
https.createServer(httpsopts, app).listen(443, process.env.N_LISTEN);
if(process.env.N_LISTEN2) {
http.createServer(app).listen(80, process.env.N_LISTEN2);
https.createServer(httpsopts, app).listen(443, process.env.N_LISTEN2);
}
});
|
JavaScript
| 0 |
@@ -189,13 +189,8 @@
e =
-new (
requ
@@ -208,20 +208,8 @@
se')
-.Mongoose)()
;%0Amo
@@ -1138,92 +1138,8 @@
%7D);
-%0A app.use(function(req, res, next) %7B%0A req.db = db;%0A next();%0A %7D);
%0A%0A
|
6205bdd76f9d8b68e4fc0d1d6d1d309c9b90005e
|
Fix var name typo in `exposeRoutes()` method
|
index.js
|
index.js
|
'use strict';
var annotations = require('express-annotations'),
state = require('express-state');
exports.extend = extendApp;
function extendApp(app) {
if (app['@map']) { return app; }
// Add Express Annotations and Express State support to the `app`.
annotations.extend(app);
state.extend(app);
// Brand
Object.defineProperty(app, '@map', {value: true});
app.map = mapRoute;
app.getRouteMap = getRouteMap;
app.exposeRoutes = exposeRoutes;
app.response.exposeRoutes = exposeRoutes;
// Sets up registry for simple param handlers that are either regular
// expressions or basic, non-middleware functions. These param handlers are
// exposed along with the exposed routes.
app.params = {};
app.param(registerParam.bind(app));
return app;
}
function mapRoute(routePath, name) {
/* jshint validthis:true */
return this.annotate(routePath, {name: name});
}
function getRouteMap(annotations) {
/* jshint validthis:true */
if (!Array.isArray(annotations)) {
annotations = [].slice.call(arguments);
}
// Gather all mapped/named routes that have the specified `annotations`.
var routes = this.findAll(annotations.concat('name'));
// Creates a mapping of name -> route configuration object used for
// serialization. The route objects are shallow copies of a route's primary
// data.
return routes.map(function (route) {
return {
path : route.path,
keys : route.keys,
regexp : route.regexp,
annotations: route.annotations
};
}).reduce(function (map, route) {
var name = route.annotations.name;
if (name) { map[name] = route; }
return map;
}, {});
}
function exposeRoutes(routeMap, namespace, local) {
/* jshint validthis:true */
var app = this.app || this;
// Shift args for optional `routeMap` argument.
if (typeof routeMap === 'string') {
local = namespace;
namespace = routePath;
routeMap = null;
}
// Setup default argument values.
routeMap || (routeMap = app.getRouteMap());
namespace || (namespace = app.get('state namespace'));
local || (local = app.get('state local'));
return this.expose({
routes: routeMap,
params: getRouteParams(routeMap, app.params)
}, namespace, local);
}
function registerParam(name, handler) {
/*jshint validthis:true */
// This unobtrusive params bookkeeper stores a reference to any param
// handlers that are regular express or basic, non-middleware functions. It
// is assumed that the Express Params package is the next param registration
// function to be called.
if ((handler instanceof RegExp) || handler.length < 3) {
this.params[name] = handler;
}
}
// -- Helper Functions ---------------------------------------------------------
function getRouteParams(routeMap, params) {
var paramsMap = {};
if (!params || !Object.keys(params).length) {
return paramsMap;
}
// Creates a param -> handler map for the params used in the specified
// `routeMap` which have handlers.
return Object.keys(routeMap).reduce(function (map, routeName) {
var route = routeMap[routeName];
route.keys.forEach(function (p) {
var paramName = p.name,
param = params[paramName];
if (param) {
map[paramName] = param;
}
});
return map;
}, paramsMap);
}
|
JavaScript
| 0.000812 |
@@ -1892,32 +1892,43 @@
t validthis:true
+, expr:true
*/%0A var app
@@ -2096,20 +2096,19 @@
= route
-Path
+Map
;%0A
|
0ca36122f915fa499482c976519f8854330e9524
|
Returns on origin equals false
|
index.js
|
index.js
|
/**
* CORS middleware
*
* @param {Object} [options]
* @return {Function}
* @api public
*/
module.exports = function(settings) {
var defaults = {
origin: '*',
methods: 'GET,HEAD,PUT,POST,DELETE'
};
settings = settings || defaults;
return function* cors(next) {
var options = settings;
if (typeof options === 'function') {
options = options(this.request);
}
if (typeof options.origin === 'function') {
options.origin = options.origin(this.request);
}
/**
* Access Control Allow Origin
*/
if (options.origin === true) {
options.origin = this.header.origin;
} else if (!options.origin) {
options.origin = '*';
}
this.set('Access-Control-Allow-Origin', options.origin);
/**
* Access Control Allow Methods
*/
if (options.methods.join) {
options.methods = options.methods.join(',');
}
this.set('Access-Control-Allow-Methods', options.methods);
/**
* Access Control Allow Credentials
*/
if (options.credentials === true) {
this.set('Access-Control-Allow-Credentials', 'true');
}
/**
* Access Control Allow Headers
*/
if (!options.headers) {
options.headers = this.header['access-control-request-headers'];
} else if (options.headers.join) {
options.headers = options.headers.join(',');
}
if (options.headers && options.headers.length) {
this.set('Access-Control-Allow-Headers', options.headers);
}
/**
* Access Control Allow Max Age
*/
options.maxAge = options.maxAge && options.maxAge.toString();
if (options.maxAge && options.maxAge.length) {
this.set('Access-Control-Allow-Max-Age', options.maxAge);
}
/**
* Returns
*/
if (this.method === 'OPTIONS') {
this.status = 204;
return;
}
return yield next;
}
};
|
JavaScript
| 0.999733 |
@@ -590,24 +590,81 @@
s.origin ===
+ false) %7B%0A return;%0A %7D else if (options.origin ===
true) %7B%0A
|
4450dd7d7c757d8eba1697f15495ca65d6c27012
|
Use named function to clear stacktrace
|
index.js
|
index.js
|
var postcss = require('postcss');
var definition = function (variables, node) {
var name = node.prop.slice(1);
variables[name] = node.value;
node.remove();
};
var variable = function (variables, node, str, name, opts, result) {
if ( opts.only ) {
if ( typeof opts.only[name] !== 'undefined' ) {
return opts.only[name];
} else {
return str;
}
} if ( typeof variables[name] !== 'undefined' ) {
return variables[name];
} else if ( opts.silent ) {
return str;
} else {
var fix = opts.unknown(node, name, result);
if ( fix ) {
return fix;
} else {
return str;
}
}
};
var simpleSyntax = function (variables, node, str, opts, result) {
return str.replace(/(^|[^\w])\$([\w\d-_]+)/g, function (_, bef, name) {
return bef + variable(variables, node, '$' + name, name, opts, result);
});
};
var inStringSyntax = function (variables, node, str, opts, result) {
return str.replace(/\$\(\s*([\w\d-_]+)\s*\)/g, function (all, name) {
return variable(variables, node, all, name, opts, result);
});
};
var bothSyntaxes = function (variables, node, str, opts, result) {
str = simpleSyntax(variables, node, str, opts, result);
str = inStringSyntax(variables, node, str, opts, result);
return str;
};
var declValue = function (variables, node, opts, result) {
node.value = bothSyntaxes(variables, node, node.value, opts, result);
};
var declProp = function (variables, node, opts, result) {
node.prop = inStringSyntax(variables, node, node.prop, opts, result);
};
var ruleSelector = function (variables, node, opts, result) {
node.selector = bothSyntaxes(variables, node, node.selector, opts, result);
};
var atruleParams = function (variables, node, opts, result) {
node.params = bothSyntaxes(variables, node, node.params, opts, result);
};
var comment = function (variables, node, opts, result) {
node.text = node.text
.replace(/<<\$\(\s*([\w\d-_]+)\s*\)>>/g, function (all, name) {
return variable(variables, node, all, name, opts, result);
});
};
module.exports = postcss.plugin('postcss-simple-vars', function (opts) {
if ( typeof opts === 'undefined' ) opts = { };
if ( !opts.unknown ) {
opts.unknown = function (node, name) {
throw node.error('Undefined variable $' + name);
};
}
return function (css, result) {
var variables = { };
if ( typeof opts.variables === 'function' ) {
variables = opts.variables();
} else if ( typeof opts.variables === 'object' ) {
for ( var i in opts.variables ) variables[i] = opts.variables[i];
}
for ( var name in variables ) {
if ( name[0] === '$' ) {
var fixed = name.slice(1);
variables[fixed] = variables[name];
delete variables[name];
}
}
css.walk(function (node) {
if ( node.type === 'decl' ) {
if ( node.value.toString().indexOf('$') !== -1 ) {
declValue(variables, node, opts, result);
}
if ( node.prop.indexOf('$(') !== -1 ) {
declProp(variables, node, opts, result);
} else if ( node.prop[0] === '$' ) {
if ( !opts.only ) definition(variables, node);
}
} else if ( node.type === 'rule' ) {
if ( node.selector.indexOf('$') !== -1 ) {
ruleSelector(variables, node, opts, result);
}
} else if ( node.type === 'atrule' ) {
if ( node.params && node.params.indexOf('$') !== -1 ) {
atruleParams(variables, node, opts, result);
}
} else if ( node.type === 'comment' ) {
if ( node.text.indexOf('$') !== -1 ) {
comment(variables, node, opts, result);
}
}
});
if ( opts.onVariables ) {
opts.onVariables(variables);
}
};
});
|
JavaScript
| 0.000003 |
@@ -32,34 +32,27 @@
);%0A%0A
-var definition = func
+function defini
tion
-
(var
@@ -160,26 +160,10 @@
);%0A%7D
-;
%0A%0A
-var variable =
func
@@ -159,32 +159,40 @@
();%0A%7D%0A%0Afunction
+variable
(variables, node
@@ -695,22 +695,26 @@
%0A %7D%0A%7D
-;
%0A%0A
-var
+function
simpleS
@@ -714,36 +714,24 @@
simpleSyntax
- = function
(variables,
@@ -922,22 +922,26 @@
%7D);%0A%7D
-;
%0A%0A
-var
+function
inStrin
@@ -947,28 +947,16 @@
ngSyntax
- = function
(variabl
@@ -1136,22 +1136,26 @@
%7D);%0A%7D
-;
%0A%0A
-var
+function
bothSyn
@@ -1159,28 +1159,16 @@
Syntaxes
- = function
(variabl
@@ -1337,22 +1337,26 @@
n str;%0A%7D
-;
%0A%0A
-var
+function
declVal
@@ -1357,28 +1357,16 @@
eclValue
- = function
(variabl
@@ -1470,26 +1470,10 @@
);%0A%7D
-;
%0A%0A
-var declProp =
func
@@ -1469,32 +1469,40 @@
t);%0A%7D%0A%0Afunction
+declProp
(variables, node
@@ -1594,22 +1594,26 @@
sult);%0A%7D
-;
%0A%0A
-var
+function
ruleSel
@@ -1617,28 +1617,16 @@
Selector
- = function
(variabl
@@ -1732,22 +1732,26 @@
sult);%0A%7D
-;
%0A%0A
-var
+function
atruleP
@@ -1755,28 +1755,16 @@
leParams
- = function
(variabl
@@ -1870,25 +1870,10 @@
);%0A%7D
-;
%0A%0A
-var comment =
func
@@ -1877,16 +1877,23 @@
unction
+comment
(variabl
@@ -2100,17 +2100,16 @@
%7D);%0A%7D
-;
%0A%0Amodule
|
40a634bb037052011165043d229d648876409150
|
Add code that was previously in anyDB.createPool
|
index.js
|
index.js
|
var inherits = require('util').inherits
var EventEmitter = require('events').EventEmitter
var Transaction = require('any-db-transaction')
var Pool = require('generic-pool').Pool
var once = require('once')
var chain = require('./lib/chain')
module.exports = ConnectionPool
inherits(ConnectionPool, EventEmitter)
function ConnectionPool(adapter, connParams, options) {
if (!(this instanceof ConnectionPool)) {
return new ConnectionPool(adapter, connParams, options)
}
EventEmitter.call(this)
options = options || {}
var poolOpts = {
min: options.min || 0,
max: options.max || 10,
create: function (ready) {
adapter.createConnection(connParams, function (err, conn) {
if (err) return ready(err);
else if (options.onConnect) options.onConnect(conn, ready)
else ready(null, conn)
})
},
destroy: function (conn) {
conn.end()
conn._events = {}
},
log: options.log
}
var resetSteps = [];
if (adapter.reset) resetSteps.unshift(adapter.reset)
if (options.reset) resetSteps.unshift(options.reset)
this.adapter = adapter.name
this._adapter = adapter
this._reset = chain(resetSteps)
this._pool = new Pool(poolOpts)
}
ConnectionPool.prototype.query = function (statement, params, callback) {
var self = this
, query = this._adapter.createQuery(statement, params, callback)
this.acquire(function (err, conn) {
if (err) {
if (typeof params === 'function') {
return params(err)
} else if (callback) {
return callback(err);
} else {
return query.emit('error', err);
}
}
conn.query(query);
self.emit('query', query)
var release = once(self.release.bind(self, conn))
query.once('end', release).once('error', function (err) {
release()
// If this was the only error listener, re-emit the error.
if (!this.listeners('error').length) {
this.emit('error', err)
}
})
})
return query
}
ConnectionPool.prototype.acquire = function (callback) {
this.emit('acquire')
this._pool.acquire(callback);
}
ConnectionPool.prototype.release = function (connection) {
this.emit('release')
var pool = this._pool
this._reset(connection, function (err) {
if (err) return pool.destroy(connection)
pool.release(connection)
})
}
ConnectionPool.prototype.destroy = function (connection) {
this._pool.destroy(connection)
}
ConnectionPool.prototype.close = function (callback) {
var self = this
this._pool.drain(function () {
self._pool.destroyAllNow()
self.emit('close')
if (callback) callback()
})
}
ConnectionPool.prototype.begin = function (beginStatement, callback) {
var tx = Transaction.begin(this._adapter.createQuery, beginStatement, callback)
var pool = this
this.acquire(function (err, connection) {
if (err) return tx.emit('error', err);
var release = pool.release.bind(pool, connection)
tx.on('query', pool.emit.bind(pool, 'query'))
tx.once('rollback:complete', release)
.once('commit:complete', release)
.setConnection(connection)
})
return tx;
}
|
JavaScript
| 0.000001 |
@@ -552,16 +552,572 @@
%7C%7C %7B%7D%0A%0A
+ if (options.create %7C%7C options.destroy) %7B%0A throw new Error(%22Use onConnect/reset options instead of create/destroy.%22)%0A %7D%0A%0A if (connParams.adapter == 'sqlite3'%0A && /:memory:$/i.test(connParams.database)%0A && (options.min %3E 1 %7C%7C options.max %3E 1))%0A %7B%0A console.warn(%0A %22Pools of more than 1 connection do not work for in-memory SQLite3 databases%5Cn%22 +%0A %22The specified minimum (%25d) and maximum (%25d) connections have been overridden%22,%0A options.min, options.max%0A )%0A if (options.min) options.min = 1%0A options.max = 1%0A %7D%0A %0A
var po
|
a0dd08e6e28bfb04ba5414d92ebe1d87d3ce8339
|
Remove strict mode rule
|
index.js
|
index.js
|
const never = "never";
const always = "always";
const possibleErrorRules = {
"no-cond-assign": 2,
"no-console": 2,
"no-constant-condition": 2,
"no-control-regex": 2,
"no-debugger": 2,
"no-dupe-args": 2,
"no-dupe-keys": 2,
"no-duplicate-case": 2,
"no-empty": 2,
"no-empty-character-class": 2,
"no-ex-assign": 2,
"no-extra-boolean-cast": 2,
"no-extra-semi": 2,
"no-func-assign": 2,
"no-inner-declarations": 2,
"no-invalid-regexp": 2,
"no-irregular-whitespace": 2,
"no-obj-calls": 2,
"no-regex-spaces": 2,
"no-sparse-arrays": 2,
"no-unexpected-multiline": 2,
"no-unreachable": 2,
"no-unsafe-finally": 2,
"no-unsafe-negation": 2,
"use-isnan": 2,
"valid-typeof": 2,
};
const bestPracticeRules = {
"curly": 2,
"guard-for-in": 2,
"no-alert": 2,
"no-bitwise": 2,
"no-case-declarations": 2,
"no-empty-pattern": 2,
"no-fallthrough": 2,
"no-multi-spaces": 2,
"no-octal": 2,
"no-redeclare": 2,
"no-self-assign": 2,
"no-unused-labels": 2,
"no-void": 2,
"radix": 2,
};
const strictModeRules = {
"strict": 2,
};
const variablesRules = {
"no-delete-var": 2,
"no-undef": 2,
"no-unused-vars": 2,
"no-use-before-define": [2, "nofunc"],
};
const styleRules = {
"brace-style": [2, "stroustrup", { allowSingleLine: true }],
"eol-last": 2,
"indent": [2, 4, { SwitchCase: 1 }],
"keyword-spacing": 2,
"linebreak-style": [2, "unix"],
"max-len": [2, 205, 4],
"no-mixed-spaces-and-tabs": 2,
"no-multiple-empty-lines": [2, { max: 1 }],
"one-var": [2, never],
"operator-linebreak": [2, "after"],
"space-before-blocks": 2,
"space-before-function-paren": [2, never],
"spaced-comment": 2,
"space-infix-ops": 2,
};
const es6Rules = {
"arrow-spacing": 2,
"constructor-super": 2,
"no-class-assign": 2,
"no-const-assign": 2,
"no-dupe-class-members": 2,
"no-duplicate-imports": 2,
"no-new-symbol": 2,
"no-this-before-super": 2,
"no-useless-constructor": 2,
"no-var": 2,
"prefer-const": 2,
"prefer-rest-params": 2,
"prefer-spread": 2,
"require-yield": 2,
};
const reactRules = {
"no-deprecated": 2,
"no-direct-mutation-state": 2,
"no-find-dom-node": 2,
"no-is-mounted": 2,
"no-render-return-value": 2,
"no-string-refs": 2,
"no-unknown-property": 2,
"prefer-es6-class": 2,
"react-in-jsx-scope": 2,
"self-closing-comp": 2,
"style-prop-object": 2,
"jsx-closing-bracket-location": [2, "line-aligned"],
"jsx-indent": [2, 4],
"jsx-indent-props": [2, 4],
"jsx-space-before-closing": 2,
"jsx-equals-spacing": 2,
"jsx-first-prop-new-line": [2, "multiline"],
"jsx-pascal-case": 2,
"jsx-max-props-per-line": [2, { maximum: 5 }],
"jsx-no-duplicate-props": 2,
"jsx-no-undef": 2,
"jsx-uses-react": 2,
"jsx-uses-vars": 2,
"jsx-wrap-multilines": 2,
};
module.exports = {
env: {
browser: true,
node: true,
es6: true,
},
plugins: ["react"],
ecmaFeatures: {
experimentalObjectRestSpread: true,
},
parser: "babel-eslint",
rules: Object.assign(
{},
possibleErrorRules,
bestPracticeRules,
strictModeRules,
variablesRules,
styleRules,
es6Rules,
Object.keys(reactRules).reduce((result, key) => (result[`react/${key}`] = reactRules[key], result), {})
),
};
|
JavaScript
| 0.000028 |
@@ -1153,55 +1153,8 @@
%7D;%0A%0A
-const strictModeRules = %7B%0A %22strict%22: 2,%0A%7D;%0A%0A
cons
@@ -3352,33 +3352,8 @@
es,%0A
- strictModeRules,%0A
|
c1efbc2b8fa99649a3ce6fabbf312df0a6f99b57
|
Move possessive outside of <a>
|
www/assets/%version/gittip/horn.js
|
www/assets/%version/gittip/horn.js
|
Gittip.horn = {};
Gittip.horn.init = function()
{
Gittip.horn.since_id = undefined;
$('#toot-form').submit(Gittip.horn.toot);
Gittip.horn.update({limit: 20});
};
Gittip.horn.update = function(data)
{
clearTimeout(Gittip.horn.handle);
data = data || {};
if (Gittip.horn.since_id !== undefined)
data.since_id = Gittip.horn.since_id;
jQuery.ajax(
{ type: "GET"
, url: "toots.json"
, data: data
, success: Gittip.horn.draw
});
};
Gittip.horn.draw = function(toots)
{
for (var i=toots.length-1, toot; toot = toots[i]; i--)
{
Gittip.horn.since_id = toot.id;
Gittip.horn.drawOne(toot);
}
Gittip.horn.handle = setTimeout(Gittip.horn.update, 10000)
};
Gittip.horn.drawOne = function(toot)
{
var escaped = $('<div>').text(toot.toot).html();
var html = '<li class="box '
+ (toot.horn === toot.tootee ? 'me' : 'them')
+ ' '
+ (toot.own ? 'own' : 'theirs')
+ '"><div class="toot">' + escaped + '</div>'
+ '<div class="nav level-1">'
+ ( toot.own
? 'You'
: '<a href="/' + toot.tooter + '/">' + toot.tooter + '</a>'
)
+ ' tooted '
+ ( toot.horn === toot.tootee
? (toot.own ? 'your own' : 'your')
: '<a href="/' + toot.tootee + '/">' + toot.tootee + '\'s</a>'
)
+ ' horn</div>'
+ '</li>'
$('#toots').prepend(html)
};
Gittip.horn.success = function(data)
{
// clear the textarea & draw any new toots
$('#toot').val('');
Gittip.horn.update(data);
};
Gittip.horn.toot = function(e)
{
e.preventDefault();
e.stopPropagation();
var toot = $('#toot').val();
jQuery.ajax(
{ type: "POST"
, url: "toot.json"
, data: {toot: toot}
, success: Gittip.horn.success
});
return false;
};
|
JavaScript
| 0.000001 |
@@ -1433,15 +1433,15 @@
+ '
-%5C's
%3C/a%3E
+%5C's
'%0A
|
bdd548eef782c79dae26a175f9ac4cf188b27fed
|
Corrected some grammatical mistakes
|
index.js
|
index.js
|
var express = require('express');
var app = express();
var path = require("path");
//Express does not deliever anything beyond route
// So need to set it up to use the public directory for static content
app.use(express.static(path.join(__dirname, 'public')));
var http = require('http');
var httpServer = http.Server(app);
var socketIO = require('socket.io');
var io = socketIO(httpServer);
var freeUsers = []; // IDs of the users who are conncected and free
idmap = {}; // Map containing ids of sockets chatting with each other. Map is symmetric
var welcomeMessage = "You are chatting with a random stranger, Say Hi!\n";
var disconnectMessage = "Stranger has left. Please Reload this page or wait for us to connect you with someone.\n";
app.get('/', function(req, res) {
res.sendFile(__dirname + '/public/index.html');
});
io.on('connection', function(socket){
// console.log('New user joined' + socket.id);
if(freeUsers.length) { // Chechk if there are some free users
var st1 = freeUsers.shift(); // Remove the user who has been waiting longest
idmap[socket.id] = st1;
idmap[st1] = socket.id;
console.log('Conncected' + socket.id + ' to ' + st1);
io.to(socket.id).emit('welcome message',welcomeMessage);
io.to(st1).emit('welcome message',welcomeMessage);
}
else {
freeUsers.push(socket.id); // Else push the user in the queue for later processing
}
//Handling Code when a User disconnects
socket.on('disconnect', function() {
var st2 = idmap[socket.id];
if(st2) {
io.to(st2).emit('disconnect message',disconnectMessage);
delete idmap[socket.id];
delete idmap[st2];
//Map the stranger to another user if there exists some free user
if(freeUsers.length) {
var st3 = freeUsers.shift();
idmap[st2] = st3;
idmap[st3] = st2;
io.to(st2).emit('welcome message',welcomeMessage);
io.to(st3).emit('welcome message',welcomeMessage);
}
else freeUsers.push(st2);
}
});
//When message comes , send it to the id mapped to socket's
socket.on('chat message', function(msg){
console.log('message: ' + msg);
if(idmap[socket.id]) io.to(idmap[socket.id]).emit('chat message', msg);
console.log(idmap);
});
});
httpServer.listen(3000, function() {
console.log('Listening on *:3000');
});
|
JavaScript
| 0.999999 |
@@ -99,17 +99,16 @@
not deli
-e
ver anyt
@@ -1126,17 +1126,16 @@
og('Conn
-c
ected' +
|
f4ae4703817a84eb3389c99fa2ef3a5ae7afc0cd
|
Fix typo
|
index.js
|
index.js
|
'use strict';
const methodNames = [
'arc',
'arcTo',
'beginPath',
'bezierCurveTo',
'clearRect',
'clip',
'closePath',
'createLinearGradient',
'createRadialGradient',
'drawImage',
'ellipse',
'fill',
'fillRect',
'fillText',
'lineTo',
'moveTo',
'quadraticCurveTo',
'rect',
'resetClip',
'restore',
'rotate',
'save',
'scale',
'setLineDash',
'setTransform',
'stroke',
'strokeRect',
'strokeText',
'transform',
'translate'
];
const setterNames = [
'fillStyle',
'font',
'globalAlpha',
'globalCompositeOperation',
'lineCap',
'lineDashOffset',
'lineJoin',
'lineWidth',
'miterLimit',
'strokeStyle',
'textAlign',
'textBaseline'
];
const passthroughNames = [
'getImageData',
'getLineDash',
'measureText',
'putImageData'
];
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
class Leinwand {
constructor(canvas) {
this._canvas = canvas;
this._ctx = canvas.getContext('2d');
}
clear() {
return this.clearRect(0, 0, this._canvas.width, this._canvas.height);
}
circle(x, y, r) {
return this.arc(x, y, r, 0, 2 * Math.PI, false);
}
strokeCircle(x, y, r) {
return this.beginPath().circle(x, y, r).closePath().stroke();
}
fillCircle(x, y, r) {
return this.beginPath().circle(x, y, r).closePath().fill();
}
rotateContextAt(x, y, r) {
return this
.translate(x, y)
.rotate(r)
.translate(-1 * x, -1 * y);
}
resetCanvas() {
this._canvas.width = this._canvas.width;
return this;
}
resetTransforms() {
return this.setTransform(1, 0, 0, 1, 0, 0);
}
clearWithTransforms() {
return this
.save()
.resetTransforms()
.clear()
.restore();
}
rectCenteredAt(x, y, w, h) {
return this
.rect(x - w / 2, y - h / 2, w, h);
}
fillRectCenteredAt(x, y, w, h) {
return this
.fillRect(x - w / 2, y - h / 2, w, h);
}
strokeRectCenteredAt(x, y, w, h) {
return this
.strokeRect(x - w / 2, y - h / 2, w, h);
}
fillTextCenteredAt(text, x, y) {
return this
.save()
.textBaseline('middle')
.textAlign('center')
.fillText(text, x, y)
.restore();
}
strokeTextCenteredAt(text, x, y) {
return this
.save()
.textBaseline('middle')
.textAlign('center')
.strokeText(text, x, y)
.resore();
}
drawImageCenteredAt(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight) {
let args = arguments.length;
if (args === 3) {
this.drawImage(image, sx - image.width / 2, sy - image.height / 2);
} else if (args === 5) {
this.drawImage(image, sx - sWidth / 2, sy - sHeight / 2, sWidth, sHeight);
} else if (args === 9) {
this.drawImage(image, sx, sy, sWidth, sHeight, dx - dWidth / 2, dy - dHeight / 2, dWidth, dHeight);
} else {
throw new TypeError(arguments.length + ' is not a valid number of arguments to Leinwand.drawImageCenteredAt');
}
return this;
}
//Getters
getContext() {
return this._ctx;
}
getCanvas() {
return this._canvas;
}
getWidth() {
return this._canvas.width;
}
getHeight() {
return this._canvas.height;
}
setWidth(width) {
this._canvas.width = width;
return this;
}
setHeight(height) {
this._canvas.height = height;
return this;
}
width(w) {
if (arguments.length === 0) {
return this._canvas.width;
}
return this.setWidth(w);
}
height(h) {
if (arguments.length === 0) {
return this._canvas.height;
}
return this.setHeight(h);
}
}
methodNames.forEach(el =>
Leinwand.prototype[el] = function(...args) {
this._ctx[el](...args);
return this;
}
);
setterNames.forEach(el => {
Leinwand.prototype[el] = function(s) {
if (arguments.length === 0) {
return this._ctx[el];
}
this._ctx[el] = s;
return this;
};
Leinwand.prototype['get' + capitalizeFirstLetter(el)] = function() {
return this._ctx[el];
};
Leinwand.prototype['set' + capitalizeFirstLetter(el)] = function(s) {
this._ctx[el] = s;
return this;
};
});
passthroughNames.forEach(el => {
Leinwand.prototype[el] = function(...args) {
return this._ctx[el](...args);
};
});
//Aliases
Leinwand.prototype.lt = Leinwand.prototype.lineTo;
Leinwand.prototype.mt = Leinwand.prototype.moveTo;
Leinwand.prototype.opacity = Leinwand.prototype.globalAlpha;
module.exports = Leinwand;
|
JavaScript
| 0.999999 |
@@ -2414,16 +2414,17 @@
.res
+t
ore();%0A
@@ -4506,8 +4506,9 @@
einwand;
+%0A
|
31e96ff19ba1d201ed16892ef89f7b31eccc0395
|
Fix exposure rounding
|
index.js
|
index.js
|
// Tournament algorithm to generate lineups from only exposures and salaries
const _ = require('underscore');
const pool = require('./samplePool.json'); // sample NBA fanduel pool from 12/12/16
// default to one lineup if no argument provided
const lineupsToBuild = process.argv[2] || 1;
// returns the salary for a lineup or partial lineup
function getSalary(lineup) {
return lineup.reduce((acc, curr) => acc + curr.salary, 0);
}
function getFormattedCurrency(usd) {
return usd.toLocaleString('en', { style: 'currency', currency: 'usd' });
}
// unique id assigned to each lineup to prevent duplicates
function getLineupKey(lineup) {
return lineup.map(player => player.id).join('-');
}
function getLineupSummary(lineup) {
const lineupKey = getLineupKey(lineup);
const formattedSalary = getFormattedCurrency(getSalary(lineup));
return `${lineupKey} (${formattedSalary})`;
}
// get players who are eligible to fill a lineup at a given position
function getPositionCandidates(playerPool, prep, position, remainingSalary) {
return playerPool.filter(player =>
_.includes(player.pos, position) && player.salary < remainingSalary);
}
function getEligiblePlayer(playerPool, prep, position, remainingSalary) {
const candidates = getPositionCandidates(playerPool, prep, position, remainingSalary);
if (candidates.length === 0) {
return null;
}
const nonLikedCandidates = candidates.filter(player => !player.liked);
const selectedLikedId = _.sample(prep[position]);
if (selectedLikedId) {
const selectedLikedArr = candidates.filter(player => player.id === selectedLikedId);
if (_.isEmpty(selectedLikedArr)) {
return null;
}
return selectedLikedArr[0];
}
return _.sample(nonLikedCandidates);
}
function getInitialExposures(outputCount, playerPool) {
return playerPool.filter(player => player.liked)
.reduce((acc, curr) => Object.assign(acc,
{ [curr.id]: { count: 0, max: Math.floor(curr.liked * outputCount) + 1 } }), {});
}
function isValidLineup(lineup, salaryFloor, salaryCap, exposures) {
const salary = getSalary(lineup);
const hasValidExposure = function hasValidExposure(player) {
// nonliked players always pass exposure check
if (!exposures[player.id]) {
return true;
}
return exposures[player.id].count + 1 <= exposures[player.id].max;
};
return salary > salaryFloor && salary < salaryCap && lineup.every(hasValidExposure);
}
// generate a weighted distribution of liked players for a given position
function generatePosDist(posSubPool) {
const liked = posSubPool.filter(player => player.liked);
const likedDist = liked.reduce((acc, curr) =>
acc.concat(_.range(curr.liked * 100).map(() => curr.id)), []);
const diff = 100 - likedDist.length;
if (diff > 0) {
return likedDist.concat(_.range(diff).map(() => null));
}
return likedDist;
}
// generate and return liked distributions for each position and max exposures
function generateLineupPrep(outputCount, playerPool, positions) {
const likedDistributions = positions.reduce((acc, curr) => {
const posSubPool = playerPool.filter(player => _.includes(player.pos, curr));
const posDist = generatePosDist(posSubPool);
return Object.assign(acc, { [curr]: posDist });
}, {});
const initialExposures = getInitialExposures(outputCount, playerPool);
return Object.assign(likedDistributions, { initialExposures });
}
function generateLineup(playerPool, prep, positions, salaryFloor, salaryCap) {
const partialLineup = [];
for (let posId = 0; posId < positions.length; posId += 1) {
const remainingSalary = salaryCap - getSalary(partialLineup);
const selection = getEligiblePlayer(playerPool, prep, positions[posId], remainingSalary);
if (!selection) {
return null;
}
partialLineup.push(selection);
}
return partialLineup;
}
function generateLineups(outputCount, playerPool, prep, positions, salaryFloor, salaryCap) {
const lineups = [];
const lineupKeys = {};
const maxAttempts = 10e6;
let attempt = 0;
// store current and max exposures for liked players as we build lineups
let exposures = prep.initialExposures;
// update the exposure count while keeping the max
const updateExposure = (acc, curr) => Object.assign(acc, { [curr.id]:
{ count: exposures[curr.id].count + 1, max: exposures[curr.id].max } });
while (lineups.length < outputCount && attempt < maxAttempts) {
const candidate = generateLineup(playerPool, prep, positions, salaryFloor, salaryCap);
if (candidate) {
const lineupKey = getLineupKey(candidate);
// only add distinct, valid lineups
if (!lineupKeys[lineupKey] && isValidLineup(candidate, salaryFloor, salaryCap, exposures)) {
lineupKeys[lineupKey] = candidate;
const updatedExposures = candidate.filter(player => player.liked)
.reduce(updateExposure, {});
exposures = Object.assign(exposures, updatedExposures);
lineups.push(candidate);
}
attempt += 1;
}
}
return lineups;
}
function printLineups(lineups) {
/* eslint-disable no-console */
lineups.sort((lineA, lineB) => getSalary(lineB) - getSalary(lineA))
.forEach(lineup => console.log(getLineupSummary(lineup)));
/* eslint-enable no-console */
}
function printMetadata(salaryFloor, salaryCap, numLineups, hrtime) {
/* eslint-disable no-console */
console.log(`salaryFloor = ${getFormattedCurrency(salaryFloor)}`);
console.log(`salaryCap = ${getFormattedCurrency(salaryCap)}`);
console.log(`Generated ${numLineups} lineups in ${hrtime[0]}s ${hrtime[1]}ns`);
/* eslint-enable no-console */
}
(function run(outputCount) {
// fanduel nba settings downscaled to 5 positions
const salaryCap = 60000 * (5 / 9);
const salaryFloor = 0.75 * salaryCap;
// TODO: allow for duplicate positions in a lineup
const positions = ['PG', 'SG', 'SF', 'PF', 'C'];
// store liked exposure distribution as well as max exposures
const prep = generateLineupPrep(outputCount, pool, positions);
const hrStart = process.hrtime();
const lineups = generateLineups(outputCount, pool, prep, positions, salaryFloor, salaryCap);
const hrEnd = process.hrtime(hrStart);
printLineups(lineups);
printMetadata(salaryFloor, salaryCap, lineups.length, hrEnd);
}(lineupsToBuild));
|
JavaScript
| 0.000005 |
@@ -1942,13 +1942,12 @@
ath.
-floor
+ceil
(cur
@@ -1968,20 +1968,16 @@
utCount)
- + 1
%7D %7D), %7B
|
8c7ba09a723dd281062502fc2010f330e9a3d50a
|
version option exits with 0, not error
|
index.js
|
index.js
|
#! /usr/bin/env node
'use strict';
var fs = require('fs');
var path = require('path');
var shell = require('shelljs');
var parser = require('nomnom');
var async = require('async');
var glob = require('glob');
var logger = require('./util/logger');
var ParseUtils = require('./util/parseUtils');
var CacheDependencyManager = require('./cacheDependencyManagers/cacheDependencyManager');
// Main entry point for npm-cache
var main = function () {
checkTarExists();
// Parse CLI Args
parser.command('install')
.callback(installDependencies)
.option('forceRefresh', {
abbr: 'r',
flag: true,
default: false,
help: 'force installing dependencies from package manager without cache'
})
.help('install specified dependencies');
parser.command('clean')
.callback(cleanCache)
.help('clear cache directory');
parser.option('cacheDirectory', {
default: path.resolve(process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE, '.package_cache'),
abbr: 'c',
help: 'directory where dependencies will be cached'
});
parser.option('version', {
abbr: 'v',
help: 'displays version info and exit',
flag: true,
callback: function () {
var packagePath = path.resolve(__dirname, 'package.json');
var packageFile = fs.readFileSync(packagePath);
var packageParsed = JSON.parse(packageFile);
return packageParsed.version;
}
});
var examples = [
'Examples:',
'\tnpm-cache install\t# try to install npm, bower, and composer components',
'\tnpm-cache install bower\t# install only bower components',
'\tnpm-cache install bower npm\t# install bower and npm components',
'\tnpm-cache install bower --allow-root composer --dry-run\t# install bower with allow-root, and composer with --dry-run',
'\tnpm-cache --cacheDirectory /home/cache/ install bower \t# install components using /home/cache as cache directory',
'\tnpm-cache --forceRefresh install bower\t# force installing dependencies from package manager without cache',
'\tnpm-cache clean\t# cleans out all cached files in cache directory'
];
parser.help(examples.join('\n'));
var npmCacheArgs = ParseUtils.getNpmCacheArgs();
parser.parse(npmCacheArgs);
};
// Verify system 'tar' command, exit if if it doesn't exist
var checkTarExists = function () {
if (! shell.which('tar')) {
logger.logError('tar command-line tool not found. exiting...');
process.exit(1);
}
};
// Creates cache directory if it does not exist yet
var prepareCacheDirectory = function (cacheDirectory) {
logger.logInfo('using ' + cacheDirectory + ' as cache directory');
if (! fs.existsSync(cacheDirectory)) {
// create directory if it doesn't exist
shell.mkdir('-p', cacheDirectory);
logger.logInfo('creating cache directory');
}
};
// npm-cache command handlers
// main method for installing specified dependencies
var installDependencies = function (opts) {
prepareCacheDirectory(opts.cacheDirectory);
var availableManagers = CacheDependencyManager.getAvailableManagers();
var managerArguments = ParseUtils.getManagerArgs();
var managers = Object.keys(managerArguments);
async.each(
managers,
function startManager (managerName, callback) {
var managerConfig = require(availableManagers[managerName]);
managerConfig.cacheDirectory = opts.cacheDirectory;
managerConfig.forceRefresh = opts.forceRefresh;
managerConfig.installOptions = managerArguments[managerName];
var manager = new CacheDependencyManager(managerConfig);
manager.loadDependencies(callback);
},
function onInstalled (error) {
if (error === undefined) {
logger.logInfo('successfully installed all dependencies');
process.exit(0);
} else {
logger.logError('error installing dependencies');
process.exit(1);
}
}
);
};
// Removes all cached dependencies from cache directory
var cleanCache = function (opts) {
prepareCacheDirectory(opts.cacheDirectory);
var md5Regexp = /\/[0-9a-f]{32}\.tar\.gz/i;
var isCachedFile = function (fileName) {
return md5Regexp.test(fileName);
};
var candidateFileNames = glob.sync(opts.cacheDirectory + '/*.tar.gz');
var cachedFiles = candidateFileNames.filter(isCachedFile);
cachedFiles.forEach(function (fileName) {
fs.unlinkSync(fileName);
});
logger.logInfo('cleaned ' + cachedFiles.length + ' files from cache directory');
};
main();
|
JavaScript
| 0.000033 |
@@ -1388,23 +1388,28 @@
;%0A
-return
+console.log(
packageP
@@ -1421,16 +1421,40 @@
.version
+);%0A process.exit(0)
;%0A %7D%0A
|
a7f103391bbb7f043b82c2082442fe8881bd4cbd
|
handle ascii for last line
|
index.js
|
index.js
|
function toHex (buf, group, wrap, LE, ascii) {
toAscii = ascii ? asciipp : function() { return ''; };
buf = buf.buffer || buf
var s = ''
var l = buf.byteLength || buf.length
for(var i = 0; i < l ; i++) {
var byte = (i&0xfffffffc)|(!LE ? i%4 : 3 - i%4)
s = s + ((buf[byte]>>4).toString(16))
+ ((buf[byte]&0xf).toString(16))
+ (group-1==i%group ? ' ' : '')
+ (wrap-1==i%wrap ? toAscii(buf.slice(i-wrap+1, i+1)) + '\n' : '')
}
return s + '\n'
}
function reverseByteOrder(n) {
return (
((n << 24) & 0xff000000)
| ((n << 8) & 0x00ff0000)
| ((n >> 8) & 0x0000ff00)
| ((n >> 24) & 0x000000ff)
)
}
function asciipp(buf) {
var arr = [].slice.call(buf);
// http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters
var placeholder = '.'.charCodeAt(0);
var printables = arr.map(function(b) { return b > 0x19 && b < 0x7f ? b : placeholder; });
return String.fromCharCode.apply(null, printables);
}
var hexpp = module.exports = function (buffer, opts) {
opts = opts || {}
opts.groups = opts.groups || 4
opts.wrap = opts.wrap || 16
return toHex(buffer, opts.groups, opts.wrap, opts.bigendian, opts.ascii)
}
hexpp.defaults = function (opts) {
return function (b) {
return hexpp(b, opts)
}
}
|
JavaScript
| 0.000005 |
@@ -467,16 +467,218 @@
'')%0A %7D%0A
+ var lastLine = l%25wrap;%0A var filler = (wrap-lastLine)*2 + Math.floor((wrap-lastLine+group-1)/group);%0A if (ascii) %7B%0A while(filler--)%0A s += ' ';%0A s += toAscii(buf.slice(l-lastLine, l));%0A %7D%0A
return
|
639af73664988c2bcce83017799c197c52ab5c02
|
Fix logging
|
index.js
|
index.js
|
'use strict';
const params = require('./param.json');
const metrics = require('./metrics.json');
const os = require('os');
const postprocessors = require('./postprocessors');
const { getByPath, fetch } = require('./util');
const pollInterval = params.pollInterval || 5000;
const baseURL = params.hipsterUrl;
const source = (params.sourcePrefix || os.hostname()).trim(); // get the metric source
if (!baseURL) {
throw new ReferenceError('Kubernetes Hipster url is missing');
}
function poll() {
return Promise.all(Object.keys(metrics)
.map(metric => {
let metricData = metrics[metric];
return getInstanceUrls(metricData.endpoints.loopBy)
.then(data => {
data = flattenDeep(data);
return Promise.all(data.map(value => {
return fetch(`${baseURL}${value.url}${metricData.endpoints.final}`)
.then(finalData => {
let result = getByPath(metricData.resultPath || [], finalData);
return { url: value.url, result };
})
.then(data => {
let postprocessors = metricData.postprocessors;
if (!postprocessors || !postprocessors.length) {
return data;
}
return sequentially(postprocessors, data, metricData);
});
}))
.then(result => ({ metric, result }));
});
}))
.then(data => data.reduce((result, current) => {
result[current.metric] = current.result;
return result;
}, {}));
}
function sequentially(arr, data, metricData) {
return arr.reduce((prev, next) => prev.then(() => {
let toApply = postprocessors[next];
return prev.then(() => toApply(data, metricData));
}), Promise.resolve());
}
function flattenDeep(array) {
if (!array.length) {
return array;
}
if (!array.some(element => Array.isArray(element))) {
return array;
}
let flatten = array.reduce((result, element) => {
if (!Array.isArray(element)) {
return [ ...result, element ];
}
return [ ...result, ...element ];
}, []);
return flattenDeep(flatten);
}
function getInstanceUrls(loopBy, result = { url: '' }) {
if (!loopBy.length) {
return Promise.resolve(result);
}
return fetch(`${baseURL}${result.url}${loopBy[0].endpoint}`)
.then(data => {
return Promise.all(data.map(a => {
let updatedLoopBy = loopBy.slice(1);
return getInstanceUrls(updatedLoopBy, { url: `${result.url}${loopBy[0].endpoint}/${a}` });
}));
});
}
function writeOutput(data) {
for (let metric in data) {
if(data.hasOwnProperty(metric)) {
data[metric].forEach(issue => {
console.log(`${metric} ${source} ${issue.result}`);
});
}
}
}
function execute() {
return poll()
.then(writeOutput)
.then(() => setTimeout(execute, pollInterval))
.catch(error => {
console.log(error);
//Retry execution after increased amount of time
setTimeout(execute, pollInterval*10);
});
}
execute();
process.on('unhandledRejection', error => {
console.log('Unhandled rejection');
console.log(error);
//Retry execution after increased amount of time
setTimeout(execute, pollInterval*10);
});
|
JavaScript
| 0 |
@@ -2930,18 +2930,8 @@
ric%7D
- $%7Bsource%7D
$%7Bi
@@ -2942,16 +2942,26 @@
.result%7D
+ $%7Bsource%7D
%60);%0A
|
eff2976b24bad0d09adf28d8ac42e2badd773a4d
|
Tidy unused variable.
|
index.js
|
index.js
|
var short = '-', long = '--';
var sre = /^-[^-]+/, lre = /^--[^-]+/, negate = /--no-/;
var camelcase = require('cli-util').camelcase;
function toOptionKey(arg, negated, opts) {
var result = alias(arg, opts), key;
if(result.aliased) return result.key;
key = arg.replace(/^-+/, '');
if(negated) key = key.replace(/^no-/, '');
return camelcase(key);
}
function alias(key, opts) {
var alias = opts.alias, z, keys;
for(z in alias) {
keys = z.split(/\s+/);
if(~keys.indexOf(key)) return {key: alias[z],
aliased: true, negated: negate.test(z)};
}
return {key: key, aliased: false};
}
function flags(arg, output, next, opts) {
var result = alias(arg, opts), keys, skip = false, i = 0, key, v = true;
if(result.aliased) output.flags[result.key] = v;
arg = arg.replace(/^-/, ''); keys = arg.split('');
for(;i < keys.length;i++, key = keys[i]) {
key = keys[i]; v = true;
if(i == keys.length - 1 && ~opts.options.indexOf(short + key)) {
return options(short + key, output, next, opts);
}
result = alias(short + key, opts);
if(result.negated) v = false;
output.flags[result.aliased ? result.key : key] = v;
}
return skip;
}
function options(arg, output, next, opts) {
var equals = arg.indexOf('='), value, result = false, negated, key;
var flag = (!next && !~equals)
|| (next && (!next.indexOf(short) && next != short) && !~equals);
if(next == short) output.stdin = true;
if(~equals) {
value = arg.slice(equals + 1); arg = arg.slice(0, equals);
}
if(~opts.flags.indexOf(arg)) flag = true;
if(next && !flag && !~equals) {
value = next; result = true;
}
negated = negate.test(arg);
key = toOptionKey(arg, negated, opts);
if(flag) {
output.flags[key] = negated ? false : true;
}else{
if(!output.options[key]) {
output.options[key] = value;
}else{
if(!Array.isArray(output.options[key])) {
output.options[key] = [output.options[key]];
}
output.options[key].push(value);
}
}
return result;
}
module.exports = function parse(args, opts) {
opts = opts || {}; opts.alias = opts.alias || {};
opts.flags = opts.flags || [], opts.options = opts.options || [];
args = args || process.argv.slice(2); args = args.slice(0);
var output = {flags: {}, options: {},
raw: args.slice(0), stdin: false, unparsed: []};
var i, arg, l = args.length, key, skip, larg, sarg;
for(i = 0;i < l;i++) {
if(!args[0]) break;
arg = '' + args.shift(), skip = false;
larg = lre.test(arg);
opts.options.forEach(function(o){
if(~arg.indexOf(o)) larg = true;
});
if(arg == short) {
output.stdin = true;
}else if(arg == long) {
output.unparsed = output.unparsed.concat(args.slice(i)); break;
}else if(larg) {
skip = options(arg, output, args[0], opts);
}else if(sre.test(arg)) {
skip = flags(arg, output, args[0], opts);
}else{
output.unparsed.push(arg);
}
if(skip) args.shift(); l--; i--;
}
return output;
}
|
JavaScript
| 0 |
@@ -689,22 +689,8 @@
eys,
- skip = false,
i =
@@ -839,26 +839,12 @@
gth;
+
i++
-, key = keys%5Bi%5D
) %7B%0A
@@ -1140,23 +1140,8 @@
%7D%0A
- return skip;%0A
%7D%0A%0Af
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.