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 |
|---|---|---|---|---|---|---|---|
f0979ab1b9520edbd5b0fd0d1a9ded57a39550e6 | Ajuste para conectar ao backend da amazon | mobile/www/js/services/applicationService.js | mobile/www/js/services/applicationService.js | angular
.module('woole')
.factory('ApplicationService', ['$http', '$q', function($http, $q) {
return {
apiPath: 'http://192.168.0.10:3200/api',
buildMapRoute: function(o, d) {
var data = {o:o, d:d};
return this.buildPostRequest('/map', data, 'An error occured while fetching the route');
},
listAllFavorite: function() {
return this.buildGetRequest('/favorites', [], 'An error occured while fetching the favorites');
},
findAddress: function(address) {
return this.buildGetRequest('/geo', [address], 'An error occured while fetching the address');
},
loadRoute: function(waypoints) {
var deferred = $q.defer();
var url = 'http://router.project-osrm.org/viaroute?';
for(var i=0; i<waypoints.length;i++) {
url = url + '&loc=' + waypoints[i].coordinates[1] + ',' + waypoints[i].coordinates[0];
}
$http.get(url + '&instructions=false&alt=false').success(function(data) {
deferred.resolve(data);
}).error(function() {
deferred.reject(errMsg);
});
return deferred.promise;
},
buildPostRequest: function(path, args, errMsg) {
var deferred = $q.defer();
$http.post(this.buildUrl(path, []), args).success(function(data) {
deferred.resolve(data);
}).error(function() {
deferred.reject(errMsg);
});
return deferred.promise;
},
buildGetRequest: function(path, args, errMsg) {
var deferred = $q.defer();
$http.get(this.buildUrl(path, args)).success(function(data) {
deferred.resolve(data);
}).error(function() {
deferred.reject(errMsg);
});
return deferred.promise;
},
buildUrl: function(path, params) {
var queryString = '';
params.forEach(function(element) {
queryString += '/' + element
}, this);
return this.apiPath + path + queryString;
}
}
}]); | JavaScript | 0 | @@ -145,19 +145,21 @@
p://
-192.168.0.1
+54.200.242.20
0:32
|
228e154347162ae13d87e527004f1caffaed3432 | Delete handlers import from GameOver.js | src/states/GameOver.js | src/states/GameOver.js | import * as handler from '../modules/handlers';
import displayText from '../modules/displayText';
import * as reset from '../helpers/reset';
class GameOver extends Phaser.State {
create() {
this.game.add.tileSprite(0, 0, 800, 600, 'game_over');
this.game.input.onTap.addOnce(this.restartGame, this);
}
restartGame() {
reset.all();
this.game.state.start("Main");
}
}
export default GameOver;
| JavaScript | 0.000001 | @@ -1,52 +1,4 @@
-import * as handler from '../modules/handlers';%0A
impo
|
065e63e88fb2c5bfeae525e35191230b3f66541b | add a message if there are no todos yet | src/root/app/todo/components.js | src/root/app/todo/components.js | 'use strict';
Vue.component('todo-app', {
template: `<div class='todo-app'>
<div class="add-new-container" style="margin-top: 5px;">
<div class="add-new">
<div class="add-new-title">Add Todo</div>
<form>
<div class="form-group container">
<textarea v-model="newTodo.text" placeholder="text" cols=50 rows=3></textarea>
<button
class="btn dark-b"
v-on:click="addTodo()"
title="add todo">
[<i class="fa fa-plus" aria-hidden="true">]</i>
</button>
</div>
</form>
</div>
</div>
<div class="todo-container">
<div class="todos-title">TODOS</div>
<ul id="todos">
<li v-for="todo in todos">
<pre class="todo-title">{{ todo.text }}</pre>
<div class="btn-group" style="float:left;">
<button
class="btn light-b"
v-on:click="removeTodo(todo)"
title="remove todo">
[<i class="fa fa-check" aria-hidden="true"></i>|
</button>
<button
class="btn light-b"
v-on:click="editTodo(todo)"
title="edit todo">
<i class="fa fa-pencil" aria-hidden="true"></i>]
</button>
</div>
<div v-if="todo.editing" class="edit-container dark-shadow">
<div class="add-new">
<div class="add-new-title">Edit Todo</div>
<form>
<div class="form-group container">
<textarea v-model="todo.text" placeholder="text" cols=50 rows=5></textarea>
<button
class="btn blue-b"
v-on:click="closeEdit(todo)"
title="edit todo">
[Save]
</button>
</div>
</form>
</div>
</div>
</li>
</ul>
</div>
</div>`,
methods: {
addTodo: function(){
this.todos.push({
text: this.newTodo.text,
editing: false
});
this.newTodo.text = 'text';
this.save();
},
removeTodo: function(todo){
let index = this.todos.indexOf(todo);
if(index >= 0){
this.todos.splice(index, 1);
}
this.save();
},
editTodo: function(todo){
todo.editing = true;
},
closeEdit: function(todo){
todo.editing = false;
this.save();
},
save: function(){
boss.fs.set_file('/home/' + this.client.user.username + '/documents', 'todos.json', JSON.stringify(this.todos), client.user);
}
},
props: ['client'],
data: function(){
return {
todos: [],
newTodo: {
text: 'text'
}
}
},
mounted: function(){
let json;
try{
json = boss.fs.get_file('/home/' + this.client.user.username + '/documents','todos.json');
} catch(err){
json = "[]";
boss.fs.set_file('/home/' + this.client.user.username + '/documents', 'todos.json', json, client.user);
}
this.todos = JSON.parse(json);
}
}); | JavaScript | 0.000001 | @@ -1043,32 +1043,146 @@
%3Cul id=%22todos%22%3E%0A
+ %3Cp v-if=%22todos.length === 0%22%3EYou haven't created any TODOs yet. Come on, get started!%3C/p%3E%0A
|
14c881b6f0810424c26fa868132ead439b8a762a | Handle empty thumbnail data | web/src/js/components/Search/WikipediaQuery.js | web/src/js/components/Search/WikipediaQuery.js | import React from 'react'
import PropTypes from 'prop-types'
import { get } from 'lodash/object'
import fetchWikipediaResults from 'js/components/Search/fetchWikipediaResults'
class WikipediaQuery extends React.Component {
constructor(props) {
super(props)
this.state = {
queryInProgress: false,
responseData: null,
}
}
componentDidMount() {
this.queryWikipedia()
}
componentDidUpdate(prevProps) {
// Fetch Wikipedia data if a query exists and has changed.
if (this.props.query && this.props.query !== prevProps.query) {
this.queryWikipedia()
}
}
async queryWikipedia() {
const { query } = this.props
if (!query) {
return
}
this.setState({
queryInProgress: true,
})
console.log(`Querying Wikipedia with query ${query}`)
const results = await fetchWikipediaResults(query)
this.setState({
responseData: results,
queryInProgress: false,
})
}
render() {
const { responseData, queryInProgress } = this.state
const pageData = get(responseData, 'query.pages[0]')
if (queryInProgress) {
return null
}
if (!pageData) {
return <div>Nothing found</div>
}
// console.log(pageData)
const {
title,
description,
extract,
fullurl: pageURL,
thumbnail: { source: thumbnailURL },
} = pageData
return (
<div>
<div>{title}</div>
<div>{description}</div>
<img
src={thumbnailURL}
alt={'Thumbnail from Wikipedia'}
style={{
maxHeight: 180,
}}
/>
<p>{extract}</p>
<a href={pageURL}>Read more</a>
<p>
From <a href={pageURL}>Wikipedia</a>
</p>
<p>
Content under{' '}
<a
href={'https://creativecommons.org/licenses/by-sa/3.0/'}
target="_blank"
rel="noopener noreferrer"
>
CC BY-SA
</a>
</p>
</div>
)
}
}
WikipediaQuery.propTypes = {
query: PropTypes.string.isRequired,
}
WikipediaQuery.defaultProps = {}
export default WikipediaQuery
| JavaScript | 0.000061 | @@ -1355,18 +1355,23 @@
ailURL %7D
+ = %7B%7D
,%0A
-
%7D =
@@ -1456,32 +1456,60 @@
cription%7D%3C/div%3E%0A
+ %7BthumbnailURL ? (%0A
%3Cimg%0A
@@ -1515,16 +1515,18 @@
+
+
src=%7Bthu
@@ -1536,16 +1536,18 @@
ailURL%7D%0A
+
@@ -1591,16 +1591,18 @@
+
+
style=%7B%7B
@@ -1602,16 +1602,18 @@
tyle=%7B%7B%0A
+
@@ -1642,16 +1642,18 @@
+
+
%7D%7D%0A
@@ -1659,10 +1659,30 @@
-/%3E
+ /%3E%0A ) : null%7D
%0A
|
75fd5af85c4c4bea520215f356f1db894632479e | Validate query document and output Xcode compatible errors | src/parseQueryDocument.js | src/parseQueryDocument.js | import {
parse,
visit,
visitWithTypeInfo,
TypeInfo
} from 'graphql';
export default function parseQueryDocument(queryDocument, schema) {
const typeInfo = new TypeInfo(schema);
const ast = parse(queryDocument);
function source(location) {
return queryDocument.slice(location.start, location.end);
}
return visit(ast, visitWithTypeInfo(typeInfo, {
leave: {
Name: node => node.value,
Document: node => node.definitions,
OperationDefinition: ({ loc, name, operation, variableDefinitions, selectionSet }) => {
return { name, operation, source: source(loc), variableDefinitions, selectionSet };
},
VariableDefinition: node => {
const type = typeInfo.getInputType();
return { name: node.variable, type: type };
},
Variable: node => node.name,
SelectionSet: ({ selections }) => selections,
Field: ({ kind, alias, name, arguments: args, directives, selectionSet }) => {
const type = typeInfo.getType();
return { kind, alias, name, type: type, selectionSet: selectionSet ? selectionSet : undefined }
}
}
}));
}
| JavaScript | 0.000002 | @@ -11,16 +11,28 @@
parse,%0A
+ validate,%0A
visit,
@@ -163,75 +163,416 @@
nst
-typeInfo = new TypeInfo(schema);%0A%0A const ast = parse(
+ast = parse(queryDocument);%0A%0A const validationErrors = validate(schema, ast);%0A if (validationErrors && validationErrors.length %3E 0) %7B%0A for (const error of validationErrors) %7B%0A const location = error.locations%5B0%5D;%0A console.log(%60graphql:$%7Blocation.line%7D: error: $%7Berror.message%7D%60);%0A %7D%0A throw Error(%22Validation of GraphQL
query
-D
+ d
ocument
+ failed%22);%0A %7D%0A%0A const typeInfo = new TypeInfo(schema
);%0A%0A
|
fe1b4f912da67dae2c24db2ed5a7826f4ba2d0a0 | Update api_5_call_2.js | src/api_5_call_2.js | src/api_5_call_2.js | function getResult(callback, json) { var token = ''; console.log('call_id : api_5_call_2'); var input = json.input; var all_required = false; if(input.spotify.artist.id){ all_required = true; } if(all_required){ var call = 'https://api.spotify.com/v1/artists/'+input.spotify.artist.id+'/top-tracks?country=FR'; require('request')(call, function (error, response, body) { if (!error && response.statusCode == 200) { var info = JSON.parse(body); if(!json.input.spotify){ json.input.spotify = {}; } if(!json.input.spotify.track){ json.input.spotify.track = {}; }json.input.spotify.track.previewUrl = info.tracks[0].preview_url; json.index = json.index+1; if(json.step[json.index].nb=='end'){ callback(json.input[json.query]); }else{ var action_module = require('./'+ json.step[json.index].call_id + '.js'); action_module.getResult(function(result) { callback(result); },json); } }else{ callback('the request failed'); } }); } } exports.getResult = getResult;
| JavaScript | 0.000003 | @@ -29,16 +29,20 @@
json) %7B
+%0A
var tok
@@ -49,16 +49,20 @@
en = '';
+%0A
console
@@ -92,16 +92,20 @@
all_2');
+%0A
var inp
@@ -120,16 +120,20 @@
n.input;
+%0A
var all
@@ -150,19 +150,24 @@
= false;
+%0A
if
+
(input.s
@@ -183,17 +183,26 @@
tist.id)
-%7B
+ %7B%0A
all_req
@@ -214,21 +214,30 @@
= true;
+%0A %7D%0A
-%7D
if
+
(all_req
@@ -242,17 +242,26 @@
equired)
-%7B
+ %7B%0A
var cal
@@ -301,17 +301,19 @@
rtists/'
-+
+ +
input.sp
@@ -327,17 +327,19 @@
rtist.id
-+
+ +
'/top-tr
@@ -355,16 +355,24 @@
try=FR';
+%0A
require
@@ -397,17 +397,16 @@
function
-
(error,
@@ -422,16 +422,28 @@
body) %7B
+%0A
if (!er
@@ -478,16 +478,32 @@
= 200) %7B
+%0A
var inf
@@ -523,19 +523,36 @@
e(body);
+%0A
if
+
(!json.i
@@ -564,17 +564,38 @@
spotify)
-%7B
+ %7B%0A
json.in
@@ -615,13 +615,46 @@
%7B%7D;
+%0A %7D%0A
-%7D
if
+
(!js
@@ -676,17 +676,38 @@
y.track)
-%7B
+ %7B%0A
json.in
@@ -729,18 +729,51 @@
ck = %7B%7D;
+%0A %7D%0A
-%7D
json.inp
@@ -829,16 +829,32 @@
iew_url;
+%0A
json.in
@@ -873,14 +873,33 @@
ndex
-+1;
+ + 1;%0A
if
+
(jso
@@ -923,17 +923,112 @@
%5D.nb
+
==
+
'end')
-%7B
+ %7B%0A console.log('result : api_5_call_2 :',json.input);%0A
cal
@@ -1057,23 +1057,61 @@
query%5D);
+%0A
%7D
+
else
-%7B
+ %7B%0A
var act
@@ -1135,16 +1135,17 @@
ire('./'
+
+ json.s
@@ -1177,16 +1177,36 @@
'.js');
+%0A
action_
@@ -1244,44 +1244,135 @@
t) %7B
- callback(result);
+%0A callback(result);%0A
%7D,
+
json);
+%0A %7D%0A
-%7D
%7D
+
else
-%7B
+ %7B%0A
cal
@@ -1403,19 +1403,43 @@
d');
- %7D %7D); %7D %7D
+%0A %7D%0A %7D);%0A %7D%0A%7D%0A
expo
|
ded9826dfdfadf6e8250838fd75b1312d54c5e95 | Add test module for globals | tests/main.js | tests/main.js | var assertionsModifier = require('../src/modifiers/assertions');
var testsModifier = require('../src/modifiers/tests');
var assert = require('assert');
var fs = require('fs');
var noOfData = 2;
var oneToTenArray = [];
for(var i = 1; i <= noOfData; i++) {
oneToTenArray.push(i);
}
var testData = oneToTenArray.map(function (i) {
return fs.readFileSync('tests/data/' + i + '/actual.js').toString();
})
var expectedData = oneToTenArray.map(function (i) {
return fs.readFileSync('tests/data/' + i + '/expected.js').toString();
})
describe('Assertions modules', function () {
it('should have a working assertion modifier', function () {
for(var i = 0; i < 1; i++) {
var result = assertionsModifier(testData[i]);
assert.equal(result, expectedData[i]);
}
});
});
describe('Tests working', function () {
it('should have a workign tests modifier', function () {
for(var i = 1; i < 2; i++) {
var result = testsModifier(testData[i]);
assert.equal(result, expectedData[i]);
}
});
});
| JavaScript | 0 | @@ -109,24 +109,83 @@
rs/tests');%0A
+var globalsModifier = require('../src/modifiers/globals');%0A
var assert =
@@ -243,17 +243,17 @@
fData =
-2
+3
;%0A%0Avar o
@@ -1037,28 +1037,260 @@
ctedData%5Bi%5D);%0A%09%09%7D%0A%09%7D);%0A%7D);%0A%0A
+describe('Globals working', function () %7B%0A%09it('should have a workign tests modifier', function () %7B%0A%09%09for(var i = 2; i %3C 3; i++) %7B%0A%09%09%09var result = globalsModifier(testData%5Bi%5D);%0A%09%09%09assert.equal(result, expectedData%5Bi%5D);%0A%09%09%7D%0A%09%7D);%0A%7D);%0A
|
7830a1d728f63d2d286c5bfe7ddd268fc7ac1dd6 | Add horizontal padding to button | src/scripts/content/intercom.js | src/scripts/content/intercom.js | 'use strict';
togglbutton.render('.conversation__card__content-expanded__controls .inbox__conversation-controls__pane-selector:not(.toggl)',
{ observe: true },
function (elem) {
if (elem.querySelector('.toggl-button')) {
// With the way this UI renders, we must check for existence of the button.
return;
}
const root = elem.closest('.card.conversation__card');
const descriptionSelector = () => {
const description = $('.inbox__card__header__title', root);
return description ? description.textContent.trim().replace(/ +/g, ' ') : '';
};
const link = togglbutton.createTimerLink({
className: 'intercom',
description: descriptionSelector
});
// Stop button being re-rendered while trying to click. Intercom has some kind of handlers doing things.
link.addEventListener('mousedown', (e) => {
e.preventDefault();
e.stopPropagation();
});
elem.appendChild(link);
});
| JavaScript | 0 | @@ -583,16 +583,59 @@
%7D;%0A%0A
+ /**%0A * @type %7BHTMLElement%7D%0A */%0A
cons
@@ -744,24 +744,62 @@
ctor%0A %7D);
+%0A link.style.paddingRight = '15px';
%0A%0A // Sto
|
d4077dd4edb31658ab529c440c4efbfd3ddceb02 | Replace multiple characters | tests/test.js | tests/test.js | var iiIii = require('../js/i-i-i-i-i');
exports.empty_returns_empty = function(test) {
test.equal("", iiIii([], ""));
test.done();
};
exports.space_returns_space = function(test) {
test.equal(" ", iiIii([], " "));
test.equal("\n", iiIii([], "\n"));
test.done();
};
exports.non_special_character_replaced = function(test) {
test.equal("_", iiIii([], "a"));
test.equal("_", iiIii([], "5"));
test.done();
};
| JavaScript | 0.999999 | @@ -414,28 +414,288 @@
%225%22));%0A test.done();%0A%7D;%0A
+%0Aexports.replace_multiple_characters = function(test) %7B%0A test.equal(%22___%22, iiIii(%5B%5D, %22abc%22));%0A test.done();%0A%7D;%0A%0Aexports.replace_multiple_characters_with_spaces = function(test) %7B%0A test.equal(%22_ __%5Cn__%22, iiIii(%5B%5D, %22a bc%5Cnde%22));%0A test.done();%0A%7D;%0A
|
aaaa90ab362a868affe922331e2344bdf5fd6655 | Move setup code to beforeEach | spec/log_tree.spec.js | spec/log_tree.spec.js | // Copyright (c) 2017 The Regents of the University of Michigan.
// All Rights Reserved. Licensed according to the terms of the Revised
// BSD License. See LICENSE.txt for details.
const log_tree = require("../lib/log_tree");
describe("a log_tree object", function() {
var tree;
describe("when created from nothing", function() {
beforeEach(function() {
tree = log_tree();
});
it("has a length of 0", function() {
expect(tree.length).toBe(0);
});
it("has a name of ''", function() {
expect(tree.name).toBe("");
});
it("remembers a name change", function() {
tree.name = "matt";
expect(tree.name).toBe("matt");
});
it("doesn't remember a length change", function() {
tree.length = 1;
expect(tree.length).toBe(0);
});
});
describe("when created with a name", function() {
it("remembers its name", function() {
tree = log_tree("name");
expect(tree.name).toBe("name");
});
});
});
| JavaScript | 0 | @@ -869,33 +869,19 @@
-it(%22remembers its name%22,
+beforeEach(
func
@@ -916,24 +916,75 @@
ee(%22name%22);%0A
+ %7D);%0A%0A it(%22remembers its name%22, function() %7B%0A
expect
|
4d5c4ddf8f0c86fb1e00a3d60c35b420a0bca84c | Update mode-verilog.js | src-min-noconflict/mode-verilog.js | src-min-noconflict/mode-verilog.js | -ace.define("ace/mode/verilog_highlight_rules", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text_highlight_rules"], function(e, t, n) {
"use strict";
var r = e("../lib/oop"),
i = e("./text_highlight_rules").TextHighlightRules,
s = function() {
var e = "if|endif|else|or",
t = "use",
n = "near|with|around|mention",
r = this.createKeywordMapper({
"invalid": n,
keyword: e,
"constant.language": t
}, "identifier", !0);
this.$rules = {
start: [{
token: "comment",
regex: "//.*$"
}, {
token: "comment.start",
regex: "/\\*",
next: [{
token: "comment.end",
regex: "\\*/",
next: "start"
}, {
defaultToken: "comment"
}]
}, {
token: "string",
regex: '".*?"'
}, {
token: "string",
regex: "'.*?'"
}, {
token: "constant.numeric",
regex: "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
}, {
token: r,
regex: "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
}, {
token: "keyword.operator",
regex: "\\+|\\-|\\/|\\/\\/|%|<@>|@>|<@|&|\\^|~|<|>|<=|=>|==|!=|<>|="
}, {
token: "paren.lparen",
regex: "[\\(]"
}, {
token: "paren.rparen",
regex: "[\\)]"
}, {
token: "text",
regex: "\\s+"
}]
}, this.normalizeRules()
};
r.inherits(s, i), t.VerilogHighlightRules = s
}), ace.define("ace/mode/verilog", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text", "ace/mode/verilog_highlight_rules", "ace/range"], function(e, t, n) {
"use strict";
var r = e("../lib/oop"),
i = e("./text").Mode,
s = e("./verilog_highlight_rules").VerilogHighlightRules,
o = e("../range").Range,
u = function() {
this.HighlightRules = s, this.$behaviour = this.$defaultBehaviour
};
r.inherits(u, i),
function() {
this.lineCommentStart = "//", this.blockComment = {
start: "/*",
end: "*/"
}, this.$id = "ace/mode/verilog"
}.call(u.prototype), t.Mode = u
})
| JavaScript | 0 | @@ -462,15 +462,12 @@
%22
-invalid
+list
%22: n
|
0d97e3ec10574b5150f1fe1ebe08f6de6f7f33d7 | Enable transformImageUri for image references (#130) | src/ast-to-react.js | src/ast-to-react.js | 'use strict'
const React = require('react')
const xtend = require('xtend')
function astToReact(node, options, parent = {}, index = 0) {
if (node.type === 'text') {
return node.value
}
const renderer = options.renderers[node.type]
if (typeof renderer !== 'function' && typeof renderer !== 'string') {
throw new Error(`Renderer for type \`${node.type}\` not defined or is not renderable`)
}
const pos = node.position.start
const key = [node.type, pos.line, pos.column].join('-')
const nodeProps = getNodeProps(node, key, options, renderer, parent, index)
return React.createElement(
renderer,
nodeProps,
nodeProps.children || resolveChildren() || undefined
)
function resolveChildren() {
return (
node.children &&
node.children.map((childNode, i) =>
astToReact(childNode, options, {node, props: nodeProps}, i)
)
)
}
}
// eslint-disable-next-line max-params, complexity
function getNodeProps(node, key, opts, renderer, parent, index) {
const props = {key}
// `sourcePos` is true if the user wants source information (line/column info from markdown source)
if (opts.sourcePos && node.position) {
props['data-sourcepos'] = flattenPosition(node.position)
}
const ref = node.identifier ? opts.definitions[node.identifier] || {} : null
switch (node.type) {
case 'root':
assignDefined(props, {className: opts.className})
break
case 'heading':
props.level = node.depth
break
case 'list':
props.start = node.start
props.ordered = node.ordered
props.tight = !node.loose
break
case 'listItem':
props.checked = node.checked
props.tight = !node.loose
props.children = (props.tight ? unwrapParagraphs(node) : node.children).map((childNode, i) => {
return astToReact(childNode, opts, { node: node, props: props }, i)
})
break
case 'definition':
assignDefined(props, {identifier: node.identifier, title: node.title, url: node.url})
break
case 'code':
assignDefined(props, {language: node.lang})
break
case 'inlineCode':
props.children = node.value
props.inline = true
break
case 'link':
assignDefined(props, {
title: node.title || undefined,
href: opts.transformLinkUri ? opts.transformLinkUri(node.url, node.children, node.title) : node.url
})
break
case 'image':
assignDefined(props, {
alt: node.alt || undefined,
title: node.title || undefined,
src: opts.transformImageUri ? opts.transformImageUri(node.url, node.children, node.title, node.alt) : node.url
})
break
case 'linkReference':
assignDefined(
props,
xtend(ref, {
href: opts.transformLinkUri ? opts.transformLinkUri(ref.href) : ref.href
})
)
break
case 'imageReference':
assignDefined(props, {
src: ref.href,
title: ref.title || undefined,
alt: node.alt || undefined
})
break
case 'table':
case 'tableHead':
case 'tableBody':
props.columnAlignment = node.align
break
case 'tableRow':
props.isHeader = parent.node.type === 'tableHead'
props.columnAlignment = parent.props.columnAlignment
break
case 'tableCell':
assignDefined(props, {
isHeader: parent.props.isHeader,
align: parent.props.columnAlignment[index]
})
break
case 'virtualHtml':
props.tag = node.tag
break
case 'html':
// @todo find a better way than this
props.isBlock = node.position.start.line !== node.position.end.line
props.escapeHtml = opts.escapeHtml
props.skipHtml = opts.skipHtml
break
default:
}
if (typeof renderer !== 'string' && node.value) {
props.value = node.value
}
return props
}
function assignDefined(target, attrs) {
for (const key in attrs) {
if (typeof attrs[key] !== 'undefined') {
target[key] = attrs[key]
}
}
}
function flattenPosition(pos) {
return [pos.start.line, ':', pos.start.column, '-', pos.end.line, ':', pos.end.column]
.map(String)
.join('')
}
function unwrapParagraphs(node) {
return node.children.reduce((array, child) => {
return array.concat(child.type === 'paragraph' ? child.children || [] : [child])
}, [])
}
module.exports = astToReact
| JavaScript | 0 | @@ -2952,16 +2952,158 @@
src:
+%0A opts.transformImageUri && ref.href%0A ? opts.transformImageUri(ref.href, node.children, ref.title, node.alt)%0A :
ref.hre
|
aa307c481c85c04954017b8d0d4859c2932f9a7d | Add .css test for postcss loader | generators/app/conf.js | generators/app/conf.js | 'use strict';
const lit = require('fountain-generator').lit;
module.exports = function webpackConf(props) {
const conf = {
module: {
loaders: [
{test: lit`/\.json$/`, loaders: ['json']}
]
}
};
if (props.test === false) {
conf.plugins = [
lit`new webpack.optimize.OccurrenceOrderPlugin()`,
lit`new webpack.NoErrorsPlugin()`,
lit`new HtmlWebpackPlugin({
template: conf.path.src('index.html'),
inject: true
})`
];
conf.postcss = lit`() => [autoprefixer]`;
}
if (props.dist === false) {
conf.debug = true;
conf.devtool = 'cheap-module-eval-source-map';
if (props.test === false) {
conf.output = {
path: lit`path.join(process.cwd(), conf.paths.tmp)`,
filename: 'index.js'
};
}
} else {
conf.output = {
path: lit`path.join(process.cwd(), conf.paths.dist)`,
filename: 'index-[hash].js'
};
}
if (props.js === 'typescript') {
conf.resolve = {
extensions: ['', '.webpack.js', '.web.js', '.js', '.ts']
};
if (props.framework === 'react') {
conf.resolve.extensions.push('.tsx');
}
}
if (props.test === false) {
const index = lit`\`./\${conf.path.src('index')}\``;
if (props.dist === false && props.framework === 'react') {
conf.entry = [
'webpack/hot/dev-server',
'webpack-hot-middleware/client',
index
];
} else if (props.dist === true && props.framework === 'angular1') {
conf.entry = [index];
if (props.js === 'typescript') {
conf.entry.push(lit`\`./\${conf.path.tmp('templateCacheHtml.ts')}\``);
} else {
conf.entry.push(lit`\`./\${conf.path.tmp('templateCacheHtml.js')}\``);
}
} else {
conf.entry = index;
}
if (props.dist === false && props.framework === 'react') {
conf.plugins.push(
lit`new webpack.HotModuleReplacementPlugin()`
);
}
if (props.dist === true) {
conf.plugins.push(
lit`new webpack.optimize.UglifyJsPlugin({
compress: {unused: true, dead_code: true} // eslint-disable-line camelcase
})`
);
}
}
if (props.test === false) {
const cssLoaders = ['style', 'css'];
let test;
if (props.css === 'scss') {
cssLoaders.push('sass');
test = lit`/\\.(css|scss)$/`;
}
if (props.css === 'less') {
cssLoaders.push('less');
test = lit`/\\.(css|less)$/`;
}
cssLoaders.push('postcss');
conf.module.loaders.push({test, loaders: cssLoaders});
}
const jsLoaders = [];
if (props.test === false && props.dist === false && props.framework === 'react') {
jsLoaders.push('react-hot');
}
if (props.framework === 'angular1') {
jsLoaders.push('ng-annotate');
}
if (props.js === 'babel' || props.js === 'js' && props.framework === 'react') {
jsLoaders.push('babel');
}
if (props.js === 'typescript') {
jsLoaders.push('ts');
}
if (jsLoaders.length > 0) {
const jsLoader = {test: lit`/\\.js$/`, exclude: lit`/node_modules/`, loaders: jsLoaders};
if (props.js === 'typescript') {
jsLoader.test = lit`/\\.ts$/`;
if (props.framework === 'react') {
jsLoader.test = lit`/\\.tsx$/`;
}
}
conf.module.loaders.push(jsLoader);
}
if (props.js === 'typescript') {
conf.ts = {
configFileName: 'conf/ts.conf.json'
};
conf.tslint = {
configuration: lit`require('./tslint.conf.json')`
};
}
if (props.test === true && props.js !== 'typescript') {
conf.module.loaders.push({
test: lit`/\\.js$/`,
exclude: lit`/(node_modules|.*\\.spec\\.js)/`,
loader: 'isparta'
});
if (props.framework === 'react') {
conf.externals = {
'react/lib/ExecutionEnvironment': true,
'react/lib/ReactContext': true
};
}
}
return conf;
};
| JavaScript | 0 | @@ -2247,16 +2247,33 @@
let test
+ = lit%60/%5C%5C.css$/%60
;%0A if
|
ddd0029fb06fa90595eee378c6aa5d08ca395ede | implement scroll to bio | assets/js/lib/models/Members.js | assets/js/lib/models/Members.js | /**
* members.js
* ----------
* Registry of members
*/
/**
* @constructor
* @param {object} data json object containing members data
*/
function Members(data) {
this.data = data;
}
// ********************
// * instance methods *
// ********************
/**
* Renders all member cards to the output element specified
* @param {string} outputElem Page element to output to
*/
Members.prototype.render = function(outputElem)
{
var memberCards = document.createElement('div');
$(memberCards).attr('class', 'member_cards');
$(this.data).each(function(index, memberData) {
var member = new Member(memberData);
// create member card wrapper
var fullMemberCard = document.createElement('div');
$(fullMemberCard).addClass('full_member_card');
var cardId = 'member-' + member.getId();
$(fullMemberCard).attr('id', cardId);
// create member card
var memberCard = document.createElement('div');
$(memberCard).attr('class', 'member_card');
member.renderCard(memberCard);
// create bio card
var memberBio = document.createElement('div');
var memberBioText = document.createElement('p');
$(memberBio).attr('class', 'member_card_bio');
$(memberBioText).text(member.getBio());
$(memberBio).append(memberBioText);
$(memberBio).hide();
// create close button
var closeBtn = document.createElement('span');
$(closeBtn).text('close');
$(closeBtn).attr('class', 'member_card_close_button');
$(memberBio).append(closeBtn);
// add click events
$(memberCard).click(function(event) {
$(fullMemberCard).toggleClass('full_member_card_clicked', true);
$(memberCard).toggleClass('member_card_clicked', true);
$(memberBio).show();
});
$(document).click(function(event) {
if ($(event.target).attr('id') !== cardId &&
$(event.target).parents().index($('#' + cardId)) == -1 &&
$(memberBio).is(':visible')
) {
$(memberCard).toggleClass('member_card_clicked', false);
$(fullMemberCard).toggleClass('full_member_card_clicked', false);
$(memberBio).hide();
}
});
$(closeBtn).click(function(event) {
$(memberCard).toggleClass('member_card_clicked', false);
$(fullMemberCard).toggleClass('full_member_card_clicked', false);
$(memberBio).hide();
});
// append
$(fullMemberCard).append(memberCard);
$(fullMemberCard).append(memberBio);
$(memberCards).append(fullMemberCard);
});
$(outputElem).append(memberCards);
};
| JavaScript | 0 | @@ -1735,16 +1735,219 @@
.show();
+%0A%0A // scroll to clicked bio after reflow is complete%0A setTimeout(function() %7B%0A $('html, body').animate(%7B%0A scrollTop: $(fullMemberCard).offset().top%0A %7D, 500);%0A %7D, 1);
%0A %7D);
|
63c765d36864248abcd4660ba13ac2dca4c079aa | add keyword filter for search refresh | csgo-puppeteer/src/search-refresh.js | csgo-puppeteer/src/search-refresh.js | #!/usr/bin/env node
const puppeteer = require('puppeteer');
const config = require('./config');
const EmailService = require('./email');
// 用到的通知邮件
const emailService1 = new EmailService('sohu');
const emailService2 = new EmailService('163');
const Utils = require('./utils');
const play = require('./sound');
const cookies = config.cookies;
let lastList;
// 搜索链接
const targetUrl = `https://steamcommunity.com/market/search?q=&category_730_ItemSet%5B%5D=any&category_730_ProPlayer%5B%5D=any&category_730_StickerCapsule%5B%5D=any&category_730_TournamentTeam%5B%5D=any&category_730_Weapon%5B%5D=any&category_730_Exterior%5B%5D=tag_WearCategory0&category_730_Type%5B%5D=tag_Type_Hands&appid=730`;
let cookieCount = 0;
let errorCount = 0;
(async () => {
// const browser = await puppeteer.launch({ headless: false, delay: 1000 });
const browser = await puppeteer.launch({ headless: true, args: ['--disable-timeouts-for-profiling'] });
const page = await browser.newPage();
const viewPort = {
width: 1280,
height: 800
};
page.setViewport(viewPort);
try {
run(page);
} catch (e) {
console.log(e);
}
})();
async function run(page) {
try {
await page.deleteCookie(...cookies[cookieCount++ % cookies.length]);
await page.setCookie(...cookies[cookieCount % cookies.length]);
await page.goto(targetUrl);
await extractPage(page);
} catch (e) {
console.log(e);
}
// schedule下一个扫描
setTimeout(() => run(page),
Utils.randomIntFromInterval(config.interval.min, config.interval.max) * 1000
);
}
async function extractPage(page) {
const listEls = await page.$$('.market_listing_row_link');
if (!listEls || !listEls.length) {
console.log('没有获得物品列表!');
if (++errorCount >= config.errorCountThreshold) {
errorCount = 0;
play(config.errorSoundFilePath);
}
return;
}
const itemList = [];
for (let target of listEls) {
const item = await page.evaluate((el) => {
const name = el.querySelector('.market_listing_item_name').innerHTML;
const count = parseInt(el.querySelector('.market_listing_num_listings_qty').innerHTML.replace(',', ''));
const link = el.href.replace(/(http|https):\/\//, '');
return { name, count, link };
}, target);
itemList.push(item);
};
console.log(Utils.getLocaleDateTime());
console.log(itemList.map(item => getItemMsg(item, false)).join('\n'));
const increasedItems = getIncreasedItems(itemList, lastList);
lastList = itemList;
if (increasedItems.length) {
const itemMsgs = increasedItems.map(item => getItemMsg(item, true));
const msg = `发现时间: ${Utils.getLocaleDateTime()} \n<br/> ${itemMsgs.join('\n<br/>')}`;
Utils.notify(config.soundFilePath, config.emailSubject, msg, emailService1, emailService2);
}
}
function getIncreasedItems(newList, oldList) {
const result = [];
if (oldList) {
newList.forEach((item) => {
const matchedItem = oldList.find(o => item.link === o.link);
if (matchedItem) {
if (matchedItem.count < item.count) {
result.push(item);
}
} else {
console.log(`新物品: ${JSON.stringify(item)}`);
result.push(item);
}
});
}
return result;
}
function getItemMsg(item, includeLink) {
let msg = `名称: ${item.name}, 数量: ${item.count}`;
includeLink && (msg += `, 链接: <a href="https://${item.link}" target="_blank">点击这里</a>`);
return msg;
}
| JavaScript | 0 | @@ -729,16 +729,90 @@
unt = 0;
+%0A// %E5%A6%82%E6%9E%9C%E7%89%A9%E5%93%81%E5%90%8D%E7%A7%B0%E5%8C%85%E5%90%AB%E4%BB%BB%E4%BD%95%E5%85%B3%E9%94%AE%E5%AD%97,%E5%B0%B1%E4%B8%8D%E4%BC%9A%E8%A2%AB%E6%AF%94%E8%BE%83%E5%92%8C%E6%8F%90%E7%A4%BA.%0Aconst excludeKeywords = %5B'%E8%8F%B1%E8%83%8C%E8%9B%87%E7%BA%B9', '%E9%A3%8E%E4%B9%8B%E5%8A%9B-%E4%B9%9D%E5%A4%B4%E8%9B%87%E5%BC%93'%5D;
%0A%0A(async
@@ -2470,16 +2470,40 @@
%0A
+ isEligibleItem(item) &&
itemLis
@@ -3758,12 +3758,225 @@
turn msg;%0A%7D%0A
+%0Afunction isEligibleItem(item) %7B%0A let rs = true;%0A for (let keyword of excludeKeywords) %7B%0A if (item.name.includes(keyword)) %7B%0A rs = false;%0A break;%0A %7D%0A %7D%0A return rs;%0A%7D
|
7a24974e6b34dfcbba6030fa3df0bdfbd6deb992 | Add xdd test | tests/test.js | tests/test.js | describe("initErrorlog", function() {
it("window.onerror should be a function", function(){
heartbeat.initErrorlog();
expect(typeof window.onerror).toBe('function');
});
// it("window.onerror should send a message", function(){
// expect(window.onerror()).toBe('function');
// });
});
describe("readProperties", function() {
it("Should extract only booleans, numbers and strings", function(){
var object = {
test1: 'test',
test2: 5,
test3: function(){ return true; },
test4: {test5: false}
};
expect(readProperties(object)).toBe('test1testtest25test3test4test5false');
});
});
describe("makeHash", function() {
it("Should be zero for empty string", function(){
expect(makeHash('')).toBe(0);
});
it("Should be 3556498 for test string", function(){
expect(makeHash('test')).toBe(3556498);
});
});
describe("prepareId", function() {
it("Should return a number", function(){
expect(prepareId()).toEqual(jasmine.any(Number));
});
});
describe("xdr", function() {
it("Should return a number", function(){
expect(prepareId()).toEqual(jasmine.any(Number));
});
});
| JavaScript | 0.000003 | @@ -1113,32 +1113,34 @@
unction() %7B%0A
+
it(%22Should retur
@@ -1137,32 +1137,31 @@
ould return
-a number
+promise
%22, function(
@@ -1175,55 +1175,104 @@
-expect(prepareId()).toEqual(jasmine.any(Number)
+var promise = xdr('http://localhost', 'POST', 'test');%0A expect(promise.then).toBeDefined(
);%0A
|
b16c4e725418354db15b23098b3ca1d4c7d76eba | Fix comment | assets/main/components/index.js | assets/main/components/index.js | /*
* Components styles and scripts.
* Will be loaded asynchronous at the bottom of the page.
*/
import '../../polyfills';
import './components.css';
| JavaScript | 0 | @@ -52,34 +52,30 @@
ded
-asynchronous at the bottom
+deferred in the %3Chead%3E
of
|
bca06c7b9dfce29d17eb4b25487abc2bdda7da20 | Test wording change | shared/modules/Template/tests/templates.spec.js | shared/modules/Template/tests/templates.spec.js | /**
* @overview In browser testing of UI
*/
import deepFreeze from 'deep-freeze';
export default function(component) {
console.log('Finished Loading');
describe('After creating one template for a new company:', function() {
const formControls = document.querySelectorAll("input.form-control");
const submitBtn = document.querySelector("#template-submit-btn");
const testTemplate = {
company: "Cobra",
dept: "Destro",
unit: "X3",
product: "Venom",
pn: "V123-2345"
}
deepFreeze(testTemplate);
// Create one template for a new company with whitespace in input
const submitTemplate = (template) => {
for (let fc of formControls) {
// input name is attribute name
fc.value = ` ${template[fc.name]} `;
}
submitBtn.click();
}
// Delete one template if test company button exists
const deleteTemplate = (done) => {
if (document.querySelector(`#${testTemplate.company}`)) {
// Open company template list
document.querySelector(`#${testTemplate.company}`).click();
// Delete after component mounts
setTimeout(function() {
document.querySelectorAll(`.delete-row-btn`)[0].click();
done();
}, 1000);
}
}
beforeAll(function(done) {
submitTemplate(testTemplate);
// Change to new company view
setTimeout(function() {
document.querySelector(`#${testTemplate.company}`).click();
setTimeout(done, 500);
}, 500);
})
afterAll(function(done) {
deleteTemplate(done);
})
it('should trim the whitespace from input text.', function(done) {
const templates = component.filteredTemplates();
expect(templates.length).toEqual(1);
expect(templates[0].company).toEqual(testTemplate.company);
expect(templates[0].dept).toEqual(testTemplate.dept);
expect(templates[0].pn).toEqual(testTemplate.pn);
done();
})
it('should clear all fields after submission.', function(done) {
const everyFormControl = Array.prototype.every.bind(formControls);
expect(everyFormControl(each => each.value === "")).toEqual(true);
done();
});
it('should add a sidebar button for new company.', function(done) {
const companyBtn = document.getElementById(testTemplate.company);
expect(companyBtn).not.toEqual(null);
done();
});
it('should add a sidebar button for new dept.', function(done) {
const companyBtn = document.getElementById(`${testTemplate.company}-${testTemplate.dept}`);
expect(companyBtn).not.toEqual(null);
done();
});
it('should not add a duplicate template.', function(done) {
const beforeLength = component.props.templates.length;
submitTemplate(testTemplate);
setTimeout(function() {
expect(component.props.templates.length).toEqual(beforeLength);
done();
}, 500);
})
it('should have one item in filtered templates list.', function(done) {
expect(component.filteredTemplates().length).toEqual(1);
done();
});
describe('should not submit if a field is blank.', function() {
it('should fail with missing company', function(done) {
submitTemplate(Object.assign({}, testTemplate, {company:""}));
setTimeout(function() {
expect(document.querySelector("input.dept").value.trim()).toEqual(testTemplate.dept);
expect(component.filteredTemplates().length).toEqual(1);
done();
}, 500);
})
it('should fail with missing dept', function(done) {
submitTemplate(Object.assign({}, testTemplate, {dept:""}));
setTimeout(function() {
expect(document.querySelector("input.company").value.trim()).toEqual(testTemplate.company);
expect(component.filteredTemplates().length).toEqual(1);
done();
}, 500);
})
it('should fail with missing unit', function(done) {
submitTemplate(Object.assign({}, testTemplate, {unit:""}));
setTimeout(function() {
expect(document.querySelector("input.company").value.trim()).toEqual(testTemplate.company);
expect(component.filteredTemplates().length).toEqual(1);
done();
}, 500);
})
it('should fail with missing product', function(done) {
submitTemplate(Object.assign({}, testTemplate, {product:""}));
setTimeout(function() {
expect(document.querySelector("input.company").value.trim()).toEqual(testTemplate.company);
expect(component.filteredTemplates().length).toEqual(1);
done();
}, 500);
})
it('should fail with missing pn', function(done) {
submitTemplate(Object.assign({}, testTemplate, {pn:""}));
setTimeout(function() {
expect(document.querySelector("input.company").value.trim()).toEqual(testTemplate.company);
expect(component.filteredTemplates().length).toEqual(1);
done();
}, 500);
})
})
});
}
| JavaScript | 0.000002 | @@ -3748,36 +3748,46 @@
it('should fail
-with
+to submit when
missing company
@@ -4210,36 +4210,46 @@
it('should fail
-with
+to submit when
missing dept',
@@ -4672,36 +4672,46 @@
it('should fail
-with
+to submit when
missing unit',
@@ -5134,36 +5134,46 @@
it('should fail
-with
+to submit when
missing product
@@ -5610,20 +5610,30 @@
ld fail
-with
+to submit when
missing
|
f967ae2317d33188297d5458e1e09cdcf22d3562 | Add selector for making stages non cumulative | src/selectors/StageSelectors.js | src/selectors/StageSelectors.js | /* @flow */
import { createSelector } from 'reselect';
import aperture from 'ramda/src/aperture';
import compose from 'ramda/src/compose';
import head from 'ramda/src/head';
import last from 'ramda/src/last';
import cond from 'ramda/src/cond';
import of from 'ramda/src/of';
import always from 'ramda/src/always';
import map from 'ramda/src/map';
import curry from 'ramda/src/curry';
export const stagesSelector = (state: any): any => state.stage.stages;
const middleConstraints = compose(
map((aperture) => {
const [prev, curr, next] = aperture;
const incThreshold = prev.threshold + 1;
return {
stage: curr,
minThreshold: incThreshold,
minParticipants: Math.max(prev.participants, curr.threshold),
maxThreshold: Math.min(curr.participants, next.threshold-1),
maxParticipants: next.participants
};
}),
aperture(3)
);
const singletonConstraint = compose(
stage => ({
stage: stage,
minThreshold: 0,
minParticipants: 1,
maxThreshold: stage.participants,
maxParticipants: Infinity
}),
head
);
const headConstraint = compose(
(aperture) => {
const [curr, next] = aperture;
return {
stage: curr,
minThreshold: 0,
minParticipants: curr.threshold,
maxThreshold: Math.min(curr.participants, next.threshold-1),
maxParticipants: next.participants
};
},
head,
aperture(2)
);
const lastConstraint = compose(
(aperture) => {
const [prev, curr] = aperture;
const incThreshold = prev.threshold + 1;
return {
stage: curr,
minThreshold: incThreshold,
minParticipants: Math.max(prev.participants, curr.threshold),
maxThreshold: curr.participants,
maxParticipants: Infinity
};
},
last,
aperture(2)
);
const lengthIs = curry((len, xs) => (xs.length === len));
const totalParticipantsSelector = state => {
return stagesSelector(state).reduce((acc, stage) => Math.max(acc, stage.participants), 0);
}
const log = (x) => { console.log(x); return x; };
export const constrainedStagesSelector = createSelector(
stagesSelector,
totalParticipantsSelector,
(stages, totalParticipants) => {
return {
stages: cond([
[lengthIs(0), () => ([])],
[lengthIs(1), compose(of, singletonConstraint)],
[lengthIs(2), xs => [headConstraint(xs), lastConstraint(xs)]],
[() => true, xs => [headConstraint(xs), ...middleConstraints(xs), lastConstraint(xs)]]
])(stages),
totalParticipants: totalParticipants,
removalAllowed: stages.length > 1
};
}
);
| JavaScript | 0.000002 | @@ -376,16 +376,50 @@
/curry';
+%0Aimport %7B mapAccum %7D from 'ramda';
%0A%0Aexport
@@ -484,16 +484,317 @@
tages;%0A%0A
+export const nonCumulativeStagesSelector = createSelector(%0A stagesSelector,%0A compose(last, mapAccum(%0A (prevParticipants, stage) =%3E (%5B%0A stage.participants,%0A %7B%0A participants: stage.participants - prevParticipants,%0A threshold: stage.threshold %0A %7D%0A %5D),%0A 0%0A ))%0A);%0A%0A
const mi
@@ -1284,25 +1284,25 @@
nThreshold:
-0
+1
,%0A minPar
@@ -1537,17 +1537,17 @@
eshold:
-0
+1
,%0A
|
c1d3a66f2ae17a58b58b8664d2f9b859df22e323 | Fix lint error | src/serverless.js | src/serverless.js | 'use strict'
const { ApolloServer } = require('apollo-server-lambda')
const config = require('./utils/config')
const connect = require('./utils/connect')
const createApolloServer = require('./utils/createApolloServer')
const { createServerlessContext } = require('./utils/createContext')
if (config.dbUrl == null) {
throw new Error('MongoDB connection URI missing in environment')
}
connect(config.dbUrl)
const apolloServer = createApolloServer(ApolloServer, {
context: createServerlessContext
})
const origin = (() => {
if (config.allowOrigin === '*') {
return true
}
if (config.allowOrigin != null) {
return config.allowOrigin.split(',')
}
})()
exports.handler = apolloServer.createHandler({
cors: {
origin,
methods: 'GET,POST,PATCH,OPTIONS',
allowedHeaders: 'Content-Type, Authorization, Time-Zone'
}
})
| JavaScript | 0.000035 | @@ -825,9 +825,8 @@
e'%0A%09%7D%0A%7D)
-%0A
|
6514e46a6a7a8e1414111907e665de80cb187854 | Update the test case, TravisCI test failing | tests/test.js | tests/test.js | //I hear you like to run node in your node, so I'm testing node using node
var spawn = require('spawn-cmd').spawn,
testProcess = spawn('node ./src/index.js < ./tests/eval.js'),
assert = require('assert');
testProcess.stdout.on('data', function (data) {
assert.equal(data, 'This is only a test');
});
testProcess.stderr.on('data', function (data) {
assert.fail(data, "nothing", "Did not expect any stderr", ":")
});
testProcess.on('close', function (code) {
assert.equal(code, 0);
});
console.log("Huzzah! The simple single test passes"); | JavaScript | 0.000019 | @@ -505,66 +505,55 @@
e, 0
-);%0D%0A%7D);%0D%0Aconsole.log(%22Huzzah! The simple single test passes%22
+, %22The spawned process did not exit cleanly%22);%0D%0A%7D
);
|
2af8387c7f2b4afe4ecfa0ee23cbddac68b04bad | Clean up migrate command | packages/truffle-core/lib/commands/migrate.js | packages/truffle-core/lib/commands/migrate.js | var command = {
command: 'migrate',
description: 'Run migrations to deploy contracts',
builder: {
reset: {
type: "boolean",
default: false
},
"compile-all": {
describe: "recompile all contracts",
type: "boolean",
default: false
},
"dry-run": {
describe: "Run migrations against an in-memory fork, for testing",
type: "boolean",
default: false
},
f: {
describe: "Specify a migration number to run from",
type: "number"
},
"interactive": {
describe: "Manually authorize deployments after seeing a preview",
type: "boolean",
default: false
},
},
run: function (options, done) {
var OS = require("os");
var Config = require("truffle-config");
var Contracts = require("truffle-workflow-compile");
var Resolver = require("truffle-resolver");
var Artifactor = require("truffle-artifactor");
var Migrate = require("truffle-migrate");
var Environment = require("../environment");
var temp = require("temp");
var copy = require("../copy");
// Source: ethereum.stackexchange.com/questions/17051
var networkWhitelist = [
1, // Mainnet (ETH & ETC)
2, // Morden (ETC)
3, // Ropsten
4, // Rinkeby
8, // Ubiq
42, // Kovan (Parity)
77, // Sokol
99, // Core
7762959, // Musiccoin
61717561 // Aquachain
]
function setupDryRunEnvironmentThenRunMigrations(config) {
return new Promise((resolve, reject) => {
Environment.fork(config, function(err) {
if (err) return reject(err);
// Copy artifacts to a temporary directory
temp.mkdir('migrate-dry-run-', function(err, temporaryDirectory) {
if (err) return reject(err);
function cleanup() {
var args = arguments;
// Ensure directory cleanup.
temp.cleanup(function(err) {
(args.length && args[0] !== null)
? reject(args[0])
: resolve();
});
};
copy(config.contracts_build_directory, temporaryDirectory, function(err) {
if (err) return reject(err);
config.contracts_build_directory = temporaryDirectory;
// Note: Create a new artifactor and resolver with the updated config.
// This is because the contracts_build_directory changed.
// Ideally we could architect them to be reactive of the config changes.
config.artifactor = new Artifactor(temporaryDirectory);
config.resolver = new Resolver(config);
runMigrations(config, cleanup);
});
});
});
});
}
function runMigrations(config, callback) {
Migrate.launchReporter();
if (options.f) {
Migrate.runFrom(options.f, config, done);
} else {
Migrate.needsMigrating(config, function(err, needsMigrating) {
if (err) return callback(err);
if (needsMigrating) {
Migrate.run(config, callback);
} else {
config.logger.log("Network up to date.")
callback();
}
});
}
};
async function executePostDryRunMigration(buildDir){
let accept = true;
if (options.interactive){
accept = await Migrate.acceptDryRun();
}
if (accept){
const environment = require('../environment');
const NewConfig = require('truffle-config');
const config = NewConfig.detect(options);
config.contracts_build_directory = buildDir;
config.artifactor = new Artifactor(buildDir);
config.resolver = new Resolver(config);
environment.detect(config, function(err) {
config.dryRun = false;
runMigrations(config, done);
})
} else {
done();
}
}
const conf = Config.detect(options);
Contracts.compile(conf, function(err) {
if (err) return done(err);
Environment.detect(conf, async function(err) {
if (err) return done(err);
var dryRun = options.dryRun === true;
var production = networkWhitelist.includes(conf.network_id) || conf.production;
// Dry run only
if (dryRun) {
try {
await setupDryRunEnvironmentThenRunMigrations(conf);
done();
} catch(err){
done(err)
};
return;
// Production: dry-run then real run
}
else if (production){
const currentBuild = conf.contracts_build_directory;
conf.dryRun = true;
try {
await setupDryRunEnvironmentThenRunMigrations(conf)
} catch(err){
return done(err)
};
executePostDryRunMigration(currentBuild);
// Development
} else {
runMigrations(conf, done);
}
});
});
}
}
module.exports = command;
| JavaScript | 0.000002 | @@ -4499,26 +4499,8 @@
%7D;
-%0A return;
%0A%0A
@@ -4551,25 +4551,16 @@
%7D
-%0A%0A
else if
@@ -4572,16 +4572,17 @@
duction)
+
%7B%0A%0A
|
6423dcd6d50602f71f1216c955f30e450e668ef8 | use syncTo in PhysicalObject | src/serialize/PhysicalObject.js | src/serialize/PhysicalObject.js | 'use strict';
const GameObject = require('./GameObject');
const Serializer = require('./Serializer');
const ThreeVector = require('./ThreeVector');
const Quaternion = require('./Quaternion');
/**
* The PhysicalObject is the base class for physical game objects
*/
class PhysicalObject extends GameObject {
static get netScheme() {
return Object.assign({
playerId: { type: Serializer.TYPES.INT16 },
position: { type: Serializer.TYPES.CLASSINSTANCE },
quaternion: { type: Serializer.TYPES.CLASSINSTANCE },
velocity: { type: Serializer.TYPES.CLASSINSTANCE },
angularVelocity: { type: Serializer.TYPES.CLASSINSTANCE }
}, super.netScheme);
}
constructor(id, position, velocity, quaternion, angularVelocity) {
super(id);
this.playerId = 0;
this.bendingIncrements = 0;
// set default position, velocity and quaternion
this.position = new ThreeVector(0, 0, 0);
this.velocity = new ThreeVector(0, 0, 0);
this.quaternion = new Quaternion(1, 0, 0, 0);
this.angularVelocity = new ThreeVector(0, 0, 0);
// use values if provided
if (position) this.position.copy(position);
if (velocity) this.velocity.copy(velocity);
if (quaternion) this.quaternion.copy(quaternion);
if (angularVelocity) this.angularVelocity.copy(angularVelocity);
this.class = PhysicalObject;
}
// for debugging purposes mostly
toString() {
let p = this.position.toString();
let v = this.velocity.toString();
let q = this.quaternion.toString();
let a = this.angularVelocity.toString();
return `phyObj[${this.id}] player${this.playerId} Pos=${p} Vel=${v} Dir=${q} AVel=${a}`;
}
bendToCurrent(original, bending, worldSettings, isLocal, bendingIncrements) {
this.bendingTarget = (new this.constructor());
this.bendingTarget.copyFrom(this);
this.copyFrom(original);
this.bendingIncrements = bendingIncrements;
this.bending = bending;
// TODO: use configurable physics bending
// TODO: does refreshToPhysics() really belong here?
// should refreshToPhysics be decoupled from syncTo
// and called explicitly in all cases?
this.velocity.copy(this.bendingTarget.velocity);
this.angularVelocity.copy(this.bendingTarget.angularVelocity);
// this.velocity.lerp(this.bendingTarget.velocity, 0.8);
// this.angularVelocity.lerp(this.bendingTarget.angularVelocity, 0.8);
this.refreshToPhysics();
}
syncTo(other) {
this.id = other.id;
this.playerId = other.playerId;
this.position.copy(other.position);
this.quaternion.copy(other.quaternion);
this.velocity.copy(other.velocity);
this.angularVelocity.copy(other.angularVelocity);
if (this.physicsObj)
this.refreshToPhysics();
}
// update position, quaternion, and velocity from new physical state.
refreshFromPhysics() {
this.position.copy(this.physicsObj.position);
this.quaternion.copy(this.physicsObj.quaternion);
this.velocity.copy(this.physicsObj.velocity);
this.angularVelocity.copy(this.physicsObj.angularVelocity);
}
// update position, quaternion, and velocity from new physical state.
refreshToPhysics() {
this.physicsObj.position.copy(this.position);
this.physicsObj.quaternion.copy(this.quaternion);
this.physicsObj.velocity.copy(this.velocity);
this.physicsObj.angularVelocity.copy(this.angularVelocity);
}
// TODO: remove this. It shouldn't be part of the
// physical object, and it shouldn't be called by the ExtrapolationStrategy logic
// Correct approach:
// render object should be refreshed only at the next iteration of the renderer's
// draw function. And then it should be smart about positions (it should interpolate)
// refresh the renderable position
refreshRenderObject() {
if (this.renderObj) {
this.renderObj.position.copy(this.physicsObj.position);
this.renderObj.quaternion.copy(this.physicsObj.quaternion);
}
}
// apply incremental bending
applyIncrementalBending() {
if (this.bendingIncrements === 0)
return;
let incrementalBending = this.bending / this.bendingIncrements;
this.position.lerp(this.bendingTarget.position, incrementalBending);
this.quaternion.slerp(this.bendingTarget.quaternion, incrementalBending);
this.bendingIncrements--;
}
}
module.exports = PhysicalObject;
| JavaScript | 0.000001 | @@ -1956,24 +1956,22 @@
gTarget.
-copyFrom
+syncTo
(this);%0A
@@ -1987,16 +1987,14 @@
his.
-copyFrom
+syncTo
(ori
|
8a277ea76914228f2523d0e293b80b0e2a76faa2 | set default page to map.html | api/routes/index.js | api/routes/index.js | 'use strict';
const router = require('express').Router();
const Seller = require('../models/Seller');
const bodyParser = require('body-parser');
const Promise = require('bluebird');
const _ = require('lodash');
router.use(bodyParser.urlencoded({extended: true}));
// router.use(bodyParser.json());
router.get('/sellers', (req, res) => {
Seller.find().lean().exec()
.then(data => {
res.json(data);
});
});
router.get('/sellers/:id', (req, res) => {
Seller.find({_id: req.params.id}).lean().exec()
.then(data => {
res.json(data ? data[0] : []);
});
});
router.post('/sellers', (req, res) => {
new Seller({
info: {
Name: req.body.name,
},
coords: [req.body.latitude, req.body.longitude]
}).save()
.then(() => {
return res.json({success: true});
})
.catch(err => {
return res.json({success: false, error: err});
});
});
router.post('/sellers/bulk', (req, res) => {
Promise.all(
_(req.body.bulk.split(/\r?\n/))
.filter(s => s.trim().length > 0)
.chunk(3)
.map(c => {
if(c.length < 3) return Promise.resolve();
console.log('c:', c);
return new Seller({
info: {Name: c[0]},
coords: [c[1], c[2]]
}).save();
}))
.then(() => {
return res.json({success: true});
})
.catch(err => {
return res.json({success: false, error: err});
});
});
router.post('/sellers/addInventory', (req, res) => {
console.log('Finding seller with ID:', req.body.sellerId);
Seller.findById(req.body.sellerId)
.then(item => {
if(!item.inventory) item.inventory = [];
item.inventory.push({name: req.body.itemName, quantity: req.body.itemQuantity, unit: req.body.itemUnit});
return item.save();
}).then(() => {
return res.json({success: true});
});
});
module.exports = router;
| JavaScript | 0.000001 | @@ -204,16 +204,42 @@
odash');
+%0Aconst fs = require('fs');
%0A%0Arouter
@@ -316,24 +316,112 @@
r.json());%0A%0A
+router.get('/', (req, res) =%3E %7B%0A fs.createReadStream('pages/map.html').pipe(res);%0A%7D);%0A%0A
router.get('
|
867b6ac0501be3d6eee788ef95f020fb4b7351d3 | update simulation | src/simulation.js | src/simulation.js | import { request } from "http"
import { createConnection } from "net"
import { v4 } from "uuid"
import { forEach } from "ramda"
import { isDevelopment } from "./share/environment"
import WebSocket from "ws"
import { logger } from "./app/index"
const clients = []
const clientCount = parseInt(process.argv[2], 10) || 20
process.on("SIGINT", () => forEach(client => {
try {
client.close()
} catch (e) {
logger.info(e.message)
}
}, clients))
export default class Client {
run() {
this.createUser()
}
createUser() {
this.userData = {
email: `${v4()}@example.com`,
password: v4(),
displayName: v4()
}
const postData = JSON.stringify(this.userData)
const options = {
method: "POST",
host: "127.0.0.1",
port: "3000",
path: "/users",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.byteLength(postData)
}
}
const req = request(options, (res) => {
if (res.statusCode === 201) {
this.cookie = res.headers["set-cookie"][0].split(";")[0]
this.connect()
}
})
req.write(postData)
req.end()
}
connect() {
this.socket = new WebSocket("ws://localhost:3000/ws", {
headers: { Cookie: this.cookie }
})
this.socket.on("open", this.open.bind(this))
this.socket.on("message", this.message.bind(this))
}
open() {
logger.info("WebSocket [OPEN]")
}
message(message) {
const { action, ...rest } = JSON.parse(message)
if (action === "universe" || action === "wait") {
return
}
logger.info(`WebSocket [RECV] ${message}`)
this[action].call(this, rest)
}
close() {
if (this.socket) {
this.socket.close()
}
}
send(command) {
const message = JSON.stringify(command)
this.socket.send(message)
logger.info(`WebSocket [SEND] ${message}`)
}
user({ user }) {
this.user = user
this.send({ action: "play" })
}
start({ game, opponent }) {
if (game.whiteUser.uuid === this.user.uuid) {
this.color = "w"
} else if (game.blackUser.uuid === this.user.uuid) {
this.color = "b"
}
/*
if (this.color !== this.board.getTurn()) {
return
}
const pieceFinder = (color, piece) => {
const ascii = piece.charCodeAt(0)
return piece !== "" &&
((color === "w" && ascii > 64 && ascii < 91) ||
(color === "b" && ascii > 96 && ascii < 123))
}
const piecesWithMoves = this.board
.getState()
.map(pieceFinder.apply(null, data.color))
.reduce((memo, piece) => {
const moves = board.getValidLocations(piece)
if (moves.length > 0) {
memo[piece] = moves
}
return memo
})
// select random piece to move
// http://stackoverflow.com/questions/2532218/pick-random-property-from-a-javascript-object
for (let piece in piecesWithMoves) {
if (Math.random() < 1 / ++count) {
const from = piece
const moves = piece_moves[piece]
}
}
const to = moves[Math.floor(Math.random() * moves.length)]
*/
const from = "", to = "", promotion = ""
setTimeout(this.send.bind(this, {
action: "revision",
from,
to,
promotion
}), 6000 - Math.floor(Math.random() * 1000))
}
}
if (isDevelopment()) {
((function simulate(count) {
checkForServer().then(createClients())
}()))
}
function checkForServer() {
return new Promise((resolve, reject) => {
createConnection(3000, "localhost", resolve)
})
}
function createClients() {
for (let n = 0; n < clientCount; n++) {
const client = new Client()
clients.push(client)
process.nextTick(client.run.bind(client))
}
}
| JavaScript | 0.000001 | @@ -202,16 +202,49 @@
rom %22ws%22
+%0Aimport %7B Chess %7D from %22chess.js%22
%0A%0Aimport
@@ -273,16 +273,67 @@
p/index%22
+%0Aimport %7B REVISION_TYPES %7D from %22./share/constants%22
%0A%0Aconst
@@ -2089,24 +2089,54 @@
ponent %7D) %7B%0A
+ this.chess = new Chess()%0A%0A
if (game
@@ -2192,19 +2192,32 @@
color =
-%22w%22
+this.chess.WHITE
%0A %7D e
@@ -2289,19 +2289,32 @@
r =
-%22b%22
+this.chess.BLACK
%0A %7D%0A%0A
@@ -2313,15 +2313,8 @@
%7D%0A%0A
- /*%0A
@@ -2341,18 +2341,15 @@
his.
-board.getT
+chess.t
urn(
@@ -2365,32 +2365,39 @@
return%0A %7D%0A%0A
+ /*%0A
const pieceF
@@ -3292,16 +3292,18 @@
from = %22
+e2
%22, to =
@@ -3303,16 +3303,18 @@
, to = %22
+e4
%22, promo
@@ -3320,18 +3320,20 @@
otion =
-%22%22
+null
%0A%0A se
@@ -3386,24 +3386,57 @@
%22revision%22,%0A
+ type: REVISION_TYPES.MOVE,%0A
from,%0A
|
ce826900b62f284769873ecec5b1a31e693b971e | Commit new solution for three sum | src/three-sum/index.js | src/three-sum/index.js | /**
* @param {number[]} numbers
* @return {number[][]}
*/
const threeSum = function (numbers) {
let results = [];
if (!numbers || numbers.length < 3) {
return results;
}
let map = new Map();
for (let i = 0; i < numbers.length; ++i) {
let count = map.get(numbers[i]);
map.set(numbers[i], count ? count + 1 : 1);
}
let distinct = Array.from(map.keys());
distinct.sort();
for (let i = 0; i < distinct.length; ++i) {
let first = distinct[i];
let firstCount = map.get(first);
if (firstCount >= 3 && first === 0) {
results.push([0, 0, 0]);
}
if (firstCount >= 2) {
let third = -first * 2;
if (third > first && map.has(third)) {
results.push([first, first, third]);
}
}
for (let j = i + 1; j < distinct.length; ++j) {
let second = distinct[j];
let third = -first - second;
if ((third === second && map.get(second) > 1) || (third > second && map.has(third))) {
results.push([first, second, third]);
}
}
}
return results;
};
module.exports = threeSum; | JavaScript | 0.995979 | @@ -68,16 +68,21 @@
threeSum
+ByMap
= funct
@@ -1178,16 +1178,1068 @@
ts;%0A%7D;%0A%0A
+const threeSum = function (nums) %7B%0A nums.sort((a, b) =%3E a - b);%0A let ret = %5B%5D;%0A let prevNum = NaN;%0A for (let i0 = 0; i0 %3C nums.length; ++i0) %7B%0A if (nums%5Bi0%5D === prevNum) %7B%0A continue; // skip duplication%0A %7D%0A let i1 = i0 + 1, i2 = nums.length - 1;%0A while (i1 %3C i2) %7B%0A let sum = nums%5Bi0%5D + nums%5Bi1%5D + nums%5Bi2%5D;%0A if (sum %3E 0) %7B%0A i2 = findDistinctNumberIndex(nums, i2, -1);%0A %7D else if (sum %3C 0) %7B%0A i1 = findDistinctNumberIndex(nums, i1, 1);%0A %7D else %7B%0A // sum === 0%0A ret.push(%5Bnums%5Bi0%5D, nums%5Bi1%5D, nums%5Bi2%5D%5D);%0A i1 = findDistinctNumberIndex(nums, i1, 1);%0A i2 = findDistinctNumberIndex(nums, i2, -1);%0A %7D%0A %7D%0A prevNum = nums%5Bi0%5D;%0A %7D%0A return ret;%0A%7D;%0A%0Afunction findDistinctNumberIndex(nums, start, direction) %7B%0A let idx = start + direction;%0A while (idx %3E= 0 && nums%5Bidx%5D === nums%5Bstart%5D) %7B%0A idx += direction;%0A %7D%0A return idx;%0A%7D%0A%0A
module.e
|
dd647644a3f6d961760273655561b85d0dd78eb0 | Remove unused options | tests/test.js | tests/test.js | import path from 'path'
import { transformSnapshot, compareFixture, expectUnchanged } from './helpers'
describe('Basic functionality', () => {
it('should work', () => {
compareFixture('basic.css', {
selfSelector: /:--component/,
namespace: '.namespaced',
})
})
it('has a default namespace selector of :--namespace', () => {
transformSnapshot(':--namespace {}', { namespace: '.my-component' })
})
it('has a default namespace .self', () => {
transformSnapshot(':--namespace {}')
})
it('works with a regexp which matches multiple selectors', () => {
compareFixture('multiself.css', {
selfSelector: /&|:--component/,
namespace: '.my-component',
})
})
it('works with :--namespace not being the first selector', () => {
transformSnapshot('.foo :--namespace {}', {
namespace: '.my-component',
})
})
it('can accept a function for the namespace option', () => {
transformSnapshot(
'.foo {}',
{ namespace: file => `.${path.basename(file, '.css')}` },
{ from: 'bar.css' },
)
})
it('does not apply if computed namespace is falsy', () => {
transformSnapshot('.foo {}', { namespace: file => !!file })
})
})
describe(':root', () => {
it('is configurable', () => {
transformSnapshot(':root .foo {}:global .foo {}', {
namespace: '.my-component',
rootSelector: ':global',
})
})
it('does not namespace :root selectors', () => {
compareFixture('root.css', {
selfSelector: /:--component/,
namespace: '.my-component',
})
})
it('does namespace :root selectors if ignoreRoot is false', () => {
transformSnapshot(':root .foo {}', {
namespace: '.my-component',
ignoreRoot: false,
})
})
it('does drop :root if dropRoot is true', () => {
transformSnapshot(':root .foo {}', {
namespace: '.my-component',
dropRoot: false,
})
})
it("does not drop :root if it's the only selector", () => {
transformSnapshot(':root {}', {
namespace: '.my-component',
dropRoot: true,
})
})
})
describe('@keyframes', () => {
it('does not transform keyframe definitions', () => {
expectUnchanged(
'@keyframes fadeout { from { opacity: 1 } to { opacity: 0 }}',
{ namespace: '.my-component' },
)
})
it('does not transform vendor prefixed keyframe definitions', () => {
expectUnchanged(
'@-moz-keyframes fadeout { from { opacity: 1 } to { opacity: 0 }}',
{ namespace: '.my-component' },
)
})
})
describe('@supports', () => {
it('does namespace in supports atrule', () => {
transformSnapshot(
'@supports (display: flex) { .bar { display: flex; } }',
{ namespace: '.my-component' },
)
})
})
describe('SCSS', function() {
const syntax = require('postcss-scss')
it('does transform basic nesting', () => {
transformSnapshot(
`
& { .bar { color: red; } }
.foo { color: blue }
`,
{ selfSelector: '&', namespace: '.my-component' },
)
})
it('does work with single line comments', () => {
transformSnapshot(
`
& { .bar { color: red; } }
//.foo { color: blue }
`,
{ selfSelector: '&', namespace: '.my-component' },
{ syntax },
)
})
it('does work with rules nested in nested media queries', () => {
compareFixture(
'nested-media-queries.scss',
{ namespace: '.my-component' },
{ syntax },
)
})
it('works with :root selector', () => {
transformSnapshot(':root { &.bar { color: red; } }', {
selfSelector: '&',
namespace: '.my-component',
dropRoot: true,
})
})
describe('@media nesting', () => {
it('media with nested around properties', () => {
transformSnapshot('& { .bar { @media (screen) { color: red; } } }', {
selfSelector: '&',
namespace: '.my-component',
})
})
it('media with nested around selector', () => {
transformSnapshot('& { @media (screen) { .bar { color: red; } } }', {
selfSelector: '&',
namespace: '.my-component',
})
})
it('media with nested around namespaced selector', () => {
transformSnapshot('@media (screen) { & { .bar { color: red; } } }', {
selfSelector: '&',
namespace: '.my-component',
})
})
})
describe('@include mixins', () => {
it('works with pseudo elements', () => {
transformSnapshot(
`
@mixin do-a-thing-with-pseudo-elements() {
position: relative;
&::before {
content: '';
}
}
.some-class {
@include do-a-thing-with-pseudo-elements();
}
`,
{ selfSelector: '&', namespace: '.my-component' },
)
})
})
describe('@for', () => {
it('does work with @for and nested @for rules', () => {
compareFixture(
'for.scss',
{ namespace: '.my-component', selfSelector: '&' },
{ syntax },
)
})
})
})
| JavaScript | 0.000003 | @@ -2270,46 +2270,8 @@
%7D',%0A
- %7B namespace: '.my-component' %7D,%0A
@@ -2449,46 +2449,8 @@
%7D',%0A
- %7B namespace: '.my-component' %7D,%0A
|
bce8b27ae457fdf4ef0c05934ea1f3583dc1ab43 | replace reserved keyword "package", fixes #1143 | src/plugins/appVersion.js | src/plugins/appVersion.js | // install : cordova plugin add https://github.com/whiteoctober/cordova-plugin-app-version.git
// link : https://github.com/whiteoctober/cordova-plugin-app-version
angular.module('ngCordova.plugins.appVersion', [])
.factory('$cordovaAppVersion', ['$q', function ($q) {
return {
getAppName: function () {
var q = $q.defer();
cordova.getAppVersion.getAppName(function (name) {
q.resolve(name);
});
return q.promise;
},
getPackageName: function () {
var q = $q.defer();
cordova.getAppVersion.getPackageName(function (package) {
q.resolve(package);
});
return q.promise;
},
getVersionNumber: function () {
var q = $q.defer();
cordova.getAppVersion.getVersionNumber(function (version) {
q.resolve(version);
});
return q.promise;
},
getVersionCode: function () {
var q = $q.defer();
cordova.getAppVersion.getVersionCode(function (code) {
q.resolve(code);
});
return q.promise;
}
};
}]);
| JavaScript | 0 | @@ -613,19 +613,16 @@
on (pack
-age
) %7B%0A
@@ -641,19 +641,16 @@
lve(pack
-age
);%0A
|
e1369714e026c13f1538b0a4f1ae82fa2826822c | use RN's style merger instead of all this obscure magic | src/basic/Button.js | src/basic/Button.js | /* eslint-disable new-cap */
import React from 'react';
import PropTypes from 'prop-types';
import {
TouchableOpacity,
Platform,
View,
TouchableNativeFeedback,
StyleSheet
} from 'react-native';
import { connectStyle } from 'native-base-shoutem-theme';
import variable from '../theme/variables/platform';
import { PLATFORM } from '../theme/variables/commonColor';
import computeProps from '../utils/computeProps';
import mapPropsToStyleNames from '../utils/mapPropsToStyleNames';
import { Text } from './Text';
class Button extends React.PureComponent {
static contextTypes = {
theme: PropTypes.object
};
setRoot(c){
this._root = c;
}
getInitialStyle() {
return {
borderedBtn: {
borderWidth: this.props.bordered
? variable.buttonDefaultBorderWidth
: undefined,
borderRadius:
this.props.rounded && this.props.bordered
? variable.borderRadiusLarge
: variable.buttonDefaultBorderRadius
}
};
}
prepareRootProps() {
const defaultProps = {
style: this.getInitialStyle().borderedBtn
};
if (Array.isArray(this.props.style)) {
const flattenedStyle = this.props.style.reduce(
(accumulator, currentValue) => accumulator.concat(currentValue),
[]
);
return computeProps(
{ ...this.props, style: flattenedStyle },
defaultProps
);
}
return computeProps(this.props, defaultProps);
}
render() {
const variables = this.context.theme
? this.context.theme['@@shoutem.theme/themeStyle'].variables
: variable;
const children =
Platform.OS === PLATFORM.IOS || !variables.buttonUppercaseAndroidText
? this.props.children
: React.Children.map(this.props.children, child =>
child && child.type === Text
? React.cloneElement(child, {
uppercase: true,
...child.props
})
: child
);
const rootProps = this.prepareRootProps();
if (
Platform.OS === PLATFORM.IOS ||
Platform.OS === PLATFORM.WEB ||
variables.androidRipple === false ||
Platform.Version < 21
) {
return (
<TouchableOpacity
{...rootProps}
ref={this.setRoot}
activeOpacity={
this.props.activeOpacity > 0
? this.props.activeOpacity
: variable.buttonDefaultActiveOpacity
}
>
{children}
</TouchableOpacity>
);
}
if (this.props.rounded) {
const buttonStyle = { ...rootProps.style };
const buttonFlex =
this.props.full || this.props.block
? variable.buttonDefaultFlex
: buttonStyle.flex;
return (
<View
style={[
{ maxHeight: buttonStyle.height },
buttonStyle,
{ paddingTop: undefined, paddingBottom: undefined }
]}
>
<TouchableNativeFeedback
ref={this.setRoot}
background={TouchableNativeFeedback.Ripple(
this.props.androidRippleColor || variables.androidRippleColor,
true
)}
{...rootProps}
>
<View
style={[
// eslint-disable-next-line no-use-before-define
styles.childContainer,
{
paddingTop: buttonStyle.paddingTop,
paddingBottom: buttonStyle.paddingBottom,
height: buttonStyle.height,
flexGrow: buttonFlex
}
]}
>
{children}
</View>
</TouchableNativeFeedback>
</View>
);
}
return (
<TouchableNativeFeedback
ref={this.setRoot}
onPress={this.props.onPress}
background={
this.props.transparent
? TouchableNativeFeedback.Ripple('transparent')
: TouchableNativeFeedback.Ripple(
variables.androidRippleColor,
false
)
}
{...rootProps}
>
<View {...rootProps}>{children}</View>
</TouchableNativeFeedback>
);
}
}
Button.propTypes = {
...TouchableOpacity.propTypes,
style: PropTypes.oneOfType([
PropTypes.object,
PropTypes.number,
PropTypes.array
]),
block: PropTypes.bool,
primary: PropTypes.bool,
transparent: PropTypes.bool,
success: PropTypes.bool,
danger: PropTypes.bool,
warning: PropTypes.bool,
info: PropTypes.bool,
bordered: PropTypes.bool,
disabled: PropTypes.bool,
rounded: PropTypes.bool,
large: PropTypes.bool,
small: PropTypes.bool,
active: PropTypes.bool
};
const styles = StyleSheet.create({
childContainer: {
flexShrink: 1,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center'
}
});
const StyledButton = connectStyle(
'NativeBase.Button',
{},
mapPropsToStyleNames
)(Button);
export { StyledButton as Button }; | JavaScript | 0 | @@ -371,58 +371,8 @@
r';%0A
-import computeProps from '../utils/computeProps';%0A
impo
@@ -978,24 +978,25 @@
otProps() %7B%0A
+%0A
const de
@@ -997,435 +997,153 @@
nst
-defaultProps = %7B%0A style: this.getInitialStyle().borderedBtn%0A %7D;%0A%0A if (Array.isArray(this.props.style)) %7B%0A const flattenedStyle = this.props.style.reduce(%0A (accumulator, currentValue) =%3E accumulator.concat(currentValue),%0A %5B%5D%0A );%0A return computeProps(%0A %7B ...this.props, style: flattenedStyle %7D,%0A defaultProps%0A );%0A %7D%0A%0A return computeProps(this.props, defaultProps);
+%7Bstyle, ...others%7D = this.props;%0A%0A return %7B%0A style: StyleSheet.compose(this.getInitialStyle().borderedBtn, style),%0A ...others%0A %7D%0A
%0A %7D
|
26cf28897b2256576be437cc20bf77a8ad92e941 | Fix issues in the SettingsForm.stories.js file. | assets/js/modules/analytics/components/settings/SettingsForm.stories.js | assets/js/modules/analytics/components/settings/SettingsForm.stories.js | /**
* Analytics SettingsView component stories.
*
* Site Kit by Google, Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Internal dependencies
*/
import SettingsForm from './SettingsForm';
import { STORE_NAME } from '../../datastore/constants';
import { MODULES_ANALYTICS_4 } from '../../../analytics-4/datastore/constants';
import { provideModules, provideModuleRegistrations, provideSiteInfo } from '../../../../../../tests/js/utils';
import WithRegistrySetup from '../../../../../../tests/js/WithRegistrySetup';
import * as fixtures from '../../datastore/__fixtures__';
import * as ga4Fixtures from '../../../analytics-4/datastore/__fixtures__';
const features = [ 'ga4setup' ];
function Template() {
return (
<div className="googlesitekit-layout">
<div className="googlesitekit-settings-module googlesitekit-settings-module--active googlesitekit-settings-module--analytics">
<div className="googlesitekit-setup-module">
<div className="googlesitekit-settings-module__content googlesitekit-settings-module__content--open">
<div className="mdc-layout-grid">
<div className="mdc-layout-inner">
<div className="mdc-layout-grid__cell mdc-layout-grid__cell--span-12">
<SettingsForm />
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
export const WithGA4andUASnippet = Template.bind( null );
WithGA4andUASnippet.storyName = 'UA and GA4 tag snippet switches';
WithGA4andUASnippet.parameters = { features };
export default {
title: 'Modules/Analytics/Settings/SettingsEdit',
decorators: [
( Story ) => {
const setupRegistry = ( registry ) => {
const account = fixtures.accountsPropertiesProfiles.accounts[ 0 ];
const properties = [
{
...fixtures.accountsPropertiesProfiles.properties[ 0 ],
websiteUrl: 'http://example.com', // eslint-disable-line sitekit/acronym-case
},
{
...fixtures.accountsPropertiesProfiles.properties[ 1 ],
},
];
const accountID = account.id;
provideModules( registry, [
{
slug: 'analytics',
active: true,
connected: true,
},
{
slug: 'analytics-4',
active: true,
connected: true,
},
] );
provideSiteInfo( registry );
provideModuleRegistrations( registry );
registry.dispatch( MODULES_ANALYTICS_4 ).receiveGetSettings( {} );
registry.dispatch( MODULES_ANALYTICS_4 ).receiveGetProperties( ga4Fixtures.properties, { accountID } );
registry.dispatch( MODULES_ANALYTICS_4 ).receiveGetSettings( {
useSnippet: true,
} );
registry.dispatch( STORE_NAME ).receiveGetSettings( {
useSnippet: true,
canUseSnippet: true,
} );
registry.dispatch( STORE_NAME ).receiveGetAccounts( [ account ] );
registry.dispatch( STORE_NAME ).receiveGetProperties( properties, { accountID } );
registry.dispatch( STORE_NAME ).receiveGetProfiles( fixtures.accountsPropertiesProfiles.profiles, { accountID, propertyID: properties[ 0 ].id } );
registry.dispatch( STORE_NAME ).receiveGetProfiles( fixtures.accountsPropertiesProfiles.profiles, { accountID, propertyID: properties[ 1 ].id } );
registry.dispatch( STORE_NAME ).selectAccount( accountID );
};
return (
<WithRegistrySetup func={ setupRegistry }>
<Story />
</WithRegistrySetup>
);
},
],
};
| JavaScript | 0 | @@ -3017,32 +3017,347 @@
accountID %7D );%0A
+%09%09%09%09registry.dispatch( MODULES_ANALYTICS_4 ).receiveGetWebDataStreams( %5B%0A%09%09%09%09%09%7B%0A%09%09%09%09%09%09_id: '2001',%0A%09%09%09%09%09%09/* eslint-disable sitekit/acronym-case */%0A%09%09%09%09%09%09measurementId: '1A2BCD345E',%0A%09%09%09%09%09%09defaultUri: 'http://example.com',%0A%09%09%09%09%09%09/* eslint-disable */%0A%09%09%09%09%09%7D,%0A%09%09%09%09%5D, %7B propertyID: ga4Fixtures.properties%5B 0 %5D._id %7D );%0A
%09%09%09%09registry.dis
@@ -3539,32 +3539,100 @@
eSnippet: true,%0A
+%09%09%09%09%09anonymizeIP: true,%0A%09%09%09%09%09trackingDisabled: %5B 'loggedinUsers' %5D,%0A
%09%09%09%09%7D );%0A%09%09%09%09reg
|
6b0ad775be1f092359b39cb1f85b278ce942a403 | Update meal displaying | src/main/webapp/meal-page-script.js | src/main/webapp/meal-page-script.js | // Copyright 2020 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
function fetchMealInfo() {
// use mapping /meal.html?id=<id>
// fetches form server by action meal/<id>
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const id = urlParams.get("id");
if (id == null) {
window.location.replace("error.html");
}
fetch(`/meal/${id}`)
.then((response) => {
if (!response.ok) {
throw new Error("Network response was not ok");
window.location.replace("error.html");
}
return response.json();
})
.then((meal) => {
const { title, description, ingredients, type } = meal;
const titleElement = document.getElementById("title");
titleElement.innerText = encodingCheck(capitalizeFirst(title));
const descriptionElement = document.getElementById("description");
descriptionElement.innerText = encodingCheck(description);
const ingredientsElement = document.getElementById("ingredients");
for (const ingredient of ingredients) {
ingredientsElement.appendChild(
createElementByTag(encodingCheck(capitalizeFirst(ingredient)), "li")
);
}
createMap(type);
})
.catch((error) => {
console.log(error);
window.location.replace("error.html");
});
}
function redirectToSimilar() {
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const pageId = urlParams.get("id") ?? 0;
fetch(`/meal/similar?id=${pageId.toString()}`)
.then((response) => response.json())
.then((id) => {
const url = `/meal.html?id=${id.toString()}`;
window.location.replace(url);
});
}
/** Creates a map and adds it to the page. */
function createMap(type) {
const userLocation = new google.maps.LatLng(55.746514, 37.627022);
const mapOptions = {
zoom: 14,
center: userLocation,
};
const map = new google.maps.Map(document.getElementById("map"), mapOptions);
const locationMarker = new google.maps.Marker({
position: userLocation,
map,
title: "You are here (probably)",
label: "You",
animation: google.maps.Animation.DROP,
});
getCurrentPositionPromise()
.then((position) => {
const location = new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude
);
map.setCenter(location);
locationMarker.setPosition(location);
})
.catch((err) => {
if (err === "NO_GEOLOCATION") {
displayWarning("Your browser doesn't support geolocation.");
} else if (err === "GET_POSITION_FAILED") {
displayWarning(
"The Geolocation service failed. Share your location, please."
);
}
})
.then(() => {
const request = {
location: map.getCenter(),
radius: "1500",
type: ["restaurant", "cafe", "meal_takeaway", "bar", "bakery"],
query: type,
};
const service = new google.maps.places.PlacesService(map);
return getSearchPromise(service, request, map).then((results) => {
addRestaurants(results, map);
});
})
.catch((err) => {
console.log(`Caught error: ${err}`);
});
}
function addRestaurants(results, map) {
for (const result of results) {
createMarker(result, map);
}
}
function getSearchPromise(service, request) {
return new Promise((resolve, reject) => {
const onSuccess = (results, status) => {
if (status !== "OK") {
reject("FAILED");
} else {
resolve(results);
}
};
const onError = () => reject("FAILED");
service.textSearch(request, onSuccess, onError);
});
}
function getCurrentPositionPromise() {
return new Promise((resolve, reject) => {
if (!navigator.geolocation) {
reject("NO_GEOLOCATION");
} else {
const onSuccess = (position) => resolve(position);
const onError = () => reject("GET_POSITION_FAILED");
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
});
}
function createMarker(place, map) {
const marker = new google.maps.Marker({
map,
position: place.geometry.location,
title: place.name,
});
const infoWindow = new google.maps.InfoWindow({ content: place.name });
marker.addListener("click", () => {
infoWindow.open(map, marker);
});
}
function displayWarning(message) {
const warningElement = document.getElementById("warning");
warningElement.innerText = "";
warningElement.appendChild(createElementByTag("Warning: ", "b"));
warningElement.appendChild(createElementByTag(message, "span"));
}
| JavaScript | 0 | @@ -1664,32 +1664,16 @@
ngCheck(
-capitalizeFirst(
ingredie
@@ -1675,17 +1675,16 @@
redient)
-)
, %22li%22)%0A
|
be5c6c3f3a4830d6298c8ce190cd95179effa1eb | update maximum-depth-of-binary-tree solution | src/maximum-depth-of-binary-tree.js | src/maximum-depth-of-binary-tree.js | /*
* Given a binary tree, find its maximum depth.
* The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
*
* Tags:
* - Tree
* - Breadth-first Search
*/
var TreeNode = require('../lib/TreeNode');
var BinaryTree = require('../lib/BinaryTree');
/**
* @param {TreeNode} root
* @return {number}
*/
var maxDepth = function(root) {
if (root === null) {
return 0;
}
var maxLevel = 0;
function getMaxLevel(node, lv) {
if (node === null) return;
getMaxLevel(node.left, lv + 1);
if (lv > maxLevel) maxLevel = lv;
getMaxLevel(node.right, lv + 1);
}
getMaxLevel(root, 0);
return maxLevel + 1;
};
// mocha testing
var expect = require('chai').expect;
describe('Maximum Depth of Binary Tree', function() {
it('[]', function () {
var input = BinaryTree();
var output = maxDepth(input);
expect(output).to.equal(0);
});
it('[0]', function () {
var input = BinaryTree(0);
var output = maxDepth(input);
expect(output).to.equal(1);
});
it('[1, 2, 3]', function () {
var input = BinaryTree(1, 2, 3);
var output = maxDepth(input);
expect(output).to.equal(2);
});
it('[1, 2, 3, 4]', function () {
var input = BinaryTree(1, 2, 3, 4);
var output = maxDepth(input);
expect(output).to.equal(3);
});
});
| JavaScript | 0.000001 | @@ -444,232 +444,167 @@
%0A%0A
-var maxLevel = 0;%0A function getMaxLevel(node, lv) %7B%0A if (node === null) return;
+// it's leaf node%0A if (root.left === null && root.right === null) %7B
%0A
-getMaxLevel(node.left, lv +
+return
1
-)
;%0A
- if (lv %3E maxLevel) maxLevel = lv;%0A getMaxLevel(node.right, lv + 1);%0A %7D%0A%0A getMaxLevel(root, 0
+%7D%0A%0A var left = maxDepth(root.left);%0A var right = maxDepth(root.right
);%0A
+%0A
re
@@ -612,16 +612,29 @@
urn
-maxLevel
+Math.max(left, right)
+ 1
|
fbcd656521b1b5ce512e35e70235d9cd696aa858 | Add firstTimeAttender field | both/collections/registrants.js | both/collections/registrants.js | Registrants = new Meteor.Collection("registrants");
Registrants.allow({
// User must be logged in to register
insert: function (userId, doc) {
return !! userId;
}
});
Registrants.attachSchema(new SimpleSchema({
'first_name' : {
type: String,
label: "First Name",
max: 200
},
'last_name': {
type: String,
label: "Last Name",
max: 200
},
'age': {
label: "Age at time of event",
type: Number,
max: 115,
min: 0
},
'ageGroup': {
type: String,
allowedValues: [
'child',
'youth',
'teen',
'youngAdult',
'adult'
],
optional: true,
autoValue: function (doc) {
// calculate age group based on age field
return calculateAgeGroup(this.field("age").value);
}
},
'childrenProgram': {
type: String,
optional: true,
autoValue: function () {
// Get registrant age
const registrantAge = this.field("age").value;
// Registrants younger than 13 automatically in children's program
if (registrantAge < 13) {
return "yes";
}
}
},
'jymProgram': {
type: String,
optional: true,
autoValue: function () {
// Get registrant age
const registrantAge = this.field("age").value;
// Registrants between 14 and 17 automatically in teen program
if (registrantAge > 13 && registrantAge < 18) {
return "yes";
}
}
},
'yafProgram': {
type: String,
optional: true
},
'gradeInSchool': {
type: String,
optional: true,
label: "School grade in Fall",
allowedValues: [
"K",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12"
],
autoform: {
type: "select",
options: function () {
return [
{label: "K", value: "K"},
{label: "1", value: "1"},
{label: "2", value: "2"},
{label: "3", value: "3"},
{label: "4", value: "4"},
{label: "5", value: "5"},
{label: "6", value: "6"},
{label: "7", value: "7"},
{label: "8", value: "8"},
{label: "9", value: "9"},
{label: "10", value: "10"},
{label: "11", value: "11"},
{label: "12", value: "12"},
];
}
}
},
'postalAddress': {
type: String,
optional: true,
label: "Primary postal address",
autoform: {
afFieldInput: {
type: "textarea"
}
}
},
'telephone': {
type: String,
optional: true,
label: "Primary telephone number",
max: 20
},
'registrationType': {
type: String,
allowedValues: [
'commuter',
'daily',
'weekly',
'cancelled'
]
},
'accommodations': {
type: String,
allowedValues: [
'camping',
'dorm',
'semiprivate'
],
optional: true,
custom: function () {
// Required if registration is daily or weekly
if ( !this.isSet
&&
(
this.field('registrationType').value === "daily"
||
this.field('registrationType').value === "weekly")
) {
return "required";
}
}
},
days: {
type: [String],
optional: true,
autoform: {
type: "select-checkbox-inline",
options: function () {
return [
{label: "Friday", value: "Friday"},
{label: "Saturday", value: "Saturday"},
{label: "Sunday", value: "Sunday"},
{label: "Monday", value: "Monday"},
{label: "Tuesday", value: "Tuesday"},
{label: "Wednesday", value: "Wednesday"}
];
}
}
},
foodPreference: {
type: [String],
optional: true,
autoform: {
type: "select-checkbox-inline",
allowedValues: [
'Omnivore',
'Vegetarian',
'Vegan',
'Gluten-free',
'Dairy-free',
'Sugar-free',
'Soy-free',
'Raw vegetables',
'Low-salt'
],
options: function () {
return [
{label: "Omnivore", value: "Omnivore"},
{label: "Vegetarian", value: "Vegetarian"},
{label: "Vegan", value: "Vegan"},
{label: "Gluten-free", value: "Gluten-free"},
{label: "Dairy-free", value: "Dairy-free"},
{label: "Sugar-free", value: "Sugar-free"},
{label: "Soy-free", value: "Soy-free"},
{label: "Raw vegetables", value: "Raw vegetables"},
{label: "Low-salt", value: "Low-salt"}
];
}
}
},
'registrantEmail': {
type: String,
regEx: SimpleSchema.RegEx.Email,
label: "Registrant E-mail address",
optional: true
},
'registrantAffiliation': {
type: String,
optional: true,
label: "Affiliated Quaker meeting, worship group, or organization"
},
'linens': {
type: Boolean,
optional: true,
defaultValue: false,
label: "Will you need linens? ($25 extra)"
},
'specialNeeds': {
type: String,
optional: true,
label: "Tell us about any special needs that we can accommodate.",
autoform: {
afFieldInput: {
type: "textarea"
}
}
},
'carbonTax': {
type: Number,
label: "Voluntary carbon tax ($USD)",
optional: true
},
'donation': {
type: Number,
label: "Optional donation ($USD)",
optional: true
},
'fee' : {
type: Number,
decimal: true,
label: "Fee",
optional: true,
autoValue: function (doc) {
// Set up an empty registration object
// to hold values from the submitted registration
var registration = {};
// get values from submitted registration and
// set attributes on the registration object
registration.age = this.field("age").value;
registration.ageGroup = calculateAgeGroup(registration.age);
registration.type = this.field("registrationType").value;
registration.accommodations = this.field("accommodations").value;
registration.days = this.field("days").value;
registration.firstTimeAttender = this.field("firstTimeAttender").value;
registration.linens = this.field("linens").value;
registration.carbonTax = this.field("carbonTax").value;
// calculate the registration fee
// based on the submitted registration
return calculateRegistrationPrice(registration);
}
}
}));
Registrants.before.insert(function (userId, doc){
// set registration created date to current date
doc.createdAt = Date.now();
// Attach registration to Meteor user
// for reporting, access control, etc
doc.createdById = userId;
// Add user email address to registration document
doc.createdByEmail = Meteor.users.findOne(userId).emails[0].address;
});
| JavaScript | 0 | @@ -903,24 +903,172 @@
%7D%0A %7D,%0A
+ 'firstTimeAttender': %7B%0A type: Boolean,%0A optional: true,%0A defaultValue: false,%0A label: %22First time attender?%22%0A %7D,%0A
'childre
|
a91d37c1f936fc313880812c65d25588d36f379a | fix js error | cdap-ui/app/features/hydrator/services/create/actions/config-actions.js | cdap-ui/app/features/hydrator/services/create/actions/config-actions.js | /*
* Copyright © 2015 Cask Data, 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.
*/
class ConfigActionsFactory {
constructor(ConfigDispatcher, myPipelineApi, $state, ConfigStore, mySettings, ConsoleActionsFactory, EventPipe, myAppsApi, GLOBALS, myHelpers, $stateParams) {
this.ConfigStore = ConfigStore;
this.mySettings = mySettings;
this.$state = $state;
this.myPipelineApi = myPipelineApi;
this.ConsoleActionsFactory = ConsoleActionsFactory;
this.EventPipe = EventPipe;
this.myAppsApi = myAppsApi;
this.GLOBALS = GLOBALS;
this.myHelpers = myHelpers;
this.$stateParams = $stateParams;
this.dispatcher = ConfigDispatcher.getDispatcher();
}
initializeConfigStore(config) {
this.dispatcher.dispatch('onInitialize', config);
}
setMetadataInfo(name, description) {
this.dispatcher.dispatch('onMetadataInfoSave', name, description);
}
setDescription(description) {
this.dispatcher.dispatch('onDescriptionSave', description);
}
setConfig(config) {
this.dispatcher.dispatch('onConfigSave', config);
}
savePlugin(plugin, type) {
this.dispatcher.dispatch('onPluginSave', {plugin: plugin, type: type});
}
saveAsDraft(config) {
this.dispatcher.dispatch('onSaveAsDraft', config);
}
setArtifact(artifact) {
this.dispatcher.dispatch('onArtifactSave', artifact);
}
addPlugin (plugin, type) {
this.dispatcher.dispatch('onPluginAdd', plugin, type);
}
editPlugin(pluginId, pluginProperties) {
this.dispatcher.dispatch('onPluginEdit', pluginId, pluginProperties);
}
propagateSchemaDownStream(pluginId) {
this.dispatcher.dispatch('onSchemaPropagationDownStream', pluginId);
}
setSchedule(schedule) {
this.dispatcher.dispatch('onSetSchedule', schedule);
}
setInstance(instance) {
this.dispatcher.dispatch('onSetInstance', instance);
}
publishPipeline() {
this.ConsoleActionsFactory.resetMessages();
let error = this.ConfigStore.validateState(true);
if (!error) { return; }
this.EventPipe.emit('showLoadingIcon', 'Publishing Pipeline to CDAP');
let removeFromUserDrafts = (adapterName) => {
this.mySettings
.get('adapterDrafts')
.then(
(res) => {
var savedDraft = this.myHelpers.objectQuery(res, this.$stateParams.namespace, adapterName);
if (savedDraft) {
delete res[this.$stateParams.namespace][adapterName];
return this.mySettings.set('adapterDrafts', res);
}
},
(err) => {
this.ConsoleActionsFactory.addMessage({
type: 'error',
content: err
});
return this.$q.reject(false);
}
)
.then(
() => {
this.EventPipe.emit('hideLoadingIcon.immediate');
this.$state.go('hydrator.detail', { pipelineId: adapterName });
}
);
};
let publish = (pipelineName) => {
this.myPipelineApi.save(
{
namespace: this.$state.params.namespace,
pipeline: pipelineName
},
config
)
.$promise
.then(
removeFromUserDrafts.bind(this, pipelineName),
(err) => {
this.EventPipe.emit('hideLoadingIcon.immediate');
this.ConsoleActionsFactory.addMessage({
type: 'error',
content: angular.isObject(err) ? err.data : err;
});
}
);
};
var config = this.ConfigStore.getConfigForExport();
// Checking if Pipeline name already exist
this.myAppsApi
.list({ namespace: this.$state.params.namespace })
.$promise
.then( (apps) => {
var appNames = apps.map( (app) => { return app.name; } );
if (appNames.indexOf(config.name) !== -1) {
this.ConsoleActionsFactory.addMessage({
type: 'error',
content: this.GLOBALS.en.hydrator.studio.error['NAME-ALREADY-EXISTS']
});
this.EventPipe.emit('hideLoadingIcon.immediate');
} else {
publish(config.name);
}
});
}
}
ConfigActionsFactory.$inject = ['ConfigDispatcher', 'myPipelineApi', '$state', 'ConfigStore', 'mySettings', 'ConsoleActionsFactory', 'EventPipe', 'myAppsApi', 'GLOBALS', 'myHelpers', '$stateParams'];
angular.module(`${PKG.name}.feature.hydrator`)
.service('ConfigActionsFactory', ConfigActionsFactory);
| JavaScript | 0.000001 | @@ -3933,17 +3933,16 @@
ta : err
-;
%0A
|
0c66015835503e6cff20732da58d3d106aef6f06 | Revert "prevent httpErrorHandler from swallowing non http errors when used with cors" | src/middlewares/httpErrorHandler.js | src/middlewares/httpErrorHandler.js | module.exports = (opts) => {
const defaults = {
logger: console.error
}
const options = Object.assign({}, defaults, opts)
return ({
onError: (handler, next) => {
if (typeof options.logger === 'function') {
options.logger(handler.error)
}
handler.response = handler.response || {}
if (handler.error.constructor.super_ && handler.error.constructor.super_.name === 'HttpError') {
handler.response = {
statusCode: handler.error.statusCode,
body: handler.error.message
}
return next()
} else {
handler.response.statusCode = 502
handler.response.body = JSON.stringify({ message: 'Internal server error' })
}
return next(handler.error)
}
})
}
| JavaScript | 0 | @@ -187,534 +187,350 @@
if (
-typeof options.logger === 'function') %7B%0A options.logger(handler.error)%0A %7D%0A%0A handler.response = handler.response %7C%7C %7B%7D%0A if (handler.error.constructor.super_ && handler.error.constructor.super_.name === 'HttpError') %7B%0A handler.response = %7B%0A statusCode: handler.error.statusCode,%0A body: handler.error.message%0A %7D%0A%0A return next()%0A %7D else %7B%0A handler.response.statusCode = 502%0A handler.response.body = JSON.stringify(%7B message: 'Internal server error' %7D
+handler.error.constructor.super_ && handler.error.constructor.super_.name === 'HttpError') %7B%0A if (typeof options.logger === 'function') %7B%0A options.logger(handler.error)%0A %7D%0A%0A handler.response = %7B%0A statusCode: handler.error.statusCode,%0A body: handler.error.message%0A %7D%0A%0A return next(
)%0A
|
b29a08c6f73fe175a29ed6018dcf1e4c5c02ed58 | Use underscore for standard lib parameter names | backend/javascript-generator.js | backend/javascript-generator.js | /*
* Translation to JavaScript
*
* Requiring this module adds a gen() method to each of the AST classes.
* Nothing is actually exported from this module.
*
* Generally, calling e.gen() where e is an expression node will return the
* JavaScript translation as a string, while calling s.gen() where s is a
* statement-level node will write its translation to standard output.
*
* require('./backend/javascript-generator');
* program.gen();
*/
const Context = require('../semantics/context');
const Program = require('../ast/program');
const VariableDeclaration = require('../ast/variable-declaration');
const AssignmentStatement = require('../ast/assignment-statement');
const BreakStatement = require('../ast/break-statement');
const ReturnStatement = require('../ast/return-statement');
const IfStatement = require('../ast/if-statement');
const WhileStatement = require('../ast/while-statement');
const CallStatement = require('../ast/call-statement');
const FunctionDeclaration = require('../ast/function-declaration');
const FunctionObject = require('../ast/function-object');
const BinaryExpression = require('../ast/binary-expression');
const UnaryExpression = require('../ast/unary-expression');
const IdentifierExpression = require('../ast/identifier-expression');
const SubscriptedExpression = require('../ast/subscripted-expression');
const Variable = require('../ast/variable');
const Call = require('../ast/call');
const Parameter = require('../ast/parameter');
const Argument = require('../ast/argument');
const BooleanLiteral = require('../ast/boolean-literal');
const NumericLiteral = require('../ast/numeric-literal');
const StringLiteral = require('../ast/string-literal');
const indentPadding = 2;
let indentLevel = 0;
function emit(line) {
console.log(`${' '.repeat(indentPadding * indentLevel)}${line}`);
}
function genStatementList(statements) {
indentLevel += 1;
statements.forEach(statement => statement.gen());
indentLevel -= 1;
}
function makeOp(op) {
return { not: '!', and: '&&', or: '||', '==': '===', '!=': '!==' }[op] || op;
}
// jsName(e) takes any PlainScript object with an id property, such as a
// Variable, Parameter, or FunctionDeclaration, and produces a JavaScript
// name by appending a unique indentifying suffix, such as '_1' or '_503'.
// It uses a cache so it can return the same exact string each time it is
// called with a particular entity.
const jsName = (() => {
let lastId = 0;
const map = new Map();
return (v) => {
if (!(map.has(v))) {
map.set(v, ++lastId); // eslint-disable-line no-plusplus
}
return `${v.id}_${map.get(v)}`;
};
})();
// This is a nice helper for variable declarations and assignment statements.
// The AST represents both of these with lists of sources and lists of targets,
// but when writing out JavaScript it seems silly to write `[x] = [y]` when
// `x = y` suffices.
function bracketIfNecessary(a) {
if (a.length === 1) {
return `${a}`;
}
return `[${a.join(', ')}]`;
}
function generateLibraryFunctions() {
function generateLibraryStub(name, params, body) {
const entity = Context.INITIAL.declarations[name];
emit(`function ${jsName(entity)}(${params}) {${body}}`);
}
// This is sloppy. There should be a better way to do this.
generateLibraryStub('print', 's', 'console.log(s);');
generateLibraryStub('sqrt', 'x', 'return Math.sqrt(x);');
}
Object.assign(Argument.prototype, {
gen() { return this.expression.gen(); },
});
Object.assign(AssignmentStatement.prototype, {
gen() {
const targets = this.targets.map(t => t.gen());
const sources = this.sources.map(s => s.gen());
emit(`${bracketIfNecessary(targets)} = ${bracketIfNecessary(sources)};`);
},
});
Object.assign(BinaryExpression.prototype, {
gen() { return `(${this.left.gen()} ${makeOp(this.op)} ${this.right.gen()})`; },
});
Object.assign(BooleanLiteral.prototype, {
gen() { return `${this.value}`; },
});
Object.assign(BreakStatement.prototype, {
gen() { return 'break;'; },
});
Object.assign(CallStatement.prototype, {
gen() { emit(`${this.call.gen()};`); },
});
Object.assign(Call.prototype, {
gen() {
const fun = this.callee.referent;
const params = {};
const args = Array(this.args.length).fill(undefined);
fun.params.forEach((p, i) => { params[p.id] = i; });
this.args.forEach((a, i) => { args[a.isPositionalArgument ? i : params[a.id]] = a; });
return `${jsName(fun)}(${args.map(a => (a ? a.gen() : 'undefined')).join(', ')})`;
},
});
Object.assign(FunctionDeclaration.prototype, {
gen() { return this.function.gen(); },
});
Object.assign(FunctionObject.prototype, {
gen() {
emit(`function ${jsName(this)}(${this.params.map(p => p.gen()).join(', ')}) {`);
genStatementList(this.body);
emit('}');
},
});
Object.assign(IdentifierExpression.prototype, {
gen() { return this.referent.gen(); },
});
Object.assign(IfStatement.prototype, {
gen() {
this.cases.forEach((c, index) => {
const prefix = index === 0 ? 'if' : '} else if';
emit(`${prefix} (${c.test.gen()}) {`);
genStatementList(c.body);
});
if (this.alternate) {
emit('} else {');
genStatementList(this.alternate);
}
emit('}');
},
});
Object.assign(NumericLiteral.prototype, {
gen() { return `${this.value}`; },
});
Object.assign(Parameter.prototype, {
gen() {
let translation = jsName(this);
if (this.defaultExpression) {
translation += ` = ${this.defaultExpression.gen()}`;
}
return translation;
},
});
Object.assign(Program.prototype, {
gen() {
generateLibraryFunctions();
this.statements.forEach(statement => statement.gen());
},
});
Object.assign(ReturnStatement.prototype, {
gen() {
if (this.returnValue) {
emit(`return ${this.returnValue.gen()};`);
} else {
emit('return;');
}
},
});
Object.assign(StringLiteral.prototype, {
gen() { return `${this.value}`; },
});
Object.assign(SubscriptedExpression.prototype, {
gen() {
const base = this.variable.gen();
const subscript = this.subscript.gen();
return `${base}[${subscript}]`;
},
});
Object.assign(UnaryExpression.prototype, {
gen() { return `(${makeOp(this.op)} ${this.operand.gen()})`; },
});
Object.assign(VariableDeclaration.prototype, {
gen() {
const variables = this.variables.map(v => v.gen());
const initializers = this.initializers.map(i => i.gen());
emit(`let ${bracketIfNecessary(variables)} = ${bracketIfNecessary(initializers)};`);
},
});
Object.assign(Variable.prototype, {
gen() { return jsName(this); },
});
Object.assign(WhileStatement.prototype, {
gen() {
emit(`while (${this.test.gen()}) {`);
genStatementList(this.body);
emit('}');
},
});
| JavaScript | 0 | @@ -3312,17 +3312,17 @@
rint', '
-s
+_
', 'cons
@@ -3329,17 +3329,17 @@
ole.log(
-s
+_
);');%0A
@@ -3367,17 +3367,17 @@
sqrt', '
-x
+_
', 'retu
@@ -3389,17 +3389,17 @@
th.sqrt(
-x
+_
);');%0A%7D%0A
|
b9f696343c4c578d199f5741dbe0a1e77f925e55 | remove extraneous _e call method | bridge/lib/ref.js | bridge/lib/ref.js | // if node
var util = require('./util.js');
// end node
var Ref = function (bridgeRoot, pathchain, operations) {
function Ref() {
var args = [].slice.apply(arguments);
Ref.call.apply(Ref, args);
}
Ref._fixops = function() {
for (var x in Ref._operations) {
var op = Ref._operations[x];
Ref[op] = Ref.get(op).call;
Ref[op + '_e'] = Ref.get(op).call;
}
};
Ref.get = function(pathadd) {
var pathadd = pathadd.split('.');
return Ref._bridgeRoot.getPathObj( Ref._pathchain.concat(pathadd) );
};
Ref.call = function() {
var args = [].slice.apply(arguments);
util.info('Calling', Ref._pathchain, args);
return Ref._bridgeRoot.send(args, Ref);
};
Ref.getLocalName = function() {
return Ref._pathchain[2];
};
Ref._getRef = function(operations) {
Ref._operations = operations;
Ref._fixops();
return Ref;
};
Ref.toDict = function() {
return {'ref': Ref._pathchain, 'operations': Ref._operations};
};
Ref._operations = operations || [];
Ref._bridgeRoot = bridgeRoot;
Ref._pathchain = pathchain;
Ref._fixops();
return Ref;
};
// if node
module.exports = Ref;
// end node
| JavaScript | 0.006482 | @@ -342,49 +342,8 @@
ll;%0A
- Ref%5Bop + '_e'%5D = Ref.get(op).call;%0A
|
49eeaff952a91a065970e4f02f8cc20c72e58fff | update for Subsonic beta 6.0 | extension/keysocket-subsonic.js | extension/keysocket-subsonic.js | function onKeyPress(key) {
if (this.jwplayer) {
if (key === NEXT) {
var playPauseButton = document.querySelector('img[onclick="onNext(false)"]');
simulateClick(playPauseButton);
} else if (key === PLAY) {
location.href = "javascript:window.jwplayer().play()";
} else if (key === PREV) {
var backButton = document.querySelector('img[onclick="onPrevious()"]');
simulateClick(backButton);
}
}
}
| JavaScript | 0 | @@ -77,122 +77,65 @@
-var playPauseButton = document.querySelector('img%5Bonclick=%22onNext(false)%22%5D');%0A simulateClick(playPauseButton)
+location.href = %22javascript:window.onNext(repeatEnabled)%22
;%0A
@@ -265,111 +265,56 @@
-var backButton = document.querySelector('img%5Bonclick=%22onPrevious()%22%5D');%0A simulateClick(backButton)
+location.href = %22javascript:window.onPrevious()%22
;%0A
|
d2642382cc812c1da7ee3b52823156377e2da767 | Improve selector | extension/keysocket-subsonic.js | extension/keysocket-subsonic.js | function onKeyPress(key) {
if (this.jwplayer) {
if (key === NEXT) {
var playPauseButton = document.querySelector('img[src="icons/default_dark/forward.png"]');
simulateClick(playPauseButton);
} else if (key === PLAY) {
location.href = "javascript:window.jwplayer().play()";
} else if (key === PREV) {
var backButton = document.querySelector('img[src="icons/default_dark/back.png"]');
simulateClick(backButton);
}
}
}
| JavaScript | 0.000002 | @@ -20,17 +20,18 @@
(key) %7B%0A
-%09
+
if (this
@@ -43,18 +43,20 @@
ayer) %7B%0A
-%09%09
+
if (key
@@ -63,27 +63,30 @@
=== NEXT) %7B%0A
-%09%09%09
+
var playPaus
@@ -127,52 +127,42 @@
img%5B
-src=%22icons/default_dark/forward.png%22%5D');%0A%09%09%09
+onclick=%22onNext(false)%22%5D');%0A
simu
@@ -189,18 +189,20 @@
utton);%0A
-%09%09
+
%7D else i
@@ -281,18 +281,20 @@
lay()%22;%0A
-%09%09
+
%7D else i
@@ -312,19 +312,22 @@
PREV) %7B%0A
-%09%09%09
+
var back
@@ -367,49 +367,41 @@
img%5B
-src=%22icons/default_dark/back.png%22%5D');%0A%09%09%09
+onclick=%22onPrevious()%22%5D');%0A
simu
@@ -427,13 +427,16 @@
n);%0A
-%09%09%7D%0A%09
+ %7D%0A
%7D%0A%7D%0A
|
cbd7ce3696261aae4cbbe453f91bfcf76ffbfcc4 | use info level as default if none is given | src/notification-service.js | src/notification-service.js | import {Container} from 'aurelia-dependency-injection';
import {inject} from 'aurelia-framework';
import {Origin} from 'aurelia-metadata';
import {CompositionEngine} from 'aurelia-templating';
import {invokeLifecycle} from './lifecycle';
import {NotificationController} from './notification-controller';
import {NotificationLevel} from './notification-level';
import {NotificationRenderer} from './notification-renderer';
@inject(CompositionEngine, Container, NotificationRenderer)
export class NotificationService {
constructor(compositionEngine, container, notificationRenderer) {
this.compositionEngine = compositionEngine;
this.container = container;
this.notificationRenderer = notificationRenderer;
}
_getViewModel(compositionContext) {
if (typeof compositionContext.viewModel === 'function') {
compositionContext.viewModel = Origin.get(compositionContext.viewModel).moduleId;
}
if (typeof compositionContext.viewModel === 'string') {
return this.compositionEngine.ensureViewModel(compositionContext);
}
return Promise.resolve(compositionContext);
}
notify(message, settings, level) {
let notificationLevel = level || NotificationLevel.info;
let _settings = Object.assign({}, this.notificationRenderer.defaultSettings, settings);
_settings.model = {
notification: message,
level: level
};
return new Promise((resolve, reject) => {
let notificationController = new NotificationController(this.notificationRenderer, _settings, resolve, reject);
let childContainer = this.container.createChild();
let compositionContext = {
viewModel: _settings.viewModel,
container: this.container,
childContainer: childContainer,
model: _settings.model
};
childContainer.registerInstance(NotificationController, notificationController);
this._getViewModel(compositionContext).then(returnedCompositionContext => {
notificationController.viewModel = returnedCompositionContext.viewModel;
return invokeLifecycle(returnedCompositionContext.viewModel, 'canActivate', _settings.model).then(canActivate => {
if (canActivate) {
return this.compositionEngine.createController(returnedCompositionContext).then(controller => {
notificationController.controller = controller;
notificationController.view = controller.view;
controller.automate();
return this.notificationRenderer.createNotificationHost(notificationController).then(() => {
return this.notificationRenderer.showNotification(notificationController);
});
});
}
});
});
});
}
info(message, settings) {
this.notify(message, settings, NotificationLevel.info);
}
success(message, settings) {
this.notify(message, settings, NotificationLevel.success);
}
warning(message, settings) {
this.notify(message, settings, NotificationLevel.warning);
}
danger(message, settings) {
this.notify(message, settings, NotificationLevel.danger);
}
}
| JavaScript | 0 | @@ -1364,17 +1364,29 @@
level:
-l
+notificationL
evel%0A
|
837fbf14c48b707b22c5ad69217fd0f02da31066 | Use utf-8 to unintentionally pop up character visibility issues | extensions/tools/hooks/stats.js | extensions/tools/hooks/stats.js | 'use strict';
var storeStats = function(time, stats) {
var i, value, tmp;
for (i in Memory.statsHistory) {
value = i in stats ? stats[i] : NaN;
// Grab previous value
tmp = Memory.statsHistory[i][Memory.statsHistory[i].length - 1];
// Value is same
if (tmp.type === undefined && tmp.value === value && tmp.last === (time - 1)) {
tmp.last = time;
// Value is counting up
} else if (tmp.last === (time - 1) && tmp.value === (value - 1) &&
(tmp.type === "countUp" || tmp.start === tmp.last)
) {
if (tmp.start === tmp.last) {
tmp.type = "countUp";
tmp.startValue = tmp.value;
}
tmp.last = time;
tmp.value = value;
// Default case
} else {
Memory.statsHistory[i].push({start: time, last: time, value: stats[i]});
}
}
// Check for new statistics
for (i in stats) {
if (!(i in Memory.statsHistory)) {
Memory.statsHistory[i] = [{start: time, last: time, value: stats[i]}];
}
}
};
var updateStats = function() {
var addStatWithMax = function(entry, n) {
Memory.stats[entry] = n;
Memory.stats[entry + 'Max'] = previous === undefined ?
n : Math.max(previous[entry + 'Max'], n);
};
var previous;
if (Memory.stats) {
storeStats(Memory.stats.time, Memory.stats);
previous = Memory.stats;
} else {
Memory.statsHistory = {};
Memory.statsDescription = {
'time': 'Time when taking stats',
// Creeps
'myCreeps': 'Current number of owning creeps',
'myCreepsMax': 'Maximum number of owning creeps',
// Queue
'globalQueue': 'Current number of creeps in global spawn queue',
'globalQueueMax': 'Maximum number of creeps in global spawn queue',
'globalPriorityQueue': 'Current number of creeps in global priority spawn queue',
'globalPriorityQueueMax': 'Maximum number of creeps in global priority spawn queue',
// Spawns
'mySpawns': 'Current number of owning spawns',
'mySpawnsMax': 'Maximum number of owning spawns',
// Flags
'myFlags': 'Current number of owning flags',
'myFlagsMax': 'Maximum number of owning flags',
};
}
Memory.stats = {
'time': Game.time,
};
// Creeps
addStatWithMax('myCreeps', Object.keys(Game.creeps).length);
// Global queues
addStatWithMax('globalQueue', Memory.spawnQueue.length);
addStatWithMax('globalPriorityQueue', Memory.spawnPriorityQueue.length);
// Spawns
addStatWithMax('mySpawns', Object.keys(Game.spawns).length);
// Flags
addStatWithMax('myFlags', Object.keys(Game.flags).length);
};
var printStatus = function() {
if (Game.time % AI.settings.statusFrequency !== 0) {
return;
}
var msg = '';
msg += "***** Round " + Game.time + " *****" + "\n\n";
msg += "Number of creeps in global queue: " + Memory.stats.globalQueue + "\n";
msg += "Number of creeps in global priorityQueue: " + Memory.stats.globalPriorityQueue + "\n";
msg += "Number of own spawn: " + Memory.stats.mySpawns + "\n";
msg += "Number of own creeps: " + Memory.stats.myCreeps + "\n";
msg += "Number of flags: " + Memory.stats.myFlags + "\n";
console.log(msg);
};
function preController() {
updateStats();
printStatus();
}
function postController() {
}
module.exports = {
preController: preController,
postController: postController
};
| JavaScript | 0 | @@ -3204,32 +3204,17 @@
msg += %22
-Number of creeps
+%E2%99%98
in glob
@@ -3275,24 +3275,9 @@
+= %22
-Number of creeps
+%E2%99%98
in
@@ -3335,32 +3335,33 @@
tyQueue + %22%5Cn%22;%0A
+%0A
msg += %22Numbe
@@ -3359,28 +3359,9 @@
+= %22
-Number of own spawn:
+%F0%9F%8F%A0
%22 +
@@ -3382,23 +3382,16 @@
mySpawns
- + %22%5Cn%22
;%0A msg
@@ -3399,29 +3399,12 @@
+= %22
-Number of own creeps:
+ - %E2%99%98
%22 +
@@ -3425,23 +3425,16 @@
myCreeps
- + %22%5Cn%22
;%0A msg
@@ -3442,24 +3442,12 @@
+= %22
-Number of flags:
+ - %F0%9F%9A%A9
%22 +
|
2da874ad7405e565c80e37edf3266ac7982b2b32 | Build new release | build/angular-no-captcha.min.js | build/angular-no-captcha.min.js | "use strict";angular.module("noCAPTCHA",[]).provider("googleGrecaptcha",function(){var a;this.setLanguage=function(b){a=b},this.$get=["$q","$window","$document","$rootScope",function(b,c,d,e){var f=b.defer();c.recaptchaOnloadCallback=function(){e.$apply(function(){f.resolve()})};var g=d[0].createElement("script"),h="https://www.google.com/recaptcha/api.js?onload=recaptchaOnloadCallback&render=explicit";return a&&(h+="&hl="+a),g.src=h,d[0].body.appendChild(g),f.promise}]}).provider("noCAPTCHA",["googleGrecaptchaProvider",function(a){var b,c,d;this.setSiteKey=function(a){b=a},this.setSize=function(a){c=a},this.setTheme=function(a){d=a},this.setLanguage=function(b){a.setLanguage(b)},this.$get=function(){return{theme:d,siteKey:b,size:c}}}]).directive("noCaptcha",["noCAPTCHA","googleGrecaptcha","$document","$window",function(a,b,c,d){var e=function(){for(var a=c[0].getElementsByClassName("pls-container"),b=0;b<a.length;b++)for(var d=a[b].parentNode;d.firstChild;)d.removeChild(d.firstChild)};return{restrict:"EA",scope:{gRecaptchaResponse:"=",siteKey:"@",size:"@",theme:"@",control:"=?",expiredCallback:"=?"},replace:!0,link:function(c,f){c.control=c.control||{};var g,h,i=c.control;if(h={sitekey:c.siteKey||a.siteKey,size:c.size||a.size,theme:c.theme||a.theme,callback:function(a){c.$apply(function(){c.gRecaptchaResponse=a})},"expired-callback":function(){c.expiredCallback&&"function"==typeof c.expiredCallback&&c.$apply(function(){c.expiredCallback()})}},!h.sitekey)throw new Error("Site Key is required");b.then(function(){g=d.grecaptcha.render(f[0],h),i.reset=function(){d.grecaptcha.reset(g),c.gRecaptchaResponse=null}}),c.$on("$destroy",function(){d.grecaptcha&&d.grecaptcha.reset(g),e()})}}}]); | JavaScript | 0 | @@ -406,16 +406,48 @@
;return
+g.type=%22application/javascript%22,
a&&(h+=%22
|
0d3882930e339c4b2e0a5083a8f2e01b39604a30 | Fix name typo in background module api | src/modules/background/utils/api.js | src/modules/background/utils/api.js | import { toUrl } from '@utils/url.utils';
import { prefetch as prefetchImage } from '@utils/image.utils';
import * as StorageUtils from '@utils/storage.utils';
import apiConfigs from '../configs/api.config';
import cacheConfigs from '../configs/cache.config';
const { client_id, base, uris } = apiConfigs;
const randomPhotoApiUrl = `${base}${uris.randomPhoto}`;
const prefetchedPhotoCacheKey = cacheConfigs.prefetchedPhotos;
const lastShownPhotoCacheKey = cacheConfigs.lastShownPhoto;
const lastShownTimeCacheKey = cacheConfigs.lastShownTime;
// random photos api defaults
const DEFAULTS = {
featured: true, orientation: 'landscape',
w: 1920, h: 1048, count: 20,
client_id,
};
// max photos to prefetch
const PREFETCH_THRESHOLD = 10;
/**
* Returns the photo url to use from the photo object.
*
* @param {Object} photo Photo object returned by the API
* @return {String} Photo url to use
*/
export function getPhotoUrl(photo = {}) {
const { urls = {} } = photo;
return urls.custom || urls.regular;
}
/**
* Fetched random photos from the API.
*
* @see https://unsplash.com/documentation#get-a-random-photo
*
* @param {Object} params Supported parameters
* @return {Promise} Promise that returns JSON data (Array of photos)
*/
export function fetchRandomPhotos(params = {}) {
params = {...DEFAULTS, ...params};
const url = toUrl(randomPhotoApiUrl, params);
return fetch(url).then(response => response.json())
.catch(response => []);
}
/**
* Prefetches the usable photo urls and
* stores corresponding photo objects in the cache.
*
* @todo: configurable categories option
*/
export async function prefetchRandomPhotos() {
const prefetchedPhotos = StorageUtils.get(prefetchedPhotoCacheKey);
const exisitngPrefetchedPhotosCount = prefetchedPhotos
&& Object.keys(prefetchedPhotos).length;
// if sufficient buffer, do not prefetch
if (exisitngPrefetchedPhotosCount >= PREFETCH_THRESHOLD) return;
// call random photos api
// then use image prefetch technique to prefetch the photo url
// then store each prefetched photo object in the cache
// { [photo id] : { photo object }, ... }
const photos = await fetchRandomPhotos();
photos.forEach(async photo => {
const url = getPhotoUrl(photo);
try {
await prefetchImage(url);
StorageUtils.update(prefetchedPhotoCacheKey, {[photo.id]: photo});
} catch(ex) {
// do nothing on image prefetch failure
}
});
}
/**
* Returns a random prefetched photo object from the cache.
* The returned photo is removed from the cache.
*
* @return {Object} Photo object as per the API
*/
export function getRandomPrefetchedPhoto() {
const prefetchedPhotos = StorageUtils.get(prefetchedPhotoCacheKey);
// no pre-fetched photos, return
if (!prefetchedPhotos || !Object.keys(prefetchedPhotos).length) {
return;
}
// there is at least one unused photo, pick the first one
const prefetchedPhotosIds = Object.keys(prefetchedPhotos);
const selectedId = prefetchedPhotosIds[0];
const unusedPhoto = prefetchedPhotos[selectedId];
// delete from cache and return the photo
delete prefetchedPhotos[selectedId];
StorageUtils.set(prefetchedPhotoCacheKey, prefetchedPhotos);
return unusedPhoto;
}
/**
* Returns a new photo to display based on the previously
* shown photo time and the passed duration to check.
*
* @param {Number} newPhotoDuration Duration to check
* @return {Object} Photo object as per the API
*/
export function getPrefetchedPhotoForDisplay(newPhotoDuration) {
// determine if a previously shown photo needs to be returned
if (Number.isInteger(newPhotoDuration)) {
const currentTime = Date.now();
const lastShownPhoto = StorageUtils.get(lastShownPhotoCacheKey);
const lastShownTime = StorageUtils.get(lastShownTimeCacheKey);
if (lastShownPhoto && Number.isInteger(lastShownTime)) {
const duration = currentTime - lastShownTime;
if (duration < newPhotoDuration) return lastShownPhoto;
}
}
// get a fresh new photo
const photo = getRandomPrefetchedPhoto();
if (photo) {
StorageUtils.set(lastShownPhotoCacheKey, photo);
StorageUtils.set(lastShownTimeCacheKey, Date.now());
}
return photo;
}
| JavaScript | 0 | @@ -1782,26 +1782,26 @@
const exis
-i
t
+i
ngPrefetched
@@ -1938,18 +1938,18 @@
if (exis
-i
t
+i
ngPrefet
|
44b5ddfbe461ae32e994d5bfbffe38021eb8a1f7 | copy config | app-template/apply.js | app-template/apply.js | #!/usr/bin/env node
'use strict';
//
var templates = {
'package-template.json': '/',
'index.html': 'www/',
'ios.html': 'www/',
'and.html': 'www/',
'boot.html': 'www/',
'config-template.xml': '/',
'ionic.config.json': '/',
'.desktop': 'webkitbuilds/',
'setup-win.iss': 'webkitbuilds/',
'build-macos.sh': 'webkitbuilds/',
'manifest.json': 'chrome-app/',
// 'bower.json': '/',
};
var configDir = process.argv[2] || 'bitchk';
var JSONheader = ' { ' + "\n" + ' "//":"Changes to this file will be overwritten",' + "\n" + ' "//":" Modify it in the app-template directory", ' + "\n";
var MakefileHeader = "# PLEASE! Do not edit this file directly \n# Modify it at app-template/\n";
var fs = require('fs-extra');
var path = require('path');
var configBlob = fs.readFileSync(configDir + '/appConfig.json', 'utf8');
var config = JSON.parse(configBlob, 'utf8');
/////////////////
console.log('Applying ' + config.nameCase + ' template');
Object.keys(templates).forEach(function(k) {
var targetDir = templates[k];
console.log(' # ' + k + ' => ' + targetDir);
var content = fs.readFileSync(k, 'utf8');
if (k.indexOf('.json') > 0) {
content = content.replace('{', JSONheader);
} else if (k.indexOf('Makefile') >= 0) {
content = MakefileHeader + content;
}
Object.keys(config).forEach(function(k) {
if (k.indexOf('_') == 0) return;
var r = new RegExp("\\*" + k.toUpperCase() + "\\*", "g");
content = content.replace(r, config[k]);
});
var r = new RegExp("\\*[A-Z]{3,30}\\*", "g");
var s = content.match(r);
if (s) {
console.log('UNKNOWN VARIABLE', s);
process.exit(1);
}
if (k === 'config-template.xml') {
k = 'config.xml';
} else if (k === 'package-template.json') {
k = 'package.json';
}
if (!fs.existsSync('../' + targetDir)) {
fs.mkdirSync('../' + targetDir);
}
fs.writeFileSync('../' + targetDir + k, content, 'utf8');
});
/////////////////
console.log('Copying ' + configDir + '/appConfig.json' + ' to root');
configBlob = configBlob.replace('{', JSONheader);
fs.writeFileSync('../appConfig.json', configBlob, 'utf8');
////////////////
var externalServices;
try {
var confName = configDir.toUpperCase();
var externalServicesConf = confName + '_EXTERNAL_SERVICES_CONFIG_LOCATION';
console.log('Looking for ' + externalServicesConf + '...');
if (typeof process.env[externalServicesConf] !== 'undefined') {
var location = process.env[externalServicesConf]
if (location.charAt(0) === '~') {
location = location.replace(/^\~/, process.env.HOME || process.env.USERPROFILE);
}
console.log('Found at: ' + location);
console.log('Copying ' + location + ' to root');
externalServices = fs.readFileSync(location, 'utf8');
} else {
throw externalServicesConf + ' environment variable not set.';
}
} catch (err) {
console.log(err);
externalServices = '{}';
console.log('External services not configured');
}
fs.writeFileSync('../externalServices.json', externalServices, 'utf8');
function copyDir(from, to) {
console.log('Copying dir ' + from + ' to ' + to);
if (fs.existsSync(to)) fs.removeSync(to); // remove previous app directory
if (!fs.existsSync(from)) return; // nothing to do
fs.copySync(from, to);
}
copyDir(configDir + '/deploy_config.js', '../www/' + config['bundleName'] + '_config.js');
copyDir(configDir + '/config/*', '../src/js/*');
// Push Notification
fs.copySync(configDir + '/GoogleService-Info.plist', '../GoogleService-Info.plist');
fs.copySync(configDir + '/google-services.json', '../google-services.json');
copyDir(configDir + '/img', '../www/img/app');
copyDir(configDir + '/sass', '../src/sass/app');
console.log("apply.js finished. \n\n"); | JavaScript | 0.000001 | @@ -3528,24 +3528,25 @@
onfig.js');%0A
+%0A
copyDir(conf
@@ -3561,18 +3561,16 @@
'/config
-/*
', '../s
@@ -3575,17 +3575,22 @@
/src/js/
-*
+config
');%0A// P
|
a8703a4ed2c9f0db0a9b70a1e4e9edd78a00d917 | remove log | ckeditor/plugins/freme/plugin.js | ckeditor/plugins/freme/plugin.js | /**
* Created by bjdmeest on 4/12/2015.
*/
CKEDITOR.plugins.add('freme', {
init: function (editor) {
var $ = window.$ || window.jQuery;
console.log(this.path);
if (!$) {
editor.showNotification('jQuery not found!', 'warning');
}
editor.addContentsCss(this.path + 'styles/style-freme.css');
editor.addCommand('fremeTranslate', new CKEDITOR.dialogCommand('fremeTranslateDialog'));
editor.ui.addButton('FremeTranslate', {
label: 'Translate',
command: 'fremeTranslate',
icon: this.path + 'icons/fremeTranslate.png',
toolbar: 'freme'
});
CKEDITOR.dialog.add('fremeTranslateDialog', this.path + 'dialogs/translate.js');
editor.addCommand('fremeEntity', new CKEDITOR.dialogCommand('fremeEntityDialog'));
editor.ui.addButton('FremeEntity', {
label: 'Detect concepts',
command: 'fremeEntity',
icon: this.path + 'icons/fremeEntity.png',
toolbar: 'freme'
});
CKEDITOR.dialog.add('fremeEntityDialog', this.path + 'dialogs/entity.js');
editor.addCommand('fremeLink', new CKEDITOR.dialogCommand('fremeLinkDialog'));
editor.ui.addButton('FremeLink', {
label: 'Get additional info',
command: 'fremeLink',
icon: this.path + 'icons/fremeLink.png',
toolbar: 'freme'
});
CKEDITOR.dialog.add('fremeLinkDialog', this.path + 'dialogs/link.js');
editor.on('instanceReady', function () {
editor.commands.fremeLink.disable();
});
editor.on('mode', function () {
editor.commands.fremeLink.disable();
});
editor.on('doubleclick', function() {
if ($(editor.document.getSelection().getStartElement().$).attr('its-ta-ident-ref')) {
editor.openDialog('fremeLinkDialog');
}
});
editor.on('selectionChange', function () {
if ($(editor.document.getSelection().getStartElement().$).attr('its-ta-ident-ref')) {
editor.commands.fremeLink.enable();
}
else {
editor.commands.fremeLink.disable();
}
});
}
}); | JavaScript | 0.000001 | @@ -148,41 +148,8 @@
y;%0A%0A
- console.log(this.path);%0A%0A
|
8e816c1693e3a05a24a9b624fbae2740d0b28179 | fix logged-in check | my-unhosted-website/www/unhosted/unhosted.js | my-unhosted-website/www/unhosted/unhosted.js | // app state shared with login.html:
// =================================
// localStorage::"unhosted".userAddress
// localStorage::"unhosted".davAuth
// localStorage::"unhosted".cryptoPwd
// localStorage::"unhosted".davBaseUrl
/////////
// DAV //
/////////
var DAV = function() {
var dav = {}
keyToUrl = function(key, wallet) {
var userAddressParts = wallet.userAddress.split("@");
var resource = document.domain;
var url = wallet.davBaseUrl
+"webdav/"+userAddressParts[1]
+"/"+userAddressParts[0]
+"/"+resource
+"/"+key;
return url;
}
dav.get = function(key) {
var wallet = getWallet();
var xhr = new XMLHttpRequest();
xhr.open("GET", keyToUrl(key, wallet), false);
xhr.send();
if(xhr.status == 200) {
return xhr.responseText;
} if(xhr.status == 404) {
return null;
} else {
alert("error: got status "+xhr.status+" when doing basic auth GET on url "+keyToUrl(key));
}
}
dav.put = function(key, text) {
var wallet = getWallet();
var xhr = new XMLHttpRequest();
//xhr.open("PUT", keyToUrl(key, wallet), false, wallet.userAddress, wallet.davToken);
//HACK:
xhr.open("PUT", keyToUrl(key, wallet), false);
xhr.setRequestHeader("Authorization", "Basic "+Base64.encode(wallet.userAddress +':'+ wallet.davToken));
//END HACK.
xhr.withCredentials = "true";
xhr.send(text);
if(xhr.status != 200 && xhr.status != 201 && xhr.status != 204) {
alert("error: got status "+xhr.status+" when doing basic auth PUT on url "+keyToUrl(key));
}
}
return dav;
}
//////////////
// Unhosted //
//////////////
var Unhosted = function() {
var unhosted = {};
var dav = DAV();
unhosted.connect = function() {
if(!getWallet().davAuth) {
window.location = config.loginUrl;
}
}
unhosted.getUserName = function() {
return getWallet().userAddress;
}
unhosted.get = function(key) {
var wallet = getWallet();
if(wallet.cryptoPwd == null) {
return JSON.parse(dav.get(key));
} else {
return JSON.parse(sjcl.decrypt(wallet.cryptoPwd, dav.get(key)));
}
}
unhosted.set = function(key, value) {
var wallet = getWallet();
if(wallet.cryptoPwd == null) {
dav.put(key, JSON.stringify(value));
} else {
dav.put(key, sjcl.encrypt(wallet.cryptoPwd, JSON.stringify(value)));
}
}
unhosted.close = function() {
setWallet({});
window.location = config.loginUrl;
}
return unhosted;
}
| JavaScript | 0.000001 | @@ -1,233 +1,4 @@
-// app state shared with login.html:%0A// =================================%0A// localStorage::%22unhosted%22.userAddress%0A// localStorage::%22unhosted%22.davAuth%0A// localStorage::%22unhosted%22.cryptoPwd%0A// localStorage::%22unhosted%22.davBaseUrl%0A%0A%0A
//
@@ -1465,20 +1465,21 @@
et().dav
-Auth
+Token
) %7B%0A%09%09%09w
|
b82816c774ebdff076375fb5705b9f720ac9de67 | reformat session configuration in preparation for the next commit | src/node/hooks/express/webaccess.js | src/node/hooks/express/webaccess.js | var express = require('express');
var log4js = require('log4js');
var httpLogger = log4js.getLogger("http");
var settings = require('../../utils/Settings');
var hooks = require('ep_etherpad-lite/static/js/pluginfw/hooks');
var ueberStore = require('../../db/SessionStore');
var stats = require('ep_etherpad-lite/node/stats');
var sessionModule = require('express-session');
var cookieParser = require('cookie-parser');
//checks for basic http auth
exports.basicAuth = function (req, res, next) {
var hookResultMangle = function (cb) {
return function (err, data) {
return cb(!err && data.length && data[0]);
}
}
var authorize = function (cb) {
// Do not require auth for static paths and the API...this could be a bit brittle
if (req.path.match(/^\/(static|javascripts|pluginfw|api)/)) return cb(true);
if (req.path.toLowerCase().indexOf('/admin') != 0) {
if (!settings.requireAuthentication) return cb(true);
if (!settings.requireAuthorization && req.session && req.session.user) return cb(true);
}
if (req.session && req.session.user && req.session.user.is_admin) return cb(true);
hooks.aCallFirst("authorize", {req: req, res:res, next:next, resource: req.path}, hookResultMangle(cb));
}
var authenticate = function (cb) {
// If auth headers are present use them to authenticate...
if (req.headers.authorization && req.headers.authorization.search('Basic ') === 0) {
var userpass = Buffer.from(req.headers.authorization.split(' ')[1], 'base64').toString().split(":")
var username = userpass.shift();
var password = userpass.join(':');
var fallback = function(success) {
if (success) return cb(true);
if (settings.users[username] != undefined && settings.users[username].password === password) {
settings.users[username].username = username;
req.session.user = settings.users[username];
return cb(true);
}
return cb(false);
};
return hooks.aCallFirst("authenticate", {req: req, res:res, next:next, username: username, password: password}, hookResultMangle(fallback));
}
hooks.aCallFirst("authenticate", {req: req, res:res, next:next}, hookResultMangle(cb));
}
/* Authentication OR authorization failed. */
var failure = function () {
return hooks.aCallFirst("authFailure", {req: req, res:res, next:next}, hookResultMangle(function (ok) {
if (ok) return;
/* No plugin handler for invalid auth. Return Auth required
* Headers, delayed for 1 second, if authentication failed
* before. */
res.header('WWW-Authenticate', 'Basic realm="Protected Area"');
if (req.headers.authorization) {
setTimeout(function () {
res.status(401).send('Authentication required');
}, 1000);
} else {
res.status(401).send('Authentication required');
}
}));
}
/* This is the actual authentication/authorization hoop. It is done in four steps:
1) Try to just access the thing
2) If not allowed using whatever creds are in the current session already, try to authenticate
3) If authentication using already supplied credentials succeeds, try to access the thing again
4) If all els fails, give the user a 401 to request new credentials
Note that the process could stop already in step 3 with a redirect to login page.
*/
authorize(function (ok) {
if (ok) return next();
authenticate(function (ok) {
if (!ok) return failure();
authorize(function (ok) {
if (ok) return next();
failure();
});
});
});
}
exports.secret = null;
exports.expressConfigure = function (hook_name, args, cb) {
// Measure response time
args.app.use(function(req, res, next) {
var stopWatch = stats.timer('httpRequests').start();
var sendFn = res.send
res.send = function() {
stopWatch.end()
sendFn.apply(res, arguments)
}
next()
})
// If the log level specified in the config file is WARN or ERROR the application server never starts listening to requests as reported in issue #158.
// Not installing the log4js connect logger when the log level has a higher severity than INFO since it would not log at that level anyway.
if (!(settings.loglevel === "WARN" || settings.loglevel == "ERROR"))
args.app.use(log4js.connectLogger(httpLogger, { level: log4js.levels.DEBUG, format: ':status, :method :url'}));
/* Do not let express create the session, so that we can retain a
* reference to it for socket.io to use. Also, set the key (cookie
* name) to a javascript identifier compatible string. Makes code
* handling it cleaner :) */
if (!exports.sessionStore) {
exports.sessionStore = new ueberStore();
exports.secret = settings.sessionKey;
}
args.app.sessionStore = exports.sessionStore;
args.app.use(sessionModule({secret: exports.secret, store: args.app.sessionStore, resave: true, saveUninitialized: true, name: 'express_sid', proxy: true, cookie: { secure: !!settings.ssl }}));
args.app.use(cookieParser(settings.sessionKey, {}));
args.app.use(exports.basicAuth);
}
| JavaScript | 0 | @@ -4896,16 +4896,21 @@
Module(%7B
+%0A
secret:
@@ -4924,16 +4924,20 @@
.secret,
+%0A
store:
@@ -4958,16 +4958,20 @@
onStore,
+%0A
resave:
@@ -4976,16 +4976,20 @@
e: true,
+%0A
saveUni
@@ -5005,16 +5005,20 @@
d: true,
+%0A
name: '
@@ -5030,16 +5030,20 @@
ss_sid',
+%0A
proxy:
@@ -5047,16 +5047,20 @@
y: true,
+%0A
cookie:
@@ -5061,16 +5061,22 @@
ookie: %7B
+%0A
secure:
@@ -5090,18 +5090,26 @@
ings.ssl
+,%0A %7D%0A
-%7D
%7D));%0A%0A
|
3f7936bd0100a6324bd12b97e6a17b7843666fa3 | fix transaction#get | src/node_modules/lib/transaction.js | src/node_modules/lib/transaction.js | const NotEnoughDataError = require('lib/not-enough-data-error')
const temporary = Buffer.alloc(8)
// Called in object stream.
class Transaction {
constructor(stream) {
this.stream = stream
this.index = 0
}
commit() {
this.stream.consume(this.index)
}
get(i) {
return this.stream.get(i)
}
get length() {
return this.stream.length
}
readBuffer(size) {
assertSize(this.index + size, this.length)
const buf = this.stream.slice(this.index, this.index + size)
this.index += size
return buf
}
}
const methods = {
readDoubleBE: 8,
readDoubleLE: 8,
readFloatBE: 4,
readFloatLE: 4,
readInt32BE: 4,
readInt32LE: 4,
readUInt32BE: 4,
readUInt32LE: 4,
readInt16BE: 2,
readInt16LE: 2,
readUInt16BE: 2,
readUInt16LE: 2,
readInt8: 1,
readUInt8: 1,
}
Object.keys(methods).forEach(method => {
const bytes = methods[method]
Transaction.prototype[method] = function() {
fastread(this.stream, bytes, this.index)
this.index += bytes
return temporary[method](0)
}
})
;['readIntBE', 'readIntLE', 'readUIntBE', 'readUIntLE'].forEach(method => {
Transaction.prototype[method] = function(bytes) {
fastread(this.stream, bytes, this.index)
this.index += bytes
return temporary[method](0, bytes)
}
})
module.exports = Transaction
function assertSize(size, length) {
if (size > length) {
throw new NotEnoughDataError(size, length)
}
}
function fastread(stream, size, i) {
assertSize(size + i, stream.length)
stream.copy(temporary, 0, i, i + size)
}
| JavaScript | 0.000007 | @@ -275,16 +275,20 @@
%0A get(i
+ = 0
) %7B%0A
@@ -310,16 +310,29 @@
eam.get(
+this.index +
i)%0A %7D%0A%0A
|
f2c3825d86234dd31c1bdcb013088d79a92b1932 | add an data attribute id to the debug window | build/js/jquery.debug-window.js | build/js/jquery.debug-window.js | /*global jQuery*/
/*jslint nomen: true, plusplus: true, browser: true, devel: true */
"use strict";
var _console = console;
var i;
var console = {
log: function() {
var args = Array.prototype.slice.call(arguments);
for (i = 0; i < args.length; i += 1) {
messageConsole(args[i], 'log');
_console.log(args[i]);
}
},
warn: function() {
var args = Array.prototype.slice.call(arguments);
for (i = 0; i < args.length; i += 1) {
messageConsole(args[i], 'warn');
_console.warn(args[i]);
}
},
error: function() {
var args = Array.prototype.slice.call(arguments);
for (i = 0; i < args.length; i += 1) {
messageConsole(args[i], 'error');
_console.error(args[i]);
}
}
}
function messageConsole(message, type) {
var ev;
var msg = stringifyLog(message);
if(!type) type = 'log';
ev = new CustomEvent('console:' + type, { 'detail': msg });
window.dispatchEvent(ev);
}
function stringifyLog(message) {
var stringMessage = '';
if (message === null) {
stringMessage = 'null';
} else if (typeof message === 'string') {
stringMessage = message;
} else if (typeof message === 'object') {
stringMessage = simpleObjectStringify(message);
}
return stringMessage;
}
function simpleObjectStringify (object){
var simpleObject = {};
for (var prop in object ){
if (!object.hasOwnProperty(prop)){
continue;
}
if (typeof(object[prop]) == 'object'){
continue;
}
if (typeof(object[prop]) == 'function'){
continue;
}
simpleObject[prop] = object[prop];
}
return JSON.stringify(simpleObject); // returns cleaned up JSON
};
function DebugObject(element, options) {
var self = $(element);
var settings = $.extend({
showMousePosition: false,
showWindowDimensions: false,
debugHtml: {
mousePositionHtml:
'<div class="mouse-position">' +
'<strong>Mouse: </strong>' +
'x<span class="x">' + mouseX + '</span>, ' +
'y<span class="y">' + mouseY + '</span>' +
'</div>',
windowDimHtml:
'<div class="window-dim">' +
'<strong>Window </strong>' +
'<ul>' +
'<li class="window-width">' +
'<strong>Width: </strong>' +
'<span class="width">' + windowWidth + '</span>px' +
'</li>' +
'<li class="window-height">' +
'<strong>Height: </strong>' +
'<span class="height">' + windowHeight + '</span>px' +
'</li>' +
'</ul>' +
'</div>',
consoleHtml:
'<div class="console"></div>'
}
}, options);
var mouseX = 0;
var mouseY = 0;
var windowWidth = $(window).width();
var windowHeight = $(window).height();
var debugWindow;
function init() {
_setStage(function () {
_setEvents();
updateDebugView();
window.setInterval(updateDebugView, 30);
});
}
function _setStage(cb) {
var windowHtml = "";
if (settings.showMousePosition) {
windowHtml += settings.debugHtml.mousePositionHtml;
windowHtml += '<hr>';
}
if (settings.showWindowDimensions) {
windowHtml += settings.debugHtml.windowDimHtml;
windowHtml += '<hr>';
}
windowHtml += settings.debugHtml.consoleHtml;
debugWindow = $('<div/>')
.attr('id', 'debug-window')
.html('Loading debug...');
self.prepend(debugWindow);
debugWindow.html(windowHtml);
cb();
};
function _setEvents() {
$(window)
.on('mousemove', function(e){
mouseX = e.pageX
mouseY = e.pageY
})
.on('resize', function(e){
windowWidth = $(window).width();
windowHeight = $(window).height();
})
.on('console:log', function(e){
debugWindow.find('.console').append($('<div/>').addClass('log line').html(e.detail));
})
.on('console:warn', function(e){
debugWindow.find('.console').append($('<div/>').addClass('warn line').html(e.detail));
})
.on('console:error', function(e){
debugWindow.find('.console').append($('<div/>').addClass('error line').html(e.detail));
})
};
function updateDebugView() {
debugWindow.find('.mouse-position .x').html(mouseX);
debugWindow.find('.mouse-position .y').html(mouseY);
debugWindow.find('.window-width .width').html(windowWidth);
debugWindow.find('.window-height .height').html(windowHeight);
debugWindow.find('.console').css('height', (windowHeight / 3) * 2 + 'px');
}
init();
}
(function ($) {
$.fn.debugWindow = function (options) {
this.each(function () {
new DebugObject(this, options);
});
return this;
};
}(jQuery));
| JavaScript | 0 | @@ -1404,17 +1404,16 @@
tringify
-
(object)
@@ -5296,25 +5296,47 @@
(options) %7B%0A
+ var index = 0;
%0A
-
this
@@ -5347,32 +5347,78 @@
h(function () %7B%0A
+ $(this).attr('data-debug-1', '');%0A
new
@@ -5453,25 +5453,24 @@
%7D);%0A
-%0A
retu
@@ -5478,17 +5478,16 @@
n this;%0A
-%0A
%7D;%0A%0A
|
3d4db5a49bf4478f4f8ec185f3b360adf7327fbe | Replace `Number.isNaN` call with `isNaN` call. | source/Grid/utils/CellSizeAndPositionManager.js | source/Grid/utils/CellSizeAndPositionManager.js | /** @flow */
/**
* Just-in-time calculates and caches size and position information for a collection of cells.
*/
export default class CellSizeAndPositionManager {
constructor ({
cellCount,
cellSizeGetter,
estimatedCellSize
}: CellSizeAndPositionManagerConstructorParams) {
this._cellSizeGetter = cellSizeGetter
this._cellCount = cellCount
this._estimatedCellSize = estimatedCellSize
// Cache of size and position data for cells, mapped by cell index.
// Note that invalid values may exist in this map so only rely on cells up to this._lastMeasuredIndex
this._cellSizeAndPositionData = {}
// Measurements for cells up to this index can be trusted; cells afterward should be estimated.
this._lastMeasuredIndex = -1
}
configure ({
cellCount,
estimatedCellSize
}: ConfigureParams): void {
this._cellCount = cellCount
this._estimatedCellSize = estimatedCellSize
}
/**
* Searches for the cell (index) nearest the specified offset.
*
* If no exact match is found the next lowest cell index will be returned.
* This allows partially visible cells (with offsets just before/above the fold) to be visible.
*/
findNearestCell (offset: number): number {
if (Number.isNaN(offset)) {
throw Error(`Invalid offset ${offset} specified`)
}
// Our search algorithms find the nearest match at or below the specified offset.
// So make sure the offset is at least 0 or no match will be found.
offset = Math.max(0, offset)
const lastMeasuredCellSizeAndPosition = this.getSizeAndPositionOfLastMeasuredCell()
const lastMeasuredIndex = Math.max(0, this._lastMeasuredIndex)
if (lastMeasuredCellSizeAndPosition.offset >= offset) {
// If we've already measured cells within this range just use a binary search as it's faster.
return this._binarySearch({
high: lastMeasuredIndex,
low: 0,
offset
})
} else {
// If we haven't yet measured this high, fallback to an exponential search with an inner binary search.
// The exponential search avoids pre-computing sizes for the full set of cells as a binary search would.
// The overall complexity for this approach is O(log n).
return this._exponentialSearch({
index: lastMeasuredIndex,
offset
})
}
}
getCellCount (): number {
return this._cellCount
}
getEstimatedCellSize (): number {
return this._estimatedCellSize
}
getLastMeasuredIndex (): number {
return this._lastMeasuredIndex
}
/**
* This method returns the size and position for the cell at the specified index.
* It just-in-time calculates (or used cached values) for cells leading up to the index.
*/
getSizeAndPositionOfCell (index: number): SizeAndPositionData {
if (index < 0 || index >= this._cellCount) {
throw Error(`Requested index ${index} is outside of range 0..${this._cellCount}`)
}
if (index > this._lastMeasuredIndex) {
let lastMeasuredCellSizeAndPosition = this.getSizeAndPositionOfLastMeasuredCell()
let offset = lastMeasuredCellSizeAndPosition.offset + lastMeasuredCellSizeAndPosition.size
for (var i = this._lastMeasuredIndex + 1; i <= index; i++) {
let size = this._cellSizeGetter({ index: i })
if (size == null || isNaN(size)) {
throw Error(`Invalid size returned for cell ${i} of value ${size}`)
}
this._cellSizeAndPositionData[i] = {
offset,
size
}
offset += size
}
this._lastMeasuredIndex = index
}
return this._cellSizeAndPositionData[index]
}
getSizeAndPositionOfLastMeasuredCell (): SizeAndPositionData {
return this._lastMeasuredIndex >= 0
? this._cellSizeAndPositionData[this._lastMeasuredIndex]
: {
offset: 0,
size: 0
}
}
/**
* Total size of all cells being measured.
* This value will be completedly estimated initially.
* As cells as measured the estimate will be updated.
*/
getTotalSize (): number {
const lastMeasuredCellSizeAndPosition = this.getSizeAndPositionOfLastMeasuredCell()
return lastMeasuredCellSizeAndPosition.offset + lastMeasuredCellSizeAndPosition.size + (this._cellCount - this._lastMeasuredIndex - 1) * this._estimatedCellSize
}
getVisibleCellRange ({
containerSize,
offset
}: GetVisibleCellRangeParams): VisibleCellRange {
const totalSize = this.getTotalSize()
if (totalSize === 0) {
return {}
}
const maxOffset = offset + containerSize
const start = this.findNearestCell(offset)
const datum = this.getSizeAndPositionOfCell(start)
offset = datum.offset + datum.size
let stop = start
while (offset < maxOffset && stop < this._cellCount - 1) {
stop++
offset += this.getSizeAndPositionOfCell(stop).size
}
return {
start,
stop
}
}
/**
* Clear all cached values for cells after the specified index.
* This method should be called for any cell that has changed its size.
* It will not immediately perform any calculations; they'll be performed the next time getSizeAndPositionOfCell() is called.
*/
resetCell (index: number): void {
this._lastMeasuredIndex = index - 1
}
_binarySearch ({
high,
low,
offset
}): number {
let middle
let currentOffset
while (low <= high) {
middle = low + Math.floor((high - low) / 2)
currentOffset = this.getSizeAndPositionOfCell(middle).offset
if (currentOffset === offset) {
return middle
} else if (currentOffset < offset) {
low = middle + 1
} else if (currentOffset > offset) {
high = middle - 1
}
}
if (low > 0) {
return low - 1
}
}
_exponentialSearch ({
index,
offset
}): number {
let interval = 1
while (
index < this._cellCount &&
this.getSizeAndPositionOfCell(index).offset < offset
) {
index += interval
interval *= 2
}
return this._binarySearch({
high: Math.min(index, this._cellCount - 1),
low: Math.floor(index / 2),
offset
})
}
}
type CellSizeAndPositionManagerConstructorParams = {
cellCount: number,
cellSizeGetter: Function,
estimatedCellSize: number
};
type ConfigureParams = {
cellCount: number,
estimatedCellSize: number
};
type GetVisibleCellRangeParams = {
containerSize: number,
offset: number
};
type SizeAndPositionData = {
offset: number,
size: number
};
type VisibleCellRange = {
start: ?number,
stop: ?number
};
| JavaScript | 0.000225 | @@ -1246,15 +1246,8 @@
if (
-Number.
isNa
|
e78a04dc0d215072a6456f85d4d41de73b978a59 | rename table cell component | new-lamassu-admin/src/pages/Assets/Assets.js | new-lamassu-admin/src/pages/Assets/Assets.js | import Grid from '@material-ui/core/Grid'
import Table from '@material-ui/core/Table'
import TableBody from '@material-ui/core/TableBody'
import TableCell from '@material-ui/core/TableCell'
import TableContainer from '@material-ui/core/TableContainer'
import TableHead from '@material-ui/core/TableHead'
import TableRow from '@material-ui/core/TableRow'
import { makeStyles, withStyles } from '@material-ui/core/styles'
import * as R from 'ramda'
import React from 'react'
import TitleSection from 'src/components/layout/TitleSection'
import { H4, Label2, P, Info2 } from 'src/components/typography'
import styles from './Assets.styles'
const useStyles = makeStyles(styles)
const StyledCell = withStyles({
root: {
borderBottom: '4px solid white',
padding: 0,
paddingLeft: 20,
paddingRight: 20
}
})(TableCell)
const HeaderCell = withStyles({
root: {
borderBottom: '4px solid white',
padding: 0,
paddingLeft: 20,
paddingRight: 20,
backgroundColor: 'white'
}
})(TableCell)
const AssetsAmountTable = ({ title, data = [], numToRender }) => {
const classes = useStyles()
const totalAmount = R.compose(R.sum, R.map(R.path(['amount'])))(data) ?? 0
const currency = data[0]?.currency ?? ''
const selectAmountPrefix = it =>
it.direction === 'in' ? '+' : R.isNil(it.direction) ? '' : '-'
return (
<>
<Grid item className={classes.card} xs={12}>
<H4 className={classes.h4}>{title}</H4>
<TableContainer>
<Table>
<TableHead>
<TableRow>
<HeaderCell>
<div className={classes.asset}>
<Label2 className={classes.label}>Asset</Label2>
</div>
</HeaderCell>
<HeaderCell>
<div className={classes.amount}>
<Label2 className={classes.label}>Amount</Label2>
</div>
</HeaderCell>
</TableRow>
</TableHead>
<TableBody>
{data?.map((asset, idx) => {
if (idx < numToRender) {
return (
<TableRow className={classes.row} key={idx}>
<StyledCell align="left">
<P>{asset.display}</P>
</StyledCell>
<StyledCell align="right">
<P>{`${selectAmountPrefix(asset)}
${formatCurrency(Math.abs(asset.amount))} ${
asset.currency
}`}</P>
</StyledCell>
</TableRow>
)
}
return null
})}
<TableRow className={classes.totalRow} key={data?.length + 1}>
<StyledCell align="left">
<Info2>{`Total ${R.toLower(title)}`}</Info2>
</StyledCell>
<StyledCell align="right">
<Info2>{`${formatCurrency(totalAmount)} ${currency}`}</Info2>
</StyledCell>
</TableRow>
</TableBody>
</Table>
</TableContainer>
</Grid>
</>
)
}
const formatCurrency = amount =>
amount.toLocaleString('en-US', { maximumFractionDigits: 2 })
const Assets = () => {
const classes = useStyles()
const mockData = [
{
id: 'fiatBalance',
display: 'Fiat balance',
amount: 10438,
currency: 'USD',
class: 'Available balance'
},
{
id: 'hedgingReserve',
display: 'Hedging reserve',
amount: -1486,
currency: 'USD',
class: 'Available balance',
direction: 'out'
},
{
id: 'hedgedWalletAssets',
display: 'Hedged wallet assets',
amount: 96446,
currency: 'USD',
class: 'Wallet assets',
direction: 'in'
},
{
id: 'unhedgedWalletAssets',
display: 'Unhedged wallet assets',
amount: 3978,
currency: 'USD',
class: 'Wallet assets',
direction: 'in'
}
]
const mockDataTotal = [
{
id: 'fiatBalance',
display: 'Fiat balance',
amount: 10438,
currency: 'USD'
},
{
id: 'hedgingReserve',
display: 'Hedging reserve',
amount: -1486,
currency: 'USD',
direction: 'out'
},
{
id: 'hedgedWalletAssets',
display: 'Market value of hedged wallet assets',
amount: 94980,
currency: 'USD',
direction: 'in'
},
{
id: 'unhedgedWalletAssets',
display: 'Unhedged wallet assets',
amount: 3978,
currency: 'USD',
direction: 'in'
}
]
const filterByClass = x =>
R.filter(it => R.path(['class'])(it) === x)(mockData)
return (
<>
<TitleSection title="Balance sheet" />
<div className={classes.root}>
<Grid container>
<Grid container direction="column" item xs={5}>
<Grid item xs={12}>
<div className={classes.leftSide}>
<AssetsAmountTable
title="Available balance"
data={filterByClass('Available balance')}
numToRender={mockData.length}
/>
</div>
<div className={classes.leftSide}>
<AssetsAmountTable
title="Wallet assets"
data={filterByClass('Wallet assets')}
numToRender={mockData.length}
/>
</div>
</Grid>
</Grid>
<Grid container direction="column" item xs={7}>
<Grid item xs={12}>
<div className={classes.rightSide}>
<AssetsAmountTable
title="Total assets"
data={mockDataTotal}
numToRender={mockDataTotal.length}
/>
</div>
</Grid>
</Grid>
</Grid>
</div>
</>
)
}
export default Assets
| JavaScript | 0.000882 | @@ -676,22 +676,16 @@
%0A%0Aconst
-Styled
Cell = w
@@ -2210,38 +2210,32 @@
%3C
-Styled
Cell align=%22left
@@ -2229,32 +2229,32 @@
l align=%22left%22%3E%0A
+
@@ -2300,38 +2300,32 @@
%3C/
-Styled
Cell%3E%0A
@@ -2329,38 +2329,32 @@
%3C
-Styled
Cell align=%22righ
@@ -2574,38 +2574,32 @@
%3C/
-Styled
Cell%3E%0A
@@ -2790,38 +2790,32 @@
%3C
-Styled
Cell align=%22left
@@ -2890,38 +2890,32 @@
%3C/
-Styled
Cell%3E%0A
@@ -2921,22 +2921,16 @@
%3C
-Styled
Cell ali
@@ -3013,32 +3013,32 @@
ency%7D%60%7D%3C/Info2%3E%0A
+
@@ -3043,14 +3043,8 @@
%3C/
-Styled
Cell
|
6af69da3fced4e8ac389c492338c6da8ad9968f2 | fix (test): fix mocks for modules and commonJS build test | __mocks__/react-easy-state.js | __mocks__/react-easy-state.js | // use this to test the raw src folder
export * from '../src'
// use this to test the es6 modules build
// export * from '../dist/es6'
// use to test the commonJS build
// export * from '../dist/es5'
| JavaScript | 0.000001 | @@ -125,18 +125,31 @@
./dist/e
-s6
+asyState.module
'%0A%0A// us
@@ -208,8 +208,23 @@
st/e
-s5
+asyState.commonJS
'%0A
|
f8dfd046008ab298622cff2e5bda6306ebed84f0 | Add test for optional prefix | __tests__/applyAtRule.test.js | __tests__/applyAtRule.test.js | import postcss from 'postcss'
import plugin from '../src/lib/substituteClassApplyAtRules'
import generateUtilities from '../src/util/generateUtilities'
import defaultConfig from '../defaultConfig.stub.js'
const defaultUtilities = generateUtilities(defaultConfig, [])
function run(input, config = defaultConfig, utilities = defaultUtilities) {
return postcss([plugin(config, utilities)]).process(input, { from: undefined })
}
test("it copies a class's declarations into itself", () => {
const output = '.a { color: red; } .b { color: red; }'
return run('.a { color: red; } .b { @apply .a; }').then(result => {
expect(result.css).toEqual(output)
expect(result.warnings().length).toBe(0)
})
})
test('selectors with invalid characters do not need to be manually escaped', () => {
const input = `
.a\\:1\\/2 { color: red; }
.b { @apply .a:1/2; }
`
const expected = `
.a\\:1\\/2 { color: red; }
.b { color: red; }
`
return run(input).then(result => {
expect(result.css).toEqual(expected)
expect(result.warnings().length).toBe(0)
})
})
test('it removes important from applied classes by default', () => {
const input = `
.a { color: red !important; }
.b { @apply .a; }
`
const expected = `
.a { color: red !important; }
.b { color: red; }
`
return run(input).then(result => {
expect(result.css).toEqual(expected)
expect(result.warnings().length).toBe(0)
})
})
test('applied rules can be made !important', () => {
const input = `
.a { color: red; }
.b { @apply .a !important; }
`
const expected = `
.a { color: red; }
.b { color: red !important; }
`
return run(input).then(result => {
expect(result.css).toEqual(expected)
expect(result.warnings().length).toBe(0)
})
})
test('cssnext custom property sets are preserved', () => {
const input = `
.a {
color: red;
}
.b {
@apply .a --custom-property-set;
}
`
const expected = `
.a {
color: red;
}
.b {
color: red;
@apply --custom-property-set;
}
`
return run(input).then(result => {
expect(result.css).toEqual(expected)
expect(result.warnings().length).toBe(0)
})
})
test('it fails if the class does not exist', () => {
return run('.b { @apply .a; }').catch(e => {
expect(e).toMatchObject({ name: 'CssSyntaxError' })
})
})
test('applying classes that are defined in a media query is not supported', () => {
const input = `
@media (min-width: 300px) {
.a { color: blue; }
}
.b {
@apply .a;
}
`
expect.assertions(1)
return run(input).catch(e => {
expect(e).toMatchObject({ name: 'CssSyntaxError' })
})
})
test('applying classes that are ever used in a media query is not supported', () => {
const input = `
.a {
color: red;
}
@media (min-width: 300px) {
.a { color: blue; }
}
.b {
@apply .a;
}
`
expect.assertions(1)
return run(input).catch(e => {
expect(e).toMatchObject({ name: 'CssSyntaxError' })
})
})
test('it does not match classes that include pseudo-selectors', () => {
const input = `
.a:hover {
color: red;
}
.b {
@apply .a;
}
`
expect.assertions(1)
return run(input).catch(e => {
expect(e).toMatchObject({ name: 'CssSyntaxError' })
})
})
test('it does not match classes that have multiple rules', () => {
const input = `
.a {
color: red;
}
.b {
@apply .a;
}
.a {
color: blue;
}
`
expect.assertions(1)
return run(input).catch(e => {
expect(e).toMatchObject({ name: 'CssSyntaxError' })
})
})
test('you can apply utility classes that do not actually exist as long as they would exist if utilities were being generated', () => {
const input = `
.foo { @apply .mt-4; }
`
const expected = `
.foo { margin-top: 1rem; }
`
const config = {
...defaultConfig,
experiments: { shadowLookup: true },
}
return run(input, config).then(result => {
expect(result.css).toEqual(expected)
expect(result.warnings().length).toBe(0)
})
})
| JavaScript | 0.000001 | @@ -4116,28 +4116,483 @@
s().length).toBe(0)%0A %7D)%0A%7D)%0A
+%0Atest('you can apply utility classes without using the given prefix', () =%3E %7B%0A const input = %60%0A .foo %7B @apply .mt-4; %7D%0A %60%0A%0A const expected = %60%0A .prefix-foo %7B margin-top: 1rem; %7D%0A %60%0A%0A const config = %7B%0A ...defaultConfig,%0A options: %7B%0A ...defaultConfig.options,%0A prefix: 'prefix',%0A %7D,%0A %7D%0A%0A return run(input, config).then(result =%3E %7B%0A expect(result.css).toEqual(expected)%0A expect(result.warnings().length).toBe(0)%0A %7D)%0A%7D)%0A
|
9b7ff2f357b7d7a3da2099a7ea3028d62c8c9fde | remove the duplicated 'it' word in the tests. | __tests__/conversions.test.js | __tests__/conversions.test.js | import { toSeatData } from '../src/conversions';
describe('when using toSeatData conversion function', () => {
let seatState, converted;
beforeEach(() => {
seatState = { x: 10, y: 40, id: 1, label: 'G-13' };
converted = toSeatData(seatState);
});
it('it removes the position of the seat in the output', () => {
expect(converted.x).toBeUndefined();
expect(converted.y).toBeUndefined();
});
it('it removes the id of the seat in the output', () => {
expect(converted.id).toBeUndefined();
});
it('it keeps the label of the seat in the output', () => {
expect(converted.label).toEqual('G-13');
});
it('it keeps the data object in the output', () => {
const data = { username: 'timinou', type: 'VIP' };
seatState['data'] = data;
converted = toSeatData(seatState);
expect(converted.data).toEqual(data);
});
it('it returns an empty dict in the data field if no data is associated with the seat', () => {
expect(converted.data).toEqual({});
});
});
| JavaScript | 0.000742 | @@ -255,35 +255,32 @@
);%0A %7D);%0A%0A it('
-it
removes the posi
@@ -415,19 +415,16 @@
%0A%0A it('
-it
removes
@@ -513,35 +513,32 @@
);%0A %7D);%0A%0A it('
-it
keeps the label
@@ -631,19 +631,16 @@
%0A%0A it('
-it
keeps th
@@ -861,11 +861,8 @@
it('
-it
retu
|
c26e1f873ed238e1bdaf99902af0ec27859d58b1 | add check dns action to community module | client/community/action-creators/dns-control/async-check-hosted-zone.js | client/community/action-creators/dns-control/async-check-hosted-zone.js | import * as t from '../../action-types'
import { createAction } from '../create-action'
/*CHECK_DNS_HOSTED_ZONE_FAILURE*/
// TODO: Call API method
export default dnsHostedZone => (dispatch, getState, { api }) => {
dispatch(createAction(t.CHECK_DNS_HOSTED_ZONE_REQUEST))
return new Promise((resolve, reject) => {
setTimeout(() => {
const updated = { ...dnsHostedZone, ns_ok: true }
dispatch(createAction(t.CHECK_DNS_HOSTED_ZONE_SUCCESS, updated))
return resolve(updated)
}, 500)
})
}
| JavaScript | 0 | @@ -85,317 +85,517 @@
on'%0A
-%0A/*CHECK_DNS_HOSTED_ZONE_FAILURE*/%0A%0A// TODO: Call API method%0Aexport default dnsHostedZone =%3E (dispatch, getState, %7B api %7D) =%3E %7B%0A%0A dispatch(createAction(t.CHECK_DNS_HOSTED_ZONE_REQUEST))%0A return new Promise((resolve, reject) =%3E %7B%0A setTimeout(() =%3E %7B%0A const updated = %7B ...dnsHostedZone, ns_ok: true %7D
+import AuthSelectors from '~client/account/redux/selectors'%0Aimport * as CommunitySelectors from '../../selectors'%0A%0Aexport default dnsHostedZone =%3E (dispatch, getState, %7B api %7D) =%3E %7B%0A const credentials = AuthSelectors(getState()).getCredentials()%0A const community = CommunitySelectors.getCurrent(getState())%0A dispatch(createAction(t.CHECK_DNS_HOSTED_ZONE_REQUEST))%0A return api%0A .get(%60/communities/$%7Bcommunity.id%7D/dns_hosted_zones/$%7BdnsHostedZone.id%7D/check%60, %7B headers: credentials %7D)%0A .then(resp =%3E %7B
%0A
@@ -652,23 +652,25 @@
UCCESS,
-updated
+resp.data
))%0A
@@ -681,16 +681,24 @@
urn
+Promise.
resolve(
upda
@@ -697,29 +697,145 @@
lve(
-updated
+resp.data
)%0A %7D
-, 500)%0A
+)%0A .catch(ex =%3E %7B%0A dispatch(createAction(t.CHECK_DNS_HOSTED_ZONE_FAILURE, ex))%0A return Promise.reject(ex)%0A
%7D)
|
8a9ed76e7cbc3b913c237bf0d98329808b59219a | Add russian translation for 'unshare' | src/translations/ru.js | src/translations/ru.js | module.exports = {
emptyDoc: 'Пишите …',
search: 'Искать …',
footer: 'Пишите с легкостью! Исходный код открыт.',
share: 'Поделиться',
unshare: 'unshare',
open: 'открыть',
modified: 'изменён',
welcome: require('./welcome-ru.txt'),
secondsAgo: function (x) {
if (x === 1) return 'a second ago'
return timeAgoWithPlural('секунду_секунды_секунд', x)
},
minutesAgo: function (x) {
return timeAgoWithPlural('минуту_минуты_минут', x)
},
hoursAgo: function (x) {
return timeAgoWithPlural('час_часа_часов', x)
},
daysAgo: function (x) {
return timeAgoWithPlural('день_дня_дней', x)
},
weeksAgo: function (x) {
return timeAgoWithPlural('неделю_недели_недель', x)
},
monthsAgo: function (x) {
return timeAgoWithPlural('месяц_месяца_месяцев', x)
},
yearsAgo: function (x) {
return timeAgoWithPlural('год_года_лет', x)
}
}
function timeAgoWithPlural (word, number) {
var num = number > 1 ? (number + ' ') : ''
return num + plural(word, +number) + ' назад'
}
function plural (word, num) {
var forms = word.split('_')
return num % 10 === 1 && num % 100 !== 11 ? forms[0] : (num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) ? forms[1] : forms[2])
}
| JavaScript | 0.000192 | @@ -51,14 +51,13 @@
h: '
-%D0%98%D1%81%D0%BA%D0%B0%D1%82%D1%8C
+%D0%9D%D0%B0%D0%B9%D1%82%D0%B8
%E2%80%A6',
@@ -125,18 +125,20 @@
e: '
-%D0%9F%D0%BE%D0%B4%D0%B5%D0%BB%D0%B8%D1%82%D1%8C%D1%81%D1%8F
+%D0%BE%D0%BF%D1%83%D0%B1%D0%BB%D0%B8%D0%BA%D0%BE%D0%B2%D0%B0%D1%82%D1%8C
',%0A
@@ -148,23 +148,35 @@
share: '
-unshare
+%D0%BE%D1%82%D0%BC%D0%B5%D0%BD%D0%B8%D1%82%D1%8C %D0%BF%D1%83%D0%B1%D0%BB%D0%B8%D0%BA%D0%B0%D1%86%D0%B8%D1%8E
',%0A ope
@@ -252,16 +252,16 @@
.txt'),%0A
+
second
@@ -285,47 +285,8 @@
) %7B%0A
- if (x === 1) return 'a second ago'%0A
|
e0c3027c8e2ce3ef7bcea190c8379050f353b984 | Clean up repeating UI bindings | src/types/repeating.js | src/types/repeating.js | "use strict";
var m = require("mithril"),
assign = require("lodash.assign"),
times = require("lodash.times"),
config = require("../config"),
hide = require("./lib/hide"),
children = require("./children"),
css = require("./repeating.css"),
icons = config.icons;
function child(ctrl, options, data, idx) {
return m("div", { class : css[idx === 0 ? "first" : "child"] },
m("div", { class : css.meta },
m("p", { class : css.counter }, idx + 1),
m("button", {
class : css.remove,
onclick : ctrl.remove.bind(ctrl, options, data, idx)
},
m("svg", { class : css.icon },
m("use", { href : icons + "#remove" })
)
)
),
m.component(children, assign({}, options, {
fields : options.field.children,
class : css.fields,
data : data,
path : options.path.concat(idx)
}))
);
}
module.exports = {
controller : function(options) {
var ctrl = this;
ctrl.children = (options.data && options.data.length) || 1;
ctrl.add = function(opts) {
ctrl.children += 1;
// Ensure that we have data placeholders for all the possible entries
times(ctrl.children, function(idx) {
if(opts.data && opts.data[idx]) {
return;
}
// Need a key here so that firebase will save this object,
// otherwise future loads can have weird gaps
opts.update(opts.path.concat(idx), { __idx : idx });
});
};
ctrl.remove = function(opts, data, idx) {
if(Array.isArray(opts.data)) {
opts.data.splice(idx, 1);
ctrl.children = opts.data.length;
} else {
--ctrl.children;
}
opts.update(opts.path, opts.data);
};
},
view : function(ctrl, options) {
var field = options.field,
hidden = hide(options),
items;
if(hidden) {
return hidden;
}
if(options.data) {
items = options.data.map(child.bind(null, ctrl, options));
} else {
items = times(ctrl.children, child.bind(null, ctrl, options, false));
}
return m("div", { class : options.class + " " + css.container },
items,
m("button", {
class : css.add,
onclick : ctrl.add.bind(ctrl, options)
}, field.button || "Add")
);
}
};
| JavaScript | 0.000002 | @@ -625,27 +625,27 @@
remove.bind(
-ctr
+nul
l, options,
@@ -1247,20 +1247,68 @@
ion(opts
+, e
) %7B%0A
+ e.preventDefault();%0A %0A
@@ -1852,28 +1852,76 @@
s, data, idx
+, e
) %7B%0A
+ e.preventDefault();%0A %0A
@@ -2822,19 +2822,19 @@
dd.bind(
-ctr
+nul
l, optio
|
ce7b258132373d0628a8a94a790471b8b2922baf | Fix linting errors. | behaviors/autocomplete.js | behaviors/autocomplete.js | 'use strict';
var _ = require('lodash'),
dom = require('../services/dom'),
db = require('../services/db'),
lists = {};
/**
* Find the first child that is a text input.
* @param {object} el
* @returns {object|undefined}
*/
function findFirstTextInput(el) {
var inputs, l, i, type, textInput;
inputs = el.querySelectorAll('input');
for (i = 0, l = inputs.length; i < l; i++) {
type = inputs[i].getAttribute('type');
if (!type || type === 'text') {
textInput = inputs[i];
break;
}
}
return textInput;
}
/**
* Get the list values from the API and store in memory.
* @param {string} apiUrl The endpoint for the list, e.g. '/lists/authors'
* @returns {promise}
*/
function getListValues(apiUrl) {
if (lists[apiUrl]) {
return Promise.resolve(lists[apiUrl]);
} else {
return db.getComponentJSONFromReference(apiUrl);
}
}
/**
* Create a unique name for the list. Does not need to be too unique because specific to one form.
* @returns {string} Name to be used for the list
*/
function createListName() {
var somewhatUnique = '' + Math.floor(Math.random() * 100) + (new Date()).getTime();
return 'autocomplete-' + somewhatUnique;
}
module.exports = function (result, args) {
var api = args.api,
existingInput = findFirstTextInput(result.el),
listName = createListName(),
optionsParent;
// Requirements.
if (!api) {
console.warn('Autocomplete requires an API.');
return result;
}
if (!existingInput) {
console.warn('Autocomplete requires a text input.');
return result;
}
getListValues(api);
// Add elements.
var datalist = document.createElement('datalist');
var options = dom.create(`
<label>
<select>
<option value="">
</select>
</label>
`);
datalist.appendChild(options);
optionsParent = options.querySelector('select');
// Set attributes.
existingInput.setAttribute('list', listName);
datalist.id = listName;
// Listen.
existingInput.addEventListener('input', (function(optionsParent) {
return function(e) {
getListValues(api).then(function (results) {
var options = results.reduce(function (prev, curr) {
return prev + '<option>' + curr;
}, '<option value="">');
options = dom.create(`${ options }`);
dom.clearChildren(optionsParent);
optionsParent.appendChild(options);
existingInput.focus();
});
};
})(optionsParent));
// Add it back to the result element.
result.el.appendChild(datalist);
return result;
}; | JavaScript | 0.000003 | @@ -1,46 +1,7 @@
-'use strict';%0Avar _ = require('lodash'),%0A
+var
dom
@@ -217,26 +217,24 @@
Input(el) %7B%0A
-
%0A var input
@@ -301,18 +301,16 @@
nput');%0A
-
%0A for (
@@ -480,18 +480,16 @@
%7D%0A %7D%0A
-
%0A retur
@@ -1114,16 +1114,17 @@
Time();%0A
+%0A
return
@@ -1205,18 +1205,16 @@
args) %7B%0A
-
%0A var a
@@ -1278,17 +1278,16 @@
ult.el),
-
%0A lis
@@ -1329,20 +1329,45 @@
nsParent
+,%0A datalist,%0A options
;%0A
-
%0A // Re
@@ -1570,18 +1570,16 @@
lt;%0A %7D%0A
-
%0A getLi
@@ -1615,20 +1615,16 @@
ents.%0A
-var
datalist
@@ -1664,20 +1664,16 @@
st');%0A
-var
options
@@ -1859,18 +1859,16 @@
lect');%0A
-
%0A // Se
@@ -2011,25 +2011,24 @@
input',
-(
function
(options
@@ -2023,55 +2023,15 @@
tion
+
(
-optionsParent) %7B %0A return function(e
) %7B%0A%0A
-
@@ -2078,23 +2078,15 @@
s) %7B
- %0A
+%0A
- var
opti
@@ -2140,18 +2140,16 @@
-
-
return p
@@ -2181,18 +2181,16 @@
-
%7D, '%3Copt
@@ -2209,26 +2209,24 @@
%3E');%0A%0A
-
-
options = do
@@ -2251,18 +2251,16 @@
ns %7D%60);%0A
-
do
@@ -2293,26 +2293,24 @@
ent);%0A
-
optionsParen
@@ -2337,19 +2337,9 @@
s);%0A
- %0A
+%0A
@@ -2371,47 +2371,16 @@
-
%7D);%0A
- %0A %7D;%0A %7D)(optionsParent)
+%0A %7D
);%0A%0A
@@ -2454,18 +2454,16 @@
alist);%0A
-
%0A retur
@@ -2476,9 +2476,8 @@
lt;%0A
-
%0A%7D;
+%0A
|
208e8a4e5ee309f540f87ab7e23d3f56a14edb40 | Fix for day of the weekday mapping, in newer versions in Node-RED | schedule.js | schedule.js | /**
* Copyright 2014 Nicholas J Humfrey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
function loadFlows() {
$.getJSON('../flows', function( nodes ) {
for (var i in nodes) {
var n = nodes[i];
var days = {
"*": "every day",
"1-5": "Mondays to Fridays",
"6-7": "Saturdays and Sundays",
"1": "Mondays",
"2": "Tuesdays",
"3": "Wednesdays",
"4": "Thursdays",
"5": "Fridays",
"6": "Saturdays",
"7": "Sundays"
};
if (n.type == 'inject' && n.crontab) {
var cronparts = n.crontab.split(" ");
var day = cronparts[4];
$('#schedule tbody').append(
'<tr>'+
'<td>'+n.name+'</td>'+
'<td>'+cronparts[1]+'</td>'+
'<td>'+cronparts[0]+'</td>'+
'<td>'+cronparts[2]+'</td>'+
'<td>'+cronparts[3]+'</td>'+
'<td>'+days[day]+'</td>'+
'<td>'+n.topic+'</td>'+
'<td>'+n.payload+'</td>'+
'</tr>'
);
}
}
});
}
$(function() {
loadFlows();
});
| JavaScript | 0 | @@ -743,17 +743,19 @@
var day
-s
+map
= %7B%0A
@@ -777,15 +777,15 @@
%22: %22
-e
+E
very
-d
+D
ay%22,
@@ -806,29 +806,59 @@
%22
-1-5
+6,0
%22: %22
-Mondays to Fri
+Weekend%22,%0A %221,2,3,4,5%22: %22Week
days
@@ -881,36 +881,16 @@
%22
-6-7
+0
%22: %22S
-aturdays and Sundays
+un
%22,%0A
@@ -913,20 +913,16 @@
1%22: %22Mon
-days
%22,%0A
@@ -941,21 +941,16 @@
2%22: %22Tue
-sdays
%22,%0A
@@ -973,15 +973,8 @@
%22Wed
-nesdays
%22,%0A
@@ -1000,15 +1000,9 @@
%22Th
-ursdays
+r
%22,%0A
@@ -1025,20 +1025,16 @@
5%22: %22Fri
-days
%22,%0A
@@ -1057,14 +1057,8 @@
%22Sat
-urdays
%22,%0A
@@ -1081,20 +1081,16 @@
7%22: %22Sun
-days
%22%0A
@@ -1227,16 +1227,17 @@
var day
+s
= cronp
@@ -1245,16 +1245,248 @@
rts%5B4%5D;%0A
+ if (daymap.hasOwnProperty(days)) %7B%0A days = daymap%5Bdays%5D;%0A %7D else %7B%0A days = days.split(',').map(function(day) %7Breturn daymap%5Bday%5D;%7D).join(', ');%0A %7D%0A%0A
@@ -1806,21 +1806,16 @@
d%3E'+days
-%5Bday%5D
+'%3C/td%3E'
|
46991b76fd4ec1b753ed80f92f4f34b87deea940 | Fix an easy `any`. | src/realm/realmActions.js | src/realm/realmActions.js | /* @flow */
import type {
Auth,
GetState,
Dispatch,
RealmFilter,
InitialData,
RealmInitAction,
DeleteTokenPushAction,
SaveTokenPushAction,
InitRealmEmojiAction,
InitRealmFilterAction,
} from '../types';
import { initializeNotifications, refreshNotificationToken } from '../utils/notifications';
import { getAuth, getPushToken } from '../selectors';
import { getRealmEmojis, getRealmFilters } from '../api';
import {
REALM_INIT,
SAVE_TOKEN_PUSH,
DELETE_TOKEN_PUSH,
INIT_REALM_EMOJI,
INIT_REALM_FILTER,
} from '../actionConstants';
export const realmInit = (data: InitialData): RealmInitAction => ({
type: REALM_INIT,
data,
});
export const deleteTokenPush = (): DeleteTokenPushAction => ({
type: DELETE_TOKEN_PUSH,
});
export const saveTokenPush = (
pushToken: string,
result: string,
msg: string,
): SaveTokenPushAction => ({
type: SAVE_TOKEN_PUSH,
pushToken,
result,
msg,
});
export const initNotifications = () => (dispatch: Dispatch, getState: GetState) => {
const auth = getAuth(getState());
const pushToken = getPushToken(getState());
if (auth.apiKey !== '' && (pushToken === '' || pushToken === undefined)) {
refreshNotificationToken();
}
initializeNotifications(auth, (token, msg, result) => {
dispatch(saveTokenPush(token, result, msg));
});
};
export const initRealmEmojis = (emojis: Object): InitRealmEmojiAction => ({
type: INIT_REALM_EMOJI,
emojis,
});
export const fetchRealmEmojis = (auth: Auth) => async (dispatch: Dispatch) =>
dispatch(initRealmEmojis(await getRealmEmojis(auth)));
export const initRealmFilters = (filters: RealmFilter[]): InitRealmFilterAction => ({
type: INIT_REALM_FILTER,
filters,
});
export const fetchRealmFilters = (auth: Auth) => async (dispatch: Dispatch) =>
dispatch(initRealmFilters(await getRealmFilters(auth)));
| JavaScript | 0.000002 | @@ -2,16 +2,29 @@
* @flow
+strict-local
*/%0Aimpor
@@ -94,16 +94,35 @@
alData,%0A
+ RealmEmojiState,%0A
RealmI
@@ -1397,14 +1397,23 @@
is:
-Object
+RealmEmojiState
): I
|
af326f7ad485710887780b5c1ae10c07dbed438c | complete add image condition | waterfallFlow/js/index.js | waterfallFlow/js/index.js | window.onload = function() {
waterfall('main', 'box');
window.onscroll = function() {
}
}
function waterfall(parent, box) {
// 将main下的所有的class为box的元素取出来
var oParent = document.getElementById(parent);
var oBoxs = getByClass(oParent, box);
// 计算整个页面显示的列数(页面宽/box的宽)
var oBoxW = oBoxs[0].offsetWidth;
var cols = Math.floor(document.documentElement.clientWidth / oBoxW); // 页面宽度
// 设置main的宽
oParent.style.cssText = 'width:' + oBoxW * cols + 'px; margin: 0 auto';
var hArr = []; // 存放每一列高度的数组
for (var i = 0; i < oBoxs.length; i++) {
if (i < cols) {
hArr.push(oBoxs[i].offsetHeight);
} else {
var minH = Math.min.apply(null, hArr);
var index = getMinhIndex(hArr, minH);
oBoxs[i].style.position = 'absolute';
oBoxs[i].style.top = minH + 'px';
// oBoxs[i].style.left = oBoxW * indxex + 'px';
oBoxs[i].style.left = oBoxs[index].offsetLeft + 'px';
hArr[index] += oBoxs[i].offsetHeight;
}
}
}
function getByClass(parent, clsName) {
var boxArr = [], // 用来存储获取到的所有class为box的元素
oElements = parent.getElementsByTagName('*');
for (var i = 0; i < oElements.length; i++) {
if (oElements[i].className == clsName) {
boxArr.push(oElements[i]);
}
}
return boxArr;
}
function getMinhIndex(arr, target) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === target) {
return i;
}
}
} | JavaScript | 0 | @@ -88,16 +88,48 @@
) %7B%0A
+if (checkScrollSlide()) %7B%0A%0A %7D
%0A %7D%0A%7D%0A%0A
@@ -671,16 +671,36 @@
else %7B%0A
+ // %E7%BB%99%E5%89%A9%E4%B8%8B%E7%9A%84%E5%85%83%E7%B4%A0%E8%BF%9B%E8%A1%8C%E5%AE%9A%E4%BD%8D%0A
va
@@ -1451,20 +1451,530 @@
eturn i;%0A %7D%0A %7D%0A%7D
+%0A%0A// %E6%A3%80%E6%B5%8B%E6%98%AF%E5%90%A6%E5%85%B7%E5%A4%87%E4%BA%86%E6%BB%9A%E5%8A%A8%E6%9D%A1%E5%8A%A0%E8%BD%BD%E6%95%B0%E6%8D%AE%E7%9A%84%E6%9D%A1%E4%BB%B6%0Afunction checkScrollSlide() %7B%0A var oParent = document.getElementById('main');%0A var oBoxs = getByClass(oParent, 'box');%0A%0A var lastBoxH = oBoxs%5BoBoxs.length - 1%5D.offsetTop + Math.floor(oBoxs%5BoBoxs.length - 1%5D.offsetHeight / 2);%0A var scrollTop = document.documentElement.scrollTop %7C%7C document.body.scrollTop;%0A var height = document.documentElement.clientHeight %7C%7C document.body.clientHeight;%0A%0A console.log(lastBoxH %3C= height + scrollTop )%0A %0A return lastBoxH %3C= height + scrollTop %0A%7D
|
81244a0f4ead086c297f8c5aeaf62d9d496aab43 | Update bindery.js | web-components/bindery.js | web-components/bindery.js | /**
# bindery
This is a simple experimental component for binding a model to the DOM.
You assign an object to the `<bindery-model>`'s `value` and then bind to its
(top-level) properties by name.
For example:
```
<bindery-model events="mouseup">
<h4>Simple Binding</h4>
<button data-on="mouseup=click" data-to="textContent=caption"></button>
<h4>One-Way Binding</h4>
<label>
to-binding
<input data-to="value=caption"><button data-on="mouseup=save">Save</button>
</label>
<h4>Two-Way Binding</h4>
<label>
from-binding
<input data-from="value=caption">
</label>
</bindery-model>
<script>
require('web-components/bindery.js');
document.querySelector('bindery-model').value = {
caption: 'an example',
click () {
alert(`you clicked "${this.value.caption}"`)
},
save (evt) {
const caption = evt.target.previousElementSibling.value;
this.value = Object.assign(this.value, {caption});
},
};
</script>
```
Bindery uses `data-on`, `data-to`, and `data-from` attributes to drive its bindings.
- `data-on` binds events to methods by name
- `data-to` sends data to the DOM by name (one-way binding)
- `data-from` syncs data to the DOM by name (two-way binding)
As of now, this is really just a toy. It only allows for one event and one data
binding per element, and it doesn't use b8r's `byPath` library or its `toTargets`
and `fromTargets`. But it's fairly easy to see that if this functionality were
integrated, then a `<bindery-model>` element would function as a standalone
`b8r`-like context.
Similarly, it would be easy enough to make the `data-from` bindings inactive by
default (essentially giving you a redux-like data-flow) or simply not support them
at all.
*/
const {
makeWebComponent,
} = require('../lib/web-components.js');
const BinderyModel = makeWebComponent('bindery-model', {
value: true,
attributes: {
events: '',
},
methods: {
get(path) {
return this.value[path];
},
handleEvent(evt) {
const bindery = evt.target.closest('bindery-model');
const model = bindery.value;
const {type, target} = evt;
const eventTarget = target.closest(`[data-on*="${type}"]`);
if (eventTarget) {
const handler = eventTarget.dataset.on.split('=').pop();
model[handler].call(bindery, evt, eventTarget, model);
}
},
handleChange(evt) {
const bindery = evt.target.closest('bindery-model');
const {type, target} = evt;
const changeTarget = target.closest(`[data-from]`);
if (changeTarget) {
const [target, path] = changeTarget.dataset.from.split('=');
bindery.value = Object.assign(bindery.value, {[path]: changeTarget[target]})
}
},
render() {
const slot = this.shadowRoot.querySelector('slot');
this.events.split(',').forEach(type => slot.addEventListener(type, this.handleEvent, {capture:true}));
['change', 'input'].forEach(type => slot.addEventListener(type, this.handleChange, {capture:true}));
const model = this.value;
if (model) {
const subscribers = this.querySelectorAll('[data-to],[data-from]');
subscribers.forEach(elt => {
const [prop, path] = (elt.dataset.to || elt.dataset.from).split('=');
elt[prop] = model[path];
});
}
}
},
});
module.exports = {
BinderyModel,
} | JavaScript | 0 | @@ -1224,16 +1224,281 @@
nding)%0A%0A
+### Ideas%0A%0A- implement multiple bindings%0A- implement %60toTargets%60 (and possibly %60fromTargets%60)%0A- implement list bindings -- %60%3Cbindery-list%3E%60? Contents become template, slot is hidden.%0A- consider whether to add %60byPath%60 support or keep paths simple (one level deep)%0A%0A
As of no
@@ -1609,19 +1609,21 @@
n't use
+%60
b8r
+%60
's %60byPa
|
d57fa56331d55c407cd6a860ddf7cbfcd53c999f | improve code formatting | src/EvernoteClient.js | src/EvernoteClient.js | import Promise from 'bluebird'
import { Evernote } from 'evernote'
import EvermarkError from './EvermarkError'
const debug = require('debug')('evernote')
// Define Evernote API error codes
export const UNKNOWN_ERROR = 1
export const BAD_DATA_FORMAT = 2
export const PERMISSION_DENIED = 3
export const INTERNAL_ERROR = 4
export const DATA_REQUIRED = 5
export const LIMIT_REACHED = 6
export const QUOTA_REACHED = 7
export const INVALID_AUTH = 8
export const AUTH_EXPIRED = 9
export const DATA_CONFLICT = 10
export const ENML_VALIDATION = 11
export const SHARD_UNAVAILABLE = 12
export const LEN_TOO_SHORT = 13
export const LEN_TOO_LONG = 14
export const TOO_FEW = 15
export const TOO_MANY = 16
export const UNSUPPORTED_OPERATION = 17
export const TAKEN_DOWN = 18
export const RATE_LIMIT_REACHED = 19
export const OBJECT_NOT_FOUND = 100
const ERROR_CODES = {
[UNKNOWN_ERROR]: 'UNKNOWN',
[BAD_DATA_FORMAT]: 'BAD_DATA_FORMAT',
[PERMISSION_DENIED]: 'PERMISSION_DENIED',
[INTERNAL_ERROR]: 'INTERNAL_ERROR',
[DATA_REQUIRED]: 'DATA_REQUIRED',
[LIMIT_REACHED]: 'LIMIT_REACHED',
[QUOTA_REACHED]: 'QUOTA_REACHED',
[INVALID_AUTH]: 'INVALID_AUTH',
[AUTH_EXPIRED]: 'AUTH_EXPIRED',
[DATA_CONFLICT]: 'DATA_CONFLICT',
[ENML_VALIDATION]: 'ENML_VALIDATION',
[SHARD_UNAVAILABLE]: 'SHARD_UNAVAILABLE',
[LEN_TOO_SHORT]: 'LEN_TOO_SHORT',
[LEN_TOO_LONG]: 'LEN_TOO_LONG',
[TOO_FEW]: 'TOO_FEW',
[TOO_MANY]: 'TOO_MANY',
[UNSUPPORTED_OPERATION]: 'UNSUPPORTED_OPERATION',
[TAKEN_DOWN]: 'TAKEN_DOWN',
[RATE_LIMIT_REACHED]: 'RATE_LIMIT_REACHED',
[OBJECT_NOT_FOUND]: 'OBJECT_NOT_FOUND',
}
// Define Evernote default resource type
export const DEFAULT_RESOURCE_TYPE = 'application/octet-stream'
// Define Evernote resource type mappings
export const RESOURCE_TYPES = {
'.png': 'image/png',
'.gif': 'image/gif',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
}
function wrapError(exception) {
const error = new EvermarkError()
error.code = exception.errorCode || UNKNOWN_ERROR
if (exception.identifier) {
error.code = OBJECT_NOT_FOUND
}
const codeStr = ERROR_CODES[error.code] || ERROR_CODES[UNKNOWN_ERROR]
const message = `Evernote API Error: ${codeStr}`
if (exception.parameter) {
error.message = `${message}\n\nThe invalid parameter: ${exception.parameter}`
}
if (exception.message) {
error.message = `${message}\n\n${exception.message}`
}
if (exception.identifier) {
error.message = `${message}\n\nObject not found by identifier ${exception.identifier}`
}
return error
}
export default class EvernoteClient {
constructor({ token, china = true, sandbox = false } = { china: true, sandbox: false }) {
if (!token) {
throw new EvermarkError('Missing developer token')
}
let serviceHost = china ? 'app.yinxiang.com' : 'www.evernote.com'
serviceHost = sandbox ? 'sandbox.evernote.com' : serviceHost
const options = { token, sandbox, serviceHost }
debug('Evernote client options: %o', options)
this.options = options
const client = new Evernote.Client(options)
this.noteStore = client.getNoteStore()
if (!this.noteStore.listNotebooksAsync) {
Promise.promisifyAll(this.noteStore)
}
}
listNotebooks() {
return this.noteStore.listNotebooksAsync()
.catch(e => {
throw wrapError(e)
})
}
createNotebook(name) {
const notebook = new Evernote.Notebook()
notebook.name = name
return this.noteStore.createNotebookAsync(notebook)
.catch(e => {
throw wrapError(e)
})
}
createNote(note) {
return this.noteStore.createNoteAsync(note)
.catch(e => {
throw wrapError(e)
})
}
updateNote(note) {
return this.noteStore.updateNoteAsync(note)
.catch(e => {
throw wrapError(e)
})
}
expungeNote(guid) {
return this.noteStore.expungeNoteAsync(guid)
.catch(e => {
throw wrapError(e)
})
}
}
| JavaScript | 0.000327 | @@ -2059,16 +2059,17 @@
UND%0A %7D%0A
+%0A
const
|
5f7ca54d4eecd29043dee6e7ae8956f1d51fda1e | update dll build | build/dll/webpack.config.dll.js | build/dll/webpack.config.dll.js | const webpack = require('webpack'),
AssetsPlugin = require('assets-webpack-plugin'),
CompressionPlugin = require('compression-webpack-plugin'),
config = require('../config.js'),
utils = require('../utils.js'),
library = '[name]_lib';
module.exports = {
mode: 'production',
entry: {
'polyfill': ['@babel/polyfill'],
'moment': ['moment'],
'react': ['react', 'react-dom', 'react-redux', 'react-router', 'react-router-config', 'react-router-dom',
'connected-react-router', 'redux', 'redux-thunk', 'react-transition-group'],
'tools': ['classnames', 'history', 'dom-helpers']
},
output: {
publicPath: './',
path: config.build.assetsRoot,
filename: utils.assetsSubPath('vendors/[name].[chunkhash].js'),
library
},
plugins: [
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
new webpack.DllPlugin({
context: __dirname,
path: utils.assetsVendorsAbsolutePath('[name]-manifest.json'),
name: library
}),
new AssetsPlugin({
path: config.build.assetsRoot,
filename: utils.assetsSubPath('vendors/vendors-assets.json')
}),
new CompressionPlugin({
test: new RegExp('\\.(' + config.productionGzipExtensions.join('|') + ')$'),
cache: true,
filename: '[path].gz[query]',
algorithm: 'gzip',
threshold: 1,
minRatio: 0.8
})
]
};
| JavaScript | 0.000001 | @@ -85,16 +85,19 @@
n'),%0A
+ //
Compres
@@ -1227,33 +1227,32 @@
son')%0A %7D)
-,
%0A%0A new Co
@@ -1240,24 +1240,27 @@
%7D)%0A%0A
+ //
new Compres
@@ -1275,24 +1275,27 @@
in(%7B%0A
+ //
test: n
@@ -1367,24 +1367,27 @@
$'),%0A
+ //
cache:
@@ -1391,32 +1391,35 @@
e: true,%0A
+ //
filename: '
@@ -1440,24 +1440,27 @@
y%5D',%0A
+ //
algorit
@@ -1474,24 +1474,27 @@
ip',%0A
+ //
thresho
@@ -1503,24 +1503,27 @@
: 1,%0A
+ //
minRati
@@ -1528,31 +1528,34 @@
tio: 0.8%0A
+ //
%7D)%0A%0A %5D%0A%0A%7D;%0A
|
c8ea3293e879738eed1c731b065d86e42a400a00 | convert to ES6 class syntax | ArtistListScreen.js | ArtistListScreen.js | 'use strict';
var React = require('react-native');
var {
AppRegistry,
Image,
ListView,
StyleSheet,
Text,
View,
} = React;
var fetch = require('fetch');
var API_KEY='81bbfd4ecee91148e9f6df34090f5d7e';
var API_URL = 'http://ws.audioscrobbler.com/2.0/?method=geo.gettopartists&country=ukraine&format=json';
var REQUEST_URL = API_URL + '&api_key=' + API_KEY;
var ArtistListScreen = React.createClass({
getInitialState: function() {
return {
isLoading: false,
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2
})
}
},
componentDidMount: function() {
this.loadArtists();
},
loadArtists: function() {
this.setState({
isLoading: true
});
fetch(REQUEST_URL)
.then((response) => response.json())
.catch((error) => {
console.error(error);
})
.then((responseData) => {
console.log(responseData)
this.setState({
isLoading: false,
dataSource: this.getDataSource(responseData.topartists.artist)
})
})
.done();
},
getDataSource: function(artists: Array<any>): ListView.DataSource {
return this.state.dataSource.cloneWithRows(artists);
},
renderRow: function(artist: Object) {
return (
<View>
<Text>
{artist.name}
</Text>
</View>
);
},
render: function() {
return (
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderRow}
automaticallyAdjustContentInsets={false}
keyboardDismissMode="onDrag"
keyboardShouldPersistTaps={true}
showsVerticalScrollIndicator={false}
/>
);
}
});
module.exports = ArtistListScreen; | JavaScript | 0.999994 | @@ -364,19 +364,21 @@
I_KEY;%0A%0A
-var
+class
ArtistL
@@ -391,74 +391,90 @@
een
-= React.createClass(%7B%0A getInitialState: function() %7B%0A return
+extends React.Component %7B%0A constructor(props) %7B%0A super(props)%0A this.state =
%7B%0A
@@ -607,25 +607,24 @@
%7D)%0A %7D%0A %7D
-,
%0A %0A compon
@@ -634,26 +634,16 @@
DidMount
-: function
() %7B%0A
@@ -666,17 +666,16 @@
s();%0A %7D
-,
%0A %0A lo
@@ -683,26 +683,16 @@
dArtists
-: function
() %7B%0A
@@ -1095,25 +1095,24 @@
.done();%0A %7D
-,
%0A%0A getDataS
@@ -1116,26 +1116,16 @@
taSource
-: function
(artists
@@ -1217,25 +1217,24 @@
rtists);%0A %7D
-,
%0A%0A renderRo
@@ -1234,26 +1234,16 @@
enderRow
-: function
(artist:
@@ -1370,17 +1370,16 @@
);%0A %7D
-,
%0A%0A rend
@@ -1384,18 +1384,8 @@
nder
-: function
() %7B
@@ -1685,17 +1685,16 @@
);%0A %7D%0A%7D
-)
;%0A%0Amodul
|
fbb8f67f838f8fe820d6446fca2d702b172b1472 | Use TranslatedText component to get translated text. | src/common/Label.js | src/common/Label.js | /* @flow */
import React, { PureComponent } from 'react';
import { Text } from 'react-native';
import { FormattedMessage } from 'react-intl';
import type { LocalizableText, Style } from '../types';
type Props = {
text: LocalizableText,
style?: Style,
};
export default class Label extends PureComponent<Props> {
static contextTypes = {
styles: () => null,
};
props: Props;
render() {
const { text, style, ...restProps } = this.props;
const message = text.text || text;
const { styles } = this.context;
return (
<Text style={[styles.label, style]} {...restProps}>
<FormattedMessage id={message} defaultMessage={message} values={text.values} />
</Text>
);
}
}
| JavaScript | 0 | @@ -99,45 +99,45 @@
ort
-%7B FormattedMessage %7D from 'react-intl
+TranslatedText from './TranslatedText
';%0A%0A
@@ -398,16 +398,53 @@
der() %7B%0A
+ const %7B styles %7D = this.context;%0A
cons
@@ -492,84 +492,8 @@
ops;
-%0A const message = text.text %7C%7C text;%0A const %7B styles %7D = this.context;
%0A%0A
@@ -574,82 +574,33 @@
%3C
-FormattedMessage id=%7Bmessage%7D defaultMessage=%7Bmessage%7D values=%7Btext.values
+TranslatedText text=%7Btext
%7D /%3E
|
50418bb49f3cb8ee2c45db7fa340cd0eac114f5c | use currentUserMock for settings story | src/pages/Settings.story.js | src/pages/Settings.story.js | import { storiesOf } from '@storybook/vue'
import store from '@/store'
import i18n from '@/i18n'
import Settings from '@/pages/Settings'
import { usersMock } from '>/mockdata'
storiesOf('Settings Page', module)
.add('Default', () => ({
render (h) {
return h(Settings)
},
created () {
store.commit('auth/Receive Login Status', { user: usersMock[0] })
},
i18n,
store,
}))
| JavaScript | 0 | @@ -140,21 +140,27 @@
mport %7B
-u
+currentU
ser
-s
Mock %7D f
@@ -365,20 +365,23 @@
er:
-u
+currentU
ser
-s
Mock
-%5B0%5D
%7D)%0A
|
a61a722f69658d4bae98c6e93a898cd5e5837b16 | Enable streaming for GAE logs | builder/server.js | builder/server.js | 'use strict';
const fs = require('fs');
const express = require('express');
const spawn = require('child_process').spawn;
const bodyParser = require('body-parser');
const API_KEY_HEADER = 'X-API-KEY';
const PORT = 8080;
// Handler for CI.
function runLH(params, req, res, next) {
const url = params.url;
const format = params.format || 'html';
const log = params.log || req.method === 'GET';
if (!url) {
res.status(400).send('Please provide a URL.');
return;
}
const fileName = `report.${Date.now()}.${format}`;
const outputPath = `./reports/${fileName}`;
const args = [`--output-path=${outputPath}`, `--output=${format}`, '--port=9222'];
const child = spawn('lighthouse', [...args, url]);
if (log) {
res.writeHead(200, {
'Content-Type': 'text/html',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
res.write(`
<style>
textarea {
font: inherit;
width: 100vw;
height: 100vh;
border: none;
outline: none;
}
</style>
<textarea>
`);
}
child.stderr.on('data', data => {
const str = data.toString();
if (log) {
res.write(str);
}
console.log(str);
});
child.on('close', statusCode => {
if (log) {
res.write('</textarea>');
res.write(`<meta http-equiv="refresh" content="0;URL='/${fileName}'">`);
res.end();
} else {
res.sendFile(`/${outputPath}`, {}, err => {
if (err) {
next(err);
}
fs.unlink(outputPath); // delete report
});
}
});
}
// Serve sent event handler for https://lighthouse-ci.appspot.com/try.
function runLighthouseAsEventStream(req, res, next) {
const url = req.query.url;
const format = req.query.format || 'html';
if (!url) {
res.status(400).send('Please provide a URL.');
return;
}
// Send headers for event-stream connection.
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'Access-Control-Allow-Origin': '*',
'X-Accel-Buffering': 'no' // Forces Flex App Engine to keep connection open for SSE.
});
const file = `report.${Date.now()}.${format}`;
const fileSavePath = './reports/';
const args = [`--output-path=${fileSavePath + file}`, `--output=${format}`, '--port=9222'];
const child = spawn('lighthouse', [...args, url]);
let log = '';
child.stderr.on('data', data => {
const str = data.toString();
res.write(`data: ${str}\n\n`);
log += str;
});
child.on('close', statusCode => {
const serverOrigin = `https://${req.host}/`;
res.write(`data: done ${serverOrigin + file}\n\n`);
res.status(410).end();
console.log(log);
log = '';
});
}
const app = express();
app.use(bodyParser.json());
app.use(express.static('reports'));
app.get('/ci', (req, res, next) => {
const apiKey = req.query.key;
// Require API for get requests.
if (!apiKey) {
const msg = `Missing API key. Please include the key parameter`;
res.status(403).send(`Missing API key. Please include the key parameter`);
return;
}
console.log(`${API_KEY_HEADER}: ${apiKey}`);
runLH(req.query, req, res, next);
});
app.post('/ci', (req, res, next) => {
// // Require an API key from users.
// if (!req.get(API_KEY_HEADER)) {
// const msg = `${API_KEY_HEADER} is missing`;
// const err = new Error(msg);
// res.status(403).json(err.message);
// return;
// }
console.log(`${API_KEY_HEADER}: ${req.get(API_KEY_HEADER)}`);
runLH(req.body, req, res, next);
});
app.get('/stream', (req, res, next) => {
runLighthouseAsEventStream(req, res, next);
});
app.listen(PORT);
console.log(`Running on http://localhost:${PORT}`);
| JavaScript | 0 | @@ -856,16 +856,114 @@
p-alive'
+,%0A 'X-Accel-Buffering': 'no' // Forces Flex App Engine to keep connection open for streaming.
%0A %7D);
|
d65c7c1f2d553b73f82ecfbd9a9e3e092542fc5a | remove unused dependencies | src/tasks/task/view/taskView.js | src/tasks/task/view/taskView.js | angular.module('tasks')
.config(['$routeProvider', '$locationProvider', '$stateProvider', '$urlRouterProvider', 'sysConfig', 'securityAuthorizationProvider',
function ($routeProvider, $locationProvider, $stateProvider, $urlRouterProvider, sysConfig, securityAuthorizationProvider) {
var taskView = {
name: 'page.taskView',
url: '/tasks/:num',
views: {
'content': {
templateUrl: sysConfig.src('tasks/task/view/taskView.tpl.html')
}
},
resolve: {
pageConfig: 'pageConfig',
currentUser: securityAuthorizationProvider.requireAuthenticatedUser()
},
onEnter: ['pageConfig', '$stateParams', function(pageConfig, $stateParams) {
pageConfig.setConfig({
breadcrumbs: [
{ name: 'Tasks', url: '#!/' },
{ name: $stateParams.num, url: '#!/tasks/' + $stateParams.num }]
});
}]
};
$stateProvider.state(taskView);
}
])
.controller('taskViewCtrl', ['$scope', 'sysConfig', 'apinetService', '$stateParams',
function($scope, sysConfig, apinetService, $stateParams) {
//TODO move to utils??
var make = function(task, prop, value, valueProp) {
valueProp = valueProp || 'id';
var val = angular.isArray(value)
? value.map(function(item) { return item[valueProp] })
: angular.isObject(value) && !angular.isDate(value)
? value[valueProp]
: value;
return {Id: task.Id, ModelVersion: task.ModelVersion, Prop: prop, Value: val};
}
$scope.changeStatus = function(hrecord) {
$scope.onUpdateProp($scope.model, 'Status', hrecord.id);
};
$scope.changeCustomStatus = function(hrecord) {
$scope.onUpdateProp($scope.model, 'CustomStatus', hrecord.id);
};
$scope.onUpdateProp = function(task, prop, val) {
apinetService.action({
method: 'tasks/tasks/UpdateTask',
project: sysConfig.project,
data: make(task, prop, val) })
.then(function(response) {
$scope.resetValidation();
angular.extend($scope.validation, response.validation);
angular.extend($scope.model, response.model);
}, handleException);
};
$scope.resetValidation = function() {
if (!$scope.validation) {
$scope.validation = {};
}
$scope.validation.generalErrors = [];
$scope.validation.fieldErrors = {};
};
var handleException = function(error) {
$scope.resetValidation();
$scope.validation.generalErrors = [error];
};
apinetService.action({
method: 'tasks/tasks/GetTask',
project: sysConfig.project,
numpp: $stateParams.num })
.then(function(response) {
$scope.model = response;
}, handleException);
$scope.resetValidation();
}]); | JavaScript | 0.000003 | @@ -32,203 +32,87 @@
(%5B'$
-routeProvider', '$locationProvider', '$stateProvider', '$urlRouterProvider', 'sysConfig', 'securityAuthorizationProvider',%0A%09function ($routeProvider, $locationProvider, $stateProvider, $urlRouter
+stateProvider', 'sysConfig', 'securityAuthorizationProvider',%0A%09function ($state
Prov
|
c13c59ce454951432da5805947970b11d90ff629 | Update app.settings.js | app/app.settings.js | app/app.settings.js | var app = angular.module('hpsa-client');
app.constant('AppSettings', {
apiUrl: 'http://expense-api.52.27.252.3.nip.io/',
})
| JavaScript | 0.000002 | @@ -103,16 +103,17 @@
.52.
-27.252.3
+39.108.65
.nip
|
039eb2066711ecb68909526fd1a238d942657146 | Update auth.js | Auth-plugin/auth.js | Auth-plugin/auth.js |
this.init = function(index, gameServer) {
this.gameServer = gameServer;
this.index = index;
}
this.beforespawn = function (player) {
if (!player.auth) {
if (!player.astage) player.astage = 0;
if (player.astage == 0) {
player.frozen = true;
player.aname = player.name;
var name = 'w = login';
if (this.index.config.allowregister == 1) {
name = name + ', Space = register';
}
if (this.index.config.requirelogin != 1) {
name = name + ', q = playasguest';
}
player.name = name;
} else if (player.astage == 1) {
player.name = 'Username: (press w)';
} else if (player.astage == 2) {
player.un = player.name;
player.name = 'pass: (press w)';
} else if (player.astage == 3) {
player.pa = player.name;
player.name = 'Press w to confirm';
} else if (player.astage == 5) {
player.name = 'Username (press w)';
} else if (player.astage == 6) {
ok = true;
for (var i in gameServer.account) {
if (gameServer.account[i].username == player.name) {
ok = false
break;
}
}
if (ok) {
player.pa = player.name;
player.name = 'Pass: (pres w)';
player.astage = 7;
} else {
player.name = 'Username taken (press w)';
player.astage = 50;
}
} else if (player.astage == 8) {
player.pass = player.name;
player.astage = 9;
var ac = {
username: player.un,
pass: player.pass,
};
gameServer.account.push(ac);
player.name = 'Success!, Press w to login'
player.astage = 50;
}
return true;
}
return true;
};
this.beforeeject = function(player) {
if (player.astage > -1 && player.astage < 3) {
player.cells.forEach((cell)=>this.removeNode(cell));
player.astage ++;
return false;
} else if (player.astage == 3) {
var ok = false;
for (var i in gameServer.account) {
var account = gameServer.account[i];
if (account && account.pass == player.pa && account.un == account.username) {
ok = true;
player.accountid = i;
break;
}
}
if (!ok) {
player.name = 'Wrong pass or username , press w';
player.astage = 50;
} else {
player.name = 'Success, press w'
player.astage = 4;
}
return false
} else if (player.astage == 4) {
player.frozen = false;
player.name = player.aname;
player.astage = 100;
return false
} else if (player.astage == 5) {
player.cells.forEach((cell)=>this.gameServer.removeNode(cell));
player.astage = 6;
} else if (player.astage == 50) {
player.cells.forEach((cell)=>this.gameServer.removeNode(cell));
player.astage = 0;
} else if (player.astage == 7) {
player.cells.forEach((cell)=>this.gameServer.removeNode(cell));
player.astage = 8;
} else {
return true;
}
return false;
};
this.beforesplit = function(player) {
if (player.astage == 0 && this.index.config.allowregister == 1) {
player.cells.forEach((cell)=>this.gameServer.removeNode(cell));
player.astage = 5;
} else {
return true;
}
return false;
};
this.beforeq = function(player) {
if (player.astage == 0 && this.index.config.requirelogin != 1) {
player.frozen = false;
player.name = player.aname;
player.astage = 50
} else if (player.astage > 0 && player.astage < 100) {
player.cells.forEach((cell)=>this.gameServer.removeNode(cell));
player.astage = 0;
}
}
module.exports = this;
| JavaScript | 0.000001 | @@ -147,24 +147,48 @@
yer.auth) %7B%0A
+ player.frozen = true;%0A
if (!playe
@@ -248,34 +248,8 @@
) %7B%0A
- player.frozen = true;%0A
@@ -2340,16 +2340,38 @@
= 100;%0A
+ player.auth = true;%0A
return
@@ -3193,18 +3193,43 @@
stage =
-50
+100%0A player.auth = true;
%0A %7D els
|
2395159e4a66c815efb6ed007d557646e028a69a | optimize ref method in props-proxy HOC | src/HOC/propsProxy.js | src/HOC/propsProxy.js | /**
* @file 高阶组件之属性代理
*/
import React, { Component } from 'react'
class Input extends Component {
constructor(props) {
super(props);
this.printName = this.printName.bind(this)
}
printName() {
console.log(`Wrapped component's name: ${this.props.name}`)
}
render() {
return <input name="name" {...this.props} />
}
}
const Editable = WrappedComponent => class extends Component {
constructor(props) {
super(props);
this.state = {
value: 'I am editable'
};
this.onChange = this.onChange.bind(this)
}
onChange(e) {
this.setState({ value: e.target.value })
}
printName(instance) {
instance.printName()
}
render() {
const newProps = {
value: this.state.value,
onChange: this.onChange,
ref: this.printName.bind(this)
};
return <WrappedComponent {...this.props} {...newProps} />
}
};
const ReadOnly = (name, value = 'I am read-only') => WrappedComponent => props => {
const newProps = {
// this will override 'name' from HOC
name,
value,
readOnly: true
};
return <WrappedComponent {...props} {...newProps} />
};
export const EditableInput = Editable(Input);
export const ReadOnlyInput = ReadOnly('read-only-input')(Input);
| JavaScript | 0 | @@ -232,55 +232,108 @@
cons
-ole.log(%60Wrapped component's name: $%7Bthis.props
+t %7B input %7D = this.refs;%0A console.log(%60Wrapped component is an $%7Binput.tagName%7D named $%7Binput
.nam
@@ -379,16 +379,28 @@
n %3Cinput
+ ref=%22input%22
name=%22n
@@ -613,58 +613,8 @@
%7D
-;%0A this.onChange = this.onChange.bind(this)
%0A
@@ -693,69 +693,8 @@
%7D%0A
- printName(instance) %7B%0A instance.printName()%0A %7D%0A
@@ -826,32 +826,39 @@
ef:
-this.printName.bind(this
+instance =%3E instance.printName(
)%0A
|
1e8b44ffc0e736bdd51f40fa9448c4380784f5a1 | remove on | node/src/socket/UDPServer.js | node/src/socket/UDPServer.js | import dgram from 'dgram'
const handleCommand = (socket) => {
// Passed string of command to relay
console.log('socket start', socket)
socket.on('prime', (data) => {
console.log(`prime command: ${data}`)
// Info for connecting to the local process via UDP
const PORT = 12345
const HOST = '192.168.7.2'
const buffer = new Buffer(data)
const client = dgram.createSocket('udp4')
client.send(buffer, 0, buffer.length, PORT, HOST, (err, bytes) => {
if (err) throw err
console.log(`UDP message sent to ${HOST}:${PORT}`)
})
client.on('listening', () => {
const address = client.address()
console.log(`UDP Client: listening on ${address.address} : ${address.port}`)
})
// Handle an incoming message over the UDP from the local application.
client.on('message', (message, remote) => {
console.log(`UDP Client: message Rx ${remote.address} : ${remote.port} - ${message}`)
const reply = message.toString('utf8')
socket.emit('commandReply', reply)
client.close()
})
client.on('UDP Client: close', () => {
console.log('Closed')
})
client.on('UDP Client: error', (err) => {
console.log(`Error: ${err}`)
})
})
}
export default handleCommand
| JavaScript | 0.000001 | @@ -127,53 +127,10 @@
art'
-, socket)%0A socket.on('prime', (data) =%3E %7B%0A
+)%0A
co
@@ -168,18 +168,16 @@
a%7D%60)%0A%0A
-
-
// Info
@@ -220,18 +220,16 @@
via UDP%0A
-
const
@@ -241,18 +241,16 @@
= 12345%0A
-
const
@@ -272,18 +272,16 @@
.7.2'%0A
-
-
const bu
@@ -305,18 +305,16 @@
(data)%0A%0A
-
const
@@ -347,26 +347,24 @@
t('udp4')%0A
-
-
client.send(
@@ -415,26 +415,24 @@
bytes) =%3E %7B%0A
-
if (err)
@@ -442,26 +442,24 @@
row err%0A
-
console.log(
@@ -497,26 +497,22 @@
PORT%7D%60)%0A
-
%7D)%0A%0A
-
client
@@ -536,26 +536,24 @@
() =%3E %7B%0A
-
const addres
@@ -573,18 +573,16 @@
dress()%0A
-
cons
@@ -654,25 +654,21 @@
port%7D%60)%0A
-
%7D)%0A
-
// Han
@@ -732,18 +732,16 @@
cation.%0A
-
client
@@ -774,26 +774,24 @@
emote) =%3E %7B%0A
-
console.
@@ -869,26 +869,24 @@
age%7D%60)%0A%0A
-
const reply
@@ -912,18 +912,16 @@
'utf8')%0A
-
sock
@@ -956,18 +956,16 @@
y)%0A%0A
-
client.c
@@ -973,24 +973,20 @@
ose()%0A
-
-
%7D)%0A%0A
-
client
@@ -1014,34 +1014,32 @@
e', () =%3E %7B%0A
-
console.log('Clo
@@ -1046,23 +1046,19 @@
sed')%0A
-
-
%7D)%0A
-
client
@@ -1097,18 +1097,16 @@
%3E %7B%0A
-
console.
@@ -1130,15 +1130,8 @@
%7D%60)%0A
- %7D)%0A
%7D)
|
b132ce780e1038cb8ca2a4ff69b0fa1319a95d2b | Introduce 10ms timeout on webview inapp dismiss | Sources/WonderPush/Resources/javascript/webViewBridgeJavascriptFileToInject.js | Sources/WonderPush/Resources/javascript/webViewBridgeJavascriptFileToInject.js | (function() {
var identifierCounter = 0;
var generateIdentifier = function() {
return ""+(+new Date())+":"+(identifierCounter++);
};
window.WonderPushInAppSDK = new Proxy({}, new function() {
this.get = function(target, prop, receiver) {
if (this.hasOwnProperty(prop)) return this[prop];
return function() {
var callId = generateIdentifier();
var message = {
method : prop,
args: Array.from(arguments),
callId: callId,
};
var promise = new Promise(function(res, rej) {
window.WonderPushInAppSDK.callIdToPromise[callId] = {resolve:res, reject:rej};
});
webkit.messageHandlers.WonderPushInAppSDK.postMessage(message);
return promise;
};
}.bind(this);
this.callIdToPromise = {};
this.resolve = function(result, callId) {
var promise = window.WonderPushInAppSDK.callIdToPromise[callId];
if (!promise || !promise.resolve) return;
promise.resolve(result);
delete window.WonderPushInAppSDK.callIdToPromise[callId];
};
this.reject = function(error, callId) {
var promise = window.WonderPushInAppSDK.callIdToPromise[callId];
if (!promise || !promise.reject) return;
promise.reject(error);
delete window.WonderPushInAppSDK.callIdToPromise[callId];
};
});
// Executed when the window is loaded
var onload = function() {
// Register event listeners on data-wonderpush-* elements
var keys = [ // Order matters: we try to dismiss last
"wonderpushButtonLabel",
"wonderpushRemoveAllTags", // remove tags before adding them
"wonderpushRemoveTag",
"wonderpushAddTag",
"wonderpushUnsubscribeFromNotifications", // unsubscribe before subscribe
"wonderpushSubscribeToNotifications",
"wonderpushTrackEvent",
"wonderpushTriggerLocationPrompt",
"wonderpushOpenAppRating",
"wonderpushOpenDeepLink", // move somewhere else last
"wonderpushOpenExternalUrl",
"wonderpushDismiss",
];
document.querySelectorAll('*').forEach(function(elt) {
if (!elt.dataset) return;
keys.forEach(function (key) {
if (!(key in elt.dataset)) return;
var val = elt.dataset[key];
var fn;
switch (key) {
case "wonderpushAddTag":
fn = function () {
window.WonderPushInAppSDK.addTag(val);
};
break;
case "wonderpushButtonLabel":
fn = function () {
window.WonderPushInAppSDK.trackClick(val);
};
break;
case "wonderpushDismiss":
fn = function () {
window.WonderPushInAppSDK.dismiss();
};
break;
case "wonderpushOpenDeepLink":
fn = function () {
window.WonderPushInAppSDK.openDeepLink(val);
};
break;
case "wonderpushOpenExternalUrl":
fn = function () {
window.WonderPushInAppSDK.openExternalUrl(val);
};
break;
case "wonderpushRemoveAllTags":
fn = function () {
window.WonderPushInAppSDK.removeAllTags();
};
break;
case "wonderpushRemoveTag":
fn = function () {
window.WonderPushInAppSDK.removeTag(val);
};
break;
case "wonderpushSubscribeToNotifications":
fn = function () {
window.WonderPushInAppSDK.subscribeToNotifications();
};
break;
case "wonderpushTrackEvent":
fn = function () {
window.WonderPushInAppSDK.trackEvent(val);
};
break;
case "wonderpushTriggerLocationPrompt":
fn = function () {
window.WonderPushInAppSDK.triggerLocationPrompt();
};
break;
case "wonderpushUnsubscribeFromNotifications":
fn = function () {
window.WonderPushInAppSDK.unsubscribeFromNotifications();
};
break;
case "wonderpushOpenAppRating":
fn = function () {
window.WonderPushInAppSDK.openAppRating();
};
break;
}
if (fn) {
elt.addEventListener('click', fn);
}
});
});
}
if (document.readyState === "complete") {
onload();
} else {
window.addEventListener("load", onload);
}
})();
| JavaScript | 0 | @@ -753,32 +753,76 @@
%7D);%0A
+ var post = function() %7B%0A
@@ -885,16 +885,158 @@
ssage);%0A
+ %7D;%0A // delay dimiss%0A if (prop === %22dismiss%22) setTimeout(post, 10);%0A else post();%0A
|
1159a107070b75f5981eb20ced8a194d9f442a4f | Fix button colour changing the wrong row when deselecting, Remove console.logs | src/pages/StocktakesPage.js | src/pages/StocktakesPage.js | /* @flow weak */
/**
* OfflineMobile Android Stocktakes Page
* Sustainable Solutions (NZ) Ltd. 2016
*/
import React from 'react';
import {
StyleSheet,
View,
TouchableOpacity,
} from 'react-native';
import {
Cell,
DataTable,
Header,
HeaderCell,
Row,
} from '../widgets/DataTable';
import Icon from 'react-native-vector-icons/Ionicons';
import { generateUUID } from '../database';
import { ListView } from 'realm/react-native';
import { Button } from '../widgets';
import globalStyles from '../globalStyles';
/**
* Renders the page for displaying Stocktakes.
* @prop {Realm} database App wide database.
* @prop {func} navigateTo callBack for navigation stack.
* @state {ListView.DataSource} dataSource DataTable input, used to update rows being rendered.
* @state {Realm.Results} Stocktakes Filtered to have only customer_stocktake.
* @state {string} sortBy Locked to createdDate created date column.
* @state {boolean} isAscending Direction sortBy should sort
* (ascending/descending:true/false).
*/
export class StocktakesPage extends React.Component {
constructor(props) {
super(props);
const dataSource = new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
});
this.state = {
dataSource: dataSource,
stocktakes: props.database.objects('Stocktake'),
sortBy: 'createdDate',
isAscending: false,
deleteSelection: [],
};
this.componentWillMount = this.componentWillMount.bind(this);
this.onDeleteConfirm = this.onDeleteConfirm.bind(this);
this.onDeleteButtonPress = this.onDeleteButtonPress.bind(this);
this.onColumnSort = this.onColumnSort.bind(this);
this.renderHeader = this.renderHeader.bind(this);
this.renderRow = this.renderRow.bind(this);
this.refreshData = this.refreshData.bind(this);
this.onNewStockTake = this.onNewStockTake.bind(this);
}
componentWillMount() {
this.refreshData();
}
onColumnSort() {
this.setState({
isAscending: !this.state.isAscending,
});
this.refreshData();
}
onNewStockTake() {
this.props.database.write(() => {
this.props.database.create('Stocktake', {
id: generateUUID(),
name: 'best stocktake',
createdDate: new Date(),
status: 'new',
comment: 'Testing StocktakesPage',
serialNumber: '1337',
lines: [],
});
});
this.props.navigateTo('stocktakeManager', 'New StockTake');
}
/**
* Takes an array of stocktakes and deletes them from database
* @param {array} stocktakes the array of stocktakes to delete
*/
onDeleteConfirm(deleteSelection) {
const { database, stocktakes } = this.state;
database.write(() => {
for (const stocktakeId of deleteSelection) {
const stocktake = stocktakes.filter('id == ${0}', stocktakeId)[0];
database.delete('Stocktake', stocktake);
}
});
this.refreshData();
}
onDeleteButtonPress(stocktake) {
const { deleteSelection } = this.state;
console.log(deleteSelection.indexOf(stocktake.id) >= 0);
if (deleteSelection.indexOf(stocktake.id) >= 0) {
deleteSelection.splice(deleteSelection.indexOf(stocktake.id) - 1, 1);
} else {
deleteSelection.push(stocktake.id);
console.log(this.state.deleteSelection.length);
}
this.refreshData();
}
/**
* Updates data within dataSource in state according to the state of sortBy and
* isAscending. This sort by on this page is always 'createdDate'.
*/
refreshData() {
const { stocktakes, sortBy, dataSource, isAscending } = this.state;
const data = stocktakes.sorted(sortBy, !isAscending); // 2nd arg: reverse sort order if true
this.setState({ dataSource: dataSource.cloneWithRows(data) });
}
renderHeader() {
return (
<Header style={globalStyles.dataTableHeader}>
<HeaderCell
style={globalStyles.dataTableHeaderCell}
textStyle={globalStyles.dataTableText}
width={COLUMN_WIDTHS[0]}
text={'DESCRIPTION'}
/>
<HeaderCell
style={globalStyles.dataTableHeaderCell}
textStyle={globalStyles.dataTableText}
width={COLUMN_WIDTHS[1]}
onPress={() => this.onColumnSort()}
isAscending={this.state.isAscending}
isSelected={this.state.sortBy === 'createdDate'}
text={'CREATED DATE'}
/>
<HeaderCell
style={globalStyles.dataTableHeaderCell}
textStyle={globalStyles.dataTableText}
width={COLUMN_WIDTHS[2]}
text={'STATUS'}
/>
<HeaderCell
style={[
globalStyles.dataTableHeaderCell,
localStyles.rightMostCell,
localStyles.deleteCell,
]}
textStyle={globalStyles.dataTableText}
width={COLUMN_WIDTHS[3]}
text={'DELETE'}
/>
</Header>
);
}
renderRow(stocktake) {
return (
<Row
style={globalStyles.dataTableRow}
onPress={() => this.props.navigateTo('stocktakeManager', 'Create Stocktake')}
>
<Cell
style={globalStyles.dataTableCell}
textStyle={globalStyles.dataTableText}
width={COLUMN_WIDTHS[0]}
>
{stocktake.comment}
</Cell>
<Cell
style={globalStyles.dataTableCell}
textStyle={globalStyles.dataTableText}
width={COLUMN_WIDTHS[1]}
>
{stocktake.createdDate.toISOString()}
</Cell>
<Cell
style={globalStyles.dataTableCell}
textStyle={globalStyles.dataTableText}
width={COLUMN_WIDTHS[2]}
>
{stocktake.status}
</Cell>
<TouchableOpacity
style={{ flex: COLUMN_WIDTHS[3] }}
onPress={() => this.onDeleteButtonPress(stocktake)}
>
<Cell
style={[globalStyles.dataTableCell, localStyles.rightMostCell, localStyles.deleteCell]}
textStyle={globalStyles.dataTableText}
width={COLUMN_WIDTHS[3]}
>
<Icon name="md-remove-circle" size={15} color="grey" />
</Cell>
</TouchableOpacity>
</Row>
);
}
render() {
return (
<View style={globalStyles.pageContentContainer}>
<View style={globalStyles.container}>
<View style={globalStyles.horizontalContainer}>
<Button
style={globalStyles.button}
textStyle={globalStyles.buttonText}
text="New StockTake"
onPress={this.onNewStockTake}
/>
</View>
<DataTable
style={globalStyles.dataTable}
listViewStyle={localStyles.listView}
dataSource={this.state.dataSource}
renderRow={this.renderRow}
renderHeader={this.renderHeader}
/>
</View>
</View>
);
}
}
StocktakesPage.propTypes = {
database: React.PropTypes.object,
navigateTo: React.PropTypes.func.isRequired,
};
const COLUMN_WIDTHS = [6, 2, 2, 1];
const localStyles = StyleSheet.create({
listView: {
flex: 1,
},
deleteCell: {
alignItems: 'center',
},
rightMostCell: {
borderRightWidth: 0,
},
dataTable: {
flex: 1,
},
});
| JavaScript | 0 | @@ -3135,69 +3135,8 @@
te;%0A
- console.log(deleteSelection.indexOf(stocktake.id) %3E= 0);%0A
@@ -3255,12 +3255,8 @@
.id)
- - 1
, 1)
@@ -3316,62 +3316,8 @@
d);%0A
- console.log(this.state.deleteSelection.length);%0A
|
7021bcf84ab33d6884788dbb158a1a05fa908ccd | disable linking packages when running in builder mode | packages/core/lib/builder/installPackages.js | packages/core/lib/builder/installPackages.js | const getPackages = require("zero-dep-tree-js").getPackages;
const fs = require("fs");
const os = require("os");
var glob = require("fast-glob");
const deepmerge = require("deepmerge");
var { spawn } = require("child_process");
const commonDeps = require("zero-common-deps");
var path = require("path");
const debug = require("debug")("core");
var firstRun = true;
//process.on('unhandledRejection', up => { throw up });
const babelConfig = {
plugins: [
"babel-plugin-react-require",
["@babel/plugin-transform-runtime"],
[
"@babel/plugin-proposal-class-properties",
{
loose: true
}
]
]
};
function runYarn(cwd, args, resolveOutput) {
const isWin = os.platform() === "win32";
var yarnPath = require.resolve("yarn/bin/yarn");
if (isWin) {
yarnPath = path.join(path.dirname(yarnPath), "yarn.cmd");
}
return new Promise((resolve, reject) => {
debug("yarn", yarnPath, args);
var child = spawn(yarnPath, args || [], {
cwd: cwd,
stdio: !resolveOutput ? "inherit" : undefined
});
if (isWin) {
// a windows bug. need to press enter sometimes
process.stdin.write("\n");
process.stdin.end();
}
var output = "";
if (resolveOutput) {
child.stdout.on("data", data => {
output += data;
});
}
child.on("exit", code => {
debug("yarn completed");
resolve(output);
});
});
}
async function getNPMVersion(pkgName) {
try {
var json = await runYarn(
process.env.BUILDPATH,
["info", pkgName, "version", "--json"],
true
);
return JSON.parse(json).data;
} catch (e) {
debug(
`[yarn ${pkgName} version]`,
"couldn't fetch package info. Returning `latest`"
);
return "latest";
}
}
async function getFiles(baseSrc) {
return glob(path.join(baseSrc, "/**"), { onlyFiles: true });
}
function installPackages(buildPath, filterFiles) {
return new Promise(async (resolve, reject) => {
var files = await getFiles(buildPath);
files = files.filter(f => {
f = path.relative(process.env.BUILDPATH, f);
return (
f.indexOf("node_modules") === -1 && f.indexOf("zero-builds") === -1
);
});
// debug("files", files)
var deps = [];
var pkgJsonChanged = false;
// build a list of packages required by all js files
files.forEach(file => {
if (
filterFiles &&
filterFiles.length > 0 &&
filterFiles.indexOf(file) === -1
) {
debug("konan skip", file);
return;
}
// if pkg.json is changed
if (
path.relative(process.env.BUILDPATH, file).toLowerCase() ===
"package.json"
) {
pkgJsonChanged = true;
}
// extract imports
deps = deps.concat(getPackages(file));
});
deps = deps.filter(function(item, pos) {
return deps.indexOf(item) == pos;
});
// check if these deps are already installed
var pkgjsonPath = path.join(buildPath, "/package.json");
var allInstalled = false;
if (fs.existsSync(pkgjsonPath)) {
try {
var pkg = require(pkgjsonPath);
allInstalled = true; // we assume all is installed
deps.forEach(dep => {
if (!pkg || !pkg.dependencies || !pkg.dependencies[dep]) {
allInstalled = false; //didn't find this dep in there.
}
});
} catch (e) {}
}
if (!allInstalled || firstRun || pkgJsonChanged) {
debug("yarn install hit", !!allInstalled, !!firstRun, !!pkgJsonChanged);
// we must run npm i on first boot,
// so we are sure pkg.json === node_modules
firstRun = false;
// now that we have a list. npm install them in our build folder
await writePackageJSON(buildPath, deps);
debug("installing", deps);
runYarn(buildPath, ["install"]).then(() => {
// installed
debug("Pkgs installed successfully.");
resolve(deps);
});
} else {
resolve(deps);
}
});
}
async function writePackageJSON(buildPath, deps) {
// first load current package.json if present
var pkgjsonPath = path.join(buildPath, "/package.json");
var newDepsFound = false;
var pkg = {
name: "zero-app",
private: true,
scripts: {
start: "zero"
},
dependencies: {}
};
if (fs.existsSync(pkgjsonPath)) {
try {
pkg = require(pkgjsonPath);
} catch (e) {}
}
// the base packages required by zero
var depsJson = commonDeps.dependenciesWithLocalPaths();
if (pkg.dependencies) {
Object.keys(depsJson).forEach(key => {
pkg.dependencies[key] = depsJson[key];
});
} else {
pkg.dependencies = depsJson;
}
// append user's imported packages (only if not already defined in package.json)
for (var i in deps) {
const dep = deps[i];
if (!pkg.dependencies[dep]) {
newDepsFound = true;
pkg.dependencies[dep] = await getNPMVersion(dep);
}
}
// write a pkg.json into tmp buildpath
fs.writeFileSync(
path.join(buildPath, "/package.json"),
JSON.stringify(pkg, null, 2),
"utf8"
);
// // merge babelrc with user's babelrc (if present in user project)
var babelPath = path.join(buildPath, "/.babelrc");
var babelSrcPath = path.join(process.env.SOURCEPATH, "/.babelrc");
var finalBabelConfig = {};
if (fs.existsSync(babelSrcPath)) {
try {
var userBabelConfig = JSON.parse(fs.readFileSync(babelSrcPath));
finalBabelConfig = deepmerge(babelConfig, userBabelConfig);
} catch (e) {
// couldn't read the file
finalBabelConfig = babelConfig;
}
} else {
finalBabelConfig = babelConfig;
}
//console.log(JSON.stringify(finalBabelConfig, null, 2))
fs.writeFileSync(
babelPath,
JSON.stringify(finalBabelConfig, null, 2),
"utf8"
);
// also save any newfound deps into user's pkg.json
// in sourcepath. But minus our hardcoded depsJson
if (newDepsFound) {
Object.keys(depsJson).forEach(key => {
delete pkg.dependencies[key];
});
console.log(`\x1b[2mUpdating package.json\x1b[0m\n`);
fs.writeFileSync(
path.join(process.env.SOURCEPATH, "/package.json"),
JSON.stringify(pkg, null, 2),
"utf8"
);
}
}
module.exports = installPackages;
| JavaScript | 0 | @@ -4495,16 +4495,76 @@
psJson =
+ process.env.ISBUILDER%0A ? commonDeps.dependencies()%0A :
commonD
|
715d7c69eae6af104b672cd85672f034ae0ea900 | Fix typos in orderedmap docstrings | src/util/orderedmap.js | src/util/orderedmap.js | // ;; Persistent data structure representing an ordered mapping from
// strings to values, with some convenient update methods.
export class OrderedMap {
constructor(content) {
this.content = content
}
find(key) {
for (let i = 0; i < this.content.length; i += 2)
if (this.content[i] == key) return i
return -1
}
// :: (string) → ?any
// Retrieve the value stored under `key`, or return undefined when
// no such key exists.
get(key) {
let found = this.find(key)
return found == -1 ? undefined : this.content[found + 1]
}
// :: (string, any, ?string) → OrderedMap
// Create a new map by replacing the value of `key` with a new
// value, or adding a binding to the end of the map. If `newKey` is
// given, the key of the binding will be replaced with that key.
update(key, value, newKey) {
let self = newKey && newKey != key ? this.remove(newKey) : this
let found = self.find(key), content = self.content.slice()
if (found == -1) {
content.push(newKey || key, value)
} else {
content[found + 1] = value
if (newKey) content[found] = newKey
}
return new OrderedMap(content)
}
// :: (string) → OrderedMap
// Return a map with the given key removed, if it existed.
remove(key) {
let found = this.find(key)
if (found == -1) return this
let content = this.content.slice()
content.splice(found, 2)
return new OrderedMap(content)
}
// :: (string, any) → OrderedMap
// Add a new key to the start of the map.
addToStart(key, value) {
return new OrderedMap([key, value].concat(this.remove(key).content))
}
// :: (string, any) → OrderedMap
// Add a new key to the end of the map.
addToEnd(key, value) {
let content = this.remove(key).content.slice()
content.push(key, value)
return new OrderedMap(content)
}
// :: ((key: string, value: any))
// Call the given function for each key/value pair in the map, in
// order.
forEach(f) {
for (let i = 0; i < this.content.length; i += 2)
f(this.content[i], this.content[i + 1])
}
// :: (union<Object, OrderedMap) → OrderedMap
// Create a new map by prepending the keys in this map that don't
// appear in `map` before the keys in `map`.
prepend(map) {
if (!map.size) return this
map = OrderedMap.from(map)
return new OrderedMap(map.content.concat(this.subtract(map).content))
}
// :: (union<Object, OrderedMap) → OrderedMap
// Create a new map by appending the keys in this map that don't
// appear in `map` after the keys in `map`.
append(map) {
if (!map.size) return this
map = OrderedMap.from(map)
return new OrderedMap(this.subtract(map).content.concat(map.content))
}
// :: (union<Object, OrderedMap) → OrderedMap
// Create a map containing all the keys in this map that don't
// appear in `map`.
subtract(map) {
let result = this
OrderedMap.from(map).forEach(key => result = result.remove(key))
return result
}
// :: number
// The amount of keys in this map.
get size() {
return this.content.length >> 1
}
// :: (?union<Object, OrderedMap) → OrderedMap
// Return a map with the given content. If null, create an empty
// map. If given an ordered map, return that map itself. If given an
// object, create a map from the object's properties.
static from(value) {
if (value instanceof OrderedMap) return value
let content = []
if (value) for (let prop in value) content.push(prop, value[prop])
return new OrderedMap(content)
}
}
| JavaScript | 0.000432 | @@ -2112,32 +2112,33 @@
ject, OrderedMap
+%3E
) %E2%86%92 OrderedMap%0A
@@ -2128,32 +2128,32 @@
%3E) %E2%86%92 OrderedMap%0A
-
// Create a ne
@@ -2434,32 +2434,33 @@
ject, OrderedMap
+%3E
) %E2%86%92 OrderedMap%0A
@@ -2753,32 +2753,33 @@
ject, OrderedMap
+%3E
) %E2%86%92 OrderedMap%0A
@@ -3100,24 +3100,24 @@
h %3E%3E 1%0A %7D%0A%0A
-
// :: (?un
@@ -3138,16 +3138,17 @@
deredMap
+%3E
) %E2%86%92 Orde
|
61b795e5b610fe608701c620fb816481e2bb99a2 | Add element type to prop-types (#3959) | definitions/npm/prop-types_v15.x.x/flow_v0.104.x-/prop-types_v15.x.x.js | definitions/npm/prop-types_v15.x.x/flow_v0.104.x-/prop-types_v15.x.x.js | type $npm$propTypes$ReactPropsCheckType = (
props: any,
propName: string,
componentName: string,
href?: string
) => ?Error;
// Copied from: https://github.com/facebook/flow/blob/0938da8d7293d0077fbe95c3a3e0eebadb57b012/lib/react.js#L433-L449
declare module 'prop-types' {
declare var array: React$PropType$Primitive<Array<any>>;
declare var bool: React$PropType$Primitive<boolean>;
declare var func: React$PropType$Primitive<(...a: Array<any>) => mixed>;
declare var number: React$PropType$Primitive<number>;
declare var object: React$PropType$Primitive<{ +[string]: mixed, ... }>;
declare var string: React$PropType$Primitive<string>;
declare var symbol: React$PropType$Primitive<Symbol>;
declare var any: React$PropType$Primitive<any>;
declare var arrayOf: React$PropType$ArrayOf;
declare var element: React$PropType$Primitive<any>;
declare var instanceOf: React$PropType$InstanceOf;
declare var node: React$PropType$Primitive<any>;
declare var objectOf: React$PropType$ObjectOf;
declare var oneOf: React$PropType$OneOf;
declare var oneOfType: React$PropType$OneOfType;
declare var shape: React$PropType$Shape;
declare function checkPropTypes<V>(
propTypes: { [key: $Keys<V>]: $npm$propTypes$ReactPropsCheckType, ... },
values: V,
location: string,
componentName: string,
getStack: ?() => ?string
): void;
}
| JavaScript | 0.000007 | @@ -849,32 +849,90 @@
Primitive%3Cany%3E;%0A
+ declare var elementType: React$PropType$Primitive%3Cany%3E;%0A
declare var in
|
9201111222a31994f0a600cbd0aa933a8966648e | Add use of actions in StocktakesPage | src/pages/StocktakesPage.js | src/pages/StocktakesPage.js | /* eslint-disable import/prefer-default-export */
/* eslint-disable react/forbid-prop-types */
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
import React, { useCallback } from 'react';
import PropTypes from 'prop-types';
import { View } from 'react-native';
import { UIDatabase } from '../database';
import Settings from '../settings/MobileAppSettings';
import { MODAL_KEYS, getAllPrograms } from '../utilities';
import { usePageReducer, useSyncListener, useNavigationFocus } from '../hooks';
import { getItemLayout, recordKeyExtractor } from './dataTableUtilities';
import { PageButton, DataTablePageView, SearchBar, ToggleBar } from '../widgets';
import { BottomConfirmModal, DataTablePageModal } from '../widgets/modals';
import { DataTable, DataTableHeaderRow, DataTableRow } from '../widgets/DataTable';
import { buttonStrings, modalStrings } from '../localization';
import globalStyles, { newPageStyles } from '../globalStyles';
import {
gotoStocktakeManagePage,
createStocktake,
gotoStocktakeEditPage,
} from '../navigation/actions';
const stateInitialiser = () => {
const backingData = UIDatabase.objects('Stocktake');
return {
backingData,
data: backingData.sorted('createdDate', true).slice(),
keyExtractor: recordKeyExtractor,
dataState: new Map(),
searchTerm: '',
filterDataKeys: ['name'],
sortBy: 'createdDate',
isAscending: false,
modalKey: '',
hasSelection: false,
usingPrograms: getAllPrograms(Settings, UIDatabase).length > 0,
};
};
export const StocktakesPage = ({ routeName, currentUser, dispatch: reduxDispatch, navigation }) => {
const [state, dispatch, instantDebouncedDispatch] = usePageReducer(
routeName,
{},
stateInitialiser
);
const {
data,
dataState,
sortBy,
isAscending,
searchTerm,
modalKey,
hasSelection,
usingPrograms,
keyExtractor,
columns,
PageActions,
} = state;
const refreshCallback = useCallback(() => dispatch(PageActions.refreshData()), []);
// Listen to sync changing stocktake data - refresh if there are any.
useSyncListener(refreshCallback, ['Stocktake']);
// Listen to navigation focusing this page - fresh if so.
useNavigationFocus(refreshCallback, navigation);
const onRowPress = useCallback(stocktake => reduxDispatch(gotoStocktakeEditPage(stocktake)), []);
const onFilterData = value => dispatch(PageActions.filterData(value));
const onCancelDelete = () => dispatch(PageActions.deselectAll());
const onConfirmDelete = () => dispatch(PageActions.deleteStocktakes());
const onCloseModal = () => dispatch(PageActions.closeModal());
const onNewStocktake = () => {
if (usingPrograms) return dispatch(PageActions.openModal(MODAL_KEYS.PROGRAM_STOCKTAKE));
return reduxDispatch(gotoStocktakeManagePage({ stocktakeName: '' }));
};
const getAction = (colKey, propName) => {
switch (colKey) {
case 'remove':
if (propName === 'onCheckAction') return PageActions.selectRow;
return PageActions.deselectRow;
default:
return null;
}
};
const getModalOnSelect = () => {
switch (modalKey) {
case MODAL_KEYS.PROGRAM_STOCKTAKE:
return ({ stocktakeName, program }) => {
reduxDispatch(createStocktake({ program, stocktakeName, currentUser }));
onCloseModal();
};
default:
return null;
}
};
const renderRow = useCallback(
listItem => {
const { item, index } = listItem;
const rowKey = keyExtractor(item);
return (
<DataTableRow
rowData={data[index]}
rowState={dataState.get(rowKey)}
rowKey={rowKey}
columns={columns}
dispatch={dispatch}
getAction={getAction}
onPress={onRowPress}
rowIndex={index}
/>
);
},
[data, dataState]
);
const renderHeader = useCallback(
() => (
<DataTableHeaderRow
columns={columns}
dispatch={instantDebouncedDispatch}
sortAction={PageActions.sortData}
isAscending={isAscending}
sortBy={sortBy}
/>
),
[sortBy, isAscending]
);
const PageButtons = useCallback(() => {
const { verticalContainer, topButton } = globalStyles;
return (
<View style={verticalContainer}>
<PageButton style={topButton} text={buttonStrings.new_stocktake} onPress={onNewStocktake} />
</View>
);
}, []);
const renderToggleBar = () => (
<ToggleBar
toggles={[
{
text: buttonStrings.current,
onPress: () => {},
isOn: true,
},
{
text: buttonStrings.past,
onPress: () => {},
isOn: !false,
},
]}
/>
);
const {
newPageTopSectionContainer,
newPageTopLeftSectionContainer,
newPageTopRightSectionContainer,
} = newPageStyles;
return (
<DataTablePageView>
<View style={newPageTopSectionContainer}>
<View style={newPageTopLeftSectionContainer}>
{renderToggleBar()}
<SearchBar onChangeText={onFilterData} value={searchTerm} />
</View>
<View style={newPageTopRightSectionContainer}>
<PageButtons />
</View>
</View>
<DataTable
data={data}
extraData={dataState}
renderRow={renderRow}
renderHeader={renderHeader}
keyExtractor={keyExtractor}
getItemLayout={getItemLayout}
/>
<BottomConfirmModal
isOpen={hasSelection}
questionText={modalStrings.remove_these_items}
onCancel={onCancelDelete}
onConfirm={onConfirmDelete}
confirmText={modalStrings.remove}
/>
<DataTablePageModal
fullScreen={false}
isOpen={!!modalKey}
modalKey={modalKey}
onClose={onCloseModal}
onSelect={getModalOnSelect()}
dispatch={dispatch}
/>
</DataTablePageView>
);
};
StocktakesPage.propTypes = {
routeName: PropTypes.string.isRequired,
dispatch: PropTypes.func.isRequired,
currentUser: PropTypes.object.isRequired,
navigation: PropTypes.object.isRequired,
};
| JavaScript | 0 | @@ -1204,16 +1204,68 @@
kingData
+%0A .filtered('status != $0', 'finalised')%0A
.sorted(
@@ -1284,16 +1284,23 @@
', true)
+%0A
.slice()
@@ -1986,16 +1986,35 @@
ctions,%0A
+ showFinalised,%0A
%7D = st
@@ -4674,34 +4674,72 @@
onPress: () =%3E
-%7B%7D
+dispatch(PageActions.showNotFinalised())
,%0A isOn
@@ -4740,20 +4740,30 @@
isOn:
-true
+!showFinalised
,%0A
@@ -4838,18 +4838,53 @@
: () =%3E
-%7B%7D
+dispatch(PageActions.showFinalised())
,%0A
@@ -4897,14 +4897,21 @@
On:
-!f
+showFin
al
+i
se
+d
,%0A
|
f7e7301641dc9889c93c448f6ad86bf594119a19 | Fix custom select | source/assets/javascripts/locastyle/_custom-fields.js | source/assets/javascripts/locastyle/_custom-fields.js | var locastyle = locastyle || {};
locastyle.customFields = (function() {
'use strict';
function init() {
findFields();
bindRemoveCustomClass();
}
function findFields(){
$('.ls-custom').find(':input').not('.ls-input-original').each(function(index, field){
if($(field).eq(0).attr('class') !== undefined){
$(field).wrap( '<div class="ls-field-container-' + $(field)[0].type + ' ' + $(field).eq(0).attr('class') + ' " />' );
}else{
$(field).wrap( '<div class="ls-field-container-' + $(field)[0].type + ' " />' );
}
setSize($(field))
if($(field)[0].type === 'select-one'){ customSelect($(field)); }
if($(field)[0].type === 'checkbox'){ customCheckbox($(field)); checkInputs($(field))}
if($(field)[0].type === 'radio'){ customRadio($(field)); checkInputs($(field)) }
})
}
function setSize($field){
$(".ls-field-container-" + $field[0].type ).css( { 'width': $field.width() } );
}
function fieldSpan($field){
$('<span class="ls-field-custom-'+ $field[0].type + '"></span>').insertBefore($field[0]);
}
function labelField($field){
return $field.siblings('.ls-field-custom-'+ $field[0].type);
}
function customSelect($field){
var selectText = $field.children('option:selected').eq(0).text();
$('<span class="ls-field-custom-'+ $field[0].type +'"> ' + selectText + ' </span>').insertBefore($field[0]);
var $labelField = labelField($field)
$field.on('change', function(){
$labelField.text($field.find('option:selected').text())
})
}
function customCheckbox($field){
fieldSpan($field);
bindCustomCheckbox($field)
}
function bindCustomCheckbox($field){
var $labelField = labelField($field)
$field.on('click', function(){
$field.is(":checked") ? $labelField.addClass("checked") : $labelField.removeClass("checked")
})
}
function bindRemoveCustomClass(){
$('.ls-input-original').on('click', function(){
$('.ls-field-custom-radio').removeClass("checked");
});
}
function customRadio($field){
fieldSpan($field);
bindCustomRadio($field);
}
function bindCustomRadio($field){
$field.on('click', function(){
uncheckInputs($field);
checkInputs($field)
});
}
function uncheckInputs($field){
var group = $field.attr("name");
$field.parents().find('.ls-field-custom-radio').removeClass("checked");
}
function checkInputs($field){
var $labelField = labelField($field);
if($field.is(":checked")){
$labelField.addClass("checked")
}
}
return {
init: init
}
}());
| JavaScript | 0.000001 | @@ -1190,32 +1190,44 @@
%5B0%5D.type);%0A %7D%0A%0A
+ // Select%0A
function custo
@@ -1235,32 +1235,32 @@
Select($field)%7B%0A
-
var selectTe
@@ -1426,16 +1426,87 @@
ld%5B0%5D);%0A
+ bindCustomSelect($field)%0A %7D%0A%0A function bindCustomSelect($field)%7B%0A
var
@@ -1640,32 +1640,46 @@
())%0A %7D)%0A %7D%0A%0A
+ // Checkbox%0A
function custo
@@ -1985,167 +1985,18 @@
%7D%0A
-%0A
-function bindRemoveCustomClass()%7B%0A $('.ls-input-original').on('click', function()%7B%0A $('.ls-field-custom-radio').removeClass(%22checked%22);%0A %7D);%0A %7D%0A
+// Radio
%0A f
@@ -2521,21 +2521,181 @@
)%0A %7D%0A
-
%7D%0A%0A
+ function bindRemoveCustomClass()%7B%0A $('.ls-input-original').on('click', function()%7B%0A $('.ls-field-custom-radio').removeClass(%22checked%22);%0A %7D);%0A %7D%0A%0A%0A
return
|
48fa46e2351351304d38581ea256ba0e282612f2 | Update EmptyMJMLError for empty body | packages/mjml-core/src/parsers/document.js | packages/mjml-core/src/parsers/document.js | import { ParseError, EmptyMJMLError, NullElementError } from '../Error'
import compact from 'lodash/compact'
import dom from '../helpers/dom'
import each from 'lodash/each'
import filter from 'lodash/filter'
import { endingTags } from '../MJMLElementsCollection'
import MJMLHeadElements from '../MJMLHead'
import warning from 'warning'
const regexTag = tag => new RegExp(`<${tag}([^>]*)>([^]*?)</${tag}>`, 'gmi')
/**
* Avoid htmlparser to parse ending tags
*/
const safeEndingTags = content => {
const regexpBody = regexTag('mj-body')
let bodyContent = content.match(regexpBody)
if (!bodyContent) {
return content
}
bodyContent = bodyContent[0].replace('$', '$') // $ is a protected chars for regexp... avoid issue with duplicate content
endingTags.forEach(tag => {
bodyContent = bodyContent.replace(regexTag(tag), dom.replaceContentByCdata(tag))
})
return content.replace(regexpBody, bodyContent)
}
/**
* converts MJML body into a JSON representation
*/
const mjmlElementParser = (elem, content) => {
if (!elem) {
throw new NullElementError('Null element found in mjmlElementParser')
}
const findLine = content.substr(0, elem.startIndex).match(/\n/g)
const lineNumber = findLine ? findLine.length + 1 : 1
const tagName = elem.tagName.toLowerCase()
const attributes = dom.getAttributes(elem)
const element = { tagName, attributes, lineNumber }
if (endingTags.indexOf(tagName) !== -1) {
const $local = dom.parseXML(elem)
element.content = $local(tagName).html().trim()
} else {
const children = dom.getChildren(elem)
element.children = children ? compact(filter(children, child => child.tagName).map(child => mjmlElementParser(child, content))) : []
}
return element
}
const parseHead = (head, attributes) => {
const $container = dom.parseHTML(attributes.container)
each(compact(filter(dom.getChildren(head), child => child.tagName)), element => {
const handler = MJMLHeadElements[element.tagName.toLowerCase()]
if (handler) {
handler(element, { $container, ...attributes })
} else {
warning(false, `No handler found for: ${element.tagName}, in mj-head, skipping it`)
}
})
attributes.container = dom.getHTML($container)
}
/**
* Import an html document containing some mjml
* returns JSON
* - container: the mjml container
* - mjml: a json representation of the mjml
*/
const documentParser = (content, attributes) => {
const safeContent = safeEndingTags(content)
let body
let head
try {
const $ = dom.parseXML(safeContent)
body = $('mjml > mj-body')
head = $('mjml > mj-head')
if (body.length > 0) {
body = body.children().get(0)
}
} catch (e) {
throw new ParseError('Error while parsing the file')
}
if (!body || body.length < 1) {
throw new EmptyMJMLError('No root "<mjml>" or "<mj-body>" found in the file')
}
if (head && head.length === 1) {
parseHead(head.get(0), attributes)
}
return mjmlElementParser(body, safeContent)
}
export default documentParser
| JavaScript | 0 | @@ -2880,32 +2880,57 @@
ound in the file
+, or %22%3Cmj-body%3E%22 is empty
')%0A %7D%0A%0A if (he
|
22b5bbb4887f756e69e6de58d59bea985637bc1b | Use sane location for config (#3584) | app/config/paths.js | app/config/paths.js | // This module exports paths, names, and other metadata that is referenced
const {homedir} = require('os');
const {app} = require('electron');
const {statSync} = require('fs');
const {resolve, join} = require('path');
const isDev = require('electron-is-dev');
const cfgFile = '.hyper.js';
const defaultCfgFile = 'config-default.js';
const homeDirectory = homedir();
const applicationDirectory = app.getPath('userData');
let cfgPath = join(applicationDirectory, cfgFile);
let cfgDir = applicationDirectory;
const devDir = resolve(__dirname, '../..');
const devCfg = join(devDir, cfgFile);
const defaultCfg = resolve(__dirname, defaultCfgFile);
if (isDev) {
// if a local config file exists, use it
try {
statSync(devCfg);
cfgPath = devCfg;
cfgDir = devDir;
//eslint-disable-next-line no-console
console.log('using config file:', cfgPath);
} catch (err) {
// ignore
}
}
const plugins = resolve(cfgDir, '.hyper_plugins');
const plugs = {
base: plugins,
local: resolve(plugins, 'local'),
cache: resolve(plugins, 'cache')
};
const yarn = resolve(__dirname, '../../bin/yarn-standalone.js');
const cliScriptPath = resolve(__dirname, '../../bin/hyper');
const cliLinkPath = '/usr/local/bin/hyper';
const icon = resolve(__dirname, '../static/icon96x96.png');
const keymapPath = resolve(__dirname, '../keymaps');
const darwinKeys = join(keymapPath, 'darwin.json');
const win32Keys = join(keymapPath, 'win32.json');
const linuxKeys = join(keymapPath, 'linux.json');
const defaultPlatformKeyPath = () => {
switch (process.platform) {
case 'darwin':
return darwinKeys;
case 'win32':
return win32Keys;
case 'linux':
return linuxKeys;
default:
return darwinKeys;
}
};
module.exports = {
cfgDir,
cfgPath,
cfgFile,
defaultCfg,
icon,
defaultPlatformKeyPath,
plugs,
yarn,
cliScriptPath,
cliLinkPath,
homeDirectory
};
| JavaScript | 0 | @@ -365,36 +365,318 @@
);%0A%0A
-const applicationDirectory =
+// If the user defines XDG_CONFIG_HOME they definitely want their config there,%0A// otherwise use the home directory in linux/mac and userdata in windows%0Aconst applicationDirectory =%0A process.env.XDG_CONFIG_HOME !== undefined%0A ? join(process.env.XDG_CONFIG_HOME, 'hyper')%0A : process.platform == 'win32' ?
app
@@ -695,16 +695,28 @@
erData')
+ : homedir()
;%0A%0Alet c
|
69cfc7a7d2916fd73dc43e7d44d09d0d594e0d63 | remove leftover debugger | src/patterns/collapsible.js | src/patterns/collapsible.js | define([
'require',
'lib/jquery',
], function(require) {
var collapsible = {
initContent: function(root) {
debugger;
$(root).find('.collapsible').each(function() {
var $this = $(this),
$data = $this.data('collapsible');
if (!$data) {
var $ctrl = $this.children(':first'),
$panel = $this.children(':gt(0)')
.wrapAll('<div class="panel-content" />')
.parent();
$this.data('collapsible', true);
if ($this.hasClass("closed")) {
$panel.toggle();
} else if (!$this.hasClass("open")) {
$this.addClass("open");
}
$ctrl.bind("click", function() {
if ($this.hasClass('open')) {
$this.removeClass('open');
$this.addClass('closed');
} else {
$this.removeClass('closed');
$this.addClass('open');
}
$panel.slideToggle();
});
}
});
}
}
return collapsible;
});
| JavaScript | 0.000004 | @@ -124,30 +124,8 @@
) %7B%0A
- debugger;%0A
|
8f0a5f2295894d68f38e7d469e3641e70933bdb0 | remove some redundant (now broken) config | webpack/webpack.config.js | webpack/webpack.config.js | const { DefinePlugin, EnvironmentPlugin } = require("webpack");
const path = require("path");
const LessColorLighten = require("less-color-lighten");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const devServer = {
open: false,
overlay: true,
port: 4200,
proxy: { "*": { target: process.env.CLUSTER_URL, secure: false } },
};
if (process.env.NODE_ENV === "testing") {
// Cypress constantly saves fixture files, which causes webpack to detect
// a filechange and rebuild the application. The problem with this is that
// when Cypress goes to load the application again, it may not be ready to
// be served, which causes the test to fail. This delays rebuilding the
// application for a very long time when in a testing environment.
const delayTime = 1000 * 60 * 60 * 5;
devServer.watchOptions = {
aggregateTimeout: delayTime,
poll: delayTime,
};
devServer.proxy = {};
}
const babelLoader = {
loader: "babel-loader",
options: {
cacheDirectory: true,
// babel-loader does not load the projects babel-config by default for some reason.
babelrc: true,
},
};
module.exports = {
devServer,
entry: "./src/js/index.tsx",
output: {
filename: "[name].[hash].js",
chunkFilename: "[name].[chunkhash].bundle.js",
},
optimization: {
runtimeChunk: "single",
splitChunks: {
chunks: "all",
},
},
resolve: {
extensions: [".ts", ".tsx", ".js", ".jsx"],
alias: {
"@styles": path.resolve(__dirname, "../src/styles"),
},
modules: [
// include packages
path.resolve(__dirname, "../packages"),
// load dependencies of main project from within packages
path.resolve(__dirname, "../node_modules"),
// load dependencies of packages themselves
"node_modules",
],
},
node: {
fs: "empty", // Jison-generated files fail otherwise
},
plugins: [
new EnvironmentPlugin(["CLUSTER_URL", "NODE_ENV"]),
new DefinePlugin({
"process.env.LATER_COV": false, // prettycron fails otherwise
}),
new MiniCssExtractPlugin({
filename: "[name].[hash].css",
disable: process.env.NODE_ENV !== "production",
}),
],
module: {
rules: [
{
type: "javascript/auto",
test: /\.mjs$/,
include: /node_modules/,
use: [],
},
{
test: /\.html$/,
use: {
loader: "html-loader",
options: {
attrs: ["link:href"],
},
},
},
{
test: /\.tsx?$/,
exclude: /node_modules/,
use: [
// we currently need babel here, as lingui relies on babel-transforms.
babelLoader,
{
loader: "ts-loader",
options: {
transpileOnly: true,
},
},
],
},
{
test: /\.jsx?$/,
exclude: (absPath) =>
absPath.includes("/node_modules/") &&
// this package needs to be babelized to work in browsers.
!absPath.includes("/objektiv/"),
use: [babelLoader],
},
{
test: /\.(svg|png|jpg|gif|ico|icns)$/,
use: [
{
loader: "file-loader",
options: {
name: "./[hash]-[name].[ext]",
esModule: false,
},
},
{
loader: "image-webpack-loader",
options: {
disable: process.env.NODE_ENV !== "production",
},
},
],
},
{
test: /\.(less|css)$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: "cache-loader",
options: {
cacheDirectory: "./node_modules/.cache/cache-loader",
},
},
{
loader: "css-loader",
options: {
sourceMap: true,
},
},
{
loader: "postcss-loader",
options: {
sourceMap: true,
config: {
path: path.join(__dirname, "../postcss.config.js"),
},
},
},
{
loader: "less-loader",
options: {
sourceMap: true,
plugins: [LessColorLighten],
},
},
],
},
{
test: /\.raml$/,
loader: "raml-validator-loader",
},
],
},
};
| JavaScript | 0 | @@ -3988,38 +3988,24 @@
options: %7B
-%0A
sourceMap:
@@ -4012,130 +4012,8 @@
true
-,%0A config: %7B%0A path: path.join(__dirname, %22../postcss.config.js%22),%0A %7D,%0A
%7D,%0A
|
432fbf5e03c0047bd07862263c47700bc3f73288 | use single quotes | canvid.js | canvid.js | (function(root, factory) {
if (typeof module !== 'undefined' && module.exports) {
module.exports = factory();
} else if (typeof define === 'function' && define.amd) {
define([], factory);
} else {
root.canvid = factory();
}
}(this, function() {
function canvid(params) {
var defaultOptions = {
width : 800,
height : 450,
selector: '.canvid-wrapper'
},
firstPlay = true,
control = {
play: function() {
console.log('Cannot play before images are loaded');
}
},
_opts = merge(defaultOptions, params),
el = typeof _opts.selector === 'string' ? document.querySelector(_opts.selector) : _opts.selector;
if (!el) {
return console.warn('Error. No element found for selector', _opts.selector);
}
if (!_opts.videos) {
return console.warn('Error. You need to define at least one video object');
}
if (hasCanvas()) {
loadImages(_opts.videos, function(err, images) {
if (err) return console.warn('Error while loading video sources.', err);
var ctx = initCanvas(),
requestAnimationFrame = reqAnimFrame();
control.play = function(key, reverse, fps) {
if (control.pause) control.pause(); // pause current vid
var img = images[key],
opts = _opts.videos[key],
frameWidth = img.width / opts.cols,
frameHeight = img.height / Math.ceil(opts.frames / opts.cols);
var curFps = fps || opts.fps || 15,
curFrame = reverse ? opts.frames - 1 : 0,
wait = 0,
playing = true,
loops = 0,
delay = 60 / curFps;
requestAnimationFrame(frame);
control.resume = function() {
playing = true;
requestAnimationFrame(frame);
};
control.pause = function() {
playing = false;
requestAnimationFrame(frame);
};
control.isPlaying = function() {
return playing;
};
control.destroy = function(){
control.pause();
removeCanvid();
};
if (firstPlay) {
firstPlay = false;
hideChildren();
}
function frame() {
if (!wait) {
drawFrame(curFrame);
curFrame = (+curFrame + (reverse ? -1 : 1));
if (curFrame < 0) curFrame += +opts.frames;
if (curFrame >= opts.frames) curFrame = 0;
if (reverse ? curFrame == opts.frames - 1 : !curFrame) loops++;
if (opts.loops && loops >= opts.loops) playing = false;
}
wait = (wait + 1) % delay;
if (playing && opts.frames > 1) requestAnimationFrame(frame);
}
function drawFrame(f) {
var fx = Math.floor(f % opts.cols) * frameWidth,
fy = Math.floor(f / opts.cols) * frameHeight;
ctx.clearRect(0, 0, _opts.width, _opts.height); // clear frame
ctx.drawImage(img, fx, fy, frameWidth, frameHeight, 0, 0, _opts.width, _opts.height);
}
}; // end control.play
if (isFunction(_opts.loaded)) {
_opts.loaded(control);
}
}); // end loadImages
} else if (opts.srcGif) {
var fallbackImage = new Image();
fallbackImage.src = opts.srcGif;
el.appendChild(fallbackImage);
}
function loadImages(imageList, callback) {
var images = {},
imagesToLoad = Object.keys(imageList).length;
if(imagesToLoad === 0) {
return callback('You need to define at least one video object.');
}
for (var key in imageList) {
images[key] = new Image();
images[key].onload = checkCallback;
images[key].onerror = callback;
images[key].src = imageList[key].src;
}
function checkCallback() {
imagesToLoad--;
if (imagesToLoad === 0) {
callback(null, images);
}
}
}
function initCanvas() {
var canvas = document.createElement('canvas');
canvas.width = _opts.width;
canvas.height = _opts.height;
canvas.classList.add('canvid');
el.appendChild(canvas);
return canvas.getContext('2d');
}
function hideChildren() {
[].forEach.call(el.children, function(child){
if(!child.classList.contains('canvid') ){
child.style.display = 'none';
}
});
}
function removeCanvid(){
[].forEach.call(el.children, function(child){
if(child.classList.contains('canvid') ){
el.removeChild(child);
}
});
}
function reqAnimFrame() {
return window.requestAnimationFrame
|| window.webkitRequestAnimationFrame
|| window.mozRequestAnimationFrame
|| window.msRequestAnimationFrame
|| function(callback) {
return setTimeout(callback, 1000 / 60);
};
}
function hasCanvas() {
// taken from Modernizr
var elem = document.createElement('canvas');
return !!(elem.getContext && elem.getContext('2d'));
}
function isFunction(obj) {
// taken from jQuery
return typeof obj === "function" || !!(obj && obj.constructor && obj.call && obj.apply);
}
function merge() {
var obj = {},
key;
for (var i = 0; i < arguments.length; i++) {
for (key in arguments[i]) {
if (arguments[i].hasOwnProperty(key)) {
obj[key] = arguments[i][key];
}
}
}
return obj;
}
return control;
}; // end canvid function
return canvid;
})); // end factory function | JavaScript | 0 | @@ -6538,17 +6538,17 @@
===
-%22
+'
function
%22 %7C%7C
@@ -6547,9 +6547,9 @@
tion
-%22
+'
%7C%7C
@@ -7086,16 +7086,17 @@
factory function
+%0A
|
99aa06f19bbd69c51a60f9ebd21cf64d58911ba2 | Fix reference | src/validator/index.js | src/validator/index.js | 'use strict'
import '../typedefs'
import _ from 'lodash'
import {dereference} from '../dereference'
import {
addWarningResult,
aggregateResults,
ensureJsonObject,
validateRequiredAttribute
} from './utils'
import containerValidatorFactory from './container'
import viewSchema from './view-schemas/v1'
import {validate as _validateValue} from './value'
export const validateValue = _validateValue
export const validateModel = validateValue
export const builtInRenderers = {
boolean: 'frost-bunsen-input-boolean',
'button-group': 'frost-bunsen-input-button-group',
integer: 'frost-bunsen-input-number',
'multi-select': 'frost-bunsen-input-multi-select',
number: 'frost-bunsen-input-number',
password: 'frost-bunsen-input-password',
'property-chooser': 'frost-bunsen-property-chooser',
select: 'frost-bunsen-input-select',
string: 'frost-bunsen-input-text',
textarea: 'frost-bunsen-input-textarea'
}
/**
* Make sure the rootContainers (if specified) are valid
* @param {BunsenView} view - the schema to validate
* @param {BunsenModel} model - the JSON schema that the containers will reference
* @param {ContainerValidator} containerValidator - the validator instance for a container in the current view
* @returns {BunsenValidationResult} the result of validating the rootContainers
*/
function _validateRootContainers (view, model, containerValidator) {
// We should already have the error for it not existing at this point, so just fake success
// this seems wrong, but I'm not sure of a better way to do it - ARM
if (!view.rootContainers) {
return {
errors: [],
warnings: []
}
}
const results = _.map(view.rootContainers, (rootContainer, index) => {
const path = `#/rootContainers/${index}`
const containerId = rootContainer.container
const containerIndex = _.findIndex(view.containers, {id: containerId})
const container = view.containers[containerIndex]
const containerPath = `#/containers/${containerIndex}`
const rootContainerResults = [
validateRequiredAttribute(rootContainer, path, 'label'),
validateRequiredAttribute(rootContainer, path, 'container', _.map(view.containers, (c) => c.id))
]
if (container !== undefined) {
rootContainerResults.push(
containerValidator.validate(containerPath, container)
)
}
return aggregateResults(rootContainerResults)
})
return aggregateResults(results)
}
/**
* Validate the root attributes of the view
* @param {BunsenView} view - the view to validate
* @param {BunsenModel} model - the JSON schema that the containers will reference
* @param {ContainerValidator} containerValidator - the validator instance for a container in the current view
* @returns {BunsenValidationResult} any errors found
*/
function _validateRootAttributes (view, model, containerValidator) {
const results = [
_validateRootContainers(view, model, containerValidator)
]
const knownAttributes = ['version', 'type', 'rootContainers', 'containers']
const unknownAttributes = _.difference(_.keys(view), knownAttributes)
results.push({
errors: [],
warnings: _.map(unknownAttributes, (attr) => {
return {
path: '#',
message: `Unrecognized attribute "${attr}"`
}
})
})
return aggregateResults(results)
}
/**
* Validate the given view
* @param {String|View} view - the view to validate (as an object or JSON string)
* @param {BunsenModel} model - the JSON schema that the containers will reference
* @param {String[]} renderers - the list of available custom renderers to validate renderer references against
* @param {Ember.ApplicationInstance} owner - application instance
* @returns {BunsenValidationResult} the results of the view validation
*/
export function validate (view, model, renderers, owner) {
renderers = renderers || Object.keys(builtInRenderers)
let strResult = null
const temp = ensureJsonObject(view)
view = temp[0]
strResult = temp[1]
if (view === undefined) {
return {
errors: [{path: '#', message: 'Invalid JSON'}],
warnings: []
}
}
if (model === undefined) {
return {
errors: [{path: '#', message: 'Invalid Model'}],
warnings: []
}
}
const derefModel = dereference(model).schema
const containerValidator = containerValidatorFactory(view.containers, derefModel, renderers, owner)
const schemaResult = validateValue(view, viewSchema, true)
if (schemaResult.errors.length !== 0) {
return schemaResult
}
const results = [
schemaResult,
_validateRootAttributes(view, derefModel, containerValidator)
]
const allContainerPaths = _.map(view.containers, (container, index) => {
return `#/containers/${index}`
})
const validatedPaths = containerValidator.containersValidated
const missedPaths = _.difference(allContainerPaths, validatedPaths)
missedPaths.forEach((path) => {
addWarningResult(results, path, 'Unused container was not validated')
})
if (strResult !== null) {
results.push(strResult)
}
return aggregateResults(results)
}
export default validate
| JavaScript | 0.000002 | @@ -307,16 +307,66 @@
as/v1'%0A%0A
+export %7Bvalidate as validateModel%7D from './model'%0A
import %7B
@@ -455,51 +455,8 @@
alue
-%0Aexport const validateModel = validateValue
%0A%0Aex
@@ -4428,16 +4428,17 @@
esult =
+_
validate
|
92a9a6a6a184ab1c04fdfd4d4abcda9fa177393c | Correct dots view. | src/view/RunnerDots.js | src/view/RunnerDots.js | /**@namespace An outputs in dots formats for Runner’s events.
*/
var RunnerDots = {};
var failuresAndErrorsBuffer = [],
failureCounter = 0,
successCounter = 0,
errorCounter = 0,
startTime,
browserReadyTime;
/** Informs the user that the emitting Runner is waiting for the browser.
*/
RunnerDots.beforeRun = function onBeforeRun() {
startTime = new Date();
}
/** Informs the user that the emitting Runner is ready to start.
*/
RunnerDots.ready = function onReady() {
browserReadyTime = new Date();
process.stdout.write('Browser ready!\n');
}
/** Presents a brief summary of a test success to the user.
*@param {Feature} feature The feature whose results are given.
*/
RunnerDots.featureSuccess = function onFeatureSuccess(feature) {
process.stdout.write('.');
successCounter++;
}
/** Presents a brief summary of a test failure to the user.
* Stores the detailed failure description in the main buffer.
*/
RunnerDots.featureFailure = function onFeatureFailure(feature, failures) {
process.stdout.write('F');
failureCounter++;
var failuresDescription = '';
failures.forEach(function(failure) {
failuresDescription += failure + '\n\n\n';
});
failuresAndErrorsBuffer.push(failuresDescription);
}
/** Presents details of a test error to the user.
* Stores the detailed error description in the main buffer.
*/
RunnerDots.featureError = function onFeatureError(feature, errors) {
process.stdout.write('!');
errorCounter++;
var errorsDescription = '';
errors.forEach(function(error) {
errorsDescription += error + '\n';
if (error.stack) {
errorsDescription += error.stack + '\n';
}
errorsDescription += '\n\n';
});
failuresAndErrorsBuffer.push(errorsDescription);
}
/** Presents a summary of the test procedure to the user.
*@private
*/
var showEndReport = function showEndReport() {
failuresAndErrorsBuffer.forEach(function(failure) {
process.stdout.write(failure);
});
process.stdout.write('\n\nFinished in '
+ getDurationString(startTime, new Date())
+ ': '
+ getTotalNumberOfTest()
+ ' features, '
+ successCounter
+ ' success, '
+ pluralize(failureCounter, 'failure')
+ ', '
+ pluralize(errorCounter, 'error')
+ '\n\n');
}
/** Presents a summary of the test procedure to the user.
*/
RunnerDots.failure = showEndReport;
/** Presents a summary of the test procedure to the user.
*/
RunnerDots.success = showEndReport;
/**
*@returns {Number} total number of tests.
*@private
*/
var getTotalNumberOfTest = function getTotalNumberOfTest() {
return successCounter + errorCounter + failureCounter;
}
/** Displays an amount, postfixed with an 's' if needed.
*@param {Number} count The number used to pluralize the string.
*@returns {String} string The string to pluralize based on the count.
*@private
*/
var pluralize = function pluralize(count, string) {
return count + ' ' + string + (count == 1 ? '' : 's');
}
/** Computes the duration between two dates.
* The order of the two dates does not matter, a duration is always positive
*@param {Date} first The first date.
*@param {Date} second The other date.
*@returns {String} A human-readable duration string, of the form "h hours m minutes s seconds".
*@private
*/
var getDurationString = function getDurationString(first, second) {
var result = '',
durationSeconds = Math.abs(second - first) / 1000;
var durations = {
hour: Math.floor(durationSeconds / 3600),
minute: Math.floor(durationSeconds / 60) % 60,
second: Math.floor(durationSeconds) % 60
}
['hour', 'minute', 'second'].forEach(function(unit) {
var value = durations[unit];
if (value > 0)
result += pluralize(value, unit) + ' ';
});
return result.trim();
}
module.exports = RunnerDots; // CommonJS export
| JavaScript | 0 | @@ -3531,16 +3531,52 @@
%25 60%0A%09%7D
+;%09// don't you remove this semicolon
%0A%0A%09%5B'hou
|
04b47bf99e16a113125d543cea6a86c68d014db2 | Handle reverting to invalid timeslice | src/timetravel.js | src/timetravel.js | import R from 'ramda'
import Bacon from 'baconjs'
import Common from './utils/common-util'
import Storage from './utils/storage-util'
import StoreNames from './stores/store-names'
import ActionTypes from './actions/action-types'
import TimeTravelAction from './actions/timetravel-action.js'
const isAction = R.pathEq(
['action', 'type']
)
const isRevert = isAction(
ActionTypes.TIMETRAVEL_REVERT
)
const isClutch = isAction(
ActionTypes.TIMETRAVEL_CLUTCH
)
const isDeclutch = isAction(
ActionTypes.TIMETRAVEL_DECLUTCH
)
const isNotEmptyArray = R.allPass([
R.is(Array),
R.complement(R.isEmpty)
])
const findRecordByName = (name, records) => (
R.find(R.propEq('name', name), records || [])
)
const findTimeRecord = R.converge(
findRecordByName, [
R.prop('name'),
R.path(['action', 'timeslice', 'records'])
]
)
const getTimeRecord = R.converge(
R.defaultTo, [
R.set(R.lensProp('state'), null),
findTimeRecord
]
)
const mapTimeRevert = R.when(
isRevert,
getTimeRecord
)
const isNotTimeTravel = R.pipe(
R.nthArg(0),
R.path(['action', 'type']),
R.flip(R.contains)([
ActionTypes.TIMETRAVEL_TOGGLE_HISTORY,
ActionTypes.TIMETRAVEL_HISTORY,
ActionTypes.TIMETRAVEL_REVERT,
ActionTypes.TIMETRAVEL_DECLUTCH,
ActionTypes.TIMETRAVEL_CLUTCH,
ActionTypes.TIMETRAVEL_IDLE
]),
R.not
)
const mapToIdle = (args) => (
R.mergeWith(R.merge)(args, {
action: {
type: ActionTypes.TIMETRAVEL_IDLE,
skipLog: true
}
})
)
const mapDeclutchToIdle = R.ifElse(
// if was declutched and not time travelling.
R.allPass([R.nthArg(1), isNotTimeTravel]),
// change the action to do nothing.
mapToIdle,
// otherwise continue reducing.
R.nthArg(0)
)
const getDeclutchStream = (preStream) => (
Bacon.mergeAll(
preStream
.filter(isClutch)
.map(R.F),
preStream
.filter(isDeclutch)
.map(R.T)
)
)
const historyInStorageStream = Bacon.fromPromise(
Storage.load('bduxHistory'))
const historyInStorageValve = historyInStorageStream
.map(R.F)
.toProperty(true)
const getDeclutchProperty = (preStream) => (
Bacon.mergeAll(
// declutch by default when resuming from session storage.
historyInStorageStream
.first()
.map(isNotEmptyArray),
// whether currently clutched to dispatcher.
getDeclutchStream(preStream)
)
.toProperty()
)
const getPreOutputStream = (preStream) => (
Bacon.when([
// wait for storage.
preStream.holdWhen(historyInStorageValve),
// filter out actions while declutched.
getDeclutchProperty(preStream)], mapDeclutchToIdle)
// record the action and store states.
.doAction(TimeTravelAction.record)
// handle revert action.
.map(mapTimeRevert)
)
export const getPreReduce = () => {
let preStream = new Bacon.Bus()
// start recording.
TimeTravelAction.start();
return {
input: preStream,
output: getPreOutputStream(preStream)
}
}
| JavaScript | 0.000001 | @@ -607,16 +607,74 @@
ty)%0A%5D)%0A%0A
+const hasTimeslice = R.path(%0A %5B'action', 'timeslice'%5D%0A)%0A%0A
const fi
@@ -1040,24 +1040,51 @@
when(%0A
-isRevert
+R.allPass(%5BisRevert, hasTimeslice%5D)
,%0A getT
|
addf9c55fc1a67d38e305451e507c3a79985f60f | Fix get started button on website | website/pages/en/index.js | website/pages/en/index.js | /**
* Copyright 2018-present Facebook.
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* @format
*/
const React = require('react');
const CompLibrary = require('../../core/CompLibrary');
const Container = CompLibrary.Container;
const GridBlock = CompLibrary.GridBlock;
const siteConfig = require(`${process.cwd()}/siteConfig.js`);
class Index extends React.Component {
render() {
if ((siteConfig.users || []).length === 0) {
return null;
}
const editUrl = `${siteConfig.repoUrl}/edit/master/website/siteConfig.js`;
const showcase = siteConfig.users.filter(u => !!u.pinned).map(user => (
<a href={user.infoLink} key={user.infoLink}>
<img src={user.image} alt={user.caption} title={user.caption} />
</a>
));
return (
<div>
<div className="splash">
<div className="content">
<h1>Formik</h1>
<h2>Build forms in React, without tears.</h2>
<div className="row">
<a className="btn primary" href="docs/overview">
Get Started
</a>
<a className="btn" href="https://github.com/jaredpalmer/formik">
GitHub
</a>
</div>
{/* <img
src="/img/splash.png"
srcSet="/img/splash.png 1x, /img/splash@2x.png 2x"
className="splashScreen"
/> */}
<div className="shadow" />
</div>
</div>
{/* <div className="content row">
<div className="col">
<img
src="/img/inspector.png"
srcSet="/img/inspector.png 1x, /img/inspector@2x.png 2x"
/>
</div>
<div className="col">
<h3>Declarative</h3>
<p>
Formik is a small collection declarative React components that
make it painless to create rich, complex forms. Formik takes care
of the repetitive and annoying stuff--keeping track of
values/errors/visited fields, orchestrating validation, and
handling submission--so you don't have to. This means you spend
less time wiring up state and change handlers and more time
focusing on your business logic.
</p>
<a className="learnmore" href="/docs/getting-started.html">
Learn more
</a>
</div>
</div>
<div className="content row">
<div className="col">
<h3>Intuitive</h3>
<p>
Formik doesn't use fancy subscriptions or observables under the
hood, just plain React state and props. By staying within the core
React framework and away from magic, Formik makes debugging,
testing, and reasoning about your forms a breeze. If you know
React, and you know a bit about forms, you know Formik!
</p>
<a className="learnmore" href="/docs/understand.html">
Learn more
</a>
</div>
<div className="col center">
<img
src="/img/FlipperKit.png"
srcSet="/img/FlipperKit.png 1x, /img/FlipperKit@2x.png 2x"
/>
</div>
</div>
<div className="content row">
<div className="col">
<img
src="/img/plugins.png"
srcSet="/img/plugins.png 1x, /img/plugins@2x.png 2x"
/>
</div>
<div className="col">
<h3>Adoptable</h3>
<p>
Form state is inherently local and ephemeral. Unlike other form
helpers, Formik does not use external state mangement librares
like Redux or MobX to store form state. This makes Formik is easy
to adopt incrementally and keeps its bundle size to just 7.5 KB
minified gzipped.
</p>
<a className="learnmore" href="/docs/js-setup.html">
Learn more
</a>
</div>
</div>
<div className="content row">
<div className="col">
<h3>Cross Platform</h3>
<p>
Formik doesn’t make assumptions about how or where you render or
style your inputs, so it works anywhere and everywhere React does
and with any 3rd party input component you can throw at it.
</p>
<a className="learnmore" href="/docs/js-setup.html">
Learn more
</a>
</div>
<div className="col">
<img
src="/img/plugins.png"
srcSet="/img/plugins.png 1x, /img/plugins@2x.png 2x"
/>
</div>
</div> */}
<div style={{ background: '#eee' }}>
<Container padding={['bottom', 'top']}>
<GridBlock
align="center"
contents={[
{
content: 'James Long, Creator of Prettier',
// image: `${siteConfig.baseUrl}img/hector-ramos.png`,
// imageAlign: 'bottom',
// imageAlt: 'James Long',
title:
"*I can't believe people ever put forms in Redux, or did anything else other than this.*",
},
{
content: `Kye Hohenberger, Creator of Emotion`,
// image: `${siteConfig.baseUrl}img/ricky-vetter.jpg`,
// imageAlign: 'bottom',
// imageAlt: 'Kye Hohenberger',
title: `*Formik removes most of the moving parts involved in forms
allowing me to move faster with more confidence.*`,
},
{
content:
'Ken Wheeler, Director of Open Source at Formidable Labs',
// image: `${siteConfig.baseUrl}img/christopher-chedeau.jpg`,
// imageAlign: 'bottom',
// imageAlt: 'Ken Wheeler',
title: `*Formik. All day. All long.*`,
},
]}
layout="threeColumn"
/>
</Container>
</div>
<div
className="showcaseSection"
style={{ marginBottom: 80, marginTop: 80 }}
>
<div className="prose">
<h2>Who's using Formik?</h2>
<p>
Formik has been powering forms at{' '}
<a href="https://palmer.net">The Palmer Group</a> since 2016.
Formik was open sourced in 2017 and is by teams of all sizes.
</p>
</div>
<div className="logos">{showcase}</div>
<a className="btn" href="users.html">
More Formik Users
</a>
</div>
</div>
);
}
}
module.exports = Index;
| JavaScript | 0 | @@ -1094,16 +1094,24 @@
%22 href=%22
+/formik/
docs/ove
@@ -6892,16 +6892,24 @@
%22 href=%22
+/formik/
users.ht
|
3bd603c7be55879fd0849a6e0fbcb27e01613b17 | Fix links | website/pages/en/index.js | website/pages/en/index.js | /**
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
const CompLibrary = require('../../core/CompLibrary.js');
const MarkdownBlock = CompLibrary.MarkdownBlock; /* Used to read markdown */
const Container = CompLibrary.Container;
const GridBlock = CompLibrary.GridBlock;
class HomeSplash extends React.Component {
render() {
const {siteConfig, language = ''} = this.props;
const {baseUrl, docsUrl} = siteConfig;
const docsPart = `${docsUrl ? `${docsUrl}/` : ''}`;
const langPart = `${language ? `${language}/` : ''}`;
const docUrl = doc => `${baseUrl}${docsPart}${langPart}${doc}`;
const SplashContainer = props => (
<div className="homeContainer">
<div className="homeSplashFade">
<div className="wrapper homeWrapper">{props.children}</div>
</div>
</div>
);
const ProjectTitle = () => (
<h2 className="projectTitle">
{siteConfig.title}
<small>{siteConfig.tagline}</small>
</h2>
);
const PromoSection = props => (
<div className="section promoSection">
<div className="promoRow">
<div className="pluginRowBlock">
{props.children}
</div>
</div>
</div>
);
const Button = props => (
<div className="pluginWrapper buttonWrapper">
<a className="button" href={props.href} target={props.target}>
{props.children}
</a>
</div>
);
return (
<SplashContainer>
<div className="inner">
<ProjectTitle siteConfig={siteConfig}/>
<PromoSection>
<Button href='./docs'>Get Started</Button>
<Button href="https://github.com/wvlet/airframe/">GitHub</Button>
<a className="github-button" href="https://github.com/wvlet/airframe"
data-color-scheme="no-preference: light; light: light; dark: dark;" data-size="large"
data-show-count="true" aria-label="Star wvlet/airframe on GitHub">Star</a>
</PromoSection>
</div>
</SplashContainer>
);
}
}
class Index extends React.Component {
render() {
const {config: siteConfig, language = ''} = this.props;
const {baseUrl} = siteConfig;
const Logo = props => (
<div className="projectLogo">
</div>
);
const Block = props => (
<Container
padding={['bottom', 'top']}
id={props.id}
background={props.background}>
<GridBlock
align="center"
contents={props.children}
layout={props.layout}
/>
</Container>
);
const FeatureCallout = () => (
<Container
padding={['bottom', 'top']}
background="light"
className="threeColumn">
<div>
<img width='200px' src={`${baseUrl}img/logos/airframe-logo-tr.png`} alt="Project Logo"/>
</div>
</Container>
);
const Features = ({background = 'light'}) => (
<Block layout="threeColumn">
{[
{
content: '[Airframe RPC](docs/airframe-rpc) supports seamless integration of server and clients using Scala as RPC interfaces.',
image: `${baseUrl}img/airframe-rpc/rpc-overview.png`,
imageAlign: 'top',
title: 'RPC Framework',
},
{
content: 'Have you ever used [slf4](http://slf4j.org/) (logging), [Jackson](https://github.com/FasterXML/jackson) (JSON-based serialization), [Guice](https://github.com/google/guice) (dependency injection)? ' +
'Airframe has redesigned these Java-based ecosystem as [airframe-logging](docs/airframe-log.md), [airframe-codec](docs/airframe-codec.md), and [airframe-di](docs/airframe.md) in order to maximize the power of Scala and Scala.js',
image: `${baseUrl}img/features/scala-logo-red-spiral-dark.png`,
imageAlign: 'top',
title: 'Designed for Scala and Scala.js',
},
{
content:
'Airframe uses [MessagePack-based schema-on-read codec](docs/airframe-codec) for fast and compact object serialization. [JSON](docs/airframe-json) serialization is also supported.',
image: `${baseUrl}img/features/msgpack.png`,
imageAlign: 'top',
title: 'MessagePack-based Object Serialization',
},
{
content: '[AirSpec](docs/airspec) is a simple unit testing framework for Scala and Scala.js. You can use public methods in your classes as test cases. No need to remember complex DSLs for writing tests in Scala.',
image: `${baseUrl}/img/features/airspec.png`,
imageAlign: 'top',
title: 'Simple Testing Framework'
},
{
content: "[airframe-http](docs/airframe-http) supports building REST web services by using Scala as an IDL (Interface Definition Language). Airframe provides a ready-to use web server implementation based on [Twitter Finagle](https://twitter.github.io/finagle/guide/) and built-in JSON/MessagePack-based REST API call mapping to crate microservice API servers and clients at ease",
image: `${baseUrl}/img/features/finagle.png`,
imageAlign: 'top',
title: 'REST Services'
},
{
content: 'Retrying HTTP requests for API calls is an essential technique for connecting microservices. [airframe-control](docs/airframe-control) will provide essential tools for making your requests reliable with exponential backoff retry, jitter, circuit-breaker, rate control, etc.',
image: `${baseUrl}/img/features/undraw_process_e90d.svg`,
imageAlign: 'top',
title: 'Retry, Rate Control'
},
{
content: "Web application development often requires mock web servers. With [airframe-http-recorder](docs/airframe-http-recorder), you can record and replay the real server responses for running unit tests even if the servers are offline or unreachable from CI environments.",
image: `${baseUrl}/img/features/undraw_server_down_s4lk.svg`,
imageAlign: 'top',
title: 'HTTP Client and Recorders',
},
{
content: "[airframe-metrics](docs/airframe-metrics) provides human-friendly time range selectors (e.g., -1d, -1w) and data units for measuring elapsed time (e.g., 0.1s, 1.5h) and data sizes (e.g., GB, PB.)",
image: `${baseUrl}/img/features//undraw_time_management_30iu.svg`,
imageAlign: 'top',
title: 'Time Series Data Management',
},
{
content: `[airframe-fluentd](docs/airframe-fluentd) supports logging your metrics to fluentd in a type-safe manner. You just need to send your case classes as metrics for fluentd.`,
image: `${baseUrl}/img/features/Fluentd_square.svg`,
imageAlign: 'top',
title: 'Fluentd Logging',
},
]}
</Block>
);
return (
<div>
<HomeSplash siteConfig={siteConfig} language={language}/>
<div className="mainContainer">
<Features/>
</div>
</div>
);
}
}
module.exports = Index;
| JavaScript | 0 | @@ -4434,20 +4434,16 @@
rame-log
-ging
%5D(docs/a
@@ -4453,19 +4453,16 @@
rame-log
-.md
), %5Bairf
@@ -4492,19 +4492,16 @@
me-codec
-.md
), and %5B
@@ -4530,11 +4530,8 @@
rame
-.md
) in
@@ -5032,16 +5032,22 @@
me-json)
+-based
seriali
|
d9bc14f41712801e1166404f4bcb296ddc5c1f70 | remove log | src/playground/executors.js | src/playground/executors.js | /*
*
*/
'use strict';
class Executor {
constructor(block, entity) {
this.scope = new Entry.Scope(block, this);
this.entity = entity;
this._callStack = [];
this.register = {};
this.paused = false;
this.parentExecutor = null;
this.valueMap = {};
this.valueState = {};
this.id = Entry.Utils.generateId();
}
execute(isFromOrigin) {
if (this.isEnd()) {
return;
}
const executedBlocks = [];
if (isFromOrigin) {
Entry.callStackLength = 0;
}
const entity = this.entity;
while (true) {
let returnVal = null;
executedBlocks.push(this.scope.block);
try {
const schema = this.scope.block.getSchema();
if (schema && Entry.skeleton[schema.skeleton].executable) {
Entry.dispatchEvent('blockExecute', this.scope.block && this.scope.block.view);
returnVal = schema.func.call(this.scope, entity, this.scope);
this.scope.key = Entry.generateHash();
}
} catch (e) {
if (e.name === 'AsyncError') {
returnVal = Entry.STATIC.BREAK;
} else if (e.name === 'IncompatibleError') {
Entry.Utils.stopProjectWithToast(this.scope, e.message, e);
} else if (this.isFuncExecutor) {
//function executor
throw e;
} else {
Entry.Utils.stopProjectWithToast(this.scope, undefined, e);
}
}
//executor can be ended after block function call
if (this.isEnd()) {
return executedBlocks;
}
if (returnVal instanceof Promise) {
this.paused = true;
returnVal
.then((value) => {
if (this.scope.block && Entry.engine.isState('run')) {
this.scope = new Entry.Scope(this.scope.block.getNextBlock(), this);
}
if (this.scope.block === null && this._callStack.length) {
this.scope = this._callStack.pop();
}
this.valueMap = {};
this.valueState = {};
this.paused = false;
})
.catch((e) => {
console.log('eeeee', e);
this.paused = false;
if (e.name === 'AsyncError') {
returnVal = Entry.STATIC.BREAK;
} else if (this.isFuncExecutor) {
throw e;
} else {
Entry.Utils.stopProjectWithToast(this.scope, undefined, e);
}
});
break;
} else if (
returnVal === undefined ||
returnVal === null ||
returnVal === Entry.STATIC.PASS
) {
this.scope = new Entry.Scope(this.scope.block.getNextBlock(), this);
this.valueMap = {};
this.valueState = {};
if (this.scope.block === null) {
if (this._callStack.length) {
const oldScope = this.scope;
this.scope = this._callStack.pop();
if (this.scope.isLooped !== oldScope.isLooped) {
break;
}
} else {
break;
}
}
} else if (returnVal === Entry.STATIC.CONTINUE) {
this.valueMap = {};
this.valueState = {};
} else if (returnVal === this.scope) {
this.valueMap = {};
this.valueState = {};
break;
} else if (returnVal === Entry.STATIC.BREAK) {
break;
}
}
return executedBlocks;
}
stepInto(thread) {
if (!(thread instanceof Entry.Thread)) {
console.error('Must step in to thread');
}
const block = thread.getFirstBlock();
if (!block) {
return Entry.STATIC.BREAK;
}
this._callStack.push(this.scope);
this.scope = new Entry.Scope(block, this);
return Entry.STATIC.CONTINUE;
}
break() {
if (this._callStack.length) {
this.scope = this._callStack.pop();
}
return Entry.STATIC.PASS;
}
breakLoop() {
if (this._callStack.length) {
this.scope = this._callStack.pop();
}
while (this._callStack.length) {
const schema = Entry.block[this.scope.block.type];
if (schema.class === 'repeat') {
break;
}
this.scope = this._callStack.pop();
}
return Entry.STATIC.PASS;
}
end() {
Entry.dispatchEvent('blockExecuteEnd', this.scope.block && this.scope.block.view);
this.scope.block = null;
}
isPause() {
return this.paused;
}
isEnd() {
return this.scope.block === null;
}
}
Entry.Executor = Executor;
| JavaScript | 0.000001 | @@ -1949,21 +1949,16 @@
.then((
-value
) =%3E %7B%0A
@@ -2529,57 +2529,8 @@
%3E %7B%0A
- console.log('eeeee', e);%0A
|
56e3cf72fac9cecc18d6d5d4153bcc6f934ddf09 | allow sourceMaps false in transpiler options (#418) | src/transpiler.js | src/transpiler.js | /*
* Traceur, Babel and TypeScript transpile hook for Loader
*/
var transpile = (function() {
// use Traceur by default
Loader.prototype.transpiler = 'traceur';
function transpile(load) {
var self = this;
return Promise.resolve(__global[self.transpiler == 'typescript' ? 'ts' : self.transpiler]
|| (self.pluginLoader || self)['import'](self.transpiler))
.then(function(transpiler) {
if (transpiler.__useDefault)
transpiler = transpiler['default'];
var transpileFunction;
if (transpiler.Compiler)
transpileFunction = traceurTranspile;
else if (transpiler.createLanguageService)
transpileFunction = typescriptTranspile;
else
transpileFunction = babelTranspile;
// note __moduleName will be part of the transformer meta in future when we have the spec for this
return '(function(__moduleName){' + transpileFunction.call(self, load, transpiler) + '\n})("' + load.name + '");\n//# sourceURL=' + load.address + '!transpiled';
});
};
function traceurTranspile(load, traceur) {
var options = this.traceurOptions || {};
options.modules = 'instantiate';
options.script = false;
options.sourceMaps = 'inline';
options.filename = load.address;
options.inputSourceMap = load.metadata.sourceMap;
options.moduleName = false;
var compiler = new traceur.Compiler(options);
return doTraceurCompile(load.source, compiler, options.filename);
}
function doTraceurCompile(source, compiler, filename) {
try {
return compiler.compile(source, filename);
}
catch(e) {
// traceur throws an error array
throw e[0];
}
}
function babelTranspile(load, babel) {
var options = this.babelOptions || {};
options.modules = 'system';
options.sourceMap = 'inline';
options.inputSourceMap = load.metadata.sourceMap;
options.filename = load.address;
options.code = true;
options.ast = false;
return babel.transform(load.source, options).code;
}
function typescriptTranspile(load, ts) {
var options = this.typescriptOptions || {};
if (options.target === undefined) {
options.target = ts.ScriptTarget.ES5;
}
options.module = ts.ModuleKind.System;
options.inlineSourceMap = true;
return ts.transpile(load.source, options, load.address);
}
return transpile;
})();
| JavaScript | 0 | @@ -1189,16 +1189,60 @@
false;%0A
+ if (options.sourceMaps === undefined)%0A
opti
@@ -1260,32 +1260,32 @@
aps = 'inline';%0A
-
options.file
@@ -1839,16 +1839,59 @@
ystem';%0A
+ if (options.sourceMap === undefined)%0A
opti
@@ -1908,32 +1908,32 @@
Map = 'inline';%0A
-
options.inpu
@@ -2209,28 +2209,24 @@
%7C%7C %7B%7D;%0A
-if (
options.targ
@@ -2233,29 +2233,8 @@
et =
-== undefined) %7B%0A
opt
@@ -2245,17 +2245,18 @@
.target
-=
+%7C%7C
ts.Scri
@@ -2277,87 +2277,184 @@
-%7D%0A options.module = ts.ModuleKind.System;%0A options.inlineSourceMap = true
+if (options.sourceMap === undefined)%0A options.sourceMap = true;%0A if (options.sourceMap)%0A options.inlineSourceMap = true;%0A%0A options.module = ts.ModuleKind.System
;%0A%0A
|
06f2b7822b19fa76f439dd593c94fbe6a5098ab0 | Fix regex for builder redirects | website/redirects.next.js | website/redirects.next.js | module.exports = [
{
source: '/docs/installation',
destination: '/docs/install',
permanent: true,
},
{
source: '/docs/command-line/machine-readable',
destination: '/docs/commands',
permanent: true,
},
{
source: '/docs/command-line/introduction',
destination: '/docs/commands',
permanent: true,
},
{
source: '/docs/templates/introduction',
destination: '/docs/templates',
permanent: true,
},
{
source: '/docs/builders/azure-setup',
destination: '/docs/builders/azure',
permanent: true,
},
{
source: '/docs/templates/veewee-to-packer',
destination: '/guides/veewee-to-packer',
permanent: true,
},
{
source: '/docs/extend/developing-plugins',
destination: '/docs/extending/plugins',
permanent: true,
},
{
source: '/docs/extending/developing-plugins',
destination: '/docs/extending/plugins',
permanent: true,
},
{
source: '/docs/extend/builder',
destination: '/docs/extending/custom-builders',
permanent: true,
},
{
source: '/docs/getting-started/setup',
destination: '/docs/getting-started/install',
permanent: true,
},
{
source: '/docs/other/community',
destination: '/community-tools',
permanent: true,
},
{
source: '/downloads-community',
destination: '/community-tools',
permanent: true,
},
{
source: '/docs/platforms',
destination: '/docs/builders',
permanent: true,
},
{
source: '/intro/platforms',
destination: '/docs/builders',
permanent: true,
},
{
source: '/docs/templates/configuration-templates',
destination: '/docs/templates/engine',
permanent: true,
},
{
source: '/docs/machine-readable/:path*',
destination: '/docs/commands',
permanent: true,
},
{
source: '/docs/command-line/:path*',
destination: '/docs/commands/:path*',
permanent: true,
},
{
source: '/docs/extend/:path*',
destination: '/docs/extending/:path*',
permanent: true,
},
{
source: '/intro/getting-started',
destination: 'https://learn.hashicorp.com/packer/getting-started/install',
permanent: true,
},
{
source: '/intro/getting-started/install',
destination: 'https://learn.hashicorp.com/packer/getting-started/install',
permanent: true,
},
{
source: '/intro/getting-started/build-image',
destination:
'https://learn.hashicorp.com/packer/getting-started/build-image',
permanent: true,
},
{
source: '/intro/getting-started/provision',
destination: 'https://learn.hashicorp.com/packer/getting-started/provision',
permanent: true,
},
{
source: '/intro/getting-started/parallel-builds',
destination:
'https://learn.hashicorp.com/packer/getting-started/parallel-builds',
permanent: true,
},
{
source: '/intro/getting-started/vagrant',
destination: 'https://learn.hashicorp.com/packer/getting-started/vagrant',
permanent: true,
},
{
source: '/intro/getting-started/next',
destination: 'https://learn.hashicorp.com/packer/getting-started/next ',
permanent: true,
},
{
source: '/docs/basics/terminology',
destination: '/docs/terminology',
permanent: true,
},
{
source: '/docs/other/:path*',
destination: '/docs/:path*',
permanent: true,
},
{
source: '/docs/configuration/from-1.5/:path*',
destination: '/docs/from-1.5/:path*',
permanent: true,
},
{
source: '/docs/configuration/from-1.5/:path*/overview',
destination: '/docs/from-1.5/:path*',
permanent: true,
},
{
source: '/docs/builders/amazon-:path*',
destination: '/docs/builders/amazon/:path*',
permanent: true,
},
{
source: '/docs/builders/azure-:path*',
destination: '/docs/builders/azure/:path*',
permanent: true,
},
{
source: '/docs/builders/hyperv-:path*',
destination: '/docs/builders/hyperv/:path*',
permanent: true,
},
{
source: '/docs/builders/oracle-:path*',
destination: '/docs/builders/oracle/:path*',
permanent: true,
},
{
source: '/docs/builders/osc-:path*',
destination: '/docs/builders/outscale/:path*',
permanent: true,
},
{
source: '/docs/builders/parallels-:path*',
destination: '/docs/builders/parallels/:path*',
permanent: true,
},
{
source: '/docs/builders/virtualbox-:path*',
destination: '/docs/builders/virtualbox/:path*',
permanent: true,
},
{
source: '/docs/builders/vmware-:path*',
destination: '/docs/builders/vmware/:path*',
permanent: true,
},
{
source: '/docs/builders/vsphere-:path*',
destination: '/docs/builders/vmware/vsphere-:path*',
permanent: true,
},
// disallow '.html' or '/index.html' in favor of cleaner, simpler paths
{ source: '/:path*/index', destination: '/:path*', permanent: true },
{ source: '/:path*.html', destination: '/:path*', permanent: true },
]
| JavaScript | 0.000001 | @@ -3643,28 +3643,27 @@
amazon-:path
-*
',%0A
+
destinat
@@ -3760,33 +3760,32 @@
ders/azure-:path
-*
',%0A destinati
@@ -3885,25 +3885,24 @@
hyperv-:path
-*
',%0A desti
@@ -4007,25 +4007,24 @@
oracle-:path
-*
',%0A desti
@@ -4126,25 +4126,24 @@
rs/osc-:path
-*
',%0A desti
@@ -4253,25 +4253,24 @@
allels-:path
-*
',%0A desti
@@ -4382,25 +4382,24 @@
ualbox-:path
-*
',%0A desti
@@ -4504,33 +4504,32 @@
ers/vmware-:path
-*
',%0A destinati
@@ -4586,32 +4586,32 @@
true,%0A %7D,%0A %7B%0A
+
source: '/do
@@ -4631,25 +4631,24 @@
sphere-:path
-*
',%0A desti
|
8b091bf0742abb7c5b11f16f9d1dcf3d32ecf378 | use camelcase for property names in JS | website/src/flux/index.js | website/src/flux/index.js | /**
* @jsx React.DOM
*/
var React = require('React');
var Site = require('Site');
var Prism = require('Prism');
var Marked = require('Marked');
var unindent = require('unindent');
var index = React.createClass({
render: function() {
return (
<Site>
<div className="hero">
<div className="wrap">
<div className="text"><strong>Flux</strong></div>
<div className="minitext">
Application Architecture for Building User Interfaces
</div>
</div>
</div>
<section className="content wrap">
<section className="home-section home-getting-started">
<p>
Flux is the application architecture that Facebook uses for building client-side web applications. It complements React's composable view components by utilizing a unidirectional data flow. It's more of a pattern rather than a formal framework, and you can start using Flux immediately without a lot of new code.
</p>
</section>
<section className="home-section home-getting-started">
<iframe width="500" height="280" src="//www.youtube.com/embed/nYkdrAPrdcw?list=PLb0IAmt7-GS188xDYE-u1ShQmFFGbrk0v&start=621" frameborder="0" allowfullscreen></iframe>
</section>
<section className="home-bottom-section">
<div className="buttons-unit">
<a href="docs/overview.html#content" className="button">Learn more about Flux</a>
</div>
</section>
<p></p>
</section>
</Site>
);
}
});
module.exports = index;
| JavaScript | 0 | @@ -1248,17 +1248,17 @@
1%22 frame
-b
+B
order=%220
@@ -1268,13 +1268,12 @@
llow
-f
+F
ull
-s
cree
|
efb1efa9cca1c1609d2e1738f20a6dc3358135a6 | Reformat Spinner.js | src/widgets/Spinner.js | src/widgets/Spinner.js | const React = require('react');
const ReactNative = require('react-native');
const {
Animated,
StyleSheet,
View,
} = ReactNative;
export class Spinner extends React.Component {
constructor(props) {
super(props);
this.progressAnimation = new Animated.Value(0);
this.startSpinning = this.startSpinning.bind(this);
this.stopSpinning = this.stopSpinning.bind(this);
}
componentDidMount() {
this.startSpinning();
}
componentWillReceiveProps(nextProps) {
if (nextProps.isSpinning) this.startSpinning();
else this.stopSpinning();
}
startSpinning() {
Animated.timing(
this.progressAnimation,
{ toValue: 100, duration: 1000, useNativeDriver: true, shouldLoop: true })
.start();
}
stopSpinning() {
this.progressAnimation.setValue(0);
}
render() {
const interpolatedRotateAnimation = this.progressAnimation.interpolate({
inputRange: [0, 100],
outputRange: ['0deg', '360deg'],
});
return (
<Animated.View
style={[
localStyles.box,
{
backgroundColor: this.props.color,
transform: [{ rotate: interpolatedRotateAnimation }],
},
]}
/>
);
}
}
Spinner.propTypes = {
isSpinning: React.PropTypes.bool,
color: React.PropTypes.string,
};
Spinner.defaultProps = {
isSpinning: true,
color: '#B7B7B7',
};
const localStyles = StyleSheet.create({
box: {
width: 40,
height: 40,
},
});
| JavaScript | 0 | @@ -1,16 +1,17 @@
-cons
+impor
t React
= re
@@ -10,77 +10,27 @@
act
-= require('react');%0Aconst ReactNative = require('react-native');%0Acons
+from 'react';%0Aimpor
t %7B%0A
@@ -69,21 +69,27 @@
,%0A%7D
-= R
+from 'r
eact
-N
+-n
ative
+'
;%0A%0Ae
@@ -1022,19 +1022,22 @@
lStyles.
-box
+square
,%0A
@@ -1412,11 +1412,14 @@
%7B%0A
-box
+square
: %7B%0A
|
12882f9f99ed2e8cc3726f50a909cd946a71144b | fix spelling of 'country' (#3679) | modules/etargetBidAdapter.js | modules/etargetBidAdapter.js | 'use strict';
import {registerBidder} from '../src/adapters/bidderFactory';
import { BANNER, VIDEO } from '../src/mediaTypes';
const BIDDER_CODE = 'etarget';
const countryMap = {
1: 'sk',
2: 'cz',
3: 'hu',
4: 'ro',
5: 'rs',
6: 'bg',
7: 'pl',
8: 'hr',
9: 'at',
10: 'co',
11: 'de',
255: 'en'
}
export const spec = {
code: BIDDER_CODE,
supportedMediaTypes: [ BANNER, VIDEO ],
isBidRequestValid: function (bid) {
return !!(bid.params.refid && bid.params.country);
},
buildRequests: function (validBidRequests, bidderRequest) {
var i, l, bid, reqParams, netRevenue, gdprObject;
var request = [];
var bids = JSON.parse(JSON.stringify(validBidRequests));
var lastContry = 'sk';
for (i = 0, l = bids.length; i < l; i++) {
bid = bids[i];
if (countryMap[bid.params.country]) {
lastContry = countryMap[bid.params.country];
}
reqParams = bid.params;
reqParams.transactionId = bid.transactionId;
request.push(formRequestUrl(reqParams));
}
request.unshift('//' + lastContry + '.search.etargetnet.com/hb/?hbget=1');
netRevenue = 'net';
if (bidderRequest && bidderRequest.gdprConsent && bidderRequest.gdprConsent.gdprApplies) {
gdprObject = {
gdpr: bidderRequest.gdprConsent.gdprApplies,
gdpr_consent: bidderRequest.gdprConsent.consentString
};
request.push('gdpr=' + gdprObject.gdpr);
request.push('gdpr_consent=' + gdprObject.gdpr_consent);
}
return {
method: 'POST',
url: request.join('&'),
data: bidderRequest,
bids: validBidRequests,
netRevenue: netRevenue,
bidder: 'etarget',
gdpr: gdprObject
};
function formRequestUrl(reqData) {
var key;
var url = [];
for (key in reqData) {
if (reqData.hasOwnProperty(key) && reqData[key]) { url.push(key, '=', reqData[key], '&'); }
}
return encodeURIComponent(btoa(url.join('').slice(0, -1)));
}
},
interpretResponse: function (serverResponse, bidRequest) {
const VALID_RESPONSES = {
banner: 1,
video: 1
};
var bidObject, bid, type;
var bidRespones = [];
var bids = bidRequest.bids;
var responses = serverResponse.body;
var data = [];
for (var i = 0; i < responses.length; i++) {
data = responses[i];
type = data.response === 'banner' ? BANNER : VIDEO;
bid = bids[i];
if (VALID_RESPONSES[data.response] && (verifySize(data, bid.sizes) || type === VIDEO)) {
bidObject = {
requestId: bid.bidId,
cpm: data.win_bid ? data.win_bid : 0,
width: data.width,
height: data.height,
creativeId: data.creativeId,
currency: data.win_cur,
netRevenue: true,
ttl: 360,
ad: data.banner,
vastXml: data.vast_content,
vastUrl: data.vast_link,
mediaType: data.response,
transactionId: bid.transactionId
};
if (bidRequest.gdpr) {
bidObject.gdpr = bidRequest.gdpr.gdpr;
bidObject.gdpr_consent = bidRequest.gdpr.gdpr_consent;
}
bidRespones.push(bidObject);
}
}
return bidRespones;
function verifySize(adItem, validSizes) {
for (var j = 0, k = validSizes.length; j < k; j++) {
if (adItem.width == validSizes[j][0] &&
adItem.height == validSizes[j][1]) {
return true;
}
}
return false;
}
}
};
registerBidder(spec);
| JavaScript | 0.999877 | @@ -703,24 +703,25 @@
var lastCo
+u
ntry = 'sk';
@@ -843,24 +843,25 @@
lastCo
+u
ntry = count
@@ -1063,16 +1063,17 @@
+ lastCo
+u
ntry + '
|
9e7c4eba73306f8adf040c758c245a48b17685d9 | Revert enabling image bitmap (#4596) | src/resources/parser/texture/img.js | src/resources/parser/texture/img.js | import { path } from '../../../core/path.js';
import { http } from '../../../net/http.js';
import {
PIXELFORMAT_R8_G8_B8, PIXELFORMAT_R8_G8_B8_A8, TEXHINT_ASSET
} from '../../../graphics/constants.js';
import { Texture } from '../../../graphics/texture.js';
import { ABSOLUTE_URL } from '../../../asset/constants.js';
/** @typedef {import('../../texture.js').TextureParser} TextureParser */
/**
* Parser for browser-supported image formats.
*
* @implements {TextureParser}
* @ignore
*/
class ImgParser {
constructor(registry) {
// by default don't try cross-origin, because some browsers send different cookies (e.g. safari) if this is set.
this.crossOrigin = registry.prefix ? 'anonymous' : null;
this.maxRetries = 0;
this.useImageBitmap = typeof ImageBitmap !== 'undefined';
}
load(url, callback, asset) {
const hasContents = !!asset?.file?.contents;
if (hasContents) {
url = {
load: URL.createObjectURL(new Blob([asset.file.contents])),
original: url.original
};
}
const handler = (err, result) => {
if (hasContents) {
URL.revokeObjectURL(url.load);
}
callback(err, result);
};
let crossOrigin;
if (asset && asset.options && asset.options.hasOwnProperty('crossOrigin')) {
crossOrigin = asset.options.crossOrigin;
} else if (ABSOLUTE_URL.test(url.load)) {
crossOrigin = this.crossOrigin;
}
if (this.useImageBitmap) {
this._loadImageBitmap(url.load, url.original, crossOrigin, handler);
} else {
this._loadImage(url.load, url.original, crossOrigin, handler);
}
}
open(url, data, device) {
const ext = path.getExtension(url).toLowerCase();
const format = (ext === '.jpg' || ext === '.jpeg') ? PIXELFORMAT_R8_G8_B8 : PIXELFORMAT_R8_G8_B8_A8;
const texture = new Texture(device, {
name: url,
// #if _PROFILER
profilerHint: TEXHINT_ASSET,
// #endif
width: data.width,
height: data.height,
format: format
});
texture.setSource(data);
return texture;
}
_loadImage(url, originalUrl, crossOrigin, callback) {
const image = new Image();
if (crossOrigin) {
image.crossOrigin = crossOrigin;
}
let retries = 0;
const maxRetries = this.maxRetries;
let retryTimeout;
// Call success callback after opening Texture
image.onload = function () {
callback(null, image);
};
image.onerror = function () {
// Retry a few times before failing
if (retryTimeout) return;
if (maxRetries > 0 && ++retries <= maxRetries) {
const retryDelay = Math.pow(2, retries) * 100;
console.log(`Error loading Texture from: '${originalUrl}' - Retrying in ${retryDelay}ms...`);
const idx = url.indexOf('?');
const separator = idx >= 0 ? '&' : '?';
retryTimeout = setTimeout(function () {
// we need to add a cache busting argument if we are trying to re-load an image element
// with the same URL
image.src = url + separator + 'retry=' + Date.now();
retryTimeout = null;
}, retryDelay);
} else {
// Call error callback with details.
callback(`Error loading Texture from: '${originalUrl}'`);
}
};
image.src = url;
}
_loadImageBitmap(url, originalUrl, crossOrigin, callback) {
const options = {
cache: true,
responseType: 'blob',
retry: this.maxRetries > 0,
maxRetries: this.maxRetries
};
http.get(url, options, function (err, blob) {
if (err) {
callback(err);
} else {
createImageBitmap(blob, {
premultiplyAlpha: 'none'
})
.then(imageBitmap => callback(null, imageBitmap))
.catch(e => callback(e));
}
});
}
}
export { ImgParser };
| JavaScript | 0 | @@ -158,17 +158,40 @@
NT_ASSET
+,%0A DEVICETYPE_WEBGPU
%0A
-
%7D from '
@@ -776,24 +776,25 @@
es = 0;%0A
+%0A
this.use
@@ -789,64 +789,960 @@
-this.useImageBitmap = typeof ImageBitmap !== 'undefined'
+// ImageBitmap current state (Sep 2022):%0A // - Lastest Chrome and Firefox browsers appear to support the ImageBitmap API fine (though%0A // there are likely still issues with older versions of both).%0A // - Safari supports the API, but completely destroys some pngs. For example the cubemaps in%0A // steampunk slots https://playcanvas.com/editor/scene/524858. See the webkit issue%0A // https://bugs.webkit.org/show_bug.cgi?id=182424 for status.%0A // - Some applications assume that PNGs loaded by the engine use HTMLImageBitmap interface and%0A // fail when using ImageBitmap. For example, Space Base project fails because it uses engine%0A // texture assets on the dom https://playcanvas.com/editor/scene/446278.%0A%0A // only enable when running webgpu%0A const isWebGPU = registry?._loader?._app?.graphicsDevice?.deviceType === DEVICETYPE_WEBGPU;%0A this.useImageBitmap = isWebGPU
;%0A
|
0ae26dcb702f3cd99223b12679a3e820af3f5eef | remove console log | src/components/topic/snapshots/foci/create/keywordSearch/KeywordSearchResultsContainer.js | src/components/topic/snapshots/foci/create/keywordSearch/KeywordSearchResultsContainer.js | import React from 'react';
import { FormattedMessage, injectIntl } from 'react-intl';
import { connect } from 'react-redux';
import { Row, Col } from 'react-flexbox-grid/lib';
import { fetchCreateFocusKeywordStories } from '../../../../../../actions/topicActions';
import composeAsyncContainer from '../../../../../common/AsyncContainer';
import StoryTable from '../../../../StoryTable';
const STORIES_TO_SHOW = 20;
const localMessages = {
title: { id: 'focus.create.keyword.results.title', defaultMessage: 'Some Matching Stories' },
about: { id: 'focus.create.keyword.results.about',
defaultMessage: 'Here is a preview of the top stores in the Timespan of the Topic you are investigating. Look over these results to make sure they are the types of stories you are hoping this Focus will focus in on.' },
};
class KeywordSearchResultsContainer extends React.Component {
componentWillReceiveProps(nextProps) {
const { fetchData, filters } = this.props;
console.log(`search for ${nextProps.keywords}`);
fetchData(filters, nextProps.keywords);
}
render() {
const { stories, topicId } = this.props;
return (
<Row>
<Col lg={10} md={10} sm={12}>
<h3><FormattedMessage {...localMessages.title} /></h3>
<StoryTable stories={stories} topicId={topicId} />
</Col>
<Col lg={2} md={2} sm={12}>
<p className="light"><i><FormattedMessage {...localMessages.about} /></i></p>
</Col>
</Row>
);
}
}
KeywordSearchResultsContainer.propTypes = {
// from context
intl: React.PropTypes.object.isRequired,
// from parent
keywords: React.PropTypes.string.isRequired,
topicId: React.PropTypes.number.isRequired,
// from mergeProps
asyncFetch: React.PropTypes.func.isRequired,
// from fetchData
fetchData: React.PropTypes.func.isRequired,
// from state
fetchStatus: React.PropTypes.string.isRequired,
filters: React.PropTypes.object.isRequired,
stories: React.PropTypes.array.isRequired,
};
const mapStateToProps = state => ({
fetchStatus: state.topics.selected.focalSets.create.matchingStories.fetchStatus,
filters: state.topics.selected.filters,
stories: state.topics.selected.focalSets.create.matchingStories.stories,
});
const mapDispatchToProps = (dispatch, ownProps) => ({
fetchData: (filters, keywords) => {
// topicId, snapshotId, timespanId, sort, limit, linkId, q
const params = {
...filters,
limit: STORIES_TO_SHOW,
q: keywords,
};
dispatch(fetchCreateFocusKeywordStories(ownProps.topicId, params));
},
});
function mergeProps(stateProps, dispatchProps, ownProps) {
return Object.assign({}, stateProps, dispatchProps, ownProps, {
asyncFetch: () => {
dispatchProps.fetchData(stateProps.filters, ownProps.keywords);
},
});
}
export default
injectIntl(
connect(mapStateToProps, mapDispatchToProps, mergeProps)(
composeAsyncContainer(
KeywordSearchResultsContainer
)
)
);
| JavaScript | 0.000003 | @@ -967,61 +967,8 @@
ps;%0A
- console.log(%60search for $%7BnextProps.keywords%7D%60);%0A
|
2620967387f88dde892e20860ea1ad4339c8ccbe | call -> apply, in diana.createUtilLogger() | app/jobs/prototype.js | app/jobs/prototype.js | 'use strict';
require(__dirname + '/../modules/diana');
exports.extend = function(subType, props) {
diana.shared.Lang.inheritPrototype(subType, Job);
subType.prototype.__super__ = Job;
_.extend(subType.prototype, props);
};
var Job = function() {
var options = {
// Result collection is dropped after the callback receives the content.
dropResultsAfterUse: true,
// Result collection name = "<job name><_suffix>".
suffix: ''
};
// Collection.mapReduce() options.
var mapReduceConfig = {};
/**
* Return a shallow copy of the job's options.
*
* @param updates {Object} Key/value pairs to change.
* @return {Object} The merge result.
*/
this.updateOptions = function(updates) {
return _.extend(options, updates);
};
/**
* Return a shallow copy of the job's options.
*
* @return {Object}
*/
this.getOptions = function() {
return _.clone(options);
};
/**
* Intended for use in run(query, ...) in order to remove option key/value pairs
* that had to be transported in a query object (e.g. from a URL query string).
*
* @param query {Object} Modified in-place.
* @return {Object} Shallow copy of merged options.
*/
this.extractOptionsFromQuery = function(query) {
_.each(this.customOptionKeys, function(key) {
if (_.has(query, key)) {
options[key] = query[key];
delete query[key];
}
});
return _.clone(options);
};
/**
* Return a shallow copy of the job's map reduce configuration.
*
* @param updates {Object} Key/value pairs to change.
* @return {Object} The merge result.
*/
this.updateMapReduceConfig = function(updates) {
return _.extend(mapReduceConfig, updates);
};
/**
* Return a shallow copy of the job's map reduce configuration.
*
* @return {Object}
*/
this.getMapReduceConfig = function() {
return _.clone(mapReduceConfig);
};
this.mongodb = diana.requireModule('mongodb').createInstance();
};
/**
* Job name prefixed results collection name.
*/
Job.prototype.name = '';
/**
* extractOptionsFromQuery(query), if used in run(query, ...), will remove these
* keys from a query object and move them into this.options.
*/
Job.prototype.customOptionKeys = [];
/**
* Calculate an expires based on a job query.
*
* @param query {Object}
* @param now {Number} (Optional) Allow unit tests to avoid Date.getTime() use.
* @return {Number} Seconds.
*/
Job.prototype.getExpires = function(query, now) {
return 60;
};
/**
* Start the map/reduce job.
*
* @param query {Object} MongoDB query object to narrow the map scope.
* @param callback {Function} Fires after success/error.
* - See MongoDB.mapReduce() for arguments notes.
*/
Job.prototype.run = function(query, callback) {};
/**
* Default suffix generator for the mapReduce() call in run().
*
* @param query {Object} Query object originally provided to run().
* @return {String}
*/
Job.prototype.getSuffix = function(query) {
var options = this.getOptions();
return options.suffix || _.sha1(_.extend(options, query));
};
/**
* Wrap a run() callback with a default clean up routine.
*
* @param callback {Function} Callback originally provided to run().
* @return {Function} Callback to supply to mapReduce().
*/
Job.prototype.wrapCallback = function(callback) {
var mongodb = this.mongodb,
options = this.getOptions();
return function(err, results, stats) {
// Avoid the dropCollection() below.
if (!options.dropResultsAfterUse) {
callback(err, results, stats);
return;
}
// mapReduce() has already cached the results by now. Evict the durable copy.
if (stats && stats.collectionName) {
mongodb.dropCollection(stats.collectionName, function() {
callback(err, results, stats);
});
} else {
callback(err, results);
}
};
};
/**
* Wrap a mapReduce() call with default configuration.
*
* @param options {Object} MongoDB.mapReduce() options merged with the default.
* - Default: {query: query}
* @param callback {Function}
*/
Job.prototype.mapReduce = function(query, callback) {
this.mongodb.mapReduce({
name: this.name,
map: this.map,
reduce: this.reduce,
options: _.extend({query: query}, this.getMapReduceConfig()),
return: 'array',
suffix: this.getSuffix(query),
callback: this.wrapCallback(callback)
});
};
/**
* Build the key of the sorted set which indexes this job's results.
*
* Ex. 'graph:CountAllPartitioned:json:3600000'.
*/
Job.prototype.buildSortedSetKey = function() { return ''; };
/**
* Build the key of hash which holds a specific map reduce result.
*
* Ex. 'graph:CountAllPartitioned:json:3600000:result:2012-02'
*
* @param resultKey {String} Ex. '2012-02'.
* @return {String}
*/
Job.prototype.buildHashKey = function(namespace, resultKey) {
return this.buildSortedSetKey(namespace) + ':result:' + resultKey;
};
/**
* Build the key of hash which holds a specific map reduce result.
*
* Ex. 'graph:CountAllPartitioned:json:3600000:result:2012-02'
*
* @param resultKey {String} Ex. '2012-02'.
* @return {String}
*/
Job.prototype.buildLastIdKey = function(namespace) {
return namespace + ':' + this.name + ':lastId';
};
/**
* Curry diana.createUtilLogger() with the job's name.
*
* @return {Function}
*/
Job.prototype.createUtilLogger = function() {
var args = Array.prototype.slice.call(arguments);
args.unshift(this.name);
return diana.createUtilLogger.call(null, arguments);
};
/**
* Placeholders.
*/
Job.prototype.map = function() {};
Job.prototype.reduce = function(key, values) {};
| JavaScript | 0 | @@ -5498,20 +5498,21 @@
lLogger.
-call
+apply
(null, a
@@ -5513,21 +5513,16 @@
ull, arg
-ument
s);%0A%7D;%0A%0A
|
4997fc27ff78d7ce83c4b035e375b6b2f23c4b32 | update decode of multigameindication | src/xseries/xpacket.js | src/xseries/xpacket.js | var _ = require('lodash');
var XBytes = require('./xbytes');
var calc = require('../xseries/utilities');
class XPacket {
constructor(byteArray) {
if (byteArray == undefined) {
throw new Error("byteArray is null or undefined");
}
if(byteArray.length < 2) {
throw new Error("length must be larger than 2");
}
if (byteArray[0] != 0xFF) {
throw new Error("array must start with 0xFF");
}
if (!_.isMatch([0x00, 0x10, 0x11, 0x22], byteArray[1])) {
throw new Error("unknown datablock type")
}
this.byteArray = byteArray;
this.validCRC = this.CalculateValidCRC(byteArray);
}
CalculateValidCRC(byteArray) {
var array = this.byteArray.slice(1, 126);
var expected = this.byteArray.slice(126, 128);
var checksum = calc.calculateChecksum(array);
var validCRC = _.isEqual(checksum, expected);
// console.log(validCRC);
return validCRC;
}
getBytes(startByte, endByte) {
if (endByte == undefined) {
endByte = startByte
}
if (startByte < 0) {
throw new Error("startByte param must equal zero or more!");
}
if (endByte < startByte) {
throw new Error("endByte param must be larger than startByte!")
}
var slice = this.byteArray.slice(startByte, endByte + 1);
return new XBytes(slice, startByte, endByte);
}
getType() {
switch (this.byteArray[1]) {
case 0x00:
return "SDB"
case 0x10:
return "PDB1"
case 0x11:
return "PDB2"
case 0x22:
return "MDB"
default:
return "UNKNOWN"
}
}
_percentage(startByte, endByte) {
var bytesObj = this.getBytes(startByte, endByte);
return {
byteRange: startByte + '-' + endByte,
hex: bytesObj.rawData(),
value: bytesObj.asPercentage(),
};
}
_ASCII(startByte, endByte) {
var bytesObj = this.getBytes(startByte, endByte);
return {
byteRange: startByte + '-' + endByte,
hex: bytesObj.rawData(),
value: bytesObj.asASCII(),
};
}
_currency(startByte, endByte) {
var bytesObj = this.getBytes(startByte, endByte);
return {
byteRange: startByte + '-' + endByte,
hex: bytesObj.rawData(),
value: bytesObj.asCurrency(),
};
}
_version(startByte, endByte) {
var bytesObj = this.getBytes(startByte, endByte);
return {
byteRange: startByte + '-' + endByte,
hex: bytesObj.rawData(),
value: bytesObj.asVersion(),
};
}
_SDBData() {
return {
configData: {
version: this._version(2, 3),
MultiGameIndication: this.getBytes(14, 15).asBCD().join(""),
BCV: this._currency(84, 85),
PID1: this._ASCII(87, 94),
PID2: this._ASCII(95, 102),
PID3: this._ASCII(103, 110),
PID4: this._ASCII(111, 118),
RTP: this._percentage(119, 120),
},
meterData: {
// To do
}
};
}
_PDB1Data() {
return {
configData: {
version: this._version(2, 3),
NrLevels: this.getBytes(14).asSingleValue(),
IncPCTLvl1: this._percentage(15, 18),
IncPCTLvl2: this._percentage(19, 22),
IncPCTLvl3: this._percentage(23, 26),
IncPCTLvl4: this._percentage(27, 30),
JPRTP: this._percentage(31, 34),
PID1: this._ASCII(71, 78),
PID2: this._ASCII(79, 86),
PID3: this._ASCII(87, 94),
PID4: this._ASCII(95, 102),
},
meterData: {
// To do
}
};
}
_PDB2Data() {
return {
configData: {
version: this._version(2, 3),
ResetLvl1: this._currency(10, 14),
ResetLvl2: this._currency(15, 19),
ResetLvl3: this._currency(20, 24),
ResetLvl4: this._currency(25, 29),
LimitLvl1: this._currency(30, 34),
LimitLvl2: this._currency(35, 39),
LimitLvl3: this._currency(40, 44),
LimitLvl4: this._currency(45, 49),
},
meterData: {
// To do
}
};
}
_MDBData() {
return {
configData: {
ManufacturerID: this.getBytes(2).asBCD().join(""),
},
meterData: {
// To do
}
};
}
_commonData() {
return {
type: this.getType(),
validCRC: this.validCRC,
};
}
asJson() {
var data = this._commonData();
if (data.type === "SDB") {
return Object.assign({}, data, this._SDBData());
}
if (data.type === "PDB1") {
return Object.assign({}, data, this._PDB1Data());
}
if (data.type === "PDB2") {
return Object.assign({}, data, this._PDB2Data());
}
if (data.type === "MDB") {
return Object.assign({}, data, this._MDBData());
}
return data;
}
}
module.exports = XPacket; | JavaScript | 0.000007 | @@ -3053,24 +3053,157 @@
eIndication:
+ %7B%0A byteRange: 14 + '-' + 15,%0A hex: this.getBytes(14, 15).rawData(),%0A value:
this.getByt
@@ -3223,32 +3223,51 @@
BCD().join(%22%22),%0A
+ %7D,%0A
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.