<commit_before>import checkShouldScroll from './checkShouldScroll';
import getCloestScrollableElement from './getCloestScrollableElement'

class Hyperscope {
  constructor(step = 10, interval = 50, delay = 100) {
    this.step = step;
    this.interval = interval;
    this.delay = delay;
    this.timeoutHanler = null;
  }

  request(x, y, element) {
    this.timeoutHanler = setTimeout(() => {
      scroll(x, y, element, this.step, this.interval, handler => {
        this.timeoutHanler = handler;
      });
    }, this.delay)
  }

  cancel() {
    clearTimeout(this.timeoutHanler);
  }
}

function scroll(x, y, element, step, interval, setHandler) {
  //0. 判断是否需要滚动
  let { x: dx, y: dy } = checkShouldScroll(x, y, element)
    , direction = dx < 0
      ? "left"
      : dx > 0
        ? "right"
        : dy < 0
          ? "up"
          : dy > 0
            ? "down"
            : "";

  if (dx || dy) {
    let scrollableElement = getCloestScrollableElement(element, direction);

    if (scrollableElement) {
      scrollableElement.scrollLeft += (dx * step);
      scrollableElement.scrollTop += (dy * step);

      setHandler(setTimeout(function () {
        scroll(x, y, element, step, interval, setHandler);
      }, interval));
    }
  }
}

export default Hyperscope;<commit_msg>intial commit<commit_after>import checkShouldScroll from './checkShouldScroll';
import getCloestScrollableElement from './getCloestScrollableElement'

class Hyperscope {
  constructor(step = 10, interval = 20, delay = 100) {
    this.step = step;
    this.interval = interval;
    this.delay = delay;
    this.timeoutHanler = null;
  }

  request(x, y, element) {
    this.timeoutHanler = setTimeout(() => {
      scroll(x, y, element, this.step, this.interval, handler => {
        this.timeoutHanler = handler;
      });
    }, this.delay)
  }

  cancel() {
    clearTimeout(this.timeoutHanler);
  }
}

function scroll(x, y, element, step, interval, setHandler) {
  //0. 判断是否需要滚动
  let { x: dx, y: dy } = checkShouldScroll(x, y, element)
    , direction = dx < 0
      ? "left"
      : dx > 0
        ? "right"
        : dy < 0
          ? "up"
          : dy > 0
            ? "down"
            : "";

  if (dx || dy) {
    let scrollableElement = getCloestScrollableElement(element, direction);

    if (scrollableElement) {
      scrollableElement.scrollLeft += (dx * step);
      scrollableElement.scrollTop += (dy * step);

      setHandler(setTimeout(function () {
        scroll(x, y, element, step, interval, setHandler);
      }, interval));
    }
  }
}

export default Hyperscope;<|endoftext|>


<commit_before>import { app, BrowserWindow } from "electron";
import installExtension, {
  REACT_DEVELOPER_TOOLS
} from "electron-devtools-installer";
import { enableLiveReload } from "electron-compile";
import { Initializer } from "./core/initializer";

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;

const isDevMode = process.execPath.match(/[\\/]electron/);

if (isDevMode) enableLiveReload({ strategy: "react-hmr" });

const createWindow = async () => {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    radii: [0, 0, 0, 0]
  });

  const indexPath = `file://${__dirname}/index.html`;
  const iconPath = `${__dirname}/resources/icons`;
  let openDevTools = true;
  let openAutomatically = true;
  let alwaysOnTop = true;
  let big = true;
  const debugFlag = true;

  if (debugFlag) {
    openDevTools = true;
    openAutomatically = true;
    alwaysOnTop = true;
  }
  const initializer = new Initializer({
    mainWindow,
    isDevMode,
    indexPath,
    iconPath,
    app,
    openDevTools,
    alwaysOnTop,
    big
  });
  initializer.initialize();
  if (openAutomatically) {
    initializer.mb.showWindow();
  }

  const installDevTools = openDevTools;
  // Open the DevTools.
  if (installDevTools) {
    await installExtension(REACT_DEVELOPER_TOOLS);
    // mainWindow.webContents.openDevTools();
  }

  // Emitted when the window is closed.
  mainWindow.on("closed", () => {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null;
  });
};

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on("ready", createWindow);

// Quit when all windows are closed.
app.on("window-all-closed", () => {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== "darwin") {
    app.quit();
  }
});

app.on("activate", () => {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWindow === null) {
    createWindow();
  }
});
<commit_msg>Turn off debug flag<commit_after>import { app, BrowserWindow } from "electron";
import installExtension, {
  REACT_DEVELOPER_TOOLS
} from "electron-devtools-installer";
import { enableLiveReload } from "electron-compile";
import { Initializer } from "./core/initializer";

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;

const isDevMode = process.execPath.match(/[\\/]electron/);

if (isDevMode) enableLiveReload({ strategy: "react-hmr" });

const createWindow = async () => {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    radii: [0, 0, 0, 0]
  });

  const indexPath = `file://${__dirname}/index.html`;
  const iconPath = `${__dirname}/resources/icons`;
  let openDevTools = true;
  let openAutomatically = true;
  let alwaysOnTop = true;
  let big = true;
  const debugFlag = false;

  if (debugFlag) {
    openDevTools = true;
    openAutomatically = true;
    alwaysOnTop = true;
  }
  const initializer = new Initializer({
    mainWindow,
    isDevMode,
    indexPath,
    iconPath,
    app,
    openDevTools,
    alwaysOnTop,
    big
  });
  initializer.initialize();
  if (openAutomatically) {
    initializer.mb.showWindow();
  }

  const installDevTools = openDevTools;
  // Open the DevTools.
  if (installDevTools) {
    await installExtension(REACT_DEVELOPER_TOOLS);
    // mainWindow.webContents.openDevTools();
  }

  // Emitted when the window is closed.
  mainWindow.on("closed", () => {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null;
  });
};

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on("ready", createWindow);

// Quit when all windows are closed.
app.on("window-all-closed", () => {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== "darwin") {
    app.quit();
  }
});

app.on("activate", () => {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWindow === null) {
    createWindow();
  }
});
<|endoftext|>


<commit_before>import React from 'react'
import { render } from 'react-dom'
import { AppContainer } from 'react-hot-loader'
import { browserHistory } from 'react-router'
import Root from './components/Root'
import configureStore from './store/configureStore'
import { syncHistoryWithStore } from 'react-router-redux'
import './styles/main.scss'
import '../node_modules/bootstrap/dist/css/bootstrap.css'
require('./favicon.ico')

import App from './components/App'

const store = configureStore()
const history = syncHistoryWithStore(browserHistory, store)

render(
  <AppContainer>
    <Root store={store} history={history} />
  </AppContainer>,
  document.getElementById('app')
)

if (module.hot) {
  module.hot.accept('./components/Root', () => {
    const NewRoot = require('./components/Root').default;
    render(
      <AppContainer>
        <NewRoot store={store} history={history} />
      </AppContainer>,
      document.getElementById('app')
    );
  });
}
<commit_msg>remove unneeded import<commit_after>import React from 'react'
import { render } from 'react-dom'
import { AppContainer } from 'react-hot-loader'
import { browserHistory } from 'react-router'
import Root from './components/Root'
import configureStore from './store/configureStore'
import { syncHistoryWithStore } from 'react-router-redux'
import './styles/main.scss'
import '../node_modules/bootstrap/dist/css/bootstrap.css'
require('./favicon.ico')

const store = configureStore()
const history = syncHistoryWithStore(browserHistory, store)

render(
  <AppContainer>
    <Root store={store} history={history} />
  </AppContainer>,
  document.getElementById('app')
)

if (module.hot) {
  module.hot.accept('./components/Root', () => {
    const NewRoot = require('./components/Root').default;
    render(
      <AppContainer>
        <NewRoot store={store} history={history} />
      </AppContainer>,
      document.getElementById('app')
    );
  });
}
<|endoftext|>


<commit_before>const React = require('react');
const ReactDOM = require('react-dom');
const StackBlur = require('../shared/stackblur');

function getStyles(target, styles, condition) {
  let conditionalStyles = require('../shared/styles');

  return Object.assign({},
    styles,
    condition && conditionalStyles[target].true,
    !condition && conditionalStyles[target].false
  )
}

function getClass(target, condition) {
  return condition && 'seemslegit' || 'ups'
}

class FullImage extends React.Component {
  constructor(props) {
    super(props)
  }
  render() {
    var {src, onLoad, style, ...other} = this.props
    return (

    )
  }
}
class LazyImage extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount(){
    var container = ReactDOM.findDOMNode(this);
    this.width = container.offsetWidth;
    this.height = container.offsetHeight;
    this.canvas = ReactDOM.findDOMNode(this.refs.canvas);
    this.canvas.height = this.height;
    this.canvas.width = this.width;
    var blurRadius = this.props.blurRadius || 0;
    this.preImg = document.createElement('img');
    this.preImg.crossOrigin = 'Anonymous';
    this.preImg.onload = () => {
      StackBlur(this.preImg, this.canvas, blurRadius, 600, 190);
    };
    this.preImg.src = this.props.src;
  }
  componentWillUpdate(nextProps) {
    if (this.preImg.src !== nextProps.src) {
      this.preImg.src = nextProps.src;
    }
    StackBlur(this.preImg, this.canvas, nextProps.blurRadius, 600, 190);
  }
  render() {
    var { src, style, ...other } = this.props;
    return (

        <canvas ref='canvas' />

    )
  }
}

class LazyImageWrapper extends React.Component {
  constructor(props) {
    super(props)
    this.handleLoaded = this.handleLoaded.bind(this);
    this.state = {
      loaded: false
    }
  }
  handleLoaded() {
    console.log('loaded')
    this.setState({
      loaded: true
    })
  }
  render() {
    var { src, small, width, height, children, className, blurRadius, ...other } = this.props;
    var styles = {
      width,
      height,
      padding: 0,
      margin: 0,
      position: 'absolute',
      top: 0
    }

    var wrapperStyles = {
      paddingBottom: styles.height,
      position: 'relative'
    }
    return (

        <FullImage src={src} style={getStyles('FullImage', styles, this.state.loaded)} onLoad={this.handleLoaded} />
        <LazyImage src={small} style={getStyles('LazyImage', styles, this.state.loaded)} blurRadius={this.props.blurRadius}/>

    )
  }
}

module.exports = LazyImageWrapper
<commit_msg>bugfix<commit_after>const React = require('react');
const ReactDOM = require('react-dom');
const StackBlur = require('../shared/stackblur');

function getStyles(target, styles, condition) {
  let conditionalStyles = require('../shared/styles');

  return Object.assign({},
    styles,
    condition && conditionalStyles[target].true,
    !condition && conditionalStyles[target].false
  )
}

class FullImage extends React.Component {
  constructor(props) {
    super(props)
  }
  render() {
    var {src, onLoad, style, ...other} = this.props
    return (

    )
  }
}
class LazyImage extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount(){
    var container = ReactDOM.findDOMNode(this);
    this.width = container.offsetWidth;
    this.height = container.offsetHeight;
    this.canvas = ReactDOM.findDOMNode(this.refs.canvas);
    this.canvas.height = this.height;
    this.canvas.width = this.width;
    var blurRadius = this.props.blurRadius || 0;
    this.preImg = document.createElement('img');
    this.preImg.crossOrigin = 'Anonymous';
    this.preImg.onload = () => {
      StackBlur(this.preImg, this.canvas, blurRadius, 600, 190);
    };
    this.preImg.src = this.props.src;
  }
  componentWillUpdate(nextProps) {
    if (this.preImg.src !== nextProps.src) {
      this.preImg.src = nextProps.src;
    }
    StackBlur(this.preImg, this.canvas, nextProps.blurRadius, 600, 190);
  }
  render() {
    var { src, style, ...other } = this.props;
    return (

        <canvas ref='canvas' />

    )
  }
}

class LazyImageWrapper extends React.Component {
  constructor(props) {
    super(props)
    this.handleLoaded = this.handleLoaded.bind(this);
    this.state = {
      loaded: false
    }
  }
  handleLoaded() {
    console.log('loaded')
    this.setState({
      loaded: true
    })
  }
  render() {
    var { src, small, width, height, children, className, blurRadius, ...other } = this.props;
    var styles = {
      width,
      height,
      padding: 0,
      margin: 0,
      position: 'absolute',
      top: 0
    }

    var wrapperStyles = {
      paddingBottom: styles.height,
      position: 'relative'
    }
    return (

        <FullImage src={src} style={getStyles('FullImage', styles, this.state.loaded)} onLoad={this.handleLoaded} />
        <LazyImage src={small} style={getStyles('LazyImage', styles, this.state.loaded)} blurRadius={this.props.blurRadius}/>

    )
  }
}

module.exports = LazyImageWrapper
<|endoftext|>


<commit_before>import forEach from 'lodash.foreach'
import {BaseError} from 'make-error'
import {EventEmitter} from 'events'

import isEmpty from './is-empty'

// ===================================================================

const {hasOwnProperty} = Object

// ===================================================================

export class BufferAlreadyFlushed extends BaseError {
  constructor () {
    super('buffer flush already requested')
  }
}

export class DuplicateIndex extends BaseError {
  constructor (name) {
    super('there is already an index with the name ' + name)
  }
}

export class DuplicateItem extends BaseError {
  constructor (key) {
    super('there is already a item with the key ' + key)
  }
}

export class IllegalTouch extends BaseError {
  constructor (value) {
    super('only an object value can be touched (found a ' + typeof value + ')')
  }
}

export class InvalidKey extends BaseError {
  constructor (key) {
    super('invalid key of type ' + typeof key)
  }
}

export class NoSuchIndex extends BaseError {
  constructor (name) {
    super('there is no index with the name ' + name)
  }
}

export class NoSuchItem extends BaseError {
  constructor (key) {
    super('there is no item with the key ' + key)
  }
}

// -------------------------------------------------------------------

export default class Collection extends EventEmitter {
  constructor () {
    super()

    this._buffer = Object.create(null)
    this._buffering = 0
    this._indexes = Object.create(null)
    this._indexedItems = Object.create(null)
    this._items = {} // Object.create(null)
    this._size = 0
  }

  // Overridable method used to compute the key of an item when
  // unspecified.
  //
  // Default implementation returns the `id` property.
  getKey (value) {
    return value && value.id
  }

  // -----------------------------------------------------------------
  // Properties
  // -----------------------------------------------------------------

  get all () {
    return this._items
  }

  get indexes () {
    return this._indexedItems
  }

  get size () {
    return this._size
  }

  // -----------------------------------------------------------------
  // Manipulation
  // -----------------------------------------------------------------

  add (keyOrObjectWithId, valueIfKey = undefined) {
    const [key, value] = this._resolveItem(keyOrObjectWithId, valueIfKey)
    this._assertHasNot(key)

    this._items[key] = value
    this._size++
    this._touch('add', key)
  }

  clear () {
    forEach(this._items, (_, key) => {
      delete this._items[key]
      this._size--
      this._touch('remove', key)
    })
  }

  remove (keyOrObjectWithId) {
    const [key] = this._resolveItem(keyOrObjectWithId)
    this._assertHas(key)

    delete this._items[key]
    this._size--
    this._touch('remove', key)
  }

  set (keyOrObjectWithId, valueIfKey = undefined) {
    const [key, value] = this._resolveItem(keyOrObjectWithId, valueIfKey)

    const action = this.has(key) ? 'update' : 'add'
    this._items[key] = value
    if (action === 'add') {
      this._size++
    }
    this._touch(action, key)
  }

  touch (keyOrObjectWithId) {
    const [key] = this._resolveItem(keyOrObjectWithId)
    this._assertHas(key)
    const value = this.get(key)
    if (typeof value !== 'object' || value === null) {
      throw new IllegalTouch(value)
    }

    this._touch('update', key)

    return this.get(key)
  }

  unset (keyOrObjectWithId) {
    const [key] = this._resolveItem(keyOrObjectWithId)

    if (this.has(key)) {
      delete this._items[key]
      this._size--
      this._touch('remove', key)
    }
  }

  update (keyOrObjectWithId, valueIfKey = undefined) {
    const [key, value] = this._resolveItem(keyOrObjectWithId, valueIfKey)
    this._assertHas(key)

    this._items[key] = value
    this._touch('update', key)
  }

  // -----------------------------------------------------------------
  // Query
  // -----------------------------------------------------------------

  get (key, defaultValue) {
    if (this.has(key)) {
      return this._items[key]
    }

    if (arguments.length > 1) {
      return defaultValue
    }

    // Throws a NoSuchItem.
    this._assertHas(key)
  }

  has (key) {
    return hasOwnProperty.call(this._items, key)
  }

  // -----------------------------------------------------------------
  // Indexes
  // -----------------------------------------------------------------

  createIndex (name, index) {
    const {_indexes: indexes} = this
    if (hasOwnProperty.call(indexes, name)) {
      throw new DuplicateIndex(name)
    }

    indexes[name] = index
    this._indexedItems[name] = index.items

    index._attachCollection(this)
  }

  deleteIndex (name) {
    const {_indexes: indexes} = this
    if (!hasOwnProperty.call(indexes, name)) {
      throw new NoSuchIndex(name)
    }

    const index = indexes[name]
    delete indexes[name]
    delete this._indexedItems[name]

    index._detachCollection(this)
  }

  // -----------------------------------------------------------------
  // Iteration
  // -----------------------------------------------------------------

  * [Symbol.iterator] () {
    const {_items: items} = this

    for (const key in items) {
      yield [key, items[key]]
    }
  }

  * keys () {
    const {_items: items} = this

    for (const key in items) {
      yield key
    }
  }

  * values () {
    const {_items: items} = this

    for (const key in items) {
      yield items[key]
    }
  }

  // -----------------------------------------------------------------
  // Events buffering
  // -----------------------------------------------------------------

  bufferEvents () {
    ++this._buffering

    let called = false
    return () => {
      if (called) {
        throw new BufferAlreadyFlushed()
      }
      called = true

      if (--this._buffering) {
        return
      }

      const {_buffer: buffer} = this

      // Due to deduplication there could be nothing in the buffer.
      if (isEmpty(buffer)) {
        return
      }

      const data = {
        add: Object.create(null),
        remove: Object.create(null),
        update: Object.create(null)
      }

      for (const key in this._buffer) {
        data[buffer[key]][key] = this._items[key]
      }

      forEach(data, (items, action) => {
        if (!isEmpty(items)) {
          this.emit(action, items)
        }
      })

      // Indicates the end of the update.
      //
      // This name has been chosen because it is used in Node writable
      // streams when the data has been successfully committed.
      this.emit('finish')

      this._buffer = Object.create(null)
    }
  }

  // =================================================================

  _assertHas (key) {
    if (!this.has(key)) {
      throw new NoSuchItem(key)
    }
  }

  _assertHasNot (key) {
    if (this.has(key)) {
      throw new DuplicateItem(key)
    }
  }

  _assertValidKey (key) {
    if (!this._isValidKey(key)) {
      throw new InvalidKey(key)
    }
  }

  _isValidKey (key) {
    return typeof key === 'number' || typeof key === 'string'
  }

  _resolveItem (keyOrObjectWithId, valueIfKey = undefined) {
    if (valueIfKey !== undefined) {
      this._assertValidKey(keyOrObjectWithId)

      return [keyOrObjectWithId, valueIfKey]
    }

    if (this._isValidKey(keyOrObjectWithId)) {
      return [keyOrObjectWithId]
    }

    const key = this.getKey(keyOrObjectWithId)
    this._assertValidKey(key)

    return [key, keyOrObjectWithId]
  }

  _touch (action, key) {
    if (this._buffering === 0) {
      const flush = this.bufferEvents()

      process.nextTick(flush)
    }

    if (action === 'add') {
      this._buffer[key] = this._buffer[key] ? 'update' : 'add'
    } else if (action === 'remove') {
      if (this._buffer[key] === 'add') {
        delete this._buffer[key]
      } else {
        this._buffer[key] = 'remove'
      }
    } else { // update
      if (!this._buffer[key]) {
        this._buffer[key] = 'update'
      }
    }
  }
}
<commit_msg>Minor opt.<commit_after>import forEach from 'lodash.foreach'
import {BaseError} from 'make-error'
import {EventEmitter} from 'events'

import isEmpty from './is-empty'

// ===================================================================

const {
  create: createObject,
  hasOwnProperty
} = Object

// ===================================================================

export class BufferAlreadyFlushed extends BaseError {
  constructor () {
    super('buffer flush already requested')
  }
}

export class DuplicateIndex extends BaseError {
  constructor (name) {
    super('there is already an index with the name ' + name)
  }
}

export class DuplicateItem extends BaseError {
  constructor (key) {
    super('there is already a item with the key ' + key)
  }
}

export class IllegalTouch extends BaseError {
  constructor (value) {
    super('only an object value can be touched (found a ' + typeof value + ')')
  }
}

export class InvalidKey extends BaseError {
  constructor (key) {
    super('invalid key of type ' + typeof key)
  }
}

export class NoSuchIndex extends BaseError {
  constructor (name) {
    super('there is no index with the name ' + name)
  }
}

export class NoSuchItem extends BaseError {
  constructor (key) {
    super('there is no item with the key ' + key)
  }
}

// -------------------------------------------------------------------

export default class Collection extends EventEmitter {
  constructor () {
    super()

    this._buffer = createObject(null)
    this._buffering = 0
    this._indexes = createObject(null)
    this._indexedItems = createObject(null)
    this._items = {} // createObject(null)
    this._size = 0
  }

  // Overridable method used to compute the key of an item when
  // unspecified.
  //
  // Default implementation returns the `id` property.
  getKey (value) {
    return value && value.id
  }

  // -----------------------------------------------------------------
  // Properties
  // -----------------------------------------------------------------

  get all () {
    return this._items
  }

  get indexes () {
    return this._indexedItems
  }

  get size () {
    return this._size
  }

  // -----------------------------------------------------------------
  // Manipulation
  // -----------------------------------------------------------------

  add (keyOrObjectWithId, valueIfKey = undefined) {
    const [key, value] = this._resolveItem(keyOrObjectWithId, valueIfKey)
    this._assertHasNot(key)

    this._items[key] = value
    this._size++
    this._touch('add', key)
  }

  clear () {
    forEach(this._items, (_, key) => {
      delete this._items[key]
      this._size--
      this._touch('remove', key)
    })
  }

  remove (keyOrObjectWithId) {
    const [key] = this._resolveItem(keyOrObjectWithId)
    this._assertHas(key)

    delete this._items[key]
    this._size--
    this._touch('remove', key)
  }

  set (keyOrObjectWithId, valueIfKey = undefined) {
    const [key, value] = this._resolveItem(keyOrObjectWithId, valueIfKey)

    const action = this.has(key) ? 'update' : 'add'
    this._items[key] = value
    if (action === 'add') {
      this._size++
    }
    this._touch(action, key)
  }

  touch (keyOrObjectWithId) {
    const [key] = this._resolveItem(keyOrObjectWithId)
    this._assertHas(key)
    const value = this.get(key)
    if (typeof value !== 'object' || value === null) {
      throw new IllegalTouch(value)
    }

    this._touch('update', key)

    return this.get(key)
  }

  unset (keyOrObjectWithId) {
    const [key] = this._resolveItem(keyOrObjectWithId)

    if (this.has(key)) {
      delete this._items[key]
      this._size--
      this._touch('remove', key)
    }
  }

  update (keyOrObjectWithId, valueIfKey = undefined) {
    const [key, value] = this._resolveItem(keyOrObjectWithId, valueIfKey)
    this._assertHas(key)

    this._items[key] = value
    this._touch('update', key)
  }

  // -----------------------------------------------------------------
  // Query
  // -----------------------------------------------------------------

  get (key, defaultValue) {
    if (this.has(key)) {
      return this._items[key]
    }

    if (arguments.length > 1) {
      return defaultValue
    }

    // Throws a NoSuchItem.
    this._assertHas(key)
  }

  has (key) {
    return hasOwnProperty.call(this._items, key)
  }

  // -----------------------------------------------------------------
  // Indexes
  // -----------------------------------------------------------------

  createIndex (name, index) {
    const {_indexes: indexes} = this
    if (hasOwnProperty.call(indexes, name)) {
      throw new DuplicateIndex(name)
    }

    indexes[name] = index
    this._indexedItems[name] = index.items

    index._attachCollection(this)
  }

  deleteIndex (name) {
    const {_indexes: indexes} = this
    if (!hasOwnProperty.call(indexes, name)) {
      throw new NoSuchIndex(name)
    }

    const index = indexes[name]
    delete indexes[name]
    delete this._indexedItems[name]

    index._detachCollection(this)
  }

  // -----------------------------------------------------------------
  // Iteration
  // -----------------------------------------------------------------

  * [Symbol.iterator] () {
    const {_items: items} = this

    for (const key in items) {
      yield [key, items[key]]
    }
  }

  * keys () {
    const {_items: items} = this

    for (const key in items) {
      yield key
    }
  }

  * values () {
    const {_items: items} = this

    for (const key in items) {
      yield items[key]
    }
  }

  // -----------------------------------------------------------------
  // Events buffering
  // -----------------------------------------------------------------

  bufferEvents () {
    ++this._buffering

    let called = false
    return () => {
      if (called) {
        throw new BufferAlreadyFlushed()
      }
      called = true

      if (--this._buffering) {
        return
      }

      const {_buffer: buffer} = this

      // Due to deduplication there could be nothing in the buffer.
      if (isEmpty(buffer)) {
        return
      }

      const data = {
        add: createObject(null),
        remove: createObject(null),
        update: createObject(null)
      }

      for (const key in this._buffer) {
        data[buffer[key]][key] = this._items[key]
      }

      forEach(data, (items, action) => {
        if (!isEmpty(items)) {
          this.emit(action, items)
        }
      })

      // Indicates the end of the update.
      //
      // This name has been chosen because it is used in Node writable
      // streams when the data has been successfully committed.
      this.emit('finish')

      this._buffer = createObject(null)
    }
  }

  // =================================================================

  _assertHas (key) {
    if (!this.has(key)) {
      throw new NoSuchItem(key)
    }
  }

  _assertHasNot (key) {
    if (this.has(key)) {
      throw new DuplicateItem(key)
    }
  }

  _assertValidKey (key) {
    if (!this._isValidKey(key)) {
      throw new InvalidKey(key)
    }
  }

  _isValidKey (key) {
    return typeof key === 'number' || typeof key === 'string'
  }

  _resolveItem (keyOrObjectWithId, valueIfKey = undefined) {
    if (valueIfKey !== undefined) {
      this._assertValidKey(keyOrObjectWithId)

      return [keyOrObjectWithId, valueIfKey]
    }

    if (this._isValidKey(keyOrObjectWithId)) {
      return [keyOrObjectWithId]
    }

    const key = this.getKey(keyOrObjectWithId)
    this._assertValidKey(key)

    return [key, keyOrObjectWithId]
  }

  _touch (action, key) {
    if (this._buffering === 0) {
      const flush = this.bufferEvents()

      process.nextTick(flush)
    }

    if (action === 'add') {
      this._buffer[key] = this._buffer[key] ? 'update' : 'add'
    } else if (action === 'remove') {
      if (this._buffer[key] === 'add') {
        delete this._buffer[key]
      } else {
        this._buffer[key] = 'remove'
      }
    } else { // update
      if (!this._buffer[key]) {
        this._buffer[key] = 'update'
      }
    }
  }
}
<|endoftext|>


<commit_before>import detectHover from 'detect-hover';
import detectPointer from 'detect-pointer';
import detectTouchEvents from 'detect-touch-events';
import detectPassiveEvents from 'detect-passive-events';

/*
 * detectIt object structure
 * const detectIt = {
 *   deviceType: 'mouseOnly' / 'touchOnly' / 'hybrid',
 *   passiveEvents: boolean,
 *   hasTouch: boolean,
 *   hasMouse: boolean,
 *   maxTouchPoints: number,
 *   primaryHover: 'hover' / 'none',
 *   primaryPointer: 'fine' / 'coarse' / 'none',
 *   state: {
 *     detectHover,
 *     detectPointer,
 *     detectTouchEvents,
 *     detectPassiveEvents,
 *   },
 *   update() {...},
 * }
 */

function determineDeviceType(hasTouch, anyHover, anyFine, state) {
  // A hybrid device is one that both hasTouch and any input device can hover
  // or has a fine pointer.
  if (hasTouch && (anyHover || anyFine)) return 'hybrid';

  // workaround for browsers that have the touch events api,
  // and have implemented Level 4 media queries but not the
  // hover and pointer media queries, so the tests are all false (notable Firefox)
  // if it hasTouch, no pointer and hover support, and on an android assume it's touchOnly
  // if it hasTouch, no pointer and hover support, and not on an android assume it's a hybrid
  if (hasTouch &&
  Object.keys(state.detectHover).filter(key => key !== 'update').every(key => state.detectHover[key] === false) &&
  Object.keys(state.detectPointer).filter(key => key !== 'update').every(key => state.detectPointer[key] === false)) {
    if (window.navigator && /android/.test(window.navigator.userAgent.toLowerCase())) {
      return 'touchOnly';
    }
    return 'hybrid';
  }

  // In almost all cases a device that doesn’t support touch will have a mouse,
  // but there may be rare exceptions. Note that it doesn’t work to do additional tests
  // based on hover and pointer media queries as older browsers don’t support these.
  // Essentially, 'mouseOnly' is the default.
  return hasTouch ? 'touchOnly' : 'mouseOnly';
}

const detectIt = {
  state: {
    detectHover,
    detectPointer,
    detectTouchEvents,
    detectPassiveEvents,
  },
  update() {
    detectIt.state.detectHover.update();
    detectIt.state.detectPointer.update();
    detectIt.state.detectTouchEvents.update();
    detectIt.state.detectPassiveEvents.update();
    detectIt.updateOnlyOwnProperties();
  },
  updateOnlyOwnProperties() {
    if (typeof window !== 'undefined') {
      detectIt.passiveEvents = detectIt.state.detectPassiveEvents.hasSupport || false;

      detectIt.hasTouch = detectIt.state.detectTouchEvents.hasSupport || false;

      detectIt.deviceType = determineDeviceType(
        detectIt.hasTouch,
        detectIt.state.detectHover.anyHover,
        detectIt.state.detectPointer.anyFine,
        detectIt.state,
      );

      detectIt.hasMouse = detectIt.deviceType !== 'touchOnly';

      detectIt.primaryInput =
        (detectIt.deviceType === 'mouseOnly' && 'mouse') ||
        (detectIt.deviceType === 'touchOnly' && 'touch') ||
        // deviceType is hybrid:
        (detectIt.state.detectHover.hover && 'mouse') ||
        (detectIt.state.detectHover.none && 'touch') ||
        // if there's no support for hover media queries but detectIt determined it's
        // a hybrid  device, then assume it's a mouse first device
        'mouse';

      // issue with Windows Chrome on hybrid devices starting in version 59 where
      // media queries represent a touch only device, so if the browser is an
      // affected Windows Chrome version and hasTouch,
      // then assume it's a hybrid with primaryInput mouse
      // note that version 62 of Chrome fixes this issue
      // see https://github.com/rafrex/detect-it/issues/8
      const inVersionRange = version => version >= 59 && version < 62;
      const isAffectedWindowsChromeVersion =
        /windows/.test(window.navigator.userAgent.toLowerCase()) &&
        /chrome/.test(window.navigator.userAgent.toLowerCase()) &&
        inVersionRange(parseInt(/Chrome\/([0-9.]+)/.exec(navigator.userAgent)[1], 10));

      if (isAffectedWindowsChromeVersion && detectIt.hasTouch) {
        detectIt.deviceType = 'hybrid';
        detectIt.hasMouse = true;
        detectIt.primaryInput = 'mouse';
      }
    }
  },
};

detectIt.updateOnlyOwnProperties();
export default detectIt;
<commit_msg>Use pointer instead of hover to determine primaryInput<commit_after>import detectHover from 'detect-hover';
import detectPointer from 'detect-pointer';
import detectTouchEvents from 'detect-touch-events';
import detectPassiveEvents from 'detect-passive-events';

/*
 * detectIt object structure
 * const detectIt = {
 *   deviceType: 'mouseOnly' / 'touchOnly' / 'hybrid',
 *   passiveEvents: boolean,
 *   hasTouch: boolean,
 *   hasMouse: boolean,
 *   maxTouchPoints: number,
 *   primaryHover: 'hover' / 'none',
 *   primaryPointer: 'fine' / 'coarse' / 'none',
 *   state: {
 *     detectHover,
 *     detectPointer,
 *     detectTouchEvents,
 *     detectPassiveEvents,
 *   },
 *   update() {...},
 * }
 */

function determineDeviceType(hasTouch, anyHover, anyFine, state) {
  // A hybrid device is one that both hasTouch and any input device can hover
  // or has a fine pointer.
  if (hasTouch && (anyHover || anyFine)) return 'hybrid';

  // workaround for browsers that have the touch events api,
  // and have implemented Level 4 media queries but not the
  // hover and pointer media queries, so the tests are all false (notable Firefox)
  // if it hasTouch, no pointer and hover support, and on an android assume it's touchOnly
  // if it hasTouch, no pointer and hover support, and not on an android assume it's a hybrid
  if (hasTouch &&
  Object.keys(state.detectHover).filter(key => key !== 'update').every(key => state.detectHover[key] === false) &&
  Object.keys(state.detectPointer).filter(key => key !== 'update').every(key => state.detectPointer[key] === false)) {
    if (window.navigator && /android/.test(window.navigator.userAgent.toLowerCase())) {
      return 'touchOnly';
    }
    return 'hybrid';
  }

  // In almost all cases a device that doesn’t support touch will have a mouse,
  // but there may be rare exceptions. Note that it doesn’t work to do additional tests
  // based on hover and pointer media queries as older browsers don’t support these.
  // Essentially, 'mouseOnly' is the default.
  return hasTouch ? 'touchOnly' : 'mouseOnly';
}

const detectIt = {
  state: {
    detectHover,
    detectPointer,
    detectTouchEvents,
    detectPassiveEvents,
  },
  update() {
    detectIt.state.detectHover.update();
    detectIt.state.detectPointer.update();
    detectIt.state.detectTouchEvents.update();
    detectIt.state.detectPassiveEvents.update();
    detectIt.updateOnlyOwnProperties();
  },
  updateOnlyOwnProperties() {
    if (typeof window !== 'undefined') {
      detectIt.passiveEvents = detectIt.state.detectPassiveEvents.hasSupport || false;

      detectIt.hasTouch = detectIt.state.detectTouchEvents.hasSupport || false;

      detectIt.deviceType = determineDeviceType(
        detectIt.hasTouch,
        detectIt.state.detectHover.anyHover,
        detectIt.state.detectPointer.anyFine,
        detectIt.state,
      );

      detectIt.hasMouse = detectIt.deviceType !== 'touchOnly';

      detectIt.primaryInput =
        (detectIt.deviceType === 'mouseOnly' && 'mouse') ||
        (detectIt.deviceType === 'touchOnly' && 'touch') ||
        // deviceType is hybrid:
        (detectIt.state.detectPointer.fine && 'mouse') ||
        (detectIt.state.detectPointer.coarse && 'touch') ||
        // if there's no support for hover media queries but detectIt determined it's
        // a hybrid  device, then assume it's a mouse first device
        'mouse';

      // issue with Windows Chrome on hybrid devices starting in version 59 where
      // media queries represent a touch only device, so if the browser is an
      // affected Windows Chrome version and hasTouch,
      // then assume it's a hybrid with primaryInput mouse
      // note that version 62 of Chrome fixes this issue
      // see https://github.com/rafrex/detect-it/issues/8
      const inVersionRange = version => version >= 59 && version < 62;
      const isAffectedWindowsChromeVersion =
        /windows/.test(window.navigator.userAgent.toLowerCase()) &&
        /chrome/.test(window.navigator.userAgent.toLowerCase()) &&
        inVersionRange(parseInt(/Chrome\/([0-9.]+)/.exec(navigator.userAgent)[1], 10));

      if (isAffectedWindowsChromeVersion && detectIt.hasTouch) {
        detectIt.deviceType = 'hybrid';
        detectIt.hasMouse = true;
        detectIt.primaryInput = 'mouse';
      }
    }
  },
};

detectIt.updateOnlyOwnProperties();
export default detectIt;
<|endoftext|>


<commit_before>import {Subject} from 'rx';
import isolate from '@cycle/isolate';

let _id = 0;

function id() {
  return _id++;
};

function registerHandlers(item, handlers, action$) {
  for (let sink in item) {
    if (sink in handlers) {
      const handler = handlers[sink];

      item[sink].subscribe(event => action$.onNext(
        (state) => handler(state, {item, event})
      ))
    }
  }
}

function makeItem (component, sources, props) {
  const newId = id();

  const newItem = isolate(component, newId.toString())({...sources, ...props});

  newItem.id = newId;

  return newItem;
}

export default function Collection (component, sources, handlers = {}, items = [], action$ = new Subject) {
  return {
    add (props) {
      const newItem = makeItem(component, sources, props);

      registerHandlers(newItem, handlers, action$);

      return Collection(
        component,
        sources,
        handlers,
        [...items, newItem],
        action$
      )
    },

    remove (itemForRemoval) {
      return Collection(
        component,
        sources,
        handlers,
        items.filter(item => item.id !== itemForRemoval.id),
        action$
      )
    },

    asArray () {
      return items;
    },

    action$: action$.asObservable()
  }
}
<commit_msg>Refactor registerHandlers to return an observable of handlers<commit_after>import {Subject, Observable} from 'rx';
import isolate from '@cycle/isolate';

let _id = 0;

function id() {
  return _id++;
};

function handlerStreams (item, handlers) {
  const sinkStreams = Object.keys(item).map(sink => {
    if (handlers[sink] === undefined) {
      return null;
    }

    const handler = handlers[sink];
    const sink$ = item[sink];

    return sink$.map(event => (state) => handler(state, {item, event}));
  });

  return Observable.merge(...sinkStreams.filter(action => action !== null));
}

function makeItem (component, sources, props) {
  const newId = id();

  const newItem = isolate(component, newId.toString())({...sources, ...props});

  newItem.id = newId;

  return newItem;
}

export default function Collection (component, sources, handlers = {}, items = [], action$ = new Subject) {
  return {
    add (props) {
      const newItem = makeItem(component, sources, props);

      handlerStreams(newItem, handlers).subscribe(action$);

      return Collection(
        component,
        sources,
        handlers,
        [...items, newItem],
        action$
      )
    },

    remove (itemForRemoval) {
      return Collection(
        component,
        sources,
        handlers,
        items.filter(item => item.id !== itemForRemoval.id),
        action$
      )
    },

    asArray () {
      return items;
    },

    action$: action$.asObservable()
  }
}
<|endoftext|>


<commit_before>import Croppie from 'croppie';
import 'croppie/croppie.css';

const VueCroppie = {
  install(Vue, options) {
    const comp = Vue.extend({
      render(h){
        return h('div', {
          class: this.customClass,
          ref: 'croppieContainer',
          id: 'croppieContainer',
        })
      },
      props: {
        boundary: Object,
        customClass: String,
        enableExif: Boolean,
        enableOrientation: {
          type: Boolean,
          default: true
        },
        enableResize: {
          type: Boolean,
          default: true
        },
        enableZoom: {
          type: Boolean,
          default: true
        },
        enforceBoundary: {
          type: Boolean,
          default: true
        },
        mouseWheelZoom: {
          type: Boolean | String,
          default: true
        },
        showZoomer: {
          type: Boolean,
          default: true
        },
        viewport: {
          type: Object,
          default: function() {
            return {
              width: 200,
              height: 200,
              type: 'square'
            }
          }
        },
        minZoom: Number,
        maxZoom: Number
      },
      mounted() {
        this.initCroppie();
      },
      data() {
        return {
          croppie: null
        }
      },
      methods: {
        initCroppie() {
          let el = this.$refs.croppieContainer;

          let options = {
            enableExif: this.enableExif,
            enableOrientation: this.enableOrientation,
            enableZoom: this.enableZoom,
            enableResize: this.enableResize,
            enforceBoundary: this.enforceBoundary,
            mouseWheelZoom: this.mouseWheelZoom,
            viewport: this.viewport,
            showZoomer: this.showZoomer,
            minZoom: this.minZoom,
            maxZoom: this.maxZoom
          }

          if(this.boundary) {
            options.boundary = this.boundary;
          }

          el.addEventListener('update', (ev) => {
            this.$emit('update', ev.detail);
          });

          this.croppie = new Croppie(el, options);
        },
        bind(options) {
          return this.croppie.bind(options)
        },
        destroy() {
          this.croppie.destroy();
        },
        get(cb) {
          if(cb){
            cb(this.croppie.get())
          } else {
            return this.croppie.get()
          }
        },
        rotate(angle) {
          this.croppie.rotate(angle);
        },
        setZoom(value) {
          this.croppie.setZoom(value);
        },
        result(options, cb) {
          if(!options) options = {type: 'base64'}
            return this.croppie.result(options).then(output => {
              if(!cb) {
                this.$emit('result', output);
              } else {
                cb(output);
              }
              return output;
            });
        },
        refresh() {
          this.croppie.destroy();
          this.initCroppie();
        }
      }
    });
    Vue.component('vue-croppie', comp);
  }
};

export default VueCroppie;
<commit_msg>Multiple possible types according to docs<commit_after>import Croppie from 'croppie';
import 'croppie/croppie.css';

const VueCroppie = {
  install(Vue, options) {
    const comp = Vue.extend({
      render(h){
        return h('div', {
          class: this.customClass,
          ref: 'croppieContainer',
          id: 'croppieContainer',
        })
      },
      props: {
        boundary: Object,
        customClass: String,
        enableExif: Boolean,
        enableOrientation: {
          type: Boolean,
          default: true
        },
        enableResize: {
          type: Boolean,
          default: true
        },
        enableZoom: {
          type: Boolean,
          default: true
        },
        enforceBoundary: {
          type: Boolean,
          default: true
        },
        mouseWheelZoom: {
          type: [Boolean, String],
          default: true
        },
        showZoomer: {
          type: Boolean,
          default: true
        },
        viewport: {
          type: Object,
          default: function() {
            return {
              width: 200,
              height: 200,
              type: 'square'
            }
          }
        },
        minZoom: Number,
        maxZoom: Number
      },
      mounted() {
        this.initCroppie();
      },
      data() {
        return {
          croppie: null
        }
      },
      methods: {
        initCroppie() {
          let el = this.$refs.croppieContainer;

          let options = {
            enableExif: this.enableExif,
            enableOrientation: this.enableOrientation,
            enableZoom: this.enableZoom,
            enableResize: this.enableResize,
            enforceBoundary: this.enforceBoundary,
            mouseWheelZoom: this.mouseWheelZoom,
            viewport: this.viewport,
            showZoomer: this.showZoomer,
            minZoom: this.minZoom,
            maxZoom: this.maxZoom
          }

          if(this.boundary) {
            options.boundary = this.boundary;
          }

          el.addEventListener('update', (ev) => {
            this.$emit('update', ev.detail);
          });

          this.croppie = new Croppie(el, options);
        },
        bind(options) {
          return this.croppie.bind(options)
        },
        destroy() {
          this.croppie.destroy();
        },
        get(cb) {
          if(cb){
            cb(this.croppie.get())
          } else {
            return this.croppie.get()
          }
        },
        rotate(angle) {
          this.croppie.rotate(angle);
        },
        setZoom(value) {
          this.croppie.setZoom(value);
        },
        result(options, cb) {
          if(!options) options = {type: 'base64'}
            return this.croppie.result(options).then(output => {
              if(!cb) {
                this.$emit('result', output);
              } else {
                cb(output);
              }
              return output;
            });
        },
        refresh() {
          this.croppie.destroy();
          this.initCroppie();
        }
      }
    });
    Vue.component('vue-croppie', comp);
  }
};

export default VueCroppie;
<|endoftext|>


<commit_before>import "./stylesheets/app.css";
import 'react-notifications/lib/notifications.css';
import React from 'react';
import EventEmitter from 'event-emitter';
import ReactDOM from 'react-dom';
import injectTapEventPlugin from 'react-tap-event-plugin';
import Web3 from 'web3';
import TruffleContract from 'truffle-contract'
import artifacts from '../build/contracts/Conference.json'
import ConferenceDetail from './components/ConferenceDetail';
import FormInput from './components/FormInput';
import Notification from './components/Notification';
import Instruction from './components/Instruction';
import Participants from './components/Participants';
import NetworkLabel from './components/NetworkLabel';
import Data from './components/Data';

import Avatar from 'material-ui/Avatar';
import AppBar from 'material-ui/AppBar';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import FlatButton from 'material-ui/FlatButton';
import $ from 'jquery';

function setup(){
  return new Promise(function(resolve,reject){
    let provider;
    let read_only = false;
    let url = "http://localhost:8545";
    // mist loading proposal https://gist.github.com/frozeman/fbc7465d0b0e6c1c4c23
    if(typeof web3 !== 'undefined'){   // eg: If accessed via mist
      provider = web3.currentProvider; // Keep provider info given from mist `web3` object
      web3 = new Web3();                 // Re-instantiate `web3` using `Web3` from Dapp
      web3.setProvider(provider);
      web3.version.getNetwork(function(err, network_id){
        resolve({web3, provider, read_only, network_id})
      })
    }else{
      provider = new Web3.providers.HttpProvider(url);
      let web3 = new Web3();             // Define and instantiate `web3` if accessed from web browser
      $.get(url, function(res){
        console.log('Success', res)
        // the endpoint is active
      }).fail(function(error){
        console.log('Fail', error)
        if(error.readyState == 4 && (error.status == 400 || error.status == 200)){
          // the endpoint is active
          console.log('Success')
        }else{
          console.log('The endspoint is not active. Falling back to read_only mode')
          url = 'https://mainnet.infura.io'
          read_only = true
        }
      }).always(function(){
        console.log('url', url)
        provider = new Web3.providers.HttpProvider(url);
        let web3 = new Web3;             // Define and instantiate `web3` if accessed from web browser
        console.log('Web3 is set', web3, provider)
        web3.setProvider(provider);
        web3.version.getNetwork(function(err, network_id){
          resolve({web3, provider, read_only, network_id})
        })
      })
    }
  });
}

window.onload = function() {
  setup().then(({provider, web3, read_only, network_id}) => {
    var env;
    switch (network_id) {
      case '1':
        env = 'mainnet';
        break;
      case '3':
        env = 'ropsten';
        break;
      case '4':
        env = 'rinkeby';
        break;
      default:
        env = 'development';
    }
    var network_obj = require('../app_config.js')[env];
    var Conference  = TruffleContract(artifacts);
    let contract, contractAddress;
    Conference.setProvider(provider);
    Conference.setNetwork(network_id);
    try {
      if (network_obj.contract_addresses['Conference']) {
        contract = Conference.at(network_obj.contract_addresses['Conference']);
      }else{
        contract = Conference.at(Conference.address);
      }
    } catch (e) {
      console.log("ERROR")
      console.log(e)
    }
    if (contract){
      contractAddress = contract.address;
    }else{
      contractAddress = '0x000';
    }

    let metadata = Data.filter(function(d){
      return d.address == contractAddress;
    })[0];
    if (!metadata) {
      metadata = Data[0]
      metadata.address = contractAddress;
    }
    window.contract = contract
    window.web3 = web3
    const eventEmitter = EventEmitter()

    function getBalance(address){
      return new Promise(function(resolve,reject){
        web3.eth.getBalance(address, function(err, result){
          resolve(result)
        })
      });
    }
    // Functions to interact with contract
    function getDetail(){
      if (!contract) return false;

      var values;
      contract.then(function(instance){
        Promise.all(['name', 'deposit', 'payout', 'totalBalance', 'registered', 'attended', 'owner', 'ended', 'limitOfParticipants', 'payoutAmount', 'encryption', 'getAdmins'].map(attributeName => {
          return instance[attributeName].call();
        })).then(_values => {
          values = _values;
          return getBalance(instance.address)
        }).then(contractBalance => {
          var detail = {
            'name': values[0],
            'deposit': values[1],
            'payout': values[2],
            'totalBalance': values[3],
            'registered': values[4],
            'attended': values[5],
            'owner': values[6],
            'ended': values[7],
            'limitOfParticipants': values[8],
            'payoutAmount': values[9],
            'encryption': values[10],
            'admins': values[11],
            'contractBalance': web3.fromWei(contractBalance, "ether").toNumber(),
            'date': metadata.date,
            'map_url': metadata.map_url,
            'location_text': metadata.location_text,
            'description_text': metadata.description_text
          }
          if(detail.ended){
            detail.canRegister = false
            detail.canAttend = false
            detail.canPayback = false
            detail.canCancel = false
            detail.canWithdraw = true
          }else{
            if(detail.registered.toNumber() > 0 ){
              detail.canAttend = true
            }

            if(detail.registered.toNumber() > 0 && detail.attended.toNumber() > 0 && detail.payout.toNumber() > 0){
              detail.canPayback = true
            }
            detail.canRegister = true
            detail.canCancel = true
            detail.canWithdraw = false
          }
          detail.contractAddress = contract.address;
          window.detail = detail
          eventEmitter.emit('detail', detail);
        })
      })
    }

    function getParticipants(callback){
      if (!contract) return false;

      var instance;

      contract
        .then(function(_instance){
          instance = _instance;
          return instance.registered.call();
        })
        .then(value => {
          let participantsArray = []
          for (var i = 1; i <= value.toNumber(); i++) {
            participantsArray.push(i);
          }
          Promise.all(participantsArray.map(index => {
            return instance.participantsIndex.call(index).then(address => {
              return instance.participants.call(address);
            })
          })).then(function(participants){
            return participants.map(participant => {
              var object =  {
                name: participant[0],
                address: participant[1],
                attended: participant[2],
                paid: participant[3]
              }
              return object
            })
          }).then(participants => {
            if(participants) {
              eventEmitter.emit('participants_updated', participants);
              window.participants = participants.length;
              callback(participants);
            }
          })
        })
    }
    var gas = 1000000;
    var gasPrice = web3.toWei(2, 'gwei');
    window.eventEmitter = eventEmitter;
    function action(name, address, args) {
      var options = {from:address, gas:gas, gasPrice:gasPrice }
      eventEmitter.emit('notification', {status:'info', message:'Requested'});
      if (!args) {
        args = [];
      }
      if (name == "register" || name == "registerWithEncryption") {
        options.value = Math.pow(10,18) / 50; // 0.02 ETH deposit
      }
      args.push(options);
      contract.then(function(instance){
        return instance[name].apply(this, args);
      })
      .then(function(trx) {
        eventEmitter.emit('notification', {status:'success', message:'Successfully Updated'});
        eventEmitter.emit('change');
        getDetail();
      }).catch(function(e) {
        eventEmitter.emit('notification', {status:'error', message:'Error has occored'});
      });
    }

    function watchEvent(){
      var event = contract.allEvents({fromBlock: 0, toBlock: 'latest'}).watch(function(error, result){
        if (error) {
          console.log("Error: " + error);
        } else {
          console.log('watchEvent result', result);
        }
      });
    }

    function getAccounts(){
      if(read_only){
        eventEmitter.emit('accounts_received', []);
        eventEmitter.emit('instruction');
        return false;
      }
      console.log('this is not read only!')
      web3.eth.getAccounts(function(err, accs) {
        if (err != null) {
          eventEmitter.emit('instruction');
          return;
        }
        if (accs.length == 0) {
          var message = "Couldn't get any accounts! Make sure your Ethereum client is configured correctly.";
          eventEmitter.emit('notification', {status:'error', message:message});
          return;
        }
        window.account = accs[0];
        eventEmitter.emit('accounts_received', accs)
      })
    }
    let networkLabel = <NetworkLabel eventEmitter={eventEmitter} read_only={read_only} />;

    const App = (props) => (

        <MuiThemeProvider muiTheme={getMuiTheme()}>

            <AppBar titleStyle={{textAlign:'center', fontSize:'xx-large', fontFamily:'Lobster'}} style={{backgroundColor:"#607D8B"}}
              title={
                Block Party - NO BLOCK NO PARTY -
              }
              iconElementLeft={<Avatar src={require('./images/nightclub-white.png')} size={50} backgroundColor="rgb(96, 125, 139)" />}
              iconElementRight={

                  {networkLabel}
                  <FlatButton style={{color:'white'}} label="About" onClick={ () => {eventEmitter.emit('instruction')}} />

              }
            />

            <Instruction eventEmitter={eventEmitter} />
            <Notification eventEmitter={eventEmitter} />

              <ConferenceDetail eventEmitter={eventEmitter} getDetail={getDetail} web3={web3} contract={contract} web3={web3} contractAddress={contractAddress} />
              <Participants eventEmitter={eventEmitter} getDetail={getDetail} getParticipants={getParticipants} getAccounts={getAccounts} action={action} web3={web3}  />

            <FormInput read_only={read_only} eventEmitter={eventEmitter} getAccounts={getAccounts} getDetail={getDetail} action={action} />

        </MuiThemeProvider>

    );

    injectTapEventPlugin();
    ReactDOM.render(
      <App
        getAccounts={getAccounts}
        getDetail={getDetail}
        eventEmitter={eventEmitter}
        action={action}
        getParticipants={getParticipants}
        web3={web3}
        contract={contract}
      />,
      document.getElementById('app')
    );
    window.getAccounts = window.getAccounts;

    // Looks like calling the function immediately returns
    // bignumber.js:1177 Uncaught BigNumber Error: new BigNumber() not a base 16 number:
    setTimeout(getAccounts, 100)
    setTimeout(getDetail, 100)
    eventEmitter.on('logger', (obj)=>{
      console.log('logger', obj)
    })
    let starTime = new Date()
    let timer = setInterval(()=>{
      let duration = new Date() - starTime;
      if((window.detail && window.participants) || duration > 200000 ) {
        let obj = {
          action:'load',
          user:window.account,
          participants: window.participants,
          contract:window.detail && window.detail.contractAddress,
          agent: navigator.userAgent,
          duration: duration,
          provider:web3.currentProvider.constructor.name
        }
        eventEmitter.emit('logger',obj);
        clearInterval(timer);
      }else{
        console.log('not ready', window.detail, window.account, window.participants)
      }
    }, 1000)
    eventEmitter.emit('network', network_obj);
  })
}
<commit_msg>Point readonly server to rinkeby<commit_after>import "./stylesheets/app.css";
import 'react-notifications/lib/notifications.css';
import React from 'react';
import EventEmitter from 'event-emitter';
import ReactDOM from 'react-dom';
import injectTapEventPlugin from 'react-tap-event-plugin';
import Web3 from 'web3';
import TruffleContract from 'truffle-contract'
import artifacts from '../build/contracts/Conference.json'
import ConferenceDetail from './components/ConferenceDetail';
import FormInput from './components/FormInput';
import Notification from './components/Notification';
import Instruction from './components/Instruction';
import Participants from './components/Participants';
import NetworkLabel from './components/NetworkLabel';
import Data from './components/Data';

import Avatar from 'material-ui/Avatar';
import AppBar from 'material-ui/AppBar';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import FlatButton from 'material-ui/FlatButton';
import $ from 'jquery';

function setup(){
  return new Promise(function(resolve,reject){
    let provider;
    let read_only = false;
    let url = "http://localhost:8545";
    // mist loading proposal https://gist.github.com/frozeman/fbc7465d0b0e6c1c4c23
    if(typeof web3 !== 'undefined'){   // eg: If accessed via mist
      provider = web3.currentProvider; // Keep provider info given from mist `web3` object
      web3 = new Web3();                 // Re-instantiate `web3` using `Web3` from Dapp
      web3.setProvider(provider);
      web3.version.getNetwork(function(err, network_id){
        resolve({web3, provider, read_only, network_id})
      })
    }else{
      provider = new Web3.providers.HttpProvider(url);
      let web3 = new Web3();             // Define and instantiate `web3` if accessed from web browser
      $.get(url, function(res){
        console.log('Success', res)
        // the endpoint is active
      }).fail(function(error){
        console.log('Fail', error)
        if(error.readyState == 4 && (error.status == 400 || error.status == 200)){
          // the endpoint is active
          console.log('Success')
        }else{
          console.log('The endspoint is not active. Falling back to read_only mode')
          url = 'https://rinkeby.infura.io'
          read_only = true
        }
      }).always(function(){
        console.log('url', url)
        provider = new Web3.providers.HttpProvider(url);
        let web3 = new Web3;             // Define and instantiate `web3` if accessed from web browser
        console.log('Web3 is set', web3, provider)
        web3.setProvider(provider);
        web3.version.getNetwork(function(err, network_id){
          resolve({web3, provider, read_only, network_id})
        })
      })
    }
  });
}

window.onload = function() {
  setup().then(({provider, web3, read_only, network_id}) => {
    var env;
    switch (network_id) {
      case '1':
        env = 'mainnet';
        break;
      case '3':
        env = 'ropsten';
        break;
      case '4':
        env = 'rinkeby';
        break;
      default:
        env = 'development';
    }
    var network_obj = require('../app_config.js')[env];
    var Conference  = TruffleContract(artifacts);
    let contract, contractAddress;
    Conference.setProvider(provider);
    Conference.setNetwork(network_id);
    try {
      if (network_obj.contract_addresses['Conference']) {
        contract = Conference.at(network_obj.contract_addresses['Conference']);
      }else{
        contract = Conference.at(Conference.address);
      }
    } catch (e) {
      console.log("ERROR")
      console.log(e)
    }
    if (contract){
      contractAddress = contract.address;
    }else{
      contractAddress = '0x000';
    }

    let metadata = Data.filter(function(d){
      return d.address == contractAddress;
    })[0];
    if (!metadata) {
      metadata = Data[0]
      metadata.address = contractAddress;
    }
    window.contract = contract
    window.web3 = web3
    const eventEmitter = EventEmitter()

    function getBalance(address){
      return new Promise(function(resolve,reject){
        web3.eth.getBalance(address, function(err, result){
          resolve(result)
        })
      });
    }
    // Functions to interact with contract
    function getDetail(){
      if (!contract) return false;

      var values;
      contract.then(function(instance){
        Promise.all(['name', 'deposit', 'payout', 'totalBalance', 'registered', 'attended', 'owner', 'ended', 'limitOfParticipants', 'payoutAmount', 'encryption', 'getAdmins'].map(attributeName => {
          return instance[attributeName].call();
        })).then(_values => {
          values = _values;
          return getBalance(instance.address)
        }).then(contractBalance => {
          var detail = {
            'name': values[0],
            'deposit': values[1],
            'payout': values[2],
            'totalBalance': values[3],
            'registered': values[4],
            'attended': values[5],
            'owner': values[6],
            'ended': values[7],
            'limitOfParticipants': values[8],
            'payoutAmount': values[9],
            'encryption': values[10],
            'admins': values[11],
            'contractBalance': web3.fromWei(contractBalance, "ether").toNumber(),
            'date': metadata.date,
            'map_url': metadata.map_url,
            'location_text': metadata.location_text,
            'description_text': metadata.description_text
          }
          if(detail.ended){
            detail.canRegister = false
            detail.canAttend = false
            detail.canPayback = false
            detail.canCancel = false
            detail.canWithdraw = true
          }else{
            if(detail.registered.toNumber() > 0 ){
              detail.canAttend = true
            }

            if(detail.registered.toNumber() > 0 && detail.attended.toNumber() > 0 && detail.payout.toNumber() > 0){
              detail.canPayback = true
            }
            detail.canRegister = true
            detail.canCancel = true
            detail.canWithdraw = false
          }
          detail.contractAddress = contract.address;
          window.detail = detail
          eventEmitter.emit('detail', detail);
        })
      })
    }

    function getParticipants(callback){
      if (!contract) return false;

      var instance;

      contract
        .then(function(_instance){
          instance = _instance;
          return instance.registered.call();
        })
        .then(value => {
          let participantsArray = []
          for (var i = 1; i <= value.toNumber(); i++) {
            participantsArray.push(i);
          }
          Promise.all(participantsArray.map(index => {
            return instance.participantsIndex.call(index).then(address => {
              return instance.participants.call(address);
            })
          })).then(function(participants){
            return participants.map(participant => {
              var object =  {
                name: participant[0],
                address: participant[1],
                attended: participant[2],
                paid: participant[3]
              }
              return object
            })
          }).then(participants => {
            if(participants) {
              eventEmitter.emit('participants_updated', participants);
              window.participants = participants.length;
              callback(participants);
            }
          })
        })
    }
    var gas = 1000000;
    var gasPrice = web3.toWei(2, 'gwei');
    window.eventEmitter = eventEmitter;
    function action(name, address, args) {
      var options = {from:address, gas:gas, gasPrice:gasPrice }
      eventEmitter.emit('notification', {status:'info', message:'Requested'});
      if (!args) {
        args = [];
      }
      if (name == "register" || name == "registerWithEncryption") {
        options.value = Math.pow(10,18) / 50; // 0.02 ETH deposit
      }
      args.push(options);
      contract.then(function(instance){
        return instance[name].apply(this, args);
      })
      .then(function(trx) {
        eventEmitter.emit('notification', {status:'success', message:'Successfully Updated'});
        eventEmitter.emit('change');
        getDetail();
      }).catch(function(e) {
        eventEmitter.emit('notification', {status:'error', message:'Error has occored'});
      });
    }

    function watchEvent(){
      var event = contract.allEvents({fromBlock: 0, toBlock: 'latest'}).watch(function(error, result){
        if (error) {
          console.log("Error: " + error);
        } else {
          console.log('watchEvent result', result);
        }
      });
    }

    function getAccounts(){
      if(read_only){
        eventEmitter.emit('accounts_received', []);
        eventEmitter.emit('instruction');
        return false;
      }
      console.log('this is not read only!')
      web3.eth.getAccounts(function(err, accs) {
        if (err != null) {
          eventEmitter.emit('instruction');
          return;
        }
        if (accs.length == 0) {
          var message = "Couldn't get any accounts! Make sure your Ethereum client is configured correctly.";
          eventEmitter.emit('notification', {status:'error', message:message});
          return;
        }
        window.account = accs[0];
        eventEmitter.emit('accounts_received', accs)
      })
    }
    let networkLabel = <NetworkLabel eventEmitter={eventEmitter} read_only={read_only} />;

    const App = (props) => (

        <MuiThemeProvider muiTheme={getMuiTheme()}>

            <AppBar titleStyle={{textAlign:'center', fontSize:'xx-large', fontFamily:'Lobster'}} style={{backgroundColor:"#607D8B"}}
              title={
                Block Party - NO BLOCK NO PARTY -
              }
              iconElementLeft={<Avatar src={require('./images/nightclub-white.png')} size={50} backgroundColor="rgb(96, 125, 139)" />}
              iconElementRight={

                  {networkLabel}
                  <FlatButton style={{color:'white'}} label="About" onClick={ () => {eventEmitter.emit('instruction')}} />

              }
            />

            <Instruction eventEmitter={eventEmitter} />
            <Notification eventEmitter={eventEmitter} />

              <ConferenceDetail eventEmitter={eventEmitter} getDetail={getDetail} web3={web3} contract={contract} web3={web3} contractAddress={contractAddress} />
              <Participants eventEmitter={eventEmitter} getDetail={getDetail} getParticipants={getParticipants} getAccounts={getAccounts} action={action} web3={web3}  />

            <FormInput read_only={read_only} eventEmitter={eventEmitter} getAccounts={getAccounts} getDetail={getDetail} action={action} />

        </MuiThemeProvider>

    );

    injectTapEventPlugin();
    ReactDOM.render(
      <App
        getAccounts={getAccounts}
        getDetail={getDetail}
        eventEmitter={eventEmitter}
        action={action}
        getParticipants={getParticipants}
        web3={web3}
        contract={contract}
      />,
      document.getElementById('app')
    );
    window.getAccounts = window.getAccounts;

    // Looks like calling the function immediately returns
    // bignumber.js:1177 Uncaught BigNumber Error: new BigNumber() not a base 16 number:
    setTimeout(getAccounts, 100)
    setTimeout(getDetail, 100)
    eventEmitter.on('logger', (obj)=>{
      console.log('logger', obj)
    })
    let starTime = new Date()
    let timer = setInterval(()=>{
      let duration = new Date() - starTime;
      if((window.detail && window.participants) || duration > 200000 ) {
        let obj = {
          action:'load',
          user:window.account,
          participants: window.participants,
          contract:window.detail && window.detail.contractAddress,
          agent: navigator.userAgent,
          duration: duration,
          provider:web3.currentProvider.constructor.name
        }
        eventEmitter.emit('logger',obj);
        clearInterval(timer);
      }else{
        console.log('not ready', window.detail, window.account, window.participants)
      }
    }, 1000)
    eventEmitter.emit('network', network_obj);
  })
}
<|endoftext|>


<commit_before>const express = require('express');
var session = require('express-session');
const path = require('path');
const https = require('https');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
var passport = require('passport');
var fs = require('fs');
//var sleep = require('sleep');
var CronJob = require('cron').CronJob;
var {google} = require('googleapis');
var config = require('./utilities/config');
//var utils = require('./utilities/utils');

var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
var User = require('./models/user');

const BigQuery = require('@google-cloud/bigquery');
const bigquery = new BigQuery();

// Get our API routes
const api = require('./routes/api');

const GOOGLE_CLIENT_ID = config.google_client_id;
const GOOGLE_CLIENT_SECRET = config.google_client_secret;

const app = express();

app.use(express.static('front-end/dist/front-end'));

app.use(passport.initialize());
app.use(passport.session());

mongoose.connect(config.mongo_connection_string);

passport.serializeUser(function(user, done) {
    var userRoleId = { 'id': user.id, 'role': user.role };
    done(null, userRoleId);
});

// used to deserialize the user
passport.deserializeUser(function(userRoleId, done) {
    User.findById(userRoleId.id, function(err, user) {
        done(err, user);
    });
});

// Use the GoogleStrategy within Passport.
//   Strategies in Passport require a `verify` function, which accept
//   credentials (in this case, an accessToken, refreshToken, and Google
//   profile), and invoke a callback with a user object.
passport.use(new GoogleStrategy({
    clientID: GOOGLE_CLIENT_ID,
    clientSecret: GOOGLE_CLIENT_SECRET,
    callbackURL: "/auth/google/callback"
  },
  function(accessToken, refreshToken, profile, done) {

       User.findOne({ googleID: profile.emails[0].value.toLowerCase() }, function (err, user) {
         if (err) {
           return done(err);
         }
         if (user) {
            // if a user is found, log them in
            config.access_token = accessToken;
            return done(null, user);
         }
         else {
           return done("User doesn't have access to the application.");
         }
       });
  }
));

// Parsers for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(session({
  secret: config.session_secret,
  resave: false,
  saveUninitialized: true,
  cookie: { secure: true, maxAge: 3600000 }
}))

// Set our api routes
app.use('/api', api);

app.get('/auth/google', passport.authenticate('google', { scope : ['profile', 'email', 'https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/bigquery.insertdata'] }));

app.get('/auth/google/callback',
  passport.authenticate('google', {
        successRedirect : '/',
        failureRedirect : '/'
  })
);

/**
 * Get port from environment and store in Express.
 */
const port = process.env.PORT || '3000';
app.set('port', port);

/**
 * Create HTTP server.
 */

 var options = {
   key  : fs.readFileSync(path.join(__dirname, 'encryption/' + config.https_key_filename)),
   cert : fs.readFileSync(path.join(__dirname, 'encryption/' + config.https_cert_filename)),
   passphrase: config.https_passphrase
};

const server = https.createServer(options, app);

server.listen(port, () => console.log(`API running on localhost:${port}`));

app.use('*', (req, res, next) => {
  res.sendFile(path.join(__dirname, '../front-end/dist/front-end/index.html'));
});
<commit_msg>Lowering BQ scope level<commit_after>const express = require('express');
var session = require('express-session');
const path = require('path');
const https = require('https');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
var passport = require('passport');
var fs = require('fs');
//var sleep = require('sleep');
var CronJob = require('cron').CronJob;
var {google} = require('googleapis');
var config = require('./utilities/config');
//var utils = require('./utilities/utils');

var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
var User = require('./models/user');

const BigQuery = require('@google-cloud/bigquery');
const bigquery = new BigQuery();

// Get our API routes
const api = require('./routes/api');

const GOOGLE_CLIENT_ID = config.google_client_id;
const GOOGLE_CLIENT_SECRET = config.google_client_secret;

const app = express();

app.use(express.static('front-end/dist/front-end'));

app.use(passport.initialize());
app.use(passport.session());

mongoose.connect(config.mongo_connection_string);

passport.serializeUser(function(user, done) {
    var userRoleId = { 'id': user.id, 'role': user.role };
    done(null, userRoleId);
});

// used to deserialize the user
passport.deserializeUser(function(userRoleId, done) {
    User.findById(userRoleId.id, function(err, user) {
        done(err, user);
    });
});

// Use the GoogleStrategy within Passport.
//   Strategies in Passport require a `verify` function, which accept
//   credentials (in this case, an accessToken, refreshToken, and Google
//   profile), and invoke a callback with a user object.
passport.use(new GoogleStrategy({
    clientID: GOOGLE_CLIENT_ID,
    clientSecret: GOOGLE_CLIENT_SECRET,
    callbackURL: "/auth/google/callback"
  },
  function(accessToken, refreshToken, profile, done) {

       User.findOne({ googleID: profile.emails[0].value.toLowerCase() }, function (err, user) {
         if (err) {
           return done(err);
         }
         if (user) {
            // if a user is found, log them in
            config.access_token = accessToken;
            return done(null, user);
         }
         else {
           return done("User doesn't have access to the application.");
         }
       });
  }
));

// Parsers for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(session({
  secret: config.session_secret,
  resave: false,
  saveUninitialized: true,
  cookie: { secure: true, maxAge: 3600000 }
}))

// Set our api routes
app.use('/api', api);

app.get('/auth/google', passport.authenticate('google', { scope : ['profile', 'email', 'https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/bigquery'] }));

app.get('/auth/google/callback',
  passport.authenticate('google', {
        successRedirect : '/',
        failureRedirect : '/'
  })
);

/**
 * Get port from environment and store in Express.
 */
const port = process.env.PORT || '3000';
app.set('port', port);

/**
 * Create HTTP server.
 */

 var options = {
   key  : fs.readFileSync(path.join(__dirname, 'encryption/' + config.https_key_filename)),
   cert : fs.readFileSync(path.join(__dirname, 'encryption/' + config.https_cert_filename)),
   passphrase: config.https_passphrase
};

const server = https.createServer(options, app);

server.listen(port, () => console.log(`API running on localhost:${port}`));

app.use('*', (req, res, next) => {
  res.sendFile(path.join(__dirname, '../front-end/dist/front-end/index.html'));
});
<|endoftext|>


<commit_before>'use strict';

console.log('Hello');
<commit_msg>Update index.js<commit_after>var Lexec = require('LISP.js').exec;
var Lparse = require('LISP.js').parse;

/*
calculate parsed node value
*/
function node_val(node)
{
  if(node instanceof Array)
	{
		switch(node[0])
		{
			case 'lambda':
				return 1 + node_val(node[2]);
			case 'not':
			case 'shl1':
			case 'shr1':
			case 'shr4':
			case 'shr16':
				return 1 + node_val(node[1]);
			case 'and':
			case 'or':
			case 'xor':
			case 'plus':
				return 1 + node_val(node[1]) + node_val(node[2]);
			case 'if0':
				return 1 + node_val(node[1]) + node_val(node[2]) + node_val(node[3]);
			case 'fold':
				return 2 + node_val(node[1]) + node_val(node[2]) + node_val(node[3][2]);
		}
	}
	return 1;
}

var expr = "(lambda (x_78631) (fold (shr1 (xor (shl1 (or (or (if0 (and x_78631 (shl1 (shl1 (and (shr16 (and (shr4 x_78631) x_78631)) x_78631)))) 0 x_78631) x_78631) 0)) 0)) 1 (lambda (x_78632 x_78633) (xor (shr4 x_78632) x_78633))))";
console.log(node_val(Lparse(expr)) == 30);
<|endoftext|>


<commit_before>const watch = require(`${__dirname}/watch.js`);
const datastore = require(`${__dirname}/datastore`);
const express = require('express');
const app = express();

app.use('/', express.static(`${__dirname}/../public`));

app.get('/api/full', function (req, res) {
    res.json(datastore.full);
});
app.get('/api/delta', function (req, res) {
    res.json(datastore.delta);
});
app.get('/api/merc/:id', function (req, res) {
    if (req.params.id && datastore.full.Merchants.list[req.params.id]) {
        res.json(datastore.full.Merchants.list[req.params.id]);
    } else {
        res.status(404).json({"error": "Not found."});
    }
});
app.listen(3088, 'localhost', function () {
    console.log('Server started on port 3088');
});<commit_msg>Security and perf improvement<commit_after>const watch = require(`${__dirname}/watch.js`);
const datastore = require(`${__dirname}/datastore`);
const express = require('express');
const app = express();

app.disable('x-powered-by');
app.set('etag', false);

app.use('/', express.static(`${__dirname}/../public`));

app.get('/api/full', function (req, res) {
    res.json(datastore.full);
});
app.get('/api/delta', function (req, res) {
    res.json(datastore.delta);
});
app.get('/api/merc/:id', function (req, res) {
    if (req.params.id && datastore.full.Merchants.list[req.params.id]) {
        res.json(datastore.full.Merchants.list[req.params.id]);
    } else {
        res.status(404).json({"error": "Not found."});
    }
});
app.listen(3088, 'localhost', function () {
    console.log('Server started on port 3088');
});<|endoftext|>


<commit_before>import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { Router, Route, Redirect } from 'react-router';
import { routerActions } from 'react-router-redux';
import { connectedReduxRedirect } from 'redux-auth-wrapper/history3/redirect';

import App from './app/App';
import Layout from './app/global/Layout'
import LoginController from './app/views/login/LoginController';
import CollectionsController from './app/views/collections/CollectionsController';
import TeamsController from './app/views/teams/TeamsController';
// import DatasetController from './app/views/datasets/DatasetsController';
// import DatasetOverviewController from './app/views/datasets/dataset-overview/DatasetOverviewController';
import Logs from './app/views/logs/Logs';

import auth from './app/utilities/auth'

import './scss/main.scss';

import { store, history } from './app/config/store';

import SelectableTest from './SelectableTest';
import PreviewController from './app/views/preview/PreviewController';

const rootPath = store.getState().state.rootPath;

const userIsAuthenticated = connectedReduxRedirect({
    authenticatedSelector: state => {
        return auth.isAuthenticated(state.state.user);
    },
    redirectAction: routerActions.replace,
    wrapperDisplayName: 'UserIsAuthenticated',
    redirectPath: `${rootPath}/login`
});

const userisAdminOrEditor = connectedReduxRedirect({
    authenticatedSelector: state => {
        return auth.isAdminOrEditor(state.state.user)
    },
    redirectAction: routerActions.replace,
    wrapperDisplayName: 'userisAdminOrEditor',
    redirectPath: `${rootPath}/collections`,
    allowRedirectBack: false
})

class UnknownRoute extends Component {
    render() {
        return (

Sorry, this page couldn't be found

        )
    }
}

class Index extends Component {
    render() {
        return (
            <Provider store={ store }>
                <Router history={ history }>
                    <Route component={ App }>
                        <Route component={ Layout }>
                            <Redirect from={`${rootPath}`} to={`${rootPath}/collections`} />
                            <Route path={`${rootPath}/collections`} component={ userIsAuthenticated(CollectionsController) }>
                                <Route path=':collectionID' component={ userIsAuthenticated(CollectionsController) }>
                                    <Route path='edit' component={ userIsAuthenticated(CollectionsController) }/>
                                    <Route path='restore-content' component={ userIsAuthenticated(CollectionsController) }/>
                                </Route>
                            </Route>
                            <Route path={`${rootPath}/collections/:collectionID/preview`} component={ userIsAuthenticated(PreviewController) }/>
                            <Route path={`${rootPath}/teams`} component={ userIsAuthenticated(userisAdminOrEditor(TeamsController)) }>
                                <Route path={`:team`} component={ userIsAuthenticated(TeamsController) }>
                                    <Route path={`edit`} component={ userIsAuthenticated(TeamsController) }/>
                                    <Route path={`delete`} component={ userIsAuthenticated(TeamsController) }/>
                                </Route>
                            </Route>
                            <Route path={`${rootPath}/selectable-list`} component={ SelectableTest } />
                            <Route path={`${rootPath}/logs`} component={ Logs } />
                            <Route path={`${rootPath}/login`} component={ LoginController } />
                            <Route path={`*`} component={ UnknownRoute } />
                        </Route>
                    </Route>
                </Router>
            </Provider>
        )
    }
}

ReactDOM.render(<Index/>, document.getElementById('app'));

<commit_msg>Add basic routing and component for users<commit_after>import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { Router, Route, Redirect } from 'react-router';
import { routerActions } from 'react-router-redux';
import { connectedReduxRedirect } from 'redux-auth-wrapper/history3/redirect';

import App from './app/App';
import Layout from './app/global/Layout'
import LoginController from './app/views/login/LoginController';
import CollectionsController from './app/views/collections/CollectionsController';
import TeamsController from './app/views/teams/TeamsController';
// import DatasetController from './app/views/datasets/DatasetsController';
// import DatasetOverviewController from './app/views/datasets/dataset-overview/DatasetOverviewController';
import Logs from './app/views/logs/Logs';

import auth from './app/utilities/auth'

import './scss/main.scss';

import { store, history } from './app/config/store';

import SelectableTest from './SelectableTest';
import PreviewController from './app/views/preview/PreviewController';

const rootPath = store.getState().state.rootPath;

const userIsAuthenticated = connectedReduxRedirect({
    authenticatedSelector: state => {
        return auth.isAuthenticated(state.state.user);
    },
    redirectAction: routerActions.replace,
    wrapperDisplayName: 'UserIsAuthenticated',
    redirectPath: `${rootPath}/login`
});

const userisAdminOrEditor = connectedReduxRedirect({
    authenticatedSelector: state => {
        return auth.isAdminOrEditor(state.state.user)
    },
    redirectAction: routerActions.replace,
    wrapperDisplayName: 'userisAdminOrEditor',
    redirectPath: `${rootPath}/collections`,
    allowRedirectBack: false
})

class UnknownRoute extends Component {
    render() {
        return (

Sorry, this page couldn't be found

        )
    }
}

class Users extends Component {
    render() {
        return (

Users

        )
    }
}

class Index extends Component {
    render() {
        return (
            <Provider store={ store }>
                <Router history={ history }>
                    <Route component={ App }>
                        <Route component={ Layout }>
                            <Redirect from={`${rootPath}`} to={`${rootPath}/collections`} />
                            <Route path={`${rootPath}/collections`} component={ userIsAuthenticated(CollectionsController) }>
                                <Route path=':collectionID' component={ userIsAuthenticated(CollectionsController) }>
                                    <Route path='edit' component={ userIsAuthenticated(CollectionsController) }/>
                                    <Route path='restore-content' component={ userIsAuthenticated(CollectionsController) }/>
                                </Route>
                            </Route>
                            <Route path={`${rootPath}/collections/:collectionID/preview`} component={ userIsAuthenticated(PreviewController) }/>
                            <Route path={`${rootPath}/teams`} component={ userIsAuthenticated(userisAdminOrEditor(TeamsController)) }>
                                <Route path={`:team`} component={ userIsAuthenticated(TeamsController) }>
                                    <Route path={`edit`} component={ userIsAuthenticated(TeamsController) }/>
                                    <Route path={`delete`} component={ userIsAuthenticated(TeamsController) }/>
                                </Route>
                            </Route>
                            <Route path={`${rootPath}/users`} component={ userIsAuthenticated(userisAdminOrEditor(Users)) }/>
                            <Route path={`${rootPath}/selectable-list`} component={ SelectableTest } />
                            <Route path={`${rootPath}/logs`} component={ Logs } />
                            <Route path={`${rootPath}/login`} component={ LoginController } />
                            <Route path={`*`} component={ UnknownRoute } />
                        </Route>
                    </Route>
                </Router>
            </Provider>
        )
    }
}

ReactDOM.render(<Index/>, document.getElementById('app'));

<|endoftext|>


<commit_before>const ImageFactory = require('sepal/ee/imageFactory')
const {switchMap} = require('rx/operators')
const {exportImageToAsset$} = require('../jobs/export/toAsset')
const _ = require('lodash')
const log = require('sepal/log').getLogger('ee')

module.exports = {
    submit$: (id, {image: {recipe, bands, scale, pyramidingPolicy, properties}}) => {
        const description = recipe.title || recipe.placeholder
        return export$({description, recipe, bands, scale, pyramidingPolicy, properties})
    }
}

const export$ = ({description, recipe, bands, scale, pyramidingPolicy, properties}) =>
    ImageFactory(recipe, bands).getImage$().pipe(
        switchMap(image => {
            const formattedProperties = formatProperties({...properties, scale})
            const imageWithProperties = image.set(formattedProperties)
                return exportImageToAsset$({
                    image: imageWithProperties,
                    description,
                    scale,
                    crs: 'EPSG:4326',
                    maxPixels: 1e13,
                    pyramidingPolicy
                })
            }
        )
    )

const formatProperties = properties => {
    const formatted = {}
    Object.keys(properties).forEach(key => {
        const value = properties[key]
        formatted[key] = _.isString(value) || _.isNumber(value) ? value : JSON.stringify(value)
    })
    return formatted
}<commit_msg>Cleanup.<commit_after>const ImageFactory = require('sepal/ee/imageFactory')
const {switchMap} = require('rx/operators')
const {exportImageToAsset$} = require('../jobs/export/toAsset')
const _ = require('lodash')

module.exports = {
    submit$: (id, {image: {recipe, bands, scale, pyramidingPolicy, properties}}) => {
        const description = recipe.title || recipe.placeholder
        return export$({description, recipe, bands, scale, pyramidingPolicy, properties})
    }
}

const export$ = ({description, recipe, bands, scale, pyramidingPolicy, properties}) =>
    ImageFactory(recipe, bands).getImage$().pipe(
        switchMap(image => {
            const formattedProperties = formatProperties({...properties, scale})
            const imageWithProperties = image.set(formattedProperties)
                return exportImageToAsset$({
                    image: imageWithProperties,
                    description,
                    scale,
                    crs: 'EPSG:4326',
                    maxPixels: 1e13,
                    pyramidingPolicy
                })
            }
        )
    )

const formatProperties = properties => {
    const formatted = {}
    Object.keys(properties).forEach(key => {
        const value = properties[key]
        formatted[key] = _.isString(value) || _.isNumber(value) ? value : JSON.stringify(value)
    })
    return formatted
}<|endoftext|>