conflict_resolution
stringlengths 27
16k
|
---|
<<<<<<<
/**
* WordPress dependencies
*/
import { Component } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
=======
const { Component } = wp.element;
const { __, _x } = wp.i18n;
>>>>>>>
/**
* WordPress dependencies
*/
import { Component } from '@wordpress/element';
import { __, _x } from '@wordpress/i18n'; |
<<<<<<<
import { Component, render } from '@wordpress/element';
=======
import { Component, render, Fragment, Suspense, lazy } from '@wordpress/element';
>>>>>>>
import { Component, render, Suspense, lazy } from '@wordpress/element';
<<<<<<<
import ErrorHandler from 'GoogleComponents/ErrorHandler';
import { Suspense, lazy } from 'GoogleUtil/react-features';
=======
>>>>>>>
import ErrorHandler from 'GoogleComponents/ErrorHandler';
<<<<<<<
const { currentAdminPage } = googlesitekit.admin;
=======
if ( hasError ) {
return <Notification
id={ 'googlesitekit-error' }
key={ 'googlesitekit-error' }
title={ error.message }
description={ info.componentStack }
dismiss={ '' }
isDismissable={ false }
format="small"
type="win-error"
/>;
}
const { currentAdminPage } = global.googlesitekit.admin;
>>>>>>>
const { currentAdminPage } = global.googlesitekit.admin; |
<<<<<<<
trackEvent( 'search_console_setup', 'add_new_sc_property' );
=======
if ( isNew ) {
sendAnalyticsTrackingEvent( 'search_console_setup', 'add_new_sc_property' );
}
>>>>>>>
if ( isNew ) {
trackEvent( 'search_console_setup', 'add_new_sc_property' );
} |
<<<<<<<
fetchEdges(site, languages, edgeType, callback){
const locationEdgeFragment = `fragment FortisDashboardLocationEdges on LocationCollection {
=======
fetchEdges(site, langCode, edgeType, callback) {
const locationEdgeFragment = `fragment FortisDashboardLocationEdges on LocationCollection {
>>>>>>>
fetchEdges(site, languages, edgeType, callback){
const locationEdgeFragment = `fragment FortisDashboardLocationEdges on LocationCollection {
<<<<<<<
const locationsQuery = `locations: locations(site: $site, languages: $languages) {
=======
const locationsQuery = `locations: locations(site: $site, langCode: $langCode) {
>>>>>>>
const locationsQuery = `locations: locations(site: $site, languages: $languages) {
<<<<<<<
let query = ` ${fragments}
query FetchAllEdge($site: String!, $languages: [String]!) {
=======
let query = ` ${fragments}
query FetchAllEdge($site: String!, $langCode: String) {
>>>>>>>
let query = ` ${fragments}
query FetchAllEdge($site: String!, $languages: [String]!) {
<<<<<<<
getSiteDefintion(siteId, retrieveSiteList, callback){
=======
request(POST, callback);
} else {
throw new Error(`Invalid bbox format for value [${bbox}]`);
}
},
getSiteDefintion(siteId, retrieveSiteList, callback) {
>>>>>>>
getSiteDefintion(siteId, retrieveSiteList, callback){
request(POST, callback);
} else {
throw new Error(`Invalid bbox format for value [${bbox}]`);
}
},
getSiteDefintion(siteId, retrieveSiteList, callback) {
<<<<<<<
let variables = {siteId};
=======
let variables = { siteId };
console.log('getSiteDefintion called');
>>>>>>>
let variables = { siteId };
console.log('getSiteDefintion called');
<<<<<<<
},
getAdminFbPages: function(){
return Rx.Observable.from([[{
url:"BritishCouncilLibya",
},
{
url:"truthlibya",
},
{
url:"ukinlibya",
}
]]);
},
getAdminLanguage:function(){
return Rx.Observable.from(["en"]);
},
getAdminTargetRegion :function(){
return Rx.Observable.from(["29.626,16.216"]);
},
getAdminLocalities: function(){
return Rx.Observable.from([[{
ar_name:"Mudīrīyat أم الرزم",
name: "Mudīrīyat Umm ar Rizam"
},
{
ar_name: "زيغان",
name: "Bardīyah"
}
]]);
},
translateSentence: function (sentence, fromLanguage, toLanguage) {
let query = `
fragment TranslationView on TranslationResult{
translatedSentence
}
query FetchEvent($sentence: String!, $fromLanguage: String!, $toLanguage: String!) {
translate(sentence: $sentence, fromLanguage: $fromLanguage, toLanguage: $toLanguage){
...TranslationView
}
}`
let variables = {sentence, fromLanguage, toLanguage};
let host = process.env.REACT_APP_SERVICE_HOST;
var POST = {
url : `${host}/api/Messages`,
method : "POST",
json: true,
withCredentials: false,
body: { query, variables }
};
return new Promise((resolve, reject) => {
request(POST, (error, response, body) => {
if(!error && body && body.data && body.data.translate && body.data.translate.translatedSentence){
resolve(body.data.translate.translatedSentence);
}
else{
reject (error || 'Translate request failed: ' + JSON.stringify(response));
}
});
});
}
=======
>>>>>>>
},
getAdminFbPages: function(){
return Rx.Observable.from([[{
url:"BritishCouncilLibya",
},
{
url:"truthlibya",
},
{
url:"ukinlibya",
}
]]);
},
getAdminLanguage:function(){
return Rx.Observable.from(["en"]);
},
getAdminTargetRegion :function(){
return Rx.Observable.from(["29.626,16.216"]);
},
getAdminLocalities: function(){
return Rx.Observable.from([[{
ar_name:"Mudīrīyat أم الرزم",
name: "Mudīrīyat Umm ar Rizam"
},
{
ar_name: "زيغان",
name: "Bardīyah"
}
]]);
},
translateSentence: function (sentence, fromLanguage, toLanguage) {
let query = `
fragment TranslationView on TranslationResult{
translatedSentence
}
query FetchEvent($sentence: String!, $fromLanguage: String!, $toLanguage: String!) {
translate(sentence: $sentence, fromLanguage: $fromLanguage, toLanguage: $toLanguage){
...TranslationView
}
}`
let variables = {sentence, fromLanguage, toLanguage};
let host = process.env.REACT_APP_SERVICE_HOST;
var POST = {
url : `${host}/api/Messages`,
method : "POST",
json: true,
withCredentials: false,
body: { query, variables }
};
return new Promise((resolve, reject) => {
request(POST, (error, response, body) => {
if(!error && body && body.data && body.data.translate && body.data.translate.translatedSentence){
resolve(body.data.translate.translatedSentence);
}
else{
reject (error || 'Translate request failed: ' + JSON.stringify(response));
}
});
});
} |
<<<<<<<
<Cell
className="googlesitekit-widget--analyticsAllTrafficV2__dimensions"
lgSize={ 5 }
mdSize={ 4 }
smSize={ 4 }
>
<DimensionTabs dimensionName={ dimensionName } />
<UserDimensionsPieChart dimensionName={ dimensionName } />
=======
<Cell size={ 4 }>
<DimensionTabs dimensionName={ dimensionName } />
<UserDimensionsPieChart sourceLink={ serviceReportURL } />
>>>>>>>
<Cell
className="googlesitekit-widget--analyticsAllTrafficV2__dimensions"
lgSize={ 5 }
mdSize={ 4 }
smSize={ 4 }
>
<DimensionTabs dimensionName={ dimensionName } />
<UserDimensionsPieChart dimensionName={ dimensionName } sourceLink={ serviceReportURL } /> |
<<<<<<<
import report from './report';
=======
import service from './service';
>>>>>>>
import report from './report';
import service from './service';
<<<<<<<
const store = Data.combineStores(
baseModuleStore,
report,
);
const {
actions,
controls,
reducer,
resolvers,
selectors,
} = store;
=======
const store = Data.combineStores(
baseModuleStore,
service
);
>>>>>>>
const store = Data.combineStores(
baseModuleStore,
report,
service,
); |
<<<<<<<
import Widgets from 'googlesitekit-widgets';
import { FORM_ALL_TRAFFIC_WIDGET, DATE_RANGE_OFFSET, STORE_NAME } from '../../../datastore/constants';
=======
import { FORM_ALL_TRAFFIC_WIDGET, DATE_RANGE_OFFSET, MODULES_ANALYTICS } from '../../../datastore/constants';
>>>>>>>
import { FORM_ALL_TRAFFIC_WIDGET, DATE_RANGE_OFFSET, STORE_NAME } from '../../../datastore/constants';
<<<<<<<
import { generateDateRangeArgs } from '../../../../analytics/util/report-date-range-args';
const { Widget } = Widgets.components;
=======
>>>>>>>
import { generateDateRangeArgs } from '../../../../analytics/util/report-date-range-args'; |
<<<<<<<
);
domReady( () => {
Widgets.registerWidget(
'analyticsAllTraffic',
{
component: DashboardAllTrafficWidget,
width: Widgets.WIDGET_WIDTHS.FULL,
priority: 1,
wrapWidget: true,
},
[
AREA_DASHBOARD_ALL_TRAFFIC,
AREA_PAGE_DASHBOARD_ALL_TRAFFIC,
],
);
Widgets.registerWidget(
'analyticsGoals',
{
component: DashboardGoalsWidget,
width: Widgets.WIDGET_WIDTHS.QUARTER,
priority: 4,
wrapWidget: true,
},
[
AREA_DASHBOARD_ALL_TRAFFIC,
],
);
Widgets.registerWidget(
'analyticsUniqueVisitors',
{
component: DashboardUniqueVisitorsWidget,
width: Widgets.WIDGET_WIDTHS.QUARTER,
priority: 3,
wrapWidget: true,
},
[
AREA_DASHBOARD_ALL_TRAFFIC,
AREA_PAGE_DASHBOARD_ALL_TRAFFIC,
],
);
Widgets.registerWidget(
'analyticsBounceRate',
{
component: DashboardBounceRateWidget,
width: Widgets.WIDGET_WIDTHS.QUARTER,
priority: 4,
wrapWidget: true,
},
[
AREA_PAGE_DASHBOARD_ALL_TRAFFIC,
],
);
} );
=======
);
domReady( () => {
Widgets.registerWidget(
'analyticsAllTraffic',
{
component: DashboardAllTrafficWidget,
width: Widgets.WIDGET_WIDTHS.FULL,
priority: 1,
wrapWidget: false,
},
[
AREA_DASHBOARD_ALL_TRAFFIC,
AREA_PAGE_DASHBOARD_ALL_TRAFFIC,
],
);
} );
>>>>>>>
);
domReady( () => {
Widgets.registerWidget(
'analyticsAllTraffic',
{
component: DashboardAllTrafficWidget,
width: Widgets.WIDGET_WIDTHS.FULL,
priority: 1,
wrapWidget: false,
},
[
AREA_DASHBOARD_ALL_TRAFFIC,
AREA_PAGE_DASHBOARD_ALL_TRAFFIC,
],
);
Widgets.registerWidget(
'analyticsGoals',
{
component: DashboardGoalsWidget,
width: Widgets.WIDGET_WIDTHS.QUARTER,
priority: 4,
wrapWidget: true,
},
[
AREA_DASHBOARD_ALL_TRAFFIC,
],
);
Widgets.registerWidget(
'analyticsUniqueVisitors',
{
component: DashboardUniqueVisitorsWidget,
width: Widgets.WIDGET_WIDTHS.QUARTER,
priority: 3,
wrapWidget: true,
},
[
AREA_DASHBOARD_ALL_TRAFFIC,
AREA_PAGE_DASHBOARD_ALL_TRAFFIC,
],
);
Widgets.registerWidget(
'analyticsBounceRate',
{
component: DashboardBounceRateWidget,
width: Widgets.WIDGET_WIDTHS.QUARTER,
priority: 4,
wrapWidget: true,
},
[
AREA_PAGE_DASHBOARD_ALL_TRAFFIC,
],
);
} ); |
<<<<<<<
import Dialog from '../../components/Dialog';
import ModuleIcon from '../../components/module-icon';
=======
import Dialog from '../../components/dialog';
import ModuleIcon from '../ModuleIcon';
>>>>>>>
import Dialog from '../../components/Dialog';
import ModuleIcon from '../ModuleIcon'; |
<<<<<<<
=======
import apiFetch from '@wordpress/api-fetch';
import { getQueryArg } from '@wordpress/url';
>>>>>>>
import { getQueryArg } from '@wordpress/url';
<<<<<<<
fetchMock.postOnce(
/^\/google-site-kit\/v1\/core\/modules\/data\/activation/,
{ body: { success: true }, status: 200 }
);
fetchMock.getOnce(
/^\/google-site-kit\/v1\/core\/modules\/data\/list/,
{ body: responseWithOptimizeEnabled, status: 200 }
);
=======
fetch
.doMockOnceIf(
/^\/google-site-kit\/v1\/core\/modules\/data\/activation/
)
.mockResponseOnce(
JSON.stringify( { success: true } ),
{ status: 200 }
);
fetch
.doMockOnceIf(
/^\/google-site-kit\/v1\/core\/modules\/data\/list/
)
.mockResponseOnce(
JSON.stringify( responseWithOptimizeEnabled ),
{ status: 200 }
);
fetch
.doMockOnceIf( /^\/google-site-kit\/v1\/core\/user\/data\/authentication/ )
.mockResponseOnce(
JSON.stringify( {} ),
{ status: 200 }
);
>>>>>>>
fetchMock.postOnce(
/^\/google-site-kit\/v1\/core\/modules\/data\/activation/,
{ body: { success: true }, status: 200 }
);
fetchMock.getOnce(
/^\/google-site-kit\/v1\/core\/modules\/data\/list/,
{ body: responseWithOptimizeEnabled, status: 200 }
);
fetchMock.getOnce(
/^\/google-site-kit\/v1\/core\/user\/data\/authentication/,
{ body: {}, status: 200 }
);
<<<<<<<
expect( fetchMock ).toHaveFetchedTimes( 3 );
=======
expect( fetch ).toHaveBeenCalledTimes( 4 );
>>>>>>>
expect( fetchMock ).toHaveFetchedTimes( 4 );
<<<<<<<
fetchMock.postOnce(
/^\/google-site-kit\/v1\/core\/modules\/data\/activation/,
{ body: response, status: 500 }
);
=======
fetch
.doMockOnceIf(
/^\/google-site-kit\/v1\/core\/modules\/data\/activation/
)
.mockResponseOnce(
JSON.stringify( response ),
{ status: 500 }
);
fetch
.doMockOnceIf( /^\/google-site-kit\/v1\/core\/user\/data\/authentication/ )
.mockResponseOnce(
JSON.stringify( {} ),
{ status: 200 }
);
>>>>>>>
fetchMock.postOnce(
/^\/google-site-kit\/v1\/core\/modules\/data\/activation/,
{ body: response, status: 500 }
);
fetchMock.getOnce(
/^\/google-site-kit\/v1\/core\/user\/data\/authentication/,
{ body: {}, status: 200 }
);
<<<<<<<
expect( fetchMock ).toHaveFetchedTimes( 2 );
=======
expect( fetch ).toHaveBeenCalledTimes( 3 );
>>>>>>>
expect( fetchMock ).toHaveBeenCalledTimes( 3 );
<<<<<<<
fetchMock.post(
/^\/google-site-kit\/v1\/core\/modules\/data\/activation/,
{ body: { success: true }, status: 200 }
);
=======
// Activate the module.
fetch
.doMockOnceIf(
/^\/google-site-kit\/v1\/core\/modules\/data\/activation/
)
.mockResponseOnce(
JSON.stringify( { success: true } ),
{ status: 200 }
);
fetch
.doMockOnceIf(
/^\/google-site-kit\/v1\/core\/modules\/data\/list/
)
.mockResponseOnce(
JSON.stringify( responseWithAnalyticsDisabled ),
{ status: 200 }
);
fetch
.doMockOnceIf( /^\/google-site-kit\/v1\/core\/user\/data\/authentication/ )
.mockResponseOnce(
JSON.stringify( {} ),
{ status: 200 }
);
registry.dispatch( STORE_NAME ).deactivateModule( slug );
>>>>>>>
fetchMock.postOnce(
/^\/google-site-kit\/v1\/core\/modules\/data\/activation/,
{ body: { success: true }, status: 200 }
);
<<<<<<<
=======
expect( fetch ).toHaveBeenCalledTimes( 4 );
>>>>>>>
<<<<<<<
expect( fetchMock ).toHaveFetchedTimes( 2 );
=======
expect( fetch ).toHaveBeenCalledTimes( 3 );
>>>>>>>
expect( fetchMock ).toHaveFetchedTimes( 3 ); |
<<<<<<<
const hasAccountCreateForm = useSelect( ( select ) => select( STORE_NAME ).hasForm( FORM_ACCOUNT_CREATE ) );
const hasProvisioningScope = useSelect( ( select ) => select( STORE_NAME ).hasProvisioningScope() );
=======
const accounts = useSelect( ( select ) => select( STORE_NAME ).getAccounts() );
>>>>>>>
const hasAccountCreateForm = useSelect( ( select ) => select( STORE_NAME ).hasForm( FORM_ACCOUNT_CREATE ) );
const hasProvisioningScope = useSelect( ( select ) => select( STORE_NAME ).hasProvisioningScope() );
const accounts = useSelect( ( select ) => select( STORE_NAME ).getAccounts() );
<<<<<<<
if ( isDoingCreateAccount || isNavigating || undefined === hasProvisioningScope ) {
=======
// If the user clicks "Back", rollback settings to restore saved values, if any.
const { rollbackSettings } = useDispatch( STORE_NAME );
const handleBack = useCallback( () => rollbackSettings() );
if ( isDoingCreateAccount || isNavigating || accounts === undefined ) {
>>>>>>>
// If the user clicks "Back", rollback settings to restore saved values, if any.
const { rollbackSettings } = useDispatch( STORE_NAME );
const handleBack = useCallback( () => rollbackSettings() );
if ( isDoingCreateAccount || isNavigating || accounts === undefined || hasProvisioningScope === undefined ) { |
<<<<<<<
Actions.constants.FACTS.CHANGE_LANGUAGE, this.handleLanguageChange,
Actions.constants.FACTS.LOAD_FACTS, this.handleLoadFacts,
=======
Actions.constants.FACTS.INITIALIZE, this.intializeSettings,
>>>>>>>
Actions.constants.FACTS.CHANGE_LANGUAGE, this.handleLanguageChange,
Actions.constants.FACTS.INITIALIZE, this.intializeSettings,
<<<<<<<
handleLoadFacts() {
this.dataStore.loading = true;
},
handleLanguageChange(language){
console.log("FactsStore. Language cganged.")
this.dataStore.language = language;
this.emit("change");
},
=======
>>>>>>>
handleLanguageChange(language){
this.dataStore.language = language;
this.emit("change");
}, |
<<<<<<<
import { STORE_NAME, CONTAINER_CREATE, CONTEXT_WEB, CONTEXT_AMP, FORM_SETUP } from './constants';
=======
import { STORE_NAME, CONTAINER_CREATE, CONTEXT_WEB, CONTEXT_AMP } from './constants';
import { STORE_NAME as CORE_MODULES } from '../../../googlesitekit/modules/datastore/constants';
>>>>>>>
import { STORE_NAME, CONTAINER_CREATE, CONTEXT_WEB, CONTEXT_AMP, FORM_SETUP } from './constants';
import { STORE_NAME as CORE_MODULES } from '../../../googlesitekit/modules/datastore/constants';
<<<<<<<
const {
getAccountID,
getContainerID,
getAMPContainerID,
getAMPContainers,
getInternalContainerID,
getInternalAMPContainerID,
getWebContainers,
hasExistingTagPermission,
haveSettingsChanged,
isDoingSubmitChanges,
} = select( STORE_NAME );
const {
isAMP,
isSecondaryAMP,
} = select( CORE_SITE );
if ( isDoingSubmitChanges() ) {
=======
try {
validateCanSubmitChanges( select );
return true;
} catch {
>>>>>>>
try {
validateCanSubmitChanges( select );
return true;
} catch {
<<<<<<<
if ( ! haveSettingsChanged() ) {
return false;
}
const accountID = getAccountID();
if ( ! isValidAccountID( accountID ) ) {
return false;
}
const containerID = getContainerID();
if ( containerID === CONTAINER_CREATE ) {
const containerName = select( CORE_FORMS ).getValue( FORM_SETUP, 'containerName' );
if ( ! isValidContainerName( containerName ) ) {
return false;
}
const webContainers = getWebContainers( accountID );
const existingContainer = Array.isArray( webContainers ) && webContainers.some( ( { name } ) => name === containerName );
if ( existingContainer ) {
return false;
}
}
if ( isAMP() ) {
const ampContainerID = getAMPContainerID();
// If AMP is active, the AMP container ID must be valid, regardless of mode.
if ( ! isValidContainerSelection( ampContainerID ) ) {
return false;
}
// If AMP is active, and a valid AMP container ID is selected, the internal ID must also be valid.
if ( isValidContainerID( ampContainerID ) && ! isValidInternalContainerID( getInternalAMPContainerID() ) ) {
return false;
}
if ( ampContainerID === CONTAINER_CREATE ) {
const ampContainerName = select( CORE_FORMS ).getValue( FORM_SETUP, 'ampContainerName' );
if ( ! isValidContainerName( ampContainerName ) ) {
return false;
}
const ampContainers = getAMPContainers( accountID );
const existingContainer = Array.isArray( ampContainers ) && ampContainers.some( ( { name } ) => name === ampContainerName );
if ( existingContainer ) {
return false;
}
}
}
// If AMP is not active, or in a secondary mode, validate the web container IDs.
if ( ! isAMP() || isSecondaryAMP() ) {
if ( ! isValidContainerSelection( containerID ) ) {
return false;
}
// If a valid container ID is selected, the internal ID must also be valid.
if ( isValidContainerID( containerID ) && ! isValidInternalContainerID( getInternalContainerID() ) ) {
return false;
}
}
// Do existing tag check last.
if ( hasExistingTagPermission() === false ) {
return false;
}
return true;
=======
>>>>>>> |
<<<<<<<
title={ sprintf( __( 'Top acquisition channels over the last %s', 'google-site-kit' ), dateRange ) }
=======
title={ sprintf( __( 'Top acquisition sources over the last %s', 'google-site-kit' ), currentDateRange ) }
>>>>>>>
title={ sprintf( __( 'Top acquisition channels over the last %s', 'google-site-kit' ), currentDateRange ) } |
<<<<<<<
doAction( 'googlesitekit.dataReceived', request.key );
this.setCache( request.key, result );
=======
this.setCache( request.dataObject, request.key, result );
>>>>>>>
this.setCache( request.key, result ); |
<<<<<<<
router.delete('/dashboards/:id', (req, res) => {
try {
let { id } = req.params;
const { privateDashboard } = paths();
let dashboardPath = path.join(privateDashboard, id + '.private.js');
let dashboardExists = fs.existsSync(dashboardPath);
if (!dashboardExists) {
return res.json({ errors: ['Could not find a Dashboard with the given id or filename'] });
}
fs.unlink(dashboardPath, err => {
if (err) {
console.error(err);
return res.end(err);
}
res.json({ ok: true });
});
}
catch (ex) {
res.json({ ok: false });
}
});
function getFileById(dir, id) {
=======
function getFileById(dir, id, overwrite) {
>>>>>>>
router.delete('/dashboards/:id', (req, res) => {
try {
let { id } = req.params;
const { privateDashboard } = paths();
let dashboardPath = path.join(privateDashboard, id + '.private.js');
let dashboardExists = fs.existsSync(dashboardPath);
if (!dashboardExists) {
return res.json({ errors: ['Could not find a Dashboard with the given id or filename'] });
}
fs.unlink(dashboardPath, err => {
if (err) {
console.error(err);
return res.end(err);
}
res.json({ ok: true });
});
}
catch (ex) {
res.json({ ok: false });
}
});
function getFileById(dir, id, overwrite) { |
<<<<<<<
* @param {Array.<{ maxAge: timestamp, type: string, identifier: string, datapoint: string, datapointId: int, callback: function }>} combinedRequest An array of data requests to resolve.
=======
* @param {Array.<{ maxAge: timestamp, dataObject: string, identifier: string, datapoint: string, datapointId: number, callback: function }>} combinedRequest An array of data requests to resolve.
>>>>>>>
* @param {Array.<{ maxAge: timestamp, type: string, identifier: string, datapoint: string, datapointId: number, callback: function }>} combinedRequest An array of data requests to resolve.
<<<<<<<
=======
*
* @return {void}
>>>>>>>
<<<<<<<
const cache = this.getCache( request.type + '::' + key, request.maxAge );
if ( 'undefined' !== typeof cache ) {
=======
const cache = this.getCache( request.dataObject, key, request.maxAge, hashlessKey );
if ( cache ) {
>>>>>>>
const cache = this.getCache( request.type + '::' + key, request.maxAge );
if ( 'undefined' !== typeof cache ) {
<<<<<<<
* Resolves a request.
=======
* Resolve a request.
*
* @param {Object} request Request object to resolve.
* @param {any} result Result to resolve this request with.
>>>>>>>
* Resolves a request.
*
* @param {Object} request Request object to resolve.
* @param {any} result Result to resolve this request with.
<<<<<<<
* @param {string} key The cache key,
* @param {mixed} data The data to cache.
=======
* @param {Object} dataObject The data object.
* @param {string} key The cache key,
* @param {Object} value The value to cache.
>>>>>>>
* @param {string} key The cache key,
* @param {mixed} data The data to cache.
<<<<<<<
lazilySetupLocalCache();
googlesitekit.admin.datacache[ key ] = data;
const storage = detectPersistentCache();
if ( ! storage ) {
return;
=======
if ( window.sessionStorage ) {
const toStore = {
value,
date: Date.now() / 1000,
};
setCache( 'sessionStorage', dataObject + '::' + key, JSON.stringify( toStore ) );
>>>>>>>
lazilySetupLocalCache();
googlesitekit.admin.datacache[ key ] = data;
const storage = detectPersistentCache();
if ( ! storage ) {
return;
<<<<<<<
* @param {string} type The data to access. One of 'core' or 'modules'.
* @param {string} identifier The data identifier, for example a module slug.
* @param {string} datapoint The datapoint.
=======
* @param {Object} dataObject The data object.
* @param {string} key The cache key,
>>>>>>>
* @param {string} type The data to access. One of 'core' or 'modules'.
* @param {string} identifier The data identifier, for example a module slug.
* @param {string} datapoint The datapoint.
<<<<<<<
path: addQueryArgs( `/google-site-kit/v1/${type}/${identifier}/data/${datapoint}`, data )
=======
path: addQueryArgs( `/google-site-kit/v1/${ dataObject }/${ identifier }/data/${ datapoint }`, queryArgs ),
>>>>>>>
path: addQueryArgs( `/google-site-kit/v1/${ type }/${ identifier }/data/${ datapoint }`, data ),
<<<<<<<
* @return {Promise} A promise for the fetch request.
=======
* @return Promise A promise for the fetch request.
>>>>>>>
* @return {Promise} A promise for the fetch request.
<<<<<<<
// Make an API request to retrieve the notifications.
=======
// Make an API request to retrieve the value.
>>>>>>>
// Make an API request to retrieve the notifications.
<<<<<<<
* @return {Promise} A promise for the fetch request.
=======
* @return Promise A promise for the fetch request.
>>>>>>>
* @return {Promise} A promise for the fetch request.
<<<<<<<
* @return {Promise} A promise for the fetch request.
=======
* @return Promise A promise for the fetch request.
>>>>>>>
* @return {Promise} A promise for the fetch request.
<<<<<<<
const type = 'modules';
const originalValue = googlesitekit[ type ][ identifier ][ datapoint ];
=======
const dataObject = 'modules';
const originalValue = googlesitekit[ dataObject ][ identifier ][ datapoint ];
>>>>>>>
const type = 'modules';
const originalValue = googlesitekit[ type ][ identifier ][ datapoint ];
<<<<<<<
return wp.apiFetch( { path: `/google-site-kit/v1/${type}/${identifier}`,
=======
return wp.apiFetch( { path: `/google-site-kit/v1/${ dataObject }/${ identifier }`,
>>>>>>>
return wp.apiFetch( { path: `/google-site-kit/v1/${ type }/${ identifier }`, |
<<<<<<<
// Check if each section has zero data.
const adminBarImpressionsHasZeroData = useSelect( AdminBarImpressions.selectHasZeroData );
const adminBarClicksHasZeroData = useSelect( AdminBarClicks.selectHasZeroData );
const adminBarUniqueVisitorsHasZeroData = useSelect( AdminBarUniqueVisitors.selectHasZeroData );
const adminBarSessionsHasZeroData = useSelect( AdminBarSessions.selectHasZeroData );
=======
>>>>>>> |
<<<<<<<
const { Component, Fragment } = wp.element;
const { __, sprintf } = wp.i18n;
=======
/**
* WordPress dependencies
*/
import { Component } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
>>>>>>>
/**
* WordPress dependencies
*/
import { Component, Fragment } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n'; |
<<<<<<<
/**
* WordPress dependencies
*/
import { Component, Fragment } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
=======
const { Component, Fragment } = wp.element;
const { __, _x, sprintf } = wp.i18n;
>>>>>>>
/**
* WordPress dependencies
*/
import { Component, Fragment } from '@wordpress/element';
import { __, _x, sprintf } from '@wordpress/i18n'; |
<<<<<<<
=======
// Actions
const WAIT_FOR_EXISTING_TAG = 'WAIT_FOR_EXISTING_TAG';
const WAIT_FOR_TAG_PERMISSION = 'WAIT_FOR_TAG_PERMISSION';
>>>>>>>
// Actions
const WAIT_FOR_TAG_PERMISSION = 'WAIT_FOR_TAG_PERMISSION';
<<<<<<<
=======
const baseActions = {
waitForExistingTag() {
return {
payload: {},
type: WAIT_FOR_EXISTING_TAG,
};
},
waitForTagPermission( propertyID ) {
return {
payload: { propertyID },
type: WAIT_FOR_TAG_PERMISSION,
};
},
};
const baseControls = {
[ WAIT_FOR_EXISTING_TAG ]: createRegistryControl( ( registry ) => () => {
const isExistingTagLoaded = () => registry.select( STORE_NAME ).getExistingTag() !== undefined;
if ( isExistingTagLoaded() ) {
return true;
}
return new Promise( ( resolve ) => {
const unsubscribe = registry.subscribe( () => {
if ( isExistingTagLoaded() ) {
unsubscribe();
resolve();
}
} );
} );
} ),
[ WAIT_FOR_TAG_PERMISSION ]: createRegistryControl( ( registry ) => ( { payload: { propertyID } } ) => {
// Select first to ensure resolution is always triggered.
const { getTagPermission, hasFinishedResolution } = registry.select( STORE_NAME );
getTagPermission( propertyID );
const isTagPermissionLoaded = () => hasFinishedResolution( 'getTagPermission', [ propertyID ] );
if ( isTagPermissionLoaded() ) {
return;
}
return new Promise( ( resolve ) => {
const unsubscribe = registry.subscribe( () => {
if ( isTagPermissionLoaded() ) {
unsubscribe();
resolve();
}
} );
} );
} ),
};
>>>>>>>
const baseActions = {
waitForTagPermission( propertyID ) {
return {
payload: { propertyID },
type: WAIT_FOR_TAG_PERMISSION,
};
},
};
const baseControls = {
[ WAIT_FOR_TAG_PERMISSION ]: createRegistryControl( ( registry ) => ( { payload: { propertyID } } ) => {
// Select first to ensure resolution is always triggered.
const { getTagPermission, hasFinishedResolution } = registry.select( STORE_NAME );
getTagPermission( propertyID );
const isTagPermissionLoaded = () => hasFinishedResolution( 'getTagPermission', [ propertyID ] );
if ( isTagPermissionLoaded() ) {
return;
}
return new Promise( ( resolve ) => {
const unsubscribe = registry.subscribe( () => {
if ( isTagPermissionLoaded() ) {
unsubscribe();
resolve();
}
} );
} );
} ),
};
<<<<<<<
=======
* Check to see if an existing tag is available on the site.
*
* @since 1.8.0
*
* @param {Object} state Data store's state.
* @return {(boolean|undefined)} True if a tag exists, false if not; undefined if not loaded.
*/
hasExistingTag: createRegistrySelector( ( select ) => () => {
const existingTag = select( STORE_NAME ).getExistingTag();
return existingTag !== undefined ? !! existingTag : undefined;
} ),
/**
* Get an existing tag on the site, if present.
*
* @since 1.8.0
*
* @param {Object} state Data store's state.
* @return {(string|undefined)} Existing tag, or `null` if none.
* Returns `undefined` if not resolved yet.
*/
getExistingTag( state ) {
const { existingTag } = state;
if ( existingTag === undefined ) {
return undefined;
}
// It's possible to have an invalid accountID saved by something like the
// AMP plugin (see: https://github.com/google/site-kit-wp/issues/1651).
// Before returning a tag we should make sure it's valid.
return !! existingTag && isValidPropertyID( existingTag ) ? existingTag : null;
},
/**
>>>>>>> |
<<<<<<<
import Button from '../Button';
import ResetButton from '../reset-button';
=======
import Button from '../button';
import ResetButton from '../ResetButton';
>>>>>>>
import Button from '../Button';
import ResetButton from '../ResetButton'; |
<<<<<<<
// Actions
const START_FETCH_SET_MODULE_ACTIVATION = 'START_FETCH_SET_MODULE_ACTIVATION';
const FETCH_SET_MODULE_ACTIVATION = 'FETCH_SET_MODULE_ACTIVATION';
const FINISH_FETCH_SET_MODULE_ACTIVATION = 'FINISH_FETCH_SET_MODULE_ACTIVATION';
const CATCH_FETCH_SET_MODULE_ACTIVATION = 'CATCH_FETCH_SET_MODULE_ACTIVATION';
const START_FETCH_MODULES = 'START_FETCH_MODULES';
const FETCH_MODULES = 'FETCH_MODULES';
const FINISH_FETCH_MODULES = 'FINISH_FETCH_MODULES';
const CATCH_FETCH_MODULES = 'CATCH_FETCH_MODULES';
const RECEIVE_MODULES = 'RECEIVE_MODULES';
const REFETCH_AUTHENICATION = 'REFETCH_AUTHENICATION';
=======
const fetchGetModulesStore = createFetchStore( {
baseName: 'getModules',
controlCallback: () => {
return API.get( 'core', 'modules', 'list', null, {
useCache: false,
} );
},
reducerCallback: ( state, modules ) => {
return {
...state,
isAwaitingModulesRefresh: false,
modules: modules.reduce( ( acc, module ) => {
return { ...acc, [ module.slug ]: module };
}, {} ),
};
},
} );
const fetchSetModuleActivationStore = createFetchStore( {
baseName: 'setModuleActivation',
controlCallback: ( { slug, active } ) => {
return API.set( 'core', 'modules', 'activation', {
slug,
active,
} );
},
reducerCallback: ( state ) => {
// Updated module activation state is handled by re-fetching module
// data instead, so this reducer just sets the below flag.
return {
...state,
isAwaitingModulesRefresh: true,
};
},
argsToParams: ( slug, active ) => {
invariant( slug, 'slug is required.' );
invariant( active !== undefined, 'active is required.' );
return {
slug,
active,
};
},
} );
>>>>>>>
// Controls
const REFETCH_AUTHENICATION = 'REFETCH_AUTHENICATION';
const fetchGetModulesStore = createFetchStore( {
baseName: 'getModules',
controlCallback: () => {
return API.get( 'core', 'modules', 'list', null, {
useCache: false,
} );
},
reducerCallback: ( state, modules ) => {
return {
...state,
isAwaitingModulesRefresh: false,
modules: modules.reduce( ( acc, module ) => {
return { ...acc, [ module.slug ]: module };
}, {} ),
};
},
} );
const fetchSetModuleActivationStore = createFetchStore( {
baseName: 'setModuleActivation',
controlCallback: ( { slug, active } ) => {
return API.set( 'core', 'modules', 'activation', {
slug,
active,
} );
},
reducerCallback: ( state ) => {
// Updated module activation state is handled by re-fetching module
// data instead, so this reducer just sets the below flag.
return {
...state,
isAwaitingModulesRefresh: true,
};
},
argsToParams: ( slug, active ) => {
invariant( slug, 'slug is required.' );
invariant( active !== undefined, 'active is required.' );
return {
slug,
active,
};
},
} );
<<<<<<<
const { response, error } = yield actions.setModuleActivation( slug, true );
yield {
payload: {},
type: REFETCH_AUTHENICATION,
};
=======
const { response, error } = yield baseActions.setModuleActivation( slug, true );
>>>>>>>
const { response, error } = yield baseActions.setModuleActivation( slug, true );
yield {
payload: {},
type: REFETCH_AUTHENICATION,
};
<<<<<<<
const { response, error } = yield actions.setModuleActivation( slug, false );
yield {
payload: {},
type: REFETCH_AUTHENICATION,
};
=======
const { response, error } = yield baseActions.setModuleActivation( slug, false );
>>>>>>>
const { response, error } = yield baseActions.setModuleActivation( slug, false );
yield {
payload: {},
type: REFETCH_AUTHENICATION,
};
<<<<<<<
/**
* Stores modules received from the REST API.
*
* @since 1.5.0
* @private
*
* @param {Array} modules Modules from the API.
* @return {Object} Redux-style action.
*/
receiveModules( modules ) {
invariant( modules, 'modules is required.' );
return {
payload: { modules },
type: RECEIVE_MODULES,
};
},
};
export const controls = {
[ FETCH_SET_MODULE_ACTIVATION ]: ( { payload: { params } } ) => {
return API.set( 'core', 'modules', 'activation', params );
},
[ FETCH_MODULES ]: () => {
return API.get( 'core', 'modules', 'list', null, { useCache: false } );
},
[ REFETCH_AUTHENICATION ]: () => {
return API.get( 'core', 'user', 'authentication', { timestamp: Date.now() }, { useCache: false } );
},
};
export const reducer = ( state, { type, payload } ) => {
switch ( type ) {
case START_FETCH_SET_MODULE_ACTIVATION: {
const { slug } = payload.params;
return {
...state,
isFetchingSetModuleActivation: {
...state.isFetchingSetModuleActivation,
[ slug ]: true,
},
};
}
case FINISH_FETCH_SET_MODULE_ACTIVATION: {
const { slug } = payload.params;
return {
...state,
isFetchingSetModuleActivation: {
...state.isFetchingSetModuleActivation,
[ slug ]: false,
},
};
}
case CATCH_FETCH_SET_MODULE_ACTIVATION: {
const { slug } = payload.params;
return {
...state,
error: payload.error,
isFetchingSetModuleActivation: {
...state.isFetchingSetModuleActivation,
[ slug ]: false,
},
};
}
case START_FETCH_MODULES: {
return {
...state,
isFetchingModules: true,
};
}
case RECEIVE_MODULES: {
const { modules } = payload;
return {
...state,
modules: modules.reduce( ( acc, module ) => {
return { ...acc, [ module.slug ]: module };
}, {} ),
};
}
case FINISH_FETCH_MODULES: {
return {
...state,
isFetchingModules: false,
};
}
case CATCH_FETCH_MODULES: {
return {
...state,
error: payload.error,
isFetchingModules: false,
};
}
default: {
return { ...state };
}
}
=======
>>>>>>>
};
export const baseControls = {
[ REFETCH_AUTHENICATION ]: () => {
return API.get( 'core', 'user', 'authentication', { timestamp: Date.now() }, { useCache: false } );
}, |
<<<<<<<
if ( ( menuButtonRef && menuButtonRef.current ) && ( menuRef && menuRef.current ) ) {
// Close the menu if the user presses the Escape key
// or if they click outside of the menu.
if (
( ( 'keyup' === event.type && 27 === event.keyCode ) || 'mouseup' === event.type ) &&
! menuButtonRef.current.contains( event.target ) &&
! menuRef.current.contains( event.target )
) {
setMenuOpen( false );
}
=======
// Close the menu if the user presses the Escape key
// or if they click outside of the menu.
if (
( ( 'keyup' === event.type && ESCAPE === event.keyCode ) || 'mouseup' === event.type ) &&
! menuButtonRef.current.buttonRef.current.contains( event.target ) &&
! menuRef.current.menuRef.current.contains( event.target )
) {
setMenuOpen( false );
>>>>>>>
if ( ( menuButtonRef && menuButtonRef.current ) && ( menuRef && menuRef.current ) ) {
// Close the menu if the user presses the Escape key
// or if they click outside of the menu.
if (
( ( 'keyup' === event.type && ESCAPE === event.keyCode ) || 'mouseup' === event.type ) &&
! menuButtonRef.current.contains( event.target ) &&
! menuRef.current.contains( event.target )
) {
setMenuOpen( false );
}
<<<<<<<
const handleMenuItemSelect = useCallback( ( index ) => {
setDateRange( Object.values( ranges )[ index ].slug );
setMenuOpen( false );
=======
const handleMenuItemSelect = useCallback( ( index, event ) => {
if (
( 'keydown' === event.type && ( ENTER === event.keyCode || SPACE === event.keyCode ) ) || // Enter or Space is pressed.
'click' === event.type // Mouse is clicked
) {
setDateRange( Object.values( ranges )[ index ].slug );
setMenuOpen( false );
}
>>>>>>>
const handleMenuItemSelect = useCallback( ( index ) => {
setDateRange( Object.values( ranges )[ index ].slug );
setMenuOpen( false ); |
<<<<<<<
import { STORE_NAME } from '../../datastore';
=======
import ProgressBar from '../../../../components/progress-bar';
import { STORE_NAME } from '../../datastore/constants';
>>>>>>>
import { STORE_NAME } from '../../datastore/constants'; |
<<<<<<<
import { isZeroReport, reduceAdSenseData } from '../../util';
import { readableLargeNumber, extractForSparkline, getSiteKitAdminURL } from '../../../../util';
=======
import { reduceAdSenseData } from '../../util';
import { readableLargeNumber, getSiteKitAdminURL } from '../../../../util';
import extractForSparkline from '../../../../util/extract-for-sparkline';
>>>>>>>
import { isZeroReport, reduceAdSenseData } from '../../util';
import { readableLargeNumber, getSiteKitAdminURL } from '../../../../util';
import extractForSparkline from '../../../../util/extract-for-sparkline';
<<<<<<<
if ( isZeroReport( today ) && isZeroReport( period ) && isZeroReport( daily ) ) {
return getNoDataComponent( __( 'AdSense', 'google-site-kit' ) );
=======
if ( ! today?.totals && ! period?.totals && ! daily?.totals ) {
return <ReportZero moduleSlug="adsense" />;
>>>>>>>
if ( isZeroReport( today ) && isZeroReport( period ) && isZeroReport( daily ) ) {
return <ReportZero moduleSlug="adsense" />; |
<<<<<<<
import { STORE_NAME as CORE_FORMS } from '../../assets/js/googlesitekit/datastore/forms/constants';
import coreLocationStore from '../../assets/js/googlesitekit/datastore/location';
import { STORE_NAME as CORE_LOCATION } from '../../assets/js/googlesitekit/datastore/location/constants';
=======
import { CORE_FORMS } from '../../assets/js/googlesitekit/datastore/forms/constants';
>>>>>>>
import { CORE_FORMS } from '../../assets/js/googlesitekit/datastore/forms/constants';
import coreLocationStore from '../../assets/js/googlesitekit/datastore/location';
import { CORE_LOCATION } from '../../assets/js/googlesitekit/datastore/location/constants'; |
<<<<<<<
registry.dispatch( STORE_NAME ).finishResolution( 'getAccounts', [] );
=======
registry.dispatch( MODULES_TAGMANAGER ).setSettings( {} );
registry.dispatch( STORE_NAME ).finishResolution( 'getAccounts', [] );
>>>>>>>
registry.dispatch( MODULES_TAGMANAGER ).setSettings( {} );
registry.dispatch( STORE_NAME ).finishResolution( 'getAccounts', [] );
<<<<<<<
registry.dispatch( STORE_NAME ).finishResolution( 'getAccounts', [] );
=======
registry.dispatch( MODULES_TAGMANAGER ).setSettings( {} );
>>>>>>>
registry.dispatch( STORE_NAME ).finishResolution( 'getAccounts', [] );
registry.dispatch( MODULES_TAGMANAGER ).setSettings( {} ); |
<<<<<<<
} );
generateReportBasedWidgetStories( {
moduleSlug: 'analytics',
datastore: STORE_NAME,
group: 'Analytics Module/Components/Dashboard/Bounce Rate Widget',
data: dashboardBounceRateWidgetData,
options: dashboardBounceRateWidgetArgs,
component: DashboardBounceRateWidget,
} );
generateReportBasedWidgetStories( {
moduleSlug: 'analytics',
datastore: STORE_NAME,
group: 'Analytics Module/Components/Page Dashboard/Bounce Rate Widget',
data: dashboardBounceRateWidgetData,
options: dashboardBounceRateWidgetArgs,
component: DashboardBounceRateWidget,
} );
generateReportBasedWidgetStories( {
moduleSlug: 'analytics',
datastore: STORE_NAME,
group: 'Analytics Module/Components/Dashboard/Goals Widget',
data: dashboardGoalsWidgetData,
options: dashboardGoalsWidgetArgs,
component: DashboardGoalsWidget,
variantCallbacks: {
Loaded: ( dispatch, data, options ) => {
dispatch( STORE_NAME ).receiveGetReport( data, { options } );
dispatch( STORE_NAME ).receiveGetGoals( goals );
},
'Data Unavailable': ( dispatch ) => {
dispatch( STORE_NAME ).receiveGetGoals( goals );
},
},
} );
generateReportBasedWidgetStories( {
moduleSlug: 'analytics',
datastore: STORE_NAME,
group: 'Analytics Module/Components/Page Dashboard/Goals Widget',
data: dashboardGoalsWidgetData,
options: dashboardGoalsWidgetArgs,
component: DashboardGoalsWidget,
variantCallbacks: {
Loaded: ( dispatch, data, options ) => {
dispatch( STORE_NAME ).receiveGetReport( data, { options } );
dispatch( STORE_NAME ).receiveGetGoals( goals );
},
'Data Unavailable': ( dispatch ) => {
dispatch( STORE_NAME ).receiveGetGoals( goals );
},
},
} );
generateReportBasedWidgetStories( {
moduleSlug: 'analytics',
datastore: STORE_NAME,
group: 'Analytics Module/Components/Dashboard/Unique Visitors Widget',
data: {
visitorData: dashboardUniqueVisitorsVisitorData,
sparkData: dashboardUniqueVisitorsSparkData,
},
options: {
visitorArgs: dashboardUniqueVisitorsVisitorArgs,
sparkArgs: dashboardUniqueVisitorsSparkArgs,
},
component: DashboardUniqueVisitorsWidget,
variantCallbacks: {
Loaded: ( dispatch, data, options ) => {
const { visitorData, sparkData } = data;
const { visitorArgs, sparkArgs } = options;
dispatch( STORE_NAME ).receiveGetReport( visitorData, { options: visitorArgs } );
dispatch( STORE_NAME ).receiveGetReport( sparkData, { options: sparkArgs } );
},
'Data Unavailable': ( dispatch, data, options ) => {
const { visitorArgs, sparkArgs } = options;
dispatch( STORE_NAME ).receiveGetReport( [], { options: visitorArgs } );
dispatch( STORE_NAME ).receiveGetReport( [], { options: sparkArgs } );
},
Error: ( dispatch, data, options ) => {
const { visitorArgs, sparkArgs } = options;
const error = {
code: 'missing_required_param',
message: 'Request parameter is empty: metrics.',
data: {},
};
dispatch( STORE_NAME ).receiveError( error, 'getReport', [ visitorArgs ] );
dispatch( STORE_NAME ).finishResolution( 'getReport', [ visitorArgs ] );
},
},
} );
generateReportBasedWidgetStories( {
moduleSlug: 'analytics',
datastore: STORE_NAME,
group: 'Analytics Module/Components/Page Dashboard/Unique Visitors Widget',
data: {
visitorData: dashboardUniqueVisitorsVisitorData,
sparkData: dashboardUniqueVisitorsSparkData,
},
options: {
visitorArgs: dashboardUniqueVisitorsVisitorArgs,
sparkArgs: dashboardUniqueVisitorsSparkArgs,
},
component: DashboardUniqueVisitorsWidget,
variantCallbacks: {
Loaded: ( dispatch, data, options ) => {
const { visitorData, sparkData } = data;
const { visitorArgs, sparkArgs } = options;
dispatch( STORE_NAME ).receiveGetReport( visitorData, { options: visitorArgs } );
dispatch( STORE_NAME ).receiveGetReport( sparkData, { options: sparkArgs } );
},
'Data Unavailable': ( dispatch, data, options ) => {
const { visitorArgs, sparkArgs } = options;
dispatch( STORE_NAME ).receiveGetReport( [], { options: visitorArgs } );
dispatch( STORE_NAME ).receiveGetReport( [], { options: sparkArgs } );
},
Error: ( dispatch, data, options ) => {
const { visitorArgs, sparkArgs } = options;
const error = {
code: 'missing_required_param',
message: 'Request parameter is empty: metrics.',
data: {},
};
dispatch( STORE_NAME ).receiveError( error, 'getReport', [ visitorArgs ] );
dispatch( STORE_NAME ).finishResolution( 'getReport', [ visitorArgs ] );
},
},
=======
wrapWidget: false,
>>>>>>>
wrapWidget: false,
} );
generateReportBasedWidgetStories( {
moduleSlug: 'analytics',
datastore: STORE_NAME,
group: 'Analytics Module/Components/Dashboard/Bounce Rate Widget',
data: dashboardBounceRateWidgetData,
options: dashboardBounceRateWidgetArgs,
component: DashboardBounceRateWidget,
} );
generateReportBasedWidgetStories( {
moduleSlug: 'analytics',
datastore: STORE_NAME,
group: 'Analytics Module/Components/Page Dashboard/Bounce Rate Widget',
data: dashboardBounceRateWidgetData,
options: dashboardBounceRateWidgetArgs,
component: DashboardBounceRateWidget,
} );
generateReportBasedWidgetStories( {
moduleSlug: 'analytics',
datastore: STORE_NAME,
group: 'Analytics Module/Components/Dashboard/Goals Widget',
data: dashboardGoalsWidgetData,
options: dashboardGoalsWidgetArgs,
component: DashboardGoalsWidget,
variantCallbacks: {
Loaded: ( dispatch, data, options ) => {
dispatch( STORE_NAME ).receiveGetReport( data, { options } );
dispatch( STORE_NAME ).receiveGetGoals( goals );
},
'Data Unavailable': ( dispatch ) => {
dispatch( STORE_NAME ).receiveGetGoals( goals );
},
},
} );
generateReportBasedWidgetStories( {
moduleSlug: 'analytics',
datastore: STORE_NAME,
group: 'Analytics Module/Components/Page Dashboard/Goals Widget',
data: dashboardGoalsWidgetData,
options: dashboardGoalsWidgetArgs,
component: DashboardGoalsWidget,
variantCallbacks: {
Loaded: ( dispatch, data, options ) => {
dispatch( STORE_NAME ).receiveGetReport( data, { options } );
dispatch( STORE_NAME ).receiveGetGoals( goals );
},
'Data Unavailable': ( dispatch ) => {
dispatch( STORE_NAME ).receiveGetGoals( goals );
},
},
} );
generateReportBasedWidgetStories( {
moduleSlug: 'analytics',
datastore: STORE_NAME,
group: 'Analytics Module/Components/Dashboard/Unique Visitors Widget',
data: {
visitorData: dashboardUniqueVisitorsVisitorData,
sparkData: dashboardUniqueVisitorsSparkData,
},
options: {
visitorArgs: dashboardUniqueVisitorsVisitorArgs,
sparkArgs: dashboardUniqueVisitorsSparkArgs,
},
component: DashboardUniqueVisitorsWidget,
variantCallbacks: {
Loaded: ( dispatch, data, options ) => {
const { visitorData, sparkData } = data;
const { visitorArgs, sparkArgs } = options;
dispatch( STORE_NAME ).receiveGetReport( visitorData, { options: visitorArgs } );
dispatch( STORE_NAME ).receiveGetReport( sparkData, { options: sparkArgs } );
},
'Data Unavailable': ( dispatch, data, options ) => {
const { visitorArgs, sparkArgs } = options;
dispatch( STORE_NAME ).receiveGetReport( [], { options: visitorArgs } );
dispatch( STORE_NAME ).receiveGetReport( [], { options: sparkArgs } );
},
Error: ( dispatch, data, options ) => {
const { visitorArgs, sparkArgs } = options;
const error = {
code: 'missing_required_param',
message: 'Request parameter is empty: metrics.',
data: {},
};
dispatch( STORE_NAME ).receiveError( error, 'getReport', [ visitorArgs ] );
dispatch( STORE_NAME ).finishResolution( 'getReport', [ visitorArgs ] );
},
},
} );
generateReportBasedWidgetStories( {
moduleSlug: 'analytics',
datastore: STORE_NAME,
group: 'Analytics Module/Components/Page Dashboard/Unique Visitors Widget',
data: {
visitorData: dashboardUniqueVisitorsVisitorData,
sparkData: dashboardUniqueVisitorsSparkData,
},
options: {
visitorArgs: dashboardUniqueVisitorsVisitorArgs,
sparkArgs: dashboardUniqueVisitorsSparkArgs,
},
component: DashboardUniqueVisitorsWidget,
variantCallbacks: {
Loaded: ( dispatch, data, options ) => {
const { visitorData, sparkData } = data;
const { visitorArgs, sparkArgs } = options;
dispatch( STORE_NAME ).receiveGetReport( visitorData, { options: visitorArgs } );
dispatch( STORE_NAME ).receiveGetReport( sparkData, { options: sparkArgs } );
},
'Data Unavailable': ( dispatch, data, options ) => {
const { visitorArgs, sparkArgs } = options;
dispatch( STORE_NAME ).receiveGetReport( [], { options: visitorArgs } );
dispatch( STORE_NAME ).receiveGetReport( [], { options: sparkArgs } );
},
Error: ( dispatch, data, options ) => {
const { visitorArgs, sparkArgs } = options;
const error = {
code: 'missing_required_param',
message: 'Request parameter is empty: metrics.',
data: {},
};
dispatch( STORE_NAME ).receiveError( error, 'getReport', [ visitorArgs ] );
dispatch( STORE_NAME ).finishResolution( 'getReport', [ visitorArgs ] );
},
}, |
<<<<<<<
describe( 'needsReauthentication', () => {
it( 'dispatches an error if the request fails', async () => {
const response = {
code: 'internal_server_error',
message: 'Internal server error',
data: { status: 500 },
};
fetch
.doMockOnceIf( coreUserDataEndpointRegExp )
.mockResponseOnce(
JSON.stringify( response ),
{ status: 500 }
);
muteConsole( 'error' );
registry.select( STORE_NAME ).needsReauthentication();
await subscribeUntil( registry,
// TODO: We may want a selector for this, but for now this is fine
// because it's internal-only.
() => store.getState().isFetchingAuthentication === false,
);
const needsReauthentication = registry.select( STORE_NAME ).needsReauthentication();
const error = registry.select( STORE_NAME ).getError();
expect( fetch ).toHaveBeenCalledTimes( 1 );
expect( needsReauthentication ).toEqual( undefined );
expect( error ).toEqual( response );
} );
it( 'returns undefined if reauthentication info is not available', async () => {
// Create a mock to avoid triggering a network request error.
// The return value is irrelevant to the test.
fetch
.doMockOnceIf( coreUserDataEndpointRegExp )
.mockResponseOnce(
JSON.stringify( {} ),
{ status: 200 }
);
const needsReauthentication = registry.select( STORE_NAME ).needsReauthentication();
expect( needsReauthentication ).toEqual( undefined );
} );
} );
=======
describe( 'getUnsatisfiedScopes', () => {
it( 'uses a resolver get all authentication info', async () => {
fetch
.doMockOnceIf( coreUserDataEndpointRegExp )
.mockResponseOnce(
JSON.stringify( coreUserDataExpectedResponse ),
{ status: 200 }
);
const initialUnsatisfiedScopes = registry.select( STORE_NAME ).getUnsatisfiedScopes();
// The scopes will be their initial value until the data is resolved.
expect( initialUnsatisfiedScopes ).toEqual( undefined );
await subscribeUntil( registry,
() => registry.select( STORE_NAME ).hasFinishedResolution( 'getAuthentication' )
);
const unsatisfiedScopes = registry.select( STORE_NAME ).getUnsatisfiedScopes();
expect( fetch ).toHaveBeenCalledTimes( 1 );
expect( unsatisfiedScopes ).toEqual( coreUserDataExpectedResponse.unsatisfiedScopes );
} );
it( 'dispatches an error if the request fails', async () => {
const response = {
code: 'internal_server_error',
message: 'Internal server error',
data: { status: 500 },
};
fetch
.doMockOnceIf( coreUserDataEndpointRegExp )
.mockResponseOnce(
JSON.stringify( response ),
{ status: 500 }
);
muteConsole( 'error' );
registry.select( STORE_NAME ).getUnsatisfiedScopes();
await subscribeUntil( registry,
() => registry.select( STORE_NAME ).hasFinishedResolution( 'getAuthentication' )
);
const unsatisfiedScopes = registry.select( STORE_NAME ).getUnsatisfiedScopes();
const error = registry.select( STORE_NAME ).getError();
expect( fetch ).toHaveBeenCalledTimes( 1 );
expect( unsatisfiedScopes ).toEqual( undefined );
expect( error ).toEqual( response );
} );
it( 'returns undefined if authentication info is not available', async () => {
// Create a mock to avoid triggering a network request error.
// The return value is irrelevant to the test.
fetch
.doMockOnceIf( coreUserDataEndpointRegExp )
.mockResponseOnce(
JSON.stringify( {} ),
{ status: 200 }
);
const unsatisfiedScopes = registry.select( STORE_NAME ).getUnsatisfiedScopes();
expect( unsatisfiedScopes ).toEqual( undefined );
} );
} );
>>>>>>>
describe( 'getUnsatisfiedScopes', () => {
it( 'uses a resolver get all authentication info', async () => {
fetch
.doMockOnceIf( coreUserDataEndpointRegExp )
.mockResponseOnce(
JSON.stringify( coreUserDataExpectedResponse ),
{ status: 200 }
);
const initialUnsatisfiedScopes = registry.select( STORE_NAME ).getUnsatisfiedScopes();
// The scopes will be their initial value until the data is resolved.
expect( initialUnsatisfiedScopes ).toEqual( undefined );
await subscribeUntil( registry,
() => registry.select( STORE_NAME ).hasFinishedResolution( 'getAuthentication' )
);
const unsatisfiedScopes = registry.select( STORE_NAME ).getUnsatisfiedScopes();
expect( fetch ).toHaveBeenCalledTimes( 1 );
expect( unsatisfiedScopes ).toEqual( coreUserDataExpectedResponse.unsatisfiedScopes );
} );
it( 'dispatches an error if the request fails', async () => {
const response = {
code: 'internal_server_error',
message: 'Internal server error',
data: { status: 500 },
};
fetch
.doMockOnceIf( coreUserDataEndpointRegExp )
.mockResponseOnce(
JSON.stringify( response ),
{ status: 500 }
);
muteConsole( 'error' );
registry.select( STORE_NAME ).getUnsatisfiedScopes();
await subscribeUntil( registry,
() => registry.select( STORE_NAME ).hasFinishedResolution( 'getAuthentication' )
);
const unsatisfiedScopes = registry.select( STORE_NAME ).getUnsatisfiedScopes();
const error = registry.select( STORE_NAME ).getError();
expect( fetch ).toHaveBeenCalledTimes( 1 );
expect( unsatisfiedScopes ).toEqual( undefined );
expect( error ).toEqual( response );
} );
it( 'returns undefined if authentication info is not available', async () => {
// Create a mock to avoid triggering a network request error.
// The return value is irrelevant to the test.
fetch
.doMockOnceIf( coreUserDataEndpointRegExp )
.mockResponseOnce(
JSON.stringify( {} ),
{ status: 200 }
);
const unsatisfiedScopes = registry.select( STORE_NAME ).getUnsatisfiedScopes();
expect( unsatisfiedScopes ).toEqual( undefined );
} );
} );
describe( 'needsReauthentication', () => {
it( 'dispatches an error if the request fails', async () => {
const response = {
code: 'internal_server_error',
message: 'Internal server error',
data: { status: 500 },
};
fetch
.doMockOnceIf( coreUserDataEndpointRegExp )
.mockResponseOnce(
JSON.stringify( response ),
{ status: 500 }
);
muteConsole( 'error' );
registry.select( STORE_NAME ).needsReauthentication();
await subscribeUntil( registry,
// TODO: We may want a selector for this, but for now this is fine
// because it's internal-only.
() => store.getState().isFetchingAuthentication === false,
);
const needsReauthentication = registry.select( STORE_NAME ).needsReauthentication();
const error = registry.select( STORE_NAME ).getError();
expect( fetch ).toHaveBeenCalledTimes( 1 );
expect( needsReauthentication ).toEqual( undefined );
expect( error ).toEqual( response );
} );
it( 'returns undefined if reauthentication info is not available', async () => {
// Create a mock to avoid triggering a network request error.
// The return value is irrelevant to the test.
fetch
.doMockOnceIf( coreUserDataEndpointRegExp )
.mockResponseOnce(
JSON.stringify( {} ),
{ status: 200 }
);
const needsReauthentication = registry.select( STORE_NAME ).needsReauthentication();
expect( needsReauthentication ).toEqual( undefined );
} );
} ); |
<<<<<<<
* @since n.e.x.t
* @private
=======
* @since 1.11.0
>>>>>>>
* @since 1.11.0
* @private
<<<<<<<
* @since n.e.x.t
* @private
=======
* @since 1.11.0
>>>>>>>
* @since 1.11.0
* @private
<<<<<<<
* @since n.e.x.t
* @private
*
* @param {number} count Number of containers to generate.
* @param {Object} [overrides] Optional. Object of container field overrides.
* @return {Object[]} Array of generated container objects.
*/
export const buildContainers = ( count, overrides ) => {
return Array.from( { length: count } )
.map( () => containerBuilder( { overrides } ) );
};
/**
* Generates an account with one or more containers.
*
* @since n.e.x.t
* @private
=======
* @since 1.11.0
>>>>>>>
* @since n.e.x.t
* @private
*
* @param {number} count Number of containers to generate.
* @param {Object} [overrides] Optional. Object of container field overrides.
* @return {Object[]} Array of generated container objects.
*/
export const buildContainers = ( count, overrides ) => {
return Array.from( { length: count } )
.map( () => containerBuilder( { overrides } ) );
};
/**
* Generates an account with one or more containers.
*
* @since 1.11.0
* @private |
<<<<<<<
import goals from './goals';
=======
import adsense from './adsense';
>>>>>>>
import adsense from './adsense';
import goals from './goals';
<<<<<<<
goals,
=======
adsense,
>>>>>>>
adsense,
goals, |
<<<<<<<
=======
import { default as setupTagMatchers } from '../components/setup/tag-matchers';
import { default as adsenseTagMatchers } from '../modules/adsense/util/tagMatchers';
import { default as analyticsTagMatchers } from '../modules/analytics/util/tagMatchers';
import { tagMatchers as tagmanagerTagMatchers } from '../modules/tagmanager/util';
>>>>>>>
<<<<<<<
import data, { TYPE_CORE } from '../components/data';
import { fillFilterWithComponent } from './helpers';
=======
>>>>>>>
import { fillFilterWithComponent } from './helpers'; |
<<<<<<<
<<<<<<< HEAD
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define('bootstrap.wysihtml5.es-AR', ['jquery', 'bootstrap.wysihtml5'], factory);
} else {
// Browser globals
factory(jQuery);
}
}(function($){
$.fn.wysihtml5.locale["es-AR"] = {
font_styles: {
normal: "Texto normal",
h1: "Título 1",
h2: "Título 2",
h3: "Título 3",
h4: "Título 4",
h5: "Título 5",
h6: "Título 6"
},
emphasis: {
bold: "Negrita",
italic: "Itálica",
underline: "Subrayado",
small: "Subíndice"
},
lists: {
ordered: "Lista ordenada",
unordered: "Lista desordenada",
indent: "Agregar sangría",
outdent: "Eliminar sangría"
},
link: {
insert: "Insertar enlace",
cancel: "Cancelar",
target: "Abrir enlace en una ventana nueva"
},
image: {
insert: "Insertar imagen",
cancel: "Cancelar"
},
html: {
edit: "Editar HTML"
},
colours: {
black: "Negro",
silver: "Plata",
gray: "Gris",
maroon: "Marrón",
red: "Rojo",
purple: "Púrpura",
green: "Verde",
olive: "Oliva",
navy: "Azul Marino",
blue: "Azul",
orange: "Naranja"
}
};
}));
=======
(function($){
$.fn.wysihtml5.locale["es-AR"] = {
font_styles: {
normal: "Texto normal",
h1: "Título 1",
h2: "Título 2",
h3: "Título 3",
h4: "Título 4",
h5: "Título 5",
h6: "Título 6"
},
emphasis: {
bold: "Negrita",
italic: "Itálica",
underline: "Subrayado",
small: "Subíndice"
},
lists: {
ordered: "Lista ordenada",
unordered: "Lista desordenada",
indent: "Agregar sangría",
outdent: "Eliminar sangría"
},
link: {
insert: "Insertar enlace",
cancel: "Cancelar",
target: "Abrir enlace en una ventana nueva"
},
image: {
insert: "Insertar imagen",
cancel: "Cancelar"
},
html: {
edit: "Editar HTML"
},
colours: {
black: "Negro",
silver: "Plata",
gray: "Gris",
maroon: "Marrón",
red: "Rojo",
purple: "Púrpura",
green: "Verde",
olive: "Oliva",
navy: "Azul Marino",
blue: "Azul",
orange: "Naranja"
}
};
}(jQuery));
>>>>>>> origin/master
=======
(function($){
$.fn.wysihtml5.locale["es-AR"] = {
font_styles: {
normal: "Texto normal",
h1: "Título 1",
h2: "Título 2",
h3: "Título 3",
h4: "Título 4",
h5: "Título 5",
h6: "Título 6"
},
emphasis: {
bold: "Negrita",
italic: "Itálica",
underline: "Subrayado",
small: "Subíndice"
},
lists: {
ordered: "Lista ordenada",
unordered: "Lista desordenada",
indent: "Agregar sangría",
outdent: "Eliminar sangría"
},
link: {
insert: "Insertar enlace",
cancel: "Cancelar",
target: "Abrir enlace en una ventana nueva"
},
image: {
insert: "Insertar imagen",
cancel: "Cancelar"
},
html: {
edit: "Editar HTML"
},
colours: {
black: "Negro",
silver: "Plata",
gray: "Gris",
maroon: "Marrón",
red: "Rojo",
purple: "Púrpura",
green: "Verde",
olive: "Oliva",
navy: "Azul Marino",
blue: "Azul",
orange: "Naranja"
}
};
}(jQuery));
>>>>>>>
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define('bootstrap.wysihtml5.es-AR', ['jquery', 'bootstrap.wysihtml5'], factory);
} else {
// Browser globals
factory(jQuery);
}
}(function($){
$.fn.wysihtml5.locale["es-AR"] = {
font_styles: {
normal: "Texto normal",
h1: "Título 1",
h2: "Título 2",
h3: "Título 3",
h4: "Título 4",
h5: "Título 5",
h6: "Título 6"
},
emphasis: {
bold: "Negrita",
italic: "Itálica",
underline: "Subrayado",
small: "Subíndice"
},
lists: {
ordered: "Lista ordenada",
unordered: "Lista desordenada",
indent: "Agregar sangría",
outdent: "Eliminar sangría"
},
link: {
insert: "Insertar enlace",
cancel: "Cancelar",
target: "Abrir enlace en una ventana nueva"
},
image: {
insert: "Insertar imagen",
cancel: "Cancelar"
},
html: {
edit: "Editar HTML"
},
colours: {
black: "Negro",
silver: "Plata",
gray: "Gris",
maroon: "Marrón",
red: "Rojo",
purple: "Púrpura",
green: "Verde",
olive: "Oliva",
navy: "Azul Marino",
blue: "Azul",
orange: "Naranja"
}
};
})); |
<<<<<<<
<<<<<<< HEAD
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define('bootstrap.wysihtml5.es-ES', ['jquery', 'bootstrap.wysihtml5'], factory);
} else {
// Browser globals
factory(jQuery);
}
}(function($){
$.fn.wysihtml5.locale["es-ES"] = {
font_styles: {
normal: "Texto normal",
h1: "Título 1",
h2: "Título 2",
h3: "Título 3",
h4: "Título 4",
h5: "Título 5",
h6: "Título 6"
},
emphasis: {
bold: "Negrita",
italic: "Itálica",
underline: "Subrayado",
small: "Subíndice"
},
lists: {
unordered: "Lista desordenada",
ordered: "Lista ordenada",
outdent: "Eliminar sangría",
indent: "Agregar sangría"
},
link: {
insert: "Insertar enlace",
cancel: "Cancelar",
target: "Abrir enlace en una ventana nueva"
},
image: {
insert: "Insertar imagen",
cancel: "Cancelar"
},
html: {
edit: "Editar HTML"
},
colours: {
black: "Negro",
silver: "Plata",
gray: "Gris",
maroon: "Marrón",
red: "Rojo",
purple: "Púrpura",
green: "Verde",
olive: "Oliva",
navy: "Azul Marino",
blue: "Azul",
orange: "Naranja"
}
};
}));
=======
(function($){
$.fn.wysihtml5.locale["es-ES"] = {
font_styles: {
normal: "Texto normal",
h1: "Título 1",
h2: "Título 2",
h3: "Título 3",
h4: "Título 4",
h5: "Título 5",
h6: "Título 6"
},
emphasis: {
bold: "Negrita",
italic: "Itálica",
underline: "Subrayado",
small: "Subíndice"
},
lists: {
unordered: "Lista desordenada",
ordered: "Lista ordenada",
outdent: "Eliminar sangría",
indent: "Agregar sangría"
},
link: {
insert: "Insertar enlace",
cancel: "Cancelar",
target: "Abrir enlace en una ventana nueva"
},
image: {
insert: "Insertar imagen",
cancel: "Cancelar"
},
html: {
edit: "Editar HTML"
},
colours: {
black: "Negro",
silver: "Plata",
gray: "Gris",
maroon: "Marrón",
red: "Rojo",
purple: "Púrpura",
green: "Verde",
olive: "Oliva",
navy: "Azul Marino",
blue: "Azul",
orange: "Naranja"
}
};
}(jQuery));
>>>>>>> origin/master
=======
(function($){
$.fn.wysihtml5.locale["es-ES"] = {
font_styles: {
normal: "Texto normal",
h1: "Título 1",
h2: "Título 2",
h3: "Título 3",
h4: "Título 4",
h5: "Título 5",
h6: "Título 6"
},
emphasis: {
bold: "Negrita",
italic: "Itálica",
underline: "Subrayado",
small: "Subíndice"
},
lists: {
unordered: "Lista desordenada",
ordered: "Lista ordenada",
outdent: "Eliminar sangría",
indent: "Agregar sangría"
},
link: {
insert: "Insertar enlace",
cancel: "Cancelar",
target: "Abrir enlace en una ventana nueva"
},
image: {
insert: "Insertar imagen",
cancel: "Cancelar"
},
html: {
edit: "Editar HTML"
},
colours: {
black: "Negro",
silver: "Plata",
gray: "Gris",
maroon: "Marrón",
red: "Rojo",
purple: "Púrpura",
green: "Verde",
olive: "Oliva",
navy: "Azul Marino",
blue: "Azul",
orange: "Naranja"
}
};
}(jQuery));
>>>>>>>
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define('bootstrap.wysihtml5.es-ES', ['jquery', 'bootstrap.wysihtml5'], factory);
} else {
// Browser globals
factory(jQuery);
}
}(function($){
$.fn.wysihtml5.locale["es-ES"] = {
font_styles: {
normal: "Texto normal",
h1: "Título 1",
h2: "Título 2",
h3: "Título 3",
h4: "Título 4",
h5: "Título 5",
h6: "Título 6"
},
emphasis: {
bold: "Negrita",
italic: "Itálica",
underline: "Subrayado",
small: "Subíndice"
},
lists: {
unordered: "Lista desordenada",
ordered: "Lista ordenada",
outdent: "Eliminar sangría",
indent: "Agregar sangría"
},
link: {
insert: "Insertar enlace",
cancel: "Cancelar",
target: "Abrir enlace en una ventana nueva"
},
image: {
insert: "Insertar imagen",
cancel: "Cancelar"
},
html: {
edit: "Editar HTML"
},
colours: {
black: "Negro",
silver: "Plata",
gray: "Gris",
maroon: "Marrón",
red: "Rojo",
purple: "Púrpura",
green: "Verde",
olive: "Oliva",
navy: "Azul Marino",
blue: "Azul",
orange: "Naranja"
}
};
})); |
<<<<<<<
// Drop any relations
function dropTable(item, next) {
=======
// Escape Table Name
table = utils.escapeName(table);
>>>>>>>
// Drop any relations
function dropTable(item, next) {
<<<<<<<
=======
// Escape Table Name
table = utils.escapeName(table);
>>>>>>>
<<<<<<<
=======
// Build a Query Object
var _query = new Query(dbs[table].definition);
// Escape Table Name
table = utils.escapeName(table);
>>>>>>>
// Build a Query Object
var _query = new Query(dbs[table].definition); |
<<<<<<<
var hmac = crypto.createHmac(algorithm, key);
=======
var hmac = crypto.createHmac('sha1', new Buffer(key));
>>>>>>>
var hmac = crypto.createHmac(algorithm, key);
<<<<<<<
var offset = digest_bytes[(hash_size/8 - 1)] & 0xf;
=======
var offset = digest_bytes[19] & 0xf;
>>>>>>>
var offset = digest_bytes[(hash_size/8 - 1)] & 0xf;
<<<<<<<
// .algorithm (optional) override the default algorighm (default sha1)
//
=======
//
>>>>>>>
// .algorithm (optional) override the default algorighm (default sha1)
//
<<<<<<<
var algorithm = options.algorithm || 'sha1';
=======
>>>>>>>
var algorithm = options.algorithm || 'sha1';
<<<<<<<
SecretKey.base32 = base32.encode(key).toString().replace(/=/g,'');
=======
SecretKey.base32 = base32.encode(key).replace(/=/g,'');
>>>>>>>
SecretKey.base32 = base32.encode(key).toString().replace(/=/g,'');
<<<<<<<
=======
var key = '';
>>>>>>>
<<<<<<<
return bytes;
};
=======
return key;
}
>>>>>>>
return bytes;
}; |
<<<<<<<
function cacheCoordsFor(listView, listItem, prepend) {
listItem.$el.remove();
=======
function cacheCoordsFor(listView, listItem) {
listItem.$el.detach();
>>>>>>>
function cacheCoordsFor(listView, listItem, prepend) {
listItem.$el.remove();
listItem.$el.detach(); |
<<<<<<<
async build (editor: any, path: string = editor.getPath()): Promise<any> {
if (!isValidEditor(editor)) {
throw new Error('invalid editor')
}
this.deleteMessages()
const options = this.goconfig.executor.getOptions('file')
const cmd = await this.goconfig.locator.findTool('go')
if (!cmd) {
throw new Error('cannot find go tool')
}
const buildPromise = this.lintInstall(cmd, options)
const testPromise = this.hasTests(path)
? this.lintTest(cmd, options)
: Promise.resolve({output: '', linterName: 'test', exitcode: 0})
=======
build (editor, path = editor.getPath()) {
if (!atom.config.get('go-plus.config.compileOnSave')) {
return Promise.resolve()
}
const that = this
return new Promise((resolve, reject) => {
if (!isValidEditor(editor)) {
reject(new Error('invalid editor'))
return
}
>>>>>>>
async build (editor: any, path: string = editor.getPath()): Promise<any> {
if (!atom.config.get('go-plus.config.compileOnSave')) {
return
}
if (!isValidEditor(editor)) {
throw new Error('invalid editor')
}
this.deleteMessages()
const options = this.goconfig.executor.getOptions('file')
const cmd = await this.goconfig.locator.findTool('go')
if (!cmd) {
throw new Error('cannot find go tool')
}
const buildPromise = this.lintInstall(cmd, options)
const testPromise = this.hasTests(path)
? this.lintTest(cmd, options)
: Promise.resolve({output: '', linterName: 'test', exitcode: 0}) |
<<<<<<<
godoc: null,
=======
loaded: null,
>>>>>>>
godoc: null,
loaded: null,
<<<<<<<
let pkgs = [ 'gofmt', 'tester-go', 'builder-go', 'go-get', 'go-config', 'godoc' ]
=======
let pkgs = [ 'gofmt', 'tester-go', 'builder-go', 'autocomplete-go', 'go-get', 'go-config' ]
>>>>>>>
let pkgs = [ 'gofmt', 'tester-go', 'builder-go', 'autocomplete-go', 'go-get', 'go-config', 'godoc' ]
<<<<<<<
let pkgs = [ 'gofmt', 'tester-go', 'builder-go', 'go-get', 'go-config', 'godoc' ]
=======
let pkgs = [ 'gofmt', 'tester-go', 'builder-go', 'autocomplete-go', 'go-get', 'go-config' ]
>>>>>>>
let pkgs = [ 'gofmt', 'tester-go', 'builder-go', 'autocomplete-go', 'go-get', 'go-config', 'godoc' ] |
<<<<<<<
=======
putAction = wiki.putAction = function(pageElement, action) {
var site;
action.date = (new Date()).getTime();
if ((site = pageElement.data('site')) != null) {
action.fork = site;
pageElement.find('h1 img').attr('src', '/favicon.png');
pageElement.find('h1 a').attr('href', '/');
pageElement.data('site', null);
state.setUrl();
addToJournal(pageElement.find('.journal'), {
type: 'fork',
site: site,
date: action.date
});
}
if (useLocalStorage()) {
pushToLocal(pageElement, action);
return pageElement.addClass("local");
} else {
return pushToServer(pageElement, action);
}
};
pushToLocal = function(pageElement, action) {
var page;
page = localStorage[pageElement.attr("id")];
if (page) page = JSON.parse(page);
if (action.type === 'create') page = action.item;
page || (page = pageElement.data("data"));
if (page.journal == null) page.journal = [];
page.journal.concat(action);
page.story = $(pageElement).find(".item").map(function() {
return $(this).data("item");
}).get();
localStorage[pageElement.attr("id")] = JSON.stringify(page);
return addToJournal(pageElement.find('.journal'), action);
};
pushToServer = function(pageElement, action) {
return $.ajax({
type: 'PUT',
url: "/page/" + (pageElement.attr('id')) + "/action",
data: {
'action': JSON.stringify(action)
},
success: function() {
return addToJournal(pageElement.find('.journal'), action);
},
error: function(xhr, type, msg) {
return wiki.log("ajax error callback", type, msg);
}
});
};
>>>>>>> |
<<<<<<<
var LEFTARROW, RIGHTARROW, addToJournal, createPage, doInternalLink, findScrollContainer, getItem, pushToLocal, pushToServer, putAction, refresh, resolveFrom, resolveLinks, scrollContainer, scrollTo, setActive, textEditor, useLocalStorage;
=======
var LEFTARROW, RIGHTARROW, addToJournal, asSlug, createPage, doInternalLink, doPlugin, emitHeader, findScrollContainer, firstUrlLocs, firstUrlPages, getItem, getPlugin, handleDragging, idx, initAddButton, initDragging, locsInDom, pagesInDom, pushToLocal, pushToServer, putAction, refresh, resolveFrom, resolveLinks, scripts, scrollContainer, scrollTo, setActive, setUrl, showState, textEditor, urlLocs, urlPage, urlPages, useLocalStorage, _len;
window.wiki = {};
>>>>>>>
var LEFTARROW, RIGHTARROW, addToJournal, createPage, doInternalLink, emitHeader, findScrollContainer, getItem, handleDragging, initAddButton, initDragging, pushToLocal, pushToServer, putAction, refresh, resolveFrom, resolveLinks, scrollContainer, scrollTo, setActive, textEditor, useLocalStorage;
<<<<<<<
wiki.dump = function() {
var i, p, _i, _j, _len, _len2, _ref, _ref2;
_ref = $('.page');
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
p = _ref[_i];
wiki.log('.page', p);
_ref2 = $(p).find('.item');
for (_j = 0, _len2 = _ref2.length; _j < _len2; _j++) {
i = _ref2[_j];
wiki.log('.item', i, 'data-item', $(i).data('item'));
}
}
return null;
};
=======
scripts = {};
wiki.getScript = function(url, callback) {
if (callback == null) callback = function() {};
if (scripts[url] != null) {
return callback();
} else {
return $.getScript(url, function() {
scripts[url] = true;
return callback();
});
}
};
getPlugin = wiki.getPlugin = function(name, callback) {
var plugin;
if (plugin = window.plugins[name]) return callback(plugin);
return wiki.getScript("/plugins/" + name + ".js", function() {
return callback(window.plugins[name]);
});
};
doPlugin = wiki.doPlugin = function(div, item) {
var error;
error = function(ex) {
var errorElement;
errorElement = $("<div />").addClass('error');
errorElement.text(ex.toString());
return div.append(errorElement);
};
try {
div.data('pageElement', div.parents(".page"));
div.data('item', item);
return getPlugin(item.type, function(plugin) {
if (plugin == null) {
throw TypeError("Can't find plugin for '" + item.type + "'");
}
try {
plugin.emit(div, item);
return plugin.bind(div, item);
} catch (err) {
return error(err);
}
});
} catch (err) {
return error(err);
}
};
>>>>>>>
<<<<<<<
if (site != null) {
$(pageElement).append("<h1><a href=\"//" + site + "\"><img src = \"/remote/" + site + "/favicon.png\" height = \"32px\"></a> " + page.title + "</h1>");
} else {
$(pageElement).append($("<h1 />").append($("<a />").attr('href', '/').append($("<img>").error(function(e) {
return plugin.get('favicon', function(favicon) {
return favicon.create();
});
}).attr('class', 'favicon').attr('src', '/favicon.png').attr('height', '32px')), " " + page.title));
}
=======
wiki.log('build', slug, 'site', site, 'context', context.join(' => '));
emitHeader(pageElement, page);
>>>>>>>
wiki.log('build', slug, 'site', site, 'context', context.join(' => '));
emitHeader(pageElement, page);
<<<<<<<
=======
scrollContainer = void 0;
findScrollContainer = function() {
var scrolled;
scrolled = $("body, html").filter(function() {
return $(this).scrollLeft() > 0;
});
if (scrolled.length > 0) {
return scrolled;
} else {
return $("body, html").scrollLeft(4).filter(function() {
return $(this).scrollLeft() > 0;
}).scrollTop(0);
}
};
scrollTo = function(el) {
var bodyWidth, contentWidth, maxX, minX, target, width;
if (scrollContainer == null) scrollContainer = findScrollContainer();
bodyWidth = $("body").width();
minX = scrollContainer.scrollLeft();
maxX = minX + bodyWidth;
wiki.log('scrollTo', el, el.position());
target = el.position().left;
width = el.outerWidth(true);
contentWidth = $(".page").outerWidth(true) * $(".page").size();
if (target < minX) {
return scrollContainer.animate({
scrollLeft: target
});
} else if (target + width > maxX) {
return scrollContainer.animate({
scrollLeft: target - (bodyWidth - width)
});
} else if (maxX > $(".pages").outerWidth()) {
return scrollContainer.animate({
scrollLeft: Math.min(target, contentWidth - bodyWidth)
});
}
};
setUrl = function() {
var idx, locs, page, pages, url;
if (history && history.pushState) {
locs = locsInDom();
pages = pagesInDom();
url = ((function() {
var _len, _results;
_results = [];
for (idx = 0, _len = pages.length; idx < _len; idx++) {
page = pages[idx];
_results.push("/" + ((locs != null ? locs[idx] : void 0) || 'view') + "/" + page);
}
return _results;
})()).join('');
if (url !== $(location).attr('pathname')) {
wiki.log('set state', locs, pages);
return history.pushState(null, null, url);
}
}
};
setActive = function(page) {
wiki.log('set active', page);
$(".active").removeClass("active");
return scrollTo($("#" + page).addClass("active"));
};
showState = function() {
var idx, name, newLocs, newPages, oldLocs, oldPages, previousPage, _i, _len, _len2, _ref;
oldPages = pagesInDom();
newPages = urlPages();
oldLocs = locsInDom();
newLocs = urlLocs();
wiki.log('showState', oldPages, newPages, oldLocs, newLocs);
previousPage = newPages;
if ((newPages === oldPages) && (newLocs === oldLocs)) return;
for (idx = 0, _len = newPages.length; idx < _len; idx++) {
name = newPages[idx];
if (__indexOf.call(oldPages, name) >= 0) {
delete oldPages[oldPages.indexOf(name)];
} else {
createPage(name, newLocs[idx]).insertAfter(previousPage).each(refresh);
}
previousPage = $('#' + name);
}
for (_i = 0, _len2 = oldPages.length; _i < _len2; _i++) {
name = oldPages[_i];
if ((_ref = $('#' + name)) != null) _ref.remove();
}
return setActive($('.page').last().attr('id'));
};
>>>>>>>
scrollContainer = void 0;
findScrollContainer = function() {
var scrolled;
scrolled = $("body, html").filter(function() {
return $(this).scrollLeft() > 0;
});
if (scrolled.length > 0) {
return scrolled;
} else {
return $("body, html").scrollLeft(4).filter(function() {
return $(this).scrollLeft() > 0;
}).scrollTop(0);
}
};
scrollTo = function(el) {
var bodyWidth, contentWidth, maxX, minX, target, width;
if (scrollContainer == null) scrollContainer = findScrollContainer();
bodyWidth = $("body").width();
minX = scrollContainer.scrollLeft();
maxX = minX + bodyWidth;
wiki.log('scrollTo', el, el.position());
target = el.position().left;
width = el.outerWidth(true);
contentWidth = $(".page").outerWidth(true) * $(".page").size();
if (target < minX) {
return scrollContainer.animate({
scrollLeft: target
});
} else if (target + width > maxX) {
return scrollContainer.animate({
scrollLeft: target - (bodyWidth - width)
});
} else if (maxX > $(".pages").outerWidth()) {
return scrollContainer.animate({
scrollLeft: Math.min(target, contentWidth - bodyWidth)
});
}
};
setActive = wiki.setActive = function(page) {
wiki.log('set active', page);
$(".active").removeClass("active");
return scrollTo($("#" + page).addClass("active"));
};
<<<<<<<
util.asSlug = function(name) {
return name.replace(/\s/g, '-').replace(/[^A-Za-z0-9-]/g, '').toLowerCase();
};
=======
util.emptyPage = function() {
return {
title: 'empty',
story: [],
journal: []
};
};
>>>>>>>
util.asSlug = function(name) {
return name.replace(/\s/g, '-').replace(/[^A-Za-z0-9-]/g, '').toLowerCase();
};
util.emptyPage = function() {
return {
title: 'empty',
story: [],
journal: []
};
}; |
<<<<<<<
var action, addContext, context, footerElement, journalElement, page, site, slug, storyElement, _i, _len, _ref, _ref1;
=======
var action, addContext, context, doItem, footerElement, journalElement, page, site, slug, storyElement, _i, _len, _ref, _ref2;
>>>>>>>
var action, addContext, context, doItem, footerElement, journalElement, page, site, slug, storyElement, _i, _len, _ref, _ref1;
<<<<<<<
}), storyElement = _ref1[0], journalElement = _ref1[1], footerElement = _ref1[2];
$.each(page.story, function(i, item) {
var div;
if ($.isArray(item)) {
item = item[0];
}
=======
}), storyElement = _ref2[0], journalElement = _ref2[1], footerElement = _ref2[2];
doItem = function(i) {
var div, item;
if (i >= page.story.length) return;
item = page.story[i];
if ($.isArray(item)) item = item[0];
>>>>>>>
}), storyElement = _ref1[0], journalElement = _ref1[1], footerElement = _ref1[2];
doItem = function(i) {
var div, item;
if (i >= page.story.length) {
return;
}
item = page.story[i];
if ($.isArray(item)) {
item = item[0];
} |
<<<<<<<
}
}, m('.items', [
ctrl.options()
.map(function (o) {
return o.value() ?
m('.item.scrollable', {'data-value': o.value(), onclick: function(e){
e.stopPropagation();
if (typeof ctrl.value === 'function')
ctrl.value.apply(this, [o.value()]);
ctrl.hideDropDown();
}}, o.title())
:
m('.group', o.title());
})
]))
)
]);
=======
}, m('.items', [
ctrl.options()
.map(function (o) {
return o.value() !== undefined && o.value() !== null && o.value() !== '' ?
m('.item.scrollable', {'data-value': o.value(), onclick: function(e){
e.stopPropagation();
if (typeof ctrl.value === 'function')
ctrl.value.apply(this, [o.value()]);
ctrl.hideDropDown();
}}, o.title())
:
m('.group', o.title());
})
]))
)
]);
>>>>>>>
}
}, m('.items', [
ctrl.options()
.map(function (o) {
return o.value() !== undefined && o.value() !== null && o.value() !== '' ?
m('.item.scrollable', {'data-value': o.value(), onclick: function(e){
e.stopPropagation();
if (typeof ctrl.value === 'function')
ctrl.value.apply(this, [o.value()]);
ctrl.hideDropDown();
}}, o.title())
:
m('.group', o.title());
})
]))
)
]); |
<<<<<<<
'frontend/express/public/javascripts/countly/countly.vue.components.js',
'frontend/express/public/javascripts/countly/countly.token.manager.js',
=======
'frontend/express/public/javascripts/countly/countly.vue.components.js',
'frontend/express/public/javascripts/countly/countly.version.history.js'
>>>>>>>
'frontend/express/public/javascripts/countly/countly.vue.components.js',
'frontend/express/public/javascripts/countly/countly.token.manager.js',
'frontend/express/public/javascripts/countly/countly.version.history.js' |
<<<<<<<
=======
if (updatedMember.member_image && updatedMember.member_image === 'delete') {
updatedMember.member_image = "";
}
/**
* Removes all active sessions for user
* @param {string} userId - id of the user for which to remove sessions
**/
function killAllSessionForUser(userId) {
common.db.collection('sessions_').find({"session": { $regex: userId }}).toArray(function(err, sessions) {
var delete_us = [];
for (let i = 0; i < sessions.length; i++) {
var parsed_data = "";
try {
parsed_data = JSON.parse(sessions[i].session);
}
catch (SyntaxError) {
console.log('Parse ' + sessions[i].session + ' JSON failed');
}
if (parsed_data && parsed_data.uid === userId) {
delete_us.push(sessions[i]._id);
}
}
if (delete_us.length > 0) {
common.db.collection('sessions_').remove({ '_id': { $in: delete_us } });
}
});
//delete auth tokens
common.db.collection('auth_tokens').remove({
'owner': userId,
'purpose': "LoggedInAuth"
});
>>>>>>>
if (updatedMember.member_image && updatedMember.member_image === 'delete') {
updatedMember.member_image = "";
} |
<<<<<<<
/** fetchedQuery
* @param {object} note - note object
* @param {array} uids - array of user ids
* @returns {object} query - query object
*/
_fetchedQuery(note, uids) {
=======
async _fetchedQuery(note, uids) {
>>>>>>>
/** fetchedQuery
* @param {object} note - note object
* @param {array} uids - array of user ids
* @returns {object} query - query object
*/
async _fetchedQuery(note, uids) {
<<<<<<<
pushFetched(note, uids, date, over, clear) {
=======
async pushFetched (note, uids, date, over, clear) {
>>>>>>>
async pushFetched (note, uids, date, over, clear) {
<<<<<<<
query = this._fetchedQuery(note, uids);
=======
query = await this._fetchedQuery(note, uids);
>>>>>>>
query = await this._fetchedQuery(note, uids);
<<<<<<<
/** pushNote
* @param {string/ObjectId} mid - object id
* @param {array} uids - user ids
* @param {object} date - date
* @returns {Promise} promise
*/
pushNote(mid, uids, date) {
=======
pushNote(mid, uids, date, recur) {
>>>>>>>
/** pushNote
* @param {string/ObjectId} mid - object id
* @param {array} uids - user ids
* @param {object} date - date
* @returns {Promise} promise
*/
pushNote(mid, uids, date, recur) {
<<<<<<<
reject(err);
}
else {
=======
if (recur === true) {
return reject(err);
}
this.db.collection(`app_users${this.app._id}`).find({uid: {$in: uids}}).toArray((error, users) => {
if (error) {
log.e('Error while loading users with msgs: %j', error);
return reject(err);
}
users = (users || []).filter(u => u.msgs && !Array.isArray(u.msgs));
if (!users.length) {
return reject(err);
}
log.w('Transforming %d users msgs from object back to array', users.length);
Promise.all(users.map(u => {
let arr = [];
Object.keys(u.msgs).forEach(k => {
arr.push(u.msgs[k]);
});
return new Promise((res, rej) => {
this.db.collection(`app_users${this.app._id}`).updateOne({uid: u.uid}, {$set: {msgs: arr}}, error => {
if (error) {
log.e('Error while transforming user %j: %j', u.uid, error);
rej(error);
} else {
res();
}
});
});
})).then(() => {
this.pushNote(mid, uids, date, true).then(resolve, reject);
}, () => {
reject(err);
});
});
} else {
>>>>>>>
if (recur === true) {
return reject(err);
}
this.db.collection(`app_users${this.app._id}`).find({uid: {$in: uids}}).toArray((error, users) => {
if (error) {
log.e('Error while loading users with msgs: %j', error);
return reject(err);
}
users = (users || []).filter(u => u.msgs && !Array.isArray(u.msgs));
if (!users.length) {
return reject(err);
}
log.w('Transforming %d users msgs from object back to array', users.length);
Promise.all(users.map(u => {
let arr = [];
Object.keys(u.msgs).forEach(k => {
arr.push(u.msgs[k]);
});
return new Promise((res, rej) => {
this.db.collection(`app_users${this.app._id}`).updateOne({uid: u.uid}, {$set: {msgs: arr}}, error => {
if (error) {
log.e('Error while transforming user %j: %j', u.uid, error);
rej(error);
} else {
res();
}
});
});
})).then(() => {
this.pushNote(mid, uids, date, true).then(resolve, reject);
}, () => {
reject(err);
});
}); |
<<<<<<<
query._id = {$ne: "meta_v2"};
validate(params, function(paramsNew) {
var columns = ["ts", "u", "a", "ip", "i"];
common.db.collection('systemlogs').count({}, function(err1, total) {
=======
query._id = {$ne:"meta_v2"};
validate(params, function(params){
var columns = ["", "ts", "u", "a", "ip", "i"];
common.db.collection('systemlogs').count({},function(err, total) {
>>>>>>>
query._id = {$ne: "meta_v2"};
validate(params, function(paramsNew) {
var columns = ["", "ts", "u", "a", "ip", "i"];
common.db.collection('systemlogs').count({}, function(err1, total) { |
<<<<<<<
req.body.email = (req.body.email + "").trim();
countlyDb.collection('members').findOne({"email": req.body.email}, function(err, member) {
if (member) {
var timestamp = Math.round(new Date().getTime() / 1000),
prid = sha512Hash(member.username + member.full_name, timestamp);
member.lang = member.lang || req.body.lang || "en";
countlyDb.collection('password_reset').insert({"prid": prid, "user_id": member._id, "timestamp": timestamp}, {safe: true}, function() {
countlyMail.sendPasswordResetInfo(member, prid);
plugins.callMethod("passwordRequest", {req: req, res: res, next: next, data: req.body});
res.redirect(countlyConfig.path + '/forgot?message=forgot.result');
});
}
else {
res.redirect(countlyConfig.path + '/forgot?message=forgot.result');
}
});
=======
if (countlyCommon.validateEmail(req.body.email)) {
membersUtility.forgot(req, function(/*member*/) {
res.render('forgot', { languages: languages, countlyFavicon: req.countly.favicon, countlyTitle: req.countly.title, countlyPage: req.countly.page, "message": "forgot.result", "csrf": req.csrfToken(), path: countlyConfig.path || "", cdn: countlyConfig.cdn || "", themeFiles: req.themeFiles, inject_template: req.template});
});
}
else {
res.send('invalid_email_format');
}
>>>>>>>
if (countlyCommon.validateEmail(req.body.email)) {
membersUtility.forgot(req, function(/*member*/) {
res.redirect(countlyConfig.path + '/forgot?message=forgot.result');
});
}
else {
res.redirect(countlyConfig.path + '/forgot?message=forgot.result');
}
<<<<<<<
var change = JSON.parse(JSON.stringify(updatedUser));
countlyDb.collection('members').findOne({"_id": countlyDb.ObjectID(req.session.uid + "")}, function(err, member) {
if (err || !member) {
return res.send(false);
}
countlyDb.collection('members').findOne({username: req.body.username}, async function(err2, user) {
if (err) {
return res.send(false);
}
member.change = change;
if ((user && user._id + "" !== req.session.uid + "") || err2) {
res.send("username-exists");
}
else {
if (req.body.old_pwd && req.body.old_pwd.length) {
if (isArgon2Hash(member.password)) {
var match;
try {
match = await verifyArgon2Hash(member.password, req.body.old_pwd);
}
catch (ex) {
match = null;
}
if (!match) {
return res.send("user-settings.old-password-not-match");
}
}
else {
var password_SHA1 = sha1Hash(req.body.old_pwd);
var password_SHA5 = sha512Hash(req.body.old_pwd);
if (member.password === password_SHA1 || member.password === password_SHA5) {
argon2Hash(req.body.old_pwd).then(password_ARGON2 => {
updateUserPasswordToArgon2(member._id, password_ARGON2);
}).catch(function() {
console.log("Problem updating password");
});
}
else {
return res.send("user-settings.old-password-not-match");
}
}
member.change.password = true;
try {
var newPassword_SHA5 = sha512Hash(req.body.new_pwd),
newPassword_ARGON2 = await argon2Hash(req.body.new_pwd);
}
catch (ex) {
return res.send(false);
}
let isUsedBefore = false;
if (plugins.getConfig('security').password_rotation > 0) {
// Check if used before
const promises = [];
const passwordHistory = member.password_history || [];
for (let i = 0; i < passwordHistory.length; i++) {
const oldPassword = passwordHistory[i];
if (isArgon2Hash(oldPassword)) {
promises.push(verifyArgon2Hash(oldPassword, req.body.new_pwd));
}
else if (oldPassword === newPassword_SHA5) {
isUsedBefore = true;
break;
}
}
if (!isUsedBefore && promises.length > 0) {
try {
const promiseResults = await Promise.all(promises);
isUsedBefore = promiseResults.some(x => x === true);
}
catch (ex) {
return res.send(false);
}
}
}
if (req.body.new_pwd !== req.body.old_pwd && !isUsedBefore) {
var passRes = validatePassword(req.body.new_pwd);
if (passRes === false) {
updatedUser.password = newPassword_ARGON2;
updatedUser.password_changed = Math.round(new Date().getTime() / 1000);
countlyDb.collection('members').update({"_id": countlyDb.ObjectID(req.session.uid + "")}, {'$set': updatedUser, $push: {password_history: {$each: [newPassword_ARGON2], $slice: -parseInt(plugins.getConfig('security').password_rotation)}}}, {safe: true}, function(err3, result) {
if (result && result.result && result.result.ok && result.result.nModified > 0 && !err3) {
killOtherSessionsForUser(req.session.uid, req.session.auth_token, req.sessionID);
plugins.callMethod("userSettings", {req: req, res: res, next: next, data: member});
res.send(updatedUser.password_changed + "");
}
else {
res.send("user-settings.old-password-not-match");
}
});
}
else {
res.send(passRes);
}
}
else {
res.send("user-settings.password-not-old");
}
}
else {
countlyDb.collection('members').update({"_id": countlyDb.ObjectID(req.session.uid + "")}, {'$set': updatedUser}, {safe: true}, function(err3, result) {
if (result && !err3) {
plugins.callMethod("userSettings", {req: req, res: res, next: next, data: member});
res.send(true);
}
else {
res.send(false);
}
});
}
}
});
});
}
else {
res.send(false);
return false;
}
=======
return result;
});
>>>>>>>
return result;
}); |
<<<<<<<
mochaTest: {
test: {
options: {
reporter: 'spec',
timeout: 50000
},
src: ['test/*/*.js']
}
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-eslint');
grunt.loadNpmTasks('grunt-mocha-test');
grunt.registerTask('default', [/*'eslint', */'mochaTest']);
=======
src: ['test/*/*.js']
}
},
mocha_nyc: {
coverage: {
src: ['test/*/*.js'], // a folder works nicely
options: {
coverage:true, // this will make the grunt.event.on('coverage') event listener to be triggered
mask: '*.js',
excludes: ['bin/*', 'frontend/*', 'extend/*', 'Gruntfile.js', 'test/*'],
mochaOptions: ['--harmony', '--async-only', '--reporter', 'spec', '--timeout', '50000', '--exit'],
nycOptions: ['--harmony', '--clean', 'false'],//,'--include-all-sources' '--all'
reportFormats: ['none']
}
}
},
istanbul_check_coverage: {
default: {
options: {
coverageFolder: 'coverage*', // will check both coverage folders and merge the coverage results
check: {
lines: 80,
statements: 80
}
}
}
}
});
//code coverage
grunt.event.on('coverage', function(lcovFileContents, done){
// Check below on the section "The coverage event"
done();
});
grunt.loadNpmTasks('grunt-mocha-nyc');
grunt.registerTask('coverage', ['mocha_nyc:coverage']);
//-----------code coverage-----------
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-mocha-test');
>>>>>>>
mochaTest: {
test: {
options: {
reporter: 'spec',
timeout: 50000
},
src: ['test/*/*.js']
}
},
mocha_nyc: {
coverage: {
src: ['test/*/*.js'], // a folder works nicely
options: {
coverage:true, // this will make the grunt.event.on('coverage') event listener to be triggered
mask: '*.js',
excludes: ['bin/*', 'frontend/*', 'extend/*', 'Gruntfile.js', 'test/*'],
mochaOptions: ['--harmony', '--async-only', '--reporter', 'spec', '--timeout', '50000', '--exit'],
nycOptions: ['--harmony', '--clean', 'false'],//,'--include-all-sources' '--all'
reportFormats: ['none']
}
}
},
istanbul_check_coverage: {
default: {
options: {
coverageFolder: 'coverage*', // will check both coverage folders and merge the coverage results
check: {
lines: 80,
statements: 80
}
}
}
}
});
//code coverage
grunt.event.on('coverage', function(lcovFileContents, done){
// Check below on the section "The coverage event"
done();
});
grunt.loadNpmTasks('grunt-mocha-nyc');
grunt.registerTask('coverage', ['mocha_nyc:coverage']);
//-----------code coverage-----------
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-eslint');
grunt.loadNpmTasks('grunt-mocha-test');
grunt.registerTask('default', [/*'eslint', */'mochaTest']); |
<<<<<<<
if(!update_array['map'][idss[i]])
update_array['map'][idss[i]]={};
if(params.qstring.set_visibility=='hide')
update_array['map'][idss[i]]['is_visible'] = false;
else
update_array['map'][idss[i]]['is_visible'] = true;
if(update_array['map'][idss[i]]['is_visible'])
delete update_array['map'][idss[i]]['is_visible'];
if(Object.keys(update_array['map'][idss[i]]).length==0)
delete update_array['map'][idss[i]];
if(params.qstring.set_visibility=='hide')
=======
if(Object.keys(update_array['map'][idss[i]]).length==0)
delete update_array['map'][idss[i]];
if(params.qstring.set_visibility=='hide' && event && event.overview && Array.isArray(event.overview))
{
for(var j=0; j<event.overview.length; j++)
>>>>>>>
if(!update_array['map'][idss[i]])
update_array['map'][idss[i]]={};
if(params.qstring.set_visibility=='hide')
update_array['map'][idss[i]]['is_visible'] = false;
else
update_array['map'][idss[i]]['is_visible'] = true;
if(update_array['map'][idss[i]]['is_visible'])
delete update_array['map'][idss[i]]['is_visible'];
if(Object.keys(update_array['map'][idss[i]]).length==0)
delete update_array['map'][idss[i]];
if(params.qstring.set_visibility=='hide' && event && event.overview && Array.isArray(event.overview)) |
<<<<<<<
var traverse = require('traverse');
/**
* Try to parse provided value as JSON, or some other value
* @param {string} val - value to parse
* @returns {string|object} parsed value
**/
var defaultParser = function(val) {
=======
var parser = function(val) {
>>>>>>>
/**
* Try to parse provided value as JSON, or some other value
* @param {string} val - value to parse
* @returns {string|object} parsed value
**/
var defaultParser = function(val) {
<<<<<<<
/**
* Try to process configuration
* @param {object} config - configuration to process
* @param {function} parser - parser to use on each property
**/
var read = function(config, parser) {
var tc = traverse(config);
var tcKeyMap = {};
=======
const OVERRIDES = {
MONGODB: {
REPLSETSERVERS: 'replSetServers',
REPLICANAME: 'replicaName',
MAX_POOL_SIZE: 'max_pool_size',
DBOPTIONS: 'dbOptions',
SERVEROPTIONS: 'serverOptions'
},
>>>>>>>
const OVERRIDES = {
MONGODB: {
REPLSETSERVERS: 'replSetServers',
REPLICANAME: 'replicaName',
MAX_POOL_SIZE: 'max_pool_size',
DBOPTIONS: 'dbOptions',
SERVEROPTIONS: 'serverOptions'
},
<<<<<<<
module.exports = function(config) {
read(config, defaultParser);
=======
>>>>>>> |
<<<<<<<
(function (prevent) {
//countly database connection
prevent.db = null;
//mail service
prevent.mail = null;
//allowed fails
prevent.fails = 3;
//first wait time after reaching fail amount
prevent.wait = 5*60;
//paths to prevent
prevent.paths = [];
prevent.defaultPrevent = function(req, res, next){
if(req.method.toLowerCase() == 'post' && prevent.paths.indexOf(req.path) !== -1){
var username = req.body.username;
if(username){
prevent.isBlocked(username, function(isBlocked, fails, err){
req.session.fails = fails;
if(isBlocked){
if(err){
res.status(500).send('Server Error');
}
else{
//blocking user
prevent.db.collection("members").findOne({ username : username}, function(err, member){
if(member)
prevent.mail.sendTimeBanWarning(member, prevent.db);
})
res.redirect(req.path+'?message=login.blocked');
}
=======
//countly database connection
prevent.collection = null;
prevent.memberCollection = null;
//mail service
prevent.mail = null;
//allowed fails
prevent.fails = 3;
//first wait time after reaching fail amount
prevent.wait = 5 * 60;
//paths to prevent
prevent.paths = [];
prevent.defaultPrevent = function(req, res, next) {
if (req.method.toLowerCase() === 'post' && prevent.paths.indexOf(req.path) !== -1) {
var username = req.body.username;
if (username) {
prevent.isBlocked(username, function(isBlocked, fails, err) {
req.session.fails = fails;
if (isBlocked) {
if (err) {
res.status(500).send('Server Error');
>>>>>>>
//countly database connection
prevent.db = null;
//mail service
prevent.mail = null;
//allowed fails
prevent.fails = 3;
//first wait time after reaching fail amount
prevent.wait = 5 * 60;
//paths to prevent
prevent.paths = [];
prevent.defaultPrevent = function(req, res, next) {
if (req.method.toLowerCase() === 'post' && prevent.paths.indexOf(req.path) !== -1) {
var username = req.body.username;
if (username) {
prevent.isBlocked(username, function(isBlocked, fails, err) {
req.session.fails = fails;
if (isBlocked) {
if (err) {
res.status(500).send('Server Error');
<<<<<<<
};
prevent.isBlocked = function(id, callback){
prevent.db.collection("failed_logins").findOne({_id:id}, function(err, result){
result = result || {fails:0};
if(err){
callback(true, result.fails, err);
}
else if(result.fails > 0 && result.fails % prevent.fails == 0 && getTimestamp() < (((result.fails/prevent.fails)*prevent.wait)+result.lastFail)){
//blocking user
callback(true, result.fails);
}
else{
callback(false, result.fails);
}
});
};
prevent.reset = function(id, callback){
callback = callback || function(){};
prevent.db.collection("failed_logins").remove({_id:id}, callback);
};
prevent.fail = function(id, callback){
callback = callback || function(){};
prevent.db.collection("failed_logins").update({_id:id}, {$inc:{fails:1}, $set:{lastFail:getTimestamp()}},{upsert:true}, callback);
};
//helpers
function getTimestamp(){
return Math.floor(new Date().getTime()/1000);
=======
>>>>>>> |
<<<<<<<
var countlyFs = require('./countlyFs');
var log = require('./log.js')('core:render');
=======
var countlyConfig = require('./../config', 'dont-enclose');
>>>>>>>
var countlyFs = require('./countlyFs');
var log = require('./log.js')('core:render');
var countlyConfig = require('./../config', 'dont-enclose'); |
<<<<<<<
=======
common.db = plugins.dbConnection();
common.writeBatcher = new WriteBatcher(common.db);
common.readBatcher = new ReadBatcher(common.db);
>>>>>>>
common.writeBatcher = new WriteBatcher(common.db);
common.readBatcher = new ReadBatcher(common.db);
<<<<<<<
plugins.dispatch("/master", {});
=======
plugins.dispatch("/master", {});
// Allow configs to load & scanner to find all jobs classes
setTimeout(() => {
jobs.job('api:topEvents').replace().schedule('every 1 day');
jobs.job('api:ping').replace().schedule('every 1 day');
jobs.job('api:clear').replace().schedule('every 1 day');
jobs.job('api:clearTokens').replace().schedule('every 1 day');
jobs.job('api:clearAutoTasks').replace().schedule('every 1 day');
jobs.job('api:task').replace().schedule('every 5 minutes');
//jobs.job('api:userMerge').replace().schedule('every 1 hour on the 10th min');
}, 10000);
}
else {
console.log("Starting worker", process.pid, "parent:", process.ppid);
const taskManager = require('./utils/taskmanager.js');
common.db = plugins.dbConnection(countlyConfig);
>>>>>>>
plugins.dispatch("/master", {});
<<<<<<<
common.cache = new CacheWorker(common.db);
common.cache.start();
=======
common.writeBatcher = new WriteBatcher(common.db);
common.readBatcher = new ReadBatcher(common.db);
//since process restarted mark running tasks as errored
taskManager.errorResults({db: common.db});
>>>>>>>
common.cache = new CacheWorker(common.db);
common.cache.start();
common.writeBatcher = new WriteBatcher(common.db);
common.readBatcher = new ReadBatcher(common.db);
<<<<<<<
process.on('message', (msg) => {
if (msg.cmd === 'log') {
common.log.ipcHandler(msg);
}
else if (msg.cmd === "dispatch" && msg.event) {
plugins.dispatch(msg.event, msg.data || {});
}
});
=======
process.on('exit', () => {
console.log('Exiting due to master exited');
});
>>>>>>>
process.on('message', (msg) => {
if (msg.cmd === 'log') {
common.log.ipcHandler(msg);
}
else if (msg.cmd === "dispatch" && msg.event) {
plugins.dispatch(msg.event, msg.data || {});
}
}); |
<<<<<<<
"bSortable": false
},
];
$('body').on('click', '.edit-event', function() {
$("#events-blueprint-drawer").addClass("open");
$('#eb-key-name').val($(this).data('event').key);
$('#eb-event-name').val($(this).data('event').name);
$('#eb-duration-name').val($(this).data('event').dur);
$('#eb-sum-name').val($(this).data('event').sum);
$('#eb-count-name').val($(this).data('event').count);
$('#eb-event-desc-input').val($(this).data('event').description);
var segments = [];
for (var i = 0; i < $(this).data('event').segments.length; i++) {
segments.push({name: $(this).data('event').segments[i], value: $(this).data('event').segments[i]})
}
var omittedSegments = [];
for (var i = 0; i < $(this).data('event').omittedSegments.length; i++) {
omittedSegments.push({name: $(this).data('event').omittedSegments[i], value: $(this).data('event').omittedSegments[i]})
}
$("#eb-multi-omit-segments-drop").clyMultiSelectSetItems(segments);
$("#eb-multi-omit-segments-drop").clyMultiSelectSetSelection(omittedSegments || []);
if ($(this).data('event').is_visible) {
$('#eb-event-visibility .on-off-switch input').attr('checked', 'checked');
$('#eb-event-visibility > div.on-off-switch > span').html(jQuery.i18n.map["events.edit.event-visible"]);
}
else {
$('#eb-event-visibility .on-off-switch input').removeAttr('checked');
$('#eb-event-visibility > div.on-off-switch > span').html();
}
$('#eb-event-desc-input').show();
if ($(this).data('event').description !== "") {
$('#eb-description-checkbox').removeClass('fa-square-o');
$('#eb-description-checkbox').addClass('fa-check-square');
$('#eb-event-desc-input').removeAttr('disabled');
}
else {
$('#eb-description-checkbox').removeClass('fa-check-square');
$('#eb-description-checkbox').addClass('fa-square-o');
$('#eb-event-desc-input').attr('disabled','disabled');
=======
"sClass": 'shrink right',
"sWidth": '100px',
"bSortable": false,
"bSearchable": false
>>>>>>>
"sClass": 'shrink right',
"sWidth": '100px',
"bSortable": false,
"bSearchable": false
},
];
$('body').on('click', '.edit-event', function() {
$("#events-blueprint-drawer").addClass("open");
$('#eb-key-name').val($(this).data('event').key);
$('#eb-event-name').val($(this).data('event').name);
$('#eb-duration-name').val($(this).data('event').dur);
$('#eb-sum-name').val($(this).data('event').sum);
$('#eb-count-name').val($(this).data('event').count);
$('#eb-event-desc-input').val($(this).data('event').description);
var segments = [];
for (var i = 0; i < $(this).data('event').segments.length; i++) {
segments.push({name: $(this).data('event').segments[i], value: $(this).data('event').segments[i]})
}
var omittedSegments = [];
for (var i = 0; i < $(this).data('event').omittedSegments.length; i++) {
omittedSegments.push({name: $(this).data('event').omittedSegments[i], value: $(this).data('event').omittedSegments[i]})
}
$("#eb-multi-omit-segments-drop").clyMultiSelectSetItems(segments);
$("#eb-multi-omit-segments-drop").clyMultiSelectSetSelection(omittedSegments || []);
if ($(this).data('event').is_visible) {
$('#eb-event-visibility .on-off-switch input').attr('checked', 'checked');
$('#eb-event-visibility > div.on-off-switch > span').html(jQuery.i18n.map["events.edit.event-visible"]);
}
else {
$('#eb-event-visibility .on-off-switch input').removeAttr('checked');
$('#eb-event-visibility > div.on-off-switch > span').html();
}
$('#eb-event-desc-input').show();
if ($(this).data('event').description !== "") {
$('#eb-description-checkbox').removeClass('fa-square-o');
$('#eb-description-checkbox').addClass('fa-check-square');
$('#eb-event-desc-input').removeAttr('disabled');
}
else {
$('#eb-description-checkbox').removeClass('fa-check-square');
$('#eb-description-checkbox').addClass('fa-square-o');
$('#eb-event-desc-input').attr('disabled','disabled');
<<<<<<<
//var self = this;
$("#eb-event-desc-input").show();
=======
var self = this;
>>>>>>>
var self = this;
$("#eb-event-desc-input").show(); |
<<<<<<<
el && (me.$el = $( el ));
// options中存在el时,覆盖el
options && options.el && (el = me.$el = $( options.el ));
// if( !el ) {
// throw new Error('Error! No element input.');
// return;
// }
=======
>>>>>>>
<<<<<<<
// 生成eventNs
me.eventNs = '.' + fn._fullname_ + uuid++;
// 执行父类的构造函数
superClass.apply( me, [ el, options ] );
me.superClass = fn.superClass = superClass;
// 初始化配置项监听
for( var opt in _optioned ){
if ( _optioned.hasOwnProperty(opt)) {
$( _optioned[ opt ] ).each( function( i, item ){
if ( item[0] === '*' || ($.isFunction( item[0] ) && item[0].call(me)) || item[0] === options[ opt ] ) {
item[ 1 ].call( me );
}
});
}
}
widgetInit.call( me, options );
// 组件初始化时才挂载插件,这样可以保证不同实例之间相互独立地使用插件,默认开启
for ( var i in fn.plugins ) {
var plugin = fn.plugins[ i ];
if( fn.plugins.hasOwnProperty( i ) && options[ i ] !== false ){
$.each( plugin, function( key, val ) {
var originFunction;
if ( ( originFunction = me[ key ] ) && $.isFunction( val ) ) {
me[ key ] = function() {
var _origin = me.origin,
result;
me.origin = originFunction;
result = val.apply( me, arguments );
if( _origin !== undefined ) {
me.origin = _origin;
} else {
delete me.origin;
}
return result;
};
}else{
me[ key ] = val;
}
});
fn.plugins[ i ]._init.call( me );
}
}
=======
/*
* NO CONFLICT
* var gmuPanel = $.fn.panel.noConflict();
* gmuPanel.call(test, 'fnname');
*/
$.fn[ key ].noConflict = function() {
$.fn[ key ] = old;
return this;
};
}
>>>>>>>
<<<<<<<
// 进行创建DOM等操作
me._create();
me.trigger('ready');
record( me.$el[ 0 ], fn._fullname_, me );
me.on( 'destroy', function() {
record( me.$el[ 0 ], fn._fullname_, null );
} );
return me;
};
$.extend( fn, {
extend: function( obj ){
$( staticlist ).each( function( i, item ) {
if(obj[ item ] !== undefined){
fn[ item ] = obj[ item ];
delete obj[ item ];
}
} );
if ( typeof fn.options === 'undefined' ) {
fn.options = {};
}
fn.options.template = fn.template;
fn.options.tpl2html = fn.tpl2html;
$.extend( fn.prototype, obj );
},
/**
* @name register
* @grammar fn.register({})
* @desc 注册插件
*/
register: function( name, obj ){
obj._init === undefined && ( obj._init = function(){} );
( fn.plugins || ( fn.plugins = {} ) )[ name ] = obj;
return fn;
},
/**
* @name inherits
* @grammar fn.inherits({})
* @desc 从该类继承出一个子类,不会被挂到gmu命名空间
*/
inherits: function( obj ){
return createClass( obj, fn );
},
/**
* @name option
* @grammar fn.option(option, value, method)
* @desc 扩充组件的配置项
*/
_optioned: {},
option: function( option, value, method ){
var covered = false;
if ( !fn._optioned[option] ) {
fn._optioned[option] = [];
}
=======
// 加载注册的option
function loadOption( klass, opts ) {
var me = this;
// 先加载父级的
if ( klass.superClass ) {
loadOption.call( me, klass.superClass, opts );
}
eachObject( record( klass, 'options' ), function( key, option ) {
option.forEach(function( item ) {
var condition = item[ 0 ],
fn = item[ 1 ];
if ( condition === '*' ||
($.isFunction( condition ) &&
condition.call( me, opts[ key ] )) ||
condition === opts[ key ] ) {
>>>>>>>
<<<<<<<
var evt = typeof name === 'string' ? new gmu.Event(name) : name,
args = [evt].concat( Array.prototype.slice.call( arguments, 1 ) ),
opEvent = this._options[evt.type],
=======
var evt = typeof name === 'string' ? new gmu.Event( name ) : name,
args = [ evt ].concat( slice.call( arguments, 1 ) ),
opEvent = this._options[ evt.type ],
>>>>>>> |
<<<<<<<
kValidatorCompiler,
kSerializerCompiler,
kReplySerializerDefault,
=======
kSchemaCompiler,
kSchemaResolver,
kReplySerializerDefault,
>>>>>>>
kValidatorCompiler,
kSerializerCompiler,
kReplySerializerDefault,
<<<<<<<
kPluginNameChain
=======
kGlobalHooks,
kPluginNameChain
>>>>>>>
kPluginNameChain
<<<<<<<
=======
if (options.logger && options.logger.genReqId) {
process.emitWarning("Using 'genReqId' in logger options is deprecated. Use fastify options instead. See: https://www.fastify.io/docs/latest/Server/#gen-request-id")
options.genReqId = options.logger.genReqId
}
const modifyCoreObjects = options.modifyCoreObjects !== false
>>>>>>>
<<<<<<<
const ajvOptions = Object.assign({
customOptions: {},
plugins: []
}, options.ajv)
// Ajv options
if (!ajvOptions.customOptions || Object.prototype.toString.call(ajvOptions.customOptions) !== '[object Object]') {
throw new Error(`ajv.customOptions option should be an object, instead got '${typeof ajvOptions.customOptions}'`)
}
if (!ajvOptions.plugins || !Array.isArray(ajvOptions.plugins)) {
throw new Error(`ajv.plugins option should be an array, instead got '${typeof ajvOptions.customOptions}'`)
}
ajvOptions.plugins = ajvOptions.plugins.map(plugin => {
return Array.isArray(plugin) ? plugin : [plugin]
})
=======
const ajvOptions = Object.assign({
customOptions: {},
plugins: []
}, options.ajv)
const frameworkErrors = options.frameworkErrors
// Ajv options
if (!ajvOptions.customOptions || Object.prototype.toString.call(ajvOptions.customOptions) !== '[object Object]') {
throw new Error(`ajv.customOptions option should be an object, instead got '${typeof ajvOptions.customOptions}'`)
}
if (!ajvOptions.plugins || !Array.isArray(ajvOptions.plugins)) {
throw new Error(`ajv.plugins option should be an array, instead got '${typeof ajvOptions.customOptions}'`)
}
ajvOptions.plugins = ajvOptions.plugins.map(plugin => {
return Array.isArray(plugin) ? plugin : [plugin]
})
>>>>>>>
const ajvOptions = Object.assign({
customOptions: {},
plugins: []
}, options.ajv)
const frameworkErrors = options.frameworkErrors
// Ajv options
if (!ajvOptions.customOptions || Object.prototype.toString.call(ajvOptions.customOptions) !== '[object Object]') {
throw new Error(`ajv.customOptions option should be an object, instead got '${typeof ajvOptions.customOptions}'`)
}
if (!ajvOptions.plugins || !Array.isArray(ajvOptions.plugins)) {
throw new Error(`ajv.plugins option should be an array, instead got '${typeof ajvOptions.customOptions}'`)
}
ajvOptions.plugins = ajvOptions.plugins.map(plugin => {
return Array.isArray(plugin) ? plugin : [plugin]
})
<<<<<<<
options.requestIdHeader = requestIdHeader
options.querystringParser = querystringParser
options.requestIdLogLabel = requestIdLogLabel
options.disableRequestLogging = disableRequestLogging
options.ajv = ajvOptions
=======
options.requestIdHeader = requestIdHeader
options.querystringParser = querystringParser
options.requestIdLogLabel = requestIdLogLabel
options.modifyCoreObjects = modifyCoreObjects
options.disableRequestLogging = disableRequestLogging
options.ajv = ajvOptions
const initialConfig = getSecuredInitialConfig(options)
>>>>>>>
options.requestIdHeader = requestIdHeader
options.querystringParser = querystringParser
options.requestIdLogLabel = requestIdLogLabel
options.disableRequestLogging = disableRequestLogging
options.ajv = ajvOptions
const initialConfig = getSecuredInitialConfig(options)
<<<<<<<
const httpHandler = router.routing
=======
const httpHandler = router.routing
// we need to set this before calling createServer
options.http2SessionTimeout = initialConfig.http2SessionTimeout
>>>>>>>
const httpHandler = router.routing
// we need to set this before calling createServer
options.http2SessionTimeout = initialConfig.http2SessionTimeout
<<<<<<<
[kValidatorCompiler]: null,
[kSerializerCompiler]: null,
[kReplySerializerDefault]: null,
[kContentTypeParser]: new ContentTypeParser(
bodyLimit,
(options.onProtoPoisoning || defaultInitOptions.onProtoPoisoning),
(options.onConstructorPoisoning || defaultInitOptions.onConstructorPoisoning)
),
=======
[kSchemaCompiler]: null,
[kSchemaResolver]: null,
[kReplySerializerDefault]: null,
[kContentTypeParser]: new ContentTypeParser(
bodyLimit,
(options.onProtoPoisoning || defaultInitOptions.onProtoPoisoning),
(options.onConstructorPoisoning || defaultInitOptions.onConstructorPoisoning)
),
>>>>>>>
[kValidatorCompiler]: null,
[kSerializerCompiler]: null,
[kReplySerializerDefault]: null,
[kContentTypeParser]: new ContentTypeParser(
bodyLimit,
(options.onProtoPoisoning || defaultInitOptions.onProtoPoisoning),
(options.onConstructorPoisoning || defaultInitOptions.onConstructorPoisoning)
),
<<<<<<<
setValidatorCompiler: setValidatorCompiler,
setSerializerCompiler: setSerializerCompiler,
setReplySerializer: setReplySerializer,
=======
setSchemaCompiler: setSchemaCompiler,
setSchemaResolver: setSchemaResolver,
setReplySerializer: setReplySerializer,
>>>>>>>
setValidatorCompiler: setValidatorCompiler,
setSerializerCompiler: setSerializerCompiler,
setReplySerializer: setReplySerializer,
<<<<<<<
if (name === 'onSend' || name === 'preSerialization' || name === 'onError') {
=======
// TODO: v3 instead of log a warning, throw an error
if (name === 'onSend' || name === 'preSerialization' || name === 'onError') {
>>>>>>>
if (name === 'onSend' || name === 'preSerialization' || name === 'onError') {
<<<<<<<
throw new Error('Async function has too many arguments. Async hooks should not use the \'done\' argument.')
=======
fastify.log.warn("Async function has too many arguments. Async hooks should not use the 'next' argument.", new Error().stack)
>>>>>>>
throw new Error('Async function has too many arguments. Async hooks should not use the \'done\' argument.')
<<<<<<<
throw new Error('Async function has too many arguments. Async hooks should not use the \'done\' argument.')
=======
fastify.log.warn("Async function has too many arguments. Async hooks should not use the 'next' argument.", new Error().stack)
>>>>>>>
throw new Error('Async function has too many arguments. Async hooks should not use the \'done\' argument.')
<<<<<<<
function onBadUrl (path, req, res) {
const body = `{"error":"Bad Request","message":"'${path}' is not a valid url component","statusCode":400}`
res.writeHead(400, {
'Content-Type': 'application/json',
'Content-Length': body.length
})
res.end(body)
}
=======
function onBadUrl (path, req, res) {
if (frameworkErrors) {
req.id = genReqId(req)
req.originalUrl = req.url
var childLogger = logger.child({ reqId: req.id })
if (modifyCoreObjects) {
req.log = res.log = childLogger
}
childLogger.info({ req }, 'incoming request')
const request = new Request(null, req, null, req.headers, childLogger)
const reply = new Reply(res, { onSend: [], onError: [] }, request, childLogger)
return frameworkErrors(new FST_ERR_BAD_URL(path), request, reply)
}
const body = `{"error":"Bad Request","message":"'${path}' is not a valid url component","statusCode":400}`
res.writeHead(400, {
'Content-Type': 'application/json',
'Content-Length': body.length
})
res.end(body)
}
>>>>>>>
function onBadUrl (path, req, res) {
if (frameworkErrors) {
var id = genReqId(req)
var childLogger = logger.child({ reqId: id })
childLogger.info({ req }, 'incoming request')
const request = new Request(id, req, null, req.headers, childLogger)
const reply = new Reply(res, { onSend: [], onError: [] }, request, childLogger)
return frameworkErrors(new FST_ERR_BAD_URL(path), request, reply)
}
const body = `{"error":"Bad Request","message":"'${path}' is not a valid url component","statusCode":400}`
res.writeHead(400, {
'Content-Type': 'application/json',
'Content-Length': body.length
})
res.end(body)
}
<<<<<<<
function setSerializerCompiler (serializerCompiler) {
throwIfAlreadyStarted('Cannot call "setSerializerCompiler" when fastify instance is already started!')
this[kSerializerCompiler] = serializerCompiler
=======
function setSchemaResolver (schemaRefResolver) {
throwIfAlreadyStarted('Cannot call "setSchemaResolver" when fastify instance is already started!')
this[kSchemaResolver] = schemaRefResolver
>>>>>>>
function setSerializerCompiler (serializerCompiler) {
throwIfAlreadyStarted('Cannot call "setSerializerCompiler" when fastify instance is already started!')
this[kSerializerCompiler] = serializerCompiler
<<<<<<<
for (const hook of instance[kHooks].onRegister) hook.call(this, instance, opts)
=======
for (const hook of instance[kGlobalHooks].onRegister) hook.call(this, instance, opts)
>>>>>>>
for (const hook of instance[kHooks].onRegister) hook.call(this, instance, opts) |
<<<<<<<
const ContentTypeParser = require('./lib/ContentTypeParser')
const { Hooks, hookRunner, hookIterator, buildHooks } = require('./lib/hooks')
=======
const ContentTypeParser = require('./lib/contentTypeParser')
const Hooks = require('./lib/hooks')
>>>>>>>
const ContentTypeParser = require('./lib/contentTypeParser')
const { Hooks, hookRunner, hookIterator, buildHooks } = require('./lib/hooks') |
<<<<<<<
const kFluentSchema = Symbol.for('fluent-schema-object')
=======
const { kSchemaVisited } = require('./symbols')
const kFluentSchema = Symbol.for('fluent-schema-object')
>>>>>>>
const { kSchemaVisited } = require('./symbols')
const kFluentSchema = Symbol.for('fluent-schema-object')
<<<<<<<
FST_ERR_SCH_DUPLICATE
=======
FST_ERR_SCH_NOT_PRESENT,
FST_ERR_SCH_DUPLICATE
>>>>>>>
FST_ERR_SCH_DUPLICATE
<<<<<<<
Schemas.prototype.add = function (inputSchema) {
var schema = fastClone((inputSchema.isFluentSchema || inputSchema[kFluentSchema])
? inputSchema.valueOf()
: inputSchema
)
// devs can add schemas without $id, but with $def instead
const id = schema.$id
if (!id) {
=======
Schemas.prototype.add = function (inputSchema, refResolver) {
var schema = fastClone((inputSchema.isFluentSchema || inputSchema[kFluentSchema])
? inputSchema.valueOf()
: inputSchema
)
const id = schema.$id
if (id === undefined) {
>>>>>>>
Schemas.prototype.add = function (inputSchema) {
var schema = fastClone((inputSchema.isFluentSchema || inputSchema[kFluentSchema])
? inputSchema.valueOf()
: inputSchema
)
// devs can add schemas without $id, but with $def instead
const id = schema.$id
if (!id) {
<<<<<<<
if (routeSchemas.body) {
routeSchemas.body = getSchemaAnyway(routeSchemas.body)
=======
// See issue https://github.com/fastify/fastify/issues/1767
const cachedSchema = Object.assign({}, routeSchemas)
try {
// this will work only for standard json schemas
// other compilers such as Joi will fail
this.traverse(routeSchemas, refResolver)
// when a plugin uses the 'skip-override' and call addSchema
// the same JSON will be pass throug all the avvio tree. In this case
// it is not possible clean the id. The id will be cleared
// in the startup phase by the call of validation.js. Details PR #1496
if (dontClearId !== true) {
this.cleanId(routeSchemas)
}
} catch (err) {
// if we have failed because `resolve` has thrown
// let's rethrow the error and let avvio handle it
if (/FST_ERR_SCH_*/.test(err.code)) throw err
// otherwise, the schema must not be a JSON schema
// so we let the user configured schemaCompiler handle it
return cachedSchema
>>>>>>>
if (routeSchemas.body) {
routeSchemas.body = getSchemaAnyway(routeSchemas.body)
<<<<<<<
function generateFluentSchema (schema) {
;['params', 'body', 'querystring', 'query', 'headers'].forEach(key => {
if (schema[key] && (schema[key].isFluentSchema || schema[key][kFluentSchema])) {
schema[key] = schema[key].valueOf()
=======
Schemas.prototype.traverse = function (schema, refResolver) {
for (var key in schema) {
// resolve the `sharedSchemaId#' only if is not a standard $ref JSON Pointer
if (typeof schema[key] === 'string' && key !== '$schema' && key !== '$ref' && schema[key].slice(-1) === '#') {
schema[key] = this.resolve(schema[key].slice(0, -1))
} else if (key === '$ref' && refResolver) {
const refValue = schema[key]
const framePos = refValue.indexOf('#')
const refId = framePos >= 0 ? refValue.slice(0, framePos) : refValue
if (refId.length > 0 && !this.store[refId]) {
const resolvedSchema = refResolver(refId)
if (resolvedSchema) {
this.add(resolvedSchema, refResolver)
}
}
}
if (schema[key] !== null && typeof schema[key] === 'object' &&
(key !== 'enum' || (key === 'enum' && schema.type !== 'string'))) {
// don't traverse non-object values and the `enum` keyword when used for string type
this.traverse(schema[key], refResolver)
>>>>>>>
function generateFluentSchema (schema) {
;['params', 'body', 'querystring', 'query', 'headers'].forEach(key => {
if (schema[key] && (schema[key].isFluentSchema || schema[key][kFluentSchema])) {
schema[key] = schema[key].valueOf()
<<<<<<<
function getSchemaAnyway (schema) {
if (schema.$ref || schema.oneOf || schema.allOf || schema.anyOf || schema.$merge || schema.$patch) return schema
if (!schema.type && !schema.properties) {
=======
Schemas.prototype.getSchemaAnyway = function (schema) {
if (schema.oneOf || schema.allOf || schema.anyOf || schema.$merge || schema.$patch) return schema
if (!schema.type || !schema.properties) {
>>>>>>>
function getSchemaAnyway (schema) {
if (schema.$ref || schema.oneOf || schema.allOf || schema.anyOf || schema.$merge || schema.$patch) return schema
if (!schema.type && !schema.properties) {
<<<<<<<
=======
Schemas.prototype.getSchemas = function () {
return Object.assign({}, this.store)
}
Schemas.prototype.getJsonSchemas = function (options) {
const store = this.getSchemas()
const schemasArray = Object.keys(store).map(schemaKey => {
// if the shared-schema "replace-way" has been used, the $id field has been removed
if (store[schemaKey].$id === undefined) {
store[schemaKey].$id = schemaKey
}
return store[schemaKey]
})
if (options && options.onlyAbsoluteUri === true) {
// the caller wants only the absolute URI (without the shared schema - "replace-way" usage)
return schemasArray.filter(_ => !/^\w*$/g.test(_.$id))
}
return schemasArray
}
>>>>>>> |
<<<<<<<
$(events).trigger('DataSetsCacheChanged', {
uri,
action: 'loaded',
cacheInfo: getCacheInfo()
});
}, (error) => {
reject(error);
}).then(() => {
=======
}, reject).then(() => {
>>>>>>>
$(events).trigger('DataSetsCacheChanged', {
uri,
action: 'loaded',
cacheInfo: getCacheInfo()
});
}, reject).then(() => { |
<<<<<<<
log({err: 'couch', body: parsed, headers: rh});
=======
if(verbose) {
console.log({err: 'couch', body: parsed, headers: rh});
}
if (!parsed) { parsed = {}; } // if HEAD request, body will be undefined
>>>>>>>
log({err: 'couch', body: parsed, headers: rh});
if (!parsed) { parsed = {}; } // if HEAD request, body will be undefined |
<<<<<<<
correct_answer = data['questions'][q_idx][2];
var wrong_answers = get_wrong_answers(label, correct_answer);
=======
>>>>>>>
correct_answer = data['questions'][q_idx][2];
var wrong_answers = get_wrong_answers(label, correct_answer); |
<<<<<<<
self._server._fiber(function() {
try {
=======
Fiber(function() {
try {
if(!self._beforeHandling('DELETE', self._requestPath.collectionId, self._requestCollection.findOne(self._requestPath.collectionId))) {
return self._rejectedResponse("Could not delete that object.");
}
>>>>>>>
self._server._fiber(function() {
try {
if(!self._beforeHandling('DELETE', self._requestPath.collectionId, self._requestCollection.findOne(self._requestPath.collectionId))) {
return self._rejectedResponse("Could not delete that object.");
} |
<<<<<<<
//TODO: figure what to put in controller, some dom modification should go in link
=======
//TODO figure what to put in controller, some dom modification should go in link
>>>>>>>
//TODO: figure what to put in controller, some dom modification should go in link
<<<<<<<
} else {
=======
}else{
>>>>>>>
} else {
<<<<<<<
} else {
mainChart.select(".chartOverlay").call(zoom);
=======
}else{
chartRect.call(zoom);
brushMainG.call(zoom)
.on("mousedown.zoom", null);
>>>>>>>
} else {
chartRect.call(zoom);
brushMainG.call(zoom)
.on("mousedown.zoom", null); |
<<<<<<<
this.updateHighlightRangeAndObtainDataPoints = function (graph, mouseOverHighlightBar, tipItems, series, sources, extraY, mousePositionData, timestampSelector, dateBisector, dateFormatter, isDataStacked, distanceToRight) {
var datapoints = [];
var bandOffset = graph.x0.bandwidth() + graph.x0.paddingInner()/2;
var xDomain = graph.x.domain();
var displayHighlightBar = false;
var xDiscreteDomain = graph.x0.domain();
var matchingTimestamp, i = d3.bisectLeft(xDiscreteDomain, mousePositionData.mouseX.getTime());
if (!xDiscreteDomain[i - 1]) {
// i === 0
matchingTimestamp = xDiscreteDomain[i];
} else if (!xDiscreteDomain[i]) {
// i === xDiscreteDomain.length
matchingTimestamp = xDiscreteDomain[i - 1];
} else {
matchingTimestamp = mousePositionData.positionX > graph.x0(xDiscreteDomain[i - 1]) + bandOffset ? xDiscreteDomain[i] : xDiscreteDomain[i - 1];
}
series.forEach(function (metric) {
var y = metric.extraYAxis ? extraY[metric.extraYAxis] : graph.y;
var displayingInLegend = ChartToolService.findMatchingMetricInSources(metric, sources).displaying;
if (metric.data.length === 0 || !displayingInLegend) {
// if the metric has no data or is toggled to hide
tipItems.selectAll('.' + metric.graphClassName).style('display', 'none');
} else {
var d = metric.data.find(function (d0) {
return timestampSelector(d0) === matchingTimestamp;
});
if (d === undefined) {
tipItems.selectAll('.' + metric.graphClassName).style('display', 'none');
} else {
var currentDatapoint = isDataStacked ? [d.data.timestamp, d.data[metric.name]] : d;
if (ChartToolService.isNotInTheDomain(currentDatapoint[0], xDomain) ||
ChartToolService.isNotInTheDomain(currentDatapoint[1], y.domain())) {
tipItems.selectAll('.' + metric.graphClassName).style('display', 'none');
} else {
tipItems.selectAll('.' + metric.graphClassName).style('display', null);
displayHighlightBar = true;
datapoints.push({
data: currentDatapoint,
graphClassName: metric.graphClassName,
name: metric.name
});
}
}
}
});
if (displayHighlightBar) {
var dateText = mouseOverHighlightBar.select('.crossLineTip');
var boxXRect = mouseOverHighlightBar.select('.crossLineTipRect');
var startingPosition = graph.x0(matchingTimestamp);
var date = dateFormatter(matchingTimestamp);
mouseOverHighlightBar.select('.highlightBar')
.attr('x', startingPosition)
.attr('dataX', matchingTimestamp)
.style('display', null);
dateText.attr('x', startingPosition).text(date);
var boxX = dateText.node().getBBox();
boxXRect.attr('x', boxX.x - crossLineTipPadding)
.attr('y', boxX.y - crossLineTipPadding)
.attr('width', boxX.width + 2 * crossLineTipPadding)
.attr('height', boxX.height + 2 * crossLineTipPadding);
flipAnElementHorizontally([dateText, boxXRect], boxX.width, distanceToRight, 0, boxX.x, crossLineTipPadding);
}
return datapoints;
};
this.updateTooltipItemsContent = function (sizeInfo, tooltipConfig, tipItems, tipBox, datapoints, mousePositionData) {
=======
this.updateTooltipItemsContent = function (sizeInfo, menuOption, tipItems, tipBox, datapoints, mousePositionData) {
>>>>>>>
this.updateHighlightRangeAndObtainDataPoints = function (graph, mouseOverHighlightBar, tipItems, series, sources, extraY, mousePositionData, timestampSelector, dateBisector, dateFormatter, isDataStacked, distanceToRight) {
var datapoints = [];
var bandOffset = graph.x0.bandwidth() + graph.x0.paddingInner()/2;
var xDomain = graph.x.domain();
var displayHighlightBar = false;
var xDiscreteDomain = graph.x0.domain();
var matchingTimestamp, i = d3.bisectLeft(xDiscreteDomain, mousePositionData.mouseX.getTime());
if (!xDiscreteDomain[i - 1]) {
// i === 0
matchingTimestamp = xDiscreteDomain[i];
} else if (!xDiscreteDomain[i]) {
// i === xDiscreteDomain.length
matchingTimestamp = xDiscreteDomain[i - 1];
} else {
matchingTimestamp = mousePositionData.positionX > graph.x0(xDiscreteDomain[i - 1]) + bandOffset ? xDiscreteDomain[i] : xDiscreteDomain[i - 1];
}
series.forEach(function (metric) {
var y = metric.extraYAxis ? extraY[metric.extraYAxis] : graph.y;
var displayingInLegend = ChartToolService.findMatchingMetricInSources(metric, sources).displaying;
if (metric.data.length === 0 || !displayingInLegend) {
// if the metric has no data or is toggled to hide
tipItems.selectAll('.' + metric.graphClassName).style('display', 'none');
} else {
var d = metric.data.find(function (d0) {
return timestampSelector(d0) === matchingTimestamp;
});
if (d === undefined) {
tipItems.selectAll('.' + metric.graphClassName).style('display', 'none');
} else {
var currentDatapoint = isDataStacked ? [d.data.timestamp, d.data[metric.name]] : d;
if (ChartToolService.isNotInTheDomain(currentDatapoint[0], xDomain) ||
ChartToolService.isNotInTheDomain(currentDatapoint[1], y.domain())) {
tipItems.selectAll('.' + metric.graphClassName).style('display', 'none');
} else {
tipItems.selectAll('.' + metric.graphClassName).style('display', null);
displayHighlightBar = true;
datapoints.push({
data: currentDatapoint,
graphClassName: metric.graphClassName,
name: metric.name
});
}
}
}
});
if (displayHighlightBar) {
var dateText = mouseOverHighlightBar.select('.crossLineTip');
var boxXRect = mouseOverHighlightBar.select('.crossLineTipRect');
var startingPosition = graph.x0(matchingTimestamp);
var date = dateFormatter(matchingTimestamp);
mouseOverHighlightBar.select('.highlightBar')
.attr('x', startingPosition)
.attr('dataX', matchingTimestamp)
.style('display', null);
dateText.attr('x', startingPosition).text(date);
var boxX = dateText.node().getBBox();
boxXRect.attr('x', boxX.x - crossLineTipPadding)
.attr('y', boxX.y - crossLineTipPadding)
.attr('width', boxX.width + 2 * crossLineTipPadding)
.attr('height', boxX.height + 2 * crossLineTipPadding);
flipAnElementHorizontally([dateText, boxXRect], boxX.width, distanceToRight, 0, boxX.x, crossLineTipPadding);
}
return datapoints;
};
this.updateTooltipItemsContent = function (sizeInfo, menuOption, tipItems, tipBox, datapoints, mousePositionData) {
<<<<<<<
=======
this.updateMouseRelatedElements = function (sizeInfo, menuOption, focus, tipItems, tipBox, series, sources, x, y, extraY, mousePositionData, isDataStacked) {
var datapoints;
var datapointsAndSnapPoint;
datapointsAndSnapPoint = this.updateFocusCirclesAndTooltipItems(focus, tipItems, series, sources, x, y, extraY, mousePositionData, isDataStacked);
datapoints = datapointsAndSnapPoint.datapoints;
// sort items in tooltip if needed
if (menuOption.tooltipConfig.isTooltipSortOn) {
datapoints = datapointsAndSnapPoint.datapoints.sort(function (a, b) {
return b.data[1] - a.data[1];
});
}
this.updateTooltipItemsContent(sizeInfo, menuOption, tipItems, tipBox, datapoints, mousePositionData);
return datapointsAndSnapPoint.snapPoint;
};
>>>>>>> |
<<<<<<<
var y;
if(metric.extraYAxis){
y = extraY_[metric.extraYAxis];
}else{
y = y_;
}
if (metric.data.length === 0 || !sources[index].displaying) {
=======
var displayingInLegend = ChartToolService.findMatchingMetricInSources(metric, sources).displaying;
if (metric.data.length === 0 || !displayingInLegend) {
>>>>>>>
var y;
if(metric.extraYAxis){
y = extraY_[metric.extraYAxis];
}else{
y = y_;
}
var displayingInLegend = ChartToolService.findMatchingMetricInSources(metric, sources).displaying;
if (metric.data.length === 0 || !displayingInLegend) {
<<<<<<<
this.redrawGraph = function (metric, source, chartType, graph, mainChart) {
// metric with no defined data or hidden
if (metric === null || metric.data === undefined || !source.displaying) return;
if (chartType === 'scatter') {
mainChart.selectAll('circle.dot.' + metric.graphClassName)
.attr('transform', function (d) {
return 'translate(' + graph.x(d[0]) + ',' + graph.y(d[1]) + ')';
})
.style('display', function (d) {
if (ChartToolService.isNotInTheDomain(d[0], graph.x.domain()) ||
ChartToolService.isNotInTheDomain(d[1], graph.y.domain())) {
return 'none';
} else {
return null;
}
});
} else {
mainChart.select('path.' + chartType + '.' + metric.graphClassName)
.datum(metric.data)
.attr('d', graph);
}
};
this.redrawGraphs = function (series, sources, chartType, graph, mainChart, extraGraph) {
var chartElementService = this;
series.forEach(function (metric, index) {
if(!metric.extraYAxis){
chartElementService.redrawGraph(metric, sources[index], chartType, graph, mainChart);
}else{
chartElementService.redrawGraph(metric, sources[index], chartType, extraGraph[metric.extraYAxis], mainChart)
=======
this.redrawGraphs = function (series, sources, chartType, graph, mainChart) {
series.forEach(function (metric) {
// metric with no defined data or hidden
var displayingInLegend = ChartToolService.findMatchingMetricInSources(metric, sources).displaying;
if (metric === null || metric.data === undefined || !displayingInLegend) return;
if (chartType === 'scatter') {
mainChart.selectAll('circle.dot.' + metric.graphClassName)
.attr('transform', function (d) {
return 'translate(' + graph.x(d[0]) + ',' + graph.y(d[1]) + ')';
})
.style('display', function (d) {
if (ChartToolService.isNotInTheDomain(d[0], graph.x.domain()) ||
ChartToolService.isNotInTheDomain(d[1], graph.y.domain())) {
return 'none';
} else {
return null;
}
});
} else {
mainChart.select('path.' + chartType + '.' + metric.graphClassName)
.datum(metric.data)
.attr('d', graph);
>>>>>>>
this.redrawGraph = function (metric, source, chartType, graph, mainChart) {
// metric with no defined data or hidden
var displayingInLegend = source.displaying;
if (metric === null || metric.data === undefined || !displayingInLegend) return;
if (chartType === 'scatter') {
mainChart.selectAll('circle.dot.' + metric.graphClassName)
.attr('transform', function (d) {
return 'translate(' + graph.x(d[0]) + ',' + graph.y(d[1]) + ')';
})
.style('display', function (d) {
if (ChartToolService.isNotInTheDomain(d[0], graph.x.domain()) ||
ChartToolService.isNotInTheDomain(d[1], graph.y.domain())) {
return 'none';
} else {
return null;
}
});
} else {
mainChart.select('path.' + chartType + '.' + metric.graphClassName)
.datum(metric.data)
.attr('d', graph);
}
};
this.redrawGraphs = function (series, sources, chartType, graph, mainChart, extraGraph) {
var chartElementService = this;
series.forEach(function (metric, index) {
var source = ChartToolService.findMatchingMetricInSources(metric, sources)
if(!metric.extraYAxis){
chartElementService.redrawGraph(metric, source, chartType, graph, mainChart);
}else{
chartElementService.redrawGraph(metric, source, chartType, extraGraph[metric.extraYAxis], mainChart)
<<<<<<<
var extraDatapoints = {};
for(var iSet of extraYAxisSet){
extraDatapoints[iSet] = [];
}
series.forEach(function (metric, index) {
// metric with no data or hidden
if (metric === null || metric.data === undefined || metric.data.length === 0 || !sources[index].displaying) return;
=======
series.forEach(function (metric) {
var displayingInLegend = ChartToolService.findMatchingMetricInSources(metric, sources).displaying;
if (metric === null || metric.data === undefined || metric.data.length === 0 || !displayingInLegend) return;
>>>>>>>
var extraDatapoints = {};
for(var iSet of extraYAxisSet){
extraDatapoints[iSet] = [];
}
series.forEach(function (metric, index) {
// metric with no data or hidden
var displayingInLegend = ChartToolService.findMatchingMetricInSources(metric, sources).displaying;
if (metric === null || metric.data === undefined || metric.data.length === 0 || !displayingInLegend) return; |
<<<<<<<
require("./services/tokenAuthInterceptor")
=======
require("./services/agTableService")
>>>>>>>
require("./services/tokenAuthInterceptor")
require("./services/agTableService") |
<<<<<<<
var defaultContainerHeight = containerHeight;
=======
>>>>>>>
var defaultContainerHeight = containerHeight;
<<<<<<<
// watch changes from chart options modal to update graph
scope.$watch('menuOption', function() {
if (!scope.hideMenu) {
// dont wat this if the menu is hidden/ there is no graph
updateDateRange();
toggleBrushMain();
toggleWheel();
toggleTooltip();
// mouseMove();
// downSample();
}
}, true);
=======
>>>>>>>
<<<<<<<
function calculateDimensions (newContainerWidth, newContainerHeight) {
var newWidth = newContainerWidth - marginLeft - marginRight;
var newHeight = parseInt((newContainerHeight - marginTop - marginBottom) * mainChartRatio);
var newHeight2 = parseInt((newContainerHeight - marginTop - marginBottom) * brushChartRatio);
var newMargin = {
top: marginTop,
right: marginRight,
bottom: newContainerHeight - marginTop - newHeight,
left: marginLeft
};
var newMargin2 = {
top: newContainerHeight - newHeight2 - marginBottom,
right: marginRight,
bottom: marginBottom,
left: marginLeft
};
return {
width: newWidth,
height: newHeight,
height2: newHeight2,
margin: newMargin,
margin2: newMargin2
};
}
=======
// watch changes from chart options modal to update graph
scope.$watch('menuOption', function() {
setColorScheme();
// setGraphTools(series);
legendCreator(names, colors, graphClassNames);
updateDateRange();
toggleBrushMain();
toggleWheel();
toggleTooltip();
scope.updateDownSample();
scope.toggleSyncChart();
// update any changes for the Y-axis tick formatting & number of ticks displayed
yAxis = d3.axisLeft()
.scale(y)
.ticks(scope.menuOption.numTicksYaxis)
.tickFormat(d3.format(scope.menuOption.formatYaxis))
;
yGrid = d3.axisLeft()
.scale(y)
.ticks(scope.menuOption.numTicksYaxis)
.tickSizeInner(-width)
;
yAxisG.call(yAxis);
yGridG.call(yGrid);
// mouseMove();
}, true);
>>>>>>>
// watch changes from chart options modal to update graph
scope.$watch('menuOption', function() {
if (!scope.hideMenu) {
setColorScheme();
// setGraphTools(series);
legendCreator(names, colors, graphClassNames);
updateDateRange();
toggleBrushMain();
toggleWheel();
toggleTooltip();
scope.updateDownSample();
scope.toggleSyncChart();
// update any changes for the Y-axis tick formatting & number of ticks displayed
yAxis = d3.axisLeft()
.scale(y)
.ticks(scope.menuOption.numTicksYaxis)
.tickFormat(d3.format(scope.menuOption.formatYaxis))
;
yGrid = d3.axisLeft()
.scale(y)
.ticks(scope.menuOption.numTicksYaxis)
.tickSizeInner(-width)
;
yAxisG.call(yAxis);
yGridG.call(yGrid);
// mouseMove();
}
}, true); |
<<<<<<<
this.buildViewElement = function(scope, element, attributes, dashboardCtrl, elementType, index, DashboardService, growl) {
=======
this.updateIndicatorStatus = updateIndicatorStatus;
this.buildViewElement = buildViewElement;
function populateChart(metricList, annotationExpressionList, optionList, divId, attributes, elementType, scope){
var objMetricCount = {};
objMetricCount.totalCount = metricList.length;
$('#' + divId).empty();
$('#' + divId).show();
// 'smallChart' currently viewed in the 'Services Dashboard'
var smallChart = attributes.smallchart ? true : false;
var chartType = attributes.type ? attributes.type : 'LINE';
var highChartOptions = getOptionsByChartType(CONFIG, chartType, smallChart);
setCustomOptions(highChartOptions, optionList);
$('#' + divId).highcharts('StockChart', highChartOptions);
var chart = $('#' + divId).highcharts('StockChart');
// show loading spinner & hide 'no data message' during api request
chart.showLoading();
chart.hideNoData();
// define series first; then build list for each metric expression
var series = [];
for (var i = 0; i < metricList.length; i++) {
var metricExpression = metricList[i].expression;
var metricOptions = metricList[i].metricSpecificOptions;
// make api call to get data for each metric item
populateSeries(metricList[i], highChartOptions, series, divId, attributes, annotationExpressionList, objMetricCount);
}
//populateAnnotations(annotationExpressionList, chart);
}
function updateIndicatorStatus(attributes, lastStatusVal) {
if (lastStatusVal < attributes.lo) {
$('#' + attributes.name + '-status').removeClass('red orange green').addClass('red');
} else if (lastStatusVal > attributes.lo && lastStatusVal < attributes.hi) {
$('#' + attributes.name + '-status').removeClass('red orange green').addClass('orange');
} else if (lastStatusVal > attributes.hi) {
$('#' + attributes.name + '-status').removeClass('red orange green').addClass('green');
}
}
function buildViewElement(scope, element, attributes, dashboardCtrl, elementType, index, DashboardService, growl) {
>>>>>>>
this.buildViewElement = function(scope, element, attributes, dashboardCtrl, elementType, index, DashboardService, growl) {
<<<<<<<
};
=======
var chart = $('#' + divId).highcharts('StockChart');
//chart.chart={renderTo: 'container',defaultSeriesType: 'line'};
//chart.renderTo='container';
//chart.defaultSeriesType='line';
populateAnnotations(annotationExpressionList, chart);
}
function resetChart(chart){
chart.zoomOut();
}
>>>>>>>
}
<<<<<<<
// 'chartOptions'
=======
function updateHeatmap(config, data, divId, optionList, attributes) {
if(data && data.length>0) {
var top = attributes.top? parseInt(attributes.top) : data.length;
var options = getOptionsByHeatmapType(config, top);
data.sort(compareAverage);
data = data.slice(0, Math.min(top, data.length));
var orgAxis = data.map(createSeriesName);
var timeSpan = getTimeSpan(data);
var timeAxis = getTimeAxis(timeSpan);
var dataSeries = copyHeatmapSeries(data, timeSpan);
options.series[0].data = dataSeries;
options.xAxis.categories = timeAxis;
options.yAxis.categories = orgAxis.reverse();
setCustomOptions(options,optionList);
$('#' + divId).highcharts(options);
}else {
$('#' + divId).highcharts('StockChart', getOptionsByChartType(config, 'LINE'));
}
}
>>>>>>>
<<<<<<<
=======
function getTimeAxis(timeSpan) {
var hours = [
'12AM', '1AM', '2AM', '3AM', '4AM', '5AM',
'6AM', '7AM', '8AM', '9AM', '10AM', '11AM',
'12PM', '1PM', '2PM', '3PM', '4PM', '5PM',
'6PM', '7PM', '8PM', '9PM', '10PM', '11PM'
];
var axis = [];
var firstHour = (new Date(timeSpan.begin)).getHours();
for (var i = 0; i < timeSpan.span; i++) {
axis.push(hours[(firstHour + i) % 24]);
}
axis.push('<b><i>Average</i></b>');
return axis;
}
>>>>>>>
<<<<<<<
=======
function copyHeatmapSeries(data, timeSpan) {
var table = data.map(getHourlyAverage.bind(null, timeSpan));
for (var i = 0; i < data.length; i++) {
table[i].push(getAverage(data[i]));
}
var dataSeries = [];
for (var i = 0; i < data.length; i++) {
for (var j = 0; j < table[0].length; j++) {
var intValue = table[data.length - 1 - i][j] ? Math.floor(table[data.length - 1 - i][j]) : null;
dataSeries.push([j, i, intValue]);
}
}
return dataSeries;
}
function copySeries(data) {
var result = [];
if (data) {
for (var i = 0; i < data.length; i++) {
var series = [];
for(var key in data[i].datapoints) {
var timestamp = parseInt(key);
if(data[i].datapoints[key] !=null){
var value = parseFloat(data[i].datapoints[key]);
series.push([timestamp, value]);
}
}
result.push({name: createSeriesName(data[i]), data: series});
}
} else {
result.push({name: 'result', data: []});
}
return result;
}
function copySeriesDataNSetOptions(data, metricItem) {
var result = [];
if (data) {
for (var i = 0; i < data.length; i++) {
var series = [];
for (var key in data[i].datapoints) {
var timestamp = parseInt(key);
if (data[i].datapoints[key] != null) {
var value = parseFloat(data[i].datapoints[key]);
series.push([timestamp, value]);
}
}
var metricName = (metricItem.name) ? metricItem.name : createSeriesName(data[i]);
var metricColor = (metricItem.color) ? metricItem.color : null;
var objSeries = {
name: metricName,
color: metricColor,
data: series
};
var objSeriesWithOptions = setCustomOptions(objSeries, metricItem.metricSpecificOptions);
result.push(objSeriesWithOptions);
}
} else {
result.push({name: 'result', data: []});
}
return result;
}
function createSeriesName(metric) {
var scope = metric.scope;
var name = metric.metric;
var tags = createTagString(metric.tags);
return scope + ':' + name + tags;
}
function createTagString(tags) {
var result = '';
if (tags) {
var tagString ='';
for (var key in tags) {
if (tags.hasOwnProperty(key)) {
tagString += (key + '=' + tags[key] + ',');
}
}
if(tagString.length) {
result += '{';
result += tagString.substring(0, tagString.length - 1);
result += '}';
}
}
return result;
}
function populateAnnotations(annotationsList, chart){
if (annotationsList && annotationsList.length>0 && chart) {
for (var i = 0; i < annotationsList.length; i++) {
addAlertFlag(annotationsList[i],chart);
}
}
}
function addAlertFlag(annotationExpression, chart) {
Annotations.query({expression: annotationExpression}, function (data) {
if(data && data.length>0) {
var forName = createSeriesName(data[0]);
var series = copyFlagSeries(data);
series.linkedTo = forName;
for(var i=0;i<chart.series.length;i++){
if(chart.series[i].name == forName){
series.color = chart.series[i].color;
break;
}
}
chart.addSeries(series);
}
});
}
function copyFlagSeries(data) {
var result;
if (data) {
result = {type: 'flags', shape: 'circlepin', stackDistance: 20, width: 16, lineWidth: 2};
result.data = [];
for (var i = 0; i < data.length; i++) {
var flagData = data[i];
result.data.push({x: flagData.timestamp, title: 'A', text: formatFlagText(flagData.fields)});
}
} else {
result = null;
}
return result;
}
function formatFlagText(fields) {
var result = '';
if (fields) {
for (var field in fields) {
if (fields.hasOwnProperty(field)) {
result += (field + ': ' + fields[field] + '<br/>');
}
}
}
return result;
}
function setCustomOptions(options, optionList){
for(var idx in optionList) {
var propertyName = optionList[idx].name;
var propertyValue = optionList[idx].value;
var result = constructObjectTree(propertyName, propertyValue);
copyProperties(result,options);
}
return options;
}
>>>>>>> |
<<<<<<<
var bufferRatio = 0.2; //the ratio of buffer above/below max/min on yAxis for better showing experience
var resizeTimeout = 250; //the time for resize function to fire
=======
var bufferRatio = 0.2 //the ratio of buffer above/below max/min on yAxis for better showing experience
>>>>>>>
var bufferRatio = 0.2; //the ratio of buffer above/below max/min on yAxis for better showing experience
<<<<<<<
if(!parent.resize){
parent.resizeJobs = [];
var timer;
parent.resize = function() {
$timeout.cancel(timer); //clear to improve performance
timer = $timeout(function () {
parent.resizeJobs.forEach(function (resize) { //resize all the charts
resize();
});
}, resizeTimeout); //only execute resize after a timeout
};
d3.select(window).on('resize', parent.resize);
}
parent.resizeJobs.push(resize);
=======
// if(!parent.resize){
// parent.resizeJobs = [];
// var timer;
// parent.resize = function() {
// $timeout.cancel(timer); //clear to improve performance
// timer = $timeout(function () {
// parent.resizeJobs.forEach(function (resize) { //resize all the charts
// resize();
// });
// }, resizeTimeout); //only execute resize after a timeout
// };
//
// d3.select(window).on('resize', parent.resize);
// }
// parent.resizeJobs.push(resize);
scope.$on('setupChart', function(){
resizeJobs = [];
});
resizeJobs.push(resize);
>>>>>>>
// if(!parent.resize){
// parent.resizeJobs = [];
// var timer;
// parent.resize = function() {
// $timeout.cancel(timer); //clear to improve performance
// timer = $timeout(function () {
// parent.resizeJobs.forEach(function (resize) { //resize all the charts
// resize();
// });
// }, resizeTimeout); //only execute resize after a timeout
// };
//
// d3.select(window).on('resize', parent.resize);
// }
// parent.resizeJobs.push(resize);
scope.$on('setupChart', function(){
resizeJobs = [];
});
resizeJobs.push(resize); |
<<<<<<<
var xScale = timeInfo.GMTon? d3.scaleUtc(): d3.scaleTime();
var y = this.getY(sizeInfo, yScaleType, yScaleConfigValue);
return {
x: xScale.domain([timeInfo.startTime, timeInfo.endTime]).range([0, sizeInfo.width]),
y: y.y,
yScalePlain: y.yScalePlain
};
};
this.getY = function (sizeInfo, yScaleType, yScaleConfigValue){
=======
var xScale = timeInfo.gmt? d3.scaleUtc(): d3.scaleTime();
>>>>>>>
var xScale = timeInfo.gmt? d3.scaleUtc(): d3.scaleTime();
var y = this.getY(sizeInfo, yScaleType, yScaleConfigValue);
return {
x: xScale.domain([timeInfo.startTime, timeInfo.endTime]).range([0, sizeInfo.width]),
y: y.y,
yScalePlain: y.yScalePlain
};
};
this.getY = function (sizeInfo, yScaleType, yScaleConfigValue){ |
<<<<<<<
},
alphabeticalSort: function(a, b) {
var textA = a.name.toUpperCase();
var textB = b.name.toUpperCase();
return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
},
objectWithoutProperties: function (obj, keys) {
var target = {};
for (var i in obj) {
if (keys.indexOf(i) >= 0) continue;
if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
target[i] = obj[i];
}
return target;
}
=======
},
removeDataResponseOverhead: function (rawData) {
var data = angular.copy(rawData);
delete data.$promise;
delete data.$resolved;
delete data.$cancelRequest;
return data;
}
>>>>>>>
},
alphabeticalSort: function(a, b) {
var textA = a.name.toUpperCase();
var textB = b.name.toUpperCase();
return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
},
objectWithoutProperties: function (obj, keys) {
var target = {};
for (var i in obj) {
if (keys.indexOf(i) >= 0) continue;
if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
target[i] = obj[i];
}
return target;
},
removeDataResponseOverhead: function (rawData) {
var data = angular.copy(rawData);
delete data.$promise;
delete data.$resolved;
delete data.$cancelRequest;
return data;
} |
<<<<<<<
var ms = require('humanize-ms');
var utility = require('utility');
=======
var ms = require('ms');
var thunkify = require('thunkify-wrap');
>>>>>>>
var ms = require('humanize-ms');
var thunkify = require('thunkify-wrap'); |
<<<<<<<
// give each series an unique ID
for (var i = 0; i < series.length; i++) {
lineChartScope.series[i].graphClassName = newChartId + "_graph" + i;
}
// append, compile, & attach new scope to line-chart directive
=======
>>>>>>>
// give each series an unique ID
for (var i = 0; i < series.length; i++) {
lineChartScope.series[i].graphClassName = newChartId + "_graph" + i;
}
// append, compile, & attach new scope to line-chart directive |
<<<<<<<
import { TransitionablePortal, Segment, Progress, Modal, Button, Icon } from 'semantic-ui-react';
=======
import { TransitionablePortal, Segment, Progress } from 'semantic-ui-react';
import uuidV4 from 'uuid/v4';
>>>>>>>
import { TransitionablePortal, Segment, Progress, Modal, Button, Icon } from 'semantic-ui-react';
import uuidV4 from 'uuid/v4';
<<<<<<<
setDefaultPaperAspectRatioInv, updateInOutPoint, removeMovieListItem, setDefaultDetectInOutPoint,
setEmailAddress
=======
setDefaultPaperAspectRatioInv, updateInOutPoint, removeMovieListItem, setDefaultDetectInOutPoint,
changeThumb, addThumb
>>>>>>>
setDefaultPaperAspectRatioInv, updateInOutPoint, removeMovieListItem, setDefaultDetectInOutPoint,
changeThumb, addThumb, setEmailAddress
<<<<<<<
const { app } = require('electron').remote;
=======
const opencv = require('opencv4nodejs');
>>>>>>>
const { app } = require('electron').remote;
const opencv = require('opencv4nodejs');
<<<<<<<
this.webviewRef = React.createRef();
=======
this.opencvVideoCanvasRef = React.createRef();
>>>>>>>
this.webviewRef = React.createRef();
this.opencvVideoCanvasRef = React.createRef();
<<<<<<<
progressBarPercentage: 100,
showFeedbackForm: false,
intendToCloseFeedbackForm: false,
=======
progressBarPercentage: 100,
timeBefore: undefined,
opencvVideo: undefined,
showScrubWindow: false,
scrubThumb: undefined,
scrubLimitLeft: 0,
scrubLimitRight: 10,
>>>>>>>
progressBarPercentage: 100,
showFeedbackForm: false,
intendToCloseFeedbackForm: false,
timeBefore: undefined,
opencvVideo: undefined,
showScrubWindow: false,
scrubThumb: undefined,
scrubLimitLeft: 0,
scrubLimitRight: 10, |
<<<<<<<
key={Math.random()}
index={index}
currentSlideIndex={this.getActiveSlideIndex()}
=======
key={index}
index={index}
>>>>>>>
key={Math.random()}
currentSlideIndex={this.getActiveSlideIndex()}
index={index} |
<<<<<<<
if (options.urls) {
// Handle for multiple file share
NativeModules.RNShare.open(options, (error) => {
return reject({error: error});
}, (success, activityType) => {
if (success) {
return resolve({
app: activityType
});
} else {
reject({error: "User did not share"});
}
});
} else {
// Handle for single file share
ActionSheetIOS.showShareActionSheetWithOptions(options, (error) => {
return reject({error: error});
}, (success, activityType) => {
if (success) {
return resolve({
app: activityType
});
} else {
reject({error: "User did not share"});
}
});
}
=======
ActionSheetIOS.showShareActionSheetWithOptions(options, (error) => {
return reject({ error: error });
}, (success, activityType) => {
if (success) {
return resolve({
app: activityType
});
} else if (options.failOnCancel === false) {
return resolve({
dismissedAction: true,
});
} else {
reject({ error: "User did not share" });
}
});
>>>>>>>
if (options.urls) {
// Handle for multiple file share
NativeModules.RNShare.open(options, (error) => {
return reject({error: error});
}, (success, activityType) => {
if (success) {
return resolve({
app: activityType
});
} else if (options.failOnCancel === false) {
return resolve({
dismissedAction: true,
});
} else {
reject({ error: "User did not share" });
}
});
} else {
// Handle for single file share
ActionSheetIOS.showShareActionSheetWithOptions(options, (error) => {
return reject({ error: error });
}, (success, activityType) => {
if (success) {
return resolve({
app: activityType
});
} else if (options.failOnCancel === false) {
return resolve({
dismissedAction: true,
});
} else {
reject({ error: "User did not share" });
}
});
} |
<<<<<<<
Crawler = require("../");
crawler = new Crawler("http://example.com");
discover = crawler.discoverResources.bind(crawler);
=======
crawler = new Crawler();
discover = function (resourceText, queueItem) {
queueItem = queueItem || {};
var resources = crawler.discoverResources(resourceText, queueItem);
return crawler.cleanExpandResources(resources, queueItem);
};
>>>>>>>
crawler = new Crawler("http://example.com");
discover = function (resourceText, queueItem) {
queueItem = queueItem || {};
var resources = crawler.discoverResources(resourceText, queueItem);
return crawler.cleanExpandResources(resources, queueItem);
}; |
<<<<<<<
if (error) {
=======
response.destroy();
>>>>>>>
if (error) {
<<<<<<<
response.socket.destroy();
/**
* Fired when the downloading of a resource was prevented
* by a download condition
* @event Crawler#downloadprevented
* @param {QueueItem} queueItem The queue item representing the resource that was halfway fetched
* @param {http.IncomingMessage} response The [http.IncomingMessage]{@link https://nodejs.org/api/http.html#http_class_http_incomingmessage} for the request's response
*/
crawler.emit("downloadprevented", queueItem, response);
=======
response.destroy();
>>>>>>>
response.destroy();
/**
* Fired when the downloading of a resource was prevented
* by a download condition
* @event Crawler#downloadprevented
* @param {QueueItem} queueItem The queue item representing the resource that was halfway fetched
* @param {http.IncomingMessage} response The [http.IncomingMessage]{@link https://nodejs.org/api/http.html#http_class_http_incomingmessage} for the request's response
*/
crawler.emit("downloadprevented", queueItem, response); |
<<<<<<<
/**
* Creates a new queue
* @class
*/
=======
/**
* Recursive function that takes two objects and updates the properties on the
* first object based on the ones in the second. Basically, it's a recursive
* version of Object.assign.
*/
function deepAssign(object, source) {
for (var key in source) {
if (source.hasOwnProperty(key)) {
if (typeof object[key] === "object" && typeof source[key] === "object") {
deepAssign(object[key], source[key]);
} else {
object[key] = source[key];
}
}
}
return object;
}
>>>>>>>
/**
* Recursive function that takes two objects and updates the properties on the
* first object based on the ones in the second. Basically, it's a recursive
* version of Object.assign.
*/
function deepAssign(object, source) {
for (var key in source) {
if (source.hasOwnProperty(key)) {
if (typeof object[key] === "object" && typeof source[key] === "object") {
deepAssign(object[key], source[key]);
} else {
object[key] = source[key];
}
}
}
return object;
}
/**
* Creates a new queue
* @class
*/
<<<<<<<
/**
* Called when {@link FetchQueue#oldestUnfetchedItem} returns a result
* @callback FetchQueue~oldestUnfetchedItemCallback
* @param {Error} [error] If the operation was successful, this will be `null`. Otherwise it will be the error that was encountered.
* @param {QueueItem} [queueItem] If there are unfetched queue items left, this will be the oldest one found. If not, this will be `null`.
*/
/**
* Gets the first unfetched item in the queue
* @param {FetchQueue~oldestUnfetchedItemCallback} callback
*/
=======
FetchQueue.prototype.update = function (url, updates, callback) {
var queue = this,
queueItem;
for (var i = 0; i < queue.length; i++) {
if (queue[i].url === url) {
queueItem = queue[i];
break;
}
}
if (!queueItem) {
callback(new Error("No queueItem found with that URL"));
} else {
deepAssign(queueItem, updates);
callback(null, queueItem);
}
};
// Get first unfetched item in the queue (and return its index)
>>>>>>>
FetchQueue.prototype.update = function (url, updates, callback) {
var queue = this,
queueItem;
for (var i = 0; i < queue.length; i++) {
if (queue[i].url === url) {
queueItem = queue[i];
break;
}
}
if (!queueItem) {
callback(new Error("No queueItem found with that URL"));
} else {
deepAssign(queueItem, updates);
callback(null, queueItem);
}
};
/**
* Called when {@link FetchQueue#oldestUnfetchedItem} returns a result
* @callback FetchQueue~oldestUnfetchedItemCallback
* @param {Error} [error] If the operation was successful, this will be `null`. Otherwise it will be the error that was encountered.
* @param {QueueItem} [queueItem] If there are unfetched queue items left, this will be the oldest one found. If not, this will be `null`.
*/
/**
* Gets the first unfetched item in the queue
* @param {FetchQueue~oldestUnfetchedItemCallback} callback
*/ |
<<<<<<<
=======
// Extract request options from queue;
var requestHost = queueItem.host,
requestPort = queueItem.port,
requestPath = queueItem.path;
// Are we passing through an HTTP proxy?
if (crawler.useProxy) {
requestHost = crawler.proxyHostname;
requestPort = crawler.proxyPort;
requestPath = queueItem.url;
}
// Load in request options
requestOptions = {
method: "GET",
host: requestHost,
port: requestPort,
path: requestPath,
agent: agent,
headers: {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate",
"User-Agent": crawler.userAgent,
"Host": queueItem.host + (queueItem.port !== 80 ? ":" + queueItem.port : "")
}
};
if (queueItem.referrer) {
requestOptions.headers.Referer = queueItem.referrer;
}
// If port is one of the HTTP/HTTPS defaults, delete the option to avoid conflicts
if (requestOptions.port === 80 || requestOptions.port === 443) {
delete requestOptions.port;
}
// Add cookie header from cookie jar if we're configured to
// send/accept cookies
if (crawler.acceptCookies && crawler.cookies.getAsHeader()) {
requestOptions.headers.cookie =
crawler.cookies.getAsHeader(queueItem.host, queueItem.path);
}
// Add auth headers if we need them
if (crawler.needsAuth) {
var auth = crawler.authUser + ":" + crawler.authPass;
// Generate auth header
auth = "Basic " + new Buffer(auth).toString("base64");
requestOptions.headers.Authorization = auth;
}
// Add proxy auth if we need it
if (crawler.proxyUser !== null && crawler.proxyPass !== null) {
var proxyAuth = crawler.proxyUser + ":" + crawler.proxyPass;
// Generate auth header
proxyAuth = "Basic " + new Buffer(proxyAuth).toString("base64");
requestOptions.headers["Proxy-Authorization"] = proxyAuth;
}
// And if we've got any custom headers available
if (crawler.customHeaders) {
for (var header in crawler.customHeaders) {
if (crawler.customHeaders.hasOwnProperty(header)) {
requestOptions.headers[header] = crawler.customHeaders[header];
}
}
}
>>>>>>> |
<<<<<<<
.option(['t', 'translateTime'], 'Display epoch timestamps as UTC ISO format or according to an optional format string (default ISO 8601)')
=======
.option(['n', 'localTime'], 'Display timestamps according to system timezone')
.option(['t', 'translateTime'], 'Convert Epoch timestamps to ISO format')
.option(['s', 'search'], 'specifiy a search pattern according to jmespath')
>>>>>>>
.option(['t', 'translateTime'], 'Display epoch timestamps as UTC ISO format or according to an optional format string (default ISO 8601)')
.option(['s', 'search'], 'specifiy a search pattern according to jmespath') |
<<<<<<<
patch: 0,
metadata: "development",
=======
patch: 1,
metadata: null,
>>>>>>>
patch: 1,
metadata: "development", |
<<<<<<<
const { name, size } = this.state.value || '';
const { image } = this.state || '';
const { customMetadata: CustomMetadata, customImageThumbnail: CustomImageThumbnail } = this.props;
const MetadataClass = CustomMetadata || FileInputMetadata;
const ImageThumbnailClass = CustomImageThumbnail || ImageThumbnail;
=======
const { label } = this.props;
const { value } = this.state;
>>>>>>>
// const { image } = this.state || '';
const { value, image } = this.state;
const { customMetadata: CustomMetadata, customImageThumbnail: CustomImageThumbnail, label } = this.props;
const MetadataClass = CustomMetadata || FileInputMetadata;
const ImageThumbnailClass = CustomImageThumbnail || ImageThumbnail;
<<<<<<<
const metadataComponent = (name && size) && <MetadataClass name={name} size={size}/>;
const imageThumbnailComponent = image && <ImageThumbnailClass image={image}/>;
=======
let renderMetadata = null;
if (value) {
const customMetadata = this.props.customMetadata({
extension: value.extension,
name: value.filename,
size: value.size,
type: value.mimeType,
});
renderMetadata = customMetadata
? customMetadata
: <FileInputMetadata
extension={value.extension}
name={value.filename}
size={value.size}
type={value.mimeType}
/>;
}
>>>>>>>
const metadataComponent = value && <MetadataClass name={value.filename} size={value.size} extension={value.extension} type={value.mimeType}/>;
const imageThumbnailComponent = image && <ImageThumbnailClass image={image}/>;
<<<<<<<
<button onClick={this.openFileDialog}>Select File</button>
<div className={!isDragging && 'brainhub-file-input__dropInfo--hidden' || ''}>
<p>Drop here to select file</p>
</div>
<div className="brainhub-file-input__fileInfo">
{this.props.displayImageThumbnail && imageThumbnailComponent}
{this.props.displayMetadata && metadataComponent}
</div>
=======
{this.props.displayMetadata && renderMetadata}
<DropArea
dragging={isDragging}
onDragEnter={this.onDragEnter}
onDragLeave={this.onDragLeave}
onDrop={this.onDrop}
openFileDialog={this.openFileDialog}
/>
>>>>>>>
<button onClick={this.openFileDialog}>Select File</button>
<div className={!isDragging && 'brainhub-file-input__dropInfo--hidden' || ''}>
<p>Drop here to select file</p>
</div>
<div className="brainhub-file-input__fileInfo">
{this.props.displayImageThumbnail && imageThumbnailComponent}
{this.props.displayMetadata && metadataComponent}
</div>
<DropArea
dragging={isDragging}
onDragEnter={this.onDragEnter}
onDragLeave={this.onDragLeave}
onDrop={this.onDrop}
openFileDialog={this.openFileDialog}
/> |
<<<<<<<
editorWillChangeBuffer: function(newBuffer) {
// Remove events from the old layoutManager.
var layoutManager = this.editor.layoutManager;
layoutManager.invalidatedRects.remove(this);
layoutManager.changedTextAtRow.remove(this);
// Add the events to the new layoutManager.
layoutManager = newBuffer.layoutManager;
layoutManager.invalidatedRects.add(this,
this.layoutManagerInvalidatedRects.bind(this));
layoutManager.changedTextAtRow.add(this,
this.layoutManagerChangedTextAtRow.bind(this));
},
set hasFocus(value) {
if (value == this._hasFocus) {
return;
}
this._hasFocus = value;
if (this._hasFocus) {
this._rearmInsertionPointBlinkTimer();
this._invalidateSelection();
this.textInput.focus();
} else {
if (this._insertionPointBlinkTimer) {
clearInterval(this._insertionPointBlinkTimer);
this._insertionPointBlinkTimer = null;
}
this._insertionPointVisible = true;
this._invalidateSelection();
this.textInput.blur();
}
},
get hasFocus() {
return this._hasFocus;
},
=======
>>>>>>>
editorWillChangeBuffer: function(newBuffer) {
// Remove events from the old layoutManager.
var layoutManager = this.editor.layoutManager;
layoutManager.invalidatedRects.remove(this);
layoutManager.changedTextAtRow.remove(this);
// Add the events to the new layoutManager.
layoutManager = newBuffer.layoutManager;
layoutManager.invalidatedRects.add(this,
this.layoutManagerInvalidatedRects.bind(this));
layoutManager.changedTextAtRow.add(this,
this.layoutManagerChangedTextAtRow.bind(this));
}, |
<<<<<<<
parent.innerHTML = '<div id="editor" class="center">Editor goes here</div><div class="south">Command line goes here</div>';
=======
parent.innerHTML = '<div class="center">Editor goes here</div>';
>>>>>>>
parent.innerHTML = '<div id="editor" class="center">Editor goes here</div>'; |
<<<<<<<
var needAspectCalc = anychart.utils.isPercent(this.getOption('zAspect'));
=======
>>>>>>>
<<<<<<<
if (needAspectCalc) {
var aspectRatio = parseFloat(zAspect) / 100;
=======
if (anychart.utils.isPercent(this.zAspectInternal)) {
var aspectRatio = parseFloat(this.zAspectInternal) / 100;
>>>>>>>
if (anychart.utils.isPercent(zAspect)) {
var aspectRatio = parseFloat(zAspect) / 100; |
<<<<<<<
// If any streams are empty, return an empty stream
if( streams.filter( function(x) { return x.empty(); } ).length > 0 ) {
return new Stream();
}
return new Stream(
f.apply( null, streams.map( function(x) { return x.head(); }) ),
function () {
var tail = self.tail();
return tail.zip.apply( tail, [f].concat(
args.map( function (x) { return x.tail(); } )
) );
}
);
=======
// If any streams are empty, return an empty stream
if( streams.filter( function(x) { return x.empty(); } ).length > 0 ) {
return new Stream();
}
return new Stream(
f.apply( null, streams.map( function(x) { return x.head(); }) ),
function () {
var tail = self.tail();
return tail.zip.apply( tail, [f].concat(
args.map( function (x) { return x.tail(); } )
) );
}
);
>>>>>>>
// If any streams are empty, return an empty stream
if( streams.filter( function(x) { return x.empty(); } ).length > 0 ) {
return new Stream();
}
return new Stream(
f.apply( null, streams.map( function(x) { return x.head(); }) ),
function () {
var tail = self.tail();
return tail.zip.apply( tail, [f].concat(
args.map( function (x) { return x.tail(); } )
) );
}
);
<<<<<<<
Stream.continually = function( callback ) {
return Stream.iterate( callback(), callback );
};
=======
function _continually( callback, wrapper ) {
return Stream.iterate( callback(), callback, wrapper );
}
Stream.continually = function( callback ) {
return _continually( callback, Lazy );
}
Stream.continuallyEager = function( callback ) {
return _continually( callback, Eager );
}
Stream.repeat = function( element ) {
return Stream.continually( function() { return element; } );
};
>>>>>>>
function _continually( callback, wrapper ) {
return Stream.iterate( callback(), callback, wrapper );
}
Stream.continually = function( callback ) {
return _continually( callback, Lazy );
}
Stream.continuallyEager = function( callback ) {
return _continually( callback, Eager );
}
Stream.repeat = function( element ) {
return Stream.continually( function() { return element; } );
};
<<<<<<<
Stream.repeat = function( element ) {
return Stream.continually( function() { return element; } );
};
=======
>>>>>>>
<<<<<<<
};
Stream.iterate = function ( x, f ) {
return new Stream( x, function () {
return Stream.iterate( f( x ), f);
} );
};
Stream.cycle = function( array ) {
var promise_generator = function( array, index) {
if( index >= array.length ) index = 0;
return function() {
return new Stream( array[index], promise_generator(array, index + 1 ) );
};
};
return new Stream( array[0], promise_generator( array, 1 ) );
};
module.exports = Stream;
},{}]},{},[1])(1)
});
=======
};
function _iterate( x, f, wrapper ) {
return new Stream( x, function () {
return _iterate( f( x ), f, wrapper );
}, wrapper );
};
Stream.iterate = function( x, f ) {
return _iterate( x, f, Lazy );
}
Stream.iterateEager = function( x, f ) {
return _iterate( x, f, Eager );
}
// Like fromArray, this is Eager-only since it would needlessly copy
// parts of the array if Lazy was used
Stream.cycle = function( array ) {
var promise_generator = function( array, index) {
if( index >= array.length ) index = 0;
return function() {
return new Stream( array[index], promise_generator(array, index + 1 ) );
};
};
return new Stream( array[0], promise_generator( array, 1 ) );
};
/*
* Since Lazy and Eager aren't exported to the outside, this is used to make
* eager streams.
*/
function EagerStream( head, tailPromise ) {
return Stream.call( this, head, tailPromise, Eager );
}
Stream.Eager = EagerStream;
>>>>>>>
};
function _iterate( x, f, wrapper ) {
return new Stream( x, function () {
return _iterate( f( x ), f, wrapper );
}, wrapper );
};
Stream.iterate = function( x, f ) {
return _iterate( x, f, Lazy );
}
Stream.iterateEager = function( x, f ) {
return _iterate( x, f, Eager );
}
// Like fromArray, this is Eager-only since it would needlessly copy
// parts of the array if Lazy was used
Stream.cycle = function( array ) {
var promise_generator = function( array, index) {
if( index >= array.length ) index = 0;
return function() {
return new Stream( array[index], promise_generator(array, index + 1 ) );
};
};
return new Stream( array[0], promise_generator( array, 1 ) );
};
/*
* Since Lazy and Eager aren't exported to the outside, this is used to make
* eager streams.
*/
function EagerStream( head, tailPromise ) {
return Stream.call( this, head, tailPromise, Eager );
}
Stream.Eager = EagerStream;
module.exports = Stream;
},{}]},{},[1])(1)
}); |
<<<<<<<
if(getWidth(wcwidth, lines[i]) > this.columns - c.x) {
if(c.x >= this.columns)
c.x = this.columns - 1;
splitWidth =
indexOfWidth(wcwidth, lines[i], this.columns - c.x);
=======
if(lines[i].length > this.columns - c.x) {
>>>>>>>
if(getWidth(wcwidth, lines[i]) > this.columns - c.x) {
<<<<<<<
if (wcwidth) {
lines[i] = lines[i].substr(0, splitWidth);
}
else {
lines[i] = lines[i].substr(0, splitWidth - 1) +
lines[i].substr(-1);
}
=======
if(c.x >= this.columns)
c.x = this.columns - 1;
lines[i] = lines[i].substr(0, this.columns - c.x - 1) +
lines[i].substr(-1);
>>>>>>>
lastChar = lines[i].substr(-1);
if(c.x >= this.columns)
c.x = this.columns - getWidth(wcwidth, lastChar);
lines[i] = substrWidth(wcwidth, lines[i], 0,
this.columns - c.x - getWidth(wcwidth, lastChar)) +
lastChar; |
<<<<<<<
if (!session.getData('currentScene')) {
session.setData('currentScene', null)
=======
if (!session.data.currentScene) {
session.update({ currentScene: null })
>>>>>>>
if (!session.getData('currentScene')) {
session.setData('currentScene', null)
<<<<<<<
if (matchedScene) {
if (matchedScene.isLeaveCommand(requestedCommandName)) {
matchedScene.handleRequest(req, sendResponse)
session.setData('currentScene', null)
=======
if (session.currentScene.isLeaveCommand(requestedCommandName)) {
session.currentScene.handleRequest(req, sendResponse, session)
session.currentScene = null
return true
} else {
const sceneResponse = await session.currentScene.handleRequest(
req, sendResponse, session
)
if (sceneResponse) {
>>>>>>>
if (matchedScene) {
if (matchedScene.isLeaveCommand(requestedCommandName)) {
matchedScene.handleRequest(req, sendResponse, session)
session.setData('currentScene', null)
<<<<<<<
session.setData('currentScene', matchedScene.name)
const sceneResponse = await matchedScene.handleRequest(
req, sendResponse
=======
session.currentScene = matchedScene
const sceneResponse = await session.currentScene.handleRequest(
req, sendResponse, session
>>>>>>>
session.setData('currentScene', matchedScene.name)
const sceneResponse = await matchedScene.handleRequest(
req, sendResponse, session |
<<<<<<<
this.fuseOptions = config || {
tokenize: true,
threshold: 0.1,
distance: 10,
=======
this.fuseOptions = {
tokenize: false,
threshold: config.fuzzyTreshold || 0.3,
distance: config.fuzzyDistance || 10,
>>>>>>>
this.fuseOptions = config || {
tokenize: false,
threshold: 0.1,
distance: 10, |
<<<<<<<
=======
$(".vis-live-toggle", $nc).click(function () {
$(this).toggleClass("running", !reload_queues.running);
reload_queues.toggle(!reload_queues.running);
}).click();
let physics_running = true;
$(".vis-physics-toggle", $nc).click(function () {
$(this).toggleClass("running");
app.network.setOptions({physics: (physics_running = !physics_running)});
});
>>>>>>>
$(".vis-live-toggle", $nc).click(function () {
$(this).toggleClass("running", !reload_queues.running);
reload_queues.toggle(!reload_queues.running);
}).click();
let physics_running = true;
$(".vis-physics-toggle", $nc).click(function () {
$(this).toggleClass("running");
app.network.setOptions({physics: (physics_running = !physics_running)});
}); |
<<<<<<<
actionCableConsumer.subscriptions.create(
{ channel, ...actionCableParams },
{
received: data => {
if (!data.cableReady) return
if (data.operations.morph && data.operations.morph.length) {
const urls = Array.from(
new Set(data.operations.morph.map(m => m.stimulusReflex.url))
)
if (urls.length !== 1 || urls[0] !== location.href) return
}
CableReady.perform(data.operations)
},
connected: () => {
actionCableSubscriptionActive = true
document.body.dispatchEvent(
new CustomEvent(`stimulus-reflex:connected`, {
bubbles: true,
cancelable: false
})
)
},
rejected: () => {
actionCableSubscriptionActive = false
document.body.dispatchEvent(
new CustomEvent(`stimulus-reflex:rejected`, {
bubbles: true,
cancelable: false
})
)
if (debugging) console.warn('Channel subscription was rejected.')
},
disconnected: willAttemptReconnect => {
actionCableSubscriptionActive = false
document.body.dispatchEvent(
new CustomEvent(`stimulus-reflex:disconnected`, {
bubbles: true,
cancelable: false,
detail: { willAttemptReconnect }
})
)
=======
actionCableConsumer.subscriptions.create(channel, {
received: data => {
if (!data.cableReady) return
if (data.operations.morph && data.operations.morph.length) {
if (data.operations.morph[0].stimulusReflex) {
const urls = Array.from(
new Set(data.operations.morph.map(m => m.stimulusReflex.url))
)
if (urls.length !== 1 || urls[0] !== location.href) return
}
>>>>>>>
actionCableConsumer.subscriptions.create(
{ channel, ...actionCableParams },
{
received: data => {
if (!data.cableReady) return
if (data.operations.morph && data.operations.morph.length) {
if (data.operations.morph[0].stimulusReflex) {
const urls = Array.from(
new Set(data.operations.morph.map(m => m.stimulusReflex.url))
)
if (urls.length !== 1 || urls[0] !== location.href) return
}
CableReady.perform(data.operations)
}
},
connected: () => {
actionCableSubscriptionActive = true
document.body.dispatchEvent(
new CustomEvent(`stimulus-reflex:connected`, {
bubbles: true,
cancelable: false
})
)
},
rejected: () => {
actionCableSubscriptionActive = false
document.body.dispatchEvent(
new CustomEvent(`stimulus-reflex:rejected`, {
bubbles: true,
cancelable: false
})
)
if (debugging) console.warn('Channel subscription was rejected.')
},
disconnected: willAttemptReconnect => {
actionCableSubscriptionActive = false
document.body.dispatchEvent(
new CustomEvent(`stimulus-reflex:disconnected`, {
bubbles: true,
cancelable: false,
detail: { willAttemptReconnect }
})
) |
<<<<<<<
import {emitter} from './channel'
=======
import { asap } from './scheduler'
import { emitter } from './channel'
import { ident } from './utils'
>>>>>>>
import { emitter } from './channel'
import { ident } from './utils' |
<<<<<<<
=======
function emitter() {
var subscribers = [];
function subscribe(sub) {
subscribers.push(sub);
return function () {
return remove(subscribers, sub);
};
}
function emit(item) {
var arr = subscribers.slice();
for (var i = 0, len = arr.length; i < len; i++) {
arr[i](item);
}
}
return {
subscribe: subscribe,
emit: emit
};
}
>>>>>>>
<<<<<<<
=======
var stdChannel$$1 = stdChannel(subscribe);
>>>>>>>
<<<<<<<
};
=======
}; // TODO: add support for the fetch API, whenever they get around to
// adding cancel support
>>>>>>>
};
<<<<<<<
// TODO: should such error here be passed to `onError`?
// or is it already if we dropped error swallowing
cb(error, true);
return;
=======
cb(error, true);
return;
>>>>>>>
}
mainTask.isMainRunning = false;
mainTask.cont(error, true);
}
}
function end(result, isErr) {
iterator._isRunning = false; // stdChannel.close()
if (!isErr) {
iterator._result = result;
iterator._deferredEnd && iterator._deferredEnd.resolve(result);
} else {
if (result instanceof Error) {
Object.defineProperty(result, 'sagaStack', {
value: "at " + name + " \n " + (result.sagaStack || result.stack),
configurable: true
});
}
if (!task.cont) {
if (result instanceof Error && onError) {
onError(result);
} else {
// TODO: could we skip this when _deferredEnd is attached?
logError(result);
}
}
iterator._error = result;
iterator._isAborted = true;
iterator._deferredEnd && iterator._deferredEnd.reject(result);
}
task.cont && task.cont(result, isErr);
task.joiners.forEach(function (j) {
return j.cb(result, isErr);
});
task.joiners = null;
}
function runEffect(effect, effectId, label, currCb) {
if (label === void 0) {
label = '';
}
/**
each effect runner must attach its own logic of cancellation to the provided callback
it allows this generator to propagate cancellation downward.
ATTENTION! effect runners must setup the cancel logic by setting cb.cancel = [cancelMethod]
And the setup must occur before calling the callback
This is a sort of inversion of control: called async functions are responsible
of completing the flow by calling the provided continuation; while caller functions
are responsible for aborting the current flow by calling the attached cancel function
Library users can attach their own cancellation logic to promises by defining a
promise[CANCEL] method in their returned promises
ATTENTION! calling cancel must have no effect on an already completed or cancelled effect
**/
var data; // prettier-ignore
return (// Non declarative effect
is.promise(effect) ? resolvePromise(effect, currCb) : is.iterator(effect) ? resolveIterator(effect, effectId, name, currCb) // declarative effects
: (data = asEffect.take(effect)) ? runTakeEffect(data, currCb) : (data = asEffect.put(effect)) ? runPutEffect(data, currCb) : (data = asEffect.all(effect)) ? runAllEffect(data, effectId, currCb) : (data = asEffect.race(effect)) ? runRaceEffect(data, effectId, currCb) : (data = asEffect.call(effect)) ? runCallEffect(data, effectId, currCb) : (data = asEffect.cps(effect)) ? runCPSEffect(data, currCb) : (data = asEffect.fork(effect)) ? runForkEffect(data, effectId, currCb) : (data = asEffect.join(effect)) ? runJoinEffect(data, currCb) : (data = asEffect.cancel(effect)) ? runCancelEffect(data, currCb) : (data = asEffect.select(effect)) ? runSelectEffect(data, currCb) : (data = asEffect.actionChannel(effect)) ? runChannelEffect(data, currCb) : (data = asEffect.flush(effect)) ? runFlushEffect(data, currCb) : (data = asEffect.cancelled(effect)) ? runCancelledEffect(data, currCb) : (data = asEffect.getContext(effect)) ? runGetContextEffect(data, currCb) : (data = asEffect.setContext(effect)) ? runSetContextEffect(data, currCb) :
/* anything else returned as is */
currCb(effect)
);
}
function digestEffect(effect, parentEffectId, label, cb) {
if (label === void 0) {
label = '';
}
var effectId = uid();
sagaMonitor && sagaMonitor.effectTriggered({
effectId: effectId,
parentEffectId: parentEffectId,
label: label,
effect: effect
});
/**
completion callback and cancel callback are mutually exclusive
We can't cancel an already completed effect
And We can't complete an already cancelled effectId
**/
var effectSettled; // Completion callback passed to the appropriate effect runner
function currCb(res, isErr) {
if (effectSettled) {
return;
}
effectSettled = true;
cb.cancel = noop; // defensive measure
if (sagaMonitor) {
isErr ? sagaMonitor.effectRejected(effectId, res) : sagaMonitor.effectResolved(effectId, res);
}
cb(res, isErr);
} // tracks down the current cancel
currCb.cancel = noop; // setup cancellation logic on the parent cb
cb.cancel = function () {
// prevents cancelling an already completed effect
if (effectSettled) {
return;
}
effectSettled = true;
/**
propagates cancel downward
catch uncaught cancellations errors; since we can no longer call the completion
callback, log errors raised during cancellations into the console
**/
try {
currCb.cancel();
} catch (err) {
logError(err);
}
currCb.cancel = noop; // defensive measure
sagaMonitor && sagaMonitor.effectCancelled(effectId);
}; // if one can find a way to decouple runEffect from closure variables
// so it could be the call to it could be referentially transparent
// this potentially could be simplified, finalRunEffect created beforehand
// and this part of the code wouldnt have to know about middleware stuff
if (is.func(middleware)) {
middleware(function (eff) {
return runEffect(eff, effectId, label, currCb);
})(effect);
return;
}
runEffect(effect, effectId, label, currCb);
}
function resolvePromise(promise, cb) {
var cancelPromise = promise[CANCEL];
if (is.func(cancelPromise)) {
cb.cancel = cancelPromise;
} else if (is.func(promise.abort)) {
cb.cancel = function () {
return promise.abort();
};
}
promise.then(cb, function (error) {
return cb(error, true);
});
}
function resolveIterator(iterator, effectId, name, cb) {
proc(iterator, stdChannel$$1, dispatch, getState, taskContext, options, effectId, name, cb);
}
function runTakeEffect(_ref2, cb) {
var _ref2$channel = _ref2.channel,
channel$$1 = _ref2$channel === void 0 ? stdChannel$$1 : _ref2$channel,
pattern = _ref2.pattern,
maybe = _ref2.maybe;
var takeCb = function takeCb(input) {
if (input instanceof Error) {
cb(input, true);
return;
}
if (isEnd(input) && !maybe) {
cb(CHANNEL_END$1);
return;
}
cb(input);
};
try {
channel$$1.take(takeCb, is.notUndef(pattern) ? matcher(pattern) : null);
} catch (err) {
cb(err, true);
return;
}
cb.cancel = takeCb.cancel;
}
function runPutEffect(_ref3, cb) {
var channel$$1 = _ref3.channel,
action = _ref3.action,
resolve = _ref3.resolve;
/**
Schedule the put in case another saga is holding a lock.
The put will be executed atomically. ie nested puts will execute after
this put has terminated.
**/
asap(function () {
var result;
try {
result = (channel$$1 ? channel$$1.put : dispatch)(action);
} catch (error) {
logError(error); // TODO: should such error here be passed to `onError`?
// or is it already if we dropped error swallowing
cb(error, true);
return;
<<<<<<<
var _task = proc(taskIterator, stdChannel$$1, dispatch, getState, taskContext, options, effectId, fn.name, detached ? null : noop);
=======
var _task = proc(taskIterator, subscribe, dispatch, getState, taskContext, options, effectId, fn.name, detached ? null : noop);
>>>>>>>
var _task = proc(taskIterator, stdChannel$$1, dispatch, getState, taskContext, options, effectId, fn.name, detached ? null : noop);
<<<<<<<
buffer = _ref8.buffer;
// TODO: something weird is going here
// rething this code + rething how END is handled
var chan = channel(buffer);
=======
_ref8$buffer = _ref8.buffer,
buffer = _ref8$buffer === void 0 ? buffers.expanding() : _ref8$buffer;
>>>>>>>
buffer = _ref8.buffer;
// TODO: rethink how END is handled
var chan = channel(buffer);
<<<<<<<
var chan = channel$$1 ? channel$$1 : function () {
{
// TODO: write better deprecation warning
log('warn', 'runSaga({ subscribe }, ...) has been deprecated in favor of runSaga({ channel })');
}
var chan = stdChannel();
var unsubscribe = subscribe(chan.put);
return _extends({}, chan, {
close: function close() {
if (is.func(unsubscribe)) {
unsubscribe();
}
chan.close();
}
});
}();
var task = proc(iterator, chan, wrapSagaDispatch(dispatch), getState, context, { sagaMonitor: sagaMonitor, logger: logger, onError: onError }, effectId, saga.name);
=======
var task = proc(iterator, subscribe, wrapSagaDispatch(dispatch), getState, context, {
sagaMonitor: sagaMonitor,
logger: logger,
onError: onError
}, effectId, saga.name);
>>>>>>>
if (("development" === 'development' || "development" === 'test') && is.notUndef(effectMiddlewares)) {
var MIDDLEWARE_TYPE_ERROR = 'effectMiddlewares must be an array of functions';
check(effectMiddlewares, is.array, MIDDLEWARE_TYPE_ERROR);
effectMiddlewares.forEach(function (effectMiddleware) {
return check(effectMiddleware, is.func, MIDDLEWARE_TYPE_ERROR);
});
}
var middleware = effectMiddlewares && compose.apply(void 0, effectMiddlewares);
var task = proc(iterator, channel$$1, wrapSagaDispatch(dispatch), getState, context, {
sagaMonitor: sagaMonitor,
logger: logger,
onError: onError,
middleware: middleware
}, effectId, saga.name);
<<<<<<<
channel$$1.put(action);
=======
sagaEmitter.emit(action);
>>>>>>>
channel$$1.put(action); |
<<<<<<<
import { noop, is, check, uid as nextSagaId, wrapSagaDispatch, isDev, log, object, createSetContextWarning } from './utils'
import proc from './proc'
=======
import { is, isDev, log } from './utils'
>>>>>>>
import { noop, is, check, uid as nextSagaId, wrapSagaDispatch, isDev, log, object, createSetContextWarning } from './utils'
<<<<<<<
export default function sagaMiddlewareFactory({ context = {}, ...options } = {}) {
let runSagaDynamically
const {sagaMonitor} = options
// monitors are expected to have a certain interface, let's fill-in any missing ones
if(sagaMonitor) {
sagaMonitor.effectTriggered = sagaMonitor.effectTriggered || noop
sagaMonitor.effectResolved = sagaMonitor.effectResolved || noop
sagaMonitor.effectRejected = sagaMonitor.effectRejected || noop
sagaMonitor.effectCancelled = sagaMonitor.effectCancelled || noop
sagaMonitor.actionDispatched = sagaMonitor.actionDispatched || noop
}
=======
export default function sagaMiddlewareFactory(options = {}) {
const {sagaMonitor, logger, onError} = options
>>>>>>>
export default function sagaMiddlewareFactory({ context = {}, ...options } = {}) {
const {sagaMonitor, logger, onError} = options
<<<<<<<
function runSaga(saga, args, sagaId) {
return proc(
saga(...args),
sagaEmitter.subscribe,
sagaDispatch,
getState,
context,
options,
sagaId,
saga.name
)
}
=======
sagaMiddleware.run = runSaga.bind(null, {
subscribe: sagaEmitter.subscribe,
dispatch,
getState,
sagaMonitor,
logger,
onError
})
>>>>>>>
sagaMiddleware.run = runSaga.bind(null, {
subscribe: sagaEmitter.subscribe,
dispatch,
getState,
sagaMonitor,
logger,
onError
}) |
<<<<<<<
return '#### ' + (pass ? (kitten + votePassComment) : voteFailComment) + '\n\n' +
=======
var resp = '#### ' + (pass ? votePassComment : voteFailComment) + '\n\n' +
>>>>>>>
var resp = '#### ' + (pass ? (kitten + votePassComment) : voteFailComment) + '\n\n' + |
<<<<<<<
if(nick.indexOf("~") >= 0) {
var fname = nick.split("~")[0];
socket.send("/nick " + fname + "~" + conn_id);
} else {
socket.send("/nick " + HTMLEncode(nick) + "~" + conn_id);
}
=======
socket.send("/nick " + HTMLEncode(nick) + "_" + conn_id);
>>>>>>>
if(nick.indexOf("~") >= 0) {
var fname = nick.split("~")[0];
socket.send("/nick " + fname + "~" + conn_id);
} else {
socket.send("/nick " + HTMLEncode(nick) + "~" + conn_id);
}
<<<<<<<
var fname = message.name.split("~")[0];
=======
updateTitle("[PM] ");
var fname = message.name.split("_")[0];
>>>>>>>
updateTitle("[PM] ");
var fname = message.name.split("~")[0];
<<<<<<<
var fname = message.from.split("~")[0];
=======
var fname = message.from.split("_")[0];
>>>>>>>
var fname = message.from.split("~")[0]; |
<<<<<<<
set isVisible(isVisible) {
if (this._isVisible === isVisible) {
return;
}
this._isVisible = isVisible;
this.domNode.style.display = isVisible ? 'block' : 'none';
if (isVisible) {
this.invalidate();
}
},
=======
>>>>>>>
set isVisible(isVisible) {
if (this._isVisible === isVisible) {
return;
}
this._isVisible = isVisible;
this.domNode.style.display = isVisible ? 'block' : 'none';
if (isVisible) {
this.invalidate();
}
},
<<<<<<<
set maximum(maximum) {
if (this._value > this._maximum) {
this.value = this._maximum;
}
if (maximum === this._maximum) {
return;
}
this._maximum = maximum;
this.invalidate();
},
=======
>>>>>>>
set maximum(maximum) {
if (this._value > this._maximum) {
this.value = this._maximum;
}
if (maximum === this._maximum) {
return;
}
this._maximum = maximum;
this.invalidate();
},
<<<<<<<
set value(value) {
if (value < 0) {
value = 0;
} else if (value > this._maximum) {
value = this._maximum;
}
if (value === this._value) {
return;
}
this._value = value;
this.valueChanged(value);
this.invalidate();
},
=======
>>>>>>>
set value(value) {
if (value < 0) {
value = 0;
} else if (value > this._maximum) {
value = this._maximum;
}
if (value === this._value) {
return;
}
this._value = value;
this.valueChanged(value);
this.invalidate();
},
<<<<<<<
// mouseWheel: function(evt) {
// var parentView = this.get('parentView');
//
// var delta;
// switch (parentView.get('layoutDirection')) {
// case LAYOUT_HORIZONTAL:
// delta = evt.wheelDeltaX;
// break;
// case LAYOUT_VERTICAL:
// delta = evt.wheelDeltaY;
// break;
// default:
// console.error("unknown layout direction");
// return;
// }
//
// parentView.set('value', parentView.get('value') + 2*delta);
// }
=======
});
Object.defineProperties(exports.ScrollerCanvasView.prototype, {
isVisible: {
set: function(isVisible) {
if (this._isVisible === isVisible) {
return;
}
this._isVisible = isVisible;
this.domNode.style.display = isVisible ? 'block' : 'none';
if (isVisible) {
this.setNeedsDisplay();
}
}
},
maximum: {
set: function(maximum) {
if (this._value > this._maximum) {
this._value = this._maximum;
}
if (maximum === this._maximum) {
return;
}
this._maximum = maximum;
this.setNeedsDisplay();
}
},
value: {
set: function(value) {
if (value < 0) {
value = 0;
} else if (value > this._maximum) {
value = this._maximum;
}
if (value === this._value) {
return;
}
this._value = value;
this.setNeedsDisplay();
}
}
>>>>>>>
// mouseWheel: function(evt) {
// var parentView = this.get('parentView');
//
// var delta;
// switch (parentView.get('layoutDirection')) {
// case LAYOUT_HORIZONTAL:
// delta = evt.wheelDeltaX;
// break;
// case LAYOUT_VERTICAL:
// delta = evt.wheelDeltaY;
// break;
// default:
// console.error("unknown layout direction");
// return;
// }
//
// parentView.set('value', parentView.get('value') + 2*delta);
// }
});
Object.defineProperties(exports.ScrollerCanvasView.prototype, {
isVisible: {
set: function(isVisible) {
if (this._isVisible === isVisible) {
return;
}
this._isVisible = isVisible;
this.domNode.style.display = isVisible ? 'block' : 'none';
if (isVisible) {
this.invalidate();
}
}
},
maximum: {
set: function(maximum) {
if (this._value > this._maximum) {
this._value = this._maximum;
}
if (maximum === this._maximum) {
return;
}
this._maximum = maximum;
this.invalidate();
}
},
value: {
set: function(value) {
if (value < 0) {
value = 0;
} else if (value > this._maximum) {
value = this._maximum;
}
if (value === this._value) {
return;
}
this._value = value;
this.invalidate();
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.