<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

const appConstants = require('../constants/appConstants')
const AppDispatcher = require('../dispatcher/appDispatcher')
const AppStore = require('./appStore')
const EventEmitter = require('events').EventEmitter
const Immutable = require('immutable')
const windowConstants = require('../constants/windowConstants')
const debounce = require('../lib/debounce')
const {getWebContents} = require('../../app/browser/webContentsCache')
const {isSourceAboutUrl} = require('../lib/appUrlUtil')
const {responseHasContent} = require('../../app/common/lib/httpUtil')

const electron = require('electron')
const BrowserWindow = electron.BrowserWindow

let eventState = Immutable.fromJS({
  page_load: [],
  page_view: [],
  page_info: []
})

const CHANGE_EVENT = 'change'

class EventStore extends EventEmitter {
  getState () {
    return eventState
  }

  emitChanges () {
    this.emit(CHANGE_EVENT)
  }

  addChangeListener (callback) {
    this.on(CHANGE_EVENT, callback)
  }

  removeChangeListener (callback) {
    this.removeListener(CHANGE_EVENT, callback)
  }
}

const eventStore = new EventStore()
const emitChanges = debounce(eventStore.emitChanges.bind(eventStore), 5)

let lastActivePageUrl = null
let lastActiveTabId = null

const addPageView = (url, tabId) => {
  const tab = getWebContents(tabId)
  const isPrivate = !tab ||
    tab.isDestroyed() ||
    !tab.session.partition.startsWith('persist:')

  if ((url && isSourceAboutUrl(url)) || isPrivate) {
    url = null
  }

  if (lastActivePageUrl === url) {
    return
  }

  let pageViewEvent = Immutable.fromJS({
    timestamp: new Date().getTime(),
    url,
    tabId
  })
  eventState = eventState.set('page_view', eventState.get('page_view').slice(-100).push(pageViewEvent))
  lastActivePageUrl = url
}

const windowBlurred = (windowId) => {
  let windowCount = BrowserWindow.getAllWindows().filter((win) => win.isFocused()).length
  if (windowCount === 0) {
    addPageView(null, null)
  }
}

const windowClosed = (windowId) => {
  let windowCount = BrowserWindow.getAllWindows().length
  let win = BrowserWindow.getFocusedWindow()
  // window may not be closed yet
  if (windowCount > 0 && win && win.id === windowId) {
    win.once('closed', () => {
      windowClosed(windowId)
    })
  }

  if (!win || windowCount === 0) {
    addPageView(null, null)
  }
}

// Register callback to handle all updates
const doAction = (action) => {
  switch (action.actionType) {
    case windowConstants.WINDOW_SET_FOCUSED_FRAME:
      if (action.location) {
        addPageView(action.location, action.tabId)
      }
      break
    case appConstants.APP_WINDOW_BLURRED:
      windowBlurred(action.windowId)
      break
    case appConstants.APP_IDLE_STATE_CHANGED:
      if (action.idleState !== 'active') {
        addPageView(null, null)
      } else {
        addPageView(lastActivePageUrl, lastActiveTabId)
      }
      break
    case appConstants.APP_CLOSE_WINDOW:
      AppDispatcher.waitFor([AppStore.dispatchToken], () => {
        windowClosed(action.windowId)
      })
      break
    case 'event-set-page-info':
      // retains all past pages, not really sure that's needed... [MTR]
      eventState = eventState.set('page_info', eventState.get('page_info').slice(-100).push(action.pageInfo))
      break
    case windowConstants.WINDOW_GOT_RESPONSE_DETAILS:
      // Only capture response for the page (not subresources, like images, JavaScript, etc)
      if (action.details && action.details.resourceType === 'mainFrame') {
        const pageUrl = action.details.newURL

        // create a page view event if this is a page load on the active tabId
        if (!lastActiveTabId || action.tabId === lastActiveTabId) {
          addPageView(pageUrl, action.tabId)
        }

        const responseCode = action.details.httpResponseCode
        if (isSourceAboutUrl(pageUrl) || !responseHasContent(responseCode)) {
          break
        }

        const pageLoadEvent = Immutable.fromJS({
          timestamp: new Date().getTime(),
          url: pageUrl,
          tabId: action.tabId,
          details: action.details
        })
        eventState = eventState.set('page_load', eventState.get('page_load').slice(-100).push(pageLoadEvent))
      }
      break
    default:
  }

  emitChanges()
}

AppDispatcher.register(doAction)

module.exports = eventStore
<commit_msg>Emit changes for EventStore only when action is actually calleed<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

const appConstants = require('../constants/appConstants')
const AppDispatcher = require('../dispatcher/appDispatcher')
const AppStore = require('./appStore')
const EventEmitter = require('events').EventEmitter
const Immutable = require('immutable')
const windowConstants = require('../constants/windowConstants')
const debounce = require('../lib/debounce')
const {getWebContents} = require('../../app/browser/webContentsCache')
const {isSourceAboutUrl} = require('../lib/appUrlUtil')
const {responseHasContent} = require('../../app/common/lib/httpUtil')

const electron = require('electron')
const BrowserWindow = electron.BrowserWindow

let eventState = Immutable.fromJS({
  page_load: [],
  page_view: [],
  page_info: []
})

const CHANGE_EVENT = 'change'

class EventStore extends EventEmitter {
  getState () {
    return eventState
  }

  emitChanges () {
    this.emit(CHANGE_EVENT)
  }

  addChangeListener (callback) {
    this.on(CHANGE_EVENT, callback)
  }

  removeChangeListener (callback) {
    this.removeListener(CHANGE_EVENT, callback)
  }
}

const eventStore = new EventStore()
const emitChanges = debounce(eventStore.emitChanges.bind(eventStore), 5)

let lastActivePageUrl = null
let lastActiveTabId = null

const addPageView = (url, tabId) => {
  const tab = getWebContents(tabId)
  const isPrivate = !tab ||
    tab.isDestroyed() ||
    !tab.session.partition.startsWith('persist:')

  if ((url && isSourceAboutUrl(url)) || isPrivate) {
    url = null
  }

  if (lastActivePageUrl === url) {
    return
  }

  let pageViewEvent = Immutable.fromJS({
    timestamp: new Date().getTime(),
    url,
    tabId
  })
  eventState = eventState.set('page_view', eventState.get('page_view').slice(-100).push(pageViewEvent))
  lastActivePageUrl = url
}

const windowBlurred = (windowId) => {
  let windowCount = BrowserWindow.getAllWindows().filter((win) => win.isFocused()).length
  if (windowCount === 0) {
    addPageView(null, null)
  }
}

const windowClosed = (windowId) => {
  let windowCount = BrowserWindow.getAllWindows().length
  let win = BrowserWindow.getFocusedWindow()
  // window may not be closed yet
  if (windowCount > 0 && win && win.id === windowId) {
    win.once('closed', () => {
      windowClosed(windowId)
    })
  }

  if (!win || windowCount === 0) {
    addPageView(null, null)
  }
}

// Register callback to handle all updates
const doAction = (action) => {
  switch (action.actionType) {
    case windowConstants.WINDOW_SET_FOCUSED_FRAME:
      if (action.location) {
        addPageView(action.location, action.tabId)
      }
      break
    case appConstants.APP_WINDOW_BLURRED:
      windowBlurred(action.windowId)
      break
    case appConstants.APP_IDLE_STATE_CHANGED:
      if (action.idleState !== 'active') {
        addPageView(null, null)
      } else {
        addPageView(lastActivePageUrl, lastActiveTabId)
      }
      break
    case appConstants.APP_CLOSE_WINDOW:
      AppDispatcher.waitFor([AppStore.dispatchToken], () => {
        windowClosed(action.windowId)
      })
      break
    case 'event-set-page-info':
      // retains all past pages, not really sure that's needed... [MTR]
      eventState = eventState.set('page_info', eventState.get('page_info').slice(-100).push(action.pageInfo))
      break
    case windowConstants.WINDOW_GOT_RESPONSE_DETAILS:
      // Only capture response for the page (not subresources, like images, JavaScript, etc)
      if (action.details && action.details.resourceType === 'mainFrame') {
        const pageUrl = action.details.newURL

        // create a page view event if this is a page load on the active tabId
        if (!lastActiveTabId || action.tabId === lastActiveTabId) {
          addPageView(pageUrl, action.tabId)
        }

        const responseCode = action.details.httpResponseCode
        if (isSourceAboutUrl(pageUrl) || !responseHasContent(responseCode)) {
          break
        }

        const pageLoadEvent = Immutable.fromJS({
          timestamp: new Date().getTime(),
          url: pageUrl,
          tabId: action.tabId,
          details: action.details
        })
        eventState = eventState.set('page_load', eventState.get('page_load').slice(-100).push(pageLoadEvent))
      }
      break
    default:
      return
  }

  emitChanges()
}

AppDispatcher.register(doAction)

module.exports = eventStore
<|endoftext|>


<commit_before>import {validateAndCallbackify, getMerchantAccessKey, schemeFromNumber, getAppData, isV3Request, isIcpRequest} from "./../utils";
import {savedNBValidationSchema, savedAPIFunc} from "./net-banking";
import {baseSchema} from "./../validation/validation-schema";
import cloneDeep from "lodash/cloneDeep";
import {handlersMap, getConfig} from "../config";
import {validateCardType, validateScheme, cardDate, validateCvv} from "../validation/custom-validations";
import {custFetch} from "../interceptor";
import {urlReEx,TRACKING_IDS,PAGE_TYPES} from "../constants";
import {getCancelResponse, refineMotoResponse} from "./response";
import {singleHopDropOutFunction, singleHopDropInFunction} from "./singleHop";
import {handleDropIn} from './drop-in';
//import $ from 'jquery';

const regExMap = {
    'cardNumber': /^[0-9]{15,19}$/,
    'name': /^(?!\s*$)[a-zA-Z .]{1,50}$/,
    'CVV': /^[0-9]{3,4}$/, //todo: handle cases for amex
    url: urlReEx
};

let cancelApiResp;

const blazeCardValidationSchema = {
    mainObjectCheck: {
        /* keysCheck: ['cardNo', 'expiry', 'cvv', 'cardHolderName',
         'email', 'phone', 'amount', 'currency', 'returnUrl', 'notifyUrl', 'merchantTransactionId', 'merchantAccessKey',
         'signature', 'cardType','cardScheme'],*/
        blazeCardCheck: true
    },
    expiry: {presence: true, cardDate: true},
    cvv: {presence: true, format: regExMap.CVV},
    //cardHolderName : { presence: true, format: regExMap.name },
    email: {presence: true, email: true},
    phone: {length: {maximum: 10}},
    amount: {presence: true},
    currency: {presence: true},
    cardType: {presence: true},
    returnUrl: {
        presence: true,
        custFormat: {
            pattern: regExMap.url,
            message: 'should be proper URL string'
        }
    },
    notifyUrl: {
        custFormat: {
            pattern: regExMap.url,
            message: 'should be proper URL string'
        }
    },
    merchantAccessKey: {presence: true},
    signature: {presence: true}
};

let makeBlazeCardPaymentConfObj;

const makeBlazeCardPayment = validateAndCallbackify(blazeCardValidationSchema, (confObj) => {
    makeBlazeCardPaymentConfObj = confObj;
    //needed to convert cardType and cardScheme with server expected values
    const paymentDetails = Object.assign({}, confObj, {
        cardType: validateCardType(confObj.cardType),
        cardScheme: confObj.cardScheme//validateScheme(confObj.cardScheme)
    });

    return custFetch(getConfig().blazeCardApiUrl + '/cards-gateway/rest/cardspg/mpi', {
        method: 'post',
        headers: {
            'Content-Type': 'application/json'
        },
        mode: 'cors',
        body: JSON.stringify(paymentDetails)
    }).then(function (resp) {
        //to handler back button cancellation scenario

        if (history && history.pushState) {
            let href = window.location.href;
            let appendChar = href.indexOf('?') > -1 ? '&' : '?';
            let newurl = window.location.href + appendChar + 'fromBank=yes';
            window.history.pushState({path: newurl}, '', newurl);
            makeBlazeCardPaymentConfObj.citrusTransactionId = resp.data.citrusTransactionId;
            localStorage.setItem('blazeCardcancelRequestObj', JSON.stringify(makeBlazeCardPaymentConfObj));
        }
        return resp;
    });

});

const merchantCardSchemesSchema = {
    merchantAccessKey: {presence: true}
};

const getmerchantCardSchemes = validateAndCallbackify(merchantCardSchemesSchema, (confObj) => {

    return custFetch(getConfig().blazeCardApiUrl + '/cards-gateway/rest/cardspg/merchantCardSchemes/getEnabledCardScheme', {
        method: 'post',
        headers: {
            'Content-Type': 'application/json'
        },
        mode: 'cors',
        body: JSON.stringify(confObj)
    });
});

//moto implementation

const motoCardValidationSchema = Object.assign(cloneDeep(baseSchema), {
    paymentDetails: {
        presence: true,
        cardCheck: true,
        keysCheck: ['type', 'number', 'holder', 'cvv', 'expiry']
    },
    "paymentDetails.holder": {presence: true, format: regExMap.name}
});

motoCardValidationSchema.mainObjectCheck.keysCheck.push('paymentDetails');

//this code has become hosted-field-specific for dropin case
//for the time being, look into it later
const motoCardApiFunc = (confObj) => {
    const cardScheme = schemeFromNumber(confObj.paymentDetails.number);
    let paymentDetails;
    //todo:refactor this if else later
    if (cardScheme === 'maestro') {
        paymentDetails = Object.assign({}, confObj.paymentDetails, {
            type: validateCardType(confObj.paymentDetails.type),
            scheme: validateScheme(cardScheme),
            expiry: confObj.paymentDetails.expiry,
            cvv: confObj.paymentDetails.cvv
        });
    } else {
        paymentDetails = Object.assign({}, confObj.paymentDetails, {
            type: validateCardType(confObj.paymentDetails.type),
            scheme: validateScheme(cardScheme),
            expiry: cardDate(confObj.paymentDetails.expiry),
            cvv: validateCvv(confObj.paymentDetails.cvv, cardScheme)
        });
    }
    if (confObj.paymentDetails.expiry) {
        var d = confObj.paymentDetails.expiry.slice(3);
        if (d.length == 2) {
            var today = new Date();
            var year = today.getFullYear().toString().slice(0, 2);
            confObj.paymentDetails.expiry = confObj.paymentDetails.expiry.toString().slice(0, 3) + year + d;
        }
    }
    if (getAppData('credit_card') && confObj.paymentDetails.type.toLowerCase() === "credit") confObj.offerToken = getAppData('credit_card')['offerToken'];
    if (getAppData('debit_card') && confObj.paymentDetails.type.toLowerCase() === "debit") confObj.offerToken = getAppData('debit_card')['offerToken'];
    const reqConf = Object.assign({}, confObj, {
        amount: {
            currency: confObj.currency || 'INR',
            value: confObj.amount
        },
        paymentToken: {
            type: 'paymentOptionToken',
            paymentMode: paymentDetails
        },
        merchantAccessKey: getMerchantAccessKey(confObj),
        requestOrigin: confObj.requestOrigin || TRACKING_IDS.CitrusGuest
    });
    reqConf.paymentToken.paymentMode.expiry = confObj.paymentDetails.expiry;
    // reqConf.offerToken = getAppData().dpOfferToken;
    delete reqConf.paymentDetails;
    delete reqConf.currency;
    const mode = (reqConf.mode) ? reqConf.mode.toLowerCase() : "";
    delete reqConf.mode;
    reqConf.deviceType = getConfig().deviceType;
    cancelApiResp = getCancelResponse(reqConf);
    //if (mode === 'dropout' || getConfig().page === PAGE_TYPES.ICP) {
    //} else {
        if (mode === 'dropin' && getConfig().page !== PAGE_TYPES.ICP) {
        if (reqConf.requestOrigin === TRACKING_IDS.CitrusGuest) {
            reqConf.returnUrl = getConfig().dropInReturnUrl;
        }
    }
    if (getConfig().page === PAGE_TYPES.ICP) {
        return custFetch(`${getConfig().motoApiUrl}/${getConfig().vanityUrl}`, {
            method: 'post',
            headers: {
                'Content-Type': 'application/json'
            },
            mode: 'cors',
            body: JSON.stringify(reqConf)
        });
    }
    else {
        return custFetch(`${getConfig().motoApiUrl}/${getConfig().vanityUrl}`, {
        //     return custFetch(`${getConfig().motoApiUrl}/struct/${getConfig().vanityUrl}`, {
            method: 'post',
            headers: {
                'Content-Type': 'application/json'
            },
            mode: 'cors',
            body: JSON.stringify(reqConf)
        }).then(function (resp) {
            if (reqConf.requestOrigin === TRACKING_IDS.CitrusGuest) return resp;
            if (getConfig().page !== PAGE_TYPES.ICP) {
                if (resp.data.redirectUrl) {
                    if (mode === "dropout") {
                        isV3Request(reqConf.requestOrigin)?window.location = resp.data.redirectUrl:singleHopDropOutFunction(resp.data.redirectUrl);
                    }
                    else {//the code will never reach this point for the time being (or atleast should not reach)
                        if (winRef && winRef.closed) {
                            handlersMap["serverErrorHandler"](cancelApiResp);
                            return;
                        }
                        handleDropIn(resp.data, winRef);
                    }
                } else {
                    if (winRef) {
                        winRef.close();
                    }
                    const response = refineMotoResponse(resp.data);
                    handlersMap['serverErrorHandler'](response);
                }
            }
        });
    }
};

const makeMotoCardPayment = validateAndCallbackify(motoCardValidationSchema, motoCardApiFunc);

//this variable is not being assigned anywhere for the time being
//after changes were made for hosted fields in this file, although
//the variable is used in unreachable portions of code for the time being.
let winRef = null;

const savedCardValidationSchema = Object.assign({}, savedNBValidationSchema);
savedCardValidationSchema.mainObjectCheck.keysCheck.push('CVV');

const makeSavedCardPayment = validateAndCallbackify(savedCardValidationSchema, (paymentData)=> {
    const apiUrl = `${getConfig().motoApiUrl}/${getConfig().vanityUrl}`;
    if(isCvvGenerationRequired(paymentData)) { paymentData.CVV = Math.floor(Math.random()*900) + 100; }
    return savedAPIFunc(paymentData, apiUrl);
});

const isCvvGenerationRequired = (paymentData)=>{
    return true;
    if((isV3Request(paymentData.requestOrigin)||isIcpRequest())&&!paymentData.CVV)
        return true;
    return false;
}

export {
    makeBlazeCardPayment, getmerchantCardSchemes, motoCardValidationSchema, motoCardApiFunc,
    makeMotoCardPayment, makeSavedCardPayment
};<commit_msg>changes for non-hosted card payments.<commit_after>import {validateAndCallbackify, getMerchantAccessKey, schemeFromNumber, getAppData, isV3Request, isIcpRequest} from "./../utils";
import {savedNBValidationSchema, savedAPIFunc} from "./net-banking";
import {baseSchema} from "./../validation/validation-schema";
import cloneDeep from "lodash/cloneDeep";
import {handlersMap, getConfig} from "../config";
import {validateCardType, validateScheme, cardDate, validateCvv} from "../validation/custom-validations";
import {custFetch} from "../interceptor";
import {urlReEx,TRACKING_IDS,PAGE_TYPES} from "../constants";
import {getCancelResponse, refineMotoResponse} from "./response";
import {singleHopDropOutFunction, singleHopDropInFunction} from "./singleHop";
import {handleDropIn,openPopupWindowForDropIn} from './drop-in';
//import $ from 'jquery';

const regExMap = {
    'cardNumber': /^[0-9]{15,19}$/,
    'name': /^(?!\s*$)[a-zA-Z .]{1,50}$/,
    'CVV': /^[0-9]{3,4}$/, //todo: handle cases for amex
    url: urlReEx
};

let cancelApiResp;

const blazeCardValidationSchema = {
    mainObjectCheck: {
        /* keysCheck: ['cardNo', 'expiry', 'cvv', 'cardHolderName',
         'email', 'phone', 'amount', 'currency', 'returnUrl', 'notifyUrl', 'merchantTransactionId', 'merchantAccessKey',
         'signature', 'cardType','cardScheme'],*/
        blazeCardCheck: true
    },
    expiry: {presence: true, cardDate: true},
    cvv: {presence: true, format: regExMap.CVV},
    //cardHolderName : { presence: true, format: regExMap.name },
    email: {presence: true, email: true},
    phone: {length: {maximum: 10}},
    amount: {presence: true},
    currency: {presence: true},
    cardType: {presence: true},
    returnUrl: {
        presence: true,
        custFormat: {
            pattern: regExMap.url,
            message: 'should be proper URL string'
        }
    },
    notifyUrl: {
        custFormat: {
            pattern: regExMap.url,
            message: 'should be proper URL string'
        }
    },
    merchantAccessKey: {presence: true},
    signature: {presence: true}
};

let makeBlazeCardPaymentConfObj;

const makeBlazeCardPayment = validateAndCallbackify(blazeCardValidationSchema, (confObj) => {
    makeBlazeCardPaymentConfObj = confObj;
    //needed to convert cardType and cardScheme with server expected values
    const paymentDetails = Object.assign({}, confObj, {
        cardType: validateCardType(confObj.cardType),
        cardScheme: confObj.cardScheme//validateScheme(confObj.cardScheme)
    });

    return custFetch(getConfig().blazeCardApiUrl + '/cards-gateway/rest/cardspg/mpi', {
        method: 'post',
        headers: {
            'Content-Type': 'application/json'
        },
        mode: 'cors',
        body: JSON.stringify(paymentDetails)
    }).then(function (resp) {
        //to handler back button cancellation scenario

        if (history && history.pushState) {
            let href = window.location.href;
            let appendChar = href.indexOf('?') > -1 ? '&' : '?';
            let newurl = window.location.href + appendChar + 'fromBank=yes';
            window.history.pushState({path: newurl}, '', newurl);
            makeBlazeCardPaymentConfObj.citrusTransactionId = resp.data.citrusTransactionId;
            localStorage.setItem('blazeCardcancelRequestObj', JSON.stringify(makeBlazeCardPaymentConfObj));
        }
        return resp;
    });

});

const merchantCardSchemesSchema = {
    merchantAccessKey: {presence: true}
};

const getmerchantCardSchemes = validateAndCallbackify(merchantCardSchemesSchema, (confObj) => {

    return custFetch(getConfig().blazeCardApiUrl + '/cards-gateway/rest/cardspg/merchantCardSchemes/getEnabledCardScheme', {
        method: 'post',
        headers: {
            'Content-Type': 'application/json'
        },
        mode: 'cors',
        body: JSON.stringify(confObj)
    });
});

//moto implementation

const motoCardValidationSchema = Object.assign(cloneDeep(baseSchema), {
    paymentDetails: {
        presence: true,
        cardCheck: true,
        keysCheck: ['type', 'number', 'holder', 'cvv', 'expiry']
    },
    "paymentDetails.holder": {presence: true, format: regExMap.name}
});

motoCardValidationSchema.mainObjectCheck.keysCheck.push('paymentDetails');

//this code has become hosted-field-specific for dropin case
//for the time being, look into it later
const motoCardApiFunc = (confObj) => {
    const cardScheme = schemeFromNumber(confObj.paymentDetails.number);
    let paymentDetails;
    //todo:refactor this if else later
    if (cardScheme === 'maestro') {
        paymentDetails = Object.assign({}, confObj.paymentDetails, {
            type: validateCardType(confObj.paymentDetails.type),
            scheme: validateScheme(cardScheme),
            expiry: confObj.paymentDetails.expiry,
            cvv: confObj.paymentDetails.cvv
        });
    } else {
        paymentDetails = Object.assign({}, confObj.paymentDetails, {
            type: validateCardType(confObj.paymentDetails.type),
            scheme: validateScheme(cardScheme),
            expiry: cardDate(confObj.paymentDetails.expiry),
            cvv: validateCvv(confObj.paymentDetails.cvv, cardScheme)
        });
    }
    if (confObj.paymentDetails.expiry) {
        var d = confObj.paymentDetails.expiry.slice(3);
        if (d.length == 2) {
            var today = new Date();
            var year = today.getFullYear().toString().slice(0, 2);
            confObj.paymentDetails.expiry = confObj.paymentDetails.expiry.toString().slice(0, 3) + year + d;
        }
    }
    if (getAppData('credit_card') && confObj.paymentDetails.type.toLowerCase() === "credit") confObj.offerToken = getAppData('credit_card')['offerToken'];
    if (getAppData('debit_card') && confObj.paymentDetails.type.toLowerCase() === "debit") confObj.offerToken = getAppData('debit_card')['offerToken'];
    const reqConf = Object.assign({}, confObj, {
        amount: {
            currency: confObj.currency || 'INR',
            value: confObj.amount
        },
        paymentToken: {
            type: 'paymentOptionToken',
            paymentMode: paymentDetails
        },
        merchantAccessKey: getMerchantAccessKey(confObj),
        requestOrigin: confObj.requestOrigin || TRACKING_IDS.CitrusGuest
    });
    reqConf.paymentToken.paymentMode.expiry = confObj.paymentDetails.expiry;
    // reqConf.offerToken = getAppData().dpOfferToken;
    delete reqConf.paymentDetails;
    delete reqConf.currency;
    const mode = (reqConf.mode) ? reqConf.mode.toLowerCase() : "";
    delete reqConf.mode;
    reqConf.deviceType = getConfig().deviceType;
    cancelApiResp = getCancelResponse(reqConf);
    //if (mode === 'dropout' || getConfig().page === PAGE_TYPES.ICP) {
    //} else {
    if (mode === 'dropin' && getConfig().page !== PAGE_TYPES.ICP ) {
        reqConf.returnUrl = getConfig().dropInReturnUrl;
        if(getConfig().page!== PAGE_TYPES.HOSTED_FIELD)
            winRef = openPopupWindowForDropIn(winRef);
    }
    if (getConfig().page === PAGE_TYPES.ICP) {
        return custFetch(`${getConfig().motoApiUrl}/${getConfig().vanityUrl}`, {
            method: 'post',
            headers: {
                'Content-Type': 'application/json'
            },
            mode: 'cors',
            body: JSON.stringify(reqConf)
        });
    }
    else {
        return custFetch(`${getConfig().motoApiUrl}/${getConfig().vanityUrl}`, {
        //     return custFetch(`${getConfig().motoApiUrl}/struct/${getConfig().vanityUrl}`, {
            method: 'post',
            headers: {
                'Content-Type': 'application/json'
            },
            mode: 'cors',
            body: JSON.stringify(reqConf)
        }).then(function (resp) {
            if (getConfig().page === PAGE_TYPES.HOSTED_FIELD) return resp;
            if (getConfig().page !== PAGE_TYPES.ICP) {
                if (resp.data.redirectUrl) {
                    if (mode === "dropout") {
                        isV3Request(reqConf.requestOrigin)?window.location = resp.data.redirectUrl:singleHopDropOutFunction(resp.data.redirectUrl);
                    }
                    else {//the code will never reach this point for the time being (or atleast should not reach)
                        if (winRef && winRef.closed) {
                            handlersMap["serverErrorHandler"](cancelApiResp);
                            return;
                        }
                        handleDropIn(resp.data, winRef);
                    }
                } else {
                    if (winRef) {
                        winRef.close();
                    }
                    const response = refineMotoResponse(resp.data);
                    handlersMap['serverErrorHandler'](response);
                }
            }
        });
    }
};

const makeMotoCardPayment = validateAndCallbackify(motoCardValidationSchema, motoCardApiFunc);

//this variable is not being assigned anywhere for the time being
//after changes were made for hosted fields in this file, although
//the variable is used in unreachable portions of code for the time being.
let winRef = null;

const savedCardValidationSchema = Object.assign({}, savedNBValidationSchema);
savedCardValidationSchema.mainObjectCheck.keysCheck.push('CVV');

const makeSavedCardPayment = validateAndCallbackify(savedCardValidationSchema, (paymentData)=> {
    const apiUrl = `${getConfig().motoApiUrl}/${getConfig().vanityUrl}`;
    if(isCvvGenerationRequired(paymentData)) { paymentData.CVV = Math.floor(Math.random()*900) + 100; }
    return savedAPIFunc(paymentData, apiUrl);
});

const isCvvGenerationRequired = (paymentData)=>{
    return true;
    if((isV3Request(paymentData.requestOrigin)||isIcpRequest())&&!paymentData.CVV)
        return true;
    return false;
}

export {
    makeBlazeCardPayment, getmerchantCardSchemes, motoCardValidationSchema, motoCardApiFunc,
    makeMotoCardPayment, makeSavedCardPayment
};<|endoftext|>


<commit_before>;(function (doc) {

  // Enable strict mode
  "use strict";

  // Local object for method references
  var App = {};

  // A proper namespace
  App.ns = "SVG Sprite Polyfill";

  // Ajax!
  App.ajax = function(loopObj, callback) {

    var request = new XMLHttpRequest();
    var response;

    request.open('GET', loopObj, true);

      request.onload = function() {
        if (request.status >= 200 && request.status < 400) {

          response = request.responseText;

          if (typeof callback === 'function') {
            callback.call(this, response);
          }

        } else {

          console.log('Error reaching the server');

        }

      };

      request.onerror = function() {

        console.log('Connection error');

      };

      request.send();

  }; // Ajax

  // Start the application
  App.init = function() {

    var svg = doc.querySelectorAll("svg > use");
    var fragment = App.create('

');
    var svgUrls = [];
    var attrArray = [];
    var url;
    var hash;
    var i;
    var j;
    var obj;
    var loopObj;
    var attr;
    //var request;
    //var resp;

    // Insert the document fragment catch the contents of the SVG
    document.body.insertBefore(fragment, document.body.childNodes[0]);

    for (i = 0; i < svg.length; i = i + 1) {

      obj = svg[i];
      attr = obj.getAttribute('xlink:href');
      attrArray = attr.split('#');
      url = attrArray[0];
      hash = attrArray[1];

      if( url ) {
        svgUrls.push( url );
        obj.setAttribute('xlink:href', '#' + hash);
      }

    } // for

    // Remove duplicate URLs from the array so we're not making double Ajax calls
    svgUrls = svgUrls.filter( function(item, pos) {
      return svgUrls.indexOf(item) == pos;
    });

    // Loop through all the URLs in the Array
    for (j = 0; j < svgUrls.length; j = j + 1) {

      loopObj = svgUrls[j];

      App.ajax( loopObj, function( response ) {
        document.getElementById('svg-poly-target').innerHTML += response;
      });

    } // for

  }; // App.init

  // Helper function to create a document fragment

  App.create = function( htmlStr ) {

    var frag = document.createDocumentFragment();
    var temp = document.createElement('div');

    temp.innerHTML = htmlStr;

    while ( temp.firstChild ) {
      frag.appendChild(temp.firstChild);
    }

    return frag;

  };

  /MSIE|Trident/.test(navigator.userAgent) && document.addEventListener('DOMContentLoaded', function () {

    App.init();

  });

} )( this.document );<commit_msg>removed aria-hidden because we're better than that<commit_after>;(function (doc) {

  // Enable strict mode
  "use strict";

  // Local object for method references
  var App = {};

  // A proper namespace
  App.ns = "SVG Sprite Polyfill";

  // Ajax!
  App.ajax = function(loopObj, callback) {

    var request = new XMLHttpRequest();
    var response;

    request.open('GET', loopObj, true);

      request.onload = function() {
        if (request.status >= 200 && request.status < 400) {

          response = request.responseText;

          if (typeof callback === 'function') {
            callback.call(this, response);
          }

        } else {

          console.log('Error reaching the server');

        }

      };

      request.onerror = function() {

        console.log('Connection error');

      };

      request.send();

  }; // Ajax

  // Start the application
  App.init = function() {

    var svgUse = doc.querySelectorAll("svg > use");
    var fragment = App.create('

');
    var svgUrls = [];
    var attrArray = [];
    var url;
    var hash;
    var i;
    var j;
    var obj;
    var loopObj;
    var attr;

    // Insert the document fragment catch the contents of the SVG
    document.body.insertBefore(fragment, document.body.childNodes[0]);

    for (i = 0; i < svgUse.length; i = i + 1) {

      obj = svgUse[i];
      attr = obj.getAttribute('xlink:href');
      attrArray = attr.split('#');
      url = attrArray[0];
      hash = attrArray[1];

      if( url ) {
        svgUrls.push( url );
        obj.setAttribute('xlink:href', '#' + hash);
      }

    } // for

    // Remove duplicate URLs from the array so we're not making double Ajax calls
    svgUrls = svgUrls.filter( function( item, pos ) {
      return svgUrls.indexOf(item) == pos;
    });

    // Loop through all the URLs in the Array
    for (j = 0; j < svgUrls.length; j = j + 1) {

      loopObj = svgUrls[j];

      App.ajax( loopObj, function( response ) {
        document.getElementById('svg-poly-target').innerHTML += response;
      });

    } // for

  }; // App.init

  // Helper function to create a document fragment

  App.create = function( htmlStr ) {

    var frag = document.createDocumentFragment();
    var temp = document.createElement('div');

    temp.innerHTML = htmlStr;

    while ( temp.firstChild ) {
      frag.appendChild(temp.firstChild);
    }

    return frag;

  };

  /MSIE|Trident/.test(navigator.userAgent) && document.addEventListener('DOMContentLoaded', function () {

    App.init();

  });

} )( this.document );<|endoftext|>


<commit_before>/*
 * arbor_main.js
 * author: jerryzou
 * email: zry656565@gmail.com
 */

(function($){

  var Renderer = function(canvas){
    var canvas = $(canvas).get(0),
        ctx = canvas.getContext("2d"),
        particleSystem;
    var gfx = arbor.Graphics(canvas);

    // helpers for figuring out where to draw arrows (thanks springy.js)
    var intersect_line_line = function(p1, p2, p3, p4)
    {
      var denom = ((p4.y - p3.y)*(p2.x - p1.x) - (p4.x - p3.x)*(p2.y - p1.y));
      if (denom === 0) return false // lines are parallel
      var ua = ((p4.x - p3.x)*(p1.y - p3.y) - (p4.y - p3.y)*(p1.x - p3.x)) / denom;
      var ub = ((p2.x - p1.x)*(p1.y - p3.y) - (p2.y - p1.y)*(p1.x - p3.x)) / denom;

      if (ua < 0 || ua > 1 || ub < 0 || ub > 1)  return false
      return arbor.Point(p1.x + ua * (p2.x - p1.x), p1.y + ua * (p2.y - p1.y));
    }

    var intersect_line_box = function(p1, p2, boxTuple)
    {
      var p3 = {x:boxTuple[0], y:boxTuple[1]},
          w = boxTuple[2],
          h = boxTuple[3]

      var tl = {x: p3.x, y: p3.y};
      var tr = {x: p3.x + w, y: p3.y};
      var bl = {x: p3.x, y: p3.y + h};
      var br = {x: p3.x + w, y: p3.y + h};

      return intersect_line_line(p1, p2, tl, tr) ||
             intersect_line_line(p1, p2, tr, br) ||
             intersect_line_line(p1, p2, br, bl) ||
             intersect_line_line(p1, p2, bl, tl) ||
             false
    }

    var that = {
      init:function(system){
        particleSystem = system;
        particleSystem.screenSize(canvas.width, canvas.height);
        particleSystem.screenPadding(20);
        that.initMouseHandling();
      },

      redraw:function(){
        //
        // redraw will be called repeatedly during the run whenever the node positions
        // change. the new positions for the nodes can be accessed by looking at the
        // .p attribute of a given node. however the p.x & p.y values are in the coordinates
        // of the particle system rather than the screen. you can either map them to
        // the screen yourself, or use the convenience iterators .eachNode (and .eachEdge)
        // which allow you to step through the actual node objects but also pass an
        // x,y point in the screen's coordinate system
        //
        if (!particleSystem) return

        ctx.clearRect(0,0, canvas.width, canvas.height)

        var nodeBoxes = {}
        particleSystem.eachNode(function(node, pt){
          // node: {mass:#, p:{x,y}, name:"", data:{}}
          // pt:   {x:#, y:#}  node position in screen coords

          // determine the box size and round off the coords if we'll be
          // drawing a text label (awful alignment jitter otherwise...)
          var label = (node.data.description || "").toString();
          var w, h, fontsize;
          switch (node.data.style) {
            case 'biggest':
              ctx.font = "24px Avenir";
              w = ctx.measureText(label).width + 10;
              h = 36;
              fontsize = "24px";
              break;
            case 'bigger':
              ctx.font = "20px Avenir";
              w = ctx.measureText(label).width + 10;
              h = 28;
              fontsize = "20px";
              break;
            default:
              ctx.font = "14px Avenir";
              w = ctx.measureText(label).width + 10;
              h = 20;
              fontsize = "14px";
              break;
          }
          if (!(label).match(/^[\t]*$/)){
            pt.x = Math.floor(pt.x);
            pt.y = Math.floor(pt.y);
          }else{
            label = null;
          }

          if (!node.data.color) {
            switch (node.data.type) {
              case 'lang':
                ctx.fillStyle = '#4F94CD';
                break;
              case 'tool':
                ctx.fillStyle = '#FF6A6A';
                break;
              case 'experience':
                ctx.fillStyle = '#EEB422';
                break;
              default:
                ctx.fillStyle = '#333333';
                break;
            }
          } else {
            ctx.fillStyle = node.data.color;
          }

          gfx.rect(pt.x-w/2, pt.y-h/2, w, h, 4, {fill:ctx.fillStyle});
          nodeBoxes[node.name] = [pt.x-w/2, pt.y-h/2-1, w, h+2];

          // draw the text
          if (label){
            ctx.font = fontsize + " Avenir, Microsoft Yahei, Hiragino Sans GB, Microsoft Sans Serif, WenQuanYi Micro Hei, sans-serif";
            ctx.textAlign = "center";
            ctx.fillStyle = "white";
            ctx.fillText(label||"", pt.x, pt.y+4);
            ctx.fillText(label||"", pt.x, pt.y+4);
          }
        })

        ctx.strokeStyle = "#cccccc";
        ctx.lineWidth = 1;
        ctx.beginPath();
        particleSystem.eachEdge(function(edge, pt1, pt2){
          // edge: {source:Node, target:Node, length:#, data:{}}
          // pt1:  {x:#, y:#}  source position in screen coords
          // pt2:  {x:#, y:#}  target position in screen coords

          var weight = edge.data.weight;
          var color = edge.data.color;

          // trace(color)
          if (!color || (""+color).match(/^[ \t]*$/)) color = null;

          // find the start point
          var tail = intersect_line_box(pt1, pt2, nodeBoxes[edge.source.name]);
          var head = intersect_line_box(tail, pt2, nodeBoxes[edge.target.name]);

          ctx.save();
            ctx.beginPath();

            if (!isNaN(weight)) ctx.lineWidth = weight;
            if (color) ctx.strokeStyle = color;
            // if (color) trace(color)
            ctx.fillStyle = null;

            ctx.moveTo(tail.x, tail.y);
            ctx.lineTo(head.x, head.y);
            ctx.stroke();
          ctx.restore();

          // draw an arrowhead if this is a -> style edge
          if (edge.data.directed){
            ctx.save();
              // move to the head position of the edge we just drew
              var wt = !isNaN(weight) ? parseFloat(weight) : ctx.lineWidth;
              var arrowLength = 6 + wt;
              var arrowWidth = 2 + wt;
              ctx.fillStyle = (color) ? color : ctx.strokeStyle;
              ctx.translate(head.x, head.y);
              ctx.rotate(Math.atan2(head.y - tail.y, head.x - tail.x));

              // delete some of the edge that's already there (so the point isn't hidden)
              ctx.clearRect(-arrowLength/2,-wt/2, arrowLength/2,wt)

              // draw the chevron
              ctx.beginPath();
              ctx.moveTo(-arrowLength, arrowWidth);
              ctx.lineTo(0, 0);
              ctx.lineTo(-arrowLength, -arrowWidth);
              ctx.lineTo(-arrowLength * 0.8, -0);
              ctx.closePath();
              ctx.fill();
            ctx.restore();
          }
        })
      },

      initMouseHandling:function(){
        // no-nonsense drag and drop (thanks springy.js)
        var dragged = null;

        // set up a handler object that will initially listen for mousedowns then
        // for moves and mouseups while dragging
        var handler = {
          clicked:function(e){
            var pos = $(canvas).offset();
            _mouseP = arbor.Point(e.pageX-pos.left, e.pageY-pos.top)
            dragged = particleSystem.nearest(_mouseP);

            if (dragged && dragged.node !== null){
              // while we're dragging, don't let physics move the node
              dragged.node.fixed = true
            }

            $(canvas).bind('mousemove', handler.dragged)
            $(window).bind('mouseup', handler.dropped)

            return false
          },
          dragged:function(e){
            var pos = $(canvas).offset();
            var s = arbor.Point(e.pageX-pos.left, e.pageY-pos.top)

            if (dragged && dragged.node !== null){
              var p = particleSystem.fromScreen(s)
              dragged.node.p = p
            }

            return false
          },

          dropped:function(e){
            if (dragged===null || dragged.node===undefined) return
            if (dragged.node !== null) dragged.node.fixed = false
            dragged.node.tempMass = 1000
            dragged = null
            $(canvas).unbind('mousemove', handler.dragged)
            $(window).unbind('mouseup', handler.dropped)
            _mouseP = null
            return false
          }
        }

        // start listening
        $(canvas).mousedown(handler.clicked);

      },

    }
    return that
  }

  $(function(){
    var sys = arbor.ParticleSystem(1000, 600, 0.5) // create the system with sensible repulsion/stiffness/friction
    sys.parameters({gravity:true}) // use center-gravity to make the graph settle nicely (ymmv)
    sys.renderer = Renderer("#skillboard") // our newly created renderer will have its .init() method called shortly by sys...

    // add some nodes to the graph and watch it go...
    //sys.addEdge('a','b')
    //sys.addEdge('a','c')
    //sys.addEdge('a','d')
    //sys.addEdge('a','e')
    //sys.addNode('f', {alone:true, mass:.25})

    // or, equivalently:
    //
    var nodes = {
      'js': { description: 'javascript', type: 'lang' },
      'java': { description: 'Java', type: 'lang' },
      'c': { description: 'C/C++', type: 'lang' },
      'c#': { description: 'C#', type: 'lang' },
      'lisp': { description: 'lisp', type: 'lang' },
      'css': { description: 'css', type: 'lang' },
      'html': { description: 'html5', type: 'lang' },
      'git': { description: 'git', type: 'tool' },
      'justjs': { description: 'JustJS', type: 'experience' },
      'jreparser': { description: 'JRE-Parser', type: 'experience' },
      'ms-intern': { description: 'Microsoft实习', type: 'experience' },
      'haijiao': { description: '海角教育', type: 'experience' },
      'cocos2d-js': { description: 'cocos2d-JS', type: 'tool' },
      'unity-3d': { description: 'Unity-3d', type: 'tool' },
      'mongodb': { description: 'MongoDB', type: 'tool' },
      'logv': { description: 'LogV', type: 'experience' },
      'kinect': { description: 'Kinect', type: 'tool' },
      'screenbuilder': { description: 'Screen Builder', type: 'experience' },
      'maoxian': { description: '冒险的召唤', type: 'experience' },
      'jekyll': { description: 'jekyll', type: 'tool' },
      'cocos-docs': { description: 'cocos维基', type: 'experience' },
      'uav': { description: '小型无人机技术大赛', type: 'experience' },
      'ssh': { description: 'Struct+Spring+Hibernate', type: 'tool' },
      'game-dev': { description: '游戏开发', type: 'experience' },
      'blog': { description: 'Jerry的乐园（博客）', type: 'experience' }
    };

    var edges = {
      'ms-intern': {
        'js': { weight: 3 },
        'css': { weight: 2 },
        'html': { weight: 2 },
        'c#': { weight: 2 },
        'git': { weight: 2 }
      },
      'haijiao':{
        'ssh': { weight: 2 },
        'js': { weight: 1 },
        'java': { weight: 2 },
        'git': { weight: 1 }
      },
      'cocos2d-js': {
        'js': { weight: 2 },
        'game-dev': { weight: 3 }
      },
      'logv': {
        'js': { weight: 2 },
        'css': { weight: 1 },
        'java': { weight: 2 },
        'mongodb': { weight: 2 }
      },
      'screenbuilder': {
        'c': { weight: 2 },
        'c#': { weight: 2 },
        'kinect': { weight: 3 }
      },
      'maoxian': {
        'unity-3d': { weight: 3 },
        'game-dev': { weight: 3 },
        'c#': { weight: 1 },
        'js': { weight: 2 }
      },
      'blog': {
        'jekyll': { weight: 2 },
        'js': { weight: 2 },
        'css': { weight: 3 },
        'html': { weight: 3 },
        'git': { weight: 2 }
      },
      'uav': {
        'c': { weight: 2 },
        'git': { weight: 1 }
      },
      'lisp': {
        'js': { weight: 1 }
      },
      'cocos-docs': {
        'cocos2d-js': { weight: 1 }
      },
      'justjs': {
        'js': { weight: 3 }
      },
      'jreparser': {
        'js': { weight: 3 }
      }
    };

    for (var n1 in edges) {
      if (edges.hasOwnProperty(n1)) {
        for (var n2 in edges[n1]) {
          if (edges[n1].hasOwnProperty(n2)) {
            var edgeWeight = edges[n1][n2].weight;
            nodes[n2].weight = nodes[n2].weight ? nodes[n2].weight + edgeWeight : edgeWeight;
          }
        }
      }
    }
    // select 3 nodes with the most weight.
    var max3 = [];
    for (var n in nodes) {
      if (nodes.hasOwnProperty(n)) {
        nodes[n].weight || (nodes[n].weight = 0);
        max3.push(nodes[n]);
      }
    }
    max3.sort(function(a, b){
      return b.weight - a.weight;
    })
    console.log(max3);
    max3[0].style = "biggest";
    max3[1].style = "bigger";
    max3[2].style = "bigger";

    sys.graft({
      nodes: nodes,
      edges: edges
    })
  })

})(this.jQuery)<commit_msg>thinner edges<commit_after>/*
 * arbor_main.js
 * author: jerryzou
 * email: zry656565@gmail.com
 */

(function($){

  var Renderer = function(canvas){
    var canvas = $(canvas).get(0),
        ctx = canvas.getContext("2d"),
        particleSystem;
    var gfx = arbor.Graphics(canvas);

    // helpers for figuring out where to draw arrows (thanks springy.js)
    var intersect_line_line = function(p1, p2, p3, p4)
    {
      var denom = ((p4.y - p3.y)*(p2.x - p1.x) - (p4.x - p3.x)*(p2.y - p1.y));
      if (denom === 0) return false // lines are parallel
      var ua = ((p4.x - p3.x)*(p1.y - p3.y) - (p4.y - p3.y)*(p1.x - p3.x)) / denom;
      var ub = ((p2.x - p1.x)*(p1.y - p3.y) - (p2.y - p1.y)*(p1.x - p3.x)) / denom;

      if (ua < 0 || ua > 1 || ub < 0 || ub > 1)  return false
      return arbor.Point(p1.x + ua * (p2.x - p1.x), p1.y + ua * (p2.y - p1.y));
    }

    var intersect_line_box = function(p1, p2, boxTuple)
    {
      var p3 = {x:boxTuple[0], y:boxTuple[1]},
          w = boxTuple[2],
          h = boxTuple[3]

      var tl = {x: p3.x, y: p3.y};
      var tr = {x: p3.x + w, y: p3.y};
      var bl = {x: p3.x, y: p3.y + h};
      var br = {x: p3.x + w, y: p3.y + h};

      return intersect_line_line(p1, p2, tl, tr) ||
             intersect_line_line(p1, p2, tr, br) ||
             intersect_line_line(p1, p2, br, bl) ||
             intersect_line_line(p1, p2, bl, tl) ||
             false
    }

    var that = {
      init:function(system){
        particleSystem = system;
        particleSystem.screenSize(canvas.width, canvas.height);
        particleSystem.screenPadding(20);
        that.initMouseHandling();
      },

      redraw:function(){
        //
        // redraw will be called repeatedly during the run whenever the node positions
        // change. the new positions for the nodes can be accessed by looking at the
        // .p attribute of a given node. however the p.x & p.y values are in the coordinates
        // of the particle system rather than the screen. you can either map them to
        // the screen yourself, or use the convenience iterators .eachNode (and .eachEdge)
        // which allow you to step through the actual node objects but also pass an
        // x,y point in the screen's coordinate system
        //
        if (!particleSystem) return

        ctx.clearRect(0,0, canvas.width, canvas.height)

        var nodeBoxes = {}
        particleSystem.eachNode(function(node, pt){
          // node: {mass:#, p:{x,y}, name:"", data:{}}
          // pt:   {x:#, y:#}  node position in screen coords

          // determine the box size and round off the coords if we'll be
          // drawing a text label (awful alignment jitter otherwise...)
          var label = (node.data.description || "").toString();
          var w, h, fontsize;
          switch (node.data.style) {
            case 'biggest':
              ctx.font = "24px Avenir";
              w = ctx.measureText(label).width + 10;
              h = 36;
              fontsize = "24px";
              break;
            case 'bigger':
              ctx.font = "20px Avenir";
              w = ctx.measureText(label).width + 10;
              h = 28;
              fontsize = "20px";
              break;
            default:
              ctx.font = "14px Avenir";
              w = ctx.measureText(label).width + 10;
              h = 20;
              fontsize = "14px";
              break;
          }
          if (!(label).match(/^[\t]*$/)){
            pt.x = Math.floor(pt.x);
            pt.y = Math.floor(pt.y);
          }else{
            label = null;
          }

          if (!node.data.color) {
            switch (node.data.type) {
              case 'lang':
                ctx.fillStyle = '#4F94CD';
                break;
              case 'tool':
                ctx.fillStyle = '#FF6A6A';
                break;
              case 'experience':
                ctx.fillStyle = '#EEB422';
                break;
              default:
                ctx.fillStyle = '#333333';
                break;
            }
          } else {
            ctx.fillStyle = node.data.color;
          }

          gfx.rect(pt.x-w/2, pt.y-h/2, w, h, 4, {fill:ctx.fillStyle});
          nodeBoxes[node.name] = [pt.x-w/2, pt.y-h/2-1, w, h+2];

          // draw the text
          if (label){
            ctx.font = fontsize + " Avenir, Microsoft Yahei, Hiragino Sans GB, Microsoft Sans Serif, WenQuanYi Micro Hei, sans-serif";
            ctx.textAlign = "center";
            ctx.fillStyle = "white";
            ctx.fillText(label||"", pt.x, pt.y+4);
            ctx.fillText(label||"", pt.x, pt.y+4);
          }
        })

        ctx.strokeStyle = "#cccccc";
        ctx.lineWidth = 1;
        ctx.beginPath();
        particleSystem.eachEdge(function(edge, pt1, pt2){
          // edge: {source:Node, target:Node, length:#, data:{}}
          // pt1:  {x:#, y:#}  source position in screen coords
          // pt2:  {x:#, y:#}  target position in screen coords

          var weight = 1;//edge.data.weight;
          var color = edge.data.color;

          // trace(color)
          if (!color || (""+color).match(/^[ \t]*$/)) color = null;

          // find the start point
          var tail = intersect_line_box(pt1, pt2, nodeBoxes[edge.source.name]);
          var head = intersect_line_box(tail, pt2, nodeBoxes[edge.target.name]);

          ctx.save();
            ctx.beginPath();

            if (!isNaN(weight)) ctx.lineWidth = weight;
            if (color) ctx.strokeStyle = color;
            // if (color) trace(color)
            ctx.fillStyle = null;

            ctx.moveTo(tail.x, tail.y);
            ctx.lineTo(head.x, head.y);
            ctx.stroke();
          ctx.restore();

          // draw an arrowhead if this is a -> style edge
          if (edge.data.directed){
            ctx.save();
              // move to the head position of the edge we just drew
              var wt = !isNaN(weight) ? parseFloat(weight) : ctx.lineWidth;
              var arrowLength = 6 + wt;
              var arrowWidth = 2 + wt;
              ctx.fillStyle = (color) ? color : ctx.strokeStyle;
              ctx.translate(head.x, head.y);
              ctx.rotate(Math.atan2(head.y - tail.y, head.x - tail.x));

              // delete some of the edge that's already there (so the point isn't hidden)
              ctx.clearRect(-arrowLength/2,-wt/2, arrowLength/2,wt)

              // draw the chevron
              ctx.beginPath();
              ctx.moveTo(-arrowLength, arrowWidth);
              ctx.lineTo(0, 0);
              ctx.lineTo(-arrowLength, -arrowWidth);
              ctx.lineTo(-arrowLength * 0.8, -0);
              ctx.closePath();
              ctx.fill();
            ctx.restore();
          }
        })
      },

      initMouseHandling:function(){
        // no-nonsense drag and drop (thanks springy.js)
        var dragged = null;

        // set up a handler object that will initially listen for mousedowns then
        // for moves and mouseups while dragging
        var handler = {
          clicked:function(e){
            var pos = $(canvas).offset();
            _mouseP = arbor.Point(e.pageX-pos.left, e.pageY-pos.top)
            dragged = particleSystem.nearest(_mouseP);

            if (dragged && dragged.node !== null){
              // while we're dragging, don't let physics move the node
              dragged.node.fixed = true
            }

            $(canvas).bind('mousemove', handler.dragged)
            $(window).bind('mouseup', handler.dropped)

            return false
          },
          dragged:function(e){
            var pos = $(canvas).offset();
            var s = arbor.Point(e.pageX-pos.left, e.pageY-pos.top)

            if (dragged && dragged.node !== null){
              var p = particleSystem.fromScreen(s)
              dragged.node.p = p
            }

            return false
          },

          dropped:function(e){
            if (dragged===null || dragged.node===undefined) return
            if (dragged.node !== null) dragged.node.fixed = false
            dragged.node.tempMass = 1000
            dragged = null
            $(canvas).unbind('mousemove', handler.dragged)
            $(window).unbind('mouseup', handler.dropped)
            _mouseP = null
            return false
          }
        }

        // start listening
        $(canvas).mousedown(handler.clicked);

      },

    }
    return that
  }

  $(function(){
    var sys = arbor.ParticleSystem(1000, 600, 0.5) // create the system with sensible repulsion/stiffness/friction
    sys.parameters({gravity:true}) // use center-gravity to make the graph settle nicely (ymmv)
    sys.renderer = Renderer("#skillboard") // our newly created renderer will have its .init() method called shortly by sys...

    // add some nodes to the graph and watch it go...
    //sys.addEdge('a','b')
    //sys.addEdge('a','c')
    //sys.addEdge('a','d')
    //sys.addEdge('a','e')
    //sys.addNode('f', {alone:true, mass:.25})

    // or, equivalently:
    //
    var nodes = {
      'js': { description: 'javascript', type: 'lang' },
      'java': { description: 'Java', type: 'lang' },
      'c': { description: 'C/C++', type: 'lang' },
      'c#': { description: 'C#', type: 'lang' },
      'lisp': { description: 'lisp', type: 'lang' },
      'css': { description: 'css', type: 'lang' },
      'html': { description: 'html5', type: 'lang' },
      'git': { description: 'git', type: 'tool' },
      'justjs': { description: 'JustJS', type: 'experience' },
      'jreparser': { description: 'JRE-Parser', type: 'experience' },
      'ms-intern': { description: 'Microsoft实习', type: 'experience' },
      'haijiao': { description: '海角教育', type: 'experience' },
      'cocos2d-js': { description: 'cocos2d-JS', type: 'tool' },
      'unity-3d': { description: 'Unity-3d', type: 'tool' },
      'mongodb': { description: 'MongoDB', type: 'tool' },
      'logv': { description: 'LogV', type: 'experience' },
      'kinect': { description: 'Kinect', type: 'tool' },
      'screenbuilder': { description: 'Screen Builder', type: 'experience' },
      'maoxian': { description: '冒险的召唤', type: 'experience' },
      'jekyll': { description: 'jekyll', type: 'tool' },
      'cocos-docs': { description: 'cocos维基', type: 'experience' },
      'uav': { description: '小型无人机技术大赛', type: 'experience' },
      'ssh': { description: 'Struct+Spring+Hibernate', type: 'tool' },
      'game-dev': { description: '游戏开发', type: 'experience' },
      'blog': { description: 'Jerry的乐园（博客）', type: 'experience' }
    };

    var edges = {
      'ms-intern': {
        'js': { weight: 3 },
        'css': { weight: 2 },
        'html': { weight: 2 },
        'c#': { weight: 2 },
        'git': { weight: 2 }
      },
      'haijiao':{
        'ssh': { weight: 2 },
        'js': { weight: 1 },
        'java': { weight: 2 },
        'git': { weight: 1 }
      },
      'cocos2d-js': {
        'js': { weight: 2 },
        'game-dev': { weight: 3 }
      },
      'logv': {
        'js': { weight: 2 },
        'css': { weight: 1 },
        'java': { weight: 2 },
        'mongodb': { weight: 2 }
      },
      'screenbuilder': {
        'c': { weight: 2 },
        'c#': { weight: 2 },
        'kinect': { weight: 3 }
      },
      'maoxian': {
        'unity-3d': { weight: 3 },
        'game-dev': { weight: 3 },
        'c#': { weight: 1 },
        'js': { weight: 2 }
      },
      'blog': {
        'jekyll': { weight: 2 },
        'js': { weight: 2 },
        'css': { weight: 3 },
        'html': { weight: 3 },
        'git': { weight: 2 }
      },
      'uav': {
        'c': { weight: 2 },
        'git': { weight: 1 }
      },
      'lisp': {
        'js': { weight: 1 }
      },
      'cocos-docs': {
        'cocos2d-js': { weight: 1 }
      },
      'justjs': {
        'js': { weight: 3 }
      },
      'jreparser': {
        'js': { weight: 3 }
      }
    };

    for (var n1 in edges) {
      if (edges.hasOwnProperty(n1)) {
        for (var n2 in edges[n1]) {
          if (edges[n1].hasOwnProperty(n2)) {
            var edgeWeight = edges[n1][n2].weight;
            nodes[n2].weight = nodes[n2].weight ? nodes[n2].weight + edgeWeight : edgeWeight;
          }
        }
      }
    }
    // select 3 nodes with the most weight.
    var max3 = [];
    for (var n in nodes) {
      if (nodes.hasOwnProperty(n)) {
        nodes[n].weight || (nodes[n].weight = 0);
        max3.push(nodes[n]);
      }
    }
    max3.sort(function(a, b){
      return b.weight - a.weight;
    })
    console.log(max3);
    max3[0].style = "biggest";
    max3[1].style = "bigger";
    max3[2].style = "bigger";

    sys.graft({
      nodes: nodes,
      edges: edges
    })
  })

})(this.jQuery)<|endoftext|>


<commit_before>var logo = require('./node-png').readPng('./node-logo.png');
var x11 = require('../../lib/x11');

var Exposure = x11.eventMask.Exposure;
var KeyPress = x11.eventMask.KeyPress;
var KeyRelease = x11.eventMask.KeyRelease;
var ButtonPress = x11.eventMask.ButtonPress;
var ButtonRelease = x11.eventMask.ButtonRelease;

x11.createClient(function(display)
{
    var X = display.client;
    X.require('big-requests', function(BigReq)
    {
         X.require('render', function(Render) {
             X.Render = Render;
             BigReq.Enable(function(maxLen)
             {

      var root = display.screen[0].root;
      var white = display.screen[0].white_pixel;
      var black = display.screen[0].black_pixel;

      var win = X.AllocID();
      X.CreateWindow(
         win, root,
         0, 0, logo.width, logo.height,
         1, 1, 0,
         {
             backgroundPixel: white, eventMask: Exposure|KeyPress|ButtonPress
         }
      );
      X.MapWindow(win);

      var gc = X.AllocID();
      X.CreateGC(gc, win);

      var pixmaplogo = X.AllocID();
      X.CreatePixmap(pixmaplogo, win, 24, logo.width, logo.height);
      var piclogo = X.AllocID();
      X.PutImage(2, pixmaplogo, gc, logo.width, logo.height, 0, 0, 0, 24, logo.data);
      Render.CreatePicture(piclogo, pixmaplogo, Render.rgb24);

X.on('event', function(ev) {
        if (ev.type == 12) // expose
         {
             Render.Composite(3, piclogo, 0, win, 0, 0, 0, 0, 0, 0, logo.width, logo.height);
         }
});

X.on('error', function(err) {
    console.log(err.stack);
});

             });
         });
    });
});
<commit_msg>simple pngs are displayed now<commit_after>//var logo = require('./node-png').readPng('./node-logo.png');
var logo = require('./node-png').readPng(process.argv[2]);
var x11 = require('../../lib/x11');

var Exposure = x11.eventMask.Exposure;
var KeyPress = x11.eventMask.KeyPress;
var KeyRelease = x11.eventMask.KeyRelease;
var ButtonPress = x11.eventMask.ButtonPress;
var ButtonRelease = x11.eventMask.ButtonRelease;
var PointerMotion = x11.eventMask.PointerMotion;

x11.createClient(function(display)
{
    var X = display.client;
    X.require('big-requests', function(BigReq)
    {
         X.require('render', function(Render) {
             X.Render = Render;
             BigReq.Enable(function(maxLen)
             {

      var root = display.screen[0].root;
      var white = display.screen[0].white_pixel;
      var black = display.screen[0].black_pixel;

      var win = X.AllocID();
      X.CreateWindow(
         win, root,
         0, 0, logo.width, logo.height,
         1, 1, 0,
         {
             backgroundPixel: white, eventMask: Exposure|KeyPress|ButtonPress|PointerMotion
         }
      );
      X.MapWindow(win);

      var gc = X.AllocID();
      X.CreateGC(gc, win);

      var pixmaplogo = X.AllocID();
      X.CreatePixmap(pixmaplogo, win, 24, logo.width, logo.height);
      X.PolyFillRectangle(pixmaplogo, gc, [0, 0, 1000, 1000]);
      X.PutImage(2, pixmaplogo, gc, logo.width, logo.height, 0, 0, 0, 24, logo.data);

      var piclogo = X.AllocID();
      Render.CreatePicture(piclogo, pixmaplogo, Render.rgb24);

      var picWin = X.AllocID();
      Render.CreatePicture(picWin, win, Render.rgb24);

X.on('event', function(ev) {
        if (ev.type == 12) // expose
        {
             Render.Composite(3, piclogo, 0, picWin, 0, 0, 0, 0, 0, 0, logo.width, logo.height);
        }
});

X.on('error', function(err) {
    console.log(err);
});

             });
         });
    });
});
<|endoftext|>


<commit_before>(function () {

var
  V = envision;

// Custom data processor
function processData (options) {

  var
    resolution = options.resolution;

  options.preprocessor
    .bound(options.min, options.max)
    .subsampleMinMax(resolution + Math.round(resolution / 3));
}

function getDefaults () {
  return {
    price : {
      name : 'envision-finance-price',
      flotr : {
        'lite-lines' : {
          lineWidth : 1,
          show : true,
          fill : true,
          fillOpacity : .2
        },
        mouse : {
          track: true,
          trackY: false,
          trackAll: true,
          sensibility: 1,
          trackDecimals: 4,
          position: 'ne'
        },
        yaxis : {
          autoscale : true,
          autoscaleMargin : 0.05,
          noTicks : 4,
          showLabels : true,
          min : 0
        }
      },
      processData : processData
    },
    volume : {
      name : 'envision-finance-volume',
      flotr : {
        whiskers : {
          show : true,
          lineWidth : 2
        },
        mouse: {
          track: true,
          trackY: false,
          trackAll: true
        }
      },
      processData : processData
    },
    summary : {
      name : 'envision-finance-summary',
      flotr : {
        'lite-lines' : {
          show : true,
          lineWidth : 1,
          fill : true,
          fillOpacity : .2,
          fillBorder : true
        },
        xaxis : {
          noTicks: 5,
          showLabels : true
        },
        yaxis : {
          autoscale : true,
          autoscaleMargin : .1
        },
        handles : {
          show : true
        },
        selection : {
          mode : 'x'
        },
        grid : {
          verticalLines : false
        }
      }
    },
    connection : {
      name : 'envision-finance-connection',
      drawing : V.QuadraticDrawing
    }
  };
}

function Finance (options) {

  var
    data = options.data,
    defaults = getDefaults(),
    vis = new V.Visualization(),
    selection = new V.Interaction(),
    hit = new V.Interaction(),
    price, volume, connection, summary;

  if (options.defaults) {
    defaults = Flotr.merge(defaults, options.defaults);
  }

  defaults.price.data = data.price;
  defaults.volume.data = data.volume;
  defaults.summary.data = data.summary;

  defaults.price.flotr.mouse.trackFormatter = options.trackFormatter || function (o) {

    var
      index = o.index,
      value = 'Price: $' + data.price[1][index] + ", Vol: " + data.volume[1][index],
      day;

    return value;
  };
  if (options.xTickFormatter) {
    defaults.summary.flotr.xaxis.tickFormatter = options.xTickFormatter;
  }
  defaults.price.flotr.yaxis.tickFormatter = options.yTickFormatter || function (n) {
    return '$' + n;
  };

  price = new V.Child(defaults.price),
  volume = new V.Child(defaults.volume),
  connection = new V.Child(defaults.connection),
  summary = new V.Child(defaults.summary),

  // Render visualization
  vis
    .add(price)
    .add(volume)
    .add(connection)
    .add(summary)
    .render(options.container);

  // Define the selection zooming interaction
  selection
    .follower(price)
    .follower(volume)
    .follower(connection)
    .leader(summary)
    .add(V.action.selection, options.selectionCallback ? { callback : options.selectionCallback } : null);

  // Define the mouseover hit interaction
  hit
    .group([price, volume])
    .add(V.action.hit);

  // Optional initial selection
  if (options.selection) {
    summary.trigger(summary, 'select', options.selection);
  }

  // Members
  this.vis = vis;
  this.selection = selection;
  this.hit = hit;
  this.price = price;
  this.volume = volume;
  this.summary = summary;
}

V.templates.Finance = Finance;

})();
<commit_msg>Fix missing 0.<commit_after>(function () {

var
  V = envision;

// Custom data processor
function processData (options) {

  var
    resolution = options.resolution;

  options.preprocessor
    .bound(options.min, options.max)
    .subsampleMinMax(resolution + Math.round(resolution / 3));
}

function getDefaults () {
  return {
    price : {
      name : 'envision-finance-price',
      flotr : {
        'lite-lines' : {
          lineWidth : 1,
          show : true,
          fill : true,
          fillOpacity : 0.2
        },
        mouse : {
          track: true,
          trackY: false,
          trackAll: true,
          sensibility: 1,
          trackDecimals: 4,
          position: 'ne'
        },
        yaxis : {
          autoscale : true,
          autoscaleMargin : 0.05,
          noTicks : 4,
          showLabels : true,
          min : 0
        }
      },
      processData : processData
    },
    volume : {
      name : 'envision-finance-volume',
      flotr : {
        whiskers : {
          show : true,
          lineWidth : 2
        },
        mouse: {
          track: true,
          trackY: false,
          trackAll: true
        }
      },
      processData : processData
    },
    summary : {
      name : 'envision-finance-summary',
      flotr : {
        'lite-lines' : {
          show : true,
          lineWidth : 1,
          fill : true,
          fillOpacity : 0.2,
          fillBorder : true
        },
        xaxis : {
          noTicks: 5,
          showLabels : true
        },
        yaxis : {
          autoscale : true,
          autoscaleMargin : 0.1
        },
        handles : {
          show : true
        },
        selection : {
          mode : 'x'
        },
        grid : {
          verticalLines : false
        }
      }
    },
    connection : {
      name : 'envision-finance-connection',
      drawing : V.QuadraticDrawing
    }
  };
}

function Finance (options) {

  var
    data = options.data,
    defaults = getDefaults(),
    vis = new V.Visualization(),
    selection = new V.Interaction(),
    hit = new V.Interaction(),
    price, volume, connection, summary;

  if (options.defaults) {
    defaults = Flotr.merge(defaults, options.defaults);
  }

  defaults.price.data = data.price;
  defaults.volume.data = data.volume;
  defaults.summary.data = data.summary;

  defaults.price.flotr.mouse.trackFormatter = options.trackFormatter || function (o) {

    var
      index = o.index,
      value = 'Price: $' + data.price[1][index] + ", Vol: " + data.volume[1][index],
      day;

    return value;
  };
  if (options.xTickFormatter) {
    defaults.summary.flotr.xaxis.tickFormatter = options.xTickFormatter;
  }
  defaults.price.flotr.yaxis.tickFormatter = options.yTickFormatter || function (n) {
    return '$' + n;
  };

  price = new V.Child(defaults.price),
  volume = new V.Child(defaults.volume),
  connection = new V.Child(defaults.connection),
  summary = new V.Child(defaults.summary),

  // Render visualization
  vis
    .add(price)
    .add(volume)
    .add(connection)
    .add(summary)
    .render(options.container);

  // Define the selection zooming interaction
  selection
    .follower(price)
    .follower(volume)
    .follower(connection)
    .leader(summary)
    .add(V.action.selection, options.selectionCallback ? { callback : options.selectionCallback } : null);

  // Define the mouseover hit interaction
  hit
    .group([price, volume])
    .add(V.action.hit);

  // Optional initial selection
  if (options.selection) {
    summary.trigger(summary, 'select', options.selection);
  }

  // Members
  this.vis = vis;
  this.selection = selection;
  this.hit = hit;
  this.price = price;
  this.volume = volume;
  this.summary = summary;
}

V.templates.Finance = Finance;

})();
<|endoftext|>


<commit_before>function Utils() {

  var that = this;
  this.apiQueue = [];

  /* adapted from djangoproject.com */
  /* Static method */
  function getCookie(name) {
    var cookieValue;
    if(document.cookie){
      var cookies = document.cookie.split(';');
      for(var i=0;i<cookies.length;i++){
        var cookie = $.trim(cookies[i]);
        if(cookie.substring(0, name.length+1) == name + '='){
          return decodeURIComponent(cookie.substring(name.length+1));
        }
      }
    }
  }

  /* Static method to make single API requests */
  Utils.prototype.makeApiRequest = function(request) {

    //console.log("doing request",request);
    $.ajax({
      url: request.url,
      type: request.type,
      data: request.data,
      headers: {'X-CSRFToken':getCookie('csrftoken')},
      error: (function(error){
        return function(e){
          //$('.saving-info').text('Saving failed! Best option for now is to do a refresh.');
        }
      })(request.error),
      success: (function(success){
        return function(data){
          success(data);
          //console.log("request complete!",request);
        }
      })(request.success)
    });
  }

  /* Object method to add a request to the API queue */
  Utils.prototype.makeApiQueueRequest = function(request){

    this.apiQueue.push(request);

    /* adapted from djangoproject.com */
    function getCookie(name){
      var cookieValue;
      if(document.cookie){
        var cookies = document.cookie.split(';');
        for(var i=0;i<cookies.length;i++){
          var cookie = $.trim(cookies[i]);
          if(cookie.substring(0, name.length+1) == name + '='){
            return decodeURIComponent(cookie.substring(name.length+1));
          }
        }
      }
    }

    if(this.apiQueue.length == 1){
      (function doApiRequest(){
        if(that.apiQueue.length == 0){
          //$('.saving-info').removeClass('saving');
          return;
        }
        //$('.saving-info').addClass('saving');
        var request = that.apiQueue.pop(0); //popleft? legit!
        console.log("doing request",request);
        $.ajax({
          url: request.url,
          type: request.type,
          data: request.data,
          headers: {'X-CSRFToken':getCookie('csrftoken')},
          error: (function(error){
            return function(e){
              //$('.saving-info').text('Saving failed! Best option for now is to do a refresh.');
            }
          })(request.error),
          success: (function(success){
            return function(data){
              success(data);
              console.log("request complete!",request);
              setTimeout(doApiRequest,0);
            }
          })(request.success)
        });
      })();
    }
  };

  /* Method to add status messages which mimic django's own. */
  Utils.prototype.setStatusMessage = function(message, tags) {
    if ($('div.messages').length === 0) {
      var prnt = $('nav.subnavbar');
      if (prnt.length === 0) {
        prnt = $('nav.navbar');
      }
      $('

').insertAfter(prnt);
    }
    var inner = $('.messages .message-container');
    var id = new Date().getTime();
    $('
<button type="button" class="close" data-dismiss="alert">×</button>' + message + '
').appendTo(inner);

    timeOutAlerts()
  }

  /**
   * Render a template on the basis of the attributes of a data object
   * @param {object} tmpl A jQuery wrapper DOM object
   * @param {object} context An object containing the template payload
   * @return {object} Rendered DOM subtree containing provided context data
   */
  Utils.prototype.render = function (tmpl, context) {
    var node = window._.template(tmpl)
    return node(context)
  }
}

// Inject String format method if not defined
if (!String.prototype.format) {
  String.prototype.format = function () {
    var args = arguments
    return this.replace(/{(\d+)}/g, function (match, number) {
      return typeof args[number] !== 'undefined' ? args[number] : match
    })
  }
}

export default Utils;
<commit_msg>eslint Utils and remove one unused function<commit_after>import $ from 'jquery';

function Utils() {
  /* adapted from djangoproject.com */
  /* Static method */
  function getCookie(name) {
    if (document.cookie) {
      const cookies = document.cookie.split(';');
      for (let i = 0; i < cookies.length; i += 1) {
        const cookie = $.trim(cookies[i]);
        if (cookie.substring(0, name.length + 1) === `${name}=`) {
          return decodeURIComponent(cookie.substring(name.length + 1));
        }
      }
    }
    return null;
  }

  /* Static method to make single API requests */
  Utils.prototype.makeApiRequest = (request) => {
    $.ajax({
      url: request.url,
      type: request.type,
      data: request.data,
      headers: { 'X-CSRFToken': getCookie('csrftoken') },
      error: request.error,
      success: request.success,
    });
  };

  /* Method to add status messages which mimic django's own. */
  Utils.prototype.setStatusMessage = (message, tags) => {
    if ($('div.messages').length === 0) {
      let prnt = $('nav.subnavbar');
      if (prnt.length === 0) {
        prnt = $('nav.navbar');
      }
      $('

').insertAfter(prnt);
    }
    const inner = $('.messages .message-container');
    const id = new Date().getTime();
    $(`<div class="alert ${tags}" id="${id}"><button type="button" class="close" data-dismiss="alert">×</button>${message}</div>`).appendTo(inner);

    timeOutAlerts();
  };

  /**
   * Render a template on the basis of the attributes of a data object
   * @param {object} tmpl A jQuery wrapper DOM object
   * @param {object} context An object containing the template payload
   * @return {object} Rendered DOM subtree containing provided context data
   */
  Utils.prototype.render = (tmpl, context) => {
    const node = window._.template(tmpl);
    return node(context);
  };
}

// Inject String format method if not defined
if (!String.prototype.format) {
  String.prototype.format = function () {
    const args = arguments;
    return this.replace(/{(\d+)}/g, (match, number) => typeof args[number] !== 'undefined' ? args[number] : match);
  };
}

export default Utils;
<|endoftext|>


<commit_before>function gmailCheckerLite() {
    // private vars
    var options;
    var xhr;
    var soundNotification;

    // main options & configuration
    this.options = {
        gmail_url: 'https://gmail.com',
        gmail_atom_feed: 'https://mail.google.com/mail/feed/atom',
        check_cycle: (1000 * localStorage.gml_seconds),
        sound_notification: localStorage.gml_sound_notification ? true : false,
        sound_notification_filepath: '../sounds/'+localStorage.gml_sound_notification,
        icon_click_action: localStorage.gml_icon_click_action,
    };

    // method that takes care of the initialization of the class
    this.setup = function() {
        self = this;

        xhr = new XMLHttpRequest();
        options = self.options;

        if (options.sound_notification) {
            localStorage.gml_email_count = 0;
            soundNotification = new Audio(options.sound_notification_filepath);
        }

        self.check();
        setInterval(function(){ self.check(); }, options.check_cycle);

        chrome.browserAction.onClicked.addListener(function (tab) {
            switch(options.icon_click_action) {
                default:
                case 'primary':
                    url_match = 'mail.google.com/mail/u/0';
                    break;
                case 'first':
                    url_match = 'mail.google.com';
                    break;
            }

            chrome.tabs.getAllInWindow(undefined, function(tabs) {
                for (var i = 0, tab; tab = tabs[i]; i++) {
                    if (tab.url.indexOf(url_match) > -1) {
                        chrome.tabs.update(tab.id, {selected: true});
                        return true;
                    }
                }

                chrome.tabs.create({
                    url: gmail.options.gmail_url
                });
            });
        });

        return true;
    };

    // method to check the actual gmail unread messages count
    this.check = function() {
        if (!xhr)
            return false;

        xhr.open("GET", options.gmail_atom_feed, true);
        xhr.onreadystatechange = function() {
            if (xhr.status == 200) {
                var xml = xhr.responseXML;
                if (xml) {
                    var count = xml.getElementsByTagName('fullcount')[0].textContent || 0;

                    if (count > 0) {
                        chrome.browserAction.setBadgeText({text: count});
                        chrome.browserAction.setBadgeBackgroundColor({color: '#ff0000'});

                        if (count > localStorage.gml_email_count && options.sound_notification) {
                            soundNotification.play();
                        }
                    }
                    else {
                        chrome.browserAction.setBadgeText({text: ''});
                    }

                    localStorage.gml_email_count = count;
                }
                else {
                    chrome.browserAction.setBadgeText({text: '--'});
                    chrome.browserAction.setBadgeBackgroundColor({color: '#f3f3f3'});
                }
            }
            else {
                chrome.browserAction.setBadgeText({text: '--'});
                chrome.browserAction.setBadgeBackgroundColor({color: '#f3f3f3'});
            }
        }
        xhr.send();

        return true;
    };

    return true;
}

// go, go, go!
gmail = new gmailCheckerLite();
gmail.setup();
<commit_msg>enhancements: always unread-check the primary account<commit_after>function gmailCheckerLite() {
    // private vars
    var options;
    var xhr;
    var soundNotification;

    // main options & configuration
    this.options = {
        gmail_url: 'https://mail.google.com',
        gmail_atom_feed: 'https://mail.google.com/mail/u/0/feed/atom',
        check_cycle: (1000 * localStorage.gml_seconds),
        sound_notification: localStorage.gml_sound_notification ? true : false,
        sound_notification_filepath: '../sounds/'+localStorage.gml_sound_notification,
        icon_click_action: localStorage.gml_icon_click_action,
    };

    // method that takes care of the initialization of the class
    this.setup = function() {
        self = this;

        xhr = new XMLHttpRequest();
        options = self.options;

        if (options.sound_notification) {
            localStorage.gml_email_count = 0;
            soundNotification = new Audio(options.sound_notification_filepath);
        }

        self.check();
        setInterval(function(){ self.check(); }, options.check_cycle);

        chrome.browserAction.onClicked.addListener(function (tab) {
            switch(options.icon_click_action) {
                default:
                case 'primary':
                    url_match = options.gmail_url+'/mail/u/0';
                    break;
                case 'first':
                    url_match = options.gmail_url;
                    break;
            }

            chrome.tabs.getAllInWindow(undefined, function(tabs) {
                for (var i = 0, tab; tab = tabs[i]; i++) {
                    if (tab.url.indexOf(url_match) > -1) {
                        chrome.tabs.update(tab.id, {selected: true});
                        return true;
                    }
                }

                chrome.tabs.create({
                    url: options.gmail_url
                });
            });
        });

        return true;
    };

    // method to check the actual gmail unread messages count
    this.check = function() {
        if (!xhr)
            return false;

        xhr.open("GET", options.gmail_atom_feed, true);
        xhr.onreadystatechange = function() {
            if (xhr.status == 200) {
                var xml = xhr.responseXML;
                if (xml) {
                    var count = xml.getElementsByTagName('fullcount')[0].textContent || 0;

                    if (count > 0) {
                        chrome.browserAction.setBadgeText({text: count});
                        chrome.browserAction.setBadgeBackgroundColor({color: '#ff0000'});

                        if (count > localStorage.gml_email_count && options.sound_notification) {
                            soundNotification.play();
                        }
                    }
                    else {
                        chrome.browserAction.setBadgeText({text: ''});
                    }

                    localStorage.gml_email_count = count;
                }
                else {
                    chrome.browserAction.setBadgeText({text: '--'});
                    chrome.browserAction.setBadgeBackgroundColor({color: '#f3f3f3'});
                }
            }
            else {
                chrome.browserAction.setBadgeText({text: '--'});
                chrome.browserAction.setBadgeBackgroundColor({color: '#f3f3f3'});
            }
        }
        xhr.send();

        return true;
    };

    return true;
}

// go, go, go!
gmail = new gmailCheckerLite();
gmail.setup();
<|endoftext|>


<commit_before>//  Copyright 2002-2014, University of Colorado Boulder

/**
 * Singleton method for use with Chrome profiling tools to automatically report garbage collection periods.
 * Must be run with chrome --enable-memory-info and hence only works in Google chrome.
 * Call this method each model.step to track garbage collections.
 *
 * @author Sam Reid
 */
define( function( require ) {
  'use strict';

  var lastUsedJSHeapSize = -1;
  var gcTimes = [];

  var average = function( array ) {
    var sum = 0;
    for ( var i = 0; i < array.length; i++ ) {
      sum += array[i];
    }
    return sum / array.length;
  };

  return function() {

    //Run with chrome --enable-memory-info
    if ( window.performance ) {
      var newHeapSize = window.performance.memory.usedJSHeapSize;

      if ( newHeapSize < lastUsedJSHeapSize ) {
        gcTimes.push( Date.now() );
        var deltas = [];
        for ( var i = 0; i < 3 && i < gcTimes.length - 1; i++ ) {
          deltas.push( gcTimes[gcTimes.length - 1 - i] - gcTimes[gcTimes.length - 1 - i - 1] );
        }
        if ( deltas.length > 0 ) {
          console.log( 'GC: average period (ms) over last ', deltas.length, ' collections:', average( deltas ), ', values: ', deltas );
        }
      }

      lastUsedJSHeapSize = newHeapSize;
    }

  };
} );
<commit_msg>Fixed window.performance.memory reference on firefox<commit_after>//  Copyright 2002-2014, University of Colorado Boulder

/**
 * Singleton method for use with Chrome profiling tools to automatically report garbage collection periods.
 * Must be run with chrome --enable-memory-info and hence only works in Google chrome.
 * Call this method each model.step to track garbage collections.
 *
 * @author Sam Reid
 */
define( function( require ) {
  'use strict';

  var lastUsedJSHeapSize = -1;
  var gcTimes = [];

  var average = function( array ) {
    var sum = 0;
    for ( var i = 0; i < array.length; i++ ) {
      sum += array[i];
    }
    return sum / array.length;
  };

  return function() {

    //Run with chrome --enable-memory-info
    if ( window.performance && window.performance.memory ) {
      var newHeapSize = window.performance.memory.usedJSHeapSize;

      if ( newHeapSize < lastUsedJSHeapSize ) {
        gcTimes.push( Date.now() );
        var deltas = [];
        for ( var i = 0; i < 3 && i < gcTimes.length - 1; i++ ) {
          deltas.push( gcTimes[gcTimes.length - 1 - i] - gcTimes[gcTimes.length - 1 - i - 1] );
        }
        if ( deltas.length > 0 ) {
          console.log( 'GC: average period (ms) over last ', deltas.length, ' collections:', average( deltas ), ', values: ', deltas );
        }
      }

      lastUsedJSHeapSize = newHeapSize;
    }

  };
} );
<|endoftext|>


<commit_before>function Background()
{
}

Background.prototype.get_text = function(callback) {
    var out = new Array();
    chrome.tabs.query({}, function(tabs) {
        tabs.forEach(function(e, i ,a) {
            // ignoring internal urls
            if (tabs[i].url.indexOf("chrome") == 0) return;
            chrome.tabs.sendMessage(tabs[i].id, {action: "get_text"}, function(response) {
                out.push({text: response.text, url: tabs[i].url, title: response.title});
            });
        });
        callback(out);
    });
}

var background = new Background();
<commit_msg>cleanup and callback<commit_after>function Background()
{
}

Background.prototype.get_text = function(callback) {
    var out = new Array();
    chrome.tabs.query({}, function(tabs) {
        var t = new Array();

        tabs.forEach(function(e, i, a){
            // ignoring internal urls
            if (tabs[i].url.indexOf("chrome") == 0) return;
            t.push(e);
        });

        t.forEach(function(e, i ,a) {
            chrome.tabs.sendMessage(tabs[i].id, {action: "get_text"}, function(response) {
                out.push({text: response.text, url: tabs[i].url, title: response.title});

                if (t.length == i+1)
                    return callback(out);
            });
        });
    });
}

var background = new Background();
<|endoftext|>


<commit_before><script type="text/javascript">
	$(document).ready(function () {
	    $("#register").validate({
		rules: {
			name: {
				lettersonly: true
			},
			surname: {
				lettersonly: true
			}
		}
	    });
	});
</script>
<commit_msg>fix dumb js<commit_after>$(document).ready(function () {
    $("#register").validate({
	rules: {
		name: {
			lettersonly: true
		},
		surname: {
			lettersonly: true
		}
	}
    });
});
<|endoftext|>


<commit_before>google.load("language", "1");
function contextMenusOnClick(info,tab,opt) {
	$.ajax({
		type:'POST',
		url : 'https://ajax.googleapis.com/ajax/services/language/translate',
		dataType : 'json',
		data : {
			q : info.selectionText,
			v : '1.0',
			langpair : opt
		},
		success : function(data){
			if(data.responseStatus == 200) {
				T = data.responseData.translatedText;
			} else {
				T = 'ERROR: '+data.responseDetails;
			}
			chrome.tabs.getSelected(null, function(tab) { // get selected string in current tab
				chrome.tabs.executeScript(tab.id,{file:'js/content.js',allFrames:true},function() {injCallBack(T)});
			});
		},
		error : function (xhr, status, error){
			T = 'Unexpeceted error occurred!';
			alert(T)
		}
	});
}

var injCallBack = function(S){
	chrome.tabs.getSelected(null, function(tab) { // get selected string in current tab
		chrome.tabs.sendRequest(tab.id,{'method':'getContextMenus','string':S}, getRequestResponseCallback)
	});
}
var getRequestResponseCallback = function getRequestResponseCallback(response) {
	console.log('response: %o',response);
};

function createcontextMenusOption(opt){
	var optString = '';
	var L = JSONSwitch(LANGUAGES);
	optString += opt.split('|')[0] ? L[opt.split('|')[0]] : t('detectLanguage');
	optString += '  ';
	optString += opt.split('|')[1] ? L[opt.split('|')[1]] : t('detectLanguage');
	chrome.contextMenus.create({
		"title": optString,
		"contexts":['selection'],
		"onclick": function(opt){
			return function(info,tab) {
				contextMenusOnClick(info,tab,opt)
			}
		}(opt)
	});
}

function start() {
	var preferred = JSON.parse(localStorage.getItem('preferred'));
	chrome.contextMenus.removeAll();
	for (var i = 0, max = preferred.length; i < max; i++) {
		createcontextMenusOption(preferred[i]);
	}
	chrome.contextMenus.create({
		"title": t('settings'),
		"contexts":['selection'],
		"onclick": function(){
			window.open('options.html');
		}
	});
}

google.setOnLoadCallback(function(){
	LANGUAGES = google.language.Languages;
	start();
});<commit_msg>Changed page encoding<commit_after>google.load("language", "1");
function contextMenusOnClick(info,tab,opt) {
	$.ajax({
		type:'POST',
		url : 'https://ajax.googleapis.com/ajax/services/language/translate',
		dataType : 'json',
		data : {
			q : info.selectionText,
			v : '1.0',
			langpair : opt
		},
		success : function(data){
			if(data.responseStatus == 200) {
				T = data.responseData.translatedText;
			} else {
				T = 'ERROR: '+data.responseDetails;
			}
			chrome.tabs.getSelected(null, function(tab) { // get selected string in current tab
				chrome.tabs.executeScript(tab.id,{file:'js/content.js',allFrames:true},function() {injCallBack(T)});
			});
		},
		error : function (xhr, status, error){
			T = 'Unexpeceted error occurred!';
			alert(T)
		}
	});
}

var injCallBack = function(S){
	chrome.tabs.getSelected(null, function(tab) { // get selected string in current tab
		chrome.tabs.sendRequest(tab.id,{'method':'getContextMenus','string':S}, getRequestResponseCallback)
	});
}
var getRequestResponseCallback = function getRequestResponseCallback(response) {
	console.log('response: %o',response);
};

function createcontextMenusOption(opt){
	var optString = '';
	var L = JSONSwitch(LANGUAGES);
	optString += opt.split('|')[0] ? L[opt.split('|')[0]] : t('detectLanguage');
	optString += ' » ';
	optString += opt.split('|')[1] ? L[opt.split('|')[1]] : t('detectLanguage');
	chrome.contextMenus.create({
		"title": optString,
		"contexts":['selection'],
		"onclick": function(opt){
			return function(info,tab) {
				contextMenusOnClick(info,tab,opt)
			}
		}(opt)
	});
}

function start() {
	var preferred = JSON.parse(localStorage.getItem('preferred'));
	chrome.contextMenus.removeAll();
	for (var i = 0, max = preferred.length; i < max; i++) {
		createcontextMenusOption(preferred[i]);
	}
	chrome.contextMenus.create({
		"title": t('settings'),
		"contexts":['selection'],
		"onclick": function(){
			window.open('options.html');
		}
	});
}

google.setOnLoadCallback(function(){
	LANGUAGES = google.language.Languages;
	start();
});<|endoftext|>