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 |
|---|---|---|---|---|---|---|---|
0baf1e9538cb1ac86ce96377c5a44d28eddfd584 | Update bacon.model.js | dist/bacon.model.js | dist/bacon.model.js | (function() {
var Bacon, init,
__slice = [].slice;
init = function(Bacon) {
var Lens, Model, defaultEquals, fold, globalModCount, id, idCounter, isModel, nonEmpty, sameValue, shallowCopy, valueLens;
id = function(x) {
return x;
};
nonEmpty = function(x) {
return x.length > 0;
};
fold = function(xs, seed, f) {
var x, _i, _len;
for (_i = 0, _len = xs.length; _i < _len; _i++) {
x = xs[_i];
seed = f(seed, x);
}
return seed;
};
isModel = function(obj) {
return obj instanceof Bacon.Property;
};
globalModCount = 0;
idCounter = 1;
defaultEquals = function(a, b) {
return a === b;
};
sameValue = function(eq) {
return function(a, b) {
return !a.initial && eq(a.value, b.value);
};
};
Model = Bacon.Model = function(initValue) {
var currentValue, eq, model, modificationBus, myId, myModCount, syncBus, valueWithSource;
myId = idCounter++;
eq = defaultEquals;
myModCount = 0;
modificationBus = new Bacon.Bus();
syncBus = new Bacon.Bus();
currentValue = void 0;
valueWithSource = Bacon.update({
initial: true
}, [modificationBus], (function(_arg, _arg1) {
var changed, f, modStack, newValue, source, value;
value = _arg.value;
source = _arg1.source, f = _arg1.f;
newValue = f(value);
modStack = [myId];
changed = newValue !== value;
return {
source: source,
value: newValue,
modStack: modStack,
changed: changed
};
}), [syncBus], (function(_, syncEvent) {
return syncEvent;
})).skipDuplicates(sameValue(eq)).changes().toProperty();
model = valueWithSource.map(".value").skipDuplicates(eq);
model.subscribeInternal(function(event) {
if (event.hasValue()) {
return currentValue = event.value();
}
});
if (!model.id) {
model.id = myId;
}
model.addSyncSource = function(syncEvents) {
return syncBus.plug(syncEvents.filter(function(e) {
return e.changed && !Bacon._.contains(e.modStack, myId);
}).doAction(function() {
return Bacon.Model.syncCount++;
}).map(function(e) {
return shallowCopy(e, "modStack", e.modStack.concat([myId]));
}).map(function(e) {
return valueLens.set(e, model.syncConverter(valueLens.get(e)));
}));
};
model.apply = function(source) {
modificationBus.plug(source.toEventStream().map(function(f) {
return {
source: source,
f: f
};
}));
return valueWithSource.changes().filter(function(change) {
return change.source !== source;
}).map(function(change) {
return change.value;
});
};
model.addSource = function(source) {
return model.apply(source.map(function(v) {
return function() {
return v;
};
}));
};
model.modify = function(f) {
return model.apply(Bacon.once(f));
};
model.set = function(value) {
return model.modify(function() {
return value;
});
};
model.get = function() {
return currentValue;
};
model.syncEvents = function() {
return valueWithSource.toEventStream();
};
model.bind = function(other) {
this.addSyncSource(other.syncEvents());
return other.addSyncSource(this.syncEvents());
};
model.lens = function(lens) {
var lensed;
lens = Lens(lens);
lensed = Model();
this.addSyncSource(model.sampledBy(lensed.syncEvents(), function(full, lensedSync) {
return valueLens.set(lensedSync, lens.set(full, lensedSync.value));
}));
lensed.addSyncSource(this.syncEvents().map(function(e) {
return valueLens.set(e, lens.get(e.value));
}));
return lensed;
};
model.syncConverter = id;
if (arguments.length >= 1) {
model.set(initValue);
}
return model;
};
Bacon.Model.syncCount = 0;
Model.combine = function(template) {
var initValue, key, lens, lensedModel, model, value;
if (typeof template !== "object") {
return Model(template);
} else if (isModel(template)) {
return template;
} else {
initValue = template instanceof Array ? [] : {};
model = Model(initValue);
for (key in template) {
value = template[key];
lens = Lens.objectLens(key);
lensedModel = model.lens(lens);
lensedModel.bind(Model.combine(value));
}
return model;
}
};
Bacon.Binding = function(_arg) {
var events, externalChanges, get, initValue, inputs, model, set;
initValue = _arg.initValue, get = _arg.get, events = _arg.events, set = _arg.set;
inputs = events.map(get);
if (initValue != null) {
set(initValue);
} else {
initValue = get();
}
model = Bacon.Model(initValue);
externalChanges = model.addSource(inputs);
externalChanges.assign(set);
return model;
};
Lens = Bacon.Lens = function(lens) {
if (typeof lens === "object") {
return lens;
} else {
return Lens.objectLens(lens);
}
};
Lens.id = Lens({
get: function(x) {
return x;
},
set: function(context, value) {
return value;
}
});
Lens.objectLens = function(path) {
var keys, objectKeyLens;
objectKeyLens = function(key) {
return Lens({
get: function(x) {
return x[key];
},
set: function(context, value) {
return shallowCopy(context, key, value);
}
});
};
keys = Bacon._.filter(nonEmpty, path.split("."));
return Lens.compose.apply(Lens, Bacon._.map(objectKeyLens, keys));
};
Lens.compose = function() {
var args, compose2;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
compose2 = function(outer, inner) {
return Lens({
get: function(x) {
return inner.get(outer.get(x));
},
set: function(context, value) {
var innerContext, newInnerContext;
innerContext = outer.get(context);
newInnerContext = inner.set(innerContext, value);
return outer.set(context, newInnerContext);
}
});
};
return fold(args, Lens.id, compose2);
};
valueLens = Lens.objectLens("value");
shallowCopy = function(x, key, value) {
var copy, k, v;
copy = x instanceof Array ? [] : {};
for (k in x) {
v = x[k];
copy[k] = v;
}
if (key != null) {
copy[key] = value;
}
return copy;
};
return Bacon;
};
if (typeof module !== "undefined" && module !== null) {
try {
Bacon = require("baconjs");
} catch (e) {
Bacon = require("bacon");
}
}
module.exports = init(Bacon);
} else {
if (typeof define === "function" && define.amd) {
define(["bacon"], init);
} else {
init(this.Bacon);
}
}
}).call(this);
| JavaScript | 0.000001 | @@ -7178,22 +7178,16 @@
;%0A %7D%0A
- %7D%0A
modu
|
84cd7a0248b7cb54a87eb6013e9a59ce56274fa1 | Update jQuery path in tests too | test/test-creation.js | test/test-creation.js | /*global describe, beforeEach, it*/
'use strict';
var path = require('path');
var fs = require('fs');
var helpers = require('yeoman-generator').test;
var temp = require('temp');
var assert = require('assert');
var exec = require('child_process').exec;
var async = require('async');
// # TESTS
describe('playground generator', function () {
after(function () {
temp.cleanup();
});
describe('Default scaffolding', function () {
before(function (done) {
runGenerator(this, {
includeNormalize: true,
includeJQuery: true
}, done);
});
it('creates expected files', function () {
var expected = [
'index.html',
'js/app.js',
'css/style.css',
'Gruntfile.js',
'package.json',
'bower.json'
];
helpers.assertFiles(expected);
});
it('links the JS and CSS file in the HTML', function (done) {
fs.readFile(path.join(this.workspace, 'index.html'), {
encoding: 'utf8'
}, function (err, html) {
if (err) {
assert.fail();
}
var containsCSSLink = html.indexOf('<link rel="stylesheet" href="css/style.css">') !== -1;
var containsJSLink = html.indexOf('<script src="js/app.js"></script>') !== -1;
assert.ok(containsCSSLink, 'Missing link to CSS file');
assert.ok(containsJSLink, 'Missing link to JS file');
done();
});
});
it('initialises a Git repository', function (done) {
exec('git status', {cwd: this.workspace}, function (err, stdout) {
console.log(err);
console.log(stdout);
});
exec('git log -1 --pretty=%s', {cwd: this.workspace}, function (err, stdout) {
if (err) {
console.log(err);
assert.fail('An error occured when checking git logs');
}
assert.equal(stdout.trim(), 'Created playground'.trim());
done();
});
});
});
describe('Normalize.css', function () {
it('includes normalize.css when accepting prompt', function (done) {
runGenerator(this, {
includeNormalize: true,
includeJQuery: true
}, function () {
async.parallel([
assertHTMLHasStylesheet(path.join(this.workspace, 'index.html'),
'bower_components/normalize-css/normalize.css'),
assertBowerDependencyIsPresent(path.join(this.workspace, 'bower.json'), 'normalize-css')
], function () {
done();
});
}.bind(this));
});
it('does not include normalize.css when declined prompt', function (done) {
runGenerator(this, {
includeNormalize: false,
includeJQuery: true
}, function () {
async.parallel([
assertHTMLHasStylesheet(path.join(this.workspace, 'index.html'),
'bower_components/normalize-css/normalize.css', true),
assertBowerDependencyIsPresent(path.join(this.workspace, 'bower.json'), 'normalize-css', true)
], function () {
done();
});
}.bind(this));
});
});
describe('jQuery', function () {
it('includes jQuery when accepting prompt', function (done) {
runGenerator(this, {
includeNormalize: true,
includeJQuery: true
}, function () {
async.parallel([
assertHTMLHasScript(path.join(this.workspace, 'index.html'),
'bower_components/jquery/jquery.js'),
assertBowerDependencyIsPresent(path.join(this.workspace, 'bower.json'), 'jquery')
], function () {
done();
});
}.bind(this));
});
it('includes jQuery when accepting prompt', function (done) {
runGenerator(this, {
includeNormalize: true,
includeJQuery: false
}, function () {
async.parallel([
assertHTMLHasScript(path.join(this.workspace, 'index.html'),
'bower_components/jquery/jquery.js', true),
assertBowerDependencyIsPresent(path.join(this.workspace, 'bower.json'), 'jquery', true)
], function () {
done();
});
}.bind(this));
});
});
});
// # HELPER FUNCTIONS
function runGenerator(context, promptAnswers, done) {
var workspace = context.workspace = temp.mkdirSync();
helpers.testDirectory(workspace, function (err) {
if (err) {
return done(err);
}
this.app = helpers.createGenerator('playground:app', [
path.resolve(__dirname, '../app')
]);
helpers.mockPrompt(this.app, promptAnswers);
this.app.options['skip-install'] = true;
console.log('Default run');
this.app.run({}, function () {
done();
});
}.bind(context));
}
function assertHTMLHasStylesheet(htmlFile, stylesheetURL, not) {
return function (done) {
fs.readFile(htmlFile, {encoding: 'utf8'}, function (err, html) {
if (err) {
assert.fail(err);
}
var linkHTML = '<link rel="stylesheet" href="' + stylesheetURL + '">';
var containsLink = html.indexOf(linkHTML) !== -1;
if (not) {
containsLink = !containsLink;
}
assert.ok(containsLink);
done();
});
};
}
function assertHTMLHasScript(htmlFile, scriptURL, not) {
return function (done) {
fs.readFile(htmlFile, {encoding: 'utf8'}, function (err, html) {
if (err) {
assert.fail(err);
}
var scriptHTML = '<script src="' + scriptURL + '">';
var containsLink = html.indexOf(scriptHTML) !== -1;
if (not) {
containsLink = !containsLink;
}
assert.ok(containsLink);
done();
});
};
}
function assertBowerDependencyIsPresent(bowerJson, dependencyName, not) {
return function (done) {
fs.readFile(bowerJson, {encoding: 'utf8'}, function (err, json) {
if (err) {
assert.fail(err);
}
var contents = JSON.parse(json);
var hasDependency = contents.dependencies[dependencyName];
if (not) {
hasDependency = !hasDependency;
}
assert.ok(hasDependency);
done();
});
};
} | JavaScript | 0 | @@ -3480,32 +3480,37 @@
mponents/jquery/
+dist/
jquery.js'),%0A
@@ -4018,16 +4018,21 @@
/jquery/
+dist/
jquery.j
@@ -6150,28 +6150,29 @@
done();%0A %7D);%0A %7D;%0A%7D
+%0A
|
1dd95d4a2411dd77e8be40b465793952a7743876 | Update img-preload.js | dist/img-preload.js | dist/img-preload.js | /*!
* jQuery-Img-Preload - 16th Out 2015
* https://github.com/miamarti/jquery-img-preload
*
* Licensed under the MIT license.
* http://opensource.org/licenses/MIT
*/
$.imgPreload = function(){
var options;
var planned = 0;
var loaded = 0;
var callback = new Function();
if(typeof arguments[1] === 'function'){
callback = arguments[1];
options = arguments[2];
} else {
options = arguments[1];
}
var defaults = {
attribute: 'url'
};
var settings = $.extend({}, defaults, options);
for(var key in arguments[0]){
planned++;
}
for(var key in arguments[0]){
(new Image()).src = arguments[0][key][settings.attribute];
$($("<img />").attr("src", arguments[0][key][settings.attribute])).load(function() {
loaded++;
});
}
var watchdog = function(){
if(planned === loaded){
callback();
} else {
setTimeout(watchdog, 10);
}
};
watchdog();
};
| JavaScript | 0.000001 | @@ -193,612 +193,348 @@
ion(
-)%7B%0A var options;%0A var planned = 0;%0A var loaded = 0;%0A var callback = new Function();%0A%0A if(typeof arguments%5B1%5D === 'function')%7B%0A callback = arguments%5B1%5D;%0A options = arguments%5B2%5D;%0A %7D else %7B%0A options = arguments%5B1%5D;
+config, callback)%7B%0A if(config)%7B%0A $(config.loading).fadeIn('slow');%0A%0A var div = $('%3Cdiv/%3E');%0A $('body').append(div);%0A
%0A
-%7D%0A%0A
-var defaults = %7B%0A attribute: 'url'%0A %7D;%0A var settings = $.extend(%7B%7D, defaults, options);%0A%0A for(var key in arguments%5B0%5D)%7B%0A planned++;
+for(var key in config.list)%7B%0A $(div).append($('%3Cimg/%3E').attr('src', config.list%5Bkey%5D%5Bconfig.attr%5D));%0A %7D%0A
%0A
-%7D%0A%0A
-for(var key in arguments%5B0%5D)%7B%0A (new Image()).src = arguments%5B0%5D%5Bkey%5D%5Bsettings.attribute%5D;%0A $($(%22%3Cimg /%3E%22).attr(%22src%22, arguments%5B0%5D%5Bkey%5D%5Bsettings.attribute%5D)).load
+if(callback)%7B%0A callback();%0A setTimeout
(fun
@@ -540,17 +540,16 @@
nction()
-
%7B%0A
@@ -557,16 +557,28 @@
-loaded++
+ $(div).remove()
;%0A
@@ -587,81 +587,72 @@
-%7D);%0A
-%7D%0A%0A
-var watchdog = function()%7B%0A if(planned === loaded)%7B
+$(config.loading).fadeOut('slow');%0A %7D, 2000);
%0A
@@ -660,76 +660,89 @@
+%7D%0A%0A
-callback();%0A %7D else %7B%0A setTimeout(watchdog, 10
+ return %7B%0A clear: function()%7B%0A $(div).remove(
);%0A
@@ -748,18 +748,26 @@
-%7D%0A
+ %7D%0A
%7D;%0A
@@ -773,19 +773,9 @@
-watchdog();
+%7D
%0A%7D;%0A
|
fa9748caae2b33e8fec7bc751667162022774702 | fix naming | src/components/RevealAuction/RevealAuctionInfo.js | src/components/RevealAuction/RevealAuctionInfo.js | import React from 'react';
import {momentFromNow} from '../../lib/util';
import Button from 'material-ui/Button';
import Card, { CardActions, CardContent } from 'material-ui/Card';
import Typography from 'material-ui/Typography';
import './RevealAuctionInfo.css';
export const RevealAuctionInfo = (props) => {
const endsmomentFromNow = momentFromNow(props.registratesAt);
const hidden = props.registratesAt.year() === 1970;
const ethersacnUrl = process.env.REACT_APP_ETHERSCAN_URL || 'https://ropsten.etherscan.io/tx/';
const txHashUrl = ethersacnUrl + props.revealTXHash;
return (
<Card raised className="RevealAuctionInfo">
<CardContent>
<Typography type="title" component="div">
ENS: {props.searchResult.searchName}.eth
</Typography>
{ hidden ? null :
(
<Typography type="title" component="div">
<p>Finalize Auction On</p>
<div>{props.registratesAt.toString()}</div>
<div>{endsmomentFromNow.toString()}</div>
</Typography>
)
}
<Typography type="title" component="div">
Email: {props.email}
</Typography>
<Typography type="title" component="div">
ETH: {props.ethBid}
</Typography>
<Typography type="title" component="div">
Secret: {props.secret}
</Typography>
<Typography type="title" component="div">
TxHash: <a target='_blank' href={txHashUrl}>{props.revealTXHash}</a>
</Typography>
<CardActions className="RevealAuctionInfo-button">
<Button raised onClick={() => props.switchPage('main')}>BACK TO SEARCH</Button>
<Button raised>MY ENS LIST</Button>
</CardActions>
</CardContent>
</Card>
);
}; | JavaScript | 0.782388 | @@ -312,25 +312,25 @@
const ends
-m
+M
omentFromNow
@@ -993,17 +993,17 @@
iv%3E%7Bends
-m
+M
omentFro
|
c90be5e3c1ab10e20bea8fd6cf30739289339dd2 | set different doc homepage from v3.26.1 onward | scripts/generate_documentation_list.js | scripts/generate_documentation_list.js | #!/usr/bin/env node
/* eslint-env node */
/**
* Generate documentation list
* ===========================
*
* ## How it works
*
* This script will generate a page listing the documentation from various
* versions of the rx-player.
*
* The documentation should entirely be present in a directory called:
* `/versions/VERSION_NUMBER/doc`
*
* Where VERSION_NUMBER is the version number in a semantic versioning scheme.
*
* The documentation homepage should be present in:
* `/versions/VERSION_NUMBER/doc/pages/index.html`
*
* This script was not written with portability in mind (it would have taken too
* much time). It might thus break if file organization changes in this project.
*
*
* ## How to run it
*
* To run this:
*
* 1. Be sure you are in the gh-pages branch
*
* 2. Call this script directly
*
* 3. a new file, `documentation_pages_by_version.html` should have been
* generated with all the right links.
*/
const fs = require("fs");
const path = require("path");
const sanitizeHTML = require("sanitize-html");
const semver = require("semver");
const INITIAL_PATH = "./versions";
function sortVersions(versions) {
return versions
.filter(v => semver.valid(v) != null)
.sort((a, b) => semver.gt(a, b) ? -1 : 1);
}
function isDirectory(source) {
return fs.lstatSync(source).isDirectory();
}
const style = `<style type="text/css">
body { font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; color: #333; }
ul { list-style-type: square; }
li { margin-top: 8px; }
a { color: #006; }
a:hover { color: #076; }
</style>`;
const head = `<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
<title>RxPlayer - Documentation pages by version</title>
${style}
</head>`;
let body = "<body>";
const files = fs.readdirSync(INITIAL_PATH);
const versions = [];
for (let i = 0; i < files.length; i++) {
const fileName = files[i];
const filePath = path.join(INITIAL_PATH, fileName);
if (isDirectory(filePath) && fs.existsSync(path.join(filePath, "doc"))) {
versions.push(fileName);
}
}
if (versions.length <= 0) {
body += "<h1>No Documentation Available</h1>";
} else {
body += "<h1>Documentation pages by version</h1>";
body += "<ul>";
const sortedVersions = sortVersions(versions);
for (let i = 0; i < sortedVersions.length; i++) {
const version = sortedVersions[i];
// const versionAsNumber = +version.split(".").join();
const dirPath = path.join(INITIAL_PATH, version, "doc/pages/index.html");
body += `<li><a href=${sanitizeHTML(dirPath)}>` +
sanitizeHTML(version) +
"</a></li>";
}
body += "</ul>";
}
body += "<body/>";
const html = "<html>" +
head +
body +
"<html>";
fs.writeFileSync("./documentation_pages_by_version.html", html);
| JavaScript | 0 | @@ -2405,86 +2405,186 @@
i%5D;%0A
+%0A
//
-const versionAsNumber = +version.split(%22.%22).join();%0A const dirPath =
+documentation homepage changed for the v3.26.1%0A const dirPath = semver.gte(version, %223.26.1%22) ?%0A path.join(INITIAL_PATH, version, %22doc/api/Overview.html%22) :%0A
pat
@@ -2638,16 +2638,17 @@
html%22);%0A
+%0A
body
|
2f88de854fa7ce9fc7d49928d77064f8b7674a99 | introduce tryCatch() | server/08-functional/004-chain.spec.js | server/08-functional/004-chain.spec.js | /*eslint no-shadow: "off"*/
/*eslint no-unused-vars: "off"*/
/*eslint eqeqeq: "off"*/
import fs from 'fs';
const Right = x =>
({
map: f => Right(f(x)),
fold: (f, g) => g(x),
inspect: () => `Right(${x})`
});
const Left = x =>
({
map: f => Left(x),
fold: (f, g) => f(x),
inspect: () => `Left(${x})`
});
const fromNullable = x =>
x != null ? Right(x) : Left(null);
const getPort = () =>{
try {
const s = fs.readFileSync('server/08-functional/config.json');
const config = JSON.parse(s);
return config.port;
} catch (e) {
return 3000;
}
};
describe('', () => {
it('getPort', () => {
getPort().should.equal(8888);
});
});
| JavaScript | 0 | @@ -385,23 +385,24 @@
nst
-getPort = ()
+tryCatch = f
=%3E
+
%7B%0A
@@ -415,17 +415,111 @@
-const s
+return Right( f() );%0A %7D catch (e) %7B%0A return Left(e);%0A %7D%0A%7D;%0A%0Aconst getPort = () =%3E%0A tryCatch(()
=
+%3E
fs.
@@ -570,28 +570,21 @@
on')
-;%0A const config
+)%0A .map(c
=
+%3E
JSO
@@ -595,87 +595,93 @@
rse(
-s);%0A return config.port;%0A %7D catch (e) %7B%0A return 3000;%0A %7D%0A%7D;%0A%0Adescribe('
+c))%0A .fold(%0A e =%3E 3000,%0A c =%3E c.port%0A );%0A%0Adescribe('composable error handling
', (
|
895a79047c0c76eef9dffc74da720a52cefef12e | refactor PUT request | server/api/photos/photos.controller.js | server/api/photos/photos.controller.js | //helpful: http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/node-examples.html
var controller = module.exports;
var request = require('request');
var Photo = require('./photos.model.js');
var seed = require('./photos.seed.js');
var AWS = require('aws-sdk');
AWS.config.region = 'us-west-1';
var s3 = new AWS.S3();
var fs = require('fs');
//sets up key and secret as env variables from a file that is .gitignored.
require('./aws_keys.js');
controller.getOne = function(req, res) {
//DEPRECATED. photo get requests should go directly to S3, not through our server.
Photo.where({id:req.params.id}).fetch({
withRelated: ['user']
}).then(function (photo) {
if(photo){
res.json(photo);
} else {
res.status(404).end();
}
});
};
controller.getAll = function(req, res) {
//DEPRECATED. photo get requests should go directly to S3, not through our server.
Photo.fetchAll({
withRelated: ['user']
}).then(function (collection) {
res.json(collection);
});
};
//POSTING A PHOTO: intended process
//client sends a GET to api/phots/addnew. includes user id, event name, file extension, other details.
//server creates an entry in photos table. generates and returns presigned S3 URL to client.
//client then uses presigned URL to upload the photo to S3.
//if successful upload: just say 'photo uploaded!'
//if error: notify client that upload failed, and notify server so it can drop that recently created record.
//TODO: photo bucket currently allows anonymous read/write access. refactor this.
//should allow credentialed read-write access (for dev environment - have api keys cached on dev machine)
//images can be viewed by the client very simply, like this:
//<img src='https://s3-us-west-1.amazonaws.com/base9photos/UNIQUE_FILE_NAME.jpg'></img>
controller.s3GetTest = function(){
console.log('s3 request received');
var fileName = 'calvin.jpg';
var params = {Bucket: 'base9photos', Key: fileName};
var file = require('fs').createWriteStream(fileName);
s3.getObject(params).createReadStream().pipe(file)
.on('finish',function(){
console.log('download complete of ' + fileName);
});
}
controller.s3PostTest = function(){
console.log('s3 post request received');
var fs = require('fs');
var zlib = require('zlib');
var fileName = 'ch.jpg';
var body = fs.createReadStream(fileName).pipe(zlib.createGzip());
var s3obj = new AWS.S3({params: {Bucket: 'base9photos', Key: 'ch.zip'}});
s3obj.upload({Body: body}).
on('httpUploadProgress', function(evt) { console.log(evt); }).
send(function(err, data) { console.log(err, data) });
}
controller.s3SignedPostTest = function(req,res){
console.log('req received for signed PUT url')
var params = {Bucket: 'base9Photos', Key: 'aNewFile.jpg'};
var url = s3.getSignedUrl('putObject', params);
console.log("The URL is", url);
res.json(url);
}
| JavaScript | 0.000084 | @@ -257,41 +257,8 @@
');%0A
-AWS.config.region = 'us-west-1';%0A
var
@@ -2728,17 +2728,17 @@
: 'base9
-P
+p
hotos',
@@ -2860,16 +2860,77 @@
n(url);%0A
+ fs.createReadStream('candles.jpg').pipe(request.put(url));%0A
%7D%0A%0A%0A%0A%0A%0A%0A
|
3d0f59d99c520f4fa8d90734c94baad26dae5f1f | Create User API | server/controllers/login.controller.js | server/controllers/login.controller.js | var mongoose = require('mongoose');
require('../models/session');
require('../models/user')
var SessionSchema = require('mongoose').model('Session').schema;
var UserSchema = require('mongoose').model('User').schema;
var bigrandom = require('bigrandom');
/**
*Create a new user account
*/
function generateUserAccount(username,password,email,firstname,lastname,isadmin) {
var User = mongoose.model('User', UserSchema);
var user_data = {
'username': username
'password': password
'email': email
};
var user = new User(user_data);
user.save(
function(err, data){
if (err){
console.error(err)
} else {
//console.log('session record created: ' + data +' | data type: ' + (typeof data));
}
} ;
)
}
/**
* generate a random 128-bit ID, save it to the session database
*/
function generateSessionID(username) {
var Session = mongoose.model('Session', SessionSchema);
var random128bitHexString = bigrandom();
// TODO: Needs to create new record
// check if exists in session table (may not need to sort checkSession query results if we avoid duplicates by checking here)
// make new entry
var session_data = {
'username': username,
'sessionId': random128bitHexString
};
var session = new Session(session_data);
session.save(
function(err, data){
if (err){
console.error(err)
} else {
//console.log('session record created: ' + data +' | data type: ' + (typeof data));
}
}
);
// return '22f5832147f5650c6a1a999fbd97695d';
return random128bitHexString;
}
/**
* Check if the current sessionID is correct and is still valid
*/
function checkSession(sessionID, callback) {
// TODO: Needs to be tested againts database records, & proper return value is needed
var Session = mongoose.model('Session', SessionSchema);
var age = undefined;
Session.findOne(
{ 'sessionId': sessionID }, // username and sessionId should match arguments
'timestamp', // should return timestamp
function (err, session) {
if (err) {
console.error(err);
callback(false);
}
//console.log('QUERY -- session record returned: ' + session.timestamp +' | data type: ' + (typeof session.timestamp));
if(session){
var age = Date.now() - session.timestamp.getTime();
callback(age < 10800000); //fails if session is > 3hrs old
} else {
callback(false);
}
}
).sort({'timestamp': -1}); // I think this will make it return the most recent match if there is more than 1, but this needs to be verified
}
/**
* Check if User's credentials are correct
*/
function checkCredentials(username, password, callback) {
// TODO: Needs to be tested againts database records, & proper return value is needed
var User = mongoose.model('User', UserSchema);
User.findOne(
{ 'username': username, 'password': password}, // username and password should match arguments
'isAdmin', //doesn't really matter what value we get back since we aren't using it (just need to see if record exists, theres probably a better way (count()))
function (err, user) {
if (err) {
console.error(err);
callback(false);
}
//console.log('user record returned: ' + user +' | data type: ' + (typeof user));
if(user){
callback(true, user.isAdmin);
} else {
callback(false);
}
}
);
}
/**
*
* @param req
* @param res
* @returns void
*/
export function login(req, res) {
// if the user hasn't logged in before, check their credentials and then generate a sessionID
checkSession(req.cookies.sessionID, (sessionIsValid) => {
if (sessionIsValid === true) {
// check if the user already has a sessionID, they have already logged in -> proceed
res.status(200).end();
} else {
if (!req.body.username || !req.body.password) {
res.status(403).end();
} else {
checkCredentials(req.body.username, req.body.password, (credsAreValid, isAdmin)=> {
if (credsAreValid === true) {
// Generate a new session that is valid for 3 hours from now
res.cookie('sessionID', generateSessionID(req.body.username), { maxAge: 10800 });
res.send({
isAdmin: isAdmin
});
res.status(200).end();
} else {
res.status(401).end();
}
})
}
}
})
}
export function logout(req, res) {
var Session = mongoose.model('Session', SessionSchema);
if (req.cookies.sessionID !== null) {
Session.remove({ 'sessionId': req.cookies.sessionID }, function(err) {
if (!err) {
res.status(200).end();
}
else {
res.status(400).end();
}
});
}
}
| JavaScript | 0 | @@ -340,27 +340,8 @@
ail,
-firstname,lastname,
isad
@@ -440,16 +440,17 @@
username
+,
%0A 'pa
@@ -466,16 +466,17 @@
password
+,
%0A 'em
@@ -486,16 +486,40 @@
': email
+,%0A 'isAdmin': isAdmin
%0A %7D;%0A
@@ -755,16 +755,15 @@
%7D
- ;
%0A )
+;
%0A%7D%0A/
|
d27d7de30409606dc8ae27276cb41085308238ba | remove team from Task | server/models/Task.js | server/models/Task.js | "use strict";
module.exports = function(imports) {
let mongoose = imports.modules.mongoose;
let Schema = mongoose.Schema;
let ObjectId = Schema.Types.ObjectId;
let taskSchema = new Schema({
name: {
type: String,
required: true
},
description: {
type: String,
required: false
},
team: {
type: ObjectId,
ref: "Team",
required: true
},
for: {
type: ObjectId,
ref: "User"
},
due_date: {
type: Date,
required: true
},
creator: {
type: ObjectId,
ref: "User"
},
completed: Boolean,
created_at: Date,
updated_at: Date,
});
taskSchema.pre("save", function(next) {
let now = new Date();
this.updated_at = now;
if (!this.created_at) {
this.created_at = now;
}
next();
});
let Task = mongoose.model("Task", taskSchema);
return Task;
};
| JavaScript | 0.000018 | @@ -375,115 +375,8 @@
%7D,%0A
- team: %7B%0A type: ObjectId,%0A ref: %22Team%22,%0A required: true%0A %7D,%0A
|
7e378e40494c1e03771abbec1ce29f69cf8cd0dc | add comments for possible future refactoring | data/socket.js | data/socket.js | // core frameworks
var io = require('socket.io')(server);
var _ = require('underscore');
var repo = require('./repository');
// sockets!
io.on('connection', function(socket){
socket.on("joinRoom", function(data){
socket.join(data.roomkey, function(error){
socket.username = data.username;
repo.createUser(data.roomkey, data.username, socket.id);
repo.getUsers(data.roomkey, function(err, users){
socket.emit("joinedGame", users);
});
socket.broadcast.to(data.roomkey).emit('newPlayer', data.username);
if(error){console.log("error:" + error);}
});
});
// need to use inside every getHand callback
function jsonParser(data) {
var jsonCards = [];
for ( i=0; i < data.length; i++) {
jsonCards.push(JSON.parse(data[i]))
}
return jsonCards;
}
// Deal cards to all users in a room
socket.on("dealCards", function(data){
console.log(data);
// need to transfer the data of faceDown card attribute to cards
var roomKey = socket.rooms[1];
repo.createDeck(roomKey);
repo.dealUsersCards(roomKey, parseInt(data.dealingCount));
updateAllUserHands(roomKey);
});
// Pass a card from one user to another
socket.on("passCard", function(data){
var roomKey = socket.rooms[1];
repo.passCard(roomKey, socket.username, data.toUser, data.cardId);
updateAllUserHands(roomKey);
});
// Draw a card from the deck
socket.on("drawCard", function(){
var roomKey = socket.rooms[1];
var username = socket.username;
var socketId = socket.id;
repo.dealUserCard(roomKey, username);
updateUserHand(roomKey, username, socketId);
});
// Pass a card to the table from the user's hand
socket.on("passTable", function(cardId){
var roomKey = socket.rooms[1];
var username = socket.username;
var socketId = socket.id;
repo.passCard(roomKey, username, "Table", cardId);
updateUserHandAndTable(roomKey, username, socketId);
});
// User collects all the cards on the table
socket.on("userCollectsTable", function(){
var roomKey = socket.rooms[1];
var username = socket.username;
var socketId = socket.id;
repo.getTable(roomKey, username);
setTimeout(function(){
updateUserHandAndTable(roomKey, username, socketId);
}, 105);
});
// User discards a card from his/her hand
socket.on("userDiscardsCard", function(cardId){
var roomKey = socket.rooms[1];
var username = socket.username;
var socketId = socket.id;
repo.passCard(roomKey, username, "Discard", cardId);
updateUserHand(roomKey, username, socketId);
});
// User obtains a card from a table
socket.on("getTableCard", function(cardId){
var roomKey = socket.rooms[1];
var username = socket.username;
var socketId = socket.id;
repo.passCard(roomKey, "Table", username, cardId);
setTimeout(function(){
updateUserHandAndTable(roomKey, username, socketId);
}, 105);
});
// Discard a card from the table
socket.on("discardTableCard", function(cardId){
var roomKey = socket.rooms[1];
repo.passCard(roomKey, "Table", "Discard", cardId);
updateTableView(roomKey);
});
});
// Refactoring Functions
// Update User's Hand
function updateUserHand(roomKey, username, socketId){
repo.getHand(roomKey, username, function(err, data){
io.to(socketId).emit("updateHand", data.sort());
});
}
// Update Table for each client
function updateTableView(roomKey){
repo.getUserKeys(roomKey, function(err, keys){
keys.forEach(function(key){
repo.getHand(roomKey, "Table", function(err, data){
io.to(key).emit("updateTable", jsonParser(data));
})
})
})
}
// Update Hands for all users
function updateAllUserHands(roomKey){
repo.getUserKeys(roomKey, function(err, keys){
keys.forEach(function(key){
repo.getUser(roomKey, key, function(err, username){
repo.getHand(roomKey, username, function(err, data){
io.to(key).emit("updateHand", jsonParser(data));
})
})
})
})
}
// Update the user's hand that activated the event and update the table
function updateUserHandAndTable(roomKey, username, socketId){
repo.getHand(roomKey, username, function(err, data){
io.to(socketId).emit("updateHand", data.sort());
updateTableView(roomKey);
});
} | JavaScript | 0 | @@ -1,12 +1,12 @@
//
-c
+C
ore fram
@@ -122,17 +122,17 @@
');%0A%0A//
-s
+S
ockets!%0A
@@ -168,16 +168,39 @@
socket)%7B
+%0A%0A // User enters room
%0A socke
@@ -2218,24 +2218,66 @@
username);%0A
+ // Possible to get around setTimeout?%0A
setTimeo
@@ -2914,24 +2914,66 @@
e, cardId);%0A
+ // Possible to get around setTimeout?%0A
setTimeo
@@ -3295,19 +3295,18 @@
Refactor
-ing
+ed
Functio
|
aab7eef7b322176d5719af3b4493034ab90aaf69 | Fix primary key bug | server/models/user.js | server/models/user.js | module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
username: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
},
password: {
type: DataTypes.STRING,
allowNull: false,
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
isEmail: {
args: true,
msg: 'Invalid email address'
},
}
},
salt: DataTypes.STRING
});
User.associate = (models) => {
User.hasMany(models.Message, {
foreignKey: 'userId'
});
User.belongsToMany(models.Group, {
as: 'Members',
foreignKey: 'groupId',
through: 'UserGroup',
});
};
return User;
};
| JavaScript | 0.000003 | @@ -646,16 +646,19 @@
%7B%0A
+ //
as: 'Me
@@ -688,13 +688,12 @@
y: '
-group
+user
Id',
@@ -718,16 +718,17 @@
serGroup
+s
',%0A %7D
|
38284608ed476aa3c47ce0fb3e9f554e4d4422c1 | Fix bug | lib/RedshiftBulkInsert.js | lib/RedshiftBulkInsert.js | var aws = require('aws-sdk');
var _ = require('underscore');
var util = require('util');
var SimpleFileWriter = require('simple-file-writer');
var log4js = require('log4js');
var path = require('path');
var fs = require('fs');
var events = require('events');
var EventEmitter = events.EventEmitter;
var logger = log4js.getLogger('redshift-bulk-insert');
module.exports = RedshiftBulkInsert;
var DELIMITER = '|';
var ESCAPE = '\\';
var NEWLINE = '\n';
var NULL = '\\N';
var SUFFIX = '.log';
util.inherits(RedshiftBulkInsert, EventEmitter);
function RedshiftBulkInsert(options) {
this._logger = logger;
this._fs = fs;
this._aws = aws;
this._date = Date;
this._pid = process.pid;
this._suffix = SUFFIX;
var pathToLogs = options.pathToLogs;
this._datastore = options.datastore;
this._tableName = options.tableName;
this._fields = options.fields;
this._pathToLogs = pathToLogs;
var idleFlushPeriod = options.idleFlushPeriod;
this._idleFlushPeriod = _.isNumber(idleFlushPeriod) ? idleFlushPeriod : 10000;
var threshold = options.threshold;
this._threshold = _.isNumber(threshold) ? threshold : 1000;
this._awsBucketName = options.awsBucketName;
this._awsAccessKeyId = options.awsAccessKeyId;
this._awsSecretAccessKey = options.awsSecretAccessKey;
this._awsrRegion = options.awsRegion;
this._numberOfEventsInFile = 0;
this.activeFlushOps = 0;
this._createFile();
this._s3 = this._createS3();
this.startIdleFlushMonitor();
}
RedshiftBulkInsert.prototype._createFile = function() {
var fileName = this._getLogFileName();
var pathToFile = path.join(pathToLogs, fileName);
this._fileName = fileName;
this._file = new SimpleFileWriter(pathToFile);
}
RedshiftBulkInsert.prototype._getLogFileName = function() {
return this._tableName + '_' + this._date.now() + '_' + this._pid + this._suffix;
};
RedshiftBulkInsert.prototype._createS3 = function() {
var options = {
region: this._awsRegion,
accessKeyId: this._awsAccessKeyId,
secretAccessKey: this._awsSecretAccessKey
};
return new this._aws.S3(options);
};
RedshiftBulkInsert.prototype.flush = function() {
if (this._numberOfEventsInFile > 0) {
this.activeFlushOps++;
var onFinishWriteToFile = _.bind(this._onFinishWriteToFile, this, this._fileName);
this._file.end(onFinishWriteToFile);
this._createFile();
this._numberOfEventsInFile = 0;
}
this.startIdleFlushMonitor();
};
RedshiftBulkInsert.prototype._onFinishWriteToFile = function(fileName) {
var sendToS3 = _.bind(this._sendToS3, this, fileName, this._date.now());
var oldPathToFile = path.join(this._pathToLogs, fileName);
this._fs.readFile(oldPathToFile, sendToS3);
};
RedshiftBulkInsert.prototype._sendToS3 = function(fileName, start, err, body) {
if (err) {
this._logger.error(err);
this._decrimentActiveFlushOpsAndEmitFlushEvent(start, err, body);
return;
}
var params = {
Body: body,
Key: fileName,
Bucket: this._awsBucketName
};
var onSentToS3 = _.bind(this._onSentToS3, this, fileName, start);
this._s3.putObject(params, onSentToS3);
};
RedshiftBulkInsert.prototype._onSentToS3 = function(fileName, start, err, data) {
if (err) {
this._logger.error(err);
this._decrimentActiveFlushOpsAndEmitFlushEvent(start, err, data);
return;
}
this._removeLogFile(fileName, start);
var onSentCopyToRedshift = _.bind(this._onSentCopyToRedshift, this, start);
var query = this._getCopyQuery(fileName);
this._datastore.query(query, onSentCopyToRedshift);
};
RedshiftBulkInsert.prototype._removeLogFile = function(fileName, start) {
var pathToFile = path.join(this._pathToLogs, fileName);
var onRemoved = _.bind(this._decrimentActiveFlushOpsAndEmitFlushEvent, this, start);
this._fs.unlink(pathToFile, onRemoved);
};
RedshiftBulkInsert.prototype._getCopyQuery = function(fileName) {
return 'COPY '
+ this._tableName
+ ' ('
+ this._fields.join(', ')
+ ')'
+ ' FROM '
+ "'"
+ 's3://'
+ this._awsBucketName
+ '/'
+ fileName
+ "'"
+ ' CREDENTIALS '
+ "'aws_access_key_id="
+ this._awsAccessKeyId
+ ';'
+ 'aws_secret_access_key='
+ this._awsSecretAccessKey
+ "'"
+ ' ESCAPE';
};
RedshiftBulkInsert.prototype._onSentCopyToRedshift = function(start, err, result) {
if (err) {
this._logger.error(err);
}
this._decrimentActiveFlushOpsAndEmitFlushEvent(start, err, result);
};
RedshiftBulkInsert.prototype._decrimentActiveFlushOpsAndEmitFlushEvent = function(start, err, result) {
this.activeFlushOps--;
this.emit('flush', err, result, '', start, this);
};
RedshiftBulkInsert.prototype.insert = function(row) {
var line = this._rowToLine(row);
var self = this;
this._file.write(line + NEWLINE);
self._numberOfEventsInFile++;
self._checkThreshold();
};
RedshiftBulkInsert.prototype._checkThreshold = function() {
if (this._numberOfEventsInFile >= this._threshold) {
clearTimeout(this.ref);
this.flush();
}
};
RedshiftBulkInsert.prototype._rowToLine = function(row) {
var lineBuff = [];
for (var i = 0, l = row.length; i < l; i++) {
var value = row[i];
value = this._escapeValue(value);
lineBuff.push(value);
}
var line = lineBuff.join(DELIMITER);
return line;
};
RedshiftBulkInsert.prototype._escapeValue = function(value) {
if (value === null || value === undefined) {
return NULL;
}
if (_.isString(value)) {
return value.replace(/\\/g, '\\\\').replace(/\|/g, '\\|');
}
return value + '';
};
RedshiftBulkInsert.prototype.close = function() {
clearTimeout(this.ref);
this._file.end();
};
RedshiftBulkInsert.prototype.startIdleFlushMonitor = function() {
var flush = _.bind(this.flush, this);
this.ref = setTimeout(flush, this._idleFlushPeriod);
}; | JavaScript | 0.000001 | @@ -1573,16 +1573,22 @@
th.join(
+this._
pathToLo
@@ -1779,26 +1779,19 @@
+ this._
-date.now()
+pid
+ '_' +
@@ -1797,19 +1797,26 @@
+ this._
-pid
+date.now()
+ this.
@@ -2534,20 +2534,17 @@
);%0A%09var
-oldP
+p
athToFil
@@ -2609,12 +2609,9 @@
ile(
-oldP
+p
athT
|
781a1d833e3a1d4cd37b5a039bce96d99ef7aaf1 | Remove Async.wrap tests | tests/hijack/async.js | tests/hijack/async.js |
Tinytest.add(
'Async - track with Meteor._wrapAsync',
function (test) {
EnableTrackingMethods();
var methodId = RegisterMethod(function () {
var wait = Meteor._wrapAsync(function(waitTime, callback) {
setTimeout(callback, waitTime);
});
wait(100);
});
var client = GetMeteorClient();
var result = client.call(methodId);
var events = GetLastMethodEvents([0]);
var expected = [
['start'],
['wait'],
['async'],
['complete']
];
test.equal(events, expected);
CleanTestData('methodstore');
}
);
Tinytest.add(
'Async - track with Meteor._wrapAsync with error',
function (test) {
EnableTrackingMethods();
var methodId = RegisterMethod(function () {
var wait = Meteor._wrapAsync(function(waitTime, callback) {
setTimeout(function () {
callback(new Error('error'));
}, waitTime);
});
try {
wait(100);
} catch (ex) {
}
});
var client = GetMeteorClient();
var result = client.call(methodId);
var events = GetLastMethodEvents([0]);
var expected = [
['start'],
['wait'],
['async'],
['complete']
];
test.equal(events, expected);
CleanTestData('methodstore');
}
);
Tinytest.add(
'Async - track with Async.wrap with error',
function (test) {
test.fail('Async not defined');
// EnableTrackingMethods();
// var methodId = RegisterMethod(function () {
// var wait = Async.wrap(function(waitTime, callback) {
// setTimeout(function () {
// callback(new Error('error'));
// }, waitTime);
// });
// try {
// wait(100);
// } catch (ex) {
// }
// });
// var client = GetMeteorClient();
// var result = client.call(methodId);
// var events = GetLastMethodEvents([0]);
// var expected = [
// ['start'],
// ['wait'],
// ['async'],
// ['complete']
// ];
// test.equal(events, expected);
// CleanTestData('methodstore');
}
);
Tinytest.add(
'Async - track with Async.wrap with error and continue',
function (test) {
test.fail('Async not defined');
// EnableTrackingMethods();
// var methodId = RegisterMethod(function () {
// var wait = Async.wrap(function(waitTime, callback) {
// setTimeout(function () {
// callback(new Error('error'));
// }, waitTime);
// });
// try {
// wait(100);
// } catch (ex) {
// }
// TestData.find({}).fetch();
// });
// var client = GetMeteorClient();
// var result = client.call(methodId);
// var events = GetLastMethodEvents([0, 2]);
// var expected = [
// ['start',, {userId: null, params: '[]'}],
// ['wait',, {waitOn: []}],
// ['async',, {}],
// ['db',, {coll: 'tinytest-data', func: 'find', selector: JSON.stringify({})}],
// ['db',, {coll: 'tinytest-data', func: 'fetch', cursor: true, selector: JSON.stringify({}), docsFetched: 0}],
// ['complete']
// ];
// test.equal(events, expected);
// CleanTestData('methodstore', 'testdata');
}
);
| JavaScript | 0.000001 | @@ -552,37 +552,24 @@
eanTestData(
-'methodstore'
);%0A %7D%0A);%0A%0AT
@@ -1243,1915 +1243,8 @@
ata(
-'methodstore');%0A %7D%0A);%0A%0ATinytest.add(%0A 'Async - track with Async.wrap with error',%0A function (test) %7B%0A test.fail('Async not defined');%0A // EnableTrackingMethods();%0A // var methodId = RegisterMethod(function () %7B%0A // var wait = Async.wrap(function(waitTime, callback) %7B%0A // setTimeout(function () %7B%0A // callback(new Error('error'));%0A // %7D, waitTime);%0A // %7D);%0A // try %7B%0A // wait(100);%0A // %7D catch (ex) %7B%0A%0A // %7D%0A // %7D);%0A // var client = GetMeteorClient();%0A // var result = client.call(methodId);%0A // var events = GetLastMethodEvents(%5B0%5D);%0A // var expected = %5B%0A // %5B'start'%5D,%0A // %5B'wait'%5D,%0A // %5B'async'%5D,%0A // %5B'complete'%5D%0A // %5D;%0A // test.equal(events, expected);%0A // CleanTestData('methodstore');%0A %7D%0A);%0A%0ATinytest.add(%0A 'Async - track with Async.wrap with error and continue',%0A function (test) %7B%0A test.fail('Async not defined');%0A // EnableTrackingMethods();%0A // var methodId = RegisterMethod(function () %7B%0A // var wait = Async.wrap(function(waitTime, callback) %7B%0A // setTimeout(function () %7B%0A // callback(new Error('error'));%0A // %7D, waitTime);%0A // %7D);%0A // try %7B%0A // wait(100);%0A // %7D catch (ex) %7B%0A%0A // %7D%0A // TestData.find(%7B%7D).fetch();%0A // %7D);%0A // var client = GetMeteorClient();%0A // var result = client.call(methodId);%0A // var events = GetLastMethodEvents(%5B0, 2%5D);%0A // var expected = %5B%0A // %5B'start',, %7BuserId: null, params: '%5B%5D'%7D%5D,%0A // %5B'wait',, %7BwaitOn: %5B%5D%7D%5D,%0A // %5B'async',, %7B%7D%5D,%0A // %5B'db',, %7Bcoll: 'tinytest-data', func: 'find', selector: JSON.stringify(%7B%7D)%7D%5D,%0A // %5B'db',, %7Bcoll: 'tinytest-data', func: 'fetch', cursor: true, selector: JSON.stringify(%7B%7D), docsFetched: 0%7D%5D,%0A // %5B'complete'%5D%0A // %5D;%0A // test.equal(events, expected);%0A // CleanTestData('methodstore', 'testdata'
);%0A
|
68ef34ed4fcd1c7314616ac1e38419f703fe3e0e | test numbers for length rule | tests/rules/length.js | tests/rules/length.js | import validate from './../../src/rules/length';
test('validates number of characters in a string', () => {
// exact length
expect(validate('hey', [3])).toBe(true);
expect(validate('hello', [3])).toBe(false);
// min-max
expect(validate('hey', [4, 5])).toBe(false);
expect(validate('hello', [3, 5])).toBe(true);
expect(validate('hello there', [3, 5])).toBe(false);
});
test('null and undefined are always rejected', () => {
expect(validate(null, [3])).toBe(false);
expect(validate(undefined, [3])).toBe(false);
});
test('validates number of elements in an enumerable', () => {
const firstSet = new Set(['h', 'e', 'y']);
const secondSet = new Set(['h', 'e', 'l', 'l']);
expect(validate(firstSet, [3])).toBe(true);
expect(validate(secondSet, [4])).toBe(false);
// min-max
expect(validate(firstSet, [4, 5])).toBe(false);
expect(validate(secondSet, [3, 5])).toBe(true);
expect(validate(new Set(['h', 'e', 'l', 'l', 'o', ' ', 't', 'h', 'e', 'r', 'e']), [3, 5])).toBe(false);
});
test('validates number of elements in an array', () => {
// exact length
expect(validate(['h', 'e', 'y'], [3])).toBe(true);
expect(validate(['h', 'e', 'l', 'l', 'o'], [3])).toBe(false);
// min-max
expect(validate(['h', 'e', 'y'], [4, 5])).toBe(false);
expect(validate(['h', 'e', 'l', 'l', 'o'], [3, 5])).toBe(true);
expect(validate(['h', 'e', 'l', 'l', 'o', ' ', 't', 'h', 'e', 'r', 'e'], [3, 5])).toBe(false);
});
| JavaScript | 0.000001 | @@ -1458,28 +1458,132 @@
%5B3, 5%5D)).toBe(false);%0D%0A%7D);%0D%0A
+%0D%0Atest('validates strings consisting of numbers', () =%3E %7B%0D%0A expect(validate(123, %5B3%5D)).toBe(true);%0D%0A%7D);
|
927e497b758ce2cb956311e321c5c38a00d377aa | Remove deprecated Audio view reference (#3210) | share/spice/sound_cloud/sound_cloud.js | share/spice/sound_cloud/sound_cloud.js | (function(env) {
"use strict"
var query = DDG.get_query();
query = query.replace(/\bsound ?cloud\b/, "").replace(/\bsc\b/, "").trim(); //replace trigger words from query
env.ddg_spice_sound_cloud = function() {
$.getJSON("/js/spice/sound_cloud_result/" + encodeURIComponent(query), sound_cloud);
}
function sound_cloud(api_result) {
// Blacklist some adult results.
var skip_ids = {
80320921: 1,
75349402: 1
};
if(!api_result){
return Spice.failed("sound_cloud");
}
Spice.add({
id: 'sound_cloud',
name: 'Audio',
data: api_result,
signal: 'medium',
meta: {
sourceName: 'SoundCloud',
sourceUrl: 'https://soundcloud.com/search?q=' + query,
sourceIcon: true,
autoplay: false,
itemType: 'Tracks'
},
templates: {
item: 'audio_item',
options: {
footer: Spice.sound_cloud.footer
}
},
view: 'Audio',
relevancy: {
dup: 'url'
},
normalize: function(o) {
if(!o) {
return null;
}
var image = o.artwork_url || o.user.avatar_url;
// Check if it's using the default avatar, if
// so switch set image to null - it will be
// replaced with DDG's default icon
if (/default_avatar_large/.test(image)) {
image = null;
} else {
// Get the larger image for our IA.
image = image.replace(/large\.jpg/, "t200x200.jpg");
image = DDG.toHTTP(image);
}
// skip items that can't be streamed or explicit id's we
// want to skip for adult content:
if (!o.stream_url || skip_ids[o.id]) {
return;
}
var streamURL = '/sc_audio/?u=' + DDG.toHTTP(o.stream_url);
return {
image: image,
hearts: o.likes_count || 0,
duration: o.duration,
title: o.title,
url: o.permalink_url,
streamURL: streamURL
};
}
});
};
ddg_spice_sound_cloud();
}(this));
| JavaScript | 0 | @@ -1153,21 +1153,25 @@
view: '
-Audio
+GridTiles
',%0A
|
911b18c0d1e86d16e8e58fa450020ceed65c84e6 | Update add-private-person.js | lib/add-private-person.js | lib/add-private-person.js | 'use strict'
function generateMetadataPrivatePerson (options) {
if (!options) {
throw new Error('Missing required input: options')
}
if (!options.firstName) {
throw new Error('Missing required input: options.firstName')
}
if (!options.lastName) {
throw new Error('Missing required input: options.lastName')
}
if (!options.personalIdNumber) {
throw new Error('Missing required input: options.personalIdNumber')
}
if (!options.streetAddress) {
throw new Error('Missing required input: options.streetAddress')
}
if (!options.zipCode) {
throw new Error('Missing required input: options.zipCode')
}
if (!options.zipPlace) {
throw new Error('Missing required input: options.zipPlace')
}
if (!options.area) {
throw new Error('Missing required input: options.area')
}
var meta = {
'clientService': 'ContactService',
'clientMethod': 'SynchronizePrivatePerson',
'args': {
'parameter': {
'Email': options.email || false,
'FirstName': options.firstName,
'LastName': options.lastName,
'MiddleName': options.middleName || false,
'PersonalIdNumber': options.personalIdNumber,
'PhoneNumber': options.phone || false,
'PrivateAddress': [
{
Area: options.area,
Country: 'NOR',
County: 'Telemark',
StreetAddress: options.streetAddress,
ZipCode: options.zipCode,
ZipPlace: options.zipPlace
}
]
}
}
}
return meta
}
module.exports = generateMetadataPrivatePerson
| JavaScript | 0.000001 | @@ -1331,40 +1331,8 @@
R',%0A
- County: 'Telemark',%0A
|
a1284f1be70ba643b23b17285b13119488e15bcc | Read the dependencies from the file | dependument.js | dependument.js | #!/usr/bin/env node
(function() {
"use strict";
const fs = require('fs');
const CONFIG_FILE = "package.json";
console.log(readFile(CONFIG_FILE));
function readFile(path) {
let contents = fs.readFileSync(path);
return JSON.parse(contents);
}
})();
| JavaScript | 0.000001 | @@ -118,43 +118,357 @@
%0A%0A
-console.log(readFile(CONFIG_FILE));
+(function() %7B%0A let file = readFile(CONFIG_FILE);%0A%0A let dependencies = getDependencies(file);%0A%0A console.log(dependencies);%0A %7D)();%0A%0A function getDependencies(file) %7B%0A let dependencies = file.dependencies;%0A%0A if (dependencies === undefined%0A %7C%7C dependencies === null) %7B%0A dependencies = %7B%7D;%0A %7D%0A%0A return dependencies;%0A %7D
%0A%0A
|
eea57debe3e30803b2c0180714297e959082a254 | Move error handling to be local to function | valve/udpToGrain.js | valve/udpToGrain.js | /* Copyright 2015 Christine S. MacNeill
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by appli cable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var H = require('highland');
var Grain = require('../model/Grain.js');
var SDP = require('../model/SDP.js');
var RTPPacket = require('../model/RTPPacket.js')
var RFC4175Packet = require('../model/RFC4175Packet.js')
module.exports = function(sdp) {
var RTP = RTPPacket;
var pushLines = false;
setSDP(sdp);
var rtpCounter = -2;
var origin_timestamp, smpte_tc, flow_id, source_id,
grain_flags, sync_timestamp, grain_duration;
var origin_timestamp_id, smpte_tc_id, flow_id_id, source_id_id,
grain_flags_id, sync_timestamp_id, grain_duration_id;
var initState = true;
function setSDP(s) {
if (!SDP.isSDP(s)) {
sdp = undefined; revExtMap = undefined; RTP = RTPPacket;
} else {
sdp = s;
var revExtMap = s.getExtMapReverse(0);
origin_timestamp_id = revExtMap['urn:x-ipstudio:rtp-hdrext:origin-timestamp'];
smpte_tc_id = revExtMap['urn:ietf:params:rtp-hdrext:smpte-tc'];
flow_id_id = revExtMap['urn:x-ipstudio:rtp-hdrext:flow-id'];
source_id_id = revExtMap['urn:x-ipstudio:rtp-hdrext:source-id'];
grain_flags_id = revExtMap['urn:x-ipstudio:rtp-hdrext:grain-flags'];
sync_timestamp_id = revExtMap['urn:x-ipstudio:rtp-hdrext:sync-timestamp'];
grain_duration_id = revExtMap['urn:x-ipstudio:rtp-hdrext:grain-duration'];
if (s.getEncodingName(0) === 'raw') {
RTP = RFC4175Packet; pushLines = true;
} else {
RTP = RTPPacket; pushLines = false;
}
}
}
var payloads = [];
var udpConsumer = function (err, x, push, next) {
if (err) {
push(err);
next();
} else if (x === H.nil) {
push(null, H.nil);
} else {
if (sdp === undefined) {
if (SDP.isSDP(x)) {
setSDP(x);
push(null, x);
} else {
push(new Error('Cannot create Grain or work out start without SDP data first.'));
}
} else { // sdp is available
if (Buffer.isBuffer(x)) {
var rtp = new RTP(x);
var nextCounter = (pushLines) ? rtp.getCompleteSequenceNumber() :
rtp.getSequenceNumber();
// console.log(pushLines, nextCounter);
if (rtpCounter !== -2) {
if (nextCounter === 0 && rtpCounter != (pushLines ? 0xffffffff : 0xffff)) {
push(new Error('Unexpected sequence number at wrap around.'));
} else {
if ((rtpCounter + 1) !== nextCounter) {
if (pushLines && (nextCounter & 0xffff === 0xffff)) {
// TODO remove this line when BBC bug is fixed
push(new Error('Detected BBC wrap around bug.'));
nextCounter = (rtpCounter & 0xffff0000) | 0xffff
} else {
push(new Error('RTP sequence discontinuity. Expected ' +
(rtpCounter + 1) + ', got ' + nextCounter + '.'));
}
}
}
}
rtpCounter = nextCounter;
if (initState) {
if (rtp.isStart(grain_flags_id)) {
initState = false;
push(null, sdp);
}
}
if (!initState) {
if (rtp.isStart(grain_flags_id)) {
payloads = (pushLines) ? rtp.getLineData().map(function (x) {
return x.data }) : [ rtp.getPayload() ];
var exts = rtp.getExtensions();
origin_timestamp = exts['id' + origin_timestamp_id];
sync_timestamp = exts['id' + sync_timestamp_id];
grain_duration = exts['id' + grain_duration_id];
smpte_tc = exts['id' + smpte_tc_id];
flow_id = exts['id' + flow_id_id];
source_id = exts['id' + source_id_id];
} else if (rtp.isEnd(grain_flags_id)) {
if (pushLines) {
rtp.getLineData().forEach(function (x) { payloads.push(x.data); })
} else {
payloads.push(rtp.getPayload());
}
push(null, new Grain(payloads, sync_timestamp, origin_timestamp,
smpte_tc, flow_id, source_id, grain_duration));
} else {
if (pushLines) {
rtp.getLineData().forEach(function (x) { payloads.push(x.data); })
} else {
payloads.push(rtp.getPayload());
}
}
}
} else {
console.log(x);
// push(new Error('Unknown data type pushed through udp-to-grain.'));
}
} // elsr => (sdp !== undefined)
next();
}
}
return H.pipeline(H.consume(udpConsumer));
}
| JavaScript | 0 | @@ -5155,16 +5155,21 @@
ipeline(
+%0A
H.consum
@@ -5182,13 +5182,89 @@
onsumer)
+,%0A H.errors(function (err, push) %7B console.error('udpToGrain: ' + err) %7D)
);%0A%7D%0A
|
3cf7256c57a1e8b951f2707e29c010fb49e74ecf | Fix getShareUrl() function | skylines/frontend/static/js/general.js | skylines/frontend/static/js/general.js | /**
* Pads a number with leading zeros
*
* @param {Number} num Number to pad
* @param {Number} size Width of returned string
* @return {String} Padded number
*/
function pad(num, size) {
var s = '000000000' + num;
return s.substr(s.length - size);
}
/**
* Returns the URL for the current page and add pinned flights
* to the URL which are only stored client-side inside a cookie.
*
* @param {String} url The original URL.
* @return {String} URL for the current flights including pinned flights.
*/
function getShareUrl(url) {
var pinnedFlights = window.pinnedFlightsService.get('pinned');
var url_re = /(.*?)\/([\d,]{1,})\/(.*)/;
var url_split = url_re.exec(url);
var ids = url_split[2].split(',').concat(pinnedFlights);
var unique_ids = [];
for (var i in ids) {
if ($.inArray(parseInt(ids[i]), unique_ids) == -1) {
unique_ids.push(parseInt(ids[i]));
}
}
return url_split[1] + '/' + unique_ids.join(',') + '/' + url_split[3];
}
| JavaScript | 0.000003 | @@ -689,16 +689,20 @@
%0A%0A var
+url_
ids = ur
@@ -727,185 +727,112 @@
,').
-concat(pinnedFlights);%0A%0A var unique_ids = %5B%5D;%0A for (var i in ids) %7B%0A if ($.inArray(parseInt(ids%5Bi%5D), unique_ids) == -1) %7B%0A unique_ids.push(parseInt(ids%5Bi%5D));%0A %7D%0A %7D
+map(function(it) %7B return parseInt(it, 10); %7D);%0A var unique_ids = url_ids.concat(pinnedFlights).uniq();
%0A%0A
|
1d8463a6ca071dab4ec2d39f298676175882b2e3 | Add keywords | lib/autocomplete/index.js | lib/autocomplete/index.js | "use strict";
// Load dependent modules
var CodeHintManager = brackets.getModule("editor/CodeHintManager");
var TokenUtils = brackets.getModule("utils/TokenUtils");
var htmlStructure = require('./html-structure.js');
var tags = htmlStructure.tags;
var TAG_NAME = 'tag';
/**
* Creates a tagInfo object and assures all the values are entered or are empty strings
* @param {string=} tokenType what is getting edited and should be hinted
* @param {number=} offset where the cursor is for the part getting hinted
* @param {string=} tagName The name of the tag
* @param {string=} attrName The name of the attribute
* @param {string=} attrValue The value of the attribute
* @return {{tagName:string,
* attr:{name:string, value:string, valueAssigned:boolean, quoteChar:string, hasEndQuote:boolean},
* position:{tokenType:string, offset:number}
* }}
* A tagInfo object with some context about the current tag hint.
*/
function createTagInfo(tokenType, offset, tagName, attrName, attrValue, valueAssigned, quoteChar, hasEndQuote) {
return {
tagName: tagName || "",
attr: {
name: attrName || "",
value: attrValue || "",
valueAssigned: valueAssigned || false,
quoteChar: quoteChar || "",
hasEndQuote: hasEndQuote || false
},
position: {
tokenType: tokenType || "",
offset: offset || 0
}
};
}
function getTagInfo(editor, pos) {
var ctx = TokenUtils.getInitialContext(editor._codeMirror, pos);
var offset = TokenUtils.offsetInToken(ctx);
// Check if this is inside a style block.
if (editor.getModeForSelection() !== "jade") {
return createTagInfo();
}
if (ctx.token.type === 'tag') {
return createTagInfo(ctx.token.type, offset, ctx.token.string)
}
return createTagInfo();
}
function TagHints() {
}
/**
* Determines whether HTML tag hints are available in the current editor
* context.
*
* @param {Editor} editor
* A non-null editor object for the active window.
*
* @param {string} implicitChar
* Either null, if the hinting request was explicit, or a single character
* that represents the last insertion and that indicates an implicit
* hinting request.
*
* @return {boolean}
* Determines whether the current provider is able to provide hints for
* the given editor context and, in case implicitChar is non- null,
* whether it is appropriate to do so.
*/
TagHints.prototype.hasHints = function (editor, implicitChar) {
var pos = editor.getCursorPos();
this.tagInfo = getTagInfo(editor, pos);
this.editor = editor;
if (this.tagInfo.position.tokenType === TAG_NAME) {
if (this.tagInfo.position.offset >= 0) {
return true;
}
}
return false;
};
/**
* Returns a list of availble HTML tag hints if possible for the current
* editor context.
*
* @return {jQuery.Deferred|{
* hints: Array.<string|jQueryObject>,
* match: string,
* selectInitial: boolean,
* handleWideResults: boolean}}
* Null if the provider wishes to end the hinting session. Otherwise, a
* response object that provides:
* 1. a sorted array hints that consists of strings
* 2. a string match that is used by the manager to emphasize matching
* substrings when rendering the hint list
* 3. a boolean that indicates whether the first result, if one exists,
* should be selected by default in the hint list window.
* 4. handleWideResults, a boolean (or undefined) that indicates whether
* to allow result string to stretch width of display.
*/
TagHints.prototype.getHints = function (implicitChar) {
this.tagInfo = getTagInfo(this.editor, this.editor.getCursorPos());
if (this.tagInfo.position.tokenType === TAG_NAME) {
if (this.tagInfo.position.offset >= 0) {
var query = this.tagInfo.tagName.slice(0, this.tagInfo.position.offset);
var result = Object.keys(tags).filter(function (key) {
return key.indexOf(query) === 0;
}).sort();
return {
hints: result,
match: query,
selectInitial: true,
handleWideResults: false
};
}
}
return null;
};
/**
* Inserts a given HTML tag hint into the current editor context.
*
* @param {string} hint
* The hint to be inserted into the editor context.
*
* @return {boolean}
* Indicates whether the manager should follow hint insertion with an
* additional explicit hint request.
*/
TagHints.prototype.insertHint = function (completion) {
var start = {line: -1, ch: -1};
var end = {line: -1, ch: -1};
var cursor = this.editor.getCursorPos();
var charCount = 0;
if (this.tagInfo.position.tokenType === TAG_NAME) {
var textAfterCursor = this.tagInfo.tagName.substr(this.tagInfo.position.offset);
charCount = this.tagInfo.tagName.length;
}
end.line = start.line = cursor.line;
start.ch = cursor.ch - this.tagInfo.position.offset;
end.ch = start.ch + charCount;
if (completion !== this.tagInfo.tagName) {
if (start.ch !== end.ch) {
this.editor.document.replaceRange(completion, start, end);
} else {
this.editor.document.replaceRange(completion, start);
}
}
return false;
};
var tagHints = new TagHints();
CodeHintManager.registerHintProvider(tagHints, ["jade"], 0);
| JavaScript | 0.000002 | @@ -265,16 +265,225 @@
= 'tag';
+%0Avar KEYWORDS = %5B%0A %22include%22,%0A %22extends%22,%0A %22if%22,%0A %22else%22,%0A %22each%22,%0A %22while%22,%0A %22case%22,%0A %22when%22,%0A %22default%22,%0A %22mixin%22,%0A %22yield%22,%0A %22doctype%22,%0A %22append%22,%0A %22prepend%22,%0A %22block%22,%0A %22unless%22,%0A %22for%22%0A%5D;
%0A%0A/**%0A *
@@ -4078,16 +4078,33 @@
s(tags).
+concat(KEYWORDS).
filter(f
|
fe630f17e06130dc3b986261c935fa95b528475d | Fix typo: requre => require | lib/backend/connection.js | lib/backend/connection.js | /**
* var connection = new Connection({ tag: 'kotoumi',
* hostName: 'localhost',
* port: 24224,
* receiveHostName: 'localhost',
* receivePort: 10030 });
*/
var EventEmitter = require('events').EventEmitter;
var fluent = require('fluent-logger');
var Receiver = requre('./receiver').Receiver;
var DEFAULT_FLUENT_TAG =
Connection.DEFAULT_FLUENT_TAG =
'kotoumi';
var DEFAULT_FLUENT_HOST_NAME =
Connection.DEFAULT_FLUENT_HOST_NAME =
'localhost';
var DEFAULT_FLUENT_PORT =
Connection.DEFAULT_FLUENT_PORT =
24224;
var DEFAULT_RECEIVE_HOST_NAME =
Connection.DEFAULT_RECEIVE_HOST_NAME =
'localhost';
var DEFAULT_RECEIVE_PORT =
Connection.DEFAULT_RECEIVE_PORT =
10030;
var ERROR_GATEWAY_TIMEOUT =
Connection.ERROR_GATEWAY_TIMEOUT =
504;
function Connection(params) {
this._params = params || {};
this._init();
}
Connection.prototype = new EventEmitter();
Connection.prototype._init = function() {
this._callbacks = {};
this._initSender();
this._initReceiver();
};
Connection.prototype._initSender = function() {
this._sender = (
this._params.sender ||
fluent.createFluentSender(this._params.tag || DEFAULT_FLUENT_TAG,
{ host: this._params.hostName || DEFAULT_FLUENT_HOST_NAME,
port: this._params.port || DEFAULT_FLUENT_PORT })
);
};
Connection.prototype._initReceiver = function() {
this.receiveHostName = this._params.receiveHostName || DEFAULT_RECEIVE_HOST_NAME;
this.receivePort = this._params.receivePort || DEFAULT_RECEIVE_PORT;
var receiver = this._params.receiver;
if (!receiver) {
receiver = new Receiver(this.receivePort);
}
this._receiver = receiver;
this._receiver.on((this._params.tag || DEFAULT_FLUENT_TAG)+ '.message',
this._handleMessage.bind(this));
};
function isSuccess(code) {
return Math.floor(code / 100) == 2;
}
Connection.prototype._handleMessage = function(envelope) {
this.emit('message', envelope);
var inReplyTo = envelope['inReplyTo'];
if (inReplyTo) {
var errorCode = envelope.statusCode;
if (!errorCode || isSuccess(errorCode))
errorCode = null;
this.emit('inReplyTo:' + inReplyTo, errorCode, envelope);
}
};
var count = 0;
function createId() {
return Date.now() + ':' + (count++);
}
function getCurrentTime() {
// The method toISOString() returns a GMT (ex. 2013-01-10T08:34:41.252Z)
// on node. However, a local time (ex. 2013-01-10T17:34:41.252+09:00) is
// more helpful for debugging. We should use it in the feature...
return new Date().toISOString();
}
function toPositiveInteger(number) {
if (!number)
return 0;
var integer = parseInt(number);
if (isNaN(integer))
return 0;
return Math.max(integer, 0);
}
Connection.prototype.emitMessage = function(type, body, callback, timeout) {
var id = createId();
var envelope = {
id: id,
date: getCurrentTime(),
replyTo: this.receiveHostName + ':' + this.receivePort,
statusCode: 200,
type: type,
body: body
};
if (callback) {
var event = 'inReplyTo:' + id;
this.once(event, callback);
timeout = toPositiveInteger(timeout);
if (timeout) {
setTimeout((function() {
if (this.listeners(event)) {
this.removeAllListeners(event);
callback(ERROR_GATEWAY_TIMEOUT, null);
}
}).bind(this), timeout);
}
}
this._sender.emit('message', envelope);
return envelope;
};
exports.Connection = Connection;
| JavaScript | 0.999987 | @@ -435,16 +435,17 @@
r = requ
+i
re('./re
|
436c04ebcb2109fb9796240f246d2f712cfd69fe | Implement search by line number. Seems to work. | lib/build-test-modules.js | lib/build-test-modules.js | var glob = require('glob')
var path = require('path')
var _ = require('lodash')
module.exports = function (locator, cwd) {
var currentTestOrdinal = 0
var criteria = criteriaFor(locator)
return _.map(glob.sync(criteria.glob), function (file) {
var testModule = require(path.resolve(cwd, file))
var tests = _.map(selectedTestFunctionsIn(testModule, criteria), function (testEntry, i) {
currentTestOrdinal++
return {
testFunction: testEntry.testFunction,
testName: testEntry.testName,
context: Object.create(null),
description: currentTestOrdinal + ' - ' + testSummaryDescription(file, testEntry.testName, i),
file: file
}
})
return {
tests: tests,
file: file,
beforeAll: testModule.beforeAll || function () {},
afterAll: testModule.afterAll || function () {},
beforeEach: testModule.beforeEach || function () {},
afterEach: testModule.afterEach || function () {}
}
})
}
function criteriaFor (locator) {
if (_.includes(locator, '#')) {
var parts = locator.split('#')
return {
glob: parts[0],
name: parts[1]
}
} else if (_.includes(locator, ':')) {
var parts = locator.split(':')
return {
glob: parts[0],
lineNumber: parts[1]
}
} else {
return { glob: locator }
}
}
var selectedTestFunctionsIn = function (testModule, criteria) {
var testFunctions = testFunctionsIn(testModule)
if (criteria.name) {
return filterTestFunctionsByName(testFunctions, criteria.name)
} else {
return testFunctions
}
}
var testFunctionsIn = function (testModule) {
if (_.isFunction(testModule)) {
return [{
testFunction: testModule,
testName: testModule.name
}]
} else {
return _(testModule).functions()
.without('beforeEach', 'beforeAll', 'afterEach', 'afterAll')
.map(function (testName) {
return {
testFunction: testModule[testName],
testName: testName
}
})
.value()
}
}
var filterTestFunctionsByName = function (testFunctions, testName) {
return _.filter(testFunctions, function (testFunction) {
return testFunction.testName === testName
})
}
var testSummaryDescription = function (file, testName, index) {
return (testName ? '"' + testName + '" - ' : '') + 'test #' + (index + 1) + ' in `' + file + '`'
}
| JavaScript | 0 | @@ -72,16 +72,99 @@
lodash')
+%0Avar fs = require('fs')%0Avar functionNamesAtLine = require('function-names-at-line')
%0A%0Amodule
@@ -343,25 +343,15 @@
test
-Module = require(
+Path =
path
@@ -369,16 +369,54 @@
d, file)
+%0A var testModule = require(testPath
)%0A va
@@ -425,18 +425,16 @@
test
+Func
s =
-_.map(
sele
@@ -473,17 +473,59 @@
criteria
-)
+, testPath)%0A var tests = _.map(testFuncs
, functi
@@ -1168,24 +1168,36 @@
(locator) %7B%0A
+ var parts%0A
if (_.incl
@@ -1214,36 +1214,32 @@
or, '#')) %7B%0A
-var
parts = locator.
@@ -1356,20 +1356,16 @@
) %7B%0A
-var
parts =
@@ -1474,16 +1474,22 @@
return %7B
+%0A
glob: l
@@ -1494,16 +1494,20 @@
locator
+%0A
%7D%0A %7D%0A%7D
@@ -1568,16 +1568,26 @@
criteria
+, testPath
) %7B%0A va
@@ -1691,16 +1691,17 @@
nsByName
+s
(testFun
@@ -1708,16 +1708,17 @@
ctions,
+%5B
criteria
@@ -1722,16 +1722,208 @@
ria.name
+%5D)%0A %7D else if (criteria.lineNumber) %7B%0A var names = functionNamesAtLine(fs.readFileSync(testPath).toString(), criteria.lineNumber)%0A return filterTestFunctionsByNames(testFunctions, names
)%0A %7D el
@@ -2434,16 +2434,17 @@
nsByName
+s
= funct
@@ -2467,24 +2467,25 @@
ns, testName
+s
) %7B%0A return
@@ -2537,32 +2537,54 @@
on) %7B%0A return
+ _.includes(testNames,
testFunction.te
@@ -2593,21 +2593,9 @@
Name
- === testName
+)
%0A %7D
|
514ee1068f7cad65984daed9c331917907121fef | add before hook to try and load an actor from the fediverse if it can't be found locally | lib/collections/actors.js | lib/collections/actors.js | /*
Agora Forum Software
Copyright (C) 2018 Gregory Sartucci
License: AGPL-3.0, Check file LICENSE
*/
this.Actors = new Mongo.Collection('actors');
this.Actors.before.insert(function(userId, actor) {
if (!activityPubActorTypes.includes(actor.type))
throw new Meteor.Error('Not an Actor', 'Cannot insert document into Actor Collection: Not an Actor.');
if (!activityPubSchemas.validate("Actor.json", actor))
throw new Meteor.Error('Invalid Actor', 'Cannot insert Actor: Schema not valid:' + activityPubSchemas.errorsText());
if (Actors.findOne({id: actor.id}))
throw new Meteor.Error('Duplicate Actor', 'Cannot insert Actor: Actor with that id already present.');
});
this.Actors.after.insert(function(userId, actor) {
if (actor.local) {
Inboxes.insert({
'@context': "https://www.w3.org/ns/activitystreams",
id: actor.inbox,
type: "OrderedCollection",
totalItems: 0,
orderedItems: []
});
Outboxes.insert({
'@context': "https://www.w3.org/ns/activitystreams",
id: actor.outbox,
type: "OrderedCollection",
totalItems: 0,
orderedItems: []
});
FollowingLists.insert({
'@context': "https://www.w3.org/ns/activitystreams",
id: actor.following,
type: "OrderedCollection",
totalItems: 0,
orderedItems: []
});
FollowerLists.insert({
'@context': "https://www.w3.org/ns/activitystreams",
id: actor.followers,
type: "OrderedCollection",
totalItems: 0,
orderedItems: []
});
}
});
if (Meteor.isServer) {
Meteor.startup(function() {
Actors._ensureIndex({id: 1});
Actors._ensureIndex({preferredUsername: 1});
});
}
| JavaScript | 0 | @@ -1727,16 +1727,264 @@
%7D%0A%7D);%0A%0A
+this.Actors.before.findOne(function(userId, selector, options) %7B%0A if ((!options %7C%7C !options.noRecursion) && selector.id && !Actors.findOne(%7Bid: selector.id%7D, %7BnoRecursion: true%7D))%0A Meteor.call('getActivityJSONFromUrl', selector.id);%0A%7D);%0A%0A
if (Mete
|
f9b1a781a93498d4adf0025f9055719e3c1547bc | add prefix to bucket list | lib/condensation/index.js | lib/condensation/index.js | var _ = require('lodash'),
AWS = require('aws-sdk'),
cutil = require('./util'),
rimraf = require('rimraf'),
gutil = require('gulp-util'),
Handlebars = require('handlebars'),
path = require('path'),
ParticleLoader = require('./loaders/particle-loader'),
through = require('through2'),
tasks = require('./tasks');
var Condensation = function(gulp,options) {
this.gulp = gulp || require('gulp');;
this.handlebars = Handlebars.create();
this.options = _.merge({
s3: [],
dist: 'dist',
root: Condensation.DEFAULT_ROOT,
dependencySrc: [],
taskPrefix: Condensation.DEFAULT_TASK_PREFIX
},options);
this.options.projectFullPath = path.join(process.cwd(),this.options.root);
this.options.particlesDir = path.join(this.options.root,Condensation.PARTICLES_DIR);
if (!this.options.projectName) {
try { this.options.projectName = require(path.join(process.cwd(),'package.json')).name; } catch(e) {}
}
this.particleLoader = new ParticleLoader({
root: this.options.root
});
this.genTaskName = cutil.genTaskNameFunc({prefix:this.options.taskPrefix});
this.helpers = require('./loaders/all-helpers')({
particleLoader: this.particleLoader,
handlebars: this.handlebars
});
};
Condensation.DEFAULT_S3_PREFIX = '';
Condensation.DEFAULT_TASK_PREFIX = 'condensation';
Condensation.PARTICLES_DIR = 'particles';
Condensation.DEFAULT_ROOT = './';
Condensation.prototype.condense = function() {
var self = this;
var options = this.options;
var gulp = this.gulp;
var buildTasks = [];
var deployTasks = [];
var labelTasks = {};
var s3config = options.s3 || [];
_.each(s3config, function(s3opts,i) {
s3opts = _.merge({
prefix: '',
labels: []
},s3opts);
var awsS3 = new AWS.S3({region: s3opts.aws.region});
var distPath = cutil.genDistPath({
id: i.toString(),
s3prefix: s3opts.prefix,
root: self.options.dist
});
// Build task
gulp.task(
self.genTaskName('build',i),
[self.genTaskName('particle-modules:load'),self.genTaskName('clean:errors')],
tasks.build.bind(self,s3opts,distPath,awsS3)
);
buildTasks.push(self.genTaskName('build',i));
// Ensure the bucket(s) defined in the config exist
gulp.task(self.genTaskName('s3','bucket','ensure',i),tasks.s3.ensureBucket.bind(this,s3opts,awsS3));
// Write objects to s3
var writeS3ObjectsDeps = [
self.genTaskName('s3','bucket','ensure',i),
self.genTaskName('build',i)
];
if (s3opts.clean) {
writeS3ObjectsDeps.push(self.genTaskName('s3','objects','delete',i));
};
gulp.task(
self.genTaskName('s3','objects','write',i),
writeS3ObjectsDeps,
tasks.s3.writeObjects.bind(this,s3opts,awsS3,distPath)
);
// Delete objects from s3
gulp.task(
self.genTaskName('s3','objects','delete',i),
[
self.genTaskName('s3','bucket','ensure',i)
],
tasks.s3.deleteObjects.bind(this,s3opts,awsS3)
);
// Deploy to s3 task
gulp.task(self.genTaskName('deploy',i),[self.genTaskName('s3','objects','write',i)]);
deployTasks.push(self.genTaskName('deploy',i));
// Create build and deploy tasks for each label
_.each(s3opts.labels,function(label) {
labelTasks[label] = labelTasks[label] || {
buildTasks: [],
deployTasks: []
};
labelTasks[label].buildTasks.push(self.genTaskName('build',i));
labelTasks[label].deployTasks.push(self.genTaskName('deploy',i));
});
});
// Find all particle modules and init
gulp.task(self.genTaskName('particle-modules:load'), function() {
return gulp.src(['**/package.json'])
.pipe(through.obj(function(file,enc,cb) {
var packageJson = JSON.parse(file.contents);
if (_.includes(packageJson.keywords,'condensation-particles')) {
this.push(file);
}
cb();
}))
.pipe(through.obj(function(file,enc,cb) {
var filePath = path.parse(file.path);
var condensationJs;
try {
condensationJs = require(filePath.dir+'/condensation');
}
catch(e) {
//do nothing
}
if (condensationJs) {
condensationJs.initialize(cb);
}
else {
cb();
}
}))
;
});
// Remove all files from 'dist'
gulp.task(self.genTaskName('clean'), function (cb) {
rimraf(options.dist, cb);
});
// Remove errors directory
gulp.task(self.genTaskName('clean:errors'), function (cb) {
rimraf('condensation_errors', cb);
});
// List s3 buckets and their ID
gulp.task(self.genTaskName('s3','list'), function(cb) {
_.each(s3config, function(s3opts,i) {
gutil.log(i + ": " + s3opts.aws.bucket);
});
cb();
});
// Tasks to launch other tasks
gulp.task(self.genTaskName('build'),buildTasks);
gulp.task(self.genTaskName('deploy'), deployTasks);
gulp.task(self.genTaskName('default'),[self.genTaskName('build')]);
_.each(_.toPairs(labelTasks),function(kv) {
gulp.task(self.genTaskName('build',kv[0]),kv[1].buildTasks);
gulp.task(self.genTaskName('deploy',kv[0]),kv[1].deployTasks);
});
};
module.exports = Condensation;
| JavaScript | 0.000004 | @@ -1,13 +1,15 @@
var
-_
+AWS
= requi
@@ -16,100 +16,150 @@
re('
-lodash'),%0AAWS = require('aws-sdk'),%0Acutil = require('./util'),%0Arimraf = require('rimraf'),%0Ag
+aws-sdk');%0Avar Handlebars = require('handlebars');%0Avar ParticleLoader = require('./loaders/particle-loader');%0Avar _ = require('lodash');%0Avar c
util
@@ -174,172 +174,155 @@
re('
-gulp-
+./
util')
-,%0AHandlebars = require('handlebars'),%0Apath = require('path'),%0AParticleLoader = require('./loaders/particle-loader'),%0Athrough = require('through2'),%0Atasks
+;%0Avar gutil = require('gulp-util');%0Avar path = require('path');%0Avar rimraf = require('rimraf');%0Avar tasks = require('./tasks');%0Avar through
= r
@@ -325,31 +325,32 @@
= require('
-./tasks
+through2
');%0A%0Avar Con
@@ -4226,19 +4226,32 @@
itialize
-(
+.apply(self,%5B
cb
+%5D
);%0A
@@ -4733,16 +4733,32 @@
%22: %22 +
+path.posix.join(
s3opts.a
@@ -4766,16 +4766,31 @@
s.bucket
+,s3opts.prefix)
);%0A %7D
|
82b5e98f55242b18dab1dbab920060f0c4e66c6b | Add defaultUseHardbreak environment variable | lib/config/environment.js | lib/config/environment.js | 'use strict'
const { toBooleanConfig, toArrayConfig, toIntegerConfig } = require('./utils')
module.exports = {
sourceURL: process.env.CMD_SOURCE_URL,
domain: process.env.CMD_DOMAIN,
urlPath: process.env.CMD_URL_PATH,
host: process.env.CMD_HOST,
port: toIntegerConfig(process.env.CMD_PORT),
path: process.env.CMD_PATH,
loglevel: process.env.CMD_LOGLEVEL,
urlAddPort: toBooleanConfig(process.env.CMD_URL_ADDPORT),
useSSL: toBooleanConfig(process.env.CMD_USESSL),
hsts: {
enable: toBooleanConfig(process.env.CMD_HSTS_ENABLE),
maxAgeSeconds: toIntegerConfig(process.env.CMD_HSTS_MAX_AGE),
includeSubdomains: toBooleanConfig(process.env.CMD_HSTS_INCLUDE_SUBDOMAINS),
preload: toBooleanConfig(process.env.CMD_HSTS_PRELOAD)
},
csp: {
enable: toBooleanConfig(process.env.CMD_CSP_ENABLE),
reportURI: process.env.CMD_CSP_REPORTURI
},
protocolUseSSL: toBooleanConfig(process.env.CMD_PROTOCOL_USESSL),
allowOrigin: toArrayConfig(process.env.CMD_ALLOW_ORIGIN),
useCDN: toBooleanConfig(process.env.CMD_USECDN),
allowAnonymous: toBooleanConfig(process.env.CMD_ALLOW_ANONYMOUS),
allowAnonymousEdits: toBooleanConfig(process.env.CMD_ALLOW_ANONYMOUS_EDITS),
allowAnonymousViews: toBooleanConfig(process.env.CMD_ALLOW_ANONYMOUS_VIEWS),
allowFreeURL: toBooleanConfig(process.env.CMD_ALLOW_FREEURL),
forbiddenNoteIDs: toArrayConfig(process.env.CMD_FORBIDDEN_NOTE_IDS),
defaultPermission: process.env.CMD_DEFAULT_PERMISSION,
dbURL: process.env.CMD_DB_URL,
sessionSecret: process.env.CMD_SESSION_SECRET,
sessionLife: toIntegerConfig(process.env.CMD_SESSION_LIFE),
responseMaxLag: toIntegerConfig(process.env.CMD_RESPONSE_MAX_LAG),
imageUploadType: process.env.CMD_IMAGE_UPLOAD_TYPE,
imgur: {
clientID: process.env.CMD_IMGUR_CLIENTID
},
s3: {
accessKeyId: process.env.CMD_S3_ACCESS_KEY_ID,
secretAccessKey: process.env.CMD_S3_SECRET_ACCESS_KEY,
region: process.env.CMD_S3_REGION,
endpoint: process.env.CMD_S3_ENDPOINT
},
minio: {
accessKey: process.env.CMD_MINIO_ACCESS_KEY,
secretKey: process.env.CMD_MINIO_SECRET_KEY,
endPoint: process.env.CMD_MINIO_ENDPOINT,
secure: toBooleanConfig(process.env.CMD_MINIO_SECURE),
port: toIntegerConfig(process.env.CMD_MINIO_PORT)
},
s3bucket: process.env.CMD_S3_BUCKET,
azure: {
connectionString: process.env.CMD_AZURE_CONNECTION_STRING,
container: process.env.CMD_AZURE_CONTAINER
},
facebook: {
clientID: process.env.CMD_FACEBOOK_CLIENTID,
clientSecret: process.env.CMD_FACEBOOK_CLIENTSECRET
},
twitter: {
consumerKey: process.env.CMD_TWITTER_CONSUMERKEY,
consumerSecret: process.env.CMD_TWITTER_CONSUMERSECRET
},
github: {
clientID: process.env.CMD_GITHUB_CLIENTID,
clientSecret: process.env.CMD_GITHUB_CLIENTSECRET
},
gitlab: {
baseURL: process.env.CMD_GITLAB_BASEURL,
clientID: process.env.CMD_GITLAB_CLIENTID,
clientSecret: process.env.CMD_GITLAB_CLIENTSECRET,
scope: process.env.CMD_GITLAB_SCOPE
},
mattermost: {
baseURL: process.env.CMD_MATTERMOST_BASEURL,
clientID: process.env.CMD_MATTERMOST_CLIENTID,
clientSecret: process.env.CMD_MATTERMOST_CLIENTSECRET
},
oauth2: {
providerName: process.env.CMD_OAUTH2_PROVIDERNAME,
baseURL: process.env.CMD_OAUTH2_BASEURL,
userProfileURL: process.env.CMD_OAUTH2_USER_PROFILE_URL,
userProfileUsernameAttr: process.env.CMD_OAUTH2_USER_PROFILE_USERNAME_ATTR,
userProfileDisplayNameAttr: process.env.CMD_OAUTH2_USER_PROFILE_DISPLAY_NAME_ATTR,
userProfileEmailAttr: process.env.CMD_OAUTH2_USER_PROFILE_EMAIL_ATTR,
tokenURL: process.env.CMD_OAUTH2_TOKEN_URL,
authorizationURL: process.env.CMD_OAUTH2_AUTHORIZATION_URL,
clientID: process.env.CMD_OAUTH2_CLIENT_ID,
clientSecret: process.env.CMD_OAUTH2_CLIENT_SECRET
},
dropbox: {
clientID: process.env.CMD_DROPBOX_CLIENTID,
clientSecret: process.env.CMD_DROPBOX_CLIENTSECRET,
appKey: process.env.CMD_DROPBOX_APPKEY
},
google: {
clientID: process.env.CMD_GOOGLE_CLIENTID,
clientSecret: process.env.CMD_GOOGLE_CLIENTSECRET
},
ldap: {
providerName: process.env.CMD_LDAP_PROVIDERNAME,
url: process.env.CMD_LDAP_URL,
bindDn: process.env.CMD_LDAP_BINDDN,
bindCredentials: process.env.CMD_LDAP_BINDCREDENTIALS,
searchBase: process.env.CMD_LDAP_SEARCHBASE,
searchFilter: process.env.CMD_LDAP_SEARCHFILTER,
searchAttributes: toArrayConfig(process.env.CMD_LDAP_SEARCHATTRIBUTES),
usernameField: process.env.CMD_LDAP_USERNAMEFIELD,
useridField: process.env.CMD_LDAP_USERIDFIELD,
tlsca: process.env.CMD_LDAP_TLS_CA
},
saml: {
idpSsoUrl: process.env.CMD_SAML_IDPSSOURL,
idpCert: process.env.CMD_SAML_IDPCERT,
issuer: process.env.CMD_SAML_ISSUER,
identifierFormat: process.env.CMD_SAML_IDENTIFIERFORMAT,
disableRequestedAuthnContext: toBooleanConfig(process.env.CMD_SAML_DISABLEREQUESTEDAUTHNCONTEXT),
groupAttribute: process.env.CMD_SAML_GROUPATTRIBUTE,
externalGroups: toArrayConfig(process.env.CMD_SAML_EXTERNALGROUPS, '|', []),
requiredGroups: toArrayConfig(process.env.CMD_SAML_REQUIREDGROUPS, '|', []),
attribute: {
id: process.env.CMD_SAML_ATTRIBUTE_ID,
username: process.env.CMD_SAML_ATTRIBUTE_USERNAME,
email: process.env.CMD_SAML_ATTRIBUTE_EMAIL
}
},
plantuml: {
server: process.env.CMD_PLANTUML_SERVER
},
email: toBooleanConfig(process.env.CMD_EMAIL),
allowEmailRegister: toBooleanConfig(process.env.CMD_ALLOW_EMAIL_REGISTER),
allowGravatar: toBooleanConfig(process.env.CMD_ALLOW_GRAVATAR),
allowPDFExport: toBooleanConfig(process.env.CMD_ALLOW_PDF_EXPORT),
openID: toBooleanConfig(process.env.CMD_OPENID)
}
| JavaScript | 0 | @@ -5711,11 +5711,91 @@
_OPENID)
+,%0A defaultUseHardbreak: toBooleanConfig(process.env.CMD_DEFAULT_USE_HARD_BREAK)
%0A%7D%0A
|
363103cdaf160d6b891a93b458a230dfd2e7ff2d | Make sure there always was a call to Diaspora.I18n.loadLocale before running a jasmine spec | spec/javascripts/helpers/SpecHelper.js | spec/javascripts/helpers/SpecHelper.js | // Add custom matchers here, in a beforeEach block. Example:
//beforeEach(function() {
// this.addMatchers({
// toBePlaying: function(expectedSong) {
// var player = this.actual;
// return player.currentlyPlayingSong === expectedSong
// && player.isPlaying;
// }
// })
//});
beforeEach(function() {
$('#jasmine_content').html(spec.readFixture("underscore_templates"));
jasmine.Clock.useMock();
Diaspora.Pages.TestPage = function() {
var self = this;
this.subscribe("page/ready", function() {
self.directionDetector = self.instantiate("DirectionDetector");
});
};
var Page = Diaspora.Pages["TestPage"];
$.extend(Page.prototype, Diaspora.EventBroker.extend(Diaspora.BaseWidget));
Diaspora.page = new Page();
Diaspora.page.publish("page/ready", [$(document.body)]);
// matches flash messages with success/error and contained text
var flashMatcher = function(flash, id, text) {
textContained = true;
if( text ) {
textContained = (flash.text().indexOf(text) !== -1);
}
return flash.is(id) &&
flash.hasClass('expose') &&
textContained;
};
// add custom matchers for flash messages
this.addMatchers({
toBeSuccessFlashMessage: function(containedText) {
var flash = this.actual;
return flashMatcher(flash, '#flash_notice', containedText);
},
toBeErrorFlashMessage: function(containedText) {
var flash = this.actual;
return flashMatcher(flash, '#flash_error', containedText);
}
});
});
afterEach(function() {
//spec.clearLiveEventBindings();
$("#jasmine_content").empty()
expect(spec.loadFixtureCount).toBeLessThan(2);
spec.loadFixtureCount = 0;
});
var context = describe;
var spec = {};
window.stubView = function stubView(text){
var stubClass = Backbone.View.extend({
render : function(){
$(this.el).html(text);
return this
}
})
return new stubClass
}
window.loginAs = function loginAs(attrs){
return app.currentUser = app.user(factory.userAttrs(attrs))
}
window.logout = function logout(){
this.app._user = undefined
return app.currentUser = new app.models.User()
}
window.hipsterIpsumFourParagraphs = "Mcsweeney's mumblecore irony fugiat, ex iphone brunch helvetica eiusmod retro" +
" sustainable mlkshk. Pop-up gentrify velit readymade ad exercitation 3 wolf moon. Vinyl aute laboris artisan irony, " +
"farm-to-table beard. Messenger bag trust fund pork belly commodo tempor street art, nihil excepteur PBR lomo laboris." +
" Cosby sweater american apparel occupy, locavore odio put a bird on it fixie kale chips. Pariatur semiotics flexitarian " +
"veniam, irure freegan irony tempor. Consectetur sriracha pour-over vice, umami exercitation farm-to-table master " +
"cleanse art party." + "\n" +
"Quinoa nostrud street art helvetica et single-origin coffee, stumptown bushwick selvage skateboard enim godard " +
"before they sold out tumblr. Portland aesthetic freegan pork belly, truffaut occupy assumenda banksy 3 wolf moon " +
"irure forage terry richardson nulla. Anim nostrud selvage sartorial organic. Consequat pariatur aute fugiat qui, " +
"organic marfa sunt gluten-free mcsweeney's elit hella whatever wayfarers. Leggings pariatur chambray, ullamco " +
"flexitarian esse sed iphone pinterest messenger bag Austin cred DIY. Duis enim squid mcsweeney's, nisi lo-fi " +
"sapiente. Small batch vegan thundercats locavore williamsburg, non aesthetic trust fund put a bird on it gluten-free " +
"consectetur." + "\n" +
"Viral reprehenderit iphone sapiente exercitation. Enim nostrud letterpress, tempor typewriter dreamcatcher tattooed." +
" Ex godard pariatur voluptate est, polaroid hoodie ea nulla umami pickled tempor portland. Nostrud food truck" +
"single-origin coffee skateboard. Fap enim tumblr retro, nihil twee trust fund pinterest non jean shorts veniam " +
"fingerstache small batch. Cred whatever photo booth sed, et dolore gastropub duis freegan. Authentic quis butcher, " +
"fanny pack art party cupidatat readymade semiotics kogi consequat polaroid shoreditch ad four loko." + "\n" +
"PBR gluten-free ullamco exercitation narwhal in godard occaecat bespoke street art veniam aesthetic jean shorts " +
"mlkshk assumenda. Typewriter terry richardson pork belly, cupidatat tempor craft beer tofu sunt qui gentrify eiusmod " +
"id. Letterpress pitchfork wayfarers, eu sunt lomo helvetica pickled dreamcatcher bicycle rights. Aliqua banksy " +
"cliche, sapiente anim chambray williamsburg vinyl cardigan. Pork belly mcsweeney's anim aliqua. DIY vice portland " +
"thundercats est vegan etsy, gastropub helvetica aliqua. Artisan jean shorts american apparel duis esse trust fund."
spec.clearLiveEventBindings = function() {
var events = jQuery.data(document, "events");
for (prop in events) {
delete events[prop];
}
};
spec.content = function() {
return $('#jasmine_content');
};
// Loads fixure markup into the DOM as a child of the jasmine_content div
spec.loadFixture = function(fixtureName) {
var $destination = $('#jasmine_content');
// get the markup, inject it into the dom
$destination.html(spec.fixtureHtml(fixtureName));
// keep track of fixture count to fail specs that
// call loadFixture() more than once
spec.loadFixtureCount++;
};
// Returns fixture markup as a string. Useful for fixtures that
// represent the response text of ajax requests.
spec.readFixture = function(fixtureName) {
return spec.fixtureHtml(fixtureName);
};
spec.fixtureHtml = function(fixtureName) {
if (!spec.cachedFixtures[fixtureName]) {
spec.cachedFixtures[fixtureName] = spec.retrieveFixture(fixtureName);
}
return spec.cachedFixtures[fixtureName];
};
spec.retrieveFixture = function(fixtureName) {
// construct a path to the fixture, including a cache-busting timestamp
var path = '/tmp/js_dom_fixtures/' + fixtureName + ".fixture.html?" + new Date().getTime();
var xhr;
// retrieve the fixture markup via xhr request to jasmine server
try {
xhr = new jasmine.XmlHttpRequest();
xhr.open("GET", path, false);
xhr.send(null);
} catch(e) {
throw new Error("couldn't fetch " + path + ": " + e);
}
var regExp = new RegExp(/Couldn\\\'t load \/fixture/);
if (regExp.test(xhr.responseText)) {
throw new Error("Couldn't load fixture with key: '" + fixtureName + "'. No such file: '" + path + "'.");
}
return xhr.responseText;
};
spec.loadFixtureCount = 0;
spec.cachedFixtures = {};
| JavaScript | 0 | @@ -733,16 +733,55 @@
get));%0A%0A
+ Diaspora.I18n.loadLocale(%7B%7D, 'en');%0A%0A
Diaspo
|
afdeedd8d2b41cc4fdaf31061bfb6e2d8475e919 | Fix settings manager serializer | lib/io/SettingsManager.js | lib/io/SettingsManager.js | "use strict";
var JSONSerializer = require('./JSONSerializer');
var SettingsManager = function (data, serializer) {
this._data = data || {};
this._serializer = serializer || JSONSerializer;
};
SettingsManager.prototype.getValue = function (key, defaultValue) {
if (typeof this._data[key] !== 'undefined')
return this._data[key];
else if (hasLocalStorageSupport())
return this._serializer.deserialize(window.localStorage.getItem(key));
else
return defaultValue;
};
SettingsManager.prototype.setValue = function (key, value) {
if (hasLocalStorageSupport())
window.localStorage.setItem(key, this._serializer.serialize(value));
};
function hasLocalStorageSupport() {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
}
module.exports = SettingsManager; | JavaScript | 0.000001 | @@ -176,16 +176,20 @@
lizer %7C%7C
+ new
JSONSer
@@ -195,16 +195,18 @@
rializer
+()
;%0A%7D;%0A%0ASe
|
149763e1fe2755873c0d4c7b9279baf1cf58f8c5 | mark sid as invalid, when no session is found but sid is in cookies | lib/middleware/session.js | lib/middleware/session.js | // TODO make sessions expire
var env = process.env;
var EventEmitter = require('events').EventEmitter;
var cookie = require('cookie');
var clone = require(env.Z_PATH_UTILS + 'clone');
var cache = require(env.Z_PATH_CACHE + 'cache');
var sessionCache = cache.pojo('sessions');
var randomStringBase = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
var publicSid = uid();
var sessionCookieKey = 'sid';
var roleKey = env.Z_SESSION_ROLE_KEY;
var userKey = env.Z_SESSION_USER_KEY;
var localeKey = env.Z_SESSION_LOCALE_KEY;
module.exports = middleware;
// session class
var Session = {};
// create a new session
Session.create = function (role, locale, user, callback) {
var self = this;
self.sid = uid();
self[roleKey] = role;
self[userKey] = user;
self[localeKey] = locale || 'en_US';
// save session
self.save(callback);
};
Session.regenerate = function () {
// renew session with a new sid
};
Session.destroy = function (callback) {
var self = this;
// remove from cache
sessionCache.rm(self.sid);
// remove session data
delete self.sid;
delete self[roleKey];
delete self[userKey];
delete self[localeKey];
callback();
};
Session.reload = function () {
// reload session data
};
// save session in cache
Session.save = function (callback) {
var self = this;
// save session
if (self.sid) {
sessionCache.set(self.sid, self);
}
callback();
};
Session.touch = function () {
// update expire
};
Session.maxAge = function () {
// expire info
};
// get or create session
function middleware (connectionHandler) {
return function (connection, response) {
// make it compatible with ws connections
var con = connection.upgradeReq ? connection.upgradeReq : connection;
connection.session = null;
// create an empty session
var session;
// parse cookies, get session id
if (con.headers.cookie) {
var parsedCookie = cookie.parse(con.headers.cookie);
if (parsedCookie && parsedCookie[sessionCookieKey]) {
var sessionId = parsedCookie[sessionCookieKey];
// get session
// TODO update expire
session = sessionCache.get(sessionId/*, now: new Date().getTime() / 1000*/);
}
}
// append session to connection
connection.session = session || clone(Session);
// continue with request
connectionHandler(null, connection, response);
};
}
// random string generator
function uid (len, string) {
len = len || 23;
string = string || '';
for (var i = 0; i < len; ++i) {
string += randomStringBase[0 | Math.random() * 62];
}
return string;
}
| JavaScript | 0.000002 | @@ -1821,44 +1821,8 @@
n;%0A%0A
- connection.session = null;%0A%0A
@@ -1844,32 +1844,32 @@
n empty session%0A
+
var sess
@@ -2087,73 +2087,8 @@
%7B%0A%0A
- var sessionId = parsedCookie%5BsessionCookieKey%5D;%0A%0A
@@ -2199,17 +2199,38 @@
get(
-sessionId
+parsedCookie%5BsessionCookieKey%5D
/*,
@@ -2265,16 +2265,169 @@
1000*/);
+%0A%0A // remove cookie from http headers%0A if (!session) %7B%0A connection._sidInvalid = true;%0A %7D
%0A
|
11ce1a1be0d7d26e9a603d362e63513cb0a6c46b | Extend JSON with additional KSS params | lib/modules/kss-parser.js | lib/modules/kss-parser.js |
'use strict';
var kss = require('kss'),
path = require('path'),
Q = require('q'),
gutil = require('gulp-util'),
kssSplitter = require('./kss-splitter'),
sanitizeHtml = require('sanitize-html');
// Parses kss.KssSection to JSON
function jsonSections(sections) {
return sections.map(function(section) {
return {
header: section.header(),
description: sanitize(section.description()),
modifiers: jsonModifiers(section.modifiers()),
deprecated: section.deprecated(),
experimental: section.experimental(),
reference: section.reference(),
markup: section.markup() ? section.markup().toString() : null
};
});
}
// Parses kss.KssModifier to JSON
function jsonModifiers(modifiers) {
return modifiers.map(function(modifier, id) {
return {
id: id + 1,
name: modifier.name(),
description: sanitize(modifier.description()),
className: modifier.className(),
markup: modifier.markup() ? modifier.markup().toString() : null
};
});
}
function trimLinebreaks(str) {
// Remove leading and trailing linebreaks
if (!str) {
return str;
}
return str.replace(/^[\r\n]+|[\r\n]+$/g, '');
}
function sanitize(string) {
return sanitizeHtml(string, {allowedTags: [], allowedAttributes: []});
}
function processBlock(block, options, json) {
return Q.Promise(function(resolve, reject) {
kss.parse(block.kss, options, function(err, styleguide) {
var section,
blockStyles;
if (err) {
console.error(' error processing kss block', err);
reject(err);
return false;
} else {
section = jsonSections(styleguide.section());
if (section.length > 0) {
if (section.length > 1) {
console.warn('Warning: KSS splitter returned more than 1 KSS block. Styleguide might not be properly generated.');
}
blockStyles = trimLinebreaks(block.code);
// Add related CSS to section
if (blockStyles && blockStyles !== '') {
section[0].css = blockStyles;
}
json.sections = json.sections.concat(section);
}
resolve();
}
});
});
}
function processFile(contents, syntax, options, json) {
return Q.Promise(function(resolve, reject) {
var blockPromises = [],
blocks;
try {
blocks = kssSplitter.getBlocks(contents, syntax);
// Process every block in the current file
blocks.forEach(function(block) {
blockPromises.push(processBlock(block, options, json));
});
} catch (err) {
reject(err);
}
Q.all(blockPromises).then(resolve);
});
}
function toInt(s) {
return parseInt(s, 10);
}
function quote(s) {
return '"' + s + '"';
}
function bySectionReference(x, y) {
var xs = x.reference.split('.').map(toInt),
ys = y.reference.split('.').map(toInt),
len = Math.min(xs.length, ys.length),
cmp, i;
for (i = 0; i < len; i += 1) {
cmp = xs[i] - ys[i];
if (cmp !== 0) {
return cmp;
}
}
len = xs.length - ys.length;
if (len === 0) {
throw new gutil.PluginError('kss-parser', 'Two sections defined with same number ' +
x.reference + ': ' + quote(x.header) + ' and ' + quote(y.header));
}
return len;
}
module.exports = {
// Parse node-kss object ( {'file.path': 'file.contents.toString('utf8'}' )
parseKSS: function(files, options) {
return Q.Promise(function(resolve, reject) {
var json = {
sections: []
},
filePromises = [],
fileKeys = Object.keys(files);
fileKeys.forEach(function(filePath) {
var contents = files[filePath],
syntax = path.extname(filePath).substring(1);
filePromises.push(processFile(contents, syntax, options, json));
});
Q.all(filePromises).then(function() {
// All files are processed. Sort results and call main promise
try {
json.sections.sort(bySectionReference);
resolve(json);
} catch (err) {
reject(err);
}
}).catch(reject);
});
}
};
| JavaScript | 0 | @@ -155,16 +155,101 @@
tter'),%0A
+ kssAdditionalParams = require('./kss-additional-params'),%0A _ = require('lodash'),%0A
saniti
@@ -1457,24 +1457,64 @@
e, reject) %7B
+%0A%0A // Parse with original KSS library
%0A kss.par
@@ -2052,24 +2052,140 @@
ock.code);%0A%0A
+ // Add extra parameters%0A section%5B0%5D = _.assign(section%5B0%5D, kssAdditionalParams.get(block.kss));%0A%0A
//
|
9f3ac4bd9932a0d2dc991199e41001ce30f8eecd | Create file if file doesnt exist | lib/plugins/write-file.js | lib/plugins/write-file.js | var fs = require('fs');
module.exports = function(context) {
//
// Write some data to a file.
//
context.writeFile = function(data, file) {
fs.writeFile(file, data, function(err) {
if (err) {
throw err;
}
});
};
};
| JavaScript | 0.000001 | @@ -101,107 +101,345 @@
//
-%0A context.writeFile = function(data, file) %7B%0A fs.writeFile(file, data, function(err) %7B%0A
+ Creates new file with the name supplied if the file doesnt exist%0A //%0A context.writeFile = function(data, file) %7B%0A fs.open(file, 'a+', function(err, fd) %7B%0A if(err) %7B%0A throw err;%0A %7D%0A%0A var buffer = new Buffer(data);%0A%0A fs.write(fd, buffer, 0, buffer.length, null, function(err, bytread, buffer) %7B %0A
if
(er
@@ -434,17 +434,16 @@
if
-
(err) %7B%0A
@@ -442,32 +442,34 @@
(err) %7B%0A
+
throw err;%0A
@@ -463,24 +463,26 @@
ow err;%0A
+
%7D%0A
%7D);%0A
@@ -473,16 +473,33 @@
%7D%0A
+ %7D);%0A %0A
%7D);%0A
|
a728f9037c86d72a5deac4eb66d685bea8e66378 | use direct | lib/reducers/appGlobal.js | lib/reducers/appGlobal.js | import {
UPDATE_APP_GLOBAL,
} from '../constants/ActionTypes';
import defaultSettings from '../data/default_settings.json';
import _ from 'lodash';// eslint-disable-line id-length
function token(state = defaultSettings.token, action = {}) {
switch (action.type) {
case UPDATE_APP_GLOBAL:
if (action.payload.configs) {
if (_.isString(action.payload.configs.get('token'))) {
return action.payload.configs.get('token');
}
}
return state;
default:
return state;
}
}
function apiEndpoint(state = defaultSettings.apiEndpoint, action = {}) {
switch (action.type) {
case UPDATE_APP_GLOBAL:
if (action.payload.configs) {
if (_.isString(action.payload.configs.get('apiEndpoint'))) {
return action.payload.configs.get('apiEndpoint');
}
}
return state;
default:
return state;
}
}
function webEndpoint(state = defaultSettings.webEndpoint, action = {}) {
switch (action.type) {
case UPDATE_APP_GLOBAL:
if (action.payload.configs) {
if (_.isString(action.payload.configs.get('webEndpoint'))) {
return action.payload.configs.get('webEndpoint');
}
}
return state;
default:
return state;
}
}
function interval(state = defaultSettings.interval, action = {}) {
switch (action.type) {
case UPDATE_APP_GLOBAL:
if (action.payload.configs) {
if (_.isFinite(action.payload.configs.get('interval'))) {
return action.payload.configs.get('interval');
}
}
return state;
default:
return state;
}
}
function autopiloting(state = false, action = {}) {
switch (action.type) {
case UPDATE_APP_GLOBAL:
if (action.payload.configs) {
if (_.isBoolean(action.payload.configs.get('autopoloting'))) {
return action.payload.configs.get('autopoloting');
}
}
return state;
default:
return state;
}
}
function autopilotedAt(state = null, action = {}) {
switch (action.type) {
case UPDATE_APP_GLOBAL:
if (action.payload.configs) {
if (_.isDate(action.payload.configs.get('autopolotedAt'))) {
return action.payload.configs.get('autopolotedAt');
}
}
return state;
default:
return state;
}
}
export default function(state = new Map(), action = {}) {
return new Map([
['defaultApiEndpoint', defaultSettings.apiEndpoint],
['defaultWebEndpoint', defaultSettings.webEndpoint],
['defaultInterval', defaultSettings.interval],
['token', token(state.get('token'), action)],
['apiEndpoint', apiEndpoint(state.get('apiEndpoint'), action)],
['webEndpoint', webEndpoint(state.get('webEndpoint'), action)],
['interval', interval(state.get('interval'), action)],
['autopiloting', autopiloting(state.get('autopiloting'), action)],
['autopilotedAt', autopilotedAt(state.get('autopilotedAt'), action)],
]);
}
| JavaScript | 0.000003 | @@ -130,56 +130,73 @@
ort
-_ from 'lodash';// eslint-disable-line id-length
+%7B%0A isString,%0A isFinite,%0A isDate,%0A isBoolean,%0A%7D from 'lodash';
%0A%0Afu
@@ -341,34 +341,32 @@
gs) %7B%0A if (
-_.
isString(action.
@@ -678,34 +678,32 @@
gs) %7B%0A if (
-_.
isString(action.
@@ -1035,18 +1035,16 @@
if (
-_.
isString
@@ -1378,18 +1378,16 @@
if (
-_.
isFinite
@@ -1700,18 +1700,16 @@
if (
-_.
isBoolea
@@ -2013,32 +2013,32 @@
load.configs) %7B%0A
+
if (_.isDa
@@ -2035,10 +2035,8 @@
if (
-_.
isDa
|
b72510664f4d2d50f66fabdd758fbdcc17bb4f17 | Remove extra restrictions. | lib/systems/draw-image.js | lib/systems/draw-image.js | "use strict";
function drawEntity(data, entity, context) {
var image = data.images.get(entity.image.name);
if (!image) {
console.error("No such image", entity.image.name);
return;
}
try {
context.drawImage(
image,
entity.image.sourceX,
entity.image.sourceY,
entity.image.sourceWidth,
entity.image.sourceHeight,
entity.image.destinationX + entity.position.x,
entity.image.destinationY + entity.position.y,
entity.image.destinationWidth,
entity.image.destinationHeight
);
} catch (e) {
console.error("Error drawing image", entity.image.name, e);
}
}
module.exports = function(ecs, data) {
ecs.add(function(entities, context) {
var keys = Object.keys(entities);
keys.sort(function(a, b) {
var za = entities[a].zindex || 0;
var zb = entities[b].zindex || 0;
return za - zb;
});
for (var i = 0; i < keys.length; i++) {
var entity = entities[keys[i]];
if (entity.image === undefined || entity.position === undefined) {
continue;
}
drawEntity(data, entity, context);
}
}, ["image", "position"]);
};
| JavaScript | 0 | @@ -1044,31 +1044,8 @@
%0A%0A%09%7D
-, %5B%22image%22, %22position%22%5D
);%0A%7D
|
6046e2ea5ff6a5b7d5c5d8008409b538dc192847 | Update TerminalOutputter | lib/terminal-outputter.js | lib/terminal-outputter.js | var _ = require('lodash'),
Time = require('./time');
function TerminalOutputter() {
this.output = output;
function output(records) {
var totalTime = 0;
var stats = [];
_.forEach(records, function(record) {
totalTime += record.total;
stats.push(record.date + '\t' + new Time(record.total).toString());
})
stats.push('');
stats.push('----------------------------------')
stats.push('Total:\t' + new Time(totalTime).toString());
console.log(stats.join('\n'));
}
}
module.exports = TerminalOutputter;
| JavaScript | 0.000001 | @@ -28,33 +28,1247 @@
-Time = require('./time');
+moment = require('moment'),%0A Time = require('./time');%0A%0Avar DELIMITER = '----------------------------';%0A%0Afunction Week(number, year) %7B%0A var self = this;%0A%0A this.number = number;%0A this.year = year;%0A this.days = %5B%5D;%0A%0A this.addDay = addDay;%0A this.printSummary = printSummary;%0A%0A function addDay(record) %7B%0A self.days.push(new Day(record));%0A %7D%0A%0A function printSummary() %7B%0A var parts = %5B%0A '',%0A DELIMITER,%0A 'WEEK ' + self.year + '/' + _.padLeft(self.number, 2, ' ') + '%5Ct' + weeklyTotal(),%0A DELIMITER,%0A daysToString(),%0A DELIMITER,%0A %5D;%0A%0A console.log(parts.join('%5Cn'));%0A %7D%0A%0A function weeklyTotal() %7B%0A var total = _.inject(self.days, function(memo, day) %7B%0A memo += day.record.total;%0A return memo;%0A %7D, 0);%0A return new Time(total).toString();%0A %7D%0A%0A function daysToString() %7B%0A return _.map(self.days, function(day) %7B%0A return day.toString();%0A %7D).join('%5Cn');%0A %7D%0A%7D%0A%0Afunction Day(record) %7B%0A this.record = record;%0A this.toString = toString;%0A%0A function toString() %7B%0A return record.date + '%5Ct' + new Time(record.total).toString()%0A %7D%0A%7D
%0A%0Afu
@@ -1397,19 +1397,20 @@
var
-stats = %5B%5D;
+weeks = %7B%7D;%0A
%0A
@@ -1433,24 +1433,130 @@
ecords,
-function
+addRecord);%0A%0A outputWeeklies();%0A console.log('');%0A outputTotal();%0A%0A function addRecord
(record)
@@ -1589,32 +1589,33 @@
= record.total;%0A
+%0A
stat
@@ -1614,73 +1614,398 @@
-stats.push(record.date + '%5Ct' + new Time(record.total).toString()
+var mom = moment(record.date);%0A var number = mom.week();%0A var week = weeks%5Bnumber%5D;%0A if (!week) %7B%0A weeks%5Bnumber%5D = week = new Week(number, mom.year());%0A %7D%0A week.addDay(record);%0A %7D%0A%0A function outputWeeklies() %7B%0A _.forEach(weeks, function(week) %7B%0A week.printSummary();%0A %7D
);%0A
@@ -2012,17 +2012,17 @@
%7D
-)
+%0A
%0A
@@ -2026,99 +2026,92 @@
-stats.push('');%0A stats.push('----------------------------------')%0A stats.push
+function outputTotal() %7B%0A console.log(DELIMITER);%0A console.log
('To
@@ -2166,38 +2166,9 @@
-console.log(stats.join('%5Cn'));
+%7D
%0A
|
3696b946c670124ec0dd0824680d5eb8acd1317a | Implement BottomPanel::{prepare, destroy, updateMessages} | lib/views/bottom-panel.js | lib/views/bottom-panel.js | 'use strict'
class BottomPanel extends HTMLElement{
set visibility(value){
if(value){
this.removeAttribute('hidden')
} else {
this.setAttribute('hidden', true)
}
}
clear(){
while(this.firstChild){
this.removeChild(this.firstChild)
}
}
}
module.exports = document.registerElement('linter-panel', {prototype: BottomPanel.prototype})
| JavaScript | 0 | @@ -7,16 +7,52 @@
trict'%0A%0A
+let Message = require('./message')%0A%0A
class Bo
@@ -88,141 +88,655 @@
%7B%0A
-set visibility(value)%7B%0A if(value)%7B%0A this.removeAttribute('hidden')%0A %7D else %7B%0A this.setAttribute('hidden', true)%0A %7D
+prepare()%7B%0A this.panel = atom.workspace.addBottomPanel(%7Bitem: this, visible: true%7D)%0A return this%0A %7D%0A destroy()%7B%0A this.panel.destroy()%0A %7D%0A set visibility(value)%7B%0A if(value)%7B%0A this.removeAttribute('hidden')%0A %7D else %7B%0A this.setAttribute('hidden', true)%0A %7D%0A %7D%0A updateMessages(messages, isProject)%7B%0A while(this.firstChild)%7B%0A this.removeChild(this.firstChild)%0A %7D%0A if(!messages.length)%7B%0A return this.visibility = false%0A %7D%0A this.visibility = true%0A messages.forEach(function(message)%7B%0A this.appendChild(Message.fromMessage(message, %7BaddPath: isProject, cloneNode: true%7D))%0A %7D.bind(this))
%0A %7D
|
502e92e14fa57048640bd7e4de5f36037aacd7b5 | Remove unnecessary console.log | lib/with-initial-fetch.js | lib/with-initial-fetch.js | import React from 'react'
import {useStore} from 'react-redux'
import P from './components/p'
import Spinner from './components/spinner'
import usePromise from './hooks/use-promise'
import useWindowSize from './hooks/use-window-size'
import getInitialAuth from './get-initial-auth'
const minHeight = '600px'
const minWidth = '320px'
const spinnerStyle = {
color: '#2389c9',
fontSize: '36px',
marginTop: '-25px',
width: '100%',
textAlign: 'center',
top: '50%',
position: 'relative'
}
const ShowError = p => (
<div className='block'>
<P>{String(p.error)}</P>
</div>
)
const ShowSpinner = () => (
<div style={spinnerStyle}>
<Spinner />
</div>
)
export default function withInitialFetch(Component, initialFetch, opts = {}) {
const serverRendered = typeof window === 'undefined'
function ClientFetch(p) {
const store = useStore()
const {query, __clientFetch} = p
const getInitialFetch = React.useCallback(
() => (__clientFetch ? initialFetch(store, query) : Promise.resolve({})),
[store, query, __clientFetch]
)
const [loading, error, results] = usePromise(getInitialFetch)
const size = useWindowSize()
// Short circuit when loaded from server
if (!__clientFetch) return <Component {...p} />
if (error) return <ShowError error={error} />
if (results) return <Component {...p} {...results} />
return (
<div style={{height: size.height || minHeight, minWidth}}>
{loading && <ShowSpinner />}
</div>
)
}
ClientFetch.getInitialProps = async ctx => {
const {user} = await getInitialAuth(ctx)
if (serverRendered && !opts.clientOnly) {
console.log('How?', serverRendered, opts.clientOnly)
const results = await initialFetch(ctx.store, ctx.query)
return {...results, user}
}
return {__clientFetch: true, user}
}
return ClientFetch
}
| JavaScript | 0.000007 | @@ -1655,67 +1655,8 @@
) %7B%0A
- console.log('How?', serverRendered, opts.clientOnly)%0A
|
8711675c241c729a19fc2af1f476faf5becf79af | remove duplicate clean task | dev/release.js | dev/release.js | 'use strict';
const fs = require('fs');
const path = require('path');
const semver = require('semver');
const inquirer = require('inquirer');
const nconf = require('nconf');
const _ = require('lodash');
const shell = require('shelljs');
const lint = require('./lint');
const clean = require('./clean');
const build = require('./build');
let VERSION = null;
let RAW = null;
function raw() {
if (!RAW) {
RAW = fs.readFileSync(path.join(process.cwd(), 'package.json'), 'utf8');
}
return RAW;
}
function pkg(contents) {
return JSON.parse(contents || raw());
}
// Preserver new line at the end of a file
function newLine(contents) {
const lastChar = (contents && contents.slice(-1) === '\n') ? '' : '\n';
return contents + lastChar;
}
function bump() {
return new Promise( (resolve, reject) => {
if (!VERSION) {
return reject(false);
}
let contents = raw();
let json = pkg(contents);
json = _.merge({}, json, {version: VERSION});
contents = JSON.stringify(json, null, 2);
contents = newLine(contents);
// update package.json
fs.writeFileSync(path.join(process.cwd(), 'package.json'), contents, 'utf8');
resolve();
});
}
function git() {
return new Promise( resolve => {
shell.exec('git add .');
shell.exec(`git commit -m "v${VERSION}"`);
shell.exec(`git tag -a v${VERSION} -m "v${VERSION}"`);
const push = nconf.get('push');
if (push) {
shell.exec('git push', 'Push to remote');
shell.exec('git push --tags', `Push new tag v${VERSION} to remote`);
}
resolve();
});
}
function prompt() {
const version = pkg().version;
const parsed = semver.parse(version);
// regular release
const simpleVersion = `${parsed.major}.${parsed.minor}.${parsed.patch}`;
let choices = [
{name: `patch ( ${version} --> ${semver.inc(simpleVersion, 'patch')}`, value: semver.inc(simpleVersion, 'patch')},
{name: `minor ( ${version} --> ${semver.inc(simpleVersion, 'minor')}`, value: semver.inc(simpleVersion, 'minor')},
{name: `major ( ${version} --> ${semver.inc(simpleVersion, 'major')}`, value: semver.inc(simpleVersion, 'major')},
new inquirer.Separator(),
{name: 'other', value: 'other'}
];
// pre-release
if (parsed.prerelease && parsed.prerelease.length) {
choices = [
{name: `prerelease ( ${version} => ${semver.inc(version, 'prerelease', parsed[0])})`, value: semver.inc(version, 'prerelease', parsed[0])},
{name: `release ( ${version} => ${simpleVersion})`, value: simpleVersion},
new inquirer.Separator(),
{name: 'other', value: 'other'}
];
}
const questions = [
{
type: 'rawlist',
name: 'bump',
message: 'What type of version bump would you like to do?',
choices
},
{
type: 'input',
name: 'version',
message: `version (current version is ${pkg().version})`,
when(answer) {
return answer.bump === 'other';
},
filter(value) {
return semver.clean(value);
},
validate(value) {
const valid = semver.valid(value);
if (valid) {
return true;
}
return 'Enter valid semver version number. Please see https://docs.npmjs.com/misc/semver for more details.';
}
}
];
return inquirer.prompt(questions).then( answers => {
VERSION = answers.bump !== 'other' ? answers.bump : answers.version;
});
}
function release() {
return prompt()
.then(lint)
.then(clean)
.then(bump)
.then(build)
.then(git);
}
module.exports = release;
| JavaScript | 0.999722 | @@ -268,42 +268,8 @@
');%0A
-const clean = require('./clean');%0A
cons
@@ -3465,25 +3465,8 @@
nt)%0A
- .then(clean)%0A
|
590abe07d9af483dea0e82b1ee481e191821edc9 | Remove use of getElement() in example | aura-components/src/main/components/uiExamples/radio/radioController.js | aura-components/src/main/components/uiExamples/radio/radioController.js | /*
* Copyright (C) 2013 salesforce.com, inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
({
onRadio: function(cmp, evt) {
var elem = evt.getSource().getElement();
var selected = elem.textContent;
resultCmp = cmp.find("radioResult");
resultCmp.set("v.value", selected);
},
onGroup: function(cmp, evt) {
var elem = evt.getSource().getElement();
var selected = elem.textContent;
resultCmp = cmp.find("radioGroupResult");
resultCmp.set("v.value", selected);
}
})
| JavaScript | 0.000002 | @@ -650,79 +650,44 @@
var
+s
ele
-m
+cted
= evt.
-getS
+s
ource
-()
.get
-Element();%0A%09%09 var selected = elem.textContent
+(%22v.label%22)
;%0A%09%09
@@ -812,79 +812,44 @@
var
+s
ele
-m
+cted
= evt.
-getS
+s
ource
-()
.get
-Element();%0A%09%09 var selected = elem.textContent
+(%22v.label%22)
;%0A%09%09
|
eb0ff20c6fbda55000bffd44999253a7ac2f4dda | Add example of advanced search, add detail to show all options available | example.js | example.js | 'use strict'
var Scraper = require ('./index')
, google = new Scraper.Google()
, bing = new Scraper.Bing()
, pics = new Scraper.Picsearch()
, yahoo = new Scraper.Yahoo();
// will take ALOT of time if num=undefined
google.list({
keyword: 'coca cola',
num: 10,
nightmare: {
show: true
}
//resolution:'l',
})
.then(function (res) {
console.log('first 10 results from google', res);
}).catch(function(err) {
console.log('err',err);
});
// listening on events is also possible
google.on('result', function(item) {
console.log('result', item);
});
bing.list({
keyword: 'banana',
num: 10
})
.then(function (res) {
console.log('first 10 results from bing', res);
}).catch(function(err) {
console.log('err',err);
});
pics.list({
keyword: 'banana',
num: 10,
}).then(function (res) {
console.log('out',res);
}).catch(function (err) {
console.log('err',err);
});
yahoo.list({
keyword: 'banana',
num: 10,
}).then(function (res) {
console.log('results', res);
}).catch(function (err) {
console.log('err',err);
}); | JavaScript | 0 | @@ -264,16 +264,31 @@
um: 10,%0A
+%09detail: true,%0A
%09nightma
@@ -312,27 +312,168 @@
e%0A%09%7D
-%0A%09//resolution:'l',
+,%0A advanced: %7B%0A imgType: 'photo', // options: clipart, face, lineart, news, photo%0A resolution: undefined // options: l(arge), m(edium), i(cons), etc.%0A %7D
%0A%7D)%0A
|
f2794c356253f2f64e8bba6211db209e2039be4f | Fix the print-schema script | src/tools/print-schema/src/index.js | src/tools/print-schema/src/index.js | /**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import { getIntrospectionResult }
from '../../../language/schema/printer';
var Promise = require('bluebird');
var parseArgs = require('minimist');
var fs = require('fs');
Promise.promisifyAll(fs);
export async function executeTool() {
try {
var argDict = parseArgs(process.argv.slice(2));
if (argDict['?'] !== undefined || argDict.help !== undefined) {
console.log(helpString);
process.exit(0);
}
if (argDict.query === undefined) {
console.log('--query is required');
console.log(helpString);
process.exit(0);
}
if (argDict.file === undefined) {
console.log('--file is required');
console.log(helpString);
process.exit(0);
}
var body = await fs.readFileAsync(argDict.file, 'utf8');
var result = await getIntrospectionResult(body, argDict.query);
var out = await JSON.stringify(result, null, 2);
console.log(out);
} catch (error) {
console.error(error);
console.error(error.stack);
}
}
var helpString = `
This tool consumes GraphQL schema definition files and outputs the
introspection query result from querying that schema.
Required:
--file <path>: The path to the input schema definition file.
--query <queryType>: The query type (root type) of the schema.`;
| JavaScript | 0.999823 | @@ -309,38 +309,34 @@
mport %7B
-getIntrospectionResult
+parseSchemaIntoAST
%7D%0A fro
@@ -367,15 +367,123 @@
ema/
-printer
+';%0Aimport %7B buildASTSchema, introspectionQuery %7D%0A from '../../../utilities/';%0Aimport %7B graphql %7D%0A from '../../../
';%0A%0A
@@ -1189,61 +1189,170 @@
var
-result = await getIntrospectionResult(body, argDict.q
+ast = parseSchemaIntoAST(body);%0A var astSchema = buildASTSchema(ast, argDict.query, argDict.mutation);%0A var result = await graphql(astSchema, introspectionQ
uery
@@ -1727,16 +1727,16 @@
n file.%0A
-
--query
@@ -1789,11 +1789,95 @@
schema.
+%0A%0AOptional:%0A%0A--mutation %3CmutationType%3E: The mutation type (root type) of the schema.
%60;%0A
|
0058f9462a50e044fcb808d8ba7869e3ec9ff76e | Increase tesimonial slider time | www/source/javascripts/home.js | www/source/javascripts/home.js | var homepageScripts = function() {
var adjustParentHeight = function($elements, $parent) {
var maxElementHeight = 0;
var currentElementHeight;
$elements.each(function() {
currentElementHeight = $(this).outerHeight(true);
if (currentElementHeight > maxElementHeight) {
maxElementHeight = currentElementHeight;
$parent.css("height", maxElementHeight);
}
});
};
// Feature Slider
const homepageSlides = ["plan-and-config", "build-packages"];
const $sliderButtons = $(".slider--nav button");
const $slides = $(".slide");
const $slidesWrap = $(".slides");
var slideHeight;
$("#slide--plan-and-config").fadeIn();
$sliderButtons.click(function() {
var $button = $(this);
$(".slider--nav .is-active").removeClass("is-active")
$button.addClass("is-active");
for (var slide in homepageSlides) {
if ($button.hasClass(homepageSlides[slide]) && $("#slide--" + homepageSlides[slide]).is(":hidden")) {
$(".slide").fadeOut();
$("#slide--" + homepageSlides[slide]).fadeIn();
}
}
adjustParentHeight($slides, $slidesWrap);
});
adjustParentHeight($slides, $slidesWrap);
$(window).resize(function() {
adjustParentHeight($slides, $slidesWrap);
});
// Production Icons
const icons = ["lock", "search", "settings", "file", "health"];
const $productionIcons = $(".production--icon");
$productionIcons.click(function() {
$icon = $(this);
var $iconText;
for (var iconName in icons) {
$iconText = $(".production--icon-text." + icons[iconName]);
if ($icon.hasClass(icons[iconName]) && !$iconText.hasClass("is-active")) {
$(".production--graphic .is-active").removeClass("is-active");
$icon.addClass("is-active");
$iconText.addClass("is-active");
}
}
});
// Testimonials slider
const $testimonials = $(".testimonial");
const testimonialsSlider = ".testimonials-slider";
const $testimonialText = $(".testimonial--blurb");
var $currentSlide, testimonialHeight, currentTestimonialHeight;
adjustParentHeight($testimonials, $(testimonialsSlider));
$(window).resize(function() {
adjustParentHeight($testimonials, $(testimonialsSlider));
});
setInterval(function() {
$currentSlide = $(".testimonial.is-active");
$(testimonialsSlider + " .is-active").removeClass("is-active");
if ($currentSlide.hasClass("first")) {
$(testimonialsSlider + " .second").addClass("is-active");
} else if ($currentSlide.hasClass("second")) {
$(testimonialsSlider + " .first").addClass("is-active");
}
}, 6000);
}; | JavaScript | 0 | @@ -2621,13 +2621,15 @@
%7D,
-6
+15
000);
+g
%0A%7D;
|
b0d6e8ac60e86092cf8f385997ab2514724c1c11 | Update maps plugin manifest to use select menu syntax | plugins/googlemap/popcorn.googlemap.js | plugins/googlemap/popcorn.googlemap.js | // PLUGIN: Google Maps
var googleCallback;
(function (Popcorn) {
/**
* googlemap popcorn plug-in
* Adds a map to the target div centered on the location specified by the user
* Options parameter will need a start, end, target, type, zoom, lat and long, and location
* -Start is the time that you want this plug-in to execute
* -End is the time that you want this plug-in to stop executing
* -Target is the id of the DOM element that you want the map to appear in. This element must be in the DOM
* -Type [optional] either: HYBRID (default), ROADMAP, SATELLITE, TERRAIN
* -Zoom [optional] defaults to 0
* -Lat and Long: the coordinates of the map must be present if location is not specified.
* -Location: the adress you want the map to display, bust be present if lat and log are not specified.
* Note: using location requires extra loading time, also not specifying both lat/long and location will
* cause and error.
* @param {Object} options
*
* Example:
var p = Popcorn('#video')
.googlemap({
start: 5, // seconds
end: 15, // seconds
type: 'ROADMAP',
target: 'map',
lat: 43.665429,
long: -79.403323
} )
*
*/
Popcorn.plugin( "googlemap" , (function(){
var newdiv, i = 1, _mapFired = false, _mapLoaded = false;
return {
manifest: {
about:{
name: "Popcorn Google Map Plugin",
version: "0.1",
author: "@annasob",
website: "annasob.wordpress.com"
},
options:{
start : {elem:'input', type:'text', label:'In'},
end : {elem:'input', type:'text', label:'Out'},
target : 'map-container',
type : {elem:'select', type:'text', label:'Type'},
zoom : {elem:'input', type:'text', label:'Zoom'},
lat : {elem:'input', type:'text', label:'Lat'},
long : {elem:'input', type:'text', label:'Long'},
location : {elem:'input', type:'text', label:'Location'}
}
},
_setup : function( options ) {
// create a new div this way anything in the target div
// this is later passed on to the maps api
options._newdiv = document.createElement('div');
options._newdiv.id = "actualmap"+i;
options._newdiv.style.width = "100%";
options._newdiv.style.height = "100%";
i++;
if (document.getElementById(options.target)) {
document.getElementById(options.target).appendChild(options._newdiv);
}
// insert google api script once
if (!_mapFired) {
_mapFired = true;
var loadScriptTime = (new Date).getTime();
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=googleCallback";
script.type = "text/javascript";
head.insertBefore( script, head.firstChild );
}
// callback function fires when the script is run
googleCallback = function() {
_mapLoaded = true;
};
// If there is no lat/long, and there is location, geocode the location
// you can only do this once google.maps exists
var isGeoReady = function() {
if ( !_mapLoaded ) {
setTimeout(function () {
isGeoReady();
}, 5);
} else {
if (options.location) {
var geocoder = new google.maps.Geocoder();
// calls an anonymous function called on separate thread
geocoder.geocode({ 'address': options.location}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
options.lat = results[0].geometry.location.lat();
options.long = results[0].geometry.location.lng();
options._location = new google.maps.LatLng(options.lat, options.long);
options._map = new google.maps.Map(options._newdiv, {mapTypeId: google.maps.MapTypeId[options.type] || google.maps.MapTypeId.HYBRID });
options._map.getDiv().style.display = 'none';
}
});
} else {
options._location = new google.maps.LatLng(options.lat, options.long);
options._map = new google.maps.Map(options._newdiv, {mapTypeId: google.maps.MapTypeId[options.type] || google.maps.MapTypeId.HYBRID });
options._map.getDiv().style.display = 'none';
}
}
};
isGeoReady();
},
/**
* @member webpage
* The start function will be executed when the currentTime
* of the video reaches the start time provided by the
* options variable
*/
start: function(event, options){
// dont do anything if the information didn't come back from google map
var isReady = function () {
if (!options._map) {
setTimeout(function () {
isReady();
}, 13);
} else {
options._map.getDiv().style.display = 'block';
// reset the location and zoom just in case the user plaid with the map
options._map.setCenter(options._location);
// make sure options.zoom is a number
if ( options.zoom && typeof options.zoom !== "number" ) {
options.zoom = +options.zoom;
}
options.zoom = options.zoom || 0; // default to 0
options._map.setZoom( options.zoom );
}
};
isReady();
},
/**
* @member webpage
* The end function will be executed when the currentTime
* of the video reaches the end time provided by the
* options variable
*/
end: function(event, options){
// if the map exists hide it do not delete the map just in
// case the user seeks back to time b/w start and end
if (options._map) {
options._map.getDiv().style.display = 'none';
}
}
};
})());
})( Popcorn );
| JavaScript | 0 | @@ -1782,35 +1782,76 @@
m:'select',
-type:'text'
+options:%5B'ROADMAP','SATELLITE', 'HYBRID', 'TERRAIN'%5D
, label:'Typ
|
f76cac63c895b6c6c824b8b2a455ac516e2aa1ae | Update passport.js | app/config/passport.js | app/config/passport.js | /*jslint node:true */
'use strict';
/**
* Passport.js config file, heavily inspired by
* http://scotch.io/tutorials/javascript/easy-node-authentication-setup-and-local
*/
var LocalStrategy = require('passport-local').Strategy,
passwordHash = require('password-hash'),
connection = require('./../config/db.js')(10);
module.exports = function (passport) {
// =========================================================================
// passport session setup ==================================================
// =========================================================================
// required for persistent login sessions
// passport needs ability to serialize and unserialize users out of session
// used to serialize the user for the session
passport.serializeUser(function (user, done) {
done(null, user.id);
});
// used to deserialize the user
passport.deserializeUser(function (id, done) {
connection.query("select * from users where id = ?", [id], function (err, rows) {
done(err, rows[0]);
});
});
// =========================================================================
// LOCAL SIGNUP ============================================================
// =========================================================================
// we are using named strategies since we have one for login and one for signup
// by default, if there was no name, it would just be called 'local'
passport.use('local-signup', new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true // allows us to pass back the entire request to the callback
},
function (req, email, password, done) {
// find a user whose email is the same as the forms email
// we are checking to see if the user trying to login already exists
connection.query("select * from users where email = ?" + [email], function (err, rows) {
if (err) {return done(err);}
if (rows.length) {
req.signUpMessage = 'Diese e-Mail ist bei uns bereits registriert';
return done(null, false);
} else {
// if there is no user with that email
// create the user
var newUserMysql = {};
newUserMysql.title = req.body.title;
newUserMysql.email = email;
newUserMysql.firstName = req.body.firstName;
newUserMysql.lastName = req.body.lastName;
newUserMysql.password = passwordHash.generate(password);
connection.query('INSERT INTO users SET ?', [newUserMysql], function (err, rows) {
newUserMysql.id = rows.insertId;
return done(null, newUserMysql);
});
}
});
}));
// =========================================================================
// LOCAL LOGIN =============================================================
// =========================================================================
// we are using named strategies since we have one for login and one for signup
// by default, if there was no name, it would just be called 'local'
passport.use('local-login', new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true // allows us to pass back the entire request to the callback
},
function (req, email, password, done) { // callback with email and password from our form
connection.query("SELECT * FROM `users` WHERE `email` = ?", [email], function (err, rows) {
if (err) {return done(err);}
if (!rows.length) {
req.loginMessage='Die eingegebene E-Mail-Adresse oder das Passwort ist falsch.';
return done(null, false);
}
// if the user is found but the password is wrong
if (!passwordHash.verify(password, rows[0].password)) {
req.loginMessage = 'Die eingegebene E-Mail-Adresse oder das Passwort ist falsch.';
return done(null, false);
}
// all is well, return successful user
return done(null, rows[0]);
});
}));
};
| JavaScript | 0.000001 | @@ -2106,10 +2106,9 @@
= ?%22
- +
+,
%5Bem
|
4a9c69a713f930a7163a65f6e70e3736e38a6eaa | Update CORS proxy, testing "alloworigin" | js/search.js | js/search.js | $.fn.pressEnter = function(fn) {
return this.each(function() {
$(this).bind('enterPress', fn);
$(this).keyup(function(e){
if(e.keyCode == 13)
{
$(this).trigger("enterPress");
console.log("algo");
}
})
});
};
$('#submit').pressEnter(function(){
$('#movies').html("");
var search = $("#submit").val();
location.href = "?q=" + search;
/*
*/
return false;
});
var search_parameter = getUrlParameter('q');
$.getJSON("http://crossorigin.me/https://yts.ag/api/v2/list_movies.json?query_term="+search_parameter, function (data) {
$('#movies').html("");
i = 0;
var trackers = "&tr=udp:\/\/open.demonii.com:1337\/announce&tr=http:\/\/tracker.trackerfix.com\/announce&tr=udp:\/\/9.rarbg.to:2710&tr=udp:\/\/9.rarbg.me:2710&tr=udp:\/\/exodus.desync.com:6969&tr=udp:\/\/tracker.coppersurfer.tk:6969&tr=udp:\/\/tracker.leechers-paradise.org:6969&tr=udp:\/\/tracker.openbittorrent.com:80&tr=udp:\/\/glotorrents.pw:6969\/announce&tr=udp:\/\/tracker.opentrackr.org:1337\/announce&tr=udp:\/\/torrent.gresille.org:80\/announce&tr=udp:\/\/p4p.arenabg.com:1337&tr=udp:\/\/tracker.internetwarriors.net:1337&tr=http:\/\/www.siambt.com\/announce.php&tr=http:\/\/bttracker.crunchbanglinux.org:6969\/announce&tr=http:\/\/www.eddie4.nl:6969\/announce&tr=http:\/\/mgtracker.org:2710\/announce";
json_data = data.data.movies;
// JSON DATA
$.each(json_data, function (i, item) {
hash = item.torrents[0].hash; imdb = item.imdb_code; magnet = "magnet:?xt=urn:btih:"+hash+"&dn="+escape(item.title)+trackers; title = item.title; rating = item.rating; poster = item.medium_cover_image; genre = item.genres[0]; background = item.background_image; content_value = item.id;
catalogue (hash, imdb, magnet, title, rating, poster, genre, background, /*api_url, provider, proxy,*/ content_value);
i++;
});
// Pagination | Infinite Scrolling
//page=page++;
// Pagination | Infinite Scrolling
//$('#movies').append(html);
}); | JavaScript | 0 | @@ -527,16 +527,138 @@
etJSON(%22
+http://alloworigin.com/get?url=https://yts.ag/api/v2/list_movies.json?query_term=%22+search_parameter, function (data) %7B //
http://c
@@ -2162,12 +2162,13 @@
html);%0A%0A%7D);%09
+%0A
|
0595dfc9fe05a4e713c040ab7733feb6131944eb | Disable i18next’s saveMissing in production | lib/i18n.js | lib/i18n.js | const i18n = require('i18next')
const XHR = require('i18next-xhr-backend')
const LanguageDetector = require('i18next-browser-languagedetector')
const options = {
fallbackLng: 'en',
load: 'languageOnly',
ns: ['common'],
defaultNS: 'common',
// debug: true,
saveMissing: true,
interpolation: {
escapeValue: false,
formatSeparator: ',',
format: (value, format, lng) => {
if (format === 'uppercase') return value.toUpperCase()
return value
}
},
detection: {
lookupCookie: 'locale',
caches: ['cookie', 'localStorage']
},
react: {
wait: false
}
}
if (process.browser) {
i18n
.use(XHR)
.use(LanguageDetector)
}
if (!i18n.isInitialized) {
i18n.init(options)
}
module.exports = i18n
| JavaScript | 0 | @@ -138,16 +138,67 @@
ctor')%0A%0A
+const dev = process.env.NODE_ENV !== 'production'%0A%0A
const op
@@ -328,20 +328,19 @@
issing:
-true
+dev
,%0A%0A int
|
2d9fab2629b0bb9bf4dfbde280af680a0cf7d799 | fix unit test | test/unit/specs/security/users/browse.spec.js | test/unit/specs/security/users/browse.spec.js | import Vue from 'vue'
import store from '../../../../../src/vuex/store'
import { mockedComponent, mockedDirective } from '../../helper'
import Promise from 'bluebird'
let BrowseInjector = require('!!vue?inject!../../../../../src/components/Security/Users/Browse')
let Browse
let sandbox = sinon.sandbox.create()
describe('Browse data tests', () => {
let vm
let formatFromQuickSearch = sandbox.stub()
let formatFromBasicSearch = sandbox.stub()
let formatSort = sandbox.stub()
let searchTerm = sandbox.stub().returns()
let rawFilter = sandbox.stub().returns()
let basicFilter = sandbox.stub().returns()
let sorting = sandbox.stub().returns()
let performSearch = sandbox.stub().returns(Promise.resolve())
const mockInjector = () => {
Browse = BrowseInjector({
'../../../services/filterFormat': {
formatFromQuickSearch,
formatFromBasicSearch,
formatSort
},
'../../../vuex/modules/common/crudlDocument/getters': {
searchTerm,
rawFilter,
basicFilter,
sorting
},
'../../../vuex/modules/common/crudlDocument/actions': {performSearch},
'../../Materialize/Headline': mockedComponent,
'../../Materialize/collapsible': mockedComponent,
'../Collections/Dropdown': mockedDirective,
'./UserItem': mockedComponent,
'../../Common/CrudlDocument': mockedComponent
})
vm = new Vue({
template: '<div><browse v-ref:browse index="toto" collection="tutu"></browse></div>',
components: {Browse},
replace: false,
store: store
}).$mount()
vm.$refs.browse.$router = {go: sandbox.stub()}
}
afterEach(() => sandbox.restore())
describe('computed tests', () => {
it('displayBulkDelete should return true if there is selected elements', () => {
vm.$refs.browse.selectedDocuments = ['foo']
expect(vm.$refs.browse.displayBulkDelete).to.equals(true)
})
it('allChecked should return true if all documents are selected', () => {
vm.$refs.browse.documents = [{id: 'foo'}, {id: 'bar'}]
vm.$refs.browse.selectedDocuments = ['foo', 'bar']
expect(vm.$refs.browse.allChecked).to.equals(true)
})
})
describe('Methods', () => {
it('isChecked should return true if my document is selected in the list', () => {
vm.$refs.browse.selectedDocuments = ['foo']
expect(vm.$refs.browse.isChecked('foo')).to.equals(true)
})
it('toggleAll should select all document', () => {
vm.$refs.browse.documents = [{id: 'foo'}, {id: 'bar'}]
vm.$refs.browse.toggleAll()
expect(vm.$refs.browse.selectedDocuments).to.deep.equals(['foo', 'bar'])
})
it('toggleAll should unselect all document', () => {
vm.$refs.browse.documents = [{id: 'foo'}, {id: 'bar'}]
vm.$refs.browse.selectedDocuments = vm.$refs.browse.documents
vm.$refs.browse.toggleAll()
expect(vm.$refs.browse.selectedDocuments).to.deep.equals([])
})
it('toggleSelectDocuments should select a document in the list', () => {
vm.$refs.browse.documents = [{id: 'foo'}, {id: 'bar'}]
vm.$refs.browse.toggleSelectDocuments('foo')
expect(vm.$refs.browse.selectedDocuments).to.deep.equals(['foo'])
})
it('toggleSelectDocuments should unselect a document in the list', () => {
vm.$refs.browse.documents = [{id: 'foo'}, {id: 'bar'}]
vm.$refs.browse.selectedDocuments = ['foo']
vm.$refs.browse.toggleSelectDocuments('foo')
expect(vm.$refs.browse.selectedDocuments).to.deep.equals([])
})
describe('fetchData', () => {
it('should do a formatFromQuickSearch', () => {
searchTerm = sandbox.stub().returns({})
basicFilter = sandbox.stub().returns(null)
mockInjector()
vm.$refs.browse.fetchData()
expect(formatFromQuickSearch.called).to.be.equal(true)
})
it('should do a formatFromBasicSearch', () => {
searchTerm = sandbox.stub().returns(null)
basicFilter = sandbox.stub().returns({})
mockInjector()
vm.$refs.browse.fetchData()
expect(formatFromBasicSearch.called).to.be.equal(true)
})
it('should perform a search with rawFilter', () => {
searchTerm = sandbox.stub().returns(null)
basicFilter = sandbox.stub().returns(null)
sorting = sandbox.stub().returns(true)
rawFilter = sandbox.stub().returns({sort: 'foo'})
mockInjector()
vm.$refs.browse.fetchData()
expect(formatSort.called).to.be.equal(true)
})
it('should call perfomSearch and get result from this function', (done) => {
searchTerm = sandbox.stub().returns({})
basicFilter = sandbox.stub().returns(null)
mockInjector()
let performSearch = sandbox.stub(vm.$refs.browse, 'performSearch').returns(Promise.resolve([{toto: 'tata'}]))
vm.$refs.browse.fetchData()
setTimeout(() => {
expect(performSearch.called).to.be.equal(true)
expect(vm.$refs.browse.documents).to.deep.equal([{toto: 'tata'}])
done()
}, 0)
})
})
})
describe('Events', () => {
it('should call toggleAll on event toggle-all', () => {
let toggleAll = sandbox.stub(vm.$refs.browse, 'toggleAll')
vm.$broadcast('toggle-all')
expect(toggleAll.called).to.be.equal(true)
})
it('should call fetchData on event crudl-refresh-search', () => {
let fetchData = sandbox.stub(vm.$refs.browse, 'fetchData')
vm.$refs.browse.$emit('crudl-refresh-search')
expect(fetchData.called).to.be.equal(true)
})
})
describe('Route data', () => {
it('should call fetchData', () => {
Browse.route.fetchData = sandbox.stub().returns({})
Browse.route.data()
expect(Browse.route.fetchData.called).to.be.equal(true)
})
})
})
| JavaScript | 0.000001 | @@ -1642,16 +1642,52 @@
)%7D%0A %7D%0A%0A
+ beforeEach(() =%3E mockInjector())%0A%0A
afterE
|
1020077e9239fc7bb091781996f4feba103a2d33 | Optimize some stuff | commands/playing.js | commands/playing.js | const config = require('../config.js');
const utils = require('../utils.js');
module.exports = {
run: function(message, betaMode) {
if (message.channel.type != 'text') return;
var expression = /^[d]\!(\w+) *(.*)/;
if (betaMode) expression = /^[d][b]\!(\w+) *(.*)/; // Use db!command instead of d!command if in beta mode
var embed = utils.generateDekuDiv(message);
if (message.content.match(expression)[2]) {
var game = message.content.match(expression)[2];
var count = message.guild.members.filter(m => {if(m.user.presence.game){ if(m.user.presence.game.name.toLowerCase() == game.toLowerCase()){return true;}}}).size;
var text = '';
if (count == 0) {
text = "There is **no one** in this guild playing `" + game + "` at the moment";
} else if (count == 1) {
text = "There is **one person** in this guild playing `" + game + "` at the moment";
} else {
text = "There are **" + count + "** people playing `" + game + "` at the moment";
}
embed.addField("Currently playing", text);
} else {
embed.setColor(config.colors.error);
embed.addField('You have to specify the game!', '**Usage:** `d!playing <game>`\n**Example:** `d!playing Overwatch`');
}
message.channel.send({embed});
}
}
| JavaScript | 0.000022 | @@ -118,18 +118,8 @@
sage
-, betaMode
) %7B%0A
@@ -193,136 +193,26 @@
= /%5E
-%5Bd%5D%5C!(%5Cw+) *(.*)/;%0A if (betaMode) expression = /%5E%5Bd%5D%5Bb%5D%5C!(%5Cw+) *(.*)/; // Use db!command instead of d!command if in beta mode
+%5Cw+%5C!(%5Cw+) *(.*)/;
%0A
|
2c9ed08bd7b45f91758fb46e3963b216ab4f9c89 | Remove unused modules | providers/pokeradar.js | providers/pokeradar.js | const _ = require('lodash');
const qs = require('qs');
const request = require('request-promise');
const moment = require('moment');
const errors = require('request-promise/errors');
const Provider = require('./provider.js');
const pokemonNames = require('../pokemon_names.js');
const pokemonStickers = require('../stickers.js');
const getReverseGeocode = require('../get_reverse_geocode.js');
class PokeRadar extends Provider {
constructor(config) {
super(config);
this._deviceId = '';
this._url = 'https://www.pokeradar.io/api/v1/submissions'
this._trustedUserId = '13661365';
this._ttl = 15 * 60;
this._filteredPokemonIds = config.filteredPokemonIds ? config.filteredPokemonIds.sort((a,b) => a-b) : null;
}
init() {
return request
.post('https://www.pokeradar.io/api/v1/users')
.then(function(body) {
const deviceId = JSON.parse(body).data.deviceId;
this._deviceId = deviceId;
return deviceId;
}.bind(this));
}
getPokemons() {
const query = {
deviceId: this._deviceId,
minLatitude: this._config.minLatitude,
maxLatitude: this._config.maxLatitude,
minLongitude: this._config.minLongitude,
maxLongitude: this._config.maxLongitude,
pokemonId: 0
};
const queryString = '?' + qs.stringify(query);
return request(this._url + queryString).then(this._processData.bind(this));
}
_processData(body) {
let pokemons = [];
let entries = JSON.parse(body).data;
let filtered = _.filter(entries, (o) => {
if (this._config.trustedUserId && o.userId != this._config.trustedUserId) {
return false;
}
if (this._filteredPokemonIds && _.sortedIndexOf(this._filteredPokemonIds, o.pokemonId) == -1) {
return false;
}
return true;
});
let processed = filtered.map((entry_) => {
let entry = _.cloneDeep(entry_);
let secs = entry.created + this._ttl - moment().unix();
entry.pokemonName = pokemonNames[entry.pokemonId];
entry.remainingTime = moment.utc(0).seconds(secs);
entry.until = moment().seconds(secs);
entry.direction = 'https://www.google.com/maps/dir/Current+Location/' + entry.latitude + ',' + entry.longitude;
entry.realId = `${entry.pokemonId}-${entry.created}`;
return entry;
});
return processed;
}
}
module.exports = PokeRadar;
| JavaScript | 0.000001 | @@ -275,123 +275,8 @@
s');
-%0Aconst pokemonStickers = require('../stickers.js');%0Aconst getReverseGeocode = require('../get_reverse_geocode.js');
%0A%0Acl
|
7fff3fdf3d2293e4eb2bdc756a97195c6c02d4d3 | Revert api keys. | platform-friends-hybrid/scripts/app/settings.js | platform-friends-hybrid/scripts/app/settings.js | /**
* Application Settings
*/
var appSettings = {
everlive: {
apiKey: 'Y84L0irUx51o4egf', // Put your Backend Services API key here
scheme: 'http'
},
eqatec: {
productKey: '7e5b6a4f3447422899a1cb3529189783', // Put your EQATEC product key here
version: '1.0.0.0' // Put your application version here
},
feedback: {
apiKey: '$APPFEEDBACK_API_KEY$' // Put your AppFeedback API key here
},
facebook: {
appId: '1408629486049918', // Put your Facebook App ID here
redirectUri: 'https://www.facebook.com/connect/login_success.html' // Put your Facebook Redirect URI here
},
google: {
clientId: '406987471724-q1sorfhhcbulk6r5r317l482u9f62ti8.apps.googleusercontent.com', // Put your Google Client ID here
redirectUri: 'http://localhost' // Put your Google Redirect URI here
},
liveId: {
clientId: '000000004C10D1AF', // Put your LiveID Client ID here
redirectUri: 'https://login.live.com/oauth20_desktop.srf' // Put your LiveID Redirect URI here
},
adfs: {
adfsRealm: '$ADFS_REALM$', // Put your ADFS Realm here
adfsEndpoint: '$ADFS_ENDPOINT$' // Put your ADFS Endpoint here
},
messages: {
mistSimulatorAlert: 'The social login doesn\'t work in the In-Browser Client, you need to deploy the app to a device, or run it in the simulator of the Windows Client or Visual Studio.',
removeActivityConfirm: 'This activity will be deleted. This action can not be undone.'
}
};
| JavaScript | 0 | @@ -84,24 +84,26 @@
y: '
-Y84L0irUx51o4egf
+$EVERLIVE_API_KEY$
', /
@@ -213,40 +213,28 @@
y: '
-7e5b6a4f3447422899a1cb3529189783
+$EQATEC_PRODUCT_KEY$
',
|
7787fa4d464d4f9557a47bac8ba90abf11b31a42 | Make sure we run default tests before releasing. | gulpfile.js | gulpfile.js | 'use strict';
var gulp = require('gulp'),
lazypipe = require('lazypipe'),
runSequence = require('run-sequence'),
bump = require('gulp-bump'),
watch = require('gulp-watch'),
karma = require('gulp-karma'),
gls = require('gulp-live-server'),
exit = require('gulp-exit'),
mocha = require('gulp-mocha'),
git = require('gulp-git'),
tagVersion = require('gulp-tag-version'),
jshint = require('gulp-jshint');
function getJSHintPipe(rc) {
return lazypipe()
.pipe(jshint, rc || '.jshintrc')
.pipe(jshint.reporter, 'jshint-stylish')
.pipe(jshint.reporter, 'fail');
}
function jsSourcePipe() {
return gulp.src('src/**/*.js');
}
gulp.task('server:karma', function(cb) {
gls.new('test/spec/server.js').start().then(function(s) {
cb();
}, function(err) {
cb(err);
});
});
function karmaPipe(action) {
return gulp.src('test/spec/**/*.js')
.pipe(karma({
configFile: 'karma.conf.js',
action: action
})).on('error', function(err) {
throw err;
});
}
gulp.task('karma:watch', ['server:karma'], function() {
return karmaPipe('watch');
});
gulp.task('karma', ['server:karma'], function() {
return karmaPipe('run')
.pipe(exit());
});
gulp.task('jshint', ['jshint:src', 'jshint:test', 'jshint:gulpfile']);
gulp.task('jshint:src', function() {
return jsSourcePipe()
.pipe(getJSHintPipe()());
});
gulp.task('jshint:test', function() {
return gulp.src('test/**/*.js')
.pipe(getJSHintPipe('test/.jshintrc')());
});
gulp.task('jshint:gulpfile', function() {
return gulp.src('gulpfile.js')
.pipe(getJSHintPipe()());
});
gulp.task('test:watch', function() {
gulp.watch(['test/*.js', 'src/**/*.js'], ['test']);
});
gulp.task('bump', function() {
return gulp.src('./*.json')
.pipe(bump({ type: gulp.env.type || 'patch' }))
.pipe(gulp.dest('./'));
});
gulp.task('bump-commit', function() {
var version = require('./package.json').version;
return gulp.src(['./*.json'])
.pipe(git.commit('Release v' + version));
});
gulp.task('tag', function() {
return gulp.src('package.json')
.pipe(tagVersion());
});
gulp.task('release', function(cb) {
runSequence(
'bump',
'bump-commit',
'tag',
cb
);
});
gulp.task('default', function() {
return runSequence('jshint', 'karma');
});
| JavaScript | 0 | @@ -2164,16 +2164,31 @@
quence(%0A
+ 'default',%0A
'bum
|
aa0fa6585337f57bf8bd716ba723b9ddd75bac1c | factor out duplicate code, https://github.com/phetsims/scenery-phet/issues/609 | js/ProtractorNode.js | js/ProtractorNode.js | // Copyright 2015-2020, University of Colorado Boulder
/**
* The protractor node is a circular device for measuring angles. In this sim it is used for measuring the angle of the
* incident, reflected and refracted light.
*
* @author Sam Reid (PhET Interactive Simulations)
* @author Chandrashekar Bemagoni (Actual Concepts)
*/
import Property from '../../axon/js/Property.js';
import Shape from '../../kite/js/Shape.js';
import merge from '../../phet-core/js/merge.js';
import sceneryPhet from '../../scenery-phet/js/sceneryPhet.js';
import protractorImage from '../../scenery-phet/mipmaps/protractor_png.js';
import SimpleDragHandler from '../../scenery/js/input/SimpleDragHandler.js';
import Image from '../../scenery/js/nodes/Image.js';
import Node from '../../scenery/js/nodes/Node.js';
import Path from '../../scenery/js/nodes/Path.js';
class ProtractorNode extends Node {
/**
* @param {Property.<boolean>} showProtractorProperty - controls the protractor visibility
* @param {Object} [options]
*/
constructor( showProtractorProperty, options ) {
options = merge( {
rotatable: false,
pointer: 'cursor'
}, options );
super();
showProtractorProperty.linkAttribute( this, 'visible' );
// Image
const protractorImageNode = new Image( protractorImage, { pickable: false } );
this.addChild( protractorImageNode );
// Use nicknames for the protractor image width and height to make the layout code easier to understand
const w = protractorImageNode.getWidth();
const h = protractorImageNode.getHeight();
// Pointer areas
const pointAreaShape = createOuterRingShape( w, h ).rect( w * 0.2, h / 2, w * 0.6, h * 0.15 );
this.mouseArea = pointAreaShape;
this.touchArea = pointAreaShape;
if ( options.rotatable ) {
// @private
this.protractorAngleProperty = new Property( 0.0 );
// Outer ring of the protractor
const outRingPath = new Path( createOuterRingShape( w, h ), {
pickable: true,
cursor: 'pointer'
} );
this.addChild( outRingPath );
// @public (read-only) the horizontal bar that spans the outer ring
this.barPath = new Path( new Shape().rect( w * 0.2, h / 2, w * 0.6, h * 0.15 ) ); //TODO duplicate code
this.addChild( this.barPath );
// Rotate when the outer ring is dragged.
let start;
outRingPath.addInputListener( new SimpleDragHandler( {
start: event => {
start = this.globalToParentPoint( event.pointer.point );
},
drag: event => {
// compute the change in angle based on the new drag event
const end = this.globalToParentPoint( event.pointer.point );
const centerX = this.getCenterX();
const centerY = this.getCenterY();
const startAngle = Math.atan2( centerY - start.y, centerX - start.x );
const angle = Math.atan2( centerY - end.y, centerX - end.x );
// rotate the protractor model
this.protractorAngleProperty.value += angle - startAngle;
start = end;
}
} ) );
// update the protractor angle
this.protractorAngleProperty.link( angle => {
this.rotateAround( this.center, angle - this.getRotation() );
} );
}
this.mutate( options );
}
/**
* @public
*/
reset() {
this.protractorAngleProperty && this.protractorAngleProperty.reset();
}
}
ProtractorNode.protractorImage = protractorImage;
/**
* Creates the outer ring shape of the protractor.
* @param {number} w - width
* @param {number} h - height
* @returns {Shape}
*/
function createOuterRingShape( w, h ) {
return new Shape()
.moveTo( w, h / 2 )
.ellipticalArc( w / 2, h / 2, w / 2, h / 2, 0, 0, Math.PI, true )
.lineTo( w * 0.2, h / 2 )
.ellipticalArc( w / 2, h / 2, w * 0.3, h * 0.3, 0, Math.PI, 0, false )
.lineTo( w, h / 2 )
.ellipticalArc( w / 2, h / 2, w / 2, h / 2, 0, 0, Math.PI, false )
.lineTo( w * 0.2, h / 2 )
.ellipticalArc( w / 2, h / 2, w * 0.3, h * 0.3, 0, Math.PI, 0, true );
}
sceneryPhet.register( 'ProtractorNode', ProtractorNode );
export default ProtractorNode; | JavaScript | 0.997635 | @@ -323,20 +323,62 @@
ncepts)%0A
+ * @author Chris Malley (PixelZoom, Inc.)%0A
*/%0A
-
%0Aimport
@@ -1699,47 +1699,42 @@
h ).
-rect( w * 0.2, h / 2, w * 0.6, h * 0.15
+shapeUnion( createBarShape( w, h )
);%0A
@@ -1966,24 +1966,26 @@
const out
+er
RingPath = n
@@ -2106,24 +2106,26 @@
ddChild( out
+er
RingPath );%0A
@@ -2234,86 +2234,33 @@
th(
-new Shape().rect( w * 0.2, h / 2, w * 0.6, h * 0.15 ) ); //TODO duplicate code
+createBarShape( w, h ) );
%0A
@@ -2368,16 +2368,18 @@
out
+er
RingPath
@@ -3525,16 +3525,44 @@
tractor.
+ Must match protractorImage!
%0A * @par
@@ -4014,32 +4014,32 @@
* 0.2, h / 2 )%0A
-
.ellipticalA
@@ -4100,16 +4100,309 @@
e );%0A%7D%0A%0A
+/**%0A * Creates the horizontal bar shape that spans the center of the protractor. Must match protractorImage!%0A * @param %7Bnumber%7D w - width%0A * @param %7Bnumber%7D h - height%0A * @returns %7BShape%7D%0A */%0Afunction createBarShape( w, h ) %7B%0A return new Shape().rect( w * 0.2, h / 2, w * 0.6, h * 0.15 );%0A%7D%0A%0A
sceneryP
|
a0d5dd92f69566bf16ac331b788ba276ce1b7406 | fix test config | test/config-startup.js | test/config-startup.js | /*
* Copyright 2015 Telefonica Investigación y Desarrollo, S.A.U
*
* This file is part of iotagent-json
*
* iotagent-json is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* iotagent-json is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with iotagent-json.
* If not, seehttp://www.gnu.org/licenses/.
*
* For those usages not covered by the GNU Affero General Public License
* please contact with::[contacto@tid.es]
*/
var config = {};
config.mqtt = {
host: 'localhost',
port: 1883,
thinkingThingsPlugin: true
};
config.amqp = {
port: 5672,
exchange: 'amq.topic',
queue: 'iota_queue',
options: {durable: true}
};
config.iota = {
logLevel: 'FATAL',
contextBroker: {
host: '192.168.1.1',
port: '1026'
},
server: {
port: 4041
},
deviceRegistry: {
type: 'memory'
},
types: {},
service: 'howtoService',
subservice: '/howto',
providerUrl: 'http://localhost:4041',
deviceRegistrationDuration: 'P1M',
defaultType: 'Thing',
defaultResource: '/iot/json'
};
config.defaultKey = '1234';
config.defaultTransport = 'MQTT';
module.exports = config;
| JavaScript | 0.000001 | @@ -1013,24 +1013,51 @@
ig.amqp = %7B%0A
+ host: 'localhost', %0A
port: 56
|
29d064e2310bf7776e56037c5bd97dae1f3d7d05 | write test for project template: export as file | __tests__/template.spec.js | __tests__/template.spec.js | const request = require('request');
require('dotenv').config();
require('babel-polyfill');
// increase timeout for remote response delay
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
import API from './../todoist/Api';
const api = new API(process.env.ACCESS_TOKEN);
test('Manager should export project as url', async () => {
await api.sync();
const project1 = api.projects.add('Project1_template');
const project2 = api.projects.add('Project2_template');
await api.commit();
const item1 = api.items.add('Item1_template', project1.id);
await api.commit();
const template_url = await api.templates.export_as_url(project1.id);
// validates returned object structure and data
expect(template_url).toHaveProperty('file_name', expect.stringMatching(/_Project1_template\.csv$/));
expect(template_url).toHaveProperty('file_url', expect.stringMatching(/(http(s?):)|([\/|.|\w|\s])*_Project1_template\.(?:csv)/));
// tests service by requesting file and checking its content.
const getFile = () => {
return new Promise((resolve, reject) => {
request.get(template_url.file_url, (error, response, body) => {
if (!error && response.statusCode === 200) {
resolve(body);
} else {
reject(error);
}
});
});
};
const fileResponse = await getFile();
expect(fileResponse).toEqual(expect.stringMatching(/task,Item1_template,4,1,/));
item1.delete();
project1.delete();
project2.delete();
await api.commit();
});
| JavaScript | 0.000001 | @@ -257,16 +257,131 @@
OKEN);%0A%0A
+let item1;%0Alet project1;%0A%0AafterAll(async () =%3E %7B%0A item1.delete();%0A project1.delete();%0A await api.commit();%0A%7D);%0A%0A
test('Ma
@@ -411,19 +411,20 @@
ject as
-url
+file
', async
@@ -450,30 +450,24 @@
i.sync();%0A
-const
project1 = a
@@ -510,61 +510,82 @@
;%0A
-const project2 = api.projects.add('Project2_template'
+await api.commit();%0A%0A item1 = api.items.add('Item1_template', project1.id
);%0A
@@ -618,83 +618,302 @@
nst
-i
tem
-1 =
+plate_file = await
api.
-i
tem
-s.add('Item1_template', project1.id);%0A await api.commit();
+plates.export_as_file(project1.id);%0A const fileContent = await template_file.text();%0A%0A expect(fileContent).toEqual(expect.stringMatching(/task,Item1_template,4,1,/));%0A%7D);%0A%0Atest('Manager should export project as url', async () =%3E %7B%0A // requires project1 and item1
%0A%0A
@@ -981,17 +981,16 @@
t1.id);%0A
-%0A
// val
@@ -1753,91 +1753,8 @@
/));
-%0A%0A item1.delete();%0A project1.delete();%0A project2.delete();%0A await api.commit();
%0A%7D);
|
1a5a8540627560127d274ab598625e57082e2336 | Add relative path resolution for browser-sync regex watch | gulpfile.js | gulpfile.js | /**
* Created by Wei-Jye on 7/12/2015.
*/
(function() {
'use strict';
var gulp = require('gulp');
var browserSync = require('browser-sync').create();
var fs = require('fs');
var karma = require('karma');
var Server = require('karma').Server;
function browserSyncTask() {
browserSync.init({
server: {
baseDir: './src',
files: ['index.html', 'app.js', '**/*.html', '**/*.js', '**/*.css'],
port: 8000,
// Not working for some reason....
browser: ['internet explorer', 'google chrome'],
logLevel: 'debug'
}
});
browserSync.reload({
stream: true //
});
gulp.watch('src/index.html', function(event, file) {
browserSync.reload('src/index.html');
});
gulp.watch('src/app.js', function() {
browserSync.reload('src/app.js');
});
//gulp.watch('src/**/*.js').on('change', browserSync.reload);
gulp.watch('src/**/*.js', function(event, file) {
console.log('event:', event);
// TODO: Extract the relative path from event.path and reload only those files.
});
gulp.watch('src/*.css').on('change', browserSync.reload);
}
gulp.task('default', browserSyncTask);
gulp.task('browser-sync', browserSyncTask);
gulp.task('test', function (done) {
new Server({
configFile: __dirname + '/karma.conf.js',
singleRun: true
}, done).start();
});
// Trying out browserify builds + watchify.
//var watchify = require('watchify');
//var browserify = require('browserify');
// TODO: To be continue...
})(); | JavaScript | 0 | @@ -165,18 +165,20 @@
var
-fs
+path
= requi
@@ -185,10 +185,12 @@
re('
-fs
+path
');%0A
@@ -973,78 +973,8 @@
%7D);%0A
- //gulp.watch('src/**/*.js').on('change', browserSync.reload);%0A
@@ -1043,58 +1043,10 @@
-console.log('event:', event);%0A // TODO:
+//
Ext
@@ -1125,75 +1125,216 @@
-%7D);%0A gulp.watch('src/*.css').on('change', browserSync.reload
+ browserSync.reload(path.relative(__dirname, event.path));%0A %7D);%0A gulp.watch('src/*.css', function(event, file)%7B%0A browserSync.reload(path.relative(__dirname, event.path));%0A %7D
);%0A
|
bc27afb557b868eb52c109dbeecca131fbafdceb | Update PlayerCell.js | src/entity/PlayerCell.js | src/entity/PlayerCell.js | var Cell = require('./Cell');
function PlayerCell() {
Cell.apply(this, Array.prototype.slice.call(arguments));
this.cellType = 0;
this.recombineTicks = 0; // Ticks until the cell can recombine with other cells
this.ignoreCollision = false; // This is used by player cells so that they dont cause any problems when splitting
}
module.exports = PlayerCell;
PlayerCell.prototype = new Cell();
// Main Functions
PlayerCell.prototype.visibleCheck = function(box,centerPos) {
// Use old fashioned checking method if cell is small
if (this.mass < 100) {
return this.collisionCheck(box.bottomY,box.topY,box.rightX,box.leftX);
}
// Checks if this cell is visible to the player
var cellSize = this.getSize();
var lenX = cellSize + box.width >> 0; // Width of cell + width of the box (Int)
var lenY = cellSize + box.height >> 0; // Height of cell + height of the box (Int)
return (this.abs(this.position.x - centerPos.x) < lenX) && (this.abs(this.position.y - centerPos.y) < lenY);
};
PlayerCell.prototype.calcMergeTime = function(base) {
this.recombineTicks = base + ((0.02 * this.mass) >> 0); // Int (30 sec + (.02 * mass))
};
// Movement
PlayerCell.prototype.calcMove = function(x2, y2, gameServer) {
var config = gameServer.config;
var r = this.getSize(); // Cell radius
// Get angle
var deltaY = y2 - this.position.y;
var deltaX = x2 - this.position.x;
var angle = Math.atan2(deltaX,deltaY);
if(isNaN(angle)) {
return;
}
// Distance between mouse pointer and cell
var dist = this.getDist(this.position.x,this.position.y,x2,y2);
var speed = Math.min(this.getSpeed(),dist);
var x1 = this.position.x + ( speed * Math.sin(angle) );
var y1 = this.position.y + ( speed * Math.cos(angle) );
// Collision check for other cells
for (var i = 0; i < this.owner.cells.length;i++) {
var cell = this.owner.cells[i];
if ((this.nodeId == cell.nodeId) || (this.ignoreCollision)) {
continue;
}
if ((cell.recombineTicks > 0) || (this.recombineTicks > 0)) {
// Cannot recombine - Collision with your own cells
var collisionDist = cell.getSize() + r; // Minimum distance between the 2 cells
dist = this.getDist(x1,y1,cell.position.x,cell.position.y); // Distance between these two cells
// Calculations
if (dist < collisionDist) { // Collided
// The moving cell pushes the colliding cell
var newDeltaY = y1 - cell.position.y;
var newDeltaX = x1 - cell.position.x;
var newAngle = Math.atan2(newDeltaX,newDeltaY);
var move = collisionDist - dist;
x1 = x1 + ( move * Math.sin(newAngle) ) >> 0;
y1 = y1 + ( move * Math.cos(newAngle) ) >> 0;
}
}
}
gameServer.gameMode.onCellMove(x1,y1,this);
// Check to ensure we're not passing the world border
if (x1 < config.borderLeft) {
x1 = config.borderLeft;
}
if (x1 > config.borderRight) {
x1 = config.borderRight;
}
if (y1 < config.borderTop) {
y1 = config.borderTop;
}
if (y1 > config.borderBottom) {
y1 = config.borderBottom;
}
this.position.x = x1 >> 0;
this.position.y = y1 >> 0;
};
// Override
PlayerCell.prototype.getEatingRange = function() {
return this.getSize() * .4;
};
PlayerCell.prototype.onConsume = function(consumer,gameServer) {
consumer.addMass(this.mass);
};
PlayerCell.prototype.onAdd = function(gameServer) {
// Add to special player node list
gameServer.nodesPlayer.push(this);
// Gamemode actions
gameServer.gameMode.onCellAdd(this);
};
PlayerCell.prototype.onRemove = function(gameServer) {
var index;
// Remove from player cell list
index = this.owner.cells.indexOf(this);
if (index != -1) {
this.owner.cells.splice(index, 1);
}
// Remove from special player controlled node list
index = gameServer.nodesPlayer.indexOf(this);
if (index != -1) {
gameServer.nodesPlayer.splice(index, 1);
}
// Gamemode actions
gameServer.gameMode.onCellRemove(this);
};
PlayerCell.prototype.moveDone = function(gameServer) {
this.ignoreCollision = false;
};
// Lib
PlayerCell.prototype.abs = function(x) {
return x < 0 ? -x : x;
}
PlayerCell.prototype.getDist = function(x1, y1, x2, y2) {
var xs = x2 - x1;
xs = xs * xs;
var ys = y2 - y1;
ys = ys * ys;
return Math.sqrt(xs + ys);
}
| JavaScript | 0.000025 | @@ -216,18 +216,17 @@
er cells
-
%0A
+
this
@@ -1027,24 +1027,298 @@
lenY);%0A%7D;%0A%0A
+PlayerCell.prototype.simpleCollide = function(check,d) %7B%0A // Simple collision check%0A var len = 2 * d %3E%3E 0; // Width of cell + width of the box (Int)%0A%0A return (this.abs(this.position.x - check.x) %3C len) &&%0A (this.abs(this.position.y - check.y) %3C len);%0A%7D;%0A%0A
PlayerCell.p
@@ -1609,21 +1609,17 @@
radius%0A
-
%0A
+
// G
@@ -1748,21 +1748,17 @@
eltaY);%0A
-
%0A
+
if(i
@@ -2656,21 +2656,9 @@
lls%0A
-
%0A
+
@@ -3175,13 +3175,9 @@
%7D%0A
-
%0A
+
@@ -4859,11 +4859,10 @@
+ ys);%0A
+
%7D%0A
-%0A
|
69f4d325122d48e44f996355661efb2c3b311fd3 | remove unneeded style code | era/ui/textbggraphic.js | era/ui/textbggraphic.js |
Ui.CanvasElement.extend('Ui.TextBgGraphic', {
textHasFocus: false,
setHasFocus: function(hasFocus) {
if(this.textHasFocus !== hasFocus) {
this.textHasFocus = hasFocus;
this.invalidateDraw();
}
},
getBackground: function() {
var color;
if(this.textHasFocus)
color = Ui.Color.create(this.getStyleProperty('focusBackground'));
else
color = Ui.Color.create(this.getStyleProperty('background'));
return color;
}
}, {
updateCanvas: function(ctx) {
var w = this.getLayoutWidth();
var h = this.getLayoutHeight();
var radius = this.getStyleProperty('radius');
radius = Math.max(0, Math.min(radius, Math.min(w/2, h/2)));
var borderWidth = this.getStyleProperty('borderWidth');
var lh = Math.max(8, h-4-16);
// handle disable
if(this.getIsDisabled())
ctx.globalAlpha = 0.2;
ctx.fillStyle = this.getBackground().getCssRgba();
ctx.beginPath();
ctx.roundRect(0, 0, w, h, radius, radius, radius, radius);
/*ctx.moveTo(0, h-lh-4);
ctx.lineTo(0, h-4);
ctx.lineTo(w, h-4);
ctx.lineTo(w, h-8-4+borderWidth);
ctx.lineTo(w-borderWidth, h-8-4+borderWidth);
ctx.lineTo(w-borderWidth, h-4-borderWidth);
ctx.lineTo(borderWidth, h-4-borderWidth);
ctx.lineTo(borderWidth, h-lh-4);*/
/*ctx.moveTo(0, h-4);
ctx.lineTo(w, h-4);
ctx.lineTo(w, h-4-borderWidth);
ctx.lineTo(0, h-4-borderWidth);*/
ctx.closePath();
ctx.fill();
},
onDisable: function() {
this.invalidateDraw();
},
onEnable: function() {
this.invalidateDraw();
},
onStyleChange: function() {
this.spacing = Math.max(0, this.getStyleProperty('spacing'));
this.iconSize = Math.max(0, this.getStyleProperty('iconSize'));
this.fontFamily = this.getStyleProperty('fontFamily');
this.fontSize = Math.max(0, this.getStyleProperty('fontSize'));
this.fontWeight = this.getStyleProperty('fontWeight');
this.invalidateDraw();
}
}, {
style: {
radius: 3,
borderWidth: 2,
background: 'rgba(120,120,120,0.2)',
focusBackground: 'rgba(33,211,255,0.4)'
}
}); | JavaScript | 0.000044 | @@ -1534,318 +1534,8 @@
) %7B%0A
-%09%09this.spacing = Math.max(0, this.getStyleProperty('spacing'));%0A%09%09this.iconSize = Math.max(0, this.getStyleProperty('iconSize'));%0A%09%09this.fontFamily = this.getStyleProperty('fontFamily');%0A%09%09this.fontSize = Math.max(0, this.getStyleProperty('fontSize'));%0A%09%09this.fontWeight = this.getStyleProperty('fontWeight');%0A
%09%09th
|
3773735fa07c39db8a10484c5fac989e7136ab5d | use node-style callbacks and fix undefined logic | lib/devices/ios/ios-hybrid.js | lib/devices/ios/ios-hybrid.js | "use strict";
var logger = require('../../server/logger.js').get('appium')
, _ = require('underscore')
, deviceCommon = require('../common.js')
, rd = require('./remote-debugger.js')
, wkrd = require('./webkit-remote-debugger.js');
var iOSHybrid = {};
iOSHybrid.closeAlertBeforeTest = function (cb) {
this.proxy("au.alertIsPresent()", function (err, res) {
if (!err && res !== null && typeof res.value !== "undefined" && res.value === true) {
logger.debug("Alert present before starting test, let's banish it");
this.proxy("au.dismissAlert()", function () {
logger.debug("Alert banished!");
cb(true);
});
} else {
cb(false);
}
}.bind(this));
};
iOSHybrid.listWebFrames = function (cb, exitCb) {
var isDone = false;
if (!this.args.bundleId) {
logger.error("Can't enter web frame without a bundle ID");
return cb(new Error("Tried to enter web frame without a bundle ID"));
}
var onDone = function (res) {
this.processingRemoteCmd = false;
isDone = true;
if (Array.isArray(res) && res.length === 0) {
// we have no web frames, so disconnect from the remote debugger
this.stopRemote();
}
cb(null, res);
}.bind(this);
this.processingRemoteCmd = true;
if (this.remote !== null && this.args.bundleId !== null) {
if (this.args.udid !== null) {
this.remote.pageArrayFromJson(cb);
} else {
this.remote.selectApp(this.args.bundleId, onDone);
}
} else {
if (this.args.udid !== null) {
this.remote = wkrd.init(exitCb);
this.remote.pageArrayFromJson(cb);
} else {
this.remote = rd.init(exitCb);
this.remote.connect(function (appDict) {
if (!_.has(appDict, this.args.bundleId)) {
logger.error("Remote debugger did not list " + this.args.bundleId +
" among its available apps");
if (_.has(appDict, "com.apple.mobilesafari")) {
logger.debug("Using mobile safari instead");
this.remote.selectApp("com.apple.mobilesafari", onDone);
} else {
onDone([]);
}
} else {
this.remote.selectApp(this.args.bundleId, onDone);
}
}.bind(this), this.onPageChange.bind(this));
var loopCloseRuns = 0;
var loopClose = function () {
loopCloseRuns++;
if (!isDone && loopCloseRuns < 3) {
this.closeAlertBeforeTest(function (didDismiss) {
if (!didDismiss) {
setTimeout(loopClose, 1000);
}
});
}
}.bind(this);
setTimeout(loopClose, 4000);
}
}
};
iOSHybrid.onPageChange = function (pageArray) {
logger.debug("Remote debugger notified us of a new page listing");
if (this.selectingNewPage) {
logger.debug("We're in the middle of selecting a page, ignoring");
return;
}
var newIds = []
, keyId = null;
_.each(pageArray, function (page) {
newIds.push(page.id.toString());
if (page.isKey) {
keyId = page.id.toString();
}
});
var newPages = [];
_.each(newIds, function (id) {
if (!_.contains(this.contexts, id)) {
newPages.push(id);
this.contexts.push(id);
}
}.bind(this));
var newPage = null;
if (this.curContext === null) {
logger.debug("We don't appear to have window set yet, ignoring");
} else if (newPages.length) {
logger.debug("We have new pages, going to select page " + newPages[0]);
newPage = newPages[0];
} else if (!_.contains(newIds, this.curContext.toString())) {
logger.debug("New page listing from remote debugger doesn't contain " +
"current window, let's assume it's closed");
if (keyId !== null) {
logger.debug("Debugger already selected page " + keyId + ", " +
"confirming that choice.");
} else {
logger.error("Don't have our current window anymore, and there " +
"aren't any more to load! Doing nothing...");
}
this.curContext = keyId;
this.remote.pageIdKey = parseInt(keyId, 10);
} else {
var dirty = function () {
var item = function (arr) {
return _.filter(arr, function (obj) {
return obj.id === this.curContext;
}, this)[0];
}.bind(this);
return !_.isEqual(item(this.contexts), item(pageArray));
}.bind(this);
// If a window gets navigated to an anchor it doesn't always fire a page callback event
// Let's check if we wound up in such a situation.
if (dirty()) {
this.remote.pageLoad();
}
logger.debug("New page listing is same as old, doing nothing");
}
if (newPage !== null) {
this.selectingNewPage = true;
this.remote.selectPage(parseInt(newPage, 10), function () {
this.selectingNewPage = false;
this.curContext = newPage;
if (this.onPageChangeCb !== null) {
this.onPageChangeCb();
this.onPageChangeCb = null;
}
}.bind(this));
} else if (this.onPageChangeCb !== null) {
this.onPageChangeCb();
this.onPageChangeCb = null;
}
this.windowHandleCache = _.map(pageArray, this.massagePage);
};
iOSHybrid.getAtomsElement = deviceCommon.getAtomsElement;
iOSHybrid.stopRemote = function (closeWindowBeforeDisconnecting) {
if (typeof closeWindowBeforeDisconnecting === "undefined") {
closeWindowBeforeDisconnecting = false;
}
if (!this.remote) {
logger.error("We don't appear to be in a web frame");
throw new Error("Tried to leave a web frame but weren't in one");
} else {
var disconnect = function () {
if (this.args.udid) {
this.remote.disconnect(function () {});
} else {
this.remote.disconnect();
}
this.curContext = null;
this.curWebFrames = [];
this.curWebCoords = null;
this.remote = null;
}.bind(this);
if (closeWindowBeforeDisconnecting) {
this.closeWindow(disconnect);
} else {
disconnect();
}
}
};
module.exports = iOSHybrid;
| JavaScript | 0.000001 | @@ -405,22 +405,16 @@
peof res
-.value
!== %22un
@@ -626,16 +626,22 @@
cb(
+null,
true);%0A
@@ -671,16 +671,22 @@
cb(
+null,
false);%0A
@@ -2442,16 +2442,21 @@
nction (
+err,
didDismi
|
2b0ed940c4eb6f2bb79a9485e023bc2961b5f956 | Add the "retries" flag into Mocha command (#14616) | script/run-unit-test.js | script/run-unit-test.js | const printUnitTestHelp = require('./run-unit-test-help.js');
const commandLineArgs = require('command-line-args');
const { runCommand } = require('./utils');
// For usage instructions see https://github.com/department-of-veterans-affairs/vets-website#unit-tests
const defaultPath = './src/**/*.unit.spec.js?(x)';
const COMMAND_LINE_OPTIONS_DEFINITIONS = [
{ name: 'log-level', type: String, defaultValue: 'log' },
{ name: 'app-folder', type: String, defaultValue: null },
{ name: 'coverage', type: Boolean, defaultValue: false },
{ name: 'reporter', type: String, defaultValue: null },
{ name: 'help', alias: 'h', type: Boolean, defaultValue: false },
{
name: 'path',
type: String,
defaultOption: true,
multiple: true,
defaultValue: [defaultPath],
},
];
const options = commandLineArgs(COMMAND_LINE_OPTIONS_DEFINITIONS);
let coverageInclude = '';
if (
options['app-folder'] &&
options.path[0] === defaultPath &&
options.path.length === 1
) {
options.path[0] = options.path[0].replace(
'/src/',
`/src/applications/${options['app-folder']}/`,
);
coverageInclude = `--include 'src/applications/${options['app-folder']}/**'`;
}
const reporterOption = options.reporter ? `--reporter ${options.reporter}` : '';
if (options.help) {
printUnitTestHelp();
process.exit(0);
}
const mochaPath = `BABEL_ENV=test mocha ${reporterOption}`;
const coveragePath = `NODE_ENV=test nyc --all ${coverageInclude} --reporter=lcov --reporter=text --reporter=json-summary mocha --reporter mocha-junit-reporter --no-color`;
const testRunner = options.coverage ? coveragePath : mochaPath;
const mochaOpts =
'src/platform/testing/unit/mocha.opts src/platform/testing/unit/helper.js';
runCommand(
`LOG_LEVEL=${options[
'log-level'
].toLowerCase()} ${testRunner} --max-old-space-size=4096 --opts ${mochaOpts} --recursive ${options.path
.map(p => `'${p}'`)
.join(' ')}`,
);
| JavaScript | 0.000011 | @@ -1554,16 +1554,28 @@
no-color
+ --retries 3
%60;%0Aconst
|
f55fa00d15f3403bbac0a115fb0d566c85f77b1e | Stringify regular expressions | src/DependencyParser.js | src/DependencyParser.js |
var fs = require('fs');
var angular = require('angular');
var inject = angular.injector(['ng']).invoke;
var NGObjectDetails = require('./NGObjectDetails');
// is there a better way to get $q?
var $q;
inject(function (_$q_) {
$q = _$q_;
});
var dependencyParser = {
/**
* Extracts information about the angular objects within a file.
* @param path
* @returns {NGObjectDetails[]}
*/
parseFile: function(path) {
var deferred = $q.defer();
fs.readFile(path, 'utf8', function (err, data) {
if (err) {
return console.log(err);
}
// now that we have the codes
var details = dependencyParser.parseCode(data);
deferred.resolve(details);
});
return deferred.promise;
},
/**
*
* @param {String} code
* @returns {NGObjectDetails[]}
*/
parseCode: function(code) {
var myRe = new RegExp(
/module\(['|"]([^)]+)['|"]\)\.(factory|service|controller)\(['|"]([^'"]+)['|"],\s*function\(([^)]*)\)/g
);
var matches;
var parsedObjects = [];
while ((matches = myRe.exec(code)) !== null)
{
// console.log(matches);
var deps = matches[4].split(', ');
var o = new NGObjectDetails(
matches[1],
matches[2],
matches[3],
deps
);
console.log(o)
parsedObjects.push(o);
}
return parsedObjects;
}
};
module.exports = dependencyParser;
| JavaScript | 1 | @@ -805,46 +805,113 @@
) %7B%0A
+%0A
%09%09
-var myRe = new RegExp(%0A%09%09%09/
+// TODO: include module parsing%0A%09%09// parse out component declarations%0A%09%09var parseModule = '
module%5C
+%5C
(%5B
+%5C
'%7C%22%5D
@@ -922,14 +922,36 @@
%5D+)%5B
+%5C
'%7C%22%5D%5C
-)
+%5C)',%0A%09%09%09parseType = '%5C
%5C.(f
@@ -981,28 +981,79 @@
er)%5C
-(%5B
+%5C(',%0A%09%09%09parseName = '%5B%5C
'%7C%22%5D(%5B%5E
+%5C
'%22%5D+)%5B
+%5C
'%7C%22%5D
-,
+',%0A%09%09%09parseDependencies = ',%5C
%5Cs*f
@@ -1060,16 +1060,17 @@
unction%5C
+%5C
((%5B%5E)%5D*)
@@ -1074,11 +1074,109 @@
%5D*)%5C
-)/g
+%5C)';%0A%09%09var objectsRegex = new RegExp(%0A%09%09%09parseModule + parseType + parseName + parseDependencies, 'g'
%0A%09%09)
@@ -1242,12 +1242,20 @@
s =
-myRe
+objectsRegex
.exe
@@ -1277,22 +1277,21 @@
ll)%0A%09%09%7B%0A
+//
%09%09%09
-//
console.
@@ -1304,16 +1304,17 @@
tches);%0A
+%0A
%09%09%09var d
|
048b05066bec85e3893e07f93ca82e6431acb0d7 | Use real nia data and no unique plugin | plugins/portal-highlighter-uniques-opacity.user.js | plugins/portal-highlighter-uniques-opacity.user.js | // ==UserScript==
// @id iitc-plugin-portal-highlighter-uniques-opacity@xificurk
// @name IITC plugin: Highlight unique visits/captures using opacity
// @category Highlighter
// @version 0.1.1.@@DATETIMEVERSION@@
// @namespace https://github.com/xificurk/iitc-plugins
// @updateURL @@UPDATEURL@@
// @downloadURL @@DOWNLOADURL@@
// @description [@@BUILDNAME@@-@@BUILDDATE@@] Use stroke and fill opacity to denote player's unique visits and captures. Requires uniques plugin.
// @include https://intel.ingress.com/*
// @include http://intel.ingress.com/*
// @match https://intel.ingress.com/*
// @match http://intel.ingress.com/*
// @include https://*.ingress.com/intel*
// @include http://*.ingress.com/intel*
// @match https://*.ingress.com/intel*
// @match http://*.ingress.com/intel*
// @include https://*.ingress.com/mission/*
// @include http://*.ingress.com/mission/*
// @match https://*.ingress.com/mission/*
// @match http://*.ingress.com/mission/*
// @grant none
// ==/UserScript==
@@PLUGINSTART@@
//PLUGIN START ////////////////////////////////////////////////////////
//use own namespace for plugin
window.plugin.portalHighlighterUniquesOpacity = function () {};
window.plugin.portalHighlighterUniquesOpacity.highlighter = {
highlight: function(data) {
var guid = data.portal.options.ent[0];
var uniqueInfo = window.plugin.uniques.uniques[guid];
var style = {};
if(uniqueInfo) {
if(uniqueInfo.captured) {
// captured (and, implied, visited too) - hide
style.fillOpacity = 0;
style.opacity = 0.25;
} else if(uniqueInfo.visited) {
style.fillOpacity = 0.2;
style.opacity = 1;
}
} else {
// no visit data at all
style.fillOpacity = 0.8;
style.opacity = 1;
}
data.portal.setStyle(style);
},
setSelected: function(active) {
window.plugin.uniques.isHighlightActive = active;
}
}
var setup = function() {
if(window.plugin.uniques === undefined) {
alert("'Portal Highlighter Uniques Opacity' requires 'uniques'");
return;
}
window.addPortalHighlighter('Uniques (opacity)', window.plugin.portalHighlighterUniquesOpacity.highlighter);
}
//PLUGIN END //////////////////////////////////////////////////////////
@@PLUGINEND@@
| JavaScript | 0 | @@ -1427,20 +1427,26 @@
var
-guid
+portalData
= data.
@@ -1468,69 +1468,215 @@
ent%5B
-0%5D;%0A var uniqueInfo = window.plugin.uniques.uniques%5Bguid%5D;
+2%5D%0A%0A if (portalData%5B18%5D) %7B%0A var visited = ((portalData%5B18%5D & 0b1) === 1)%0A var captured = ((portalData%5B18%5D & 0b10) === 2)%0A%0A var uniqueInfo = %7B%0A captured,%0A visited%0A %7D%0A %7D
%0A%0A
@@ -2116,262 +2116,37 @@
%0A %7D
-,%0A%0A setSelected: function(active) %7B%0A window.plugin.uniques.isHighlightActive = active;%0A %7D%0A%7D%0A%0A%0Avar setup = function() %7B%0A if(window.plugin.uniques === undefined) %7B%0A alert(%22'Portal Highlighter Uniques Opacity' requires 'uniques'%22);%0A return;%0A %7D%0A
+%0A%7D%0A%0A%0Avar setup = function() %7B
%0A w
|
4141d95cf77c88c7dbed5070e05550e5c69e8546 | Add comment | vertex_coloring/javascript/vertex_coloring.js | vertex_coloring/javascript/vertex_coloring.js | import {AdjacencyList} from './adjacency_list.js';
// getVertexColoring returns the vertex coloring of the graph, with colors are represented as
// positive integers.
export function getVertexColoring(graph) {
const list = new AdjacencyList(graph);
// coloring[x] is the color of the vertex x.
const coloring = new Array(graph.vertexCount).fill(-1);
// neighboringColorsSets[x] is the set of colors adjacent to x.
// Caching these sets allows this algorithm to run in O(n²) time.
const neighboringColors = Array.from({length: graph.vertexCount}, () => new Set());
while (true) {
// At each iteration, Brélaz's heuristic selects the uncolored vertex with highest color
// degree.
const x = getUncoloredVertexWithHighestColorDegree(list, coloring, neighboringColors);
if (x < 0) {
// All vertices are colored. Done!
return coloring;
}
// Color x.
const color = lowestAvailableColor(neighboringColors[x]);
coloring[x] = color;
list.a[x].forEach(y => neighboringColors[y].add(color));
}
}
// getUncoloredVertexWithHighestColorDegree returns the uncolored vertex adjacent to the most
// different colors, or -1 if no uncolored vertex can be found.
function getUncoloredVertexWithHighestColorDegree(list, coloring, neighboringColors) {
return list.a.reduce((best, edges, x) => {
if (coloring[x] >= 0) {
// x is colored and not eligible.
return best;
}
if (best < 0) {
return x;
}
return neighboringColors[x].size > neighboringColors[best].size ? x : best;
}, -1);
}
//
function lowestAvailableColor(colors) {
let i = 0;
while (colors.has(i)) {
i++;
}
return i;
}
| JavaScript | 0 | @@ -1678,16 +1678,85 @@
);%0A%7D%0A%0A//
+ lowestAvailableColor returns the lowest color not present in colors.
%0Afunctio
|
405432952368c90f707bc6cf753311bca1c043bc | Fix broken test in IE11. | test/mouse-events.js | test/mouse-events.js | /* global describe, it, simulateEvent, sinon, expect */
describe('Mouse Events', function () {
var fixture = document.createElement('div');
describe('click', function () {
it('should trigger', function () {
var spy = sinon.spy();
fixture.addEventListener('click', spy);
simulateEvent(fixture, 'click');
expect(spy).to.have.been.calledOnce;
});
});
describe('mousedown', function () {
it('should trigger', function () {
var spy = sinon.spy();
fixture.addEventListener('mousedown', spy);
simulateEvent(fixture, 'mousedown');
expect(spy).to.have.been.calledOnce;
});
});
describe('mouseup', function () {
it('should trigger', function () {
var spy = sinon.spy();
fixture.addEventListener('mouseup', spy);
simulateEvent(fixture, 'mouseup');
expect(spy).to.have.been.calledOnce;
});
});
describe('mouseenter', function () {
it('should trigger', function () {
var spy = sinon.spy();
fixture.addEventListener('mouseenter', spy);
simulateEvent(fixture, 'mouseenter');
expect(spy).to.have.been.calledOnce;
});
});
describe('mouseleave', function () {
it('should trigger', function () {
var spy = sinon.spy();
fixture.addEventListener('mouseleave', spy);
simulateEvent(fixture, 'mouseleave');
expect(spy).to.have.been.calledOnce;
});
});
describe('mouseover', function () {
it('should trigger', function () {
var spy = sinon.spy();
fixture.addEventListener('mouseover', spy);
simulateEvent(fixture, 'mouseover');
expect(spy).to.have.been.calledOnce;
});
});
describe('mousemove', function () {
it('should trigger', function () {
var spy = sinon.spy();
fixture.addEventListener('mousemove', spy);
simulateEvent(fixture, 'mousemove');
expect(spy).to.have.been.calledOnce;
});
});
describe('mouseout', function () {
it('should trigger', function () {
var spy = sinon.spy();
fixture.addEventListener('mouseout', spy);
simulateEvent(fixture, 'mouseout');
expect(spy).to.have.been.calledOnce;
});
});
describe('contextmenu', function () {
it('should trigger', function () {
var spy = sinon.spy();
fixture.addEventListener('contextmenu', spy);
simulateEvent(fixture, 'contextmenu');
expect(spy).to.have.been.calledOnce;
});
});
});
| JavaScript | 0.000003 | @@ -135,16 +135,54 @@
('div');
+%0A document.body.appendChild(fixture);
%0A%0A desc
|
2b997bb2a09a5fc99f35f569a7713373a673b72d | Make View configurable regarding element type. | src/view.js | src/view.js | "use strict";
var util = require("substance-util");
// Substance.View
// ==========================================================================
//
// Application View abstraction, inspired by Backbone.js
var View = function() {
var that = this;
// Either use the provided element or make up a new element
this.$el = $('<div/>');
this.el = this.$el[0];
this.dispatchDOMEvents();
};
View.Prototype = function() {
// Shorthand for selecting elements within the view
// ----------
//
this.$ = function(selector) {
return this.$el.find(selector);
};
this.render = function() {
return this;
};
// Dispatching DOM events (like clicks)
// ----------
//
this.dispatchDOMEvents = function() {
var that = this;
// showReport(foo) => ["showReport(foo)", "showReport", "foo"]
// showReport(12) => ["showReport(12)", "showReport", "12"]
function extractFunctionCall(str) {
var match = /(\w+)\((.*)\)/.exec(str);
if (!match) throw new Error("Invalid click handler '"+str+"'");
return {
"method": match[1],
"args": match[2].split(',')
};
}
this.$el.delegate('[sbs-click]', 'click', function(e) {
// Matches things like this
// showReport(foo) => ["showReport(foo)", "showReport", "foo"]
// showReport(12) => ["showReport(12)", "showReport", "12"]
var fnCall = extractFunctionCall($(e.currentTarget).attr('sbs-click'));
// Event bubbles up if there is no handler
var method = that[fnCall.method];
if (method) {
method.apply(that, fnCall.args);
return false;
}
});
};
};
View.Prototype.prototype = util.Events;
View.prototype = new View.Prototype();
module.exports = View;
| JavaScript | 0 | @@ -224,19 +224,53 @@
unction(
-) %7B
+options) %7B%0A options = options %7C%7C %7B%7D;
%0A var t
@@ -281,17 +281,16 @@
= this;%0A
-%0A
// Eit
@@ -354,23 +354,84 @@
his.
-$
el =
-$('%3C
+options.el %7C%7C window.document.createElement(options.elementType %7C%7C '
div
-/%3E
');%0A
@@ -441,24 +441,24 @@
his.
+$
el =
+$(
this.
-$
el
-%5B0%5D
+)
;%0A%0A
|
653f7455e3d0599da39bcbd19cea7888bf74c19f | Revert "start extracting options" | js/app/lib/browse.js | js/app/lib/browse.js | var $ = require('jquery'),
_ = require('underscore'),
Facility = require('cloud/models/facility'),
parse;
if ( typeof Parse == 'undefined' ) {
// can't require parse from within parse cloud. seems silly.
parse = require('parse');
} else {
parse = Parse;
}
var DEFAULT_OPTIONS = {
sort: 'name',
limit: 10,
filter: {},
offset: 0
};
var Browse = function(params, callbacks) {
// all params are optional, NULL or missing means don't filter
// {
// sort: 'near'|'name'
// limit: int (default 10)
// filter:
// {isOpen: true,
// gender: 'M'|'F'
// age: ['C', 'Y', 'A', 'S'] // children, youth, adult, senior
// categories: ['medical', 'hygiene', 'food', 'shelter']
// }
// }
//
//
var filter = params.filter || {};
var options = $.extend({}, params, DEFAULT_OPTIONS),
query = new parse.Query(Facility);
console.log(options);
console.log(options.filter);
if ( options.sort === 'near' ) {
if ( !(options.lat && options.lon) ) {
return callbacks.error("Please provide a lat and lon");
}
var geopoint = new parse.GeoPoint(params.lat, params.lon);
query.near('location', geopoint);
} else {
query.ascending('name');
}
// query.limit(limit);
query.include('services');
query.skip(options.offset);
var resp = [];
console.log(query.filter);
query.find().then(function(results) {
var filteredResults = [];
_.each(results, function(result) {
if ( filteredResults.length >= options.limit )
return;
if ( result.matchesFilter(filter) ) {
filteredResults.push(result);
}
options.offset++;
console.log(options.offset);
});
callbacks.success({offset: options.offset, data: filteredResults});
}, function(err) {
callbacks.error(err);
});
};
module.exports = Browse;
| JavaScript | 0 | @@ -1,12 +1,62 @@
+module.exports = function (params, callbacks) %7B%0A
var $ = requ
@@ -74,16 +74,18 @@
'),%0A
+
_ = requ
@@ -99,24 +99,26 @@
derscore'),%0A
+
Facility
@@ -162,299 +162,17 @@
+
parse;%0A
-%0Aif ( typeof Parse == 'undefined' ) %7B%0A // can't require parse from within parse cloud. seems silly.%0A parse = require('parse');%0A%7D else %7B%0A parse = Parse;%0A%7D%0A%0Avar DEFAULT_OPTIONS = %7B%0A sort: 'name',%0A limit: 10,%0A filter: %7B%7D,%0A offset: 0%0A%7D;%0A%0Avar Browse = function(params, callbacks) %7B
%0A /
@@ -529,205 +529,188 @@
var
-filter = params.filter %7C%7C %7B%7D;%0A var options = $.extend(%7B%7D, params, DEFAULT_OPTIONS),%0A query = new parse.Query(Facility);%0A%0A console.log(options);%0A console.log(options.filter);%0A if ( options.
+sort = params.sort %7C%7C 'name';%0A var limit = params.limit %7C%7C 10;%0A var filter = params.filter %7C%7C %7B%7D;%0A var offset = params.offset %7C%7C 0;%0A var q = new parse.Query(Facility);%0A%0A if (
sort
@@ -736,22 +736,21 @@
if ( !(
-option
+param
s.lat &&
@@ -750,22 +750,21 @@
.lat &&
-option
+param
s.lon) )
@@ -903,20 +903,16 @@
);%0A q
-uery
.near('l
@@ -948,20 +948,16 @@
%7B%0A q
-uery
.ascendi
@@ -979,20 +979,16 @@
%0A%0A // q
-uery
.limit(l
@@ -997,20 +997,16 @@
it);%0A q
-uery
.include
@@ -1026,26 +1026,14 @@
%0A q
-uery
.skip(
-options.
offs
@@ -1062,42 +1062,9 @@
%0A%0A
-console.log(query.filter);%0A query
+q
.fin
@@ -1152,22 +1152,17 @@
unction(
-result
+f
) %7B%0A
@@ -1198,23 +1198,16 @@
%3E=
-options.
limit )
+
%0A
@@ -1231,22 +1231,17 @@
if (
-result
+f
.matches
@@ -1288,22 +1288,17 @@
ts.push(
-result
+f
);%0A
@@ -1306,24 +1306,16 @@
%7D%0A
-options.
offset++
@@ -1320,43 +1320,8 @@
++;%0A
- console.log(options.offset);%0A
@@ -1359,16 +1359,8 @@
et:
-options.
offs
@@ -1449,29 +1449,4 @@
%7D;%0A%0A
-module.exports = Browse;%0A
|
18fa3dc9e28fc97a39d70e6418e0d1f00acccb35 | add browser policy, remove newb packages | lib/init.js | lib/init.js | // Meteor Generate
// Copyright(c) 2014 Adam Brodzinski <adambrodzinski@gmail.com>
// MIT Licensed
/*global templatePath */
var fs = require('fs-extra'),
router = require('./router.js');
module.exports = {
initSource: templatePath + 'init/',
// Public: Copy the boilerplate in the templates init folder to
// the user's root project folder. Creates a router and client
// folder. The project name is used for removing original boilerplate.
//
// Examples:
// require('./init').init('myProjectName');
//
// projectName - the {String} name of the user's meteor project
//
init: function(projectName) {
var self = this;
this.projectName = projectName;
this.projDir = './' + projectName + '/';
this._runCommand('meteor create ' + projectName, function() {
router.create(self.projDir);
self._copyTemplate();
self._removeOriginalMeteorFiles(projectName);
// append package into meteor/packages to allow an mrt install
fs.appendFileSync(self.projDir + '.meteor/packages', 'iron-router');
console.log('\n-------------------------------------------');
console.log(' type cd %s to navigate to project', projectName);
console.log(' then run `mrt update` to install Iron Router');
console.log('-------------------------------------------\n');
});
},
// Private: Copy the boilerplate from templates directory and place it
// in the user's project root directory. Remove .gitkeep when done
//
_copyTemplate: function() {
fs.copySync(this.initSource, this.projDir);
fs.removeSync(this.projDir + 'client/.gitkeep');
fs.removeSync(this.projDir + 'server/.gitkeep');
console.log(' Created: .jshintrc');
console.log(' Created: .jshintignore');
console.log(' Created: smart.json');
console.log(' Created: makefile');
},
// Private: Removes the original foo.html, foo.js, and foo.css files
// that Meteor creates after a `meteor create foo` command
//
_removeOriginalMeteorFiles: function() {
// example: remove "./mybook/mybook.js"
fs.removeSync(this.projDir + this.projectName + '.js');
fs.removeSync(this.projDir + this.projectName + '.html');
fs.removeSync(this.projDir + this.projectName + '.css');
console.log(' Removed: original boilerplate');
},
// Private: Run a command on the command line.
//
// command - the {String} command to run
// callback - a {Function} to call when complete
//
_runCommand: function(command, callback) {
var exec = require('child_process').exec;
exec(command, function (err) {
if (err) console.log('exec error: ' + err);
callback.call(this);
});
}
};
| JavaScript | 0 | @@ -729,16 +729,71 @@
e + '/';
+%0A this.packages = this.projDir + '.meteor/packages';
%0A%0A th
@@ -972,149 +972,513 @@
e);%0A
+%0A
-// append p
+self._removePackage('insecure');%0A self._removePackage('autopublish');%0A puts(%22Updating Packages%22);%0A puts(%22 Removed P
ackage
+:
in
-to meteor/packages to allow an mrt install%0A fs.appendFileSync(self.projDir + '.meteor/packages', 'iron-router'
+secure%22);%0A puts(%22 Removed Package: autopublish%22);%0A%0A // add packages to .meteor/packages file%0A fs.appendFileSync(self.projDir + '.meteor/packages', 'iron-router%5Cn');%0A fs.appendFileSync(self.projDir + '.meteor/packages', 'browser-policy%5Cn');%0A puts(%22 Added Package: iron-router%22);%0A puts(%22 Added Package: browser-policy%22
);%0A%0A
@@ -3121,16 +3121,479 @@
%7D);%0A
+ %7D,%0A%0A // Private: Look at packages file and remove package if present. Stream%0A // packages file, replace, then overwrite original file. %0A //%0A // packageName - The %7BString%7D name of the package%0A //%0A _removePackage: function(packageName) %7B%0A var oldPackages, newPackages;%0A%0A oldPackages = fs.readFileSync(this.packages, %7Bencoding: 'utf-8'%7D);%0A newPackages = oldPackages.replace(packageName + '%5Cn', '');%0A fs.writeFileSync(this.packages, newPackages);%0A
%7D%0A%0A%7D;%0A
|
5f9d43c0ec322ce906246d028326183a7b5d25bf | Modify services.js to alina's firebase url | app/js/services.js | app/js/services.js | 'use strict';
/* Services */
angular.module('myApp.services', [])
.value('FIREBASE_URL', 'https://waitandeat-demo.firebaseio.com/')
.factory('dataService', function($firebase, FIREBASE_URL) {
var dataRef = new Firebase(FIREBASE_URL);
var fireData = $firebase(dataRef);
return fireData;
})
.factory('partyService', function(dataService) {
var users = dataService.$child('users');
var partyServiceObject = {
saveParty: function(party, userId) {
users.$child(userId).$child('parties').$add(party);
},
getPartiesByUserId: function(userId) {
return users.$child(userId).$child('parties');
}
};
return partyServiceObject;
})
.factory('textMessageService', function(dataService, partyService) {
var textMessages = dataService.$child('textMessages');
var textMessageServiceObject = {
sendTextMessage: function(party, userId) {
var newTextMessage = {
phoneNumber: party.phone,
size: party.size,
name: party.name
};
textMessages.$add(newTextMessage);
partyService.getPartiesByUserId(userId).$child(party.$id).$update({notified: 'Yes'});
}
};
return textMessageServiceObject;
})
.factory('authService', function($firebaseSimpleLogin, $location, $rootScope, FIREBASE_URL, dataService) {
var authRef = new Firebase(FIREBASE_URL);
var auth = $firebaseSimpleLogin(authRef);
var emails = dataService.$child('emails');
var authServiceObject = {
register: function(user) {
auth.$createUser(user.email, user.password).then(function(data) {
console.log(data);
authServiceObject.login(user, function() {
emails.$add({email: user.email});
});
});
},
login: function(user, optionalCallback) {
auth.$login('password', user).then(function(data) {
console.log(data);
if (optionalCallback) {
optionalCallback();
}
$location.path('/waitlist');
});
},
logout: function() {
auth.$logout();
$location.path('/');
},
getCurrentUser: function() {
return auth.$getCurrentUser();
}
};
$rootScope.$on('$firebaseSimpleLogin:login', function(e, user) {
$rootScope.currentUser = user;
});
$rootScope.$on('$firebaseSimpleLogin:logout', function() {
$rootScope.currentUser = null;
});
return authServiceObject;
});
| JavaScript | 0 | @@ -110,12 +110,13 @@
eat-
-demo
+alina
.fir
|
41ed6dacb1b892b7a403f599eb86b2685c004a29 | Fix error with #_jqueryRemove | src/view.js | src/view.js | Minionette.View = Backbone.View.extend({
constructor: function() {
Backbone.View.apply(this, arguments);
// Done so we don't bindAll to standard methods.
_.bindAll(this, '_jqueryRemove', '_remove');
// Keep track of our subviews.
this._subViews = {};
// Have the view listenTo the model and collection.
this._listenToEvents(this.model, this.modelEvents);
this._listenToEvents(this.collection, this.collectionEvents);
},
// A default template that will clear this.$el.
// Override this in a subclass to something useful.
template: function() { return ''; },
// When delegating events, bind this view to jQuery's special remove event.
// Allows us to clean up the view, even if you remove this.$el with jQuery.
// http://blog.alexmaccaw.com/jswebapps-memory-management
delegateEvents: function() {
Backbone.View.prototype.delegateEvents.apply(this, arguments);
this.$el.on('remove.delegateEvents' + this.cid, this._jqueryRemove);
},
// A useful remove method to that triggers events.
remove: function() {
this.trigger('remove:before');
this._removeSubViews();
Backbone.View.prototype.remove.apply(this, arguments);
this.trigger('remove');
},
// A remove helper to clear our subviews.
_removeSubViews: function() {
_.invoke(this._subViews, 'remove');
},
// Assign a subview to an element in my template.
// `selector` is a dom selector to assign to.
// `view` is the subview to assign the selector to.
// `replace` is a boolean.
// `False` (default), set view's $el to the selector.
// `True`, replace the selector with view's $el.
// Alternate syntax by passing in an object for selector.
// With "selector": subview
// Replace will be the second param in this case.
assign : function (selector, view, replace) {
var selectors;
if (_.isObject(selector)) {
selectors = selector;
replace = view;
} else {
selectors = {};
selectors[selector] = view;
}
if (!selectors) { return; }
_.each(selectors, function (view, selector) {
this._subViews[view.cid] = view;
if (replace) {
this.$(selector).replaceWith(view.el);
} else {
view.setElement(this.$(selector)).render();
}
}, this);
},
// A proxy method to this.remove().
// This is bindAll-ed to the view instance.
// Done so that we don't need to bindAll to remove().
_jqueryRemove: function() {
this.remove();
},
// Loop through the events given, and listen to
// entity's event.
_listenToEvents: function(entity, events) {
for (var event in events) {
var method = events[event];
if (!_.isFunction(method)) { method = this[method]; }
if (!method) { continue; }
this.listenTo(entity, event, method);
}
return this;
}
});
| JavaScript | 0.000001 | @@ -115,119 +115,8 @@
);%0A%0A
- // Done so we don't bindAll to standard methods.%0A _.bindAll(this, '_jqueryRemove', '_remove');%0A%0A
@@ -845,32 +845,75 @@
his, arguments);
+%0A%0A _.bindAll(this, '_jqueryRemove');
%0A this.$e
@@ -2446,25 +2446,30 @@
//
-A proxy
+Does the sa
me
+
th
-od to
+ing as
thi
@@ -2482,114 +2482,130 @@
ve()
-.%0A // This is bindAll-ed to the view instance.%0A // Done so that we don't need to bindAll to
+, without%0A // actually removing the element. Done to prevent%0A // us from removing an element that is already
remove
-()
+d
.%0A
@@ -2647,22 +2647,68 @@
this.
-remove
+trigger('remove:jquery');%0A this.stopListening
();%0A
|
73a58ddcb1b89418c539b82fd7e43ddd266934fe | update GroupBanner map zoom | agir/groups/components/groupPage/GroupBanner.js | agir/groups/components/groupPage/GroupBanner.js | import PropTypes from "prop-types";
import React, { useMemo } from "react";
import styled from "styled-components";
import style from "@agir/front/genericComponents/_variables.scss";
import { getGroupTypeWithLocation } from "./utils";
import Map from "@agir/carte/common/Map";
const StyledMap = styled.div``;
const StyledBanner = styled.div`
display: flex;
flex-flow: row-reverse nowrap;
background-color: ${style.secondary500};
margin: 0 auto;
@media (max-width: ${style.collapse}px) {
max-width: 100%;
flex-flow: column nowrap;
background-color: white;
}
header {
flex: 1 1 auto;
padding: 2.25rem;
@media (max-width: ${style.collapse}px) {
padding: 1.5rem 1.5rem 1.25rem;
}
}
h2,
h4 {
margin: 0;
&::first-letter {
text-transform: uppercase;
}
}
h2 {
font-weight: 700;
font-size: 1.75rem;
line-height: 1.419;
margin-bottom: 0.5rem;
@media (max-width: ${style.collapse}px) {
font-size: 1.25rem;
line-height: 1.519;
}
}
h4 {
font-size: 1rem;
font-weight: 500;
line-height: 1.5;
@media (max-width: ${style.collapse}px) {
font-size: 0.875rem;
}
}
${StyledMap} {
flex: 0 0 424px;
clip-path: polygon(100% 0%, 100% 100%, 0% 100%, 11% 0%);
@media (max-width: ${style.collapse}px) {
clip-path: none;
width: 100%;
flex-basis: 155px;
}
}
`;
const GroupBanner = (props) => {
const { name, type, location, commune, iconConfiguration } = props;
const subtitle = useMemo(
() => getGroupTypeWithLocation(type, location, commune),
[type, location, commune]
);
return (
<StyledBanner>
{location.coordinates &&
Array.isArray(location.coordinates.coordinates) ? (
<StyledMap>
<Map
center={location.coordinates.coordinates}
iconConfiguration={iconConfiguration}
isStatic
/>
</StyledMap>
) : null}
<header>
<h2>{name}</h2>
<h4>{subtitle}</h4>
</header>
</StyledBanner>
);
};
GroupBanner.propTypes = {
name: PropTypes.string.isRequired,
type: PropTypes.string.isRequired,
iconConfiguration: PropTypes.object,
location: PropTypes.shape({
city: PropTypes.string,
zip: PropTypes.string,
coordinates: PropTypes.shape({
coordinates: PropTypes.arrayOf(PropTypes.number),
}),
}).isRequired,
commune: PropTypes.shape({
nameOf: PropTypes.string,
}),
};
export default GroupBanner;
| JavaScript | 0 | @@ -1803,16 +1803,38 @@
%3CMap%0A
+ zoom=%7B11%7D%0A
|
563ce02d7a30b342176aad43a474031c5a0bcc78 | 修正表单选择日期后必须点击表单才能显示,否则不显示。 | lib/form/edit/DateEdit.ios.js | lib/form/edit/DateEdit.ios.js | /**
* Created by kevin on 15/11/26.
*/
'use strict';
import React from 'react';
import t from 'tcomb-form-native';
import moment from 'moment';
import stylesheet from '../stylesheets/flat'
import templates from '../templates/flat'
import {
StyleSheet,
View,
Modal,
DatePickerIOS,
Image,
TouchableOpacity,
TouchableWithoutFeedback,
Text
} from 'react-native';
let Form = t.form.Form;
Form.templates = templates;
Form.stylesheet = stylesheet;
export default class extends t.form.Component {
constructor(props: any) {
super(props);
this.state = {
show: false,
date: this.props.value,
};
this.renderPopup = this.renderPopup.bind(this);
this.done = this.done.bind(this);
}
done(){
if (this.onChange){
this.onChange(this.state.date);
}
this.setState({show: false})
}
renderPopup() {
let date = new Date(this.state.date);
return (
<Modal
visible={this.state.show}
transparent={true}
animationType="slide">
<View style={styles.modalBackgroundStyle}>
<TouchableWithoutFeedback onPress={()=>this.setState({show: false})}>
<View style={{flex: 1}}></View>
</TouchableWithoutFeedback>
<View style={styles.container}>
<View style = {styles.toolbar}>
<TouchableOpacity style = {styles.button} onPress = {()=>this.setState({show: false})}>
<Image source={require('../../images/cancel.png')} style={styles.buttonIcon}/>
</TouchableOpacity>
<View style={styles.title}>
<Text style={styles.titleText}>{this.props.title || '选择日期'}</Text>
</View>
<TouchableOpacity style = {styles.button} onPress = {this.done}>
<Image source={require('../../images/return.png')} style={styles.buttonIcon}/>
</TouchableOpacity>
</View>
<DatePickerIOS
style={styles.picker}
date={date}
onDateChange={(v)=>this.setState({date: (moment(v).format('YYYY-MM-DD'))})}
mode={this.props.mode || 'date'}/>
</View>
</View>
</Modal>
)
}
shouldComponentUpdate(nextProps, nextState) {
var should = (
nextState.value !== this.state.value ||
nextState.date !== this.state.date ||
nextState.hasError !== this.state.hasError ||
nextProps.options !== this.props.options ||
nextProps.type !== this.props.type ||
nextState.show !== this.state.show
);
return should;
}
getLocals() {
let locals = super.getLocals();
locals.help = this.props.options['help'];
return locals;
}
render() {
let locals = this.getLocals();
var stylesheet = locals.stylesheet;
var formGroupStyle = stylesheet.formGroup.normal;
var controlLabelStyle = stylesheet.controlLabel.normal;
var textboxStyle = stylesheet.textbox.normal;
var helpBlockStyle = stylesheet.helpBlock.normal;
var errorBlockStyle = stylesheet.errorBlock;
if (locals.hasError) {
formGroupStyle = stylesheet.formGroup.error;
controlLabelStyle = stylesheet.controlLabel.error;
textboxStyle = stylesheet.textbox.error;
helpBlockStyle = stylesheet.helpBlock.error;
}
var label = locals.label ? <Text style={controlLabelStyle}>{locals.label}</Text> : null;
var help = locals.help ? <Text style={helpBlockStyle}>{locals.help}</Text> : null;
var error = locals.hasError && locals.error ? <Text style={errorBlockStyle}>{locals.error}</Text> : null;
return (
<View style={formGroupStyle}>
<View style={{flexDirection: 'row', justifyContent: 'center', alignItems: 'center'}}>
{label}
<TouchableOpacity
style={{flex: 1, justifyContent: 'center', alignItems: 'flex-end'}}
onPress={() => {
this.setState({
date: this.props.value || moment().format("YYYY-MM-DD"),
show: true})
}}>
<Text style={[textboxStyle, {height: 22}]}>{this.props.value}</Text>
</TouchableOpacity>
</View>
{help}
{error}
{this.renderPopup()}
</View>
);
}
}
const styles = StyleSheet.create({
modalBackgroundStyle: {
flex: 1,
backgroundColor: 'rgba(0, 0, 0, 0.2)',
justifyContent: 'flex-end'
},
container: {
backgroundColor: '#ffffff',
},
toolbar: {
flexDirection: 'row',
paddingHorizontal: 5,
alignItems: 'center',
height: 44,
borderBottomWidth: 1,
borderBottomColor: "#e8e8e8",
},
title: {
flex: 1,
alignItems: 'center',
},
titleText: {
fontSize: 20,
color: '#303030'
},
button: {
padding: 6,
},
buttonIcon: {
},
picker: {alignSelf: 'center'}
});
| JavaScript | 0 | @@ -4096,26 +4096,25 @@
%7D%3E%7Bthis.
-props.valu
+state.dat
e%7D%3C/Text
|
9415404a2582628d12272370f2cff03a75de2c8f | Initialize PanelView on init | lib/init.js | lib/init.js | /** @babel */
/* global atom */
import { CompositeDisposable } from 'atom'
import { run } from 'node-jq'
// import BottomPanel from './views/BottomPanel'
const log = (...args) => {
console.log(...args)
}
export default {
activate (state) {
this.subscriptions = new CompositeDisposable()
this.subscriptions.add(
atom.commands.add('atom-workspace', {
'atom-jq:toggle': () => this.togglePackage()
})
)
},
togglePackage () {
console.log('ATOM-JQ TOGGLED')
// const textEditor = atom.workspace.getActiveTextEditor()
// textEditor.getText()
const activePane = atom.workspace.getActivePaneItem()
const activeFile = activePane.buffer.file
const activeFilePath = activeFile.path
console.log('activeFile', activeFile)
console.log('filePath', activeFilePath)
run('.', activeFilePath)
.then(log)
.catch(log)
},
deactivate () {
console.log('ATOM-JQ PLUGIN UN-LOADED')
this.subscriptions.dispose()
}
}
const isPathJson = (filepath) => {
return /\.json$/.test(filepath)
}
| JavaScript | 0 | @@ -103,29 +103,24 @@
jq'%0A
-//
import
-Bottom
Panel
+View
fro
@@ -134,19 +134,17 @@
ews/
-Bottom
Panel
+View
'%0A%0Ac
@@ -212,17 +212,16 @@
fault %7B%0A
-%0A
activa
@@ -229,24 +229,45 @@
e (state) %7B%0A
+ console.clear()%0A%0A
this.sub
@@ -301,24 +301,122 @@
isposable()%0A
+%0A this.panelView = new PanelView(%7B%0A highlight: false%0A %7D)%0A this.panelView.content()%0A%0A
this.sub
@@ -574,43 +574,8 @@
) %7B%0A
- console.log('ATOM-JQ TOGGLED')%0A
@@ -661,16 +661,17 @@
tText()%0A
+%0A
cons
@@ -905,17 +905,20 @@
run('
-.
+keys
', activ
@@ -940,19 +940,47 @@
.then(
-log
+(a) =%3E %7B%0A log(a)%0A %7D
)%0A
@@ -1023,156 +1023,40 @@
-console.log('ATOM-JQ PLUGIN UN-LOADED')%0A this.subscriptions.dispose()%0A %7D%0A%0A%7D%0A%0Aconst isPathJson = (filepath) =%3E %7B%0A return /%5C.json$/.test(filepath)
+this.subscriptions.dispose()%0A %7D%0A
%0A%7D%0A
|
75304256f294f154bc3de2e27ebd0ff600a2614d | remove unused square dom attribute "data-key" | src/view.js | src/view.js | var util = require('./util');
var board = require('./board');
var drag = require('./drag');
var anim = require('./anim');
function renderPiece(ctrl, key, p) {
var attrs = {
class: ['cg-piece', p.role, p.color].join(' ')
};
if (ctrl.board.draggable.current.orig === key) {
attrs.style = {
webkitTransform: util.translate(ctrl.board.draggable.current.pos)
};
attrs.class = attrs.class + ' dragging';
}
else if (ctrl.board.animation.current.anims) {
var animation = ctrl.board.animation.current.anims[key];
if (animation) {
attrs.style = {
webkitTransform: util.translate(animation[1])
};
}
}
return {
tag: 'div',
attrs: attrs
};
}
function renderSquare(ctrl, pos) {
var styleX = (pos[0] - 1) * 12.5 + '%';
var styleY = (pos[1] - 1) * 12.5 + '%';
var file = util.files[pos[0] - 1];
var rank = pos[1];
var key = file + rank;
var piece = ctrl.board.pieces.get(key);
var attrs = {
class: key + ' cg-square ' + util.classSet({
'selected': ctrl.board.selected === key,
'check': ctrl.board.check === key,
'last-move': util.contains2(ctrl.board.lastMove, key),
'move-dest': util.containsX(ctrl.board.movable.dests[ctrl.board.selected], key),
'premove-dest': util.containsX(ctrl.board.premovable.dests, key),
'current-premove': util.contains2(ctrl.board.premovable.current, key),
'drag-over': ctrl.board.draggable.current.over === key
}),
style: ctrl.board.orientation === 'white' ? {
left: styleX,
bottom: styleY
} : {
right: styleX,
top: styleY
},
'data-key': key
};
if (pos[1] === (ctrl.board.orientation === 'white' ? 1 : 8)) attrs['data-coord-x'] = file;
if (pos[0] === (ctrl.board.orientation === 'white' ? 8 : 1)) attrs['data-coord-y'] = rank;
return {
tag: 'div',
attrs: attrs,
children: piece ? renderPiece(ctrl, key, piece) : null
};
}
module.exports = function(ctrl) {
return m('div.cg-board', {
config: function(el, isInit, context) {
if (isInit) ctrl.board.size = el.clientWidth;
},
onclick: function(e) {
var key = e.target.getAttribute('data-key') || e.target.parentNode.getAttribute('data-key');
ctrl.selectSquare(key);
},
onmousedown: drag.start.bind(ctrl.board)
},
util.allPos.map(function(pos) {
return renderSquare(ctrl, pos);
})
);
}
| JavaScript | 0 | @@ -1614,29 +1614,8 @@
%7D
-,%0A 'data-key': key
%0A %7D
|
3e77ade9c10b8ff75a46735c7f6a008886b72dac | fix - reload CSS styles w/o restarting the browser | gulpfile.js | gulpfile.js | var path = require('path');
var gulp = require('gulp');
var clean = require("gulp-clean");
var runSequence = require('run-sequence');
var ts = require('gulp-typescript');
var util = require('gulp-util');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var watchify = require('watchify');
var express = require('express');
var livereload = require('gulp-livereload');
var templateCache = require('gulp-angular-templatecache');
var minifyHTML = require('gulp-minify-html');
var livereloadInjector = require('connect-livereload');
var concat = require('gulp-concat');
var boilerPlateName = 'stencil';
var compiledJsTemplateFilename = 'templates.js';
var stencilJsFilename = boilerPlateName + '.js';
var compiledStencilJsFilename = 'compiled.' + stencilJsFilename;
var compiledStencilCssFilename = 'compiled.' + boilerPlateName + '.css';
var appIndexHtmlFilename = 'index.html';
var paths = {
ts: 'app/**/*.ts',
build: './build/app',
dist: './dist',
html: 'app/' + appIndexHtmlFilename,
templates: [
'app/**/*.html',
'!app/assets/**/*.html'
],
css: [
'app/assets/**/*.css'
],
fonts: [
'app/assets/**/*.eot',
'app/assets/**/*.svg',
'app/assets/**/*.ttf',
'app/assets/**/*.woff'
],
assets: [
'app/assets/**/*.*'
],
image: [
'app/assets/**/*.png',
'app/assets/**/*.jpg',
'app/assets/**/*.gif'
]
};
function browserifier() {
return browserify(paths.build + '/' + stencilJsFilename, {
fullPaths: false,
cache: {},
packageCache: {},
debug: true
});
}
function reload(event) {
setTimeout(function() {
livereload.changed();
util.log('[reloaded] ' + path.basename(event.path));
}, 2000);
}
gulp.task('compile-typescript', function() {
return gulp.src(paths.ts)
.pipe(ts({
module: 'commonjs'
}))
.pipe(gulp.dest(paths.build));
});
gulp.task('clean', function() {
return gulp.src([paths.build, paths.dist], {read: false})
.pipe(clean());
});
gulp.task('copy-html', function() {
return gulp.src(paths.html)
.pipe(concat(appIndexHtmlFilename))
.pipe(gulp.dest(paths.build));
});
gulp.task('copy-assets', function() {
return gulp.src(paths.assets)
.pipe(gulp.dest(path.join(paths.build, '/assets')));
});
gulp.task('copy-css', function() {
return gulp.src(paths.css)
.pipe(concat(compiledStencilCssFilename))
.pipe(gulp.dest(paths.build));
});
gulp.task('browserify', function(){
return browserifier()
.bundle()
.pipe(source(compiledStencilJsFilename))
.pipe(gulp.dest(paths.build));
});
gulp.task('watchify', function() {
var browseritor = watchify(
browserifier()
);
browseritor.on('update', rebundle);
function rebundle() {
return browseritor.bundle()
.on('error', util.log.bind(util, 'Browserify Error'))
.pipe(source(compiledStencilJsFilename))
.pipe(gulp.dest(paths.build));
}
return rebundle();
});
gulp.task('compile-templates', function() {
return gulp.src(paths.templates)
.pipe(minifyHTML())
.pipe(templateCache(
compiledJsTemplateFilename, {
module: 'Templates',
moduleSystem: 'Browserify',
standalone: true
}))
.pipe(gulp.dest(paths.build));
});
gulp.task('watches', function() {
gulp.watch(paths.html, ['copy-html']);
gulp.watch(paths.css, ['copy-css']);
gulp.watch(paths.ts, ['compile-typescript']);
gulp.watch(paths.templates, ['compile-templates']);
// post-build watcher(s)
gulp.watch([
path.join(paths.build, compiledStencilCssFilename),
path.join(paths.build, compiledStencilJsFilename),
path.join(paths.build, appIndexHtmlFilename)
], {
debounceDelay: 1000
})
.on('change', function(event) {
reload(event);
});
});
gulp.task('start-livereload', function(){
livereload.listen();
});
gulp.task('start-server', function() {
var server = express();
server.use(livereloadInjector());
server.use(express.static(paths.build));
server.listen(3000);
});
gulp.task('copy-images', function(){
return gulp.src(paths.image)
.pipe(gulp.dest(paths.build + '/img'));
});
gulp.task('copy-builds-to-dist', function(){
gulp.src([
path.join(paths.build, appIndexHtmlFilename),
path.join(paths.build, compiledStencilCssFilename),
path.join(paths.build, compiledStencilJsFilename)
])
.pipe(gulp.dest(paths.dist));
gulp.src([paths.build + '/img/**/*'])
.pipe(gulp.dest(paths.dist + '/img'));
});
gulp.task('dev', function() {
runSequence(
'clean',
'copy-assets',
'copy-html',
'copy-css',
'copy-images',
'compile-typescript',
'compile-templates',
'watchify',
'start-livereload',
'start-server',
'watches'
);
});
gulp.task('deploy', function() {
runSequence(
'clean',
'copy-assets',
'copy-html',
'copy-css',
'copy-images',
'compile-typescript',
'compile-templates',
'browserify',
'copy-builds-to-dist'
);
});
gulp.task('default', ['dev']); | JavaScript | 0 | @@ -1134,31 +1134,24 @@
'app/
-assets/
**/*.css'%0A
@@ -2559,32 +2559,60 @@
st(paths.build))
+%0A .pipe(livereload())
;%0A%7D);%0A%0Agulp.task
@@ -3776,68 +3776,8 @@
h(%5B%0A
- path.join(paths.build, compiledStencilCssFilename),%0A
|
7f69184c9c7854bcc70f7c873e7d057512cc4465 | Add custom font icon. | src/common/icon/index.js | src/common/icon/index.js | const builder = require('focus-core').component.builder;
const React = require('react');
const types = require('focus-core').component.types;
const oneOf = React.PropTypes.oneOf;
const iconMixin = {
displayName: 'Icon',
getDefaultProps() {
return {
name: '',
library: 'material'
};
},
propTypes: {
handleOnClick: types('function'),
name: types('string'),
library: oneOf(['material', 'font-awesome', 'focus'])
},
/**
* Render the img.
* @returns {XML} Html code.
*/
render: function renderIcon(){
const {name, library, onClick, style} = this.props;
switch (library) {
case 'material':
return <i className='material-icons' onClick={onClick} {...style}>{name}</i>;
case 'font-awesome':
const faCss = `fa fa-${name}`;
return <i className={faCss} onClick={onClick} {...style}></i>;
default:
return null;
}
}
};
module.exports = builder(iconMixin);
| JavaScript | 0 | @@ -476,19 +476,25 @@
me', 'fo
-cus
+nt-custom
'%5D)%0A
@@ -967,24 +967,121 @@
tyle%7D%3E%3C/i%3E;%0A
+ case 'font-custom':%0A return %3Cspan className=%7B%60icon-$%7Bname%7D%60%7D%3E%3C/span%3E;%0A
|
711ccc3c0f67d4e27d3dfc7d285599a56814b2d6 | Refactor to ternary if | src/LocalizedStrings.js | src/LocalizedStrings.js | 'use strict';
import React from 'react';
/**
* Simple module to localize the React interface using the same syntax
* used in the ReactNativeLocalization module
* (https://github.com/stefalda/ReactNativeLocalization)
*
* Originally developed by Stefano Falda (stefano.falda@gmail.com)
*
* It uses a call to the Navigator/Browser object to get the current interface language,
* then display the correct language strings or the default language (the first
* one if a match is not found).
*
* How to use:
* Check the instructions at:
* https://github.com/stefalda/react-localization
*/
const placeholderRegex = /(\{\d+\})/;
const isReactComponent = value => typeof value.$$typeof === 'symbol';
const DEFAULT_VALUE = 'en-US';
let reservedNames = [ '_interfaceLanguage',
'_language',
'_defaultLanguage',
'_defaultLanguageFirstLevelKeys',
'_props' ];
export default class LocalizedStrings {
_getInterfaceLanguage() {
let lang = null;
if (typeof navigator !== 'undefined' && navigator.languages && typeof navigator.languages !== 'undefined' && navigator.languages[0] && typeof navigator.languages[0] !== 'undefined') {
lang = navigator.languages[0];
} else if (typeof navigator !== 'undefined' && navigator.language && typeof navigator.language !== 'undefined') {
lang = navigator.language;
} else if (typeof navigator !== 'undefined' && navigator.userLanguage && typeof navigator.userLanguage !== 'undefined') {
lang = navigator.userLanguage;
} else if (typeof navigator !== 'undefined' && navigator.browserLanguage && typeof navigator.browserLanguage !== 'undefined') {
lang = navigator.browserLanguage;
}
return lang || DEFAULT_VALUE;
}
_getBestMatchingLanguage(language, props) {
//If an object with the passed language key exists return it
if (props[language]) return language;
//if the string is composed try to find a match with only the first language identifiers (en-US --> en)
const idx = language.indexOf('-');
const auxLang = (idx >= 0) ? language.substring(0, idx) : language;
return props[auxLang] ? auxLang : Object.keys(props)[0];
}
constructor(props) {
this._interfaceLanguage = this._getInterfaceLanguage();
this._language = this._interfaceLanguage;
this.setContent(props);
}
setContent(props){
this._defaultLanguage = Object.keys(props)[0];
this._defaultLanguageFirstLevelKeys = [];
//Store locally the passed strings
this._props = props;
//Check for use of reserved words
this._validateProps(props[this._defaultLanguage]);
//Store first level keys (for identifying missing translations)
for (var key in this._props[this._defaultLanguage]) {
if (typeof this._props[this._defaultLanguage][key]=="string") {
this._defaultLanguageFirstLevelKeys.push(key);
}
}
//Set language to its default value (the interface)
this.setLanguage(this._interfaceLanguage);
}
_validateProps(props) {
Object.keys(props).map(key => {
if (reservedNames.indexOf(key)>=0) throw new Error(`${key} cannot be used as a key. It is a reserved word.`)
})
}
//Can be used from ouside the class to force a particular language
//indipendently from the interface one
setLanguage(language) {
//Check if exists a translation for the current language or if the default
//should be used
var bestLanguage = this._getBestMatchingLanguage(language, this._props);
var defaultLanguage = Object.keys(this._props)[0];
this._language = bestLanguage;
//Associate the language object to the this object
if (this._props[bestLanguage]) {
//delete default propery values to identify missing translations
for (key of this._defaultLanguageFirstLevelKeys){
delete this[key];
}
var localizedStrings = Object.assign({}, this._props[this._language]);
for (var key in localizedStrings) {
if (localizedStrings.hasOwnProperty(key)) {
this[key] = localizedStrings[key];
}
}
//Now add any string missing from the translation but existing in the default language
if (defaultLanguage !== this._language) {
localizedStrings = this._props[defaultLanguage];
this._fallbackValues(localizedStrings, this);
}
}
}
//Load fallback values for missing translations
_fallbackValues(defaultStrings, strings) {
for (var key in defaultStrings) {
if (defaultStrings.hasOwnProperty(key) && !strings[key]) {
strings[key] = defaultStrings[key];
console.log(`🚧 👷 key '${key}' not found in localizedStrings for language ${this._language} 🚧`);
} else {
if (typeof strings[key] != "string") {
//It's an object
this._fallbackValues(defaultStrings[key], strings[key]);
}
}
}
}
//The current language displayed (could differ from the interface language
// if it has been forced manually and a matching translation has been found)
getLanguage() {
return this._language;
}
//The current interface language (could differ from the language displayed)
getInterfaceLanguage() {
return this._interfaceLanguage;
}
//Return an array containing the available languages passed as props in the constructor
getAvailableLanguages() {
if (!this._availableLanguages) {
this._availableLanguages = [];
for (let language in this._props) {
this._availableLanguages.push(language);
}
}
return this._availableLanguages;
}
//Format the passed string replacing the numbered placeholders
//i.e. I'd like some {0} and {1}, or just {0}
//Use example:
// strings.formatString(strings.question, strings.bread, strings.butter)
formatString(str, ...values) {
return str
.split(placeholderRegex)
.map((textPart, index) => {
if (textPart.match(placeholderRegex)) {
const valueForPlaceholder = values[parseInt(textPart.slice(1, -1))];
if (isReactComponent(valueForPlaceholder)) {
return React.Children.toArray(valueForPlaceholder)
.map(component => ({...component, key: index}));
}
return valueForPlaceholder;
}
return textPart;
});
}
//Return a string with the passed key in a different language
getString(key, language) {
try {
return this._props[language][key];
} catch (ex) {
console.log("No localization found for key " + key + " and language " + language);
}
return null;
}
//Replace all occurrences of a string in another using RegExp
_replaceAll(find, replace, str) {
//Escape find
find = find.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
return str.replace(new RegExp(find, 'g'), replace);
}
} | JavaScript | 0.998453 | @@ -6610,20 +6610,23 @@
-if (
+return
isReactC
@@ -6654,19 +6654,16 @@
eholder)
-) %7B
%0A
@@ -6679,22 +6679,17 @@
-return
+?
React.C
@@ -6728,37 +6728,8 @@
der)
-%0A
.map
@@ -6771,17 +6771,16 @@
index%7D))
-;
%0A
@@ -6795,37 +6795,14 @@
- %7D%0A
- return
+:
val
|
67b6a34c54bfeb390d80f205ad010d6d31b107be | Fix Firefox drag-drop of files do not trigger on-change | app/directives/file.js | app/directives/file.js | define(['app', 'angular', 'text!./file.html'], function(app, ng, fileDropTemplate) { 'use strict';
app.directive('type', ['$http', function($http) {
return {
restrict: 'A',
replace: true,
require: '?ngModel',
scope: {
onUpload : "&onUpload"
},
link: function($scope, element, attr, ctrl) {
if(element.prop("tagName")!=="INPUT") return;
if(attr.type !=="file") return;
if(!ctrl) return;
$scope.$on('$destroy', function(){
element.off('change');
});
element.on('change', function() {
var htmlFiles = element[0].files;
if(isAutoUpload())
{
var files = [];
for(var i=0; i<htmlFiles.length; ++i) {
var formData = new FormData();
var htmlFile = htmlFiles[i];
formData.append("file", htmlFile);
var qs = {};
if(attr.encrypt!==undefined)
qs.encrypt = "true";
$http.post('/api/v2015/temporary-files', formData, {
params: qs,
transformRequest: ng.identity,
headers: {'Content-Type': undefined}
}).then(function(res){
files = files.concat([res.data]);
setViewValue(files);
onUpload(htmlFile, res.data, null);
return res.data;
}).catch(function(err){
err = err.data || err;
files = files.concat([{ error: err }]);
setViewValue(files);
onUpload(htmlFile, null, err);
res.data;
});
}
}
else {
setViewValue(htmlFiles);
}
if(isAutoReset())
reset();
});
function isMutiple() {
return element.attr('multiple')!==undefined;
}
function isAutoUpload() {
return attr.onUpload!==undefined;
}
function onUpload(htmlFile, file, err) {
return $scope.onUpload({
htmlFile: htmlFile,
file: file,
error: err
});
}
function isAutoReset() {
return $scope.$eval(attr.autoReset) || isAutoUpload();
}
function reset() {
$scope.$applyAsync(function() { element.val(''); });
}
function setViewValue(files){
ctrl.$setViewValue(isMutiple() ? files : files[0]);
}
}
};
}]);
app.directive('fileDrop', ['$compile', function($compile) {
return {
restrict: 'E',
replace: true,
template: fileDropTemplate,
require: 'ngModel',
scope: {
autoReset: '<autoReset',
caption: '@caption',
onUpload : "&onUpload",
danger : "=?"
},
link: function($scope, form, attr, ngModelCtrl) {
var inputFile = ng.element('<span><input class="hidden" ng-disabled="isDisabled()" type="file" auto-reset="autoReset" ng-model="files" ng-change="proxyOnChange()" data-multiple-caption="{count} files selected" /><span>').find('input:file');
if(attr.multiple!==undefined) inputFile.attr('multiple', '');
if(attr.accept !==undefined) inputFile.attr('accept', attr.accept);
if(attr.encrypt !==undefined) inputFile.attr('encrypt', "");
if(attr.onUpload!==undefined) inputFile.attr('on-upload', "proxyOnUpload({ htmlFile: htmlFile, file: file, error: error})");
inputFile = $compile(inputFile.parent().html())($scope);
form.find('label').append(inputFile);
//////////////////////
$scope.isMutiple = isMutiple;
$scope.isDisabled = isDisabled;
$scope.proxyOnUpload = $scope.onUpload;
$scope.proxyOnChange = function() { ngModelCtrl.$setViewValue($scope.files); };
var div = document.createElement('div');
$scope.allowDragDrop = (('draggable' in div) || ('ondragstart' in div && 'ondrop' in div)) && 'FormData' in window && 'FileReader' in window;
if ($scope.allowDragDrop) {
form.on('drop', onFileDrop);
form.on('dragover dragenter', function( ) { $scope.$apply(function() { $scope.dragOver = true; }); });
form.on('dragleave dragend drop', function( ) { $scope.$apply(function() { $scope.dragOver = false; }); });
form.on('drag dragstart dragend dragover dragenter dragleave drop', function(e) {
e.preventDefault(); // preventing the unwanted behaviours
e.stopPropagation();
});
$scope.$on('$destroy', function(){
form.off('drag dragstart dragend dragover dragenter dragleave drop');
});
}
function isMutiple() {
return inputFile.attr('multiple')!==undefined;
}
function isDisabled() {
return form.attr('disabled')!==undefined;
}
function onFileDrop(e) {
e.preventDefault();
inputFile[0].files = e.originalEvent.dataTransfer.files;
}
}
};
}]);
});
| JavaScript | 0.000001 | @@ -722,24 +722,63 @@
nction() %7B%0A%0A
+ increaseChange();%0A%0A
@@ -3450,32 +3450,182 @@
%7D
+%0A%0A function increaseChange() %7B%0A element.data('changeCount', (element.data('changeCount')%7C%7C0) + 1);%0A %7D
%0A%09 %7D%0A%09
@@ -6588,104 +6588,625 @@
-e.preventDefault();%0A%0A inputFile%5B0%5D.files = e.originalEvent.dataTransfer.files
+var oldChangeCount, newChangeCount;%0A%0A var value = e.originalEvent.dataTransfer.files;%0A%0A e.preventDefault();%0A%0A oldChangeCount = fileChangeCount();%0A%0A inputFile%5B0%5D.files = value;%0A%0A newChangeCount = fileChangeCount();%0A%0A if(oldChangeCount == newChangeCount) %7B // Firefox do not trigger %60change%60 when %60files%60 is set;%0A inputFile.change();%0A %7D%0A%0A %7D%0A%0A function fileChangeCount() %7B%0A return inputFile.data('changeCount') %7C%7C 0
;%0A
@@ -7212,32 +7212,48 @@
%7D
+
%0A%09 %7D%0A%09
|
40af89fe4f78ce305680ca20f13b8169c3c0e302 | fix for the slider height | _js/bessa.js | _js/bessa.js |
$(document).ready(function(){
"use strict"
function smoothScroll (duration) {
$('a[href^="#introduction"]').on('click', function(event) {
var target = $( $(this).attr('href') );
if( target.length ) {
event.preventDefault();
$('html, body').animate({
scrollTop: target.offset().top
}, duration);
}
});
}
smoothScroll(300);
// mobile menu
$(".sub-mobile-trigger").click(function(){
var stylesMobile= {
background: "#f5f5f5",
}
$(this).toggleClass("bessa-bg-red");
$(this).find(">a").toggleClass("white-text");
$(this).children().toggleClass("sub-menu-active");
$(" ul.sub-mobile-items").css(stylesMobile)
});
// sidebar opening and closing
function sidebarToggler(){
$(".sidbar-trigger").toggleClass("change");
$(".sidebar .social").toggle();
}
function checkSidebarOpen(){
var test= $(".sidebar .social").css("display");
if( test=== "block" ){
sidebarToggler();
}
}
$(".sidbar-trigger").on("click",sidebarToggler)
// $('.slider').slider();
// scrolling configuration ? get the dimensions of te footer and container
var $containerWidth= $(".bg-bessa").width();
var $footerHeight= $("footer").outerHeight();
var $nav = $(".navbar-fixed nav");
$( window ).resize(function() {
$containerWidth= $(".bg-bessa").width();
$footerHeight= $("footer").outerHeight();
setFooter();
setNavbar();
});
function setNavbar(){
$nav.css("width",$containerWidth)
}
function setFooter(){
$("footer").css("width",$containerWidth);
$(".bg-bessa").css("marginBottom",$footerHeight);
}
setFooter();
setNavbar();
var amimationSettings ={
fast: 200,
medium: 400,
slow: 600
}
// scrolling effects
$(window).scroll(function(){
var wScroll = $(this).scrollTop();
// cards animation
if( ( $("#introduction").length) && wScroll > $("#introduction").offset().top - ($(window).height()/1.2) ){
$(".card").each(function(i){
setTimeout(function(){
$(".card").eq(i).addClass("is-showing");
},amimationSettings.fast*(i+1));
});
}
// newsletter animation
if( ( $(".newsletter-container").length ) && wScroll > $(".newsletter-container").offset().top - ($(window).height()/1.2) ){
$(".newsletter-container").addClass("newsletter-showing");
}
if(( $(".quote-media").length ) && wScroll > $(".quote-media").offset().top - ($(window).height()/1.2) ){
$(".quote-media").addClass("newsletter-showing");
}
// avantages section animation
if( ( $(".value").length ) && wScroll > $(".value").offset().top - ($(window).height()/1.2) ){
$(".val").each(function(i){
setTimeout(function(){
$(".val").eq(i).addClass("is-showing");
},amimationSettings.fast *(i+1));
})
}
});
});
| JavaScript | 0 | @@ -1635,16 +1635,109 @@
vbar();%0A
+$(window).load(function() %7B%0A $('.preloader').fadeOut();%0A setFooter();%0A setNavbar();%0A%7D);
%0Avar ami
|
d495dd6ec7ca48226e020f74d5958e2688923268 | Comment and cleanup. | lib/jobs.js | lib/jobs.js | var async = require('async'),
moment = require('moment'),
events = require('events'),
_ = require('lodash'),
shouldStillProcess,
pg = require('pg'),
Transaction = require('pg-transaction');
module.exports = function(options) {
var Jobs = {};
var jobsModel = require('../models/jobs');
// Expose jobs model when we are testing so we can set up stuff on the Db.
if (process.env.NODE_ENV === 'test') {
Jobs.jobsModel = jobsModel;
}
Jobs.eventEmitter = new events.EventEmitter();
Jobs.create = function(jobData, processIn, done) {
pg.connect(options.db, function(err, db, releaseClient) {
var doneAndRelease = function(err) {
releaseClient();
done(err);
};
if (err) return doneAndRelease(err);
jobsModel.write(db, null, processIn, jobData, doneAndRelease);
});
};
function updateJob(db, jobSnapshot, newJobData, processIn, cb) {
jobsModel.write(db, jobSnapshot.job_id, processIn, newJobData, complete);
function complete(err) {
if (err) return cb(err);
Jobs.eventEmitter.emit('jobUpdated');
cb();
}
}
function serviceJob(db, jobContainer, userJobIterator, callback) {
return userJobIterator(jobContainer.job_id, jobContainer.data,
processingComplete);
function processingComplete(err, newJobData, processIn) {
if (err) {
return callback(err);
} else {
updateJob(db, jobContainer, newJobData, processIn, callback);
}
}
}
Jobs.stopProcessing = function() {
shouldStillProcess = false;
};
Jobs.continueProcessing = function() {
return shouldStillProcess;
};
/**
* Examines and services jobs in the 'jobs' array, repeatedly, forever, unless
* stopProcessing() is called.
* Call this once to start processing jobs.
* @param {function} serviceJob Iterator function to be run on jobs requiring
* service.
*/
Jobs.process = function(processFunction, done) {
shouldStillProcess = true;
done = done || function() {};
pg.connect(options.db, connected);
function connected(err, db, releaseClient) {
if (err) return done(err);
async.whilst(Jobs.continueProcessing, iterator, finish);
function iterator(callback) {
setImmediate(function() {
Jobs.eventEmitter.emit('maybeServiceJob');
jobsModel.nextToProcess(db, getJobProcessor(false, db, processFunction, callback));
});
}
function finish(err) {
releaseClient();
Jobs.eventEmitter.emit('stopProcess');
done();
}
}
};
Jobs.processNow = function(jobId, processFunction, done) {
done = done || function() {};
pg.connect(options.db, connected);
function connected(err, db, releaseClient) {
if (err) return done(err);
jobsModel.obtainLock(db, jobId, getJobProcessor(true, db, _processFunction, function(err) {
releaseClient();
done(err);
}));
Jobs.eventEmitter.emit('lockSought');
}
function _processFunction(id, data, callback) {
processFunction(null, data, callback);
}
};
function getJobProcessor(now, db, processFunction, callback) {
return function(err, jobSnap) {
if (err) return callback(err);
if (!jobSnap) {
if (now) return callback(new Error('Could not locate job'));
Jobs.eventEmitter.emit('drain');
return setTimeout(callback, options.pollInterval || 1000);
}
if (now) Jobs.eventEmitter.emit('lockObtained');
processJob(jobSnap);
}
function processJob(jobSnap) {
var tx = new Transaction(db);
tx.on('error', function() {
jobsModel.unlock(db, jobSnap.id);
callback(new Error('Transaction error'));
});
serviceJob(tx, jobSnap, processFunction, function(err) {
if (err) {
tx.rollback();
} else {
tx.commit();
Jobs.eventEmitter.emit(now ? 'processNowCommitted' : 'processCommitted');
}
jobsModel.unlock(db, jobSnap.id);
callback();
});
}
}
return Jobs;
};
// vim: set et sw=2 ts=2 colorcolumn=80:
| JavaScript | 0 | @@ -1933,16 +1933,187 @@
ervice.%0A
+ * @param %7Bfunction%7D done callback to receive errors pertaining to running%0A * process() - i.e. db connection issues. Also called when stopProcessing() is%0A * called.%0A
*/%0A
@@ -3748,16 +3748,17 @@
);%0A %7D
+;
%0A%0A fu
|
1b1fc954f735461e4f3e2d79d3943b53f0854f05 | Test updates. | test/funky_tag_test.js | test/funky_tag_test.js | 'use strict';
var grunt = require('grunt');
/*
======== A Handy Little Nodeunit Reference ========
https://github.com/caolan/nodeunit
Test methods:
test.expect(numAssertions)
test.done()
Test assertions:
test.ok(value, [message])
test.equal(actual, expected, [message])
test.notEqual(actual, expected, [message])
test.deepEqual(actual, expected, [message])
test.notDeepEqual(actual, expected, [message])
test.strictEqual(actual, expected, [message])
test.notStrictEqual(actual, expected, [message])
test.throws(block, [error], [message])
test.doesNotThrow(block, [error], [message])
test.ifError(value)
*/
exports.tag = {
setUp: function(done) {
done();
},
works: function(test) {
test.expect(1);
test.ok(true, 'Works.');
test.done();
}
};
| JavaScript | 0 | @@ -671,11 +671,17 @@
rts.
-tag
+all_tests
= %7B
|
53d7ed41e702738b84d3c8e5bb7771d640b73745 | Add colours to LogLevels. | src/foam/log/LogLevel.js | src/foam/log/LogLevel.js | /**
* @license
* Copyright 2017 The FOAM Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
foam.ENUM({
package: 'foam.log',
name: 'LogLevel',
properties: [
{
class: 'String',
name: 'shortName'
},
{
class: 'String',
name: 'consoleMethodName'
}
],
values: [
{
name: 'DEBUG',
shortName: 'DEBG',
label: 'Debug',
consoleMethodName: 'debug'
},
{
name: 'INFO',
shortName: 'INFO',
label: 'Info',
consoleMethodName: 'info'
},
{
name: 'WARN',
shortName: 'WARN',
label: 'Warn',
consoleMethodName: 'warn'
},
{
name: 'ERROR',
shortName: 'ERRR',
label: 'Error',
consoleMethodName: 'error'
}
]
});
| JavaScript | 0 | @@ -822,22 +822,77 @@
odName'%0A
+ %7D,%0A %7B%0A class: 'Color',%0A name: 'color'%0A
%7D%0A
-
%5D,%0A%0A
@@ -971,24 +971,45 @@
l: 'Debug',%0A
+ color: 'blue',%0A
consol
@@ -1108,16 +1108,40 @@
'Info',%0A
+ color: '#0000cc',%0A
co
@@ -1243,16 +1243,40 @@
'Warn',%0A
+ color: '#ffa500',%0A
co
@@ -1354,24 +1354,24 @@
me: 'ERRR',%0A
-
label:
@@ -1376,24 +1376,44 @@
l: 'Error',%0A
+ color: 'red',%0A
consol
|
7c225a540766c2a7aee17b4e888afd1a1ae28859 | Delete unused variable. | bin/contribution/controllers/contribution.js | bin/contribution/controllers/contribution.js | #!/usr/bin/env node
const debug = require('debug')('query-v1');
const memberId = "Member:74617";
const utils = require('../lib/utils');
var memberAndTasksQuery = [
{
"from": "Member",
"select": [ "Name", "Nickname" ],
"where": { "ID": memberId }
},
{
"from": "Task",
"select": [ "Name", "Number", "Status.Name", "ChangeDate", "CreateDate", "DetailEstimate",
{
"from": "Owners",
"select": [ "Name", "Nickname" ]
},{
"from": "Parent",
"select": [ "Name", "Number" ]
}
],
"where": {
"Owners.ID": memberId,
"Status.Name": "Completed"
},
"filter": [
"ChangeDate>'2017-01-01T00:00:00'"
],
"sort": [
"-ChangeDate"
],
"asof": "2017-04-01T00:00:00"
}
];
function storyQuery(storyId) {
return {
from: 'Story',
select: [
'Name', 'Number', 'ChangeDate', 'CreateDate',
{
from: 'Children',
select: [
'Name', 'Number', 'DetailEstimate',
{
from: 'Owners',
select: [ 'Name', 'Nickname' ]
}
]
},
{
from: 'Owners',
select: [ 'Name', 'Nickname' ]
}
],
where: {
ID: storyId,
}
}
}
function storyRow({number = 'TK-UNKNOWN', name = '[NAME]', owners = [], linkUrl = ''} = {}) {
const ownerSummary = `(${owners.length}) ` + owners.join(';');
return `<tr><td>STORY<td> ${number} ${name} ${ownerSummary} $linkUrl`;
};
//debug('memberAndTasksQuery', JSON.stringify(memberAndTasksQuery, null, ' '));
var storiesPromise;
function report(req, res) {
utils.loadCache('stories', () => {
return utils.fetchV1(memberAndTasksQuery)
.then(utils.filterErrors('first request:'))
.then(response => response.json())
.then(function (data) {
const USER_QUERY_INDEX = 0;
const TASKS_QUERY_INDEX = 1;
const storyIdSet = {};
debug('User', data[USER_QUERY_INDEX][0].Name);
const storyQueries = data[TASKS_QUERY_INDEX].reduce((accumulator, currentTask) => {
const parentStory = currentTask.Parent[0];
const versionedParentId = parentStory._oid;
const storyId = versionedParentId.replace(/:\d+$/, '');
if (!storyIdSet.hasOwnProperty(storyId)) {
debug('keeping ', storyId, parentStory.Name);
accumulator.push(storyQuery(storyId));
storyIdSet[storyId] = parentStory.Name;
} else {
debug('skipping duplicate', storyId);
}
return accumulator;
}, []);
return utils.fetchV1(storyQueries);
})
.then(utils.filterErrors('second request:'))
.then(response => response.json())
})
.then(stories => {
debug('Iterating over stories...');
// td #{row.storyNumber}
// td #{row.storyName}
// td #{row.taskNumber}
// td #{row.taskName}
// td #{row.estimatedHours}
// td #{row.ownedHours}
// td #{row.contributionPercent}
// td #{row.ownerCount}
// td #{row.ownerList}
var viewData = []
stories.forEach(subResult => {
const story = subResult[0];
const storyRow = {
storyNumber: story.Number,
storyName: story.Name,
taskNumber: '-',
taskName: '-',
estimatedHours: 0,
ownedHours: 0
};
viewData.push(storyRow);
const storyOwnerIds = new Set();
const storyOwnerNames = [];
function addOwner(ownerId, ownerName) {
if (!storyOwnerIds.has(ownerId)) {
storyOwnerIds.add(ownerId);
storyOwnerNames.push(ownerName);
}
}
story.Children.forEach(task => {
const taskOwnerIds = new Set(task.Owners.map(owner => owner._oid));
const estimatedHours = Number(task.DetailEstimate);
var ownedHours = 0;
var contributionPercent = 0;
if (taskOwnerIds.has(memberId)) {
ownedHours = Math.round(10 * estimatedHours / taskOwnerIds.size) / 10;
contributionPercent = Math.round(100 / taskOwnerIds.size);
}
storyRow.estimatedHours += estimatedHours;
storyRow.ownedHours += ownedHours;
task.Owners.forEach(owner => addOwner(owner._oid, owner.Name));
viewData.push({
storyNumber: story.Number,
storyName: '"',
taskNumber: task.Number,
taskName: task.Name,
estimatedHours: estimatedHours,
ownedHours: ownedHours || '-',
contributionPercent: contributionPercent || '-',
ownerCount: task.Owners.length,
ownerList: task.Owners.map(owner => owner.Name).join(', ')
});
});
storyRow.contributionPercent = Math.floor(100 * storyRow.ownedHours / storyRow.estimatedHours);
storyRow.ownerList = storyOwnerNames.join(', ');
storyRow.ownerCount = storyOwnerIds.size;
});
stories.forEach(subQueryResult => {
const story = subQueryResult[0];
console.log(storyRow({}));
console.log('"' + ['STORY', story.Number, story.Name, story.Owners.map(owner => owner.Name).join(':'), utils.baseUris.story + story._oid].join('", "') + '"')
const tasks = story.Children;
tasks.forEach(task => {
// console.log('"' + ['.', task.Number, task.Name, task.DetailEstimate, task.Owners.map(owner => owner.Name).join(':'), taskBaseUri + task._oid].join('", "') + '"');
});
})
// debug(JSON.stringify(viewData, null, ' '));
res.render('index', {rows: viewData});
// debug(JSON.stringify(stories, null, ' '));
})
.catch(error => debug('failed to get data', error));
};
module.exports = report;
| JavaScript | 0 | @@ -1485,109 +1485,8 @@
%7D;%0A%0A
-//debug('memberAndTasksQuery', JSON.stringify(memberAndTasksQuery, null, ' '));%0Avar storiesPromise;%0A%0A
func
|
86dd7a2cca760162b89436e2caacdc86357847e8 | wordify the percent symbol in slugs | app/helper/makeSlug.js | app/helper/makeSlug.js | var ensure = require('./ensure');
var MAX_LENGTH = 100;
var encodeAmpersands = require('./encodeAmpersands');
// This must always return a string but it can be empty
function makeSlug (string) {
var words, components, trimmed = '';
ensure(string, 'string');
var slug = '';
slug = string;
// We do this to handle ampersands nicely
slug = encodeAmpersands(slug);
// Remove query sluging
if (slug.indexOf('?=') > -1)
slug = slug.slice(0, slug.indexOf('?='));
slug = slug.trim()
.slice(0, MAX_LENGTH + 10)
.toLowerCase()
// remove common punction, basically everything except & _ and - /
.replace(/&/g, 'and')
.replace(/→/g, 'to')
.replace(/←/g, 'from')
.replace(/\./g,'-')
.replace(/[\“\”\‘\’\`\~\!\@\#\$\%\^\&\*\(\)\+\=\\\|\]\}\{\[\'\"\;\:\?\>\.\<\,]/g, '')
.replace(/[^[:alnum:]0-9_-\s]/g, '') // remove invalid chars
.replace(/\s+/g, '-') // collapse whitespace and replace by -
.replace(/-+/g, '-'); // collapse dashes
words = slug.split('-');
trimmed = words.shift();
for (var x = 0;x < words.length;x++) {
if (trimmed.length + words[x].length > MAX_LENGTH)
break;
trimmed += '-' + words[x];
}
slug = trimmed;
// Remove leading and trailing
// slashes and dashes.
if (slug[0] === '/')
slug = slug.slice(1);
if (slug.slice(-1) === '/')
slug = slug.slice(0,-1);
if (slug[0] === '-')
slug = slug.slice(1);
if (slug.slice(-1) === '-')
slug = slug.slice(0,-1);
components = slug.split('/');
for (var i = 0;i < components.length;i++)
components[i] = encodeURIComponent(components[i]);
slug = components.join('/');
slug = slug || '';
return slug;
}
var Is = require('./is');
var is = Is(makeSlug);
is('!@#$%^*()=+[]{}\\|;:\'\",?><', '');
is('foo!@#$%^*()=+[]{}\\|;:\'\",?><bar', 'foobar');
is('', '');
is('H', 'h');
is('HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello', 'hellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohello');
is('Hello', 'hello');
is('Hello unicode: ', 'hello-unicode-%EF%A3%BF');
is('/Hello/there/', 'hello/there');
is('Hello/THIS/IS/SHIT', 'hello/this/is/shit');
is('Hello This Is Me', 'hello-this-is-me');
is('Hello?=l&=o', 'hello');
is('123', '123');
is('1-2-3-4', '1-2-3-4');
is('12 34', '12-34');
is('f/ü/k', 'f/%C3%BC/k');
is('微博', '%E5%BE%AE%E5%8D%9A');
is('Review of “The Development of William Butler Yeats” by V. K. Narayana Menon', 'review-of-the-development-of-william-butler-yeats-by-v-k-narayana-menon');
is('Review of The Development of William Butler Yeats by V. K. Narayana Menon Review of The Development offff William Butler Yeats by V. K. Narayana Menon', "review-of-the-development-of-william-butler-yeats-by-v-k-narayana-menon-review-of-the-development");
is('AppleScript/Automator Folder Action to Convert Excel to CSV', 'applescript/automator-folder-action-to-convert-excel-to-csv');
is("'xsb' command line error.", 'xsb-command-line-error');
is('Foo & bar', 'foo-and-bar');
is('Foo & bar', 'foo-and-bar');
is('China ← NYC → China', 'china-from-nyc-to-china');
is('Chin+a()[] ← NY!C → China', 'china-from-nyc-to-china');
module.exports = makeSlug; | JavaScript | 0.999999 | @@ -642,16 +642,55 @@
nd - /%0A%0A
+ .replace(/%5C%25/g, '-percent')%0A
@@ -1869,25 +1869,24 @@
);%0A%0Ais('!@#$
-%25
%5E*()=+%5B%5D%7B%7D%5C%5C
@@ -1915,17 +1915,16 @@
'foo!@#$
-%25
%5E*()=+%5B%5D
@@ -2521,32 +2521,96 @@
lohellohello');%0A
+is('100%25 luck 15%25 skill', '100-percent-luck-15-percent-skill');%0A
is('Hello', 'hel
|
c21feab3df843015f093fd0a1999b4158f4719ba | convert to express test server | test/server/index.js | test/server/index.js | /**
* Create a local web server for tests
*/
var http = require("http"),
url = require("url"),
path = require("path"),
fs = require("fs");
// this is crazy over-simple, gotta switch to connect...
function contentType(ext) {
var ct = "text/html";
if (ext === ".xml")
ct = "text/xml";
else if (ext === ".txt")
ct = "text/plain";
return ct;
}
module.exports = {
start: function(rootDir, port, end) {
http.createServer(function(request, response) {
var uri = url.parse(request.url).pathname,
filename = path.join(rootDir, uri),
extname = path.extname(filename);
fs.exists(filename, function(exists) {
if(!exists) {
response.writeHead(404, {"content-type": "text/plain"});
response.write("404 Not Found\n");
response.end();
return;
}
if (fs.statSync(filename).isDirectory()) filename += '/index.html';
fs.readFile(filename, "binary", function(err, file) {
if(err) {
response.writeHead(500, {"content-type": "text/plain"});
response.write(err + "\n");
response.end();
if (typeof end === "function")
setTimeout(end, 1000);
return;
}
response.writeHead(200, {"content-type": contentType(extname)});
response.write(file, "binary");
response.end();
if (typeof end === "function")
setTimeout(end, 1000);
});
});
}).listen(parseInt(port, 10));
}
}; | JavaScript | 0.999996 | @@ -44,20 +44,21 @@
*/%0Avar
-http
+pathm
= requi
@@ -65,668 +65,238 @@
re(%22
-http%22),%0A url = require(%22url%22),%0A path = require(%22path%22),%0A fs = require(%22fs%22);%0A%0A// this is crazy over-simple, gotta switch to connect...%0Afunction contentType(ext) %7B%0A var ct = %22text/html%22;%0A if (ext === %22.xml%22)%0A ct = %22text/xml%22;%0A else if (ext === %22.txt%22)%0A ct = %22text/plain%22;%0A return ct;%0A%7D%0A%0Amodule.exports = %7B%0A%0A start: function(rootDir, port, end) %7B%0A http.createServer(function(request, response) %7B%0A%0A var uri = url.parse(request.url).pathname,%0A filename = path.join(rootDir, uri),%0A
+path%22);%0Avar express = require(%22express%22);%0A%0Avar server = express();%0A%0Afunction setHeaders(res, path) %7B%0A // if we are serving a sitemap.xml.gz, then content-type is application/xml%0A if (pathm.
extname
- =
+(
path
-.extname(filename);%0A%0A fs.exists(filename, function(exists) %7B%0A if(!exists) %7B%0A response.writeHead(404, %7B
+) === %22.gz%22) %7B%0A res.set(
%22con
@@ -309,289 +309,96 @@
ype%22
-: %22text/plain%22%7D);%0A response.write(%22404 Not Found%5Cn%22);%0A response.end();%0A return;%0A %7D%0A%0A if (fs.statSync(filename).isDirectory()) filename += '/index.html';%0A%0A fs.readFile(filename, %22binary%22, function(err, file) %7B%0A if(err
+, %22application/xml%22);%0A %7D%0A%7D%0A%0Amodule.exports = %7B%0A%0A start: function(rootDir, port
) %7B%0A
@@ -397,501 +397,93 @@
- response.writeHead(500, %7B%22content-type%22: %22text/plain%22%7D);%0A response.write(err + %22%5Cn%22);%0A response.end();%0A if (typeof end === %22function%22)%0A setTimeout(end, 1000);%0A return;%0A %7D%0A%0A response.writeHead(200, %7B%22content-type%22: contentType(extname)%7D);%0A response.write(file, %22binary%22);%0A response.end();%0A if (typeof end === %22function%22)%0A setTimeout(end, 1000);%0A %7D);%0A %7D);%0A %7D)
+server.use(express.static(rootDir, %7B%0A setHeaders: setHeaders%0A %7D));%0A server
.lis
@@ -511,10 +511,11 @@
));%0A %7D%0A
+%0A
%7D;
|
ff04b2c677d6fdc19abea79e9d4991d5d2e0a2db | Add a blank line | app/helpers/courses.js | app/helpers/courses.js | import _ from 'lodash'
import Promise from 'bluebird'
import Immutable from 'immutable'
import db from './db'
import buildQueryFromString from 'sto-helpers/lib/buildQueryFromString'
/**
* Gets a course from the database.
*
* @param {Number} clbid - a class/lab ID
* @promise TreoDatabasePromise
* @fulfill {Object} - the course object.
* @reject {Error} - a message about retrieval failing.
*/
function getCourse(clbid) {
// console.log('called getCourse', clbid)
return db
.store('courses')
.index('clbid')
.get(clbid)
.catch((err) => new Error(`course retrieval failed for ${clbid}`, err))
}
/**
* Gets a list of course ids from the database.
*
* @param {Array|Immutable.List} clbids - a list of class/lab IDs
* @promise BluebirdPromiseArray
* @fulfill {Array} - the courses.
*/
function getCourses(clbids) {
// Takes a list of clbids, and returns a list of the course objects for
// those clbids.
// console.log('called getCourses', clbids)
if (Immutable.List.isList(clbids))
clbids = clbids.toJS()
return Promise.all(clbids.map(getCourse))
}
function queryCourseDatabase(queryString) {
let queryObject = buildQueryFromString(queryString)
console.log('query object', queryObject)
let start = performance.now()
return db
.store('courses')
.query(queryObject)
.catch(err => new Error('course query failed on', queryString, err))
}
export {
getCourse,
getCourses,
queryCourseDatabase
}
window.courseStuff = {
getCourse,
getCourses,
queryCourseDatabase,
}
| JavaScript | 1 | @@ -1249,16 +1249,17 @@
e.now()%0A
+%0A
%09return
|
bbb7c3643898343f1b0eda22a20dc0bdd1b30b10 | Fix button for Bin. | examples/battest/app.js | examples/battest/app.js | window.addEventListener("load", function() {
console.log("Hello World!");
});
function fireNetwork(){
console.log("Hello World!");
}
| JavaScript | 0 | @@ -69,16 +69,80 @@
rld!%22);%0A
+ document.getElementById('fireNetwork').onclick = fireNetwork;%0A
%7D);%0A%0Afun
|
6b606723ed61329365d8a07c584f5d1ba7242629 | remove mock code | web/public/wap/modules/photo/myPhotoCtrl.js | web/public/wap/modules/photo/myPhotoCtrl.js | /**
* 需要外部传入的app, 则`module.exports`为function
*/
define(function (require, exports, module) {
'use strict';
module.exports = function(app){
app.register.controller('myPhotoCtrl', ['$scope', '$routeParams', '$location', '$http', 'PhotoService',
function($scope, $routeParams, $location, $http, PhotoService) {
$scope.photo = {};
$scope.photo.records = null;
var uri;
function refresh() {
PhotoService.getByUrl(uri)
.then(function(records) {
records = [{path: 111}, {path: 222}];
$scope.photo.records = records.sort(function(a, b) { return a.startDate > b.startDate ? -1 : 1;});
});
}
$scope.photo.remove = function(record) {
if (confirm("确认删除该批图片?")) {
PhotoService.remove(record.id)
.then(function() {
alert('删除成功!');
refresh();
}, function() {
alert('删除失败!');
});
}
};
$scope.$watch("session.user", function() {
if (!$scope.session.user) {
return;
}
var path = $location.path();
var schoolId = $routeParams.schoolId;
if (path.indexOf('teacher') >= 0) {
var teacherId = $scope.photo.teacherId = $routeParams.teacherId;
uri = '/api/school/' + schoolId + '/teacher/' + teacherId + '/photo';
} else if (path.indexOf('parent') >= 0) {
var parentId = $scope.photo.parentId = $routeParams.parentId;
uri = '/api/school/' + schoolId + '/parent/' + parentId + '/photo';
} else {
alert("未支持的功能.");
return;
}
refresh();
});
}]
);
}
}); | JavaScript | 0.000277 | @@ -594,16 +594,18 @@
+//
records
|
73bc46371bd5eddb764f62bc487fa5a6dcc4cf77 | Update to script structure | gulpfile.js | gulpfile.js | // Require plugins
var gulp = require('gulp'),
rename = require("gulp-rename"),
concat = require('gulp-concat'),
uglify = require('gulp-uglify'),
sass = require('gulp-ruby-sass'),
prefix = require('gulp-autoprefixer'),
cssmin = require('gulp-minify-css'),
imagemin = require ('gulp-imagemin');
// Concat & Minify JS
gulp.task('scripts', function(){
gulp.src(['js/lib/plugins/**','js/global.js'])
.pipe(concat('global.js'))
.pipe(gulp.dest('js/build'))
.pipe(uglify())
.pipe(rename('global.min.js'))
.pipe(gulp.dest('js/build'))
});
// Build, autoprefix & minify CSS
gulp.task('sass', function () {
gulp.src('css/build.scss')
.pipe(sass({noCache:true,debugInfo:true}))
.pipe(rename('global.css'))
.pipe(gulp.dest('css/build/unprefixed'))
.pipe(prefix("last 2 versions", "> 1%", "ie 8"))
.pipe(gulp.dest('css/build/prefixed'))
.pipe(cssmin())
.pipe(rename('global.min.css'))
.pipe(gulp.dest('css/build/prefixed'))
});
// Minify images
gulp.task('images', function () {
gulp.src('img/*')
.pipe(imagemin())
.pipe(gulp.dest('img'))
});
// Default
gulp.task('default', function(){
// Run Task
gulp.run('scripts', 'sass', 'images');
// Watch & build .scss
gulp.watch('css/**/*.scss' , function(ev){
gulp.run('sass')
});
// Watch & build js
gulp.watch(['js/global.js','js/user/*.js', 'js/lib/plugins/*.js'], function(ev){
gulp.run('scripts')
});
// Watch & minify images
gulp.watch(['img/**'], function(ev){
gulp.run('images')
});
}); | JavaScript | 0 | @@ -456,11 +456,29 @@
ns/*
-*
+.js','js/user/*.js
',
+
'js/
@@ -1519,39 +1519,24 @@
/global.js',
-'js/user/*.js',
'js/lib/plu
@@ -1545,16 +1545,32 @@
ns/*.js'
+, 'js/user/*.js'
%5D, funct
|
5ebcfaeda6effc1b2624116ed3d0780e020e6ae3 | remove the comments | javascripts/workouts.js | javascripts/workouts.js |
var camera, scene, renderer;
var mesh;
var lastVelocity = 0,
lastTime = new Date(),
lastPosition = 0;
init();
animate();
initGyro();
function init() {
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
//
camera = new THREE.PerspectiveCamera( 70, window.innerWidth /
window.innerHeight, 1, 1000 );
camera.position.z = 600;
scene = new THREE.Scene();
var geometry = new THREE.BoxGeometry( 200, 200, 200 );
var texture = THREE.ImageUtils.loadTexture( 'textures/crate.gif' );
texture.anisotropy = renderer.getMaxAnisotropy();
var material = new THREE.MeshBasicMaterial( { map: texture } );
mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );
//
window.addEventListener( 'resize', onWindowResize, false );
}
function velocity (lastVelocity, acceleration, timeStep) {
return lastVelocity + (acceleration * timeStep);
}
function position (lastPosition, lastVelocity, acceleration, timeStep) {
return lastPosition + lastVelocity * timeStep +
(0.5 * acceleration * timeStep * timeStep);
}
// initialize gyro some other comments
function initGyro() {
console.log("start tracking");
gyro.frequency = 100;
gyro.startTracking(function(o) {
var yNoiseUpper = 0.2,
yNoiseLower = 0;
if (parseFloat(o.y.toFixed(2)) >= yNoiseUpper ||
parseFloat(o.y.toFixed(2)) <= yNoiseLower) {
var yAcceleration = o.y.toFixed(3),
needsRender = false,
currentTime = new Date(),
timeStep = currentTime - lastTime;
console.log("y-acceleration: " + o.y.toFixed(3));
lastVelocity = velocity(lastVelocity, yAcceleration, timeStep);
lastPosition = position(lastPosition, lastVelocity, yAcceleration, timeStep);
console.log("Velocity: " + lastVelocity);
console.log("Position: " + lastPosition);
lastTime = currentTime;
// if (newY <= 400 && newY >= -400) {
// mesh.position.y = newY;
// needsRender = true;
// }
if (needsRender) {
renderer.render( scene, camera );
console.log(mesh.position.y);
}
// o.z
// o.alpha
// o.beta
// o.gamma
}
if (parseFloat(o.x.toFixed(1)) >= 0.5) {
console.log("x-acceleration: " + o.x.toFixed(3));
}
if (parseFloat(o.z.toFixed(1)) >= 9.8) {
console.log("z-acceleration: " + o.z.toFixed(3));
}
});
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function animate() {
requestAnimationFrame( animate );
renderer.render( scene, camera );
}
| JavaScript | 0 | @@ -1317,50 +1317,8 @@
%7D%0A%0A%0A
- // initialize gyro some other comments
%0A
|
69251369a1b318e1c5d62e06c0277f205a0211eb | add IE11 compatibility | src/components/Beacon.js | src/components/Beacon.js | import React from 'react';
import PropTypes from 'prop-types';
export default class JoyrideBeacon extends React.Component {
constructor(props) {
super(props);
if (!props.beaconComponent) {
const head = document.head || document.getElementsByTagName('head')[0];
const style = document.createElement('style');
const css = `
@keyframes joyride-beacon-inner {
20% {
opacity: 0.9;
}
90% {
opacity: 0.7;
}
}
@keyframes joyride-beacon-outer {
0% {
transform: scale(1);
}
45% {
opacity: 0.7;
transform: scale(0.75);
}
100% {
opacity: 0.9;
transform: scale(1);
}
}
`;
style.type = 'text/css';
style.id = 'joyride-beacon-animation';
style.appendChild(document.createTextNode(css));
head.appendChild(style);
}
}
static propTypes = {
beaconComponent: PropTypes.oneOfType([
PropTypes.func,
PropTypes.element,
]),
onClickOrHover: PropTypes.func.isRequired,
styles: PropTypes.object.isRequired,
};
componentWillUnmount() {
const style = document.getElementById('joyride-beacon-animation');
if (style) {
style.remove();
}
}
render() {
const { beaconComponent, onClickOrHover, styles } = this.props;
const props = {
'aria-label': 'Open',
onClick: onClickOrHover,
onMouseEnter: onClickOrHover,
title: 'Open',
};
let component;
if (beaconComponent) {
if (React.isValidElement(beaconComponent)) {
component = React.cloneElement(beaconComponent, props);
}
else {
component = beaconComponent(props);
}
}
else {
component = (
<button
key="JoyrideBeacon"
className="joyride-beacon"
style={styles.beacon}
{...props}
>
<span style={styles.beaconInner} />
<span style={styles.beaconOuter} />
</button>
);
}
return component;
}
}
| JavaScript | 0 | @@ -1162,15 +1162,36 @@
yle.
-remove(
+parentNode.removeChild(style
);%0A
|
42e5d8543366d98f4ff76b76dd7bb3574d734be5 | Create uploadfolder if it doesn't exist | create-folders.js | create-folders.js | // Screenshot Backend
// Standalone tool for checking and creating upload directories
var uploadfolder = "uploads";
var auth = require("./auth.json");
var fs = require("fs");
var path = require("path");
usersLeft = auth.users.length + auth.keys.length;
foldersCreated = 0;
for (i in auth.users) {
if (!fs.existsSync(__dirname + path.sep + uploadfolder + path.sep + auth.users[i].dirs.images)) {
foldersCreated++;
fs.mkdirSync(__dirname + path.sep + uploadfolder + path.sep + auth.users[i].dirs.images);
}
if (!fs.existsSync(__dirname + path.sep + uploadfolder + path.sep + auth.users[i].dirs.videos)) {
foldersCreated++;
fs.mkdirSync(__dirname + path.sep + uploadfolder + path.sep + auth.users[i].dirs.videos);
}
if (!fs.existsSync(__dirname + path.sep + uploadfolder + path.sep + auth.users[i].dirs.files)) {
foldersCreated++;
fs.mkdirSync(__dirname + path.sep + uploadfolder + path.sep + auth.users[i].dirs.files);
}
if (--usersLeft === 0) { // If list is empty, and we haven't reported a success/bad password, return with user not found
doneLooping();
}
}
for (i in auth.keys) {
if (!fs.existsSync(__dirname + path.sep + uploadfolder + path.sep + auth.keys[i].uploaddir)) {
foldersCreated++;
fs.mkdirSync(__dirname + path.sep + uploadfolder + path.sep + auth.keys[i].uploaddir);
}
if (--usersLeft === 0) { // If list is empty, and we haven't reported a success/bad password, return with user not found
doneLooping();
}
}
function doneLooping() {
console.log("Done!\n" + foldersCreated + " folders created.\n" + (auth.users.length * 3 + auth.keys.length) + " folders scanned.");
}
| JavaScript | 0.000001 | @@ -271,16 +271,134 @@
ed = 0;%0A
+%0Aif (!fs.existsSync(__dirname + path.sep + uploadfolder)) %7B%0A fs.mkdirSync(__dirname + path.sep + uploadfolder);%0A%7D%0A%0A
for (i i
|
ba06cbb1ea36a589a4f802887b6bc1fe9a8da1b0 | Add queue button | js/content-script.js | js/content-script.js | JavaScript | 0.000003 | @@ -0,0 +1,914 @@
+console.log('loaded');%0D%0A%0D%0Afunction addQueueButton() %7B%0D%0A let saveButtons = document.querySelectorAll('%5Bvalue=%22Save Edits%22%5D');%0D%0A saveButtons.forEach(button =%3E %7B%0D%0A if (!button.parentNode.querySelector('.queue-edit-button')) %7B%0D%0A let queueButton = document.createElement('input');%0D%0A queueButton.type = 'button';%0D%0A queueButton.value = 'Queue Edits';%0D%0A queueButton.classList.add('queue-edit-button');%0D%0A button.parentNode.insertBefore(queueButton, button.nextSibling);%0D%0A button.parentNode.insertBefore(document.createTextNode(%22 %22), queueButton);%0D%0A %7D%0D%0A %7D);%0D%0A%7D%0D%0A%0D%0Alet observer = new MutationObserver((mutations, observer) =%3E %7B%0D%0A mutations.forEach(mutation =%3E %7B%0D%0A mutation.addedNodes.forEach(addQueueButton);%0D%0A %7D);%0D%0A%7D);%0D%0A%0D%0Aobserver.observe(document, %7B%0D%0A subtree: true,%0D%0A childList: true,%0D%0A characterData: true%0D%0A%7D);
| |
cfd38a1d570d32731a3f52b285830fa9749d500d | Add additional disability sort categories | app/assets/javascripts/sorts/disability_sort.js | app/assets/javascripts/sorts/disability_sort.js | (function(){
Tablesort.extend('disability', function(item) {
return (
item.search(/(High|Moderate|Low < 2)/i) !== -1
);
}, function(a,b) {
var disability = ['Low < 2','Moderate','High'];
return disability.indexOf(b) - disability.indexOf(a);
});
}()); | JavaScript | 0 | @@ -178,16 +178,24 @@
lity = %5B
+'None',
'Low %3C 2
@@ -196,16 +196,29 @@
ow %3C 2',
+ 'Low %3E= 2',
'Moderat
@@ -220,16 +220,17 @@
derate',
+
'High'%5D;
@@ -299,8 +299,9 @@
);%0A%7D());
+%0A
|
ad39c5113a74e15afe95bc8553fcd47c169eb6df | Use fs.stat instead of fs.realpath for dynamicPath resolution. | lib/middleware/dynamicPath.js | lib/middleware/dynamicPath.js | /**
Middleware that provides comprehension of route parameters
("/:version/combo") to the default `combine` middleware.
**/
var fs = require('fs');
var path = require('path');
var BadRequest = require('../error/bad-request');
/**
Route middleware to provide parsing of route parameters
into filesystem root paths.
@method dynamicPath
@param {Object} options
@return {Function}
**/
exports = module.exports = function (options) {
// don't explode when misconfigured, just pass through with a warning
if (!options || !options.rootPath) {
console.warn("dynamicPathMiddleware: config missing!");
return function disabledMiddleware(req, res, next) {
next();
};
}
// private fs.realpath cache
var PATH_CACHE = {};
var rootPath = options.rootPath,
dynamicKey = getDynamicKey(rootPath),
dynamicParam,
rootSuffix;
// str.match() in route config returns null if no matches or [":foo"]
if (dynamicKey) {
// key for the req.params must be stripped of the colon
dynamicParam = dynamicKey.substr(1);
// if the parameter is not the last token in the rootPath
// (e.g., '/foo/:version/bar/')
if (path.basename(rootPath).indexOf(dynamicKey) === -1) {
// rootSuffix must be stored for use in getDynamicRoot
rootSuffix = rootPath.substr(rootPath.indexOf(dynamicKey) + dynamicKey.length);
}
// remove key + suffix from rootPath used in initial realpathSync
rootPath = rootPath.substring(0, rootPath.indexOf(dynamicKey));
}
// Intentionally using the sync method because this only runs when the
// middleware is initialized, and we want it to throw if there's an error.
rootPath = fs.realpathSync(rootPath);
return function dynamicPathMiddleware(req, res, next) {
// on the off chance this middleware runs twice
if (!res.locals.rootPath) {
// supply subsequent middleware with the res.locals.rootPath property
getDynamicRoot(req.params, {
"rootPath" : rootPath,
"dynamicParam": dynamicParam,
"rootSuffix" : rootSuffix,
"pathCache" : PATH_CACHE
}, function (err, resolvedRootPath) {
if (err) {
next(new BadRequest('Unable to resolve path: ' + req.path));
} else {
res.locals.rootPath = resolvedRootPath;
next();
}
});
} else {
next();
}
};
};
function getDynamicRoot(params, opts, cb) {
var rootPath = opts.rootPath;
var dynamicParam = opts.dynamicParam;
var rootSuffix = opts.rootSuffix;
var pathCache = opts.pathCache;
var dynamicValue = dynamicParam && params[dynamicParam];
var dynamicRoot;
// a dynamic parameter has been configured
if (dynamicValue) {
// rootSuffix contributes to cache key
if (rootSuffix) {
dynamicValue = path.join(dynamicValue, rootSuffix);
}
dynamicRoot = path.normalize(path.join(rootPath, dynamicValue));
if (pathCache[dynamicRoot]) {
// a path has already been resolved
cb(null, pathCache[dynamicRoot]);
}
else {
// a path needs resolving
fs.realpath(dynamicRoot, pathCache, function (err, resolved) {
if (err) {
cb(err);
} else {
// cache for later short-circuit
pathCache[dynamicRoot] = resolved;
cb(null, resolved);
}
});
}
}
// default to rootPath when no dynamic parameter present
else {
cb(null, rootPath);
}
}
function getDynamicKey(rootPath) {
// route parameter matches ":foo" of "/:foo/bar/"
var paramRegex = /:\w+/;
return paramRegex.test(rootPath) && rootPath.match(paramRegex)[0];
}
| JavaScript | 0 | @@ -723,24 +723,20 @@
vate fs.
-realp
+st
at
-h
cache%0A
@@ -742,20 +742,20 @@
var
-P
+ST
AT
-H
_CACHE =
@@ -2210,20 +2210,20 @@
%22
-p
+st
at
-h
Cache%22
@@ -2229,12 +2229,12 @@
:
-P
+ST
AT
-H
_CAC
@@ -2765,20 +2765,20 @@
var
-p
+st
at
-h
Cache =
@@ -2782,20 +2782,20 @@
= opts.
-p
+st
at
-h
Cache;%0A%0A
@@ -3182,20 +3182,20 @@
if (
-p
+st
at
-h
Cache%5Bdy
@@ -3277,26 +3277,16 @@
b(null,
-pathCache%5B
dynamicR
@@ -3288,17 +3288,16 @@
amicRoot
-%5D
);%0A
@@ -3369,24 +3369,20 @@
fs.
-realp
+st
at
-h
(dynamic
@@ -3390,19 +3390,8 @@
oot,
- pathCache,
fun
@@ -3402,24 +3402,20 @@
n (err,
-resolved
+stat
) %7B%0A
@@ -3564,20 +3564,20 @@
-p
+st
at
-h
Cache%5Bdy
@@ -3589,24 +3589,20 @@
Root%5D =
-resolved
+stat
;%0A
@@ -3624,24 +3624,27 @@
b(null,
-resolved
+dynamicRoot
);%0A
|
b2eeadfcf6aee2e6e0b1c4d2940697bf8052ac8b | Refactor so we can query platforms | src/PlatformsManager.js | src/PlatformsManager.js | // Copyright © 2014 Intel Corporation. All rights reserved.
// Use of this source code is governed by an Apache v2
// license that can be found in the LICENSE-APACHE-V2 file.
var PlatformInfo = require("./PlatformInfo");
/**
* Class that manages platform backends.
* @constructor
* @param {OutputIface} Output instance
*/
function PlatformsManager(output) {
this._output = output;
}
PlatformsManager._implementations = [
"crosswalk-app-tools-backend-ios",
"crosswalk-app-tools-backend-deb",
"crosswalk-app-tools-backend-demo",
"crosswalk-app-tools-backend-test",
"../android/index.js"
];
/**
* Load default backend.
* @returns {PlatformInfo} Metadata object for loaded platform.
*/
PlatformsManager.prototype.loadDefault =
function() {
var output = this._output;
var platformInfo = null;
var warnings = [];
for (var i = 0; i < PlatformsManager._implementations.length; i++) {
platformInfo = this.load(PlatformsManager._implementations[i]);
if (platformInfo) {
break;
} else {
// Accumulate warnings, only emit them if no backend was found.
warnings.push("Loading backend " + PlatformsManager._implementations[i] + " failed");
}
}
if (!platformInfo) {
for (var j = 0; j < warnings.length; j++) {
output.warning(warnings[j]);
}
}
return platformInfo;
};
/**
* Load default backend.
* @returns {PlatformInfo} Metadata object for loaded platform.
*/
PlatformsManager.prototype.loadAll =
function() {
var output = this._output;
var backends = [];
for (var i = 0; i < PlatformsManager._implementations.length; i++) {
platformInfo = this.load(PlatformsManager._implementations[i]);
if (platformInfo) {
backends.push(platformInfo);
}
}
return backends;
};
/**
* Load backend by name.
* @returns {PlatformInfo} Metadata object or null if platform could not be loaded.
*/
PlatformsManager.prototype.load =
function(name) {
var platformInfo = null;
try {
var Ctor = require(name);
var prefix = "crosswalk-app-tools-backend-";
var platformId = null;
if (name.substring(0, prefix.length) == prefix) {
// Extract last part after common prefix.
platformId = name.substring(prefix.length);
} else if (name == "../android/index.js") {
// Special case built-in android backend, so we get a conforming name.
platformId = "android";
} else {
throw new Error("Unhandled platform name " + name);
}
platformInfo = new PlatformInfo(Ctor, platformId);
} catch (e) {
// Ignore because we have a hardcoded list of platforms and not all
// will be available.
}
return platformInfo;
};
module.exports = PlatformsManager;
| JavaScript | 0 | @@ -433,13 +433,20 @@
s =
-%5B
+%7B
%0A
+ %22ios%22:
%22cr
@@ -476,24 +476,31 @@
nd-ios%22,%0A
+ %22deb%22:
%22crosswalk-
@@ -522,24 +522,32 @@
nd-deb%22,%0A
+ %22demo%22:
%22crosswalk-
@@ -574,16 +574,24 @@
mo%22,%0A
+ %22test%22:
%22crossw
@@ -622,16 +622,27 @@
st%22,%0A
+ %22android%22:
%22../and
@@ -656,17 +656,17 @@
dex.js%22%0A
-%5D
+%7D
;%0A%0A/**%0A
@@ -906,34 +906,37 @@
for (var
-i = 0; i %3C
+platformId in
PlatformsMa
@@ -953,36 +953,24 @@
lementations
-.length; i++
) %7B%0A%0A
@@ -974,33 +974,25 @@
-platformInfo = this.load(
+var moduleName =
Plat
@@ -1021,21 +1021,86 @@
tations%5B
-i%5D);%0A
+platformId%5D;%0A platformInfo = this.load(platformId, moduleName);
%0A
@@ -1116,25 +1116,24 @@
formInfo) %7B%0A
-%0A
@@ -1139,17 +1139,16 @@
break;%0A
-%0A
@@ -1271,60 +1271,37 @@
ing
-backend %22 + PlatformsManager._implementations%5Bi%5D
+platform '%22 + moduleName
+ %22
+'
fai
@@ -1709,18 +1709,21 @@
var
-i = 0; i %3C
+platformId in
Pla
@@ -1756,20 +1756,8 @@
ions
-.length; i++
) %7B%0A
@@ -1769,33 +1769,25 @@
-platformInfo = this.load(
+var moduleName =
Plat
@@ -1820,10 +1820,76 @@
ons%5B
-i%5D
+platformId%5D;%0A platformInfo = this.load(platformId, moduleName
);%0A
@@ -2027,16 +2027,146 @@
y name.%0A
+ * @param %7BString%7D platformId Unique platform name%0A * @param %7BString%7D moduleName Name of node module that implements the platform%0A
* @retu
@@ -2288,17 +2288,35 @@
unction(
-n
+platformId, moduleN
ame) %7B%0A%0A
@@ -2387,529 +2387,20 @@
ire(
-name);%0A var prefix = %22crosswalk-app-tools-backend-%22;%0A var platformId = null;%0A if (name.substring(0, prefix.length) == prefix) %7B%0A // Extract last part after common prefix.%0A platformId = name.substring(prefix.length);%0A %7D else if (name == %22../android/index.js%22) %7B%0A // Special case built-in android backend, so we get a conforming name.%0A platformId = %22android%22;%0A %7D else %7B%0A throw new Error(%22Unhandled platform name %22 + name);%0A %7D%0A
+moduleName);
%0A
|
922513bf65f90a33871272b75d907a461967a648 | rewrite url regex rule | startups.js | startups.js | var slackbot = require('./lib/bot');
var http = require('http');
var querystring = require('querystring');
var request = require('request');
var config = {
server: 'irc.freenode.com',
nick: 'slackbot',
username: 'g0vslackbot',
token: process.env.TOKEN ||'', // get from https://api.slack.com/web#basics
income_url: process.env.INCOME_URL || '',
outcome_token: process.env.OUTCOME_TOKEN || '',
channels: {
'#g0v.tw': '#g0v_tw'
},
users: {
},
// optionals
floodProtection: true,
silent: false // keep the bot quiet
};
var slackUsers = {};
var slackChannels = {};
function updateLists () {
request.get({
url: 'https://slack.com/api/users.list?token=' + config.token
}, function (error, response, body) {
var res = JSON.parse(body);
console.log('updated:', new Date());
res.members.map(function (member) {
slackUsers[member.id] = member.name;
});
});
request.get({
url: 'https://slack.com/api/channels.list?token=' + config.token
}, function (error, response, body) {
var res = JSON.parse(body);
res.channels.map(function (channel) {
slackChannels[channel.id] = channel.name;
});
});
setTimeout(function () {
updateLists()
}, 10 * 60 * 1000);
}
updateLists();
var slackbot = new slackbot.Bot(config);
slackbot.listen();
var server = http.createServer(function (req, res) {
if (req.method == 'POST') {
req.on('data', function(data) {
var payload = querystring.parse(data.toString());
if (payload.token == config.outcome_token && payload.user_name != 'slackbot') {
var ircMsg = "<" + payload.user_name + "> " + payload.text;
var channel = Object.keys(config.channels)[0];
/*
* Channel ID -> Channel Name
* Member ID -> Member Name
* decoed URL and remove <, >
*/
ircMsg = ircMsg.replace(/<#C\w{8}>/g, function (matched) {
var channel_id = matched.match(/#(C\w{8})/)[1];
return '#' + slackChannels[channel_id];
}).replace(/<@U\w{8}>/g, function (matched) {
var member_id = matched.match(/@(U\w{8})/)[1];
return '@' + slackUsers[member_id];
}).replace(/<(https?\:\/\/.+)\|.+>/g, function (matched, link) {
return link.replace(/&/g, '&');
}).replace(/</g,'<').replace(/>/g, '>');
slackbot.speak(channel, ircMsg);
res.end('done');
}
res.end('request should not be from slackbot or must have matched token.')
});
} else {
res.end('recieved request (not post)');
}
});
server.listen(5555);
console.log("Server running at http://localhost:5555/");
| JavaScript | 0.00008 | @@ -1729,16 +1729,284 @@
ls)%5B0%5D;%0A
+ // %22%5B-a-zA-Z0-9@:%25_%5C+%5C.~#?&//=%5D%7B2,256%7D.%5Ba-z%5D%7B2,4%7D%5Cb(%5C/%5B-a-zA-Z0-9@:%25_%5C+.~#?&//=%5D*)?%22%0A var url = %22%5B-a-zA-Z0-9@:%25_%5C%5C+%5C.~#?&//=%5D%7B2,256%7D%5C%5C.%5Ba-z%5D%7B2,4%7D%5C%5Cb(%5C%5C/%5B-a-zA-Z0-9@:%25_%5C%5C+.~#?&//=%5D*)?%22;%0A var re = new RegExp(%22%3C(%22 + url + %22)%5C%5C%7C%22 + url + %22%3E%22,%22gi%22);%0A
@@ -2487,33 +2487,10 @@
ace(
-/%3C(https?%5C:%5C/%5C/.+)%5C%7C.+%3E/g
+re
, fu
|
8c2166980812dc30ba0e3c78012815eb9e91baf1 | set bookmark width | js/content_script.js | js/content_script.js | /* global bookMarks */
(function(global) {
var g_timerID;
var g_textCountFlag;
var g_CounterMsg = 'Click to count';
function elementsToArray(node) {
var list = [];
var e = node.querySelectorAll('div.project div.name, div.project div.notes, div.children div.childrenEnd');
// title in first line
list.push({title: e[0].textContent, type: 'title'});
// notes in first line
var text = e[1].getElementsByClassName("content")[0];
if (text.textContent.length > 1) {
list.push({title: text.textContent.replace(/\n+$/g,''), type: 'note'});
}
for (var i = 2; i < e.length; i++) {
if (e[i].matches('div.childrenEnd')) {
list.push({title: '', type: 'eoc'});
} else {
text = e[i].getElementsByClassName("content")[0];
if (e[i].className.match('notes') && text.textContent.length > 1) {
list.push({title: text.textContent.replace(/\n+$/g,''), type: 'note'});
} else if (e[i].className.match('name')) {
list.push({title: text.textContent, type: 'node'});
};
};
};
return list;
}
function setCSS(css) {
if (document.head) {
var style = document.createElement("style");
style.innerHTML = css;
document.head.appendChild(style);
}
}
function injectCSS() {
chrome.storage.sync.get(["theme_enable", "theme", "custom_css"], function (option) {
if (!option.theme_enable) return;
if (option.theme != "CUSTOM") {
var link = document.createElement("link");
link.href = chrome.extension.getURL("css/theme/"+option.theme+".css");
link.type = "text/css";
link.rel = "stylesheet";
document.getElementsByTagName("head")[0].appendChild(link);
}
if (option.custom_css.length > 0) setCSS(option.custom_css);
});
}
function addTextCounter() {
var styles = {
"font-size" : "13px",
color : '#fff',
"background-image" : $("#header").css("background-image"),
"background-color" : $("#header").css("background-color"),
float : "right"
};
styles["padding"] = "8px 20px 8px 0px";
$('<a></a>', {id: 'textCounter'}).css(styles).appendTo($("#header"));
$('#textCounter').html(g_CounterMsg);
jQuery('#textCounter').click(function() {
if (g_textCountFlag) {
clearInterval(g_timerID);
$('#textCounter').html(g_CounterMsg);
} else {
textCounter();
g_timerID = setInterval(textCounter, 1000);
}
g_textCountFlag = !g_textCountFlag;
});
}
function textCounter() {
var content = elementsToArray(document.querySelector('div.selected'));
var chars = 0;
for (var i=0; i < content.length; i++) {
if (content[i].type != 'node') continue;
chars = chars + content[i].title.length;
}
var html = chars + ' letters';
$('#textCounter').html(html);
}
function getHtml(list){
var html = '';
for (var i = 0; i < list.length; i++) {
var url = list[i].url;
var title = list[i].title.replace(/ - WorkFlowy$/, '');
html = html.concat('<li><a href="' + url + '">' + title + '</a></li>');
}
return html;
}
function replaceSideBar()
{
var bookmarks;
chrome.storage.sync.get(["bookmark_enable", "bookmarks"], function (option) {
if (option.bookmark_enable) {
if (!option.bookmarks) {
console.log('NO BOOKMARK');
bookmarks = [{ label: 'WorkFlowy', id: 1234567, children: [
{ label: 'HOME', url: 'https://workflowy.com/#'}
]}];
} else {
console.log('GET BOOKMARK ' + option.bookmarks);
bookmarks = JSON.parse(option.bookmarks);
}
console.log(bookmarks);
// ツリーの構築
var html = '<div class="title ui-dialog-titlebar ui-widget-header">Bookmark</div><div id="bookmark_area"></div>';
$('#keyboardShortcutHelper').html(html);
$('#bookmark_area').tree({
dragAndDrop: true,
autoOpen: 0,
keyboardSupport: false,
data: bookmarks
});
// ブックマーククリック時の処理
$('#bookmark_area').bind('tree.click',
function(event) {
var node = event.node;
if (typeof node.url !== "undefined") location.href = node.url;
}
);
// ツリー移動時の処理
$('#bookmark_area').bind('tree.move', function(event) {
console.log('tree moved');
setTimeout(function() {
var tree = $('#bookmark_area');
chrome.storage.sync.set({
'bookmarks': tree.tree('toJson')
});
}, 1000);
});
}
});
}
function getContent(callback) {
var content = elementsToArray(document.querySelector('div.selected'));
var url = location.href;
var title = document.title;
callback({content: content, url: url, title: title});
}
function addBookmark(url, title) {
console.log("ADD BOOKMARK:" + url + title);
var tree = $('#bookmark_area');
var parent_node = tree.tree('getNodeById', 1234567);
console.log(parent_node);
title = title.replace(/\s\-\sWorkFlowy$/, '');
tree.tree('appendNode', { label: title, url: url }, parent_node);
console.log('save');
console.log(tree.tree('toJson'));
chrome.storage.sync.set({
'bookmarks': tree.tree('toJson')
});
}
function main() {
g_textCountFlag = false;
// show icon in address bar
chrome.extension.sendRequest({type: 'showIcon'}, function() {});
$(document).ready(function(){
injectCSS();
});
$(window).load(function(){
addTextCounter();
replaceSideBar();
});
chrome.extension.onMessage.addListener(function(msg, sender, callback) {
console.log(msg);
switch (msg.request) {
case 'gettopic':
getContent(callback);
break;
case 'bookmark':
addBookmark(msg.info.url, msg.info.title);
break;
};
});
}
main();
})();
| JavaScript | 0.000001 | @@ -3343,24 +3343,83 @@
k_enable) %7B%0A
+ setCSS('#keyboardShortcutHelper %7Bwidth: 300px;%7D');%0A
if (
@@ -3855,16 +3855,31 @@
-header%22
+ style=%22width:%22
%3EBookmar
|
743ff5a9a2d0b569b32ded46452673c01e789d7b | Add comments to the popover | app/assets/scripts/components/charts/popover.js | app/assets/scripts/components/charts/popover.js | 'use strict';
var React = require('react/addons');
var $ = require('jquery');
var _ = require('lodash');
function popover() {
var _id = _.uniqueId('ds-popover-');
var $popover = null;
var _working = false;
var _content = null;
var _prev_content = null;
var _x = null;
var _y = null;
var _prev_x = null;
var _prev_y = null;
this.setContent = function(ReactElement) {
_prev_content = _content;
_content = React.renderToStaticMarkup(
<div className="popover" id={_id}>
{ReactElement}
</div>
);
return this;
}
this.show = function(anchorX, anchorY) {
_prev_x = _x;
_prev_y = _y;
_x = anchorX;
_y = anchorY;
if (_working) return;
if (_content === null) {
console.warn('Content must be set before showing the popover.');
return this;
}
var changePos = !(_prev_x == _x && _prev_y == _y);
// Different content?
if (_content != _prev_content) {
$popover = $('#' + _id);
if ($popover.length > 0) {
$popover.replaceWith(_content);
}
else {
$popover = $(_content);
$('#site-canvas').append($popover);
}
// With a change in content, position has to change.
changePos = true;
}
if (changePos) {
_working = true;
$popover = $('#' + _id);
// Set position on next tick.
// Otherwise the popover has no spatiality.
setTimeout(function() {
var containerW = $('#site-canvas').outerWidth();
var sizeW = $popover.outerWidth();
var sizeH = $popover.outerHeight();
var leftOffset = anchorX - sizeW / 2;
var topOffset = anchorY - sizeH - 8;
// If the popover would be to appear outside the window on the right
// move it to the left by that amount.
// And add some padding.
var overflowR = (leftOffset + sizeW) - containerW ;
if (overflowR > 0) {
leftOffset -= overflowR + 16;
}
// Same for the left side.
if (leftOffset < 0) {
leftOffset = 16;
}
$popover
.css('left', leftOffset + 'px')
.css('top', topOffset + 'px')
.show();
_working = false;
}, 1);
}
return this;
}
this.hide = function() {
$('#' + _id).remove();
_content = null;
_prev_content = null;
_x = null;
_y = null;
_prev_x = null;
_prev_y = null;
return this;
}
return this;
};
module.exports = popover; | JavaScript | 0 | @@ -99,16 +99,201 @@
ash');%0A%0A
+/**%0A * All purpose popover.%0A * Positioned absolutely according to an anchor point.%0A *%0A * Usage:%0A * popover.setContent(content)%0A * popover.show(posX, posY);%0A * popover.hide();%0A *%0A */%0A
function
@@ -305,17 +305,16 @@
ver() %7B%0A
-%0A
var _i
@@ -418,36 +418,8 @@
ll;%0A
- var _prev_content = null;%0A
va
@@ -454,274 +454,1003 @@
;%0A
-var _prev_x = null;%0A var _prev_y = null;%0A%0A this.setContent = function(ReactElement) %7B%0A _prev_content = _content;%0A _content = React.renderToStaticMarkup(%0A %3Cdiv className=%22popover%22 id=%7B_id%7D%3E%0A %7BReactElement%7D%0A %3C/div%3E%0A );%0A return this;%0A %7D%0A
+// Previous values. Used to know if we need to reposition or update%0A // the popover.%0A var _prev_content = null;%0A var _prev_x = null;%0A var _prev_y = null;%0A%0A /**%0A * Sets the popover content.%0A * %0A * @param ReactElement%0A * Content for the popover. Can be anything supported by react. %0A */%0A this.setContent = function(ReactElement) %7B%0A _prev_content = _content;%0A _content = React.renderToStaticMarkup(%0A %3Cdiv className=%22popover%22 id=%7B_id%7D%3E%0A %7BReactElement%7D%0A %3C/div%3E%0A );%0A return this;%0A %7D%0A%0A /**%0A * Appends the popover to #site-canvas positioning it absolutely%0A * at the specified coordinates. %0A * If the popover already exists it will be repositioned.%0A * The anchor point for the popover is the bottom center with 8px of offset.%0A *%0A * Note: The popover needs to have content before being shown.%0A * %0A * @param anchorX%0A * Where to position the popover horizontally.%0A * @param anchorY%0A * Where to position the popover vertically.%0A */
%0A t
@@ -3143,16 +3143,67 @@
s;%0A %7D%0A%0A
+ /**%0A * Removes the popover from the DOM.%0A */%0A
this.h
|
9b98f673987257ba828a97e6d5feb0e7d35e50b2 | add semicolon in gulpfile | gulpfile.js | gulpfile.js | const gulp = require('gulp');
const minify = require('gulp-minify');
const babel = require('gulp-babel');
const concat = require('gulp-concat');
const clean = require('gulp-clean');
const rev = require('gulp-rev');
const runSequence = require('run-sequence');
const merge = require('gulp-merge-json');
const insert = require('gulp-insert');
gulp.task('minify', () =>
gulp
.src(['dex-opt.js'])
.pipe(babel())
.pipe(minify())
.pipe(gulp.dest('.tmp'))
);
gulp.task('concat', () =>
gulp
.src([".tmp/config.json", ".tmp/dex-opt-min.js"])
.pipe(concat('dexecure.js'))
.pipe(insert.prepend("var dexecure = "))
.pipe(gulp.dest('.tmp'))
);
gulp.task('move', () =>
gulp
.src(['dex-opt.js', 'index.html'])
.pipe(gulp.dest('.tmp'))
);
gulp.task('rev', () =>
gulp
.src('.tmp/dexecure.js')
.pipe(rev())
.pipe(gulp.dest('dist'))
.pipe(rev.manifest())
.pipe(gulp.dest('.tmp'))
);
gulp.task('clean', () =>
gulp
.src(['dist', '.tmp'], {read: false})
.pipe(clean())
);
gulp.task('html', () => {
var fs = require('fs');
var scriptName = JSON.parse(fs.readFileSync('.tmp/rev-manifest.json'))["dexecure.js"];
console.log(scriptName);
var scriptToInject = `<script>var DEXECURE_URL = "/${scriptName}";</script>`;
return gulp
.src('.tmp/index.html')
.pipe(insert.prepend(scriptToInject))
.pipe(gulp.dest("dist"));
});
gulp.task('config', () => {
gulp
.src(['config.default.json', 'config.user.json'])
.pipe(merge('config.json'))
.pipe(gulp.dest('.tmp'))
});
gulp.task('default', () => {
runSequence('clean', 'move', ['minify', 'config'], 'concat', 'rev', 'html');
}); | JavaScript | 0.000379 | @@ -568,16 +568,32 @@
cure.js'
+, %7BnewLine: ';'%7D
))%0A%09.pip
|
a2536a05198f6b05100965c268c9e1430546b0f6 | Fix footer spacing | src/components/Footer.js | src/components/Footer.js | import React from 'react'
import { Flex, Box, Heading, Text, Link as A } from '@hackclub/design-system'
import { Link } from 'react-static'
import Icon from './Icon'
import { mx, geo } from '../theme'
const Base = Flex.withComponent('footer').extend`
${props => geo(props.theme.colors.snow)};
div { flex: 1 1 auto; }
`
const LeftCol = Box.withComponent('aside').extend.attrs({
px: 3,
mb: 2,
w: [1, 1 / 2],
align: ['left', 'right']
})``
const RightCol = Box.withComponent('article').extend.attrs({
px: 3,
w: [1, 1 / 2]
})``
const Service = ({ href, icon, ...props }) => (
<A target="_blank" href={href} mx={2} title={icon} {...props}>
<Icon name={icon} size={32} fill="muted" alt={icon} />
</A>
)
const Footer = () => (
<Base flexDirection="column" alignItems="center" p={[4, 5]}>
<Flex w={1} mx={-3} wrap>
<LeftCol>
<Heading.h3 bold m={0}>
Learn like a hacker.
</Heading.h3>
</LeftCol>
<RightCol>
<Flex align="center" mx={-2}>
<Service href="/slack_invite" icon="slack" />
<Service href="https://twitter.com/starthackclub" icon="twitter" />
<Service href="https://github.com/hackclub" icon="github" />
<Service
href="https://www.instagram.com/starthackclub"
icon="instagram"
/>
<Service
href="https://www.facebook.com/Hack-Club-741805665870458"
icon="facebook"
/>
<Service href="mailto:team@hackclub.com" icon="mail_outline" />
</Flex>
</RightCol>
</Flex>
<Flex w={1} mx={-3} mt={3} wrap>
<LeftCol>
<Heading.h3 bold m={0}>
Hack Club HQ
</Heading.h3>
</LeftCol>
<RightCol>
<Text m={0}>
576 Natoma St<br />San Francisco, CA 94103
</Text>
<Text>Nonprofit EIN: 81-2908499</Text>
<Text>
<A href="https://conduct.hackclub.com" color="info" underline>
Read our Code of Conduct
</A>
</Text>
<Text f={1} color="muted" mt={3}>
© {new Date().getFullYear()} Hack Club
</Text>
</RightCol>
</Flex>
</Base>
)
export default Footer
| JavaScript | 0.000001 | @@ -1848,16 +1848,23 @@
%3CText
+ my=%7B2%7D
%3ENonprof
@@ -1898,24 +1898,31 @@
%3CText
+ my=%7B2%7D
%3E%0A
@@ -2087,20 +2087,19 @@
muted%22 m
-t
=%7B
-3
+0
%7D%3E%0A
|
960ce6940c845353f7e73895513f278613a4067e | add additional type | lib/node-test-pull-request.js | lib/node-test-pull-request.js | 'use strict'
const request = require('request')
const Build = require('./build')
const utils = require('./utils')
const chalk = require('chalk')
const columnify = require('columnify')
const archy = require('archy')
module.exports = NodeTestPR
function NodeTestPR(opts) {
if (!(this instanceof NodeTestPR))
return new NodeTestPR(opts)
opts = opts || {}
this.opts = opts
this.id = opts.id
this.depth = opts.depth || 5
this.creds = {
username: opts.user
, password: opts.token
}
this.status = ''
this.duration = ''
this.url = this.getUrl()
this.rebaseOnto = ''
this.startedBy = ''
this.prUrl = ''
}
NodeTestPR.prototype.getUrl = function getUrl() {
return utils.getBuildUrl(this.id, 'node-test-pull-request', this.depth)
}
NodeTestPR.prototype.fetch = function fetch(cb) {
const opts = {
uri: this.getUrl()
, json: true
, auth: this.creds
}
request.get(opts, (err, res, body) => {
if (err) return cb(err)
if (res.statusCode !== 200) {
const er = new Error(`Received non-200 status code: ${res.statusCode}`)
er.body = body
return cb(er)
}
cb(null, body)
})
}
NodeTestPR.prototype.buildToJSON = function buildToJSON(build) {
const out = {
label: utils.formatType(build.result, build.name)
, nodes: build.nodes.map((i) => {
return this.buildToJSON(i)
})
}
if (build.duration)
out.label += ` (${build.duration})`
if (build.url && build.result === 'FAILURE') {
out.label += ` [${chalk.underline(build.url)}]`
}
return out
}
NodeTestPR.print = function(opts) {
const pr = new NodeTestPR(opts)
pr.fetch((err, res) => {
if (err) throw err
const data = []
pr.status = res.building
? 'building'
: utils.formatType(res.result)
pr.duration = utils.parseMS(res.duration)
const params = utils.getBuildParams(res)
pr.rebaseOnto = params.rebaseOnto
pr.startedBy = params.startedBy
pr.prUrl = params.prUrl
printLine('status', pr.status)
printLine('duration', pr.duration)
printLine('url', pr.url)
printLine('id', pr.id)
printLine('rebase onto', pr.rebaseOnto)
printLine('started by', pr.startedBy)
printLine('pull request', pr.prUrl)
console.log(columnify(data, {
showHeaders: false
, config: {
heading: {
align: 'right'
}
}
}))
console.log()
const build = new Build(res, 'node-test-pull-request')
console.log(archy(pr.buildToJSON(build)))
function printLine(heading, val) {
data.push({
heading: chalk.cyan(` ${heading} `)
, value: val
})
}
})
}
| JavaScript | 0.000011 | @@ -1690,16 +1690,76 @@
a = %5B%5D%0A%0A
+ const build = new Build(res, 'node-test-pull-request')%0A%0A
pr.s
@@ -1791,18 +1791,36 @@
?
-'building'
+utils.formatType('BUILDING')
%0A
@@ -1895,24 +1895,42 @@
es.duration)
+ %7C%7C build.duration
%0A const p
@@ -2492,67 +2492,8 @@
()%0A%0A
- const build = new Build(res, 'node-test-pull-request')%0A
|
fc06503d2030868f37b8df410ba40af5a4c3533f | Test Update | gulpfile.js | gulpfile.js | /* Dev-Dependencies */
var
gulp = require('gulp'),
sourcemaps = require('gulp-sourcemaps'),
babel = require('gulp-babel'),
mocha = require('gulp-spawn-mocha'),
jshint = require('gulp-jshint'),
beautify = require('gulp-jsbeautify'),
shell = require('gulp-shell'),
ghPages = require('gulp-gh-pages'),
rimraf = require('rimraf'),
config = require('./config'),
semver = require('semver'),
version = require('node-version').long,
isHarmony = !semver.lt(version.toString(), '0.11.0'),
changelog = require('gulp-changelog');
/*
Copyright 2013 Daniel Wirtz <dcode@dcode.io>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* node-harmonize (c) 2013 Daniel Wirtz <dcode@dcode.io>
* Released under the Apache License, Version 2.0
* see: https://github.com/dcodeIO/node-harmonize for details
*/
var child_process = require("child_process");
(function harmony() {
if (typeof Proxy == 'undefined') { // We take direct proxies as our marker
if (!isHarmony) return;
var features = ['--harmony', '--harmony-proxies'];
console.log('Enabled Harmony');
var node = child_process.spawn(process.argv[0], features.concat(process.argv.slice(1)), { stdio: 'inherit' });
node.on("close", function(code) {
process.exit(code);
});
// Interrupt process flow in the parent
process.once("uncaughtException", function(e) {});
throw "harmony";
}
})();
/** Backs up the files in case of emergency! */
gulp.task('backup', function () {
return gulp
.src('lib/**/**/**.js')
.pipe(gulp.dest('./.backup'));
});
gulp.task('recover', function () {
return gulp
.src('./.backup/**/**/*.js')
.pipe(gulp.dest('lib/'));
});
/* Formats the files */
gulp.task('beautify', ['backup'], function () {
return gulp.src('./lib/**/**/*.js')
.pipe(beautify(config.beautify))
.pipe(gulp.dest('./lib'));
});
/*
* Clean the docs themes folder
*/
gulp.task('clean-docs', ['gh-pages'], function (cb) {
rimraf('./docs/themes', cb);
});
/*
* Create the gh-pages branch - wont push automatically
*/
gulp.task('gh-pages', ['doc'], function () {
return gulp.src('./docs/**/*')
.pipe(ghPages());
});
/* Checks the coding style and builds from ES6 to ES5*/
gulp.task('lib', ['beautify'], function () {
return gulp.src('./lib/**/**/*.js')
.pipe(jshint(config.jshint))
.pipe(jshint.reporter('jshint-stylish'))
.pipe(jshint.reporter('fail'))
.pipe(sourcemaps.init())
.pipe(babel())
.pipe(sourcemaps.write('./source maps/'))
.pipe(gulp.dest('./'));
});
/* Watches for changes and applies the build task*/
gulp.task('watch', function () {
return gulp.watch('./lib/**/**/*.js', ['build']);
});
/* Runs tests */
gulp.task('test', ['lib'], function (cb) {
var source;
if (isHarmony)
source = gulp.src('./tests/**/*.js');
else source = gulp.src([
'./tests/express/index.js',
'./tests/hapi/index.js'
]);
return source.pipe(mocha());
});
gulp.task('changelog', function (cb) {
changelog(require('./package.json')).then(function (stream) {
stream.pipe(gulp.dest('./')).on('end', cb);
});
});
/*
* Runs the doxx command and builds the docs
* Install other themes here, generate docs for each.
*/
gulp.task('doc', ['build'], shell.task([
(function(){
var doc = 'node_modules/mr-doc/bin/mr-doc',
cmd = {
source: ' -s lib/',
output: ' -o docs/',
name:' -n "gengo.js/accept"',
theme:' -t cayman'
};
return doc + cmd.source + cmd.output + cmd.name + cmd.theme;
})()
]));
gulp.task('default', ['backup', 'beautify', 'lib', 'watch']);
gulp.task('build', ['backup', 'beautify', 'lib', 'test']);
gulp.task('docs', ['build', 'doc', 'gh-pages', 'clean-docs']); | JavaScript | 0 | @@ -1552,48 +1552,8 @@
'%5D;%0A
- console.log('Enabled Harmony');%0A
@@ -1663,24 +1663,70 @@
nherit' %7D);%0A
+ console.log('Enabled Harmony', node);%0A
node
|
a3ac2b6dfe4e199daccb70beefec47624467d689 | Add links to the license and GitHub profile to the footer | src/components/Footer.js | src/components/Footer.js | import React from 'react';
import { Container } from 'semantic-ui-react';
const Footer = () =>
<div>
<Container textAlign="center">
Free & Open Source (MIT)
<br />
Copyright © 2017 laurids-reichardt
<br />
<br />
</Container>
</div>;
export default Footer;
| JavaScript | 0 | @@ -161,67 +161,221 @@
rce
-(MIT)%0A %3Cbr /%3E%0A Copyright %C2%A9 2017 laurids-reichardt
+ (%0A %3Ca href=%22https://github.com/laurids-reichardt/Currency-Exchange-Rates/blob/master/LICENSE%22%3EMIT%3C/a%3E)%0A %3Cbr /%3E%0A Copyright %C2%A9 2017 %3Ca href=%22https://github.com/laurids-reichardt%22%3Elaurids-reichardt%3C/a%3E
%0A
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.