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
|
---|---|---|---|---|---|---|---|
44961c2780748726db65c43b176255be3a0de333 | use less resources to update timestamps | lib/timeAgo.js | lib/timeAgo.js | const Value = require('mutant/value')
const computed = require('mutant/computed')
const nest = require('depnest')
const human = require('human-time')
exports.gives = nest('lib.obs.timeAgo')
exports.create = function (api) {
return nest('lib.obs.timeAgo', timeAgo)
function timeAgo (timestamp) {
var timer
var value = Value(Time(timestamp))
return computed([value], (a) => a, {
onListen: () => {
timer = setInterval(refresh, 5e3)
refresh()
},
onUnlisten: () => {
clearInterval(timer)
}
})
function refresh () {
value.set(Time(timestamp))
}
}
}
function Time (timestamp) {
return human(new Date(timestamp))
.replace(/minute/, 'min')
.replace(/second/, 'sec')
}
| JavaScript | 0 | @@ -454,9 +454,10 @@
sh,
-5
+30
e3)%0A
@@ -546,16 +546,42 @@
%7D%0A
+ %7D, %7B%0A idle: true%0A
%7D)%0A%0A
|
631e133f449220b943bffbcdbf9f247e2c35c4c3 | support for using websocket to connect plugin ui server | lib/upgrade.js | lib/upgrade.js | var handleWebsocket = require('./https').handleWebsocket;
var hparser = require('hparser');
var Buffer = require('safe-buffer').Buffer;
var pluginMgr = require('./plugins');
var util = require('./util');
var config = require('./config');
var formatHeaders = hparser.formatHeaders;
var getRawHeaderNames = hparser.getRawHeaderNames;
var getRawHeaders = hparser.getRawHeaders;
var WS_RE = /\bwebsocket\b/i;
var PLUGIN_PATH_RE = /^\/(whistle|plugin)\.([^/?#]+)(\/)?/;
function getPluginNameByReq(req, callback) {
if (!req) {
return callback();
}
var host = req.headers.host;
var index = host.indexOf(':');
var port = req.isHttps ? 443 : 80;
if (index !== -1) {
port = host.substring(index + 1);
host = host.substring(0, index);
}
var isWebUI = (port == config.port || port == config.uiport) && util.isLocalAddress(host);
isWebUI = isWebUI || config.isWebUIHost(host);
var pluginName;
var isPluginUrl;
if (!isWebUI) {
pluginName = config.getPluginNameByHost(host);
} else if (PLUGIN_PATH_RE.test(req.url)) {
isPluginUrl = RegExp.$1 === 'plugin';
pluginName = RegExp.$2;
}
if (!pluginName) {
return callback();
}
req.url = req.url.replace(PLUGIN_PATH_RE, '$3');
if (req.url[0] !== '/') {
req.url = '/' + req.url;
}
var plugin = isPluginUrl ? pluginMgr.getPluginByName(name) : pluginMgr.getPlugin(name + ':');
pluginMgr.loadPlugin(plugin, function(err, ports) {
var uiPort = ports && ports.uiPort;
if (err || !uiPort) {
var msg = ['HTTP/1.1', err ? 500 : 404, err ? 'Internal Server Error' : 'Not Found'].join(' ');
err = err ? '<pre>' + err + '</pre>' : 'Not Found';
var length = Buffer.byteLength(err);
err = [
msg,
'Content-Type: text/html; charset=utf8',
'Content-Length: ' + length,
'\r\n',
err
].join('\r\n');
}
callback(err, uiPort);
});
}
function upgradeHandler(req, socket) {
var destroyed, resSocket;
function destroy(err) {
if (destroyed) {
return;
}
destroyed = true;
socket.destroy(err);
resSocket && resSocket.destroy(err);
}
socket.on('error', destroy);
var headers = req.headers;
var getBuffer = function(method, newHeaders, path) {
var rawData = [(method || 'GET') + ' ' + (path || req.url) + ' ' + 'HTTP/1.1'];
newHeaders = formatHeaders(newHeaders || headers, req.rawHeaders);
rawData.push(getRawHeaders(newHeaders));
return Buffer.from(rawData.join('\r\n') + '\r\n\r\n');
};
socket.headers = headers;
req.isHttps = socket.isHttps = !!headers[config.HTTPS_FIELD];
// format headers
socket.fullUrl = util.getFullUrl(socket).replace('http', 'ws');
var isWs = WS_RE.test(headers.upgrade);
getPluginNameByReq(isWs ? req : null, function(err, uiPort) {
if (err) {
return socket.write(err);
}
// 其它协议直接转成普通https请求,方便抓包调试
// 如果是插件的websocket请求,直接转插件
if (!isWs || uiPort) {
if (!isWs) {
delete headers.upgrade;
delete headers['http2-settings'];
headers.connection = 'keep-alive';
}
req.pause();
util.connect({
port: uiPort || config.port,
localhost: '127.0.0.1'
}, function(err, s) {
if (err) {
return destroy(err);
}
resSocket = s;
resSocket.on('error', destroy);
resSocket.write(getBuffer(req.method));
req.pipe(resSocket).pipe(socket).resume();
});
return;
}
// 不能放到上面,否则转发后的协议将丢失
delete headers[config.HTTPS_FIELD];
socket.rawHeaderNames = getRawHeaderNames(req.rawHeaders);
socket.url = req.url;
var clientInfo = util.parseClientInfo(req);
var clientIp = clientInfo[0] || util.getClientIp(req);
var clientPort = clientInfo[1] || util.getClientPort(req);
delete socket.headers[config.CLIENT_PORT_HEAD];
socket.getBuffer = function(newHeaders, path) {
return getBuffer(null, newHeaders, path);
};
handleWebsocket(socket, clientIp, clientPort);
});
}
module.exports = function(server) {
server.on('upgrade', upgradeHandler);
};
| JavaScript | 0 | @@ -1330,17 +1330,23 @@
nByName(
-n
+pluginN
ame) : p
@@ -1364,17 +1364,23 @@
tPlugin(
-n
+pluginN
ame + ':
|
ad2fe720cdc0d5e140489c5f986506e44ec1ef64 | add salmon links to rss feed | server/api/social_butterfly/feed.js | server/api/social_butterfly/feed.js | import constants from '../../../shared/constants';
import { buildUrl, contentUrl, profileUrl } from '../../../shared/util/url_factory';
import crypto from 'crypto';
import endpointWithApollo from '../../util/endpoint_with_apollo';
import gql from 'graphql-tag';
import { graphql } from 'react-apollo';
import { NotFoundError } from '../../util/exceptions';
import React, { createElement as RcE, PureComponent } from 'react';
export default async (req, res, next) => {
res.type('xml');
res.write(`<?xml version="1.0" encoding="UTF-8"?>`);
return await endpointWithApollo(req, res, next, <Feed req={req} />);
};
@graphql(
gql`
query FeedAndUserQuery($username: String!) {
fetchFeed(username: $username) {
album
createdAt
updatedAt
name
section
title
username
view
content
}
fetchPublicUserData(username: $username) {
description
email
favicon
license
logo
name
title
username
}
}
`,
{
options: ({
req: {
query: { username },
},
}) => ({
variables: {
username,
},
}),
}
)
class Feed extends PureComponent {
render() {
const contentOwner = this.props.data.fetchPublicUserData;
if (!contentOwner) {
throw new NotFoundError();
}
const { req } = this.props;
const username = req.query.username;
const feed = this.props.data.fetchFeed;
const feedUrl = buildUrl({ req, pathname: req.originalUrl });
const profile = profileUrl(username, req);
const md5 = crypto.createHash('md5');
const supId = md5
.update(feedUrl)
.digest('hex')
.slice(0, 10);
const namespaces = {
xmlLang: 'en-US',
xmlns: 'http://www.w3.org/2005/Atom',
'xmlns:activity': 'http://activitystrea.ms/spec/1.0/',
'xmlns:poco': 'http://portablecontacts.net/spec/1.0',
'xmlns:media': 'http://purl.org/syndication/atommedia',
'xmlns:thr': 'http://purl.org/syndication/thread/1.0',
};
return (
<feed {...namespaces}>
<generator uri="https://github.com/mimecuvalo/helloworld">Hello, world.</generator>
<id>{feedUrl}</id>
<title>{contentOwner.title}</title>
<subtitle>a hello world site.</subtitle>
<link rel="self" href={feedUrl} />
<link rel="alternate" type="text/html" href={profile} />
<link rel="hub" href={constants.pushHub} />
<link
rel="http://api.friendfeed.com/2008/03#sup"
href={`http://friendfeed.com/api/public-sup.json#${supId}`}
type="application/json"
/>
<link rel="license" href={contentOwner.license} />
{contentOwner.license ? (
<rights>
{contentOwner.license === 'http://purl.org/atompub/license#unspecified'
? `Copyright ${new Date().getFullYear()} by ${contentOwner.name}`
: `${constants.licenses[contentOwner.license]['name']}: ${contentOwner.license}`}
</rights>
) : null}
{feed.length ? <updated>{new Date(feed[0].updatedAt).toISOString()}</updated> : null}
<Author contentOwner={contentOwner} profile={profile} />
{contentOwner.logo ? <logo>{buildUrl({ req, pathname: contentOwner.logo })}</logo> : null}
<icon>
{contentOwner.favicon
? buildUrl({ req, pathname: contentOwner.favicon })
: buildUrl({ req, pathname: '/favicon.ico' })}
</icon>
{feed.map(content => (
<Entry key={content.name} content={content} req={req} />
))}
</feed>
);
}
}
const Author = ({ contentOwner, profile }) => (
<author>
{RcE('activity:object-type', {}, `http://activitystrea.ms/schema/1.0/person`)}
<name>{contentOwner.name}</name>
<uri>{profile}</uri>
<email>{contentOwner.email}</email>
{RcE('poco:preferredusername', {}, contentOwner.username)}
{RcE('poco:displayname', {}, contentOwner.name)}
{RcE('poco:emails', {}, [
RcE('poco:value', { key: 'value' }, contentOwner.email),
RcE('poco:type', { key: 'type' }, 'home'),
RcE('poco:primary', { key: 'primary' }, 'true'),
])}
{RcE('poco:urls', {}, [
RcE('poco:value', { key: 'value' }, profile),
RcE('poco:type', { key: 'type' }, 'profile'),
RcE('poco:primary', { key: 'primary' }, 'true'),
])}
</author>
);
class Entry extends PureComponent {
render() {
const { content, req } = this.props;
const statsImgSrc = buildUrl({ req, pathname: '/api/stats', searchParams: { url: contentUrl(content) } });
const statsImg = `<img src="${statsImgSrc}" />`;
const absoluteUrlReplacement = buildUrl({ req, pathname: '/resource' });
const viewWithAbsoluteUrls =
'<![CDATA[' + content.view.replace(/(['"])\/resource/gm, `$1${absoluteUrlReplacement}`) + ']]>';
const html = viewWithAbsoluteUrls + statsImg;
return (
<entry>
<title>{content.title}</title>
<link href={contentUrl(content, req)} />
<id>
{`tag:${req.hostname}` +
`,${new Date(content.createdAt).toISOString().slice(0, 10)}` +
`:${contentUrl(content)}`}
</id>
<content type="html" dangerouslySetInnerHTML={{ __html: html }} />
<published>{new Date(content.createdAt).toISOString()}</published>
<updated>{new Date(content.updatedAt).toISOString()}</updated>
{RcE('activity:verb', {}, `http://activitystrea.ms/schema/1.0/post`)}
</entry>
);
}
}
| JavaScript | 0 | @@ -1506,59 +1506,215 @@
nst
-feedUrl = buildUrl(%7B req, pathname: req.originalUrl
+acct = %60acct:$%7Busername%7D@$%7Breq.get('host')%7D%60;%0A const feedUrl = buildUrl(%7B req, pathname: req.originalUrl %7D);%0A const salmonUrl = buildUrl(%7B req, pathname: '/api/social/salmon', searchParams: %7B q: acct %7D
%7D);
@@ -2830,24 +2830,241 @@
%0A /%3E%0A
+ %3Clink rel=%22salmon%22 href=%7BsalmonUrl%7D /%3E%0A %3Clink rel=%22http://salmon-protocol.org/ns/salmon-replies%22 href=%7BsalmonUrl%7D /%3E%0A %3Clink rel=%22http://salmon-protocol.org/ns/salmon-mention%22 href=%7BsalmonUrl%7D /%3E%0A
%3Clin
|
e7a0e86518c74ce07f4c453dc928c52752abfe85 | Make the login form more robust to failed logins | clients/web/src/views/layout/LoginView.js | clients/web/src/views/layout/LoginView.js | import $ from 'jquery';
import _ from 'underscore';
import View from 'girder/views/View';
import events from 'girder/events';
import { handleClose, handleOpen } from 'girder/dialog';
import { login } from 'girder/auth';
import UserModel from 'girder/models/UserModel';
import LoginDialogTemplate from 'girder/templates/layout/loginDialog.pug';
import 'girder/utilities/jquery/girderEnable';
import 'girder/utilities/jquery/girderModal';
/**
* This view shows a login modal dialog.
*/
var LoginView = View.extend({
events: {
'submit #g-login-form': function (e) {
e.preventDefault();
login(this.$('#g-login').val(), this.$('#g-password').val());
events.once('g:login.success', function () {
this.$el.modal('hide');
}, this);
events.once('g:login.error', function (status, err) {
this.$('.g-validation-failed-message').text(err.responseJSON.message);
this.$('#g-login-button').girderEnable(true);
if (err.responseJSON.extra === 'emailVerification') {
var html = err.responseJSON.message +
' <a class="g-send-verification-email">Click here to send verification email.</a>';
$('.g-validation-failed-message').html(html);
}
}, this);
this.$('#g-login-button').girderEnable(false);
this.$('.g-validation-failed-message').text('');
},
'click .g-send-verification-email': function () {
this.$('.g-validation-failed-message').html('');
const loginName = this.$('#g-login').val();
UserModel.sendVerificationEmail(loginName)
.done((resp) => {
this.$('.g-validation-failed-message').html(resp.message);
}).fail((err) => {
this.$('.g-validation-failed-message').html(err.responseJSON.message);
});
},
'click a.g-register-link': function () {
events.trigger('g:registerUi');
},
'click a.g-forgot-password': function () {
events.trigger('g:resetPasswordUi');
}
},
initialize: function (settings) {
this.registrationPolicy = settings.registrationPolicy;
this.enablePasswordLogin = _.has(settings, 'enablePasswordLogin') ? settings.enablePasswordLogin : true;
},
render: function () {
this.$el.html(LoginDialogTemplate({
registrationPolicy: this.registrationPolicy,
enablePasswordLogin: this.enablePasswordLogin
})).girderModal(this)
.on('shown.bs.modal', () => {
this.$('#g-login').focus();
}).on('hidden.bs.modal', () => {
handleClose('login', {replace: true});
});
handleOpen('login', {replace: true});
this.$('#g-login').focus();
return this;
}
});
export default LoginView;
| JavaScript | 0 | @@ -623,39 +623,201 @@
-login(this.$('#g-login').val(),
+this.$('#g-login-button').girderEnable(false);%0A this.$('.g-validation-failed-message').text('');%0A%0A const loginName = this.$('#g-login').val();%0A const password =
thi
@@ -840,19 +840,17 @@
').val()
-);%0A
+;
%0A
@@ -858,53 +858,69 @@
-events.once('g:login.success', function () %7B%0A
+login(loginName, password)%0A .done(() =%3E %7B%0A
@@ -963,34 +963,30 @@
-%7D, this);%0A
+ %7D)
%0A
@@ -990,62 +990,33 @@
-events.once('g:login.error', function (status, err) %7B%0A
+ .fail((err) =%3E %7B%0A
@@ -1102,70 +1102,13 @@
e);%0A
+%0A
- this.$('#g-login-button').girderEnable(true);%0A
@@ -1193,16 +1193,20 @@
+
+
var html
@@ -1235,16 +1235,20 @@
ssage +%0A
+
@@ -1367,16 +1367,20 @@
+
$('.g-va
@@ -1429,24 +1429,28 @@
+
%7D%0A
@@ -1455,19 +1455,55 @@
+
-%7D, this);%0A%0A
+ %7D)%0A .always(() =%3E %7B%0A
@@ -1541,36 +1541,35 @@
').girderEnable(
-fals
+tru
e);%0A
@@ -1572,54 +1572,13 @@
-this.$('.g-validation-failed-message').text(''
+ %7D
);%0A
|
593caa2518c20ccf9e51b3e6ae07b089d779ee42 | Update ga-controller.js | server/controllers/ga-controller.js | server/controllers/ga-controller.js | var { google } = require("googleapis");
var ga = google.analytics("v3");
var moment = require("moment");
module.exports = function (app) {
var gaQuery = function (req, res, options) {
var jwt = new google.auth.JWT(
options.serviceEmail,
options.pemFilename,
null,
["https://www.googleapis.com/auth/analytics.readonly"],
null);
if (app.get("env") !== "development") {
res.header("Access-Control-Allow-Origin", options.origin);
}
jwt.authorize(function (err, tokens) { // eslint-disable-line no-unused-vars
if (err) {
console.log("jwt error", err);
return;
}
ga.data.ga.get({
auth: jwt,
ids: options.accountId,
"start-date": "2014-01-01",
"end-date": moment().format("YYYY-MM-DD"),
"metrics": "ga:pageviews",
"filters": "ga:pagePath==/" + options.pathRoot + "/" + (req.query.path || "")
}, function (err, result) {
if (err) {
console.log("api error", err, result);
}
res.send(result && result.rows && result.rows[0] ? result.rows[0][0] : "(unknown)");
});
});
};
app.get("/ga", function (req, res) {
gaQuery(req, res, {
serviceEmail: process.env.SERVICE_EMAIL,
pemFilename: "grnsight.pem",
origin: "https://dondi.github.io",
accountId: "ga:91279024",
pathRoot: "GRNsight",
});
});
app.get("/grnmap", function (req, res) {
gaQuery(req, res, {
serviceEmail: process.env.GRNMAP_SERVICE_EMAIL,
pemFilename: "grnmap.pem",
origin: "http://kdahlquist.github.io",
accountId: "ga:97014398",
pathRoot: "GRNmap",
});
});
};
| JavaScript | 0.000001 | @@ -1,18 +1,14 @@
var
- %7B
google
- %7D
= r
@@ -1603,17 +1603,16 @@
RNsight%22
-,
%0A
@@ -1916,17 +1916,16 @@
%22GRNmap%22
-,
%0A
|
bef06668457e342028d0ba8555a85b11001367bc | add routes | bob/routes.js | bob/routes.js | /*
Here comes the API.
*/
app.get('/api/getBasemaps', function (req, res) {
// Hier müsste man die Basemaps holen
res.send('Hello World!');
});
app.get('/api/getEinsatz/:EinsatzID/', function(req, res){
// Beispiel wie das mit den Parametern läuft ;-)
var einsatzid = req.params.EinsatzID;
});
| JavaScript | 0.000006 | @@ -17,19 +17,17 @@
the API.
-%09%0A%09
+%0A
%0A*/%0A%0A%0Aap
@@ -112,17 +112,16 @@
ps holen
-%09
%0A%0A res.
@@ -208,18 +208,17 @@
, res)%7B%0A
-%09
%0A
+
%09// Beis
@@ -259,18 +259,17 @@
uft ;-)%0A
-%09
%0A
+
%09var ein
@@ -304,11 +304,1010 @@
D;%0A%0A
-%09%0A%09
+%0A%0A%7D);%0A%0A/* liefert liste mit den ids und titeln der taktischen zeichen*/%0Aapp.get('/zeichen/', function(req, res)%7B%0A%09//'Schema' durch entsprechendes mongoose schema f%C3%BCr taktische zeichen ersetzen%0A%09Schema.find(function(err, result)%7B%0A%09%09if (err) return console.err(err);%0A%09%09res.send(result);%0A%09%7D)%0A%7D);%0A%0A/* liefert das zeichen mit der ID :id */%0Aapp.get('/zeichen/:id/', function(req, res)%7B%0A%09var zeichenID = req.params.id;%0A%0A%09//'Schema' durch entsprechendes mongoose schema f%C3%BCr taktsiche zeichen ersetzen%0A%09Schema.findOne(%7B_id: zeichenID%7D, function(err, callback)%7B%0A%09%09%09if (err) return console.log(err);%0A%09%09%09res.send(callback);%0A%09%7D);%0A%7D);%0A%0A/* nimmt ein ge%C3%A4ndertes Zeichen entgegen */%0Aapp.post('/zeichen/:id/', function(req, res)%7B%0A var zeichenID = req.params.id;%0A%0A //'Schema' durch entsprechendes mongoose schema f%C3%BCr taktsiche zeichen ersetzen%0A Schema.findByIdAndUpdate(zeichenID, %7B$set: %7B/* hier die json elemente einf%C3%BCgen */%7D%7D, function(err, schema)%7B%0A if (err) return handelError(err);%0A res.send(schema);%0A %7D);
%0A%7D);
|
dd82c529b15e32994496ec13d27b94fd88ed8e95 | remove unused cookie | app/js/controllers/parameterButtonCtrl.js | app/js/controllers/parameterButtonCtrl.js | /**
* Created by stefas on 19/05/15.
*/
angular.module('myApp.controllers')
.controller('ParameterButtonCtrl', ['$sce', '$scope', '$http',
'defaults', '$controller', 'Session',
function ($sce, $scope, $http, defaults, $controller, Session) {
$controller('CommonCtrl', {
$scope: $scope,
$http: $http,
defaults: defaults,
Session: Session
});
// Store parameters in the cookies
$scope.saveVideoPreferences = function () {
var now = new Date(),
exp = new Date(now.getFullYear(), now.getMonth() + 1, now.getDate());
Cookies.set("use.default.video.path", $scope.model.useDefaultVideoPath, {
expires: exp
});
Cookies.set("video.path", $scope.model.videoPath, {
expires: exp
});
};
}
]); | JavaScript | 0.000002 | @@ -590,242 +590,8 @@
e(),
-%0A exp = new Date(now.getFullYear(), now.getMonth() + 1, now.getDate());%0A%0A Cookies.set(%22use.default.video.path%22, $scope.model.useDefaultVideoPath, %7B%0A expires: exp%0A %7D);
%0A%0A
|
4d2895cc0c529e374ae8bc25eb3ff0873c5a04a2 | Clean code (api) | api/data.js | api/data.js | const fs = require('fs');
const got = require('got');
const unzipper = require('unzipper');
const chalk = require('chalk');
const debug = require('./utils/debug.js');
const db = require('./db.js');
// Update GTFS data.
async function update(cb) {
debug.info(`Starting data update`);
debug.time('update');
debug.time('data', 'Downloading data');
// Download GTFS ZIP file.
const res = await got.stream('http://peatus.ee/gtfs/gtfs.zip');
debug.timeEnd('data', 'Downloaded data');
debug.time('extract', 'Extracting data');
// Extract GTFS ZIP file into tmp folder.
await res.pipe(unzipper.Extract({ path: 'tmp' })).promise();
debug.timeEnd('extract', 'Extracted data');
// Import data from files.
fs.readdir('sql/importers', (err, files) => {
next(0);
function next(i) {
if (i > files.length - 1) {
debug.timeEnd('update', 'Data update completed');
return void (cb ? cb() : null);
}
const file = files[i];
const name = file.slice(0, -4);
debug.time(name, `Importing ${name}`);
fs.readFile(`sql/importers/${file}`, (err, data) => {
db.query(data.toString(), (err) => {
debug.timeEnd(name, `Imported ${name}`);
next(i + 1);
});
});
}
});
};
module.exports.update = update;
| JavaScript | 0.000001 | @@ -257,17 +257,17 @@
ug.info(
-%60
+'
Starting
@@ -278,17 +278,17 @@
a update
-%60
+'
);%0A%09debu
@@ -563,18 +563,24 @@
e into t
+e
mp
+orary
folder.
@@ -836,21 +836,16 @@
- 1) %7B%0A
-%09%09%09%09%0A
%09%09%09%09debu
@@ -890,21 +890,16 @@
eted');%0A
-%09%09%09%09%0A
%09%09%09%09retu
@@ -926,21 +926,16 @@
null);%0A
-%09%09%09%09%0A
%09%09%09%7D%0A%09%09%09
@@ -1149,22 +1149,16 @@
r) =%3E %7B%0A
-%09%09%09%09%09%0A
%09%09%09%09%09deb
@@ -1195,16 +1195,16 @@
ame%7D%60);%0A
+
%09%09%09%09%09nex
@@ -1217,14 +1217,8 @@
1);%0A
-%09%09%09%09%09%0A
%09%09%09%09
|
174c4ee167d398acefa4d21631a696b62ff7e4ee | fix email finding script | app/scripts/controllers/subscriberInfo.js | app/scripts/controllers/subscriberInfo.js | /**************
Copyright 2016 Open Effect
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.
***************/
AMIApp.controller('SubscriberCtrl', ['$scope', '$location', '$window', 'NavCollection', 'AMIRequest', 'identifiers', 'urls', 'dataProviderService', '$translate', function ($scope, $location, $window, NavCollection, AMIRequest, identifiers, urls, dataProviderService, $translate) {
$window.scrollTo(0,0);
$scope.nextIsLoading = false;
$scope.$watch(function(){
$scope.previousStage = NavCollection.previousItem();
$scope.nextStage = NavCollection.nextItem();
});
$scope.previous = function(){
$location.url($scope.previousStage.id);
}
$scope.next = function(){
$location.url($scope.nextStage.id);
}
if(!AMIRequest.has('services')){
$scope.previous();
return;
}
$scope.operator = AMIRequest.get('operator');
$scope.services = AMIRequest.get('services');
if(identifiers){
if(AMIRequest.has('subject')){
$scope.subject = AMIRequest.get('subject');
}
else{
$scope.subject = {};
$scope.subject.basic_personal_info = {};
$scope.subject.service_identifiers = {};
console.log("subject overwrite", $scope.subject);
AMIRequest.set('subject', $scope.subject);
}
console.log($scope.subject);
if(identifiers['basic_personal_info']){
$scope.basic_identifiers = identifiers['basic_personal_info'];
}
$scope.service_identifiers = identifiers;
delete $scope.service_identifiers['basic_personal_info'];
for(i in $scope.service_identifiers){
if(typeof $scope.subject.service_identifiers[i] == "undefined"){
$scope.subject.service_identifiers[i] = {};
}
}
}
$scope.$on("$destroy", function(){
$scope.submit();
});
var emailFieldREGEX;
$translate('status.emailField').then(function (emailField) {
emailFieldREGEX = new RegExp("/" + emailField + "/i");
});
var findEmail = function(subject){
var email = null;
var keys;
for(var property in subject.basic_personal_info){
console.log(subject.basic_personal_info[property]);
if(subject.basic_personal_info[property]['title'].match(emailFieldREGEX)){
email = subject.basic_personal_info[property]['value'];
}
if(email){
break;
}
}
return email;
}
$scope.hasEmailField = (typeof findEmail($scope.service_identifiers) !== "undefined");
$scope.email = {};
$scope.rateLimited = false;
if(AMIRequest.has('statistics')){
$scope.statistics = AMIRequest.get('statistics');
}
else{
$scope.statistics = true;
}
if(AMIRequest.has('subscribe')){
$scope.subscribe = AMIRequest.get('subscribe');
}
else{
$scope.subscribe = false;
}
$scope.anon = AMIRequest.getAnon();
$scope.servicelist = '';
for(var i=0; i < $scope.anon.services.length; i++){
var dividerChar = "";
if(i == $scope.anon.services.length - 1){
dividerChar = ""
}
else{
dividerChar = ", ";
}
$scope.servicelist = $scope.servicelist + $scope.anon.services[i].title + dividerChar;
}
if(AMIRequest.has('operator')){
$scope.company = AMIRequest.get('operator');
}
$scope.$watch('subject', function(newVal, oldVal){
console.log("subject", newVal);
AMIRequest.set('subject', newVal);
});
$scope.$watch(function(){
AMIRequest.set('statistics', $scope.statistics);
if($scope.statistics === false){
$scope.subscribe = false;
}
AMIRequest.set('subscribe', $scope.subscribe);
$scope.nextStage = NavCollection.nextItem();
if(AMIRequest.has('subject')){
if(findEmail(AMIRequest.get('subject'))){
$scope.hasEmail = true;
$scope.email.address = findEmail(AMIRequest.get('subject'));
}
}
else{
$scope.hasEmail = false;
}
});
$scope.submit = function(){
if(!AMIRequest.get('statistics')){
return;
}
var payload = {
data: $scope.anon,
subscribe: AMIRequest.get('subscribe'),
language: $translate.use(),
email: false
}
if(AMIRequest.get('subscribe')){
payload.email = $scope.email;
}
AMIRequest.serverResponse = {};
AMIRequest.serverIsLoading = true;
dataProviderService.postItem(urls.enrollmentURL(), "/enroll/", {}, payload)
.then(function(response){
AMIRequest.serverResponse.serverIsLoading = false;
AMIRequest.serverResponse.serverError = false;
AMIRequest.serverResponse.serverDown = false;
AMIRequest.serverResponse.response = response.title;
AMIRequest.serverResponse.responseStatuses = {};
AMIRequest.serverResponse.responseStatuses[response.title.statusCode] = true;
AMIRequest.serverResponse.success = true;
}, function(response){
AMIRequest.serverResponse.serverIsLoading = false;
AMIRequest.serverResponse.serverError = true;
if(response.status === -1){
AMIRequest.serverResponse.serverDown = true;
}
else{
AMIRequest.serverResponse.serverDown = false;
}
if(response.status === 429){
AMIRequest.serverResponse.rateLimited = true;
}
});
}
$scope.submitAndNext = function(){
$scope.next();
}
}]); | JavaScript | 0.000992 | @@ -2266,16 +2266,19 @@
REGEX;%0A
+ //
$transl
@@ -2283,21 +2283,22 @@
slate('s
-tatus
+ubject
.emailFi
@@ -2369,35 +2369,23 @@
Exp(
-%22/%22 + emailField + %22
+/email
/i
-%22
);%0A
+ //
%7D);
@@ -2627,16 +2627,30 @@
title'%5D.
+toLowerCase().
match(em
@@ -2726,24 +2726,51 @@
%5D%5B'value'%5D;%0A
+ console.log(email)%0A
%7D%0A
@@ -2829,20 +2829,21 @@
email;%0A
-
%7D%0A
+%0A
$scope
|
96b9f6c3debecafcc2926243c1fa3d62ebff2d46 | Save staled authentication replay flag for later verification | src/RequestSender.js | src/RequestSender.js |
/**
* @fileoverview Request Sender
*/
/**
* @augments JsSIP
* @class Class creating a request sender.
* @param {Object} applicant
* @param {JsSIP.UA} ua
*/
JsSIP.RequestSender = function(applicant, ua) {
this.ua = ua;
this.applicant = applicant;
this.method = applicant.request.method;
this.request = applicant.request;
this.credentials = null;
this.challenged = false;
this.staled = false;
// If ua is in closing process or even closed just allow sending Bye and ACK
if (ua.status === JsSIP.c.UA_STATUS_USER_CLOSED && (this.method !== JsSIP.c.BYE || this.method !== JsSIP.c.ACK)) {
this.onTransportError();
}
this.credentials = ua.getCredentials(this.request);
};
/**
* Create the client transaction and send the message.
*/
JsSIP.RequestSender.prototype = {
send: function() {
if (this.credentials) {
if (this.request.method === JsSIP.c.REGISTER) {
this.request.setHeader('authorization', this.credentials.authenticate());
} else if (this.request.method !== JsSIP.c.CANCEL) {
this.request.setHeader('proxy-authorization', this.credentials.authenticate());
}
}
switch(this.method) {
case "INVITE":
this.clientTransaction = new JsSIP.Transactions.InviteClientTransaction(this, this.request, this.ua.transport);
break;
case "ACK":
this.clientTransaction = new JsSIP.Transactions.AckClientTransaction(this, this.request, this.ua.transport);
break;
default:
this.clientTransaction = new JsSIP.Transactions.NonInviteClientTransaction(this, this.request, this.ua.transport);
}
this.clientTransaction.send();
},
/**
* Callback fired when receiving a request timeout error from the client transaction.
* To be re-defined by the applicant.
* @event
*/
onRequestTimeout: function() {
this.applicant.onRequestTimeout();
},
/**
* Callback fired when receiving a transport error from the client transaction.
* To be re-defined by the applicant.
* @event
*/
onTransportError: function() {
this.applicant.onTransportError();
},
/**
* Called from client transaction when receiving a correct response to the request.
* Authenticate request if needed or pass the response back to the applicant.
* @param {JsSIP.IncomingResponse} response
*/
receiveResponse: function(response) {
var cseq, challenge,
status_code = response.status_code;
/*
* Authentication
* Authenticate once. _challenged_ flag used to avoid infinite authentications.
*/
if ((status_code === 401 || status_code === 407) && this.ua.configuration.password !== null) {
if (status_code === 401) {
challenge = response.s('WWW-Authenticate');
} else {
challenge = response.s('Proxy-Authenticate');
}
if ( !this.challenged || (this.challenged && !this.staled && challenge.stale) ) {
if (!this.credentials) {
this.credentials = new JsSIP.DigestAuthentication(this.ua, this.request, response);
} else {
this.credentials.update(response);
}
if (response.method === JsSIP.c.REGISTER) {
cseq = this.applicant.cseq += 1;
} else if (this.request.dialog){
cseq = this.request.dialog.local_seqnum += 1;
} else {
cseq = this.request.headers.CSeq.toString().split(' ')[0];
cseq = parseInt(cseq,10) +1;
}
this.request.setHeader('cseq', cseq +' '+ this.method);
this.challenged = true;
this.send();
}
} else {
if (this.challenged && response.status_code >= 200) {
this.ua.saveCredentials(this.credentials);
}
this.applicant.receiveResponse(response);
}
}
}; | JavaScript | 0 | @@ -2893,16 +2893,27 @@
ge.stale
+ === 'true'
) ) %7B%0A
@@ -3102,32 +3102,116 @@
se);%0A %7D%0A%0A
+ if (challenge.stale === 'true') %7B%0A this.staled = true;%0A %7D%0A%0A%0A
if (resp
|
6c185106ac782e1f39dadfa9c69fe478cb47e728 | Update app.js | desio/asilo_nido/app.js | desio/asilo_nido/app.js | // Code goes here
var myApp = angular.module('myApp', ['angularUtils.directives.dirPagination']);
function MyController($scope, $http,NgMap) {
NgMap.getMap().then(function(map) {
$scope.map = map;
});
$scope.currentPage = 1;
$scope.pageSize = 20;
$scope.items = [];
$http.get("entities.json")
.then(function(response) {
$scope.items = response.data;
});
$scope.pageChangeHandler = function(num) {
};
}
function OtherController($scope) {
$scope.pageChangeHandler = function(num) {
};
}
myApp.controller('MyController', MyController);
myApp.controller('OtherController', OtherController);
| JavaScript | 0.000002 | @@ -143,72 +143,8 @@
%7B%0A%0A
-NgMap.getMap().then(function(map) %7B%0A $scope.map = map;%0A %7D);%0A
%0A $
|
0a95d06c2a4c2c2f5bffd9e31d0d279cbe5b900b | add autocomplete script by default | form.js | form.js |
var j_forms = require('j-forms')
,fields = j_forms.fields
,widgets = j_forms.widgets
,mongoose = require('mongoose')
,_ = require('underscore')
,jest = require('jest');
var api_loaded = false;
var api_path;
var AdminForm = exports.AdminForm = j_forms.forms.MongooseForm.extend({
init: function(request,options,model)
{
this._super(request,options,model);
this.static['js'].push('/node-forms/js/jquery-ui-1.8.22.custom.min.js');
this.static['css'].push('/node-forms/css/ui-lightness/jquery-ui-1.8.22.custom.css');
this.static['css'].push('/node-forms/css/forms.css');
},
scanFields : function(form_fields){
var self = this;
_.each(form_fields,function(value,key) {
if(value instanceof fields.RefField) {
if( (value.options.url || api_loaded) && value.options.query) {
value.options.widget_options.url = value.options.url || api_path;
value.options.widget_options.data = value.options.widget_options.data || {};
value.options.widget_options.data.data = encodeURIComponent(JSON.stringify({
model: value.options.ref,
query: value.options.query || '/__value__/i.test(this.name || this.title || this._id.toString())'
}));
value.widget = new widgets.AutocompleteWidget(value.options.widget_options);
}
}
else if(value instanceof fields.EnumField)
value.widget = new widgets.ComboBoxWidget(value.options.widget_options);
else if (value instanceof fields.ListField)
self.scanFields(value.fields);
});
},
get_fields: function() {
this._super();
this.scanFields(this.fields);
}
});
exports.loadApi = function(app,path) {
var api = new jest.Api(path || 'admin_api',app);
var Resource = jest.Resource.extend({
init:function(){
this._super();
this.fields = {
value:null,
label:null
};
this.allowed_methods = ['get'];
this.filtering = {
data:null,
query:null
};
},
mapObjects: function(objects) {
return objects.map(function(object) {
return { value: object.id, label:object.toString() };
});
},
get_objects:function(req,filters,sorts,limit,offset,callback) {
var self = this;
var data = JSON.parse(filters.data);
var model = mongoose.model(data.model);
var query = data.query.replace(/__value__/g,escapeRegex(filters.query));
model.find({$where:query},function(err,results) {
if(results) {
if(results.objects)
results.objects = self.mapObjects(results.objects);
else
results = self.mapObjects(results);
}
callback(err,results);
});
}
});
api.register('ref',new Resource());
api_path = '/' + api.path + 'ref';
api_loaded = true;
};
function escapeRegex (a){
return a.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");
} | JavaScript | 0 | @@ -465,24 +465,90 @@
m.min.js');%0A
+ this.static%5B'js'%5D.push('/node-forms/js/autocomplete.js');%0A
this
|
5d03539ad1fb34c246b3d7f729256c4370f1ad6d | Replace all tabs with spaces. | javascript/mailblock.js | javascript/mailblock.js | (function($) {
$(document).ready(function(){
showHideButton();
$('.cms-tabset-nav-primary li').on('click', showHideButton);
function showHideButton() {
if ($('#Root_Mailblock_set').is(':visible')) {
$('#Form_EditForm_action_mailblockTestEmail').show();
}
else {
$('#Form_EditForm_action_mailblockTestEmail').hide();
}
}
})
})(jQuery); | JavaScript | 0.000001 | @@ -8,17 +8,20 @@
on($) %7B%0A
-%09
+
$(docume
@@ -42,19 +42,24 @@
tion()%7B%0A
-%0A%09%09
+
showHide
@@ -68,18 +68,24 @@
tton();%0A
-%09%09
+
$('.cms-
@@ -141,13 +141,25 @@
n);%0A
-%09%09%0A%09%09
+ %0A
func
@@ -182,19 +182,28 @@
ton() %7B%0A
-%09%09%09
+
if ($('#
@@ -241,20 +241,32 @@
le')) %7B%0A
-%09%09%09%09
+
$('#Form
@@ -315,27 +315,57 @@
();%0A
-%09%09%09%7D%0A%09%09%09else %7B%0A%09%09%09%09
+ %7D%0A else %7B%0A
$('#
@@ -418,18 +418,36 @@
();%0A
-%09%09%09%7D%0A%09%09%7D%0A%09
+ %7D%0A %7D%0A
%7D)%0A%7D
|
fed9ff29a9a2390146666ec19119836fa91cd96a | Add 3 movies in example, looks better | examples/starters/list/js/controllers.js | examples/starters/list/js/controllers.js | angular.module('listExample.controllers', [])
// Controller that fetches a list of data
.controller('MovieIndexCtrl', function($scope, MovieService) {
// "MovieService" is a service returning mock data (services.js)
// the returned data from the service is placed into this
// controller's scope so the template can render the data
$scope.movies = MovieService.all();
$scope.title = "Completely Random Collection Of Movies";
})
// Controller that shows more detailed info about a movie
.controller('MovieDetailCtrl', function($scope, $routeParams, MovieService) {
// "MovieService" is a service returning mock data (services.js)
$scope.movie = MovieService.get($routeParams.movieId);
$scope.title = "Movie Info";
});
| JavaScript | 0.000001 | @@ -138,24 +138,33 @@
MovieService
+,$timeout
) %7B%0A %0A //
@@ -443,16 +443,1320 @@
Movies%22;
+%0A%0A // Method called on infinite scroll%0A // Receives a %22done%22 callback to inform the infinite scroll that we are done%0A $scope.loadMore = function(done) %7B%0A $timeout(function() %7B%0A $scope.movies.push(%7B%0A id: 'tt0114814',%0A title: 'Usual Suspects',%0A released: '1995',%0A description: 'A boat has been destroyed, criminals are dead, and the key to this mystery lies with the only survivor and his twisted, convoluted story beginning with five career crooks in a seemingly random police lineup.',%0A director: 'Bryan Singer',%0A rating: 8.3%0A %7D);%0A $scope.movies.push(%7B%0A id: 'tt0357413',%0A title: 'Anchorman: The Legend of Ron Burgundy',%0A released: '2004',%0A description: %22Ron Burgundy is San Diego's top rated newsman in the male-dominated broadcasting of the 70's, but that's all about to change for Ron and his cronies when an ambitious woman is hired as a new anchor.%22,%0A director: 'Adam McKay',%0A rating: 7.2%0A %7D);%0A $scope.movies.push(%7B%0A id: 'tt0058331',%0A title: 'Mary Poppins',%0A released: '1964',%0A description: %22A magic nanny comes to work for a cold banker's unhappy family.%22,%0A director: 'Robert Stevenson',%0A rating: 7.7%0A %7D);%0A done();%0A %7D, 1000);%0A %7D
%0A%7D)%0A%0A//
|
cde8bf8579a086bd952b3927c02241eef8c43375 | Use state | src/TestComponent.js | src/TestComponent.js | import React, { Component } from 'react';
class Greeter extends Component {
render() {
return (
<h1>Hello, {this.props.name}!</h1>
);
}
}
export class TestComponent extends Component {
render() {
return (
<div>
<Greeter name="Ben222" />
</div>
);
}
}
| JavaScript | 0.000003 | @@ -33,17 +33,16 @@
'react'
-;
%0A%0Aclass
@@ -145,63 +145,306 @@
)
-;%0A %7D%0A%7D%0A%0Aexport class TestComponent extends Component %7B
+%0A %7D%0A%7D%0A%0Aclass ChatList extends Component %7B%0A render() %7B%0A var chats = this.props.data.map(%0A chat =%3E %3Cli%3E%7Bchat%7D%3C/li%3E%0A )%0A return (%0A %3Cul%3E%7Bchats%7D%3C/ul%3E%0A )%0A %7D%0A%7D%0A%0Aexport class TestComponent extends Component %7B%0A constructor(props) %7B%0A super(props)%0A this.state = %7B data: %5B%5D %7D%0A %7D
%0A r
@@ -474,24 +474,68 @@
%3Cdiv%3E%0A
+ %3CChatList data=%7Bthis.state.data%7D /%3E%0A
%3CGre
@@ -552,11 +552,8 @@
%22Ben
-222
%22 /%3E
@@ -575,9 +575,8 @@
)
-;
%0A %7D
|
af892e2365daa6b213c89b3bacdfaf4da777d1d6 | Update the enemy bounds in the enemy class | src/js/Enemy.js | src/js/Enemy.js | 'use strict';
/**
* @description Enemy class => objects the player should avoid
* @constructor
* @param {number} x position of the enemy on the 'x' axis
* @param {number} y position of the enemy on the 'y' axis
* @param {number} speed speed factor of the enemy
*/
var Enemy = function (x, y, speed) {
this.x = x;
this.y = y; // TODO: update y = (y * rowHeight) + (0.5 * rowHeight) + 73
this.speed = speed; // TODO: update speed = * speedRatio
this.sprite = 'images/goomba.png'; //TODO: remove hard coded sprite
};
/**
* @description Move the enemy accross the gameBord
* @param {number} dt Time delta between the previous and actual frame
* @param {object} bounds Gameboard bounds
*/
Enemy.prototype.update = function (dt, bounds) {
// Restrict the enemy back and forth mouvement to the bound of the screen
this.speed = this.x < bounds.right && this.x > bounds.left ? this.speed : -this.speed;
// Move the enemy accross the screen back and forth
this.x += this.speed * dt;
};
/**
* @descritpion Render the enemy object
*/
Enemy.prototype.render = function (context) {
context.drawImage(Resources.get(this.sprite), this.x, this.y);
};
| JavaScript | 0.000001 | @@ -922,16 +922,21 @@
s.right
+- 10
&& this
@@ -952,16 +952,21 @@
ds.left
++ 10
? this.s
|
ac7f76e29a2bd531da6598aef6e3a84b55fb1b85 | Fix fusebox config | fuse.js | fuse.js | // const {
// FuseBox,
// SVGPlugin,
// CSSPlugin,
// BabelPlugin,
// QuantumPlugin,
// WebIndexPlugin,
// EnvPlugin,
// Sparky,
// } = require('fuse-box')
// let fuse, app, vendor, isProduction
// Sparky.task('config', () => {
// fuse = new FuseBox({
// homeDir: 'app/',
// sourceMaps: !isProduction,
// hash: isProduction,
// output: 'dist/$name.js',
// useTypescriptCompiler: true,
// experimentalFeatures: true,
// plugins: [
// SVGPlugin(),
// CSSPlugin(),
// EnvPlugin({ isProduction }),
// WebIndexPlugin({
// path: '.',
// template: 'app/index.html'
// }),
// isProduction && QuantumPlugin({
// treeshake: true,
// uglify: true
// })
// ]
// })
// // vendor
// vendor = fuse.bundle('vendor').instructions('~ index.ts')
// // bundle app
// app = fuse.bundle('app').instructions('> [index.ts]')
// })
// Sparky.task('default', ['clean', 'config'], () => {
// fuse.dev({ port: 3000 })
// // add dev instructions
// app.watch().hmr()
// return fuse.run()
// })
// Sparky.task('clean', () => Sparky.src('dist/').clean('dist/'))
// Sparky.task('prod-env', ['clean'], () => { isProduction = true })
// Sparky.task('dist', ['prod-env', 'config'], () => {
// // comment out to prevent dev server from running (left for the demo)
// fuse.dev({ port: 3000 })
// return fuse.run()
// })
const {
FuseBox,
SassPlugin,
CSSPlugin,
SVGPlugin,
JSONPlugin,
WebIndexPlugin,
Sparky,
UglifyJSPlugin,
QuantumPlugin,
EnvPlugin
} = require('fuse-box')
const express = require('express')
const path = require('path')
const {spawn} = require('child_process')
let fuse, app, vendor
let isProduction = false
const setupServer = server => {
const app = server.httpServer.app
app.use('/assets/', express.static(path.join(__dirname, 'assets')))
}
Sparky.task('config', () => {
fuse = FuseBox.init({
homeDir: 'app/',
output: 'dist/$name.js',
hash: isProduction,
tsConfig : 'tsconfig.json',
experimentalFeatures: true,
useTypescriptCompiler: true,
sourceMaps: !isProduction ? { project: true, vendor: true } : false,
cache: !isProduction,
plugins: [
SVGPlugin(),
CSSPlugin(),
JSONPlugin(),
EnvPlugin({ isProduction }),
WebIndexPlugin({
path: '.',
template: 'app/index.html',
}),
isProduction && QuantumPlugin({
treeshake: true,
uglify: true,
}),
],
})
// vendor
let vendor = fuse.bundle('vendor').instructions('~ index.ts')
// bundle app
let app = fuse.bundle('app').instructions('> [index.ts]')
})
// main task
Sparky.task('default', ['clean', 'clean-cache', 'config'], () => {
fuse.dev({ port: 3000 }, setupServer)
app.watch().hmr()
return fuse.run()
})
// wipe it all
Sparky.task('clean', () => Sparky.src('dist/*').clean('dist/'))
// wipe it all from .fusebox - cache dir
Sparky.task('clean-cache', () => Sparky.src('.fusebox/*').clean('.fusebox/'))
// prod build
Sparky.task('set-production-env', () => isProduction = true)
Sparky.task('dist', ['clean', 'clean-cache', 'set-production-env', 'config'], () => {
fuse.dev({ port: 3000 }, setupServer)
return fuse.run()
})
| JavaScript | 0.000001 | @@ -1,1442 +1,4 @@
-// const %7B%0A// FuseBox,%0A// SVGPlugin,%0A// CSSPlugin,%0A// BabelPlugin,%0A// QuantumPlugin,%0A// WebIndexPlugin,%0A// EnvPlugin,%0A// Sparky,%0A// %7D = require('fuse-box')%0A%0A// let fuse, app, vendor, isProduction%0A%0A// Sparky.task('config', () =%3E %7B%0A// fuse = new FuseBox(%7B%0A// homeDir: 'app/',%0A// sourceMaps: !isProduction,%0A// hash: isProduction,%0A// output: 'dist/$name.js',%0A// useTypescriptCompiler: true,%0A// experimentalFeatures: true,%0A// plugins: %5B%0A// SVGPlugin(),%0A// CSSPlugin(),%0A// EnvPlugin(%7B isProduction %7D),%0A// WebIndexPlugin(%7B%0A// path: '.',%0A// template: 'app/index.html'%0A// %7D),%0A// isProduction && QuantumPlugin(%7B%0A// treeshake: true,%0A// uglify: true%0A// %7D)%0A// %5D%0A// %7D)%0A// // vendor%0A// vendor = fuse.bundle('vendor').instructions('~ index.ts')%0A%0A// // bundle app%0A// app = fuse.bundle('app').instructions('%3E %5Bindex.ts%5D')%0A// %7D)%0A%0A// Sparky.task('default', %5B'clean', 'config'%5D, () =%3E %7B%0A// fuse.dev(%7B port: 3000 %7D)%0A// // add dev instructions%0A// app.watch().hmr()%0A// return fuse.run()%0A// %7D)%0A%0A// Sparky.task('clean', () =%3E Sparky.src('dist/').clean('dist/'))%0A// Sparky.task('prod-env', %5B'clean'%5D, () =%3E %7B isProduction = true %7D)%0A// Sparky.task('dist', %5B'prod-env', 'config'%5D, () =%3E %7B%0A// // comment out to prevent dev server from running (left for the demo)%0A// fuse.dev(%7B port: 3000 %7D)%0A// return fuse.run()%0A// %7D)%0A%0A%0A
cons
@@ -1103,20 +1103,16 @@
endor%0A
-let
vendor =
@@ -1182,14 +1182,10 @@
app%0A
+
-let
app
|
b6da535e2061e73f76c1028330ed9aa3411280d7 | fix copy and paste issue in Chrome and Safari | src/ace/TextInput.js | src/ace/TextInput.js | /**
* Ajax.org Code Editor (ACE)
*
* @copyright 2010, Ajax.org Services B.V.
* @license LGPLv3 <http://www.gnu.org/licenses/lgpl-3.0.txt>
* @author Fabian Jakobs <fabian AT ajax DOT org>
*/
require.def("ace/TextInput", ["ace/lib/event"], function(event) {
var TextInput = function(parentNode, host) {
var text = document.createElement("textarea");
var style = text.style;
style.position = "absolute";
style.left = "-10000px";
style.top = "-10000px";
parentNode.appendChild(text);
var PLACEHOLDER = String.fromCharCode(0);
sendText();
var inCompostion = false;
var copied = false;
function sendText() {
if (!copied) {
var value = text.value;
if (value) {
if (value.charCodeAt(value.length-1) == PLACEHOLDER.charCodeAt(0)) {
value = value.slice(0, -1);
if (value)
host.onTextInput(value);
} else
host.onTextInput(value);
}
}
copied = false;
// Safari doesn't fire copy events if no text is selected
text.value = PLACEHOLDER;
text.select();
}
var onTextInput = function(e) {
setTimeout(function() {
if (!inCompostion)
sendText();
}, 0);
};
var onCompositionStart = function(e) {
inCompostion = true;
sendText();
text.value = "";
host.onCompositionStart();
setTimeout(onCompositionUpdate, 0);
};
var onCompositionUpdate = function() {
host.onCompositionUpdate(text.value);
};
var onCompositionEnd = function() {
inCompostion = false;
host.onCompositionEnd();
onTextInput();
};
var onCopy = function() {
copied = true;
text.value = host.getCopyText();
text.select();
copied = true;
};
var onCut = function() {
copied = true;
text.value = host.getCopyText();
host.onCut();
text.select();
};
event.addListener(text, "keypress", onTextInput);
event.addListener(text, "textInput", onTextInput);
event.addListener(text, "paste", onTextInput);
event.addListener(text, "propertychange", onTextInput);
event.addListener(text, "copy", onCopy);
event.addListener(text, "cut", onCut);
event.addListener(text, "compositionstart", onCompositionStart);
event.addListener(text, "compositionupdate", onCompositionUpdate);
event.addListener(text, "compositionend", onCompositionEnd);
event.addListener(text, "blur", function() {
host.onBlur();
});
event.addListener(text, "focus", function() {
host.onFocus();
text.select();
});
this.focus = function() {
host.onFocus();
text.select();
text.focus();
};
this.blur = function() {
text.blur();
};
};
return TextInput;
}); | JavaScript | 0 | @@ -1915,24 +1915,57 @@
ied = true;%0A
+ setTimeout(sendText, 0);%0A
%7D;%0A%0A
@@ -2094,24 +2094,57 @@
t.select();%0A
+ setTimeout(sendText, 0);%0A
%7D;%0A%0A
|
6fe2e2c20ed2b6e3531df6de7f72a79b0b1e3228 | fix timezone bug | tests/unit/components/bootstrap-datepicker-test.js | tests/unit/components/bootstrap-datepicker-test.js | import { run } from '@ember/runloop';
import { test, moduleForComponent } from 'ember-qunit';
import startApp from '../../helpers/start-app';
var App;
moduleForComponent('bootstrap-datepicker', 'BootstrapDatepickerComponent', {
unit: true,
beforeEach: function() {
App = startApp();
},
afterEach: function() {
run(App, 'destroy');
}
});
test('is an input tag', function(assert) {
assert.equal(this.$().prop('tagName'), 'INPUT');
});
test('displays empty input field when no date is set', function(assert) {
this.subject({
value: null
});
assert.equal(this.$().val(), '');
});
test('displays date with default format when no format is set', function(assert) {
this.subject({
value: new Date(2014, 11, 31)
});
assert.equal(this.$().val(), '12/31/2014');
});
test('displays date with custom format when format is set', function(assert) {
this.subject({
value: new Date(2014, 11, 31),
format: 'dd.M.yy'
});
assert.equal(this.$().val(), '31.Dec.14');
});
test('resets date when input is cleared', function(assert) {
this.subject({
value: new Date(2014, 11, 31)
});
assert.ok(this.$().datepicker('getDate'), 'initial value is set');
this.$().val('');
this.$().datepicker('update');
assert.equal(this.$().datepicker('getDate'), null, 'value is reset when input is cleared');
});
test('should use customParser if provided', function(assert) {
assert.expect(1);
this.subject({
value: '2015-09-14T16:59:01+02:00',
customParser: function(value) {
return new Date(value);
}
});
assert.equal(this.$().val(), '09/14/2015');
});
test('sets dates provided by value (multidate, default multidateSeparator)', function(assert) {
this.subject({
value: [new Date(2015, 0, 13), new Date(2015, 0, 7), new Date(2015, 0, 15)],
multidate: true
});
assert.equal(this.$().val(), '01/13/2015,01/07/2015,01/15/2015', 'sets value as input field value');
assert.equal(this.$().datepicker('getDates').length, 3, 'sets internal datepicker dates by value');
});
test('sets dates provided by value (multidate, multidateSeparator provided)', function(assert) {
this.subject({
value: [new Date(2015, 0, 13), new Date(2015, 0, 7), new Date(2015, 0, 15)],
multidate: true,
multidateSeparator: ';'
});
assert.equal(this.$().val(), '01/13/2015;01/07/2015;01/15/2015', 'sets value as input field value using multidate separator');
assert.equal(this.$().datepicker('getDates').length, 3, 'sets internal datepicker dates by value');
});
test('updates startDate', function(assert) {
var startDate = new Date(2015, 2);
var newStartDate = new Date(2015, 3);
var component = this.subject({
value: new Date(2015, 4),
startDate: startDate
});
assert.equal(this.$().data('datepicker').o.startDate.getMonth(), startDate.getMonth(), 'sets initial startDate');
component.set('startDate', newStartDate);
assert.equal(this.$().data('datepicker').o.startDate.getMonth(), newStartDate.getMonth(), 'updates startDate');
});
test('updates format', function(assert) {
var format = 'mm/yyyy';
var newFormat = 'yyyy';
var component = this.subject({
value: new Date(2015, 4),
format: format
});
assert.equal(this.$().data('datepicker').o.format, format, 'sets initial format');
component.set('format', newFormat);
assert.equal(this.$().data('datepicker').o.format, newFormat, 'updates format');
});
test('updates minViewMode', function(assert) {
var minViewMode = 'years';
var yearsViewModeNumber = 2;
var newMinViewMode = 'months';
var monthsViewModeNumber = 1;
var component = this.subject({
value: new Date(2015, 4),
minViewMode: minViewMode
});
assert.equal(this.$().data('datepicker').o.minViewMode, yearsViewModeNumber, 'sets initial minViewMode');
component.set('minViewMode', newMinViewMode);
assert.equal(this.$().data('datepicker').o.minViewMode, monthsViewModeNumber, 'updates minViewMode');
});
| JavaScript | 0.000001 | @@ -2807,32 +2807,35 @@
.o.startDate.get
+UTC
Month(), startDa
@@ -2832,32 +2832,35 @@
), startDate.get
+UTC
Month(), 'sets i
@@ -2974,32 +2974,35 @@
.o.startDate.get
+UTC
Month(), newStar
@@ -3010,16 +3010,19 @@
Date.get
+UTC
Month(),
|
8b01cba77dc10ccb2810ddd085d7f4ce63a32ad2 | refresh token on init | apis/nsw.js | apis/nsw.js | /**
* @file apis/nsw.js
*
* @author fewieden
* @license MIT
*
* @see https://github.com/fewieden/MMM-Fuel
*/
/**
* @external node-fetch
* @see https://www.npmjs.com/package/node-fetch
*/
const fetch = require('node-fetch');
/**
* @external moment
* @see https://www.npmjs.com/package/moment
*/
const moment = require('moment');
const SECOND = 1000;
const MINUTE = 60 * SECOND;
const HOUR = 60 * MINUTE;
const QUARTER_DAY = 6 * HOUR;
/**
* @module apis/nsw
* @description Queries data from https://api.nsw.gov.au
* @async
*
* @requires external:node-fetch
*
* @param {Object} config - Configuration.
* @param {number} config.lat - Latitude of Coordinate.
* @param {number} config.lng - Longitude of Coordinate.
* @param {int} config.radius - Lookup area for gas stations.
* @param {string} config.sortBy - Type to sort by price.
* @param {string[]} config.types - Requested fuel types.
* @param {boolean} config.showOpenOnly - Flag to show only open gas stations.
*
* @returns {Object} Object with function getData.
*/
module.exports = async config => {
/** @member {string} baseUrl - API url */
const baseUrl = 'https://api.onegov.nsw.gov.au';
/** @member {number} transaction - unique transaction id */
let transaction = 1;
/** @member {Object} types - Mapping of fuel types to API fuel types. */
const types = {
diesel: 'DL',
e5: 'P95'
};
/** @member {string|undefined} token - authorization token */
let token;
async function refreshToken() {
try {
const response = await fetch(`${baseUrl}/oauth/client_credential/accesstoken?grant_type=client_credentials`, {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${Buffer.from(`${config.api_key}:${config.secret}`).toString('base64')}`
}
});
const parsedResponse = await response.json();
token = parsedResponse.access_token;
} catch (e) {
console.log('MMM-Fuel: Failed to refresh token', e);
}
}
setInterval(refreshToken, QUARTER_DAY);
/**
* @function requestFuelType
* @description API request for specified type.
* @async
*
* @param {string} type - Fuel type.
* @returns {Promise} Object with fuel type and data.
*/
const requestFuelType = async type => {
const response = await fetch(`${baseUrl}/FuelPriceCheck/v1/fuel/prices/nearby`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
apikey: config.api_key,
Authorization: `Bearer ${token}`,
transactionid: transaction++,
requesttimestamp: moment().utc()
.format('DD/MM/YYYY hh:mm:ss A')
},
body: JSON.stringify({
fueltype: types[type],
latitude: config.lat,
longitude: config.lng,
radius: config.radius,
sortby: 'price',
sortascending: true
})
});
return {
type,
data: await response.json()
};
};
/**
* @function filterStations
* @description Helper function to filter gas stations.
*
* @param {Object} station - Gas Station
*
* @returns {boolean} To keep or filter the station.
*/
const filterStations = station => {
const prices = Object.keys(station.prices);
return !prices.every(type => station.prices[type] === -1);
};
/**
* @function sortByDistance
* @description Helper function to sort gas stations by distance.
*
* @param {Object} a - Gas Station
* @param {Object} b - Gas Station
*
* @returns {number} Sorting weight.
*/
const sortByDistance = (a, b) => a.distance - b.distance;
/**
* @function normalizeStations
* @description Helper function to normalize the structure of gas stations for the UI.
*
* @param {Object[]} stations - Gas Station.
* @param {string[]} keys - Fuel types except config option sortBy.
*
* @returns {void}
*
* @see apis/README.md
*/
const normalizeStations = (stations, keys) => {
stations.forEach((value, index) => {
/* eslint-disable no-param-reassign */
stations[index].prices = { [config.sortBy]: value.price };
keys.forEach(type => {
stations[index].prices[type] = -1;
});
stations[index].lat = value.location.latitude;
stations[index].lng = value.location.longitude;
stations[index].distance = value.location.distance;
/* eslint-enable no-param-reassign */
});
};
const mapPriceToStation = ({ stations, prices }) => {
for (const station of stations) {
for (const price of prices) {
if (station.code === price.stationcode) {
station.price = price.price;
break;
}
}
}
return stations;
};
return {
/**
* @function getData
* @description Performs the data query and processing.
* @async
*
* @returns {Object} Returns object described in the provider documentation.
*
* @see apis
*/
async getData() {
const responses = await Promise.all(config.types.map(requestFuelType));
const collection = {};
for (const response of responses) {
collection[response.type] = mapPriceToStation(response.data);
}
let stations = collection[config.sortBy];
const maxPrices = {};
for (const type in collection) {
for (const station of collection[type]) {
if (!maxPrices[type] || station.price > maxPrices[type]) {
maxPrices[type] = station.price;
}
}
}
delete collection[config.sortBy];
const keys = Object.keys(collection);
normalizeStations(stations, keys);
keys.forEach(type => {
collection[type].forEach(station => {
for (let i = 0; i < stations.length; i += 1) {
if (station.code === stations[i].code) {
stations[i].prices[type] = station.price;
break;
}
}
});
});
for (const station of stations) {
for (const type in station.prices) {
if (station.prices[type] === -1) {
station.prices[type] = `>${maxPrices[types[type]]}`;
}
}
}
stations = stations.filter(filterStations);
const distance = stations.slice(0);
distance.sort(sortByDistance);
return {
types: ['diesel', 'e5'],
unit: 'km',
currency: 'AUD',
byPrice: stations,
byDistance: distance
};
}
};
};
| JavaScript | 0.000001 | @@ -2110,24 +2110,50 @@
%7D%0A %7D%0A%0A
+ await refreshToken();%0A
setInter
|
d5cedc87452e82c3bf54a4b14fc112dc3c4f5189 | put paddle particle clean up in more obvious place. | polyball/shared/model/powerups/KingMidas.js | polyball/shared/model/powerups/KingMidas.js | /**
* Created by ryan on 01/04/16.
*/
var inherits = require('inherits');
var Powerup = require('polyball/shared/model/powerups/Powerup');
var StyleCommons = require('polyball/shared/StyleCommons');
var _ = require('lodash');
var Events = require('polyball/shared/model/behaviors/Events');
/**
* This powerup makes balls worth an additional point
* @param config - see powerup config
* @constructor
*/
var KingMidas = function (config){
config.body.styles = StyleCommons.kingMidasStyle;
Powerup.call(this, config);
this.name = KingMidas.Name;
this.renderer = config.renderer;
};
inherits(KingMidas, Powerup);
KingMidas.prototype.handleGoal = function(event){
if (event.ball.lastTouchedID === this.owner){
var player = this.model.getPlayer(this.owner);
if (player != null){
if (player.id !== event.entity.id){
player.score += 1;
} else {
player.score -= 1;
}
}
}
};
KingMidas.prototype.activate = function(model){
if (!this.active){
this.model = model;
KingMidas.super_.prototype.activate.call(this, model);
model.getWorld().on(Events.ballGoalCollision, this.handleGoal, this);
this.active = true;
}
};
KingMidas.prototype.deactivate = function(model){
if (this.active){
model.getWorld().off(Events.ballGoalCollision, this.handleGoal, this);
this.active = false;
}
if (typeof this.deactivateRender === 'function') {
this.deactivateRender();
}
};
KingMidas.prototype.render = function(renderer) {
var self = this;
if (this.active) {
var emitter;
var emitters = renderer.getEmitters();
// add paddle emitter
var paddleEmitters = emitters.filter(function (emitter) {
return self.owner === emitter.owner;
});
var ownerPaddle = self.model.getPlayer(self.owner).paddle;
if (paddleEmitters.length === 0) {
kingMidasPaddleParticleStyle.angleStart = ownerPaddle.body.state.angular.pos * 57.2958;
paddleEmitters.push(renderer.addEmitter(['res/particle.png'], kingMidasPaddleParticleStyle));
paddleEmitters[0].owner = self.owner;
}
renderer.moveEmitter(
paddleEmitters[0],
{x: ownerPaddle.body.state.pos.x, y: ownerPaddle.body.state.pos.y}
);
// add ball emmitters
var balls = this.model.getBalls(function(ball) {
return ball.lastTouchedID === self.owner;
});
balls.forEach(function(ball) {
// Find the emitter for this ball
var foundEmitters = emitters.filter(function(emitter) {
return emitter.ball === ball;
});
if (foundEmitters.length === 0) { // Create a new emitter
emitter = renderer.addEmitter(['res/particle.png'], kingMidasBallParticleStyle);
emitter.ball = ball;
}
else if (foundEmitters.length === 1) { // Update emitter location
emitter = foundEmitters[0];
var point = {
x: ball.body.state.pos.x,
y: ball.body.state.pos.y
};
renderer.moveEmitter(emitter, point);
}
});
// Remove any emitters if they hit an opposing players paddle.
balls = this.model.getBalls(function(ball) {
return ball.lastTouchedID !== self.owner;
});
balls.forEach(function(ball) {
var foundEmitters = emitters.filter(function(emitter) {
return emitter.ball === ball;
});
foundEmitters.forEach(function(emitter) {
renderer.removeEmitter(emitter);
});
});
}
if (!this.renderedAtLeastOnce) {
this.deactivateRender = function () {
var emitters = renderer.getEmitters();
var balls = self.model.getBalls(function (ball) {
return ball.lastTouchedID === self.owner;
});
balls.forEach(function (ball) {
var foundEmitters = emitters.filter(function (emitter) {
return emitter.ball === ball || emitter.owner === self.owner;
});
foundEmitters.forEach(function(emitter) {
renderer.removeEmitter(emitter);
});
});
};
}
this.renderedAtLeastOnce = true;
};
KingMidas.prototype.toConfig = function (){
var config = { name: this.name};
_.assign(config, KingMidas.super_.prototype.toConfig.call(this));
return config;
};
var kingMidasBallParticleStyle = {
"alpha": {
"start": 1,
"end": 0
},
"scale": {
"start": 0.11,
"end": 0.01
},
"color": {
"start": StyleCommons.midasParticleStartColor,
"end": StyleCommons.midasParticleEndColor
},
"speed": {
"start": 12,
"end": 0
},
"startRotation": {
"min": 0,
"max": 0
},
"rotationSpeed": {
"min": 0,
"max": 0
},
"lifetime": {
"min": 1,
"max": 2
},
"blendMode": "normal",
"frequency": 0.005,
"emitterLifetime": -1,
"maxParticles": 500,
"pos": {
"x": 0,
"y": 0
},
"addAtBack": true,
"spawnType": "circle",
"spawnCircle": {
"x": 0,
"y": 0,
"r": 6
}
};
var kingMidasPaddleParticleStyle = {
"alpha": {
"start": 0,
"end": 0.22
},
"scale": {
"start": 0.8,
"end": 0.18,
"minimumScaleMultiplier": 1
},
"color": {
"start": "#ffcc00",
"end": "#ffcc00"
},
"speed": {
"start": 60,
"end": 0
},
"acceleration": {
"x": 0,
"y": 0
},
"startRotation": {
"min": 0,
"max": 0
},
"rotationSpeed": {
"min": 0,
"max": 0
},
"lifetime": {
"min": 0.4,
"max": 0.4
},
"blendMode": "add",
"frequency": 0.01,
"emitterLifetime": -1,
"maxParticles": 500,
"pos": {
"x": 0,
"y": 0
},
"addAtBack": true,
"spawnType": "burst",
"particlesPerWave": 8,
"particleSpacing": 45,
"angleStart": 45
};
KingMidas.Name = "KingMidas";
module.exports = KingMidas; | JavaScript | 0 | @@ -4093,32 +4093,291 @@
%7D);%0A%0A
+ var foundEmitters = emitters.filter(function (emitter) %7B%0A return emitter.owner === self.owner;%0A %7D);%0A%0A foundEmitters.forEach(function(emitter) %7B%0A renderer.removeEmitter(emitter);%0A %7D);%0A%0A
ball
@@ -4529,40 +4529,8 @@
ball
- %7C%7C emitter.owner === self.owner
;%0A
|
dc5d42f40d2e71a49cf78539be57041d434679ec | Add completed JS exercise for printTriangle | solutions/printTriangle.js | solutions/printTriangle.js | /*
Function name: printTriangle(count);
Input: A number n
Returns: Nothing
Prints: A right triangle consisting of "*" characters that is "n"
characters tall
For example, printTriangle(4); should print
*
**
***
****
The printLine(); function is here to help you.
Conceptually, it prints out a row of stars (*) equal to "count".
Run it yourself to see how it works. Experiment with different inputs.
*/
function printLine(count) {
var starRow = "";
for (var i = 0; i < count; i++) {
starRow += "*";
}
console.log(starRow);
}
function printTriangle(height) {
// You have to fill in the details here! =]
}
// console.log(); prints something to the console as a means of basic debugging.
console.log(printTriangle(1));
console.log("\n\n\n"); // This is here to make the separation between triangles clearer
console.log(printTriangle(2));
console.log("\n\n\n"); // This is here to make the separation between triangles clearer
console.log(printTriangle(3));
console.log("\n\n\n"); // This is here to make the separation between triangles clearer
console.log(printTriangle(10));
/*
Remember: these are rumble strips, not a driving instructor.
If any are "false" then something is broken. But just because they all return
"true" doesn't mean you've nailed it. =]
*/
| JavaScript | 0 | @@ -641,52 +641,64 @@
%7B%0A
-// You have to fill in the details here! =%5D
+for (var i = 0; i %3C height; i++) %7B%0A printLine(i);%0A %7D
%0A%7D%0A%0A
@@ -806,17 +806,17 @@
riangle(
-1
+2
));%0A%0Acon
@@ -921,33 +921,33 @@
g(printTriangle(
-2
+3
));%0A%0Aconsole.log
@@ -1044,33 +1044,33 @@
g(printTriangle(
-3
+6
));%0A%0Aconsole.log
|
fd6304bfd73ae6d1f7559a22186ac313978b64c7 | add input autofocus | js/components/Header.js | js/components/Header.js | import React from 'react';
import classNames from 'classnames';
import emitter from '../emitter';
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {
showLoading: false
};
this._search = this._search.bind(this);
}
componentDidMount () {
emitter.on('resetLoader', () => {
this.setState({
showLoading: false
});
});
}
componentWillUnmount () {
emitter.removeListener('resetLoader');
}
_search (e) {
// only trigger search while user type enter
if (e.keyCode === 13) {
this.setState({
showLoading: true
});
emitter.emit('search', e.target.value);
}
}
render () {
return (
<div className="ui inverted segment center aligned">
<h1 className="ui header">
<div className={classNames('ui', 'icon', 'input', {
'loading': this.state.showLoading
})}>
<input type="text" onKeyDown={this._search} placeholder="Search..." />
<i className="search icon"></i>
</div>
</h1>
</div>
);
}
}
export default Header; | JavaScript | 0.000066 | @@ -1020,16 +1020,26 @@
arch...%22
+ autoFocus
/%3E%0A
|
4a05d5b3ccc2c5ab382438d92f1d31a4cedb07d2 | Revert "Revert "using HTTPS"" | src/actions/index.js | src/actions/index.js | import axios from 'axios';
const OPEN_WEATHER_API_KEY = '9b1e26b7dac3c0f0fec461c2d3d01883';
const ROOT_URL = `http://api.openweathermap.org/data/2.5/forecast?appid=${OPEN_WEATHER_API_KEY}`;
export const FETCH_WEATHER = 'FETCH_WEATHER';
export function fetchWeather(city) {
const url = `${ROOT_URL}&q=${city},es`;
const request = axios.get(url);
return {
type: FETCH_WEATHER,
payload: request
};
}
| JavaScript | 0 | @@ -108,16 +108,17 @@
= %60http
+s
://api.o
|
730371571ea1395eda9d46593aa7ac055dee3345 | Provide consistent way to see if user logged in | troposphere/static/js/context.js | troposphere/static/js/context.js | define([], function () {
return {
profile: null
}
});
| JavaScript | 0.999999 | @@ -29,16 +29,104 @@
eturn %7B%0A
+ hasLoggedInUser: function() %7B%0A return !!this.profile.get('username');%0A %7D,%0A
prof
|
2688315e38c2904f2e10248d013dd34763aa5f3e | add input callback to callback stack | DialogAndroid.js | DialogAndroid.js | /**
* @providesModule DialogAndroid
*/
'use strict';
var { NativeModules } = require('react-native');
var callbackNames = [
'onPositive',
'onNegative',
'onNeutral',
'onAny',
'itemsCallback',
'itemsCallbackSingleChoice',
'itemsCallbackMultiChoice',
'showListener',
'cancelListener',
'dismissListener',
];
class DialogAndroid {
constructor() {
this.options = {};
}
set(obj) {
Object.assign(this.options, obj);
}
show() {
var finalOptions = Object.assign({}, this.options);
var callbacks = {
error: (err, op) => console.error(err, op),
}
// Remove callbacks from the options, and store them separately
callbackNames.forEach(cb => {
if (cb in finalOptions) {
callbacks[cb] = finalOptions[cb];
finalOptions[cb] = true;
}
});
// Handle special case of input separately
if ('input' in finalOptions) {
finalOptions.input = Object.assign({}, finalOptions.input);
var inputCallback = finalOptions.input.callback || (x => console.log(x));
finalOptions.input.callback = true;
}
// Parse the result form multiple choice dialog
if ('itemsCallbackMultiChoice' in callbacks) {
var originalCallback = callbacks.itemsCallbackMultiChoice;
callbacks.itemsCallbackMultiChoice = selected => {
var indices = selected.split(',').map(x => parseInt(x));
var elements = indices.map(ind => (finalOptions.items || [])[ind]);
originalCallback(indices, elements);
}
}
var callbackFunc = (cb, ...rest) => callbacks[cb](...rest);
NativeModules.DialogAndroid.show(finalOptions, callbackFunc);
}
}
module.exports = DialogAndroid;
| JavaScript | 0 | @@ -1086,24 +1086,66 @@
ack = true;%0A
+ callbacks%5B'input'%5D = inputCallback;%0A
%7D%0A%0A /
|
d7991bc3af6d3bce7ae1fec107e8497c4b1e25f1 | Add click listener to play buttotn. | js/components/player.js | js/components/player.js | import React from 'react';
module.exports = React.createClass({
getInitialState: function getInitialState() {
return {
isPlayingStream: typeof window.orientation === 'undefined', // Should return true if not mobile
nowPlayingLabel: 'Offline',
};
},
setPlayerState: function setPlayerState() {
const stream = document.getElementById('stream-player');
if (!this.state.isPlayingStream) {
stream.pause();
} else {
stream.play();
}
},
componentDidMount: function componentDidMount() {
this.setPlayerState();
},
componentDidUpdate: function componentDidUpdate() {
this.setPlayerState();
},
render: function render() {
const audioButtonClass = this.state.isPlayingStream ? 'icon-play3' : 'icon-pause2';
return (
<div className="c-player">
<audio id="stream-player" src="http://airtime.frequency.asia:8000/airtime_128"></audio>
<button id="play-stream" className="c-player__button">
<span className={ audioButtonClass }></span>
</button>
<p className="c-player__text">{ this.state.nowPlayingLabel }</p>
<div className="c-player__volume">
<input type="range" value="8" data-steps="10" id="volume-slider" />
</div>
</div>
);
},
});
| JavaScript | 0 | @@ -268,16 +268,135 @@
;%0A %7D,%0A%0A
+ onPlayClicked: function onPlayClicked() %7B%0A this.setState(%7B isPlayingStream: !this.state.isPlayingStream %7D);%0A %7D,%0A%0A
setPla
@@ -872,12 +872,13 @@
on-p
-lay3
+ause2
' :
@@ -884,21 +884,20 @@
'icon-p
-ause2
+lay3
';%0A r
@@ -1094,16 +1094,47 @@
_button%22
+ onClick=%7B this.onPlayClicked %7D
%3E%0A
|
be9b0592d18af822971c2a61b97fde28ec2dea13 | Remove unused imports | app/Card.js | app/Card.js | import React, { Component, PropTypes } from 'react';
import { Button, ButtonToolbar, Collapse, Panel, Glyphicon } from 'react-bootstrap';
import Content from './Content';
import Interactions from './Interactions';
import Metadata from './Metadata';
const propTypes = {
// Required props
activity_comments: PropTypes.number.isRequired,
activity_date: PropTypes.string.isRequired,
activity_likes: PropTypes.number.isRequired,
activity_shares: PropTypes.number.isRequired,
activity_sentiment: PropTypes.number.isRequired,
activity_url: PropTypes.string.isRequired,
actor_avator: PropTypes.string.isRequired,
actor_description: PropTypes.string.isRequired,
actor_name: PropTypes.string.isRequired,
actor_url: PropTypes.string.isRequired,
actor_username: PropTypes.string.isRequired,
provider: PropTypes.string.isRequired,
// Optional props
activity_attachment: PropTypes.string,
activity_attachment_type: PropTypes.string,
activity_latitude: PropTypes.string,
activity_longitude: PropTypes.string,
activity_message: PropTypes.string,
};
class Card extends Component {
constructor() {
super();
this.state = { showMetadata: false };
this.toggleMetadata = this.toggleMetadata.bind(this);
}
toggleMetadata() {
this.setState({ showMetadata: !this.state.showMetadata });
}
render() {
let titleSentiment;
let titleColor;
if (this.props.activity_sentiment > 0) {
titleSentiment = (<h2>Positive</h2>);
titleColor = 'success';
} else if (this.props.activity_sentiment < 0) {
titleSentiment = (<h2>Negative</h2>);
titleColor = 'danger';
} else {
titleSentiment = (<h2>Neutral</h2>);
titleColor = 'warning';
}
return (
<div className="card">
<Panel header={titleSentiment} bsStyle={titleColor}>
<Content
activity_comments={this.props.activity_comments}
activity_date={this.props.activity_date}
activity_likes={this.props.activity_likes}
activity_shares={this.props.activity_shares}
activity_url={this.props.activity_url}
actor_name={this.props.actor_name}
actor_url={this.props.actor_url}
provider={this.props.provider}
activity_attachment={this.props.activity_attachment}
activity_attachment_type={this.props.activity_attachment_type}
activity_message={this.props.activity_message}
/>
<Interactions
showMetadata={this.state.showMetadata}
metadataCallbacks={{ toggle: this.toggleMetadata.bind(this) }}
/>
<Collapse in={this.state.showMetadata}>
<div>
<br /> {/* Quick fix to make spacing look better. */}
<Metadata
activity_latitude={this.props.activity_latitude}
activity_longitude={this.props.activity_longitude}
actor_avator={this.props.actor_avator}
actor_description={this.props.actor_description}
actor_name={this.props.actor_name}
actor_url={this.props.actor_url}
actor_username={this.props.actor_username}
/>
</div>
</Collapse>
</Panel>
</div>
);
}
}
Card.propTypes = propTypes;
export default Card;
| JavaScript | 0.000001 | @@ -58,31 +58,8 @@
rt %7B
- Button, ButtonToolbar,
Col
@@ -74,19 +74,8 @@
anel
-, Glyphicon
%7D f
|
a95aea19da39b6bee28a4539188b00fcd9d4732a | Remove logging | tasks/md.js | tasks/md.js | var async = require('async');
var mm = require('marky-mark');
var fs = require('fs-extra');
var _ = require('lodash');
var chalk = require('chalk');
var path = require('path');
module.exports = function(grunt) {
grunt.registerMultiTask('md', 'Compile markdown files with yml view context into html', function() {
var done = this.async();
var options = this.options({
mm: {}
});
async.reduce(this.files, [], function(memo, file, next) {
var dest = file.dest ? file.dest.replace('.md', '.html') : '';
mm.parseFiles(file.src, options.mm, function(err, markedObj) {
if (err) {
return next(err);
}
markedObj.forEach(function(obj, i) {
if (dest && dest.split('/').pop().indexOf('.') === -1) {
var thisDest = dest + '/' + (options.flatten ? obj.filename + '.html' : file.src[i]);
obj.dest = path.normalize(thisDest);
} else {
obj.dest = dest;
}
obj.origPath = file.src[i];
console.log(obj);
});
next(null, memo.concat(markedObj));
});
}, function(err, markedObjs) {
if (err) {
return grunt.log.fatal(err);
}
async.each(markedObjs, function(obj, next) {
if (options.config) {
grunt.config.set(options.config + '.' + obj.filename, obj);
}
if (options.event) {
grunt.event.emit(options.event, obj);
}
if (obj.dest) {
var html = obj.content;
if (options.wrapper) {
var wrapper = options.wrapper;
if (_.isPlainObject(wrapper)) {
wrapper = wrapper[obj.origPath] || wrapper[obj.filename] || wrapper['*'];
} else if (typeof wrapper !== 'string') {
grunt.log.warn('Wrapper type not supported: options.wrapper must be an object or a string.');
next();
}
fs.readFile(wrapper, 'utf8', function(err, wrap) {
html = _.template(wrap, _.extend({}, obj.meta, { content: html }));
fs.outputFile(obj.dest, html, next);
});
} else {
fs.outputFile(obj.dest, html, next);
}
} else {
next();
}
}, function(err) {
if (err) {
grunt.log.fatal(err);
} else {
grunt.log.writeln(chalk.green(markedObjs.length, 'files compiled'));
}
done();
});
});
});
};
| JavaScript | 0.000001 | @@ -1012,36 +1012,8 @@
i%5D;%0A
- console.log(obj);%0A
|
59c79ef434fabaf0377239488d6a302dd3f3ebe5 | Remove a duplicate todo | cli/main.js | cli/main.js | #!/usr/bin/env node
'use strict'
require('debug').enable('UCompiler:*')
const UCompiler = require('..')
const knownCommands = ['go', 'watch']
const parameters = process.argv.slice(2)
if (!parameters.length || knownCommands.indexOf(parameters[0]) === -1) {
console.log('Usage: ucompiler go|watch [path]')
process.exit(0)
}
if (parameters[0] === 'go') {
// TODO: Compile only those by default that are in rules
UCompiler.compile(parameters[1] || null, {cwd: process.cwd()}).catch(function(e) {
console.error(e)
process.exit(1)
})
}
| JavaScript | 0.000005 | @@ -356,67 +356,8 @@
) %7B%0A
- // TODO: Compile only those by default that are in rules%0A
UC
|
c962ec925be82cb28d089be75d464bd477074d9c | Fix incorrect postgres update syntax in password migration | api/controllers/auth.js | api/controllers/auth.js | 'use strict'
let passport = require('passport')
let BasicStrategy = require('passport-http').BasicStrategy
let BearerStrategy = require('passport-http-bearer').Strategy
let crypto = require('crypto')
let LocalStrategy = require('passport-local').Strategy
let User = require('../db').User
let Token = require('../db').Token
let Client = require('../db').Client
let bcrypt = require('bcrypt')
exports.LocalStrategy = new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
session: false
},
function (email, password, done) {
User.findOne({ where: { email: { $iLike: email }}}).then(function (user) {
if (!user) {
done(null, false)
return
}
if (user.salt) {
crypto.pbkdf2(password, user.salt, 25000, 512, 'sha256', function (err, hashRaw) {
let hash = new Buffer(hashRaw, 'binary').toString('hex')
if (user.password === hash) {
// Legacy password system migration
bcrypt.hash(password, 16, function (error, convertedPassword) {
if (error) {
done(null, user)
return
}
User.update({
password: convertedPassword,
salt: null
}).then(function () {
done(null, user)
}).catch(function () {
done(null, user)
})
})
} else {
done(null, false)
}
})
} else {
bcrypt.compare(password, user.password, function (err, res) {
if (err || res === false) {
done(null, false)
} else {
done(null, user)
}
})
}
}).catch(function () {
done(null, false)
})
})
passport.use(exports.LocalStrategy)
passport.use('client-basic', new BasicStrategy(
function (username, secret, callback) {
Client.findOne({ name: username }).then(function (client) {
if (!client) {
callback(null, false)
}
bcrypt.compare(secret, client.secret, function (err, res) {
if (err || res === false) {
callback(null, false)
} else {
callback(null, client)
}
})
}).catch(function () {
callback(null, false)
})
}
))
passport.use(new BearerStrategy(
function (accessToken, callback) {
Token.findOne({ value: accessToken }).then(function (token) {
if (!token) {
callback(null, false)
return
}
callback(null, token.userId, { scope: '*' })
}).catch(function () {
callback(null, false)
})
}
))
exports.isClientAuthenticated = passport.authenticate('client-basic', { session : false })
exports.isBearerAuthenticated = passport.authenticate('bearer', { session: false })
exports.isAuthenticated = function (req, res, next) {
if (req.isUnauthenticated() === false) {
return next()
} else {
req.session.returnTo = req.originalUrl || req.url
return passport.authenticate('bearer', { session : true, failureRedirect: '/login' })(req, res, next)
}
}
| JavaScript | 0.000009 | @@ -1196,16 +1196,59 @@
t: null%0A
+ %7D, %7B%0A id: user.id%0A
|
f6b46ce86fbe2aed6c1022ee3383d92fc6dc8203 | Copy css.map as well | build/copy.js | build/copy.js | module.exports = {
all: {
files: [
{
expand: true,
src: [
'index.html',
'404.html',
'sitemap.xml',
'robots.txt'
],
dest: global.dist
},
{ expand: true, cwd: 'src/download/', src: ['**'], dest: global.dist + '/download/' },
{ expand: true, cwd: 'src/images/', src: ['**'], dest: global.dist + '/images/', },
{ expand: true, cwd: 'src/javascript/_autogenerated/', src: ['**'], dest: global.dist + '/js/texts/' },
{ expand: true, cwd: 'src/javascript/_common/lib/pushwooshSDK/', src: ['**'], dest: global.dist }, /* serves pushwoosh sdks from root */
{ expand: true, cwd: 'src/javascript/', src: ['manifest.json'], dest: global.dist },
{ expand: true, cwd: 'scripts', src: ['CNAME'], dest: 'dist' },
// chartiq-dependency
{ expand: true, cwd: 'node_modules/@binary-com/smartcharts/dist/', src: ['chartiq.min.js'], dest: global.dist + '/js' },
{ expand: true, cwd: 'node_modules/@binary-com/smartcharts/dist/', src: ['smartcharts.css'], dest: global.dist + '/css', },
// binary-style
{ expand: true, cwd: 'node_modules/@binary-com/binary-style/src/images/favicons', src: ['**'], dest: global.dist + '/images/favicons/', },
{ expand: true, cwd: 'node_modules/@binary-com/binary-style/src/images/favicons', src: ['favicon.ico'], dest: global.dist },
{ expand: true, cwd: 'node_modules/@binary-com/binary-style/src/images/logo', src: ['**'], dest: global.dist + '/images/logo/', },
]
}
};
| JavaScript | 0 | @@ -1233,24 +1233,26 @@
iq.min.js'%5D,
+
dest: globa
@@ -1373,16 +1373,17 @@
arts.css
+*
'%5D, dest
|
c15c4f9ea2843271c9cd827007f70bcfd274c4b3 | Resolve about asserts | topics/about_asserts.js | topics/about_asserts.js |
module("About Asserts (topics/about_asserts.js)");
test("ok", function() {
ok(__ === true, 'what will satisfy the ok assertion?');
});
test("not ok", function() {
ok(__ === false, 'what is a false value?');
});
test("equal", function() {
equal(__, 1 + 1, 'what will satisfy the equal assertion?');
});
| JavaScript | 0.000546 | @@ -73,26 +73,28 @@
() %7B%0A ok(
-__
+true
=== true, '
@@ -172,18 +172,21 @@
%0A ok(
-__
+false
=== fal
@@ -262,10 +262,9 @@
ual(
-__
+2
, 1
@@ -298,25 +298,24 @@
equal assertion?');%0A%7D);
-%0A
|
612a72c8551df75f8329a31020cd4a76d49ad63a | Set texture on updateTexture event from voxel-stitch | aoshader.js | aoshader.js | var fs = require("fs")
var createShader = require("gl-shader")
var mat4 = require('gl-matrix').mat4
module.exports = function(game, opts) {
return new ShaderPlugin(game, opts);
};
module.exports.pluginInfo = {
clientOnly: true,
loadAfter: ['voxel-stitch'],
};
function ShaderPlugin(game, opts) {
this.shell = game.shell;
this.stitcher = game.plugins.get('voxel-stitch');
if (!this.stitcher) throw new Error('voxel-shader requires voxel-stitch plugin'); // for tileCount uniform below
this.perspectiveResize = opts.perspectiveResize !== undefined ? opts.perspectiveResize : true;
this.enable();
}
ShaderPlugin.prototype.enable = function() {
this.shell.on('gl-init', this.onInit = this.ginit.bind(this));
this.shell.on('gl-render', this.onRender = this.render.bind(this));
if (this.perspectiveResize) this.shell.on('gl-resize', this.onResize = this.resize.bind(this));
};
ShaderPlugin.prototype.disable = function() {
this.shell.removeListener('gl-init', this.onInit);
this.shell.removeListener('gl-render', this.onRender);
if (this.onResize) this.shell.removeListener('gl-resize', this.onResize);
};
ShaderPlugin.prototype.ginit = function() {
this.shader = this.createAOShader();
this.resize();
this.modelMatrix = mat4.identity(new Float32Array(16)) // TODO: merge with view into modelView? or leave for flexibility?
};
ShaderPlugin.prototype.resize = function() {
//Calculation projection matrix
this.projectionMatrix = mat4.perspective(new Float32Array(16), Math.PI/4.0, this.shell.width/this.shell.height, 1.0, 1000.0)
};
ShaderPlugin.prototype.render = function() {
var gl = this.shell.gl
this.viewMatrix = this.shell.camera.view() // TODO: expose camera through a plugin instead?
gl.enable(gl.CULL_FACE)
gl.enable(gl.DEPTH_TEST)
//Bind the shader
var shader = this.shader
shader.bind()
shader.attributes.attrib0.location = 0
shader.attributes.attrib1.location = 1
shader.uniforms.projection = this.projectionMatrix
shader.uniforms.view = this.viewMatrix
shader.uniforms.model = this.modelMatrix
shader.uniforms.tileCount = this.stitcher.tileCount
// TODO: relocate variables off of game.shell (texture, meshes)
var texture = this.stitcher.texture
if (texture) shader.uniforms.tileMap = texture.bind() // texture might not have loaded yet
for (var i = 0; i < this.shell.meshes.length; ++i) {
var mesh = this.shell.meshes[i];
mesh.triangleVAO.bind()
gl.drawArrays(gl.TRIANGLES, 0, mesh.triangleVertexCount)
mesh.triangleVAO.unbind()
}
};
ShaderPlugin.prototype.createAOShader = function() {
return createShader(this.shell.gl,
fs.readFileSync(__dirname+"/lib/ao.vsh"),
fs.readFileSync(__dirname+"/lib/ao.fsh"))
};
| JavaScript | 0 | @@ -491,13 +491,31 @@
orm
-below
+and updateTexture event
%0A%0A
@@ -908,16 +908,107 @@
this));%0A
+ this.stitcher.on('updateTexture', this.onUpdateTexture = this.updateTexture.bind(this));%0A
%7D;%0A%0AShad
@@ -1235,18 +1235,204 @@
esize);%0A
+ this.stitcher.removeListener('updateTexture', this.onUpdateTexture);%0A%7D;%0A%0AShaderPlugin.prototype.updateTexture = function(texture) %7B%0A this.texture = texture; // used in tileMap uniform%0A
%7D
-;
%0A%0AShader
@@ -2493,50 +2493,17 @@
%0A%0A
-var texture = this.stitcher.texture%0A if (
+if (this.
text
@@ -2533,16 +2533,21 @@
leMap =
+this.
texture.
|
f7219351462b59f8694b96f89eca43aba2bba6ed | Disable loading if the plugin is already loaded | js/components/plugin.js | js/components/plugin.js |
define(
['react', 'stores/plugin_store', 'actions/plugin_action_creators', 'require'],
function(React, PluginStore, Actions, require) {
var getStateFromStore = function(plugin) {
return {
loaded: PluginStore.loaded(plugin)
};
};
return React.createClass({
displayName: 'Plugin',
propTypes: {
plugin: React.PropTypes.string.isRequired
},
getInitialState: function() {
return getStateFromStore(this.props.plugin);
},
render: function() {
if (this.state.loaded) {
return (
<div className="plugin">
{React.createElement(require(this.props.plugin), null)}
</div>
);
} else {
return (
<div className="plugin-loading">
Loading...
</div>
);
}
},
componentDidMount: function() {
PluginStore.addLoadListener(this._onLoad);
},
componentWillUnmount: function() {
PluginStore.removeLoadListener(this._onLoad);
},
componentWillMount: function() {
Actions.loadPlugin(this.props.plugin);
},
_onLoad: function() {
this.setState(getStateFromStore(this.props.plugin));
}
});
}
); | JavaScript | 0.000001 | @@ -1107,32 +1107,68 @@
t: function() %7B%0A
+ if (!this.state.loaded) %7B%0A
Actions.
@@ -1190,32 +1190,42 @@
.props.plugin);%0A
+ %7D%0A
%7D,%0A%0A
|
c64828b97f6005ad586c4e9c0c1d1cf731428471 | add toast to boots and css dependancies | app/boot.js | app/boot.js | require.config({
waitSeconds: 120,
baseUrl : 'app/',
IESelectorLimit: true,
paths: {
'angular' : 'libs/angular-flex/angular-flex',
'angular-animate' : 'libs/angular-animate/angular-animate.min',
'angular-loading-bar' : 'libs/angular-loading-bar/src/loading-bar',
'angular-route' : 'libs/angular-route/angular-route',
'angular-sanitize' : 'libs/angular-sanitize/angular-sanitize.min',
'angular-storage' : 'libs/angular-local-storage/dist/angular-local-storage.min',
'angular-messages' : 'libs/angular-messages/angular-messages.min',
'app-css' : 'css/main',
'css' : 'libs/require-css/css.min',
'bootstrap' : 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min',
'bm' :'libs/bootstrap-material-design/dist/js/material.min',
'bm-rip' : 'libs/bootstrap-material-design/dist/js/ripples.min',
'dragula':'libs/angular-dragula/dist/angular-dragula',
'flag-icon-css' : 'libs/flag-icon-css/css/flag-icon.min',
'font-awsome-css' : 'libs/font-awesome/css/font-awesome.min',
'iconate' : 'libs/iconate/dist/iconate',
'iconateCSS' : 'libs/iconate/dist/iconate.min',
'ionsound' : 'libs/ionsound/js/ion.sound.min',
'jquery' : 'libs/jquery/dist/jquery',
'linqjs' : 'libs/linqjs/linq.min',
'lodash' : 'libs/lodash/lodash',
'moment' : 'libs/moment/moment',
'ng-file-upload' :'libs/ng-file-upload/ng-file-upload.min',
'ng-file-upload-shim' :'libs/ng-file-upload/ng-file-upload.shim.min',
'ngDialog' :'libs/ng-dialog/js/ngDialog.min',
'ngSmoothScroll' : 'libs/ngSmoothScroll/lib/angular-smooth-scroll',
'outdated-browser-css' : 'libs/outdated-browser/outdatedbrowser/outdatedbrowser.min',
'scroll-directive' :'libs/scroll-animate-directive/src/scroll-animate-directive',
'shim' : 'libs/require-shim/src/shim',
'teather' :'libs/tether/dist/js/tether',
'text' : 'libs/requirejs-text/text',
'BM-date-picker' : 'libs/bootstrap-material-datetimepicker/js/bootstrap-material-datetimepicker',
// 'text-angular' : 'libs/textAngular/dist/textAngular.min',
'socket.io' : 'libs/socket.io-1.4.5/index'
// 'URIjs' : 'libs/uri.js/src',
},
shim: {
'libs/angular/angular' : { deps: ['jquery'] },
'angular' : { deps: ['libs/angular/angular'] },
'angular-route' : { deps: ['angular'] },
'angular-sanitize' : { deps: ['angular'] },
'guid' : { exports: 'ui_guid_generator' },
'angular-animate' : { deps: ['angular']},
'angular-loading-bar' : { deps: ['angular'] },
'bootstrap' : { deps:[ 'jquery','teather']},
'ng-file-upload' : { deps:[ 'angular']},
'ngSmoothScroll' : { deps:[ 'angular']},
'scroll-directive' : { deps:[ 'angular']},
'moment' : { deps:[ 'jquery']},
'BM-date-picker' : { deps:[ 'jquery','moment']},
'dragula': { deps: ['jquery','angular'] },
// 'text-angular' : { 'deps': ['text-angular-sanitize', 'angular'] },
// 'text-angular-sanitize' : { 'deps': ['angular', 'angular-sanitize']},
},
packages: [
{ name: 'scbd-angularjs-services', location : 'libs/scbd-angularjs-services/services' },
{ name: 'scbd-branding', location : 'libs/scbd-branding/directives' },
{ name: 'scbd-filters', location : 'libs/scbd-filters/filters' },
{ name: 'scbd-angularjs-filters', location : 'libs/scbd-angularjs-services/filters' },
{ name: 'scbd-angularjs-controls', location : 'libs/scbd-angularjs-controls/form-control-directives' },
]
});
// BOOT
require(['angular', 'app','moment', 'text', 'routes', 'template','bootstrap'], function(ng, app, moment) {
ng.element(document).ready(function () {
ng.bootstrap(document, [app.name]);
window.moment = require('moment');
});
});
// Fix IE Console
(function(a){a.console||(a.console={});for(var c="log info warn error debug trace dir group groupCollapsed groupEnd time timeEnd profile profileEnd dirxml assert count markTimeline timeStamp clear".split(" "),d=function(){},b=0;b<c.length;b++)a.console[c[b]]||(a.console[c[b]]=d)})(window); //jshint ignore:line
| JavaScript | 0 | @@ -2289,24 +2289,200 @@
im',%0A
+ 'toastr' : 'libs/angular-toastr/dist/angular-toastr.tpls.min',%0A 'toastr-css' : 'libs/angular-toastr/dist/angular-toastr.min',%0A //
'teather'
@@ -3435,18 +3435,8 @@
ery'
-,'teather'
%5D%7D,%0A
@@ -3533,32 +3533,91 @@
: %7B deps:%5B
+ 'angular','jquery'%5D%7D,%0A 'toastr' : %7B deps:%5B
'angular'%5D%7D,%0A
@@ -3825,32 +3825,77 @@
','angular'%5D %7D,%0A
+ 'app-css': %7B deps: %5B'toastr-css'%5D %7D,%0A
// 'text
|
de7a7d390f0981e5e44305560759e793ab827606 | fix condition | components/ui/map/map-thumbnail/helper.js | components/ui/map/map-thumbnail/helper.js | import 'isomorphic-fetch';
const BASEMAP_QUERY = 'SELECT the_geom_webmercator FROM gadm28_countries';
const BASEMAP_CARTOCSS = '#gadm28_countries { polygon-fill: #bbbbbb; polygon-opacity: 1; line-color: #FFFFFF; line-width: 0.5; line-opacity: 0.5; }';
export const getImageFromCarto = ({
width, height, zoom, lat, lng, layerConfig
}) => {
if (!layerConfig) throw Error('layerConfig param is required');
if (!layerConfig.body) throw Error('layerConfig does not have body param');
const { body, account } = layerConfig;
const format = 'png';
const layerTpl = { version: '1.3.0', stat_tag: 'API', layers: body.layers };
const params = `?stat_tag=API&config=${encodeURIComponent(JSON.stringify(layerTpl))}`;
const url = `https://${account}.carto.com/api/v1/map${params}`;
return fetch(url)
.then((response) => {
if (response.status >= 400) throw new Error(response.json());
return response.json();
})
.then((data) => {
const { layergroupid } = data;
return `https://${data.cdn_url.https}/${account}/api/v1/map/static/center/${layergroupid}/${zoom}/${lat}/${lng}/${width}/${height}.${format}`;
});
};
export const getImageFromMapService = ({ width, height, layerConfig }) => {
if (!layerConfig) throw Error('layerConfig param is required');
if (!layerConfig.body) throw Error('layerConfig does not have body param');
const { body } = layerConfig;
const { url } = body;
// BBOX for zoom 1, lat 20, long -20
const bbox = '-125.15625000000001,-55.7765730186677,85.78125,72.81607371878991';
const bboxSR = encodeURIComponent(JSON.stringify({ wkid: 4326 }));
const imageSR = encodeURIComponent(JSON.stringify({ wkid: 3857 }));
const format = 'png';
const result = `${url}/export?bbox=${bbox}&bboxSR=${bboxSR}&layers=&layerDefs=&size=${width}%2C${height}&imageSR=${imageSR}&format=${format}&transparent=true&dpi=&time=&layerTimeOptions=&dynamicLayers=&gdbVersion=&mapScale=&rotation=&f=image`;
return result;
};
export const getBasemapImage = ({
width, height, zoom, lat, lng, format, layerSpec
}) => {
const basemapSpec = {
account: 'wri-01',
body: {
maxzoom: 18,
minzoom: 3,
layers: [{
type: 'mapnik',
options: {
sql: BASEMAP_QUERY,
cartocss: BASEMAP_CARTOCSS,
cartocss_version: '2.3.0'
}
}]
}
};
const { body, account } = basemapSpec;
const layerTpl = { version: '1.3.0', stat_tag: 'API', layers: body.layers };
const params = `?stat_tag=API&config=${encodeURIComponent(JSON.stringify(layerTpl))}`;
const url = `https://${account}.carto.com/api/v1/map${params}`;
return fetch(url)
.then((response) => {
if (response.status >= 400) throw new Error('Bad response from server');
return response.json();
})
.then((data) => {
const { layergroupid } = data;
if (layerSpec.provider === 'gee' ||
layerSpec.provider === 'nexgddp' ||
layerSpec.provider === 'leaflet') {
return `https://${data.cdn_url.https}/${account}/api/v1/map/${layergroupid}/0/0/0.${format || 'png'}`;
}
return `https://${data.cdn_url.https}/${account}/api/v1/map/static/center/${layergroupid}/${zoom}/${lat}/${lng}/${width}/${height}.${format || 'png'}`;
});
};
export const getImageForGEE = ({ layerSpec }) => {
const { layerConfig } = layerSpec;
if (!layerConfig) throw Error('layerConfig param is required');
if (!layerConfig.body) throw Error('layerConfig does not have body param');
const tile = `${process.env.WRI_API_URL}/layer/${layerSpec.id}/tile/gee/0/0/0`;
return tile;
};
export const getImageForLeaflet = ({ layerSpec }) => {
const { layerConfig } = layerSpec;
if (!layerConfig) throw Error('layerConfig param is required');
if (!layerConfig.body) throw Error('layerConfig does not have body param');
if (layerConfig.type !== 'tileLayer') {
return null;
}
if (!layerConfig.url && !layerConfig.body && !layerConfig.body.url) {
return null;
}
const url = layerConfig.url || layerConfig.body.url;
const tile = url.replace('{z}', '0').replace('{x}', '0').replace('{y}', '0');
return tile;
};
export const getLayerImage = async ({
width, height, zoom, lat, lng, layerSpec
}) => {
if (!layerSpec) throw Error('No layerSpec specified.');
const { id, layerConfig, provider } = layerSpec;
let result;
switch (provider) {
case 'carto':
try {
result = await getImageFromCarto({
width, height, zoom, lat, lng, layerConfig
});
} catch (e) {
result = null;
}
break;
case 'cartodb':
try {
result = await getImageFromCarto({
width, height, zoom, lat, lng, layerConfig
});
} catch (e) {
result = null;
}
break;
case 'mapservice':
result = getImageFromMapService({ width, height, layerConfig });
break;
case 'featureservice':
result = getImageFromMapService({ width, height, layerConfig });
break;
case 'arcgis':
result = getImageFromMapService({ width, height, layerConfig });
break;
case 'gee':
result = getImageForGEE({ layerSpec });
break;
case 'leaflet':
result = getImageForLeaflet({ layerSpec });
break;
default:
result = null;
}
return result;
};
| JavaScript | 0.000001 | @@ -3945,20 +3945,20 @@
fig.url
-&& !
+%7C%7C (
layerCon
@@ -3991,16 +3991,17 @@
ody.url)
+)
%7B%0A r
|
79c24cc4ea87eabf72a0a3f684090ccbc95eeb64 | tweak colouring and function name | game.js | game.js | /*global ROT */
var Game = {
display: null,
player: null,
engine: null,
map: {},
init: function() {
this.display = new ROT.Display({spacing:1.1});
document.body.appendChild(this.display.getContainer());
this._generateMap();
var scheduler = new ROT.Scheduler.Simple();
scheduler.add(this.player, true);
this.engine = new ROT.Engine(scheduler);
this.engine.start();
},
_generateMap: function() {
var config = {
corridorLength:[1,3],
dugPercentage:0.5,
roomWidth:[3,9],
roomheight:[3,9],
};
var digger = new ROT.Map.Digger(ROT.DEFAULT_WIDTH, ROT.DEFAULT_HEIGHT, config);
var freeCells = [];
var digCallback = function(x, y, value) {
var key = x+","+y;
//value is 1 or zero depending if its a wall or not
if (value) {
this.map[key] = "#";
} else {
this.map[key] = ".";
freeCells.push(key);
}
//doors are just marked as walls at this point
};
var dugmap = digger.create(digCallback.bind(this));
this._createPlaer(freeCells);
},
_createPlayer: function(freeCells) {
var index = Math.floor(ROT.RNG.getUniform() * freeCells.length);
var key = freeCells.splice(index, 1)[0];
var parts = key.split(",");
var x = parseInt(parts[0]);
var y = parseInt(parts[1]);
this.player = new Player(x, y);
},
_drawWholeMap: function() {
for (var key in this.map) {
var parts = key.split(",");
var x = parseInt(parts[0]);
var y = parseInt(parts[1]);
this.display.draw(x, y, this.map[key], "#ff0");
}
this.display.draw(this.player._x, this.player._y, "@", "#ff0");
}
};
var Player = function(x, y) {
this._x = x;
this._y = y;
};
Player.prototype.act = function() {
Game._drawWholeMap();
Game.engine.lock();
window.addEventListener("keydown", this);
};
Player.prototype.handleEvent = function(e) {
var keyMap = {};
//numpad directions
keyMap[ROT.VK_UP] = 0;
keyMap[ROT.VK_PAGE_UP] = 1;
keyMap[ROT.VK_RIGHT] = 2;
keyMap[ROT.VK_PAGE_DOWN] = 3;
keyMap[ROT.VK_DOWN] = 4;
keyMap[ROT.VK_END] = 5;
keyMap[ROT.VK_LEFT] = 6;
keyMap[ROT.VK_HOME] = 7;
keyMap[ROT.VK_NUMPAD8] = 0;
keyMap[ROT.VK_NUMPAD9] = 1;
keyMap[ROT.VK_NUMPAD6] = 2;
keyMap[ROT.VK_NUMPAD3] = 3;
keyMap[ROT.VK_NUMPAD2] = 4;
keyMap[ROT.VK_NUMPAD1] = 5;
keyMap[ROT.VK_NUMPAD4] = 6;
keyMap[ROT.VK_NUMPAD7] = 7;
var code = e.keyCode;
/* one of numpad directions? */
if (!(code in keyMap)) {
return;
}
/* is there a free space? */
var dir = ROT.DIRS[8][keyMap[code]];
var newX = this._x + dir[0];
var newY = this._y + dir[1];
var newKey = newX + "," + newY;
if (!(newKey in Game.map) || (Game.map[newKey] === "#")) {
return;
}
this._x = newX;
this._y = newY;
window.removeEventListener("keydown", this);
Game.engine.unlock();
};
| JavaScript | 0 | @@ -1282,16 +1282,17 @@
reatePla
+y
er(freeC
@@ -1872,25 +1872,25 @@
p%5Bkey%5D, %22#ff
-0
+f
%22);%0A
@@ -2514,16 +2514,21 @@
E%5D = 7;%0A
+ %0A
keyM
|
973aad5c96e5731ad6891f0d507b630d76c63c1b | Fix doesPadExist check | node/db/PadManager.js | node/db/PadManager.js | /**
* The Pad Manager is a Factory for pad Objects
*/
/*
* 2011 Peter 'Pita' Martischka (Primary Technology Ltd)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var ERR = require("async-stacktrace");
var customError = require("../utils/customError");
var Pad = require("../db/Pad").Pad;
var db = require("./DB").db;
/**
* An Object containing all known Pads. Provides "get" and "set" functions,
* which should be used instead of indexing with brackets. These prepend a
* colon to the key, to avoid conflicting with built-in Object methods or with
* these functions themselves.
*
* If this is needed in other places, it would be wise to make this a prototype
* that's defined somewhere more sensible.
*/
var globalPads = {
get: function (name) { return this[':'+name]; },
set: function (name, value) { this[':'+name] = value; },
remove: function (name) { delete this[':'+name]; }
};
/**
* An array of padId transformations. These represent changes in pad name policy over
* time, and allow us to "play back" these changes so legacy padIds can be found.
*/
var padIdTransforms = [
[/\s+/g, '_'],
[/:+/g, '_']
];
/**
* Returns a Pad Object with the callback
* @param id A String with the id of the pad
* @param {Function} callback
*/
exports.getPad = function(id, text, callback)
{
//check if this is a valid padId
if(!exports.isValidPadId(id))
{
callback(new customError(id + " is not a valid padId","apierror"));
return;
}
//make text an optional parameter
if(typeof text == "function")
{
callback = text;
text = null;
}
//check if this is a valid text
if(text != null)
{
//check if text is a string
if(typeof text != "string")
{
callback(new customError("text is not a string","apierror"));
return;
}
//check if text is less than 100k chars
if(text.length > 100000)
{
callback(new customError("text must be less than 100k chars","apierror"));
return;
}
}
var pad = globalPads.get(id);
//return pad if its already loaded
if(pad != null)
{
callback(null, pad);
}
//try to load pad
else
{
pad = new Pad(id);
//initalize the pad
pad.init(text, function(err)
{
if(ERR(err, callback)) return;
globalPads.set(id, pad);
callback(null, pad);
});
}
}
//checks if a pad exists
exports.doesPadExists = function(padId, callback)
{
db.get("pad:"+padId, function(err, value)
{
if(ERR(err, callback)) return;
callback(null, value != null);
});
}
//returns a sanitized padId, respecting legacy pad id formats
exports.sanitizePadId = function(padId, callback) {
var transform_index = arguments[2] || 0;
//we're out of possible transformations, so just return it
if(transform_index >= padIdTransforms.length)
{
callback(padId);
}
//check if padId exists
else
{
exports.doesPadExists(padId, function(junk, exists)
{
if(exists)
{
callback(padId);
}
else
{
//get the next transformation *that's different*
var transformedPadId = padId;
while(transformedPadId == padId && transform_index < padIdTransforms.length)
{
transformedPadId = padId.replace(padIdTransforms[transform_index][0], padIdTransforms[transform_index][1]);
transform_index += 1;
}
//check the next transform
exports.sanitizePadId(transformedPadId, callback, transform_index);
}
});
}
}
exports.isValidPadId = function(padId)
{
return /^(g.[a-zA-Z0-9]{16}\$)?[^$]{1,50}$/.test(padId);
}
//removes a pad from the array
exports.unloadPad = function(padId)
{
if(globalPads.get(padId))
globalPads.remove(padId);
}
| JavaScript | 0.000001 | @@ -3072,16 +3072,31 @@
!= null
+ && value.atext
); %0A %7D
|
3c2cdaf31c5e205a91dd34d7e9c8940821ae002d | remove commented-out lines | api/models/Community.js | api/models/Community.js | module.exports = bookshelf.Model.extend({
tableName: 'community',
creator: function () {
return this.belongsTo(User, 'created_by_id')
},
inactiveUsers: function () {
return this.belongsToMany(User, 'users_community', 'community_id', 'user_id')
.query({where: {'users_community.active': false}})
},
invitations: function () {
return this.hasMany(Invitation)
},
leader: function () {
return this.belongsTo(User, 'leader_id')
},
memberships: function () {
return this.hasMany(Membership).query({where: {'users_community.active': true}})
},
moderators: function () {
return this.belongsToMany(User, 'users_community', 'community_id', 'user_id')
.query({where: {role: Membership.MODERATOR_ROLE}})
},
network: function () {
return this.belongsTo(Network)
},
users: function () {
return this.belongsToMany(User).through(Membership)
.query({where: {'users.active': true}}).withPivot('role')
// return this.belongsToMany(User, 'users_community', 'community_id', 'user_id')
// .query({where: {'users_community.active': true}}).withPivot('role')
},
posts: function () {
return this.belongsToMany(Post).through(PostMembership)
.query({where: {'post.active': true}})
},
comments: function () {
// FIXME get this to use the model relation API
// instead of the Collection API so that the use
// of fetch vs. fetchAll isn't confusing.
// as it is now, it uses "fetchAll" when all the
// other relations use "fetch"
var communityId = this.id
return Comment.query(function (qb) {
qb.where({
'post_community.community_id': communityId,
'comment.active': true
}).leftJoin('post_community', () => this.on('post_community.post_id', 'comment.post_id'))
})
},
createStarterPosts: function (trx) {
var self = this
var now = new Date()
var timeShift = {
chat: 0,
intention: 1,
offer: 2,
request: 3
}
return Community.find('starter-posts', {withRelated: ['posts', 'posts.followers']})
.tap(c => {
if (!c) throw new Error('Starter posts community not found')
})
.then(c => c.relations.posts.models)
.then(posts => Promise.map(posts, post => {
if (post.get('type') === 'welcome') return
var newPost = post.copy()
var time = new Date(now - timeShift[newPost.get('type')] * 1000)
return newPost.save({created_at: time, updated_at: time}, {transacting: trx})
.then(() => Promise.all(_.flatten([
self.posts().attach(newPost, {transacting: trx}),
post.relations.followers.map(u =>
Follow.create(u.id, newPost.id, {transacting: trx}))
])))
}))
}
}, {
find: function (id_or_slug, options) {
if (isNaN(Number(id_or_slug))) {
return Community.where({slug: id_or_slug}).fetch(options)
}
return Community.where({id: id_or_slug}).fetch(options)
},
canInvite: function (userId, communityId) {
return Community.find(communityId).then(function (community) {
if (community.get('settings').all_can_invite) return true
return Membership.hasModeratorRole(userId, communityId)
})
},
copyAssets: function (opts) {
return Community.find(opts.communityId).then(c => Promise.join(
AssetManagement.copyAsset(c, 'community', 'avatar_url'),
AssetManagement.copyAsset(c, 'community', 'banner_url')
))
},
notifyAboutCreate: function (opts) {
return Community.find(opts.communityId, {withRelated: ['creator']}).then(c => {
var creator = c.relations.creator
var recipient = process.env.ASANA_NEW_COMMUNITIES_EMAIL
Email.sendRawEmail(recipient, {
subject: c.get('name'),
body: format(
'%s<br/>created by %s<br/>%s<br/>%s',
Frontend.Route.community(c),
creator.get('name'),
creator.get('email'),
Frontend.Route.profile(creator))
}, {
sender: {
name: 'Hylobot',
address: 'edward@hylo.com'
}
})
})
},
inNetworkWithUser: function (communityId, userId) {
return Community.find(communityId)
.then(community => community && community.get('network_id'))
.then(networkId => networkId && Network.containsUser(networkId, userId))
}
})
| JavaScript | 0 | @@ -970,170 +970,8 @@
e')%0A
- // return this.belongsToMany(User, 'users_community', 'community_id', 'user_id')%0A // .query(%7Bwhere: %7B'users_community.active': true%7D%7D).withPivot('role')%0A
%7D,
|
fc511ba796ac4b7710aeae4704df568c0408a89f | Clear Timeout before leaving implement route | app/assets/javascripts/editor/submissions.js | app/assets/javascripts/editor/submissions.js | CodeOceanEditorSubmissions = {
FILENAME_URL_PLACEHOLDER: '{filename}',
AUTOSAVE_INTERVAL: 15 * 1000,
autosaveTimer: null,
autosaveLabel: "#autosave-label span",
/**
* Submission-Creation
*/
createSubmission: function (initiator, filter, callback) {
this.showSpinner(initiator);
var url = $(initiator).data('url') || $('#editor').data('submissions-url');
if (url === undefined) {
const data = {
initiator: initiator,
filter: filter,
}
Sentry.captureException(JSON.stringify(data));
return;
}
var jqxhr = this.ajax({
data: {
submission: {
cause: $(initiator).data('cause') || $(initiator).prop('id'),
exercise_id: $('#editor').data('exercise-id'),
files_attributes: (filter || _.identity)(this.collectFiles())
},
annotations_arr: []
},
dataType: 'json',
method: 'POST',
url: url + '.json'
});
jqxhr.always(this.hideSpinner.bind(this));
jqxhr.done(this.createSubmissionCallback.bind(this));
if(callback != null){
jqxhr.done(callback.bind(this));
}
jqxhr.fail(this.ajaxError.bind(this));
},
collectFiles: function() {
var editable_editors = _.filter(this.editors, function(editor) {
return !editor.getReadOnly();
});
return _.map(editable_editors, function(editor) {
return {
content: editor.getValue(),
file_id: $(editor.container).data('file-id')
};
});
},
createSubmissionCallback: function(data){
// set all frames context types to submission
$('.frame').each(function(index, element) {
$(element).data('context-type', 'Submission');
});
// update the ids of the editors and reload the annotations
for (var i = 0; i < this.editors.length; i++) {
// set the data attribute to submission
//$(editors[i].container).data('context-type', 'Submission');
var file_id_old = $(this.editors[i].container).data('file-id');
// file_id_old is always set. Either it is a reference to a teacher supplied given file, or it is the actual id of a new user created file.
// This is the case, since it is set via a call to ancestor_id on the model, which returns either file_id if set, or id if it is not set.
// therefore the else part is not needed any longer...
// if we have an file_id set (the file is a copy of a teacher supplied given file) and the new file-ids are present in the response
if (file_id_old != null && data.files){
// if we find file_id_old (this is the reference to the base file) in the submission, this is the match
for(var j = 0; j< data.files.length; j++){
if(data.files[j].file_id == file_id_old){
//$(editors[i].container).data('id') = data.files[j].id;
$(this.editors[i].container).data('id', data.files[j].id );
}
}
}
}
// toggle button states (it might be the case that the request for comments button has to be enabled
this.toggleButtonStates();
this.updateSaveStateLabel();
},
/**
* File-Management
*/
destroyFile: function() {
this.createSubmission($('#destroy-file'), function(files) {
return _.reject(files, function(file) {
return file.file_id === CodeOceanEditor.active_file.id;
});
}, window.CodeOcean.refresh);
},
downloadCode: function(event) {
event.preventDefault();
this.createSubmission('#download', null,function(response) {
var url = response.download_url;
// to download just a single file, use the following url
//var url = response.download_file_url.replace(FILENAME_URL_PLACEHOLDER, active_file.filename);
window.location = url;
});
},
resetCode: function(onlyActiveFile = false) {
this.showSpinner(this);
this.ajax({
method: 'GET',
url: $('#start-over').data('url')
}).done(function(response) {
this.hideSpinner();
_.each(this.editors, function(editor) {
var file_id = $(editor.container).data('file-id');
var file = _.find(response.files, function(file) {
return file.id === file_id;
});
if(file && !onlyActiveFile || file && file.id === CodeOceanEditor.active_file.id){
editor.setValue(file.content);
}
}.bind(this));
}.bind(this));
},
renderCode: function(event) {
event.preventDefault();
if ($('#render').is(':visible')) {
this.createSubmission('#render', null, function (response) {
var url = response.render_url.replace(this.FILENAME_URL_PLACEHOLDER, CodeOceanEditor.active_file.filename.replace(/#$/,'')); // remove # if it is the last character, this is not part of the filename and just an anchor
var pop_up_window = window.open(url);
if (pop_up_window) {
pop_up_window.onerror = function (message) {
this.clearOutput();
this.printOutput({
stderr: message
}, true, 0);
this.sendError(message, response.id);
this.showOutputBar();
};
}
});
}
},
/**
* Execution-Logic
*/
runCode: function(event) {
event.preventDefault();
this.stopCode(event);
if ($('#run').is(':visible')) {
this.createSubmission('#run', null, this.runSubmission.bind(this));
}
},
runSubmission: function (submission) {
//Run part starts here
$('#stop').data('url', submission.stop_url);
this.running = true;
this.showSpinner($('#run'));
$('#score_div').addClass('d-none');
this.toggleButtonStates();
var url = submission.run_url.replace(this.FILENAME_URL_PLACEHOLDER, CodeOceanEditor.active_file.filename.replace(/#$/,'')); // remove # if it is the last character, this is not part of the filename and just an anchor
this.initializeSocketForRunning(url);
},
saveCode: function(event) {
event.preventDefault();
this.createSubmission('#save', null, function() {
$.flash.success({
text: $('#save').data('message-success')
});
});
},
testCode: function(event) {
event.preventDefault();
if ($('#test').is(':visible')) {
this.createSubmission('#test', null, function(response) {
this.showSpinner($('#test'));
$('#score_div').addClass('d-none');
var url = response.test_url.replace(this.FILENAME_URL_PLACEHOLDER, CodeOceanEditor.active_file.filename.replace(/#$/,'')); // remove # if it is the last character, this is not part of the filename and just an anchor
this.initializeSocketForTesting(url);
}.bind(this));
}
},
submitCode: function() {
this.createSubmission($('#submit'), null, function (response) {
if (response.redirect) {
Turbolinks.clearCache();
Turbolinks.visit(response.redirect);
}
})
},
/**
* Autosave-Logic
*/
resetSaveTimer: function () {
clearTimeout(this.autosaveTimer);
this.autosaveTimer = setTimeout(this.autosave.bind(this), this.AUTOSAVE_INTERVAL);
},
unloadAutoSave: function() {
if(this.autosaveTimer != null){
this.autosave();
clearTimeout(this.autosaveTimer);
}
},
updateSaveStateLabel: function() {
var date = new Date();
var autosaveLabel = $(this.autosaveLabel);
autosaveLabel.parent().css("visibility", "visible");
autosaveLabel.text(date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds());
autosaveLabel.text(date.toLocaleTimeString());
},
autosave: function () {
this.autosaveTimer = null;
this.createSubmission($('#autosave'), null);
}
};
| JavaScript | 0 | @@ -6835,24 +6835,66 @@
earCache();%0A
+ clearTimeout(this.autosaveTimer);%0A
Turb
|
43c01fcab8c3bfdd9255cf238590be1ae3249586 | make js simpler so that string is standard | javascript/api.js | javascript/api.js | $(document).ready(function () {
$('button').click(function() {
var url = 'https://api.target.com/items/v3/055-02-3741';
var data = {
id_type : 'dpci',
store_id : '530',
fields : 'ids,descriptions,locations,pricing,images',
// fields : ['ids','descriptions','locations','pricing','images'],
mode : 'online',
key : '1Kfdqvy6wHmvJ4LDyAVOl7saCBoKHcSb'
};
$.getJSON(url, data, function (response) {
var callback = function(response) {
var responseHTML = '<ul class="tbu">';
responseHTML += '<li class="detail">' + product_composite_response.items.online_description.value + '</li>';
responseHTML += '<li class="detail">' + product_composite_response.items.online_price.current_price + '</li>';
responseHTML += '<li class="detail">' + product_composite_response.items.online_price.original_price + '</li>';
responseHTML += '<li class="detail">' + product_composite_response.items.image.internal_primary_image_url + '</li>';
};
}); // end getJSON
}); // end button.click
}); // end ready | JavaScript | 0.998948 | @@ -54,24 +54,59 @@
nction() %7B%0A%0A
+ var product_id = %22055-02-3741%22%0A
var url
@@ -144,25 +144,161 @@
/v3/
-055-02-3741
+' + product_id + '?id_type=dpci&store_id=530&fields=ids,descriptions,locations,pricing,images&mode=online&key=1Kfdqvy6wHmvJ4LDyAVOl7saCBoKHcSb
';%0A
+%0A%0A
+ //
var
@@ -311,18 +311,21 @@
= %7B%0A
+//
+
id_type
@@ -337,16 +337,19 @@
ci',%0A
+ //
store
@@ -364,16 +364,19 @@
30',%0A
+ //
field
@@ -427,16 +427,19 @@
es',%0A
+ //
// fi
@@ -503,16 +503,19 @@
s'%5D,%0A
+ //
mode
@@ -529,16 +529,19 @@
ne',%0A
+ //
key :
@@ -579,16 +579,19 @@
cSb'%0A
+ //
%7D;%0A%0A
@@ -609,15 +609,8 @@
url,
- data,
func
|
e3b51aca1c64e30ca8990bc1fd171505adbb83ac | diff overlay didn't always show the proper content diff | trac/htdocs/js/blame.js | trac/htdocs/js/blame.js |
(function($){
window.enableBlame = function(url, reponame, original_path) {
var message = null;
var message_rev = null;
/* for each blame cell... */
var path = null;
$("table.code th.blame").each(function() {
// determine path from the changeset link
var a = $(this).find("a");
var href = a.attr("href");
if ( ! (href || path) )
return; // was "Rev" column title
if ( href ) {
a.removeAttr("href");
href = href.slice(href.indexOf("changeset/") + 10);
if (reponame)
href = href.substr(reponame.length);
var sep = href.indexOf("/");
if ( sep > 0 )
path = href.slice(sep+1);
else
path = original_path;
}
// determine rev from th class, which is of the form "blame r123"
var rev = $(this).attr("class").split(" ")[1];
if (!rev)
return;
$(this).css("cursor", "pointer").click(function() {
var row = this.parentNode;
var message_is_visible = message && message.css("display") == "block";
var highlight_rev = null;
var annotate_path = path;
function show() {
/* Display commit message for the selected revision */
var message_w = message.get(0).offsetWidth;
// limit message panel width to 3/5 of the row width
var row_w = row.offsetWidth;
var max_w = (3.0 * row_w / 5.0);
if (!message_w || message_w > max_w) {
message_w = max_w;
var borderw = (3+8)*2; // borderwidth + padding on both sides
message.css({width: message_w - borderw + "px"});
}
var row_offset = $(row).offset();
var left = row_offset.left + row.offsetWidth - message_w;
message.css({display: "block", top: row_offset.top+"px", left: left-2+"px"});
}
function hide() {
/* Hide commit message */
message.css({display: "none"});
/* Remove highlighting for lines of the current revision */
$("table.code th."+message_rev).each(function() {
$(this.parentNode).removeClass("hilite")
});
}
if (message_rev != rev) { // fetch a new revision
if (message_is_visible) {
hide();
}
message_rev = rev;
highlight_rev = message_rev;
$.get(url + [rev.substr(1), reponame].join("/"),
{annotate: annotate_path}, function(data) {
// remove former message panel if any
if (message)
message.remove();
// create new message panel
message = $('<div class="message">').css("position", "absolute")
.append($('<div class="inlinebuttons">')
.append($('<input value="Close" type="button">').click(hide)))
.append($('<div>').html(data || "<strong>(no changeset information)</strong>"))
.appendTo("body");
// workaround non-clickable "Close" issue in Firefox
if ($.browser.mozilla || $.browser.safari)
message.find("div.inlinebuttons").next().css("clear", "right");
show();
});
} else if (message_is_visible) {
hide();
} else {
show();
highlight_rev = message_rev;
}
/* Highlight all lines of the current revision */
$("table.code th."+highlight_rev).each(function() {
$(this.parentNode).addClass("hilite")
});
});
});
}
})(jQuery);
| JavaScript | 0.999987 | @@ -544,108 +544,173 @@
-if (reponame)%0A href = href.substr(reponame.length);%0A var sep = href.indexOf(%22/%22
+var sep = href.indexOf(%22/%22);%0A if ( sep %3E 0 ) %7B%0A path = href.slice(sep+1);%0A if (reponame)%0A path = path.substr(reponame.length
);%0A
+
@@ -721,19 +721,17 @@
if (
- sep %3E 0 )%0A
+!path)%0A
@@ -743,33 +743,29 @@
path =
-href.slice(sep+1)
+original_path
;%0A
@@ -765,21 +765,25 @@
%0A
+ %7D
else
+ %7B
%0A
@@ -803,24 +803,34 @@
ginal_path;%0A
+ %7D%0A
%7D%0A%0A
@@ -1220,20 +1220,31 @@
_path =
+decodeURI(
path
+)
;%0A %0A
|
768f4bf499d00c6a801b018b6a1c656c5800076c | Print out uncaught exceptions. Node stops doing this when you add an uncaught exception handler. | nodejs/lib/hoptoad.js | nodejs/lib/hoptoad.js | var Hoptoad = require('hoptoad-notifier').Hoptoad
, env = require('../environment')
, shouldReport = env.hoptoad && env.hoptoad.reportErrors;
if(shouldReport)
Hoptoad.key = env.hoptoad.apiKey;
process.addListener('uncaughtException', function(err) {
if(shouldReport)
Hoptoad.notify(err, function(){});
});
Hoptoad.expressErrorNotifier = function(err,req,res,next){
if(shouldReport)
Hoptoad.notify(err, function(){});
next(err);
}
Hoptoad.notifyCallback = function(err){
if(shouldReport && err)
Hoptoad.notify(err, function(){});
}
module.exports = Hoptoad;
| JavaScript | 0 | @@ -309,16 +309,87 @@
n()%7B%7D);%0A
+%09console.error(%22~~~ Error ~~~ %22 + Date())%0A%09console.error(err.stack);%0A
%7D);%0A%0AHop
|
5b1b46a73abc95f9ec8fd10fda2ab9b6c418bd07 | Delete unnecessary lines in the code | src/js/index.js | src/js/index.js | import lightgallery from 'lightgallery.js';
import lgThumbnail from 'lg-thumbnail.js';
import lgAutoplay from 'lg-autoplay.js';
import lgVideo from 'lg-video.js';
import lgFullscreen from 'lg-fullscreen.js';
import lgPager from 'lg-pager.js';
import lgZoom from 'lg-zoom.js';
import lgHash from 'lg-hash.js';
import hljs from 'highlight.js';
import fontawesomeCollection from './_fontawesome-collection.js'
import { locale } from './_locale-ru.js'
document.addEventListener('DOMContentLoaded', () => {
initNavbar(100);
initSearchPanel();
initLightGallery(200, 10);
initSyntaxHighlighting();
});
function initNavbar(scrollTopNavbarHide) {
const navbar = document.getElementById('h-navbar');
if (!!navbar) {
const root = document.documentElement;
const navbarBurger = document.getElementById('h-burger');
const navbarBottom = document.getElementById('h-navbar-bottom');
const logo = document.getElementById('h-logo');
let lastY = 0;
let currentY = 0;
let hasClassHide = logo.classList.contains('h-is-hidden');
navbarBottom.onmouseover = function(event) {
navbar.classList.remove('h-is-hidden');
hasClassHide = false;
};
navbarBurger.addEventListener('click', () => {
root.classList.toggle('h-is-clipped-touch');
const target = document.getElementById(navbarBurger.dataset.target);
navbarBurger.classList.toggle('is-active');
target.classList.toggle('is-active');
});
window.addEventListener('scroll', function() {
lastY = currentY;
currentY = window.scrollY;
if ((currentY > scrollTopNavbarHide) && (currentY > lastY) && (!hasClassHide)) {
navbar.classList.add('h-is-hidden');
hasClassHide = true;
}
if ((currentY < lastY) && (hasClassHide)) {
navbar.classList.remove('h-is-hidden');
hasClassHide = false;
}
});
}
}
function initSearchPanel() {
const searchForm = document.getElementById('h-search-form');
if (!!searchForm) {
const navbarMenu = document.getElementById('h-navbar-menu');
const searchButtonOpen = document.getElementById('h-search-button-open');
const searchButtonClose = document.getElementById('h-search-button-close');
const searchInput = document.getElementById('h-search-input');
let timeOfAnimation = 500;
searchInput.placeholder = translate('Search…');
searchButtonOpen.addEventListener('click', () => {
searchForm.classList.remove("h-is-hidden");
navbarMenu.classList.add('has-visible-search-from');
focusAfterAnimation(searchInput, timeOfAnimation);
showOrHideSearchButtonClose();
});
searchButtonClose.addEventListener('click', () => {
if (searchInput.value.length >= 1) {
searchInput.value = "";
showOrHideSearchButtonClose();
} else {
searchForm.classList.add("h-is-hidden");
navbarMenu.classList.remove('has-visible-search-from');
searchInput.blur();
}
});
searchInput.addEventListener('input', () => {
showOrHideSearchButtonClose();
});
}
}
function initLightGallery(rowHeight, margins) {
var lightboxes = document.getElementsByClassName('h-lightbox');
Array.from(lightboxes).forEach(el => {
lightGallery(el, {
hash: true,
share: false
});
});
var galleries = document.getElementsByClassName('h-gallery');
Array.from(galleries).forEach(el => {
lightGallery(el, {
hash: true,
share: false,
selector: '.item'
});
});
/*jQuery('.js-gallery').justifiedGallery({
rowHeight: rowHeight,
margins: margins,
border: 0
});*/
}
function initSyntaxHighlighting() {
hljs.initHighlightingOnLoad();
/*jQuery('pre code').each(function(i, block) {
hljs.highlightBlock(block);
});*/
}
function focusAfterAnimation(elem, timeOfAnimation) {
window.setTimeout(function() {
elem.focus();
}, timeOfAnimation);
}
function showOrHideSearchButtonClose() {
const searchInput = document.getElementById('h-search-input');
const searchButtonClose = document.getElementById('h-search-button-close');
if (searchInput.value.length >= 1) {
searchButtonClose.classList.remove('is-hidden-touch');
} else {
searchButtonClose.classList.add('is-hidden-touch');
}
}
function translate(string) {
let lang = document.documentElement.lang;
return lang == 'en' ? string : locale[string];
} | JavaScript | 0.000108 | @@ -3724,99 +3724,8 @@
();%0A
- /*jQuery('pre code').each(function(i, block) %7B%0A hljs.highlightBlock(block);%0A %7D);*/%0A
%7D%0A%0Af
|
62515fc2b87a05647f97e6e0e28f2f1864b4678c | fix add-on incompatiblity hiding (bug 673979) | media/js/impala/addon_details.js | media/js/impala/addon_details.js | $(function () {
if ($('body').hasClass('listing')) {
$('.performance-note .popup').each(function(i,p) {
var $p = $(this),
$a = $p.siblings('a').first();
$p.popup($a, {width: 300, pointTo: $a});
});
$('.item.addon').each(function(i,p){
var $this = $(this);
if ($this.find('.concealed').length) {
$this.addClass('incompatible');
}
});
$(document.body).bind('newStatic', function() {
$('.install-note:visible').closest('.item').addClass('static');
}).bind('closeStatic', function() {
$('.item.static').removeClass('static');
});
}
if (!$("body").hasClass('addon-details')) return;
$(".previews").zCarousel({
btnNext: ".previews .next",
btnPrev: ".previews .prev",
itemsPerPage: 3
});
(function() {
var $document = $(document),
$lightbox = $("#lightbox"),
$content = $("#lightbox .content"),
$caption = $("#lightbox .caption span"),
current, $strip,
lbImage = template('<img id="preview{0}" src="{1}">');
if (!$lightbox.length) return;
function showLightbox() {
$lightbox.show();
showImage(this);
$(window).bind('keydown.lightboxDismiss', function(e) {
switch(e.which) {
case 27:
hideLightbox();
break;
case 37:
showPrev();
break;
case 39:
showNext();
break;
}
});
//I want to ensure the lightbox is painted before fading it in.
setTimeout(function () {
$lightbox.addClass("show");
},0);
}
function hideLightbox() {
$lightbox.removeClass("show");
// We can't trust transitionend to fire in all cases.
setTimeout(function() {
$lightbox.hide();
}, 500);
$(window).unbind('keydown.lightboxDismiss');
}
function showImage(a) {
var $a = $(a),
$oldimg = $lightbox.find("img");
current = $a.parent().index();
$strip = $a.closest("ul").find("li");
var $img = $("#preview"+current);
if ($img.length) {
$oldimg.css("opacity", 0);
$img.css({
"opacity": 1,
'margin-top': (525-$img.height())/2+'px',
'margin-left': (700-$img.width())/2+'px'
});
} else {
$img = $(lbImage([current, $a.attr("href")]));
$content.append($img);
$img.load(function(e) {
$oldimg.css("opacity", 0);
$img.css({
"opacity": 1,
'margin-top': (525-$img.height())/2+'px',
'margin-left': (700-$img.width())/2+'px'
});
for (var i=0; i<$strip.length; i++) {
if (i != current) {
var $p = $strip.eq(i).find("a");
$content.append(lbImage([i, $p.attr("href")]));
}
}
});
}
$caption.text($a.attr("title"));
$lightbox.find(".control").removeClass("disabled");
if (current < 1) {
$lightbox.find(".control.prev").addClass("disabled");
}
if (current == $strip.length-1){
$lightbox.find(".control.next").addClass("disabled");
}
}
function showNext() {
if (current < $strip.length-1) {
showImage($strip.eq(current+1).find("a"));
$(this).blur();
}
}
function showPrev() {
if (current > 0) {
showImage($strip.eq(current-1).find("a"));
$(this).blur();
}
}
$("#lightbox .next").click(_pd(showNext));
$("#lightbox .prev").click(_pd(showPrev));
$(".previews ul a").click(_pd(showLightbox));
$('#lightbox').click(_pd(function(e) {
if ($(e.target).is('.close, #lightbox')) {
hideLightbox();
}
}));
})();
if ($('#more-webpage').exists()) {
var $moreEl = $('#more-webpage');
url = $moreEl.attr('data-more-url');
$.get(url, function(resp) {
var $newContent = $(resp);
$moreEl.replaceWith($newContent);
$newContent.find('.listing-grid h3').truncate( {dir: 'h'} );
$newContent.find('.install').installButton();
$newContent.find('.listing-grid').each(listing_grid);
$('#reviews-link').addClass('scrollto').attr('href', '#reviews');
});
}
if ($('#review-add-box').exists())
$('#review-add-box').modal('#add-review', { delegate: '#page', width: '650px' });
if ($('#privacy-policy').exists())
$('#privacy-policy').modal('.privacy-policy', { width: '500px' });
// Show add-on ID when icon is clicked
if ($("#addon[data-id], #persona[data-id]").exists()) {
$("#addon .icon").click(function() {
window.location.hash = "id=" + $("#addon, #persona").attr("data-id");
});
}
$('#abuse-modal').modal('#report-abuse', {delegate: '#page'});
});
| JavaScript | 0 | @@ -372,24 +372,56 @@
led').length
+ == $this.find('.button').length
) %7B%0A
|
e0860e4491a2519493426cb1cfdbcca8071467e9 | Reimplement early exit for JSON parse errors. | validators/json/load.js | validators/json/load.js | const utils = require('../../utils')
const load = (files, jsonFiles, jsonContentsDict, annexed, dir) => {
let issues = []
// Read JSON file contents and parse for issues
const readJsonFile = (file, annexed, dir) =>
utils.files
.readFile(file, annexed, dir)
.then(contents => utils.json.parse(file, contents))
.then(({ issues: parseIssues, parsed }) => {
// Append any parse issues to returned issues
Array.prototype.push.apply(issues, parseIssues)
// Abort further tests if an error is found
if (
parseIssues &&
!parseIssues.some(issue => issue.severity === 'error')
) {
jsonContentsDict[file.relativePath] = parsed
jsonFiles.push(file)
}
})
// Start concurrent read/parses
const fileReads = files.map(file =>
utils.limit(() => readJsonFile(file, annexed, dir)),
)
// After all reads/parses complete, return any found issues
return Promise.all(fileReads).then(() => issues)
}
module.exports = load
| JavaScript | 0 | @@ -31,16 +31,137 @@
tils')%0A%0A
+class JSONParseError extends Error %7B%0A constructor(message) %7B%0A super(message)%0A this.name = 'JSONParseError'%0A %7D%0A%7D%0A%0A
const lo
@@ -713,9 +713,8 @@
-!
pars
@@ -773,24 +773,98 @@
) %7B%0A
+ throw new JSONParseError('Aborted due to parse error')%0A %7D%0A%0A
json
@@ -908,26 +908,24 @@
sed%0A
-
jsonFiles.pu
@@ -933,26 +933,16 @@
h(file)%0A
- %7D%0A
%7D)
@@ -1170,16 +1170,21 @@
leReads)
+%0A
.then(()
@@ -1195,16 +1195,176 @@
issues)%0A
+ .catch(err =%3E %7B%0A // Handle early exit%0A if (err instanceof JSONParseError) %7B%0A return issues%0A %7D else %7B%0A throw err%0A %7D%0A %7D)%0A
%7D%0A%0Amodul
|
c0907163a93af468d79ab63100dd3ec2e2a28655 | Make sure the ''Close'' button on the changeset panel in the annotate view works for some versions of Safari and Chrome. | trac/htdocs/js/blame.js | trac/htdocs/js/blame.js |
(function($){
window.enableBlame = function(url, original_path) {
var message = null;
var message_rev = null;
/* for each blame cell containing a changeset link... */
var rev_paths = {};
$("table.code th.blame a").each(function() {
href = $(this).attr("href");
$(this).removeAttr("href");
rev_href = href.substr(href.indexOf("changeset/") + 10);
elts = rev_href.split("/");
var path = elts.slice(1).join("/");
if (path != original_path)
rev_paths["r"+elts[0]] = path;
});
/* for each blame cell... */
$("table.code th.blame").each(function() {
var rev = $(this).attr("class").split(" ")[1]; // "blame r123"
var path = rev_paths[rev] || original_path; // only found if != orig
if (!rev)
return;
$(this).css("cursor", "pointer").click(function() {
var row = this.parentNode;
var message_is_visible = message && message.css("display") == "block";
var highlight_rev = null;
function show() {
/* Display commit message for the selected revision */
var message_w = message.get(0).offsetWidth;
// limit message panel width to 3/5 of the row width
var row_w = row.offsetWidth;
var max_w = (3.0 * row_w / 5.0);
if (!message_w || message_w > max_w) {
message_w = max_w;
var borderw = (3+8)*2; // borderwidth + padding on both sides
message.css({width: message_w - borderw + "px"});
}
var row_offset = $(row).offset();
var left = row_offset.left + row.offsetWidth - message_w;
message.css({display: "block", top: row_offset.top+"px", left: left-2+"px"});
}
function hide() {
/* Hide commit message */
message.css({display: "none"});
/* Remove highlighting for lines of the current revision */
$("table.code th."+message_rev).each(function() {
$(this.parentNode).removeClass("hilite")
});
}
if (message_rev != rev) { // fetch a new revision
if (message_is_visible) {
hide();
}
message_rev = rev;
highlight_rev = message_rev;
$.get(url + rev.substr(1), {annotate: path}, function(data) {
// remove former message panel if any
if (message)
message.remove();
// create new message panel
message = $('<div class="message">').css("position", "absolute")
.append($('<div class="inlinebuttons">')
.append($('<input value="Close" type="button">').click(hide)))
.append($('<div>').html(data || "<strong>(no changeset information)</strong>"))
.appendTo("body");
// workaround non-clickable "Close" issue in Firefox
if ($.browser.mozilla)
message.find("div.inlinebuttons").next().css("clear", "right");
show();
});
} else if (message_is_visible) {
hide();
} else {
show();
highlight_rev = message_rev;
}
/* Highlight all lines of the current revision */
$("table.code th."+highlight_rev).each(function() {
$(this.parentNode).addClass("hilite")
});
});
});
}
})(jQuery);
| JavaScript | 0.000027 | @@ -2947,16 +2947,36 @@
.mozilla
+ %7C%7C $.browser.safari
)%0A
|
b70fbed215915ace425ad0d45964cf3a881e3050 | use mkdirp create folder | raml-store.js | raml-store.js | var express = require('express');
var debug = require('debug')('raml-store');
var path = require('path');
var config = require('config');
var cors = require('cors');
// creates dist-override/editor.html
var fs = require('fs');
var editorFile = fs.readFileSync(path.join(__dirname, 'node_modules/api-designer/dist/index.html'), 'utf8');
var consoleFile = fs.readFileSync(path.join(__dirname, 'node_modules/api-console/dist/index.html'), 'utf8');
editorFile = editorFile.replace(/<\/body\>/g, '<script src="angular-persistence.js"></script></body>');
fs.writeFileSync(path.join(__dirname, 'dist-override/editor.html'), editorFile, 'utf8');
consoleFile = consoleFile.replace('<raml-initializer></raml-initializer>', '<raml-console src="/files/index.raml" disable-theme-switcher disable-raml-client-generator></raml-console>');
fs.writeFileSync(path.join(__dirname, 'dist-override/console.html'), consoleFile, 'utf8');
function serveEditor (req, res, next) {
if (req.url === '/') {
return res.redirect('/editor/index.html');
};
if (req.url === '/index.html') {
return res.sendFile('/editor.html', { root: path.join(__dirname, 'dist-override') });
}
if (req.url === '/angular-persistence.js') {
return res.sendFile('/angular-persistence.js', { root: path.join(__dirname, 'dist-override') });
}
var requestedFile = req.url.replace(/\?.*/, '');
debug('requested:', requestedFile);
res.sendFile(requestedFile, { root: path.join(__dirname, 'node_modules/api-designer/dist') }, function (err) {
if (!!err && err.code === 'ENOENT') return res.sendStatus(404);
if (!!err) return next(err);
});
}
function serveConsole (req, res, next) {
if (req.url === '/index.html' || req.url === '/') {
return res.sendFile('/console.html', { root: path.join(__dirname, 'dist-override') });
}
var requestedFile = req.url.replace(/\?.*/, '');
debug('requested:', requestedFile);
res.sendFile(requestedFile, { root: path.join(__dirname, 'node_modules/api-console/dist') }, function (err) {
if (!!err && err.code === 'ENOENT') return res.sendStatus(404);
if (!!err) return next(err);
});
}
var ramlServe;
module.exports = ramlServe = function (ramlPath) {
var router = express.Router();
var bodyParser = require('body-parser');
var api = require('./api')(ramlPath);
router.use(cors());
router.use(bodyParser.json());
router.get('/files', api.get);
router.get('/files/*', api.get);
router.post('/files/*', api.post);
router.put('/files/*', api.put);
router.delete('/files/*', api.delete);
router.use('/editor', serveEditor);
router.use('/', serveConsole);
return router;
};
if (module.parent === null) {
var app = express();
app.use('/', ramlServe(config.ramlPath));
var server = app.listen(config.port, function() {
console.log('Express server listening on ' + server.address().address + ':' + server.address().port + '/');
});
}
| JavaScript | 0 | @@ -159,16 +159,79 @@
'cors');
+%0Avar mkdirp = require('mkdirp');%0A%0Amkdirp.sync(config.ramlPath);
%0A%0A// cre
|
694a4fbe7371470ef23b590d2880dd666e335ad7 | Fix typo | source/gulp/tasks/build.js | source/gulp/tasks/build.js | const gulp = require("gulp");
const source = require("vinyl-source-stream"); // Used to stream bundle for further handling
const buffer = require("vinyl-buffer");
const babelify = require("babelify");
const browserify = require("browserify");
const watchify = require("watchify");
const gutil = require("gulp-util");
const cssmin = require("gulp-cssmin");
const less = require("gulp-less");
const uglify = require("gulp-uglify");
const header = require("gulp-header");
const config = require("../config");
const _error_ = "error"
// Build without watch:
gulp.task("js-build", () => {
config.esToJs.forEach(o => {
var filename = o.filename + ".js";
browserify(o.entry, { debug: true })
.transform(babelify, {
sourceMaps: true
})
.bundle()
.on(_error_, err => console.log(err))
.pipe(source(filename))
.pipe(gulp.dest(o.destfolder));
});
});
gulp.task("dist", () => {
config.esToJs.forEach(o => {
var filename = o.filename + ".js";
browserify(o.entry, { debug: false })
.transform(babelify, {
sourceMaps: false
})
.bundle()
.on(_error_, err => console.log(err))
.pipe(source(filename))
.pipe(buffer())
.pipe(uglify())
.pipe(header(config.license, {
version: config.version,
build: (new Date()).toUTCString()
}))
.pipe(gulp.dest(config.distFolder));
});
var allLess = config.lessToCss.concat(config.lessToCssExtras);
allLess.forEach(o => {
if (o.nodist) return;
var source = o.src, dest = o.dest;
gulp.src(source) // path to your files
.pipe(less().on(_error_, err => console.log(err)))
.pipe(cssmin().on(_error_, err => console.log(err))) // always minify CSS, remove temptation of editing css directly
.pipe(gulp.dest(config.cssDistFolder));
});
});
// Build for distribution (with uglify)
gulp.task("js-min", () => {
//NB: the following lines are working examples of source mapping generation and js minification
//they are commented on purpose, to keep the build process fast during development
config.esToJs.forEach(o => {
var filename = o.filename + ".min.js";
browserify(o.entry, { debug: false })
.transform(babelify, {
sourceMaps: false
})
.bundle()
.on(_error_, err => console.log(err))
.pipe(source(filename))
.pipe(buffer())
.pipe(uglify())
.pipe(gulp.dest(o.destfolder));
});
});
gulp.task("css-min", () => {
config.lessToCss.forEach(o => {
var source = o.src, dest = o.dest;
gulp.src(source) // path to your files
.pipe(less().on(_error_, err => console.log(err)))
.pipe(cssmin().on(_error_, err => console.log(err))) // always minify CSS, remove temptation of editing css directly
.pipe(gulp.dest(dest));
});
});
// Copies static files to the output folder
gulp.task("copy-static", () => {
config.toBeCopied.forEach(o => {
gulp.src([o.src])
.pipe(gulp.dest(o.dest));
});
});
// watches less files for changes; compiles the files upon change
gulp.task("watch-less", () => {
gulp.watch(config.lessRoot, ["css-build"]);
});
// Build using watchify, and watch
gulp.task("watch-es", watch => {
if (watch === undefined) watch = true;
config.esToJs.forEach(o => {
var filename = o.filename + ".built.js";
var bundler = browserify(o.entry, {
debug: true, // gives us sourcemapping
cache: {}, // required for watchify
packageCache: {}, // required for watchify
fullPaths: true // required for watchify
});
bundler.transform(babelify, {});
if (watch) {
bundler = watchify(bundler);
}
function rebundle() {
var stream = bundler.bundle();
stream.on(_error_, err => console.log(err));
stream = stream.pipe(source(filename));
return stream.pipe(gulp.dest(o.destfolder));
}
bundler.on("update", () => {
console.log(`[*] Rebuilding ${o.destfolder}${filename}`);
rebundle();
});
return rebundle();
});
});
gulp.task("dev-init", ["js-build", "css-min", "copy-static"]);
gulp.task("env-init", ["js-dist", "css-min", "copy-static"]);
| JavaScript | 0.999999 | @@ -710,33 +710,32 @@
form(babelify, %7B
-
%0A sourceM
@@ -743,17 +743,16 @@
ps: true
-
%0A %7D
@@ -903,16 +903,19 @@
p.task(%22
+js-
dist%22, (
@@ -1053,33 +1053,32 @@
form(babelify, %7B
-
%0A sourceM
@@ -1079,33 +1079,32 @@
ourceMaps: false
-
%0A %7D)%0A
@@ -2236,17 +2236,16 @@
elify, %7B
-
%0A
@@ -2262,17 +2262,16 @@
s: false
-
%0A %7D
|
44837bf9f9323cd1823b1b9ff87f1dbd92dedf6e | Update fileManager.js | lib/FileManager/fileManager.js | lib/FileManager/fileManager.js | /**
* fileManager.js
* Andrea Tino - 2015
*/
/**
* Handles files.
* We create a shadow file in order to store escaped source Javascript
* so that we can call the parser on that file.
*/
module.exports = function(fpath) {
var fs = require('fs');
var path = require('path');
var text = require('../text.js');
// Module construction
var validatePath = function(p) {
if (!p) {
throw 'Error: Path cannot be null or undefined!';
}
return p;
};
var processPath = function(p) {
return path.normalize(p);
};
// Private variables
var EXT = '.3kaku';
var filepath = processPath(validatePath(fpath));
var fileContent = null;
// Private functions
var escapeContent = function(str) {
return text().jsEscape(str);
};
var fetchFileContent = function() {
try {
fileContent = fs.readFileSync(filepath, {encoding: 'utf8'});
} catch(e) {
throw 'Error loading file content from ' + filepath + '!';
}
};
// Constructor
{
fetchFileContent();
};
return {
/**
* Gets the name of the shadow file.
*/
shadowFileName() = function() {
return filepath + EXT;
},
/**
* Creates the shadow file and initializes its content basing
* on the original file.
*/
createShadowFile: function() {
if (!fileContent) {
throw 'Error: File content not available to create shadow file!';
}
var dir = path.dirname(filepath);
var shadowFilePath = path.join(dir, shadowFileName());
// If file exists, overwrite it, if it does not exists, create it
var fd = fs.openSync(shadowFilePath, 'w');
var shadowContent = escapeContent(fileContent); // fileContent available from cton time
shadowContent = 'print(Reflect.parse(\"' + shadowContent + '\"));';
fs.writeSync(fd, shadowContent, 0, {encoding: 'utf8'});
fs.closeSync(fd);
},
/**
* Removes the shadow file.
*/
removeShadowFile: function(errorIfDoesNotExists) {
errorIfDoesNotExists = (typeof errorIfDoesNotExists === 'undefined') ?
false : errorIfDoesNotExists;
var dir = path.dirname(filepath);
var shadowFilePath = path.join(dir, shadowFileName());
// If the file does not exist, do nothing or throw
if (!fs.existsSync(shadowFilePath) && errorIfDoesNotExists) {
throw 'Error: Cannot find shadow file to remove!';
} else {
return;
}
// The shadow file exists: we need to remove it
fs.unlinkSync(shadowFilePath);
}
};
};
| JavaScript | 0.000001 | @@ -1837,24 +1837,36 @@
%22));';%0A
+ var bytes =
fs.writeSyn
@@ -1934,16 +1934,112 @@
nc(fd);%0A
+ %0A if (bytes %3C= 0) %7B%0A throw 'Error: Error while writing shadow file!';%0A %7D%0A
%7D,%0A
|
fb58c75a9f07e97094bb414a0e6f818896cf5424 | modify schema | api/schemas/articles.js | api/schemas/articles.js | var Schema, article, mongoose;
mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
Schema = mongoose.Schema;
article = new Schema({
name: {
type: String
},
description: {
type: String
},
price: {
type: String
}
});
module.exports = mongoose.model('articles', article); | JavaScript | 0.000001 | @@ -227,24 +227,126 @@
%0A price: %7B%0A
+ type: Number%0A %7D,%0A stars: %7B%0A type: Number%0A %7D,%0A quantity: %7B%0A type: Number%0A %7D,%0A image: %7B%0A
type: St
|
d550600b0142f1db593645eaef16926d0358e064 | ADD a loglevel option for dev mode in CLI | lib/core/src/server/cli/dev.js | lib/core/src/server/cli/dev.js | import program from 'commander';
import chalk from 'chalk';
import { logger } from '@storybook/node-logger';
import { parseList, getEnvConfig } from './utils';
async function getCLI(packageJson) {
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
program
.version(packageJson.version)
.option('-p, --port [number]', 'Port to run Storybook', (str) => parseInt(str, 10))
.option('-h, --host [string]', 'Host to run Storybook')
.option('-s, --static-dir <dir-names>', 'Directory where to load static files from', parseList)
.option('-c, --config-dir [dir-name]', 'Directory where to load Storybook configurations from')
.option(
'--https',
'Serve Storybook over HTTPS. Note: You must provide your own certificate information.'
)
.option(
'--ssl-ca <ca>',
'Provide an SSL certificate authority. (Optional with --https, required if using a self-signed certificate)',
parseList
)
.option('--ssl-cert <cert>', 'Provide an SSL certificate. (Required with --https)')
.option('--ssl-key <key>', 'Provide an SSL key. (Required with --https)')
.option('--smoke-test', 'Exit after successful start')
.option('--ci', "CI mode (skip interactive prompts, don't open browser)")
.option('--quiet', 'Suppress verbose build output')
.option('--no-version-updates', 'Suppress update check', true)
.option('--no-dll', 'Do not use dll reference')
.option('--debug-webpack', 'Display final webpack configurations for debugging purposes')
.option(
'--preview-url [string]',
'Disables the default storybook preview and lets your use your own'
)
.option('--docs', 'Build a documentation-only site using addon-docs')
.parse(process.argv);
// Workaround the `-h` shorthand conflict.
// Output the help if `-h` is called without any value.
// See storybookjs/storybook#5360
program.on('option:host', (value) => {
if (!value) {
program.help();
}
});
logger.info(chalk.bold(`${packageJson.name} v${packageJson.version}`) + chalk.reset('\n'));
// The key is the field created in `program` variable for
// each command line argument. Value is the env variable.
getEnvConfig(program, {
port: 'SBCONFIG_PORT',
host: 'SBCONFIG_HOSTNAME',
staticDir: 'SBCONFIG_STATIC_DIR',
configDir: 'SBCONFIG_CONFIG_DIR',
ci: 'CI',
});
if (typeof program.port === 'string' && program.port.length > 0) {
program.port = parseInt(program.port, 10);
}
return { ...program };
}
export default getCLI;
| JavaScript | 0 | @@ -1254,16 +1254,91 @@
wser)%22)%0A
+ .option('--loglevel %5Blevel%5D', 'Control level of logging during build')%0A
.opt
|
93c6ff42245145c3a6cdbcadefb52f6d9561c448 | Modify the value when the menu disappears | src/js/index.js | src/js/index.js | /*!
* Harrix HTML Template (https://github.com/Harrix/Harrix-HTML-Template)
* Copyright 2018 Sergienko Anton
* Licensed under MIT (https://github.com/Harrix/Harrix-HTML-Template/blob/master/LICENSE)
*/
import fontawesome from '@fortawesome/fontawesome'
import fontawesomeFreeSolid from '@fortawesome/fontawesome-free-solid'
import fontawesomeFreeRegular from '@fortawesome/fontawesome-free-regular'
import fontawesomeFreeBrands from '@fortawesome/fontawesome-free-brands'
function getAll(selector) {
return Array.prototype.slice.call(document.querySelectorAll(selector), 0);
}
specialShadow.onmouseover = function(event) {
const navbarEl = document.getElementById('navbar');
navbarEl.classList.remove('translateY-hide');
};
document.addEventListener('DOMContentLoaded', () => {
const navbarEl = document.getElementById('navbar');
const navbarBurger = document.getElementById('navbarBurger');
const specialShadow = document.getElementById('specialShadow');
const rootEl = document.documentElement;
const logo = document.getElementById('logo');
let lastY = 0;
let currentY = 0;
navbarBurger.addEventListener('click', () => {
rootEl.classList.toggle('bd-is-clipped-touch');
const target = document.getElementById(navbarBurger.dataset.target);
navbarBurger.classList.toggle('is-active');
target.classList.toggle('is-active');
});
window.addEventListener('scroll', function() {
lastY = currentY;
currentY = window.scrollY;
if (currentY >= 50) {
logo.classList.add('logo-shrink');
} else {
logo.classList.remove('logo-shrink');
}
if (currentY >= lastY) {
if (currentY > 200) {
navbarEl.classList.add('translateY-hide');
console.log('add ' + lastY + " " + currentY);
}
} else {
navbarEl.classList.remove('translateY-hide');
console.log('remove ' + lastY + " " + currentY);
}
});
}); | JavaScript | 0.000002 | @@ -1734,17 +1734,17 @@
rentY %3E
-2
+3
00) %7B%0A
|
0f3b131cf0e06eac89885aabd84252d6f9dfe141 | make use of new caching module in help | source/redux/parts/help.js | source/redux/parts/help.js | // @flow
import {type ReduxState} from '../index'
import {type ToolOptions} from '../../views/help/types'
import {fetchHelpTools} from '../../lib/cache'
type Dispatch<A: Action> = (action: A | Promise<A> | ThunkAction<A>) => any
type GetState = () => ReduxState
type ThunkAction<A: Action> = (dispatch: Dispatch<A>, getState: GetState) => any
type Action = GetEnabledToolsAction
const ENABLED_TOOLS_START = 'help/ENABLED_TOOLS/start'
const ENABLED_TOOLS_FAILURE = 'help/ENABLED_TOOLS/failure'
const ENABLED_TOOLS_SUCCESS = 'help/ENABLED_TOOLS/success'
type GetEnabledToolsStartAction = {type: 'help/ENABLED_TOOLS/start'}
type GetEnabledToolsSuccessAction = {
type: 'help/ENABLED_TOOLS/success',
payload: Array<ToolOptions>,
}
type GetEnabledToolsFailureAction = {type: 'help/ENABLED_TOOLS/failure'}
type GetEnabledToolsAction =
| GetEnabledToolsStartAction
| GetEnabledToolsSuccessAction
| GetEnabledToolsFailureAction
export function getEnabledTools(): ThunkAction<GetEnabledToolsAction> {
return async dispatch => {
dispatch({type: ENABLED_TOOLS_START})
try {
const config = await fetchHelpTools()
dispatch({type: ENABLED_TOOLS_SUCCESS, payload: config})
} catch (err) {
dispatch({type: ENABLED_TOOLS_FAILURE})
}
}
}
export type State = {|
+fetching: boolean,
+tools: Array<ToolOptions>,
+lastFetchError: ?boolean,
|}
const initialState = {
fetching: false,
tools: [],
lastFetchError: null,
}
export function help(state: State = initialState, action: Action) {
switch (action.type) {
case ENABLED_TOOLS_START:
return {...state, fetching: true}
case ENABLED_TOOLS_FAILURE:
return {
...state,
fetching: false,
lastFetchError: true,
}
case ENABLED_TOOLS_SUCCESS:
return {
...state,
fetching: false,
lastFetchError: false,
tools: action.payload,
}
default:
return state
}
}
| JavaScript | 0 | @@ -117,41 +117,380 @@
etch
-HelpTools%7D from '../../lib/cache'
+AndCacheItem, type CacheResult%7D from '../../lib/cache'%0Aimport %7BAPI%7D from '@frogpond/api'%0A%0Afunction fetchHelpTools(): CacheResult%3C?Array%3CToolOptions%3E%3E %7B%0A%09return fetchAndCacheItem(%7B%0A%09%09key: 'help:tools',%0A%09%09url: API('/tools/help'),%0A%09%09afterFetch: parsed =%3E parsed.data,%0A%09%09ttl: %5B1, 'hour'%5D,%0A%09%09cbForBundledData: () =%3E%0A%09%09%09Promise.resolve(require('../../../docs/help.json')),%0A%09%7D)%0A%7D
%0A%0Aty
@@ -1456,32 +1456,37 @@
()%0A%09%09%09dispatch(%7B
+%0A%09%09%09%09
type: ENABLED_TO
@@ -1497,17 +1497,21 @@
SUCCESS,
-
+%0A%09%09%09%09
payload:
@@ -1517,16 +1517,33 @@
: config
+.value %7C%7C %5B%5D,%0A%09%09%09
%7D)%0A%09%09%7D c
|
b9cef3cf119985c474f33bd01eff2a9d3076133d | Update index.js | lib/ember/addon/utils/index.js | lib/ember/addon/utils/index.js | import Ember from 'ember';
export const isArray = Ember.isArray;
export const isBlank = Ember.isBlank;
export const isEmpty = Ember.isEmpty;
export const isNone = Ember.isNone;
export const isPresent = Ember.isPresent;
export const tryInvoke = Ember.tryInvoke;
export const typeOf = Ember.typeOf;
| JavaScript | 0.000002 | @@ -134,16 +134,54 @@
sEmpty;%0A
+export const isEqual = Ember.isEqual;%0A
export c
|
8623fa65d54b8664cd1d9c7a74d77606ca24d2e5 | Make the encrypted regex a bit better | notable/static/app.js | notable/static/app.js | /**
* Encapsulate and namespace
*/
(function() {
if ( typeof(NOTABLE) === "undefined") {
NOTABLE = {};
};
// Constants
var ENCRYPTED = '<ENCRYPTED>';
var RE_ENCRYPTED = new RegExp(/[^ ]{32,}$/);
var RE_DECRYPTED = new RegExp(/^[\000-\177]*$/);
/**
* Main application
*/
NOTABLE.Application = function(el) {
var that = this;
/**
* Application setup
*/
this.init = function() {
var pkgs = ['corechart', 'table'];
google.load('visualization', '1.0', {'packages':pkgs});
google.setOnLoadCallback(that.perform_search);
// Add event handlers
$('#create').on('click', that.create);
$('#persist').on('click', that.persist);
$('#refresh').on('click', that.perform_search);
$('#reset').on('click', that.reset_all);
$('#search input').on('keypress', that.perform_search);
$('#password-dialog form').on('submit', that.decrypt);
$('#editor').on('click', that.launch_editor);
$('#delete').on('click', that.delete);
// Key bindings
$(document).keydown(function(e) {
switch (e.which) {
case 27:
that.reset_all();
break;
case 78:
that.create();
break;
case 83:
that.search_dialog();
break;
}
});
return this;
};
/**
* Center an element
*/
this.center = function(el) {
el = $(el);
el.css({
position: 'absolute',
left: '50%',
'margin-left': 0 - (el.width() / 2)
});
return el;
};
/**
* Post process the note content as it might be encrypted
*/
this.content = function(data, i) {
var idx = data.getColumnIndex('content');
var content = data.getValue(i, idx).split('\n');
content.shift();
if (RE_ENCRYPTED.test(content)) {
return ENCRYPTED;
}
return content.join('\n').substr(0, 100);
};
/**
* Create a new note
*/
this.create = function() {
var found = NOTABLE.any_visible(['#search input', '#content textarea']);
if (! found) {
$('#create').hide();
$('#refresh').hide();
$('#content').show();
$('#reset').show();
$('#persist').show();
$('#delete').show();
$('#editor').show();
setTimeout("$('#content textarea').focus()", 100);
}
}
/**
* Decrypt a particular note's contents
*/
this.decrypt = function() {
var post = {
password: $('#password-dialog input').val(),
uid: $('#content #uid').val(),
}
$.post('/api/decrypt', post, function (response) {
if (RE_DECRYPTED.test(response)) {
$('#content textarea').val(response);
that.reset_password();
$('#delete').show();
} else {
$('#password-dialog input').val('');
};
});
return false;
}
/**
* Delete a note
*/
this.delete = function() {
var post = {
password: $('#content #password').val(),
uid: $('#content #uid').val(),
}
$.post('/api/delete', post, function (response) {
that.reset_all();
that.perform_search();
});
}
/**
* Edit an existing note
*/
this.edit = function(data, row) {
that.create();
$('#content textarea').val(data.getValue(row, data.getColumnIndex('content')))
$('#content #uid').val(data.getValue(row, data.getColumnIndex('uid')))
$('#content #tags').val(data.getValue(row, data.getColumnIndex('tags')))
var b = data.getValue(row, data.getColumnIndex('content')).split('\n')[1];
if (RE_ENCRYPTED.test(b)) {
that.password_dialog();
$('#delete').hide();
}
}
/**
* Launch external editor
*/
this.launch_editor = function() {
var post = {
content: $('#content textarea').val(),
uid: $('#content #uid').val(),
}
$.post('/api/launch_editor', post, function (response) {
that.poll_disk(response);
});
}
/**
* Spawn password entry dialog for an encrypted note
*/
this.password_dialog = function() {
this.center('#password-dialog').show();
setTimeout("$('#password-dialog input').focus()", 100);
}
/**
* Make network call to search for notes
*/
this.perform_search = function() {
var q = {s: $('#search input').val()};
$.get('/api/list', q, function (response) {
that.render_listing(response);
});
}
/**
* Persist a note to the backend
*/
this.persist = function() {
var post = {
content: $('#content textarea').val(),
password: $('#content #password').val(),
tags: $('#content #tags').val(),
uid: $('#content #uid').val(),
}
$.post('/api/persist', post, function (response) {
that.reset_all();
that.perform_search();
});
}
/**
* Poll disk for updates by an external text editor
*/
this.poll_disk = function(uid) {
$.get('/api/from_disk/' + uid, function (response) {
if (response != 'missing') {
$('#content textarea').val(response);
setTimeout(that.poll_disk(uid), 1000)
}
});
}
/**
* Render note listing
*/
this.render_listing = function(json) {
var div = document.getElementById('listing')
var data = new google.visualization.DataTable(json);
var table = new google.visualization.Table(div);
var view = new google.visualization.DataView(data);
var columns = [
data.getColumnIndex('updated'),
data.getColumnIndex('subject'),
{calc: that.content, id:'body', type:'string', label:'Body'},
data.getColumnIndex('tags'),
]
var options = {
height: '200px',
sortAscending: false,
sortColumn: 0,
width: '100%',
};
view.setColumns(columns);
table.draw(view, options);
// Add navigation listener
google.visualization.events.addListener(table, 'select',
function(e) {
that.edit(data, table.getSelection()[0].row);
});
}
/**
* Reset all dialogs and forms
*/
this.reset_all = function() {
$('#content').hide();
$('#reset').hide();
$('#persist').hide();
$('#delete').hide();
$('#editor').hide();
$('#create').show();
$('#refresh').show();
$('#content #tags').val('');
$('#content textarea').val('');
$('#content #uid').val('');
$('#content #password').val('');
that.reset_password();
that.reset_search();
}
/**
* Reset password dialog
*/
this.reset_password = function() {
$('#password-dialog').hide();
$('#password-dialog input').val('');
}
/**
* Reset search dialog
*/
this.reset_search = function() {
$('#search').hide();
$('#search input').val('');
}
/**
* Render search dialog
*/
this.search_dialog = function() {
var found = NOTABLE.any_visible(['#content textarea']);
if (! found) {
$('#search').show();
setTimeout("$('#search input').focus()", 100);
}
}
}; // eoc
/**
* Return boolean if any of the specified selectors are visible
*/
NOTABLE.any_visible = function(selectors) {
var guilty = false
$.each(selectors, function(idx, value) {
if ($(value).is(":visible")) {
guilty = true;
return false;
};
});
return guilty;
}
}());
| JavaScript | 0.002444 | @@ -193,16 +193,17 @@
RegExp(/
+%5E
%5B%5E %5D%7B32,
|
22e57ed1fbb7af030184c3926e536e6f87f98e13 | Fix broken navigation shortcuts | app/main.js | app/main.js | 'use strict'
// Handle the Squirrel.Windows install madnesss
/* eslint global-require: "off" */
if (require('electron-squirrel-startup')) return
const {
app, BrowserWindow, globalShortcut, Menu
} = require('electron')
const autoUpdater = require('./auto-updater')
const contextMenu = require('./context-menu')
const dockMenu = require('./dock-menu')
const errorHandlers = require('./error-handlers')
const mainMenu = require('./menu')
const options = require('./options')
const SoundCloud = require('./soundcloud')
const touchBarMenu = require('./touch-bar-menu')
const windowOpenPolicy = require('./window-open-policy')
const windowState = require('electron-window-state')
let mainWindow = null
let aboutWindow = null
const {
autoUpdaterBaseUrl,
baseUrl,
developerTools,
profile,
quitAfterLastWindow,
useAutoUpdater,
userData
} = options(process)
if (userData)
app.setPath('userData', userData)
else if (profile)
app.setPath('userData', app.getPath('userData') + ' ' + profile)
let quitting = false
app.on('before-quit', () => {
quitting = true
})
const shouldQuit = app.makeSingleInstance(() => {
if (mainWindow) {
if (mainWindow.isMinimized()) mainWindow.restore()
mainWindow.show()
mainWindow.focus()
}
})
if (shouldQuit) app.quit()
if (useAutoUpdater) autoUpdater(autoUpdaterBaseUrl)
windowOpenPolicy(app)
app.on('activate', () => {
if (mainWindow) mainWindow.show()
})
app.on('ready', () => {
const menu = mainMenu({ developerTools })
Menu.setApplicationMenu(menu)
const mainWindowState = windowState({
defaultWidth: 1024,
defaultHeight: 640
})
mainWindow = new BrowserWindow({
x: mainWindowState.x,
y: mainWindowState.y,
width: mainWindowState.width,
height: mainWindowState.height,
minWidth: 640,
minHeight: 320,
webPreferences: {
nodeIntegration: false,
preload: `${__dirname}/preload.js`
}
})
const soundcloud = new SoundCloud(mainWindow)
contextMenu(mainWindow, soundcloud)
errorHandlers(mainWindow)
if (process.platform == 'darwin') {
dockMenu(soundcloud)
touchBarMenu(mainWindow, soundcloud)
}
mainWindowState.manage(mainWindow)
mainWindow.on('close', (event) => {
// Due to (probably) a bug in Spectron this prevents quitting
// the app in tests:
// https://github.com/electron/spectron/issues/137
if (!quitting && !quitAfterLastWindow) {
// Do not quit
event.preventDefault()
// Hide the window instead of quitting
if (mainWindow.isFullScreen()) {
// Avoid blank black screen when closing a fullscreen window on macOS
// by only hiding when the leave-fullscreen animation finished.
// See https://github.com/electron/electron/issues/6033
mainWindow.once('leave-full-screen', () => mainWindow.hide())
mainWindow.setFullScreen(false)
} else
mainWindow.hide()
}
})
// Only send commands from menu accelerators when the app is not focused.
// This avoids double-triggering actions and triggering actions during text
// is entered into the search input or in other places.
function isNotFocused() {
return !mainWindow || !mainWindow.isFocused()
}
mainWindow.on('closed', () => {
if (process.platform !== 'darwin')
app.quit()
mainWindow = null
})
globalShortcut.register('MediaPlayPause', () => {
soundcloud.playPause()
})
globalShortcut.register('MediaNextTrack', () => {
soundcloud.nextTrack()
})
globalShortcut.register('MediaPreviousTrack', () => {
soundcloud.previousTrack()
})
menu.events.on('playPause', () => {
if (isNotFocused()) soundcloud.playPause()
})
menu.events.on('likeUnlike', () => {
if (isNotFocused()) soundcloud.likeUnlike()
})
menu.events.on('repost', () => {
if (isNotFocused()) soundcloud.repost()
})
menu.events.on('nextTrack', () => {
if (isNotFocused()) soundcloud.nextTrack()
})
menu.events.on('previousTrack', () => {
if (isNotFocused()) soundcloud.previousTrack()
})
menu.events.on('home', () => {
if (isNotFocused()) soundcloud.goHome()
})
menu.events.on('back', () => {
if (isNotFocused()) soundcloud.goBack()
})
menu.events.on('forward', () => {
if (isNotFocused()) soundcloud.goForward()
})
menu.events.on('main-window', () => {
if (mainWindow.isVisible())
mainWindow.hide()
else
mainWindow.show()
})
menu.events.on('about', () => {
showAbout()
})
mainWindow.on('app-command', (e, cmd) => {
switch (cmd) {
case 'media-play':
soundcloud.play()
break
case 'media-pause':
soundcloud.pause()
break
case 'media-play-pause':
soundcloud.playPause()
break
case 'browser-backward':
soundcloud.goBack()
break
case 'browser-forward':
soundcloud.goForward()
break
case 'browser-home':
soundcloud.goHome()
break
default:
}
})
// "You cannot require or use this module until the `ready` event of the
// `app` module is emitted."
/* eslint global-require: off */
require('electron').powerMonitor.on('suspend', () => {
soundcloud.pause()
})
soundcloud.on('play-new-track', ({ title, subtitle, artworkURL }) => {
mainWindow.webContents.send('notification', { title, body: subtitle, icon: artworkURL })
})
mainWindow.webContents.once('did-start-loading', () => {
mainWindow.setTitle('Loading soundcloud.com...')
})
mainWindow.loadURL(getUrl())
})
function getUrl() {
if (baseUrl)
return baseUrl
return 'https://soundcloud.com'
}
function showAbout() {
if (aboutWindow)
aboutWindow.show()
else {
aboutWindow = new BrowserWindow({
fullscreen: false,
fullscreenable: false,
height: 520,
maximizable: false,
resizable: false,
show: false,
skipTaskbar: true,
width: 385,
modal: true,
parent: mainWindow
})
aboutWindow.setMenu(null)
aboutWindow.once('ready-to-show', () => {
aboutWindow.show()
})
aboutWindow.on('close', () => {
aboutWindow = null
})
aboutWindow.loadURL(`file://${__dirname}/about.html`)
}
}
| JavaScript | 0.000038 | @@ -4042,32 +4042,155 @@
usTrack()%0A %7D)%0A%0A
+ // The shortcuts *not* handled by SoundCloud itself%0A // don't need the isNotFocused() check to avoid double triggering%0A%0A
menu.events.on
@@ -4209,36 +4209,16 @@
=%3E %7B%0A
- if (isNotFocused())
soundcl
@@ -4272,36 +4272,16 @@
=%3E %7B%0A
- if (isNotFocused())
soundcl
@@ -4338,36 +4338,16 @@
=%3E %7B%0A
- if (isNotFocused())
soundcl
|
de9776c72302d0a01bc02b8bc36ef375f0d11c5c | Fix typo | lib/functions/getScripts.js | lib/functions/getScripts.js | const {
google,
} = require('googleapis');
const constants = require('../constants.js');
const triageGoogleError = require('./triageGoogleError.js');
/**
* Lists the names and IDs of script files.
*
* @param {google.auth.OAuth2} auth - An authorized OAuth2 client.
* @param {String} nameFilter - String to filter results on.
* @param {String} nextPageToken - Token of the resultpage to get.
* @param {String} allFiles - String to filter results on.
* @returns {Promise} - A promise resolving a list of files
*/
function getScripts(auth, nameFilter, nextPageToken, allFiles) {
return new Promise((resolve, reject) => {
let query = '';
if (nameFilter) {
query = `mimeType='${constants.MIME_GAS}' and name contains '${nameFilter}'`;
} else {
query = `mimeType='${constants.MIME_GAS}'`;
}
const drive = google.drive('v3');
drive.files.list({
auth,
pageSize: 1000,
fields: 'nextPageToken, files(id, name, description, createdTime, modifiedTime)',
orderBy: 'name',
includeTeamDriveItems: true,
supportsTeamDrives: true,
q: query,
spaces: 'drive',
pageToken: nextPageToken,
}, (err, response) => {
if (err) {
triageGoogleError(err, 'listScriptFIles').then((triaged) => {
reject(triaged);
}).catch((notTriaged) => {
reject(notTriaged);
});
return;
}
const files = response.data.files;
allFiles = allFiles.concat(files);
// Need to get another page of results?
if (response.nextPageToken) {
getScripts(auth, nameFilter, response.nextPageToken, allFiles).then((allFiles) => {
resolve(allFiles);
}).catch((err) => {
reject(err);
});
return;
} else {
resolve(allFiles);
return;
}
});
});
}
module.exports = getScripts;
| JavaScript | 0.999999 | @@ -1364,17 +1364,17 @@
tScriptF
-I
+i
les').th
|
fe8270eb5b8a15aa1cc4daec881cbf4ecb9301d3 | Remove garbage | src/js/index.js | src/js/index.js | // TODO 同じタイトルのとき上書きする前に聞くためのチェックボックスがoptionにほしい
// TODO bluebird入れる
// TODO 全体的なスタイル当てなど(haml, css)
// TODO esaで開くボタン欲しい
getConfig = function(defaultConfig) {
return new Promise(function(resolve, reject) {
var defaultConfig = {teamName: "", token: ""};
chrome.storage.sync.get(defaultConfig, function(config) {
if(!config.teamName || !config.token) {
reject("Please configure options (\\( ˘⊖˘)/)");
}
resolve(config);
});
});
}
searchPost = function(config) {
return new Promise(function(resolve, reject) {
var title = $("#title").val();
$.ajax({
type: "GET",
url: "https://api.esa.io/v1/teams/" + config.teamName + "/posts?access_token=" + config.token,
data: {
q: "name:" + title
},
success: function(response) {
if(response.posts[0]) {
config.postId = response.posts[0].number;
}
resolve(config);
},
error: reject
})
})
}
savePost = function(config) {
return new Promise(function(resolve, reject) {
var type;
var url = "https://api.esa.io/v1/teams/" + config.teamName + "/posts";
var title = $("#title").val();
var body = $("#body").val();
var postId = config.postId;
if(postId) {
type = "PATCH";
url = url + "/" + postId;
} else {
type = "POST";
}
$.ajax({
type: type,
url: url,
data: {
post: {
name: title,
body_md: body,
message: "from tsuibami"
},
access_token: config.token
},
error: reject,
success: resolve((postId) ? "updated!" : "created!")
});
});
}
notifyReady = function(config) {
notifySuccess('team "' + config.teamName + '" is used', true);
}
notifySuccess = function(msg) {
showMessage(msg + " (\\( ⁰⊖⁰)/)", true);
}
notifyError = function(msg) {
if(msg.responseJSON) {
showMessage(msg.responseJSON.message);
} else {
showMessage(msg);
}
}
showMessage = function(message, isFadeOut) {
$("#msg").text(message);
if(isFadeOut) {
setTimeout(function() {
$("#msg").fadeOut("normal", function() {
$("#msg").text("");
$("#msg").toggle();
});
}, 3000);
}
}
$(function() {
$(window).on("load", function() {
console.log("load");
getConfig().then(notifyReady).catch(notifyError);
});
$("#post").on("click", function() {
getConfig().then(searchPost).then(savePost).then(notifySuccess, notifyError);
});
});
| JavaScript | 0.000186 | @@ -2638,37 +2638,8 @@
) %7B%0A
- console.log(%22load%22);%0A
|
754bd76e3f18246b4b3cf161755fb9919571cc19 | Change en_US code from "en" to "en-us" for consistency | app/util.js | app/util.js | function randomFrom(array) {
return array[Math.floor(Math.random()*array.length)]
}
function filter_available(item) {
return !item.unreleased
}
var language_map = {
"en_US": "en",
"fr_FR": "fr",
"ja_JP": "ja",
"fr_CA": "fr-ca",
"es_ES": "es",
"es_MX": "es-mx"
}
String.prototype.format = function(scope) {
eval(Object.keys(scope).map(
function(x) { return "var " + x + "=scope." + x
}).join(";"));
return this.replace(/{(.+?)}/g, function($0, $1) {
return eval($1);
})
};
angular.module('splatApp').util = function($scope, $sce) {
// this only works when each language is moved to a directory setup like above (ie in distribution on loadout.ink)
$scope.redirect = function(lang) {
var dir = language_map[lang]
var URL = window.location.protocol + "//"+ window.location.hostname + "/" + dir + "/"
if(window.location.hash) URL += window.location.hash;
if (typeof(Storage) !== "undefined") {
localStorage.selectedLang = lang;
}
window.location = URL;
}
$scope.renderHtml = function(html_code) {
return $sce.trustAsHtml(html_code);
};
}
| JavaScript | 0.000691 | @@ -178,16 +178,19 @@
US%22: %22en
+-us
%22,%0A %22fr
|
3168d77df96ba6326557e9b296dae22121bb5c7a | Remove needless await | src/js/popup.js | src/js/popup.js | 'use strict';
import Promise from 'bluebird';
import Ui from './ui';
import Post from './post';
import Esa from './esa';
export default class Popup {
constructor() {
this.ui = new Ui();
this.post = new Post();
this.esa = undefined;
}
setPreviousPost() {
Post.load((loadedPost) => {
this.post = loadedPost;
this.syncSaveButtonWithPost();
this.ui.post = this.post;
if (this.ui.title != '') {
// Move cursor at previous position
this.ui.cursorPosition = this.post.cursorPosition;
}
});
}
setPreviousState() {
return new Promise((resolve, reject) => {
let defaultConfig = {
teamName: '',
token: '',
teamIcon: '',
};
chrome.storage.sync.get(defaultConfig, (config) => {
if (!config.teamName || !config.token) {
this.ui.toggleDisplayOptionLink(true);
this.ui.team = { teamName: 'Configuration failed' };
throw new Error('Please configure options (\\( ˘⊖˘)/)');
}
this.esa = new Esa(config);
this.ui.toggleDisplayOptionLink(false);
this.ui.team = config;
resolve();
});
});
}
setPreviousSavedPostLink() {
return new Promise((resolve, reject) => {
let defaultLinkData = {
savedPostLink: '',
postId: '',
};
chrome.storage.sync.get(defaultLinkData, (data) => {
if (data.savedPostLink) {
this.ui.savedPostLink = data.savedPostLink;
} else {
// NOTE: 0.2.1以前の後方互換性のための対応
// TODO: 次々回のリリースで削除する
// 合わせてこの関数で行っているsavedPostLinkの設定をsetPreviousPost()に統合する(Postの持つデータとしてsavedPostLinkを使う)
this.ui.savedPostLink = `https://${this.ui.teamName}.esa.io/posts/${
data.postId
}`;
}
resolve();
});
});
}
setHooks(targetName, hooks) {
let targetDom;
switch (targetName) {
case 'title':
targetDom = this.ui.titleDom;
break;
case 'body':
targetDom = this.ui.bodyDom;
break;
case 'post-button':
targetDom = this.ui.postButtonDom;
break;
default:
console.error(`error: invalid target '${targetName}' is specified`);
return;
}
Object.keys(hooks).forEach((key) => {
targetDom.on(key, hooks[key]);
});
}
save() {
this.ui.toggleDisabledSaveButton(true);
this.ui.toggleUploadingStatus(true);
(async () => {
let postId = await this.searchTargetPostInEsa();
let response = await this.uploadPost(postId);
await this.syncPostWithEsaResponse(response);
await this.syncUIWithPost(response);
await this.notifySuccess(response);
})()
.catch((error) => {
console.log(error);
let message = error.hasOwnProperty('statusText')
? error.statusText
: error;
message = error.hasOwnProperty('status')
? `${message} (${error.status})`
: message;
this.showMessage(message);
})
.finally(() => {
this.ui.toggleUploadingStatus(false);
});
}
storeTitle() {
let title = this.ui.title;
if (title != this.post.title) {
this.post.update({ title: title, saved: false });
this.post.store(function() {}, this.showErrorMessage);
this.ui.toggleDisabledSaveButton(false);
}
}
storeBody() {
let body = this.ui.body;
if (body != this.post.body) {
this.post.update({ body: body, saved: false });
this.ui.toggleDisabledSaveButton(false);
}
let cursorPosition = this.ui.cursorPosition;
if (cursorPosition != this.post.cursorPosition) {
this.post.cursorPosition = cursorPosition;
}
// TODO: bodyが変更されていたらcursorPositionも変更されているはずなので↑のif文の中に↓を入れる
this.post.store(function() {}, this.showErrorMessage);
}
storeCursorPosition() {
let cursorPosition = this.ui.cursorPosition;
if (cursorPosition != this.post.cursorPosition) {
this.post.cursorPosition = cursorPosition;
this.post.store(function() {}, this.showErrorMessage);
}
}
// private
// TODO: privateっぽい名前にする?
searchTargetPostInEsa() {
return new Promise((resolve, reject) => {
let [category, title] = Post.splitCategory(this.ui.title);
let q = `name:${title}`;
if (category.length != 0) q = `${q} category:${category}`;
let filterPostsFunc = (response) => {
// nameによる検索は部分一致のため、完全一致させるために検索結果から更に絞り込んでいる
let hitPost = Post.filterPosts(title, category, response);
let postId = hitPost ? hitPost.number : undefined;
resolve(postId);
};
this.esa.search(q, filterPostsFunc, reject);
});
}
uploadPost(postId) {
return new Promise((resolve, reject) => {
let [category, title] = Post.splitCategory(this.ui.title);
let postData = {
id: postId,
name: title,
category: category,
body_md: this.ui.body,
message: 'from tsuibami',
};
this.esa.save(postData, resolve, reject);
});
}
syncPostWithEsaResponse(response) {
this.post.saved = true;
this.post.savedPostLink = response.url;
if (this.ui.isClearCheckBoxChecked) {
this.post.title = '';
this.post.body = '';
this.post.cursorPosition = 0;
} else {
// 保存したタイトルによっては末尾に "(2)" などの表記がesaによってつけられていたり、タイトル無しで保存した場合にカテゴリが変わっている可能性があるため、内容を更新する
this.post.title = response.full_name;
}
return new Promise((resolve, reject) => {
this.post.store(
() => {
this.syncSaveButtonWithPost();
resolve(response);
},
() => {
reject(response);
},
);
});
}
syncUIWithPost(response) {
return new Promise((resolve, _reject) => {
this.ui.post = this.post;
this.ui.savedPostLink = this.post.savedPostLink;
resolve(response);
});
}
syncSaveButtonWithPost() {
this.ui.toggleDisabledSaveButton(this.post.saved);
}
notifySuccess(response) {
// 最初の保存の時だけメッセージを変える
let message = response.revision_number == 1 ? 'created!' : 'updated!';
this.showMessage(message + ' (\\( ⁰⊖⁰)/)', true);
}
showErrorMessage() {
let message;
if (chrome.runtime.lastError === undefined) message = 'unknown error';
else message = chrome.runtime.lastError.message;
this.showMessage('Error: ' + message, false);
}
showMessage(message, succeeded) {
if (succeeded) {
this.ui.messageArea.showMessageOnSuccess(message);
} else {
this.ui.messageArea.showMessageOnFailure(message);
}
}
}
| JavaScript | 0.000227 | @@ -2686,30 +2686,24 @@
se);%0A%0A
-await
this.notifyS
|
d6d1a25b992360031a14c7c14f92bed2fad79069 | Add search WS | app/guildProgress/guildProgressController.js | app/guildProgress/guildProgressController.js | "use strict";
//Load dependencies
var applicationStorage = process.require("core/applicationStorage.js");
var guildProgressModel = process.require("guildProgress/guildProgressModel.js");
var guildModel = process.require("guilds/guildModel.js");
module.exports.getProgress = function (req, res, next) {
var logger = applicationStorage.logger;
logger.info("%s %s %s %s", req.headers['x-forwarded-for'] || req.connection.remoteAddress, req.method, req.path, JSON.stringify(req.params));
var projection = {};
projection["progress.tier_" + req.params.tier] = 1;
guildProgressModel.find({
region: req.params.region,
realm: req.params.realm,
name: req.params.name
}, projection, function (error, guilds) {
if (error) {
logger.error(error.message);
res.status(500).send(error.message);
} else if (guilds && guilds.length > 0 && guilds[0]['progress'] && guilds[0]['progress']["tier_" + req.params.tier]) {
res.json(guilds[0]["progress"]["tier_" + req.params.tier]);
} else {
next();
}
});
};
module.exports.getProgressSimple = function (req, res, next) {
var logger = applicationStorage.logger;
logger.info("%s %s %s %s", req.headers['x-forwarded-for'] || req.connection.remoteAddress, req.method, req.path, JSON.stringify(req.params));
var projection = {};
projection["progress.tier_" + req.params.tier + ".normalCount"] = 1;
projection["progress.tier_" + req.params.tier + ".heroicCount"] = 1;
projection["progress.tier_" + req.params.tier + ".mythicCount"] = 1;
guildProgressModel.find({
region: req.params.region,
realm: req.params.realm,
name: req.params.name
}, projection, function (error, guilds) {
if (error) {
logger.error(error.message);
res.status(500).send(error.message);
} else if (guilds && guilds.length > 0) {
res.json(guilds[0]);
} else {
next();
}
});
};
module.exports.searchGuild = function (req, res) {
var logger = applicationStorage.logger;
logger.info("%s %s %s %s", req.headers['x-forwarded-for'] || req.connection.remoteAddress, req.method, req.path, JSON.stringify(req.query));
if (req.params.text.length >= 3) {
var limit = 0;
if (req.query.number) {
limit = parseInt(req.query.number, 10);
if (isNaN(limit)) {
return;
}
limit = limit < 0 ? 0 : limit;
}
async.waterfall([
function (callback) {
guildProgressModel.find({name: {$regex: "^" + req.params.text, $options: "i"}},
{region: 1, realm: 1, name: 1, _id: 0},
{name: 1}, limit,
function (error, guilds) {
callback(error, guilds);
}
);
},
function (guilds, callback) {
async.each(guilds, function (guild, callback) {
guildModel.getGuildInfo(guild.region, guild.realm, guild.name, function (error, guild) {
if (guild && guild.bnet && guild.bnet.side != null) {
guild["side"] = guild.bnet.side;
}
if (guild && guild.ad && guild.ad.lfg == true) {
guild["lfg"] = true;
}
callback(error);
});
}, function (error) {
callback(error, guilds);
})
}
], function (error, guilds) {
if (error) {
logger.error(error.message);
res.status(500).send(error.message);
} else {
res.json(guilds);
}
});
}
else {
res.json([]);
}
}; | JavaScript | 0.000001 | @@ -239,16 +239,47 @@
l.js%22);%0A
+var async = require(%22async%22);%0A%0A
%0A%0Amodule
|
9275f77e77d4371cc88705d00749dd0807dab844 | Add timeout, success, and error from options | gist.js | gist.js | (function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory)
} else if (typeof exports === 'object') {
module.exports = factory(require('jquery'))
} else {
factory(jQuery)
}
}(function ($) {
'use strict';
var Gist = function (element, options) {
this.options = options
this.$gist = $(element)
this.request()
}
Gist.DEFAULTS = {
timeout: 1000,
success: onAjaxSuccess,
error: onAjaxError
}
Gist.prototype.request = function () {
var gist = this
var id = this.$gist.data('gist')
var file = this.$gist.data('file') || false
var url = 'https://gist.github.com/' + id + '.json'
if (file) {
url += '?file=' + file
}
$.ajax({
url: url,
dataType: 'jsonp',
cache: true,
success: function (data, textStatus, jqXHR) {
self.onAjaxSuccess(self, data, textStatus, jqXHR)
},
error: function (jqXHR, textStatus, errorThrown) {
self.onAjaxError(self, jqXHR, textStatus, errorThrown)
}
})
}
Gist.prototype.onAjaxSuccess = function (self, data, textStatus, jqXHR) {
if (! data || ! 'div' in data) {
self.onAjaxError()
return
}
// Append the stylesheet if it doesn't exists.
// Trying to minimize requests.
if (! $('link[href="' + data.stylesheet + '"]').length) {
$(document.head).append('<link href="' + data.stylesheet + '" rel="stylesheet">')
}
// When loading different files from the same gist
// on one page, there will be duplicate ids.
//
// That should be fixed.
self.$gist.html(data.div)
}
Gist.prototype.onAjaxError = function (self, jqXHR, textStatus, errorThrown) {
self.$gist.html(':(')
}
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('gist-initialized')
var options = $.extend({}, Gist.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (! data) {
$this.data('gist-initialized', (data = new Gist(this, options)))
}
})
}
var old = $.fn.gist
$.fn.gist = Plugin
$.fn.gist.Constructor = Gist
$.fn.gist.noConflict = function () {
$.fn.gist = old
return this
}
})) | JavaScript | 0.000001 | @@ -837,248 +837,107 @@
-success: function (data, textStatus, jqXHR) %7B%0A self.onAjaxSuccess(self, data, textStatus, jqXHR)%0A %7D,%0A error: function (jqXHR, textStatus, errorThrown) %7B%0A self.onAjaxError(self, jqXHR, textStatus, errorThrown)%0A %7D
+timeout: gist.options.timeout,%0A success: gist.options.success,%0A error: gist.options.error
%0A
|
1b29ca8608753636ba1638f094eaff85e1f8b949 | Test for warning on bad command usage. | test/cli.js | test/cli.js | var path = require('path');
var should = require('chai').should();
var expect = require('chai').expect;
var avisynth = require('../main');
var system = require('../code/system');
var my = require('../package.json');
// Since testing a command line script is a bunch of boilerplate, I'll abstract it.
function testCli(doneCallback, args, stdin, expectedCode, expectedOut, expectedErr) {
// Note that while we use a shebang in the cli script and npm can wrap it in
// shell scripts automatically, in this case we're running it by itself and
// in Windows shebangs don't count. So we must explicitely run it through node.
var cli = path.resolve(__dirname, '../cli.js');
var args = [cli].concat(args);
// Also note that we're reusing system's spawn because we're not masochists.
system.spawn('node', args, __dirname, true, function(returnCode, stdout, stderr) {
expect(returnCode).to.equal(expectedCode);
// Note how expectedOut and expectedErr can be strings or validator functions.
if (typeof expectedOut === 'string') {
expect(stdout).to.equal(expectedOut);
} else {
expect(expectedOut(stdout)).to.equal(true);
}
if (typeof expectedErr === 'string') {
expect(stderr).to.equal(expectedErr);
} else {
expect(expectedErr(stderr)).to.equal(true);
}
doneCallback();
});
}
describe('Command-line interface', function() {
this.timeout(10000); // All tests here shouldn't fail because of timeouts.
describe('avisynth-js version', function() {
it('should print the version number', function(done) {
testCli(done, ['version'], null, 0, my.version + '\n', '');
});
});
describe('avisynth-js help', function() {
it('should print the help without warnings', function(done) {
testCli(done, ['help'], null, 0, function(text) {
var lines = text.split(/\r?\n/);
var ok = true;
lines.forEach(function(line) {
if (/^Bad argument: /.test(line)) ok = false;
});
if (!/^Usage: /.test(lines[4])) console.log(text), ok = false;
return ok;
}, '');
});
});
describe('avisynth-js info', function() {
it('should return expected info (NTSC broadcast example)', function(done) {
// Let's cook up a NTSC broadcast example.
var script = new avisynth.Script();
script.colorBarsHD(640, 480);
script.assumeFPS('ntsc_film');
script.trim(1, 1438);
script.code('AudioDub(Tone(54.321, 432, 44056, 1))');
script.convertAudioTo16bit();
script.convertToYV12();
script.assumeFieldBased();
script.assumeTFF();
var info = {
width : 640,
height : 480,
ratio : '4:3',
fps : 23.976,
fpsFraction : '24000/1001',
videoTime : 59.9766,
frameCount : 1438,
colorspace : 'YV12',
bitsPerPixel : 12,
interlaceType : 'field-based',
fieldOrder : 'TFF',
channels : 1,
bitsPerSample : 16,
sampleType : 'int',
audioTime : 54.321,
samplingRate : 44056,
sampleCount : 2393166,
blockSize : 2
};
var args = ['info', script.getPath()];
var infoJson = JSON.stringify(info, undefined, 4);
testCli(done, args, null, 0, infoJson + '\n', '');
});
it('should return expected info (1080p production example)', function(done) {
// Let's cook up a 1080p "production-grade" example.
var script = new avisynth.Script();
script.colorBarsHD(1920, 1080);
script.assumeFPS(60);
script.trim(1, 3600);
script.code('AudioDub(Tone(60, 528, 48000, 6))');
script.convertAudioToFloat();
script.convertToYUY2();
script.assumeFrameBased();
var info = {
width : 1920,
height : 1080,
ratio : '16:9',
fps : 60,
fpsFraction : '60/1',
videoTime : 60,
frameCount : 3600,
colorspace : 'YUY2',
bitsPerPixel : 16,
interlaceType : 'frame-based',
fieldOrder : 'BFF',
channels : 6,
bitsPerSample : 32,
sampleType : 'float',
audioTime : 60,
samplingRate : 48000,
sampleCount : 2880000,
blockSize : 24
};
var args = ['info', script.getPath()];
var infoJson = JSON.stringify(info, undefined, 4);
testCli(done, args, null, 0, infoJson + '\n', '');
});
});
});
| JavaScript | 0 | @@ -2206,26 +2206,436 @@
%5D))
-console.log(text),
+ok = false;%0A return ok;%0A %7D, '');%0A %7D);%0A%0A it('should print help with warnings when a bad command is used', function(done) %7B%0A testCli(done, %5B'feminism'%5D, null, 1, function(text) %7B%0A var lines = text.split(/%5Cr?%5Cn/);%0A var ok = true;%0A if (lines%5B4%5D !== 'Bad argument: %22feminism%22') ok = false;%0A if (!/%5EUsage: /.test(lines%5B6%5D))
ok
|
5071d72ef81131bf203da1424b7e7aee8bd1275c | Disable login panel correctly for chromoting client plugin | remoting/client/extension/chromoting_tab.js | remoting/client/extension/chromoting_tab.js | // Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Message id so that we can identify (and ignore) message fade operations for
// old messages. This starts at 1 and is incremented for each new message.
chromoting.messageId = 1;
function init() {
// This page should only get one request, and it should be
// from the chromoting extension asking for initial connection.
// Later we may need to create a more persistent channel for
// better UI communication. Then, we should probably switch
// to chrome.extension.connect().
chrome.extension.onRequest.addListener(requestListener);
}
function submitLogin() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
// Make the login panel invisible and submit login info.
document.getElementById("login_panel").className = "login_panel";
chromoting.plugin.submitLoginInfo(username, password);
}
/**
* A listener function to be called when the extension fires a request.
*
* @param request The request sent by the calling script.
* @param sender The MessageSender object with info about the calling script's
* context.
* @param sendResponse Function to call with response.
*/
function requestListener(request, sender, sendResponse) {
console.log(sender.tab ?
'from a content script: ' + sender.tab.url :
'from the extension');
// Kick off the connection.
var plugin = document.getElementById('chromoting');
chromoting.plugin = plugin;
chromoting.username = request.username;
chromoting.hostname = request.hostName;
// Setup the callback that the plugin will call when the connection status
// has changes and the UI needs to be updated. It needs to be an object with
// a 'callback' property that contains the callback function.
plugin.connectionInfoUpdate = pluginCallback;
plugin.loginChallenge = pluginLoginChallenge;
// TODO(garykac): Clean exit if |connect| isn't a funtion.
if (typeof plugin.connect === 'function') {
plugin.connect(request.username, request.hostJid,
request.xmppAuth);
}
document.getElementById('title').innerText = request.hostName;
// Send an empty response since we have nothing to say.
sendResponse({});
}
/**
* This is the callback method that the plugin calls to request username and
* password for logging into the remote host.
*/
function pluginLoginChallenge() {
// Make the login panel visible.
document.getElementById("login_panel").style.display = "block";
}
/**
* This is the callback that the plugin invokes to indicate that the host/
* client connection status has changed.
*/
function pluginCallback() {
var status = chromoting.plugin.status;
var quality = chromoting.plugin.quality;
if (status == chromoting.plugin.STATUS_UNKNOWN) {
showClientStateMessage('');
} else if (status == chromoting.plugin.STATUS_CONNECTING) {
showClientStateMessage('Connecting to ' + chromoting.hostname +
' as ' + chromoting.username);
} else if (status == chromoting.plugin.STATUS_INITIALIZING) {
showClientStateMessage('Initializing connection to ' + chromoting.hostname);
} else if (status == chromoting.plugin.STATUS_CONNECTED) {
showClientStateMessage('Connected to ' + chromoting.hostname, 1000);
} else if (status == chromoting.plugin.STATUS_CLOSED) {
showClientStateMessage('Closed');
} else if (status == chromoting.plugin.STATUS_FAILED) {
showClientStateMessage('Failed');
}
}
/**
* Show a client message on the screen.
* If duration is specified, the message fades out after the duration expires.
* Otherwise, the message stays until the state changes.
*
* @param {string} message The message to display.
* @param {number} duration Milliseconds to show message before fading.
*/
function showClientStateMessage(message, duration) {
// Increment message id to ignore any previous fadeout requests.
chromoting.messageId++;
console.log('setting message ' + chromoting.messageId);
// Update the status message.
var msg = document.getElementById('status_msg');
msg.innerText = message;
msg.style.opacity = 1;
if (duration) {
// Set message duration.
window.setTimeout("fade('status_msg', " + chromoting.messageId + ", " +
"100, 10, 200)",
duration);
}
}
/**
* This is that callback that the plugin invokes to indicate that the
* host/client connection status has changed.
*/
function pluginCallback() {
var status = chromoting.plugin.status;
var quality = chromoting.plugin.quality;
if (status == chromoting.plugin.STATUS_UNKNOWN) {
setClientStateMessage('');
} else if (status == chromoting.plugin.STATUS_CONNECTING) {
setClientStateMessage('Connecting to ' + chromoting.hostname
+ ' as ' + chromoting.username);
} else if (status == chromoting.plugin.STATUS_INITIALIZING) {
setClientStateMessageFade('Initializing connection to ' +
chromoting.hostname);
} else if (status == chromoting.plugin.STATUS_CONNECTED) {
setClientStateMessageFade('Connected to ' + chromoting.hostname, 1000);
} else if (status == chromoting.plugin.STATUS_CLOSED) {
setClientStateMessage('Closed');
} else if (status == chromoting.plugin.STATUS_FAILED) {
setClientStateMessage('Failed');
}
}
/**
* Show a client message that stays on the screeen until the state changes.
*
* @param {string} message The message to display.
*/
function setClientStateMessage(message) {
// Increment message id to ignore any previous fadeout requests.
chromoting.messageId++;
console.log('setting message ' + chromoting.messageId);
// Update the status message.
var msg = document.getElementById('status_msg');
msg.innerText = message;
msg.style.opacity = 1;
}
/**
* Show a client message for the specified amount of time.
*
* @param {string} message The message to display.
* @param {number} duration Milliseconds to show message before fading.
*/
function setClientStateMessageFade(message, duration) {
setClientStateMessage(message);
// Set message duration.
window.setTimeout("fade('status_msg', " + chromoting.messageId + ", " +
"100, 10, 200)",
duration);
}
/**
* Fade the specified element.
* For example, to have element 'foo' fade away over 2 seconds, you could use
* either:
* fade('foo', 100, 10, 200)
* - Start at 100%, decrease by 10% each time, wait 200ms between updates.
* fade('foo', 100, 5, 100)
* - Start at 100%, decrease by 5% each time, wait 100ms between updates.
*
* @param {string} name Name of element to fade.
* @param {number} id The id of the message associated with this fade request.
* @param {number} val The new opacity value (0-100) for this element.
* @param {number} delta Amount to adjust the opacity each iteration.
* @param {number} delay Delay (in ms) to wait between each update.
*/
function fade(name, id, val, delta, delay) {
// Ignore the fade call if it does not apply to the current message.
if (id != chromoting.messageId) {
return;
}
var e = document.getElementById(name);
if (e) {
var newVal = val - delta;
if (newVal > 0) {
// Decrease opacity and set timer for next fade event.
e.style.opacity = newVal / 100;
window.setTimeout("fade('status_msg', " + id + ", " + newVal + ", " +
delta + ", " + delay + ")",
delay);
} else {
// Completely hide the text and stop fading.
e.style.opacity = 0;
}
}
}
| JavaScript | 0.000003 | @@ -963,32 +963,29 @@
l%22).
-className = %22login_pa
+style.display = %22no
ne
-l
%22;%0A
|
c9261681fbf590e6914513d7ea4a27f3eed6123c | Add more map tests. | test/map.js | test/map.js | "use strict";
var map = require("../map")
var into = require("../into")
exports["test map sequence"] = function(assert) {
var called = 0
var source = [ 1, 2, 3 ]
var actual = map(source, function(item) {
called = called + 1
return item + 10
})
assert.equal(called, 0, "map does not invokes until result is reduced")
assert.deepEqual(into(actual), [ 11, 12, 13 ], "values are mapped")
assert.equal(called, 3, "mapper called once per item")
}
exports["test map value"] = function(assert) {
var called = 0
var actual = map(7, function(item) {
called = called + 1
return item + 10
})
assert.equal(called, 0, "map does not invokes until result is reduced")
assert.deepEqual(into(actual), [ 17 ], "values is mapped")
assert.equal(called, 1, "mapper called once per item")
}
if (module == require.main)
require("test").run(exports)
| JavaScript | 0 | @@ -8,16 +8,184 @@
rict%22;%0A%0A
+var test = require(%22./util/test%22)%0Avar delay = require(%22../delay%22)%0Avar error = require(%22../error%22)%0Avar concat = require(%22../concat%22)%0Avar capture = require(%22../capture%22)%0A
var map
@@ -981,23 +981,986 @@
%0A%7D%0A%0A
-%0Aif (module ==
+exports%5B%22test map empty%22%5D = test(function(assert) %7B%0A var actual = map(%5B%5D, function(element) %7B%0A throw Error(%22map fn was executed%22)%0A %7D)%0A%0A assert(actual, %5B%5D, %22mapping empty is empty%22)%0A%7D)%0A%0A%0Aexports%5B%22test number map%22%5D = test(function(assert) %7B%0A var numbers = %5B1, 2, 3, 4%5D%0A var actual = map(numbers, function(number) %7B return number * 2 %7D)%0A%0A assert(actual, %5B2, 4, 6, 8%5D, %22numbers are doubled%22)%0A%7D)%0A%0Aexports%5B%22test map with async stream%22%5D = test(function(assert) %7B%0A var source = delay(%5B5, 4, 3, 2, 1%5D)%0A var actual = map(source, function(x) %7B return x + 1 %7D)%0A assert(actual, %5B6, 5, 4, 3, 2%5D, %22async number stream is incermented%22)%0A%7D)%0A%0Aexports%5B%22test map broken stream%22%5D = test(function(assert) %7B%0A var boom = Error(%22Boom!%22)%0A var source = concat(%5B3, 2, 1%5D, error(boom))%0A var mapped = map(delay(source), function(x) %7B return x * x %7D)%0A var actual = capture(mapped, function(error) %7B return error.message %7D)%0A%0A assert(actual, %5B9, 4, 1, boom.message%5D, %22errors propagate%22)%0A%7D)%0A%0Aif (
requ
@@ -1967,16 +1967,27 @@
ire.main
+ === module
)%0A requ
|
89cf31f3dcaba7d3a318209d78857fd05144ea67 | Add refactoring suggestion comments on block reducers file #275 | app/modules/mobilizations/blocks/reducers.js | app/modules/mobilizations/blocks/reducers.js | import c from '../../mobilizations/blocks/constants'
export const initialState = {
loaded: false,
data: [],
error: undefined,
uploadingBackgroundImage: false,
uploadedBackgroundImage: undefined,
}
export default function BlockReducers(state = initialState, action) {
let data
switch (action.type) {
//
// Async Actions
//
case c.REQUEST_ASYNC_BLOCK_FETCH:
return { ...state, loaded: false }
case c.SUCCESS_ASYNC_BLOCK_FETCH:
return { ...state, loaded: true, data: action.payload }
case c.FAILURE_ASYNC_BLOCK_FETCH:
return { ...state, loaded: true, error: action.payload }
case c.REQUEST_ASYNC_BLOCK_CREATE:
return { ...state, loaded: false }
case c.SUCCESS_ASYNC_BLOCK_CREATE:
return { ...state, loaded: true, data: state.data.concat([action.payload]) }
case c.FAILURE_ASYNC_BLOCK_CREATE:
return { ...state, loaded: true, error: action.payload }
case c.REQUEST_ASYNC_BLOCK_UPDATE:
return { ...state, loaded: false }
case c.SUCCESS_ASYNC_BLOCK_UPDATE:
data = state.data.map(block => block.id === action.payload.id ? action.payload : block)
return { ...state, loaded: true, data }
case c.FAILURE_ASYNC_BLOCK_UPDATE:
return { ...state, loaded: true, error: action.payload }
case c.REQUEST_ASYNC_BLOCK_SELECT:
return { ...state, loaded: false }
case c.SUCCESS_ASYNC_BLOCK_SELECT:
return { ...state, loaded: true, data: action.payload }
case c.FAILURE_ASYNC_BLOCK_SELECT:
return { ...state, loaded: true, error: action.payload }
case c.REQUEST_ASYNC_BLOCK_DESTROY:
return { ...state, loaded: false }
case c.SUCCESS_ASYNC_BLOCK_DESTROY:
data = state.data.filter(block => action.payload.id !== block.id)
return { ...state, loaded: true, data }
case c.FAILURE_ASYNC_BLOCK_DESTROY:
return { ...state, loaded: true, error: action.payload }
case c.REQUEST_ASYNC_BLOCK_MOVE_UP:
return { ...state, loaded: false }
case c.SUCCESS_ASYNC_BLOCK_MOVE_UP:
data = state.data.map((block, index) => {
if (index + 1 < state.data.length && state.data[index + 1].id === action.payload.id) {
return action.payload
} else if (block.id === action.payload.id) {
return state.data[index - 1]
}
return block
})
return { ...state, loaded: true, data }
case c.FAILURE_ASYNC_BLOCK_MOVE_UP:
return { ...state, loaded: true, error: action.payload }
case c.REQUEST_ASYNC_BLOCK_MOVE_DOWN:
return { ...state, loaded: false }
case c.SUCCESS_ASYNC_BLOCK_MOVE_DOWN:
data = state.data.map((block, index) => {
if (index > 0 && state.data[index - 1].id === action.payload.id) {
return action.payload
} else if (block.id === action.payload.id) {
return state.data[index + 1]
}
return block
})
return { ...state, loaded: true, data }
case c.FAILURE_ASYNC_BLOCK_MOVE_DOWN:
return { ...state, loaded: true, error: action.payload }
//
// Sync Actions
//
case c.BLOCK_SELECTED_LAYOUT:
return { ...state, selectedLayout: action.layout }
case c.BLOCK_BACKGROUND_IMAGE_UPLOADING:
return { ...state, uploadingBackgroundImage: action.uploading }
case c.BLOCK_BACKGROUND_IMAGE_UPLOADED:
return { ...state, uploadedBackgroundImage: action.image }
default:
return state
}
}
| JavaScript | 0 | @@ -202,16 +202,165 @@
ned,%0A%7D%0A%0A
+//%0A// TODO: Maybe split these reducers into separated files%0A// to turns more explicit what is its responsibility and let%0A// the code more cleaner%0A//%0A
export d
@@ -485,32 +485,138 @@
Actions%0A //%0A
+ // @suggestion: Maybe this block of code turns%0A // into a file called %60async-block-fetch-reducer%60?%0A
case c.REQUE
|
d26daa7a7ecebe9dd796a60e3b61fc8d4857c9d8 | refactor plugin | js/jquery.newsticker.js | js/jquery.newsticker.js | (function($) {
$.fn.newsticker = function(opts) {
var config = $.extend({}, {
height: 30,
speed: 800,
interval: 3000,
move: null
}, opts);
function init(obj) {
var $newsticker = obj,
$frame = $newsticker.find('.ui-newsticker-list'),
$item = $frame.find('.ui-newsticker-item'),
$next,
startPos = 0,
stop = false;
function init(){
var customizedHeight = parseInt($item.eq(0).css('height').split('px')[0]),
lineHeight = parseInt($newsticker.css('lineHeight').split('px')[0]);
$newsticker.css('height', config.height); //set customized height
startPos = (config.height - lineHeight) / 2; //re-write start position;
$frame.css('top', startPos);
$item.eq(0).addClass('current'); //set start item
suspend();
move();
};
function suspend(){
$newsticker.on('mouseover mouseout', function(e) {
if (e.type == 'mouseover') {
stop = true;
} else { //mouseout
stop = false;
}
});
};
function move(){
if($.isFunction(config.move)){
config.move.call(this);
} else {
setInterval(function() {
if (!stop) {
var $current = $frame.find('.current');
$frame.animate({
top: '-=' + config.height + 'px'
}, config.speed, function() {
$next = $frame.find('.current').next();
$next.addClass('current');
$current.removeClass('current');
$current.clone().appendTo($frame);
$current.remove();
$frame.css('top', startPos + 'px');
});
}
}, config.interval);
}
};
init();
}
this.each(function() {
init($(this));
});
return this;
};
})(jQuery); | JavaScript | 0.000001 | @@ -419,105 +419,217 @@
-function init()%7B%0A var customizedHeight = parseInt($item.eq(0).css('height').split('px')%5B0%5D
+//init settings%0A function init(ticker, height) %7B%0A var $ticker = $(ticker),%0A $frame = $ticker.find('.ui-newsticker-list'),%0A $firstItem = $frame.find('.ui-newsticker-item').eq(0
),%0A
@@ -662,20 +662,16 @@
rseInt($
-news
ticker.c
@@ -702,16 +702,22 @@
px')%5B0%5D)
+ %7C%7C 15
;%0A%0A
@@ -716,28 +716,24 @@
;%0A%0A $
-news
ticker.css('
@@ -741,23 +741,16 @@
eight',
-config.
height);
@@ -797,25 +797,27 @@
s =
- (config.
+calStartPos(
height
- -
+,
lin
@@ -828,65 +828,36 @@
ght)
- / 2; //re-write start position;%0A $frame.css('top'
+;%0A setStartPos($frame
, st
@@ -878,18 +878,17 @@
$
-item.eq(0)
+firstItem
.add
@@ -944,34 +944,374 @@
d();
-%0A move();%0A %7D;%0A
+ //trigger mouse event for suspending newsticker%0A move(); //activate newsticker%0A %7D;%0A%0A //calculate start position%0A function calStartPos(height, lineHeight) %7B%0A return (height - lineHeight) / 2;%0A %7D;%0A%0A //set start position%0A function setStartPos(frame, pos) %7B%0A frame.css('top', pos);%0A %7D;%0A%0A //suspend newsticker
%0A
@@ -1331,16 +1331,17 @@
uspend()
+
%7B%0A
@@ -1403,20 +1403,16 @@
-if (
e.type =
@@ -1412,16 +1412,17 @@
.type ==
+=
'mouseo
@@ -1429,78 +1429,24 @@
ver'
-) %7B%0A stop = true;%0A %7D else %7B //mouseout%0A
+ ? stop = true :
sto
@@ -1468,33 +1468,49 @@
- %7D%0A
+%7D);%0A
%7D
-)
;
+%0A
%0A
-%7D;%0A
+//activate newsticker
%0A
@@ -1527,16 +1527,17 @@
n move()
+
%7B%0A
@@ -2239,16 +2239,42 @@
init(
+$newsticker, config.height
);%0A %7D
|
978e2d4c732f195c1fe74d24f6b81666e249b12e | update js snippet with oo style | js/jquery.newsticker.js | js/jquery.newsticker.js | (function($) {
$.fn.newsticker = function(opts) {
// default configuration
var config = $.extend({}, {
height: 30,
speed: 800,
start: 8,
interval: 3000
}, opts);
// main function
function init(obj) {
var dNewsticker = obj,
dFrame = dNewsticker.find('.newsticker-list'),
dItem = dFrame.find('.newsticker-item'),
dNext,
stop = false;
dItem.eq(0).addClass('current');
setInterval(function() {
if (!stop) {
var dCurrent = dFrame.find('.current');
dFrame.animate({
top: '-=' + config.height + 'px'
}, config.speed, function() {
dNext = dFrame.find('.current').next();
dNext.addClass('current');
dCurrent.removeClass('current');
dCurrent.clone().appendTo(dFrame);
dCurrent.remove();
dFrame.css('top', config.start + 'px');
});
}
}, config.interval);
dNewsticker.on('mouseover mouseout', function(e) {
if (e.type == 'mouseover') {
stop = true;
} else { // mouseout
stop = false;
}
});
}
// initialize every element
this.each(function() {
init($(this));
});
return this;
};
// start
$(function() {
$('.newsticker').newsticker();
});
})(jQuery); | JavaScript | 0 | @@ -301,18 +301,18 @@
var
-dN
+$n
ewsticke
@@ -340,19 +340,19 @@
-dF
+$f
rame =
-dN
+$n
ewst
@@ -403,18 +403,18 @@
-dI
+$i
tem =
-dF
+$f
rame
@@ -456,18 +456,18 @@
-dN
+$n
ext,%0A
@@ -510,42 +510,461 @@
-dItem.eq(0).addClass('current');%0A%0A
+$newsticker.init = function()%7B%0A $newsticker.on('mouseover mouseout', function(e) %7B%0A if (e.type == 'mouseover') %7B%0A stop = true;%0A %7D else %7B // mouseout%0A stop = false;%0A %7D%0A %7D);%0A $item.eq(0).addClass('current');%0A $newsticker.move();%0A %7D;%0A%0A $newsticker.move = function()%7B%0A
@@ -1008,24 +1008,28 @@
+
+
if (!stop) %7B
@@ -1053,14 +1053,18 @@
+
var
-dC
+$c
urre
@@ -1064,26 +1064,26 @@
$current =
-dF
+$f
rame.find('.
@@ -1110,26 +1110,30 @@
-dF
+ $f
rame.animate
@@ -1159,16 +1159,20 @@
+
+
top: '-=
@@ -1196,16 +1196,20 @@
+ 'px'%0A
+
@@ -1278,18 +1278,22 @@
-dN
+ $n
ext =
-dF
+$f
rame
@@ -1342,18 +1342,22 @@
-dN
+ $n
ext.addC
@@ -1389,34 +1389,38 @@
-dC
+ $c
urrent.removeCla
@@ -1454,26 +1454,30 @@
+
-dC
+ $c
urrent.clone
@@ -1488,18 +1488,18 @@
ppendTo(
-dF
+$f
rame);%0A
@@ -1521,18 +1521,22 @@
-dC
+ $c
urrent.r
@@ -1572,10 +1572,14 @@
-dF
+ $f
rame
@@ -1624,32 +1624,36 @@
+
%7D);%0A
@@ -1648,34 +1648,41 @@
-%7D%0A
+ %7D%0A
%7D, c
@@ -1669,32 +1669,33 @@
%0A
+
%7D, config.interv
@@ -1699,17 +1699,16 @@
erval);%0A
-%0A
@@ -1715,239 +1715,41 @@
-dNewsticker.on('mouseover mouseout', function(e) %7B%0A if (e.type == 'mouseover') %7B%0A stop = true;%0A %7D else %7B // mouseout%0A stop = false;%0A %7D%0A %7D
+%7D;%0A%0A $newsticker.init(
);%0A
|
1d6a42ab8ca3cf859fa7f13e750dc4d67907ebc5 | add mocks module to family specs | app/scripts/superdesk-archive/family_spec.js | app/scripts/superdesk-archive/family_spec.js | 'use strict';
describe('familyService', function() {
var items = [
{_id: 'z', family_id: 'family1', task: {desk: 'desk1'}},
{_id: 'x', family_id: 'family1', task: {desk: 'desk2'}},
{_id: 'c', family_id: 'family2', task: {desk: 'desk3'}}
];
var deskList = {
desk1: {title: 'desk1'},
desk3: {title: 'desk3'}
};
beforeEach(module('superdesk.archive.directives'));
beforeEach(module(function($provide) {
$provide.service('api', function($q) {
return function() {
return {
query: function(params) {
var familyId = params.source.query.filtered.filter.and[1].term.family_id;
var members = _.filter(items, {family_id: familyId});
if (params.source.query.filtered.filter.and[2]) {
_.remove(members, {_id: params.source.query.filtered.filter.and[2].not.term._id});
}
return $q.when({_items: members});
}
};
};
});
$provide.service('desks', function() {
return {
deskLookup: deskList
};
});
}));
it('can fetch members of a family', inject(function($rootScope, familyService, api) {
var members = null;
familyService.fetchItems('family1')
.then(function(result) {
members = result;
});
$rootScope.$digest();
expect(members._items.length).toBe(2);
}));
it('can fetch members of a family with exclusion', inject(function($rootScope, familyService, api) {
var members = null;
familyService.fetchItems('family1', {_id: 'z'})
.then(function(result) {
members = result;
});
$rootScope.$digest();
expect(members._items.length).toBe(1);
}));
it('can fetch desks of members of a family', inject(function($rootScope, familyService, api, desks) {
var memberDesks = null;
familyService.fetchDesks({_id: 'z', family_id: 'family1'})
.then(function(result) {
memberDesks = result;
});
$rootScope.$digest();
expect(memberDesks.length).toBe(1);
}));
it('can fetch desks of members of a family with exclusion', inject(function($rootScope, familyService, api, desks) {
var memberDesks = null;
familyService.fetchDesks({_id: 'z', family_id: 'family1'}, true)
.then(function(result) {
memberDesks = result;
});
$rootScope.$digest();
expect(memberDesks.length).toBe(0);
}));
});
| JavaScript | 0.000001 | @@ -360,16 +360,59 @@
%7D;%0A%0A
+ beforeEach(module('superdesk.mocks'));%0A
befo
@@ -598,32 +598,140 @@
return %7B%0A
+ find: function() %7B%0A return $q.reject(%7B%7D);%0A %7D,%0A
|
fa778d8c4c0ec30fad3ed4adeb12434bd2c43aff | Revert "tmp: debug estDocCount" | lib/analytics/stats-queryer.js | lib/analytics/stats-queryer.js | var async = require('async');
var Report = require('../../models/report');
var Incident = require('../../models/incident');
var _ = require('underscore');
var ONE_MINUTE = 60 * 1000;
var StatsQueryer = function() {
this.handlers = {
all: this._countAll,
incidents: this._countAllIncidents,
reports: this._countAllReports,
interval: this._countReportsPerMinute
};
};
StatsQueryer.prototype.count = function(type, callback) {
type || (type = 'all');
var handler = this.handlers[type];
var self = this;
if (!handler) return callback(new Error('Handler not found'));
handler.call(this, callback);
};
StatsQueryer.prototype._countReports = function(query, callback) {
query || (query = {});
// DO NOT REMOVE: substantially improves Aggie performance
if (_.isEmpty(query)) {
Report.estimatedDocumentCount({}, (err, count) => {
console.log(`AAAAHHHHHHHHH: ${count}`)
callback(err, count)
});
} else {
Report.countDocuments(query, callback);
}
};
StatsQueryer.prototype._countIncidents = function(query, callback) {
query || (query = {});
Incident.countDocuments(query, callback);
};
StatsQueryer.prototype._countAllReports = function(callback) {
async.parallel({
totalReports: this._countReports,
totalReportsUnread: this._countReports.bind(this, { read: false }),
totalReportsTagged: this._countReports.bind(this, { smtcTags: {$type: "objectId" }}),
totalReportsEscalated: this._countReports.bind(this, { escalated: true }),
totalReportsPerMinute: this._countReports.bind(this, { storedAt: { $gte: minuteAgo() } }),
}, callback);
};
StatsQueryer.prototype._countReportsPerMinute = function(callback) {
return this._countReports({ storedAt: { $gte: minuteAgo() } }, function(err, results) {
if (err) return callback(err);
callback(err, { totalReportsPerMinute: results });
});
};
StatsQueryer.prototype._countAllIncidents = function(callback) {
async.parallel({
totalIncidents: this._countIncidents,
totalEscalatedIncidents: this._countIncidents.bind(this, { escalated: true })
}, callback);
};
StatsQueryer.prototype._countAll = function(callback) {
var self = this;
async.parallel({
reports: this._countAllReports.bind(this),
incidents: this._countAllIncidents.bind(this)
}, function(err, results) {
if (err) return callback(err);
_.extend(results.reports, results.incidents);
callback(null, results.reports);
});
};
// helpers
function minuteAgo() {
var now = new Date();
return new Date(now.getTime() - ONE_MINUTE);
}
module.exports = StatsQueryer;
| JavaScript | 0 | @@ -846,103 +846,16 @@
%7B%7D,
-(err, count) =%3E %7B%0A console.log(%60AAAAHHHHHHHHH: $%7Bcount%7D%60)%0A callback(err, count)%0A %7D
+callback
);%0A
|
a076b27e970b3cbcffd6df7d088618b3d12f9077 | Fix Bowser8 remapping | js/randomizer.bowser.js | js/randomizer.bowser.js | var bowserentrances = [
{"name": "frontdoor", "world": 10, "exits": -1, "castle": 0, "palace": 0, "ghost": 0, "water": 0, "id": 0x10D},
{"name": "backdoor", "world": 10, "exits": -1, "castle": 0, "palace": 0, "ghost": 0, "water": 0, "id": 0x10E},
];
var BOWSER_DARKROOM_ID = 0x1BD;
function randomizeBowserEntrances(random, map, rom)
{
backupData(bowserentrances, rom);
shuffle(bowserentrances, random);
for (var i = 0; i < bowserentrances.length; ++i)
performCopy(bowserentrances[i], map, rom);
}
var bowser8doors = [ 0x1D4, 0x1D3, 0x1D2, 0x1D1, 0x1CF, 0x1CE, 0x1CD, 0x1CC ];
function randomizeBowser8Doors(random, rom)
{
// get a list of rooms
var rooms = [];
for (var i = 0; i < bowser8doors.length; ++i)
{
// get the location that this room exits to
var id = bowser8doors[i];
var exits = getScreenExits(id, rom);
// save this information
rooms.push({ out: exits[0], sublevel: id });
}
rooms.shuffle(random);
var hold0 = findOpenSublevel(0x100, rom);
moveSublevel(hold0, rooms[0].sublevel, rom);
for (var i = 1; i < rooms.length; ++i)
{
moveSublevel(rooms[i-1].sublevel, rooms[i].sublevel, rom);
rom[rooms[i-1].out.addr+3] = rooms[i].target & 0xFF;
}
moveSublevel(rooms[rooms.length-1].sublevel, hold0, rom);
rom[rooms[rooms.length-1].out.addr+3] = rooms[0].target & 0xFF;
}
function generateGauntlet(random, rom)
{
// get a list of rooms
var rooms = bowser8doors.slice(0).shuffle(random), numrooms = rooms.length;
rooms.push(BOWSER_DARKROOM_ID);
// copy the first room into both castle entrances
for (var i = 0; i < bowserentrances.length; ++i)
copySublevel(bowserentrances[i].id, rooms[0], rom);
// chain together all 8 rooms \("v")/
for (var i = 0; i < numrooms; ++i)
{
var exits = getScreenExits(rooms[i], rom);
for (var j = 0; j < exits.length; ++j)
rom[exits[j].addr+3] = rooms[i+1] & 0xFF;
}
} | JavaScript | 0 | @@ -1179,16 +1179,20 @@
ooms%5Bi%5D.
+out.
target &
@@ -1310,16 +1310,20 @@
ooms%5B0%5D.
+out.
target &
|
1bb82fcce9b880555695c17a999c283b3ec36df8 | Use local appPath since sails.config.appPath doesnt exist yet | lib/app/configuration/index.js | lib/app/configuration/index.js | /**
* Module dependencies.
*/
var _ = require('lodash');
var path = require('path');
var fs = require('fs');
var DEFAULT_HOOKS = require('./defaultHooks');
module.exports = function(sails) {
/**
* Expose new instance of `Configuration`
*/
return new Configuration();
function Configuration() {
/**
* Sails default configuration
*
* @api private
*/
this.defaults = function defaultConfig(appPath) {
var defaultEnv;
// If we're not loading the userconfig hook, which normally takes care
// of ensuring that we have an environment, then make sure we set one here.
// TODO: Is this the best way of checking that userconfig is off?
if (sails.config.hooks && sails.config.hooks.userconfig === false ||
(sails.config.loadHooks && sails.config.loadHooks.indexOf('userconfig') == -1)
) {
defaultEnv = sails.config.environment || "development";
}
// If `appPath` not specified, unfortunately, this is a fatal error,
// since reasonable defaults cannot be assumed
if (!appPath) {
throw new Error('No `appPath` specified!');
}
// Set up config defaults
return {
environment: defaultEnv,
// Default hooks
// TODO: remove hooks from config to avoid confusion
// (because you can't configure hooks in `userconfig`-- only in `overrides`)
hooks: _.reduce(DEFAULT_HOOKS, function (memo, hookName) {
memo[hookName] = require('../../hooks/'+hookName);
return memo;
}, {}),
// Save appPath in implicit defaults
// appPath is passed from above in case `sails lift` was used
// This is the directory where this Sails process is being initiated from.
// ( usually this means `process.cwd()` )
appPath: appPath,
// Variables which will be made globally accessible
// (if `globals:false` is set, all globals will be disabled)
globals: {
_: true,
async: true,
sails: true
},
// Built-in path defaults
paths: {
tmp: path.resolve(sails.config.appPath, '.tmp')
},
// Start off `routes` and `middleware` as empty objects
routes: {},
middleware: {}
};
},
/**
* Load the configuration modules
*
* @api private
*/
this.load = require('./load')(sails);
// Bind the context of all instance methods
_.bindAll(this);
}
};
| JavaScript | 0 | @@ -2153,29 +2153,16 @@
resolve(
-sails.config.
appPath,
|
40f62338dd7fd3e0b516db25e6b31422689c42a4 | Add a function that creates a function with identical execution context as the current one. | js/shared/javascript.js | js/shared/javascript.js |
exports.bind = function(context, method/*, args... */) {
var args = Array.prototype.slice.call(arguments, 2)
return function() {
fn = (typeof method == 'string' ? context[method] : method)
return fn.apply(context, args.concat(Array.prototype.slice.call(arguments, 0)))
}
}
exports.forEach = function(items, ctx, fn) {
if (!items) { return }
if (!fn) { fn = ctx, ctx = this }
if (exports.isArray(items)) {
for (var i=0, item; item = items[i]; i++) { fn.call(ctx, item, i) }
} else {
for (var key in items) { fn.call(ctx, key, items[key]) }
}
}
exports.map = function(items, fn) {
var results = []
exports.forEach(items, function(item) { results.push(fn(item)) })
return results
}
exports.Class = function(parent, proto) {
if(!proto) { proto = parent }
proto.prototype = parent.prototype
var cls = function() { if(this.init) { this.init.apply(this, arguments) }}
cls.prototype = new proto(function(context, method, args) {
var target = parent
while(target = target.prototype) {
if(target[method]) {
return target[method].apply(context, args || [])
}
}
throw new Error('supr: parent method ' + method + ' does not exist')
})
// Sometimes you want a method that renders UI to only execute once if it's called
// multiple times within a short time period. Delayed methods do just that
cls.prototype.createDelayedMethod = function(methodName, fn) {
// "this" is the class
this[methodName] = function() {
// now "this" is the instance. Each instance gets its own function
var executionTimeout
this[methodName] = bind(this, function() {
clearTimeout(executionTimeout)
executionTimeout = setTimeout(bind(fn, 'apply', this, arguments), 10)
})
}
}
cls.prototype.constructor = cls
return cls
}
exports.Singleton = function(parent, proto) {
return new (exports.Class(parent, proto))()
}
var stripRegexp = /^\s*(.*?)\s*$/
exports.strip = function(str) {
return str.match(stripRegexp)[1]
}
exports.capitalize = function(str) {
if (!str) { return '' }
return str[0].toUpperCase() + str.substring(1)
}
exports.isArray = function(obj) {
return Object.prototype.toString.call(obj) === '[object Array]'
}
exports.blockCallback = function(callback) {
var blocks = 0
function removeBlock(err) {
if (err) { throw err }
setTimeout(function() { if (--blocks == 0) callback() })
}
return {
addBlock: function() {
blocks++
return removeBlock
},
tryNow: function() {
if (blocks == 0) callback()
}
}
}
exports.bytesToString = function(byteArray, offset) {
return byteArray.toString();
return String.fromCharCode.apply(String, Array.prototype.slice.call(byteArray, offset || 0))
}
| JavaScript | 0.999999 | @@ -2672,12 +2672,135 @@
et %7C%7C 0))%0A%7D%0A
+%0Aexports.recall = function(self, args, timeout) %7B%0A%09var fn = args.callee%0A%09return function()%7B return fn.apply(self, args) %7D%0A%7D
|
e8bd69e43372a1b6d46439585a787869e3c44595 | Change name of xcuitest automation name | lib/basedriver/desired-caps.js | lib/basedriver/desired-caps.js | import log from './logger';
import validator from 'validate.js';
import B from 'bluebird';
let desiredCapabilityConstraints = {
platformName: {
presence: true,
isString: true,
inclusionCaseInsensitive: [
'iOS',
'Android',
'FirefoxOS',
'Fake'
]
},
deviceName: {
presence: true,
isString: true
},
platformVersion: {},
newCommandTimeout: {
isNumber: true
},
automationName: {
inclusionCaseInsensitive: [
'Appium',
'Selendroid',
'WebDriverAgent',
'YouiEngine'
]
},
autoLaunch: {
isBoolean: true
},
udid: {
isString: true
},
orientation: {
inclusion: [
'LANDSCAPE',
'PORTRAIT'
]
},
autoWebview: {
isBoolean: true
},
noReset: {
isBoolean: true
},
fullReset: {
isBoolean: true
},
language: {
isString: true
},
locale: {
isString: true
}
};
validator.validators.isString = function (value) {
if (typeof value === 'string') {
return null;
}
if (typeof value === 'undefined') {
return null;
}
return 'must be of type string';
};
validator.validators.isNumber = function (value) {
if (typeof value === 'number') {
return null;
}
if (typeof value === 'undefined') {
return null;
}
return 'must be of type number';
};
validator.validators.isBoolean = function (value) {
if (typeof value === 'boolean') {
return null;
}
// allow a string value
if (typeof value === 'string' &&
((value.toLowerCase() === 'true' || value.toLowerCase() === 'false') ||
(value === ''))) {
log.warn('Boolean capability passed in as string. Functionality may be compromised.');
return null;
}
if (typeof value === 'undefined') {
return null;
}
return 'must be of type boolean';
};
validator.validators.isObject = function (value) {
if (typeof value === 'object') {
return null;
}
if (typeof value === 'undefined') {
return null;
}
return 'must be of type object';
};
validator.validators.deprecated = function (value, options, key) {
if (options) {
log.warn(`${key} is a deprecated capability`);
}
return null;
};
validator.validators.inclusionCaseInsensitive = function (value, options) {
if (typeof value === 'undefined') {
return null;
} else if (typeof value !== 'string') {
return 'unrecognised';
}
for (let option of options) {
if (option.toLowerCase() === value.toLowerCase()) {
return null;
}
}
return `${value} not part of ${options.toString()}`;
};
validator.promise = B;
validator.prettify = (val) => { return val; };
export { desiredCapabilityConstraints, validator };
| JavaScript | 0.000001 | @@ -515,21 +515,15 @@
'
-WebDriverAgen
+XCUITes
t',%0A
|
3b08a76c82515e1d245d1abee32c0ff62f86f343 | Update presets.js | lib/core/src/server/presets.js | lib/core/src/server/presets.js | import dedent from 'ts-dedent';
import { join } from 'path';
import { logger } from '@storybook/node-logger';
import fs from 'fs'
import { resolveFile } from './utils/resolve-file';
const isObject = (val) => val != null && typeof val === 'object' && Array.isArray(val) === false;
const isFunction = (val) => typeof val === 'function';
// Copied out of parse-package-name
// '@storybook/addon-actions/register' => ( name: '@storybook/addon-actions', path: '/register', version: '' )
const RE_SCOPED = /^(@[^/]+\/[^/@]+)(?:\/([^@]+))?(?:@([\s\S]+))?/;
const RE_NORMAL = /^([^/@]+)(?:\/([^@]+))?(?:@([\s\S]+))?/;
function parsePackageName(input) {
if (typeof input !== 'string') {
throw new TypeError('Expected a string');
}
const matched = input.startsWith('@') ? input.match(RE_SCOPED) : input.match(RE_NORMAL);
if (!matched) {
throw new Error(`[parse-package-name] "${input}" is not a valid string`);
}
return {
name: matched[1],
path: matched[2] || '',
version: matched[3] || '',
};
}
const resolvePresetFunction = (input, presetOptions, storybookOptions) => {
if (isFunction(input)) {
return input({ ...storybookOptions, ...presetOptions });
}
if (Array.isArray(input)) {
return input;
}
return [];
};
const isLocalFileImport = (packageName) => fs.existsSync(packageName);
/**
* Parse an addon into either a managerEntry or a preset. Throw on invalid input.
*
* Valid inputs:
* - '@storybook/addon-actions/register'
* => { type: 'managerEntries', item }
*
* - '@storybook/addon-docs/preset'
* => { type: 'presets', item }
*
* - '@storybook/addon-docs'
* => { type: 'presets', item: '@storybook/addon-docs/preset' }
*
* - { name: '@storybook/addon-docs(/preset)?', options: { ... } }
* => { type: 'presets', item: { name: '@storybook/addon-docs/preset', options } }
*/
export const resolveAddonName = (name) => {
let path;
if (isLocalFileImport(name)) {
path = name;
} else {
({ path } = parsePackageName(name));
}
// when user provides full path, we don't need to do anything
if (path) {
return {
name,
// Accept `register`, `register.js`, `require.resolve('foo/register'), `register-panel`
type: path.match(/register(-panel)?(.js)?$/) ? 'managerEntries' : 'presets',
};
}
try {
return {
name: resolveFile(join(name, 'preset')),
type: 'presets',
};
// eslint-disable-next-line no-empty
} catch (err) {}
try {
return {
name: resolveFile(join(name, 'register')),
type: 'managerEntries',
};
// eslint-disable-next-line no-empty
} catch (err) {}
return { name, type: 'presets' };
};
export const splitAddons = (addons) => {
return addons.reduce(
(acc, item) => {
try {
if (isObject(item)) {
const { name } = resolveAddonName(item.name);
acc.presets.push({ ...item, name });
} else {
const { name, type } = resolveAddonName(item);
acc[type].push(name);
}
} catch (err) {
logger.error(
`Addon value should end in /register OR it should be a valid preset https://storybook.js.org/docs/presets/introduction/\n${item}`
);
}
return acc;
},
{
managerEntries: [],
presets: [],
}
);
};
function interopRequireDefault(filePath) {
// eslint-disable-next-line global-require,import/no-dynamic-require
const result = require(`${filePath}`);
const isES6DefaultExported =
typeof result === 'object' && result !== null && typeof result.default !== 'undefined';
return isES6DefaultExported ? result.default : result;
}
function loadPreset(input, level, storybookOptions) {
try {
const name = input.name ? input.name : input;
const presetOptions = input.options ? input.options : {};
let contents = interopRequireDefault(name);
if (typeof contents === 'function') {
// allow the export of a preset to be a function, that gets storybookOptions
contents = contents(storybookOptions);
}
if (Array.isArray(contents)) {
const subPresets = contents;
return loadPresets(subPresets, level + 1, storybookOptions);
}
if (isObject(contents)) {
const { addons: addonsInput, presets: presetsInput, ...rest } = contents;
const subPresets = resolvePresetFunction(presetsInput, presetOptions, storybookOptions);
const subAddons = resolvePresetFunction(addonsInput, presetOptions, storybookOptions);
const { managerEntries, presets } = splitAddons(subAddons);
return [
...loadPresets([...subPresets, ...presets], level + 1, storybookOptions),
{ name: `${name}_additionalManagerEntries`, preset: { managerEntries } },
{
name,
preset: rest,
options: presetOptions,
},
];
}
throw new Error(dedent`
${input} is not a valid preset
`);
} catch (e) {
const warning =
level > 0
? ` Failed to load preset: ${JSON.stringify(input)} on level ${level}`
: ` Failed to load preset: ${JSON.stringify(input)}`;
logger.warn(warning);
logger.error(e);
return [];
}
}
function loadPresets(presets, level, storybookOptions) {
if (!presets || !Array.isArray(presets) || !presets.length) {
return [];
}
if (!level) {
logger.info('=> Loading presets');
}
return presets.reduce((acc, preset) => {
const loaded = loadPreset(preset, level, storybookOptions);
return acc.concat(loaded);
}, []);
}
function applyPresets(presets, extension, config, args, storybookOptions) {
const presetResult = new Promise((resolve) => resolve(config));
if (!presets.length) {
return presetResult;
}
return presets.reduce((accumulationPromise, { preset, options }) => {
const change = preset[extension];
if (!change) {
return accumulationPromise;
}
if (typeof change === 'function') {
const extensionFn = change;
const context = {
extensionFn,
preset,
combinedOptions: { ...storybookOptions, ...args, ...options, presetsList: presets },
};
return accumulationPromise.then((newConfig) =>
context.extensionFn.call(context.preset, newConfig, context.combinedOptions)
);
}
return accumulationPromise.then((newConfig) => {
if (Array.isArray(newConfig) && Array.isArray(change)) {
return [...newConfig, ...change];
}
if (isObject(newConfig) && isObject(change)) {
return { ...newConfig, ...change };
}
return change;
});
}, presetResult);
}
function getPresets(presets, storybookOptions) {
const loadedPresets = loadPresets(presets, 0, storybookOptions);
return {
apply: async (extension, config, args = {}) =>
applyPresets(loadedPresets, extension, config, args, storybookOptions),
};
}
export default getPresets;
| JavaScript | 0.000001 | @@ -122,16 +122,17 @@
rom 'fs'
+;
%0Aimport
|
4b1ca537c83d47db5346fad8c26fe468741753b3 | document the login responder | lib/helpers/login-responder.js | lib/helpers/login-responder.js | 'use strict';
var createSession = require('./create-session');
var createIdSiteSession = require('./create-id-site-session');
function loginResponse(req, res) {
var config = req.app.get('stormpathConfig');
var accepts = req.accepts(['html', 'json']);
var redirectUrl = config.web.login.nextUri;
var url = req.query.next || redirectUrl;
if (accepts === 'json') {
return res.end();
}
res.redirect(302, url);
}
module.exports = function(passwordGrantAuthenticationResult, account, req, res) {
var config = req.app.get('stormpathConfig');
var postLoginHandler = config.postLoginHandler;
if (passwordGrantAuthenticationResult) {
createSession(passwordGrantAuthenticationResult, account, req, res);
} else {
createIdSiteSession(account, req, res);
}
if (postLoginHandler) {
postLoginHandler(req.user, req, res, function() {
loginResponse(req, res);
});
} else {
loginResponse(req, res);
}
};
| JavaScript | 0 | @@ -121,16 +121,274 @@
ion');%0A%0A
+/**%0A * If the request has the Accept header set to json, it will respond by just ending the response.%0A * Else it will redirect to the configured url.%0A *%0A * @method%0A *%0A * @param %7BObject%7D req - The http request.%0A * @param %7BObject%7D res - The http response.%0A */%0A
function
@@ -682,16 +682,414 @@
rl);%0A%7D%0A%0A
+/**%0A * Takes a password grant authentication result and an account together with an%0A * http request and response and responds with a new session if successful.%0A *%0A * @method%0A *%0A * @param %7BObject%7D passwordGrantAuthenticationResult - The authentication result.%0A * @param %7BObject%7D account - Account to log in.%0A * @param %7BObject%7D req - The http request.%0A * @param %7BObject%7D res - The http response.%0A */%0A
module.e
|
f868b4e836c7922e51c18826d35c1f1d3721f5df | fix constructor params | lib/me.publicize-connection.js | lib/me.publicize-connection.js | const root = '/me/publicize-connections/';
class PublicizeConnection {
/**
* `PublicizeConnection` constructor.
*
* @param {String} connectionId - application identifier
* @param {WPCOM} wpcom - wpcom instance
* @return {Null} null
*/
constructor( connectionId, wpcom ) {
if ( ! ( this instanceof PublicizeConnection ) ) {
return new PublicizeConnection( wpcom );
}
this._id = connectionId;
this.wpcom = wpcom;
}
/**
* Get a single publicize connection that the current user has set up.
*
* @param {Object} [query] - query object parameter
* @param {Function} fn - callback function
* @return {Function} request handler
*/
get( query, fn ) {
return this.wpcom.req.get( root + this._id, query, fn );
}
/**
* Add a publicize connection belonging to the current user.
*
* @param {Object} [query] - query object parameter
* @param {Object} body - body object parameter
* @param {Function} fn - callback function
* @return {Function} request handler
*/
add( query, body, fn ) {
return this.wpcom.req.post( root + 'new', query, body, fn );
}
/**
* Update a publicize connection belonging to the current user.
*
* @param {Object} [query] - query object parameter
* @param {Object} body - body object parameter
* @param {Function} fn - callback function
* @return {Function} request handler
*/
update( query, body, fn ) {
return this.wpcom.req.put( root + this._id, query, body, fn );
}
/**
* Delete the app of the current user
* through of the given connectionId
*
* @param {Object} [query] - query object parameter
* @param {Function} fn - callback function
* @return {Function} request handler
*/
delete( query, fn ) {
return this.wpcom.req.del( root + this._id + '/delete', query, fn );
}
}
/**
* Expose `PublicizeConnection` module
*/
module.exports = PublicizeConnection;
| JavaScript | 0.000001 | @@ -361,16 +361,30 @@
nection(
+ connectionId,
wpcom )
|
88d3861b79a453ced3251dce8a2b31b5c79083ec | Fix dependency collection | lib/mincer/assets/processed.js | lib/mincer/assets/processed.js | /** internal
* class ProcessedAsset
*
* `ProcessedAsset`s are internal representation of processable files.
*
*
* ##### SUBCLASS OF
*
* [[Asset]]
**/
'use strict';
// 3rd-party
var _ = require('underscore');
var async = require('async');
// internal
var noop = require('../common').noop;
var prop = require('../common').prop;
var getter = require('../common').getter;
var Asset = require('./asset');
////////////////////////////////////////////////////////////////////////////////
// internal class used to build dependency graph
function DependencyFile(pathname, mtime, digest) {
prop(this, 'pathname', pathname);
prop(this, 'mtime', mtime);
prop(this, 'digest', digest);
prop(this, 'hash', '<DependnecyFile ' + JSON.stringify(this) + '>');
}
////////////////////////////////////////////////////////////////////////////////
/**
* new ProcessedAsset()
*
* See [[Asset.new]] for details.
**/
var ProcessedAsset = module.exports = function ProcessedAsset() {
Asset.apply(this, arguments);
prop(this, 'type', 'processed');
};
require('util').inherits(ProcessedAsset, Asset);
/**
* ProcessedAsset#isFresh(environment) -> Boolean
* - environment (Environment|Index)
*
* Checks if Asset is stale by comparing the actual mtime and
* digest to the inmemory model.
**/
ProcessedAsset.prototype.isFresh = function (environment) {
return _.all(this.__dependencyPaths__, function (dep) {
return Asset.isDependencyFresh(environment, dep);
});
};
// recursively iterate over all requried assets,
// gather a list of (compiling if needed) assets that should be required
function resolve_dependencies(self, paths, callback) {
var assets = [], cache = {}, done;
// async callback
done = function (err) {
callback(err, assets);
};
async.forEachSeries(paths, function (p, next) {
var asset;
if (p === self.pathname) {
if (!cache[p]) {
cache[p] = true;
assets.push(self);
}
next();
return;
}
asset = self.environment.findAsset(p, {bundle: false});
if (asset) {
asset.compile(function (err, asset) {
if (err) {
next(err);
return;
}
asset.__requiredAssets__.forEach(function (asset_dependency) {
if (!cache[asset_dependency.pathname]) {
cache[asset_dependency.pathname] = true;
assets.push(asset_dependency);
}
});
next();
});
return;
}
// else
next();
}, done);
}
// build all required assets
function build_required_assets(self, context, callback) {
var assets, stubs;
async.series([
function (next) {
var paths = context.__requiredPaths__.concat([self.pathname]);
resolve_dependencies(self, paths, function (err, arr) {
assets = arr;
next(err);
});
},
function (next) {
resolve_dependencies(self, context.__stubbedAssets__, function (err, arr) {
stubs = arr;
next(err);
});
},
function (next) {
prop(self, '__requiredAssets__', _.without(assets, stubs));
next();
}
], callback);
}
// prepare an ordered list (map) of dependencies
function build_dependency_paths(self, context, callback) {
var dependency_paths = {};
context.__dependencyPaths__.forEach(function (p) {
var dep = new DependencyFile(p, self.environment.stat(p).mtime,
self.environment.getFileDigest(p));
dependency_paths[dep.hash] = dep;
});
async.forEachSeries(context.__dependencyAssets__, function (p, next) {
var dep, asset;
if (p === self.pathname) {
dep = new DependencyFile(p, self.environment.stat(p).mtime,
self.environment.getFileDigest(p));
dependency_paths[dep.hash] = dep;
next();
return;
}
asset = self.environment.findAsset(p, {bundle: false});
if (asset) {
asset.compile(function (err) {
if (err) {
next(err);
return;
}
asset.dependencyPaths.forEach(function (d) {
dependency_paths[d.hash] = d;
});
next();
});
return;
}
next();
}, function (err) {
prop(self, '__dependencyPaths__', Object.keys(dependency_paths));
callback(err);
});
}
// return digest based on digests of all dependencies
function compute_dependency_digest(self) {
return _.inject(self.requiredAssets, function (digest, asset) {
return digest.update(asset.digest);
}, self.environment.digest).digest('hex');
}
// See apidoc of [[Asset#compile]]
ProcessedAsset.prototype.compile = function (callback) {
var self = this, Klass, context, options;
// make sure callback is callable
callback = callback || noop;
// do not compile again once asset was compiled
if (this.isCompiled) {
callback(null, this);
return;
}
// prepare to build ourself
Klass = this.environment.ContextClass;
context = new Klass(this.environment, this.logicalPath, this.pathname);
context.evaluate(self.pathname, options, function (err, source) {
var tasks;
if (err) {
callback(err);
return;
}
// TODO: Remove once laszySources would be dropped
source = _.isString(source) ? source : source.toString();
// save rendered string
prop(self, '__buffer__', new Buffer(source));
// update some props
self.length = Buffer.byteLength(source);
self.digest = self.environment.digest.update(source).digest('hex');
// run after-compile tasks
tasks = [
function (next) { build_required_assets(self, context, next); },
function (next) { build_dependency_paths(self, context, next); }
];
async.series(tasks, function (err) {
prop(self, 'dependencyDigest', compute_dependency_digest(self));
callback(err, self);
});
});
};
// See apidoc of [[Asset#buffer]]
getter(ProcessedAsset.prototype, 'buffer', function () {
this._requireCompilation('buffer');
return this.__buffer__;
});
// See apidoc of [[Asset#source]]
getter(ProcessedAsset.prototype, 'source', function () {
return this.buffer.toString('utf8');
});
// See [[Asset#isCompiled]] documentation
getter(ProcessedAsset.prototype, 'isCompiled', function () {
return !!this.__buffer__;
});
| JavaScript | 0.000002 | @@ -620,28 +620,21 @@
%7B%0A
-prop(
this
-, '
+.
pathname
',
@@ -629,19 +629,18 @@
pathname
-',
+=
pathnam
@@ -644,153 +644,59 @@
name
-)
;%0A
-prop(
this
-, '
+.
mtime
-',
+=
mtime
-)
;%0A
-prop(
this
-, '
+.
digest
-',
+=
digest
-);%0A prop(this, 'hash', '%3CDependnecyFile ' + JSON.stringify(this) + '%3E')
;%0A%7D%0A
@@ -3423,32 +3423,43 @@
dency_paths%5B
-dep.hash
+JSON.stringify(dep)
%5D = dep;%0A %7D
@@ -3747,16 +3747,27 @@
ths%5B
-dep.hash
+JSON.stringify(dep)
%5D =
@@ -4038,16 +4038,18 @@
ction (d
+ep
) %7B%0A
@@ -4075,19 +4075,34 @@
ths%5B
-d.hash
+JSON.stringify(dep)
%5D = d
+ep
;%0A
@@ -4235,18 +4235,15 @@
_',
-Object.key
+_.value
s(de
|
af3224dee1a02079e9d84d361276026d424c5e1d | delete code repetition | lib/mobile-browser-emulator.js | lib/mobile-browser-emulator.js | var Proxy = require('browsermob-proxy').Proxy;
function run(url, browserWidth, browserHeight, display, cb) {
var proxy = new Proxy({port: 8080});
var generate_traffic = function (proxyAddr, done) {
startBrowser(url, browserWidth, browserHeight, display, cb, proxyAddr, done);
};
proxy.cbHAR({name: url, captureHeaders: true}, generate_traffic, function (err, har) {
if (err) {
console.log(err);
} else {
try {
var data = JSON.parse(har);
} catch (e) {
console.log(err);
}
cb('har', data);
}
cb('close');
});
};
function startBrowser(url, browserWidth, browserHeight, display, cb, proxyAddr, done) {
//Dependencies
var webdriver = require('selenium-webdriver')
, fs = require('fs')
, metaparser = require('./metaviewport-parser')
, chromedriver = require('chromedriver');
;
function setViewPort (driver) {
var metaTags = new Array();
var metaNames = new Array();
var viewports = new Array();
var contentAttr;
var renderingData;
driver.findElements(webdriver.By.css('meta[name="viewport"]')).then(function(viewportDecls){
// return all the metaviewports found
webdriver.promise.map(
viewportDecls,
function (el) { return el.getAttribute("content");}
).then(
function (contentAttrs) {
cb('metaviewports', contentAttrs);
contentAttr = contentAttrs[contentAttrs.length - 1];
}
);
}).then(function(){
if(contentAttr) {
var viewportProps = metaparser.parseMetaViewPortContent(contentAttr);
renderingData = metaparser.getRenderingDataFromViewport(viewportProps.validProperties, browserWidth, browserHeight, 4, 0.25 );
cb('viewport', renderingData);
} else {
renderingData = { zoom: null, width: browserWidth*3, height: browserHeight*3 };
cb('viewport', renderingData);
}
driver.manage().window().setSize(renderingData.width, renderingData.height);
});
}
var chrome = require("selenium-webdriver/chrome");
var proxy = require('selenium-webdriver/proxy');
var capabilities = webdriver.Capabilities.chrome();
var proxyPrefs = proxy.manual({http: proxyAddr, https: proxyAddr});
capabilities.set(webdriver.Capability.PROXY, proxyPrefs);
// enabling metaviewport
var options = new chrome.Options();
options.addArguments(["--enable-viewport-meta"]);
options.addArguments(['--user-agent=Mozilla/5.0 (Linux; Android 4.4.4; Galaxy Nexus Build/IMM76B) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/36.0.1025.133 Mobile Safari/535.19']);
capabilities.merge(options.toCapabilities());
// enabling metaviewport
var options = new chrome.Options();
options.addArguments(["--enable-viewport-meta"]);
options.addArguments(['--user-agent=Mozilla/5.0 (Linux; Android 4.4.4; Galaxy Nexus Build/IMM76B) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/36.0.1025.133 Mobile Safari/535.19']);
options.addArguments(['--disable-bundled-ppapi-flash']);
capabilities.merge(options.toCapabilities());
var chromeservicebuilder = new chrome.ServiceBuilder(chromedriver.path).withEnvironment({DISPLAY:':' + display}).build();
var driver = chrome.createDriver(capabilities, chromeservicebuilder);
var time = Date.now();
driver.get(url).then(function(){
time = Date.now() - time;
cb('pageSpeed', time);
}).then(setViewPort(driver));
driver.findElement(webdriver.By.tagName('head')).then(function(head){
head.getInnerHtml().then(function(innerHtml){
cb('head', innerHtml);
});
});
driver.executeScript(function () {
return document.documentElement.innerHTML;
}).then(function(html){
cb('html', html);
});
driver.executeScript(function () {
return document.documentElement.clientWidth; //document.width not supported by chrome driver or selenium.
}).then(function(width){
console.log(width);
cb('documentWidth', width);
});
var tags = [
"html"
, "body"
, "header"
, "div"
, "section"
, "p"
, "button"
, "input"
, "h1"
, "h2"
, "h3"
, "h4"
, "h5"
, "h6"
];
var fontSizes = new Array();
var tagFontSize = {
tagName : new Array ()
, fontSize : new Array()
, location : new Array()
};
//for index in tagList
// get tagElements
// then for each
// get CSS font size -> object
// get name -> object
// get localisation -> object
// then push object in array
// then send to cb object array
for(var index in tags){
driver.executeScript(function (tag) {
return document.documentElement.getElementsByTagName(tag);
}, tags[index]).then(function(tag, index){
for (var index in tag){
tag[index].getCssValue("font-size").then(function(ftSize){
tagFontSize.fontSize.push(ftSize);
});
tag[index].getTagName().then(function(tagName){
tagFontSize.tagName.push(tagName);
});
tag[index].getLocation().then(function(location){
tagFontSize.location.push(location);
});
}
}).then(function(){
cb('tagFonts', tagFontSize);
});
}
driver.takeScreenshot().then(function(data){
var base64Data = data.replace(/^data:image\/png;base64,/,"")
fs.writeFile("public/screenshot.png", base64Data, 'base64', function(err) {
if(err) cb('error', err);
});
}).then(function() {
driver.quit();
done();
});
}
exports.run = run;
| JavaScript | 0.000005 | @@ -2445,349 +2445,8 @@
);%0A%0A
-// enabling metaviewport%0Avar options = new chrome.Options();%0Aoptions.addArguments(%5B%22--enable-viewport-meta%22%5D);%0Aoptions.addArguments(%5B'--user-agent=Mozilla/5.0 (Linux; Android 4.4.4; Galaxy Nexus Build/IMM76B) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/36.0.1025.133 Mobile Safari/535.19'%5D);%0Acapabilities.merge(options.toCapabilities());%0A%0A
// e
|
e6013666d6a3ec8fcf05320c7a5210e6b3a0c39e | set _class default parameter to deleteEdge function | lib/models/VertexCollection.js | lib/models/VertexCollection.js | 'use strict';
import * as GraphManager from './GraphManager';
class VertexCollection {
constructor (className, schema, connection) {
this.conn = connection;
this.gm = GraphManager.getInstance(this.conn);
this.className = className;
this.schema = schema;
}
/**
* Updates or create a vertex on database
* @param criteria
* @param data
* @param done
*/
upsert(criteria, data, done) {
// Validate data before the upset
if(this.schema.validate(data)) {
this.gm.database.update(this.className).set(data).upsert(criteria).return('after @this').one()
.then((record) => { done(null, this.inflate(record)); });
} else {
// Return errors if schema is not valid
done(this.schema.errors);
}
}
/**
* Inflates the record to a Vertex object
* @param record
* @returns {*}
*/
inflate (record) {
if (record === undefined) {
return record;
}
let vertex = {rid: record['@rid'].toString()};
for(let propertyName in this.schema.structure) {
vertex[propertyName] = record[propertyName];
}
return vertex;
}
/**
* Create a new vertex in database
* @param data
* @param done
* @returns {*}
*/
create(data, done) {
// Validate data
if(this.schema.validate(data)) {
this.gm.database.insert().into(this.className).set(data).one()
.then((record) => done(null, this.inflate(record)));
} else {
// Return errors if schema is not valid
return done(this.schema.errors);
}
}
/**
* Delete vertex matching with criteria
* @param criteria
* @param done
*/
delete(criteria, done) {
this.gm.database.delete('VERTEX').from(this.className).where(criteria).one().then((count) => done(null, count));
}
/**
* Returns first vertex matching with criteria
* @param criteria
* @param done
*/
findOne(criteria, done) {
this.gm.database.select().from(this.className).where(criteria).one().then((record) => done(null, this.inflate(record)))
}
/**
* Create or update an edge
*
* @param label
* @param from
* @param to
* @param data
* @param done
*/
upsertEdge(label, from, to, data, done) {
this.gm.database.select().from('E').where({in: to, out: from}).one().then((edge) => {
if (edge === undefined) {
this.createEdge(label, from, to, data, done)
} else {
this.gm.database.update(edge['@rid'].toString()).set(data).one().then((edge) => done(null, edge));
}
});
}
/**
* Create an edge
*
* @param label
* @param from
* @param to
* @param data
* @param done
*/
createEdge(label, from, to, data, done) {
this.gm.database.create('EDGE', label).set(data).from(from).to(to).one().then((edge) => done(null, edge));
}
/**
* Delete edge
*
* @param from
* @param to
* @param done
*/
deleteEdge(from, to, done) {
this.gm.database.delete('EDGE').from(from).to(to).scalar().then((count) => done(null, count));
}
/**
* Execute query in database
*
* @param query
* @param params
* @param done
*/
query(query, params, done) {
this.gm.database.query(query, {params: params}).then((results) => {
done(null, results);
}, done);
}
getQueryBuilder() {
return this.gm.database;
}
}
export default VertexCollection;
| JavaScript | 0 | @@ -2837,32 +2837,82 @@
elete edge%0A *%0A
+ *%0A * @param _class Optional, by default is E%0A
* @param from
@@ -2963,16 +2963,28 @@
eteEdge(
+_class='E',
from, to
@@ -3027,16 +3027,24 @@
e('EDGE'
+, _class
).from(f
|
79e4e4fcf59448fc35a7cbe9ba98930996cd6c1a | Use proper base object for Options panel overlay | lib/options/options-overlay.js | lib/options/options-overlay.js | /* See license.txt for terms of usage */
"use strict";
const self = require("sdk/self");
const { Cu, Ci } = require("chrome");
const { Trace, TraceError } = require("firebug.sdk/lib/core/trace.js").get(module.id);
const { loadSheet, removeSheet } = require("sdk/stylesheet/utils");
const { Class } = require("sdk/core/heritage");
const { gDevTools } = require("firebug.sdk/lib/core/devtools.js");
const { BaseOverlay } = require("../chrome/base-overlay.js");
const { Services } = Cu.import("resource://gre/modules/Services.jsm", {});
/**
* @overlay This object represents an overlay that is responsible
* for customizing the Options panel.
*/
const OptionsOverlay = Class(
/** @lends OptionsOverlay */
{
extends: BaseOverlay,
overlayId: "options",
// Initialization
initialize: function(options) {
BaseOverlay.prototype.initialize.apply(this, arguments);
Trace.sysout("optionsOverlay.initialize;", options);
},
onReady: function(options) {
BaseOverlay.prototype.onReady.apply(this, arguments);
Trace.sysout("optionsOverlay.onReady;", options);
},
destroy: function() {
Trace.sysout("optionsOverlay.destroy;", arguments);
},
onApplyTheme: function(iframeWin, oldTheme) {
Services.prefs.addObserver("devtools", this, false);
},
onUnapplyTheme: function(iframeWin, newTheme) {
Services.prefs.removeObserver("devtools", this, false);
},
// Preferences
observe: function(subject, topic, data) {
let event = {
pref: data,
newValue: GetPref(data),
};
switch (data) {
case "devtools.cache.disabled":
this.panel._prefChanged("pref-changed", event)
break;
}
}
});
// Helpers
// xxxHonza: move to core/options FIXME
function GetPref(name) {
let type = Services.prefs.getPrefType(name);
switch (type) {
case Services.prefs.PREF_STRING:
return Services.prefs.getCharPref(name);
case Services.prefs.PREF_INT:
return Services.prefs.getIntPref(name);
case Services.prefs.PREF_BOOL:
return Services.prefs.getBoolPref(name);
default:
throw new Error("Unknown type");
}
}
function SetPref(name, value) {
let type = Services.prefs.getPrefType(name);
switch (type) {
case Services.prefs.PREF_STRING:
return Services.prefs.setCharPref(name, value);
case Services.prefs.PREF_INT:
return Services.prefs.setIntPref(name, value);
case Services.prefs.PREF_BOOL:
return Services.prefs.setBoolPref(name, value);
default:
throw new Error("Unknown type");
}
}
// Exports from this module
exports.OptionsOverlay = OptionsOverlay;
| JavaScript | 0 | @@ -50,16 +50,30 @@
rict%22;%0A%0A
+// Add-on SDK%0A
const se
@@ -94,25 +94,24 @@
sdk/self%22);%0A
-%0A
const %7B Cu,
@@ -140,95 +140,8 @@
%22);%0A
-const %7B Trace, TraceError %7D = require(%22firebug.sdk/lib/core/trace.js%22).get(module.id);%0A
cons
@@ -247,24 +247,127 @@
/heritage%22);
+%0A%0A// Firebug.SDK%0Aconst %7B Trace, TraceError %7D = require(%22firebug.sdk/lib/core/trace.js%22).get(module.id);
%0Aconst %7B gDe
@@ -430,20 +430,21 @@
const %7B
-Base
+Panel
Overlay
@@ -460,37 +460,137 @@
re(%22
-../chrome/base-overlay.js%22);%0A
+firebug.sdk/lib/panel-overlay.js%22);%0Aconst %7B Options %7D = require(%22firebug.sdk/lib/core/options.js%22);%0A%0A// Firebug.next%0A%0A// Platform
%0Acon
@@ -846,20 +846,21 @@
xtends:
-Base
+Panel
Overlay,
@@ -911,403 +911,8 @@
on%0A%0A
- initialize: function(options) %7B%0A BaseOverlay.prototype.initialize.apply(this, arguments);%0A%0A Trace.sysout(%22optionsOverlay.initialize;%22, options);%0A %7D,%0A%0A onReady: function(options) %7B%0A BaseOverlay.prototype.onReady.apply(this, arguments);%0A%0A Trace.sysout(%22optionsOverlay.onReady;%22, options);%0A %7D,%0A%0A destroy: function() %7B%0A Trace.sysout(%22optionsOverlay.destroy;%22, arguments);%0A %7D,%0A%0A
on
@@ -1248,17 +1248,25 @@
wValue:
-G
+Options.g
etPref(d
@@ -1420,878 +1420,8 @@
);%0A%0A
-// Helpers%0A%0A// xxxHonza: move to core/options FIXME%0Afunction GetPref(name) %7B%0A let type = Services.prefs.getPrefType(name);%0A switch (type) %7B%0A case Services.prefs.PREF_STRING:%0A return Services.prefs.getCharPref(name);%0A case Services.prefs.PREF_INT:%0A return Services.prefs.getIntPref(name);%0A case Services.prefs.PREF_BOOL:%0A return Services.prefs.getBoolPref(name);%0A default:%0A throw new Error(%22Unknown type%22);%0A %7D%0A%7D%0A%0Afunction SetPref(name, value) %7B%0A let type = Services.prefs.getPrefType(name);%0A switch (type) %7B%0A case Services.prefs.PREF_STRING:%0A return Services.prefs.setCharPref(name, value);%0A case Services.prefs.PREF_INT:%0A return Services.prefs.setIntPref(name, value);%0A case Services.prefs.PREF_BOOL:%0A return Services.prefs.setBoolPref(name, value);%0A default:%0A throw new Error(%22Unknown type%22);%0A %7D%0A%7D%0A%0A
// E
|
940459e654b780ead489aeefb471d10afc3f4a67 | remove outdated comments (#891) | lib/rules_core/replacements.js | lib/rules_core/replacements.js | // Simple typographic replacements
//
// (c) (C) → ©
// (tm) (TM) → ™
// (r) (R) → ®
// +- → ±
// (p) (P) -> §
// ... → … (also ?.... → ?.., !.... → !..)
// ???????? → ???, !!!!! → !!!, `,,` → `,`
// -- → –, --- → —
//
'use strict';
// TODO:
// - fractionals 1/2, 1/4, 3/4 -> ½, ¼, ¾
// - multiplications 2 x 4 -> 2 × 4
var RARE_RE = /\+-|\.\.|\?\?\?\?|!!!!|,,|--/;
// Workaround for phantomjs - need regex without /g flag,
// or root check will fail every second time
var SCOPED_ABBR_TEST_RE = /\((c|tm|r)\)/i;
var SCOPED_ABBR_RE = /\((c|tm|r)\)/ig;
var SCOPED_ABBR = {
c: '©',
r: '®',
tm: '™'
};
function replaceFn(match, name) {
return SCOPED_ABBR[name.toLowerCase()];
}
function replace_scoped(inlineTokens) {
var i, token, inside_autolink = 0;
for (i = inlineTokens.length - 1; i >= 0; i--) {
token = inlineTokens[i];
if (token.type === 'text' && !inside_autolink) {
token.content = token.content.replace(SCOPED_ABBR_RE, replaceFn);
}
if (token.type === 'link_open' && token.info === 'auto') {
inside_autolink--;
}
if (token.type === 'link_close' && token.info === 'auto') {
inside_autolink++;
}
}
}
function replace_rare(inlineTokens) {
var i, token, inside_autolink = 0;
for (i = inlineTokens.length - 1; i >= 0; i--) {
token = inlineTokens[i];
if (token.type === 'text' && !inside_autolink) {
if (RARE_RE.test(token.content)) {
token.content = token.content
.replace(/\+-/g, '±')
// .., ..., ....... -> …
// but ?..... & !..... -> ?.. & !..
.replace(/\.{2,}/g, '…').replace(/([?!])…/g, '$1..')
.replace(/([?!]){4,}/g, '$1$1$1').replace(/,{2,}/g, ',')
// em-dash
.replace(/(^|[^-])---(?=[^-]|$)/mg, '$1\u2014')
// en-dash
.replace(/(^|\s)--(?=\s|$)/mg, '$1\u2013')
.replace(/(^|[^-\s])--(?=[^-\s]|$)/mg, '$1\u2013');
}
}
if (token.type === 'link_open' && token.info === 'auto') {
inside_autolink--;
}
if (token.type === 'link_close' && token.info === 'auto') {
inside_autolink++;
}
}
}
module.exports = function replace(state) {
var blkIdx;
if (!state.md.options.typographer) { return; }
for (blkIdx = state.tokens.length - 1; blkIdx >= 0; blkIdx--) {
if (state.tokens[blkIdx].type !== 'inline') { continue; }
if (SCOPED_ABBR_TEST_RE.test(state.tokens[blkIdx].content)) {
replace_scoped(state.tokens[blkIdx].children);
}
if (RARE_RE.test(state.tokens[blkIdx].content)) {
replace_rare(state.tokens[blkIdx].children);
}
}
};
| JavaScript | 0.000001 | @@ -92,24 +92,8 @@
%E2%86%92 %C2%B1%0A
-// (p) (P) -%3E %C2%A7%0A
// .
|
9673beee1bf8eb73ee415c23570b2fa19d999543 | Break down BucketService#_process into various methods | lib/services/bucket-service.js | lib/services/bucket-service.js | import { Object, A, Map, Evented, RSVP, run, get, set } from 'ember';
var slice = Array.prototype.slice;
/**
@class BucketService
@namespace EB
*/
var BucketService = Object.extend(Evented, {
/**
@property queues
*/
queues: null,
/**
@method addToBucket
*/
addToBucket: function(name, target) {
var bucket = this._bucket(name);
return bucket.addObject(target);
},
/**
@method removeFromBucket
*/
removeFromBucket: function(name, target) {
var bucket = this._bucket(name);
return bucket.removeObject(target);
},
/**
@method getBucket
*/
getBucket: function(name) {
var bucket;
return bucket = this._bucket(name);
},
/**
@method emptyBucket
*/
emptyBucket: function(name) {
var bucket;
bucket = this._bucket(name);
this._bucket(name).forEach(function(target) {
bucket.removeObject(target);
});
this.trigger('didEmpty' + name.capitalize());
},
/**
@method moveToBucket
*/
moveToBucket: function(from, to) {
var src = this._bucket(from);
var dest = this._bucket(to);
src.forEach(function(item) {
dest.addObject(item);
});
dest.forEach(function(item) {
src.removeObject(item);
});
},
/**
@method setOperation
*/
setOperation: function(name, fn) {
return this._operation(name, fn);
},
/**
@method reset
*/
reset: function() {
var queues = get(this, 'queues');
return queues.forEach((function(_this) {
return function(key) {
if (!key.match(/operation$/)) {
_this.emptyBucket(key);
}
return queues.remove(key);
};
})(this));
},
/**
@private
@method _initQueues
*/
_initQueues: (function() {
set(this, 'queues', Map.create());
}).on('init'),
/**
@private
@method _bucket
*/
_bucket: function(name) {
var queues = get(this, 'queues');
var bucket = queues.get(name);
if (!bucket) {
queues.set(name, A([]));
this._operation(name, null);
this._setupCommand(name);
}
return bucket || queues.get(name);
},
/**
@private
@method _operation
*/
_operation: function(name, fn) {
var fnKey = "%@:operation".fmt(name);
var queues = get(this, 'queues');
if (typeof fn === 'function') {
return queues.set(fnKey, fn);
} else if (fn === null) {
var _name = name;
queues.set(fnKey, function(target) {
return target[_name].call(target);
});
} else {
return queues.get(fnKey);
}
},
/**
@private
@method _process
*/
_process: function(name) {
var bucket = this._bucket(name);
var fn = this._operation(name);
var results = A([]);
var __process = function(item) {
var result = null;
run(function() {
return result = fn(item);
});
if (result && typeof result.then === 'function') {
results.pushObject(result);
result.then(function() {
bucket.removeObject(item);
});
} else {
bucket.removeObject(item);
}
return result;
};
var bucketItems = bucket.toArray();
for (var i = 0, len = bucketItems.length; i < len; i++) {
__process(bucketItems[i]);
}
if (results.length) {
var suffix = name.capitalize();
var didProcess = 'did' + suffix;
var didNotProcess = 'didNot' + suffix;
return RSVP.Promise.all(results).then((function(_this) {
return function() {
return _this.trigger(didProcess);
};
})(this), (function(_this) {
return function() {
return _this.trigger(didNotProcess);
};
})(this));
}
},
/**
@private
@method _setupCommand
*/
_setupCommand: function(name) {
var _name = name;
var command = 'do' + name.capitalize();
var processor = (function(_this) {
return function() {
return _this._process(_name);
};
})(this);
this.on(command, processor);
return this[command] = processor;
}
});
var _singletonInstance = null;
BucketService.reopenClass({
/**
@method create
*/
create: function() {
if (_singletonInstance != null) {
return _singletonInstance;
}
return _singletonInstance = Object.create.apply(this, slice.call(arguments));
},
/**
@method getSingleton
*/
getSingleton: function() {
return BucketService.create.apply(this, slice.call(arguments));
}
});
export default BucketService;
| JavaScript | 0.000237 | @@ -2713,16 +2713,397 @@
rocess =
+ this._processFactory(bucket, fn, results);%0A var bucketItems = bucket.toArray();%0A for (var i = 0, len = bucketItems.length; i %3C len; i++) %7B%0A __process(bucketItems%5Bi%5D);%0A %7D%0A this._processResults(results);%0A %7D,%0A%0A /**%0A @private%0A @method _processFactory - creates a function to process a bucket item%0A */%0A _processFactory: function(bucket, fn, results) %7B%0A return
functio
@@ -3108,24 +3108,24 @@
ion(item) %7B%0A
-
var re
@@ -3471,146 +3471,98 @@
;%0A
- var bucketItems = bucket.toArray();%0A for (var i = 0, len = bucketItems.length; i %3C len; i++) %7B%0A __process(bucketItems%5Bi%5D);%0A %7D
+%7D,%0A%0A /**%0A @private%0A @method _processResults%0A */%0A _processResults: function(results) %7B
%0A
|
33ea92f9263332d266b0664c2d8a421a925f9752 | change default order to viewCount | lib/services/youtube-search.js | lib/services/youtube-search.js | 'use strict';
const google = require('googleapis');
const youtube = google.youtube('v3');
const nconf = require('nconf');
nconf
.argv()
.env()
.file({file: '../config.json'});
/**
* QUOTA IMPACT: 100
*
* @param params
* @param callback
*/
exports.searchList = function(params, callback) {
youtube.search.list(
Object.assign(
{
auth: nconf.get('google_api_key'),
fields: 'items(id/videoId),nextPageToken,pageInfo',
maxResults: '50',
order: 'rating',
part: 'snippet',
type: 'video',
safeSearch: 'none',
videoEmbeddable: true
},
params
),
callback
);
};
/**
* QUOTA IMPACT: 5
* @param id
* @param callback
*/
exports.videosList = function(id, callback) {
youtube.videos.list(
{
auth: nconf.get('google_api_key'),
part: 'recordingDetails,snippet',
id: id
},
callback
);
}; | JavaScript | 0 | @@ -522,14 +522,17 @@
r: '
-rating
+viewCount
',%0A
|
edb703103e5afc2845406c5b2fb54ede4e193ce7 | Update skoleskyss-add-document.js | lib/skoleskyss-add-document.js | lib/skoleskyss-add-document.js | 'use strict'
function generateMetadataDocument (options) {
if (!options) {
throw new Error('Missing required input: options')
}
if (!options.title) {
throw new Error('Missing required input: options.title')
}
if (!options.offTitle) {
throw new Error('Missing required input: options.title')
}
if (!options.personalIdNumber) {
throw new Error('Missing required input: options.personalIdNumber')
}
if (!options.file) {
throw new Error('Missing required input: options.file')
}
if (!options.fileTitle) {
throw new Error('Missing required input: options.fileTitle')
}
if (!options.caseNumber) {
throw new Error('Missing required input: options.caseNumber')
}
if (!options.contacts) {
throw new Error('Missing required input: options.contacts')
}
if (!options.category) {
throw new Error('Missing required input: options.category')
}
if (!options.role) {
throw new Error('Missing required input: options.category')
}
var responsiblePerson = options.responsiblePerson ? '' : '214853'
var meta = {
'clientService': 'DocumentService',
'clientMethod': 'CreateDocument',
'args': {
'parameter': {
'AccessCode': '13', // Codetable: Accesscode
'AccessGroup': 'Skoleskyss', // Codetable: Tilgangsgruppe navn
'Category': options.category, // Codetable: Document category
'Contacts': [
{
'DocumentContactParameter': {
'ReferenceNumber': options.personalIdNumber,
'Role': options.role
}
}
],
'Files': [
{
'CreateFileParameter': {
'Base64Data': options.file, // Must be base64 encoded
'Category': '1', // Codetable: File category
'Format': 'pdf', // Codetable: File format
'Status': 'F', // Codetable: FileStatus
'Title': options.fileTitle,
'VersionFormat': 'A' // Codetable: File status
}
}
],
'Paragraph': 'Offl §13 jfr Fvl §13', // Codetable: Paragraph
'ResponsibleEnterpriseRecno': '213419', // Recnr ansvarlig virksomhet
'ResponsiblePersonRecno': responsiblePerson,
'Status': 'J', // Codetable: Document status
'Title': options.offTitle,
'UnofficialTitle': options.title,
'Archive': 'Saksdokument', // Codetable: Document archive
'CaseNumber': options.caseNumber,
'SendersReference': ''
}
}
}
return meta
}
module.exports = generateMetadataDocument
| JavaScript | 0 | @@ -989,76 +989,8 @@
%0A %7D
-%0A var responsiblePerson = options.responsiblePerson ? '' : '214853'
%0A%0A
@@ -2147,25 +2147,16 @@
o':
-responsiblePerson
+'214853'
,%0A
@@ -2440,16 +2440,109 @@
%7D%0A %7D%0A
+ if (options.responsiblePerson) %7B%0A delete meta.args.parameter.ResponsiblePersonRecno%0A %7D%0A
return
|
697ccbf0abb7f5ba161c0a6a940af1f3af5c8b82 | Rename mkdir to mkdirTemp | lib/tasks/install-blueprint.js | lib/tasks/install-blueprint.js | 'use strict';
const Blueprint = require('../models/blueprint');
const Task = require('../models/task');
const RSVP = require('rsvp');
const isGitRepo = require('is-git-url');
const temp = require('temp');
const childProcess = require('child_process');
const path = require('path');
const merge = require('ember-cli-lodash-subset').merge;
const logger = require('heimdalljs-logger')('ember-cli:tasks:install-blueprint');
// Automatically track and cleanup temp files at exit
temp.track();
let mkdir = RSVP.denodeify(temp.mkdir);
let exec = RSVP.denodeify(childProcess.exec);
class InstallBlueprintTask extends Task {
run(options) {
let cwd = process.cwd();
let name = options.rawName;
let blueprintOption = options.blueprint;
// If we're in a dry run, pretend we changed directories.
// Pretending we cd'd avoids prompts in the actual current directory.
let fakeCwd = path.join(cwd, name);
let target = options.dryRun ? fakeCwd : cwd;
let installOptions = {
target,
entity: { name },
ui: this.ui,
analytics: this.analytics,
project: this.project,
dryRun: options.dryRun,
targetFiles: options.targetFiles,
rawArgs: options.rawArgs,
};
installOptions = merge(installOptions, options || {});
if (isGitRepo(blueprintOption)) {
return mkdir('ember-cli').then(pathName => {
logger.info(`Cloning blueprint from git (${blueprintOption}) into "${pathName}" ...`);
let execArgs = ['git', 'clone', blueprintOption, pathName].join(' ');
return exec(execArgs).then(() => {
logger.info(`Running "npm install" in "${pathName}" ...`);
return exec('npm install', { cwd: pathName });
}).then(() => {
logger.info(`Installing blueprint into "${target}" ...`);
let blueprint = Blueprint.load(pathName);
return blueprint.install(installOptions);
});
});
} else {
let blueprintName = blueprintOption || 'app';
logger.info(`Looking up blueprint "${blueprintName}" ...`);
let blueprint = Blueprint.lookup(blueprintName, {
paths: this.project.blueprintLookupPaths(),
});
logger.info(`Installing blueprint into "${target}" ...`);
return blueprint.install(installOptions);
}
}
}
module.exports = InstallBlueprintTask;
| JavaScript | 0.000014 | @@ -494,16 +494,20 @@
et mkdir
+Temp
= RSVP.
@@ -1339,16 +1339,20 @@
rn mkdir
+Temp
('ember-
|
97fba1f86707e350fef20fc9ce57bc5f8298c80f | fix sidebar topic urls | lib/topic-store/topic-store.js | lib/topic-store/topic-store.js | import Store from '../store/store';
import request from '../request/request';
import config from '../config/config';
import forumStore from '../forum-store/forum-store';
import urlBuilder from '../url-builder/url-builder';
const voteOptions = ['negative', 'positive', 'neutral'];
class TopicStore extends Store {
name () {
return 'topic';
}
parse (topic) {
if (!config.multiForum) return Promise.resolve(topic);
if (config.multiForum && !topic.forum) {
throw new Error(`Topic ${topic.id} needs a forum.`);
}
return forumStore.findOne(topic.forum).then(forum => {
topic.url = urlBuilder.topic(topic, forum);
return topic;
}).catch(err => {
throw err;
});
}
publish (id) {
if (!this.item.get(id)) {
return Promise.reject(new Error('Cannot publish not fetched item.'));
}
let promise = new Promise((resolve, reject) => {
request
.post(`${this.url(id)}/publish`)
.end((err, res) => {
if (err || !res.ok) return reject(err);
this.parse(res.body).then(item => {
this.item.set(id, item);
resolve(item);
this.busEmit(`update:${id}`, item);
});
});
});
return promise;
}
vote (id, value) {
if (!this.item.get(id)) {
return Promise.reject(new Error('Cannot vote not fetched item.'));
}
if (!~voteOptions.indexOf(value)) {
return Promise.reject(new Error('Invalid vote value.'));
}
let promise = new Promise((resolve, reject) => {
request
.post(`${this.url(id)}/vote`)
.send({ value: value })
.end((err, res) => {
if (err || !res.ok) return reject(err);
this.parse(res.body).then(item => {
this.item.set(id, item);
resolve(item);
this.busEmit(`update:${id}`, item);
});
});
});
return promise;
}
}
export default new TopicStore;
| JavaScript | 0.000003 | @@ -367,67 +367,8 @@
) %7B%0A
- if (!config.multiForum) return Promise.resolve(topic);%0A
@@ -414,22 +414,38 @@
%7B%0A
-throw
+return Promise.reject(
new Erro
@@ -481,24 +481,25 @@
forum.%60)
+)
;%0A %7D%0A
retu
@@ -494,50 +494,122 @@
%7D%0A
+%0A
-return forumStore.findOne(topic.forum)
+let findForum = config.multiForum ? forumStore.findOne(topic.forum) : Promise.resolve();%0A return findForum
.the
@@ -701,48 +701,8 @@
%7D)
-.catch(err =%3E %7B%0A throw err;%0A %7D);
%0A %7D
|
41becd17172ea0a21aaaa5f3487ac740cde92a50 | Rename `program` param to `options` in file.js | bin/file.js | bin/file.js | var Transformer = require('./../lib/transformer');
var _ = require('lodash');
module.exports = function (program) {
// Enable all transformers by default
var transformers = {
classes: true,
stringTemplates: true,
arrowFunctions: true,
let: true,
defaultArguments: true,
objectMethods: true,
objectShorthands: true,
noStrict: true,
importCommonjs: false,
exportCommonjs: false,
};
// When --no-classes used, disable classes transformer
if(! program.classes) {
transformers.classes = false;
}
// When --transformers used turn off everything besides the specified tranformers
if (program.transformers) {
transformers = _.mapValues(transformers, _.constant(false));
program.transformers.forEach(function (name) {
if (!transformers.hasOwnProperty(name)) {
console.error("Unknown transformer '" + name + "'.");
}
transformers[name] = true;
});
}
// When --module=commonjs used, enable CommonJS Transformers
if (program.module === 'commonjs') {
transformers.importCommonjs = true;
transformers.exportCommonjs = true;
}
else if (program.module) {
console.error("Unsupported module system '" + program.module + "'.");
}
var transformer = new Transformer({transformers: transformers});
transformer.readFile(program.inFile);
transformer.applyTransformations();
transformer.writeFile(program.outFile);
console.log('The file "' + program.outFile + '" has been written.');
};
| JavaScript | 0 | @@ -99,23 +99,23 @@
nction (
-program
+options
) %7B%0A //
@@ -486,18 +486,18 @@
if
+
(!
- program
+options
.cla
@@ -633,23 +633,23 @@
s%0A if (
-program
+options
.transfo
@@ -727,23 +727,23 @@
);%0A%0A
-program
+options
.transfo
@@ -1003,31 +1003,31 @@
rmers%0A if (
-program
+options
.module ===
@@ -1135,23 +1135,23 @@
lse if (
-program
+options
.module)
@@ -1203,23 +1203,23 @@
em '%22 +
-program
+options
.module
@@ -1322,23 +1322,23 @@
eadFile(
-program
+options
.inFile)
@@ -1401,23 +1401,23 @@
iteFile(
-program
+options
.outFile
@@ -1453,15 +1453,15 @@
' +
-program
+options
.out
|
a89d7168ec2552b8e0ed49a5c1384c4730bf5ef8 | Fix lint issue | local_modules/sensepat/test.js | local_modules/sensepat/test.js | // Testing
const pat = require('./index')
const test = require('tape')
const V = {
time: 0,
value: [
[1, 0, 1],
[0, 1, 0]
],
mass: [
[1, 1, 1],
[1, 1, 1]
]
}
const ONESHALF = {
time: 0,
value: [
[1, 1, 1],
[1, 1, 1]
],
mass: [
[1, 1, 1],
[0, 0, 0]
]
}
test('len', (t) => {
t.equal(pat.len(V), 3)
t.end()
})
test('mean', (t) => {
t.deepEqual(pat.mean(ONESHALF), [1, 0])
t.deepEqual(pat.mean(V), [2/3, 1/3])
t.end()
})
test('width', (t) => {
t.equal(pat.width(V), 2)
t.end()
})
| JavaScript | 0.000002 | @@ -458,14 +458,18 @@
, %5B2
-/
+ /
3, 1
-/
+ /
3%5D)%0A
|
bc3f787f5c4ba75a333a1bf041a00a0225d05d11 | Change how caching is controlled | html.js | html.js | const weakMap = new WeakMap()
const createAssertionError = (actual, expected) =>
Error(`Expected ${expected}. Found ${actual}.`)
export const tokenTypes = {
variable: 0,
tag: 1,
endtag: 2,
key: 3,
value: 4,
node: 5,
text: 6,
constant: 7
}
const valueTrue = {
type: tokenTypes.value,
value: true
}
const END = Symbol('end')
const isSpaceChar = (char) => !char.trim()
const isOfTag = (char) => char !== '/' && char !== '>' && !isSpaceChar(char)
const isOfKey = (char) => char !== '=' && isOfTag(char)
const isQuoteChar = (char) => char === '"' || char === "'"
const tokenize = (acc, strs, vlength) => {
const tokens = []
let afterVar = false
const current = () => str.charAt(i)
const next = () => str.charAt(i + 1)
let str
let i
for (let index = 0, length = strs.length; index < length; index++) {
str = strs[index]
i = 0
let tag = acc.tag
while (current()) {
if (!tag) {
let value = ''
if (current() === '<') {
let end = false
if (next() === '/') {
end = true
i++
}
while (next() && isOfTag(next())) {
i++
value += current()
}
afterVar = false
tokens.push({
type: !end ? tokenTypes.tag : tokenTypes.endtag,
value
})
tag = value
i++
} else {
while (current() && current() !== '<') {
value += current()
i++
}
if (value.trim() || (afterVar && current() !== '<')) {
tokens.push({
type: tokenTypes.text,
value
})
}
}
} else if (isSpaceChar(current())) {
i++
} else if (current() === '/' && next() === '>') {
tokens.push(
END,
{
type: tokenTypes.endtag,
value: tag
},
END
)
tag = false
i += 2
} else if (current() === '>') {
tokens.push(END)
tag = false
i++
} else if (isOfKey(current())) {
let value = ''
i--
while (next() && isOfKey(next())) {
i++
value += current()
}
tokens.push({
type: tokenTypes.key,
value
})
if (next() === '=') {
i++
let quote = ''
let value = ''
if (next() && isQuoteChar(next())) {
i++
quote = current()
while (next() !== quote) {
if (next()) {
i++
value += current()
} else {
throw createAssertionError('', quote)
}
}
i++
tokens.push({
type: tokenTypes.value,
value
})
} else if (next()) {
throw createAssertionError(next(), '"')
}
} else {
tokens.push(valueTrue)
}
i++
}
}
acc.tag = tag
if (index < vlength) {
afterVar = true
tokens.push({
type: tokenTypes.variable,
value: index
})
}
}
return tokens
}
const parse = (tokens, parent, tag, variables) => {
const child = {
tag,
dynamic: false,
type: tokenTypes.node,
attributes: [],
children: []
}
let token
for (;;) {
token = tokens.shift()
if (!token || token === END) break
let key = false
let constant = false
let value = token.value
if (token.type === tokenTypes.key) {
key = token.value
token = tokens.shift()
const firstChar = key.charAt(0)
const colon = ':' === firstChar
const atSign = '@' === firstChar
if (colon) {
key = key.substring(1)
}
constant = token.type === tokenTypes.value
value = token.value
if (token.type === tokenTypes.variable && !colon && !atSign) {
value = variables[value]
constant = true
}
}
if (constant) {
if (child.attributes.offset != null) child.attributes.offset++
child.attributes.unshift({
type: tokenTypes.constant,
key,
value
})
} else {
child.dynamic = true
child.attributes.offset =
child.attributes.offset ?? child.attributes.length
child.attributes.push({
type: tokenTypes.variable,
key,
value
})
}
}
for (;;) {
token = tokens.shift()
if (!token) break
if (token.type === tokenTypes.endtag && token.value === child.tag) {
break
} else if (token.type === tokenTypes.tag) {
const dynamic = parse(tokens, child, token.value, variables)
child.dynamic = child.dynamic || dynamic
} else if (token.type === tokenTypes.text) {
child.children.push({
type: tokenTypes.text,
value: token.value
})
} else if (token.type === tokenTypes.variable) {
child.dynamic = true
child.children.offset = child.children.offset ?? child.children.length
child.children.push({
type: tokenTypes.variable,
value: token.value
})
}
}
if (child.dynamic) {
parent.children.offset = parent.children.offset ?? parent.children.length
}
parent.children.push(child)
return child.dynamic
}
let view = 1
const toTemplate = (strs, variables) => {
const acc = {
tag: false
}
const tokens = tokenize(acc, strs, variables.length)
const children = []
for (;;) {
const token = tokens.shift()
if (!token) break
if (token.type === tokenTypes.tag) {
parse(tokens, {children}, token.value, variables)
} else if (token.type === tokenTypes.text && token.value.trim()) {
throw createAssertionError(token.type, "'node'")
}
}
if (children.length !== 1) {
throw createAssertionError(children.length, 1)
}
children[0].view = view++
return children[0]
}
const html = (strs, ...variables) => {
let result = html.cache?.get(strs)
if (!result) {
result = toTemplate(strs, variables)
html.cache?.set(strs, result)
}
return {variables, ...result}
}
html.cache = weakMap
export {html}
| JavaScript | 0.000007 | @@ -3938,32 +3938,41 @@
alue%0A%0A if (
+%0A
token.type === t
@@ -3992,16 +3992,24 @@
iable &&
+%0A
!colon
@@ -4014,16 +4014,52 @@
n &&
- !atSign
+%0A !atSign &&%0A !html.dev%0A
) %7B%0A
@@ -6126,27 +6126,23 @@
esult =
-html.cache?
+weakMap
.get(str
@@ -6212,19 +6212,15 @@
-html.cache?
+weakMap
.set
@@ -6283,23 +6283,19 @@
tml.
-cache = weakMap
+dev = false
%0A%0Aex
|
24c7c7b8f9db0b881f3f6d44c3e6dd20e2f2d9e2 | add cmd/git.js and cmd/lazy.js. | cmd/lazy.js | cmd/lazy.js | const path = require('path');
const { compile } = require('../config/util');
const argv = process.argv;
const msg = argv[2];
(async () => {
await compile(
`npm run version && npm run noistanbul && npm run build && npm run hasistanbul && npm run git ${msg}`,
path.resolve(__dirname, '..')
);
process.exit(0);
})(); | JavaScript | 0 | @@ -253,14 +253,16 @@
git
+%22
$%7Bmsg%7D
+%22
%60, %0A
|
c3090607ab0bf717a3cb18c19216cc8f4a5833b0 | Improve Button disabled-state tests | spec/bbctrl-button.spec.js | spec/bbctrl-button.spec.js | /*global define, describe, it, expect */
define(['backbone', 'bbctrl-button'], function (Backbone, Button) {
'use strict';
//
var
// Helper methods to simulate user interaction with the control. These may serve as an
// effective indication of all the interactions that the control supports (and the suite tests
// for). They unavoidably leverage privileged knowlege of control internals, for example
// reaching into the control's document, to invoke a click on an appropriately named class. In
// this sense, they also serve as a means of isolating the most brittle part of the test suite
// - that, which is coupled with the unit's implementation - into a small set of APIs. These
// may be adjusted as needed to account for changes in the control's implementation while
// keeping the rest of the suite unaffected
clickButton = function (button) {
button.$el.click();
};
//
describe('The button control', function () {
describe('in terms of misc events', function () {
it('should trigger clicked-event when clicked', function () {
var button, isButtonClickHandlerInvoked;
button = new Button();
button.on('clicked', function () {
isButtonClickHandlerInvoked = true;
});
clickButton(button);
expect(isButtonClickHandlerInvoked).toBeTruthy();
});
});
describe('in terms of disabled behaviour', function () {
it('should not trigger clicked-event when clicked (.disable())', function () {
var button, isButtonClickHandlerInvoked;
button = new Button();
button.disable();
button.on('clicked', function () {
isButtonClickHandlerInvoked = true;
});
clickButton(button);
expect(isButtonClickHandlerInvoked).toBeFalsy();
});
it('should not trigger clicked-event when clicked (.enable(false))', function () {
var button, isButtonClickHandlerInvoked;
button = new Button();
button.enable(false);
button.on('clicked', function () {
isButtonClickHandlerInvoked = true;
});
clickButton(button);
expect(isButtonClickHandlerInvoked).toBeFalsy();
});
it('should not trigger clicked-event when clicked (uiState.set({ isDisabled: true }))', function () {
var button, isButtonClickHandlerInvoked;
button = new Button({
uiState: new Backbone.Model({ isDisabled: true })
});
button.enable(false);
button.on('clicked', function () {
isButtonClickHandlerInvoked = true;
});
clickButton(button);
expect(isButtonClickHandlerInvoked).toBeFalsy();
});
it('should trigger clicked-event when clicked when re-enabled (.enable())', function () {
var button, isButtonClickHandlerInvoked;
button = new Button();
button.disable();
button.on('clicked', function () {
isButtonClickHandlerInvoked = true;
});
button.enable();
clickButton(button);
expect(isButtonClickHandlerInvoked).toBeTruthy();
});
it('should trigger clicked-event when clicked when re-enabled (.disable(false))', function () {
var button, isButtonClickHandlerInvoked;
button = new Button();
button.disable();
button.on('clicked', function () {
isButtonClickHandlerInvoked = true;
});
button.disable(false);
clickButton(button);
expect(isButtonClickHandlerInvoked).toBeTruthy();
});
it('should trigger clicked-event when clicked when re-enabled (uiState.set({ isDisabled: false }))', function () {
var button, uiState, isButtonClickHandlerInvoked;
uiState = new Backbone.Model({ isDisabled: true });
button = new Button({ uiState: uiState });
button.disable();
button.on('clicked', function () {
isButtonClickHandlerInvoked = true;
});
uiState.set({ isDisabled: false });
clickButton(button);
expect(isButtonClickHandlerInvoked).toBeTruthy();
});
});
});
});
| JavaScript | 0 | @@ -1630,34 +1630,8 @@
();%0A
- button.disable();%0A
@@ -1661,32 +1661,32 @@
, function () %7B%0A
+
isButt
@@ -1720,32 +1720,58 @@
e;%0A %7D);%0A%0A
+ button.disable();%0A
clickBut
@@ -2025,38 +2025,8 @@
();%0A
- button.enable(false);%0A
@@ -2115,32 +2115,62 @@
e;%0A %7D);%0A%0A
+ button.enable(false);%0A
clickBut
@@ -2304,36 +2304,50 @@
en clicked (
+initialized with
uiState
-.set(
+:
%7B isDisabled
@@ -2351,25 +2351,24 @@
led: true %7D)
-)
', function
@@ -2527,38 +2527,8 @@
%7D);%0A
- button.enable(false);%0A
@@ -2732,32 +2732,36 @@
it('should
+not
trigger clicked-
@@ -2771,32 +2771,536 @@
nt when clicked
+(uiState.set(%7B isDisabled: true %7D))', function () %7B%0A var button, uiState, isButtonClickHandlerInvoked;%0A uiState = new Backbone.Model(%7B isDisabled: false %7D);%0A button = new Button(%7B uiState: uiState %7D);%0A button.on('clicked', function () %7B%0A isButtonClickHandlerInvoked = true;%0A %7D);%0A%0A uiState.set(%7B isDisabled: true %7D);%0A clickButton(button);%0A%0A expect(isButtonClickHandlerInvoked).toBeFalsy();%0A %7D);%0A%0A it('should trigger clicked-event
when re-enabled
@@ -3306,24 +3306,36 @@
(.enable())
+ and clicked
', function
@@ -3711,37 +3711,24 @@
-event when
-clicked when
re-enabled (
@@ -3735,32 +3735,44 @@
.disable(false))
+ and clicked
', function () %7B
@@ -4158,21 +4158,8 @@
hen
-clicked when
re-e
@@ -4197,24 +4197,36 @@
d: false %7D))
+ and clicked
', function
@@ -4340,32 +4340,32 @@
abled: true %7D);%0A
+
button =
@@ -4403,34 +4403,8 @@
%7D);%0A
- button.disable();%0A
|
fea368f1da1c6c3a58ad7bbcf6193d56c5592e68 | Disable idleTimer on iOS for appified apps | app/Resources/appify.js | app/Resources/appify.js | /*
* This is a template used when TiShadow "appifying" a titanium project.
* See the README.
*/
var TiShadow = require("/api/TiShadow");
var Compression = require('ti.compression');
// Need to unpack the bundle on a first load;
var path_name = "{{app_name}}".replace(/ /g,"_");
var target = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, path_name);
if (!target.exists()) {
target.createDirectory();
Compression.unzip(Ti.Filesystem.applicationDataDirectory + "/" + path_name, Ti.Filesystem.resourcesDirectory + "/" + path_name + '.zip',true);
}
//Call home
TiShadow.connect({
proto: "{{proto}}",
host : "{{host}}",
port : "{{port}}",
room : "{{room}}",
name : Ti.Platform.osname + ", " + Ti.Platform.version + ", " + Ti.Platform.address
});
//Launch the app
TiShadow.launchApp(path_name);
| JavaScript | 0 | @@ -93,16 +93,56 @@
E.%0A */%0A%0A
+Titanium.App.idleTimerDisabled = true;%0A%0A
var TiSh
|
f930c37b5af434562017c223f43e42090f45175e | clean up logging | kemia/model/reaction.js | kemia/model/reaction.js | goog.provide('kemia.model.Reaction');
goog.require('kemia.model.Molecule');
goog.require('goog.math.Box');
goog.require('goog.math.Rect');
/**
* Creates a new Reaction.
*
* @constructor
*/
kemia.model.Reaction = function() {
this.header = "";
this.reactants = [];
this.products = [];
this.arrows = [];
this.pluses = [];
this.reagentsText = "";
this.conditionsText = "";
};
// TODO add docs
kemia.model.Reaction.prototype.addReactant = function(mol) {
this.reactants.push(mol);
};
kemia.model.Reaction.prototype.addProduct = function(mol) {
this.products.push(mol);
};
kemia.model.Reaction.prototype.addArrow = function(coord){
this.arrows.push(coord);
coord.reaction = this;
}
kemia.model.Reaction.prototype.removeArrow = function(coord){
goog.array.remove(this.arrows, coord);
coord.reaction = undefined;
}
kemia.model.Reaction.prototype.addPlus = function(coord){
this.pluses.push(coord);
coord.reaction = this;
}
kemia.model.Reaction.prototype.removePlus = function(coord){
goog.array.remove(this.pluses, coord);
coord.reaction = undefined;
}
kemia.model.Reaction.prototype.generatePlusCoords = function(molecules) {
var previousMol;
goog.array.forEach(molecules, function(mol) {
if (previousMol) {
var center = this.center( [ previousMol, mol ]);
this.addPlus(center);
}
previousMol = mol;
}, this);
};
kemia.model.Reaction.prototype.generateArrowCoords = function(reactants,
products) {
var r_box = this.boundingBox(reactants);
var p_box = this.boundingBox(products);
this.addArrow(new goog.math.Coordinate((r_box.right + p_box.left)/2, (r_box.top + p_box.bottom)/2));
};
/**
* bounding box of an array of molecules
*
* @return goog.math.Box
*/
kemia.model.Reaction.prototype.boundingBox = function(molecules){
var atoms = goog.array.flatten(goog.array.map(molecules, function(mol) {
return mol.atoms;
}));
var coords = goog.array.map(atoms, function(a) {
return a.coord;
})
return goog.math.Box.boundingBox.apply(null, coords);
};
/**
* finds center of an array of molecules
*
* @return goog.math.Coordinate
*/
kemia.model.Reaction.prototype.center = function(molecules) {
var bbox = this.boundingBox(molecules);
return new goog.math.Coordinate((bbox.left + bbox.right) / 2,
(bbox.top + bbox.bottom) / 2);
};
/**
* layout molecules to eliminate any molecule overlap, if necessary
*/
kemia.model.Reaction.prototype.removeOverlap = function(){
var margin = 4;
var molecules = goog.array.concat(this.reactants, this.products);
var accumulated_rect;
goog.array.forEach(molecules, function(mol) {
var mol_rect = goog.math.Rect.createFromBox(this.boundingBox([mol]));
console.log('mol_rect: ' + mol_rect);
if (accumulated_rect){
console.log("accumulated_rect: " + accumulated_rect);
if (goog.math.Rect.intersection(accumulated_rect, mol_rect)){
this.translateMolecule(mol, new goog.math.Coordinate(margin + accumulated_rect.left + accumulated_rect.width - mol_rect.left, 0));
}
// expand to include this molecule location
accumulated_rect.boundingRect(goog.math.Rect.createFromBox(this.boundingBox([mol])));
} else{
accumulated_rect = mol_rect;
}
}, this);
console.log(molecules);
};
/**
* change molecule coordinates
*
* @param {kemia.model.Molecule}
* molecule, the molecule to translate
* @param {goog.math.Coordinate}
* coord, contains x and y change amounts
*
* @return {kemia.model.Molecule}
*/
kemia.model.Reaction.prototype.translateMolecule = function(molecule, coord){
console.log("coord: " + coord);
goog.array.forEach(molecule.atoms, function(a) {
console.log("from: " + a.coord);
a.coord = goog.math.Coordinate.sum(a.coord, coord);
console.log("to: " + a.coord);
})
};
| JavaScript | 0 | @@ -2653,127 +2653,37 @@
;%0A%09%09
-console.log('mol_rect: ' + mol_rect);%0A%09%09if (accumulated_rect)%7B%0A%09%09%09console.log(%22accumulated_rect: %22 + accumulated_rect);
+%0A%09%09if (accumulated_rect)%7B%0A%09%09%09
%0A%09%09%09
@@ -3083,32 +3083,8 @@
s);%0A
-%09console.log(molecules);
%0A%0A%7D;
@@ -3417,41 +3417,8 @@
d)%7B%0A
-%09console.log(%22coord: %22 + coord);%0A
%09goo
@@ -3467,43 +3467,8 @@
) %7B%0A
-%09%09console.log(%22from: %22 + a.coord);%0A
%09%09a.
@@ -3521,41 +3521,8 @@
d);%0A
-%09%09console.log(%22to: %22 + a.coord);%0A
%09%7D)%0A
|
405289d89629e2fab3adf6c5a97c9a4a2780f27f | remove token generation from registration | app/controllers/auth.js | app/controllers/auth.js |
/**
* Dependencies
*/
import { User, Token } from '../models'
/**
* POST a new user
*/
export async function register (ctx, next) {
try {
var user = await User.register(ctx.request.body)
} catch (err) {
if (err.code === 11000) ctx.throw('Account already exists', 422)
}
const token = await Token.generate(user)
ctx.body = { data: { user, token } }
}
/**
* POST to login
*/
export async function login (ctx, next) {
const { username, password } = ctx.request.body
const user = await User.findOneAsync({ username })
ctx.assert(user, 422, 'Account does not exist')
await user.isValidPassword(password)
? ctx.body = { data: await Token.generate(user) }
: ctx.throw('Invalid credentials', 422)
}
| JavaScript | 0 | @@ -288,51 +288,8 @@
%0A %7D
-%0A const token = await Token.generate(user)
%0A%0A
@@ -310,24 +310,13 @@
ata:
- %7B
user
-, token %7D
%7D%0A%7D
|
723ae931172e12d81fe23162d02859e1f5847a2e | remove an alert | app/controllers/list.js | app/controllers/list.js | /**
* @author Yang Sun
*/
if (Ti.Platform.osname == "iphone") {
var postBtn = Ti.UI.createButton({
title : "Post",
style : Titanium.UI.iPhone.SystemButtonStyle.PLAIN
});
postBtn.addEventListener('click', function(e) {
var postController = require('lib/post');
postController.postActivity();
});
$.listWin.rightNavButton = postBtn;
}
// create table view
var tableview;
if (Ti.Platform.osname == "android") {
tableview = Titanium.UI.createTableView({
left : 20,
right : 20,
});
} else if (Ti.Platform.osname == "iphone") {
tableview = Titanium.UI.createTableView();
}
$.listWin.add(tableview);
$.listWin.addEventListener("focus", function(e) {
refreshLocation();
});
function refreshLocation() {
Ti.Geolocation.purpose = "Recieve User Location";
Titanium.Geolocation.accuracy = Titanium.Geolocation.ACCURACY_BEST;
Titanium.Geolocation.distanceFilter = 10;
Titanium.Geolocation.getCurrentPosition(function(e) {
if (e.error) {
alert('Stash cannot get your current location');
return;
}
getMessagesOnCloud(e.coords.longitude, e.coords.latitude);
});
}
function getMessagesOnCloud(lng, lat) {
var yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
var Cloud = require('ti.cloud');
Cloud.debug = true;
Cloud.Objects.query({
classname : "messages",
limit : 50,
where : {
expiredate : {
"$gt" : yesterday
},
coordinates : {
$nearSphere : [lng, lat],
$maxDistance : 0.00126
}
},
order : "created_at"
}, function(e) {
if (e.success) {
createTableView(e.messages, lng, lat);
} else {
// alert('Error:\n' + ((e.error && e.message) || JSON.stringify(e)));
}
});
}
function createTableView(messages, lng, lat) {
var data = [];
for (var i = 0; i < messages.length; i++) {
var msg = messages[i];
if (Ti.Platform.osname == "android") {
var row = Ti.UI.createTableViewRow({
title : msg.message,
color : "white",
font : {
fontSize : 30,
fontFamily : 'Helvetica Neue'
},
height : Ti.UI.SIZE,
top : 10,
bottom : 10
});
} else if (Ti.Platform.osname == "iphone") {
var row = Ti.UI.createTableViewRow({
title : msg.message,
color : "black",
font : {
fontSize : 30,
fontFamily : 'Helvetica Neue'
},
height : Ti.UI.SIZE,
});
}
var createDate = new Date(Date(msg.created_at));
var expireDate = new Date(Date.parse(msg.expiredate));
row.addEventListener("click", function(e) {
var info = "Message: " + msg.message + "\n";
info += "Created by: " + msg.user.username + "\n";
info += "Created on: " + createDate.toLocaleDateString() + "\n";
info += "Expired on: " + expireDate.toLocaleDateString() + "\n";
info += "Distance: " + distance(lat, lng, msg.coordinates[0][1], msg.coordinates[0][0]) + " km";
alert(info);
});
data.push(row);
}
alert(data.length);
tableview.setData(data);
}
function distance(lat1, lng1, lat2, lng2) {
var radlat1 = Math.PI * lat1 / 180;
var radlat2 = Math.PI * lat2 / 180;
var radlng1 = Math.PI * lng1 / 180;
var radlng2 = Math.PI * lng2 / 180;
var theta = lng1 - lng2;
var radtheta = Math.PI * theta / 180;
var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
dist = Math.acos(dist);
dist = dist * 180 / Math.PI;
dist = dist * 60 * 1.1515;
dist = dist * 1.609344;
return parseFloat(dist).toFixed(2)
} | JavaScript | 0.000024 | @@ -2845,29 +2845,8 @@
%0A%09%7D%0A
-%09alert(data.length);%0A
%09tab
|
2aae9ec50d187ba52bb96c6f79e79ab14b1357fd | Improve parallel | src/parallel.js | src/parallel.js | import pipe from './pipe';
import _ from 'lodash';
export default (stream, pipes) => {
if (_.isEmpty(pipes)) {
return Promise.resolve(stream);
}
return new Promise((resolve, reject) => {
Promise.all(_.map(pipes, pipeDescriptor => pipe(stream, pipeDescriptor)))
.then(resolvedStreams => {
const resolvedStream = _.assign.apply(null, resolvedStreams);
resolve(resolvedStream)
})
.catch(reject);
});
}
| JavaScript | 0.000064 | @@ -45,16 +45,120 @@
dash';%0A%0A
+function reconcileResolvedStreams(resolvedStreams) %7B%0A return _.assign.apply(null, resolvedStreams);%0A%7D%0A%0A
export d
@@ -408,95 +408,40 @@
=%3E
-%7B%0A const resolvedStream = _.assign.apply(null, resolvedStreams);%0A resolve
+resolve(reconcileResolvedStreams
(res
@@ -455,17 +455,11 @@
ream
-)%0A %7D
+s))
)%0A
|
e1e854609217c2a80b3197f3b121f5ebb8c26350 | revert back to sync call | lib/markdown-to-asciidoc.js | lib/markdown-to-asciidoc.js | 'use babel';
//import MarkdownToAsciidocView from './markdown-to-asciidoc-view';
import { CompositeDisposable } from 'atom';
var path = require('path');
var java = require("java");
java.options.push('-Djava.awt.headless=true');
java.options.push('-Xrs');
java.options.push('-Xmx100m');
java.options.push('-Xmx100m');
console.log('Pushed jvm options.');
java.classpath.push(path.resolve(__dirname, "markdown_to_asciidoc-1.0.jar"));
java.classpath.push(path.resolve(__dirname, "asm-all-4.1.jar"));
java.classpath.push(path.resolve(__dirname, "jsoup-1.8.1.jar"));
java.classpath.push(path.resolve(__dirname, "parboiled-core-1.1.6.jar"));
java.classpath.push(path.resolve(__dirname, "parboiled-java-1.1.6.jar"));
java.classpath.push(path.resolve(__dirname, "pegdown-1.4.2.jar"));
console.log('Pushed classpath.');
export default {
markdownToAsciidocView: null,
modalPanel: null,
subscriptions: null,
activate(state) {
// Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
this.subscriptions = new CompositeDisposable();
// Register command that converts this view
this.subscriptions.add(atom.commands.add('atom-workspace', {
'markdown-to-asciidoc:convert': () => this.convert()
}));
},
deactivate() {
this.subscriptions.dispose();
},
convert() {
let editor
if (editor = atom.workspace.getActiveTextEditor()) {
console.log('Converting ' + editor.getPath() + ' to asciidoc.');
// Blocking
//var result = java.callStaticMethodSync("nl.jworks.markdown_to_asciidoc.Converter", "convertMarkdownToAsciiDoc", editor.getText());
//editor.setText(result);
java.callStaticMethod("nl.jworks.markdown_to_asciidoc.Converter", "convertMarkdownToAsciiDoc", editor.getText(), function(err, results) {
if(err) { console.error(err); return; }
console.log('Have result.');
editor.setText(results);
});
}
}
};
| JavaScript | 0.000001 | @@ -120,16 +120,40 @@
atom';%0A%0A
+//console.log(dialog);%0A%0A
var path
@@ -1495,17 +1495,16 @@
doc.');%0A
-%0A
//
@@ -1523,22 +1523,31 @@
-//var result =
+editor.setText(%0A
jav
@@ -1569,16 +1569,27 @@
hodSync(
+%0A
%22nl.jwor
@@ -1644,32 +1644,42 @@
downToAsciiDoc%22,
+%0A
editor.getText(
@@ -1680,16 +1680,24 @@
tText())
+%0A )
;%0A
@@ -1702,38 +1702,30 @@
//
-editor.setText(result);%0A
+ Non Blocking
%0A
+ //
jav
@@ -1864,16 +1864,19 @@
%7B%0A
+ //
if(er
@@ -1915,16 +1915,19 @@
%7D%0A
+ //
conso
@@ -1951,24 +1951,27 @@
lt.');%0A
+ //
editor.se
@@ -1995,14 +1995,16 @@
+ //
%7D);%0A
-%0A
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.