<commit_before>import _ from 'underscore';
import validateDeck from '../deck-validator.js';

function selectDeck(state, deck) {
    if(state.decks && state.decks.length !== 0) {
        state.selectedDeck = deck;
    } else {
        delete state.selectedDeck;
    }

    return state;
}

function processDecks(decks, state) {
    _.each(decks, deck => {
        if(!state.cards || !deck.faction) {
            deck.status = {};
            return;
        }

        deck.faction = state.factions[deck.faction.value];
        if(deck.agenda) {
            deck.agenda = state.agendas[deck.agenda.code];
        }

        if(deck.bannerCards) {
            deck.bannerCards = _.map(deck.bannerCards, card => state.cards[card.code]);
        }

        deck.plotCards = processCardCounts(deck.plotCards, state.cards);
        deck.drawCards = processCardCounts(deck.drawCards, state.cards);

        deck.status = validateDeck(deck, { packs: state.packs, restrictedList: state.restrictedList });
    });
}

function processCardCounts(cardCounts, cardData) {
    let cardCountsWithData = cardCounts.map(cardCount => {
        return { count: cardCount.count, card: cardCount.card.custom ? cardCount.card : cardData[cardCount.card.code] };
    });

    // Filter out any cards that aren't available in the card data.
    return cardCountsWithData.filter(cardCount => !!cardCount.card);
}

export default function(state = {}, action) {
    let newState;
    switch(action.type) {
        case 'RECEIVE_CARDS':
            var agendas = {};

            _.each(action.response.cards, card => {
                if(card.type === 'agenda') {
                    agendas[card.code] = card;
                }
            });

            var banners = _.filter(agendas, card => {
                return card.label.startsWith('Banner of the');
            });

            newState = Object.assign({}, state, {
                cards: action.response.cards,
                agendas: agendas,
                banners: banners
            });

            // In case the card list is received after the decks, updated the decks now
            processDecks(newState.decks, newState);

            return newState;
        case 'RECEIVE_PACKS':
            return Object.assign({}, state, {
                packs: action.response.packs
            });
        case 'RECEIVE_FACTIONS':
            var factions = {};

            _.each(action.response.factions, faction => {
                factions[faction.value] = faction;
            });

            return Object.assign({}, state, {
                factions: factions
            });
        case 'RECEIVE_RESTRICTED_LIST':
            return Object.assign({}, state, {
                restrictedList: action.response.restrictedList
            });
        case 'ZOOM_CARD':
            return Object.assign({}, state, {
                zoomCard: action.card
            });
        case 'CLEAR_ZOOM':
            return Object.assign({}, state, {
                zoomCard: undefined
            });
        case 'RECEIVE_DECKS':
            processDecks(action.response.decks, state);
            newState = Object.assign({}, state, {
                singleDeck: false,
                decks: action.response.decks
            });

            newState = selectDeck(newState, newState.decks[0]);

            return newState;
        case 'REQUEST_DECK':
            return Object.assign({}, state, {
                deckSaved: false,
                deckDeleted: false
            });
        case 'REQUEST_DECKS':
            newState = Object.assign({}, state, {
                deckSaved: false,
                deckDeleted: false
            });

            if(newState.selectedDeck && !newState.selectedDeck._id) {
                if(_.size(newState.decks) > 0) {
                    newState.selectedDeck = newState.decks[0];
                }
            }

            return newState;
        case 'RECEIVE_DECK':
            newState = Object.assign({}, state, {
                singleDeck: true,
                deckSaved: false
            });

            processDecks([action.response.deck], state);

            newState.decks = _.map(state.decks, deck => {
                if(action.response.deck._id === deck.id) {
                    return deck;
                }

                return deck;
            });

            if(!_.any(newState.decks, deck => {
                return deck._id === action.response.deck._id;
            })) {
                newState.decks.push(action.response.deck);
            }

            var selected = _.find(newState.decks, deck => {
                return deck._id === action.response.deck._id;
            });

            newState = selectDeck(newState, selected);

            return newState;
        case 'SELECT_DECK':
            newState = Object.assign({}, state, {
                selectedDeck: action.deck,
                deckSaved: false
            });

            if(newState.selectedDeck) {
                processDecks([newState.selectedDeck], state);
            }

            return newState;
        case 'ADD_DECK':
            var newDeck = { name: 'New Deck', drawCards: [], plotCards: [] };

            newState = Object.assign({}, state, {
                selectedDeck: newDeck,
                deckSaved: false
            });

            processDecks([newState.selectedDeck], state);

            return newState;
        case 'UPDATE_DECK':
            newState = Object.assign({}, state, {
                selectedDeck: action.deck,
                deckSaved: false
            });

            if(newState.selectedDeck) {
                processDecks([newState.selectedDeck], state);
            }

            return newState;
        case 'SAVE_DECK':
            newState = Object.assign({}, state, {
                deckSaved: false
            });

            return newState;
        case 'DECK_SAVED':
            newState = Object.assign({}, state, {
                deckSaved: true,
                decks: undefined
            });

            return newState;
        case 'DECK_DELETED':
            newState = Object.assign({}, state, {
                deckDeleted: true
            });

            newState.decks = _.reject(newState.decks, deck => {
                return deck._id === action.response.deckId;
            });

            newState.selectedDeck = _.first(newState.decks);

            return newState;
        case 'CLEAR_DECK_STATUS':
            return Object.assign({}, state, {
                deckDeleted: false,
                deckSaved: false
            });
        default:
            return state;
    }
}
<commit_msg>Delay validation until restricted list loads (#1856)<commit_after>import _ from 'underscore';
import validateDeck from '../deck-validator.js';

function selectDeck(state, deck) {
    if(state.decks && state.decks.length !== 0) {
        state.selectedDeck = deck;
    } else {
        delete state.selectedDeck;
    }

    return state;
}

function processDecks(decks, state) {
    _.each(decks, deck => {
        if(!state.cards || !deck.faction) {
            deck.status = {};
            return;
        }

        deck.faction = state.factions[deck.faction.value];
        if(deck.agenda) {
            deck.agenda = state.agendas[deck.agenda.code];
        }

        if(deck.bannerCards) {
            deck.bannerCards = _.map(deck.bannerCards, card => state.cards[card.code]);
        }

        deck.plotCards = processCardCounts(deck.plotCards, state.cards);
        deck.drawCards = processCardCounts(deck.drawCards, state.cards);

        if(!state.restrictedList) {
            deck.status = {};
        } else {
            deck.status = validateDeck(deck, { packs: state.packs, restrictedList: state.restrictedList });
        }
    });
}

function processCardCounts(cardCounts, cardData) {
    let cardCountsWithData = cardCounts.map(cardCount => {
        return { count: cardCount.count, card: cardCount.card.custom ? cardCount.card : cardData[cardCount.card.code] };
    });

    // Filter out any cards that aren't available in the card data.
    return cardCountsWithData.filter(cardCount => !!cardCount.card);
}

export default function(state = {}, action) {
    let newState;
    switch(action.type) {
        case 'RECEIVE_CARDS':
            var agendas = {};

            _.each(action.response.cards, card => {
                if(card.type === 'agenda') {
                    agendas[card.code] = card;
                }
            });

            var banners = _.filter(agendas, card => {
                return card.label.startsWith('Banner of the');
            });

            newState = Object.assign({}, state, {
                cards: action.response.cards,
                agendas: agendas,
                banners: banners
            });

            // In case the card list is received after the decks, updated the decks now
            processDecks(newState.decks, newState);

            return newState;
        case 'RECEIVE_PACKS':
            return Object.assign({}, state, {
                packs: action.response.packs
            });
        case 'RECEIVE_FACTIONS':
            var factions = {};

            _.each(action.response.factions, faction => {
                factions[faction.value] = faction;
            });

            return Object.assign({}, state, {
                factions: factions
            });
        case 'RECEIVE_RESTRICTED_LIST':
            newState = Object.assign({}, state, {
                restrictedList: action.response.restrictedList
            });

            // In case the restricted list is received after the decks, updated the decks now
            processDecks(newState.decks, newState);

            return newState;
        case 'ZOOM_CARD':
            return Object.assign({}, state, {
                zoomCard: action.card
            });
        case 'CLEAR_ZOOM':
            return Object.assign({}, state, {
                zoomCard: undefined
            });
        case 'RECEIVE_DECKS':
            processDecks(action.response.decks, state);
            newState = Object.assign({}, state, {
                singleDeck: false,
                decks: action.response.decks
            });

            newState = selectDeck(newState, newState.decks[0]);

            return newState;
        case 'REQUEST_DECK':
            return Object.assign({}, state, {
                deckSaved: false,
                deckDeleted: false
            });
        case 'REQUEST_DECKS':
            newState = Object.assign({}, state, {
                deckSaved: false,
                deckDeleted: false
            });

            if(newState.selectedDeck && !newState.selectedDeck._id) {
                if(_.size(newState.decks) > 0) {
                    newState.selectedDeck = newState.decks[0];
                }
            }

            return newState;
        case 'RECEIVE_DECK':
            newState = Object.assign({}, state, {
                singleDeck: true,
                deckSaved: false
            });

            processDecks([action.response.deck], state);

            newState.decks = _.map(state.decks, deck => {
                if(action.response.deck._id === deck.id) {
                    return deck;
                }

                return deck;
            });

            if(!_.any(newState.decks, deck => {
                return deck._id === action.response.deck._id;
            })) {
                newState.decks.push(action.response.deck);
            }

            var selected = _.find(newState.decks, deck => {
                return deck._id === action.response.deck._id;
            });

            newState = selectDeck(newState, selected);

            return newState;
        case 'SELECT_DECK':
            newState = Object.assign({}, state, {
                selectedDeck: action.deck,
                deckSaved: false
            });

            if(newState.selectedDeck) {
                processDecks([newState.selectedDeck], state);
            }

            return newState;
        case 'ADD_DECK':
            var newDeck = { name: 'New Deck', drawCards: [], plotCards: [] };

            newState = Object.assign({}, state, {
                selectedDeck: newDeck,
                deckSaved: false
            });

            processDecks([newState.selectedDeck], state);

            return newState;
        case 'UPDATE_DECK':
            newState = Object.assign({}, state, {
                selectedDeck: action.deck,
                deckSaved: false
            });

            if(newState.selectedDeck) {
                processDecks([newState.selectedDeck], state);
            }

            return newState;
        case 'SAVE_DECK':
            newState = Object.assign({}, state, {
                deckSaved: false
            });

            return newState;
        case 'DECK_SAVED':
            newState = Object.assign({}, state, {
                deckSaved: true,
                decks: undefined
            });

            return newState;
        case 'DECK_DELETED':
            newState = Object.assign({}, state, {
                deckDeleted: true
            });

            newState.decks = _.reject(newState.decks, deck => {
                return deck._id === action.response.deckId;
            });

            newState.selectedDeck = _.first(newState.decks);

            return newState;
        case 'CLEAR_DECK_STATUS':
            return Object.assign({}, state, {
                deckDeleted: false,
                deckSaved: false
            });
        default:
            return state;
    }
}
<|endoftext|>


<commit_before>import {
  GET_TASKS,
  CLEAR_TASKS,
  NEW_TASK,
  DELETE_TASK,
  EDIT_TASK,
  ADD_TIME_TO_PROJECT,
  TOGGLE_DONE,
  FETCH_TASKS,
  SUBTRACT_TASK_TIME,
  ADD_TIMELOG
} from '../actions/actionTypes';

export function tasks(state = { list: [], project: undefined }, action) {
  switch (action.type) {
    case FETCH_TASKS:
      return { ...state, isFetching: action.response };
    case GET_TASKS:
      return {
        ...state,
        list: action.response.list,
        project: {
          ...action.response.project,
          initialTime: action.response.project.timeSpent
        },
        isFetching: false
      };
    case CLEAR_TASKS:
      return { ...state, list: action.response };
    case NEW_TASK: {
      return { ...state, list: [...state.list, action.task] };
    }
    case DELETE_TASK: {
      return {
        ...state,
        list: state.list.filter(item => item._id !== action.id)
      };
    }
    case EDIT_TASK: {
      let sameProject = false;
      const tasksList = state.list.map(item => {
        if (item._id === action.id) {
          item.name = action.name; // eslint-disable-line no-param-reassign
          if (item.project !== action.newProject) {
            item.project = action.newProject; // eslint-disable-line no-param-reassign
          } else {
            sameProject = true;
          }
        }
        return item;
      });
      if (sameProject) {
        return { ...state, list: tasksList };
      }
      return {
        ...state,
        list: tasksList.filter(item => item.project !== action.newProject)
      };
    }
    case TOGGLE_DONE: {
      const tasksList = state.list
        .map(item => {
          if (item._id === action.id) {
            return undefined;
          }
          return item;
        })
        .filter(item => item !== undefined);
      return { ...state, list: tasksList };
    }
    case ADD_TIME_TO_PROJECT:
    case ADD_TIMELOG: {
      const tasksList = state.list.map(item => {
        if (item._id === action.data.task._id) {
          item.timeSpent += action.seconds; // eslint-disable-line no-param-reassign
        }
        return item;
      });
      const project = {
        ...state.project,
        timeSpent: state.project.timeSpent + action.seconds
      };
      return { ...state, list: tasksList, project };
    }
    case SUBTRACT_TASK_TIME: {
      const project = {
        ...state.project,
        timeSpent: state.project.timeSpent - action.timeSpent
      };
      return { ...state, project };
    }
    default:
      return state;
  }
}

export default tasks;
<commit_msg>new state shape to not load all the tasks on each request<commit_after>import deepClone from 'lodash.clonedeep';
import {
  GET_TASKS,
  NEW_TASK,
  DELETE_TASK,
  EDIT_TASK,
  ADD_TIME_TO_PROJECT,
  TOGGLE_DONE,
  FETCH_TASKS,
  SUBTRACT_TASK_TIME,
  ADD_TIMELOG
} from '../actions/actionTypes';

export function tasks(state = { list: [] }, action) {
  switch (action.type) {
    case FETCH_TASKS:
      return { ...state, isFetching: action.response };
    case GET_TASKS: {
      let newProject = true;
      let newState = state.list.map(item => {
        const newItem = deepClone(item);
        if (item.project._id === action.response.project._id) {
          newProject = false;
          newItem.list = action.response.list || newItem.list;
          newItem.doneList = action.response.doneList || newItem.doneList;
          newItem.project = {
            ...action.response.project,
            initialTime: action.response.project.timeSpent
          };
        }
        return newItem;
      });
      if (newProject) {
        newState = [
          ...state.list,
          {
            list: action.response.list,
            doneList: action.response.doneList,
            project: {
              ...action.response.project,
              initialTime: action.response.project.timeSpent
            }
          }
        ];
      }
      return { list: newState, isFetching: false };
    }
    case NEW_TASK: {
      const newList = state.list.map(item => {
        if (item.project._id === action.task.project) {
          const newItem = deepClone(item);
          newItem.list.push(action.task);
          return newItem;
        }
        return item;
      });
      return { ...state, list: newList };
    }
    case DELETE_TASK: {
      const newList = state.list.map(item => {
        if (item.project._id === action.projectId) {
          const newItem = deepClone(item);
          newItem.list = newItem.list.filter(task => task._id !== action.id);
          return newItem;
        }
        return item;
      });
      return { ...state, list: newList };
    }
    case EDIT_TASK: {
      let editedTask;
      let addList;
      const toBeMoved = action.currentProject !== action.newProject;
      const newList = state.list.map(item => {
        if (item.project._id === action.currentProject) {
          const newItem = deepClone(item);
          newItem.list = newItem.list
            .map(task => {
              const newTask = { ...task };
              if (task._id === action.id) {
                newTask.name = action.name;
                editedTask = newTask;
                if (toBeMoved) {
                  return undefined;
                }
              }
              return newTask;
            })
            .filter(edited => edited !== undefined);
          return newItem;
        }
        return item;
      });
      if (toBeMoved) {
        addList = newList.map(myItem => {
          if (myItem.project._id === action.newProject) {
            const newItem = deepClone(myItem);
            newItem.list.push(editedTask);
            return newItem;
          }
          return myItem;
        });
      }
      return { ...state, list: addList || newList };
    }
    case TOGGLE_DONE: {
      let newList = state.list;
      let taskBuffer;
      newList = state.list.map(item => {
        const newItem = deepClone(item);
        if (item.project._id === action.projectId) {
          if (action.done) {
            newItem.list = newItem.list.filter(task => {
              if (task._id === action.id) {
                taskBuffer = task;
                taskBuffer.done = true;
              }
              return task._id !== action.id;
            });
            if (newItem.doneList) {
              newItem.doneList = [...newItem.doneList, taskBuffer];
            }
          } else if (action.done === false) {
            newItem.doneList = newItem.doneList.filter(task => {
              if (task._id === action.id) {
                taskBuffer = task;
                taskBuffer.done = false;
              }
              return task._id !== action.id;
            });
            if (newItem.list) {
              newItem.list = [...newItem.list, taskBuffer];
            }
          }
          return newItem;
        }
        return newItem;
      });

      return { ...state, list: newList };
    }
    case ADD_TIME_TO_PROJECT:
    case ADD_TIMELOG: {
      const newList = state.list.map(item => {
        const newItem = { ...item };
        if (item.project._id === action.data.project._id) {
          newItem.list = newItem.list.map(task => {
            const newTask = deepClone(task);
            if (task._id === action.data.task._id) {
              newTask.timeSpent += action.seconds;
            }
            return newTask;
          });
          newItem.project.timeSpent += action.seconds;
          return newItem;
        }
        return newItem;
      });
      return { ...state, list: newList };
    }
    case SUBTRACT_TASK_TIME: {
      if (!action.params.deleteTime && !action.params.moveTime) {
        return state;
      }
      const newList = state.list.map(item => {
        const newItem = deepClone(item);
        if (
          item.project._id === action.params.currentProject &&
          action.params.deleteTime
        ) {
          const project = {
            ...newItem.project,
            timeSpent:
              newItem.project.timeSpent - (action.params.timeSpent || 0)
          };
          newItem.project = project;
        }
        if (
          item.project._id === action.params.newProject &&
          action.params.moveTime
        ) {
          const project = {
            ...newItem.project,
            timeSpent:
              newItem.project.timeSpent + (action.params.timeSpent || 0)
          };
          newItem.project = project;
        }
        return newItem;
      });
      return { ...state, list: newList };
    }
    default:
      return state;
  }
}

export default tasks;
<|endoftext|>


<commit_before>import _ from 'lodash';

/* global process */
let env = process.env;

let config = {

    general: {
        title: 'StarHackIt',
        description: 'StarHackIt is a fullstack boilerplate written in es6/es7',
        apiUrl: '/api/v1/',
        analytics: {
            google: ""
        },
        socialAuth: {
            facebook: true,
            fidor: true
        }
    },

    development: {
        env: "development"
    },

    production: {
        env: "production"

    }
};

export default _.extend( {}, config.general, config[ env.NODE_ENV ] );
<commit_msg>fidor off on FE<commit_after>import _ from 'lodash';

/* global process */
let env = process.env;

let config = {

    general: {
        title: 'StarHackIt',
        description: 'StarHackIt is a fullstack boilerplate written in es6/es7',
        apiUrl: '/api/v1/',
        analytics: {
            google: ""
        },
        socialAuth: {
            facebook: true,
            fidor: false
        }
    },

    development: {
        env: "development"
    },

    production: {
        env: "production"

    }
};

export default _.extend( {}, config.general, config[ env.NODE_ENV ] );
<|endoftext|>


<commit_before>sap.ui.define([
	"sap/ui/demo/cardExplorer/controller/BaseController",
	'sap/ui/model/json/JSONModel',
	"sap/ui/model/BindingMode",
	"../model/ExploreNavigationModel",
	"../model/ExploreSettingsModel",
	"sap/m/MessageToast",
	"sap/f/GridContainerItemLayoutData",
	"sap/ui/Device"
], function (
	BaseController,
	JSONModel,
	BindingMode,
	exploreNavigationModel,
	exploreSettingsModel,
	MessageToast,
	GridContainerItemLayoutData,
	Device
) {
	"use strict";

	return BaseController.extend("sap.ui.demo.cardExplorer.controller.ExploreSamples", {

		/**
		 * Called when the controller is instantiated.
		 */
		onInit: function () {
			var oRouter = this.getRouter();
			oRouter.getRoute("exploreSamples").attachMatched(this._onRouteMatched, this);

			this.oModel = new JSONModel();
			this.oModel.setDefaultBindingMode(BindingMode.OneWay);

			this.getView().setModel(this.oModel);
			this.getView().setModel(exploreSettingsModel, "settings");
			this._editor = this.byId("editor");
			//This will prevent all auto complete and suggestions of the editor
			this._editor._oEditor.completers = [];

			//This catches any "json" validation errors that ware made inside the editor
			this._editor._oEditor.session.on("changeAnnotation", this._onSyntaxError.bind(this));

			//This catches any error that was produced by the card
			this.byId("cardSample").attachEvent("_error", this._onCardError, this);

			this._errorMessageStrip = this.getView().byId("errorMessageStrip");
			this._registerResize();

			this.byId("cardSample").attachEvent("action", this._onCardAction, this);
		},

		onExit: function () {
			this._deregisterResize();
		},

		onManifestEdited: function (oEvent) {
			var sValue = oEvent.getParameter("value");

			if (exploreSettingsModel.getProperty("/autoRun")) {
				this._updateSample(sValue);
			}
		},
		onRunPressed: function (oEvent) {
			var sValue = this.getView().byId("editor").getValue();
			this._updateSample(sValue);
		},

		onChangeSplitterOrientation: function (oEvent) {
			//Toggles the value of splitter orientation
			exploreSettingsModel.setProperty("/splitViewVertically", !exploreSettingsModel.getProperty("/splitViewVertically"));
			var isOrientationVertical = exploreSettingsModel.getProperty("/splitViewVertically");
			this.getView().byId("splitView").getRootPaneContainer().setOrientation(isOrientationVertical ? "Vertical" : "Horizontal");
		},

		showError: function (sMessage) {
			this._errorMessageStrip.setVisible(true);
			this._errorMessageStrip.setText(sMessage);
		},

		onSubSampleChange: function (oEvent) {
			var item = oEvent.getParameter('selectedItem');

			this.getRouter().navTo(
				"exploreSamples",
				{
					key: this.oModel.getProperty("/sample").key,
					subSampleKey: item.getKey()
				}
			);
		},

		_onSyntaxError: function () {
			var aErrorAnnotations = this._editor._oEditor.session.$annotations,
				sMessage = "";
			if (aErrorAnnotations.length) {
				aErrorAnnotations.forEach(function (oError) {
					sMessage += "Line " + String(oError.row) + ": " + oError.text + '\n';
				});
				this.showError(sMessage);
			}
		},

		_onCardError: function (oEvent) {
			this.showError(oEvent.getParameters().message);
		},

		_deregisterResize: function () {
			Device.media.detachHandler(this._onResize, this);
		},

		_registerResize: function () {
			Device.media.attachHandler(this._onResize, this);
			this._onResize();
		},

		_onResize: function () {
			var isOrientationVertical = exploreSettingsModel.getProperty("/splitViewVertically"),
				sRangeName = Device.media.getCurrentRange("StdExt").name;

			if (sRangeName == "Tablet" || sRangeName == "Phone" && !isOrientationVertical) {
				exploreSettingsModel.setProperty("/splitViewVertically", true);
				this.getView().byId("splitView").getRootPaneContainer().setOrientation("Vertical");
			}
		},

		_onRouteMatched: function (oEvent) {
			var oArgs = oEvent.getParameter("arguments"),
				sSampleKey = oArgs["key"],
				oSample = this._findSample(sSampleKey),
				sSubSampleKey = oArgs["subSampleKey"],
				oSubSample;

			// reset the model
			this.oModel.setData({});

			if (!oSample) {
				//TODO sample not found
				return;
			}

			if (oSample.subSamples && !sSubSampleKey) {
				// select the first sub sample
				sSubSampleKey = oSample.subSamples[0].key;
			}

			oSubSample = this._findSubSample(oSample, sSubSampleKey);
			if (sSubSampleKey && !oSubSample) {
				//TODO sub sample not found
				return;
			}

			this._showSample(oSample, oSubSample);
		},

		_onCardAction: function (oEvent) {
			var sType = oEvent.getParameter("type"),
				mParameters = oEvent.getParameter("manifestParameters"),
				sMessage;

			sMessage = "Action '" + sType + "'";
			if (mParameters) {
				sMessage += " with parameters '" + JSON.stringify(mParameters) + "'";
			}

			MessageToast.show(sMessage, {
				at: "center center",
				width: "25rem"
			});
		},

		_findSample: function (sSampleKey) {
			var aSections = exploreNavigationModel.getProperty("/navigation"),
				oFoundSample;

			// loops through all samples in the navigation and gets the current one
			aSections.some(function (oSection) {
				oSection.items.some(function (oSample) {
					if (oSample.key === sSampleKey) {
						oFoundSample = oSample;
						return true;
					}
				});
			});

			return oFoundSample;
		},

		_findSubSample: function (oSample, sSubSampleKey) {
			var oFoundSubSample;

			if (!sSubSampleKey) {
				return null;
			}

			oSample.subSamples.some(function (oSubSample) {
				if (oSubSample.key === sSubSampleKey) {
					oFoundSubSample = oSubSample;
					return true;
				}
			});

			return oFoundSubSample;
		},

		_showSample: function (oSample, oSubSample) {
			var sManifestUrl,
				oLayoutSettings = {
					minRows: 1,
					columns: 4
				},
				oCard = this.byId("cardSample"),
				bEditable = true;

			this.oModel.setProperty("/sample", oSample);

			if (oSubSample) {
				this.oModel.setProperty("/subSample", oSubSample);
				oLayoutSettings = Object.assign(oLayoutSettings, oSubSample.settings);
				sManifestUrl = oSubSample.manifestUrl;
			} else {
				oLayoutSettings = Object.assign(oLayoutSettings, oSample.settings);
				sManifestUrl = oSample.manifestUrl;
			}

			if (oCard) {
				oCard.setLayoutData(new GridContainerItemLayoutData(oLayoutSettings));
				this.byId("cardContainer").rerender();
			}

			if (!sManifestUrl) {
				// TODO no manifest for the given sample or sub sample
				return;
			}

			sManifestUrl = sap.ui.require.toUrl("sap/ui/demo/cardExplorer" + sManifestUrl);

			if (oSample.disableEditor) {
				oCard.setManifest(sManifestUrl);
				bEditable = false;
			}

			this.getModel("settings").setProperty("/editable", bEditable);

			this._loadManifest(sManifestUrl);
		},

		_loadManifest: function (sManifestUrl) {
			jQuery.ajax(sManifestUrl, {
				async: true,
				dataType: "text",
				success: function (sValue) {
					this.byId("editor").setValue(sValue);
				}.bind(this)
			});
		},

		_updateSample: function (sValue) {
			if (!sValue) {
				// TODO hide the card or something like that. Currently it shows busy indicator which might be confusing
				this.byId("cardSample").setManifest(null);
				return;
			}

			try {
				var oData = JSON.parse(sValue);
				this.byId("cardSample").setManifest(oData);
				this._errorMessageStrip.setVisible(false);
			} catch (oException) {
				this.byId("cardSample").setManifest(null);
			}

		}
	});
});<commit_msg>[INTERNAL] Card Explorer: Examples are now refreshed<commit_after>sap.ui.define([
	"sap/ui/demo/cardExplorer/controller/BaseController",
	'sap/ui/model/json/JSONModel',
	"sap/ui/model/BindingMode",
	"../model/ExploreNavigationModel",
	"../model/ExploreSettingsModel",
	"sap/m/MessageToast",
	"sap/f/GridContainerItemLayoutData",
	"sap/ui/Device"
], function (
	BaseController,
	JSONModel,
	BindingMode,
	exploreNavigationModel,
	exploreSettingsModel,
	MessageToast,
	GridContainerItemLayoutData,
	Device
) {
	"use strict";

	return BaseController.extend("sap.ui.demo.cardExplorer.controller.ExploreSamples", {

		/**
		 * Called when the controller is instantiated.
		 */
		onInit: function () {
			var oRouter = this.getRouter();
			oRouter.getRoute("exploreSamples").attachMatched(this._onRouteMatched, this);

			this.oModel = new JSONModel();
			this.oModel.setDefaultBindingMode(BindingMode.OneWay);

			this.getView().setModel(this.oModel);
			this.getView().setModel(exploreSettingsModel, "settings");
			this._editor = this.byId("editor");
			//This will prevent all auto complete and suggestions of the editor
			this._editor._oEditor.completers = [];

			//This catches any "json" validation errors that ware made inside the editor
			this._editor._oEditor.session.on("changeAnnotation", this._onSyntaxError.bind(this));

			//This catches any error that was produced by the card
			this.byId("cardSample").attachEvent("_error", this._onCardError, this);

			this._errorMessageStrip = this.getView().byId("errorMessageStrip");
			this._registerResize();

			this.byId("cardSample").attachEvent("action", this._onCardAction, this);
		},

		onExit: function () {
			this._deregisterResize();
		},

		onManifestEdited: function (oEvent) {
			var sValue = oEvent.getParameter("value");

			if (exploreSettingsModel.getProperty("/autoRun")) {
				this._updateSample(sValue);
			}
		},
		onRunPressed: function (oEvent) {
			var sValue = this.getView().byId("editor").getValue();
			this._updateSample(sValue);
		},

		onChangeSplitterOrientation: function (oEvent) {
			//Toggles the value of splitter orientation
			exploreSettingsModel.setProperty("/splitViewVertically", !exploreSettingsModel.getProperty("/splitViewVertically"));
			var isOrientationVertical = exploreSettingsModel.getProperty("/splitViewVertically");
			this.getView().byId("splitView").getRootPaneContainer().setOrientation(isOrientationVertical ? "Vertical" : "Horizontal");
		},

		showError: function (sMessage) {
			this._errorMessageStrip.setVisible(true);
			this._errorMessageStrip.setText(sMessage);
		},

		onSubSampleChange: function (oEvent) {
			var item = oEvent.getParameter('selectedItem');

			this.getRouter().navTo(
				"exploreSamples",
				{
					key: this.oModel.getProperty("/sample").key,
					subSampleKey: item.getKey()
				}
			);
		},

		_onSyntaxError: function () {
			var aErrorAnnotations = this._editor._oEditor.session.$annotations,
				sMessage = "";
			if (aErrorAnnotations.length) {
				aErrorAnnotations.forEach(function (oError) {
					sMessage += "Line " + String(oError.row) + ": " + oError.text + '\n';
				});
				this.showError(sMessage);
			}
		},

		_onCardError: function (oEvent) {
			this.showError(oEvent.getParameters().message);
		},

		_deregisterResize: function () {
			Device.media.detachHandler(this._onResize, this);
		},

		_registerResize: function () {
			Device.media.attachHandler(this._onResize, this);
			this._onResize();
		},

		_onResize: function () {
			var isOrientationVertical = exploreSettingsModel.getProperty("/splitViewVertically"),
				sRangeName = Device.media.getCurrentRange("StdExt").name;

			if (sRangeName == "Tablet" || sRangeName == "Phone" && !isOrientationVertical) {
				exploreSettingsModel.setProperty("/splitViewVertically", true);
				this.getView().byId("splitView").getRootPaneContainer().setOrientation("Vertical");
			}
		},

		_onRouteMatched: function (oEvent) {
			var oArgs = oEvent.getParameter("arguments"),
				sSampleKey = oArgs["key"],
				oSample = this._findSample(sSampleKey),
				sSubSampleKey = oArgs["subSampleKey"],
				oSubSample;

			// reset the model
			this.oModel.setData({});

			if (!oSample) {
				//TODO sample not found
				return;
			}

			if (oSample.subSamples && !sSubSampleKey) {
				// select the first sub sample
				sSubSampleKey = oSample.subSamples[0].key;
			}

			oSubSample = this._findSubSample(oSample, sSubSampleKey);
			if (sSubSampleKey && !oSubSample) {
				//TODO sub sample not found
				return;
			}

			this._showSample(oSample, oSubSample);
		},

		_onCardAction: function (oEvent) {
			var sType = oEvent.getParameter("type"),
				mParameters = oEvent.getParameter("manifestParameters"),
				sMessage;

			sMessage = "Action '" + sType + "'";
			if (mParameters) {
				sMessage += " with parameters '" + JSON.stringify(mParameters) + "'";
			}

			MessageToast.show(sMessage, {
				at: "center center",
				width: "25rem"
			});
		},

		_findSample: function (sSampleKey) {
			var aSections = exploreNavigationModel.getProperty("/navigation"),
				oFoundSample;

			// loops through all samples in the navigation and gets the current one
			aSections.some(function (oSection) {
				oSection.items.some(function (oSample) {
					if (oSample.key === sSampleKey) {
						oFoundSample = oSample;
						return true;
					}
				});
			});

			return oFoundSample;
		},

		_findSubSample: function (oSample, sSubSampleKey) {
			var oFoundSubSample;

			if (!sSubSampleKey) {
				return null;
			}

			oSample.subSamples.some(function (oSubSample) {
				if (oSubSample.key === sSubSampleKey) {
					oFoundSubSample = oSubSample;
					return true;
				}
			});

			return oFoundSubSample;
		},

		_showSample: function (oSample, oSubSample) {
			var sManifestUrl,
				oLayoutSettings = {
					minRows: 1,
					columns: 4
				},
				oCard = this.byId("cardSample"),
				bEditable = true;

			this.oModel.setProperty("/sample", oSample);

			if (oSubSample) {
				this.oModel.setProperty("/subSample", oSubSample);
				oLayoutSettings = Object.assign(oLayoutSettings, oSubSample.settings);
				sManifestUrl = oSubSample.manifestUrl;
			} else {
				oLayoutSettings = Object.assign(oLayoutSettings, oSample.settings);
				sManifestUrl = oSample.manifestUrl;
			}

			if (oCard) {
				oCard.setLayoutData(new GridContainerItemLayoutData(oLayoutSettings));
				this.byId("cardContainer").rerender();
			}

			if (!sManifestUrl) {
				// TODO no manifest for the given sample or sub sample
				return;
			}

			sManifestUrl = sap.ui.require.toUrl("sap/ui/demo/cardExplorer" + sManifestUrl);

			if (oSample.disableEditor) {
				oCard.setManifest(sManifestUrl);
				bEditable = false;
			}

			this.getModel("settings").setProperty("/editable", bEditable);

			this._loadManifest(sManifestUrl);
		},

		_loadManifest: function (sManifestUrl) {
			jQuery.ajax(sManifestUrl, {
				async: true,
				dataType: "text",
				success: function (sValue) {
					this.byId("editor").setValue(sValue);
				}.bind(this)
			});
		},

		_updateSample: function (sValue) {
			if (!sValue) {
				// TODO hide the card or something like that. Currently it shows busy indicator which might be confusing
				this.byId("cardSample").setManifest(null);
				return;
			}

			try {
				var oData = JSON.parse(sValue);
				this.byId("cardSample").setManifest(oData);
				this._errorMessageStrip.setVisible(false);
				this.byId("cardSample").refresh();
			} catch (oException) {
				this.byId("cardSample").setManifest(null);
			}

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


<commit_before>var request = require('request');
var Promise = require('bluebird');

module.exports = function ajax(options) {
  return new Promise(function (resolve, reject) {
    var optionsClone = Object.assign({}, options);
    if (optionsClone.uri.startsWith('/')) {
      optionsClone.uri = window.location.origin + optionsClone.uri;
    }
    request(optionsClone, function (error, response, body) {
      if (error) {
        reject(error);
      } else {
        resolve(response);
      }
    });
  });
};
<commit_msg>Changed error handling for ajax.<commit_after>var request = require('request');
var Promise = require('bluebird');

module.exports = function ajax(options) {
  return new Promise(function (resolve, reject) {
    var optionsClone = Object.assign({}, options);
    if (optionsClone.uri.startsWith('/')) {
      optionsClone.uri = window.location.origin + optionsClone.uri;
    }
    request(optionsClone, function (error, response, body) {
      if (error) {
        console.error(error);
        error.message = 'The server could not be reached.';
        reject(error);
      } else {
        resolve(response);
      }
    });
  });
};
<|endoftext|>


<commit_before>importScripts("simulation.js");
importScripts("simulationtools.js");
importScripts("person.js");
importScripts("hcv.js");

self.onmessage = function (e) {
    var SimNumber = e.data.SimNumber;
    var SimData = e.data.SimData;

	IncrementSize=Math.round(SimData.NoPeople/100);

	Year=2014.5;
	GenotypeValue=0;
	Age=29;
	Sex=1;
	Alcohol=0;

	HCVParam={};
	HCVParam.F0F1=0.2;
	HCVParam.F1F2=0.1;
	HCVParam.F2F3=0.15;
	HCVParam.F3F4=0.3;
	HCVParam.F4LF=0.5;
	HCVParam.F4HCC=0.4;

	self.postMessage({ConsoleMessage: "Starting to load Person object"});

	var PP=[];
	for (i=0; i<SimData.NoPeople; i++){
		PP.push(new PersonObject(2, 1985.1));
		if (i%IncrementSize==0){
			self.postMessage({ProgressBarValue: i/SimData.NoPeople});
		}
	}

	self.postMessage({ConsoleMessage: "Starting to HCV progression"});

	for (i=0; i<SimData.NoPeople; i++){
		PP[i].HCV.Infection(Year, GenotypeValue, Age, Sex, Alcohol, HCVParam );
		if (i%IncrementSize==0){
			self.postMessage({ProgressBarValue: i/SimData.NoPeople});
		}
	}

	//Determine fibrosis levels with year

	FibrosisMatrix=ZeroMatrix(6, 100);

	self.postMessage({ConsoleMessage: "Starting to HCV progression"});
	YearCount=0;
	for (GraphYear=Year-1; GraphYear<Year+40; GraphYear++){
		for (i=0; i<SimData.NoPeople; i++){
			FibrosisLevel=PP[i].HCV.Fibrosis.Get(GraphYear).Value;
			//self.postMessage({ConsoleMessage: "FibrosisLevel "+ FibrosisLevel+ " YearCount" + YearCount});
			FibrosisMatrix[FibrosisLevel][YearCount]++;
		}
		YearCount++;
		self.postMessage({ConsoleMessage: "FibrosisLevel "+ FibrosisLevel+ " YearCount" + YearCount});
	}

	self.postMessage({ConsoleMessage: "Starting to run time until diagnosis"});

	var Rarray=[];
	TotalLoops=10000000;
    var seconds1 = new Date().getTime() / 1000;
	for (var i=1; i<TotalLoops; i++){
		Rarray=TimeUntilEvent(0.3);
		if (i%10000==0){
			self.postMessage({ProgressBarValue: i/TotalLoops});
		}
	}
	var seconds2 = new Date().getTime() / 1000;
    TotalTime=seconds2 -seconds1;
	CalcsPerSec=TotalLoops/TotalTime;

	ReturnMessage=WhatsGiven+SimNumber+" "+CalcsPerSec;

	self.postMessage({ConsoleMessage: "Finished simulation"});
};
<commit_msg>Cleaning out code no longer sued<commit_after>importScripts("simulation.js");
importScripts("simulationtools.js");
importScripts("person.js");
importScripts("hcv.js");

self.onmessage = function (e) {
    var seconds1 = new Date().getTime() / 1000;

	var SimNumber = e.data.SimNumber;
    var SimData = e.data.SimData;

	IncrementSize=Math.round(SimData.NoPeople/100);

	Year=2014.5;
	GenotypeValue=0;
	Age=29;
	Sex=1;
	Alcohol=0;

	HCVParam={};
	HCVParam.F0F1=0.2;
	HCVParam.F1F2=0.1;
	HCVParam.F2F3=0.15;
	HCVParam.F3F4=0.3;
	HCVParam.F4LF=0.5;
	HCVParam.F4HCC=0.4;

	self.postMessage({ConsoleMessage: "Starting to load Person object"});

	var PP=[];
	for (i=0; i<SimData.NoPeople; i++){
		PP.push(new PersonObject(2, 1985.1));
		if (i%IncrementSize==0){
			self.postMessage({ProgressBarValue: i/SimData.NoPeople});
		}
	}

	self.postMessage({ConsoleMessage: "Starting to HCV progression"});

	for (i=0; i<SimData.NoPeople; i++){
		PP[i].HCV.Infection(Year, GenotypeValue, Age, Sex, Alcohol, HCVParam );
		if (i%IncrementSize==0){
			self.postMessage({ProgressBarValue: i/SimData.NoPeople});
		}
	}

	//Determine fibrosis levels with year

	FibrosisMatrix=ZeroMatrix(6, 100);

	self.postMessage({ConsoleMessage: "Starting to HCV progression"});
	YearCount=0;
	for (GraphYear=Year-1; GraphYear<Year+40; GraphYear++){
		for (i=0; i<SimData.NoPeople; i++){
			FibrosisLevel=PP[i].HCV.Fibrosis.Get(GraphYear).Value;
			//self.postMessage({ConsoleMessage: "FibrosisLevel "+ FibrosisLevel+ " YearCount" + YearCount});
			FibrosisMatrix[FibrosisLevel][YearCount]++;
		}
		YearCount++;
		self.postMessage({ConsoleMessage: "FibrosisLevel "+ FibrosisLevel+ " YearCount" + YearCount});
	}

	var seconds2 = new Date().getTime() / 1000;
    TotalTime=seconds2 -seconds1;

	self.postMessage({ConsoleMessage: "Finished simulation in "+TotalTime+" seconds"});
};
<|endoftext|>


<commit_before>/*global app, client*/
"use strict";

var async = require('async');
var BaseCollection = require('./baseCollection');
var MUC = require('./muc');

module.exports = BaseCollection.extend({
    type: 'mucs',
    model: MUC,
    comparator: function (model1, model2) {
        var name1 = model1.displayName.toLowerCase();
        var name2 = model2.displayName.toLowerCase();
        if (name1 === name2) {
            return 0;
        }
        if (name1 < name2) {
            return -1;
        }
        return 1;
    },
    initialize: function (model, options) {
        this.bind('change', this.sort, this);
    },
    loadBookmarks: function () {
        var self = this;
        app.whenConnected(function () {
            client.getBookmarks(function (err, res) {
                if (err) return;

                var mucs = res.privateStorage.bookmarks.conferences;
                mucs.forEach(function (muc) {
                    self.add(muc);
                    if (muc.autoJoin) {
                        self.get(muc.jid).join();
                    }
                });
            });
        });
    },
    init: function () {
        var self = this;
        app.whenConnected(function () {

            function _fetch(init) {
                self.fetch(function() {
                    self.update();
                    if (init) self.trigger('loaded');
                    setTimeout(_fetch, 30000);
                });
            }
            _fetch(true);

        });
    },
    fetch: function(cb) {
        var self = this;
        while(app.mucInfos.length > 0) {
            app.mucInfos.pop();
        }

        if (SERVER_CONFIG.muc) {
            if (client.sessionStarted) {

                var rooms = [];
                client.getDiscoItems(SERVER_CONFIG.muc, '', function (err, res) {
                    if (err) return;

                    rooms = res.discoItems.items;
                    if (rooms === undefined)
                        rooms = [];
                    var roomNum = 0;

                    rooms.forEach (function (room) {
                      client.getDiscoInfo(room.jid, '', function (err, res) {

                        if (err) return;

                        var features = res.discoInfo.features;

                        var persistent = features.indexOf("muc_persistent") > -1;
                        var membersOnly = features.indexOf("muc_membersonly") > -1;

                        var mucInfo = {
                          id: room.jid.full,
                          name: room.name,
                          jid: room.jid,
                          nick: me.nick,
                          autoJoin: persistent,
                          persistent: persistent
                        };

                        if(membersOnly)
                        {
                            async.parallel([
                                function(callback) {
                                    client.getRoomMembers(mucInfo.jid, { items: [ { affiliation: 'member' } ] }, function (err, res) {
                                        if(err) {
                                            callback(null, 'false');
                                        }
                                        else if(res && res.mucAdmin && res.mucAdmin.items) {
                                            var members = res.mucAdmin.items.map(function (item) {
                                                return item.jid.bare;
                                            });
                                            var amMember = members.indexOf(client.jid.bare) > -1;
                                            callback(null, amMember ? 'true' : 'false');
                                        }
                                        else {
                                            callback(null, 'false');
                                        }
                                    })
                                },
                                function(callback) {
                                    client.getRoomMembers(mucInfo.jid, { items: [ { affiliation: 'admin' } ] }, function (err, res) {
                                        if(err) {
                                            callback(null, 'false');
                                        }
                                        else if(res && res.mucAdmin && res.mucAdmin.items) {
                                            var members = res.mucAdmin.items.map(function (item) {
                                                return item.jid.bare;
                                            });
                                            var amMember = members.indexOf(client.jid.bare) > -1;
                                            callback(null, amMember ? 'true' : 'false');
                                        }
                                        else {
                                            callback(null, 'false');
                                        }
                                    })
                                },
                                function(callback) {
                                    client.getRoomMembers(mucInfo.jid, { items: [ { affiliation: 'owner' } ] }, function (err, res) {
                                        if(err) {
                                            callback(null, 'false');
                                        }
                                        else if(res && res.mucAdmin && res.mucAdmin.items) {
                                            var members = res.mucAdmin.items.map(function (item) {
                                                return item.jid.bare;
                                            });
                                            var amMember = members.indexOf(client.jid.bare) > -1;
                                            callback(null, amMember ? 'true' : 'false');
                                        }
                                        else {
                                            callback(null, 'false');
                                        }
                                    })
                                }
                            ],
                            function(err, results){
                                console.log(results);
                                if(results.indexOf('true') > -1) {
                                    app.mucInfos.push(mucInfo);
                                    roomNum++;
                                    if (cb && roomNum == rooms.length) cb();
                                }
                            });
                        }
                        else
                        {
                            app.mucInfos.push(mucInfo);
                            roomNum++;
                            if (cb && roomNum == rooms.length) cb();
                        }

                      });
/*
                        .then(function() {
                        if (cb && roomNum == rooms.length) cb();
                      });
*/
                    });
                }).then(function() {
                    if (cb && !rooms.length) cb();
                });

            } else {
                app.whenConnected(function () {
                    self.fetch(cb);
                });
            }
            return;
        }

        if (cb) cb();

    },
    update: function () {
        if (SERVER_CONFIG.muc) {
            var toRemove = [];
            for ( var i = 0; i < this.models.length; i++) {
                toRemove.push(this.models[i]);
            }

            for (var i = 0; i < app.mucInfos.length; i++) {

                var mucInfo = app.mucInfos[i];
                var muc = this.get(mucInfo.jid);
                if (muc) {
                    muc.name = mucInfo.name;
                    muc.autoJoin =  mucInfo.autoJoin;
                    muc.persistent = mucInfo.persistent;

                    var index = toRemove.indexOf(muc);
                    if (index > -1) {
                        toRemove.splice(index, 1);
                    }
                }
                else {
                    this.add(mucInfo);
                    muc = this.get(mucInfo.jid);
                }

                if (muc.autoJoin && !muc.joined) {
                    muc.join();
                }

            }

            this.remove(toRemove);

            while(app.mucInfos.length > 0) {
                app.mucInfos.pop();
            }
        }
    },
    save: function (cb) {
        var self = this;
        app.whenConnected(function () {
            var models = [];
            self.models.forEach(function (model) {
                models.push({
                    name: model.name,
                    jid: model.jid,
                    nick: model.nick,
                    autoJoin: model.autoJoin
                });
            });
            client.setBookmarks({conferences: models}, cb);
        });
    }
});
<commit_msg>Update mucs.js<commit_after>/*global app, client*/
"use strict";

var async = require('async');
var BaseCollection = require('./baseCollection');
var MUC = require('./muc');

module.exports = BaseCollection.extend({
    type: 'mucs',
    model: MUC,
    comparator: function (model1, model2) {
        var name1 = model1.displayName.toLowerCase();
        var name2 = model2.displayName.toLowerCase();
        if (name1 === name2) {
            return 0;
        }
        if (name1 < name2) {
            return -1;
        }
        return 1;
    },
    initialize: function (model, options) {
        this.bind('change', this.sort, this);
    },
    loadBookmarks: function () {
        var self = this;
        app.whenConnected(function () {
            client.getBookmarks(function (err, res) {
                if (err) return;

                var mucs = res.privateStorage.bookmarks.conferences;
                mucs.forEach(function (muc) {
                    self.add(muc);
                    if (muc.autoJoin) {
                        self.get(muc.jid).join();
                    }
                });
            });
        });
    },
    init: function () {
        var self = this;
        app.whenConnected(function () {

            function _fetch(init) {
                self.fetch(function() {
                    self.update();
                    if (init) self.trigger('loaded');
                    setTimeout(_fetch, 30000);
                });
            }
            _fetch(true);

        });
    },
    fetch: function(cb) {
        var self = this;
        while(app.mucInfos.length > 0) {
            app.mucInfos.pop();
        }

        if (SERVER_CONFIG.muc) {
            if (client.sessionStarted) {

                var rooms = [];
                client.getDiscoItems(SERVER_CONFIG.muc, '', function (err, res) {
                    if (err) return;

                    rooms = res.discoItems.items;
                    if (rooms === undefined)
                        rooms = [];
                    var roomNum = 0;

                    rooms.forEach (function (room) {
                      client.getDiscoInfo(room.jid, '', function (err, res) {

                        if (err) return;

                        var features = res.discoInfo.features;

                        var persistent = features.indexOf("muc_persistent") > -1;
                        var membersOnly = features.indexOf("muc_membersonly") > -1;

                        var mucInfo = {
                          id: room.jid.full,
                          name: room.name,
                          jid: room.jid,
                          nick: me.nick,
                          autoJoin: persistent,
                          persistent: persistent
                        };

                        if(membersOnly)
                        {
                            async.parallel([
                                function(callback) {
                                    client.getRoomMembers(mucInfo.jid, { items: [ { affiliation: 'member' } ] }, function (err, res) {
                                        if(err) {
                                            callback(null, 'false');
                                        }
                                        else if(res && res.mucAdmin && res.mucAdmin.items) {
                                            var members = res.mucAdmin.items.map(function (item) {
                                                return item.jid.bare;
                                            });
                                            var amMember = members.indexOf(client.jid.bare) > -1;
                                            callback(null, amMember ? 'true' : 'false');
                                        }
                                        else {
                                            callback(null, 'false');
                                        }
                                    })
                                },
                                function(callback) {
                                    client.getRoomMembers(mucInfo.jid, { items: [ { affiliation: 'admin' } ] }, function (err, res) {
                                        if(err) {
                                            callback(null, 'false');
                                        }
                                        else if(res && res.mucAdmin && res.mucAdmin.items) {
                                            var members = res.mucAdmin.items.map(function (item) {
                                                return item.jid.bare;
                                            });
                                            var amMember = members.indexOf(client.jid.bare) > -1;
                                            callback(null, amMember ? 'true' : 'false');
                                        }
                                        else {
                                            callback(null, 'false');
                                        }
                                    })
                                },
                                function(callback) {
                                    client.getRoomMembers(mucInfo.jid, { items: [ { affiliation: 'owner' } ] }, function (err, res) {
                                        if(err) {
                                            callback(null, 'false');
                                        }
                                        else if(res && res.mucAdmin && res.mucAdmin.items) {
                                            var members = res.mucAdmin.items.map(function (item) {
                                                return item.jid.bare;
                                            });
                                            var amMember = members.indexOf(client.jid.bare) > -1;
                                            callback(null, amMember ? 'true' : 'false');
                                        }
                                        else {
                                            callback(null, 'false');
                                        }
                                    })
                                }
                            ],
                            function(err, results){
                                console.log(results);
                                if(results.indexOf('true') > -1) {
                                    app.mucInfos.push(mucInfo);
                                }
                                roomNum++;
                                if (cb && roomNum == rooms.length) cb();
                            });
                        }
                        else
                        {
                            app.mucInfos.push(mucInfo);
                            roomNum++;
                            if (cb && roomNum == rooms.length) cb();
                        }

                      });
/*
                        .then(function() {
                        if (cb && roomNum == rooms.length) cb();
                      });
*/
                    });
                }).then(function() {
                    if (cb && !rooms.length) cb();
                });

            } else {
                app.whenConnected(function () {
                    self.fetch(cb);
                });
            }
            return;
        }

        if (cb) cb();

    },
    update: function () {
        if (SERVER_CONFIG.muc) {
            var toRemove = [];
            for ( var i = 0; i < this.models.length; i++) {
                toRemove.push(this.models[i]);
            }

            for (var i = 0; i < app.mucInfos.length; i++) {

                var mucInfo = app.mucInfos[i];
                var muc = this.get(mucInfo.jid);
                if (muc) {
                    muc.name = mucInfo.name;
                    muc.autoJoin =  mucInfo.autoJoin;
                    muc.persistent = mucInfo.persistent;

                    var index = toRemove.indexOf(muc);
                    if (index > -1) {
                        toRemove.splice(index, 1);
                    }
                }
                else {
                    this.add(mucInfo);
                    muc = this.get(mucInfo.jid);
                }

                if (muc.autoJoin && !muc.joined) {
                    muc.join();
                }

            }

            this.remove(toRemove);

            while(app.mucInfos.length > 0) {
                app.mucInfos.pop();
            }
        }
    },
    save: function (cb) {
        var self = this;
        app.whenConnected(function () {
            var models = [];
            self.models.forEach(function (model) {
                models.push({
                    name: model.name,
                    jid: model.jid,
                    nick: model.nick,
                    autoJoin: model.autoJoin
                });
            });
            client.setBookmarks({conferences: models}, cb);
        });
    }
});
<|endoftext|>


<commit_before>"use strict";

var Android = require('./android.js')
  , Chromedriver = require('appium-chromedriver')
  , _ = require('underscore')
  , logger = require('../../server/logger.js').get('appium')
  , status = require('../../server/status.js')
  , deviceCommon = require('../common.js')
  , jwpSuccess = deviceCommon.jwpSuccess
  , async = require('async')
  , UiAutomator = require('./uiautomator.js');

var NATIVE_WIN = "NATIVE_APP";
var WEBVIEW_WIN = "WEBVIEW";
var WEBVIEW_BASE = WEBVIEW_WIN + "_";

var ChromeAndroid = function () {
  this.init();
};

_.extend(ChromeAndroid.prototype, Android.prototype);
ChromeAndroid.prototype._androidInit = Android.prototype.init;
ChromeAndroid.prototype.init = function () {
  this._androidInit();
  this.adb = null;
  this.onDieCb = null;
  this.setChromedriverMode();
};

ChromeAndroid.prototype.setChromedriverMode = function () {
  logger.info("Set mode: Proxying straight through to Chromedriver");
  this.isProxy = true;
  // when proxying to chromedriver, we need to make sure the context endpoints
  // are trapped by appium for its own purposes
  this.avoidProxy = [
    ['POST', new RegExp('^/wd/hub/session/[^/]+/context')],
    ['GET', new RegExp('^/wd/hub/session/[^/]+/context')],
    ['POST', new RegExp('^/wd/hub/session/[^/]+/touch/perform')],
    ['POST', new RegExp('^/wd/hub/session/[^/]+/touch/multi/perform')]
  ];
};

ChromeAndroid.prototype.setNativeMode = function () {
  logger.info("Set mode: Proxying to Appium Bootstrap");
  this.isProxy = false;
};

ChromeAndroid.prototype.configure = function (args, caps, cb) {
  logger.debug("Looks like we want chrome on android");
  this._deviceConfigure(args, caps);
  var bName = this.args.browserName || "";
  var app = this.appString().toLowerCase() ||
            bName.toString().toLowerCase();
  if (app === "chromium") {
    this.args.androidPackage = "org.chromium.chrome.shell";
    this.args.androidActivity = ".ChromeShellActivity";
  } else if (app === "chromebeta") {
    this.args.androidPackage = "com.chrome.beta";
    this.args.androidActivity = "com.google.android.apps.chrome.Main";
  } else if (app === "browser") {
    this.args.androidPackage = "com.android.browser";
    this.args.androidActivity = "com.android.browser.BrowserActivity";
  } else {
    this.args.androidPackage = "com.android.chrome";
    this.args.androidActivity = "com.google.android.apps.chrome.Main";
  }
  // don't allow setAndroidArgs to reclobber our androidPackage/activity
  delete this.capabilities.appPackage;
  delete this.capabilities.appActivity;
  this.setAndroidArgs();
  this.args.app = null;
  this.args.proxyPort = this.args.chromeDriverPort;
  cb();
};

ChromeAndroid.prototype.startAutomation = function (cb) {
  // this wrapper is required because uiautomator is not instantiated
  // at the beginning of the async#series call
  this.uiautomator.start(cb);
};

ChromeAndroid.prototype.start = function (cb, onDie) {
  this.onDieCb = onDie;

  async.series([
    this.initAdb.bind(this),
    this.prepareUiAutomator.bind(this),
    this.initUiautomator.bind(this),
    this.prepareDevice.bind(this),
    this.prepareChromedriver.bind(this),
    this.pushAndUnlock.bind(this),
    this.forwardPort.bind(this),
    this.pushAppium.bind(this),
    this.startAutomation.bind(this),
    this.getDataDir.bind(this),
    this.createSession.bind(this)
  ], function (err, results) {
    if (err) return cb(err);
    this.didLaunch = true;
    var sessionId = results[results.length - 1];
    cb(null, sessionId);
  }.bind(this));
};

ChromeAndroid.prototype.prepareChromedriver = function (cb) {
  var chromeArgs = {
    port: this.args.proxyPort,
    executable: this.args.chromedriverExecutable
  };
  this.chromedriver = new Chromedriver(chromeArgs);
  this.proxyReqRes = this.chromedriver.proxyReq.bind(this.chromedriver);
  cb();
};

ChromeAndroid.prototype.prepareUiAutomator = function (cb) {
  this.uiautomator = new UiAutomator(this.adb, this.args);
  this.uiautomator.setExitHandler(this.onUiautomatorExit.bind(this));
  cb();
};

ChromeAndroid.prototype.pushAndUnlock = function (cb) {
  this.pushUnlock(function (err) {
    if (err) return cb(err);
    this.unlock(cb);
  }.bind(this));
};

ChromeAndroid.prototype.createSession = function (cb) {
  var caps = {
    chromeOptions: {
      androidPackage: this.args.appPackage
    }
  };
  if (this.args.enablePerformanceLogging) {
    caps.loggingPrefs = {performance: 'ALL'};
  }

  var knownPackages = ["org.chromium.chrome.shell",
                       "com.android.chrome",
                       "com.chrome.beta"];

  if (!_.contains(knownPackages, this.args.appPackage)) {
    caps.chromeOptions.androidActivity = this.args.appActivity;
  }

  caps = this.decorateChromeOptions(caps);
  this.chromedriver.on(Chromedriver.EVENT_CHANGED, function (msg) {
    if (msg.state === Chromedriver.STATE_STOPPED) {
      logger.info("Chromedriver stopped unexpectedly on us, shutting down " +
                  "then calling back up with the on-die callback");
      this.onChromedriverStop(this.onDieCb);
    }
  }.bind(this));
  this.chromedriver.start(caps).nodeify(function (err) {
    if (err) return cb(err);
    cb(null, this.chromedriver.sessionId());
  }.bind(this));
};

ChromeAndroid.prototype.stop = function (cb) {
  // stop listening for the stopped state event
  this.chromedriver.removeAllListeners(Chromedriver.EVENT_CHANGED);
  // now we can handle the stop on our own
  this.chromedriver.stop().nodeify(function (err) {
    if (err) logger.warn("Error stopping Chromedriver: " + err.message);
    this.onChromedriverStop(cb);
  }.bind(this));
};

ChromeAndroid.prototype.onChromedriverStop = function (cb) {
  if (this.adb) {
    this.uiautomator.shutdown(function () {
      this.adb.forceStop(this.args.appPackage, function (err) {
        if (err) return cb(err);
        this.adb.stopLogcat(cb);
      }.bind(this));
    }.bind(this));
  } else {
    cb();
  }
};

// since we're in chrome, our default context is not the native mode, but web
ChromeAndroid.prototype.defaultContext = function () {
  return WEBVIEW_BASE + "1";
};

// write a new getContexts function that hard-codes the two available contexts
ChromeAndroid.prototype.getContexts = function (cb) {
  this.contexts = [NATIVE_WIN, this.defaultContext()];
  logger.info("Available contexts: " + this.contexts);
  cb(null, {
    status: status.codes.Success.code
  , value: this.contexts
  });
};

// write a new setContext function that handles starting and stopping of
// chrome mode; the default android context controller method won't work here
// because here we don't need to worry about starting/stopping chromedriver
// itself; it's already on
ChromeAndroid.prototype.setContext = function (name, cb) {
  if (name === null) {
    name = this.defaultContext();
  } else if (name === WEBVIEW_WIN) {
    name = this.defaultContext();
  }
  this.getContexts(function () {
    if (!_.contains(this.contexts, name)) {
      return cb(null, {
        status: status.codes.NoSuchContext.code
      , value: "Context '" + name + "' does not exist"
      });
    }
    if (name === this.curContext) {
      return jwpSuccess(cb);
    }
    if (name.indexOf(WEBVIEW_WIN) !== -1) {
      this.setChromedriverMode();
    } else {
      this.setNativeMode();
    }
    this.curContext = name;
    jwpSuccess(cb);
  }.bind(this));
};

module.exports = ChromeAndroid;
<commit_msg>Adding support for chrome browser rotation<commit_after>"use strict";

var Android = require('./android.js')
  , Chromedriver = require('appium-chromedriver')
  , _ = require('underscore')
  , logger = require('../../server/logger.js').get('appium')
  , status = require('../../server/status.js')
  , deviceCommon = require('../common.js')
  , jwpSuccess = deviceCommon.jwpSuccess
  , async = require('async')
  , UiAutomator = require('./uiautomator.js');

var NATIVE_WIN = "NATIVE_APP";
var WEBVIEW_WIN = "WEBVIEW";
var WEBVIEW_BASE = WEBVIEW_WIN + "_";

var ChromeAndroid = function () {
  this.init();
};

_.extend(ChromeAndroid.prototype, Android.prototype);
ChromeAndroid.prototype._androidInit = Android.prototype.init;
ChromeAndroid.prototype.init = function () {
  this._androidInit();
  this.adb = null;
  this.onDieCb = null;
  this.setChromedriverMode();
};

ChromeAndroid.prototype.setChromedriverMode = function () {
  logger.info("Set mode: Proxying straight through to Chromedriver");
  this.isProxy = true;
  // when proxying to chromedriver, we need to make sure the context endpoints
  // are trapped by appium for its own purposes
  this.avoidProxy = [
    ['POST', new RegExp('^/wd/hub/session/[^/]+/context')],
    ['GET', new RegExp('^/wd/hub/session/[^/]+/context')],
    ['POST', new RegExp('^/wd/hub/session/[^/]+/touch/perform')],
    ['POST', new RegExp('^/wd/hub/session/[^/]+/touch/multi/perform')],
    ['POST', new RegExp('^/wd/hub/session/[^/]+/orientation')],
    ['GET', new RegExp('^/wd/hub/session/[^/]+/orientation')]
  ];
};

ChromeAndroid.prototype.setNativeMode = function () {
  logger.info("Set mode: Proxying to Appium Bootstrap");
  this.isProxy = false;
};

ChromeAndroid.prototype.configure = function (args, caps, cb) {
  logger.debug("Looks like we want chrome on android");
  this._deviceConfigure(args, caps);
  var bName = this.args.browserName || "";
  var app = this.appString().toLowerCase() ||
            bName.toString().toLowerCase();
  if (app === "chromium") {
    this.args.androidPackage = "org.chromium.chrome.shell";
    this.args.androidActivity = ".ChromeShellActivity";
  } else if (app === "chromebeta") {
    this.args.androidPackage = "com.chrome.beta";
    this.args.androidActivity = "com.google.android.apps.chrome.Main";
  } else if (app === "browser") {
    this.args.androidPackage = "com.android.browser";
    this.args.androidActivity = "com.android.browser.BrowserActivity";
  } else {
    this.args.androidPackage = "com.android.chrome";
    this.args.androidActivity = "com.google.android.apps.chrome.Main";
  }
  // don't allow setAndroidArgs to reclobber our androidPackage/activity
  delete this.capabilities.appPackage;
  delete this.capabilities.appActivity;
  this.setAndroidArgs();
  this.args.app = null;
  this.args.proxyPort = this.args.chromeDriverPort;
  cb();
};

ChromeAndroid.prototype.startAutomation = function (cb) {
  // this wrapper is required because uiautomator is not instantiated
  // at the beginning of the async#series call
  this.uiautomator.start(cb);
};

ChromeAndroid.prototype.start = function (cb, onDie) {
  this.onDieCb = onDie;

  async.series([
    this.initAdb.bind(this),
    this.prepareUiAutomator.bind(this),
    this.initUiautomator.bind(this),
    this.prepareDevice.bind(this),
    this.prepareChromedriver.bind(this),
    this.pushAndUnlock.bind(this),
    this.forwardPort.bind(this),
    this.pushAppium.bind(this),
    this.startAutomation.bind(this),
    this.getDataDir.bind(this),
    this.createSession.bind(this)
  ], function (err, results) {
    if (err) return cb(err);
    this.didLaunch = true;
    var sessionId = results[results.length - 1];
    cb(null, sessionId);
  }.bind(this));
};

ChromeAndroid.prototype.prepareChromedriver = function (cb) {
  var chromeArgs = {
    port: this.args.proxyPort,
    executable: this.args.chromedriverExecutable
  };
  this.chromedriver = new Chromedriver(chromeArgs);
  this.proxyReqRes = this.chromedriver.proxyReq.bind(this.chromedriver);
  cb();
};

ChromeAndroid.prototype.prepareUiAutomator = function (cb) {
  this.uiautomator = new UiAutomator(this.adb, this.args);
  this.uiautomator.setExitHandler(this.onUiautomatorExit.bind(this));
  cb();
};

ChromeAndroid.prototype.pushAndUnlock = function (cb) {
  this.pushUnlock(function (err) {
    if (err) return cb(err);
    this.unlock(cb);
  }.bind(this));
};

ChromeAndroid.prototype.createSession = function (cb) {
  var caps = {
    chromeOptions: {
      androidPackage: this.args.appPackage
    }
  };
  if (this.args.enablePerformanceLogging) {
    caps.loggingPrefs = {performance: 'ALL'};
  }

  var knownPackages = ["org.chromium.chrome.shell",
                       "com.android.chrome",
                       "com.chrome.beta"];

  if (!_.contains(knownPackages, this.args.appPackage)) {
    caps.chromeOptions.androidActivity = this.args.appActivity;
  }

  caps = this.decorateChromeOptions(caps);
  this.chromedriver.on(Chromedriver.EVENT_CHANGED, function (msg) {
    if (msg.state === Chromedriver.STATE_STOPPED) {
      logger.info("Chromedriver stopped unexpectedly on us, shutting down " +
                  "then calling back up with the on-die callback");
      this.onChromedriverStop(this.onDieCb);
    }
  }.bind(this));
  this.chromedriver.start(caps).nodeify(function (err) {
    if (err) return cb(err);
    cb(null, this.chromedriver.sessionId());
  }.bind(this));
};

ChromeAndroid.prototype.stop = function (cb) {
  // stop listening for the stopped state event
  this.chromedriver.removeAllListeners(Chromedriver.EVENT_CHANGED);
  // now we can handle the stop on our own
  this.chromedriver.stop().nodeify(function (err) {
    if (err) logger.warn("Error stopping Chromedriver: " + err.message);
    this.onChromedriverStop(cb);
  }.bind(this));
};

ChromeAndroid.prototype.onChromedriverStop = function (cb) {
  if (this.adb) {
    this.uiautomator.shutdown(function () {
      this.adb.forceStop(this.args.appPackage, function (err) {
        if (err) return cb(err);
        this.adb.stopLogcat(cb);
      }.bind(this));
    }.bind(this));
  } else {
    cb();
  }
};

// since we're in chrome, our default context is not the native mode, but web
ChromeAndroid.prototype.defaultContext = function () {
  return WEBVIEW_BASE + "1";
};

// write a new getContexts function that hard-codes the two available contexts
ChromeAndroid.prototype.getContexts = function (cb) {
  this.contexts = [NATIVE_WIN, this.defaultContext()];
  logger.info("Available contexts: " + this.contexts);
  cb(null, {
    status: status.codes.Success.code
  , value: this.contexts
  });
};

// write a new setContext function that handles starting and stopping of
// chrome mode; the default android context controller method won't work here
// because here we don't need to worry about starting/stopping chromedriver
// itself; it's already on
ChromeAndroid.prototype.setContext = function (name, cb) {
  if (name === null) {
    name = this.defaultContext();
  } else if (name === WEBVIEW_WIN) {
    name = this.defaultContext();
  }
  this.getContexts(function () {
    if (!_.contains(this.contexts, name)) {
      return cb(null, {
        status: status.codes.NoSuchContext.code
      , value: "Context '" + name + "' does not exist"
      });
    }
    if (name === this.curContext) {
      return jwpSuccess(cb);
    }
    if (name.indexOf(WEBVIEW_WIN) !== -1) {
      this.setChromedriverMode();
    } else {
      this.setNativeMode();
    }
    this.curContext = name;
    jwpSuccess(cb);
  }.bind(this));
};

module.exports = ChromeAndroid;
<|endoftext|>


<commit_before>enyo.kind({
	name: "analyzer.Reader",
	kind: enyo.Async,
	go: function(inData) {
		this.modules = inData.modules;
		this.designs = inData.designs;
		this.files = inData.modules.concat(inData.designs);
		enyo.asyncMethod(this, "nextFile");
		return this;
	},
	nextFile: function() {
		var f = this.files.shift();
		if (f) {
			this.loadFile(f);
		} else {
			this.filesFinished();
		}
	},
	loadFile: function(inFile) {
		enyo.xhr.request({
			url: inFile.path,
			callback: this.bindSafely("fileLoaded", inFile)
		});
	},
	fileLoaded: function(inFile, inCode, xhr) {
		var code = inCode;
		var striped = "";

		if(inFile.path.search("onyx") != 1 || inFile.path.search("layout") != 1){
			inCode = "";
			for (var l = 0; l <= code.length; l++ ){
				if(code.charAt(l) === "/" && code.charAt(l+1) === "*"){					//if we find /*

					for (l ; l <= code.length; l++ ){
						striped = striped + code.charAt(l);			// strip here
						if(code.charAt(l) === "*" && code.charAt(l+1) === "/"){			// stop strip here if we find */
							striped = striped + code.charAt(l) + code.charAt( l+ 1);  // add the last two char
							l++;

							if (striped.search("@lends") != -1){
								striped = striped + "/n";
							}else{
								inCode = inCode + striped;
								striped = "";
							}
							break;
						}
					}
				}else{
					inCode = inCode + code.charAt(l);
				}
			}
		}
		if(inFile.path.search("boot") === 1 ){
		}

		if (xhr.status >= 200 && xhr.status < 300) {
			this.addFile(inFile, inCode);
		}
		else {
			this.fail("Analyser cannot read " + inFile.path + ": " + xhr.status + ' ' + xhr.statusText);
		}
		this.nextFile();
	},
	addFile: function(inFile, inCode) {
		if (inCode && inCode.length) {
			inFile.code = inCode;
		}
	},
	filesFinished: function() {
		this.respond({modules: this.modules, designs: this.designs});
	}
});
<commit_msg>add enyo to the check for code after a commit<commit_after>enyo.kind({
	name: "analyzer.Reader",
	kind: enyo.Async,
	go: function(inData) {
		this.modules = inData.modules;
		this.designs = inData.designs;
		this.files = inData.modules.concat(inData.designs);
		enyo.asyncMethod(this, "nextFile");
		return this;
	},
	nextFile: function() {
		var f = this.files.shift();
		if (f) {
			this.loadFile(f);
		} else {
			this.filesFinished();
		}
	},
	loadFile: function(inFile) {
		enyo.xhr.request({
			url: inFile.path,
			callback: this.bindSafely("fileLoaded", inFile)
		});
	},
	fileLoaded: function(inFile, inCode, xhr) {
		var code = inCode;
		var striped = "";

		if(inFile.path.search("onyx") != 1 || inFile.path.search("layout") != 1 || inFile.path.search("layout" != 1)){
			inCode = "";
			for (var l = 0; l <= code.length; l++ ){
				if(code.charAt(l) === "/" && code.charAt(l+1) === "*"){					//if we find /*

					for (l ; l <= code.length; l++ ){
						striped = striped + code.charAt(l);			// strip here
						if(code.charAt(l) === "*" && code.charAt(l+1) === "/"){			// stop strip here if we find */
							striped = striped + code.charAt(l) + code.charAt( l+ 1);  // add the last two char
							l++;

							if (striped.search("@lends") != -1){
								striped = striped + "/n";
							}else{
								inCode = inCode + striped;
								striped = "";
							}
							break;
						}
					}
				}else{
					inCode = inCode + code.charAt(l);
				}
			}
		}
		if(inFile.path.search("boot") === 1 ){
		}

		if (xhr.status >= 200 && xhr.status < 300) {
			this.addFile(inFile, inCode);
		}
		else {
			this.fail("Analyser cannot read " + inFile.path + ": " + xhr.status + ' ' + xhr.statusText);
		}
		this.nextFile();
	},
	addFile: function(inFile, inCode) {
		if (inCode && inCode.length) {
			inFile.code = inCode;
		}
	},
	filesFinished: function() {
		this.respond({modules: this.modules, designs: this.designs});
	}
});
<|endoftext|>


<commit_before>var Extractor = require('./extractor'),
  Class = require('ee-class'),
  Q = require('q'),
  util = require('util');

var DailyMotion = new Class({
  /**
   * [inherits description]
   * @type {[type]}
   */
  inherits: Extractor,
  /**
   * Parts of the response to look at in order to parse
   * @type {Object}
   */
  placeholders: {
    start: 'var info =',
    stop: '"parent.screenname":null}' //this looks suspect. may break.
  },
  download: function(url, options) {
    var defer = Q.defer();
    options = options || {};
    this.info(url).done(function(info) {
      defer.resolve(this.get(info.stream_h264_url));
    }.bind(this));
    return defer.promise;
  },
  /**
   * @todo This is a horrible extractor for DM. Need to find a better way to parse the data. Seems to work for now.
   */
  info: function(url, options) {
    var defer = Q.defer();
    url = util.format(this.config.endpoints.dailymotion, this.getId(url));
    this.get(url, function(error, response, body) {
      body = body.replace(/\\/g, '');
      var start = this.placeholders.start,
        stop = this.placeholders.stop;
      var indexes = {
        start: body.indexOf(start) + start.length,
        stop: body.indexOf(stop) + stop.length
      };
      var info = body.substr(indexes.start, (indexes.stop - indexes.start));
      info = JSON.parse(info);
      defer.resolve(info);
    }.bind(this));
    return defer.promise;
  }
});

module.exports = DailyMotion;<commit_msg>Updates to the dailymotion extractor<commit_after>var Extractor = require('./extractor'),
  Class = require('ee-class'),
  Q = require('q'),
  util = require('util'),
  Url = require('url');

var DailyMotion = new Class({
  /**
   * [inherits description]
   * @type {[type]}
   */
  inherits: Extractor,
  /**
   * Parts of the response to look at in order to parse
   * @type {Object}
   */
  placeholders: {
    start: 'var info =',
    stop: '"parent.screenname":null}' //this looks suspect. may break.
  },
  _download: function(response) {
    var url = Url.parse(response.request.uri.href);
    var request = {
      url: url.href,
      followAllRedirects: true,
      headers: {
        'Host': url.host
      }
    };
    var req = this.get(request);
    return req;
  },
  download: function(url, options) {
    var defer = Q.defer();
    options = options || {};
    this.info(url).done(function(info) {
      this.get(info.stream_h264_url).on('response', function(response) {
        defer.resolve(this._download(response));
      }.bind(this));
    }.bind(this));
    return defer.promise;
  },
  /**
   * @todo This is a horrible extractor for DM. Need to find a better way to parse the data. Seems to work for now.
   */
  info: function(url, options) {
    var defer = Q.defer();
    url = util.format(this.config.endpoints.dailymotion, this.getId(url));
    this.get(url, function(error, response, body) {
      body = body.replace(/\\/g, '');
      var start = this.placeholders.start,
        stop = this.placeholders.stop;
      var indexes = {
        start: body.indexOf(start) + start.length,
        stop: body.indexOf(stop) + stop.length
      };
      var info = body.substr(indexes.start, (indexes.stop - indexes.start));
      info = JSON.parse(info);
      defer.resolve(info);
    }.bind(this));
    return defer.promise;
  }
});

module.exports = DailyMotion;<|endoftext|>


<commit_before>const fs = require('fs');

const ROOT_PATH = `${__dirname}/`;
const inputFiles = [ROOT_PATH + 'README_SOURCE.md'];
const outputFile = ROOT_PATH + 'README.md';

const result = inputFiles
    .map(filePath => fs.readFileSync(filePath, 'utf8'))
    .map(injectCodeBlocks)
    .map(injectExpanders);

fs.writeFileSync(outputFile, result, 'utf8');

function injectCodeBlocks(text) {
    const regex = /::codeblock='(.+?)'::/g;
    return text.replace(regex, createMatchReplacer(withSourceWrapper));
}

function injectExpanders(text) {
    const regex = /::expander='(.+?)'::/g;
    return text.replace(regex, createMatchReplacer(withDetailsWrapper));
}

function createMatchReplacer(wrapper) {
    return (match, filePath) => {
        console.log(ROOT_PATH + filePath);
        const text = fs.readFileSync(ROOT_PATH + filePath, 'utf8');
        return wrapper(text);
    };
}

function withSourceWrapper(text) {
    return `
${'```tsx'}
${text}
${'```'}
  `.trim();
}

function withDetailsWrapper(text) {
    return `
Click to expand

${'```tsx'}
${text}
${'```'}

  `.trim();
}
<commit_msg>Updated generate-readme script to be compatible with newer node runtimes<commit_after>const fs = require('fs');

const ROOT_PATH = `${__dirname}/`;
const inputFiles = [ROOT_PATH + 'README_SOURCE.md'];
const outputFile = ROOT_PATH + 'README.md';

const result = inputFiles
    .map(filePath => fs.readFileSync(filePath, 'utf8'))
    .map(injectCodeBlocks)
    .map(injectExpanders)
    .toString();

fs.writeFileSync(outputFile, result, 'utf8');

function injectCodeBlocks(text) {
    const regex = /::codeblock='(.+?)'::/g;
    return text.replace(regex, createMatchReplacer(withSourceWrapper));
}

function injectExpanders(text) {
    const regex = /::expander='(.+?)'::/g;
    return text.replace(regex, createMatchReplacer(withDetailsWrapper));
}

function createMatchReplacer(wrapper) {
    return (match, filePath) => {
        console.log(ROOT_PATH + filePath);
        const text = fs.readFileSync(ROOT_PATH + filePath, 'utf8');
        return wrapper(text);
    };
}

function withSourceWrapper(text) {
    return `
${'```tsx'}
${text}
${'```'}
  `.trim();
}

function withDetailsWrapper(text) {
    return `
Click to expand

${'```tsx'}
${text}
${'```'}

  `.trim();
}
<|endoftext|>