<commit_before>var websocket = {
    socket: null,
    retrySocketDelay: 1,
    buffer: new Map(),
    messageCounter: 0,
    hasConnected: false,
    reconnectAttempts: 0,
    open: function() {
        console.info("Trying to open websocket...");

        websocket.socket = new WebSocket(location.protocol.replace(/^http/, 'ws') + location.host + "/florence/websocket");
        websocket.reconnectAttempts++;

        websocket.socket.onopen = function() {
            console.info("Websocket has been opened");
            websocket.hasConnected = true;
            websocket.retrySocketDelay = 1;
            websocket.buffer.forEach(function(message) {
                websocket.socket.send(message);
            });
            // FIXME we should be logging that the socket is open - but there's a horrible cyclical dependency on startup atm
        }

        websocket.socket.onerror = function() {
            console.error("Error opening websocket");
        }

        websocket.socket.onmessage = function(message) {
            message = JSON.parse(message.data);
            if (message.type === "version") {
                // TODO Not being used yet to check version but should replace existing implementation at some point
                Florence.version = message.payload.version;
                return;
            }
            if (message.type !== "ack") {
                return;
            }
            websocket.buffer.delete(parseInt(message.payload));
        }

        websocket.socket.onclose = function() {
            console.info("Websocket has been closed");
            websocket.retrySocketDelay *= 2;
            if (websocket.retrySocketDelay >= 300000) {
                websocket.retrySocketDelay = 300000;
            }

            if (!websocket.hasConnected && websocket.reconnectAttempts >= 100) {
                console.info("Unable to connect websocket after 100 attempts, so stop retrying websocket");
                return;
            }

            setTimeout(() => {
                // setTimeout sets 'this' to window wrapping 'this.open()' in a lambda function
                // (rather than passing it inline), stops it.
                // Ref: https://stackoverflow.com/questions/2130241/pass-correct-this-context-to-settimeout-callback
                websocket.open();
            }, websocket.retrySocketDelay);
        }
    },
    send: function(message) {
        websocket.messageCounter++;
        message = websocket.messageCounter + ":" + message;

        if (websocket.buffer.size >= 50) {
            console.warn(`Websocket buffer has reached it's limit, so message will not be sent to server. Message: \n`, message);
            log.add(log.eventTypes.socketBufferFull); // This has to be excluded from being sent to the server or else we'll have an infinite loop
            return;
        }

        websocket.buffer.set(websocket.messageCounter, message);

        if (websocket.socket.readyState === 1) {
            websocket.socket.send(message);
        }
    }
};<commit_msg>Stop logging full websocket buffer to fix infinite loop<commit_after>var websocket = {
    socket: null,
    retrySocketDelay: 1,
    buffer: new Map(),
    messageCounter: 0,
    hasConnected: false,
    reconnectAttempts: 0,
    open: function() {
        console.info("Trying to open websocket...");

        websocket.socket = new WebSocket(location.protocol.replace(/^http/, 'ws') + location.host + "/florence/websocket");
        websocket.reconnectAttempts++;

        websocket.socket.onopen = function() {
            console.info("Websocket has been opened");
            websocket.hasConnected = true;
            websocket.retrySocketDelay = 1;
            websocket.buffer.forEach(function(message) {
                websocket.socket.send(message);
            });
            // FIXME we should be logging that the socket is open - but there's a horrible cyclical dependency on startup atm
        }

        websocket.socket.onerror = function() {
            console.error("Error opening websocket");
        }

        websocket.socket.onmessage = function(message) {
            message = JSON.parse(message.data);
            if (message.type === "version") {
                // TODO Not being used yet to check version but should replace existing implementation at some point
                Florence.version = message.payload.version;
                return;
            }
            if (message.type !== "ack") {
                return;
            }
            websocket.buffer.delete(parseInt(message.payload));
        }

        websocket.socket.onclose = function() {
            console.info("Websocket has been closed");
            websocket.retrySocketDelay *= 2;
            if (websocket.retrySocketDelay >= 300000) {
                websocket.retrySocketDelay = 300000;
            }

            if (!websocket.hasConnected && websocket.reconnectAttempts >= 100) {
                console.info("Unable to connect websocket after 100 attempts, so stop retrying websocket");
                return;
            }

            setTimeout(() => {
                // setTimeout sets 'this' to window wrapping 'this.open()' in a lambda function
                // (rather than passing it inline), stops it.
                // Ref: https://stackoverflow.com/questions/2130241/pass-correct-this-context-to-settimeout-callback
                websocket.open();
            }, websocket.retrySocketDelay);
        }
    },
    send: function(message) {
        websocket.messageCounter++;
        message = websocket.messageCounter + ":" + message;

        if (websocket.buffer.size >= 50) {
            console.warn(`Websocket buffer has reached it's limit, so message will not be sent to server. Message: \n`, message);
            //log.add(log.eventTypes.socketBufferFull); // This has to be excluded from being sent to the server or else we'll have an infinite loop
            return;
        }

        websocket.buffer.set(websocket.messageCounter, message);

        if (websocket.socket.readyState === 1) {
            websocket.socket.send(message);
        }
    }
};<|endoftext|>


<commit_before>import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

/* Layout */
import Layout from '@/views/layout/Layout'

/* Router Modules */
import componentsRouter from './modules/components'
import chartsRouter from './modules/charts'
import tableRouter from './modules/table'
import nestedRouter from './modules/nested'

/** note: submenu only apppear when children.length>=1
 *  detail see  https://panjiachen.github.io/vue-element-admin-site/guide/essentials/router-and-nav.html
 **/

/**
* hidden: true                   if `hidden:true` will not show in the sidebar(default is false)
* alwaysShow: true               if set true, will always show the root menu, whatever its child routes length
*                                if not set alwaysShow, only more than one route under the children
*                                it will becomes nested mode, otherwise not show the root menu
* redirect: noredirect           if `redirect:noredirect` will no redirct in the breadcrumb
* name:'router-name'             the name is used by <keep-alive> (must set!!!)
* meta : {
    roles: ['admin','editor']     will control the page roles (you can set multiple roles)
    title: 'title'               the name show in submenu and breadcrumb (recommend set)
    icon: 'svg-name'             the icon show in the sidebar,
    noCache: true                if true ,the page will no be cached(default is false)
  }
**/
export const constantRouterMap = [
  {
    path: '/redirect',
    component: Layout,
    hidden: true,
    children: [
      {
        path: '/redirect/:path*',
        component: () => import('@/views/redirect/index')
      }
    ]
  },
  {
    path: '/login',
    component: () => import('@/views/login/index'),
    hidden: true
  },
  {
    path: '/authredirect',
    component: () => import('@/views/login/authredirect'),
    hidden: true
  },
  {
    path: '/404',
    component: () => import('@/views/errorPage/404'),
    hidden: true
  },
  {
    path: '/401',
    component: () => import('@/views/errorPage/401'),
    hidden: true
  },
  {
    path: '',
    component: Layout,
    redirect: 'dashboard',
    children: [
      {
        path: 'dashboard',
        component: () => import('@/views/dashboard/index'),
        name: 'Dashboard',
        meta: { title: 'dashboard', icon: 'dashboard', noCache: true }
      }
    ]
  },
  {
    path: '/documentation',
    component: Layout,
    redirect: '/documentation/index',
    children: [
      {
        path: 'index',
        component: () => import('@/views/documentation/index'),
        name: 'Documentation',
        meta: { title: 'documentation', icon: 'documentation', noCache: true }
      }
    ]
  },
  {
    path: '/guide',
    component: Layout,
    redirect: '/guide/index',
    children: [
      {
        path: 'index',
        component: () => import('@/views/guide/index'),
        name: 'Guide',
        meta: { title: 'guide', icon: 'guide', noCache: true }
      }
    ]
  }
]

export default new Router({
  // mode: 'history', // require service support
  scrollBehavior: () => ({ y: 0 }),
  routes: constantRouterMap
})

export const asyncRouterMap = [
  {
    path: '/permission',
    component: Layout,
    redirect: '/permission/index',
    alwaysShow: true, // will always show the root menu
    meta: {
      title: 'permission',
      icon: 'lock',
      roles: ['admin', 'editor'] // you can set roles in root nav
    },
    children: [
      {
        path: 'page',
        component: () => import('@/views/permission/page'),
        name: 'PagePermission',
        meta: {
          title: 'pagePermission',
          roles: ['admin'] // or you can only set roles in sub nav
        }
      },
      {
        path: 'directive',
        component: () => import('@/views/permission/directive'),
        name: 'DirectivePermission',
        meta: {
          title: 'directivePermission'
          // if do not set roles, means: this page does not require permission
        }
      }
    ]
  },

  {
    path: '/icon',
    component: Layout,
    children: [
      {
        path: 'index',
        component: () => import('@/views/svg-icons/index'),
        name: 'Icons',
        meta: { title: 'icons', icon: 'icon', noCache: true }
      }
    ]
  },

  /** When your routing table is too long, you can split it into small modules**/
  componentsRouter,
  chartsRouter,
  nestedRouter,
  tableRouter,

  {
    path: '/example',
    component: Layout,
    redirect: '/example/list',
    name: 'Example',
    meta: {
      title: 'example',
      icon: 'example'
    },
    children: [
      {
        path: 'create',
        component: () => import('@/views/example/create'),
        name: 'CreateArticle',
        meta: { title: 'createArticle', icon: 'edit' }
      },
      {
        path: 'edit/:id(\\d+)',
        component: () => import('@/views/example/edit'),
        name: 'EditArticle',
        meta: { title: 'editArticle', noCache: true },
        hidden: true
      },
      {
        path: 'list',
        component: () => import('@/views/example/list'),
        name: 'ArticleList',
        meta: { title: 'articleList', icon: 'list' }
      }
    ]
  },

  {
    path: '/tab',
    component: Layout,
    children: [
      {
        path: 'index',
        component: () => import('@/views/tab/index'),
        name: 'Tab',
        meta: { title: 'tab', icon: 'tab' }
      }
    ]
  },

  {
    path: '/error',
    component: Layout,
    redirect: 'noredirect',
    name: 'ErrorPages',
    meta: {
      title: 'errorPages',
      icon: '404'
    },
    children: [
      {
        path: '401',
        component: () => import('@/views/errorPage/401'),
        name: 'Page401',
        meta: { title: 'page401', noCache: true }
      },
      {
        path: '404',
        component: () => import('@/views/errorPage/404'),
        name: 'Page404',
        meta: { title: 'page404', noCache: true }
      }
    ]
  },

  {
    path: '/error-log',
    component: Layout,
    redirect: 'noredirect',
    children: [
      {
        path: 'log',
        component: () => import('@/views/errorLog/index'),
        name: 'ErrorLog',
        meta: { title: 'errorLog', icon: 'bug' }
      }
    ]
  },

  {
    path: '/excel',
    component: Layout,
    redirect: '/excel/export-excel',
    name: 'Excel',
    meta: {
      title: 'excel',
      icon: 'excel'
    },
    children: [
      {
        path: 'export-excel',
        component: () => import('@/views/excel/exportExcel'),
        name: 'ExportExcel',
        meta: { title: 'exportExcel' }
      },
      {
        path: 'export-selected-excel',
        component: () => import('@/views/excel/selectExcel'),
        name: 'EelectExcel',
        meta: { title: 'selectExcel' }
      },
      {
        path: 'upload-excel',
        component: () => import('@/views/excel/uploadExcel'),
        name: 'UploadExcel',
        meta: { title: 'uploadExcel' }
      }
    ]
  },

  {
    path: '/zip',
    component: Layout,
    redirect: '/zip/download',
    alwaysShow: true,
    meta: { title: 'zip', icon: 'zip' },
    children: [
      {
        path: 'download',
        component: () => import('@/views/zip/index'),
        name: 'ExportZip',
        meta: { title: 'exportZip' }
      }
    ]
  },

  {
    path: '/theme',
    component: Layout,
    redirect: 'noredirect',
    children: [
      {
        path: 'index',
        component: () => import('@/views/theme/index'),
        name: 'Theme',
        meta: { title: 'theme', icon: 'theme' }
      }
    ]
  },

  {
    path: '/clipboard',
    component: Layout,
    redirect: 'noredirect',
    children: [
      {
        path: 'index',
        component: () => import('@/views/clipboard/index'),
        name: 'ClipboardDemo',
        meta: { title: 'clipboardDemo', icon: 'clipboard' }
      }
    ]
  },

  {
    path: '/i18n',
    component: Layout,
    children: [
      {
        path: 'index',
        component: () => import('@/views/i18n-demo/index'),
        name: 'I18n',
        meta: { title: 'i18n', icon: 'international' }
      }
    ]
  },

  {
    path: 'external-link',
    component: Layout,
    children: [
      {
        path: 'https://github.com/PanJiaChen/vue-element-admin',
        meta: { title: 'externalLink', icon: 'link' }
      }
    ]
  },

  { path: '*', redirect: '/404', hidden: true }
]
<commit_msg>fix name typo<commit_after>import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

/* Layout */
import Layout from '@/views/layout/Layout'

/* Router Modules */
import componentsRouter from './modules/components'
import chartsRouter from './modules/charts'
import tableRouter from './modules/table'
import nestedRouter from './modules/nested'

/** note: submenu only apppear when children.length>=1
 *  detail see  https://panjiachen.github.io/vue-element-admin-site/guide/essentials/router-and-nav.html
 **/

/**
* hidden: true                   if `hidden:true` will not show in the sidebar(default is false)
* alwaysShow: true               if set true, will always show the root menu, whatever its child routes length
*                                if not set alwaysShow, only more than one route under the children
*                                it will becomes nested mode, otherwise not show the root menu
* redirect: noredirect           if `redirect:noredirect` will no redirct in the breadcrumb
* name:'router-name'             the name is used by <keep-alive> (must set!!!)
* meta : {
    roles: ['admin','editor']     will control the page roles (you can set multiple roles)
    title: 'title'               the name show in submenu and breadcrumb (recommend set)
    icon: 'svg-name'             the icon show in the sidebar,
    noCache: true                if true ,the page will no be cached(default is false)
  }
**/
export const constantRouterMap = [
  {
    path: '/redirect',
    component: Layout,
    hidden: true,
    children: [
      {
        path: '/redirect/:path*',
        component: () => import('@/views/redirect/index')
      }
    ]
  },
  {
    path: '/login',
    component: () => import('@/views/login/index'),
    hidden: true
  },
  {
    path: '/authredirect',
    component: () => import('@/views/login/authredirect'),
    hidden: true
  },
  {
    path: '/404',
    component: () => import('@/views/errorPage/404'),
    hidden: true
  },
  {
    path: '/401',
    component: () => import('@/views/errorPage/401'),
    hidden: true
  },
  {
    path: '',
    component: Layout,
    redirect: 'dashboard',
    children: [
      {
        path: 'dashboard',
        component: () => import('@/views/dashboard/index'),
        name: 'Dashboard',
        meta: { title: 'dashboard', icon: 'dashboard', noCache: true }
      }
    ]
  },
  {
    path: '/documentation',
    component: Layout,
    redirect: '/documentation/index',
    children: [
      {
        path: 'index',
        component: () => import('@/views/documentation/index'),
        name: 'Documentation',
        meta: { title: 'documentation', icon: 'documentation', noCache: true }
      }
    ]
  },
  {
    path: '/guide',
    component: Layout,
    redirect: '/guide/index',
    children: [
      {
        path: 'index',
        component: () => import('@/views/guide/index'),
        name: 'Guide',
        meta: { title: 'guide', icon: 'guide', noCache: true }
      }
    ]
  }
]

export default new Router({
  // mode: 'history', // require service support
  scrollBehavior: () => ({ y: 0 }),
  routes: constantRouterMap
})

export const asyncRouterMap = [
  {
    path: '/permission',
    component: Layout,
    redirect: '/permission/index',
    alwaysShow: true, // will always show the root menu
    meta: {
      title: 'permission',
      icon: 'lock',
      roles: ['admin', 'editor'] // you can set roles in root nav
    },
    children: [
      {
        path: 'page',
        component: () => import('@/views/permission/page'),
        name: 'PagePermission',
        meta: {
          title: 'pagePermission',
          roles: ['admin'] // or you can only set roles in sub nav
        }
      },
      {
        path: 'directive',
        component: () => import('@/views/permission/directive'),
        name: 'DirectivePermission',
        meta: {
          title: 'directivePermission'
          // if do not set roles, means: this page does not require permission
        }
      }
    ]
  },

  {
    path: '/icon',
    component: Layout,
    children: [
      {
        path: 'index',
        component: () => import('@/views/svg-icons/index'),
        name: 'Icons',
        meta: { title: 'icons', icon: 'icon', noCache: true }
      }
    ]
  },

  /** When your routing table is too long, you can split it into small modules**/
  componentsRouter,
  chartsRouter,
  nestedRouter,
  tableRouter,

  {
    path: '/example',
    component: Layout,
    redirect: '/example/list',
    name: 'Example',
    meta: {
      title: 'example',
      icon: 'example'
    },
    children: [
      {
        path: 'create',
        component: () => import('@/views/example/create'),
        name: 'CreateArticle',
        meta: { title: 'createArticle', icon: 'edit' }
      },
      {
        path: 'edit/:id(\\d+)',
        component: () => import('@/views/example/edit'),
        name: 'EditArticle',
        meta: { title: 'editArticle', noCache: true },
        hidden: true
      },
      {
        path: 'list',
        component: () => import('@/views/example/list'),
        name: 'ArticleList',
        meta: { title: 'articleList', icon: 'list' }
      }
    ]
  },

  {
    path: '/tab',
    component: Layout,
    children: [
      {
        path: 'index',
        component: () => import('@/views/tab/index'),
        name: 'Tab',
        meta: { title: 'tab', icon: 'tab' }
      }
    ]
  },

  {
    path: '/error',
    component: Layout,
    redirect: 'noredirect',
    name: 'ErrorPages',
    meta: {
      title: 'errorPages',
      icon: '404'
    },
    children: [
      {
        path: '401',
        component: () => import('@/views/errorPage/401'),
        name: 'Page401',
        meta: { title: 'page401', noCache: true }
      },
      {
        path: '404',
        component: () => import('@/views/errorPage/404'),
        name: 'Page404',
        meta: { title: 'page404', noCache: true }
      }
    ]
  },

  {
    path: '/error-log',
    component: Layout,
    redirect: 'noredirect',
    children: [
      {
        path: 'log',
        component: () => import('@/views/errorLog/index'),
        name: 'ErrorLog',
        meta: { title: 'errorLog', icon: 'bug' }
      }
    ]
  },

  {
    path: '/excel',
    component: Layout,
    redirect: '/excel/export-excel',
    name: 'Excel',
    meta: {
      title: 'excel',
      icon: 'excel'
    },
    children: [
      {
        path: 'export-excel',
        component: () => import('@/views/excel/exportExcel'),
        name: 'ExportExcel',
        meta: { title: 'exportExcel' }
      },
      {
        path: 'export-selected-excel',
        component: () => import('@/views/excel/selectExcel'),
        name: 'SelectExcel',
        meta: { title: 'selectExcel' }
      },
      {
        path: 'upload-excel',
        component: () => import('@/views/excel/uploadExcel'),
        name: 'UploadExcel',
        meta: { title: 'uploadExcel' }
      }
    ]
  },

  {
    path: '/zip',
    component: Layout,
    redirect: '/zip/download',
    alwaysShow: true,
    meta: { title: 'zip', icon: 'zip' },
    children: [
      {
        path: 'download',
        component: () => import('@/views/zip/index'),
        name: 'ExportZip',
        meta: { title: 'exportZip' }
      }
    ]
  },

  {
    path: '/theme',
    component: Layout,
    redirect: 'noredirect',
    children: [
      {
        path: 'index',
        component: () => import('@/views/theme/index'),
        name: 'Theme',
        meta: { title: 'theme', icon: 'theme' }
      }
    ]
  },

  {
    path: '/clipboard',
    component: Layout,
    redirect: 'noredirect',
    children: [
      {
        path: 'index',
        component: () => import('@/views/clipboard/index'),
        name: 'ClipboardDemo',
        meta: { title: 'clipboardDemo', icon: 'clipboard' }
      }
    ]
  },

  {
    path: '/i18n',
    component: Layout,
    children: [
      {
        path: 'index',
        component: () => import('@/views/i18n-demo/index'),
        name: 'I18n',
        meta: { title: 'i18n', icon: 'international' }
      }
    ]
  },

  {
    path: 'external-link',
    component: Layout,
    children: [
      {
        path: 'https://github.com/PanJiaChen/vue-element-admin',
        meta: { title: 'externalLink', icon: 'link' }
      }
    ]
  },

  { path: '*', redirect: '/404', hidden: true }
]
<|endoftext|>


<commit_before>import Vue from 'vue'
import VueRouter from 'vue-router'

import Splash from '../routes/splash.vue'
import WardLeaderList from '../routes/ward-leader-list.vue'
import WardLeader from '../routes/ward-leader.vue'
import ContentPage from '../routes/content-page.vue'

Vue.use(VueRouter)

const routes = [
  { path: '/', component: Splash },
  { path: '/leaders', redirect: '/leaders/democratic' },
  { path: '/leaders/:party', component: WardLeaderList, props: true },
  { path: '/leaders/:party/:ward/:slug', component: WardLeader, props: true },
  { path: '/:slug', component: ContentPage, props: true }
]

const router = new VueRouter({
  mode: 'history',
  routes
})

export default router
<commit_msg>Router: add scroll behavior. Closes #123<commit_after>import Vue from 'vue'
import VueRouter from 'vue-router'

import Splash from '../routes/splash.vue'
import WardLeaderList from '../routes/ward-leader-list.vue'
import WardLeader from '../routes/ward-leader.vue'
import ContentPage from '../routes/content-page.vue'

Vue.use(VueRouter)

const routes = [
  { path: '/', component: Splash },
  { path: '/leaders', redirect: '/leaders/democratic' },
  { path: '/leaders/:party', component: WardLeaderList, props: true },
  { path: '/leaders/:party/:ward/:slug', component: WardLeader, props: true },
  { path: '/:slug', component: ContentPage, props: true }
]

const router = new VueRouter({
  mode: 'history',
  routes,
  scrollBehavior
})

function scrollBehavior (to, from, savedPosition) {
  if (savedPosition) {
    return savedPosition
  } else {
    return { x: 0, y: 0 }
  }
}

export default router
<|endoftext|>


<commit_before>import Vue        from 'vue'
import Router     from 'vue-router'
import menuModule from '../store/modules/menu'

Vue.use(Router)

const router =  new Router({
  mode: 'history',
  routes: [
    {
      path: '/culture/report',
      redirect: '/error/-1'
    },
    ...generateRoutesFromMenu(menuModule.state.items),
    {
      name: 'News',
      path: '/culture/news/:id',
      component: (resolve) => { require(['@/components/layout/Newspaper.vue'], resolve) }
    },
    {
      name: 'Post',
      path: '/culture/post/:id',
      component: (resolve) => { require(['@/components/layout/Reader.vue'], resolve) }
    },
    {
      name: 'Museum',
      path: '/intro/museum/:id',
      component: (resolve) => { require(['@/components/layout/CreationView.vue'], resolve) }
    },
    {
      name: 'Error',
      path: '/error/:status',
      component: (resolve) => { require(['@/components/layout/Error.vue'], resolve) }
    },
    {
      name: 'News',
      path: '/culture/news/:id/index.html',
      component: (resolve) => { require(['@/components/layout/Reader.vue'], resolve) }
    },
    {
      path: '*',
      redirect: '/error/404'
    }
  ]
})

function generateRoutesFromMenu (menu = [], routes = []) {
  for (let i = 0, l = menu.length; i < l; i++) {
    let item = menu[i]
    if (item.path) {
      routes.push(item)
    }
  }
  return routes
}

export default router
<commit_msg>Methods: Hide post collection page from route.<commit_after>import Vue        from 'vue'
import Router     from 'vue-router'
import menuModule from '../store/modules/menu'

Vue.use(Router)

const router =  new Router({
  mode: 'history',
  routes: [
    {
      path: '/culture/post',
      redirect: '/error/-1'
    },
    ...generateRoutesFromMenu(menuModule.state.items),
    {
      name: 'News',
      path: '/culture/news/:id',
      component: (resolve) => { require(['@/components/layout/Newspaper.vue'], resolve) }
    },
    {
      name: 'Post',
      path: '/culture/post/:id',
      component: (resolve) => { require(['@/components/layout/Reader.vue'], resolve) }
    },
    {
      name: 'Museum',
      path: '/intro/museum/:id',
      component: (resolve) => { require(['@/components/layout/CreationView.vue'], resolve) }
    },
    {
      name: 'Error',
      path: '/error/:status',
      component: (resolve) => { require(['@/components/layout/Error.vue'], resolve) }
    },
    {
      name: 'News',
      path: '/culture/news/:id/index.html',
      component: (resolve) => { require(['@/components/layout/Reader.vue'], resolve) }
    },
    {
      path: '*',
      redirect: '/error/404'
    }
  ]
})

function generateRoutesFromMenu (menu = [], routes = []) {
  for (let i = 0, l = menu.length; i < l; i++) {
    let item = menu[i]
    if (item.path) {
      routes.push(item)
    }
  }
  return routes
}

export default router
<|endoftext|>


<commit_before>class ContentQueue {

  constructor(processor, interval = 1, workFactor = 1, minWork = 1) {
    this.processor = processor;

    this.interval = interval;
    this.workFactor = workFactor;
    this.minWork = minWork;

    this.queue = new Map();

    this.schedule = ::this.schedule;
    this.run = ::this.run;

    this.schedule();
  }

  has(keyPattern) {
    // todo: allow wildcards (ie 8-*)
    return this.queue.has(keyPattern);
  }

  add(key, job) {
    if (this.queue.has(key)) {
      return;
    }

    this.queue.set(key, job);
  }

  remove(keyPattern) {
    let count = 0;

    if (keyPattern.toString().includes('*')) {
      for (const entry of this.queue) {
        const key = entry[0];

        if (key.startsWith(keyPattern.split('*')[0])) {
          this.queue.delete(key);
          count++;
        }
      }
    } else {
      if (this.queue.has(keyPattern)) {
        this.queue.delete(keyPattern);
        count++;
      }
    }

    return count;
  }

  schedule() {
    setTimeout(this.run, this.interval);
  }

  run() {
    let count = 0;
    const max = Math.min(this.queue.size * this.workFactor, this.minWork);

    for (const entry of this.queue) {
      const [key, job] = entry;

      this.processor(job);
      this.queue.delete(key);

      count++;

      if (count > max) {
        break;
      }
    }

    this.schedule();
  }

  clear() {
    this.queue.clear();
  }

}

export default ContentQueue;
<commit_msg>Removed unused pattern matching logic<commit_after>class ContentQueue {

  constructor(processor, interval = 1, workFactor = 1, minWork = 1) {
    this.processor = processor;

    this.interval = interval;
    this.workFactor = workFactor;
    this.minWork = minWork;

    this.queue = new Map();

    this.schedule = ::this.schedule;
    this.run = ::this.run;

    this.schedule();
  }

  has(keyPattern) {
    // todo: allow wildcards (ie 8-*)
    return this.queue.has(keyPattern);
  }

  add(key, job) {
    if (this.queue.has(key)) {
      return;
    }

    this.queue.set(key, job);
  }

  remove(key) {
    let count = 0;

    if (this.queue.has(key)) {
      this.queue.delete(key);
      count++;
    }

    return count;
  }

  schedule() {
    setTimeout(this.run, this.interval);
  }

  run() {
    let count = 0;
    const max = Math.min(this.queue.size * this.workFactor, this.minWork);

    for (const entry of this.queue) {
      const [key, job] = entry;

      this.processor(job);
      this.queue.delete(key);

      count++;

      if (count > max) {
        break;
      }
    }

    this.schedule();
  }

  clear() {
    this.queue.clear();
  }

}

export default ContentQueue;
<|endoftext|>


<commit_before>import Vue from 'vue';
import Router from 'vue-router';
import Home from '../components/Home.vue';
import Dashboard from '../components/Dashboard.vue';
import NewProject from '../components/NewProject.vue';
// import ProjectDetails from '../components/ProjectDetails.vue';

Vue.use(Router);

export default new Router({
  routes: [{
    path: '/',
    name: 'home',
    component: Home,
    children: [{
      path: '',
      name: 'dashboard',
      component: Dashboard
    }, {
      path: '/new-project',
      name: 'new-project',
      component: NewProject
    }, {
      path: '/project/:projectId',
      name: 'project-details',
      component: Dashboard,
      props: true
    }]
  }],
});
<commit_msg>Fixed navigation<commit_after>import Vue from 'vue';
import Router from 'vue-router';
import Home from '../components/Home.vue';
import Dashboard from '../components/Dashboard.vue';
import NewProject from '../components/NewProject.vue';
// import ProjectDetails from '../components/ProjectDetails.vue';

Vue.use(Router);

export default new Router({
  routes: [{
    path: '/',
    name: 'home',
    component: Home,
    children: [{
      path: '',
      name: 'dashboard',
      component: Dashboard
    }, {
      path: '/new-project',
      name: 'new-project',
      component: NewProject
    }, {
      path: '/:projectId',
      name: 'project-details',
      component: Dashboard,
      props: true
    }]
  }],
});
<|endoftext|>


<commit_before>import Vue from 'vue'
import Router from 'vue-router'
import Hello from '@/components/Hello'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Hello',
      component: Hello
    }
  ]
})
<commit_msg>修改路由配置<commit_after>import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

const home = r => require.ensure([], () => r(require('../pages/home')), 'home')

export default new Router({
  mode: 'history',
  routes: [
    {
      path: '/',
      name: 'home',
      component: home
    }
  ]
})
<|endoftext|>


<commit_before>var ldap = require('ldapjs');
var assert = require('assert');
var _ = require('lodash');

var mongoose = require('mongoose');

var model = require('../server/model');
var Page = model.Page;
var PageVersion = model.PageVersion;
var User = model.User;
var Group = model.Group;

var options = require('../server/options-handler').options;

var extractor = require('./LDAPExtractor');

var LDAPEntryToUser = extractor.LDAPEntryToUser;
var LDAPEntryToGroup = extractor.LDAPEntryToGroup;

var fetchUsers = function(successCallback,errorCallback) {
  var client = ldap.createClient({
    url: options['ldap']['server']
  });

  client.bind('', '', function(err) {
    console.error("RESULT");
    if (err) {
      client.unbind(function(err2) {
        errorCallback(err);
      });
      return;
    }
    var count=0;
    var users = [];
    client.search(options['ldap']['userDN'],{
      scope:"one",
      timeLimit:60*60
    },function(err, res) {
      if (err) {
        errorCallback(err);
        return;
      }

      res.on('searchEntry', function(entry) {
        var user = LDAPEntryToUser(entry);
        if (!user) {
          return;
        }
        users.push(user);

        count++;
        if(count%1000==0) {
          console.error(count);
        }
      });
      res.on('searchReference', function(referral) {
        console.error('referral: ' + referral.uris.join());
      });
      res.on('error', function(err) {
        console.error('error: ' + err.message);
      });
      res.on('end', function(result) {
        console.error('status: ' + result.status);
        if (result.status==0) {
          successCallback(users);
          client.unbind(function(err) {
          });
        } else {
          errorCallback(true);
        }
      });
    });
  });
};

var fetchGroups = function(successCallback,errorCallback) {
  var client = ldap.createClient({
    url: options['ldap']['server']
  });

  client.bind('', '', function(err) {
    console.error("RESULT");
    if (err) {
      client.unbind(function(err2) {
        errorCallback(err);
      });
      return;
    }
    var count=0;
    var userGroupMap = {};
    var groupNames = [];
    client.search(options['ldap']['groupDN'],{
      scope:"one",
      timeLimit:60*60
    },function(err, res) {
      if (err) {
        errorCallback(err);
        return;
      }

      res.on('searchEntry', function(entry) {
        //console.error('entry: ' + JSON.stringify(entry.object));
        var group = LDAPEntryToGroup(entry);
        if (!group) {
          return;
        }

        var groupName = group.name;
        var userlist = group.userlist;
        groupNames.push(groupName);
        for (var i=0;i<userlist.length;i++) {
          var user = userlist[i];
          if (!userGroupMap[user]) {
            //console.error("new user: " + user);
            userGroupMap[user] = [groupName];
          } else {
            userGroupMap[user].push(groupName);
          }
        }
        count++;
        if(count%1000==0) {
          console.error(count);
        }
      });
      res.on('searchReference', function(referral) {
        console.error('referral: ' + referral.uris.join());
      });
      res.on('error', function(err) {
        console.error('error: ' + err.message);
      });
      res.on('end', function(result) {
        console.error('status: ' + result.status);
        if (result.status==0) {
          successCallback(groupNames,userGroupMap);
          client.unbind(function(err) {
          });
        } else {
          errorCallback(true);
        }
      });
    });
  });
};

var getUsersAndGroups = function(success,failure) {
  fetchUsers(
    function(users) {
      var uidMap = {};
      for (var i=0;i<users.length;i++) {
        var user = users[i];
        user.groups = [];
        //console.log(user.username + "\t" + user.email + "\t" + user.fullName);
        uidMap[user.username] = user;
      }

      fetchGroups(
        function(groupList,userGroupMap) {
          for (var uid in userGroupMap) {
            if (uidMap[uid]) {
              //console.log('"' + uid + '"\t' + JSON.stringify(userGroupMap[uid]));
              uidMap[uid].groups = userGroupMap[uid];
            }
          }

          success(uidMap,groupList);
        },
        function(err) {
          failure(err);
        });
    },
    function(err) {
      failure(err);
    });
};

mongoose.connect('mongodb://localhost/tidalwave');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
  getUsersAndGroups(function (userIdMap,groupList) {
    var groupNameMap = {};
    for (var a=0;a<groupList.length;a++) {
      groupNameMap[groupList[a]] = groupList[a];
    }

    var groupNameIdMap = {};

    // This runs after update groups (below)
    var updateUsers = function() {

      // Replace the group names with group ids.
      for (var key in userIdMap) {
        var newUser = userIdMap[key];
        var groupNames = newUser.groups;
        newUser.groups = [];
        for (var b=0;b<groupNames.length;b++) {
          if (groupNames[b] in groupNameIdMap) {
            newUser.groups.push(groupNameIdMap[groupNames[b]]);
          } else {
            console.log("MISSING GROUP ID: " + groupNames[b]);
          }
        }
      }

      // Update users
      User
        .find({})
        .exec(function(err, results){
          var usersToUpdate = [];
          var usersToRemove = [];

          console.log("UPDATING USERS: " + results.length);
          for (var a=0;a<results.length;a++) {
            var user = results[a];
            if (userIdMap[user.username]) {
              var newUser = userIdMap[user.username];

              // See if anything has changed
              if (user.fullName != newUser.fullName ||
                  user.email != newUser.email ||
                  !_.isEqual(user.groups,newUser.groups)) {
                // Update the user record from LDAP
                console.log(JSON.stringify(newUser) + "!= " + JSON.stringify(user));
                user = _.extend(user,newUser);
                user.fromLdap = true;
                console.log("Updating user: " + JSON.stringify(user));
                usersToUpdate.push(user);
              }

              // Consume the LDAP record
              delete userIdMap[user.username];
            } else if (user.fromLdap) {
              // Record was not in LDAP anymore, remove
              console.log("Removing user: " + JSON.stringify(user));
              usersToRemove.push(user);
            }
          }

          var updateUsers = function(callback) {
            if (usersToUpdate.length>0) {
              var onUpdate = 0;
              var iterate = function() {
                if (onUpdate>= usersToUpdate.length) {
                  callback();
                  return;
                }
                usersToUpdate[onUpdate].save(function(err) {
                  onUpdate++;
                  iterate();
                });
              };
              iterate();
            } else {
              callback();
            }
          };

          var removeUsers = function(callback) {
            if (usersToRemove.length>0) {
              var onRemove = 0;
              var iterate = function() {
                if (onRemove >= usersToRemove.length) {
                  callback();
                  return;
                }
                usersToRemove[onRemove].remove(function(err) {
                  onRemove++;
                  iterate();
                });
              };
              iterate();
            } else {
              callback();
            }
          };

          var usersToSave = [];
          var userCount=0;
          for (var userId in userIdMap) {
            userCount++;
            if (userCount%100==0) {
              console.log(userCount + " / " + Object.keys(userIdMap).length);
            }
            var ldapUser = userIdMap[userId];
            ldapUser.fromLdap = true;
            usersToSave.push(ldapUser);
          }

          var createUsers = function(callback) {
            if (usersToSave.length) {
              var onUser = 0;
              var iterateUser = function(err, product, numberAffected) {
                console.log("Added user: " + JSON.stringify(product));
                onUser++;
                if (usersToSave.length>onUser) {
                  new User(usersToSave[onUser]).save(iterateUser);
                } else {
                  callback();
                }
              };
              new User(usersToSave[onUser]).save(iterateUser);
            } else {
              callback();
            }
          };

          removeUsers(function() {
            updateUsers(function() {
              createUsers(function() {
                // Finished, now close the DB
                console.log("FINISHED");
                mongoose.disconnect();
              });
            });
          });
        });
    };

    // Update groups
    Group
      .find({})
      .exec(function(err, results) {
        console.log("UPDATING GROUPS: " + results.length);
        if (err) {
          assert.ifError(err);
        }

        if (results) {
          for (var a=0;a<results.length;a++) {
            var group = results[a];
            if (groupNameMap[group.name]) {
              // The group still exists
              groupNameIdMap[group.name] = group._id;
              delete groupNameMap[group.name];
            } else if(group.fromLdap) {
              // The group is deleted
              console.log("Removing group: " + JSON.stringify(group));
              group.remove();
            }
          }
        }

        var groupsToSave = [];
        for (var groupName in groupNameMap) {
          var group = new Group({name:groupName,fromLdap:true});
          groupsToSave.push(group);
        }

        if (groupsToSave.length) {
          var onGroup = 0;
          var iterateGroup = function(err, product, numberAffected) {
            console.log("Added group: " + JSON.stringify(product));
            groupNameIdMap[product.name] = product._id;
            onGroup++;
            if (groupsToSave.length>onGroup) {
              groupsToSave[onGroup].save(iterateGroup);
            } else {
              // Finished, now update users
              updateUsers();
            }
          };
          groupsToSave[onGroup].save(iterateGroup);
        } else {
          // Nothing to do, update users
          updateUsers();
        }

      });
  }, function(err) {
    assert.ifError(err);
  });
});

<commit_msg>Use mongoose helper in UpdateLDAP.<commit_after>var ldap = require('ldapjs');
var assert = require('assert');
var _ = require('lodash');

var mongoose = require('mongoose');

var model = require('../server/model');
var Page = model.Page;
var PageVersion = model.PageVersion;
var User = model.User;
var Group = model.Group;

var options = require('../server/options-handler').options;

var mongooseHandler = require('../server/mongoose-handler');

var extractor = require('./LDAPExtractor');

var LDAPEntryToUser = extractor.LDAPEntryToUser;
var LDAPEntryToGroup = extractor.LDAPEntryToGroup;

var fetchUsers = function(successCallback,errorCallback) {
  var client = ldap.createClient({
    url: options['ldap']['server']
  });

  client.bind('', '', function(err) {
    console.error("RESULT");
    if (err) {
      client.unbind(function(err2) {
        errorCallback(err);
      });
      return;
    }
    var count=0;
    var users = [];
    client.search(options['ldap']['userDN'],{
      scope:"one",
      timeLimit:60*60
    },function(err, res) {
      if (err) {
        errorCallback(err);
        return;
      }

      res.on('searchEntry', function(entry) {
        var user = LDAPEntryToUser(entry);
        if (!user) {
          return;
        }
        users.push(user);

        count++;
        if(count%1000==0) {
          console.error(count);
        }
      });
      res.on('searchReference', function(referral) {
        console.error('referral: ' + referral.uris.join());
      });
      res.on('error', function(err) {
        console.error('error: ' + err.message);
      });
      res.on('end', function(result) {
        console.error('status: ' + result.status);
        if (result.status==0) {
          successCallback(users);
          client.unbind(function(err) {
          });
        } else {
          errorCallback(true);
        }
      });
    });
  });
};

var fetchGroups = function(successCallback,errorCallback) {
  var client = ldap.createClient({
    url: options['ldap']['server']
  });

  client.bind('', '', function(err) {
    console.error("RESULT");
    if (err) {
      client.unbind(function(err2) {
        errorCallback(err);
      });
      return;
    }
    var count=0;
    var userGroupMap = {};
    var groupNames = [];
    client.search(options['ldap']['groupDN'],{
      scope:"one",
      timeLimit:60*60
    },function(err, res) {
      if (err) {
        errorCallback(err);
        return;
      }

      res.on('searchEntry', function(entry) {
        //console.error('entry: ' + JSON.stringify(entry.object));
        var group = LDAPEntryToGroup(entry);
        if (!group) {
          return;
        }

        var groupName = group.name;
        var userlist = group.userlist;
        groupNames.push(groupName);
        for (var i=0;i<userlist.length;i++) {
          var user = userlist[i];
          if (!userGroupMap[user]) {
            //console.error("new user: " + user);
            userGroupMap[user] = [groupName];
          } else {
            userGroupMap[user].push(groupName);
          }
        }
        count++;
        if(count%1000==0) {
          console.error(count);
        }
      });
      res.on('searchReference', function(referral) {
        console.error('referral: ' + referral.uris.join());
      });
      res.on('error', function(err) {
        console.error('error: ' + err.message);
      });
      res.on('end', function(result) {
        console.error('status: ' + result.status);
        if (result.status==0) {
          successCallback(groupNames,userGroupMap);
          client.unbind(function(err) {
          });
        } else {
          errorCallback(true);
        }
      });
    });
  });
};

var getUsersAndGroups = function(success,failure) {
  fetchUsers(
    function(users) {
      var uidMap = {};
      for (var i=0;i<users.length;i++) {
        var user = users[i];
        user.groups = [];
        //console.log(user.username + "\t" + user.email + "\t" + user.fullName);
        uidMap[user.username] = user;
      }

      fetchGroups(
        function(groupList,userGroupMap) {
          for (var uid in userGroupMap) {
            if (uidMap[uid]) {
              //console.log('"' + uid + '"\t' + JSON.stringify(userGroupMap[uid]));
              uidMap[uid].groups = userGroupMap[uid];
            }
          }

          success(uidMap,groupList);
        },
        function(err) {
          failure(err);
        });
    },
    function(err) {
      failure(err);
    });
};

mongooseHandler.init(function callback () {
  getUsersAndGroups(function (userIdMap,groupList) {
    var groupNameMap = {};
    for (var a=0;a<groupList.length;a++) {
      groupNameMap[groupList[a]] = groupList[a];
    }

    var groupNameIdMap = {};

    // This runs after update groups (below)
    var updateUsers = function() {

      // Replace the group names with group ids.
      for (var key in userIdMap) {
        var newUser = userIdMap[key];
        var groupNames = newUser.groups;
        newUser.groups = [];
        for (var b=0;b<groupNames.length;b++) {
          if (groupNames[b] in groupNameIdMap) {
            newUser.groups.push(groupNameIdMap[groupNames[b]]);
          } else {
            console.log("MISSING GROUP ID: " + groupNames[b]);
          }
        }
      }

      // Update users
      User
        .find({})
        .exec(function(err, results){
          var usersToUpdate = [];
          var usersToRemove = [];

          console.log("UPDATING USERS: " + results.length);
          for (var a=0;a<results.length;a++) {
            var user = results[a];
            if (userIdMap[user.username]) {
              var newUser = userIdMap[user.username];

              // See if anything has changed
              if (user.fullName != newUser.fullName ||
                  user.email != newUser.email ||
                  !_.isEqual(user.groups,newUser.groups)) {
                // Update the user record from LDAP
                console.log(JSON.stringify(newUser) + "!= " + JSON.stringify(user));
                user = _.extend(user,newUser);
                user.fromLdap = true;
                console.log("Updating user: " + JSON.stringify(user));
                usersToUpdate.push(user);
              }

              // Consume the LDAP record
              delete userIdMap[user.username];
            } else if (user.fromLdap) {
              // Record was not in LDAP anymore, remove
              console.log("Removing user: " + JSON.stringify(user));
              usersToRemove.push(user);
            }
          }

          var updateUsers = function(callback) {
            if (usersToUpdate.length>0) {
              var onUpdate = 0;
              var iterate = function() {
                if (onUpdate>= usersToUpdate.length) {
                  callback();
                  return;
                }
                usersToUpdate[onUpdate].save(function(err) {
                  onUpdate++;
                  iterate();
                });
              };
              iterate();
            } else {
              callback();
            }
          };

          var removeUsers = function(callback) {
            if (usersToRemove.length>0) {
              var onRemove = 0;
              var iterate = function() {
                if (onRemove >= usersToRemove.length) {
                  callback();
                  return;
                }
                usersToRemove[onRemove].remove(function(err) {
                  onRemove++;
                  iterate();
                });
              };
              iterate();
            } else {
              callback();
            }
          };

          var usersToSave = [];
          var userCount=0;
          for (var userId in userIdMap) {
            userCount++;
            if (userCount%100==0) {
              console.log(userCount + " / " + Object.keys(userIdMap).length);
            }
            var ldapUser = userIdMap[userId];
            ldapUser.fromLdap = true;
            usersToSave.push(ldapUser);
          }

          var createUsers = function(callback) {
            if (usersToSave.length) {
              var onUser = 0;
              var iterateUser = function(err, product, numberAffected) {
                console.log("Added user: " + JSON.stringify(product));
                onUser++;
                if (usersToSave.length>onUser) {
                  new User(usersToSave[onUser]).save(iterateUser);
                } else {
                  callback();
                }
              };
              new User(usersToSave[onUser]).save(iterateUser);
            } else {
              callback();
            }
          };

          removeUsers(function() {
            updateUsers(function() {
              createUsers(function() {
                // Finished, now close the DB
                console.log("FINISHED");
                mongoose.disconnect();
              });
            });
          });
        });
    };

    // Update groups
    Group
      .find({})
      .exec(function(err, results) {
        console.log("UPDATING GROUPS: " + results.length);
        if (err) {
          assert.ifError(err);
        }

        if (results) {
          for (var a=0;a<results.length;a++) {
            var group = results[a];
            if (groupNameMap[group.name]) {
              // The group still exists
              groupNameIdMap[group.name] = group._id;
              delete groupNameMap[group.name];
            } else if(group.fromLdap) {
              // The group is deleted
              console.log("Removing group: " + JSON.stringify(group));
              group.remove();
            }
          }
        }

        var groupsToSave = [];
        for (var groupName in groupNameMap) {
          var group = new Group({name:groupName,fromLdap:true});
          groupsToSave.push(group);
        }

        if (groupsToSave.length) {
          var onGroup = 0;
          var iterateGroup = function(err, product, numberAffected) {
            console.log("Added group: " + JSON.stringify(product));
            groupNameIdMap[product.name] = product._id;
            onGroup++;
            if (groupsToSave.length>onGroup) {
              groupsToSave[onGroup].save(iterateGroup);
            } else {
              // Finished, now update users
              updateUsers();
            }
          };
          groupsToSave[onGroup].save(iterateGroup);
        } else {
          // Nothing to do, update users
          updateUsers();
        }

      });
  }, function(err) {
    assert.ifError(err);
  });
});
<|endoftext|>


<commit_before>const Argument = require('./Argument');

/**
 * Base Abstracted class for Multi-Resolving D.JS and Klasa Structures.
 * @extends Argument
 */
class MultiArgument extends Argument {

	/**
	 * A getter for the base argument
	 * @since 0.5.0
	 * @type {Argument}
	 * @readonly
	 * @abstract
	 */
	get base() {
		throw new Error('A "base" getter must be implemented in extended classes.');
	}

	/**
	 * The run method for handling MultiArguments (not to be implemented in extended classes)
	 * @since 0.5.0
	 * @param {string} argument The string argument string to resolve
	 * @param {Possible} possible This current usage possible
	 * @param {KlasaMessage} message The message that triggered the command
	 */
	async run(argument, possible, message) {
		const structures = [];
		const { min, max } = possible;
		const { args, usage: { usageDelim } } = message.prompter;
		const index = args.indexOf(argument);
		const rest = args.splice(index, args.length - index);
		const { base } = this;
		let i = 0;

		for (const arg of rest) {
			if (max && i > max) break;
			try {
				const structure = await base.run(arg, possible, message);
				structures.push(structure);
				i++;
			} catch (err) {
				break;
			}
		}

		args.push(rest.splice(0, structures.length).join(usageDelim), ...rest);
		if ((min && structures.length < min) || !structures.length) throw message.language.get(`RESOLVER_MULTI_TOO_FEW`, base.name, min);
		return structures;
	}

}

module.exports = MultiArgument;
<commit_msg>fix off by one bug with MultiArgument<commit_after>const Argument = require('./Argument');

/**
 * Base Abstracted class for Multi-Resolving D.JS and Klasa Structures.
 * @extends Argument
 */
class MultiArgument extends Argument {

	/**
	 * A getter for the base argument
	 * @since 0.5.0
	 * @type {Argument}
	 * @readonly
	 * @abstract
	 */
	get base() {
		throw new Error('A "base" getter must be implemented in extended classes.');
	}

	/**
	 * The run method for handling MultiArguments (not to be implemented in extended classes)
	 * @since 0.5.0
	 * @param {string} argument The string argument string to resolve
	 * @param {Possible} possible This current usage possible
	 * @param {KlasaMessage} message The message that triggered the command
	 */
	async run(argument, possible, message) {
		const structures = [];
		const { min, max } = possible;
		const { args, usage: { usageDelim } } = message.prompter;
		const index = args.indexOf(argument);
		const rest = args.splice(index, args.length - index);
		const { base } = this;
		let i = 0;

		for (const arg of rest) {
			if (max && i >= max) break;
			try {
				const structure = await base.run(arg, possible, message);
				structures.push(structure);
				i++;
			} catch (err) {
				break;
			}
		}

		args.push(rest.splice(0, structures.length).join(usageDelim), ...rest);
		if ((min && structures.length < min) || !structures.length) throw message.language.get(`RESOLVER_MULTI_TOO_FEW`, base.name, min);
		return structures;
	}

}

module.exports = MultiArgument;
<|endoftext|>


<commit_before>import Router from 'koa-router'
import indexCtrl from '../controllers/indexCtrl'
import voteCtrl from '../controllers/voteCtrl'

import adminCtrl from '../controllers/adminLoginCtrl'

import changeStatusCtrl from '../controllers/changeStatusCtrl'
import typeStatusCtrl from '../controllers/typeStatusCtrl'

const router = new Router({
  prefix: '/vote_drx'
})

router.get('/index', indexCtrl)
router.post('/vote', voteCtrl)
router.post('/adminLogin', adminCtrl)
router.post('/changeStatus', changeStatusCtrl)

router.get('/typeStatus', typeStatusCtrl)

// router.get('/test', async (ctx) => {
//     await ctx.render('index')
// })
// router.get('/admin', async (ctx) => {
//     await ctx.render('admin')
// })

export default router
<commit_msg>静态资源路径问题<commit_after>import Router from 'koa-router'
import indexCtrl from '../controllers/indexCtrl'
import voteCtrl from '../controllers/voteCtrl'

import adminCtrl from '../controllers/adminLoginCtrl'

import changeStatusCtrl from '../controllers/changeStatusCtrl'
import typeStatusCtrl from '../controllers/typeStatusCtrl'

const router = Router()

router.get('/vote_drx/index', indexCtrl)
router.post('/vote_drx/vote', voteCtrl)
router.post('/vote_drx/adminLogin', adminCtrl)
router.post('/vote_drx/changeStatus', changeStatusCtrl)

router.get('/vote_drx/typeStatus', typeStatusCtrl)

export default router
<|endoftext|>


<commit_before>import React from 'react'
import { Router, Route, IndexRoute, browserHistory } from 'react-router'

import App from '../containers/App'
import Article from '../containers/Article'
import Blank from '../containers/Blank'
import Category from '../containers/Category'
import Home from '../containers/Home'
import Photography from '../containers/Photography'
import Search from '../containers/Search'
import Tag from '../containers/Tag'
import Topic from '../containers/Topic'

export default function (history = browserHistory) {
  return (
    <Router history={history} onUpdate={() => window.scrollTo(0, 0)}>
      <Route path="/" component={App}>
        <IndexRoute component={Home} />
        <Route path="category/:category" component={Category}/>
        <Route path="topic/:topicId" component={Topic} />
        <Route path="tag/:tagId" component={Tag} />
        <Route path="photography" component={Photography}/>
        <Route path="search" component={Search}/>
        <Route path="check" component={Blank}/>
        <Route path="a/:slug" component={Article}/>
      </Route>
    </Router>
  )
}
<commit_msg>Add keystone preview path<commit_after>import React from 'react'
import { Router, Route, IndexRoute, browserHistory } from 'react-router'

import App from '../containers/App'
import Article from '../containers/Article'
import Blank from '../containers/Blank'
import Category from '../containers/Category'
import Home from '../containers/Home'
import Photography from '../containers/Photography'
import Search from '../containers/Search'
import Tag from '../containers/Tag'
import Topic from '../containers/Topic'

export default function (history = browserHistory) {
  return (
    <Router history={history} onUpdate={() => window.scrollTo(0, 0)}>
      <Route path="/" component={App}>
        <IndexRoute component={Home} />
        <Route path="category/:category" component={Category}/>
        <Route path="topic/:topicId" component={Topic} />
        <Route path="tag/:tagId" component={Tag} />
        <Route path="photography" component={Photography}/>
        <Route path="search" component={Search}/>
        <Route path="check" component={Blank}/>
        <Route path="a/:slug" component={Article}/>
      </Route>
      <Route path="/keystone/preview" component={App}>
        <IndexRoute component={Home} />
        <Route path="a/:slug" component={Article}/>
      </Route>
    </Router>
  )
}
<|endoftext|>


<commit_before>'use strict';

const express = require('express'),
    router = express.Router(),
    UserModel = require('../model/user');

router.get('/', getUsers);
router.put('/', putUser);
router.delete('/:id', deleteUser);

module.exports = router;

function getUsers (req, res) {
    res.send({});
}

function putUser (req, res, next) {
    let user = new UserModel(req.body);

    user.save()
        .then(user => res.status(201).send(user))
        .catch(error);

    function error (err) {
        //@TODO implements erroar handler
        if (err.name === 'ValidationError' || err.code === 11000) {
            err.status = 422;
        }
        next(err);
    }
}

function deleteUser (req, res, next) {
    UserModel.remove({ _id: req.query.id })
        .then(success);

    function success () {
        return res.sendStatus(204);
    }
}
<commit_msg>send self user data<commit_after>'use strict';

const express = require('express'),
    router = express.Router(),
    UserModel = require('../model/user');

router.get('/', getUsers);
router.get('/self/details', getUserDetail);
router.put('/', putUser);
router.delete('/:id', deleteUser);

module.exports = router;

function getUsers (req, res) {
    res.send({});
}

function putUser (req, res, next) {
    let user = new UserModel(req.body);

    user.save()
        .then(user => res.status(201).send(user))
        .catch(error);

    function error (err) {
        //@TODO implements erroar handler
        if (err.name === 'ValidationError' || err.code === 11000) {
            err.status = 422;
        }
        next(err);
    }
}

function deleteUser (req, res, next) {
    UserModel.remove({ _id: req.query.id })
        .then(success);

    function success () {
        return res.sendStatus(204);
    }
}

function getUserDetail(req, res, next) {
    UserModel.findOne({_id: req.user.id}).then(user => res.send(user));
}
<|endoftext|>


<commit_before>const owners = config.prop.owners;

module.exports = {

	hasRole(member, rolename) {
		let role = member.guild.roles.find(r => r.name === rolename);
		return (role && member.roles.includes(role.id));
	},

	isAdmin(member) {
		return (module.exports.hasRole(member, "DJ") || owners.includes(member.id) || member.guild.ownerID === member.id);
	},

	isBlocked(member) {
		let hdb = require(`../src/config.json`).prop.blocked;
		delete require.cache[require.resolve(`../src/config.json`)];

		return ((module.exports.hasRole(member, "NoMusic") || hdb.includes(member)) && !owners.includes(member) && member.guild.ownerID !== member);
	},

	isDonator(member) {
		let donators = require(`../src/config.json`).prop.donators;
		delete require.cache[require.resolve(`../src/config.json`)];

		return (donators.includes(member) || owners.includes(member));
	}

}
<commit_msg>Permissions Handler fix<commit_after>const owners = config.owners;

module.exports = {

	hasRole(member, rolename) {
		if (!member.guild) return false;
		let role = member.guild.roles.find(r => r.name === rolename);
		return (role && member.roles.includes(role.id));
	},

	isAdmin(member) {
		return (module.exports.hasRole(member, "DJ") || owners.includes(member.id) || member.guild.ownerID === member.id);
	},

	isBlocked(member) {
		let hdb = require(`../src/config.json`).hardblock;
		delete require.cache[require.resolve(`../src/config.json`)];

		return ((module.exports.hasRole(member, "NoMusic") || hdb.includes(member.id)) && !owners.includes(member.id) && member.guild.ownerID !== member.id);
	},

	isDonator(member) {
		let donators = require(`../src/config.json`).donators;
		delete require.cache[require.resolve(`../src/config.json`)];

		return (donators.includes(member) || owners.includes(member));
	}

}
<|endoftext|>


<commit_before>const LoadTest = require("./LoadTest");

const runPorcelain = (config) => {
  const loadTest = new LoadTest({
    ...config,
    onSuccess: ({ url }, duration, text) => {
      console.log("Ok:", url, `${duration}ms`);
    },
    onFail: ({ url }, duration, text) => {
      console.log("Failed:", url, `${duration}ms`);
    },
    onError: (e) => {
      console.log("Error:", e.message);
    },
  });

  // print header
  console.log("-----------------------");
  console.log("Load Generator");
  console.log("-----------------------");
  const { values, headers, ...bulk } = config;
  console.log(JSON.stringify(bulk, null, 2));
  console.log("-----------------------");

  // start run
  loadTest.start();
};

module.exports = runPorcelain;
<commit_msg>Handle exit codes<commit_after>const LoadTest = require("./LoadTest");

const runPorcelain = (config) => {
  const loadTest = new LoadTest({
    ...config,
    onSuccess: ({ url }, duration, text) => {
      console.log("Ok:", url, `${duration}ms`);
    },
    onFail: ({ url }, duration, text) => {
      console.log("Failed:", url, `${duration}ms`);
    },
    onError: (e) => {
      console.log("Error:", e.message);
    },
  });

  // print header
  console.log("-----------------------");
  console.log("Load Generator");
  console.log("-----------------------");
  const { values, headers, ...bulk } = config;
  console.log(JSON.stringify(bulk, null, 2));
  console.log("-----------------------");

  // listen for exit signals
  const exit = (cause) => {
    loadTest.stop();
    console.log(cause);
    process.exit();
  };
  process.on("SIGTERM", () => exit("Received SIGTERM"));

  // catch esc
  const { stdin } = process;
  stdin.setRawMode(true);
  stdin.resume();
  stdin.setEncoding("utf8");
  stdin.on("data", (key) => {
    const exitKeys = [
      "\u0003", // ctrl-c
      "\u001b", // esc
      "\u0071", // q
    ];

    if (exitKeys.includes(key)) {
      return exit("Aborted by user");
    }

    // write the key to stdout all normal like
    process.stdout.write(key);
  });

  // start run
  loadTest.start();
};

module.exports = runPorcelain;
<|endoftext|>


<commit_before>/**
 * Copyright 2018 The Subscribe with Google Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/** @interface */
export class DepsDef {
  /**
   * @return {!../model/doc.Doc}
   */
  doc() {}

  /**
   * @return {!Window}
   */
  win() {}

  /**
   * @return {!../api/subscriptions.Config}
   */
  config() {}

  /**
   * @return {!../model/page-config.PageConfig}
   */
  pageConfig() {}

  /**
   * @return {!../components/activities.ActivityPorts}
   */
  activities() {}

  /**
   * @return {!./pay-client.PayClient}
   */
  payClient() {}

  /**1
   * @return {!../components/dialog-manager.DialogManager}
   */
  dialogManager() {}

  /**
   * @return {!./entitlements-manager.EntitlementsManager}
   */
  entitlementsManager() {}

  /**
   * @return {!./callbacks.Callbacks}
   */
  callbacks() {}

  /**
   * @return {!../runtime/storage.Storage}
   */
  storage() {}

  /**
   * @return {!../runtime/analytics-service.AnalyticsService}
   */
  analytics() {}

  /**
   * @return {!../runtime/jserror.JsError}
   */
  jserror() {}

  /**
   * @return {!../api/client-event-manager-api.ClientEventManagerApi}
   */
  eventManager() {}
}
<commit_msg>Remove a '1'.<commit_after>/**
 * Copyright 2018 The Subscribe with Google Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/** @interface */
export class DepsDef {
  /**
   * @return {!../model/doc.Doc}
   */
  doc() {}

  /**
   * @return {!Window}
   */
  win() {}

  /**
   * @return {!../api/subscriptions.Config}
   */
  config() {}

  /**
   * @return {!../model/page-config.PageConfig}
   */
  pageConfig() {}

  /**
   * @return {!../components/activities.ActivityPorts}
   */
  activities() {}

  /**
   * @return {!./pay-client.PayClient}
   */
  payClient() {}

  /**
   * @return {!../components/dialog-manager.DialogManager}
   */
  dialogManager() {}

  /**
   * @return {!./entitlements-manager.EntitlementsManager}
   */
  entitlementsManager() {}

  /**
   * @return {!./callbacks.Callbacks}
   */
  callbacks() {}

  /**
   * @return {!../runtime/storage.Storage}
   */
  storage() {}

  /**
   * @return {!../runtime/analytics-service.AnalyticsService}
   */
  analytics() {}

  /**
   * @return {!../runtime/jserror.JsError}
   */
  jserror() {}

  /**
   * @return {!../api/client-event-manager-api.ClientEventManagerApi}
   */
  eventManager() {}
}
<|endoftext|>


<commit_before>;(function () {
    var ls = window.localStorage;

    try {
        var test = '__vue-localstorage-test__';

        ls.setItem(test, test);
        ls.removeItem(test);
    } catch (e) {
        console.error('Local storage not supported by this browser');
    }

    var type, key, value;

    var VueLocalStorage = {
        // Get value from localStorage
        get: function (lsKey) {
            if (ls.hasOwnProperty(lsKey)) {
                type = String;

                for (key in VueLocalStorage._properties) {
                    if (key === lsKey) {
                        type = VueLocalStorage._properties[key].type;
                        break;
                    }
                }

                return VueLocalStorage._process(type, ls[lsKey]);
            }

            return null;
        },
        // Set localStorage value
        set: function (lsKey, value) {
            for (key in VueLocalStorage._properties) {
                type = VueLocalStorage._properties[key].type;

                if ((key === lsKey) && (type === Array || type === Object)) {
                    ls[lsKey] = JSON.stringify(value);
                    return value;
                }
            }

            ls[lsKey] = value;

            return value;
        },
        // Remove from localStorage
        remove: function (lsKey) {
            return ls.removeItem(lsKey);
        },
        // Private function that processes the value
        _process: function (type, value) {
            switch (type) {
                case Boolean:
                    return value === 'true';
                case Number:
                    return parseInt(value, 10);
                case Array:
                    try {
                        let array = JSON.parse(value);
                        return Array.isArray(array) ? array : [];
                    } catch (e) {
                        return [];
                    }
                case Object:
                    try {
                        return JSON.parse(value);
                    } catch (e) {
                        return {};
                    }
                default:
                    return value;
            }
        },
        // Properties Object created from components
        _properties: {}
    };

    var localStoragePlugin = {
        install: function (Vue) {
            Vue.mixin({
                created: function () {
                    if (this.$options.hasOwnProperty('localStorage')) {
                        // Copy all properties to _properties object
                        for (key in this.$options.localStorage) {
                            if (!VueLocalStorage._properties.hasOwnProperty(key)) {
                                VueLocalStorage._properties[key] = {};
                            }

                            type = (this.$options.localStorage[key].hasOwnProperty('type'))
                                ? this.$options.localStorage[key].type
                                : String;

                            VueLocalStorage._properties[key].type = type;

                            // Check for default value
                            if (
                                !ls.hasOwnProperty(key) &&
                                this.$options.localStorage[key].hasOwnProperty('default')
                            ) {
                                value = this.$options.localStorage[key].default;
                                ls[key] = (type === Array || type === Object) ? JSON.stringify(value) : value;
                            }
                        }
                    }

                    // Global localStorage instance
                    this.$localStorage = VueLocalStorage;
                }
            });
        }
    };

    if (typeof exports === 'object') {
        module.exports = localStoragePlugin;
    } else if (typeof define === 'function' && define.amd) {
        define([], function () {
            return localStoragePlugin;
        })
    } else if (window.Vue) {
        window.VueLocalStorage = localStoragePlugin;
    }
})();
<commit_msg>let array changed to var array inside commonjs version<commit_after>;(function () {
    var ls = window.localStorage;

    try {
        var test = '__vue-localstorage-test__';

        ls.setItem(test, test);
        ls.removeItem(test);
    } catch (e) {
        console.error('Local storage not supported by this browser');
    }

    var type, key, value;

    var VueLocalStorage = {
        // Get value from localStorage
        get: function (lsKey) {
            if (ls.hasOwnProperty(lsKey)) {
                type = String;

                for (key in VueLocalStorage._properties) {
                    if (key === lsKey) {
                        type = VueLocalStorage._properties[key].type;
                        break;
                    }
                }

                return VueLocalStorage._process(type, ls[lsKey]);
            }

            return null;
        },
        // Set localStorage value
        set: function (lsKey, value) {
            for (key in VueLocalStorage._properties) {
                type = VueLocalStorage._properties[key].type;

                if ((key === lsKey) && (type === Array || type === Object)) {
                    ls[lsKey] = JSON.stringify(value);
                    return value;
                }
            }

            ls[lsKey] = value;

            return value;
        },
        // Remove from localStorage
        remove: function (lsKey) {
            return ls.removeItem(lsKey);
        },
        // Private function that processes the value
        _process: function (type, value) {
            switch (type) {
                case Boolean:
                    return value === 'true';
                case Number:
                    return parseInt(value, 10);
                case Array:
                    try {
                        var array = JSON.parse(value);
                        return Array.isArray(array) ? array : [];
                    } catch (e) {
                        return [];
                    }
                case Object:
                    try {
                        return JSON.parse(value);
                    } catch (e) {
                        return {};
                    }
                default:
                    return value;
            }
        },
        // Properties Object created from components
        _properties: {}
    };

    var localStoragePlugin = {
        install: function (Vue) {
            Vue.mixin({
                created: function () {
                    if (this.$options.hasOwnProperty('localStorage')) {
                        // Copy all properties to _properties object
                        for (key in this.$options.localStorage) {
                            if (!VueLocalStorage._properties.hasOwnProperty(key)) {
                                VueLocalStorage._properties[key] = {};
                            }

                            type = (this.$options.localStorage[key].hasOwnProperty('type'))
                                ? this.$options.localStorage[key].type
                                : String;

                            VueLocalStorage._properties[key].type = type;

                            // Check for default value
                            if (
                                !ls.hasOwnProperty(key) &&
                                this.$options.localStorage[key].hasOwnProperty('default')
                            ) {
                                value = this.$options.localStorage[key].default;
                                ls[key] = (type === Array || type === Object) ? JSON.stringify(value) : value;
                            }
                        }
                    }

                    // Global localStorage instance
                    this.$localStorage = VueLocalStorage;
                }
            });
        }
    };

    if (typeof exports === 'object') {
        module.exports = localStoragePlugin;
    } else if (typeof define === 'function' && define.amd) {
        define([], function () {
            return localStoragePlugin;
        })
    } else if (window.Vue) {
        window.VueLocalStorage = localStoragePlugin;
    }
})();
<|endoftext|>


<commit_before>import styles from "./style.yml";

const axisStyles = {
  barConfig: {
    stroke: "#ccc"
  },
  gridConfig: {
    stroke: "#ccc"
  },
  shapeConfig: {
    labelConfig: {
      fontColor: () => "#211f1a",
      fontFamily: () => "Source Sans Pro",
      fontSize: () => 12,
      fontWeight: () => 400
    },
    stroke: "#ccc"
  },
  tickSize: 5,
  titleConfig: {
    fontColor: () => "#211f1a",
    fontFamily: () => "Palanquin",
    fontSize: () => 12,
    fontWeight: () => 400
  }
};

export default {
  barPadding: 0,
  colorScaleConfig: {
    axisConfig: {
      labelOffset: true,
      labelRotation: false
    },
    color: ["#ecf3f7", "#cfdfeb", "#b0cde1", "#90bad8", "#6ea7d2", "#4c96cb", "#3182bd", "#004374"],
    // color: ["#f8ecec", "#edd1d1", "#e4b4b4", "#dc9595", "#d57676", "#cf5555", "#CA3434", "#7b0000"],
    scale: "jenks"
  },
  confidenceConfig: {
    fillOpacity: 0.2
  },
  legendConfig: {
    shapeConfig: {
      labelConfig: {
        fontFamily: () => "Palanquin",
        fontSize: () => 13
      },
      height: () => 20,
      width: () => 20
    }
  },
  messageMask: false,
  messageStyle: {
    "color": "#888",
    "font-family": "'Palanquin', sans-serif",
    "font-size": "16px",
    "font-weight": "300"
  },
  ocean: "#D5DADC",
  padPixel: 1,
  shapeConfig: {
    fill: styles.red,
    hoverOpacity: 0.5,
    labelConfig: {
      fontFamily: () => "Pathway Gothic One",
      fontSize: () => 13,
      padding: 5
    },
    Line: {
      stroke: styles.red,
      strokeWidth: 3,
      strokeLinecap: "round"
    },
    Path: {
      fillOpacity: 0.75
    }
  },
  titleConfig: {
    fontFamily: "Pathway Gothic One",
    fontSize: 20,
    fontWeight: 400,
    padding: 0
  },
  tooltipConfig: {
    background: "white",
    border: "1px solid #888",
    footerStyle: {
      "color": "#666",
      "font-family": "'Palanquin', sans-serif",
      "font-size": "12px",
      "font-weight": "300",
      "padding-top": "5px"
    },
    padding: "10px",
    titleStyle: {
      "color": "#888",
      "font-family": "'Palanquin', sans-serif",
      "font-size": "16px",
      "font-weight": "300"
    }
  },
  xConfig: {...axisStyles},
  yConfig: {...axisStyles}
};
<commit_msg>adds global styling for colorScale ticks<commit_after>import styles from "./style.yml";

const axisStyles = {
  barConfig: {
    stroke: "#ccc"
  },
  gridConfig: {
    stroke: "#ccc"
  },
  shapeConfig: {
    labelConfig: {
      fontColor: () => "#211f1a",
      fontFamily: () => "Source Sans Pro",
      fontSize: () => 12,
      fontWeight: () => 400
    },
    stroke: "#ccc"
  },
  tickSize: 5,
  titleConfig: {
    fontColor: () => "#211f1a",
    fontFamily: () => "Palanquin",
    fontSize: () => 12,
    fontWeight: () => 400
  }
};

export default {
  barPadding: 0,
  colorScaleConfig: {
    axisConfig: {
      labelOffset: true,
      labelRotation: false,
      shapeConfig: {
        labelConfig: {
          fontColor: () => "#211f1a",
          fontFamily: () => "Source Sans Pro",
          fontSize: () => 12,
          fontWeight: () => 400
        }
      },
      titleConfig: {
        fontColor: () => "#211f1a",
        fontFamily: () => "Palanquin",
        fontSize: () => 12,
        fontWeight: () => 400
      }
    },
    color: ["#ecf3f7", "#cfdfeb", "#b0cde1", "#90bad8", "#6ea7d2", "#4c96cb", "#3182bd", "#004374"],
    // color: ["#f8ecec", "#edd1d1", "#e4b4b4", "#dc9595", "#d57676", "#cf5555", "#CA3434", "#7b0000"],
    scale: "jenks"
  },
  confidenceConfig: {
    fillOpacity: 0.2
  },
  legendConfig: {
    shapeConfig: {
      labelConfig: {
        fontFamily: () => "Palanquin",
        fontSize: () => 13
      },
      height: () => 20,
      width: () => 20
    }
  },
  messageMask: false,
  messageStyle: {
    "color": "#888",
    "font-family": "'Palanquin', sans-serif",
    "font-size": "16px",
    "font-weight": "300"
  },
  ocean: "#D5DADC",
  padPixel: 1,
  shapeConfig: {
    fill: styles.red,
    hoverOpacity: 0.5,
    labelConfig: {
      fontFamily: () => "Pathway Gothic One",
      fontSize: () => 13,
      padding: 5
    },
    Line: {
      stroke: styles.red,
      strokeWidth: 3,
      strokeLinecap: "round"
    },
    Path: {
      fillOpacity: 0.75
    }
  },
  titleConfig: {
    fontFamily: "Pathway Gothic One",
    fontSize: 20,
    fontWeight: 400,
    padding: 0
  },
  tooltipConfig: {
    background: "white",
    border: "1px solid #888",
    footerStyle: {
      "color": "#666",
      "font-family": "'Palanquin', sans-serif",
      "font-size": "12px",
      "font-weight": "300",
      "padding-top": "5px"
    },
    padding: "10px",
    titleStyle: {
      "color": "#888",
      "font-family": "'Palanquin', sans-serif",
      "font-size": "16px",
      "font-weight": "300"
    }
  },
  xConfig: {...axisStyles},
  yConfig: {...axisStyles}
};
<|endoftext|>


<commit_before>// HOTSWAPPABLE GLOBAL MODULE CORE!
// Probably a better way to do this in ES5/6 nowadays but this is some old code

var Global = {
    io : { },
    serial : { },
    logger : { },
    config : { }
}

module.exports = global;<commit_msg>we don't need this<commit_after><|endoftext|>


<commit_before>const config = require('../config/config');
const mongojs = require('mongojs');
const assert = require('assert');
const fs = require('fs');
const async = require('async');

const dburl = config.db;
const db = mongojs(dburl);
const movies = db.collection('movies');

movies.drop()

fs.readFile('config/seed.json', 'utf8', function(err, contents) {
	if(err) console.log(err);
	movies.insert(JSON.parse(contents).data, function(err, docs) {
		if(err)
			console.log(err);
		else {
			console.log('insertion of seed data success.');
			movies.find(function(err, docs) {
				console.log(docs);
			});
		}
	})
});

console.log('running import file');
console.log('db url: ' + dburl);
<commit_msg>introduce async in import<commit_after>const config = require('../config/config');
const mongojs = require('mongojs');
const assert = require('assert');
const fs = require('fs');
const async = require('async');

const dburl = config.db;
const db = mongojs(dburl);
const movies = db.collection('movies');

async.series([
	function(callback) {
		movies.drop(function(err, result) {
			if(err)
				console.log(err);
			else {
				console.log(result);
				console.log('movies collection dropped');
			}
		});
		callback();
	},
	function(callback) {
		fs.readFile('config/seed.json', 'utf8', function(err, contents) {
			if(err) console.log(err);
			movies.insert(JSON.parse(contents).data, function(err, docs) {
				if(err)
					console.log(err);
				else {
					console.log('insertion of seed data success');
				}
				callback();
			})
		});
	},
	function(callback) {
		movies.find(function(err, docs) {
			console.log('movies collection contains the following documents now:');
			console.log(docs);
		});
	}
]);

console.log('running import file');
console.log('db url: ' + dburl);
<|endoftext|>


<commit_before>var Renderer = require('./Renderer.js');
var EventEmitter = require('events');

function errorHandler(msg) {
    throw new Error(msg);
}

function Boo(stream, originalCanvas, filteredCanvas, progressBar) {
    // inherit from EventEmitter
    EventEmitter.call(this);

    this.progressBar = progressBar;
    this.originalRenderer = new Renderer(originalCanvas, errorHandler, null);

    this.filteredRenderer = new Renderer(filteredCanvas, errorHandler, function onStreamReady() {
        // create a muted, invisible video element to stream
        // the camera/mic output to
        this.video = document.createElement('video');
        this.video.style = 'display:none';
        this.video.muted = true;
        this.video.src = window.URL.createObjectURL(stream);
        document.body.appendChild(this.video);
        this.video.play();

        this.video.addEventListener('loadedmetadata', function () {
            var w = this.video.videoWidth;
            var h = this.video.videoHeight;
            this.filteredRenderer.setSize(w, h);
            this.originalRenderer.setSize(w, h);
        }.bind(this));

        this.filteredRenderer.nextEffect();

        this.video.addEventListener('loadeddata', function () {
            this.emit('ready');
            window.requestAnimationFrame(this._tick.bind(this));
            this.canvasStream = filteredCanvas.captureStream(12);
            this.canvasStream.addTrack(this.stream.getAudioTracks()[0]);
            this.recorder = new MediaRecorder(this.canvasStream);
        }.bind(this), false);
    }.bind(this));

    this.stream = stream;
}

// inherit from EventEmitter
Boo.prototype = Object.create(EventEmitter.prototype);
Boo.prototype.constructor = Boo;

Boo.RECORD_TIME = 6; // in seconds

Boo.prototype._tick = function (elapsed) {
    if (this.isRecording) { // update progress bar when recording
        if (!this._started) {
            this._started = elapsed;
        }
        else {
            this.progressBar.value = (elapsed - this._started) / 1000;
        }
    }

    window.requestAnimationFrame(this._tick.bind(this));
    this.originalRenderer.updateTexture(this.video);
    this.filteredRenderer.updateTexture(this.video);
};

Boo.prototype.record = function () {
    this.recorder.start();
    this._started = null;

    this.progressBar.max = Boo.RECORD_TIME;
    this.progressBar.value = 0;

    this.isRecording = true;

    this.recorder.ondataavailable = function (evt) {
        this.emit('finished', evt.data);
    }.bind(this);

    setTimeout(function () {
        this.isRecording = false;
        this.recorder.stop();
        this.progressBar.value = this.progressBar.max;
    }.bind(this), Boo.RECORD_TIME * 1000);
};

Boo.prototype.getVideoEffects = function ()  {
    return this.filteredRenderer.getEffects();
};

Boo.prototype.applyVideoEffect = function (index) {
    this.filteredRenderer.selectEffect(index);
};

// Boo.prototype.render = function () {
//     var width, height, offsetX, offsetY;
//     var ratio = this.video.videoWidth / this.video.videoHeight;
//
//     if (ratio > 0) { // landscape
//         height = this.original.height;
//         width = ratio * this.original.width;
//         offsetX = (this.original.width - width) / 2;
//         offsetY = 0;
//     }
//     else { // portrait
//         width = this.original.width;
//         height = ratio * this.original.height;
//         offsetY = (this.original.height - height) / 2;
//         offsetX = 0;
//     }
//
//     this.ctx.drawImage(
//         this.video,
//         0, 0,
//         this.video.videoWidth, this.video.videoHeight,
//         offsetX, offsetY,
//         width, height);
// };

module.exports = Boo;
<commit_msg>rewrite to use scope variables instead of prototype based objects, fixes issue #17<commit_after>var Renderer = require('./Renderer.js');
var EventEmitter = require('events').EventEmitter;
var util = require('util');

function errorHandler(msg) {
    throw new Error(msg);
}

function Boo(stream, originalCanvas, filteredCanvas, progressBar) {

    var self = this;
    var video;
    var originalRenderer, filteredRenderer;
    var canvasStream;
    var recorder;
    var RECORD_TIME = 6; // in seconds
    var isRecording = false;
    var recordingStartTime;

    EventEmitter.call(this);

    originalRenderer = new Renderer(originalCanvas, errorHandler, null);
    filteredRenderer = new Renderer(filteredCanvas, errorHandler, onStreamReady);

    function onStreamReady() {
        // create a muted, invisible video element to stream
        // the camera/mic output to
        video = document.createElement('video');
        video.style = 'display:none';
        video.muted = true;
        video.src = window.URL.createObjectURL(stream);
        document.body.appendChild(video);
        video.play();

        video.addEventListener('loadedmetadata', function () {
            var w = video.videoWidth;
            var h = video.videoHeight;
            filteredRenderer.setSize(w, h);
            originalRenderer.setSize(w, h);
        });

        filteredRenderer.nextEffect();

        video.addEventListener('loadeddata', function () {
            self.emit('ready');
            requestAnimationFrame(animate);
            canvasStream = filteredCanvas.captureStream(12);
            canvasStream.addTrack(stream.getAudioTracks()[0]);
            recorder = new MediaRecorder(canvasStream);
        });
    }

    function animate(elapsedTime) {

        requestAnimationFrame(animate);

        if (isRecording) { // update progress bar when recording
            if (!recordingStartTime) {
                recordingStartTime = elapsedTime;
            } else {
                progressBar.value = (elapsedTime - recordingStartTime) / 1000;
            }
        }

        originalRenderer.updateTexture(video);
        filteredRenderer.updateTexture(video);
    }

    function onRecordingTimeOver() {
        isRecording = false;
        recorder.stop();
        progressBar.value = progressBar.max;
    }

    this.record = function () {
        recorder.start();
        recordingStartTime = null;

        progressBar.max = RECORD_TIME;
        progressBar.value = 0;

        isRecording = true;

        recorder.ondataavailable = function (evt) {
            self.emit('finished', evt.data);
        };

        setTimeout(onRecordingTimeOver, RECORD_TIME * 1000);
    };

    this.getVideoEffects = function ()  {
        return filteredRenderer.getEffects();
    };

    this.applyVideoEffect = function (index) {
        filteredRenderer.selectEffect(index);
    };

}

util.inherits(Boo, EventEmitter);

module.exports = Boo;
<|endoftext|>


<commit_before>'use strict';

angular.module('app.services', ['restangular']);
angular.module('app.controllers', ['app.services']);

angular.module('app', [
	'ngSanitize',
	'ui.router',
	'ui.bootstrap',
	'ui.tinymce',
	'restangular',
	'localytics.directives',
	'app.filters',
	'app.services',
	'app.directives',
	'app.controllers',
]).config(function(RestangularProvider) {
	RestangularProvider.setBaseUrl('https://api.tnyu.org/v3-test');

	// Configuring Restangular to work with JSONAPI spec
	RestangularProvider.setDefaultHeaders({
		'Accept': 'application/vnd.api+json, application/*, */*',
		'Content-Type': 'application/vnd.api+json'
	});

	RestangularProvider.addResponseInterceptor(function(data, operation, what, url, response, deferred) {
		//console.log("addResponseInterceptor", data, response);
		if ( operation === "remove" ){
			return null;
		}
		return data.data;
	});

	//called before sending any data to the server
	RestangularProvider.addRequestInterceptor(function(data, operation, what, url) {
		if ( operation === "remove" ) {
			return null;
		}
		return {data: data};
	});

	//called after we get a response from the server
	RestangularProvider.addResponseInterceptor(function(data, operation, what, url, response, deferred) {
		//console.log('wee', data, operation, what, url);
		if (operation === "remove"){
			return null;
		}
		var flattenTree = function(resource) {
			var flatten = function(object, parentKey) {
				if (_.isObject(object) && !_.isArray(object)) {
					Object.keys(object).forEach(function(key) {
						flatten(object[key], parentKey + '.' + key);
					});
				} else {
					resource[parentKey] = object;
				}
			};

			Object.keys(resource).forEach(function(key) {
				flatten(resource[key], key);
			});
		};

		if (_.isArray(data)) {
			_.pluck(data, 'attributes').forEach(flattenTree);
		} else {
			flattenTree(data.attributes);
		}
		return data;
	});

	RestangularProvider.addRequestInterceptor(function(data, operation, what, url) {
		// 'deepening' to perform before sending out any request data.
		// This reverses the above flattening process.
		if (operation === 'getList' || operation === 'get') {
			return data;
		}

		_.forOwn(data, function(value, key) {
			var tokens = key.split('.');
			if (tokens.length > 1) {
				var p = data;
				for (var i = 0; i < tokens.length; ++i) {
					var t = tokens[i];
					if (!p[t]) {
						p[t] = {};
					}
					if (i === tokens.length - 1) {
						p[t] = value;
					} else {
						p = p[t];
					}
				}
				delete data[key];
			}
		});
		return data;
	});

}).config(function(datepickerConfig) {
	datepickerConfig.showWeeks = false;
});
<commit_msg>Switch back to production API as v3-test is down<commit_after>'use strict';

angular.module('app.services', ['restangular']);
angular.module('app.controllers', ['app.services']);

angular.module('app', [
	'ngSanitize',
	'ui.router',
	'ui.bootstrap',
	'ui.tinymce',
	'restangular',
	'localytics.directives',
	'app.filters',
	'app.services',
	'app.directives',
	'app.controllers',
]).config(function(RestangularProvider) {
	RestangularProvider.setBaseUrl('https://api.tnyu.org/v3');

	// Configuring Restangular to work with JSONAPI spec
	RestangularProvider.setDefaultHeaders({
		'Accept': 'application/vnd.api+json, application/*, */*',
		'Content-Type': 'application/vnd.api+json'
	});

	RestangularProvider.addResponseInterceptor(function(data, operation, what, url, response, deferred) {
		//console.log("addResponseInterceptor", data, response);
		if ( operation === "remove" ){
			return null;
		}
		return data.data;
	});

	//called before sending any data to the server
	RestangularProvider.addRequestInterceptor(function(data, operation, what, url) {
		if ( operation === "remove" ) {
			return null;
		}
		return {data: data};
	});

	//called after we get a response from the server
	RestangularProvider.addResponseInterceptor(function(data, operation, what, url, response, deferred) {
		//console.log('wee', data, operation, what, url);
		if (operation === "remove"){
			return null;
		}
		var flattenTree = function(resource) {
			var flatten = function(object, parentKey) {
				if (_.isObject(object) && !_.isArray(object)) {
					Object.keys(object).forEach(function(key) {
						flatten(object[key], parentKey + '.' + key);
					});
				} else {
					resource[parentKey] = object;
				}
			};

			Object.keys(resource).forEach(function(key) {
				flatten(resource[key], key);
			});
		};

		if (_.isArray(data)) {
			_.pluck(data, 'attributes').forEach(flattenTree);
		} else {
			flattenTree(data.attributes);
		}
		return data;
	});

	RestangularProvider.addRequestInterceptor(function(data, operation, what, url) {
		// 'deepening' to perform before sending out any request data.
		// This reverses the above flattening process.
		if (operation === 'getList' || operation === 'get') {
			return data;
		}

		_.forOwn(data, function(value, key) {
			var tokens = key.split('.');
			if (tokens.length > 1) {
				var p = data;
				for (var i = 0; i < tokens.length; ++i) {
					var t = tokens[i];
					if (!p[t]) {
						p[t] = {};
					}
					if (i === tokens.length - 1) {
						p[t] = value;
					} else {
						p = p[t];
					}
				}
				delete data[key];
			}
		});
		return data;
	});

}).config(function(datepickerConfig) {
	datepickerConfig.showWeeks = false;
});
<|endoftext|>