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
|
---|---|---|---|---|---|---|---|
a42850a15a6215bee18e22e608c60cd09ba20296
|
update Row component
|
src/components/grid/Row.js
|
src/components/grid/Row.js
|
const Radium = require('radium');
const React = require('react');
const Row = React.createClass({
propTypes: {
style: React.PropTypes.object
},
render () {
const styles = this.styles();
return (
<div {...this.props} style={styles.component}>
{this.props.children}
</div>
);
},
styles () {
return {
component: Object.assign({}, {
boxSizing: 'border-box',
display: 'flex',
flexWrap: 'wrap',
margin: '0 -10px'
}, this.props.style)
};
}
});
module.exports = Radium(Row);
|
JavaScript
| 0 |
@@ -1,38 +1,4 @@
-const Radium = require('radium');%0A
cons
@@ -64,438 +64,111 @@
%7B%0A
-propTypes: %7B%0A style: React.PropTypes.object%0A %7D,%0A%0A render () %7B%0A const styles = this.styles();%0A%0A return (%0A %3Cdiv %7B...this.props%7D style=%7Bstyles.component%7D%3E%0A %7Bthis.props.children%7D%0A %3C/div%3E%0A );%0A %7D,%0A%0A styles () %7B%0A return %7B%0A component: Object.assign(%7B%7D, %7B%0A boxSizing: 'border-box',%0A display: 'flex',%0A flexWrap: 'wrap',%0A margin: '0 -10px'%0A %7D, this.props.style)%0A %7D
+render () %7B%0A return (%0A %3Cdiv className=%7B'row'%7D%3E%0A %7Bthis.props.children%7D%0A %3C/div%3E%0A )
;%0A
@@ -196,16 +196,7 @@
= R
-adium(Row);%0A
+ow;
|
949089caeac3a28025d028654f8c427d36ddc921
|
Correct jshint
|
backend/config/express.js
|
backend/config/express.js
|
'use strict';
/**
* Module dependencies.
*/
var express = require('express');
var mongoStore = require('connect-mongo')(express);
var flash = require('connect-flash');
var config = require('./config');
var path = require('path');
module.exports = function (app, env, passport, dbConnexion) {
app.set('showStackError', true);
//Prettify HTML
app.locals.pretty = true;
//Should be placed before express.static
app.use(express.compress({
filter: function (req, res) {
return (/json|text|javascript|css/).test(res.getHeader('Content-Type'));
},
level: 9
}));
//Setting the fav icon and static folder
app.use(express.favicon());
app.set('port', config.port);
if (env === 'development') {
// Development only
console.log('Development Environment');
app.set('views', config.root + '/app');
app.use(express.static(path.join(config.root, 'app')));
app.use(express.errorHandler());
}
else {
// Production
console.log('Production Environment');
app.set('views', config.root + '/dist');
app.use(express.static(path.join(config.root, 'dist')));
}
// Don't use logger for test env
if (env !== 'test') {
app.use(express.logger('dev'));
}
// Enable jsonp
app.enable('jsonp callback');
app.configure(function () {
// CookieParser should be above session
app.use(express.cookieParser());
// For the view engine
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
// request body parsing middleware should be above methodOverride
app.use(express.urlencoded());
app.use(express.json());
//express/mongo session storage
app.use(express.session({
secret: 'My_Real_Secret_Here',
cookie: { maxAge: 24 * 60 * 60 * 1000 },
clear_interval: 3600,
store: new mongoStore({
db: dbConnexion.db,
collection: 'sessions'
})
}));
// Connect flash for flash messages
app.use(flash());
//use passport session
app.use(passport.initialize());
app.use(passport.session());
//routes should be at the last
app.use(app.router);
//Assume 'not found' in the error msgs is a 404. this is somewhat silly, but valid, you can do whatever you like, set properties, use instanceof etc.
app.use(function (err, req, res, next) {
//Treat as 404
if (err.message.indexOf('not found')) {
console.log('not found');
return next();
}
//Log it
console.error('Internal Error: ' + err.stack);
//Error page
res.status(500).render('500', {
error: err.stack
});
});
//Assume 404 since no middleware responded
app.use(function (req, res) {
res.status(404).render('404', {
url: req.originalUrl,
error: 'Not found'
});
});
});
};
|
JavaScript
| 0.998728 |
@@ -1695,16 +1695,51 @@
ssion(%7B%0A
+ /*jshint camelcase: false */%0A
se
|
c318ea3b628914eab3af279d2c1b4e90e792cf15
|
fix failing test due to undefined "params" in context
|
blueocean-dashboard/src/test/js/pipelines-spec.js
|
blueocean-dashboard/src/test/js/pipelines-spec.js
|
import React from 'react';
import { assert} from 'chai';
import sd from 'skin-deep';
import Immutable from 'immutable';
import Pipelines from '../../main/js/components/Pipelines.jsx';
import { pipelines } from './pipelines';
const
resultArrayHeaders = ['Name', 'Status', 'Branches', 'Pull Requests', '']
;
describe("pipelines", () => {
let tree;
const config = {
getRootURL: () => "/"
};
beforeEach(() => {
tree = sd.shallowRender(
()=>React.createElement(Pipelines), // For some reason using a fn turns on context
{
pipelines: Immutable.fromJS(pipelines),
config
}
);
});
it("renders pipelines - check header to be as expected", () => {
const
header = tree.subTree('Table').getRenderOutput();
assert.equal(header.props.headers.length, resultArrayHeaders.length);
});
it("renders pipelines - check rows number to be as expected", () => {
const
row = tree.everySubTree('PipelineRowItem')
;
assert.equal(row.length, 2);
});
});
|
JavaScript
| 0.000001 |
@@ -400,16 +400,40 @@
%22%0A %7D;%0A%0A
+ const params = %7B%7D;%0A%0A
before
@@ -633,16 +633,36 @@
lines),%0A
+ params,%0A
@@ -671,16 +671,17 @@
config
+,
%0A
|
ca060ca3176f0db95c84fbfc0044ed374babebea
|
Remove line under the last sort by item
|
app/hotels/src/filter/order/OrderPopup.js
|
app/hotels/src/filter/order/OrderPopup.js
|
// @flow strict
import * as React from 'react';
import { View } from 'react-native';
import { ButtonPopup, Text, StyleSheet } from '@kiwicom/mobile-shared';
import { Translation } from '@kiwicom/mobile-localization';
import { defaultTokens } from '@kiwicom/mobile-orbit';
import { SeparatorFullWidth } from '@kiwicom/mobile-navigation';
import type { OrderByEnum } from '../FilterParametersType';
import OrderCheckbox from './OrderCheckbox';
const ordersOptions = [
{
key: 'PRICE',
title: <Translation id="hotels_search.filter.order_popup.price" />,
},
{
key: 'DISTANCE',
title: <Translation id="hotels_search.filter.order_popup.distance" />,
},
{
key: 'STARS',
title: <Translation id="hotels_search.filter.order_popup.stars" />,
},
];
type Props = {|
+onClose: () => void,
+onSave: (orderBy: OrderByEnum | null) => void,
+isVisible: boolean,
+orderBy: OrderByEnum | null,
|};
type State = {|
currentOrder: OrderByEnum | null,
|};
export default class OrderPopup extends React.Component<Props, State> {
state = {
currentOrder: this.props.orderBy,
};
onSave = () => {
this.props.onSave(this.state.currentOrder);
};
onClose = () => {
this.setState({ currentOrder: null });
this.props.onClose();
};
setOrder = (currentOrder: OrderByEnum | null) => {
this.setState({ currentOrder });
};
render = () => (
<ButtonPopup
buttonTitle={<Translation id="shared.button.save" />}
buttonCloseTitle={<Translation id="shared.button.close" />}
onSave={this.onSave}
onClose={this.onClose}
isVisible={this.props.isVisible}
>
<Text style={styles.title}>
<Translation id="hotels_search.filter.order_popup.title" />
</Text>
{ordersOptions.map(option => (
<React.Fragment key={option.key}>
<OrderCheckbox
onPress={this.setOrder}
isChecked={this.state.currentOrder === option.key}
checkKey={option.key}
>
{option.title}
</OrderCheckbox>
<View style={styles.separator}>
<SeparatorFullWidth color={defaultTokens.paletteInkLighter} />
</View>
</React.Fragment>
))}
</ButtonPopup>
);
}
const styles = StyleSheet.create({
title: {
color: defaultTokens.colorHeading,
fontSize: 16,
fontWeight: '500',
paddingTop: 15,
paddingBottom: 10,
},
separator: {
marginEnd: -15,
},
});
|
JavaScript
| 0.000001 |
@@ -1771,22 +1771,31 @@
ons.map(
+(
option
+, index)
=%3E (%0A
@@ -1834,16 +1834,198 @@
n.key%7D%3E%0A
+ %7Bindex !== 0 && (%0A %3CView style=%7Bstyles.separator%7D%3E%0A %3CSeparatorFullWidth color=%7BdefaultTokens.paletteInkLighter%7D /%3E%0A %3C/View%3E%0A )%7D%0A
@@ -2209,24 +2209,24 @@
tion.title%7D%0A
+
%3C/
@@ -2244,143 +2244,8 @@
ox%3E%0A
- %3CView style=%7Bstyles.separator%7D%3E%0A %3CSeparatorFullWidth color=%7BdefaultTokens.paletteInkLighter%7D /%3E%0A %3C/View%3E%0A
|
88a9538d6692f3c9d28f38f9d417e183f19610c8
|
Fix karma runner ports. It appears the port number for the karma server running unit tests in the background during 'grunt watch' was the same as the one used when running E2E tests. As a result, the 'karma:unit:run' test wasn't running properly.
|
karma/karma-e2e.tpl.js
|
karma/karma-e2e.tpl.js
|
module.exports = function ( karma ) {
karma.set({
/**
* From where to look for files, starting with the location of this file.
*/
basePath: '../',
/**
* This is the list of file patterns to load into the browser during testing.
*/
files: [
// Include the ng-scenario library and adapter
// Remove these when `karma-ng-scenario` can be included:
// https://github.com/karma-runner/grunt-karma/issues/13
'vendor/angular-scenario/angular-scenario.js',
'node_modules/karma-ng-scenario/lib/adapter.js',
// Include all scenario tests
'src/**/*.scenario.*',
// Serve the contents of the "dist" folder as static files
{pattern: 'build/**/*', watched: false, included: false, served: true}
],
//frameworks: [ 'ng-scenario' ],
plugins: [ 'karma-firefox-launcher', 'karma-chrome-launcher', 'karma-coffee-preprocessor' ],
preprocessors: {
'**/*.coffee': 'coffee'
},
/**
* How to report, by default.
*/
reporters: 'dots',
/**
* On which port should the browser connect, on which port is the test runner
* operating, and what is the URL path for the browser to use.
*/
port: 9019,
runnerPort: 9101,
urlRoot: '/',
/**
* Disable file watching by default.
*/
autoWatch: false,
/**
* Run E2E tests once by default
*/
singleRun: true,
/**
* The list of browsers to launch to test on. This includes only "Firefox" by
* default, but other browser names include:
* Chrome, ChromeCanary, Firefox, Opera, Safari, PhantomJS
*
* Note that you can also use the executable name of the browser, like "chromium"
* or "firefox", but that these vary based on your operating system.
*
* You may also leave this blank and manually navigate your browser to
* http://localhost:9018/ when you're running tests. The window/tab can be left
* open and the tests will automatically occur there during the build. This has
* the aesthetic advantage of not launching a browser every time you save.
*/
browsers: [
'Firefox'
]
});
};
|
JavaScript
| 0 |
@@ -1226,10 +1226,10 @@
: 90
-19
+20
,%0A
@@ -1245,17 +1245,17 @@
ort: 910
-1
+2
,%0A ur
|
f1b77735ac3b149894e465ccf0ae6d3a8de333be
|
redefine port to fix bundling error
|
backend/headlessServer.js
|
backend/headlessServer.js
|
import {Sessions} from './sessions';
import {Logger} from './logger';
import {SequelizeManager, OPTIONS} from './sequelizeManager';
import {ElasticManager} from './elasticManager';
import {serverMessageReceive,
CHANNEL} from './messageHandler';
import * as fs from 'fs';
import YAML from 'yamljs';
let mainWindow = null;
import restify from 'restify';
import {setupRoutes} from './routes';
const logger = new Logger(OPTIONS, mainWindow, CHANNEL);
const sessions = new Sessions();
const sequelizeManager = new SequelizeManager(logger, sessions);
const elasticManager = new ElasticManager(logger, sessions);
const responseTools = {
sequelizeManager, elasticManager, mainWindow, OPTIONS
};
const acceptRequestsFrom = YAML.load(`${__dirname}/acceptedDomains.yaml`);
console.warn('process.env: ', process.env);
if (OPTIONS.https) {
const keyFile = `${__dirname}/../ssl/certs/server/privkey.pem`;
const csrFile = `${__dirname}/../ssl/certs/server/fullchain.pem`;
console.log('using the following certs');
console.warn('keyFile: ', keyFile);
console.warn('csrFile: ', csrFile);
const httpsOptions = {
key: fs.readFileSync(keyFile),
certificate: fs.readFileSync(csrFile)
};
const httpsServer = restify.createServer(httpsOptions);
/*
* parsed content will always be available in req.query,
* additionally params are merged into req.params
*/
httpsServer.use(restify.queryParser());
httpsServer.use(restify.bodyParser({ mapParams: true }));
httpsServer.use(restify.CORS({
origins: acceptRequestsFrom.domains,
credentials: false,
headers: ['Access-Control-Allow-Origin']
})).listen(process.env.PORT || OPTIONS.port);
console.log('listening on port ', process.env.PORT || OPTIONS.port);
/*
* https://github.com/restify/node-restify/issues/664
* Handle all OPTIONS requests to a deadend (Allows CORS to work them out)
*/
httpsServer.opts( /.*/, (req, res) => res.send(204));
setupRoutes(httpsServer, serverMessageReceive(responseTools));
console.log('https server is setup');
} else {
const httpServer = restify.createServer();
httpServer.use(restify.queryParser());
httpServer.use(restify.bodyParser({ mapParams: true }));
httpServer.use(restify.CORS({
origins: ['*'],
credentials: false,
headers: ['Access-Control-Allow-Origin']
})).listen(process.env.PORT || OPTIONS.port);
console.log(`listening on port ${process.env.PORT || OPTIONS.port}`);
setupRoutes(httpServer, serverMessageReceive(responseTools));
console.log('http server is setup');
}
|
JavaScript
| 0.000001 |
@@ -298,16 +298,39 @@
yamljs';
+%0Aimport R from 'ramda';
%0A%0Alet ma
@@ -799,49 +799,176 @@
);%0A%0A
-console.warn('process.env: ', process.env
+let port;%0Aif (R.has('PORT', process.env) && process.env.PORT) %7B%0A port = process.env.PORT;%0A%7D else %7B%0A port = OPTIONS.port;%0A%7D%0Aconsole.log(%60listening on port $%7Bport%7D%60
);%0A%0A
@@ -1847,114 +1847,14 @@
en(p
-rocess.env.PORT %7C%7C OPTIONS.port);%0A console.log('listening on port ', process.env.PORT %7C%7C OPTIONS.p
ort);
+%0A
%0A
@@ -2486,113 +2486,11 @@
en(p
-rocess.env.PORT %7C%7C OPTIONS.port);%0A console.log(%60listening on port $%7Bprocess.env.PORT %7C%7C OPTIONS.port%7D%60
+ort
);%0A%0A
|
e204496472a91c3ed324cbf36581865e7cf24dfd
|
rename sn.fm.loadingScreen EVENTS => ROUTE_EVENTS
|
app/js/fm-loading-screen/loadingScreen.js
|
app/js/fm-loading-screen/loadingScreen.js
|
"use strict";
/**
* Implements a loading screen inbetween route changes
* @module sn.fm.loadingScreen
* @author SOON_
*/
angular.module("sn.fm.loadingScreen", [])
/**
* @constant
* @property EVENTS
* @type {Object}
*/
.constant("EVENTS", {
ROUTE_CHANGE_START: "$routeChangeStart",
ROUTE_CHANGE_SUCCESS: "$routeChangeSuccess",
ROUTE_CHANGE_ERROR: "$routeChangeError"
})
/**
* Angular directive for a progress bar
* @example
<fm-loading-screen></fm-loading-screen>
* @class fmLoadingScreen
* @module sn.fm.loadingScreen
* @author SOON_
*/
.directive("fmLoadingScreen",[
"$rootScope",
"EVENTS",
/**
* @constructor
* @param {Service} $rootScope
* @param {Object} EVENTS
*/
function ($rootScope, EVENTS){
return {
restrict: "EA",
templateUrl: "partials/loading.html",
link: function ($scope, $element){
/**
* display the loading screen
* @method show
*/
var show = function show(){
$element.removeClass("hide");
};
/**
* hide the loading screen
* @method show
*/
var hide = function hide(){
$element.addClass("hide");
};
$rootScope.$on(EVENTS.ROUTE_CHANGE_START, show);
$rootScope.$on(EVENTS.ROUTE_CHANGE_SUCCESS, hide);
$rootScope.$on(EVENTS.ROUTE_CHANGE_ERROR, hide);
}
};
}
]);
|
JavaScript
| 0.000002 |
@@ -190,16 +190,22 @@
roperty
+ROUTE_
EVENTS%0A
@@ -236,16 +236,22 @@
nstant(%22
+ROUTE_
EVENTS%22,
@@ -627,16 +627,22 @@
%22,%0A %22
+ROUTE_
EVENTS%22,
@@ -729,16 +729,22 @@
bject%7D
+ROUTE_
EVENTS%0A
@@ -776,16 +776,22 @@
tScope,
+ROUTE_
EVENTS)%7B
@@ -1415,32 +1415,38 @@
$rootScope.$on(
+ROUTE_
EVENTS.ROUTE_CHA
@@ -1486,32 +1486,38 @@
$rootScope.$on(
+ROUTE_
EVENTS.ROUTE_CHA
@@ -1567,16 +1567,22 @@
ope.$on(
+ROUTE_
EVENTS.R
|
291dea97503abdd79637f7d58a67b33b9256ae63
|
Handle error case
|
src/js/controllers/buy-bitcoin/kyc-status.controller.js
|
src/js/controllers/buy-bitcoin/kyc-status.controller.js
|
'use strict';
(function () {
angular
.module('bitcoincom.controllers')
.controller('buyBitcoinKycStatusController',
buyBitcoinKycStatusController);
function buyBitcoinKycStatusController(
bitAnalyticsService
, gettextCatalog
, kycFlowService
, moonPayService
, moment
, ongoingProcess
, popupService
, $scope
, $ionicHistory
) {
var currentState = {};
var vm = this;
// Functions
vm.goBack = goBack;
$scope.$on("$ionicView.beforeEnter", onBeforeEnter);
$scope.$on("$ionicView.beforeLeave", onBeforeLeave);
function _initVariables() {
currentState = kycFlowService.getCurrentStateClone();
// Title Label
vm.statusTitle = gettextCatalog.getString('Pending');
// Identity Check Status
if(!currentState.status) {
// Do Submit to Moonpay
ongoingProcess.set('submitingKycInfo', true);
moonPayService.getCustomer().then(function onGetCustomerSuccess(customer) {
var taskList = [];
// Update Customer
customer.firstName = currentState.firstName
customer.lastName = currentState.lastName
customer.dateOfBirth = moment(currentState.dob, 'DD/MM/YYY').format('YYYY-MM-DD')
customer.address = {
'street': currentState.streetAddress1
, 'town': currentState.city
, 'postCode': currentState.postalCode
, 'country': currentState.country
}
if (currentState.streetAddress2) {
customer.address.subStreet = currentState.streetAddress2;
}
taskList.push(moonPayService.updateCustomer(customer));
// Upload documents
currentState.documents.forEach(function(imageFile, index) {
if( index === currentState.documents.length-1) {
taskList.push(moonPayService.uploadFile(imageFile, 'selfie', currentState.countryCode, null));
}
taskList.push(moonPayService.uploadFile(imageFile, currentState.documentType, currentState.countryCode, index === 0 ? 'front' : 'back'));
});
// Block All for Completion
Promise.all(taskList).then(function onTaskListSuccess(results) {
moonPayService.createIdentityCheck().then(function onSuccess(response) {
try {
// Clean history
var historyId = $ionicHistory.currentHistoryId();
var history = $ionicHistory.viewHistory().histories[historyId];
for (var i = history.stack.length - 1; i >= 0; i--){
if (history.stack[i].stateName == 'tabs.buybitcoin'){
$ionicHistory.backView(history.stack[i]);
}
}
} catch (err) {
console.log(err);
}
updateStatusUi(response);
}).catch(function onError(error) {
// Activate Retry Button
console.log('Moonpay API Errors:', error);
popupService.showAlert(gettextCatalog.getString('Error'), gettextCatalog.getString('Failed to submit information. Please try again.'));
}).finally(function onComplete() {
ongoingProcess.set('submitingKycInfo', false);
});
}).catch(function(error) {
console.log('Moonpay API Errors:', error);
popupService.showAlert(gettextCatalog.getString('Error'), gettextCatalog.getString('Failed to submit information. Please try again.'));
// Activate Retry Button
// TODO: Add Back button logic to popup
ongoingProcess.set('submitingKycInfo', false);
});
})
} else {
ongoingProcess.set('fetchingKycStatus', true);
moonPayService.getIdentityCheck().then(function onSuccess(response) {
updateStatusUi(response);
ongoingProcess.set('fetchingKycStatus', false);
}).catch(function onError(error) {
// Activate Retry Button
ongoingProcess.set('fetchingKycStatus', false);
});
}
}
function updateStatusUi(response) {
var statusType;
if(response.status === 'completed') {
statusType = response.result === 'clear' ? 'accepted' : 'rejected';
}
switch(statusType) {
case 'accepted':
vm.statusTitle = gettextCatalog.getString('Verified');
vm.description = gettextCatalog.getString('Your account has been successfully verified.');
break;
case 'rejected':
vm.statusTitle = gettextCatalog.getString('Rejected');
vm.description = gettextCatalog.getString('Your verification was denied. Please contact support for additional assistance.');
break;
default:
vm.statusTitle = gettextCatalog.getString('Pending');
vm.description = gettextCatalog.getString('Your account is currently being verified. This process may take up to 3 business days.');
break;
}
}
function goBack() {
$ionicHistory.goBack();
}
function onBeforeEnter(event, data) {
_initVariables();
bitAnalyticsService.postEvent('buy_bitcoin_kyc_status_screen_open' ,[], ['leanplum']);
}
function onBeforeLeave(event, data) {
bitAnalyticsService.postEvent('buy_bitcoin_kyc_status_screen_close' ,[], ['leanplum']);
}
}
})();
|
JavaScript
| 0.000002 |
@@ -3180,32 +3180,102 @@
ase try again.')
+, function() %7B%0A $ionicHistory.goBack();%0A %7D
);%0A %7D
@@ -3469,32 +3469,128 @@
rors:', error);%0A
+ // Activate Retry Button%0A ongoingProcess.set('submitingKycInfo', false);%0A
popu
@@ -3722,156 +3722,74 @@
n.')
-);%0A // Activate Retry Button%0A // TODO: Add Back button logic to popup%0A ongoingProcess.set('submitingKycInfo', false
+, function() %7B%0A $ionicHistory.goBack();%0A %7D
);%0A
@@ -4184,32 +4184,237 @@
tatus', false);%0A
+ popupService.showAlert(gettextCatalog.getString('Error'), gettextCatalog.getString('Failed to get information. Please try again.'), function() %7B%0A $ionicHistory.goBack();%0A %7D);%0A
%7D);%0A
|
df4d9121da36526d48584a75cc8f2c4122d0fa93
|
set max filter date for user stats view to last Friday
|
app/js/users/controllers/UserStatsCtrl.js
|
app/js/users/controllers/UserStatsCtrl.js
|
"use strict";
/**
* @module FM.users.UserStatsCtrl
* @author SOON_
*/
angular.module("FM.users.UserStatsCtrl", [
"FM.api.UsersResource",
"FM.stats",
"ngRoute",
"chart.js",
"ui.bootstrap.datepicker"
])
/**
* @method config
* @param {Provider} $routeProvider
*/
.config([
"$routeProvider",
function ($routeProvider) {
$routeProvider
.when("/users/:id", {
templateUrl: "partials/users/stats.html",
controller: "UserStatsCtrl",
resolve: {
stats: ["statsResolver", "$route", "UsersResource", function (statsResolver, $route, UsersResource) {
return statsResolver(UsersResource.stats, $route.current.params);
}],
user: ["UsersResource", "$route", function (UsersResource, $route){
return UsersResource.get($route.current.params).$promise;
}]
}
});
}
])
/**
* @constructor
* @class UserStatsCtrl
* @param {Object} $scope Scoped application data
* @param {Service} $q Angular promise service
* @param {Service} $filter Angular filter service
* @param {Service} $location Angular URL service
* @param {Service} DateUtils Date helper functions
* @param {Array} CHART_COLOURS List of global chart colours
* @param {Object} CHART_OPTIONS ChartJS config options
* @param {Resource} StatsResource Provides communication with stats API endpoint
* @param {Object} stats User's stats resolved from API
* @param {Object} user User object resolved from API
*/
.controller("UserStatsCtrl", [
"$scope",
"$q",
"$filter",
"$location",
"DateUtils",
"CHART_COLOURS",
"CHART_OPTIONS",
"UsersResource",
"stats",
"user",
function ($scope, $q, $filter, $location, DateUtils, CHART_COLOURS, CHART_OPTIONS, UsersResource, stats, user) {
/**
* User
* @property {Object} user
*/
$scope.user = user;
/**
* User's stats resolved from API
* @property {Object} stats
*/
$scope.stats = stats;
/**
* Current search params
* @property {Object} search
*/
$scope.search = $location.search();
/**
* @property {Object} filter
*/
$scope.filter = {};
/**
* Track open status of datepickers
* @property {Object} datepickerOpened
*/
$scope.datepickerOpened = {
from: "",
to: ""
};
/**
* List of colours to use for charts
* @property {Array} chartColours
*/
$scope.chartColours = CHART_COLOURS;
/**
* ChartJS config for play time line graph
* @property {Object} playTime
*/
$scope.playTime = {
data: [[]],
series: [user.display_name], // jshint ignore:line
labels: [],
options: CHART_OPTIONS
};
/**
* Load historic play time statistics for line chart based on filter start/end dates
* @method loadHistoricData
* @param {String} startDate Filter start date
* @param {String} endDate Filter end date
*/
$scope.loadHistoricData = function loadHistoricData (startDate, endDate) {
var dates = DateUtils.historicDatePeriods(startDate, endDate, 3);
// request historic data from API using calculated date ranges
$q.all([
UsersResource.stats({ from: dates[0].from, to: dates[0].to, id: user.id }).$promise,
UsersResource.stats({ from: dates[1].from, to: dates[1].to, id: user.id }).$promise,
UsersResource.stats({ from: dates[2].from, to: dates[2].to, id: user.id }).$promise
]).then(function (responses) {
responses.forEach(function (response, index) {
// add data to play time chart dataset
$scope.playTime.labels.unshift($filter("date")(dates[index].from, "dd-MM-yyyy"));
// convert milliseconds to minutes
$scope.playTime.data[0].unshift(Math.round(response.total_play_time / 1000 / 60)); // jshint ignore:line
});
});
};
/**
* Filter stats by dates
* @method updateFilter
*/
$scope.updateFilter = function updateFilter () {
if ($scope.filter.to) {
$scope.search.to = $scope.filter.to.toISOString ? $filter("date")($scope.filter.to.toISOString(), "yyyy-MM-dd") : $scope.filter.to;
} else {
$scope.search.to = undefined;
}
if ($scope.filter.from) {
$scope.search.from = $scope.filter.from.toISOString ? $filter("date")($scope.filter.from.toISOString(), "yyyy-MM-dd") : $scope.filter.from;
} else {
$scope.search.from = undefined;
$scope.search.all = true;
}
$location.search($scope.search);
};
/**
* Open datepicker
* @method updateFilter
*/
$scope.openDatepicker = function openDatepicker($event, id) {
$event.preventDefault();
$event.stopPropagation();
$scope.datepickerOpened[id] = !$scope.datepickerOpened[id] ;
};
/**
* Set current filter params and load historic data on initalise
* @method init
*/
$scope.init = function init () {
$scope.filter.from = $scope.search.from || undefined;
$scope.filter.to = $scope.search.to || undefined;
// set max datepicker date to today
$scope.datepickerMaxDate = new Date();
if ($scope.filter.from) {
// Format total play time per user stats for charts
$scope.playTime.labels.unshift($filter("date")($scope.filter.from, "dd-MM-yyyy"));
// convert milliseconds to minutes
$scope.playTime.data[0].unshift(Math.round(stats.total_play_time / 1000 / 60)); // jshint ignore:line
// Load additional data for play time line chart
$scope.loadHistoricData($scope.filter.from, $scope.filter.to);
}
};
$scope.init();
}
]);
|
JavaScript
| 0.000001 |
@@ -5919,17 +5919,33 @@
e =
-new Date(
+DateUtils.lastOccurence(5
);%0A%0A
|
01d1b9467080c75679e38639f8a3e7cdd82eb4ce
|
add asynDataGet function
|
app/scripts/dataservice/CommonDatabase.js
|
app/scripts/dataservice/CommonDatabase.js
|
// CommonDatabase.js
import axios from 'axios';
import {getAPI} from './config.js';
var User=function(){
this.data=null;
}
User.prototype.asynLogin=function(email,psw){
var userAPI=getAPI('Login');
var scope=this;
return axios[userAPI.method](userAPI.url,{
email:email,
password:psw,
}).then(function(data){
var user=data.data;
if(user.data)
{
scope.setUser(user.data);
return user;
}
else{
throw new Error(user.msg);
}
},function(){
throw new Error(null);
});
}
User.prototype.storeUserInLocal=function(){
}
User.prototype.getUserFromLocal=function(){
}
User.prototype.getUser=function(){
return this.data;
}
User.prototype.setUser=function(user){
return this.data=user;
}
var user=new User();
export{user};
|
JavaScript
| 0.000001 |
@@ -77,16 +77,52 @@
ig.js';%0A
+import Util from '../core/Util.js';%0A
%0A%0Avar Us
@@ -759,16 +759,17 @@
user;%0A%7D%0A
+%0A
var user
@@ -785,17 +785,255 @@
();%0A
-export%7Buser
+%0Afunction asynData(apiName, data=%7B%7D)%7B%0A%09return axios%5BapiName.method%5D(apiName.url,data)%0A%09.then(function(data)%7B%0A%09%09console.log(data);%0A%09%09return data;%0A%09%7D,function()%7B%0A%09%09throw new Error('failed to get data from server');%0A%09%7D)%0A%7D%0A%0Aexport%7Buser, asynData ,getAPI
%7D;
|
18c3941f75d5376f9f730abec6bf380bd1018bc5
|
Remove vm. for local variable in function.
|
app/scripts/services/bodyclass-service.js
|
app/scripts/services/bodyclass-service.js
|
'use strict';
(function() {
angular.module('ncsaas')
.service('BodyClassService', [BodyClassService]);
function BodyClassService() {
var vm = this;
vm.getBodyClass = getBodyClass;
function getBodyClass(name) {
var stateWithProfile = [
'profile',
'profile-edit',
'project',
'project-edit',
'customer',
'customer-edit',
'customer-plans',
'user',
'home',
'login',
];
if (stateWithProfile.indexOf(name) > -1 ) {
if (name === 'login' || name === 'home') {
vm.bodyClass = 'app-body site-body';
return vm.bodyClass;
} else {
vm.bodyClass = 'app-body obj-view';
return vm.bodyClass;
}
} else {
vm.bodyClass = 'app-body'
return vm.bodyClass;
}
}
}
})();
|
JavaScript
| 0 |
@@ -230,24 +230,48 @@
ass(name) %7B%0A
+ var bodyClass;%0A%0A
var
@@ -638,35 +638,32 @@
) %7B%0A
-vm.
bodyClass = 'app
@@ -691,35 +691,32 @@
return
-vm.
bodyClass;%0A
@@ -733,35 +733,32 @@
e %7B%0A
-vm.
bodyClass = 'app
@@ -785,35 +785,32 @@
return
-vm.
bodyClass;%0A
@@ -843,19 +843,16 @@
-vm.
bodyClas
@@ -883,19 +883,16 @@
return
-vm.
bodyClas
|
f96b5bd8444ef5c46c5a6aeccfe3fde289c4286b
|
Tweak cookie expiry to 12hrs
|
app/scripts/views/home/home-controller.js
|
app/scripts/views/home/home-controller.js
|
(function() {
'use strict';
/**
* Controller for the imls app home view
*/
/* ngInject */
function HomeController($cookies, $log, $q, $scope, $geolocation, $state, Config, Geocoder, Museum) {
var ctl = this;
var map = null;
var searchMarker = null;
var SEARCH_DIST_METERS = 1609.34; // 1 mile
initialize();
function initialize() {
ctl.list = [];
ctl.safeList = [];
ctl.states = {
DISCOVER: 0,
LIST: 1,
ERROR: -1
};
ctl.pageState = ctl.states.DISCOVER;
ctl.rowsPerPage = 10;
ctl.onLocationClicked = onLocationClicked;
ctl.onSearchClicked = onSearchClicked;
ctl.onTypeaheadSelected = onTypeaheadSelected;
ctl.search = search;
$scope.$on('imls:vis:ready', function (e, vis, newMap) {
map = newMap;
var lastSearched = $cookies.getObject(Config.cookies.LAST_SEARCHED);
if (lastSearched) {
ctl.pageState = ctl.states.LIST;
ctl.searchText = lastSearched.text;
requestNearbyMuseums(lastSearched.position);
}
});
}
function onLocationClicked() {
$geolocation.getCurrentPosition({
enableHighAccuracy: true,
maximumAge: 0
}).then(function (position) {
requestNearbyMuseums({
x: position.coords.longitude,
y: position.coords.latitude
});
})
.catch(function (error) {
$log.error(error);
ctl.pageState = ctl.states.ERROR;
});
}
function onSearchClicked() {
search(ctl.searchText);
}
function search(text) {
return $q.all([Geocoder.search(text), Museum.suggest(text)]).then(function (results) {
$log.info(results);
return _.flatten(results);
}).catch(function (error) {
ctl.pageState = ctl.states.ERROR;
$log.error(error);
});
}
function onTypeaheadSelected(item) {
if (item.ismuseum) {
requestNearbyMuseums({
x: item.longitude,
y: item.latitude
});
} else if (item.feature) {
// TODO: Additional handling to pass extent to requestNearbyMuseums?
requestNearbyMuseums(item.feature.geometry);
} else {
$log.error('No valid handlers for typeahead item:', item);
ctl.pageState = ctl.states.ERROR;
}
}
// position is an object with x and y keys
function requestNearbyMuseums(position) {
map.setView([position.y, position.x], Config.detailZoom);
addSearchLocationMarker(position);
Museum.list(position, SEARCH_DIST_METERS).then(function (rows) {
if (rows.length) {
ctl.list = rows;
ctl.pageState = ctl.states.LIST;
setLastPositionCookie(position);
} else {
ctl.pageState = ctl.states.ERROR;
}
}).catch(function (error) {
$log.error(error);
ctl.pageState = ctl.states.ERROR;
});
}
function setLastPositionCookie(position) {
$cookies.putObject(Config.cookies.LAST_SEARCHED, {
text: ctl.searchText || '',
position: position
}, {
expires: new Date(new Date().getTime() + 3600 * 1000)
});
}
function addSearchLocationMarker(position) {
clearSearchLocationMarker();
searchMarker = L.marker([position.y, position.x], {
clickable: false,
keyboard: false
});
searchMarker.addTo(map);
}
function clearSearchLocationMarker() {
if (searchMarker) {
map.removeLayer(searchMarker);
searchMarker = null;
}
}
}
angular.module('imls.views.home')
.controller('HomeController', HomeController);
})();
|
JavaScript
| 0.000002 |
@@ -3772,24 +3772,77 @@
%7D, %7B%0A
+ // Set expiry to 12hrs from set time%0A
@@ -3885,16 +3885,21 @@
Time() +
+ 12 *
3600 *
|
c46650e67e217430ceab71947a985e1f6f106dab
|
Correct server error on errorController.errorAction and offer the possibilty to add an error message
|
app/server/controllers/errorController.js
|
app/server/controllers/errorController.js
|
'use strict';
/**
* @module core-controllers
*/
/**
* Provides route actions to deal with errors.
*
* @class errorController
*/
var errors = process.require('app/server/httpErrors.js');
var defaultController = process.require('app/server/controllers/defaultController.js');
/**
* Handles requests which does not correspond to anything.
*
* @method notFoundAction
* @static
*/
module.exports.notFoundAction = function(request, response, next) {
next(errors.PATH_NOT_FOUND);
};
/**
* Handles all errors.
*
* @example
* {
* "code" : 1,
* "httpCode" : 500,
* "module" : "core"
* }
*
* @method errorAction
* @static
* @param {Object} error An error object with error code, HTTP code
* and the module associated to the error
*/
module.exports.errorAction = function(error, request, response, next) {
if (!error)
error = errors.UNKNOWN_ERROR;
if (!error.module)
error.module = 'core';
process.logger.error('Error', {
code: error.code,
module: error.module,
method: request.method,
path: request.url,
headers: request.headers
});
// Send response with HTML content
if (request.accepts('html') && (error.httpCode == '401' || error.httpCode == '403')) {
response.status(error.httpCode);
defaultController.defaultAction(request, response, next);
return;
}
// Send response with JSON content or HTML but not 401 or 403 errorCode
response.status(error.httpCode);
response.send({error: {
code: error.code,
module: error.module
}});
};
/**
* Handles forgotten requests.
*
* Depending on request Accept HTTP header, either an HTML content,
* a JSON content or a text content will be returned with a 404 code.
*
* @method notFoundPageAction
* @static
*/
module.exports.notFoundPageAction = function(request, response) {
process.logger.warn('404 Not Found', {
method: request.method,
path: request.url,
headers: request.headers
});
response.status(404);
// HTML content
if (request.accepts('html')) {
response.render('404', {
url: request.url
});
return;
}
// JSON content
if (request.accepts('json')) {
response.send({
error: 'Not found',
url: request.url
});
return;
}
// Text content
response.type('txt').send(request.url + ' not found');
};
|
JavaScript
| 0.000001 |
@@ -857,16 +857,31 @@
(!error
+ %7C%7C !error.code
)%0A er
@@ -1496,16 +1496,21 @@
e.send(%7B
+%0A
error: %7B
@@ -1510,24 +1510,26 @@
rror: %7B%0A
+
+
code: error.
@@ -1526,32 +1526,34 @@
de: error.code,%0A
+
module: erro
@@ -1560,20 +1560,55 @@
r.module
+,%0A message: error.message%0A %7D
%0A
-%7D
%7D);%0A%7D;%0A%0A
|
92f8af02ef21b6a8cd741d5d694cba5a8e17ea51
|
fix syntax error
|
app/services/database/removeDuplicates.js
|
app/services/database/removeDuplicates.js
|
"use strict"
const mongoose = require('mongoose'),
Concept = require('../../models/Concept');
module.exports = () => {
let data = {}
Concept.find()
.sort('label')
.select('label _id')
.exec((err, collection)=>{
if (err) throw err
let dupes = {}
collection.forEach((entry) => {
if (!dupes[entry.label.replace(/ /g, "")]) {
dupes[.replace(/ /g, "")] = true
} else {
//remove the entry
Concept.find({_id: entry._id})
.remove()
}
})
}) // end find
} //end exports
|
JavaScript
| 0.000003 |
@@ -394,16 +394,27 @@
dupes%5B
+entry.label
.replace
|
f1c867010229011fb6c4cfa7853f301885566cc7
|
Remove unnecessary script attributes
|
src/util/dom_misc.js
|
src/util/dom_misc.js
|
(function() {
var _slice = Array.prototype.slice;
/**
* Takes id and returns an element with that id (if one exists in a document)
* @memberOf fabric.util
* @param {String|HTMLElement} id
* @return {HTMLElement|null}
*/
function getById(id) {
return typeof id === 'string' ? fabric.document.getElementById(id) : id;
}
/**
* Converts an array-like object (e.g. arguments or NodeList) to an array
* @memberOf fabric.util
* @param {Object} arrayLike
* @return {Array}
*/
var toArray = function(arrayLike) {
return _slice.call(arrayLike, 0);
};
var sliceCanConvertNodelists;
try {
sliceCanConvertNodelists = toArray(fabric.document.childNodes) instanceof Array;
}
catch(err) { }
if (!sliceCanConvertNodelists) {
toArray = function(arrayLike) {
var arr = new Array(arrayLike.length), i = arrayLike.length;
while (i--) {
arr[i] = arrayLike[i];
}
return arr;
};
}
/**
* Creates specified element with specified attributes
* @memberOf fabric.util
* @param {String} tagName Type of an element to create
* @param {Object} [attributes] Attributes to set on an element
* @return {HTMLElement} Newly created element
*/
function makeElement(tagName, attributes) {
var el = fabric.document.createElement(tagName);
for (var prop in attributes) {
if (prop === 'class') {
el.className = attributes[prop];
}
else if (prop === 'for') {
el.htmlFor = attributes[prop];
}
else {
el.setAttribute(prop, attributes[prop]);
}
}
return el;
}
/**
* Adds class to an element
* @memberOf fabric.util
* @param {HTMLElement} element Element to add class to
* @param {String} className Class to add to an element
*/
function addClass(element, className) {
if ((' ' + element.className + ' ').indexOf(' ' + className + ' ') === -1) {
element.className += (element.className ? ' ' : '') + className;
}
}
/**
* Wraps element with another element
* @memberOf fabric.util
* @param {HTMLElement} element Element to wrap
* @param {HTMLElement|String} wrapper Element to wrap with
* @param {Object} [attributes] Attributes to set on a wrapper
* @return {HTMLElement} wrapper
*/
function wrapElement(element, wrapper, attributes) {
if (typeof wrapper === 'string') {
wrapper = makeElement(wrapper, attributes);
}
if (element.parentNode) {
element.parentNode.replaceChild(wrapper, element);
}
wrapper.appendChild(element);
return wrapper;
}
/**
* Returns offset for a given element
* @function
* @memberOf fabric.util
* @param {HTMLElement} element Element to get offset for
* @return {Object} Object with "left" and "top" properties
*/
function getElementOffset(element) {
// TODO (kangax): need to fix this method
var valueT = 0, valueL = 0;
do {
valueT += element.offsetTop || 0;
valueL += element.offsetLeft || 0;
element = element.offsetParent;
}
while (element);
return ({ left: valueL, top: valueT });
}
/**
* Returns position of a given element
* @function
* @memberOf fabric.util
* @param {HTMLElement} element Element to get offset for
* @return {Object} position of the given element.
*/
var getElementPosition;
if (fabric.document.defaultView && fabric.document.defaultView.getComputedStyle) {
getElementPosition = function (element) {
return fabric.document.defaultView.getComputedStyle(element, null).position;
};
}
else {
/** @ignore */
getElementPosition = function (element) {
var value = element.style.position;
if (!value && element.currentStyle) value = element.currentStyle.position;
return value;
};
}
(function () {
var style = fabric.document.documentElement.style;
var selectProp = 'userSelect' in style
? 'userSelect'
: 'MozUserSelect' in style
? 'MozUserSelect'
: 'WebkitUserSelect' in style
? 'WebkitUserSelect'
: 'KhtmlUserSelect' in style
? 'KhtmlUserSelect'
: '';
/**
* Makes element unselectable
* @memberOf fabric.util
* @param {HTMLElement} element Element to make unselectable
* @return {HTMLElement} Element that was passed in
*/
function makeElementUnselectable(element) {
if (typeof element.onselectstart !== 'undefined') {
element.onselectstart = fabric.util.falseFunction;
}
if (selectProp) {
element.style[selectProp] = 'none';
}
else if (typeof element.unselectable === 'string') {
element.unselectable = 'on';
}
return element;
}
/**
* Makes element selectable
* @memberOf fabric.util
* @param {HTMLElement} element Element to make selectable
* @return {HTMLElement} Element that was passed in
*/
function makeElementSelectable(element) {
if (typeof element.onselectstart !== 'undefined') {
element.onselectstart = null;
}
if (selectProp) {
element.style[selectProp] = '';
}
else if (typeof element.unselectable === 'string') {
element.unselectable = '';
}
return element;
}
fabric.util.makeElementUnselectable = makeElementUnselectable;
fabric.util.makeElementSelectable = makeElementSelectable;
})();
(function() {
/**
* Inserts a script element with a given url into a document; invokes callback, when that script is finished loading
* @memberOf fabric.util
* @param {String} url URL of a script to load
* @param {Function} callback Callback to execute when script is finished loading
*/
function getScript(url, callback) {
var headEl = fabric.document.getElementsByTagName("head")[0],
scriptEl = fabric.document.createElement('script'),
loading = true;
scriptEl.type = 'text/javascript';
scriptEl.setAttribute('runat', 'server');
/** @ignore */
scriptEl.onload = /** @ignore */ scriptEl.onreadystatechange = function(e) {
if (loading) {
if (typeof this.readyState === 'string' &&
this.readyState !== 'loaded' &&
this.readyState !== 'complete') return;
loading = false;
callback(e || fabric.window.event);
scriptEl = scriptEl.onload = scriptEl.onreadystatechange = null;
}
};
scriptEl.src = url;
headEl.appendChild(scriptEl);
// causes issue in Opera
// headEl.removeChild(scriptEl);
}
fabric.util.getScript = getScript;
})();
fabric.util.getById = getById;
fabric.util.toArray = toArray;
fabric.util.makeElement = makeElement;
fabric.util.addClass = addClass;
fabric.util.wrapElement = wrapElement;
fabric.util.getElementOffset = getElementOffset;
fabric.util.getElementPosition = getElementPosition;
})();
|
JavaScript
| 0.000003 |
@@ -5971,98 +5971,8 @@
e;%0A%0A
- scriptEl.type = 'text/javascript';%0A scriptEl.setAttribute('runat', 'server');%0A%0A
|
ec297cddbf0e1e0c05eaf8dd61b56b240f73fd43
|
debug Alexa
|
lib/api/alexa/index.js
|
lib/api/alexa/index.js
|
'use strict';
var moment = require('moment');
var _ = require('lodash');
function configure (app, wares, ctx, env) {
var entries = ctx.entries;
var express = require('express')
, api = express.Router( )
;
// invoke common middleware
api.use(wares.sendJSONStatus);
// text body types get handled as raw buffer stream
api.use(wares.bodyParser.raw());
// json body types get handled as parsed json
api.use(wares.bodyParser.json());
ctx.plugins.eachEnabledPlugin(function each(plugin){
if (plugin.alexa) {
if (plugin.alexa.intentHandlers) {
console.log(plugin.name + ' is Alexa enabled');
_.each(plugin.alexa.intentHandlers, function (route) {
if (route) {
ctx.alexa.configureIntentHandler(route.intent, route.intentHandler, route.routableSlot, route.slots);
}
});
}
if (plugin.alexa.rollupHandlers) {
console.log(plugin.name + ' is Alexa rollup enabled');
_.each(plugin.alexa.rollupHandlers, function (route) {
console.log('Route');
console.log(route);
if (route) {
ctx.alexa.addToRollup(route.rollupGroup, route.rollupHandler, route.rollupName);
}
});
}
} else {
console.log('Plugin ' + plugin.name + ' is not Alexa enabled');
}
});
api.post('/alexa', ctx.authorization.isPermitted('api:*:read'), function (req, res, next) {
console.log('Incoming request from Alexa');
switch (req.body.request.type) {
case 'IntentRequest':
onIntent(req.body.request.intent, function (title, response) {
res.json(ctx.alexa.buildSpeechletResponse(title, response, '', 'true'));
next( );
});
break;
case 'LaunchRequest':
onLaunch(req.body.request.intent, function (title, response) {
res.json(ctx.alexa.buildSpeechletResponse(title, response, '', 'true'));
next( );
});
break;
case 'SessionEndedRequest':
onSessionEnded(req.body.request.intent, function (alexaResponse) {
res.json(alexaResponse);
next( );
});
break;
}
});
ctx.alexa.addToRollup('Status', function bgRollupHandler(slots, sbx, callback) {
entries.list({count: 1}, function(err, records) {
var direction;
if (records[0].direction === 'FortyFiveDown') {
direction = ' and slightly dropping';
} else if (records[0].direction === 'FortyFiveUp') {
direction = ' and slightly rising';
} else if (records[0].direction === 'Flat') {
direction = ' and holding';
} else if (records[0].direction === 'SingleUp') {
direction = ' and rising';
} else if (records[0].direction === 'SingleDown') {
direction = ' and dropping';
} else if (records[0].direction === 'DoubleDown') {
direction = ' and rapidly dropping';
} else if (records[0].direction === 'DoubleUp') {
direction = ' and rapidly rising';
} else {
direction = records[0].direction;
}
console.log(records[0].data.lastSG.sg);
var status = sbx.scaleMgdl(records[0].sgv) + direction + ' as of ' + moment(records[0].date).from(moment(sbx.time)) + '.';
callback(null, {results: status, priority: -1});
});
//console.log('BG results called');
//callback(null, 'BG results');
}, 'BG Status');
ctx.alexa.configureIntentHandler('MetricNow', function (callback, slots, sbx) {
entries.list({count: 1}, function(err, records) {
var direction = '';
if (records[0].direction === 'FortyFiveDown') {
direction = ' and slightly dropping';
} else if (records[0].direction === 'FortyFiveUp') {
direction = ' and slightly rising';
} else if (records[0].direction === 'Flat') {
direction = ' and holding';
} else if (records[0].direction === 'SingleUp') {
direction = ' and rising';
} else if (records[0].direction === 'SingleDown') {
direction = ' and dropping';
} else if (records[0].direction === 'DoubleDown') {
direction = ' and rapidly dropping';
} else if (records[0].direction === 'DoubleUp') {
direction = ' and rapidly rising';
}
var status = sbx.scaleMgdl(records[0].sgv) + direction + ' as of ' + moment(records[0].date).from(moment(sbx.time));
console.log('configureIntentHandler: status: ' + status);
callback('Current blood glucose', status);
});
}, 'metric', ['bg', 'blood glucose', 'number']);
ctx.alexa.configureIntentHandler('NSStatus', function(callback, slots, sbx) {
ctx.alexa.getRollup('Status', sbx, slots, function (status) {
callback('Full status', status);
});
});
function onLaunch() {
console.log('Session launched');
}
function onIntent(intent, next) {
console.log('Received intent request');
console.log(JSON.stringify(intent));
handleIntent(intent.name, intent.slots, next);
}
function onSessionEnded() {
console.log('Session ended');
}
function handleIntent(intentName, slots, next) {
var handler = ctx.alexa.getIntentHandler(intentName, slots);
if (handler){
var sbx = initializeSandbox();
handler(next, slots, sbx);
} else {
next('Unknown Intent', 'I\'m sorry I don\'t know what you\'re asking for');
}
}
function initializeSandbox() {
var sbx = require('../../sandbox')();
sbx.serverInit(env, ctx);
ctx.plugins.setProperties(sbx);
return sbx;
}
return api;
}
module.exports = configure;
|
JavaScript
| 0.000003 |
@@ -3565,32 +3565,62 @@
;%0A %7D%0A
+ console.log(sbx);%0A
cons
|
4b6dd3c26619683187f428519dae5d5caa52cb0a
|
handle not existing rest folders
|
NiWAappWorker.js
|
NiWAappWorker.js
|
var SC=µ.shortcut({
File:"File"
});
var LOG=require("./logger");
var logger;
var rest={};
worker.init=function(param)
{
logger=LOG.setCoreLogger(LOG("apps/"+param.name));
return new SC.File("rest").listFiles().then(files=>
files.filter(s=>s.slice(-3)===".js").map(s=>s.slice(0,-3))//cut ".js"
.forEach(script=>
rest[script]=require(new SC.File("./rest").changePath(script).getAbsolutePath())
)
);
}
worker.restCall=function(param)
{
if(param.path.length==0)
{
return JSON.stringify(rest,function(key,value)
{
if(value instanceof Function) return value.toString().match(/^[^\(]+[^,]*,?([^\)]*)/)[1].split(",").map(s=>s.trim()).filter(s=>s!="");
return value;
});
}
else
{
var method=rest;
var i=0;
while(method&&typeof method!="function")
{
method=method[param.path[i++]];
}
if(!method)
{
return Promise.reject({data:"no such method: "+param.path.slice(0,i)});
}
else
{
param.path=param.path.slice(i);
param.headers=null;
param.status=null;
return Promise.resolve(method.apply(null,[param,param.path]))
.then(data=>({data:data,headers:param.headers,status:param.status}),
error=>Promise.reject({data:error,headers:param.headers,status:param.status}));
}
}
};
|
JavaScript
| 0.000001 |
@@ -199,16 +199,60 @@
%22rest%22).
+exists()%0A%09.then(function()%0A%09%7B%0A%09%09return this.
listFile
@@ -268,16 +268,17 @@
files=%3E%0A
+%09
%09%09files.
@@ -343,16 +343,17 @@
%22.js%22%0A%09%09
+%09
.forEach
@@ -362,16 +362,17 @@
cript=%3E%0A
+%09
%09%09%09rest%5B
@@ -449,19 +449,218 @@
th())%0A%09%09
+%09
)%0A%09
+%09);%0A%09%7D,%0A%09function()%0A%09%7B%0A%09%09return %22'rest' folder does not exist%22;%0A%09%7D)%0A%09.catch(e=%3E%0A%09%7B%0A%09%09setTimeout(function()%7Bthrow e;%7D,1) //for native error message%0A%09%09return Promise.reject(LOG.errorSerializer(e));%0A%09%7D
);%0A%7D%0Awor
|
0a83ef05290b10f684ac1b6de913b959adb6b059
|
use default import as it is default exported
|
lib/grammars/javascript.js
|
lib/grammars/javascript.js
|
'use babel';
import path from 'path';
import GrammarUtils, { command, OperatingSystem } from '../grammar-utils';
const babel = path.join(__dirname, '../..', 'node_modules', '.bin', OperatingSystem.isWindows() ? 'babel.cmd' : 'babel');
const babelConfig = path.join(__dirname, 'babel.config.js');
const args = ({ filepath }) => {
const cmd = `'${babel}' --filename '${filepath}' --config-file ${babelConfig} < '${filepath}'| node`;
return GrammarUtils.formatArgs(cmd);
};
exports.Dart = {
'Selection Based': {
command: 'dart',
args: (context) => {
const code = context.getCode();
const tmpFile = GrammarUtils.createTempFileWithCode(code, '.dart');
return [tmpFile];
},
},
'File Based': {
command: 'dart',
args: ({ filepath }) => [filepath],
},
};
exports.JavaScript = {
'Selection Based': {
command,
args: (context) => {
const code = context.getCode();
const filepath = GrammarUtils.createTempFileWithCode(code, '.js');
return args({ filepath });
},
},
'File Based': { command, args },
};
exports['Babel ES6 JavaScript'] = exports.JavaScript;
exports['JavaScript with JSX'] = exports.JavaScript;
exports['JavaScript for Automation (JXA)'] = {
'Selection Based': {
command: 'osascript',
args: context => ['-l', 'JavaScript', '-e', context.getCode()],
},
'File Based': {
command: 'osascript',
args: ({ filepath }) => ['-l', 'JavaScript', filepath],
},
};
exports.TypeScript = {
'Selection Based': {
command: 'ts-node',
args: context => ['-e', context.getCode()],
},
'File Based': {
command: 'ts-node',
args: ({ filepath }) => [filepath],
},
};
|
JavaScript
| 0.000002 |
@@ -55,38 +55,8 @@
tils
-, %7B command, OperatingSystem %7D
fro
@@ -146,16 +146,29 @@
'.bin',
+GrammarUtils.
Operatin
@@ -821,24 +821,46 @@
sed': %7B%0A
+command: GrammarUtils.
command,%0A
@@ -1055,16 +1055,38 @@
sed': %7B
+command: GrammarUtils.
command,
|
c989609ae35743be72c46b2f55e44f55028356d2
|
Remove unused response parameter
|
lib/haibu/drone/service.js
|
lib/haibu/drone/service.js
|
/*
* service.js: RESTful JSON-based web service for the drone module.
*
* (C) 2010, Nodejitsu Inc.
*
*/
var haibu = require('../../haibu');
//
// ### function createRouter (dron, logger)
// #### @drone {Drone} Instance of the Drone resource to use in this router.
//
// Creates the Journey router which represents the `haibu` Drone webservice.
//
exports.createRouter = function (drone) {
//
// TODO (indexzero): Setup token-based auth for Drone API servers
//
haibu.router.strict = false;
//
// ### Default Root
// `GET /` responds with default JSON message
//
haibu.router.get('/', function () {
this.res.json(400, { message: 'No drones specified' });
});
//
// ### Version Binding
// `GET /version` returns the version string for this webservice
//
// TODO (indexzero): Consume `haibu.version` instead of journey.
//
haibu.router.get(/\/version/, function (response) {
this.res.json(200, { version: 'haibu ' + haibu.version });
});
haibu.router.post(/\/deploy\/([\w\-\.]+)\/([\w\-\.]+)/, { stream: true }, function (userId, appId) {
var res = this.res;
drone.deploy(userId, appId, this.req, function (err, result) {
if (err) {
haibu.emit(['error', 'service'], 'error', err);
return res.json(500, { error: err });
}
res.json(200, { drone: result });
})
});
//
// ### Drones Resource
// Routes for RESTful access to the Drone resource.
//
haibu.router.path('/drones', function () {
//
// ### List Apps
// `GET /drones` returns list of all drones managed by the
// Drone associated with this router.
//
this.get(function () {
var res = this.res,
data = { drones: drone.list() };
res.json(200, data);
});
//
// ### List Drone Processes
// `GET /drones/running` returns with a list of formatted
// drone processes.
//
this.get(/\/running/, function () {
this.res.json(200, drone.running());
});
//
// ### Show App
// `GET /drones/:id` shows details of a drone managed by the
// Drone associated with this router.
//
this.get(/\/([\w\-\.]+)/, function (id) {
var data = drone.show(id);
if (typeof data === 'undefined') {
this.res.json(404, { message: 'No drone(s) found for application ' + id });
}
else {
this.res.json(200, data);
}
});
//
// ### Start Drone for App
// `POST /drone/:id/start` starts a new drone for app with :id on this server.
//
this.post(/\/([\w\-\.]+)\/start/, function (id) {
var res = this.res;
drone.start(this.req.body.start, function (err, result) {
if (err) {
haibu.emit(['error', 'service'], 'error', err);
return res.json(500, { error: err });
}
res.json(200, { drone: result });
});
});
//
// ### Stop Drone for App
// `POST /drone/:id/stop` stops all drones for app with :id on this server.
//
this.post(/\/([\w\-\.]+)\/stop/, function (id) {
var res = this.res;
drone.stop(this.req.body.stop.name, function (err, result) {
if (err || !result) {
err = err || new Error('Unknown error from drone.');
haibu.emit('error:service', 'error', err);
return res.json(500, { error: err });
}
res.json(200);
});
});
//
// ### Restart Drone for App
// `POST /drone/:id/restart` restarts all drones for app with :id on this server.
//
this.post(/\/([\w\-\.]+)\/restart/, function (id) {
var res = this.res;
drone.restart(this.req.body.restart.name, function (err, drones) {
if (err) {
haibu.emit(['error', 'service'], 'error', err);
return res.json(500, { error: err });
}
res.json(200, { drones: drones });
});
});
//
// ### Clean Drone for App
// `POST /drones/:id/clean` removes all of the dependencies and source files for
// the app with :id on this server.
//
this.post(/\/([\w\-\.]+)\/clean/, function (id) {
var res = this.res;
drone.clean(this.req.body, function (err, drones) {
if (err) {
haibu.emit('error:service', 'error', err);
return res.json(500, { error: err });
}
res.json(200, { clean: true });
});
});
//
// ### Update Drone for App
// `POST /drones/:id/update` cleans and starts
// the app with :id on this server.
//
this.post(/\/([\w\-\.]+)\/update/, function (id) {
var res = this.res;
drone.update(this.req.body, function (err, drones) {
if (err) {
haibu.emit('error:service', 'error', err);
return res.json(500, { error: err });
}
res.json(200, { update: true });
});
});
//
// ### Clean All Drones
// `POST /drones/cleanall` removes all of the dependencies and source files for
// all apps on this server.
//
this.post(/\/cleanall/, function (response) {
var res = this.res;
drone.cleanAll(function (err, drones) {
if (err) {
haibu.emit('error:service', 'error', err);
return res.json(500, { error: err });
}
res.json(200, { clean: true });
});
});
});
};
|
JavaScript
| 0.000001 |
@@ -792,80 +792,8 @@
//%0A
- // TODO (indexzero): Consume %60haibu.version%60 instead of journey.%0A //%0A
ha
@@ -826,32 +826,24 @@
, function (
-response
) %7B%0A this
|
5e8fb351544773f0095baea1afc0c3b084c5497f
|
Simplify some type syntax to make tsc happy
|
modules/add-to-device-calendar/add-to-calendar.js
|
modules/add-to-device-calendar/add-to-calendar.js
|
// @flow
import * as React from 'react'
import type {EventType} from '@frogpond/event-type'
import {addToCalendar} from './lib'
import delay from 'delay'
type Props = {
event: EventType,
compactMessages?: boolean,
render: ({
message: string,
disabled: boolean,
onPress: () => any,
}) => React.Node,
}
type State = {
message: string,
disabled: boolean,
}
const VERBOSE_MESSAGES = {
active: 'Adding event to calendar…',
success: 'Event has been added to your calendar',
error: 'Error. Try again?',
}
const COMPACT_MESSAGES: $Shape<typeof VERBOSE_MESSAGES> = {
active: 'Saving…',
success: 'Saved',
error: 'Error. Try again?',
}
export class AddToCalendar extends React.Component<Props, State> {
state = {
message: '',
disabled: false,
}
addEvent = async () => {
let MESSAGES = this.props.compactMessages
? COMPACT_MESSAGES
: VERBOSE_MESSAGES
let {event} = this.props
let start = Date.now()
this.setState(() => ({message: MESSAGES.active}))
// wait 0.5 seconds – if we let it go at normal speed, it feels broken.
let elapsed = Date.now() - start
if (elapsed < 500) {
await delay(500 - elapsed)
}
let result = await addToCalendar(event)
if (result) {
this.setState(() => ({message: MESSAGES.success, disabled: true}))
} else {
this.setState(() => ({message: MESSAGES.error, disabled: false}))
}
}
render() {
return this.props.render({
message: this.state.message,
disabled: this.state.disabled,
onPress: this.addEvent,
})
}
}
|
JavaScript
| 0.000002 |
@@ -221,17 +221,16 @@
ender: (
-%7B
%0A%09%09messa
@@ -285,17 +285,16 @@
%3E any,%0A%09
-%7D
) =%3E Rea
@@ -535,41 +535,8 @@
AGES
-: $Shape%3Ctypeof VERBOSE_MESSAGES%3E
= %7B
|
ef5c908a35a544d57c9e78eb629a6d7d0dcc8ca9
|
Change output path and add images and logos alias path
|
cfg/base.js
|
cfg/base.js
|
var path = require('path');
var port = 8000;
var srcPath = path.join(__dirname, '/../src');
var publicPath = '/assets/';
module.exports = {
port: port,
debug: true,
output: {
path: path.join(__dirname, '/../dist/assets'),
filename: 'app.js',
publicPath: publicPath
},
devServer: {
contentBase: './src/',
historyApiFallback: true,
hot: true,
port: port,
publicPath: publicPath,
noInfo: false
},
resolve: {
extensions: [
'',
'.js',
'.jsx'
],
alias: {
actions: srcPath + '/actions/',
components: srcPath + '/components/',
sources: srcPath + '/sources/',
stores: srcPath + '/stores/',
styles: srcPath + '/styles/',
calls: srcPath + '/calls/',
config: srcPath + '/config/' + process.env.REACT_WEBPACK_ENV
}
},
module: {
preLoaders: [{
test: /\.(js|jsx)$/,
include: srcPath,
loader: 'eslint-loader'
}],
loaders: [
{
test: /\.css$/,
loader: 'style-loader!css-loader!postcss-loader'
},
{
test: /\.sass/,
loader: 'style-loader!css-loader!postcss-loader!sass-loader?outputStyle=expanded&indentedSyntax'
},
{
test: /\.scss/,
loader: 'style-loader!css-loader!postcss-loader!sass-loader?outputStyle=expanded'
},
{
test: /\.(png|jpg|gif|woff|woff2)$/,
loader: 'url-loader?limit=8192'
}
]
},
postcss: function () {
return [
require('autoprefixer')({
browsers: ['last 2 versions', 'ie >= 8']
})
];
}
};
|
JavaScript
| 0 |
@@ -222,16 +222,21 @@
t/assets
+/app/
'),%0A
@@ -690,20 +690,54 @@
,%0A
-styl
+calls: srcPath + '/calls/',%0A imag
es: srcP
@@ -744,20 +744,20 @@
ath + '/
-styl
+imag
es/',%0A
@@ -752,36 +752,36 @@
images/',%0A
-call
+icon
s: srcPath + '/c
@@ -771,36 +771,36 @@
ns: srcPath + '/
-call
+icon
s/',%0A confi
|
dc3bd1a2aa96987c2edba58372f2362199a5ad43
|
Use the minified version of Bootstrap CSS (#900)
|
docs/lib/Home/index.js
|
docs/lib/Home/index.js
|
import React from 'react';
import { PrismCode } from 'react-prism';
import { Button, Container, Row, Col, Jumbotron } from 'reactstrap';
import { Link } from 'react-router';
import Example from '../examples/import-basic';
const importBasic = require('!!raw!../examples/import-basic');
export default () => {
return (
<div>
<Jumbotron tag="section" className="jumbotron-header text-center mb-3">
<Container>
<Row>
<Col>
<p className="lead">
<img src="/assets/logo.png" alt="" width="150px" />
</p>
<h1 className="jumbotron-heading display-4">reactstrap</h1>
<p className="lead">
Easy to use React Bootstrap 4 components
</p>
<p>
<Button outline color="danger" href="https://github.com/reactstrap/reactstrap">View on Github</Button>
<Button color="danger" tag={Link} to="/components/">View Components</Button>
</p>
</Col>
</Row>
</Container>
</Jumbotron>
<Container>
<Row className="justify-content-sm-center">
<Col sm={8}>
<h2>Installation</h2>
<hr />
<h3 className="mt-5">NPM</h3>
<p>Install reactstrap and peer dependencies via NPM</p>
<pre>
<PrismCode className="language-bash">npm install --save reactstrap@next react react-dom</PrismCode>
</pre>
<p>Import the components you need</p>
<div className="docs-example">
<Example />
</div>
<pre>
<PrismCode className="language-jsx">
{importBasic}
</PrismCode>
</pre>
<h3 className="mt-5">Getting Started with Create React App</h3>
<p>Follow the <a href="https://github.com/facebookincubator/create-react-app#getting-started" target="_blank">create-react-app instructions</a> up to the <code>Adding Bootstrap</code> section and instead follow the reactstrap version of adding bootstrap.</p>
<h4>tl;dr</h4>
<pre>
<PrismCode className="language-bash">
{`npm install -g create-react-app
create-react-app my-app
cd my-app/
npm start`}
</PrismCode>
</pre>
<p>
Then open <a href="http://localhost:3000/" target="_blank">http://localhost:3000/</a> to see your app. The initial structure of your app is setup. Next, let's add reactstrap and bootstrap.
</p>
<h4>Adding Bootstrap</h4>
<p>Install reactstrap and Bootstrap from NPM. Reactstrap does not include Bootstrap CSS so this needs to be installed as well:</p>
<pre>
<PrismCode className="language-bash">
{`npm install bootstrap --save
npm install --save reactstrap@next react react-dom`}
</PrismCode>
</pre>
<p>Import Bootstrap CSS in the <code>src/index.js</code> file:</p>
<pre>
<PrismCode className="language-bash">import 'bootstrap/dist/css/bootstrap.css';</PrismCode>
</pre>
<p>Import required reactstrap components within <code>src/App.js</code> file or your custom component files:</p>
<pre>
<PrismCode className="language-bash">
{`import { Button } from 'reactstrap';`}
</PrismCode>
</pre>
<p>Now you are ready to use the imported reactstrap components within your component hierarchy defined in the render method. Here is an example <a href="https://gist.github.com/eddywashere/e13033c0e655ab7cda995f8bc77ce40d" target="_blank"><code>App.js</code></a> redone using reactstrap.</p>
<h2 className="mt-5">CDN</h2>
<p>Reactstrap can be included directly in your application's bundle or excluded during compilation and linked directly to a CDN.</p>
<pre>
<PrismCode className="language-jsx">
https://cdnjs.cloudflare.com/ajax/libs/reactstrap/4.8.0/reactstrap.min.js
</PrismCode>
</pre>
<blockquote className="blockquote">
<p>
<strong>Note</strong>: When using the external CDN library, be sure to include the required dependencies as necessary <strong>prior</strong> to the Reactstrap library:
</p>
<ul>
<li><a href="//cdnjs.com/libraries/react" target="_blank">React</a></li>
<li><a href="//unpkg.com/react-transition-group/dist/react-transition-group.min.js" target="_blank">ReactTransitionGroup</a></li>
</ul>
</blockquote>
<p>Check out the demo <a href="http://output.jsbin.com/dimive/latest">here</a></p>
<h2 className="mt-5">About the Project</h2>
<hr />
<p>This library contains React Bootstrap 4 components that favor composition and control. The library does not depend on jQuery or Bootstrap javascript. However, <a href="https://popper.js.org/">https://popper.js.org/</a> via <a href="https://github.com/souporserious/react-popper">https://github.com/souporserious/react-popper</a> is relied upon for advanced positioning of content like Tooltips, Popovers, and auto-flipping Dropdowns.</p>
<p>There are a few core concepts to understand in order to make the most out of this library.</p>
<p>1) Your content is expected to be composed via props.children rather than using named props to pass in Components.</p>
<pre>
<PrismCode className="language-jsx">
{`// Content passed in via props
const Example = (props) => {
return (
<p>This is a tooltip <TooltipTrigger tooltip={TooltipContent}>example</TooltipTrigger>!</p>
);
}
// Content passed in as children (Preferred)
const PreferredExample = (props) => {
return (
<p>
This is a <a href="#" id="TooltipExample">tooltip</a> example.
<Tooltip target="TooltipExample">
<TooltipContent/>
</Tooltip>
</p>
);
}`}
</PrismCode>
</pre>
<p>
2) Attributes in this library are used to pass in state, conveniently apply modifier classes, enable advanced functionality (like popperjs), or automatically include non-content based elements.
</p>
<p>Examples:</p>
<ul>
<li><code>isOpen</code> - current state for items like dropdown, popover, tooltip</li>
<li><code>toggle</code> - callback for toggling isOpen in the controlling component</li>
<li><code>color</code> - applies color classes, ex: <code>{'<Button color="danger"/>'}</code></li>
<li><code>size</code> for controlling size classes. ex: <code>{'<Button size="sm"/>'}</code></li>
<li><code>tag</code> - customize component output by passing in an element name or Component</li>
<li>boolean based props (attributes) when possible for alternative style classes or sr-only content</li>
</ul>
</Col>
</Row>
</Container>
</div>
);
};
|
JavaScript
| 0.000009 |
@@ -3154,16 +3154,20 @@
otstrap.
+min.
css';%3C/P
|
d68e9aeb60b3e071a1c61aa642123b1c88f226af
|
Remove the unnecessary depthTest parameter
|
browser/plugins/three_meshline_material.plugin.js
|
browser/plugins/three_meshline_material.plugin.js
|
(function() {
var ThreeMeshLineMaterialPlugin = E2.plugins.three_meshline_material = function(core) {
AbstractThreeMaterialPlugin.apply(this, arguments)
this.desc = 'THREE.js MeshLine Material'
this.input_slots = [
{ name: 'color', dt: core.datatypes.COLOR, def: new THREE.Color(0xffffff) },
{ name: 'sizeAttenuation', dt: core.datatypes.BOOL, def: true },
{ name: 'lineWidth', dt: core.datatypes.FLOAT, def: 0.01 },
{ name: 'near', dt: core.datatypes.FLOAT, def: 0.01 },
{ name: 'far', dt: core.datatypes.FLOAT, def: 1000 },
{ name: 'depthTest', dt: core.datatypes.BOOL, def: true },
{ name: 'wireframe', dt: core.datatypes.BOOL, def: false }
].concat(this.input_slots)
this.output_slots = [{
name: 'material',
dt: core.datatypes.MATERIAL
}]
// Needed for the shader sizeAttenuation
this.resolution = new THREE.Vector2(1, 1)
// Get the parameters from the input_slots
var params = {}
this.input_slots.map(function(slot) {
params[slot.name] = slot.def
})
params.resolution = this.resolution
this.material = new THREE.MeshLineMaterial(params)
}
ThreeMeshLineMaterialPlugin.prototype = Object.create(AbstractThreeMaterialPlugin.prototype)
ThreeMeshLineMaterialPlugin.prototype.state_changed = function(ui) {
// if ui is null, first time called, bind the resize
if (!ui) {
E2.core.on('resize', this.resize.bind(this))
}
}
ThreeMeshLineMaterialPlugin.prototype.update_input = function(slot, data) {
Plugin.prototype.update_input.apply(this, arguments)
if ( slot.name === 'transparent'
|| slot.name === 'wireframe'
|| slot.name === 'side'
|| slot.name === 'blending' ) {
// Use the abstract material update method
AbstractThreeMaterialPlugin.prototype.update_input.apply(this, arguments)
} else {
// Just update the shader directly
this.material.uniforms[slot.name].value = data
}
}
ThreeMeshLineMaterialPlugin.prototype.resize = function() {
// Need to recalculate the resolution
var canvasArea = E2.app.calculateCanvasArea()
this.resolution.set(canvasArea.width, canvasArea.height)
this.material.uniforms.resolution.value = this.resolution
}
})()
|
JavaScript
| 0.000018 |
@@ -546,71 +546,8 @@
%7D,%0A
-%09%09%7B name: 'depthTest',%09%09dt: core.datatypes.BOOL, def: true %7D,%0A
%09%09%7B
|
e0434005308fd74f344f61ed168b4581e152508e
|
remove null state
|
skm-spa/clocks-react/main.js
|
skm-spa/clocks-react/main.js
|
let e = React.createElement;
class Clocks extends React.Component {
constructor(props) {
super(props);
this.state = {
clocks: [
{ name: 'Tel Aviv', offset: 0, start: Date.now() },
{ name: 'London', offset: -2, start: Date.now() },
{ name: 'New York', offset: -7, start: Date.now() }
]
}
}
reset() {
this.setState({
clocks: [
{ name: 'Tel Aviv', offset: 0, start: Date.now() },
{ name: 'London', offset: -2, start: Date.now() },
{ name: 'New York', offset: -7, start: Date.now() }
]
})
}
render() {
return e('div', {}, [
e('button', { onClick: () => this.reset() }, 'Reset'),
e('ul', {}, this.state.clocks.map(clock => {
return e('li', {}, e(Clock, clock))
}))
]);
}
}
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {
time: null,
lastStart: props.start
};
}
tick() {
this.setState({ time: new Date(this.state.time.getTime() + 1000) });
}
static getOffsetTime(start, offset) {
let nextTime = new Date(start);
nextTime.setHours(nextTime.getHours() + offset);
return nextTime;
}
static getDerivedStateFromProps(props, state) {
if (state.time === null || state.lastStart !== props.start) {
return {
time: Clock.getOffsetTime(props.start, props.offset),
lastStart: props.start
};
}
return state;
}
start() {
this.tick();
this.intervalId = setInterval(() => {
this.tick();
}, 1000);
}
pause() {
clearInterval(this.intervalId);
}
componentDidMount() {
this.start();
}
render() {
let time = (new Date(this.state.time)).toLocaleString();
return e('div', {}, [
e('span', {}, `Name: ${this.props.name}`),
e('span', {}, `Time: ${time}`),
e('button', { onClick: () => this.pause() }, 'Pause'),
e('button', { onClick: () => this.start() }, 'Start'),
]);
}
}
ReactDOM.render(
e(Clocks),
document.querySelector('main')
);
|
JavaScript
| 0.000472 |
@@ -914,20 +914,62 @@
time:
-null
+Clock.getOffsetTime(props.start, props.offset)
,%0A
@@ -1306,31 +1306,8 @@
if (
-state.time === null %7C%7C
stat
|
6a1315d6220ece5154b354115f9636b2a35cc1ef
|
Auth::Controller:Set APIError
|
server/controllers/auth.js
|
server/controllers/auth.js
|
import jwt from 'jsonwebtoken'
import config from '../../config/env'
import logger from '../../config/winston'
import User from '../models/user'
import httpStatus from 'http-status'
/**
* Returns jwt token if valid username and password is provided
* @param req - Request
* @param res - Response
* @returns {*}
*/
function login(req, res) {
User.findOne({
username: req.body.username,
}, (err, user) => {
if (err) throw err
if (!user) {
logger.log('debug', 'API::Auth::JWT:User Not Found')
return res.status(401).json({
status: 401,
userMessage: httpStatus[401],
developerMessage: '',
errorCode: 0,
moreInfo: '',
})
} else {
// Check if password matches
user.comparePassword(req.body.password, (err, isMatch) => {
if (isMatch && !err) {
const payload = {
name: user.name,
surname: user.surname,
username: user.username,
email: user.email,
}
// Create token if the password matched and no error was thrown
const token = jwt.sign(payload, config.jwt.secret, { expiresIn: config.jwt.expire, })
return res.status(200).json({
token: token,
token_type: 'Bearer',
expires_in: config.jwt.expire,
})
} else {
logger.log('debug', 'API::Auth::JWT:Password did not match')
return res.status(401).json({
status: 401,
userMessage: httpStatus[401],
developerMessage: '',
errorCode: 0,
moreInfo: '',
})
}
})
}
})
}
export default {
login,
}
|
JavaScript
| 0.999377 |
@@ -4,16 +4,16 @@
ort
-jwt
+APIError
@@ -33,20 +33,27 @@
om '
-jsonwebtoken
+../helpers/APIError
'%0Aim
@@ -104,16 +104,115 @@
ig/env'%0A
+import httpStatus from 'http-status'%0Aimport jwt from 'jsonwebtoken'%0A
import l
@@ -317,57 +317,8 @@
er'%0A
-import httpStatus from 'http-status'%0A
%0A%0A/*
@@ -432,16 +432,49 @@
esponse%0A
+ * @param next - Next Middleware%0A
* @retu
@@ -508,16 +508,22 @@
req, res
+, next
) %7B%0A Us
@@ -700,80 +700,33 @@
-return res.status(401).json(%7B%0A status: 401,%0A userMessage:
+const err = new APIError(
http
@@ -741,90 +741,28 @@
01%5D,
+ 401)
%0A
- developerMessage: '',%0A errorCode: 0,%0A moreInfo: '',%0A %7D
+next(err
)%0A
@@ -1506,88 +1506,33 @@
-return res.status(401).json(%7B%0A status: 401,%0A userMessage:
+const err = new APIError(
http
@@ -1543,16 +1543,21 @@
us%5B401%5D,
+ 401)
%0A
@@ -1563,95 +1563,16 @@
- developerMessage: '',%0A errorCode: 0,%0A moreInfo: '',%0A %7D
+next(err
)%0A
|
4a832ea8776aca8bc35b8a7f047cee0e2debdcaf
|
throw error instead of console
|
server/controllers/auth.js
|
server/controllers/auth.js
|
'use strict';
const version = require('../package.json').version;
const router = require('express').Router;
const app = router();
const ntb = require('turbasen');
const userAgent = `Hytteadmin/${version}`;
process.env.NTB_USER_AGENT = userAgent;
process.env.DNT_CONNECT_USER_AGENT = userAgent;
process.env.DNT_API_USER_AGENT = userAgent;
const Turbasen = require('turbasen-auth');
const DntConnect = require('dnt-connect');
const DntApi = require('dnt-api');
const connect = new DntConnect(
process.env.DNT_CONNECT_CLIENT,
process.env.DNT_CONNECT_KEY
);
const dntApi = new DntApi(
process.env.DNT_API_USER_AGENT,
process.env.DNT_API_KEY
);
app.get('/', (req, res) => {
if (req.session && req.session.user) {
res.json(req.session.user);
} else {
res.status(401);
res.json({ authenticated: false });
}
});
app.get('/login/dnt', connect.middleware('signon'));
app.get('/login/dnt', (req, res, next) => {
if (!req.dntConnect) {
const err = new Error('DNT Connect: unknown error');
err.status = 500;
return next(err);
}
if (req.dntConnect.err || !req.dntConnect.data.er_autentisert) {
// @TODO redierect back to login page with error message
return res.redirect('/login');
}
req.session.user = {
id: `sherpa3:${req.dntConnect.data.sherpa_id}`,
brukertype: 'DNT',
navn: `${req.dntConnect.data.fornavn} ${req.dntConnect.data.etternavn}`,
epost: req.dntConnect.data.epost,
er_admin: false,
grupper: [],
};
return next();
});
app.get('/login/dnt', (req, res) => {
const user = {
bruker_sherpa_id: req.dntConnect.data.sherpa_id,
};
// Find groups the user belongs to in Sherpa
dntApi.getAssociationsFor(user, (err, statusCode, associations) => {
let isAdmin = false;
const groups = [];
if (err) { throw err; }
if (statusCode === 200) {
for (let i = 0; i < associations.length; i++) {
if (associations[i].object_id) {
groups.push(associations[i]);
}
if (!isAdmin && associations[i].navn === 'Den Norske Turistforening') {
isAdmin = true;
}
}
req.session.user.er_admin = isAdmin;
} else {
throw new Error(`Request to DNT API failed: ${statusCode}`);
}
// Find groups that the user belongs to in Turbasen
ntb.grupper({ 'privat.brukere.id': user.bruker_sherpa_id }, (ntbErr, ntbRes, body) => {
if (ntbErr) {
console.error(`Request to Turbasen API failed: ${err.message}`); // eslint-disable-line no-console, max-len
} else if (body && body.documents && body.documents.length) {
for (let i = 0; i < body.documents.length; i++) {
groups.push(body.documents[i]);
}
}
req.session.user.grupper = groups;
res.redirect('/');
});
});
});
app.post('/login/turbasen', Turbasen.middleware);
app.post('/login/turbasen', (req, res, next) => {
if (req.turbasenAuth) {
req.session.user = req.turbasenAuth;
req.session.user.brukertype = 'Gruppe';
res.status(200);
res.json(req.session.user);
} else {
req.session.destroy(err => {
if (!err) {
const error = new Error('Invalid email or password');
error.status = 401;
return next(error);
}
return next(err);
});
}
});
app.get('/logout', (req, res) => {
req.session.destroy(err => {
if (err) { throw err; }
if (req.query.next) {
res.redirect(req.query.next);
} else {
res.redirect('/');
}
});
});
app.post('/logout', (req, res) => {
req.session.destroy(err => {
if (err) { throw err; }
res.status(204).end();
});
});
module.exports = app;
|
JavaScript
| 0.000005 |
@@ -2425,17 +2425,19 @@
-console.e
+throw new E
rror
@@ -2472,17 +2472,20 @@
iled: $%7B
-e
+ntbE
rr.messa
@@ -2494,51 +2494,8 @@
%7D%60);
- // eslint-disable-line no-console, max-len
%0A
|
02071c91d210984c8fde9420280a672121803623
|
fix clean script
|
packages/coinstac-server-core/scripts/clean-db.js
|
packages/coinstac-server-core/scripts/clean-db.js
|
/* eslint-disable no-console */
'use strict';
const async = require('async');
const CoinstacServer = require('../src/coinstac-server.js');
const dbmap = require('/coins/config/dbmap.json');
const rimraf = require('rimraf');
const superagent = require('superagent');
const urlBase = dbmap.coinstac ?
`http://${dbmap.coinstac.user}:${dbmap.coinstac.password}@localhost:5984` :
'http://localhost:5984';
async.parallel([
cb1 => {
console.log('Removing database dir…');
rimraf(CoinstacServer.DB_PATH, error => {
if (error) {
cb1(error);
} else {
console.log('Database dir removed');
cb1(null);
}
});
},
cb2 => {
async.waterfall([
cb2a => {
superagent
.get(`${urlBase}/_all_dbs`)
.set('Accept', 'application/json')
.end(cb2a);
},
(response, cb2b) => {
async.map(
response.body.filter(name => name.charAt(0) !== '_'),
(dbName, cb2b1) => {
superagent
.delete(`${urlBase}/${dbName}`)
.set('Accept', 'application/json')
.end((error, deleteResponse) => {
const body = deleteResponse.body;
if (error) {
cb2b1(error);
} else if (!body.ok) {
cb2b1(body);
} else {
console.log(`Removed database: ${dbName}`);
cb2b1(null);
}
});
},
cb2b
);
},
], cb2);
},
], error => {
if (error) {
console.error(error);
}
});
/* eslint-enable no-console */
|
JavaScript
| 0.000019 |
@@ -264,24 +264,73 @@
');%0A
-%0Aconst urlBase =
+const url = require('url');%0A%0Aconst urlBase = url.format(%7B%0A auth:
dbm
@@ -346,19 +346,9 @@
ac ?
-%0A %60http://
+%60
$%7Bdb
@@ -396,53 +396,77 @@
ord%7D
-@localhost:5984%60 :%0A 'http://localhost:5984';
+%60 : '',%0A hostname: 'localhost',%0A port: 5984,%0A protocol: 'http',%0A%7D)
%0A%0Aas
|
3c511406cdfbc407eb69fa54aa2d9765e0e7e796
|
Correct option processing.
|
source/scripts/wizard_tags.js
|
source/scripts/wizard_tags.js
|
var WizardTags = (function() {
var MakeDefaultTagsGenerator = function(tags) {
return function(query) {
return tags.filter(
function(tag) {
return tag.substr(0, query.length) == query;
}
);
};
};
var GetTagsGenerator = function(options) {
var tags_generator = function() {
return [];
};
if (options.tags instanceof Function) {
tags_generator = options.tags;
} else if (options.tags instanceof Array) {
tags_generator = MakeDefaultTagsGenerator(options.tags);
}
return tags_generator;
};
var ProcessOptions = function(options) {
var processed_options = options || {};
processed_options.tags = GetTagsGenerator(processed_options);
processed_options.separators = processed_options.separators || ' ';
processed_options.onChange =
processed_options.onChange
|| function() {};
return processed_options;
};
return function(root_element_query, options) {
options = ProcessOptions(options);
console.log(options);
};
})();
|
JavaScript
| 0.000001 |
@@ -24,16 +24,55 @@
ion() %7B%0A
+%09var OptionsProcessor = (function() %7B%0A%09
%09var Mak
@@ -112,16 +112,17 @@
tags) %7B%0A
+%09
%09%09return
@@ -139,24 +139,25 @@
query) %7B%0A%09%09%09
+%09
return tags.
@@ -168,16 +168,17 @@
er(%0A%09%09%09%09
+%09
function
@@ -181,24 +181,25 @@
tion(tag) %7B%0A
+%09
%09%09%09%09%09return
@@ -236,16 +236,17 @@
query;%0A
+%09
%09%09%09%09%7D%0A%09%09
@@ -250,17 +250,24 @@
%0A%09%09%09
-)
+%09);%0A%09%09%09%7D
;%0A%09%09%7D;%0A%09
%7D;%0A%09
@@ -262,19 +262,16 @@
;%0A%09%09%7D;%0A%09
-%7D;%0A
%09var Get
@@ -304,24 +304,25 @@
ptions) %7B%0A%09%09
+%09
var tags_gen
@@ -342,24 +342,25 @@
tion() %7B%0A%09%09%09
+%09
return %5B%5D;%0A%09
@@ -360,19 +360,21 @@
n %5B%5D;%0A%09%09
+%09
%7D;%0A
+%09
%09%09if (op
@@ -406,24 +406,25 @@
ction) %7B%0A%09%09%09
+%09
tags_generat
@@ -442,16 +442,17 @@
s.tags;%0A
+%09
%09%09%7D else
@@ -492,16 +492,17 @@
y) %7B%0A%09%09%09
+%09
tags_gen
@@ -554,15 +554,17 @@
s);%0A
+%09
%09%09%7D%0A%0A%09%09
+%09
retu
@@ -586,33 +586,36 @@
or;%0A
+%09
%09%7D;%0A
-%09var ProcessOptions =
+%0A%09%09return %7B%0A%09%09%09process:
fun
@@ -627,24 +627,26 @@
(options) %7B%0A
+%09%09
%09%09var proces
@@ -672,24 +672,26 @@
ns %7C%7C %7B%7D;%0A%09%09
+%09
+%09
processed_op
@@ -740,16 +740,18 @@
tions);%0A
+%09%09
%09%09proces
@@ -774,17 +774,22 @@
rators =
-
+%0A%09%09%09%09%09
processe
@@ -812,17 +812,22 @@
tors
-
+%0A%09%09%09%09%09
%7C%7C ' ';%0A
%09%09pr
@@ -822,16 +822,18 @@
%7C%7C ' ';%0A
+%09%09
%09%09proces
@@ -854,24 +854,26 @@
Change =%0A%09%09%09
+%09%09
processed_op
@@ -887,16 +887,18 @@
nChange%0A
+%09%09
%09%09%09%7C%7C fu
@@ -907,24 +907,26 @@
tion() %7B%7D;%0A%0A
+%09%09
%09%09return pro
@@ -942,17 +942,30 @@
tions;%0A%09
-%7D
+%09%09%7D%0A%09%09%7D;%0A%09%7D)()
;%0A%0A%09retu
@@ -1023,21 +1023,31 @@
s =
-ProcessOption
+OptionsProcessor.proces
s(op
|
57d5869a5b5efe1e980cecad243a4402d6f97a41
|
Add check for config key matching style rule
|
lib/layerStylePresenter.js
|
lib/layerStylePresenter.js
|
'use strict';
var assert = require('assert')
var merge = require('object-merge')
var each = require('foreach')
/**
* Looks up config and gets style rules object for a given property
* @param {string|number|boolean} propertyValue
* @param {object} configProperties
* @return {object}
*/
function styleRulesForPropertyValue(propertyValue, configProperties) {
assert.ok(propertyValue, '`propertyValue` must not be undefined')
assert.equal(typeof (configProperties), 'object', '`configProperties` must be an object')
if (configProperties[propertyValue]) {
return configProperties[propertyValue]
}
}
/**
* Merges base styles object with an additional styles object, properties in
* both with be overwritten by additionalStyles
* @param {object} baseStyles
* @param {object} additionalStyles
* @return {object}
*/
function mergeStyles(baseStyles, additionalStyles) {
assert.equal(typeof (baseStyles), 'object', '`baseStyles` must be an object')
assert.equal(typeof (additionalStyles), 'object', '`additionalStyles` must be an object')
return merge(baseStyles, additionalStyles)
}
/**
* Returns an styles object by looking up config for style definitions matching
* the properties in the given properties object.
* @param {object} properties
* @param {object} config
* @return {object}
*/
function buildStylesForProperties(properties, config) {
assert.equal(typeof (properties), 'object', '`properties` must be an object')
assert.equal(typeof (config), 'object', '`config` must be an object')
var styles = {}
each(properties, (value, key) => {
styles = merge(styles, styleRulesForPropertyValue(value, config[key] || {}))
})
return styles
}
/**
* LayerStylePresenter class
* Takes a config object and provides a present function to be used for each
* geojson feature to generate map feature styles
*/
class LayerStylePresenter {
/**
* Sets config input
*/
constructor(config) {
assert.equal(typeof (config), 'object', '`config` must be an object')
assert.equal(typeof (config.general), 'object', '`config.general` must be an object')
this.config = config
}
/**
* Takes an object with various properties and returns an object containing
* map style rules
* @param {object} properties
* @return {object}
*/
present(properties) {
assert.equal(typeof (properties), 'object', '`properties` should be an object')
if(!this.config.properties) return this.config.general
var baseStyles = this.config.general
var propertyStyles = buildStylesForProperties(properties, this.config.properties)
return mergeStyles(baseStyles, propertyStyles)
}
}
module.exports = (config) => new LayerStylePresenter(config)
|
JavaScript
| 0 |
@@ -529,16 +529,18 @@
%0A%0A if (
+!!
configPr
@@ -1591,16 +1591,106 @@
y) =%3E %7B%0A
+ // If the config style matches on the current property key%0A if (!!config%5Bkey%5D) %7B%0A
styl
@@ -1708,16 +1708,17 @@
styles,
+(
styleRul
@@ -1754,16 +1754,17 @@
fig%5Bkey%5D
+)
%7C%7C %7B%7D))
@@ -1764,16 +1764,22 @@
%7C%7C %7B%7D))%0A
+ %7D%0A
%7D)%0A r
|
e1fda050ea463b9f83341578d78e511f3852f84f
|
Fix issues on password reset
|
server/controllers/auth.js
|
server/controllers/auth.js
|
require('dotenv').config();
const User = require('../database/models').User;
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt-nodejs');
const _ = require('lodash');
const Validator = require('validatorjs');
const { handleError, handleSuccess, sendMail } = require('../helpers/helpers');
module.exports = {
signup(req, res) {
const obj = req.body;
const validator = new Validator(obj, User.signupRules());
if (validator.passes()) {
if (obj.confirm_password !== obj.password) {
return handleError('password not matched', res);
}
User.findOne({
where: {
$or: [{ email: obj.email }, { username: obj.username }]
}
})
.then((existingUser) => {
if (existingUser) {
let message = '';
if (existingUser.email === obj.email) message = 'A user with this email already exists';
if (existingUser.username === obj.username) message = 'This Username has been used';
return Promise.reject(message);
}
// if user does not exist and he/she registering for the first time
if (!req.body.mobile) {
obj.mobile = '';
}
obj.username = obj.username.toLowerCase();
obj.fullname = obj.fullname.toLowerCase();
obj.email = obj.email.toLowerCase();
return User.create(obj, { fields: ['email', 'password', 'username', 'mobile', 'fullname'] });
})
.then((savedUser) => {
const data = _.pick(savedUser, ['id', 'username', 'email', 'mobile', 'fullname']);
const token = jwt.sign(data, process.env.JWT_SECRET);
return handleSuccess(201, token, res);
})
.catch(err => handleError(err, res));
} else if (validator.fails()) {
return handleError({ validateError: validator.errors.all() }, res);
} else {
return handleError('There are Problems in your input', res);
}
},
signin(req, res) {
const body = _.pick(req.body, ['username', 'password']);
const validator = new Validator(body, User.loginRules());
if (validator.fails()) {
return handleError({ validateError: validator.errors.all() }, res);
}
User.findOne({
where: {
username: body.username.toLowerCase()
}
})
.then((user) => {
if (!user) {
return Promise.reject({ code: 404, message: 'User not found' });
}
if (!user.comparePassword(body.password)) {
return Promise.reject('Incorrect password');
}
// If all is well
const data = _.pick(user, ['id', 'username', 'email', 'fullname']);
// Give the user token and should expire in the next 24 hours
const token = jwt.sign(data, process.env.JWT_SECRET);
return handleSuccess(200, token, res);
})
.catch(err => handleError(err, res));
},
passwordRecovery(req, res) {
const body = _.pick(req.body, ['email']);
const rules = {
email: 'required|email'
};
const validator = new Validator(body, rules);
if (validator.fails()) {
return handleError({ validateError: validator.errors.all() }, res);
}
User.findOne({
where: {
email: body.email.toLowerCase()
}
})
.then((user) => {
if (!user) {
return Promise.reject({ code: 404, message: 'Sorry! this email doesn\'t match our records' });
}
// If all is well
const data = _.pick(user, ['id', 'username', 'email']);
// Create token and should expire in the next 24 hours
const token = jwt.sign(data, process.env.JWT_SECRET, { expiresIn: 3600 * 6 });
// We handle our send email here
const from = 'no-reply <[email protected]>';
const to = user.email;
const link = process.env.NODE_ENV === 'production' ?
`https://jimoh-postit.herokuapp.com/reset-password?qrp=${token}` :
`http://localhost:8080/reset-password?qrp=${token}`;
const subject = 'Your PostIt Password recovery link';
// const message = '<h2>Click the link below to recover your password</h2><p><a href="localhost:4000/change-password?qrp='+token+'">Recover password</a></p>';
const message = `<h2>Click the link below to reset your password</h2><p><a href="${link}">Recover Password</a></p>`;
sendMail(from, to, subject, message)
.then((sent) => {
if (!sent) {
return Promise.reject('Password recovery failed...try again');
}
return handleSuccess(200, 'Password recovery link sent to your email', res);
})
// send successful whether error occurred or not since message was created
.catch(err => handleError(err, res));
})
.catch(err => handleError(err, res));
},
resetPasswordGet(req, res) {
if (!req.reset) {
return handleError('This request is invalid', res);
}
return handleSuccess(200, 'You can reset password', res);
},
resetPasswordPost(req, res) {
if (!req.reset) {
return handleError('Invalid request', res);
}
const obj = _.pick(req.body, ['password', 'confirm_password']);
const rules = {
password: 'required',
confirm_password: 'required'
};
const validator = new Validator(obj, rules);
if (!validator.passes()) {
return handleError({ validateError: validator.errors.all() }, res);
}
if (obj.password !== obj.confirm_password) {
return handleError('Passwords not matched', res);
}
const userInfo = req.reset;
User.findById(userInfo.id)
.then((user) => {
const salt = bcrypt.genSaltSync(10);
const hash = bcrypt.hashSync(obj.password, salt);
return user.update({ password: hash }, { where: { id: user.id } });
})
.then(updatedUser => handleSuccess(200, 'Password changed successfully', res))
.catch(err => handleError(err, res));
}
};
|
JavaScript
| 0.000002 |
@@ -2967,16 +2967,39 @@
);%0A %7D,%0A
+ // password Recovery%0A
passwo
|
80b456e0a7a42dbe02d2f41025bc0f11a6637a78
|
fix prettier issue
|
packages/components/bolt-ratio/__tests__/ratio.js
|
packages/components/bolt-ratio/__tests__/ratio.js
|
import {
isConnected,
render,
renderString,
stopServer,
html,
} from '../../../testing/testing-helpers';
const timeout = 60000;
const imageVrtConfig = {
failureThreshold: '0.005',
failureThresholdType: 'percent',
};
describe('<bolt-ratio> Component', () => {
let page, context;
beforeEach(async () => {
page = await context.newPage();
await page.goto('http://127.0.0.1:4444/', {
timeout: 0,
waitLoad: true,
waitNetworkIdle: true, // defaults to false
waitUntil: 'networkidle0',
});
}, timeout);
beforeAll(async () => {
context = await global.__BROWSER__.createIncognitoBrowserContext();
});
afterAll(async function() {
await context.close();
await stopServer();
});
test('<bolt-ratio> compiles', async () => {
const results = await render('@bolt-components-ratio/ratio.twig', {
children: '<img src="/fixtures/1200x660.jpg">',
ratio: '1200/660',
});
expect(results.ok).toBe(true);
expect(results.html).toMatchSnapshot();
});
test('Default <bolt-ratio> w/o Shadow DOM renders', async function() {
const renderedRatioHTML = await page.evaluate(() => {
const ratio = document.createElement('bolt-ratio');
const img = document.createElement('img');
img.setAttribute('src', '/fixtures/1200x660.jpg');
ratio.setAttribute('no-shadow', '');
ratio.setAttribute('ratio', '1200/660');
ratio.appendChild(img);
document.body.appendChild(ratio);
ratio.useShadow = false;
ratio.updated();
return ratio.outerHTML;
});
expect(renderedRatioHTML).toMatchSnapshot();
await page.evaluate(async () => {
const selectors = Array.from(document.querySelectorAll('bolt-ratio'));
return await Promise.all(
selectors.map(ratio => {
if (ratio._wasInitiallyRendered) return;
return new Promise((resolve, reject) => {
ratio.addEventListener('ready', resolve);
ratio.addEventListener('error', reject);
});
}),
);
});
const image = await page.screenshot();
expect(image).toMatchImageSnapshot(imageVrtConfig);
const renderedRatioStyles = await page.evaluate(() => {
const ratio = document.querySelector('bolt-ratio');
const innerRatio = ratio.renderRoot.querySelector('.c-bolt-ratio');
return innerRatio.style.getPropertyValue('--aspect-ratio').trim();
});
expect(renderedRatioStyles).toMatch(parseFloat(1200 / 660).toFixed(5));
});
test('<bolt-ratio> with HTML5 video renders', async function() {
const renderedRatioHTML = await page.evaluate(() => {
const ratio = document.createElement('bolt-ratio');
ratio.innerHTML = `<video controls poster="/fixtures/videos/poster.png">
<source src="/fixtures/videos/devstories.webm" type="video/webm;codecs="vp8, vorbis"">
<source src="/fixtures/videos/devstories.mp4" type="video/mp4;codecs="avc1.42E01E, mp4a.40.2"">
<track src="/fixtures/videos/devstories-en.vtt" label="English subtitles" kind="subtitles" srclang="en" default="">
</video>`;
ratio.setAttribute('ratio', '640/360');
ratio.style.width = '640px';
document.body.appendChild(ratio);
ratio.updated();
return ratio.outerHTML;
});
await page.evaluate(async () => {
const selectors = Array.from(document.querySelectorAll('bolt-ratio'));
return await Promise.all(
selectors.map(ratio => {
if (ratio._wasInitiallyRendered === true) return '_wasInitiallyRendered';
return new Promise((resolve, reject) => {
ratio.addEventListener('ready', resolve('ready'));
ratio.addEventListener('error', reject);
});
}),
);
});
await page.evaluate(async () => {
const selectors = Array.from(document.querySelectorAll('bolt-ratio'));
return await Promise.all(
selectors.map(ratio => {
const video = ratio.querySelector('video');
if (video.readyState === 4) return;
return new Promise((resolve, reject) => {
video.addEventListener('canplaythrough', resolve);
video.addEventListener('error', reject);
});
}),
);
});
// const renderedRatioSize = await page.evaluate(() => {
// const ratioSize = {
// width: document.querySelector('bolt-ratio').clientWidth,
// height: document.querySelector('bolt-ratio').clientHeight,
// };
// return ratioSize;
// });
const image = await page.screenshot();
expect(image).toMatchImageSnapshot(imageVrtConfig);
expect(renderedRatioHTML).toMatchSnapshot();
});
test('<bolt-ratio> twig - ratio prop fraction containing a decimal', async () => {
const results = await render('@bolt-components-ratio/ratio.twig', {
children: '<img src="/fixtures/1200x850-alt.jpg">',
ratio: '12/8.5',
});
expect(results.ok).toBe(true);
expect(results.html).toMatchSnapshot();
const html = results.html;
await page.evaluate(html => {
const div = document.createElement('div');
div.innerHTML = `${html}`;
document.body.appendChild(div);
const ratio = document.querySelector('bolt-ratio');
ratio.updated();
}, html);
await page.evaluate(async () => {
const selectors = Array.from(document.querySelectorAll('bolt-ratio'));
await Promise.all(
selectors.map(ratio => {
if (ratio._wasInitiallyRendered === true) return;
return new Promise((resolve, reject) => {
ratio.addEventListener('ready', resolve);
ratio.addEventListener('error', reject);
});
}),
);
});
await page.evaluate(async () => {
const selectors = Array.from(document.querySelectorAll('bolt-ratio'));
return await Promise.all(
selectors.map(ratio => {
const image = ratio.querySelector('img');
if (image.complete) {
return;
}
return new Promise((resolve, reject) => {
image.addEventListener('load', resolve);
image.addEventListener('error', reject);
});
}),
);
});
// await page.waitFor(500); // wait a second before testing
const image = await page.screenshot();
expect(image).toMatchImageSnapshot(imageVrtConfig);
const renderedRatioStyles = await page.evaluate(() => {
const ratio = document.querySelector('bolt-ratio');
const innerRatio = ratio.renderRoot.querySelector('.c-bolt-ratio');
return innerRatio.style.getPropertyValue('--aspect-ratio').trim();
});
expect(renderedRatioStyles).toMatch(parseFloat(1200 / 850).toFixed(5));
});
test('<bolt-ratio> web component - ratio prop fraction containing a decimal', async function() {
const renderedRatioHTML = await page.evaluate(() => {
const ratio = document.createElement('bolt-ratio');
const img = document.createElement('img');
img.setAttribute('src', '/fixtures/1200x850.jpg');
ratio.setAttribute('ratio', '12/8.5');
ratio.appendChild(img);
document.body.appendChild(ratio);
ratio.updated();
return ratio.outerHTML;
});
expect(renderedRatioHTML).toMatchSnapshot();
await page.evaluate(async () => {
const selectors = Array.from(document.querySelectorAll('bolt-ratio'));
await Promise.all(
selectors.map(ratio => {
if (ratio._wasInitiallyRendered === true) return;
return new Promise((resolve, reject) => {
ratio.addEventListener('ready', resolve);
ratio.addEventListener('error', reject);
});
}),
);
});
const image = await page.screenshot();
expect(image).toMatchImageSnapshot(imageVrtConfig);
const renderedRatioStyles = await page.evaluate(() => {
const ratio = document.querySelector('bolt-ratio');
const innerRatio = ratio.renderRoot.querySelector('.c-bolt-ratio');
return innerRatio.style.getPropertyValue('--aspect-ratio').trim();
});
expect(renderedRatioStyles).toMatch(parseFloat(1200 / 850).toFixed(5));
});
});
|
JavaScript
| 0.000025 |
@@ -3554,24 +3554,36 @@
ed === true)
+%0A
return '_wa
|
a3ddbb08bdf5efd0830b2c1647cfa4a3dbefbbc6
|
Add deregisterInstance to $ionDrawerVerticalHandle Controller
|
ion-drawer-vertical/ionic.contrib.drawer.vertical.js
|
ion-drawer-vertical/ionic.contrib.drawer.vertical.js
|
(function() {
'use strict';
angular.module('ionic.contrib.drawer.vertical', ['ionic'])
.controller('$ionDrawerVerticalHandle', function($element, $attrs, $ionicGesture, $timeout) {
// We need closure
var self = this;
// Possible states the drawer can have
var STATE_CLOSE = 'closed';
var STATE_OPEN = 'opened';
// Possible directions the drawer may slide out to
var DIRECTION_DOWN = 'down';
var DIRECTION_UP = 'up';
// Get state & direction
// default: STATE_OPEN and DIRECTION_DOWN
var state = ($attrs.state === STATE_CLOSE ? STATE_CLOSE : STATE_OPEN);
var direction = ($attrs.direction === DIRECTION_UP ? DIRECTION_UP : DIRECTION_DOWN);
// Parameter which tells if we are animating or not
var isBusyAnimating = false;
// Persist the state and direction on the wrapper
// (needed for animations)
var $wrapper = $element.parent('ion-drawer-vertical-wrapper');
$wrapper.addClass(state);
$wrapper.addClass(direction);
// Open the drawer
var open = function() {
if (!this.isOpen() || isBusyAnimating) {
isBusyAnimating = true;
$wrapper.removeClass(STATE_CLOSE);
$wrapper.addClass(STATE_OPEN + ' animate');
$timeout(function() {
$wrapper.removeClass('animate');
state = STATE_OPEN;
isBusyAnimating = false;
}, 400);
}
}
this.open = open;
// Close the drawer
var close = function() {
if (this.isOpen() || isBusyAnimating) {
isBusyAnimating = true;
$wrapper.removeClass(STATE_OPEN);
$wrapper.addClass(STATE_CLOSE + ' animate');
$timeout(function() {
$wrapper.removeClass('animate');
state = STATE_CLOSE;
isBusyAnimating = false;
}, 400);
}
}
this.close = close;
// Toggle the drawer
var toggle = function() {
if (this.isOpen()) {
this.close();
} else {
this.open();
}
}
this.toggle = toggle;
// Check if the drawer is open or not
var isOpen = function() {
return state === STATE_OPEN;
}
this.isOpen = isOpen;
// Handle drag up event: open or close (based on direction)
$ionicGesture.on('dragup', function(e) {
// Don't do jack if we are already animating
if (isBusyAnimating) return;
// Drawer needs to slide up in order to be open, and state is not open: open it!
if ((direction == DIRECTION_UP) && !self.isOpen()) {
self.open();
return;
}
// Drawer needs to slide up in order to be closed, and state is open (not closed): close it!
if ((direction == DIRECTION_DOWN) && self.isOpen()) {
self.close();
return;
}
}, $element);
// Handle drag down event: open or close (based on direction)
$ionicGesture.on('dragdown', function(e) {
// Don't do jack if we are already animating
if (isBusyAnimating) return;
// Drawer needs to slide down in order to be open, and state is not open: open it!
if ((direction == DIRECTION_DOWN) && !self.isOpen()) {
self.open();
return;
}
// Drawer needs to slide up in order to be closed, and state is open (not closed): close it!
if ((direction == DIRECTION_UP) && self.isOpen()) {
self.close();
return;
}
}, $element);
});
})();
(function() {
angular.module('ionic.contrib.drawer.vertical')
.directive('ionDrawerVerticalWrapper', function() {
return {
restrict: 'E'
}
})
.directive('ionDrawerVerticalHandle', function() {
return {
restrict: 'E',
controller: '$ionDrawerVerticalHandle',
link: function($scope, $element, $attr, ctrl) {
$scope.openDrawer = function() {
ctrl.open();
};
$scope.closeDrawer = function() {
ctrl.close();
};
$scope.toggleDrawer = function() {
ctrl.toggle();
};
}
}
});
})();
(function() {
angular.module('ionic.contrib.drawer.vertical')
.service('$ionDrawerVerticalHandleDelegate', ionic.DelegateService([
'openDrawer',
'closeDrawer',
'toggleDrawer'
]));
})();
|
JavaScript
| 0 |
@@ -134,16 +134,24 @@
unction(
+$scope,
$element
@@ -183,16 +183,65 @@
$timeout
+, $ionicHistory, $ionDrawerVerticalHandleDelegate
) %7B%0A%0A%09%09/
@@ -952,28 +952,25 @@
wrapper');%0A%09
-
+%09
$wrapper.add
@@ -984,20 +984,17 @@
tate);%0A%09
-
+%09
$wrapper
@@ -1021,12 +1021,281 @@
;%0A%0A%09
-
+%09// Delegate Stuff%0A%09%09var deregisterInstance = $ionDrawerVerticalHandleDelegate._registerInstance(%0A%09%09%09self, $attrs.delegateHandle, function() %7B%0A%09%09%09%09return $ionicHistory.isActiveScope($scope);%0A%09%09%09%7D%0A%09%09);%0A%09%09$scope.$on('$destroy', function() %7B%0A%09%09%09deregisterInstance();%0A%09%09%7D);%0A%0A%09%09
// O
|
fedb810414e70689690629138621622779a5eb8e
|
Remove reference to old imagescaling in infinite scroll
|
source/themes/quis/js/init.js
|
source/themes/quis/js/init.js
|
// =============================================
//
// WWW.QUIS.CC
// ---------------------------------------------
//
// By Chris Hill-Scott, except where noted.
//
// =============================================
$(function() {
for (var module in QUIS) {
if (QUIS[module].init) QUIS[module].init();
}
if (!QUIS.isMobile) {
$(".next-link")
.hide();
}
// Automatically load new photos when scrolling near bottom of page
$("#photos")
.infinitescroll(
{
navSelector: "footer",
nextSelector: ".next-link a",
itemSelector: ".unit",
loadingText: "Loading more photos",
donetext: "No more photos",
callback: function(path, pageID) {
// size newly-loaded images
$("#" + pageID + " " + QUIS.imageSelector)
.imageScale();
QUIS.map.renderMap();
if (_gaq) {
// Notify Google Analytics of page view
_gaq.push(['_trackPageview', path]);
}
}
}
);
// Keyboard navigation controller
$(document)
.keydown(
function(event) {
switch (event.keyCode || event.which) {
case 74: // j
case 40: // down arrow
return scrollPhotos.go(1);
case 75: // k
case 38: // up arrow
return scrollPhotos.go(-1);
}
}
);
});
|
JavaScript
| 0 |
@@ -773,133 +773,8 @@
%7B%0A%0A
- // size newly-loaded images%0A $(%22#%22 + pageID + %22 %22 + QUIS.imageSelector)%0A .imageScale();%0A%0A
|
0ff0d381b0d61c3f100c3c1858cbe61d38ed665f
|
Update buttons.js
|
packages/materialize/views/collections/buttons.js
|
packages/materialize/views/collections/buttons.js
|
Template.materializeButtons.rendered = function() {
Session.set("orion_autoformLoading", undefined);
};
|
JavaScript
| 0.000001 |
@@ -25,19 +25,19 @@
ons.
-r
+onR
endered
- =
+(
func
@@ -97,10 +97,11 @@
ined);%0A%7D
+)
;%0A
|
fc8f46363721ed3f9b8aea61ae7df9d73438c7c4
|
fix status code to be BadMonitoredItemFilterUnsupported when a DeadbandPercent filter is requested and the uaVariable has no euRange
|
packages/node-opcua-server/src/validate_filter.js
|
packages/node-opcua-server/src/validate_filter.js
|
var assert = require("node-opcua-assert");
var _ = require("underscore");
var subscription_service = require("node-opcua-service-subscription");
var StatusCodes = require("node-opcua-status-code").StatusCodes;
var AttributeIds = require("node-opcua-data-model").AttributeIds;
var UAVariable = require("node-opcua-address-space").UAVariable;
var NodeId = require("node-opcua-nodeid").NodeId;
var EventFilter = require("node-opcua-service-filter").EventFilter;
function __validateDataChangeFilter(filter,itemToMonitor,node) {
assert(itemToMonitor.attributeId === AttributeIds.Value);
assert(filter instanceof subscription_service.DataChangeFilter);
if (!(node instanceof UAVariable)) {
return StatusCodes.BadNodeIdInvalid;
}
assert(node instanceof UAVariable);
// if node is not Numerical=> DataChangeFilter
assert(node.dataType instanceof NodeId);
var dataType = node.addressSpace.findDataType(node.dataType);
var dataTypeNumber = node.addressSpace.findDataType("Number");
if (!dataType.isSupertypeOf(dataTypeNumber)) {
return StatusCodes.BadFilterNotAllowed;
}
if (filter.deadbandType === subscription_service.DeadbandType.Percent) {
if (filter.deadbandValue < 0 || filter.deadbandValue > 100) {
return StatusCodes.BadDeadbandFilterInvalid;
}
// node must also have a valid euRange
if (!node.euRange) {
console.log(" node has no euRange ! DeadbandPercent cannot be used on node "+ node.nodeId.toString());
return StatusCodes.BadFilterNotAllowed;
}
}
return StatusCodes.Good;
}
function __validateFilter(filter, itemToMonitor ,node) {
// handle filter information
if (filter && filter instanceof EventFilter && itemToMonitor.attributeId !== AttributeIds.EventNotifier) {
// invalid filter on Event
return StatusCodes.BadFilterNotAllowed;
}
if (filter && filter instanceof subscription_service.DataChangeFilter && itemToMonitor.attributeId !== AttributeIds.Value) {
// invalid DataChange filter on non Value Attribute
return StatusCodes.BadFilterNotAllowed;
}
if (filter && itemToMonitor.attributeId !== AttributeIds.EventNotifier && itemToMonitor.attributeId !== AttributeIds.Value) {
return StatusCodes.BadFilterNotAllowed;
}
if (filter instanceof subscription_service.DataChangeFilter) {
return __validateDataChangeFilter(filter,itemToMonitor,node);
}
return StatusCodes.Good;
}
exports.validateFilter = __validateFilter;
|
JavaScript
| 0 |
@@ -1562,38 +1562,52 @@
tusCodes.Bad
-FilterNotAllow
+MonitoredItemFilterUnsupport
ed;%0A
|
f74c3e5ec350b78d8047268d6d2e9ee87646c841
|
add cases for json and verbose (#1573)
|
packages/webpack-cli/__tests__/StatsGroup.test.js
|
packages/webpack-cli/__tests__/StatsGroup.test.js
|
const StatsGroup = require('../lib/groups/StatsGroup');
describe('StatsGroup', function () {
{
StatsGroup.validOptions().map((option) => {
it(`should handle ${option} option`, () => {
const statsGroup = new StatsGroup([
{
stats: option,
},
]);
const result = statsGroup.run();
expect(result.options.stats).toEqual(option);
});
});
}
});
|
JavaScript
| 0.000001 |
@@ -503,13 +503,514 @@
);%0A %7D
+%0A%0A it('should handle verbose', () =%3E %7B%0A const group = new StatsGroup(%5B%0A %7B%0A verbose: true,%0A %7D,%0A %5D);%0A%0A const result = group.run();%0A expect(result.options.stats).toEqual('verbose');%0A %7D);%0A%0A it('should handle json', () =%3E %7B%0A const group = new StatsGroup(%5B%0A %7B%0A json: true,%0A %7D,%0A %5D);%0A%0A const result = group.run();%0A expect(result.outputOptions.json).toBeTruthy();%0A %7D);
%0A%7D);%0A
|
e7553a8598db88d4215a2ed0f5b3cce2fa909b64
|
fix click after filter is reset
|
src/app/ResultsGrid.js
|
src/app/ResultsGrid.js
|
define([
'dojo/text!app/templates/ResultsGrid.html',
'dojo/_base/declare',
'dojo/_base/array',
'dojo/_base/lang',
'dojo/store/Memory',
'dojo/topic',
'dojo/dom-class',
'dijit/_WidgetBase',
'dijit/_TemplatedMixin',
'dgrid/OnDemandGrid',
'dgrid/Selection',
'esri/tasks/query',
'app/config'
], function(
template,
declare,
array,
lang,
Memory,
topic,
domClass,
_WidgetBase,
_TemplatedMixin,
Grid,
Selection,
Query,
config
) {
return declare([_WidgetBase, _TemplatedMixin], {
// description:
// Sorts and displays the search results.
templateString: template,
baseClass: 'results-grid',
// grid: Grid
// the main grid
grid: null,
// Properties to be sent into constructor
postCreate: function() {
// summary:
// Overrides method of same name in dijit._Widget.
// tags:
// private
console.log('app.ResultsGrid::postCreate', arguments);
this.setupConnections();
},
setupConnections: function() {
// summary:
// wire events, and such
console.log('app.ResultsGrid::setupConnections', arguments);
this.own(
topic.subscribe(config.topics.events.search, lang.hitch(this, 'search')),
topic.subscribe(config.topics.events.updateEnd, lang.hitch(this, 'showSearchResultsInGrid'))
);
},
startup: function() {
// summary:
// creates the dgrid
console.log('app.ResultsGrid::startup', arguments);
this.store = new Memory({
data: []
});
this.query = new Query();
this.grid = new(declare([Grid, Selection]))({
bufferRows: Infinity,
store: this.store,
noDataMessage: 'No results found.',
loadingMessage: 'Querying boundaries...',
columns: {
id: 'id',
name: 'Boundary Name',
service: 'Type of Service',
level: 'Level of Service',
geometry: 'shape'
},
selectionMode: 'single'
}, this.domNode);
this.grid.on('dgrid-select', function(events) {
var row = events.rows[0];
if (!row) {
return;
}
topic.publish(config.topics.map.highlight, row.data.geometry);
topic.publish(config.topics.map.zoom, row.data.geometry);
topic.publish(config.topics.events.setTitle, row.data.name);
});
this.grid.styleColumn('geometry', 'display: none;');
this.grid.styleColumn('id', 'display: none;');
},
showSearchResultsInGrid: function (result) {
// summary:
// description
// param or return
console.log('app.ResultsGrid:showSearchResultsInGrid', arguments);
this.store.data = null;
this.grid.refresh();
var data = result.target.graphics.map(function(feature) {
return {
// property names used here match those used when creating the dgrid
'id': feature.attributes.OBJECTID,
'name': feature.attributes.NAME,
'service': feature.attributes.SERVICE_TYPE,
'level': feature.attributes.SERVICE_LEVEL,
'geometry': feature.geometry
};
});
this.store.data = data;
this.grid.refresh();
domClass.remove(this.domNode, 'hide');
this.grid.startup();
},
search: function(args) {
// summary:
// queries the data and displays features in a grid
// args: { point - the map point click geometry, layer - the layer being queried }
console.log('app.ResultsGrid::search', arguments);
if (this.grid) {
this.grid.store.data = null;
this.grid.refresh();
}
var self = this;
this.query.geometry = args.point;
if (args.layer.layerDefinitions) {
this.query.where = args.layer.layerDefinitions[0];
}
args.layer.queryFeatures(this.query, function(results) {
var data = array.map(results.features, function(feature) {
return {
// property names used here match those used when creating the dgrid
'id': feature.attributes.OBJECTID,
'name': feature.attributes.NAME,
'service': feature.attributes.SERVICE_TYPE,
'level': feature.attributes.SERVICE_LEVEL,
'geometry': feature.geometry
};
});
self.store.data = data;
self.grid.refresh();
domClass.remove(self.domNode, 'hide');
self.grid.startup();
});
}
});
});
|
JavaScript
| 0 |
@@ -350,18 +350,19 @@
function
+
(%0A
-
temp
@@ -881,32 +881,33 @@
Create: function
+
() %7B%0A
@@ -1174,32 +1174,33 @@
ctions: function
+
() %7B%0A
@@ -1600,16 +1600,17 @@
function
+
() %7B%0A
@@ -2464,16 +2464,17 @@
function
+
(events)
@@ -3316,32 +3316,33 @@
ics.map(function
+
(feature) %7B%0A
@@ -3960,16 +3960,17 @@
function
+
(args) %7B
@@ -4226,134 +4226,8 @@
);%0A%0A
- if (this.grid) %7B%0A this.grid.store.data = null;%0A this.grid.refresh();%0A %7D%0A%0A
@@ -4418,32 +4418,257 @@
%0A %7D%0A%0A
+ var priorQuery = args.layer.getDefinitionExpression();%0A if (priorQuery === '1=2') %7B%0A args.layer.setVisibility(false);%0A args.layer.setDefinitionExpression();%0A %7D%0A%0A
args
@@ -4708,16 +4708,17 @@
function
+
(results
@@ -4717,24 +4717,137 @@
(results) %7B%0A
+ args.layer.setDefinitionExpression(priorQuery);%0A args.layer.setVisibility(true);%0A%0A
@@ -4897,16 +4897,17 @@
function
+
(feature
@@ -5505,32 +5505,32 @@
mNode, 'hide');%0A
-
@@ -5542,32 +5542,315 @@
grid.startup();%0A
+ %7D, function () %7B%0A args.layer.setDefinitionExpression(priorQuery);%0A args.layer.setVisibility(true);%0A%0A if (self.grid) %7B%0A self.grid.store.data = null;%0A self.grid.refresh();%0A %7D%0A
%7D);%0A
|
bddbc2f86bd0002fef6790905da77bc07e8d08c6
|
use platform specific EOL
|
lib/plugins/input/files.js
|
lib/plugins/input/files.js
|
'use strict'
/*
* See the NOTICE.txt file distributed with this work for additional information
* regarding copyright ownership.
* Sematext licenses logagent-js to you 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 path = require('path')
var fs = require('fs')
var os = require('os')
var Tail = require('tail-forever')
var glob = require('glob')
var logger = require('../../util/logger.js')
function InputFile (options, eventEmitter) {
this.eventEmitter = eventEmitter
this.options = options
this.filesToWatch = []
this.fileNamesToWatch = []
this.scanCounter = 0
this.stats = {}
this.sigTermHandled = false
this.laStats = require('../../core/printStats')
this.laStats.fileManger = this
this.activated = false
}
function getFilesizeInBytes (filename) {
try {
var stats = fs.statSync(filename)
return stats.size
} catch (fsErr) {
return -1
}
}
InputFile.prototype.stop = function (cb) {
this.terminate()
cb()
}
InputFile.prototype.start = function () {
var globPattern = this.options.glob || process.env.GLOB_PATTERN
if (this.options.args && this.options.args.length > 0) {
this.filePointers = this.readFilePointers()
// tail files
this.tailFiles(this.options.args)
this.activated = true
}
if (globPattern) {
this.activated = true
if (!this.filePointers) {
this.filePointers = this.readFilePointers()
}
// remove quotes from shell script
globPattern = globPattern.replace(/"/g, '').replace(/'/g, '').replace(/\s/g, '')
logger.log('using glob pattern: ' + globPattern)
this.tailFilesFromGlob(globPattern, 60000)
}
}
InputFile.prototype.tailFiles = function (fileList) {
fileList.forEach(this.tailFile.bind(this))
}
InputFile.prototype.getTempDir = function () {
return this.options.diskBufferDir || process.env.LOGSENE_TMP_DIR || os.tmpdir()
}
InputFile.prototype.getTailPosition = function (file) {
var storedPos = this.filePointers[file]
if (!storedPos) {
logger.debug('no position stored for ' + file)
// tail from end of file
return {start: this.options.tailStartPosition || getFilesizeInBytes(file)}
} else {
var fd = fs.openSync(file, 'r')
var stat = fs.fstatSync(fd)
if (stat.ino === storedPos.inode) {
return {start: storedPos.pos, inode: storedPos.inode}
} else {
logger.debug('Watching file ' + file + ' inode changed, set tail position = 0')
return {start: 0}
}
}
}
InputFile.prototype.tailFilesFromGlob = function (globPattern, scanTime) {
if (globPattern) {
glob(globPattern, {
strict: false,
silent: false
}, function globCb (err, files) {
if (!err) {
this.tailFiles(files)
} else {
logger.error('Error in glob file patttern ' + globPattern + ': ' + err.message)
}
}.bind(this))
if (!this.globPattern && scanTime > 0) {
this.globPattern = globPattern
setInterval(function scanFilesTimer () {
this.scanCounter = 1
this.tailFilesFromGlob(this.globPattern, scanTime)
}.bind(this), scanTime)
}
}
}
InputFile.prototype.tailFile = function (file) {
var tail = null
var pos = {start: 0}
if (this.fileNamesToWatch.indexOf(file) > -1) {
// check if we watch this file already
return null
}
try {
pos = this.getTailPosition(file)
} catch (error) {
// file might not exists, we ignore it and start watching
pos = {start: 0}
}
if (this.scanCounter > 0) {
// a new file matched the glob pattern
// reading from begin of file
logger.log('New file detected: ' + file)
pos = {start: 0}
}
try {
if (pos.start === -1) {
// there was no postion stored, let's start from the beginning
// throw new Error('File ' + file + ' does not exist.')
pos.start = 0
}
tail = new Tail(file, pos)
this.filesToWatch.push(tail)
this.fileNamesToWatch.push(file)
var context = {sourceName: file, startPos: pos}
tail.on('line', function (line) {
this.stats[file] = (this.stats[file] || 0) + 1
this.eventEmitter.emit('data.raw', line, context)
}.bind(this))
tail.once('error', function (error) {
var errMessage = 'ERROR tailing file ' + file + ': ' + error
logger.error(errMessage)
this.eventEmitter.emit('error.plugin.input.file', errMessage, {file: file, error: error})
}.bind(this))
logger.log('Watching file:' + file + ' from position: ' + pos.start)
return tail
} catch (error) {
// log('ERROR tailing file ' + file + ': ' + error)
return null
}
}
InputFile.prototype.terminate = function () {
if (!this.sigTermHandled && this.activated) {
this.sigTermHandled = true
this.savePositions()
}
}
InputFile.prototype.savePositions = function () {
var filePositions = this.filesToWatch.map(function filesToWatchMap (tailObj) {
try {
var position = tailObj.unwatch()
position.fileName = tailObj.filename
logger.log('Stop watching ' + tailObj.filename + ' inode: ' + position.inode + ' pos:' + position.pos)
return position
} catch (fileExistsError) {
// file got removed
return null
}
})
try {
var fileName = path.join(this.getTempDir(), 'logagentTailPointers.json')
fs.writeFileSync(fileName, JSON.stringify(filePositions))
logger.log('File positions stored in: ' + fileName)
} catch (err) {
logger.log('error writing file pointers:' + err)
}
}
InputFile.prototype.readFilePointers = function () {
var filePointers = {}
try {
var fileName = path.join(this.getTempDir(), 'logagentTailPointers.json')
var fp = fs.readFileSync(fileName)
var filePointerArr = JSON.parse(fp)
filePointerArr.forEach(function storeFp (f) {
filePointers[f.fileName] = {pos: f.pos, inode: f.inode}
})
if (Object.keys(filePointers).length > 0) {
logger.debug(JSON.stringify(filePointers, null, '\t'))
}
fs.unlinkSync(fileName)
} catch (err) {
logger.log('No stored file postions (file not found):' + fileName)
}
return filePointers
}
module.exports = InputFile
|
JavaScript
| 0 |
@@ -4307,24 +4307,85 @@
t = 0%0A %7D%0A
+ // pass platform specific EOL%0A pos.separator = os.EOL%0A
tail = n
|
ebf004ee3597f704d3ceb08e93f04056c92b25cb
|
Remove left over param
|
BrowserExtension/scripts/community/profile_inventory.js
|
BrowserExtension/scripts/community/profile_inventory.js
|
'use strict';
if( document.getElementById( 'inventory_link_753' ) )
{
GetOption( {
'link-inventory': true,
'link-inventory-gift-subid': true,
'enhancement-inventory-sidebar': true,
'enhancement-inventory-update-urls': true,
'enhancement-inventory-quick-sell': true,
'enhancement-inventory-quick-sell-auto': false,
'enhancement-inventory-no-sell-reload': true
}, function( items )
{
if( items[ 'enhancement-inventory-sidebar' ] )
{
var style = document.createElement( 'link' );
style.id = 'steamdb_inventory_sidebar';
style.type = 'text/css';
style.rel = 'stylesheet';
style.href = GetLocalResource( 'styles/inventory-sidebar.css' );
document.head.appendChild( style );
}
if( items[ 'link-inventory' ] )
{
document.body.dataset.steamdbLinks = 'true';
}
if( items[ 'link-inventory-gift-subid' ] )
{
document.body.dataset.steamdbGiftSubid = 'true';
}
if( items[ 'enhancement-inventory-quick-sell' ] )
{
document.body.dataset.steamdbQuickSell = 'true';
}
if( items[ 'enhancement-inventory-quick-sell-auto' ] )
{
document.body.dataset.steamdbQuickSellAuto = 'true';
}
if( items[ 'enhancement-inventory-no-sell-reload' ] )
{
document.body.dataset.steamdbNoSellReload = 'true';
}
var element = document.createElement( 'script' );
element.id = 'steamdb_inventory_hook';
element.type = 'text/javascript';
element.src = GetLocalResource( 'scripts/community/inventory.js' );
element.dataset.homepage = GetHomepage();
document.head.appendChild( element );
} );
}
|
JavaScript
| 0 |
@@ -186,53 +186,8 @@
ue,%0A
-%09%09'enhancement-inventory-update-urls': true,%0A
%09%09'e
|
72e0ef14c5c1a1fb034a5a59a4ed4093719d1489
|
Fix for graph height issue.
|
ui/src/shared/components/ResizeContainer.js
|
ui/src/shared/components/ResizeContainer.js
|
import React, {PropTypes} from 'react'
import ResizeHandle from 'shared/components/ResizeHandle'
const {
node,
string,
} = PropTypes
const ResizeContainer = React.createClass({
propTypes: {
children: node.isRequired,
},
getInitialState() {
return {
topHeight: '60%',
bottomHeight: '40%',
isDragging: false,
}
},
handleStopDrag() {
this.setState({isDragging: false})
},
handleStartDrag() {
this.setState({isDragging: true})
},
handleMouseLeave() {
this.setState({isDragging: false})
},
handleDrag(e) {
if (!this.state.isDragging) {
return
}
const appHeight = parseInt(getComputedStyle(this.refs.resizeContainer).height, 10)
// headingOffset moves the resize handle as many pixels as the page-heading is taking up.
const headingOffset = window.innerHeight - appHeight
const turnToPercent = 100
const newTopPanelPercent = Math.ceil(((e.pageY - headingOffset) / (appHeight)) * turnToPercent)
const newBottomPanelPercent = (turnToPercent - newTopPanelPercent)
// Don't trigger a resize unless the change in size is greater than minResizePercentage
const minResizePercentage = 0.5
if (Math.abs(newTopPanelPercent - parseFloat(this.state.topHeight)) < minResizePercentage) {
return
}
// Don't trigger a resize if the new sizes are too small
const minTopPanelHeight = 200
const minBottomPanelHeight = 200
const topHeightPixels = ((newTopPanelPercent / turnToPercent) * appHeight)
const bottomHeightPixels = ((newBottomPanelPercent / turnToPercent) * appHeight)
if (topHeightPixels < minTopPanelHeight || bottomHeightPixels < minBottomPanelHeight) {
return
}
this.setState({topHeight: `${(newTopPanelPercent)}%`, bottomHeight: `${(newBottomPanelPercent)}%`, topHeightPixels})
},
renderHandle() {
const {isDragging, topHeight} = this.state
return (
<ResizeHandle isDragging={isDragging} onHandleStartDrag={this.handleStartDrag} top={topHeight} />
)
},
render() {
const {topHeight, topHeightPixels, bottomHeight} = this.state
const top = React.cloneElement(this.props.children[0], {height: topHeight, heightPixels: topHeightPixels})
const bottom = React.cloneElement(this.props.children[1], {height: bottomHeight})
return (
<div className="resize-container page-contents" onMouseLeave={this.handleMouseLeave} onMouseUp={this.handleStopDrag} onMouseMove={this.handleDrag} ref="resizeContainer" >
{top}
{this.renderHandle()}
{bottom}
</div>
)
},
})
export const ResizeBottom = ({
height,
children,
}) => (
<div className="resize-bottom" style={{height}}>
{children}
</div>
)
ResizeBottom.propTypes = {
children: node.isRequired,
height: string,
}
export default ResizeContainer
|
JavaScript
| 0 |
@@ -1736,16 +1736,23 @@
tState(%7B
+%0A
topHeigh
@@ -1781,16 +1781,22 @@
ent)%7D%25%60,
+%0A
bottomH
@@ -1832,16 +1832,22 @@
ent)%7D%25%60,
+%0A
topHeig
@@ -1850,24 +1850,56 @@
HeightPixels
+,%0A bottomHeightPixels,%0A
%7D)%0A %7D,%0A%0A r
@@ -2114,16 +2114,23 @@
const %7B
+%0A
topHeigh
@@ -2131,16 +2131,22 @@
pHeight,
+%0A
topHeig
@@ -2154,16 +2154,22 @@
tPixels,
+%0A
bottomH
@@ -2169,24 +2169,36 @@
bottomHeight
+Pixels,%0A
%7D = this.sta
@@ -2394,16 +2394,22 @@
omHeight
+Pixels
%7D)%0A r
@@ -2741,18 +2741,86 @@
,%0A%7D) =%3E
-(%0A
+%7B%0A const child = React.cloneElement(children, %7Bheight%7D)%0A return (%0A
%3Cdiv c
@@ -2870,29 +2870,34 @@
+
%7Bchild
-ren
%7D%0A
+
+
%3C/div%3E%0A
-)
+ )%0A%7D
%0A%0ARe
|
8ee6f4cbc96e29e79bad625f7a10e700468649b0
|
Add cpython dedicated project to OSD event.
|
public/modules/events/controllers/events.client.controller.js
|
public/modules/events/controllers/events.client.controller.js
|
'use strict';
angular.module('events').controller('EventsController', ['$scope',
function($scope) {
// TODO: Get events from a database or something. Don't hard code.
$scope.events = [
{
title: 'WWU Open Source Day',
day: 'Saturday',
dayNum: 9,
month: 'May',
monthNum: 5,
description: 'Dive into the world of open source and see how you can contribute to projects and make a difference today!',
link: 'http://www.wwu.edu/emarket/opensourceday/',
info:
'<dl>\
<dt>Suggested Resources</dt>\
<dd>Github\'s Atom text editor. <br><a target="_BLANK" href="https://atom.io/">https://atom.io/</a></dd>\
<dt>Git Resources</dt>\
<dd>Try Git tutorial. <br><a target="_BLANK" href="https://try.github.io">https://try.github.io</a></dd>\
<dd>Git Bash. <br><a target="_BLANK" href="http://git-scm.com/downloads">http://git-scm.com/downloads</a></dd>\
<dd>Github for Mac. <br><a target="_BLANK" href="https://mac.github.com/">https://mac.github.com/</a></dd>\
<dd>Github for Windows. <br><a target="_BLANK" href="https://windows.github.com/">https://windows.github.com/</a></dd>\
<dt>Dedicated Table Projects</dt>\
<dd><strong>Drupal</strong> (Jennifer Dixey) <br><a target="_blank" href="https://www.drupal.org/">https://www.drupal.org/</a></dd>\
<dd><strong>KeyMail (NachoBits)</strong> (Aaron Griffin) <br><a target="_blank" href="https://github.com/NachoBits/keymail">https://github.com/NachoBits/keymail</a></dd>\
<dd><strong>Language of Languages</strong> (Jamie & Andi Douglass) <br><a target="_blank" href="https://github.com/jamiedouglass/LanguageOfLanguages">https://github.com/jamiedouglass/LanguageOfLanguages</a></dd>\
<dd><strong>Able Player</strong> (Terry Thompson) <br><a target="_blank" href="https://github.com/ableplayer/ableplayer">https://github.com/ableplayer/ableplayer</a></dd>\
<dt>Other Suggested Projects</dt>\
<dd><strong>MediaWiki</strong> (lots of bite-size bugs, written in PHP) <br><a target="_blank" href="https://openhatch.org/projects/MediaWiki">https://openhatch.org/projects/MediaWiki</a> </dd>\
<dd><strong>openemr</strong> (social interest, looks beginner friendly) <br><a target="_blank" href="https://openhatch.org/projects/openemr">https://openhatch.org/projects/openemr</a> </dd>\
<dd><strong>OLPC</strong> (One Laptop per Child, social interest) <br><a target="_blank" href="https://openhatch.org/projects/OLPC">https://openhatch.org/projects/OLPC</a> </dd>\
<dd><strong>gedit</strong> (bite-sized bugs, documentation) <br><a target="_blank" href="http://openhatch.org/projects/gedit">http://openhatch.org/projects/gedit</a> </dd>\
<dd><strong>Mifos</strong> (social interest, written in Java) <br><a target="_blank" href="http://openhatch.org/projects/Mifos">http://openhatch.org/projects/Mifos</a> </dd>\
<dd><strong>Dreamwidth</strong> (lots of bite-sized bugs) <br><a target="_blank" href="https://openhatch.org/projects/Dreamwidth">https://openhatch.org/projects/Dreamwidth</a> </dd>\
<dd><strong>openspending</strong> (social/political interest, written in Python) <br><a target="_blank" href="https://openhatch.org/projects/openspending">https://openhatch.org/projects/openspending</a> </dd>\
<dd><strong>sympy</strong> (for math lovers, lots of bite-sized bugs, written in Python) <br><a target="_blank" href="https://openhatch.org/projects/sympy">https://openhatch.org/projects/sympy</a> </dd>\
<dd><strong>Firefox</strong> (lots of bite-sized bugs) <br><a target="_blank" href="https://openhatch.org/projects/Firefox">https://openhatch.org/projects/Firefox</a> </dd>\
</dl>'
},
{
title: 'Whatcom Robotics Expo',
day: 'Saturday',
dayNum: 27,
month: 'June',
monthNum: 6,
description: 'Whatcom county is full of different robotics groups! Experience them all under one roof and build your path in engineering from Kindergarten to College!',
link: 'https://www.facebook.com/events/1076239542392620/'
}
]
}
]);
|
JavaScript
| 0 |
@@ -1833,24 +1833,204 @@
r%3C/a%3E%3C/dd%3E%5C%0A
+%09%3Cdd%3E%3Cstrong%3Ecpython%3C/strong%3E (Alex Lord) %3Cbr%3E%3Ca target=%22_blank%22 href=%22https://openhatch.org/search/?q=&language=Python%22%3Ehttps://openhatch.org/search/?q=&language=Python%3C/a%3E%3C/dd%3E%5C%0A
%09%3Cdt%3EOther S
|
124f486d3719ce022db3e7eb36da3bbadbed6e32
|
Fix some syntax bugs
|
public/modules/events/controllers/events.client.controller.js
|
public/modules/events/controllers/events.client.controller.js
|
'use strict';
// Articles controller
angular.module('events').controller('EventsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Events',
function($scope, $stateParams, $location, Authentication, Events) {
$scope.authentication = Authentication;
// Create new Article
$scope.create = function() {
var googlePlaces = searchBox.getPlaces();
var location;
if (googlePlaces) {
var longitude = googlePlaces[0].geometry.location.lng();
var latitude = googlePlaces[0].geometry.location.lat();
location = [longitude, latitude];
}
// Create new Article object
var eventmodel = new Events({
title: this.title,
content: this.content,
location: location
});
// Redirect after save
eventmodel.$save(function(response) {
$location.path('events/' + response._id);
// Clear form fields
$scope.title = '';
$scope.content = '';
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Remove existing Article
$scope.remove = function(eventmodel) {
if (eventmodel) {
eventmodel.$remove();
for (var i in $scope.eventmodels) {
if ($scope.eventmodels[i] === eventmodel) {
$scope.eventmodels.splice(i, 1);
}
}
} else {
$scope.eventmodel.$remove(function() {
$location.path('eventmodels');
});
}
};
// Update existing Article
$scope.update = function() {
var eventmodel = $scope.eventmodel;
eventmodel.$update(function() {
$location.path('events/' + eventmodel._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Find a list of Articles
$scope.find = function() {
$scope.events = Events.query();
};
// Find existing Article
$scope.findOne = function() {
$scope.eventmodel = Events.get({
eventId: $stateParams.eventId
});
};
var input = document.getElementById('place');
if(input)
{
var searchBox = new google.maps.places.SearchBox(input);
}
}
]);
|
JavaScript
| 0.001012 |
@@ -266,16 +266,32 @@
cation;%0A
+%09%09var%09searchBox;
%0A%09%09// Cr
@@ -382,17 +382,17 @@
Places()
-;
+,
%0A
@@ -398,14 +398,8 @@
- var
loca
@@ -408,22 +408,17 @@
on;%0A
-
+%0A
if
(go
@@ -413,17 +413,16 @@
if
-
(googleP
@@ -430,22 +430,16 @@
aces) %7B%0A
-
%09v
@@ -496,18 +496,16 @@
ng()
-;
+,
%0A%09%09%09%09
-var
+%09%09
lati
@@ -548,25 +548,24 @@
tion.lat();%0A
-%0A
%09%09%09%09location
@@ -595,18 +595,18 @@
%5D;%0A%09%09
-
%7D
+%0A
%0A%09%09%09// C
@@ -1972,25 +1972,16 @@
put)
-%0A%09%09%7B%0A %09var
+ %7B%0A
sea
@@ -2030,20 +2030,16 @@
input);%0A
-
%7D%0A%09%7D
@@ -2042,8 +2042,9 @@
%7D%0A%09%7D%0A%5D);
+%0A
|
26f135fbd3f95cf1a08a8e5611c643af4658843d
|
Update stripe key
|
source/javascripts/config.js
|
source/javascripts/config.js
|
Flynn.config = {
stripeJSURL: "https://js.stripe.com/v2/",
STRIPE_KEY: "pk_LHV1PeIYOXtG1OfgADW0j5JKl3ST4"
};
|
JavaScript
| 0 |
@@ -74,37 +74,37 @@
%22pk_
-LHV1PeIYOXtG1OfgADW0j5JKl3ST4
+live_u7VRS3rSf1TjGLky5Im4ClH5
%22%0A%7D;
|
08cfa95c5efa508521ea28c8185d9a5b08997a12
|
Fix falsy pass
|
src/geophoto/server.js
|
src/geophoto/server.js
|
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
/**
* Module dependencies.
*/
var express = require('express'),
bodyParser = require('body-parser'),
errorHandler = require('errorhandler'),
expressEjsLayouts = require('express-ejs-layouts'),
io = require('socket.io'),
methodOverride = require('method-override'),
multer = require('multer')({dest: './uploads'}),
pushpinController = require('./controllers/pushpinController'),
socketio = require('socket.io'),
http = require('http'),
path = require('path');
var app = module.exports = express();
// Configuration
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(expressEjsLayouts);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(methodOverride());
app.use(express.static(path.join(__dirname, '/public')));
if ('development' === app.get('env')) {
app.use(errorHandler());
}
if ('production' == app.get('env')) {
app.use(errorHandler());
}
// Routes
app.get('/', pushpinController.showPushpins);
app.get('/setup', pushpinController.setup);
app.post('/setupPOST', pushpinController.setupPOST);
app.post('/createPushpin', multer.array('image'), pushpinController.createPushpin);
var server = app.listen(app.get('port'), function () {
console.log("Express server listening on port %d in %s mode",
app.get('port'),
app.get('env'));
});
// Setup socket.io
pushpinController.io = io(server);
pushpinController.io.on('connection', pushpinController.socketConnection);
|
JavaScript
| 0.000017 |
@@ -1564,16 +1564,17 @@
tion' ==
+=
app.get
|
15798e240b7883ccf8c0bed54e55f3ebe969df6d
|
Fix `isEditable` property for question answers
|
Dashboard/app/js/lib/views/data/question-answer-view.js
|
Dashboard/app/js/lib/views/data/question-answer-view.js
|
// this function is also present in assignment-edit-views.js, we need to consolidate using moment.js
function formatDate(date) {
if (date && !isNaN(date.getTime())) {
return date.getFullYear() + "/" + (date.getMonth() + 1) + "/" + date.getDate();
} else return null;
}
FLOW.QuestionAnswerView = Ember.View.extend({
isTextType: function(){
return this.get('questionType') === 'FREE_TEXT';
}.property('this.questionType'),
isCascadeType: function(){
return this.get('questionType') === 'CASCADE';
}.property('this.questionType'),
isOptionType: function(){
return this.get('questionType') === 'OPTION';
}.property('this.questionType'),
isNumberType: function(){
return this.get('questionType') === 'NUMBER';
}.property('this.questionType'),
isBarcodeType: function(){
return this.get('questionType') === 'SCAN';
}.property('this.questionType'),
isDateType: function(){
return this.get('questionType') === 'DATE';
}.property('this.questionType'),
isPhotoType: function(){
return this.get('questionType') === 'PHOTO';
}.property('this.questionType'),
isVideoType: function(){
return this.get('questionType') === 'VIDEO';
}.property('this.questionType'),
form: function() {
if (FLOW.selectedControl.get('selectedSurvey')) {
return FLOW.selectedControl.get('selectedSurvey');
}
}.property('FLOW.selectedControl.selectedSurvey'),
optionsList: function(){
var c = this.content;
if (Ember.none(c)) {
return [];
}
var questionId = c.get('questionID');
var options = FLOW.store.filter(FLOW.QuestionOption, function (item) {
return item.get('questionId') === +questionId;
});
optionArray = options.toArray();
optionArray.sort(function (a, b) {
return a.get('order') - b.get('order');
});
tempList = [];
optionArray.forEach(function (item) {
tempList.push(item.get('text'));
});
return tempList;
}.property('this.content'),
content: null,
inEditMode: false,
isNotEditable: function(){
var type = this.get('questionType');
return (type == 'GEO' || type == 'PHOTO' || type == 'VIDEO' || type == 'GEOSHAPE' || !this.get('isEditable'));
}.property('this.questionType,this.isEditable'),
isEditable: function () {
return FLOW.permControl.canEditResponses(this.get('form'));
}.property('this.form'),
date: null,
numberValue: null,
cascadeValue: function(key, value, previousValue){
var c = this.content;
// setter
if (arguments.length > 1) {
// split according to pipes
var cascadeNames = value.split("|");
var cascadeResponse = [];
var obj = null;
cascadeNames.forEach(function(item){
if (item.trim().length > 0) {
obj = {};
obj.name = item.trim();
cascadeResponse.push(obj);
}
});
c.set('value', JSON.stringify(cascadeResponse));
}
// getter
var cascadeString = "", cascadeJson;
if (c && c.get('value')) {
if (c.get('value').indexOf("|") > -1) {
cascadeString += c.get('value');
} else {
cascadeJson = JSON.parse(c.get('value'));
cascadeString = cascadeJson.map(function(item){
return item.name;
}).join("|");
}
return cascadeString;
}
return null;
}.property('this.content'),
photoUrl: function(){
var c = this.content;
if (!Ember.empty(c.get('value'))) {
return FLOW.Env.photo_url_root + c.get('value').split('/').pop();
}
}.property('this.content,this.isPhotoType,this.isVideoType'),
questionType: function(){
if(this.get('question')){
return this.get('question').get('type');
}
}.property('this.question'),
question: function(){
var c = this.get('content');
if (c) {
var questionId = c.get('questionID');
var q = FLOW.questionControl.findProperty('keyId', +questionId);
return q;
}
}.property('FLOW.questionControl.content'),
init: function () {
this._super();
},
doEdit: function () {
this.set('inEditMode', true);
var c = this.content;
if (this.get('isDateType') && !Ember.empty(c.get('value'))) {
var d = new Date(+c.get('value')); // need to coerce c.get('value') due to milliseconds
this.set('date', formatDate(d));
}
if (this.get('isNumberType') && !Ember.empty(c.get('value'))) {
this.set('numberValue', c.get('value'));
}
},
doCancel: function () {
this.set('inEditMode', false);
},
doSave: function () {
if (this.get('isDateType')) {
var d = Date.parse(this.get('date'));
if (isNaN(d) || d < 0) {
this.content.set('value', null);
} else {
this.content.set('value', d);
}
}
if (this.get('isNumberType')) {
if (isNaN(this.numberValue)) {
this.content.set('value', null);
} else {
this.content.set('value', this.numberValue);
}
}
FLOW.store.commit();
this.set('inEditMode', false);
},
doValidateNumber: function () {
// TODO should check for minus sign and decimal point, depending on question setting
this.set('numberValue', this.get('numberValue').toString().replace(/[^\d.]/g, ""));
}.observes('this.numberValue')
});
FLOW.QuestionAnswerInspectDataView = FLOW.QuestionAnswerView.extend({
templateName: 'navData/question-answer',
});
|
JavaScript
| 0.000002 |
@@ -1226,16 +1226,84 @@
ype'),%0A%0A
+ nonEditableQuestionTypes: %5B'GEO', 'PHOTO', 'VIDEO', 'GEOSHAPE'%5D,%0A%0A
form:
@@ -2132,139 +2132,77 @@
on()
+
%7B%0A
-var type = this.get('questionType');%0A return (type == 'GEO' %7C%7C type == 'PHOTO' %7C%7C type == 'VIDEO' %7C%7C type == 'GEOSHAPE' %7C%7C
+// keep this property to limit template rafactoring%0A return
!th
@@ -2221,17 +2221,16 @@
itable')
-)
;%0A %7D.pr
@@ -2246,26 +2246,8 @@
his.
-questionType,this.
isEd
@@ -2277,28 +2277,217 @@
: function (
+) %7B%0A var isEditableQuestionType, canEditFormResponses;%0A isEditableQuestionType = this.nonEditableQuestionTypes.indexOf(this.get('questionType')) %3C 0;%0A if (!isEditableQuestionType
) %7B%0A
+
return F
@@ -2489,75 +2489,225 @@
urn
-FLOW.permControl.canEditResponses(this.get('form'));%0A %7D.property('
+false; // no need to check permissions%0A %7D%0A%0A canEditFormResponses = FLOW.permControl.canEditResponses(this.get('form'));%0A return isEditableQuestionType && canEditFormResponses;%0A %7D.property('this.questionType,
this
|
1d6080f4999635a54c3817b326a5dece893a6fd8
|
Allow PhotoSwipeBase for lazyLoadData method
|
src/js/slide/loader.js
|
src/js/slide/loader.js
|
import PhotoSwipeBase from '../core/base.js';
import { getViewportSize, getPanAreaSize } from '../util/viewport-size.js';
import ZoomLevel from './zoom-level.js';
/** @typedef {import('./content.js').default} Content */
/** @typedef {import('./slide.js').default} Slide */
/** @typedef {import('./slide.js').SlideData} SlideData */
/** @typedef {import('../photoswipe.js').default} PhotoSwipe */
/** @typedef {import('../lightbox/lightbox.js').default} PhotoSwipeLightbox */
const MIN_SLIDES_TO_CACHE = 5;
/**
* Lazy-load an image
* This function is used both by Lightbox and PhotoSwipe core,
* thus it can be called before dialog is opened.
*
* @param {SlideData} itemData Data about the slide
* @param {PhotoSwipe | PhotoSwipeLightbox | PhotoSwipeBase} instance PhotoSwipe or PhotoSwipeLightbox
* @param {number} index
* @returns Image that is being decoded or false.
*/
export function lazyLoadData(itemData, instance, index) {
// src/slide/content/content.js
const content = instance.createContentFromData(itemData, index);
if (!content || !content.lazyLoad) {
return;
}
const { options } = instance;
// We need to know dimensions of the image to preload it,
// as it might use srcset and we need to define sizes
// @ts-expect-error should provide pswp instance?
const viewportSize = instance.viewportSize || getViewportSize(options, instance);
const panAreaSize = getPanAreaSize(options, viewportSize, itemData, index);
const zoomLevel = new ZoomLevel(options, itemData, -1);
zoomLevel.update(content.width, content.height, panAreaSize);
content.lazyLoad();
content.setDisplayedSize(
Math.ceil(content.width * zoomLevel.initial),
Math.ceil(content.height * zoomLevel.initial)
);
return content;
}
/**
* Lazy-loads specific slide.
* This function is used both by Lightbox and PhotoSwipe core,
* thus it can be called before dialog is opened.
*
* By default it loads image based on viewport size and initial zoom level.
*
* @param {number} index Slide index
* @param {PhotoSwipe | PhotoSwipeLightbox} instance PhotoSwipe or PhotoSwipeLightbox eventable instance
*/
export function lazyLoadSlide(index, instance) {
const itemData = instance.getItemData(index);
if (instance.dispatch('lazyLoadSlide', { index, itemData }).defaultPrevented) {
return;
}
return lazyLoadData(itemData, instance, index);
}
class ContentLoader {
/**
* @param {PhotoSwipe} pswp
*/
constructor(pswp) {
this.pswp = pswp;
// Total amount of cached images
this.limit = Math.max(
pswp.options.preload[0] + pswp.options.preload[1] + 1,
MIN_SLIDES_TO_CACHE
);
/** @type {Content[]} */
this._cachedItems = [];
}
/**
* Lazy load nearby slides based on `preload` option.
*
* @param {number=} diff Difference between slide indexes that was changed recently, or 0.
*/
updateLazy(diff) {
const { pswp } = this;
if (pswp.dispatch('lazyLoad').defaultPrevented) {
return;
}
const { preload } = pswp.options;
const isForward = diff === undefined ? true : (diff >= 0);
let i;
// preload[1] - num items to preload in forward direction
for (i = 0; i <= preload[1]; i++) {
this.loadSlideByIndex(pswp.currIndex + (isForward ? i : (-i)));
}
// preload[0] - num items to preload in backward direction
for (i = 1; i <= preload[0]; i++) {
this.loadSlideByIndex(pswp.currIndex + (isForward ? (-i) : i));
}
}
/**
* @param {number} index
*/
loadSlideByIndex(index) {
index = this.pswp.getLoopedIndex(index);
// try to get cached content
let content = this.getContentByIndex(index);
if (!content) {
// no cached content, so try to load from scratch:
content = lazyLoadSlide(index, this.pswp);
// if content can be loaded, add it to cache:
if (content) {
this.addToCache(content);
}
}
}
/**
* @param {Slide} slide
*/
getContentBySlide(slide) {
let content = this.getContentByIndex(slide.index);
if (!content) {
// create content if not found in cache
content = this.pswp.createContentFromData(slide.data, slide.index);
if (content) {
this.addToCache(content);
}
}
if (content) {
// assign slide to content
content.setSlide(slide);
}
return content;
}
/**
* @param {Content} content
*/
addToCache(content) {
// move to the end of array
this.removeByIndex(content.index);
this._cachedItems.push(content);
if (this._cachedItems.length > this.limit) {
// Destroy the first content that's not attached
const indexToRemove = this._cachedItems.findIndex((item) => {
return !item.isAttached && !item.hasSlide;
});
if (indexToRemove !== -1) {
const removedItem = this._cachedItems.splice(indexToRemove, 1)[0];
removedItem.destroy();
}
}
}
/**
* Removes an image from cache, does not destroy() it, just removes.
*
* @param {number} index
*/
removeByIndex(index) {
const indexToRemove = this._cachedItems.findIndex(item => item.index === index);
if (indexToRemove !== -1) {
this._cachedItems.splice(indexToRemove, 1);
}
}
/**
* @param {number} index
*/
getContentByIndex(index) {
return this._cachedItems.find(content => content.index === index);
}
destroy() {
this._cachedItems.forEach(content => content.destroy());
this._cachedItems = null;
}
}
export default ContentLoader;
|
JavaScript
| 0 |
@@ -1,50 +1,4 @@
-import PhotoSwipeBase from '../core/base.js';%0A
impo
@@ -276,24 +276,91 @@
lideData */%0A
+/** @typedef %7Bimport('../core/base.js').default%7D PhotoSwipeBase */%0A
/** @typedef
@@ -798,37 +798,24 @@
toSwipe
-or PhotoSwipeLightbox
+instance
%0A * @par
|
d8092243ea08717f683836273676ad7a964d4950
|
Add corrected prop usage in BottomModalContainer
|
src/widgets/bottomModals/BottomModalContainer.js
|
src/widgets/bottomModals/BottomModalContainer.js
|
/* eslint-disable react/forbid-prop-types */
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
import React from 'react';
import PropTypes from 'prop-types';
import { Keyboard, StyleSheet, View } from 'react-native';
import Modal from 'react-native-modalbox';
import { DARKER_GREY } from '../../globalStyles/index';
export const BottomModalContainer = ({
children,
isOpen,
swipeToClose,
backdropPressToClose,
position,
backdrop,
modalStyle,
containerStyle,
...modalProps
}) => {
React.useEffect(() => {
Keyboard.dismiss();
}, [isOpen]);
return (
<Modal
swipeToClose={swipeToClose}
backdropPressToClose={backdropPressToClose}
position={position}
backdrop={backdrop}
{...modalProps}
style={localStyles.modalStyle}
>
<View style={localStyles.containerStyle}>{children}</View>
</Modal>
);
};
const localStyles = StyleSheet.create({
containerStyle: {
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'flex-end',
alignItems: 'center',
},
modalStyle: {
height: 60,
justifyContent: 'center',
alignItems: 'flex-end',
backgroundColor: DARKER_GREY,
},
});
BottomModalContainer.defaultProps = {
swipeToClose: false,
backdropPressToClose: false,
position: 'bottom',
backdrop: false,
modalStyle: localStyles.modalStyle,
containerStyle: localStyles.containerStyle,
};
BottomModalContainer.propTypes = {
isOpen: PropTypes.bool.isRequired,
swipeToClose: PropTypes.bool,
backdropPressToClose: PropTypes.bool,
position: PropTypes.string,
backdrop: PropTypes.bool,
children: PropTypes.oneOfType([PropTypes.node, PropTypes.arrayOf(PropTypes.node)]).isRequired,
modalStyle: PropTypes.object,
containerStyle: PropTypes.object,
};
|
JavaScript
| 0 |
@@ -735,16 +735,38 @@
ckdrop%7D%0A
+ isOpen=%7BisOpen%7D%0A
%7B.
|
5e9c717442bd45363d3ddf33c3febe4cad301892
|
fix send command
|
reddcoin.js
|
reddcoin.js
|
var Future = Npm.require("fibers/future");
reddcoin = function(object) {
this.rdd = Npm.require("node-reddcoin")(object);
};
// reddcoind getbalance [account]
reddcoin.prototype.balance = function(account) {
var future = new Future();
if(account) {
this.rdd.exec("getbalance", account, function(err, balance) {
if(err) {
console.log(err);
future.return(err);
} else {
future.return(balance);
}
});
} else {
this.rdd.exec("getbalance", function(err, balance) {
if(err) {
console.log(err);
future.return(err);
} else {
future.return(balance);
}
});
}
return future.wait();
};
// reddcoind getinfo
reddcoin.prototype.info = function() {
var future = new Future();
this.rdd.exec("getinfo", function(err, info) {
if(err) {
console.log(err);
future.return(err);
} else {
future.return(info);
}
});
return future.wait();
}
// reddcoind gettransaction txid
reddcoin.prototype.transaction = function(txid) {
var future = new Future();
this.rdd.exec("gettransaction", txid, function(err, transaction) {
if(err) {
console.log(err);
future.return(err);
} else {
future.return(transaction);
}
});
return future.wait();
};
// reddcoind listtransactions
reddcoin.prototype.transactions = function() {
var future = new Future();
this.rdd.exec("listtransactions", function(err, transactions) {
if(err) {
console.log(err);
future.return(err);
} else {
future.return(transactions);
}
});
return future.wait();
};
// reddcoind listaccounts
reddcoin.prototype.accounts = function() {
var future = new Future();
this.rdd.exec("listaccounts", function(err, accounts) {
if(err) {
console.log(err);
future.return(err);
} else {
future.return(accounts);
}
});
return future.wait();
};
// reddcoind validateaddress address
reddcoin.prototype.validate = function(address) {
var future = new Future();
this.rdd.exec("validateaddress", address, function(err, validate) {
if(err) {
console.log(err);
future.return(err);
} else {
future.return(validate);
}
});
return future.wait();
};
// reddcoind getstakinginfo
reddcoin.prototype.stake = function() {
var future = new Future();
this.rdd.exec("getstakinginfo", function(err, stake) {
if(err) {
console.log(err);
future.return(err);
} else {
future.return(stake);
}
});
return future.wait();
};
// reddcoind walletpassphrase passphrase timeout stakeonly?
reddcoin.prototype.unlock = function(passphrase, timeout, stakeonly) {
var future = new Future();
if(stakeonly == undefined) {
stakeonly = false;
}
this.rdd.exec("walletpassphrase", passphrase, timeout, stakeonly, function(err, unlock) {
if(err) {
console.log(err);
future.return(err);
} else {
future.return(unlock);
}
});
return future.wait();
};
// reddcoind walletlock
reddcoin.prototype.lock = function() {
var future = new Future();
this.rdd.exec("walletlock", function(err, lock) {
if(err) {
console.log(err);
future.return(err);
} else {
future.return(lock);
}
});
return future.wait();
};
// reddcoind send to_address amount [comment]
reddcoin.prototype.send = function(address, amount, comment) {
var future = new Future();
this.rdd.exec("send", address, amount, comment, function(err, send) {
if(err) {
console.log(err);
future.return(err);
} else {
future.return(send);
}
});
return future.wait();
}
// reddcoind getblockcount
reddcoin.prototype.blockcount = function() {
var future = new Future();
this.rdd.exec("getblockcount", function(err, blockcount) {
if(err) {
console.log(err);
future.return(err);
} else {
future.return(blockcount);
}
});
return future.wait();
}
// reddcoind getblockhash [index]
reddcoin.prototype.blockhash = function(index) {
var future = new Future();
this.rdd.exec("getblockhash", index, function(err, hash) {
if(err) {
console.log(err);
future.return(err);
} else {
future.return(hash);
}
});
return future.wait();
}
// reddcoind getblock [hash]
reddcoin.prototype.block = function(hash) {
var future = new Future();
this.rdd.exec("getblock", hash, function(err, block) {
if(err) {
console.log(err);
future.return(err);
} else {
future.return(block);
}
});
return future.wait();
}
|
JavaScript
| 0.000002 |
@@ -3760,16 +3760,25 @@
ind send
+toaddress
to_addr
@@ -3916,16 +3916,25 @@
ec(%22send
+toaddress
%22, addre
@@ -5182,28 +5182,29 @@
%0A return future.wait();%0A%7D
+%0A
|
f8e11388481225fe10930ae05da94b149f485efa
|
Add CardForm alias for existing card fields
|
src/interface/button.js
|
src/interface/button.js
|
/* @flow */
import { isPayPalDomain } from '@paypal/sdk-client/src';
import { PopupOpenError as _PopupOpenError, destroy as zoidDestroy, destroyComponents } from 'zoid/src';
import type { LazyExport, LazyProtectedExport } from '../types';
import { allowIframe as _allowIframe } from '../lib';
import { getCheckoutComponent, type CheckoutComponent } from '../zoid/checkout';
import { getButtonsComponent, type ButtonsComponent } from '../zoid/buttons';
import { getCardFieldsComponent, type CardFieldsComponent } from '../zoid/card-fields';
import { getMenuComponent, type MenuComponent } from '../zoid/menu';
import { getInstallmentsComponent, type InstallmentsComponent } from '../zoid/installments';
import { Buttons as _ButtonsTemplate } from '../ui/buttons';
import { getQRCodeComponent, type QRCodeComponent } from '../zoid/qr-code';
import { getModalComponent, type ModalComponent } from '../zoid/modal/component';
function protectedExport<T>(xport : T) : ?T {
if (isPayPalDomain()) {
return xport;
}
}
export const Buttons : LazyExport<ButtonsComponent> = {
__get__: () => getButtonsComponent()
};
export const Checkout : LazyProtectedExport<CheckoutComponent> = {
__get__: () => protectedExport(getCheckoutComponent())
};
export const CardFields : LazyProtectedExport<CardFieldsComponent> = {
__get__: () => protectedExport(getCardFieldsComponent())
};
export const Menu : LazyProtectedExport<MenuComponent> = {
__get__: () => protectedExport(getMenuComponent())
};
export const Modal : LazyProtectedExport<ModalComponent> = {
__get__: () => protectedExport(getModalComponent())
};
export const Installments : LazyProtectedExport<InstallmentsComponent> = {
__get__: () => protectedExport(getInstallmentsComponent())
};
export const QRCode : LazyProtectedExport<QRCodeComponent> = {
__get__: () => protectedExport(getQRCodeComponent())
};
export const ButtonsTemplate : LazyProtectedExport<typeof _ButtonsTemplate> = {
__get__: () => protectedExport(_ButtonsTemplate)
};
export const PopupOpenError : LazyProtectedExport<typeof _PopupOpenError> = {
__get__: () => protectedExport(_PopupOpenError)
};
export const allowIframe : LazyProtectedExport<typeof _allowIframe> = {
__get__: () => protectedExport(_allowIframe)
};
export const forceIframe : LazyProtectedExport<typeof _allowIframe> = {
__get__: () => protectedExport(_allowIframe)
};
export const destroyAll : LazyProtectedExport<typeof destroyComponents> = {
__get__: () => protectedExport(destroyComponents)
};
export function setup() {
getButtonsComponent();
getCheckoutComponent();
}
export function destroy(err? : mixed) {
zoidDestroy(err);
}
|
JavaScript
| 0 |
@@ -1381,32 +1381,166 @@
omponent())%0A%7D;%0A%0A
+export const CardForm : LazyProtectedExport%3CCardFieldsComponent%3E = %7B%0A __get__: () =%3E protectedExport(getCardFieldsComponent())%0A%7D;%0A%0A
export const Men
|
6eeaa8c5b998fc2853f82c6fcf3a6a546ecc8425
|
Call getCheckoutComponent to register component in parent window
|
src/interface/button.js
|
src/interface/button.js
|
/* @flow */
import { isPayPalDomain } from '@paypal/sdk-client/src';
import { PopupOpenError as _PopupOpenError } from 'zoid/src';
import { setupLogger, allowIframe as _allowIframe } from '../lib';
import { getCheckoutComponent } from '../checkout';
import { getButtonsComponent } from '../buttons';
export const Buttons = getButtonsComponent();
export let Checkout;
export let PopupOpenError;
export let allowIframe;
if (isPayPalDomain()) {
Checkout = getCheckoutComponent();
PopupOpenError = _PopupOpenError;
allowIframe = _allowIframe;
}
export function setupButtons() {
setupLogger();
}
|
JavaScript
| 0 |
@@ -296,16 +296,67 @@
tons';%0A%0A
+const CheckoutComponent = getCheckoutComponent();%0A%0A
export c
@@ -501,27 +501,24 @@
Checkout =
-get
CheckoutComp
@@ -522,18 +522,16 @@
omponent
-()
;%0A Po
|
d5ea6dfe0579968d953d2e00744adc8b41f2be59
|
fix error with image-comp (doesn’t load image in full size)
|
src/core/cloudinary-url.js
|
src/core/cloudinary-url.js
|
// http://res.cloudinary.com/demo/image/upload/f_auto,q_auto,w_250,h_250,c_fit/sample.jpg
const defaultState = 'f_auto,q_auto,fl_lossy';
export default (url, { mode, maxWidth, effect, maxHeight, border, width, height, cropX, cropY, quality, blur, retina, crop: crop0 } = {}, crop) => {
if (!crop) crop = crop0;
if (!mode) mode = 'fill';
// RETINA
// if (retina && width) width *= 2; geht so nicht, da cloudinary einen Fehler wirft, wenn die angefragt Größe > als die tatsächlich ist
// if (retina && height) height *= 2;
if (retina && maxWidth && maxWidth * 2 < width) maxWidth *= 2;
if (retina && maxHeight && maxHeight * 2 < height) maxHeight *= 2;
if (!url) return url;
if (crop) {
width = crop[0];
height = crop[1];
cropX = crop[2];
cropY = crop[3];
}
if (url.indexOf('http://res.cloudinary.com/') === 0) {
url = url.split('ttp://res.cloudinary.com/').join('ttps://res.cloudinary.com/');
}
if (url.indexOf('https://res.cloudinary.com/') !== 0) return url;
let part = defaultState;
if (cropX !== undefined && cropY !== undefined) {
part = `x_${cropX},y_${cropY},w_${width},h_${height},c_crop/${part}`;
} else if (width && height) {
part = `w_${width},h_${height},c_${mode}/${part}`;
}
if (maxWidth || maxHeight) {
if (maxWidth) part += `,w_${maxWidth}`;
if (maxHeight) part += `,h_${maxHeight}`;
part += `,c_${mode}`;
}
if (quality) {
part += `,q_${quality}`;
}
if (blur) {
part += `,e_blur:${blur}`;
}
if (part === defaultState) {
part += ',q_75';
}
if (border) {
Object.keys(border).map((key) => {
part = `bo_${border[key]}px_solid_${key}/${part}`;
});
}
if (effect) {
part = `e_${effect}/${part}`;
}
return url.replace('/upload/', `/upload/${part}/`);
};
|
JavaScript
| 0 |
@@ -1182,32 +1182,35 @@
&& height) %7B%0A
+ //
part = %60w_$%7Bwid
@@ -1241,24 +1241,401 @@
%7D/$%7Bpart%7D%60;%0A
+ // beni, solltest du das hier %C3%A4ndern wollen, dann sag mir Bescheid. Mit dieser Zeile wird eine URL wie folgt erzeugt:%0A // https://res.cloudinary.com/dhsf4vjjc/image/upload/w_2896,h_1944,c_fill/f_auto,q_auto,fl_lossy,w_960,c_fill/v1490025279/p0xdfvo73u7pj6oudtf4.tiff%0A // d.h. die Bilder werden mit voller Dimension geladen, egal wie gro%C3%9F sie eigentlich sein sollten!%0A
%7D%0A%0A if (m
|
7621e0b9e81634a0d9764e57c50b37d32f484f89
|
Move `frame` clearing
|
src/internal/machine.js
|
src/internal/machine.js
|
// @flow
/**
* Machine: contains all mutable state.
* @module machine
*
* The machine should be in charge of managing the animation frames, but it
* doesn't know anything about what to do in those frames, that's up to the
* Animator.
*/
import type { VoidFn, Machine } from './flow-types'
// TODO: use utils
const noop: VoidFn = () => {};
/**
* Creates a machine that will continue to run until the caller tells it to stop.
*/
export const PerpetualMachineFactory = (
requestAnimationFrame: (fn: VoidFn) => void,
cancelAnimationFrame: (frame: number) => void,
) => (
onComplete?: VoidFn = noop,
onFrame?: VoidFn = noop,
): Machine => {
let frame: ?number = null;
let machineIsStopped: boolean = false;
const jobs: Array<VoidFn> = [];
const runIteration: VoidFn = () => {
if (machineIsStopped) return;
onFrame();
frame = requestAnimationFrame(() => {
jobs.forEach(job => job());
runIteration();
});
}
const machine: Machine = {
isStopped: () => machineIsStopped,
do: (job: VoidFn) => {
jobs.push(job);
return machine;
},
run: () => {
runIteration();
return machine;
},
stop: () => {
if (frame) {
cancelAnimationFrame(frame);
frame = null;
}
machineIsStopped = true;
onComplete();
}
};
return machine;
};
/**
* Creates a machine that will stop running after the specified duration.
*/
export const TimedMachineFactory = (
requestAnimationFrame: (fn: VoidFn) => void,
cancelAnimationFrame: (frame: number) => void,
) => (
duration: number,
onComplete?: VoidFn = noop,
onFrame?: VoidFn = noop,
): Machine => {
let startTime: number = 0;
const _onFrame: VoidFn = () => {
const elapsedTime: number = Date.now() - startTime;
onFrame();
if (elapsedTime >= duration) {
machine.stop();
}
}
const factory = PerpetualMachineFactory(requestAnimationFrame, cancelAnimationFrame);
const machine: Machine = factory(onComplete, _onFrame);
const _run = machine.run;
machine.run = () => {
startTime = Date.now();
return _run();
}
return machine;
};
|
JavaScript
| 0 |
@@ -1245,24 +1245,30 @@
e(frame);%0A
+ %7D%0A
frame
@@ -1275,24 +1275,16 @@
= null;%0A
- %7D%0A
ma
|
7b82f48f7d9cf40bdb0734f0ee2fa0c272d6f2e8
|
normalize ampcontext-lib (#6524)
|
build-system/tasks/size.js
|
build-system/tasks/size.js
|
/**
* Copyright 2015 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var del = require('del');
var fs = require('fs');
var gulp = require('gulp-help')(require('gulp'));
var gzipSize = require('gzip-size');
var prettyBytes = require('pretty-bytes');
var table = require('text-table');
var through = require('through2');
var util = require('gulp-util');
var tempFolderName = '__size-temp';
var MIN_FILE_SIZE_POS = 0;
var GZIP_POS = 1;
var FILENAME_POS = 2;
// normalized table headers
var tableHeaders = [
['max', 'min', 'gzip', 'file'],
['---', '---', '---', '---'],
];
var tableOptions = {
align: ['r', 'r', 'r', 'l'],
hsep: ' | ',
};
/**
* Returns a number greater than -1 if item is found within the array, else
* returns -1.
*
* @param {!Array<!Array>} rows
* @param {!fuction(string)} predicate
* @return {number}
*/
function findMaxIndexByFilename(rows, predicate) {
for (var i = 0; i < rows.length; i++) {
var curRow = rows[i];
var curFilename = curRow[FILENAME_POS];
if (predicate(curFilename)) {
return i;
}
}
return -1;
}
/**
* Mutates the rows in place and merges the minified file entry as well
* as its unminified file entry counterpart.
* @param {!Array<!Array>} rows
* @param {string} minFilename
* @param {string} maxFilename
* @param {boolean} mergeNames
*/
function normalizeRow(rows, minFilename, maxFilename, mergeNames) {
var minIndex = findMaxIndexByFilename(rows, function(filename) {
return filename == minFilename;
});
var maxIndex = findMaxIndexByFilename(rows, function(filename) {
return filename == maxFilename;
});
if (maxIndex != -1 && minIndex != -1) {
if (mergeNames) {
rows[minIndex][FILENAME_POS] += ' / ' + rows[maxIndex][FILENAME_POS];
}
rows[minIndex].unshift(rows[maxIndex][MIN_FILE_SIZE_POS]);
rows.splice(maxIndex, 1);
}
}
/**
* Call normalizeRow on the core file, integration file and all extensions.
* @param {!Array<!Array>} rows
* @return {!Array<!Array>}
*/
function normalizeRows(rows) {
// normalize amp.js
normalizeRow(rows, 'v0.js', 'amp.js', true);
// normalize integration.js
normalizeRow(rows, 'current-min/f.js', 'current/integration.js', true);
// normalize alp.js
normalizeRow(rows, 'alp.js', 'alp.max.js', true);
// normalize amp-shadow.js
normalizeRow(rows, 'shadow-v0.js', 'amp-shadow.js', true);
normalizeRow(rows, 'amp4ads-v0.js', 'amp-inabox.js', true);
normalizeRow(rows, 'amp4ads-host-v0.js', 'amp-inabox-host.js', true);
// normalize sw.js
normalizeRow(rows, 'sw.js', 'sw.max.js', true);
normalizeRow(rows, 'sw-kill.js', 'sw-kill.max.js', true);
// normalize extensions
var curName = null;
var i = rows.length;
// we are mutating in place... kind of icky but this will do fow now.
while (i--) {
curName = rows[i][FILENAME_POS];
if (/^v0/.test(curName)) {
normalizeExtension(rows, curName);
}
}
return rows;
}
/**
* Finds the counterpart entry of the extension file, wether it be
* the unminified or the minified counterpart.
* @param {!Array<!Array>} rows
* @param {string} filename
*/
function normalizeExtension(rows, filename) {
var isMax = /\.max\.js$/.test(filename);
var counterpartName = filename.replace(/(v0\/.*?)(\.max)?(\.js)$/,
function(full, grp1, grp2, grp3) {
if (isMax) {
return grp1 + grp3;
}
return full;
});
if (isMax) {
normalizeRow(rows, counterpartName, filename, false);
} else {
normalizeRow(rows, filename, counterpartName, false);
}
}
/**
* Through2 transform function - Tracks the original size and the gzipped size
* of the file content in the rows array. Passes the file and/or err to the
* callback when finished.
* @param {!Array<!Array<string>>} rows array to store content size information
* @param {!File} file File to process
* @param {string} enc Encoding (not used)
* @param {function(?Error, !File)} cb Callback function
*/
function onFileThrough(rows, file, enc, cb) {
if (file.isNull()) {
cb(null, file);
return;
}
if (file.isStream()) {
cb(new util.PluginError('size', 'Stream not supported'));
return;
}
rows.push([
prettyBytes(file.contents.length),
prettyBytes(gzipSize.sync(file.contents)),
file.relative,
]);
cb(null, file);
}
/**
* Through2 flush function - combines headers with the rows and generates
* a text-table of the content size information to log to the console and the
* test/size.txt logfile.
*
* @param {!Array<!Array<string>>} rows array of content size information
* @param {function()} cb Callback function
*/
function onFileThroughEnd(rows, cb) {
rows = normalizeRows(rows);
rows.unshift.apply(rows, tableHeaders);
var tbl = table(rows, tableOptions);
console/*OK*/.log(tbl);
fs.writeFileSync('test/size.txt', tbl);
cb();
}
/**
* Setup through2 to capture size information using the above transform and
* flush functions on a stream
* @return {!Stream} a Writable Stream
*/
function sizer() {
var rows = [];
return through.obj(
onFileThrough.bind(null, rows),
onFileThroughEnd.bind(null, rows)
);
}
/**
* Pipe the distributable js files through the sizer to get a record of
* the content size before and after gzip and cleanup any temporary file
* output from the process.
*/
function sizeTask() {
gulp.src([
'dist/**/*.js',
'!dist/**/*-latest.js',
'!dist/**/*check-types.js',
'dist.3p/{current,current-min}/**/*.js',
])
.pipe(sizer())
.pipe(gulp.dest(tempFolderName))
.on('end', del.bind(null, [tempFolderName]));
}
gulp.task('size', 'Runs a report on artifact size', sizeTask);
|
JavaScript
| 0 |
@@ -2763,32 +2763,129 @@
on.js', true);%0A%0A
+ normalizeRow(rows, 'current-min/ampcontext-lib.js',%0A 'current/ampcontext-lib.js', true);%0A%0A
// normalize a
|
55c0b66f8426b63c532b153357c016feb625fedb
|
Set install.js as main file
|
build/webpack.base.conf.js
|
build/webpack.base.conf.js
|
var path = require('path')
var fs = require('fs')
var utils = require('./utils')
var config = require('../config')
var vueLoaderConfig = require('./vue-loader.conf')
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
module.exports = {
entry: {
app: './src/main.js'
},
output: {
path: config.build.assetsRoot,
filename: '[name].js',
publicPath: process.env.NODE_ENV === 'production'
? config.build.assetsPublicPath
: config.dev.assetsPublicPath
},
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'@': resolve('src'),
},
symlinks: false
},
module: {
rules: [
{
test: /\.(js|vue)$/,
loader: 'eslint-loader',
enforce: 'pre',
include: [resolve('src'), resolve('test')],
options: {
formatter: require('eslint-friendly-formatter')
}
},
{
test: /\.vue$/,
loader: 'vue-loader',
options: vueLoaderConfig
},
{
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('test')]
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
{
test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('media/[name].[hash:7].[ext]')
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
}
]
}
}
|
JavaScript
| 0 |
@@ -267,11 +267,14 @@
-app
+plugin
: '.
@@ -282,12 +282,15 @@
src/
-ma
in
+stall
.js'
|
7ba7cacf163f4a525d8bc5588414218b150164a4
|
Make location thumbnails large and clickable
|
client/components/Location/Thumbnail/index.js
|
client/components/Location/Thumbnail/index.js
|
// A list of images from entries.
var Thumbnail = require('georap-components').Thumbnail;
var ThumbnailForm = require('./Form');
var template = require('./template.ejs');
var models = require('tresdb-models');
var rootBus = require('tresdb-bus');
var ui = require('tresdb-ui');
module.exports = function (location, entries) {
// Parameters:
// location: plain location object
// entries: an array of entry objects
//
var $mount = null;
var $elems = {};
var children = {}; // id -> thumbnailView
var bus = models.location.bus(location, rootBus);
var self = this;
self.bind = function ($mountEl) {
$mount = $mountEl;
$mount.html(template());
$elems.thumbnail = $mount.find('.location-thumbnail');
$elems.open = $mount.find('.location-thumbnail-open');
bus.on('location_entry_created', function (ev) {
models.entries.forward(entries, ev);
models.location.forward(location, ev);
self.update();
});
bus.on('location_entry_changed', function (ev) {
models.entries.forward(entries, ev);
models.location.forward(location, ev);
self.update();
});
bus.on('location_entry_removed', function (ev) {
models.entries.forward(entries, ev);
models.location.forward(location, ev);
self.update();
});
bus.on('location_thumbnail_changed', function (ev) {
models.location.forward(location, ev);
self.update();
});
// Setup form
$elems.open.click(function () {
if (children.form) {
children.form.unbind();
children.form.off('exit');
children.form.off('success');
delete children.form;
} else {
var atts = models.entries.getAttachments(entries);
var imgs = models.attachments.getImages(atts);
var locId = location._id;
children.form = new ThumbnailForm(locId, location.thumbnail, imgs);
children.form.bind($mount.find('.location-thumbnail-form-container'));
children.form.once('exit', function () {
children.form.unbind();
children.form.off('success');
delete children.form;
});
children.form.once('success', function () {
children.form.unbind();
children.form.off('exit');
delete children.form;
});
}
});
// Initial update
self.update();
};
self.update = function () {
// Update according to current number of available image attachments.
if ($mount) {
// var images = models.entries.getImages(entries);
// Hide if no thumbnails to show
if (location.thumbnail) {
ui.show($mount);
if (children.thumbnail) {
children.thumbnail.update(location.thumbnail);
} else {
children.thumbnail = new Thumbnail(location.thumbnail);
children.thumbnail.bind($elems.thumbnail);
}
} else {
ui.hide($mount);
if (location.thumbnail) {
children.thumbnail.unbind();
delete children.thumbnail;
}
}
}
};
self.unbind = function () {
if ($mount) {
bus.off();
// Unbind each child
ui.unbindAll(children);
children = {};
ui.offAll($elems);
$elems = {};
$mount.empty();
$mount = null;
}
};
};
|
JavaScript
| 0.000062 |
@@ -2806,32 +2806,99 @@
cation.thumbnail
+, %7B%0A size: 'xl',%0A makeLink: true,%0A %7D
);%0A chi
|
36fda00494fd30914dcf0acb1f6cb90de566c24e
|
clean up last checkin
|
BreezeCRM/Scripts/app/controllers.js
|
BreezeCRM/Scripts/app/controllers.js
|
'use strict';
angular.module('crmApp.controllers', [])
.controller('CustomerListController', ['$scope', '$location', 'custDataService', function ($scope, $location, custDataService) {
$scope.search = function () {
debugger;
custDataService.getAllCustomers($scope.criteria, $scope.sortOption, $scope.currentPage)
.then(function (data) {
debugger;
$scope.customers = data.results;
$scope.totalItems = data.inlineCount;
$scope.totalPages = data.inlineCount / 5;
})
.catch(function (error) {
console.log('Error calling api: ' + error.message);
});
};
$scope.search(null, 'companyName', 1);
//$scope.$watchCollection('customers', function (newValue) {
// setPagination(newValue);
//});
//function setPagination(newValue) {
// if (!newValue) {
// return;
// }
// $scope.totalItems = newValue.length;
// $scope.currentPage = 1;
// $scope.maxSize = 5;
//}
$scope.setPage = function (pageNo) {
$scope.currentPage = pageNo;
$scope.search();
};
$scope.markForDelete = function (customer) {
custDataService.deleteCustomer(customer, false);
};
$scope.edit = function (id) {
location.href = '#/customer/' + id + '/edit/';
};
$scope.saveChanges = function () {
custDataService.saveChanges();
};
}]).controller('EditCustomerController', ['$scope', '$location', '$routeParams', 'custDataService', function ($scope, $location, $routeParams, custDataService) {
custDataService.getCustomerById($routeParams.customerId)
.then(function (data) {
$scope.customer = data.entity;
}).catch(function (error) {
console.log('Error calling api: ' + error.message);
});
$scope.cancel = function () {
$scope.customer.entityAspect.rejectChanges(); //undo pending changes and reset entityState to 'Unchanged'
$location.path('/');
};
$scope.delete = function () {
custDataService.deleteCustomer($scope.customer, true);
$location.path('/');
};
$scope.canDelete = true;
$scope.save = function () {
custDataService.saveChanges();
$location.path('/');
};
}]).controller('CreateCustomerController', ['$scope', '$location', 'custDataService', function ($scope, $location, custDataService) {
$scope.cancel = function () {
$location.path('/');
};
var customer = custDataService.newCustomer({ customerID: 'TEMP' }); //TEMP is a HACK - Can't create entity w/o ID and 'AutoGeneratedKeyType' is none
customer.customerID = '';
$scope.customer = customer;
$scope.save = function () {
custDataService.saveChanges();
$location.path('/');
};
}]);
|
JavaScript
| 0 |
@@ -227,38 +227,16 @@
on () %7B%0A
- debugger;%0A
@@ -749,411 +749,10 @@
rch(
-null, 'companyName', 1);%0A%0A //$scope.$watchCollection('customers', function (newValue) %7B%0A // setPagination(newValue);%0A //%7D);%0A%0A //function setPagination(newValue) %7B%0A // if (!newValue) %7B%0A // return;%0A // %7D%0A%0A // $scope.totalItems = newValue.length;%0A // $scope.currentPage = 1;%0A // $scope.maxSize = 5;%0A%0A //%7D
+);
%0A%0A
|
e7ae7996da9f9c4383b297dd7de964f27976ed07
|
set location instead of reload to avoid post page again.
|
src/Modules/UI/Dnn.EditBar.UI/editBar/scripts/ExitEditMode.js
|
src/Modules/UI/Dnn.EditBar.UI/editBar/scripts/ExitEditMode.js
|
define(['jquery'], function ($) {
'use strict';
var menuItem, util;
var init = function (menu, utility, params, callback) {
menuItem = menu;
util = utility;
if (typeof callback === 'function') {
callback();
}
};
var onClick = function () {
var mode = "View";
util.sf.moduleRoot = 'internalservices';
util.sf.controller = "controlBar";
util.sf.post('ToggleUserMode', { UserMode: mode }, function handleToggleUserMode() {
window.parent.location.reload();
});
}
return {
init: init,
onClick: onClick
};
});
|
JavaScript
| 0 |
@@ -537,14 +537,38 @@
dow.
-parent
+top.location.href = window.top
.loc
@@ -577,16 +577,12 @@
ion.
+h
re
-load()
+f
;%0A
|
403db9112865994d1aedde036c2358d014dfdeb2
|
Fix up template
|
src/directives/df-model.js
|
src/directives/df-model.js
|
angular.module('dynamicForms').directive('dfModel', function($compile, $templateCache, DfSchemaService) {
return {
restrict: 'EA',
priority: 1100,
compile: function(element, attrs) {
element.removeAttr('df-model');
var columns = DfSchemaService.extractColumns(attrs.dfSchema),
mode = attrs.mode;
var template = $templateCache.get('dynamic-forms/templates/column.html');
_.each(columns, function(it) {
element.append( $templateCache.get(it.template) || _.template(template)({column: it.column, layout: mode === 'summary' ? 'form' : 'form'}) );
});
}
}
});
|
JavaScript
| 0.000013 |
@@ -420,22 +420,8 @@
et('
-dynamic-forms/
temp
|
6479703ac413ab21f021583a002d8abbab8f9dff
|
remove comments
|
www/iroot.js
|
www/iroot.js
|
var exec = require('cordova/exec');
var IRoot = function () {
this.name = "IRoot";
};
IRoot.prototype.isRooted = function (successCallback, failureCallback) {
exec(successCallback, failureCallback, "iRoot", "isRooted", []);
};
module.exports = new IRoot();
// cordova.exec(
// function(winParam) {},
// function(error) {},
// "service",
// "action",
// ["arguments..."]
// );
|
JavaScript
| 0 |
@@ -265,144 +265,4 @@
();%0A
-%0A// cordova.exec(%0A// function(winParam) %7B%7D,%0A// function(error) %7B%7D,%0A// %22service%22,%0A// %22action%22,%0A// %5B%22arguments...%22%5D%0A// );%0A
|
19af479841186d2fcbda8e76a3a97066451b0c8d
|
Fix external links not always updated
|
src/external_links_menu.js
|
src/external_links_menu.js
|
(function(){
var menuClass = 'smi-external-links-menu';
var externalLinks = [{
title: 'steemd.com',
href: function(username) {
return 'https://steemd.com/@' + username;
}
}, {
title: 'SteemTracked',
href: function(username) {
return 'https://steemtracked.com/@' + username;
}
}, {
title: 'Followers graph',
href: function(username) {
return 'https://steem.makerwannabe.com/@' + username + '/followers/4';
}
}];
var createMenuLinks = function(username) {
return externalLinks.map(function(link){
return '<li>\
<a href="' + link.href(username) + '" target="_blank">' + link.title + '</a>\
</li>';
}).join('');
};
var createMenu = function(username) {
var menu = $('<li class="' + menuClass + '">\
<a class="smi-open-menu" aria-haspopup="true">\
Links\
<span class="Icon dropdown-arrow" style="display: inline-block; width: 1.12rem; height: 1.12rem;">\
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 512 512" enable-background="new 0 0 512 512" xml:space="preserve"><g><polygon points="128,90 256,218 384,90"></polygon></g></svg>\
</span>\
</a>\
<div class="dropdown-pane">\
<ul class="VerticalMenu menu vertical">' +
createMenuLinks(username) +
'</ul>\
</div>\
</li>');
return menu;
};
var addExternalLinksMenu = function() {
var name = window.SteemMoreInfo.Utils.getPageAccountName();
if(!name){
return;
}
console.log('Adding external links menu: ' + name);
window.SteemMoreInfo.Utils.getUserTopMenusForAccountName(name, function(menus){
var menu = menus.eq(1); // second menu
var el = menu.find('li.' + menuClass);
if(!el.length){
el = createMenu(name);
el.find('a.smi-open-menu').on('click', function(e) {
e.preventDefault();
el.find('.dropdown-pane').addClass('is-open');
});
menu.prepend(el);
}
});
};
window.SteemMoreInfo.Events.addEventListener(window, 'page-account-name', function() {
addExternalLinksMenu();
});
addExternalLinksMenu();
$('body').on('click', function(e) {
var t = $(e.target);
if(!t.closest('.' + menuClass).length){
$('.' + menuClass + ' .dropdown-pane').removeClass('is-open');
}
});
})();
|
JavaScript
| 0 |
@@ -93,17 +93,17 @@
title: '
-s
+S
teemd.co
@@ -339,16 +339,22 @@
title: '
+Steem
Follower
@@ -358,14 +358,8 @@
wers
- graph
',%0A
@@ -1859,17 +1859,16 @@
if(
-!
el.lengt
@@ -1869,24 +1869,51 @@
.length)%7B%0A
+ el.remove();%0A %7D%0A
el = c
@@ -1931,26 +1931,24 @@
ame);%0A
-
-
el.find('a.s
@@ -1988,18 +1988,16 @@
on(e) %7B%0A
-
@@ -2020,26 +2020,24 @@
();%0A
-
el.find('.dr
@@ -2077,24 +2077,20 @@
;%0A
-
-
%7D);%0A
-
me
@@ -2105,24 +2105,16 @@
nd(el);%0A
- %7D%0A
%7D);%0A
|
13b7b35f2f14e3afd4b657dd9ef1a017ac3979c5
|
Allow stream to auto-resize (redo)
|
src/flash/net/URLStream.js
|
src/flash/net/URLStream.js
|
/* -*- Mode: js; js-indent-level: 2; indent-tabs-mode: nil; tab-width: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/*
* Copyright 2013 Mozilla Foundation
*
* 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 URLStreamDefinition = (function () {
var def = {
initialize: function () {
this._stream = null;
this._connected = false;
this._littleEndian = false;
},
close: function close() {
this._session.close();
},
load: function load(request) {
var session = FileLoadingService.createSession();
var self = this;
var initStream = true;
session.onprogress = function (data, progressState) {
if (initStream) {
initStream = false;
var length = Math.max(progressState.bytesTotal, data.length);
var buffer = new ArrayBuffer(length);
self._stream = new Stream(buffer, 0, 0, length);
} else if (self._stream.pos + data.length > self._stream.end) {
var length = self._stream.pos + data.length;
var buffer = new ArrayBuffer(length);
newStream = new Stream(buffer, 0, 0, length);
newStream.push(self._stream.bytes.subarray(0, self._stream.pos));
self._stream = newStream;
}
self._stream.push(data);
var ProgressEventClass = avm2.systemDomain.getClass("flash.events.ProgressEvent");
self.dispatchEvent(ProgressEventClass.createInstance(["progress",
false, false, progressState.bytesLoaded, progressState.bytesTotal]));
};
session.onerror = function (error) {
self._connected = false;
self.dispatchEvent(new flash.events.IOErrorEvent(flash.events.IOErrorEvent.IO_ERROR, false, false, error));
};
session.onopen = function () {
self._connected = true;
self.dispatchEvent(new flash.events.Event("open", false, false));
};
session.onhttpstatus = function (location, httpStatus, httpHeaders) {
var HTTPStatusEventClass = avm2.systemDomain.getClass("flash.events.HTTPStatusEvent");
var URLRequestHeaderClass = avm2.systemDomain.getClass("flash.net.URLRequestHeader");
var httpStatusEvent = HTTPStatusEventClass.createInstance([
'httpStatus', false, false, httpStatus]);
var headers = [];
httpHeaders.split(/\r\n/g).forEach(function (h) {
var m = /^([^:]+): (.*)$/.exec(h);
if (m) {
headers.push(URLRequestHeaderClass.createInstance([m[1], m[2]]));
if (m[1] === 'Location') { // Headers have redirect location
location = m[2];
}
}
});
httpStatusEvent.public$responseHeaders = headers;
httpStatusEvent.public$responseURL = location;
self.dispatchEvent(httpStatusEvent);
};
session.onclose = function () {
self._connected = false;
if (!self._stream) {
// We need to have something to return in data
var buffer = new ArrayBuffer(0);
self._stream = new Stream(buffer, 0, 0, 0);
}
self.dispatchEvent(new flash.events.Event("complete", false, false))
};
session.open(request._toFileRequest());
this._session = session;
},
readBoolean: function readBoolean() {
throw 'Not implemented: URLStream.readBoolean';
},
readByte: function readByte() {
var stream = this._stream;
stream.ensure(1);
return stream.bytes[stream.pos++];
},
readBytes: function readBytes(bytes, offset, length) {
if (length < 0)
throw 'Invalid length argument';
var stream = this._stream;
if (!length)
length = stream.remaining();
else
stream.ensure(length);
bytes.writeRawBytes(stream.bytes.subarray(stream.pos,
stream.pos + length), offset, length);
stream.pos += length;
},
readDouble: function readDouble() {
throw 'Not implemented: URLStream.readDouble';
},
readFloat: function readFloat() {
throw 'Not implemented: URLStream.readFloat';
},
readInt: function readInt() {
throw 'Not implemented: URLStream.readInt';
},
readMultiByte: function readMultiByte(length, charSet) {
throw 'Not implemented: URLStream.readMultiByte';
},
readObject: function readObject() {
throw 'Not implemented: URLStream.readObject';
},
readShort: function readShort() {
throw 'Not implemented: URLStream.readShort';
},
readUTF: function readUTF() {
throw 'Not implemented: URLStream.readUTF';
},
readUTFBytes: function readUTFBytes(length) {
throw 'Not implemented: URLStream.readUTFBytes';
},
readUnsignedByte: function readUnsignedByte() {
throw 'Not implemented: URLStream.readUnsignedByte';
},
readUnsignedInt: function readUnsignedInt() {
throw 'Not implemented: URLStream.readUnsignedInt';
},
readUnsignedShort: function readUnsignedShort() {
var stream = this._stream;
stream.ensure(2);
var result = stream.getUint16(stream.pos, this._littleEndian);
stream.pos += 2;
return result;
},
get bytesAvailable() {
return this._stream.remaining();
},
get connected() {
return this._connected;
},
get endian() {
return this._littleEndian ? 'littleEndian' : 'bigEndian';
},
set endian(val) {
this._littleEndian = (val == 'littleEndian');
},
get objectEncoding() {
throw 'Not implemented: URLStream.objectEncoding$get';
},
set objectEncoding(val) {
throw 'Not implemented: URLStream.objectEncoding$set';
}
};
var desc = Object.getOwnPropertyDescriptor;
def.__glue__ = {
native: {
instance: {
close: def.close,
load: def.load,
readBoolean: def.readBoolean,
readByte: def.readByte,
readBytes: def.readBytes,
readDouble: def.readDouble,
readFloat: def.readFloat,
readInt: def.readInt,
readMultiByte: def.readMultiByte,
readObject: def.readObject,
readShort: def.readShort,
readUTF: def.readUTF,
readUTFBytes: def.readUTFBytes,
readUnsignedByte: def.readUnsignedByte,
readUnsignedInt: def.readUnsignedInt,
readUnsignedShort: def.readUnsignedShort,
bytesAvailable: desc(def, 'bytesAvailable'),
connected: desc(def, 'connected'),
endian: desc(def, 'endian'),
objectEncoding: desc(def, 'objectEncoding')
}
}
};
return def;
}).call(this);
|
JavaScript
| 0 |
@@ -1457,35 +1457,35 @@
f (self._stream.
-pos
+end
+ data.length %3E
@@ -1498,19 +1498,28 @@
_stream.
-end
+bytes.length
) %7B%0A
@@ -1550,19 +1550,19 @@
_stream.
-pos
+end
+ data.
@@ -1742,19 +1742,19 @@
_stream.
-pos
+end
));%0A
|
695e2719f51949c26d3f74cec982cf19796388f3
|
use shared storage for logout as well
|
packages/@uppy/companion-client/src/Provider.js
|
packages/@uppy/companion-client/src/Provider.js
|
'use strict'
const RequestClient = require('./RequestClient')
const _getName = (id) => {
return id.split('-').map((s) => s.charAt(0).toUpperCase() + s.slice(1)).join(' ')
}
module.exports = class Provider extends RequestClient {
constructor (uppy, opts) {
super(uppy, opts)
this.provider = opts.provider
this.id = this.provider
this.authProvider = opts.authProvider || this.provider
this.name = this.opts.name || _getName(this.id)
this.pluginId = this.opts.pluginId
this.tokenKey = `companion-${this.pluginId}-auth-token`
}
get defaultHeaders () {
return Object.assign({}, super.defaultHeaders, {'uppy-auth-token': this.getAuthToken()})
}
// @todo(i.olarewaju) consider whether or not this method should be exposed
setAuthToken (token) {
// @todo(i.olarewaju) add fallback for OOM storage
this.uppy.getPlugin(this.pluginId).storage.setItem(this.tokenKey, token)
}
getAuthToken () {
return this.uppy.getPlugin(this.pluginId).storage.getItem(this.tokenKey)
}
checkAuth () {
return this.get(`${this.id}/authorized`)
.then((payload) => {
return payload.authenticated
})
}
authUrl () {
return `${this.hostname}/${this.id}/connect`
}
fileUrl (id) {
return `${this.hostname}/${this.id}/get/${id}`
}
list (directory) {
return this.get(`${this.id}/list/${directory || ''}`)
}
logout (redirect = location.href) {
return this.get(`${this.id}/logout?redirect=${redirect}`)
.then((res) => {
this.storage.removeItem(this.tokenKey)
return res
})
}
static initPlugin (plugin, opts, defaultOpts) {
plugin.type = 'acquirer'
plugin.files = []
if (defaultOpts) {
plugin.opts = Object.assign({}, defaultOpts, opts)
}
if (opts.serverPattern) {
const pattern = opts.serverPattern
// validate serverPattern param
if (typeof pattern !== 'string' && !Array.isArray(pattern) && !(pattern instanceof RegExp)) {
throw new TypeError(`${plugin.id}: the option "serverPattern" must be one of string, Array, RegExp`)
}
plugin.opts.serverPattern = pattern
} else {
// does not start with https://
if (/^(?!https?:\/\/).*$/.test(opts.serverUrl)) {
plugin.opts.serverPattern = `${location.protocol}//${opts.serverUrl.replace(/^\/\//, '')}`
} else {
plugin.opts.serverPattern = opts.serverUrl
}
}
plugin.storage = plugin.opts.storage || localStorage
}
}
|
JavaScript
| 0 |
@@ -1523,16 +1523,46 @@
this.
+uppy.getPlugin(this.pluginId).
storage.
|
e9446e379ce9a3155921fb07e4c355741913a027
|
Add also check for attr
|
src/js/forms-handler.js
|
src/js/forms-handler.js
|
/*===============================================================================
************ Store and parse forms data ************
===============================================================================*/
app.formsData = {};
app.formStoreData = function (formId, formJSON) {
// Store form data in app.formsData
app.formsData[formId] = formJSON;
// Store form data in local storage also
app.ls['f7form-' + formId] = JSON.stringify(formJSON);
};
app.formDeleteData = function (formId) {
// Delete form data from app.formsData
if (app.formsData[formId]) {
app.formsData[formId] = '';
delete app.formsData[formId];
}
// Delete form data from local storage also
if (app.ls['f7form-' + formId]) {
app.ls['f7form-' + formId] = '';
app.ls.removeItem('f7form-' + formId);
}
};
app.formGetData = function (formId) {
// First of all check in local storage
if (app.ls['f7form-' + formId]) {
return JSON.parse(app.ls['f7form-' + formId]);
}
// Try to get it from formsData obj
else if (app.formsData[formId]) return app.formsData[formId];
};
app.formToJSON = function (form) {
form = $(form);
if (form.length !== 1) return false;
// Form data
var formData = {};
// Skip input types
var skipTypes = ['submit', 'image', 'button', 'file'];
var skipNames = [];
form.find('input, select, textarea').each(function () {
var input = $(this);
var name = input.attr('name');
var type = input.attr('type');
var tag = this.nodeName.toLowerCase();
if (skipTypes.indexOf(type) >= 0) return;
if (skipNames.indexOf(name) >= 0 || !name) return;
if (tag === 'select' && input.attr('multiple')) {
skipNames.push(name);
formData[name] = [];
form.find('select[name="' + name + '"] option').each(function () {
if (this.selected) formData[name].push(this.value);
});
}
else {
switch (type) {
case 'checkbox' :
skipNames.push(name);
formData[name] = [];
form.find('input[name="' + name + '"]').each(function () {
if (this.checked) formData[name].push(this.value);
});
break;
case 'radio' :
skipNames.push(name);
form.find('input[name="' + name + '"]').each(function () {
if (this.checked) formData[name] = this.value;
});
break;
default :
formData[name] = input.val();
break;
}
}
});
form.trigger('formToJSON', {formData: formData});
return formData;
};
app.formFromJSON = function (form, formData) {
form = $(form);
if (form.length !== 1) return false;
// Skip input types
var skipTypes = ['submit', 'image', 'button', 'file'];
var skipNames = [];
form.find('input, select, textarea').each(function () {
var input = $(this);
var name = input.attr('name');
var type = input.attr('type');
var tag = this.nodeName.toLowerCase();
if (!formData[name]) return;
if (skipTypes.indexOf(type) >= 0) return;
if (skipNames.indexOf(name) >= 0 || !name) return;
if (tag === 'select' && input.attr('multiple')) {
skipNames.push(name);
form.find('select[name="' + name + '"] option').each(function () {
if (formData[name].indexOf(this.value) >= 0) this.selected = true;
else this.selected = false;
});
}
else {
switch (type) {
case 'checkbox' :
skipNames.push(name);
form.find('input[name="' + name + '"]').each(function () {
if (formData[name].indexOf(this.value) >= 0) this.checked = true;
else this.checked = false;
});
break;
case 'radio' :
skipNames.push(name);
form.find('input[name="' + name + '"]').each(function () {
if (formData[name] === this.value) this.checked = true;
else this.checked = false;
});
break;
default :
input.val(formData[name]);
break;
}
}
});
form.trigger('formFromJSON', {formData: formData});
};
app.initFormsStorage = function (pageContainer) {
pageContainer = $(pageContainer);
if (pageContainer.length === 0) return;
var forms = pageContainer.find('form.store-data');
if (forms.length === 0) return;
// Parse forms data and fill form if there is such data
forms.each(function () {
var id = this.getAttribute('id');
if (!id) return;
var formData = app.formGetData(id);
if (formData) app.formFromJSON(this, formData);
});
// Update forms data on inputs change
function storeForm() {
/*jshint validthis:true */
var form = $(this);
var formId = form[0].id;
if (!formId) return;
var formJSON = app.formToJSON(form);
if (!formJSON) return;
app.formStoreData(formId, formJSON);
form.trigger('store', {data: formJSON});
}
forms.on('change submit', storeForm);
// Detach Listeners
function pageBeforeRemove() {
forms.off('change submit', storeForm);
pageContainer.off('pageBeforeRemove', pageBeforeRemove);
}
pageContainer.on('pageBeforeRemove', pageBeforeRemove);
};
// Ajax submit on forms
$(document).on('submit change', 'form.ajax-submit, form.ajax-submit-onchange', function (e) {
var form = $(this);
if (e.type === 'change' && !form.hasClass('ajax-submit-onchange')) return;
if (e.type === 'submit') e.preventDefault();
var method = form.attr('method') || 'GET';
var contentType = form.prop('enctype');
var url = form.attr('action');
if (!url) return;
var data;
if (method === 'POST') data = new FormData(form[0]);
else data = $.serializeObject(app.formToJSON(form[0]));
var xhr = $.ajax({
method: method,
url: url,
contentType: contentType,
data: data,
beforeSend: function (xhr) {
form.trigger('beforeSubmit', {data:data, xhr: xhr});
},
error: function (xhr) {
form.trigger('submitError', {data:data, xhr: xhr});
},
success: function (data) {
form.trigger('submitted', {data: data, xhr: xhr});
}
});
});
|
JavaScript
| 0 |
@@ -6211,16 +6211,40 @@
nctype')
+ %7C%7C form.attr('enctype')
;%0A%0A v
|
a2ca517a86a8302a0d777846a4688f78ef1df1f7
|
add spinner to update app update
|
src/front/screens/About.js
|
src/front/screens/About.js
|
import { useFocusEffect } from '@react-navigation/native';
import { Button, Divider, Layout, Text } from '@ui-kitten/components';
import Constants from 'expo-constants';
import { brand, modelName, osVersion } from 'expo-device';
import { channel, checkForUpdateAsync, fetchUpdateAsync, reloadAsync } from 'expo-updates';
import { useState } from 'react';
import { Alert, ScrollView, StyleSheet, View } from 'react-native';
import 'yup-phone';
import Spinner from '../components/Spinner';
import ValueContainer from '../components/ValueContainer';
import { clearBaseMapCache, getBaseMapCacheSize } from '../services/offline';
import { PADDING } from '../services/styles';
async function forceUpdate() {
const updateCheckResult = await checkForUpdateAsync();
if (updateCheckResult.isAvailable) {
await fetchUpdateAsync();
await reloadAsync();
} else {
Alert.alert('No update available', 'You are already running the latest version of the app.');
}
}
export default function AppInfoScreen() {
const [isLoading, setIsLoading] = useState(false);
const [cacheSize, setCacheSize] = useState('calculating...');
useFocusEffect(() => {
const getSize = async () => {
const size = await getBaseMapCacheSize();
setCacheSize(size);
};
getSize();
});
const handleClearCache = async () => {
setIsLoading(true);
await clearBaseMapCache();
setCacheSize(await getBaseMapCacheSize());
setIsLoading(false);
};
return (
<Layout style={styles.container}>
<ScrollView style={styles.container}>
<Text style={styles.paragraph} category="p1">
The Utah Wildlife-Vehicle Collision Reporter app (WVCR) is a smartphone-based system for reporting animals
that have been involved in vehicle collisions. Data collected from this app will allow UDWR and UDOT to reduce
wildlife-vehicle collisions and make highways safer for drivers and wildlife.
</Text>
<Text category="h5" style={styles.header}>
App
</Text>
<Divider />
<ValueContainer label="Application Version" value={Constants.manifest2.extra.expoClient.version} />
<ValueContainer label="Runtime Version" value={Constants.manifest2.runtimeVersion} />
<ValueContainer label="Build Number" value={Constants.manifest2.extra.expoClient.ios.buildNumber} />
<ValueContainer label="Release Channel" value={channel || 'dev'} />
<View style={styles.buttonContainer}>
<Button onPress={forceUpdate}>Force App Update</Button>
</View>
<Text category="h5" style={styles.header}>
Device
</Text>
<Divider />
<ValueContainer label="Brand" value={brand} />
<ValueContainer label="Model" value={modelName} />
<ValueContainer label="OS Version" value={osVersion} />
<Text category="h5" style={styles.header}>
Offline Base Map Cache
</Text>
<Divider />
<ValueContainer label="Size" value={cacheSize} />
<View style={styles.buttonContainer}>
<Button onPress={handleClearCache}>Clear Cache</Button>
</View>
</ScrollView>
<Spinner show={isLoading} message={'Deleting cache files...'} />
</Layout>
);
}
const styles = StyleSheet.create({
container: { flex: 1 },
header: {
margin: PADDING,
marginTop: PADDING * 2,
},
buttonContainer: {
padding: PADDING,
paddingTop: PADDING * 2,
},
paragraph: {
paddingHorizontal: PADDING,
paddingTop: PADDING,
textAlign: 'justify',
},
});
|
JavaScript
| 0.000001 |
@@ -669,39 +669,442 @@
';%0A%0A
-async function forceUpdate() %7B%0A
+const deleteCacheMessage = 'Deleting cache files...';%0Aconst updateMessage = 'Checking for updates...';%0Aexport default function AppInfoScreen() %7B%0A const %5BloaderMessage, setLoaderMessage%5D = useState(null);%0A const %5BcacheSize, setCacheSize%5D = useState('calculating...');%0A%0A async function forceUpdate() %7B%0A setLoaderMessage(updateMessage);%0A%0A if (__DEV__) %7B%0A Alert.alert('Cannot update in development mode.');%0A %7D else %7B%0A
co
@@ -1156,16 +1156,20 @@
sync();%0A
+
if (up
@@ -1195,24 +1195,28 @@
vailable) %7B%0A
+
await fe
@@ -1233,24 +1233,28 @@
sync();%0A
+
+
await reload
@@ -1262,16 +1262,20 @@
sync();%0A
+
%7D else
@@ -1273,24 +1273,28 @@
%7D else %7B%0A
+
Alert.al
@@ -1385,171 +1385,52 @@
;%0A
-%7D%0A%7D%0A%0Aexport default function AppInfoScreen() %7B%0A const %5BisLoading,
+ %7D%0A %7D%0A%0A
set
-Is
Load
-ing%5D = useState(false);%0A const %5BcacheSize, setCacheSize%5D = useState('calculating...');
+erMessage(null);%0A %7D
%0A%0A
@@ -1641,21 +1641,39 @@
set
-Is
Load
-ing(tru
+erMessage(deleteCacheMessag
e);%0A
@@ -1762,23 +1762,26 @@
set
-Is
Load
-ing(false
+erMessage(null
);%0A
@@ -3526,53 +3526,47 @@
ow=%7B
-isLoading%7D message=%7B'Deleting cache files...'
+!!loaderMessage%7D message=%7BloaderMessage
%7D /%3E
|
6da73f42b2931a89daf72920e08982ea0878df29
|
fix compatibility with IE (#1796)
|
docs/app/Components/ComponentDoc/ComponentProps.js
|
docs/app/Components/ComponentDoc/ComponentProps.js
|
import _ from 'lodash'
import PropTypes from 'prop-types'
import React, { Component } from 'react'
import { Header, Icon, Popup, Table } from 'src'
const extraDescriptionStyle = {
color: '#666',
}
const extraDescriptionContentStyle = {
marginLeft: '0.5em',
}
const Extra = ({ title, children, inline, ...rest }) => (
<div {...rest} style={extraDescriptionStyle}>
<strong>{title}</strong>
<div style={{ ...extraDescriptionContentStyle, display: inline ? 'inline' : 'block' }}>
{children}
</div>
</div>
)
Extra.propTypes = {
children: PropTypes.node,
inline: PropTypes.bool,
title: PropTypes.node,
}
const getTagType = tag => tag.type.type === 'AllLiteral' ? 'any' : tag.type.name
/**
* Displays a table of a Component's PropTypes.
*/
export default class ComponentProps extends Component {
static propTypes = {
/**
* A single Component's prop info as generated by react-docgen.
* @type {object} Props info object where keys are prop names and values are prop definitions.
*/
props: PropTypes.object,
/**
* A single Component's meta info.
* @type {object} Meta info object where enum prop values are defined.
*/
meta: PropTypes.object,
}
state = {
showEnumsFor: {},
}
toggleEnumsFor = (prop) => () => {
this.setState({
showEnumsFor: {
...this.state.showEnumsFor,
[prop]: !this.state.showEnumsFor[prop],
},
})
}
renderName = item => <code>{item.name}</code>
renderRequired = item => item.required && (
<Popup
position='right center'
style={{ padding: '0.5em' }}
trigger={<Icon size='small' color='red' name='asterisk' />}
content='Required'
size='tiny'
inverted
/>
)
renderDefaultValue = item => {
const defaultValue = _.get(item, 'defaultValue.value')
if (_.isNil(defaultValue)) return null
return <code>{defaultValue}</code>
}
renderFunctionSignature = (item) => {
const params = _.filter(item.tags, { title: 'param' })
const returns = _.find(item.tags, { title: 'returns' })
// this doesn't look like a function propType doc block
// don't try to render a signature
if (_.isEmpty(params) && !returns) return
const paramSignature = params
.map(param => `${param.name}: ${getTagType(param)}`)
// prevent object properties from showing as individual params
.filter(p => !p.includes('.'))
.join(', ')
const tagDescriptionRows = _.compact([...params, returns]).map(tag => {
const name = tag.name || tag.title
return (
<div key={name} style={{ display: 'flex', flexDirection: 'row' }}>
<div style={{ flex: '2 2 0', padding: '0.1em 0' }}>
<code>{name}</code>
</div>
<div style={{ flex: '5 5 0', padding: '0.1em 0' }}>
{tag.description}
</div>
</div>
)
})
return (
<Extra title={<pre>{item.name}({paramSignature}){returns ? `: ${getTagType(returns)}` : ''}</pre>}>
{tagDescriptionRows}
</Extra>
)
}
renderEnums = ({ name, type, value }) => {
if (type !== '{enum}' || !value) return
const { showEnumsFor } = this.state
const truncateAt = 10
const valueElements = _.map(value, val => <span key={val}><code>{val}</code> </span>)
// show all if there are few
if (value.length < truncateAt) return <Extra title='Enums:' inline>{valueElements}</Extra>
// add button to show more when there are many values and it is not toggled
if (!showEnumsFor[name]) {
return (
<Extra title='Enums:' inline>
<a style={{ cursor: 'pointer' }} onClick={this.toggleEnumsFor(name)}>
Show all {value.length}
</a>
<div>{valueElements.slice(0, truncateAt - 1)}...</div>
</Extra>
)
}
// add "show more" button when there are many
return (
<Extra title='Enums:' inline>
<a style={{ cursor: 'pointer' }} onClick={this.toggleEnumsFor(name)}>Show less</a>
<div>{valueElements}</div>
</Extra>
)
}
renderRow = item => {
return (
<Table.Row key={item.name}>
<Table.Cell collapsing>{this.renderName(item)}{this.renderRequired(item)}</Table.Cell>
<Table.Cell collapsing>{this.renderDefaultValue(item)}</Table.Cell>
<Table.Cell collapsing>{item.type}</Table.Cell>
<Table.Cell>
{item.description && <p>{item.description}</p>}
{this.renderFunctionSignature(item)}
{this.renderEnums(item)}
</Table.Cell>
</Table.Row>
)
}
render() {
const { props: propsDefinition } = this.props
const content = _.sortBy(_.map(propsDefinition, (config, name) => {
const value = _.get(config, 'type.value')
let type = _.get(config, 'type.name')
if (type === 'union') {
type = _.map(value, (val) => val.name).join('|')
}
type = type && `{${type}}`
const description = _.get(config, 'docBlock.description', '')
return {
name,
type,
value,
tags: _.get(config, 'docBlock.tags'),
required: config.required,
defaultValue: config.defaultValue,
description: description && description.split('\n').map(l => ([l, <br key={l} />])),
}
}), 'name')
return (
<Table compact='very' basic='very'>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Name</Table.HeaderCell>
<Table.HeaderCell>Default</Table.HeaderCell>
<Table.HeaderCell>Type</Table.HeaderCell>
<Table.HeaderCell>Description</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
{_.map(content, this.renderRow)}
</Table.Body>
</Table>
)
}
}
|
JavaScript
| 0 |
@@ -2417,17 +2417,17 @@
r(p =%3E !
-p
+_
.include
@@ -2428,16 +2428,19 @@
ncludes(
+p,
'.'))%0A
|
f3096d1cef56de5aa72c95ad59a625cff3305ac4
|
revert refactoring because sort was important
|
packages/constraint-solver/dependencies-list.js
|
packages/constraint-solver/dependencies-list.js
|
var mori = Npm.require('mori');
////////////////////////////////////////////////////////////////////////////////
// DependenciesList
////////////////////////////////////////////////////////////////////////////////
// A persistent data-structure that wrapps persistent dictionary
ConstraintSolver.DependenciesList = function (prev) {
var self = this;
if (prev) {
self._mapping = prev._mapping;
} else {
self._mapping = mori.hash_map();
}
};
ConstraintSolver.DependenciesList.prototype.contains = function (d) {
var self = this;
return mori.has_key(self._mapping, d);
};
// returns a new version containing passed dependency
ConstraintSolver.DependenciesList.prototype.push = function (d) {
var self = this;
if (self.contains(d)) {
return self;
}
var newList = new ConstraintSolver.DependenciesList(self);
newList._mapping = mori.assoc(self._mapping, d, d);
return newList;
};
ConstraintSolver.DependenciesList.prototype.remove = function (d) {
var self = this;
var newList = new ConstraintSolver.DependenciesList(self);
newList._mapping = mori.dissoc(self._mapping, d);
return newList;
};
ConstraintSolver.DependenciesList.prototype.peek = function () {
var self = this;
return mori.last(mori.first(self._mapping));
};
// a weird method that returns a list of exact constraints those correspond to
// the dependencies in this list
ConstraintSolver.DependenciesList.prototype.exactConstraintsIntersection =
function (constraintsList) {
var self = this;
var exactConstraints = new ConstraintSolver.ConstraintsList();
self.each(function (d) {
var c = mori.last(
// pick an exact constraint for this dependency if such exists
mori.last(mori.get(mori.get(constraintsList.byName, d), "exact")));
if (c)
exactConstraints = exactConstraints.push(c);
});
return exactConstraints;
};
ConstraintSolver.DependenciesList.prototype.union = function (anotherList) {
var self = this;
var newList = new ConstraintSolver.DependenciesList(self);
newList._mapping = mori.union(newList._mapping, anotherList._mapping);
return newList;
};
ConstraintSolver.DependenciesList.prototype.isEmpty = function () {
var self = this;
return mori.is_empty(self._mapping);
};
ConstraintSolver.DependenciesList.prototype.each = function (iter) {
var self = this;
mori.each(self._mapping, function (d) {
iter(mori.last(d));
});
};
ConstraintSolver.DependenciesList.prototype.toString = function (simple) {
var self = this;
var str = "";
strs.sort();
self.each(function (d) {
if (str !== "") {
str += simple ? " " : ", ";
}
str += d;
});
return simple ? str : "<dependencies list: " + str + ">";
};
ConstraintSolver.DependenciesList.prototype.toArray = function () {
var self = this;
var arr = [];
self.each(function (d) {
arr.push(d);
});
return arr;
};
ConstraintSolver.DependenciesList.fromArray = function (arr) {
var list = new ConstraintSolver.DependenciesList();
var args = [];
_.each(arr, function (d) {
args.push(d);
args.push(d);
});
list._mapping = mori.hash_map.apply(mori, args);
return list;
};
|
JavaScript
| 0.000001 |
@@ -2525,16 +2525,85 @@
= %22%22;%0A%0A
+ var strs = %5B%5D;%0A self.each(function (d) %7B%0A strs.push(d);%0A %7D);%0A%0A
strs.s
@@ -2607,34 +2607,37 @@
s.sort();%0A
-self
+_
.each(
+strs,
function (d)
|
1cf711706c3d74ab307c29fc014a20540db8c319
|
introduce recalcinvolved
|
src/js/libgeo/Prover.js
|
src/js/libgeo/Prover.js
|
var conjectures = [];
function guessIncidences(el) {
if (guessIncidences.hasOwnProperty(el.kind))
guessIncidences[el.kind](el);
}
guessIncidences.P = function(p) {
csgeo.lines.forEach(function(l) {
var conjecture = incidentPL(p, l);
if (conjecture.holds())
conjectures.push(conjecture);
});
csgeo.conics.forEach(function(c) {
var conjecture = incidentPC(p, c);
if (conjecture.holds())
conjectures.push(conjecture);
});
};
guessIncidences.L = function(l) {
csgeo.points.forEach(function(p) {
var conjecture = incidentPL(p, l);
if (conjecture.holds())
conjectures.push(conjecture);
});
};
guessIncidences.S = guessIncidences.L;
guessIncidences.C = function(c) {
csgeo.points.forEach(function(p) {
var conjecture = incidentPC(p, c);
if (conjecture.holds())
conjectures.push(conjecture);
});
};
function applyIncidence(a, b) {
return function() {
a.incidences.push(b.name);
b.incidences.push(a.name);
};
}
function incidentPL(p, l) {
return {
getInvolved: function() {
return [p, l];
},
toString: function() {
return "point " + p.name + " incident line " + l.name;
},
apply: applyIncidence(p, l),
holds: function() {
var pn = List.scaldiv(List.abs(p.homog), p.homog);
var ln = List.scaldiv(List.abs(l.homog), l.homog);
var prod = CSNumber.abs(List.scalproduct(pn, ln));
return (prod.value.real < 0.0000000000001);
}
};
}
function incidentPC(p, c) {
return {
getInvolved: function() {
return [p, c];
},
toString: function() {
return "point " + p.name + " incident conic " + c.name;
},
apply: applyIncidence(p, c),
holds: function() {
var erg = General.mult(c.matrix, p.homog);
erg = General.mult(p.homog, erg);
erg = CSNumber.abs(erg);
return (erg.value.real < 0.0000000000001);
}
};
}
function checkConjectures() {
var debug = true;
if (debug) console.log("conjectures", conjectures.length);
//if (!debug)
if (conjectures.length === 0) return;
backupGeo();
var ii, jj, emove;
var nummoves = 3;
// filter free objects which are involved in conjectures
var involved = [];
conjectures.forEach(function(con) {
var invs = con.getInvolved();
invs = invs.forEach(function(el) {
if (involved.indexOf(el) < 0 && csgeo.free.indexOf(el) >= 0) involved.push(el);
});
});
// debug code remove later
var nconject = conjectures.length;
involved.forEach(function(el) {
ii = nummoves;
while (ii--) {
if (el.pinned) {
break;
}
if (debug) console.log("prover: moving element", el.name);
// get random move and move free element
emove = geoOps[el.type].getRandomMove(el);
movepointscr(el, emove.value, emove.type);
// if something bad happens
if (tracingFailed) stateIn.set(stateLastGood);
// check if conjecture still holds
conjectures = conjectures.filter(function(con) {
return con.holds();
});
}
});
if (debug) {
console.log("dropped ", nconject - conjectures.length, " conjectures");
}
if (!debug) {
restoreGeo();
}
for (var i = 0; i < conjectures.length; ++i) {
conjectures[i].apply();
}
conjectures = [];
if (debug) {
csgeo.gslp.forEach(function(el) {
console.log(el.name, el.incidences);
});
}
}
|
JavaScript
| 0 |
@@ -2443,16 +2443,72 @@
var
+involved;%0A%0A var recalcInvolved = function()%7B%0A
involved
@@ -2510,24 +2510,28 @@
olved = %5B%5D;%0A
+
conjectu
@@ -2562,24 +2562,28 @@
) %7B%0A
+
+
var invs = c
@@ -2596,24 +2596,28 @@
Involved();%0A
+
invs
@@ -2655,24 +2655,28 @@
+
+
if (involved
@@ -2699,35 +2699,19 @@
&&
-csgeo.free.indexOf(el) %3E= 0
+el.moveable
) in
@@ -2723,24 +2723,40 @@
d.push(el);%0A
+ %7D);%0A
%7D);%0A
@@ -2756,24 +2756,45 @@
%7D);%0A %7D
+%0A%0A recalcInvolved(
);%0A%0A // d
@@ -3501,24 +3501,33 @@
);%0A %7D
+ // while
%0A %7D);%0A%0A
|
5e6f08bbc4e64a4684a48b9c115857c899458198
|
fix missing param
|
packages/easysearch:elasticsearch/lib/engine.js
|
packages/easysearch:elasticsearch/lib/engine.js
|
import ElasticSearchDataSyncer from './data-syncer'
if (Meteor.isServer) {
var Future = Npm.require('fibers/future'),
elasticsearch = Npm.require('elasticsearch');
}
/**
* The ElasticsearchEngine lets you search documents through an Elasticsearch Index.
*
* @type {ElasticSearchEngine}
*/
class ElasticSearchEngine extends EasySearch.ReactiveEngine {
/**
* Constructor.
*/
constructor() {
super(...arguments);
}
/**
* Return default configuration.
*
* @returns {Object}
*/
defaultConfiguration() {
return _.defaults({}, ElasticSearchEngine.defaultElasticsearchConfiguration(), super.defaultConfiguration());
}
/**
* Default configuration.
*
* @returns {Object}
*/
static defaultElasticsearchConfiguration() {
return {
indexName: 'easysearch',
/**
* Return the fields to index in ElasticSearch.
*
* @param {Object} options Index options
*
* @returns {null|Array}
*/
fieldsToIndex(options) {
return null;
},
/**
* The ES query object used for searching the results.
*
* @param {Object} searchObject Search object
* @param {Object} options Search options
*
* @return array
*/
query(searchObject, options) {
let query = {
bool: {
should: []
}
};
_.each(searchObject, function (searchString, field) {
query.bool.should.push({
match: {
[field]: {
query: searchString,
fuzziness: 'AUTO',
operator: 'or'
}
}
});
});
return query;
},
/**
* The ES sorting method used for sorting the results.
*
* @param {Object} searchObject Search object
* @param {Object} options Search options
*
* @return array
*/
sort(searchObject, options) {
return options.index.fields;
},
/**
* Return the ElasticSearch document to index.
*
* @param {Object} doc Document to index
* @param {Array} fields Array of document fields
*/
getElasticSearchDoc(doc, fields) {
if (null === fields) {
return doc;
}
let partialDoc = {};
_.each(fields, function (field) {
if (_.has(doc, field)) {
partialDoc[field] = _.get(doc, field);
}
});
return partialDoc;
},
/**
* Return the elastic search body.
*
* @param {Object} body Existing ES body
*
* @return {Object}
*/
body: (body) => body,
/**
* Default ES client configuration.
*/
client: {
host: 'localhost:9200',
},
};
}
/**
* Put mapping according to mapping field provided when creating an EasySearch index
*
* @param {Object} indexConfig Index configuration
* @param {Function} cb callback on finished mapping
*/
putMapping(indexConfig = {}, cb) {
const {
mapping: body,
elasticSearchClient,
} = indexConfig;
if (!body) {
return cb();
}
const { indexName } = this.config
const type = this.getIndexType()
elasticSearchClient.indices.create({
updateAllTypes: false,
index: indexName,
}, Meteor.bindEnvironment(() => {
elasticSearchClient.indices.getMapping({
index: indexName,
type
}, Meteor.bindEnvironment((err, res) => {
const isEmpty = Object.keys(res).length === 0 && res.constructor === Object;
if (!isEmpty) {
return cb();
}
elasticSearchClient.indices.putMapping({
updateAllTypes: false,
index: indexName,
type,
body
}, cb);
}));
}));
}
/**
* @returns {String}
*/
getIndexType(indexConfig) {
return this.config.indexType || indexConfig.name;
}
/**
* Act on index creation.
*
* @param {Object} indexConfig Index configuration
*/
onIndexCreate(indexConfig) {
super.onIndexCreate(indexConfig);
if (Meteor.isServer) {
indexConfig.elasticSearchClient = new elasticsearch.Client(this.config.client);
this.putMapping(indexConfig, Meteor.bindEnvironment(() => {
indexConfig.elasticSearchSyncer = new ElasticSearchDataSyncer({
indexName: this.config.indexName,
indexType: this.getIndexType(indexConfig),
collection: indexConfig.collection,
client: indexConfig.elasticSearchClient,
beforeIndex: (doc) => this.callConfigMethod('getElasticSearchDoc', doc, this.callConfigMethod('fieldsToIndex', indexConfig))
});
}));
}
}
/**
* Return the reactive search cursor.
*
* @param {Object} searchDefinition Search definition
* @param {Object} options Search and index options
*/
getSearchCursor(searchDefinition, options) {
let fut = new Future(),
body = {};
searchDefinition = EasySearch.MongoDB.prototype.transformSearchDefinition(searchDefinition, options);
body.query = this.callConfigMethod('query', searchDefinition, options);
body.sort = this.callConfigMethod('sort', searchDefinition, options);
body.fields = ['_id'];
body = this.callConfigMethod('body', body, options);
options.index.elasticSearchClient.search({
index: this.config.indexName,
type: this.getIndexType(options.index),
body: body,
size: options.search.limit,
from: options.search.skip
}, Meteor.bindEnvironment((error, data) => {
if (error) {
console.log('Had an error while searching!');
console.log(error);
return;
}
let { total, ids } = this.getCursorData(data),
cursor;
if (ids.length > 0) {
cursor = options.index.collection.find({
$or: _.map(ids, (_id) => {
return { _id };
})
}, { limit: options.search.limit });
} else {
cursor = EasySearch.Cursor.emptyCursor;
}
fut['return'](new EasySearch.Cursor(cursor, total));
}));
return fut.wait();
}
/**
* Get data for the cursor from the elastic search response.
*
* @param {Object} data ElasticSearch data
*
* @returns {Object}
*/
getCursorData(data) {
return {
ids : _.map(data.hits.hits, (resultSet) => resultSet._id),
total: data.hits.total
};
}
}
EasySearch.ElasticSearch = ElasticSearchEngine
export default ElasticSearchEngine
|
JavaScript
| 0.000083 |
@@ -3323,16 +3323,27 @@
dexType(
+indexConfig
)%0A%0A e
|
dfba3d8c5ee3434c0f70afbb83944c67b43774e5
|
Remove unused [GLIMMER] flag
|
packages/ember-glimmer/tests/utils/test-case.js
|
packages/ember-glimmer/tests/utils/test-case.js
|
export { TestCase, moduleFor } from './abstract-test-case';
import {
AbstractApplicationTest,
AbstractRenderingTest
} from './abstract-test-case';
import assign from 'ember-metal/assign';
import { GLIMMER } from 'ember-application/system/engine';
import ComponentLookup from 'ember-views/component_lookup';
export class ApplicationTest extends AbstractApplicationTest {
get applicationOptions() {
return assign(super.applicationOptions, { [GLIMMER]: true });
}
}
export class RenderingTest extends AbstractRenderingTest {
constructor() {
super();
let { owner } = this;
this.env = owner.lookup('service:-glimmer-environment');
owner.register('component-lookup:main', ComponentLookup);
owner.registerOptionsForType('helper', { instantiate: false });
owner.registerOptionsForType('component', { singleton: false });
}
render(...args) {
super.render(...args);
this.renderer._root = this.component;
}
}
|
JavaScript
| 0 |
@@ -148,108 +148,8 @@
e';%0A
-import assign from 'ember-metal/assign';%0Aimport %7B GLIMMER %7D from 'ember-application/system/engine';%0A
impo
@@ -272,107 +272,8 @@
t %7B%0A
- get applicationOptions() %7B%0A return assign(super.applicationOptions, %7B %5BGLIMMER%5D: true %7D);%0A %7D%0A
%7D%0A%0Ae
|
51b0cbbcf49ae8e87894c96d3f6e1e829a5124b5
|
Send data received from the watch to the configured URL
|
src/js/pebble-js-app.js
|
src/js/pebble-js-app.js
|
/*
* Copyright (c) 2016, Natacha Porté
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
var cfg_endpoint = null;
var cfg_data_field = null;
Pebble.addEventListener("ready", function() {
console.log("Health Export PebbleKit JS ready!");
Pebble.sendAppMessage({ "modalMessage": "Not configured" });
});
Pebble.addEventListener("appmessage", function(e) {
console.log('Received message: ' + JSON.stringify(e.payload));
if (e.payload.dataKey) {
Pebble.sendAppMessage({ "lastSent": e.payload.dataKey });
}
});
Pebble.addEventListener("showConfiguration", function() {
var settings = "?v=1.0";
if (cfg_endpoint) {
settings += "&url=" + encodeURIComponent(cfg_endpoint);
}
if (cfg_data_field) {
settings += "&data_field=" + encodeURIComponent(cfg_data_field);
}
Pebble.openURL("https://cdn.rawgit.com/faelys/pebble-health-export/v1.0/config.html" + settings);
});
Pebble.addEventListener("webviewclosed", function(e) {
var configData = JSON.parse(decodeURIComponent(e.response));
var wasConfigured = (cfg_endpoint && cfg_data_field);
if (configData.url) {
cfg_endpoint = configData.url;
}
if (configData.dataField) {
cfg_data_field = configData.dataField;
}
if (!wasConfigured && cfg_endpoint && cfg_data_field) {
Pebble.sendAppMessage({ "lastSent": 0 });
}
});
|
JavaScript
| 0 |
@@ -820,16 +820,541 @@
null;%0A%0A
+var to_send = %5B%5D;%0Avar sender = new XMLHttpRequest();%0A%0Afunction sendHead() %7B%0A if (to_send.length %3C 1) return;%0A var line = to_send.shift();%0A var data = new FormData();%0A data.append(cfg_data_field, line);%0A sender.open(%22POST%22, cfg_endpoint, true);%0A sender.send(data);%0A%7D%0A%0Afunction enqueue(key, line) %7B%0A to_send.push(line);%0A if (to_send.length === 1) sendHead();%0A%7D%0A%0Afunction uploadError() %7B console.log(this.statusText); %7D%0A%0Asender.addEventListener(%22load%22, sendHead);%0Asender.addEventListener(%22error%22, uploadError);%0A%0A
Pebble.a
@@ -1655,19 +1655,95 @@
.dataKey
-) %7B
+ && e.payload.dataLine) %7B%0A enqueue(e.payload.dataKey, e.payload.dataLine);
%0A P
|
5c3df97674aeaa069bd569f07df8179a4875aeda
|
REMOVE unnecessary log
|
lib/ui/src/core/context.js
|
lib/ui/src/core/context.js
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Events from '@storybook/core-events';
import initProviderApi from './init-provider-api';
import initKeyHandler from './init-key-handler';
import getInitialState from './initial-state';
import initAddons from './addons';
import initChannel from './channel';
import initNotifications from './notifications';
import initStories from './stories';
import initLayout from './layout';
import initURL from './url';
import initVersions from './versions';
const Context = React.createContext({ api: undefined, state: getInitialState({}) });
const { STORY_CHANGED, SET_STORIES, SELECT_STORY, APPLY_SHORTCUT } = Events;
export class Provider extends Component {
static propTypes = {
navigate: PropTypes.func.isRequired,
provider: PropTypes.shape({}).isRequired,
location: PropTypes.shape({}).isRequired,
path: PropTypes.string,
viewMode: PropTypes.oneOf(['components', 'info']),
storyId: PropTypes.string,
children: PropTypes.oneOfType([PropTypes.node, PropTypes.func]).isRequired,
};
static defaultProps = {
viewMode: undefined,
storyId: undefined,
path: undefined,
};
constructor(props) {
super(props);
const { provider, location, path, viewMode, storyId, navigate } = props;
const store = {
getState: () => this.state,
setState: (a, b) => this.setState(a, b),
};
const apiData = {
navigate,
store,
provider,
location,
path,
viewMode,
storyId,
};
const modules = [
initChannel,
initAddons,
initLayout,
initNotifications,
initStories,
initURL,
initVersions,
].map(initModule => initModule(apiData));
// Create our initial state by combining the initial state of all modules
const state = getInitialState(...modules.map(m => m.state));
// Get our API by combining the APIs exported by each module
const combo = Object.assign({ navigate }, ...modules.map(m => m.api));
const eventHandler = initKeyHandler({ store, api: combo });
const api = initProviderApi({ provider, store, api: combo, eventHandler });
api.on(STORY_CHANGED, id => {
const options = api.getParameters(id, 'options');
api.setOptions(options);
});
console.log(SET_STORIES);
api.on(SET_STORIES, data => {
api.setStories(data.stories);
});
api.on(SELECT_STORY, ({ kind, story, ...rest }) => {
api.selectStory(kind, story, rest);
});
api.on(APPLY_SHORTCUT, data => {
api.handleShortcut(data.event);
});
// Now every module has had a chance to set its API, call init on each module which gives it
// a chance to do things that call other modules' APIs.
modules.forEach(({ init }) => {
if (init) {
init({
...apiData,
api,
});
}
});
this.state = state;
this.api = api;
this.eventHandler = eventHandler;
}
componentDidMount() {
this.eventHandler.bind();
}
shouldComponentUpdate(nextProps, nextState) {
const { state: prevState, props: prevProps } = this;
if (prevState !== nextState) {
return true;
}
if (prevProps.path !== nextProps.path) {
return true;
}
return false;
}
static getDerivedStateFromProps = (props, state) => {
if (state.path !== props.path) {
return {
...state,
location: props.location,
path: props.path,
viewMode: props.viewMode,
storyId: props.storyId,
};
}
return null;
};
render() {
const { children } = this.props;
const value = {
state: this.state,
api: this.api,
};
return (
<Context.Provider value={value}>
{typeof children === 'function' ? children(value) : children}
</Context.Provider>
);
}
}
Provider.displayName = 'Manager';
export const { Consumer } = Context;
|
JavaScript
| 0.000001 |
@@ -2323,38 +2323,8 @@
);%0A%0A
- console.log(SET_STORIES);%0A
|
e5055c6cd80e04488c9e41b4ef2f4f524e0ff2b9
|
Add getter for count
|
lib/views/bottom-status.js
|
lib/views/bottom-status.js
|
'use strict';
class BottomStatus extends HTMLElement{
createdCallback() {
this.classList.add('inline-block')
this.classList.add('linter-highlight')
this.iconSpan = document.createElement('span')
this.iconSpan.classList.add('icon')
this.appendChild(this.iconSpan)
this.count = 0
this.addEventListener('click', function() {
atom.commands.dispatch(atom.views.getView(atom.workspace), 'linter:next-error')
})
}
set count(Value) {
if (Value) {
this.classList.remove('status-success')
this.iconSpan.classList.remove('icon-check')
this.classList.add('status-error')
this.iconSpan.classList.add('icon-x')
this.iconSpan.textContent = Value === 1 ? '1 Issue' : `${Value} Issues`
} else {
this.classList.remove('status-error')
this.iconSpan.classList.remove('icon-x')
this.classList.add('status-success')
this.iconSpan.classList.add('icon-check')
this.iconSpan.textContent = 'No Issues'
}
}
}
module.exports = BottomStatus = document.registerElement('linter-bottom-status', {prototype: BottomStatus.prototype})
|
JavaScript
| 0 |
@@ -454,26 +454,93 @@
%0A%0A
-set count(Value) %7B
+get count()%7B%0A return this._count%0A %7D%0A%0A set count(Value) %7B%0A this._count = Value
%0A
|
1b6f537f7b1fbf3abae850004491fc5c9e360335
|
支持在项目的 package.json 里配置
|
lib/webpack.config.base.js
|
lib/webpack.config.base.js
|
/**
* @file webpack.config.base.js
* @author 刘巍峰 <[email protected]>
* Created on 2016-02-13 23:53
*/
/**
* Created by liuweifeng on 16/1/14.
*/
'use strict';
const path = require('path');
const fs = require('fs');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = function (options) {
var hwpConfig = {
title: options.title || '咸鱼 - 前端开发脚手架',
template: path.join(__dirname, 'index.ejs')
};
if(options.template){
let content = fs.readFileSync(path.resolve(path.join(process.cwd(), options.template)));
if(content.indexOf('<body>') == -1){
hwpConfig.content = content;
}else{
hwpConfig.templateContent = content;
}
}
return {
entry: {
'index': path.resolve(process.cwd(), 'src/js/index')
},
output: {
path: path.join(process.cwd(), ''),
filename: '[name].js',
publicPath: `http://dev.js.weibo.cn/${options.module}/build/`
},
plugins: [
new HtmlWebpackPlugin(hwpConfig)
],
resolve: {
extensions: ['', '.js', '.vue', '.css', '.jsx'],
modulesDirectories: ['web_modules', 'node_modules', path.join(process.cwd(), 'node_modules'), path.join(__dirname, '../node_modules')]
},
resolveLoader: {
modulesDirectories: ['web_loaders', 'web_modules', 'node_loaders', 'node_modules', path.join(__dirname, '../node_modules')]
},
module: {
loaders: [
{
test: /\.jsx?$/,
loaders: ['babel'],
exclude: [/node_modules/]
},
//{
// test: /\.css$/,
// loaders: ['style', 'css']
//},
{
test: /\.(png|jpg|gif)$/,
loaders: ['url', 'file']
},
{
test: /\.json/,
loaders: ['json']
},
{
test: /\.svg$/,
loaders: ['raw']
}
]
},
babel: {
presets: [require('babel-preset-es2015'), require('babel-preset-stage-0')],
plugins: [require('babel-plugin-transform-runtime')]
}
};
};
|
JavaScript
| 0 |
@@ -363,131 +363,135 @@
-var hwpConfig = %7B%0A title: options.title %7C%7C '%E5%92%B8%E9%B1%BC - %E5%89%8D%E7%AB%AF%E5%BC%80%E5%8F%91%E8%84%9A%E6%89%8B%E6%9E%B6',%0A template: path.join(__dirname, 'index.ejs')%0A %7D
+const localConfig = require(process.cwd() + '/package.json')%5B'xianyu'%5D %7C%7C %7B%7D;%0A options = Object.assign(options, localConfig)
;%0A
@@ -781,112 +781,472 @@
%7D%0A
+%0A
-return %7B%0A entry: %7B%0A 'index': path.resolve(process.cwd(), 'src/js/index')%0A %7D
+const template = path.join(__dirname, 'index.ejs');%0A let plugins = %5B%5D;%0A let entry = %7B%7D;%0A Object.keys(options.entry).forEach(function(e)%7B%0A entry%5Be%5D = process.cwd() + '/' + options.entry%5Be%5D;%0A plugins%5Bplugins.length%5D = new HtmlWebpackPlugin(%7B%0A title: options.title %7C%7C '%E5%92%B8%E9%B1%BC - %E5%89%8D%E7%AB%AF%E5%BC%80%E5%8F%91%E8%84%9A%E6%89%8B%E6%9E%B6',%0A template: template,%0A chunks: %5Be%5D,%0A filename: e + '.html'%0A %7D)%0A %7D);%0A return %7B%0A entry: entry
,%0A
@@ -1450,64 +1450,15 @@
ns:
-%5B%0A new HtmlWebpackPlugin(hwpConfig)%0A %5D
+plugins
,%0A
|
7e592a9cf4c7f1b178ba85d092c3a3497a1c5c3d
|
Complete * 判断文件是否存在,不存在就创建
|
zhihu/app.js
|
zhihu/app.js
|
'use strict'
/**
* TODO 下个版本1.2.0添加功能
* 不重复保存已保存的收藏
* 如果该收藏被删除,提示用户
* 在网络状态差的情况下,重新请求
* 介绍页面弄一下
*/
var zhihu = require('./zhihuapi/api.js').zhihu
var fs = require('fs')
var readline = require('readline')
/**
* [rl 命令行输入框]
*/
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
})
fs.exists('/zhihu', function (exists) {
if (!exists) {
fs.mkdir('./zhihu', '0777', function (err) {
if (err) throw err
})
}
})
rl.question('知乎收藏id是多少?', function (answer) {
console.log('收藏ID是' + answer)
console.log('正在开始,不要慌张!!!!')
GetCollectionList(answer)
// test id 42474270
rl.close()
})
/**
* 获取当前页数,并且调取保存
* @param {int} id 当前专题id
*/
function GetCollectionList (id) {
zhihu.GetCollectionPages(id).then(function (pages) {
if (!pages) return false
console.log('当前收藏共计:' + pages.last + '页')
GetCollection(id, pages.first, pages.last)
})
}
/**
* 读取知乎收藏夹
* @param {string} id 收藏的id
* @param {string} page 当前页码
*/
function GetCollection (id, pagefirst, pagelast) {
var page = pagefirst
zhihu.GetCollection(id, page).then(function (value) {
console.log('----- 第' + page + '页已获取 -----')
return value
}).then(function (value) {
value.forEach(function (value) {
// value 包含 {title,body,key}
io(value)
})
setTimeout(function () {
if (page < pagelast) {
++page
GetCollection(id, page, pagelast)
}
}, 450)
})
}
/**
* 存储文件
* @param {object} value {包含title\body\key}
*/
function io (value) {
var title = value.title
var body = value.body
var key = value.key
fs.open('zhihu/' + title + key + '.md', 'w', function (err, data) {
if (err) {
console.log('文件创建失败')
return false
}
fs.writeFile('zhihu/' + title + key + '.md', body, function (err) {
if (err) {
console.log('文件写入失败')
return console.error(err)
}
console.log(title + '.md' + '-----文件写入成功')
fs.close(data, function (err) {
if (err) {
console.log('文件关闭失败')
return console.error(err)
}
})
})
})
}
|
JavaScript
| 0.000001 |
@@ -215,112 +215,27 @@
%0A *
-%5Brl %E5%91%BD%E4%BB%A4%E8%A1%8C%E8%BE%93%E5%85%A5%E6%A1%86%5D%0A */%0Avar rl = readline.createInterface(%7B%0A input: process.stdin,%0A output: process.stdout%0A%7D)%0A
+%E5%88%A4%E6%96%AD%E6%96%87%E4%BB%B6%E6%98%AF%E5%90%A6%E5%AD%98%E5%9C%A8%EF%BC%8C%E4%B8%8D%E5%AD%98%E5%9C%A8%E5%B0%B1%E5%88%9B%E5%BB%BA%0A */
%0Afs.
@@ -377,16 +377,128 @@
%7D%0A%7D)%0A%0A
+/**%0A * %5Brl %E5%91%BD%E4%BB%A4%E8%A1%8C%E8%BE%93%E5%85%A5%E6%A1%86%5D%0A */%0Avar rl = readline.createInterface(%7B%0A input: process.stdin,%0A output: process.stdout%0A%7D)%0A%0A
rl.quest
|
d75816043989851013fd795b76adaf8f75bdae92
|
remove console.log
|
src/js/tabs/advanced.js
|
src/js/tabs/advanced.js
|
var util = require('util'),
webutil = require('../util/web'),
Tab = require('../client/tab').Tab,
Currency = ripple.Currency;
var AdvancedTab = function ()
{
Tab.call(this);
};
util.inherits(AdvancedTab, Tab);
AdvancedTab.prototype.tabName = 'advanced';
AdvancedTab.prototype.mainMenu = 'advanced';
AdvancedTab.prototype.generateHtml = function ()
{
return require('../../templates/tabs/advanced.jade')();
};
AdvancedTab.prototype.angular = function(module)
{
module.controller('AdvancedCtrl', ['$scope', '$rootScope', 'rpId', 'rpKeychain',
function ($scope, $rootScope, $id, $keychain)
{
if (!$id.loginStatus) $id.goId();
// XRP currency object.
// {name: "XRP - Ripples", order: 146, value: "XRP"}
var xrpCurrency = Currency.from_json("XRP");
$scope.xrp = {
name: xrpCurrency.to_human({full_name:$scope.currencies_all_keyed.XRP.name}),
code: xrpCurrency.get_iso(),
currency: xrpCurrency
};
$scope.options = Options;
$scope.optionsBackup = $.extend(true, {}, Options);
$scope.passwordProtection = !$scope.userBlob.data.persistUnlock;
$scope.editBlob = false;
$scope.editMaxNetworkFee = false;
$scope.editAcctOptions = false;
$scope.max_tx_network_fee_human = ripple.Amount.from_json($scope.options.max_tx_network_fee).to_human();
$scope.saveSetings = function() {
// force serve ports to be number
_.each($scope.options.server.servers, function(s) {
s.port = +s.port;
});
// Save in local storage
if (!store.disabled) {
store.set('ripple_settings', angular.toJson($scope.options));
}
}
$scope.saveBlob = function() {
$scope.saveSetings();
$scope.editBlob = false;
// Reload
location.reload();
};
$scope.saveMaxNetworkFee = function () {
// Save in local storage
if (!store.disabled) {
$scope.options.max_tx_network_fee = ripple.Amount.from_human($scope.max_tx_network_fee_human).to_json();
store.set('ripple_settings', angular.toJson($scope.options));
}
$scope.editMaxNetworkFee = false;
// Reload
location.reload();
};
$scope.cancelEditMaxNetworkFee = function () {
$scope.editMaxNetworkFee = false;
$scope.options.max_tx_network_fee = $scope.optionsBackup.max_tx_network_fee;
};
$scope.cancelEditAcctOptions = function () {
$scope.editAcctOptions = false;
};
$scope.$on('$blobUpdate', function(){
$scope.passwordProtection = !$scope.userBlob.data.persistUnlock;
});
$scope.setPasswordProtection = function () {
$keychain.setPasswordProtection(!$scope.passwordProtection, function(err, resp){
if (err) {
$scope.passwordProtection = !$scope.PasswordProtection;
//TODO: report errors to user
}
});
};
// Add a new server
$scope.addServer = function () {
// Create a new server line
if(!$scope.options.server.servers.isEmptyServer)
$scope.options.server.servers.push({isEmptyServer: true, secure: false});
// Set editing to true
$scope.editing = true;
}
}]);
module.controller('ServerRowCtrl', ['$scope',
function ($scope) {
$scope.editing = $scope.server.isEmptyServer;
// Delete the server
$scope.remove = function () {
$scope.options.server.servers.splice($scope.index,1);
$scope.saveSetings();
}
$scope.hasRemove = function () {
return !$scope.server.isEmptyServer && $scope.options.server.servers.length !== 1;
}
$scope.cancel = function () {
if ($scope.server.isEmptyServer) {
$scope.remove();
return;
}
$scope.editing = false;
console.log('---- ServerRowCtrl::cancel index: ' + $scope.index);
console.log(JSON.stringify($scope.server));
$scope.server = $.extend({ '$$hashKey' : $scope.server.$$hashKey }, $scope.optionsBackup.server.servers[$scope.index]);
Options.server.servers[$scope.index] = $.extend({}, $scope.optionsBackup.server.servers[$scope.index]);
console.log(JSON.stringify($scope.server));
console.log(JSON.stringify(Options.server.servers));
}
$scope.noCancel = function () {
return $scope.server.isEmptyServer && $scope.options.server.servers.length === 1;
}
$scope.save = function () {
$scope.server.isEmptyServer = false;
$scope.editing = false;
$scope.saveSetings();
// Reload
location.reload();
};
}
]);
};
module.exports = AdvancedTab;
|
JavaScript
| 0.000001 |
@@ -3816,134 +3816,8 @@
se;%0A
- console.log('---- ServerRowCtrl::cancel index: ' + $scope.index);%0A console.log(JSON.stringify($scope.server));%0A
@@ -4056,121 +4056,8 @@
%5D);%0A
- console.log(JSON.stringify($scope.server));%0A console.log(JSON.stringify(Options.server.servers));%0A
|
1aabaec1584a1bc0bda9f63ab542d2daf20c0109
|
Revert "comment out spammy CTD logging"
|
src/ConstantTimeDispatcher.js
|
src/ConstantTimeDispatcher.js
|
/*
Copyright 2017 Vector Creations 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.
*/
// singleton which dispatches invocations of a given type & argument
// rather than just a type (as per EventEmitter and Flux's dispatcher etc)
//
// This means you can have a single point which listens for an EventEmitter event
// and then dispatches out to one of thousands of RoomTiles (for instance) rather than
// having each RoomTile register for the EventEmitter event and having to
// iterate over all of them.
class ConstantTimeDispatcher {
constructor() {
// type -> arg -> [ listener(arg, params) ]
this.listeners = {};
}
register(type, arg, listener) {
if (!this.listeners[type]) this.listeners[type] = {};
if (!this.listeners[type][arg]) this.listeners[type][arg] = [];
this.listeners[type][arg].push(listener);
}
unregister(type, arg, listener) {
if (this.listeners[type] && this.listeners[type][arg]) {
var i = this.listeners[type][arg].indexOf(listener);
if (i > -1) {
this.listeners[type][arg].splice(i, 1);
}
}
else {
console.warn("Unregistering unrecognised listener (type=" + type + ", arg=" + arg + ")");
}
}
dispatch(type, arg, params) {
if (!this.listeners[type] || !this.listeners[type][arg]) {
//console.warn("No registered listeners for dispatch (type=" + type + ", arg=" + arg + ")");
return;
}
this.listeners[type][arg].forEach(listener=>{
listener.call(arg, params);
});
}
}
if (!global.constantTimeDispatcher) {
global.constantTimeDispatcher = new ConstantTimeDispatcher();
}
module.exports = global.constantTimeDispatcher;
|
JavaScript
| 0 |
@@ -1868,18 +1868,16 @@
-//
console.
|
e2b89801a4f84e0e9fe81d2f760798b6f05275be
|
test updated
|
lib/assets/test/spec/cartodb/table/tableview.spec.js
|
lib/assets/test/spec/cartodb/table/tableview.spec.js
|
/**
* test for table view
*/
describe("tableview", function() {
describe("headerview", function() {
var view;
var model = new cdb.admin.CartoDBTableMetadata({
name: 'test'
});
beforeEach(function() {
view = new cdb.admin.HeaderView({
el: $('<div>'),
column: ['name', 'type'],
table: model
});
});
it('should render', function() {
view.render();
expect(view.$('label > a').html().trim()).toEqual('name');
expect(view.$('p > a').html()).toEqual('type');
});
it("when click on column name a menu should be opened", function() {
runs(function() {
view.render();
view.$('.coloptions').trigger('click');
});
//WTF i need to wait this time to click to be triggered? <- in fact it probably doesn't have anything to do with time, but with the way the Browser UI thread choose what's going to execute next
waits(400);
runs(function() {
expect(cdb.admin.HeaderView.colOptions.$el.css('display')).toEqual('block');
});
});
});
describe('TableView', function() {
var tview;
var model;
beforeEach(function() {
this.server = sinon.fakeServer.create();
model = new cdb.admin.CartoDBTableMetadata({
name: 'test',
schema: [
['id', 'integer'],
['col1', 'integer'],
['col2', 'integer'],
['col3', 'integer']
]
});
tview = new cdb.admin.TableView({
el: $('<table>'),
dataModel: model.data(),
model: model,
row_header: true
});
model.data().reset([
{'id': 1, 'col1': 1, 'col2': 2, 'col3': 3},
{'id': 2, 'col1': 4, 'col2': 5, 'col3': 6}
]);
});
it('should a table', function() {
model.set({
columns: [['test', 'integer']]
});
tview.render();
expect(tview.$('thead').length).toEqual(1);
});
it("should edit cell", function() {
spyOn(tview, '_getEditor');
tview.render();
tview.getCell(0, 0).trigger('dblclick');
expect(tview._getEditor).toHaveBeenCalled();
});
it("should not edit cell", function() {
var sqlView = new cdb.admin.SQLViewData(null, { sql: 'select * from a' });
model.useSQLView(sqlView);
sqlView.reset([
{'id': 1, 'col1': 1, 'col2': 2, 'col3': 3},
{'id': 2, 'col1': 4, 'col2': 5, 'col3': 6}
]);
spyOn(tview, '_getEditor');
tview.getCell(0, 0).trigger('click');
expect(tview._getEditor).not.toHaveBeenCalled();
});
it("should be able to add an empty row", function() {
var prevSize = tview._models[0].table.data().length;
tview.addEmptyRow();
this.server.requests[0].respond(200,{ "Content-Type": "application/json" },"");
expect(prevSize+1).toEqual(tview._models[0].table.data().length);
})
it("should show the empty table layout when there's no data", function() {
model.data().reset();
model.data().trigger('dataLoaded');
expect(tview.$('.placeholder.noRows').length).toBe(2);
expect(tview.$('.placeholder.noRows.decoration').length).toBe(1);
expect(tview.$('tfoot').length).toBe(1);
})
it("should notify the model when a row changes", function() {
var notified = 0;
model.bind('notice', function() { notified++});
tview.rowChanged();
expect(notified).toEqual(1);
});
it("should notify the model when a row is synched", function() {
var notified = 0;
model.bind('notice', function() { notified++});
tview.rowSynched();
expect(notified).toEqual(1);
});
it("should notify the model when a row synch fails", function() {
var notified = 0;
model.bind('notice', function() { notified++});
tview.rowFailed();
expect(notified).toEqual(1);
});
it("should notify the model when a row is deleted", function() {
var notified = 0;
model.bind('notice', function() { notified++});
tview.rowDestroyed();
expect(notified).toEqual(1);
});
it("should not show the empty table layout after an empty row insertion", function() {
model.data().reset();
tview.render();
tview.addEmptyRow()
expect(tview.$('.placeholder.noRows').length).toBe(0);
expect(tview.$('.placeholder.noRows.decoration').length).toBe(0);
expect(tview.$('tfoot').length).toBe(0);
})
xit("should show the empty table layout after the deletion of the last row", function() {
// @todo (Xabel) this is not working, I'm not sure why, because in the app everything goes fine
model.data().reset();
tview = new cdb.admin.TableView({
el: $('<table>'),
dataModel: model.data(),
model: model,
row_header: true
});
tview.render();
tview.addEmptyRow();
spyOn(tview, 'rowDestroyed');
spyOn(tview, 'emptyTable');
var rowOptions = tview.rowViews[0]._getRowOptions();
rowOptions.setRow(tview.rowViews[0].model);
rowOptions.deleteRow();
waits(100);
expect(tview.emptyTable).toHaveBeenCalled();
expect(tview.$('.placeholder.noRows').length).toBe(2);
expect(tview.$('.placeholder.noRows.decoration').length).toBe(1);
expect(tview.$('tfoot').length).toBe(1);
})
});
describe('TableTab', function() {
var tview;
var model;
beforeEach(function() {
model = new cdb.admin.CartoDBTableMetadata({
name: 'test'
});
tview = new cdb.admin.TableTab({
model: model
});
});
it('should render a div', function() {
tview.render();
expect(tview.$el.hasClass('table')).toBeTruthy();
});
});
describe('HeaderDropdown', function() {
var view;
var model;
beforeEach(function() {
model = new cdb.admin.CartoDBTableMetadata({
name: 'test'
});
view = new cdb.admin.HeaderDropdown({
position: 'position',
template_base: "table/views/table_header_options"
});
});
it("should render all options for normal fields", function() {
view.setTable(model, 'normal');
expect(view.$('li').length).toEqual(7);
});
it("should not render all options for reserved column", function() {
view.setTable(model, 'cartodb_id');
expect(view.$('li').length).toEqual(2);
view.setTable(model, 'normal');
expect(view.$('li').length).toEqual(7);
});
it("should not render all options for read only data", function() {
var sqlView = new cdb.admin.SQLViewData(null, { sql: 'select * from a' });
model.useSQLView(sqlView);
view.setTable(model, 'cartodb_id');
expect(view.$('li').length).toEqual(2);
view.setTable(model, 'normal');
expect(view.$('li').length).toEqual(2);
});
});
});
|
JavaScript
| 0 |
@@ -3280,15 +3280,22 @@
row
-changes
+is being saved
%22, f
@@ -3403,15 +3403,14 @@
.row
-Changed
+Saving
();%0A
|
21a95ddc1269129c4d568af42f3b2bb6dbb3f30a
|
Clear the timeout timer in the catch
|
lib/cluster/services/cluster/backends/state-utils.js
|
lib/cluster/services/cluster/backends/state-utils.js
|
'use strict';
const _ = require('lodash');
const parseError = require('@terascope/error-parser');
function _iterateState(clusterState, cb) {
return _.chain(clusterState)
.filter(node => node.state === 'connected')
.map((node) => {
const workers = node.active.filter(cb);
return workers.map((worker) => {
worker.node_id = node.node_id;
worker.hostname = node.hostname;
return worker;
});
})
.flatten()
.value();
}
function findAllSlicers(clusterState) {
return _iterateState(
clusterState,
worker => worker.assignment === 'execution_controller'
);
}
function findWorkersByExecutionID(clusterState, exId) {
return _iterateState(
clusterState,
worker => worker.assignment === 'worker' && worker.ex_id === exId
);
}
function findSlicersByExecutionID(clusterState, exIdDict) {
return _iterateState(
clusterState,
worker => worker.assignment === 'execution_controller' && exIdDict[worker.ex_id]
);
}
function newGetSlicerStats(clusterState, context, messaging) {
// eslint-disable-next-line no-undef
return function getSlicerStats(exIds, specificId) {
return new Promise(((resolve, reject) => {
let timer;
const nodeQueries = [];
const exIdDict = exIds.reduce((prev, curr) => {
prev[curr] = curr;
return prev;
}, {});
const list = findSlicersByExecutionID(clusterState, exIdDict);
const numberOfCalls = list.length;
if (numberOfCalls === 0) {
if (specificId) {
reject({ message: `Could not find active slicer for ex_id: ${specificId}`, code: 404 });
} else {
// for the general slicer stats query, just return a empty array
resolve([]);
}
return;
}
_.each(list, (slicer) => {
const msg = { ex_id: slicer.ex_id };
nodeQueries.push(messaging.send({
to: 'execution_controller',
address: slicer.node_id,
message: 'cluster:slicer:analytics',
payload: msg,
response: true
}));
});
function formatResponse(msg) {
const payload = _.get(msg, 'payload', {});
const identifiers = { ex_id: msg.ex_id, job_id: msg.job_id, name: payload.name };
return Object.assign(identifiers, payload.stats);
}
Promise.all(nodeQueries)
.then((results) => {
clearTimeout(timer);
const formatedData = results.map(formatResponse);
const sortedData = _.sortBy(formatedData, ['name', 'started']);
const reversedData = sortedData.reduce((prev, curr) => {
prev.push(curr);
return prev;
}, []);
resolve(reversedData);
})
.catch(err => reject({ message: parseError(err), code: 500 }));
timer = setTimeout(() => {
reject({ message: 'Timeout has occurred for query', code: 500 });
}, context.sysconfig.teraslice.action_timeout);
}));
};
}
module.exports = {
_iterateState, // Exporting so it can be tested
findAllSlicers,
findWorkersByExecutionID,
findSlicersByExecutionID,
newGetSlicerStats
};
|
JavaScript
| 0.000023 |
@@ -1163,49 +1163,8 @@
) %7B%0A
- // eslint-disable-next-line no-undef%0A
@@ -3194,14 +3194,79 @@
tch(
+(
err
+)
=%3E
+ %7B%0A clearTimeout(timer);%0A
rej
@@ -3309,16 +3309,35 @@
: 500 %7D)
+;%0A %7D
);%0A%0A
|
1709f098aaaaf9358292a107e04795b12a6284cb
|
add another bad args catcher in applyPagination
|
lib/graphql-bookshelf-bridge/util/applyPagination.js
|
lib/graphql-bookshelf-bridge/util/applyPagination.js
|
import { countTotal } from '../../../lib/util/knex'
export const PAGINATION_TOTAL_COLUMN_NAME = '__total'
export default function applyPagination (query, tableName, opts) {
const { first, cursor, order, offset, sortBy = 'id' } = opts
if (cursor && offset) {
throw new Error('Specifying both cursor and offset is not allowed.')
}
query = query.orderBy(sortBy, order)
if (first) {
query = query.limit(first)
query = countTotal(query, tableName, PAGINATION_TOTAL_COLUMN_NAME)
}
if (cursor) {
const op = order === 'asc' ? '>' : '<'
query = query.where(`${tableName}.${sortBy}`, op, cursor)
} else if (offset) {
query.offset(offset)
}
return query
}
|
JavaScript
| 0.000001 |
@@ -324,13 +324,130 @@
not
-allow
+supported.')%0A %7D%0A%0A if (cursor && sortBy !== 'id') %7B%0A throw new Error('Specifying both cursor and sortBy is not support
ed.'
|
1dc3804e06a7e878a8b79407712623ac660a9ffc
|
Fix typo with event
|
lib/middleware/apiGatewayProxyWebsocket/lib/event.js
|
lib/middleware/apiGatewayProxyWebsocket/lib/event.js
|
const smash = require("../../../../smash");
const logger = smash.logger("Event");
const errorUtil = new smash.SmashError(logger);
class Event {
constructor(rawEvent, context, terminate) {
if (typeof rawEvent !== 'object') {
throw new Error("First parameter of Event() must be an object, " + errorUtil.typeOf(rawEvent));
}
if (typeof terminate !== 'object') {
throw new Error("Third parameter of Event() must be a object, " + errorUtil.typeOf(terminate));
}
if (typeof terminate.terminate !== 'function') {
throw new Error("Third parameter of Event() must be an object with a function called terminate, " + errorUtil.typeOf(terminate.terminate));
}
if (terminate.terminate.length !== 2) {
throw new Error("Third parameter of Event() must be an object with a function called terminate witch takes 2 parameters: error, data, " + terminate.terminate.length + " given");
}
this._terminate = terminate;
Object.assign(this, rawEvent);
this._rawEvent = rawEvent;
this.keyword = rawEvent.requestContext.routeKey;
this.connectionId = rawEvent.requestContext.connectionId;
this.headers = event.headers;
/* this.body = null;
if (event.body) {
this.body = JSON.parse(event.body);
} */
/* this.parameters = {};
if (event.queryStringParameters) {
this.parameters = event.queryStringParameters;
} */
this.user = null;
if (event.requestContext && event.requestContext.authorizer && Object.keys(event.requestContext.authorizer).length > 0) {
this.user = Object.assign({}, event.requestContext.authorizer);
}
if (event.requestContext && event.requestContext.requestId) {
this.requestId = event.requestContext.requestId;
}
if (event.requestContext && event.requestContext.identity && event.requestContext.identity.caller) {
if (this.user === null) {
this.user = {};
}
this.user.caller = event.requestContext.identity.caller;
}
if (event.requestContext && event.requestContext.identity && event.requestContext.identity.userArn) {
if (this.user === null) {
this.user = {};
}
this.user.userArn = event.requestContext.identity.userArn;
}
if (event.requestContext && event.requestContext.identity && event.requestContext.identity.user) {
if (this.user === null) {
this.user = {};
}
this.user.user = event.requestContext.identity.user;
}
this.context = context;
}
terminate(error, data) {
this._terminate.terminate(error, data);
return this;
}
success(data) {
this.terminate(null, data);
return this;
}
failure(error) {
this.terminate(error, null);
return this;
}
}
module.exports = Event;
|
JavaScript
| 0.99996 |
@@ -1230,25 +1230,28 @@
s.headers =
-e
+rawE
vent.headers
@@ -1578,33 +1578,36 @@
ll;%0A if (
-e
+rawE
vent.requestCont
@@ -1605,33 +1605,36 @@
questContext &&
-e
+rawE
vent.requestCont
@@ -1663,17 +1663,20 @@
ct.keys(
-e
+rawE
vent.req
@@ -1755,17 +1755,20 @@
ign(%7B%7D,
-e
+rawE
vent.req
@@ -1806,33 +1806,36 @@
%7D%0A if (
-e
+rawE
vent.requestCont
@@ -1833,33 +1833,36 @@
questContext &&
-e
+rawE
vent.requestCont
@@ -1907,17 +1907,20 @@
estId =
-e
+rawE
vent.req
@@ -1956,33 +1956,36 @@
%7D%0A if (
-e
+rawE
vent.requestCont
@@ -1983,33 +1983,36 @@
questContext &&
-e
+rawE
vent.requestCont
@@ -2019,33 +2019,36 @@
ext.identity &&
-e
+rawE
vent.requestCont
@@ -2181,25 +2181,28 @@
er.caller =
-e
+rawE
vent.request
@@ -2240,33 +2240,36 @@
%7D%0A if (
-e
+rawE
vent.requestCont
@@ -2267,33 +2267,36 @@
questContext &&
-e
+rawE
vent.requestCont
@@ -2303,33 +2303,36 @@
ext.identity &&
-e
+rawE
vent.requestCont
@@ -2471,17 +2471,20 @@
erArn =
-e
+rawE
vent.req
@@ -2531,25 +2531,28 @@
if (
-e
+rawE
vent.request
@@ -2558,25 +2558,28 @@
tContext &&
-e
+rawE
vent.request
@@ -2598,17 +2598,20 @@
tity &&
-e
+rawE
vent.req
@@ -2752,17 +2752,20 @@
.user =
-e
+rawE
vent.req
|
88cbdbcaa0069a92271ae7171196162dc7c023ce
|
Use navigator.language
|
src/lib/exceptionist.js
|
src/lib/exceptionist.js
|
var logger = require('./logger')
var transport = require('./transport')
var utils = require('./utils')
module.exports = {
normalizeFrame: function normalizeFrame (frame, options) {
options = options || {}
if (!frame.url) return
// normalize the frames data
var normalized = {
'filename': frame.url,
'lineno': frame.line,
'colno': frame.column,
'function': frame.func || '[anonymous]'
}
return normalized
},
traceKitStackToOpbeatException: function (stackInfo, options) {
options = options || {}
stackInfo.frames = []
if (stackInfo.stack && stackInfo.stack.length) {
stackInfo.stack.forEach(function (stack, i) {
var frame = this.normalizeFrame(stack)
if (frame) {
stackInfo.frames.push(frame)
}
}.bind(this))
}
return stackInfo
},
processException: function processException (exception, options) {
options = options || {}
var stacktrace, label, i
var type = exception.type
var message = exception.message
var fileurl = exception.fileurl
var lineno = exception.lineno
var frames = exception.frames
// In some instances message is not actually a string, no idea why,
// so we want to always coerce it to one.
message += ''
// Sometimes an exception is getting logged in Opbeat.com as
// <no message value>
// This can only mean that the message was falsey since this value
// is hardcoded into Opbeat.com itself.
// At this point, if the message is falsey, we bail since it's useless
if (type === 'Error' && !message) return
if (frames && frames.length) {
fileurl = frames[0].filename || fileurl
// Opbeat.com expects frames oldest to newest
// and JS sends them as newest to oldest
frames.reverse()
stacktrace = {frames: frames}
} else if (fileurl) {
stacktrace = {
frames: [{
filename: fileurl,
lineno: lineno,
in_app: true
}]
}
}
label = lineno ? message + ' at ' + lineno : message
var data = {
exception: {
type: type,
value: message
},
stacktrace: stacktrace,
culprit: fileurl,
message: label
}
var viewportInfo = utils.getViewPortInfo()
var extra = {
'environment': {
'utcOffset': new Date().getTimezoneOffset() / - 60.0,
'browserWidth': viewportInfo.width,
'browserHeight': viewportInfo.height,
'screenWidth': screen.width,
'screenHeight': screen.height,
'userLanguage': navigator.userLanguage,
'userAgent': navigator.userAgent,
'platform': navigator.platform
},
'page': {
'referer': document.referrer,
'host': document.domain,
'location': location.href
}
}
data.extra = extra
logger.log('opbeat.exceptionst.processException', data)
transport.sendToOpbeat(data, options)
}
}
|
JavaScript
| 0.000003 |
@@ -2580,21 +2580,17 @@
'
-userL
+l
anguage'
@@ -2605,13 +2605,9 @@
tor.
-userL
+l
angu
@@ -2691,16 +2691,17 @@
platform
+,
%0A %7D
@@ -2822,16 +2822,17 @@
ion.href
+,
%0A %7D
|
ab0618427f30278f5529d427e6e7ba39633e523e
|
Correct mergeSchemas signature
|
src/lib/mergeSchemas.js
|
src/lib/mergeSchemas.js
|
import urljoin from "url-join"
import {
mergeSchemas as _mergeSchemas,
introspectSchema,
makeRemoteExecutableSchema,
} from "graphql-tools"
import { ApolloLink } from "apollo-link"
import { createHttpLink } from "apollo-link-http"
import { setContext } from "apollo-link-context"
import fetch from "node-fetch"
import localSchema from "../schema"
import { headers as requestIDHeaders } from "./requestIDs"
import config from "config"
const { CONVECTION_API_BASE } = config
export function createConvectionLink() {
const httpLink = createHttpLink({
fetch,
uri: urljoin(CONVECTION_API_BASE, "graphql"),
})
const middlewareLink = new ApolloLink((operation, forward) =>
forward(operation)
)
const authMiddleware = setContext((_request, context) => {
const locals = context.graphqlContext && context.graphqlContext.res.locals
const tokenLoader = locals && locals.dataLoaders.convectionTokenLoader
const headers = { ...(locals && requestIDHeaders(locals.requestIDs)) }
// If a token loader exists for Convection (i.e. this is an authenticated request), use that token to make
// authenticated requests to Convection.
if (tokenLoader) {
return tokenLoader().then(({ token }) => ({
headers: Object.assign(headers, { Authorization: `Bearer ${token}` }),
}))
}
// Otherwise use no authentication, which is also meant for fetching the service’s (public) schema.
return { headers }
})
return middlewareLink.concat(authMiddleware).concat(httpLink)
}
export async function mergeSchemas() {
const convectionLink = createConvectionLink()
const convectionSchema = await makeRemoteExecutableSchema({
schema: await introspectSchema(convectionLink),
link: convectionLink,
})
const linkTypeDefs = `
extend type Submission {
artist: Artist
}
`
const mergedSchema = _mergeSchemas({
schemas: [localSchema, convectionSchema, linkTypeDefs],
// Prefer others over the local MP schema.
onTypeConflict: (_leftType, rightType) => {
console.warn(`[!] Type collision ${rightType}`) // eslint-disable-line no-console
return rightType
},
resolvers: {
Submission: {
artist: {
fragment: `fragment SubmissionArtist on Submission { artist_id }`,
resolve: (parent, args, context, info) => {
const id = parent.artist_id
return info.mergeInfo.delegateToSchema(
localSchema,
"query",
"artist",
{ id },
context,
info
)
},
},
},
},
})
mergedSchema.__allowedLegacyNames = ["__id"]
return mergedSchema
}
|
JavaScript
| 0.000002 |
@@ -1903,38 +1903,141 @@
s: %5B
-localSchema, convectionSchema,
+%0A %7B name: %22local%22, schema: localSchema %7D,%0A %7B name: %22convection%22, schema: convectionSchema %7D,%0A %7B name: %22links%22, schema:
lin
@@ -2045,16 +2045,24 @@
TypeDefs
+ %7D,%0A
%5D,%0A /
|
471871ba295c3075c6f20d7021e2263c6606b29b
|
Allow string value in Value.
|
src/js/components/Value.js
|
src/js/components/Value.js
|
// (C) Copyright 2016 Hewlett Packard Enterprise Development LP
import React, { Component, PropTypes } from 'react';
const CLASS_ROOT = "value";
export default class Value extends Component {
render () {
const classes = [CLASS_ROOT];
if (this.props.size) {
classes.push(`${CLASS_ROOT}--${this.props.size}`);
}
if (this.props.align) {
classes.push(`${CLASS_ROOT}--align-${this.props.align}`);
}
if (this.props.onClick) {
classes.push(`${CLASS_ROOT}--interactive`);
}
if (this.props.colorIndex) {
classes.push(`color-index-${this.props.colorIndex}`);
}
if (this.props.className) {
classes.push(this.props.className);
}
let units;
if (this.props.units) {
units = (
<span className={`${CLASS_ROOT}__units`}>
{this.props.units}
</span>
);
}
let label;
if (this.props.label) {
label = (
<span className={`${CLASS_ROOT}__label`}>
{this.props.label}
</span>
);
}
return (
<div className={classes.join(' ')} onClick={this.props.onClick}>
<div className={`${CLASS_ROOT}__annotated`}>
{this.props.icon}
<span className={`${CLASS_ROOT}__value`}>
{this.props.value}
</span>
{units}
{this.props.trendIcon}
</div>
{label}
</div>
);
}
}
Value.propTypes = {
align: PropTypes.oneOf(['start', 'center', 'end']),
colorIndex: PropTypes.string,
icon: PropTypes.node,
label: PropTypes.string,
onClick: PropTypes.func,
size: PropTypes.oneOf(['small', 'medium', 'large', 'xlarge']),
trendIcon: PropTypes.node,
value: PropTypes.number.isRequired,
units: PropTypes.string
};
Value.defaultProps = {
align: 'center'
};
|
JavaScript
| 0.000007 |
@@ -1708,14 +1708,55 @@
pes.
-number
+oneOfType(%5BPropTypes.number, PropTypes.string%5D)
.isR
|
166cc9919188d43a1f4bedbace5282480b9dd467
|
Fix tabs
|
lime/src/audio/audiomap.js
|
lime/src/audio/audiomap.js
|
goog.provide('lime.audio.AudioMap');
goog.require('goog.events');
goog.require('lime.userAgent');
goog.require('jukebox.Manager');
goog.require('jukebox.Player');
/**
* AudioMap object
* @constructor
* @param {object} config Configuration object.
*/
lime.audio.AudioMap = function(config) {
if (config.data && goog.isFunction(config.data)) {
config = config.data();
}
this.config = config;
if (lime.userAgent.IOS || lime.userAgent.WINPHONE) {
goog.events.listenOnce(window, lime.userAgent.SUPPORTS_TOUCH ? 'touchstart' : 'mousedown', this._initPlayer, true, this);
}
else {
this._initPlayer();
}
};
lime.audio.AudioMap.prototype._initPlayer = function() {
this.player = new jukebox.Player(this.config);
}
/**
* Start playing the audio
* @param {string} sprite Sprite name to play.
*/
lime.audio.AudioMap.prototype.play = function(sprite) {
if (this.player && this.config.spritemap[sprite]) {
this.player.play(sprite);
}
};
/**
* Stop playing the audio
*/
lime.audio.AudioMap.prototype.stop = function() {
if (this.player) {
this.player.pause();
}
};
|
JavaScript
| 0.000002 |
@@ -286,25 +286,28 @@
n(config) %7B%0A
-%09
+
if (config.d
@@ -345,18 +345,24 @@
ata)) %7B%0A
-%09%09
+
config =
@@ -377,20 +377,26 @@
data();%0A
-%09%7D%0A%09
+ %7D%0A
this.con
@@ -413,11 +413,17 @@
ig;%0A
-%09%0A%09
+ %0A
if (
@@ -471,18 +471,24 @@
HONE) %7B%0A
-%09%09
+
goog.eve
@@ -605,21 +605,33 @@
s);%0A
-%09%7D%0A%09else %7B%0A%09%09
+ %7D%0A else %7B%0A
this
@@ -642,25 +642,28 @@
itPlayer();%0A
-%09
+
%7D%0A%7D;%0A%0Alime.a
@@ -713,17 +713,20 @@
ion() %7B%0A
-%09
+
this.pla
@@ -902,25 +902,28 @@
n(sprite) %7B%0A
-%09
+
if (this.pla
@@ -958,26 +958,32 @@
%5Bsprite%5D) %7B%0A
-%09%09
+
this.player.
@@ -996,17 +996,20 @@
prite);%0A
-%09
+
%7D%0A%7D;%0A%0A/*
@@ -1090,17 +1090,20 @@
ion() %7B%0A
-%09
+
if (this
@@ -1117,10 +1117,16 @@
) %7B%0A
-%09%09
+
this
@@ -1146,9 +1146,12 @@
();%0A
-%09
+
%7D%0A%7D;
|
e37382c814eda6e6e3e4a72254968d2e89c0bb9e
|
Manage close token
|
src/knockout_tokenfield.js
|
src/knockout_tokenfield.js
|
;(function(factory) {
//CommonJS
if (typeof require === "function" && typeof exports === "object" && typeof module === "object") {
factory(require("knockout"), require("jQuery"), exports);
//AMD
} else if (typeof define === "function" && define.amd) {
define(["knockout", "jQuery", "exports"], factory);
//normal script tag
} else {
factory(ko, $);
}
}(function(ko, $) {
function updater(state,cb){
if (state.updating)
return;
state.updating=true;
cb();
state.updating=false;
}
ko.bindingHandlers.tokenfield = {
init: function(element, valueAccessor, allBindings) {
var $element=$(element), value= valueAccessor(),
tokens = value.tokens, options = allBindings.get('tokenfieldOptions'), state ={updating:false},
display = options.display, tokenoptions = value.predefined,
tokenFactory =value.tokenFactory || function(){return null;},
counterCount = 0, finder = options.finder, typeaheadSource;
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
$element.tokenfield('destroy');
});
$element.data('tokenfield_ko_options',options);
$element.data('tokenfield_ko_state',state);
if (!finder){
var localsource = new Bloodhound({
datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d.label);},
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: $.map(tokenoptions,function(el){return {value:el,label:el[display]};})
});
localsource.initialize();
typeaheadSource =localsource.ttAdapter();
}
else{
typeaheadSource = function (query, syncResults, asyncResults){
finder(query).then(function(val){
asyncResults($.map(val,function(el){return {value:el,label:el[display]};}));
});
};
}
options.typeahead =[options.typeahead || null,{displayKey:'label',source:typeaheadSource}];
$element.tokenfield(options)
.on('tokenfield:createtoken', function (e) {
if ((state.updating) || (e.fromSelection))
return true;
//set temp label
e.attrs.value = counterCount;
var created = (function(count){
return tokenFactory(e.attrs.label,function(res){
$.each($element.tokenfield('getTokens'),function(index,element){
if (element.value===count){
if (res===null){
}
else{
element.value=res;
element.label = res[display];
}
}
});
});
})(counterCount);
counterCount++;
if (created===null)
e.preventDefault();
else if (typeof(created) != 'undefined'){
e.attrs.value = created;
}
})
.on('tokenfield:createdtoken', function (e) {
updater(state,function(){
var value = e.attrs.value;
if (value){
tokens.push(value);
console.log(value);
}
});
})
.on('tokenfield:editedtoken', function (e) {
})
.on('tokenfield:edittoken', function (e) {
})
.on('tokenfield:removetoken', function (e) {
updater(state,function(){
tokens.splice($(e.relatedTarget).index(),1);
});
}).
on('tokenfield:sortedtoken', function (e) {
updater(state,function(){
var element = tokens()[e.oldPosition];
tokens.splice(e.oldPosition,1);
tokens.splice(e.newPosition,0,element);
});
});
},
update: function(element, valueAccessor, allBindingsAccessor, deprecated, bindingContext) {
var $element=$(element), options= $element.data('tokenfield_ko_options'),
value = ko.utils.unwrapObservable(valueAccessor()) || [], display = options.display;
console.log('update');
updater($element.data('tokenfield_ko_state'),function(){
$element.tokenfield('setTokens', $.map(value.tokens(),function(el){
return {value:el, label:ko.utils.unwrapObservable(el[display])};
}) );
});
}
};
}));
|
JavaScript
| 0.000001 |
@@ -3211,75 +3211,12 @@
ount
+++
);
-%0A%0A counterCount++;%0A
%0A%0A
|
95847e2d74258dd02b8cf32e185540b4802892d5
|
Refresh friends list on login
|
project/src/js/ui/loginModal.js
|
project/src/js/ui/loginModal.js
|
import session from '../session';
import push from '../push';
import challengesApi from '../lichess/challenges';
import * as utils from '../utils';
import * as helper from './helper';
import i18n from '../i18n';
import signupModal from './signupModal';
import backbutton from '../backbutton';
import * as m from 'mithril';
const loginModal = {};
var isOpen = false;
function submit(form) {
const login = form[0].value.trim();
const pass = form[1].value;
if (!login || !pass) return false;
window.cordova.plugins.Keyboard.close();
return session.login(login, pass)
.then(function() {
loginModal.close();
window.plugins.toast.show(i18n('loginSuccessful'), 'short', 'center');
push.register();
challengesApi.refresh();
session.refresh()
.catch(err => {
if (err.response && err.response.status === 401) {
window.navigator.notification.alert('Lichess authentication cannot work without cookies enabled. Please make sure cookies are authorized.');
}
});
})
.catch(utils.handleXhrError);
}
loginModal.open = function() {
backbutton.stack.push(helper.slidesOutDown(loginModal.close, 'loginModal'));
isOpen = true;
};
loginModal.close = function(fromBB) {
window.cordova.plugins.Keyboard.close();
if (fromBB !== 'backbutton' && isOpen) backbutton.stack.pop();
isOpen = false;
};
loginModal.view = function() {
if (!isOpen) return null;
return m('div.modal#loginModal', { oncreate: helper.slidesInUp }, [
m('header', [
m('button.modal_close[data-icon=L]', {
oncreate: helper.ontap(helper.slidesOutDown(loginModal.close, 'loginModal'))
}),
m('h2', i18n('signIn'))
]),
m('div.modal_content', [
m('form.login', {
onsubmit: function(e) {
e.preventDefault();
return submit(e.target);
}
}, [
m('input#pseudo[type=text]', {
placeholder: i18n('username'),
autocomplete: 'off',
autocapitalize: 'off',
autocorrect: 'off',
spellcheck: false,
required: true
}),
m('input#password[type=password]', {
placeholder: i18n('password'),
required: true
}),
m('button.fat', i18n('signIn'))
]),
m('div.signup', [
m('a', {
oncreate: helper.ontap(signupModal.open)
}, [i18n('newToLichess'), ' ', i18n('signUp')])
])
])
]);
};
export default loginModal;
|
JavaScript
| 0 |
@@ -23,24 +23,56 @@
./session';%0A
+import socket from '../socket';%0A
import push
@@ -718,24 +718,92 @@
'center');%0A
+ // reconnect socket to refresh friends...%0A socket.connect();%0A
push.reg
|
8a1d9eb96a3cf191d24f734cd0a2bffd852567dd
|
Move comment around
|
src/scripts/browser/components/native-notifier/impl-darwin.js
|
src/scripts/browser/components/native-notifier/impl-darwin.js
|
/* eslint-disable babel/new-cap */
import $ from 'nodobjc';
import BaseNativeNotifier from 'browser/components/native-notifier/base';
class DarwinNativeNotifier extends BaseNativeNotifier {
constructor () {
super();
// Flag that this notifier has been implemented
this.isImplemented = true;
// Obj-C setup
$.framework('Foundation');
const pool = $.NSAutoreleasePool('alloc')('init'); // eslint-disable-line no-unused-vars
// Get the notification center
this.center = $.NSUserNotificationCenter('defaultUserNotificationCenter');
// Create a notifications delegate
this.Delegate = $.NSObject.extend(global.manifest.productName + 'NotificationDelegate');
this.Delegate.addMethod('userNotificationCenter:didActivateNotification:',
[$.void, [this.Delegate, $.selector, $.id, $.id]], ::this.didActivateNotification);
this.Delegate.addMethod('userNotificationCenter:shouldPresentNotification:',
['c', [this.Delegate, $.selector, $.id, $.id]], ::this.shouldPresentNotification);
this.Delegate.register();
// Set the delegate
this.delegate = this.Delegate('alloc')('init');
this.center('setDelegate', this.delegate);
}
shouldPresentNotification (self, cmd, center, notif) {
log('shouldPresentNotification', notif('identifier'), 'true');
return true;
}
didActivateNotification (self, cmd, center, notif) {
const type = parseInt(notif('activationType').toString(), 10);
const identifier = notif('identifier').toString();
const tag = identifier.split(':::')[0];
const payload = {
tag,
type: DarwinNativeNotifier.ACTIVATION_TYPES[type],
identifier
};
if (payload.type === 'replied') {
payload.response = notif('response');
if (payload.response) {
payload.response = payload.response.toString().replace('{\n}', '');
}
}
log('didActivateNotification', JSON.stringify(payload));
this.emit('notif-activated-' + identifier, payload);
this.emit('notif-activated', payload);
}
fireNotification ({title, subtitle, body, tag = title, canReply, icon, onClick, onCreate}) {
const identifier = tag + ':::' + Date.now();
const data = {title, subtitle, body, tag, canReply, onClick, onCreate, identifier};
// Create
const notification = $.NSUserNotification('alloc')('init');
notification('setTitle', $.NSString('stringWithUTF8String', title));
notification('setIdentifier', $.NSString('stringWithUTF8String', identifier));
notification('setHasReplyButton', !!canReply);
if (subtitle) {
const str = $.NSString('stringWithUTF8String', subtitle);
notification('setSubtitle', str);
}
if (body) {
const str = $.NSString('stringWithUTF8String', body);
notification('setInformativeText', str);
}
if (icon) {
const contentImageUrl = $.NSURL('URLWithString', $(icon));
const contentImage = $.NSImage('alloc')('initByReferencingURL', contentImageUrl);
notification('setContentImage', contentImage);
}
// Deliver
log('delivering notification', JSON.stringify(data));
this.center('deliverNotification', notification);
// Click callback
if (onClick) {
this.on('notif-activated-' + identifier, onClick);
}
// Creation callback
if (onCreate) {
onCreate(data);
}
}
removeNotification (identifier) {
const deliveredNotifications = this.center('deliveredNotifications');
for (let i = 0; i < deliveredNotifications('count'); i++) {
const deliveredNotif = deliveredNotifications('objectAtIndex', $(i)('unsignedIntValue'));
const deliveredIdentifier = deliveredNotif('identifier');
if (deliveredIdentifier && deliveredIdentifier.toString() === identifier) {
log('removing notification', identifier, deliveredNotif);
this.center('removeDeliveredNotification', deliveredNotif);
break;
}
}
}
}
export default DarwinNativeNotifier;
|
JavaScript
| 0 |
@@ -1,39 +1,4 @@
-/* eslint-disable babel/new-cap */%0A
impo
@@ -94,16 +94,51 @@
base';%0A%0A
+/* eslint-disable babel/new-cap */%0A
class Da
@@ -357,22 +357,21 @@
');%0A
-const
+this.
pool = $
@@ -410,46 +410,8 @@
t');
- // eslint-disable-line no-unused-vars
%0A%0A
|
116a58a2763831858aa34d46f64e8c46a860c1dd
|
Use wall time, not a timer
|
src/main/webapp/js/tile.js
|
src/main/webapp/js/tile.js
|
var Tile = function(sprite) {
this.sprite_ = sprite;
sprite.anchor.set(0.5);
sprite.width = Tile.WIDTH;
sprite.height = Tile.HEIGHT;
sprite.inputEnabled = true;
sprite.events.onInputDown.add(this.listener_, this);
sprite.events.onInputOver.add(this.showTimer_, this);
sprite.events.onInputOut.add(this.hideTimer_, this);
this.level_ = 0;
this.timer_ = game.time.create(false);
this.timer_.add(11000, this.finish_, this);
this.text_ = game.add.text(this.sprite_.x, this.sprite_.y, '', { fill: '#ffffff' });
this.text_.anchor.set(0.5);
this.text_.visible = false;
// TODO: move to subclasses.
this.color_ = 0xffffff;
this.color_inc_ = 0x202000;
};
Tile.WIDTH = 64;
Tile.HEIGHT = 64;
Tile.prototype.update = function() {
if (this.timer_.running) {
this.text_.text = this.getLevelTime_() - Math.floor(this.timer_.ms / 1000);
}
};
Tile.prototype.listener_ = function() {
if (this.timer_.running) {
return;
}
this.text_.visible = true;
this.timer_.start();
this.color_ -= this.color_inc_;
this.sprite_.tint = this.color_;
};
Tile.prototype.showTimer_ = function() {
this.text_.visible = true;
};
Tile.prototype.hideTimer_ = function() {
this.text_.visible = false;
};
Tile.prototype.getLevelTime_ = function() {
var time = [10, 100, 1000, 10000];
return time[this.level_];
};
Tile.prototype.finish_ = function() {
this.timer_.stop();
this.level_++;
this.text_.visible = false;
};
|
JavaScript
| 0.001895 |
@@ -376,94 +376,109 @@
-this.timer_ = game.time.create(false);%0A this.timer_.add(11000, this.finish_, this);
+// If there is a timer running for this tile.%0A this.timer_ = false;%0A // The text for the timer.
%0A
@@ -813,32 +813,24 @@
(this.timer_
-.running
) %7B%0A
@@ -833,89 +833,397 @@
-this.text_.text = this.getLevelTime_() - Math.floor(this.timer_.ms / 1000);%0A %7D
+var secsRemaining = this.getLatencySecs() -%0A Math.floor((new Date().getTime() - this.start_ms_) / 1000);%0A if (secsRemaining == 0) %7B%0A this.timer_ = false;%0A this.finish_();%0A %7D%0A this.text_.text = secsRemaining;%0A %7D%0A%7D;%0A%0ATile.prototype.getLatencySecs = function() %7B%0A var time = %5B10, 100, 1000, 10000%5D;%0A return time%5Bthis.level_%5D;
%0A%7D;%0A
@@ -1286,16 +1286,8 @@
mer_
-.running
) %7B%0A
@@ -1304,24 +1304,201 @@
turn;%0A %7D%0A
+ this.timer_ = true;%0A // We don't use the in-game timer because we don't want pausing/switching%0A // tabs to pause the timer.%0A this.start_ms_ = new Date().getTime();%0A
this.tex
@@ -1520,33 +1520,8 @@
ue;%0A
- this.timer_.start();%0A
@@ -1765,171 +1765,30 @@
ype.
-getLevelTime_ = function() %7B%0A var time = %5B10, 100, 1000, 10000%5D;%0A return time%5Bthis.level_%5D;%0A%7D;%0A%0ATile.prototype.finish_ = function() %7B%0A this.timer_.stop();
+finish_ = function() %7B
%0A
|
fc93c675abff814d9c9c52e46e088c8be68f64fd
|
Fix to page scrolling
|
SideTube.user.js
|
SideTube.user.js
|
// ==UserScript==
// @name SideTube
// @namespace dairful
// @version 0.0.1
// @description Reorder content panels and resize panels into a scrollable panel
// @author Dairful
// @include *://www.youtube.com/*
// @grant none
// @require http://code.jquery.com/jquery-latest.js
// @downloadURL https://github.com/Dairful/SideTube/raw/master/SideTube.user.js
// ==/UserScript==
function main(){
// Check if current page is a video page
if($("#page").hasClass("watch")){
// Reorder content panels
$("#watch7-sidebar-contents").before($("#watch-discussion"));
$("#watch-discussion").after($("#watch7-sidebar-contents"));
$("#watch7-sidebar-contents").after($("#watch-discussion"));
// CSS modifications
$("#watch-discussion").css({"height":"auto",
"max-height":"550px",
"overflow":"auto",
"overflow-x":"hidden"});
$("#action-panel-details").css({"height":"auto",
"max-height":"550px",
"overflow":"auto"});
$("#watch7-sidebar-contents").css({"height":"auto",
"min-height":"153px",
"max-height":"153px",
"overflow":"auto"});
}
}
main();
$(document).on("spfdone", main);
|
JavaScript
| 0.00001 |
@@ -83,17 +83,17 @@
0.0.
-1
+2
%0A// @des
@@ -521,41 +521,23 @@
-// Reorder content panels%0A
+ var $upnext =
$(%22
@@ -566,16 +566,34 @@
ts%22)
-.before(
+;%0A var $comments =
$(%22#
@@ -602,33 +602,32 @@
tch-discussion%22)
-)
;%0A $(%22#wa
@@ -624,114 +624,149 @@
-$(%22#watch-discussion%22).after($(%22#watch7-sidebar-contents%22));%0A $(%22#watch7-sidebar-cont
+var $description = $(%22#action-panel-details%22);%0A // Reorder content panels%0A $upnext.before($comments);%0A $comm
ents
-%22)
.after($
(%22#w
@@ -765,32 +765,53 @@
er($
-(%22#watch-discussion%22)
+upnext);%0A $upnext.after($comments
);%0A
+
@@ -836,39 +836,68 @@
ions
-%0A $(%22#watch-discussion%22)
+ (could be put in CSS using Stylish instead)%0A $upnext
.css
@@ -926,32 +926,58 @@
+ %22min-height%22:%22153px%22, %0A
@@ -987,35 +987,35 @@
%22max-height%22:%22
-550
+153
px%22, %0A
@@ -1017,32 +1017,145 @@
+%22overflow%22:%22auto%22%7D);%0A $comments.css(%7B%22height%22:%22auto%22, %0A %22max-height%22:%22550px%22, %0A
@@ -1176,32 +1176,16 @@
auto%22, %0A
-
@@ -1237,33 +1237,19 @@
$
-(%22#action-panel-details%22)
+description
.css
@@ -1294,33 +1294,16 @@
-
-
%22max-hei
@@ -1317,33 +1317,16 @@
50px%22, %0A
-
@@ -1376,150 +1376,321 @@
-$(%22#watch7-sidebar-contents%22).css(%7B%22height%22:%22auto%22, %0A %22min-height%22:%22153px%22, %0A
+// Prevent page scroll when textbox scrolls to bottom%0A $upnext.bind( 'mousewheel DOMMouseScroll', function ( e ) %7B%0A var e0 = e.originalEvent,%0A delta = e0.wheelDelta %7C%7C -e0.detail;%0A%0A this.scrollTop += ( delta %3C 0 ? 1 : -1 ) * 30;%0A e.preventDefault();%0A
@@ -1681,32 +1681,36 @@
();%0A
+%7D);%0A
@@ -1701,112 +1701,261 @@
- %22max-height%22:%22153px%22, %0A %22overflow%22:%22auto%22
+$comments.bind( 'mousewheel DOMMouseScroll', function ( e ) %7B%0A var e0 = e.originalEvent,%0A delta = e0.wheelDelta %7C%7C -e0.detail;%0A%0A this.scrollTop += ( delta %3C 0 ? 1 : -1 ) * 30;%0A e.preventDefault();%0A
%7D);%0A
@@ -2003,8 +2003,9 @@
, main);
+%0A
|
462523fc8bbc30eb70a5062ff5e5399e7a2f6a88
|
add documentations
|
src/main/webapp/components/directives/peptideViewer-directive/peptideViewer-directive.js
|
src/main/webapp/components/directives/peptideViewer-directive/peptideViewer-directive.js
|
/**
* @author Jose A. Dianes <[email protected]>
*
* The prc-peptide-viewer directive allows us to reuse a list of Peptides everywhere we want to show it (e.g.
* in the clusterDetail-view)
*
*/
var peptideViewerDirective = angular.module('prideClusterApp.peptideViewerDirective', ['ngTable']);
peptideViewerDirective.directive('prcPeptideViewer', function () {
return {
restrict: 'EA',
scope: {
clusterId: '=clusterid'
},
controller: 'PeptideViewerCtrl',
//link: link,
templateUrl: 'components/directives/peptideViewer-directive/peptideViewer-directive.html'
};
});
peptideViewerDirective.controller("PeptideViewerCtrl", ['$scope', '$filter', 'ClusterPeptides', 'ngTableParams', function($scope, $filter, ClusterPeptides, ngTableParams) {
$scope.peptides = [];
$scope.getPeptides = function() {
ClusterPeptides.get(
{clusterId: $scope.clusterId},
function (data) {
$scope.peptides = data.clusteredPeptides;
// here we create a simplified modification list for each peptide that is used for
// showing tooltips as required by the <prc-peptide-sequence-viewer> directive
for (j = 0; j < $scope.peptides.length; j++) {
var peptide = $scope.peptides[j];
peptide.mods = [];
if (peptide.modifications != null) {
for (i = 0; i < peptide.modifications.length; i++) {
peptide.mods[peptide.modifications[i].mainPosition - 1] = peptide.modifications[i].name;
}
}
}
$scope.tableParams.reload();
}
);
};
$scope.tableParams = new ngTableParams({
page: 1, // show first page
count: 10, // count per page
sorting: {
numberOfPSMs: 'desc'
}
}, {
total: $scope.peptides.length, // length of data
getData: function($defer, params) {
// use build-in angular filter
var orderedData = params.sorting() ?
$filter('orderBy')($scope.peptides, params.orderBy()) :
data;
params.total(orderedData.length);
$scope.peptides_slice = orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count());
$defer.resolve($scope.peptides_slice);
}
});
}]);
|
JavaScript
| 0 |
@@ -817,30 +817,147 @@
-$scope.peptides = %5B%5D;%0A
+// init an empty array of peptides%0A $scope.peptides = %5B%5D;%0A%0A // function to be called at init to get peptides using remote web service
%0A
@@ -1901,16 +1901,66 @@
%7D;%0A%0A
+ // setup ng-table with sorting and pagination%0A
$sco
|
3d8703d5aa344d6a94ce6dfec9de3dd5da21d389
|
test getTokenFromHeader
|
api/src/routes/utils/__tests__/get-token-from-header.js
|
api/src/routes/utils/__tests__/get-token-from-header.js
|
// Things to know:
// - `test` is a global function from Jest:
// `test(messageString, testerFunction)`
// Learn more here: https://facebook.github.io/jest/docs/api.html#testname-fn
// - `expect` is a global function from Jest
// which allows you to make assertsions. For
// example:
// `expect(1).toBe(1)`
// Learn more here: https://facebook.github.io/jest/docs/expect.html
//
// Write unit tests for getTokenFromHeader.
// See `api/src/routes/utils/get-token-from-header.js`
// to see how this function has been implemented and
// how it's intended to be used. Write at least two unit
// tests to ensure that that use case is always supported.
import getTokenFromHeader from '../get-token-from-header'
test('this is the title of your test', () => {
// this is where you put your test code. Write code that will
// throw an error if getTokenFromHeader has a bug. The `expect`
// global is a utility that makes writting such assertions easier,
// but you can do it however you like.
})
//////// Elaboration & Feedback /////////
// When you've finished with the exercises:
// 1. Copy the URL below into your browser and fill out the form
// 2. remove the `.skip` from the test below
// 3. Change submitted from `false` to `true`
// 4. And you're all done!
/*
http://ws.kcd.im/?ws=Testing&e=API%20Unit&[email protected]*/
test.skip('I submitted my elaboration and feedback', () => {
const submitted = false // change this when you've submitted!
expect(true).toBe(submitted)
})
////////////////////////////////
|
JavaScript
| 0.000001 |
@@ -1,420 +1,171 @@
-// Things to know:%0A// - %60test%60 is a global function from Jest:%0A// %60test(messageString, testerFunction)%60%0A// Learn more here: https://facebook.github.io/jest/docs/api.html#testname-fn%0A// - %60expect%60 is a global function from Jest%0A// which allows you to make assertsions. For%0A// example:%0A// %60expect(1).toBe(1)%60%0A// Learn more here: https://facebook.github.io/jest/docs/expect.html%0A//%0A// Write unit tests for
+import getTokenFromHeader from '../get-token-from-header'%0A%0Atest('getTokenFromHeader returns null if there is no token', () =%3E %7B%0A const req = getReq()%0A const result =
get
@@ -183,582 +183,369 @@
ader
-.%0A// See %60api/src/routes/utils/get-t
+(req)%0A expect(result).toBeNull()%0A%7D)%0A%0Atest('getT
oken
--from-h
+FromH
eader
-.js%60%0A// to see how this function has been implemented and%0A// how it's intended to be used. Write at least two unit%0A// te
+ returns the token when provided', () =%3E %7B%0A con
st
-s
to
- ensure that that use case is always supported.%0Aimport getTokenFromHeader from '../get-token-from-header'%0A%0Atest('this is the title of your test', () =%3E %7B%0A // this is where you put your test code. Write code that will%0A // throw an error if getTokenFromHeader has a bug. The %60expect%60%0A // global is a utility that makes writting such assertions easier,%0A // but you can do it however you like.
+ken = 'some.token.thing'%0A const authorization = %60Token $%7Btoken%7D%60%0A const req = getReq(authorization)%0A const result = getTokenFromHeader(req)%0A expect(result).toBe(token)%0A%7D)%0A%0Afunction getReq(authorization) %7B%0A return %7Bheaders: %7Bauthorization%7D%7D
%0A%7D
-)
%0A%0A//
@@ -883,21 +883,16 @@
m*/%0Atest
-.skip
('I subm
@@ -955,20 +955,19 @@
itted =
-fals
+tru
e // cha
|
d0bb38916fb17a92bc312630b633b419e84d6734
|
Use $apply() in ngChanged to immediately propagate model changes.
|
app/assets/javascripts/angular/directives/ng_changed.js
|
app/assets/javascripts/angular/directives/ng_changed.js
|
angular.module("Prometheus.directives").directive('ngChanged', function() {
return {
restrict: "A",
link: function(scope, element, attrs) {
element.bind("change", function() {
scope.$eval(attrs.ngChanged);
});
}
};
});
|
JavaScript
| 0 |
@@ -204,12 +204,13 @@
pe.$
-eval
+apply
(att
|
246f77c98d48df011a2e80ae5d33bee1104b6366
|
tweak positioning when it has no room to right
|
app/assets/javascripts/discourse/views/user-card.js.es6
|
app/assets/javascripts/discourse/views/user-card.js.es6
|
import CleansUp from 'discourse/mixins/cleans-up';
var clickOutsideEventName = "mousedown.outside-user-card",
clickDataExpand = "click.discourse-user-card",
clickMention = "click.discourse-user-mention";
export default Discourse.View.extend(CleansUp, {
elementId: 'user-card',
classNameBindings: ['controller.visible::hidden', 'controller.showBadges', 'controller.hasCardBadgeImage'],
allowBackgrounds: Discourse.computed.setting('allow_profile_backgrounds'),
addBackground: function() {
var url = this.get('controller.user.card_background');
if (!this.get('allowBackgrounds')) { return; }
var $this = this.$();
if (!$this) { return; }
if (Ember.empty(url)) {
$this.css('background-image', '').addClass('no-bg');
} else {
$this.css('background-image', "url(" + url + ")").removeClass('no-bg');
}
}.observes('controller.user.card_background'),
_setup: function() {
var self = this;
this.appEvents.on('poster:expand', this, '_posterExpand');
$('html').off(clickOutsideEventName).on(clickOutsideEventName, function(e) {
if (self.get('controller.visible')) {
var $target = $(e.target);
if ($target.closest('[data-user-card]').data('userCard') ||
$target.closest('a.mention').length > 0 ||
$target.closest('#user-card').length > 0) {
return;
}
self.get('controller').close();
}
return true;
});
var expand = function(username, $target){
self._posterExpand($target);
self.get('controller').show(username, $target[0]);
return false;
};
$('#main-outlet').on(clickDataExpand, '[data-user-card]', function(e) {
var $target = $(e.currentTarget);
var username = $target.data('user-card');
return expand(username, $target);
});
$('#main-outlet').on(clickMention, 'a.mention', function(e) {
var $target = $(e.target);
var username = $target.text().replace(/^@/, '');
return expand(username, $target);
});
}.on('didInsertElement'),
_posterExpand: function(target) {
if (!target) { return; }
var self = this,
width = this.$().width();
Em.run.schedule('afterRender', function() {
if (target) {
var position = target.offset();
if (position) {
position.left += target.width() + 10;
var overage = ($(window).width() - 50) - (position.left + width);
if (overage < 0) {
position.left += overage;
position.top += target.height() + 5;
}
position.top -= $('#main-outlet').offset().top;
self.$().css(position);
}
}
});
},
cleanUp: function() {
this.get('controller').close();
},
_removeEvents: function() {
$('html').off(clickOutsideEventName);
$('#main').off(clickDataExpand);
$('#main').off(clickMention);
this.appEvents.off('poster:expand', this, '_posterExpand');
}.on('willDestroyElement')
});
|
JavaScript
| 0 |
@@ -2500,18 +2500,25 @@
eft
-+= overage
+-= (width/2) - 10
;%0A
@@ -2561,17 +2561,17 @@
ght() +
-5
+8
;%0A
|
932e7eac2f0d1a58e5e93792331543985bd0e7ba
|
fix eslint error
|
test/unit/directives/mwlCalendarHourList.spec.js
|
test/unit/directives/mwlCalendarHourList.spec.js
|
'use strict';
var angular = require('angular'),
moment = require('moment');
describe('mwlCalendarHourList directive', function() {
var MwlCalendarCtrl,
element,
scope,
$rootScope,
directiveScope,
calendarConfig,
showModal,
clock,
template =
'<mwl-calendar-hour-list ' +
'day-view-start="dayViewStart" ' +
'day-view-end="dayViewEnd" ' +
'day-view-split="dayViewSplit || 30" ' +
'on-event-times-changed="eventDropped(calendarEvent, calendarDate, calendarNewEventStart, calendarNewEventEnd)" ' +
'cell-modifier="cellModifier"' +
'day-width="dayWidth"' +
'view="{{ view }}"' +
'></mwl-calendar-hour-list>';
function prepareScope(vm) {
//These variables MUST be set as a minimum for the calendar to work
vm.dayViewStart = '06:00';
vm.dayViewEnd = '22:59';
vm.dayViewsplit = 30;
vm.cellModifier = sinon.stub();
vm.view = 'day';
showModal = sinon.spy();
vm.onEventClick = function(event) {
showModal('Clicked', event);
};
vm.onEventTimesChanged = function(event) {
showModal('Dropped or resized', event);
};
}
beforeEach(angular.mock.module('mwl.calendar'));
beforeEach(angular.mock.inject(function($compile, _$rootScope_, _calendarConfig_) {
calendarConfig = _calendarConfig_;
clock = sinon.useFakeTimers(new Date('October 20, 2015 11:10:00').getTime());
$rootScope = _$rootScope_;
scope = $rootScope.$new();
prepareScope(scope);
element = $compile(template)(scope);
scope.$apply();
directiveScope = element.isolateScope();
MwlCalendarCtrl = directiveScope.vm;
}));
afterEach(function() {
clock.restore();
});
it('should define a list of hours', function() {
expect(MwlCalendarCtrl.hourGrid.length).to.equal(17);
});
it('should update the list of hours when the calendar refreshes if the locale changes', function() {
sinon.stub(moment, 'locale').returns('another locale');
scope.dayViewStart = '00:00';
scope.$apply();
scope.$broadcast('calendar.refreshView');
expect(MwlCalendarCtrl.hourGrid.length).to.equal(23);
moment.locale.restore();
});
it('should call the event times changed callback when an event is dropped', function() {
var event = {
startsAt: moment().toDate(),
endsAt: moment().add(1, 'day').toDate()
};
var date = moment().add(2, 'days').toDate();
MwlCalendarCtrl.onEventTimesChanged = sinon.spy();
MwlCalendarCtrl.eventDropped(event, date);
var calledWith = MwlCalendarCtrl.onEventTimesChanged.getCall(0).args[0];
expect(calledWith.calendarEvent).to.equal(event);
expect(calledWith.calendarDate.getTime()).to.equal(date.getTime());
expect(calledWith.calendarNewEventStart.getTime()).to.equal(date.getTime());
expect(calledWith.calendarNewEventEnd.getTime()).to.equal(moment().add(3, 'days').toDate().getTime());
});
it('should initialise the date range select', function() {
var date = new Date();
MwlCalendarCtrl.onDragSelectStart(date, 1);
expect(MwlCalendarCtrl.dateRangeSelect).to.deep.equal({
active: true,
startDate: date,
endDate: date,
dayIndex: 1
});
});
it('should update the date ranges end date', function() {
var date = new Date();
MwlCalendarCtrl.dateRangeSelect = {
startDate: 'date1',
endDate: 'date2'
};
MwlCalendarCtrl.onDragSelectMove(date);
expect(MwlCalendarCtrl.dateRangeSelect).to.deep.equal({
startDate: 'date1',
endDate: date
});
});
it('should not throw if there is no date range being selected', function() {
var date = new Date();
MwlCalendarCtrl.dateRangeSelect = null;
expect(function() {
MwlCalendarCtrl.onDragSelectMove(date);
}).not.to.throw();
});
it('should call the onDateRangeSelect callback if there is a valid date range', function() {
MwlCalendarCtrl.onDateRangeSelect = sinon.spy();
var date1 = moment();
var date2 = moment(Date.now() + 100000);
MwlCalendarCtrl.dateRangeSelect = {
startDate: date1,
endDate: moment(Date.now() + 10)
};
MwlCalendarCtrl.onDragSelectEnd(date2);
expect(MwlCalendarCtrl.onDateRangeSelect).to.have.been.calledWith({
calendarRangeStartDate: date1.toDate(),
calendarRangeEndDate: date2.toDate()
});
expect(MwlCalendarCtrl.dateRangeSelect).to.be.undefined;
});
it('should not call the onDateRangeSelect callback if there is an invalid date range', function() {
MwlCalendarCtrl.onDateRangeSelect = sinon.spy();
var date1 = moment();
var date2 = moment(Date.now() - 100000);
MwlCalendarCtrl.dateRangeSelect = {
startDate: date1,
endDate: moment(Date.now() - 10)
};
MwlCalendarCtrl.onDragSelectEnd(date2);
expect(MwlCalendarCtrl.onDateRangeSelect).not.to.have.been.called;
expect(MwlCalendarCtrl.dateRangeSelect).to.be.undefined;
});
it('should allow the hour segments to have their CSS class overridden', function() {
sinon.stub(moment, 'locale').returns('another locale');
scope.cellModifier = function(args) {
args.calendarCell.cssClass = 'foo';
};
scope.$apply();
scope.$broadcast('calendar.refreshView');
scope.$apply();
moment.locale.restore();
expect(element[0].querySelector('.cal-day-hour-part.foo')).to.be.ok;
});
it('should allow the week view with times day segments CSS classes to be customised', function() {
scope.view = 'week';
scope.dayWidth = 50;
sinon.stub(moment, 'locale').returns('another locale');
scope.cellModifier = function(args) {
args.calendarCell.cssClass = 'foo';
};
scope.$apply();
scope.$broadcast('calendar.refreshView');
scope.$apply();
moment.locale.restore();
expect(element[0].querySelector('.cal-day-hour-part-spacer.foo')).to.be.ok;
});
it('should not throw if there is no current range being selected', function() {
expect(function() {
MwlCalendarCtrl.onDragSelectEnd(new Date());
}).not.to.throw();
});
});
|
JavaScript
| 0.001996 |
@@ -215,28 +215,8 @@
pe,%0A
- calendarConfig,%0A
@@ -1267,68 +1267,11 @@
ope_
-, _calendarConfig_) %7B%0A calendarConfig = _calendarConfig_;
+) %7B
%0A
|
35c75bc1c1b36a7f055ce3ca2dcdb0415e6418c9
|
Fix discrete zoom test
|
testing/test-cases/jasmine-tests/discreteZoom.js
|
testing/test-cases/jasmine-tests/discreteZoom.js
|
/*global describe, it, expect, geo*/
describe('DiscreteZoom and ParallelProjection', function () {
'use strict';
var map, width = 800, height = 800;
var cam;
// create an osm map layer
map = geo.map({
'node': '#map',
'center': [0, 0],
'zoom': 3,
discreteZoom: true
});
map.createLayer('osm');
map.resize(0, 0, width, height);
map.draw();
it('Zoom to a non-integer value', function (done) {
expect(map.discreteZoom()).toBe(true);
map.geoOff(geo.event.transitionend)
.geoOn(geo.event.transitionend, function () {
expect(map.zoom()).toBe(6);
done();
});
map.zoom(5.75);
});
it('Turn off discrete zoom and zoom to a non-integer value', function (done) {
map.discreteZoom(false);
expect(map.discreteZoom()).toBe(false);
map.geoOff(geo.event.transitionend)
.geoOn(geo.event.transitionend, function () {
expect(map.zoom()).toBe(5.75);
done();
});
map.zoom(5.75);
});
it('Turn back on discrete zoom', function (done) {
map.geoOff(geo.event.transitionend)
.geoOn(geo.event.transitionend, function () {
expect(map.discreteZoom()).toBe(true);
expect(map.zoom()).toBe(6);
done();
});
map.discreteZoom(true);
});
it('Turn on parallel projection', function (done) {
cam = map.baseLayer().renderer().contextRenderer().camera();
var proj = cam.projectionMatrix();
expect(proj[1] === 0 && proj[2] === 0 && proj[3] === 0 && proj[4] === 0 &&
proj[6] === 0 && proj[7] === 0 && proj[8] === 0 && proj[9] === 0 &&
proj[11] === 0 && proj[15] === 1).toBe(false);
expect(map.parallelProjection()).toBe(false);
map.geoOff(geo.event.transitionend)
.geoOn(geo.event.transitionend, function () {
expect(map.parallelProjection()).toBe(true);
var proj = cam.projectionMatrix();
expect(proj[1] === 0 && proj[2] === 0 && proj[3] === 0 &&
proj[4] === 0 && proj[6] === 0 && proj[7] === 0 &&
proj[8] === 0 && proj[9] === 0 && proj[11] === 0 &&
proj[15] === 1).toBe(true);
done();
});
map.parallelProjection(true).draw();
});
});
|
JavaScript
| 0.000003 |
@@ -407,36 +407,32 @@
lue', function (
-done
) %7B%0A expect(m
@@ -474,100 +474,24 @@
map.
-geoOff(geo.event.transitionend)%0A .geoOn(geo.event.transitionend, function () %7B%0A
+zoom(5.75);%0A
-
expe
@@ -518,54 +518,8 @@
6);%0A
- done();%0A %7D);%0A map.zoom(5.75);%0A
%7D)
@@ -586,36 +586,32 @@
lue', function (
-done
) %7B%0A map.disc
@@ -683,100 +683,24 @@
map.
-geoOff(geo.event.transitionend)%0A .geoOn(geo.event.transitionend, function () %7B%0A
+zoom(5.75);%0A
-
expe
@@ -730,54 +730,8 @@
5);%0A
- done();%0A %7D);%0A map.zoom(5.75);%0A
%7D)
@@ -778,28 +778,24 @@
nction (
-done
) %7B%0A
map.geoO
@@ -790,111 +790,8 @@
-map.geoOff(geo.event.transitionend)%0A .geoOn(geo.event.transitionend, function () %7B%0A expect(
map.
@@ -803,35 +803,23 @@
eteZoom(
-)).toBe(
true);%0A
-
expe
@@ -846,62 +846,8 @@
6);%0A
- done();%0A %7D);%0A map.discreteZoom(true);%0A
%7D)
@@ -895,20 +895,16 @@
nction (
-done
) %7B%0A
@@ -1211,32 +1211,33 @@
1).toBe(false);%0A
+%0A
expect(map.p
@@ -1282,96 +1282,42 @@
map.
-geoOff(geo.event.transitionend)%0A .geoOn(geo.event.transitionend, function () %7B%0A
+parallelProjection(true).draw();%0A%0A
@@ -1365,24 +1365,16 @@
e);%0A
- var
proj = c
@@ -1396,20 +1396,16 @@
trix();%0A
-
expe
@@ -1465,28 +1465,24 @@
%0A
-
proj%5B4%5D ===
@@ -1512,36 +1512,32 @@
roj%5B7%5D === 0 &&%0A
-
proj%5B
@@ -1590,28 +1590,24 @@
%0A
-
-
proj%5B15%5D ===
@@ -1626,75 +1626,8 @@
e);%0A
- done();%0A %7D);%0A map.parallelProjection(true).draw();%0A
%7D)
|
1419dfc77db204e689e0a0ea2bdc2c17dc1e907a
|
fix the e2e fixture
|
tests/e2e/fixtures/default-researcher.fixture.js
|
tests/e2e/fixtures/default-researcher.fixture.js
|
'use strict';
var encrypt = require('../../../server/utilities/encryption');
module.exports = {
load: function(mongoose, next) {
console.log('Create `User` fixture');
var salt = encrypt.createSalt(),
hash = encrypt.hashPwd(salt, 'jcust');
mongoose.model('User').create({
firstName: 'Chris',
lastName: 'Perry',
username: 'cperry',
email: '[email protected]',
salt: salt,
hashed_pwd: hash,
role: 'researcher',
assessments: [],
language: 'English'
}, function(err) {
if(err) {
console.log('The fixture has not been created. The error is');
console.log(err);
} else {
console.log('The fixture has been successfully created');
}
next();
});
}
};
|
JavaScript
| 0.000004 |
@@ -262,13 +262,14 @@
t, '
-jcust
+cperry
');%0A
|
016927edd2155c2c28c61d4e6ba083aff52a9ac9
|
fix voor refresh
|
Urireferencer.js
|
Urireferencer.js
|
define([
'dojo/_base/declare',
'dojo/_base/lang',
'dojo/_base/array',
'dijit/_WidgetBase',
'dijit/_TemplatedMixin',
'dojo/text!./templates/Urireferencer.html',
'./controllers/UriController',
'dojo/dom-construct',
'dojo/dom-class',
'dojo/on',
'dojo/query',
'dojo/NodeList-traverse'
], function (
declare,
lang,
array,
WidgetBase,
TemplatedMixin,
template,
UriController,
domConstruct,
domClass,
on,
query
) {
return declare([WidgetBase, TemplatedMixin], {
templateString: template,
uriUrl: null,
controller: null,
ssoToken: null,
checkUri: null,
totalCount: 0,
postCreate: function () {
this.inherited(arguments);
this.controller = new UriController({
uriUrl: this.uriUrl,
ssoToken: this.ssoToken
})
},
startup: function () {
this.controller.checkUri(this.checkUri).then(lang.hitch(this, function(data) {
this.referenceCount.innerHTML = data.count;
array.forEach(data.applications, lang.hitch(this, function(app) {
this._createExpanderElement(app);
}));
this.referenceLoadingMessage.style.display = 'none';
this.expanderControls.style.display = 'inline-block';
}))
},
checkUri: function(uri) {
this.referenceLoadingMessage.style.display = 'none';
this.expanderControls.style.display = 'none';
domConstruct.empty(this.expanderContainer);
this.controller.checkUri(uri).then(lang.hitch(this, function(data) {
this.referenceCount.innerHTML = data.count;
array.forEach(data.applications, lang.hitch(this, function(app) {
this._createExpanderElement(app);
}));
this.referenceLoadingMessage.style.display = 'none';
this.expanderControls.style.display = 'inline-block';
}))
},
_createExpanderElement: function(app) {
var exp = domConstruct.create('div', { 'class': 'expander' }, this.expanderContainer);
var header = domConstruct.create('div', { 'class': 'expander-header' }, exp);
var content = domConstruct.create('div', { 'class': 'expander-content' }, exp);
domConstruct.create('div', { 'class': 'expander-icon' }, header);
var title = '<strong>' + app.title + '</strong> <small>(' +
(app.count ? app.count : (app.success ? '0' : 'fout bij controleren')) + ' referenties)</small>';
domConstruct.create('h5', { innerHTML: title }, header);
var ul = domConstruct.create('ul', { 'class': 'nodisk', style: 'padding-left: 20px;' }, content);
if (app.success && app.has_references) {
array.forEach(app.items, lang.hitch(this, function(item) {
domConstruct.create('li', { innerHTML: '<i class="fa fa-angle-right"></i> <a target="_blank" href="' + item.uri + '">' + item.title + '</a>'}, ul);
}));
} else {
if (!app.success) {
domConstruct.create('li', { innerHTML: 'Er ging iets mis bij het controleren van de referenties.'}, ul);
} else {
domConstruct.create('li', { innerHTML: 'Er zijn geen referenties gevonden.'}, ul);
}
}
on(header, 'click', lang.hitch(this, function(evt) {
this._toggleExpander(evt);
}));
},
_toggleExpander: function(evt) {
evt ? evt.preventDefault() : null;
var expander = evt.target.closest('.expander');
var container = expander.closest('.expander-container');
// Close other expanded elements // Excluded here because of showAll/closeAll
//query(container).children('.expander').forEach(function(child) {
// if (child != expander) {
// if (domClass.contains(child, 'expander-expanded')){
// domClass.remove(child, 'expander-expanded');
// }
// }
//});
// Toggle this element
if (domClass.contains(expander, 'expander-expanded')) {
domClass.remove(expander, 'expander-expanded');
} else {
domClass.add(expander, 'expander-expanded');
}
},
_openAll: function(evt) {
evt ? evt.preventDefault() : null;
query(this.expanderContainer).children('.expander').forEach(function(child) {
domClass.add(child, 'expander-expanded');
});
},
_closeAll: function(evt) {
evt ? evt.preventDefault() : null;
query(this.expanderContainer).children('.expander').forEach(function(child) {
domClass.remove(child, 'expander-expanded');
});
}
});
});
|
JavaScript
| 0 |
@@ -1248,24 +1248,26 @@
%7D,%0A%0A
+re
checkUri: fu
|
7f2282fdc51d488942a2840a5c853265fe5543fa
|
Update script.js
|
Web/js/script.js
|
Web/js/script.js
|
$(document).ready(function() {
// nav
// nav clase
$(".nav a").on("click", function(){
$(".nav").find(".active").removeClass("active");
$(this).parent().addClass("active");
});
// new
$('.navbar-collapse a').click(function (e) {
$('.navbar-collapse').collapse('toggle');
});
// end new
$('nav').affix({
offset: {
top: function() { return $('#imagen-inicial').height(); }
}
});
$('a[href*="#"]:not([href="#"])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html, body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
/*
// Animación
var $window = $(window),
win_height_padded = $window.height() * 1.1,
isTouch = Modernizr.touch;
if (isTouch) { $('.revealOnScroll').addClass('animated'); }
$window.on('scroll', revealOnScroll);
function revealOnScroll() {
var scrolled = $window.scrollTop(),
win_height_padded = $window.height() * 1.1;
// Showed...
$(".revealOnScroll:not(.animated)").each(function () {
var $this = $(this),
offsetTop = $this.offset().top;
if (scrolled + win_height_padded > offsetTop) {
if ($this.data('timeout')) {
window.setTimeout(function(){
$this.addClass('animated ' + $this.data('animation'));
}, parseInt($this.data('timeout'),10));
} else {
$this.addClass('animated ' + $this.data('animation'));
}
}
});
// Hidden...
$(".revealOnScroll.animated").each(function (index) {
var $this = $(this),
offsetTop = $this.offset().top;
if (scrolled + win_height_padded < offsetTop) {
$(this).removeClass('animated fadeInUp flipInX lightSpeedIn')
}
});
}
revealOnScroll();
*/
});
|
JavaScript
| 0.000002 |
@@ -196,16 +196,18 @@
// new%0A
+/*
$('.nav
@@ -303,16 +303,18 @@
%7D);
+*/
%0A // en
@@ -899,14 +899,8 @@
%0A %0A
- /*%0A%0A
//
@@ -2099,13 +2099,8 @@
%0A %0A
- */%0A
%7D);%0A
|
975f1fb21d60c7c9860dcb26ddb6de2185816b82
|
Update apps/roundcube/src/js/mailFrameScripts.js
|
apps/roundcube/src/js/mailFrameScripts.js
|
apps/roundcube/src/js/mailFrameScripts.js
|
var buffer = 20; //scroll bar buffer
function pageY(elem) {
return elem.offsetParent ? (elem.offsetTop + pageY(elem.offsetParent)) : elem.offsetTop;
}
function resizeIframe() {
var height = document.documentElement.clientHeight;
height -= pageY(document.getElementById('roundcubeFrame'))+ buffer ;
height = (height < 0) ? 0 : height;
document.getElementById('roundcubeFrame').style.height = '100%';
// fix scrollbar issue
$('#content').css('overflow','hidden');
$('#content').css('height','+ height+');
width=$('#content').css('width');
$('#content').css('width','+ width +');
}
$('#roundcubeFrame').load(function() {
resizeIframe();
var mainscreen = $('#roundcubeFrame').contents().find('#mainscreen');
// remove header line, includes about line and
var top_line = $('#roundcubeFrame').contents().find('#topline');
// correct top padding
var top_margin=10;
try{
var top_nav = $('#roundcubeFrame').contents().find('#topnav');
// check if the above element exits (only in new larry theme, if null use rc 0.7 default theme
// TODO refactor and move theme check
if(top_nav.height()!=null){
top_margin= 10;
//In larry theme with accounts plugin, we have to move the account selection
var acc_select = top_line.find('.username');
if (acc_select) {
mainscreen.find('div#messagetoolbar').attr('id',''); //Quick n dirty for space
acc_select.appendTo(mainscreen.find('div#searchfilter')).css({position: 'absolute', top:'0px', left:'-170px'});
}
} else {
top_margin= parseInt(mainscreen.css('top'),10)-top_line.height();
}
} catch (e) {}
top_line.remove();
// fix topbar, issue https://github.com/hypery2k/owncloud/issues/54
$('#roundcubeFrame').contents().find('.toolbar').css('z-index','80');
$('#roundcubeFrame').contents().find('.toolbar').css('position','absolute');
// remove logout button
$('#roundcubeFrame').contents().find('.button-logout').remove();
// check if the header menu from roundcube was disabled
if($('#disable_header_nav').val() === 'true') {
var top_nav = $('#roundcubeFrame').contents().find('#header');
// check if the above element exits (only in new larry theme, if null use rc 0.7 default theme
if(top_nav.height()==null){
top_nav = $('#roundcubeFrame').contents().find('#taskbar');
} else {
//top_in= top_margin-top_nav.height();
}
top_nav.remove();
$('#roundcubeFrame').contents().find('#mainscreen').css('top',top_margin);
} else {
// correct top padding
$('#roundcubeFrame').contents().find('#mainscreen').css('top','50px');
}
// slide in roundcube nice
$('#loader').fadeOut('slow');
$('#roundcubeFrame').slideDown('slow');
// remove email adresse
$('#roundcubeFrame').contents().find('.username').remove();
});
|
JavaScript
| 0 |
@@ -1,290 +1,105 @@
-var buffer = 20; //scroll bar buffer%0A%09%0Afunction pageY(elem) %7B%0A return elem.offsetParent ? (elem.offsetTop + pageY(elem.offsetParent)) : elem.offsetTop;%0A%7D%0A%09%0Afunction resizeIframe() %7B%0A var height = document.documentElement.clientHeight;%0A height -= pageY(document.getElementById
+$(document).ready(function() %7B%0A $(window).resize(function () %7B%0A fillWindow($
('
+#
roun
@@ -107,96 +107,75 @@
cube
-Frame'))+ buffer ;%0A height = (height %3C 0) ? 0 : height;%0A document.getElementById
+_container'));%0A %7D);%0A $(window).resize();%0A $
('
+#
roun
@@ -183,225 +183,85 @@
cube
-Frame').style.height = '100%25';%0A%09// fix scrollbar issue%0A%09$('#content').css('overflow','hidden');%0A%09$('#content').css('height','+ height+');%0A%09width=$('#content').css('width');%0A%09$('#content').css('width','+ width +');%0A%09%0A%7D
+_container').scroll(updateOnBottom).empty().width($('#content').width());%0A%7D);
%0A%0A$(
@@ -301,26 +301,8 @@
) %7B%0A
-%09resizeIframe();%0A%0A
%09var
|
5a6cfd069df05db7f452fec062590b0155292143
|
use String.fromCodePoint in singleton implementation when available
|
src/Data/String/CodePoints.js
|
src/Data/String/CodePoints.js
|
var hasArrayFrom = typeof Array.from === 'function';
var hasStringIterator =
typeof Symbol !== 'undefined' &&
Symbol != null &&
typeof Symbol.iterator !== 'undefined' &&
typeof String.prototype[Symbol.iterator] === 'function';
var hasFromCodePoint = typeof String.prototype.fromCodePoint === 'function';
exports._codePointAt = function (fallback) {
return function (Just) {
return function (Nothing) {
return function (relIndex) {
return function (str) {
var length = str.length;
if (length <= relIndex) return Nothing;
var index = relIndex < 0 ? ((relIndex % length) + length) % length : relIndex;
if (typeof String.prototype.codePointAt === 'function') {
var cp = str.codePointAt(index);
return cp == null ? Nothing : Just(cp);
} else if (hasArrayFrom) {
var cps = Array.from(str);
if (cps.length <= index) return Nothing;
return Just(cps[index]);
} else if (hasStringIterator) {
var i = index;
var iter = str[Symbol.iterator]();
for (;;) {
var o = iter.next();
if (o.done) return Nothing;
if (i == 0) return Just(o.value);
--i;
}
}
return fallback(index)(str);
};
};
};
};
};
exports.singleton = fromCodePoint;
exports._take = function (fallback) {
return function (n) {
return function (str) {
if (hasArrayFrom) {
return Array.from(str);
} else if (hasStringIterator) {
var accum = "";
var iter = str[Symbol.iterator]();
for (var i = 0; i < n; ++i) {
var o = iter.next();
if (o.done) return accum;
accum += o.value;
}
return accum;
}
return fallback(str);
};
};
};
exports._toCodePointArray = function (fallback) {
return function (str) {
if (hasArrayFrom) {
return Array.from(str);
} else if (hasStringIterator) {
var accum = [];
var iter = str[Symbol.iterator]();
for (;;) {
var o = iter.next();
if (o.done) return accum;
accum.push(o.value);
}
}
return fallback(str);
};
};
exports.fromCodePointArray = function (cps) {
if (hasFromCodePoint) {
return String.fromCodePoint.apply(cps);
}
return cps.map(fromCodePoint).join('');
};
function fromCodePoint(cp) {
if (cp <= 0xFFFF) return String.fromCharCode(cp);
var cu1 = String.fromCharCode(Math.floor((cp - 0x10000) / 0x400) + 0xD800);
var cu2 = String.fromCharCode((cp - 0x10000) % 0x400 + 0xDC00);
return cu1 + cu2;
}
|
JavaScript
| 0 |
@@ -1386,16 +1386,58 @@
gleton =
+ hasFromCodePoint ? String.fromCodePoint :
fromCod
@@ -2413,16 +2413,24 @@
t.apply(
+String,
cps);%0A
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.