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
|
---|---|---|---|---|---|---|---|
f108c39c9399cd9c97da0228b1085bc202ffd72e | Handle catch before then | node_modules/gh-core/lib/globals/sequelize.js | node_modules/gh-core/lib/globals/sequelize.js | /**
* Copyright (c) 2015 "Fronteer LTD"
* Grasshopper Event Engine
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
var Promise = require('sequelize/lib/promise');
/**
* Add a style helper to the sequelize Promise that allows us to use callback-style error handling
*
* @param {Function} callback Standard callback function
* @param {Object} callback.err An error that occurred, if any
* @param {Args} callback.arg0 A variable number of callback-specific return arguments
*/
Promise.prototype.complete = function(callback) {
this
// Success condition
.then(function() {
// Shift a null value as the first parameter in the callback to indicate the result is
// a success
var args = Array.prototype.slice.call(arguments);
args.unshift(null);
return callback.apply(null, args);
})
// Failure condition
.catch(function(err) {
// Send the err argument to the consumer as the first and only parameter
callback.call(null, err);
});
};
| JavaScript | 0 | @@ -786,20 +786,476 @@
ise');%0A%0A
+/*!%0A * If an unhandled error is thrown inside the promise, we should promote it. This is needed because%0A * if an unhandled exception occurs in the %60callback%60 during the %60then%60 handler it is considered a%0A * rejection. Since we want things like unit tests to catch these in the test domain, or express to%0A * catch exceptions in the error handling middlewhere, we will promote them%0A */%0APromise.onPossiblyUnhandledRejection(function(err) %7B%0A throw err;%0A%7D);%0A%0A
/**%0A
-
* Add a
@@ -1645,16 +1645,407 @@
this%0A
+%0A // Failure condition. This must be registered before the %60then%60 condition to ensure that an%0A // error in the callback does not get caught by this handler, risking that the callback be%0A // invoked twice%0A .catch(function(err) %7B%0A // Send the err argument to the consumer as the first and only parameter%0A callback.call(null, err);%0A %7D)%0A%0A
@@ -2322,23 +2322,16 @@
-return
callback
@@ -2354,203 +2354,8 @@
s);%0A
- %7D)%0A%0A // Failure condition%0A .catch(function(err) %7B%0A // Send the err argument to the consumer as the first and only parameter%0A callback.call(null, err);%0A
|
c33db62c36243c90fa669fb5a93ac6efc6bfbff5 | Fix broken tests (since I made error toasts sticky) | omod/src/test/webapp/resources/scripts/emr.js | omod/src/test/webapp/resources/scripts/emr.js |
var window;
window.messages = {};
describe("Tests of emr functions", function() {
it("should display success message", function() {
var jqueryWithSpy = jq();
emr.setJqObject(jqueryWithSpy);
spyOn(jqueryWithSpy,'toastmessage').andCallThrough(); // call through just to make sure the underlying plugin doesn't throw an error
emr.successMessage("some success message");
expect(jqueryWithSpy.toastmessage).toHaveBeenCalledWith('showToast', { type : 'success', position : 'top-right', text : 'some success message' });
});
it("should display error message", function() {
var jqueryWithSpy = jq();
emr.setJqObject(jqueryWithSpy);
spyOn(jqueryWithSpy,'toastmessage').andCallThrough(); // call through just to make sure the underlying plugin doesn't throw an error
emr.errorMessage("some error message");
expect(jqueryWithSpy.toastmessage).toHaveBeenCalledWith('showToast', { type : 'error', position : 'top-right', text : 'some error message' });
});
it("should display success alert", function() {
var jqueryWithSpy = jq();
emr.setJqObject(jqueryWithSpy);
spyOn(jqueryWithSpy,'toastmessage').andCallThrough(); // call through just to make sure the underlying plugin doesn't throw an error
emr.successAlert("some success message");
expect(jqueryWithSpy.toastmessage).toHaveBeenCalledWith('showToast', { type : 'success', position : 'top-right', text : 'some success message', stayTime: 8000, close: null });
});
it("should display error alert", function() {
var jqueryWithSpy = jq();
emr.setJqObject(jqueryWithSpy);
spyOn(jqueryWithSpy,'toastmessage').andCallThrough(); // call through just to make sure the underlying plugin doesn't throw an error
emr.errorAlert("some error message");
expect(jqueryWithSpy.toastmessage).toHaveBeenCalledWith('showToast', { type : 'error', position : 'top-right', text : 'some error message', stayTime: 8000, close: null });
});
it("should translate success message", function() {
window.messages['success.message.code'] = 'some success message';
var jqueryWithSpy = jq();
emr.setJqObject(jqueryWithSpy);
spyOn(jqueryWithSpy,'toastmessage').andCallThrough(); // call through just to make sure the underlying plugin doesn't throw an error
emr.successMessage("success.message.code");
expect(jqueryWithSpy.toastmessage).toHaveBeenCalledWith('showToast', { type : 'success', position : 'top-right', text : 'some success message' });
});
it("should translate error message", function() {
window.messages['error.message.code'] = 'some error message';
var jqueryWithSpy = jq();
emr.setJqObject(jqueryWithSpy);
spyOn(jqueryWithSpy,'toastmessage').andCallThrough(); // call through just to make sure the underlying plugin doesn't throw an error
emr.errorMessage("error.message.code");
expect(jqueryWithSpy.toastmessage).toHaveBeenCalledWith('showToast', { type : 'error', position : 'top-right', text : 'some error message' });
});
it("should translate alert message", function() {
window.messages['alert.message.code'] = 'some alert message';
var jqueryWithSpy = jq();
emr.setJqObject(jqueryWithSpy);
spyOn(jqueryWithSpy,'toastmessage').andCallThrough(); // call through just to make sure the underlying plugin doesn't throw an error
emr.alertMessage("alert.message.code");
expect(jqueryWithSpy.toastmessage).toHaveBeenCalledWith('showToast', { type : 'alert', position : 'top-right', text : 'some alert message' });
});
it("should translate success alert", function() {
window.messages['success.message.code'] = 'some success message';
var jqueryWithSpy = jq();
emr.setJqObject(jqueryWithSpy);
spyOn(jqueryWithSpy,'toastmessage').andCallThrough(); // call through just to make sure the underlying plugin doesn't throw an error
emr.successAlert("success.message.code");
expect(jqueryWithSpy.toastmessage).toHaveBeenCalledWith('showToast', { type : 'success', position : 'top-right', text : 'some success message', stayTime: 8000, close: null });
});
it("should translate error alert", function() {
window.messages['error.message.code'] = 'some error message';
var jqueryWithSpy = jq();
emr.setJqObject(jqueryWithSpy);
spyOn(jqueryWithSpy,'toastmessage').andCallThrough(); // call through just to make sure the underlying plugin doesn't throw an error
emr.errorAlert("error.message.code");
expect(jqueryWithSpy.toastmessage).toHaveBeenCalledWith('showToast', { type : 'error', position : 'top-right', text : 'some error message', stayTime: 8000, close: null });
});
it("should say a more precise session locale is compatible", function() {
window.sessionContext = { locale: 'en_GB' };
expect(emr.isCompatibleWithSessionLocale('en')).toBe(true);
});
it("should say a less precise session locale is compatible", function() {
window.sessionContext = { locale: 'en' };
expect(emr.isCompatibleWithSessionLocale('en_GB')).toBe(true);
});
it("should say a different session locale is compatible", function() {
window.sessionContext = { locale: 'en_US' };
expect(emr.isCompatibleWithSessionLocale('en_GB')).toBe(false);
});
it("should say a completely different session locale is not compatible", function() {
window.sessionContext = { locale: 'en_GB' };
expect(emr.isCompatibleWithSessionLocale('fr')).toBe(false);
});
}) | JavaScript | 0 | @@ -999,32 +999,46 @@
n : 'top-right',
+ sticky: true,
text : 'some er
@@ -3157,32 +3157,46 @@
n : 'top-right',
+ sticky: true,
text : 'some er
|
109e73553e6a9a42296398caff3ed0682c087cf2 | return width and height in bounding box | packages/d3fc-label-layout/src/boundingBox.js | packages/d3fc-label-layout/src/boundingBox.js | export default () => {
var bounds = [0, 0];
var strategy = (data) => data.map((d, i) => {
var tx = d.x;
var ty = d.y;
if (tx + d.width > bounds[0]) {
tx -= d.width;
}
if (ty + d.height > bounds[1]) {
ty -= d.height;
}
return {x: tx, y: ty};
});
strategy.bounds = function(value) {
if (!arguments.length) {
return bounds;
}
bounds = value;
return strategy;
};
return strategy;
};
| JavaScript | 0.000037 | @@ -310,16 +310,50 @@
return %7B
+height: d.height, width: d.width,
x: tx, y
|
f3b4cf64865f772af1892a2a5761f488f683bec8 | Increase network timeout connection for Yarn users | packages/generators/app/lib/create-project.js | packages/generators/app/lib/create-project.js | 'use strict';
// FIXME
/* eslint-disable import/extensions */
const { join } = require('path');
const fse = require('fs-extra');
const chalk = require('chalk');
const execa = require('execa');
const ora = require('ora');
const _ = require('lodash');
const stopProcess = require('./utils/stop-process');
const { trackUsage, captureStderr } = require('./utils/usage');
const mergeTemplate = require('./utils/merge-template.js');
const packageJSON = require('./resources/json/package.json');
const createDatabaseConfig = require('./resources/templates/database.js');
const createAdminConfig = require('./resources/templates/admin-config.js');
const createEnvFile = require('./resources/templates/env.js');
module.exports = async function createProject(scope, { client, connection, dependencies }) {
console.log(`Creating a new Strapi application at ${chalk.green(scope.rootPath)}.`);
console.log('Creating files.');
const { rootPath } = scope;
const resources = join(__dirname, 'resources');
try {
// copy files
await fse.copy(join(resources, 'files'), rootPath);
// copy dot files
await fse.writeFile(join(rootPath, '.env'), createEnvFile());
const dotFiles = await fse.readdir(join(resources, 'dot-files'));
await Promise.all(
dotFiles.map(name => {
return fse.copy(join(resources, 'dot-files', name), join(rootPath, `.${name}`));
})
);
await trackUsage({ event: 'didCopyProjectFiles', scope });
// copy templates
await fse.writeJSON(
join(rootPath, 'package.json'),
packageJSON({
strapiDependencies: scope.strapiDependencies,
additionalsDependencies: dependencies,
strapiVersion: scope.strapiVersion,
projectName: _.kebabCase(scope.name),
uuid: scope.uuid,
packageJsonStrapi: scope.packageJsonStrapi,
}),
{
spaces: 2,
}
);
await trackUsage({ event: 'didWritePackageJSON', scope });
// ensure node_modules is created
await fse.ensureDir(join(rootPath, 'node_modules'));
// create config/database.js
await fse.writeFile(
join(rootPath, `config/database.js`),
createDatabaseConfig({
client,
connection,
})
);
// create config/server.js
await fse.writeFile(join(rootPath, `config/admin.js`), createAdminConfig());
await trackUsage({ event: 'didCopyConfigurationFiles', scope });
// merge template files if a template is specified
const hasTemplate = Boolean(scope.template);
if (hasTemplate) {
try {
await mergeTemplate(scope, rootPath);
} catch (error) {
throw new Error(`⛔️ Template installation failed: ${error.message}`);
}
}
} catch (err) {
await fse.remove(scope.rootPath);
throw err;
}
await trackUsage({ event: 'willInstallProjectDependencies', scope });
const installPrefix = chalk.yellow('Installing dependencies:');
const loader = ora(installPrefix).start();
const logInstall = (chunk = '') => {
loader.text = `${installPrefix} ${chunk
.toString()
.split('\n')
.join(' ')}`;
};
try {
if (scope.installDependencies !== false) {
const runner = runInstall(scope);
runner.stdout.on('data', logInstall);
runner.stderr.on('data', logInstall);
await runner;
}
loader.stop();
console.log(`Dependencies installed ${chalk.green('successfully')}.`);
await trackUsage({ event: 'didInstallProjectDependencies', scope });
} catch (error) {
loader.stop();
await trackUsage({
event: 'didNotInstallProjectDependencies',
scope,
error: error.stderr.slice(-1024),
});
console.error(`${chalk.red('Error')} while installing dependencies:`);
console.error(error.stderr);
await captureStderr('didNotInstallProjectDependencies', error);
console.log(chalk.black.bgWhite(' Keep trying! '));
console.log();
console.log(
chalk.bold(
'Oh, it seems that you encountered errors while installing dependencies in your project.'
)
);
console.log(`Don't give up, your project was created correctly.`);
console.log(
`Fix the issues mentioned in the installation errors and try to run the following command:`
);
console.log();
console.log(
`cd ${chalk.green(rootPath)} && ${chalk.cyan(scope.useYarn ? 'yarn' : 'npm')} install`
);
console.log();
stopProcess();
}
await trackUsage({ event: 'didCreateProject', scope });
console.log();
console.log(`Your application was created at ${chalk.green(rootPath)}.\n`);
const cmd = chalk.cyan(scope.useYarn ? 'yarn' : 'npm run');
console.log('Available commands in your project:');
console.log();
console.log(` ${cmd} develop`);
console.log(
' Start Strapi in watch mode. (Changes in Strapi project files will trigger a server restart)'
);
console.log();
console.log(` ${cmd} start`);
console.log(' Start Strapi without watch mode.');
console.log();
console.log(` ${cmd} build`);
console.log(' Build Strapi admin panel.');
console.log();
console.log(` ${cmd} strapi`);
console.log(` Display all available commands.`);
console.log();
console.log('You can start by doing:');
console.log();
console.log(` ${chalk.cyan('cd')} ${rootPath}`);
console.log(` ${cmd} develop`);
console.log();
};
const installArguments = ['install', '--production', '--no-optional'];
function runInstall({ rootPath, useYarn }) {
if (useYarn) {
return execa('yarnpkg', installArguments, {
cwd: rootPath,
stdin: 'ignore',
});
}
return execa('npm', installArguments, { cwd: rootPath, stdin: 'ignore' });
}
| JavaScript | 0 | @@ -5519,24 +5519,136 @@
(useYarn) %7B%0A
+ // Increase timeout for slow internet connections.%0A installArguments.push('--network-timeout 1000000');%0A%0A
return e
|
275c5a457b8fb89bf53c0a6b9d2241ba7ef8a513 | Allow <StaticRouter> to render <Route>s | packages/react-router/modules/StaticRouter.js | packages/react-router/modules/StaticRouter.js | import invariant from 'invariant'
import React, { PropTypes } from 'react'
import { createPath, parsePath } from 'history/PathUtils'
import Router from './Router'
const normalizeLocation = (object) => {
const { pathname = '/', search = '', hash = '' } = object
return {
pathname,
search: search === '?' ? '' : search,
hash: hash === '#' ? '' : hash
}
}
const createLocation = (location) =>
typeof location === 'string' ? parsePath(location) : normalizeLocation(location)
const createURL = (location) =>
typeof location === 'string' ? location : createPath(location)
const staticHandler = (methodName) => () => {
invariant(
false,
'You cannot %s with <StaticRouter>',
methodName
)
}
/**
* The public top-level API for a "static" <Router>, so-called because it
* can't actually change the current location. Instead, it just records
* location changes in a context object. Useful mainly in testing and
* server-rendering scenarios.
*/
class StaticRouter extends React.Component {
static propTypes = {
basename: PropTypes.string,
context: PropTypes.object.isRequired,
location: PropTypes.oneOfType([
PropTypes.string,
PropTypes.object
])
}
static defaultProps = {
basename: '',
location: '/'
}
createHref = (path) =>
this.props.basename + createURL(path)
handlePush = (location) => {
const { context } = this.props
context.action = 'PUSH'
context.location = createLocation(location)
context.url = createURL(location)
}
handleReplace = (location) => {
const { context } = this.props
context.action = 'REPLACE'
context.location = createLocation(location)
context.url = createURL(location)
}
render() {
const { context, location, ...props } = this.props // eslint-disable-line no-unused-vars
const history = {
isStatic: true,
createHref: this.createHref,
action: 'POP',
location: createLocation(location),
push: this.handlePush,
replace: this.handleReplace,
go: staticHandler('go'),
goBack: staticHandler('goBack'),
goForward: staticHandler('goForward'),
listen: staticHandler('listen')
}
return <Router {...props} history={history}/>
}
}
export default StaticRouter
| JavaScript | 0 | @@ -719,16 +719,39 @@
%0A )%0A%7D%0A%0A
+const noop = () =%3E %7B%7D%0A%0A
/**%0A * T
@@ -1745,16 +1745,49 @@
n)%0A %7D%0A%0A
+ handleListen = () =%3E%0A noop%0A%0A
render
@@ -2224,31 +2224,25 @@
en:
-staticH
+this.h
andle
-r('l
+L
isten
-')
%0A
|
51de94009604a64f855a161fd04359e093adf5ed | disable strict | actor-apps/app-web/webpack.config.js | actor-apps/app-web/webpack.config.js | import minimist from 'minimist';
import path from 'path';
import webpack from 'webpack';
const argv = minimist(process.argv.slice(2));
const DEBUG = !argv.release;
export default {
cache: DEBUG,
debug: DEBUG,
devtool: DEBUG ? 'inline-source-map' : 'source-map',
hotComponents: DEBUG,
entry: {
app: DEBUG ? [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/dev-server',
'./src/app/index.js'
] : ['./src/app/index.js'],
styles: DEBUG ? [
'webpack/hot/dev-server',
'./src/styles'
] : ['./src/styles']
},
output: {
path: path.join(__dirname, 'dist/assets'),
publicPath: 'assets/',
filename: '[name].js',
chunkFilename: '[chunkhash].js',
sourceMapFilename: '[name].map'
},
resolve: {
modulesDirectories: ['node_modules'],
root: [
path.join(__dirname, 'src/app')
]
},
module: {
preLoaders: [
{
test: /\.js$/,
loaders: ['eslint', 'source-map'],
exclude: /node_modules/
}
],
loaders: [
// Styles
{
test: /\.(scss|css)$/,
loaders: [
'react-hot',
'style',
'css',
'autoprefixer?browsers=last 3 versions',
'sass?outputStyle=expanded&indentedSyntax' +
'includePaths[]=' + (path.resolve(__dirname, './node_modules'))
]
},
// JavaScript
{
test: /\.js$/,
loaders: [
'react-hot',
'babel?optional[]=strict' +
'&optional[]=es7.classProperties' +
'&optional[]=es7.decorators'
],
exclude: /(node_modules)/
},{
test: /\.json$/,
loaders: ['json']
},
// Assets
{
test: /\.(png|mp3)$/,
loaders: ['file?name=[name].[ext]']
},
// Fonts
{
test: /\.(ttf|eot|svg|woff|woff2)$/,
loaders: ['file?name=fonts/[name].[ext]']
}
]
},
plugins: [
new webpack.ResolverPlugin([
new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin('package.json', ['main'])
]),
new webpack.optimize.DedupePlugin()
],
eslint: {
configFile: './.eslintrc'
}
};
| JavaScript | 0.000001 | @@ -1504,43 +1504,8 @@
l%5B%5D=
-strict' +%0A '&optional%5B%5D=
es7.
|
2131d47bd5accef8e7f59b49867cd23dc7c229aa | remove duplicate declaration | addon/components/bc-sortable-list.js | addon/components/bc-sortable-list.js | /**
* @module component
*
*/
import { camelize } from '@ember/string';
import EmberObject from '@ember/object';
import { A } from '@ember/array';
import { assert } from '@ember/debug';
import { isNone } from '@ember/utils';
import Component from '@ember/component';
import layout from '../templates/components/bc-sortable-list';
/**
* `BC/SortableList`
*
* @class
* Renders a sortable list view of model objects
*
*
* @extends Ember.Component
*/
export default Component.extend({
layout: layout,
classNames: ['bc-sortable-list'],
model: null,
reportData: null,
meta: null,
withChildren: false,
childrenArray: 'none',
init() {
this._super();
this.setMeta();
this.addSortClasses();
this.setReportData();
},
setMeta() {
const meta = this.get('meta');
const model = this.get('model');
if (isNone(meta)) {
if (isNone(model.get('meta'))) {
assert('meta data not present');
} else {
this.set('meta', model.get('meta'));
}
}
},
setReportData() {
let model = this.get('model');
const meta = this.get('meta');
let reportData = A([]);
const reportData = Ember.A([]);
model.forEach(item => {
let newModel = EmberObject.create({});
meta.forEach(metaItem => {
const header = metaItem.machineName || camelize(metaItem.header);
if (!isNone(item.get(header))) {
if (metaItem.isImage) {
newModel.set(header, {imageUrl: item.get(header), 'isImage': true});
} else {
newModel.set(header, item.get(header));
}
} else {
newModel.set(header, '-');
}
});
const newModel = this.createSortableObject(item);
reportData.push(newModel);
});
this.set('reportData', reportData);
},
createSortableObject(item, childArray) {
const newModel = Ember.Object.create({});
const meta = this.get('meta');
const childrenArray = childArray || this.get('childrenArray');
meta.forEach(metaItem => {
const header = metaItem.machineName || Ember.String.camelize(metaItem.header);
const machineHeader = header.replace('-', '.');
if (!Ember.isNone(item.get(machineHeader))) {
const newObject = Ember.Object.create({content: item.get(machineHeader)});
if (metaItem.isImage) {
newObject.set('isImage', true);
} if (metaItem.formatCurrency) {
newObject.set('formatCurrency', true);
} if (metaItem.formatTime) {
newObject.set('formatTime', true);
} if (this.get('withChildren') && !Ember.isNone(item.get(childrenArray))) {
const children = [];
item.get(childrenArray).forEach(child => {
const itemChild = this.createSortableObject(child)
children.push(itemChild);
});
item.set('children', children);
}
newModel.set(Ember.String.camelize(header), newObject);
// newModel.set(header + 'Sort', item.get(machineHeader));
} else {
newModel.set(Ember.String.camelize(header), '-');
}
});
return newModel;
},
addSortClasses() {
const headers = this.get('meta');
headers.forEach(item => {
if (item.sortable) {
item.set('notSorted', true);
item.set('desc', false);
item.set('asc', false);
}
});
},
actions: {
sortAction(item) {
const sortBy = item.machineName || camelize(item.header);
this.get('meta').forEach(header => {
if (header.get('header') !== item.get('header')) {
header.set('notSorted', true);
header.set('desc', false);
header.set('asc', false);
}
});
if (item.get('notSorted') || item.get('asc')) {
item.set('notSorted', false);
item.set('desc', true);
item.set('asc', false);
this.set('reportData', this.get('reportData').sortBy(sortBy));
} else if (item.get('desc')) {
item.set('notSorted', false);
item.set('desc', false);
item.set('asc', true);
this.set('reportData', this.get('reportData').sortBy(sortBy).reverse());
}
},
rowClickAction(item) {
this.sendAction('rowAction', item);
}
}
});
| JavaScript | 0.000003 | @@ -1061,35 +1061,8 @@
');%0A
-%09%09let reportData = A(%5B%5D);%0A%0A
%09%09co
|
cd57d7971068eccabe7bbd5eccbc54f16e538302 | Allow to override progress property of backdrop-content | addon/components/content-backdrop.js | addon/components/content-backdrop.js | import Ember from "ember";
const {
Component,
computed,
String: { htmlSafe },
computed: { alias },
inject: { service },
get,
} = Ember;
export default Component.extend({
sideMenu: service(),
progress: alias("sideMenu.progress"),
attributeBindings: ["style"],
classNames: ["content-backdrop"],
style: computed("progress", function () {
const progress = get(this, "progress");
const opacity = progress / 100;
const visibility = progress === 0 ? "hidden" : "visible";
let transition = "none";
if (progress === 100) {
transition = "opacity 0.2s ease-out";
} else if (progress === 0) {
transition = "visibility 0s linear 0.2s, opacity 0.2s ease-out";
}
return htmlSafe(
`opacity: ${opacity}; visibility: ${visibility}; transition: ${transition}`
);
}),
click() {
get(this, "sideMenu").close();
},
});
| JavaScript | 0 | @@ -100,21 +100,22 @@
uted: %7B
-alias
+oneWay
%7D,%0A
@@ -234,13 +234,14 @@
ss:
-alias
+oneWay
(%22si
|
c92996101dbc22011bd99670e5fbd1d88686c8e6 | Create attributes on load | addon/components/table-filterable.js | addon/components/table-filterable.js | import Ember from 'ember';
import layout from '../templates/components/table-filterable';
export default Ember.Component.extend({
layout,
store: Ember.inject.service(),
type: null,
page: 1,
per_page: 10,
direction: 'ASC',
onInit: Ember.on('init', function(){
this.send('createFilter');
}),
operators: ['=*'],
directions: ['ASC', 'DESC'],
filters: Ember.A([]),
attributes: Ember.computed('type', function(){
let attributes = [];
if(!Ember.isNone(this.get('type'))){
let model = this.get('store').modelFor(this.get('type'));
attributes = Ember.get(model, 'attributes');
}
return attributes;
}),
params: Ember.computed('filters.[]', 'page', 'per_page', 'direction', function(){
let params = {};
this.get('filters').forEach((filter) => {
params[filter.attribute] = `${filter.operator}${filter.value}`;
});
let self = this;
['page', 'per_page', 'direction'].forEach((p) => {
params[p] = self.get(p);
});
return params;
}),
records: Ember.computed('type', 'params.[]', function(){
return this.get('store').query(this.get('type'), this.get('params'));
}),
actions: {
createFilter(){
let filter = Ember.Object.create({
attribute: null, operator: null, value: null
});
this.set('filter', filter);
},
pushFilter(filter){
this.get('filters').pushObject(filter);
this.send('createFilter');
},
removeFilter(filter){
this.get('filters').removeObject(filter);
}
}
});
| JavaScript | 0.000001 | @@ -232,86 +232,8 @@
C',%0A
-%0A onInit: Ember.on('init', function()%7B%0A this.send('createFilter');%0A %7D),%0A%0A
op
@@ -280,17 +280,16 @@
DESC'%5D,%0A
-%0A
filter
@@ -304,17 +304,16 @@
.A(%5B%5D),%0A
-%0A
attrib
@@ -322,242 +322,105 @@
es:
-Ember.computed('type', function()%7B%0A let attributes = %5B%5D;%0A if(!Ember.isNone(this.get('type')))%7B%0A let model = this.get('store').modelFor(this.get('type
+%5B%5D,%0A%0A onInit: Ember.on('init', function()%7B%0A this.send('createFilter
')
-)
;%0A
- attributes = Ember.get(model, 'attributes');%0A %7D%0A return a
+this.send('createA
ttri
@@ -424,16 +424,18 @@
tributes
+')
;%0A %7D),%0A
@@ -435,16 +435,17 @@
%0A %7D),%0A%0A
+%0A
params
@@ -1123,24 +1123,368 @@
r);%0A %7D,%0A%0A
+ createAttributes()%7B%0A if(this.get('store') && Ember.isEmpty(this.get('attributes')))%7B%0A if(!Ember.isNone(this.get('type')))%7B%0A let model = this.get('store').modelFor(this.get('type'));%0A let attributes = Ember.get(model, 'attributes');%0A this.set('attributes', attributes);%0A %7D%0A %7D%0A %7D,%0A%0A
pushFilt
|
753ca6e2327c61cc28ee420a57fc9d7a4acd5466 | Add test cases for aliases | test/anye-test.js | test/anye-test.js | "use strict";
var Anye = require( "../lib/anye.js" );
module.exports = {
setUp: function( fDone ) {
Anye.clear();
fDone();
},
"Anye Tests": function( oTest ) {
// Setting
oTest.equal( Anye.set( "simple", "/url/" ), "/url/", "Anye.set should return the given URL." );
oTest.equal( Anye.set( "one-param", "/url/:id" ), "/url/:id", "Anye.set should return the given URL." );
// Counting
oTest.equal( Anye.length, 2, "Anye.length should be 2." );
Anye.set( "multi-params", "/url/:id/:module" );
oTest.equal( Anye.length, 3, "Anye.length should be 3." );
// Clearing
Anye.clear();
oTest.equal( Anye.length, 0, "Anye.length should be 0." );
Anye.set( "simple", "/url/" );
Anye.set( "one-param", "/url/:id" );
Anye.set( "multi-params", "/url/:id/:module" );
// Retrieving
oTest.throws( function() { Anye.get( "unknown" ); }, "Anye.get should throws when calling an url that is not in the store." );
oTest.equal( Anye.get( "simple" ), "/url/", "Anye.get should return the good url." );
oTest.throws( function() { Anye.get( "one-param" ); }, "Anye.get should throws when calling an url expecting with no params." );
oTest.throws( function() { Anye.get( "one-param", { foo: "bar" } ); }, "Anye.get should throws when calling an url expecting with not the attended params." );
oTest.equal( Anye.get( "one-param", { id: 2 } ), "/url/2", "Anye.get should return the good url, with the given params." );
oTest.equal( Anye.get( "one-param", { id: "bar" } ), "/url/bar", "Anye.get should return the good url, with the given params." );
oTest.throws( function() { Anye.get( "multi-params", { id: 2 } ); }, "Anye.get should throws when calling an url expecting with not the attended params." );
oTest.equal( Anye.get( "multi-params", { id: 2, module: "foo" } ), "/url/2/foo", "Anye.get should return the good url, with the given params." );
oTest.equal( Anye.get( "multi-params", { module: 2, id: "foo" } ), "/url/foo/2", "Anye.get should return the good url, with the given params." );
// URL Decoding
oTest.equal( Anye.get( "one-param", { id: "bar^" } ), "/url/bar%5E", "Anye.get should return the good url, with the given params, and URL-encoded by default." );
oTest.equal( Anye.get( "one-param", { id: "bar^" }, true ), "/url/bar^", "Anye.get should return the good url, with the given params, and URL-decoded." );
// Additional parameters
oTest.equal( Anye.get( "simple", { id: 2, foo: "bar" } ), "/url/?id=2&foo=bar", "Anye.get should return the good url and add additional params to the query string." );
oTest.equal( Anye.get( "one-param", { id: 2, foo: "bar" } ), "/url/2?foo=bar", "Anye.get should return the good url, with the given params, and add additional params to the query string." );
oTest.equal( Anye.get( "one-param", { id: 2, foo: "bar", bar: "baz" } ), "/url/2?foo=bar&bar=baz", "Anye.get should return the good url, with the given params, and add additional params to the query string." );
oTest.equal( Anye.get( "one-param", { id: 2, foo: "bar^", bar: "baz" }, true ), "/url/2?foo=bar^&bar=baz", "Anye.get should return the good url, with the given params, and add additional params to the query string, and URL-decoded." );
// Complex & nested additional parameters
oTest.equal( Anye.get( "one-param", { id: 2, foo: "bar", bar: [ 1, 2, 3 ] } ), "/url/2?foo=bar&bar%5B0%5D=1&bar%5B1%5D=2&bar%5B2%5D=3", "Anye.get should return the good url, with the given params, and add additional params to the query string, event the complex ones, like Arrays." );
oTest.equal( Anye.get( "one-param", { id: 2, foo: "bar", bar: { baz: "bar", zab: "baz" } } ), "/url/2?foo=bar&bar%5Bbaz%5D=bar&bar%5Bzab%5D=baz", "Anye.get should return the good url, with the given params, and add additional params to the query string, event the complex ones, like Objects." );
oTest.equal( Anye.get( "one-param", { id: 2, foo: "bar", bar: { baz: "bar", zab: "baz" } }, true ), "/url/2?foo=bar&bar[baz]=bar&bar[zab]=baz", "Anye.get should return the good url, with the given params, and add additional params to the query string, event the complex ones, like Objects, and URL-decoded." );
oTest.done();
}
};
| JavaScript | 0.000001 | @@ -4386,32 +4386,376 @@
L-decoded.%22 );%0A%0A
+ // Aliases%0A oTest.equal( Anye.store( %22simple%22, %22/url/%22 ), %22/url/%22, %22Anye.store() should behave like Anye.set().%22 );%0A oTest.equal( Anye.retrieve( %22simple%22 ), %22/url/%22, %22Anye.retrieve() should behave like Anye.get().%22 );%0A oTest.equal( Anye.build( %22simple%22 ), %22/url/%22, %22Anye.build() should behave like Anye.get().%22 );%0A%0A
oTest.do
|
d745919379e9814d2d749fe60821d378e1c8962a | Fix tests | test/app/index.js | test/app/index.js | const chai = require('chai');
const expect = chai.expect;
const spies = require('chai-spies');
chai.use(spies);
const _ = require('lodash');
const test = require('ava');
const TestUtils = require('fountain-generator').TestUtils;
let context;
const base = {
devDependencies: {
'jspm': '0.17.0-beta.25',
'systemjs-builder': '0.15.23',
'gulp-replace': '^0.5.4'
},
scripts: {
jspm: 'jspm'
}
};
test.before(() => {
context = TestUtils.mock('app');
require('../../generators/app/index');
process.chdir('../../');
});
test.beforeEach(() => {
context.updateJson['package.json'] = {};
context.mergeJson['package.json'] = {};
});
test(`Move dependencies to jspm from 'package.json'`, t => {
context.updateJson['package.json'] = {
dependencies: {angular: '^1.5.0'},
devDependencies: {'angular-mocks': '^1.5.0'}
};
const expected = {
devDependencies: {},
jspm: {
dependencies: {
angular: 'npm:angular@^1.5.0',
ts: 'github:frankwallis/plugin-typescript@4.0.16'
},
devDependencies: {'angular-mocks': 'npm:angular-mocks@^1.5.0'}
}
};
TestUtils.call(context, 'configuring.pkg', {framework: 'angular1', js: 'typescript'});
t.deepEqual(context.updateJson['package.json'], expected);
t.deepEqual(context.mergeJson['package.json'], _.merge({}, base, context.mergeJson['package.json']));
});
test(`Add 'reflect-metadata' to jspm dependencies if framework is 'angular2'`, t => {
context.updateJson['package.json'] = {
dependencies: {},
devDependencies: {},
jspm: {
dependencies: {}
}
};
TestUtils.call(context, 'configuring.pkg', {framework: 'angular2', js: 'typescript'});
t.is(context.updateJson['package.json'].jspm.dependencies['reflect-metadata'], 'npm:reflect-metadata@^0.1.3');
});
test(`Delete dependencies from 'package.json'`, t => {
context.updateJson['package.json'] = {
dependencies: {react: '^15.0.1'},
devDependencies: {'react-addons-test-utils': '^15.0.1'}
};
const expected = {
devDependencies: {},
jspm: {
dependencies: {
'css': 'github:systemjs/plugin-css@^0.1.21',
'react': 'npm:react@^15.0.1',
'babel-polyfill': 'npm:babel-polyfill@^6.7.4',
'es6-shim': 'npm:es6-shim@^0.35.0'
},
devDependencies: {'react-addons-test-utils': 'npm:react-addons-test-utils@^15.0.1'}
}
};
TestUtils.call(context, 'configuring.pkg', {framework: 'react', sample: 'todoMVC', js: 'js'});
t.deepEqual(context.updateJson['package.json'], expected);
t.deepEqual(context.mergeJson['package.json'], _.merge({}, base, context.mergeJson['package.json']));
});
test(`Delete dependencies from 'package.json'`, t => {
context.updateJson['package.json'] = {
dependencies: {react: '^15.0.1'},
devDependencies: {'react-addons-test-utils': '^15.0.1'}
};
const expected = {
devDependencies: {},
jspm: {
dependencies: {
'css': 'github:systemjs/plugin-css@^0.1.21',
'react': 'npm:react@^15.0.1',
'babel-polyfill': 'npm:babel-polyfill@^6.7.4'
},
devDependencies: {'react-addons-test-utils': 'npm:react-addons-test-utils@^15.0.1'}
}
};
TestUtils.call(context, 'configuring.pkg', {framework: 'react', sample: 'todoMVC', js: 'babel'});
t.deepEqual(context.updateJson['package.json'], expected);
t.deepEqual(context.mergeJson['package.json'], _.merge({}, base, context.mergeJson['package.json']));
});
test('configjs(): Call this.copyTemplate 3 times', () => {
const spy = chai.spy.on(context, 'copyTemplate');
TestUtils.call(context, 'configuring.configjs');
expect(spy).to.have.been.called.exactly(3);
});
test(`gulp(): copy 'gulp_tasks/systemjs.js' when framework is angular1`, t => {
TestUtils.call(context, 'writing.gulp', {framework: 'angular1'});
t.true(context.copyTemplate['gulp_tasks/systemjs.js'].length > 0);
});
test(`gulp(): copy 'gulp_tasks/systemjs.js' when framework is react`, t => {
TestUtils.call(context, 'writing.gulp', {framework: 'react'});
t.true(context.copyTemplate['gulp_tasks/systemjs.js'].length > 0);
});
test(`gulp(): copy 'gulp_tasks/systemjs.js' when framework is angular2`, t => {
TestUtils.call(context, 'writing.gulp', {framework: 'angular2'});
t.true(context.copyTemplate['gulp_tasks/systemjs.js'].length > 0);
});
test(`indexHtml(): Call replaceInFileWithTemplate twice`, () => {
context.templatePath = context.destinationPath = path => path;
context.replaceInFileWithTemplate = () => {};
const spy = chai.spy.on(context, 'replaceInFileWithTemplate');
TestUtils.call(context, 'writing.indexHtml');
expect(spy).to.have.been.called.exactly(2);
});
test('Call runInstall', () => {
context.runInstall = () => {};
const spy = chai.spy.on(context, 'runInstall');
TestUtils.call(context, 'install');
expect(spy).to.have.been.called.once();
});
| JavaScript | 0.000003 | @@ -1019,14 +1019,13 @@
ipt@
-4.0.16
+5.1.2
'%0A
|
253dc863ee3bb6c4cfce511993573abe96ac12d4 | Handle games with a TBD time. | _includes/js/application.js | _includes/js/application.js | (function() {
var Time = {
MINUTES_IN_HOUR : 60,
MILLISECONDS_IN_MINUTE : 60000,
OFFSETS : [300, 240, 300, 240, 300, 240, 300, 240, 300, 240, 300, 240,
300, 240, 300, 240, 300, 240, 300, 240, 300, 240, 300],
UNTILS : [1268550000000, 1289109600000, 1299999600000, 1320559200000,
1331449200000, 1352008800000, 1362898800000, 1383458400000,
1394348400000, 1414908000000, 1425798000000, 1446357600000,
1457852400000, 1478412000000, 1489302000000, 1509861600000,
1520751600000, 1541311200000, 1552201200000, 1572760800000,
1583650800000, 1604210400000, null],
formatDate: function(date) {
return new Intl.DateTimeFormat(undefined, {
month : "long",
day : "numeric"
}).format(date);
},
formatTime: function(time) {
return new Intl.DateTimeFormat(undefined, {
hour : "numeric",
minute : "numeric"
}).format(time);
},
offset: function() {
var target = Date.now(),
untils = this.UNTILS,
offsets = this.OFFSETS,
offset,
offsetNext,
offsetPrev;
for (var index = 0; index < untils.length - 1; index++) {
offset = offsets[index];
offsetNext = offsets[index + 1];
offsetPrev = offsets[index ? index - 1 : index];
if (offset < offsetNext && false) {
offset = offsetNext;
} else if (offset > offsetPrev && true) {
offset = offsetPrev;
}
if (target < untils[index] - (offset * this.MILLISECONDS_IN_MINUTE)) {
return offsets[index] / this.MINUTES_IN_HOUR;
}
}
return offsets[untils.length - 1] / this.MINUTES_IN_HOUR;
}
};
var now = new Date(),
hours = now.getUTCHours(),
slice = Array.prototype.slice,
offset = Time.offset(),
sections = slice.call(document.querySelectorAll("section"));
if (navigator.platform.match(/Win/)) {
document.querySelector("header h1 a").innerHTML = "Hockey";
}
if (hours < offset) {
now.setUTCHours(hours - offset);
}
var year = now.getUTCFullYear(),
month = now.getUTCMonth() + 1,
day = now.getUTCDate(),
limit = 7,
count = 1;
sections.forEach(function(section) {
section.classList.remove("week");
});
sections
.filter(function(section) {
var parts = section.querySelector("h1 time").getAttribute("datetime").split("-"),
sectionYear = parseInt(parts[0], 10),
sectionMonth = parseInt(parts[1], 10),
sectionDay = parseInt(parts[2].split("T")[0], 10);
return (sectionYear > year) ||
(sectionYear >= year && sectionMonth > month) ||
(sectionYear >= year && sectionMonth >= month && sectionDay >= day);
})
.forEach(function(section, index) {
if (!section.querySelector("tr")) {
return;
} else if (count > limit && window.location.pathname === "/hockey/") {
return;
}
count++;
if (window.Intl && window.Intl.DateTimeFormat) {
var time = section.querySelector("h1 time");
time.innerText = Time.formatDate(
new Date(time.getAttribute("datetime"))
);
slice.call(section.querySelectorAll("th time")).forEach(function(time) {
time.textContent = Time.formatTime(
new Date(time.getAttribute("datetime"))
);
});
}
section.classList.add("week");
});
})();
| JavaScript | 0 | @@ -3405,55 +3405,18 @@
-time.textContent = Time.formatTime(%0A
+var date =
new
@@ -3443,32 +3443,34 @@
ute(%22datetime%22))
+;%0A
%0A );%0A
@@ -3464,16 +3464,87 @@
+time.textContent = date.getHours() === 3 ? %22TBD%22 : Time.formatTime(date
);%0A
|
448e7c38da51560ee00a81dfb3e7b7ea1dc5bf39 | update default font | app/eme/config.js | app/eme/config.js | 'use strict'
const os = require('os')
const Config = require('./utils/electron-config')
const cmdOrCtrl = os.platform() === 'darwin' ? 'command' : 'ctrl'
const config = new Config({
defaults: {
recentFiles: [],
lastAppState: {
tabs: [],
currentTabIndex: null
},
settings: {
theme: 'white',
colorSchema: 'base16-light',
highlight: 'github',
fontSize: 16,
font: `-apple-system, BlinkMacSystemFont,'avenir next', avenir,helvetica, 'helvetica neue',Ubuntu,'segoe ui', arial,sans-serif`,
writingMode: 'default',
tabSize: 2,
indentWithTabs: false,
keys: {
openNewTab: `${cmdOrCtrl}+t`,
openFile: `${cmdOrCtrl}+o`,
openLastSession: `${cmdOrCtrl}+l`,
switchWritingMode: `${cmdOrCtrl}+shift+m`,
distractionFreeMode: `${cmdOrCtrl}+j`,
vimMode: `${cmdOrCtrl}+i`,
focusMode: `${cmdOrCtrl}+\\`,
presentationMode: `${cmdOrCtrl}+k`
}
}
}
})
module.exports = config
| JavaScript | 0.000001 | @@ -419,129 +419,60 @@
nt:
-%60-apple-system, BlinkMacSystemFont,'avenir next', avenir,helvetica, 'helvetica neue',Ubuntu,'segoe ui', arial,sans-serif%60
+'Menlo, %22DejaVu Sans Mono%22, %22Lucida Console%22, monos'
,%0A
|
ab286ea464de684651e217f78abf9aa1b0ba6770 | add some more logs | functions/index.js | functions/index.js | 'use strict';
// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');
// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
var severDict = {'Larceny From Motor Vehicle' : 1, 'Harassment' : 2, 'Missing Person Reported' : 3,
'Larceny' : 4, 'Robbery' : 5, 'Vandalism' : 6, 'Investigate Property': 7,
'Simple Assault' : 8, 'Verbal Disputes' : 9, 'Medical Assistance' : 10,
'Violations' : 11, 'Drug Violation' : 12, 'Aggravated Assault' : 13,
'Property Lost' : 14, 'Police Service Incidents' : 15, 'Towed' : 16,
'Warrant Arrests' : 17, 'Counterfeiting' : 18, 'Other' : 19,
'Motor Vehicle Accident Response Disorderly Conduct' : 20,
'Auto Theft' : 21, 'Recovered Stolen Property' : 22, 'Restraining Order Violations' : 23,
'Firearm Violations' : 24, 'Commercial Burglary' : 25, 'Investigate Person' : 26,
'Residential Burglary' : 27, 'Missing Person Located' : 28, 'Sex Offender Registration' : 29,
'Fraud' : 30, 'Confidence Games' : 31, 'Evading Fare' : 32, 'Auto Theft Recovery' : 33,
'Assembly or Gathering Violations Other Burglary' : 34, 'Indecent Assault' : 35,
'Property Found' : 36, 'License Violation' : 37, 'Landlord/Tenant Disputes' : 38,
'Fire Related Reports' : 39, 'Operating Under the Influence' : 40, 'Service' : 41,
'Search Warrants' : 42, 'Property Related Damage' : 43, 'Prisoner Related Incidents' : 44,
'Offenses Against Child / Family Harbor Related Incidents' : 45 }
admin.initializeApp(functions.config().firebase);
exports.computeCrimePercentages = functions.database.ref('crimedata/{pushId}/offense_code_group')
.onWrite(event => {
console.log('Recalculating crime percentages for new message', event.params.pushId);
// Only edit data when it is first created.
if (!event.data.changed()) {
console.log('Skipping update to same value');
return;
}
return updateCrimePercentage(
event.data.val(),
event.data.previous.val(),
event.data.previous.exists());
});
exports.backfillCrimePercentages = functions.https.onRequest((req, resp) => {
var query = admin.database().ref('/crimedata').orderByKey();
return query.once('value')
.then(snapshot => {
snapshot.forEach(child => {
console.log("Backfilling", child.key);
updateCrimePercentage(child.val().offense_code_group, null, false);
});
resp.end();
});
});
function updateCrimePercentage(current, previous, previous_exists) {
var ocgRef = admin.database().ref('analytics/offense_code_group');
return ocgRef.transaction(current_value => {
if (!current_value) {
return current_value;
}
if (current_value.hasOwnProperty(current)) {
console.log("Incrementing", current);
current_value[current]+= 1;
} else {
console.log("Incrementing", current);
current_value[current] = 1;
}
if (previous_exists) {
if (current_value[previous]) {
console.log("Decrementing", previous);
current_value[previous]-= 1;
if (current_value[previous] <= 0) {
delete current_value[previous];
}
}
}
return current_value;
}).then(() => console.log("Transaction committed"));
}
exports.computeSeverityLevel = functions.database.ref('crimedata/{pushId}/offense_code_group')
.onWrite(event => {
console.log('Calculating severity level for', event.params.pushId);
return event.data.ref.parent.child('Severity').set(severDict[event.data.val()]);
});
| JavaScript | 0 | @@ -2557,24 +2557,74 @@
apshot =%3E %7B%0A
+ console.log(%22Got snapshot:%22, snapshot.key);%0A
snapsh
@@ -3017,24 +3017,79 @@
nt_value) %7B%0A
+ console.log(%22Got null current_value, skipping%22);%0A
return
|
906a433265c2ebee2ff87fc519a04707e0c20d24 | Document DefaultScheduler | src/default-scheduler.js | src/default-scheduler.js | // If the scheduler is not customized via `etch.setScheduler`, an instance of
// this class will be used to schedule updates to the document. The
// `updateDocument` method accepts functions to be run at some point in the
// future, then runs them on the next animation frame.
export default class DefaultScheduler {
constructor () {
this.updateRequests = []
this.pendingAnimationFrame = null
this.performUpdates = this.performUpdates.bind(this)
}
updateDocument (fn) {
this.updateRequests.push(fn)
if (!this.pendingAnimationFrame) {
this.pendingAnimationFrame = window.requestAnimationFrame(this.performUpdates)
}
}
updateDocumentSync (fn) {
if (this.pendingAnimationFrame) window.cancelAnimationFrame(this.pendingAnimationFrame)
this.updateRequests.push(fn)
this.performUpdates()
}
getNextUpdatePromise () {
if (!this.nextUpdatePromise) {
this.nextUpdatePromise = new Promise(resolve => {
this.resolveNextUpdatePromise = resolve
})
}
return this.nextUpdatePromise
}
performUpdates () {
while (this.updateRequests.length > 0) {
this.updateRequests.shift()()
}
this.pendingAnimationFrame = null
if (this.nextUpdatePromise) {
let resolveNextUpdatePromise = this.resolveNextUpdatePromise
this.nextUpdatePromise = null
this.resolveNextUpdatePromise = null
resolveNextUpdatePromise()
}
}
}
| JavaScript | 0 | @@ -454,24 +454,237 @@
(this)%0A %7D%0A%0A
+ // Enqueues functions that write to the DOM to be performed on the next%0A // animation frame. Functions passed to this method should *never* read from%0A // the DOM, because that could cause synchronous reflows.%0A
updateDocu
@@ -863,16 +863,123 @@
%7D%0A %7D%0A%0A
+ // Enqueues a DOM writer, then runs all enqueued functions and cancels the%0A // pending animation frame.%0A
update
@@ -1154,16 +1154,195 @@
()%0A %7D%0A%0A
+ // Returns a promise that will resolve at the end of the next update cycle,%0A // after all the functions passed to %60updateDocument%60 and %60updateDocumentSync%60%0A // have been run.%0A
getNex
@@ -1554,16 +1554,229 @@
se%0A %7D%0A%0A
+ // Performs all the pending document updates. If running these update%0A // functions causes *more* updates to be enqueued, they are run synchronously%0A // in this update cycle without waiting for another frame.%0A
perfor
@@ -1871,24 +1871,98 @@
ft()()%0A %7D
+%0A%0A // We don't clear the pending frame until the request queue is fully
%0A this.pe
@@ -1984,24 +1984,25 @@
rame = null%0A
+%0A
if (this
|
c97e3d1359ff9538cf43446c2ed18f42b0e531c2 | fix regexes that match for error messages in tests. output changed with new less version | test/compiless.js | test/compiless.js | /*global describe, it, __dirname*/
var express = require('express'),
Path = require('path'),
unexpected = require('unexpected'),
compiless = require('../lib/compiless');
describe('compiless', function () {
var root = Path.resolve(__dirname, 'root'),
expect = unexpected.clone()
.installPlugin(require('unexpected-express'))
.addAssertion('to yield response', function (expect, subject, value) {
return expect(
express()
.use(compiless({root: root}))
.use('/hello', function (req, res, next) {
res.setHeader('Content-Type', 'text/plain');
res.setHeader('ETag', 'W/"fake-etag"');
res.status(200);
res.write('world');
res.end();
})
.use(express['static'](root)),
'to yield exchange', {
request: subject,
response: value
}
);
});
it('should not mess with request for non-less file', function () {
return expect('GET /something.txt', 'to yield response', {
headers: {
'Content-Type': 'text/plain; charset=UTF-8',
'ETag': expect.it('not to match', /-compiless/),
'Content-Length': '4'
},
body: 'foo\n'
});
});
it('should not mess with request for non-less related route', function () {
return expect('GET /hello', 'to yield response', {
headers: {
'Content-Type': 'text/plain',
'ETag': expect.it('not to match', /-compiless/)
},
body: 'world'
});
});
it('should respond with an ETag header and support conditional GET', function () {
return expect('GET /simple.less', 'to yield response', {
statusCode: 200,
headers: {
'Content-Type': 'text/css; charset=utf-8',
ETag: /^W\/".*-compiless"$/
},
body: '#foo #bar {\n color: blue;\n}\n'
}).then(function (context) {
var etag = context.httpResponse.headers.get('ETag');
return expect({
url: 'GET /simple.less',
headers: {
'If-None-Match': etag
}
}, 'to yield response', {
statusCode: 304,
headers: {
ETag: etag
}
});
});
});
it('should compile less file with @import to css with .compilessinclude rules first', function () {
return expect('GET /stylesheet.less', 'to yield response', {
headers: {
'Content-Type': 'text/css; charset=utf-8'
},
body: '.compilessinclude {background-image: url(imports/a.less); display: none;}\nbody {\n width: 100%;\n}\n#foo #bar {\n color: red;\n}\n/* multi-line\n comment\n*/\n'
});
});
it('should render less file that has a syntax error with the error message as the first thing in the output, wrapped in a body:before rule', function () {
return expect('GET /syntaxerror.less', 'to yield response', {
statusCode: 200,
headers: {
'Content-Type': 'text/css; charset=utf-8'
},
body: /Error compiling \/syntaxerror.less:.*(?:missing closing `\}`|Unrecognised input\. Possibly missing something) at line 8/
});
});
it('should render less file that has an @import error with the error message as the first thing in the output, wrapped in a body:before rule', function () {
return expect('GET /importerror.less', 'to yield response', {
statusCode: 200,
headers: {
'Content-Type': 'text/css; charset=utf-8'
},
body: /body:before \{.*Error.*\/importerror\.less.*notfound\.less/
});
});
it('should render less file that has an @import that points at a file with a syntax error', function () {
return expect('GET /importedsyntaxerror.less', 'to yield response', {
statusCode: 200,
headers: {
'Content-Type': 'text/css; charset=utf-8'
},
body: /Error compiling.*importedsyntaxerror.less:.*(missing closing `\}`|Unrecognised input. Possibly missing something) at line 8/
});
});
it('should render less file that has an second level @import error with the error message as the first thing in the output, wrapped in a body:before rule', function () {
return expect('GET /secondlevelimporterror.less', 'to yield response', {
statusCode: 200,
headers: {
'Content-Type': 'text/css; charset=utf-8'
},
body: /body:before \{.*Error compiling \/secondlevelimporterror\.less/
});
});
it('should rewrite urls correctly', function () {
return expect('GET /importLessWithRelativeImageReferenceInDifferentDir.less', 'to yield response', {
statusCode: 200,
headers: {
'Content-Type': 'text/css; charset=utf-8'
},
body: /url\(imports\/images\/foo.png\)/
});
});
it('should deliver a response even though the less file has @imports and references an undefined variable', function () {
return expect('GET /undefinedVariable.less', 'to yield response', {
statusCode: 200,
headers: {
'Content-Type': 'text/css; charset=utf-8'
},
body: /Error compiling.*variable.*undefined/
});
});
});
| JavaScript | 0.000013 | @@ -3562,114 +3562,10 @@
ling
- %5C/syntaxerror.less:.*(?:missing closing %60%5C%7D%60%7CUnrecognised input%5C. Possibly missing something) at line 8
/%0A
+
@@ -3960,66 +3960,23 @@
y: /
-body:before %5C%7B.*Error.*%5C/importerror%5C.less.*notfound%5C.less
+Error compiling
/%0A
@@ -4345,116 +4345,8 @@
ling
-.*importedsyntaxerror.less:.*(missing closing %60%5C%7D%60%7CUnrecognised input. Possibly missing something) at line 8
/%0A
@@ -4767,70 +4767,23 @@
y: /
-body:before %5C%7B.*Error compiling %5C/secondlevelimporterror%5C.less
+Error compiling
/%0A
|
e307a4045de639783524b97e753b08e0b1676c3f | Update query import for new export model | app/helpers/db.js | app/helpers/db.js | import treo from 'treo'
let schema = treo.schema()
.version(1)
.addStore('courses', { key: 'clbid' })
.addIndex('clbid', 'clbid', { unique: true })
.addIndex('credits', 'credits')
.addIndex('crsid', 'crsid')
.addIndex('dept', 'dept')
.addIndex('depts', 'depts', { multi: true })
.addIndex('deptnum', 'deptnum')
.addIndex('desc', 'desc')
.addIndex('gereqs', 'gereqs', { multi: true })
.addIndex('groupid', 'groupid')
.addIndex('grouptype', 'grouptype')
.addIndex('halfcredit', 'halfcredit')
.addIndex('level', 'level')
.addIndex('name', 'name')
.addIndex('notes', 'notes')
.addIndex('num', 'num')
.addIndex('pf', 'pf')
.addIndex('places', 'places', { multi: true })
.addIndex('profs', 'profs', { multi: true })
.addIndex('sect', 'sect')
.addIndex('sem', 'sem')
.addIndex('term', 'term')
.addIndex('times', 'times', { multi: true })
.addIndex('title', 'title')
.addIndex('type', 'type')
.addIndex('year', 'year')
.addIndex('sourcePath', 'sourcePath')
.addStore('areas', { key: 'sourcePath' })
.addIndex('type', 'type', { multi: true })
.addIndex('sourcePath', 'sourcePath')
.addStore('students', { key: 'id' })
.version(2)
.getStore('courses')
.addIndex('words', 'words', { multi: true })
.version(3)
.getStore('courses')
.addIndex('profWords', 'profWords', { multi: true })
import treoPromise from 'treo/plugins/treo-promise'
import queryTreoDatabase from './queryTreoDatabase'
import treoBatchGet from './treoBatchGet'
let db = treo('gobbldygook', schema)
.use(queryTreoDatabase())
.use(treoPromise())
.use(treoBatchGet())
export default db
window.deleteDatabase = () => new Promise(resolve => {
window.indexedDB.deleteDatabase('gobbldygook', resolve)
}).then((res) => {
console.log('Database dropped')
return res
})
window.eraseStorage = () => new Promise(resolve => {
window.localStorage.clear()
resolve()
}).then((res) => {
console.log('Storage erased')
return res
})
window.eraseDatabase = () => {
window.deleteDatabase()
window.eraseStorage()
}
window.database = db
| JavaScript | 0 | @@ -1578,18 +1578,16 @@
Database
-()
)%0A%09.use(
|
9a6b70cef8f44276e9905318a4b725c39eba3938 | Add initial registrar server connection listener | registrar/index.js | registrar/index.js | const program = require('commander');
program
.version('0.0.1')
.option('-p, --port <port>', 'specify the websocket port to listen to [9872]', 9872)
.parse(process.argv);
const io = require('socket.io'),
winston = require('winston'),
models = require('./models');
winston.level = 'debug';
winston.remove(winston.transports.Console);
winston.add(winston.transports.Console, {'timestamp': true});
const PORT = program.port;
winston.info('Unichat registrar service');
winston.info('Connecting to database...');
const addUser = (user) => {
return models.User.create(user).then((user) => {
winston.debug('User ' + user.email + ' has been created.');
return user;
}).catch((e) => {
let errorMessage;
if (e.name == 'SequelizeValidationError') {
if (e.message.startsWith("notNull Violation")) {
errorMessage = user.username + ': Please fill all necessary fields.';
}
else if (e.message.startsWith("Validation error: Validation isEmail failed")) {
errorMessage = user.username + ': Invalid email given.';
}
else if (e.message.startsWith("Password confirmation")) {
errorMessage = user.username + ': Passwords don\'t match';
}
else if (e.message.startsWith("Password should be at least 6 characters")) {
errorMessage = user.username + ': ' + e.message;
}
else {
throw e;
}
}
else if (e.name == 'SequelizeUniqueConstraintError') {
errorMessage = user.email + ': Email already exists.';
}
else {
throw e;
}
throw new Error(errorMessage);
});
};
models.sequelize.sync().then( () => {
winston.info('Listening on port ' + PORT);
const socket = io.listen(PORT);
});
| JavaScript | 0 | @@ -1895,12 +1895,128 @@
(PORT);%0A
+ socket.on('connection', (client) =%3E %7B%0A winston.debug('New connection from client ' + client.id);%0A %7D);%0A
%7D);%0A
|
16bf066cd528f08457eab92231e65ea070d45381 | Remove Document#bounds and #size, since this will be on Page. | src/document/Document.js | src/document/Document.js | /*
* Paper.js
*
* This file is part of Paper.js, a JavaScript Vector Graphics Library,
* based on Scriptographer.org and designed to be largely API compatible.
* http://paperjs.org/
* http://scriptographer.org/
*
* Distributed under the MIT license. See LICENSE file for details.
*
* Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
* http://lehni.org/ & http://jonathanpuckey.com/
*
* All rights reserved.
*/
var Document = this.Document = Base.extend({
beans: true,
// XXX: Add arguments to define pages, but do not pass canvas here
initialize: function(canvas) {
// Store reference to the currently active global paper scope:
this._scope = paper;
// Push it onto this._scope.documents and set index:
this._index = this._scope.documents.push(this) - 1;
// Activate straight away so paper.document is set, as required by
// Layer and DoumentView constructors.
this.activate();
this.layers = [];
this.views = [];
this.symbols = [];
this.activeLayer = new Layer();
this.activeView = canvas ? new DocumentView(canvas) : null;
// XXX: Introduce pages and remove Document#bounds!
var size = this.activeView && this.activeView._size
|| new Size(1024, 768);
this._bounds = Rectangle.create(0, 0, size.width, size.height);
this._selectedItems = {};
this._selectedItemCount = 0;
this.setCurrentStyle(null);
},
getBounds: function() {
// TODO: Consider LinkedRectangle once it is required.
return this._bounds;
},
setBounds: function(rect) {
rect = Rectangle.read(arguments);
this._bounds.set(rect.x, rect.y, rect.width, rect.height);
},
getSize: function() {
return this._bounds.getSize();
},
setSize: function(size) {
// TODO: Once _bounds is a LinkedRectangle, this will recurse
this._bounds.setSize.apply(this._bounds, arguments);
},
getCurrentStyle: function() {
return this._currentStyle;
},
setCurrentStyle: function(style) {
this._currentStyle = PathStyle.create(null, style);
},
activate: function() {
if (this._index != null) {
this._scope.document = this;
return true;
}
return false;
},
remove: function() {
var res = Base.splice(this._scope.documents, null, this._index, 1);
this._scope = null;
// Remove all views. This also removes the installed event handlers.
for (var i = this.views.length - 1; i >= 0; i--)
this.views[i].remove();
return !!res.length;
},
getIndex: function() {
return this._index;
},
getSelectedItems: function() {
// TODO: return groups if their children are all selected,
// and filter out their children from the list.
// TODO: the order of these items should be that of their
// drawing order.
var items = [];
Base.each(this._selectedItems, function(item) {
items.push(item);
});
return items;
},
// TODO: implement setSelectedItems?
_selectItem: function(item, select) {
if (select) {
this._selectedItemCount++;
this._selectedItems[item.getId()] = item;
} else {
this._selectedItemCount--;
delete this._selectedItems[item.getId()];
}
},
/**
* Selects all items in the document.
*/
selectAll: function() {
// TODO: is using for var i in good practice?
// or should we use Base.each? (JP)
for (var i = 0, l = this.layers.length; i < l; i++)
this.layers[i].setSelected(true);
},
/**
* Deselects all selected items in the document.
*/
deselectAll: function() {
// TODO: is using for var i in good practice?
// or should we use Base.each? (JP)
for (var i in this._selectedItems)
this._selectedItems[i].setSelected(false);
},
draw: function(ctx) {
ctx.save();
var param = { offset: new Point(0, 0) };
for (var i = 0, l = this.layers.length; i < l; i++)
Item.draw(this.layers[i], ctx, param);
ctx.restore();
// Draw the selection of the selected items in the document:
if (this._selectedItemCount > 0) {
ctx.save();
ctx.strokeWidth = 1;
// TODO: use Layer#color
ctx.strokeStyle = ctx.fillStyle = '#009dec';
param = { selection: true };
Base.each(this._selectedItems, function(item) {
item.draw(ctx, param);
});
ctx.restore();
}
},
redraw: function() {
for (var i = 0, l = this.views.length; i < l; i++)
this.views[i].draw();
}
});
| JavaScript | 0 | @@ -1067,751 +1067,94 @@
;%0A%09%09
-// XXX: Introduce pages and remove Document#bounds!%0A%09%09var size = this.activeView && this.activeView._size%0A%09%09%09%09%7C%7C new Size(1024, 768);%0A%09%09this._bounds = Rectangle.create(0, 0, size.width, size.height);%0A%09%09this._selectedItems = %7B%7D;%0A%09%09this._selectedItemCount = 0;%0A%09%09this.setCurrentStyle(null);%0A%09%7D,%0A%0A%09getBounds: function() %7B%0A%09%09// TODO: Consider LinkedRectangle once it is required.%0A%09%09return this._bounds;%0A%09%7D,%0A%0A%09setBounds: function(rect) %7B%0A%09%09rect = Rectangle.read(arguments);%0A%09%09this._bounds.set(rect.x, rect.y, rect.width, rect.height);%0A%09%7D,%0A%0A%09getSize: function() %7B%0A%09%09return this._bounds.getSize();%0A%09%7D,%0A%09%0A%09setSize: function(size) %7B%0A%09%09// TODO: Once _bounds is a LinkedRectangle, this will recurse%0A%09%09this._bounds.setSize.apply(this._bounds, arguments);
+this._selectedItems = %7B%7D;%0A%09%09this._selectedItemCount = 0;%0A%09%09this.setCurrentStyle(null);
%0A%09%7D,
|
08bb48b047cd7e62517cce8720b74e21a52eb4e5 | improve $controller function doc readability | src/ng/controller.js | src/ng/controller.js | 'use strict';
/**
* @ngdoc object
* @name ng.$controllerProvider
* @description
* The {@link ng.$controller $controller service} is used by Angular to create new
* controllers.
*
* This provider allows controller registration via the
* {@link ng.$controllerProvider#register register} method.
*/
function $ControllerProvider() {
var controllers = {};
/**
* @ngdoc function
* @name ng.$controllerProvider#register
* @methodOf ng.$controllerProvider
* @param {string} name Controller name
* @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
* annotations in the array notation).
*/
this.register = function(name, constructor) {
if (isObject(name)) {
extend(controllers, name)
} else {
controllers[name] = constructor;
}
};
this.$get = ['$injector', '$window', function($injector, $window) {
/**
* @ngdoc function
* @name ng.$controller
* @requires $injector
*
* @param {Function|string} constructor If called with a function then it's considered to be the
* controller constructor function. Otherwise it's considered to be a string which is used
* to retrieve the controller constructor using the following steps:
*
* * check if a controller with given name is registered via `$controllerProvider`
* * check if evaluating the string on the current scope returns a constructor
* * check `window[constructor]` on the global `window` object
*
* @param {Object} locals Injection locals for Controller.
* @return {Object} Instance of given controller.
*
* @description
* `$controller` service is responsible for instantiating controllers.
*
* It's just simple call to {@link AUTO.$injector $injector}, but extracted into
* a service, so that one can override this service with {@link https://gist.github.com/1649788
* BC version}.
*/
return function(constructor, locals) {
if(isString(constructor)) {
var name = constructor;
constructor = controllers.hasOwnProperty(name)
? controllers[name]
: getter(locals.$scope, name, true) || getter($window, name, true);
assertArgFn(constructor, name, true);
}
return $injector.instantiate(constructor, locals);
};
}];
}
| JavaScript | 0.000016 | @@ -1768,16 +1768,18 @@
's just
+a
simple c
|
d8d64262de7a8dd4f3eaae33d9781ba447e39c61 | Tidy up shape store. | src/draw/Control.Draw.js | src/draw/Control.Draw.js | L.Map.mergeOptions({
drawControl: false
});
L.Control.Draw = L.Control.extend({
options: {
position: 'topleft',
polyline: {
title: 'Draw a polyline'
},
polygon: {
title: 'Draw a polygon'
},
rectangle: {
title: 'Draw a rectangle'
},
circle: {
title: 'Draw a circle'
},
marker: {
title: 'Add a marker'
}
},
initialize: function (options) {
L.Util.extend(this.options, options);
},
onAdd: function (map) {
var className = 'leaflet-control-draw',
container = L.DomUtil.create('div', ''),
buttonIndex = 0;
this._drawContainer = L.DomUtil.create('div', className),
this._cancelContainer = L.DomUtil.create('div', className + ' leaflet-control-draw-cancel');
// TODO: should this be done in initialize()?
this._shapes = {};
//
if (this.options.polyline) {
this._initShapeHandler(L.Polyline.Draw, this._drawContainer, buttonIndex++);
}
if (this.options.polygon) {
this._initShapeHandler(L.Polygon.Draw, this._drawContainer, buttonIndex++);
}
if (this.options.rectangle) {
this._initShapeHandler(L.Rectangle.Draw, this._drawContainer, buttonIndex++);
}
if (this.options.circle) {
this._initShapeHandler(L.Circle.Draw, this._drawContainer, buttonIndex++);
}
if (this.options.marker) {
this._initShapeHandler(L.Marker.Draw, this._drawContainer, buttonIndex);
}
// Save button index of the last button
this._lastButtonIndex = buttonIndex;
// Create the cancel button
this._createButton({
title: 'Cancel drawing',
text: 'Cancel',
container: this._cancelContainer,
callback: this._cancelDrawing,
context: this
});
// Add draw and cancel containers to the control container
container.appendChild(this._drawContainer);
container.appendChild(this._cancelContainer);
return container;
},
_initShapeHandler: function (Handler, container, buttonIndex) {
// TODO: make as a part of options?
var className = 'leaflet-control-draw',
type = Handler.TYPE;
this._shapes[type] = {};
this._shapes[type].handler = new Handler(map, this.options[type]);
this._shapes[type].button = this._createButton({
title: this.options.polyline.title,
className: className + '-' + type,
container: container,
callback: this._shapes[type].handler.enable,
context: this._shapes[type].handler
});
this._shapes[type].buttonIndex = buttonIndex;
this._shapes[type].handler
.on('activated', this._drawHandlerActivated, this)
.on('deactivated', this._drawHandlerDeactivated, this);
},
_createButton: function (options) {
var link = L.DomUtil.create('a', options.className || '', options.container);
link.href = '#';
if (options.text) link.innerHTML = options.text;
if (options.title) link.title = options.title;
L.DomEvent
.on(link, 'click', L.DomEvent.stopPropagation)
.on(link, 'mousedown', L.DomEvent.stopPropagation)
.on(link, 'dblclick', L.DomEvent.stopPropagation)
.on(link, 'click', L.DomEvent.preventDefault)
.on(link, 'click', options.callback, options.context);
return link;
},
_drawHandlerActivated: function (e) {
// Disable active mode (if present)
if (this._activeShape && this._activeShape.handler.enabled()) {
this._activeShape.handler.disable();
}
// Cache new active shape
this._activeShape = this._shapes[e.drawingType];
L.DomUtil.addClass(this._activeShape.button, 'leaflet-control-draw-button-enabled');
this._showCancelButton();
},
_drawHandlerDeactivated: function (e) {
this._hideCancelButton();
L.DomUtil.removeClass(this._activeShape.button, 'leaflet-control-draw-button-enabled');
this._activeShape = null;
},
_showCancelButton: function () {
var buttonIndex = this._activeShape.buttonIndex,
lastButtonIndex = this._lastButtonIndex,
buttonHeight = 19, // TODO: this should be calculated
buttonMargin = 5, // TODO: this should also be calculated
cancelPosition = (buttonIndex * buttonHeight) + (buttonIndex * buttonMargin);
// Correctly position the cancel button
this._cancelContainer.style.marginTop = cancelPosition + 'px';
// TODO: remove the top and button rounded border if first or last button
if (buttonIndex === 0) {
L.DomUtil.addClass(this._drawContainer, 'leaflet-control-draw-cancel-top');
}
else if (buttonIndex === lastButtonIndex) {
L.DomUtil.addClass(this._drawContainer, 'leaflet-control-draw-cancel-bottom');
}
// Show the cancel button
// TODO: anitmation!
this._cancelContainer.style.display = 'block';
},
_hideCancelButton: function () {
// TODO: anitmation!
this._cancelContainer.style.display = 'none';
L.DomUtil.removeClass(this._drawContainer, 'leaflet-control-draw-cancel-top');
L.DomUtil.removeClass(this._drawContainer, 'leaflet-control-draw-cancel-bottom');
},
_cancelDrawing: function (e) {
this._activeShape.handler.disable();
}
});
L.Map.addInitHook(function () {
if (this.options.drawControl) {
this.drawControl = new L.Control.Draw();
this.addControl(this.drawControl);
}
});
| JavaScript | 0.000001 | @@ -414,16 +414,38 @@
ptions);
+%0A%0A%09%09this._shapes = %7B%7D;
%0A%09%7D,%0A%09%0A%09
@@ -734,84 +734,9 @@
');%0A
-%09%0A%09%09// TODO: should this be done in initialize()?%0A%09%09this._shapes = %7B%7D;%0A%0A%09%09//
+%0A
%0A%09%09i
|
ba8d17ee4ca4e7fb07a888b88a69824d7cf23445 | Add a method for querying last.fm | spotifyCurrentlyPlaying.js | spotifyCurrentlyPlaying.js | ;(function(global, $) {
var Spotify = function(selector, username, api_key, width, height) {
return new Spotify.init(selector, username, api_key, width, height);
}
Spotify.prototype = {
/*
* Display the Spotify player
*/
displayPlayer: function() {
if(!this.selector) {
throw 'Missing selector';
}
// TODO
// 1. Query Last.FM
// 2. Search Spotify for the track
// 3. Display the Spotify player using the selector
},
/*
* Validate the supplied Last.FM username and api key
*/
validateLastFM: function() {
if(!this.username) {
throw 'Missing username';
}
if(!this.api_key) {
throw 'Missing api_key';
}
console.log('Validating Last.FM...');
console.log('Username: ' + this.username);
console.log('API Key: ' + this.api_key);
}
};
Spotify.init = function(selector, username, api_key, width, height) {
var self = this;
self.selector: selector || '';
self.username: username || '';
self.api_key: api_key || '';
self.width: width || 300;
self.height: height || 400;
// Validate the Last.fm username and api_key
self.validateLastFM();
// Display the Spotify player
self.displayPlayer();
}
Spotify.init.prototype = Spotify.prototype;
global.Spotify = Spotify;
}(window, jQuery));
| JavaScript | 0.000006 | @@ -1025,24 +1025,496 @@
);%0A %7D
+,%0A%0A /*%0A * Get the most recently scrobbled track from LastFM%0A */%0A queryLastFM: function() %7B%0A console.log('Querying Last.FM...');%0A%0A // TODO%0A // 1. Make an API call to get the most recent track information%0A // 2. Return the results = %7Btitle, artist, album%7D%0A%0A return %7B%0A title: 'title',%0A artist: 'artist',%0A album: 'album'%0A %7D;%0A %7D,
%0A%0A %7D;%0A%0A
|
73067e1cd7b35585e15567921429672f36676a19 | Add missing parameter to onFilterSuccess | app/assets/javascripts/filterable_list.js | app/assets/javascripts/filterable_list.js | /**
* Makes search request for content when user types a value in the search input.
* Updates the html content of the page with the received one.
*/
export default class FilterableList {
constructor(form, filter, holder) {
this.filterForm = form;
this.listFilterElement = filter;
this.listHolderElement = holder;
this.filterUrl = `${this.filterForm.getAttribute('action')}?${$(this.filterForm).serialize()}`;
}
initSearch() {
// Wrap to prevent passing event arguments to .filterResults;
this.debounceFilter = _.debounce(this.onFilterInput.bind(this), 500);
this.unbindEvents();
this.bindEvents();
}
onFilterInput() {
const url = this.filterForm.getAttribute('action');
const data = $(this.filterForm).serialize();
this.filterResults(url, data, 'filter-input');
}
bindEvents() {
this.listFilterElement.addEventListener('input', this.debounceFilter);
}
unbindEvents() {
this.listFilterElement.removeEventListener('input', this.debounceFilter);
}
filterResults(url, data, comingFrom) {
const endpoint = url || this.filterForm.getAttribute('action');
const additionalData = data || $(this.filterForm).serialize();
$(this.listHolderElement).fadeTo(250, 0.5);
return $.ajax({
url: endpoint,
data: additionalData,
type: 'GET',
dataType: 'json',
context: this,
complete: this.onFilterComplete,
success: (response, textStatus, xhr) => {
if (this.preOnFilterSuccess) {
this.preOnFilterSuccess(comingFrom);
}
this.onFilterSuccess(response, xhr);
},
});
}
onFilterSuccess(data) {
if (data.html) {
this.listHolderElement.innerHTML = data.html;
}
// Change url so if user reload a page - search results are saved
return window.history.replaceState({
page: this.filterUrl,
}, document.title, this.filterUrl);
}
onFilterComplete() {
$(this.listHolderElement).fadeTo(250, 1);
}
}
| JavaScript | 0.000001 | @@ -1652,16 +1652,21 @@
ess(data
+, xhr
) %7B%0A
|
8a5c0e544d3896e992547d90de8c1c0fbc32fd44 | Version the banner | app/assets/javascripts/global-bar-init.js | app/assets/javascripts/global-bar-init.js | //= require libs/GlobalBarHelper.js
//= require govuk_publishing_components/lib/cookie-functions
'use strict'
window.GOVUK = window.GOVUK || {}
// Bump this if you are releasing a major change to the banner
// This will reset the view count so all users will see the banner, even if previously seen
var BANNER_VERSION = 5;
var GLOBAL_BAR_SEEN_COOKIE = "global_bar_seen"
var globalBarInit = {
getBannerVersion: function() {
return BANNER_VERSION
},
getLatestCookie: function() {
var currentCookie = window.GOVUK.getCookie(GLOBAL_BAR_SEEN_COOKIE)
if (currentCookie == null) {
return currentCookie
} else {
return currentCookie
}
},
urlBlockList: function() {
var paths = [
"^/done",
"^/transition-check$",
"^/coronavirus$"
]
var ctaLink = document.querySelector('.js-call-to-action')
if (ctaLink) {
var ctaPath = "^" + ctaLink.getAttribute('href') + "$"
paths.push(ctaPath)
}
return new RegExp(paths.join("|")).test(window.location.pathname)
},
checkDuplicateCookie: function() {
var cookies = document.cookie.split(';')
var matches = 0
for (var i = 0; i < cookies.length; i++) {
if (cookies[i] && cookies[i].indexOf('global_bar_seen') !== -1) {
matches++
}
}
if (matches > 1) {
var possiblePaths = window.location.pathname.split("/")
var pathString= ""
// The duplicate cookie will have a path set to something other than "/".
// The cookie will only surface on that path or it's sub-paths
// As there isn't a way of directly finding out the path, we need to try cookie deletion with all path combinations possible on the current URL.
for (var i = 0; i < possiblePaths.length; i++) {
if (possiblePaths[i] !== "") {
pathString = pathString + "/" + possiblePaths[i]
document.cookie = 'global_bar_seen=; expires=Thu, 01 Jan 1970 00:00:01 GMT;path=' + pathString
}
}
}
},
setBannerCookie: function() {
var cookieCategory = window.GOVUK.getCookieCategory(GLOBAL_BAR_SEEN_COOKIE)
var cookieConsent = GOVUK.getConsentCookie()
if (cookieConsent && cookieConsent[cookieCategory]) {
var value = JSON.stringify({count: 0, version: globalBarInit.getBannerVersion()})
window.GOVUK.setCookie(GLOBAL_BAR_SEEN_COOKIE, value, {days: 84});
}
},
makeBannerVisible: function() {
document.documentElement.className = document.documentElement.className.concat(" show-global-bar")
},
init: function() {
if (!globalBarInit.urlBlockList()) {
// We had a bug which meant that the global_bar_seen cookie was sometimes set more than once.
// This bug has now been fixed, but some users will be left with these duplicate cookies and therefore will continue to see the issue.
// We need to check for duplicate cookies so we can delete them
globalBarInit.checkDuplicateCookie()
if (globalBarInit.getLatestCookie() === null) {
globalBarInit.setBannerCookie()
globalBarInit.makeBannerVisible()
} else {
var currentCookieVersion = parseCookie(globalBarInit.getLatestCookie()).version
if (currentCookieVersion !== globalBarInit.getBannerVersion()) {
globalBarInit.setBannerCookie()
}
var newCookieCount = parseCookie(globalBarInit.getLatestCookie()).count
if (newCookieCount < 3) {
globalBarInit.makeBannerVisible()
}
}
}
}
}
window.GOVUK.globalBarInit = globalBarInit;
| JavaScript | 0 | @@ -319,9 +319,9 @@
N =
-5
+6
;%0Ava
|
98c568cd129356889dd0431c75055d506a02ccea | Make sure value is defined before trying to call length | app/assets/javascripts/identifier-form.js | app/assets/javascripts/identifier-form.js | (function() {
$('.assignment_invitations.identifier, .group_assignment_invitations.identifier').ready(function() {
return $('form').on('change keyup', function() {
return $('.js-form-submit').prop('disabled', $('#student_identifier_value').val().length === 0);
});
});
}).call(this);
| JavaScript | 0.000001 | @@ -159,24 +159,90 @@
unction() %7B%0A
+ if ($('#student_identifier_value').val() !== undefined) %7B%0A
return
@@ -332,16 +332,24 @@
=== 0);%0A
+ %7D%0A
%7D);%0A
|
9db26fa921e6afc71024f8adebef9d887a849012 | update closeBox | app/assets/js/controllers/organization.js | app/assets/js/controllers/organization.js | 'use strict';
function knyMiddleware(context){
return kny.syllbreak( kny.fontConvert(context, "unicode5"), "unicode5");
}
angular.module('MyanmarFlood')
.run(function($rootScope){
$rootScope.box = {
show: null,
description: null,
phone_numbers: null,
donation_location: null
}
})
.controller('OrganizationCtrl', ['$scope', '$rootScope', 'Organization', function ($scope, $rootScope, Organization) {
// Initial scope data
$scope.organizations = [];
$scope.total = null;
$scope.loading = false;
$scope.currentPage = 1;
$scope.init = function () {
fetchOrganizationData();
}
$scope.init();
$scope.nextPage = function() {
fetchOrganizationData();
}
// Fetch organization data from api server.
function fetchOrganizationData() {
$scope.loading = true;
Organization.paginate($scope.currentPage).then(function (response) {
responseSuccess(response);
});
}
$scope.showDetailBox = function (index){
$rootScope.box.show = true;
$rootScope.box.description = $scope.organizations[index].description;
$rootScope.box.phone_numbers = $scope.organizations[index].phone_numbers;
$rootScope.box.donation_location = $scope.organizations[index].donation_location;
}
// Callback function after http request is success.
function responseSuccess(response) {
var data = response.data.data;
$scope.total = response.data.meta.total_count;
$scope.currentPage = $scope.currentPage + 1;
data = data.map(function(info){
info.title = knyMiddleware(info.title);
info.description = knyMiddleware(info.description);
info.donation_location = knyMiddleware(info.donation_location);
info.phone_numbers = knyMiddleware(info.phone_numbers);
info.description = info.description.replace(/\n/g, "</br>");
return info;
});
$scope.loading = false;
$scope.organizations = $scope.organizations.concat(data);
}
}])
.controller('ModalboxCtrl', ['$scope', '$rootScope', 'Modalbox', function ($scope, $rootScope, Modalbox) {
$scope.closeBox = function(){
$rootScope.box.show = null;
}
}]);
| JavaScript | 0.000001 | @@ -2104,16 +2104,142 @@
x.show =
+ false;%0A $rootScope.box.description = null;%0A $rootScope.box.phone_numbers = null;%0A $rootScope.box.donation_location =
null;%0A
|
066abe6388980f31949e88eb7ad94f271a1104f3 | Fix OAuthError::toString During the refactor I forgot to update this method | src/errors/OAuthError.js | src/errors/OAuthError.js | /*
* BSD 3-Clause License
*
* Copyright (c) 2020, Mapcreator
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* OAuth error
*/
export default class OAuthError extends Error {
/**
* OAuth error code
* @type {String}
*/
error;
/**
* OAuth error response
* @param {String} error - OAuth error key
* @param {String} message - OAuth error message
*/
constructor (error, message = '') {
super(message);
this.error = String(error);
}
/**
* Displayable error string
* @returns {String} - error
*/
toString () {
let error = this._error;
if (error.includes('_')) {
error = error.replace('_', ' ').replace(/^./, x => x.toUpperCase());
}
if (this._message) {
return `${error}: ${this._message}`;
}
return error;
}
}
| JavaScript | 0.000014 | @@ -2064,17 +2064,16 @@
= this.
-_
error;%0A%0A
@@ -2194,25 +2194,24 @@
if (this.
-_
message) %7B%0A
@@ -2240,17 +2240,16 @@
$%7Bthis.
-_
message%7D
|
0c857c8611bb5dd4507bc81c2bae453164289da5 | Fix linking to engine's application route | addon/-private/link-to-component.js | addon/-private/link-to-component.js | import Ember from 'ember';
import { attributeMungingMethod } from './link-to-utils';
const {
LinkComponent,
getOwner,
get,
set
} = Ember;
export default LinkComponent.extend({
[attributeMungingMethod]() {
this._super(...arguments);
let owner = getOwner(this);
if (owner.mountPoint) {
// Prepend engine mount point to targetRouteName
let fullRouteName = owner.mountPoint + '.' + get(this, 'targetRouteName');
set(this, 'targetRouteName', fullRouteName);
// Prepend engine mount point to current-when if set
let currentWhen = get(this, 'current-when');
if (currentWhen !== null) {
let fullCurrentWhen = owner.mountPoint + '.' + currentWhen;
set(this, 'current-when', fullCurrentWhen);
}
}
}
});
| JavaScript | 0 | @@ -368,131 +368,64 @@
-let fullRouteName = owner.mountPoint + '.' + get(this, 'targetRouteName');%0A set(this, 'targetRouteName', fullRouteName
+this._prefixProperty(owner.mountPoint, 'targetRouteName'
);%0A%0A
@@ -493,26 +493,12 @@
-let currentWhen =
+if (
get(
@@ -522,74 +522,50 @@
en')
-;%0A if (currentWhen !== null) %7B%0A let fullCurrentWhen =
+ !== null) %7B%0A this._prefixProperty(
owne
@@ -580,36 +580,33 @@
oint
- + '.' +
+, '
current
-W
+-w
hen
+')
;%0A
se
@@ -605,67 +605,313 @@
- set(this, 'current-when', fullCurrentWhen)
+%7D%0A %7D%0A %7D,%0A%0A _prefixProperty(prefix, prop) %7B%0A let propValue = get(this, prop);%0A%0A let namespacedPropValue;%0A if (propValue === 'application') %7B%0A namespacedPropValue = prefix;%0A %7D else %7B%0A namespacedPropValue = prefix + '.' + propValue
;%0A
-
-
%7D
+%0A
%0A
-%7D
+set(this, prop, namespacedPropValue);
%0A %7D
|
edb27d9a0290b19994033aa1ba60ec1251859903 | Work around Webconverger issue | cck2/chrome/content/cck2-extensions-overlay.js | cck2/chrome/content/cck2-extensions-overlay.js | Components.utils.import("resource://gre/modules/Services.jsm");
Components.utils.import("resource://cck2/CCK2.jsm");
(function () {
var temp = {};
Components.utils.import("resource://cck2/Preferences.jsm", temp);
var Preferences = temp.Preferences;
let scope = {};
Services.scriptloader.loadSubScript("chrome://cck2/content/util.js", scope);
let {E, hide, errorCritical} = scope;
function startup()
{
try {
window.removeEventListener("load", startup, false);
var config = CCK2.getConfig();
if (config && "extension" in config && config.extension.hide) {
window.addEventListener("ViewChanged", function() {
var richlistitem = document.querySelector("richlistitem[value='" + config.extension.id + "']");
if (richlistitem)
richlistitem.hidden = true;
} , false)
}
var showDiscoverPane = Preferences.get("extensions.getAddons.showPane", true);
var xpinstallEnabled = Preferences.get("xpinstall.enabled", true);
if (!showDiscoverPane || !xpinstallEnabled) {
hide(gCategories.get("addons://discover/"));
hide(E("#search-list-empty button"));
hide(E("#addon-list-empty button"));
if (E("view-port") && E("view-port").selectedIndex == 0)
gViewController.loadView("addons://list/extension");
}
if (!xpinstallEnabled) {
hide(E("search-filter-remote"));
if (E("search-filter-radiogroup"))
E("search-filter-radiogroup").selectedIndex = 0; // Search in local addons
hide(E("utils-installFromFile-separator"));
hide(E("utils-installFromFile"));
}
} catch (e) {
errorCritical(e);
}
}
function shutdown()
{
window.removeEventListener("unload", shutdown, false);
}
window.addEventListener("load", startup, false);
window.addEventListener("unload", shutdown, false);
})();
| JavaScript | 0 | @@ -1203,18 +1203,31 @@
ex == 0)
-%0A%09
+ %7B%0A%09 try %7B%0A%09
gViewC
@@ -1273,16 +1273,81 @@
sion%22);%0A
+%09 %7D catch (ex) %7B%0A%09 // Ignore error from Webconverger%0A%09 %7D%0A%09%7D%0A
%7D%0A
|
b431acea482a7597a371146ac57742e5ba3e79c9 | fix spec | test/lib/route.js | test/lib/route.js | /**
* Route tests
*/
var koa = require('koa')
, http = require('http')
, request = require('supertest')
, router = require('../../lib/router')
, should = require('should')
, Route = require('../../lib/route');
describe('Route', function() {
it('supports regular expression route paths', function(done) {
var app = koa();
app.use(router(app));
app.get(/^\/blog\/\d{4}-\d{2}-\d{2}\/?$/i, function *(next) {
this.status = 204;
});
request(http.createServer(app.callback()))
.get('/blog/2013-04-20')
.expect(204)
.end(function(err) {
if (err) return done(err);
done();
});
});
it('composes multiple callbacks/middlware', function(done) {
var app = koa();
app.use(router(app));
app.get(
'/:category/:title',
function *(next) {
this.status = 500;
yield next;
},
function *(next) {
this.status = 204;
yield next;
}
);
request(http.createServer(app.callback()))
.get('/programming/how-to-node')
.expect(204)
.end(function(err) {
if (err) return done(err);
done();
});
});
describe('Route#match()', function() {
it('captures URL path parameters', function(done) {
var app = koa();
app.use(router(app));
app.get('/:category/:title', function *(next) {
this.should.have.property('params');
this.params.should.be.type('object');
this.params.should.have.property('category', 'match');
this.params.should.have.property('title', 'this');
this.status = 204;
done();
});
request(http.createServer(app.callback()))
.get('/match/this')
.expect(204)
.end(function(err) {
if (err) return done(err);
});
});
it('populates ctx.params with regexp captures', function(done) {
var app = koa();
app.use(router(app));
app.get(/^\/api\/([^\/]+)\/?/i, function *(next) {
this.should.have.property('params');
this.params.should.be.type('object');
this.params.should.have.property(0, '1');
yield next;
}, function *(next) {
this.should.have.property('params');
this.params.should.be.type('object');
this.params.should.have.property(0, '1');
this.status = 204;
});
request(http.createServer(app.callback()))
.get('/api/1')
.expect(204)
.end(function(err) {
if (err) return done(err);
done();
});
});
it('should populates ctx.params with regexp captures include undefiend', function(done) {
var app = koa();
app.use(router(app));
app.get(/^\/api(\/.+)?/i, function *(next) {
this.should.have.property('params');
this.params.should.be.type('object');
this.params.should.have.property(0, undefined);
yield next;
}, function *(next) {
this.should.have.property('params');
this.params.should.be.type('object');
this.params.should.have.property(0, undefined);
this.status = 204;
});
request(http.createServer(app.callback()))
.get('/api')
.expect(204)
.end(function(err) {
if (err) return done(err);
done();
});
})
});
describe('Route#url()', function() {
it('generates route URL', function() {
var route = new Route('/:category/:title', ['get'], function* () {}, 'books');
var url = route.url({ category: 'programming', title: 'how-to-node' });
url.should.equal('/programming/how-to-node');
url = route.url('programming', 'how-to-node');
url.should.equal('/programming/how-to-node');
});
it('escapes using encodeURIComponent()', function() {
var route = new Route('/:category/:title', ['get'], function *() {}, 'books');
var url = route.url({ category: 'programming', title: 'how to node' });
url.should.equal('/programming/how%20to%20node');
});
});
});
| JavaScript | 0.000001 | @@ -2526,23 +2526,16 @@
it('
-should
populate
|
f3c09436e592f2c6c6133fdbc42298da4c8dcc7a | remove tests for language and tag not specified | test/lib/utils.js | test/lib/utils.js | var rewire = require('rewire'),
expect = require('chai').expect,
path = require('path'),
utils = rewire('../../lib/utils');
utils.__set__('fs', { readFileSync: function(path) { return path; } });
var IMAGE_PREFIX = utils.__get__('IMAGE_PREFIX');
describe('Utils', function() {
describe('.formatImage()', function() {
context('when a repository is specified', function() {
var language = 'ruby',
tag = 'latest',
formated = utils.formatImage('grounds', language, tag);
it('formats image name with repository prefix', function() {
var expected = 'grounds/'+IMAGE_PREFIX+'-'+language+':'+tag;
expect(formated).to.equal(expected);
});
});
context('when no repository is specified', function() {
var language = 'java',
tag = '1.0.0',
formated = utils.formatImage('', language, tag);
it('formats image name without repository prefix', function() {
expect(formated).to.equal(IMAGE_PREFIX+'-'+language+':'+tag);
});
});
context('when no language is specified', function() {
var formated = utils.formatImage('grounds', '', 'latest');
expectEmptyString(formated);
});
context('when no tag is specified', function() {
var formated = utils.formatImage('grounds', 'ruby', '');
expectEmptyString(formated);
});
});
describe('.formatCmd()', function() {
var formated = utils.formatCmd('puts "Hello world\\n\\r\\t"\r\n\t');
it('returns an escaped string', function() {
var escapedString = 'puts "Hello world\\\\n\\\\r\\\\t"\\r\\n\\t';
expect(formated).to.equal(escapedString);
});
context('when code is not specified', function() {
var formated = utils.formatCmd();
expectEmptyString(formated);
});
});
function expectEmptyString(formated) {
it('returns an empty string', function() {
expect(formated).to.equal('');
});
}
describe('.formatStatus()', function() {
it('returns a signed integer (range -128 to 127)', function() {
var statusTable = [0, 1, 128, 254, 255],
statusExpected = [0, 1, -128, -2, -1];
for (var i in statusTable) {
var formated = utils.formatStatus(statusTable[i]),
expected = statusExpected[i];
expect(formated).to.equal(expected);
}
});
});
});
| JavaScript | 0 | @@ -1151,377 +1151,8 @@
%7D);
-%0A%0A context('when no language is specified', function() %7B%0A var formated = utils.formatImage('grounds', '', 'latest');%0A%0A expectEmptyString(formated);%0A %7D);%0A%0A context('when no tag is specified', function() %7B%0A var formated = utils.formatImage('grounds', 'ruby', '');%0A%0A expectEmptyString(formated);%0A %7D);
%0A
|
9bd6a58691c8842261b43a1a2a41dcd75adc5951 | Replace querySelector(":scope > :frist-child") children[0] in PreferenceDialog | src/component/PreferenceDialog.js | src/component/PreferenceDialog.js |
(() => {
"use strict";
var doc = document.currentScript.ownerDocument;
class PreferenceDialog extends window.jikkyo.Modal {
createdCallback() {
super.createdCallback();
this.width = 500;
this.height = 340;
this.preference = null;
this.appendStyle(document.importNode(doc.querySelector("#style").content, true));
this.appendContent(document.importNode(doc.querySelector("#content").content, true));
this._modePrefs = [];
this._initPrefCb = [];
this._savePrefCb = [];
this._tabs = this.content.querySelector("#tabs");
this._prefs = this.content.querySelector("#prefs");
var prefc = this.content.querySelectorAll(".pref");
Array.from(prefc).forEach(c => {
this.addModePreference(c, c.dataset.title, null, null, true);
}, this);
this.content.querySelector("#ok").addEventListener("click", (() => {
this.hide();
}).bind(this));
}
show() {
var at = this._tabs.querySelector(".active");
if (at) at.classList.remove("active");
at = this._prefs.querySelector(".pref.active");
if (at) at.classList.remove("active");
at = this._tabs.querySelector(":scope > :first-child");
if (at) at.classList.add("active");
at = this._prefs.querySelector(":scope > :first-child");
if (at) at.classList.add("active");
var pr = this.preference;
if (pr) {
this._modePrefs.forEach((p, i) => this._initPrefCb[i](p, pr), this);
}
super.show();
}
hide() {
var pr = this.preference;
if (pr) {
this._modePrefs.forEach((p, i) => this._savePrefCb[i](p, pr), this);
}
pr.save();
super.hide();
}
addModePreference(element, title, initCb, saveCb, builtin) {
if (!element) return;
var tab = document.createElement("li");
tab.textContent = title;
tab.addEventListener("click", (() => {
var active = this._prefs.querySelector(".active");
if (active) active.classList.remove("active");
element.classList.add("active");
this._tabs.querySelector(".active").classList.remove("active");
tab.classList.add("active");
}).bind(this));
this._tabs.appendChild(tab);
element.classList.add("pref");
this._prefs.appendChild(element);
if (!builtin) {
this._modePrefs.push(element);
if (initCb) this._initPrefCb.push(initCb);
if (saveCb) this._savePrefCb.push(saveCb);
}
}
}
window.jikkyo.PreferenceDialog = document.registerElement("jikkyo-preference-dialog", {
prototype: PreferenceDialog.prototype
});
})();
| JavaScript | 0 | @@ -1189,46 +1189,19 @@
abs.
-querySelector(%22:scope %3E :first-child%22)
+children%5B0%5D
;%0A
@@ -1267,46 +1267,19 @@
efs.
-querySelector(%22:scope %3E :first-child%22)
+children%5B0%5D
;%0A
|
269ca76ae0c8143c4cf3cc56610611454131c627 | remove unused var | src/components/AboutPage/index.js | src/components/AboutPage/index.js | import React from 'react'
import { Button, Col, Row } from 'react-bootstrap'
import { setDocumentTitle } from '../../helpers'
import './@AboutPage.css'
export default class AboutPage extends React.Component {
render () {
setDocumentTitle('About')
return (
<div className={'AboutPage__root'}>
<section className={'AboutPage__section'}>
<div className={'container'}>
<Row>
<Col>
<h1 className={'AboutPage__section-heading'}>A New Open Data Exploration Experience</h1>
<div className={'AboutPage__section-body'}>
<p>The Open Data Explorer is designed to make finding and understanding open data easier.</p>
<p>The Explorer gives you a way to:</p>
<ul>
<li> quickly access the City of San Francisco's open data catalog,</li>
<li> visually understand a dataset's underlying structure,</li>
<li> easily access a dataset's metadata,</li>
<li> test underlying assumptions about a dataset, and</li>
<li> determine if a dataset is a candidate for further analysis</li>
</ul>
<p>It's also an open source project, meaning you can see the <a href='https://github.com/DataSF/open-data-explorer'>source code and contribute if you like</a>.</p>
</div>
</Col>
</Row>
</div>
</section>
<section className={'AboutPage__section'}>
<div className={'container'}>
<Row>
<Col>
<h2 className={'AboutPage__section-heading'}>We're in Beta!</h2>
<div className={'AboutPage__section-body'}>
<p>We're shaking out bugs, tuning the application and gathering information on new features. We would love your input making the Explorer better.</p>
<p>You can help us anytime by giving offering your feedback. Use the feedback button at the top if you have an issue to report or an idea! You can read about changes we make, and bugs we fix in the project <a href='https://github.com/DataSF/open-data-explorer/blob/develop/CHANGELOG.md'>CHANGELOG</a></p>
<p><strong>Want to get more involved?</strong> Join the beta program below.</p>
</div>
</Col>
</Row>
</div>
</section>
<section className={'AboutPage__section'}>
<div className={'container'}>
<Row>
<Col>
<h2 className={'AboutPage__section-heading'}>Join the Beta Program</h2>
<div className={'AboutPage__section-body'}>
<p>As a member of the beta program, you'll get:</p>
<ul>
<li>product change updates from the development team,</li>
<li>opportunities to help the team test new features,</li>
<li>opportunities to give input on future features, and</li>
<li>lots of appreciation from the DataSF team for all your help</li>
</ul>
<p>You can participate at whatever level you have time for by doing one or all of the following:</p>
<ul>
<li><strong>Use the Explorer as much as you can.</strong> Explore your favorite open datasets. We’ll be logging bugs and anonymous usage data automatically to help make the Explorer better!</li>
<li><strong>Use the feedback button in the application.</strong> Have an idea? Found a really problematic bug? Click on the feedback button in the navigation bar to tell us more.</li>
<li><strong>Participate in feature testing and other feedback opportunities.</strong> We’ll let you know when these opportunities are available. No pressure, but we’ll make these as fun and rewarding as we can.</li>
</ul>
<div className={'AboutPage__join-beta-program'}>
<a href={'http://eepurl.com/c1r3Jv'} className={'btn btn-primary AboutPage__join-beta-program-button'} bsStyle={'primary'}>Join the beta program today!</a>
</div>
</div>
</Col>
</Row>
</div>
</section>
</div>
)
}
}
/*
<section className={'AboutPage__section'}>
<div className={'container'}>
<Row>
<Col>
<h2 className={'AboutPage__section-heading'}>Need a Demo?</h2>
<div className={'AboutPage__section-body'}>
<p>Watch the quick video below for a 2 minute getting started demo.</p>
<p>Video...</p>
</div>
</Col>
</Row>
</div>
</section>
*/
| JavaScript | 0.000089 | @@ -31,16 +31,8 @@
rt %7B
- Button,
Col
|
cde20171dae65a724d4acb96dd927778a68f88b6 | Remove a “trick babel” hack in analytics | app/jsx/Department/DepartmentFilterBox.js | app/jsx/Department/DepartmentFilterBox.js | import ComboBox from 'compiled/widget/ComboBox'
import DepartmentRouter from '../Department/DepartmentRouter'
export default class DepartmentFilterBox extends ComboBox {
constructor(model) {
{
// Hack: trick Babel/TypeScript into allowing this before super.
if (false) { super(); }
let thisFn = (() => { return this; }).toString();
let thisName = thisFn.match(/_this\d*/)[0];
eval(`${thisName} = this;`);
}
this.model = model
// add a router tied to the model
this.router = new DepartmentRouter(this.model)
// construct combobox
super(this.model.get('filters').models, {
value: filter => filter.get('id'),
label: filter => filter.get('label'),
selected: this.model.get('filter').get('id')
})
// connect combobox to model
this.on('change', this.push)
this.model.on('change:filter', this.pull)
}
// #
// Push the current value of the combobox to the URL
push = filter => this.router.select(filter.get('fragment'))
// #
// Pull the current value from the model to the combobox
pull = () => this.select(this.model.get('filter').get('id'))
}
| JavaScript | 0.000004 | @@ -191,263 +191,212 @@
) %7B%0A
-%0A %7B%0A
-
//
-Hack: trick Babel/TypeScript into allowing this before super.%0A if (false) %7B super(); %7D%0A let thisFn = (() =%3E %7B return this; %7D).toString();%0A let thisName = thisFn.match(/_this%5Cd*/)%5B0%5D;%0A eval(%60$%7BthisName%7D = this;%60);
+construct combobox%0A super(model.get('filters').models, %7B%0A value: filter =%3E filter.get('id'),%0A label: filter =%3E filter.get('label'),%0A selected: model.get('filter').get('id')
%0A %7D
-%0A
+)
%0A
@@ -510,223 +510,8 @@
l)%0A%0A
- // construct combobox%0A super(this.model.get('filters').models, %7B%0A value: filter =%3E filter.get('id'),%0A label: filter =%3E filter.get('label'),%0A selected: this.model.get('filter').get('id')%0A %7D)%0A
%0A
|
5d3007b1de31baa2e3a2a3e651a3583f1b0c4230 | Make composite children work | src/components/StaticGoogleMap.js | src/components/StaticGoogleMap.js | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Async from 'react-promise';
import invariant from 'invariant';
import MarkerStrategy from '../strategies/marker';
import PathStrategy from '../strategies/path';
import MarkerGroupStrategy from '../strategies/markergroup';
import PathGroupStrategy from '../strategies/pathgroup';
import DirectionStrategy from '../strategies/direction/index';
import MapStrategy from '../strategies/map';
class StaticGoogleMap extends Component {
static propTypes = {
as: PropTypes.oneOfType([PropTypes.element, PropTypes.string]),
onGenerate: PropTypes.func,
rootURL: PropTypes.string,
size: PropTypes.string.isRequired,
scale: PropTypes.oneOf([1, 2, 4, '1', '2', '4']),
format: PropTypes.oneOf([
'png',
'png8',
'png32',
'gif',
'jpg',
'jpg-baseline',
]),
maptype: PropTypes.oneOf(['roadmap', 'satellite', 'terrain', 'hybrid']),
language: PropTypes.string,
region: PropTypes.string,
visible: PropTypes.string,
style: PropTypes.string,
center: PropTypes.string,
zoom: PropTypes.string,
client: PropTypes.string,
apiKey: PropTypes.string,
signature: PropTypes.string,
channel: PropTypes.string,
};
static defaultProps = {
as: 'img',
scale: 1,
format: 'png',
rootURL: 'https://maps.googleapis.com/maps/api/staticmap',
apiKey: '',
maptype: 'roadmap',
};
buildParts(children, props) {
return React.Children.map(children, Child => {
switch (Child.type.name) {
case 'Marker':
return MarkerStrategy(Child, props);
case 'MarkerGroup':
return MarkerGroupStrategy(Child, props);
case 'Path':
return PathStrategy(Child, props);
case 'PathGroup':
return PathGroupStrategy(Child, props);
case 'Direction':
return DirectionStrategy(Child, props);
default:
return null;
}
});
}
render() {
const { children, onGenerate, as: Component, ...props } = this.props;
const {
rootURL,
size,
zoom,
scale,
style,
center,
format,
client,
region,
visible,
channel,
maptype,
language,
signature,
apiKey,
...componentProps
} = props;
invariant(size, 'size property is not set');
invariant(
children,
'Component must have `Marker`, `Path` or `Direction` child'
);
const childrenUrlParts = this.buildParts(children, props) || [];
const mainUrlParts = MapStrategy(props);
const urlParts = Promise.all(childrenUrlParts).then(
parts => `${mainUrlParts}&${parts.filter(part => part).join('&')}`
);
return (
<Async
promise={urlParts}
then={URL => {
if (onGenerate) {
onGenerate(URL);
}
return <Component {...componentProps} src={URL} />;
}}
catch={err => (
console.error(err), <span>Image generation failed.</span>
)}
/>
);
}
}
export default StaticGoogleMap;
| JavaScript | 0.000004 | @@ -465,16 +465,151 @@
es/map';
+%0Aimport %7B%0A isStatelessComponent,%0A renderStatelessComponent,%0A isClassComponent,%0A renderClassComponent,%0A%7D from '../strategies/utils';
%0A%0Aclass
@@ -1665,17 +1665,17 @@
ildren,
-C
+c
hild =%3E
@@ -1672,24 +1672,96 @@
child =%3E %7B%0A
+ if (!React.isValidElement(child)) %7B%0A return null;%0A %7D%0A%0A
switch
@@ -1762,17 +1762,17 @@
switch (
-C
+c
hild.typ
@@ -1828,33 +1828,33 @@
MarkerStrategy(
-C
+c
hild, props);%0A
@@ -1908,33 +1908,33 @@
erGroupStrategy(
-C
+c
hild, props);%0A
@@ -1974,33 +1974,33 @@
rn PathStrategy(
-C
+c
hild, props);%0A
@@ -2050,33 +2050,33 @@
thGroupStrategy(
-C
+c
hild, props);%0A
@@ -2134,17 +2134,17 @@
trategy(
-C
+c
hild, pr
@@ -2166,16 +2166,477 @@
efault:%0A
+ const componentType = child.type;%0A%0A if (isStatelessComponent(componentType)) %7B%0A return this.buildParts(%0A renderStatelessComponent(componentType, %7B ...child.props %7D),%0A props%0A );%0A %7D%0A%0A if (isClassComponent(componentType)) %7B%0A return this.buildParts(%0A renderClassComponent(componentType, %7B ...child.props %7D),%0A props%0A );%0A %7D%0A%0A
|
ee3173356e1f69da6e16cbd183ed445bf3f035c0 | fix fetchmark | www/js/lib/brandmark.js | www/js/lib/brandmark.js | var brandmark = null;
function fetch_mark(callback) {
$.get("../img/brandmark-grouped.svg", function(data) {
brandmark = data.documentElement;
if (typeof callback === 'function') {
callback();
}
});
}
function generateMark() {
console.log($('.logo-wrapper'));
$('.logo-wrapper').each(function (i, e) {
var mark = make_number_mark($('blockquote').text());
if (mark) {
$(this).replaceWith(mark);
}
});
}
function swap_color(e) {
var e_class = $(e).attr('class');
if (e_class == 'st0') {
$(e).attr('class', '');
} else {
$(e).attr('class', 'st0');
}
}
function make_number_mark(n) {
if (!brandmark) {
return;
}
var new_mark = brandmark.cloneNode(true);
var groups = $(new_mark).find('g');
var elems = $(new_mark).find('polygon, path');
var rng = new Math.seedrandom(n);
var swapProb = rng.quick();
// start from orange
elems.not('.st0, .st1').attr('class', 'st0');
// swap with black according to swapProb
elems.each(function(i, e) {
if (rng.quick() < swapProb) {
swap_color(e);
}
});
groups.each(function (i, e) {
$(e).css('fill-opacity', rng.quick());
});
var div = document.createElement("div");
div.className = "logo-wrapper";
div.innerHTML = new XMLSerializer().serializeToString(new_mark);
return div;
}
| JavaScript | 0.000001 | @@ -52,15 +52,34 @@
) %7B%0A
-%09$.get(
+ $.ajax(%7B%0A url:
%22../
@@ -105,16 +105,33 @@
ed.svg%22,
+%0A success:
functio
@@ -140,18 +140,28 @@
data) %7B%0A
-%09%09
+
brandmar
@@ -186,18 +186,28 @@
lement;%0A
-%09%09
+
if (type
@@ -240,28 +240,84 @@
) %7B%0A
-%09%09%09callback();%0A%09%09%7D%0A%09
+ callback();%0A %7D%0A %7D,%0A dataType: 'xml'
%7D);%0A
@@ -382,18 +382,20 @@
per'));%0A
-%09%09
+
$('.logo
@@ -428,19 +428,22 @@
i, e) %7B%0A
-%09%09%09
+
var ma
@@ -509,19 +509,22 @@
mark) %7B%0A
-%09%09%09
+
$(
@@ -558,18 +558,20 @@
%7D%0A
-%09%09
+
%7D);%0A%7D%0A%0Af
@@ -594,17 +594,18 @@
or(e) %7B%0A
-%09
+
var e_cl
@@ -630,17 +630,18 @@
lass');%0A
-%09
+
if (e_cl
@@ -652,26 +652,28 @@
== 'st0') %7B%0A
-%09%09
+
$(e).attr('c
@@ -684,17 +684,18 @@
', '');%0A
-%09
+
%7D else %7B
@@ -695,18 +695,20 @@
else %7B%0A
-%09%09
+
$(e).att
@@ -726,17 +726,18 @@
'st0');%0A
-%09
+
%7D%0A%7D%0A%0Afun
@@ -802,17 +802,18 @@
rn;%0A %7D%0A
-%09
+
var new_
@@ -843,25 +843,26 @@
ode(true);%0A%0A
-%09
+
var groups =
@@ -885,17 +885,18 @@
d('g');%0A
-%09
+
var elem
@@ -931,25 +931,26 @@
n, path');%0A%0A
-%09
+
var rng = ne
@@ -971,17 +971,18 @@
dom(n);%0A
-%09
+
var swap
@@ -998,25 +998,26 @@
g.quick();%0A%0A
-%09
+
// start fro
@@ -1025,17 +1025,18 @@
orange%0A
-%09
+
elems.no
@@ -1074,17 +1074,18 @@
st0');%0A%0A
-%09
+
// swap
@@ -1117,17 +1117,18 @@
wapProb%0A
-%09
+
elems.ea
@@ -1147,18 +1147,20 @@
i, e) %7B%0A
-%09%09
+
if (rng.
@@ -1185,11 +1185,14 @@
) %7B%0A
-%09%09%09
+
swap
@@ -1206,19 +1206,23 @@
e);%0A
-%09%09%7D%0A%09
+ %7D%0A
%7D);%0A%0A
-%09
+
grou
@@ -1251,10 +1251,12 @@
) %7B%0A
-%09%09
+
$(e)
@@ -1294,15 +1294,17 @@
));%0A
-%09
+
%7D);%0A%0A
-%09
+
var
@@ -1340,17 +1340,18 @@
%22div%22);%0A
-%09
+
div.clas
@@ -1374,17 +1374,18 @@
apper%22;%0A
-%09
+
div.inne
@@ -1445,9 +1445,10 @@
k);%0A
-%09
+
retu
|
8115982e17ebcddb60169f1772b57cf7516f7568 | Remove log statements. | app/scripts/directives/vn-price-search.js | app/scripts/directives/vn-price-search.js | 'use strict';
/**
* @ngdoc directive
* @name vnToolboxCommonApp.directive:vnPriceSearch
* @description
* # vnPriceSearch
*/
angular.module('Volusion.toolboxCommon')
.directive('vnPriceSearch', ['vnProductParams', function (vnProductParams) {
return {
templateUrl: 'vn-faceted-search/vn-price-search.html',
restrict : 'AE',
scope : {
queryProducts: '&'
},
link : function postLink(scope) {
scope.searchByPrice = function (event) {
vnProductParams.setMinPrice(scope.minPrice);
vnProductParams.setMaxPrice(scope.maxPrice);
scope.$watch(
function() {
return vnProductParams.getMinPrice();
},
function(min) {
scope.minPrice = min;
}
);
scope.$watch(
function() {
return vnProductParams.getMaxPrice();
},
function(min) {
scope.maxPrice = min;
}
);
vnProductParams.setMinPrice(scope.minPrice);
vnProductParams.setMaxPrice(scope.maxPrice);
if (event.which === 13) {
console.log('enter detected running a product query');
scope.queryProducts();
console.log('log prodParams from price directive after query run: ', vnProductParams.getParamsObject());
}
};
}
};
}]);
| JavaScript | 0 | @@ -1034,200 +1034,28 @@
%09%09%09%09
-console.log('enter detected running a product query');%0A%09%09%09%09%09%09scope.queryProducts();%0A%09%09%09%09%09%09console.log('log prodParams from price directive after query run: ', vnProductParams.getParamsObject()
+scope.queryProducts(
);%0A%09
|
0bfb068b6fa2a75b7346534359956f4850d5b75b | fix invalid prop node.type to Props | addons/info/src/components/Props.js | addons/info/src/components/Props.js | import React from 'react';
import PropTypes from 'prop-types';
import PropVal from './PropVal';
const stylesheet = {
propStyle: {},
propNameStyle: {},
propValueStyle: {},
};
export default function Props(props) {
const { maxPropsIntoLine, maxPropArrayLength, maxPropObjectKeys, maxPropStringLength } = props;
const nodeProps = props.node.props;
const defaultProps = props.node.type.defaultProps;
if (!nodeProps || typeof nodeProps !== 'object') {
return <span />;
}
const { propValueStyle, propNameStyle } = stylesheet;
const names = Object.keys(nodeProps).filter(
name =>
name[0] !== '_' &&
name !== 'children' &&
(!defaultProps || nodeProps[name] !== defaultProps[name])
);
const breakIntoNewLines = names.length > maxPropsIntoLine;
const endingSpace = props.singleLine ? ' ' : '';
const items = [];
names.forEach((name, i) => {
items.push(
<span key={name}>
{breakIntoNewLines ? <span><br /> </span> : ' '}
<span style={propNameStyle}>{name}</span>
{/* Use implicit true: */}
{(!nodeProps[name] || typeof nodeProps[name] !== 'boolean') &&
<span>
=
<span style={propValueStyle}>
<PropVal
val={nodeProps[name]}
maxPropObjectKeys={maxPropObjectKeys}
maxPropArrayLength={maxPropArrayLength}
maxPropStringLength={maxPropStringLength}
/>
</span>
</span>}
{i === names.length - 1 && (breakIntoNewLines ? <br /> : endingSpace)}
</span>
);
});
return <span>{items}</span>;
}
Props.defaultProps = {
singleLine: false,
};
Props.propTypes = {
node: PropTypes.shape({
props: PropTypes.object,
type: PropTypes.node.isRequired,
}).isRequired,
singleLine: PropTypes.bool,
maxPropsIntoLine: PropTypes.number.isRequired,
maxPropObjectKeys: PropTypes.number.isRequired,
maxPropArrayLength: PropTypes.number.isRequired,
maxPropStringLength: PropTypes.number.isRequired,
};
| JavaScript | 0.000004 | @@ -1740,86 +1740,12 @@
pes.
-shape(%7B%0A props: PropTypes.object,%0A type: PropTypes.node.isRequired,%0A %7D)
+node
.isR
|
6ea852fedf6120bb51f30314b0a8bdb2d21e1066 | Change case for data size // Resolve #3 | app/scripts/filters/embedded-formatter.js | app/scripts/filters/embedded-formatter.js | /**
* Copyright 2014-2016 Ivan Kravets <me@ikravets.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function() {
'use strict';
angular.module('siteApp')
.filter('embeddedFormatter', embeddedFormatter);
function embeddedFormatter() {
return function(value, toFormat) {
switch (toFormat) {
case 'frequency':
value = (value / 1000000) + ' MHz';
break;
case 'size':
if (value % 1024 === 0) {
value /= 1024;
} else {
value = Math.round(value / 1024 * 10) / 10;
}
value += ' Kb';
break;
}
return value;
};
}
})();
| JavaScript | 0 | @@ -1110,10 +1110,10 @@
= '
-Kb
+kB
';%0A
|
8e0d43c67d7df26bde922377cbaff19e0774a5d6 | Add custom children support to DialogHeader | src/Dialog/DialogHeader.js | src/Dialog/DialogHeader.js | import React, {PureComponent} from 'react'
import PropTypes from 'prop-types'
import classNames from 'classnames'
class DialogHeader extends PureComponent {
static displayName = 'DialogHeader'
static propTypes = {
children: PropTypes.node,
className: PropTypes.string,
}
render() {
const {
children,
className,
...otherProps,
} = this.props
const cssClasses = classNames('mdc-dialog__header', className)
return (
<header
{...otherProps}
className={cssClasses}
>
{React.isValidElement(children) ? children : (
<h2 className="mdc-dialog__header__title">{children}</h2>
)}
</header>
)
}
}
export default DialogHeader
| JavaScript | 0 | @@ -276,20 +276,467 @@
string,%0A
+ title: PropTypes.node,%0A %7D%0A%0A _renderTitle() %7B%0A const %7Btitle%7D = this.props%0A if (title) %7B%0A if (React.isValidElement(title)) %7B%0A const cssClasses = classNames(%0A 'mdc-dialog__header__title',%0A title.props.className%0A )%0A return React.cloneElement(title, %7B%0A className: cssClasses,%0A %7D)%0A %7D%0A return (%0A %3Ch2 className=%22mdc-dialog__header__title%22%3E%7Btitle%7D%3C/h2%3E%0A )%0A %7D%0A
%7D%0A
-
%0A rende
@@ -786,16 +786,29 @@
ssName,%0A
+ title,%0A
..
@@ -1009,131 +1009,46 @@
%7B
-React.isValidElement(children) ? children : (%0A %3Ch2 className=%22mdc-dialog__header__title%22%3E%7Bchildren%7D%3C/h2%3E%0A )
+this._renderTitle()%7D%0A %7Bchildren
%7D%0A
|
cb351f8e56dd18aedda6e5526d1287999066663f | add main.appFont to be bached | src/helpers/serialize.js | src/helpers/serialize.js | import getSubset from './getSubset';
import toJson from './toJson';
export default function serialize(storage) {
return {
...storage,
put: (key, state, cb) => {
const data = getSubset(toJson(state), ['main.appLocale', 'main.writeDelay']);
return storage.put(key, data, cb);
}
};
}
| JavaScript | 0.000001 | @@ -227,16 +227,32 @@
Locale',
+ 'main.appFont',
'main.w
|
fd737426de42cee7b1147419bf8e793fe0c67e04 | add pagination params for elastic search api | nodegeqe/WebServer/routes/app/posts.js | nodegeqe/WebServer/routes/app/posts.js | var express = require('express');
var router = express.Router();
var netHelpers = just_include('netHelpers');
var ES_HOST = ''
var ES_PORT = 9200
/*
Get posts based on a bounding box and optinal text query
example: curl -H "Content-Type: application/json" -XPOST http://localhost:3000/app/posts/bin -d '{
"boundingPoly": [
{"lat": 41.462,"lng": -81.697},
{"lat": 41.462, "lng": -81.69800000000001},
{"lat": 41.461,"lng": -81.69800000000001},
{"lat": 41.461,"lng": -81.697}
],
"query_string": "The first rule of fight club is"
}'
*/
router.post('/bin', function (req, res) {
var query = { "query": {"filtered": {}}}
query["query"]["filtered"]["query"] = getMatchQuery( req.body.query_string )
query["query"]["filtered"]["filter"] = getGeoPolygonFilter( req.body.boundingPoly)
netHelpers.performAjaxRequest(ES_HOST, ES_PORT, '/geqe/post/_search', 'POST',query,function (resultObject) {
if (resultObject.error) {
res.status(resultObject.error.status).send(resultObject.error.message);
return;
}
res.status(200).send(resultObject);
})
});
/**
* Query all points within the result set
* post body example: {"query_string": "hello world", "resultset": resultsetObject}
*/
router.post('/resultset', function (req, res) {
var resultset = req.body.resultset
var query_string = req.body.query_string
var query = { "query": {"filtered": {}}}
query["query"]["filtered"]["query"] = getMatchQuery( query_string )
// generate a filter for each are in the results
var filters = []
for (var i in resultset["bingroups"]){
for (var j in resultset["bingroups"][i]["bins"]){
var bin = resultset["bingroups"][i]["bins"][j]
filters.push(getGeoPolygonFilter(bin.boundingPoly))
}
}
query["query"]["filtered"]["filter"] = {"bool": { "should" : filters}}
netHelpers.performAjaxRequest(ES_HOST, ES_PORT, '/geqe/post/_search', 'POST',query,function (resultObject) {
if (resultObject.error) {
res.status(resultObject.error.status).send(resultObject.error.message);
return;
}
res.status(200).send(resultObject);
})
});
/**
* Query all points within the result set
* post body example: {"query_string": "hello world", "sitelist": sitelistObject}
*/
router.post('/sitelist', function (req, res) {
var sitelist = req.body.sitelist
var query_string = req.body.query_string
var query = { "query": {"filtered": {}}}
query["query"]["filtered"]["query"] = getMatchQuery( query_string )
// generate a filter for each are in the results
var filters = []
for (var i in sitelist["sites"]){
var site = sitelist["sites"][i]
var points = getGeoPoints(site.lats,site.lons)
filters.push(getGeoPolygonFilter(points))
}
query["query"]["filtered"]["filter"] = {"bool": { "should" : filters}}
netHelpers.performAjaxRequest(ES_HOST, ES_PORT, '/geqe/post/_search', 'POST',query,function (resultObject) {
if (resultObject.error) {
res.status(resultObject.error.status).send(resultObject.error.message);
return;
}
res.status(200).send(resultObject);
})
});
module.exports = router;
/// Helper fucntions
/**
* Return the elastic search api geo_polygon_filter for the given list of points
* @param points list of geo points [{lat: , lng: },..]
* @returns elastic search filter object
*/
function getGeoPolygonFilter(points){
var coordinates = []
for (var i in points){
coordinates.push( [ points[i].lng, points[i].lat] )
}
// close the polygon
coordinates.push( [ points[0].lng, points[0].lat] )
var filter = {
"geo_shape": {
"location": {
"shape":{
"type": "polygon",
"coordinates" : [coordinates]
}
}
}
}
return filter
}
/**
* Given arrays of lats and lons reutrn a list of GeoPoint objects
* @param lats
* @param lons
*/
function getGeoPoints(lats,lons){
var points = []
if (lats.length != lons.length) {
throw new Error("Geo arrays of unequal length.")
}
for (var i in lats){
points.push({lng: lons[i], lat: lats[i]})
}
return points
}
/**
* Return a elastic search match query for a query string
* @param query_string
* @returns {undefined}
*/
function getMatchQuery(query_string){
var query = undefined;
if (query_string && query_string != ""){
query = {
"match" : {
"message" : {
"query" : query_string,
"operator" : "or"
}
}
}
} else {
query = {"match_all": { } }
}
return query
} | JavaScript | 0 | @@ -120,18 +120,36 @@
HOST = '
+scc.silverdale.dev
'%0A
-
var ES_P
@@ -328,16 +328,58 @@
n -d '%7B%0A
+ %22from%22: 0,%0A %22size%22: 100,%0A
@@ -763,32 +763,138 @@
filtered%22: %7B%7D%7D%7D%0A
+ if (req.body.from) query%5B%22from%22%5D = req.body.from%0A if (req.body.size) query%5B%22size%22%5D = req.body.size%0A
query%5B%22query
@@ -1670,32 +1670,138 @@
filtered%22: %7B%7D%7D%7D%0A
+ if (req.body.from) query%5B%22from%22%5D = req.body.from%0A if (req.body.size) query%5B%22size%22%5D = req.body.size%0A
query%5B%22query
@@ -2821,32 +2821,32 @@
y.query_string%0A%0A
-
var query =
@@ -2870,24 +2870,130 @@
ered%22: %7B%7D%7D%7D%0A
+ if (req.body.from) query%5B%22from%22%5D = req.body.from%0A if (req.body.size) query%5B%22size%22%5D = req.body.size%0A
query%5B%22q
|
1369d97ca2a12e8181be11143f89c68bf4656e8a | Use classNames in overview table header component | web/src/containers/page/overview/table/header.js | web/src/containers/page/overview/table/header.js | import React from 'react';
import { OVERVIEW_COLUMNS } from '../../../../misc/const';
export default function OverviewTableHeader() {
const header = OVERVIEW_COLUMNS.map((column, key) => {
const className = [
'col',
column[0]
].join(' ');
return <div className={className} key={key}>
<span className="text">{column[1]}</span>
</div>;
});
return <div className="row header">{header}</div>;
}
| JavaScript | 0 | @@ -20,17 +20,53 @@
react';%0A
+import classNames from 'classnames';
%0A
-
import %7B
@@ -206,22 +206,41 @@
NS.map((
+%5B
column
+Class, columnName%5D
, key) =
@@ -273,69 +273,37 @@
e =
-%5B%0A 'col',%0A column%5B0%5D%0A %5D.join(' '
+classNames('col', columnClass
);%0A%0A
@@ -401,11 +401,12 @@
lumn
-%5B1%5D
+Name
%7D%3C/s
|
2e245ba04f543662689d01250dda8af7b6e87b96 | Add new error | api/tests/unit/domain/errors_test.js | api/tests/unit/domain/errors_test.js | const {describe, it, expect} = require('../../test-helper');
const errors = require('../../../lib/domain/errors');
describe('Unit | Domain | Errors', () => {
it('should export a NotFoundError', () => {
expect(errors.NotFoundError).to.exist;
});
it('should export a InvalidTokenError', () => {
expect(errors.InvalidTokenError).to.exist;
});
it('should export a InvalidAuthorizationHeaders', () => {
expect(errors.InvalidAuthorizationHeaders).to.exist;
});
});
| JavaScript | 0.000002 | @@ -1,15 +1,16 @@
const %7B
+
describe
@@ -21,16 +21,17 @@
, expect
+
%7D = requ
|
72a3c0d2ded06f02e81c871a6ad1244f59fc9c42 | fix full-text search | api/controllers/SearchController.js | api/controllers/SearchController.js | import { get } from 'lodash/fp'
import { normalizePost, normalizeComment, uniqize } from '../../lib/util/normalize'
const userColumns = q => q.column('id', 'name', 'avatar_url')
const findCommunityIds = req => {
if (req.param('communityId')) {
return Promise.resolve([req.param('communityId')])
} else if (req.param('type') === 'communities' && req.param('moderated')) {
if (Admin.isSignedIn(req)) {
return Community.query().pluck('id')
} else {
return Membership.activeCommunityIds(req.session.userId, true)
}
} else {
return Promise.join(
Network.activeCommunityIds(req.session.userId),
Membership.activeCommunityIds(req.session.userId)
).then(ids => _(ids).flatten().uniq().value())
}
}
module.exports = {
autocomplete: function (req, res) {
var term = req.param('q').trim()
var resultType = req.param('type')
var sort, method, columns
switch (resultType) {
case 'posts':
method = Search.forPosts
sort = 'posts.created_at'
break
case 'communities':
method = Search.forCommunities
columns = ['id', 'name', 'avatar_url', 'slug']
break
case 'tags':
method = Search.forTags
columns = ['tags.id', 'name']
break
default:
method = Search.forUsers
if (term.startsWith('@')) {
term = term.slice(1)
} else if (term.startsWith('#')) {
method = Search.forTags
term = term.slice(1)
}
}
return findCommunityIds(req)
.then(ids => method({
communities: ids,
autocomplete: term,
limit: req.param('limit') || 10,
sort: sort
}).fetchAll({columns: columns}))
.then(rows => rows.map(row => row.pick('id', 'name', 'avatar_url', 'slug')))
.then(res.ok)
.catch(res.serverError)
},
showFullText: function (req, res) {
var term = req.param('q')
if (!term) return res.badRequest('expected a parameter named "q"')
var type = req.param('type')
var limit = req.param('limit')
var offset = req.param('offset')
var userId = req.session.userId
var items
return Membership.activeCommunityIds(userId)
.then(communityIds =>
FullTextSearch.searchInCommunities(communityIds, {term, type, limit, offset}))
.then(items_ => {
items = items_
var ids = _.transform(items, (ids, item) => {
var type = item.post_id ? 'posts'
: item.comment_id ? 'comments' : 'people'
if (!ids[type]) ids[type] = []
var id = item.post_id || item.comment_id || item.user_id
ids[type].push(id)
}, {})
return Promise.join(
ids.posts && Post.where('id', 'in', ids.posts).fetchAll({
withRelated: PostPresenter.relations(userId)
}),
ids.comments && Comment.where('id', 'in', ids.comments).fetchAll({
withRelated: [
{'user': userColumns},
{'post': q => q.column('id', 'type', 'name', 'user_id')},
{'post.user': userColumns},
{'post.relatedUsers': userColumns},
{'thanks.thankedBy': userColumns}
]
}),
ids.people && User.where('id', 'in', ids.people).fetchAll({
withRelated: 'tags'
}),
(posts, comments, people) =>
items.map(formatResult(posts, comments, people))
)
})
.then(results => ({items: results, total: get('0.total', items) || 0}))
.then(results => {
const buckets = {communities: [], people: []}
results.items.forEach(item => {
switch (item.type) {
case 'post':
normalizePost(item.data, buckets)
break
case 'comment':
normalizeComment(item.data, buckets)
break
}
})
uniqize(buckets)
return Object.assign(buckets, results)
})
.then(res.ok)
}
}
const formatResult = (posts, comments, people) => item => {
var result = {rank: item.rank}
if (item.user_id) {
result.type = 'person'
const person = people.find(p => p.id === item.user_id)
result.data = UserPresenter.presentForList(person)
} else if (item.post_id) {
result.type = 'post'
const post = posts.find(p => p.id === item.post_id)
result.data = PostPresenter.present(post)
} else {
result.type = 'comment'
const comment = comments.find(c => c.id === item.comment_id)
result.data = comment.toJSON()
}
return result
}
| JavaScript | 0 | @@ -2,19 +2,40 @@
mport %7B
-get
+flatten, flow, get, uniq
%7D from
@@ -194,16 +194,184 @@
_url')%0A%0A
+const fetchAllCommunityIds = userId =%3E%0A Promise.join(%0A Network.activeCommunityIds(userId),%0A Membership.activeCommunityIds(userId)%0A ).then(flow(flatten, uniq))%0A%0A
const fi
@@ -753,181 +753,47 @@
urn
-Promise.join(%0A Network.activeCommunityIds(req.session.userId),%0A Membership.activeCommunityIds(req.session.userId)%0A ).then(ids =%3E _(ids).flatten().uniq().value()
+fetchAllCommunityIds(req.session.userId
)%0A
@@ -2206,33 +2206,24 @@
return
-Membership.active
+fetchAll
Communit
|
7248fc412f712d10a4fcd34c66ab839516e40236 | use CommonJS | src/plugins/Redux.js | src/plugins/Redux.js | const Plugin = require('./Plugin')
export default class Redux extends Plugin {
constructor (core, opts) {
super(core, opts)
this.type = 'state-sync'
this.id = 'Redux'
this.title = 'Redux Emitter'
if (typeof opts.action === 'undefined') {
throw new Error('action option is not defined')
}
if (typeof opts.dispatch === 'undefined') {
throw new Error('dispatch option is not defined')
}
this.opts = opts
this.handleStateUpdate = this.handleStateUpdate.bind(this)
}
handleStateUpdate (prev, state, patch) {
this.opts.dispatch(this.opts.action(prev, state, patch)) // this dispatches a redux event with the new state
}
install () {
this.core.emitter.on('core:state-update', this.handleStateUpdate)
this.handleStateUpdate({}, this.core.state, this.core.state) // set the initial redux state
}
uninstall () {
this.core.emitter.off('core:state-update', this.handleStateUpdate)
}
}
| JavaScript | 0.000007 | @@ -33,22 +33,24 @@
')%0A%0A
-export default
+module.exports =
cla
|
b5b3b89da2efa98e7bc9d3f5f84a2ea64c56f28e | Fix spawn check | src/programs/city.js | src/programs/city.js | 'use strict'
class City extends kernel.process {
constructor (...args) {
super(...args)
this.priority = PRIORITIES_CITY
}
getDescriptor () {
return this.data.room
}
main () {
if (!Game.rooms[this.data.room] || !Game.rooms[this.data.room].controller.my) {
Room.removeCity(this.data.room)
return this.suicide()
}
this.room = Game.rooms[this.data.room]
const spawns = this.room.find(FIND_MY_SPAWNS)
if (spawns.length < 0) {
this.launchChildProcess('gethelp', 'empire_expand', {
'colony': this.data.room,
'recover': true
})
return
}
this.launchChildProcess('spawns', 'spawns', {
'room': this.data.room
})
this.launchChildProcess('defense', 'city_defense', {
'room': this.data.room
})
this.launchChildProcess('reboot', 'city_reboot', {
'room': this.data.room
})
// If the room isn't planned launch the room layout program, otherwise launch construction program
if (!this.room.getLayout().isPlanned()) {
this.launchChildProcess('layout', 'city_layout', {
'room': this.data.room
})
} else {
this.launchChildProcess('construct', 'city_construct', {
'room': this.data.room
})
}
// Launch fillers
let options = {}
if (this.room.getRoomSetting('PURE_CARRY_FILLERS')) {
options['carry_only'] = true
options['energy'] = Math.max(Math.min(1600, this.room.energyCapacityAvailable / 2), 400)
}
const fillerQuantity = this.room.getRoomSetting('ADDITIONAL_FILLERS') ? 4 : 2
this.launchCreepProcess('fillers', 'filler', this.data.room, fillerQuantity, options)
// Launch mining if all level 2 extensions are build.
if (this.room.energyCapacityAvailable > 500) {
this.launchChildProcess('mining', 'city_mine', {
'room': this.data.room
})
}
const mineCount = this.room.getRoomSetting('REMOTE_MINES')
const lastAdd = qlib.events.getTimeSinceEvent('addmine')
if (mineCount && lastAdd >= 2000) {
let remoteMines = this.room.getMines()
if (remoteMines.length < mineCount) {
const cpuUsage = sos.lib.monitor.getPriorityRunStats(PRIORITIES_CREEP_DEFAULT)
if (cpuUsage && cpuUsage['long'] <= 1.25) {
const mine = this.room.selectNextMine()
if (mine) {
this.room.addMine(mine)
remoteMines = this.room.getMines()
}
}
}
let mineRoomName
for (mineRoomName of remoteMines) {
this.launchChildProcess(`mine_${mineRoomName}`, 'city_mine', {
'room': this.data.room,
'mine': mineRoomName
})
}
}
// Launch mineral extraction
if (this.room.isEconomyCapable('EXTRACT_MINERALS') && this.room.getRoomSetting('EXTRACT_MINERALS')) {
// Note that once the program starts it won't stop until the minerals are mined out regardless of economic
// conditions.
const mineral = this.room.find(FIND_MINERALS)[0]
if (mineral.mineralAmount > 0 && !mineral.ticksToRegeneration) {
this.launchChildProcess('extraction', 'city_extract', {
'room': this.data.room
})
}
}
// Launch upgraders
if (this.room.isEconomyCapable('UPGRADE_CONTROLLERS')) {
let upgraderQuantity = this.room.getRoomSetting('UPGRADERS_QUANTITY')
if (this.room.isEconomyCapable('EXTRA_UPGRADERS')) {
upgraderQuantity += 2
}
if (this.room.isEconomyCapable('MORE_EXTRA_UPGRADERS')) {
upgraderQuantity += 2
}
if (this.room.controller.level >= 8) {
upgraderQuantity = 1
}
this.launchCreepProcess('upgraders', 'upgrader', this.data.room, upgraderQuantity, {
'priority': 5
})
}
if (this.room.controller.isTimingOut()) {
this.launchCreepProcess('eupgrader', 'upgrader', this.data.room, 1, {
priority: 1,
energy: 200
})
}
// Launch scouts to map out neighboring rooms
if (this.room.getRoomSetting('SCOUTS')) {
this.launchCreepProcess('scouts', 'spook', this.data.room, 1, {
'priority': 4
})
}
}
}
module.exports = City
| JavaScript | 0 | @@ -466,16 +466,17 @@
length %3C
+=
0) %7B%0A
|
429a4e352679c0148cc984200ef0783eca768698 | fix lint | src/crypto/verification/QRCode.js | src/crypto/verification/QRCode.js | /*
Copyright 2018 New Vector Ltd
Copyright 2020 The Matrix.org Foundation C.I.C.
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.
*/
/**
* QR code key verification.
* @module crypto/verification/QRCode
*/
import {VerificationBase as Base} from "./Base";
import {
newKeyMismatchError,
newUserMismatchError,
} from './Error';
export const SHOW_QR_CODE_METHOD = "m.qr_code.show.v1";
export const SCAN_QR_CODE_METHOD = "m.qr_code.scan.v1";
/**
* @class crypto/verification/QRCode/ReciprocateQRCode
* @extends {module:crypto/verification/Base}
*/
export class ReciprocateQRCode extends Base {
static factory(...args) {
return new ReciprocateQRCode(...args);
}
static get NAME() {
return "m.reciprocate.v1";
}
async _doVerification() {
if (!this.startEvent) {
// TODO: Support scanning QR codes
throw new Error("It is not currently possible to start verification" +
"with this method yet.");
}
const targetUserId = this.startEvent.getSender();
if (!this.userId) {
console.log("Asking to confirm user ID");
this.userId = await new Promise((resolve, reject) => {
this.emit("confirm_user_id", {
userId: targetUserId,
confirm: resolve, // takes a userId
cancel: () => reject(newUserMismatchError()),
});
});
} else if (targetUserId !== this.userId) {
throw newUserMismatchError({
expected: this.userId,
actual: targetUserId,
});
}
if (this.startEvent.getContent()['secret'] !== this.request.encodedSharedSecret) {
throw newKeyMismatchError();
}
// If we've gotten this far, verify the user's master cross signing key
const xsignInfo = this._baseApis.getStoredCrossSigningForUser(this.userId);
if (!xsignInfo) throw new Error("Missing cross signing info");
const masterKey = xsignInfo.getId("master");
const masterKeyId = `ed25519:${masterKey}`;
const keys = {[masterKeyId]: masterKey};
const devices = (await this._baseApis.getStoredDevicesForUser(this.userId)) || [];
const targetDevice = devices.find(d => d.deviceId === this.request.estimatedTargetDevice.deviceId);
if (!targetDevice) throw new Error("Device not found, somehow");
keys[`ed25519:${targetDevice.deviceId}`] = targetDevice.getFingerprint();
if (this.request.requestingUserId === this.request.receivingUserId) {
delete keys[masterKeyId];
}
await this._verifyKeys(this.userId, keys, (keyId, device, keyInfo) => {
const targetKey = keys[keyId];
if (!targetKey) throw newKeyMismatchError();
if (keyInfo !== targetKey) {
console.error("key ID from key info does not match");
throw newKeyMismatchError();
}
// if (keyId !== masterKeyId) {
// console.error("key id doesn't match");
// throw newKeyMismatchError();
// }
// if (device.deviceId !== targetKey) {
// console.error("master key does not match device ID");
// throw newKeyMismatchError();
// }
for (const deviceKeyId in device.keys) {
if (!deviceKeyId.startsWith("ed25519")) continue;
const deviceTargetKey = keys[deviceKeyId];
if (!deviceTargetKey) throw newKeyMismatchError();
// if (deviceKeyId !== masterKeyId) {
// console.error("device key ID does not match");
// throw newKeyMismatchError();
// }
if (device.keys[deviceKeyId] !== deviceTargetKey) {
console.error("master key does not match");
throw newKeyMismatchError();
}
}
// Otherwise it is probably fine
});
}
}
| JavaScript | 0.000013 | @@ -2791,16 +2791,37 @@
ind(d =%3E
+ %7B%0A return
d.devic
@@ -2871,16 +2871,27 @@
deviceId
+;%0A %7D
);%0A
@@ -3523,365 +3523,8 @@
%7D%0A
- // if (keyId !== masterKeyId) %7B%0A // console.error(%22key id doesn't match%22);%0A // throw newKeyMismatchError();%0A // %7D%0A // if (device.deviceId !== targetKey) %7B%0A // console.error(%22master key does not match device ID%22);%0A // throw newKeyMismatchError();%0A // %7D%0A
@@ -3768,205 +3768,8 @@
();%0A
- // if (deviceKeyId !== masterKeyId) %7B%0A // console.error(%22device key ID does not match%22);%0A // throw newKeyMismatchError();%0A // %7D%0A
|
828c69cd4b9f44cebbaa6f9eed06f53821786fab | update LazyImage | src/LazyImage/LazyImage.js | src/LazyImage/LazyImage.js | /**
* @file LazyImage component
* @author liangxiaojun(liangxiaojun@derbysoft.com)
*/
import React, {Component, createRef} from 'react';
import PropTypes from 'prop-types';
import debounce from 'lodash/debounce';
import classNames from 'classnames';
import eventOn from 'dom-helpers/events/on';
import eventOff from 'dom-helpers/events/off';
import CircularLoading from '../CircularLoading';
import Event from '../_vendors/Event';
class LazyImage extends Component {
constructor(props, ...restArgs) {
super(props, ...restArgs);
this.wrapper = createRef();
this.state = {
imageState: 0
};
}
scrollHandler = debounce(() => {
if (this.state.imageState > 0 || !this.wrapperEl
|| this.wrapperEl.getBoundingClientRect().top > window.innerHeight) {
return;
}
const {onImageLoadStart} = this.props;
let result;
if (onImageLoadStart) {
result = onImageLoadStart();
}
if (result === false) {
return;
}
this.setState({
imageState: 1
}, () => {
const image = new Image();
Event.addEvent(image, 'load', e => {
this.setState({
imageState: 2
}, () => {
const {onImageLoaded} = this.props;
onImageLoaded && onImageLoaded(e);
});
});
image.src = this.props.src;
});
}, 250);
componentDidMount() {
this.wrapperEl = this.wrapper && this.wrapper.current;
eventOn(this.props.scrollEl, 'scroll', this.scrollHandler);
this.scrollHandler();
}
componentWillUnmount() {
eventOff(this.props.scrollEl, 'scroll', this.scrollHandler);
}
render() {
const {className, style, src, alt, loadingWidth, loadingHeight, width, height, placeholder} = this.props,
{imageState} = this.state,
lazyImageClassName = classNames('lazy-image', {
[className]: className
}),
lazyImageStyle = {
...style,
width: imageState === 2 ? width : loadingWidth,
height: imageState === 2 ? height : loadingHeight
},
placeholderClassName = classNames('lazy-image-placeholder', {
hidden: imageState === 2
});
return (
<div ref={this.wrapper}
className={lazyImageClassName}
style={lazyImageStyle}>
<img className="lazy-image-img"
src={imageState === 2 ? src : ''}
alt={alt}
width={width}
height={height}/>
<div className={placeholderClassName}>
{
placeholder ?
{placeholder}
:
<CircularLoading className="lazy-image-loading"/>
}
</div>
</div>
);
}
}
LazyImage.propTypes = {
/**
* The CSS class name of the root element.
*/
className: PropTypes.string,
/**
* Override the styles of the root element.
*/
style: PropTypes.object,
/**
* Image src url.
*/
src: PropTypes.string.isRequired,
/**
* Image alt text.
*/
alt: PropTypes.string,
/**
* Loading width.
*/
loadingWidth: PropTypes.number,
/**
* Loading height.
*/
loadingHeight: PropTypes.number,
/**
* Image width.
*/
width: PropTypes.number,
/**
* Image height.
*/
height: PropTypes.number,
/**
* Image placeholder.
*/
placeholder: PropTypes.any,
scrollEl: PropTypes.object,
/**
* Image load start callback.
*/
onImageLoadStart: PropTypes.func,
/**
* Image load end callback.
*/
onImageLoaded: PropTypes.func
};
LazyImage.defaultProps = {
alt: '',
placeholder: '',
scrollEl: document,
loadingWidth: 100,
loadingHeight: 100
};
export default LazyImage;
| JavaScript | 0 | @@ -387,24 +387,81 @@
rLoading';%0A%0A
+import LazyLoadStatus from '../_statics/LazyLoadStatus';%0A
import Event
@@ -521,24 +521,61 @@
omponent %7B%0A%0A
+ static Status = LazyLoadStatus;%0A%0A
construc
@@ -713,21 +713,38 @@
-imageState: 0
+status: LazyLoadStatus.PENDING
%0A
@@ -824,22 +824,39 @@
ate.
-imageState %3E 0
+status %3E LazyLoadStatus.PENDING
%7C%7C
@@ -1239,21 +1239,38 @@
-imageState: 1
+status: LazyLoadStatus.LOADING
%0A
@@ -1431,21 +1431,37 @@
-imageState: 2
+status: LazyLoadStatus.FINISH
%0A
@@ -2142,26 +2142,22 @@
%7B
-imageState
+status
%7D = this
@@ -2177,34 +2177,141 @@
-lazyImageC
+isFinish = status === LazyLoadStatus.FINISH;%0A%0A return (%0A %3Cdiv ref=%7Bthis.wrapper%7D%0A c
lassName
= class
@@ -2294,35 +2294,34 @@
className
- =
+=%7B
classNames('lazy
@@ -2347,16 +2347,21 @@
+
%5BclassNa
@@ -2391,12 +2391,19 @@
-%7D),%0A
+ %7D)%7D%0A
@@ -2414,27 +2414,25 @@
-lazyImageStyle = %7B%0A
+ style=%7B%7B%0A
@@ -2473,16 +2473,21 @@
+
width: i
mage
@@ -2482,31 +2482,23 @@
width: i
-mageState === 2
+sFinish
? width
@@ -2526,24 +2526,29 @@
+
height: imag
@@ -2544,31 +2544,23 @@
eight: i
-mageState === 2
+sFinish
? heigh
@@ -2593,283 +2593,14 @@
-%7D,%0A%0A placeholderClassName = classNames('lazy-image-placeholder', %7B%0A hidden: imageState === 2%0A %7D);%0A%0A return (%0A %3Cdiv ref=%7Bthis.wrapper%7D%0A className=%7BlazyImageClassName%7D%0A style=%7BlazyImageStyle
+ %7D
%7D%3E%0A%0A
@@ -2678,23 +2678,15 @@
c=%7Bi
-mageState === 2
+sFinish
? s
@@ -2836,28 +2836,102 @@
me=%7B
-placeholderClassName
+classNames('lazy-image-placeholder', %7B%0A hidden: isFinish%0A %7D)
%7D%3E%0A
@@ -3017,17 +3017,16 @@
-%7B
placehol
@@ -3028,17 +3028,16 @@
ceholder
-%7D
%0A
|
1d4af2502ae5bcb9b122e86aa5958d7f01356403 | fix signpost formatting | app/assets/javascripts/d3_helpers.js | app/assets/javascripts/d3_helpers.js | /*global d3 */
var formatDate = d3.time.format.utc("%B %d, %Y"),
formatMonthYear = d3.time.format.utc("%B %Y"),
formatYear = d3.time.format.utc("%Y"),
formatDateTime = d3.time.format.utc("%d %b %Y %H:%M UTC"),
formatTime = d3.time.format.utc("%H:%M UTC"),
formatWeek = d3.time.format.utc("%U"),
formatHour = d3.time.format.utc("%H"),
formatNumber = d3.format(",d"),
formatFixed = d3.format(",.0f"),
formatPercent = d3.format(",.0%");
function numberWithDelimiter(number) {
if(number !== 0) {
return formatFixed(number);
} else {
return null;
}
}
// Format file size into human-readable format
function numberToHumanSize(bytes) {
var thresh = 1000;
if(bytes < thresh) { return bytes + ' B'; }
var units = ['KB','MB','GB','TB','PB'];
var u = -1;
do { bytes /= thresh; ++u; } while(bytes >= thresh);
return bytes.toFixed(1) + ' ' + units[u];
}
// construct date object from date parts
function datePartsToDate(date_parts) {
var len = date_parts.length;
// not in expected format
if (len === 0 || len > 3) { return null; }
// turn numbers to strings and pad with 0
for (var i = 0; i < len; ++i) {
if (date_parts[i] < 10) {
date_parts[i] = "0" + date_parts[i];
} else {
date_parts[i] = "" + date_parts[i];
}
}
// convert to date, workaround for different time zones
var timestamp = Date.parse(date_parts.join('-') + 'T12:00');
return new Date(timestamp);
}
// format date
function formattedDate(date) {
var timestamp = new Date(Date.parse(date));
switch (date.length) {
case 4:
return formatYear(timestamp);
case 7:
return formatMonthYear(timestamp);
case 10:
return formatDate(timestamp);
default:
return formatDateTime(timestamp);
}
}
// pagination
function paginate(json, tag) {
if ((json.meta.page !== "") && json.meta.total_pages > 1) {
var prev = (json.meta.page > 1) ? "«" : null;
var next = (json.meta.page < json.meta.total_pages) ? "»" : null;
d3.select(tag).append("div")
.attr("id", "paginator")
.attr("class", "text-center");
$('#paginator').bootpag({
total: json.meta.total_pages,
page: json.meta.page,
maxVisible: 10,
href: json.href,
leaps: false,
prev: prev,
next: next
});
}
}
// link to individual work
function pathForWork(id) {
if (typeof id === "undefined") { return ""; };
if (id.substring(0, 15) === "http://doi.org/" ||
id.substring(0, 35) === "http://www.ncbi.nlm.nih.gov/pubmed/" ||
id.substring(0, 41) === "http://www.ncbi.nlm.nih.gov/pmc/works/PMC" ||
id.substring(0, 41) === "http://www.ncbi.nlm.nih.gov/pmc/works/PMC" ||
id.substring(0, 21) === "http://arxiv.org/abs/" ||
id.substring(0, 15) === "http://n2t.net/") {
return id.replace(/^https?:\/\//,'');
} else {
return id;
}
}
function signpostsToString(work, sources, source_id, sort) {
var name = "";
if (typeof source_id !== "undefined" && source_id !== "") {
name = source_id;
} else if (typeof sort !== "undefined" && sort !== "") {
name = sort;
}
if (name !== "") {
var source = sources.filter(function(d) { return d.id === name; })[0];
}
if (typeof source !== "undefined" && source !== "") {
var a = [source.title + ": " + formatFixed(work.events[name])];
} else {
var a = [];
}
var b = signpostsFromWork(work, sources, name);
if (b.length > 0) { a.push(b.join(" • ")); }
return a.join(" | ");
}
function signpostsFromWork(work, sources, name) {
var signposts = [],
source = {};
for (var key in work.events) {
source = sources.filter(function(d) { return d.id === key && d.id !== name; })[0];
if (typeof source !== "undefined" && source !== {}) {
signposts.push(source.title + ": " + formatFixed(work.events[name]));
}
}
return signposts;
}
function relationToString(work, sources, relation_types) {
var source = sources.filter(function(d) { return d.id === work.source_id; })[0];
if (typeof source == "undefined" || source === "") { source = {}; }
var relation_type = relation_types.filter(function(d) { return d.id === work.relation_type_id; })[0];
if (typeof relation_type == "undefined" || relation_type === "") { relation_type = {}; }
return [relation_type.title, " via " + source.title];
}
function metadataToString(work, work_types) {;
var containerTitleString = work["container-title"] ? " via " + work["container-title"] : "";
var work_type = work_types.filter(function(d) { return d.id === work.work_type_id; })[0];
if (typeof work_type == "undefined" || work_type === "") { work_type = { "title": "Work" }; }
return work_type.title + " published " + formattedDate(work.issued) + containerTitleString;
}
// construct author list from author object
function formattedAuthorList(authorList) {
authorList = authorList.map(function(d) { return formattedAuthor(d); });
switch (authorList.length) {
case 0:
case 1:
case 2:
return authorList.join(" & ");
case 3:
case 4:
return authorList.slice(0,-1).join(", ") + " & " + authorList[authorList.length - 1];
default:
return authorList.slice(0,3).join(", ") + ", <em>et al</em>";
}
}
// construct author object from author parts
function formattedAuthor(author) {
var given = (typeof author.given !== "undefined") ? author.given : "";
var family = (typeof author.family !== "undefined") ? author.family : "";
var name = [given, family].join(" ");
var name = (typeof author["ORCID"] !== "undefined") ? '<a href="/contributors/' + author["ORCID"].substring(7) + '">' + name + '</a>' : name;
return name;
}
function formattedState(state) {
if (state === "failed") {
return '<span class="label label-fatal">failed</span>';
} else {
return state;
}
}
| JavaScript | 0.000016 | @@ -3847,20 +3847,19 @@
.events%5B
-name
+key
%5D));%0A
|
100f2875bf77ef1494c547051e1962107254ab74 | add keyboard event | app/assets/scripts/components/app.js | app/assets/scripts/components/app.js | import React,{Component} from "react";
import {connect} from "react-redux";
import {bindActionCreators} from "redux";
import {foldersFetch} from "../actions/index";
import File from "../libs/file";
import $ from "jquery";
import jQuery from "jquery";
window.$ = $;
window.jQuery = jQuery;
class App extends Component {
constructor(props){
super(props);
this.state = {};
this.file = new File();
this.file.loadSetupFile(function (data){
props.foldersFetch(data.folders);
});
}
render() {
return (
<div className="component-app">
{this.props.children}
</div>
);
}
}
function mapStateToProps({}){
return {};
}
function mapDispatchToProps(dispatch){
return bindActionCreators({foldersFetch},dispatch);
}
export default connect (mapStateToProps,mapDispatchToProps)(App);
| JavaScript | 0.00001 | @@ -131,16 +131,32 @@
ersFetch
+,folderAdd,modal
%7D from %22
@@ -170,24 +170,24 @@
ons/index%22;%0A
-
import File
@@ -540,16 +540,193 @@
%7D);
+%0A%0A document.addEventListener('keyup', (e) =%3E %7B%0A if (e.shiftKey && e.keyCode == 65) %7B%0A props.modal(%22newFolder%22);%0A %7D%0A %7D, false);
%0A %7D%0A%0A
@@ -965,16 +965,16 @@
patch)%7B%0A
-
retu
@@ -1008,16 +1008,32 @@
ersFetch
+,folderAdd,modal
%7D,dispat
|
9bb157de771837903d4d819c0f33e914687e3f71 | fix : make pageRange flexible based on container width, keeping the pagination aligned horizontally. | app/containers/ProductsPage/index.js | app/containers/ProductsPage/index.js | /*
* FeaturePage
*
* List all the features
*/
import React from 'react';
import Helmet from 'react-helmet';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import { createStructuredSelector } from 'reselect';
import Dimensions from 'react-dimensions';
import { FaAngleLeft, FaAngleRight } from 'react-icons/lib/fa/';
import ContentList from 'components/ContentList';
import ProductTile from 'components/ProductTile';
import Pagination from 'components/Pagination';
import {
makeSelectProducts,
makeSelectLoading,
makeSelectError,
makeSelectProductBrand,
makeSelectCount,
makeSelectPage,
} from './selectors';
import * as productActions from './actions';
import { PER_PAGE } from './constants';
class ProductsPage extends React.Component { // eslint-disable-line react/prefer-stateless-function
componentDidMount() {
const { getProducts, productBrand, countProducts, page } = this.props;
getProducts(productBrand, page);
countProducts(productBrand);
}
showProducts(item) {
console.log(item);
}
handleChange(props) {
return (paginationPage) => {
const { getProducts, productBrand, setPage, page, pushState } = props;
if (paginationPage !== page) {
pushState(`/products/${productBrand}?page=${paginationPage}`);
setPage(paginationPage);
getProducts(productBrand, paginationPage);
}
};
}
render() {
const { loading, error, products, page, count, containerWidth } = this.props;
console.log(containerWidth);
const contentListProps = {
loading,
error,
component: ProductTile,
onClick: this.showProducts,
payload: products,
};
return (
<div>
<Helmet
title="Cellphone List"
meta={[
{ name: 'description', content: 'Cellphone list page contains list of cellphones from specific brand' },
]}
/>
<div className="row center-xs">
<div className="col-xs-11 col-sm-9 col-md-8 col-lg-8">
<ContentList {...contentListProps} />
</div>
</div>
{!loading && <Pagination
hideDisabled
pageRangeDisplayed={10}
firstPageText={'First'}
lastPageText={'Last'}
prevPageText={<FaAngleLeft size={20} />}
nextPageText={<FaAngleRight size={20} />}
activePage={page}
itemsCountPerPage={parseInt(PER_PAGE, 10)}
totalItemsCount={count}
onChange={this.handleChange(this.props)}
/>}
</div>
);
}
}
ProductsPage.propTypes = {
containerWidth: React.PropTypes.number,
loading: React.PropTypes.bool,
error: React.PropTypes.oneOfType([
React.PropTypes.object,
React.PropTypes.bool,
]),
products: React.PropTypes.oneOfType([
React.PropTypes.array,
React.PropTypes.bool,
]),
getProducts: React.PropTypes.func,
countProducts: React.PropTypes.func,
setPage: React.PropTypes.func,
productBrand: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.bool,
]),
page: React.PropTypes.number,
count: React.PropTypes.number,
pushState: React.PropTypes.func,
};
const mapDispatchToProps = {
getProducts: productActions.loadProducts,
countProducts: productActions.getProductsCount,
setPage: productActions.setPage,
pushState: push,
};
const mapStateToProps = createStructuredSelector({
productBrand: makeSelectProductBrand(),
products: makeSelectProducts(),
loading: makeSelectLoading(),
page: makeSelectPage(),
count: makeSelectCount(),
error: makeSelectError(),
});
const EnhancedProductsPage = Dimensions()(ProductsPage);
// Wrap the component to inject dispatch and state into it
export default connect(mapStateToProps, mapDispatchToProps)(EnhancedProductsPage);
| JavaScript | 0 | @@ -1519,31 +1519,51 @@
cons
-ole.log(containerWidth)
+t pageRange = containerWidth %3C= 400 ? 3 : 5
;%0A
@@ -2222,18 +2222,25 @@
played=%7B
-10
+pageRange
%7D%0A
|
7e73a113c209ada218b5bd1d4c30108b82aa814a | Add padding to circle grid | example/src/AnotherOne.js | example/src/AnotherOne.js | import React from 'react';
import {LayoutTransitionGroup} from '../../src/index';
class AnotherOne extends LayoutTransitionGroup {
state = {
config: 0,
};
config = (i) => {
return () => {
this.beginTransition((prevState) => ({
config: i,
}), [this.barRef, this.listRef], 250, 'cubic-bezier(0.64, 0.13, 0.05, 1.67)');
};
};
render() {
const config = this.state.config;
const config1 = config === 0;
const config2 = config === 1;
const count = config1 ? 5 : config2 ? 6 : 7;
const gridStyle = {
height: '240px',
width: '100%',
maxWidth: '300px',
margin: '0 auto',
display: 'flex',
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'center',
flexGrow: '3',
};
const horizontalStyle = {
width: '100%',
height: '80px',
display: 'flex',
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
};
const barStyle = {
height: '80px',
};
const childStyle = (i) => ({
width: '48px',
height: '48px',
borderRadius: '50%',
backgroundColor: 'rgb(230, 150, 0)',
margin: '16px',
});
const buttonHolder = {
backgroundColor: 'rgb(150, 200, 230)',
height: '64px',
display: 'flex',
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
};
const buttonStyle = {
height: '48px',
flexGrow: '1',
margin: '8px',
backgroundColor: 'white',
border: '0',
};
const verticalFlex = {
height: '75%',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
};
const pStyle = {
textAlign: 'center',
flexGrow: config1 ? 0 : config2 ? 2 : 4,
};
return (
<div>
<div style={buttonHolder}>
<button style={buttonStyle} onClick={this.config(0)}>0</button>
<button style={buttonStyle} onClick={this.config(1)}>1</button>
<button style={buttonStyle} onClick={this.config(2)}>2</button>
</div>
<div
style={horizontalStyle}
ref={(ref) => {
this.barRef = ref;
}}
>
<div style={{...barStyle, flexGrow: 1, backgroundColor: 'rgb(200, 0, 0)'}}></div>
<div style={{...barStyle, flexGrow: config1 ? 1 : config2 ? 5 : 1, backgroundColor: 'rgb(0, 200, 0)'}}></div>
<div style={{...barStyle, flexGrow: config1 ? 1 : config2 ? 5 : 10, backgroundColor: 'rgb(0, 0, 200)'}}></div>
</div>
<div
style={gridStyle}
ref={(ref) => {
this.listRef = ref;
}}
>
{[...Array(count).keys()].map((i) => <div style={childStyle(i)} key={i}></div>)}
</div>
</div>
);
}
}
export default AnotherOne;
| JavaScript | 0 | @@ -731,16 +731,89 @@
auto',%0A
+ paddingTop: config1 ? '20px' : config2 ? '100px' : ' 200px',%0A
|
4c840d29cbc07b2b03c603ade86137a32f804297 | Remove debugger. | app/assets/javascripts/histogram.js | app/assets/javascripts/histogram.js | var parseHistogram = function(infoHash) {
var dataset = []// = [{'x':0, 'y':0}];
var dateArray = [];
for (property in infoHash) {
if (infoHash.hasOwnProperty(property)) {
var d = new Date(d3.time.format("%Y-%m-%d").parse(infoHash[property].date.substring(0, 10)))
dateArray.push(d);
}
}
result = { };
for(i = dateArray.length - 1; i >= 0; --i) {
if(!result[dateArray[i]]) {
result[dateArray[i]] = 0;
}
++result[dateArray[i]];
}
for (property in result){
dataset.push({'x':Date.parse(property.toString()), 'y':result[property]});
}
debugger;
//Add zeros to close off graph for fill
dataset.push({'x':dataset[dataset.length-1].x, 'y': 0});
dataset.unshift({'x': dataset[0].x, 'y': 0})
displayHistogram(dataset);
}
var displayHistogram = function(lineData){
var vis = d3.select("#js-histogram")
.append("svg:svg")
.attr("width", 1000)
.attr("height", 500)
.append("svg:g"),
WIDTH = 1000,
HEIGHT = 500,
MARGINS = {
top: 20,
right: 20,
bottom: 20,
left: 50
},
xRange = d3.scale.linear().range([MARGINS.left, WIDTH - MARGINS.right]).domain([d3.min(lineData, function (d) {
return d.x;
}),
d3.max(lineData, function (d) {
return d.x;
})
]),
yRange = d3.scale.linear().range([HEIGHT - MARGINS.top, MARGINS.bottom]).domain([d3.min(lineData, function (d) {
return d.y;
}),
d3.max(lineData, function (d) {
return d.y;
})
]),
xAxis = d3.svg.axis()
.scale(xRange)
.tickSize(5)
.tickSubdivide(true)
.tickFormat(function(d) { return d3.time.format('%b %d')(new Date(d)); }),
yAxis = d3.svg.axis()
.scale(yRange)
.tickSize(5)
.orient("left")
.tickSubdivide(true);
vis.append("svg:g")
.attr("class", "x axis")
.attr("transform", "translate(0," + (HEIGHT - MARGINS.bottom) + ")")
.call(xAxis);
vis.append("svg:g")
.attr("class", "y axis")
.attr("transform", "translate(" + (MARGINS.left) + ",0)")
.call(yAxis);
var lineFunc = d3.svg.line()
.x(function (d) {
return xRange(d.x);
})
.y(function (d) {
return yRange(d.y);
})
.interpolate('linear');
vis.append("svg:path")
.attr("d", lineFunc(lineData))
.attr("stroke", "blue")
.attr("stroke-width", 2)
.attr("fill", "none");
}
| JavaScript | 0.000001 | @@ -604,20 +604,8 @@
%7D%0A
- debugger;%0A
//
@@ -748,16 +748,19 @@
y': 0%7D)%0A
+ %0A
displa
|
8966e86fd49844b8c9335f1ecbc794970e802ac7 | replace cmd component with textarea & modify style (#1003) | web/src/components/stageTemplate/add/Config.js | web/src/components/stageTemplate/add/Config.js | import PropTypes from 'prop-types';
import SectionCard from '@/components/public/sectionCard';
import MakeField from '@/components/public/makeField';
import { defaultFormItemLayout } from '@/lib/const';
import { Field, FieldArray } from 'formik';
import { Form, Input, Row, Col, Button } from 'antd';
const InputField = MakeField(Input);
const FormItem = Form.Item;
const Fragment = React.Fragment;
const ConfigSection = props => {
const { values } = props;
return (
<SectionCard title={intl.get('config')}>
<FieldArray
name="spec.pod.inputs.arguments"
render={() => (
<Fragment>
{_.get(values, 'spec.pod.inputs.arguments', []).map(
(field, index) => (
<Field
key={field.name}
label={intl.get(`template.form.config.${field.name}`)}
name={`spec.pod.inputs.arguments.${index}.value`}
component={InputField}
required
/>
)
)}
</Fragment>
)}
/>
<FieldArray
name="spec.pod.spec.containers"
render={() => (
<div>
{_.get(values, 'spec.pod.spec.containers', []).map((a, index) => (
<Fragment key={index}>
<FormItem label={intl.get('env')} {...defaultFormItemLayout}>
<FieldArray
name={`spec.pod.spec.containers.${index}.env`}
render={arrayHelpers => (
<div>
{_.get(
values,
`spec.pod.spec.containers.${index}.env`,
[]
).length > 0 && (
<Row gutter={16}>
<Col span={11}>{intl.get('key')}</Col>
<Col span={11}>{intl.get('value')}</Col>
</Row>
)}
{_.get(
values,
`spec.pod.spec.containers.${index}.env`,
[]
).map((a, i) => (
<Row key={i} gutter={16}>
<Col span={11}>
<Field
key={a.name}
name={`spec.pod.spec.containers.${index}.env.${i}.name`}
component={InputField}
hasFeedback
/>
</Col>
<Col span={11}>
<Field
key={a.value}
name={`spec.pod.spec.containers.${index}.env.${i}.value`}
component={InputField}
hasFeedback
/>
</Col>
<Col span={2}>
<Button
type="circle"
icon="delete"
onClick={() => arrayHelpers.remove(i)}
/>
</Col>
</Row>
))}
<Button
ico="plus"
onClick={() => {
arrayHelpers.push({ name: '', value: '' });
}}
>
{intl.get('workflow.addEnv')}
</Button>
</div>
)}
/>
</FormItem>
</Fragment>
))}
</div>
)}
/>
</SectionCard>
);
};
ConfigSection.propTypes = {
values: PropTypes.object,
};
export default ConfigSection;
| JavaScript | 0 | @@ -295,16 +295,87 @@
antd';%0A%0A
+const %7B TextArea %7D = Input;%0Aconst TextareaField = MakeField(TextArea);%0A
const In
@@ -475,61 +475,314 @@
nst
-ConfigSection = props =%3E %7B%0A const %7B values %7D = props
+inputMap = %7B%0A image: %7B%0A component: InputField,%0A props: %7B%7D,%0A %7D,%0A cmd: %7B%0A component: TextareaField,%0A props: %7B%0A style: %7B%0A height: 100,%0A %7D,%0A %7D,%0A %7D,%0A%7D;%0A%0Aconst ConfigSection = props =%3E %7B%0A const %7B values %7D = props;%0A const args = _.get(values, 'spec.pod.inputs.arguments', %5B%5D)
;%0A
@@ -956,59 +956,26 @@
%7B
-_.get(values, 'spec.pod.inputs.arguments', %5B%5D).map(
+args.length %3E 0 &&
%0A
@@ -985,16 +985,25 @@
+args.map(
(field,
@@ -1238,34 +1238,110 @@
component=%7B
-I
+i
nput
-Field
+Map%5Bfield.name%5D%5B'component'%5D%7D%0A %7B...inputMap%5Bfield.name%5D%5B'props'%5D
%7D%0A
@@ -1391,29 +1391,16 @@
)
-%0A
)%7D%0A
|
31a1db2b4090710016e886a645df3a826c5f32cc | Add CognitoIdentityServiceProvider into AWS when building it with webpack | src/deep-framework/scripts/aws.js | src/deep-framework/scripts/aws.js | const AWS = require('aws-sdk/global');
AWS.Lambda = require('aws-sdk/clients/lambda');
AWS.CognitoIdentity = require('aws-sdk/clients/cognitoidentity');
AWS.CognitoSync = require('aws-sdk/clients/cognitosync');
AWS.SQS = require('aws-sdk/clients/sqs');
module.exports = AWS;
| JavaScript | 0 | @@ -143,24 +143,120 @@
identity');%0A
+AWS.CognitoIdentityServiceProvider = require('aws-sdk/clients/cognitoidentityserviceprovider');%0A
AWS.CognitoS
|
a1b732a7a48568c4424f73085d0efebf0d7e1bf9 | fix CS title | src/components/calculatorSmall/presentation/CSlTitle.js | src/components/calculatorSmall/presentation/CSlTitle.js | 'use strict';
import React from 'react';
import PropTypes from 'prop-types'
import {connect} from 'react-redux'
class CalculatorSmallTitle extends React.Component {
constructor(props) {
super(props);
}
render() {
const {discount, calcTitleDiscount: ctd, calcTitle: ct} = this.props;
//have to chance this variables depends on conditions
let calcTitle;
//case when discount exist
if (discount !== 0) {
if (!!ctd) {
let title, subtitle;
//set custom title with discount
title = (ctd.substr(0, ctd.indexOf('%')) + discount * 100 + ctd.substr(ctd.indexOf('%')));
//check if subtitle exist
if (title.indexOf('.') !== -1) {
title = title.substr(0, title.indexOf('.') + 1);
subtitle = ctd.substr(ctd.indexOf('.') + 1);
}
calcTitle =
<div className="cs-title">
<div>{title}</div>
<div className="cs-title--sm">{subtitle}</div>
</div>
} else {
//set default title with discount
calcTitle =
<div className="cs-title">
<div className="cs-title__first-line">Your first order</div>
<div className="cs-title__second-line">
<span className="cs-title--dsc">{discount * 100}% off</span>
<span className="cs-title--sm">Limited time!</span>
</div>
</div>
}
}
//case when there is no any discount
else {
if (!!ct) {
//set custom title without discount
calcTitle =
<div className="cs-title">
{ct}
</div>
} else {
//set default title without discount
calcTitle =
<div className="cs-title">Get a quick estimate</div>
}
}
return (
<div>{calcTitle}</div>
)
}
}
CalculatorSmallTitle.propTypes = {
discount: PropTypes.number.isRequired,
};
//container to match redux state to component props and dispatch redux actions to callback props
const mapStateToProps = reduxState => {
return {
discount: reduxState.discount,
}
};
const mapDispatchToProps = dispatch => {
return {}
};
export default connect(mapStateToProps, mapDispatchToProps)(CalculatorSmallTitle);
| JavaScript | 0.999907 | @@ -2176,22 +2176,20 @@
-%3Cdiv%3E%7B
+
calcTitl
@@ -2185,31 +2185,24 @@
calcTitle
-%7D%3C/div%3E
%0A )%0A
|
21d95b5d598362e5a17bebe3ffd0326014f03e63 | fix prod checks | src/defaults/asyncLocalStorage.js | src/defaults/asyncLocalStorage.js | const genericSetImmediate = typeof setImmediate === 'undefined' ? global.setImmediate : setImmediate
const nextTick = process && process.nextTick ? process.nextTick : genericSetImmediate
const noStorage = process && process.env && process.env.NODE_ENV === 'production'
? () => { /* noop */ return null }
: () => {
console.error('redux-persist asyncLocalStorage requires a global localStorage object. Either use a different storage backend or if this is a universal redux application you probably should conditionally persist like so: https://gist.github.com/rt2zz/ac9eb396793f95ff3c3b')
return null
}
function hasLocalStorage () {
let storageExists
try {
storageExists = (typeof window === 'object' && !!window.localStorage)
if (storageExists) {
const testKey = 'redux-persist localStorage test'
// @TODO should we also test set and remove?
window.localStorage.getItem(testKey)
}
} catch (e) {
if (process && process.env && process.env.NODE_ENV === 'production') console.warn('redux-persist localStorage getItem test failed, persistence will be disabled.')
return false
}
return storageExists
}
function hasSessionStorage () {
try {
return typeof window === 'object' && typeof window.sessionStorage !== 'undefined'
} catch (e) { return false }
}
function getStorage (type) {
if (type === 'local') {
return hasLocalStorage()
? window.localStorage
: { getItem: noStorage, setItem: noStorage, removeItem: noStorage, getAllKeys: noStorage }
}
if (type === 'session') {
return hasSessionStorage()
? window.sessionStorage
: { getItem: noStorage, setItem: noStorage, removeItem: noStorage, getAllKeys: noStorage }
}
}
export default function (type, config) {
const deprecated = config && config.deprecated
let storage = getStorage(type)
return {
getAllKeys: function (cb) {
// warn if deprecated
if (deprecated) console.warn('redux-persist: ', deprecated)
return new Promise((resolve, reject) => {
try {
var keys = []
for (var i = 0; i < storage.length; i++) {
keys.push(storage.key(i))
}
nextTick(() => {
cb && cb(null, keys)
resolve(keys)
})
} catch (e) {
cb && cb(e)
reject(e)
}
})
},
getItem (key, cb) {
return new Promise((resolve, reject) => {
try {
var s = storage.getItem(key)
nextTick(() => {
cb && cb(null, s)
resolve(s)
})
} catch (e) {
cb && cb(e)
reject(e)
}
})
},
setItem (key, string, cb) {
return new Promise((resolve, reject) => {
try {
storage.setItem(key, string)
nextTick(() => {
cb && cb(null)
resolve()
})
} catch (e) {
cb && cb(e)
reject(e)
}
})
},
removeItem (key, cb) {
return new Promise((resolve, reject) => {
try {
storage.removeItem(key)
nextTick(() => {
cb && cb(null)
resolve()
})
} catch (e) {
cb && cb(e)
reject(e)
}
})
}
}
}
| JavaScript | 0 | @@ -202,34 +202,8 @@
ge =
- process && process.env &&
pro
@@ -932,34 +932,8 @@
cess
- && process.env && process
.env
@@ -934,33 +934,33 @@
ss.env.NODE_ENV
-=
+!
== 'production')
|
4beb743002beb6ee883dc113635e8ab1a301289e | Remove pre-binding in game_list | app/chrome/components/game_list.es6 | app/chrome/components/game_list.es6 |
import React from "react";
import classNames from "classnames";
let remote = window.require("remote");
let AppActions = remote.require("./metal/actions/app_actions")
class GameCell extends React.Component {
constructor() {
super();
this.view_game = this.view_game.bind(this);
this.download = this.download.bind(this);
}
render() {
let {game} = this.props;
let {title, cover_url, user} = game;
let has_cover = !!cover_url;
let style = {
backgroundImage: cover_url && `url('${cover_url}')`
};
return <div className="game_cell">
<div className="bordered">
<div className={classNames("game_thumb", {has_cover})} onClick={this.view_game} style={style}/>
</div>
<div className="game_title">{title}</div>
{user ?
<div className="game_author">{user.display_name}</div>
:''}
<div className="game_launch button" onClick={this.download}>
<span className="icon icon-install"/> Install
</div>
</div>;
}
// non-React methods
view_game() {
AppActions.view_game(this.props.game);
}
download() {
AppActions.download_queue({game: this.props.game});
}
}
class GameList extends React.Component {
render() {
let {games} = this.props;
if (!games) return <div/>;
return <div className="game_list">
{games.map(game => {
return <GameCell key={game.id} game={game}/>
})}
</div>;
}
}
export {GameList};
| JavaScript | 0 | @@ -207,138 +207,8 @@
t %7B%0A
- constructor() %7B%0A super();%0A this.view_game = this.view_game.bind(this);%0A this.download = this.download.bind(this);%0A %7D%0A%0A
re
@@ -548,19 +548,31 @@
nClick=%7B
-thi
+() =%3E AppAction
s.view_g
@@ -574,16 +574,22 @@
iew_game
+(game)
%7D style=
@@ -802,21 +802,47 @@
ck=%7B
-this.download
+() =%3E AppActions.download_queue(%7Bgame%7D)
%7D%3E%0A
@@ -928,174 +928,8 @@
%7D%0A%0A
- // non-React methods%0A %0A view_game() %7B%0A AppActions.view_game(this.props.game);%0A %7D%0A%0A download() %7B%0A AppActions.download_queue(%7Bgame: this.props.game%7D);%0A %7D%0A%0A
%7D%0A%0Ac
|
8c771f73c223a83625244f50f9c396bbb8c47455 | return scorer posttoserver deferred | examples/dscore/Scorer.js | examples/dscore/Scorer.js | define(['jquery','app/API','underscore','./computeD','./msgCat','./parcelMng'],function($,API,_,computeData,msgMan,parcelMng){
var Scorer = {};
//comment
$.extend(Scorer, {
/* Function: Void addSettings.
Input: settings object.
Output: set the settings in computeD object or msgCat according to input
Description: Settings for computeD or msgCat
*/
addSettings: function(type,Obj){
if (type =="compute"){
computeData.setComputeObject(Obj);
}else{
if (type =="message") msgMan.setMsgObject(Obj);
}
},
/* Function: Void init.
Input: none.
Output: none
Description: make sure console.log is safe among all browsers.
*/
init: function(){
console || (console = {});
console.log || (console.log = function(){});
},
/* Function: Void computeD.
Input: none.
Output: final score.
Description: Calculate the score returns an object that hold
the score an an error msg.
*/
computeD: function(){
Scorer.init();
computeData.setDataArray();
// console.log('started computeD');
// console.log(computeData);
// console.log(msgMan);
parcelMng.Init(computeData);
parcelMng.avgAll(computeData);
//parcelMng.diffAll(computeData);
parcelMng.varianceAll(computeData);
parcelMng.scoreAll(computeData);
var scoreObj = parcelMng.scoreData;
// console.log('the score from new scoree is: '+scoreObj.score );
//var oldScore = parcelMng.simulateOldCode(computeData);//for testing only
//console.log('the score from old scoree is: '+oldScore );
return scoreObj;
//return score.toFixed(2);
},
getInfo: function(){
//return computeData;
},
/* Function: Void postToServer.
Input: score, a message a key to be used.
Output: Ajax send to server.
Description: post to server the score and the message.
*/
postToServer: function(score,msg,scoreKey,msgKey){
var postSettings = computeData.postSettings;
var url = postSettings.url;
if (scoreKey == null || scoreKey == undefined) scoreKey = postSettings.score;
if (msgKey == null || msgKey == undefined) msgKey = postSettings.msg;
var data = {};
data[scoreKey] =score;
data[msgKey] = msg;
return $.post(url,JSON.stringify(data));
},
// get message according to user input
getFBMsg: function(DScore){
var msg = msgMan.getMsg(DScore);
return msg;
}
});
return Scorer;
});
| JavaScript | 0.000001 | @@ -2223,18 +2223,16 @@
data));%0A
-%0A%0A
%09%7D,%0A
|
cbc79e13a0e9c92b453a746892875258f0b8ff16 | fix percentage offset domain scale | examples/js/extensions.js | examples/js/extensions.js | var RenderControls = function(args) {
this.initialize = function() {
this.element = args.element;
this.graph = args.graph;
this.settings = this.serialize();
this.inputs = {
renderer: this.element.elements.renderer,
interpolation: this.element.elements.interpolation,
offset: this.element.elements.offset
};
this.element.addEventListener('change', function(e) {
this.settings = this.serialize();
if (e.target.name == 'renderer') {
this.setDefaultOffset(e.target.value);
}
this.syncOptions();
this.settings = this.serialize();
var config = {
renderer: this.settings.renderer,
interpolation: this.settings.interpolation
};
if (this.settings.offset == 'value') {
config.unstack = true;
config.offset = 'zero';
} else {
config.unstack = false;
config.offset = this.settings.offset;
}
this.graph.configure(config);
this.graph.render();
}.bind(this), false);
}
this.serialize = function() {
var values = {};
var pairs = $(this.element).serializeArray();
pairs.forEach( function(pair) {
values[pair.name] = pair.value;
} );
return values;
};
this.syncOptions = function() {
var options = this.rendererOptions[this.settings.renderer];
Array.prototype.forEach.call(this.inputs.interpolation, function(input) {
if (options.interpolation) {
input.disabled = false;
input.parentNode.classList.remove('disabled');
} else {
input.disabled = true;
input.parentNode.classList.add('disabled');
}
});
Array.prototype.forEach.call(this.inputs.offset, function(input) {
if (options.offset.filter( function(o) { return o == input.value } ).length) {
input.disabled = false;
input.parentNode.classList.remove('disabled');
} else {
input.disabled = true;
input.parentNode.classList.add('disabled');
}
}.bind(this));
};
this.setDefaultOffset = function(renderer) {
var options = this.rendererOptions[renderer];
if (options.defaults && options.defaults.offset) {
Array.prototype.forEach.call(this.inputs.offset, function(input) {
if (input.value == options.defaults.offset) {
input.checked = true;
} else {
input.checked = false;
}
}.bind(this));
}
};
this.rendererOptions = {
area: {
interpolation: true,
offset: ['zero', 'wiggle', 'expand', 'value'],
defaults: { offset: 'zero' }
},
line: {
interpolation: true,
offset: ['expand', 'value'],
defaults: { offset: 'value' }
},
bar: {
interpolation: false,
offset: ['zero', 'wiggle', 'expand', 'value'],
defaults: { offset: 'zero' }
},
scatterplot: {
interpolation: false,
offset: ['value'],
defaults: { offset: 'value' }
}
};
this.initialize();
};
| JavaScript | 0 | @@ -774,16 +774,135 @@
'zero';%0A
+%09%09%09%7D else if (this.settings.offset == 'expand') %7B%0A%09%09%09%09config.unstack = true;%0A%09%09%09%09config.offset = this.settings.offset;%0A
%09%09%09%7D els
@@ -1357,25 +1357,24 @@
s.renderer%5D;
-%09
%0A%0A%09%09Array.pr
@@ -2092,17 +2092,16 @@
nderer%5D;
-%09
%0A%0A%09%09if (
|
4f22ba54bf9779226dfee4c44d5c7bcd056e5662 | Add getAttributeNS to domstubs for SVG example | examples/node/domstubs.js | examples/node/domstubs.js | /* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
function xmlEncode(s){
var i = 0, ch;
s = String(s);
while (i < s.length && (ch = s[i]) !== '&' && ch !== '<' &&
ch !== '\"' && ch !== '\n' && ch !== '\r' && ch !== '\t') {
i++;
}
if (i >= s.length) {
return s;
}
var buf = s.substring(0, i);
while (i < s.length) {
ch = s[i++];
switch (ch) {
case '&':
buf += '&';
break;
case '<':
buf += '<';
break;
case '\"':
buf += '"';
break;
case '\n':
buf += '
';
break;
case '\r':
buf += '
';
break;
case '\t':
buf += '	';
break;
default:
buf += ch;
break;
}
}
return buf;
}
global.btoa = function btoa(chars) {
var digits =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var buffer = '';
var i, n;
for (i = 0, n = chars.length; i < n; i += 3) {
var b1 = chars.charCodeAt(i) & 0xFF;
var b2 = chars.charCodeAt(i + 1) & 0xFF;
var b3 = chars.charCodeAt(i + 2) & 0xFF;
var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4);
var d3 = i + 1 < n ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64;
var d4 = i + 2 < n ? (b3 & 0x3F) : 64;
buffer += (digits.charAt(d1) + digits.charAt(d2) +
digits.charAt(d3) + digits.charAt(d4));
}
return buffer;
};
function DOMElement(name) {
this.nodeName = name;
this.childNodes = [];
this.attributes = {};
this.textContent = '';
if (name === 'style') {
this.sheet = {
cssRules: [],
insertRule: function (rule) {
this.cssRules.push(rule);
},
};
}
}
DOMElement.prototype = {
setAttributeNS: function DOMElement_setAttributeNS(NS, name, value) {
value = value || '';
value = xmlEncode(value);
this.attributes[name] = value;
},
appendChild: function DOMElement_appendChild(element) {
var childNodes = this.childNodes;
if (childNodes.indexOf(element) === -1) {
childNodes.push(element);
}
},
toString: function DOMElement_toString() {
var attrList = [];
for (i in this.attributes) {
attrList.push(i + '="' + xmlEncode(this.attributes[i]) + '"');
}
if (this.nodeName === 'svg:tspan' || this.nodeName === 'svg:style') {
var encText = xmlEncode(this.textContent);
return '<' + this.nodeName + ' ' + attrList.join(' ') + '>' +
encText + '</' + this.nodeName + '>';
} else if (this.nodeName === 'svg:svg') {
var ns = 'xmlns:xlink="http://www.w3.org/1999/xlink" ' +
'xmlns:svg="http://www.w3.org/2000/svg"'
return '<' + this.nodeName + ' ' + ns + ' ' + attrList.join(' ') + '>' +
this.childNodes.join('') + '</' + this.nodeName + '>';
} else {
return '<' + this.nodeName + ' ' + attrList.join(' ') + '>' +
this.childNodes.join('') + '</' + this.nodeName + '>';
}
},
cloneNode: function DOMElement_cloneNode() {
var newNode = new DOMElement(this.nodeName);
newNode.childNodes = this.childNodes;
newNode.attributes = this.attributes;
newNode.textContent = this.textContent;
return newNode;
},
}
global.document = {
childNodes : [],
get currentScript() {
return { src: '' };
},
get documentElement() {
return this;
},
createElementNS: function (NS, element) {
var elObject = new DOMElement(element);
return elObject;
},
createElement: function (element) {
return this.createElementNS('', element);
},
getElementsByTagName: function (element) {
if (element === 'head') {
return [this.head || (this.head = new DOMElement('head'))];
}
return [];
}
};
function Image () {
this._src = null;
this.onload = null;
}
Image.prototype = {
get src () {
return this._src;
},
set src (value) {
this._src = value;
if (this.onload) {
this.onload();
}
}
}
global.Image = Image;
| JavaScript | 0 | @@ -1795,16 +1795,154 @@
pe = %7B%0A%0A
+ getAttributeNS: function DOMElement_getAttributeNS(NS, name) %7B%0A return name in this.attributes ? this.attributes%5Bname%5D : null;%0A %7D,%0A%0A
setAtt
|
77232f440e0dfa2ba5855f52bacd48345a133af2 | refactor for loop | app/assets/javascripts/feature/application.js | app/assets/javascripts/feature/application.js | //= require jquery
//= require_tree .
var bindFeatureBoxes = function() {
var featureBoxes = $('.feature-box');
for(i = 0, i < featureBoxes; i++) {
bindFeatureBox($(featureBoxes[i]));
};
}
var updateFeature = function (box, feature) {
if (feature.type == 'boolean') {
} else {
for(var input in box.find('input')) {
var value = feature.data[input.name]
input.value = value;
}
}
};
var toggleError = function(toggle) {
if (toggle) {
$('body .container').append("<div class='loading error'>Error</div>")
} else {
$('.loading').remove()
}
}
var toggleSaving = function(toggle) {
if (toggle) {
$('body .container').append("<div class='loading'>Saving...</div>")
} else {
$('.loading').remove()
}
}
var bindFeatureBox = function(box) {
var featureName = box.data('name')
var featureType = box.data('type')
var updatePath = window.location.pathname "/features/" + featureName
box.find('input').on('change', function(e) {
var key = e.currentTarget.dataset.key
if (featureType == 'boolean') {
var value = e.currentTarget.checked
} else {
var value = e.currentTarget.value
}
var data = {}
data[key] = value
toggleSaving(true)
$.ajax({
method: 'PATCH',
url: updatePath,
data: { feature: data },
success: (response) => {
updateFeature(box, response.feature)
toggleError(false)
toggleSaving(false)
},
error: (response) => {
toggleSaving(false)
toggleError(true)
}
})
})
};
| JavaScript | 0.000028 | @@ -137,16 +137,23 @@
ureBoxes
+.lenght
; i++) %7B
@@ -298,20 +298,16 @@
e %7B%0A
-for(
var inpu
@@ -307,19 +307,19 @@
ar input
- in
+s =
box.fin
@@ -328,16 +328,55 @@
'input')
+%0A%0A for(i = 0, i %3C inputs.lenght; i++
) %7B%0A
@@ -407,16 +407,20 @@
ta%5Binput
+s%5Bi%5D
.name%5D%0A
@@ -429,16 +429,20 @@
input
+s%5Bi%5D
.value =
|
9b87434a1caa2db36994abd96c7d9e75d2d39fc8 | give true false for auth.isLoggedIn | app/assets/javascripts/service/authService.js | app/assets/javascripts/service/authService.js | module.factory('authService', [
'$rootScope',
'$location',
'$route',
'$cacheFactory',
'typeService',
'$window',
'$q',
'messageService',
'constantService',
'routerService',
'Party',
function ($rootScope, $location, $route, $cacheFactory, typeService, $window, $q, messages, constants, router, Party) {
var auth = {};
//
auth.user = undefined;
auth.parseUser = function (user) {
var reload = true;
if (user) {
if (angular.isDefined(user.superuser) && user.superuser > 0) {
user.superuser = new Date(Date.now() + user.superuser);
}
else {
user.superuser = false;
}
if (auth.user && auth.user.id === user.id && !!auth.user.superuser === !!user.superuser) {
reload = false;
}
} else if (!user && !auth.user) {
reload = false;
}
auth.user = user || undefined;
if (reload) {
$cacheFactory.removeAll();
$route.reload();
}
};
var deferred = $q.defer();
auth.$promise = deferred.promise;
auth.updateUser = function (user) {
if (user) {
auth.parseUser(user);
return deferred.resolve();
}
Party.user(function (data) {
if (data.id == -1 || angular.isString(data)) {
auth.parseUser(undefined);
}
else {
auth.parseUser(data);
}
deferred.resolve();
}, function () {
auth.parseUser(undefined);
deferred.resolve();
});
};
auth.updateUser();
//
var parseAuthLevel = function (level) {
return $.isNumeric(level) ? parseInt(level) :
angular.isString(level) ? constants.data.permissionName[level.toUpperCase()] : -1;
};
var parseUserAuth = function (object) {
if (!auth.user || !auth.user.id || auth.user.id == -1) {
return -1;
}
if (angular.isDate(auth.user.superuser) && auth.user.superuser > new Date()) {
return parseAuthLevel('SUPER');
}
if (angular.isObject(object) && object.permission) {
return object.permission;
}
return auth.user.access;
};
//
auth.hasAuth = function (level) {
return parseUserAuth() >= parseAuthLevel(level);
};
auth.isAuth = function (level) {
return parseUserAuth() == parseAuthLevel(level);
};
//
auth.hasAccess = function (level, object) {
return parseUserAuth(object) >= parseAuthLevel(level);
};
auth.isAccess = function (level, object) {
return parseUserAuth(object) == parseAuthLevel(level);
};
//
auth.tryLogin = function () {
auth.next = $location.url();
$location.url(router.login());
};
auth.logout = function () {
Party.logout(function (data) {
auth.parseUser(data);
$location.url('/login');
messages.add({
body: constants.message('logout.success'),
type: 'yellow',
countdown: 3000
});
}, function (res) {
$location.url('/');
messages.add({
body: constants.message('logout.error'),
report: res,
});
});
};
auth.showProfile = function () {
$location.path(router.profile());
};
//
auth.isLoggedIn = function () {
return auth.user && auth.user.id && auth.user.id != -1;
};
auth.hasToken = function () {
return $window.$play && $window.$play.object && typeService.isToken($window.$play.object);
};
auth.getToken = function () {
if (!auth.hasToken()) {
return;
}
return $window.$play.object;
};
auth.isPasswordReset = function () {
return auth.hasToken() && $window.$play.object.reset;
};
auth.isPasswordPending = function () {
return auth.hasToken() && !$window.$play.object.reset;
};
auth.isUnauthorized = function () {
return auth.isLoggedIn() && auth.isAuth('NONE');
};
auth.isAuthorized = function () {
return auth.isLoggedIn() && auth.hasAuth('VIEW');
};
//
var enableSU = function (form) {
Party.superuserOn({
auth: form.auth
},
function (data) {
auth.parseUser(data);
messages.add({
body: constants.message('superuser.on.success'),
type: 'green',
countdown: 2000
});
}, function (res) {
messages.addError({
body: constants.message('superuser.on.error'),
report: res,
});
});
};
var disableSU = function () {
Party.superuserOff(function (data) {
auth.parseUser(data);
messages.add({
body: constants.message('superuser.off.success'),
type: 'green',
countdown: 2000
});
}, function (res) {
messages.addError({
body: constants.message('superuser.off.error'),
report: res,
});
});
};
auth.toggleSU = function (form) {
if (angular.isDefined(form)) {
enableSU(form);
}
else {
disableSU();
}
};
//
return auth;
}
]);
| JavaScript | 0.998469 | @@ -2995,32 +2995,35 @@
() %7B%0A%09%09%09return
+!!(
auth.user && aut
@@ -3053,16 +3053,17 @@
id != -1
+)
;%0A%09%09%7D;%0A%0A
|
89cf75ac80a9e934b33db3229857b3a35bda5142 | Define a preClickAction in depTree | app/js/arethusa.dep_tree/dep_tree.js | app/js/arethusa.dep_tree/dep_tree.js | 'use strict';
/* Dependency Tree Handler with Diff capabilities
*
* This service has not much to do - the tree itself is handled
* completely by the dependencyTree directive.
*
* It has however additional diff capabilities, that are triggered
* by a global diffLoaded event.
* Knows how to pass style information to the tree visualization in
* case a comparison/review was done.
* * One could experiment here that this code should go back to a diff plugin
* itself.
* A diff plugin would calculate style information and pass this data load
* through the diffLoaded event. The depTree service would listen to this
* and pass the style info to its tree.
*
* Let's wait on a decision for this until we have done more work on the
* diff plugin itself and resolved issue #80.
* (https://github.com/latin-language-toolkit/llt-annotation_environment/issues/80)
*/
angular.module('arethusa.depTree').service('depTree', [
'state',
'configurator',
'globalSettings',
'notifier',
function (state, configurator, globalSettings, notifier) {
var self = this;
this.name = "depTree";
this.externalDependencies = {
ordered: [
"bower_components/d3/d3.min.js",
"vendor/dagre-d3/dagre-d3.min.js"
]
};
function configure() {
configurator.getConfAndDelegate(self);
self.diffMode = false;
self.diffPresent = false;
self.diffInfo = {};
}
this.toggleDiff = function () {
self.diffMode = !self.diffMode;
};
// We have three things we can colorize as wrong in the tree
// Label
// Head
// and the word itself for morphological stuff
function analyseDiffs(tokens) {
return arethusaUtil.inject({}, tokens, function (memo, id, token) {
var diff = token.diff;
if (diff) {
memo[id] = analyseDiff(diff);
}
});
}
function analyseDiff(diff) {
return arethusaUtil.inject({}, diff, function (memo, key, val) {
if (key === 'relation') {
memo.label = { color: 'red' };
} else {
if (key === 'head') {
memo.edge = {
stroke: 'red',
'stroke-width': '1px'
};
} else {
memo.token = { color: 'red' };
}
}
});
}
this.diffStyles = function () {
if (self.diffMode) {
return self.diffInfo;
} else {
return false;
}
};
state.on('diffLoaded', function () {
self.diffPresent = true;
self.diffInfo = analyseDiffs(state.tokens);
self.diffMode = true;
});
function addMissingHeadsToState() {
angular.forEach(state.tokens, addHead);
}
function addHead(token) {
if (!token.head) token.head = {};
}
function hasHead(token) {
return token.head.id;
}
state.on('tokenAdded', function(event, token) {
addHead(token);
});
state.on('tokenRemoved', function(event, token) {
// We need to disconnect manually, so that this event
// can be properly undone.
if (hasHead(token)) self.disconnect(token);
var id = token.id;
angular.forEach(state.tokens, function(t, i) {
if (t.head.id === id) {
self.disconnect(t);
}
});
});
// Used inside the context menu
this.disconnect = function(token) {
state.change(token, 'head.id', '');
};
this.toRoot = function(token) {
state.change(token, 'head.id', '0000');
};
function getHeadsToChange(token) {
var sId = token.sentenceId;
var id = token.id;
var notAllowed;
var res = [];
for (var otherId in state.clickedTokens) {
var otherToken = state.getToken(otherId);
if (otherToken.sentenceId !== sId) {
notAllowed = true;
break;
}
if (id !== otherId) {
res.push(otherToken);
}
}
return notAllowed ? 'err': (res.length ? res : false);
}
function changeHead(tokenToChange, targetToken) {
if (isDescendant(targetToken, tokenToChange)) {
state.change(targetToken, 'head.id', tokenToChange.head.id);
}
state.change(tokenToChange, 'head.id', targetToken.id);
}
function isDescendant(targetToken, token) {
var current = targetToken;
var currHead = aU.getProperty(current, 'head.id');
var tokenId = token.id;
var desc = false;
while ((!desc) && current && currHead) {
if (tokenId === currHead) {
desc = true;
} else {
current = state.getToken(currHead);
currHead = current ? aU.getProperty(current, 'head.id') : false;
}
}
return desc;
}
function changeHeadAction(id) {
var token = state.getToken(id);
var headsToChange = getHeadsToChange(token);
if (headsToChange) {
if (headsToChange === 'err') {
notifier.error('Cannot change heads across sentences');
return;
}
state.doBatched(function() {
angular.forEach(headsToChange, function(otherToken, i) {
changeHead(otherToken, token);
});
});
} else {
globalSettings.defaultClickAction(id);
}
}
var clickActionName = 'change head';
globalSettings.addClickAction(clickActionName, changeHeadAction);
globalSettings.setClickAction(clickActionName);
this.init = function () {
configure();
addMissingHeadsToState();
};
}
]);
| JavaScript | 0.000127 | @@ -5264,24 +5264,578 @@
%7D%0A %7D%0A%0A
+ function awaitingHeadChange(id, event) %7B%0A return !state.isSelected(id) && state.hasClickSelections() && !event.ctrlKey;%0A %7D%0A%0A function preHeadChange(id, scope, element) %7B%0A element.bind('mouseenter', function (event) %7B%0A scope.$apply(function() %7B%0A if (awaitingHeadChange(id, event)) %7B%0A element.addClass('copy-cursor');%0A %7D%0A %7D);%0A %7D);%0A element.bind('mouseleave', function () %7B%0A scope.$apply(function () %7B%0A element.removeClass('copy-cursor');%0A %7D);%0A %7D);%0A %7D%0A%0A
var clic
@@ -5931,16 +5931,31 @@
adAction
+, preHeadChange
);%0A g
|
e998e0c8ebe04ec6eb557e025ac67bc00813c8cb | Fix secondary nav bar alignment. | app/js/components/SecondaryNavBar.js | app/js/components/SecondaryNavBar.js | import React, { Component, PropTypes } from 'react'
import { Link } from 'react-router'
const SecondaryNavLink = props => {
const alignment = (props.align === "right") ? "float-right pull-right" : "float-left pull-left"
const active = props.isActive === true ? "active" : ""
return (
<Link
className={`btn btn-link ${alignment} ${active}`}
to={props.link}>
{props.title}
</Link>
)
}
const SecondaryNavButton = props => {
const alignment = (props.align === "right") ? "float-right pull-right" : "float-left pull-left"
const active = props.isActive === true ? "active" : ""
return (
<button
className={`btn btn-link ${alignment} ${active}`}
title={props.title}
onClick={props.onClick}>
{props.title}
</button>
)
}
class SecondaryNavBar extends Component {
static propTypes = {
title: PropTypes.string,
leftButtonTitle: PropTypes.string,
rightButtonTitle: PropTypes.string,
leftButtonLink: PropTypes.string,
rightButtonLink: PropTypes.string,
onLeftButtonClick: PropTypes.func,
onRightButtonClick: PropTypes.func,
isLeftActive: PropTypes.bool,
isRightActive: PropTypes.bool
}
render() {
return (
<div className="container-fluid secondary-nav">
<div className="row">
<div className="col-xs-6">
{this.props.leftButtonTitle !== undefined && (
this.props.onLeftButtonClick !== undefined ?
<SecondaryNavButton
title={this.props.leftButtonTitle}
onClick={this.props.onLeftButtonClick}
align="left"
isActive={this.props.isLeftActive} />
:
<SecondaryNavLink
title={this.props.leftButtonTitle}
link={this.props.leftButtonLink}
align="left"
isActive={this.props.isLeftActive} />
) }
</div>
<div className="col-xs-6">
{this.props.rightButtonTitle !== undefined && (
this.props.onRightButtonClick !== undefined ?
<SecondaryNavButton
title={this.props.rightButtonTitle}
onClick={this.props.onRightButtonClick}
align="right"
isActive={this.props.isRightActive} />
:
<SecondaryNavLink
title={this.props.rightButtonTitle}
link={this.props.rightButtonLink}
align="right"
isActive={this.props.isRightActive} />
) }
</div>
</div>
</div>
)
}
}
export default SecondaryNavBar | JavaScript | 0 | @@ -182,39 +182,18 @@
ight
- pull-right%22 : %22float-left pull
+%22 : %22float
-lef
@@ -495,39 +495,18 @@
ight
- pull-right%22 : %22float-left pull
+%22 : %22float
-lef
@@ -1276,37 +1276,32 @@
v className=%22col
--xs-6
%22%3E%0A %7B
@@ -1889,32 +1889,32 @@
%3C/div%3E%0A
+
%3Cdiv c
@@ -1930,13 +1930,8 @@
%22col
--xs-6
%22%3E%0A
|
1fb56dc4d43b3ff15e18d0e055b4f225f52eb7eb | Remove paypal OAuth call for cleanup | app/js/main/controllers/LoginCtrl.js | app/js/main/controllers/LoginCtrl.js | app.controller('LoginCtrl', [
'$rootScope',
'$scope',
'$state',
'TweetFactory',
'TwitterUserFactory',
'PaypalFactory',
'$cookies',
function(
$rootScope,
$scope,
$state,
TweetFactory,
TwitterUserFactory,
PaypalFactory,
$cookies) {
$scope.twitter_authorized = false;
$scope.paypal_authorized = false;
$scope.authenticate = function(provider) {
OAuth.initialize('ZEezHY42tLMdO9i2rKNBAgAxdak')
OAuth.popup(provider, {cache: true}).done(function(response) {
if (provider === 'twitter') {
$rootScope.twitterOAuthResult = response;
// $cookies.twitter_token = response.oauth_token; // enable storing cookies once app.run is configured to check login
$scope.twitterAuthorized = true;
// Load all necessary data upon login and serve through app - need a strategy to accomodate live update or stream API
TweetFactory.getTweets()
.success(function(response) {
$rootScope.tweets = response;
});
TwitterUserFactory.getFollowers()
.success(function(response) {
$rootScope.followers = response.users;
});
TwitterUserFactory.getFriends()
.success(function(response) {
$rootScope.friends = response.users;
});
TwitterUserFactory.getMe()
.then(function(response) {
$rootScope.me = response;
alert('User data loaded.');
$state.go('app.home');
});
};
if (provider === 'paypal') {
$rootScope.paypalOAuthResult = response;
PaypalFactory.getMe().then(function(response) {
debugger;
}).fail(function(response) { alert('Failed') });
};
}).fail(function(error) {
console.log(error.message);
});
}
$scope.logout = function() {
};
}]);
| JavaScript | 0 | @@ -1547,24 +1547,27 @@
se;%0A%09 %09%0A%09
+ //
%09PaypalF
@@ -1613,24 +1613,10 @@
%7B%0A%09
- %09%09debugger;%0A%09
+//
@@ -1663,24 +1663,27 @@
led') %7D);%0A%0A%09
+ //
%7D;%0A%09%09%7D).
@@ -1679,16 +1679,19 @@
%7D;%0A%09%09
+//
%7D).fail(
@@ -1710,16 +1710,19 @@
or) %7B%0A%09%09
+//
%09%09consol
@@ -1745,16 +1745,19 @@
age);%0A%09%09
+//
%7D);%0A%09%7D%0A%0A
|
801af3ee29771865a5fb5b80eaaed1401b8ecdef | change callback to promise | app/js/src/managers/assetsManager.js | app/js/src/managers/assetsManager.js | const manifest = [
{ id: 'monster', src: 'img/monster-sprite.png' },
{ id: 'bird', src: 'img/bird-sprite.png' },
{ id: 'chicken', src: 'img/chicken-sprite.png' },
{ id: 'spike', src: 'img/spike.png' },
{ id: 'sky', src: 'img/bg/sky.png' },
{ id: 'start', src: 'img/bg/start.png' },
{ id: 'mountain', src: 'img/bg/mountain.png' },
{ id: 'ground', src: 'img/bg/ground.png' },
{ id: 'btn', src: 'img/btn-sprite.png' },
{ id: 'icon-btn', src: 'img/icon-btn-sprite.png' },
{ id: 'icon', src: 'img/icon-sprite.png' },
{ id: 'back', src: 'sound/background.ogg' },
{ id: 'flap', src: 'sound/flap.ogg' },
{ id: 'loose', src: 'sound/loose.ogg' },
];
const getHeroSpriteSheetData = name => ({
images: [name],
frames: { width: 100, height: 78 },
animations: {
fly: 0,
flap: [1, 3, 'fly'],
dead: 4,
},
});
const spriteSheetsData = {
bird: getHeroSpriteSheetData('bird'),
monster: getHeroSpriteSheetData('monster'),
chicken: getHeroSpriteSheetData('chicken'),
btn: {
images: ['btn'],
frames: { width: 210, height: 69, spacing: 2 },
animations: {
greenOut: 0,
greenOver: 2,
greenDown: 4,
orangeOut: 6,
orangeOver: 8,
orangeDown: 1,
redOut: 3,
redOver: 5,
redDown: 7,
disable: 9,
},
},
iconBtn: {
images: ['icon-btn'],
frames: { width: 69, height: 71, spacing: 2 },
animations: {
greenOut: 0,
greenOver: 1,
greenDown: 2,
orangeOut: 3,
orangeOver: 4,
orangeDown: 5,
redOut: 8,
redOver: 7,
redDown: 6,
disable: 9,
},
},
icon: {
images: ['icon'],
frames: { width: 40, height: 40 },
animations: {
sound: 0,
soundOff: 1,
},
},
};
const spriteSheets = {};
const assetsManager = {
load(callback) {
createjs.Sound.alternateExtensions = ['mp3'];
this.queue = new createjs.LoadQueue();
this.queue.installPlugin(createjs.Sound);
this.queue.loadManifest(manifest);
this.queue.addEventListener('complete', callback);
},
getResult(name) {
return this.queue.getResult(name);
},
getSpriteSheet(name) {
if (!spriteSheets[name]) {
const data = spriteSheetsData[name];
if (!data) {
throw new Error('invalid spriteSheet name');
}
data.images = data.images.map(img => this.getResult(img));
spriteSheets[name] = new createjs.SpriteSheet(data);
}
return spriteSheets[name];
},
};
export default assetsManager;
| JavaScript | 0 | @@ -1807,21 +1807,13 @@
%7B%0A
-load(callback
+init(
) %7B%0A
@@ -1990,16 +1990,53 @@
ifest);%0A
+%0A return new Promise(resolve =%3E%0A
this
@@ -2075,16 +2075,24 @@
e',
-callback
+() =%3E resolve())
);%0A
|
457affce4eae793d6d9b18f76f8243a1845484ff | support nested string literals | src/foam/u2/detail/SectionView.js | src/foam/u2/detail/SectionView.js | /**
* @license
* Copyright 2019 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
package: 'foam.u2.detail',
name: 'SectionView',
extends: 'foam.u2.View',
requires: [
'foam.core.ArraySlot',
'foam.core.ConstantSlot',
'foam.core.ProxySlot',
'foam.core.SimpleSlot',
'foam.layout.Section',
'foam.u2.detail.SectionedDetailPropertyView',
'foam.u2.DisplayMode',
'foam.u2.layout.Cols',
'foam.u2.layout.Grid',
'foam.u2.layout.GUnit',
'foam.u2.layout.Rows'
],
css: `
.subtitle {
color: /*%GREY2%*/ #8e9090;
font-size: 14px;
line-height: 1.5;
margin-bottom: 15px;
}
`,
properties: [
{
class: 'String',
name: 'sectionName'
},
{
class: 'FObjectProperty',
of: 'foam.layout.Section',
name: 'section',
expression: function(data, sectionName) {
if ( ! data ) return null;
var of = data.cls_;
var a = of.getAxiomByName(sectionName);
return this.Section.create().fromSectionAxiom(a, of);
}
},
{
class: 'Boolean',
name: 'showTitle',
value: true
},
{
class: 'Function',
name: 'evaluateMessage',
documentation: `Evaluates model messages without executing potentially harmful values`,
factory: function() {
return (msg) => msg.replace(/\${(.*?)}/g, (x,g) => this.data[g]);
}
}
],
methods: [
function initE() {
var self = this;
self.SUPER();
self
.addClass(self.myClass())
.add(self.slot(function(section, showTitle, section$title, section$subTitle) {
if ( ! section ) return;
return self.Rows.create()
.show(section.createIsAvailableFor(self.data$))
.callIf(showTitle && section$title, function() {
var slot$ = foam.Function.isInstance(self.section.title) ?
foam.core.ExpressionSlot.create({
args: [ self.evaluateMessage$, self.data$ ],
obj$: self.data$,
code: section.title
}) : section.title$;
this.start('h2').add(slot$).end();
})
.callIf(section$subTitle, function() {
var slot$ = foam.Function.isInstance(self.section.subTitle) ?
foam.core.ExpressionSlot.create({
args: [ self.evaluateMessage$, self.data$ ],
obj$: self.data$,
code: section.subTitle
}) : section.subTitle$;
this.start().addClass('subtitle').add(slot$).end();
})
.start(self.Grid)
.forEach(section.properties, function(p, index) {
this.start(self.GUnit, {columns: p.gridColumns})
.show(p.createVisibilityFor(self.data$, self.controllerMode$).map(mode => mode !== self.DisplayMode.HIDDEN))
.tag(self.SectionedDetailPropertyView, {
prop: p,
data$: self.data$
})
.end();
})
.end()
.start(self.Cols)
.style({
'justify-content': 'end',
'margin-top': section.actions.length ? '4vh' : 'initial'
})
.forEach(section.actions, function(a) {
this.add(a);
})
.end();
}));
}
]
});
| JavaScript | 0.000003 | @@ -1428,28 +1428,426 @@
(x,
-g
+ str
) =%3E
-this.data%5Bg%5D);
+%7B%0A var obj = this.data.clone();%0A return this.getNestedPropValue(obj, str);%0A %7D);%0A %7D%0A %7D,%0A %7B%0A class: 'Function',%0A name: 'getNestedPropValue',%0A factory: function() %7B%0A return (obj, path) =%3E %7B%0A if ( ! path ) return obj;%0A const props = path.split('.');%0A return this.getNestedPropValue(obj%5Bprops.shift()%5D, props.join('.'))%0A %7D
%0A
|
f7ae4e2562e3f3cb5bafb59640096a0f4ea8fdcc | remove unused vars | app/scripts/controllers/analytics.js | app/scripts/controllers/analytics.js | 'use strict';
/**
* @ngdoc function
* @name wheretoliveApp.controller:AnalyticsCtrl
* @description
* # AnalyticsCtrl
* Controller of the wheretoliveApp
*/
angular.module('wheretoliveApp')
.controller('AnalyticsCtrl', ['$scope', 'Search',
function ($scope, Search) {
$scope.topCrimeAggregateNumber = '0';
$scope.totalNewsCity = '0';
$scope.showAnalytics = function (city) {
$scope.totalCrimeCityS(city);
$scope.aggregateTotalCrimesInCity(city);
$scope.aggregateTotalNewsInCity(city);
$scope.aggregateTopCrimesInCity(city);
$scope.aggregateTopJournalsInCity(city);
};
$scope.newspapers = [
{
titolo: 'Giornale 1'
},
{
titolo: 'Giornale 1'
},
{
titolo: 'Giornale 1'
},
{
titolo: 'Giornale 1'
},
{
titolo: 'Giornale 1'
},
{
titolo: 'Giornale 1'
},
{
titolo: 'Giornale 1'
},
{
titolo: 'Giornale 1'
},
{
titolo: 'Giornale 1'
},
{
titolo: 'Giornale 1'
}
];
/** TOP CRIME **/
$scope.topCrime = {};
$scope.topCrimeChartType = 'bar';
$scope.topCrimeConfig = {
tooltips: true,
labels: false, // labels on data points
// exposed events
mouseover: function () {},
mouseout: function () {},
click: function () {},
// legend config
legend: {
display: true, // can be either 'left' or 'right'.
position: 'right',
// you can have html in series name
htmlEnabled: false
},
// override this array if you're not happy with default colors
colors: [],
innerRadius: 0, // Only on pie Charts
lineLegend: 'lineEnd', // Only on line Charts
lineCurveType: 'cardinal', // change this as per d3 guidelines to avoid smoothline
isAnimate: true, // run animations while rendering chart
yAxisTickFormat: 's' //refer tickFormats in d3 to edit this value
};
/** TOP DAY CRIME **/
$scope.topCrymeDayFeatures = {
legend: {
toggle: true,
highlight: true
}
};
$scope.topDayCrimeChartType = 'line';
$scope.topCrymeDayOptions = {
renderer: 'area',
stroke: true,
preserve: true,
};
$scope.topCrymeDaySeries = [{
name: 'Series 1',
color: 'steelblue',
data: [{
x: 0,
y: 23
}, {
x: 1,
y: 15
}, {
x: 2,
y: 79
}, {
x: 3,
y: 31
}, {
x: 4,
y: 60
}]
}, {
name: 'Series 2',
color: 'lightblue',
data: [{
x: 0,
y: 30
}, {
x: 1,
y: 20
}, {
x: 2,
y: 64
}, {
x: 3,
y: 50
}, {
x: 4,
y: 15
}]
}];
/** TOP NEWSPAPER BY DAY **/
$scope.topNewspaperDaySeries = [{
name: 'Series 1',
color: 'steelblue',
data: [{
x: 0,
y: 23
}, {
x: 1,
y: 15
}, {
x: 2,
y: 79
}, {
x: 3,
y: 31
}, {
x: 4,
y: 60
}]
}, {
name: 'Series 2',
color: 'lightblue',
data: [{
x: 0,
y: 30
}, {
x: 1,
y: 20
}, {
x: 2,
y: 64
}, {
x: 3,
y: 50
}, {
x: 4,
y: 15
}]
}];
$scope.topNewspaperDayFeatures = {};
$scope.topDayNewspaperOptions = {
renderer: 'area',
stroke: true,
preserve: true
};
$scope.totalCrimeCityS = function(city){
Search.aggregateCountCrimes(city).success(function(data){
var array = data.aggregations.crimes_count.buckets;
var result = 0;
var i = 0;
for (i = 0; i < array.length; i++){
result += array[i].doc_count;
}
console.log(result);
$scope.topCrimeAggregateNumber = result;
});
};
$scope.aggregateTotalCrimesInCity = function (city) {
var res = Search.aggregateTotalCrimesInCity(city).then(function (data) {
var res1 = data.data.aggregations.crimes_count.buckets; //jshint ignore:line
var i = 0;
var x = [];
var y = [];
for (i = 0; i < res1.length; i++) {
x.push(res1[i].key);
y.push(res1[i].doc_count); //jshint ignore:line
}
$scope.topCrime.series = x;
$scope.topCrime.data = [{
x: 'Top Crimini',
y: y
}];
$scope.topCrimeAggregateNumber = res1.length;
return res1;
});
return res;
};
$scope.aggregateTotalNewsInCity = function (city) {
Search.aggregateTotalNewsInCity(city).then(function (data) {
var res1 = data.data.hits.total;
$scope.totalNewsCity = res1;
return res1;
});
return res;
};
$scope.aggregateTopCrimesInCity = function (city) {
Search.aggregateTopCrimesInCity(city).then(function (data) {
var res1 = data.data.hits.total;
return res1;
});
return res;
};
$scope.aggregateTopJournalsInCity = function (city) {
Search.aggregateTopCrimesInCity(city).then(function (data) {
var res1 = data.data.aggregations.crime_histograms.buckets; //jshint ignore:line
//var res1="ciao";
return res1;
});
return res;
};
$scope.init = function () {
// $scope.aggregateTotalCrimesInCity("Bari");
// $scope.aggregateTotalNewsInCity("Bari");
//$scope.aggregateTopCrimesInCity("Bari");
//$scope.aggregateTopJournalsInCity('Bari');
};
}]);
| JavaScript | 0.000001 | @@ -5825,49 +5825,8 @@
%7D%0A
- console.log(result);%0A
@@ -6003,18 +6003,8 @@
- var res =
Sea
@@ -6643,155 +6643,28 @@
%7D%5D;%0A
- $scope.topCrimeAggregateNumber = res1.length;%0A return res1;%0A%0A%0A %7D);%0A return res
+%0A%0A %7D)
;%0A
@@ -6924,89 +6924,29 @@
s1;%0A
- return res1;%0A%0A%0A %7D);%0A return res
+%0A%0A%0A %7D)
;%0A
@@ -7156,87 +7156,27 @@
al;%0A
- return res1;%0A %7D);%0A return res
+%0A %7D)
;%0A
@@ -7476,87 +7476,27 @@
o%22;%0A
- return res1;%0A %7D);%0A return res
+%0A %7D)
;%0A
|
b4267c2812423d1da039f8b4a8913c2ce3fbebe1 | Fix the issue for regex inside the html file. | src/extensions/default/JavaScriptCodeHints/HintUtils.js | src/extensions/default/JavaScriptCodeHints/HintUtils.js | /*
* Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50, regexp: true */
/*global define */
define(function (require, exports, module) {
"use strict";
var Acorn = require("thirdparty/acorn/acorn");
var LANGUAGE_ID = "javascript",
HTML_LANGUAGE_ID = "html",
SUPPORTED_LANGUAGES = [LANGUAGE_ID, HTML_LANGUAGE_ID],
SINGLE_QUOTE = "'",
DOUBLE_QUOTE = "\"";
/**
* Create a hint token with name value that occurs at the given list of
* positions.
*
* @param {string} value - name of the new hint token
* @param {?Array.<number>=} positions - optional list of positions at which
* the token occurs
* @return {Object} - a new hint token
*/
function makeToken(value, positions) {
positions = positions || [];
return {
value: value,
positions: positions
};
}
/**
* Is the string key perhaps a valid JavaScript identifier?
*
* @param {string} key - string to test.
* @return {boolean} - could key be a valid identifier?
*/
function maybeIdentifier(key) {
var result = false,
i;
for (i = 0; i < key.length; i++) {
result = Acorn.isIdentifierChar(key.charCodeAt(i));
if (!result) {
break;
}
}
return result;
}
/**
* Is the token's class hintable? (A very conservative test.)
*
* @param {Object} token - the token to test for hintability
* @return {boolean} - could the token be hintable?
*/
function hintable(token) {
switch (token.type) {
case "comment":
case "number":
case "regexp":
case "string":
// exclude variable & param decls
case "def":
return false;
case "string-2":
// exclude strings inside a regexp
return !token.state || token.state.lastType !== "regexp";
default:
return true;
}
}
/**
* Determine if hints should be displayed for the given key.
*
* @param {string} key - key entered by the user
* @param {boolean} showOnDot - show hints on dot (".").
* @return {boolean} true if the hints should be shown for the key,
* false otherwise.
*/
function hintableKey(key, showOnDot) {
return (key === null || (showOnDot && key === ".") || maybeIdentifier(key));
}
/*
* Get a JS-hints-specific event name. Used to prevent event namespace
* pollution.
*
* @param {string} name - the unqualified event name
* @return {string} - the qualified event name
*/
function eventName(name) {
var EVENT_TAG = "brackets-js-hints";
return name + "." + EVENT_TAG;
}
/*
* Annotate a list of tokens as literals of a particular kind;
* if string literals, annotate with an appropriate delimiter.
*
* @param {Array.<Object>} literals - list of hint tokens
* @param {string} kind - the kind of literals in the list (e.g., "string")
* @return {Array.<Object>} - the input array; to each object in the array a
* new literal {boolean} property has been added to indicate that it
* is a literal hint, and also a new kind {string} property to indicate
* the literal kind. For string literals, a delimiter property is also
* added to indicate what the default delimiter should be (viz. a
* single or double quotation mark).
*/
function annotateLiterals(literals, kind) {
return literals.map(function (t) {
t.literal = true;
t.kind = kind;
t.origin = "ecma5";
if (kind === "string") {
if (/[\\\\]*[^\\]"/.test(t.value)) {
t.delimiter = SINGLE_QUOTE;
} else {
t.delimiter = DOUBLE_QUOTE;
}
}
return t;
});
}
/*
* Annotate a list of tokens as keywords
*
* @param {Array.<Object>} keyword - list of keyword tokens
* @return {Array.<Object>} - the input array; to each object in the array a
* new keyword {boolean} property has been added to indicate that the
* hint is a keyword.
*/
function annotateKeywords(keywords) {
return keywords.map(function (t) {
t.keyword = true;
t.origin = "ecma5";
return t;
});
}
function isSupportedLanguage(languageId) {
return SUPPORTED_LANGUAGES.indexOf(languageId) !== -1;
}
var KEYWORD_NAMES = [
"break", "case", "catch", "continue", "debugger", "default", "delete",
"do", "else", "finally", "for", "function", "if", "in", "instanceof",
"new", "return", "switch", "this", "throw", "try", "typeof", "var",
"void", "while", "with"
],
KEYWORD_TOKENS = KEYWORD_NAMES.map(function (t) {
return makeToken(t, []);
}),
KEYWORDS = annotateKeywords(KEYWORD_TOKENS);
var LITERAL_NAMES = [
"true", "false", "null"
],
LITERAL_TOKENS = LITERAL_NAMES.map(function (t) {
return makeToken(t, []);
}),
LITERALS = annotateLiterals(LITERAL_TOKENS);
exports.makeToken = makeToken;
exports.hintable = hintable;
exports.hintableKey = hintableKey;
exports.maybeIdentifier = maybeIdentifier;
exports.eventName = eventName;
exports.annotateLiterals = annotateLiterals;
exports.isSupportedLanguage = isSupportedLanguage;
exports.KEYWORDS = KEYWORDS;
exports.LITERALS = LITERALS;
exports.LANGUAGE_ID = LANGUAGE_ID;
exports.SINGLE_QUOTE = SINGLE_QUOTE;
exports.DOUBLE_QUOTE = DOUBLE_QUOTE;
exports.SUPPORTED_LANGUAGES = SUPPORTED_LANGUAGES;
});
| JavaScript | 0.000001 | @@ -2909,24 +2909,260 @@
le(token) %7B%0A
+ %0A function _isInsideRegExp(token) %7B%0A return token.state && (token.state.lastType === %22regexp%22 %7C%7C%0A (token.state.localState && token.state.localState.lastType === %22regexp%22));%0A %7D%0A %0A
swit
@@ -3456,56 +3456,30 @@
rn !
-token.state %7C%7C token.state.lastType !== %22regexp%22
+_isInsideRegExp(token)
;%0A
|
29854d3bd286b84ef2a6a9d22d94f38240d55cd9 | use tags/inbox to get inbox count | app/scripts/services/mailpile.api.js | app/scripts/services/mailpile.api.js | 'use strict';
/**
* @ngdoc service
* @name mailpile.api
* @description
* # mailpile.api
* Service in the blimpCockpitApp.
*/
angular.module('blimpCockpitApp')
.factory('mailpileApi', ['$resource', '$http', '$q', '$rootScope', '$state', '$localstorage', 'cockpitApi',
function ($resource, $http, $q, $rootScope, $state, $localstorage, cockpitApi) {
var mailpileUrl = '/mailpile/' + cockpitApi.getCurrentUser().id;
var mailpileApiUrl = mailpileUrl + '/api/0/';
var service = {
getInboxCount: function(){
var deferred = $q.defer();
$http.get(mailpileApiUrl + 'search/?q=in:inbox').
then(function (response) {
if(response.data.result && response.data.result.stats )
{
deferred.resolve(response.data.result.stats.total);
}
else {
deferred.resolve("n/a");
}
},
function (_, status) {
deferred.resolve("n/a");
});
return deferred.promise;
}
}
return service;
}]);
| JavaScript | 0 | @@ -614,26 +614,19 @@
+ '
-search/?q=in:
+tags/
inbox
+/
').%0A
@@ -706,38 +706,8 @@
ult
-&& response.data.result.stats
)%0A
@@ -778,19 +778,25 @@
ult.
-s
ta
-ts.total
+gs%5B0%5D.stats.new
);%0A
|
a85f68db940a6aebc2cdfbf10ce108954a975208 | allow to remove tag from category | app/components/browser/sidebar/SideBarTags.js | app/components/browser/sidebar/SideBarTags.js | import '../../../css/browser/side-bar-tags'
import React, { PropTypes } from 'react'
import { connect } from 'react-redux'
import { FormattedMessage as T, intlShape } from 'react-intl'
import cx from 'classnames'
import { Creatable } from 'react-select'
import partition from 'lodash.partition'
import uniq from 'lodash.uniq'
import difference from 'lodash.difference'
import { TAGS_NS } from '../../../constants'
import Button from '../../Button'
import { addTagsCategory, addTag, removeTag, fetchTags } from '../../../actions/tags'
class SideBarTags extends React.Component {
constructor (props) {
super(props)
this.state = {
newCategory: '',
// to avoid disappearing categories if new categories come from corpus-watcher just after creation
categories: [],
hideCategories: false
}
// prepopulate inputs
const userTags = props.webentity.tags[TAGS_NS]
if (userTags) {
Object.keys(userTags).forEach(k => {
this.state[`values/${k}`] = userTags[k]
})
}
// Force-bind methods used like `onEvent={ this.method }`
this.addCategory = this.addCategory.bind(this)
this.onChangeNewCategory = this.onChangeNewCategory.bind(this)
this.renderTagsCategory = this.renderTagsCategory.bind(this)
}
toggleCategories () {
this.setState({ hideCategories : !this.state.hideCategories })
}
componentWillMount () {
this.updateFullSuggestions(this.props.categories)
}
componentWillReceiveProps ({ categories }) {
if (JSON.stringify(categories) !== JSON.stringify(this.props.categories)) {
this.updateFullSuggestions(categories)
}
}
updateFullSuggestions (categories) {
// Updated categories, fetch suggestions
const { serverUrl, corpusId, fetchTags } = this.props
fetchTags(serverUrl, corpusId).then((tags) => {
categories.forEach((category) => {
this.setState({ ['suggestions/' + category]: tags[category] })
})
})
}
onChangeNewCategory ({ target }) {
this.setState({ newCategory: target.value })
}
addCategory (e) {
e.preventDefault()
const { newCategory } = this.state
if (newCategory) {
const { serverUrl, corpusId, webentity, addTagsCategory } = this.props
addTagsCategory(serverUrl, corpusId, webentity.id, newCategory)
this.setState({ newCategory: '', categories: this.state.categories.concat(newCategory) })
}
}
onChangeCreatable (options, category) {
const { serverUrl, corpusId, webentity, addTag, removeTag } = this.props
const key = `values/${category}`
const previousTags = this.state[key] || []
const nextTags = options.map(o => o.value)
const addedTags = difference(nextTags, previousTags)
const removedTags = difference(previousTags, nextTags)
addedTags.map(tag => addTag(serverUrl, corpusId, category, webentity.id, tag, tag))
removedTags.map(tag => removeTag(serverUrl, corpusId, category, webentity.id, tag))
this.setState({ [key]: nextTags })
}
// big textarea-like with many tags
renderFreeTagsCategory (category) {
const { formatMessage } = this.context.intl
const suggestions = this.state[`suggestions/${category}`] || []
const values = this.state[`values/${category}`] || []
return (
<div className="browser-side-bar-tags-free-tags" key={ category }>
<h3><span>{ formatMessage({ id: 'sidebar.freetags' }) }</span></h3>
<Creatable
clearable={ false }
multi={ true }
newOptionCreator={ ({ label }) => toOption(label) }
options={ suggestions.map(toOption) }
onChange={ (options) => this.onChangeCreatable(options, category) }
placeholder={ formatMessage({ id: 'sidebar.select-tags' }) }
promptTextCreator={ (tag) => `${formatMessage({ id: 'sidebar.create-tag' })}"${tag}"` }
value={ values.map(toOption) } />
</div>
)
}
// simpler input with only one tag to fill
renderTagsCategory (category) {
const { formatMessage } = this.context.intl
const suggestions = this.state[`suggestions/${category}`] || []
const values = this.state[`values/${category}`] || []
return (
<div className="browser-side-bar-tags-category" key={ category }>
<h4 className="category-name">{ category }</h4>
<div className="category-tag">
<Creatable
clearable={ false }
multi={ false }
newOptionCreator={ ({ label }) => toOption(label) }
options={ suggestions.map(toOption) }
onChange={ (option) => this.onChangeCreatable([option], category) }
placeholder={ '' }
promptTextCreator={ (tag) => `${formatMessage({ id: 'sidebar.create-tag' })}"${tag}"` }
value={ values.map(toOption)[0] || '' } />
</div>
</div>
)
}
// free tags should be first, then other categories, then add category field
render () {
const { formatMessage } = this.context.intl
const [freeTags, cats] = partition(this.props.categories, isFreeTags)
const categories = uniq((cats || []).concat(this.state.categories).filter(x => x))
return (
<div className="browser-side-bar-tags">
{ this.renderFreeTagsCategory(freeTags[0]) }
<div>
<h3 onClick={ () => this.toggleCategories() }>
<T id="sidebar.categories" />
<span className={ cx({
'ti-angle-up': !this.state.hideCategories,
'ti-angle-down': this.state.hideCategories
}) }></span>
</h3>
{ !this.state.hideCategories && <div>
{ categories.map(this.renderTagsCategory) }
<form className="browser-side-bar-tags-new-category" onSubmit={ this.addCategory }>
<input placeholder={ formatMessage({ id: 'sidebar.add-tags-category' }) }
value={ this.state.newCategory }
onInput={ this.onChangeNewCategory } />
<Button icon="plus" title={ formatMessage({ id: 'sidebar.add-tags-category' }) } />
</form>
</div> }
</div>
</div>
)
}
}
function isFreeTags (category) {
return category === 'FREETAGS'
}
function toOption (tag) {
return tag
? { label: tag.toLowerCase(), value: tag.toLowerCase() }
: { label: '', value: '' }
}
SideBarTags.contextTypes = {
intl: intlShape
}
SideBarTags.propTypes = {
serverUrl: PropTypes.string.isRequired,
corpusId: PropTypes.string.isRequired,
webentity: PropTypes.object.isRequired,
categories: PropTypes.arrayOf(PropTypes.string).isRequired,
locale: PropTypes.string.isRequired,
// actions
addTag: PropTypes.func.isRequired,
removeTag: PropTypes.func.isRequired,
addTagsCategory: PropTypes.func.isRequired,
fetchTags: PropTypes.func.isRequired
}
const mapStateToProps = ({ corpora, intl: { locale } }, props) => ({
...props,
categories: corpora.list[props.corpusId].tagsCategories || [],
locale
})
export default connect(mapStateToProps, {
addTag,
removeTag,
addTagsCategory,
fetchTags
})(SideBarTags)
| JavaScript | 0 | @@ -2648,24 +2648,39 @@
s = options.
+filter(o =%3E o).
map(o =%3E o.v
@@ -4394,40 +4394,8 @@
ble%0A
- clearable=%7B false %7D%0A
|
d139855430c7aa62eeff1c52398bd96ff90b6279 | Apply changes only to the preview that has loaded, otherwise latebloomers don't fade in. | client/js/directives/photo-stream-directive.js | client/js/directives/photo-stream-directive.js | "use strict";
angular.module("hikeio").
directive("photoStream", ["$document", "$rootScope", "$timeout", "config", function($document, $rootScope, $timeout, config) {
var normalImage = "small";
var biggerImage = "medium";
var template = "<div class='preview-list'>" +
"<a href='/hikes/{{hike.string_id}}' data-ng-repeat='hike in hikes'>" +
"<div class='preview'>" +
"<div data-ng-class='{\"featured-box\": $first}' >" +
"<img data-ng-src='" + config.hikeImagesPath + "/{{hike.photo_preview.string_id}}{{ $first && \"-" + biggerImage + "\" || \"-" + normalImage + "\" }}.jpg' data-aspect-ratio='{{hike.photo_preview.height / hike.photo_preview.width}}' alt='{{hike.photo_preview.alt}}'></img>" +
"<div class='preview-footer'>" +
"<div>" +
"<h4 class='preview-title'>{{hike.name}}</h4>" +
"<h4 class='preview-location'>{{hike.locality}}</h4>" +
"</div>" +
"<div>" +
"<h4 class='preview-distance'>{{hike.distance | distance:\"kilometers\":\"miles\":1}} mi.</h4>" +
"</div>" +
"</div>" +
"</div>" +
"</div>" +
"</a>";
return {
replace: true,
scope: {
hikes: "="
},
template: template,
link: function (scope, element) {
var gutterWidth = 2;
var maxColumnWidth = 400;
scope.$watch("hikes", function(newValue, oldValue) {
if (newValue.length === 0) return;
$timeout(function() {
element.find(".preview > div > img").load(function() {
$(this).parent().parent().css("opacity", "1");
$timeout(function() {
element.find(".preview").addClass("no-transition");
element.find(".preview").hover(function() {
$(this).css("opacity", ".95");
}, function() {
$(this).css("opacity", "1");
});
}, 400)
}).each(function() {
if (this.complete) {
$(this).load();
}
});
element.masonry({
itemSelector: ".preview",
gutterWidth: gutterWidth,
isAnimated: true,
columnWidth: function(containerWidth) {
var boxes = Math.ceil(containerWidth / maxColumnWidth);
var boxWidth = Math.floor((containerWidth - (boxes - 1) * gutterWidth) / boxes);
// TODO: clean up these selectors
element.find(".preview > div").width(boxWidth);
element.find(".preview > div > img").each(function(i, img) {
var aspectRatio = parseFloat($(img).attr("data-aspect-ratio"), 10);
$(img).height(aspectRatio * boxWidth);
});
if (boxes !== 1) {
element.find(".preview > .featured-box").width(boxWidth * 2 + gutterWidth);
var featuredBoxImage = element.find(".preview > .featured-box > img");
var aspectRatio = parseFloat(featuredBoxImage.attr("data-aspect-ratio"), 10);
featuredBoxImage.height(aspectRatio * boxWidth * 2);
}
return boxWidth;
}
});
});
}, true);
}
};
}]); | JavaScript | 0 | @@ -1475,24 +1475,38 @@
() %7B%0A%09%09%09%09%09%09%09
+var preview =
$(this).pare
@@ -1518,16 +1518,32 @@
parent()
+;%0A%09%09%09%09%09%09%09preview
.css(%22op
@@ -1597,32 +1597,15 @@
%09%09%09%09
-element.find(%22.
preview
-%22)
.add
@@ -1640,32 +1640,15 @@
%09%09%09%09
-element.find(%22.
preview
-%22)
.hov
@@ -1664,39 +1664,39 @@
on() %7B%0A%09%09%09%09%09%09%09%09%09
-$(this)
+preview
.css(%22opacity%22,
@@ -1736,23 +1736,23 @@
%09%09%09%09%09%09%09%09
-$(this)
+preview
.css(%22op
|
9ee3ebb027f45516de9fbd7987c8b2afb4b92b66 | Add background color | client/js/mini-app/components/resource-card.js | client/js/mini-app/components/resource-card.js | import React from 'react'
import injectSheet from 'react-jss'
const formatPhoneNumber = phoneNumber => {
const areaCode = phoneNumber.substring(2, 5)
const prefix = phoneNumber.substring(5, 8)
const lineNumber = phoneNumber.substring(8, 12)
return `${areaCode}-${prefix}-${lineNumber}`
}
const ResourceCard = ({ classes, resource }) => {
const { line1, line2, city, state, zip } = resource.address
return (
<div className={classes.root}>
<div className={classes.resourceName}>{resource.prcName}</div>
<div className={classes.resourceAddress}>
{line1} <br />
{line2} {line2 && <br />}
{`${city}, ${state} ${zip}`}
</div>
<div className={classes.resourcePhone}>
<a href={`tel:${resource.phone}`}>
{formatPhoneNumber(resource.phone)}
</a>
</div>
<div className={classes.resourceWebsite}>
<a href={resource.website} target="_blank" rel="noopener noreferrer">
{resource.website}
</a>
</div>
</div>
)
}
const styles = {
root: {
border: '2px solid #3d65f9',
'border-radius': '4px',
margin: '20px 20px 20px 20px',
},
resourceName: {
margin: '40px 0px 0px 30px',
'font-family': 'sans-serif',
'font-size': '20px',
},
resourceAddress: {
margin: '20px 0px 20px 30px',
'font-family': 'sans-serif',
'font-size': '15px',
},
resourcePhone: {
margin: '20px 0px 20px 30px',
'font-family': 'sans-serif',
'font-size': '15px',
},
resourceWebsite: {
margin: '20px 0px 20px 30px',
'font-family': 'sans-serif',
'font-size': '15px',
},
}
export default injectSheet(styles)(ResourceCard)
| JavaScript | 0.000002 | @@ -441,14 +441,75 @@
es.r
+esourceCardR
oot%7D%3E%0A
+%09%09%09%3Cdiv className=%7Bclasses.resourceCardBorder%7D%3E%0A%09
%09%09%09%3C
@@ -566,24 +566,25 @@
Name%7D%3C/div%3E%0A
+%09
%09%09%09%3Cdiv clas
@@ -616,24 +616,25 @@
dress%7D%3E%0A%09%09%09%09
+%09
%7Bline1%7D %3Cbr
@@ -636,16 +636,17 @@
%3Cbr /%3E%0A
+%09
%09%09%09%09%7Blin
@@ -671,16 +671,17 @@
/%3E%7D%0A%09%09%09%09
+%09
%7B%60$%7Bcity
@@ -700,31 +700,33 @@
$%7Bzip%7D%60%7D%0A%09%09%09
+%09
%3C/div%3E%0A
+%09
%09%09%09%3Cdiv clas
@@ -752,32 +752,33 @@
urcePhone%7D%3E%0A%09%09%09%09
+%09
%3Ca href=%7B%60tel:$%7B
@@ -796,16 +796,17 @@
one%7D%60%7D%3E%0A
+%09
%09%09%09%09%09%7Bfo
@@ -838,16 +838,17 @@
phone)%7D%0A
+%09
%09%09%09%09%3C/a%3E
@@ -851,23 +851,25 @@
%3C/a%3E%0A%09%09%09
+%09
%3C/div%3E%0A
+%09
%09%09%09%3Cdiv
@@ -901,24 +901,25 @@
ceWebsite%7D%3E%0A
+%09
%09%09%09%09%3Ca href=
@@ -985,16 +985,17 @@
%22%3E%0A%09%09%09%09%09
+%09
%7Bresourc
@@ -1005,16 +1005,17 @@
ebsite%7D%0A
+%09
%09%09%09%09%3C/a%3E
@@ -1015,16 +1015,27 @@
%09%09%09%3C/a%3E%0A
+%09%09%09%09%3C/div%3E%0A
%09%09%09%3C/div
@@ -1070,19 +1070,103 @@
s = %7B%0A%09r
-oot
+esourceCardRoot: %7B%0A%09%09border: '20px solid rgb(93, 93, 93, .08)',%0A%09%7D,%0A%09resourceCardBorder
: %7B%0A%09%09bo
@@ -1222,41 +1222,8 @@
x',%0A
-%09%09margin: '20px 20px 20px 20px',%0A
%09%7D,%0A
@@ -1578,33 +1578,33 @@
rgin: '20px 0px
-2
+4
0px 30px',%0A%09%09'fo
|
4f4ee3967a9410fc22ebd0d26e6c289fbfaf5635 | fix client side test | ui/shared/components/page/Footer.test.js | ui/shared/components/page/Footer.test.js | import React from 'react'
import { shallow, configure } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
import Footer from './Footer'
configure({ adapter: new Adapter() })
test('shallow-render without crashing', () => {
shallow(<Footer />)
})
| JavaScript | 0.000001 | @@ -109,16 +109,62 @@
act-16'%0A
+import configureStore from 'redux-mock-store'%0A
import F
@@ -185,16 +185,16 @@
Footer'%0A
-
%0Aconfigu
@@ -273,16 +273,79 @@
() =%3E %7B%0A
+ const store = configureStore()(%7B meta: %7Bversion: '0.1' %7D %7D)%0A%0A
shallo
@@ -353,16 +353,30 @@
(%3CFooter
+ store=%7Bstore%7D
/%3E)%0A%7D)%0A
|
7265f0f503c2fe24f195bc023f9367ec55201408 | Remove delete for _internal db | ui/src/admin/components/DatabaseTable.js | ui/src/admin/components/DatabaseTable.js | import React, {PropTypes} from 'react'
import DatabaseRow from 'src/admin/components/DatabaseRow'
import ConfirmButtons from 'src/admin/components/ConfirmButtons'
const {
func,
shape,
bool,
} = PropTypes
const DatabaseTable = ({
database,
notify,
isRFDisplayed,
onEditDatabase,
onKeyDownDatabase,
onCancelDatabase,
onConfirmDatabase,
onStartDeleteDatabase,
onDatabaseDeleteConfirm,
onAddRetentionPolicy,
onCreateRetentionPolicy,
onUpdateRetentionPolicy,
onRemoveRetentionPolicy,
onDeleteRetentionPolicy,
}) => {
return (
<div className="db-manager">
<DatabaseTableHeader
database={database}
isAddRPDisabled={!!database.retentionPolicies.some(rp => rp.isNew)}
onEdit={onEditDatabase}
onKeyDown={onKeyDownDatabase}
onCancel={onCancelDatabase}
onConfirm={onConfirmDatabase}
onStartDelete={onStartDeleteDatabase}
onDatabaseDeleteConfirm={onDatabaseDeleteConfirm}
onAddRetentionPolicy={onAddRetentionPolicy}
/>
<div className="db-manager-table">
<table className="table v-center admin-table">
<thead>
<tr>
<th>Retention Policy</th>
<th>Duration</th>
{isRFDisplayed ? <th>Replication Factor</th> : null}
<th></th>
</tr>
</thead>
<tbody>
{
database.retentionPolicies.map(rp => {
return (
<DatabaseRow
key={rp.links.self}
notify={notify}
database={database}
retentionPolicy={rp}
onCreate={onCreateRetentionPolicy}
onUpdate={onUpdateRetentionPolicy}
onRemove={onRemoveRetentionPolicy}
onDelete={onDeleteRetentionPolicy}
isRFDisplayed={isRFDisplayed}
isDeletable={database.retentionPolicies.length > 1}
/>
)
})
}
</tbody>
</table>
</div>
</div>
)
}
DatabaseTable.propTypes = {
onEditDatabase: func,
database: shape(),
notify: func,
isRFDisplayed: bool,
isAddRPDisabled: bool,
onKeyDownDatabase: func,
onCancelDatabase: func,
onConfirmDatabase: func,
onStartDeleteDatabase: func,
onDatabaseDeleteConfirm: func,
onAddRetentionPolicy: func,
onCancelRetentionPolicy: func,
onCreateRetentionPolicy: func,
onUpdateRetentionPolicy: func,
onRemoveRetentionPolicy: func,
onDeleteRetentionPolicy: func,
}
const DatabaseTableHeader = ({
database,
onEdit,
onKeyDown,
onConfirm,
onCancel,
onStartDelete,
onDatabaseDeleteConfirm,
onAddRetentionPolicy,
isAddRPDisabled,
}) => {
if (database.isEditing) {
return (
<EditHeader
database={database}
onEdit={onEdit}
onKeyDown={onKeyDown}
onConfirm={onConfirm}
onCancel={onCancel}
/>
)
}
return (
<Header
database={database}
onStartDelete={onStartDelete}
onDatabaseDeleteConfirm={onDatabaseDeleteConfirm}
onAddRetentionPolicy={onAddRetentionPolicy}
onConfirm={onConfirm}
onCancel={onCancel}
isAddRPDisabled={isAddRPDisabled}
/>
)
}
DatabaseTableHeader.propTypes = {
onEdit: func,
database: shape(),
onKeyDown: func,
onCancel: func,
onConfirm: func,
onStartDelete: func,
onDatabaseDeleteConfirm: func,
onAddRetentionPolicy: func,
isAddRPDisabled: bool,
}
const Header = ({
database,
onStartDelete,
onDatabaseDeleteConfirm,
onAddRetentionPolicy,
isAddRPDisabled,
onCancel,
onConfirm,
}) => {
const confirmStyle = {
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
}
const buttons = (
<div className="text-right">
<button className="btn btn-xs btn-danger" onClick={() => onStartDelete(database)}>
Delete
</button>
<button className="btn btn-xs btn-primary" disabled={isAddRPDisabled} onClick={() => onAddRetentionPolicy(database)}>
Add retention policy
</button>
</div>
)
const deleteConfirm = (
<div style={confirmStyle}>
<div className="admin-table--delete-cell">
<input
className="form-control"
name="name"
type="text"
value={database.deleteCode || ''}
placeholder={`DELETE ${database.name}`}
onChange={(e) => onDatabaseDeleteConfirm(database, e)}
onKeyDown={(e) => onDatabaseDeleteConfirm(database, e)}
autoFocus={true}
/>
</div>
<ConfirmButtons item={database} onConfirm={onConfirm} onCancel={onCancel} />
</div>
)
return (
<div className="db-manager-header">
<h4>{database.name}</h4>
{database.hasOwnProperty('deleteCode') ? deleteConfirm : buttons}
</div>
)
}
Header.propTypes = {
database: shape(),
onStartDelete: func,
onDatabaseDeleteConfirm: func,
onAddRetentionPolicy: func,
isAddRPDisabled: bool,
onConfirm: func,
onCancel: func,
}
const EditHeader = ({database, onEdit, onKeyDown, onConfirm, onCancel}) => (
<div className="db-manager-header-edit">
<input
className="form-control"
name="name"
type="text"
value={database.name}
placeholder="Database name"
onChange={(e) => onEdit(database, {name: e.target.value})}
onKeyDown={(e) => onKeyDown(e, database)}
autoFocus={true}
/>
<ConfirmButtons item={database} onConfirm={onConfirm} onCancel={onCancel} />
</div>
)
EditHeader.propTypes = {
database: shape(),
onEdit: func,
onKeyDown: func,
onCancel: func,
onConfirm: func,
isRFDisplayed: bool,
}
export default DatabaseTable
| JavaScript | 0 | @@ -3870,24 +3870,83 @@
ext-right%22%3E%0A
+ %7B%0A database.name === '_internal' ? null :%0A
%3Cbutto
@@ -4034,15 +4034,23 @@
+
Delete%0A
+
@@ -4057,24 +4057,32 @@
%3C/button%3E%0A
+ %7D%0A
%3Cbutto
|
7f49b2acf87867abc792ceeddf62a186e3cb274b | Make the toggleButton function a self contained object binding to change events. | app/soc/content/js/melange.action.js | app/soc/content/js/melange.action.js | /* Copyright 2011 the Melange authors.
*
* 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.
*/
/**
* @author <a href="mailto:madhusudancs@gmail.com">Madhusudan.C.S</a>
*/
(function () {
/** @lends melange.action */
if (window.melange === undefined) {
throw new Error("Melange not loaded");
}
var melange = window.melange;
/** Package that handles all action buttons related functions
* @name melange.action
* @namespace melange.action
* @borrows melange.logging.debugDecorator.log as log
*/
melange.action = window.melange.action = function () {
return new melange.action();
};
/** Shortcut to current package.
* @private
*/
var $m = melange.logging.debugDecorator(melange.action);
melange.error.createErrors([
]);
$m.createFloatMenu = function () {
var name = "#floatMenu";
var menuYloc = null;
jQuery(document).ready(function(){
menuYloc = parseInt(jQuery(name).css("top").substring(
0, jQuery(name).css("top").indexOf("px")))
jQuery(window).scroll(function () {
offset = menuYloc + jQuery(document).scrollTop()+"px";
jQuery(name).animate({top: offset},{duration: 500, queue: false});
});
});
}
$m.createToggleButton = function () {
$(window).load(function() {
$('.on_off :checkbox').iphoneStyle({
checkedLabel: 'Yes', uncheckedLabel: 'No'
});
$('.disabled :checkbox').iphoneStyle({
checkedLabel: 'Yes', uncheckedLabel: 'No'
});
$('.long :checkbox').iphoneStyle({
checkedLabel: 'Enable', uncheckedLabel: 'Disable'
});
/* This function exists as a show case function to show that this
* functionality of chaining the onchange of some other button to
* this button is possible. It is currently not used anywhere. */
$m.createOnChangeButton = function () {
var onchange_checkbox = jQuery('.onchange :checkbox').iphoneStyle();
setInterval(function toggleCheckbox() {
onchange_checkbox.attr(
'checked', !onchange_checkbox.is(':checked')).change();
jQuery('span#status').html(onchange_checkbox.is(':checked').toString());
}, 2500);
}
$m.createCluetip = function () {
jQuery(document).ready(function() {
jQuery('a.load-tooltip').cluetip({
local:true,
cursor: 'pointer',
showTitle:false,
tracking:true,
dropShadow:false
});
});
}
}());
| JavaScript | 0 | @@ -1730,15 +1730,9 @@
$m.
-createT
+t
oggl
@@ -1755,39 +1755,232 @@
on (
-) %7B%0A $(window).load(
+id, type, post_url, init_state, labels) %7B%0A this.id = id;%0A this.type = type;%0A this.post_url = post_url;%0A this.state = init_state;%0A this.labels = labels;%0A%0A var self_obj = this;%0A%0A this.is_enabled =
function
() %7B
@@ -1967,32 +1967,33 @@
abled = function
+
() %7B%0A $('.o
@@ -1991,102 +1991,134 @@
-$('.on_off :checkbox').iphoneStyle(%7B%0A checkedLabel: 'Yes', uncheckedLabel: 'No'
+if (this.state == %22enabled%22) %7B%0A return true;%0A %7D else if (this.state == %22disabled%22) %7B%0A return false;
%0A %7D
);%0A
@@ -2117,224 +2117,617 @@
%7D
-);
%0A
- $('.disabled :checkbox').iphoneStyle(%7B%0A checkedLabel: 'Yes', uncheckedLabel: 'No'%0A %7D);%0A $('.long :checkbox').iphoneStyle(%7B%0A checkedLabel: 'Enable', uncheckedLabel: 'Disable'%0A %7D);
+%7D%0A%0A jQuery(window).load(function() %7B%0A jQuery('.' + self_obj.type + ' :checkbox#' + self_obj.id).iphoneStyle(%7B%0A checkedLabel: self_obj.labels.checked,%0A uncheckedLabel: self_obj.labels.unchecked%0A %7D).change(function ()%7B%0A jQuery.post(self_obj.post_url,%0A %7Bvalue: self_obj.state, xsrf_token: window.xsrf_token%7D,%0A function(data) %7B%0A if (self_obj.state == %22enabled%22) %7B%0A self_obj.state = %22disabled%22;%0A %7D else if (self_obj.state == %22disabled%22) %7B%0A self_obj.state = %22enabled%22;%0A %7D%0A %7D);%0A %7D);%0A %7D);%0A %7D
%0A%0A
|
a761a4713c9a5b4b142876d6b0619afa7fddb112 | Add const ERROR_CANCELLED | www/cordova-plugin-multiple-media-selection.js | www/cordova-plugin-multiple-media-selection.js | var exec = require('cordova/exec');
var MultipleMediaSelection = function(){};
MultipleMediaSelection.prototype.getPictures = function(success, error, options) {
options = options || {};
options.height = options.height || 0;
options.isTemporaryFile = typeof options.isTemporaryFile == 'undefined' || options.isTemporaryFile == true;
options.maxImages = options.maxImages || 5;
options.mediaType = options.mediaType || 'any';
options.minImages = options.minImages || 0;
options.quality = options.quality || 100;
options.width = options.width || 0;
exec(success, error, 'MultipleMediaSelection', 'getPictures', [options]);
};
window.multipleMediaSelection = new MultipleMediaSelection();
| JavaScript | 0.000067 | @@ -74,16 +74,114 @@
n()%7B%7D;%0A%0A
+// Refer to MediaPicker.java:136%0AMultipleMediaSelection.prototype.ERROR_CANCELLED = 'Cancelled';%0A%0A
Multiple
|
f0c56820be9c728e704d69fe1ea90a03cbf6d1dc | Update admin settings controler for nodemailer | app/controllers/settings.server.controller.js | app/controllers/settings.server.controller.js | 'use strict';
var settingsService = require('../services/settings.server.service'),
nodemailer = require('nodemailer'),
_ = require('lodash');
exports.createSettings = function(req, res) {
settingsService.createSettings(req)
.then(function(settings) {
return res.status(200).send(settings);
})
.catch(function(error) {
return res.status(500).send(error);
})
.done();
};
exports. getSettings = function(req, res) {
settingsService.getSettings(req)
.then(function(settings) {
return res.status(200).send(settings);
})
.catch(function(error) {
return res.status(500).send(error);
})
.done();
};
exports.updateSettings = function(req, res) {
settingsService.updateSettings(req)
.then(function(settings) {
return res.status(200).send({msg:'Successfully update'});
})
.catch(function(error) {
return res.status(500).send(error);
})
.done();
};
exports. getEmailSettings = function(req, res) {
settingsService.getSettings(req)
.then(function(settings) {
return res.status(200).send(settings);
})
.catch(function(error) {
return res.status(500).send(error);
})
.done();
};
var emailSend = function(emailSettings, recipientEmail, subject, htmlBody, callback){
var smtpTransport = nodemailer.createTransport({
host: emailSettings.host,
port: emailSettings.port,
secure: emailSettings.ssl,
auth: {
user: emailSettings.user,
pass: emailSettings.password
}
});
var mailOptions = {
from: emailSettings.emailDisplayName +'-<'+ emailSettings.emailAddress +'>',
to: recipientEmail,
subject: subject + ' ✔',
html: htmlBody
};
smtpTransport.sendMail(mailOptions, function(error, response){
if(error){
callback(false);
}else{
callback(true);
}
// if you don't want to use this transport object anymore, uncomment following line
//smtpTransport.close(); // shut down the connection pool, no more messages
});
};
var getDefaultEmailInfo = function(callback) {
var emailCount = 0;
var defaultEmailInfo = null;
settingsService.getSettings()
.then(function(settings) {
_.forEach(settings.emails, function(email) {
emailCount+=1;
if(email.isDefault) {
defaultEmailInfo = email;
}
});
if(emailCount === settings.emails.length) {
callback(defaultEmailInfo);
}
})
.catch(function(error) {
callback(defaultEmailInfo);
})
.done();
};
exports.getDefaultEmailSettings = function(callback) {
getDefaultEmailInfo(function(defaultEmailInfo) {
if(defaultEmailInfo) {
callback(defaultEmailInfo);
}
else {
callback(null);
}
});
};
exports. testEmailSettingsBySendEmail = function(req, res) {
getDefaultEmailInfo(function(defaultEmailInfo) {
if(defaultEmailInfo) {
emailSend(defaultEmailInfo, req.body.sendTo, 'Test email setting','<h2>BS-Commerce email settings is perfect </h2>', function(sent) {
if(sent) {
return res.status(200).send({msg: 'Successfully send your mail'});
}
return res.status(500).send({msg: 'Not send your mail. Please check your settings'});
});
}
});
};
| JavaScript | 0 | @@ -1486,223 +1486,94 @@
ort(
-%7B%0A host: emailSettings.host,%0A port: emailSettings.port,%0A secure: emailSettings.ssl,%0A auth: %7B%0A user: emailSettings.user,%0A pass: emailSettings.password%0A %7D%0A %7D
+'smtps://'+emailSettings.user+'%2540gmail.com:'+emailSettings.password+'@smtp.gmail.com'
);%0A%0A
@@ -1927,24 +1927,24 @@
back(true);%0A
+
%7D%0A%0A
@@ -1944,185 +1944,8 @@
%7D
-%0A%0A // if you don't want to use this transport object anymore, uncomment following line%0A //smtpTransport.close(); // shut down the connection pool, no more messages
%0A
|
bc10e69498a385d5f2d64bac1d2e8a7af7546733 | Fix Angular 5 + Webpack error: "Critical dependency: the request of a dependency is an expression" | generators/client/templates/angular/webpack/_webpack.common.js | generators/client/templates/angular/webpack/_webpack.common.js | <%#
Copyright 2013-2017 the original author or authors from the JHipster project.
This file is part of the JHipster project, see http://www.jhipster.tech/
for more information.
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.
-%>
const webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const StringReplacePlugin = require('string-replace-webpack-plugin');
<%_ if (enableTranslation) { _%>
const MergeJsonWebpackPlugin = require("merge-jsons-webpack-plugin");
<%_ } _%>
const utils = require('./utils.js');
module.exports = (options) => {
const DATAS = {
VERSION: `'${utils.parseVersion()}'`,
DEBUG_INFO_ENABLED: options.env === 'development'<% if (authenticationType !== 'uaa') { %>,
// The root URL for API calls, ending with a '/' - for example: `"http://www.jhipster.tech:8081/myservice/"`.
// If this URL is left empty (""), then it will be relative to the current context.
// If you use an API server, in `prod` mode, you will need to enable CORS
// (see the `jhipster.cors` common JHipster property in the `application-*.yml` configurations)
SERVER_API_URL: `""`<% } %>
};
return {
resolve: {
extensions: ['.ts', '.js'],
modules: ['node_modules']
},
stats: {
children: false
},
module: {
rules: [
{ test: /bootstrap\/dist\/js\/umd\//, loader: 'imports-loader?jQuery=jquery' },
{
test: /\.html$/,
loader: 'html-loader',
options: {
minimize: true,
caseSensitive: true,
removeAttributeQuotes:false,
minifyJS:false,
minifyCSS:false
},
exclude: ['./<%= MAIN_SRC_DIR %>index.html']
},
{
test: /\.(jpe?g|png|gif|svg|woff2?|ttf|eot)$/i,
loaders: ['file-loader?hash=sha512&digest=hex&name=content/[hash].[ext]']
},
{
test: /manifest.webapp$/,
loader: 'file-loader?name=manifest.webapp!web-app-manifest-loader'
},
{
test: /app.constants.ts$/,
loader: StringReplacePlugin.replace({
replacements: [{
pattern: /\/\* @toreplace (\w*?) \*\//ig,
replacement: (match, p1, offset, string) => `_${p1} = ${DATAS[p1]};`
}]
})
}
]
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify(options.env)
}
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'polyfills',
chunks: ['polyfills']
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
chunks: ['main'],
minChunks: module => utils.isExternalLib(module)
}),
new webpack.optimize.CommonsChunkPlugin({
name: ['polyfills', 'vendor'].reverse()
}),
new webpack.optimize.CommonsChunkPlugin({
name: ['manifest'],
minChunks: Infinity,
}),
/**
* See: https://github.com/angular/angular/issues/11580
*/
new webpack.ContextReplacementPlugin(
/angular(\\|\/)core(\\|\/)@angular/,
utils.root('<%= MAIN_SRC_DIR %>app'), {}
),
new CopyWebpackPlugin([
{ from: './node_modules/swagger-ui/dist/css', to: 'swagger-ui/dist/css' },
{ from: './node_modules/swagger-ui/dist/lib', to: 'swagger-ui/dist/lib' },
{ from: './node_modules/swagger-ui/dist/swagger-ui.min.js', to: 'swagger-ui/dist/swagger-ui.min.js' },
{ from: './<%= MAIN_SRC_DIR %>swagger-ui/', to: 'swagger-ui' },
{ from: './<%= MAIN_SRC_DIR %>favicon.ico', to: 'favicon.ico' },
{ from: './<%= MAIN_SRC_DIR %>manifest.webapp', to: 'manifest.webapp' },
// jhipster-needle-add-assets-to-webpack - JHipster will add/remove third-party resources in this array
{ from: './<%= MAIN_SRC_DIR %>robots.txt', to: 'robots.txt' }
]),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
}),
<%_ if (enableTranslation) { _%>
new MergeJsonWebpackPlugin({
output: {
groupBy: [
// jhipster-needle-i18n-language-webpack - JHipster will add/remove languages in this array
]
}
}),
<%_ } _%>
new HtmlWebpackPlugin({
template: './<%= MAIN_SRC_DIR %>index.html',
chunksSortMode: 'dependency',
inject: 'body'
}),
new StringReplacePlugin()
]
};
};
| JavaScript | 0.000001 | @@ -4248,16 +4248,21 @@
/
+(.+)?
angular(
@@ -4276,22 +4276,12 @@
ore(
-%5C%5C%7C%5C/)@angular
+.+)?
/,%0A
|
b887126fe7158c24ee3300880bccadeb11ca86b0 | Add auto-hash prepend to channels | app/directives/beamNetworkClient.js | app/directives/beamNetworkClient.js | var irc = require('irc');
angular.module('beam.directives')
.directive('beamNetworkClient', function() {
return {
restrict: 'E',
templateUrl: '../templates/beamNetworkClient.html',
scope: {
settings: '@',
},
controller: function($compile, $scope, $rootScope, ircService, configService) {
this.channels = [];
this.topics = {};
this.currentChannel = '';
this.connectionClosed = true;
this.connectionError = 'Unknown error';
this.showChannelModal = false;
this.displayChannelModal = function() {
this.showChannelModal = true;
}.bind(this);
this.onRegistered = function() {
this.connected = true;
}.bind(this);
this.setTopic = function(channel, topic) {
this.topics[channel] = topic;
};
this.connect = function(settings) {
ircService.connect(settings);
};
if (!configService.canLoad()) {
// Signal main process to open welcome dialog because settings aren't
// available.
require('ipc').send('show-welcome', true);
}
this.host = configService.get('host');
this.connect({
host: this.host,
port: configService.get('port'),
nick: configService.get('nick'),
userName: configService.get('userName'),
realName: configService.get('realName'),
channels: configService.get('channels'),
autoRejoin: configService.get('autoRejoin'),
tls: configService.get('tls'),
ignoreSecure: configService.get('ignoreSecure'),
});
this.connection = ircService.get(this.host);
this.connection.on('registered', this.onRegistered);
this.connection.on('ctcp-version', function(from, to) {
if (to === this.connection.nick) {
var os = require('os');
var platform = os.platform() + ' ' + os.arch();
this.connection.ctcp(from, 'notice', 'VERSION beam.io v0.1.0-a3 on ' + platform);
}
}.bind(this));
this.connection.on('error', function(message) {
console.log('Error in IRC library: ', message);
}.bind(this));
this.connection.conn.addListener('close', function() {
this.connectionClosed = true;
}.bind(this));
this.connection.conn.addListener('error', function(err) {
this.connectionError = err;
$scope.$apply();
}.bind(this));
this.connection.on('join', function(channel, nick) {
if (nick === this.connection.nick) {
this.channels.push(channel);
$scope.$apply();
this.currentChannel = channel;
}
}.bind(this));
this.connection.on('part', function(channel, nick) {
if (nick === this.connection.nick) {
this.removeTab(channel);
$scope.$apply();
}
}.bind(this));
this.connection.on('pm', function(nick, text) {
this.addChannel(nick);
$scope.$apply();
$rootScope.$broadcast(('message|' + nick), text);
}.bind(this));
// Called on /msg
$rootScope.$on('selfMessage', function(event, data) {
this.addChannel(data[0]);
$rootScope.$broadcast(('selfMessage|' + data[0]), data[1]);
}.bind(this));
this.addChannel = function(channel) {
if (this.channels.indexOf(channel) === -1) {
this.channels.push(channel);
this.topics[channel] = '';
}
};
this.setActiveChannel = function(channel) {
this.currentChannel = channel;
}.bind(this);
this.joinChannel = function(channel) {
this.connection.join($scope.channelToJoin);
$scope.channelToJoin = '';
this.showChannelModal = false;
}.bind(this);
this.partChannel = function(channel) {
// Check if only channel open.
if (this.channels.indexOf(channel) == 0 & this.channels.length == 1) {
// Close connection? Close window? Destroy the universe?
;
} else {
// If not, close channel.
this.connection.part(channel);
// Check if first channel in list.
if (this.channels.indexOf(channel) == 0) {
// If so, select next channel.
this.currentChannel = this.channels[this.channels.indexOf(channel) + 1];
} else {
// If not, select previous channel.
this.currentChannel = this.channels[this.channels.indexOf(channel) - 1];
}
// Remove channel tab.
this.removeTab(channel);
}
}.bind(this);
this.showModal = function() {
$('.ui.modal').modal('show');
}.bind(this);
this.removeTab = function(channel) {
var chan = this.channels.indexOf(channel);
// Channel may have alredy been removed on part. check.
if (chan !== -1) {
this.channels.splice(chan, 1);
}
};
},
controllerAs: 'clientCtrl',
};
});
| JavaScript | 0 | @@ -3774,32 +3774,162 @@
tion(channel) %7B%0A
+ if (!$scope.channelToJoin.startsWith('#')) %7B%0A $scope.channelToJoin = '#' + $scope.channelToJoin;%0A %7D%0A
this.c
|
bb6b05b724f7c83309467d8f20695eef423fd57b | Make header transport API consistent with cookie | js/server/modules/@arangodb/foxx/sessions/transports/header.js | js/server/modules/@arangodb/foxx/sessions/transports/header.js | 'use strict';
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2015 ArangoDB GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Alan Plum
////////////////////////////////////////////////////////////////////////////////
module.exports = function headerTransport(name) {
if (!name) {
name = 'X-Session-Id';
}
return {
get(req) {
return req.headers[name.toLowerCase()];
},
set(res, value) {
res.set(name, value);
}
};
};
| JavaScript | 0.000001 | @@ -125,16 +125,21 @@
ght 2015
+-2016
ArangoD
@@ -943,20 +943,19 @@
ansport(
-name
+cfg
) %7B%0A if
@@ -961,20 +961,19 @@
f (!
-name
+cfg
) %7B%0A
name
@@ -968,20 +968,19 @@
) %7B%0A
-name
+cfg
= 'X-Se
@@ -994,16 +994,76 @@
d';%0A %7D%0A
+ if (typeof cfg === 'string') %7B%0A cfg = %7Bname: cfg%7D;%0A %7D%0A
return
@@ -1105,16 +1105,20 @@
headers%5B
+cfg.
name.toL
@@ -1173,16 +1173,20 @@
res.set(
+cfg.
name, va
|
9dace23d92a65a7dd2b6029173cce5432632c7f7 | Fix missing light shadows when some props have not been included | src/lib/descriptors/Light/DirectionalLightDescriptor.js | src/lib/descriptors/Light/DirectionalLightDescriptor.js | import THREE from 'three.js';
import LightDescriptorBase from './LightDescriptorBase';
import PropTypes from 'react/lib/ReactPropTypes';
class DirectionalLightDescriptor extends LightDescriptorBase {
constructor(react3Instance) {
super(react3Instance);
this.hasProp('intensity', {
type: PropTypes.number,
simple: true,
default: 1,
});
this.hasProp('shadowBias', {
type: PropTypes.number,
simple: true,
default: 0,
});
this.hasProp('shadowDarkness', {
type: PropTypes.number,
simple: true,
default: 0.5,
});
[
'shadowMapWidth',
'shadowMapHeight',
].forEach(propName => {
this.hasProp(propName, {
type: PropTypes.number,
updateInitial: true,
update(threeObject, value) {
threeObject[propName] = value;
},
default: 512,
});
});
this.hasProp('shadowCameraNear', {
type: PropTypes.number,
updateInitial: true,
update(threeObject, value) {
threeObject.shadow.camera.near = value;
// threeObject.shadow.camera.updateProjectionMatrix();
},
default: 50,
});
this.hasProp('shadowCameraFar', {
type: PropTypes.number,
updateInitial: true,
update(threeObject, value) {
threeObject.shadow.camera.far = value;
// threeObject.shadow.camera.updateProjectionMatrix();
},
default: 5000,
});
[
'shadowCameraLeft',
'shadowCameraBottom',
].forEach(propName => {
this.hasProp(propName, {
type: PropTypes.number,
updateInitial: true,
update(threeObject, value) {
threeObject[propName] = value;
// threeObject.shadow.camera.updateProjectionMatrix();
},
default: -500,
});
});
[
'shadowCameraRight',
'shadowCameraTop',
].forEach(propName => {
this.hasProp(propName, {
type: PropTypes.number,
updateInitial: true,
update(threeObject, value) {
threeObject[propName] = value;
// threeObject.shadow.camera.updateProjectionMatrix();
},
default: 500,
});
});
this.hasProp('castShadow', {
override: true,
type: PropTypes.bool,
update: this.triggerRemount,
default: false,
});
this.hasColor();
}
applyInitialProps(threeObject, props) {
super.applyInitialProps(threeObject, props);
if (props.hasOwnProperty('castShadow')) {
threeObject.castShadow = props.castShadow;
}
}
construct(props) {
const color = props.color;
const intensity = props.intensity;
return new THREE.DirectionalLight(color, intensity);
}
unmount(threeObject) {
super.unmount(threeObject);
}
}
export default DirectionalLightDescriptor;
| JavaScript | 0.999999 | @@ -790,36 +790,72 @@
reeObject, value
+, hasProp
) %7B%0A
+ if (hasProp) %7B%0A
threeO
@@ -871,32 +871,44 @@
pName%5D = value;%0A
+ %7D%0A
%7D,%0A
@@ -1062,36 +1062,70 @@
reeObject, value
+, hasProp
) %7B%0A
+ if (hasProp) %7B%0A
threeObj
@@ -1148,32 +1148,42 @@
a.near = value;%0A
+ %7D%0A
// three
@@ -1384,36 +1384,70 @@
reeObject, value
+, hasProp
) %7B%0A
+ if (hasProp) %7B%0A
threeObj
@@ -1469,32 +1469,42 @@
ra.far = value;%0A
+ %7D%0A
// three
@@ -1794,36 +1794,72 @@
reeObject, value
+, hasProp
) %7B%0A
+ if (hasProp) %7B%0A
threeO
@@ -1875,32 +1875,44 @@
pName%5D = value;%0A
+ %7D%0A
// thr
@@ -2224,20 +2224,56 @@
t, value
+, hasProp
) %7B%0A
+ if (hasProp) %7B%0A
@@ -2297,32 +2297,44 @@
pName%5D = value;%0A
+ %7D%0A
// thr
|
a94333649a5374c593100a72aa6d8f442a4fce82 | Update `propTypes` for the `CTA` component | assets/js/components/notifications/CTA.js | assets/js/components/notifications/CTA.js | /**
* CTA component.
*
* Site Kit by Google, Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* External dependencies
*/
import PropTypes from 'prop-types';
import classnames from 'classnames';
/**
* Internal dependencies
*/
import Link from '../Link';
const CTA = ( {
title,
description,
ctaLink,
ctaLabel,
ctaLinkExternal,
error,
onClick,
'aria-label': ariaLabel,
} ) => (
<div
className={ classnames( 'googlesitekit-cta', {
'googlesitekit-cta--error': error,
} ) }
>
{ title && <h3 className="googlesitekit-cta__title">{ title }</h3> }
{ description && typeof description === 'string' && (
<p className="googlesitekit-cta__description">{ description }</p>
) }
{ description && typeof description !== 'string' && (
<div className="googlesitekit-cta__description">
{ description }
</div>
) }
{ ctaLabel && (
<Link
href={ ctaLink }
onClick={ onClick }
inverse={ ! error }
caps
arrow
aria-label={ ariaLabel }
external={ ctaLinkExternal }
hideExternalIndicator={ ctaLinkExternal }
>
{ ctaLabel }
</Link>
) }
</div>
);
CTA.propTypes = {
title: PropTypes.string.isRequired,
description: PropTypes.oneOfType( [ PropTypes.string, PropTypes.node ] ),
ctaLink: PropTypes.string,
ctaLabel: PropTypes.string,
'aria-label': PropTypes.string,
error: PropTypes.bool,
onClick: PropTypes.func,
};
CTA.defaultProps = {
title: '',
description: '',
ctaLink: '',
ctaLabel: '',
error: false,
onClick: () => {},
};
export default CTA;
| JavaScript | 0 | @@ -1924,16 +1924,50 @@
s.func,%0A
+%09ctaLinkExternal: PropTypes.bool,%0A
%7D;%0A%0ACTA.
@@ -2077,16 +2077,41 @@
=%3E %7B%7D,%0A
+%09ctaLinkExternal: false,%0A
%7D;%0A%0Aexpo
|
0ea8b47dc2f896130b166c93ec4b1c94310b95eb | Fix serialization | lib/node_modules/@stdlib/ndarray/base/memoized-ctor/lib/key.js | lib/node_modules/@stdlib/ndarray/base/memoized-ctor/lib/key.js | /**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// MODULES //
var OPTIONS = require( './options.json' );
// VARIABLES //
var NOPTS = OPTIONS.length;
// MAIN //
/**
* Returns a cache key.
*
* @private
* @param {string} dtype - data type
* @param {Options} opts - function options
* @param {boolean} opts.codegen - boolean indicating whether to use code generation
* @returns {string} cache key
*
* @example
* var opts = {
* 'codegen': true
* };
* var key = getKey( 'float64', opts );
* // returns 'float64,codegen,true'
*/
function getKey( dtype, opts ) {
var key;
var i;
key = [ dtype ];
for ( i = 0; i < NOPTS; i++ ) {
// Note: we assume that an option value can be uniquely serialized to a `string` via `toString()`...
key.push( OPTIONS[ i ], opts[ OPTIONS[i] ].toString() );
}
return key.join( ',' );
}
// EXPORTS //
module.exports = getKey;
| JavaScript | 0.00715 | @@ -1342,16 +1342,24 @@
NS%5B i %5D,
+ String(
opts%5B O
@@ -1373,18 +1373,9 @@
i%5D %5D
-.toString(
+
) );
|
bb3085b3116ea6264eb7a8eb2a18a88ff73a79c9 | fix comments when loggedout | lib/site/topic-layout/topic-article/comments/list/component.js | lib/site/topic-layout/topic-article/comments/list/component.js | import React from 'react'
import Timeago from 'lib/site/timeago'
export default function CommentsList (props) {
const comments = props.comments || []
return (
<div className='comments-list'>
{
comments.map((item) => {
const handlers = {
onUnvote: () => props.onUnvote(item.id),
onUpvote: () => props.onUpvote(item.id),
onDownvote: () => props.onDownvote(item.id)
}
return <Comment key={item.id} comment={item} {...handlers} />
})
}
</div>
)
}
function Comment (props) {
const {comment} = props
const {upvoted, downvoted} = comment.currentUser
function handleUnvote (evt) {
evt.currentTarget.classList.remove('active')
props.onUnvote()
}
function handleUpvote (evt) {
evt.currentTarget.classList.add('active')
props.onUpvote()
}
function handleDownvote (evt) {
evt.currentTarget.classList.add('active')
props.onDownvote()
}
return (
<article className='comments-list-item' id={`comment-${comment.id}`}>
<header className='meta'>
<img
className='avatar'
src={comment.author.avatar}
alt={comment.author.fullName} />
<h3 className='name'>{comment.author.displayName}</h3>
<div className='created-at'>
<Timeago date={comment.createdAt} />
</div>
</header>
<div
className='text'
dangerouslySetInnerHTML={{__html: comment.textHtml}} />
<footer className='actions'>
<div className='votes'>
<span className='score'>{comment.score}</span>
<button
className={`upvote ${upvoted ? 'active' : ''}`}
onClick={upvoted ? handleUnvote : handleUpvote}>
<i className='icon-like' />
</button>
<button
className={`downvote ${downvoted ? 'active' : ''}`}
onClick={downvoted ? handleUnvote : handleDownvote}>
<i className='icon-dislike' />
</button>
</div>
</footer>
</article>
)
}
| JavaScript | 0 | @@ -632,16 +632,17 @@
oted%7D =
+(
comment.
@@ -652,16 +652,23 @@
rentUser
+ %7C%7C %7B%7D)
%0A%0A func
|
7ee832a0de9ff490f620394c4f04f1485deeb0cd | Update mag-template.js | src/addons/mag-template.js | src/addons/mag-template.js | /*
Name: Mag-template v0.1.1
Description: run mag.module by html url, returns instance in promise
Example:
var promise = mag.template(
'my-template.html',
component,
props)
.then((magInstance) => {
magInstance(newProps)
});
Author: Michael Glazer
License: MIT
Homepage: https://github.com/magnumjs/mag.js
@requires mag.js & mag addons
(c) 2017
*/
//TODO: what about within a module, mag.create or attach to a specific node?
;
(function(mag, document) {
'use strict';
var attached = [];
mag.template = function(url, component, props) {
return mag.request({
url: url,
cache: true
})
.then(function(data) {
//get html as node
var template = document.createElement('template');
template.innerHTML = data;
var newNode = template.content.children[0];
var id = newNode.id;
var instance = mag.module(newNode, component, props);
instance.subscribe(function() {
//only once
if (!attached[id]) {
document.body.appendChild(newNode);
attached[id] = 1;
}
})
return instance;
});
};
})(mag, document);
| JavaScript | 0.000001 | @@ -43,21 +43,21 @@
run mag.
-modul
+creat
e by htm
@@ -65,37 +65,8 @@
url
-, returns instance in promise
%0AExa
@@ -334,152 +334,243 @@
*/%0A%0A
-//TODO: what about within a module, mag.create or attach to a specific node?%0A%0A;%0A(function(mag, document
+;%0A(function(mag, document) %7B%0A%0A 'use strict';%0A var attached = %5B%5D;%0A%0A var getParentNode = function(parentInstance
) %7B%0A
-%0A 'use strict'
+ var parentId = mag.getId(parentInstance)
;%0A
+
var
-attached = %5B%5D;
+parentNode = mag.getNode(parentId);%0A return parentNode;%0A %7D;%0A
%0A m
@@ -984,24 +984,25 @@
props);%0A
+%0A
%0A
@@ -993,16 +993,66 @@
+var parentInstance = mag.mod.runningViewInstance;%0A
%0A
@@ -1080,20 +1080,32 @@
unction(
+parentInst
) %7B%0A
+
@@ -1161,24 +1161,149 @@
-document
+var parentNode = getParentNode(parentInst);%0A //Attach to parent instance if available%0A (document %7C%7C parentNode)
.body.ap
@@ -1369,24 +1369,51 @@
%7D%0A %7D
+.bind(null, parentInstance)
)%0A re
|
7558195d5dea217463388167eba412b908ebb220 | fix comparison operator on residue classes | src/arithmetic/residues.js | src/arithmetic/residues.js | const _inverse = (a, m) => {
let [t, t1] = [0, 1];
let [r, r1] = [m, a];
while (r1 != 0) {
const q = Math.floor(r / r1);
[t, t1] = [t1, t - q * t1];
[r, r1] = [r1, r - q * r1];
}
if (r == 1)
return t < 0 ? t + m : t;
};
const _make = (a, m) => a < 0 ? (a % m) + m : a % m;
const _plus = (a, b, m) => (a + b) % m;
const _minus = (a, b, m) => (m - b + a) % m;
const _times = (a, b, m) => (a * b) % m;
const _div = (a, b, m) => (_inverse(b, m) * a) % m;
const _cmp = (a, b) => (a > b) - (a > b);
export function extend(basis, m) {
const methods = {
toJS : { Integer: a => _make(a, m) },
abs : { Integer: a => _make(a, m) },
floor: { Integer: a => _make(a, m) },
ceil : { Integer: a => _make(a, m) },
round: { Integer: a => _make(a, m) },
negative: { Integer: a => _minus(0, _make(a, m)) },
sgn : { Integer: a => a % m != 0 },
isEven : { Integer: a => _make(a, m) % 2 == 0 },
cmp: {
Integer: {
Integer: (a, b) => _cmp(_make(a, m), _make(b, m), m)
}
},
plus: {
Integer: {
Integer: (a, b) => _plus(_make(a, m), _make(b, m), m)
}
},
minus: {
Integer: {
Integer: (a, b) => _minus(_make(a, m), _make(b, m), m)
}
},
times: {
Integer: {
Integer: (a, b) => _times(_make(a, m), _make(b, m), m)
}
},
div: {
Integer: {
Integer: (a, b) => _div(_make(a, m), _make(b, m), m)
}
}
};
return basis.register(methods);
};
| JavaScript | 0.000001 | @@ -516,17 +516,17 @@
b) - (a
-%3E
+%3C
b);%0A%0A%0Ae
|
cff38f770cbeb41ebab83305f8f68d3e52ccb741 | Update Light_accessory.js (#435) | accessories/Light_accessory.js | accessories/Light_accessory.js | var Accessory = require('../').Accessory;
var Service = require('../').Service;
var Characteristic = require('../').Characteristic;
var uuid = require('../').uuid;
var LightController = {
name: "Simple Light", //name of accessory
pincode: "031-45-154",
username: "FA:3C:ED:5A:1A:1A", // MAC like address used by HomeKit to differentiate accessories.
manufacturer: "HAP-NodeJS", //manufacturer (optional)
model: "v1.0", //model (optional)
serialNumber: "A12S345KGB", //serial number (optional)
power: false, //curent power status
brightness: 100, //current brightness
hue: 0, //current hue
saturation: 0, //current saturation
outputLogs: false, //output logs
setPower: function(status) { //set power of accessory
if(this.outputLogs) console.log("Turning the '%s' %s", this.name, status ? "on" : "off");
this.power = status;
},
getPower: function() { //get power of accessory
if(this.outputLogs) console.log("'%s' is %s.", this.name, this.power ? "on" : "off");
return this.power ? true : false;
},
setBrightness: function(brightness) { //set brightness
if(this.outputLogs) console.log("Setting '%s' brightness to %s", this.name, brightness);
this.brightness = brightness;
},
getBrightness: function() { //get brightness
if(this.outputLogs) console.log("'%s' brightness is %s", this.name, this.brightness);
return this.brightness;
},
setSaturation: function(saturation) { //set brightness
if(this.outputLogs) console.log("Setting '%s' saturation to %s", this.name, saturation);
this.saturation = saturation;
},
getSaturation: function() { //get brightness
if(this.outputLogs) console.log("'%s' saturation is %s", this.name, this.saturation);
return this.saturation;
},
setHue: function(hue) { //set brightness
if(this.outputLogs) console.log("Setting '%s' hue to %s", this.name, hue);
this.hue = hue;
},
getHue: function() { //get hue
if(this.outputLogs) console.log("'%s' hue is %s", this.name, this.hue);
return this.hue;
},
identify: function() { //identify the accessory
if(this.outputLogs) console.log("Identify the '%s'", this.name);
}
}
// Generate a consistent UUID for our light Accessory that will remain the same even when
// restarting our server. We use the `uuid.generate` helper function to create a deterministic
// UUID based on an arbitrary "namespace" and the word "light".
var lightUUID = uuid.generate('hap-nodejs:accessories:light' + LightController.name);
// This is the Accessory that we'll return to HAP-NodeJS that represents our light.
var lightAccessory = exports.accessory = new Accessory(LightController.name, lightUUID);
// Add properties for publishing (in case we're using Core.js and not BridgedCore.js)
lightAccessory.username = LightController.username;
lightAccessory.pincode = LightController.pincode;
// set some basic properties (these values are arbitrary and setting them is optional)
lightAccessory
.getService(Service.AccessoryInformation)
.setCharacteristic(Characteristic.Manufacturer, LightController.manufacturer)
.setCharacteristic(Characteristic.Model, LightController.model)
.setCharacteristic(Characteristic.SerialNumber, LightController.serialNumber);
// listen for the "identify" event for this Accessory
lightAccessory.on('identify', function(paired, callback) {
LightController.identify();
callback();
});
// Add the actual Lightbulb Service and listen for change events from iOS.
// We can see the complete list of Services and Characteristics in `lib/gen/HomeKitTypes.js`
lightAccessory
.addService(Service.Lightbulb, LightController.name) // services exposed to the user should have "names" like "Light" for this case
.getCharacteristic(Characteristic.On)
.on('set', function(value, callback) {
LightController.setPower(value);
// Our light is synchronous - this value has been successfully set
// Invoke the callback when you finished processing the request
// If it's going to take more than 1s to finish the request, try to invoke the callback
// after getting the request instead of after finishing it. This avoids blocking other
// requests from HomeKit.
callback();
})
// We want to intercept requests for our current power state so we can query the hardware itself instead of
// allowing HAP-NodeJS to return the cached Characteristic.value.
.on('get', function(callback) {
callback(null, LightController.getPower());
});
// To inform HomeKit about changes occurred outside of HomeKit (like user physically turn on the light)
// Please use Characteristic.updateValue
//
// lightAccessory
// .getService(Service.Lightbulb)
// .getCharacteristic(Characteristic.On)
// .updateValue(true);
// also add an "optional" Characteristic for Brightness
lightAccessory
.getService(Service.Lightbulb)
.addCharacteristic(Characteristic.Brightness)
.on('set', function(value, callback) {
LightController.setBrightness(value);
callback();
})
.on('get', function(callback) {
callback(null, LightController.getBrightness());
});
// also add an "optional" Characteristic for Saturation
lightAccessory
.getService(Service.Lightbulb)
.addCharacteristic(Characteristic.Saturation)
.on('set', function(value, callback) {
LightController.setSaturation(value);
callback();
})
.on('get', function(callback) {
callback(null, LightController.getSaturation());
});
// also add an "optional" Characteristic for Hue
lightAccessory
.getService(Service.Lightbulb)
.addCharacteristic(Characteristic.Hue)
.on('set', function(value, callback) {
LightController.setHue(value);
callback();
})
.on('get', function(callback) {
callback(null, LightController.getHue());
});
| JavaScript | 0 | @@ -1024,23 +1024,8 @@
ower
- ? true : false
;%0A
|
9e2671da57f0756d41f14705bb86b90053ee841c | Reset the partner-pf state | src/scripts/app/play/proofreadings/partner-play-ctrl.js | src/scripts/app/play/proofreadings/partner-play-ctrl.js | 'use strict';
module.exports =
/*@ngInject*/
function PartnerPlayCtrl($scope, localStorageService, _) {
//Add in some custom images for the 3 stories we are showcasing
$scope.pfImages = {
'70B-T6vLMTM9zjQ9LCwoCg': 'the_princes_and_the_turtle_story_header.png',
'MJCtkml_69W2Dav79v4r9Q': 'ernest_shackleton_story_header.png',
'Yh49ICvX_YME8ui7cDoFXQ': 'the_apollo_8_photograph_story_header.png'
};
$scope.onScoreReset = function() {
var keys = _.keys($scope.pfImages);
function remove(key) {
localStorageService.remove(key);
}
_.each(keys, function(key) {
_.each(['pf-' + key, 'sw-' + key, 'sw-temp-' + key], remove);
});
$scope.showResetScoreModal = false;
};
};
| JavaScript | 0 | @@ -95,16 +95,24 @@
rvice, _
+, $state
) %7B%0A //
@@ -717,16 +717,67 @@
false;%0A
+ $state.go($state.current, %7B%7D, %7Breload: true%7D);%0A
%7D;%0A%7D;%0A
|
00fb8d1fad83e87ebb29ab7a83ad9aa95d37278d | fix datatable sass config (webpack) | ng2-components/ng2-alfresco-datatable/config/webpack.common.js | ng2-components/ng2-alfresco-datatable/config/webpack.common.js | const webpack = require('webpack');
const helpers = require('./helpers');
const fs = require('fs');
const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');
var HappyPack = require('happypack');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const ENV = process.env.NODE_ENV = process.env.ENV = 'production';
const ENV = process.env.NODE_ENV = process.env.ENV = 'production';
module.exports = {
resolveLoader: {
alias: {
"file-multi-loader": path.resolve(__dirname, "./custom-loaders/file-loader-multi"),
"license-check": path.resolve(__dirname, "./custom-loaders/license-check")
}
},
resolve: {
alias: {
"ng2-alfresco-core": helpers.root('../ng2-alfresco-core/index.ts')
},
extensions: ['.ts', '.js'],
symlinks: false,
modules: [helpers.root('../../ng2-components'), helpers.root('node_modules')]
},
module: {
rules: [
{
enforce: 'pre',
test: /\.js$/,
loader: 'source-map-loader',
exclude: [/node_modules/, /bundles/, /dist/, /demo/]
},
{
enforce: 'pre',
test: /\.ts$/,
loader: 'tslint-loader',
options: {
emitErrors: true,
failOnHint: true,
fix: true
},
exclude: [/node_modules/, /bundles/, /dist/, /demo/]
},
{
test: /\.ts$/,
loader: ['happypack/loader?id=ts', 'angular2-template-loader'],
exclude: [/node_modules/, /bundles/, /dist/, /demo/]
},
{
test: /\.html$/,
loader: 'html-loader',
exclude: [/node_modules/, /bundles/, /dist/, /demo/]
},
{
test: /\.css$/,
loader: ['to-string-loader', 'css-loader'],
exclude: [/node_modules/, /bundles/, /dist/, /demo/]
},
{
test: /\.component.scss$/,
use: ['to-string-loader', 'raw-loader', 'sass-loader'],
exclude: [/node_modules/, /bundles/, /dist/, /demo/]
},
{
enforce: 'pre',
test: /\.ts$/,
loader: 'license-check',
options: {
emitErrors: true,
licenseFile: path.resolve(__dirname, './assets/license_header.txt')
},
exclude: [/node_modules/, /bundles/, /dist/, /demo/, /rendering-queue.services.ts/],
},
{
test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
loader: 'file-multi-loader',
query: {
name: '[name].[hash].[ext]',
outputPath: (url, resourcePath)=> {
return resourcePath.replace('src', 'bundles') + url;
},
publicPath: (url, resourcePath)=> {
var component = resourcePath.substring(0, resourcePath.indexOf('src'));
var path = resourcePath.replace(component, '').replace('src/', '');
return path + url;
}
}
}
]
},
plugins: [
new ForkTsCheckerWebpackPlugin(),
new HappyPack({
id: 'ts',
threads: 8,
loaders: [
{
path: 'ts-loader',
query: {
happyPackMode: true,
"compilerOptions": {
"paths": {}
}
}
}
]
}),
new CopyWebpackPlugin([{
from: `src/i18n/`,
to: `bundles/assets/${path.basename(helpers.root(''))}/i18n/`
}]),
new webpack.NoEmitOnErrorsPlugin(),
new webpack.BannerPlugin(fs.readFileSync(path.resolve(__dirname, './assets/license_header_add.txt'), 'utf8')),
new webpack.ContextReplacementPlugin(
/angular(\\|\/)core(\\|\/)@angular/,
helpers.root('./src'),
{}
),
new webpack.DefinePlugin({
'process.env': {
'ENV': JSON.stringify(ENV)
}
}),
new webpack.LoaderOptionsPlugin({
htmlLoader: {
minimize: false // workaround for ng2
}
})
],
node: {
fs: 'empty',
module: false
}
};
| JavaScript | 0 | @@ -2134,32 +2134,33 @@
%7D,%0A
+
%7B%0A
@@ -2174,18 +2174,8 @@
/%5C.
-component.
scss
@@ -2204,55 +2204,378 @@
e: %5B
-'to-string-loader', 'raw-loader', 'sass-loader'
+%0A %7B loader: %22to-string-loader%22 %7D,%0A %7B loader: %22raw-loader%22 %7D,%0A %7B%0A loader: %22sass-loader%22,%0A options: %7B%0A includePaths: %5B path.resolve(__dirname, '../../ng2-alfresco-core/styles')%5D%0A %7D%0A %7D%0A
%5D,%0A
|
70949c2a417fc7fcaca2856d9aa74235007d1c55 | add doubling time increment test | e2e/cypress/integration/tests/steppers.spec.js | e2e/cypress/integration/tests/steppers.spec.js | /// <reference types="cypress" />
context('Increment steppers', () => {
beforeEach(() => {
cy.visit('/')
});
it('Increment regional population', () => {
cy.contains('Hospitalized Admissions peaks at 301');
cy.get('input.st-al').eq(0)
.should('has.value', '3600000');
cy.get('.step-up').eq(0).click();
cy.get('input.st-al').eq(0)
.should('has.value', '3600001');
cy.contains('Hospitalized Admissions peaks at 301');
});
it('Increment hospital market share', () => {
cy.contains('Hospitalized Admissions peaks at 301');
cy.get('input.st-al').eq(1)
.should('has.value', '15');
cy.get('.step-up').eq(1).click();
cy.get('input.st-al').eq(1)
.should('has.value', '15.1');
cy.contains('Hospitalized Admissions peaks at 303');
});
});
| JavaScript | 0.00018 | @@ -806,13 +806,349 @@
);%0A %7D);
+%0A%0A it('Increment doubling time', () =%3E %7B%0A cy.contains('Hospitalized Admissions peaks at 301');%0A%0A cy.get('input.st-al').eq(3)%0A .should('has.value', '4');%0A%0A cy.get('.step-up').eq(3).click();%0A%0A cy.get('input.st-al').eq(3)%0A .should('has.value', '4.25');%0A%0A cy.contains('Hospitalized Admissions peaks at 273');%0A %7D);
%0A%7D);%0A
|
4bffe2749ca1fe08734ce0872ba778a15577b3bd | Remove error log | packages/strapi-plugin-users-permissions/services/Providers.js | packages/strapi-plugin-users-permissions/services/Providers.js | 'use strict';
/**
* Module dependencies.
*/
// Public node modules.
const _ = require('lodash');
const request = require('request');
// Purest strategies.
const Purest = require('purest');
/**
* Connect thanks to a third-party provider.
*
*
* @param {String} provider
* @param {String} access_token
*
* @return {*}
*/
exports.connect = (provider, query) => {
const access_token = query.access_token || query.code || query.oauth_token;
return new Promise((resolve, reject) => {
if (!access_token) {
return reject(null, {
message: 'No access_token.'
});
}
// Get the profile.
getProfile(provider, query, async (err, profile) => {
if (err) {
return reject(err);
}
// We need at least the mail.
if (!profile.email) {
return reject([{
message: 'Email was not available.'
}, null]);
}
try {
const users = await strapi.query('user', 'users-permissions').find(strapi.utils.models.convertParams('user', {
email: profile.email
}));
const advanced = await strapi.store({
environment: '',
type: 'plugin',
name: 'users-permissions',
key: 'advanced'
}).get();
if (_.isEmpty(_.find(users, {provider})) && !advanced.allow_register) {
return resolve([null, [{ messages: [{ id: 'Auth.advanced.allow_register' }] }], 'Register action is actualy not available.']);
}
const user = _.find(users, {provider});
if (!_.isEmpty(user)) {
return resolve([user, null]);
}
if (!_.isEmpty(_.find(users, user => user.provider !== provider)) && advanced.unique_email) {
return resolve([null, [{ messages: [{ id: 'Auth.form.error.email.taken' }] }], 'Email is already taken.']);
}
// Retrieve default role.
const defaultRole = await strapi.query('role', 'users-permissions').findOne({ type: advanced.default_role }, []);
// Create the new user.
const params = _.assign(profile, {
provider: provider,
role: defaultRole._id || defaultRole.id
});
const createdUser = await strapi.query('user', 'users-permissions').create(params);
return resolve([createdUser, null]);
} catch (err) {
strapi.log.error(err);
reject([null, err]);
}
});
});
};
/**
* Helper to get profiles
*
* @param {String} provider
* @param {Function} callback
*/
const getProfile = async (provider, query, callback) => {
const access_token = query.access_token || query.code || query.oauth_token;
const grant = await strapi.store({
environment: '',
type: 'plugin',
name: 'users-permissions',
key: 'grant'
}).get();
switch (provider) {
case 'discord': {
const discord = new Purest({
provider: 'discord',
config: {
'discord': {
'https://discordapp.com/api/': {
'__domain': {
'auth': {
'auth': {'bearer': '[0]'}
}
},
'{endpoint}': {
'__path': {
'alias': '__default'
}
}
}
}
}
});
discord.query().get('users/@me').auth(access_token).request((err, res, body) => {
if (err) {
callback(err);
} else {
// Combine username and discriminator because discord username is not unique
var username = `${body.username}#${body.discriminator}`;
callback(null, {
username: username,
email: body.email
});
}
});
break;
}
case 'facebook': {
const facebook = new Purest({
provider: 'facebook'
});
facebook.query().get('me?fields=name,email').auth(access_token).request((err, res, body) => {
if (err) {
callback(err);
} else {
callback(null, {
username: body.name,
email: body.email
});
}
});
break;
}
case 'google': {
const google = new Purest({
provider: 'google'
});
google.query('plus').get('people/me').auth(access_token).request((err, res, body) => {
if (err) {
callback(err);
} else {
callback(null, {
username: body.emails[0].value.split("@")[0],
email: body.emails[0].value
});
}
});
break;
}
case 'github': {
const github = new Purest({
provider: 'github',
defaults: {
headers: {
'user-agent': 'strapi'
}
}
});
request.post({
url: 'https://github.com/login/oauth/access_token',
form: {
client_id: grant.github.key,
client_secret: grant.github.secret,
code: access_token
}
}, (err, res, body) => {
github.query().get('user').auth(body.split('&')[0].split('=')[1]).request((err, res, body) => {
if (err) {
callback(err);
} else {
callback(null, {
username: body.login,
email: body.email
});
}
});
});
break;
}
case 'microsoft': {
const microsoft = new Purest({
provider: 'microsoft',
config:{
'microsoft': {
'https://graph.microsoft.com': {
'__domain': {
'auth': {
'auth': {'bearer': '[0]'}
}
},
'[version]/{endpoint}': {
'__path': {
'alias': '__default',
'version': 'v1.0'
}
}
}
}
}
});
microsoft.query().get('me').auth(access_token).request((err, res, body) => {
if (err) {
callback(err);
} else {
callback(null, {
username: body.userPrincipalName,
email: body.userPrincipalName
});
}
});
break;
}
case 'twitter': {
const twitter = new Purest({
provider: 'twitter',
key: grant.twitter.key,
secret: grant.twitter.secret
});
twitter.query().get('account/verify_credentials').auth(access_token, query.access_secret).qs({screen_name: query['raw[screen_name]'], include_email: 'true'}).request((err, res, body) => {
if (err) {
callback(err);
} else {
callback(null, {
username: body.screen_name,
email: body.email
});
}
});
break;
}
default:
callback({
message: 'Unknown provider.'
});
break;
}
};
| JavaScript | 0 | @@ -2339,39 +2339,8 @@
) %7B%0A
- strapi.log.error(err);%0A
|
95785a9585d673a16403fec7c22ebc0da51cca79 | remove unnecessary View | react/features/notifications/components/Notification.native.js | react/features/notifications/components/Notification.native.js | // @flow
import React from 'react';
import { Text, TouchableOpacity, View } from 'react-native';
import { Icon } from '../../base/font-icons';
import { translate } from '../../base/i18n';
import { NOTIFICATION_TYPE } from '../constants';
import AbstractNotification, {
type Props
} from './AbstractNotification';
import styles from './styles';
/**
* Implements a React {@link Component} to display a notification.
*
* @extends Component
*/
class Notification extends AbstractNotification<Props> {
/**
* Implements React's {@link Component#render()}.
*
* @inheritdoc
* @returns {ReactElement}
*/
render() {
const {
appearance,
isDismissAllowed,
t,
title,
titleArguments,
titleKey
} = this.props;
let notificationStyle;
switch (appearance) {
case NOTIFICATION_TYPE.ERROR:
notificationStyle = styles.notificationTypeError;
break;
case NOTIFICATION_TYPE.NORMAL:
notificationStyle = styles.notificationTypeNormal;
break;
case NOTIFICATION_TYPE.SUCCESS:
notificationStyle = styles.notificationTypeSuccess;
break;
case NOTIFICATION_TYPE.WARNING:
notificationStyle = styles.notificationTypeWarning;
break;
case NOTIFICATION_TYPE.INFO:
default:
notificationStyle = styles.notificationTypeInfo;
}
return (
<View
pointerEvents = 'box-none'
style = { [
styles.notification,
notificationStyle
] }>
<View style = { styles.contentColumn }>
<View
pointerEvents = 'box-none'
style = { styles.notificationTitle }>
<Text style = { styles.titleText }>
{
title || t(titleKey, titleArguments)
}
</Text>
</View>
<View
pointerEvents = 'box-none'
style = { styles.notificationContent }>
{
this._getDescription().map((line, index) => (
<Text
key = { index }
style = { styles.contentText }>
{ line }
</Text>
))
}
</View>
</View>
{
isDismissAllowed
&& <View style = { styles.actionColumn }>
<TouchableOpacity onPress = { this._onDismissed }>
<Icon
name = { 'close' }
style = { styles.dismissIcon } />
</TouchableOpacity>
</View>
}
</View>
);
}
_getDescription: () => Array<string>;
_onDismissed: () => void;
}
export default translate(Notification);
| JavaScript | 0 | @@ -2821,71 +2821,8 @@
&&
- %3CView style = %7B styles.actionColumn %7D%3E%0A
%3CTo
@@ -2893,20 +2893,16 @@
-
%3CIcon%0A
@@ -2927,20 +2927,16 @@
-
-
name = %7B
@@ -2946,20 +2946,16 @@
lose' %7D%0A
-
@@ -3028,20 +3028,16 @@
-
%3C/Toucha
@@ -3052,36 +3052,8 @@
ty%3E%0A
- %3C/View%3E%0A
|
32fdc38f8fcb00444f1d7c22958e9c98d99e070f | comment out breaking empty fns | react/src/base/inputs/SprkInputContainer/SprkInputContainer.js | react/src/base/inputs/SprkInputContainer/SprkInputContainer.js | import React, { Component } from 'react';
import classNames from 'classnames';
import PropTypes from 'prop-types';
import SprkLabel from '../SprkLabel/SprkLabel';
import SprkInput from '../SprkInput/SprkInput';
import SprkErrorContainer from '../SprkErrorContainer/SprkErrorContainer';
class SprkInputContainer extends Component {
constructor(props) {
super(props);
this.renderChildren = this.renderChildren.bind(this);
}
renderChildren() {
const { children } = this.props;
let id;
let labelFor;
let errorContainerID;
/*
* Store references to id, for
* and errorContainerID.
*/
React.Children.forEach(children, (child) => {
if (child.type.name === SprkInput.name) {
id = child.props.id;
}
if (child.type.name === SprkLabel.name) {
labelFor = child.props.htmlFor;
}
if (child.type.name === SprkErrorContainer.name) {
errorContainerID = child.props.id;
}
});
if (id && labelFor && id.length > 0 && labelFor.length > 0) {
const childrenElements = React.Children.map(children, (child) => {
/*
* If the label for and the input id
* are mismatching, use the id
* value to set the `for` attribute on the label.
* SprkInput and SprkLabel will always have
* an ID and a for. We check for presence (id="")
* before checking for length to avoid running
* .length on undefined.
*/
if (id !== labelFor) {
if (child.type.name === SprkLabel.name) {
return React.cloneElement(child, {
htmlFor: id,
});
}
}
/*
* If there is an error container
* with an id then match the aria-describedby
* on the input to the id on the
* error container.
*/
if (
errorContainerID &&
child.type.name === SprkInput.name &&
child.props.ariaDescribedBy !== errorContainerID
) {
return React.cloneElement(child, {
ariaDescribedBy: errorContainerID,
});
}
return child;
});
return childrenElements;
}
// Return other elements ex. <div>
return children;
}
render() {
const {
additionalClasses,
analyticsString,
children,
idString,
variant,
...rest
} = this.props;
return (
<div
data-analytics={analyticsString}
data-id={idString}
className={classNames('sprk-b-InputContainer', additionalClasses, {
'sprk-b-InputContainer--huge': variant === 'huge',
})}
{...rest}
>
{this.renderChildren()}
</div>
);
}
}
SprkInputContainer.propTypes = {
/**
* Determines the style of the input container.
* Supplying no value will cause
* the default styles to be used.
*/
variant: PropTypes.oneOf(['huge']),
/**
* A space-separated string of
* classes to add to the outermost
* container of the component.
*/
additionalClasses: PropTypes.string,
/**
* Assigned to the `data-analytics`
* attribute serving as a unique selector
* for outside libraries to capture data.
*/
analyticsString: PropTypes.string,
/**
* Content to render inside of
* the component.
*/
children: PropTypes.node,
/**
* Assigned to the `data-id` attribute
* serving as a unique selector for
* automated tools.
*/
idString: PropTypes.string,
};
export default SprkInputContainer;
| JavaScript | 0.000001 | @@ -2425,16 +2425,235 @@
props;%0A%0A
+ React.Children.forEach(children, () =%3E %7B%0A let sprkLabel;%0A if (children.type.name !== SprkLabel.name) %7B%0A sprkLabel = children;%0A console.log(sprkLabel, 'the label component')%0A %7D%0A %7D);%0A%0A%0A
retu
|
3a7018254bf0545c54f6ff7d73eb21aadcfb8ec9 | Update info about non-compliant .toggle(*, undefined) | src/jquery.class_list.js | src/jquery.class_list.js | /**
* jQuery classList extension
* Author & copyright: Michał Gołębiowski <m.goleb@gmail.com>
*
* Source: https://github.com/mzgol/jquery.classList
* Released under the MIT license (see the LICENSE.txt file)
*/
(function ($) {
'use strict';
var rnotwhite = /\S+/g,
svgNode = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
if (!svgNode.classList) {
// Don't break non-classList-compatible browsers. Some browsers support classList
// on regular elements but not on SVGs so this check is safer.
return;
}
svgNode.classList.add('a', 'b');
svgNode.classList.toggle('c', false);
if (!svgNode.classList.contains('a') || !svgNode.classList.contains('b') ||
svgNode.classList.contains('c')) {
// No support for multiple arguments to classList.add and/or the toggle flag;
// don't use this plugin.
return;
}
$.fn.extend({
addClass: function (value) {
var classes, elem,
i = 0,
len = this.length,
proceed = typeof value === 'string' && value;
if ($.isFunction(value)) {
return this.each(function (j) {
$(this).addClass(value.call(this, j, this.className));
});
}
if (proceed) {
// The disjunction here is for better compressibility (see removeClass)
classes = (value || '').match(rnotwhite) || [];
for (; i < len; i++) {
elem = this[i];
if (elem.nodeType === 1) {
elem.classList.add.apply(elem.classList, classes);
}
}
}
return this;
},
removeClass: function (value) {
var classes, elem,
i = 0,
len = this.length,
proceed = arguments.length === 0 || typeof value === 'string' && value;
if ($.isFunction(value)) {
return this.each(function (j) {
$(this).removeClass(value.call(this, j, this.className));
});
}
if (proceed) {
classes = (value || '').match(rnotwhite) || [];
for (; i < len; i++) {
elem = this[i];
if (elem.nodeType === 1 && elem.className) {
if (!value) {
elem.className = '';
}
elem.classList.remove.apply(elem.classList, classes);
}
}
}
return this;
},
toggleClass: function (value, stateVal) {
var type = typeof value,
isBool = typeof stateVal === 'boolean';
if ($.isFunction(value)) {
return this.each(function (i) {
$(this).toggleClass(value.call(this, i, this.className, stateVal), stateVal);
});
}
return this.each(function () {
if (this.nodeType === 1) {
if (type === 'string') {
// Toggle individual class names
var clazz,
i = 0,
classes = value.match(rnotwhite) || [];
// Check each class given, space separated list
while ((clazz = classes[i++])) {
// The branching is needed as `stateVal === undefined` is treated
// in three different ways by the spec, Chrome & Firefox.
// See https://github.com/whatwg/dom/issues/64
if (isBool) {
this.classList.toggle(clazz, stateVal);
} else {
this.classList.toggle(clazz);
}
}
} else if (type === 'undefined' || type === 'boolean') {
// Toggle whole class name
if (this.className) {
// store className if set
$._data(this, '__className__', this.className);
}
// If the element has a class name or if we're passed 'false',
// then remove the whole className (if there was one, the above saved it).
// Otherwise bring back whatever was previously saved (if anything),
// falling back to the empty string if nothing was stored.
this.className = this.className ||
value === false ? '' : $._data(this, '__className__') || '';
}
}
});
},
hasClass: function (value) {
var i = 0,
l = this.length;
for (; i < l; i++) {
if (this[i].nodeType === 1) {
if (this[i].classList.contains(value)) {
return true;
}
}
}
return false;
},
});
})(jQuery);
| JavaScript | 0 | @@ -3577,155 +3577,219 @@
//
-The branching is needed as %60stateVal === undefined%60 is treated%0A // in three different ways by the spec, Chrome & Firefox
+Support: Chrome 44+, Safari 8+, Edge 10240+%0A // The branching is needed as most browsers cast an %60undefined%60%0A // %60stateVal%60 to %60false%60 instead of ignoring it
.%0A
@@ -3820,12 +3820,8 @@
//
- See
htt
@@ -3857,16 +3857,277 @@
sues/64%0A
+ // https://code.google.com/p/chromium/issues/detail?id=489665%0A // https://bugs.webkit.org/show_bug.cgi?id=148582%0A // https://connect.microsoft.com/IE/feedbackdetail/view/1725606/%0A
|
656ecb1ebd68c5298e70f81010ab8cedfb542858 | support redux dev tools if installed | src/js/configureStore.js | src/js/configureStore.js | import { createStore, applyMiddleware } from 'redux';
import thunkMiddleware from 'redux-thunk';
import rootReducer from './reducers';
import { createLogger } from 'redux-logger';
const middlewares = [thunkMiddleware];
if (process.env.NODE_ENV === 'development') {
middlewares.push(createLogger());
}
export default function configureStore (initialState) {
return createStore(
rootReducer,
initialState,
applyMiddleware(...middlewares)
);
}
| JavaScript | 0 | @@ -30,16 +30,25 @@
ddleware
+, compose
%7D from
@@ -56,16 +56,16 @@
redux';%0A
-
import t
@@ -226,12 +226,274 @@
e%5D;%0A
-if (
+%0Aconst hasReduxDevToolsInstalled = !!(%0A typeof window === 'object' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__%0A);%0A%0Aconst composeEnhancers = hasReduxDevToolsInstalled%0A ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__%0A : compose;%0A%0Aif (!hasReduxDevToolsInstalled &&
proc
@@ -686,16 +686,33 @@
te,%0A
+composeEnhancers(
applyMid
@@ -734,16 +734,17 @@
lewares)
+)
%0A );%0A%7D%0A
|
9def98c5e2519a82acef8b0c7e4bf10d6c2b555d | call update on child components | src/js/core/scrollspy.js | src/js/core/scrollspy.js | import { $, isInView } from '../util/index';
export default function (UIkit) {
UIkit.component('scrollspy', {
args: 'cls',
props: {
cls: 'list',
target: String,
hidden: Boolean,
offsetTop: Number,
offsetLeft: Number,
repeat: Boolean,
delay: Number
},
defaults: {
cls: ['uk-scrollspy-inview'],
target: false,
hidden: true,
offsetTop: 0,
offsetLeft: 0,
repeat: false,
delay: 0,
inViewClass: 'uk-scrollspy-inview'
},
init() {
this.$emitSync();
},
computed: {
elements() {
return this.target && $(this.target, this.$el) || this.$el;
}
},
update: [
{
write() {
if (this.hidden) {
this.elements.filter(`:not(.${this.inViewClass})`).css('visibility', 'hidden');
}
}
},
{
read() {
this.elements.each((_, el) => {
if (!el._scrollspy) {
var cls = $(el).attr('uk-scrollspy-class');
el._scrollspy = {toggles: cls && cls.split(',') || this.cls};
}
el._scrollspy.show = isInView(el, this.offsetTop, this.offsetLeft);
});
},
write() {
var index = this.elements.length === 1 ? 1 : 0;
this.elements.each((i, el) => {
var $el = $(el), data = el._scrollspy, cls = data.toggles[i] || data.toggles[0];
if (data.show) {
if (!data.inview && !data.timer) {
var show = () => {
$el.css('visibility', '')
.addClass(this.inViewClass)
.toggleClass(cls)
.trigger('inview');
data.inview = true;
delete data.timer;
};
if (this.delay && index) {
data.timer = setTimeout(show, this.delay * index);
} else {
show();
}
index++;
}
} else {
if (data.inview && this.repeat) {
if (data.timer) {
clearTimeout(data.timer);
delete data.timer;
}
$el.removeClass(this.inViewClass)
.toggleClass(cls)
.css('visibility', this.hidden ? 'hidden' : '')
.trigger('outview');
data.inview = false;
}
}
});
},
events: ['scroll', 'load', 'resize']
}
]
});
}
| JavaScript | 0 | @@ -2223,32 +2223,85 @@
ger('inview');%0A%0A
+ this.$update();%0A%0A
@@ -3323,32 +3323,81 @@
er('outview');%0A%0A
+ this.$update();%0A%0A
|
2f3a4b40525a6a0e3a0d8b6ccdbf077e5a417c74 | Update inform7.js to new class names | src/languages/inform7.js | src/languages/inform7.js | /*
Language: Inform 7
Author: Bruno Dias <bruno.r.dias@gmail.com>
Description: Language definition for Inform 7, a DSL for writing parser interactive fiction.
*/
function(hljs) {
var START_BRACKET = '\\[';
var END_BRACKET = '\\]';
return {
aliases: ['i7'],
case_insensitive: true,
keywords: {
// Some keywords more or less unique to I7, for relevance.
keyword:
// kind:
'thing room person man woman animal container ' +
'supporter backdrop door ' +
// characteristic:
'scenery open closed locked inside gender ' +
// verb:
'is are say understand ' +
// misc keyword:
'kind of rule'
},
contains: [
{
className: 'string',
begin: '"', end: '"',
relevance: 0,
contains: [
{
className: 'subst',
begin: START_BRACKET, end: END_BRACKET
}
]
},
{
className: 'title',
begin: /^(Volume|Book|Part|Chapter|Section|Table)\b/,
end: '$'
},
{
// Rule definition
// This is here for relevance.
begin: /^(Check|Carry out|Report|Instead of|To|Rule|When|Before|After)\b/,
end: ':',
contains: [
{
//Rule name
begin: '\\b\\(This',
end: '\\)'
}
]
},
{
className: 'comment',
begin: START_BRACKET, end: END_BRACKET,
contains: ['self']
}
]
};
}
| JavaScript | 0 | @@ -968,13 +968,15 @@
e: '
-title
+section
',%0A
@@ -1319,30 +1319,15 @@
'%5C%5C
-b%5C%5C
(This',
-%0A
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.