<commit_before>import { createAction } from 'redux-actions'
import { matchPath } from 'react-router'
import { push } from 'connected-react-router'
import coreUtils from '@opentripplanner/core-utils'

import {
  getConfigLocales,
  getDefaultLocale,
  getMatchingLocaleString,
  loadLocaleData
} from '../util/i18n'
import { getModesForActiveAgencyFilter, getUiUrlParams } from '../util/state'
import { getPathFromParts } from '../util/ui'

import { clearActiveSearch, parseUrlQueryString, setActiveSearch } from './form'
import { clearLocation } from './map'
import { findRoute, setUrlSearch } from './api'
import { setActiveItinerary } from './narrative'
import { setMapCenter, setMapZoom, setRouterId } from './config'

const updateLocale = createAction('UPDATE_LOCALE')

// UI state enums

export const MainPanelContent = {
  ROUTE_VIEWER: 1,
  STOP_VIEWER: 2
}

export const MobileScreens = {
  RESULTS_SUMMARY: 8,
  SEARCH_FORM: 3,
  SET_DATETIME: 7,
  SET_FROM_LOCATION: 4,
  SET_INITIAL_LOCATION: 2,
  SET_OPTIONS: 6,
  SET_TO_LOCATION: 5,
  WELCOME_SCREEN: 1
}

/**
 * Enum to describe the layout of the itinerary view
 * (currently only used in batch results).
 */
export const ItineraryView = {
  /** One itinerary is shown. (In mobile view, the map is hidden.) */
  FULL: 'full',
  /** One itinerary is shown, itinerary and map are focused on a leg. (The mobile view is split.) */
  LEG: 'leg',
  /** One itinerary leg is hidden. (In mobile view, the map is expanded.) */
  LEG_HIDDEN: 'leg-hidden',
  /** The list of itineraries is shown. (The mobile view is split.) */
  LIST: 'list',
  /** The list of itineraries is hidden. (In mobile view, the map is expanded.) */
  LIST_HIDDEN: 'list-hidden'
}

const setPanel = createAction('SET_MAIN_PANEL_CONTENT')
export const setMobileScreen = createAction('SET_MOBILE_SCREEN')
export const clearPanel = createAction('CLEAR_MAIN_PANEL')
const viewStop = createAction('SET_VIEWED_STOP')
export const setHoveredStop = createAction('SET_HOVERED_STOP')
export const setViewedTrip = createAction('SET_VIEWED_TRIP')
const viewRoute = createAction('SET_VIEWED_ROUTE')
export const toggleAutoRefresh = createAction('TOGGLE_AUTO_REFRESH')
const setPreviousItineraryView = createAction('SET_PREVIOUS_ITINERARY_VIEW')

/**
 * Wrapper function for history#push (or, if specified, replace, etc.)
 * that preserves the current search or, if
 * replaceSearch is provided (including an empty string), replaces the search
 * when routing to a new URL path.
 * @param  {[type]} url           path to route to
 * @param  {string} replaceSearch optional search string to replace current one
 * @param  {func}   routingMethod the connected-react-router method to execute (defaults to push).
 */
export function routeTo(url, replaceSearch, routingMethod = push) {
  return function (dispatch, getState) {
    // Get search to preserve when routing to new path.
    const { router } = getState()
    const search = router ? router.location.search : window.location.search
    let path = url
    if (replaceSearch || replaceSearch === '') {
      path = `${path}${replaceSearch}`
    } else {
      path = `${path}${search}`
    }
    dispatch(routingMethod(path))
  }
}

export function setViewedRoute(payload) {
  return function (dispatch, getState) {
    dispatch(viewRoute(payload))

    const path = getPathFromParts(
      'route',
      payload?.routeId,
      // If a pattern is supplied, include pattern in path
      payload?.patternId && 'pattern',
      payload?.patternId
    )
    dispatch(routeTo(path))
  }
}

/**
 * Sets the main panel content according to the payload (one of the enum values
 * of MainPanelContent) and routes the application to the correct path.
 * @param {number} payload MainPanelContent value
 */
export function setMainPanelContent(payload) {
  return function (dispatch, getState) {
    const { otp, router } = getState()
    if (otp.ui.mainPanelContent === payload) {
      console.warn(
        `Attempt to route from ${otp.ui.mainPanelContent} to ${payload}. Doing nothing`
      )
      // Do nothing if the panel is already set. This will guard against over
      // enthusiastic routing and overwriting current/nested states.
      return
    }
    dispatch(setPanel(payload))
    switch (payload) {
      case MainPanelContent.ROUTE_VIEWER:
        dispatch(routeTo('/route'))
        break
      case MainPanelContent.STOP_VIEWER:
        dispatch(routeTo('/stop'))
        break
      default:
        // Clear route, stop, and trip viewer focus and route to root
        dispatch(viewRoute(null))
        dispatch(viewStop(null))
        dispatch(setViewedTrip(null))
        if (router.location.pathname !== '/') dispatch(routeTo('/'))
        break
    }
  }
}

// Stop/Route/Trip Viewer actions
export function setViewedStop(payload) {
  return function (dispatch, getState) {
    dispatch(viewStop(payload))
    // payload.stopId may be undefined, which is ok as will be ignored by getPathFromParts
    const path = getPathFromParts('stop', payload?.stopId)
    dispatch(routeTo(path))
  }
}

/**
 * Split the path id into its parts (according to specified delimiter). Parse
 * numbers if detected.
 */
function idToParams(id, delimiter = ',') {
  return id.split(delimiter).map((s) => (isNaN(s) ? s : +s))
}

/**
 * Checks URL and redirects app to appropriate content (e.g., viewed
 * route or stop).
 */
export function matchContentToUrl(location) {
  // eslint-disable-next-line complexity
  return function (dispatch, getState) {
    // This is a bit of a hack to make up for the fact that react-router does
    // not always provide the match params as expected.
    // https://github.com/ReactTraining/react-router/issues/5870#issuecomment-394194338
    const root = location.pathname.split('/')[1]
    const match = matchPath(location.pathname, {
      exact: false,
      path: `/${root}/:id`,
      strict: false
    })
    const id = match?.params?.id
    switch (root) {
      case 'route':
        if (id) {
          dispatch(findRoute({ routeId: id }))
          // Check for pattern "submatch"
          const subMatch = matchPath(location.pathname, {
            exact: true,
            path: `/${root}/:id/pattern/:patternId`,
            strict: false
          })
          const patternId = subMatch?.params?.patternId
          // patternId may be undefined, which is OK as the route will still be routed
          dispatch(setViewedRoute({ patternId, routeId: id }))
        } else {
          dispatch(setViewedRoute(null))
          dispatch(setMainPanelContent(MainPanelContent.ROUTE_VIEWER))
        }
        break
      case 'stop':
        if (id) {
          dispatch(setViewedStop({ stopId: id }))
        } else {
          dispatch(setViewedStop(null))
          dispatch(setMainPanelContent(MainPanelContent.STOP_VIEWER))
        }
        break
      case 'start':
      case '@': {
        // Parse comma separated params (ensuring numbers are parsed correctly).
        let [lat, lon, zoom, routerId] = id ? idToParams(id) : []
        if (!lat || !lon) {
          // Attempt to parse path if lat/lon not found. (Legacy UI otp.js used
          // slashes in the pathname to specify lat, lon, etc.)
          // prettier-ignore
          [,, lat, lon, zoom, routerId] = idToParams(location.pathname, '/')
        }
        console.log(lat, lon, zoom, routerId)
        // Update map location/zoom and optionally override router ID.
        if (+lat && +lon) dispatch(setMapCenter({ lat, lon }))
        if (+zoom) dispatch(setMapZoom({ zoom }))
        // If router ID is provided, override the default routerId.
        if (routerId) dispatch(setRouterId(routerId))
        dispatch(setMainPanelContent(null))
        break
      }
      // For any other route path, just revert to default panel.
      default:
        dispatch(setMainPanelContent(null))
        break
    }
  }
}

/**
 * Event listener for responsive webapp that handles a back button press and
 * sets the active search and itinerary according to the URL query params.
 */
export function handleBackButtonPress(e) {
  return function (dispatch, getState) {
    const state = getState()
    const { activeSearchId } = state.otp
    const uiUrlParams = getUiUrlParams(state)
    // Get new search ID from URL after back button pressed.
    // console.log('back button pressed', e)
    const urlParams = coreUtils.query.getUrlParams()
    const previousSearchId = urlParams.ui_activeSearch
    const previousItinIndex = +urlParams.ui_activeItinerary || 0
    const previousSearch = state.otp.searches[previousSearchId]
    if (previousSearch) {
      // If back button pressed and active search has changed, set search to
      // previous search ID.
      if (activeSearchId !== previousSearchId) {
        dispatch(setActiveSearch(previousSearchId))
      } else if (uiUrlParams.ui_activeItinerary !== previousItinIndex) {
        // Active itinerary index has changed.
        dispatch(setActiveItinerary({ index: previousItinIndex }))
      }
    } else {
      // The back button was pressed, but there was no corresponding search
      // found for the previous search ID. Derive search from URL params.
      if (!previousSearchId && activeSearchId) {
        // There is no search ID. Clear active search and from/to
        dispatch(clearActiveSearch())
        dispatch(clearLocation({ type: 'from' }))
        dispatch(clearLocation({ type: 'to' }))
      } else if (previousSearchId) {
        console.warn(
          `No search found in state history for search ID: ${previousSearchId}. Replanning...`
        )
        // Set query to the params found in the URL and perform routing query
        // for search ID.
        // Also, we don't want to update the URL here because that will funk with
        // the browser history.
        dispatch(parseUrlQueryString(urlParams))
      }
    }
  }
}

/**
 * Sets the itinerary view state (see values above) in the URL params
 * (currently only used in batch results).
 */
export function setItineraryView(value) {
  return function (dispatch, getState) {
    const urlParams = coreUtils.query.getUrlParams()
    const prevItineraryView = urlParams.ui_itineraryView || ItineraryView.LIST

    // If the itinerary value is changed,
    // set the desired ui query param, or remove it if same as default,
    // and store the current view as previousItineraryView.
    if (value !== urlParams.ui_itineraryView) {
      if (value !== ItineraryView.LIST) {
        urlParams.ui_itineraryView = value
      } else if (urlParams.ui_itineraryView) {
        delete urlParams.ui_itineraryView
      }

      dispatch(setUrlSearch(urlParams))
      dispatch(setPreviousItineraryView(prevItineraryView))
    }
  }
}

/**
 * Switch the mobile batch results view between full map view and the split state
 * (itinerary list or itinerary leg view) that was in place prior.
 */
export function toggleBatchResultsMap() {
  return function (dispatch, getState) {
    const urlParams = coreUtils.query.getUrlParams()
    const itineraryView = urlParams.ui_itineraryView || ItineraryView.LIST

    if (itineraryView === ItineraryView.LEG) {
      dispatch(setItineraryView(ItineraryView.LEG_HIDDEN))
    } else if (itineraryView === ItineraryView.LIST) {
      dispatch(setItineraryView(ItineraryView.LIST_HIDDEN))
    } else {
      const { previousItineraryView } = getState().otp.ui
      dispatch(setItineraryView(previousItineraryView))
    }
  }
}

/**
 * Takes the user back to the mobile search screen in mobile views.
 */
export function showMobileSearchScreen() {
  return function (dispatch, getState) {
    // Reset itinerary view state to show the list of results *before* clearing the search.
    // (Otherwise, if the map is expanded, the search is not cleared.)
    dispatch(setItineraryView(ItineraryView.LIST))
    dispatch(clearActiveSearch())
    dispatch(setMobileScreen(MobileScreens.SEARCH_FORM))
  }
}

/**
 * Sets the locale to the specified value and loads the corresponding messages.
 * If the specified locale is null, fall back to the defaultLocale
 * set in the configuration.
 * Also update the lang attribute on the root <html> element for accessibility.
 */
export function setLocale(locale) {
  return async function (dispatch, getState) {
    const { config } = getState().otp
    const { loggedInUser } = getState().user
    const { language: customMessages } = config
    const configLocales = getConfigLocales(customMessages)
    const effectiveLocale = locale || getDefaultLocale(config, loggedInUser)
    const matchedLocale = getMatchingLocaleString(effectiveLocale, 'en-US')
    const messages = await loadLocaleData(
      matchedLocale,
      customMessages,
      configLocales
    )

    // Update the redux state, only with a matched locale
    dispatch(updateLocale({ locale: matchedLocale, messages }))

    // Update the lang attribute in the root <html> element.
    // (The lang is the first portion of the locale.)
    const lang = effectiveLocale.split('-')[0]
    document.documentElement.lang = lang
  }
}

const updateRouteViewerFilter = createAction('UPDATE_ROUTE_VIEWER_FILTER')
/**
 * Updates the route viewer filter
 * @param {*} filter Object which includes either agency, mode, and/or search
 */
export function setRouteViewerFilter(filter) {
  return async function (dispatch, getState) {
    dispatch(updateRouteViewerFilter(filter))

    // If we're changing agency, and have a mode selected,
    // ensure that the mode filter doesn't select non-existent modes!
    const activeModeFilter = getState().otp.ui.routeViewer.filter.mode
    if (
      filter.agency &&
      activeModeFilter &&
      !getModesForActiveAgencyFilter(getState()).includes(
        activeModeFilter.toUpperCase()
      )
    ) {
      // If invalid mode is selected, reset mode
      dispatch(updateRouteViewerFilter({ mode: null }))
    }
  }
}
<commit_msg>refactor(setLocale): Pass missing configLocales to locale matching fn<commit_after>import { createAction } from 'redux-actions'
import { matchPath } from 'react-router'
import { push } from 'connected-react-router'
import coreUtils from '@opentripplanner/core-utils'

import {
  getConfigLocales,
  getDefaultLocale,
  getMatchingLocaleString,
  loadLocaleData
} from '../util/i18n'
import { getModesForActiveAgencyFilter, getUiUrlParams } from '../util/state'
import { getPathFromParts } from '../util/ui'

import { clearActiveSearch, parseUrlQueryString, setActiveSearch } from './form'
import { clearLocation } from './map'
import { findRoute, setUrlSearch } from './api'
import { setActiveItinerary } from './narrative'
import { setMapCenter, setMapZoom, setRouterId } from './config'

const updateLocale = createAction('UPDATE_LOCALE')

// UI state enums

export const MainPanelContent = {
  ROUTE_VIEWER: 1,
  STOP_VIEWER: 2
}

export const MobileScreens = {
  RESULTS_SUMMARY: 8,
  SEARCH_FORM: 3,
  SET_DATETIME: 7,
  SET_FROM_LOCATION: 4,
  SET_INITIAL_LOCATION: 2,
  SET_OPTIONS: 6,
  SET_TO_LOCATION: 5,
  WELCOME_SCREEN: 1
}

/**
 * Enum to describe the layout of the itinerary view
 * (currently only used in batch results).
 */
export const ItineraryView = {
  /** One itinerary is shown. (In mobile view, the map is hidden.) */
  FULL: 'full',
  /** One itinerary is shown, itinerary and map are focused on a leg. (The mobile view is split.) */
  LEG: 'leg',
  /** One itinerary leg is hidden. (In mobile view, the map is expanded.) */
  LEG_HIDDEN: 'leg-hidden',
  /** The list of itineraries is shown. (The mobile view is split.) */
  LIST: 'list',
  /** The list of itineraries is hidden. (In mobile view, the map is expanded.) */
  LIST_HIDDEN: 'list-hidden'
}

const setPanel = createAction('SET_MAIN_PANEL_CONTENT')
export const setMobileScreen = createAction('SET_MOBILE_SCREEN')
export const clearPanel = createAction('CLEAR_MAIN_PANEL')
const viewStop = createAction('SET_VIEWED_STOP')
export const setHoveredStop = createAction('SET_HOVERED_STOP')
export const setViewedTrip = createAction('SET_VIEWED_TRIP')
const viewRoute = createAction('SET_VIEWED_ROUTE')
export const toggleAutoRefresh = createAction('TOGGLE_AUTO_REFRESH')
const setPreviousItineraryView = createAction('SET_PREVIOUS_ITINERARY_VIEW')

/**
 * Wrapper function for history#push (or, if specified, replace, etc.)
 * that preserves the current search or, if
 * replaceSearch is provided (including an empty string), replaces the search
 * when routing to a new URL path.
 * @param  {[type]} url           path to route to
 * @param  {string} replaceSearch optional search string to replace current one
 * @param  {func}   routingMethod the connected-react-router method to execute (defaults to push).
 */
export function routeTo(url, replaceSearch, routingMethod = push) {
  return function (dispatch, getState) {
    // Get search to preserve when routing to new path.
    const { router } = getState()
    const search = router ? router.location.search : window.location.search
    let path = url
    if (replaceSearch || replaceSearch === '') {
      path = `${path}${replaceSearch}`
    } else {
      path = `${path}${search}`
    }
    dispatch(routingMethod(path))
  }
}

export function setViewedRoute(payload) {
  return function (dispatch, getState) {
    dispatch(viewRoute(payload))

    const path = getPathFromParts(
      'route',
      payload?.routeId,
      // If a pattern is supplied, include pattern in path
      payload?.patternId && 'pattern',
      payload?.patternId
    )
    dispatch(routeTo(path))
  }
}

/**
 * Sets the main panel content according to the payload (one of the enum values
 * of MainPanelContent) and routes the application to the correct path.
 * @param {number} payload MainPanelContent value
 */
export function setMainPanelContent(payload) {
  return function (dispatch, getState) {
    const { otp, router } = getState()
    if (otp.ui.mainPanelContent === payload) {
      console.warn(
        `Attempt to route from ${otp.ui.mainPanelContent} to ${payload}. Doing nothing`
      )
      // Do nothing if the panel is already set. This will guard against over
      // enthusiastic routing and overwriting current/nested states.
      return
    }
    dispatch(setPanel(payload))
    switch (payload) {
      case MainPanelContent.ROUTE_VIEWER:
        dispatch(routeTo('/route'))
        break
      case MainPanelContent.STOP_VIEWER:
        dispatch(routeTo('/stop'))
        break
      default:
        // Clear route, stop, and trip viewer focus and route to root
        dispatch(viewRoute(null))
        dispatch(viewStop(null))
        dispatch(setViewedTrip(null))
        if (router.location.pathname !== '/') dispatch(routeTo('/'))
        break
    }
  }
}

// Stop/Route/Trip Viewer actions
export function setViewedStop(payload) {
  return function (dispatch, getState) {
    dispatch(viewStop(payload))
    // payload.stopId may be undefined, which is ok as will be ignored by getPathFromParts
    const path = getPathFromParts('stop', payload?.stopId)
    dispatch(routeTo(path))
  }
}

/**
 * Split the path id into its parts (according to specified delimiter). Parse
 * numbers if detected.
 */
function idToParams(id, delimiter = ',') {
  return id.split(delimiter).map((s) => (isNaN(s) ? s : +s))
}

/**
 * Checks URL and redirects app to appropriate content (e.g., viewed
 * route or stop).
 */
export function matchContentToUrl(location) {
  // eslint-disable-next-line complexity
  return function (dispatch, getState) {
    // This is a bit of a hack to make up for the fact that react-router does
    // not always provide the match params as expected.
    // https://github.com/ReactTraining/react-router/issues/5870#issuecomment-394194338
    const root = location.pathname.split('/')[1]
    const match = matchPath(location.pathname, {
      exact: false,
      path: `/${root}/:id`,
      strict: false
    })
    const id = match?.params?.id
    switch (root) {
      case 'route':
        if (id) {
          dispatch(findRoute({ routeId: id }))
          // Check for pattern "submatch"
          const subMatch = matchPath(location.pathname, {
            exact: true,
            path: `/${root}/:id/pattern/:patternId`,
            strict: false
          })
          const patternId = subMatch?.params?.patternId
          // patternId may be undefined, which is OK as the route will still be routed
          dispatch(setViewedRoute({ patternId, routeId: id }))
        } else {
          dispatch(setViewedRoute(null))
          dispatch(setMainPanelContent(MainPanelContent.ROUTE_VIEWER))
        }
        break
      case 'stop':
        if (id) {
          dispatch(setViewedStop({ stopId: id }))
        } else {
          dispatch(setViewedStop(null))
          dispatch(setMainPanelContent(MainPanelContent.STOP_VIEWER))
        }
        break
      case 'start':
      case '@': {
        // Parse comma separated params (ensuring numbers are parsed correctly).
        let [lat, lon, zoom, routerId] = id ? idToParams(id) : []
        if (!lat || !lon) {
          // Attempt to parse path if lat/lon not found. (Legacy UI otp.js used
          // slashes in the pathname to specify lat, lon, etc.)
          // prettier-ignore
          [,, lat, lon, zoom, routerId] = idToParams(location.pathname, '/')
        }
        console.log(lat, lon, zoom, routerId)
        // Update map location/zoom and optionally override router ID.
        if (+lat && +lon) dispatch(setMapCenter({ lat, lon }))
        if (+zoom) dispatch(setMapZoom({ zoom }))
        // If router ID is provided, override the default routerId.
        if (routerId) dispatch(setRouterId(routerId))
        dispatch(setMainPanelContent(null))
        break
      }
      // For any other route path, just revert to default panel.
      default:
        dispatch(setMainPanelContent(null))
        break
    }
  }
}

/**
 * Event listener for responsive webapp that handles a back button press and
 * sets the active search and itinerary according to the URL query params.
 */
export function handleBackButtonPress(e) {
  return function (dispatch, getState) {
    const state = getState()
    const { activeSearchId } = state.otp
    const uiUrlParams = getUiUrlParams(state)
    // Get new search ID from URL after back button pressed.
    // console.log('back button pressed', e)
    const urlParams = coreUtils.query.getUrlParams()
    const previousSearchId = urlParams.ui_activeSearch
    const previousItinIndex = +urlParams.ui_activeItinerary || 0
    const previousSearch = state.otp.searches[previousSearchId]
    if (previousSearch) {
      // If back button pressed and active search has changed, set search to
      // previous search ID.
      if (activeSearchId !== previousSearchId) {
        dispatch(setActiveSearch(previousSearchId))
      } else if (uiUrlParams.ui_activeItinerary !== previousItinIndex) {
        // Active itinerary index has changed.
        dispatch(setActiveItinerary({ index: previousItinIndex }))
      }
    } else {
      // The back button was pressed, but there was no corresponding search
      // found for the previous search ID. Derive search from URL params.
      if (!previousSearchId && activeSearchId) {
        // There is no search ID. Clear active search and from/to
        dispatch(clearActiveSearch())
        dispatch(clearLocation({ type: 'from' }))
        dispatch(clearLocation({ type: 'to' }))
      } else if (previousSearchId) {
        console.warn(
          `No search found in state history for search ID: ${previousSearchId}. Replanning...`
        )
        // Set query to the params found in the URL and perform routing query
        // for search ID.
        // Also, we don't want to update the URL here because that will funk with
        // the browser history.
        dispatch(parseUrlQueryString(urlParams))
      }
    }
  }
}

/**
 * Sets the itinerary view state (see values above) in the URL params
 * (currently only used in batch results).
 */
export function setItineraryView(value) {
  return function (dispatch, getState) {
    const urlParams = coreUtils.query.getUrlParams()
    const prevItineraryView = urlParams.ui_itineraryView || ItineraryView.LIST

    // If the itinerary value is changed,
    // set the desired ui query param, or remove it if same as default,
    // and store the current view as previousItineraryView.
    if (value !== urlParams.ui_itineraryView) {
      if (value !== ItineraryView.LIST) {
        urlParams.ui_itineraryView = value
      } else if (urlParams.ui_itineraryView) {
        delete urlParams.ui_itineraryView
      }

      dispatch(setUrlSearch(urlParams))
      dispatch(setPreviousItineraryView(prevItineraryView))
    }
  }
}

/**
 * Switch the mobile batch results view between full map view and the split state
 * (itinerary list or itinerary leg view) that was in place prior.
 */
export function toggleBatchResultsMap() {
  return function (dispatch, getState) {
    const urlParams = coreUtils.query.getUrlParams()
    const itineraryView = urlParams.ui_itineraryView || ItineraryView.LIST

    if (itineraryView === ItineraryView.LEG) {
      dispatch(setItineraryView(ItineraryView.LEG_HIDDEN))
    } else if (itineraryView === ItineraryView.LIST) {
      dispatch(setItineraryView(ItineraryView.LIST_HIDDEN))
    } else {
      const { previousItineraryView } = getState().otp.ui
      dispatch(setItineraryView(previousItineraryView))
    }
  }
}

/**
 * Takes the user back to the mobile search screen in mobile views.
 */
export function showMobileSearchScreen() {
  return function (dispatch, getState) {
    // Reset itinerary view state to show the list of results *before* clearing the search.
    // (Otherwise, if the map is expanded, the search is not cleared.)
    dispatch(setItineraryView(ItineraryView.LIST))
    dispatch(clearActiveSearch())
    dispatch(setMobileScreen(MobileScreens.SEARCH_FORM))
  }
}

/**
 * Sets the locale to the specified value and loads the corresponding messages.
 * If the specified locale is null, fall back to the defaultLocale
 * set in the configuration.
 * Also update the lang attribute on the root <html> element for accessibility.
 */
export function setLocale(locale) {
  return async function (dispatch, getState) {
    const { config } = getState().otp
    const { loggedInUser } = getState().user
    const { language: customMessages } = config
    const configLocales = getConfigLocales(customMessages)
    const effectiveLocale = locale || getDefaultLocale(config, loggedInUser)
    const matchedLocale = getMatchingLocaleString(
      effectiveLocale,
      'en-US',
      configLocales
    )
    const messages = await loadLocaleData(
      matchedLocale,
      customMessages,
      configLocales
    )

    // Update the redux state, only with a matched locale
    dispatch(updateLocale({ locale: matchedLocale, messages }))

    // Update the lang attribute in the root <html> element.
    // (The lang is the first portion of the locale.)
    const lang = effectiveLocale.split('-')[0]
    document.documentElement.lang = lang
  }
}

const updateRouteViewerFilter = createAction('UPDATE_ROUTE_VIEWER_FILTER')
/**
 * Updates the route viewer filter
 * @param {*} filter Object which includes either agency, mode, and/or search
 */
export function setRouteViewerFilter(filter) {
  return async function (dispatch, getState) {
    dispatch(updateRouteViewerFilter(filter))

    // If we're changing agency, and have a mode selected,
    // ensure that the mode filter doesn't select non-existent modes!
    const activeModeFilter = getState().otp.ui.routeViewer.filter.mode
    if (
      filter.agency &&
      activeModeFilter &&
      !getModesForActiveAgencyFilter(getState()).includes(
        activeModeFilter.toUpperCase()
      )
    ) {
      // If invalid mode is selected, reset mode
      dispatch(updateRouteViewerFilter({ mode: null }))
    }
  }
}
<|endoftext|>


<commit_before>import Ember from 'ember';

var config = {
  'image-service': [
    {
      name: 'photos',
      routeName: 'image-service.photos'
    }, {
      name: 'search',
      routeName: 'image-service.search'
    }, {
      name: 'upload',
      routeName: 'image-service.upload'
    }
  ],
  'image-service.photo': [
    {
      name: 'properties',
      routeName: 'image-service.photo.properties'
    }, {
      name: 'crops',
      routeName: 'image-service.photo.crops'
    }
  ]
};

export default Ember.Service.extend({
  init() {
    this.set('config', config);
  },

  getTabs(route) {
    return this.get('config')[route.routeName];
  }

});
<commit_msg>Fixed local menu service<commit_after>import Ember from 'ember';

var config = {
  'container.image-service': [
    {
      name: 'photos',
      routeName: 'image-service.photos'
    }, {
      name: 'search',
      routeName: 'image-service.search'
    }, {
      name: 'upload',
      routeName: 'image-service.upload'
    }
  ],
  'container.image-service.photo': [
    {
      name: 'properties',
      routeName: 'image-service.photo.properties'
    }, {
      name: 'crops',
      routeName: 'image-service.photo.crops'
    }
  ]
};

export default Ember.Service.extend({
  init() {
    this.set('config', config);
  },

  getTabs(route) {
    return this.get('config')[route.routeName];
  }

});
<|endoftext|>


<commit_before>;(function(factors){
    var worker = new Worker('js/factorisation-worker.js');

    var input = document.getElementById('n');
    var output = document.getElementById('factors');

    worker.addEventListener('message', function(event){
        if (event.data.type == 'factor') {
            output.innerHTML += event.data.d;
            output.innerHTML += '×'
        }
        if (event.data.type == 'finish') {
            output.innerHTML += '1'
        }
        console.log(event.data);

    });

    function calculateFactors(){
        try {
            output.innerHTML = '';
            var n = parseInt(input.value);
            worker.postMessage({ 'n': n });
        } catch(e) {
            /* do nothing */
        }
    }

    input.addEventListener('change', calculateFactors);

    calculateFactors();

    var connection = new WebSocket('ws://localhost:8080');
    connection.onopen = function(){
        console.log('open connection');
    }
    connection.onclose = function(){
        console.log('close connection');
    }
})(factors);
<commit_msg>client handle message<commit_after>;(function(factors){
    var worker = new Worker('js/factorisation-worker.js');

    var input = document.getElementById('n');
    var output = document.getElementById('factors');

    worker.addEventListener('message', function(event){
        if (event.data.type == 'factor') {
            output.innerHTML += event.data.d;
            output.innerHTML += '×'
        }
        if (event.data.type == 'finish') {
            output.innerHTML += '1'
        }
        console.log(event.data);

    });

    function calculateFactors(){
        try {
            output.innerHTML = '';
            var n = parseInt(input.value);
            worker.postMessage({ 'n': n });
        } catch(e) {
            /* do nothing */
        }
    }

    input.addEventListener('change', calculateFactors);

    calculateFactors();

    var connection = new WebSocket('ws://localhost:8080');
    connection.onopen = function(){
        console.log('open connection');
    }
    connection.onclose = function(){
        console.log('close connection');
    }
    connection.onmessage = function(message){
        console.log(message);
    }
})(factors);
<|endoftext|>


<commit_before>/**
 * extension of Field class to support file field
 */
appForm.models.Field = function (module) {
  function checkFileObj(obj) {
    return obj.fileName && obj.fileType && obj.hashName;
  }
  module.prototype.process_file = function (params, cb) {
    var inputValue = params.value;
    var isStore = params.isStore === undefined ? true : params.isStore;
    if (typeof inputValue === 'undefined' || inputValue === null) {
      return cb(null, null);
    }
    if (typeof inputValue !== 'object' || !inputValue instanceof HTMLInputElement && !inputValue instanceof File && !checkFileObj(inputValue)) {
      throw 'the input value for file field should be a html file input element or a File object';
    }
    if (checkFileObj(inputValue)) {
      return cb(null, inputValue);
    }
    var file = inputValue;
    if (inputValue instanceof HTMLInputElement) {
      file = inputValue.files[0];  // 1st file only, not support many files yet.
    }

    if(typeof(file.lastModifiedDate) === 'undefined'){
      file.lastModifiedDate = appForm.utils.getTime();
    }
    var rtnJSON = {
        'fileName': file.name,
        'fileSize': file.size,
        'fileType': file.type,
        'fileUpdateTime': file.lastModifiedDate,
        'hashName': '',
        'contentType': 'binary'
      };
    var name = file.name + new Date().getTime() + Math.ceil(Math.random() * 100000);
    appForm.utils.md5(name, function (err, res) {
      var hashName = res;
      if (err) {
        hashName = name;
      }
      hashName = 'filePlaceHolder' + hashName;
      rtnJSON.hashName = hashName;
      if (isStore) {
        appForm.utils.fileSystem.save(hashName, file, function (err, res) {
          if (err) {
            $fh.forms.log.e(err);
            cb(err);
          } else {
            cb(null, rtnJSON);
          }
        });
      } else {
        cb(null, rtnJSON);
      }
    });
  };
  return module;
}(appForm.models.Field || {});<commit_msg>Fixed date issue with submitting files<commit_after>/**
 * extension of Field class to support file field
 */
appForm.models.Field = function (module) {
  function checkFileObj(obj) {
    return obj.fileName && obj.fileType && obj.hashName;
  }
  module.prototype.process_file = function (params, cb) {
    var inputValue = params.value;
    var isStore = params.isStore === undefined ? true : params.isStore;
    var lastModDate = new Date().getTime();
    if (typeof inputValue === 'undefined' || inputValue === null) {
      return cb(null, null);
    }
    if (typeof inputValue !== 'object' || !inputValue instanceof HTMLInputElement && !inputValue instanceof File && !checkFileObj(inputValue)) {
      throw 'the input value for file field should be a html file input element or a File object';
    }
    if (checkFileObj(inputValue)) {
      return cb(null, inputValue);
    }
    var file = inputValue;
    if (inputValue instanceof HTMLInputElement) {
      file = inputValue.files[0];  // 1st file only, not support many files yet.
    }

    if(typeof(file.lastModifiedDate) === 'undefined'){
      lastModDate = appForm.utils.getTime().getTime();
    }

    if(file.lastModifiedDate instanceof Date){
      lastModDate = file.lastModifiedDate.getTime();
    }
    var rtnJSON = {
        'fileName': file.name,
        'fileSize': file.size,
        'fileType': file.type,
        'fileUpdateTime': lastModDate,
        'hashName': '',
        'contentType': 'binary'
      };
    var name = file.name + new Date().getTime() + Math.ceil(Math.random() * 100000);
    appForm.utils.md5(name, function (err, res) {
      var hashName = res;
      if (err) {
        hashName = name;
      }
      hashName = 'filePlaceHolder' + hashName;
      rtnJSON.hashName = hashName;
      if (isStore) {
        appForm.utils.fileSystem.save(hashName, file, function (err, res) {
          if (err) {
            $fh.forms.log.e(err);
            cb(err);
          } else {
            cb(null, rtnJSON);
          }
        });
      } else {
        cb(null, rtnJSON);
      }
    });
  };
  return module;
}(appForm.models.Field || {});<|endoftext|>


<commit_before>export const MAIN_USER_KEY = 'USER_KEYS';
export const SECURE_SESSION_STORAGE_KEY = 'SECURE';
export const MAILBOX_PASSWORD_KEY = 'proton:mailbox_pwd';
export const UID_KEY = 'proton:oauth:UID';
export const INTERVAL_EVENT_TIMER = 30 * 1000;
export const EVENT_ACTIONS = {
    DELETE: 0,
    CREATE: 1,
    UPDATE: 2,
    UPDATE_DRAFT: 2,
    UPDATE_FLAGS: 3
};
export const USER_ROLES = {
    FREE_ROLE: 0,
    MEMBER_ROLE: 1,
    ADMIN_ROLE: 2
};
export const ELEMENTS_PER_PAGE = 10;
export const INVOICE_OWNER = {
    USER: 0,
    ORGANIZATION: 1
};
export const DEFAULT_CURRENCY = 'EUR';
export const CURRENCIES = ['EUR', 'USD', 'CHF'];
export const MIN_BITCOIN_AMOUNT = 500;
export const DEFAULT_DONATION_AMOUNT = 2500;
export const BTC_DONATION_ADDRESS = '1Q1nhq1NbxPYAbw1BppwKbCqg58ZqMb9A8';
export const AUTH_LOG_EVENTS = {
    LOGIN_FAILURE_PASSWORD: 0,
    LOGIN_SUCCESS: 1,
    LOGOUT: 2,
    LOGIN_FAILURE_2FA: 3,
    LOGIN_SUCCESS_AWAIT_2FA: 4
};
export const INVOICE_TYPE = {
    OTHER: 0,
    SUBSCRIPTION: 1,
    CANCELLATION: 2,
    CREDIT: 3,
    DONATION: 4
};
export const INVOICE_STATE = {
    UNPAID: 0,
    PAID: 1,
    VOID: 2,
    BILLED: 3
};

export const BASE_SIZE = 1024;
export const GIGA = BASE_SIZE ** 3;

export const LOGS_STATE = {
    DISABLE: 0,
    BASIC: 1,
    ADVANCED: 2
};

export const MEMBER_TYPE = {
    MEMBER: 0,
    SUB_MEMBER: 1
};

export const DOMAIN_STATE = {
    DOMAIN_STATE_DEFAULT: 0, // Domain's State before verify or after deactivation
    DOMAIN_STATE_ACTIVE: 1, // active once verified
    DOMAIN_STATE_WARN: 2 // detected backward DNS change after ACTIVE
};

export const VERIFY_STATE = {
    VERIFY_STATE_DEFAULT: 0, // 0 is default, no good
    VERIFY_STATE_EXIST: 1, // 1 is has code but doesn't match DB's, no good
    VERIFY_STATE_GOOD: 2 // 2 is has code and matches DB's, good!
};

export const MX_STATE = {
    MX_STATE_DEFAULT: 0, // 0 is default, no good
    MX_STATE_NO_US: 1, // 1 is set but does not have us
    MX_STATE_INC_US: 2, // 2 is includes our MX but priority no good
    MX_STATE_GOOD: 3 // 3 is includes our MX and we are highest and pri is legit, good!
};

export const SPF_STATE = {
    SPF_STATE_DEFAULT: 0, // 0 is default, no spf record
    SPF_STATE_ONE: 1, // 1 is has spf record but not us
    SPF_STATE_MULT: 2, // 2 is has multiple spf records, no good
    SPF_STATE_GOOD: 3 // 3 is has spf record and includes us, good!
};

export const DKIM_STATE = {
    DKIM_STATE_DEFAULT: 0, // 0 is default, no dkim record
    DKIM_STATE_ONE: 1, // 1 is found entries but format wrong
    DKIM_STATE_MULT: 2, // 2 is multiple dkim records, no good
    DKIM_STATE_CHECK: 3, // 3 is proper entry, but did not check or did not match DB's public key
    DKIM_STATE_GOOD: 4, // 4 is proper entry and matches DB's public key, good!
    DKIM_STATE_OFF: 5 // 5 is User wants to stop signing with dkim
};

export const DMARC_STATE = {
    DMARC_STATE_DEFAULT: 0, // 0 is default, no dmarc record
    DMARC_STATE_ONE: 1, // 1 is found entries but format wrong
    DMARC_STATE_MULT: 2, // 2 is multiple dmarc records, no good
    DMARC_STATE_GOOD: 3 // 3 is good!
};

export const ADDRESS_STATUS = {
    STATUS_DISABLED: 0,
    STATUS_ENABLED: 1
};

export const ADDRESS_TYPE = {
    TYPE_ORIGINAL: 1,
    TYPE_ALIAS: 2,
    TYPE_CUSTOM_DOMAIN: 3,
    TYPE_PREMIUM: 4
};

export const RECEIVE_ADDRESS = {
    RECEIVE_YES: 1,
    RECEIVE_NO: 0
};

export const SEND_ADDRESS = {
    SEND_YES: 1,
    SEND_NO: 0
};

export const MEMBER_PRIVATE = {
    READABLE: 0,
    UNREADABLE: 1
};

export const MEMBER_ROLE = {
    ORGANIZATION_NONE: 0,
    ORGANIZATION_MEMBER: 1,
    ORGANIZATION_OWNER: 2
};

export const PACKAGE_TYPE = {
    SEND_PM: 1,
    SEND_EO: 2,
    SEND_CLEAR: 4,
    SEND_PGP_INLINE: 8,
    SEND_PGP_MIME: 16
};

export const SHOW_IMAGES = {
    REMOTE: 1,
    EMBEDDED: 2
};

export const COMPOSER_MODE = {
    POPUP: 0,
    MAXIMIZED: 1
};

export const DEFAULT_CYCLE = 12;

export const CYCLE = {
    MONTHLY: 1,
    YEARLY: 12,
    TWO_YEARS: 24
};

export const BUNDLE_COUPON_CODE = 'BUNDLE';
const BLACK_FRIDAY_YEAR = 2018;
export const BLACK_FRIDAY = {
    YEAR: BLACK_FRIDAY_YEAR,
    COUPON_CODE: 'TWO4ONE2018',
    CYCLE: CYCLE.TWO_YEARS,
    BETWEEN: {
        START: `${BLACK_FRIDAY_YEAR}-11-23`,
        END: `${BLACK_FRIDAY_YEAR}-11-26`
    },
    INTERVAL: 10 * 60 * 1000
};
export const MIN_PAYPAL_AMOUNT = 500;
export const MAX_PAYPAL_AMOUNT = 99999900;
export const NEWS = {
    ANNOUNCEMENTS: 1,
    FEATURES: 2,
    NEWSLETTER: 4,
    BETA: 8
};

export const CONTACT_EMAILS_LIMIT = 1000;
export const CONTACTS_LIMIT = 1000;
export const EXPORT_CONTACTS_LIMIT = 50; // Maximum page size for export is 50 from API
export const CONTACTS_REQUESTS_PER_SECOND = 10;
export const ALL_MEMBERS_ID = 'ALL';

export const LABEL_COLORS = [
    '#7272a7',
    '#8989ac',

    '#cf5858',
    '#cf7e7e',

    '#c26cc7',
    '#c793ca',

    '#7569d1',
    '#9b94d1',

    '#69a9d1',
    '#a8c4d5',

    '#5ec7b7',
    '#97c9c1',

    '#72bb75',
    '#9db99f',

    '#c3d261',
    '#c6cd97',

    '#e6c04c',
    '#e7d292',

    '#e6984c',
    '#dfb286'
];
<commit_msg>AddLayouts react-components companion (#8)<commit_after>export const MAIN_USER_KEY = 'USER_KEYS';
export const SECURE_SESSION_STORAGE_KEY = 'SECURE';
export const MAILBOX_PASSWORD_KEY = 'proton:mailbox_pwd';
export const UID_KEY = 'proton:oauth:UID';
export const INTERVAL_EVENT_TIMER = 30 * 1000;
export const EVENT_ACTIONS = {
    DELETE: 0,
    CREATE: 1,
    UPDATE: 2,
    UPDATE_DRAFT: 2,
    UPDATE_FLAGS: 3
};
export const USER_ROLES = {
    FREE_ROLE: 0,
    MEMBER_ROLE: 1,
    ADMIN_ROLE: 2
};
export const ELEMENTS_PER_PAGE = 10;
export const INVOICE_OWNER = {
    USER: 0,
    ORGANIZATION: 1
};
export const DEFAULT_CURRENCY = 'EUR';
export const CURRENCIES = ['EUR', 'USD', 'CHF'];
export const MIN_BITCOIN_AMOUNT = 500;
export const DEFAULT_DONATION_AMOUNT = 2500;
export const BTC_DONATION_ADDRESS = '1Q1nhq1NbxPYAbw1BppwKbCqg58ZqMb9A8';
export const AUTH_LOG_EVENTS = {
    LOGIN_FAILURE_PASSWORD: 0,
    LOGIN_SUCCESS: 1,
    LOGOUT: 2,
    LOGIN_FAILURE_2FA: 3,
    LOGIN_SUCCESS_AWAIT_2FA: 4
};
export const INVOICE_TYPE = {
    OTHER: 0,
    SUBSCRIPTION: 1,
    CANCELLATION: 2,
    CREDIT: 3,
    DONATION: 4
};
export const INVOICE_STATE = {
    UNPAID: 0,
    PAID: 1,
    VOID: 2,
    BILLED: 3
};

export const BASE_SIZE = 1024;
export const GIGA = BASE_SIZE ** 3;

export const LOGS_STATE = {
    DISABLE: 0,
    BASIC: 1,
    ADVANCED: 2
};

export const MEMBER_TYPE = {
    MEMBER: 0,
    SUB_MEMBER: 1
};

export const DOMAIN_STATE = {
    DOMAIN_STATE_DEFAULT: 0, // Domain's State before verify or after deactivation
    DOMAIN_STATE_ACTIVE: 1, // active once verified
    DOMAIN_STATE_WARN: 2 // detected backward DNS change after ACTIVE
};

export const VERIFY_STATE = {
    VERIFY_STATE_DEFAULT: 0, // 0 is default, no good
    VERIFY_STATE_EXIST: 1, // 1 is has code but doesn't match DB's, no good
    VERIFY_STATE_GOOD: 2 // 2 is has code and matches DB's, good!
};

export const MX_STATE = {
    MX_STATE_DEFAULT: 0, // 0 is default, no good
    MX_STATE_NO_US: 1, // 1 is set but does not have us
    MX_STATE_INC_US: 2, // 2 is includes our MX but priority no good
    MX_STATE_GOOD: 3 // 3 is includes our MX and we are highest and pri is legit, good!
};

export const SPF_STATE = {
    SPF_STATE_DEFAULT: 0, // 0 is default, no spf record
    SPF_STATE_ONE: 1, // 1 is has spf record but not us
    SPF_STATE_MULT: 2, // 2 is has multiple spf records, no good
    SPF_STATE_GOOD: 3 // 3 is has spf record and includes us, good!
};

export const DKIM_STATE = {
    DKIM_STATE_DEFAULT: 0, // 0 is default, no dkim record
    DKIM_STATE_ONE: 1, // 1 is found entries but format wrong
    DKIM_STATE_MULT: 2, // 2 is multiple dkim records, no good
    DKIM_STATE_CHECK: 3, // 3 is proper entry, but did not check or did not match DB's public key
    DKIM_STATE_GOOD: 4, // 4 is proper entry and matches DB's public key, good!
    DKIM_STATE_OFF: 5 // 5 is User wants to stop signing with dkim
};

export const DMARC_STATE = {
    DMARC_STATE_DEFAULT: 0, // 0 is default, no dmarc record
    DMARC_STATE_ONE: 1, // 1 is found entries but format wrong
    DMARC_STATE_MULT: 2, // 2 is multiple dmarc records, no good
    DMARC_STATE_GOOD: 3 // 3 is good!
};

export const ADDRESS_STATUS = {
    STATUS_DISABLED: 0,
    STATUS_ENABLED: 1
};

export const ADDRESS_TYPE = {
    TYPE_ORIGINAL: 1,
    TYPE_ALIAS: 2,
    TYPE_CUSTOM_DOMAIN: 3,
    TYPE_PREMIUM: 4
};

export const RECEIVE_ADDRESS = {
    RECEIVE_YES: 1,
    RECEIVE_NO: 0
};

export const SEND_ADDRESS = {
    SEND_YES: 1,
    SEND_NO: 0
};

export const MEMBER_PRIVATE = {
    READABLE: 0,
    UNREADABLE: 1
};

export const MEMBER_ROLE = {
    ORGANIZATION_NONE: 0,
    ORGANIZATION_MEMBER: 1,
    ORGANIZATION_OWNER: 2
};

export const PACKAGE_TYPE = {
    SEND_PM: 1,
    SEND_EO: 2,
    SEND_CLEAR: 4,
    SEND_PGP_INLINE: 8,
    SEND_PGP_MIME: 16
};

export const SHOW_IMAGES = {
    REMOTE: 1,
    EMBEDDED: 2
};

export const COMPOSER_MODE = {
    POPUP: 0,
    MAXIMIZED: 1
};

export const VIEW_LAYOUT = {
    COLUMN: 0,
    ROW: 1
};

export const VIEW_MODE = {
    GROUP: 0,
    SINGLE: 1
};

export const DEFAULT_CYCLE = 12;

export const CYCLE = {
    MONTHLY: 1,
    YEARLY: 12,
    TWO_YEARS: 24
};

export const BUNDLE_COUPON_CODE = 'BUNDLE';
const BLACK_FRIDAY_YEAR = 2018;
export const BLACK_FRIDAY = {
    YEAR: BLACK_FRIDAY_YEAR,
    COUPON_CODE: 'TWO4ONE2018',
    CYCLE: CYCLE.TWO_YEARS,
    BETWEEN: {
        START: `${BLACK_FRIDAY_YEAR}-11-23`,
        END: `${BLACK_FRIDAY_YEAR}-11-26`
    },
    INTERVAL: 10 * 60 * 1000
};
export const MIN_PAYPAL_AMOUNT = 500;
export const MAX_PAYPAL_AMOUNT = 99999900;
export const NEWS = {
    ANNOUNCEMENTS: 1,
    FEATURES: 2,
    NEWSLETTER: 4,
    BETA: 8
};

export const CONTACT_EMAILS_LIMIT = 1000;
export const CONTACTS_LIMIT = 1000;
export const EXPORT_CONTACTS_LIMIT = 50; // Maximum page size for export is 50 from API
export const CONTACTS_REQUESTS_PER_SECOND = 10;
export const ALL_MEMBERS_ID = 'ALL';

export const LABEL_COLORS = [
    '#7272a7',
    '#8989ac',

    '#cf5858',
    '#cf7e7e',

    '#c26cc7',
    '#c793ca',

    '#7569d1',
    '#9b94d1',

    '#69a9d1',
    '#a8c4d5',

    '#5ec7b7',
    '#97c9c1',

    '#72bb75',
    '#9db99f',

    '#c3d261',
    '#c6cd97',

    '#e6c04c',
    '#e7d292',

    '#e6984c',
    '#dfb286'
];
<|endoftext|>


<commit_before>(function(document, housewarming){

    var playground = document.getElementById('playground');
    playground.width = document.body.clientWidth;
    playground.height = document.body.clientHeight;

    var options = {
	distance: 20,
	couple: {
	    x: 3*playground.width/4, y: playground.height/2,
	    src: 'image/robin-marloes-small.jpg'
	},
	background: { color: 'rgba(0,0,0,0.1)'},
	house: {
	    x: playground.width/4, y: playground.height/2,
	    size: 40,
	    color: 'green',
	    featuresColor: 'brown'
	}
    };
    var game = new housewarming.Game(options);
    new housewarming.View(game, playground, options);

    function mousemoveHandler(event){
	game.couple.placeAt(event.x, event.y);
    }
    game.on('finished', function(){
	document.body.removeEventListener('mousemove', mousemoveHandler);
	var p = document.createElement('p');
	p.innerHTML = 'Congratulations';
	p.setAttribute('class', 'winning');
	document.body.appendChild(p);
    });

    var go = document.getElementById('go');
    go.addEventListener('click', function(){
	document.body.removeChild(go);
	document.body.addEventListener('mousemove', mousemoveHandler);
    });

})(document, housewarming);
<commit_msg>Make it possible to switch targets<commit_after>(function(document, housewarming){

    var playground = document.getElementById('playground');
    playground.width = document.body.clientWidth;
    playground.height = document.body.clientHeight;

    var options = {
	distance: 20,
	couple: {
	    x: 3*playground.width/4, y: playground.height/2,
	    src: 'image/robin-marloes-small.jpg'
	},
	background: { color: 'rgba(0,0,0,0.1)'},
	house: {
	    x: playground.width/4, y: playground.height/2,
	    size: 40,
	    color: 'green',
	    featuresColor: 'brown'
	}
    };
    var game = new housewarming.Game(options);
    new housewarming.View(game, playground, options);

    var target = 'couple';
    function mousemoveHandler(event){
	game[target].placeAt(event.x, event.y);
    }
    game.on('finished', function(){
	document.body.removeEventListener('mousemove', mousemoveHandler);
	var p = document.createElement('p');
	p.innerHTML = 'Congratulations';
	p.setAttribute('class', 'winning');
	document.body.appendChild(p);
    });

    var go = document.getElementById('go');
    go.addEventListener('click', function(){
	document.body.removeChild(go);
	document.body.addEventListener('mousemove', mousemoveHandler);
    });

})(document, housewarming);
<|endoftext|>


<commit_before>define(
    [
        'jquery',
        'underscore',
        'backbone',
        'module',
        'views/Base',
        'models/shared/ClassicURL',
        'app/views/tours/Tours',
        'app/views/tours/image/Editor',
        'app/views/tours/interactive/Editor',
        'app/views/tours/Iframe',
        'views/shared/tour/ImageTour/Master',
        'splunk.util',
        'uri/route',
        'app/contrib/dom.outline'
    ],
    function(
        $,
        _,
        backbone,
        module,
        BaseView,
        ClassicURL,
        ToursView,
        ImageTourEditor,
        InteractiveTourEditor,
        IFrame,
        ImageTour,
        splunkUtils,
        route,
        tourscss,
        outline
    ){
        return BaseView.extend({
            moduleId: module.id,
            initialize: function() {
                BaseView.prototype.initialize.apply(this, arguments);

                this.model.classicurl = new ClassicURL();
                this.model.classicurl.fetch();

                var queryProps = splunkUtils.queryStringToProp(window.location.search);
                if (queryProps && queryProps.t) {
                    this.editTour = this.collection.tours.getTourModel(queryProps.t);
                    this.model.tour = this.editTour;
                    if (!this.model.tour) {
                        this.model.classicurl.unset('t');
                        this.model.classicurl.save({}, {replaceState: true});
                    }
                }

                this.activate({deep: true});
            },

            startListening: function() {
                this.listenTo(this.collection.tours, 'new', function(tour) {
                    this.model.tour = tour;
                    this.renderEditPage();
                });
                this.listenTo(this.collection.tours, 'update', function(tour) {
                    this.collection.tours.fetch({
                        data: {
                            app: 'tour_makr',
                            owner: this.model.application.get('owner'),
                            count: -1
                        }
                    });
                });
                this.listenTo(this.collection.tours, 'new-interactive', function(tour) {
                    this.model.tour = tour;
                    this.editInteractiveTour();
                });
            },

            editInteractiveTour: function(tourModel) {
                var tourPage = this.model.tour.entry.content.get('tourPage') || 'search';

                this.children.interactiveEditor = new InteractiveTourEditor({
                    model: {
                        application: this.model.application,
                        tour: this.model.tour
                    },
                    collection: {
                        tours: this.collection.tours
                    }
                });

                this.listenTo(this.children.interactiveEditor, 'int-menu-closed', function() {
                    this.refreshTours();
                    this.killIframe();
                });

                $('body').append(this.children.interactiveEditor.render().el);
                setTimeout(function() {
                    // strictly for aestetics sliding the menus simultaneously
                    $('body').addClass('open-right');
                    $(this.children.interactiveEditor.el).addClass('open');
                    $('header').addClass('hidden');
                }.bind(this), 50);

                this.activateIframe();
            },

            runInteractiveTour: function(tourName) {
                var app = this.model.tour.entry.content.get('other-app') || 'search',
                    tourPage = this.model.tour.getTourPage() || 'search',
                    data = splunkUtils.queryStringToProp(this.model.tour.getTourURLData() || '');

                data.tour = tourName;
                var tourUrl = route.page(
                    this.model.application.get('root'),
                    this.model.application.get('locale'),
                    app,
                    tourPage,
                    { data: data }
                );
                window.location.href = tourUrl;
            },

            runTour: function(tourName) {
                if (this.model.tour) {
                    this.children.tour = new ImageTour({
                        model: {
                            tour: this.model.tour,
                            application: this.model.application
                        },
                        onHiddenRemove: true,
                        backdrop: 'static'
                    });
                    $('body').append('

');
                    $('.image-tour').append(this.children.tour.render().el);
                    this.children.tour.show();
                }
            },

            renderTours: function() {
                this.children.toursView = new ToursView({
                    model: {
                        application: this.model.application
                    },
                    collection: {
                        tours: this.collection.tours,
                        appLocals: this.collection.appLocals
                    }
                });

                this.listenTo(this.children.toursView, 'edit', function(tourName) {
                    this.model.tour = this.collection.tours.getTourModel(tourName);
                    this.renderEditPage();
                });
                this.listenTo(this.children.toursView, 'edit-interactive', function(tourName) {
                    this.model.tour = this.collection.tours.getTourModel(tourName);
                    this.editInteractiveTour();
                });
                this.listenTo(this.children.toursView, 'run', function(tourName) {
                    this.runTour(tourName);
                });
                this.listenTo(this.children.toursView, 'run-interactive', function(tourName) {
                    this.model.tour = this.collection.tours.getTourModel(tourName);
                    this.runInteractiveTour(tourName);
                });

                this.$('.tours-container').html(this.children.toursView.render().el);
            },

            renderEditPage: function() {
                var tourName = this.model.tour.entry.get('name');
                this.model.classicurl.set({'t': tourName});
                this.model.classicurl.save({}, {replaceState: true});

                this.children.tourEditPage = new ImageTourEditor({
                    model: {
                        application: this.model.application,
                        tour: this.model.tour
                    },
                    collection: {
                        tours: this.collection.tours,
                        appLocals: this.collection.appLocals
                    }
                });

                this.$el.html(this.template);
                this.$('.tours-container').append(this.children.tourEditPage.render().el);

                this.listenTo(this.children.tourEditPage, "back", function() {
                    this.model.classicurl.unset('t');
                    this.model.classicurl.save({}, {replaceState: true});
                    this.editTour = null;
                    this.refreshTours();
                });
            },

            refreshTours: function() {
                this.collection.tours.fetch({
                    data: {
                        app: 'tour_makr',
                        owner: this.model.application.get('owner'),
                        count: -1
                    },
                    success: function(collection, response) {
                        this.renderTours();
                        this.children.toursView.delegateEvents();
                    }.bind(this)
                });
            },

            activateIframe: function() {
                var qsObj = {},
                    tourApp = this.model.tour.entry.content.get('other-app') || 'search',
                    tourPage = this.model.tour.getTourPage() || 'search',
                    urlData = this.model.tour.getTourURLData(),
                    qs, iFrameURL;

                    if (urlData) {
                        var decodedQS = decodeURIComponent(urlData);
                        qs = decodedQS.substring(decodedQS.indexOf('?'), decodedQS.length);
                        qsObj = splunkUtils.queryStringToProp(qs);
                    }

                iFrameURL = splunkUtils.make_full_url('app/' + tourApp + '/' + tourPage, qsObj);

                this.children.iframe = new IFrame({
                    src: iFrameURL
                });

                this.$('.iframe-container').fadeIn();

                setTimeout(function() {
                    this.$('.iframe-container').append(this.children.iframe.render().el);
                    setTimeout(function() {
                        var $iframe = $('iframe');
                        $iframe.ready(function() {
                            var domoutline = eval(DomOutline),
                                domoutlineScript = 'var DomOutline = ' + domoutline;

                            var myIframe = document.getElementById('iframefoo')
                            var script = myIframe.contentWindow.document.createElement("script");
                            script.type = "text/javascript";
                            script.text = domoutlineScript;
                            myIframe.contentWindow.document.body.appendChild(script);
                        });
                    }, 500);
                }.bind(this), 500);
            },

            editURL: function() {
                console.log('EDIT URL')
            },

            killIframe: function() {
                this.$('.iframe-container').fadeOut(function() {
                    this.$('.iframe-container').empty();
                }.bind(this));
            },

            render: function() {
                this.$el.html(this.template);
                if (this.editTour) {
                    this.renderEditPage();
                } else {
                    this.renderTours();
                }
                return this;
            },

            template: '\

\

\
            '
        });
    }
);
<commit_msg>Fixing issue were tour didn't run the first time<commit_after>define(
    [
        'jquery',
        'underscore',
        'backbone',
        'module',
        'views/Base',
        'models/shared/ClassicURL',
        'app/views/tours/Tours',
        'app/views/tours/image/Editor',
        'app/views/tours/interactive/Editor',
        'app/views/tours/Iframe',
        'views/shared/tour/ImageTour/Master',
        'splunk.util',
        'uri/route',
        'app/contrib/dom.outline'
    ],
    function(
        $,
        _,
        backbone,
        module,
        BaseView,
        ClassicURL,
        ToursView,
        ImageTourEditor,
        InteractiveTourEditor,
        IFrame,
        ImageTour,
        splunkUtils,
        route,
        tourscss,
        outline
    ){
        return BaseView.extend({
            moduleId: module.id,
            initialize: function() {
                BaseView.prototype.initialize.apply(this, arguments);

                this.model.classicurl = new ClassicURL();
                this.model.classicurl.fetch();

                var queryProps = splunkUtils.queryStringToProp(window.location.search);
                if (queryProps && queryProps.t) {
                    this.editTour = this.collection.tours.getTourModel(queryProps.t);
                    this.model.tour = this.editTour;
                    if (!this.model.tour) {
                        this.model.classicurl.unset('t');
                        this.model.classicurl.save({}, {replaceState: true});
                    }
                }

                this.activate({deep: true});
            },

            startListening: function() {
                this.listenTo(this.collection.tours, 'new', function(tour) {
                    this.model.tour = tour;
                    this.renderEditPage();
                });
                this.listenTo(this.collection.tours, 'update', function(tour) {
                    this.collection.tours.fetch({
                        data: {
                            app: 'tour_makr',
                            owner: this.model.application.get('owner'),
                            count: -1
                        }
                    });
                });
                this.listenTo(this.collection.tours, 'new-interactive', function(tour) {
                    this.model.tour = tour;
                    this.editInteractiveTour();
                });
            },

            editInteractiveTour: function(tourModel) {
                var tourPage = this.model.tour.entry.content.get('tourPage') || 'search';

                this.children.interactiveEditor = new InteractiveTourEditor({
                    model: {
                        application: this.model.application,
                        tour: this.model.tour
                    },
                    collection: {
                        tours: this.collection.tours
                    }
                });

                this.listenTo(this.children.interactiveEditor, 'int-menu-closed', function() {
                    this.refreshTours();
                    this.killIframe();
                });

                $('body').append(this.children.interactiveEditor.render().el);
                setTimeout(function() {
                    // strictly for aestetics sliding the menus simultaneously
                    $('body').addClass('open-right');
                    $(this.children.interactiveEditor.el).addClass('open');
                    $('header').addClass('hidden');
                }.bind(this), 50);

                this.activateIframe();
            },

            runInteractiveTour: function(tourName) {
                var app = this.model.tour.entry.content.get('other-app') || 'search',
                    tourPage = this.model.tour.getTourPage() || 'search',
                    data = splunkUtils.queryStringToProp(this.model.tour.getTourURLData() || '');

                data.tour = tourName;
                var tourUrl = route.page(
                    this.model.application.get('root'),
                    this.model.application.get('locale'),
                    app,
                    tourPage,
                    { data: data }
                );
                window.location.href = tourUrl;
            },

            runTour: function(tourName) {
                if (this.model.tour) {
                    this.children.tour = new ImageTour({
                        model: {
                            tour: this.model.tour,
                            application: this.model.application
                        },
                        onHiddenRemove: true,
                        backdrop: 'static'
                    });
                    $('body').append('

');
                    $('.image-tour').append(this.children.tour.render().el);
                    this.children.tour.show();
                }
            },

            renderTours: function() {
                this.children.toursView = new ToursView({
                    model: {
                        application: this.model.application
                    },
                    collection: {
                        tours: this.collection.tours,
                        appLocals: this.collection.appLocals
                    }
                });

                this.listenTo(this.children.toursView, 'edit', function(tourName) {
                    this.model.tour = this.collection.tours.getTourModel(tourName);
                    this.renderEditPage();
                });
                this.listenTo(this.children.toursView, 'edit-interactive', function(tourName) {
                    this.model.tour = this.collection.tours.getTourModel(tourName);
                    this.editInteractiveTour();
                });
                this.listenTo(this.children.toursView, 'run', function(tourName) {
                    this.model.tour = this.collection.tours.getTourModel(tourName);
                    this.runTour(tourName);
                });
                this.listenTo(this.children.toursView, 'run-interactive', function(tourName) {
                    this.model.tour = this.collection.tours.getTourModel(tourName);
                    this.runInteractiveTour(tourName);
                });

                this.$('.tours-container').html(this.children.toursView.render().el);
            },

            renderEditPage: function() {
                var tourName = this.model.tour.entry.get('name');
                this.model.classicurl.set({'t': tourName});
                this.model.classicurl.save({}, {replaceState: true});

                this.children.tourEditPage = new ImageTourEditor({
                    model: {
                        application: this.model.application,
                        tour: this.model.tour
                    },
                    collection: {
                        tours: this.collection.tours,
                        appLocals: this.collection.appLocals
                    }
                });

                this.$el.html(this.template);
                this.$('.tours-container').append(this.children.tourEditPage.render().el);

                this.listenTo(this.children.tourEditPage, "back", function() {
                    this.model.classicurl.unset('t');
                    this.model.classicurl.save({}, {replaceState: true});
                    this.editTour = null;
                    this.refreshTours();
                });
            },

            refreshTours: function() {
                this.collection.tours.fetch({
                    data: {
                        app: 'tour_makr',
                        owner: this.model.application.get('owner'),
                        count: -1
                    },
                    success: function(collection, response) {
                        this.renderTours();
                        this.children.toursView.delegateEvents();
                    }.bind(this)
                });
            },

            activateIframe: function() {
                var qsObj = {},
                    tourApp = this.model.tour.entry.content.get('other-app') || 'search',
                    tourPage = this.model.tour.getTourPage() || 'search',
                    urlData = this.model.tour.getTourURLData(),
                    qs, iFrameURL;

                    if (urlData) {
                        var decodedQS = decodeURIComponent(urlData);
                        qs = decodedQS.substring(decodedQS.indexOf('?'), decodedQS.length);
                        qsObj = splunkUtils.queryStringToProp(qs);
                    }

                iFrameURL = splunkUtils.make_full_url('app/' + tourApp + '/' + tourPage, qsObj);

                this.children.iframe = new IFrame({
                    src: iFrameURL
                });

                this.$('.iframe-container').fadeIn();

                setTimeout(function() {
                    this.$('.iframe-container').append(this.children.iframe.render().el);
                    setTimeout(function() {
                        var $iframe = $('iframe');
                        $iframe.ready(function() {
                            var domoutline = eval(DomOutline),
                                domoutlineScript = 'var DomOutline = ' + domoutline;

                            var myIframe = document.getElementById('iframefoo')
                            var script = myIframe.contentWindow.document.createElement("script");
                            script.type = "text/javascript";
                            script.text = domoutlineScript;
                            myIframe.contentWindow.document.body.appendChild(script);
                        });
                    }, 500);
                }.bind(this), 500);
            },

            editURL: function() {
                console.log('EDIT URL')
            },

            killIframe: function() {
                this.$('.iframe-container').fadeOut(function() {
                    this.$('.iframe-container').empty();
                }.bind(this));
            },

            render: function() {
                this.$el.html(this.template);
                if (this.editTour) {
                    this.renderEditPage();
                } else {
                    this.renderTours();
                }
                return this;
            },

            template: '\

\

\
            '
        });
    }
);
<|endoftext|>


<commit_before>// ==UserScript==
// @name         Anti Pop-under
// @namespace    https://openuserjs.org/scripts/DaTechNinja/Anti_Pop-under
// @description  This user script attempts to disable pop-under scripts from working when clicking elements on a site
// @author       DaTechNinja
// @version      1.0.4
// @encoding     utf-8
// @license      https://raw.githubusercontent.com/DaTechNinja/anti-pop-under/master/LICENSE
// @icon         https://raw.githubusercontent.com/DaTechNinja/anti-pop-under/master/favicon.ico
// @homepage     https://github.com/DaTechNinja/anti-pop-under
// @supportURL   https://github.com/DaTechNinja/anti-pop-under/issues
// @updateURL    https://raw.githubusercontent.com/DaTechNinja/anti-pop-under/anti-pop-under.user.js
// @downloadURL  https://raw.githubusercontent.com/DaTechNinja/anti-pop-under/anti-pop-under.user.js
// @match        http*://*/*
// @grant        none
// @require      https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js
// ==/UserScript==

/*
   DISCLAIMER: The author of this code is not responsible for any potential damages caused by its use.
*/

(function ($, undefined) {
  $(function () {
     'use strict';

    $(document).ready(function() {
        var antiPopUnderOptions = {
            'checkIndefinitely': false,      // Whether to check for pop-under script indefinitely or not, default: false
            'maxChecksBeforeStopping': 300,  // Maximum amount of times to check for pop-under script, default: 300
            'checkInterval': 1000            // Interval in milliseconds to check for pop-under script, default: 1000
        };

        var popUnderAlreadyKilled = false;
        var checkCountForPopUnder = 0;

        function killPopUnder() {
            if (!antiPopUnderOptions.checkIndefinitely) {
                if (++checkCountForPopUnder == antiPopUnderOptions.maxChecksBeforeStopping) {
                    console.log('Anti Pop-under: Reached max check count of ' + antiPopUnderOptions.maxChecksBeforeStopping + ', stopping...');
                    return;
                }
            }

            if (typeof window._wm !== 'undefined' && typeof window._wm === 'object') {
                if (typeof window._wm.format.popunder !== 'undefined' && typeof window._wm.format.popunder === 'object') {
                    window._wm = 'undefined';
                    popUnderAlreadyKilled = true;
                    console.log('Anti Pop-under: Found and killed pop-under script!');
                }
            }

            if (!popUnderAlreadyKilled || antiPopUnderOptions.checkIndefinitely) {
                setTimeout(killPopUnder, antiPopUnderOptions.checkInterval);
            }
        }

        killPopUnder();
    });
  });
})(window.jQuery.noConflict(true));
<commit_msg>Changing default options to reduce browser lag<commit_after>// ==UserScript==
// @name         Anti Pop-under
// @namespace    https://openuserjs.org/scripts/DaTechNinja/Anti_Pop-under
// @description  This user script attempts to disable pop-under scripts from working when clicking elements on a site
// @author       DaTechNinja
// @version      1.0.5
// @encoding     utf-8
// @license      https://raw.githubusercontent.com/DaTechNinja/anti-pop-under/master/LICENSE
// @icon         https://raw.githubusercontent.com/DaTechNinja/anti-pop-under/master/favicon.ico
// @homepage     https://github.com/DaTechNinja/anti-pop-under
// @supportURL   https://github.com/DaTechNinja/anti-pop-under/issues
// @updateURL    https://raw.githubusercontent.com/DaTechNinja/anti-pop-under/anti-pop-under.user.js
// @downloadURL  https://raw.githubusercontent.com/DaTechNinja/anti-pop-under/anti-pop-under.user.js
// @match        http*://*/*
// @grant        none
// @require      https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js
// ==/UserScript==

/*
   DISCLAIMER: The author of this code is not responsible for any potential damages caused by its use.
*/

(function ($, undefined) {
  $(function () {
     'use strict';

    $(document).ready(function() {
        var antiPopUnderOptions = {
            'checkIndefinitely': false,      // Whether to check for pop-under script indefinitely or not, default: false
            'maxChecksBeforeStopping': 10,  // Maximum amount of times to check for pop-under script, default: 10
            'checkInterval': 1500            // Interval in milliseconds to check for pop-under script, default: 1500
        };

        var popUnderAlreadyKilled = false;
        var checkCountForPopUnder = 0;

        function killPopUnder() {
            if (!antiPopUnderOptions.checkIndefinitely) {
                if (++checkCountForPopUnder == antiPopUnderOptions.maxChecksBeforeStopping) {
                    console.log('Anti Pop-under: Reached max check count of ' + antiPopUnderOptions.maxChecksBeforeStopping + ', stopping...');
                    return;
                }
            }

            if (typeof window._wm !== 'undefined' && typeof window._wm === 'object') {
                if (typeof window._wm.format.popunder !== 'undefined' && typeof window._wm.format.popunder === 'object') {
                    window._wm = 'undefined';
                    popUnderAlreadyKilled = true;
                    console.log('Anti Pop-under: Found and killed pop-under script!');
                }
            }

            if (!popUnderAlreadyKilled || antiPopUnderOptions.checkIndefinitely) {
                setTimeout(killPopUnder, antiPopUnderOptions.checkInterval);
            }
        }

        killPopUnder();
    });
  });
})(window.jQuery.noConflict(true));
<|endoftext|>


<commit_before>'use strict';

// var debug = require('debug')('MWS:amazon-mws');
AmazonMws.DEFAULT_HOST = 'mws.amazonservices.com';
AmazonMws.DEFAULT_PORT = '443';
AmazonMws.DEFAULT_BASE_PATH = '/';
AmazonMws.DEFAULT_RESPONSE_FORMAT = 'JSON';
AmazonMws.DEFAULT_API_VERSION = null;

// Use node's default timeout:
AmazonMws.DEFAULT_TIMEOUT = require('http').createServer().timeout;

AmazonMws.PACKAGE_VERSION = require('../package.json').version;

AmazonMws.USER_AGENT = {
    bindings_version: AmazonMws.PACKAGE_VERSION,
    lang: 'node',
    lang_version: process.version,
    platform: process.platform,
    publisher: 'amazon-mws',
    uname: null
};

AmazonMws.USER_AGENT_SERIALIZED = null;

var exec = require('child_process').exec;

var resources = {
    feeds: require('./resources/Feeds'),
    finances: require('./resources/Finances'),
    fulfillmentInboundShipment: require('./resources/FulfillmentInboundShipment'),
    fulfillmentOutboundShipment: require('./resources/FulfillmentOutboundShipment'),
    fulfillmentInventory: require('./resources/FulfillmentInventory'),
    merchantFulfillment: require('./resources/MerchantFulfillment'),
    products: require('./resources/Products'),
    orders: require('./resources/Orders'),
    recommendations: require('./resources/Recommendations'),
    reports: require('./resources/Reports'),
    subscriptions: require('./resources/Subscriptions'),
    sellers: require('./resources/Sellers')
};

AmazonMws.AmazonMwsResource = require('./AmazonMwsResource');
AmazonMws.resources = resources;

function AmazonMws(accessKey, accessSecret, version) {
    if (!(this instanceof AmazonMws)) {
        return new AmazonMws(accessKey, accessSecret, version);
    }

    this._api = {
        auth: null,
        host: AmazonMws.DEFAULT_HOST,
        port: AmazonMws.DEFAULT_PORT,
        basePath: AmazonMws.DEFAULT_BASE_PATH,
        version: AmazonMws.DEFAULT_API_VERSION,
        timeout: AmazonMws.DEFAULT_TIMEOUT,
        agent: null,
        dev: false
    };

    if (!version) {
        version = '';
    }
    if (!accessKey) {
        accessKey = '';
    }
    if (!accessSecret) {
        accessSecret = '';
    }
    this._prepResources();
    this.setApiKey(accessKey, accessSecret);
    this.setApiVersion(version);
    // this.setResponseFormat(AmazonMws.DEFAULT_RESPONSE_FORMAT);
}

AmazonMws.prototype = {

    setHost: function (host, port, protocol) {
        this._setApiField('host', host);
        if (port) {
            this.setPort(port);
        }
        if (protocol) {
            this.setProtocol(protocol);
        }
    },

    setProtocol: function (protocol) {
        this._setApiField('protocol', protocol.toLowerCase());
    },

    setPort: function (port) {
        this._setApiField('port', port);
    },

    setResponseFormat: function (format) {
        this._setApiField('format', format);
    },

    setContentType: function (contentType) {
        this._setApiField('contentType', contentType);
    },

    setApiVersion: function (version) {
        if (version) {
            this._setApiField('version', version);
        }
    },

    setApiKey: function (accessKey, accessSecret) {
        if (accessKey) {
            this._setApiField('key', accessKey);
        }
        if (accessSecret) {
            this._setApiField('secret', accessSecret);
        }
    },

    setTimeout: function (timeout) {
        this._setApiField('timeout', timeout === null ? AmazonMws.DEFAULT_TIMEOUT : timeout);
    },

    setHttpAgent: function (agent) {
        this._setApiField('agent', agent);
    },

    _setApiField: function (key, value) {
        this._api[key] = value;
    },

    getApiField: function (key) {
        return this._api[key];
    },

    getResponseFormat: function (key) {
        return this._api[key];
    },

    getConstant: function (c) {
        return AmazonMws[c];
    },

    _prepResources: function () {
        for (var name in resources) {
            this[name[0].toLowerCase() + name.substring(1)] = new resources[name](this);
        }
    },

    // Gets a JSON version of a User-Agent and uses a cached version for a slight
    // speed advantage.
    getClientUserAgent: function (cb) {
        if (AmazonMws.USER_AGENT_SERIALIZED) {
            return cb(AmazonMws.USER_AGENT_SERIALIZED);
        }
        this.getClientUserAgentSeeded(AmazonMws.USER_AGENT, function (cua) {
            AmazonMws.USER_AGENT_SERIALIZED = cua;
            cb(AmazonMws.USER_AGENT_SERIALIZED);
        });
    },

    // Gets a JSON version of a User-Agent by encoding a seeded object and
    // fetching a uname from the system.
    getClientUserAgentSeeded: function (seed, cb) {
        exec('uname -a', function (err, uname) {
            var userAgent = {};
            for (var field in seed) {
                userAgent[field] = encodeURIComponent(seed[field]);
            }

            // URI-encode in case there are unusual characters in the system's uname.
            userAgent.uname = encodeURIComponent(uname) || 'UNKNOWN';

            cb(JSON.stringify(userAgent));
        });
    }
};

module.exports = AmazonMws;

module.exports.AmazonMws = AmazonMws;
<commit_msg>- stop for loop from reading properties in prototype chain<commit_after>'use strict';

// var debug = require('debug')('MWS:amazon-mws');
AmazonMws.DEFAULT_HOST = 'mws.amazonservices.com';
AmazonMws.DEFAULT_PORT = '443';
AmazonMws.DEFAULT_BASE_PATH = '/';
AmazonMws.DEFAULT_RESPONSE_FORMAT = 'JSON';
AmazonMws.DEFAULT_API_VERSION = null;

// Use node's default timeout:
AmazonMws.DEFAULT_TIMEOUT = require('http').createServer().timeout;

AmazonMws.PACKAGE_VERSION = require('../package.json').version;

AmazonMws.USER_AGENT = {
    bindings_version: AmazonMws.PACKAGE_VERSION,
    lang: 'node',
    lang_version: process.version,
    platform: process.platform,
    publisher: 'amazon-mws',
    uname: null
};

AmazonMws.USER_AGENT_SERIALIZED = null;

var exec = require('child_process').exec;

var resources = {
    feeds: require('./resources/Feeds'),
    finances: require('./resources/Finances'),
    fulfillmentInboundShipment: require('./resources/FulfillmentInboundShipment'),
    fulfillmentOutboundShipment: require('./resources/FulfillmentOutboundShipment'),
    fulfillmentInventory: require('./resources/FulfillmentInventory'),
    merchantFulfillment: require('./resources/MerchantFulfillment'),
    products: require('./resources/Products'),
    orders: require('./resources/Orders'),
    recommendations: require('./resources/Recommendations'),
    reports: require('./resources/Reports'),
    subscriptions: require('./resources/Subscriptions'),
    sellers: require('./resources/Sellers')
};

AmazonMws.AmazonMwsResource = require('./AmazonMwsResource');
AmazonMws.resources = resources;

function AmazonMws(accessKey, accessSecret, version) {
    if (!(this instanceof AmazonMws)) {
        return new AmazonMws(accessKey, accessSecret, version);
    }

    this._api = {
        auth: null,
        host: AmazonMws.DEFAULT_HOST,
        port: AmazonMws.DEFAULT_PORT,
        basePath: AmazonMws.DEFAULT_BASE_PATH,
        version: AmazonMws.DEFAULT_API_VERSION,
        timeout: AmazonMws.DEFAULT_TIMEOUT,
        agent: null,
        dev: false
    };

    if (!version) {
        version = '';
    }
    if (!accessKey) {
        accessKey = '';
    }
    if (!accessSecret) {
        accessSecret = '';
    }
    this._prepResources();
    this.setApiKey(accessKey, accessSecret);
    this.setApiVersion(version);
    // this.setResponseFormat(AmazonMws.DEFAULT_RESPONSE_FORMAT);
}

AmazonMws.prototype = {

    setHost: function (host, port, protocol) {
        this._setApiField('host', host);
        if (port) {
            this.setPort(port);
        }
        if (protocol) {
            this.setProtocol(protocol);
        }
    },

    setProtocol: function (protocol) {
        this._setApiField('protocol', protocol.toLowerCase());
    },

    setPort: function (port) {
        this._setApiField('port', port);
    },

    setResponseFormat: function (format) {
        this._setApiField('format', format);
    },

    setContentType: function (contentType) {
        this._setApiField('contentType', contentType);
    },

    setApiVersion: function (version) {
        if (version) {
            this._setApiField('version', version);
        }
    },

    setApiKey: function (accessKey, accessSecret) {
        if (accessKey) {
            this._setApiField('key', accessKey);
        }
        if (accessSecret) {
            this._setApiField('secret', accessSecret);
        }
    },

    setTimeout: function (timeout) {
        this._setApiField('timeout', timeout === null ? AmazonMws.DEFAULT_TIMEOUT : timeout);
    },

    setHttpAgent: function (agent) {
        this._setApiField('agent', agent);
    },

    _setApiField: function (key, value) {
        this._api[key] = value;
    },

    getApiField: function (key) {
        return this._api[key];
    },

    getResponseFormat: function (key) {
        return this._api[key];
    },

    getConstant: function (c) {
        return AmazonMws[c];
    },

    _prepResources: function () {
        for (var name in resources) {
            if (resources.hasOwnProperty(name)) {
                this[name[0].toLowerCase() + name.substring(1)] = new resources[name](this);
           }
        }
    },

    // Gets a JSON version of a User-Agent and uses a cached version for a slight
    // speed advantage.
    getClientUserAgent: function (cb) {
        if (AmazonMws.USER_AGENT_SERIALIZED) {
            return cb(AmazonMws.USER_AGENT_SERIALIZED);
        }
        this.getClientUserAgentSeeded(AmazonMws.USER_AGENT, function (cua) {
            AmazonMws.USER_AGENT_SERIALIZED = cua;
            cb(AmazonMws.USER_AGENT_SERIALIZED);
        });
    },

    // Gets a JSON version of a User-Agent by encoding a seeded object and
    // fetching a uname from the system.
    getClientUserAgentSeeded: function (seed, cb) {
        exec('uname -a', function (err, uname) {
            var userAgent = {};
            for (var field in seed) {
                userAgent[field] = encodeURIComponent(seed[field]);
            }

            // URI-encode in case there are unusual characters in the system's uname.
            userAgent.uname = encodeURIComponent(uname) || 'UNKNOWN';

            cb(JSON.stringify(userAgent));
        });
    }
};

module.exports = AmazonMws;

module.exports.AmazonMws = AmazonMws;
<|endoftext|>


<commit_before>pepdb.tableinit = pepdb.tableinit || {};
var asInitVals = new Array();

$(document).ready(function(){
  function baseDir(){
    var url = document.location.pathname.split('/')[1];
    if (url == "pepdb"){
      return '/'+url;
    }else{
      return '';
    }
  };

  var url = baseDir();

  $.getScript(url+'/script/initshowtable.js');
/* --------------DataTables configuration----------------  */
  /* initialize first table with searchable columns*/
  var oTable = $('#select_table').dataTable({
    "bPaginate": "true",
    "sPaginationType": "full_numbers",
    "bInfo": true,
    "bJQueryUI": true,
  });

  $('#select_table thead input').click( function(e){
    stopTableSorting(e);
  });

  $('#select_table thead input').keyup( function(e){
    stopTableSorting(e);
    oTable.fnFilter(this.value, $("#select_table thead input").index(this));
  });

  $('#select_table thead input').each( function (i) {
    asInitVals[i] = this.value;
  } );

  $('#select_table thead input').focus( function () {
    if ( this.className == "search_init" )
    {
      this.className = "text_filter";
      this.value = "";
    }
  } );

  $('#select_table thead input').blur( function (i) {
    if ( this.value == "" )
    {
      $(this).addClass("search_init");
      this.value = asInitVals[$("#select_table thead input").index(this)];
    }
  } );

  $('#select_table tr').hover(function(){
    $(this).toggleClass('highlight');
  });

  $('#select_table tr:has(td)').click(function(){
    var selectedID = $(this).find("td:first").html();
    var route = $('#reftype').val();
    var path = document.location.pathname;
    if (path == url+"/cluster-search"){
      if($('#clsearch').is(':visible')){
        $('#clsearch').toggle();
      }
      $.get(url+'/cluster-infos', {selCl:selectedID}, function(data){
        $('#clprop').html(data);
        $.getScript(url+'/script/initshowtable.js', function(){
          $('#clsearch').toggle();
        });
      });
    } else {
    if ($('#selecteddata').is(':visible')){
      $('#selecteddata').hide();
      $('#datainfo').hide();
    }
    $.get(url+'/info-tables', {infoElem:selectedID}, function(data){
      $('#selectedinfo').html(data);
    });
    $.get(url+'/show_sn_table', {ele_name:selectedID, ref: route}, function(data){
      $('#selecteddata').html(data);
      $.getScript(url+'/script/initshowtable.js', function(){
        $('#selecteddata').show();
      });
    });
    }
  });

});
<commit_msg>fixed js to correctly handle table rows when more pages are available<commit_after>pepdb.tableinit = pepdb.tableinit || {};
var asInitVals = new Array();

$(document).ready(function(){
  function baseDir(){
    var url = document.location.pathname.split('/')[1];
    if (url == "pepdb"){
      return '/'+url;
    }else{
      return '';
    }
  };

  var url = baseDir();

  $.getScript(url+'/script/initshowtable.js');
/* --------------DataTables configuration----------------  */
  /* initialize first table with searchable columns*/
  var oTable = $('#select_table').dataTable({
    "bPaginate": "true",
    "sPaginationType": "full_numbers",
    "bInfo": true,
    "bJQueryUI": true,
  });

  $('#select_table thead input').click( function(e){
    stopTableSorting(e);
  });

  $('#select_table thead input').keyup( function(e){
    stopTableSorting(e);
    oTable.fnFilter(this.value, $("#select_table thead input").index(this));
  });

  $('#select_table thead input').each( function (i) {
    asInitVals[i] = this.value;
  } );

  $('#select_table thead input').focus( function () {
    if ( this.className == "search_init" )
    {
      this.className = "text_filter";
      this.value = "";
    }
  } );

  $('#select_table thead input').blur( function (i) {
    if ( this.value == "" )
    {
      $(this).addClass("search_init");
      this.value = asInitVals[$("#select_table thead input").index(this)];
    }
  } );

  $('#select_table').on('mouseenter mouseleave', 'tr', function(){
    $(this).toggleClass('highlight');
  });

  $('#select_table').on('click', 'tr:has(td)', function(){
    var selectedID = $(this).find("td:first").html();
    var route = $('#reftype').val();
    var path = document.location.pathname;
    if (path == url+"/cluster-search"){
      if($('#clsearch').is(':visible')){
        $('#clsearch').toggle();
      }
      $.get(url+'/cluster-infos', {selCl:selectedID}, function(data){
        $('#clprop').html(data);
        $.getScript(url+'/script/initshowtable.js', function(){
          $('#clsearch').toggle();
        });
      });
    } else {
    if ($('#selecteddata').is(':visible')){
      $('#selecteddata').hide();
      $('#datainfo').hide();
    }
    $.get(url+'/info-tables', {infoElem:selectedID}, function(data){
      $('#selectedinfo').html(data);
    });
    $.get(url+'/show_sn_table', {ele_name:selectedID, ref: route}, function(data){
      $('#selecteddata').html(data);
      $.getScript(url+'/script/initshowtable.js', function(){
        $('#selecteddata').show();
      });
    });
    }
  });

});
<|endoftext|>


<commit_before>import React from "react";

export default class Profile extends React.Component {
  render() {
    return (

        Profile page

    );
  }
}
<commit_msg>Update `Profile` container<commit_after>import React, {Component, PropTypes} from 'react';
import {connect} from 'react-redux';

@connect(
  state => ({
    user: state.auth.user
  })
)
export default class Profile extends Component {
  static propTypes = {
    user: PropTypes.object
  };

  render() {
    return (

        Welcome, {this.props.user.username}!

    );
  }
}
<|endoftext|>