<commit_before>import React, {Component} from 'react';

import RaisedButton from 'dist/RaisedButton';
import Menu from 'dist/Menu';
import List from 'dist/List';
import Theme from 'dist/Theme';
import Widget from 'dist/Widget';
import WidgetHeader from 'dist/WidgetHeader';

import PropTypeDescTable from '../PropTypeDescTable';
import MenuDoc from 'assets/propTypes/MenuBody.json';

import 'sass/containers/app/modules/popup/PopupExamples.scss';

export default class MenuExamples extends Component {

    constructor(props) {

        super(props);

        this.state = {
            menuVisible1: false,
            menuVisible2: false,
            menuVisible3: false,
            menuVisible4: false,
            menuVisible5: false,
            menuVisible6: false,
            menuVisible7: false,
            menuVisible8: false,
            menuVisible9: false,
            menuVisible10: false,
            menuVisible11: false,
            menuVisible12: false,
            menuVisible13: false,
            menuVisible14: false,
            menuVisible15: false,
            triggerEl1: null,
            triggerEl2: null,
            triggerEl3: null,
            triggerEl4: null,
            triggerEl5: null,
            triggerEl6: null,
            triggerEl7: null,
            triggerEl8: null,
            triggerEl9: null,
            triggerEl10: null,
            triggerEl11: null,
            triggerEl12: null,
            triggerEl13: null,
            triggerEl14: null,
            triggerEl15: null
        };

        this.showMenu = this::this.showMenu;
        this.hideMenu = this::this.hideMenu;

    }

    showMenu(e, id) {
        this.setState({
            [`menuVisible${id}`]: true,
            [`triggerEl${id}`]: e.currentTarget
        });
    }

    hideMenu(id) {
        this.setState({
            [`menuVisible${id}`]: false
        });
    }

    render() {

        const {
                menuVisible1, menuVisible3, menuVisible4, menuVisible5, menuVisible6,
                menuVisible7, menuVisible8, menuVisible9, menuVisible10, menuVisible11, menuVisible12,
                menuVisible13, menuVisible14, menuVisible15,
                triggerEl1, triggerEl3, triggerEl4, triggerEl5, triggerEl6,
                triggerEl7, triggerEl8, triggerEl9, triggerEl10, triggerEl11, triggerEl12
                , triggerEl13, triggerEl14, triggerEl15
            } = this.state,
            items = [{
                iconCls: 'fa fa-facebook',
                text: 'Facebook',
                theme: Theme.PRIMARY
            }, {
                iconCls: 'fa fa-twitter',
                text: 'Twitter',
                theme: Theme.PRIMARY
            }, {
                iconCls: 'fa fa-google-plus',
                text: 'Google+',
                theme: Theme.PRIMARY
            }];

        return (

Menu

                    A Menu can be used as an alternative to a Drop Down Menu that can contain elements
                    inside.

Examples

                <Widget>

                    <WidgetHeader className="example-header"
                                  title="Basic"/>

Menu simple example.

                                <RaisedButton className="trigger-button"
                                              value="Toggle Menu"
                                              onMouseEnter={(e) => {
                                                  this.showMenu(e, 1);
                                              }}/>

                                <Menu visible={menuVisible1}
                                      triggerEl={triggerEl1}
                                      onRequestClose={() => {
                                          this.hideMenu(1);
                                      }}>

                                        Menu

                                </Menu>

                </Widget>

                <Widget>

                    <WidgetHeader className="example-header"
                                  title="Without triangle"/>

                                    Set hasTriangle to false,the popover will have
                                    no triangle on the top of the DOM element.

                                <RaisedButton className="trigger-button"
                                              value="Toggle Menu"
                                              onMouseEnter={(e) => {
                                                  this.showMenu(e, 3);
                                              }}/>

                                <Menu visible={menuVisible3}
                                      triggerEl={triggerEl3}
                                      hasTriangle={false}
                                      onRequestClose={() => {
                                          this.hideMenu(3);
                                      }}>
                                    <List items={items}/>
                                </Menu>

                </Widget>

                <Widget>

                    <WidgetHeader className="example-header"
                                  title="With value"/>

                                    Set the value property to show different position of Menu.

                                        <RaisedButton className="trigger-position-button"
                                                      value="Top Left"
                                                      onMouseEnter={(e) => {
                                                          this.showMenu(e, 7);
                                                      }}/>
                                        <RaisedButton className="trigger-position-button"
                                                      value="Top"
                                                      onMouseEnter={(e) => {
                                                          this.showMenu(e, 8);
                                                      }}/>
                                        <RaisedButton className="trigger-position-button"
                                                      value="Top right"
                                                      onMouseEnter={(e) => {
                                                          this.showMenu(e, 9);
                                                      }}/>

                                        <RaisedButton className="trigger-position-button"
                                                      value="Right Top"
                                                      onMouseEnter={(e) => {
                                                          this.showMenu(e, 13);
                                                      }}/>
                                        <RaisedButton className="trigger-position-button"
                                                      value="Right"
                                                      onMouseEnter={(e) => {
                                                          this.showMenu(e, 14);
                                                      }}/>
                                        <RaisedButton className="trigger-position-button"
                                                      value="Right Bottom"
                                                      onMouseEnter={(e) => {
                                                          this.showMenu(e, 15);
                                                      }}/>

                                        <RaisedButton className="trigger-position-button"
                                                      value="Bottom Left"
                                                      onMouseEnter={(e) => {
                                                          this.showMenu(e, 4);
                                                      }}/>
                                        <RaisedButton className="trigger-position-button"
                                                      value="Bottom"
                                                      onMouseEnter={(e) => {
                                                          this.showMenu(e, 5);
                                                      }}/>
                                        <RaisedButton className="trigger-position-button"
                                                      value="Bottom Right"
                                                      onMouseEnter={(e) => {
                                                          this.showMenu(e, 6);
                                                      }}/>

                                        <RaisedButton className="trigger-position-button"
                                                      value="Left Top"
                                                      onMouseEnter={(e) => {
                                                          this.showMenu(e, 10);
                                                      }}/>
                                        <RaisedButton className="trigger-position-button"
                                                      value="Left"
                                                      onMouseEnter={(e) => {
                                                          this.showMenu(e, 11);
                                                      }}/>
                                        <RaisedButton className="trigger-position-button"
                                                      value="Left Bottom"
                                                      onMouseEnter={(e) => {
                                                          this.showMenu(e, 12);
                                                      }}/>

                                <Menu visible={menuVisible4}
                                      triggerEl={triggerEl4}
                                      theme={Theme.PRIMARY}
                                      position={Menu.Position.BOTTOM_LEFT}
                                      onRequestClose={() => {
                                          this.hideMenu(4);
                                      }}>
                                    <List items={items}/>
                                </Menu>
                                <Menu visible={menuVisible5}
                                      triggerEl={triggerEl5}
                                      theme={Theme.PRIMARY}
                                      position={Menu.Position.BOTTOM}
                                      onRequestClose={() => {
                                          this.hideMenu(5);
                                      }}>
                                    <List items={items}/>
                                </Menu>
                                <Menu visible={menuVisible6}
                                      triggerEl={triggerEl6}
                                      theme={Theme.PRIMARY}
                                      position={Menu.Position.BOTTOM_RIGHT}
                                      onRequestClose={() => {
                                          this.hideMenu(6);
                                      }}>
                                    <List items={items}/>
                                </Menu>

                                <Menu visible={menuVisible7}
                                      triggerEl={triggerEl7}
                                      theme={Theme.PRIMARY}
                                      position={Menu.Position.TOP_LEFT}
                                      onRequestClose={() => {
                                          this.hideMenu(7);
                                      }}>
                                    <List items={items}/>
                                </Menu>
                                <Menu visible={menuVisible8}
                                      triggerEl={triggerEl8}
                                      theme={Theme.PRIMARY}
                                      position={Menu.Position.TOP}
                                      onRequestClose={() => {
                                          this.hideMenu(8);
                                      }}>
                                    <List items={items}/>
                                </Menu>
                                <Menu visible={menuVisible9}
                                      triggerEl={triggerEl9}
                                      theme={Theme.PRIMARY}
                                      position={Menu.Position.TOP_RIGHT}
                                      onRequestClose={() => {
                                          this.hideMenu(9);
                                      }}>
                                    <List items={items}/>
                                </Menu>

                                <Menu visible={menuVisible10}
                                      triggerEl={triggerEl10}
                                      theme={Theme.PRIMARY}
                                      position={Menu.Position.LEFT_TOP}
                                      onRequestClose={() => {
                                          this.hideMenu(10);
                                      }}>
                                    <List items={items}/>
                                </Menu>
                                <Menu visible={menuVisible11}
                                      triggerEl={triggerEl11}
                                      theme={Theme.PRIMARY}
                                      position={Menu.Position.LEFT}
                                      onRequestClose={() => {
                                          this.hideMenu(11);
                                      }}>
                                    <List items={items}/>
                                </Menu>
                                <Menu visible={menuVisible12}
                                      triggerEl={triggerEl12}
                                      theme={Theme.PRIMARY}
                                      position={Menu.Position.LEFT_BOTTOM}
                                      onRequestClose={() => {
                                          this.hideMenu(12);
                                      }}>
                                    <List items={items}/>
                                </Menu>

                                <Menu visible={menuVisible13}
                                      triggerEl={triggerEl13}
                                      theme={Theme.PRIMARY}
                                      position={Menu.Position.RIGHT_TOP}
                                      onRequestClose={() => {
                                          this.hideMenu(13);
                                      }}>
                                    <List items={items}/>
                                </Menu>
                                <Menu visible={menuVisible14}
                                      triggerEl={triggerEl14}
                                      theme={Theme.PRIMARY}
                                      position={Menu.Position.RIGHT}
                                      onRequestClose={() => {
                                          this.hideMenu(14);
                                      }}>
                                    <List items={items}/>
                                </Menu>
                                <Menu visible={menuVisible15}
                                      triggerEl={triggerEl15}
                                      theme={Theme.PRIMARY}
                                      position={Menu.Position.RIGHT_BOTTOM}
                                      onRequestClose={() => {
                                          this.hideMenu(15);
                                      }}>
                                    <List items={items}/>
                                </Menu>

                </Widget>

Properties

                <PropTypeDescTable data={MenuDoc}/>

        );
    }
};<commit_msg>update Menu examples<commit_after>import React, {Component} from 'react';

import RaisedButton from 'dist/RaisedButton';
import Menu from 'dist/Menu';
import List from 'dist/List';
import Theme from 'dist/Theme';
import Widget from 'dist/Widget';
import WidgetHeader from 'dist/WidgetHeader';

import PropTypeDescTable from '../PropTypeDescTable';
import MenuDoc from 'assets/propTypes/MenuBody.json';

import 'sass/containers/app/modules/popup/PopupExamples.scss';

export default class MenuExamples extends Component {

    constructor(props) {

        super(props);

        this.state = {
            menuVisible1: false,
            menuVisible2: false,
            menuVisible3: false,
            menuVisible4: false,
            menuVisible5: false,
            menuVisible6: false,
            menuVisible7: false,
            menuVisible8: false,
            menuVisible9: false,
            menuVisible10: false,
            menuVisible11: false,
            menuVisible12: false,
            menuVisible13: false,
            menuVisible14: false,
            menuVisible15: false,
            triggerEl1: null,
            triggerEl2: null,
            triggerEl3: null,
            triggerEl4: null,
            triggerEl5: null,
            triggerEl6: null,
            triggerEl7: null,
            triggerEl8: null,
            triggerEl9: null,
            triggerEl10: null,
            triggerEl11: null,
            triggerEl12: null,
            triggerEl13: null,
            triggerEl14: null,
            triggerEl15: null
        };

        this.showMenu = this::this.showMenu;
        this.hideMenu = this::this.hideMenu;

    }

    showMenu(e, id) {
        this.setState({
            [`menuVisible${id}`]: true,
            [`triggerEl${id}`]: e.currentTarget
        });
    }

    hideMenu(id) {
        this.setState({
            [`menuVisible${id}`]: false
        });
    }

    render() {

        const {
                menuVisible1, menuVisible3, menuVisible4, menuVisible5, menuVisible6,
                menuVisible7, menuVisible8, menuVisible9, menuVisible10, menuVisible11, menuVisible12,
                menuVisible13, menuVisible14, menuVisible15,
                triggerEl1, triggerEl3, triggerEl4, triggerEl5, triggerEl6,
                triggerEl7, triggerEl8, triggerEl9, triggerEl10, triggerEl11, triggerEl12
                , triggerEl13, triggerEl14, triggerEl15
            } = this.state,
            items = [{
                iconCls: 'fa fa-facebook',
                text: 'Facebook'
            }, {
                iconCls: 'fa fa-twitter',
                text: 'Twitter'
            }, {
                iconCls: 'fa fa-google-plus',
                text: 'Google+'
            }];

        return (

Menu

                    A Menu can be used as an alternative to a Drop Down Menu that can contain elements
                    inside.

Examples

                <Widget>

                    <WidgetHeader className="example-header"
                                  title="Basic"/>

Menu simple example.

                                <RaisedButton className="trigger-button"
                                              value="Toggle Menu"
                                              onMouseEnter={(e) => {
                                                  this.showMenu(e, 1);
                                              }}/>

                                <Menu theme={Theme.PRIMARY}
                                      visible={menuVisible1}
                                      triggerEl={triggerEl1}
                                      onRequestClose={() => {
                                          this.hideMenu(1);
                                      }}>

                                        Menu

                                </Menu>

                </Widget>

                <Widget>

                    <WidgetHeader className="example-header"
                                  title="Without triangle"/>

                                    Set hasTriangle to false,the popover will have
                                    no triangle on the top of the DOM element.

                                <RaisedButton className="trigger-button"
                                              value="Toggle Menu"
                                              onMouseEnter={(e) => {
                                                  this.showMenu(e, 3);
                                              }}/>

                                <Menu visible={menuVisible3}
                                      triggerEl={triggerEl3}
                                      hasTriangle={false}
                                      onRequestClose={() => {
                                          this.hideMenu(3);
                                      }}>
                                    <List items={items}/>
                                </Menu>

                </Widget>

                <Widget>

                    <WidgetHeader className="example-header"
                                  title="With value"/>

                                    Set the value property to show different position of Menu.

                                        <RaisedButton className="trigger-position-button"
                                                      value="Top Left"
                                                      onMouseEnter={(e) => {
                                                          this.showMenu(e, 7);
                                                      }}/>
                                        <RaisedButton className="trigger-position-button"
                                                      value="Top"
                                                      onMouseEnter={(e) => {
                                                          this.showMenu(e, 8);
                                                      }}/>
                                        <RaisedButton className="trigger-position-button"
                                                      value="Top right"
                                                      onMouseEnter={(e) => {
                                                          this.showMenu(e, 9);
                                                      }}/>

                                        <RaisedButton className="trigger-position-button"
                                                      value="Right Top"
                                                      onMouseEnter={(e) => {
                                                          this.showMenu(e, 13);
                                                      }}/>
                                        <RaisedButton className="trigger-position-button"
                                                      value="Right"
                                                      onMouseEnter={(e) => {
                                                          this.showMenu(e, 14);
                                                      }}/>
                                        <RaisedButton className="trigger-position-button"
                                                      value="Right Bottom"
                                                      onMouseEnter={(e) => {
                                                          this.showMenu(e, 15);
                                                      }}/>

                                        <RaisedButton className="trigger-position-button"
                                                      value="Bottom Left"
                                                      onMouseEnter={(e) => {
                                                          this.showMenu(e, 4);
                                                      }}/>
                                        <RaisedButton className="trigger-position-button"
                                                      value="Bottom"
                                                      onMouseEnter={(e) => {
                                                          this.showMenu(e, 5);
                                                      }}/>
                                        <RaisedButton className="trigger-position-button"
                                                      value="Bottom Right"
                                                      onMouseEnter={(e) => {
                                                          this.showMenu(e, 6);
                                                      }}/>

                                        <RaisedButton className="trigger-position-button"
                                                      value="Left Top"
                                                      onMouseEnter={(e) => {
                                                          this.showMenu(e, 10);
                                                      }}/>
                                        <RaisedButton className="trigger-position-button"
                                                      value="Left"
                                                      onMouseEnter={(e) => {
                                                          this.showMenu(e, 11);
                                                      }}/>
                                        <RaisedButton className="trigger-position-button"
                                                      value="Left Bottom"
                                                      onMouseEnter={(e) => {
                                                          this.showMenu(e, 12);
                                                      }}/>

                                <Menu visible={menuVisible4}
                                      triggerEl={triggerEl4}
                                      position={Menu.Position.BOTTOM_LEFT}
                                      onRequestClose={() => {
                                          this.hideMenu(4);
                                      }}>
                                    <List items={items}/>
                                </Menu>
                                <Menu visible={menuVisible5}
                                      triggerEl={triggerEl5}
                                      position={Menu.Position.BOTTOM}
                                      onRequestClose={() => {
                                          this.hideMenu(5);
                                      }}>
                                    <List items={items}/>
                                </Menu>
                                <Menu visible={menuVisible6}
                                      triggerEl={triggerEl6}
                                      position={Menu.Position.BOTTOM_RIGHT}
                                      onRequestClose={() => {
                                          this.hideMenu(6);
                                      }}>
                                    <List items={items}/>
                                </Menu>

                                <Menu visible={menuVisible7}
                                      triggerEl={triggerEl7}
                                      position={Menu.Position.TOP_LEFT}
                                      onRequestClose={() => {
                                          this.hideMenu(7);
                                      }}>
                                    <List items={items}/>
                                </Menu>
                                <Menu visible={menuVisible8}
                                      triggerEl={triggerEl8}
                                      position={Menu.Position.TOP}
                                      onRequestClose={() => {
                                          this.hideMenu(8);
                                      }}>
                                    <List items={items}/>
                                </Menu>
                                <Menu visible={menuVisible9}
                                      triggerEl={triggerEl9}
                                      position={Menu.Position.TOP_RIGHT}
                                      onRequestClose={() => {
                                          this.hideMenu(9);
                                      }}>
                                    <List items={items}/>
                                </Menu>

                                <Menu visible={menuVisible10}
                                      triggerEl={triggerEl10}
                                      position={Menu.Position.LEFT_TOP}
                                      onRequestClose={() => {
                                          this.hideMenu(10);
                                      }}>
                                    <List items={items}/>
                                </Menu>
                                <Menu visible={menuVisible11}
                                      triggerEl={triggerEl11}
                                      position={Menu.Position.LEFT}
                                      onRequestClose={() => {
                                          this.hideMenu(11);
                                      }}>
                                    <List items={items}/>
                                </Menu>
                                <Menu visible={menuVisible12}
                                      triggerEl={triggerEl12}
                                      position={Menu.Position.LEFT_BOTTOM}
                                      onRequestClose={() => {
                                          this.hideMenu(12);
                                      }}>
                                    <List items={items}/>
                                </Menu>

                                <Menu visible={menuVisible13}
                                      triggerEl={triggerEl13}
                                      position={Menu.Position.RIGHT_TOP}
                                      onRequestClose={() => {
                                          this.hideMenu(13);
                                      }}>
                                    <List items={items}/>
                                </Menu>
                                <Menu visible={menuVisible14}
                                      triggerEl={triggerEl14}
                                      position={Menu.Position.RIGHT}
                                      onRequestClose={() => {
                                          this.hideMenu(14);
                                      }}>
                                    <List items={items}/>
                                </Menu>
                                <Menu visible={menuVisible15}
                                      triggerEl={triggerEl15}
                                      position={Menu.Position.RIGHT_BOTTOM}
                                      onRequestClose={() => {
                                          this.hideMenu(15);
                                      }}>
                                    <List items={items}/>
                                </Menu>

                </Widget>

Properties

                <PropTypeDescTable data={MenuDoc}/>

        );
    }
};<|endoftext|>


<commit_before>/*globals COURSES:true */
import React from 'react'
import Dashboard from './Dashboard'
import Nav from './Nav'

const styles = {}

styles.sidebar = {
  float: 'left',
  width: 200,
  padding: 20,
  borderRight: '1px solid #aaa',
  marginRight: 20
}

class Course extends React.Component {
  render() {
    let { sidebar, main, params } = this.props
    let course = COURSES[params.courseId]

    return (

{course.name}

        {sidebar && main ? (

              {sidebar}

              {main}

        ) : (
          <Dashboard />
        )}

    )
  }
}

module.exports = Course
<commit_msg>Fix /course/:courseId/grades<commit_after>/*globals COURSES:true */
import React from 'react'
import Dashboard from './Dashboard'
import Nav from './Nav'

const styles = {}

styles.sidebar = {
  float: 'left',
  width: 200,
  padding: 20,
  borderRight: '1px solid #aaa',
  marginRight: 20
}

class Course extends React.Component {
  render() {
    let { sidebar, main, children, params } = this.props
    let course = COURSES[params.courseId]

    let content
    if (sidebar && main) {
      content = (

            {sidebar}

            {main}

      )
    } else if (children) {
      content = children
    } else {
      content = <Dashboard />
    }

    return (

{course.name}

        {content}

    )
  }
}

module.exports = Course
<|endoftext|>


<commit_before>const GH_RESERVED_USER_NAMES = [
  'settings', 'orgs', 'organizations',
  'site', 'blog', 'about', 'explore',
  'styleguide', 'showcases', 'trending',
  'stars', 'dashboard', 'notifications',
  'search', 'developer', 'account',
  'pulls', 'issues', 'features', 'contact',
  'security', 'join', 'login', 'watching',
  'new', 'integrations', 'gist', 'business',
  'mirrors', 'open-source', 'personal',
  'pricing'
]
const GH_RESERVED_REPO_NAMES = ['followers', 'following', 'repositories']
const GH_404_SEL = '#parallax_wrapper'
const GH_PJAX_CONTAINER_SEL = '#js-repo-pjax-container, .context-loader-container, [data-pjax-container]'
const GH_CONTAINERS = '.container, .container-responsive'
const GH_RAW_CONTENT = 'body > pre'

class GitHub extends Adapter {

  constructor() {
    super(['jquery.pjax.js'])

    $.pjax.defaults.timeout = 0 // no timeout
    $(document)
      .on('pjax:send', () => $(document).trigger(EVENT.REQ_START))
      .on('pjax:end', () => $(document).trigger(EVENT.REQ_END))
  }

  // @override
  init($sidebar) {
    super.init($sidebar)

    if (!window.MutationObserver) return

    // Fix #151 by detecting when page layout is updated.
    // In this case, split-diff page has a wider layout, so need to recompute margin.
    // Note that couldn't do this in response to URL change, since new DOM via pjax might not be ready.
    const diffModeObserver = new window.MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        if (~mutation.oldValue.indexOf('split-diff') ||
            ~mutation.target.className.indexOf('split-diff')) {
          return $(document).trigger(EVENT.LAYOUT_CHANGE)
        }
      })
    })

    diffModeObserver.observe(document.body, {
      attributes: true,
      attributeFilter: ['class'],
      attributeOldValue: true
    })

    // GitHub switch pages using pjax. This observer detects if the pjax container
    // has been updated with new contents and trigger layout.
    const pageChangeObserver = new window.MutationObserver(() => {
      // Trigger location change, can't just relayout as Octotree might need to
      // hide/show depending on whether the current page is a code page or not.
      return $(document).trigger(EVENT.LOC_CHANGE)
    })

    const pjaxContainer = $(GH_PJAX_CONTAINER_SEL)[0]

    if (pjaxContainer) {
      pageChangeObserver.observe(pjaxContainer, {
        childList: true,
      })
    }
    else { // Fall back if DOM has been changed
      let firstLoad = true, href, hash

      function detectLocChange() {
        if (location.href !== href || location.hash !== hash) {
          href = location.href
          hash = location.hash

          // If this is the first time this is called, no need to notify change as
          // Octotree does its own initialization after loading options.
          if (firstLoad) {
            firstLoad = false
          }
          else {
            setTimeout(() => {
              $(document).trigger(EVENT.LOC_CHANGE)
            }, 300) // Wait a bit for pjax DOM change
          }
        }
        setTimeout(detectLocChange, 200)
      }

      detectLocChange()
    }
  }

  // @override
  getCssClass() {
    return 'octotree_github_sidebar'
  }

  // @override
  canLoadEntireTree() {
    return true
  }

  // @override
  getCreateTokenUrl() {
    return `${location.protocol}//${location.host}/settings/tokens/new`
  }

  // @override
  updateLayout(togglerVisible, sidebarVisible, sidebarWidth) {
    const SPACING = 10
    const $containers = $(GH_CONTAINERS)
    const autoMarginLeft = ($(document).width() - $containers.width()) / 2
    const shouldPushLeft = sidebarVisible && (autoMarginLeft <= sidebarWidth + SPACING)

    $('html').css('margin-left', shouldPushLeft ? sidebarWidth : '')
    $containers.css('margin-left', shouldPushLeft ? SPACING : '')
  }

  // @override
  getRepoFromPath(showInNonCodePage, currentRepo, token, cb) {

    // 404 page, skip
    if ($(GH_404_SEL).length) {
      return cb()
    }

    // Skip raw page
    if ($(GH_RAW_CONTENT).length) {
      return cb()
    }

    // (username)/(reponame)[/(type)]
    const match = window.location.pathname.match(/([^\/]+)\/([^\/]+)(?:\/([^\/]+))?/)
    if (!match) {
      return cb()
    }

    const username = match[1]
    const reponame = match[2]

    // Not a repository, skip
    if (~GH_RESERVED_USER_NAMES.indexOf(username) ||
        ~GH_RESERVED_REPO_NAMES.indexOf(reponame)) {
      return cb()
    }

    // Skip non-code page unless showInNonCodePage is true
    if (!showInNonCodePage && match[3] && !~['tree', 'blob'].indexOf(match[3])) {
      return cb()
    }

    // Get branch by inspecting page, quite fragile so provide multiple fallbacks
    const GH_BRANCH_SEL_1 = '[aria-label="Switch branches or tags"]'
    const GH_BRANCH_SEL_2 = '.repo-root a[data-branch]'
    const GH_BRANCH_SEL_3 = '.repository-sidebar a[aria-label="Code"]'
    const GH_BRANCH_SEL_4 = '.current-branch'
    const GH_BRANCH_SEL_5 = 'link[title*="Recent Commits to"]'

    const branch =
      // Detect branch in code page
      $(GH_BRANCH_SEL_1).attr('title') || $(GH_BRANCH_SEL_2).data('branch') ||
      // Non-code page (old GH design)
      ($(GH_BRANCH_SEL_3).attr('href') || ' ').match(/([^\/]+)/g)[3] ||
      // Non-code page: commit page
      ($(GH_BRANCH_SEL_4).attr('title') || ' ').match(/([^\:]+)/g)[1] ||
      // Non-code page: others
      ($(GH_BRANCH_SEL_5).length === 1 && ($(GH_BRANCH_SEL_5).attr('title') || ' ').match(/([^\:]+)/g)[1]) ||

      // Reuse last selected branch if exist
      (currentRepo.username === username && currentRepo.reponame === reponame && currentRepo.branch) ||
      // Get default branch from cache
      this._defaultBranch[username + '/' + reponame]

    // Still no luck, get default branch for real
    const repo = {username: username, reponame: reponame, branch: branch}

    if (repo.branch) {
      cb(null, repo)
    }
    else {
      this._get(null, {repo, token}, (err, data) => {
        if (err) return cb(err)
        repo.branch = this._defaultBranch[username + '/' + reponame] = data.default_branch || 'master'
        cb(null, repo)
      })
    }
  }

  // @override
  selectFile(path) {
    const $pjaxContainer = $(GH_PJAX_CONTAINER_SEL)

    if ($pjaxContainer.length) {
      $.pjax({
        // needs full path for pjax to work with Firefox as per cross-domain-content setting
        url: location.protocol + '//' + location.host + path,
        container: $pjaxContainer
      })
    }
    else { // falls back
      super.selectFile(path)
    }
  }

  // @override
  loadCodeTree(opts, cb) {
    opts.encodedBranch = encodeURIComponent(decodeURIComponent(opts.repo.branch))
    opts.path = (opts.node && (opts.node.sha || opts.encodedBranch)) ||
                (opts.encodedBranch + '?recursive=1')
    this._loadCodeTree(opts, null, cb)
  }

  // @override
  _getTree(path, opts, cb) {
    this._get(`/git/trees/${path}`, opts, (err, res) => {
      if (err) cb(err)
      else cb(null, res.tree)
    })
  }

  // @override
  _getSubmodules(tree, opts, cb) {
    const item = tree.filter((item) => /^\.gitmodules$/i.test(item.path))[0]
    if (!item) return cb()

    this._get(`/git/blobs/${item.sha}`, opts, (err, res) => {
      if (err) return cb(err)
      const data = atob(res.content.replace(/\n/g,''))
      cb(null, parseGitmodules(data))
    })
  }

  _get(path, opts, cb) {
    const host = location.protocol + '//' +
      (location.host === 'github.com' ? 'api.github.com' : (location.host + '/api/v3'))
    const url = `${host}/repos/${opts.repo.username}/${opts.repo.reponame}${path || ''}`
    const cfg  = { url, method: 'GET', cache: false }

    if (opts.token) {
      cfg.headers = { Authorization: 'token ' + opts.token }
    }

    $.ajax(cfg)
      .done((data) => {
        if (path && path.indexOf('/git/trees') === 0 && data.truncated) {
          this._handleError({status: 206}, cb)
        }
        else cb(null, data)
      })
      .fail((jqXHR) => this._handleError(jqXHR, cb))
  }
}
<commit_msg>Github has changed their DOM (#359)<commit_after>const GH_RESERVED_USER_NAMES = [
  'settings', 'orgs', 'organizations',
  'site', 'blog', 'about', 'explore',
  'styleguide', 'showcases', 'trending',
  'stars', 'dashboard', 'notifications',
  'search', 'developer', 'account',
  'pulls', 'issues', 'features', 'contact',
  'security', 'join', 'login', 'watching',
  'new', 'integrations', 'gist', 'business',
  'mirrors', 'open-source', 'personal',
  'pricing'
]
const GH_RESERVED_REPO_NAMES = ['followers', 'following', 'repositories']
const GH_404_SEL = '#parallax_wrapper'
const GH_PJAX_CONTAINER_SEL = '#js-repo-pjax-container, .context-loader-container, [data-pjax-container]'
const GH_CONTAINERS = '.container, .container-responsive'
const GH_RAW_CONTENT = 'body > pre'

class GitHub extends Adapter {

  constructor() {
    super(['jquery.pjax.js'])

    $.pjax.defaults.timeout = 0 // no timeout
    $(document)
      .on('pjax:send', () => $(document).trigger(EVENT.REQ_START))
      .on('pjax:end', () => $(document).trigger(EVENT.REQ_END))
  }

  // @override
  init($sidebar) {
    super.init($sidebar)

    if (!window.MutationObserver) return

    // Fix #151 by detecting when page layout is updated.
    // In this case, split-diff page has a wider layout, so need to recompute margin.
    // Note that couldn't do this in response to URL change, since new DOM via pjax might not be ready.
    const diffModeObserver = new window.MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        if (~mutation.oldValue.indexOf('split-diff') ||
            ~mutation.target.className.indexOf('split-diff')) {
          return $(document).trigger(EVENT.LAYOUT_CHANGE)
        }
      })
    })

    diffModeObserver.observe(document.body, {
      attributes: true,
      attributeFilter: ['class'],
      attributeOldValue: true
    })

    // GitHub switch pages using pjax. This observer detects if the pjax container
    // has been updated with new contents and trigger layout.
    const pageChangeObserver = new window.MutationObserver(() => {
      // Trigger location change, can't just relayout as Octotree might need to
      // hide/show depending on whether the current page is a code page or not.
      return $(document).trigger(EVENT.LOC_CHANGE)
    })

    const pjaxContainer = $(GH_PJAX_CONTAINER_SEL)[0]

    if (pjaxContainer) {
      pageChangeObserver.observe(pjaxContainer, {
        childList: true,
      })
    }
    else { // Fall back if DOM has been changed
      let firstLoad = true, href, hash

      function detectLocChange() {
        if (location.href !== href || location.hash !== hash) {
          href = location.href
          hash = location.hash

          // If this is the first time this is called, no need to notify change as
          // Octotree does its own initialization after loading options.
          if (firstLoad) {
            firstLoad = false
          }
          else {
            setTimeout(() => {
              $(document).trigger(EVENT.LOC_CHANGE)
            }, 300) // Wait a bit for pjax DOM change
          }
        }
        setTimeout(detectLocChange, 200)
      }

      detectLocChange()
    }
  }

  // @override
  getCssClass() {
    return 'octotree_github_sidebar'
  }

  // @override
  canLoadEntireTree() {
    return true
  }

  // @override
  getCreateTokenUrl() {
    return `${location.protocol}//${location.host}/settings/tokens/new`
  }

  // @override
  updateLayout(togglerVisible, sidebarVisible, sidebarWidth) {
    const SPACING = 10
    const $containers = $(GH_CONTAINERS)
    const autoMarginLeft = ($(document).width() - $containers.width()) / 2
    const shouldPushLeft = sidebarVisible && (autoMarginLeft <= sidebarWidth + SPACING)

    $('html').css('margin-left', shouldPushLeft ? sidebarWidth : '')
    $containers.css('margin-left', shouldPushLeft ? SPACING : '')
  }

  // @override
  getRepoFromPath(showInNonCodePage, currentRepo, token, cb) {

    // 404 page, skip
    if ($(GH_404_SEL).length) {
      return cb()
    }

    // Skip raw page
    if ($(GH_RAW_CONTENT).length) {
      return cb()
    }

    // (username)/(reponame)[/(type)]
    const match = window.location.pathname.match(/([^\/]+)\/([^\/]+)(?:\/([^\/]+))?/)
    if (!match) {
      return cb()
    }

    const username = match[1]
    const reponame = match[2]

    // Not a repository, skip
    if (~GH_RESERVED_USER_NAMES.indexOf(username) ||
        ~GH_RESERVED_REPO_NAMES.indexOf(reponame)) {
      return cb()
    }

    // Skip non-code page unless showInNonCodePage is true
    if (!showInNonCodePage && match[3] && !~['tree', 'blob'].indexOf(match[3])) {
      return cb()
    }

    // Get branch by inspecting page, quite fragile so provide multiple fallbacks
    const GH_BRANCH_SEL_1 = '[aria-label="Switch branches or tags"] .css-truncate-target'
    const GH_BRANCH_SEL_2 = '.repo-root a[data-branch]'
    const GH_BRANCH_SEL_3 = '.repository-sidebar a[aria-label="Code"]'
    const GH_BRANCH_SEL_4 = '.current-branch'
    const GH_BRANCH_SEL_5 = 'link[title*="Recent Commits to"]'

    const branch =
      // Detect branch in code page
      $(GH_BRANCH_SEL_1).text() || $(GH_BRANCH_SEL_2).data('branch') ||
      // Non-code page (old GH design)
      ($(GH_BRANCH_SEL_3).attr('href') || ' ').match(/([^\/]+)/g)[3] ||
      // Non-code page: commit page
      ($(GH_BRANCH_SEL_4).attr('title') || ' ').match(/([^\:]+)/g)[1] ||
      // Non-code page: others
      ($(GH_BRANCH_SEL_5).length === 1 && ($(GH_BRANCH_SEL_5).attr('title') || ' ').match(/([^\:]+)/g)[1]) ||

      // Reuse last selected branch if exist
      (currentRepo.username === username && currentRepo.reponame === reponame && currentRepo.branch) ||
      // Get default branch from cache
      this._defaultBranch[username + '/' + reponame]

    // Still no luck, get default branch for real
    const repo = {username: username, reponame: reponame, branch: branch}

    if (repo.branch) {
      cb(null, repo)
    }
    else {
      this._get(null, {repo, token}, (err, data) => {
        if (err) return cb(err)
        repo.branch = this._defaultBranch[username + '/' + reponame] = data.default_branch || 'master'
        cb(null, repo)
      })
    }
  }

  // @override
  selectFile(path) {
    const $pjaxContainer = $(GH_PJAX_CONTAINER_SEL)

    if ($pjaxContainer.length) {
      $.pjax({
        // needs full path for pjax to work with Firefox as per cross-domain-content setting
        url: location.protocol + '//' + location.host + path,
        container: $pjaxContainer
      })
    }
    else { // falls back
      super.selectFile(path)
    }
  }

  // @override
  loadCodeTree(opts, cb) {
    opts.encodedBranch = encodeURIComponent(decodeURIComponent(opts.repo.branch))
    opts.path = (opts.node && (opts.node.sha || opts.encodedBranch)) ||
                (opts.encodedBranch + '?recursive=1')
    this._loadCodeTree(opts, null, cb)
  }

  // @override
  _getTree(path, opts, cb) {
    this._get(`/git/trees/${path}`, opts, (err, res) => {
      if (err) cb(err)
      else cb(null, res.tree)
    })
  }

  // @override
  _getSubmodules(tree, opts, cb) {
    const item = tree.filter((item) => /^\.gitmodules$/i.test(item.path))[0]
    if (!item) return cb()

    this._get(`/git/blobs/${item.sha}`, opts, (err, res) => {
      if (err) return cb(err)
      const data = atob(res.content.replace(/\n/g,''))
      cb(null, parseGitmodules(data))
    })
  }

  _get(path, opts, cb) {
    const host = location.protocol + '//' +
      (location.host === 'github.com' ? 'api.github.com' : (location.host + '/api/v3'))
    const url = `${host}/repos/${opts.repo.username}/${opts.repo.reponame}${path || ''}`
    const cfg  = { url, method: 'GET', cache: false }

    if (opts.token) {
      cfg.headers = { Authorization: 'token ' + opts.token }
    }

    $.ajax(cfg)
      .done((data) => {
        if (path && path.indexOf('/git/trees') === 0 && data.truncated) {
          this._handleError({status: 206}, cb)
        }
        else cb(null, data)
      })
      .fail((jqXHR) => this._handleError(jqXHR, cb))
  }
}
<|endoftext|>


<commit_before>import React, { Component, Fragment } from 'react'
import ErrorPage from 'components/admin/ErrorPage'
import LoadingBar from 'components/LoadingBar'
import Login from 'components/auth/Login'
import Helmet from 'react-helmet'
import Nav from 'components/apply/ApplyNav'
import Fuse from 'fuse.js'
import {
  Text,
  Container,
  Icon,
  Box,
  Flex,
  Field,
  Heading,
  theme
} from '@hackclub/design-system'
import api from 'api'
import styled from 'styled-components'

const FlexCardLink = styled(Flex.withComponent('a'))`
  padding-top: ${theme.space[3]}px;
  padding-bottom: ${theme.space[3]}px;
  border-top: 1px solid ${theme.colors.smoke};
  align-items: center;

  div {
    flex: 1 1 auto;
  }
`

const ClubCard = ({ visible, high_school_name, id, new_leaders }) =>
  visible ? (
    <FlexCardLink
      boxShadowSize="sm"
      fontSize={3}
      href={`/admin/clubs/edit?id=${id}`}
    >
      <Box align="left" mr={3}>
        <Text bold color="black">
          {high_school_name}
        </Text>
        <Text color="slate" fontSize={1}>
          {new_leaders.map((leader, index) => (
            <Fragment key={leader.id}>
              <Text.span>{leader.name}</Text.span>
              {new_leaders.length - 1 > index && ', '}
            </Fragment>
          ))}
        </Text>
      </Box>
      <Icon glyph="view-forward" color="info" />
    </FlexCardLink>
  ) : null

class SearchInput extends Component {
  state = {
    value: this.props.initialValue || '',
    queryTimeoutId: null
  }

  cancelCurrentTimeout() {
    const { queryTimeoutId } = this.state

    if (queryTimeoutId) {
      window.clearTimeout(queryTimeoutId)
      this.setState({ queryTimeoutId: null })
    }
  }

  handleChange(e) {
    this.cancelCurrentTimeout()

    const value = e.target.value
    const queryTimeoutId = window.setTimeout(() => {
      this.props.callback(value)
    }, 300)
    this.setState({ value, queryTimeoutId })
  }

  componentWillUnmount() {
    this.cancelCurrentTimeout()
  }

  render() {
    return (
      <Field
        placeholder="Search by high school or leaders"
        value={this.state.value}
        onChange={e => this.handleChange(e)}
        my={[3, 5]}
      />
    )
  }
}

export default class extends Component {
  state = { status: 'loading', searchQuery: '' }

  componentDidMount() {
    api
      .currentUser()
      .then(user => {
        api.get(`v1/new_clubs`).then(clubs => {
          this.setState({ user, clubs, status: 'success' })
        })
      })
      .catch(err => {
        switch (err.status) {
          case 401:
          case 403:
            this.setState({ status: 'needsToAuth' })
            break
          default:
            this.setState({ status: 'error' })
            break
        }
      })
  }

  render() {
    const { status, clubs, searchQuery } = this.state
    switch (status) {
      case 'loading':
        return <LoadingBar fill />
      case 'success':
        const fuse = new Fuse(clubs, {
          threshold: 0.4,
          keys: ['high_school_name', 'new_leaders.name', 'new_leaders.email']
        })
        const visibleClubIds = fuse.search(searchQuery).map(club => club.id)
        return (
          <Fragment>
            <Helmet title="Club Dashboard – Hack Club" />
            <Nav />
            <Container maxWidth={32}>
              <Heading.h1 fontSize={[5, 6]}>Club Dashboard</Heading.h1>
              <Heading.h2 color="muted" fontSize={4} mt={2} regular>
                Hello, it’s{' '}
                {new Date().toLocaleDateString('en-us', { weekday: 'long' })}
                {'. '}
                You’re doing great.
              </Heading.h2>
              <SearchInput
                callback={searchQuery => this.setState({ searchQuery })}
              />
              <Box mx={-3}>
                {clubs.map(club => (
                  <ClubCard
                    {...club}
                    key={club.id}
                    visible={
                      searchQuery === '' ||
                      visibleClubIds.indexOf(club.id) !== -1
                    }
                  />
                ))}
              </Box>
            </Container>
          </Fragment>
        )
      case 'needsToAuth':
        return <Login userType="admin" />
      case 'error':
      default:
        return <ErrorPage />
    }
  }
}
<commit_msg>Fix padding on mobile for admin club index<commit_after>import React, { Component, Fragment } from 'react'
import ErrorPage from 'components/admin/ErrorPage'
import LoadingBar from 'components/LoadingBar'
import Login from 'components/auth/Login'
import Helmet from 'react-helmet'
import Nav from 'components/apply/ApplyNav'
import Fuse from 'fuse.js'
import {
  Text,
  Container,
  Icon,
  Box,
  Flex,
  Field,
  Heading,
  theme
} from '@hackclub/design-system'
import api from 'api'
import styled from 'styled-components'

const FlexCardLink = styled(Flex.withComponent('a'))`
  padding: ${theme.space[3]}px;
  border-top: 1px solid ${theme.colors.smoke};
  align-items: center;

  div {
    flex: 1 1 auto;
  }
`

const ClubCard = ({ visible, high_school_name, id, new_leaders }) =>
  visible ? (
    <FlexCardLink
      boxShadowSize="sm"
      fontSize={3}
      href={`/admin/clubs/edit?id=${id}`}
    >
      <Box align="left" mr={3}>
        <Text bold color="black">
          {high_school_name}
        </Text>
        <Text color="slate" fontSize={1}>
          {new_leaders.map((leader, index) => (
            <Fragment key={leader.id}>
              <Text.span>{leader.name}</Text.span>
              {new_leaders.length - 1 > index && ', '}
            </Fragment>
          ))}
        </Text>
      </Box>
      <Icon glyph="view-forward" color="info" />
    </FlexCardLink>
  ) : null

class SearchInput extends Component {
  state = {
    value: this.props.initialValue || '',
    queryTimeoutId: null
  }

  cancelCurrentTimeout() {
    const { queryTimeoutId } = this.state

    if (queryTimeoutId) {
      window.clearTimeout(queryTimeoutId)
      this.setState({ queryTimeoutId: null })
    }
  }

  handleChange(e) {
    this.cancelCurrentTimeout()

    const value = e.target.value
    const queryTimeoutId = window.setTimeout(() => {
      this.props.callback(value)
    }, 300)
    this.setState({ value, queryTimeoutId })
  }

  componentWillUnmount() {
    this.cancelCurrentTimeout()
  }

  render() {
    return (
      <Field
        placeholder="Search by high school or leaders"
        value={this.state.value}
        onChange={e => this.handleChange(e)}
        my={[3, 5]}
      />
    )
  }
}

export default class extends Component {
  state = { status: 'loading', searchQuery: '' }

  componentDidMount() {
    api
      .currentUser()
      .then(user => {
        api.get(`v1/new_clubs`).then(clubs => {
          this.setState({ user, clubs, status: 'success' })
        })
      })
      .catch(err => {
        switch (err.status) {
          case 401:
          case 403:
            this.setState({ status: 'needsToAuth' })
            break
          default:
            this.setState({ status: 'error' })
            break
        }
      })
  }

  render() {
    const { status, clubs, searchQuery } = this.state
    switch (status) {
      case 'loading':
        return <LoadingBar fill />
      case 'success':
        const fuse = new Fuse(clubs, {
          threshold: 0.4,
          keys: ['high_school_name', 'new_leaders.name', 'new_leaders.email']
        })
        const visibleClubIds = fuse.search(searchQuery).map(club => club.id)
        return (
          <Fragment>
            <Helmet title="Club Dashboard – Hack Club" />
            <Nav />
            <Container maxWidth={32} p={1} w={1}>
              <Heading.h1 fontSize={[5, 6]}>Club Dashboard</Heading.h1>
              <Heading.h2 color="muted" fontSize={4} mt={2} regular>
                Hello, it’s{' '}
                {new Date().toLocaleDateString('en-us', { weekday: 'long' })}
                {'. '}
                You’re doing great.
              </Heading.h2>
              <SearchInput
                callback={searchQuery => this.setState({ searchQuery })}
              />
              <Box mx={-3}>
                {clubs.map(club => (
                  <ClubCard
                    {...club}
                    key={club.id}
                    visible={
                      searchQuery === '' ||
                      visibleClubIds.indexOf(club.id) !== -1
                    }
                  />
                ))}
              </Box>
            </Container>
          </Fragment>
        )
      case 'needsToAuth':
        return <Login userType="admin" />
      case 'error':
      default:
        return <ErrorPage />
    }
  }
}
<|endoftext|>


<commit_before>function requestMPDInformation(){
	var mpdRequest = null;
	mpdRequest = new XMLHttpRequest();
	mpdRequest.open("GET", "http://kiosk.shack:8080/mpd/status", true);
	mpdRequest.setRequestHeader("Content-type","application/json");

	mpdRequest.onreadystatechange=function(){
		if(mpdRequest.readyState==4 && mpdRequest.status==200){
			response = JSON.parse(mpdRequest.responseText);
			console.log(response);
			if(response.error){
				document.getElementById("mpd").innerHTML= "MPD disabled"
			}
			else{
				document.getElementById("mpd").innerHTML=response.artist + " - " + response.title;
			}
		}
	}

	mpdRequest.send();
}

function requestPowerInformation(){
	var powerRequest = null;
	powerRequest = new XMLHttpRequest();
	powerRequest.open("GET", "http://glados.shack/siid/apps/powermeter.py?n=1", true);
	powerRequest.setRequestHeader("Content-type","application/json");

	powerRequest.onreadystatechange=function(){
		if(powerRequest.readyState==4 && powerRequest.status==200){
			response = JSON.parse(powerRequest.responseText);
			console.log(response);
			document.getElementById("power").innerHTML=response.Total[0] + " Watt";
		}
	}

	powerRequest.send();
}

function requestTempInformation(){
	var tempRequest = null;
	tempRequest = new XMLHttpRequest();
	tempRequest.open("GET", "http://heidi:8888/api/env/temperature", true);
	tempRequest.setRequestHeader("Content-type","application/json");

	tempRequest.onreadystatechange=function(){
		if(tempRequest.readyState==4 && tempRequest.status==200){
			response = JSON.parse(tempRequest.responseText);
			console.log(response);
			if(response[0] != "No Data"){
				document.getElementById("temp").innerHTML=response[0] + " &degC";
			}
		}
	}

	tempRequest.send();
}

function requestHumidityInformation(){
	var humidityRequest = null;
	humidityRequest = new XMLHttpRequest();
	humidityRequest.open("GET", "http://heidi:8888/api/env/humidity", true);
	humidityRequest.setRequestHeader("Content-type","application/json");

	humidityRequest.onreadystatechange=function(){
		if(humidityRequest.readyState==4 && humidityRequest.status==200){
			response = JSON.parse(humidityRequest.responseText);
			console.log(response);
			if(response[0] != "No Data"){
				document.getElementById("humidity").innerHTML=response[0] + "%";
			}
		}
	}

	humidityRequest.send();
}

function requestBTCInformation(){
	var btcRequest = null;
	btcRequest = new XMLHttpRequest();
	btcRequest.open("GET", "http://kiosk.shack:8080/btc", true);
	btcRequest.setRequestHeader("Content-type","application/json");

	btcRequest.onreadystatechange=function(){
		if(btcRequest.readyState==4 && btcRequest.status==200){
			response = JSON.parse(btcRequest.responseText);
			console.log(response);
			document.getElementById("btc").innerHTML=response.btc + "$";
		}
	}

	btcRequest.send();
}

function requestKeyInformation(){
	var keyRequest = null;
	keyRequest = new XMLHttpRequest();
	keyRequest.open("GET", "http://portal.shack:8088/status", true);
	keyRequest.setRequestHeader("Content-type","application/json");

	keyRequest.onreadystatechange=function(){
		if(keyRequest.readyState==4 && keyRequest.status==200){
			response = JSON.parse(keyRequest.responseText);
			console.log(response);
			document.getElementById("keyholder").innerHTML= response.keyholder;
		}
	}

	keyRequest.send();
}

function requestPeopleInformation(){
	var peopleRequest = null;
	peopleRequest = new XMLHttpRequest();
	peopleRequest.open("GET", "http://shackles.shack/api/user", true);
	peopleRequest.setRequestHeader("Content-type","application/json");

	peopleRequest.onreadystatechange=function(){
		if(peopleRequest.readyState==4 && peopleRequest.status==200){
			document.getElementById("users").innerHTML = "";
			if(peopleRequest.responseText != "{}"){
				response = JSON.parse(peopleRequest.responseText);
				console.log(response);
				for(key in response){
					if(response[key]["status"] != "logged out"){
						document.getElementById("users").innerHTML = document.getElementById("users").innerHTML + " " + response[key]["_id"] + ",";
					}
				}
			}
		}
	}

	peopleRequest.send();
}

function requestHackerspaceInformation(){
	var listRequest = null;
	listRequest = new XMLHttpRequest();
	listRequest.open("GET", "http://localhost:8080/wd.lst", true);
	//listRequest.setRequestHeader("Content-type","application/json");

	listRequest.onreadystatechange=function(){
		if(this.readyState==4 && this.status==200){
			var spaceURLs = this.responseText.split("\n");
			for(key in spaceURLs){
				url = spaceURLs[key];
				var hackerspaceRequest = null;
				hackerspaceRequest = new XMLHttpRequest();
				hackerspaceRequest.open("GET", url, true);
				hackerspaceRequest.setRequestHeader("Content-type","application/json");

				hackerspaceRequest.onreadystatechange = function(){
					if(this.readyState==4 && this.status==200){
						try{ //Spaces may implement the API wrong and we dont want to see all the errors
							var response = JSON.parse(this.responseText);
							if(response.state.open){
								spacesOpen++;
							}
							spacesTotal++;
							document.getElementById("spaces").innerHTML = spacesOpen + "/" + spacesTotal;
						}
						catch(e){
							console.log(e);
						}
					}
				}

				hackerspaceRequest.send();
			}
		}
	}

	listRequest.send();
}

function requestGelberSack(){
	var keyRequest = null;
	sackRequest = new XMLHttpRequest();
	sackRequest.open("GET", "http://openhab.shack/muellshack/gelber_sack", true);
	sackRequest.setRequestHeader("Content-type","application/json");

	sackRequest.onreadystatechange=function(){
		if(sackRequest.readyState==4 && sackRequest.status==200){
			response = JSON.parse(sackRequest.responseText);
			var sackdate = new Date(response.gelber_sack);
			if ( isNaN( sackdate.getTime() ) ) {
				document.getElementById("sack").innerHTML= "kein Termin vorhanden";
			} else {
				var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
				document.getElementById("sack").innerHTML= sackdate.toLocaleDateString('de-DE', options);
			}
		}
	}

	sackRequest.send();
}

function requestPapierMuell(){
	var keyRequest = null;
	papiermuellRequest = new XMLHttpRequest();
	papiermuellRequest.open("GET", "http://openhab.shack/muellshack/papiermuell", true);
	papiermuellRequest.setRequestHeader("Content-type","application/json");

	papiermuellRequest.onreadystatechange=function(){
		if(papiermuellRequest.readyState==4 && papiermuellRequest.status==200){
			response = JSON.parse(papiermuellRequest.responseText);
			var muelldate = new Date(response.papiermuell);
			if ( isNaN( muelldate.getTime() ) ) {
				document.getElementById("papier").innerHTML= "kein Termin vorhanden";
			} else {
				var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
				document.getElementById("papier").innerHTML= muelldate.toLocaleDateString('de-DE', options);
			}
		}
	}

	papiermuellRequest.send();
}

function requestRestMuell(){
	var keyRequest = null;
	restmuellRequest = new XMLHttpRequest();
	restmuellRequest.open("GET", "http://openhab.shack/muellshack/restmuell", true);
	restmuellRequest.setRequestHeader("Content-type","application/json");

	restmuellRequest.onreadystatechange=function(){
		if(restmuellRequest.readyState==4 && restmuellRequest.status==200){
			response = JSON.parse(restmuellRequest.responseText);
			var muelldate = new Date(response.restmuell);
			if ( isNaN( muelldate.getTime() ) ) {
				document.getElementById("rest").innerHTML= "kein Termin vorhanden";
			} else {
				var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
				document.getElementById("rest").innerHTML= muelldate.toLocaleDateString('de-DE', options);
			}
		}
	}

	restmuellRequest.send();
}

function requestIssues(){
    issuesRequest = new XMLHttpRequest();
    issuesRequest.open("GET", "https://api.github.com/repos/shackspace/spaceIssues/issues?state=open", true);
    issuesRequest.setRequestHeader("Content-type", "application/json");

    issuesRequest.onreadystatechange=function() {
        if(issuesRequest.readyState==4 && issuesRequest.status==200){
            response = JSON.parse(issuesRequest.responseText);
            document.getElementById("issues").innerHTML = response.length;
        }
    }

    issuesRequest.send();
}

function requestFeinstaub(){
  feinstaubRequest_sued = new XMLHttpRequest();
  feinstaubRequest_sued.open("GET", "http://api.dusti.xyz/v1/data/?sensor=61&page_size=1", true);
  feinstaubRequest_sued.setRequestHeader("Content-type","application/json");
  feinstaubRequest_sued.onreadystatechange=function(){update_feinstaub(this, "feinstaub-sued")};
  feinstaubRequest_sued.send();

  feinstaubRequest_nord = new XMLHttpRequest();
  feinstaubRequest_nord.open("GET", "http://api.dusti.xyz/v1/data/?sensor=63&page_size=1", true);
  feinstaubRequest_nord.setRequestHeader("Content-type","application/json");
  feinstaubRequest_nord.onreadystatechange=function(){update_feinstaub(this, "feinstaub-nord")};
  feinstaubRequest_nord.send();

}

function update_feinstaub(foo, inner_id){
  var feinstaub_html="";
  if(foo.readyState==4 && foo.status==200){
    response = JSON.parse(foo.responseText);
    for (var idx in response.results[0].sensordatavalues) {
      var sdvalue = response.results[0].sensordatavalues[idx];
      if(sdvalue.value_type == 'P1') {
        console.log(sdvalue.value);
        feinstaub_html += " P1:" + sdvalue.value;
      }
      if(sdvalue.value_type == 'P2') {
        console.log(sdvalue.value);
        feinstaub_html += " P2:" + sdvalue.value;
      }
    }
  }
  document.getElementById(inner_id).innerHTML = feinstaub_html;
}

var spacesOpen = 0;
var spacesTotal = 0;

document.onreadystatechange = function() {
	var state = document.readyState;
	if(state == 'complete') {
		requestPeopleInformation();
		requestMPDInformation();
		requestPowerInformation();
		requestTempInformation();
		requestHumidityInformation();
		requestBTCInformation();
		requestKeyInformation();
		requestGelberSack();
		requestPapierMuell();
		requestRestMuell();
		requestHackerspaceInformation();
        requestIssues();
          requestFeinstaub();

		setInterval(function(){
			requestPeopleInformation();
			requestMPDInformation();
			requestPowerInformation();
			requestTempInformation();
			requestHumidityInformation();
			requestBTCInformation();
			requestKeyInformation();
                        requestFeinstaub();
		}, 10000);
	}
}
<commit_msg>Cleanups<commit_after>function requestMPDInformation(){
	var mpdRequest = null;
	mpdRequest = new XMLHttpRequest();
	mpdRequest.open("GET", "http://kiosk.shack:8080/mpd/status", true);
	mpdRequest.setRequestHeader("Content-type","application/json");

	mpdRequest.onreadystatechange=function(){
		if(mpdRequest.readyState==4 && mpdRequest.status==200){
			response = JSON.parse(mpdRequest.responseText);
			console.log(response);
			if(response.error){
				document.getElementById("mpd").innerHTML= "MPD disabled"
			}
			else{
				document.getElementById("mpd").innerHTML=response.artist + " - " + response.title;
			}
		}
	}

	mpdRequest.send();
}

function requestPowerInformation(){
	var powerRequest = null;
	powerRequest = new XMLHttpRequest();
	powerRequest.open("GET", "http://glados.shack/siid/apps/powermeter.py?n=1", true);
	powerRequest.setRequestHeader("Content-type","application/json");

	powerRequest.onreadystatechange=function(){
		if(powerRequest.readyState==4 && powerRequest.status==200){
			response = JSON.parse(powerRequest.responseText);
			console.log(response);
			document.getElementById("power").innerHTML=response.Total[0] + " Watt";
		}
	}

	powerRequest.send();
}

function requestTempInformation(){
	var tempRequest = null;
	tempRequest = new XMLHttpRequest();
	tempRequest.open("GET", "http://heidi:8888/api/env/temperature", true);
	tempRequest.setRequestHeader("Content-type","application/json");

	tempRequest.onreadystatechange=function(){
		if(tempRequest.readyState==4 && tempRequest.status==200){
			response = JSON.parse(tempRequest.responseText);
			console.log(response);
			if(response[0] != "No Data"){
				document.getElementById("temp").innerHTML=response[0] + " &degC";
			}
		}
	}

	tempRequest.send();
}

function requestHumidityInformation(){
	var humidityRequest = null;
	humidityRequest = new XMLHttpRequest();
	humidityRequest.open("GET", "http://heidi:8888/api/env/humidity", true);
	humidityRequest.setRequestHeader("Content-type","application/json");

	humidityRequest.onreadystatechange=function(){
		if(humidityRequest.readyState==4 && humidityRequest.status==200){
			response = JSON.parse(humidityRequest.responseText);
			console.log(response);
			if(response[0] != "No Data"){
				document.getElementById("humidity").innerHTML=response[0] + "%";
			}
		}
	}

	humidityRequest.send();
}

function requestBTCInformation(){
	var btcRequest = null;
	btcRequest = new XMLHttpRequest();
	btcRequest.open("GET", "http://kiosk.shack:8080/btc", true);
	btcRequest.setRequestHeader("Content-type","application/json");

	btcRequest.onreadystatechange=function(){
		if(btcRequest.readyState==4 && btcRequest.status==200){
			response = JSON.parse(btcRequest.responseText);
			console.log(response);
			document.getElementById("btc").innerHTML=response.btc + "$";
		}
	}

	btcRequest.send();
}

function requestKeyInformation(){
	var keyRequest = null;
	keyRequest = new XMLHttpRequest();
	keyRequest.open("GET", "http://portal.shack:8088/status", true);
	keyRequest.setRequestHeader("Content-type","application/json");

	keyRequest.onreadystatechange=function(){
		if(keyRequest.readyState==4 && keyRequest.status==200){
			response = JSON.parse(keyRequest.responseText);
			console.log(response);
			document.getElementById("keyholder").innerHTML= response.keyholder;
		}
	}

	keyRequest.send();
}

function requestPeopleInformation(){
	var peopleRequest = null;
	peopleRequest = new XMLHttpRequest();
	peopleRequest.open("GET", "http://shackles.shack/api/user", true);
	peopleRequest.setRequestHeader("Content-type","application/json");

	peopleRequest.onreadystatechange=function(){
		if(peopleRequest.readyState==4 && peopleRequest.status==200){
			document.getElementById("users").innerHTML = "";
			if(peopleRequest.responseText != "{}"){
				response = JSON.parse(peopleRequest.responseText);
				console.log(response);
				for(key in response){
					if(response[key]["status"] != "logged out"){
						document.getElementById("users").innerHTML = document.getElementById("users").innerHTML + " " + response[key]["_id"] + ",";
					}
				}
			}
		}
	}

	peopleRequest.send();
}

function requestHackerspaceInformation(){
	var listRequest = null;
	listRequest = new XMLHttpRequest();
	listRequest.open("GET", "http://localhost:8080/wd.lst", true);
	//listRequest.setRequestHeader("Content-type","application/json");

	listRequest.onreadystatechange=function(){
		if(this.readyState==4 && this.status==200){
			var spaceURLs = this.responseText.split("\n");
			for(key in spaceURLs){
				url = spaceURLs[key];
				var hackerspaceRequest = null;
				hackerspaceRequest = new XMLHttpRequest();
				hackerspaceRequest.open("GET", url, true);
				hackerspaceRequest.setRequestHeader("Content-type","application/json");

				hackerspaceRequest.onreadystatechange = function(){
					if(this.readyState==4 && this.status==200){
						try{ //Spaces may implement the API wrong and we dont want to see all the errors
							var response = JSON.parse(this.responseText);
							if(response.state.open){
								spacesOpen++;
							}
							spacesTotal++;
							document.getElementById("spaces").innerHTML = spacesOpen + "/" + spacesTotal;
						}
						catch(e){
							console.log(e);
						}
					}
				}

				hackerspaceRequest.send();
			}
		}
	}

	listRequest.send();
}

function requestGelberSack(){
	var keyRequest = null;
	sackRequest = new XMLHttpRequest();
	sackRequest.open("GET", "http://openhab.shack/muellshack/gelber_sack", true);
	sackRequest.setRequestHeader("Content-type","application/json");

	sackRequest.onreadystatechange=function(){
		if(sackRequest.readyState==4 && sackRequest.status==200){
			response = JSON.parse(sackRequest.responseText);
			var sackdate = new Date(response.gelber_sack);
			if ( isNaN( sackdate.getTime() ) ) {
				document.getElementById("sack").innerHTML= "kein Termin vorhanden";
			} else {
				var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
				document.getElementById("sack").innerHTML= sackdate.toLocaleDateString('de-DE', options);
			}
		}
	}

	sackRequest.send();
}

function requestPapierMuell(){
	var keyRequest = null;
	papiermuellRequest = new XMLHttpRequest();
	papiermuellRequest.open("GET", "http://openhab.shack/muellshack/papiermuell", true);
	papiermuellRequest.setRequestHeader("Content-type","application/json");

	papiermuellRequest.onreadystatechange=function(){
		if(papiermuellRequest.readyState==4 && papiermuellRequest.status==200){
			response = JSON.parse(papiermuellRequest.responseText);
			var muelldate = new Date(response.papiermuell);
			if ( isNaN( muelldate.getTime() ) ) {
				document.getElementById("papier").innerHTML= "kein Termin vorhanden";
			} else {
				var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
				document.getElementById("papier").innerHTML= muelldate.toLocaleDateString('de-DE', options);
			}
		}
	}

	papiermuellRequest.send();
}

function requestRestMuell(){
	var keyRequest = null;
	restmuellRequest = new XMLHttpRequest();
	restmuellRequest.open("GET", "http://openhab.shack/muellshack/restmuell", true);
	restmuellRequest.setRequestHeader("Content-type","application/json");

	restmuellRequest.onreadystatechange=function(){
		if(restmuellRequest.readyState==4 && restmuellRequest.status==200){
			response = JSON.parse(restmuellRequest.responseText);
			var muelldate = new Date(response.restmuell);
			if ( isNaN( muelldate.getTime() ) ) {
				document.getElementById("rest").innerHTML= "kein Termin vorhanden";
			} else {
				var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
				document.getElementById("rest").innerHTML= muelldate.toLocaleDateString('de-DE', options);
			}
		}
	}

	restmuellRequest.send();
}

function requestIssues(){
    issuesRequest = new XMLHttpRequest();
    issuesRequest.open("GET", "https://api.github.com/repos/shackspace/spaceIssues/issues?state=open", true);
    issuesRequest.setRequestHeader("Content-type", "application/json");

    issuesRequest.onreadystatechange=function() {
        if(issuesRequest.readyState==4 && issuesRequest.status==200){
            response = JSON.parse(issuesRequest.responseText);
            document.getElementById("issues").innerHTML = response.length;
        }
    }

    issuesRequest.send();
}

function requestFeinstaub(){
  feinstaubRequest_sued = new XMLHttpRequest();
  feinstaubRequest_sued.open("GET", "http://api.dusti.xyz/v1/data/?sensor=61&page_size=1", true);
  feinstaubRequest_sued.setRequestHeader("Content-type","application/json");
  feinstaubRequest_sued.onreadystatechange=function(){update_feinstaub(this, "feinstaub-sued")};
  feinstaubRequest_sued.send();

  feinstaubRequest_nord = new XMLHttpRequest();
  feinstaubRequest_nord.open("GET", "http://api.dusti.xyz/v1/data/?sensor=63&page_size=1", true);
  feinstaubRequest_nord.setRequestHeader("Content-type","application/json");
  feinstaubRequest_nord.onreadystatechange=function(){update_feinstaub(this, "feinstaub-nord")};
  feinstaubRequest_nord.send();

}

function update_feinstaub(foo, inner_id){
  var feinstaub_html="";
  if(foo.readyState==4 && foo.status==200){
    response = JSON.parse(foo.responseText);
    for (var idx in response.results[0].sensordatavalues) {
      var sdvalue = response.results[0].sensordatavalues[idx];
      if(sdvalue.value_type == 'P1') {
        console.log(sdvalue.value);
        feinstaub_html += " P1:" + sdvalue.value;
      }
      if(sdvalue.value_type == 'P2') {
        console.log(sdvalue.value);
        feinstaub_html += " P2:" + sdvalue.value;
      }
    }
  }
  document.getElementById(inner_id).innerHTML = feinstaub_html;
}

var spacesOpen = 0;
var spacesTotal = 0;

document.onreadystatechange = function() {
	var state = document.readyState;
	if(state == 'complete') {
		requestPeopleInformation();
		requestMPDInformation();
		requestPowerInformation();
		requestTempInformation();
		requestHumidityInformation();
		requestKeyInformation();
		requestGelberSack();
		requestPapierMuell();
		requestRestMuell();
		requestHackerspaceInformation();
        requestIssues();
		requestFeinstaub();

		setInterval(function(){
			requestPeopleInformation();
			requestMPDInformation();
			requestPowerInformation();
			requestTempInformation();
			requestHumidityInformation();
			requestKeyInformation();
            requestFeinstaub();
		}, 10000);
	}
}
<|endoftext|>


<commit_before>var request = require('request');
var cheerio = require('cheerio');
var Promise = require('promise');
var requestp = require('../../requestp');

/* Resource for ligamagic */
module.exports = {
  find : function(cardname, proxy) {
    // Add some way to get the card with this resource
    console.log("Looking for " + cardname);
    console.log("Proxy: " + proxy);
    return new Promise(function(resolve, reject) {
      var request_options = {
        headers: {
          'User-Agent' : 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.155 Safari/537.36',
          'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
        },
        url: "http://ligamagic.com.br/?view=cards%2Fsearch&card=" + cardname
      };
      requestp(request_options)
        .then(function(body) {

          //read the data
          var $ = cheerio.load(body);
          var title = $(".cardTitle").text();
          var card_sets = {};
          var card = {};
          $(".overview td").each(function(i, elem) {
            var card_set = $("a", elem).attr("href");
            card_set = card_set.split("%3d")[1];
            card_sets[card_set] = []; //No prices found yet!

            //@TODO:  Stop reading from the Javascript at the end of the page
            //        and scrappe the page instead. Dumbass! There's a table
            //        with the prices, lel!

            //Find the minor price for the card
            var regexMinorPrice = new RegExp("VETprecoMenor\\[" + i.toString() + "\\]\\s+=\\s+\"(.*)\";", "i");
            var minorPrice = body.match(regexMinorPrice)[1].replace(',', '.');
            card_sets[card_set].push(minorPrice);

            //Find the medium price for the card
            var regexMediumPrice = new RegExp("VETprecoMedio\\[" + i.toString() + "\\]\\s+=\\s+\"(.*)\";", "i");
            var mediumPrice = body.match(regexMediumPrice)[1].replace(',', '.');
            card_sets[card_set].push(mediumPrice);

            //Find the major price for the card
            var regexMajorPrice = new RegExp("VETprecoMaior\\[" + i.toString() + "\\]\\s+=\\s+\"(.*)\";", "i");
            var majorPrice = body.match(regexMajorPrice)[1].replace(',', '.');
            card_sets[card_set].push(majorPrice);
          });

          card["title"] = title;
          card["sets"] = card_sets;
          card["url"] = request_options["url"];

          resolve(card);
          //resolve("Misterious card info!");
        }, function(err) {
          reject(err); //Cascading promises
        });
    });
  }
}
<commit_msg>Fixed when card not found<commit_after>var request = require('request');
var cheerio = require('cheerio');
var Promise = require('promise');
var requestp = require('../../requestp');

/* Resource for ligamagic */
module.exports = {
  find : function(cardname, proxy) {
    // Add some way to get the card with this resource
    console.log("Looking for " + cardname);
    console.log("Proxy: " + proxy);
    return new Promise(function(resolve, reject) {
      var request_options = {
        headers: {
          'User-Agent' : 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.155 Safari/537.36',
          'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
        },
        url: "http://ligamagic.com.br/?view=cards%2Fsearch&card=" + cardname
      };
      requestp(request_options)
        .then(function(body) {

          if(body.indexOf("0-0") !== -1)
            reject("Card not found");

          //read the data
          var $ = cheerio.load(body);
          var title = $(".cardTitle").text();
          var card_sets = {};
          var card = {};
          $(".overview td").each(function(i, elem) {
            var card_set = $("a", elem).attr("href");
            card_set = card_set.split("%3d")[1];
            card_sets[card_set] = []; //No prices found yet!

            //@TODO:  Stop reading from the Javascript at the end of the page
            //        and scrappe the page instead. Dumbass! There's a table
            //        with the prices, lel!

            //Find the minor price for the card
            var regexMinorPrice = new RegExp("VETprecoMenor\\[" + i.toString() + "\\]\\s+=\\s+\"(.*)\";", "i");
            var minorPrice = body.match(regexMinorPrice)[1].replace(',', '.');
            card_sets[card_set].push(minorPrice);

            //Find the medium price for the card
            var regexMediumPrice = new RegExp("VETprecoMedio\\[" + i.toString() + "\\]\\s+=\\s+\"(.*)\";", "i");
            var mediumPrice = body.match(regexMediumPrice)[1].replace(',', '.');
            card_sets[card_set].push(mediumPrice);

            //Find the major price for the card
            var regexMajorPrice = new RegExp("VETprecoMaior\\[" + i.toString() + "\\]\\s+=\\s+\"(.*)\";", "i");
            var majorPrice = body.match(regexMajorPrice)[1].replace(',', '.');
            card_sets[card_set].push(majorPrice);
          });

          card["title"] = title;
          card["sets"] = card_sets;
          card["url"] = request_options["url"];

          resolve(card);
          //resolve("Misterious card info!");
        }, function(err) {
          reject(err); //Cascading promises
        });
    });
  }
}
<|endoftext|>