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 |
|---|---|---|---|---|---|---|---|
b54012553db3d39a72b8ea3babd606de92b49fc2 | Remove babel-polyfill | local_modules/peercast-yp-channels-parser/webpack.config.js | local_modules/peercast-yp-channels-parser/webpack.config.js | const webpack = require("webpack");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const failPlugin = require("webpack-fail-plugin");
const uglifySaveLicense = require("uglify-save-license");
const isProduction = process.env.NODE_ENV === "production";
function tsModule(targets) {
return {
rules: [{
test: /\.tsx?$/,
use: [
{
loader: "babel-loader",
options: {
env: {
delelopment: {
plugins: [[
"babel-plugin-espower",
{ "embedAst": true }
]]
},
production: {
presets: ["babili"]
}
},
presets: [["env", { targets }]]
}
},
{
loader: "ts-loader",
options: { compilerOptions: { sourceMap: !isProduction } }
}
]
}]
};
}
module.exports = {
devtool: isProduction
? false
: "inline-source-map",
entry: {
index: ["babel-polyfill", "./src/index.ts"],
"test/test": ["babel-polyfill", "./src/test/test.ts"]
},
externals: /^(?!\.)/,
module: tsModule({ node: 6 }),
node: {
__filename: true,
__dirname: true
},
output: {
filename: "lib/[name].js",
libraryTarget: "commonjs2"
},
plugins: isProduction
? [failPlugin]
: [],
resolve: { extensions: [".ts", ".tsx", ".js"] },
target: "node"
};
| JavaScript | 0.000001 | @@ -1318,35 +1318,16 @@
index:
- %5B%22babel-polyfill%22,
%22./src/
@@ -1335,17 +1335,16 @@
ndex.ts%22
-%5D
,%0A
|
8a9fc816325a7a70548e916a110c748bfaa54928 | Adding location question | src/RecruiterQuestions.js | src/RecruiterQuestions.js | import React, { Component } from 'react';
import './style/recruiter.css';
var questions = [
{
question: "Are you willing to relocate?",
answer: "I have grown roots in the Dallas/Fort Worth metroplex and will not move my family. I am not interested in opportunities that involve relocation at this time."
},
{
question: "Will you travel for work?",
answer: "Occasional travel for team building or co-located sites will not be a problem. Weekly travel for work is not acceptable for my family's needs."
},
{
question: "What is your compensation range?",
answer: "For full-time salary, I'm looking for $130,000 plus benefits, PTO, and bonus. For contracting, I am interested in $80/hour as W2, or corp-to-corp contracting through my company Hemera, Inc. at $150/hour."
},
{
question: "Are you willing to telecommute?",
answer: "After working from home for several years, I've determined I prefer having an office with face-to-face interactions. I am not interested in telecommute positions at this time. "
},
{
question:"What perks interest you?",
answer: "Strong benefits offering with excellent health care, FSA, DCA, vision, and education reimbursement such as Lynda.com or Safari Online. Option to occasionally work from home. On-site gym or fitness center. Core schedule with no production support requirements (no after-hours). "
},
{
question:"What job title's interest you?",
answer:"Software Architect, Principal Architect, or Technical Lead."
},
{
question: "Could you describe your ideal job?",
answer: "Casual atmosphere practicing Agile methodologies on cutting edge micro-service cloud technologies with a DevOps team, IT Ops, QA team and Dev team. Code coverage would be in the 90% range with full automated CI deployment to stage and production. Runbooks for production issues are well prepared and technical writers are developing documentation with the architecture staff. Production outages are non-existent with a 5 sigma uptime and production updates occur via automated daytime executions. While this is my ideal job, I am realistic about this being the ultimate goal of a software team and not a commonly found reality. I have not yet participated in such a job (or I would still be there). "
}
];
class RecruiterQuestions extends Component {
render() {
return (
<table className="recruiter-questions">
<tbody>
{questions.map(function(entry, index) {
var cssClassName = (index % 2 === 0) ? 'alternate' : 'normal';
return <tr className={cssClassName} key={index}><td>{entry.question}</td><td className="recruiter-answer">{entry.answer}</td></tr>;
})}
</tbody>
</table>
);
}
}
export default RecruiterQuestions; | JavaScript | 0.999902 | @@ -87,16 +87,292 @@
ns = %5B%0A%0A
+ %7B%0A question: %22Where are you located?%22,%0A answer: %22I live in northeast Fort Worth near North Richland Hills in the 76118 zip code. For my commute, portions of Dallas are more accessible than southwest Fort Worth. Please see my commute page for my commute range.%22%0A %7D,%0A
%7B%0A
@@ -1780,16 +1780,33 @@
chitect,
+ DevOps Engineer,
or Tech
|
dda27746b180d1f427ef4894ec54189977ae0885 | Fix emitter | src/behaviours/DamageEmitter.js | src/behaviours/DamageEmitter.js | import Phaser from 'phaser';
import Behaviour from './Behaviour';
const SMOKE_LIFETIME = 500; // milliseconds
export default class extends Behaviour {
constructor(game, owner) {
super(game, owner);
this.smokeEmitter = game.add.emitter(-7, -12, 10);
// Make particles fade out after 1000ms
this.smokeEmitter.setAlpha(1, 0, SMOKE_LIFETIME, Phaser.Easing.Linear.InOut);
// Create the actual particles
this.smokeEmitter.makeParticles('damage', 2);
this.owner.addChild(this.smokeEmitter);
}
update() {
// @TODO: Not sure that's the most elegant way of starting this...
// (makes it run on intro otherwise)
if (!this.smokeEmitter.on && this.owner.health <= 80) {
this.smokeEmitter.start(false, SMOKE_LIFETIME, 50);
this.smokeEmitter.on = true;
} else if (this.smokeEmitter && this.owner.health > 80) {
this.smokeEmitter.on = false;
}
}
}
| JavaScript | 0.000003 | @@ -767,43 +767,8 @@
0);%0A
- this.smokeEmitter.on = true;%0A
|
6b61da7f9731b0014b3e3ced95b88d9054639fdb | Update header.client.controller.js | modules/core/client/controllers/header.client.controller.js | modules/core/client/controllers/header.client.controller.js | (function () {
'use strict';
angular
.module('core')
.controller('HeaderController', HeaderController);
HeaderController.$inject = ['$scope', '$state', 'Authentication', 'menuService'];
function HeaderController($scope, $state, Authentication, menuService) {
var vm = this;
vm.accountMenu = menuService.getMenu('account').items[0];
vm.authentication = Authentication;
vm.isCollapsed = false;
vm.menu = menuService.getMenu('topbar');
$scope.$on('$stateChangeSuccess', stateChangeSuccess);
function stateChangeSuccess() {
// Collapsing the menu after navigation
vm.isCollapsed = false;
}
}
}());
| JavaScript | 0 | @@ -465,16 +465,173 @@
opbar');
+%0A %0A function consentpage() %7B%0A if (document.URL.contains(%22consent-form%22)) %7B%0A return false;%0A %7D else %7B%0A return true;%0A %7D%0A %7D
%0A%0A $s
|
824c220f299c935dbbf5e410f6e3446c970daf7d | add onClick test to Candidate component | src/components/CandidateList/Candidate.spec.js | src/components/CandidateList/Candidate.spec.js | /* eslint-env mocha */
var React = require('react');
var expect = require('expect');
var enzyme = require('enzyme');
var Candidate = require('./Candidate');
var mockDetals = {
name: 'Test Candidate',
birthDate: '1990-03-08'
};
var mockExperience = [
{
company: 'RobCo Industries Inc.',
position: 'Business Analyst',
startDate: '2012-08-05',
endDate: '2016-04-30',
summary: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'
}
];
describe('<Candidate>', function () {
var wrapper;
beforeEach(function () {
wrapper = enzyme.shallow(<Candidate details={mockDetals} experience={mockExperience}/>);
});
it('displays the candidate\'s name', function () {
expect(wrapper.find('.candidate__name').text()).toEqual(mockDetals.name);
});
it('does not show candidate details by default', function () {
expect(wrapper.find('.candidate__details').prop('open')).toBe(undefined);
});
});
| JavaScript | 0 | @@ -1317,13 +1317,231 @@
);%0A %7D);
+%0A%0A it('shows candidate details when candidate name is clicked', function () %7B%0A wrapper.find('.candidate__name').simulate('click');%0A expect(wrapper.find('.candidate__details').prop('open')).toBe(undefined);%0A %7D);
%0A%7D);%0A
|
ce168556771417414e2cec2d54493a6493bb0509 | Enable links on trackerdash dashboard page to the dataset items | src/ResultTablePane.js | src/ResultTablePane.js | trackerdash.views.ResultTablePane = Backbone.View.extend({
el: '.result-table-pane',
initialize: function (settings) {
this.results = settings.percentErrorByDataset;
this.datasetMap = settings.datasetMap;
this.trajectoryMap = settings.trajectoryMap;
if (this.results === undefined) {
console.error('No error percentages defined.');
}
this.render();
},
render: function () {
// dots in names confound css selectors
_.each(this.results, _.bind(function (result) {
result.id = result.dataset.replace(/\./g, "_");
this.datasetMap[result.id] = this.datasetMap[result.dataset];
this.trajectoryMap[result.id] = this.trajectoryMap[result.dataset];
}, this));
var resultsByDatasetId = _.groupBy(this.results, function (result) {
return result.id;
});
this.$el.html(jade.templates.tablePane({
resultsByDatasetId: resultsByDatasetId,
datasetMap: this.datasetMap,
trajectoryMap: this.trajectoryMap
}));
this.$el.promise().done(_.bind(function () {
_.each(this.results, function (result) {
// render bullets
new trackerdash.views.ErrorBulletWidget({
el: '#' + result.id + '-' + result.metric + ' svg',
result: result
});
// activate callback for bullet if specified
if (typeof(result.callback) === 'function') {
$('#' + result.id + '-' + result.metric)
.css('cursor', 'pointer')
.click(result.callback);
}
});
_.each(this.datasetMap, function (value, key) {
if (typeof(value) === 'function') {
$('#' + key + '-link').click(value);
}
});
_.each(this.trajectoryMap, function (value, key) {
if (typeof(value) === 'function') {
$('#' + key + '-trajectory-link').click(value);
}
});
}, this));
}
});
| JavaScript | 0 | @@ -221,16 +221,22 @@
tasetMap
+ %7C%7C %7B%7D
;%0A
@@ -280,16 +280,22 @@
ctoryMap
+ %7C%7C %7B%7D
;%0A
|
b2aab80eb7f2cd48776c790e13dd1333ee241b4f | Change to use Angular $document. | src/angular-no-captcha.js | src/angular-no-captcha.js | 'use strict';
angular.module('noCAPTCHA', [])
.service('googleGrecaptcha', ['$q', '$window', function GoogleGrecaptchaService($q, $window) {
var deferred = $q.defer();
$window.recaptchaOnloadCallback = function () {
deferred.resolve();
};
var s = document.createElement('script');
s.src = 'https://www.google.com/recaptcha/api.js?onload=recaptchaOnloadCallback&render=explicit';
document.body.appendChild(s);
return deferred.promise;
}])
.provider('noCAPTCHA', function NoCaptchaProvider() {
var siteKey,
theme;
this.setSiteKey = function(_siteKey){
siteKey = _siteKey;
};
this.setTheme = function(_theme){
theme = _theme;
};
this.$get = [function NoCaptchaFactory() {
return {
theme: theme,
siteKey: siteKey
}
}];
})
.directive('noCaptcha', ['noCAPTCHA','googleGrecaptcha', function(noCaptcha, googleGrecaptcha){
return {
restrict:'EA',
scope: {
gRecaptchaResponse:'=',
siteKey:'@',
theme:'@',
control:'=',
expiredCallback: '='
},
replace: true,
link: function(scope, element) {
var widgetId,
grecaptchaCreateParameters,
control = scope.control || {};
grecaptchaCreateParameters = {
sitekey: scope.siteKey || noCaptcha.siteKey,
theme: scope.theme || noCaptcha.theme,
callback: function(r){
scope.$apply(function(){
scope.gRecaptchaResponse = r;
});
},
'expired-callback': function () {
if (scope.expiredCallback && typeof (scope.expiredCallback) === 'function') {
scope.$apply(function () {
scope.expiredCallback();
});
}
}
};
if(!grecaptchaCreateParameters.sitekey){
throw new Error('Site Key is required');
}
googleGrecaptcha.then(function(){
widgetId = grecaptcha.render(
element[0],
grecaptchaCreateParameters
);
control.reset = function(){
grecaptcha.reset(widgetId);
scope.gRecaptchaResponse = null;
};
});
scope.$on('$destroy', function(){
grecaptcha.reset(widgetId);
});
}
};
}]);
| JavaScript | 0 | @@ -88,16 +88,29 @@
window',
+ '$document',
functio
@@ -146,16 +146,27 @@
$window
+, $document
) %7B%0A
@@ -291,16 +291,17 @@
var s =
+$
document
@@ -428,20 +428,21 @@
licit';%0A
-
+$
document
|
9d54f181edbd2bb4fea3b3b6de6a73b8f52a9a34 | add default values to duration, options for click guard | common/components/utils/guard.js | common/components/utils/guard.js | // @ flow
// helpers to guard against accidental/unwanted repeatedly submitted actions, etc
import _ from 'lodash';
class Guard {
static click(func: string, duration: number, options: object): string {
return _.debounce(func, duration, options)
}
}
export default Guard;
| JavaScript | 0 | @@ -161,16 +161,23 @@
duration
+ = 1000
: number
@@ -185,16 +185,36 @@
options
+ = %7B'leading': true%7D
: object
|
aaa915c5211fdbfca302df1ccb6410f227e0bd24 | use match in client rendering to wait for async route | src/client.js | src/client.js | import React from 'react';
import ReactDOM from 'react-dom';
import useScroll from 'scroll-behavior/lib/useStandardScroll';
import { Router, browserHistory, useRouterHistory } from 'react-router';
import getRoutes from './routes';
import createBrowserHistory from 'history/lib/createBrowserHistory';
const createScrollHistory = useScroll(createBrowserHistory);
const appHistory = useRouterHistory(createScrollHistory)();
import { Provider } from 'react-redux';
import createStore from './createStore';
const store = createStore(window.__INITIAL_STATE__);
ReactDOM.render(
<Provider store={store}>
<Router routes={getRoutes(store)} history={appHistory} />
</Provider>
, document.getElementById('app')); | JavaScript | 0 | @@ -127,16 +127,23 @@
import %7B
+ match,
Router,
@@ -561,16 +561,187 @@
TE__);%0A%0A
+const routes = getRoutes(store);%0Aconst %7B pathname, search, hash %7D = window.location;%0Aconst location = %60$%7Bpathname%7D$%7Bsearch%7D$%7Bhash%7D%60;%0A%0Amatch(%7B routes, location %7D, () =%3E %7B%0A%09
ReactDOM
@@ -749,16 +749,17 @@
render(%0A
+%09
%09%3CProvid
@@ -778,16 +778,17 @@
ore%7D%3E%0A%09%09
+%09
%3CRouter
@@ -795,32 +795,22 @@
routes=%7B
-getR
+r
outes
-(store)
%7D histor
@@ -827,16 +827,17 @@
ory%7D /%3E%0A
+%09
%09%3C/Provi
@@ -841,16 +841,17 @@
ovider%3E%0A
+%09
%09, docum
@@ -877,8 +877,12 @@
'app'));
+%0A%7D);
|
5e62b2ce3836120117ee1feae7e19eafdaef073b | Implement delete function for azure adapter | api/src/lib/storage-adapter/azure.js | api/src/lib/storage-adapter/azure.js | const { BlobServiceClient, StorageSharedKeyCredential } = require('@azure/storage-blob');
const sharedKeyCredential = new StorageSharedKeyCredential(
process.env.AZURE_STORAGE_ACCOUNT,
process.env.AZURE_STORAGE_ACCESS_KEY
);
const blobServiceClient = new BlobServiceClient(
`https://${process.env.AZURE_STORAGE_ACCOUNT}.blob.core.windows.net`,
sharedKeyCredential
);
// [Node.js only] A helper method used to read a Node.js readable stream into string
async function streamToString(readableStream) {
return new Promise((resolve, reject) => {
const chunks = [];
readableStream.on("data", (data) => {
chunks.push(data.toString());
});
readableStream.on("end", () => {
resolve(chunks.join(""));
});
readableStream.on("error", reject);
});
}
module.exports = {
async upload(stream, blobName, contentType) {
const containerClient = blobServiceClient.getContainerClient(process.env.OIDC_AZURE_STORAGE_CONTAINER);
const blockBlobClient = containerClient.getBlockBlobClient(blobName);
const options = {
blobHTTPHeaders: {
blobContentType: contentType,
blobCacheControl: 'public, must-revalidate, proxy-revalidate, max-age=0'
}
};
await blockBlobClient.uploadStream(
stream,
undefined, // Keep default bufferSize
undefined, // Keep default maxConcurrency
options
);
const filename = (
`https://${process.env.AZURE_STORAGE_ACCOUNT}.blob.core.windows.net/` +
`${process.env.OIDC_AZURE_STORAGE_CONTAINER}/${blobName}`
);
return filename;
},
async get(container, blob) {
const containerClient = blobServiceClient.getContainerClient(container);
const blobClient = containerClient.getBlobClient(blob);
const downloadBlockBlobResponse = await blobClient.download();
const downloaded = await streamToString(downloadBlockBlobResponse.readableStreamBody);
return downloaded;
},
delete() {
},
};
| JavaScript | 0.000001 | @@ -1946,20 +1946,341 @@
delete(
-) %7B%0A
+pathToBlob) %7B%0A const blobName = pathToBlob.replace(%60$%7Bprocess.env.OIDC_AZURE_STORAGE_CONTAINER%7D/%60, '');%0A const containerClient = blobServiceClient.getContainerClient(process.env.OIDC_AZURE_STORAGE_CONTAINER);%0A const blockBlobClient = containerClient.getBlockBlobClient(blobName);%0A return blockBlobClient.delete();
%0A %7D,%0A%7D;
|
9d94e4c35f4f038eb10c6139aa78e8fb4d69f0d5 | Update src | src/client.js | src/client.js | import feathers from 'feathers/client';
import socketio from 'feathers-socketio/client';
import primus from 'feathers-primus/client';
import rest from 'feathers-rest/client';
import authentication from 'feathers-authentication/client';
import hooks from 'feathers-hooks';
Object.assign(feathers, { socketio, primus, rest, hooks, authentication });
export default feathers;
| JavaScript | 0 | @@ -164,24 +164,60 @@
st/client';%0A
+import hooks from 'feathers-hooks';%0A
import authe
@@ -268,44 +268,8 @@
nt';
-%0Aimport hooks from 'feathers-hooks';
%0A%0AOb
|
f57b317defcfd829d10d98f510789b1ba7ec9426 | Fix serializer | src/client.js | src/client.js | var EventEmitter = require('events').EventEmitter;
var debug = require('./debug');
var createSerializer = require("./transforms/serializer").createSerializer;
var createDeserializer = require("./transforms/serializer").createDeserializer;
class Client extends EventEmitter {
serializer;
deserializer;
isServer;
constructor(isServer) {
super();
this.isServer = !!isServer;
}
setSerializer() {
this.serializer = createSerializer(isServer: this.isServer);
this.deserializer = createDeserializer(isServer: this.isServer);
this.serializer.on('error', (e) => {
var parts = e.field.split(".");
parts.shift();
var serializerDirection = !this.isServer ? 'toServer' : 'toClient';
e.field = [this.protocolState, serializerDirection].concat(parts).join(".");
e.message = `Serialization error for ${e.field} : ${e.message}`;
this.emit('error', e);
});
this.deserializer.on('error', (e) => {
var parts = e.field.split(".");
parts.shift();
var deserializerDirection = this.isServer ? 'toServer' : 'toClient';
e.field = [deserializerDirection].concat(parts).join(".");
e.message = `Deserialization error for ${e.field} : ${e.message}`;
this.emit('error', e);
});
this.deserializer.on('data', (parsed) => {
parsed.metadata.name = parsed.data.name;
parsed.data = parsed.data.params;
this.emit('packet', parsed.data, parsed.metadata);
this.emit(parsed.metadata.name, parsed.data, parsed.metadata);
this.emit('raw.' + parsed.metadata.name, parsed.buffer, parsed.metadata);
this.emit('raw', parsed.buffer, parsed.metadata);
});
}
setSocket(socket) {
var ended = false;
var endSocket = () => {
if (ended) return;
ended = true;
this.socket.removeListener('close', endSocket);
this.socket.removeListener('end', endSocket);
this.socket.removeListener('timeout', endSocket);
this.emit('end', this._endReason);
};
var onFatalError = (err) => {
this.emit('error', err);
endSocket();
};
var onError = (err) => this.emit('error', err);
this.socket = socket;
if (this.socket.setNoDelay)
this.socket.setNoDelay(true);
this.socket.on('connect', () => this.emit('connect'));
this.socket.on('error', onFatalError);
this.socket.on('close', endSocket);
this.socket.on('end', endSocket);
this.socket.on('timeout', endSocket);
this.splitter.on('error', onError);
this.socket.pipe(this.splitter).pipe(this.deserializer);
this.serializer.pipe(this.framer).pipe(this.socket);
}
end(reason) {
this._endReason = reason;
if (this.socket) this.socket.end();
}
write(name, params) {
debug("writing packet " + this.state + "." + name);
debug(params);
this.serializer.write({
name,
params
});
}
writeRaw(buffer) {
if (this.compressor === null)
this.framer.write(buffer);
else
this.compressor.write(buffer);
}
}
module.exports = Client; | JavaScript | 0.000039 | @@ -445,34 +445,24 @@
eSerializer(
-isServer:
this.isServe
@@ -512,18 +512,8 @@
zer(
-isServer:
this
|
18e8f3ab9e6a60034707dee4053e54a5726bb3ac | Fix syntax error. | grade/edit/tree/functions.js | grade/edit/tree/functions.js | /**
* Toggles the selection checkboxes of all grade items children of the given eid (a category id)
*/
function togglecheckboxes(eid, value) {
var rows = YAHOO.util.Dom.getElementsByClassName(eid);
for (var i = 0; i < rows.length; i++) {
var element = new YAHOO.util.Element(rows[i]);
var checkboxes = element.getElementsByClassName('itemselect');
if (checkboxes[0]) {
checkboxes[0].checked=value;
}
}
toggleCategorySelector();
}
function toggle_advanced_columns() {
var advEls = YAHOO.util.Dom.getElementsByClassName("advanced");
var shownAdvEls = YAHOO.util.Dom.getElementsByClassName("advancedshown");
for (var i = 0; i < advEls.length; i++) {
YAHOO.util.Dom.replaceClass(advEls[i], "advanced", "advancedshown");
}
for (var i = 0; i < shownAdvEls.length; i++) {
YAHOO.util.Dom.replaceClass(shownAdvEls[i], "advancedshown", "advanced");
}
}
/**
* Check if any of the grade item checkboxes is ticked. If yes, enable the dropdown. Otherwise, disable it
*/
function toggleCategorySelector() {
var itemboxes = YAHOO.util.Dom.getElementsByClassName('itemselect');
for (var i = 0; i < itemboxes.length; i++) {
if (itemboxes[i].checked) {
document.getElementById('menumoveafter').disabled = false;
return true;
}
document.getElementById('menumoveafter').disabled = 'disabled';
}
YAHOO.namespace('grade_edit_tree');
(function() {
var Dom = YAHOO.util.Dom;
var DDM = YAHOO.util.DragDropMgr;
var Event = YAHOO.util.Event;
var gretree = YAHOO.grade_edit_tree;
gretree.DDApp = {
init: function() {
var edit_tree_table = Dom.get('grade_edit_tree_table');
var i;
var item_rows = edit_tree_table.getElementsByClassName('item', 'tr');
var category_rows = edit_tree_table.getElementsByClassName('category', 'tr');
new YAHOO.util.DDTarget('grade_edit_tree_table');
for (i = 0; i < item_rows.length; i++) {
if (!Dom.hasClass(item_rows[i],'categoryitem')) {
new gretree.DDList(item_rows[i]);
}
}
for (i = 0; i < category_rows.length; i++) {
if (!Dom.hasClass(category_rows[i],'coursecategory')) {
// Find the cell that spans rows for this category
var rowspancell = category_rows[i].getElementsByClassName('name', 'td');
var rowspan = parseInt(rowspancell[0].previousSibling.rowSpan) + 1;
var rows = Array(rowspan);
var lastRow = category_rows[i];
for (var j = 0; j < rowspan; j++) {
rows[j] = lastRow;
lastRow = lastRow.nextSibling;
}
new gretree.DDList(rows);
}
}
YAHOO.util.Event.on("showButton", "click", this.showOrder);
YAHOO.util.Event.on("switchButton", "click", this.switchStyles);
},
showOrder: function() {
var parseTable = function(table, title) {
var items = table.getElementsByTagName('tr');
var out = title + ": ";
for (i = 0; i < items.length; i++) {
out += items[i].id + ' ';
}
return out;
};
var table = Dom.get('grade_edit_tree_table');
alert(parseTable(table, "Grade edit tree table"));
},
switchStyles: function() {
Dom.get('grade_edit_tree_table').className = 'draglist_alt';
}
};
gretree.DDList = function(id, sGroup, config) {
gretree.DDList.superclass.constructor.call(this, id, sGroup, config);
this.logger = this.logger || YAHOO;
var el = this.getDragEl();
Dom.setStyle(el, 'opacity', 0.67);
this.goingUp = false;
this.lastY = 0;
};
YAHOO.extend(gretree.DDList, YAHOO.util.DDProxy, {
startDrag: function(x, y) {
this.logger.log(this.id + ' startDrag');
// Make the proxy look like the source element
var dragEl = this.getDragEl();
var clickEl = this.getEl();
Dom.setStyle(clickEl, 'visibility', 'hidden');
dragEl.innerHTML = clickEl.innerHTML;
Dom.setStyle(dragEl, 'color', Dom.getStyle(clickEl, 'color'));
Dom.setStyle(dragEl, 'backgroundColor', Dom.getStyle(clickEl, 'backgroundColor'));
Dom.setStyle(dragEl, 'border', '2px solid gray');
},
endDrag: function(e) {
this.logger.log(this.id + ' endDrag');
var srcEl = this.getEl();
var proxy = this.getDragEl();
// Show the proxy element and adnimate it to the src element's location
Dom.setStyle(proxy, 'visibility', '');
var a = new YAHOO.util.Motion(proxy, { points: { to: Dom.getXY(srcEl) } }, 0.2, YAHOO.util.Easing.easeOut);
var proxyid = proxy.id;
var thisid = this.id;
// Hide the proxy and show the source element when finished with the animation
a.onComplete.subscribe(function() {
Dom.setStyle(proxyid, 'visibility', 'hidden');
Dom.setStyle(thisid, 'visibility', '');
});
a.animate();
},
onDragDrop: function(e, id) {
this.logger.log(this.id + ' dragDrop');
// If there is one drop interaction, the tr was dropped either on the table, or it was dropped on the current location of the source element
if (DDM.interactionInfo.drop.length === 1) {
// The position of the cursor at the time of the drop (YAHOO.util.Point)
var pt = DDM.interactionInfo.point;
// The region occupied by the source element at the time of the drop
var region = DDM.interactionInfo.sourceRegion;
// Check to see if we are over the source element's location. We will append to the bottom of the list once we are sure it was a drop in the negative space
if (!region.intersect(pt)) {
var destEl = Dom.get(id);
var destDD = DDM.getDDById(id);
destEl.appendChild(this.getEl());
destDD.isEmpty = false;
DDM.refreshCache();
}
}
},
onDrag: function(e) {
// Keep track of the direction of the drag for use during onDragOver
var y = Event.getPageY(e);
if (y < this.lastY) {
this.goingUp = true;
} else if (y > this.lastY) {
this.goingUp = false;
}
this.lastY = y;
},
onDragOver: function(e, id) {
var srcEl = this.getEl();
var destEl = Dom.get(id);
// We are only concerned with tr items, we ignore the dragover notifications for the table
if (destEl.nodeName.toLowerCase() == 'tr') {
var orig_p = srcEl.parentNode;
var p = destEl.parentNode;
if (this.goingup) {
p.insertBefore(srcEl, destEl); // insert above
} else {
p.insertBefore(srcEl, destEl.nextSibling); // insert below
}
DDM.refreshCache();
}
}
});
// YAHOO.util.Event.onDOMReady(gretree.DDApp.init, gretree.DDApp, true); // Uncomment this line when dragdrop is fully implemented
})();
| JavaScript | 0.000004 | @@ -1346,24 +1346,34 @@
eturn true;%0A
+ %7D%0A
%7D%0A do
|
15bff37b02e6ce650ac8acecdcde977528b6c05e | Use utf8 encoding when reading files | src/commands/analyse-project.js | src/commands/analyse-project.js | "use strict";
const fs = require("fs");
const vscode = require("vscode");
const minimatch = require("minimatch");
const analyser = require("../complexity-analyzer");
const config = require("../config");
const utils = require("../utils");
const FileAnalysis = require("../models/file-analysis.js");
const ProjectAnalysis = require("../models/project-analysis.js");
const FileReport = require("../report/file-report.js");
const ProjectReport = require("../report/project-report.js");
function AnalyseProject(reportFactory, navigator) {
function findFiles(includePatterns, excludePatterns) {
return vscode.workspace.findFiles("**/*.js", "**/node_modules/**")
.then(files => {
const hasIncludePatterns = includePatterns.length > 0;
const hasExcludePatterns = excludePatterns.length > 0;
return files.filter(file => {
const include = !hasIncludePatterns ||
utils.any(includePatterns, pattern => minimatch(file.path, pattern));
const exclude = hasExcludePatterns &&
utils.any(excludePatterns, pattern => minimatch(file.path, pattern));
return include && !exclude;
});
});
}
function buildReport() {
const project = new ProjectAnalysis();
const include = config.getInclude();
const exclude = config.getExclude();
return findFiles(include, exclude)
.then(files => {
const analysePromises = files.map(file => analyseSingleFile(file, project));
return Promise.all(analysePromises);
}).then(analyses => {
return createAggregateReport(analyses);
});
}
function readFile(file) {
return new Promise((resolve, reject) => {
fs.readFile(file.fsPath, (error, data) => {
if (error) {
return reject(error);
}
return resolve(data);
});
});
}
function analyseSingleFile(file, project) {
const relativePath = vscode.workspace.asRelativePath(file);
return readFile(file)
.then(fileContents => {
try {
const rawAnalysis = analyser.analyse(fileContents);
const analysis = new FileAnalysis(relativePath, rawAnalysis);
const report = new FileReport(analysis);
reportFactory.addReport(relativePath, report);
return analysis;
} catch (e) {
const errorMsg = `File ${ relativePath } analysis failed: ${ e }`;
console.error(errorMsg);
return errorMsg;
}
});
}
function createAggregateReport(analyses, channel, metrics) {
const projectAnalysis = new ProjectAnalysis();
const errors = [];
analyses.forEach(analysis => {
if (typeof analysis !== "string") {
projectAnalysis.add(analysis);
} else {
errors.push(analysis);
}
});
const aggregate = projectAnalysis.getSummary();
const report = new ProjectReport(aggregate, errors);
reportFactory.addReport("/", report);
navigator.navigate("/");
}
function handleError(error) {
vscode.window.showErrorMessage("Failed to analyse file. " + error);
console.log(error);
}
function runAnalysis() {
try {
buildReport()
.then(null, handleError);
} catch (error) {
handleError(error);
}
}
this.execute = runAnalysis;
}
module.exports = AnalyseProject;
| JavaScript | 0.000001 | @@ -1923,16 +1923,24 @@
.fsPath,
+ %22utf8%22,
(error,
|
0eca9f819a1ed1bbeb22294fbc96ca4c21cc1b12 | Create email button | src/components/Sidebar/index.js | src/components/Sidebar/index.js | import React from 'react';
// import LazyLoad from 'react-lazyload';
import Link from 'gatsby-link';
import PropTypes from 'prop-types';
import config from '../../../data/config';
import Information from './Information';
import './index.scss';
const Icon = ({ href, name, content }) => (
<a
target="_blank"
href={href}
rel="external nofollow noopener noreferrer"
className="custom-icon"
>
<span className="fa-stack fa-lg mx-1">
<i className="fa fa-circle fa-stack-2x" />
<i className={`fa fa-stack-1x fa-inverse ${name}`}>{content}</i>
</span>
</a>
);
const Sidebar = ({ post, totalCount, posts }) => (
<header className={`ml-auto mb-4 mx-3 pb-3 intro-header site-heading text-center col-lg-2 col-xs-12 order-lg-1 ${post === true ? 'order-11' : 'order-1'}`} >
<div className="about-me">
<img
className="avatar my-3"
src="https://i.imgur.com/kjt2x52.png"
alt="Calpa"
/>
<Link to="/about/" href="/about" className="name">
<h4>Calpa</h4>
</Link>
<p className="mb-1">夢裡不覺秋已深</p>
<p className="mb-3">餘情豈是為他人</p>
<Icon
href={`https://www.zhihu.com/people/${config.zhihu_username}`}
content="知"
/>
<Icon
href={`https://github.com/${config.github_username}`}
name="fa-github"
/>
<Information
totalCount={totalCount}
posts={posts}
/>
</div>
</header>
);
Sidebar.propTypes = {
post: PropTypes.bool,
totalCount: PropTypes.number,
};
Sidebar.defaultProps = {
post: false,
totalCount: 0,
};
export default Sidebar;
| JavaScript | 0.000006 | @@ -1333,32 +1333,120 @@
ithub%22%0A /%3E%0A
+ %3CIcon%0A href=%7B%60mailto:$%7Bconfig.email%7D%60%7D%0A name=%22fa-envelope%22%0A /%3E%0A
%3CInformati
|
6da017cbb14cbc3ffb2e1b9f8a208459c99b4358 | increase legibility | src/components/TestInterface.js | src/components/TestInterface.js | import React from 'react'
import { render } from 'react-dom';
import { connect } from 'react-redux'
import ace from 'brace';
import AceEditor from 'react-ace';
import 'brace/mode/ruby';
import 'brace/theme/monokai';
import { asyncSubmitCode } from '../redux/modules/userTester'
const TestInterface = (props) => {
const editorName = "test-input-area"
const onClick = () => {
const editor = ace.edit(editorName)
const source = editor.getSession().getValue()
const testId = document.getElementsByClassName('test-interface')[0].dataset.testId
props.dispatch(asyncSubmitCode(source, testId))
}
return (
<div className="problem-window">
<AceEditor
mode="ruby"
theme="monokai"
tabSize={2}
name={editorName}
highlightActiveLine={true}
value={props.inputText}
editorProps={{$blockScrolling: true}}
/>
<button onClick={onClick}>Submit</button>
</div>
)
}
export default connect()(TestInterface)
| JavaScript | 0.000014 | @@ -749,25 +749,70 @@
-name=%7BeditorName%7D
+fontSize=%7B18%7D%0A name=%7BeditorName%7D%0A width=%221200px%22
%0A
|
c6cb0a819ebfb6de8a1670c3f223ab2e1c082b6d | comment cleanup | src/components/form/Dropdown.js | src/components/form/Dropdown.js | // dependencies
//
import React from 'react';
import uniqueId from 'lodash/uniqueId';
import classnames from 'classnames';
/**
* The Dropdown component
*/
class Dropdown extends React.Component {
/**
* Construct the component instance
* @param {Object} props The component props
*/
constructor(props) {
super(props);
// generate a unique ID for this instance
//
this.id = uniqueId('form-dropdown-');
// bind `this` to the event handlers
//
this.isValid = this.isValid.bind(this);
this.onChange = this.onChange.bind(this);
}
/**
* Handle the `onChange` event for the select element
* @param {Object} event The event object
*/
onChange(event) {
// do we have an onChange handler? if so, call it with the appropriate
// value
//
if (this.props.onChange) {
// figure out which value to use
//
let value = this.isValid(event.target.value)
? event.target.value
: '';
if (this.props.options[0] && !value) {
value = this.props.options[0].value;
}
// call the onChange handler with the value
//
this.props.onChange(value);
}
}
/**
* Determine if a value is valid
* @param {String} The value to check
* @return {Boolean} True if the value is valid (ie. found in the array of
* options); false otherwise
*/
isValid(value = this.props.value) {
return this.props.options.findIndex((opt) => opt.value === value) !== -1;
}
/**
* Render the component
* @return {React.Element} The React element describing the component
*/
render() {
// figure out what value to display
//
let value = this.isValid() ? this.props.value : '';
if (this.props.options[0] && !value) {
value = this.props.options[0].value;
}
// generate the label for the component
//
const label = this.props.label
? (
<label
htmlFor={this.id}
className={classnames('control-label', {
[`col-xs-${this.context.labelColumns}`]: this.context.labelColumns,
})}
>
{this.props.label}
</label>
)
: null;
// generate the select element for the component
//
let select = (
<select
id={this.id}
className="form-control"
value={value}
onChange={this.onChange}
>
{this.props.options.map((opt) =>
<option key={uniqueId('form-dropdown-option-')} value={opt.value}>
{opt.name}
</option>
)}
</select>
);
if (this.context.labelColumns) {
select = (
<div
className={classnames(
'form-dropdown-columns',
`col-xs-${12 - this.context.labelColumns}`
)}
>
{select}
</div>
);
}
// return the component
//
return label
? <div className="form-group">{label}{select}</div>
: select;
}
}
// the prop types for the component
//
Dropdown.propTypes = {
label: React.PropTypes.string,
value: React.PropTypes.string,
options: React.PropTypes.array.isRequired,
onChange: React.PropTypes.func,
};
// set the context types for values received from higher up the food chain
//
Dropdown.contextTypes = {
labelColumns: React.PropTypes.number,
};
// export the component
//
export default Dropdown;
| JavaScript | 0 | @@ -2988,24 +2988,163 @@
);%0A%0A
+ // do we have columns for this component? if so, wrap the select element%0A // in a div to implement those columns%0A //%0A
if (
@@ -3168,24 +3168,24 @@
lColumns) %7B%0A
-
@@ -3489,24 +3489,25 @@
;%0A %7D%0A
+%0A
// r
@@ -3658,18 +3658,26 @@
%7D%0A%0A/
-/ t
+**%0A * T
he prop
+erty
typ
@@ -3697,17 +3697,36 @@
mponent%0A
-/
+ * @type %7BObject%7D%0A *
/%0ADropdo
@@ -3911,15 +3911,15 @@
;%0A%0A/
-/ set t
+**%0A * T
he c
@@ -3939,55 +3939,42 @@
for
-values received from higher up the food chain%0A/
+the component%0A * @type %7BObject%7D%0A *
/%0ADr
|
8d0cbdc3ec1bc79d770abcfa5098b9632a6f2aef | Check for android before adding the click handler. | src/components/navbar/Navbar.js | src/components/navbar/Navbar.js | import React, { PropTypes } from 'react'
import classNames from 'classnames'
import { NavbarLabel } from './NavbarLabel'
import { NavbarLayoutTool } from './NavbarLayoutTool'
import { NavbarLink } from './NavbarLink'
import { NavbarMark } from './NavbarMark'
import { NavbarMorePostsButton } from './NavbarMorePostsButton'
import { NavbarOmniButton } from './NavbarOmniButton'
import { NavbarProfile } from './NavbarProfile'
import {
BoltIcon, CircleIcon, GridIcon, ListIcon, SearchIcon, SparklesIcon, StarIcon,
} from './NavbarIcons'
// yuck..
import NotificationsContainer from '../../containers/notifications/NotificationsContainer'
export const NavbarLoggedOut = ({
currentStream,
hasLoadMoreButton,
isLoggedIn,
onClickLoadMorePosts,
onClickNavbarMark,
pathname,
}) =>
<nav className="Navbar" role="navigation" >
<NavbarMark
currentStream={currentStream}
isLoggedIn={isLoggedIn}
onClick={onClickNavbarMark}
/>
<NavbarLabel />
{hasLoadMoreButton ? <NavbarMorePostsButton onClick={onClickLoadMorePosts} /> : null}
<div className="NavbarLinks">
<NavbarLink
className="LabelOnly"
icon={<SparklesIcon />}
label="Discover"
pathname={pathname}
to="/"
/>
<NavbarLink
className="IconOnly"
icon={<SearchIcon />}
label="Search"
pathname={pathname}
to="/search"
/>
<NavbarLink
className="LabelOnly"
label="Log in"
pathname={pathname}
to="/enter"
/>
<NavbarLink
className="LabelOnly isSignUp"
label="Sign up"
pathname={pathname}
to="/signup"
/>
</div>
</nav>
NavbarLoggedOut.propTypes = {
currentStream: PropTypes.string.isRequired,
hasLoadMoreButton: PropTypes.bool.isRequired,
isLoggedIn: PropTypes.bool.isRequired,
onClickLoadMorePosts: PropTypes.func.isRequired,
onClickNavbarMark: PropTypes.func.isRequired,
pathname: PropTypes.string.isRequired,
}
export const NavbarLoggedIn = ({
avatar,
currentStream,
deviceSize,
hasLoadMoreButton,
isGridMode,
isLayoutToolHidden,
isLoggedIn,
isNotificationsActive,
isNotificationsUnread,
isProfileMenuActive,
notificationCategory,
onClickAvatar,
onClickLoadMorePosts,
onClickNavbarMark,
onClickNotification,
onClickOmniButton,
onClickToggleLayoutMode,
onDragLeaveStreamLink,
onDragOverOmniButton,
onDragOverStreamLink,
onDropStreamLink,
onLogOut,
pathname,
username,
}) =>
<nav className="Navbar" role="navigation" >
<NavbarMark
currentStream={currentStream}
isLoggedIn={isLoggedIn}
onClick={onClickNavbarMark}
/>
<NavbarOmniButton
onClick={onClickOmniButton}
onDragOver={onDragOverOmniButton}
/>
{hasLoadMoreButton ? <NavbarMorePostsButton onClick={onClickLoadMorePosts} /> : null}
<div className="NavbarLinks">
<NavbarLink
className="LabelOnly"
icon={<SparklesIcon />}
label="Discover"
pathname={pathname}
to="/discover"
/>
<NavbarLink
className="LabelOnly"
icon={<CircleIcon />}
label="Following"
onDragLeave={onDragLeaveStreamLink}
onDragOver={onDragOverStreamLink}
onDrop={onDropStreamLink}
pathname={pathname}
to="/following"
/>
<NavbarLink
className=""
icon={<StarIcon />}
label="Starred"
onDragLeave={onDragLeaveStreamLink}
onDragOver={onDragOverStreamLink}
onDrop={onDropStreamLink}
pathname={pathname}
to="/starred"
/>
<NavbarLink
className={classNames('IconOnly', { isNotificationsUnread })}
icon={<BoltIcon />}
label="Notifications"
onClick={deviceSize !== 'mobile' ? onClickNotification : null}
pathname={pathname}
to={`/notifications${notificationCategory}`}
/>
<NavbarLink
className="IconOnly"
icon={<SearchIcon />}
label="Search"
pathname={pathname}
to="/search"
/>
</div>
<NavbarProfile
avatar={avatar}
isProfileMenuActive={isProfileMenuActive}
onClickAvatar={onClickAvatar}
onLogOut={onLogOut}
username={username}
/>
{deviceSize === 'mobile' && !isLayoutToolHidden ?
<NavbarLayoutTool
icon={isGridMode ? <ListIcon /> : <GridIcon />}
onClick={onClickToggleLayoutMode}
/> : null
}
{deviceSize !== 'mobile' && isNotificationsActive ?
<NotificationsContainer /> : null
}
</nav>
NavbarLoggedIn.propTypes = {
avatar: PropTypes.shape({}),
currentStream: PropTypes.string.isRequired,
deviceSize: PropTypes.string.isRequired,
hasLoadMoreButton: PropTypes.bool.isRequired,
isGridMode: PropTypes.bool,
isLayoutToolHidden: PropTypes.bool.isRequired,
isLoggedIn: PropTypes.bool.isRequired,
isNotificationsActive: PropTypes.bool.isRequired,
isNotificationsUnread: PropTypes.bool.isRequired,
isProfileMenuActive: PropTypes.bool.isRequired,
notificationCategory: PropTypes.string.isRequired,
onClickAvatar: PropTypes.func.isRequired,
onClickLoadMorePosts: PropTypes.func.isRequired,
onClickNavbarMark: PropTypes.func.isRequired,
onClickNotification: PropTypes.func.isRequired,
onClickOmniButton: PropTypes.func.isRequired,
onClickToggleLayoutMode: PropTypes.func.isRequired,
onDragLeaveStreamLink: PropTypes.func.isRequired,
onDragOverOmniButton: PropTypes.func.isRequired,
onDragOverStreamLink: PropTypes.func.isRequired,
onDropStreamLink: PropTypes.func.isRequired,
onLogOut: PropTypes.func.isRequired,
pathname: PropTypes.string.isRequired,
username: PropTypes.string,
}
| JavaScript | 0 | @@ -70,16 +70,67 @@
snames'%0A
+import %7B isElloAndroid %7D from '../../vendor/jello'%0A
import %7B
@@ -3845,16 +3845,35 @@
nClick=%7B
+isElloAndroid() %7C%7C
deviceSi
@@ -3867,33 +3867,33 @@
) %7C%7C deviceSize
-!
+=
== 'mobile' ? on
@@ -3889,16 +3889,23 @@
obile' ?
+ null :
onClick
@@ -3916,23 +3916,16 @@
fication
- : null
%7D%0A
|
779c291ec8af2e33cc24805b25c2fdbe3d84d742 | Make number component not default to 0, but rather empty string. | src/components/number/Number.js | src/components/number/Number.js | import maskInput from 'vanilla-text-mask';
import _ from 'lodash';
import {createNumberMask} from 'text-mask-addons';
import BaseComponent from '../base/Base';
import {getNumberSeparators, getNumberDecimalLimit} from '../../utils/utils';
export default class NumberComponent extends BaseComponent {
static schema(...extend) {
return BaseComponent.schema({
type: 'number',
label: 'Number',
key: 'number',
validate: {
min: '',
max: '',
step: 'any',
integer: ''
}
}, ...extend);
}
static get builderInfo() {
return {
title: 'Number',
icon: 'fa fa-hashtag',
group: 'basic',
documentation: 'http://help.form.io/userguide/#number',
weight: 10,
schema: NumberComponent.schema()
};
}
constructor(component, options, data) {
super(component, options, data);
this.validators = this.validators.concat(['min', 'max']);
const separators = getNumberSeparators(this.options.language);
this.decimalSeparator = options.decimalSeparator = options.decimalSeparator
|| separators.decimalSeparator;
if (this.component.delimiter) {
if (options.hasOwnProperty('thousandsSeparator')) {
console.warn("Property 'thousandsSeparator' is deprecated. Please use i18n to specify delimiter.");
}
this.delimiter = options.thousandsSeparator || separators.delimiter;
}
else {
this.delimiter = '';
}
this.decimalLimit = getNumberDecimalLimit(this.component);
// Currencies to override BrowserLanguage Config. Object key {}
if (_.has(this.options, `languageOverride.${this.options.language}`)) {
const override = _.get(this.options, `languageOverride.${this.options.language}`);
this.decimalSeparator = override.decimalSeparator;
this.delimiter = override.delimiter;
}
}
get defaultSchema() {
return NumberComponent.schema();
}
get emptyValue() {
return 0;
}
parseNumber(value) {
// Remove delimiters and convert decimal separator to dot.
value = value.split(this.delimiter).join('').replace(this.decimalSeparator, '.');
if (this.component.validate && this.component.validate.integer) {
return parseInt(value, 10);
}
else {
return parseFloat(value);
}
}
setInputMask(input) {
input.setAttribute('pattern', '\\d*');
input.mask = maskInput({
inputElement: input,
mask: createNumberMask({
prefix: '',
suffix: '',
thousandsSeparatorSymbol: _.get(this.component, 'thousandsSeparator', this.delimiter),
decimalSymbol: _.get(this.component, 'decimalSymbol', this.decimalSeparator),
decimalLimit: _.get(this.component, 'decimalLimit', this.decimalLimit),
allowNegative: _.get(this.component, 'allowNegative', true),
allowDecimal: _.get(this.component, 'allowDecimal',
!(this.component.validate && this.component.validate.integer))
})
});
}
elementInfo() {
const info = super.elementInfo();
info.attr.type = 'text';
info.attr.inputmode = 'numeric';
info.changeEvent = 'input';
return info;
}
getValueAt(index) {
if (!this.inputs.length || !this.inputs[index]) {
return null;
}
const val = this.inputs[index].value;
if (!val) {
return null;
}
return this.parseNumber(val);
}
clearInput(input) {
let value = parseFloat(input);
if (!_.isNaN(value)) {
value = String(value).replace('.', this.decimalSeparator);
}
else {
value = null;
}
return value;
}
formatValue(value) {
return value;
}
setValueAt(index, value) {
return super.setValueAt(index, this.formatValue(this.clearInput(value)));
}
focus() {
const input = this.inputs[0];
if (input) {
input.focus();
input.setSelectionRange(0, input.value.length);
}
}
}
| JavaScript | 0.000001 | @@ -1966,17 +1966,18 @@
return
-0
+''
;%0A %7D%0A%0A
|
1bfd27a95211db6d42ee59ceca6cab7696eff83c | use -f options instead of -m when commiting | src/commit.js | src/commit.js | /* eslint no-console: 'off' */
import argv from 'minimist-argv';
import { readFileSync, unlinkSync } from 'fs';
import { execSync, spawnSync } from 'child_process';
import prepareCommitMessage from './prepare-commit-msg';
import notification from './notifications';
export default function () {
['p', 'C', 'c', 'm', 't'].forEach((argKey) => {
if (argv[argKey]) {
console.log(`Argument -${argKey} not supported`);
process.exit(1);
}
});
[
'patch',
'reuse-message',
'reedit-message',
'fixup',
'squash',
'message',
'template',
'amend',
].forEach((argKey) => {
if (argv[argKey]) {
console.log(`Argument --${argKey} not supported`);
process.exit(1);
}
});
argv.path = '#temp_commit';
prepareCommitMessage()
.then(() => {
execSync('$EDITOR \\#temp_commit', { stdio: 'inherit' });
const commitMsg = readFileSync(argv.path);
if (!commitMsg) {
throw new Error('The commit message is empty');
}
spawnSync(
'git',
['commit'].concat(process.argv.slice(2)).concat(`-m${commitMsg}`),
{ stdio: 'inherit' },
);
})
.then(() => {
unlinkSync(argv.path);
})
.catch((msg) => {
notification.failure(msg);
process.exit(1);
});
}
| JavaScript | 0 | @@ -70,22 +70,8 @@
rt %7B
- readFileSync,
unl
@@ -857,146 +857,8 @@
);%0A%0A
- const commitMsg = readFileSync(argv.path);%0A if (!commitMsg) %7B%0A throw new Error('The commit message is empty');%0A %7D%0A%0A
@@ -902,16 +902,34 @@
'commit'
+, %60-F$%7Bargv.path%7D%60
%5D.concat
@@ -955,33 +955,8 @@
(2))
-.concat(%60-m$%7BcommitMsg%7D%60)
,%0A
|
08587fdf198a9a8d6364341e39123f78ac17475b | Update iot-hub.js | IoThub/iot-hub.js | IoThub/iot-hub.js | /*
* IoT Gateway BLE Script - Microsoft Sample Code - Copyright (c) 2016 - Licensed MIT
*/
'use strict';
var EventHubClient = require('azure-event-hubs').Client;
// Close connection to IoT Hub.
IoTHubReaderClient.prototype.stopReadMessage = function() {
this.iotHubClient.close();
}
// Read device-to-cloud messages from IoT Hub.
IoTHubReaderClient.prototype.startReadMessage = function(cb) {
var printError = function(err) {
console.error(err.message || err);
};
var deviceId = process.env['Azure.IoT.IoTHub.DeviceId'];
this.iotHubClient.open()
.then(this.iotHubClient.getPartitionIds.bind(this.iotHubClient))
.then(function(partitionIds) {
return partitionIds.map(function(partitionId) {
return this.iotHubClient.createReceiver(this.consumerGroupName, partitionId, {
'startAfterTime': Date.now()
})
.then(function(receiver) {
receiver.on('errorReceived', printError);
receiver.on('message', (message) => {
var from = message.annotations['iothub-connection-device-id'];
if (deviceId && deviceId !== from) {
return;
}
cb(message.body, Date.parse(message.enqueuedTimeUtc));
});
}.bind(this));
}.bind(this));
}.bind(this))
.catch(printError);
}
function IoTHubReaderClient(connectionString, consumerGroupName) {
this.iotHubClient = EventHubClient.fromConnectionString(connectionString);
this.consumerGroupName = consumerGroupName;
}
module.exports = IoTHubReaderClient;
| JavaScript | 0 | @@ -1449,16 +1449,17 @@
ubClient
+1
= Event
|
fa808c07f2d7471c27e618387cd67f613f185f7f | Fix windows name pipeline issue | src/common.js | src/common.js | 'use strict';
const path = require('path');
const os = require('os');
exports.toNumber = function(x) { return (x = Number(x)) >= 0 ? x : false; };
exports.getSocketPath = function(channel)
{
let pipePath = path.resolve(os.tmpdir(), `.fast.mq.${channel}`);
// use windows named pipe
if (process.platform === 'win32')
{
pipePath = path.replace(/^\//, '');
pipePath = path.replace(/\//g, '-');
pipePath = `\\\\.\\pipe\\${pipePath}`;
}
return pipePath;
};
const pid = (process && process.pid) ? process.pid : 0;
function uuid()
{
var time = Date.now();
var last = uuid.last || time;
uuid.last = time > last ? (pid + time) : (pid + last + 1);
return uuid.last;
}
exports.uuid = uuid;
| JavaScript | 0.000001 | @@ -341,32 +341,36 @@
pipePath = p
+ipeP
ath.replace(/%5E%5C/
@@ -393,24 +393,28 @@
pipePath = p
+ipeP
ath.replace(
|
fb86cdf1de61c603c5793c306045934e65d992ed | fix some for rn | components/list/demo/basic.rn.js | components/list/demo/basic.rn.js | import React from 'react';
import { Image, ScrollView } from 'react-native';
import List from '../index.ios';
import Button from '../../button/index.ios';
export default class BasicListExample extends React.Component {
render() {
return (
<ScrollView>
{/* 基本用法 Demo */}
<List>
<List.Header>基本用法 Demo</List.Header>
<List.Body>
<List.Item
onClick={this.onClick}
needActive={false}
>标题文字,无Active效果</List.Item>
<List.Item
onClick={this.onClick}
>标题文字默认有Active效果</List.Item>
<List.Item
extra="内容内容"
onClick={this.onClick}
last
>标题文字</List.Item>
</List.Body>
<List.Footer>列表尾部,List.Footer</List.Footer>
</List>
<List>
<List.Header>icon Demo</List.Header>
<List.Body>
<List.Item
thumb="https://os.alipayobjects.com/rmsportal/mOoPurdIfmcuqtr.png"
arrow="horizontal"
onClick={window.openurl}
>icon</List.Item>
<List.Item
thumb="https://os.alipayobjects.com/rmsportal/mOoPurdIfmcuqtr.png"
onClick={window.clickItem}
>icon</List.Item>
<List.Item
icon=""
extra={<Image source="https://os.alipayobjects.com/rmsportal/mOoPurdIfmcuqtr.png" width="28" height="28" />}
arrow="horizontal"
onClick={window.clickItem}
>扩展信息传入icon</List.Item>
</List.Body>
</List>
{/* 箭头 Demo */}
<List>
<List.Header>箭头 Demo</List.Header>
<List.Body>
<List.Item extra="horizontal,剪头向右" arrow="horizontal">标题文字</List.Item>
<List.Item extra="down,剪头向下" arrow="down">标题文字</List.Item>
<List.Item extra="up,剪头向上" arrow="up">标题文字</List.Item>
<List.Item
extra={<List.Item.Extra><List.Item.Content>zhifubao@alipay.com</List.Item.Content><List.Item.Detail>001</List.Item.Detail></List.Item.Extra>}
line={2}
arrow="horizontal"
last
><List.Item.Content>账户名</List.Item.Content></List.Item>
</List.Body>
</List>
{/* 双行列表 Demo */}
<List>
<List.Header>双行列表 Demo</List.Header>
<List.Body>
<List.Item line={2} thumb="http://img0.bdstatic.com/img/image/daren/ximeng2.jpg" arrow="horizontal">
<List.Item.Content>收银员</List.Item.Content>
<List.Item.Detail>仅可进行收款、退款及查账操作</List.Item.Detail>
</List.Item>
<List.Item line={2} thumb="http://img0.bdstatic.com/img/image/daren/ximeng2.jpg" arrow="horizontal"
extra={<List.Item.Extra><List.Item.Content>第一行文字</List.Item.Content><List.Item.Detail>Detail</List.Item.Detail></List.Item.Extra>}>
<List.Item.Content>Content</List.Item.Content>
<List.Item.Detail>Detail</List.Item.Detail>
</List.Item>
<List.Item line={2} arrow="down">
<List.Item.Content>运营</List.Item.Content>
<List.Item.Detail>可进行收款、折扣管理、查看数据等操作。如果文字超长那就省略号</List.Item.Detail>
</List.Item>
<List.Item line={2} arrow="up" extra={<Button mode="light" size="small" onPress={() => alert(1)}>按钮</Button>}>
<List.Item.Content>区域经理</List.Item.Content>
<List.Item.Detail>可进行收款、折扣管理、查看数据等操作。</List.Item.Detail>
</List.Item>
<List.Item line={2} last arrow="horizontal" align={'top'}
extra={<List.Item.Extra><List.Item.Content>zhifubao@alipay.com</List.Item.Content><List.Item.Detail>001</List.Item.Detail></List.Item.Extra>}>
<List.Item.Content>账户名</List.Item.Content>
</List.Item>
</List.Body>
<List.Footer>文本说明文本说明</List.Footer>
</List>
{/* 业务例子 Demo */}
<List >
<List.Header>业务例子 Demo</List.Header>
<List.Body>
<List.Item
link="http://www.baidu.com"
extra="鹿港小镇"
arrow="horizontal"
>所属门店</List.Item>
<List.Item
extra="张三"
>员工姓名</List.Item>
<List.Item
extra="收银员"
>员工角色</List.Item>
<List.Item
extra="13838383756"
>员工手机</List.Item>
<List.Item
extra="只可退自己的"
>退款权限</List.Item>
<List.Item
content="其他权限"
arrow="horizontal"
>文本信息</List.Item>
<List.Item
extra={<Image source="https://os.alipayobjects.com/rmsportal/mOoPurdIfmcuqtr.png" width="29" height="29" />}
arrow="horizontal"
>员工二维码</List.Item>
<List.Item
extra={<List.Item.Extra><List.Item.Content>koubei@alipay.com</List.Item.Content><List.Item.Detail>002</List.Item.Detail></List.Item.Extra>}
arrow="horizontal"
last
>垂直居中对齐</List.Item>
</List.Body>
</List>
</ScrollView>
);
}
}
export const title = 'List';
export const description = 'List Example';
| JavaScript | 0.000018 | @@ -1398,33 +1398,41 @@
=%7B%3CImage source=
-%22
+%7B%7B uri: '
https://os.alipa
@@ -1465,33 +1465,36 @@
PurdIfmcuqtr.png
-%22
+' %7D%7D
width=%2228%22 heig
@@ -4850,17 +4850,25 @@
source=
-%22
+%7B%7B uri: '
https://
@@ -4917,17 +4917,20 @@
uqtr.png
-%22
+' %7D%7D
width=%22
|
9c2e04ce16383458576c773dc9fd7e2110a2bc10 | Add markdown support | src/config.js | src/config.js |
/**
* Configuration module
*/
var path = require('path');
var fs = require('fs');
var lodash = require('lodash');
var jsonlint = require('json-lint');
var print = require('./print.js');
module.exports = {
read: read
};
var defaultConfig = {
'source': './',
'destination': './situs',
'ignore': [
'node_modules/**/*',
'situs.json'
],
'port': 4000,
'noConfig': false,
'global': {}
};
function read(filePath, callback) {
fs.exists(filePath, function (exists) {
if (!exists) {
// Add compiled dir in ignore list
defaultConfig.ignore.push('situs/**/*');
defaultConfig.noConfig = true;
return callback(null, defaultConfig);
}
fs.readFile(filePath, 'utf8', function (error, data) {
if (error) {
return callback(error);
}
var lint = jsonlint(data, {comments:false});
if (lint.error) {
error = 'Syntax error on situs.json:'+lint.line+'.\n'+lint.error;
return callback(error);
}
var obj = lodash.extend(defaultConfig, JSON.parse(data));
// Add compiled dir in ignore list
obj.ignore.push(path.normalize(obj.destination)+'/**/*');
return callback(null, obj);
});
});
} | JavaScript | 0.000001 | @@ -397,16 +397,39 @@
%0A %5D,%0A
+ 'markdown': false,%0A
'por
|
88c55ac3cbd1ebd11c67192cd9734b8ae2e77825 | Add pin logging management in config | src/config.js | src/config.js | import path from 'path';
let secret = 'NgWlfDWCbX4mPuxau1FmG3TPLHm7iglEA3mp1f8nrlT7zKDn8ZZAwWQOqUArvQBFfMEbFSAMnUHzgQW1FkczTiZYjPZWqdseNtk2';
let rootPath = path.normalize(__dirname);
let env = process.env.NODE_ENV || 'development';
let rightsManagement = {
all: ['admin', 'seller'],
seller: {
read: [
'/api/articles',
'/api/articleslinks',
'/api/users',
'/api/usersrights',
'/api/usersgroups',
'/api/devicespoints',
'/api/devices',
'/api/meanofloginsusers',
'/api/services/availableArticles'
],
write: [
'/api/services/purchase'
]
},
reloader: {
read: [
'/api/users',
'/api/usersrights',
'/api/usersgroups',
'/api/devicespoints',
'/api/devices',
'/api/reloadtypes',
'/api/meanofloginsusers'
],
write: [
'/api/services/reload'
]
}
};
let config = {
development: {
root: rootPath,
secret: secret,
rightsManagement: rightsManagement,
app: {
name: 'buckuttServer'
},
port: 3000,
db: {
db: 'buckuttServer_development'
},
level: 'debug'
},
test: {
root: rootPath,
secret: secret,
rightsManagement: rightsManagement,
app: {
name: 'buckuttServer'
},
port: 3006,
db: {
db: 'buckuttServer_test'
},
level: 'debug'
},
production: {
root: rootPath,
secret: secret,
rightsManagement: rightsManagement,
app: {
name: 'buckuttServer'
},
port: 3000,
db: {
db: 'buckuttServer_production'
},
level: 'info'
}
};
export default config[env];
| JavaScript | 0.000001 | @@ -1037,16 +1037,53 @@
%7D%0A%7D;%0A%0A
+let pinLoggingAllowed = %5B'seller'%5D;%0A%0A
let conf
@@ -1085,24 +1085,24 @@
config = %7B%0A
-
developm
@@ -1192,32 +1192,74 @@
ghtsManagement,%0A
+ pinManagement: pinLoggingAllowed,%0A
app: %7B%0A
@@ -1518,32 +1518,74 @@
ghtsManagement,%0A
+ pinManagement: pinLoggingAllowed,%0A
app: %7B%0A
@@ -1799,32 +1799,32 @@
secret: secret,%0A
-
rightsMa
@@ -1843,32 +1843,74 @@
ghtsManagement,%0A
+ pinManagement: pinLoggingAllowed,%0A
app: %7B%0A
|
119df8188802d70ac5c6671b6c45e6e6c8027c01 | rename fastExit to bails | src/config.js | src/config.js | import { assign, getPath } from './utils';
const DEFAULT_CONFIG = {
locale: 'en',
delay: 0,
errorBagName: 'errors',
dictionary: null,
fieldsBagName: 'fields',
classes: false,
classNames: {
touched: 'touched', // the control has been blurred
untouched: 'untouched', // the control hasn't been blurred
valid: 'valid', // model is valid
invalid: 'invalid', // model is invalid
pristine: 'pristine', // control has not been interacted with
dirty: 'dirty' // control has been interacted with
},
events: 'input',
inject: true,
fastExit: true,
aria: true,
validity: false,
mode: 'aggressive',
useConstraintAttrs: true,
i18n: null,
i18nRootKey: 'validation'
};
export let currentConfig = assign({}, DEFAULT_CONFIG);
export const resolveConfig = (ctx) => {
const selfConfig = getPath('$options.$_veeValidate', ctx, {});
return assign({}, currentConfig, selfConfig);
};
export const getConfig = () => currentConfig;
export const setConfig = (newConf) => {
currentConfig = assign({}, currentConfig, newConf);
};
| JavaScript | 0.000044 | @@ -565,16 +565,13 @@
,%0A
-fastExit
+bails
: tr
|
08cb82e255e997a9f0e6ea9bade70b9a617be6b5 | Update copyright a year later | src/config.js | src/config.js | const appConfig = require('application-config')('WebTorrent')
const path = require('path')
const electron = require('electron')
const arch = require('arch')
const APP_NAME = 'WebTorrent'
const APP_TEAM = 'WebTorrent, LLC'
const APP_VERSION = require('../package.json').version
const IS_TEST = isTest()
const PORTABLE_PATH = IS_TEST
? path.join(process.platform === 'win32' ? 'C:\\Windows\\Temp' : '/tmp', 'WebTorrentTest')
: path.join(path.dirname(process.execPath), 'Portable Settings')
const IS_PRODUCTION = isProduction()
const IS_PORTABLE = isPortable()
const UI_HEADER_HEIGHT = 38
const UI_TORRENT_HEIGHT = 100
module.exports = {
ANNOUNCEMENT_URL: 'https://webtorrent.io/desktop/announcement',
AUTO_UPDATE_URL: 'https://webtorrent.io/desktop/update',
CRASH_REPORT_URL: 'https://webtorrent.io/desktop/crash-report',
TELEMETRY_URL: 'https://webtorrent.io/desktop/telemetry',
APP_COPYRIGHT: 'Copyright © 2014-2017 ' + APP_TEAM,
APP_FILE_ICON: path.join(__dirname, '..', 'static', 'WebTorrentFile'),
APP_ICON: path.join(__dirname, '..', 'static', 'WebTorrent'),
APP_NAME: APP_NAME,
APP_TEAM: APP_TEAM,
APP_VERSION: APP_VERSION,
APP_WINDOW_TITLE: APP_NAME + ' (BETA)',
CONFIG_PATH: getConfigPath(),
DEFAULT_TORRENTS: [
{
testID: 'bbb',
name: 'Big Buck Bunny',
posterFileName: 'bigBuckBunny.jpg',
torrentFileName: 'bigBuckBunny.torrent'
},
{
testID: 'cosmos',
name: 'Cosmos Laundromat (Preview)',
posterFileName: 'cosmosLaundromat.jpg',
torrentFileName: 'cosmosLaundromat.torrent'
},
{
testID: 'sintel',
name: 'Sintel',
posterFileName: 'sintel.jpg',
torrentFileName: 'sintel.torrent'
},
{
testID: 'tears',
name: 'Tears of Steel',
posterFileName: 'tearsOfSteel.jpg',
torrentFileName: 'tearsOfSteel.torrent'
},
{
testID: 'wired',
name: 'The WIRED CD - Rip. Sample. Mash. Share',
posterFileName: 'wiredCd.jpg',
torrentFileName: 'wiredCd.torrent'
}
],
DELAYED_INIT: 3000 /* 3 seconds */,
DEFAULT_DOWNLOAD_PATH: getDefaultDownloadPath(),
GITHUB_URL: 'https://github.com/webtorrent/webtorrent-desktop',
GITHUB_URL_ISSUES: 'https://github.com/webtorrent/webtorrent-desktop/issues',
GITHUB_URL_RAW: 'https://raw.githubusercontent.com/webtorrent/webtorrent-desktop/master',
HOME_PAGE_URL: 'https://webtorrent.io',
IS_PORTABLE: IS_PORTABLE,
IS_PRODUCTION: IS_PRODUCTION,
IS_TEST: IS_TEST,
OS_SYSARCH: arch() === 'x64' ? 'x64' : 'ia32',
POSTER_PATH: path.join(getConfigPath(), 'Posters'),
ROOT_PATH: path.join(__dirname, '..'),
STATIC_PATH: path.join(__dirname, '..', 'static'),
TORRENT_PATH: path.join(getConfigPath(), 'Torrents'),
WINDOW_ABOUT: 'file://' + path.join(__dirname, '..', 'static', 'about.html'),
WINDOW_MAIN: 'file://' + path.join(__dirname, '..', 'static', 'main.html'),
WINDOW_WEBTORRENT: 'file://' + path.join(__dirname, '..', 'static', 'webtorrent.html'),
WINDOW_INITIAL_BOUNDS: {
width: 500,
height: UI_HEADER_HEIGHT + (UI_TORRENT_HEIGHT * 6) // header + 6 torrents
},
WINDOW_MIN_HEIGHT: UI_HEADER_HEIGHT + (UI_TORRENT_HEIGHT * 2), // header + 2 torrents
WINDOW_MIN_WIDTH: 425,
UI_HEADER_HEIGHT: UI_HEADER_HEIGHT,
UI_TORRENT_HEIGHT: UI_TORRENT_HEIGHT
}
function getConfigPath () {
if (IS_PORTABLE) {
return PORTABLE_PATH
} else {
return path.dirname(appConfig.filePath)
}
}
function getDefaultDownloadPath () {
if (IS_PORTABLE) {
return path.join(getConfigPath(), 'Downloads')
} else {
return getPath('downloads')
}
}
function getPath (key) {
if (!process.versions.electron) {
// Node.js process
return ''
} else if (process.type === 'renderer') {
// Electron renderer process
return electron.remote.app.getPath(key)
} else {
// Electron main process
return electron.app.getPath(key)
}
}
function isTest () {
return process.env.NODE_ENV === 'test'
}
function isPortable () {
if (IS_TEST) {
return true
}
if (process.platform !== 'win32' || !IS_PRODUCTION) {
// Fast path: Non-Windows platforms should not check for path on disk
return false
}
const fs = require('fs')
try {
// This line throws if the "Portable Settings" folder does not exist, and does
// nothing otherwise.
fs.accessSync(PORTABLE_PATH, fs.constants.R_OK | fs.constants.W_OK)
return true
} catch (err) {
return false
}
}
function isProduction () {
if (!process.versions.electron) {
// Node.js process
return false
}
if (process.platform === 'darwin') {
return !/\/Electron\.app\//.test(process.execPath)
}
if (process.platform === 'win32') {
return !/\\electron\.exe$/.test(process.execPath)
}
if (process.platform === 'linux') {
return !/\/electron$/.test(process.execPath)
}
}
| JavaScript | 0 | @@ -930,9 +930,9 @@
-201
-7
+8
' +
|
e59a71d34e95353fc0785f363e3d5a438a08e8e7 | update bkmlt | src/crunch.js | src/crunch.js | javascript:(function()%7Bfunction%20Boom()%7Bvar%20t%3Dwindow.prompt(%22Boom%3A%20Which%20One%22)%2Ce%3D%7Bplex%3A%22javascript%3A%2520var%2520s%3Ddocument.createElement(%2522script%2522)%3Bs.type%3D%2522text%2Fjavascript%2522%3Bs.src%3D%2522https%3A%2F%2Fmy.plexapp.com%2Fqueue%2Fbookmarklet_payload%3Fuid%3D819f10b976818604%2522%3Bvar%2520h%3Ddocument.getElementsByTagName(%2522head%2522)%255B0%255D%3Bh.appendChild(s)%3Bvoid(0)%3B%22%2Cpocket%3A%22javascript%3A(function()%257BISRIL_H%3D'edaa'%3BPKT_D%3D'getpocket.com'%3BISRIL_SCRIPT%3Ddocument.createElement('SCRIPT')%3BISRIL_SCRIPT.type%3D'text%2Fjavascript'%3BISRIL_SCRIPT.src%3D'http%3A%2F%2F'%2BPKT_D%2B'%2Fb%2Fr.js'%3Bdocument.getElementsByTagName('head')%255B0%255D.appendChild(ISRIL_SCRIPT)%257D)()%3B%22%2Cbuiltwith%3A%22javascript%3Avoid(location.href%3D'http%3A%2F%2Fbuiltwith.com%3F'%2Blocation.href)%22%2Cwhois%3A%22javascript%3Avoid(location.href%3D'https%3A%2F%2Fwho.is%2Fwhois%2F'%2Blocation.host)%22%2Ctdfw%3A%22javascript%3A(function()%257Bjavascript%3Avar%2520s%253Ddocument.createElement(%2527script%2527)%253Bs.setAttribute(%2527src%2527%2C%2527https%3A%2F%2Fnthitz.github.io%2Fturndownforwhatjs%2Ftdfw.js%2527)%253Bdocument.body.appendChild(s)%253B%257D)()%253B%22%7D%2Co%3DObject.keys(e)%3B%22help%22%3D%3D%3Dt%26%26alert(o)%2Co.contains(t)%26%26(window.location%3De%5Bt%5D)%7DArray.prototype.contains%3Dfunction(t)%7Bfor(var%20e%3Dthis.length%3Be--%3B)if(this%5Be%5D%3D%3D%3Dt)return!0%3Breturn!1%7D%2CBoom()%3B%7D)()
| JavaScript | 0.000001 | @@ -1285,24 +1285,113 @@
3Dt%25
-26%2526alert(o)%252C
+3Falert(%2522The%2520available%2520bookmarklets%2520for%2520this%2520version%2520are%253A%255Cn%2522%252Bo.join(%2522%255Cn%2522))%253A
o.co
@@ -1404,14 +1404,10 @@
(t)%25
-26%2526(
+3F
wind
@@ -1428,16 +1428,56 @@
e%255Bt%255D
+%253Aalert(%2522Bookmarklet%2520not%2520found%2522
)%257DArra
|
424006534710cccffffc9337ba93e55eca6f7bc0 | Fix #7 - cursor.set polymorphism | src/cursor.js | src/cursor.js | /**
* Baobab Cursor Abstraction
* ==========================
*
* Nested selection into a baobab tree.
*/
var EventEmitter = require('emmett'),
mixins = require('./mixins.js'),
helpers = require('./helpers.js'),
types = require('./typology.js');
/**
* Main Class
*/
function Cursor(root, path) {
var self = this;
// Extending event emitter
EventEmitter.call(this);
// Enforcing array
path = path || [];
path = (typeof path === 'string') ? [path] : path;
// Properties
this.root = root;
this.path = path;
this.relevant = this.get() !== undefined;
// Root listeners
this.root.on('update', function(e) {
var log = e.data.log,
shouldFire = false,
c, p, l, m, i, j;
// If selector listens at root, we fire
if (!self.path.length)
return self.emit('update');
// Checking update log to see whether the cursor should update.
root:
for (i = 0, l = log.length; i < l; i++) {
c = log[i];
for (j = 0, m = c.length; j < m; j++) {
p = c[j];
// If path is not relevant to us, we break
if (p !== self.path[j])
break;
// If we reached last item and we are relevant, we fire
if (j + 1 === m || j + 1 === self.path.length) {
shouldFire = true;
break root;
}
}
}
// Handling relevancy
var data = self.get() !== undefined;
if (self.relevant) {
if (data && shouldFire) {
self.emit('update');
}
else {
self.emit('irrelevant');
self.relevant = false;
}
}
else {
if (data && shouldFire) {
self.emit('relevant');
self.emit('update');
self.relevant = true;
}
}
});
// Making mixin
this.mixin = mixins.cursor(this);
}
helpers.inherits(Cursor, EventEmitter);
/**
* Private prototype
*/
Cursor.prototype._stack = function(spec) {
this.root._stack(helpers.pathObject(this.path, spec));
return this;
};
/**
* Prototype
*/
Cursor.prototype.select = function(path) {
if (!path)
throw Error('precursors.Cursor.select: invalid path.');
if (arguments.length > 1)
path = Array.prototype.slice.call(arguments);
if (!types.check(path, 'path'))
throw Error('precursors.Cursor.select: invalid path.');
return new Cursor(this.root, this.path.concat(path));
};
Cursor.prototype.up = function() {
if (this.path.length)
return new Cursor(this.root, this.path.slice(0, -1));
else
return new Cursor(this.root, []);
};
Cursor.prototype.get = function(path) {
if (arguments.length > 1)
path = Array.prototype.slice.call(arguments);
if (path)
return this.root.get(this.path.concat(path));
else
return this.root.get(this.path);
};
Cursor.prototype.set = function(value) {
return this.update({$set: value});
};
Cursor.prototype.push = function(value) {
if (arguments.length > 1)
return this.update({$push: helpers.arrayOf(arguments)});
else
return this.update({$push: value});
};
Cursor.prototype.unshift = function(value) {
if (arguments.length > 1)
return this.update({$unshift: helpers.arrayOf(arguments)});
else
return this.update({$unshift: value});
};
Cursor.prototype.append = function(value) {
return this.update({$append: value});
};
Cursor.prototype.prepend = function(value) {
return this.update({$prepend: value});
};
Cursor.prototype.update = function(spec) {
return this._stack(spec);
};
/**
* Type definition
*/
types.add('cursor', function(v) {
return v instanceof Cursor;
});
/**
* Output
*/
Cursor.prototype.toJSON = function() {
return this.get();
};
/**
* Export
*/
module.exports = Cursor;
| JavaScript | 0.000001 | @@ -2777,32 +2777,37 @@
.set = function(
+key,
value) %7B%0A retur
@@ -2805,42 +2805,169 @@
%7B%0A
-return this.update(%7B$set: value%7D);
+if (arguments.length %3C 2) %7B%0A return this.update(%7B$set: key%7D);%0A %7D%0A else %7B%0A var spec = %7B%7D;%0A spec%5Bkey%5D = %7B$set: value%7D;%0A return this.update(spec);%0A %7D
%0A%7D;%0A
|
d06dfb451e598baab24a23c50b855ab6e395cf50 | Fix payment view import | solution/app/scripts/modules/app.js | solution/app/scripts/modules/app.js | /*
Copyright 2016 Google 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.
*/
//jshint esversion: 6
import Cart from 'cart';
import LocalStorage from 'local-storage';
import CartView from 'cart-view';
import ShopView from 'shop-view';
import PaymentView from 'Payment-view';
import HeaderController from 'header-controller';
import {products} from 'products';
import {replaceLocationHash} from 'url-tools';
export default class App {
constructor() {
this._storage = new LocalStorage();
this._cart = new Cart(this._storage, this._cartChanged.bind(this));
this._cartView = new CartView(this._cart);
this._shopView = new ShopView(this._cart);
this._paymentView = new PaymentView(this._cart);
this._header = new HeaderController();
this._hashChangeListener = this._handleHashChange.bind(this);
}
install() {
window.addEventListener('hashchange', this._hashChangeListener);
this._cartView.install();
this._paymentView.install();
}
uninstall() {
window.removeEventListener('hashchange', this._hashChangeListener);
}
// Manage element visibility (hide the cart when store is selected and vice versa)
set selection(sel) {
// TODO States: shop|cart, checkout, pay, confirmation
switch(sel) {
case 'shop':
case 'cart':
this._header.selection = sel;
this._shopView.visible = sel == 'shop';
this._cartView.visible = sel != 'shop';
this._paymentView.visible = false;
break;
case 'pay':
this._header.selection = 'cart';
this._cartView.visible = true;
this._paymentView.visible = true;
break;
}
// add cases for payment status, confirmation display
}
run() {
replaceLocationHash('shop'); // Set window.location to end in #shop
this._cart.load();
this._shopView.render();
this._cartView.render();
this._updateCartCountDisplay();
this.selection = 'shop';
// *** The following changes are meant to make this a single-page app ***
// TODO add controller for payment form, handle payment flow
// TODO add hash states for payment (#checkout -> #pay [w/ spinner] -> #confirmation (replace))
// TODO Fix the shop not rendering on first load.
// TODO pick up delete icon, possible add icon
// TODO Refactor out visibility code into a base class or utility package
}
// Pop up a user notification
showToast(message) {
var notification = document.getElementById('snackbar');
// This depends on the MDL script which he unit tests don't have
if (notification && notification.MaterialSnackbar) {
notification.MaterialSnackbar.showSnackbar({message: (message)});
}
}
// Handle hashChange, manage history (#store or #cart, maybe #pay)
_handleHashChange(event) {
if (!event.newURL) return;
let index = event.newURL.lastIndexOf('#');
if (index < 0) return;
let sel = event.newURL.substr(index+1);
this.selection = sel;
}
_cartChanged(details) {
if (details.action == 'load') return; // save would be redundant
if (details.action == 'add' || details.action == 'change') {
this._cartView.total =
this.showToast('Cart updated');
}
this._updateCartCountDisplay();
this._cart.save();
}
_updateCartCountDisplay() {
this._header.count = this._cart.count;
}
// Testing hooks
set headerController(obj) {
this._header = obj;
}
get cart() {
return this._cart;
}
get storage() {
return this._storage;
}
}
| JavaScript | 0.000003 | @@ -735,17 +735,17 @@
w from '
-P
+p
ayment-v
|
6fd4c1e995ac6d90ae6f9b62fc84825a9a2d5143 | Fix crash in timeline on broken logs with missing events | src/interface/report/Results/Timeline/Buffs.js | src/interface/report/Results/Timeline/Buffs.js | import React from 'react';
import PropTypes from 'prop-types';
import { formatDuration } from 'common/format';
import Icon from 'common/Icon';
import SpellLink from 'common/SpellLink';
import BuffsModule from 'parser/core/modules/Buffs';
import Tooltip from 'common/Tooltip';
import './Buffs.scss';
class Buffs extends React.PureComponent {
static propTypes = {
start: PropTypes.number.isRequired,
secondWidth: PropTypes.number.isRequired,
parser: PropTypes.shape({
eventHistory: PropTypes.arrayOf(PropTypes.shape({
type: PropTypes.string.isRequired,
})).isRequired,
}).isRequired,
buffs: PropTypes.instanceOf(BuffsModule).isRequired,
};
constructor() {
super();
this.renderEvent = this.renderEvent.bind(this);
}
getOffsetLeft(timestamp) {
return (timestamp - this.props.start) / 1000 * this.props.secondWidth;
}
// TODO: Fabricate removebuff events for buffs that expired after the fight
isApplicableBuffEvent(event) {
const parser = this.props.parser;
if (!parser.toPlayer(event)) {
// Ignore pet/boss buffs
return false;
}
const spellId = event.ability.guid;
const buff = this.props.buffs.getBuff(spellId);
if (!buff || !buff.timelineHightlight) {
return false;
}
return true;
}
renderEvent(event) {
switch (event.type) {
case 'applybuff':
if (this.isApplicableBuffEvent(event)) {
return this.renderApplyBuff(event);
} else {
return null;
}
case 'removebuff':
if (this.isApplicableBuffEvent(event)) {
return this.renderRemoveBuff(event);
} else {
return null;
}
case 'fightend':
return this.renderLeftOverBuffs(event);
default:
return null;
}
}
_applied = {};
_levels = [];
_maxLevel = 0;
_getLevel() {
// Look for the first available level, reusing levels that are no longer used
let level = 0;
while (this._levels[level] !== undefined) {
level += 1;
}
return level;
}
renderApplyBuff(event) {
const spellId = event.ability.guid;
// Avoid overlapping icons
const level = this._getLevel();
this._applied[spellId] = event;
this._levels[level] = spellId;
this._maxLevel = Math.max(this._maxLevel, level);
return this.renderIcon(event, {
className: 'hoist',
style: {
'--level': level,
},
children: <div className="time-indicator" />,
});
}
renderRemoveBuff(event) {
const applied = this._applied[event.ability.guid];
const left = this.getOffsetLeft(applied.timestamp);
const duration = event.timestamp - applied.timestamp;
const fightDuration = (applied.timestamp - this.props.start) / 1000;
const level = this._levels.indexOf(event.ability.guid);
this._levels[level] = undefined;
delete this._applied[event.ability.guid];
// TODO: tooltip renders at completely wrong places
return (
<Tooltip
content={`${formatDuration(fightDuration, 3)}: gained ${event.ability.name} for ${(duration / 1000).toFixed(2)}s`}
>
<div
key={`buff-${left}-${event.ability.guid}`}
className="buff hoist"
style={{
left,
width: (event.timestamp - applied.timestamp) / 1000 * this.props.secondWidth,
'--level': level,
}}
data-effect="float"
/>
</Tooltip>
);
}
renderLeftOverBuffs(event) {
// We don't have a removebuff event for buffs that end *after* the fight, so instead we go through all remaining active buffs and manually trigger the removebuff render.
const elems = [];
Object.keys(this._applied).forEach(spellId => {
const applied = this._applied[spellId];
elems.push(this.renderRemoveBuff({
...applied,
timestamp: event.timestamp,
}));
});
return elems;
}
renderIcon(event, { className = '', style = {}, children } = {}) {
const left = this.getOffsetLeft(event.timestamp);
return (
<SpellLink
key={`cast-${left}-${event.ability.guid}`}
id={event.ability.guid}
icon={false}
className={`cast ${className}`}
style={{
left,
...style,
}}
>
<Icon
icon={event.ability.abilityIcon.replace('.jpg', '')}
alt={event.ability.name}
/>
{children}
</SpellLink>
);
}
render() {
const { parser } = this.props;
const buffs = parser.eventHistory.map(this.renderEvent);
return (
<div className="buffs" style={{ '--levels': this._maxLevel + 1 }}>
{buffs}
</div>
);
}
}
export default Buffs;
| JavaScript | 0.000001 | @@ -2588,24 +2588,156 @@
lity.guid%5D;%0A
+ if (!applied) %7B%0A // This may occur for broken logs with missing events due to range/logger issues%0A return null;%0A %7D%0A
const le
|
84ad8b3823b1f57e48c4af2dd312ecd5596e005b | change locale namespace | src/jquery.continuous-calendar/date-locales.js | src/jquery.continuous-calendar/date-locales.js | var DATE_LOCALE_FI = {
init: function() {
Date.monthNames = [
'tammikuu',
'helmikuu',
'maaliskuu',
'huhtikuu',
'toukokuu',
'kesäkuu',
'heinäkuu',
'elokuu',
'syyskuu',
'lokakuu',
'marraskuu',
'joulukuu'];
Date.dayNames = ['Su','Ma','Ti','Ke','To','Pe','La'];
Date.daysLabel = function(days) {return days + ' ' + (days == '1' ? 'päivä' : 'päivää');};
Date.hoursLabel = function(hours) {return hours + ' ' + (hours == '1' ? 'tunti' : 'tuntia');};
},
shortDateFormat: 'j.n.Y',
weekDateFormat: 'D j.n.Y',
dateTimeFormat: 'D j.n.Y k\\lo G:i',
firstWeekday: Date.MONDAY
};
var DATE_LOCALE_EN = {
init: function() {
Date.monthNames = ['January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'];
Date.dayNames = ['Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'];
Date.daysLabel = function(days) {return days + ' ' + (days == '1' ? 'Day' : 'Days');};
Date.hoursLabel = function(hours) {return hours + ' ' + (hours == '1' ? 'Hour' : 'Hours');};
},
shortDateFormat: 'n/j/Y',
weekDateFormat: 'D n/j/Y',
dateTimeFormat: 'D n/j/Y G:i',
firstWeekday: Date.SUNDAY
}; | JavaScript | 0.000004 | @@ -1,24 +1,27 @@
-var
+window.
DATE_LOCALE_FI = %7B%0A
@@ -666,12 +666,15 @@
%0A%7D;%0A
-var
+window.
DATE
|
6299c36f1d690b5707f2fd5331039df62d6fd6af | edit render | app/assets/javascripts/categories.js | app/assets/javascripts/categories.js | class Artwork {
constructor(title, year, artist, id, museum_id) {
this.title = title
this.year = year
this.artist = artist
this.id = id
this.museum_id = museum_id
}
render() {
let li = document.createElement('li')
console.log(this.museum_id)
li.innerHTML = `<a href="/museums/${this.museum_id}/artworks/${this.id}">` + `${this.title} | ${this.artist} | ${this.year}` + "</a>"
return li.innerHTML
}
}
$(document).ready(function() {
renderArtworks();
})
function renderArtworks() {
var id = $(".artwork_list").attr("id")
$.get(`/categories/${id}/artworks`, function(data) {
var html = new Artwork(data[0].title, data[0].year, data[0].artist, data[0].id, data[0].museum.id).render()
$(".artwork_list ul").append(html)
})
}
| JavaScript | 0.000001 | @@ -204,96 +204,32 @@
-let li = document.createElement('li')%0A console.log(this.museum_id)%0A li.innerHTML =
+var artworkLi = %22%3Cli%3E%22 +
%60%3Ca
@@ -342,16 +342,21 @@
+ %22%3C/a%3E
+%3C/li%3E
%22%0A re
@@ -364,20 +364,17 @@
urn
-li.innerHTML
+artworkLi
%0A %7D
@@ -553,24 +553,85 @@
ion(data) %7B%0A
+ console.log(data)%0A data.forEach(function(artwork) %7B%0A
var html
@@ -649,23 +649,23 @@
ork(
-data%5B0%5D
+artwork
.title,
data
@@ -664,57 +664,57 @@
le,
-data%5B0%5D.year, data%5B0%5D.artist, data%5B0%5D.id, data%5B0%5D
+artwork.year, artwork.artist, artwork.id, artwork
.mus
@@ -730,16 +730,18 @@
ender()%0A
+
$(%22.
@@ -771,15 +771,22 @@
d(html)%0A
+ %7D)%0A
%7D)%0A%7D%0A
|
61ab5976b6d6438d50c55c1f2d3bce0e19aef13f | move dash to previous line | app/assets/javascripts/categories.js | app/assets/javascripts/categories.js | pages.categories.mobileCategories = function(){
$('.categories-select').on('change', function(){
var category = $(this).find('option:selected').text().toLowerCase();
var url = '/categories/' +
$(this).val() +
'-' +
category.split(' ').join('-');
if (url) {
window.location.replace(url);
}
return false;
});
};
| JavaScript | 0.000001 | @@ -217,22 +217,16 @@
.val() +
-%0A
'-' +%0A
|
5188b9b0ea4cca9b91cab902b06802e669b39fc6 | tweak appearance of data dictionary table | app/assets/javascripts/dictionary.js | app/assets/javascripts/dictionary.js | $(function() {
$("#jsGrid").jsGrid({
height: "160vh",
width: "90%",
filtering: true,
inserting: false,
editing: false,
sorting: true,
paging: true,
autoload: true,
noDataContent: "...Loading...",
searchButtonTooltip: "Search",
clearFilterButtonTooltip: "Clear filter",
pageSize: 40,
controller: {
loadData: function(filter) {
return $.ajax({
type: "GET",
url: "/definitions",
data: filter
});
}
},
fields: [
{ type: 'control', deleteButton: false, editButton: false },
{ name: 'nlm doc', width: 38, align: 'center' },
{ name: 'db section', type: "text", width: 75 },
{ name: 'table', type: "text", width: 150 },
{ name: 'column', type: "text", width: 180 },
{ name: 'data type', type: "text", width: 70 },
{ name: 'source', type: "text", width: 260 },
{ name: 'CTTI note', type: "text", width: 360 },
{ name: 'row count', type: 'text', width: 100, align: 'center' },
{ name: 'enumerations', type: "text", width: 280 },
]
});
});
| JavaScript | 0 | @@ -78,9 +78,10 @@
h: %22
-9
+10
0%25%22,
@@ -1068,78 +1068,8 @@
%7D,%0A
- %7B name: 'source', type: %22text%22, width: 260 %7D,%0A
@@ -1128,17 +1128,17 @@
width: 3
-6
+5
0 %7D,%0A
@@ -1285,17 +1285,87 @@
width: 2
-8
+50 %7D,%0A %7B name: 'source', type: %22text%22, width: 25
0 %7D,%0A
|
80fd029cf9b0c01136642355e548e80f669086a2 | add comments to the key zoomIn function block | app/assets/javascripts/percolator.js | app/assets/javascripts/percolator.js | var isZooming = false;
var solutionNumber;
var isLoaded = false;
// GTG
jQuery.ajaxSetup({
'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
})
$(document).on("ajax:success", "#solution-form", function(){
$("#solution-form").find("input[type=text], textarea").val("");
$("#solution-form").hide();
var ajaxRequest = $.ajax({
type: "POST",
url: problem_solutions_create_path()
});
ajaxRequest.done(function( response ) {
console.log(response);
Canvas.init();
})
});
function addEventListeners() {
$('#chart-popup button#back').unbind('click').click(function () {
zoomOut();
hideChartPopupElements();
console.log("Firing back")
});
$('#chart-popup button#render-solution-form').unbind('click').click(function () {
renderSolutionForm();
console.log("Firing form")
});
$('#new_solution').on("submit", function (e) {
e.preventDefault();
$(this.solution_title).val("");
$(this.solution_description).val("");
$(this).hide();
});
}
// GTG
function showPopup() {
$('#chart-popup').hide().slideDown(500);
//$('#page-title')[0].innerHTML = $.parseJSON(window.data).solutions[solutionNumber].title
// SAVE COMMENT
// ADD $.parseJSON(window.data) as a this.problemData element when OOJSing so
// these queries can access the correct solution number without making another query
//$('#synopsis')[0].innerHTML = $.parseJSON(window.data).solutions[solutionNumber].description
sendIdAjax();
Menu.init();
}
function sendIdAjax() {
$.ajax({
type: "POST",
url: '/improvements',
data: solutionNumber
});
}
function hideChartPopupElements() {
$('#chart-popup').show().slideUp(500);
}
function renderSolutionForm() {
var solutionForm = $('#solution-form').detach();
$(solutionForm).appendTo("#problem-container");
$("#solution-form").show();
$("#new_solution").show();
}
function zoomIn(target) {
var posX;
var posY;
if (target) {
posX = target.attributes[0].value - ((Canvas.WIDTH / 2) * Canvas.ZOOM_MAX);
posY = target.attributes[1].value - ((Canvas.HEIGHT / 2) * Canvas.ZOOM_MAX);
$("span.upvote").attr("id", "upvote");
$("span.downvote").attr("id", "downvote");
solutionNumber = $(target).attr("id");
}
else {
posX = (Canvas.WIDTH / 2) - ((Canvas.WIDTH / 2) * Canvas.ZOOM_MAX);
posY = (Canvas.HEIGHT / 2) - ((Canvas.HEIGHT / 2) * Canvas.ZOOM_MAX);
$("span.upvote").attr("id", "problem_upvote");
$("span.downvote").attr("id", "problem_downvote");
}
solutionNumber = $(target).attr("id");
console.log(solutionNumber)
isZooming = true;
Canvas.zoomIn(posX, posY, zoomInComplete);
Canvas.hideSolutions();
}
// GTG
// GTG
function zoomOut() {
problemText.animate({transform: "s1"}, 400);
Canvas.zoomOut(0, 0, zoomOutComplete);
Canvas.showSolutions();
isZooming = true;
}
// GTG
function zoomInComplete()
{
showPopup();
isZooming = false;
}
function zoomOutComplete()
{
isZooming = false;
}
// function improvement() {
// $()
// }
// GTG
function upvote() {
$("#upvote").on("click",function(){
$.ajax({
beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
url: "/solution_upvote",
type: "POST",
data: {solution_number: solutionNumber.toString()}
}).done(function(r){
var response = $.parseJSON(r);
count = response[0] - response[1];
$("#count").html(""+count+"");
});
});
}
// GTG
// GTG
function downvote() {
$("#downvote").on("click",function(){
$.ajax({
beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
url: "/solution_downvote",
type: "POST",
data: {solution_number: solutionNumber.toString()}
}).done(function(r){
var response1 = $.parseJSON(r);
var count = response1[0] - response1[1];
$("#count").html(""+count+"");
});
});
}
// GTG
// function ajaxUpvote() {
// $.ajax({
// beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
// url: "/solution_upvote",
// type: "POST"
// }).done(function(r){
// var response = $.parseJSON(r);
// count = response[0] - response[1];
// $("#count").html(""+count+"");
// });
// }
// function ajaxDownvote() {
// }
// GTG
$(document).ready(function () {
if ($("#canvas_container").length) {
var problem = $.parseJSON(window.data);
$('#problem-container').removeClass('hidden');
$('#bubble-container').removeClass('hidden');
$('#solution-form').hide();
$('#chart-popup').hide();
$('#page-title')[0].innerHTML = problem.title;
$('#synopsis')[0].innerHTML = problem.description;
upvote();
downvote();
addEventListeners();
Canvas.init();
}
});
$(window).resize(function () {
Canvas.init();
});
$(document).on("ajax:success", "#solution-form", function(){
$("#solution-form").find("input[type=text], textarea").val("");
$("#solution-form").hide();
});
| JavaScript | 0 | @@ -1575,165 +1575,18 @@
-sendIdAjax();%0A Menu.init();%0A%7D%0A%0Afunction sendIdAjax() %7B%0A $.ajax(%7B%0A type: %22POST%22,%0A url: '/improvements',%0A data: solutionNumber%0A %7D
+Menu.init(
);%0A%7D
@@ -1939,24 +1939,60 @@
f (target) %7B
+// if the click target is a solution
%0A pos
@@ -2296,24 +2296,24 @@
id%22);%0A %7D%0A
-
else %7B%0A
@@ -2310,16 +2310,53 @@
else %7B
+// if the click target is the problem
%0A
|
2fa759c3c6ed264cbbf45db1883445e04854a58b | Update staging url | app/assets/scripts/config/staging.js | app/assets/scripts/config/staging.js | /*
* App config overrides for staging.
*/
// set staging-specific options here.
module.exports = {
environment: 'staging',
OAMUploaderApi: 'http://52.91.218.109/',
googleClient: '36015894456-3d5ka80qtpaqcjhco3lsl38s1fj0dr71.apps.googleusercontent.com',
googleDeveloperKey: ''
};
// copy over any production settings that weren't specifically set above
var production = require('./production');
for (var p in production) {
if (typeof module.exports[p] === 'undefined') {
module.exports[p] = production[p];
}
}
| JavaScript | 0.000001 | @@ -151,21 +151,45 @@
p://
-52.91.218.109
+upload-api-staging.openaerialmap.org/
/',%0A
|
8f2bcb143373195fe4654f2b0843c473edab0c78 | handle missing home variable | app/components/application-header.js | app/components/application-header.js | import Ember from 'ember';
import ENV from 'bracco/config/environment';
export default Ember.Component.extend({
default: false,
type: 'transparent',
title: null,
home: '/',
sandbox: null,
data: {},
// init: function () {
// this._super();
//
// if (!this.get('default')) {
// Ember.run.schedule("afterRender",this,function() {
// this.send("transitionNoAccess");
// });
// }
// },
actions: {
transitionNoAccess() {
this.get('router').transitionTo(this.get('home'));
}
},
didInsertElement: function() {
if (this.get('default')) {
this.set('type', null);
this.set('title', Ember.String.htmlSafe(ENV.SITE_TITLE));
}
let home = this.get('currentUser').get('home');
if (Ember.typeOf(home) == 'object') {
this.set('home', { route: home.route, model: home.id });
} else {
this.set('home', { href: home });
}
let sandbox = this.get('currentUser').get('sandbox');
if (Ember.typeOf(sandbox) == 'object') {
this.set('sandbox', { route: sandbox.route, model: sandbox.id });
} else if (sandbox) {
this.set('sandbox', { href: sandbox });
}
let url = ENV.CDN_URL + "/data/links.json";
let self = this;
fetch(url).then(function(response) {
return response.json();
}).then(function(data) {
data.header_links = data[ENV.environment + '_links'];
self.set('data', data);
});
}
});
| JavaScript | 0.000015 | @@ -868,16 +868,26 @@
%7D else
+ if (home)
%7B%0A
@@ -918,32 +918,75 @@
: home %7D);%0A %7D
+ else %7B%0A this.set('home', null);%0A %7D
%0A%0A let sandbo
|
6a8133064f5cdcbc8ac8ed7e1ff29f51c743ac4c | Set timeout for closing all notis | Themes/default/js/breezeNoti.js | Themes/default/js/breezeNoti.js | /**
* breezeNoti.js
*
* The purpose of this file is to fetch notifications for the current user and display them.
* @package Breeze mod
* @version 1.0
* @author Jessica Gonzlez <suki@missallsunday.com>
* @copyright Copyright (c) 2011, 2014 Jessica Gonzlez
* @license http://www.mozilla.org/MPL/MPL-1.1.html
*/
/*
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is http://missallsunday.com code.
*
* The Initial Developer of the Original Code is
* Jessica Gonzlez.
* Portions created by the Initial Developer are Copyright (c) 2012, 2013
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
*/
breeze.tools.stream = function(currentUser)
{
var number = 0;
// Make an ajax call to get all notifications for this user.
jQuery.ajax({
type: 'GET',
url: smf_scripturl + '?action=breezeajax;sa=fetchNoti;js=1;' + breeze.session.v + '=' + breeze.session.id + ';u=' + currentUser,
cache: false,
dataType: 'json',
success: function(noti)
{
if (noti.data == '')
return;
// Loops for everyone!!
jQuery.each(noti.data, function(i, item){
number++;
noty({
text: item.message,
timeout: 3500,
type: 'notification',
dismissQueue: true,
layout: 'topRight',
closeWith: ['button'],
buttons: [
{addClass: 'button_submit', text: breeze.text.noti_markasread, onClick: function($noty){
jQuery.ajax({
type: 'POST',
url: smf_scripturl + '?action=breezeajax;sa=notimark;js=1;' + breeze.session.v + '=' + breeze.session.id,
data: ({content : noti.id, user : noti.user}),
cache: false,
dataType: 'json',
success: function(html){
if(html.type == 'error'){
noty({text: breeze_error_message, timeout: 3500, type: 'error'});
}
else if(html.type == 'ok'){
noty({text: breeze.text.noti_markasread_after, timeout: 3500, type: 'success'});
}
},
error: function (html){
noty({text: breeze_error_message, timeout: 3500, type: 'error'});
},
});
$noty.close();
}},
{addClass: 'button_submit', text: breeze.text.noti_delete, onClick: function($noty){
jQuery.ajax({
type: 'POST',
url: smf_scripturl + '?action=breezeajax;sa=notidelete;js=1;' + breeze.session.v + '=' + breeze.session.id,
data: ({content : noti.id, user : noti.user}),
cache: false,
dataType: 'json',
success: function(html){
if(html.type == 'error'){
noty({text: html.data, timeout: 3500, type: 'error'});
}
else if(html.type == 'deleted'){
noty({text: html.data, timeout: 3500, type: 'error'});
}
else if(html.type == 'ok'){
noty({text: html.data, timeout: 3500, type: 'success'});
}
},
error: function (html){
noty({text: breeze_error_message, timeout: 3500, type: 'error'});
},
});
$noty.close();
}},
{addClass: 'button_submit', text: breeze.text.noti_cancel, onClick: function($noty){
$noty.close();
}}
]
});
});
// Show a close all button
noty({
text: breeze.text.noti_closeAll,
type: 'warning',
dismissQueue: true,
layout: 'topRight',
closeWith: ['click'],
callback: {
afterClose: function() {
jQuery.noty.closeAll();
},
onShow: function() {window.setTimeout("jQuery.noty.closeAll()", 5 * 1000 );},
},
});
// Append the number of notifications to the wall button
jQuery('#button_wall a.firstlevel span').append(' ['+ number +']');
},
error: function (noti){
},
});
}
| JavaScript | 0 | @@ -3962,17 +3962,93 @@
All()%22,
-5
+((breeze.currentSettings.clear_noti) ? breeze.currentSettings.clear_noti : 5)
* 1000
|
e97d29c2f6e454c019890182ccceb3eee81c0fd0 | Set a default for localstorage data, just in case. | Trump-To-Butt/content_script.js | Trump-To-Butt/content_script.js | walk(document.body);
var rpl = "butt";
function loadRpl() {
var rpl = localStorage["rpl"];
return rpl;
}
function walk(node)
{
// I stole this function from here:
// http://is.gd/mwZp7E
var child, next;
switch ( node.nodeType )
{
case 1: // Element
case 9: // Document
case 11: // Document fragment
child = node.firstChild;
while ( child )
{
next = child.nextSibling;
walk(child);
child = next;
}
break;
case 3: // Text node
handleText(node);
break;
}
}
function handleText(textNode)
{
var v = textNode.nodeValue;
rpl = loadRpl();
v = v.replace(/\bTrump\b/g, rpl);
textNode.nodeValue = v;
}
| JavaScript | 0 | @@ -593,16 +593,125 @@
dRpl();%0A
+ // LocalStorage isn't working as I'd expect, so set a default.%0A if ( rpl == undefined ) %7B rpl = %22Butt%22; %7D%0A
%09v = v.r
|
d657c2d9f324bb659217798c4bdd6288819a1652 | fix conflicts | packages/articles/public/tests/articles.spec.js | packages/articles/public/tests/articles.spec.js | 'use strict';
(function() {
// Articles Controller Spec
describe('MEAN controllers', function() {
describe('ArticlesController', function() {
// The $resource service augments the response object with methods for updating and deleting the resource.
// If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
// the responses exactly. To solve the problem, we use a newly-defined toEqualData Jasmine matcher.
// When the toEqualData matcher compares two objects, it takes only object properties into
// account and ignores methods.
beforeEach(function() {
jasmine.addMatchers({
toEqualData: function() {
return {
compare: function(actual, expected) {
return {
pass: angular.equals(actual, expected)
};
}
};
}
});
});
beforeEach(function() {
module('mean');
module('mean.system');
module('mean.articles');
});
// Initialize the controller and a mock scope
var ArticlesController,
scope,
$httpBackend,
$stateParams,
$location;
// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
// This allows us to inject a service but then attach it to a variable
// with the same name as the service.
beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) {
scope = $rootScope.$new();
ArticlesController = $controller('ArticlesController', {
$scope: scope
});
$stateParams = _$stateParams_;
$httpBackend = _$httpBackend_;
$location = _$location_;
}));
it('$scope.find() should create an array with at least one article object ' +
'fetched from XHR', function() {
// test expected GET request
$httpBackend.expectGET('api\/articles').respond([{
title: 'An Article about MEAN',
content: 'MEAN rocks!'
}]);
// run controller
scope.find();
$httpBackend.flush();
// test scope value
expect(scope.articles).toEqualData([{
title: 'An Article about MEAN',
content: 'MEAN rocks!'
}]);
});
it('$scope.findOne() should create an array with one article object fetched ' +
'from XHR using a articleId URL parameter', function() {
// fixture URL parament
$stateParams.articleId = '525a8422f6d0f87f0e407a33';
// fixture response object
var testArticleData = function() {
return {
title: 'An Article about MEAN',
content: 'MEAN rocks!'
};
};
// test expected GET request with response object
$httpBackend.expectGET(/api\/articles\/([0-9a-fA-F]{24})$/).respond(testArticleData());
// run controller
scope.findOne();
$httpBackend.flush();
// test scope value
expect(scope.article).toEqualData(testArticleData());
});
it('$scope.create() with valid form data should send a POST request ' +
'with the form input values and then ' +
'locate to new object URL', function() {
// fixture expected POST data
var postArticleData = function() {
return {
title: 'An Article about MEAN',
content: 'MEAN rocks!'
};
};
// fixture expected response data
var responseArticleData = function() {
return {
_id: '525cf20451979dea2c000001',
title: 'An Article about MEAN',
content: 'MEAN rocks!'
};
};
// fixture mock form input values
scope.title = 'An Article about MEAN';
scope.content = 'MEAN rocks!';
// test post request is sent
$httpBackend.expectPOST('api\/articles', postArticleData()).respond(responseArticleData());
// Run controller
scope.create(true);
$httpBackend.flush();
// test form input(s) are reset
expect(scope.title).toEqual('');
expect(scope.content).toEqual('');
// test URL location to new object
expect($location.path()).toBe('/api/articles/' + responseArticleData()._id);
});
it('$scope.update(true) should update a valid article', inject(function(Articles) {
// fixture rideshare
var putArticleData = function() {
return {
_id: '525a8422f6d0f87f0e407a33',
title: 'An Article about MEAN',
to: 'MEAN is great!'
};
};
// mock article object from form
var article = new Articles(putArticleData());
// mock article in scope
scope.article = article;
// test PUT happens correctly
$httpBackend.expectPUT(/api\/articles\/([0-9a-fA-F]{24})$/).respond();
// testing the body data is out for now until an idea for testing the dynamic updated array value is figured out
//$httpBackend.expectPUT(/articles\/([0-9a-fA-F]{24})$/, putArticleData()).respond();
/*
Error: Expected PUT /articles\/([0-9a-fA-F]{24})$/ with different data
EXPECTED: {"_id":"525a8422f6d0f87f0e407a33","title":"An Article about MEAN","to":"MEAN is great!"}
GOT: {"_id":"525a8422f6d0f87f0e407a33","title":"An Article about MEAN","to":"MEAN is great!","updated":[1383534772975]}
*/
// run controller
scope.update(true);
$httpBackend.flush();
// test URL location to new object
expect($location.path()).toBe('/api/articles/' + putArticleData()._id);
}));
it('$scope.remove() should send a DELETE request with a valid articleId ' +
'and remove the article from the scope', inject(function(Articles) {
// fixture rideshare
var article = new Articles({
_id: '525a8422f6d0f87f0e407a33'
});
// mock rideshares in scope
scope.articles = [];
scope.articles.push(article);
// test expected rideshare DELETE request
$httpBackend.expectDELETE(/api\/articles\/([0-9a-fA-F]{24})$/).respond(204);
// run controller
scope.remove(article);
$httpBackend.flush();
// test after successful delete URL location articles list
//expect($location.path()).toBe('/articles');
expect(scope.articles.length).toBe(0);
}));
});
});
}());
| JavaScript | 0.000112 | @@ -4481,36 +4481,32 @@
.path()).toBe('/
-api/
articles/' + res
@@ -5913,12 +5913,8 @@
e('/
-api/
arti
|
17fc53c5327d0a916845167573a5fa071f83dfd3 | Set __filename and __dirname to true | packages/backpack-core/config/webpack.config.js | packages/backpack-core/config/webpack.config.js | const fs = require('fs')
const webpack = require('webpack')
const nodeExternals = require('webpack-node-externals')
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin')
const config = require('./paths')
const path = require('path')
const babelPreset = require('../babel')
// This is the Webpack configuration.
// It is focused on developer experience and fast rebuilds.
module.exports = (options) => {
const babelRcPath = path.resolve('.babelrc')
const hasBabelRc = fs.existsSync(babelRcPath)
const mainBabelOptions = {
babelrc: true,
cacheDirectory: true,
presets: []
}
if (hasBabelRc) {
console.log('> Using .babelrc defined in your app root')
} else {
mainBabelOptions.presets.push(require.resolve('../babel'))
}
return {
// Webpack can target multiple environments such as `node`,
// `browser`, and even `electron`. Since Backpack is focused on Node,
// we set the default target accordingly.
target: 'node',
// The benefit of Webpack over just using babel-cli or babel-node
// command is sourcemap support. Although it slows down compilation,
// it makes debugging dramatically easier.
devtool: 'source-map',
// Webpack allows you to define externals - modules that should not be
// bundled. When bundling with Webpack for the backend - you usually
// don't want to bundle its node_modules dependencies. This creates an externals
// function that ignores node_modules when bundling in Webpack.
// @see https://github.com/liady/webpack-node-externals
externals: nodeExternals({
whitelist: [
/\.(eot|woff|woff2|ttf|otf)$/,
/\.(svg|png|jpg|jpeg|gif|ico|webm)$/,
/\.(mp4|mp3|ogg|swf|webp)$/,
/\.(css|scss|sass|less|styl)$/,
]
}),
// As of Webpack 2 beta, Webpack provides performance hints.
// Since we are not targeting a browser, bundle size is not relevant.
// Additionally, the performance hints clutter up our nice error messages.
performance: {
hints: false
},
// Since we are wrapping our own webpack config, we need to properly resolve
// Backpack's and the given user's node_modules without conflict.
resolve: {
extensions: ['.js', '.json'],
modules: [config.userNodeModulesPath, path.resolve(__dirname, '../node_modules')]
},
resolveLoader: {
modules: [config.userNodeModulesPath, path.resolve(__dirname, '../node_modules')]
},
node: {
__filename: false,
__dirname: false
},
entry: {
main: [
`${config.serverSrcPath}/index.js`
],
},
// This sets the default output file path, name, and compile target
// module type. Since we are focused on Node.js, the libraryTarget
// is set to CommonJS2
output: {
path: config.serverBuildPath,
filename: '[name].js',
sourceMapFilename: '[name].map',
publicPath: config.publicPath,
libraryTarget: 'commonjs2'
},
// Define a few default Webpack loaders. Notice the use of the new
// Webpack 2 configuration: module.rules instead of module.loaders
module: {
rules: [
// This is the development configuration.
// It is focused on developer experience and fast rebuilds.
{
test: /\.json$/,
loader: 'json-loader'
},
// Process JS with Babel (transpiles ES6 code into ES5 code).
{
test: /\.(js|jsx)$/,
loader: 'babel-loader',
exclude: [
/node_modules/,
config.buildPath
],
options: mainBabelOptions
}
]
},
plugins: [
// We define some sensible Webpack flags. One for the Node environment,
// and one for dev / production. These become global variables. Note if
// you use something like eslint or standard in your editor, you will
// want to configure __DEV__ as a global variable accordingly.
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(options.env),
'__DEV__': options.env === 'development'
}),
// In order to provide sourcemaps, we automagically insert this at the
// top of each file using the BannerPlugin.
new webpack.BannerPlugin({
raw: true,
banner: `require('${require.resolve('source-map-support/register')}')`
}),
// The FriendlyErrorsWebpackPlugin (when combined with source-maps)
// gives Backpack its human-readable error messages.
new FriendlyErrorsWebpackPlugin(),
// This plugin is awkwardly named. Use to be called NoErrorsPlugin.
// It does not actually swallow errors. Instead, it just prevents
// Webpack from printing out compile time stats to the console.
// @todo new webpack.NoEmitOnErrorsPlugin()
new webpack.NoErrorsPlugin()
]
}
}
| JavaScript | 0.999999 | @@ -2498,20 +2498,19 @@
lename:
-fals
+tru
e,%0A
@@ -2521,20 +2521,19 @@
irname:
-fals
+tru
e%0A %7D,
@@ -4294,24 +4294,50 @@
raw: true,%0A
+ entryOnly: false,%0A
bann
|
5f3b393be7166a7864ce089bab791b7a6f8d09e7 | Fix #491 - Disabled ------------ as country | packages/components/containers/payments/Card.js | packages/components/containers/payments/Card.js | import React from 'react';
import { c } from 'ttag';
import PropTypes from 'prop-types';
import { Block, Input, Select } from 'react-components';
import { getFullList } from '../../helpers/countries';
import ExpInput from './ExpInput';
import CardNumberInput from './CardNumberInput';
const Card = ({ card, errors, onChange, loading = false }) => {
const countries = getFullList().map(({ value, label: text }) => ({ value, text }));
const handleChange = (key) => ({ target }) => onChange(key, target.value);
return (
<>
<Block>
<Input
autoComplete="cc-name"
name="ccname"
value={card.fullname}
onChange={handleChange('fullname')}
placeholder={c('Placeholder').t`Full name`}
error={errors.fullname}
disabled={loading}
required
/>
</Block>
<Block>
<CardNumberInput
value={card.number}
onChange={(value) => onChange('number', value)}
error={errors.number}
disabled={loading}
required
/>
</Block>
<div className="flex-autogrid">
<div className="flex-autogrid-item ">
<ExpInput
month={card.month}
year={card.year}
error={errors.month}
disabled={loading}
onChange={({ month, year }) => {
onChange('month', month);
onChange('year', year);
}}
required
/>
</div>
<div className="flex-autogrid-item">
<Input
autoComplete="cc-csc"
name="cvc"
value={card.cvc}
onChange={handleChange('cvc')}
placeholder={c('Placeholder, make it short').t`Security code`}
error={errors.cvc}
disabled={loading}
required
/>
</div>
</div>
<div className="flex-autogrid">
<div className="flex-autogrid-item">
<Select
value={card.country}
onChange={handleChange('country')}
options={countries}
disabled={loading}
autoComplete="country"
/>
</div>
<div className="flex-autogrid-item">
<Input
autoComplete="postal-code"
value={card.zip}
onChange={handleChange('zip')}
placeholder={card.country === 'US' ? c('Placeholder').t`ZIP` : c('Placeholder').t`Postal code`}
title={c('Title').t`ZIP / postal code`}
error={errors.zip}
disabled={loading}
minLength={3}
maxLength={9}
required
/>
</div>
</div>
</>
);
};
Card.propTypes = {
loading: PropTypes.bool,
card: PropTypes.object.isRequired,
errors: PropTypes.object.isRequired,
onChange: PropTypes.func.isRequired
};
export default Card;
| JavaScript | 0.000002 | @@ -405,16 +405,26 @@
el: text
+, disabled
%7D) =%3E (
@@ -436,16 +436,26 @@
ue, text
+, disabled
%7D));%0A
|
78019a55d01e77044b11d8dda072bd12c88c5430 | implement update() and destroy() API | VisComponent/mixin/VegaChart.js | VisComponent/mixin/VegaChart.js | import vega from '../../util/vega';
let VegaChart = (Base, spec) => class extends Base {
constructor (...args) {
super(...args);
this.options = args[1];
this.chart = vega.parseChart(spec, this.el, this.options);
}
render () {
this.chart.then(chart => {
if (this.width) {
chart = chart.width(this.width);
}
if (this.height) {
chart = chart.height(this.height);
}
chart.update();
});
}
get serializationFormats () {
return ['png', 'svg'];
}
serialize (format) {
if (!this.chart) {
return Promise.reject('The render() method must be called before serialize().');
}
return this.chart.then(vobj => {
return vobj.toImageURL(format);
});
}
};
export default VegaChart;
| JavaScript | 0 | @@ -456,16 +456,533 @@
);%0A %7D%0A%0A
+ update (options) %7B%0A let promise = this.chart;%0A%0A Object.assign(this.options, options);%0A%0A if (this.options.data) %7B%0A promise = promise.then(chart =%3E %7B%0A chart.data('data')%0A .remove(() =%3E true)%0A .insert(this.options.data);%0A %7D);%0A %7D%0A%0A if (this.options.width) %7B%0A this.width = this.options.width;%0A %7D%0A%0A if (this.options.height) %7B%0A this.height = this.options.height;%0A %7D%0A%0A return promise;%0A %7D%0A%0A destroy () %7B%0A this.empty();%0A delete this.chart;%0A %7D%0A%0A
get se
|
cfebcc162c37d5aba9a24ddfa8b9e41975c63852 | Update messages.js | app/assets/javascripts/messages.js | app/assets/javascripts/messages.js | // @flow
export default {
"save.failed_simultaneous_tracing": `It seems that you edited the tracing simultaneously in different windows.
Editing should be done in a single window only.
In order to restore the current window, a reload is necessary.`,
"save.failed_client_error": `We've encountered a permanent error while trying to save.
In order to restore the current window, a reload is necessary.`,
"save.leave_page_unfinished":
"You haven't saved your progress, please give us 2 seconds to do so and and then leave this site.",
"save.failed": "Failed to save tracing. Retrying.",
"finish.confirm": "Are you sure you want to permanently finish this tracing?",
"download.wait": "Please wait...",
"download.close_window": "You may close this window after the download has started.",
"add_script.confirm_change": "This will replace the code you have written. Continue?",
"tracing.copy_position": "Click this button to copy the position.",
"tracing.copy_rotation": "Click this button to copy the rotation.",
"tracing.no_more_branchpoints": "No more branchpoints",
"tracing.branchpoint_set": "Branchpoint set",
"tracing.branchpoint_jump_twice":
"You didn't add a node after jumping to this branchpoint, do you really want to jump again?",
"webgl.disabled": "Couldn't initialise WebGL, please make sure WebGL is enabled.",
"task.user_script_retrieval_error": "Unable to retrieve script",
"task.new_description": "You are now tracing a new task with the following description",
"task.no_description": "You are now tracing a new task with no description.",
"task.delete": "Do you really want to delete this task?",
"dataset.upload_success": "The dataset was uploaded successfully",
"dataset.confirm_signup":
"For dataset annotation, please log in or create an account. For dataset viewing, no account is required. Do you wish to sign up now?",
"annotation.delete": "Do you really want to delete this annotation?",
"annotation.dataset_no_public":
"Public tracings require the respective dataset to be public too. Please, make sure to add public access rights to the dataset as well.",
"project.delete": "Do you really want to delete this project?",
"script.delete": "Do you really want to delete this script?",
"team.delete": "Do you really want to delete this team?",
"taskType.delete": "Do you really want to delete this task type?",
"auth.registration_email_input": "Please input your E-mail!",
"auth.registration_email_invalid": "The input is not valid E-mail!",
"auth.registration_password_input": "Please input your password!",
"auth.registration_password_confirm": "Please confirm your password!",
"auth.registration_password_missmatch": "Passwords do not match!",
"auth.registration_password_length": "Passwords needs min. 8 characters.",
"auth.registration_firstName_input": "Please input your password!",
"auth.registration_lastName_input": "Please input your password!",
"auth.registration_team_input": "Please select a team!",
"auth.reset_logout": "You will be logged out, after successfully changing your password.",
"auth.reset_old_password": "Please input your old password!",
"auth.reset_new_password": "Please input your new password!",
"auth.reset_new_password2": "Please repeat your new password!",
"auth.reset_token": "Please input the token!",
"auth.reset_email_notification":
"An email with instructions to reset your password has been send to you.",
"auth.reset_pw_confirmation": "Your password was successfully changed",
"auth.account_created":
"Your account has been created. An administrator is going to unlock you soon.",
"auth.automatic_user_activation": "User was activated automatically",
"request.max_item_count_alert":
"Your request returned more than 1000 results. More results might be available on the server but were omitted for technical reasons.",
};
| JavaScript | 0.000001 | @@ -2870,32 +2870,34 @@
input your
-password
+first name
!%22,%0A %22auth.
@@ -2941,32 +2941,33 @@
input your
-password
+last name
!%22,%0A %22auth.
|
7973165887eed7f77def85fd92d4e7e417186636 | fix minimizer settings (#14795) | packages/gatsby-plugin-netlify-cms/src/gatsby-node.js | packages/gatsby-plugin-netlify-cms/src/gatsby-node.js | import path from "path"
import { get, mapValues, isPlainObject, trim } from "lodash"
import webpack from "webpack"
import HtmlWebpackPlugin from "html-webpack-plugin"
import HtmlWebpackExcludeAssetsPlugin from "html-webpack-exclude-assets-plugin"
import MiniCssExtractPlugin from "mini-css-extract-plugin"
// TODO: swap back when https://github.com/geowarin/friendly-errors-webpack-plugin/pull/86 lands
import FriendlyErrorsPlugin from "@pieh/friendly-errors-webpack-plugin"
/**
* Deep mapping function for plain objects and arrays. Allows any value,
* including an object or array, to be transformed.
*/
function deepMap(obj, fn) {
/**
* If the transform function transforms the value, regardless of type,
* return the transformed value.
*/
const mapped = fn(obj)
if (mapped !== obj) {
return mapped
}
/**
* Recursively deep map arrays and plain objects, otherwise return the value.
*/
if (Array.isArray(obj)) {
return obj.map(value => deepMap(value, fn))
}
if (isPlainObject(obj)) {
return mapValues(obj, value => deepMap(value, fn))
}
return obj
}
exports.onCreateDevServer = ({ app, store }, { publicPath = `admin` }) => {
const { program } = store.getState()
const publicPathClean = trim(publicPath, `/`)
app.get(`/${publicPathClean}`, function(req, res) {
res.sendFile(
path.join(program.directory, `public`, publicPathClean, `index.html`),
err => {
if (err) {
res.status(500).end(err.message)
}
}
)
})
}
exports.onCreateWebpackConfig = (
{ store, stage, getConfig, plugins, pathPrefix },
{
modulePath,
publicPath = `admin`,
enableIdentityWidget = true,
htmlTitle = `Content Manager`,
manualInit = false,
}
) => {
if (![`develop`, `build-javascript`].includes(stage)) {
return Promise.resolve()
}
const gatsbyConfig = getConfig()
const { program } = store.getState()
const publicPathClean = trim(publicPath, `/`)
const config = {
...gatsbyConfig,
entry: {
cms: [
manualInit && `${__dirname}/cms-manual-init.js`,
`${__dirname}/cms.js`,
enableIdentityWidget && `${__dirname}/cms-identity.js`,
]
.concat(modulePath)
.filter(p => p),
},
output: {
path: path.join(program.directory, `public`, publicPathClean),
},
module: {
/**
* Manually swap `style-loader` for `MiniCssExtractPlugin.loader`.
* `style-loader` is only used in development, and doesn't allow us to
* pass the `styles` entry css path to Netlify CMS.
*/
rules: deepMap(gatsbyConfig.module.rules, value => {
if (
typeof get(value, `loader`) === `string` &&
value.loader.includes(`style-loader`)
) {
return { ...value, loader: MiniCssExtractPlugin.loader }
}
return value
}),
},
plugins: [
/**
* Remove plugins that either attempt to process the core Netlify CMS
* application, or that we want to replace with our own instance.
*/
...gatsbyConfig.plugins.filter(
plugin =>
![`MiniCssExtractPlugin`, `GatsbyWebpackStatsExtractor`].find(
pluginName =>
plugin.constructor && plugin.constructor.name === pluginName
)
),
/**
* Provide a custom message for Netlify CMS compilation success.
*/
stage === `develop` &&
new FriendlyErrorsPlugin({
clearConsole: false,
compilationSuccessInfo: {
messages: [
`Netlify CMS is running at ${program.ssl ? `https` : `http`}://${
program.host
}:${program.port}/${publicPathClean}/`,
],
},
}),
/**
* Use a simple filename with no hash so we can access from source by
* path.
*/
new MiniCssExtractPlugin({
filename: `[name].css`,
}),
/**
* Auto generate CMS index.html page.
*/
new HtmlWebpackPlugin({
title: htmlTitle,
chunks: [`cms`],
excludeAssets: [/cms.css/],
}),
/**
* Exclude CSS from index.html, as any imported styles are assumed to be
* targeting the editor preview pane. Uses `excludeAssets` option from
* `HtmlWebpackPlugin` config.
*/
new HtmlWebpackExcludeAssetsPlugin(),
/**
* Pass in needed Gatsby config values.
*/
new webpack.DefinePlugin({
__PATH__PREFIX__: pathPrefix,
CMS_PUBLIC_PATH: JSON.stringify(publicPath),
}),
].filter(p => p),
/**
* Remove common chunks style optimizations from Gatsby's default
* config, they cause issues for our pre-bundled code.
*/
mode: stage === `develop` ? `development` : `production`,
optimization: {
/**
* Without this, node can get out of memory errors
* when building for production.
*/
minimizer: gatsbyConfig.optimization.minimizer,
},
devtool: stage === `develop` ? `cheap-module-source-map` : `source-map`,
}
return new Promise((resolve, reject) => {
if (stage === `develop`) {
webpack(config).watch({}, () => {})
return resolve()
}
return webpack(config).run((err, stats) => {
if (err) return reject(err)
const errors = stats.compilation.errors || []
if (errors.length > 0) return reject(stats.compilation.errors)
return resolve()
})
})
}
| JavaScript | 0 | @@ -4989,16 +4989,43 @@
nimizer:
+ stage === %60develop%60 ? %5B%5D :
gatsbyC
|
fda17b5e200538826ff4501ef429f56b2839c958 | fix package.json template | packages/gluestick/src/generator/templates/package.js | packages/gluestick/src/generator/templates/package.js | /* @flow */
import type { CreateTemplate } from '../../types';
const version = require('../../../package.json').version;
module.exports = (createTemplate: CreateTemplate) => createTemplate`
{
"name": "${(args) => args.appName}",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "gluestick start",
"test": "gluestick test",
"flow": "flow",
"lint": "eslint src"
},
"dependencies": {
"babel-core": "6.22.1",
"babel-loader": "6.2.10",
"babel-plugin-gluestick": "0.0.1",
"babel-plugin-transform-decorators-legacy": "1.3.4",
"babel-preset-es2015": "6.22.0",
"babel-preset-react": "6.22.0",
"babel-preset-stage-0": "6.22.0",
"css-loader": "0.26.1",
"file-loader": "0.9.0",
"gluestick": "${
(args) => args.dev || version
}",
"image-webpack-loader": "3.1.0",
"normalize.css": "^5.0.0",
"react": "15.4.2",
"react-dom": "15.4.2",
"react-helmet": "4.0.0",
"react-redux": "5.0.2",
"react-router": "3.0.2",
"redux": "3.6.0",
"sass-loader": "4.1.1",
"style-loader": "0.13.1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-eslint": "7.1.1",
"babel-jest": "18.0.0",
"babel-plugin-react-transform": "2.0.2",
"enzyme": "2.7.1",
"eslint": "3.14.1",
"eslint-plugin-react": "6.9.0",
"flow-bin": "${(args) => args.flowVersion}",
"react-addons-test-utils": "15.4.2",
"react-hot-loader": "1.3.1",
"react-transform-catch-errors": "1.0.2",
"react-transform-hmr": "1.0.4",
"redbox-react": "1.3.3",
"webpack-hot-middleware": "2.15.0"
}
}
`;
| JavaScript | 0.000002 | @@ -115,16 +115,115 @@
version;
+%0Aconst path = require('path');%0A%0A/**%0A * TODO: include also other packages if dev flag was passed%0A */
%0A%0Amodule
@@ -909,10 +909,59 @@
dev
-%7C%7C
+? path.join('..', args.dev, 'packages/gluestick') :
ver
|
28720548ef3393d169be59acc66f4fa54c6e1f45 | fix spacing | UWPWebBrowser/js/appBarColor.js | UWPWebBrowser/js/appBarColor.js | /*
This function expects two hexStrings and relies on hexStrToRGBA to convert
to a JSON object that represents RGBA for the underlying Windows API to
understand.
Examples of valid values:
setAppBarColors('#FFFFFF','#000000');
setAppBarColors('#FFF','#000');
setAppBarColors('FFFFFF','000000');
setAppBarColors('FFF','000');
*/
"use strict";
function setAppBarColors () {
// Detect if the Windows namespace exists in the global object
if (typeof Windows !== 'undefined' &&
typeof Windows.UI !== 'undefined' &&
typeof Windows.UI.ViewManagement !== 'undefined') {
// Get a reference to the App Title Bar
var appTitleBar = Windows.UI.ViewManagement.ApplicationView.getForCurrentView().titleBar;
// Set your default colors
var brand = hexStrToRGBA('#3B3B3B');
var black = hexStrToRGBA('#000');
var white = hexStrToRGBA('#FFF');
var gray = hexStrToRGBA('#666');
appTitleBar.foregroundColor = white;
appTitleBar.backgroundColor = brand;
appTitleBar.buttonForegroundColor = white;
appTitleBar.buttonBackgroundColor = brand;
appTitleBar.buttonHoverForegroundColor = white;
appTitleBar.buttonHoverBackgroundColor = gray;
appTitleBar.buttonPressedForegroundColor = brand;
appTitleBar.buttonPressedBackgroundColor = white;
appTitleBar.inactiveForegroundColor = gray;
appTitleBar.inactiveBackgroundColor = brand;
appTitleBar.buttonInactiveForegroundColor = gray;
appTitleBar.buttonInactiveBackgroundColor = brand;
appTitleBar.buttonInactiveHoverForegroundColor = white;
appTitleBar.buttonInactiveHoverBackgroundColor = brand;
appTitleBar.buttonPressedForegroundColor = brand;
appTitleBar.buttonPressedBackgroundColor = brand;
}
}
// Helper function to support HTML hexColor Strings
function hexStrToRGBA(hexStr) {
// RGBA color object
var colorObject = { r: 255, g: 255, b: 255, a: 255 };
// remove hash if it exists
hexStr = hexStr.replace('#', '');
if (hexStr.length === 6) {
// No Alpha
colorObject.r = parseInt(hexStr.slice(0, 2), 16);
colorObject.g = parseInt(hexStr.slice(2, 4), 16);
colorObject.b = parseInt(hexStr.slice(4, 6), 16);
colorObject.a = parseInt('0xFF', 16);
} else if (hexStr.length === 8) {
// Alpha
colorObject.r = parseInt(hexStr.slice(0, 2), 16);
colorObject.g = parseInt(hexStr.slice(2, 4), 16);
colorObject.b = parseInt(hexStr.slice(4, 6), 16);
colorObject.a = parseInt(hexStr.slice(6, 8), 16);
} else if (hexStr.length === 3) {
// Shorthand hex color
var rVal = hexStr.slice(0, 1);
var gVal = hexStr.slice(1, 2);
var bVal = hexStr.slice(2, 3);
colorObject.r = parseInt(rVal + rVal, 16);
colorObject.g = parseInt(gVal + gVal, 16);
colorObject.b = parseInt(bVal + bVal, 16);
} else {
throw new Error('Invalid HexString length. Expected either 8, 6, or 3. The actual length was ' + hexStr.length);
}
return colorObject;
}
// Initialize when the window loads
addEventListener('load', setAppBarColors); | JavaScript | 0.000054 | @@ -1954,16 +1954,17 @@
trToRGBA
+
(hexStr)
@@ -1962,24 +1962,24 @@
(hexStr) %7B%0A
-
// RGBA
@@ -2057,17 +2057,17 @@
%0A //
-r
+R
emove ha
@@ -2389,32 +2389,36 @@
xFF', 16);%0A %7D
+%0A
else if (hexStr
@@ -2684,24 +2684,28 @@
, 16);%0A %7D
+%0A
else if (he
@@ -3026,21 +3026,25 @@
l, 16);%0A
-
%7D
+%0A
else %7B%0A
|
08c9c2c01c371cb712bdde3899d591317be50158 | remove redundant code | app/controllers/user.controller.js | app/controllers/user.controller.js | var jwt = require('jsonwebtoken');
var User = require('../models/user.model');
// var Document = require('../models/document.model');
var config = require('../../config/config');
// this method creates a new document
exports.createUser = function(req, res) {
var user = new User();
user.username = req.body.username;
user.name = {
first: req.body.first,
last: req.body.last
};
user.email = req.body.email;
user.password = req.body.password;
user.save(function(err) {
if (!user.username || !user.email || !user.password) {
return res.status(401).send({
success: false,
message: 'Invalid Username or Email or Password!'
});
}
else if (!user.name.first || !user.name.first) {
return res.status(401).send({
success: false,
message: 'Invalid Firstname or Lastname!'
});
}
else if (err) {
if (err.code === 11000) {
return res.status(401).send({
success: false,
message: 'Username Already Exists!'
});
}
else {
return res.status(401).send(err);
}
}
else {
var token = jwt.sign(user, config.secret, {
expiresIn: 1440
});
res.status(200).send({
success: true,
token: token,
message: 'User Created.',
id: user._id
});
}
});
};
// this method logs a user in
exports.login = function(req, res) {
User.findOne({
username: req.body.username})
.select('username password')
.exec(function(err, user) {
if (err) {
throw err;
}
if (!user) {
return res.status(401).send({
success: false,
message: 'Invalid Username or Password!'
});
}
else {
var validPassword = user.comparePassword(req.body.password);
if (!validPassword) {
return res.status(401).send({
success: false,
message: 'Invalid Username or Password!'
});
}
else {
var token = jwt.sign(user, config.secret, {
expiresIn: 1440
});
res.json({
success: true,
message: 'Token generated.',
token: token,
id: user._id
});
}
}
});
};
// this method authenticates user
exports.middleware = function(req, res, next) {
var token = req.body.token ||
req.query.token ||
req.headers['x-access-token'];
if (token) {
jwt.verify(token, config.secret, function(err, decoded) {
if (err) {
return res.json({
success: false,
message: 'Failed to authenticate token.' });
}
else {
req.decoded = decoded;
next();
}
});
}
else {
return res.status(403).send({
success: false,
message: 'No token provided.'
});
}
};
// this method logs a user out
exports.logout = function(req, res) {
req.session.destroy(function(err, success) {
if (err) {
res.send(err);
}
else {
res.send({
success: true,
message: 'You have logged out.'
});
}
});
};
// this method returns all users
exports.getAllUsers = function(req, res) {
User.find({}).exec(function(err, users) {
if (err) {
res.send(err);
}
else if (!users) {
res.status(404).send({
success: false,
message: 'Users not found!'
});
}
else {
res.json(users);
}
});
};
// this method returns a single user
exports.getUser = function(req, res) {
User.findById(req.params.id, function(err, user) {
if (err) {
res.send(err);
}
else {
res.json(user);
}
});
};
// this method allows user information to be edited
exports.editUser = function(req, res) {
User.findByIdAndUpdate(req.params.id, req.body, function(err, user) {
res.send({
success: true,
message: 'User Updated!'
});
});
};
// this method deletes single document
exports.deleteUser = function(req, res) {
User.findById(req.params.id).remove(function(err, user) {
if (err) {
return res.send(err);
}
else {
res.send({
success: true,
message: 'User Deleted'
});
}
});
};
| JavaScript | 0.000231 | @@ -76,63 +76,8 @@
');%0A
-// var Document = require('../models/document.model');%0A
var
@@ -1243,22 +1243,33 @@
e: '
-User Created.'
+Welcome ' + user.username
,%0A
@@ -2092,25 +2092,33 @@
e: '
-Token generated.'
+Welcome ' + user.username
,%0A
@@ -3835,20 +3835,23 @@
ssage: '
-User
+Account
Updated
@@ -4130,20 +4130,23 @@
ssage: '
-User
+Account
Deleted
|
2d7605905267334b0dcffe4e12c930c5b8c8b1ba | refactor urls as variables in tweetFactory | app/js/core/services/TweetFactory.js | app/js/core/services/TweetFactory.js | 'use strict';
app.factory('TweetFactory', ['$rootScope', function($rootScope) {
var tweets = {};
var url = "/1.1/statuses/user_timeline.json";
tweets.getTweets = function() {
return $rootScope.twitterOAuthResult.get(url)
// .success(function(response) {
// $rootScope.tweets = response;
// // show the home page once tweets are retrieved
// $rootScope.go('/home');
// })
};
tweets.postTweet = function(text) {
$rootScope.twitterOAuthResult.post('/1.1/statuses/update.json', {
data: {
status: text
}
}).success(function(response) {
alert("Tweet Sent");
})
}
return tweets;
}]) | JavaScript | 0.001322 | @@ -97,21 +97,67 @@
%7B%7D;%0A
+%09var postUrl = '/1.1/statuses/update.json';
%0A%09var
-u
+getU
rl =
-%22
+'
/1.1
@@ -188,10 +188,12 @@
json
-%22;
+';%0A%09
%0A%09tw
@@ -269,180 +269,16 @@
get(
-url)%0A%09%09%09// .success(function(response) %7B%0A%09%09%09// %09$rootScope.tweets = response;%0A%09%09%09// %09// show the home page once tweets are retrieved%0A%09%09%09// %09$rootScope.go('/home');%0A%09%09%09// %7D)
+getUrl);
%0A%09%7D;
@@ -357,35 +357,15 @@
ost(
-'/1.1/statuses/update.json'
+postUrl
, %7B%0A
|
fcb92d70a111c538d5c657009903bad9abaf1187 | Fix user feed selection | app/routes/users/UserProfileRoute.js | app/routes/users/UserProfileRoute.js | // @flow
import { compose } from 'redux';
import { connect } from 'react-redux';
import UserProfile from './components/UserProfile';
import { fetchUser } from 'app/actions/UserActions';
import { fetchUserFeed } from 'app/actions/FeedActions';
import {
selectFeedById,
selectFeedActivitesByFeedId,
feedIdByUserId
} from 'app/reducers/feeds';
import { selectUserWithGroups } from 'app/reducers/users';
import loadingIndicator from 'app/utils/loadingIndicator';
import replaceUnlessLoggedIn from 'app/utils/replaceUnlessLoggedIn';
import prepare from 'app/utils/prepare';
import { LoginPage } from 'app/components/LoginForm';
const loadData = ({ params: { username } }, dispatch) => {
return dispatch(fetchUser(username)).then(action =>
dispatch(fetchUserFeed(action.payload.result))
);
};
const mapStateToProps = (state, props) => {
const { params } = props;
const username =
params.username === 'me' ? state.auth.username : params.username;
const user = selectUserWithGroups(state, { username });
const feed = selectFeedById(state, { feedId: feedIdByUserId(state.auth.id) });
const feedItems = selectFeedActivitesByFeedId(state, {
feedId: feedIdByUserId(state.auth.id)
});
const isMe =
params.username === 'me' || params.username === state.auth.username;
const actionGrant = (user && user.actionGrant) || [];
const showSettings = isMe || actionGrant.includes('edit');
return {
username,
auth: state.auth,
loggedIn: props.loggedIn,
user,
feed,
feedItems,
showSettings,
isMe
};
};
const mapDispatchToProps = { fetchUser, fetchUserFeed };
export default compose(
replaceUnlessLoggedIn(LoginPage),
prepare(loadData, ['params.username']),
connect(mapStateToProps, mapDispatchToProps),
loadingIndicator(['user'])
)(UserProfile);
| JavaScript | 0.000004 | @@ -1076,34 +1076,28 @@
dIdByUserId(
-state.auth
+user
.id) %7D);%0A c
@@ -1177,26 +1177,20 @@
yUserId(
-state.auth
+user
.id)%0A %7D
|
43437ab9ec8b6fafbff09a918e6d8fa0175e2278 | fix bug that kepy size from properly incrementing | app/services/database/mapConcepts.js | app/services/database/mapConcepts.js | "use strict"
const mongoose = require('mongoose'),
Q = require('q'),
Article = require('../../models/Article'),
Concept = require('../../models/Concept');
module.exports = () => {
console.log('mapping articles to concepts')
Article.find()
.exec((err, collection) => {
collection.forEach((article)=>{
if (!article.mapped) {
article.mapped = true;
article.save((err, result) => {
if (err) throw err;
})
}
article.concepts.forEach((articleConcept)=>{
Concept.findOne({label: articleConcept.concept.label})
.exec((err, concept)=>{
if (!concept) {
let newConcept = new Concept({
"id": articleConcept.concept.id,
"label": articleConcept.concept.label,
"articles": [article._id],
"size": 1
})
newConcept.save((err, result) => {
if (err) throw err;
})
} else
// if the concept exists, add the article id to it's list
{
// console.log(concept)
if (concept.articles.indexOf(article._id) == -1) {
concept.articles.push(article._id)
if (concept.size) {
concept.size = concept.articles.length
} else {
concept.size = 1
}
concept.save((err, result) => {
if (err) throw err;
})
}//end if
} ///end else
})//end exec
}) //end for each
// }//end if
}) //end for each
}) //end exec
} | JavaScript | 0 | @@ -640,32 +640,33 @@
r, concept)=%3E%7B%0A%0A
+%0A
@@ -682,17 +682,16 @@
ept) %7B%0A%0A
-%0A
@@ -1212,16 +1212,89 @@
oncept)%0A
+ // console.log('updating', articleConcept.concept.label)%0A
@@ -1409,19 +1409,16 @@
le._id)%0A
-%0A
@@ -1431,34 +1431,18 @@
-if (concept.size) %7B%0A
+%7D//end if%0A
@@ -1496,103 +1496,9 @@
gth%0A
- %7D else %7B%0A concept.size = 1%0A %7D%0A%0A
+%0A
@@ -1551,35 +1551,32 @@
-
if (err) throw e
@@ -1599,42 +1599,11 @@
-
-
%7D)%0A
- %7D//end if
%0A
|
9aaa665d2ae3a29c19a46a30c6bc3e4d0aafd2f8 | Simplify removing of last stackitem | app/src/js/widgets/buic/buicStack.js | app/src/js/widgets/buic/buicStack.js | /**
* @param {Object} $ - Global jQuery object
* @param {Object} bolt - The Bolt module
*/
(function ($, bolt) {
'use strict';
/**
* BUIC stack widget.
*
* @license http://opensource.org/licenses/mit-license.php MIT License
* @author rarila
*
* @class buicStack
* @memberOf jQuery.widget.bolt
*/
$.widget('bolt.buicStack', /** @lends jQuery.widget.bolt.buicStack.prototype */ {
/**
* The constructor of the stack widget.
*
* @private
*/
_create: function () {
/**
* Refs to UI elements of this widget.
*
* @type {Object}
* @name _ui
* @memberOf jQuery.widget.bolt.buicStack.prototype
* @private
*
* @property {Object} holder - Stackholder
*/
this._ui = {
holder: this.element.find('.stackholder')
};
bolt.uploads.bindStack(this.element);
},
/**
* Add a file to the stack.
*
* @param {string} path - Path to add to the stack
*/
add: function (path) {
bolt.stack.addToStack(path);
},
/**
* Add a file item to the stack display.
*
* @param {string} path - Path to add to the stack
*/
prepend: function (path) {
var stack = $('.stackitem', this._ui.holder),
ext = path.substr(path.lastIndexOf('.') + 1).toLowerCase(),
item,
html,
i;
// Move all current items one down, and remove the last one.
for (i = stack.length; i >= 1; i--) {
item = $('.stackitem.item-' + i, this._ui.holder);
item.addClass('item-' + (i + 1)).removeClass('item-' + i);
}
if ($('.stackitem.item-8', this._ui.holder).is('*')) {
$('.stackitem.item-8', this._ui.holder).remove();
}
// Insert new item at the front.
if (ext === 'jpg' || ext === 'jpeg' || ext === 'png' || ext === 'gif') {
html = $('#protostack div.image').clone();
$(html).find('img').attr('src', bolt.conf('paths.bolt') + '../thumbs/100x100c/' + encodeURI(path));
} else {
html = $('#protostack div.other').clone();
$(html).find('strong').html(ext.toUpperCase());
$(html).find('small').html(path);
}
this._ui.holder.prepend(html);
// If the "empty stack" notice was showing, remove it.
$('.nostackitems').remove();
}
});
})(jQuery, Bolt);
| JavaScript | 0.000044 | @@ -1916,20 +1916,16 @@
-if (
$('.stac
@@ -1933,82 +1933,21 @@
item
-.item-8', this._ui.holder).is('*')) %7B%0A $('.stackitem.item-8
+:nth-child(7)
', t
@@ -1971,30 +1971,16 @@
emove();
-%0A %7D
%0A%0A
|
4233b0a54c651b83ead9dd1c6b1c50f71bb9d445 | add a test | __tests__/request-validation.js | __tests__/request-validation.js | const request = require('supertest')
const app = require('../examples/stranger-things')
test('successful POST /characters', () => {
return request(app)
.post('/characters')
.send({name: 'Nancy Wheeler'})
.expect(201)
})
test('invalid POST /characters', () => {
return request(app)
.post('/characters')
.expect(400)
})
| JavaScript | 0.000109 | @@ -333,12 +333,146 @@
ect(400)%0A%7D)%0A
+%0Atest('invalid POST /characters (2)', () =%3E %7B%0A return request(app)%0A .post('/characters')%0A .send(%7Bname: 1%7D)%0A .expect(400)%0A%7D)%0A
|
1a9466bd892907fdf2bcb1ffe65e4582433c4325 | Update index.js | Paramour/index.js | Paramour/index.js | var
paramours = $(".compile-paramour"),
javascripts = $(".compile-javascript"),
paramour_textarea = $(".edit-paramour")[0],
javascript_textarea = $(".edit-javascript")[0],
poptions = {
mode: "paramour",
lineNumbers: false,
styleActiveLine: true,
matchBrackets: true,
indentUnit: 2,
tabsize: 2,
indentWithTabs: false,
readOnly: false,
autofocus: false,
lineSeperator: "\n",
theme: "tomorrow-night-bright",
fold: "brace"
},
joptions = {
mode: "javascript",
lineNumbers: false,
styleActiveLine: true,
matchBrackets: true,
indentUnit: 2,
tabsize: 2,
indentWithTabs: false,
readOnly: true,
autofocus: false,
lineSeperator: "\n",
theme: "tomorrow-night-bright",
fold: "brace"
}, Peditor, Jeditor;
// Duds
for(var x = 0; x < paramours.length; x++)
CodeMirror.fromTextArea(paramours[x], poptions);
for(x = 0; x < javascripts.length; x++) {
javascripts[x].value = Paramour(paramours[x].value, true);
CodeMirror.fromTextArea(javascripts[x], joptions);
}
// Actual scripts
poptions.readOnly = false;
Peditor = CodeMirror.fromTextArea(paramour_textarea, poptions);
javascript_textarea.value = Paramour(paramour_textarea.value, true);
Jeditor = CodeMirror.fromTextArea(javascript_textarea, joptions);
window.Peditor = Peditor, window.Jeditor = Jeditor;
| JavaScript | 0.000002 | @@ -980,21 +980,30 @@
%5D.value,
+ %7Bembed:
true
+%7D
);%0A Cod
@@ -1224,21 +1224,30 @@
a.value,
+ %7Bembed:
true
+%7D
);%0AJedit
|
281c93b0794d2dd35a216ef355791640ae7ef0c6 | Update jiveCommentHandler.js | GitHub4Jive-Addon/services/jive/backend/webhooks/jiveCommentHandler.js | GitHub4Jive-Addon/services/jive/backend/webhooks/jiveCommentHandler.js | /*
* Copyright 2014 Jive Software
*
* 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.
*/
var q = require("q");
var libDir = process.cwd() + "/lib/";
var gitFacade = require(libDir + "github4jive/gitHubFacade");
var helpers = require("./helpers");
function formatGitComment(japi, user, userPage, hookPayload) {
return "<!--Jive-->\n"+ //placeHolder so that GitHubWebhook handler can tell if the comment originated from Jive
"[[Jive](" + japi.community.jiveUrl + ") - [" + user.displayName +"](" + userPage + ")] " // On behalf of information
+ hookPayload.object.summary; //The comment text
}
/*
* create a GitHub comment on the issue associated with the discussion in the webhook
* @param {object} hookPayload entire Jive webhookPayload that contains a message that was marked as the answer
* @return {promise}
*/
exports.createGitHubComment = function (hookPayload) {
var placeURL = hookPayload.target.id;
var jiveMessageReply = hookPayload.object;
return helpers.getPlace(placeURL)
.then(function (place) { return helpers.getJiveApi(place)
.then(function (japi) { return helpers.hydrateObject(japi, jiveMessageReply)
.then(function (message) { return message.retrieveAllExtProps()
.then(function (commentprops) {
if (commentprops.fromGitHub) {//Check for a jiveMessageReply originally from GitHub
return q();
}
//then check if the jiveMessageReply was even on a linked discussion
var discussion = helpers.getDiscussionUrl(message);
return japi.getAllExtProps(discussion).then(function (props) {
var issueNumber = props.github4jiveIssueNumber;
if (!issueNumber) {//Discussion is not linked to an issue so we can throw this payload out
return q();
}
//finally, create the jiveMessageReply on GitHub with relevant user data
return japi.get(hookPayload.object.author.id).then(function (user) {
user = user.entity;
var userPage = user.resources.html.ref;
var gitComment = formatGitComment(japi, user, userPage, hookPayload);
var auth = gitFacade.createOauthObject(place.github.token.access_token);
return gitFacade.addNewComment(place.github.repoOwner, place.github.repo,
issueNumber, gitComment, auth).then(function (response) {
})
});
});
});
});
});
});
};
| JavaScript | 0 | @@ -1797,24 +1797,24 @@
nction (
-commentp
+messageP
rops) %7B%0A
@@ -1833,16 +1833,16 @@
if (
-commentp
+messageP
rops
|
20f9cf537d47b63330756006450009a97d5906b5 | apply the app nav color to the SFViewControllers too | source/views/components/open-url.js | source/views/components/open-url.js | // @flow
import {Platform, Linking, StatusBar} from 'react-native'
import {tracker} from '../../analytics'
import SafariView from 'react-native-safari-view'
import {CustomTabs} from 'react-native-custom-tabs'
const iosOnShowListener = () => StatusBar.setBarStyle('dark-content')
const iosOnDismissListener = () => StatusBar.setBarStyle('light-content')
export function startStatusBarColorChanger() {
return SafariView.isAvailable()
.then(() => {
SafariView.addEventListener('onShow', iosOnShowListener)
SafariView.addEventListener('onDismiss', iosOnDismissListener)
})
.catch(() => {})
}
export function stopStatusBarColorChanger() {
return SafariView.isAvailable()
.then(() => {
SafariView.removeEventListener('onShow', iosOnShowListener)
SafariView.removeEventListener('onDismiss', iosOnDismissListener)
})
.catch(() => {})
}
function genericOpen(url: string) {
return Linking.canOpenURL(url)
.then(isSupported => {
if (!isSupported) {
console.warn('cannot handle', url)
}
return Linking.openURL(url)
})
.catch(err => {
tracker.trackException(err)
console.error(err)
})
}
function iosOpen(url: string) {
// SafariView.isAvailable throws if it's not available
return SafariView.isAvailable()
.then(() => SafariView.show({url}))
.catch(() => genericOpen(url))
}
function androidOpen(url: string) {
return CustomTabs.openURL(url, {
showPageTitle: true,
enableUrlBarHiding: true,
enableDefaultShare: true,
}).catch(() => genericOpen(url)) // fall back to opening in Chrome / Browser / platform default
}
export default function openUrl(url: string) {
const protocol = /^(.*?):/.exec(url)
if (protocol.length) {
switch (protocol[1]) {
case 'tel':
return genericOpen(url)
case 'mailto':
return genericOpen(url)
default:
break
}
}
switch (Platform.OS) {
case 'android':
return androidOpen(url)
case 'ios':
return iosOpen(url)
default:
return genericOpen(url)
}
}
export {openUrl}
export function trackedOpenUrl({url, id}: {url: string, id?: string}) {
tracker.trackScreenView(id || url)
return openUrl(url)
}
export function canOpenUrl(url: string) {
// iOS navigates to about:blank when you provide raw HTML to a webview.
// Android navigates to data:text/html;$stuff (that is, the document you passed) instead.
if (/^(?:about|data):/.test(url)) {
return false
}
return true
}
| JavaScript | 0 | @@ -62,16 +62,46 @@
ative'%0A%0A
+import * as c from './colors'%0A
import %7B
@@ -239,650 +239,162 @@
s'%0A%0A
-const iosOnShowListener = () =%3E StatusBar.setBarStyle('dark-content')%0Aconst iosOnDismissListener = () =%3E StatusBar.setBarStyle('light-content')%0Aexport function startStatusBarColorChanger() %7B%0A%09return SafariView.isAvailable()%0A%09%09.then(() =%3E %7B%0A%09%09%09SafariView.addEventListener('onShow', iosOnShowListener)%0A%09%09%09SafariView.addEventListener('onDismiss', iosOnDismissListener)%0A%09%09%7D)%0A%09%09.catch(() =%3E %7B%7D)%0A%7D%0A%0Aexport function stopStatusBarColorChanger() %7B%0A%09return SafariView.isAvailable()%0A%09%09.then(() =%3E %7B%0A%09%09%09SafariView.removeEventListener('onShow', iosOnShowListener)%0A%09%09%09SafariView.removeEventListener('onDismiss', iosOnDismissListener)%0A%09%09%7D)%0A%09%09.catch(() =%3E %7B%7D
+export function startStatusBarColorChanger() %7B%0A%09return Promise.resolve(null)%0A%7D%0A%0Aexport function stopStatusBarColorChanger() %7B%0A%09return Promise.resolve(null
)%0A%7D%0A
@@ -824,16 +824,46 @@
how(%7Burl
+, barTintColor: c.carletonBlue
%7D))%0A%09%09.c
|
0459d1f5dbb9431e098b3cc2f23a633e2f299dcf | Update xform.js | jive-sdk-service/generator/examples/simple-stream/extension_src/data/xform.js | jive-sdk-service/generator/examples/simple-stream/extension_src/data/xform.js | function transform(body, headers, options, callback) {
/*
* TO DO: Parse 'body' arg based on incoming event from 3rd party system.
* TO DO: Replace the sample code below with your own transformation code.
*/
// Build activity object.
var activityInfo = { actor: {}, object:{}, jive:{} };
// Optional name of actor for this activity. Remove if n/a.
// activityInfo.actor.name = "Jane Doe";
// Optional email of actor for activity. Remove if n/a.
// activityInfo.actor.email = "janedoe@example.com";
// Optional URL for this activity. Remove if n/a.
activityInfo.object.url = "https://developer.jivesoftware.com";
// Required URL to the image for this activity.
activityInfo.object.image = "https://developer.jivesoftware.com/DeveloperAssets/images/icons/jivedev-med.png";
// Required title of the activity.
activityInfo.object.title = body.title;
// Optional HTML description of activity. Remove if n/a.
activityInfo.object.description = body.description;
// Optional ... Removes the Go To Item Link in the Activity Stream Link (User will use the tile)
//activityInfo.object.hideGoToItem = true;
/*** TEMPORARY WORKAROUND NEEDED FOR REFERENCING STRUCTURES IN body, headers, options RATHER THAN INDIVIDUALLY TRAVERSING EACH KEY ***/
function clone(obj) { if (null == obj || "object" != typeof obj) return obj; var copy = {}; for (var attr in obj) { copy[attr] = clone(obj[attr]); } return copy; }
body = clone(body);
headers = clone(headers);
options = clone(options);
/*** END TEMPORARY WORK AROUND ****/
activityInfo.jive.app = {
'appUUID': "{{{GENERATED_APP_UUID}}}",
'view': "ext-object",
'context': {
'timestamp': new Date().toISOString(),
'body': body,
'headers': headers,
'options': options
}
}
/*
* Call the callback function with our transformed activity information
*/
callback({ "activity" : activityInfo });
} | JavaScript | 0 | @@ -1105,435 +1105,8 @@
rue;
-%0A%0A/*** TEMPORARY WORKAROUND NEEDED FOR REFERENCING STRUCTURES IN body, headers, options RATHER THAN INDIVIDUALLY TRAVERSING EACH KEY ***/%0Afunction clone(obj) %7B if (null == obj %7C%7C %22object%22 != typeof obj) return obj; var copy = %7B%7D; for (var attr in obj) %7B copy%5Battr%5D = clone(obj%5Battr%5D); %7D return copy; %7D %0Abody = clone(body); %0Aheaders = clone(headers); %0Aoptions = clone(options); %0A/*** END TEMPORARY WORK AROUND ****/
%0A %0A
@@ -1466,9 +1466,10 @@
fo %7D);%0A%0A
-
%7D
+%0A
|
0a945db928c7c5bde63c62bd5f859e0f761c9c08 | Create saveSurvey thunk | app/javascript/app/components/modal-download/modal-download-actions.js | app/javascript/app/components/modal-download/modal-download-actions.js | import { createAction } from 'redux-actions';
const setModalDownloadParams = createAction('setModalDownloadParams');
const toggleModalDownload = createAction('toggleModalDownload');
export default {
setModalDownloadParams,
toggleModalDownload
};
| JavaScript | 0 | @@ -43,142 +43,679 @@
s';%0A
-%0Aconst setModalDownloadParams = createAction('setModalDownloadParams');%0Aconst toggleModalDownload = createAction('toggleModalDownload'
+import %7B createThunkAction %7D from 'utils/redux';%0Aimport %7B USER_SURVEY_SPREADSHEET_URL %7D from 'data/constants';%0A%0Aconst setModalDownloadParams = createAction('setModalDownloadParams');%0Aconst setRequiredFieldsError = createAction('setRequiredFieldsError');%0Aconst toggleModalDownload = createAction('toggleModalDownload');%0A%0Aconst saveSurveyData = createThunkAction(%0A 'saveSurveyData',%0A requestParams =%3E (dispatch, getState) =%3E %7B%0A const %7B modalDownload %7D = getState();%0A if (!modalDownload.requiredError) %7B%0A fetch(%0A %60$%7BUSER_SURVEY_SPREADSHEET_URL%7D?$%7BrequestParams.join('&')%7D%60%0A ).then(() =%3E window.location.assign(modalDownload.downloadUrl));%0A %7D%0A %7D%0A
);%0A%0A
@@ -757,16 +757,42 @@
Params,%0A
+ setRequiredFieldsError,%0A
toggle
@@ -804,12 +804,30 @@
Download
+,%0A saveSurveyData
%0A%7D;%0A
|
55bd4bf8c3e7e84f09b85e3b5019978d541f6720 | Add cations like redux strucure | src/actions/actions.js | src/actions/actions.js | import fetch from 'isomorphic-fetch'
export const REQUEST_BUS_STOPS = 'REQUEST_BUS_STOPS'
export const RECEIVE_BUS_STOPS = 'RECEIVE_BUS_STOPS'
function requestBusStops(meters, coors) {
return {
type: REQUEST_POSTS
}
}
function receiveBusStops(received) {
return {
type: RECEIVE_POSTS
}
}
| JavaScript | 0.999954 | @@ -31,16 +31,40 @@
fetch'%0A%0A
+//%0A// action types%0A//%0A%0A
export c
@@ -81,24 +81,34 @@
ST_BUS_STOPS
+_AROUND_ME
= 'REQUEST_
@@ -116,16 +116,26 @@
US_STOPS
+_AROUND_ME
'%0Aexport
@@ -158,16 +158,26 @@
US_STOPS
+_AROUND_ME
= 'RECE
@@ -189,19 +189,63 @@
US_STOPS
-'%0A%0A
+_AROUND_ME'%0A%0A//%0A// action creators%0A//%0A%0Aexport
function
@@ -260,16 +260,24 @@
BusStops
+AroundMe
(meters,
@@ -319,21 +319,58 @@
EST_
-POSTS
+BUS_STOPS_AROUND_ME,%0A meters,%0A coors
%0A %7D%0A%7D%0A%0A
func
@@ -365,16 +365,23 @@
%0A %7D%0A%7D%0A%0A
+export
function
@@ -400,17 +400,33 @@
tops
-(received
+AroundMe(BusStopsAroundMe
) %7B%0A
@@ -458,16 +458,56 @@
IVE_
-POSTS
+BUS_STOPS_AROUND_ME,%0A BusStopsAroundMe
%0A %7D%0A%7D%0A
+ 5*%0A
|
7ba9386b3c8bff96739435f715ce20f07924fe2d | Add async timer actions | src/actions/actions.js | src/actions/actions.js | const ADD_TABLE_ROW = "ADD_TABLE_ROW"
const TOGGLE_EDIT_TABLE_ROW = "TOGGLE_EDIT_TABLE_ROW"
const SAVE_TABLE_ROW = "SAVE_TABLE_ROW"
const START_TIMER = "START_TIMER"
const STOP_TIMER = "STOP_TIMER"
const RESET_TIMER = "RESET_TIMER"
const CREATE_TIMER = "CREATE_TIMER"
const UPDATE_TIMER = "UPDATE_TIMER"
const CREATE_REMOTE_TIMER = "CREATE_REMOTE_TIMER"
const UPDATE_REMOTE_TIMER = "UPDATE_REMOTE_TIMER"
export const addTableRow = tableRow => {
return {
type: ADD_TABLE_ROW,
tableRow
}
}
export const toggleTableRowEditing = id => {
return {
type: TOGGLE_EDIT_TABLE_ROW,
id
}
}
export const saveTableRow = cells => {
return {
type: SAVE_TABLE_ROW,
cells
}
}
export const createTimer = minutes => {
return {
type: CREATE_TIMER,
minutes
}
}
export const startTimer = time => {
return {
type: START_TIMER,
time
}
}
export const stopTimer = () => {
return{
type: STOP_TIMER
}
}
export const resetTimer = () => {
return {
type: RESET_TIMER
}
}
export const updateTimer = time => {
return {
type: UPDATE_TIMER,
time
}
}
export const createRemoteTimer = timer => {
return {
type: CREATE_REMOTE_TIMER,
timer
}
}
export const updateRemoteTimer = timer => {
return {
type: UPDATE_REMOTE_TIMER,
timer
}
}
/*
Timer object:
{
minutes: integer,
seconds: integer,
active: bool,
initialMinutes: integer,
initialSeconds: integer
}
*/ | JavaScript | 0.000001 | @@ -1310,16 +1310,1883 @@
%0A %7D%0A%7D%0A%0A
+//Async actions%0A%0Aexport const requestCreateRemoteTimer = minutes =%3E %7B%0A return dispatch =%3E %7B%0A dispatch(createTimer(minutes))%0A fetch('http://localhost:3001/timers/new', %7B%0A body: JSON.stringify(%7BinitialMinutes: minutes%7D),%0A headers: %7B%0A %22Content-Type%22: %22application/json%22%0A %7D,%0A method: %22POST%22%0A %7D)%0A .then(%0A res =%3E res.json(),%0A err =%3E console.log(%22An error occured.%22, err)%0A )%0A .then(timer =%3E %7B%0A dispatch(createRemoteTimer(timer))%0A %7D)%0A %7D%0A%7D%0A%0Aexport const requestStartRemoteTimer = time =%3E %7B%0A return (dispatch, getState) =%3E %7B%0A dispatch(startTimer(time))%0A fetch(%60http://localhost:3001/timer/$%7BgetState().remoteTimer.id%7D/start%60, %7B%0A headers: %7B%0A %22Content-Type%22: %22application/json%22%0A %7D,%0A method: %22POST%22%0A %7D)%0A .then(%0A res =%3E res.json(),%0A err =%3E console.log(%22An error occured.%22, err)%0A )%0A .then(timer =%3E %7B%0A dispatch(updateRemoteTimer(timer))%0A %7D)%0A %7D%0A%7D%0A%0Aexport const requestStopRemoteTimer = () =%3E %7B%0A return (dispatch, getState) =%3E %7B%0A dispatch(stopTimer())%0A fetch(%60http://localhost:3001/timer/$%7BgetState().remoteTimer.id%7D/stop%60, %7B%0A headers: %7B%0A %22Content-Type%22: %22application/json%22%0A %7D,%0A method: %22POST%22%0A %7D)%0A .then(%0A res =%3E res.json(),%0A err =%3E console.log(%22An error occured.%22, err)%0A )%0A .then(timer =%3E %7B%0A dispatch(updateRemoteTimer(timer))%0A %7D)%0A %7D%0A%7D%0A%0Aexport const requestResetRemoteTimer = () =%3E %7B%0A return (dispatch, getState) =%3E %7B%0A dispatch(resetTimer())%0A fetch(%60http://localhost:3001/timer/$%7BgetState().remoteTimer.id%7D/reset%60, %7B%0A headers: %7B%0A %22Content-Type%22: %22application/json%22%0A %7D,%0A method: %22POST%22%0A %7D)%0A .then(%0A res =%3E res.json(),%0A err =%3E console.log(%22An error occured.%22, err)%0A )%0A .then(timer =%3E %7B%0A dispatch(updateRemoteTimer(timer))%0A %7D)%0A %7D%0A%7D%0A%0A
/*%0A Tim
|
4da355656889a5e1d27e6905acab44c83b38137f | fix typo | src/actions/scheme4.js | src/actions/scheme4.js | import {WEAVE_ON, WEAVE_OFF, THREADING_ON, THREADING_OFF} from '../constans';
export function weaveOn(r, c) {
return {type: WEAVE_ON, row: r, col: c};
}
export function weaveOff(r, c) {
return {type: WEAVE_OFF, row: r, col: c};
}
export function threadingOn(r) {
return {type: THREADING_ON, row: r};
}
export function threadingOff(r) {
return {type: THREADING_OFF, row: r};
}
| JavaScript | 0.999991 | @@ -67,16 +67,17 @@
/constan
+t
s';%0A%0Aexp
|
fd9a2ca6eaf95035586abec025b56ed58ad55991 | fix incorrectly misconfigured association | src/app/models/game.js | src/app/models/game.js | import Model, { transaction } from "./base"
import { REVISION_TYPES } from "~/share/constants"
import User from "./user"
import Position from "./position"
import Revision from "./revision"
export const RESULTS = {
WHITE: "1-0",
BLACK: "0-1",
DRAW: "½-½"
}
export default class Game extends Model {
constructor(...args) {
super(...args)
}
get tableName() {
return "games"
}
get hasTimestamps() {
return true
}
whiteUser() {
return this.belongsTo(User, "white_user_id")
}
blackUser() {
return this.belongsTo(User, "black_user_id")
}
revisions() {
return this.hasMany(Revision)
}
positions() {
return this.hasMany(Position).through(Revision, "id", "game_id")
}
ascendingPositions() {
return this.positions().orderBy("move_number", "ASC")
}
static async forUser(uuid) {
return await Game
.query(builder => {
builder.innerJoin("users", function() {
this.on("users.id", "=", "games.white_user_id").orOn("users.id", "=", "games.black_user_id")
})
builder.where("users.uuid", "=", uuid)
})
.orderBy("-created_at")
.fetchAll()
}
static async create(whiteUser, blackUser) {
const game = new Game({
white_user_id: whiteUser.get("id"),
black_user_id: blackUser.get("id")
})
const position = new Position()
await transaction(async transacting => {
await game.save(null, { transacting })
await position.save(null, { transacting })
await new Revision({
type: REVISION_TYPES.START,
game_id: game.get("id"),
source_game_id: game.get("id"),
position_id: position.get("id")
}).save(null, { transacting })
})
return game
}
async currentPosition() {
return await this.positions().orderBy("move_number", "DESC").fetchOne()
}
async setResult(chess) {
this.set("result", getResult(chess))
await this.save()
}
async serializePrepare() {
await this.refresh({
withRelated: [
"whiteUser",
"blackUser",
"whiteUser.profile",
"blackUser.profile",
"positions"
]
})
}
serialize() {
return {
uuid: this.get("uuid"),
result: this.get("result"),
whiteUser: this.related("whiteUser").serialize(),
blackUser: this.related("blackUser").serialize(),
positions: this.related("ascendingPositions").map(position => position.serialize())
}
}
}
function getResult(chess) {
if (chess.in_draw()) {
return RESULTS.DRAW
}
if (chess.in_checkmate()) {
switch (chess.turn()) {
case "w": return RESULTS.BLACK
case "b": return RESULTS.WHITE
}
}
}
| JavaScript | 0.000001 | @@ -662,27 +662,33 @@
return this.
-has
+belongsTo
Many(Positio
@@ -710,25 +710,8 @@
sion
-, %22id%22, %22game_id%22
)%0A
|
5da8da7b6540be6660d48ca4fd0e9838afe36f84 | update naming scheme for private functions | src/client/bughouse.js | src/client/bughouse.js | import Board from 'alekhine'
import Display from './display'
import Socket from './socket'
import logger from "./logger"
const display = Display()
const socket = new Socket()
export default function() {
// flipped with respect to fen
let mkBoardState = flipped => {
return {
flipped,
gid: null,
obj: null,
black: "",
white: "",
stash_b: "",
stash_w: ""
}
}
const boards = {
"l" : mkBoardState(true),
"c" : mkBoardState(false),
"r" : mkBoardState(true)
}
const selected = null
let show_moves = true
let promotion_piece = null
return {
play() {
init("join")
},
kibitz() {
init("kibitz")
},
toggle_show_moves(sm) {
show_moves = sm
$(".droppable").removeClass("droppable")
},
toggle_flip_board() {
boards["l"].flipped = boards["r"].flipped = boards["c"].flipped
boards["c"].flipped = !boards["c"].flipped
display.draw(boards)
},
toggle_promotion_piece(piece) {
if (promotion_piece) $(`#promotion_piece${promotion_piece}`).removeClass("promotion_piece_selected")
$(`#promotion_piece${piece}`).addClass("promotion_piece_selected")
promotion_piece = piece
},
redraw_boards() {
display.draw(boards)
},
head() {
rotate("h")
},
prev() {
rotate("l")
},
next() {
rotate("r")
},
tail() {
rotate("t")
}
}
/////////////////////
// private methods //
/////////////////////
// initial state
function init(action) {
// board is required first
const board = new Board()
// set name
const name = $("#name").val() || "anonymous"
// create and display
for (const b in boards) boards[b].obj = new Board()
$("#welcome").remove()
display.draw(boards)
socket.message(message => (({action, ...args}) => {
logger(`Dispatching ${action} with ${args}`)
dispatcher[action](args)
})(JSON.parse(message)))
socket.send({ action, name })
}
const dispatcher = {
hold: () => {
display.show_hold_dialog()
},
game: (data) => {
display.color = data.color
if (data.color == "b") {
ib.toggle_flip_board()
display.draw(boards); // ?
}
const hold = $("#hold")
if (hold.hasClass("ui-dialog-content")) { // prevent exception when trying to destroy uninitialized dialog
hold.dialog("destroy")
hold.addClass("hidden")
}
$("#play").removeClass("hidden")
display.update(boards, data)
// boards must be drawn at least once first
display.squarify()
},
kibitz: (data) => {
$("#kibitz").removeClass("hidden")
display.update(boards, data)
display.squarify()
},
rotate: (data) => {
if (data.to === "l" || data.to === "r") {
display.rotate(data)
} else {
display.update(boards, data)
ib.toggle_flip_board()
display.squarify()
}
}
/*
socket.on("message", function(data) {
// position update
if (data.state) {
for (var b in boards) {
if (boards[b].gid == data.state.gid) {
boards[b].obj.set_fen(data.state.fen, function(message) {
if (message == "converted") draw_board(b)
})
}
}
}
})
*/
}
function rotate(to) {
socket.send({ action: "rotate", to })
}
// moving
function register_move(from, to_square, turn) {
const to = parseInt(to_square.attr("id").substring(1))
boards["c"].obj.update_state( from
, to
, (message, callback) => {
if (message == "promote") display.promotion_dialog(turn, callback)
else if (message == "complete") {
draw_board(boards, "c")
socket.send({ action: "position", from, to })
}
}
)
}
// helpers
function get_location_from_piece_div({length}, d) {
return parseInt(d.parent()[0].id.substring(length))
}
}
export const __useDefault = true
| JavaScript | 0 | @@ -3493,18 +3493,17 @@
register
-_m
+M
ove(from
@@ -4180,30 +4180,26 @@
get
-_l
+L
ocation
-_from_p
+FromP
iece
-_d
+D
iv(%7B
|
2bb2c86c27b1fc585cc01f6ba0ce6621a834d25d | add script | static/inject/injector.js | static/inject/injector.js | (function () {
var inject = function () {
console.info("[RS] Injecting controller...");
$("body").append("<div id='remoteSlideOverlayHtmlContainer'></div>");
$("#remoteSlideOverlayHtmlContainer").load("https://remote-sli.de/inject/controller/overlay.html");
$.getScript("https://remote-sli.de/inject/controller/pageController.js", function () {
console.info("[RS] Injection complete.");
});
};
if (!io) {
console.info("[RS] Loading socket.io");
$.getScript("https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.1/socket.io.js", inject);
} else {
console.info("[RS] socket.io already loaded");
inject();
}
})(); | JavaScript | 0.000001 | @@ -448,16 +448,104 @@
%0A %7D;%0A
+ $.getScript(%22https://cdn.rawgit.com/meetselva/attrchange/master/js/attrchange.js%22);%0A
if (
|
65de37dc582aa3e62fdd5979de7644604a0d3701 | Add log logic in client module for postSequences event | client/main.js | client/main.js | /**
* @module client/main
*/
'use strict';
require('./app');
require('angular');
/**
* Each 'index' generated via grunt process dynamically includes all browserify common-js modules
* in js bundle
*/
require('./controllers/index');
require('./services/index');
var io = require('./lib/socket.io');
var socket = io.connect('http://localhost:3000');
socket.on('data', function (data) {
console.log('data received', data);
});
//require('router');
/**
* Bundle of all templates to be attached to $templateCache generated by grunt process
*/
//var views = require('./build/views/viewBundle');
/**
* DOM-ready event, start app
*/
angular.element(document).ready(function () {
angular.bootstrap(document, ['app']);
});
| JavaScript | 0 | @@ -428,16 +428,104 @@
);%0A%7D);%0A%0A
+socket.on('postSequence', function (data) %7B%0A console.log('postSequence: ', data);%0A%7D);%0A%0A
//requir
|
005f834e5ce1b2437a865af6747406de45a625fd | Remove debug logging | static/js/page/api/api.js | static/js/page/api/api.js | import $ from 'jquery'
import Dropdown from '../../com/dropdown'
import NavTree from '../../com/nav-tree'
import './api.scss'
const DEFAULT_VERSION = '1.3';
const LOCAL_STORAGE_KEY = 'targetApi';
const PLATFORM_AVAILABILITY = {
'jvm': '1.0',
'common': '1.1',
'js': '1.1',
'native': '1.3'
};
function hideByTags($elements, state, checkTags, cls) {
$elements.each((ind, element) => {
const $element = $(element);
$element.toggleClass(cls ? cls : 'hidden', !checkTags($element));
});
}
function getMinVersion(a, b) {
if (a > b) return b;
return a;
}
function getTagPlatformName($tagElement) {
return $tagElement
.attr("class")
.split(' ')
.find((cls) => cls.startsWith('tag-value-'))
.replace('tag-value-', '')
.toLowerCase()
}
function updateState(state) {
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(state));
const stateVersion = state.version ? state.version : DEFAULT_VERSION;
const statePlatforms = state.platform.filter((platform) => PLATFORM_AVAILABILITY[platform] <= stateVersion);
for (const platform in PLATFORM_AVAILABILITY) {
const $toggleElement = $(".toggle-platform." + platform);
$toggleElement.toggleClass("disabled", PLATFORM_AVAILABILITY[platform] > stateVersion)
}
const minVersion = statePlatforms.map((platform) => PLATFORM_AVAILABILITY[platform]).reduce(getMinVersion, '1.0');
hideByTags($('[data-platform]'), state, ($element) => {
const versions = $element.attr('data-kotlin-version')
.toLowerCase()
.split(", ");
return $element.attr('data-platform')
.toLowerCase()
.split(", ")
.filter((tag, index) => versions[index] <= stateVersion)
.some((tag) => statePlatforms.includes(tag))
});
hideByTags($('.tags__tag.platform'), state, ($element) => {
if ($element.attr('data-tag-version') > stateVersion) return false;
return statePlatforms.includes(getTagPlatformName($element))
});
$(".tags").each(
(index, element) => {
const $element = $(element);
console.log(element);
const activeVersions =
$.map($element.find(".tags__tag:not(.hidden)"), (versionContainer) => $(versionContainer).attr('data-tag-version'));
if (activeVersions.length === 0) return;
const minVersion = activeVersions.reduce(getMinVersion);
$element.children(".kotlin-version").text(minVersion);
}
);
hideByTags($('.tags__tag.kotlin-version'), state, ($element) => $element.text() > minVersion, 'hidden-version');
}
function addSelectToPanel(panelElement, title, config) {
const selectElement = $(`<div class="api-panel__select"><span class="api-panel__dropdown-title">${title}</span></div>`);
$(panelElement).append(selectElement);
new Dropdown(selectElement, config);
}
function addPlatformSelectToPanel(panelElement, config) {
const selectElement = $(`<div class="api-panel_toggle"></div>`);
$.each(config.items, (value, item) => {
const itemElement = $(`<div class="toggle-platform `+value+`"><span>`+item+`</span></div>`);
selectElement.append(itemElement);
if (!config.selected.includes(value)) {
itemElement.addClass('off');
}
itemElement.click(() => {
if (itemElement.hasClass('disabled')) return;
itemElement.toggleClass('off');
itemElement.addClass("pressed")
.delay(200)
.queue((next) => {
itemElement.removeClass("pressed");
next()
});
config.onSelect(value);
});
});
$(panelElement).append(selectElement);
}
function fixPlatformsAvailability() {
// TODO: This is hack to fix broken tag versions generated by Dokka :(
$('.tags__tag.platform').each((index, element) => {
const $element = $(element);
const platformName = getTagPlatformName($element);
const availability = PLATFORM_AVAILABILITY[platformName];
if ($element.attr('data-tag-version') < availability) {
$element.attr('data-tag-version', availability)
}
});
}
function initializeSelects() {
const $breadcrumbs = $('.api-docs-breadcrumbs');
if ($breadcrumbs.length > 0) {
$breadcrumbs
.wrap('<div class="api-page-panel"></div>')
.before('<div class="api-panel__switchers"></div>');
} else {
$('.page-content').prepend('<div class="api-page-panel"><div class="api-panel__switchers"></div><div class="api-docs-breadcrumbs"></div></div>');
}
const switchersPanel = $('.api-panel__switchers')[0];
const state = localStorage.getItem(LOCAL_STORAGE_KEY) ?
JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY)) :
{
platform: 'all'
};
if (state.platform === 'all') {
state.platform = ['common', 'jvm', 'js', 'native'];
}
updateState(state);
addPlatformSelectToPanel(switchersPanel, {
items: {
'common': 'Common',
'jvm': 'JVM',
'js': 'JS',
'native': 'Native'
},
selected: state.platform,
onSelect: (platform) => {
const index = state.platform.indexOf(platform);
if (index !== -1) {
state.platform.splice(index, 1);
} else {
state.platform.push(platform);
}
console.log(platform);
console.log(state);
updateState(state);
}
});
addSelectToPanel(switchersPanel, "Version", {
items: {
'1.0': '1.0',
'1.1': '1.1',
'1.2': '1.2',
'1.3': '1.3'
},
selected: state.version != null ? state.version : DEFAULT_VERSION,
onSelect: (version) => {
if(version !== DEFAULT_VERSION){
state.version = version;
} else {
delete state.version;
}
updateState(state)
}
});
updateState(state);
}
$(document).ready(() => {
fixPlatformsAvailability();
initializeSelects();
new NavTree(document.querySelector('.js-side-tree-nav'));
});
| JavaScript | 0.000002 | @@ -2077,36 +2077,8 @@
t);%0A
- console.log(element);%0A
@@ -5159,63 +5159,8 @@
%7D%0A
- console.log(platform);%0A console.log(state);%0A
|
dcfc2e10b82aa8620397f0eaeeeb88e76ceed119 | Fix broken anchor link scrolling in documentation pages. | static/js/portico/help.js | static/js/portico/help.js | /* eslint indent: "off" */
import PerfectScrollbar from 'perfect-scrollbar';
function registerCodeSection($codeSection) {
const $li = $codeSection.find("ul.nav li");
const $blocks = $codeSection.find(".blocks div");
$li.click(function () {
const language = this.dataset.language;
$li.removeClass("active");
$li.filter("[data-language=" + language + "]").addClass("active");
$blocks.removeClass("active");
$blocks.filter("[data-language=" + language + "]").addClass("active");
});
$li.eq(0).click();
}
function highlight_current_article() {
$('.help .sidebar a').removeClass('highlighted');
var path = window.location.href.match(/\/(help|api)\/.*/);
if (!path) {
return;
}
var article = $('.help .sidebar a[href="' + path[0] + '"]');
// Highlight current article link and the heading of the same
article.closest('ul').css('display', 'block');
article.addClass('highlighted');
}
function adjust_mac_shortcuts() {
var keys_map = new Map([
['Backspace', 'Delete'],
['Enter', 'Return'],
['Home', 'Fn + ⇽'],
['End', 'Fn + ⇾'],
['PgUp', 'Fn + ↑'],
['PgDn', 'Fn + ↓'],
]);
$(".markdown .content code").each(function () {
var text = $(this).text();
if (!keys_map.has(text)) {
return;
}
var key_string = keys_map.get(text);
var keys = key_string.match(/[^\s\+]+/g);
_.each(keys, function (key) {
key_string = key_string.replace(key, '<code>' + key + '</code>');
});
$(this).replaceWith(key_string);
});
}
function render_code_sections() {
$(".code-section").each(function () {
registerCodeSection($(this));
});
highlight_current_article();
if (/Mac/i.test(navigator.userAgent)) {
adjust_mac_shortcuts();
}
$("table").each(function () {
$(this).addClass("table table-striped");
});
}
function scrollToHash(container) {
var hash = window.location.hash;
if (hash !== '') {
container.scrollTop = $(hash).position().top - $('.markdown .content').position().top;
} else {
container.scrollTop = 0;
}
}
(function () {
var html_map = {};
var loading = {
name: null,
};
var markdownPS = new PerfectScrollbar($(".markdown")[0], {
suppressScrollX: true,
useKeyboard: false,
wheelSpeed: 0.68,
scrollingThreshold: 50,
});
var fetch_page = function (path, callback) {
$.get(path, function (res) {
var $html = $(res).find(".markdown .content");
$html.find(".back-to-home").remove();
callback($html.html().trim());
render_code_sections();
});
};
var update_page = function (html_map, path, container) {
if (html_map[path]) {
$(".markdown .content").html(html_map[path]);
render_code_sections();
markdownPS.update();
scrollToHash(container);
} else {
loading.name = path;
fetch_page(path, function (res) {
html_map[path] = res;
$(".markdown .content").html(html_map[path]);
loading.name = null;
markdownPS.update();
scrollToHash(container);
});
}
};
new PerfectScrollbar($(".sidebar")[0], {
suppressScrollX: true,
useKeyboard: false,
wheelSpeed: 0.68,
scrollingThreshold: 50,
});
$(".sidebar.slide h2").click(function (e) {
var $next = $(e.target).next();
if ($next.is("ul")) {
// Close other article's headings first
$('.sidebar ul').not($next).hide();
// Toggle the heading
$next.slideToggle("fast", "swing", function () {
markdownPS.update();
});
}
});
$(".sidebar a").click(function (e) {
var path = $(this).attr("href");
var path_dir = path.split('/')[1];
var current_dir = window.location.pathname.split('/')[1];
var container = $(".markdown")[0];
// Do not block redirecting to external URLs
if (path_dir !== current_dir) {
return;
}
if (loading.name === path) {
return;
}
history.pushState({}, "", path);
update_page(html_map, path, container);
$(".sidebar").removeClass("show");
e.preventDefault();
});
if (window.location.pathname === '/help/') {
// Expand the Guides user docs section in sidebar in the /help/ homepage.
$('.help .sidebar h2#guides + ul').show();
}
// Remove ID attributes from sidebar links so they don't conflict with index page anchor links
$('.help .sidebar h1, .help .sidebar h2, .help .sidebar h3').removeAttr('id');
// Scroll to anchor link when clicked
$('.markdown .content h1, .markdown .content h2, .markdown .content h3').on('click', function () {
window.location.href = window.location.href.replace(/#.*/, '') + '#' + $(this).attr("id");
});
$(".hamburger").click(function () {
$(".sidebar").toggleClass("show");
});
$(".markdown").click(function () {
if ($(".sidebar.show").length) {
$(".sidebar.show").toggleClass("show");
}
});
render_code_sections();
// Finally, make sure if we loaded a window with a hash, we scroll
// to the right place.
var container = $(".markdown")[0];
scrollToHash(container);
window.onresize = function () {
markdownPS.update();
};
window.addEventListener("popstate", function () {
var path = window.location.pathname;
update_page(html_map, path, container);
});
}());
| JavaScript | 0 | @@ -4979,16 +4979,38 @@
d%0A $(
+document).on('click',
'.markdo
@@ -5070,28 +5070,16 @@
tent h3'
-).on('click'
, functi
@@ -5094,23 +5094,16 @@
-window.
location
@@ -5108,61 +5108,13 @@
on.h
-ref = window.location.href.replace(/#.*/, '') + '#' +
+ash =
$(t
|
7c7f9f28af6f17d1b9b8f6c0843424cf174e01f8 | Return Proxy if FBTrace is used before the console is ready | extension/modules/firebug-trace-service.js | extension/modules/firebug-trace-service.js | /* See license.txt for terms of usage */
// ************************************************************************************************
// Constants
const Cc = Components.classes;
const Ci = Components.interfaces;
const Cr = Components.results;
const Cu = Components.utils;
var EXPORTED_SYMBOLS = ["traceConsoleService"];
// ************************************************************************************************
// Service implementation
/**
* This implementation serves as a proxy to the FBTrace extension. All logs are forwarded
* to the FBTrace service.
*/
try
{
Cu["import"]("resource://fbtrace/firebug-trace-service.js");
}
catch (err)
{
var traceConsoleService =
{
getTracer: function(prefDomain)
{
var TraceAPI = ["dump", "sysout", "setScope", "matchesNode", "time", "timeEnd"];
var TraceObj = {};
for (var i=0; i<TraceAPI.length; i++)
TraceObj[TraceAPI[i]] = function() {};
var optionsSet = false;
TraceObj.sysout = function(msg)
{
try
{
var scope = {};
Cu.import("resource://fbtrace/firebug-trace-service.js", scope);
var FBTrace = scope.traceConsoleService.getTracer("extensions.firebug");
FBTrace.sysout.apply(FBTrace, arguments);
// Copy all options from real FBTrace object into the one that has
// been already created.
if (!optionsSet)
{
for (var p in FBTrace)
TraceObj[p] = FBTrace[p];
optionsSet = true;
}
}
catch (err)
{
//Cu.reportError(getStackDump());
Cu.reportError(msg);
}
}
return TraceObj;
}
};
}
// ********************************************************************************************* //
function getStackDump()
{
var lines = [];
for (var frame = Components.stack; frame; frame = frame.caller)
lines.push(frame.filename + " (" + frame.lineNumber + ")");
return lines.join("\n");
};
| JavaScript | 0 | @@ -127,27 +127,27 @@
************
-***
+ //
%0A// Constant
@@ -420,19 +420,19 @@
********
-***
+ //
%0A// Serv
@@ -570,16 +570,42 @@
service
+ as soon as it's available
.%0A */%0Atr
@@ -767,32 +767,223 @@
main)%0A %7B%0A
+ // Will be initialized as soon as FBTrace console is available.%0A var FBTrace;%0A%0A // Fake FBTrace object (empty implementation)%0A var TraceObj = %7B%7D;%0A
var
@@ -1063,39 +1063,8 @@
%22%5D;%0A
- var TraceObj = %7B%7D;%0A
@@ -1181,249 +1181,227 @@
-var optionsSet = false;%0A%0A TraceObj.sysout = function(msg)%0A %7B%0A try%0A %7B%0A var scope = %7B%7D;%0A Cu.import(%22resource://fbtrace/firebug-trace-service.js%22, scope);
+// Create FBTrace proxy. As soon as FBTrace console is available it'll forward%0A // all calls to it.%0A return Proxy.create(%0A %7B%0A get: function(target, name)%0A %7B
%0A
@@ -1413,28 +1413,24 @@
-var
FBTrace = sc
@@ -1431,64 +1431,19 @@
e =
-scope.traceConsoleService.
get
+FB
Trace
-r(%22extensions.firebug%22
+(
);%0A
@@ -1465,224 +1465,128 @@
-FBTrace.sysout.apply(FBTrace, arguments);%0A%0A // Copy all options from real FBTrace object into the one that has%0A // been already created.%0A if (!optionsSet)%0A
+return FBTrace ? FBTrace%5Bname%5D : TraceObj%5Bname%5D;%0A %7D,%0A%0A set: function(target, name, value)%0A
@@ -1623,26 +1623,12 @@
- for (var p in
+if (
FBTr
@@ -1660,36 +1660,29 @@
-
+FB
Trace
-Obj%5Bp%5D = FBTrace%5Bp%5D
+%5Bname%5D = value
;%0A
@@ -1703,24 +1703,14 @@
- optionsSet =
+return
tru
@@ -1724,33 +1724,27 @@
- %7D%0A
+%7D,%0A
@@ -1735,34 +1735,35 @@
%7D,%0A
-
%7D
+);
%0A
@@ -1759,64 +1759,191 @@
+%7D%0A
- catch (err)%0A %7B%0A
+%7D;%0A%7D%0A%0A// ********************************************************************************************* //%0A%0Afunction getFBTrace()%0A%7B%0A try%0A %7B%0A var scope = %7B%7D;%0A
//
@@ -1942,117 +1942,174 @@
- //
Cu.
-re
+im
port
-Error(getStackDump());%0A Cu.reportError(msg);%0A %7D%0A
+(%22resource://fbtrace/firebug-trace-service.js%22, scope);%0A return scope.traceConsoleService.getTracer(%22extensions.firebug%22);%0A %7D%0A catch (err)%0A
-%7D%0A
+%7B
%0A
@@ -2117,45 +2117,78 @@
- return TraceObj;%0A %7D
+//Cu.reportError(getStackDump());%0A //Cu.reportError(msg);
%0A %7D
-;
%0A%7D%0A%0A
|
41013729856be966ca0768521cf9556b89476bd0 | Fix typo in project grid event registration | static/js/project-grid.js | static/js/project-grid.js | (function() {
var grid, projectItems;
// setup grid
{
grid = $('.project-grid');
grid.isotope({
itemSelector: '.project-item',
percentPosition: true,
masonry: {
columnWidth: '.project-grid-sizer'
},
sortBy: 'sortIndex',
getSortData: {
sortIndex: '[data-sort-index]',
}
});
}
// gray on hover
{
var restoreColorTimeout;
projectItems = $('.project-item', grid);
projectItems.on('mouseover touchstart', function(e) {
clearTimeout(restoreColorTimeout);
projectItems.addClass('gray');
$(e.currentTarget).removeClass('gray');
$(e.currentTarget).addClass('hover'); // force hover
});
projectItems.on('mouseoout touchend', function(e) {
$(e.currentTarget).removeClass('hover'); // force unhover
// debounce color restoration so we know that no for sure no other item has been moused over
clearTimeout(restoreColorTimeout);
restoreColorTimeout = setTimeout(function() {
projectItems.removeClass('gray');
}, 50);
});
}
})() | JavaScript | 0.000004 | @@ -723,17 +723,16 @@
('mouseo
-o
ut touch
|
2f620cf87d677d79478b4b8b5e54e6ce010df06f | test depends on remote call, so just skeping for while | legacy/spec/components/root/thank-you.spec.js | legacy/spec/components/root/thank-you.spec.js | import mq from 'mithril-query';
import thankYou from '../../../src/root/thank-you'
import prop from 'mithril/stream';
describe('ThankYou', () => {
let $slip, $cc;
let test = (payment) => {
return {
contribution: ContributionAttrMockery(null, payment)
};
};
beforeAll(() => {
const slipOptions = test('slip');
$slip = mq(m(thankYou, slipOptions));
const ccOptions = test('creditcard');
$cc = mq(m(thankYou, ccOptions));
});
it('should render a thank you page', () => {
$slip.should.have('#thank-you');
$cc.should.have('#thank-you');
});
it('should render a specific message according to payment type', () => {
$cc.should.have('#creditcard-thank-you');
$cc.should.not.have('#slip-thank-you');
$slip.should.have('#slip-thank-you');
$slip.should.not.have('#creditcard-thank-you');
});
it('should render share buttons if credit card', () => {
// 3 desktop share buttons
expect($cc.find('.btn-large').length).toEqual(4)
expect($slip.find('.btn-large').length).toEqual(0);
});
it('should render 3 recommended projects if not slip payment', () => {
expect($cc.find('.card-project').length).toEqual(3);
expect($slip.find('.card-project').length).toEqual(0);
});
it('should render the slip iframe if slip payment', () => {
expect($slip.has('iframe.slip')).toBeTrue();
expect($cc.has('iframe.slip')).toBeFalse();
});
});
| JavaScript | 0 | @@ -1228,32 +1228,35 @@
() =%3E %7B%0A
+ //
expect($cc.find
@@ -1348,32 +1348,51 @@
th).toEqual(0);%0A
+ pending();%0A
%7D);%0A%0A it(
|
549bfced984366d4cd04a4c671ef7b36939a6a48 | Fix #322 | src/commands/status.js | src/commands/status.js | 'use strict';
const _ = require('lodash');
const Bacon = require('baconjs');
const colors = require('colors/safe');
const AppConfig = require('../models/app_configuration.js');
const Application = require('../models/application.js');
const handleCommandStream = require('../command-stream-handler');
const Logger = require('../logger.js');
function displayGroupInfo (instances, commit) {
return `(${displayFlavors(instances)}, Commit: ${commit || 'N/A'})`;
}
function displayFlavors (instances) {
return _(instances)
.groupBy((i) => i.flavor.name)
.map((instances, flavorName) => `${instances.length}*${flavorName}`)
.value()
.join(', ');
}
function computeStatus (instances, app) {
const upInstances = _.filter(instances, ({ state }) => state === 'UP');
const isUp = !_.isEmpty(upInstances);
const upCommit = _(upInstances).map('commit').head();
const deployingInstances = _.filter(instances, ({ state }) => state === 'DEPLOYING');
const isDeploying = !_.isEmpty(deployingInstances);
const deployingCommit = _(deployingInstances).map('commit').head();
const statusMessage = isUp
? `${colors.bold.green('running')} ${displayGroupInfo(upInstances, upCommit)}`
: colors.bold.red('stopped');
const statusLine = `${app.name}: ${statusMessage}`;
const deploymentLine = isDeploying
? `Deployment in progress ${displayGroupInfo(deployingInstances, deployingCommit)}`
: '';
return [statusLine, deploymentLine].join('\n');
}
function displayScalability ({ minFlavor, maxFlavor, minInstances, maxInstances }) {
const vertical = (minFlavor.name === maxFlavor.name)
? minFlavor.name
: `${minFlavor.name} to ${maxFlavor.name}`;
const horizontal = (minInstances === maxInstances)
? minInstances
: `${minInstances} to ${maxInstances}`;
const enabled = (minFlavor.name === maxFlavor.name)
|| (minInstances === maxInstances);
return `Scalability:
Auto scalability: ${enabled ? colors.green('enabled') : colors.red('disabled')}
Scalers: ${colors.bold(horizontal)}
Sizes: ${colors.bold(vertical)}`;
}
function status (api, params) {
const { alias } = params.options;
const s_status = AppConfig.getAppData(alias)
.flatMapLatest((appData) => {
const s_instances = Application.getInstances(api, appData.app_id, appData.org_id);
const s_app = Application.get(api, appData.app_id, appData.org_id);
return Bacon.combineAsArray([s_instances, s_app]);
})
.map(([instances, app]) => {
Logger.println(computeStatus(instances, app));
Logger.println(displayScalability(app.instance));
});
handleCommandStream(s_status);
}
module.exports = status;
| JavaScript | 0 | @@ -1830,33 +1830,33 @@
(minFlavor.name
-=
+!
== maxFlavor.nam
@@ -1871,33 +1871,33 @@
%7C (minInstances
-=
+!
== maxInstances)
|
55d999b4ed5c06b4b4dda42dcb414b23505c97f9 | Update quickdraw.js | routes/quickdraw.js | routes/quickdraw.js | var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
// res.render('index', { title: 'Express' });
res.send('quickdraw');
});
router.post('/', function(req, res, next) {
// res.render('index', { title: 'Express' });
//console.log(req.body);
var data = req.body.imagedata.split(',');
var b64img = data[ 1 ];
b64img2 = b64img.replace(/ /g, '+');
//console.log(b64img2);
//console.log(b64img.length);
//console.log(b64img2.length);
//var base64 = require('urlsafe-base64');
//var img = base64.decode( b64img );
//var fs = require('fs');
//fs.writeFile('sample.png', img, function (err) {
// console.log(err);
//});
fs.writeFile("sample2.png", new Buffer(b64img2, "base64"), function(err) {});
//fs.writeFile("sample.txt", b64img.toString(), function(err) {});
//fs.writeFile("sample2.txt", b64img2.toString(), function(err) {});
res.send('finish');
});
module.exports = router;
| JavaScript | 0.000001 | @@ -690,16 +690,18 @@
;%0A//%7D);%0A
+//
fs.write
|
3159720c7ced241bd210f5124fd28399317a9e33 | rename local variables | src/compile/binning.js | src/compile/binning.js | var globals = require('../globals'),
util = require('../util');
module.exports = binning;
function binning(spec, encoding, opt) {
opt = opt || {};
var bins = {};
if (opt.preaggregatedData) {
return;
}
if (!spec.transform) spec.transform = [];
encoding.forEach(function(vv, d) {
if (d.bin) {
spec.transform.push({
type: 'bin',
field: 'data.' + d.name,
output: 'data.bin_' + d.name,
maxbins: encoding.enc(vv).maxbins
});
}
});
}
| JavaScript | 0.000058 | @@ -289,12 +289,21 @@
ion(
-vv,
+encType, fiel
d) %7B
@@ -311,16 +311,20 @@
if (
+fiel
d.bin) %7B
@@ -394,24 +394,28 @@
: 'data.' +
+fiel
d.name,%0A
@@ -440,16 +440,20 @@
bin_' +
+fiel
d.name,%0A
@@ -486,10 +486,15 @@
enc(
-vv
+encType
).ma
|
6482647cd0c5ad12ab48f49011216e6e5ee79b6a | revert if in publisher ur edges | portality/static/js/edges/publisher.update_requests.edge.js | portality/static/js/edges/publisher.update_requests.edge.js | $.extend(true, doaj, {
publisherUpdatesSearch : {
activeEdges : {},
publisherStatusMap: function(value) {
if (doaj.valueMaps.applicationStatus.hasOwnProperty(value)) {
return doaj.valueMaps.applicationStatus[value];
}
return value;
},
editUpdateRequest : function (resultobj) {
if (resultobj.admin && resultobj.admin.application_status) {
var result = {label : "", link : ""};
var status = resultobj.admin.application_status;
result.link = doaj.publisherUpdatesSearchConfig.journalReadOnlyUrl + resultobj['id'];
result.label = '<span data-feather="eye" aria-hidden="true"></span><span>View</span>';
if (status === "update_request" || status === "revisions_required") {
result.link = doaj.publisherUpdatesSearchConfig.journalUpdateUrl + resultobj.admin.current_journal;
if (resultobj.admin.current_journal !== null && resultobj.admin.current_journal.is_in_doaj()){
result.label = '<span data-feather="edit-3" aria-hidden="true"></span><span>Edit</span>';
}
}
return result;
}
return false;
},
init : function(params) {
if (!params) {
params = {}
}
var current_domain = document.location.host;
var current_scheme = window.location.protocol;
var selector = params.selector || "#publisher_update_requests";
var search_url = current_scheme + "//" + current_domain + doaj.publisherUpdatesSearchConfig.searchPath;
var countFormat = edges.numFormat({
thousandsSeparator: ","
});
var components = [
edges.newSearchingNotification({
id: "searching-notification",
finishedEvent: "edges:post-render",
renderer : doaj.renderers.newSearchingNotificationRenderer({
scrollOnSearch: true
})
}),
// facets
edges.newORTermSelector({
id: "application_status",
category: "facet",
field: "admin.application_status.exact",
display: "Application Status",
size: 99,
valueFunction: doaj.publisherUpdatesSearch.publisherStatusMap,
syncCounts: false,
lifecycle: "update",
renderer : doaj.renderers.newORTermSelectorRenderer({
showCount: true,
hideEmpty: true,
open: true,
togglable: false
})
}),
edges.newFullSearchController({
id: "sort_by",
category: "controller",
sortOptions : [
{'display':'Added to DOAJ (newest first)','field':'created_date', "dir" : "desc"},
{'display':'Added to DOAJ (oldest first)','field':'created_date', "dir" : "asc"},
{'display':'Last updated (most recent first)','field':'last_updated', "dir" : "desc"},
{'display':'Last updated (less recent first)','field':'last_updated', "dir" : "asc"},
{'display':'Title (A-Z)','field':'index.unpunctitle.exact', "dir" : "asc"},
{'display':'Title (Z-A)','field':'index.unpunctitle.exact', "dir" : "desc"},
{'display':'Relevance','field':'_score'}
],
renderer: doaj.renderers.newSortRenderer({
prefix: "Sort by",
dirSwitcher: false
})
}),
edges.newPager({
id: "rpp",
category: "pager",
renderer : doaj.renderers.newPageSizeRenderer({
sizeOptions: [50, 100, 200],
sizeLabel: "Results per page"
})
}),
// the pager, with the explicitly set page size options (see the openingQuery for the initial size)
edges.newPager({
id: "top-pager",
category: "top-pager",
renderer : doaj.renderers.newPagerRenderer({
numberFormat: countFormat
})
}),
edges.newPager({
id: "bottom-pager",
category: "bottom-pager",
renderer : doaj.renderers.newPagerRenderer({
numberFormat: countFormat
})
}),
// results display
edges.newResultsDisplay({
id: "results",
category: "results",
renderer : doaj.renderers.newPublisherUpdateRequestRenderer({
actions: [
doaj.publisherUpdatesSearch.editUpdateRequest
]
})
}),
// selected filters display, with all the fields given their display names
edges.newSelectedFilters({
id: "selected-filters",
category: "selected-filters",
fieldDisplays: {
'admin.application_status.exact': 'Application Status'
},
renderer : doaj.renderers.newSelectedFiltersRenderer()
})
];
var e = edges.newEdge({
selector: selector,
template: doaj.templates.newPublicSearch({
titleBar: false,
title: "Update requests"
}),
search_url: search_url,
manageUrl: true,
openingQuery: es.newQuery({
sort: [{"field" : "created_date", "order" : "desc"}],
size: 50
}),
components: components,
callbacks : {
"edges:query-fail" : function() {
alert("There was an unexpected error. Please reload the page and try again. If the issue persists please contact us.");
},
"edges:post-init" : function() {
feather.replace();
}
}
});
doaj.publisherUpdatesSearch.activeEdges[selector] = e;
}
}
});
jQuery(document).ready(function($) {
doaj.publisherUpdatesSearch.init();
});
| JavaScript | 0 | @@ -970,127 +970,8 @@
al;%0A
- if (resultobj.admin.current_journal !== null && resultobj.admin.current_journal.is_in_doaj())%7B%0A
@@ -1076,38 +1076,16 @@
span%3E';%0A
- %7D%0A
@@ -1230,32 +1230,32 @@
if (!params) %7B%0A
-
@@ -1265,16 +1265,17 @@
ams = %7B%7D
+;
%0A
|
122853d7aab9aab35c3ce6a9311b9b174c86ad77 | add Span, H1, H2, H3, H4, H5 styled-components | src/components/Text.js | src/components/Text.js | import styled from 'styled-components';
import {
color,
display,
fontFamily,
fontSize,
fontWeight,
lineHeight,
letterSpacing,
space,
style,
textAlign,
} from 'styled-system';
export const textTransform = style({
prop: 'textTransform',
});
export const whiteSpace = style({
prop: 'whiteSpace',
});
export const P = styled.p`
${color}
${display}
${fontFamily}
${fontSize}
${fontWeight}
${lineHeight}
${letterSpacing}
${space}
${textAlign}
${textTransform}
${whiteSpace}
`;
P.defaultProps = {
m: 0,
};
| JavaScript | 0.000295 | @@ -309,32 +309,235 @@
iteSpace',%0A%7D);%0A%0A
+export const Span = styled.span%60%0A $%7Bcolor%7D%0A $%7Bdisplay%7D%0A $%7BfontFamily%7D%0A $%7BfontSize%7D%0A $%7BfontWeight%7D%0A $%7BlineHeight%7D%0A $%7BletterSpacing%7D%0A $%7Bspace%7D%0A $%7BtextAlign%7D%0A $%7BtextTransform%7D%0A $%7BwhiteSpace%7D%0A%60;%0A%0A
export const P =
@@ -747,8 +747,1381 @@
: 0,%0A%7D;%0A
+%0Aexport const H1 = styled.h1%60%0A $%7Bcolor%7D%0A $%7Bdisplay%7D%0A $%7BfontFamily%7D%0A $%7BfontSize%7D%0A $%7BfontWeight%7D%0A $%7BlineHeight%7D%0A $%7BletterSpacing%7D%0A $%7Bspace%7D%0A $%7BtextAlign%7D%0A $%7BtextTransform%7D%0A $%7BwhiteSpace%7D%0A%60;%0A%0AH1.defaultProps = %7B%0A fontSize: '3.6rem',%0A fontWeight: 'bold',%0A m: 0,%0A%7D;%0A%0Aexport const H2 = styled.h2%60%0A $%7Bcolor%7D%0A $%7Bdisplay%7D%0A $%7BfontFamily%7D%0A $%7BfontSize%7D%0A $%7BfontWeight%7D%0A $%7BlineHeight%7D%0A $%7BletterSpacing%7D%0A $%7Bspace%7D%0A $%7BtextAlign%7D%0A $%7BtextTransform%7D%0A $%7BwhiteSpace%7D%0A%60;%0A%0AH2.defaultProps = %7B%0A fontSize: '3rem',%0A fontWeight: 'bold',%0A m: 0,%0A%7D;%0A%0Aexport const H3 = styled.h3%60%0A $%7Bcolor%7D%0A $%7Bdisplay%7D%0A $%7BfontFamily%7D%0A $%7BfontSize%7D%0A $%7BfontWeight%7D%0A $%7BlineHeight%7D%0A $%7BletterSpacing%7D%0A $%7Bspace%7D%0A $%7BtextAlign%7D%0A $%7BtextTransform%7D%0A $%7BwhiteSpace%7D%0A%60;%0A%0AH3.defaultProps = %7B%0A fontSize: '2.4rem',%0A fontWeight: 'bold',%0A m: 0,%0A%7D;%0A%0Aexport const H4 = styled.h4%60%0A $%7Bcolor%7D%0A $%7Bdisplay%7D%0A $%7BfontFamily%7D%0A $%7BfontSize%7D%0A $%7BfontWeight%7D%0A $%7BlineHeight%7D%0A $%7BletterSpacing%7D%0A $%7Bspace%7D%0A $%7BtextAlign%7D%0A $%7BtextTransform%7D%0A $%7BwhiteSpace%7D%0A%60;%0A%0AH4.defaultProps = %7B%0A fontSize: '1.8rem',%0A fontWeight: 'bold',%0A m: 0,%0A%7D;%0A%0Aexport const H5 = styled.h5%60%0A $%7Bcolor%7D%0A $%7Bdisplay%7D%0A $%7BfontFamily%7D%0A $%7BfontSize%7D%0A $%7BfontWeight%7D%0A $%7BlineHeight%7D%0A $%7BletterSpacing%7D%0A $%7Bspace%7D%0A $%7BtextAlign%7D%0A $%7BtextTransform%7D%0A $%7BwhiteSpace%7D%0A%60;%0A%0AH5.defaultProps = %7B%0A fontSize: '1.2rem',%0A fontWeight: 'bold',%0A m: 0,%0A%7D;%0A
|
12f3681e0e9e32fa980def3969a01d0f19090188 | Fix test and improve process sandboxing (#5027) | packages/jest-util/src/create_process_object.js | packages/jest-util/src/create_process_object.js | /**
* Copyright (c) 2017-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import deepCyclicCopy from './deep_cyclic_copy';
const BLACKLIST = new Set(['mainModule']);
export default function() {
const process = require('process');
const newProcess = deepCyclicCopy(process, BLACKLIST);
newProcess[Symbol.toStringTag] = 'process';
// Sequentially execute all constructors over the object.
let proto = process;
while ((proto = Object.getPrototypeOf(proto))) {
if (typeof proto.constructor === 'function') {
proto.constructor.call(newProcess);
}
}
return newProcess;
}
| JavaScript | 0 | @@ -299,16 +299,27 @@
nModule'
+, '_events'
%5D);%0A%0Aexp
|
b8a7f52d5827dbcd7a5a291d8ce0fb80bca6f7a3 | FIX logger reference | lib/core/src/server/manager/manager-config.js | lib/core/src/server/manager/manager-config.js | import path from 'path';
import fs from 'fs-extra';
import findUp from 'find-up';
import resolveFrom from 'resolve-from';
import logger from '@storybook/node-logger';
import loadPresets from '../presets';
import loadCustomPresets from '../common/custom-presets';
import { typeScriptDefaults } from '../config/defaults';
const getAutoRefs = async (options) => {
const location = await findUp('package.json', { cwd: options.configDir });
const directory = path.dirname(location);
const { dependencies, devDependencies } = await fs.readJSON(location);
const list = await Promise.all(
Object.keys({ ...dependencies, ...devDependencies }).map(async (d) => {
try {
const l = resolveFrom(directory, path.join(d, 'package.json'));
const { storybook, name } = await fs.readJSON(l);
if (storybook?.url) {
return { id: name, ...storybook };
}
} catch {
logger.warn(`unable to find package.json for ${d}`);
return undefined;
}
return undefined;
})
);
return list.filter(Boolean);
};
const toTitle = (input) => {
const result = input
.replace(/[A-Z]/g, (f) => ` ${f}`)
.replace(/[-_][A-Z]/gi, (f) => ` ${f.toUppercase()}`)
.replace('-', ' ')
.replace('_', ' ');
return `${result.substring(0, 1).toUpperCase()}${result.substring(1)}`.trim();
};
async function getManagerWebpackConfig(options, presets) {
const typescriptOptions = await presets.apply('typescript', { ...typeScriptDefaults }, options);
const babelOptions = await presets.apply('babel', {}, { ...options, typescriptOptions });
const autoRefs = await getAutoRefs(options);
const refs = await presets.apply('refs', undefined, options);
const entries = await presets.apply('managerEntries', [], options);
if (refs) {
autoRefs.forEach(({ id, url, title }) => {
refs[id] = {
id,
url,
title,
};
});
Object.entries(refs).forEach(([key, value]) => {
const url = typeof value === 'string' ? value : value.url;
const title = typeof value === 'string' ? toTitle(key) : value.title || toTitle(value.key);
refs[key] = {
id: key,
title,
url,
};
});
entries.push(path.resolve(path.join(options.configDir, `generated-refs.js`)));
}
return presets.apply('managerWebpack', {}, { ...options, babelOptions, entries, refs });
}
export default async (options) => {
const { corePresets = [], frameworkPresets = [], overridePresets = [], ...restOptions } = options;
const presetsConfig = [
...corePresets,
require.resolve('../common/babel-cache-preset.js'),
...frameworkPresets,
...loadCustomPresets(options),
...overridePresets,
];
const presets = loadPresets(presetsConfig, restOptions);
return getManagerWebpackConfig({ ...restOptions, presets }, presets);
};
| JavaScript | 0 | @@ -122,23 +122,27 @@
%0A%0Aimport
+ %7B
logger
+ %7D
from '@
|
6a3cc0ab2fe8dbde1b1191f6e045d6a517cf1153 | fix author | lib/dependencies/CreateScriptUrlDependency.js | lib/dependencies/CreateScriptUrlDependency.js | /*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Ivan Kopeykin @vankop
*/
"use strict";
const RuntimeGlobals = require("../RuntimeGlobals");
const makeSerializable = require("../util/makeSerializable");
const NullDependency = require("./NullDependency");
/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
/** @typedef {import("../Dependency")} Dependency */
/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
class CreateScriptUrlDependency extends NullDependency {
/**
* @param {[number, number]} range range
*/
constructor(range) {
super();
this.range = range;
}
get type() {
return "create script url";
}
}
CreateScriptUrlDependency.Template = class CreateScriptUrlDependencyTemplate extends (
NullDependency.Template
) {
/**
* @param {Dependency} dependency the dependency for which the template should be applied
* @param {ReplaceSource} source the current replace source which can be modified
* @param {DependencyTemplateContext} templateContext the context object
* @returns {void}
*/
apply(dependency, source, { runtimeRequirements }) {
const dep = /** @type {CreateScriptUrlDependency} */ (dependency);
runtimeRequirements.add(RuntimeGlobals.createScriptUrl);
source.insert(dep.range[0], `${RuntimeGlobals.createScriptUrl}(`);
source.insert(dep.range[1], ")");
}
};
makeSerializable(
CreateScriptUrlDependency,
"webpack/lib/dependencies/CreateScriptUrlDependency"
);
module.exports = CreateScriptUrlDependency;
| JavaScript | 0.000189 | @@ -72,29 +72,29 @@
hor
-Ivan
+Tobias
Kop
-eykin @vankop
+pers @sokra
%0A*/%0A
|
d7decd9b6c83c923918ae464b4d88ea0c99b34c9 | update icon url | src/app/components/nav.js | src/app/components/nav.js | var React = require('react');
import Block from './Block';
require('../../css/nav.css');
function Navbar(props){
return(
<div className='pane'>
<nav className='navbar' id='navbarPage'>
<ul>
<li id='button'><Block handleClick={props.handleClick} task='' imgURL='./images/back.png'/></li>
<li id='headerText'><div><h3 className='Text'>{props.header}</h3></div></li>
</ul>
</nav>
</div>
);
}
export default Navbar; | JavaScript | 0.000001 | @@ -322,13 +322,13 @@
='./
-image
+asset
s/ba
|
7f781a43146856083d10a60250ab51a8dd59c7f4 | Fix content loading | src/app/preloads/index.js | src/app/preloads/index.js | const loadContent = require('../../shared/utils/load-content');
if (window.location.href.startsWith('wexond://newtab')) {
loadContent('newtab');
}
| JavaScript | 0 | @@ -62,16 +62,19 @@
);%0A%0Aif (
+%0A
window.l
@@ -115,16 +115,91 @@
newtab')
+ %7C%7C%0A window.location.href.startsWith('http://localhost:8080/newtab.html')%0A
) %7B%0A lo
|
40b2a1ef08a0737e3843f2912e0f8f4ff33cc57f | add warning on store not set | src/app/utils/UserUtil.js | src/app/utils/UserUtil.js | /**
* This file replicates and extends the contents of User.js in branches new-url-scheme && notifications-ui.
* Additions here need to be added to ./User.js when those are merged. Imports should pull that file, and this one should be deleted.
*/
let store = false;
export const setStore = (theStore) => {
if(!store) {
store = theStore;
} else {
throw Error("Routes.setStore - store has already been set.");
}
}
/**
* returns the current user's username *if* there is one.
*
* later can be modified to return full user object if passed *true* for 1st argument
* @returns {boolean}
*/
export const currentUser = () => {
if (store) {
const state = store.getState();
if (state.user) {
const current = state.user.getIn(['current']);
if (current) {
return current;
}
}
}
return false;
}
/**
* returns the current user's username *if* there is one.
*
* later can be modified to return full user object if passed *true* for 1st argument
* @returns {boolean}
*/
export const currentUsername = () => {
if (store) {
const state = store.getState();
if (state.user) {
const uName = state.user.getIn(['current', 'username']);
if (uName) {
return uName;
}
}
}
return false;
}
export const isOwnAccount = (username) => {
return (username === currentUsername());
}
/**
*
* @returns {boolean}
*/
export const isLoggedIn = () => {
return localStorage.getItem('autopost2')? true : false;
}
| JavaScript | 0.000001 | @@ -263,16 +263,62 @@
= false;
+%0Aconst MSG_STORE_NOT_SET = 'store is not set';
%0A%0Aexport
@@ -915,32 +915,86 @@
%7D%0A %7D%0A
+ %7D else %7B%0A console.warn(MSG_STORE_NOT_SET);%0A
%7D%0A return
@@ -1432,32 +1432,32 @@
;%0A %7D%0A
-
%7D%0A %7D%0A
@@ -1446,24 +1446,78 @@
%7D%0A %7D%0A
+ %7D else %7B%0A console.warn(MSG_STORE_NOT_SET);%0A
%7D%0A re
|
dd5215eceb5a08f42cd46c9a9d586cee0fcfaa5c | fix search submit functionality | docs/app/src/search.js | docs/app/src/search.js | angular.module('search', [])
.controller('DocsSearchCtrl', ['$scope', '$location', 'docsSearch', function($scope, $location, docsSearch) {
function clearResults() {
$scope.results = [];
$scope.colClassName = null;
$scope.hasResults = false;
}
$scope.search = function(q) {
var MIN_SEARCH_LENGTH = 2;
if(q.length >= MIN_SEARCH_LENGTH) {
var results = docsSearch(q);
var totalAreas = 0;
for(var i in results) {
++totalAreas;
}
if(totalAreas > 0) {
$scope.colClassName = 'cols-' + totalAreas;
}
$scope.hasResults = totalAreas > 0;
$scope.results = results;
}
else {
clearResults();
}
if(!$scope.$$phase) $scope.$apply();
};
$scope.submit = function() {
var result;
for(var i in $scope.results) {
result = $scope.results[i][0];
if(result) {
break;
}
}
if(result) {
$location.path(result.url);
$scope.hideResults();
}
};
$scope.hideResults = function() {
clearResults();
$scope.q = '';
};
}])
.controller('Error404SearchCtrl', ['$scope', '$location', 'docsSearch', function($scope, $location, docsSearch) {
$scope.results = docsSearch($location.path().split(/[\/\.:]/).pop());
}])
.factory('lunrSearch', function() {
return function(properties) {
if (window.RUNNING_IN_NG_TEST_RUNNER) return null;
var engine = lunr(properties);
return {
store : function(values) {
engine.add(values);
},
search : function(q) {
return engine.search(q);
}
};
};
})
.factory('docsSearch', ['$rootScope','lunrSearch', 'NG_PAGES',
function($rootScope, lunrSearch, NG_PAGES) {
if (window.RUNNING_IN_NG_TEST_RUNNER) {
return null;
}
var index = lunrSearch(function() {
this.ref('id');
this.field('title', {boost: 50});
this.field('keywords', { boost : 20 });
});
angular.forEach(NG_PAGES, function(page, key) {
if(page.searchTerms) {
index.store({
id : key,
title : page.searchTerms.titleWords,
keywords : page.searchTerms.keywords
});
};
});
return function(q) {
var results = {
api : [],
tutorial : [],
guide : [],
error : [],
misc : []
};
angular.forEach(index.search(q), function(result) {
var key = result.ref;
var item = NG_PAGES[key];
var area = item.area;
item.path = key;
var limit = area == 'api' ? 40 : 14;
if(results[area].length < limit) {
results[area].push(item);
}
});
return results;
};
}])
.directive('focused', function($timeout) {
return function(scope, element, attrs) {
element[0].focus();
element.on('focus', function() {
scope.$apply(attrs.focused + '=true');
});
element.on('blur', function() {
// have to use $timeout, so that we close the drop-down after the user clicks,
// otherwise when the user clicks we process the closing before we process the click.
$timeout(function() {
scope.$eval(attrs.focused + '=false');
});
});
scope.$eval(attrs.focused + '=true');
};
})
.directive('docsSearchInput', ['$document',function($document) {
return function(scope, element, attrs) {
var ESCAPE_KEY_KEYCODE = 27,
FORWARD_SLASH_KEYCODE = 191;
angular.element($document[0].body).bind('keydown', function(event) {
var input = element[0];
if(event.keyCode == FORWARD_SLASH_KEYCODE && document.activeElement != input) {
event.stopPropagation();
event.preventDefault();
input.focus();
}
});
element.bind('keydown', function(event) {
if(event.keyCode == ESCAPE_KEY_KEYCODE) {
event.stopPropagation();
event.preventDefault();
scope.$apply(function() {
scope.hideResults();
});
}
});
};
}]);
| JavaScript | 0.000004 | @@ -946,11 +946,12 @@
ult.
-url
+path
);%0A
|
858470f5afe3ef6e0707c43c8ce99390fd1d95b3 | delete useless code | app/js/component/ui/course_view.js | app/js/component/ui/course_view.js | define(function (require) {
var defineComponent = require('flight/lib/component');
var templates = require('js/templates'),
template = templates['course'];
var _ = require('lodash/lodash');
return defineComponent(course);
function course() {
this.defaultAttrs({
app: '#app',
courseName: '.course_name'
});
this.renderCourse = function () {
var course = this.attr.course;
var groups = this.groupCheckpoints(this.attr.course.checkpoints);
var html = template.render({
groups: groups,
name: course.name,
sponsor: course.sponsor,
trainer: course.trainer
});
$('#app').html(html).fadeIn();
this.on('.checkpoint-item', 'click', this.handleChecked);
//this.select('app').append(html).fadeIn();
};
this.handleChecked = function (event) {
var id = event.target.id;
var data = event.target.checked;
var userId = $('body').data('_id');
var courseId = this.attr.course._id;
console.log(courseId);
//$.ajax('/api/users/course/checkpoints/' + id, {
$.ajax('/api/users/' + userId + '/course/' + courseId + '/checkpoints/' + id, {
method: 'patch',
data: {checked: data}
}).fail(function () {
console.log('checkpoint 更新失败');
}).done(function (data) {
console.log('checkpoint 更新成功');
});
};
this.groupCheckpoints = function (checkpointList) {
var self = this;
var checkpoints = self.addChecked(checkpointList);
var groupCheckpoints = [];
var groupNames = _.uniq(_.pluck(checkpoints, 'type'));
_.forEach(groupNames, function (groupName) {
groupCheckpoints.push({groupName: groupName, checkpoints: _.where(checkpoints, {type: groupName})})
});
return groupCheckpoints;
};
this.addChecked = function (checkpointList) {
var checkpoints = checkpointList;
var self = this;
_.forEach(checkpointList, function (checkpoint) {
checkpoint.checked = self.checked(checkpoint._id);
console.log(checkpoint);
});
return checkpoints;
};
this.checked = function (id) {
var results = this.attr.data.data.result;
var checked = false;
_.forEach(results, function (result) {
if (result.checkpointId === id) {
checked = result.traineeChecked;
}
});
return checked;
};
this.after('initialize', function () {
this.renderCourse();
});
}
});
| JavaScript | 0.000021 | @@ -1152,43 +1152,8 @@
_id;
-%0A console.log(courseId);
%0A%0A
|
b2b4c9b792902f6a6eef667ef871ca336da6799d | remove import for nonexistent file #618 | app/js/welcome/components/index.js | app/js/welcome/components/index.js | export PairBrowserView from './PairBrowserView'
export LandingView from './LandingView'
export RestoreView from './RestoreView'
export NewInternetView from './NewInternetView'
export DataControlView from './DataControlView'
export EnterPasswordView from './EnterPasswordView'
export CreateIdentityView from './CreateIdentityView'
export WriteDownKeyView from './WriteDownKeyView'
export ConfirmIdentityKeyView from './ConfirmIdentityKeyView'
export EnterEmailView from './EnterEmailView'
| JavaScript | 0 | @@ -221,60 +221,8 @@
ew'%0A
-export EnterPasswordView from './EnterPasswordView'%0A
expo
|
7a3ebc83db8107958625908da03cf7ae68752bea | fix bug: check selection state on selectAll action | app/scripts/services/CustomGrid.js | app/scripts/services/CustomGrid.js | 'use strict';
angular.module('customApp')
.factory('CustomGrid', function (DefaultOptions) {
var CustomGrid = function (options) {
var that = this;
var _total = function () {
return that._data.length;
};
var _pristineTotal = function () {
return that._pristineData.length;
};
var _getRanges = function () {
var ranges = [];
var total = that.total();
var pageSize = that._options.pageSize;
var rangeNum = Math.ceil(total / pageSize);
for (var i = 0; i < rangeNum; i++) {
ranges.push({
from: i * pageSize,
to: (i + 1) * pageSize,
data: _.slice(that._data, i * pageSize, (i + 1) * pageSize)
});
}
return ranges;
};
var _totalPages = function () {
return that._ranges.length;
};
var _fetchPage = function (page, clean) {
if (clean === true) {
that.view.length = 0;
}
if (_.isUndefined(page)) {
page = that.page();
}
var range = that._ranges[page - 1];
if (range && range.from >= that.view.length) {
Array.prototype.push.apply(that.view, range.data);
}
};
var _fetchPages = function (pages) {
that.view.length = 0;
_.each(pages, function (page) {
_fetchPage(page);
});
};
var _page = function (page) {
if (!page) {
return that._page;
} else {
if (page > _totalPages()) {
throw 'Page range error. You try set ' + page + ' page of ' + _totalPages();
}
_fetchPage(page, !that.virtualization);
that._page = page;
}
};
var _sort = function (column, direction) {
var comparer = function (firstItem, secondItem, direction) {
var result;
if (firstItem[column] === secondItem[column]) {
result = 0;
} else {
result = firstItem[column] > secondItem[column] ? 1 : -1;
}
if (direction === 'asc') {
return result;
} else {
return -1 * result;
}
};
that._data.sort(_.partialRight(comparer, direction));
that._ranges = _getRanges();
if (!that.virtualization) {
_fetchPage(undefined, true);
} else {
_fetchPages(_.range(1, that.page() + 1))
}
that.sorting.direction = direction;
that.sorting.column = column;
};
var _filter = function () {
var filtered = _.filter(that._pristineData, function (dataItem) {
var result = true;
_.each(that.filters, function (value, key) {
if (key === '__selected') {
result = result && (dataItem[key] === true);
} else if (key === 'Age') {
var maxAge = _.last(value.split('-'));
var minAge = _.first(value.split('-'));
result = result && (dataItem[key] > minAge && dataItem[key] < maxAge);
} else {
if (value && dataItem[key].indexOf(value) === -1) {
result = false;
}
}
});
if (result && that.filters.Age) {
var parts = that.filters.Age.split('-');
result = dataItem.Age > parts[0] && dataItem.Age < parts[1];
}
return result;
});
that._data.length = 0;
Array.prototype.push.apply(that._data, filtered);
that._ranges = _getRanges();
that._page = 1;
that.view.length = 0;
that.fetchPage();
};
var _select = function (dataItem) {
if (!that._options.editable) {
return;
}
if (_.contains(that.selected, dataItem)) {
_.pull(that.selected, dataItem);
delete dataItem.__selected;
} else {
that.selected.push(dataItem);
dataItem.__selected = true;
}
};
var _selectAll = function() {
_.each(that.view, that.select);
};
var _clearSelection = function () {
_.each(that.selected, function (dataItem) {
delete dataItem.__selected;
//delete dataItem.__selected;
});
that.selected.length = 0;
if (that.filters.__selected) {
that.filter();
}
};
var _remove = function () {
_.each(that.selected, function (dataItem) {
_.pull(that._pristineData, dataItem);
});
that._data.length = 0;
Array.prototype.push.apply(that._data, that._pristineData);
that._ranges = _getRanges();
if (!that.virtualization) {
_fetchPage(undefined, true);
} else {
_fetchPages(_.range(1, that.page() + 1))
}
that.selected.length = 0;
that._total = that.total();
that._pristineTotal = that.pristineTotal();
that.filter();
};
var _clearFilter = function (column) {
that.filters[column] = '';
that.filter();
};
//Public grid API
//without side effects
that.totalPages = _totalPages;
that.total = _total;
that.getRanges = _getRanges;
that.pristineTotal = _pristineTotal;
that.clearFilter = _clearFilter;
that.clearSelection = _clearSelection;
that.remove = _remove;
that.select = _select;
that.filter = _filter;
that.sort = _sort;
that.page = _page;
that.fetchPage = _fetchPage;
that.selectAll = _selectAll;
that.init(options);
};
CustomGrid.prototype.init = function (options) {
var that = this;
var validateOptions = function (options) {
var validated = {};
_.extend(validated, angular.copy(DefaultOptions));
_.each(options, function (value, key) {
if (!DefaultOptions.hasOwnProperty(key)) {
delete options[key];
}
});
_.extend(validated, angular.copy(options));
//options.data.length = 0;
return validated;
};
var extractColumns = function (data) {
return data.length ? _.chain(data).first().keys().without('__uid', '__selected', '__editing').value() : [];
};
var setupData = function (data) {
_.each(data, function (dataItem, index) {
_.each(['__uid', '__selected', '__editing'], function (prop) {
if (dataItem.hasOwnProperty(prop)) {
throw 'dataItems should not contain ' + prop + ' property';
}
});
dataItem.__uid = index;
});
};
//private grid properties
that._options = validateOptions(options);
that._pristineData = that._options.data;
that._data = that._pristineData.slice();
that._ranges = that.getRanges();
that._total = that.total();
that._pristineTotal = that.pristineTotal();
that._pageSize = that._options.pageSize;
that._page = 1;
//public grid properties
that.selected = [];
that.filters = {};
that.sorting = {
column: '__uid',
direction: 'asc'
};
that.paging = {
pageSize: that._pageSize
};
that.view = [];
that.virtualization = that._options.virtualization;
that.columns = extractColumns(that._pristineData);
if (!that.columns.length) {
that.columns = that._options.columns || [];
}
if (!that.columns.length) {
throw 'You must specified dataItems or columns!';
}
setupData(that._pristineData);
that.fetchPage(1);
};
return CustomGrid;
});
| JavaScript | 0 | @@ -4095,27 +4095,130 @@
t.view,
-that.select
+function(dataItem) %7B%0A if(!dataItem.__selected) %7B%0A that.select(dataItem);%0A %7D%0A %7D
);%0A
|
adf5b0d13aa8cc8da9b920a773b5067a37ac7fa7 | use platform getPrBody | lib/workers/repository/onboarding/pr/index.js | lib/workers/repository/onboarding/pr/index.js | const is = require('@sindresorhus/is');
const { getConfigDesc } = require('./config-description');
const { getErrors, getWarnings } = require('./errors-warnings');
const { getBaseBranchDesc } = require('./base-branch');
const { getPrList } = require('./pr-list');
async function ensureOnboardingPr(config, packageFiles, branches) {
if (config.repoIsOnboarded) {
return;
}
logger.debug('ensureOnboardingPr()');
logger.trace({ config });
const onboardingBranch = `renovate/configure`;
const onboardingPrTitle = 'Configure Renovate';
logger.debug('Filling in onboarding PR template');
let prTemplate = `Welcome to [Renovate](https://renovatebot.com)! This is an onboarding PR to help you understand and configure settings before regular Pull Requests begin.\n\n`;
prTemplate += config.requireConfig
? `Renovate will begin keeping your dependencies up-to-date only once you merge this Pull Request.\nIf you close this Pull Request unmerged, then Renovate will be disabled.\n\n`
: `Renovate will begin keeping your dependencies up-to-date only once you merge or close this Pull Request.\n\n`;
prTemplate += `If you have any questions, try reading our [Docs](https://renovatebot.com/docs), particularly the Getting Started section.
You can post questions in [our Config Help repository](https://github.com/renovatebot/config-help/issues) or @ the app author @rarkins in this PR and he'll probably see it.
---
{{PACKAGE FILES}}
{{CONFIG}}
{{WARNINGS}}
{{ERRORS}}
{{BASEBRANCH}}
{{PRLIST}}
---
`;
let prBody = prTemplate;
if (packageFiles && Object.entries(packageFiles).length) {
let files = [];
for (const [manager, managerFiles] of Object.entries(packageFiles)) {
files = files.concat(
managerFiles.map(file => ` * \`${file.packageFile}\` (${manager})`)
);
}
prBody =
prBody.replace(
'{{PACKAGE FILES}}',
'### Detected Package Files\n\n' + files.join('\n')
) + '\n';
} else {
prBody = prBody.replace('{{PACKAGE FILES}}\n', '');
}
prBody = prBody.replace('{{CONFIG}}\n', getConfigDesc(config, packageFiles));
prBody = prBody.replace('{{WARNINGS}}\n', getWarnings(config));
prBody = prBody.replace('{{ERRORS}}\n', getErrors(config));
prBody = prBody.replace('{{BASEBRANCH}}\n', getBaseBranchDesc(config));
prBody = prBody.replace('{{PRLIST}}\n', getPrList(config, branches));
// istanbul ignore if
if (config.global) {
if (config.global.prBanner) {
prBody = config.global.prBanner + '\n\n' + prBody;
}
if (config.global.prFooter) {
prBody = prBody + '\n---\n\n' + config.global.prFooter + '\n';
}
}
logger.trace('prBody:\n' + prBody);
// Check if existing PR exists
const existingPr = await platform.getBranchPr(`renovate/configure`);
if (existingPr) {
logger.info('Found open onboarding PR');
// Check if existing PR needs updating
if (existingPr.title === onboardingPrTitle && existingPr.body === prBody) {
logger.info(`${existingPr.displayNumber} does not need updating`);
return;
}
// PR must need updating
await platform.updatePr(existingPr.number, onboardingPrTitle, prBody);
logger.info(`Updated ${existingPr.displayNumber}`);
return;
}
logger.info('Creating onboarding PR');
const labels = [];
const useDefaultBranch = true;
try {
const pr = await platform.createPr(
onboardingBranch,
onboardingPrTitle,
prBody,
labels,
useDefaultBranch
);
logger.info({ pr: pr.displayNumber }, 'Created onboarding PR');
} catch (err) /* istanbul ignore next */ {
if (
err.statusCode === 422 &&
err.response &&
err.response.body &&
!is.empty(err.response.body.errors) &&
err.response.body.errors[0].message &&
err.response.body.errors[0].message.startsWith(
'A pull request already exists'
)
) {
logger.info('Onboarding PR already exists but cannot find it');
await platform.deleteBranch(onboardingBranch);
return;
}
throw err;
}
}
module.exports = {
ensureOnboardingPr,
};
| JavaScript | 0 | @@ -2679,16 +2679,56 @@
Body);%0A%0A
+ prBody = platform.getPrBody(prBody);%0A%0A
// Che
|
9cb1f1571cfb4b2ce1b5fc9f282e36f28558a1c0 | Fix bugs | src/dbl-option.js | src/dbl-option.js | /*
Created by Samir Chaves
Git Repo https://github.com/samirbraga/Double-Option-Button---JQuery-Plugin/edit/master/README.md
*/
$.fn.dblOption = function(opts){
$(this).each(function(){
var self = $(this);
self[0].dblOptions = $.extend({}, $.fn.dblOption.defaults, opts);
opts = self[0].dblOptions;
self.addClass('dbl-option-container ' + opts['initSide']);
if (opts['callOnInit'] == true) {
if (opts['initSide'] == 'right') {
self.setSide('right');
} else {
self.setSide('left');
}
} else {
if (opts['initSide'] == 'left') {
self[0].dblOptions.side = 'left';
} else {
self[0].dblOptions.side = 'right';
}
}
self.css({
width: opts['width'],
height: opts['height'],
lineHeight: opts['height']
});
var template = [
'<div class="labels labels-back">',
'<div class="label label-left">',
'<span></span>',
'</div>',
'<div class="label label-right">',
'<span>RENTTALLER</span>',
'</div>',
'</div>',
'<div class="labels labels-front">',
'<div class="labels-ranger">',
'<div class="label label-left">',
' <span>RENTTER</span>',
'</div>',
'<div class="label label-right">',
'<span>RENTTALLER</span>',
'</div>',
'</div>',
'</div>'
].join('');
self.append(template);
self.find('.labels-ranger').css('background', opts['bgSelector']);
if (opts['animation'] == true) {
self.find('.labels-ranger').addClass('animated');
self.find('.labels-front').addClass('animated');
}
self.mousedown(function(e){
e.preventDefault();
return false;
})
self.find('.label-right span').text(opts['rightLabel']);
self.find('.label-left span').text(opts['leftLabel']);
var toggleOption = function(e){
e.preventDefault();
var label = $(this);
if (label.hasClass('label-right')) {
self.setSide('right');
} else {
self.setSide('left');
}
return false;
}
self.find('.labels-back .label').click(toggleOption);
})
}
$.fn.dblOption.defaults = {
width: '220px',
height: '30px',
initSide: 'right',
leftLabel: 'OPTION 1',
rightLabel: 'OPTION 2',
callOnInit: true,
bgSelector: '#363b44',
animation: true,
onChange: function () {
},
onRight: function () {
console.log('right');
},
onLeft: function () {
console.log('left');
}
}
$.fn.setSide = function(side){
var self = $(this);
if (self.hasClass('dbl-option-container') && !!side) {
side = side.toLowerCase();
self.removeClass('right left');
self.addClass(side);
if (side == 'right' && self[0].dblOptions.side != 'right') {
self[0].dblOptions.side = 'right';
self[0].dblOptions['onRight']()
self[0].dblOptions['onChange']()
} else if (side == 'left' && self[0].dblOptions.side != 'left') {
self[0].dblOptions.side = 'left';
self[0].dblOptions['onLeft']();
self[0].dblOptions['onChange']()
}
}
}
$.fn.toggleSide = function() {
var self = $(this);
if (self.hasClass('dbl-option-container')) {
if (self[0].dblOptions.side == 'right') {
self.setSide('left');
} else if (self[0].dblOptions.side == 'left') {
self.setSide('right');
}
}
}
$.fn.getSide = function() {
var self = $(this);
return self[0].dblOptions.side;
}
| JavaScript | 0.000004 | @@ -2253,34 +2253,8 @@
) %7B%0A
- console.log('right');%0A
%7D,
@@ -2282,33 +2282,8 @@
) %7B%0A
- console.log('left');%0A
%7D%0A
|
459b8ec5b9d6996b29d73fdf7b34ac19aa5ad9f6 | teste gccbcv | spec/suites/testeJAsmine.js | spec/suites/testeJAsmine.js | describe('Exibicao da mensagem de boas-vindas', function(){
beforeEach(function(){
setFixtures('<div id="mensagem" />');
this.mensagem = $('#mensagem');
});
afterEach(function(){
this.horas = [];
});
it("Deve exibir 'Bom-dia!' entre 5:00 e 11:59", function(){
this.horas = ['05:00', '09:33', '10:22', '11:59'];
for(i in this.horas){
saudacao(this.horas[i]);
expect(this.mensagem.text()).toEqual('Bom-dia!');
}
});
it("Deve exibir 'Boa-tarde!' entre 12:00 e 17:59", function(){
this.horas = ['15:00', '13:22', '17:59'];
for(i in this.horas){
saudacao(this.horas[i]);
expect(this.mensagem.text()).toEqual('Boa-tarde!');
}
});
it("Deve exibir 'Boa-noite!' entre 18:00 e 23:59", function(){
this.horas = ['18:00', '20:22', '23:59'];
for(i in this.horas){
saudacao(this.horas[i]);
expect(this.mensagem.text()).toEqual('Boa-noite!');
}
});
it("Deve exibir, por padrão, a mensagem de acordo com a hora do cliente", function(){
var data = new Date;
data.setTime(data.getTime());
var hora = data.getHours();
saudacao();
var texto = this.mensagem.text();
if(hora < 5)
expect(texto).toEqual('Dormir é para os fracos!');
if(hora < 12)
expect(texto).toEqual('Bom-dia!');
else if(hora < 18)
expect(texto).toEqual('Boa-tarde!');
else
expect(texto).toEqual('Boa-noite!');
});
});
describe('Quando eu passar o soma para calculadora', function(){
beforeEach(function(){
setFixtures('<div id="mensagem" />');
this.mensagem = $('#mensagem');
});
afterEach(function(){
this.primeiroValor = null;
this.segundoValor = null;
});
it("passando 1 e 2! deve retornar 3", function(){
var retorno = 0;
this.primeiroValor = 1;
this.segundoValor = 2;
retorno = objTeste.calculadora('soma',this.primeiroValor,this.segundoValor);
expect(retorno).toEqual(3);
expect('3').toEqual(this.mensagem.text())
});
it("passando valores vazio! deve retornar 0", function(){
var retorno = 0;
this.primeiroValor = '';
this.segundoValor ='';
retorno = objTeste.calculadora('soma',this.primeiroValor,this.segundoValor);
expect(retorno).toEqual(0);
expect('0').toEqual(this.mensagem.text())
});
it("passando valores undefined! deve retornar 0", function(){
var retorno = 0;
retorno = objTeste.calculadora('soma');
expect(retorno).toEqual(0);
expect('0').toEqual(this.mensagem.text())
});
it("passando 1 e -2! deve retornar -1", function(){
var retorno = -1;
this.primeiroValor = 1;
this.segundoValor =-2;
retorno = objTeste.calculadora('soma',this.primeiroValor,this.segundoValor);
expect(retorno).toEqual(-1);
expect('-1').toEqual(this.mensagem.text())
});
});
describe("Quando eu chamar a calculadora", function(){
beforeEach(function(){
});
afterEach(function(){
this.primeiroValor = null;
this.segundoValor = null;
});
it('Tem que passar uma vez pela soma!', function(){
this.primeiroValor = 1;
this.segundoValor = 2;
spyOn(objTeste, 'soma');
objTeste.calculadora('soma',this.primeiroValor,this.segundoValor);
expect(objTeste.soma).toHaveBeenCalled();
});
it('Tem que passar pela soma com os parametros 1 e 2!', function(){
this.primeiroValor = 1;
this.segundoValor = 2;
spyOn(objTeste, 'soma');
objTeste.calculadora('soma',this.primeiroValor,this.segundoValor);
expect(objTeste.soma).toHaveBeenCalledWith(this.primeiroValor,this.segundoValor);
});
it('Não deve passar pela subtração!', function(){
this.primeiroValor = 1;
this.segundoValor = 2;
spyOn(objTeste, 'subtracao');
objTeste.calculadora('soma',this.primeiroValor,this.segundoValor);
expect(objTeste.subtracao).not.toHaveBeenCalled();
});
});
| JavaScript | 0.000003 | @@ -45,37 +45,32 @@
s', function()%7B%0A
- %0A
beforeEach(f
|
54d0381174f622f69f1f5553c2d5ebd8ee3b610a | Update RivCrimeReport.js | Examples/js/RivCrimeReport.js | Examples/js/RivCrimeReport.js | (function() {
// Create the connector object
var myConnector = tableau.makeConnector();
// Define the schema
myConnector.getSchema = function(schemaCallback) {
var cols = [{
id: "npc",
alias: "npc",
dataType: tableau.dataTypeEnum.string
}];
var tableSchema = {
id: "riversideCrime",
alias: "Riverside Crime Top 20 JSON entries",
columns: cols
};
schemaCallback([tableSchema]);
};
// Download the data
myConnector.getData = function(table, doneCallback) {
$.getJSON("https://riversideca.gov/transparency/data/dataset/json/27", function(resp) {
var feat = resp.features,
tableData = [];
// Iterate over the JSON object
for (var i = 0, len = feat.length; i < len; i++) {
tableData.push({
"npc": data[i][npc],
});
}
table.appendRows(tableData);
doneCallback();
});
};
tableau.registerConnector(myConnector);
// Create event listeners for when the user submits the form
$(document).ready(function() {
$("#submitButton").click(function() {
tableau.connectionName = "Riverside Crime Report"; // This will be the data source name in Tableau
tableau.submit(); // This sends the connector object to Tableau
});
});
})();
| JavaScript | 0 | @@ -420,15 +420,8 @@
ime
-Top 20
JSON
|
7dab8a806cabac86d399a36c94e792551f5a0979 | Change order of Risk level graph | app/assets/javascripts/roster.js | app/assets/javascripts/roster.js | $(function() {
if ($('body').hasClass('homerooms') && $('body').hasClass('show')) {
// Initialize table sort on roster table
var table = document.getElementById('roster-table');
new Tablesort(table, { descending: false });
// Initialize table sort on roster table
$('#homeroom-select').bind('change', function() {
window.location.pathname = '/homerooms/' + $(this).val();
});
function updateColumns () {
for (i = 0; i < roster_columns.length; i++) {
var column = roster_columns[i];
if (columns_selected.indexOf(column) === -1) {
$('.' + column).hide();
} else {
$('.' + column).show();
}
}
}
function updateCookies () {
Cookies.set("columns_selected", columns_selected);
}
// Show/hide column groups
var roster_columns = [
'attendance',
'discipline',
'language',
'star',
'program',
'free-reduced',
'access',
'dibels',
'name',
'risk',
'sped',
'mcas'
];
var columns_selected = Cookies.getJSON("columns_selected");
console.log(columns_selected);
updateColumns();
$("#column-group-select").chosen({width: "110%"}).on('change', function(e, params) {
if (params.deselected !== undefined) {
var assessment = params.deselected;
var index = columns_selected.indexOf(assessment)
columns_selected.splice(index, 1);
updateCookies();
updateColumns();
} else if (params.selected !== undefined) {
var assessment = params.selected;
columns_selected.push(assessment)
updateCookies();
updateColumns();
}
});
// Risk level tooltip for overall roster table
var roster_rooltip_template = $('#roster-tooltip-template').html();
var rendered = Mustache.render(roster_rooltip_template);
$('#roster-tooltip').tooltipster({
content: rendered,
position: 'bottom-right',
contentAsHTML: true
});
// Tooltips for individual student risk levels
function getRiskLevelToolTip (studentId) {
var tooltip = $(".risk-level-tooltip[data-student-id='" + studentId + "']").html();
var mustache_rendered = Mustache.render(tooltip);
return mustache_rendered;
}
$.each($('.risk-tooltip-circle'), function() {
$this = $(this)
var student_id = parseInt($this.data('student-id'))
var tooltip = getRiskLevelToolTip(student_id)
$this.tooltipster({
content: tooltip,
position: 'bottom',
contentAsHTML: true
});
});
// Turn table rows into links to student profiles
$('tbody td').click(function () {
location.href = $(this).attr('href');
});
}
});
$(function() {
if ($('body').hasClass('homerooms') && $('body').hasClass('show')) {
var attendance_series = [{
name: 'Risk level',
data: [5, 2, 1, 4]
}, {
name: 'Interventions',
data: [3, 2, 0, 0]
}, ]
var behavior_series = [{
name: 'Behavior incidents',
data: [2, 1, 4, 1, 3]
},]
var mcas_series = [{
name: 'MCAS Math',
data: [65, 54, 31, 67, 43]
}, {
name: 'MCAS English',
data: [54, 32, 48, 83, 92]
}]
var star_series = [{
name: 'STAR Math',
data: [33, 39, 52, 67, 59, 29, 49, 29, 90]
}, {
name: 'STAR English',
data: [49, 29, 90, 83, 73, 59, 33, 39, 52]
}]
var options = {
chart: {
renderTo: 'chart',
type: 'column'
},
title: {
text: '',
style: {
display: 'none'
}
},
subtitle: {
text: '',
style: {
display: 'none'
}
},
legend: {
layout: 'horizontal',
align: 'right',
verticalAlign: 'top',
itemStyle: {
font: '12px "Open Sans", sans-serif !important;',
color: '#555555'
}
},
xAxis: {
categories: [
'Risk level 0',
'Risk level 1',
'Risk level 2',
'Risk level 3',
],
},
yAxis: {
title: {
text: '',
style: {
display: 'none'
}
},
plotLines: [
{
color: '#B90504',
width: 1,
zIndex: 3,
label: {
text: '',
align: 'center',
style: {
color: '#999999'
}
}
}
],
},
tooltip: {
shared: true
},
credits: {
enabled: false
},
plotOptions: {
areaspline: {
fillOpacity: 0
}
}
}
options.series = attendance_series
var chart = new Highcharts.Chart(options);
$("#chart-type").on('change', function(){
var selVal = $("#chart-type").val();
if(selVal == "attendance" || selVal == '') {
options.series = attendance_series
options.xAxis.categories = ["0", "1", "2", "3"]
}
else if(selVal == "behavior") {
options.series = behavior_series
options.xAxis.categories = ["2010 - 11", "2011 - 12", "2012 - 13", "2013 - 14", "2014 - 15"]
}
else if(selVal == "mcas-growth") {
options.series = mcas_series
options.yAxis.plotLines[0].label.text = "MCAS Growth warning: Less than 40 points"
options.yAxis.plotLines[0].value = "40"
options.xAxis.categories = ["2010 - 11", "2011 - 12", "2013 - 14", "2014 - 15"]
}
else {
options.series = star_series
options.yAxis.plotLines[0].label.text = "STAR Percentile warning: Less than 40 points"
options.yAxis.plotLines[0].value = "40"
options.xAxis.categories = ["Sept. 2010 - 11", "Jan. 2010 - 11", "May 2011 - 12", "Sept. 2011 - 12", "Jan. 2011 - 12", "May 2011 - 12", "Sept. 2012 - 13", "Jan. 2012 - 13", "May 2012 - 13", "Sept. 2013 - 14", "Jan. 2013 - 14", "May 2013 - 14"]
}
var chart = new Highcharts.Chart(options);
});
}
});
| JavaScript | 0.000001 | @@ -2942,18 +2942,18 @@
a: %5B
-5
+6, 2
, 2, 1
-, 4
%5D%0A
@@ -4179,17 +4179,49 @@
k level
-0
+3',%0A 'Risk level 2
',%0A
@@ -4279,41 +4279,9 @@
vel
-2',%0A 'Risk level 3
+0
',%0A
|
79583ad5f7caf7c3ff5bf69b89879893d2c7d86c | Remove commented code in movim_websocket | app/assets/js/movim_websocket.js | app/assets/js/movim_websocket.js | /**
* Movim Websocket
*
* This file define the websocket behaviour and handle its connection
*/
WebSocket.prototype.unregister = function() {
this.send(JSON.stringify({'func' : 'unregister'}));
};
WebSocket.prototype.register = function(host) {
this.send(JSON.stringify({'func' : 'register', 'host' : host}));
};
WebSocket.prototype.admin = function(key) {
this.send(JSON.stringify({'func' : 'admin', 'key' : key}));
};
/**
* @brief Definition of the MovimWebsocket object
* @param string error
*/
var MovimWebsocket = {
connection: null,
attached: new Array(),
registered: new Array(),
unregistered: false,
attempts: 1,
launchAttached : function() {
for(var i = 0; i < MovimWebsocket.attached.length; i++) {
MovimWebsocket.attached[i]();
}
},
launchRegistered : function() {
for(var i = 0; i < MovimWebsocket.registered.length; i++) {
MovimWebsocket.registered[i]();
}
},
init : function() {
if(SECURE_WEBSOCKET) {
var uri = 'wss://' + BASE_HOST + '/ws/';
} else {
var uri = 'ws://' + BASE_HOST + '/ws/';
}
this.connection = new WebSocket(uri);
this.connection.onopen = function(e) {
console.log("Connection established!");
MovimWebsocket.attempts = 1;
MovimWebsocket.launchAttached();
};
this.connection.onmessage = function(e) {
//console.log(e.data);
data = pako.ungzip(base64_decode(e.data), { to: 'string' });
//data = e.data;
var obj = JSON.parse(data);
if(obj != null) {
if(obj.func == 'registered') {
MovimWebsocket.launchRegistered();
}
if(obj.func == 'disconnected') {
movim_disconnect();
}
MovimWebsocket.handle(obj);
}
};
this.connection.onclose = function(e) {
console.log("Connection closed by the server or session closed");
if(e.code == 1006 || e.code == 1000) {
if(MovimWebsocket.unregistered == false) {
movim_disconnect();
} else {
MovimWebsocket.unregistered = false;
MovimWebsocket.init();
}
}
};
this.connection.onerror = function(e) {
console.log(e.code);
console.log(e);
console.log("Connection error!");
setTimeout(function () {
// We've tried to reconnect so increment the attempts by 1
MovimWebsocket.attempts++;
// Connection has closed so try to reconnect every 10 seconds.
MovimWebsocket.init();
}, MovimWebsocket.generateInterval());
// We prevent the onclose launch
this.onclose = null;
};
},
send : function(widget, func, params) {
if(this.connection.readyState == 1) {
this.connection.send(
JSON.stringify(
{'func' : 'message', 'body' :
{
'widget' : widget,
'func' : func,
'params' : params
}
}
)
);
}
},
attach : function(func) {
if(typeof(func) === "function") {
this.attached.push(func);
}
},
register : function(func) {
if(typeof(func) === "function") {
this.registered.push(func);
}
},
clearAttached : function() {
this.attached = new Array();
},
handle : function(funcalls) {
//var funcalls = JSON.parse(json);
if(funcalls != null) {
for(h = 0; h < funcalls.length; h++) {
var funcall = funcalls[h];
//console.log(funcall);
if(funcall.func != null && (typeof window[funcall.func] == 'function')) {
try {
window[funcall.func].apply(null, funcall.params);
} catch(err) {
console.log("Error caught: " + err.toString() + " - " + funcall.func + ":" + JSON.stringify(funcall.params));
}
} else if(funcall.func != null) {
var funcs = funcall.func.split('.');
var called = funcs[0];
if(typeof window[called] == 'object') {
window[funcs[0]][funcs[1]].apply(null, funcall.params);
}
}
}
}
},
unregister : function(reload) {
if(reload == false) this.unregistered = true;
this.connection.unregister();
},
generateInterval :function() {
var maxInterval = (Math.pow(2, MovimWebsocket.attempts) - 1) * 1000;
if (maxInterval > 30*1000) {
maxInterval = 30*1000; // If the generated interval is more than 30 seconds, truncate it down to 30 seconds.
}
// generate the interval to a random number between 0 and the maxInterval determined from above
return Math.random() * maxInterval;
}
}
function remoteUnregister()
{
MovimWebsocket.unregister(false);
}
function remoteUnregisterReload()
{
MovimWebsocket.unregister(true);
}
document.addEventListener("visibilitychange", function () {
if(!document.hidden) {
if(MovimWebsocket.connection.readyState == 3) {
MovimWebsocket.init();
}
}
});
window.onbeforeunload = function() {
MovimWebsocket.connection.onclose = function () {}; // disable onclose handler first
MovimWebsocket.connection.close()
};
movim_add_onload(function() {
// And we start it
MovimWebsocket.init();
});
| JavaScript | 0.000001 | @@ -1471,43 +1471,8 @@
) %7B%0A
- //console.log(e.data);%0A
@@ -1543,37 +1543,8 @@
%7D);
-%0A //data = e.data;
%0A%0A
@@ -3779,51 +3779,8 @@
) %7B%0A
- //var funcalls = JSON.parse(json);%0A
@@ -3904,48 +3904,8 @@
h%5D;%0A
- //console.log(funcall);%0A
|
abe2429fe747222333d28c67613f1bc50b17d4d1 | make gravatars secure | app/components/gravatar-image.js | app/components/gravatar-image.js | import Ember from "ember";
/**
* Helper to make a gravatar from a md5 email hash
* Hash must be pre-generated
*/
export default Ember.Component.extend({
tagName: '',
hash: '',
size: 200,
gravatarUrl: function(){
var hash = this.get('hash');
var size = this.get('size');
return "http://www.gravatar.com/avatar/"+hash+".jpg?d=mm&r=pg&s="+size;
}.property('email', 'size')
}); | JavaScript | 0 | @@ -318,16 +318,17 @@
rn %22http
+s
://www.g
|
6c4dda6d66ee6ae23a1283e0e33eac3a441e8006 | Add missing require main file for view. | app/dashboard/static/js/build.js | app/dashboard/static/js/build.js | ({
appDir: '../',
baseUrl: 'js',
dir: '/tmp/assets-build',
allowSourceOverwrites: true,
paths: {
'lib': './lib',
'app': './app',
'charts': './app/charts',
'utils': './app/utils',
'jquery': 'lib/jquery-2.1.4',
'bootstrap': 'lib/bootstrap-3.3.5',
'sprintf': 'lib/sprintf-1.0.1',
'd3': 'lib/d3-3.5.5',
'datatables': 'lib/dataTables-1.10.7',
'datatables.bootstrap': 'lib/dataTables.bootstrap-1.10.7',
'jquery.hotkeys': 'empty:',
'jquery.hotkeymap': 'empty:'
},
map: {
'*': {
'app/view-boots-all': 'app/view-boots-all.20150701',
'app/view-boots-all-job': 'app/view-boots-all-job.20150701',
'app/view-boots-all-job-kernel-defconfig': 'app/view-boots-all-job-kernel-defconfig.20150625',
'app/view-boots-all-lab': 'app/view-boots-all-lab.20150701',
'app/view-boots-board': 'app/view-boots-board.20150702',
'app/view-boots-board-job': 'app/view-boots-board-job.20150625',
'app/view-boots-board-job-kernel': 'app/view-boots-board-job-kernel.20150626',
'app/view-boots-board-job-kernel-defconfig': 'app/view-boots-board-job-kernel-defconfig.20150701',
'app/view-boots-id': 'app/view-boots-id.20150702',
'app/view-boots-job-kernel': 'app/view-boots-job-kernel.20150703',
'app/view-builds-all': 'app/view-builds-all.20150626',
'app/view-builds-job-kernel': 'app/view-builds-job-kernel.20150703',
'app/view-builds-job-kernel-defconfig': 'app/view-builds-job-kernel-defconfig.20150703',
'app/view-index': 'app/view-index.20150701',
'app/view-info-faq': 'app/view-info-faq.20150702',
'app/view-jobs-all': 'app/view-jobs-all.20150701',
'app/view-jobs-job': 'app/view-jobs-job.20150703',
'app/view-jobs-job-branch': 'app/view-jobs-job-branch.20150702',
'charts/passpie': 'charts/passpie.20150626',
'utils/base': 'utils/base.20150623',
'utils/bisect': 'utils/bisect.20150703',
'utils/git-rules': 'utils/git-rules.20150702',
'utils/init': 'utils/init.20150701',
'utils/request': 'utils/request.20150630',
'utils/show-hide-btns': 'utils/show-hide-btns.20150626',
'utils/tables': 'utils/tables.20150702',
'utils/urls': 'utils/urls.20150703',
'utils/web-storage': 'utils/web-storage.20150702'
}
},
shim: {
'bootstrap': {
deps: ['jquery']
},
'datatables.bootstrap': {
deps: ['datatables']
},
'jquery.hotkeys': {
deps: ['jquery'],
exports: 'jQuery'
},
'jquery.hotkeymap': {
deps: ['jquery.hotkeys']
}
},
modules: [
{name: 'app/view-boots-all-job-kernel-defconfig.20150625'},
{name: 'app/view-boots-all-job.20150701'},
{name: 'app/view-boots-all-lab.20150701'},
{name: 'app/view-boots-all.20150701'},
{name: 'app/view-boots-board-job-kernel-defconfig.20150701'},
{name: 'app/view-boots-board-job-kernel.20150626'},
{name: 'app/view-boots-board-job.20150625'},
{name: 'app/view-boots-board.20150702'},
{name: 'app/view-boots-id.20150702'},
{name: 'app/view-boots-job-kernel.20150703'},
{name: 'app/view-builds-all.20150626'},
{name: 'app/view-builds-job-kernel-defconfig.20150703'},
{name: 'app/view-builds-job-kernel.20150703'},
{name: 'app/view-index.20150701'},
{name: 'app/view-info-faq.20150702'},
{name: 'app/view-jobs-all.20150701'},
{name: 'app/view-jobs-job-branch.20150702'},
{name: 'app/view-jobs-job.20150703'},
{name: 'kci-boots-all'},
{name: 'kci-boots-all-job'},
{name: 'kci-boots-all-job-kernel-defconfig'},
{name: 'kci-boots-all-lab'},
{name: 'kci-boots-board'},
{name: 'kci-boots-board-job'},
{name: 'kci-boots-board-job-kernel'},
{name: 'kci-boots-board-job-kernel-defconfig'},
{name: 'kci-boots-id'},
{name: 'kci-boots-job-kernel'},
{name: 'kci-builds-all'},
{name: 'kci-builds-job-kernel'},
{name: 'kci-builds-job-kernel-defconfig'},
{name: 'kci-index'},
{name: 'kci-info-faq'},
{name: 'kci-jobs-all'},
{name: 'kci-jobs-job'}
]
})
| JavaScript | 0 | @@ -4508,16 +4508,55 @@
bs-job'%7D
+,%0A %7Bname: 'kci-jobs-job-branch'%7D
%0A %5D%0A%7D
|
bf193ef29b45a59be3ebb69b16a194f420f2d7b9 | Set workshops, IT seats based on variant | amy/static/membership_create.js | amy/static/membership_create.js | jQuery(function() {
$('#id_main_organization').on('change.select2', (e) => {
// additional data is sent from the backend and it's stored in
// select2 `data` parameter
const fullname = $(e.target).select2("data")[0].fullname;
const id_name = $("#id_name");
// only write the new name if "name" field is empty
if (!!fullname && !!id_name && !id_name.val()) {
id_name.val(fullname);
}
});
});
| JavaScript | 0 | @@ -456,13 +456,860 @@
%0A %7D);
+%0A%0A $('#id_variant').on('change', (e) =%3E %7B%0A const parameters = %7B%0A bronze: %7B%0A it_seats_public: 0,%0A workshops: 2%0A %7D,%0A silver: %7B%0A it_seats_public: 6,%0A workshops: 4%0A %7D,%0A gold: %7B%0A it_seats_public: 15,%0A workshops: 6%0A %7D%0A %7D;%0A%0A const publicInstructorTrainingSeats = $(%22#id_public_instructor_training_seats%22);%0A const workshopsWithoutAdminFee = $(%22#id_workshops_without_admin_fee_per_agreement%22);%0A%0A if (e.target.value in parameters) %7B%0A // set values from parameters%0A publicInstructorTrainingSeats.val(parameters%5Be.target.value%5D.it_seats_public);%0A workshopsWithoutAdminFee.val(parameters%5Be.target.value%5D.workshops);%0A %7D%0A %7D);
%0A%7D);%0A
|
c30cef74bef57697d8f1418164c178acb25393cc | fix IE 6 nifty arguments JS error | WebRoot/js/lib/niftyLayout.js | WebRoot/js/lib/niftyLayout.js | /*nifty corners layout*/
window.onload=function(){
Nifty("div#menu a","small transparent top");
Nifty("ul#intro li","same-height");
Nifty("div.date");
Nifty("div#content,div#side","same-height");
Nifty("div.comments div");
Nifty("div#footer");
Nifty("div#container","bottom");
} | JavaScript | 0 | @@ -23,18 +23,14 @@
*/%0A%0A
-window.onl
+NiftyL
oad=
@@ -41,16 +41,23 @@
tion()%7B%0A
+try%09%7B%0A%09
Nifty(%22d
@@ -89,24 +89,25 @@
rent top%22);%0A
+%09
Nifty(%22ul#in
@@ -122,32 +122,35 @@
%22same-height%22);%0A
+%09%0A%09
Nifty(%22div.date%22
@@ -148,24 +148,28 @@
div.date%22);%0A
+%0A//%09
Nifty(%22div#c
@@ -197,24 +197,98 @@
e-height%22);%0A
+%09Nifty(%22div#content%22, %22same-height%22);%0A%09Nifty(%22div#side%22, %22same-height%22);%0A%09
Nifty(%22div.c
@@ -298,24 +298,25 @@
ents div%22);%0A
+%09
Nifty(%22div#f
@@ -324,16 +324,17 @@
oter%22);%0A
+%09
Nifty(%22d
@@ -358,9 +358,52 @@
ttom%22);%0A
+%09%7D%0Acatch(er)%09%7B%0A//%09debug(er.description);%0A%7D%0A
%7D
|
aa624267087de9a87889cdf6ee49517fc04e4a24 | Fix maximum length for messages | app/js/arethusa.core/notifier.js | app/js/arethusa.core/notifier.js | 'use strict';
angular.module('arethusa.core').service('notifier', function () {
var self = this;
this.messages = [];
function Message(type, message, description) {
this.type = type;
this.message = message;
this.description = description;
}
this.success = function (message) {
self.messages.unshift({
type: 'success',
message: message
});
};
this.error = function (message) {
self.messages.unshift({
type: 'error',
message: message
});
};
this.lastMessage = function () {
return self.messages[0];
};
this.oldMessages = function () {
return self.messages.slice(1);
};
});
| JavaScript | 0.999831 | @@ -306,39 +306,19 @@
elf.
-m
+addM
essage
-s.unshift(%7B%0A type:
+(
'suc
@@ -323,30 +323,24 @@
uccess',
-%0A
message
: messag
@@ -327,39 +327,24 @@
ss', message
-: message%0A %7D
);%0A %7D;%0A th
@@ -388,47 +388,27 @@
elf.
-m
+addM
essage
-s.unshift(%7B%0A type:
+(
'error',
%0A
@@ -407,22 +407,16 @@
or',
-%0A
message
: me
@@ -415,31 +415,16 @@
sage
-: message%0A %7D
);%0A %7D;%0A
th
@@ -415,24 +415,25 @@
sage);%0A %7D;%0A
+%0A
this.lastM
@@ -564,12 +564,249 @@
);%0A %7D;%0A
+%0A%0A this.addMessage = function(type, message) %7B%0A if (self.messages.length === 15) %7B%0A self.messages.pop();%0A %7D%0A self.messages.unshift(new Message(type, message));%0A %7D;%0A this.reset = function() %7B%0A self.messages = %5B%5D;%0A %7D;%0A
%7D);%0A
|
2ec2139777e67694f911364278a2d6bb5c833c44 | fix double touch on mobile | app/js/src/screens/MainScreen.js | app/js/src/screens/MainScreen.js | import screensManager from '../managers/screensManager';
import dataManager from '../managers/dataManager';
import Background from '../display/Background';
import Hero from '../display/Hero';
import Spike from '../display/Spike';
import ShadowOverlay from '../display/ShadowOverlay';
const GROUND_HEIGHT = 82;
export default class MainScreen extends createjs.Container {
constructor(width, height) {
super();
this.width = width;
this.height = height;
this.speed = 290;
this.distance = 0;
this.shadowOverlay = new ShadowOverlay(this.width, this.height);
this.createBg();
this.createSpikes();
this.createHero();
this.createHud();
this.pause('Пробел - взмах крыльями, esc - пауза');
this.bindEvents();
}
createBg() {
this.bgSky = new Background('sky', this.width);
this.bgMountain = new Background('mountain', this.width);
this.bgGround = new Background('ground', this.width);
this.bgSky.y = this.bgMountain.y = this.bgGround.y = this.height;
this.addChild(this.bgSky, this.bgMountain, this.bgGround);
}
createSpikes() {
this.spikes = [new Spike(), new Spike()];
this.spikes[0].x = -this.spikes[0].bounds.width / 2;
this.spikes[1].x = this.width / 2;
this.spikes.forEach(spike => this.resetSpike(spike));
this.addChild(...this.spikes);
}
createHero() {
this.hero = new Hero(dataManager.heroType);
this.hero.x = this.width / 2;
this.hero.y = 190;
this.addChild(this.hero);
}
createHud() {
this.hudDistance = new createjs.Text('0 м', '25px Guerilla', '#000');
this.hudDistance.x = 20;
this.hudDistance.y = 15;
this.addChild(this.hudDistance);
}
resetSpike(spike) {
spike.reset();
spike.x += this.width + spike.bounds.width;
if (Math.random() > 0.5) {
spike.y = this.height - GROUND_HEIGHT;
spike.rotation = 0;
} else {
spike.y = 0;
spike.rotation = 180;
}
}
pause(text) {
this.paused = true;
this.shadowOverlay.setText(text);
this.addChild(this.shadowOverlay);
}
bindEvents() {
this.addEventListener('click', () => this.handleAction());
this.onKeyDown = e => {
switch (e.keyCode) {
case 32:
this.handleAction();
e.preventDefault();
break;
case 27:
this.togglePause();
break;
}
};
this.onTouchStart = e => {
e.preventDefault();
this.handleAction();
};
window.addEventListener('keydown', this.onKeyDown);
window.addEventListener('touchstart', this.onTouchStart);
}
handleAction() {
if (this.paused) {
this.togglePause();
} else {
this.hero.flap();
}
}
togglePause() {
if (this.paused) {
this.paused = false;
this.removeChild(this.shadowOverlay);
} else {
this.pause('Нажмите пробел или esc');
}
}
moveWorld(time) {
const path = this.speed * time;
if (this.hero.dead) {
this.hero.x += path * 0.5;
} else {
this.moveSpikes(path);
this.bgSky.move(path * 0.1);
this.bgMountain.move(path * 0.3);
this.bgGround.move(path);
this.distance += path;
dataManager.score = Math.floor(this.distance / 25);
this.hudDistance.text = `${dataManager.score} м`;
}
}
moveSpikes(path) {
this.spikes.forEach(spike => {
spike.x -= path;
if (spike.x < -spike.bounds.width / 2) {
this.resetSpike(spike);
this.speed += 1;
}
if (ndgmr.checkPixelCollision(this.hero, spike)) {
this.hero.die();
}
});
}
moveHero(time) {
this.hero.move(time);
if (this.hero.y < 0) {
this.hero.vY = 0;
this.hero.y = 0;
} else if (this.hero.y > this.height + this.hero.bounds.height / 2) {
screensManager.change('EndScreen');
} else if (this.hero.y > this.height - (GROUND_HEIGHT + this.hero.bounds.height / 2)) {
this.hero.die();
}
}
tick(e) {
const sec = e.delta * 0.001;
if (this.paused || sec > 0.3) {
return;
}
this.moveWorld(sec);
this.moveHero(sec);
}
destroy() {
window.removeEventListener('keydown', this.onKeyDown);
window.removeEventListener('touchstart', this.onTouchStart);
}
}
| JavaScript | 0 | @@ -2374,215 +2374,62 @@
%7D;%0A
- this.onTouchStart = e =%3E %7B%0A e.preventDefault();%0A this.handleAction();%0A %7D;%0A%0A window.addEventListener('keydown', this.onKeyDown);%0A window.addEventListener('touchstart', this.onTouchStart
+%0A window.addEventListener('keydown', this.onKeyDown
);%0A
@@ -4027,73 +4027,8 @@
n);%0A
- window.removeEventListener('touchstart', this.onTouchStart);%0A
%7D%0A
|
61003a945be6696baccd403a14f7dba4242bbc57 | Load carto lib for torque | app/assets/javascripts/table.js | app/assets/javascripts/table.js | //= require codemirror
//= require show-hint
//= require anyword-hint
//= require custom-list-hint
//= require select2.min
//= require jquery.faviconNotify
//= require rgbcolor
//= require crossfilter
//= require_tree ../../../vendor/assets/javascripts/jquery-ui
//= require jquery.caret
//= require ZeroClipboard
//= require tag-it
//= require jquery.tipsy
//= require d3.v2
//= require jquery.fileupload
//= require jquery.fileupload-fp
//= require jquery.fileupload-ui
//= require leaflet.draw
//= require moment
//= require carto
//= require moment
//= require ../../../lib/assets/javascripts/utils/postgres.codemirror
//= require ../../../lib/assets/javascripts/utils/carto.codemirror
//= require models
//= require ../../../lib/assets/javascripts/cartodb/common/dropdown_menu
//= require ../../../lib/assets/javascripts/cartodb/common/forms/string_field
//= require ../../../lib/assets/javascripts/cartodb/common/forms/widgets
//= require ../../../lib/assets/javascripts/cartodb/common/import/import_pane.js
//= require ../../../lib/assets/javascripts/cartodb/common/import/import_info/import_info.js
//= require_tree ../../../lib/assets/javascripts/cartodb/common
//= require ../../../lib/assets/javascripts/cartodb/table/right_menu
//= require ../../../lib/assets/javascripts/cartodb/table/menu_module
//= require ../../../lib/assets/javascripts/cartodb/table/menu_modules/carto_editor
//= require ../../../lib/assets/javascripts/cartodb/table/menu_modules/carto_wizard
//= require ../../../lib/assets/javascripts/cartodb/table/menu_modules/wizards/color_wizard
//= require_tree ../../../lib/assets/javascripts/cartodb/table
//= require ../../../lib/assets/javascripts/cartodb/table/table
//= require_tree ../../../lib/assets/javascripts/cartodb/table/views
//= require_tree ../../../lib/assets/javascripts/cartodb/dashboard/views | JavaScript | 0 | @@ -521,16 +521,31 @@
require
+cdb/vendor/mod/
carto%0A//
@@ -1844,12 +1844,13 @@
hboard/views
+%0A
|
e3c651004fa6d96d8cb0e9c811acbafb57d4135e | Remove useless button value change in users/form | app/assets/javascripts/users.js | app/assets/javascripts/users.js | //generate token button
$(function() {
$("#generate-token").live("click", function(e) {
$(this).html("Génération...");
$(this).disabled = true;
$.ajax({
type: "GET",
url: "/users/random_token",
//data: $(this).val(),
//dataType: "script",
callback: null
});
$(this).html("Générer");
return false;
});
$("#remove-token").live("click", function(e) {
$("#authentication_token").html("");
$("#user_authentication_token").attr("value", "");
$("#remove-token").hide();
$("#generate-token").show();
return false;
});
});
| JavaScript | 0.000001 | @@ -87,43 +87,8 @@
) %7B%0A
- $(this).html(%22G%C3%A9n%C3%A9ration...%22);%0A
@@ -268,37 +268,8 @@
%7D);%0A
- $(this).html(%22G%C3%A9n%C3%A9rer%22);%0A
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.