<commit_before>import 'es6-symbol/implement';
import {Provider} from 'react-redux';
import store from './src/redux/store';
import AppViewContainer from './src/modules/AppViewContainer';
import React from 'react';
import {AppRegistry, BackAndroid} from 'react-native';
import * as NavigationStateActions from './src/modules/navigation/NavigationState';

const PepperoniAppTemplate = React.createClass({

  componentWillMount() {
    BackAndroid.addEventListener('hardwareBackPress', this.navigateBack);
  },

  navigateBack() {
    const navigationState = store.getState().get('navigationState');
    const tabs = navigationState.get('tabs');
    const tabKey = tabs.getIn(['routes', tabs.get('index')]).get('key');
    const currentTab = navigationState.get(tabKey);

    // if we are in the beginning of our tab stack
    if (currentTab.get('index') === 0) {

      // if we are not in the first tab, switch tab to the leftmost one
      if (navigationState.get('index') !== 0) {
        store.dispatch(NavigationStateActions.switchTab(0));
        return true;
      }

      // otherwise let OS handle the back button action
      return false;
    }

    store.dispatch(NavigationStateActions.popRoute());
    return true;
  },

  render() {
    return (
      <Provider store={store}>
        <AppViewContainer />
      </Provider>
    );
  }
});

AppRegistry.registerComponent('PepperoniAppTemplate', () => PepperoniAppTemplate);
<commit_msg>allow Android back button to close the app when tapped on the homepage (#158)<commit_after>import 'es6-symbol/implement';
import {Provider} from 'react-redux';
import store from './src/redux/store';
import AppViewContainer from './src/modules/AppViewContainer';
import React from 'react';
import {AppRegistry, BackAndroid} from 'react-native';
import * as NavigationStateActions from './src/modules/navigation/NavigationState';

const PepperoniAppTemplate = React.createClass({

  componentWillMount() {
    BackAndroid.addEventListener('hardwareBackPress', this.navigateBack);
  },

  navigateBack() {
    const navigationState = store.getState().get('navigationState');
    const tabs = navigationState.get('tabs');
    const tabKey = tabs.getIn(['routes', tabs.get('index')]).get('key');
    const currentTab = navigationState.get(tabKey);

    // if we are in the beginning of our tab stack
    if (currentTab.get('index') === 0) {

      // if we are not in the first tab, switch tab to the leftmost one
      if (tabs.get('index') !== 0) {
        store.dispatch(NavigationStateActions.switchTab(0));
        return true;
      }

      // otherwise let OS handle the back button action
      return false;
    }

    store.dispatch(NavigationStateActions.popRoute());
    return true;
  },

  render() {
    return (
      <Provider store={store}>
        <AppViewContainer />
      </Provider>
    );
  }
});

AppRegistry.registerComponent('PepperoniAppTemplate', () => PepperoniAppTemplate);
<|endoftext|>


<commit_before>/**
 * Module Description
 *
 * Version    Date               Author                    Remarks
 * 1.00       17 Nov 2013     mohanboopalan
 *
 */

/**
 * The recordType (internal id) corresponds to the "Applied To" record in your script deployment.
 * @appliedtorecord recordType
 *
 * @param {String} type Operation types: create, edit, delete, xedit,
 *                      approve, cancel, reject (SO, ER, Time Bill, PO & RMA only)
 *                      pack, ship (IF only)
 *                      dropship, specialorder, orderitems (PO only)
 *                      paybills (vendor payments)
 * @returns {Void}
 */
function userEventAfterSubmit(type){

var IsInclCustomField = true;
var IsCallSchedule = true;

 if ( type == 'create')
  {
     var currentid = nlapiGetRecordId();
     var currentType = nlapiGetRecordType();
     var currentrecord = nlapiGetNewRecord();

     if (currentType == 'account' || currentType == 'department' || currentType == 'classification' || currentType == 'location' || currentType == 'subsidiary')
      {

               if (IsInclCustomField) {
                  if (currentrecord.getFieldValue(GetInclCustomField(currentType)) == 'T' )
                  { IsCallSchedule = true;} else {IsCallSchedule = false;}
                }

              if (IsCallSchedule)
               {
               var params = new Array();
               params['custscript_acctsint_userrectype'] = GetSegmentId(currentType);
               params['custscript_acctsint_userrectypeid'] = currentid;
               params['custscript_acctsint_optype'] = 'create';
              var results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched', params);

                    if ( results != 'QUEUED' )
         {
results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched1', params);
                    if ( results != 'QUEUED' )
            {
results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched2', params);
                    if ( results != 'QUEUED' )
                {
results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched3', params);
                    if ( results != 'QUEUED' )
                    {
results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched4', params);

                        if (results != 'QUEUED')
                         {
	                  nlapiLogExecution('ERROR','Process Error',  'Will not be able to trigger event due to max simultaneous call');
                         }
                     }
                }
           }
       }

               }
        }
  }
  if ( type == 'edit')
  {

     var currentType = nlapiGetRecordType();
      var newrecord = nlapiGetNewRecord();
      var oldrecord = nlapiGetOldRecord();
      var inclopttype = '';
      var IsCallSchedule = true;

     if (currentType == 'account' || currentType == 'department' || currentType == 'classification' || currentType == 'location' || currentType == 'subsidiary')
      {

                  if (IsInclCustomField) {
                  if ((oldrecord.getFieldValue(GetInclCustomField(currentType)) == 'T' ) &&
                     (newrecord.getFieldValue(GetInclCustomField(currentType)) == 'F' ))
                     { inclopttype = 'edit-false';}
                  if ((oldrecord.getFieldValue(GetInclCustomField(currentType)) == 'F' ) &&
                     (newrecord.getFieldValue(GetInclCustomField(currentType)) == 'T' ))
                     { inclopttype = 'edit-true';}
                  if ((oldrecord.getFieldValue(GetInclCustomField(currentType)) == 'F' ) &&
                     (newrecord.getFieldValue(GetInclCustomField(currentType)) == 'F' ))
                     { IsCallSchedule = false;}
                 }

               var params = new Array();
               params['custscript_acctsint_userrectype'] =  GetSegmentId(currentType);
               params['custscript_acctsint_userrectypeid'] = newrecord.getId();

               if (( newrecord.getFieldValue('isinactive') != 'T' && oldrecord.getFieldValue('isinactive') == 'T' ) ||
                   ( newrecord.getFieldValue('isinactive') == 'F' && oldrecord.getFieldValue('isinactive') != 'F' ) &&
                   (IsCallSchedule))
                  {

                      if  (inclopttype != '')
                      {
                       params['custscript_acctsint_optype'] = inclopttype;

                       }
                       else
                       {
                       params['custscript_acctsint_optype'] = 'edit-true';
                       }

                    var results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched', params);
                    if ( results != 'QUEUED' )
         {
results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched1', params);
                    if ( results != 'QUEUED' )
            {
results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched2', params);
                    if ( results != 'QUEUED' )
                {
results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched3', params);
                    if ( results != 'QUEUED' )
                    {
results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched4', params);

                        if (results != 'QUEUED')
                         {
	                  nlapiLogExecution('ERROR','Process Error',  'Will not be able to trigger event due to max simultaneous call');
                         }
                     }
                }
           }
       }
                    //nlapiLogExecution('AUDIT','Queued',results);

                      //if ( newrecord.getFieldValue('parent') != '')
                       //{
                       //     var filters = new Array();
                       //    filters[0] = new nlobjSearchFilter('isinactive',null,'is','F');
                       //    filters[1] = new nlobjSearchFilter('internalid',null,'is',newrecord.getFieldValue('parent'));
                       //   var searchresults = nlapiSearchRecord(currentType,null,filters,null);

                       //              for ( var i = 0;  i < searchresults.length; i++)
                       //              {
                       //      params['custscript_acctsint_userrectypeid'] = newrecord.getFieldValue('parent');
                       //var results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched', params);
                    //nlapiLogExecution('AUDIT','Queued',results);

                       //               }
                        //}

                }
              if (( newrecord.getFieldValue('isinactive') != 'F' && oldrecord.getFieldValue('isinactive') == 'F' ) || ( newrecord.getFieldValue('isinactive') == 'T' && oldrecord.getFieldValue('isinactive') != 'T' ) && (IsCallSchedule))
              {
                       if  (inclopttype != '')
                      {
                       params['custscript_acctsint_optype'] = inclopttype;
                       }
                       else
                       {
                       params['custscript_acctsint_optype'] = 'edit-false';
                       }

                        //var results;
                        //do
                       //{

                    var results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched', params);
                    if ( results != 'QUEUED' )
         {
results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched1', params);
                    if ( results != 'QUEUED' )
            {
results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched2', params);
                    if ( results != 'QUEUED' )
                {
results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched3', params);
                    if ( results != 'QUEUED' )
                    {
results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched4', params);

                        if (results != 'QUEUED')
                         {
	                  nlapiLogExecution('ERROR','Process Error',  'Will not be able to trigger event due to max simultaneous call');
                         }
                     }
                }
           }
       }

                    nlapiLogExecution('AUDIT','Queued',results);

                       //} while (results != 'QUEUED')

                       //if ( newrecord.getFieldValue('parent') == '')
                       //{
                       //     var filters = new Array();
                       //    filters[0] = new nlobjSearchFilter('isinactive',null,'is','F');

                      //    var searchresults = nlapiSearchRecord(currentType,null,filters,null);

                         //          for ( var i = 0;  i < searchresults.length; i++)
                            //         {
                               //             if ( newrecord.getId() != searchresults[i].getId() && searchresults[i].getId() != '')
                               //                {
                                //           params['custscript_acctsint_userrectypeid'] = searchresults[i].getId();
// as of now, no way to track down the sub department using parent department
//                      var results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched', params);
                                   //                nlapiLogExecution('AUDIT','Queued',results);
                                   //            }

                                   //  }
                       //}

               }

     }
  }
  if ( type == 'delete')
  {
     var currentid = nlapiGetRecordId();
     var currentType = nlapiGetRecordType();
      var oldrecord = nlapiGetOldRecord();

     if (currentType == 'account' || currentType == 'department' || currentType == 'classification' || currentType == 'location' || currentType == 'subsidiary')
      {
                   //call Delete

               var params = new Array();
               params['custscript_acctsint_userrectype'] =  GetSegmentId(currentType);
               params['custscript_acctsint_userrectypeid'] = currentid;

               if ( currentType == 'account')
               {
                         params['custscript_acctsint_deletedsegmentname'] = oldrecord.getFieldValue('acctnumber') + ':' + oldrecord.getFieldValue('acctname');
                }
               if ( currentType == 'department')
               {
                         params['custscript_acctsint_deletedsegmentname'] = oldrecord.getFieldValue('name') + ':' + oldrecord.getId();
                }
               if ( currentType == 'classification' )
               {
                         params['custscript_acctsint_deletedsegmentname'] =  oldrecord.getFieldValue('name') + ':' + oldrecord.getId();
                }
               if ( currentType == 'location')
               {
                         params['custscript_acctsint_deletedsegmentname'] =  oldrecord.getFieldValue('namenohierarchy') + ':' + oldrecord.getId();
                }
               if ( currentType == 'subsidiary')
               {
                         params['custscript_acctsint_deletedsegmentname'] =  oldrecord.getFieldValue('namenohierarchy') + ':' + oldrecord.getId();
                }

               params['custscript_create_optype'] = 'delete';
              var results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched', params);
                    if ( results != 'QUEUED' )
         {
results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched1', params);
                    if ( results != 'QUEUED' )
            {
results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched2', params);
                    if ( results != 'QUEUED' )
                {
results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched3', params);
                    if ( results != 'QUEUED' )
                    {
results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched4', params);

                        if (results != 'QUEUED')
                         {
	                  nlapiLogExecution('ERROR','Process Error',  'Will not be able to trigger event due to max simultaneous call');
                         }
                     }
                }
           }
       }

     }
  }

}

function GetSegmentId(paramvalue)
{
      if (paramvalue == 'account') { return '1' };
      if (paramvalue == 'department') { return '2' };
      if (paramvalue == 'classification' ) { return '3' };
      if (paramvalue == 'subsidiary') { return '4' };
      if (paramvalue == 'location') { return '5' };

}
function GetInclCustomField(paramvalue)
{
      if (paramvalue == 'account') { return 'custrecord_acctincludeincoupa' };
      if (paramvalue == 'department') { return 'custrecord_deptincludeincoupa' };
      if (paramvalue == 'classification' ) { return '3' };
      if (paramvalue == 'subsidiary') { return 'custrecord_subincludeincoupa' };
      if (paramvalue == 'location') { return '5' };

}<commit_msg>commit latest changes to Accts Integration<commit_after>/**
 * Module Description
 *
 * Version    Date               Author                    Remarks
 * 1.00       17 Nov 2013     mohanboopalan
 * 1.10       01 Feb 2014     mohanboopalan                Logic to include customfield or not
 */

/**
 * The recordType (internal id) corresponds to the "Applied To" record in your script deployment.
 * @appliedtorecord recordType
 *
 * @param {String} type Operation types: create, edit, delete, xedit,
 *                      approve, cancel, reject (SO, ER, Time Bill, PO & RMA only)
 *                      pack, ship (IF only)
 *                      dropship, specialorder, orderitems (PO only)
 *                      paybills (vendor payments)
 * @returns {Void}
 */
function userEventAfterSubmit(type){

if (nlapiGetContext().getSetting('SCRIPT' , 'custscript_acctsint_isinclCustomField') == 'T' )
 {
     var IsInclCustomField = true;
 }
 else
 {
     var IsInclCustomField = false;
 }

var IsCallSchedule = true;

 if ( type == 'create')
  {
     var currentid = nlapiGetRecordId();
     var currentType = nlapiGetRecordType();
     var currentrecord = nlapiGetNewRecord();

     if (currentType == 'account' || currentType == 'department' || currentType == 'classification' || currentType == 'location' || currentType == 'subsidiary')
      {

               if (IsInclCustomField) {
                  if (currentrecord.getFieldValue(GetInclCustomField(currentType)) == 'T' )
                  { IsCallSchedule = true;} else {IsCallSchedule = false;}
                }

              if (IsCallSchedule)
               {
               var params = new Array();
               params['custscript_acctsint_userrectype'] = GetSegmentId(currentType);
               params['custscript_acctsint_userrectypeid'] = currentid;
               params['custscript_acctsint_optype'] = 'create';
              var results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched', params);

                    if ( results != 'QUEUED' )
         {
results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched1', params);
                    if ( results != 'QUEUED' )
            {
results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched2', params);
                    if ( results != 'QUEUED' )
                {
results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched3', params);
                    if ( results != 'QUEUED' )
                    {
results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched4', params);

                        if (results != 'QUEUED')
                         {
	                  nlapiLogExecution('ERROR','Process Error',  'Will not be able to trigger event due to max simultaneous call');
                         }
                     }
                }
           }
       }

               }
        }
  }
  if ( type == 'edit')
  {

     var currentType = nlapiGetRecordType();
      var newrecord = nlapiGetNewRecord();
      var oldrecord = nlapiGetOldRecord();
      var inclopttype = '';
      var IsCallSchedule = true;

     if (currentType == 'account' || currentType == 'department' || currentType == 'classification' || currentType == 'location' || currentType == 'subsidiary')
      {

                  if (IsInclCustomField) {

                  if ((oldrecord.getFieldValue(GetInclCustomField(currentType)) == 'T' ) &&
                     (newrecord.getFieldValue(GetInclCustomField(currentType)) == 'F' ))
                     { inclopttype = 'edit-false';}

                  if ((oldrecord.getFieldValue(GetInclCustomField(currentType)) == 'F' ) &&
                     (newrecord.getFieldValue(GetInclCustomField(currentType)) == 'T' ))
                     { inclopttype = 'edit-true';}

                  if ((oldrecord.getFieldValue(GetInclCustomField(currentType)) == 'F' ) &&
                     (newrecord.getFieldValue(GetInclCustomField(currentType)) == 'F' ))
                     { IsCallSchedule = false;}

                 }

               var params = new Array();
               params['custscript_acctsint_userrectype'] =  GetSegmentId(currentType);
               params['custscript_acctsint_userrectypeid'] = newrecord.getId();

               if (( newrecord.getFieldValue('isinactive') != 'T' && oldrecord.getFieldValue('isinactive') == 'T' ) ||
                   ( newrecord.getFieldValue('isinactive') == 'F' && oldrecord.getFieldValue('isinactive') != 'F' ) &&
                   (IsCallSchedule))
                  {
                      if  (inclopttype != '')
                      {
                       params['custscript_acctsint_optype'] = inclopttype;

                       }
                       else
                       {
                       params['custscript_acctsint_optype'] = 'edit-true';
                       }

                    var results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched', params);
                    if ( results != 'QUEUED' )
         {
results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched1', params);
                    if ( results != 'QUEUED' )
            {
results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched2', params);
                    if ( results != 'QUEUED' )
                {
results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched3', params);
                    if ( results != 'QUEUED' )
                    {
results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched4', params);

                        if (results != 'QUEUED')
                         {
	                  nlapiLogExecution('ERROR','Process Error',  'Will not be able to trigger event due to max simultaneous call');
                         }
                     }
                }
           }
       }
                    //nlapiLogExecution('AUDIT','Queued',results);

                      //if ( newrecord.getFieldValue('parent') != '')
                       //{
                       //     var filters = new Array();
                       //    filters[0] = new nlobjSearchFilter('isinactive',null,'is','F');
                       //    filters[1] = new nlobjSearchFilter('internalid',null,'is',newrecord.getFieldValue('parent'));
                       //   var searchresults = nlapiSearchRecord(currentType,null,filters,null);

                       //              for ( var i = 0;  i < searchresults.length; i++)
                       //              {
                       //      params['custscript_acctsint_userrectypeid'] = newrecord.getFieldValue('parent');
                       //var results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched', params);
                    //nlapiLogExecution('AUDIT','Queued',results);

                       //               }
                        //}

                }
              if ( newrecord.getFieldValue('isinactive') == 'T' && oldrecord.getFieldValue('isinactive') != 'T'  && (IsCallSchedule))
              {

                       if  (inclopttype != '')
                      {
                       params['custscript_acctsint_optype'] = inclopttype;
                       }
                       else
                       {
                       params['custscript_acctsint_optype'] = 'edit-false';
                       }

                        //var results;
                        //do
                       //{

                    var results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched', params);
                    if ( results != 'QUEUED' )
         {
results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched1', params);
                    if ( results != 'QUEUED' )
            {
results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched2', params);
                    if ( results != 'QUEUED' )
                {
results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched3', params);
                    if ( results != 'QUEUED' )
                    {
results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched4', params);

                        if (results != 'QUEUED')
                         {
	                  nlapiLogExecution('ERROR','Process Error',  'Will not be able to trigger event due to max simultaneous call');
                         }
                     }
                }
           }
       }

                    nlapiLogExecution('AUDIT','Queued',results);

                       //} while (results != 'QUEUED')

                       //if ( newrecord.getFieldValue('parent') == '')
                       //{
                       //     var filters = new Array();
                       //    filters[0] = new nlobjSearchFilter('isinactive',null,'is','F');

                      //    var searchresults = nlapiSearchRecord(currentType,null,filters,null);

                         //          for ( var i = 0;  i < searchresults.length; i++)
                            //         {
                               //             if ( newrecord.getId() != searchresults[i].getId() && searchresults[i].getId() != '')
                               //                {
                                //           params['custscript_acctsint_userrectypeid'] = searchresults[i].getId();
// as of now, no way to track down the sub department using parent department
//                      var results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched', params);
                                   //                nlapiLogExecution('AUDIT','Queued',results);
                                   //            }

                                   //  }
                       //}

               }

     }
  }
  if ( type == 'delete')
  {
     var currentid = nlapiGetRecordId();
     var currentType = nlapiGetRecordType();
      var oldrecord = nlapiGetOldRecord();

     if (currentType == 'account' || currentType == 'department' || currentType == 'classification' || currentType == 'location' || currentType == 'subsidiary')
      {
                   //call Delete

               var params = new Array();
               params['custscript_acctsint_userrectype'] =  GetSegmentId(currentType);
               params['custscript_acctsint_userrectypeid'] = currentid;

               if ( currentType == 'account')
               {
                         params['custscript_acctsint_deletedsegmentname'] = oldrecord.getFieldValue('acctnumber') + ':' + oldrecord.getFieldValue('acctname');
                }
               if ( currentType == 'department')
               {
                         params['custscript_acctsint_deletedsegmentname'] = oldrecord.getFieldValue('name') + ':' + oldrecord.getId();
                }
               if ( currentType == 'classification' )
               {
                         params['custscript_acctsint_deletedsegmentname'] =  oldrecord.getFieldValue('name') + ':' + oldrecord.getId();
                }
               if ( currentType == 'location')
               {
                         params['custscript_acctsint_deletedsegmentname'] =  oldrecord.getFieldValue('namenohierarchy') + ':' + oldrecord.getId();
                }
               if ( currentType == 'subsidiary')
               {
                         params['custscript_acctsint_deletedsegmentname'] =  oldrecord.getFieldValue('namenohierarchy') + ':' + oldrecord.getId();
                }

               params['custscript_create_optype'] = 'delete';
              var results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched', params);
                    if ( results != 'QUEUED' )
         {
results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched1', params);
                    if ( results != 'QUEUED' )
            {
results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched2', params);
                    if ( results != 'QUEUED' )
                {
results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched3', params);
                    if ( results != 'QUEUED' )
                    {
results =  nlapiScheduleScript('customscript_acctsint_userevent_sched', 'customdeploy_acctsint_userevent_sched4', params);

                        if (results != 'QUEUED')
                         {
	                  nlapiLogExecution('ERROR','Process Error',  'Will not be able to trigger event due to max simultaneous call');
                         }
                     }
                }
           }
       }

     }
  }

}

function GetSegmentId(paramvalue)
{
      if (paramvalue == 'account') { return '1' };
      if (paramvalue == 'department') { return '2' };
      if (paramvalue == 'classification' ) { return '3' };
      if (paramvalue == 'subsidiary') { return '4' };
      if (paramvalue == 'location') { return '5' };

}
function GetInclCustomField(paramvalue)
{
      if (paramvalue == 'account') { return 'custrecord_acctincludeincoupa' };
      if (paramvalue == 'department') { return 'custrecord_deptincludeincoupa' };
      if (paramvalue == 'classification' ) { return '3' };
      if (paramvalue == 'subsidiary') { return 'custrecord_subincludeincoupa' };
      if (paramvalue == 'location') { return '5' };

}<|endoftext|>


<commit_before>var playername = window.location.search.split("name=")[1];
var xhr = new XMLHttpRequest();

xhr.open("GET", "https://api.wynncraft.com/public_api.php?action=playerStats&command=" + playername);
xhr.send();

xhr.addEventListener("readystatechange", processRequest, false);

function processRequest(e) {
  if (xhr.readyState == 4 && xhr.status == 200) {
    var response = JSON.parse(xhr.responseText);

    if (response.error == "Player not found") {
      document.getElementsByClassName("main")[0].innerHTML = "
WynnStats

Player not found!

Find Another Player's Stats
<form action='player' method='get'><input type='text' name='name' placeholder='Username (Case Sensitive)'><input type='submit'></form>

";
      return
    }

    document.getElementsByTagName("title")[0].innerHTML = response.username + " - WynnStats";
    document.getElementById("username").innerHTML = response.username;

    if (response.tag != "") {
      document.getElementById("rank").innerHTML = response.rank + " (" + response.tag + ")";
    }
    else {
      document.getElementById("rank").innerHTML = response.rank;
    }

    if (response.guild.name != "None") {
      document.getElementById("guildname").innerHTML = response.guild.name;
      document.getElementById("guildrank").innerHTML = response.guild.rank;
      document.getElementById("guildinfo").onclick = function(){window.open("guild?name=" + response.guild.name, "_self");};
    }
    else {
      document.getElementById("guildinfo").innerHTML = "";
    }

    if (response.current_server != "null") {
      document.getElementById("c_server").innerHTML = "Currently Online: " + response.current_server;
    }

    document.getElementById("playtime").innerHTML = response.playtime + " minutes
≈ " + Math.round((response.playtime / 60) * 100) / 100 + " hours";
    document.getElementById("first_join").innerHTML = response.first_join_friendly;
    document.getElementById("last_join").innerHTML = response.last_join_friendly;
    document.getElementById("mobs_killed").innerHTML = response.global.mobs_killed;
    document.getElementById("pvp_kills").innerHTML = response.global.pvp_kills;
    document.getElementById("pvp_deaths").innerHTML = response.global.pvp_deaths;
    document.getElementById("chests_found").innerHTML = response.global.chests_found;
    document.getElementById("logins").innerHTML = response.global.logins;
    document.getElementById("deaths").innerHTML = response.global.deaths;
    document.getElementById("total_level").innerHTML = response.global.total_level;

    for (var classname in response.classes) {
      if (response.classes.hasOwnProperty(classname)) {
        c = eval("response.classes." + classname)
         var cur_stat_html = "

" + classname + "

Total Playtime	" + c.playtime + " minutes
≈ " + Math.round((c.playtime / 60) * 100) / 100 + " hours
Level	" + c.level + "

XP	" + c.xp + "%

Dungeons	" + c.dungeonsAmount + "
"
        for (var dungeonname in c.dungeons) {
          if (c.dungeons.hasOwnProperty(dungeonname)) {
            cur_stat_html += "
	" + dungeonname + " (" + c.dungeons[dungeonname] + ")
"
          }
        }
        cur_stat_html += "
Quests	" + c.questsAmount + "
"
        for (var questname in c.quests) {
          if (c.quests.hasOwnProperty(questname)) {
            cur_stat_html += "
	" + c.quests[questname] + "
"
          }
        }
        document.getElementById("classdiv").innerHTML += cur_stat_html + "
Mobs Killed	" + c.mobs_killed + "

PvP Kills	" + c.pvp_kills + "

PvP Deaths	" + c.pvp_deaths + "

Chests Found	" + c.chests_found + "

Logins	" + c.logins + "

Deaths	" + c.deaths + "

Events Won	" + c.events_won + "

"
      }
    }
    document.getElementById("classdiv").innerHTML += "

Find Another Player's Stats
<form action='player' method='get'><input type='text' name='name' placeholder='Username (Case Sensitive)'><input type='submit'></form>

"
  }
}

function toggleHideId(e) {
  if (document.getElementById(e).style.display == "") {
    document.getElementById(e).style.display = "none"
  }
  else {
    document.getElementById(e).style.display = ""
  }
}

function toggleHideClass(e) {
  for (var i in document.getElementsByClassName(e)) {
    if (document.getElementsByClassName(e).hasOwnProperty(i)) {
      j = eval(document.getElementsByClassName(e)[i])
      if (j.style.display == "") {
        j.style.display = "none"
      }
      else {
        j.style.display = ""
      }
    }
  }
}
<commit_msg>Added class skill points for players<commit_after>var playername = window.location.search.split("name=")[1];
var xhr = new XMLHttpRequest();

xhr.open("GET", "https://api.wynncraft.com/public_api.php?action=playerStats&command=" + playername);
xhr.send();

xhr.addEventListener("readystatechange", processRequest, false);

function processRequest(e) {
  if (xhr.readyState == 4 && xhr.status == 200) {
    var response = JSON.parse(xhr.responseText);

    if (response.error == "Player not found") {
      document.getElementsByClassName("main")[0].innerHTML = "
WynnStats

Player not found!

Find Another Player's Stats
<form action='player' method='get'><input type='text' name='name' placeholder='Username (Case Sensitive)'><input type='submit'></form>

";
      return
    }

    document.getElementsByTagName("title")[0].innerHTML = response.username + " - WynnStats";
    document.getElementById("username").innerHTML = response.username;

    if (response.tag != "") {
      document.getElementById("rank").innerHTML = response.rank + " (" + response.tag + ")";
    }
    else {
      document.getElementById("rank").innerHTML = response.rank;
    }

    if (response.guild.name != "None") {
      document.getElementById("guildname").innerHTML = response.guild.name;
      document.getElementById("guildrank").innerHTML = response.guild.rank;
      document.getElementById("guildinfo").onclick = function(){window.open("guild?name=" + response.guild.name, "_self");};
    }
    else {
      document.getElementById("guildinfo").innerHTML = "";
    }

    if (response.current_server != "null") {
      document.getElementById("c_server").innerHTML = "Currently Online: " + response.current_server;
    }

    document.getElementById("playtime").innerHTML = response.playtime + " minutes
≈ " + Math.round((response.playtime / 60) * 100) / 100 + " hours";
    document.getElementById("first_join").innerHTML = response.first_join_friendly;
    document.getElementById("last_join").innerHTML = response.last_join_friendly;
    document.getElementById("mobs_killed").innerHTML = response.global.mobs_killed;
    document.getElementById("pvp_kills").innerHTML = response.global.pvp_kills;
    document.getElementById("pvp_deaths").innerHTML = response.global.pvp_deaths;
    document.getElementById("chests_found").innerHTML = response.global.chests_found;
    document.getElementById("logins").innerHTML = response.global.logins;
    document.getElementById("deaths").innerHTML = response.global.deaths;
    document.getElementById("total_level").innerHTML = response.global.total_level;

    for (var classname in response.classes) {
      if (response.classes.hasOwnProperty(classname)) {
        c = eval("response.classes." + classname)
        var cur_stat_html = "

" + classname + "

Total Playtime	" + c.playtime + " minutes
≈ " + Math.round((c.playtime / 60) * 100) / 100 + " hours
Level	" + c.level + "

XP	" + c.xp + "%

Skills	Click to Expand
"
        for (var skillname in c.skills) {
          if (c.skills.hasOwnProperty(skillname)) {
            cur_stat_html += "
" + skillname + "	" + c.skills[skillname] + "
"
          }
        }
        cur_stat_html += "
Dungeons	" + c.dungeonsAmount + "
"
        for (var dungeonname in c.dungeons) {
          if (c.dungeons.hasOwnProperty(dungeonname)) {
            cur_stat_html += "
	" + dungeonname + " (" + c.dungeons[dungeonname] + ")
"
          }
        }
        cur_stat_html += "
Quests	" + c.questsAmount + "
"
        for (var questname in c.quests) {
          if (c.quests.hasOwnProperty(questname)) {
            cur_stat_html += "
	" + c.quests[questname] + "
"
          }
        }
        document.getElementById("classdiv").innerHTML += cur_stat_html + "
Mobs Killed	" + c.mobs_killed + "

PvP Kills	" + c.pvp_kills + "

PvP Deaths	" + c.pvp_deaths + "

Chests Found	" + c.chests_found + "

Logins	" + c.logins + "

Deaths	" + c.deaths + "

Events Won	" + c.events_won + "

"
      }
    }
    document.getElementById("classdiv").innerHTML += "

Find Another Player's Stats
<form action='player' method='get'><input type='text' name='name' placeholder='Username (Case Sensitive)'><input type='submit'></form>

"
  }
}

function toggleHideId(e) {
  if (document.getElementById(e).style.display == "") {
    document.getElementById(e).style.display = "none"
  }
  else {
    document.getElementById(e).style.display = ""
  }
}

function toggleHideClass(e) {
  for (var i in document.getElementsByClassName(e)) {
    if (document.getElementsByClassName(e).hasOwnProperty(i)) {
      j = eval(document.getElementsByClassName(e)[i])
      if (j.style.display == "") {
        j.style.display = "none"
      }
      else {
        j.style.display = ""
      }
    }
  }
}
<|endoftext|>


<commit_before>const fs = require("fs");
const https = require("https");
const zlib = require("zlib");
const path = require("path");
const tar = require("tar");

const licenseKey = process.env.MAXMIND_LICENSE_KEY;
if (!licenseKey) {
  console.error(`Error: License key is not configured.\n
  You need to signup for a _free_ Maxmind account to get a license key.
  Go to https://www.maxmind.com/en/geolite2/signup, obtain your key and
  put it in the MAXMIND_LICENSE_KEY environment variable\n`);
  process.exit(1);
}

const link = edition =>
  `https://download.maxmind.com/app/geoip_download?edition_id=${edition}&license_key=${licenseKey}&suffix=tar.gz`;

const links = [
  link('GeoLite2-City'),
  link('GeoLite2-Country'),
  link('GeoLite2-ASN'),
];

const downloadPath = path.join(__dirname, "..", "dbs");

if (!fs.existsSync(downloadPath)) fs.mkdirSync(downloadPath);

const download = url =>
  new Promise(resolve => {
    https.get(url, function(response) {
      resolve(response.pipe(zlib.createGunzip({})));
    });
  });

console.log("Downloading maxmind databases...");
links.forEach(url =>
  download(url).then(result =>
    result.pipe(tar.t()).on("entry", entry => {
      if (entry.path.endsWith(".mmdb")) {
        const dstFilename = path.join(downloadPath, path.basename(entry.path));
        entry.pipe(fs.createWriteStream(dstFilename));
      }
    })
  )
);
<commit_msg>Add ability to take license key from package.json<commit_after>const fs = require("fs");
const https = require("https");
const zlib = require("zlib");
const path = require("path");
const tar = require("tar");

let licenseKey = process.env.MAXMIND_LICENSE_KEY;
if (!licenseKey) {
  try {
    const packageJSONFilename = path.join(process.env["INIT_CWD"], "package.json");
    const packageJSON = JSON.parse(fs.readFileSync(packageJSONFilename).toString());
    licenseKey = packageJSON["node-geolite2"]["license-key"];
  }
  catch(e) {
    console.error(`Error reading Maxmind license key from package.json:
    ${e.message}\n`);
  }
}

if (!licenseKey) {
  console.error(`Error: License key is not configured.\n
  You need to signup for a _free_ Maxmind account to get a license key.
  Go to https://www.maxmind.com/en/geolite2/signup, obtain your key and
  put it in the MAXMIND_LICENSE_KEY environment variable
  or in your package.json file (at the root level) like this:
  "node-geolite2": {
    "license-key": "<your license key>"
  }\n`);
  process.exit(1);
}

const link = edition =>
  `https://download.maxmind.com/app/geoip_download?edition_id=${edition}&license_key=${licenseKey}&suffix=tar.gz`;

const links = [
  link('GeoLite2-City'),
  link('GeoLite2-Country'),
  link('GeoLite2-ASN'),
];

const downloadPath = path.join(__dirname, "..", "dbs");

if (!fs.existsSync(downloadPath)) fs.mkdirSync(downloadPath);

const download = url =>
  new Promise(resolve => {
    https.get(url, function(response) {
      resolve(response.pipe(zlib.createGunzip({})));
    });
  });

console.log("Downloading maxmind databases...");
links.forEach(url =>
  download(url).then(result =>
    result.pipe(tar.t()).on("entry", entry => {
      if (entry.path.endsWith(".mmdb")) {
        const dstFilename = path.join(downloadPath, path.basename(entry.path));
        entry.pipe(fs.createWriteStream(dstFilename));
      }
    })
  )
);<|endoftext|>


<commit_before>/* global requirejs, require */

var classify = Ember.String.classify;
var get = Ember.get;

var LOADING_WHITELIST = ['badges', 'userActivity', 'userPrivateMessages', 'admin', 'adminFlags',
                         'user', 'preferences', 'adminEmail', 'adminUsersList'];
var _dummyRoute;
var _loadingView;

function loadingResolver(cb) {
  return function(parsedName) {
    var fullNameWithoutType = parsedName.fullNameWithoutType;

    if (fullNameWithoutType.indexOf('Loading') >= 0) {
      fullNameWithoutType = fullNameWithoutType.replace('Loading', '');
      if (LOADING_WHITELIST.indexOf(fullNameWithoutType) !== -1) {
        return cb(fullNameWithoutType);
      }
    }
  };
}

function parseName(fullName) {
  const nameParts = fullName.split(":"),
        type = nameParts[0], fullNameWithoutType = nameParts[1],
        name = fullNameWithoutType,
        namespace = get(this, 'namespace'),
        root = namespace;

  return {
    fullName: fullName,
    type: type,
    fullNameWithoutType: fullNameWithoutType,
    name: name,
    root: root,
    resolveMethodName: "resolve" + classify(type)
  };
}

export default Ember.DefaultResolver.extend({
  parseName: parseName,

  normalize(fullName) {
    var split = fullName.split(':');
    if (split.length > 1) {
      var discourseBase = 'discourse/' + split[0] + 's/';
      var adminBase = 'admin/' + split[0] + 's/';

      // Allow render 'admin/templates/xyz' too
      split[1] = split[1].replace('.templates', '').replace('/templates', '');

      // Try slashes
      var dashed = Ember.String.dasherize(split[1].replace(/\./g, '/'));
      if (requirejs.entries[discourseBase + dashed] || requirejs.entries[adminBase + dashed]) {
        return split[0] + ":" + dashed;
      }

      // Try with dashes instead of slashes
      dashed = Ember.String.dasherize(split[1].replace(/\./g, '-'));
      if (requirejs.entries[discourseBase + dashed] || requirejs.entries[adminBase + dashed]) {
        return split[0] + ":" + dashed;
      }
    }
    return this._super(fullName);
  },

  customResolve(parsedName) {
    // If we end with the name we want, use it. This allows us to define components within plugins.
    const suffix = parsedName.type + 's/' + parsedName.fullNameWithoutType,
          dashed = Ember.String.dasherize(suffix),
          moduleName = Object.keys(requirejs.entries).find(function(e) {
            return (e.indexOf(suffix, e.length - suffix.length) !== -1) ||
                   (e.indexOf(dashed, e.length - dashed.length) !== -1);
          });

    var module;
    if (moduleName) {
      module = require(moduleName, null, null, true /* force sync */);
      if (module && module['default']) { module = module['default']; }
    }
    return module;
  },

  resolveWidget(parsedName) {
    return this.customResolve(parsedName) || this._super(parsedName);
  },

  resolveAdapter(parsedName) {
    return this.customResolve(parsedName) || this._super(parsedName);
  },

  resolveModel(parsedName) {
    return this.customResolve(parsedName) || this._super(parsedName);
  },

  resolveView(parsedName) {
    return this.findLoadingView(parsedName) || this.customResolve(parsedName) || this._super(parsedName);
  },

  resolveHelper(parsedName) {
    return this.customResolve(parsedName) || this._super(parsedName);
  },

  resolveController(parsedName) {
    return this.customResolve(parsedName) || this._super(parsedName);
  },

  resolveComponent(parsedName) {
    return this.customResolve(parsedName) || this._super(parsedName);
  },

  resolveRoute(parsedName) {
    return this.findLoadingRoute(parsedName) || this.customResolve(parsedName) || this._super(parsedName);
  },

  resolveTemplate(parsedName) {
    return this.findPluginTemplate(parsedName) ||
           this.findPluginMobileTemplate(parsedName) ||
           this.findMobileTemplate(parsedName) ||
           this.findTemplate(parsedName) ||
           Ember.TEMPLATES.not_found;
  },

  findLoadingRoute: loadingResolver(function() {
    _dummyRoute = _dummyRoute || Ember.Route.extend();
    return _dummyRoute;
  }),

  findLoadingView: loadingResolver(function() {
    if (!_loadingView) {
      _loadingView = require('discourse/views/loading', null, null, true /* force sync */);
      if (_loadingView && _loadingView['default']) { _loadingView = _loadingView['default']; }
    }
    return _loadingView;
  }),

  findPluginTemplate(parsedName) {
    var pluginParsedName = this.parseName(parsedName.fullName.replace("template:", "template:javascripts/"));
    return this.findTemplate(pluginParsedName);
  },

  findPluginMobileTemplate(parsedName) {
    if (this.mobileView) {
      var pluginParsedName = this.parseName(parsedName.fullName.replace("template:", "template:javascripts/mobile/"));
      return this.findTemplate(pluginParsedName);
    }
  },

  findMobileTemplate(parsedName) {
    if (this.mobileView) {
      var mobileParsedName = this.parseName(parsedName.fullName.replace("template:", "template:mobile/"));
      return this.findTemplate(mobileParsedName);
    }
  },

  findTemplate(parsedName) {
    const withoutType = parsedName.fullNameWithoutType,
          slashedType = withoutType.replace(/\./g, '/'),
          decamelized = withoutType.decamelize(),
          dashed = decamelized.replace(/\./g, '-').replace(/\_/g, '-'),
          templates = Ember.TEMPLATES;

    return this._super(parsedName) ||
           templates[slashedType] ||
           templates[withoutType] ||
           templates[dashed] ||
           templates[decamelized.replace(/\./, '/')] ||
           templates[decamelized.replace(/\_/, '/')] ||
           this.findAdminTemplate(parsedName) ||
           this.findUnderscoredTemplate(parsedName);
  },

  findUnderscoredTemplate(parsedName) {
    var decamelized = parsedName.fullNameWithoutType.decamelize();
    var underscored = decamelized.replace(/\-/g, "_");
    return Ember.TEMPLATES[underscored];
  },

  // Try to find a template within a special admin namespace, e.g. adminEmail => admin/templates/email
  // (similar to how discourse lays out templates)
  findAdminTemplate(parsedName) {
    var decamelized = parsedName.fullNameWithoutType.decamelize();

    if (decamelized.indexOf('components') === 0) {
      const compTemplate = Ember.TEMPLATES['admin/templates/' + decamelized];
      if (compTemplate) { return compTemplate; }
    }

    if (decamelized === "javascripts/admin") {
      return Ember.TEMPLATES['admin/templates/admin'];
    }

    if (decamelized.indexOf('admin') === 0 || decamelized.indexOf('javascripts/admin') === 0) {
      decamelized = decamelized.replace(/^admin\_/, 'admin/templates/');
      decamelized = decamelized.replace(/^admin\./, 'admin/templates/');
      decamelized = decamelized.replace(/\./g, '_');

      const dashed = decamelized.replace(/_/g, '-');
      return Ember.TEMPLATES[decamelized] ||
             Ember.TEMPLATES[dashed] ||
             Ember.TEMPLATES[dashed.replace('admin-', 'admin/')];
    }
  }

});
<commit_msg>fix order of plugin template resolution<commit_after>/* global requirejs, require */

var classify = Ember.String.classify;
var get = Ember.get;

var LOADING_WHITELIST = ['badges', 'userActivity', 'userPrivateMessages', 'admin', 'adminFlags',
                         'user', 'preferences', 'adminEmail', 'adminUsersList'];
var _dummyRoute;
var _loadingView;

function loadingResolver(cb) {
  return function(parsedName) {
    var fullNameWithoutType = parsedName.fullNameWithoutType;

    if (fullNameWithoutType.indexOf('Loading') >= 0) {
      fullNameWithoutType = fullNameWithoutType.replace('Loading', '');
      if (LOADING_WHITELIST.indexOf(fullNameWithoutType) !== -1) {
        return cb(fullNameWithoutType);
      }
    }
  };
}

function parseName(fullName) {
  const nameParts = fullName.split(":"),
        type = nameParts[0], fullNameWithoutType = nameParts[1],
        name = fullNameWithoutType,
        namespace = get(this, 'namespace'),
        root = namespace;

  return {
    fullName: fullName,
    type: type,
    fullNameWithoutType: fullNameWithoutType,
    name: name,
    root: root,
    resolveMethodName: "resolve" + classify(type)
  };
}

export default Ember.DefaultResolver.extend({
  parseName: parseName,

  normalize(fullName) {
    var split = fullName.split(':');
    if (split.length > 1) {
      var discourseBase = 'discourse/' + split[0] + 's/';
      var adminBase = 'admin/' + split[0] + 's/';

      // Allow render 'admin/templates/xyz' too
      split[1] = split[1].replace('.templates', '').replace('/templates', '');

      // Try slashes
      var dashed = Ember.String.dasherize(split[1].replace(/\./g, '/'));
      if (requirejs.entries[discourseBase + dashed] || requirejs.entries[adminBase + dashed]) {
        return split[0] + ":" + dashed;
      }

      // Try with dashes instead of slashes
      dashed = Ember.String.dasherize(split[1].replace(/\./g, '-'));
      if (requirejs.entries[discourseBase + dashed] || requirejs.entries[adminBase + dashed]) {
        return split[0] + ":" + dashed;
      }
    }
    return this._super(fullName);
  },

  customResolve(parsedName) {
    // If we end with the name we want, use it. This allows us to define components within plugins.
    const suffix = parsedName.type + 's/' + parsedName.fullNameWithoutType,
          dashed = Ember.String.dasherize(suffix),
          moduleName = Object.keys(requirejs.entries).find(function(e) {
            return (e.indexOf(suffix, e.length - suffix.length) !== -1) ||
                   (e.indexOf(dashed, e.length - dashed.length) !== -1);
          });

    var module;
    if (moduleName) {
      module = require(moduleName, null, null, true /* force sync */);
      if (module && module['default']) { module = module['default']; }
    }
    return module;
  },

  resolveWidget(parsedName) {
    return this.customResolve(parsedName) || this._super(parsedName);
  },

  resolveAdapter(parsedName) {
    return this.customResolve(parsedName) || this._super(parsedName);
  },

  resolveModel(parsedName) {
    return this.customResolve(parsedName) || this._super(parsedName);
  },

  resolveView(parsedName) {
    return this.findLoadingView(parsedName) || this.customResolve(parsedName) || this._super(parsedName);
  },

  resolveHelper(parsedName) {
    return this.customResolve(parsedName) || this._super(parsedName);
  },

  resolveController(parsedName) {
    return this.customResolve(parsedName) || this._super(parsedName);
  },

  resolveComponent(parsedName) {
    return this.customResolve(parsedName) || this._super(parsedName);
  },

  resolveRoute(parsedName) {
    return this.findLoadingRoute(parsedName) || this.customResolve(parsedName) || this._super(parsedName);
  },

  resolveTemplate(parsedName) {
    return this.findPluginMobileTemplate(parsedName) ||
           this.findPluginTemplate(parsedName) ||
           this.findMobileTemplate(parsedName) ||
           this.findTemplate(parsedName) ||
           Ember.TEMPLATES.not_found;
  },

  findLoadingRoute: loadingResolver(function() {
    _dummyRoute = _dummyRoute || Ember.Route.extend();
    return _dummyRoute;
  }),

  findLoadingView: loadingResolver(function() {
    if (!_loadingView) {
      _loadingView = require('discourse/views/loading', null, null, true /* force sync */);
      if (_loadingView && _loadingView['default']) { _loadingView = _loadingView['default']; }
    }
    return _loadingView;
  }),

  findPluginTemplate(parsedName) {
    var pluginParsedName = this.parseName(parsedName.fullName.replace("template:", "template:javascripts/"));
    return this.findTemplate(pluginParsedName);
  },

  findPluginMobileTemplate(parsedName) {
    if (this.mobileView) {
      var pluginParsedName = this.parseName(parsedName.fullName.replace("template:", "template:javascripts/mobile/"));
      return this.findTemplate(pluginParsedName);
    }
  },

  findMobileTemplate(parsedName) {
    if (this.mobileView) {
      var mobileParsedName = this.parseName(parsedName.fullName.replace("template:", "template:mobile/"));
      return this.findTemplate(mobileParsedName);
    }
  },

  findTemplate(parsedName) {
    const withoutType = parsedName.fullNameWithoutType,
          slashedType = withoutType.replace(/\./g, '/'),
          decamelized = withoutType.decamelize(),
          dashed = decamelized.replace(/\./g, '-').replace(/\_/g, '-'),
          templates = Ember.TEMPLATES;

    return this._super(parsedName) ||
           templates[slashedType] ||
           templates[withoutType] ||
           templates[dashed] ||
           templates[decamelized.replace(/\./, '/')] ||
           templates[decamelized.replace(/\_/, '/')] ||
           this.findAdminTemplate(parsedName) ||
           this.findUnderscoredTemplate(parsedName);
  },

  findUnderscoredTemplate(parsedName) {
    var decamelized = parsedName.fullNameWithoutType.decamelize();
    var underscored = decamelized.replace(/\-/g, "_");
    return Ember.TEMPLATES[underscored];
  },

  // Try to find a template within a special admin namespace, e.g. adminEmail => admin/templates/email
  // (similar to how discourse lays out templates)
  findAdminTemplate(parsedName) {
    var decamelized = parsedName.fullNameWithoutType.decamelize();

    if (decamelized.indexOf('components') === 0) {
      const compTemplate = Ember.TEMPLATES['admin/templates/' + decamelized];
      if (compTemplate) { return compTemplate; }
    }

    if (decamelized === "javascripts/admin") {
      return Ember.TEMPLATES['admin/templates/admin'];
    }

    if (decamelized.indexOf('admin') === 0 || decamelized.indexOf('javascripts/admin') === 0) {
      decamelized = decamelized.replace(/^admin\_/, 'admin/templates/');
      decamelized = decamelized.replace(/^admin\./, 'admin/templates/');
      decamelized = decamelized.replace(/\./g, '_');

      const dashed = decamelized.replace(/_/g, '-');
      return Ember.TEMPLATES[decamelized] ||
             Ember.TEMPLATES[dashed] ||
             Ember.TEMPLATES[dashed.replace('admin-', 'admin/')];
    }
  }

});
<|endoftext|>


<commit_before>/* global requirejs, require */

var classify = Ember.String.classify;
var get = Ember.get;

var LOADING_WHITELIST = ['badges', 'userActivity', 'userPrivateMessages', 'admin', 'adminFlags',
                         'user', 'preferences', 'adminEmail', 'adminUsersList'];
var _dummyRoute;
var _loadingView;

function loadingResolver(cb) {
  return function(parsedName) {
    var fullNameWithoutType = parsedName.fullNameWithoutType;

    if (fullNameWithoutType.indexOf('Loading') >= 0) {
      fullNameWithoutType = fullNameWithoutType.replace('Loading', '');
      if (LOADING_WHITELIST.indexOf(fullNameWithoutType) !== -1) {
        return cb(fullNameWithoutType);
      }
    }
  };
}

function parseName(fullName) {
  const nameParts = fullName.split(":"),
        type = nameParts[0], fullNameWithoutType = nameParts[1],
        name = fullNameWithoutType,
        namespace = get(this, 'namespace'),
        root = namespace;

  return {
    fullName: fullName,
    type: type,
    fullNameWithoutType: fullNameWithoutType,
    name: name,
    root: root,
    resolveMethodName: "resolve" + classify(type)
  };
}

export default Ember.DefaultResolver.extend({
  parseName: parseName,

  normalize(fullName) {
    var split = fullName.split(':');
    if (split.length > 1) {
      var discourseBase = 'discourse/' + split[0] + 's/';
      var adminBase = 'admin/' + split[0] + 's/';

      // Allow render 'admin/templates/xyz' too
      split[1] = split[1].replace('.templates', '').replace('/templates', '');

      // Try slashes
      var dashed = Ember.String.dasherize(split[1].replace(/\./g, '/'));
      if (requirejs.entries[discourseBase + dashed] || requirejs.entries[adminBase + dashed]) {
        return split[0] + ":" + dashed;
      }

      // Try with dashes instead of slashes
      dashed = Ember.String.dasherize(split[1].replace(/\./g, '-'));
      if (requirejs.entries[discourseBase + dashed] || requirejs.entries[adminBase + dashed]) {
        return split[0] + ":" + dashed;
      }
    }
    return this._super(fullName);
  },

  customResolve(parsedName) {
    // If we end with the name we want, use it. This allows us to define components within plugins.
    const suffix = parsedName.type + 's/' + parsedName.fullNameWithoutType,
          dashed = Ember.String.dasherize(suffix),
          moduleName = Object.keys(requirejs.entries).find(function(e) {
            return (e.indexOf(suffix, e.length - suffix.length) !== -1) ||
                   (e.indexOf(dashed, e.length - dashed.length) !== -1);
          });

    var module;
    if (moduleName) {
      module = require(moduleName, null, null, true /* force sync */);
      if (module && module['default']) { module = module['default']; }
    }
    return module;
  },

  resolveWidget(parsedName) {
    return this.customResolve(parsedName) || this._super(parsedName);
  },

  resolveAdapter(parsedName) {
    return this.customResolve(parsedName) || this._super(parsedName);
  },

  resolveModel(parsedName) {
    return this.customResolve(parsedName) || this._super(parsedName);
  },

  resolveView(parsedName) {
    return this.findLoadingView(parsedName) || this.customResolve(parsedName) || this._super(parsedName);
  },

  resolveHelper(parsedName) {
    return this.customResolve(parsedName) || this._super(parsedName);
  },

  resolveController(parsedName) {
    return this.customResolve(parsedName) || this._super(parsedName);
  },

  resolveComponent(parsedName) {
    return this.customResolve(parsedName) || this._super(parsedName);
  },

  resolveRoute(parsedName) {
    return this.findLoadingRoute(parsedName) || this.customResolve(parsedName) || this._super(parsedName);
  },

  resolveTemplate(parsedName) {
    return this.findPluginTemplate(parsedName) ||
           this.findMobileTemplate(parsedName) ||
           this.findTemplate(parsedName) ||
           Ember.TEMPLATES.not_found;
  },

  findLoadingRoute: loadingResolver(function() {
    _dummyRoute = _dummyRoute || Ember.Route.extend();
    return _dummyRoute;
  }),

  findLoadingView: loadingResolver(function() {
    if (!_loadingView) {
      _loadingView = require('discourse/views/loading', null, null, true /* force sync */);
      if (_loadingView && _loadingView['default']) { _loadingView = _loadingView['default']; }
    }
    return _loadingView;
  }),

  findPluginTemplate(parsedName) {
    var pluginParsedName = this.parseName(parsedName.fullName.replace("template:", "template:javascripts/"));
    return this.findTemplate(pluginParsedName);
  },

  findMobileTemplate(parsedName) {
    if (this.mobileView) {
      var mobileParsedName = this.parseName(parsedName.fullName.replace("template:", "template:mobile/"));
      return this.findTemplate(mobileParsedName);
    }
  },

  findTemplate(parsedName) {
    const withoutType = parsedName.fullNameWithoutType,
          slashedType = withoutType.replace(/\./g, '/'),
          decamelized = withoutType.decamelize(),
          dashed = decamelized.replace(/\./g, '-').replace(/\_/g, '-'),
          templates = Ember.TEMPLATES;

    return this._super(parsedName) ||
           templates[slashedType] ||
           templates[withoutType] ||
           templates[dashed] ||
           templates[decamelized.replace(/\./, '/')] ||
           templates[decamelized.replace(/\_/, '/')] ||
           this.findAdminTemplate(parsedName) ||
           this.findUnderscoredTemplate(parsedName);
  },

  findUnderscoredTemplate(parsedName) {
    var decamelized = parsedName.fullNameWithoutType.decamelize();
    var underscored = decamelized.replace(/\-/g, "_");
    return Ember.TEMPLATES[underscored];
  },

  // Try to find a template within a special admin namespace, e.g. adminEmail => admin/templates/email
  // (similar to how discourse lays out templates)
  findAdminTemplate(parsedName) {
    var decamelized = parsedName.fullNameWithoutType.decamelize();

    if (decamelized.indexOf('components') === 0) {
      const compTemplate = Ember.TEMPLATES['admin/templates/' + decamelized];
      if (compTemplate) { return compTemplate; }
    }

    if (decamelized === "javascripts/admin") {
      return Ember.TEMPLATES['admin/templates/admin'];
    }

    if (decamelized.indexOf('admin') === 0 || decamelized.indexOf('javascripts/admin') === 0) {
      decamelized = decamelized.replace(/^admin\_/, 'admin/templates/');
      decamelized = decamelized.replace(/^admin\./, 'admin/templates/');
      decamelized = decamelized.replace(/\./g, '_');

      const dashed = decamelized.replace(/_/g, '-');
      return Ember.TEMPLATES[decamelized] ||
             Ember.TEMPLATES[dashed] ||
             Ember.TEMPLATES[dashed.replace('admin-', 'admin/')];
    }
  }

});
<commit_msg>check the plugin mobile/list dir for templates<commit_after>/* global requirejs, require */

var classify = Ember.String.classify;
var get = Ember.get;

var LOADING_WHITELIST = ['badges', 'userActivity', 'userPrivateMessages', 'admin', 'adminFlags',
                         'user', 'preferences', 'adminEmail', 'adminUsersList'];
var _dummyRoute;
var _loadingView;

function loadingResolver(cb) {
  return function(parsedName) {
    var fullNameWithoutType = parsedName.fullNameWithoutType;

    if (fullNameWithoutType.indexOf('Loading') >= 0) {
      fullNameWithoutType = fullNameWithoutType.replace('Loading', '');
      if (LOADING_WHITELIST.indexOf(fullNameWithoutType) !== -1) {
        return cb(fullNameWithoutType);
      }
    }
  };
}

function parseName(fullName) {
  const nameParts = fullName.split(":"),
        type = nameParts[0], fullNameWithoutType = nameParts[1],
        name = fullNameWithoutType,
        namespace = get(this, 'namespace'),
        root = namespace;

  return {
    fullName: fullName,
    type: type,
    fullNameWithoutType: fullNameWithoutType,
    name: name,
    root: root,
    resolveMethodName: "resolve" + classify(type)
  };
}

export default Ember.DefaultResolver.extend({
  parseName: parseName,

  normalize(fullName) {
    var split = fullName.split(':');
    if (split.length > 1) {
      var discourseBase = 'discourse/' + split[0] + 's/';
      var adminBase = 'admin/' + split[0] + 's/';

      // Allow render 'admin/templates/xyz' too
      split[1] = split[1].replace('.templates', '').replace('/templates', '');

      // Try slashes
      var dashed = Ember.String.dasherize(split[1].replace(/\./g, '/'));
      if (requirejs.entries[discourseBase + dashed] || requirejs.entries[adminBase + dashed]) {
        return split[0] + ":" + dashed;
      }

      // Try with dashes instead of slashes
      dashed = Ember.String.dasherize(split[1].replace(/\./g, '-'));
      if (requirejs.entries[discourseBase + dashed] || requirejs.entries[adminBase + dashed]) {
        return split[0] + ":" + dashed;
      }
    }
    return this._super(fullName);
  },

  customResolve(parsedName) {
    // If we end with the name we want, use it. This allows us to define components within plugins.
    const suffix = parsedName.type + 's/' + parsedName.fullNameWithoutType,
          dashed = Ember.String.dasherize(suffix),
          moduleName = Object.keys(requirejs.entries).find(function(e) {
            return (e.indexOf(suffix, e.length - suffix.length) !== -1) ||
                   (e.indexOf(dashed, e.length - dashed.length) !== -1);
          });

    var module;
    if (moduleName) {
      module = require(moduleName, null, null, true /* force sync */);
      if (module && module['default']) { module = module['default']; }
    }
    return module;
  },

  resolveWidget(parsedName) {
    return this.customResolve(parsedName) || this._super(parsedName);
  },

  resolveAdapter(parsedName) {
    return this.customResolve(parsedName) || this._super(parsedName);
  },

  resolveModel(parsedName) {
    return this.customResolve(parsedName) || this._super(parsedName);
  },

  resolveView(parsedName) {
    return this.findLoadingView(parsedName) || this.customResolve(parsedName) || this._super(parsedName);
  },

  resolveHelper(parsedName) {
    return this.customResolve(parsedName) || this._super(parsedName);
  },

  resolveController(parsedName) {
    return this.customResolve(parsedName) || this._super(parsedName);
  },

  resolveComponent(parsedName) {
    return this.customResolve(parsedName) || this._super(parsedName);
  },

  resolveRoute(parsedName) {
    return this.findLoadingRoute(parsedName) || this.customResolve(parsedName) || this._super(parsedName);
  },

  resolveTemplate(parsedName) {
    return this.findPluginTemplate(parsedName) ||
           this.findPluginMobileTemplate(parsedName) ||
           this.findMobileTemplate(parsedName) ||
           this.findTemplate(parsedName) ||
           Ember.TEMPLATES.not_found;
  },

  findLoadingRoute: loadingResolver(function() {
    _dummyRoute = _dummyRoute || Ember.Route.extend();
    return _dummyRoute;
  }),

  findLoadingView: loadingResolver(function() {
    if (!_loadingView) {
      _loadingView = require('discourse/views/loading', null, null, true /* force sync */);
      if (_loadingView && _loadingView['default']) { _loadingView = _loadingView['default']; }
    }
    return _loadingView;
  }),

  findPluginTemplate(parsedName) {
    var pluginParsedName = this.parseName(parsedName.fullName.replace("template:", "template:javascripts/"));
    return this.findTemplate(pluginParsedName);
  },

  findPluginMobileTemplate(parsedName) {
    var pluginParsedName = this.parseName(parsedName.fullName.replace("template:", "template:javascripts/mobile/"));
    return this.findTemplate(pluginParsedName);
  },

  findMobileTemplate(parsedName) {
    if (this.mobileView) {
      var mobileParsedName = this.parseName(parsedName.fullName.replace("template:", "template:mobile/"));
      return this.findTemplate(mobileParsedName);
    }
  },

  findTemplate(parsedName) {
    const withoutType = parsedName.fullNameWithoutType,
          slashedType = withoutType.replace(/\./g, '/'),
          decamelized = withoutType.decamelize(),
          dashed = decamelized.replace(/\./g, '-').replace(/\_/g, '-'),
          templates = Ember.TEMPLATES;

    return this._super(parsedName) ||
           templates[slashedType] ||
           templates[withoutType] ||
           templates[dashed] ||
           templates[decamelized.replace(/\./, '/')] ||
           templates[decamelized.replace(/\_/, '/')] ||
           this.findAdminTemplate(parsedName) ||
           this.findUnderscoredTemplate(parsedName);
  },

  findUnderscoredTemplate(parsedName) {
    var decamelized = parsedName.fullNameWithoutType.decamelize();
    var underscored = decamelized.replace(/\-/g, "_");
    return Ember.TEMPLATES[underscored];
  },

  // Try to find a template within a special admin namespace, e.g. adminEmail => admin/templates/email
  // (similar to how discourse lays out templates)
  findAdminTemplate(parsedName) {
    var decamelized = parsedName.fullNameWithoutType.decamelize();

    if (decamelized.indexOf('components') === 0) {
      const compTemplate = Ember.TEMPLATES['admin/templates/' + decamelized];
      if (compTemplate) { return compTemplate; }
    }

    if (decamelized === "javascripts/admin") {
      return Ember.TEMPLATES['admin/templates/admin'];
    }

    if (decamelized.indexOf('admin') === 0 || decamelized.indexOf('javascripts/admin') === 0) {
      decamelized = decamelized.replace(/^admin\_/, 'admin/templates/');
      decamelized = decamelized.replace(/^admin\./, 'admin/templates/');
      decamelized = decamelized.replace(/\./g, '_');

      const dashed = decamelized.replace(/_/g, '-');
      return Ember.TEMPLATES[decamelized] ||
             Ember.TEMPLATES[dashed] ||
             Ember.TEMPLATES[dashed.replace('admin-', 'admin/')];
    }
  }

});
<|endoftext|>


<commit_before>/**
 * RegExp.js
 * 各种有趣的正则
 */

;(function(window){
	'use strict';

	var regexpLib = {

	};

	// 手机号、银行卡号只显示后四位
	(function(){

		var re = /\d(?=\d{4})/g;
		var str = '18689161829';
		console.log(str.replace(re,'*')); // *******1829

	})();

	// 手机号显示为 ***-****-****
	(function(){

		var re = /(\d{3})(\d{4})(\d{4})/;
		var str = '18689161829';
		var arr = re.exec(str);
		arr.shift();
		var newStr = arr.join('-');
		console.log(newStr);

	})();

	// 转驼峰
	(function(){
		var re = /-(\w)/g;
		var str = 'border-top-width';

		str.replace(re,function($0,$1){
			return $1.toUpperCase();
		});

	})();

	window.regexpLib = regexpLib;

})(window);<commit_msg>regexp.js<commit_after>/**
 * RegExp.js
 * 各种有趣的正则
 */

;(function(window){
	'use strict';

	var regexpLib = {

	};

	// 手机号、银行卡号只显示后四位
	(function(){

		var re = /\d(?=\d{4})/g;
		var str = '18689161829';
		console.log(str.replace(re,'*')); // *******1829

	})();

	// 手机号显示为 ***-****-****
	(function(){

		var re = /(\d{3})(\d{4})(\d{4})/;
		var str = '18689161829';
		var arr = re.exec(str);
		arr.shift();
		var newStr = arr.join('-');
		console.log(newStr);

	})();

	// 转驼峰
	(function(){
		var re = /-(\w)/g;
		var str = 'border-top-width';

		str.replace(re,function($0,$1){
			return $1.toUpperCase();
		});

	})();

	// 获取url对应的参数值
	(function(){

		//var str = location.search;
		var str = '?search=123&categoryId=-1&serviceType=totalCourse';

		function queryUrlParam(key){
			var re = new RegExp('[?&]' + key + '=([^&]+)');

			return re.exec(str) ? re.exec(str)[1] : null;

		}

	})();

	window.regexpLib = regexpLib;

})(window);<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    ExperimentSchema = mongoose.model('ExperimentSchema');

/**
 * List of Experiment schemas
 */
exports.list = function(req, res) {

    ExperimentSchema.find({}, function(err, schemas) {

        if (err) {
            res.json(500, {error: err.message});
        } else {
            res.json(200, schemas);
        }
    });
};

/**
 * Build a random experiment from a random ExperimentSchema
 */
exports.random = function(req, res) {

    function errorHandler(err) {
        res.json(500, {error: err.message});
    }

    ExperimentSchema.count({}, function(err, count) {

        if (err) {
            return errorHandler(err);
        } else if (count < 1) {
            return errorHandler(new Error('No experiment schemas in' +
                ' database.'));
        } else {

            // Get a random number from [0, number of schema)
            var rand = Math.floor(Math.random() * count);

            // Get a random schema
            ExperimentSchema.find({})
                .skip(rand)
                .limit(1)
                .populate('mediaPool', 'artist title label')
                .exec(function(err, schema) {

                    if (err) {
                        return errorHandler(err);
                    }

                    // Using the controller, build an experiment from this
                    // schema
                    schema[0].buildExperiment(function(err, builtExperiment) {

                        // Send the response
                        res.json(200, builtExperiment);
                    });
                });
        }
    });
};<commit_msg>Change deprecated call to res.json(status, body)<commit_after>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    ExperimentSchema = mongoose.model('ExperimentSchema');

/**
 * List of Experiment schemas
 */
exports.list = function(req, res) {

    ExperimentSchema.find({}, function(err, schemas) {

        if (err) {
            res.json(500, {error: err.message});
        } else {
            res.json(200, schemas);
        }
    });
};

/**
 * Build a random experiment from a random ExperimentSchema
 */
exports.random = function(req, res) {

    function errorHandler(err) {
        res.json(500, {error: err.message});
    }

    ExperimentSchema.count({}, function(err, count) {

        if (err) {
            return errorHandler(err);
        } else if (count < 1) {
            return errorHandler(new Error('No experiment schemas in' +
                ' database.'));
        } else {

            // Get a random number from [0, number of schema)
            var rand = Math.floor(Math.random() * count);

            // Get a random schema
            ExperimentSchema.find({})
                .skip(rand)
                .limit(1)
                .populate('mediaPool', 'artist title label')
                .exec(function(err, schema) {

                    if (err) {
                        return errorHandler(err);
                    }

                    // Using the controller, build an experiment from this
                    // schema
                    schema[0].buildExperiment(function(err, builtExperiment) {

                        // Send the response
                        res.status(200).json(builtExperiment);
                    });
                });
        }
    });
};<|endoftext|>


<commit_before>var async = require("async");
var moment = require("moment");
var fs = require("fs-extra");

/*

TODO: BUG FIX FOR MULTIPLE IMAGES IN POST

"when a Day ONE entry contains more than one image it seems that

1) only the first image is converted
2) the old path is left in place for the other images
3) but it also looks like those images are not part of the new folder either
"

*/

module.exports = function(json, outputDirectory, callback) {
  async.eachSeries(
    json.entries,
    function(input, next) {
      var entry = {};

      entry.tags = input.tags || [];
      entry.created = entry.dateStamp = moment
        .utc(input.creationDate)
        .valueOf();
      entry.metadata = {};

      if (input.starred) {
        entry.metadata.Starred = "yes";
      }

      if (input.weather) entry.metadata.Weather = input.weather.weatherCode;
      if (input.location)
        entry.metadata.Coordinates =
          input.location.latitude + ", " + input.location.longitude;

      var id = input.text.match(/!\[\]\(dayone-moment:\/\/([^.\),]+)\)/)[1];
      // console.log(id);

      var image =
        "_images/" +
        input.photos.filter(function(i) {
          return i.identifier === id;
        })[0].md5 +
        ".jpeg";

      // console.log(image);

      input.text = input.text.split("dayone-moment://" + id).join(image);

      // input.text = input.text.split('dayone-moment://F37015BF4E5840F192BE44E13EFCAF23')

      var file = [];

      file.push("Date: " + moment(entry.dateStamp).format('MMMM Do YYYY, h:mm:ss a'));

      for (var i in entry.metadata) file.push(i + ": " + entry.metadata[i]);

      if (file.length) file.push("");
      file.push(input.text);

      file = file.join('\n');

      // console.log(input);
      console.log(entry);

      var lines = input.text.trim().split('\n');

      lines = lines.filter(function(line){
        return line.indexOf('![') === -1 && line.indexOf('://') === -1;
      });

      if (lines.length) slug = lines[0].split('/').join('-').split(' ').join('-').toLowerCase();

      slug = slug.split('.').join('');
      slug = slug.split(',').join('');
      slug = slug.split('/').join('');
      slug = slug.split('/').join('');
      slug = slug.split('\'').join('');

      while (slug.indexOf('--') > -1)
        slug = slug.split('--').join('-');

      fs.writeFile(
        outputDirectory + "/" + moment(entry.dateStamp).format('YYYY-MM-DD-') + (slug || 'untitled') + ".txt",
        file,
        next
      );
    },
    callback
  );
};
<commit_msg>Handle no image in Day One importer<commit_after>var async = require("async");
var moment = require("moment");
var fs = require("fs-extra");

/*

TODO: BUG FIX FOR MULTIPLE IMAGES IN POST

"when a Day ONE entry contains more than one image it seems that

1) only the first image is converted
2) the old path is left in place for the other images
3) but it also looks like those images are not part of the new folder either
"

*/

module.exports = function(json, outputDirectory, callback) {
  async.eachSeries(
    json.entries,
    function(input, next) {
      var entry = {};

      entry.tags = input.tags || [];
      entry.created = entry.dateStamp = moment
        .utc(input.creationDate)
        .valueOf();
      entry.metadata = {};

      if (input.starred) {
        entry.metadata.Starred = "yes";
      }

      if (input.weather) entry.metadata.Weather = input.weather.weatherCode;
      if (input.location)
        entry.metadata.Coordinates =
          input.location.latitude + ", " + input.location.longitude;

      var id;

      try {
        id = input.text.match(/!\[\]\(dayone-moment:\/\/([^.\),]+)\)/)[1];
      } catch (e) {
        console.log("WARNING no id:", input.text);
      }

      if (id) {
        var image =
          "_images/" +
          input.photos.filter(function(i) {
            return i.identifier === id;
          })[0].md5 +
          ".jpeg";

        // console.log(image);

        input.text = input.text.split("dayone-moment://" + id).join(image);
      }

      // input.text = input.text.split('dayone-moment://F37015BF4E5840F192BE44E13EFCAF23')

      var file = [];

      file.push(
        "Date: " + moment(entry.dateStamp).format("MMMM Do YYYY, h:mm:ss a")
      );

      for (var i in entry.metadata) file.push(i + ": " + entry.metadata[i]);

      if (file.length) file.push("");
      file.push(input.text);

      file = file.join("\n");

      // console.log(input);
      console.log(entry);

      var lines = input.text.trim().split("\n");

      lines = lines.filter(function(line) {
        return line.indexOf("![") === -1 && line.indexOf("://") === -1;
      });

      if (lines.length)
        slug = lines[0]
          .split("/")
          .join("-")
          .split(" ")
          .join("-")
          .toLowerCase();

      slug = slug.split(".").join("");
      slug = slug.split(",").join("");
      slug = slug.split("/").join("");
      slug = slug.split("/").join("");
      slug = slug.split("'").join("");

      while (slug.indexOf("--") > -1) slug = slug.split("--").join("-");

      slug = slug.slice(0,20);

      fs.writeFile(
        outputDirectory +
          "/" +
          moment(entry.dateStamp).format("YYYY-MM-DD-") +
          (slug || "untitled") +
          ".txt",
        file,
        next
      );
    },
    callback
  );
};
<|endoftext|>


<commit_before>#!/usr/bin/env node

var path = require('path'),
    fs = require('fs'),
    readInstalled = require("read-installed"),
    osenv = require('osenv'),
    npmconf = require('npmconf'),
    parse = require('url').parse;

var ostemp = osenv.tmpdir();
var oshome = osenv.home();
var regHost = undefined;

var cwd = process.cwd(),
    cache = findCache(),
    tmp = findTmp();

function findCache () {
  return process.platform === "win32"
            ? path.resolve(process.env.APPDATA || oshome || ostemp, "npm-cache")
            : path.resolve( oshome || ostemp, ".npm");
}

function findTmp () {
  return process.platform === "win32"
            ? path.resolve(ostemp, "npm-cache")
            : path.resolve("/tmp", ".npm");
}

function relock () {
  var packages = {};
  npmconf.load(function (err, conf) {
    if (err) {
      throw err;
    }
    regHost = parse(conf.get('registry')).host;
    readInstalled(cwd, void 0, function (er, data) {
      if (er) throw er;
      //console.log(data);
      if (data.dependencies) {
        Object.keys(data.dependencies).forEach(function (key) {
          walk(data.dependencies[key], packages);
        });
      }
      fs.writeFile(path.join(cwd, 'lockdown.json'), JSON.stringify(sortObj(packages), null, '  ') + '\n');
    });
  });
}

// we take advantage of the way JSON.stringify() is implemented to
// write sorted lockdown.json files for better diffs.
function sortObj(obj) {
  if (typeof obj === 'object' && obj !== null) {
    var sorted = {};
    Object.keys(obj).sort().forEach(function(k) {
      sorted[k] = sortObj(obj[k]);
    });
    return sorted;
  } else if (Array.isArray(obj)) {
    return obj.sort().map(sortObj);
  }
  return obj;
}

function walk (data, packages) {
  var name, version, shasum;
  if (data.name) name = data.name;
  if (data.version) version = data.version;

  if (name) {
    shasum = getShasum(cache, name, version);
    if (!(name in packages)) packages[name] = {};
    packages[name][version] = shasum;
  }

  if (data.dependencies) {
    Object.keys(data.dependencies).forEach(function (key) {
      // ignore bundled dependencies
      if (data.bundleDependencies && data.bundleDependencies.indexOf(key) > -1 ) return;
      walk(data.dependencies[key], packages);
    });
  }
}

function getShasum (cache, name, version) {
  var sha;
  try {
    // find sha in cache/name/version/.cache.json
    sha = require(path.resolve(path.join(cache, name, version, ".cache.json"))).dist.shasum;
  } catch (e) {
    try {
      // find sha in cache/name/.cache.json
      sha = require(path.resolve(path.join(cache, name, ".cache.json"))).versions[version].dist.shasum;
    } catch (e) {
      try {
        // find sha in cache/regHost/name/version/.cache.json
        sha = require(path.resolve(path.join(cache, regHost, name, version, ".cache.json"))).dist.shasum;
      } catch (e) {
        try {
          // find sha in cache/regHost/name/.cache.json
          sha = require(path.resolve(path.join(cache, regHost, name, ".cache.json"))).versions[version].dist.shasum
        } catch (e) {
          try {
            // find sha in {cwd}/node_modules/name/package.json
            var package_data = require(path.resolve(path.join(cwd, 'node_modules', name, "package.json")));
            sha = package_data.dist && package_data.dist.shasum || package_data._shasum;
          } catch (e) {}
        }
      }
    }
  }
  // finally, check in the tmp directory
  if (!sha && cache !== tmp) return getShasum(tmp, name, version);

  if (!sha) console.error("Warning: no shasum for "+name+"@"+version);

  return sha || "*";
}

exports.relock = relock;

if (fs.realpathSync(process.argv[1]) === fs.realpathSync(__filename)) relock();

<commit_msg>add additional folders to search for sha checksum<commit_after>#!/usr/bin/env node

var path = require('path'),
    fs = require('fs'),
    readInstalled = require("read-installed"),
    osenv = require('osenv'),
    npmconf = require('npmconf'),
    parse = require('url').parse;

var ostemp = osenv.tmpdir();
var oshome = osenv.home();
var regHost = undefined;

var cwd = process.cwd(),
    cache = findCache(),
    tmp = findTmp();

function findCache () {
  return process.platform === "win32"
            ? path.resolve(process.env.APPDATA || oshome || ostemp, "npm-cache")
            : path.resolve( oshome || ostemp, ".npm");
}

function findTmp () {
  return process.platform === "win32"
            ? path.resolve(ostemp, "npm-cache")
            : path.resolve("/tmp", ".npm");
}

function relock () {
  var packages = {};
  npmconf.load(function (err, conf) {
    if (err) {
      throw err;
    }
    regHost = parse(conf.get('registry')).host;
    readInstalled(cwd, void 0, function (er, data) {
      if (er) throw er;
      //console.log(data);
      if (data.dependencies) {
        Object.keys(data.dependencies).forEach(function (key) {
          walk(data.dependencies[key], packages);
        });
      }
      fs.writeFile(path.join(cwd, 'lockdown.json'), JSON.stringify(sortObj(packages), null, '  ') + '\n');
    });
  });
}

// we take advantage of the way JSON.stringify() is implemented to
// write sorted lockdown.json files for better diffs.
function sortObj(obj) {
  if (typeof obj === 'object' && obj !== null) {
    var sorted = {};
    Object.keys(obj).sort().forEach(function(k) {
      sorted[k] = sortObj(obj[k]);
    });
    return sorted;
  } else if (Array.isArray(obj)) {
    return obj.sort().map(sortObj);
  }
  return obj;
}

function walk (data, packages) {
  var name, version, shasum;
  if (data.name) name = data.name;
  if (data.version) version = data.version;

  if (name) {
    shasum = getShasum(cache, name, version);
    if (!(name in packages)) packages[name] = {};
    packages[name][version] = shasum;
  }

  if (data.dependencies) {
    Object.keys(data.dependencies).forEach(function (key) {
      // ignore bundled dependencies
      if (data.bundleDependencies && data.bundleDependencies.indexOf(key) > -1 ) return;
      walk(data.dependencies[key], packages);
    });
  }
}

function getShasum (cache, name, version) {
  var sha;
  try {
    // find sha in cache/name/version/.cache.json
    sha = require(path.resolve(path.join(cache, name, version, ".cache.json"))).dist.shasum;
  } catch (e) {
    try {
      // find sha in cache/name/.cache.json
      sha = require(path.resolve(path.join(cache, name, ".cache.json"))).versions[version].dist.shasum;
    } catch (e) {
      try {
        // find sha in cache/regHost/name/version/.cache.json
        sha = require(path.resolve(path.join(cache, regHost, name, version, ".cache.json"))).dist.shasum;
      } catch (e) {
        try {
          // find sha in cache/regHost/name/.cache.json
          sha = require(path.resolve(path.join(cache, regHost, name, ".cache.json"))).versions[version].dist.shasum
        } catch (e) {
          try {
            // find sha in cache/name/version/package.json
            sha = require(path.resolve(path.join(cache, name, version, "package", "package.json")))._shasum
          } catch (e) {
            try {
              // find sha in node_modules/name/package.json
              sha = require(path.resolve(path.join("node_modules", name, "package.json")))._shasum
            } catch (e) {

            }
          }
        }
      }
    }
  }
  // finally, check in the tmp directory
  if (!sha && cache !== tmp) return getShasum(tmp, name, version);

  if (!sha) console.error("Warning: no shasum for "+name+"@"+version);

  return sha || "*";
}

exports.relock = relock;

if (fs.realpathSync(process.argv[1]) === fs.realpathSync(__filename)) relock();

<|endoftext|>


<commit_before>;(function()
{
	// CommonJS
	typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;

	function Brush()
	{
		// Contributed by David Simmons-Duffin and Marty Kube

		var funcs =
			'abs accept alarm atan2 bind binmode chdir chmod chomp chop chown chr ' +
			'chroot close closedir connect cos crypt defined delete each endgrent ' +
			'endhostent endnetent endprotoent endpwent endservent eof exec exists ' +
			'exp fcntl fileno flock fork format formline getc getgrent getgrgid ' +
			'getgrnam gethostbyaddr gethostbyname gethostent getlogin getnetbyaddr ' +
			'getnetbyname getnetent getpeername getpgrp getppid getpriority ' +
			'getprotobyname getprotobynumber getprotoent getpwent getpwnam getpwuid ' +
			'getservbyname getservbyport getservent getsockname getsockopt glob ' +
			'gmtime grep hex index int ioctl join keys kill lc lcfirst length link ' +
			'listen localtime lock log lstat map mkdir msgctl msgget msgrcv msgsnd ' +
			'oct open opendir ord pack pipe pop pos print printf prototype push ' +
			'quotemeta rand read readdir readline readlink readpipe recv rename ' +
			'reset reverse rewinddir rindex rmdir scalar seek seekdir select semctl ' +
			'semget semop send setgrent sethostent setnetent setpgrp setpriority ' +
			'setprotoent setpwent setservent setsockopt shift shmctl shmget shmread ' +
			'shmwrite shutdown sin sleep socket socketpair sort splice split sprintf ' +
			'sqrt srand stat study substr symlink syscall sysopen sysread sysseek ' +
			'system syswrite tell telldir time times tr truncate uc ucfirst umask ' +
			'undef unlink unpack unshift utime values vec wait waitpid warn write';

		var keywords =
			'bless caller continue dbmclose dbmopen die do dump else elsif eval exit ' +
			'for foreach goto if import last local my next no our package redo ref ' +
			'require return sub tie tied unless untie until use wantarray while';

		this.regexList = [
			{ regex: /<<((\w+)|(['"])(.+?)\2)[\s\S]+?\n\2\4\n/g,	css: 'string' },    	// here doc
			{ regex: /#.*$/gm,										css: 'comments' },
			{ regex: /^#!.*\n/g,									css: 'preprocessor' },	// shebang
			{ regex: SyntaxHighlighter.regexLib.doubleQuotedString,	css: 'string' },
			{ regex: SyntaxHighlighter.regexLib.singleQuotedString,	css: 'string' },
			// currently ignoring single quote package separator and utf8 names
			{ regex: /(?:[$@%*]|\$#)[a-zA-Z_](\w+|::)*/g,   		css: 'variable' },
			{ regex: /\b__(?:END|DATA)__\b[\s\S]*$/g,				css: 'comments' },
			{ regex: /^=\w[\s\S]*?\n=cut\s*$/gm,					css: 'comments' },		// pod
			{ regex: new RegExp(this.getKeywords(funcs), 'gm'),		css: 'functions' },
			{ regex: new RegExp(this.getKeywords(keywords), 'gm'),	css: 'keyword' }
		];

		this.forHtmlScript(SyntaxHighlighter.regexLib.phpScriptTags);
	}

	Brush.prototype	= new SyntaxHighlighter.Highlighter();
	Brush.aliases		= ['perl', 'Perl', 'pl'];

	SyntaxHighlighter.brushes.Perl = Brush;

	// CommonJS
	typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
})();
<commit_msg>Add a few "keywords" that are common in modern perl<commit_after>;(function()
{
	// CommonJS
	typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;

	function Brush()
	{
		// Contributed by David Simmons-Duffin and Marty Kube

		var funcs =
			'abs accept alarm atan2 bind binmode chdir chmod chomp chop chown chr ' +
			'chroot close closedir connect cos crypt defined delete each endgrent ' +
			'endhostent endnetent endprotoent endpwent endservent eof exec exists ' +
			'exp fcntl fileno flock fork format formline getc getgrent getgrgid ' +
			'getgrnam gethostbyaddr gethostbyname gethostent getlogin getnetbyaddr ' +
			'getnetbyname getnetent getpeername getpgrp getppid getpriority ' +
			'getprotobyname getprotobynumber getprotoent getpwent getpwnam getpwuid ' +
			'getservbyname getservbyport getservent getsockname getsockopt glob ' +
			'gmtime grep hex index int ioctl join keys kill lc lcfirst length link ' +
			'listen localtime lock log lstat map mkdir msgctl msgget msgrcv msgsnd ' +
			'oct open opendir ord pack pipe pop pos print printf prototype push ' +
			'quotemeta rand read readdir readline readlink readpipe recv rename ' +
			'reset reverse rewinddir rindex rmdir scalar seek seekdir select semctl ' +
			'semget semop send setgrent sethostent setnetent setpgrp setpriority ' +
			'setprotoent setpwent setservent setsockopt shift shmctl shmget shmread ' +
			'shmwrite shutdown sin sleep socket socketpair sort splice split sprintf ' +
			'sqrt srand stat study substr symlink syscall sysopen sysread sysseek ' +
			'system syswrite tell telldir time times tr truncate uc ucfirst umask ' +
			'undef unlink unpack unshift utime values vec wait waitpid warn write ' +
			// feature
			'say';

		var keywords =
			'bless caller continue dbmclose dbmopen die do dump else elsif eval exit ' +
			'for foreach goto if import last local my next no our package redo ref ' +
			'require return sub tie tied unless untie until use wantarray while ' +
			// feature
			'given when default ' +
			// Try::Tiny
			'try catch finally ' +
			// Moose
			'has extends with before after around override augment';

		this.regexList = [
			{ regex: /<<((\w+)|(['"])(.+?)\2)[\s\S]+?\n\2\4\n/g,	css: 'string' },    	// here doc
			{ regex: /#.*$/gm,										css: 'comments' },
			{ regex: /^#!.*\n/g,									css: 'preprocessor' },	// shebang
			{ regex: SyntaxHighlighter.regexLib.doubleQuotedString,	css: 'string' },
			{ regex: SyntaxHighlighter.regexLib.singleQuotedString,	css: 'string' },
			// currently ignoring single quote package separator and utf8 names
			{ regex: /(?:[$@%*]|\$#)[a-zA-Z_](\w+|::)*/g,   		css: 'variable' },
			{ regex: /\b__(?:END|DATA)__\b[\s\S]*$/g,				css: 'comments' },
			{ regex: /^=\w[\s\S]*?\n=cut\s*$/gm,					css: 'comments' },		// pod
			{ regex: new RegExp(this.getKeywords(funcs), 'gm'),		css: 'functions' },
			{ regex: new RegExp(this.getKeywords(keywords), 'gm'),	css: 'keyword' }
		];

		this.forHtmlScript(SyntaxHighlighter.regexLib.phpScriptTags);
	}

	Brush.prototype	= new SyntaxHighlighter.Highlighter();
	Brush.aliases		= ['perl', 'Perl', 'pl'];

	SyntaxHighlighter.brushes.Perl = Brush;

	// CommonJS
	typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
})();
<|endoftext|>